dbgate-plugin-mongo 4.7.4-alpha.8 → 4.7.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/backend.js +2 -2
- package/package.json +3 -3
package/dist/backend.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
module.exports=function(e){var t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)n.d(r,o,function(t){return e[t]}.bind(null,o));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=228)}([function(e,t,n){"use strict";const r=n(3).MongoError,o=n(29);var i=t.formatSortValue=function(e){switch((""+e).toLowerCase()){case"ascending":case"asc":case"1":return 1;case"descending":case"desc":case"-1":return-1;default:throw new Error("Illegal sort clause, must be of the form [['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]")}},s=t.formattedOrderClause=function(e){var t={};if(null==e)return null;if(Array.isArray(e)){if(0===e.length)return null;for(var n=0;n<e.length;n++)e[n].constructor===String?t[e[n]]=1:t[e[n][0]]=i(e[n][1])}else if(null!=e&&"object"==typeof e)t=e;else{if("string"!=typeof e)throw new Error("Illegal sort clause, must be of the form [['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]");t[e]=1}return t},a=t.isObject=function(e){return"[object Object]"===Object.prototype.toString.call(e)};const c=["w","j","wtimeout","fsync","writeConcern"];const u=+process.version.split(".")[0].substring(1),l=process.emitWarning?e=>u<=6?process.emitWarning(e,"DeprecationWarning",m):process.emitWarning(e,{type:"DeprecationWarning",code:m}):e=>console.error(e);function f(e,t){return`${e} option [${t}] is deprecated and will be removed in a later version.`}const p={};try{n(188),p.ASYNC_ITERATOR=!0}catch(e){p.ASYNC_ITERATOR=!1}class d{constructor(e,t){this.db=e,this.collection=t}toString(){return this.collection?`${this.db}.${this.collection}`:this.db}withCollection(e){return new d(this.db,e)}static fromString(e){if(!e)throw new Error(`Cannot parse namespace from "${e}"`);const t=e.indexOf(".");return new d(e.substring(0,t),e.substring(t+1))}}function h(){const e=process.hrtime();return Math.floor(1e3*e[0]+e[1]/1e6)}const m="MONGODB DRIVER";function g(e){return process.emitWarning?u<=6?process.emitWarning(e,void 0,m):process.emitWarning(e,{code:m}):console.error(`[${m}] Warning:`,e)}const y=new Set;e.exports={filterOptions:function(e,t){var n={};for(var r in e)-1!==t.indexOf(r)&&(n[r]=e[r]);return n},mergeOptions:function(e,t){for(var n in t)e[n]=t[n];return e},translateOptions:function(e,t){var n={sslCA:"ca",sslCRL:"crl",sslValidate:"rejectUnauthorized",sslKey:"key",sslCert:"cert",sslPass:"passphrase",socketTimeoutMS:"socketTimeout",connectTimeoutMS:"connectionTimeout",replicaSet:"setName",rs_name:"setName",secondaryAcceptableLatencyMS:"acceptableLatency",connectWithNoPrimary:"secondaryOnlyConnectionAllowed",acceptableLatencyMS:"localThresholdMS"};for(var r in t)n[r]?e[n[r]]=t[r]:e[r]=t[r];return e},shallowClone:function(e){var t={};for(var n in e)t[n]=e[n];return t},getSingleProperty:function(e,t,n){Object.defineProperty(e,t,{enumerable:!0,get:function(){return n}})},checkCollectionName:function(e){if("string"!=typeof e)throw new r("collection name must be a String");if(!e||-1!==e.indexOf(".."))throw new r("collection names cannot be empty");if(-1!==e.indexOf("$")&&null==e.match(/((^\$cmd)|(oplog\.\$main))/))throw new r("collection names must not contain '$'");if(null!=e.match(/^\.|\.$/))throw new r("collection names must not start or end with '.'");if(-1!==e.indexOf("\0"))throw new r("collection names cannot contain a null character")},toError:function(e){if(e instanceof Error)return e;for(var t=e.err||e.errmsg||e.errMessage||e,n=r.create({message:t,driver:!0}),o="object"==typeof e?Object.keys(e):[],i=0;i<o.length;i++)try{n[o[i]]=e[o[i]]}catch(e){}return n},formattedOrderClause:s,parseIndexOptions:function(e){var t,n={},r=[];return"string"==typeof e?(r.push(e+"_1"),n[e]=1):Array.isArray(e)?e.forEach((function(e){"string"==typeof e?(r.push(e+"_1"),n[e]=1):Array.isArray(e)?(r.push(e[0]+"_"+(e[1]||1)),n[e[0]]=e[1]||1):a(e)&&(t=Object.keys(e)).forEach((function(t){r.push(t+"_"+e[t]),n[t]=e[t]}))})):a(e)&&(t=Object.keys(e)).forEach((function(t){r.push(t+"_"+e[t]),n[t]=e[t]})),{name:r.join("_"),keys:t,fieldHash:n}},normalizeHintField:function(e){var t=null;if("string"==typeof e)t=e;else if(Array.isArray(e))t={},e.forEach((function(e){t[e]=1}));else if(null!=e&&"object"==typeof e)for(var n in t={},e)t[n]=e[n];return t},handleCallback:function(e,t,n,r){try{if(null==e)return;if(e)return r?e(t,n,r):e(t,n)}catch(t){return process.nextTick((function(){throw t})),!1}return!0},decorateCommand:function(e,t,n){for(var r in t)-1===n.indexOf(r)&&(e[r]=t[r]);return e},isObject:a,debugOptions:function(e,t){var n={};return e.forEach((function(e){n[e]=t[e]})),n},MAX_JS_INT:Number.MAX_SAFE_INTEGER+1,conditionallyMergeWriteConcern:function(e,t){let n=!1;for(const t of c)if(t in e){n=!0;break}if(!n)for(const n of c)t[n]&&("writeConcern"in e||(e.writeConcern={}),e.writeConcern[n]=t[n]);return e},executeLegacyOperation:(e,t,n,o)=>{if(null==e)throw new TypeError("This method requires a valid topology instance");if(!Array.isArray(n))throw new TypeError("This method requires an array of arguments to apply");o=o||{};const i=e.s.promiseLibrary;let s,a,c,u=n[n.length-1];if(!o.skipSessions&&e.hasSessionSupport())if(a=n[n.length-2],null==a||null==a.session){c=Symbol(),s=e.startSession({owner:c});const t=n.length-2;n[t]=Object.assign({},n[t],{session:s})}else if(a.session&&a.session.hasEnded)throw new r("Use of expired sessions is not permitted");const l=(e,t)=>function(n,r){if(s&&s.owner===c&&!o.returnsCursor)s.endSession(()=>{if(delete a.session,n)return t(n);e(r)});else{if(n)return t(n);e(r)}};if("function"==typeof u){u=n.pop();const e=l(e=>u(null,e),e=>u(e,null));n.push(e);try{return t.apply(null,n)}catch(t){throw e(t),t}}if(null!=n[n.length-1])throw new TypeError("final argument to `executeLegacyOperation` must be a callback");return new i((function(e,r){const o=l(e,r);n[n.length-1]=o;try{return t.apply(null,n)}catch(e){o(e)}}))},applyRetryableWrites:function(e,t){return t&&t.s.options.retryWrites&&(e.retryWrites=!0),e},applyWriteConcern:function(e,t,n){n=n||{};const r=t.db,i=t.collection;if(n.session&&n.session.inTransaction())return e.writeConcern&&delete e.writeConcern,e;const s=o.fromOptions(n);return s?Object.assign(e,{writeConcern:s}):i&&i.writeConcern?Object.assign(e,{writeConcern:Object.assign({},i.writeConcern)}):r&&r.writeConcern?Object.assign(e,{writeConcern:Object.assign({},r.writeConcern)}):e},isPromiseLike:function(e){return e&&"function"==typeof e.then},decorateWithCollation:function(e,t,n){const o=t.s&&t.s.topology||t.topology;if(!o)throw new TypeError('parameter "target" is missing a topology');const i=o.capabilities();if(n.collation&&"object"==typeof n.collation){if(!i||!i.commandsTakeCollation)throw new r("Current topology does not support collation");e.collation=n.collation}},decorateWithReadConcern:function(e,t,n){if(n&&n.session&&n.session.inTransaction())return;let r=Object.assign({},e.readConcern||{});t.s.readConcern&&Object.assign(r,t.s.readConcern),Object.keys(r).length>0&&Object.assign(e,{readConcern:r})},decorateWithExplain:function(e,t){return e.explain?e:{explain:e,verbosity:t.verbosity}},deprecateOptions:function(e,t){if(!0===process.noDeprecation)return t;const n=e.msgHandler?e.msgHandler:f,r=new Set;function o(){const o=arguments[e.optionsIndex];return a(o)&&0!==Object.keys(o).length?(e.deprecatedOptions.forEach(t=>{if(Object.prototype.hasOwnProperty.call(o,t)&&!r.has(t)){r.add(t);const o=n(e.name,t);if(l(o),this&&this.getLogger){const e=this.getLogger();e&&e.warn(o)}}}),t.apply(this,arguments)):t.apply(this,arguments)}return Object.setPrototypeOf(o,t),t.prototype&&(o.prototype=t.prototype),o},SUPPORTS:p,MongoDBNamespace:d,emitDeprecationWarning:l,makeCounter:function*(e){let t=e||0;for(;;){const e=t;t+=1,yield e}},maybePromise:function(e,t,n){const r=e&&e.s&&e.s.promiseLibrary||Promise;let o;return"function"!=typeof t&&(o=new r((e,n)=>{t=(t,r)=>{if(t)return n(t);e(r)}})),n((function(e,n){if(null==e)t(e,n);else try{t(e)}catch(e){return process.nextTick(()=>{throw e})}})),o},now:h,calculateDurationInMs:function(e){if("number"!=typeof e)throw TypeError("numeric value required to calculate duration");const t=h()-e;return t<0?0:t},makeInterruptableAsyncInterval:function(e,t){let n,r,o,i=!1;const s=(t=t||{}).interval||1e3,a=t.minInterval||500,c="boolean"==typeof t.immediate&&t.immediate,u="function"==typeof t.clock?t.clock:h;function l(e){i||(clearTimeout(n),n=setTimeout(f,e||s))}function f(){o=0,r=u(),e(e=>{if(e)throw e;l(s)})}return c?f():(r=u(),l()),{wake:function(){const e=u(),t=e-o,n=s-(e-r);o=e,t<a||(n>a&&l(a),n<0&&f())},stop:function(){i=!0,n&&(clearTimeout(n),n=null),r=0,o=0}}},hasAtomicOperators:function e(t){return Array.isArray(t)?t.reduce((t,n)=>t||e(n),null):Object.keys("function"!=typeof t.toBSON?t:t.toBSON()).map(e=>e[0]).indexOf("$")>=0},MONGODB_WARNING_CODE:m,emitWarning:g,emitWarningOnce:function(e){if(!y.has(e))return y.add(e),g(e)}}},function(e,t,n){"use strict";const r=n(90).Explain,o=n(3).MongoError,i={READ_OPERATION:Symbol("READ_OPERATION"),WRITE_OPERATION:Symbol("WRITE_OPERATION"),RETRYABLE:Symbol("RETRYABLE"),EXECUTE_WITH_SELECTION:Symbol("EXECUTE_WITH_SELECTION"),NO_INHERIT_OPTIONS:Symbol("NO_INHERIT_OPTIONS"),EXPLAINABLE:Symbol("EXPLAINABLE")};e.exports={Aspect:i,defineAspects:function(e,t){return Array.isArray(t)||t instanceof Set||(t=[t]),t=new Set(t),Object.defineProperty(e,"aspects",{value:t,writable:!1}),t},OperationBase:class{constructor(e){if(this.options=Object.assign({},e),this.hasAspect(i.EXPLAINABLE))this.explain=r.fromOptions(e);else if(void 0!==this.options.explain)throw new o("explain is not supported on this command")}hasAspect(e){return null!=this.constructor.aspects&&this.constructor.aspects.has(e)}set session(e){Object.assign(this.options,{session:e})}get session(){return this.options.session}clearSession(){delete this.options.session}get canRetryRead(){return!0}execute(){throw new TypeError("`execute` must be implemented for OperationBase subclasses")}}}},function(e,t,n){"use strict";let r=n(185);const o=n(132)(n(186)),i=n(4).retrieveEJSON();try{const e=o("bson-ext");e&&(r=e)}catch(e){}e.exports={MongoError:n(3).MongoError,MongoNetworkError:n(3).MongoNetworkError,MongoParseError:n(3).MongoParseError,MongoTimeoutError:n(3).MongoTimeoutError,MongoServerSelectionError:n(3).MongoServerSelectionError,MongoWriteConcernError:n(3).MongoWriteConcernError,Connection:n(187),Server:n(134),ReplSet:n(428),Mongos:n(430),Logger:n(16),Cursor:n(17).CoreCursor,ReadPreference:n(10),Sessions:n(34),BSON:r,EJSON:i,Topology:n(431).Topology,Query:n(21).Query,MongoCredentials:n(198).MongoCredentials,defaultAuthProviders:n(193).defaultAuthProviders,MongoCR:n(194),X509:n(195),Plain:n(196),GSSAPI:n(197),ScramSHA1:n(87).ScramSHA1,ScramSHA256:n(87).ScramSHA256,parseConnectionString:n(446)}},function(e,t,n){"use strict";const r=Symbol("errorLabels");class o extends Error{constructor(e){if(e instanceof Error)super(e.message),this.stack=e.stack;else{if("string"==typeof e)super(e);else for(var t in super(e.message||e.errmsg||e.$err||"n/a"),e.errorLabels&&(this[r]=new Set(e.errorLabels)),e)"errorLabels"!==t&&"errmsg"!==t&&(this[t]=e[t]);Error.captureStackTrace(this,this.constructor)}this.name="MongoError"}get errmsg(){return this.message}static create(e){return new o(e)}hasErrorLabel(e){return null!=this[r]&&this[r].has(e)}addErrorLabel(e){null==this[r]&&(this[r]=new Set),this[r].add(e)}get errorLabels(){return this[r]?Array.from(this[r]):[]}}const i=Symbol("beforeHandshake");class s extends o{constructor(e,t){super(e),this.name="MongoNetworkError",t&&!0===t.beforeHandshake&&(this[i]=!0)}}class a extends o{constructor(e){super(e),this.name="MongoParseError"}}class c extends o{constructor(e,t){t&&t.error?super(t.error.message||t.error):super(e),this.name="MongoTimeoutError",t&&(this.reason=t)}}class u extends o{constructor(e,t){super(e),this.name="MongoWriteConcernError",t&&Array.isArray(t.errorLabels)&&(this[r]=new Set(t.errorLabels)),null!=t&&(this.result=function(e){const t=Object.assign({},e);return 0===t.ok&&(t.ok=1,delete t.errmsg,delete t.code,delete t.codeName),t}(t))}}const l=new Set([6,7,89,91,189,9001,10107,11600,11602,13435,13436]),f=new Set([11600,11602,10107,13435,13436,189,91,7,6,89,9001,262]);const p=new Set([91,189,11600,11602,13436]),d=new Set([10107,13435]),h=new Set([11600,91]);function m(e){return!(!e.code||!p.has(e.code))||(e.message.match(/not master or secondary/)||e.message.match(/node is recovering/))}e.exports={MongoError:o,MongoNetworkError:s,MongoNetworkTimeoutError:class extends s{constructor(e,t){super(e,t),this.name="MongoNetworkTimeoutError"}},MongoParseError:a,MongoTimeoutError:c,MongoServerSelectionError:class extends c{constructor(e,t){super(e,t),this.name="MongoServerSelectionError"}},MongoWriteConcernError:u,isRetryableError:function(e){return l.has(e.code)||e instanceof s||e.message.match(/not master/)||e.message.match(/node is recovering/)},isSDAMUnrecoverableError:function(e){return e instanceof a||null==e||!!(m(e)||(t=e,t.code&&d.has(t.code)||!m(t)&&t.message.match(/not master/)));var t},isNodeShuttingDownError:function(e){return e.code&&h.has(e.code)},isRetryableWriteError:function(e){return e instanceof u?f.has(e.code)||f.has(e.result.code):f.has(e.code)},isNetworkErrorBeforeHandshake:function(e){return!0===e[i]}}},function(e,t,n){"use strict";const r=n(410),o=n(20),i=n(132)(n(186));const s=function(){throw new Error("The `mongodb-extjson` module was not found. Please install it and try again.")};function a(e){if(e){if(e.ismaster)return e.ismaster.maxWireVersion;if("function"==typeof e.lastIsMaster){const t=e.lastIsMaster();if(t)return t.maxWireVersion}if(e.description)return e.description.maxWireVersion}return 0}e.exports={uuidV4:()=>{const e=o.randomBytes(16);return e[6]=15&e[6]|64,e[8]=63&e[8]|128,e},relayEvents:function(e,t,n){n.forEach(n=>e.on(n,e=>t.emit(n,e)))},collationNotSupported:function(e,t){return t&&t.collation&&a(e)<5},retrieveEJSON:function(){let e=i("mongodb-extjson");return e||(e={parse:s,deserialize:s,serialize:s,stringify:s,setBSONModule:s,BSON:s}),e},retrieveKerberos:function(){let e;try{e=i("kerberos")}catch(e){if("MODULE_NOT_FOUND"===e.code)throw new Error("The `kerberos` module was not found. Please install it and try again.");throw e}return e},maxWireVersion:a,isPromiseLike:function(e){return e&&"function"==typeof e.then},eachAsync:function(e,t,n){e=e||[];let r=0,o=0;for(r=0;r<e.length;++r)o++,t(e[r],i);function i(t){o--,t?n(t):r===e.length&&o<=0&&n()}0!==o||n()},eachAsyncSeries:function(e,t,n){let r=0,o=(e=e||[]).length;0!==o?t(e[r],(function i(s){r++,o--,s?n(s):r===e.length&&o<=0?n():t(e[r],i)})):n()},isUnifiedTopology:function(e){return null!=e.description},arrayStrictEqual:function(e,t){return!(!Array.isArray(e)||!Array.isArray(t))&&(e.length===t.length&&e.every((e,n)=>e===t[n]))},tagsStrictEqual:function(e,t){const n=Object.keys(e),r=Object.keys(t);return n.length===r.length&&n.every(n=>t[n]===e[n])},errorStrictEqual:function(e,t){return e===t||!(null==e&&null!=t||null!=e&&null==t)&&(e.constructor.name===t.constructor.name&&e.message===t.message)},makeStateMachine:function(e){return function(t,n){const r=e[t.s.state];if(r&&r.indexOf(n)<0)throw new TypeError(`illegal state transition from [${t.s.state}] => [${n}], allowed: [${r}]`);t.emit("stateChanged",t.s.state,n),t.s.state=n}},makeClientMetadata:function(e){e=e||{};const t={driver:{name:"nodejs",version:n(411).version},os:{type:r.type(),name:process.platform,architecture:process.arch,version:r.release()},platform:`'Node.js ${process.version}, ${r.endianness} (${e.useUnifiedTopology?"unified":"legacy"})`};if(e.driverInfo&&(e.driverInfo.name&&(t.driver.name=`${t.driver.name}|${e.driverInfo.name}`),e.driverInfo.version&&(t.version=`${t.driver.version}|${e.driverInfo.version}`),e.driverInfo.platform&&(t.platform=`${t.platform}|${e.driverInfo.platform}`)),e.appname){const n=Buffer.from(e.appname);t.application={name:n.length>128?n.slice(0,128).toString("utf8"):e.appname}}return t},noop:()=>{}}},function(e,t){e.exports=require("util")},function(e,t,n){"use strict";const r=n(10),o=n(3).MongoError,i=n(13).ServerType,s=n(189).TopologyDescription;e.exports={getReadPreference:function(e,t){var n=e.readPreference||new r("primary");if(t.readPreference&&(n=t.readPreference),"string"==typeof n&&(n=new r(n)),!(n instanceof r))throw new o("read preference must be a ReadPreference instance");return n},MESSAGE_HEADER_SIZE:16,COMPRESSION_DETAILS_SIZE:9,opcodes:{OP_REPLY:1,OP_UPDATE:2001,OP_INSERT:2002,OP_QUERY:2004,OP_GETMORE:2005,OP_DELETE:2006,OP_KILL_CURSORS:2007,OP_COMPRESSED:2012,OP_MSG:2013},parseHeader:function(e){return{length:e.readInt32LE(0),requestId:e.readInt32LE(4),responseTo:e.readInt32LE(8),opCode:e.readInt32LE(12)}},applyCommonQueryOptions:function(e,t){return Object.assign(e,{raw:"boolean"==typeof t.raw&&t.raw,promoteLongs:"boolean"!=typeof t.promoteLongs||t.promoteLongs,promoteValues:"boolean"!=typeof t.promoteValues||t.promoteValues,promoteBuffers:"boolean"==typeof t.promoteBuffers&&t.promoteBuffers,monitoring:"boolean"==typeof t.monitoring&&t.monitoring,fullResult:"boolean"==typeof t.fullResult&&t.fullResult}),"number"==typeof t.socketTimeout&&(e.socketTimeout=t.socketTimeout),t.session&&(e.session=t.session),"string"==typeof t.documentsReturnedIn&&(e.documentsReturnedIn=t.documentsReturnedIn),e},isSharded:function(e){if("mongos"===e.type)return!0;if(e.description&&e.description.type===i.Mongos)return!0;if(e.description&&e.description instanceof s){return Array.from(e.description.servers.values()).some(e=>e.type===i.Mongos)}return!1},databaseNamespace:function(e){return e.split(".")[0]},collectionNamespace:function(e){return e.split(".").slice(1).join(".")}}},function(e,t,n){"use strict";const r=n(10),o=n(13).TopologyType,i=n(3).MongoError,s=n(3).isRetryableWriteError,a=n(4).maxWireVersion,c=n(3).MongoNetworkError;function u(e,t,n){e.listeners(t).length>0&&e.emit(t,n)}var l=function(e){return e.s.serverDescription||(e.s.serverDescription={address:e.name,arbiters:[],hosts:[],passives:[],type:"Unknown"}),e.s.serverDescription},f=function(e,t){e.listeners("serverDescriptionChanged").length>0&&(e.emit("serverDescriptionChanged",{topologyId:-1!==e.s.topologyId?e.s.topologyId:e.id,address:e.name,previousDescription:l(e),newDescription:t}),e.s.serverDescription=t)},p=function(e){return e.s.topologyDescription||(e.s.topologyDescription={topologyType:"Unknown",servers:[{address:e.name,arbiters:[],hosts:[],passives:[],type:"Unknown"}]}),e.s.topologyDescription},d=function(e,t){return t||(t=e.ismaster),t?t.ismaster&&"isdbgrid"===t.msg?"Mongos":t.ismaster&&!t.hosts?"Standalone":t.ismaster?"RSPrimary":t.secondary?"RSSecondary":t.arbiterOnly?"RSArbiter":"Unknown":"Unknown"},h=function(e){return function(t){if("destroyed"!==e.s.state){var n=(new Date).getTime();u(e,"serverHeartbeatStarted",{connectionId:e.name}),e.command("admin.$cmd",{ismaster:!0},{monitoring:!0},(function(r,o){if(r)u(e,"serverHeartbeatFailed",{durationMS:i,failure:r,connectionId:e.name});else{e.emit("ismaster",o,e);var i=(new Date).getTime()-n;u(e,"serverHeartbeatSucceeded",{durationMS:i,reply:o.result,connectionId:e.name}),function(e,t,n){var r=d(e,t);return d(e,n)!==r}(e,e.s.ismaster,o.result)&&f(e,{address:e.name,arbiters:[],hosts:[],passives:[],type:e.s.inTopology?d(e):"Standalone"}),e.s.ismaster=o.result,e.s.isMasterLatencyMS=i}if("function"==typeof t)return t(r,o);e.s.inquireServerStateTimeout=setTimeout(h(e),e.s.haInterval)}))}}};const m={endSessions:function(e,t){Array.isArray(e)||(e=[e]),this.command("admin.$cmd",{endSessions:e},{readPreference:r.primaryPreferred},()=>{"function"==typeof t&&t()})}};function g(e){return e.description?e.description.type:"mongos"===e.type?o.Sharded:"replset"===e.type?o.ReplicaSetWithPrimary:o.Single}const y=function(e){return!(e.lastIsMaster().maxWireVersion<6)&&(!!e.logicalSessionTimeoutMinutes&&g(e)!==o.Single)},b="This MongoDB deployment does not support retryable writes. Please add retryWrites=false to your connection string.";e.exports={SessionMixins:m,resolveClusterTime:function(e,t){null==e.clusterTime?e.clusterTime=t:t.clusterTime.greaterThan(e.clusterTime.clusterTime)&&(e.clusterTime=t)},inquireServerState:h,getTopologyType:d,emitServerDescriptionChanged:f,emitTopologyDescriptionChanged:function(e,t){e.listeners("topologyDescriptionChanged").length>0&&(e.emit("topologyDescriptionChanged",{topologyId:-1!==e.s.topologyId?e.s.topologyId:e.id,address:e.name,previousDescription:p(e),newDescription:t}),e.s.serverDescription=t)},cloneOptions:function(e){var t={};for(var n in e)t[n]=e[n];return t},createCompressionInfo:function(e){return e.compression&&e.compression.compressors?(e.compression.compressors.forEach((function(e){if("snappy"!==e&&"zlib"!==e)throw new Error("compressors must be at least one of snappy or zlib")})),e.compression.compressors):[]},clone:function(e){return JSON.parse(JSON.stringify(e))},diff:function(e,t){var n={servers:[]};e||(e={servers:[]});for(var r=0;r<e.servers.length;r++){for(var o=!1,i=0;i<t.servers.length;i++)if(t.servers[i].address.toLowerCase()===e.servers[r].address.toLowerCase()){o=!0;break}o||n.servers.push({address:e.servers[r].address,from:e.servers[r].type,to:"Unknown"})}for(i=0;i<t.servers.length;i++){for(o=!1,r=0;r<e.servers.length;r++)if(e.servers[r].address.toLowerCase()===t.servers[i].address.toLowerCase()){o=!0;break}o||n.servers.push({address:t.servers[i].address,from:"Unknown",to:t.servers[i].type})}for(r=0;r<e.servers.length;r++){var s=e.servers[r];for(i=0;i<t.servers.length;i++){var a=t.servers[i];s.address.toLowerCase()===a.address.toLowerCase()&&s.type!==a.type&&n.servers.push({address:s.address,from:s.type,to:a.type})}}return n},Interval:function(e,t){var n=!1;this.start=function(){return this.isRunning()||(n=setInterval(e,t)),this},this.stop=function(){return clearInterval(n),n=!1,this},this.isRunning=function(){return!1!==n}},Timeout:function(e,t){var n=!1,r=()=>{n&&(clearTimeout(n),n=!1,e())};this.start=function(){return this.isRunning()||(n=setTimeout(r,t)),this},this.stop=function(){return clearTimeout(n),n=!1,this},this.isRunning=function(){return!1!==n}},isRetryableWritesSupported:y,getMMAPError:function(e){return 20===e.code&&e.errmsg.includes("Transaction numbers")?new i({message:b,errmsg:b,originalError:e}):e},topologyType:g,legacyIsRetryableWriteError:function(e,t){return e instanceof i&&(y(t)&&(e instanceof c||a(t)<9&&s(e))&&e.addErrorLabel("RetryableWriteError"),e.hasErrorLabel("RetryableWriteError"))}}},function(e,t){e.exports=require("events")},function(e,t,n){"use strict";const r=n(132)(n(412));function o(){throw new Error("Attempted to use Snappy compression, but Snappy is not installed. Install or disable Snappy compression and try again.")}e.exports={debugOptions:function(e,t){const n={};return e.forEach((function(e){n[e]=t[e]})),n},retrieveBSON:function(){const e=n(185);e.native=!1;const t=r("bson-ext");return t?(t.native=!0,t):e},retrieveSnappy:function(){let e=r("snappy");return e||(e={compress:o,uncompress:o,compressSync:o,uncompressSync:o}),e}}},function(e,t,n){"use strict";const r=n(0).emitWarningOnce,o=function(e,t,n){if(!o.isValid(e))throw new TypeError(`Invalid read preference mode ${e}`);if(t&&!Array.isArray(t)){r("ReadPreference tags must be an array, this will change in the next major version");const e=void 0!==t.maxStalenessSeconds,o=void 0!==t.hedge;e||o?(n=t,t=void 0):t=[t]}if(this.mode=e,this.tags=t,this.hedge=n&&n.hedge,null!=(n=n||{}).maxStalenessSeconds){if(n.maxStalenessSeconds<=0)throw new TypeError("maxStalenessSeconds must be a positive integer");this.maxStalenessSeconds=n.maxStalenessSeconds,this.minWireVersion=5}if(this.mode===o.PRIMARY){if(this.tags&&Array.isArray(this.tags)&&this.tags.length>0)throw new TypeError("Primary read preference cannot be combined with tags");if(this.maxStalenessSeconds)throw new TypeError("Primary read preference cannot be combined with maxStalenessSeconds");if(this.hedge)throw new TypeError("Primary read preference cannot be combined with hedge")}};Object.defineProperty(o.prototype,"preference",{enumerable:!0,get:function(){return this.mode}}),o.PRIMARY="primary",o.PRIMARY_PREFERRED="primaryPreferred",o.SECONDARY="secondary",o.SECONDARY_PREFERRED="secondaryPreferred",o.NEAREST="nearest";const i=[o.PRIMARY,o.PRIMARY_PREFERRED,o.SECONDARY,o.SECONDARY_PREFERRED,o.NEAREST,null];o.fromOptions=function(e){if(!e)return null;const t=e.readPreference;if(!t)return null;const n=e.readPreferenceTags,r=e.maxStalenessSeconds;if("string"==typeof t)return new o(t,n);if(!(t instanceof o)&&"object"==typeof t){const e=t.mode||t.preference;if(e&&"string"==typeof e)return new o(e,t.tags,{maxStalenessSeconds:t.maxStalenessSeconds||r,hedge:t.hedge})}return t},o.resolve=function(e,t){const n=(t=t||{}).session,r=e&&e.readPreference;let i;return i=t.readPreference?o.fromOptions(t):n&&n.inTransaction()&&n.transaction.options.readPreference?n.transaction.options.readPreference:null!=r?r:o.primary,"string"==typeof i?new o(i):i},o.translate=function(e){if(null==e.readPreference)return e;const t=e.readPreference;if("string"==typeof t)e.readPreference=new o(t);else if(!t||t instanceof o||"object"!=typeof t){if(!(t instanceof o))throw new TypeError("Invalid read preference: "+t)}else{const n=t.mode||t.preference;n&&"string"==typeof n&&(e.readPreference=new o(n,t.tags,{maxStalenessSeconds:t.maxStalenessSeconds}))}return e},o.isValid=function(e){return-1!==i.indexOf(e)},o.prototype.isValid=function(e){return o.isValid("string"==typeof e?e:this.mode)};const s=["primaryPreferred","secondary","secondaryPreferred","nearest"];o.prototype.slaveOk=function(){return-1!==s.indexOf(this.mode)},o.prototype.equals=function(e){return e.mode===this.mode},o.prototype.toJSON=function(){const e={mode:this.mode};return Array.isArray(this.tags)&&(e.tags=this.tags),this.maxStalenessSeconds&&(e.maxStalenessSeconds=this.maxStalenessSeconds),this.hedge&&(e.hedge=this.hedge),e},o.primary=new o("primary"),o.primaryPreferred=new o("primaryPreferred"),o.secondary=new o("secondary"),o.secondaryPreferred=new o("secondaryPreferred"),o.nearest=new o("nearest"),e.exports=o},function(e,t,n){"use strict";const r=n(0).applyWriteConcern,o=n(2).BSON.Code,i=n(0).debugOptions,s=n(0).handleCallback,a=n(2).MongoError,c=n(0).parseIndexOptions,u=n(2).ReadPreference,l=n(0).toError,f=n(140),p=n(0).MongoDBNamespace,d=["authSource","w","wtimeout","j","native_parser","forceServerObjectId","serializeFunctions","raw","promoteLongs","promoteValues","promoteBuffers","bufferMaxEntries","numberOfRetries","retryMiliSeconds","readPreference","pkFactory","parentDb","promiseLibrary","noListener"];function h(e,t,n,o,i){let p=Object.assign({},{readPreference:u.PRIMARY},o);if(p=r(p,{db:e},o),p.writeConcern&&"function"!=typeof i)throw a.create({message:"Cannot use a writeConcern without a provided callback",driver:!0});if(e.serverConfig&&e.serverConfig.isDestroyed())return i(new a("topology was destroyed"));!function(e,t,n,o,i){const f=c(n),p="string"==typeof o.name?o.name:f.name,d=[{name:p,key:f.fieldHash}],h=Object.keys(d[0]).concat(["writeConcern","w","wtimeout","j","fsync","readPreference","session"]);for(let e in o)-1===h.indexOf(e)&&(d[0][e]=o[e]);const g=e.s.topology.capabilities();if(d[0].collation&&g&&!g.commandsTakeCollation){const e=new a("server/primary/mongos does not support collation");return e.code=67,i(e)}const y=r({createIndexes:t,indexes:d},{db:e},o);o.readPreference=u.PRIMARY,m(e,y,o,(e,t)=>e?s(i,e,null):0===t.ok?s(i,l(t),null):void s(i,null,p))}(e,t,n,p,(r,c)=>{if(null==r)return s(i,r,c);if(67===r.code||11e3===r.code||85===r.code||86===r.code||11600===r.code||197===r.code)return s(i,r,c);const u=y(e,t,n,o);p.checkKeys=!1,e.s.topology.insert(e.s.namespace.withCollection(f.SYSTEM_INDEX_COLLECTION),u,p,(e,t)=>{if(null!=i)return e?s(i,e):null==t?s(i,null,null):t.result.writeErrors?s(i,a.create(t.result.writeErrors[0]),null):void s(i,null,u.name)})})}function m(e,t,n,r){if(e.serverConfig&&e.serverConfig.isDestroyed())return r(new a("topology was destroyed"));const o=n.dbName||n.authdb||e.databaseName;n.readPreference=u.resolve(e,n),e.s.logger.isDebug()&&e.s.logger.debug(`executing command ${JSON.stringify(t)} against ${o}.$cmd with options [${JSON.stringify(i(d,n))}]`),e.s.topology.command(e.s.namespace.withCollection("$cmd"),t,n,(e,t)=>e?s(r,e):n.full?s(r,null,t):void s(r,null,t.result))}function g(e,t,n,r){const o=null!=n.full&&n.full;if(e.serverConfig&&e.serverConfig.isDestroyed())return r(new a("topology was destroyed"));e.collection(t).listIndexes(n).toArray((e,t)=>e?r(l(e)):Array.isArray(t)?o?s(r,null,t):void s(r,null,function(e){let t={};for(let n=0;n<e.length;n++){const r=e[n];t[r.name]=[];for(let e in r.key)t[r.name].push([e,r.key[e]])}return t}(t)):s(r,null,[]))}function y(e,t,n,r){const o=c(n),i=o.fieldHash,s="string"==typeof r.name?r.name:o.name,a={ns:e.s.namespace.withCollection(t).toString(),key:i,name:s},u=null!=r&&"object"!=typeof r&&r;r=null==r||"boolean"==typeof r?{}:r;const l=Object.keys(a);for(let e in r)-1===l.indexOf(e)&&(a[e]=r[e]);null==a.unique&&(a.unique=u);const f=["w","wtimeout","j","fsync","readPreference","session"];for(let e=0;e<f.length;e++)delete a[f[e]];return a}e.exports={createListener:function(e,t,n){return function(r){if(n.listeners(t).length>0){n.emit(t,r,e);for(let n=0;n<e.s.children.length;n++)e.s.children[n].emit(t,r,e.s.children[n])}}},createIndex:h,ensureIndex:function(e,t,n,o,i){const c=r({},{db:e},o),l=y(e,t,n,o).name;if(e.serverConfig&&e.serverConfig.isDestroyed())return i(new a("topology was destroyed"));c.readPreference=u.PRIMARY,g(e,t,c,(r,a)=>{if(null!=r&&26!==r.code)return s(i,r,null);if(null!=a&&a[l]){if("function"==typeof i)return s(i,null,l)}else h(e,t,n,o,i)})},evaluate:function(e,t,n,r,i){let c=t,l=[];if(e.serverConfig&&e.serverConfig.isDestroyed())return i(new a("topology was destroyed"));c&&"Code"===c._bsontype||(c=new o(c)),null==n||Array.isArray(n)||"function"==typeof n?null!=n&&Array.isArray(n)&&"function"!=typeof n&&(l=n):l=[n];let f={$eval:c,args:l};r.nolock&&(f.nolock=r.nolock),r.readPreference=new u(u.PRIMARY),m(e,f,r,(e,t)=>e?s(i,e,null):t&&1===t.ok?s(i,null,t.retval):t?s(i,a.create({message:`eval failed: ${t.errmsg}`,driver:!0}),null):void s(i,e,t))},executeCommand:m,executeDbAdminCommand:function(e,t,n,r){const o=new p("admin","$cmd");e.s.topology.command(o,t,n,(t,n)=>e.serverConfig&&e.serverConfig.isDestroyed()?r(new a("topology was destroyed")):t?s(r,t):void s(r,null,n.result))},indexInformation:g,profilingInfo:function(e,t,n){try{e.collection("system.profile").find({},t).toArray(n)}catch(e){return n(e,null)}},validateDatabaseName:function(e){if("string"!=typeof e)throw a.create({message:"database name must be a string",driver:!0});if(0===e.length)throw a.create({message:"database name cannot be the empty string",driver:!0});if("$external"===e)return;const t=[" ",".","$","/","\\"];for(let n=0;n<t.length;n++)if(-1!==e.indexOf(t[n]))throw a.create({message:"database names cannot contain the character '"+t[n]+"'",driver:!0})}}},function(e,t){var n=Array.isArray;e.exports=n},function(e,t,n){"use strict";const r={Single:"Single",ReplicaSetNoPrimary:"ReplicaSetNoPrimary",ReplicaSetWithPrimary:"ReplicaSetWithPrimary",Sharded:"Sharded",Unknown:"Unknown"};e.exports={STATE_CLOSING:"closing",STATE_CLOSED:"closed",STATE_CONNECTING:"connecting",STATE_CONNECTED:"connected",TOPOLOGY_DEFAULTS:{useUnifiedTopology:!0,localThresholdMS:15,serverSelectionTimeoutMS:3e4,heartbeatFrequencyMS:1e4,minHeartbeatFrequencyMS:500},TopologyType:r,ServerType:{Standalone:"Standalone",Mongos:"Mongos",PossiblePrimary:"PossiblePrimary",RSPrimary:"RSPrimary",RSSecondary:"RSSecondary",RSArbiter:"RSArbiter",RSOther:"RSOther",RSGhost:"RSGhost",Unknown:"Unknown"},serverType:function(e){let t=e.s.description||e.s.serverDescription;return t.topologyType===r.Single?t.servers[0].type:t.type},drainTimerQueue:function(e){e.forEach(clearTimeout),e.clear()},clearAndRemoveTimerFrom:function(e,t){return clearTimeout(e),t.delete(e)}}},function(e,t,n){"use strict";const r=n(0).applyRetryableWrites,o=n(0).applyWriteConcern,i=n(0).decorateWithCollation,s=n(0).decorateWithReadConcern,a=n(11).executeCommand,c=n(0).formattedOrderClause,u=n(0).handleCallback,l=n(2).MongoError,f=n(2).ReadPreference,p=n(0).toError,d=n(17).CursorState,h=n(4).maxWireVersion;function m(e,t,n){const r="boolean"==typeof n.forceServerObjectId?n.forceServerObjectId:e.s.db.options.forceServerObjectId;return!0===r?t:t.map(t=>(!0!==r&&null==t._id&&(t._id=e.s.pkFactory.createPk()),t))}e.exports={buildCountCommand:function(e,t,n){const r=n.skip,o=n.limit;let a=n.hint;const c=n.maxTimeMS;t=t||{};const u={count:n.collectionName,query:t};return e.s.numberOfRetries?(e.options.hint?a=e.options.hint:e.cmd.hint&&(a=e.cmd.hint),i(u,e,e.cmd)):i(u,e,n),"number"==typeof r&&(u.skip=r),"number"==typeof o&&(u.limit=o),"number"==typeof c&&(u.maxTimeMS=c),a&&(u.hint=a),s(u,e),u},findAndModify:function(e,t,n,s,l,p){const d={findAndModify:e.collectionName,query:t};(n=c(n))&&(d.sort=n),d.new=!!l.new,d.remove=!!l.remove,d.upsert=!!l.upsert;const h=l.projection||l.fields;h&&(d.fields=h),l.arrayFilters&&(d.arrayFilters=l.arrayFilters,delete l.arrayFilters),s&&!l.remove&&(d.update=s),l.maxTimeMS&&(d.maxTimeMS=l.maxTimeMS),l.serializeFunctions=l.serializeFunctions||e.s.serializeFunctions,l.checkKeys=!1;let m=Object.assign({},l);m=r(m,e.s.db),m=o(m,{db:e.s.db,collection:e},l),m.writeConcern&&(d.writeConcern=m.writeConcern),!0===m.bypassDocumentValidation&&(d.bypassDocumentValidation=m.bypassDocumentValidation),m.readPreference=f.primary;try{i(d,e,m)}catch(e){return p(e,null)}a(e.s.db,d,m,(e,t)=>e?u(p,e,null):u(p,null,t))},indexInformation:function(e,t,n,r){const o=null!=n.full&&n.full;if(e.serverConfig&&e.serverConfig.isDestroyed())return r(new l("topology was destroyed"));e.collection(t).listIndexes(n).toArray((e,t)=>e?r(p(e)):Array.isArray(t)?o?u(r,null,t):void u(r,null,function(e){let t={};for(let n=0;n<e.length;n++){const r=e[n];t[r.name]=[];for(let e in r.key)t[r.name].push([e,r.key[e]])}return t}(t)):u(r,null,[]))},nextObject:function(e,t){if(e.s.state===d.CLOSED||e.isDead&&e.isDead())return u(t,l.create({message:"Cursor is closed",driver:!0}));if(e.s.state===d.INIT&&e.cmd&&e.cmd.sort)try{e.cmd.sort=c(e.cmd.sort)}catch(e){return u(t,e)}e._next((n,r)=>{if(e.s.state=d.OPEN,n)return u(t,n);u(t,null,r)})},prepareDocs:m,insertDocuments:function(e,t,n,i){"function"==typeof n&&(i=n,n={}),n=n||{},t=Array.isArray(t)?t:[t];let s=Object.assign({},n);s=r(s,e.s.db),s=o(s,{db:e.s.db,collection:e},n),!0===s.keepGoing&&(s.ordered=!1),s.serializeFunctions=n.serializeFunctions||e.s.serializeFunctions,t=m(e,t,n),e.s.topology.insert(e.s.namespace,t,s,(e,n)=>{if(null!=i){if(e)return u(i,e);if(null==n)return u(i,null,null);if(n.result.code)return u(i,p(n.result));if(n.result.writeErrors)return u(i,p(n.result.writeErrors[0]));n.ops=t,u(i,null,n)}})},removeDocuments:function(e,t,n,s){"function"==typeof n?(s=n,n={}):"function"==typeof t&&(s=t,n={},t={}),n=n||{};let a=Object.assign({},n);a=r(a,e.s.db),a=o(a,{db:e.s.db,collection:e},n),null==t&&(t={});const c={q:t,limit:0};n.single?c.limit=1:a.retryWrites&&(a.retryWrites=!1),n.hint&&(c.hint=n.hint);try{i(a,e,n)}catch(e){return s(e,null)}if(void 0!==n.explain&&h(e.s.topology)<3)return s?s(new l("server does not support explain on remove")):void 0;e.s.topology.remove(e.s.namespace,[c],a,(e,t)=>{if(null!=s)return e?u(s,e,null):null==t?u(s,null,null):t.result.code?u(s,p(t.result)):t.result.writeErrors?u(s,p(t.result.writeErrors[0])):void u(s,null,t)})},updateDocuments:function(e,t,n,s,a){if("function"==typeof s&&(a=s,s=null),null==s&&(s={}),"function"!=typeof a&&(a=null),null==t||"object"!=typeof t)return a(p("selector must be a valid JavaScript object"));if(null==n||"object"!=typeof n)return a(p("document must be a valid JavaScript object"));let c=Object.assign({},s);c=r(c,e.s.db),c=o(c,{db:e.s.db,collection:e},s),c.serializeFunctions=s.serializeFunctions||e.s.serializeFunctions;const f={q:t,u:n};f.upsert=void 0!==s.upsert&&!!s.upsert,f.multi=void 0!==s.multi&&!!s.multi,s.hint&&(f.hint=s.hint),c.arrayFilters&&(f.arrayFilters=c.arrayFilters,delete c.arrayFilters),c.retryWrites&&f.multi&&(c.retryWrites=!1);try{i(c,e,s)}catch(e){return a(e,null)}if(void 0!==s.explain&&h(e.s.topology)<3)return a?a(new l("server does not support explain on update")):void 0;e.s.topology.update(e.s.namespace,[f],c,(e,t)=>{if(null!=a)return e?u(a,e,null):null==t?u(a,null,null):t.result.code?u(a,p(t.result)):t.result.writeErrors?u(a,p(t.result.writeErrors[0])):void u(a,null,t)})}}},function(e,t){e.exports=function(e){return null!=e&&"object"==typeof e}},function(e,t,n){"use strict";var r=n(5).format,o=n(3).MongoError,i={},s={},a=null,c=process.pid,u=null,l=function(e,t){if(!(this instanceof l))return new l(e,t);t=t||{},this.className=e,t.logger?u=t.logger:null==u&&(u=console.log),t.loggerLevel&&(a=t.loggerLevel||"error"),null==s[this.className]&&(i[this.className]=!0)};l.prototype.debug=function(e,t){if(this.isDebug()&&(Object.keys(s).length>0&&s[this.className]||0===Object.keys(s).length&&i[this.className])){var n=(new Date).getTime(),o=r("[%s-%s:%s] %s %s","DEBUG",this.className,c,n,e),a={type:"debug",message:e,className:this.className,pid:c,date:n};t&&(a.meta=t),u(o,a)}},l.prototype.warn=function(e,t){if(this.isWarn()&&(Object.keys(s).length>0&&s[this.className]||0===Object.keys(s).length&&i[this.className])){var n=(new Date).getTime(),o=r("[%s-%s:%s] %s %s","WARN",this.className,c,n,e),a={type:"warn",message:e,className:this.className,pid:c,date:n};t&&(a.meta=t),u(o,a)}},l.prototype.info=function(e,t){if(this.isInfo()&&(Object.keys(s).length>0&&s[this.className]||0===Object.keys(s).length&&i[this.className])){var n=(new Date).getTime(),o=r("[%s-%s:%s] %s %s","INFO",this.className,c,n,e),a={type:"info",message:e,className:this.className,pid:c,date:n};t&&(a.meta=t),u(o,a)}},l.prototype.error=function(e,t){if(this.isError()&&(Object.keys(s).length>0&&s[this.className]||0===Object.keys(s).length&&i[this.className])){var n=(new Date).getTime(),o=r("[%s-%s:%s] %s %s","ERROR",this.className,c,n,e),a={type:"error",message:e,className:this.className,pid:c,date:n};t&&(a.meta=t),u(o,a)}},l.prototype.isInfo=function(){return"info"===a||"debug"===a},l.prototype.isError=function(){return"error"===a||"info"===a||"debug"===a},l.prototype.isWarn=function(){return"error"===a||"warn"===a||"info"===a||"debug"===a},l.prototype.isDebug=function(){return"debug"===a},l.reset=function(){a="error",s={}},l.currentLogger=function(){return u},l.setCurrentLogger=function(e){if("function"!=typeof e)throw new o("current logger must be a function");u=e},l.filter=function(e,t){"class"===e&&Array.isArray(t)&&(s={},t.forEach((function(e){s[e]=!0})))},l.setLevel=function(e){if("info"!==e&&"error"!==e&&"debug"!==e&&"warn"!==e)throw new Error(r("%s is an illegal logging level",e));a=e},e.exports=l},function(e,t,n){"use strict";const r=n(16),o=n(9).retrieveBSON,i=n(3).MongoError,s=n(3).MongoNetworkError,a=n(4).collationNotSupported,c=n(10),u=n(4).isUnifiedTopology,l=n(56),f=n(18).Readable,p=n(0).SUPPORTS,d=n(0).MongoDBNamespace,h=n(0).mergeOptions,m=n(1).OperationBase,g=o().Long,y={INIT:0,OPEN:1,CLOSED:2,GET_MORE:3};function b(e,t,n){try{e(t,n)}catch(t){process.nextTick((function(){throw t}))}}class v extends f{constructor(e,t,n,o){super({objectMode:!0}),o=o||{},t instanceof m&&(this.operation=t,t=this.operation.ns.toString(),o=this.operation.options,n=this.operation.cmd?this.operation.cmd:{}),this.pool=null,this.server=null,this.disconnectHandler=o.disconnectHandler,this.bson=e.s.bson,this.ns=t,this.namespace=d.fromString(t),this.cmd=n,this.options=o,this.topology=e,this.cursorState={cursorId:null,cmd:n,documents:o.documents||[],cursorIndex:0,dead:!1,killed:!1,init:!1,notified:!1,limit:o.limit||n.limit||0,skip:o.skip||n.skip||0,batchSize:o.batchSize||n.batchSize||1e3,currentLimit:0,transforms:o.transforms,raw:o.raw||n&&n.raw},"object"==typeof o.session&&(this.cursorState.session=o.session);const i=e.s.options;"boolean"==typeof i.promoteLongs?this.cursorState.promoteLongs=i.promoteLongs:"boolean"==typeof o.promoteLongs&&(this.cursorState.promoteLongs=o.promoteLongs),"boolean"==typeof i.promoteValues?this.cursorState.promoteValues=i.promoteValues:"boolean"==typeof o.promoteValues&&(this.cursorState.promoteValues=o.promoteValues),"boolean"==typeof i.promoteBuffers?this.cursorState.promoteBuffers=i.promoteBuffers:"boolean"==typeof o.promoteBuffers&&(this.cursorState.promoteBuffers=o.promoteBuffers),i.reconnect&&(this.cursorState.reconnect=i.reconnect),this.logger=r("Cursor",i),"number"==typeof n?(this.cursorState.cursorId=g.fromNumber(n),this.cursorState.lastCursorId=this.cursorState.cursorId):n instanceof g&&(this.cursorState.cursorId=n,this.cursorState.lastCursorId=n),this.operation&&(this.operation.cursorState=this.cursorState)}setCursorBatchSize(e){this.cursorState.batchSize=e}cursorBatchSize(){return this.cursorState.batchSize}setCursorLimit(e){this.cursorState.limit=e}cursorLimit(){return this.cursorState.limit}setCursorSkip(e){this.cursorState.skip=e}cursorSkip(){return this.cursorState.skip}_next(e){!function e(t,n){if(t.cursorState.notified)return n(new Error("cursor is exhausted"));if(function(e,t){if(e.cursorState.killed)return w(e,t),!0;return!1}(t,n))return;if(function(e,t){if(e.cursorState.dead&&!e.cursorState.killed)return e.cursorState.killed=!0,w(e,t),!0;return!1}(t,n))return;if(function(e,t){if(e.cursorState.dead&&e.cursorState.killed)return b(t,new i("cursor is dead")),!0;return!1}(t,n))return;if(!t.cursorState.init){if(!t.topology.isConnected(t.options)){if("server"===t.topology._type&&!t.topology.s.options.reconnect)return n(new i("no connection available"));if(null!=t.disconnectHandler)return t.topology.isDestroyed()?n(new i("Topology was destroyed")):void t.disconnectHandler.addObjectAndMethod("cursor",t,"next",[n],n)}return void t._initializeCursor((r,o)=>{r||null===o?n(r,o):e(t,n)})}if(t.cursorState.limit>0&&t.cursorState.currentLimit>=t.cursorState.limit)t.kill(()=>S(t,n));else if(t.cursorState.cursorIndex!==t.cursorState.documents.length||g.ZERO.equals(t.cursorState.cursorId)){if(t.cursorState.documents.length===t.cursorState.cursorIndex&&t.cmd.tailable&&g.ZERO.equals(t.cursorState.cursorId))return b(n,new i({message:"No more documents in tailed cursor",tailable:t.cmd.tailable,awaitData:t.cmd.awaitData}));if(t.cursorState.documents.length===t.cursorState.cursorIndex&&g.ZERO.equals(t.cursorState.cursorId))S(t,n);else{if(t.cursorState.limit>0&&t.cursorState.currentLimit>=t.cursorState.limit)return void t.kill(()=>S(t,n));t.cursorState.currentLimit+=1;let e=t.cursorState.documents[t.cursorState.cursorIndex++];if(!e||e.$err)return void t.kill(()=>S(t,(function(){b(n,new i(e?e.$err:void 0))})));t.cursorState.transforms&&"function"==typeof t.cursorState.transforms.doc&&(e=t.cursorState.transforms.doc(e)),b(n,null,e)}}else{if(t.cursorState.documents=[],t.cursorState.cursorIndex=0,t.topology.isDestroyed())return n(new s("connection destroyed, not possible to instantiate cursor"));if(function(e,t){if(e.pool&&e.pool.isDestroyed()){e.cursorState.killed=!0;const n=new s(`connection to host ${e.pool.host}:${e.pool.port} was destroyed`);return _(e,()=>t(n)),!0}return!1}(t,n))return;t._getMore((function(r,o,s){return r?b(n,r):(t.connection=s,0===t.cursorState.documents.length&&t.cmd.tailable&&g.ZERO.equals(t.cursorState.cursorId)?b(n,new i({message:"No more documents in tailed cursor",tailable:t.cmd.tailable,awaitData:t.cmd.awaitData})):0===t.cursorState.documents.length&&t.cmd.tailable&&!g.ZERO.equals(t.cursorState.cursorId)?e(t,n):t.cursorState.limit>0&&t.cursorState.currentLimit>=t.cursorState.limit?S(t,n):void e(t,n))}))}}(this,e)}clone(){const e=h({},this.options);return delete e.session,this.topology.cursor(this.ns,this.cmd,e)}isDead(){return!0===this.cursorState.dead}isKilled(){return!0===this.cursorState.killed}isNotified(){return!0===this.cursorState.notified}bufferedCount(){return this.cursorState.documents.length-this.cursorState.cursorIndex}readBufferedDocuments(e){const t=this.cursorState.documents.length-this.cursorState.cursorIndex,n=e<t?e:t;let r=this.cursorState.documents.slice(this.cursorState.cursorIndex,this.cursorState.cursorIndex+n);if(this.cursorState.transforms&&"function"==typeof this.cursorState.transforms.doc)for(let e=0;e<r.length;e++)r[e]=this.cursorState.transforms.doc(r[e]);return this.cursorState.limit>0&&this.cursorState.currentLimit+r.length>this.cursorState.limit&&(r=r.slice(0,this.cursorState.limit-this.cursorState.currentLimit),this.kill()),this.cursorState.currentLimit=this.cursorState.currentLimit+r.length,this.cursorState.cursorIndex=this.cursorState.cursorIndex+r.length,r}kill(e){this.cursorState.dead=!0,this.cursorState.killed=!0,this.cursorState.documents=[],null==this.cursorState.cursorId||this.cursorState.cursorId.isZero()||!1===this.cursorState.init?e&&e(null,null):this.server.killCursors(this.ns,this.cursorState,e)}rewind(){this.cursorState.init&&(this.cursorState.dead||this.kill(),this.cursorState.currentLimit=0,this.cursorState.init=!1,this.cursorState.dead=!1,this.cursorState.killed=!1,this.cursorState.notified=!1,this.cursorState.documents=[],this.cursorState.cursorId=null,this.cursorState.cursorIndex=0)}_read(){if(this.s&&this.s.state===y.CLOSED||this.isDead())return this.push(null);this._next((e,t)=>e?(this.listeners("error")&&this.listeners("error").length>0&&this.emit("error",e),this.isDead()||this.close(),this.emit("end"),this.emit("finish")):this.cursorState.streamOptions&&"function"==typeof this.cursorState.streamOptions.transform&&null!=t?this.push(this.cursorState.streamOptions.transform(t)):(this.push(t),void(null===t&&this.isDead()&&this.once("end",()=>{this.close(),this.emit("finish")}))))}_endSession(e,t){"function"==typeof e&&(t=e,e={}),e=e||{};const n=this.cursorState.session;return n&&(e.force||n.owner===this)?(this.cursorState.session=void 0,this.operation&&this.operation.clearSession(),n.endSession(t),!0):(t&&t(),!1)}_getMore(e){this.logger.isDebug()&&this.logger.debug(`schedule getMore call for query [${JSON.stringify(this.query)}]`);let t=this.cursorState.batchSize;this.cursorState.limit>0&&this.cursorState.currentLimit+t>this.cursorState.limit&&(t=this.cursorState.limit-this.cursorState.currentLimit);const n=this.cursorState;this.server.getMore(this.ns,n,t,this.options,(t,r,o)=>{(t||n.cursorId&&n.cursorId.isZero())&&this._endSession(),e(t,r,o)})}_initializeCursor(e){const t=this;if(u(t.topology)&&t.topology.shouldCheckForSessionSupport())return void t.topology.selectServer(c.primaryPreferred,t=>{t?e(t):this._initializeCursor(e)});function n(n,r){const o=t.cursorState;if((n||o.cursorId&&o.cursorId.isZero())&&t._endSession(),0===o.documents.length&&o.cursorId&&o.cursorId.isZero()&&!t.cmd.tailable&&!t.cmd.awaitData)return w(t,e);e(n,r)}const r=(e,r)=>{if(e)return n(e);const o=r.message;if(Array.isArray(o.documents)&&1===o.documents.length){const e=o.documents[0];if(o.queryFailure)return n(new i(e),null);if(!t.cmd.find||t.cmd.find&&!1===t.cmd.virtual){if(e.$err||e.errmsg)return n(new i(e),null);if(null!=e.cursor&&"string"!=typeof e.cursor){const r=e.cursor.id;return e.cursor.ns&&(t.ns=e.cursor.ns),t.cursorState.cursorId="number"==typeof r?g.fromNumber(r):r,t.cursorState.lastCursorId=t.cursorState.cursorId,t.cursorState.operationTime=e.operationTime,Array.isArray(e.cursor.firstBatch)&&(t.cursorState.documents=e.cursor.firstBatch),n(null,o)}}}const s=o.cursorId||0;t.cursorState.cursorId=s instanceof g?s:g.fromNumber(s),t.cursorState.documents=o.documents,t.cursorState.lastCursorId=o.cursorId,t.cursorState.transforms&&"function"==typeof t.cursorState.transforms.query&&(t.cursorState.documents=t.cursorState.transforms.query(o)),n(null,o)};if(t.operation)return t.logger.isDebug()&&t.logger.debug(`issue initial query [${JSON.stringify(t.cmd)}] with flags [${JSON.stringify(t.query)}]`),void l(t.topology,t.operation,(e,o)=>{if(e)n(e);else{if(t.server=t.operation.server,t.cursorState.init=!0,null!=t.cursorState.cursorId)return n();r(e,o)}});const o={};return t.cursorState.session&&(o.session=t.cursorState.session),t.operation?o.readPreference=t.operation.readPreference:t.options.readPreference&&(o.readPreference=t.options.readPreference),t.topology.selectServer(o,(o,s)=>{if(o){const n=t.disconnectHandler;return null!=n?n.addObjectAndMethod("cursor",t,"next",[e],e):e(o)}if(t.server=s,t.cursorState.init=!0,a(t.server,t.cmd))return e(new i(`server ${t.server.name} does not support collation`));if(null!=t.cursorState.cursorId)return n();if(t.logger.isDebug()&&t.logger.debug(`issue initial query [${JSON.stringify(t.cmd)}] with flags [${JSON.stringify(t.query)}]`),null!=t.cmd.find)return void s.query(t.ns,t.cmd,t.cursorState,t.options,r);const c=Object.assign({session:t.cursorState.session},t.options);s.command(t.ns,t.cmd,c,r)})}}function S(e,t){e.cursorState.dead=!0,w(e,t)}function w(e,t){_(e,()=>b(t,null,null))}function _(e,t){if(e.cursorState.notified=!0,e.cursorState.documents=[],e.cursorState.cursorIndex=0,!e.cursorState.session)return t();e._endSession(t)}p.ASYNC_ITERATOR&&(v.prototype[Symbol.asyncIterator]=n(188).asyncIterator),e.exports={CursorState:y,CoreCursor:v}},function(e,t){e.exports=require("stream")},function(e,t,n){var r=n(149),o="object"==typeof self&&self&&self.Object===Object&&self,i=r||o||Function("return this")();e.exports=i},function(e,t){e.exports=require("crypto")},function(e,t,n){"use strict";var r=(0,n(9).retrieveBSON)().Long;const o=n(22).Buffer;var i=0,s=n(6).opcodes,a=function(e,t,n,r){if(null==t)throw new Error("ns must be specified for query");if(null==n)throw new Error("query must be specified for query");if(-1!==t.indexOf("\0"))throw new Error("namespace cannot contain a null character");this.bson=e,this.ns=t,this.query=n,this.numberToSkip=r.numberToSkip||0,this.numberToReturn=r.numberToReturn||0,this.returnFieldSelector=r.returnFieldSelector||null,this.requestId=a.getRequestId(),this.pre32Limit=r.pre32Limit,this.serializeFunctions="boolean"==typeof r.serializeFunctions&&r.serializeFunctions,this.ignoreUndefined="boolean"==typeof r.ignoreUndefined&&r.ignoreUndefined,this.maxBsonSize=r.maxBsonSize||16777216,this.checkKeys="boolean"!=typeof r.checkKeys||r.checkKeys,this.batchSize=this.numberToReturn,this.tailable=!1,this.slaveOk="boolean"==typeof r.slaveOk&&r.slaveOk,this.oplogReplay=!1,this.noCursorTimeout=!1,this.awaitData=!1,this.exhaust=!1,this.partial=!1};a.prototype.incRequestId=function(){this.requestId=i++},a.nextRequestId=function(){return i+1},a.prototype.toBin=function(){var e=[],t=null,n=0;this.tailable&&(n|=2),this.slaveOk&&(n|=4),this.oplogReplay&&(n|=8),this.noCursorTimeout&&(n|=16),this.awaitData&&(n|=32),this.exhaust&&(n|=64),this.partial&&(n|=128),this.batchSize!==this.numberToReturn&&(this.numberToReturn=this.batchSize);var r=o.alloc(20+o.byteLength(this.ns)+1+4+4);e.push(r);var i=this.bson.serialize(this.query,{checkKeys:this.checkKeys,serializeFunctions:this.serializeFunctions,ignoreUndefined:this.ignoreUndefined});e.push(i),this.returnFieldSelector&&Object.keys(this.returnFieldSelector).length>0&&(t=this.bson.serialize(this.returnFieldSelector,{checkKeys:this.checkKeys,serializeFunctions:this.serializeFunctions,ignoreUndefined:this.ignoreUndefined}),e.push(t));var a=r.length+i.length+(t?t.length:0),c=4;return r[3]=a>>24&255,r[2]=a>>16&255,r[1]=a>>8&255,r[0]=255&a,r[c+3]=this.requestId>>24&255,r[c+2]=this.requestId>>16&255,r[c+1]=this.requestId>>8&255,r[c]=255&this.requestId,r[(c+=4)+3]=0,r[c+2]=0,r[c+1]=0,r[c]=0,r[(c+=4)+3]=s.OP_QUERY>>24&255,r[c+2]=s.OP_QUERY>>16&255,r[c+1]=s.OP_QUERY>>8&255,r[c]=255&s.OP_QUERY,r[(c+=4)+3]=n>>24&255,r[c+2]=n>>16&255,r[c+1]=n>>8&255,r[c]=255&n,c=(c+=4)+r.write(this.ns,c,"utf8")+1,r[c-1]=0,r[c+3]=this.numberToSkip>>24&255,r[c+2]=this.numberToSkip>>16&255,r[c+1]=this.numberToSkip>>8&255,r[c]=255&this.numberToSkip,r[(c+=4)+3]=this.numberToReturn>>24&255,r[c+2]=this.numberToReturn>>16&255,r[c+1]=this.numberToReturn>>8&255,r[c]=255&this.numberToReturn,c+=4,e},a.getRequestId=function(){return++i};var c=function(e,t,n,r){r=r||{},this.numberToReturn=r.numberToReturn||0,this.requestId=i++,this.bson=e,this.ns=t,this.cursorId=n};c.prototype.toBin=function(){var e=4+o.byteLength(this.ns)+1+4+8+16,t=0,n=o.alloc(e);return n[t+3]=e>>24&255,n[t+2]=e>>16&255,n[t+1]=e>>8&255,n[t]=255&e,n[(t+=4)+3]=this.requestId>>24&255,n[t+2]=this.requestId>>16&255,n[t+1]=this.requestId>>8&255,n[t]=255&this.requestId,n[(t+=4)+3]=0,n[t+2]=0,n[t+1]=0,n[t]=0,n[(t+=4)+3]=s.OP_GETMORE>>24&255,n[t+2]=s.OP_GETMORE>>16&255,n[t+1]=s.OP_GETMORE>>8&255,n[t]=255&s.OP_GETMORE,n[(t+=4)+3]=0,n[t+2]=0,n[t+1]=0,n[t]=0,t=(t+=4)+n.write(this.ns,t,"utf8")+1,n[t-1]=0,n[t+3]=this.numberToReturn>>24&255,n[t+2]=this.numberToReturn>>16&255,n[t+1]=this.numberToReturn>>8&255,n[t]=255&this.numberToReturn,n[(t+=4)+3]=this.cursorId.getLowBits()>>24&255,n[t+2]=this.cursorId.getLowBits()>>16&255,n[t+1]=this.cursorId.getLowBits()>>8&255,n[t]=255&this.cursorId.getLowBits(),n[(t+=4)+3]=this.cursorId.getHighBits()>>24&255,n[t+2]=this.cursorId.getHighBits()>>16&255,n[t+1]=this.cursorId.getHighBits()>>8&255,n[t]=255&this.cursorId.getHighBits(),t+=4,n};var u=function(e,t,n){this.ns=t,this.requestId=i++,this.cursorIds=n};u.prototype.toBin=function(){var e=24+8*this.cursorIds.length,t=0,n=o.alloc(e);n[t+3]=e>>24&255,n[t+2]=e>>16&255,n[t+1]=e>>8&255,n[t]=255&e,n[(t+=4)+3]=this.requestId>>24&255,n[t+2]=this.requestId>>16&255,n[t+1]=this.requestId>>8&255,n[t]=255&this.requestId,n[(t+=4)+3]=0,n[t+2]=0,n[t+1]=0,n[t]=0,n[(t+=4)+3]=s.OP_KILL_CURSORS>>24&255,n[t+2]=s.OP_KILL_CURSORS>>16&255,n[t+1]=s.OP_KILL_CURSORS>>8&255,n[t]=255&s.OP_KILL_CURSORS,n[(t+=4)+3]=0,n[t+2]=0,n[t+1]=0,n[t]=0,n[(t+=4)+3]=this.cursorIds.length>>24&255,n[t+2]=this.cursorIds.length>>16&255,n[t+1]=this.cursorIds.length>>8&255,n[t]=255&this.cursorIds.length,t+=4;for(var r=0;r<this.cursorIds.length;r++)n[t+3]=this.cursorIds[r].getLowBits()>>24&255,n[t+2]=this.cursorIds[r].getLowBits()>>16&255,n[t+1]=this.cursorIds[r].getLowBits()>>8&255,n[t]=255&this.cursorIds[r].getLowBits(),n[(t+=4)+3]=this.cursorIds[r].getHighBits()>>24&255,n[t+2]=this.cursorIds[r].getHighBits()>>16&255,n[t+1]=this.cursorIds[r].getHighBits()>>8&255,n[t]=255&this.cursorIds[r].getHighBits(),t+=4;return n};var l=function(e,t,n,o,i){i=i||{promoteLongs:!0,promoteValues:!0,promoteBuffers:!1},this.parsed=!1,this.raw=t,this.data=o,this.bson=e,this.opts=i,this.length=n.length,this.requestId=n.requestId,this.responseTo=n.responseTo,this.opCode=n.opCode,this.fromCompressed=n.fromCompressed,this.responseFlags=o.readInt32LE(0),this.cursorId=new r(o.readInt32LE(4),o.readInt32LE(8)),this.startingFrom=o.readInt32LE(12),this.numberReturned=o.readInt32LE(16),this.documents=new Array(this.numberReturned),this.cursorNotFound=0!=(1&this.responseFlags),this.queryFailure=0!=(2&this.responseFlags),this.shardConfigStale=0!=(4&this.responseFlags),this.awaitCapable=0!=(8&this.responseFlags),this.promoteLongs="boolean"!=typeof i.promoteLongs||i.promoteLongs,this.promoteValues="boolean"!=typeof i.promoteValues||i.promoteValues,this.promoteBuffers="boolean"==typeof i.promoteBuffers&&i.promoteBuffers};l.prototype.isParsed=function(){return this.parsed},l.prototype.parse=function(e){if(!this.parsed){var t,n,r=(e=e||{}).raw||!1,o=e.documentsReturnedIn||null;n={promoteLongs:"boolean"==typeof e.promoteLongs?e.promoteLongs:this.opts.promoteLongs,promoteValues:"boolean"==typeof e.promoteValues?e.promoteValues:this.opts.promoteValues,promoteBuffers:"boolean"==typeof e.promoteBuffers?e.promoteBuffers:this.opts.promoteBuffers},this.index=20;for(var i=0;i<this.numberReturned;i++)t=this.data[this.index]|this.data[this.index+1]<<8|this.data[this.index+2]<<16|this.data[this.index+3]<<24,this.documents[i]=r?this.data.slice(this.index,this.index+t):this.bson.deserialize(this.data.slice(this.index,this.index+t),n),this.index=this.index+t;if(1===this.documents.length&&null!=o&&r){const e={};e[o]=!0,n.fieldsAsRaw=e;const t=this.bson.deserialize(this.documents[0],n);this.documents=[t]}this.parsed=!0}},e.exports={Query:a,GetMore:c,Response:l,KillCursor:u}},function(e,t,n){var r=n(131),o=r.Buffer;function i(e,t){for(var n in e)t[n]=e[n]}function s(e,t,n){return o(e,t,n)}o.from&&o.alloc&&o.allocUnsafe&&o.allocUnsafeSlow?e.exports=r:(i(r,t),t.Buffer=s),s.prototype=Object.create(o.prototype),i(o,s),s.from=function(e,t,n){if("number"==typeof e)throw new TypeError("Argument must not be a number");return o(e,t,n)},s.alloc=function(e,t,n){if("number"!=typeof e)throw new TypeError("Argument must be a number");var r=o(e);return void 0!==t?"string"==typeof n?r.fill(t,n):r.fill(t):r.fill(0),r},s.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return o(e)},s.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return r.SlowBuffer(e)}},function(e,t,n){"use strict";const r=n(1).Aspect,o=n(1).OperationBase,i=n(0).applyWriteConcern,s=n(0).debugOptions,a=n(0).handleCallback,c=n(2).MongoError,u=n(2).ReadPreference,l=n(0).MongoDBNamespace,f=["authSource","w","wtimeout","j","native_parser","forceServerObjectId","serializeFunctions","raw","promoteLongs","promoteValues","promoteBuffers","bufferMaxEntries","numberOfRetries","retryMiliSeconds","readPreference","pkFactory","parentDb","promiseLibrary","noListener"];e.exports=class extends o{constructor(e,t,n,o){super(t),this.hasAspect(r.WRITE_OPERATION)?(i(this.options,null!=n?{db:e,coll:n}:{db:e},this.options),this.options.readPreference=u.primary):this.options.readPreference=null!=n?u.resolve(n,t):u.resolve(e,t),this.db=e,null!=o&&(this.command=o),null!=n&&(this.collection=n)}_buildCommand(){if(null!=this.command)return this.command}execute(e){const t=this.db,n=Object.assign({},this.options);if(t.serverConfig&&t.serverConfig.isDestroyed())return e(new c("topology was destroyed"));let o;try{o=this._buildCommand()}catch(t){return e(t)}const i=n.dbName||n.authdb||t.databaseName;this.hasAspect(r.WRITE_OPERATION)&&(!n.writeConcern||n.session&&n.session.inTransaction()||(o.writeConcern=n.writeConcern)),t.s.logger.isDebug()&&t.s.logger.debug(`executing command ${JSON.stringify(o)} against ${i}.$cmd with options [${JSON.stringify(s(f,n))}]`);const u=null!=this.namespace?this.namespace:new l(i,"$cmd");t.s.topology.command(u,o,n,(t,r)=>t?a(e,t):n.full?a(e,null,r):void a(e,null,r.result))}}},function(e,t,n){(function(e){var r;
|
|
1
|
+
module.exports=function(e){var t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)n.d(r,o,function(t){return e[t]}.bind(null,o));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=228)}([function(e,t,n){"use strict";const r=n(3).MongoError,o=n(29);var i=t.formatSortValue=function(e){switch((""+e).toLowerCase()){case"ascending":case"asc":case"1":return 1;case"descending":case"desc":case"-1":return-1;default:throw new Error("Illegal sort clause, must be of the form [['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]")}},s=t.formattedOrderClause=function(e){var t={};if(null==e)return null;if(Array.isArray(e)){if(0===e.length)return null;for(var n=0;n<e.length;n++)e[n].constructor===String?t[e[n]]=1:t[e[n][0]]=i(e[n][1])}else if(null!=e&&"object"==typeof e)t=e;else{if("string"!=typeof e)throw new Error("Illegal sort clause, must be of the form [['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]");t[e]=1}return t},a=t.isObject=function(e){return"[object Object]"===Object.prototype.toString.call(e)};const c=["w","j","wtimeout","fsync","writeConcern"];const u=+process.version.split(".")[0].substring(1),l=process.emitWarning?e=>u<=6?process.emitWarning(e,"DeprecationWarning",m):process.emitWarning(e,{type:"DeprecationWarning",code:m}):e=>console.error(e);function f(e,t){return`${e} option [${t}] is deprecated and will be removed in a later version.`}const p={};try{n(188),p.ASYNC_ITERATOR=!0}catch(e){p.ASYNC_ITERATOR=!1}class d{constructor(e,t){this.db=e,this.collection=t}toString(){return this.collection?`${this.db}.${this.collection}`:this.db}withCollection(e){return new d(this.db,e)}static fromString(e){if(!e)throw new Error(`Cannot parse namespace from "${e}"`);const t=e.indexOf(".");return new d(e.substring(0,t),e.substring(t+1))}}function h(){const e=process.hrtime();return Math.floor(1e3*e[0]+e[1]/1e6)}const m="MONGODB DRIVER";function g(e){return process.emitWarning?u<=6?process.emitWarning(e,void 0,m):process.emitWarning(e,{code:m}):console.error(`[${m}] Warning:`,e)}const y=new Set;e.exports={filterOptions:function(e,t){var n={};for(var r in e)-1!==t.indexOf(r)&&(n[r]=e[r]);return n},mergeOptions:function(e,t){for(var n in t)e[n]=t[n];return e},translateOptions:function(e,t){var n={sslCA:"ca",sslCRL:"crl",sslValidate:"rejectUnauthorized",sslKey:"key",sslCert:"cert",sslPass:"passphrase",socketTimeoutMS:"socketTimeout",connectTimeoutMS:"connectionTimeout",replicaSet:"setName",rs_name:"setName",secondaryAcceptableLatencyMS:"acceptableLatency",connectWithNoPrimary:"secondaryOnlyConnectionAllowed",acceptableLatencyMS:"localThresholdMS"};for(var r in t)n[r]?e[n[r]]=t[r]:e[r]=t[r];return e},shallowClone:function(e){var t={};for(var n in e)t[n]=e[n];return t},getSingleProperty:function(e,t,n){Object.defineProperty(e,t,{enumerable:!0,get:function(){return n}})},checkCollectionName:function(e){if("string"!=typeof e)throw new r("collection name must be a String");if(!e||-1!==e.indexOf(".."))throw new r("collection names cannot be empty");if(-1!==e.indexOf("$")&&null==e.match(/((^\$cmd)|(oplog\.\$main))/))throw new r("collection names must not contain '$'");if(null!=e.match(/^\.|\.$/))throw new r("collection names must not start or end with '.'");if(-1!==e.indexOf("\0"))throw new r("collection names cannot contain a null character")},toError:function(e){if(e instanceof Error)return e;for(var t=e.err||e.errmsg||e.errMessage||e,n=r.create({message:t,driver:!0}),o="object"==typeof e?Object.keys(e):[],i=0;i<o.length;i++)try{n[o[i]]=e[o[i]]}catch(e){}return n},formattedOrderClause:s,parseIndexOptions:function(e){var t,n={},r=[];return"string"==typeof e?(r.push(e+"_1"),n[e]=1):Array.isArray(e)?e.forEach((function(e){"string"==typeof e?(r.push(e+"_1"),n[e]=1):Array.isArray(e)?(r.push(e[0]+"_"+(e[1]||1)),n[e[0]]=e[1]||1):a(e)&&(t=Object.keys(e)).forEach((function(t){r.push(t+"_"+e[t]),n[t]=e[t]}))})):a(e)&&(t=Object.keys(e)).forEach((function(t){r.push(t+"_"+e[t]),n[t]=e[t]})),{name:r.join("_"),keys:t,fieldHash:n}},normalizeHintField:function(e){var t=null;if("string"==typeof e)t=e;else if(Array.isArray(e))t={},e.forEach((function(e){t[e]=1}));else if(null!=e&&"object"==typeof e)for(var n in t={},e)t[n]=e[n];return t},handleCallback:function(e,t,n,r){try{if(null==e)return;if(e)return r?e(t,n,r):e(t,n)}catch(t){return process.nextTick((function(){throw t})),!1}return!0},decorateCommand:function(e,t,n){for(var r in t)-1===n.indexOf(r)&&(e[r]=t[r]);return e},isObject:a,debugOptions:function(e,t){var n={};return e.forEach((function(e){n[e]=t[e]})),n},MAX_JS_INT:Number.MAX_SAFE_INTEGER+1,conditionallyMergeWriteConcern:function(e,t){let n=!1;for(const t of c)if(t in e){n=!0;break}if(!n)for(const n of c)t[n]&&("writeConcern"in e||(e.writeConcern={}),e.writeConcern[n]=t[n]);return e},executeLegacyOperation:(e,t,n,o)=>{if(null==e)throw new TypeError("This method requires a valid topology instance");if(!Array.isArray(n))throw new TypeError("This method requires an array of arguments to apply");o=o||{};const i=e.s.promiseLibrary;let s,a,c,u=n[n.length-1];if(!o.skipSessions&&e.hasSessionSupport())if(a=n[n.length-2],null==a||null==a.session){c=Symbol(),s=e.startSession({owner:c});const t=n.length-2;n[t]=Object.assign({},n[t],{session:s})}else if(a.session&&a.session.hasEnded)throw new r("Use of expired sessions is not permitted");const l=(e,t)=>function(n,r){if(s&&s.owner===c&&!o.returnsCursor)s.endSession(()=>{if(delete a.session,n)return t(n);e(r)});else{if(n)return t(n);e(r)}};if("function"==typeof u){u=n.pop();const e=l(e=>u(null,e),e=>u(e,null));n.push(e);try{return t.apply(null,n)}catch(t){throw e(t),t}}if(null!=n[n.length-1])throw new TypeError("final argument to `executeLegacyOperation` must be a callback");return new i((function(e,r){const o=l(e,r);n[n.length-1]=o;try{return t.apply(null,n)}catch(e){o(e)}}))},applyRetryableWrites:function(e,t){return t&&t.s.options.retryWrites&&(e.retryWrites=!0),e},applyWriteConcern:function(e,t,n){n=n||{};const r=t.db,i=t.collection;if(n.session&&n.session.inTransaction())return e.writeConcern&&delete e.writeConcern,e;const s=o.fromOptions(n);return s?Object.assign(e,{writeConcern:s}):i&&i.writeConcern?Object.assign(e,{writeConcern:Object.assign({},i.writeConcern)}):r&&r.writeConcern?Object.assign(e,{writeConcern:Object.assign({},r.writeConcern)}):e},isPromiseLike:function(e){return e&&"function"==typeof e.then},decorateWithCollation:function(e,t,n){const o=t.s&&t.s.topology||t.topology;if(!o)throw new TypeError('parameter "target" is missing a topology');const i=o.capabilities();if(n.collation&&"object"==typeof n.collation){if(!i||!i.commandsTakeCollation)throw new r("Current topology does not support collation");e.collation=n.collation}},decorateWithReadConcern:function(e,t,n){if(n&&n.session&&n.session.inTransaction())return;let r=Object.assign({},e.readConcern||{});t.s.readConcern&&Object.assign(r,t.s.readConcern),Object.keys(r).length>0&&Object.assign(e,{readConcern:r})},decorateWithExplain:function(e,t){return e.explain?e:{explain:e,verbosity:t.verbosity}},deprecateOptions:function(e,t){if(!0===process.noDeprecation)return t;const n=e.msgHandler?e.msgHandler:f,r=new Set;function o(){const o=arguments[e.optionsIndex];return a(o)&&0!==Object.keys(o).length?(e.deprecatedOptions.forEach(t=>{if(Object.prototype.hasOwnProperty.call(o,t)&&!r.has(t)){r.add(t);const o=n(e.name,t);if(l(o),this&&this.getLogger){const e=this.getLogger();e&&e.warn(o)}}}),t.apply(this,arguments)):t.apply(this,arguments)}return Object.setPrototypeOf(o,t),t.prototype&&(o.prototype=t.prototype),o},SUPPORTS:p,MongoDBNamespace:d,emitDeprecationWarning:l,makeCounter:function*(e){let t=e||0;for(;;){const e=t;t+=1,yield e}},maybePromise:function(e,t,n){const r=e&&e.s&&e.s.promiseLibrary||Promise;let o;return"function"!=typeof t&&(o=new r((e,n)=>{t=(t,r)=>{if(t)return n(t);e(r)}})),n((function(e,n){if(null==e)t(e,n);else try{t(e)}catch(e){return process.nextTick(()=>{throw e})}})),o},now:h,calculateDurationInMs:function(e){if("number"!=typeof e)throw TypeError("numeric value required to calculate duration");const t=h()-e;return t<0?0:t},makeInterruptableAsyncInterval:function(e,t){let n,r,o,i=!1;const s=(t=t||{}).interval||1e3,a=t.minInterval||500,c="boolean"==typeof t.immediate&&t.immediate,u="function"==typeof t.clock?t.clock:h;function l(e){i||(clearTimeout(n),n=setTimeout(f,e||s))}function f(){o=0,r=u(),e(e=>{if(e)throw e;l(s)})}return c?f():(r=u(),l()),{wake:function(){const e=u(),t=e-o,n=s-(e-r);o=e,t<a||(n>a&&l(a),n<0&&f())},stop:function(){i=!0,n&&(clearTimeout(n),n=null),r=0,o=0}}},hasAtomicOperators:function e(t){return Array.isArray(t)?t.reduce((t,n)=>t||e(n),null):Object.keys("function"!=typeof t.toBSON?t:t.toBSON()).map(e=>e[0]).indexOf("$")>=0},MONGODB_WARNING_CODE:m,emitWarning:g,emitWarningOnce:function(e){if(!y.has(e))return y.add(e),g(e)}}},function(e,t,n){"use strict";const r=n(91).Explain,o=n(3).MongoError,i={READ_OPERATION:Symbol("READ_OPERATION"),WRITE_OPERATION:Symbol("WRITE_OPERATION"),RETRYABLE:Symbol("RETRYABLE"),EXECUTE_WITH_SELECTION:Symbol("EXECUTE_WITH_SELECTION"),NO_INHERIT_OPTIONS:Symbol("NO_INHERIT_OPTIONS"),EXPLAINABLE:Symbol("EXPLAINABLE")};e.exports={Aspect:i,defineAspects:function(e,t){return Array.isArray(t)||t instanceof Set||(t=[t]),t=new Set(t),Object.defineProperty(e,"aspects",{value:t,writable:!1}),t},OperationBase:class{constructor(e){if(this.options=Object.assign({},e),this.hasAspect(i.EXPLAINABLE))this.explain=r.fromOptions(e);else if(void 0!==this.options.explain)throw new o("explain is not supported on this command")}hasAspect(e){return null!=this.constructor.aspects&&this.constructor.aspects.has(e)}set session(e){Object.assign(this.options,{session:e})}get session(){return this.options.session}clearSession(){delete this.options.session}get canRetryRead(){return!0}execute(){throw new TypeError("`execute` must be implemented for OperationBase subclasses")}}}},function(e,t,n){"use strict";let r=n(185);const o=n(132)(n(186)),i=n(4).retrieveEJSON();try{const e=o("bson-ext");e&&(r=e)}catch(e){}e.exports={MongoError:n(3).MongoError,MongoNetworkError:n(3).MongoNetworkError,MongoParseError:n(3).MongoParseError,MongoTimeoutError:n(3).MongoTimeoutError,MongoServerSelectionError:n(3).MongoServerSelectionError,MongoWriteConcernError:n(3).MongoWriteConcernError,Connection:n(187),Server:n(134),ReplSet:n(428),Mongos:n(430),Logger:n(16),Cursor:n(17).CoreCursor,ReadPreference:n(10),Sessions:n(34),BSON:r,EJSON:i,Topology:n(431).Topology,Query:n(21).Query,MongoCredentials:n(198).MongoCredentials,defaultAuthProviders:n(193).defaultAuthProviders,MongoCR:n(194),X509:n(195),Plain:n(196),GSSAPI:n(197),ScramSHA1:n(88).ScramSHA1,ScramSHA256:n(88).ScramSHA256,parseConnectionString:n(446)}},function(e,t,n){"use strict";const r=Symbol("errorLabels");class o extends Error{constructor(e){if(e instanceof Error)super(e.message),this.stack=e.stack;else{if("string"==typeof e)super(e);else for(var t in super(e.message||e.errmsg||e.$err||"n/a"),e.errorLabels&&(this[r]=new Set(e.errorLabels)),e)"errorLabels"!==t&&"errmsg"!==t&&(this[t]=e[t]);Error.captureStackTrace(this,this.constructor)}this.name="MongoError"}get errmsg(){return this.message}static create(e){return new o(e)}hasErrorLabel(e){return null!=this[r]&&this[r].has(e)}addErrorLabel(e){null==this[r]&&(this[r]=new Set),this[r].add(e)}get errorLabels(){return this[r]?Array.from(this[r]):[]}}const i=Symbol("beforeHandshake");class s extends o{constructor(e,t){super(e),this.name="MongoNetworkError",t&&!0===t.beforeHandshake&&(this[i]=!0)}}class a extends o{constructor(e){super(e),this.name="MongoParseError"}}class c extends o{constructor(e,t){t&&t.error?super(t.error.message||t.error):super(e),this.name="MongoTimeoutError",t&&(this.reason=t)}}class u extends o{constructor(e,t){super(e),this.name="MongoWriteConcernError",t&&Array.isArray(t.errorLabels)&&(this[r]=new Set(t.errorLabels)),null!=t&&(this.result=function(e){const t=Object.assign({},e);return 0===t.ok&&(t.ok=1,delete t.errmsg,delete t.code,delete t.codeName),t}(t))}}const l=new Set([6,7,89,91,189,9001,10107,11600,11602,13435,13436]),f=new Set([11600,11602,10107,13435,13436,189,91,7,6,89,9001,262]);const p=new Set([91,189,11600,11602,13436]),d=new Set([10107,13435]),h=new Set([11600,91]);function m(e){return!(!e.code||!p.has(e.code))||(e.message.match(/not master or secondary/)||e.message.match(/node is recovering/))}e.exports={MongoError:o,MongoNetworkError:s,MongoNetworkTimeoutError:class extends s{constructor(e,t){super(e,t),this.name="MongoNetworkTimeoutError"}},MongoParseError:a,MongoTimeoutError:c,MongoServerSelectionError:class extends c{constructor(e,t){super(e,t),this.name="MongoServerSelectionError"}},MongoWriteConcernError:u,isRetryableError:function(e){return l.has(e.code)||e instanceof s||e.message.match(/not master/)||e.message.match(/node is recovering/)},isSDAMUnrecoverableError:function(e){return e instanceof a||null==e||!!(m(e)||(t=e,t.code&&d.has(t.code)||!m(t)&&t.message.match(/not master/)));var t},isNodeShuttingDownError:function(e){return e.code&&h.has(e.code)},isRetryableWriteError:function(e){return e instanceof u?f.has(e.code)||f.has(e.result.code):f.has(e.code)},isNetworkErrorBeforeHandshake:function(e){return!0===e[i]}}},function(e,t,n){"use strict";const r=n(410),o=n(20),i=n(132)(n(186));const s=function(){throw new Error("The `mongodb-extjson` module was not found. Please install it and try again.")};function a(e){if(e){if(e.ismaster)return e.ismaster.maxWireVersion;if("function"==typeof e.lastIsMaster){const t=e.lastIsMaster();if(t)return t.maxWireVersion}if(e.description)return e.description.maxWireVersion}return 0}e.exports={uuidV4:()=>{const e=o.randomBytes(16);return e[6]=15&e[6]|64,e[8]=63&e[8]|128,e},relayEvents:function(e,t,n){n.forEach(n=>e.on(n,e=>t.emit(n,e)))},collationNotSupported:function(e,t){return t&&t.collation&&a(e)<5},retrieveEJSON:function(){let e=i("mongodb-extjson");return e||(e={parse:s,deserialize:s,serialize:s,stringify:s,setBSONModule:s,BSON:s}),e},retrieveKerberos:function(){let e;try{e=i("kerberos")}catch(e){if("MODULE_NOT_FOUND"===e.code)throw new Error("The `kerberos` module was not found. Please install it and try again.");throw e}return e},maxWireVersion:a,isPromiseLike:function(e){return e&&"function"==typeof e.then},eachAsync:function(e,t,n){e=e||[];let r=0,o=0;for(r=0;r<e.length;++r)o++,t(e[r],i);function i(t){o--,t?n(t):r===e.length&&o<=0&&n()}0!==o||n()},eachAsyncSeries:function(e,t,n){let r=0,o=(e=e||[]).length;0!==o?t(e[r],(function i(s){r++,o--,s?n(s):r===e.length&&o<=0?n():t(e[r],i)})):n()},isUnifiedTopology:function(e){return null!=e.description},arrayStrictEqual:function(e,t){return!(!Array.isArray(e)||!Array.isArray(t))&&(e.length===t.length&&e.every((e,n)=>e===t[n]))},tagsStrictEqual:function(e,t){const n=Object.keys(e),r=Object.keys(t);return n.length===r.length&&n.every(n=>t[n]===e[n])},errorStrictEqual:function(e,t){return e===t||!(null==e&&null!=t||null!=e&&null==t)&&(e.constructor.name===t.constructor.name&&e.message===t.message)},makeStateMachine:function(e){return function(t,n){const r=e[t.s.state];if(r&&r.indexOf(n)<0)throw new TypeError(`illegal state transition from [${t.s.state}] => [${n}], allowed: [${r}]`);t.emit("stateChanged",t.s.state,n),t.s.state=n}},makeClientMetadata:function(e){e=e||{};const t={driver:{name:"nodejs",version:n(411).version},os:{type:r.type(),name:process.platform,architecture:process.arch,version:r.release()},platform:`'Node.js ${process.version}, ${r.endianness} (${e.useUnifiedTopology?"unified":"legacy"})`};if(e.driverInfo&&(e.driverInfo.name&&(t.driver.name=`${t.driver.name}|${e.driverInfo.name}`),e.driverInfo.version&&(t.version=`${t.driver.version}|${e.driverInfo.version}`),e.driverInfo.platform&&(t.platform=`${t.platform}|${e.driverInfo.platform}`)),e.appname){const n=Buffer.from(e.appname);t.application={name:n.length>128?n.slice(0,128).toString("utf8"):e.appname}}return t},noop:()=>{}}},function(e,t){e.exports=require("util")},function(e,t,n){"use strict";const r=n(10),o=n(3).MongoError,i=n(13).ServerType,s=n(189).TopologyDescription;e.exports={getReadPreference:function(e,t){var n=e.readPreference||new r("primary");if(t.readPreference&&(n=t.readPreference),"string"==typeof n&&(n=new r(n)),!(n instanceof r))throw new o("read preference must be a ReadPreference instance");return n},MESSAGE_HEADER_SIZE:16,COMPRESSION_DETAILS_SIZE:9,opcodes:{OP_REPLY:1,OP_UPDATE:2001,OP_INSERT:2002,OP_QUERY:2004,OP_GETMORE:2005,OP_DELETE:2006,OP_KILL_CURSORS:2007,OP_COMPRESSED:2012,OP_MSG:2013},parseHeader:function(e){return{length:e.readInt32LE(0),requestId:e.readInt32LE(4),responseTo:e.readInt32LE(8),opCode:e.readInt32LE(12)}},applyCommonQueryOptions:function(e,t){return Object.assign(e,{raw:"boolean"==typeof t.raw&&t.raw,promoteLongs:"boolean"!=typeof t.promoteLongs||t.promoteLongs,promoteValues:"boolean"!=typeof t.promoteValues||t.promoteValues,promoteBuffers:"boolean"==typeof t.promoteBuffers&&t.promoteBuffers,monitoring:"boolean"==typeof t.monitoring&&t.monitoring,fullResult:"boolean"==typeof t.fullResult&&t.fullResult}),"number"==typeof t.socketTimeout&&(e.socketTimeout=t.socketTimeout),t.session&&(e.session=t.session),"string"==typeof t.documentsReturnedIn&&(e.documentsReturnedIn=t.documentsReturnedIn),e},isSharded:function(e){if("mongos"===e.type)return!0;if(e.description&&e.description.type===i.Mongos)return!0;if(e.description&&e.description instanceof s){return Array.from(e.description.servers.values()).some(e=>e.type===i.Mongos)}return!1},databaseNamespace:function(e){return e.split(".")[0]},collectionNamespace:function(e){return e.split(".").slice(1).join(".")}}},function(e,t,n){"use strict";const r=n(10),o=n(13).TopologyType,i=n(3).MongoError,s=n(3).isRetryableWriteError,a=n(4).maxWireVersion,c=n(3).MongoNetworkError;function u(e,t,n){e.listeners(t).length>0&&e.emit(t,n)}var l=function(e){return e.s.serverDescription||(e.s.serverDescription={address:e.name,arbiters:[],hosts:[],passives:[],type:"Unknown"}),e.s.serverDescription},f=function(e,t){e.listeners("serverDescriptionChanged").length>0&&(e.emit("serverDescriptionChanged",{topologyId:-1!==e.s.topologyId?e.s.topologyId:e.id,address:e.name,previousDescription:l(e),newDescription:t}),e.s.serverDescription=t)},p=function(e){return e.s.topologyDescription||(e.s.topologyDescription={topologyType:"Unknown",servers:[{address:e.name,arbiters:[],hosts:[],passives:[],type:"Unknown"}]}),e.s.topologyDescription},d=function(e,t){return t||(t=e.ismaster),t?t.ismaster&&"isdbgrid"===t.msg?"Mongos":t.ismaster&&!t.hosts?"Standalone":t.ismaster?"RSPrimary":t.secondary?"RSSecondary":t.arbiterOnly?"RSArbiter":"Unknown":"Unknown"},h=function(e){return function(t){if("destroyed"!==e.s.state){var n=(new Date).getTime();u(e,"serverHeartbeatStarted",{connectionId:e.name}),e.command("admin.$cmd",{ismaster:!0},{monitoring:!0},(function(r,o){if(r)u(e,"serverHeartbeatFailed",{durationMS:i,failure:r,connectionId:e.name});else{e.emit("ismaster",o,e);var i=(new Date).getTime()-n;u(e,"serverHeartbeatSucceeded",{durationMS:i,reply:o.result,connectionId:e.name}),function(e,t,n){var r=d(e,t);return d(e,n)!==r}(e,e.s.ismaster,o.result)&&f(e,{address:e.name,arbiters:[],hosts:[],passives:[],type:e.s.inTopology?d(e):"Standalone"}),e.s.ismaster=o.result,e.s.isMasterLatencyMS=i}if("function"==typeof t)return t(r,o);e.s.inquireServerStateTimeout=setTimeout(h(e),e.s.haInterval)}))}}};const m={endSessions:function(e,t){Array.isArray(e)||(e=[e]),this.command("admin.$cmd",{endSessions:e},{readPreference:r.primaryPreferred},()=>{"function"==typeof t&&t()})}};function g(e){return e.description?e.description.type:"mongos"===e.type?o.Sharded:"replset"===e.type?o.ReplicaSetWithPrimary:o.Single}const y=function(e){return!(e.lastIsMaster().maxWireVersion<6)&&(!!e.logicalSessionTimeoutMinutes&&g(e)!==o.Single)},b="This MongoDB deployment does not support retryable writes. Please add retryWrites=false to your connection string.";e.exports={SessionMixins:m,resolveClusterTime:function(e,t){null==e.clusterTime?e.clusterTime=t:t.clusterTime.greaterThan(e.clusterTime.clusterTime)&&(e.clusterTime=t)},inquireServerState:h,getTopologyType:d,emitServerDescriptionChanged:f,emitTopologyDescriptionChanged:function(e,t){e.listeners("topologyDescriptionChanged").length>0&&(e.emit("topologyDescriptionChanged",{topologyId:-1!==e.s.topologyId?e.s.topologyId:e.id,address:e.name,previousDescription:p(e),newDescription:t}),e.s.serverDescription=t)},cloneOptions:function(e){var t={};for(var n in e)t[n]=e[n];return t},createCompressionInfo:function(e){return e.compression&&e.compression.compressors?(e.compression.compressors.forEach((function(e){if("snappy"!==e&&"zlib"!==e)throw new Error("compressors must be at least one of snappy or zlib")})),e.compression.compressors):[]},clone:function(e){return JSON.parse(JSON.stringify(e))},diff:function(e,t){var n={servers:[]};e||(e={servers:[]});for(var r=0;r<e.servers.length;r++){for(var o=!1,i=0;i<t.servers.length;i++)if(t.servers[i].address.toLowerCase()===e.servers[r].address.toLowerCase()){o=!0;break}o||n.servers.push({address:e.servers[r].address,from:e.servers[r].type,to:"Unknown"})}for(i=0;i<t.servers.length;i++){for(o=!1,r=0;r<e.servers.length;r++)if(e.servers[r].address.toLowerCase()===t.servers[i].address.toLowerCase()){o=!0;break}o||n.servers.push({address:t.servers[i].address,from:"Unknown",to:t.servers[i].type})}for(r=0;r<e.servers.length;r++){var s=e.servers[r];for(i=0;i<t.servers.length;i++){var a=t.servers[i];s.address.toLowerCase()===a.address.toLowerCase()&&s.type!==a.type&&n.servers.push({address:s.address,from:s.type,to:a.type})}}return n},Interval:function(e,t){var n=!1;this.start=function(){return this.isRunning()||(n=setInterval(e,t)),this},this.stop=function(){return clearInterval(n),n=!1,this},this.isRunning=function(){return!1!==n}},Timeout:function(e,t){var n=!1,r=()=>{n&&(clearTimeout(n),n=!1,e())};this.start=function(){return this.isRunning()||(n=setTimeout(r,t)),this},this.stop=function(){return clearTimeout(n),n=!1,this},this.isRunning=function(){return!1!==n}},isRetryableWritesSupported:y,getMMAPError:function(e){return 20===e.code&&e.errmsg.includes("Transaction numbers")?new i({message:b,errmsg:b,originalError:e}):e},topologyType:g,legacyIsRetryableWriteError:function(e,t){return e instanceof i&&(y(t)&&(e instanceof c||a(t)<9&&s(e))&&e.addErrorLabel("RetryableWriteError"),e.hasErrorLabel("RetryableWriteError"))}}},function(e,t){e.exports=require("events")},function(e,t,n){"use strict";const r=n(132)(n(412));function o(){throw new Error("Attempted to use Snappy compression, but Snappy is not installed. Install or disable Snappy compression and try again.")}e.exports={debugOptions:function(e,t){const n={};return e.forEach((function(e){n[e]=t[e]})),n},retrieveBSON:function(){const e=n(185);e.native=!1;const t=r("bson-ext");return t?(t.native=!0,t):e},retrieveSnappy:function(){let e=r("snappy");return e||(e={compress:o,uncompress:o,compressSync:o,uncompressSync:o}),e}}},function(e,t,n){"use strict";const r=n(0).emitWarningOnce,o=function(e,t,n){if(!o.isValid(e))throw new TypeError(`Invalid read preference mode ${e}`);if(t&&!Array.isArray(t)){r("ReadPreference tags must be an array, this will change in the next major version");const e=void 0!==t.maxStalenessSeconds,o=void 0!==t.hedge;e||o?(n=t,t=void 0):t=[t]}if(this.mode=e,this.tags=t,this.hedge=n&&n.hedge,null!=(n=n||{}).maxStalenessSeconds){if(n.maxStalenessSeconds<=0)throw new TypeError("maxStalenessSeconds must be a positive integer");this.maxStalenessSeconds=n.maxStalenessSeconds,this.minWireVersion=5}if(this.mode===o.PRIMARY){if(this.tags&&Array.isArray(this.tags)&&this.tags.length>0)throw new TypeError("Primary read preference cannot be combined with tags");if(this.maxStalenessSeconds)throw new TypeError("Primary read preference cannot be combined with maxStalenessSeconds");if(this.hedge)throw new TypeError("Primary read preference cannot be combined with hedge")}};Object.defineProperty(o.prototype,"preference",{enumerable:!0,get:function(){return this.mode}}),o.PRIMARY="primary",o.PRIMARY_PREFERRED="primaryPreferred",o.SECONDARY="secondary",o.SECONDARY_PREFERRED="secondaryPreferred",o.NEAREST="nearest";const i=[o.PRIMARY,o.PRIMARY_PREFERRED,o.SECONDARY,o.SECONDARY_PREFERRED,o.NEAREST,null];o.fromOptions=function(e){if(!e)return null;const t=e.readPreference;if(!t)return null;const n=e.readPreferenceTags,r=e.maxStalenessSeconds;if("string"==typeof t)return new o(t,n);if(!(t instanceof o)&&"object"==typeof t){const e=t.mode||t.preference;if(e&&"string"==typeof e)return new o(e,t.tags,{maxStalenessSeconds:t.maxStalenessSeconds||r,hedge:t.hedge})}return t},o.resolve=function(e,t){const n=(t=t||{}).session,r=e&&e.readPreference;let i;return i=t.readPreference?o.fromOptions(t):n&&n.inTransaction()&&n.transaction.options.readPreference?n.transaction.options.readPreference:null!=r?r:o.primary,"string"==typeof i?new o(i):i},o.translate=function(e){if(null==e.readPreference)return e;const t=e.readPreference;if("string"==typeof t)e.readPreference=new o(t);else if(!t||t instanceof o||"object"!=typeof t){if(!(t instanceof o))throw new TypeError("Invalid read preference: "+t)}else{const n=t.mode||t.preference;n&&"string"==typeof n&&(e.readPreference=new o(n,t.tags,{maxStalenessSeconds:t.maxStalenessSeconds}))}return e},o.isValid=function(e){return-1!==i.indexOf(e)},o.prototype.isValid=function(e){return o.isValid("string"==typeof e?e:this.mode)};const s=["primaryPreferred","secondary","secondaryPreferred","nearest"];o.prototype.slaveOk=function(){return-1!==s.indexOf(this.mode)},o.prototype.equals=function(e){return e.mode===this.mode},o.prototype.toJSON=function(){const e={mode:this.mode};return Array.isArray(this.tags)&&(e.tags=this.tags),this.maxStalenessSeconds&&(e.maxStalenessSeconds=this.maxStalenessSeconds),this.hedge&&(e.hedge=this.hedge),e},o.primary=new o("primary"),o.primaryPreferred=new o("primaryPreferred"),o.secondary=new o("secondary"),o.secondaryPreferred=new o("secondaryPreferred"),o.nearest=new o("nearest"),e.exports=o},function(e,t,n){"use strict";const r=n(0).applyWriteConcern,o=n(2).BSON.Code,i=n(0).debugOptions,s=n(0).handleCallback,a=n(2).MongoError,c=n(0).parseIndexOptions,u=n(2).ReadPreference,l=n(0).toError,f=n(140),p=n(0).MongoDBNamespace,d=["authSource","w","wtimeout","j","native_parser","forceServerObjectId","serializeFunctions","raw","promoteLongs","promoteValues","promoteBuffers","bufferMaxEntries","numberOfRetries","retryMiliSeconds","readPreference","pkFactory","parentDb","promiseLibrary","noListener"];function h(e,t,n,o,i){let p=Object.assign({},{readPreference:u.PRIMARY},o);if(p=r(p,{db:e},o),p.writeConcern&&"function"!=typeof i)throw a.create({message:"Cannot use a writeConcern without a provided callback",driver:!0});if(e.serverConfig&&e.serverConfig.isDestroyed())return i(new a("topology was destroyed"));!function(e,t,n,o,i){const f=c(n),p="string"==typeof o.name?o.name:f.name,d=[{name:p,key:f.fieldHash}],h=Object.keys(d[0]).concat(["writeConcern","w","wtimeout","j","fsync","readPreference","session"]);for(let e in o)-1===h.indexOf(e)&&(d[0][e]=o[e]);const g=e.s.topology.capabilities();if(d[0].collation&&g&&!g.commandsTakeCollation){const e=new a("server/primary/mongos does not support collation");return e.code=67,i(e)}const y=r({createIndexes:t,indexes:d},{db:e},o);o.readPreference=u.PRIMARY,m(e,y,o,(e,t)=>e?s(i,e,null):0===t.ok?s(i,l(t),null):void s(i,null,p))}(e,t,n,p,(r,c)=>{if(null==r)return s(i,r,c);if(67===r.code||11e3===r.code||85===r.code||86===r.code||11600===r.code||197===r.code)return s(i,r,c);const u=y(e,t,n,o);p.checkKeys=!1,e.s.topology.insert(e.s.namespace.withCollection(f.SYSTEM_INDEX_COLLECTION),u,p,(e,t)=>{if(null!=i)return e?s(i,e):null==t?s(i,null,null):t.result.writeErrors?s(i,a.create(t.result.writeErrors[0]),null):void s(i,null,u.name)})})}function m(e,t,n,r){if(e.serverConfig&&e.serverConfig.isDestroyed())return r(new a("topology was destroyed"));const o=n.dbName||n.authdb||e.databaseName;n.readPreference=u.resolve(e,n),e.s.logger.isDebug()&&e.s.logger.debug(`executing command ${JSON.stringify(t)} against ${o}.$cmd with options [${JSON.stringify(i(d,n))}]`),e.s.topology.command(e.s.namespace.withCollection("$cmd"),t,n,(e,t)=>e?s(r,e):n.full?s(r,null,t):void s(r,null,t.result))}function g(e,t,n,r){const o=null!=n.full&&n.full;if(e.serverConfig&&e.serverConfig.isDestroyed())return r(new a("topology was destroyed"));e.collection(t).listIndexes(n).toArray((e,t)=>e?r(l(e)):Array.isArray(t)?o?s(r,null,t):void s(r,null,function(e){let t={};for(let n=0;n<e.length;n++){const r=e[n];t[r.name]=[];for(let e in r.key)t[r.name].push([e,r.key[e]])}return t}(t)):s(r,null,[]))}function y(e,t,n,r){const o=c(n),i=o.fieldHash,s="string"==typeof r.name?r.name:o.name,a={ns:e.s.namespace.withCollection(t).toString(),key:i,name:s},u=null!=r&&"object"!=typeof r&&r;r=null==r||"boolean"==typeof r?{}:r;const l=Object.keys(a);for(let e in r)-1===l.indexOf(e)&&(a[e]=r[e]);null==a.unique&&(a.unique=u);const f=["w","wtimeout","j","fsync","readPreference","session"];for(let e=0;e<f.length;e++)delete a[f[e]];return a}e.exports={createListener:function(e,t,n){return function(r){if(n.listeners(t).length>0){n.emit(t,r,e);for(let n=0;n<e.s.children.length;n++)e.s.children[n].emit(t,r,e.s.children[n])}}},createIndex:h,ensureIndex:function(e,t,n,o,i){const c=r({},{db:e},o),l=y(e,t,n,o).name;if(e.serverConfig&&e.serverConfig.isDestroyed())return i(new a("topology was destroyed"));c.readPreference=u.PRIMARY,g(e,t,c,(r,a)=>{if(null!=r&&26!==r.code)return s(i,r,null);if(null!=a&&a[l]){if("function"==typeof i)return s(i,null,l)}else h(e,t,n,o,i)})},evaluate:function(e,t,n,r,i){let c=t,l=[];if(e.serverConfig&&e.serverConfig.isDestroyed())return i(new a("topology was destroyed"));c&&"Code"===c._bsontype||(c=new o(c)),null==n||Array.isArray(n)||"function"==typeof n?null!=n&&Array.isArray(n)&&"function"!=typeof n&&(l=n):l=[n];let f={$eval:c,args:l};r.nolock&&(f.nolock=r.nolock),r.readPreference=new u(u.PRIMARY),m(e,f,r,(e,t)=>e?s(i,e,null):t&&1===t.ok?s(i,null,t.retval):t?s(i,a.create({message:`eval failed: ${t.errmsg}`,driver:!0}),null):void s(i,e,t))},executeCommand:m,executeDbAdminCommand:function(e,t,n,r){const o=new p("admin","$cmd");e.s.topology.command(o,t,n,(t,n)=>e.serverConfig&&e.serverConfig.isDestroyed()?r(new a("topology was destroyed")):t?s(r,t):void s(r,null,n.result))},indexInformation:g,profilingInfo:function(e,t,n){try{e.collection("system.profile").find({},t).toArray(n)}catch(e){return n(e,null)}},validateDatabaseName:function(e){if("string"!=typeof e)throw a.create({message:"database name must be a string",driver:!0});if(0===e.length)throw a.create({message:"database name cannot be the empty string",driver:!0});if("$external"===e)return;const t=[" ",".","$","/","\\"];for(let n=0;n<t.length;n++)if(-1!==e.indexOf(t[n]))throw a.create({message:"database names cannot contain the character '"+t[n]+"'",driver:!0})}}},function(e,t){var n=Array.isArray;e.exports=n},function(e,t,n){"use strict";const r={Single:"Single",ReplicaSetNoPrimary:"ReplicaSetNoPrimary",ReplicaSetWithPrimary:"ReplicaSetWithPrimary",Sharded:"Sharded",Unknown:"Unknown"};e.exports={STATE_CLOSING:"closing",STATE_CLOSED:"closed",STATE_CONNECTING:"connecting",STATE_CONNECTED:"connected",TOPOLOGY_DEFAULTS:{useUnifiedTopology:!0,localThresholdMS:15,serverSelectionTimeoutMS:3e4,heartbeatFrequencyMS:1e4,minHeartbeatFrequencyMS:500},TopologyType:r,ServerType:{Standalone:"Standalone",Mongos:"Mongos",PossiblePrimary:"PossiblePrimary",RSPrimary:"RSPrimary",RSSecondary:"RSSecondary",RSArbiter:"RSArbiter",RSOther:"RSOther",RSGhost:"RSGhost",Unknown:"Unknown"},serverType:function(e){let t=e.s.description||e.s.serverDescription;return t.topologyType===r.Single?t.servers[0].type:t.type},drainTimerQueue:function(e){e.forEach(clearTimeout),e.clear()},clearAndRemoveTimerFrom:function(e,t){return clearTimeout(e),t.delete(e)}}},function(e,t,n){"use strict";const r=n(0).applyRetryableWrites,o=n(0).applyWriteConcern,i=n(0).decorateWithCollation,s=n(0).decorateWithReadConcern,a=n(11).executeCommand,c=n(0).formattedOrderClause,u=n(0).handleCallback,l=n(2).MongoError,f=n(2).ReadPreference,p=n(0).toError,d=n(17).CursorState,h=n(4).maxWireVersion;function m(e,t,n){const r="boolean"==typeof n.forceServerObjectId?n.forceServerObjectId:e.s.db.options.forceServerObjectId;return!0===r?t:t.map(t=>(!0!==r&&null==t._id&&(t._id=e.s.pkFactory.createPk()),t))}e.exports={buildCountCommand:function(e,t,n){const r=n.skip,o=n.limit;let a=n.hint;const c=n.maxTimeMS;t=t||{};const u={count:n.collectionName,query:t};return e.s.numberOfRetries?(e.options.hint?a=e.options.hint:e.cmd.hint&&(a=e.cmd.hint),i(u,e,e.cmd)):i(u,e,n),"number"==typeof r&&(u.skip=r),"number"==typeof o&&(u.limit=o),"number"==typeof c&&(u.maxTimeMS=c),a&&(u.hint=a),s(u,e),u},findAndModify:function(e,t,n,s,l,p){const d={findAndModify:e.collectionName,query:t};(n=c(n))&&(d.sort=n),d.new=!!l.new,d.remove=!!l.remove,d.upsert=!!l.upsert;const h=l.projection||l.fields;h&&(d.fields=h),l.arrayFilters&&(d.arrayFilters=l.arrayFilters,delete l.arrayFilters),s&&!l.remove&&(d.update=s),l.maxTimeMS&&(d.maxTimeMS=l.maxTimeMS),l.serializeFunctions=l.serializeFunctions||e.s.serializeFunctions,l.checkKeys=!1;let m=Object.assign({},l);m=r(m,e.s.db),m=o(m,{db:e.s.db,collection:e},l),m.writeConcern&&(d.writeConcern=m.writeConcern),!0===m.bypassDocumentValidation&&(d.bypassDocumentValidation=m.bypassDocumentValidation),m.readPreference=f.primary;try{i(d,e,m)}catch(e){return p(e,null)}a(e.s.db,d,m,(e,t)=>e?u(p,e,null):u(p,null,t))},indexInformation:function(e,t,n,r){const o=null!=n.full&&n.full;if(e.serverConfig&&e.serverConfig.isDestroyed())return r(new l("topology was destroyed"));e.collection(t).listIndexes(n).toArray((e,t)=>e?r(p(e)):Array.isArray(t)?o?u(r,null,t):void u(r,null,function(e){let t={};for(let n=0;n<e.length;n++){const r=e[n];t[r.name]=[];for(let e in r.key)t[r.name].push([e,r.key[e]])}return t}(t)):u(r,null,[]))},nextObject:function(e,t){if(e.s.state===d.CLOSED||e.isDead&&e.isDead())return u(t,l.create({message:"Cursor is closed",driver:!0}));if(e.s.state===d.INIT&&e.cmd&&e.cmd.sort)try{e.cmd.sort=c(e.cmd.sort)}catch(e){return u(t,e)}e._next((n,r)=>{if(e.s.state=d.OPEN,n)return u(t,n);u(t,null,r)})},prepareDocs:m,insertDocuments:function(e,t,n,i){"function"==typeof n&&(i=n,n={}),n=n||{},t=Array.isArray(t)?t:[t];let s=Object.assign({},n);s=r(s,e.s.db),s=o(s,{db:e.s.db,collection:e},n),!0===s.keepGoing&&(s.ordered=!1),s.serializeFunctions=n.serializeFunctions||e.s.serializeFunctions,t=m(e,t,n),e.s.topology.insert(e.s.namespace,t,s,(e,n)=>{if(null!=i){if(e)return u(i,e);if(null==n)return u(i,null,null);if(n.result.code)return u(i,p(n.result));if(n.result.writeErrors)return u(i,p(n.result.writeErrors[0]));n.ops=t,u(i,null,n)}})},removeDocuments:function(e,t,n,s){"function"==typeof n?(s=n,n={}):"function"==typeof t&&(s=t,n={},t={}),n=n||{};let a=Object.assign({},n);a=r(a,e.s.db),a=o(a,{db:e.s.db,collection:e},n),null==t&&(t={});const c={q:t,limit:0};n.single?c.limit=1:a.retryWrites&&(a.retryWrites=!1),n.hint&&(c.hint=n.hint);try{i(a,e,n)}catch(e){return s(e,null)}if(void 0!==n.explain&&h(e.s.topology)<3)return s?s(new l("server does not support explain on remove")):void 0;e.s.topology.remove(e.s.namespace,[c],a,(e,t)=>{if(null!=s)return e?u(s,e,null):null==t?u(s,null,null):t.result.code?u(s,p(t.result)):t.result.writeErrors?u(s,p(t.result.writeErrors[0])):void u(s,null,t)})},updateDocuments:function(e,t,n,s,a){if("function"==typeof s&&(a=s,s=null),null==s&&(s={}),"function"!=typeof a&&(a=null),null==t||"object"!=typeof t)return a(p("selector must be a valid JavaScript object"));if(null==n||"object"!=typeof n)return a(p("document must be a valid JavaScript object"));let c=Object.assign({},s);c=r(c,e.s.db),c=o(c,{db:e.s.db,collection:e},s),c.serializeFunctions=s.serializeFunctions||e.s.serializeFunctions;const f={q:t,u:n};f.upsert=void 0!==s.upsert&&!!s.upsert,f.multi=void 0!==s.multi&&!!s.multi,s.hint&&(f.hint=s.hint),c.arrayFilters&&(f.arrayFilters=c.arrayFilters,delete c.arrayFilters),c.retryWrites&&f.multi&&(c.retryWrites=!1);try{i(c,e,s)}catch(e){return a(e,null)}if(void 0!==s.explain&&h(e.s.topology)<3)return a?a(new l("server does not support explain on update")):void 0;e.s.topology.update(e.s.namespace,[f],c,(e,t)=>{if(null!=a)return e?u(a,e,null):null==t?u(a,null,null):t.result.code?u(a,p(t.result)):t.result.writeErrors?u(a,p(t.result.writeErrors[0])):void u(a,null,t)})}}},function(e,t){e.exports=function(e){return null!=e&&"object"==typeof e}},function(e,t,n){"use strict";var r=n(5).format,o=n(3).MongoError,i={},s={},a=null,c=process.pid,u=null,l=function(e,t){if(!(this instanceof l))return new l(e,t);t=t||{},this.className=e,t.logger?u=t.logger:null==u&&(u=console.log),t.loggerLevel&&(a=t.loggerLevel||"error"),null==s[this.className]&&(i[this.className]=!0)};l.prototype.debug=function(e,t){if(this.isDebug()&&(Object.keys(s).length>0&&s[this.className]||0===Object.keys(s).length&&i[this.className])){var n=(new Date).getTime(),o=r("[%s-%s:%s] %s %s","DEBUG",this.className,c,n,e),a={type:"debug",message:e,className:this.className,pid:c,date:n};t&&(a.meta=t),u(o,a)}},l.prototype.warn=function(e,t){if(this.isWarn()&&(Object.keys(s).length>0&&s[this.className]||0===Object.keys(s).length&&i[this.className])){var n=(new Date).getTime(),o=r("[%s-%s:%s] %s %s","WARN",this.className,c,n,e),a={type:"warn",message:e,className:this.className,pid:c,date:n};t&&(a.meta=t),u(o,a)}},l.prototype.info=function(e,t){if(this.isInfo()&&(Object.keys(s).length>0&&s[this.className]||0===Object.keys(s).length&&i[this.className])){var n=(new Date).getTime(),o=r("[%s-%s:%s] %s %s","INFO",this.className,c,n,e),a={type:"info",message:e,className:this.className,pid:c,date:n};t&&(a.meta=t),u(o,a)}},l.prototype.error=function(e,t){if(this.isError()&&(Object.keys(s).length>0&&s[this.className]||0===Object.keys(s).length&&i[this.className])){var n=(new Date).getTime(),o=r("[%s-%s:%s] %s %s","ERROR",this.className,c,n,e),a={type:"error",message:e,className:this.className,pid:c,date:n};t&&(a.meta=t),u(o,a)}},l.prototype.isInfo=function(){return"info"===a||"debug"===a},l.prototype.isError=function(){return"error"===a||"info"===a||"debug"===a},l.prototype.isWarn=function(){return"error"===a||"warn"===a||"info"===a||"debug"===a},l.prototype.isDebug=function(){return"debug"===a},l.reset=function(){a="error",s={}},l.currentLogger=function(){return u},l.setCurrentLogger=function(e){if("function"!=typeof e)throw new o("current logger must be a function");u=e},l.filter=function(e,t){"class"===e&&Array.isArray(t)&&(s={},t.forEach((function(e){s[e]=!0})))},l.setLevel=function(e){if("info"!==e&&"error"!==e&&"debug"!==e&&"warn"!==e)throw new Error(r("%s is an illegal logging level",e));a=e},e.exports=l},function(e,t,n){"use strict";const r=n(16),o=n(9).retrieveBSON,i=n(3).MongoError,s=n(3).MongoNetworkError,a=n(4).collationNotSupported,c=n(10),u=n(4).isUnifiedTopology,l=n(56),f=n(18).Readable,p=n(0).SUPPORTS,d=n(0).MongoDBNamespace,h=n(0).mergeOptions,m=n(1).OperationBase,g=o().Long,y={INIT:0,OPEN:1,CLOSED:2,GET_MORE:3};function b(e,t,n){try{e(t,n)}catch(t){process.nextTick((function(){throw t}))}}class v extends f{constructor(e,t,n,o){super({objectMode:!0}),o=o||{},t instanceof m&&(this.operation=t,t=this.operation.ns.toString(),o=this.operation.options,n=this.operation.cmd?this.operation.cmd:{}),this.pool=null,this.server=null,this.disconnectHandler=o.disconnectHandler,this.bson=e.s.bson,this.ns=t,this.namespace=d.fromString(t),this.cmd=n,this.options=o,this.topology=e,this.cursorState={cursorId:null,cmd:n,documents:o.documents||[],cursorIndex:0,dead:!1,killed:!1,init:!1,notified:!1,limit:o.limit||n.limit||0,skip:o.skip||n.skip||0,batchSize:o.batchSize||n.batchSize||1e3,currentLimit:0,transforms:o.transforms,raw:o.raw||n&&n.raw},"object"==typeof o.session&&(this.cursorState.session=o.session);const i=e.s.options;"boolean"==typeof i.promoteLongs?this.cursorState.promoteLongs=i.promoteLongs:"boolean"==typeof o.promoteLongs&&(this.cursorState.promoteLongs=o.promoteLongs),"boolean"==typeof i.promoteValues?this.cursorState.promoteValues=i.promoteValues:"boolean"==typeof o.promoteValues&&(this.cursorState.promoteValues=o.promoteValues),"boolean"==typeof i.promoteBuffers?this.cursorState.promoteBuffers=i.promoteBuffers:"boolean"==typeof o.promoteBuffers&&(this.cursorState.promoteBuffers=o.promoteBuffers),i.reconnect&&(this.cursorState.reconnect=i.reconnect),this.logger=r("Cursor",i),"number"==typeof n?(this.cursorState.cursorId=g.fromNumber(n),this.cursorState.lastCursorId=this.cursorState.cursorId):n instanceof g&&(this.cursorState.cursorId=n,this.cursorState.lastCursorId=n),this.operation&&(this.operation.cursorState=this.cursorState)}setCursorBatchSize(e){this.cursorState.batchSize=e}cursorBatchSize(){return this.cursorState.batchSize}setCursorLimit(e){this.cursorState.limit=e}cursorLimit(){return this.cursorState.limit}setCursorSkip(e){this.cursorState.skip=e}cursorSkip(){return this.cursorState.skip}_next(e){!function e(t,n){if(t.cursorState.notified)return n(new Error("cursor is exhausted"));if(function(e,t){if(e.cursorState.killed)return w(e,t),!0;return!1}(t,n))return;if(function(e,t){if(e.cursorState.dead&&!e.cursorState.killed)return e.cursorState.killed=!0,w(e,t),!0;return!1}(t,n))return;if(function(e,t){if(e.cursorState.dead&&e.cursorState.killed)return b(t,new i("cursor is dead")),!0;return!1}(t,n))return;if(!t.cursorState.init){if(!t.topology.isConnected(t.options)){if("server"===t.topology._type&&!t.topology.s.options.reconnect)return n(new i("no connection available"));if(null!=t.disconnectHandler)return t.topology.isDestroyed()?n(new i("Topology was destroyed")):void t.disconnectHandler.addObjectAndMethod("cursor",t,"next",[n],n)}return void t._initializeCursor((r,o)=>{r||null===o?n(r,o):e(t,n)})}if(t.cursorState.limit>0&&t.cursorState.currentLimit>=t.cursorState.limit)t.kill(()=>S(t,n));else if(t.cursorState.cursorIndex!==t.cursorState.documents.length||g.ZERO.equals(t.cursorState.cursorId)){if(t.cursorState.documents.length===t.cursorState.cursorIndex&&t.cmd.tailable&&g.ZERO.equals(t.cursorState.cursorId))return b(n,new i({message:"No more documents in tailed cursor",tailable:t.cmd.tailable,awaitData:t.cmd.awaitData}));if(t.cursorState.documents.length===t.cursorState.cursorIndex&&g.ZERO.equals(t.cursorState.cursorId))S(t,n);else{if(t.cursorState.limit>0&&t.cursorState.currentLimit>=t.cursorState.limit)return void t.kill(()=>S(t,n));t.cursorState.currentLimit+=1;let e=t.cursorState.documents[t.cursorState.cursorIndex++];if(!e||e.$err)return void t.kill(()=>S(t,(function(){b(n,new i(e?e.$err:void 0))})));t.cursorState.transforms&&"function"==typeof t.cursorState.transforms.doc&&(e=t.cursorState.transforms.doc(e)),b(n,null,e)}}else{if(t.cursorState.documents=[],t.cursorState.cursorIndex=0,t.topology.isDestroyed())return n(new s("connection destroyed, not possible to instantiate cursor"));if(function(e,t){if(e.pool&&e.pool.isDestroyed()){e.cursorState.killed=!0;const n=new s(`connection to host ${e.pool.host}:${e.pool.port} was destroyed`);return _(e,()=>t(n)),!0}return!1}(t,n))return;t._getMore((function(r,o,s){return r?b(n,r):(t.connection=s,0===t.cursorState.documents.length&&t.cmd.tailable&&g.ZERO.equals(t.cursorState.cursorId)?b(n,new i({message:"No more documents in tailed cursor",tailable:t.cmd.tailable,awaitData:t.cmd.awaitData})):0===t.cursorState.documents.length&&t.cmd.tailable&&!g.ZERO.equals(t.cursorState.cursorId)?e(t,n):t.cursorState.limit>0&&t.cursorState.currentLimit>=t.cursorState.limit?S(t,n):void e(t,n))}))}}(this,e)}clone(){const e=h({},this.options);return delete e.session,this.topology.cursor(this.ns,this.cmd,e)}isDead(){return!0===this.cursorState.dead}isKilled(){return!0===this.cursorState.killed}isNotified(){return!0===this.cursorState.notified}bufferedCount(){return this.cursorState.documents.length-this.cursorState.cursorIndex}readBufferedDocuments(e){const t=this.cursorState.documents.length-this.cursorState.cursorIndex,n=e<t?e:t;let r=this.cursorState.documents.slice(this.cursorState.cursorIndex,this.cursorState.cursorIndex+n);if(this.cursorState.transforms&&"function"==typeof this.cursorState.transforms.doc)for(let e=0;e<r.length;e++)r[e]=this.cursorState.transforms.doc(r[e]);return this.cursorState.limit>0&&this.cursorState.currentLimit+r.length>this.cursorState.limit&&(r=r.slice(0,this.cursorState.limit-this.cursorState.currentLimit),this.kill()),this.cursorState.currentLimit=this.cursorState.currentLimit+r.length,this.cursorState.cursorIndex=this.cursorState.cursorIndex+r.length,r}kill(e){this.cursorState.dead=!0,this.cursorState.killed=!0,this.cursorState.documents=[],null==this.cursorState.cursorId||this.cursorState.cursorId.isZero()||!1===this.cursorState.init?e&&e(null,null):this.server.killCursors(this.ns,this.cursorState,e)}rewind(){this.cursorState.init&&(this.cursorState.dead||this.kill(),this.cursorState.currentLimit=0,this.cursorState.init=!1,this.cursorState.dead=!1,this.cursorState.killed=!1,this.cursorState.notified=!1,this.cursorState.documents=[],this.cursorState.cursorId=null,this.cursorState.cursorIndex=0)}_read(){if(this.s&&this.s.state===y.CLOSED||this.isDead())return this.push(null);this._next((e,t)=>e?(this.listeners("error")&&this.listeners("error").length>0&&this.emit("error",e),this.isDead()||this.close(),this.emit("end"),this.emit("finish")):this.cursorState.streamOptions&&"function"==typeof this.cursorState.streamOptions.transform&&null!=t?this.push(this.cursorState.streamOptions.transform(t)):(this.push(t),void(null===t&&this.isDead()&&this.once("end",()=>{this.close(),this.emit("finish")}))))}_endSession(e,t){"function"==typeof e&&(t=e,e={}),e=e||{};const n=this.cursorState.session;return n&&(e.force||n.owner===this)?(this.cursorState.session=void 0,this.operation&&this.operation.clearSession(),n.endSession(t),!0):(t&&t(),!1)}_getMore(e){this.logger.isDebug()&&this.logger.debug(`schedule getMore call for query [${JSON.stringify(this.query)}]`);let t=this.cursorState.batchSize;this.cursorState.limit>0&&this.cursorState.currentLimit+t>this.cursorState.limit&&(t=this.cursorState.limit-this.cursorState.currentLimit);const n=this.cursorState;this.server.getMore(this.ns,n,t,this.options,(t,r,o)=>{(t||n.cursorId&&n.cursorId.isZero())&&this._endSession(),e(t,r,o)})}_initializeCursor(e){const t=this;if(u(t.topology)&&t.topology.shouldCheckForSessionSupport())return void t.topology.selectServer(c.primaryPreferred,t=>{t?e(t):this._initializeCursor(e)});function n(n,r){const o=t.cursorState;if((n||o.cursorId&&o.cursorId.isZero())&&t._endSession(),0===o.documents.length&&o.cursorId&&o.cursorId.isZero()&&!t.cmd.tailable&&!t.cmd.awaitData)return w(t,e);e(n,r)}const r=(e,r)=>{if(e)return n(e);const o=r.message;if(Array.isArray(o.documents)&&1===o.documents.length){const e=o.documents[0];if(o.queryFailure)return n(new i(e),null);if(!t.cmd.find||t.cmd.find&&!1===t.cmd.virtual){if(e.$err||e.errmsg)return n(new i(e),null);if(null!=e.cursor&&"string"!=typeof e.cursor){const r=e.cursor.id;return e.cursor.ns&&(t.ns=e.cursor.ns),t.cursorState.cursorId="number"==typeof r?g.fromNumber(r):r,t.cursorState.lastCursorId=t.cursorState.cursorId,t.cursorState.operationTime=e.operationTime,Array.isArray(e.cursor.firstBatch)&&(t.cursorState.documents=e.cursor.firstBatch),n(null,o)}}}const s=o.cursorId||0;t.cursorState.cursorId=s instanceof g?s:g.fromNumber(s),t.cursorState.documents=o.documents,t.cursorState.lastCursorId=o.cursorId,t.cursorState.transforms&&"function"==typeof t.cursorState.transforms.query&&(t.cursorState.documents=t.cursorState.transforms.query(o)),n(null,o)};if(t.operation)return t.logger.isDebug()&&t.logger.debug(`issue initial query [${JSON.stringify(t.cmd)}] with flags [${JSON.stringify(t.query)}]`),void l(t.topology,t.operation,(e,o)=>{if(e)n(e);else{if(t.server=t.operation.server,t.cursorState.init=!0,null!=t.cursorState.cursorId)return n();r(e,o)}});const o={};return t.cursorState.session&&(o.session=t.cursorState.session),t.operation?o.readPreference=t.operation.readPreference:t.options.readPreference&&(o.readPreference=t.options.readPreference),t.topology.selectServer(o,(o,s)=>{if(o){const n=t.disconnectHandler;return null!=n?n.addObjectAndMethod("cursor",t,"next",[e],e):e(o)}if(t.server=s,t.cursorState.init=!0,a(t.server,t.cmd))return e(new i(`server ${t.server.name} does not support collation`));if(null!=t.cursorState.cursorId)return n();if(t.logger.isDebug()&&t.logger.debug(`issue initial query [${JSON.stringify(t.cmd)}] with flags [${JSON.stringify(t.query)}]`),null!=t.cmd.find)return void s.query(t.ns,t.cmd,t.cursorState,t.options,r);const c=Object.assign({session:t.cursorState.session},t.options);s.command(t.ns,t.cmd,c,r)})}}function S(e,t){e.cursorState.dead=!0,w(e,t)}function w(e,t){_(e,()=>b(t,null,null))}function _(e,t){if(e.cursorState.notified=!0,e.cursorState.documents=[],e.cursorState.cursorIndex=0,!e.cursorState.session)return t();e._endSession(t)}p.ASYNC_ITERATOR&&(v.prototype[Symbol.asyncIterator]=n(188).asyncIterator),e.exports={CursorState:y,CoreCursor:v}},function(e,t){e.exports=require("stream")},function(e,t,n){var r=n(149),o="object"==typeof self&&self&&self.Object===Object&&self,i=r||o||Function("return this")();e.exports=i},function(e,t){e.exports=require("crypto")},function(e,t,n){"use strict";var r=(0,n(9).retrieveBSON)().Long;const o=n(22).Buffer;var i=0,s=n(6).opcodes,a=function(e,t,n,r){if(null==t)throw new Error("ns must be specified for query");if(null==n)throw new Error("query must be specified for query");if(-1!==t.indexOf("\0"))throw new Error("namespace cannot contain a null character");this.bson=e,this.ns=t,this.query=n,this.numberToSkip=r.numberToSkip||0,this.numberToReturn=r.numberToReturn||0,this.returnFieldSelector=r.returnFieldSelector||null,this.requestId=a.getRequestId(),this.pre32Limit=r.pre32Limit,this.serializeFunctions="boolean"==typeof r.serializeFunctions&&r.serializeFunctions,this.ignoreUndefined="boolean"==typeof r.ignoreUndefined&&r.ignoreUndefined,this.maxBsonSize=r.maxBsonSize||16777216,this.checkKeys="boolean"!=typeof r.checkKeys||r.checkKeys,this.batchSize=this.numberToReturn,this.tailable=!1,this.slaveOk="boolean"==typeof r.slaveOk&&r.slaveOk,this.oplogReplay=!1,this.noCursorTimeout=!1,this.awaitData=!1,this.exhaust=!1,this.partial=!1};a.prototype.incRequestId=function(){this.requestId=i++},a.nextRequestId=function(){return i+1},a.prototype.toBin=function(){var e=[],t=null,n=0;this.tailable&&(n|=2),this.slaveOk&&(n|=4),this.oplogReplay&&(n|=8),this.noCursorTimeout&&(n|=16),this.awaitData&&(n|=32),this.exhaust&&(n|=64),this.partial&&(n|=128),this.batchSize!==this.numberToReturn&&(this.numberToReturn=this.batchSize);var r=o.alloc(20+o.byteLength(this.ns)+1+4+4);e.push(r);var i=this.bson.serialize(this.query,{checkKeys:this.checkKeys,serializeFunctions:this.serializeFunctions,ignoreUndefined:this.ignoreUndefined});e.push(i),this.returnFieldSelector&&Object.keys(this.returnFieldSelector).length>0&&(t=this.bson.serialize(this.returnFieldSelector,{checkKeys:this.checkKeys,serializeFunctions:this.serializeFunctions,ignoreUndefined:this.ignoreUndefined}),e.push(t));var a=r.length+i.length+(t?t.length:0),c=4;return r[3]=a>>24&255,r[2]=a>>16&255,r[1]=a>>8&255,r[0]=255&a,r[c+3]=this.requestId>>24&255,r[c+2]=this.requestId>>16&255,r[c+1]=this.requestId>>8&255,r[c]=255&this.requestId,r[(c+=4)+3]=0,r[c+2]=0,r[c+1]=0,r[c]=0,r[(c+=4)+3]=s.OP_QUERY>>24&255,r[c+2]=s.OP_QUERY>>16&255,r[c+1]=s.OP_QUERY>>8&255,r[c]=255&s.OP_QUERY,r[(c+=4)+3]=n>>24&255,r[c+2]=n>>16&255,r[c+1]=n>>8&255,r[c]=255&n,c=(c+=4)+r.write(this.ns,c,"utf8")+1,r[c-1]=0,r[c+3]=this.numberToSkip>>24&255,r[c+2]=this.numberToSkip>>16&255,r[c+1]=this.numberToSkip>>8&255,r[c]=255&this.numberToSkip,r[(c+=4)+3]=this.numberToReturn>>24&255,r[c+2]=this.numberToReturn>>16&255,r[c+1]=this.numberToReturn>>8&255,r[c]=255&this.numberToReturn,c+=4,e},a.getRequestId=function(){return++i};var c=function(e,t,n,r){r=r||{},this.numberToReturn=r.numberToReturn||0,this.requestId=i++,this.bson=e,this.ns=t,this.cursorId=n};c.prototype.toBin=function(){var e=4+o.byteLength(this.ns)+1+4+8+16,t=0,n=o.alloc(e);return n[t+3]=e>>24&255,n[t+2]=e>>16&255,n[t+1]=e>>8&255,n[t]=255&e,n[(t+=4)+3]=this.requestId>>24&255,n[t+2]=this.requestId>>16&255,n[t+1]=this.requestId>>8&255,n[t]=255&this.requestId,n[(t+=4)+3]=0,n[t+2]=0,n[t+1]=0,n[t]=0,n[(t+=4)+3]=s.OP_GETMORE>>24&255,n[t+2]=s.OP_GETMORE>>16&255,n[t+1]=s.OP_GETMORE>>8&255,n[t]=255&s.OP_GETMORE,n[(t+=4)+3]=0,n[t+2]=0,n[t+1]=0,n[t]=0,t=(t+=4)+n.write(this.ns,t,"utf8")+1,n[t-1]=0,n[t+3]=this.numberToReturn>>24&255,n[t+2]=this.numberToReturn>>16&255,n[t+1]=this.numberToReturn>>8&255,n[t]=255&this.numberToReturn,n[(t+=4)+3]=this.cursorId.getLowBits()>>24&255,n[t+2]=this.cursorId.getLowBits()>>16&255,n[t+1]=this.cursorId.getLowBits()>>8&255,n[t]=255&this.cursorId.getLowBits(),n[(t+=4)+3]=this.cursorId.getHighBits()>>24&255,n[t+2]=this.cursorId.getHighBits()>>16&255,n[t+1]=this.cursorId.getHighBits()>>8&255,n[t]=255&this.cursorId.getHighBits(),t+=4,n};var u=function(e,t,n){this.ns=t,this.requestId=i++,this.cursorIds=n};u.prototype.toBin=function(){var e=24+8*this.cursorIds.length,t=0,n=o.alloc(e);n[t+3]=e>>24&255,n[t+2]=e>>16&255,n[t+1]=e>>8&255,n[t]=255&e,n[(t+=4)+3]=this.requestId>>24&255,n[t+2]=this.requestId>>16&255,n[t+1]=this.requestId>>8&255,n[t]=255&this.requestId,n[(t+=4)+3]=0,n[t+2]=0,n[t+1]=0,n[t]=0,n[(t+=4)+3]=s.OP_KILL_CURSORS>>24&255,n[t+2]=s.OP_KILL_CURSORS>>16&255,n[t+1]=s.OP_KILL_CURSORS>>8&255,n[t]=255&s.OP_KILL_CURSORS,n[(t+=4)+3]=0,n[t+2]=0,n[t+1]=0,n[t]=0,n[(t+=4)+3]=this.cursorIds.length>>24&255,n[t+2]=this.cursorIds.length>>16&255,n[t+1]=this.cursorIds.length>>8&255,n[t]=255&this.cursorIds.length,t+=4;for(var r=0;r<this.cursorIds.length;r++)n[t+3]=this.cursorIds[r].getLowBits()>>24&255,n[t+2]=this.cursorIds[r].getLowBits()>>16&255,n[t+1]=this.cursorIds[r].getLowBits()>>8&255,n[t]=255&this.cursorIds[r].getLowBits(),n[(t+=4)+3]=this.cursorIds[r].getHighBits()>>24&255,n[t+2]=this.cursorIds[r].getHighBits()>>16&255,n[t+1]=this.cursorIds[r].getHighBits()>>8&255,n[t]=255&this.cursorIds[r].getHighBits(),t+=4;return n};var l=function(e,t,n,o,i){i=i||{promoteLongs:!0,promoteValues:!0,promoteBuffers:!1},this.parsed=!1,this.raw=t,this.data=o,this.bson=e,this.opts=i,this.length=n.length,this.requestId=n.requestId,this.responseTo=n.responseTo,this.opCode=n.opCode,this.fromCompressed=n.fromCompressed,this.responseFlags=o.readInt32LE(0),this.cursorId=new r(o.readInt32LE(4),o.readInt32LE(8)),this.startingFrom=o.readInt32LE(12),this.numberReturned=o.readInt32LE(16),this.documents=new Array(this.numberReturned),this.cursorNotFound=0!=(1&this.responseFlags),this.queryFailure=0!=(2&this.responseFlags),this.shardConfigStale=0!=(4&this.responseFlags),this.awaitCapable=0!=(8&this.responseFlags),this.promoteLongs="boolean"!=typeof i.promoteLongs||i.promoteLongs,this.promoteValues="boolean"!=typeof i.promoteValues||i.promoteValues,this.promoteBuffers="boolean"==typeof i.promoteBuffers&&i.promoteBuffers};l.prototype.isParsed=function(){return this.parsed},l.prototype.parse=function(e){if(!this.parsed){var t,n,r=(e=e||{}).raw||!1,o=e.documentsReturnedIn||null;n={promoteLongs:"boolean"==typeof e.promoteLongs?e.promoteLongs:this.opts.promoteLongs,promoteValues:"boolean"==typeof e.promoteValues?e.promoteValues:this.opts.promoteValues,promoteBuffers:"boolean"==typeof e.promoteBuffers?e.promoteBuffers:this.opts.promoteBuffers},this.index=20;for(var i=0;i<this.numberReturned;i++)t=this.data[this.index]|this.data[this.index+1]<<8|this.data[this.index+2]<<16|this.data[this.index+3]<<24,this.documents[i]=r?this.data.slice(this.index,this.index+t):this.bson.deserialize(this.data.slice(this.index,this.index+t),n),this.index=this.index+t;if(1===this.documents.length&&null!=o&&r){const e={};e[o]=!0,n.fieldsAsRaw=e;const t=this.bson.deserialize(this.documents[0],n);this.documents=[t]}this.parsed=!0}},e.exports={Query:a,GetMore:c,Response:l,KillCursor:u}},function(e,t,n){var r=n(131),o=r.Buffer;function i(e,t){for(var n in e)t[n]=e[n]}function s(e,t,n){return o(e,t,n)}o.from&&o.alloc&&o.allocUnsafe&&o.allocUnsafeSlow?e.exports=r:(i(r,t),t.Buffer=s),s.prototype=Object.create(o.prototype),i(o,s),s.from=function(e,t,n){if("number"==typeof e)throw new TypeError("Argument must not be a number");return o(e,t,n)},s.alloc=function(e,t,n){if("number"!=typeof e)throw new TypeError("Argument must be a number");var r=o(e);return void 0!==t?"string"==typeof n?r.fill(t,n):r.fill(t):r.fill(0),r},s.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return o(e)},s.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return r.SlowBuffer(e)}},function(e,t,n){"use strict";const r=n(1).Aspect,o=n(1).OperationBase,i=n(0).applyWriteConcern,s=n(0).debugOptions,a=n(0).handleCallback,c=n(2).MongoError,u=n(2).ReadPreference,l=n(0).MongoDBNamespace,f=["authSource","w","wtimeout","j","native_parser","forceServerObjectId","serializeFunctions","raw","promoteLongs","promoteValues","promoteBuffers","bufferMaxEntries","numberOfRetries","retryMiliSeconds","readPreference","pkFactory","parentDb","promiseLibrary","noListener"];e.exports=class extends o{constructor(e,t,n,o){super(t),this.hasAspect(r.WRITE_OPERATION)?(i(this.options,null!=n?{db:e,coll:n}:{db:e},this.options),this.options.readPreference=u.primary):this.options.readPreference=null!=n?u.resolve(n,t):u.resolve(e,t),this.db=e,null!=o&&(this.command=o),null!=n&&(this.collection=n)}_buildCommand(){if(null!=this.command)return this.command}execute(e){const t=this.db,n=Object.assign({},this.options);if(t.serverConfig&&t.serverConfig.isDestroyed())return e(new c("topology was destroyed"));let o;try{o=this._buildCommand()}catch(t){return e(t)}const i=n.dbName||n.authdb||t.databaseName;this.hasAspect(r.WRITE_OPERATION)&&(!n.writeConcern||n.session&&n.session.inTransaction()||(o.writeConcern=n.writeConcern)),t.s.logger.isDebug()&&t.s.logger.debug(`executing command ${JSON.stringify(o)} against ${i}.$cmd with options [${JSON.stringify(s(f,n))}]`);const u=null!=this.namespace?this.namespace:new l(i,"$cmd");t.s.topology.command(u,o,n,(t,r)=>t?a(e,t):n.full?a(e,null,r):void a(e,null,r.result))}}},function(e,t,n){(function(e){var r;
|
|
2
2
|
/**
|
|
3
3
|
* @license
|
|
4
4
|
* Lodash <https://lodash.com/>
|
|
@@ -6,4 +6,4 @@ module.exports=function(e){var t={};function n(r){if(t[r])return t[r].exports;va
|
|
|
6
6
|
* Released under MIT license <https://lodash.com/license>
|
|
7
7
|
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
|
|
8
8
|
* Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
|
|
9
|
-
*/(function(){var o="Expected a function",i="__lodash_placeholder__",s=[["ary",128],["bind",1],["bindKey",2],["curry",8],["curryRight",16],["flip",512],["partial",32],["partialRight",64],["rearg",256]],a="[object Arguments]",c="[object Array]",u="[object Boolean]",l="[object Date]",f="[object Error]",p="[object Function]",d="[object GeneratorFunction]",h="[object Map]",m="[object Number]",g="[object Object]",y="[object RegExp]",b="[object Set]",v="[object String]",S="[object Symbol]",w="[object WeakMap]",_="[object ArrayBuffer]",O="[object DataView]",T="[object Float32Array]",C="[object Float64Array]",x="[object Int8Array]",E="[object Int16Array]",N="[object Int32Array]",I="[object Uint8Array]",A="[object Uint16Array]",k="[object Uint32Array]",M=/\b__p \+= '';/g,R=/\b(__p \+=) '' \+/g,j=/(__e\(.*?\)|\b__t\)) \+\n'';/g,D=/&(?:amp|lt|gt|quot|#39);/g,P=/[&<>"']/g,B=RegExp(D.source),L=RegExp(P.source),q=/<%-([\s\S]+?)%>/g,U=/<%([\s\S]+?)%>/g,z=/<%=([\s\S]+?)%>/g,$=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,W=/^\w*$/,F=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,V=/[\\^$.*+?()[\]{}|]/g,K=RegExp(V.source),H=/^\s+/,Y=/\s/,G=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,J=/\{\n\/\* \[wrapped with (.+)\] \*/,X=/,? & /,Z=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,Q=/[()=,{}\[\]\/\s]/,ee=/\\(\\)?/g,te=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,ne=/\w*$/,re=/^[-+]0x[0-9a-f]+$/i,oe=/^0b[01]+$/i,ie=/^\[object .+?Constructor\]$/,se=/^0o[0-7]+$/i,ae=/^(?:0|[1-9]\d*)$/,ce=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,ue=/($^)/,le=/['\n\r\u2028\u2029\\]/g,fe="\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff",pe="\\xac\\xb1\\xd7\\xf7\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf\\u2000-\\u206f \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",de="[\\ud800-\\udfff]",he="["+pe+"]",me="["+fe+"]",ge="\\d+",ye="[\\u2700-\\u27bf]",be="[a-z\\xdf-\\xf6\\xf8-\\xff]",ve="[^\\ud800-\\udfff"+pe+ge+"\\u2700-\\u27bfa-z\\xdf-\\xf6\\xf8-\\xffA-Z\\xc0-\\xd6\\xd8-\\xde]",Se="\\ud83c[\\udffb-\\udfff]",we="[^\\ud800-\\udfff]",_e="(?:\\ud83c[\\udde6-\\uddff]){2}",Oe="[\\ud800-\\udbff][\\udc00-\\udfff]",Te="[A-Z\\xc0-\\xd6\\xd8-\\xde]",Ce="(?:"+be+"|"+ve+")",xe="(?:"+Te+"|"+ve+")",Ee="(?:"+me+"|"+Se+")"+"?",Ne="[\\ufe0e\\ufe0f]?"+Ee+("(?:\\u200d(?:"+[we,_e,Oe].join("|")+")[\\ufe0e\\ufe0f]?"+Ee+")*"),Ie="(?:"+[ye,_e,Oe].join("|")+")"+Ne,Ae="(?:"+[we+me+"?",me,_e,Oe,de].join("|")+")",ke=RegExp("['’]","g"),Me=RegExp(me,"g"),Re=RegExp(Se+"(?="+Se+")|"+Ae+Ne,"g"),je=RegExp([Te+"?"+be+"+(?:['’](?:d|ll|m|re|s|t|ve))?(?="+[he,Te,"$"].join("|")+")",xe+"+(?:['’](?:D|LL|M|RE|S|T|VE))?(?="+[he,Te+Ce,"$"].join("|")+")",Te+"?"+Ce+"+(?:['’](?:d|ll|m|re|s|t|ve))?",Te+"+(?:['’](?:D|LL|M|RE|S|T|VE))?","\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])","\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",ge,Ie].join("|"),"g"),De=RegExp("[\\u200d\\ud800-\\udfff"+fe+"\\ufe0e\\ufe0f]"),Pe=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,Be=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],Le=-1,qe={};qe[T]=qe[C]=qe[x]=qe[E]=qe[N]=qe[I]=qe["[object Uint8ClampedArray]"]=qe[A]=qe[k]=!0,qe[a]=qe[c]=qe[_]=qe[u]=qe[O]=qe[l]=qe[f]=qe[p]=qe[h]=qe[m]=qe[g]=qe[y]=qe[b]=qe[v]=qe[w]=!1;var Ue={};Ue[a]=Ue[c]=Ue[_]=Ue[O]=Ue[u]=Ue[l]=Ue[T]=Ue[C]=Ue[x]=Ue[E]=Ue[N]=Ue[h]=Ue[m]=Ue[g]=Ue[y]=Ue[b]=Ue[v]=Ue[S]=Ue[I]=Ue["[object Uint8ClampedArray]"]=Ue[A]=Ue[k]=!0,Ue[f]=Ue[p]=Ue[w]=!1;var ze={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},$e=parseFloat,We=parseInt,Fe="object"==typeof global&&global&&global.Object===Object&&global,Ve="object"==typeof self&&self&&self.Object===Object&&self,Ke=Fe||Ve||Function("return this")(),He=t&&!t.nodeType&&t,Ye=He&&"object"==typeof e&&e&&!e.nodeType&&e,Ge=Ye&&Ye.exports===He,Je=Ge&&Fe.process,Xe=function(){try{var e=Ye&&Ye.require&&Ye.require("util").types;return e||Je&&Je.binding&&Je.binding("util")}catch(e){}}(),Ze=Xe&&Xe.isArrayBuffer,Qe=Xe&&Xe.isDate,et=Xe&&Xe.isMap,tt=Xe&&Xe.isRegExp,nt=Xe&&Xe.isSet,rt=Xe&&Xe.isTypedArray;function ot(e,t,n){switch(n.length){case 0:return e.call(t);case 1:return e.call(t,n[0]);case 2:return e.call(t,n[0],n[1]);case 3:return e.call(t,n[0],n[1],n[2])}return e.apply(t,n)}function it(e,t,n,r){for(var o=-1,i=null==e?0:e.length;++o<i;){var s=e[o];t(r,s,n(s),e)}return r}function st(e,t){for(var n=-1,r=null==e?0:e.length;++n<r&&!1!==t(e[n],n,e););return e}function at(e,t){for(var n=null==e?0:e.length;n--&&!1!==t(e[n],n,e););return e}function ct(e,t){for(var n=-1,r=null==e?0:e.length;++n<r;)if(!t(e[n],n,e))return!1;return!0}function ut(e,t){for(var n=-1,r=null==e?0:e.length,o=0,i=[];++n<r;){var s=e[n];t(s,n,e)&&(i[o++]=s)}return i}function lt(e,t){return!!(null==e?0:e.length)&&St(e,t,0)>-1}function ft(e,t,n){for(var r=-1,o=null==e?0:e.length;++r<o;)if(n(t,e[r]))return!0;return!1}function pt(e,t){for(var n=-1,r=null==e?0:e.length,o=Array(r);++n<r;)o[n]=t(e[n],n,e);return o}function dt(e,t){for(var n=-1,r=t.length,o=e.length;++n<r;)e[o+n]=t[n];return e}function ht(e,t,n,r){var o=-1,i=null==e?0:e.length;for(r&&i&&(n=e[++o]);++o<i;)n=t(n,e[o],o,e);return n}function mt(e,t,n,r){var o=null==e?0:e.length;for(r&&o&&(n=e[--o]);o--;)n=t(n,e[o],o,e);return n}function gt(e,t){for(var n=-1,r=null==e?0:e.length;++n<r;)if(t(e[n],n,e))return!0;return!1}var yt=Tt("length");function bt(e,t,n){var r;return n(e,(function(e,n,o){if(t(e,n,o))return r=n,!1})),r}function vt(e,t,n,r){for(var o=e.length,i=n+(r?1:-1);r?i--:++i<o;)if(t(e[i],i,e))return i;return-1}function St(e,t,n){return t==t?function(e,t,n){var r=n-1,o=e.length;for(;++r<o;)if(e[r]===t)return r;return-1}(e,t,n):vt(e,_t,n)}function wt(e,t,n,r){for(var o=n-1,i=e.length;++o<i;)if(r(e[o],t))return o;return-1}function _t(e){return e!=e}function Ot(e,t){var n=null==e?0:e.length;return n?Et(e,t)/n:NaN}function Tt(e){return function(t){return null==t?void 0:t[e]}}function Ct(e){return function(t){return null==e?void 0:e[t]}}function xt(e,t,n,r,o){return o(e,(function(e,o,i){n=r?(r=!1,e):t(n,e,o,i)})),n}function Et(e,t){for(var n,r=-1,o=e.length;++r<o;){var i=t(e[r]);void 0!==i&&(n=void 0===n?i:n+i)}return n}function Nt(e,t){for(var n=-1,r=Array(e);++n<e;)r[n]=t(n);return r}function It(e){return e?e.slice(0,Ht(e)+1).replace(H,""):e}function At(e){return function(t){return e(t)}}function kt(e,t){return pt(t,(function(t){return e[t]}))}function Mt(e,t){return e.has(t)}function Rt(e,t){for(var n=-1,r=e.length;++n<r&&St(t,e[n],0)>-1;);return n}function jt(e,t){for(var n=e.length;n--&&St(t,e[n],0)>-1;);return n}function Dt(e,t){for(var n=e.length,r=0;n--;)e[n]===t&&++r;return r}var Pt=Ct({"À":"A","Á":"A","Â":"A","Ã":"A","Ä":"A","Å":"A","à":"a","á":"a","â":"a","ã":"a","ä":"a","å":"a","Ç":"C","ç":"c","Ð":"D","ð":"d","È":"E","É":"E","Ê":"E","Ë":"E","è":"e","é":"e","ê":"e","ë":"e","Ì":"I","Í":"I","Î":"I","Ï":"I","ì":"i","í":"i","î":"i","ï":"i","Ñ":"N","ñ":"n","Ò":"O","Ó":"O","Ô":"O","Õ":"O","Ö":"O","Ø":"O","ò":"o","ó":"o","ô":"o","õ":"o","ö":"o","ø":"o","Ù":"U","Ú":"U","Û":"U","Ü":"U","ù":"u","ú":"u","û":"u","ü":"u","Ý":"Y","ý":"y","ÿ":"y","Æ":"Ae","æ":"ae","Þ":"Th","þ":"th","ß":"ss","Ā":"A","Ă":"A","Ą":"A","ā":"a","ă":"a","ą":"a","Ć":"C","Ĉ":"C","Ċ":"C","Č":"C","ć":"c","ĉ":"c","ċ":"c","č":"c","Ď":"D","Đ":"D","ď":"d","đ":"d","Ē":"E","Ĕ":"E","Ė":"E","Ę":"E","Ě":"E","ē":"e","ĕ":"e","ė":"e","ę":"e","ě":"e","Ĝ":"G","Ğ":"G","Ġ":"G","Ģ":"G","ĝ":"g","ğ":"g","ġ":"g","ģ":"g","Ĥ":"H","Ħ":"H","ĥ":"h","ħ":"h","Ĩ":"I","Ī":"I","Ĭ":"I","Į":"I","İ":"I","ĩ":"i","ī":"i","ĭ":"i","į":"i","ı":"i","Ĵ":"J","ĵ":"j","Ķ":"K","ķ":"k","ĸ":"k","Ĺ":"L","Ļ":"L","Ľ":"L","Ŀ":"L","Ł":"L","ĺ":"l","ļ":"l","ľ":"l","ŀ":"l","ł":"l","Ń":"N","Ņ":"N","Ň":"N","Ŋ":"N","ń":"n","ņ":"n","ň":"n","ŋ":"n","Ō":"O","Ŏ":"O","Ő":"O","ō":"o","ŏ":"o","ő":"o","Ŕ":"R","Ŗ":"R","Ř":"R","ŕ":"r","ŗ":"r","ř":"r","Ś":"S","Ŝ":"S","Ş":"S","Š":"S","ś":"s","ŝ":"s","ş":"s","š":"s","Ţ":"T","Ť":"T","Ŧ":"T","ţ":"t","ť":"t","ŧ":"t","Ũ":"U","Ū":"U","Ŭ":"U","Ů":"U","Ű":"U","Ų":"U","ũ":"u","ū":"u","ŭ":"u","ů":"u","ű":"u","ų":"u","Ŵ":"W","ŵ":"w","Ŷ":"Y","ŷ":"y","Ÿ":"Y","Ź":"Z","Ż":"Z","Ž":"Z","ź":"z","ż":"z","ž":"z","IJ":"IJ","ij":"ij","Œ":"Oe","œ":"oe","ʼn":"'n","ſ":"s"}),Bt=Ct({"&":"&","<":"<",">":">",'"':""","'":"'"});function Lt(e){return"\\"+ze[e]}function qt(e){return De.test(e)}function Ut(e){var t=-1,n=Array(e.size);return e.forEach((function(e,r){n[++t]=[r,e]})),n}function zt(e,t){return function(n){return e(t(n))}}function $t(e,t){for(var n=-1,r=e.length,o=0,s=[];++n<r;){var a=e[n];a!==t&&a!==i||(e[n]=i,s[o++]=n)}return s}function Wt(e){var t=-1,n=Array(e.size);return e.forEach((function(e){n[++t]=e})),n}function Ft(e){var t=-1,n=Array(e.size);return e.forEach((function(e){n[++t]=[e,e]})),n}function Vt(e){return qt(e)?function(e){var t=Re.lastIndex=0;for(;Re.test(e);)++t;return t}(e):yt(e)}function Kt(e){return qt(e)?function(e){return e.match(Re)||[]}(e):function(e){return e.split("")}(e)}function Ht(e){for(var t=e.length;t--&&Y.test(e.charAt(t)););return t}var Yt=Ct({"&":"&","<":"<",">":">",""":'"',"'":"'"});var Gt=function e(t){var n,r=(t=null==t?Ke:Gt.defaults(Ke.Object(),t,Gt.pick(Ke,Be))).Array,Y=t.Date,fe=t.Error,pe=t.Function,de=t.Math,he=t.Object,me=t.RegExp,ge=t.String,ye=t.TypeError,be=r.prototype,ve=pe.prototype,Se=he.prototype,we=t["__core-js_shared__"],_e=ve.toString,Oe=Se.hasOwnProperty,Te=0,Ce=(n=/[^.]+$/.exec(we&&we.keys&&we.keys.IE_PROTO||""))?"Symbol(src)_1."+n:"",xe=Se.toString,Ee=_e.call(he),Ne=Ke._,Ie=me("^"+_e.call(Oe).replace(V,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Ae=Ge?t.Buffer:void 0,Re=t.Symbol,De=t.Uint8Array,ze=Ae?Ae.allocUnsafe:void 0,Fe=zt(he.getPrototypeOf,he),Ve=he.create,He=Se.propertyIsEnumerable,Ye=be.splice,Je=Re?Re.isConcatSpreadable:void 0,Xe=Re?Re.iterator:void 0,yt=Re?Re.toStringTag:void 0,Ct=function(){try{var e=ti(he,"defineProperty");return e({},"",{}),e}catch(e){}}(),Jt=t.clearTimeout!==Ke.clearTimeout&&t.clearTimeout,Xt=Y&&Y.now!==Ke.Date.now&&Y.now,Zt=t.setTimeout!==Ke.setTimeout&&t.setTimeout,Qt=de.ceil,en=de.floor,tn=he.getOwnPropertySymbols,nn=Ae?Ae.isBuffer:void 0,rn=t.isFinite,on=be.join,sn=zt(he.keys,he),an=de.max,cn=de.min,un=Y.now,ln=t.parseInt,fn=de.random,pn=be.reverse,dn=ti(t,"DataView"),hn=ti(t,"Map"),mn=ti(t,"Promise"),gn=ti(t,"Set"),yn=ti(t,"WeakMap"),bn=ti(he,"create"),vn=yn&&new yn,Sn={},wn=Ni(dn),_n=Ni(hn),On=Ni(mn),Tn=Ni(gn),Cn=Ni(yn),xn=Re?Re.prototype:void 0,En=xn?xn.valueOf:void 0,Nn=xn?xn.toString:void 0;function In(e){if(Vs(e)&&!js(e)&&!(e instanceof Rn)){if(e instanceof Mn)return e;if(Oe.call(e,"__wrapped__"))return Ii(e)}return new Mn(e)}var An=function(){function e(){}return function(t){if(!Fs(t))return{};if(Ve)return Ve(t);e.prototype=t;var n=new e;return e.prototype=void 0,n}}();function kn(){}function Mn(e,t){this.__wrapped__=e,this.__actions__=[],this.__chain__=!!t,this.__index__=0,this.__values__=void 0}function Rn(e){this.__wrapped__=e,this.__actions__=[],this.__dir__=1,this.__filtered__=!1,this.__iteratees__=[],this.__takeCount__=4294967295,this.__views__=[]}function jn(e){var t=-1,n=null==e?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}function Dn(e){var t=-1,n=null==e?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}function Pn(e){var t=-1,n=null==e?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}function Bn(e){var t=-1,n=null==e?0:e.length;for(this.__data__=new Pn;++t<n;)this.add(e[t])}function Ln(e){var t=this.__data__=new Dn(e);this.size=t.size}function qn(e,t){var n=js(e),r=!n&&Rs(e),o=!n&&!r&&Ls(e),i=!n&&!r&&!o&&Qs(e),s=n||r||o||i,a=s?Nt(e.length,ge):[],c=a.length;for(var u in e)!t&&!Oe.call(e,u)||s&&("length"==u||o&&("offset"==u||"parent"==u)||i&&("buffer"==u||"byteLength"==u||"byteOffset"==u)||ci(u,c))||a.push(u);return a}function Un(e){var t=e.length;return t?e[Br(0,t-1)]:void 0}function zn(e,t){return Ci(vo(e),Jn(t,0,e.length))}function $n(e){return Ci(vo(e))}function Wn(e,t,n){(void 0===n||As(e[t],n))&&(void 0!==n||t in e)||Yn(e,t,n)}function Fn(e,t,n){var r=e[t];Oe.call(e,t)&&As(r,n)&&(void 0!==n||t in e)||Yn(e,t,n)}function Vn(e,t){for(var n=e.length;n--;)if(As(e[n][0],t))return n;return-1}function Kn(e,t,n,r){return tr(e,(function(e,o,i){t(r,e,n(e),i)})),r}function Hn(e,t){return e&&So(t,wa(t),e)}function Yn(e,t,n){"__proto__"==t&&Ct?Ct(e,t,{configurable:!0,enumerable:!0,value:n,writable:!0}):e[t]=n}function Gn(e,t){for(var n=-1,o=t.length,i=r(o),s=null==e;++n<o;)i[n]=s?void 0:ga(e,t[n]);return i}function Jn(e,t,n){return e==e&&(void 0!==n&&(e=e<=n?e:n),void 0!==t&&(e=e>=t?e:t)),e}function Xn(e,t,n,r,o,i){var s,c=1&t,f=2&t,w=4&t;if(n&&(s=o?n(e,r,o,i):n(e)),void 0!==s)return s;if(!Fs(e))return e;var M=js(e);if(M){if(s=function(e){var t=e.length,n=new e.constructor(t);t&&"string"==typeof e[0]&&Oe.call(e,"index")&&(n.index=e.index,n.input=e.input);return n}(e),!c)return vo(e,s)}else{var R=oi(e),j=R==p||R==d;if(Ls(e))return po(e,c);if(R==g||R==a||j&&!o){if(s=f||j?{}:si(e),!c)return f?function(e,t){return So(e,ri(e),t)}(e,function(e,t){return e&&So(t,_a(t),e)}(s,e)):function(e,t){return So(e,ni(e),t)}(e,Hn(s,e))}else{if(!Ue[R])return o?e:{};s=function(e,t,n){var r=e.constructor;switch(t){case _:return ho(e);case u:case l:return new r(+e);case O:return function(e,t){var n=t?ho(e.buffer):e.buffer;return new e.constructor(n,e.byteOffset,e.byteLength)}(e,n);case T:case C:case x:case E:case N:case I:case"[object Uint8ClampedArray]":case A:case k:return mo(e,n);case h:return new r;case m:case v:return new r(e);case y:return function(e){var t=new e.constructor(e.source,ne.exec(e));return t.lastIndex=e.lastIndex,t}(e);case b:return new r;case S:return o=e,En?he(En.call(o)):{}}var o}(e,R,c)}}i||(i=new Ln);var D=i.get(e);if(D)return D;i.set(e,s),Js(e)?e.forEach((function(r){s.add(Xn(r,t,n,r,e,i))})):Ks(e)&&e.forEach((function(r,o){s.set(o,Xn(r,t,n,o,e,i))}));var P=M?void 0:(w?f?Yo:Ho:f?_a:wa)(e);return st(P||e,(function(r,o){P&&(r=e[o=r]),Fn(s,o,Xn(r,t,n,o,e,i))})),s}function Zn(e,t,n){var r=n.length;if(null==e)return!r;for(e=he(e);r--;){var o=n[r],i=t[o],s=e[o];if(void 0===s&&!(o in e)||!i(s))return!1}return!0}function Qn(e,t,n){if("function"!=typeof e)throw new ye(o);return wi((function(){e.apply(void 0,n)}),t)}function er(e,t,n,r){var o=-1,i=lt,s=!0,a=e.length,c=[],u=t.length;if(!a)return c;n&&(t=pt(t,At(n))),r?(i=ft,s=!1):t.length>=200&&(i=Mt,s=!1,t=new Bn(t));e:for(;++o<a;){var l=e[o],f=null==n?l:n(l);if(l=r||0!==l?l:0,s&&f==f){for(var p=u;p--;)if(t[p]===f)continue e;c.push(l)}else i(t,f,r)||c.push(l)}return c}In.templateSettings={escape:q,evaluate:U,interpolate:z,variable:"",imports:{_:In}},In.prototype=kn.prototype,In.prototype.constructor=In,Mn.prototype=An(kn.prototype),Mn.prototype.constructor=Mn,Rn.prototype=An(kn.prototype),Rn.prototype.constructor=Rn,jn.prototype.clear=function(){this.__data__=bn?bn(null):{},this.size=0},jn.prototype.delete=function(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t},jn.prototype.get=function(e){var t=this.__data__;if(bn){var n=t[e];return"__lodash_hash_undefined__"===n?void 0:n}return Oe.call(t,e)?t[e]:void 0},jn.prototype.has=function(e){var t=this.__data__;return bn?void 0!==t[e]:Oe.call(t,e)},jn.prototype.set=function(e,t){var n=this.__data__;return this.size+=this.has(e)?0:1,n[e]=bn&&void 0===t?"__lodash_hash_undefined__":t,this},Dn.prototype.clear=function(){this.__data__=[],this.size=0},Dn.prototype.delete=function(e){var t=this.__data__,n=Vn(t,e);return!(n<0)&&(n==t.length-1?t.pop():Ye.call(t,n,1),--this.size,!0)},Dn.prototype.get=function(e){var t=this.__data__,n=Vn(t,e);return n<0?void 0:t[n][1]},Dn.prototype.has=function(e){return Vn(this.__data__,e)>-1},Dn.prototype.set=function(e,t){var n=this.__data__,r=Vn(n,e);return r<0?(++this.size,n.push([e,t])):n[r][1]=t,this},Pn.prototype.clear=function(){this.size=0,this.__data__={hash:new jn,map:new(hn||Dn),string:new jn}},Pn.prototype.delete=function(e){var t=Qo(this,e).delete(e);return this.size-=t?1:0,t},Pn.prototype.get=function(e){return Qo(this,e).get(e)},Pn.prototype.has=function(e){return Qo(this,e).has(e)},Pn.prototype.set=function(e,t){var n=Qo(this,e),r=n.size;return n.set(e,t),this.size+=n.size==r?0:1,this},Bn.prototype.add=Bn.prototype.push=function(e){return this.__data__.set(e,"__lodash_hash_undefined__"),this},Bn.prototype.has=function(e){return this.__data__.has(e)},Ln.prototype.clear=function(){this.__data__=new Dn,this.size=0},Ln.prototype.delete=function(e){var t=this.__data__,n=t.delete(e);return this.size=t.size,n},Ln.prototype.get=function(e){return this.__data__.get(e)},Ln.prototype.has=function(e){return this.__data__.has(e)},Ln.prototype.set=function(e,t){var n=this.__data__;if(n instanceof Dn){var r=n.__data__;if(!hn||r.length<199)return r.push([e,t]),this.size=++n.size,this;n=this.__data__=new Pn(r)}return n.set(e,t),this.size=n.size,this};var tr=Oo(ur),nr=Oo(lr,!0);function rr(e,t){var n=!0;return tr(e,(function(e,r,o){return n=!!t(e,r,o)})),n}function or(e,t,n){for(var r=-1,o=e.length;++r<o;){var i=e[r],s=t(i);if(null!=s&&(void 0===a?s==s&&!Zs(s):n(s,a)))var a=s,c=i}return c}function ir(e,t){var n=[];return tr(e,(function(e,r,o){t(e,r,o)&&n.push(e)})),n}function sr(e,t,n,r,o){var i=-1,s=e.length;for(n||(n=ai),o||(o=[]);++i<s;){var a=e[i];t>0&&n(a)?t>1?sr(a,t-1,n,r,o):dt(o,a):r||(o[o.length]=a)}return o}var ar=To(),cr=To(!0);function ur(e,t){return e&&ar(e,t,wa)}function lr(e,t){return e&&cr(e,t,wa)}function fr(e,t){return ut(t,(function(t){return zs(e[t])}))}function pr(e,t){for(var n=0,r=(t=co(t,e)).length;null!=e&&n<r;)e=e[Ei(t[n++])];return n&&n==r?e:void 0}function dr(e,t,n){var r=t(e);return js(e)?r:dt(r,n(e))}function hr(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":yt&&yt in he(e)?function(e){var t=Oe.call(e,yt),n=e[yt];try{e[yt]=void 0;var r=!0}catch(e){}var o=xe.call(e);r&&(t?e[yt]=n:delete e[yt]);return o}(e):function(e){return xe.call(e)}(e)}function mr(e,t){return e>t}function gr(e,t){return null!=e&&Oe.call(e,t)}function yr(e,t){return null!=e&&t in he(e)}function br(e,t,n){for(var o=n?ft:lt,i=e[0].length,s=e.length,a=s,c=r(s),u=1/0,l=[];a--;){var f=e[a];a&&t&&(f=pt(f,At(t))),u=cn(f.length,u),c[a]=!n&&(t||i>=120&&f.length>=120)?new Bn(a&&f):void 0}f=e[0];var p=-1,d=c[0];e:for(;++p<i&&l.length<u;){var h=f[p],m=t?t(h):h;if(h=n||0!==h?h:0,!(d?Mt(d,m):o(l,m,n))){for(a=s;--a;){var g=c[a];if(!(g?Mt(g,m):o(e[a],m,n)))continue e}d&&d.push(m),l.push(h)}}return l}function vr(e,t,n){var r=null==(e=yi(e,t=co(t,e)))?e:e[Ei(Ui(t))];return null==r?void 0:ot(r,e,n)}function Sr(e){return Vs(e)&&hr(e)==a}function wr(e,t,n,r,o){return e===t||(null==e||null==t||!Vs(e)&&!Vs(t)?e!=e&&t!=t:function(e,t,n,r,o,i){var s=js(e),p=js(t),d=s?c:oi(e),w=p?c:oi(t),T=(d=d==a?g:d)==g,C=(w=w==a?g:w)==g,x=d==w;if(x&&Ls(e)){if(!Ls(t))return!1;s=!0,T=!1}if(x&&!T)return i||(i=new Ln),s||Qs(e)?Vo(e,t,n,r,o,i):function(e,t,n,r,o,i,s){switch(n){case O:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case _:return!(e.byteLength!=t.byteLength||!i(new De(e),new De(t)));case u:case l:case m:return As(+e,+t);case f:return e.name==t.name&&e.message==t.message;case y:case v:return e==t+"";case h:var a=Ut;case b:var c=1&r;if(a||(a=Wt),e.size!=t.size&&!c)return!1;var p=s.get(e);if(p)return p==t;r|=2,s.set(e,t);var d=Vo(a(e),a(t),r,o,i,s);return s.delete(e),d;case S:if(En)return En.call(e)==En.call(t)}return!1}(e,t,d,n,r,o,i);if(!(1&n)){var E=T&&Oe.call(e,"__wrapped__"),N=C&&Oe.call(t,"__wrapped__");if(E||N){var I=E?e.value():e,A=N?t.value():t;return i||(i=new Ln),o(I,A,n,r,i)}}if(!x)return!1;return i||(i=new Ln),function(e,t,n,r,o,i){var s=1&n,a=Ho(e),c=a.length,u=Ho(t).length;if(c!=u&&!s)return!1;var l=c;for(;l--;){var f=a[l];if(!(s?f in t:Oe.call(t,f)))return!1}var p=i.get(e),d=i.get(t);if(p&&d)return p==t&&d==e;var h=!0;i.set(e,t),i.set(t,e);var m=s;for(;++l<c;){f=a[l];var g=e[f],y=t[f];if(r)var b=s?r(y,g,f,t,e,i):r(g,y,f,e,t,i);if(!(void 0===b?g===y||o(g,y,n,r,i):b)){h=!1;break}m||(m="constructor"==f)}if(h&&!m){var v=e.constructor,S=t.constructor;v!=S&&"constructor"in e&&"constructor"in t&&!("function"==typeof v&&v instanceof v&&"function"==typeof S&&S instanceof S)&&(h=!1)}return i.delete(e),i.delete(t),h}(e,t,n,r,o,i)}(e,t,n,r,wr,o))}function _r(e,t,n,r){var o=n.length,i=o,s=!r;if(null==e)return!i;for(e=he(e);o--;){var a=n[o];if(s&&a[2]?a[1]!==e[a[0]]:!(a[0]in e))return!1}for(;++o<i;){var c=(a=n[o])[0],u=e[c],l=a[1];if(s&&a[2]){if(void 0===u&&!(c in e))return!1}else{var f=new Ln;if(r)var p=r(u,l,c,e,t,f);if(!(void 0===p?wr(l,u,3,r,f):p))return!1}}return!0}function Or(e){return!(!Fs(e)||function(e){return!!Ce&&Ce in e}(e))&&(zs(e)?Ie:ie).test(Ni(e))}function Tr(e){return"function"==typeof e?e:null==e?Ha:"object"==typeof e?js(e)?Ar(e[0],e[1]):Ir(e):nc(e)}function Cr(e){if(!di(e))return sn(e);var t=[];for(var n in he(e))Oe.call(e,n)&&"constructor"!=n&&t.push(n);return t}function xr(e){if(!Fs(e))return function(e){var t=[];if(null!=e)for(var n in he(e))t.push(n);return t}(e);var t=di(e),n=[];for(var r in e)("constructor"!=r||!t&&Oe.call(e,r))&&n.push(r);return n}function Er(e,t){return e<t}function Nr(e,t){var n=-1,o=Ps(e)?r(e.length):[];return tr(e,(function(e,r,i){o[++n]=t(e,r,i)})),o}function Ir(e){var t=ei(e);return 1==t.length&&t[0][2]?mi(t[0][0],t[0][1]):function(n){return n===e||_r(n,e,t)}}function Ar(e,t){return li(e)&&hi(t)?mi(Ei(e),t):function(n){var r=ga(n,e);return void 0===r&&r===t?ya(n,e):wr(t,r,3)}}function kr(e,t,n,r,o){e!==t&&ar(t,(function(i,s){if(o||(o=new Ln),Fs(i))!function(e,t,n,r,o,i,s){var a=vi(e,n),c=vi(t,n),u=s.get(c);if(u)return void Wn(e,n,u);var l=i?i(a,c,n+"",e,t,s):void 0,f=void 0===l;if(f){var p=js(c),d=!p&&Ls(c),h=!p&&!d&&Qs(c);l=c,p||d||h?js(a)?l=a:Bs(a)?l=vo(a):d?(f=!1,l=po(c,!0)):h?(f=!1,l=mo(c,!0)):l=[]:Ys(c)||Rs(c)?(l=a,Rs(a)?l=aa(a):Fs(a)&&!zs(a)||(l=si(c))):f=!1}f&&(s.set(c,l),o(l,c,r,i,s),s.delete(c));Wn(e,n,l)}(e,t,s,n,kr,r,o);else{var a=r?r(vi(e,s),i,s+"",e,t,o):void 0;void 0===a&&(a=i),Wn(e,s,a)}}),_a)}function Mr(e,t){var n=e.length;if(n)return ci(t+=t<0?n:0,n)?e[t]:void 0}function Rr(e,t,n){t=t.length?pt(t,(function(e){return js(e)?function(t){return pr(t,1===e.length?e[0]:e)}:e})):[Ha];var r=-1;return t=pt(t,At(Zo())),function(e,t){var n=e.length;for(e.sort(t);n--;)e[n]=e[n].value;return e}(Nr(e,(function(e,n,o){return{criteria:pt(t,(function(t){return t(e)})),index:++r,value:e}})),(function(e,t){return function(e,t,n){var r=-1,o=e.criteria,i=t.criteria,s=o.length,a=n.length;for(;++r<s;){var c=go(o[r],i[r]);if(c){if(r>=a)return c;var u=n[r];return c*("desc"==u?-1:1)}}return e.index-t.index}(e,t,n)}))}function jr(e,t,n){for(var r=-1,o=t.length,i={};++r<o;){var s=t[r],a=pr(e,s);n(a,s)&&$r(i,co(s,e),a)}return i}function Dr(e,t,n,r){var o=r?wt:St,i=-1,s=t.length,a=e;for(e===t&&(t=vo(t)),n&&(a=pt(e,At(n)));++i<s;)for(var c=0,u=t[i],l=n?n(u):u;(c=o(a,l,c,r))>-1;)a!==e&&Ye.call(a,c,1),Ye.call(e,c,1);return e}function Pr(e,t){for(var n=e?t.length:0,r=n-1;n--;){var o=t[n];if(n==r||o!==i){var i=o;ci(o)?Ye.call(e,o,1):eo(e,o)}}return e}function Br(e,t){return e+en(fn()*(t-e+1))}function Lr(e,t){var n="";if(!e||t<1||t>9007199254740991)return n;do{t%2&&(n+=e),(t=en(t/2))&&(e+=e)}while(t);return n}function qr(e,t){return _i(gi(e,t,Ha),e+"")}function Ur(e){return Un(Aa(e))}function zr(e,t){var n=Aa(e);return Ci(n,Jn(t,0,n.length))}function $r(e,t,n,r){if(!Fs(e))return e;for(var o=-1,i=(t=co(t,e)).length,s=i-1,a=e;null!=a&&++o<i;){var c=Ei(t[o]),u=n;if("__proto__"===c||"constructor"===c||"prototype"===c)return e;if(o!=s){var l=a[c];void 0===(u=r?r(l,c,a):void 0)&&(u=Fs(l)?l:ci(t[o+1])?[]:{})}Fn(a,c,u),a=a[c]}return e}var Wr=vn?function(e,t){return vn.set(e,t),e}:Ha,Fr=Ct?function(e,t){return Ct(e,"toString",{configurable:!0,enumerable:!1,value:Fa(t),writable:!0})}:Ha;function Vr(e){return Ci(Aa(e))}function Kr(e,t,n){var o=-1,i=e.length;t<0&&(t=-t>i?0:i+t),(n=n>i?i:n)<0&&(n+=i),i=t>n?0:n-t>>>0,t>>>=0;for(var s=r(i);++o<i;)s[o]=e[o+t];return s}function Hr(e,t){var n;return tr(e,(function(e,r,o){return!(n=t(e,r,o))})),!!n}function Yr(e,t,n){var r=0,o=null==e?r:e.length;if("number"==typeof t&&t==t&&o<=2147483647){for(;r<o;){var i=r+o>>>1,s=e[i];null!==s&&!Zs(s)&&(n?s<=t:s<t)?r=i+1:o=i}return o}return Gr(e,t,Ha,n)}function Gr(e,t,n,r){var o=0,i=null==e?0:e.length;if(0===i)return 0;for(var s=(t=n(t))!=t,a=null===t,c=Zs(t),u=void 0===t;o<i;){var l=en((o+i)/2),f=n(e[l]),p=void 0!==f,d=null===f,h=f==f,m=Zs(f);if(s)var g=r||h;else g=u?h&&(r||p):a?h&&p&&(r||!d):c?h&&p&&!d&&(r||!m):!d&&!m&&(r?f<=t:f<t);g?o=l+1:i=l}return cn(i,4294967294)}function Jr(e,t){for(var n=-1,r=e.length,o=0,i=[];++n<r;){var s=e[n],a=t?t(s):s;if(!n||!As(a,c)){var c=a;i[o++]=0===s?0:s}}return i}function Xr(e){return"number"==typeof e?e:Zs(e)?NaN:+e}function Zr(e){if("string"==typeof e)return e;if(js(e))return pt(e,Zr)+"";if(Zs(e))return Nn?Nn.call(e):"";var t=e+"";return"0"==t&&1/e==-1/0?"-0":t}function Qr(e,t,n){var r=-1,o=lt,i=e.length,s=!0,a=[],c=a;if(n)s=!1,o=ft;else if(i>=200){var u=t?null:qo(e);if(u)return Wt(u);s=!1,o=Mt,c=new Bn}else c=t?[]:a;e:for(;++r<i;){var l=e[r],f=t?t(l):l;if(l=n||0!==l?l:0,s&&f==f){for(var p=c.length;p--;)if(c[p]===f)continue e;t&&c.push(f),a.push(l)}else o(c,f,n)||(c!==a&&c.push(f),a.push(l))}return a}function eo(e,t){return null==(e=yi(e,t=co(t,e)))||delete e[Ei(Ui(t))]}function to(e,t,n,r){return $r(e,t,n(pr(e,t)),r)}function no(e,t,n,r){for(var o=e.length,i=r?o:-1;(r?i--:++i<o)&&t(e[i],i,e););return n?Kr(e,r?0:i,r?i+1:o):Kr(e,r?i+1:0,r?o:i)}function ro(e,t){var n=e;return n instanceof Rn&&(n=n.value()),ht(t,(function(e,t){return t.func.apply(t.thisArg,dt([e],t.args))}),n)}function oo(e,t,n){var o=e.length;if(o<2)return o?Qr(e[0]):[];for(var i=-1,s=r(o);++i<o;)for(var a=e[i],c=-1;++c<o;)c!=i&&(s[i]=er(s[i]||a,e[c],t,n));return Qr(sr(s,1),t,n)}function io(e,t,n){for(var r=-1,o=e.length,i=t.length,s={};++r<o;){var a=r<i?t[r]:void 0;n(s,e[r],a)}return s}function so(e){return Bs(e)?e:[]}function ao(e){return"function"==typeof e?e:Ha}function co(e,t){return js(e)?e:li(e,t)?[e]:xi(ca(e))}var uo=qr;function lo(e,t,n){var r=e.length;return n=void 0===n?r:n,!t&&n>=r?e:Kr(e,t,n)}var fo=Jt||function(e){return Ke.clearTimeout(e)};function po(e,t){if(t)return e.slice();var n=e.length,r=ze?ze(n):new e.constructor(n);return e.copy(r),r}function ho(e){var t=new e.constructor(e.byteLength);return new De(t).set(new De(e)),t}function mo(e,t){var n=t?ho(e.buffer):e.buffer;return new e.constructor(n,e.byteOffset,e.length)}function go(e,t){if(e!==t){var n=void 0!==e,r=null===e,o=e==e,i=Zs(e),s=void 0!==t,a=null===t,c=t==t,u=Zs(t);if(!a&&!u&&!i&&e>t||i&&s&&c&&!a&&!u||r&&s&&c||!n&&c||!o)return 1;if(!r&&!i&&!u&&e<t||u&&n&&o&&!r&&!i||a&&n&&o||!s&&o||!c)return-1}return 0}function yo(e,t,n,o){for(var i=-1,s=e.length,a=n.length,c=-1,u=t.length,l=an(s-a,0),f=r(u+l),p=!o;++c<u;)f[c]=t[c];for(;++i<a;)(p||i<s)&&(f[n[i]]=e[i]);for(;l--;)f[c++]=e[i++];return f}function bo(e,t,n,o){for(var i=-1,s=e.length,a=-1,c=n.length,u=-1,l=t.length,f=an(s-c,0),p=r(f+l),d=!o;++i<f;)p[i]=e[i];for(var h=i;++u<l;)p[h+u]=t[u];for(;++a<c;)(d||i<s)&&(p[h+n[a]]=e[i++]);return p}function vo(e,t){var n=-1,o=e.length;for(t||(t=r(o));++n<o;)t[n]=e[n];return t}function So(e,t,n,r){var o=!n;n||(n={});for(var i=-1,s=t.length;++i<s;){var a=t[i],c=r?r(n[a],e[a],a,n,e):void 0;void 0===c&&(c=e[a]),o?Yn(n,a,c):Fn(n,a,c)}return n}function wo(e,t){return function(n,r){var o=js(n)?it:Kn,i=t?t():{};return o(n,e,Zo(r,2),i)}}function _o(e){return qr((function(t,n){var r=-1,o=n.length,i=o>1?n[o-1]:void 0,s=o>2?n[2]:void 0;for(i=e.length>3&&"function"==typeof i?(o--,i):void 0,s&&ui(n[0],n[1],s)&&(i=o<3?void 0:i,o=1),t=he(t);++r<o;){var a=n[r];a&&e(t,a,r,i)}return t}))}function Oo(e,t){return function(n,r){if(null==n)return n;if(!Ps(n))return e(n,r);for(var o=n.length,i=t?o:-1,s=he(n);(t?i--:++i<o)&&!1!==r(s[i],i,s););return n}}function To(e){return function(t,n,r){for(var o=-1,i=he(t),s=r(t),a=s.length;a--;){var c=s[e?a:++o];if(!1===n(i[c],c,i))break}return t}}function Co(e){return function(t){var n=qt(t=ca(t))?Kt(t):void 0,r=n?n[0]:t.charAt(0),o=n?lo(n,1).join(""):t.slice(1);return r[e]()+o}}function xo(e){return function(t){return ht(za(Ra(t).replace(ke,"")),e,"")}}function Eo(e){return function(){var t=arguments;switch(t.length){case 0:return new e;case 1:return new e(t[0]);case 2:return new e(t[0],t[1]);case 3:return new e(t[0],t[1],t[2]);case 4:return new e(t[0],t[1],t[2],t[3]);case 5:return new e(t[0],t[1],t[2],t[3],t[4]);case 6:return new e(t[0],t[1],t[2],t[3],t[4],t[5]);case 7:return new e(t[0],t[1],t[2],t[3],t[4],t[5],t[6])}var n=An(e.prototype),r=e.apply(n,t);return Fs(r)?r:n}}function No(e){return function(t,n,r){var o=he(t);if(!Ps(t)){var i=Zo(n,3);t=wa(t),n=function(e){return i(o[e],e,o)}}var s=e(t,n,r);return s>-1?o[i?t[s]:s]:void 0}}function Io(e){return Ko((function(t){var n=t.length,r=n,i=Mn.prototype.thru;for(e&&t.reverse();r--;){var s=t[r];if("function"!=typeof s)throw new ye(o);if(i&&!a&&"wrapper"==Jo(s))var a=new Mn([],!0)}for(r=a?r:n;++r<n;){var c=Jo(s=t[r]),u="wrapper"==c?Go(s):void 0;a=u&&fi(u[0])&&424==u[1]&&!u[4].length&&1==u[9]?a[Jo(u[0])].apply(a,u[3]):1==s.length&&fi(s)?a[c]():a.thru(s)}return function(){var e=arguments,r=e[0];if(a&&1==e.length&&js(r))return a.plant(r).value();for(var o=0,i=n?t[o].apply(this,e):r;++o<n;)i=t[o].call(this,i);return i}}))}function Ao(e,t,n,o,i,s,a,c,u,l){var f=128&t,p=1&t,d=2&t,h=24&t,m=512&t,g=d?void 0:Eo(e);return function y(){for(var b=arguments.length,v=r(b),S=b;S--;)v[S]=arguments[S];if(h)var w=Xo(y),_=Dt(v,w);if(o&&(v=yo(v,o,i,h)),s&&(v=bo(v,s,a,h)),b-=_,h&&b<l){var O=$t(v,w);return Bo(e,t,Ao,y.placeholder,n,v,O,c,u,l-b)}var T=p?n:this,C=d?T[e]:e;return b=v.length,c?v=bi(v,c):m&&b>1&&v.reverse(),f&&u<b&&(v.length=u),this&&this!==Ke&&this instanceof y&&(C=g||Eo(C)),C.apply(T,v)}}function ko(e,t){return function(n,r){return function(e,t,n,r){return ur(e,(function(e,o,i){t(r,n(e),o,i)})),r}(n,e,t(r),{})}}function Mo(e,t){return function(n,r){var o;if(void 0===n&&void 0===r)return t;if(void 0!==n&&(o=n),void 0!==r){if(void 0===o)return r;"string"==typeof n||"string"==typeof r?(n=Zr(n),r=Zr(r)):(n=Xr(n),r=Xr(r)),o=e(n,r)}return o}}function Ro(e){return Ko((function(t){return t=pt(t,At(Zo())),qr((function(n){var r=this;return e(t,(function(e){return ot(e,r,n)}))}))}))}function jo(e,t){var n=(t=void 0===t?" ":Zr(t)).length;if(n<2)return n?Lr(t,e):t;var r=Lr(t,Qt(e/Vt(t)));return qt(t)?lo(Kt(r),0,e).join(""):r.slice(0,e)}function Do(e){return function(t,n,o){return o&&"number"!=typeof o&&ui(t,n,o)&&(n=o=void 0),t=ra(t),void 0===n?(n=t,t=0):n=ra(n),function(e,t,n,o){for(var i=-1,s=an(Qt((t-e)/(n||1)),0),a=r(s);s--;)a[o?s:++i]=e,e+=n;return a}(t,n,o=void 0===o?t<n?1:-1:ra(o),e)}}function Po(e){return function(t,n){return"string"==typeof t&&"string"==typeof n||(t=sa(t),n=sa(n)),e(t,n)}}function Bo(e,t,n,r,o,i,s,a,c,u){var l=8&t;t|=l?32:64,4&(t&=~(l?64:32))||(t&=-4);var f=[e,t,o,l?i:void 0,l?s:void 0,l?void 0:i,l?void 0:s,a,c,u],p=n.apply(void 0,f);return fi(e)&&Si(p,f),p.placeholder=r,Oi(p,e,t)}function Lo(e){var t=de[e];return function(e,n){if(e=sa(e),(n=null==n?0:cn(oa(n),292))&&rn(e)){var r=(ca(e)+"e").split("e");return+((r=(ca(t(r[0]+"e"+(+r[1]+n)))+"e").split("e"))[0]+"e"+(+r[1]-n))}return t(e)}}var qo=gn&&1/Wt(new gn([,-0]))[1]==1/0?function(e){return new gn(e)}:Za;function Uo(e){return function(t){var n=oi(t);return n==h?Ut(t):n==b?Ft(t):function(e,t){return pt(t,(function(t){return[t,e[t]]}))}(t,e(t))}}function zo(e,t,n,s,a,c,u,l){var f=2&t;if(!f&&"function"!=typeof e)throw new ye(o);var p=s?s.length:0;if(p||(t&=-97,s=a=void 0),u=void 0===u?u:an(oa(u),0),l=void 0===l?l:oa(l),p-=a?a.length:0,64&t){var d=s,h=a;s=a=void 0}var m=f?void 0:Go(e),g=[e,t,n,s,a,d,h,c,u,l];if(m&&function(e,t){var n=e[1],r=t[1],o=n|r,s=o<131,a=128==r&&8==n||128==r&&256==n&&e[7].length<=t[8]||384==r&&t[7].length<=t[8]&&8==n;if(!s&&!a)return e;1&r&&(e[2]=t[2],o|=1&n?0:4);var c=t[3];if(c){var u=e[3];e[3]=u?yo(u,c,t[4]):c,e[4]=u?$t(e[3],i):t[4]}(c=t[5])&&(u=e[5],e[5]=u?bo(u,c,t[6]):c,e[6]=u?$t(e[5],i):t[6]);(c=t[7])&&(e[7]=c);128&r&&(e[8]=null==e[8]?t[8]:cn(e[8],t[8]));null==e[9]&&(e[9]=t[9]);e[0]=t[0],e[1]=o}(g,m),e=g[0],t=g[1],n=g[2],s=g[3],a=g[4],!(l=g[9]=void 0===g[9]?f?0:e.length:an(g[9]-p,0))&&24&t&&(t&=-25),t&&1!=t)y=8==t||16==t?function(e,t,n){var o=Eo(e);return function i(){for(var s=arguments.length,a=r(s),c=s,u=Xo(i);c--;)a[c]=arguments[c];var l=s<3&&a[0]!==u&&a[s-1]!==u?[]:$t(a,u);if((s-=l.length)<n)return Bo(e,t,Ao,i.placeholder,void 0,a,l,void 0,void 0,n-s);var f=this&&this!==Ke&&this instanceof i?o:e;return ot(f,this,a)}}(e,t,l):32!=t&&33!=t||a.length?Ao.apply(void 0,g):function(e,t,n,o){var i=1&t,s=Eo(e);return function t(){for(var a=-1,c=arguments.length,u=-1,l=o.length,f=r(l+c),p=this&&this!==Ke&&this instanceof t?s:e;++u<l;)f[u]=o[u];for(;c--;)f[u++]=arguments[++a];return ot(p,i?n:this,f)}}(e,t,n,s);else var y=function(e,t,n){var r=1&t,o=Eo(e);return function t(){var i=this&&this!==Ke&&this instanceof t?o:e;return i.apply(r?n:this,arguments)}}(e,t,n);return Oi((m?Wr:Si)(y,g),e,t)}function $o(e,t,n,r){return void 0===e||As(e,Se[n])&&!Oe.call(r,n)?t:e}function Wo(e,t,n,r,o,i){return Fs(e)&&Fs(t)&&(i.set(t,e),kr(e,t,void 0,Wo,i),i.delete(t)),e}function Fo(e){return Ys(e)?void 0:e}function Vo(e,t,n,r,o,i){var s=1&n,a=e.length,c=t.length;if(a!=c&&!(s&&c>a))return!1;var u=i.get(e),l=i.get(t);if(u&&l)return u==t&&l==e;var f=-1,p=!0,d=2&n?new Bn:void 0;for(i.set(e,t),i.set(t,e);++f<a;){var h=e[f],m=t[f];if(r)var g=s?r(m,h,f,t,e,i):r(h,m,f,e,t,i);if(void 0!==g){if(g)continue;p=!1;break}if(d){if(!gt(t,(function(e,t){if(!Mt(d,t)&&(h===e||o(h,e,n,r,i)))return d.push(t)}))){p=!1;break}}else if(h!==m&&!o(h,m,n,r,i)){p=!1;break}}return i.delete(e),i.delete(t),p}function Ko(e){return _i(gi(e,void 0,Di),e+"")}function Ho(e){return dr(e,wa,ni)}function Yo(e){return dr(e,_a,ri)}var Go=vn?function(e){return vn.get(e)}:Za;function Jo(e){for(var t=e.name+"",n=Sn[t],r=Oe.call(Sn,t)?n.length:0;r--;){var o=n[r],i=o.func;if(null==i||i==e)return o.name}return t}function Xo(e){return(Oe.call(In,"placeholder")?In:e).placeholder}function Zo(){var e=In.iteratee||Ya;return e=e===Ya?Tr:e,arguments.length?e(arguments[0],arguments[1]):e}function Qo(e,t){var n,r,o=e.__data__;return("string"==(r=typeof(n=t))||"number"==r||"symbol"==r||"boolean"==r?"__proto__"!==n:null===n)?o["string"==typeof t?"string":"hash"]:o.map}function ei(e){for(var t=wa(e),n=t.length;n--;){var r=t[n],o=e[r];t[n]=[r,o,hi(o)]}return t}function ti(e,t){var n=function(e,t){return null==e?void 0:e[t]}(e,t);return Or(n)?n:void 0}var ni=tn?function(e){return null==e?[]:(e=he(e),ut(tn(e),(function(t){return He.call(e,t)})))}:ic,ri=tn?function(e){for(var t=[];e;)dt(t,ni(e)),e=Fe(e);return t}:ic,oi=hr;function ii(e,t,n){for(var r=-1,o=(t=co(t,e)).length,i=!1;++r<o;){var s=Ei(t[r]);if(!(i=null!=e&&n(e,s)))break;e=e[s]}return i||++r!=o?i:!!(o=null==e?0:e.length)&&Ws(o)&&ci(s,o)&&(js(e)||Rs(e))}function si(e){return"function"!=typeof e.constructor||di(e)?{}:An(Fe(e))}function ai(e){return js(e)||Rs(e)||!!(Je&&e&&e[Je])}function ci(e,t){var n=typeof e;return!!(t=null==t?9007199254740991:t)&&("number"==n||"symbol"!=n&&ae.test(e))&&e>-1&&e%1==0&&e<t}function ui(e,t,n){if(!Fs(n))return!1;var r=typeof t;return!!("number"==r?Ps(n)&&ci(t,n.length):"string"==r&&t in n)&&As(n[t],e)}function li(e,t){if(js(e))return!1;var n=typeof e;return!("number"!=n&&"symbol"!=n&&"boolean"!=n&&null!=e&&!Zs(e))||(W.test(e)||!$.test(e)||null!=t&&e in he(t))}function fi(e){var t=Jo(e),n=In[t];if("function"!=typeof n||!(t in Rn.prototype))return!1;if(e===n)return!0;var r=Go(n);return!!r&&e===r[0]}(dn&&oi(new dn(new ArrayBuffer(1)))!=O||hn&&oi(new hn)!=h||mn&&"[object Promise]"!=oi(mn.resolve())||gn&&oi(new gn)!=b||yn&&oi(new yn)!=w)&&(oi=function(e){var t=hr(e),n=t==g?e.constructor:void 0,r=n?Ni(n):"";if(r)switch(r){case wn:return O;case _n:return h;case On:return"[object Promise]";case Tn:return b;case Cn:return w}return t});var pi=we?zs:sc;function di(e){var t=e&&e.constructor;return e===("function"==typeof t&&t.prototype||Se)}function hi(e){return e==e&&!Fs(e)}function mi(e,t){return function(n){return null!=n&&(n[e]===t&&(void 0!==t||e in he(n)))}}function gi(e,t,n){return t=an(void 0===t?e.length-1:t,0),function(){for(var o=arguments,i=-1,s=an(o.length-t,0),a=r(s);++i<s;)a[i]=o[t+i];i=-1;for(var c=r(t+1);++i<t;)c[i]=o[i];return c[t]=n(a),ot(e,this,c)}}function yi(e,t){return t.length<2?e:pr(e,Kr(t,0,-1))}function bi(e,t){for(var n=e.length,r=cn(t.length,n),o=vo(e);r--;){var i=t[r];e[r]=ci(i,n)?o[i]:void 0}return e}function vi(e,t){if(("constructor"!==t||"function"!=typeof e[t])&&"__proto__"!=t)return e[t]}var Si=Ti(Wr),wi=Zt||function(e,t){return Ke.setTimeout(e,t)},_i=Ti(Fr);function Oi(e,t,n){var r=t+"";return _i(e,function(e,t){var n=t.length;if(!n)return e;var r=n-1;return t[r]=(n>1?"& ":"")+t[r],t=t.join(n>2?", ":" "),e.replace(G,"{\n/* [wrapped with "+t+"] */\n")}(r,function(e,t){return st(s,(function(n){var r="_."+n[0];t&n[1]&&!lt(e,r)&&e.push(r)})),e.sort()}(function(e){var t=e.match(J);return t?t[1].split(X):[]}(r),n)))}function Ti(e){var t=0,n=0;return function(){var r=un(),o=16-(r-n);if(n=r,o>0){if(++t>=800)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}function Ci(e,t){var n=-1,r=e.length,o=r-1;for(t=void 0===t?r:t;++n<t;){var i=Br(n,o),s=e[i];e[i]=e[n],e[n]=s}return e.length=t,e}var xi=function(e){var t=Ts(e,(function(e){return 500===n.size&&n.clear(),e})),n=t.cache;return t}((function(e){var t=[];return 46===e.charCodeAt(0)&&t.push(""),e.replace(F,(function(e,n,r,o){t.push(r?o.replace(ee,"$1"):n||e)})),t}));function Ei(e){if("string"==typeof e||Zs(e))return e;var t=e+"";return"0"==t&&1/e==-1/0?"-0":t}function Ni(e){if(null!=e){try{return _e.call(e)}catch(e){}try{return e+""}catch(e){}}return""}function Ii(e){if(e instanceof Rn)return e.clone();var t=new Mn(e.__wrapped__,e.__chain__);return t.__actions__=vo(e.__actions__),t.__index__=e.__index__,t.__values__=e.__values__,t}var Ai=qr((function(e,t){return Bs(e)?er(e,sr(t,1,Bs,!0)):[]})),ki=qr((function(e,t){var n=Ui(t);return Bs(n)&&(n=void 0),Bs(e)?er(e,sr(t,1,Bs,!0),Zo(n,2)):[]})),Mi=qr((function(e,t){var n=Ui(t);return Bs(n)&&(n=void 0),Bs(e)?er(e,sr(t,1,Bs,!0),void 0,n):[]}));function Ri(e,t,n){var r=null==e?0:e.length;if(!r)return-1;var o=null==n?0:oa(n);return o<0&&(o=an(r+o,0)),vt(e,Zo(t,3),o)}function ji(e,t,n){var r=null==e?0:e.length;if(!r)return-1;var o=r-1;return void 0!==n&&(o=oa(n),o=n<0?an(r+o,0):cn(o,r-1)),vt(e,Zo(t,3),o,!0)}function Di(e){return(null==e?0:e.length)?sr(e,1):[]}function Pi(e){return e&&e.length?e[0]:void 0}var Bi=qr((function(e){var t=pt(e,so);return t.length&&t[0]===e[0]?br(t):[]})),Li=qr((function(e){var t=Ui(e),n=pt(e,so);return t===Ui(n)?t=void 0:n.pop(),n.length&&n[0]===e[0]?br(n,Zo(t,2)):[]})),qi=qr((function(e){var t=Ui(e),n=pt(e,so);return(t="function"==typeof t?t:void 0)&&n.pop(),n.length&&n[0]===e[0]?br(n,void 0,t):[]}));function Ui(e){var t=null==e?0:e.length;return t?e[t-1]:void 0}var zi=qr($i);function $i(e,t){return e&&e.length&&t&&t.length?Dr(e,t):e}var Wi=Ko((function(e,t){var n=null==e?0:e.length,r=Gn(e,t);return Pr(e,pt(t,(function(e){return ci(e,n)?+e:e})).sort(go)),r}));function Fi(e){return null==e?e:pn.call(e)}var Vi=qr((function(e){return Qr(sr(e,1,Bs,!0))})),Ki=qr((function(e){var t=Ui(e);return Bs(t)&&(t=void 0),Qr(sr(e,1,Bs,!0),Zo(t,2))})),Hi=qr((function(e){var t=Ui(e);return t="function"==typeof t?t:void 0,Qr(sr(e,1,Bs,!0),void 0,t)}));function Yi(e){if(!e||!e.length)return[];var t=0;return e=ut(e,(function(e){if(Bs(e))return t=an(e.length,t),!0})),Nt(t,(function(t){return pt(e,Tt(t))}))}function Gi(e,t){if(!e||!e.length)return[];var n=Yi(e);return null==t?n:pt(n,(function(e){return ot(t,void 0,e)}))}var Ji=qr((function(e,t){return Bs(e)?er(e,t):[]})),Xi=qr((function(e){return oo(ut(e,Bs))})),Zi=qr((function(e){var t=Ui(e);return Bs(t)&&(t=void 0),oo(ut(e,Bs),Zo(t,2))})),Qi=qr((function(e){var t=Ui(e);return t="function"==typeof t?t:void 0,oo(ut(e,Bs),void 0,t)})),es=qr(Yi);var ts=qr((function(e){var t=e.length,n=t>1?e[t-1]:void 0;return n="function"==typeof n?(e.pop(),n):void 0,Gi(e,n)}));function ns(e){var t=In(e);return t.__chain__=!0,t}function rs(e,t){return t(e)}var os=Ko((function(e){var t=e.length,n=t?e[0]:0,r=this.__wrapped__,o=function(t){return Gn(t,e)};return!(t>1||this.__actions__.length)&&r instanceof Rn&&ci(n)?((r=r.slice(n,+n+(t?1:0))).__actions__.push({func:rs,args:[o],thisArg:void 0}),new Mn(r,this.__chain__).thru((function(e){return t&&!e.length&&e.push(void 0),e}))):this.thru(o)}));var is=wo((function(e,t,n){Oe.call(e,n)?++e[n]:Yn(e,n,1)}));var ss=No(Ri),as=No(ji);function cs(e,t){return(js(e)?st:tr)(e,Zo(t,3))}function us(e,t){return(js(e)?at:nr)(e,Zo(t,3))}var ls=wo((function(e,t,n){Oe.call(e,n)?e[n].push(t):Yn(e,n,[t])}));var fs=qr((function(e,t,n){var o=-1,i="function"==typeof t,s=Ps(e)?r(e.length):[];return tr(e,(function(e){s[++o]=i?ot(t,e,n):vr(e,t,n)})),s})),ps=wo((function(e,t,n){Yn(e,n,t)}));function ds(e,t){return(js(e)?pt:Nr)(e,Zo(t,3))}var hs=wo((function(e,t,n){e[n?0:1].push(t)}),(function(){return[[],[]]}));var ms=qr((function(e,t){if(null==e)return[];var n=t.length;return n>1&&ui(e,t[0],t[1])?t=[]:n>2&&ui(t[0],t[1],t[2])&&(t=[t[0]]),Rr(e,sr(t,1),[])})),gs=Xt||function(){return Ke.Date.now()};function ys(e,t,n){return t=n?void 0:t,zo(e,128,void 0,void 0,void 0,void 0,t=e&&null==t?e.length:t)}function bs(e,t){var n;if("function"!=typeof t)throw new ye(o);return e=oa(e),function(){return--e>0&&(n=t.apply(this,arguments)),e<=1&&(t=void 0),n}}var vs=qr((function(e,t,n){var r=1;if(n.length){var o=$t(n,Xo(vs));r|=32}return zo(e,r,t,n,o)})),Ss=qr((function(e,t,n){var r=3;if(n.length){var o=$t(n,Xo(Ss));r|=32}return zo(t,r,e,n,o)}));function ws(e,t,n){var r,i,s,a,c,u,l=0,f=!1,p=!1,d=!0;if("function"!=typeof e)throw new ye(o);function h(t){var n=r,o=i;return r=i=void 0,l=t,a=e.apply(o,n)}function m(e){return l=e,c=wi(y,t),f?h(e):a}function g(e){var n=e-u;return void 0===u||n>=t||n<0||p&&e-l>=s}function y(){var e=gs();if(g(e))return b(e);c=wi(y,function(e){var n=t-(e-u);return p?cn(n,s-(e-l)):n}(e))}function b(e){return c=void 0,d&&r?h(e):(r=i=void 0,a)}function v(){var e=gs(),n=g(e);if(r=arguments,i=this,u=e,n){if(void 0===c)return m(u);if(p)return fo(c),c=wi(y,t),h(u)}return void 0===c&&(c=wi(y,t)),a}return t=sa(t)||0,Fs(n)&&(f=!!n.leading,s=(p="maxWait"in n)?an(sa(n.maxWait)||0,t):s,d="trailing"in n?!!n.trailing:d),v.cancel=function(){void 0!==c&&fo(c),l=0,r=u=i=c=void 0},v.flush=function(){return void 0===c?a:b(gs())},v}var _s=qr((function(e,t){return Qn(e,1,t)})),Os=qr((function(e,t,n){return Qn(e,sa(t)||0,n)}));function Ts(e,t){if("function"!=typeof e||null!=t&&"function"!=typeof t)throw new ye(o);var n=function(){var r=arguments,o=t?t.apply(this,r):r[0],i=n.cache;if(i.has(o))return i.get(o);var s=e.apply(this,r);return n.cache=i.set(o,s)||i,s};return n.cache=new(Ts.Cache||Pn),n}function Cs(e){if("function"!=typeof e)throw new ye(o);return function(){var t=arguments;switch(t.length){case 0:return!e.call(this);case 1:return!e.call(this,t[0]);case 2:return!e.call(this,t[0],t[1]);case 3:return!e.call(this,t[0],t[1],t[2])}return!e.apply(this,t)}}Ts.Cache=Pn;var xs=uo((function(e,t){var n=(t=1==t.length&&js(t[0])?pt(t[0],At(Zo())):pt(sr(t,1),At(Zo()))).length;return qr((function(r){for(var o=-1,i=cn(r.length,n);++o<i;)r[o]=t[o].call(this,r[o]);return ot(e,this,r)}))})),Es=qr((function(e,t){return zo(e,32,void 0,t,$t(t,Xo(Es)))})),Ns=qr((function(e,t){return zo(e,64,void 0,t,$t(t,Xo(Ns)))})),Is=Ko((function(e,t){return zo(e,256,void 0,void 0,void 0,t)}));function As(e,t){return e===t||e!=e&&t!=t}var ks=Po(mr),Ms=Po((function(e,t){return e>=t})),Rs=Sr(function(){return arguments}())?Sr:function(e){return Vs(e)&&Oe.call(e,"callee")&&!He.call(e,"callee")},js=r.isArray,Ds=Ze?At(Ze):function(e){return Vs(e)&&hr(e)==_};function Ps(e){return null!=e&&Ws(e.length)&&!zs(e)}function Bs(e){return Vs(e)&&Ps(e)}var Ls=nn||sc,qs=Qe?At(Qe):function(e){return Vs(e)&&hr(e)==l};function Us(e){if(!Vs(e))return!1;var t=hr(e);return t==f||"[object DOMException]"==t||"string"==typeof e.message&&"string"==typeof e.name&&!Ys(e)}function zs(e){if(!Fs(e))return!1;var t=hr(e);return t==p||t==d||"[object AsyncFunction]"==t||"[object Proxy]"==t}function $s(e){return"number"==typeof e&&e==oa(e)}function Ws(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=9007199254740991}function Fs(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}function Vs(e){return null!=e&&"object"==typeof e}var Ks=et?At(et):function(e){return Vs(e)&&oi(e)==h};function Hs(e){return"number"==typeof e||Vs(e)&&hr(e)==m}function Ys(e){if(!Vs(e)||hr(e)!=g)return!1;var t=Fe(e);if(null===t)return!0;var n=Oe.call(t,"constructor")&&t.constructor;return"function"==typeof n&&n instanceof n&&_e.call(n)==Ee}var Gs=tt?At(tt):function(e){return Vs(e)&&hr(e)==y};var Js=nt?At(nt):function(e){return Vs(e)&&oi(e)==b};function Xs(e){return"string"==typeof e||!js(e)&&Vs(e)&&hr(e)==v}function Zs(e){return"symbol"==typeof e||Vs(e)&&hr(e)==S}var Qs=rt?At(rt):function(e){return Vs(e)&&Ws(e.length)&&!!qe[hr(e)]};var ea=Po(Er),ta=Po((function(e,t){return e<=t}));function na(e){if(!e)return[];if(Ps(e))return Xs(e)?Kt(e):vo(e);if(Xe&&e[Xe])return function(e){for(var t,n=[];!(t=e.next()).done;)n.push(t.value);return n}(e[Xe]());var t=oi(e);return(t==h?Ut:t==b?Wt:Aa)(e)}function ra(e){return e?(e=sa(e))===1/0||e===-1/0?17976931348623157e292*(e<0?-1:1):e==e?e:0:0===e?e:0}function oa(e){var t=ra(e),n=t%1;return t==t?n?t-n:t:0}function ia(e){return e?Jn(oa(e),0,4294967295):0}function sa(e){if("number"==typeof e)return e;if(Zs(e))return NaN;if(Fs(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=Fs(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=It(e);var n=oe.test(e);return n||se.test(e)?We(e.slice(2),n?2:8):re.test(e)?NaN:+e}function aa(e){return So(e,_a(e))}function ca(e){return null==e?"":Zr(e)}var ua=_o((function(e,t){if(di(t)||Ps(t))So(t,wa(t),e);else for(var n in t)Oe.call(t,n)&&Fn(e,n,t[n])})),la=_o((function(e,t){So(t,_a(t),e)})),fa=_o((function(e,t,n,r){So(t,_a(t),e,r)})),pa=_o((function(e,t,n,r){So(t,wa(t),e,r)})),da=Ko(Gn);var ha=qr((function(e,t){e=he(e);var n=-1,r=t.length,o=r>2?t[2]:void 0;for(o&&ui(t[0],t[1],o)&&(r=1);++n<r;)for(var i=t[n],s=_a(i),a=-1,c=s.length;++a<c;){var u=s[a],l=e[u];(void 0===l||As(l,Se[u])&&!Oe.call(e,u))&&(e[u]=i[u])}return e})),ma=qr((function(e){return e.push(void 0,Wo),ot(Ta,void 0,e)}));function ga(e,t,n){var r=null==e?void 0:pr(e,t);return void 0===r?n:r}function ya(e,t){return null!=e&&ii(e,t,yr)}var ba=ko((function(e,t,n){null!=t&&"function"!=typeof t.toString&&(t=xe.call(t)),e[t]=n}),Fa(Ha)),va=ko((function(e,t,n){null!=t&&"function"!=typeof t.toString&&(t=xe.call(t)),Oe.call(e,t)?e[t].push(n):e[t]=[n]}),Zo),Sa=qr(vr);function wa(e){return Ps(e)?qn(e):Cr(e)}function _a(e){return Ps(e)?qn(e,!0):xr(e)}var Oa=_o((function(e,t,n){kr(e,t,n)})),Ta=_o((function(e,t,n,r){kr(e,t,n,r)})),Ca=Ko((function(e,t){var n={};if(null==e)return n;var r=!1;t=pt(t,(function(t){return t=co(t,e),r||(r=t.length>1),t})),So(e,Yo(e),n),r&&(n=Xn(n,7,Fo));for(var o=t.length;o--;)eo(n,t[o]);return n}));var xa=Ko((function(e,t){return null==e?{}:function(e,t){return jr(e,t,(function(t,n){return ya(e,n)}))}(e,t)}));function Ea(e,t){if(null==e)return{};var n=pt(Yo(e),(function(e){return[e]}));return t=Zo(t),jr(e,n,(function(e,n){return t(e,n[0])}))}var Na=Uo(wa),Ia=Uo(_a);function Aa(e){return null==e?[]:kt(e,wa(e))}var ka=xo((function(e,t,n){return t=t.toLowerCase(),e+(n?Ma(t):t)}));function Ma(e){return Ua(ca(e).toLowerCase())}function Ra(e){return(e=ca(e))&&e.replace(ce,Pt).replace(Me,"")}var ja=xo((function(e,t,n){return e+(n?"-":"")+t.toLowerCase()})),Da=xo((function(e,t,n){return e+(n?" ":"")+t.toLowerCase()})),Pa=Co("toLowerCase");var Ba=xo((function(e,t,n){return e+(n?"_":"")+t.toLowerCase()}));var La=xo((function(e,t,n){return e+(n?" ":"")+Ua(t)}));var qa=xo((function(e,t,n){return e+(n?" ":"")+t.toUpperCase()})),Ua=Co("toUpperCase");function za(e,t,n){return e=ca(e),void 0===(t=n?void 0:t)?function(e){return Pe.test(e)}(e)?function(e){return e.match(je)||[]}(e):function(e){return e.match(Z)||[]}(e):e.match(t)||[]}var $a=qr((function(e,t){try{return ot(e,void 0,t)}catch(e){return Us(e)?e:new fe(e)}})),Wa=Ko((function(e,t){return st(t,(function(t){t=Ei(t),Yn(e,t,vs(e[t],e))})),e}));function Fa(e){return function(){return e}}var Va=Io(),Ka=Io(!0);function Ha(e){return e}function Ya(e){return Tr("function"==typeof e?e:Xn(e,1))}var Ga=qr((function(e,t){return function(n){return vr(n,e,t)}})),Ja=qr((function(e,t){return function(n){return vr(e,n,t)}}));function Xa(e,t,n){var r=wa(t),o=fr(t,r);null!=n||Fs(t)&&(o.length||!r.length)||(n=t,t=e,e=this,o=fr(t,wa(t)));var i=!(Fs(n)&&"chain"in n&&!n.chain),s=zs(e);return st(o,(function(n){var r=t[n];e[n]=r,s&&(e.prototype[n]=function(){var t=this.__chain__;if(i||t){var n=e(this.__wrapped__),o=n.__actions__=vo(this.__actions__);return o.push({func:r,args:arguments,thisArg:e}),n.__chain__=t,n}return r.apply(e,dt([this.value()],arguments))})})),e}function Za(){}var Qa=Ro(pt),ec=Ro(ct),tc=Ro(gt);function nc(e){return li(e)?Tt(Ei(e)):function(e){return function(t){return pr(t,e)}}(e)}var rc=Do(),oc=Do(!0);function ic(){return[]}function sc(){return!1}var ac=Mo((function(e,t){return e+t}),0),cc=Lo("ceil"),uc=Mo((function(e,t){return e/t}),1),lc=Lo("floor");var fc,pc=Mo((function(e,t){return e*t}),1),dc=Lo("round"),hc=Mo((function(e,t){return e-t}),0);return In.after=function(e,t){if("function"!=typeof t)throw new ye(o);return e=oa(e),function(){if(--e<1)return t.apply(this,arguments)}},In.ary=ys,In.assign=ua,In.assignIn=la,In.assignInWith=fa,In.assignWith=pa,In.at=da,In.before=bs,In.bind=vs,In.bindAll=Wa,In.bindKey=Ss,In.castArray=function(){if(!arguments.length)return[];var e=arguments[0];return js(e)?e:[e]},In.chain=ns,In.chunk=function(e,t,n){t=(n?ui(e,t,n):void 0===t)?1:an(oa(t),0);var o=null==e?0:e.length;if(!o||t<1)return[];for(var i=0,s=0,a=r(Qt(o/t));i<o;)a[s++]=Kr(e,i,i+=t);return a},In.compact=function(e){for(var t=-1,n=null==e?0:e.length,r=0,o=[];++t<n;){var i=e[t];i&&(o[r++]=i)}return o},In.concat=function(){var e=arguments.length;if(!e)return[];for(var t=r(e-1),n=arguments[0],o=e;o--;)t[o-1]=arguments[o];return dt(js(n)?vo(n):[n],sr(t,1))},In.cond=function(e){var t=null==e?0:e.length,n=Zo();return e=t?pt(e,(function(e){if("function"!=typeof e[1])throw new ye(o);return[n(e[0]),e[1]]})):[],qr((function(n){for(var r=-1;++r<t;){var o=e[r];if(ot(o[0],this,n))return ot(o[1],this,n)}}))},In.conforms=function(e){return function(e){var t=wa(e);return function(n){return Zn(n,e,t)}}(Xn(e,1))},In.constant=Fa,In.countBy=is,In.create=function(e,t){var n=An(e);return null==t?n:Hn(n,t)},In.curry=function e(t,n,r){var o=zo(t,8,void 0,void 0,void 0,void 0,void 0,n=r?void 0:n);return o.placeholder=e.placeholder,o},In.curryRight=function e(t,n,r){var o=zo(t,16,void 0,void 0,void 0,void 0,void 0,n=r?void 0:n);return o.placeholder=e.placeholder,o},In.debounce=ws,In.defaults=ha,In.defaultsDeep=ma,In.defer=_s,In.delay=Os,In.difference=Ai,In.differenceBy=ki,In.differenceWith=Mi,In.drop=function(e,t,n){var r=null==e?0:e.length;return r?Kr(e,(t=n||void 0===t?1:oa(t))<0?0:t,r):[]},In.dropRight=function(e,t,n){var r=null==e?0:e.length;return r?Kr(e,0,(t=r-(t=n||void 0===t?1:oa(t)))<0?0:t):[]},In.dropRightWhile=function(e,t){return e&&e.length?no(e,Zo(t,3),!0,!0):[]},In.dropWhile=function(e,t){return e&&e.length?no(e,Zo(t,3),!0):[]},In.fill=function(e,t,n,r){var o=null==e?0:e.length;return o?(n&&"number"!=typeof n&&ui(e,t,n)&&(n=0,r=o),function(e,t,n,r){var o=e.length;for((n=oa(n))<0&&(n=-n>o?0:o+n),(r=void 0===r||r>o?o:oa(r))<0&&(r+=o),r=n>r?0:ia(r);n<r;)e[n++]=t;return e}(e,t,n,r)):[]},In.filter=function(e,t){return(js(e)?ut:ir)(e,Zo(t,3))},In.flatMap=function(e,t){return sr(ds(e,t),1)},In.flatMapDeep=function(e,t){return sr(ds(e,t),1/0)},In.flatMapDepth=function(e,t,n){return n=void 0===n?1:oa(n),sr(ds(e,t),n)},In.flatten=Di,In.flattenDeep=function(e){return(null==e?0:e.length)?sr(e,1/0):[]},In.flattenDepth=function(e,t){return(null==e?0:e.length)?sr(e,t=void 0===t?1:oa(t)):[]},In.flip=function(e){return zo(e,512)},In.flow=Va,In.flowRight=Ka,In.fromPairs=function(e){for(var t=-1,n=null==e?0:e.length,r={};++t<n;){var o=e[t];r[o[0]]=o[1]}return r},In.functions=function(e){return null==e?[]:fr(e,wa(e))},In.functionsIn=function(e){return null==e?[]:fr(e,_a(e))},In.groupBy=ls,In.initial=function(e){return(null==e?0:e.length)?Kr(e,0,-1):[]},In.intersection=Bi,In.intersectionBy=Li,In.intersectionWith=qi,In.invert=ba,In.invertBy=va,In.invokeMap=fs,In.iteratee=Ya,In.keyBy=ps,In.keys=wa,In.keysIn=_a,In.map=ds,In.mapKeys=function(e,t){var n={};return t=Zo(t,3),ur(e,(function(e,r,o){Yn(n,t(e,r,o),e)})),n},In.mapValues=function(e,t){var n={};return t=Zo(t,3),ur(e,(function(e,r,o){Yn(n,r,t(e,r,o))})),n},In.matches=function(e){return Ir(Xn(e,1))},In.matchesProperty=function(e,t){return Ar(e,Xn(t,1))},In.memoize=Ts,In.merge=Oa,In.mergeWith=Ta,In.method=Ga,In.methodOf=Ja,In.mixin=Xa,In.negate=Cs,In.nthArg=function(e){return e=oa(e),qr((function(t){return Mr(t,e)}))},In.omit=Ca,In.omitBy=function(e,t){return Ea(e,Cs(Zo(t)))},In.once=function(e){return bs(2,e)},In.orderBy=function(e,t,n,r){return null==e?[]:(js(t)||(t=null==t?[]:[t]),js(n=r?void 0:n)||(n=null==n?[]:[n]),Rr(e,t,n))},In.over=Qa,In.overArgs=xs,In.overEvery=ec,In.overSome=tc,In.partial=Es,In.partialRight=Ns,In.partition=hs,In.pick=xa,In.pickBy=Ea,In.property=nc,In.propertyOf=function(e){return function(t){return null==e?void 0:pr(e,t)}},In.pull=zi,In.pullAll=$i,In.pullAllBy=function(e,t,n){return e&&e.length&&t&&t.length?Dr(e,t,Zo(n,2)):e},In.pullAllWith=function(e,t,n){return e&&e.length&&t&&t.length?Dr(e,t,void 0,n):e},In.pullAt=Wi,In.range=rc,In.rangeRight=oc,In.rearg=Is,In.reject=function(e,t){return(js(e)?ut:ir)(e,Cs(Zo(t,3)))},In.remove=function(e,t){var n=[];if(!e||!e.length)return n;var r=-1,o=[],i=e.length;for(t=Zo(t,3);++r<i;){var s=e[r];t(s,r,e)&&(n.push(s),o.push(r))}return Pr(e,o),n},In.rest=function(e,t){if("function"!=typeof e)throw new ye(o);return qr(e,t=void 0===t?t:oa(t))},In.reverse=Fi,In.sampleSize=function(e,t,n){return t=(n?ui(e,t,n):void 0===t)?1:oa(t),(js(e)?zn:zr)(e,t)},In.set=function(e,t,n){return null==e?e:$r(e,t,n)},In.setWith=function(e,t,n,r){return r="function"==typeof r?r:void 0,null==e?e:$r(e,t,n,r)},In.shuffle=function(e){return(js(e)?$n:Vr)(e)},In.slice=function(e,t,n){var r=null==e?0:e.length;return r?(n&&"number"!=typeof n&&ui(e,t,n)?(t=0,n=r):(t=null==t?0:oa(t),n=void 0===n?r:oa(n)),Kr(e,t,n)):[]},In.sortBy=ms,In.sortedUniq=function(e){return e&&e.length?Jr(e):[]},In.sortedUniqBy=function(e,t){return e&&e.length?Jr(e,Zo(t,2)):[]},In.split=function(e,t,n){return n&&"number"!=typeof n&&ui(e,t,n)&&(t=n=void 0),(n=void 0===n?4294967295:n>>>0)?(e=ca(e))&&("string"==typeof t||null!=t&&!Gs(t))&&!(t=Zr(t))&&qt(e)?lo(Kt(e),0,n):e.split(t,n):[]},In.spread=function(e,t){if("function"!=typeof e)throw new ye(o);return t=null==t?0:an(oa(t),0),qr((function(n){var r=n[t],o=lo(n,0,t);return r&&dt(o,r),ot(e,this,o)}))},In.tail=function(e){var t=null==e?0:e.length;return t?Kr(e,1,t):[]},In.take=function(e,t,n){return e&&e.length?Kr(e,0,(t=n||void 0===t?1:oa(t))<0?0:t):[]},In.takeRight=function(e,t,n){var r=null==e?0:e.length;return r?Kr(e,(t=r-(t=n||void 0===t?1:oa(t)))<0?0:t,r):[]},In.takeRightWhile=function(e,t){return e&&e.length?no(e,Zo(t,3),!1,!0):[]},In.takeWhile=function(e,t){return e&&e.length?no(e,Zo(t,3)):[]},In.tap=function(e,t){return t(e),e},In.throttle=function(e,t,n){var r=!0,i=!0;if("function"!=typeof e)throw new ye(o);return Fs(n)&&(r="leading"in n?!!n.leading:r,i="trailing"in n?!!n.trailing:i),ws(e,t,{leading:r,maxWait:t,trailing:i})},In.thru=rs,In.toArray=na,In.toPairs=Na,In.toPairsIn=Ia,In.toPath=function(e){return js(e)?pt(e,Ei):Zs(e)?[e]:vo(xi(ca(e)))},In.toPlainObject=aa,In.transform=function(e,t,n){var r=js(e),o=r||Ls(e)||Qs(e);if(t=Zo(t,4),null==n){var i=e&&e.constructor;n=o?r?new i:[]:Fs(e)&&zs(i)?An(Fe(e)):{}}return(o?st:ur)(e,(function(e,r,o){return t(n,e,r,o)})),n},In.unary=function(e){return ys(e,1)},In.union=Vi,In.unionBy=Ki,In.unionWith=Hi,In.uniq=function(e){return e&&e.length?Qr(e):[]},In.uniqBy=function(e,t){return e&&e.length?Qr(e,Zo(t,2)):[]},In.uniqWith=function(e,t){return t="function"==typeof t?t:void 0,e&&e.length?Qr(e,void 0,t):[]},In.unset=function(e,t){return null==e||eo(e,t)},In.unzip=Yi,In.unzipWith=Gi,In.update=function(e,t,n){return null==e?e:to(e,t,ao(n))},In.updateWith=function(e,t,n,r){return r="function"==typeof r?r:void 0,null==e?e:to(e,t,ao(n),r)},In.values=Aa,In.valuesIn=function(e){return null==e?[]:kt(e,_a(e))},In.without=Ji,In.words=za,In.wrap=function(e,t){return Es(ao(t),e)},In.xor=Xi,In.xorBy=Zi,In.xorWith=Qi,In.zip=es,In.zipObject=function(e,t){return io(e||[],t||[],Fn)},In.zipObjectDeep=function(e,t){return io(e||[],t||[],$r)},In.zipWith=ts,In.entries=Na,In.entriesIn=Ia,In.extend=la,In.extendWith=fa,Xa(In,In),In.add=ac,In.attempt=$a,In.camelCase=ka,In.capitalize=Ma,In.ceil=cc,In.clamp=function(e,t,n){return void 0===n&&(n=t,t=void 0),void 0!==n&&(n=(n=sa(n))==n?n:0),void 0!==t&&(t=(t=sa(t))==t?t:0),Jn(sa(e),t,n)},In.clone=function(e){return Xn(e,4)},In.cloneDeep=function(e){return Xn(e,5)},In.cloneDeepWith=function(e,t){return Xn(e,5,t="function"==typeof t?t:void 0)},In.cloneWith=function(e,t){return Xn(e,4,t="function"==typeof t?t:void 0)},In.conformsTo=function(e,t){return null==t||Zn(e,t,wa(t))},In.deburr=Ra,In.defaultTo=function(e,t){return null==e||e!=e?t:e},In.divide=uc,In.endsWith=function(e,t,n){e=ca(e),t=Zr(t);var r=e.length,o=n=void 0===n?r:Jn(oa(n),0,r);return(n-=t.length)>=0&&e.slice(n,o)==t},In.eq=As,In.escape=function(e){return(e=ca(e))&&L.test(e)?e.replace(P,Bt):e},In.escapeRegExp=function(e){return(e=ca(e))&&K.test(e)?e.replace(V,"\\$&"):e},In.every=function(e,t,n){var r=js(e)?ct:rr;return n&&ui(e,t,n)&&(t=void 0),r(e,Zo(t,3))},In.find=ss,In.findIndex=Ri,In.findKey=function(e,t){return bt(e,Zo(t,3),ur)},In.findLast=as,In.findLastIndex=ji,In.findLastKey=function(e,t){return bt(e,Zo(t,3),lr)},In.floor=lc,In.forEach=cs,In.forEachRight=us,In.forIn=function(e,t){return null==e?e:ar(e,Zo(t,3),_a)},In.forInRight=function(e,t){return null==e?e:cr(e,Zo(t,3),_a)},In.forOwn=function(e,t){return e&&ur(e,Zo(t,3))},In.forOwnRight=function(e,t){return e&&lr(e,Zo(t,3))},In.get=ga,In.gt=ks,In.gte=Ms,In.has=function(e,t){return null!=e&&ii(e,t,gr)},In.hasIn=ya,In.head=Pi,In.identity=Ha,In.includes=function(e,t,n,r){e=Ps(e)?e:Aa(e),n=n&&!r?oa(n):0;var o=e.length;return n<0&&(n=an(o+n,0)),Xs(e)?n<=o&&e.indexOf(t,n)>-1:!!o&&St(e,t,n)>-1},In.indexOf=function(e,t,n){var r=null==e?0:e.length;if(!r)return-1;var o=null==n?0:oa(n);return o<0&&(o=an(r+o,0)),St(e,t,o)},In.inRange=function(e,t,n){return t=ra(t),void 0===n?(n=t,t=0):n=ra(n),function(e,t,n){return e>=cn(t,n)&&e<an(t,n)}(e=sa(e),t,n)},In.invoke=Sa,In.isArguments=Rs,In.isArray=js,In.isArrayBuffer=Ds,In.isArrayLike=Ps,In.isArrayLikeObject=Bs,In.isBoolean=function(e){return!0===e||!1===e||Vs(e)&&hr(e)==u},In.isBuffer=Ls,In.isDate=qs,In.isElement=function(e){return Vs(e)&&1===e.nodeType&&!Ys(e)},In.isEmpty=function(e){if(null==e)return!0;if(Ps(e)&&(js(e)||"string"==typeof e||"function"==typeof e.splice||Ls(e)||Qs(e)||Rs(e)))return!e.length;var t=oi(e);if(t==h||t==b)return!e.size;if(di(e))return!Cr(e).length;for(var n in e)if(Oe.call(e,n))return!1;return!0},In.isEqual=function(e,t){return wr(e,t)},In.isEqualWith=function(e,t,n){var r=(n="function"==typeof n?n:void 0)?n(e,t):void 0;return void 0===r?wr(e,t,void 0,n):!!r},In.isError=Us,In.isFinite=function(e){return"number"==typeof e&&rn(e)},In.isFunction=zs,In.isInteger=$s,In.isLength=Ws,In.isMap=Ks,In.isMatch=function(e,t){return e===t||_r(e,t,ei(t))},In.isMatchWith=function(e,t,n){return n="function"==typeof n?n:void 0,_r(e,t,ei(t),n)},In.isNaN=function(e){return Hs(e)&&e!=+e},In.isNative=function(e){if(pi(e))throw new fe("Unsupported core-js use. Try https://npms.io/search?q=ponyfill.");return Or(e)},In.isNil=function(e){return null==e},In.isNull=function(e){return null===e},In.isNumber=Hs,In.isObject=Fs,In.isObjectLike=Vs,In.isPlainObject=Ys,In.isRegExp=Gs,In.isSafeInteger=function(e){return $s(e)&&e>=-9007199254740991&&e<=9007199254740991},In.isSet=Js,In.isString=Xs,In.isSymbol=Zs,In.isTypedArray=Qs,In.isUndefined=function(e){return void 0===e},In.isWeakMap=function(e){return Vs(e)&&oi(e)==w},In.isWeakSet=function(e){return Vs(e)&&"[object WeakSet]"==hr(e)},In.join=function(e,t){return null==e?"":on.call(e,t)},In.kebabCase=ja,In.last=Ui,In.lastIndexOf=function(e,t,n){var r=null==e?0:e.length;if(!r)return-1;var o=r;return void 0!==n&&(o=(o=oa(n))<0?an(r+o,0):cn(o,r-1)),t==t?function(e,t,n){for(var r=n+1;r--;)if(e[r]===t)return r;return r}(e,t,o):vt(e,_t,o,!0)},In.lowerCase=Da,In.lowerFirst=Pa,In.lt=ea,In.lte=ta,In.max=function(e){return e&&e.length?or(e,Ha,mr):void 0},In.maxBy=function(e,t){return e&&e.length?or(e,Zo(t,2),mr):void 0},In.mean=function(e){return Ot(e,Ha)},In.meanBy=function(e,t){return Ot(e,Zo(t,2))},In.min=function(e){return e&&e.length?or(e,Ha,Er):void 0},In.minBy=function(e,t){return e&&e.length?or(e,Zo(t,2),Er):void 0},In.stubArray=ic,In.stubFalse=sc,In.stubObject=function(){return{}},In.stubString=function(){return""},In.stubTrue=function(){return!0},In.multiply=pc,In.nth=function(e,t){return e&&e.length?Mr(e,oa(t)):void 0},In.noConflict=function(){return Ke._===this&&(Ke._=Ne),this},In.noop=Za,In.now=gs,In.pad=function(e,t,n){e=ca(e);var r=(t=oa(t))?Vt(e):0;if(!t||r>=t)return e;var o=(t-r)/2;return jo(en(o),n)+e+jo(Qt(o),n)},In.padEnd=function(e,t,n){e=ca(e);var r=(t=oa(t))?Vt(e):0;return t&&r<t?e+jo(t-r,n):e},In.padStart=function(e,t,n){e=ca(e);var r=(t=oa(t))?Vt(e):0;return t&&r<t?jo(t-r,n)+e:e},In.parseInt=function(e,t,n){return n||null==t?t=0:t&&(t=+t),ln(ca(e).replace(H,""),t||0)},In.random=function(e,t,n){if(n&&"boolean"!=typeof n&&ui(e,t,n)&&(t=n=void 0),void 0===n&&("boolean"==typeof t?(n=t,t=void 0):"boolean"==typeof e&&(n=e,e=void 0)),void 0===e&&void 0===t?(e=0,t=1):(e=ra(e),void 0===t?(t=e,e=0):t=ra(t)),e>t){var r=e;e=t,t=r}if(n||e%1||t%1){var o=fn();return cn(e+o*(t-e+$e("1e-"+((o+"").length-1))),t)}return Br(e,t)},In.reduce=function(e,t,n){var r=js(e)?ht:xt,o=arguments.length<3;return r(e,Zo(t,4),n,o,tr)},In.reduceRight=function(e,t,n){var r=js(e)?mt:xt,o=arguments.length<3;return r(e,Zo(t,4),n,o,nr)},In.repeat=function(e,t,n){return t=(n?ui(e,t,n):void 0===t)?1:oa(t),Lr(ca(e),t)},In.replace=function(){var e=arguments,t=ca(e[0]);return e.length<3?t:t.replace(e[1],e[2])},In.result=function(e,t,n){var r=-1,o=(t=co(t,e)).length;for(o||(o=1,e=void 0);++r<o;){var i=null==e?void 0:e[Ei(t[r])];void 0===i&&(r=o,i=n),e=zs(i)?i.call(e):i}return e},In.round=dc,In.runInContext=e,In.sample=function(e){return(js(e)?Un:Ur)(e)},In.size=function(e){if(null==e)return 0;if(Ps(e))return Xs(e)?Vt(e):e.length;var t=oi(e);return t==h||t==b?e.size:Cr(e).length},In.snakeCase=Ba,In.some=function(e,t,n){var r=js(e)?gt:Hr;return n&&ui(e,t,n)&&(t=void 0),r(e,Zo(t,3))},In.sortedIndex=function(e,t){return Yr(e,t)},In.sortedIndexBy=function(e,t,n){return Gr(e,t,Zo(n,2))},In.sortedIndexOf=function(e,t){var n=null==e?0:e.length;if(n){var r=Yr(e,t);if(r<n&&As(e[r],t))return r}return-1},In.sortedLastIndex=function(e,t){return Yr(e,t,!0)},In.sortedLastIndexBy=function(e,t,n){return Gr(e,t,Zo(n,2),!0)},In.sortedLastIndexOf=function(e,t){if(null==e?0:e.length){var n=Yr(e,t,!0)-1;if(As(e[n],t))return n}return-1},In.startCase=La,In.startsWith=function(e,t,n){return e=ca(e),n=null==n?0:Jn(oa(n),0,e.length),t=Zr(t),e.slice(n,n+t.length)==t},In.subtract=hc,In.sum=function(e){return e&&e.length?Et(e,Ha):0},In.sumBy=function(e,t){return e&&e.length?Et(e,Zo(t,2)):0},In.template=function(e,t,n){var r=In.templateSettings;n&&ui(e,t,n)&&(t=void 0),e=ca(e),t=fa({},t,r,$o);var o,i,s=fa({},t.imports,r.imports,$o),a=wa(s),c=kt(s,a),u=0,l=t.interpolate||ue,f="__p += '",p=me((t.escape||ue).source+"|"+l.source+"|"+(l===z?te:ue).source+"|"+(t.evaluate||ue).source+"|$","g"),d="//# sourceURL="+(Oe.call(t,"sourceURL")?(t.sourceURL+"").replace(/\s/g," "):"lodash.templateSources["+ ++Le+"]")+"\n";e.replace(p,(function(t,n,r,s,a,c){return r||(r=s),f+=e.slice(u,c).replace(le,Lt),n&&(o=!0,f+="' +\n__e("+n+") +\n'"),a&&(i=!0,f+="';\n"+a+";\n__p += '"),r&&(f+="' +\n((__t = ("+r+")) == null ? '' : __t) +\n'"),u=c+t.length,t})),f+="';\n";var h=Oe.call(t,"variable")&&t.variable;if(h){if(Q.test(h))throw new fe("Invalid `variable` option passed into `_.template`")}else f="with (obj) {\n"+f+"\n}\n";f=(i?f.replace(M,""):f).replace(R,"$1").replace(j,"$1;"),f="function("+(h||"obj")+") {\n"+(h?"":"obj || (obj = {});\n")+"var __t, __p = ''"+(o?", __e = _.escape":"")+(i?", __j = Array.prototype.join;\nfunction print() { __p += __j.call(arguments, '') }\n":";\n")+f+"return __p\n}";var m=$a((function(){return pe(a,d+"return "+f).apply(void 0,c)}));if(m.source=f,Us(m))throw m;return m},In.times=function(e,t){if((e=oa(e))<1||e>9007199254740991)return[];var n=4294967295,r=cn(e,4294967295);e-=4294967295;for(var o=Nt(r,t=Zo(t));++n<e;)t(n);return o},In.toFinite=ra,In.toInteger=oa,In.toLength=ia,In.toLower=function(e){return ca(e).toLowerCase()},In.toNumber=sa,In.toSafeInteger=function(e){return e?Jn(oa(e),-9007199254740991,9007199254740991):0===e?e:0},In.toString=ca,In.toUpper=function(e){return ca(e).toUpperCase()},In.trim=function(e,t,n){if((e=ca(e))&&(n||void 0===t))return It(e);if(!e||!(t=Zr(t)))return e;var r=Kt(e),o=Kt(t);return lo(r,Rt(r,o),jt(r,o)+1).join("")},In.trimEnd=function(e,t,n){if((e=ca(e))&&(n||void 0===t))return e.slice(0,Ht(e)+1);if(!e||!(t=Zr(t)))return e;var r=Kt(e);return lo(r,0,jt(r,Kt(t))+1).join("")},In.trimStart=function(e,t,n){if((e=ca(e))&&(n||void 0===t))return e.replace(H,"");if(!e||!(t=Zr(t)))return e;var r=Kt(e);return lo(r,Rt(r,Kt(t))).join("")},In.truncate=function(e,t){var n=30,r="...";if(Fs(t)){var o="separator"in t?t.separator:o;n="length"in t?oa(t.length):n,r="omission"in t?Zr(t.omission):r}var i=(e=ca(e)).length;if(qt(e)){var s=Kt(e);i=s.length}if(n>=i)return e;var a=n-Vt(r);if(a<1)return r;var c=s?lo(s,0,a).join(""):e.slice(0,a);if(void 0===o)return c+r;if(s&&(a+=c.length-a),Gs(o)){if(e.slice(a).search(o)){var u,l=c;for(o.global||(o=me(o.source,ca(ne.exec(o))+"g")),o.lastIndex=0;u=o.exec(l);)var f=u.index;c=c.slice(0,void 0===f?a:f)}}else if(e.indexOf(Zr(o),a)!=a){var p=c.lastIndexOf(o);p>-1&&(c=c.slice(0,p))}return c+r},In.unescape=function(e){return(e=ca(e))&&B.test(e)?e.replace(D,Yt):e},In.uniqueId=function(e){var t=++Te;return ca(e)+t},In.upperCase=qa,In.upperFirst=Ua,In.each=cs,In.eachRight=us,In.first=Pi,Xa(In,(fc={},ur(In,(function(e,t){Oe.call(In.prototype,t)||(fc[t]=e)})),fc),{chain:!1}),In.VERSION="4.17.21",st(["bind","bindKey","curry","curryRight","partial","partialRight"],(function(e){In[e].placeholder=In})),st(["drop","take"],(function(e,t){Rn.prototype[e]=function(n){n=void 0===n?1:an(oa(n),0);var r=this.__filtered__&&!t?new Rn(this):this.clone();return r.__filtered__?r.__takeCount__=cn(n,r.__takeCount__):r.__views__.push({size:cn(n,4294967295),type:e+(r.__dir__<0?"Right":"")}),r},Rn.prototype[e+"Right"]=function(t){return this.reverse()[e](t).reverse()}})),st(["filter","map","takeWhile"],(function(e,t){var n=t+1,r=1==n||3==n;Rn.prototype[e]=function(e){var t=this.clone();return t.__iteratees__.push({iteratee:Zo(e,3),type:n}),t.__filtered__=t.__filtered__||r,t}})),st(["head","last"],(function(e,t){var n="take"+(t?"Right":"");Rn.prototype[e]=function(){return this[n](1).value()[0]}})),st(["initial","tail"],(function(e,t){var n="drop"+(t?"":"Right");Rn.prototype[e]=function(){return this.__filtered__?new Rn(this):this[n](1)}})),Rn.prototype.compact=function(){return this.filter(Ha)},Rn.prototype.find=function(e){return this.filter(e).head()},Rn.prototype.findLast=function(e){return this.reverse().find(e)},Rn.prototype.invokeMap=qr((function(e,t){return"function"==typeof e?new Rn(this):this.map((function(n){return vr(n,e,t)}))})),Rn.prototype.reject=function(e){return this.filter(Cs(Zo(e)))},Rn.prototype.slice=function(e,t){e=oa(e);var n=this;return n.__filtered__&&(e>0||t<0)?new Rn(n):(e<0?n=n.takeRight(-e):e&&(n=n.drop(e)),void 0!==t&&(n=(t=oa(t))<0?n.dropRight(-t):n.take(t-e)),n)},Rn.prototype.takeRightWhile=function(e){return this.reverse().takeWhile(e).reverse()},Rn.prototype.toArray=function(){return this.take(4294967295)},ur(Rn.prototype,(function(e,t){var n=/^(?:filter|find|map|reject)|While$/.test(t),r=/^(?:head|last)$/.test(t),o=In[r?"take"+("last"==t?"Right":""):t],i=r||/^find/.test(t);o&&(In.prototype[t]=function(){var t=this.__wrapped__,s=r?[1]:arguments,a=t instanceof Rn,c=s[0],u=a||js(t),l=function(e){var t=o.apply(In,dt([e],s));return r&&f?t[0]:t};u&&n&&"function"==typeof c&&1!=c.length&&(a=u=!1);var f=this.__chain__,p=!!this.__actions__.length,d=i&&!f,h=a&&!p;if(!i&&u){t=h?t:new Rn(this);var m=e.apply(t,s);return m.__actions__.push({func:rs,args:[l],thisArg:void 0}),new Mn(m,f)}return d&&h?e.apply(this,s):(m=this.thru(l),d?r?m.value()[0]:m.value():m)})})),st(["pop","push","shift","sort","splice","unshift"],(function(e){var t=be[e],n=/^(?:push|sort|unshift)$/.test(e)?"tap":"thru",r=/^(?:pop|shift)$/.test(e);In.prototype[e]=function(){var e=arguments;if(r&&!this.__chain__){var o=this.value();return t.apply(js(o)?o:[],e)}return this[n]((function(n){return t.apply(js(n)?n:[],e)}))}})),ur(Rn.prototype,(function(e,t){var n=In[t];if(n){var r=n.name+"";Oe.call(Sn,r)||(Sn[r]=[]),Sn[r].push({name:t,func:n})}})),Sn[Ao(void 0,2).name]=[{name:"wrapper",func:void 0}],Rn.prototype.clone=function(){var e=new Rn(this.__wrapped__);return e.__actions__=vo(this.__actions__),e.__dir__=this.__dir__,e.__filtered__=this.__filtered__,e.__iteratees__=vo(this.__iteratees__),e.__takeCount__=this.__takeCount__,e.__views__=vo(this.__views__),e},Rn.prototype.reverse=function(){if(this.__filtered__){var e=new Rn(this);e.__dir__=-1,e.__filtered__=!0}else(e=this.clone()).__dir__*=-1;return e},Rn.prototype.value=function(){var e=this.__wrapped__.value(),t=this.__dir__,n=js(e),r=t<0,o=n?e.length:0,i=function(e,t,n){var r=-1,o=n.length;for(;++r<o;){var i=n[r],s=i.size;switch(i.type){case"drop":e+=s;break;case"dropRight":t-=s;break;case"take":t=cn(t,e+s);break;case"takeRight":e=an(e,t-s)}}return{start:e,end:t}}(0,o,this.__views__),s=i.start,a=i.end,c=a-s,u=r?a:s-1,l=this.__iteratees__,f=l.length,p=0,d=cn(c,this.__takeCount__);if(!n||!r&&o==c&&d==c)return ro(e,this.__actions__);var h=[];e:for(;c--&&p<d;){for(var m=-1,g=e[u+=t];++m<f;){var y=l[m],b=y.iteratee,v=y.type,S=b(g);if(2==v)g=S;else if(!S){if(1==v)continue e;break e}}h[p++]=g}return h},In.prototype.at=os,In.prototype.chain=function(){return ns(this)},In.prototype.commit=function(){return new Mn(this.value(),this.__chain__)},In.prototype.next=function(){void 0===this.__values__&&(this.__values__=na(this.value()));var e=this.__index__>=this.__values__.length;return{done:e,value:e?void 0:this.__values__[this.__index__++]}},In.prototype.plant=function(e){for(var t,n=this;n instanceof kn;){var r=Ii(n);r.__index__=0,r.__values__=void 0,t?o.__wrapped__=r:t=r;var o=r;n=n.__wrapped__}return o.__wrapped__=e,t},In.prototype.reverse=function(){var e=this.__wrapped__;if(e instanceof Rn){var t=e;return this.__actions__.length&&(t=new Rn(this)),(t=t.reverse()).__actions__.push({func:rs,args:[Fi],thisArg:void 0}),new Mn(t,this.__chain__)}return this.thru(Fi)},In.prototype.toJSON=In.prototype.valueOf=In.prototype.value=function(){return ro(this.__wrapped__,this.__actions__)},In.prototype.first=In.prototype.head,Xe&&(In.prototype[Xe]=function(){return this}),In}();Ke._=Gt,void 0===(r=function(){return Gt}.call(t,n,t,e))||(e.exports=r)}).call(this)}).call(this,n(62)(e))},function(e,t,n){var r=n(36),o=n(248),i=n(249),s=r?r.toStringTag:void 0;e.exports=function(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":s&&s in Object(e)?o(e):i(e)}},function(e,t,n){"use strict";const r=n(18).Transform,o=n(18).PassThrough,i=n(5).deprecate,s=n(0).handleCallback,a=n(2).ReadPreference,c=n(2).MongoError,u=n(17).CoreCursor,l=n(17).CursorState,f=n(2).BSON.Map,p=n(0).maybePromise,d=n(56),h=n(0).formattedOrderClause,m=n(90).Explain,g=n(1).Aspect,y=n(448).each,b=n(449),v=["tailable","oplogReplay","noCursorTimeout","awaitData","exhaust","partial"],S=["numberOfRetries","tailableRetryInterval"];class w extends u{constructor(e,t,n,r){super(e,t,n,r),this.operation&&(r=this.operation.options);const o=r.numberOfRetries||5,i=r.tailableRetryInterval||500,s=o,a=r.promiseLibrary||Promise;this.s={numberOfRetries:o,tailableRetryInterval:i,currentNumberOfRetries:s,state:l.INIT,promiseLibrary:a,explicitlyIgnoreSession:!!r.explicitlyIgnoreSession},!r.explicitlyIgnoreSession&&r.session&&(this.cursorState.session=r.session),!0===this.options.noCursorTimeout&&this.addCursorFlag("noCursorTimeout",!0);let c=1e3;this.cmd.cursor&&this.cmd.cursor.batchSize?c=this.cmd.cursor.batchSize:r.cursor&&r.cursor.batchSize?c=r.cursor.batchSize:"number"==typeof r.batchSize&&(c=r.batchSize),this.setCursorBatchSize(c)}get readPreference(){return this.operation?this.operation.readPreference:this.options.readPreference}get sortValue(){return this.cmd.sort}_initializeCursor(e){this.operation&&null!=this.operation.session?this.cursorState.session=this.operation.session:this.s.explicitlyIgnoreSession||this.cursorState.session||!this.topology.hasSessionSupport()||(this.cursorState.session=this.topology.startSession({owner:this}),this.operation&&(this.operation.session=this.cursorState.session)),super._initializeCursor(e)}hasNext(e){if(this.s.state===l.CLOSED||this.isDead&&this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return p(this,e,e=>{const t=this;if(t.isNotified())return e(null,!1);t._next((n,r)=>n?e(n):null==r||t.s.state===w.CLOSED||t.isDead()?e(null,!1):(t.s.state=l.OPEN,t.cursorState.cursorIndex--,t.cursorState.limit>0&&t.cursorState.currentLimit--,void e(null,!0)))})}next(e){return p(this,e,e=>{const t=this;if(t.s.state===l.CLOSED||t.isDead&&t.isDead())e(c.create({message:"Cursor is closed",driver:!0}));else{if(t.s.state===l.INIT&&t.cmd.sort)try{t.cmd.sort=h(t.cmd.sort)}catch(t){return e(t)}t._next((n,r)=>{if(n)return e(n);t.s.state=l.OPEN,e(null,r)})}})}filter(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.query=e,this}maxScan(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.maxScan=e,this}hint(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.hint=e,this}min(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.min=e,this}max(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.max=e,this}returnKey(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.returnKey=e,this}showRecordId(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.showDiskLoc=e,this}snapshot(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.snapshot=e,this}setCursorOption(e,t){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});if(-1===S.indexOf(e))throw c.create({message:`option ${e} is not a supported option ${S}`,driver:!0});return this.s[e]=t,"numberOfRetries"===e&&(this.s.currentNumberOfRetries=t),this}addCursorFlag(e,t){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});if(-1===v.indexOf(e))throw c.create({message:`flag ${e} is not a supported flag ${v}`,driver:!0});if("boolean"!=typeof t)throw c.create({message:`flag ${e} must be a boolean value`,driver:!0});return this.cmd[e]=t,this}addQueryModifier(e,t){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});if("$"!==e[0])throw c.create({message:`${e} is not a valid query modifier`,driver:!0});const n=e.substr(1);return this.cmd[n]=t,"orderby"===n&&(this.cmd.sort=this.cmd[n]),this}comment(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.comment=e,this}maxAwaitTimeMS(e){if("number"!=typeof e)throw c.create({message:"maxAwaitTimeMS must be a number",driver:!0});if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.maxAwaitTimeMS=e,this}maxTimeMS(e){if("number"!=typeof e)throw c.create({message:"maxTimeMS must be a number",driver:!0});if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.maxTimeMS=e,this}project(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.fields=e,this}sort(e,t){if(this.options.tailable)throw c.create({message:"Tailable cursor doesn't support sorting",driver:!0});if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});let n=e;return Array.isArray(n)&&Array.isArray(n[0])&&(n=new f(n.map(e=>{const t=[e[0],null];if("asc"===e[1])t[1]=1;else if("desc"===e[1])t[1]=-1;else{if(1!==e[1]&&-1!==e[1]&&!e[1].$meta)throw new c("Illegal sort clause, must be of the form [['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]");t[1]=e[1]}return t}))),null!=t&&(n=[[e,t]]),this.cmd.sort=n,this}batchSize(e){if(this.options.tailable)throw c.create({message:"Tailable cursor doesn't support batchSize",driver:!0});if(this.s.state===l.CLOSED||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});if("number"!=typeof e)throw c.create({message:"batchSize requires an integer",driver:!0});return this.cmd.batchSize=e,this.setCursorBatchSize(e),this}collation(e){return this.cmd.collation=e,this}limit(e){if(this.options.tailable)throw c.create({message:"Tailable cursor doesn't support limit",driver:!0});if(this.s.state===l.OPEN||this.s.state===l.CLOSED||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});if("number"!=typeof e)throw c.create({message:"limit requires an integer",driver:!0});return this.cmd.limit=e,this.setCursorLimit(e),this}skip(e){if(this.options.tailable)throw c.create({message:"Tailable cursor doesn't support skip",driver:!0});if(this.s.state===l.OPEN||this.s.state===l.CLOSED||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});if("number"!=typeof e)throw c.create({message:"skip requires an integer",driver:!0});return this.cmd.skip=e,this.setCursorSkip(e),this}each(e){this.rewind(),this.s.state=l.INIT,y(this,e)}forEach(e,t){if(this.rewind(),this.s.state=l.INIT,"function"!=typeof t)return new this.s.promiseLibrary((t,n)=>{y(this,(r,o)=>r?(n(r),!1):null==o?(t(null),!1):(e(o),!0))});y(this,(n,r)=>{if(n)return t(n),!1;if(null!=r)return e(r),!0;if(null==r&&t){const e=t;return t=null,e(null),!1}})}setReadPreference(e){if(this.s.state!==l.INIT)throw c.create({message:"cannot change cursor readPreference after cursor has been accessed",driver:!0});if(e instanceof a)this.options.readPreference=e;else{if("string"!=typeof e)throw new TypeError("Invalid read preference: "+e);this.options.readPreference=new a(e)}return this}toArray(e){if(this.options.tailable)throw c.create({message:"Tailable cursor cannot be converted to array",driver:!0});return p(this,e,e=>{const t=this,n=[];t.rewind(),t.s.state=l.INIT;const r=()=>{t._next((o,i)=>{if(o)return s(e,o);if(null==i)return t.close({skipKillCursors:!0},()=>s(e,null,n));if(n.push(i),t.bufferedCount()>0){let e=t.readBufferedDocuments(t.bufferedCount());Array.prototype.push.apply(n,e)}r()})};r()})}count(e,t,n){if(null==this.cmd.query)throw c.create({message:"count can only be used with find command",driver:!0});"function"==typeof t&&(n=t,t={}),t=t||{},"function"==typeof e&&(n=e,e=!0),this.cursorState.session&&(t=Object.assign({},t,{session:this.cursorState.session}));const r=new b(this,e,t);return d(this.topology,r,n)}close(e,t){return"function"==typeof e&&(t=e,e={}),e=Object.assign({},{skipKillCursors:!1},e),p(this,t,t=>{this.s.state=l.CLOSED,e.skipKillCursors||this.kill(),this._endSession(()=>{this.emit("close"),t(null,this)})})}map(e){if(this.cursorState.transforms&&this.cursorState.transforms.doc){const t=this.cursorState.transforms.doc;this.cursorState.transforms.doc=n=>e(t(n))}else this.cursorState.transforms={doc:e};return this}isClosed(){return this.isDead()}destroy(e){e&&this.emit("error",e),this.pause(),this.close()}stream(e){return this.cursorState.streamOptions=e||{},this}transformStream(e){const t=e||{};if("function"==typeof t.transform){const e=new r({objectMode:!0,transform:function(e,n,r){this.push(t.transform(e)),r()}});return this.pipe(e)}return this.pipe(new o({objectMode:!0}))}explain(e,t){if("function"==typeof e&&(t=e,e=!0),void 0===e&&(e=!0),!this.operation||!this.operation.hasAspect(g.EXPLAINABLE))throw new c("This command cannot be explained");return this.operation.explain=new m(e),p(this,t,e=>{u.prototype._next.apply(this,[e])})}getLogger(){return this.logger}}w.prototype.maxTimeMs=w.prototype.maxTimeMS,i(w.prototype.each,"Cursor.each is deprecated. Use Cursor.forEach instead."),i(w.prototype.maxScan,"Cursor.maxScan is deprecated, and will be removed in a later version"),i(w.prototype.snapshot,"Cursor Snapshot is deprecated, and will be removed in a later version"),e.exports=w},function(e,t,n){"use strict";const r=n(1).Aspect,o=n(1).OperationBase,i=n(2).ReadPreference,s=n(46),a=n(29),c=n(4).maxWireVersion,u=n(0).decorateWithExplain,l=n(34).commandSupportsReadConcern,f=n(3).MongoError;e.exports=class extends o{constructor(e,t,n){super(t),this.ns=e.s.namespace.withCollection("$cmd");const o=this.hasAspect(r.NO_INHERIT_OPTIONS)?void 0:e;this.readPreference=this.hasAspect(r.WRITE_OPERATION)?i.primary:i.resolve(o,this.options),this.readConcern=function(e,t){return s.fromOptions(t)||e&&e.readConcern}(o,this.options),this.writeConcern=function(e,t){return a.fromOptions(t)||e&&e.writeConcern}(o,this.options),n&&"boolean"==typeof n.fullResponse&&(this.fullResponse=!0),this.options.readPreference=this.readPreference,e.s.logger?this.logger=e.s.logger:e.s.db&&e.s.db.logger&&(this.logger=e.s.db.logger)}executeCommand(e,t,n){this.server=e;const o=this.options,i=c(e),s=this.session&&this.session.inTransaction();this.readConcern&&l(t)&&!s&&Object.assign(t,{readConcern:this.readConcern}),o.collation&&i<5?n(new f(`Server ${e.name}, which reports wire version ${i}, does not support collation`)):(i>=5&&(this.writeConcern&&this.hasAspect(r.WRITE_OPERATION)&&Object.assign(t,{writeConcern:this.writeConcern}),o.collation&&"object"==typeof o.collation&&Object.assign(t,{collation:o.collation})),"number"==typeof o.maxTimeMS&&(t.maxTimeMS=o.maxTimeMS),"string"==typeof o.comment&&(t.comment=o.comment),this.hasAspect(r.EXPLAINABLE)&&this.explain&&(i<6&&t.aggregate?t.explain=!0:t=u(t,this.explain)),this.logger&&this.logger.isDebug()&&this.logger.debug(`executing command ${JSON.stringify(t)} against ${this.ns}`),e.command(this.ns.toString(),t,this.options,(e,t)=>{e?n(e,null):this.fullResponse?n(null,t):n(null,t.result)}))}}},function(e,t){e.exports=function(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}},function(e,t,n){"use strict";const r=new Set(["w","wtimeout","j","journal","fsync"]);let o;class i{constructor(e,t,n,r){null!=e&&(this.w=e),null!=t&&(this.wtimeout=t),null!=n&&(this.j=n),null!=r&&(this.fsync=r)}static fromOptions(e){if(null!=e&&(null!=e.writeConcern||null!=e.w||null!=e.wtimeout||null!=e.j||null!=e.journal||null!=e.fsync)){if(e.writeConcern){if("string"==typeof e.writeConcern)return new i(e.writeConcern);if(!Object.keys(e.writeConcern).some(e=>r.has(e)))return;return new i(e.writeConcern.w,e.writeConcern.wtimeout,e.writeConcern.j||e.writeConcern.journal,e.writeConcern.fsync)}return o||(o=n(0)),o.emitWarningOnce("Top-level use of w, wtimeout, j, and fsync is deprecated. Use writeConcern instead."),new i(e.w,e.wtimeout,e.j||e.journal,e.fsync)}}}e.exports=i},function(e,t,n){"use strict";const r=n(9).retrieveSnappy(),o=n(413),i={snappy:1,zlib:2},s=new Set(["ismaster","saslStart","saslContinue","getnonce","authenticate","createUser","updateUser","copydbSaslStart","copydbgetnonce","copydb"]);e.exports={compressorIDs:i,uncompressibleCommands:s,compress:function(e,t,n){switch(e.options.agreedCompressor){case"snappy":r.compress(t,n);break;case"zlib":var i={};e.options.zlibCompressionLevel&&(i.level=e.options.zlibCompressionLevel),o.deflate(t,i,n);break;default:throw new Error('Attempt to compress message using unknown compressor "'+e.options.agreedCompressor+'".')}},decompress:function(e,t,n){if(e<0||e>i.length)throw new Error("Server sent message compressed using an unsupported compressor. (Received compressor ID "+e+")");switch(e){case i.snappy:r.uncompress(t,n);break;case i.zlib:o.inflate(t,n);break;default:n(null,t)}}}},function(e,t,n){var r=n(247),o=n(252);e.exports=function(e,t){var n=o(e,t);return r(n)?n:void 0}},function(e,t,n){"use strict";function r(e,t){return new Buffer(e,t)}e.exports={normalizedFunctionString:function(e){return e.toString().replace(/function *\(/,"function (")},allocBuffer:"function"==typeof Buffer.alloc?function(){return Buffer.alloc.apply(Buffer,arguments)}:r,toBuffer:"function"==typeof Buffer.from?function(){return Buffer.from.apply(Buffer,arguments)}:r}},function(e,t,n){"use strict";e.exports={AuthContext:class{constructor(e,t,n){this.connection=e,this.credentials=t,this.options=n}},AuthProvider:class{constructor(e){this.bson=e}prepare(e,t,n){n(void 0,e)}auth(e,t){t(new TypeError("`auth` method must be overridden by subclass"))}}}},function(e,t,n){"use strict";const r=n(9).retrieveBSON,o=n(8),i=r(),s=i.Binary,a=n(4).uuidV4,c=n(3).MongoError,u=n(3).isRetryableError,l=n(3).MongoNetworkError,f=n(3).MongoWriteConcernError,p=n(54).Transaction,d=n(54).TxnState,h=n(4).isPromiseLike,m=n(10),g=n(0).maybePromise,y=n(54).isTransactionCommand,b=n(7).resolveClusterTime,v=n(6).isSharded,S=n(4).maxWireVersion,w=n(0).now,_=n(0).calculateDurationInMs;function O(e,t){if(null==e.serverSession){const e=new c("Cannot use a session that has ended");if("function"==typeof t)return t(e,null),!1;throw e}return!0}const T=Symbol("serverSession");class C extends o{constructor(e,t,n,r){if(super(),null==e)throw new Error("ClientSession requires a topology");if(null==t||!(t instanceof R))throw new Error("ClientSession requires a ServerSessionPool");n=n||{},r=r||{},this.topology=e,this.sessionPool=t,this.hasEnded=!1,this.clientOptions=r,this[T]=void 0,this.supports={causalConsistency:void 0===n.causalConsistency||n.causalConsistency},this.clusterTime=n.initialClusterTime,this.operationTime=null,this.explicit=!!n.explicit,this.owner=n.owner,this.defaultTransactionOptions=Object.assign({},n.defaultTransactionOptions),this.transaction=new p}get id(){return this.serverSession.id}get serverSession(){return null==this[T]&&(this[T]=this.sessionPool.acquire()),this[T]}endSession(e,t){"function"==typeof e&&(t=e,e={}),e=e||{};const n=this;return g(this,t,e=>{if(n.hasEnded)return e();function t(){n.sessionPool.release(n.serverSession),n[T]=void 0,n.hasEnded=!0,n.emit("ended",n),e()}n.serverSession&&n.inTransaction()?n.abortTransaction(n=>{if(n)return e(n);t()}):t()})}advanceOperationTime(e){null!=this.operationTime?e.greaterThan(this.operationTime)&&(this.operationTime=e):this.operationTime=e}equals(e){return e instanceof C&&this.id.id.buffer.equals(e.id.id.buffer)}incrementTransactionNumber(){this.serverSession.txnNumber++}inTransaction(){return this.transaction.isActive}startTransaction(e){if(O(this),this.inTransaction())throw new c("Transaction already in progress");const t=S(this.topology);if(v(this.topology)&&null!=t&&t<8)throw new c("Transactions are not supported on sharded clusters in MongoDB < 4.2.");this.incrementTransactionNumber(),this.transaction=new p(Object.assign({},this.clientOptions,e||this.defaultTransactionOptions)),this.transaction.transition(d.STARTING_TRANSACTION)}commitTransaction(e){return g(this,e,e=>k(this,"commitTransaction",e))}abortTransaction(e){return g(this,e,e=>k(this,"abortTransaction",e))}toBSON(){throw new Error("ClientSession cannot be serialized to BSON.")}withTransaction(e,t){return A(this,w(),e,t)}}const x=new Set(["CannotSatisfyWriteConcern","UnknownReplWriteConcern","UnsatisfiableWriteConcern"]);function E(e,t){return _(e)<t}function N(e){return null!=e&&(50===e.code||e.writeConcernError&&50===e.writeConcernError.code)}const I=new Set([d.NO_TRANSACTION,d.TRANSACTION_COMMITTED,d.TRANSACTION_ABORTED]);function A(e,t,n,r){let o;e.startTransaction(r);try{o=n(e)}catch(e){o=Promise.reject(e)}if(!h(o))throw e.abortTransaction(),new TypeError("Function provided to `withTransaction` must return a Promise");return o.then(()=>{if(!function(e){return I.has(e.transaction.state)}(e))return function e(t,n,r,o){return t.commitTransaction().catch(i=>{if(i instanceof c&&E(n,12e4)&&!N(i)){if(i.hasErrorLabel("UnknownTransactionCommitResult"))return e(t,n,r,o);if(i.hasErrorLabel("TransientTransactionError"))return A(t,n,r,o)}throw i})}(e,t,n,r)}).catch(o=>{function i(o){if(o instanceof c&&o.hasErrorLabel("TransientTransactionError")&&E(t,12e4))return A(e,t,n,r);throw N(o)&&o.addErrorLabel("UnknownTransactionCommitResult"),o}return e.transaction.isActive?e.abortTransaction().then(()=>i(o)):i(o)})}function k(e,t,n){if(!O(e,n))return;let r=e.transaction.state;if(r===d.NO_TRANSACTION)return void n(new c("No transaction started"));if("commitTransaction"===t){if(r===d.STARTING_TRANSACTION||r===d.TRANSACTION_COMMITTED_EMPTY)return e.transaction.transition(d.TRANSACTION_COMMITTED_EMPTY),void n(null,null);if(r===d.TRANSACTION_ABORTED)return void n(new c("Cannot call commitTransaction after calling abortTransaction"))}else{if(r===d.STARTING_TRANSACTION)return e.transaction.transition(d.TRANSACTION_ABORTED),void n(null,null);if(r===d.TRANSACTION_ABORTED)return void n(new c("Cannot call abortTransaction twice"));if(r===d.TRANSACTION_COMMITTED||r===d.TRANSACTION_COMMITTED_EMPTY)return void n(new c("Cannot call abortTransaction after calling commitTransaction"))}const o={[t]:1};let i;function s(r,o){var i;"commitTransaction"===t?(e.transaction.transition(d.TRANSACTION_COMMITTED),r&&(r instanceof l||r instanceof f||u(r)||N(r))&&(N(i=r)||!x.has(i.codeName)&&100!==i.code&&79!==i.code)&&(r.addErrorLabel("UnknownTransactionCommitResult"),e.transaction.unpinServer())):e.transaction.transition(d.TRANSACTION_ABORTED),n(r,o)}function a(e){return"commitTransaction"===t?e:null}e.transaction.options.writeConcern?i=Object.assign({},e.transaction.options.writeConcern):e.clientOptions&&e.clientOptions.w&&(i={w:e.clientOptions.w}),r===d.TRANSACTION_COMMITTED&&(i=Object.assign({wtimeout:1e4},i,{w:"majority"})),i&&Object.assign(o,{writeConcern:i}),"commitTransaction"===t&&e.transaction.options.maxTimeMS&&Object.assign(o,{maxTimeMS:e.transaction.options.maxTimeMS}),e.transaction.recoveryToken&&function(e){return!!e.topology.s.options.useRecoveryToken}(e)&&(o.recoveryToken=e.transaction.recoveryToken),e.topology.command("admin.$cmd",o,{session:e},(t,n)=>{if(t&&u(t))return o.commitTransaction&&(e.transaction.unpinServer(),o.writeConcern=Object.assign({wtimeout:1e4},o.writeConcern,{w:"majority"})),e.topology.command("admin.$cmd",o,{session:e},(e,t)=>s(a(e),t));s(a(t),n)})}class M{constructor(){this.id={id:new s(a(),s.SUBTYPE_UUID)},this.lastUse=w(),this.txnNumber=0,this.isDirty=!1}hasTimedOut(e){return Math.round(_(this.lastUse)%864e5%36e5/6e4)>e-1}}class R{constructor(e){if(null==e)throw new Error("ServerSessionPool requires a topology");this.topology=e,this.sessions=[]}endAllPooledSessions(e){this.sessions.length?this.topology.endSessions(this.sessions.map(e=>e.id),()=>{this.sessions=[],"function"==typeof e&&e()}):"function"==typeof e&&e()}acquire(){const e=this.topology.logicalSessionTimeoutMinutes;for(;this.sessions.length;){const t=this.sessions.shift();if(!t.hasTimedOut(e))return t}return new M}release(e){const t=this.topology.logicalSessionTimeoutMinutes;for(;this.sessions.length;){if(!this.sessions[this.sessions.length-1].hasTimedOut(t))break;this.sessions.pop()}if(!e.hasTimedOut(t)){if(e.isDirty)return;this.sessions.unshift(e)}}}function j(e,t){return!!(e.aggregate||e.count||e.distinct||e.find||e.parallelCollectionScan||e.geoNear||e.geoSearch)||!(!(e.mapReduce&&t&&t.out)||1!==t.out.inline&&"inline"!==t.out)}e.exports={ClientSession:C,ServerSession:M,ServerSessionPool:R,TxnState:d,applySession:function(e,t,n){if(e.hasEnded)return new c("Cannot use a session that has ended");if(n&&n.writeConcern&&0===n.writeConcern.w)return;const r=e.serverSession;r.lastUse=w(),t.lsid=r.id;const o=e.inTransaction()||y(t),s=n.willRetryWrite,a=j(t,n);if(r.txnNumber&&(s||o)&&(t.txnNumber=i.Long.fromNumber(r.txnNumber)),!o)return e.transaction.state!==d.NO_TRANSACTION&&e.transaction.transition(d.NO_TRANSACTION),void(e.supports.causalConsistency&&e.operationTime&&a&&(t.readConcern=t.readConcern||{},Object.assign(t.readConcern,{afterClusterTime:e.operationTime})));if(n.readPreference&&!n.readPreference.equals(m.primary))return new c(`Read preference in a transaction must be primary, not: ${n.readPreference.mode}`);if(t.autocommit=!1,e.transaction.state===d.STARTING_TRANSACTION){e.transaction.transition(d.TRANSACTION_IN_PROGRESS),t.startTransaction=!0;const n=e.transaction.options.readConcern||e.clientOptions.readConcern;n&&(t.readConcern=n),e.supports.causalConsistency&&e.operationTime&&(t.readConcern=t.readConcern||{},Object.assign(t.readConcern,{afterClusterTime:e.operationTime}))}},updateSessionFromResponse:function(e,t){t.$clusterTime&&b(e,t.$clusterTime),t.operationTime&&e&&e.supports.causalConsistency&&e.advanceOperationTime(t.operationTime),t.recoveryToken&&e&&e.inTransaction()&&(e.transaction._recoveryToken=t.recoveryToken)},commandSupportsReadConcern:j}},function(e,t,n){"use strict";const r=n(8),o=n(2).MongoError,i=n(5).format,s=n(2).ReadPreference,a=n(2).Sessions.ClientSession;var c=function(e,t){var n=this;t=t||{force:!1,bufferMaxEntries:-1},this.s={storedOps:[],storeOptions:t,topology:e},Object.defineProperty(this,"length",{enumerable:!0,get:function(){return n.s.storedOps.length}})};c.prototype.add=function(e,t,n,r,s){if(this.s.storeOptions.force)return s(o.create({message:"db closed by application",driver:!0}));if(0===this.s.storeOptions.bufferMaxEntries)return s(o.create({message:i("no connection available for operation and number of stored operation > %s",this.s.storeOptions.bufferMaxEntries),driver:!0}));if(this.s.storeOptions.bufferMaxEntries>0&&this.s.storedOps.length>this.s.storeOptions.bufferMaxEntries)for(;this.s.storedOps.length>0;){this.s.storedOps.shift().c(o.create({message:i("no connection available for operation and number of stored operation > %s",this.s.storeOptions.bufferMaxEntries),driver:!0}))}else this.s.storedOps.push({t:e,n:t,o:n,op:r,c:s})},c.prototype.addObjectAndMethod=function(e,t,n,r,s){if(this.s.storeOptions.force)return s(o.create({message:"db closed by application",driver:!0}));if(0===this.s.storeOptions.bufferMaxEntries)return s(o.create({message:i("no connection available for operation and number of stored operation > %s",this.s.storeOptions.bufferMaxEntries),driver:!0}));if(this.s.storeOptions.bufferMaxEntries>0&&this.s.storedOps.length>this.s.storeOptions.bufferMaxEntries)for(;this.s.storedOps.length>0;){this.s.storedOps.shift().c(o.create({message:i("no connection available for operation and number of stored operation > %s",this.s.storeOptions.bufferMaxEntries),driver:!0}))}else this.s.storedOps.push({t:e,m:n,o:t,p:r,c:s})},c.prototype.flush=function(e){for(;this.s.storedOps.length>0;)this.s.storedOps.shift().c(e||o.create({message:i("no connection available for operation"),driver:!0}))};var u=["primary","primaryPreferred","nearest","secondaryPreferred"],l=["secondary","secondaryPreferred"];c.prototype.execute=function(e){e=e||{};var t=this.s.storedOps;this.s.storedOps=[];for(var n="boolean"!=typeof e.executePrimary||e.executePrimary,r="boolean"!=typeof e.executeSecondary||e.executeSecondary;t.length>0;){var o=t.shift();"cursor"===o.t?n&&r?o.o[o.m].apply(o.o,o.p):n&&o.o.options&&o.o.options.readPreference&&-1!==u.indexOf(o.o.options.readPreference.mode)?o.o[o.m].apply(o.o,o.p):!n&&r&&o.o.options&&o.o.options.readPreference&&-1!==l.indexOf(o.o.options.readPreference.mode)&&o.o[o.m].apply(o.o,o.p):"auth"===o.t?this.s.topology[o.t].apply(this.s.topology,o.o):n&&r?this.s.topology[o.t](o.n,o.o,o.op,o.c):n&&o.op&&o.op.readPreference&&-1!==u.indexOf(o.op.readPreference.mode)?this.s.topology[o.t](o.n,o.o,o.op,o.c):!n&&r&&o.op&&o.op.readPreference&&-1!==l.indexOf(o.op.readPreference.mode)&&this.s.topology[o.t](o.n,o.o,o.op,o.c)}},c.prototype.all=function(){return this.s.storedOps};var f=function(e){var t=function(e,t,n){Object.defineProperty(e,t,{enumerable:!0,get:function(){return n}})},n=!1,r=!1,o=!1,i=!1,s=!1,a=!1,c=e.maxWriteBatchSize||1e3,u=!1,l=!1;e.minWireVersion>=0&&(o=!0),e.maxWireVersion>=1&&(n=!0,i=!0),e.maxWireVersion>=2&&(r=!0),e.maxWireVersion>=3&&(s=!0,a=!0),e.maxWireVersion>=5&&(u=!0,l=!0),null==e.minWireVersion&&(e.minWireVersion=0),null==e.maxWireVersion&&(e.maxWireVersion=0),t(this,"hasAggregationCursor",n),t(this,"hasWriteCommands",r),t(this,"hasTextSearch",o),t(this,"hasAuthCommands",i),t(this,"hasListCollectionsCommand",s),t(this,"hasListIndexesCommand",a),t(this,"minWireVersion",e.minWireVersion),t(this,"maxWireVersion",e.maxWireVersion),t(this,"maxNumberOfDocsInBatch",c),t(this,"commandsTakeWriteConcern",u),t(this,"commandsTakeCollation",l)};class p extends r{constructor(){super(),this.setMaxListeners(1/0)}hasSessionSupport(){return null!=this.logicalSessionTimeoutMinutes}startSession(e,t){const n=new a(this,this.s.sessionPool,e,t);return n.once("ended",()=>{this.s.sessions.delete(n)}),this.s.sessions.add(n),n}endSessions(e,t){return this.s.coreTopology.endSessions(e,t)}get clientMetadata(){return this.s.coreTopology.s.options.metadata}capabilities(){return this.s.sCapabilities?this.s.sCapabilities:null==this.s.coreTopology.lastIsMaster()?null:(this.s.sCapabilities=new f(this.s.coreTopology.lastIsMaster()),this.s.sCapabilities)}command(e,t,n,r){this.s.coreTopology.command(e.toString(),t,s.translate(n),r)}insert(e,t,n,r){this.s.coreTopology.insert(e.toString(),t,n,r)}update(e,t,n,r){this.s.coreTopology.update(e.toString(),t,n,r)}remove(e,t,n,r){this.s.coreTopology.remove(e.toString(),t,n,r)}isConnected(e){return e=e||{},e=s.translate(e),this.s.coreTopology.isConnected(e)}isDestroyed(){return this.s.coreTopology.isDestroyed()}cursor(e,t,n){return n=n||{},(n=s.translate(n)).disconnectHandler=this.s.store,n.topology=this,this.s.coreTopology.cursor(e,t,n)}lastIsMaster(){return this.s.coreTopology.lastIsMaster()}selectServer(e,t,n){return this.s.coreTopology.selectServer(e,t,n)}unref(){return this.s.coreTopology.unref()}connections(){return this.s.coreTopology.connections()}close(e,t){this.s.sessions.forEach(e=>e.endSession()),this.s.sessionPool&&this.s.sessionPool.endAllPooledSessions(),!0===e&&(this.s.storeOptions.force=e,this.s.store.flush()),this.s.coreTopology.destroy({force:"boolean"==typeof e&&e},t)}}Object.defineProperty(p.prototype,"bson",{enumerable:!0,get:function(){return this.s.coreTopology.s.bson}}),Object.defineProperty(p.prototype,"parserType",{enumerable:!0,get:function(){return this.s.coreTopology.parserType}}),Object.defineProperty(p.prototype,"logicalSessionTimeoutMinutes",{enumerable:!0,get:function(){return this.s.coreTopology.logicalSessionTimeoutMinutes}}),Object.defineProperty(p.prototype,"type",{enumerable:!0,get:function(){return this.s.coreTopology.type}}),t.Store=c,t.ServerCapabilities=f,t.TopologyBase=p},function(e,t,n){var r=n(19).Symbol;e.exports=r},function(e,t){e.exports=function(e){return function(t){return e(t)}}},function(e,t,n){var r=n(148),o=n(109);e.exports=function(e){return null!=e&&o(e.length)&&!r(e)}},function(e,t,n){var r=n(12),o=n(116),i=n(297),s=n(40);e.exports=function(e,t){return r(e)?e:o(e,t)?[e]:i(s(e))}},function(e,t,n){var r=n(300);e.exports=function(e){return null==e?"":r(e)}},function(e,t,n){var r=n(71);e.exports=function(e){if("string"==typeof e||r(e))return e;var t=e+"";return"0"==t&&1/e==-1/0?"-0":t}},function(e,t,n){"use strict";const r=n(2),o=n(447),i=n(59).connect;i.MongoError=r.MongoError,i.MongoNetworkError=r.MongoNetworkError,i.MongoTimeoutError=r.MongoTimeoutError,i.MongoServerSelectionError=r.MongoServerSelectionError,i.MongoParseError=r.MongoParseError,i.MongoWriteConcernError=r.MongoWriteConcernError,i.MongoBulkWriteError=n(141).BulkWriteError,i.BulkWriteError=i.MongoBulkWriteError,i.Admin=n(218),i.MongoClient=n(59),i.Db=n(97),i.Collection=n(61),i.Server=n(98),i.ReplSet=n(222),i.Mongos=n(221),i.ReadPreference=r.ReadPreference,i.GridStore=n(491),i.Chunk=n(227),i.Logger=r.Logger,i.AggregationCursor=n(142),i.CommandCursor=n(143),i.Cursor=n(26),i.GridFSBucket=n(492),i.CoreServer=r.Server,i.CoreConnection=r.Connection,i.Binary=r.BSON.Binary,i.Code=r.BSON.Code,i.Map=r.BSON.Map,i.DBRef=r.BSON.DBRef,i.Double=r.BSON.Double,i.Int32=r.BSON.Int32,i.Long=r.BSON.Long,i.MinKey=r.BSON.MinKey,i.MaxKey=r.BSON.MaxKey,i.ObjectID=r.BSON.ObjectID,i.ObjectId=r.BSON.ObjectID,i.Symbol=r.BSON.Symbol,i.Timestamp=r.BSON.Timestamp,i.BSONRegExp=r.BSON.BSONRegExp,i.Decimal128=r.BSON.Decimal128,i.connect=i,i.instrument=function(e,t){"function"==typeof e&&(t=e,e={});const n=new o;return n.instrument(i.MongoClient,t),n},e.exports=i},function(e,t){function n(e,t){if(!(this instanceof n))return new n(e,t);this._bsontype="Long",this.low_=0|e,this.high_=0|t}n.prototype.toInt=function(){return this.low_},n.prototype.toNumber=function(){return this.high_*n.TWO_PWR_32_DBL_+this.getLowBitsUnsigned()},n.prototype.toBigInt=function(){return BigInt(this.toString())},n.prototype.toJSON=function(){return this.toString()},n.prototype.toString=function(e){var t=e||10;if(t<2||36<t)throw Error("radix out of range: "+t);if(this.isZero())return"0";if(this.isNegative()){if(this.equals(n.MIN_VALUE)){var r=n.fromNumber(t),o=this.div(r),i=o.multiply(r).subtract(this);return o.toString(t)+i.toInt().toString(t)}return"-"+this.negate().toString(t)}var s=n.fromNumber(Math.pow(t,6));i=this;for(var a="";!i.isZero();){var c=i.div(s),u=i.subtract(c.multiply(s)).toInt().toString(t);if((i=c).isZero())return u+a;for(;u.length<6;)u="0"+u;a=""+u+a}},n.prototype.getHighBits=function(){return this.high_},n.prototype.getLowBits=function(){return this.low_},n.prototype.getLowBitsUnsigned=function(){return this.low_>=0?this.low_:n.TWO_PWR_32_DBL_+this.low_},n.prototype.getNumBitsAbs=function(){if(this.isNegative())return this.equals(n.MIN_VALUE)?64:this.negate().getNumBitsAbs();for(var e=0!==this.high_?this.high_:this.low_,t=31;t>0&&0==(e&1<<t);t--);return 0!==this.high_?t+33:t+1},n.prototype.isZero=function(){return 0===this.high_&&0===this.low_},n.prototype.isNegative=function(){return this.high_<0},n.prototype.isOdd=function(){return 1==(1&this.low_)},n.prototype.equals=function(e){return this.high_===e.high_&&this.low_===e.low_},n.prototype.notEquals=function(e){return this.high_!==e.high_||this.low_!==e.low_},n.prototype.lessThan=function(e){return this.compare(e)<0},n.prototype.lessThanOrEqual=function(e){return this.compare(e)<=0},n.prototype.greaterThan=function(e){return this.compare(e)>0},n.prototype.greaterThanOrEqual=function(e){return this.compare(e)>=0},n.prototype.compare=function(e){if(this.equals(e))return 0;var t=this.isNegative(),n=e.isNegative();return t&&!n?-1:!t&&n?1:this.subtract(e).isNegative()?-1:1},n.prototype.negate=function(){return this.equals(n.MIN_VALUE)?n.MIN_VALUE:this.not().add(n.ONE)},n.prototype.add=function(e){var t=this.high_>>>16,r=65535&this.high_,o=this.low_>>>16,i=65535&this.low_,s=e.high_>>>16,a=65535&e.high_,c=e.low_>>>16,u=0,l=0,f=0,p=0;return f+=(p+=i+(65535&e.low_))>>>16,p&=65535,l+=(f+=o+c)>>>16,f&=65535,u+=(l+=r+a)>>>16,l&=65535,u+=t+s,u&=65535,n.fromBits(f<<16|p,u<<16|l)},n.prototype.subtract=function(e){return this.add(e.negate())},n.prototype.multiply=function(e){if(this.isZero())return n.ZERO;if(e.isZero())return n.ZERO;if(this.equals(n.MIN_VALUE))return e.isOdd()?n.MIN_VALUE:n.ZERO;if(e.equals(n.MIN_VALUE))return this.isOdd()?n.MIN_VALUE:n.ZERO;if(this.isNegative())return e.isNegative()?this.negate().multiply(e.negate()):this.negate().multiply(e).negate();if(e.isNegative())return this.multiply(e.negate()).negate();if(this.lessThan(n.TWO_PWR_24_)&&e.lessThan(n.TWO_PWR_24_))return n.fromNumber(this.toNumber()*e.toNumber());var t=this.high_>>>16,r=65535&this.high_,o=this.low_>>>16,i=65535&this.low_,s=e.high_>>>16,a=65535&e.high_,c=e.low_>>>16,u=65535&e.low_,l=0,f=0,p=0,d=0;return p+=(d+=i*u)>>>16,d&=65535,f+=(p+=o*u)>>>16,p&=65535,f+=(p+=i*c)>>>16,p&=65535,l+=(f+=r*u)>>>16,f&=65535,l+=(f+=o*c)>>>16,f&=65535,l+=(f+=i*a)>>>16,f&=65535,l+=t*u+r*c+o*a+i*s,l&=65535,n.fromBits(p<<16|d,l<<16|f)},n.prototype.div=function(e){if(e.isZero())throw Error("division by zero");if(this.isZero())return n.ZERO;if(this.equals(n.MIN_VALUE)){if(e.equals(n.ONE)||e.equals(n.NEG_ONE))return n.MIN_VALUE;if(e.equals(n.MIN_VALUE))return n.ONE;var t=this.shiftRight(1).div(e).shiftLeft(1);if(t.equals(n.ZERO))return e.isNegative()?n.ONE:n.NEG_ONE;var r=this.subtract(e.multiply(t));return t.add(r.div(e))}if(e.equals(n.MIN_VALUE))return n.ZERO;if(this.isNegative())return e.isNegative()?this.negate().div(e.negate()):this.negate().div(e).negate();if(e.isNegative())return this.div(e.negate()).negate();var o=n.ZERO;for(r=this;r.greaterThanOrEqual(e);){t=Math.max(1,Math.floor(r.toNumber()/e.toNumber()));for(var i=Math.ceil(Math.log(t)/Math.LN2),s=i<=48?1:Math.pow(2,i-48),a=n.fromNumber(t),c=a.multiply(e);c.isNegative()||c.greaterThan(r);)t-=s,c=(a=n.fromNumber(t)).multiply(e);a.isZero()&&(a=n.ONE),o=o.add(a),r=r.subtract(c)}return o},n.prototype.modulo=function(e){return this.subtract(this.div(e).multiply(e))},n.prototype.not=function(){return n.fromBits(~this.low_,~this.high_)},n.prototype.and=function(e){return n.fromBits(this.low_&e.low_,this.high_&e.high_)},n.prototype.or=function(e){return n.fromBits(this.low_|e.low_,this.high_|e.high_)},n.prototype.xor=function(e){return n.fromBits(this.low_^e.low_,this.high_^e.high_)},n.prototype.shiftLeft=function(e){if(0===(e&=63))return this;var t=this.low_;if(e<32){var r=this.high_;return n.fromBits(t<<e,r<<e|t>>>32-e)}return n.fromBits(0,t<<e-32)},n.prototype.shiftRight=function(e){if(0===(e&=63))return this;var t=this.high_;if(e<32){var r=this.low_;return n.fromBits(r>>>e|t<<32-e,t>>e)}return n.fromBits(t>>e-32,t>=0?0:-1)},n.prototype.shiftRightUnsigned=function(e){if(0===(e&=63))return this;var t=this.high_;if(e<32){var r=this.low_;return n.fromBits(r>>>e|t<<32-e,t>>>e)}return 32===e?n.fromBits(t,0):n.fromBits(t>>>e-32,0)},n.fromInt=function(e){if(-128<=e&&e<128){var t=n.INT_CACHE_[e];if(t)return t}var r=new n(0|e,e<0?-1:0);return-128<=e&&e<128&&(n.INT_CACHE_[e]=r),r},n.fromNumber=function(e){return isNaN(e)||!isFinite(e)?n.ZERO:e<=-n.TWO_PWR_63_DBL_?n.MIN_VALUE:e+1>=n.TWO_PWR_63_DBL_?n.MAX_VALUE:e<0?n.fromNumber(-e).negate():new n(e%n.TWO_PWR_32_DBL_|0,e/n.TWO_PWR_32_DBL_|0)},n.fromBigInt=function(e){return n.fromString(e.toString(10),10)},n.fromBits=function(e,t){return new n(e,t)},n.fromString=function(e,t){if(0===e.length)throw Error("number format error: empty string");var r=t||10;if(r<2||36<r)throw Error("radix out of range: "+r);if("-"===e.charAt(0))return n.fromString(e.substring(1),r).negate();if(e.indexOf("-")>=0)throw Error('number format error: interior "-" character: '+e);for(var o=n.fromNumber(Math.pow(r,8)),i=n.ZERO,s=0;s<e.length;s+=8){var a=Math.min(8,e.length-s),c=parseInt(e.substring(s,s+a),r);if(a<8){var u=n.fromNumber(Math.pow(r,a));i=i.multiply(u).add(n.fromNumber(c))}else i=(i=i.multiply(o)).add(n.fromNumber(c))}return i},n.INT_CACHE_={},n.TWO_PWR_16_DBL_=65536,n.TWO_PWR_24_DBL_=1<<24,n.TWO_PWR_32_DBL_=n.TWO_PWR_16_DBL_*n.TWO_PWR_16_DBL_,n.TWO_PWR_31_DBL_=n.TWO_PWR_32_DBL_/2,n.TWO_PWR_48_DBL_=n.TWO_PWR_32_DBL_*n.TWO_PWR_16_DBL_,n.TWO_PWR_64_DBL_=n.TWO_PWR_32_DBL_*n.TWO_PWR_32_DBL_,n.TWO_PWR_63_DBL_=n.TWO_PWR_64_DBL_/2,n.ZERO=n.fromInt(0),n.ONE=n.fromInt(1),n.NEG_ONE=n.fromInt(-1),n.MAX_VALUE=n.fromBits(-1,2147483647),n.MIN_VALUE=n.fromBits(0,-2147483648),n.TWO_PWR_24_=n.fromInt(1<<24),e.exports=n,e.exports.Long=n},function(e,t,n){"use strict";const r=n(4).arrayStrictEqual,o=n(4).tagsStrictEqual,i=n(4).errorStrictEqual,s=n(13).ServerType,a=n(0).now,c=new Set([s.RSPrimary,s.Standalone,s.Mongos]),u=new Set([s.RSPrimary,s.RSSecondary,s.Mongos,s.Standalone]),l=["minWireVersion","maxWireVersion","maxBsonObjectSize","maxMessageSizeBytes","maxWriteBatchSize","compression","me","hosts","passives","arbiters","tags","setName","setVersion","electionId","primary","logicalSessionTimeoutMinutes","saslSupportedMechs","__nodejs_mock_server__","$clusterTime"];function f(e){return e&&e.ok?e.isreplicaset?s.RSGhost:e.msg&&"isdbgrid"===e.msg?s.Mongos:e.setName?e.hidden?s.RSOther:e.ismaster?s.RSPrimary:e.secondary?s.RSSecondary:e.arbiterOnly?s.RSArbiter:s.RSOther:s.Standalone:s.Unknown}function p(e,t){return null==e||null==t?-1:e.processId.equals(t.processId)?e.counter===t.counter?0:e.counter<t.counter?-1:1:-1}e.exports={ServerDescription:class{constructor(e,t,n){n=n||{},t=Object.assign({minWireVersion:0,maxWireVersion:0,hosts:[],passives:[],arbiters:[],tags:[]},t),this.address=e,this.error=n.error,this.roundTripTime=n.roundTripTime||-1,this.lastUpdateTime=a(),this.lastWriteDate=t.lastWrite?t.lastWrite.lastWriteDate:null,this.opTime=t.lastWrite?t.lastWrite.opTime:null,this.type=f(t),this.topologyVersion=n.topologyVersion||t.topologyVersion,l.forEach(e=>{void 0!==t[e]&&(this[e]=t[e])}),this.me&&(this.me=this.me.toLowerCase()),this.hosts=this.hosts.map(e=>e.toLowerCase()),this.passives=this.passives.map(e=>e.toLowerCase()),this.arbiters=this.arbiters.map(e=>e.toLowerCase())}get allHosts(){return this.hosts.concat(this.arbiters).concat(this.passives)}get isReadable(){return this.type===s.RSSecondary||this.isWritable}get isDataBearing(){return u.has(this.type)}get isWritable(){return c.has(this.type)}get host(){const e=`:${this.port}`.length;return this.address.slice(0,-e)}get port(){const e=this.address.split(":").pop();return e?Number.parseInt(e,10):e}equals(e){const t=this.topologyVersion===e.topologyVersion||0===p(this.topologyVersion,e.topologyVersion);return null!=e&&i(this.error,e.error)&&this.type===e.type&&this.minWireVersion===e.minWireVersion&&this.me===e.me&&r(this.hosts,e.hosts)&&o(this.tags,e.tags)&&this.setName===e.setName&&this.setVersion===e.setVersion&&(this.electionId?e.electionId&&this.electionId.equals(e.electionId):this.electionId===e.electionId)&&this.primary===e.primary&&this.logicalSessionTimeoutMinutes===e.logicalSessionTimeoutMinutes&&t}},parseServerType:f,compareTopologyVersion:p}},function(e,t,n){"use strict";const r=n(22).Buffer,o=n(6).opcodes,i=n(6).databaseNamespace,s=n(10),a=n(3).MongoError;let c=0;class u{constructor(e,t,n,r){if(null==n)throw new Error("query must be specified for query");this.bson=e,this.ns=t,this.command=n,this.command.$db=i(t),r.readPreference&&r.readPreference.mode!==s.PRIMARY&&(this.command.$readPreference=r.readPreference.toJSON()),this.options=r||{},this.requestId=r.requestId?r.requestId:u.getRequestId(),this.serializeFunctions="boolean"==typeof r.serializeFunctions&&r.serializeFunctions,this.ignoreUndefined="boolean"==typeof r.ignoreUndefined&&r.ignoreUndefined,this.checkKeys="boolean"==typeof r.checkKeys&&r.checkKeys,this.maxBsonSize=r.maxBsonSize||16777216,this.checksumPresent=!1,this.moreToCome=r.moreToCome||!1,this.exhaustAllowed="boolean"==typeof r.exhaustAllowed&&r.exhaustAllowed}toBin(){const e=[];let t=0;this.checksumPresent&&(t|=1),this.moreToCome&&(t|=2),this.exhaustAllowed&&(t|=65536);const n=r.alloc(20);e.push(n);let i=n.length;const s=this.command;return i+=this.makeDocumentSegment(e,s),n.writeInt32LE(i,0),n.writeInt32LE(this.requestId,4),n.writeInt32LE(0,8),n.writeInt32LE(o.OP_MSG,12),n.writeUInt32LE(t,16),e}makeDocumentSegment(e,t){const n=r.alloc(1);n[0]=0;const o=this.serializeBson(t);return e.push(n),e.push(o),n.length+o.length}serializeBson(e){return this.bson.serialize(e,{checkKeys:this.checkKeys,serializeFunctions:this.serializeFunctions,ignoreUndefined:this.ignoreUndefined})}}u.getRequestId=function(){return c=c+1&2147483647,c};e.exports={Msg:u,BinMsg:class{constructor(e,t,n,r,o){o=o||{promoteLongs:!0,promoteValues:!0,promoteBuffers:!1},this.parsed=!1,this.raw=t,this.data=r,this.bson=e,this.opts=o,this.length=n.length,this.requestId=n.requestId,this.responseTo=n.responseTo,this.opCode=n.opCode,this.fromCompressed=n.fromCompressed,this.responseFlags=r.readInt32LE(0),this.checksumPresent=0!=(1&this.responseFlags),this.moreToCome=0!=(2&this.responseFlags),this.exhaustAllowed=0!=(65536&this.responseFlags),this.promoteLongs="boolean"!=typeof o.promoteLongs||o.promoteLongs,this.promoteValues="boolean"!=typeof o.promoteValues||o.promoteValues,this.promoteBuffers="boolean"==typeof o.promoteBuffers&&o.promoteBuffers,this.documents=[]}isParsed(){return this.parsed}parse(e){if(this.parsed)return;e=e||{},this.index=4;const t=e.raw||!1,n=e.documentsReturnedIn||null,r={promoteLongs:"boolean"==typeof e.promoteLongs?e.promoteLongs:this.opts.promoteLongs,promoteValues:"boolean"==typeof e.promoteValues?e.promoteValues:this.opts.promoteValues,promoteBuffers:"boolean"==typeof e.promoteBuffers?e.promoteBuffers:this.opts.promoteBuffers};for(;this.index<this.data.length;){const e=this.data.readUInt8(this.index++);if(1===e)throw new a("OP_MSG Payload Type 1 detected unsupported protocol");if(0===e){const e=this.data.readUInt32LE(this.index),n=this.data.slice(this.index,this.index+e);this.documents.push(t?n:this.bson.deserialize(n,r)),this.index+=e}}if(1===this.documents.length&&null!=n&&t){const e={};e[n]=!0,r.fieldsAsRaw=e;const t=this.bson.deserialize(this.documents[0],r);this.documents=[t]}this.parsed=!0}}}},function(e,t,n){"use strict";class r{constructor(e){null!=e&&(this.level=e)}static fromOptions(e){if(null!=e)return e.readConcern?e.readConcern instanceof r?e.readConcern:new r(e.readConcern.level):e.level?new r(e.level):void 0}static get MAJORITY(){return"majority"}static get AVAILABLE(){return"available"}static get LINEARIZABLE(){return"linearizable"}static get SNAPSHOT(){return"snapshot"}}e.exports=r},function(e,t,n){"use strict";var r=n(91),o=Object.keys||function(e){var t=[];for(var n in e)t.push(n);return t};e.exports=f;var i=Object.create(n(57));i.inherits=n(58);var s=n(203),a=n(206);i.inherits(f,s);for(var c=o(a.prototype),u=0;u<c.length;u++){var l=c[u];f.prototype[l]||(f.prototype[l]=a.prototype[l])}function f(e){if(!(this instanceof f))return new f(e);s.call(this,e),a.call(this,e),e&&!1===e.readable&&(this.readable=!1),e&&!1===e.writable&&(this.writable=!1),this.allowHalfOpen=!0,e&&!1===e.allowHalfOpen&&(this.allowHalfOpen=!1),this.once("end",p)}function p(){this.allowHalfOpen||this._writableState.ended||r.nextTick(d,this)}function d(e){e.end()}Object.defineProperty(f.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Object.defineProperty(f.prototype,"destroyed",{get:function(){return void 0!==this._readableState&&void 0!==this._writableState&&(this._readableState.destroyed&&this._writableState.destroyed)},set:function(e){void 0!==this._readableState&&void 0!==this._writableState&&(this._readableState.destroyed=e,this._writableState.destroyed=e)}}),f.prototype._destroy=function(e,t){this.push(null),this.end(),r.nextTick(t,e)}},function(e,t,n){var r=n(105),o=n(106);e.exports=function(e,t,n,i){var s=!n;n||(n={});for(var a=-1,c=t.length;++a<c;){var u=t[a],l=i?i(n[u],e[u],u,n,e):void 0;void 0===l&&(l=e[u]),s?o(n,u,l):r(n,u,l)}return n}},function(e,t,n){var r=n(152),o=n(271),i=n(38);e.exports=function(e){return i(e)?r(e):o(e)}},function(e,t,n){var r=n(39),o=n(41);e.exports=function(e,t){for(var n=0,i=(t=r(t,e)).length;null!=e&&n<i;)e=e[o(t[n++])];return n&&n==i?e:void 0}},function(e,t){e.exports=function(e,t){for(var n=-1,r=null==e?0:e.length,o=Array(r);++n<r;)o[n]=t(e[n],n,e);return o}},function(e,t){e.exports=function(e){for(var t=-1,n=null==e?0:e.length,r=0,o=[];++t<n;){var i=e[t];i&&(o[r++]=i)}return o}},function(e,t,n){if("undefined"!=typeof global)var r=n(131).Buffer;var o=n(32);function i(e,t){if(!(this instanceof i))return new i(e,t);if(!(null==e||"string"==typeof e||r.isBuffer(e)||e instanceof Uint8Array||Array.isArray(e)))throw new Error("only String, Buffer, Uint8Array or Array accepted");if(this._bsontype="Binary",e instanceof Number?(this.sub_type=e,this.position=0):(this.sub_type=null==t?s:t,this.position=0),null==e||e instanceof Number)void 0!==r?this.buffer=o.allocBuffer(i.BUFFER_SIZE):"undefined"!=typeof Uint8Array?this.buffer=new Uint8Array(new ArrayBuffer(i.BUFFER_SIZE)):this.buffer=new Array(i.BUFFER_SIZE),this.position=0;else{if("string"==typeof e)if(void 0!==r)this.buffer=o.toBuffer(e);else{if("undefined"==typeof Uint8Array&&"[object Array]"!==Object.prototype.toString.call(e))throw new Error("only String, Buffer, Uint8Array or Array accepted");this.buffer=a(e)}else this.buffer=e;this.position=e.length}}i.prototype.put=function(e){if(null!=e.length&&"number"!=typeof e&&1!==e.length)throw new Error("only accepts single character String, Uint8Array or Array");if("number"!=typeof e&&e<0||e>255)throw new Error("only accepts number in a valid unsigned byte range 0-255");var t=null;if(t="string"==typeof e?e.charCodeAt(0):null!=e.length?e[0]:e,this.buffer.length>this.position)this.buffer[this.position++]=t;else if(void 0!==r&&r.isBuffer(this.buffer)){var n=o.allocBuffer(i.BUFFER_SIZE+this.buffer.length);this.buffer.copy(n,0,0,this.buffer.length),this.buffer=n,this.buffer[this.position++]=t}else{n=null,n="[object Uint8Array]"===Object.prototype.toString.call(this.buffer)?new Uint8Array(new ArrayBuffer(i.BUFFER_SIZE+this.buffer.length)):new Array(i.BUFFER_SIZE+this.buffer.length);for(var s=0;s<this.buffer.length;s++)n[s]=this.buffer[s];this.buffer=n,this.buffer[this.position++]=t}},i.prototype.write=function(e,t){if(t="number"==typeof t?t:this.position,this.buffer.length<t+e.length){var n=null;if(void 0!==r&&r.isBuffer(this.buffer))n=o.allocBuffer(this.buffer.length+e.length),this.buffer.copy(n,0,0,this.buffer.length);else if("[object Uint8Array]"===Object.prototype.toString.call(this.buffer)){n=new Uint8Array(new ArrayBuffer(this.buffer.length+e.length));for(var i=0;i<this.position;i++)n[i]=this.buffer[i]}this.buffer=n}if(void 0!==r&&r.isBuffer(e)&&r.isBuffer(this.buffer))e.copy(this.buffer,t,0,e.length),this.position=t+e.length>this.position?t+e.length:this.position;else if(void 0!==r&&"string"==typeof e&&r.isBuffer(this.buffer))this.buffer.write(e,t,"binary"),this.position=t+e.length>this.position?t+e.length:this.position;else if("[object Uint8Array]"===Object.prototype.toString.call(e)||"[object Array]"===Object.prototype.toString.call(e)&&"string"!=typeof e){for(i=0;i<e.length;i++)this.buffer[t++]=e[i];this.position=t>this.position?t:this.position}else if("string"==typeof e){for(i=0;i<e.length;i++)this.buffer[t++]=e.charCodeAt(i);this.position=t>this.position?t:this.position}},i.prototype.read=function(e,t){if(t=t&&t>0?t:this.position,this.buffer.slice)return this.buffer.slice(e,e+t);for(var n="undefined"!=typeof Uint8Array?new Uint8Array(new ArrayBuffer(t)):new Array(t),r=0;r<t;r++)n[r]=this.buffer[e++];return n},i.prototype.value=function(e){if((e=null!=e&&e)&&void 0!==r&&r.isBuffer(this.buffer)&&this.buffer.length===this.position)return this.buffer;if(void 0!==r&&r.isBuffer(this.buffer))return e?this.buffer.slice(0,this.position):this.buffer.toString("binary",0,this.position);if(e){if(null!=this.buffer.slice)return this.buffer.slice(0,this.position);for(var t="[object Uint8Array]"===Object.prototype.toString.call(this.buffer)?new Uint8Array(new ArrayBuffer(this.position)):new Array(this.position),n=0;n<this.position;n++)t[n]=this.buffer[n];return t}return c(this.buffer,0,this.position)},i.prototype.length=function(){return this.position},i.prototype.toJSON=function(){return null!=this.buffer?this.buffer.toString("base64"):""},i.prototype.toString=function(e){return null!=this.buffer?this.buffer.slice(0,this.position).toString(e):""};var s=0,a=function(e){for(var t="undefined"!=typeof Uint8Array?new Uint8Array(new ArrayBuffer(e.length)):new Array(e.length),n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t},c=function(e,t,n){for(var r="",o=t;o<n;o++)r+=String.fromCharCode(e[o]);return r};i.BUFFER_SIZE=256,i.SUBTYPE_DEFAULT=0,i.SUBTYPE_FUNCTION=1,i.SUBTYPE_BYTE_ARRAY=2,i.SUBTYPE_UUID_OLD=3,i.SUBTYPE_UUID=4,i.SUBTYPE_MD5=5,i.SUBTYPE_USER_DEFINED=128,e.exports=i,e.exports.Binary=i},function(e,t,n){"use strict";const r=n(3).MongoError,o=n(10),i=n(46),s=n(29);let a,c;a={NO_TRANSACTION:"NO_TRANSACTION",STARTING_TRANSACTION:"STARTING_TRANSACTION",TRANSACTION_IN_PROGRESS:"TRANSACTION_IN_PROGRESS",TRANSACTION_COMMITTED:"TRANSACTION_COMMITTED",TRANSACTION_COMMITTED_EMPTY:"TRANSACTION_COMMITTED_EMPTY",TRANSACTION_ABORTED:"TRANSACTION_ABORTED"},c={NO_TRANSACTION:["NO_TRANSACTION","STARTING_TRANSACTION"],STARTING_TRANSACTION:["TRANSACTION_IN_PROGRESS","TRANSACTION_COMMITTED","TRANSACTION_COMMITTED_EMPTY","TRANSACTION_ABORTED"],TRANSACTION_IN_PROGRESS:["TRANSACTION_IN_PROGRESS","TRANSACTION_COMMITTED","TRANSACTION_ABORTED"],TRANSACTION_COMMITTED:["TRANSACTION_COMMITTED","TRANSACTION_COMMITTED_EMPTY","STARTING_TRANSACTION","NO_TRANSACTION"],TRANSACTION_ABORTED:["STARTING_TRANSACTION","NO_TRANSACTION"],TRANSACTION_COMMITTED_EMPTY:["TRANSACTION_COMMITTED_EMPTY","NO_TRANSACTION"]};e.exports={TxnState:a,Transaction:class{constructor(e){e=e||{},this.state=a.NO_TRANSACTION,this.options={};const t=s.fromOptions(e);if(t){if(t.w<=0)throw new r("Transactions do not support unacknowledged write concern");this.options.writeConcern=t}e.readConcern&&(this.options.readConcern=i.fromOptions(e)),e.readPreference&&(this.options.readPreference=o.fromOptions(e)),e.maxCommitTimeMS&&(this.options.maxTimeMS=e.maxCommitTimeMS),this._pinnedServer=void 0,this._recoveryToken=void 0}get server(){return this._pinnedServer}get recoveryToken(){return this._recoveryToken}get isPinned(){return!!this.server}get isActive(){return-1!==[a.STARTING_TRANSACTION,a.TRANSACTION_IN_PROGRESS].indexOf(this.state)}transition(e){const t=c[this.state];if(t&&-1!==t.indexOf(e))return this.state=e,void(this.state!==a.NO_TRANSACTION&&this.state!==a.STARTING_TRANSACTION||this.unpinServer());throw new r(`Attempted illegal state transition from [${this.state}] to [${e}]`)}pinServer(e){this.isActive&&(this._pinnedServer=e)}unpinServer(){this._pinnedServer=void 0}},isTransactionCommand:function(e){return!(!e.commitTransaction&&!e.abortTransaction)}}},function(e,t,n){"use strict";const r=n(21).Query,o=n(45).Msg,i=n(3).MongoError,s=n(6).getReadPreference,a=n(6).isSharded,c=n(6).databaseNamespace,u=n(54).isTransactionCommand,l=n(34).applySession,f=n(3).MongoNetworkError,p=n(4).maxWireVersion;function d(e,t,n,p,d){const h=e.s.bson,m=e.s.pool,g=s(n,p),y=function(e){const t=e.ismaster?e.ismaster:e.description;if(null==t)return!1;return t.maxWireVersion>=6&&null==t.__nodejs_mock_server__}(e),b=p.session;let v=e.clusterTime,S=Object.assign({},n);if(function(e){if(null==e)return!1;if(e.description)return e.description.maxWireVersion>=6;return null!=e.ismaster&&e.ismaster.maxWireVersion>=6}(e)&&b){b.clusterTime&&b.clusterTime.clusterTime.greaterThan(v.clusterTime)&&(v=b.clusterTime);const e=l(b,S,p);if(e)return d(e)}v&&(S.$clusterTime=v),a(e)&&!y&&g&&"primary"!==g.mode&&(S={$query:S,$readPreference:g.toJSON()});const w=Object.assign({command:!0,numberToSkip:0,numberToReturn:-1,checkKeys:!1},p);w.slaveOk=g.slaveOk();const _=`${c(t)}.$cmd`,O=y?new o(h,_,S,w):new r(h,_,S,w),T=b&&(b.inTransaction()||u(S))?function(e){return e&&e instanceof f&&!e.hasErrorLabel("TransientTransactionError")&&e.addErrorLabel("TransientTransactionError"),!n.commitTransaction&&e&&e instanceof i&&e.hasErrorLabel("TransientTransactionError")&&b.transaction.unpinServer(),d.apply(null,arguments)}:d;try{m.write(O,w,T)}catch(e){T(e)}}e.exports=function(e,t,n,r,o){if("function"==typeof r&&(o=r,r={}),r=r||{},null==n)return o(new i(`command ${JSON.stringify(n)} does not return a cursor`));if(!function(e){return p(e)&&e.autoEncrypter}(e))return void d(e,t,n,r,o);const s=p(e);"number"!=typeof s||s<8?o(new i("Auto-encryption requires a minimum MongoDB version of 4.2")):function(e,t,n,r,o){const i=e.autoEncrypter;function s(e,t){e||null==t?o(e,t):i.decrypt(t.result,r,(e,n)=>{e?o(e,null):(t.result=n,t.message.documents=[n],o(null,t))})}i.encrypt(t,n,r,(n,i)=>{n?o(n,null):d(e,t,i,r,s)})}(e,t,n,r,o)}},function(e,t,n){"use strict";const r=n(0).maybePromise,o=n(3).MongoError,i=n(1).Aspect,s=n(1).OperationBase,a=n(10),c=n(3).isRetryableError,u=n(4).maxWireVersion,l=n(4).isUnifiedTopology;function f(e,t,n){if(null==e)throw new TypeError("This method requires a valid topology instance");if(!(t instanceof s))throw new TypeError("This method requires a valid operation instance");return r(e,n,n=>{if(l(e)&&e.shouldCheckForSessionSupport())return function(e,t,n){e.selectServer(a.primaryPreferred,r=>{if(r)return n(r);f(e,t,n)})}(e,t,n);let r,s;if(e.hasSessionSupport()){if(null==t.session)s=Symbol(),r=e.startSession({owner:s}),t.session=r;else if(t.session.hasEnded)return n(new o("Use of expired sessions is not permitted"))}else if(t.session)return n(new o("Current topology does not support sessions"));function u(e,o){r&&r.owner===s&&(r.endSession(),t.session===r&&t.clearSession()),n(e,o)}try{t.hasAspect(i.EXECUTE_WITH_SELECTION)?function(e,t,n){const r=t.readPreference||a.primary,s=t.session&&t.session.inTransaction();if(s&&!r.equals(a.primary))return void n(new o(`Read preference in a transaction must be primary, not: ${r.mode}`));const u={readPreference:r,session:t.session};function l(r,o){return null==r?n(null,o):c(r)?void e.selectServer(u,(e,r)=>{!e&&p(r)?t.execute(r,n):n(e,null)}):n(r)}e.selectServer(u,(r,o)=>{if(r)return void n(r,null);const a=!1!==e.s.options.retryReads&&t.session&&!s&&p(o)&&t.canRetryRead;t.hasAspect(i.RETRYABLE)&&a?t.execute(o,l):t.execute(o,n)})}(e,t,u):t.execute(u)}catch(e){r&&r.owner===s&&(r.endSession(),t.session===r&&t.clearSession()),n(e)}})}function p(e){return u(e)>=6}e.exports=f},function(e,t){function n(e){return Object.prototype.toString.call(e)}t.isArray=function(e){return Array.isArray?Array.isArray(e):"[object Array]"===n(e)},t.isBoolean=function(e){return"boolean"==typeof e},t.isNull=function(e){return null===e},t.isNullOrUndefined=function(e){return null==e},t.isNumber=function(e){return"number"==typeof e},t.isString=function(e){return"string"==typeof e},t.isSymbol=function(e){return"symbol"==typeof e},t.isUndefined=function(e){return void 0===e},t.isRegExp=function(e){return"[object RegExp]"===n(e)},t.isObject=function(e){return"object"==typeof e&&null!==e},t.isDate=function(e){return"[object Date]"===n(e)},t.isError=function(e){return"[object Error]"===n(e)||e instanceof Error},t.isFunction=function(e){return"function"==typeof e},t.isPrimitive=function(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||void 0===e},t.isBuffer=Buffer.isBuffer},function(e,t,n){try{var r=n(5);if("function"!=typeof r.inherits)throw"";e.exports=r.inherits}catch(t){e.exports=n(437)}},function(e,t,n){"use strict";const r=n(139),o=n(97),i=n(8).EventEmitter,s=n(5).inherits,a=n(2).MongoError,c=n(5).deprecate,u=n(29),l=n(0).MongoDBNamespace,f=n(10),p=n(0).maybePromise,d=n(219),h=n(220).connect,m=n(220).validOptions;function g(e,t){if(!(this instanceof g))return new g(e,t);i.call(this),t&&t.autoEncryption&&n(223),this.s={url:e,options:t||{},promiseLibrary:t&&t.promiseLibrary||Promise,dbCache:new Map,sessions:new Set,writeConcern:u.fromOptions(t),readPreference:f.fromOptions(t)||f.primary,namespace:new l("admin")}}s(g,i),Object.defineProperty(g.prototype,"writeConcern",{enumerable:!0,get:function(){return this.s.writeConcern}}),Object.defineProperty(g.prototype,"readPreference",{enumerable:!0,get:function(){return this.s.readPreference}}),g.prototype.connect=function(e){if("string"==typeof e)throw new TypeError("`connect` only accepts a callback");const t=this;return p(this,e,e=>{const n=m(t.s.options);if(n)return e(n);h(t,t.s.url,t.s.options,n=>{if(n)return e(n);e(null,t)})})},g.prototype.logout=c((function(e,t){"function"==typeof e&&(t=e,e={}),"function"==typeof t&&t(null,!0)}),"Multiple authentication is prohibited on a connected client, please only authenticate once per MongoClient"),g.prototype.close=function(e,t){"function"==typeof e&&(t=e,e=!1);const n=this;return p(this,t,t=>{const r=e=>{if(n.emit("close",n),!(n.topology instanceof d))for(const e of n.s.dbCache)e[1].emit("close",n);n.removeAllListeners("close"),t(e)};null!=n.topology?n.topology.close(e,t=>{const o=n.topology.s.options.encrypter;if(o)return o.close(n,e,e=>{r(t||e)});r(t)}):r()})},g.prototype.db=function(e,t){t=t||{},e||(e=this.s.options.dbName);const n=Object.assign({},this.s.options,t);if(this.s.dbCache.has(e)&&!0!==n.returnNonCachedInstance)return this.s.dbCache.get(e);if(n.promiseLibrary=this.s.promiseLibrary,!this.topology)throw new a("MongoClient must be connected before calling MongoClient.prototype.db");const r=new o(e,this.topology,n);return this.s.dbCache.set(e,r),r},g.prototype.isConnected=function(e){return e=e||{},!!this.topology&&this.topology.isConnected(e)},g.connect=function(e,t,n){const r=Array.prototype.slice.call(arguments,1);n="function"==typeof r[r.length-1]?r.pop():void 0;const o=new g(e,t=(t=r.length?r.shift():null)||{});return o.connect(n)},g.prototype.startSession=function(e){if(e=Object.assign({explicit:!0},e),!this.topology)throw new a("Must connect to a server before calling this method");return this.topology.startSession(e,this.s.options)},g.prototype.withSession=function(e,t){"function"==typeof e&&(t=e,e=void 0);const n=this.startSession(e);let r=(e,t,o)=>{if(r=()=>{throw new ReferenceError("cleanupHandler was called too many times")},o=Object.assign({throw:!0},o),n.endSession(),e){if(o.throw)throw e;return Promise.reject(e)}};try{const e=t(n);return Promise.resolve(e).then(e=>r(null,e)).catch(e=>r(e,null,{throw:!0}))}catch(e){return r(e,null,{throw:!1})}},g.prototype.watch=function(e,t){return e=e||[],t=t||{},Array.isArray(e)||(t=e,e=[]),new r(this,e,t)},g.prototype.getLogger=function(){return this.s.options.logger},e.exports=g},function(e,t,n){"use strict";const r=n(0).applyWriteConcern,o=n(2).BSON.Code,i=n(11).createIndex,s=n(0).decorateWithCollation,a=n(0).decorateWithReadConcern,c=n(11).ensureIndex,u=n(11).evaluate,l=n(11).executeCommand,f=n(0).handleCallback,p=n(11).indexInformation,d=n(2).BSON.Long,h=n(2).MongoError,m=n(2).ReadPreference,g=n(14).insertDocuments,y=n(14).updateDocuments;function b(e,t,n){p(e.s.db,e.collectionName,t,n)}e.exports={createIndex:function(e,t,n,r){i(e.s.db,e.collectionName,t,n,r)},createIndexes:function(e,t,n,r){const o=e.s.topology.capabilities();for(let e=0;e<t.length;e++)if(null==t[e].name){const n=[];if(t[e].collation&&o&&!o.commandsTakeCollation)return r(new h("server/primary/mongos does not support collation"));for(let r in t[e].key)n.push(`${r}_${t[e].key[r]}`);t[e].name=n.join("_")}n=Object.assign({},n,{readPreference:m.PRIMARY}),l(e.s.db,{createIndexes:e.collectionName,indexes:t},n,r)},ensureIndex:function(e,t,n,r){c(e.s.db,e.collectionName,t,n,r)},group:function(e,t,n,r,i,c,p,d,h){if(p){const u=i&&"Code"===i._bsontype?i:new o(i),p={group:{ns:e.collectionName,$reduce:u,cond:n,initial:r,out:"inline"}};if(null!=c&&(p.group.finalize=c),"function"==typeof t||t&&"Code"===t._bsontype)p.group.$keyf=t&&"Code"===t._bsontype?t:new o(t);else{const e={};t.forEach(t=>{e[t]=1}),p.group.key=e}(d=Object.assign({},d)).readPreference=m.resolve(e,d),a(p,e,d);try{s(p,e,d)}catch(e){return h(e,null)}l(e.s.db,p,d,(e,t)=>{if(e)return f(h,e,null);f(h,null,t.retval)})}else{const s=null!=i&&"Code"===i._bsontype?i.scope:{};s.ns=e.collectionName,s.keys=t,s.condition=n,s.initial=r;const a='function () {\nvar c = db[ns].find(condition);\nvar map = new Map();\nvar reduce_function = reduce;\n\nwhile (c.hasNext()) {\nvar obj = c.next();\nvar key = {};\n\nfor (var i = 0, len = keys.length; i < len; ++i) {\nvar k = keys[i];\nkey[k] = obj[k];\n}\n\nvar aggObj = map.get(key);\n\nif (aggObj == null) {\nvar newObj = Object.extend({}, key);\naggObj = Object.extend(newObj, initial);\nmap.put(key, aggObj);\n}\n\nreduce_function(obj, aggObj);\n}\n\nreturn { "result": map.values() };\n}'.replace(/ reduce;/,i.toString()+";");u(e.s.db,new o(a,s),null,d,(e,t)=>{if(e)return f(h,e,null);f(h,null,t.result||t)})}},indexes:function(e,t,n){t=Object.assign({},{full:!0},t),p(e.s.db,e.collectionName,t,n)},indexExists:function(e,t,n,r){b(e,n,(e,n)=>{if(null!=e)return f(r,e,null);if(!Array.isArray(t))return f(r,null,null!=n[t]);for(let e=0;e<t.length;e++)if(null==n[t[e]])return f(r,null,!1);return f(r,null,!0)})},indexInformation:b,parallelCollectionScan:function(e,t,n){const r={parallelCollectionScan:e.collectionName,numCursors:t.numCursors};a(r,e,t);const o=t.raw;delete t.raw,l(e.s.db,r,t,(r,i)=>{if(r)return f(n,r,null);if(null==i)return f(n,new Error("no result returned for parallelCollectionScan"),null);t=Object.assign({explicitlyIgnoreSession:!0},t);const s=[];o&&(t.raw=o);for(let n=0;n<i.cursors.length;n++){const r=i.cursors[n].cursor.id,o="number"==typeof r?d.fromNumber(r):r;s.push(e.s.topology.cursor(e.namespace,o,t))}f(n,null,s)})},save:function(e,t,n,o){const i=r(Object.assign({},n),{db:e.s.db,collection:e},n);if(null!=t._id)return i.upsert=!0,y(e,{_id:t._id},t,i,o);g(e,[t],i,(e,n)=>{if(null!=o)return null==t?f(o,null,null):e?f(o,e,null):void f(o,null,n)})}}},function(e,t,n){"use strict";const r=n(5).deprecate,o=n(0).deprecateOptions,i=n(0).emitWarningOnce,s=n(0).checkCollectionName,a=n(2).BSON.ObjectID,c=n(2).MongoError,u=n(0).normalizeHintField,l=n(0).decorateCommand,f=n(0).decorateWithCollation,p=n(0).decorateWithReadConcern,d=n(0).formattedOrderClause,h=n(2).ReadPreference,m=n(450),g=n(451),y=n(139),b=n(0).executeLegacyOperation,v=n(29),S=n(46),w=n(0).MongoDBNamespace,_=n(142),O=n(143),T=n(60).ensureIndex,C=n(60).group,x=n(60).parallelCollectionScan,E=n(14).removeDocuments,N=n(60).save,I=n(14).updateDocuments,A=n(95),k=n(209),M=n(452),R=n(210),j=n(453),D=n(454),P=n(455),B=n(144).DropCollectionOperation,L=n(211),q=n(456),U=n(457),z=n(458),$=n(459),W=n(96),F=n(460),V=n(461),K=n(462),H=n(463),Y=n(464),G=n(465),J=n(212),X=n(466),Z=n(467),Q=n(468),ee=n(469),te=n(470),ne=n(213),re=n(217),oe=n(479),ie=n(480),se=n(481),ae=n(482),ce=n(483),ue=n(56),le=["ignoreUndefined"];function fe(e,t,n,r,o,i){s(r);const c=null==i||null==i.slaveOk?e.slaveOk:i.slaveOk,u=null==i||null==i.serializeFunctions?e.s.options.serializeFunctions:i.serializeFunctions,l=null==i||null==i.raw?e.s.options.raw:i.raw,f=null==i||null==i.promoteLongs?e.s.options.promoteLongs:i.promoteLongs,p=null==i||null==i.promoteValues?e.s.options.promoteValues:i.promoteValues,d=null==i||null==i.promoteBuffers?e.s.options.promoteBuffers:i.promoteBuffers,m=new w(n,r),g=i.promiseLibrary||Promise;o=null==o?a:o,this.s={pkFactory:o,db:e,topology:t,options:i,namespace:m,readPreference:h.fromOptions(i),slaveOk:c,serializeFunctions:u,raw:l,promoteLongs:f,promoteValues:p,promoteBuffers:d,internalHint:null,collectionHint:null,promiseLibrary:g,readConcern:S.fromOptions(i),writeConcern:v.fromOptions(i)}}Object.defineProperty(fe.prototype,"dbName",{enumerable:!0,get:function(){return this.s.namespace.db}}),Object.defineProperty(fe.prototype,"collectionName",{enumerable:!0,get:function(){return this.s.namespace.collection}}),Object.defineProperty(fe.prototype,"namespace",{enumerable:!0,get:function(){return this.s.namespace.toString()}}),Object.defineProperty(fe.prototype,"readConcern",{enumerable:!0,get:function(){return null==this.s.readConcern?this.s.db.readConcern:this.s.readConcern}}),Object.defineProperty(fe.prototype,"readPreference",{enumerable:!0,get:function(){return null==this.s.readPreference?this.s.db.readPreference:this.s.readPreference}}),Object.defineProperty(fe.prototype,"writeConcern",{enumerable:!0,get:function(){return null==this.s.writeConcern?this.s.db.writeConcern:this.s.writeConcern}}),Object.defineProperty(fe.prototype,"hint",{enumerable:!0,get:function(){return this.s.collectionHint},set:function(e){this.s.collectionHint=u(e)}});const pe=["maxScan","fields","snapshot","oplogReplay"];function de(e,t,n,r,o){const i=Array.prototype.slice.call(arguments,1);return o="function"==typeof i[i.length-1]?i.pop():void 0,t=i.length&&i.shift()||[],n=i.length?i.shift():null,r=i.length&&i.shift()||{},(r=Object.assign({},r)).readPreference=h.PRIMARY,ue(this.s.topology,new W(this,e,t,n,r),o)}fe.prototype.find=o({name:"collection.find",deprecatedOptions:pe,optionsIndex:1},(function(e,t,n){"object"==typeof n&&i("Third parameter to `find()` must be a callback or undefined");let r=e;"function"!=typeof n&&("function"==typeof t?(n=t,t=void 0):null==t&&(n="function"==typeof r?r:void 0,r="object"==typeof r?r:void 0)),r=null==r?{}:r;const o=r;if(Buffer.isBuffer(o)){const e=o[0]|o[1]<<8|o[2]<<16|o[3]<<24;if(e!==o.length){const t=new Error("query selector raw message size does not match message header size ["+o.length+"] != ["+e+"]");throw t.name="MongoError",t}}null!=r&&"ObjectID"===r._bsontype&&(r={_id:r}),t||(t={});let s=t.projection||t.fields;s&&!Buffer.isBuffer(s)&&Array.isArray(s)&&(s=s.length?s.reduce((e,t)=>(e[t]=1,e),{}):{_id:1});let a=Object.assign({},t);for(let e in this.s.options)-1!==le.indexOf(e)&&(a[e]=this.s.options[e]);if(a.skip=t.skip?t.skip:0,a.limit=t.limit?t.limit:0,a.raw="boolean"==typeof t.raw?t.raw:this.s.raw,a.hint=null!=t.hint?u(t.hint):this.s.collectionHint,a.timeout=void 0===t.timeout?void 0:t.timeout,a.slaveOk=null!=t.slaveOk?t.slaveOk:this.s.db.slaveOk,a.readPreference=h.resolve(this,a),null==a.readPreference||"primary"===a.readPreference&&"primary"===a.readPreference.mode||(a.slaveOk=!0),null!=r&&"object"!=typeof r)throw c.create({message:"query selector must be an object",driver:!0});const m={find:this.s.namespace.toString(),limit:a.limit,skip:a.skip,query:r};"boolean"==typeof t.allowDiskUse&&(m.allowDiskUse=t.allowDiskUse),"boolean"==typeof a.awaitdata&&(a.awaitData=a.awaitdata),"boolean"==typeof a.timeout&&(a.noCursorTimeout=!a.timeout),l(m,a,["session","collation"]),s&&(m.fields=s),a.db=this.s.db,a.promiseLibrary=this.s.promiseLibrary,null==a.raw&&"boolean"==typeof this.s.raw&&(a.raw=this.s.raw),null==a.promoteLongs&&"boolean"==typeof this.s.promoteLongs&&(a.promoteLongs=this.s.promoteLongs),null==a.promoteValues&&"boolean"==typeof this.s.promoteValues&&(a.promoteValues=this.s.promoteValues),null==a.promoteBuffers&&"boolean"==typeof this.s.promoteBuffers&&(a.promoteBuffers=this.s.promoteBuffers),m.sort&&(m.sort=d(m.sort)),p(m,this,t);try{f(m,this,t)}catch(e){if("function"==typeof n)return n(e,null);throw e}const g=this.s.topology.cursor(new z(this,this.s.namespace,m,a),a);if("function"!=typeof n)return g;n(null,g)})),fe.prototype.insertOne=function(e,t,n){"function"==typeof t&&(n=t,t={}),t=t||{},this.s.options.ignoreUndefined&&((t=Object.assign({},t)).ignoreUndefined=this.s.options.ignoreUndefined);const r=new Z(this,e,t);return ue(this.s.topology,r,n)},fe.prototype.insertMany=function(e,t,n){"function"==typeof t&&(n=t,t={}),t=t?Object.assign({},t):{ordered:!0};const r=new X(this,e,t);return ue(this.s.topology,r,n)},fe.prototype.bulkWrite=function(e,t,n){if("function"==typeof t&&(n=t,t={}),t=t||{ordered:!0},!Array.isArray(e))throw c.create({message:"operations must be an array of documents",driver:!0});const r=new k(this,e,t);return ue(this.s.topology,r,n)},fe.prototype.insert=r((function(e,t,n){return"function"==typeof t&&(n=t,t={}),t=t||{ordered:!1},e=Array.isArray(e)?e:[e],!0===t.keepGoing&&(t.ordered=!1),this.insertMany(e,t,n)}),"collection.insert is deprecated. Use insertOne, insertMany or bulkWrite instead."),fe.prototype.updateOne=function(e,t,n,r){return"function"==typeof n&&(r=n,n={}),n=Object.assign({},n),this.s.options.ignoreUndefined&&((n=Object.assign({},n)).ignoreUndefined=this.s.options.ignoreUndefined),ue(this.s.topology,new ce(this,e,t,n),r)},fe.prototype.replaceOne=function(e,t,n,r){return"function"==typeof n&&(r=n,n={}),n=Object.assign({},n),this.s.options.ignoreUndefined&&((n=Object.assign({},n)).ignoreUndefined=this.s.options.ignoreUndefined),ue(this.s.topology,new ie(this,e,t,n),r)},fe.prototype.updateMany=function(e,t,n,r){return"function"==typeof n&&(r=n,n={}),n=Object.assign({},n),this.s.options.ignoreUndefined&&((n=Object.assign({},n)).ignoreUndefined=this.s.options.ignoreUndefined),ue(this.s.topology,new ae(this,e,t,n),r)},fe.prototype.update=r((function(e,t,n,r){return"function"==typeof n&&(r=n,n={}),n=n||{},this.s.options.ignoreUndefined&&((n=Object.assign({},n)).ignoreUndefined=this.s.options.ignoreUndefined),b(this.s.topology,I,[this,e,t,n,r])}),"collection.update is deprecated. Use updateOne, updateMany, or bulkWrite instead."),fe.prototype.deleteOne=function(e,t,n){"function"==typeof t&&(n=t,t={}),t=Object.assign({},t),this.s.options.ignoreUndefined&&((t=Object.assign({},t)).ignoreUndefined=this.s.options.ignoreUndefined);const r=new D(this,e,t);return ue(this.s.topology,r,n)},fe.prototype.removeOne=fe.prototype.deleteOne,fe.prototype.deleteMany=function(e,t,n){"function"==typeof t&&(n=t,t={}),t=Object.assign({},t),this.s.options.ignoreUndefined&&((t=Object.assign({},t)).ignoreUndefined=this.s.options.ignoreUndefined);const r=new j(this,e,t);return ue(this.s.topology,r,n)},fe.prototype.removeMany=fe.prototype.deleteMany,fe.prototype.remove=r((function(e,t,n){return"function"==typeof t&&(n=t,t={}),t=t||{},this.s.options.ignoreUndefined&&((t=Object.assign({},t)).ignoreUndefined=this.s.options.ignoreUndefined),b(this.s.topology,E,[this,e,t,n])}),"collection.remove is deprecated. Use deleteOne, deleteMany, or bulkWrite instead."),fe.prototype.save=r((function(e,t,n){return"function"==typeof t&&(n=t,t={}),t=t||{},this.s.options.ignoreUndefined&&((t=Object.assign({},t)).ignoreUndefined=this.s.options.ignoreUndefined),b(this.s.topology,N,[this,e,t,n])}),"collection.save is deprecated. Use insertOne, insertMany, updateOne, or updateMany instead."),fe.prototype.findOne=o({name:"collection.find",deprecatedOptions:pe,optionsIndex:1},(function(e,t,n){"object"==typeof n&&i("Third parameter to `findOne()` must be a callback or undefined"),"function"==typeof e&&(n=e,e={},t={}),"function"==typeof t&&(n=t,t={});const r=new $(this,e=e||{},t=t||{});return ue(this.s.topology,r,n)})),fe.prototype.rename=function(e,t,n){"function"==typeof t&&(n=t,t={}),t=Object.assign({},t,{readPreference:h.PRIMARY});const r=new re(this,e,t);return ue(this.s.topology,r,n)},fe.prototype.drop=function(e,t){"function"==typeof e&&(t=e,e={}),e=e||{};const n=new B(this.s.db,this.collectionName,e);return ue(this.s.topology,n,t)},fe.prototype.options=function(e,t){"function"==typeof e&&(t=e,e={});const n=new ne(this,e=e||{});return ue(this.s.topology,n,t)},fe.prototype.isCapped=function(e,t){"function"==typeof e&&(t=e,e={});const n=new Q(this,e=e||{});return ue(this.s.topology,n,t)},fe.prototype.createIndex=function(e,t,n){"function"==typeof t&&(n=t,t={}),t=t||{};const r=new R(this,this.collectionName,e,t);return ue(this.s.topology,r,n)},fe.prototype.createIndexes=function(e,t,n){"function"==typeof t&&(n=t,t={}),"number"!=typeof(t=t?Object.assign({},t):{}).maxTimeMS&&delete t.maxTimeMS;const r=new R(this,this.collectionName,e,t);return ue(this.s.topology,r,n)},fe.prototype.dropIndex=function(e,t,n){const r=Array.prototype.slice.call(arguments,1);n="function"==typeof r[r.length-1]?r.pop():void 0,(t=r.length&&r.shift()||{}).readPreference=h.PRIMARY;const o=new L(this,e,t);return ue(this.s.topology,o,n)},fe.prototype.dropIndexes=function(e,t){"function"==typeof e&&(t=e,e={}),"number"!=typeof(e=e?Object.assign({},e):{}).maxTimeMS&&delete e.maxTimeMS;const n=new q(this,e);return ue(this.s.topology,n,t)},fe.prototype.dropAllIndexes=r(fe.prototype.dropIndexes,"collection.dropAllIndexes is deprecated. Use dropIndexes instead."),fe.prototype.reIndex=r((function(e,t){"function"==typeof e&&(t=e,e={});const n=new oe(this,e=e||{});return ue(this.s.topology,n,t)}),"collection.reIndex is deprecated. Use db.command instead."),fe.prototype.listIndexes=function(e){return new O(this.s.topology,new ee(this,e),e)},fe.prototype.ensureIndex=r((function(e,t,n){return"function"==typeof t&&(n=t,t={}),t=t||{},b(this.s.topology,T,[this,e,t,n])}),"collection.ensureIndex is deprecated. Use createIndexes instead."),fe.prototype.indexExists=function(e,t,n){"function"==typeof t&&(n=t,t={});const r=new G(this,e,t=t||{});return ue(this.s.topology,r,n)},fe.prototype.indexInformation=function(e,t){const n=Array.prototype.slice.call(arguments,0);t="function"==typeof n[n.length-1]?n.pop():void 0,e=n.length&&n.shift()||{};const r=new J(this.s.db,this.collectionName,e);return ue(this.s.topology,r,t)},fe.prototype.count=r((function(e,t,n){const r=Array.prototype.slice.call(arguments,0);return n="function"==typeof r[r.length-1]?r.pop():void 0,e=r.length&&r.shift()||{},"function"==typeof(t=r.length&&r.shift()||{})&&(n=t,t={}),t=t||{},ue(this.s.topology,new U(this,e,t),n)}),"collection.count is deprecated, and will be removed in a future version. Use Collection.countDocuments or Collection.estimatedDocumentCount instead"),fe.prototype.estimatedDocumentCount=function(e,t){"function"==typeof e&&(t=e,e={});const n=new U(this,e=e||{});return ue(this.s.topology,n,t)},fe.prototype.countDocuments=function(e,t,n){const r=Array.prototype.slice.call(arguments,0);n="function"==typeof r[r.length-1]?r.pop():void 0,e=r.length&&r.shift()||{},t=r.length&&r.shift()||{};const o=new M(this,e,t);return ue(this.s.topology,o,n)},fe.prototype.distinct=function(e,t,n,r){const o=Array.prototype.slice.call(arguments,1);r="function"==typeof o[o.length-1]?o.pop():void 0;const i=o.length&&o.shift()||{},s=o.length&&o.shift()||{},a=new P(this,e,i,s);return ue(this.s.topology,a,r)},fe.prototype.indexes=function(e,t){"function"==typeof e&&(t=e,e={});const n=new Y(this,e=e||{});return ue(this.s.topology,n,t)},fe.prototype.stats=function(e,t){const n=Array.prototype.slice.call(arguments,0);t="function"==typeof n[n.length-1]?n.pop():void 0,e=n.length&&n.shift()||{};const r=new se(this,e);return ue(this.s.topology,r,t)},fe.prototype.findOneAndDelete=function(e,t,n){return"function"==typeof t&&(n=t,t={}),t=t||{},this.s.options.ignoreUndefined&&((t=Object.assign({},t)).ignoreUndefined=this.s.options.ignoreUndefined),ue(this.s.topology,new F(this,e,t),n)},fe.prototype.findOneAndReplace=function(e,t,n,r){return"function"==typeof n&&(r=n,n={}),n=n||{},this.s.options.ignoreUndefined&&((n=Object.assign({},n)).ignoreUndefined=this.s.options.ignoreUndefined),ue(this.s.topology,new V(this,e,t,n),r)},fe.prototype.findOneAndUpdate=function(e,t,n,r){return"function"==typeof n&&(r=n,n={}),n=n||{},this.s.options.ignoreUndefined&&((n=Object.assign({},n)).ignoreUndefined=this.s.options.ignoreUndefined),ue(this.s.topology,new K(this,e,t,n),r)},fe.prototype.findAndModify=r(de,"collection.findAndModify is deprecated. Use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead."),fe.prototype._findAndModify=de,fe.prototype.findAndRemove=r((function(e,t,n,r){const o=Array.prototype.slice.call(arguments,1);return r="function"==typeof o[o.length-1]?o.pop():void 0,t=o.length&&o.shift()||[],(n=o.length&&o.shift()||{}).remove=!0,ue(this.s.topology,new W(this,e,t,null,n),r)}),"collection.findAndRemove is deprecated. Use findOneAndDelete instead."),fe.prototype.aggregate=function(e,t,n){if(Array.isArray(e))"function"==typeof t&&(n=t,t={}),null==t&&null==n&&(t={});else{const r=Array.prototype.slice.call(arguments,0);n=r.pop();const o=r[r.length-1];t=o&&(o.readPreference||o.explain||o.cursor||o.out||o.maxTimeMS||o.hint||o.allowDiskUse)?r.pop():{},e=r}const r=new _(this.s.topology,new A(this,e,t),t);if("function"!=typeof n)return r;n(null,r)},fe.prototype.watch=function(e,t){return e=e||[],t=t||{},Array.isArray(e)||(t=e,e=[]),new y(this,e,t)},fe.prototype.parallelCollectionScan=r((function(e,t){return"function"==typeof e&&(t=e,e={numCursors:1}),e.numCursors=e.numCursors||1,e.batchSize=e.batchSize||1e3,(e=Object.assign({},e)).readPreference=h.resolve(this,e),e.promiseLibrary=this.s.promiseLibrary,e.session&&(e.session=void 0),b(this.s.topology,x,[this,e,t],{skipSessions:!0})}),"parallelCollectionScan is deprecated in MongoDB v4.1"),fe.prototype.geoHaystackSearch=r((function(e,t,n,r){const o=Array.prototype.slice.call(arguments,2);r="function"==typeof o[o.length-1]?o.pop():void 0,n=o.length&&o.shift()||{};const i=new H(this,e,t,n);return ue(this.s.topology,i,r)}),"geoHaystackSearch is deprecated, and will be removed in a future version."),fe.prototype.group=r((function(e,t,n,r,o,i,s,a){const c=Array.prototype.slice.call(arguments,3);return a="function"==typeof c[c.length-1]?c.pop():void 0,r=c.length?c.shift():null,o=c.length?c.shift():null,i=c.length?c.shift():null,s=c.length&&c.shift()||{},"function"!=typeof o&&(i=o,o=null),!Array.isArray(e)&&e instanceof Object&&"function"!=typeof e&&"Code"!==e._bsontype&&(e=Object.keys(e)),"function"==typeof r&&(r=r.toString()),"function"==typeof o&&(o=o.toString()),i=null==i||i,b(this.s.topology,C,[this,e,t,n,r,o,i,s,a])}),"MongoDB 3.6 or higher no longer supports the group command. We recommend rewriting using the aggregation framework."),fe.prototype.mapReduce=function(e,t,n,r){if("function"==typeof n&&(r=n,n={}),null==n.out)throw new Error("the out option parameter must be defined, see mongodb docs for possible values");"function"==typeof e&&(e=e.toString()),"function"==typeof t&&(t=t.toString()),"function"==typeof n.finalize&&(n.finalize=n.finalize.toString());const o=new te(this,e,t,n);return ue(this.s.topology,o,r)},fe.prototype.initializeUnorderedBulkOp=function(e){return null==(e=e||{}).ignoreUndefined&&(e.ignoreUndefined=this.s.options.ignoreUndefined),e.promiseLibrary=this.s.promiseLibrary,m(this.s.topology,this,e)},fe.prototype.initializeOrderedBulkOp=function(e){return null==(e=e||{}).ignoreUndefined&&(e.ignoreUndefined=this.s.options.ignoreUndefined),e.promiseLibrary=this.s.promiseLibrary,g(this.s.topology,this,e)},fe.prototype.getLogger=function(){return this.s.db.s.logger},e.exports=fe},function(e,t){e.exports=function(e){return e.webpackPolyfill||(e.deprecate=function(){},e.paths=[],e.children||(e.children=[]),Object.defineProperty(e,"loaded",{enumerable:!0,get:function(){return e.l}}),Object.defineProperty(e,"id",{enumerable:!0,get:function(){return e.i}}),e.webpackPolyfill=1),e}},function(e,t,n){var r=n(237),o=n(238),i=n(239),s=n(240),a=n(241);function c(e){var t=-1,n=null==e?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}c.prototype.clear=r,c.prototype.delete=o,c.prototype.get=i,c.prototype.has=s,c.prototype.set=a,e.exports=c},function(e,t,n){var r=n(65);e.exports=function(e,t){for(var n=e.length;n--;)if(r(e[n][0],t))return n;return-1}},function(e,t){e.exports=function(e,t){return e===t||e!=e&&t!=t}},function(e,t,n){var r=n(31)(Object,"create");e.exports=r},function(e,t,n){var r=n(261);e.exports=function(e,t){var n=e.__data__;return r(t)?n["string"==typeof t?"string":"hash"]:n.map}},function(e,t){var n=/^(?:0|[1-9]\d*)$/;e.exports=function(e,t){var r=typeof e;return!!(t=null==t?9007199254740991:t)&&("number"==r||"symbol"!=r&&n.test(e))&&e>-1&&e%1==0&&e<t}},function(e,t,n){(function(e){var r=n(149),o=t&&!t.nodeType&&t,i=o&&"object"==typeof e&&e&&!e.nodeType&&e,s=i&&i.exports===o&&r.process,a=function(){try{var e=i&&i.require&&i.require("util").types;return e||s&&s.binding&&s.binding("util")}catch(e){}}();e.exports=a}).call(this,n(62)(e))},function(e,t,n){var r=n(281),o=n(103),i=n(282),s=n(160),a=n(283),c=n(25),u=n(150),l=u(r),f=u(o),p=u(i),d=u(s),h=u(a),m=c;(r&&"[object DataView]"!=m(new r(new ArrayBuffer(1)))||o&&"[object Map]"!=m(new o)||i&&"[object Promise]"!=m(i.resolve())||s&&"[object Set]"!=m(new s)||a&&"[object WeakMap]"!=m(new a))&&(m=function(e){var t=c(e),n="[object Object]"==t?e.constructor:void 0,r=n?u(n):"";if(r)switch(r){case l:return"[object DataView]";case f:return"[object Map]";case p:return"[object Promise]";case d:return"[object Set]";case h:return"[object WeakMap]"}return t}),e.exports=m},function(e,t,n){var r=n(25),o=n(15);e.exports=function(e){return"symbol"==typeof e||o(e)&&"[object Symbol]"==r(e)}},function(e,t,n){var r=n(25),o=n(12),i=n(15);e.exports=function(e){return"string"==typeof e||!o(e)&&i(e)&&"[object String]"==r(e)}},function(e,t,n){var r=n(25),o=n(114),i=n(15),s=Function.prototype,a=Object.prototype,c=s.toString,u=a.hasOwnProperty,l=c.call(Object);e.exports=function(e){if(!i(e)||"[object Object]"!=r(e))return!1;var t=o(e);if(null===t)return!0;var n=u.call(t,"constructor")&&t.constructor;return"function"==typeof n&&n instanceof n&&c.call(n)==l}},function(e,t){e.exports=function(e){return e}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dumpSqlCommand=t.dumpSqlInsert=t.dumpSqlDelete=t.dumpSqlUpdate=t.dumpSqlSelect=void 0;const r=n(180),o=n(126),i=n(127);function s(e,t){e.put("^select "),t.distinct&&e.put("^distinct "),t.topRecords&&(e.dialect.rangeSelect&&!e.dialect.offsetFetchRangeSyntax||e.put("^top %s ",t.topRecords)),t.selectAll&&e.put("* "),t.columns&&(t.selectAll&&e.put("&n,"),e.put("&>&n"),e.putCollection(",&n",t.columns,t=>{(0,r.dumpSqlExpression)(e,t),t.alias&&e.put(" ^as %i",t.alias)}),e.put("&n&<")),e.put("^from "),(0,o.dumpSqlFromDefinition)(e,t.from),t.where&&(e.put("&n^where "),(0,i.dumpSqlCondition)(e,t.where),e.put("&n")),t.groupBy&&(e.put("&n^group ^by "),e.putCollection(", ",t.groupBy,t=>(0,r.dumpSqlExpression)(e,t)),e.put("&n")),t.having&&(e.put("&n^having "),(0,i.dumpSqlCondition)(e,t.having),e.put("&n")),t.orderBy&&(e.put("&n^order ^by "),e.putCollection(", ",t.orderBy,t=>{(0,r.dumpSqlExpression)(e,t),e.put(" %k",t.direction)}),e.put("&n")),t.range&&(e.dialect.offsetFetchRangeSyntax?e.put("^offset %s ^rows ^fetch ^next %s ^rows ^only",t.range.offset,t.range.limit):e.put("^limit %s ^offset %s ",t.range.limit,t.range.offset)),t.topRecords&&e.dialect.rangeSelect&&!e.dialect.offsetFetchRangeSyntax&&e.put("^limit %s ",t.topRecords)}function a(e,t){e.put("^update "),(0,o.dumpSqlSourceRef)(e,t.from),e.put("&n^set "),e.put("&>"),e.putCollection(", ",t.fields,t=>{e.put("%i=",t.targetColumn),(0,r.dumpSqlExpression)(e,t)}),e.put("&<"),t.where&&(e.put("&n^where "),(0,i.dumpSqlCondition)(e,t.where),e.put("&n"))}function c(e,t){e.put("^delete ^from "),(0,o.dumpSqlSourceRef)(e,t.from),t.where&&(e.put("&n^where "),(0,i.dumpSqlCondition)(e,t.where),e.put("&n"))}function u(e,t){e.put("^insert ^into %f (%,i) ^values (",t.targetTable,t.fields.map(e=>e.targetColumn)),e.putCollection(",",t.fields,t=>(0,r.dumpSqlExpression)(e,t)),e.put(")")}t.dumpSqlSelect=s,t.dumpSqlUpdate=a,t.dumpSqlDelete=c,t.dumpSqlInsert=u,t.dumpSqlCommand=function(e,t){switch(t.commandType){case"select":s(e,t);break;case"update":a(e,t);break;case"delete":c(e,t);break;case"insert":u(e,t);break;case"allowIdentityInsert":e.allowIdentityInsert(t.targetTable,t.allow)}}},function(e,t){function n(e){if(!(this instanceof n))return new n(e);this._bsontype="Double",this.value=e}n.prototype.valueOf=function(){return this.value},n.prototype.toJSON=function(){return this.value},e.exports=n,e.exports.Double=n},function(e,t){function n(e,t){if(!(this instanceof n))return new n(e,t);this._bsontype="Timestamp",this.low_=0|e,this.high_=0|t}n.prototype.toInt=function(){return this.low_},n.prototype.toNumber=function(){return this.high_*n.TWO_PWR_32_DBL_+this.getLowBitsUnsigned()},n.prototype.toJSON=function(){return this.toString()},n.prototype.toString=function(e){var t=e||10;if(t<2||36<t)throw Error("radix out of range: "+t);if(this.isZero())return"0";if(this.isNegative()){if(this.equals(n.MIN_VALUE)){var r=n.fromNumber(t),o=this.div(r),i=o.multiply(r).subtract(this);return o.toString(t)+i.toInt().toString(t)}return"-"+this.negate().toString(t)}var s=n.fromNumber(Math.pow(t,6));i=this;for(var a="";!i.isZero();){var c=i.div(s),u=i.subtract(c.multiply(s)).toInt().toString(t);if((i=c).isZero())return u+a;for(;u.length<6;)u="0"+u;a=""+u+a}},n.prototype.getHighBits=function(){return this.high_},n.prototype.getLowBits=function(){return this.low_},n.prototype.getLowBitsUnsigned=function(){return this.low_>=0?this.low_:n.TWO_PWR_32_DBL_+this.low_},n.prototype.getNumBitsAbs=function(){if(this.isNegative())return this.equals(n.MIN_VALUE)?64:this.negate().getNumBitsAbs();for(var e=0!==this.high_?this.high_:this.low_,t=31;t>0&&0==(e&1<<t);t--);return 0!==this.high_?t+33:t+1},n.prototype.isZero=function(){return 0===this.high_&&0===this.low_},n.prototype.isNegative=function(){return this.high_<0},n.prototype.isOdd=function(){return 1==(1&this.low_)},n.prototype.equals=function(e){return this.high_===e.high_&&this.low_===e.low_},n.prototype.notEquals=function(e){return this.high_!==e.high_||this.low_!==e.low_},n.prototype.lessThan=function(e){return this.compare(e)<0},n.prototype.lessThanOrEqual=function(e){return this.compare(e)<=0},n.prototype.greaterThan=function(e){return this.compare(e)>0},n.prototype.greaterThanOrEqual=function(e){return this.compare(e)>=0},n.prototype.compare=function(e){if(this.equals(e))return 0;var t=this.isNegative(),n=e.isNegative();return t&&!n?-1:!t&&n?1:this.subtract(e).isNegative()?-1:1},n.prototype.negate=function(){return this.equals(n.MIN_VALUE)?n.MIN_VALUE:this.not().add(n.ONE)},n.prototype.add=function(e){var t=this.high_>>>16,r=65535&this.high_,o=this.low_>>>16,i=65535&this.low_,s=e.high_>>>16,a=65535&e.high_,c=e.low_>>>16,u=0,l=0,f=0,p=0;return f+=(p+=i+(65535&e.low_))>>>16,p&=65535,l+=(f+=o+c)>>>16,f&=65535,u+=(l+=r+a)>>>16,l&=65535,u+=t+s,u&=65535,n.fromBits(f<<16|p,u<<16|l)},n.prototype.subtract=function(e){return this.add(e.negate())},n.prototype.multiply=function(e){if(this.isZero())return n.ZERO;if(e.isZero())return n.ZERO;if(this.equals(n.MIN_VALUE))return e.isOdd()?n.MIN_VALUE:n.ZERO;if(e.equals(n.MIN_VALUE))return this.isOdd()?n.MIN_VALUE:n.ZERO;if(this.isNegative())return e.isNegative()?this.negate().multiply(e.negate()):this.negate().multiply(e).negate();if(e.isNegative())return this.multiply(e.negate()).negate();if(this.lessThan(n.TWO_PWR_24_)&&e.lessThan(n.TWO_PWR_24_))return n.fromNumber(this.toNumber()*e.toNumber());var t=this.high_>>>16,r=65535&this.high_,o=this.low_>>>16,i=65535&this.low_,s=e.high_>>>16,a=65535&e.high_,c=e.low_>>>16,u=65535&e.low_,l=0,f=0,p=0,d=0;return p+=(d+=i*u)>>>16,d&=65535,f+=(p+=o*u)>>>16,p&=65535,f+=(p+=i*c)>>>16,p&=65535,l+=(f+=r*u)>>>16,f&=65535,l+=(f+=o*c)>>>16,f&=65535,l+=(f+=i*a)>>>16,f&=65535,l+=t*u+r*c+o*a+i*s,l&=65535,n.fromBits(p<<16|d,l<<16|f)},n.prototype.div=function(e){if(e.isZero())throw Error("division by zero");if(this.isZero())return n.ZERO;if(this.equals(n.MIN_VALUE)){if(e.equals(n.ONE)||e.equals(n.NEG_ONE))return n.MIN_VALUE;if(e.equals(n.MIN_VALUE))return n.ONE;var t=this.shiftRight(1).div(e).shiftLeft(1);if(t.equals(n.ZERO))return e.isNegative()?n.ONE:n.NEG_ONE;var r=this.subtract(e.multiply(t));return t.add(r.div(e))}if(e.equals(n.MIN_VALUE))return n.ZERO;if(this.isNegative())return e.isNegative()?this.negate().div(e.negate()):this.negate().div(e).negate();if(e.isNegative())return this.div(e.negate()).negate();var o=n.ZERO;for(r=this;r.greaterThanOrEqual(e);){t=Math.max(1,Math.floor(r.toNumber()/e.toNumber()));for(var i=Math.ceil(Math.log(t)/Math.LN2),s=i<=48?1:Math.pow(2,i-48),a=n.fromNumber(t),c=a.multiply(e);c.isNegative()||c.greaterThan(r);)t-=s,c=(a=n.fromNumber(t)).multiply(e);a.isZero()&&(a=n.ONE),o=o.add(a),r=r.subtract(c)}return o},n.prototype.modulo=function(e){return this.subtract(this.div(e).multiply(e))},n.prototype.not=function(){return n.fromBits(~this.low_,~this.high_)},n.prototype.and=function(e){return n.fromBits(this.low_&e.low_,this.high_&e.high_)},n.prototype.or=function(e){return n.fromBits(this.low_|e.low_,this.high_|e.high_)},n.prototype.xor=function(e){return n.fromBits(this.low_^e.low_,this.high_^e.high_)},n.prototype.shiftLeft=function(e){if(0===(e&=63))return this;var t=this.low_;if(e<32){var r=this.high_;return n.fromBits(t<<e,r<<e|t>>>32-e)}return n.fromBits(0,t<<e-32)},n.prototype.shiftRight=function(e){if(0===(e&=63))return this;var t=this.high_;if(e<32){var r=this.low_;return n.fromBits(r>>>e|t<<32-e,t>>e)}return n.fromBits(t>>e-32,t>=0?0:-1)},n.prototype.shiftRightUnsigned=function(e){if(0===(e&=63))return this;var t=this.high_;if(e<32){var r=this.low_;return n.fromBits(r>>>e|t<<32-e,t>>>e)}return 32===e?n.fromBits(t,0):n.fromBits(t>>>e-32,0)},n.fromInt=function(e){if(-128<=e&&e<128){var t=n.INT_CACHE_[e];if(t)return t}var r=new n(0|e,e<0?-1:0);return-128<=e&&e<128&&(n.INT_CACHE_[e]=r),r},n.fromNumber=function(e){return isNaN(e)||!isFinite(e)?n.ZERO:e<=-n.TWO_PWR_63_DBL_?n.MIN_VALUE:e+1>=n.TWO_PWR_63_DBL_?n.MAX_VALUE:e<0?n.fromNumber(-e).negate():new n(e%n.TWO_PWR_32_DBL_|0,e/n.TWO_PWR_32_DBL_|0)},n.fromBits=function(e,t){return new n(e,t)},n.fromString=function(e,t){if(0===e.length)throw Error("number format error: empty string");var r=t||10;if(r<2||36<r)throw Error("radix out of range: "+r);if("-"===e.charAt(0))return n.fromString(e.substring(1),r).negate();if(e.indexOf("-")>=0)throw Error('number format error: interior "-" character: '+e);for(var o=n.fromNumber(Math.pow(r,8)),i=n.ZERO,s=0;s<e.length;s+=8){var a=Math.min(8,e.length-s),c=parseInt(e.substring(s,s+a),r);if(a<8){var u=n.fromNumber(Math.pow(r,a));i=i.multiply(u).add(n.fromNumber(c))}else i=(i=i.multiply(o)).add(n.fromNumber(c))}return i},n.INT_CACHE_={},n.TWO_PWR_16_DBL_=65536,n.TWO_PWR_24_DBL_=1<<24,n.TWO_PWR_32_DBL_=n.TWO_PWR_16_DBL_*n.TWO_PWR_16_DBL_,n.TWO_PWR_31_DBL_=n.TWO_PWR_32_DBL_/2,n.TWO_PWR_48_DBL_=n.TWO_PWR_32_DBL_*n.TWO_PWR_16_DBL_,n.TWO_PWR_64_DBL_=n.TWO_PWR_32_DBL_*n.TWO_PWR_32_DBL_,n.TWO_PWR_63_DBL_=n.TWO_PWR_64_DBL_/2,n.ZERO=n.fromInt(0),n.ONE=n.fromInt(1),n.NEG_ONE=n.fromInt(-1),n.MAX_VALUE=n.fromBits(-1,2147483647),n.MIN_VALUE=n.fromBits(0,-2147483648),n.TWO_PWR_24_=n.fromInt(1<<24),e.exports=n,e.exports.Timestamp=n},function(e,t,n){var r="inspect",o=n(32),i=parseInt(16777215*Math.random(),10),s=new RegExp("^[0-9a-fA-F]{24}$");try{if(Buffer&&Buffer.from){var a=!0;r=n(5).inspect.custom||"inspect"}}catch(e){a=!1}for(var c=function e(t){if(t instanceof e)return t;if(!(this instanceof e))return new e(t);if(this._bsontype="ObjectID",null==t||"number"==typeof t)return this.id=this.generate(t),void(e.cacheHexString&&(this.__id=this.toString("hex")));var n=e.isValid(t);if(!n&&null!=t)throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters");if(n&&"string"==typeof t&&24===t.length&&a)return new e(o.toBuffer(t,"hex"));if(n&&"string"==typeof t&&24===t.length)return e.createFromHexString(t);if(null==t||12!==t.length){if(null!=t&&"function"==typeof t.toHexString)return t;throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters")}this.id=t,e.cacheHexString&&(this.__id=this.toString("hex"))},u=[],l=0;l<256;l++)u[l]=(l<=15?"0":"")+l.toString(16);c.prototype.toHexString=function(){if(c.cacheHexString&&this.__id)return this.__id;var e="";if(!this.id||!this.id.length)throw new Error("invalid ObjectId, ObjectId.id must be either a string or a Buffer, but is ["+JSON.stringify(this.id)+"]");if(this.id instanceof p)return e=d(this.id),c.cacheHexString&&(this.__id=e),e;for(var t=0;t<this.id.length;t++)e+=u[this.id.charCodeAt(t)];return c.cacheHexString&&(this.__id=e),e},c.prototype.get_inc=function(){return c.index=(c.index+1)%16777215},c.prototype.getInc=function(){return this.get_inc()},c.prototype.generate=function(e){"number"!=typeof e&&(e=~~(Date.now()/1e3));var t=("undefined"==typeof process||1===process.pid?Math.floor(1e5*Math.random()):process.pid)%65535,n=this.get_inc(),r=o.allocBuffer(12);return r[3]=255&e,r[2]=e>>8&255,r[1]=e>>16&255,r[0]=e>>24&255,r[6]=255&i,r[5]=i>>8&255,r[4]=i>>16&255,r[8]=255&t,r[7]=t>>8&255,r[11]=255&n,r[10]=n>>8&255,r[9]=n>>16&255,r},c.prototype.toString=function(e){return this.id&&this.id.copy?this.id.toString("string"==typeof e?e:"hex"):this.toHexString()},c.prototype[r]=c.prototype.toString,c.prototype.toJSON=function(){return this.toHexString()},c.prototype.equals=function(e){return e instanceof c?this.toString()===e.toString():"string"==typeof e&&c.isValid(e)&&12===e.length&&this.id instanceof p?e===this.id.toString("binary"):"string"==typeof e&&c.isValid(e)&&24===e.length?e.toLowerCase()===this.toHexString():"string"==typeof e&&c.isValid(e)&&12===e.length?e===this.id:!(null==e||!(e instanceof c||e.toHexString))&&e.toHexString()===this.toHexString()},c.prototype.getTimestamp=function(){var e=new Date,t=this.id[3]|this.id[2]<<8|this.id[1]<<16|this.id[0]<<24;return e.setTime(1e3*Math.floor(t)),e},c.index=~~(16777215*Math.random()),c.createPk=function(){return new c},c.createFromTime=function(e){var t=o.toBuffer([0,0,0,0,0,0,0,0,0,0,0,0]);return t[3]=255&e,t[2]=e>>8&255,t[1]=e>>16&255,t[0]=e>>24&255,new c(t)};var f=[];for(l=0;l<10;)f[48+l]=l++;for(;l<16;)f[55+l]=f[87+l]=l++;var p=Buffer,d=function(e){return e.toString("hex")};c.createFromHexString=function(e){if(void 0===e||null!=e&&24!==e.length)throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters");if(a)return new c(o.toBuffer(e,"hex"));for(var t=new p(12),n=0,r=0;r<24;)t[n++]=f[e.charCodeAt(r++)]<<4|f[e.charCodeAt(r++)];return new c(t)},c.isValid=function(e){return null!=e&&("number"==typeof e||("string"==typeof e?12===e.length||24===e.length&&s.test(e):e instanceof c||(e instanceof p||"function"==typeof e.toHexString&&(e.id instanceof p||"string"==typeof e.id)&&(12===e.id.length||24===e.id.length&&s.test(e.id)))))},Object.defineProperty(c.prototype,"generationTime",{enumerable:!0,get:function(){return this.id[3]|this.id[2]<<8|this.id[1]<<16|this.id[0]<<24},set:function(e){this.id[3]=255&e,this.id[2]=e>>8&255,this.id[1]=e>>16&255,this.id[0]=e>>24&255}}),e.exports=c,e.exports.ObjectID=c,e.exports.ObjectId=c},function(e,t){function n(e,t){if(!(this instanceof n))return new n;this._bsontype="BSONRegExp",this.pattern=e||"",this.options=t||"";for(var r=0;r<this.options.length;r++)if("i"!==this.options[r]&&"m"!==this.options[r]&&"x"!==this.options[r]&&"l"!==this.options[r]&&"s"!==this.options[r]&&"u"!==this.options[r])throw new Error("the regular expression options ["+this.options[r]+"] is not supported")}e.exports=n,e.exports.BSONRegExp=n},function(e,t,n){var r=Buffer&&n(5).inspect.custom||"inspect";function o(e){if(!(this instanceof o))return new o(e);this._bsontype="Symbol",this.value=e}o.prototype.valueOf=function(){return this.value},o.prototype.toString=function(){return this.value},o.prototype[r]=function(){return this.value},o.prototype.toJSON=function(){return this.value},e.exports=o,e.exports.Symbol=o},function(e,t){var n=function e(t,n){if(!(this instanceof e))return new e(t,n);this._bsontype="Code",this.code=t,this.scope=n};n.prototype.toJSON=function(){return{scope:this.scope,code:this.code}},e.exports=n,e.exports.Code=n},function(e,t,n){"use strict";var r=n(43),o=/^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/,i=/^(\+|-)?(Infinity|inf)$/i,s=/^(\+|-)?NaN$/i,a=6176,c=[124,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse(),u=[248,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse(),l=[120,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse(),f=/^([-+])?(\d+)?$/,p=n(32),d=function(e){return!isNaN(parseInt(e,10))},h=function(e){var t=r.fromNumber(1e9),n=r.fromNumber(0),o=0;if(!(e.parts[0]||e.parts[1]||e.parts[2]||e.parts[3]))return{quotient:e,rem:n};for(o=0;o<=3;o++)n=(n=n.shiftLeft(32)).add(new r(e.parts[o],0)),e.parts[o]=n.div(t).low_,n=n.modulo(t);return{quotient:e,rem:n}},m=function(e){this._bsontype="Decimal128",this.bytes=e};m.fromString=function(e){var t,n=!1,h=!1,g=!1,y=0,b=0,v=0,S=0,w=0,_=[0],O=0,T=0,C=0,x=0,E=0,N=0,I=[0,0],A=[0,0],k=0;if((e=e.trim()).length>=7e3)throw new Error(e+" not a valid Decimal128 string");var M=e.match(o),R=e.match(i),j=e.match(s);if(!M&&!R&&!j||0===e.length)throw new Error(e+" not a valid Decimal128 string");if(M&&M[4]&&void 0===M[2])throw new Error(e+" not a valid Decimal128 string");if("+"!==e[k]&&"-"!==e[k]||(n="-"===e[k++]),!d(e[k])&&"."!==e[k]){if("i"===e[k]||"I"===e[k])return new m(p.toBuffer(n?u:l));if("N"===e[k])return new m(p.toBuffer(c))}for(;d(e[k])||"."===e[k];)if("."!==e[k])O<34&&("0"!==e[k]||g)&&(g||(w=b),g=!0,_[T++]=parseInt(e[k],10),O+=1),g&&(v+=1),h&&(S+=1),b+=1,k+=1;else{if(h)return new m(p.toBuffer(c));h=!0,k+=1}if(h&&!b)throw new Error(e+" not a valid Decimal128 string");if("e"===e[k]||"E"===e[k]){var D=e.substr(++k).match(f);if(!D||!D[2])return new m(p.toBuffer(c));E=parseInt(D[0],10),k+=D[0].length}if(e[k])return new m(p.toBuffer(c));if(C=0,O){if(x=O-1,y=v,0!==E&&1!==y)for(;"0"===e[w+y-1];)y-=1}else C=0,x=0,_[0]=0,v=1,O=1,y=0;for(E<=S&&S-E>16384?E=-6176:E-=S;E>6111;){if((x+=1)-C>34){var P=_.join("");if(P.match(/^0+$/)){E=6111;break}return new m(p.toBuffer(n?u:l))}E-=1}for(;E<-6176||O<v;){if(0===x){E=-6176,y=0;break}if(O<v?v-=1:x-=1,!(E<6111)){if((P=_.join("")).match(/^0+$/)){E=6111;break}return new m(p.toBuffer(n?u:l))}E+=1}if(x-C+1<y&&"0"!==e[y]){var B=b;h&&-6176===E&&(w+=1,B+=1);var L=parseInt(e[w+x+1],10),q=0;if(L>=5&&(q=1,5===L))for(q=_[x]%2==1,N=w+x+2;N<B;N++)if(parseInt(e[N],10)){q=1;break}if(q)for(var U=x;U>=0&&++_[U]>9;U--)if(_[U]=0,0===U){if(!(E<6111))return new m(p.toBuffer(n?u:l));E+=1,_[U]=1}}if(I=r.fromNumber(0),A=r.fromNumber(0),0===y)I=r.fromNumber(0),A=r.fromNumber(0);else if(x-C<17)for(U=C,A=r.fromNumber(_[U++]),I=new r(0,0);U<=x;U++)A=(A=A.multiply(r.fromNumber(10))).add(r.fromNumber(_[U]));else{for(U=C,I=r.fromNumber(_[U++]);U<=x-17;U++)I=(I=I.multiply(r.fromNumber(10))).add(r.fromNumber(_[U]));for(A=r.fromNumber(_[U++]);U<=x;U++)A=(A=A.multiply(r.fromNumber(10))).add(r.fromNumber(_[U]))}var z,$,W,F,V=function(e,t){if(!e&&!t)return{high:r.fromNumber(0),low:r.fromNumber(0)};var n=e.shiftRightUnsigned(32),o=new r(e.getLowBits(),0),i=t.shiftRightUnsigned(32),s=new r(t.getLowBits(),0),a=n.multiply(i),c=n.multiply(s),u=o.multiply(i),l=o.multiply(s);return a=a.add(c.shiftRightUnsigned(32)),c=new r(c.getLowBits(),0).add(u).add(l.shiftRightUnsigned(32)),{high:a=a.add(c.shiftRightUnsigned(32)),low:l=c.shiftLeft(32).add(new r(l.getLowBits(),0))}}(I,r.fromString("100000000000000000"));V.low=V.low.add(A),z=V.low,$=A,W=z.high_>>>0,F=$.high_>>>0,(W<F||W===F&&z.low_>>>0<$.low_>>>0)&&(V.high=V.high.add(r.fromNumber(1))),t=E+a;var K={low:r.fromNumber(0),high:r.fromNumber(0)};V.high.shiftRightUnsigned(49).and(r.fromNumber(1)).equals(r.fromNumber)?(K.high=K.high.or(r.fromNumber(3).shiftLeft(61)),K.high=K.high.or(r.fromNumber(t).and(r.fromNumber(16383).shiftLeft(47))),K.high=K.high.or(V.high.and(r.fromNumber(0x7fffffffffff)))):(K.high=K.high.or(r.fromNumber(16383&t).shiftLeft(49)),K.high=K.high.or(V.high.and(r.fromNumber(562949953421311)))),K.low=V.low,n&&(K.high=K.high.or(r.fromString("9223372036854775808")));var H=p.allocBuffer(16);return k=0,H[k++]=255&K.low.low_,H[k++]=K.low.low_>>8&255,H[k++]=K.low.low_>>16&255,H[k++]=K.low.low_>>24&255,H[k++]=255&K.low.high_,H[k++]=K.low.high_>>8&255,H[k++]=K.low.high_>>16&255,H[k++]=K.low.high_>>24&255,H[k++]=255&K.high.low_,H[k++]=K.high.low_>>8&255,H[k++]=K.high.low_>>16&255,H[k++]=K.high.low_>>24&255,H[k++]=255&K.high.high_,H[k++]=K.high.high_>>8&255,H[k++]=K.high.high_>>16&255,H[k++]=K.high.high_>>24&255,new m(H)};a=6176,m.prototype.toString=function(){for(var e,t,n,o,i,s,c=0,u=new Array(36),l=0;l<u.length;l++)u[l]=0;var f,p,d,m,g,y=0,b=!1,v={parts:new Array(4)},S=[];y=0;var w=this.bytes;if(o=w[y++]|w[y++]<<8|w[y++]<<16|w[y++]<<24,n=w[y++]|w[y++]<<8|w[y++]<<16|w[y++]<<24,t=w[y++]|w[y++]<<8|w[y++]<<16|w[y++]<<24,e=w[y++]|w[y++]<<8|w[y++]<<16|w[y++]<<24,y=0,{low:new r(o,n),high:new r(t,e)}.high.lessThan(r.ZERO)&&S.push("-"),(i=e>>26&31)>>3==3){if(30===i)return S.join("")+"Infinity";if(31===i)return"NaN";s=e>>15&16383,d=8+(e>>14&1)}else d=e>>14&7,s=e>>17&16383;if(f=s-a,v.parts[0]=(16383&e)+((15&d)<<14),v.parts[1]=t,v.parts[2]=n,v.parts[3]=o,0===v.parts[0]&&0===v.parts[1]&&0===v.parts[2]&&0===v.parts[3])b=!0;else for(g=3;g>=0;g--){var _=0,O=h(v);if(v=O.quotient,_=O.rem.low_)for(m=8;m>=0;m--)u[9*g+m]=_%10,_=Math.floor(_/10)}if(b)c=1,u[y]=0;else for(c=36,l=0;!u[y];)l++,c-=1,y+=1;if((p=c-1+f)>=34||p<=-7||f>0){for(S.push(u[y++]),(c-=1)&&S.push("."),l=0;l<c;l++)S.push(u[y++]);S.push("E"),p>0?S.push("+"+p):S.push(p)}else if(f>=0)for(l=0;l<c;l++)S.push(u[y++]);else{var T=c+f;if(T>0)for(l=0;l<T;l++)S.push(u[y++]);else S.push("0");for(S.push(".");T++<0;)S.push("0");for(l=0;l<c-Math.max(T-1,0);l++)S.push(u[y++])}return S.join("")},m.prototype.toJSON=function(){return{$numberDecimal:this.toString()}},e.exports=m,e.exports.Decimal128=m},function(e,t){function n(){if(!(this instanceof n))return new n;this._bsontype="MinKey"}e.exports=n,e.exports.MinKey=n},function(e,t){function n(){if(!(this instanceof n))return new n;this._bsontype="MaxKey"}e.exports=n,e.exports.MaxKey=n},function(e,t){function n(e,t,r){if(!(this instanceof n))return new n(e,t,r);this._bsontype="DBRef",this.namespace=e,this.oid=t,this.db=r}n.prototype.toJSON=function(){return{$ref:this.namespace,$id:this.oid,$db:null==this.db?"":this.db}},e.exports=n,e.exports.DBRef=n},function(e,t){e.exports=require("dns")},function(e,t,n){"use strict";const r=n(20),o=n(22).Buffer,i=n(9).retrieveBSON,s=n(3).MongoError,a=n(33).AuthProvider,c=n(0).emitWarning,u=i().Binary;let l;try{l=n(416)}catch(e){}class f extends a{constructor(e,t){super(e),this.cryptoMethod=t||"sha1"}prepare(e,t,n){const o=this.cryptoMethod;"sha256"===o&&null==l&&c("Warning: no saslprep library specified. Passwords will not be sanitized"),r.randomBytes(24,(r,i)=>{if(r)return n(r);Object.assign(t,{nonce:i});const s=t.credentials,a=Object.assign({},e,{speculativeAuthenticate:Object.assign(h(o,s,i),{db:s.source})});n(void 0,a)})}auth(e,t){const n=e.response;n&&n.speculativeAuthenticate?m(this.cryptoMethod,n.speculativeAuthenticate,e,t):function(e,t,n){const r=t.connection,o=t.credentials,i=t.nonce,s=o.source,a=h(e,o,i);r.command(`${s}.$cmd`,a,(r,o)=>{const i=w(r,o);if(i)return n(i);m(e,o.result,t,n)})}(this.cryptoMethod,e,t)}}function p(e){return e.replace("=","=3D").replace(",","=2C")}function d(e,t){return o.concat([o.from("n=","utf8"),o.from(e,"utf8"),o.from(",r=","utf8"),o.from(t.toString("base64"),"utf8")])}function h(e,t,n){const r=p(t.username);return{saslStart:1,mechanism:"sha1"===e?"SCRAM-SHA-1":"SCRAM-SHA-256",payload:new u(o.concat([o.from("n,,","utf8"),d(r,n)])),autoAuthorize:1,options:{skipEmptyExchange:!0}}}function m(e,t,n,i){const a=n.connection,c=n.credentials,f=n.nonce,h=c.source,m=p(c.username),_=c.password;let O;if("sha256"===e)O=l?l(_):_;else try{O=function(e,t){if("string"!=typeof e)throw new s("username must be a string");if("string"!=typeof t)throw new s("password must be a string");if(0===t.length)throw new s("password cannot be empty");const n=r.createHash("md5");return n.update(`${e}:mongo:${t}`,"utf8"),n.digest("hex")}(m,_)}catch(e){return i(e)}const T=o.isBuffer(t.payload)?new u(t.payload):t.payload,C=g(T.value()),x=parseInt(C.i,10);if(x&&x<4096)return void i(new s(`Server returned an invalid iteration count ${x}`),!1);const E=C.s,N=C.r;if(N.startsWith("nonce"))return void i(new s(`Server returned an invalid nonce: ${N}`),!1);const I=`c=biws,r=${N}`,A=function(e,t,n,o){const i=[e,t.toString("base64"),n].join("_");if(void 0!==b[i])return b[i];const s=r.pbkdf2Sync(e,t,n,S[o],o);v>=200&&(b={},v=0);return b[i]=s,v+=1,s}(O,o.from(E,"base64"),x,e),k=y(e,A,"Client Key"),M=y(e,A,"Server Key"),R=(j=e,D=k,r.createHash(j).update(D).digest());var j,D;const P=[d(m,f),T.value().toString("base64"),I].join(","),B=[I,`p=${function(e,t){o.isBuffer(e)||(e=o.from(e));o.isBuffer(t)||(t=o.from(t));const n=Math.max(e.length,t.length),r=[];for(let o=0;o<n;o+=1)r.push(e[o]^t[o]);return o.from(r).toString("base64")}(k,y(e,R,P))}`].join(","),L=y(e,M,P),q={saslContinue:1,conversationId:t.conversationId,payload:new u(o.from(B))};a.command(`${h}.$cmd`,q,(e,t)=>{const n=w(e,t);if(n)return i(n);const c=t.result,u=g(c.payload.value());if(!function(e,t){if(e.length!==t.length)return!1;if("function"==typeof r.timingSafeEqual)return r.timingSafeEqual(e,t);let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return 0===n}(o.from(u.v,"base64"),L))return void i(new s("Server returned an invalid signature"));if(!c||!1!==c.done)return i(n,c);const l={saslContinue:1,conversationId:c.conversationId,payload:o.alloc(0)};a.command(`${h}.$cmd`,l,i)})}function g(e){const t={},n=e.split(",");for(let e=0;e<n.length;e++){const r=n[e].split("=");t[r[0]]=r[1]}return t}function y(e,t,n){return r.createHmac(e,t).update(n).digest()}let b={},v=0;const S={sha256:32,sha1:20};function w(e,t){if(e)return e;const n=t.result;return n.$err||n.errmsg?new s(n):void 0}e.exports={ScramSHA1:class extends f{constructor(e){super(e,"sha1")}},ScramSHA256:class extends f{constructor(e){super(e,"sha256")}}}},function(e,t){e.exports=require("fs")},function(e,t){e.exports=require("url")},function(e,t,n){"use strict";const r=n(3).MongoError,o={queryPlanner:"queryPlanner",queryPlannerExtended:"queryPlannerExtended",executionStats:"executionStats",allPlansExecution:"allPlansExecution"};class i{constructor(e){this.verbosity="boolean"==typeof e?e?"allPlansExecution":"queryPlanner":e}static fromOptions(e){if(null==e||void 0===e.explain)return;const t=e.explain;if("boolean"==typeof t||t in o)return new i(e.explain);throw new r(`explain must be one of ${Object.keys(o)} or a boolean`)}}e.exports={Explain:i}},function(e,t,n){"use strict";"undefined"==typeof process||!process.version||0===process.version.indexOf("v0.")||0===process.version.indexOf("v1.")&&0!==process.version.indexOf("v1.8.")?e.exports={nextTick:function(e,t,n,r){if("function"!=typeof e)throw new TypeError('"callback" argument must be a function');var o,i,s=arguments.length;switch(s){case 0:case 1:return process.nextTick(e);case 2:return process.nextTick((function(){e.call(null,t)}));case 3:return process.nextTick((function(){e.call(null,t,n)}));case 4:return process.nextTick((function(){e.call(null,t,n,r)}));default:for(o=new Array(s-1),i=0;i<o.length;)o[i++]=arguments[i];return process.nextTick((function(){e.apply(null,o)}))}}}:e.exports=process},function(e,t,n){var r=n(131),o=r.Buffer;function i(e,t){for(var n in e)t[n]=e[n]}function s(e,t,n){return o(e,t,n)}o.from&&o.alloc&&o.allocUnsafe&&o.allocUnsafeSlow?e.exports=r:(i(r,t),t.Buffer=s),i(o,s),s.from=function(e,t,n){if("number"==typeof e)throw new TypeError("Argument must not be a number");return o(e,t,n)},s.alloc=function(e,t,n){if("number"!=typeof e)throw new TypeError("Argument must be a number");var r=o(e);return void 0!==t?"string"==typeof n?r.fill(t,n):r.fill(t):r.fill(0),r},s.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return o(e)},s.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return r.SlowBuffer(e)}},function(e,t,n){"use strict";class r{constructor(e){this.time=new Date,this.address=e.address}}e.exports={CMAP_EVENT_NAMES:["connectionPoolCreated","connectionPoolClosed","connectionCreated","connectionReady","connectionClosed","connectionCheckOutStarted","connectionCheckOutFailed","connectionCheckedOut","connectionCheckedIn","connectionPoolCleared"],ConnectionPoolCreatedEvent:class extends r{constructor(e){super(e),this.options=e.options}},ConnectionPoolClosedEvent:class extends r{constructor(e){super(e)}},ConnectionCreatedEvent:class extends r{constructor(e,t){super(e),this.connectionId=t.id}},ConnectionReadyEvent:class extends r{constructor(e,t){super(e),this.connectionId=t.id}},ConnectionClosedEvent:class extends r{constructor(e,t,n){super(e),this.connectionId=t.id,this.reason=n||"unknown"}},ConnectionCheckOutStartedEvent:class extends r{constructor(e){super(e)}},ConnectionCheckOutFailedEvent:class extends r{constructor(e,t){super(e),this.reason=t}},ConnectionCheckedOutEvent:class extends r{constructor(e,t){super(e),this.connectionId=t.id}},ConnectionCheckedInEvent:class extends r{constructor(e,t){super(e),this.connectionId=t.id}},ConnectionPoolClearedEvent:class extends r{constructor(e){super(e)}}}},function(e,t,n){"use strict";const r=n(2).MongoNetworkError,o=new Set([6,7,89,91,189,262,9001,10107,11600,11602,13435,13436,63,150,13388,234,133,43]);e.exports={GET_MORE_RESUMABLE_CODES:o,isResumableError:function(e,t){return e instanceof r||(t>=9?43===e.code||e.hasErrorLabel("ResumableChangeStreamError"):o.has(e.code))}}},function(e,t,n){"use strict";const r=n(27),o=n(2).MongoError,i=n(4).maxWireVersion,s=n(2).ReadPreference,a=n(1).Aspect,c=n(1).defineAspects;class u extends r{constructor(e,t,n){if(super(e,n,{fullResponse:!0}),this.target=e.s.namespace&&e.s.namespace.collection?e.s.namespace.collection:1,this.pipeline=t,this.hasWriteStage=!1,"string"==typeof n.out)this.pipeline=this.pipeline.concat({$out:n.out}),this.hasWriteStage=!0;else if(t.length>0){const e=t[t.length-1];(e.$out||e.$merge)&&(this.hasWriteStage=!0)}if(this.hasWriteStage&&(this.readPreference=s.primary),this.explain&&this.writeConcern)throw new o('"explain" cannot be used on an aggregate call with writeConcern');if(null!=n.cursor&&"object"!=typeof n.cursor)throw new o("cursor options must be an object")}get canRetryRead(){return!this.hasWriteStage}addToPipeline(e){this.pipeline.push(e)}execute(e,t){const n=this.options,r=i(e),o={aggregate:this.target,pipeline:this.pipeline};this.hasWriteStage&&r<8&&(this.readConcern=null),r>=5&&this.hasWriteStage&&this.writeConcern&&Object.assign(o,{writeConcern:this.writeConcern}),!0===n.bypassDocumentValidation&&(o.bypassDocumentValidation=n.bypassDocumentValidation),"boolean"==typeof n.allowDiskUse&&(o.allowDiskUse=n.allowDiskUse),n.hint&&(o.hint=n.hint),this.explain&&(n.full=!1),o.cursor=n.cursor||{},n.batchSize&&!this.hasWriteStage&&(o.cursor.batchSize=n.batchSize),super.executeCommand(e,o,t)}}c(u,[a.READ_OPERATION,a.RETRYABLE,a.EXECUTE_WITH_SELECTION,a.EXPLAINABLE]),e.exports=u},function(e,t,n){"use strict";const r=n(1).OperationBase,o=n(0).applyRetryableWrites,i=n(0).applyWriteConcern,s=n(0).decorateWithCollation,a=n(11).executeCommand,c=n(0).formattedOrderClause,u=n(0).handleCallback,l=n(2).ReadPreference,f=n(4).maxWireVersion,p=n(94).MongoError,d=n(1).Aspect,h=n(1).defineAspects,m=n(0).decorateWithExplain;class g extends r{constructor(e,t,n,r,o){super(o),this.collection=e,this.query=t,this.sort=n,this.doc=r}execute(e){const t=this.collection,n=this.query,r=c(this.sort),d=this.doc;let h=this.options,g={findAndModify:t.collectionName,query:n};r&&(g.sort=r),g.new=!!h.new,g.remove=!!h.remove,g.upsert=!!h.upsert;const y=h.projection||h.fields;y&&(g.fields=y),h.arrayFilters&&(g.arrayFilters=h.arrayFilters),d&&!h.remove&&(g.update=d),h.maxTimeMS&&(g.maxTimeMS=h.maxTimeMS),h.serializeFunctions=h.serializeFunctions||t.s.serializeFunctions,h.checkKeys=!1,h=o(h,t.s.db),h=i(h,{db:t.s.db,collection:t},h),h.writeConcern&&(g.writeConcern=h.writeConcern),!0===h.bypassDocumentValidation&&(g.bypassDocumentValidation=h.bypassDocumentValidation),h.readPreference=l.primary;try{s(g,t,h)}catch(t){return e(t,null)}if(h.hint){if(h.writeConcern&&0===h.writeConcern.w||f(t.s.topology)<8)return void e(new p("The current topology does not support a hint on findAndModify commands"));g.hint=h.hint}if(this.explain){if(f(t.s.topology)<4)return void e(new p("server does not support explain on findAndModify"));g=m(g,this.explain)}a(t.s.db,g,h,(t,n)=>t?u(e,t,null):u(e,null,n))}}h(g,[d.EXPLAINABLE]),e.exports=g},function(e,t,n){"use strict";const r=n(8).EventEmitter,o=n(5).inherits,i=n(0).getSingleProperty,s=n(143),a=n(0).handleCallback,c=n(0).filterOptions,u=n(0).toError,l=n(2).ReadPreference,f=n(2).MongoError,p=n(2).ObjectID,d=n(2).Logger,h=n(61),m=n(0).conditionallyMergeWriteConcern,g=n(0).executeLegacyOperation,y=n(139),b=n(5).deprecate,v=n(0).deprecateOptions,S=n(0).MongoDBNamespace,w=n(140),_=n(29),O=n(46),T=n(142),C=n(11).createListener,x=n(11).ensureIndex,E=n(11).evaluate,N=n(11).profilingInfo,I=n(11).validateDatabaseName,A=n(95),k=n(214),M=n(471),R=n(23),j=n(472),D=n(473),P=n(210),B=n(144).DropCollectionOperation,L=n(144).DropDatabaseOperation,q=n(215),U=n(212),z=n(474),$=n(475),W=n(216),F=n(217),V=n(476),K=n(56),H=["w","wtimeout","fsync","j","writeConcern","readPreference","readPreferenceTags","native_parser","forceServerObjectId","pkFactory","serializeFunctions","raw","bufferMaxEntries","authSource","ignoreUndefined","promoteLongs","promiseLibrary","readConcern","retryMiliSeconds","numberOfRetries","parentDb","noListener","loggerLevel","logger","promoteBuffers","promoteLongs","promoteValues","compression","retryWrites"];function Y(e,t,n){if(n=n||{},!(this instanceof Y))return new Y(e,t,n);r.call(this);const o=n.promiseLibrary||Promise;(n=c(n,H)).promiseLibrary=o,this.s={dbCache:{},children:[],topology:t,options:n,logger:d("Db",n),bson:t?t.bson:null,readPreference:l.fromOptions(n),bufferMaxEntries:"number"==typeof n.bufferMaxEntries?n.bufferMaxEntries:-1,parentDb:n.parentDb||null,pkFactory:n.pkFactory||p,nativeParser:n.nativeParser||n.native_parser,promiseLibrary:o,noListener:"boolean"==typeof n.noListener&&n.noListener,readConcern:O.fromOptions(n),writeConcern:_.fromOptions(n),namespace:new S(e)},I(e),i(this,"serverConfig",this.s.topology),i(this,"bufferMaxEntries",this.s.bufferMaxEntries),i(this,"databaseName",this.s.namespace.db),n.parentDb||this.s.noListener||(t.on("error",C(this,"error",this)),t.on("timeout",C(this,"timeout",this)),t.on("close",C(this,"close",this)),t.on("parseError",C(this,"parseError",this)),t.once("open",C(this,"open",this)),t.once("fullsetup",C(this,"fullsetup",this)),t.once("all",C(this,"all",this)),t.on("reconnect",C(this,"reconnect",this)))}o(Y,r),Y.prototype.on=b((function(){return Y.super_.prototype.on.apply(this,arguments)}),"Listening to events on the Db class has been deprecated and will be removed in the next major version."),Y.prototype.once=b((function(){return Y.super_.prototype.once.apply(this,arguments)}),"Listening to events on the Db class has been deprecated and will be removed in the next major version."),Object.defineProperty(Y.prototype,"topology",{enumerable:!0,get:function(){return this.s.topology}}),Object.defineProperty(Y.prototype,"options",{enumerable:!0,get:function(){return this.s.options}}),Object.defineProperty(Y.prototype,"slaveOk",{enumerable:!0,get:function(){return null!=this.s.options.readPreference&&("primary"!==this.s.options.readPreference||"primary"!==this.s.options.readPreference.mode)}}),Object.defineProperty(Y.prototype,"readConcern",{enumerable:!0,get:function(){return this.s.readConcern}}),Object.defineProperty(Y.prototype,"readPreference",{enumerable:!0,get:function(){return null==this.s.readPreference?l.primary:this.s.readPreference}}),Object.defineProperty(Y.prototype,"writeConcern",{enumerable:!0,get:function(){return this.s.writeConcern}}),Object.defineProperty(Y.prototype,"namespace",{enumerable:!0,get:function(){return this.s.namespace.toString()}}),Y.prototype.command=function(e,t,n){"function"==typeof t&&(n=t,t={}),t=Object.assign({},t);const r=new j(this,e,t);return K(this.s.topology,r,n)},Y.prototype.aggregate=function(e,t,n){"function"==typeof t&&(n=t,t={}),null==t&&null==n&&(t={});const r=new T(this.s.topology,new A(this,e,t),t);if("function"!=typeof n)return r;n(null,r)},Y.prototype.admin=function(){return new(n(218))(this,this.s.topology,this.s.promiseLibrary)};const G=["pkFactory","readPreference","serializeFunctions","strict","readConcern","ignoreUndefined","promoteValues","promoteBuffers","promoteLongs"];Y.prototype.collection=function(e,t,n){"function"==typeof t&&(n=t,t={}),t=t||{},(t=Object.assign({},t)).promiseLibrary=this.s.promiseLibrary,t.readConcern=t.readConcern?new O(t.readConcern.level):this.readConcern,this.s.options.ignoreUndefined&&(t.ignoreUndefined=this.s.options.ignoreUndefined);for(const e of G)e in t||void 0===this.s.options[e]||(t[e]=this.s.options[e]);if(null==(t=m(t,this.s.options))||!t.strict)try{const r=new h(this,this.s.topology,this.databaseName,e,this.s.pkFactory,t);return n&&n(null,r),r}catch(e){if(e instanceof f&&n)return n(e);throw e}if("function"!=typeof n)throw u(`A callback is required in strict mode. While getting collection ${e}`);if(this.serverConfig&&this.serverConfig.isDestroyed())return n(new f("topology was destroyed"));const r=Object.assign({},t,{nameOnly:!0});this.listCollections({name:e},r).toArray((r,o)=>{if(null!=r)return a(n,r,null);if(0===o.length)return a(n,u(`Collection ${e} does not exist. Currently in strict mode.`),null);try{return a(n,null,new h(this,this.s.topology,this.databaseName,e,this.s.pkFactory,t))}catch(r){return a(n,r,null)}})},Y.prototype.createCollection=v({name:"Db.createCollection",deprecatedOptions:["autoIndexId","strict","w","wtimeout","j"],optionsIndex:1},(function(e,t,n){"function"==typeof t&&(n=t,t={}),(t=t||{}).promiseLibrary=t.promiseLibrary||this.s.promiseLibrary,t.readConcern=t.readConcern?new O(t.readConcern.level):this.readConcern;const r=new D(this,e,t);return K(this.s.topology,r,n)})),Y.prototype.stats=function(e,t){"function"==typeof e&&(t=e,e={});const n={dbStats:!0};null!=(e=e||{}).scale&&(n.scale=e.scale),null==e.readPreference&&this.s.readPreference&&(e.readPreference=this.s.readPreference);const r=new R(this,e,null,n);return K(this.s.topology,r,t)},Y.prototype.listCollections=function(e,t){return e=e||{},t=t||{},new s(this.s.topology,new z(this,e,t),t)},Y.prototype.eval=b((function(e,t,n,r){const o=Array.prototype.slice.call(arguments,1);return r="function"==typeof o[o.length-1]?o.pop():void 0,t=o.length?o.shift():t,n=o.length&&o.shift()||{},g(this.s.topology,E,[this,e,t,n,r])}),"Db.eval is deprecated as of MongoDB version 3.2"),Y.prototype.renameCollection=function(e,t,n,r){"function"==typeof n&&(r=n,n={}),(n=Object.assign({},n,{readPreference:l.PRIMARY})).new_collection=!0;const o=new F(this.collection(e),t,n);return K(this.s.topology,o,r)},Y.prototype.dropCollection=function(e,t,n){"function"==typeof t&&(n=t,t={});const r=new B(this,e,t=t||{});return K(this.s.topology,r,n)},Y.prototype.dropDatabase=function(e,t){"function"==typeof e&&(t=e,e={});const n=new L(this,e=e||{});return K(this.s.topology,n,t)},Y.prototype.collections=function(e,t){"function"==typeof e&&(t=e,e={});const n=new M(this,e=e||{});return K(this.s.topology,n,t)},Y.prototype.executeDbAdminCommand=function(e,t,n){"function"==typeof t&&(n=t,t={}),(t=t||{}).readPreference=l.resolve(this,t);const r=new q(this,e,t);return K(this.s.topology,r,n)},Y.prototype.createIndex=function(e,t,n,r){"function"==typeof n&&(r=n,n={}),n=n?Object.assign({},n):{};const o=new P(this,e,t,n);return K(this.s.topology,o,r)},Y.prototype.ensureIndex=b((function(e,t,n,r){return"function"==typeof n&&(r=n,n={}),n=n||{},g(this.s.topology,x,[this,e,t,n,r])}),"Db.ensureIndex is deprecated as of MongoDB version 3.0 / driver version 2.0"),Y.prototype.addChild=function(e){if(this.s.parentDb)return this.s.parentDb.addChild(e);this.s.children.push(e)},Y.prototype.addUser=function(e,t,n,r){"function"==typeof n&&(r=n,n={}),n=n||{},"string"==typeof e&&null!=t&&"object"==typeof t&&(n=t,t=null);const o=new k(this,e,t,n);return K(this.s.topology,o,r)},Y.prototype.removeUser=function(e,t,n){"function"==typeof t&&(n=t,t={});const r=new W(this,e,t=t||{});return K(this.s.topology,r,n)},Y.prototype.setProfilingLevel=function(e,t,n){"function"==typeof t&&(n=t,t={});const r=new V(this,e,t=t||{});return K(this.s.topology,r,n)},Y.prototype.profilingInfo=b((function(e,t){return"function"==typeof e&&(t=e,e={}),e=e||{},g(this.s.topology,N,[this,e,t])}),"Db.profilingInfo is deprecated. Query the system.profile collection directly."),Y.prototype.profilingLevel=function(e,t){"function"==typeof e&&(t=e,e={});const n=new $(this,e=e||{});return K(this.s.topology,n,t)},Y.prototype.indexInformation=function(e,t,n){"function"==typeof t&&(n=t,t={});const r=new U(this,e,t=t||{});return K(this.s.topology,r,n)},Y.prototype.unref=function(){this.s.topology.unref()},Y.prototype.watch=function(e,t){return e=e||[],t=t||{},Array.isArray(e)||(t=e,e=[]),new y(this,e,t)},Y.prototype.getLogger=function(){return this.s.logger},Y.SYSTEM_NAMESPACE_COLLECTION=w.SYSTEM_NAMESPACE_COLLECTION,Y.SYSTEM_INDEX_COLLECTION=w.SYSTEM_INDEX_COLLECTION,Y.SYSTEM_PROFILE_COLLECTION=w.SYSTEM_PROFILE_COLLECTION,Y.SYSTEM_USER_COLLECTION=w.SYSTEM_USER_COLLECTION,Y.SYSTEM_COMMAND_COLLECTION=w.SYSTEM_COMMAND_COLLECTION,Y.SYSTEM_JS_COLLECTION=w.SYSTEM_JS_COLLECTION,e.exports=Y},function(e,t,n){"use strict";const r=n(2).Server,o=n(26),i=n(35).TopologyBase,s=n(35).Store,a=n(2).MongoError,c=n(0).MAX_JS_INT,u=n(0).translateOptions,l=n(0).filterOptions,f=n(0).mergeOptions;var p=["ha","haInterval","acceptableLatencyMS","poolSize","ssl","checkServerIdentity","sslValidate","sslCA","sslCRL","sslCert","ciphers","ecdhCurve","sslKey","sslPass","socketOptions","bufferMaxEntries","store","auto_reconnect","autoReconnect","emitError","keepAlive","keepAliveInitialDelay","noDelay","connectTimeoutMS","socketTimeoutMS","family","loggerLevel","logger","reconnectTries","reconnectInterval","monitoring","appname","domainsEnabled","servername","promoteLongs","promoteValues","promoteBuffers","compression","promiseLibrary","monitorCommands"];class d extends i{constructor(e,t,n){super();const i=(n=l(n,p)).promiseLibrary;var d={force:!1,bufferMaxEntries:"number"==typeof n.bufferMaxEntries?n.bufferMaxEntries:c},h=n.store||new s(this,d);if(-1!==e.indexOf("/"))null!=t&&"object"==typeof t&&(n=t,t=null);else if(null==t)throw a.create({message:"port must be specified",driver:!0});var m="boolean"!=typeof n.auto_reconnect||n.auto_reconnect;m="boolean"==typeof n.autoReconnect?n.autoReconnect:m;var g=f({},{host:e,port:t,disconnectHandler:h,cursorFactory:o,reconnect:m,emitError:"boolean"!=typeof n.emitError||n.emitError,size:"number"==typeof n.poolSize?n.poolSize:5,monitorCommands:"boolean"==typeof n.monitorCommands&&n.monitorCommands});g=u(g,n);var y=n.socketOptions&&Object.keys(n.socketOptions).length>0?n.socketOptions:n;g=u(g,y),this.s={coreTopology:new r(g),sCapabilities:null,clonedOptions:g,reconnect:g.reconnect,emitError:g.emitError,poolSize:g.size,storeOptions:d,store:h,host:e,port:t,options:n,sessionPool:null,sessions:new Set,promiseLibrary:i||Promise}}connect(e,t){var n=this;"function"==typeof e&&(t=e,e={}),null==e&&(e=this.s.clonedOptions),"function"!=typeof t&&(t=null),e=Object.assign({},this.s.clonedOptions,e),n.s.options=e,n.s.storeOptions.bufferMaxEntries="number"==typeof e.bufferMaxEntries?e.bufferMaxEntries:-1;var r=function(){return function(e){["timeout","error","close"].forEach((function(e){n.s.coreTopology.removeListener(e,a[e])})),n.s.coreTopology.removeListener("connect",r);try{t(e)}catch(e){process.nextTick((function(){throw e}))}}},o=function(e){return function(t){"error"!==e&&n.emit(e,t)}},i=function(){n.s.store.flush()},s=function(e){return function(t,r){n.emit(e,t,r)}},a={timeout:r("timeout"),error:r("error"),close:r("close")};["timeout","error","close","serverOpening","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","serverClosed","topologyOpening","topologyClosed","topologyDescriptionChanged","commandStarted","commandSucceeded","commandFailed"].forEach((function(e){n.s.coreTopology.removeAllListeners(e)})),n.s.coreTopology.once("timeout",a.timeout),n.s.coreTopology.once("error",a.error),n.s.coreTopology.once("close",a.close),n.s.coreTopology.once("connect",(function(){["timeout","error","close","destroy"].forEach((function(e){n.s.coreTopology.removeAllListeners(e)})),n.s.coreTopology.on("timeout",o("timeout")),n.s.coreTopology.once("error",o("error")),n.s.coreTopology.on("close",o("close")),n.s.coreTopology.on("destroy",i),n.emit("open",null,n);try{t(null,n)}catch(e){process.nextTick((function(){throw e}))}})),n.s.coreTopology.on("reconnect",(function(){n.emit("reconnect",n),n.s.store.execute()})),n.s.coreTopology.on("reconnectFailed",(function(e){n.emit("reconnectFailed",e),n.s.store.flush(e)})),n.s.coreTopology.on("serverDescriptionChanged",s("serverDescriptionChanged")),n.s.coreTopology.on("serverHeartbeatStarted",s("serverHeartbeatStarted")),n.s.coreTopology.on("serverHeartbeatSucceeded",s("serverHeartbeatSucceeded")),n.s.coreTopology.on("serverHeartbeatFailed",s("serverHeartbeatFailed")),n.s.coreTopology.on("serverOpening",s("serverOpening")),n.s.coreTopology.on("serverClosed",s("serverClosed")),n.s.coreTopology.on("topologyOpening",s("topologyOpening")),n.s.coreTopology.on("topologyClosed",s("topologyClosed")),n.s.coreTopology.on("topologyDescriptionChanged",s("topologyDescriptionChanged")),n.s.coreTopology.on("commandStarted",s("commandStarted")),n.s.coreTopology.on("commandSucceeded",s("commandSucceeded")),n.s.coreTopology.on("commandFailed",s("commandFailed")),n.s.coreTopology.on("attemptReconnect",s("attemptReconnect")),n.s.coreTopology.on("monitoring",s("monitoring")),n.s.coreTopology.connect(e)}}Object.defineProperty(d.prototype,"poolSize",{enumerable:!0,get:function(){return this.s.coreTopology.connections().length}}),Object.defineProperty(d.prototype,"autoReconnect",{enumerable:!0,get:function(){return this.s.reconnect}}),Object.defineProperty(d.prototype,"host",{enumerable:!0,get:function(){return this.s.host}}),Object.defineProperty(d.prototype,"port",{enumerable:!0,get:function(){return this.s.port}}),e.exports=d},function(e,t,n){"use strict";class r extends Error{constructor(e){super(e),this.name="MongoCryptError",Error.captureStackTrace(this,this.constructor)}}e.exports={debug:function(e){process.env.MONGODB_CRYPT_DEBUG&&console.log(e)},databaseNamespace:function(e){return e.split(".")[0]},collectionNamespace:function(e){return e.split(".").slice(1).join(".")},MongoCryptError:r,promiseOrCallback:function(e,t){if("function"!=typeof e)return new Promise((e,n)=>{t((function(t,r){return null!=t?n(t):arguments.length>2?e(Array.prototype.slice.call(arguments,1)):void e(r)}))});t((function(t){if(null==t)e.apply(this,arguments);else try{e(t)}catch(e){return process.nextTick(()=>{throw e})}}))}}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.noSplitSplitterOptions=t.mongoSplitterOptions=t.sqliteSplitterOptions=t.postgreSplitterOptions=t.mssqlSplitterOptions=t.mysqlSplitterOptions=t.defaultSplitterOptions=void 0,t.defaultSplitterOptions={stringsBegins:["'"],stringsEnds:{"'":"'"},stringEscapes:{"'":"'"},allowSemicolon:!0,allowCustomDelimiter:!1,allowGoDelimiter:!1,allowDollarDollarString:!1,noSplit:!1,doubleDashComments:!0,multilineComments:!0,javaScriptComments:!1,returnRichInfo:!1},t.mysqlSplitterOptions=Object.assign(Object.assign({},t.defaultSplitterOptions),{allowCustomDelimiter:!0,stringsBegins:["'","`"],stringsEnds:{"'":"'","`":"`"},stringEscapes:{"'":"\\","`":"`"}}),t.mssqlSplitterOptions=Object.assign(Object.assign({},t.defaultSplitterOptions),{allowSemicolon:!1,allowGoDelimiter:!0,stringsBegins:["'","["],stringsEnds:{"'":"'","[":"]"},stringEscapes:{"'":"'"}}),t.postgreSplitterOptions=Object.assign(Object.assign({},t.defaultSplitterOptions),{allowDollarDollarString:!0,stringsBegins:["'",'"'],stringsEnds:{"'":"'",'"':'"'},stringEscapes:{"'":"'",'"':'"'}}),t.sqliteSplitterOptions=Object.assign(Object.assign({},t.defaultSplitterOptions),{stringsBegins:["'",'"'],stringsEnds:{"'":"'",'"':'"'},stringEscapes:{"'":"'",'"':'"'}}),t.mongoSplitterOptions=Object.assign(Object.assign({},t.defaultSplitterOptions),{stringsBegins:["'",'"'],stringsEnds:{"'":"'",'"':'"'},stringEscapes:{"'":"\\",'"':"\\"}}),t.noSplitSplitterOptions=Object.assign(Object.assign({},t.defaultSplitterOptions),{noSplit:!0})},function(e,t,n){var r=n(147);e.exports=function(e){return r(e,5)}},function(e,t,n){var r=n(63),o=n(242),i=n(243),s=n(244),a=n(245),c=n(246);function u(e){var t=this.__data__=new r(e);this.size=t.size}u.prototype.clear=o,u.prototype.delete=i,u.prototype.get=s,u.prototype.has=a,u.prototype.set=c,e.exports=u},function(e,t,n){var r=n(31)(n(19),"Map");e.exports=r},function(e,t,n){var r=n(253),o=n(260),i=n(262),s=n(263),a=n(264);function c(e){var t=-1,n=null==e?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}c.prototype.clear=r,c.prototype.delete=o,c.prototype.get=i,c.prototype.has=s,c.prototype.set=a,e.exports=c},function(e,t,n){var r=n(106),o=n(65),i=Object.prototype.hasOwnProperty;e.exports=function(e,t,n){var s=e[t];i.call(e,t)&&o(s,n)&&(void 0!==n||t in e)||r(e,t,n)}},function(e,t,n){var r=n(151);e.exports=function(e,t,n){"__proto__"==t&&r?r(e,t,{configurable:!0,enumerable:!0,value:n,writable:!0}):e[t]=n}},function(e,t,n){var r=n(268),o=n(15),i=Object.prototype,s=i.hasOwnProperty,a=i.propertyIsEnumerable,c=r(function(){return arguments}())?r:function(e){return o(e)&&s.call(e,"callee")&&!a.call(e,"callee")};e.exports=c},function(e,t,n){(function(e){var r=n(19),o=n(269),i=t&&!t.nodeType&&t,s=i&&"object"==typeof e&&e&&!e.nodeType&&e,a=s&&s.exports===i?r.Buffer:void 0,c=(a?a.isBuffer:void 0)||o;e.exports=c}).call(this,n(62)(e))},function(e,t){e.exports=function(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=9007199254740991}},function(e,t){var n=Object.prototype;e.exports=function(e){var t=e&&e.constructor;return e===("function"==typeof t&&t.prototype||n)}},function(e,t,n){var r=n(152),o=n(274),i=n(38);e.exports=function(e){return i(e)?r(e,!0):o(e)}},function(e,t,n){var r=n(279),o=n(155),i=Object.prototype.propertyIsEnumerable,s=Object.getOwnPropertySymbols,a=s?function(e){return null==e?[]:(e=Object(e),r(s(e),(function(t){return i.call(e,t)})))}:o;e.exports=a},function(e,t){e.exports=function(e,t){for(var n=-1,r=t.length,o=e.length;++n<r;)e[o+n]=t[n];return e}},function(e,t,n){var r=n(154)(Object.getPrototypeOf,Object);e.exports=r},function(e,t,n){var r=n(161);e.exports=function(e){var t=new e.constructor(e.byteLength);return new r(t).set(new r(e)),t}},function(e,t,n){var r=n(12),o=n(71),i=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,s=/^\w*$/;e.exports=function(e,t){if(r(e))return!1;var n=typeof e;return!("number"!=n&&"symbol"!=n&&"boolean"!=n&&null!=e&&!o(e))||(s.test(e)||!i.test(e)||null!=t&&e in Object(t))}},function(e,t,n){var r=n(104),o=n(321),i=n(322);function s(e){var t=-1,n=null==e?0:e.length;for(this.__data__=new r;++t<n;)this.add(e[t])}s.prototype.add=s.prototype.push=o,s.prototype.has=i,e.exports=s},function(e,t){e.exports=function(e,t){return e.has(t)}},function(e,t,n){"use strict";var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function s(e){try{c(r.next(e))}catch(e){i(e)}}function a(e){try{c(r.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((r=r.apply(e,t||[])).next())}))},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DatabaseAnalyser=void 0;const i=o(n(333)),s=o(n(359)),a=o(n(177)),c=o(n(52)),u=["tables","collections","views","matviews","functions","procedures","triggers"],l=e=>t=>(0,a.default)(t,e);class f{constructor(e,t,n){this.pool=e,this.driver=t,this.singleObjectId=null,this.dialect=(null==t?void 0:t.dialectByVersion)&&(null==t?void 0:t.dialectByVersion(n))||(null==t?void 0:t.dialect)}_runAnalysis(){return r(this,void 0,void 0,(function*(){return f.createEmptyStructure()}))}_getFastSnapshot(){return r(this,void 0,void 0,(function*(){return null}))}_computeSingleObjectId(){return r(this,void 0,void 0,(function*(){}))}addEngineField(e){var t;if(null===(t=this.driver)||void 0===t?void 0:t.engine){for(const t of u)if(e[t])for(const n of e[t])n.engine=this.driver.engine;return e.engine=this.driver.engine,e}}fullAnalysis(){return r(this,void 0,void 0,(function*(){return this.addEngineField(yield this._runAnalysis())}))}singleObjectAnalysis(e,t){var n,o;return r(this,void 0,void 0,(function*(){this.singleObjectFilter=Object.assign(Object.assign({},e),{typeField:t}),yield this._computeSingleObjectId();const r=this.addEngineField(yield this._runAnalysis());return 1==(null===(n=r[t])||void 0===n?void 0:n.length)?r[t][0]:null===(o=r[t])||void 0===o?void 0:o.find(t=>t.pureName==e.pureName&&t.schemaName==e.schemaName)}))}incrementalAnalysis(e){return r(this,void 0,void 0,(function*(){this.structure=e;const t=yield this.getModifications();if(null==t)return this.structure=null,this.addEngineField(yield this._runAnalysis());const n=t.filter(e=>"setTableRowCounts"!=e.action),r=t.find(e=>"setTableRowCounts"==e.action);let o=null;if(r){const t=(i=e,s=r.rowCounts,Object.assign(Object.assign({},i),{tables:(i.tables||[]).map(e=>{var t,n;return Object.assign(Object.assign({},e),{tableRowCount:null!==(n=null===(t=s.find(t=>t.objectId==e.objectId))||void 0===t?void 0:t.tableRowCount)&&void 0!==n?n:e.tableRowCount})})}));(function(e,t){for(const n of e.tables||[]){const e=(t.tables||[]).find(e=>e.objectId==n.objectId);if((null==n?void 0:n.tableRowCount)!==(null==e?void 0:e.tableRowCount))return!0}return!1})(e,t)&&(o=t)}var i,s;return 0==n.length?o?this.addEngineField(o):null:(this.modifications=n,o&&(this.structure=o),console.log("DB modifications detected:",this.modifications),this.addEngineField(this.mergeAnalyseResult(yield this._runAnalysis())))}))}mergeAnalyseResult(e){if(null==this.structure)return Object.assign(Object.assign({},f.createEmptyStructure()),e);const t={};for(const n of u){const r=this.modifications.filter(e=>"remove"==e.action&&e.objectTypeField==n).map(e=>e.objectId),o=e[n]||[],s=[...r,...o.map(e=>e.objectId)];t[n]=(0,i.default)([...(this.structure[n]||[]).filter(e=>!s.includes(e.objectId)),...o],e=>e.pureName);for(const e of t[n]){const t=(this.structure[n]||[]).find(t=>t.objectId==e.objectId);if(t)for(const n in t)e[n]||(e[n]=t[n])}}return t}getRequestedObjectPureNames(e,t){if(this.singleObjectFilter){const{typeField:t,pureName:n}=this.singleObjectFilter;if(t==e)return[n]}return this.modifications?this.modifications.filter(t=>t.objectTypeField==e).filter(e=>e.newName).map(e=>e.newName.pureName):t}createQuery(e,t){if(this.singleObjectFilter){const{typeField:n}=this.singleObjectFilter;return this.singleObjectId&&(t&&t.includes(n))?e.replace(/=OBJECT_ID_CONDITION/g,` = '${this.singleObjectId}'`):null}if(!this.modifications||!t||0==this.modifications.length)return e.replace(/=OBJECT_ID_CONDITION/g," is not null");if(this.modifications.some(e=>t.includes(e.objectTypeField)&&"all"==e.action))return e.replace(/=OBJECT_ID_CONDITION/g," is not null");const n=this.modifications.filter(e=>t.includes(e.objectTypeField)&&("add"==e.action||"change"==e.action)).map(e=>e.objectId);return 0==n.length?e.replace(/=OBJECT_ID_CONDITION/g," = '0'"):e.replace(/=OBJECT_ID_CONDITION/g,` in (${n.map(e=>`'${e}'`).join(",")})`)}getDeletedObjectsForField(e,t){const n=e[t];return n&&this.structure[t]?this.structure[t].filter(e=>!n.find(t=>e.objectId==t.objectId)).map(e=>({oldName:(0,a.default)(e,["schemaName","pureName"]),objectId:e.objectId,action:"remove",objectTypeField:t})):[]}getDeletedObjects(e){return[...this.getDeletedObjectsForField(e,"tables"),...this.getDeletedObjectsForField(e,"collections"),...this.getDeletedObjectsForField(e,"views"),...this.getDeletedObjectsForField(e,"matviews"),...this.getDeletedObjectsForField(e,"procedures"),...this.getDeletedObjectsForField(e,"functions"),...this.getDeletedObjectsForField(e,"triggers")]}getModifications(){return r(this,void 0,void 0,(function*(){const e=yield this._getFastSnapshot();if(!e)return null;const t=[];for(const n in e){const r=e[n];if(null!==r){if(void 0!==r)for(const e of r){const{objectId:r,schemaName:o,pureName:i,contentHash:s}=e,c=this.structure[n].find(e=>e.objectId==r);if(c&&s&&c.contentHash==s)continue;const u=c?{newName:{schemaName:o,pureName:i},oldName:(0,a.default)(c,["schemaName","pureName"]),action:"change",objectTypeField:n,objectId:r}:{newName:{schemaName:o,pureName:i},action:"add",objectTypeField:n,objectId:r};t.push(u)}}else t.push({objectTypeField:n,action:"all"})}const n=(e.tables||[]).filter(e=>null!=e.tableRowCount).map(e=>({objectId:e.objectId,tableRowCount:e.tableRowCount}));return n.length>0&&t.push({action:"setTableRowCounts",rowCounts:n}),[...(0,c.default)(t),...this.getDeletedObjects(e)]}))}safeQuery(e){return r(this,void 0,void 0,(function*(){try{return yield this.driver.query(this.pool,e)}catch(e){return console.log("Error running analyser query",e.message),{rows:[]}}}))}static createEmptyStructure(){return{tables:[],collections:[],views:[],matviews:[],functions:[],procedures:[],triggers:[],schemas:[]}}static byTableFilter(e){return t=>t.pureName==e.pureName&&t.schemaName==t.schemaName}static extractPrimaryKeys(e,t){const n=t.filter(f.byTableFilter(e));if(0!=n.length)return Object.assign(Object.assign({},(0,a.default)(n[0],["constraintName","schemaName","pureName"])),{constraintType:"primaryKey",columns:n.map(l("columnName"))})}static extractForeignKeys(e,t){const n=(0,s.default)(t.filter(f.byTableFilter(e)),"constraintName");return Object.keys(n).map(e=>Object.assign(Object.assign({constraintName:e,constraintType:"foreignKey"},(0,a.default)(n[e][0],["constraintName","schemaName","pureName","refSchemaName","refTableName","updateAction","deleteAction"])),{columns:n[e].map(l(["columnName","refColumnName"]))}))}}t.DatabaseAnalyser=f},function(e,t,n){var r=n(336),o=n(344),i=n(74),s=n(12),a=n(347);e.exports=function(e){return"function"==typeof e?e:null==e?i:"object"==typeof e?s(e)?o(e[0],e[1]):r(e):a(e)}},function(e,t,n){var r=n(338),o=n(15);e.exports=function e(t,n,i,s,a){return t===n||(null==t||null==n||!o(t)&&!o(n)?t!=t&&n!=n:r(t,n,i,s,e,a))}},function(e,t){e.exports=function(e){var t=-1,n=Array(e.size);return e.forEach((function(e){n[++t]=e})),n}},function(e,t,n){var r=n(171);e.exports=function(e){return(null==e?0:e.length)?r(e,1):[]}},function(e,t,n){var r=n(25),o=n(15);e.exports=function(e){return"number"==typeof e||o(e)&&"[object Number]"==r(e)}},function(e,t,n){var r,o,i=n(369),s=n(370),a=0,c=0;e.exports=function(e,t,n){var u=t&&n||0,l=t||[],f=(e=e||{}).node||r,p=void 0!==e.clockseq?e.clockseq:o;if(null==f||null==p){var d=i();null==f&&(f=r=[1|d[0],d[1],d[2],d[3],d[4],d[5]]),null==p&&(p=o=16383&(d[6]<<8|d[7]))}var h=void 0!==e.msecs?e.msecs:(new Date).getTime(),m=void 0!==e.nsecs?e.nsecs:c+1,g=h-a+(m-c)/1e4;if(g<0&&void 0===e.clockseq&&(p=p+1&16383),(g<0||h>a)&&void 0===e.nsecs&&(m=0),m>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");a=h,c=m,o=p;var y=(1e4*(268435455&(h+=122192928e5))+m)%4294967296;l[u++]=y>>>24&255,l[u++]=y>>>16&255,l[u++]=y>>>8&255,l[u++]=255&y;var b=h/4294967296*1e4&268435455;l[u++]=b>>>8&255,l[u++]=255&b,l[u++]=b>>>24&15|16,l[u++]=b>>>16&255,l[u++]=p>>>8|128,l[u++]=255&p;for(var v=0;v<6;++v)l[u+v]=f[v];return t||s(l)}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dumpSqlFromDefinition=t.dumpSqlRelation=t.dumpSqlSourceRef=t.dumpSqlSourceDef=void 0;const r=n(75),o=n(127);function i(e,t){let n=0;if(null!=t.name&&n++,null!=t.subQuery&&n++,null!=t.subQueryString&&n++,1!=n)throw new Error("sqltree.Source should have exactly one source");null!=t.name&&e.put("%f",t.name),t.subQuery&&(e.put("("),(0,r.dumpSqlSelect)(e,t.subQuery),e.put(")")),t.subQueryString&&(e.put("("),e.putRaw(t.subQueryString),e.put(")")),t.alias&&e.put(" %i",t.alias)}function s(e,t){e.put("&n %k ",t.joinType),i(e,t),t.conditions&&t.conditions.length>0&&(e.put(" ^on "),e.putCollection(" ^and ",t.conditions,t=>(0,o.dumpSqlCondition)(e,t)))}t.dumpSqlSourceDef=i,t.dumpSqlSourceRef=function(e,t){return t.alias?(e.put("%i",t.alias),!0):!!t.name&&(e.put("%f",t.name),!0)},t.dumpSqlRelation=s,t.dumpSqlFromDefinition=function(e,t){i(e,t),e.put(" "),t.relations&&t.relations.forEach(t=>s(e,t))}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dumpSqlCondition=void 0;const r=n(180),o=n(75);t.dumpSqlCondition=function e(t,n){switch(n.conditionType){case"binary":(0,r.dumpSqlExpression)(t,n.left),t.put(" %s ",n.operator),(0,r.dumpSqlExpression)(t,n.right);break;case"isNull":(0,r.dumpSqlExpression)(t,n.expr),t.put(" ^is ^null");break;case"isNotNull":(0,r.dumpSqlExpression)(t,n.expr),t.put(" ^is ^not ^null");break;case"isEmpty":t.put("^trim("),(0,r.dumpSqlExpression)(t,n.expr),t.put(") = ''");break;case"isNotEmpty":t.put("^trim("),(0,r.dumpSqlExpression)(t,n.expr),t.put(") <> ''");break;case"and":case"or":t.putCollection(` ^${n.conditionType} `,n.conditions,n=>{t.putRaw("("),e(t,n),t.putRaw(")")});break;case"like":(0,r.dumpSqlExpression)(t,n.left),t.put(t.dialect.ilike?" ^ilike ":" ^like "),(0,r.dumpSqlExpression)(t,n.right);break;case"notLike":(0,r.dumpSqlExpression)(t,n.left),t.put(" ^not ^like "),(0,r.dumpSqlExpression)(t,n.right);break;case"not":t.put("^not ("),e(t,n.condition),t.put(")");break;case"exists":t.put("^exists ("),(0,o.dumpSqlSelect)(t,n.subQuery),t.put(")");break;case"notExists":t.put("^not ^exists ("),(0,o.dumpSqlSelect)(t,n.subQuery),t.put(")");break;case"between":(0,r.dumpSqlExpression)(t,n.expr),t.put(" ^between "),(0,r.dumpSqlExpression)(t,n.left),t.put(" ^and "),(0,r.dumpSqlExpression)(t,n.right)}}},function(e,t,n){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.modelCompareDbDiffOptions=t.matchPairedObjects=t.getAlterDatabaseScript=t.getAlterTableScript=t.createAlterDatabasePlan=t.createAlterTablePlan=t.testEqualSqlObjects=t.testEqualTables=t.testEqualTypes=t.testEqualColumns=t.generateDbPairingId=t.generateTablePairingId=void 0;const o=r(n(125)),i=n(386),s=r(n(388)),a=r(n(184)),c=r(n(101)),u=r(n(396)),l=r(n(177));function f(e){var t,n,r,i,s;return e?e.pairingId?e:Object.assign(Object.assign({},e),{columns:null===(t=e.columns)||void 0===t?void 0:t.map(e=>Object.assign(Object.assign({},e),{pairingId:e.pairingId||(0,o.default)()})),foreignKeys:null===(n=e.foreignKeys)||void 0===n?void 0:n.map(e=>Object.assign(Object.assign({},e),{pairingId:e.pairingId||(0,o.default)()})),checks:null===(r=e.checks)||void 0===r?void 0:r.map(e=>Object.assign(Object.assign({},e),{pairingId:e.pairingId||(0,o.default)()})),indexes:null===(i=e.indexes)||void 0===i?void 0:i.map(e=>Object.assign(Object.assign({},e),{pairingId:e.pairingId||(0,o.default)()})),uniques:null===(s=e.uniques)||void 0===s?void 0:s.map(e=>Object.assign(Object.assign({},e),{pairingId:e.pairingId||(0,o.default)()})),pairingId:e.pairingId||(0,o.default)()}):e}function p(e){return e.objectTypeField?Object.assign(Object.assign({},e),{pairingId:e.pairingId||(0,o.default)()}):e}function d(e,t,n){return n.ignoreCase?(e||"").toLowerCase()==(t||"").toLowerCase():e==t}function h(e,t,n){return null==e||null==t?e==t:function(e,t,n){return"ignore"==n.schemaMode&&(e=null),"ignoreImplicit"==n.schemaMode&&e==n.leftImplicitSchema&&(e=null),"ignore"==n.schemaMode&&(t=null),"ignoreImplicit"==n.schemaMode&&t==n.rightImplicitSchema&&(t=null),d(e,t,n)}(e.schemaName,t.schemaName,n)&&d(e.pureName,t.pureName,n)}function m(e,t,n,r,o={}){if(n&&!d(e.columnName,t.columnName,o))return!1;if(e.computedExpression!=t.computedExpression)return console.debug(`Column ${e.pureName}.${e.columnName}, ${t.pureName}.${t.columnName}: different computed expression: ${e.computedExpression}, ${t.computedExpression}`),!1;if(null!=e.computedExpression)return!0;if(r){if(null==e.defaultValue){if(e.defaultValue!=t.defaultValue)return console.debug(`Column ${e.pureName}.${e.columnName}, ${t.pureName}.${t.columnName}: different default value: ${e.defaultValue}, ${t.defaultValue}`),!1}else if(e.defaultValue!=t.defaultValue)return console.debug(`Column ${e.pureName}.${e.columnName}, ${t.pureName}.${t.columnName}: different default value: ${e.defaultValue}, ${t.defaultValue}`),!1;if(e.defaultConstraint!=t.defaultConstraint)return console.debug(`Column ${e.pureName}.${e.columnName}, ${t.pureName}.${t.columnName}: different default constraint: ${e.defaultConstraint}, ${t.defaultConstraint}`),!1}return(e.notNull||!1)!=(t.notNull||!1)?(console.debug(`Column ${e.pureName}.${e.columnName}, ${t.pureName}.${t.columnName}: different nullability: ${e.notNull}, ${t.notNull}`),!1):(e.autoIncrement||!1)!=(t.autoIncrement||!1)?(console.debug(`Column ${e.pureName}.${e.columnName}, ${t.pureName}.${t.columnName}: different autoincrement: ${e.autoIncrement}, ${t.autoIncrement}`),!1):(e.isSparse||!1)!=(t.isSparse||!1)?(console.debug(`Column ${e.pureName}.${e.columnName}, ${t.pureName}.${t.columnName}: different is_sparse: ${e.isSparse}, ${t.isSparse}`),!1):(e.isUnsigned||!1)!=(t.isUnsigned||!1)?(console.debug(`Column ${e.pureName}.${e.columnName}, ${t.pureName}.${t.columnName}: different unsigned: ${e.isUnsigned}, ${t.isUnsigned}`),!1):(e.isZerofill||!1)!=(t.isZerofill||!1)?(console.debug(`Column ${e.pureName}.${e.columnName}, ${t.pureName}.${t.columnName}: different zerofill: ${e.isZerofill}, ${t.isZerofill}`),!1):(e.columnComment||"")!=(t.columnComment||"")?(console.debug(`Column ${e.pureName}.${e.columnName}, ${t.pureName}.${t.columnName}: different comment: ${e.columnComment}, ${t.columnComment}`),!1):!!g(e,t,o)}function g(e,t,n={}){return!!n.ignoreDataTypes||((e.dataType||"").toLowerCase()==(t.dataType||"").toLowerCase()||(console.debug(`Column ${e.pureName}.${e.columnName}, ${t.pureName}.${t.columnName}: different data type: ${e.dataType}, ${t.dataType}`),!1))}function y(e){const t=[];return e.primaryKey&&t.push(e.primaryKey),e.foreignKeys&&t.push(...e.foreignKeys),e.indexes&&t.push(...e.indexes),e.uniques&&t.push(...e.uniques),e.checks&&t.push(...e.checks),t}function b(e,t,n=null){const r=[];for(const o of e){const e=t.find(e=>e.pairingId==o.pairingId||n&&n(o,e));e?r.push([o,e]):r.push([o,null])}for(const e of t)r.find(t=>t[1]==e)||r.push([null,e]);return r}function v(e,t,n){var r,o,i;const s=n.preloadedRowsKey||(null===(o=null===(r=n.primaryKey)||void 0===r?void 0:r.columns)||void 0===o?void 0:o.map(e=>e.columnName));(null===(i=n.preloadedRows)||void 0===i?void 0:i.length)>0&&(null==s?void 0:s.length)>0&&e.fillPreloadedRows(n,null==t?void 0:t.preloadedRows,n.preloadedRows,s,n.preloadedRowsInsertOnly)}function S(e,t,n,r){const o=b(t.columns,n.columns),i=b(y(t),y(n),(e,t)=>"primaryKey"==e.constraintType&&"primaryKey"==t.constraintType);r.noDropConstraint||i.filter(e=>null==e[1]).forEach(t=>e.dropConstraint(t[0])),r.noDropColumn||o.filter(e=>null==e[1]).forEach(t=>e.dropColumn(t[0])),h(t,n,r)||r.noRenameTable||e.renameTable(t,n.pureName),o.filter(e=>null==e[0]).forEach(t=>e.createColumn(t[1])),o.filter(e=>e[0]&&e[1]).forEach(t=>{m(t[0],t[1],!0,!0,r)||(m(t[0],t[1],!1,!0,r)&&!r.noRenameColumn?e.renameColumn(t[0],t[1].columnName):e.changeColumn(t[0],t[1]))}),i.filter(e=>e[0]&&e[1]).forEach(t=>{(function(e,t,n={}){const r=[];return n.ignoreForeignKeyActions&&(r.push("updateAction"),r.push("deleteAction")),n.ignoreConstraintNames&&r.push("constraintName"),"ignore"==n.schemaMode&&(r.push("schemaName"),r.push("refSchemaName")),(0,s.default)((0,a.default)(e,r))==(0,s.default)((0,a.default)(t,r))})(t[0],t[1],r)||e.changeConstraint(t[0],t[1])}),i.filter(e=>null==e[0]).forEach(t=>e.createConstraint(t[1])),v(e,t,n)}function w(e,t,n){return e.createSql==t.createSql}function _(e,t,n,r,o,s){const a=new i.AlterPlan(r,o,s.dialect,n);return null==e?(a.createTable(t),v(a,null,t)):null==t?a.dropTable(e):S(a,e,t,n),a.transformPlan(),a}function O(e,t,n,r,o,s){const a=new i.AlterPlan(r,o,s.dialect,n);for(const r of["tables","views","procedures","matviews","functions"]){for(const o of e[r]||[]){const e=(t[r]||[]).find(e=>e.pairingId==o.pairingId);"tables"==r?null==e?n.noDropTable||a.dropTable(o):S(a,o,e,n):null==e?n.noDropSqlObject||a.dropSqlObject(o):w(o.createSql,e.createSql)||(a.recreates.sqlObjects+=1,n.noDropSqlObject||a.dropSqlObject(o),a.createSqlObject(e))}for(const n of t[r]||[]){const t=(e[r]||[]).find(e=>e.pairingId==n.pairingId);"tables"==r?null==t&&(a.createTable(n),v(a,null,n)):null==t&&a.createSqlObject(n)}}return a.transformPlan(),a}t.generateTablePairingId=f,t.generateDbPairingId=function(e){var t,n,r,o,i,s;return e?Object.assign(Object.assign({},e),{tables:null===(t=e.tables)||void 0===t?void 0:t.map(f),views:null===(n=e.views)||void 0===n?void 0:n.map(p),procedures:null===(r=e.procedures)||void 0===r?void 0:r.map(p),functions:null===(o=e.functions)||void 0===o?void 0:o.map(p),triggers:null===(i=e.triggers)||void 0===i?void 0:i.map(p),matviews:null===(s=e.matviews)||void 0===s?void 0:s.map(p)}):e},t.testEqualColumns=m,t.testEqualTypes=g,t.testEqualTables=function(e,t,n,r,o,s){const a=new i.AlterPlan(r,o,s.dialect,n);return S(a,e,t,n),0==a.operations.length},t.testEqualSqlObjects=w,t.createAlterTablePlan=_,t.createAlterDatabasePlan=O,t.getAlterTableScript=function(e,t,n,r,o,i){if(!e&&!t||!i)return{sql:"",recreates:[]};const s=_(e,t,n,r,o,i),a=i.createDumper({useHardSeparator:!0});return i.dialect.disableExplicitTransaction||a.beginTransaction(),s.run(a),i.dialect.disableExplicitTransaction||a.commitTransaction(),{sql:a.s,recreates:s.recreates}},t.getAlterDatabaseScript=function(e,t,n,r,o,i){const s=O(e,t,n,r,o,i),a=i.createDumper({useHardSeparator:!0});return i.dialect.disableExplicitTransaction||a.beginTransaction(),s.run(a),i.dialect.disableExplicitTransaction||a.commitTransaction(),{sql:a.s,recreates:s.recreates,isEmpty:0==s.operations.length}},t.matchPairedObjects=function(e,t,n){if(!e||!t)return null;const r=(0,c.default)(t);for(const t of["tables","views","procedures","matviews","functions"])for(const o of r[t]||[]){const r=e[t].find(e=>h(e,o,n));if(r&&(o.pairingId=r.pairingId,"tables"==t)){for(const e of o.columns){const t=r.columns.find(t=>d(t.columnName,e.columnName,n));t&&(e.pairingId=t.pairingId)}for(const e of o.foreignKeys){const t=r.foreignKeys.find(t=>d(t.refTableName,e.refTableName,n)&&(0,u.default)(t.columns.map(e=>(0,l.default)(e,["columnName","refColumnName"])),e.columns.map(e=>(0,l.default)(e,["columnName","refColumnName"]))));t&&(e.pairingId=t.pairingId)}for(const e of o.uniques){const t=r.uniques.find(t=>(0,u.default)(t.columns.map(e=>(0,l.default)(e,["columnName"])),e.columns.map(e=>(0,l.default)(e,["columnName"]))));t&&(e.pairingId=t.pairingId)}for(const e of o.indexes){const t=r.indexes.find(t=>d(t.constraintName,e.constraintName,n));t&&(e.pairingId=t.pairingId)}}}return r},t.modelCompareDbDiffOptions={ignoreCase:!0,schemaMode:"ignore",ignoreConstraintNames:!0,ignoreForeignKeyActions:!0,ignoreDataTypes:!0}},function(e,t,n){"use strict";if(void 0!==global.Map)e.exports=global.Map,e.exports.Map=global.Map;else{var r=function(e){this._keys=[],this._values={};for(var t=0;t<e.length;t++)if(null!=e[t]){var n=e[t],r=n[0],o=n[1];this._keys.push(r),this._values[r]={v:o,i:this._keys.length-1}}};r.prototype.clear=function(){this._keys=[],this._values={}},r.prototype.delete=function(e){var t=this._values[e];return null!=t&&(delete this._values[e],this._keys.splice(t.i,1),!0)},r.prototype.entries=function(){var e=this,t=0;return{next:function(){var n=e._keys[t++];return{value:void 0!==n?[n,e._values[n].v]:void 0,done:void 0===n}}}},r.prototype.forEach=function(e,t){t=t||this;for(var n=0;n<this._keys.length;n++){var r=this._keys[n];e.call(t,this._values[r].v,r,t)}},r.prototype.get=function(e){return this._values[e]?this._values[e].v:void 0},r.prototype.has=function(e){return null!=this._values[e]},r.prototype.keys=function(){var e=this,t=0;return{next:function(){var n=e._keys[t++];return{value:void 0!==n?n:void 0,done:void 0===n}}}},r.prototype.set=function(e,t){return this._values[e]?(this._values[e].v=t,this):(this._keys.push(e),this._values[e]={v:t,i:this._keys.length-1},this)},r.prototype.values=function(){var e=this,t=0;return{next:function(){var n=e._keys[t++];return{value:void 0!==n?e._values[n].v:void 0,done:void 0===n}}}},Object.defineProperty(r.prototype,"size",{enumerable:!0,get:function(){return this._keys.length}}),e.exports=r,e.exports.Map=r}},function(e,t){var n=function(e){if(!(this instanceof n))return new n(e);this._bsontype="Int32",this.value=e};n.prototype.valueOf=function(){return this.value},n.prototype.toJSON=function(){return this.value},e.exports=n,e.exports.Int32=n},function(e,t){e.exports=require("buffer")},function(e,t,n){"use strict";const r=n(409);function o(e,t,n,o){let i;"object"==typeof o?(i=o,r(!(i.hasOwnProperty("notFound")&&i.hasOwnProperty("default")),"optionalRequire: options set with both `notFound` and `default`")):i={message:o};try{return t?e.resolve(n):e(n)}catch(e){if("MODULE_NOT_FOUND"!==e.code||!function(e,t){const n=e.message.split("\n")[0];return n&&(n.includes(`'${t}'`)||n.includes(` ${t} `)||n.includes(` ${t}. `)||n.includes(` ${t}, `))}(e,n)){if("function"==typeof i.fail)return i.fail(e);throw e}if(i.message){const e="string"==typeof i.message?`${i.message} - `:"",r=t?"resolved":"found";a.log(`${e}optional module not ${r}`,n)}return"function"==typeof i.notFound?i.notFound(e):i.default}}const i=(e,t,n)=>o(e,!1,t,n),s=(e,t,n)=>o(e,!0,t,n);function a(e){const t=(t,n)=>i(e,t,n);return t.resolve=(t,n)=>s(e,t,n),t}a.try=i,a.tryResolve=s,a.resolve=s,a.log=(e,t)=>console.log(`Just FYI: ${e}; Path "${t}"`),e.exports=a},function(e,t,n){"use strict";var r=function(e,t,n){this.result=e,this.connection=t,this.message=n};r.prototype.toJSON=function(){let e=Object.assign({},this,this.result);return delete e.message,e},r.prototype.toString=function(){return JSON.stringify(this.toJSON())},e.exports=r},function(e,t,n){"use strict";var r=n(5).inherits,o=n(5).format,i=n(8).EventEmitter,s=n(10),a=n(16),c=n(9).debugOptions,u=n(9).retrieveBSON,l=n(414),f=n(3).MongoError,p=n(3).MongoNetworkError,d=n(199),h=n(17).CoreCursor,m=n(7),g=n(7).createCompressionInfo,y=n(7).resolveClusterTime,b=n(7).SessionMixins,v=n(4).relayEvents;const S=n(4).collationNotSupported,w=n(4).makeClientMetadata;var _=["reconnect","reconnectTries","reconnectInterval","emitError","cursorFactory","host","port","size","keepAlive","keepAliveInitialDelay","noDelay","connectionTimeout","checkServerIdentity","socketTimeout","ssl","ca","crl","cert","key","rejectUnauthorized","promoteLongs","promoteValues","promoteBuffers","servername"],O=0,T=!1,C={},x=u();function E(e){return null==e.s.parent?e.id:e.s.parent.id}var N=function(e){e=e||{},i.call(this),this.id=O++,this.s={options:Object.assign({metadata:w(e)},e),logger:a("Server",e),Cursor:e.cursorFactory||h,bson:e.bson||new x([x.Binary,x.Code,x.DBRef,x.Decimal128,x.Double,x.Int32,x.Long,x.Map,x.MaxKey,x.MinKey,x.ObjectId,x.BSONRegExp,x.Symbol,x.Timestamp]),pool:null,disconnectHandler:e.disconnectHandler,monitoring:"boolean"!=typeof e.monitoring||e.monitoring,inTopology:!!e.parent,monitoringInterval:"number"==typeof e.monitoringInterval?e.monitoringInterval:5e3,compression:{compressors:g(e)},parent:e.parent},this.s.parent||(this.s.clusterTime=null),this.ismaster=null,this.lastIsMasterMS=-1,this.monitoringProcessId=null,this.initialConnect=!0,this._type="server",this.lastUpdateTime=0,this.lastWriteDate=0,this.staleness=0};function I(e,t,n,r,i,s){return e.s.pool.isConnected()||!e.s.options.reconnect||null==e.s.disconnectHandler||i.monitoring?e.s.pool.isConnected()?void 0:(s(new f(o("no connection available to server %s",e.name))),!0):(e.s.disconnectHandler.add(t,n,r,i,s),!0)}r(N,i),Object.assign(N.prototype,b),Object.defineProperty(N.prototype,"type",{enumerable:!0,get:function(){return this._type}}),Object.defineProperty(N.prototype,"parserType",{enumerable:!0,get:function(){return x.native?"c++":"js"}}),Object.defineProperty(N.prototype,"logicalSessionTimeoutMinutes",{enumerable:!0,get:function(){return this.ismaster&&this.ismaster.logicalSessionTimeoutMinutes||null}}),Object.defineProperty(N.prototype,"clientMetadata",{enumerable:!0,get:function(){return this.s.options.metadata}}),Object.defineProperty(N.prototype,"clusterTime",{enumerable:!0,set:function(e){const t=this.s.parent?this.s.parent:this.s;y(t,e)},get:function(){return(this.s.parent?this.s.parent:this.s).clusterTime||null}}),N.enableServerAccounting=function(){T=!0,C={}},N.disableServerAccounting=function(){T=!1},N.servers=function(){return C},Object.defineProperty(N.prototype,"name",{enumerable:!0,get:function(){return this.s.options.host+":"+this.s.options.port}});var A=function(e,t){return function(n,r){if(e.s.logger.isInfo()){var i=n instanceof f?JSON.stringify(n):{};e.s.logger.info(o("server %s fired event %s out with message %s",e.name,t,i))}if("connect"===t){if(e.initialConnect=!1,e.ismaster=r.ismaster,e.lastIsMasterMS=r.lastIsMasterMS,r.agreedCompressor&&(e.s.pool.options.agreedCompressor=r.agreedCompressor),r.zlibCompressionLevel&&(e.s.pool.options.zlibCompressionLevel=r.zlibCompressionLevel),r.ismaster.$clusterTime){const t=r.ismaster.$clusterTime;e.clusterTime=t}"isdbgrid"===e.ismaster.msg&&(e._type="mongos"),e.s.monitoring&&(e.monitoringProcessId=setTimeout(function e(t){return function(){if(!t.s.pool.isDestroyed()){t.emit("monitoring",t);var n=(new Date).getTime();t.command("admin.$cmd",{ismaster:!0},{socketTimeout:"number"!=typeof t.s.options.connectionTimeout?2e3:t.s.options.connectionTimeout,monitoring:!0},(r,o)=>{t.lastIsMasterMS=(new Date).getTime()-n,t.s.pool.isDestroyed()||(o&&(t.ismaster=o.result),t.monitoringProcessId=setTimeout(e(t),t.s.monitoringInterval))})}}}(e),e.s.monitoringInterval)),m.emitServerDescriptionChanged(e,{address:e.name,arbiters:[],hosts:[],passives:[],type:m.getTopologyType(e)}),e.s.inTopology||m.emitTopologyDescriptionChanged(e,{topologyType:"Single",servers:[{address:e.name,arbiters:[],hosts:[],passives:[],type:m.getTopologyType(e)}]}),e.s.logger.isInfo()&&e.s.logger.info(o("server %s connected with ismaster [%s]",e.name,JSON.stringify(e.ismaster))),e.emit("connect",e)}else if("error"===t||"parseError"===t||"close"===t||"timeout"===t||"reconnect"===t||"attemptReconnect"===t||"reconnectFailed"===t){if(T&&-1!==["close","timeout","error","parseError","reconnectFailed"].indexOf(t)&&(e.s.inTopology||e.emit("topologyOpening",{topologyId:e.id}),delete C[e.id]),"close"===t&&m.emitServerDescriptionChanged(e,{address:e.name,arbiters:[],hosts:[],passives:[],type:"Unknown"}),"reconnectFailed"===t)return e.emit("reconnectFailed",n),void(e.listeners("error").length>0&&e.emit("error",n));if(-1!==["disconnected","connecting"].indexOf(e.s.pool.state)&&e.initialConnect&&-1!==["close","timeout","error","parseError"].indexOf(t))return e.initialConnect=!1,e.emit("error",new p(o("failed to connect to server [%s] on first connect [%s]",e.name,n)));if("reconnect"===t)return m.emitServerDescriptionChanged(e,{address:e.name,arbiters:[],hosts:[],passives:[],type:m.getTopologyType(e)}),e.emit(t,e);e.emit(t,n)}}};function k(e){return e.s.pool?e.s.pool.isDestroyed()?new f("server instance pool was destroyed"):void 0:new f("server instance is not connected")}N.prototype.connect=function(e){if(e=e||{},T&&(C[this.id]=this),this.s.pool&&!this.s.pool.isDisconnected()&&!this.s.pool.isDestroyed())throw new f(o("server instance in invalid state %s",this.s.pool.state));this.s.pool=new l(this,Object.assign(this.s.options,e,{bson:this.s.bson})),this.s.pool.on("close",A(this,"close")),this.s.pool.on("error",A(this,"error")),this.s.pool.on("timeout",A(this,"timeout")),this.s.pool.on("parseError",A(this,"parseError")),this.s.pool.on("connect",A(this,"connect")),this.s.pool.on("reconnect",A(this,"reconnect")),this.s.pool.on("reconnectFailed",A(this,"reconnectFailed")),v(this.s.pool,this,["commandStarted","commandSucceeded","commandFailed"]),this.s.inTopology||this.emit("topologyOpening",{topologyId:E(this)}),this.emit("serverOpening",{topologyId:E(this),address:this.name}),this.s.pool.connect()},N.prototype.auth=function(e,t){"function"==typeof t&&t(null,null)},N.prototype.getDescription=function(){var e=this.ismaster||{},t={type:m.getTopologyType(this),address:this.name};return e.hosts&&(t.hosts=e.hosts),e.arbiters&&(t.arbiters=e.arbiters),e.passives&&(t.passives=e.passives),e.setName&&(t.setName=e.setName),t},N.prototype.lastIsMaster=function(){return this.ismaster},N.prototype.unref=function(){this.s.pool.unref()},N.prototype.isConnected=function(){return!!this.s.pool&&this.s.pool.isConnected()},N.prototype.isDestroyed=function(){return!!this.s.pool&&this.s.pool.isDestroyed()},N.prototype.command=function(e,t,n,r){"function"==typeof n&&(r=n,n=(n={})||{});var i=function(e,t){if(k(e),t.readPreference&&!(t.readPreference instanceof s))throw new Error("readPreference must be an instance of ReadPreference")}(this,n);return i?r(i):(n=Object.assign({},n,{wireProtocolCommand:!1}),this.s.logger.isDebug()&&this.s.logger.debug(o("executing command [%s] against %s",JSON.stringify({ns:e,cmd:t,options:c(_,n)}),this.name)),I(this,"command",e,t,n,r)?void 0:S(this,t)?r(new f(`server ${this.name} does not support collation`)):void d.command(this,e,t,n,r))},N.prototype.query=function(e,t,n,r,o){d.query(this,e,t,n,r,o)},N.prototype.getMore=function(e,t,n,r,o){d.getMore(this,e,t,n,r,o)},N.prototype.killCursors=function(e,t,n){d.killCursors(this,e,t,n)},N.prototype.insert=function(e,t,n,r){"function"==typeof n&&(r=n,n=(n={})||{});var o=k(this);return o?r(o):I(this,"insert",e,t,n,r)?void 0:(t=Array.isArray(t)?t:[t],d.insert(this,e,t,n,r))},N.prototype.update=function(e,t,n,r){"function"==typeof n&&(r=n,n=(n={})||{});var o=k(this);return o?r(o):I(this,"update",e,t,n,r)?void 0:S(this,n)?r(new f(`server ${this.name} does not support collation`)):(t=Array.isArray(t)?t:[t],d.update(this,e,t,n,r))},N.prototype.remove=function(e,t,n,r){"function"==typeof n&&(r=n,n=(n={})||{});var o=k(this);return o?r(o):I(this,"remove",e,t,n,r)?void 0:S(this,n)?r(new f(`server ${this.name} does not support collation`)):(t=Array.isArray(t)?t:[t],d.remove(this,e,t,n,r))},N.prototype.cursor=function(e,t,n){const r=(n=n||{}).topology||this;return new(n.cursorFactory||this.s.Cursor)(r,e,t,n)},N.prototype.equals=function(e){return"string"==typeof e?this.name.toLowerCase()===e.toLowerCase():!!e.name&&this.name.toLowerCase()===e.name.toLowerCase()},N.prototype.connections=function(){return this.s.pool.allConnections()},N.prototype.selectServer=function(e,t,n){"function"==typeof e&&void 0===n&&(n=e,e=void 0,t={}),"function"==typeof t&&(n=t,t=e,e=void 0),n(null,this)};var M=["close","error","timeout","parseError","connect"];N.prototype.destroy=function(e,t){if(this._destroyed)"function"==typeof t&&t(null,null);else{"function"==typeof e&&(t=e,e={}),e=e||{};var n=this;if(T&&delete C[this.id],this.monitoringProcessId&&clearTimeout(this.monitoringProcessId),!n.s.pool||this._destroyed)return this._destroyed=!0,void("function"==typeof t&&t(null,null));this._destroyed=!0,e.emitClose&&n.emit("close",n),e.emitDestroy&&n.emit("destroy",n),M.forEach((function(e){n.s.pool.removeAllListeners(e)})),n.listeners("serverClosed").length>0&&n.emit("serverClosed",{topologyId:E(n),address:n.name}),n.listeners("topologyClosed").length>0&&!n.s.inTopology&&n.emit("topologyClosed",{topologyId:E(n)}),n.s.logger.isDebug()&&n.s.logger.debug(o("destroy called on server %s",n.name)),this.s.pool.destroy(e.force,t)}},e.exports=N},function(e,t,n){"use strict";const r=n(415),o=n(192),i=n(187),s=n(3).MongoError,a=n(3).MongoNetworkError,c=n(3).MongoNetworkTimeoutError,u=n(193).defaultAuthProviders,l=n(33).AuthContext,f=n(190),p=n(4).makeClientMetadata,d=f.MAX_SUPPORTED_WIRE_VERSION,h=f.MAX_SUPPORTED_SERVER_VERSION,m=f.MIN_SUPPORTED_WIRE_VERSION,g=f.MIN_SUPPORTED_SERVER_VERSION;let y;const b=["pfx","key","passphrase","cert","ca","ciphers","NPNProtocols","ALPNProtocols","servername","ecdhCurve","secureProtocol","secureContext","session","minDHSize","crl","rejectUnauthorized"];function v(e,t){const n="string"==typeof t.host?t.host:"localhost";return-1!==n.indexOf("/")?{path:n}:{family:e,host:n,port:"number"==typeof t.port?t.port:27017,rejectUnauthorized:!1}}const S=new Set(["error","close","timeout","parseError"]);e.exports=function(e,t,n){"function"==typeof t&&(n=t,t=void 0);const f=e&&e.connectionType?e.connectionType:i;null==y&&(y=u(e.bson)),function(e,t,n,i){const s="boolean"==typeof t.ssl&&t.ssl,u="boolean"!=typeof t.keepAlive||t.keepAlive;let l="number"==typeof t.keepAliveInitialDelay?t.keepAliveInitialDelay:12e4;const f="boolean"!=typeof t.noDelay||t.noDelay,p="number"==typeof t.connectionTimeout?t.connectionTimeout:"number"==typeof t.connectTimeoutMS?t.connectTimeoutMS:3e4,d="number"==typeof t.socketTimeout?t.socketTimeout:0,h="boolean"!=typeof t.rejectUnauthorized||t.rejectUnauthorized;l>d&&(l=Math.round(d/2));let m;const g=function(e,t){e&&m&&m.destroy(),i(e,t)};try{s?(m=o.connect(function(e,t){const n=v(e,t);for(const e in t)null!=t[e]&&-1!==b.indexOf(e)&&(n[e]=t[e]);!1===t.checkServerIdentity?n.checkServerIdentity=function(){}:"function"==typeof t.checkServerIdentity&&(n.checkServerIdentity=t.checkServerIdentity);null!=n.servername||r.isIP(n.host)||(n.servername=n.host);return n}(e,t)),"function"==typeof m.disableRenegotiation&&m.disableRenegotiation()):m=r.createConnection(v(e,t))}catch(e){return g(e)}m.setKeepAlive(u,l),m.setTimeout(p),m.setNoDelay(f);const y=s?"secureConnect":"connect";let w;function _(e){return t=>{S.forEach(e=>m.removeAllListeners(e)),w&&n.removeListener("cancel",w),m.removeListener(y,O),g(function(e,t){switch(e){case"error":return new a(t);case"timeout":return new c("connection timed out");case"close":return new a("connection closed");case"cancel":return new a("connection establishment was cancelled");default:return new a("unknown network error")}}(e,t))}}function O(){if(S.forEach(e=>m.removeAllListeners(e)),w&&n.removeListener("cancel",w),m.authorizationError&&h)return g(m.authorizationError);m.setTimeout(d),g(null,m)}S.forEach(e=>m.once(e,_(e))),n&&(w=_("cancel"),n.once("cancel",w));m.once(y,O)}(void 0!==e.family?e.family:0,e,t,(t,r)=>{t?n(t,r):function(e,t,n){const r=function(t,r){t&&e&&e.destroy(),n(t,r)},o=t.credentials;if(o&&!o.mechanism.match(/DEFAULT/i)&&!y[o.mechanism])return void r(new s(`authMechanism '${o.mechanism}' not supported`));const a=new l(e,o,t);!function(e,t){const n=e.options,r=n.compression&&n.compression.compressors?n.compression.compressors:[],o={ismaster:!0,client:n.metadata||p(n),compression:r},i=e.credentials;if(i){if(i.mechanism.match(/DEFAULT/i)&&i.username)return Object.assign(o,{saslSupportedMechs:`${i.source}.${i.username}`}),void y["scram-sha-256"].prepare(o,e,t);return void y[i.mechanism].prepare(o,e,t)}t(void 0,o)}(a,(n,c)=>{if(n)return r(n);const u=Object.assign({},t);(t.connectTimeoutMS||t.connectionTimeout)&&(u.socketTimeout=t.connectTimeoutMS||t.connectionTimeout);const l=(new Date).getTime();e.command("admin.$cmd",c,u,(n,u)=>{if(n)return void r(n);const f=u.result;if(0===f.ok)return void r(new s(f));const p=function(e,t){const n=e&&"number"==typeof e.maxWireVersion&&e.maxWireVersion>=m,r=e&&"number"==typeof e.minWireVersion&&e.minWireVersion<=d;if(n){if(r)return null;const n=`Server at ${t.host}:${t.port} reports minimum wire version ${e.minWireVersion}, but this version of the Node.js Driver requires at most ${d} (MongoDB ${h})`;return new s(n)}const o=`Server at ${t.host}:${t.port} reports maximum wire version ${e.maxWireVersion||0}, but this version of the Node.js Driver requires at least ${m} (MongoDB ${g})`;return new s(o)}(f,t);if(p)r(p);else{if(!function(e){return!(e instanceof i)}(e)&&f.compression){const n=c.compression.filter(e=>-1!==f.compression.indexOf(e));n.length&&(e.agreedCompressor=n[0]),t.compression&&t.compression.zlibCompressionLevel&&(e.zlibCompressionLevel=t.compression.zlibCompressionLevel)}if(e.ismaster=f,e.lastIsMasterMS=(new Date).getTime()-l,f.arbiterOnly||!o)r(void 0,e);else{Object.assign(a,{response:f});const t=o.resolveAuthMechanism(f);y[t.mechanism].auth(a,t=>{if(t)return r(t);r(void 0,e)})}}})})}(new f(r,e),e,n)})}},function(e,t){e.exports=require("path")},function(e,t){e.exports=require("querystring")},function(e,t,n){"use strict";function r(e,t){t=t||{};this._head=0,this._tail=0,this._capacity=t.capacity,this._capacityMask=3,this._list=new Array(4),Array.isArray(e)&&this._fromArray(e)}r.prototype.peekAt=function(e){var t=e;if(t===(0|t)){var n=this.size();if(!(t>=n||t<-n))return t<0&&(t+=n),t=this._head+t&this._capacityMask,this._list[t]}},r.prototype.get=function(e){return this.peekAt(e)},r.prototype.peek=function(){if(this._head!==this._tail)return this._list[this._head]},r.prototype.peekFront=function(){return this.peek()},r.prototype.peekBack=function(){return this.peekAt(-1)},Object.defineProperty(r.prototype,"length",{get:function(){return this.size()}}),r.prototype.size=function(){return this._head===this._tail?0:this._head<this._tail?this._tail-this._head:this._capacityMask+1-(this._head-this._tail)},r.prototype.unshift=function(e){if(void 0===e)return this.size();var t=this._list.length;return this._head=this._head-1+t&this._capacityMask,this._list[this._head]=e,this._tail===this._head&&this._growArray(),this._capacity&&this.size()>this._capacity&&this.pop(),this._head<this._tail?this._tail-this._head:this._capacityMask+1-(this._head-this._tail)},r.prototype.shift=function(){var e=this._head;if(e!==this._tail){var t=this._list[e];return this._list[e]=void 0,this._head=e+1&this._capacityMask,e<2&&this._tail>1e4&&this._tail<=this._list.length>>>2&&this._shrinkArray(),t}},r.prototype.push=function(e){if(void 0===e)return this.size();var t=this._tail;return this._list[t]=e,this._tail=t+1&this._capacityMask,this._tail===this._head&&this._growArray(),this._capacity&&this.size()>this._capacity&&this.shift(),this._head<this._tail?this._tail-this._head:this._capacityMask+1-(this._head-this._tail)},r.prototype.pop=function(){var e=this._tail;if(e!==this._head){var t=this._list.length;this._tail=e-1+t&this._capacityMask;var n=this._list[this._tail];return this._list[this._tail]=void 0,this._head<2&&e>1e4&&e<=t>>>2&&this._shrinkArray(),n}},r.prototype.removeOne=function(e){var t=e;if(t===(0|t)&&this._head!==this._tail){var n=this.size(),r=this._list.length;if(!(t>=n||t<-n)){t<0&&(t+=n),t=this._head+t&this._capacityMask;var o,i=this._list[t];if(e<n/2){for(o=e;o>0;o--)this._list[t]=this._list[t=t-1+r&this._capacityMask];this._list[t]=void 0,this._head=this._head+1+r&this._capacityMask}else{for(o=n-1-e;o>0;o--)this._list[t]=this._list[t=t+1+r&this._capacityMask];this._list[t]=void 0,this._tail=this._tail-1+r&this._capacityMask}return i}}},r.prototype.remove=function(e,t){var n,r=e,o=t;if(r===(0|r)&&this._head!==this._tail){var i=this.size(),s=this._list.length;if(!(r>=i||r<-i||t<1)){if(r<0&&(r+=i),1===t||!t)return(n=new Array(1))[0]=this.removeOne(r),n;if(0===r&&r+t>=i)return n=this.toArray(),this.clear(),n;var a;for(r+t>i&&(t=i-r),n=new Array(t),a=0;a<t;a++)n[a]=this._list[this._head+r+a&this._capacityMask];if(r=this._head+r&this._capacityMask,e+t===i){for(this._tail=this._tail-t+s&this._capacityMask,a=t;a>0;a--)this._list[r=r+1+s&this._capacityMask]=void 0;return n}if(0===e){for(this._head=this._head+t+s&this._capacityMask,a=t-1;a>0;a--)this._list[r=r+1+s&this._capacityMask]=void 0;return n}if(r<i/2){for(this._head=this._head+e+t+s&this._capacityMask,a=e;a>0;a--)this.unshift(this._list[r=r-1+s&this._capacityMask]);for(r=this._head-1+s&this._capacityMask;o>0;)this._list[r=r-1+s&this._capacityMask]=void 0,o--;e<0&&(this._tail=r)}else{for(this._tail=r,r=r+t+s&this._capacityMask,a=i-(t+e);a>0;a--)this.push(this._list[r++]);for(r=this._tail;o>0;)this._list[r=r+1+s&this._capacityMask]=void 0,o--}return this._head<2&&this._tail>1e4&&this._tail<=s>>>2&&this._shrinkArray(),n}}},r.prototype.splice=function(e,t){var n=e;if(n===(0|n)){var r=this.size();if(n<0&&(n+=r),!(n>r)){if(arguments.length>2){var o,i,s,a=arguments.length,c=this._list.length,u=2;if(!r||n<r/2){for(i=new Array(n),o=0;o<n;o++)i[o]=this._list[this._head+o&this._capacityMask];for(0===t?(s=[],n>0&&(this._head=this._head+n+c&this._capacityMask)):(s=this.remove(n,t),this._head=this._head+n+c&this._capacityMask);a>u;)this.unshift(arguments[--a]);for(o=n;o>0;o--)this.unshift(i[o-1])}else{var l=(i=new Array(r-(n+t))).length;for(o=0;o<l;o++)i[o]=this._list[this._head+n+t+o&this._capacityMask];for(0===t?(s=[],n!=r&&(this._tail=this._head+n+c&this._capacityMask)):(s=this.remove(n,t),this._tail=this._tail-l+c&this._capacityMask);u<a;)this.push(arguments[u++]);for(o=0;o<l;o++)this.push(i[o])}return s}return this.remove(n,t)}}},r.prototype.clear=function(){this._head=0,this._tail=0},r.prototype.isEmpty=function(){return this._head===this._tail},r.prototype.toArray=function(){return this._copyArray(!1)},r.prototype._fromArray=function(e){for(var t=0;t<e.length;t++)this.push(e[t])},r.prototype._copyArray=function(e){var t,n=[],r=this._list,o=r.length;if(e||this._head>this._tail){for(t=this._head;t<o;t++)n.push(r[t]);for(t=0;t<this._tail;t++)n.push(r[t])}else for(t=this._head;t<this._tail;t++)n.push(r[t]);return n},r.prototype._growArray=function(){this._head&&(this._list=this._copyArray(!0),this._head=0),this._tail=this._list.length,this._list.length*=2,this._capacityMask=this._capacityMask<<1|1},r.prototype._shrinkArray=function(){this._list.length>>>=1,this._capacityMask>>>=1},e.exports=r},function(e,t,n){"use strict";const r=n(138),o=n(8),i=n(94).isResumableError,s=n(2).MongoError,a=n(26),c=n(4).relayEvents,u=n(4).maxWireVersion,l=n(0).maybePromise,f=n(0).now,p=n(0).calculateDurationInMs,d=n(95),h=Symbol("resumeQueue"),m=["resumeAfter","startAfter","startAtOperationTime","fullDocument"],g=["batchSize","maxAwaitTimeMS","collation","readPreference"].concat(m),y={COLLECTION:Symbol("Collection"),DATABASE:Symbol("Database"),CLUSTER:Symbol("Cluster")};class b extends a{constructor(e,t,n){super(e,t,n),n=n||{},this._resumeToken=null,this.startAtOperationTime=n.startAtOperationTime,n.startAfter?this.resumeToken=n.startAfter:n.resumeAfter&&(this.resumeToken=n.resumeAfter)}set resumeToken(e){this._resumeToken=e,this.emit("resumeTokenChanged",e)}get resumeToken(){return this._resumeToken}get resumeOptions(){const e={};for(const t of g)this.options[t]&&(e[t]=this.options[t]);if(this.resumeToken||this.startAtOperationTime)if(["resumeAfter","startAfter","startAtOperationTime"].forEach(t=>delete e[t]),this.resumeToken){const t=this.options.startAfter&&!this.hasReceived?"startAfter":"resumeAfter";e[t]=this.resumeToken}else this.startAtOperationTime&&u(this.server)>=7&&(e.startAtOperationTime=this.startAtOperationTime);return e}cacheResumeToken(e){0===this.bufferedCount()&&this.cursorState.postBatchResumeToken?this.resumeToken=this.cursorState.postBatchResumeToken:this.resumeToken=e,this.hasReceived=!0}_processBatch(e,t){const n=t.cursor;n.postBatchResumeToken&&(this.cursorState.postBatchResumeToken=n.postBatchResumeToken,0===n[e].length&&(this.resumeToken=n.postBatchResumeToken))}_initializeCursor(e){super._initializeCursor((t,n)=>{if(t||null==n)return void e(t,n);const r=n.documents[0];null==this.startAtOperationTime&&null==this.resumeAfter&&null==this.startAfter&&u(this.server)>=7&&(this.startAtOperationTime=r.operationTime),this._processBatch("firstBatch",r),this.emit("init",n),this.emit("response"),e(t,n)})}_getMore(e){super._getMore((t,n)=>{t?e(t):(this._processBatch("nextBatch",n),this.emit("more",n),this.emit("response"),e(t,n))})}}function v(e,t){const n={fullDocument:t.fullDocument||"default"};S(n,t,m),e.type===y.CLUSTER&&(n.allChangesForCluster=!0);const r=[{$changeStream:n}].concat(e.pipeline),o=S({},t,g),i=new b(e.topology,new d(e.parent,r,t),o);if(c(i,e,["resumeTokenChanged","end","close"]),e.listenerCount("change")>0&&i.on("data",(function(t){w(e,t)})),i.on("error",(function(t){_(e,t)})),e.pipeDestinations){const t=i.stream(e.streamOptions);for(let n of e.pipeDestinations)t.pipe(n)}return i}function S(e,t,n){return n.forEach(n=>{t[n]&&(e[n]=t[n])}),e}function w(e,t,n){const r=e.cursor;if(null==t&&(e.closed=!0),!e.closed){if(t&&!t._id){const t=new Error("A change stream document has been received that lacks a resume token (_id).");return n?n(t):e.emit("error",t)}return r.cacheResumeToken(t._id),e.options.startAtOperationTime=void 0,n?n(void 0,t):e.emit("change",t)}n&&n(new s("ChangeStream is closed"))}function _(e,t,n){const r=e.topology,o=e.cursor;if(!e.closed)return o&&i(t,u(o.server))?(e.cursor=void 0,["data","close","end","error"].forEach(e=>o.removeAllListeners(e)),o.close(),void function e(t,n,r){setTimeout(()=>{n&&null==n.start&&(n.start=f());const o=n.start||f(),i=n.timeout||3e4,a=n.readPreference;return t.isConnected({readPreference:a})?r():p(o)>i?r(new s("Timed out waiting for connection")):void e(t,n,r)},500)}(r,{readPreference:o.options.readPreference},t=>{if(t)return c(t);const r=v(e,o.resumeOptions);if(!n)return a(r);r.hasNext(e=>{if(e)return c(e);a(r)})})):n?n(t):e.emit("error",t);function a(t){e.cursor=t,T(e)}function c(t){n||(e.emit("error",t),e.emit("close")),T(e,t),e.closed=!0}n&&n(new s("ChangeStream is closed"))}function O(e,t){e.isClosed()?t(new s("ChangeStream is closed.")):e.cursor?t(void 0,e.cursor):e[h].push(t)}function T(e,t){for(;e[h].length;){const n=e[h].pop();if(e.isClosed()&&!t)return void n(new s("Change Stream is not open."));n(t,e.cursor)}}e.exports=class extends o{constructor(e,t,o){super();const i=n(61),s=n(97),a=n(59);if(this.pipeline=t||[],this.options=o||{},this.parent=e,this.namespace=e.s.namespace,e instanceof i)this.type=y.COLLECTION,this.topology=e.s.db.serverConfig;else if(e instanceof s)this.type=y.DATABASE,this.topology=e.serverConfig;else{if(!(e instanceof a))throw new TypeError("parent provided to ChangeStream constructor is not an instance of Collection, Db, or MongoClient");this.type=y.CLUSTER,this.topology=e.topology}this.promiseLibrary=e.s.promiseLibrary,!this.options.readPreference&&e.s.readPreference&&(this.options.readPreference=e.s.readPreference),this[h]=new r,this.cursor=v(this,o),this.closed=!1,this.on("newListener",e=>{"change"===e&&this.cursor&&0===this.listenerCount("change")&&this.cursor.on("data",e=>w(this,e))}),this.on("removeListener",e=>{"change"===e&&0===this.listenerCount("change")&&this.cursor&&this.cursor.removeAllListeners("data")})}get resumeToken(){return this.cursor.resumeToken}hasNext(e){return l(this.parent,e,e=>{O(this,(t,n)=>{if(t)return e(t);n.hasNext(e)})})}next(e){return l(this.parent,e,e=>{O(this,(t,n)=>{if(t)return e(t);n.next((t,n)=>{if(t)return this[h].push(()=>this.next(e)),void _(this,t,e);w(this,n,e)})})})}isClosed(){return this.closed||this.cursor&&this.cursor.isClosed()}close(e){return l(this.parent,e,e=>{if(this.closed)return e();if(this.closed=!0,!this.cursor)return e();const t=this.cursor;return t.close(n=>(["data","close","end","error"].forEach(e=>t.removeAllListeners(e)),this.cursor=void 0,e(n)))})}pipe(e,t){return this.pipeDestinations||(this.pipeDestinations=[]),this.pipeDestinations.push(e),this.cursor.pipe(e,t)}unpipe(e){return this.pipeDestinations&&this.pipeDestinations.indexOf(e)>-1&&this.pipeDestinations.splice(this.pipeDestinations.indexOf(e),1),this.cursor.unpipe(e)}stream(e){return this.streamOptions=e,this.cursor.stream(e)}pause(){return this.cursor.pause()}resume(){return this.cursor.resume()}}},function(e,t,n){"use strict";e.exports={SYSTEM_NAMESPACE_COLLECTION:"system.namespaces",SYSTEM_INDEX_COLLECTION:"system.indexes",SYSTEM_PROFILE_COLLECTION:"system.profile",SYSTEM_USER_COLLECTION:"system.users",SYSTEM_COMMAND_COLLECTION:"$cmd",SYSTEM_JS_COLLECTION:"system.js"}},function(e,t,n){"use strict";const r=n(2).BSON.Long,o=n(2).MongoError,i=n(2).BSON.ObjectID,s=n(2).BSON,a=n(2).MongoWriteConcernError,c=n(0).toError,u=n(0).handleCallback,l=n(0).applyRetryableWrites,f=n(0).applyWriteConcern,p=n(0).executeLegacyOperation,d=n(0).isPromiseLike,h=n(0).hasAtomicOperators,m=n(4).maxWireVersion,g=new s([s.Binary,s.Code,s.DBRef,s.Decimal128,s.Double,s.Int32,s.Long,s.Map,s.MaxKey,s.MinKey,s.ObjectId,s.BSONRegExp,s.Symbol,s.Timestamp]);class y{constructor(e){this.result=e}get ok(){return this.result.ok}get nInserted(){return this.result.nInserted}get nUpserted(){return this.result.nUpserted}get nMatched(){return this.result.nMatched}get nModified(){return this.result.nModified}get nRemoved(){return this.result.nRemoved}getInsertedIds(){return this.result.insertedIds}getUpsertedIds(){return this.result.upserted}getUpsertedIdAt(e){return this.result.upserted[e]}getRawResponse(){return this.result}hasWriteErrors(){return this.result.writeErrors.length>0}getWriteErrorCount(){return this.result.writeErrors.length}getWriteErrorAt(e){return e<this.result.writeErrors.length?this.result.writeErrors[e]:null}getWriteErrors(){return this.result.writeErrors}getLastOp(){return this.result.lastOp}getWriteConcernError(){if(0===this.result.writeConcernErrors.length)return null;if(1===this.result.writeConcernErrors.length)return this.result.writeConcernErrors[0];{let e="";for(let t=0;t<this.result.writeConcernErrors.length;t++){e+=this.result.writeConcernErrors[t].errmsg,0===t&&(e+=" and ")}return new b({errmsg:e,code:64})}}toJSON(){return this.result}toString(){return`BulkWriteResult(${this.toJSON(this.result)})`}isOk(){return 1===this.result.ok}}class b{constructor(e){this.err=e}get code(){return this.err.code}get errmsg(){return this.err.errmsg}toJSON(){return{code:this.err.code,errmsg:this.err.errmsg}}toString(){return`WriteConcernError(${this.err.errmsg})`}}class v{constructor(e){this.err=e}get code(){return this.err.code}get index(){return this.err.index}get errmsg(){return this.err.errmsg}getOperation(){return this.err.op}toJSON(){return{code:this.err.code,index:this.err.index,errmsg:this.err.errmsg,op:this.err.op}}toString(){return`WriteError(${JSON.stringify(this.toJSON())})`}}function S(e,t,n,o){if(n)o=n;else if(o&&o.result)o=o.result;else if(null==o)return;if(0===o.ok&&1===t.ok){t.ok=0;const n={index:0,code:o.code||0,errmsg:o.message,op:e.operations[0]};return void t.writeErrors.push(new v(n))}if(0===o.ok&&0===t.ok)return;if(o.opTime||o.lastOp){const e=o.lastOp||o.opTime;let n=null,i=null;if(e&&"Timestamp"===e._bsontype)null==t.lastOp?t.lastOp=e:e.greaterThan(t.lastOp)&&(t.lastOp=e);else{t.lastOp&&(n="number"==typeof t.lastOp.ts?r.fromNumber(t.lastOp.ts):t.lastOp.ts,i="number"==typeof t.lastOp.t?r.fromNumber(t.lastOp.t):t.lastOp.t);const o="number"==typeof e.ts?r.fromNumber(e.ts):e.ts,s="number"==typeof e.t?r.fromNumber(e.t):e.t;null==t.lastOp?t.lastOp=e:o.greaterThan(n)?t.lastOp=e:o.equals(n)&&s.greaterThan(i)&&(t.lastOp=e)}}1===e.batchType&&o.n&&(t.nInserted=t.nInserted+o.n),3===e.batchType&&o.n&&(t.nRemoved=t.nRemoved+o.n);let i=0;if(Array.isArray(o.upserted)){i=o.upserted.length;for(let n=0;n<o.upserted.length;n++)t.upserted.push({index:o.upserted[n].index+e.originalZeroIndex,_id:o.upserted[n]._id})}else o.upserted&&(i=1,t.upserted.push({index:e.originalZeroIndex,_id:o.upserted}));if(2===e.batchType&&o.n){const e=o.nModified;t.nUpserted=t.nUpserted+i,t.nMatched=t.nMatched+(o.n-i),t.nModified="number"==typeof e?t.nModified+e:null}if(Array.isArray(o.writeErrors))for(let n=0;n<o.writeErrors.length;n++){const r={index:e.originalIndexes[o.writeErrors[n].index],code:o.writeErrors[n].code,errmsg:o.writeErrors[n].errmsg,op:e.operations[o.writeErrors[n].index]};t.writeErrors.push(new v(r))}o.writeConcernError&&t.writeConcernErrors.push(new b(o.writeConcernError))}function w(e,t,n){if(0===e.s.batches.length)return u(n,null,new y(e.s.bulkResult));const r=e.s.batches.shift();e.finalOptionsHandler({options:t,batch:r,resultHandler:function(o,i){if((o&&o.driver||o&&o.message)&&!(o instanceof a))return u(n,o);if(o&&(o.ok=0),o instanceof a)return function(e,t,n,r){S(e,t,null,n.result);const o=new b({errmsg:n.result.writeConcernError.errmsg,code:n.result.writeConcernError.result});return u(r,new _(c(o),new y(t)),null)}(r,e.s.bulkResult,o,n);const s=new y(e.s.bulkResult);if(null!=S(r,e.s.bulkResult,o,i))return u(n,null,s);e.handleWriteError(n,s)||w(e,t,n)}},n)}class _ extends o{constructor(e,t){super(e.err||e.errmsg||e.errMessage||e),Object.assign(this,e),this.name="BulkWriteError",this.result=t}}class O{constructor(e){this.s=e.s}update(e){const t="boolean"==typeof this.s.currentOp.upsert&&this.s.currentOp.upsert,n={q:this.s.currentOp.selector,u:e,multi:!0,upsert:t};return e.hint&&(n.hint=e.hint),this.s.currentOp=null,this.s.options.addToOperationsList(this,2,n)}updateOne(e){const t="boolean"==typeof this.s.currentOp.upsert&&this.s.currentOp.upsert,n={q:this.s.currentOp.selector,u:e,multi:!1,upsert:t};if(e.hint&&(n.hint=e.hint),!h(e))throw new TypeError("Update document requires atomic operators");return this.s.currentOp=null,this.s.options.addToOperationsList(this,2,n)}replaceOne(e){const t="boolean"==typeof this.s.currentOp.upsert&&this.s.currentOp.upsert,n={q:this.s.currentOp.selector,u:e,multi:!1,upsert:t};if(e.hint&&(n.hint=e.hint),h(e))throw new TypeError("Replacement document must not use atomic operators");return this.s.currentOp=null,this.s.options.addToOperationsList(this,2,n)}upsert(){return this.s.currentOp.upsert=!0,this}deleteOne(){const e={q:this.s.currentOp.selector,limit:1};return this.s.currentOp=null,this.s.options.addToOperationsList(this,3,e)}delete(){const e={q:this.s.currentOp.selector,limit:0};return this.s.currentOp=null,this.s.options.addToOperationsList(this,3,e)}removeOne(){return this.deleteOne()}remove(){return this.delete()}}class T{constructor(e,t,n,r){this.isOrdered=r,n=null==n?{}:n;const o=t.s.namespace,i=e.bson,s=e.lastIsMaster(),a=!(!e.s.options||!e.s.options.autoEncrypter),c=s&&s.maxBsonObjectSize?s.maxBsonObjectSize:16777216,u=a?2097152:c,p=s&&s.maxWriteBatchSize?s.maxWriteBatchSize:1e3,d=(p-1).toString(10).length+2;let h=Object.assign({},n);h=l(h,t.s.db),h=f(h,{collection:t},n);const m=h.writeConcern,g=n.promiseLibrary||Promise;this.s={bulkResult:{ok:1,writeErrors:[],writeConcernErrors:[],insertedIds:[],nInserted:0,nUpserted:0,nMatched:0,nModified:0,nRemoved:0,upserted:[]},currentBatch:null,currentIndex:0,currentBatchSize:0,currentBatchSizeBytes:0,currentInsertBatch:null,currentUpdateBatch:null,currentRemoveBatch:null,batches:[],writeConcern:m,maxBsonObjectSize:c,maxBatchSizeBytes:u,maxWriteBatchSize:p,maxKeySize:d,namespace:o,bson:i,topology:e,options:h,currentOp:null,executed:!1,collection:t,promiseLibrary:g,err:null,checkKeys:"boolean"!=typeof n.checkKeys||n.checkKeys},!0===n.bypassDocumentValidation&&(this.s.bypassDocumentValidation=!0)}insert(e){return!0!==this.s.collection.s.db.options.forceServerObjectId&&null==e._id&&(e._id=new i),this.s.options.addToOperationsList(this,1,e)}find(e){if(!e)throw c("Bulk find operation must specify a selector");return this.s.currentOp={selector:e},new O(this)}raw(e){const t=Object.keys(e)[0],n="boolean"==typeof this.s.options.forceServerObjectId?this.s.options.forceServerObjectId:this.s.collection.s.db.options.forceServerObjectId;if(e.updateOne&&e.updateOne.q||e.updateMany&&e.updateMany.q||e.replaceOne&&e.replaceOne.q)return e[t].multi=!e.updateOne&&!e.replaceOne,this.s.options.addToOperationsList(this,2,e[t]);if(e.updateOne||e.updateMany||e.replaceOne){if(e.replaceOne&&h(e[t].replacement))throw new TypeError("Replacement document must not use atomic operators");if((e.updateOne||e.updateMany)&&!h(e[t].update))throw new TypeError("Update document requires atomic operators");const n=!e.updateOne&&!e.replaceOne,r={q:e[t].filter,u:e[t].update||e[t].replacement,multi:n};if(e[t].hint&&(r.hint=e[t].hint),this.isOrdered?(r.upsert=!!e[t].upsert,e.collation&&(r.collation=e.collation)):e[t].upsert&&(r.upsert=!0),e[t].arrayFilters){if(m(this.s.topology)<6)throw new TypeError("arrayFilters are only supported on MongoDB 3.6+");r.arrayFilters=e[t].arrayFilters}return this.s.options.addToOperationsList(this,2,r)}if(e.removeOne||e.removeMany||e.deleteOne&&e.deleteOne.q||e.deleteMany&&e.deleteMany.q)return e[t].limit=e.removeOne?1:0,this.s.options.addToOperationsList(this,3,e[t]);if(e.deleteOne||e.deleteMany){const n=e.deleteOne?1:0,r={q:e[t].filter,limit:n};return e[t].hint&&(r.hint=e[t].hint),this.isOrdered&&e.collation&&(r.collation=e.collation),this.s.options.addToOperationsList(this,3,r)}if(e.insertOne&&null==e.insertOne.document)return!0!==n&&null==e.insertOne._id&&(e.insertOne._id=new i),this.s.options.addToOperationsList(this,1,e.insertOne);if(e.insertOne&&e.insertOne.document)return!0!==n&&null==e.insertOne.document._id&&(e.insertOne.document._id=new i),this.s.options.addToOperationsList(this,1,e.insertOne.document);if(!e.insertMany)throw c("bulkWrite only supports insertOne, insertMany, updateOne, updateMany, removeOne, removeMany, deleteOne, deleteMany");for(let t=0;t<e.insertMany.length;t++)!0!==n&&null==e.insertMany[t]._id&&(e.insertMany[t]._id=new i),this.s.options.addToOperationsList(this,1,e.insertMany[t])}_handleEarlyError(e,t){if("function"!=typeof t)return this.s.promiseLibrary.reject(e);t(e,null)}bulkExecute(e,t,n){if("function"==typeof t&&(n=t,t={}),t=t||{},"function"==typeof e?n=e:e&&"object"==typeof e&&(this.s.writeConcern=e),this.s.executed){const e=c("batch cannot be re-executed");return this._handleEarlyError(e,n)}if(this.isOrdered?this.s.currentBatch&&this.s.batches.push(this.s.currentBatch):(this.s.currentInsertBatch&&this.s.batches.push(this.s.currentInsertBatch),this.s.currentUpdateBatch&&this.s.batches.push(this.s.currentUpdateBatch),this.s.currentRemoveBatch&&this.s.batches.push(this.s.currentRemoveBatch)),0===this.s.batches.length){const e=c("Invalid Operation, no operations specified");return this._handleEarlyError(e,n)}return{options:t,callback:n}}execute(e,t,n){const r=this.bulkExecute(e,t,n);return!r||d(r)?r:(t=r.options,n=r.callback,p(this.s.topology,w,[this,t,n]))}finalOptionsHandler(e,t){const n=Object.assign({ordered:this.isOrdered},e.options);null!=this.s.writeConcern&&(n.writeConcern=this.s.writeConcern),!0!==n.bypassDocumentValidation&&delete n.bypassDocumentValidation,this.operationId&&(e.resultHandler.operationId=this.operationId),this.s.options.serializeFunctions&&(n.serializeFunctions=!0),this.s.options.ignoreUndefined&&(n.ignoreUndefined=!0),!0===this.s.bypassDocumentValidation&&(n.bypassDocumentValidation=!0),!1===this.s.checkKeys&&(n.checkKeys=!1),n.retryWrites&&(2===e.batch.batchType&&(n.retryWrites=n.retryWrites&&!e.batch.operations.some(e=>e.multi)),3===e.batch.batchType&&(n.retryWrites=n.retryWrites&&!e.batch.operations.some(e=>0===e.limit)));try{1===e.batch.batchType?this.s.topology.insert(this.s.namespace,e.batch.operations,n,e.resultHandler):2===e.batch.batchType?this.s.topology.update(this.s.namespace,e.batch.operations,n,e.resultHandler):3===e.batch.batchType&&this.s.topology.remove(this.s.namespace,e.batch.operations,n,e.resultHandler)}catch(n){n.ok=0,u(t,null,S(e.batch,this.s.bulkResult,n,null))}}handleWriteError(e,t){if(this.s.bulkResult.writeErrors.length>0){const n=this.s.bulkResult.writeErrors[0].errmsg?this.s.bulkResult.writeErrors[0].errmsg:"write operation failed";return u(e,new _(c({message:n,code:this.s.bulkResult.writeErrors[0].code,writeErrors:this.s.bulkResult.writeErrors}),t),null),!0}if(t.getWriteConcernError())return u(e,new _(c(t.getWriteConcernError()),t),null),!0}}Object.defineProperty(T.prototype,"length",{enumerable:!0,get:function(){return this.s.currentIndex}}),e.exports={Batch:class{constructor(e,t){this.originalZeroIndex=t,this.currentIndex=0,this.originalIndexes=[],this.batchType=e,this.operations=[],this.size=0,this.sizeBytes=0}},BulkOperationBase:T,bson:g,INSERT:1,UPDATE:2,REMOVE:3,BulkWriteError:_}},function(e,t,n){"use strict";const r=n(2).MongoError,o=n(26),i=n(17).CursorState;class s extends o{constructor(e,t,n){super(e,t,n)}batchSize(e){if(this.s.state===i.CLOSED||this.isDead())throw r.create({message:"Cursor is closed",driver:!0});if("number"!=typeof e)throw r.create({message:"batchSize requires an integer",driver:!0});return this.operation.options.batchSize=e,this.setCursorBatchSize(e),this}geoNear(e){return this.operation.addToPipeline({$geoNear:e}),this}group(e){return this.operation.addToPipeline({$group:e}),this}limit(e){return this.operation.addToPipeline({$limit:e}),this}match(e){return this.operation.addToPipeline({$match:e}),this}maxTimeMS(e){return this.operation.options.maxTimeMS=e,this}out(e){return this.operation.addToPipeline({$out:e}),this}project(e){return this.operation.addToPipeline({$project:e}),this}lookup(e){return this.operation.addToPipeline({$lookup:e}),this}redact(e){return this.operation.addToPipeline({$redact:e}),this}skip(e){return this.operation.addToPipeline({$skip:e}),this}sort(e){return this.operation.addToPipeline({$sort:e}),this}unwind(e){return this.operation.addToPipeline({$unwind:e}),this}getLogger(){return this.logger}}s.prototype.get=s.prototype.toArray,e.exports=s},function(e,t,n){"use strict";const r=n(2).ReadPreference,o=n(2).MongoError,i=n(26),s=n(17).CursorState;class a extends i{constructor(e,t,n,r){super(e,t,n,r)}setReadPreference(e){if(this.s.state===s.CLOSED||this.isDead())throw o.create({message:"Cursor is closed",driver:!0});if(this.s.state!==s.INIT)throw o.create({message:"cannot change cursor readPreference after cursor has been accessed",driver:!0});if(e instanceof r)this.options.readPreference=e;else{if("string"!=typeof e)throw new TypeError("Invalid read preference: "+e);this.options.readPreference=new r(e)}return this}batchSize(e){if(this.s.state===s.CLOSED||this.isDead())throw o.create({message:"Cursor is closed",driver:!0});if("number"!=typeof e)throw o.create({message:"batchSize requires an integer",driver:!0});return this.cmd.cursor&&(this.cmd.cursor.batchSize=e),this.setCursorBatchSize(e),this}maxTimeMS(e){return this.topology.lastIsMaster().minWireVersion>2&&(this.cmd.maxTimeMS=e),this}getLogger(){return this.logger}}a.prototype.get=a.prototype.toArray,e.exports=a},function(e,t,n){"use strict";const r=n(1).Aspect,o=n(23),i=n(1).defineAspects,s=n(0).handleCallback;class a extends o{constructor(e,t){const n=Object.assign({},t,e.s.options);t.session&&(n.session=t.session),super(e,n)}execute(e){super.execute((t,n)=>t?s(e,t):n.ok?s(e,null,!0):void s(e,null,!1))}}i(a,r.WRITE_OPERATION);e.exports={DropOperation:a,DropCollectionOperation:class extends a{constructor(e,t,n){super(e,n),this.name=t,this.namespace=`${e.namespace}.${t}`}_buildCommand(){return{drop:this.name}}},DropDatabaseOperation:class extends a{_buildCommand(){return{dropDatabase:1}}}}},function(e,t,n){"use strict";let r,o,i;e.exports={loadCollection:function(){return r||(r=n(61)),r},loadCursor:function(){return o||(o=n(26)),o},loadDb:function(){return i||(i=n(97)),i}}},function(e,t,n){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.transformRowUsingColumnMap=t.prepareTableForImport=void 0;const o=r(n(101)),i=r(n(296)),s=r(n(162));t.prepareTableForImport=function(e){const t=(0,o.default)(e);return t.foreignKeys=[],t.indexes=[],t.uniques=[],t.checks=[],t.primaryKey&&(t.primaryKey.constraintName=null),t},t.transformRowUsingColumnMap=function(e,t){return(0,i.default)(t.map(t=>[t.dst,(0,s.default)(e,t.src)]))}},function(e,t,n){var r=n(102),o=n(265),i=n(105),s=n(266),a=n(273),c=n(276),u=n(277),l=n(278),f=n(280),p=n(157),d=n(159),h=n(70),m=n(284),g=n(285),y=n(290),b=n(12),v=n(108),S=n(292),w=n(28),_=n(294),O=n(49),T=n(111),C={};C["[object Arguments]"]=C["[object Array]"]=C["[object ArrayBuffer]"]=C["[object DataView]"]=C["[object Boolean]"]=C["[object Date]"]=C["[object Float32Array]"]=C["[object Float64Array]"]=C["[object Int8Array]"]=C["[object Int16Array]"]=C["[object Int32Array]"]=C["[object Map]"]=C["[object Number]"]=C["[object Object]"]=C["[object RegExp]"]=C["[object Set]"]=C["[object String]"]=C["[object Symbol]"]=C["[object Uint8Array]"]=C["[object Uint8ClampedArray]"]=C["[object Uint16Array]"]=C["[object Uint32Array]"]=!0,C["[object Error]"]=C["[object Function]"]=C["[object WeakMap]"]=!1,e.exports=function e(t,n,x,E,N,I){var A,k=1&n,M=2&n,R=4&n;if(x&&(A=N?x(t,E,N,I):x(t)),void 0!==A)return A;if(!w(t))return t;var j=b(t);if(j){if(A=m(t),!k)return u(t,A)}else{var D=h(t),P="[object Function]"==D||"[object GeneratorFunction]"==D;if(v(t))return c(t,k);if("[object Object]"==D||"[object Arguments]"==D||P&&!N){if(A=M||P?{}:y(t),!k)return M?f(t,a(A,t)):l(t,s(A,t))}else{if(!C[D])return N?t:{};A=g(t,D,k)}}I||(I=new r);var B=I.get(t);if(B)return B;I.set(t,A),_(t)?t.forEach((function(r){A.add(e(r,n,x,r,t,I))})):S(t)&&t.forEach((function(r,o){A.set(o,e(r,n,x,o,t,I))}));var L=j?void 0:(R?M?d:p:M?T:O)(t);return o(L||t,(function(r,o){L&&(r=t[o=r]),i(A,o,e(r,n,x,o,t,I))})),A}},function(e,t,n){var r=n(25),o=n(28);e.exports=function(e){if(!o(e))return!1;var t=r(e);return"[object Function]"==t||"[object GeneratorFunction]"==t||"[object AsyncFunction]"==t||"[object Proxy]"==t}},function(e,t){var n="object"==typeof global&&global&&global.Object===Object&&global;e.exports=n},function(e,t){var n=Function.prototype.toString;e.exports=function(e){if(null!=e){try{return n.call(e)}catch(e){}try{return e+""}catch(e){}}return""}},function(e,t,n){var r=n(31),o=function(){try{var e=r(Object,"defineProperty");return e({},"",{}),e}catch(e){}}();e.exports=o},function(e,t,n){var r=n(267),o=n(107),i=n(12),s=n(108),a=n(68),c=n(153),u=Object.prototype.hasOwnProperty;e.exports=function(e,t){var n=i(e),l=!n&&o(e),f=!n&&!l&&s(e),p=!n&&!l&&!f&&c(e),d=n||l||f||p,h=d?r(e.length,String):[],m=h.length;for(var g in e)!t&&!u.call(e,g)||d&&("length"==g||f&&("offset"==g||"parent"==g)||p&&("buffer"==g||"byteLength"==g||"byteOffset"==g)||a(g,m))||h.push(g);return h}},function(e,t,n){var r=n(270),o=n(37),i=n(69),s=i&&i.isTypedArray,a=s?o(s):r;e.exports=a},function(e,t){e.exports=function(e,t){return function(n){return e(t(n))}}},function(e,t){e.exports=function(){return[]}},function(e,t,n){var r=n(113),o=n(114),i=n(112),s=n(155),a=Object.getOwnPropertySymbols?function(e){for(var t=[];e;)r(t,i(e)),e=o(e);return t}:s;e.exports=a},function(e,t,n){var r=n(158),o=n(112),i=n(49);e.exports=function(e){return r(e,i,o)}},function(e,t,n){var r=n(113),o=n(12);e.exports=function(e,t,n){var i=t(e);return o(e)?i:r(i,n(e))}},function(e,t,n){var r=n(158),o=n(156),i=n(111);e.exports=function(e){return r(e,i,o)}},function(e,t,n){var r=n(31)(n(19),"Set");e.exports=r},function(e,t,n){var r=n(19).Uint8Array;e.exports=r},function(e,t,n){var r=n(50);e.exports=function(e,t,n){var o=null==e?void 0:r(e,t);return void 0===o?n:o}},function(e,t,n){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.findEngineDriver=t.extractShellApiFunctionName=t.extractPackageName=t.extractShellApiPlugins=void 0;const o=r(n(301)),i=r(n(72)),s=r(n(73));t.extractShellApiPlugins=function(e,t){const n=[],r=e.match(/^([^@]+)@([^@]+)/);if(r&&n.push(r[2]),t&&t.connection&&t.connection.engine){const e=t.connection.engine.match(/^([^@]+)@([^@]+)/);e&&n.push(e[2])}return n},t.extractPackageName=function(e){if(!e)return null;const t=e.match(/^([^@]+)@([^@]+)/);return t?t[2]:null},t.extractShellApiFunctionName=function(e){const t=e.match(/^([^@]+)@([^@]+)/);return t?`${(0,o.default)(t[2])}.shellApi.${t[1]}`:`dbgateApi.${e}`},t.findEngineDriver=function(e,t){if((0,i.default)(e))return t.drivers.find(t=>t.engine==e);if((0,s.default)(e)){const{engine:n}=e;if(n)return t.drivers.find(e=>e.engine==n)}return null}},function(e,t){e.exports=function(e,t,n){var r=-1,o=e.length;t<0&&(t=-t>o?0:o+t),(n=n>o?o:n)<0&&(n+=o),o=t>n?0:n-t>>>0,t>>>=0;for(var i=Array(o);++r<o;)i[r]=e[r+t];return i}},function(e,t){var n=RegExp("[\\u200d\\ud800-\\udfff\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff\\ufe0e\\ufe0f]");e.exports=function(e){return n.test(e)}},function(e,t,n){var r=n(323);e.exports=function(e,t){return!!(null==e?0:e.length)&&r(e,t,0)>-1}},function(e,t){e.exports=function(e,t,n){for(var r=-1,o=null==e?0:e.length;++r<o;)if(n(t,e[r]))return!0;return!1}},function(e,t,n){var r=n(74),o=n(169),i=n(170);e.exports=function(e,t){return i(o(e,t,r),e+"")}},function(e,t,n){var r=n(327),o=Math.max;e.exports=function(e,t,n){return t=o(void 0===t?e.length-1:t,0),function(){for(var i=arguments,s=-1,a=o(i.length-t,0),c=Array(a);++s<a;)c[s]=i[t+s];s=-1;for(var u=Array(t+1);++s<t;)u[s]=i[s];return u[t]=n(c),r(e,this,u)}}},function(e,t,n){var r=n(328),o=n(330)(r);e.exports=o},function(e,t,n){var r=n(113),o=n(334);e.exports=function e(t,n,i,s,a){var c=-1,u=t.length;for(i||(i=o),a||(a=[]);++c<u;){var l=t[c];n>0&&i(l)?n>1?e(l,n-1,i,s,a):r(a,l):s||(a[a.length]=l)}return a}},function(e,t,n){var r=n(117),o=n(339),i=n(118);e.exports=function(e,t,n,s,a,c){var u=1&n,l=e.length,f=t.length;if(l!=f&&!(u&&f>l))return!1;var p=c.get(e),d=c.get(t);if(p&&d)return p==t&&d==e;var h=-1,m=!0,g=2&n?new r:void 0;for(c.set(e,t),c.set(t,e);++h<l;){var y=e[h],b=t[h];if(s)var v=u?s(b,y,h,t,e,c):s(y,b,h,e,t,c);if(void 0!==v){if(v)continue;m=!1;break}if(g){if(!o(t,(function(e,t){if(!i(g,t)&&(y===e||a(y,e,n,s,c)))return g.push(t)}))){m=!1;break}}else if(y!==b&&!a(y,b,n,s,c)){m=!1;break}}return c.delete(e),c.delete(t),m}},function(e,t,n){var r=n(28);e.exports=function(e){return e==e&&!r(e)}},function(e,t){e.exports=function(e,t){return function(n){return null!=n&&(n[e]===t&&(void 0!==t||e in Object(n)))}}},function(e,t,n){var r=n(345),o=n(346);e.exports=function(e,t){return null!=e&&o(e,t,r)}},function(e,t,n){var r=n(351),o=n(354)(r);e.exports=o},function(e,t,n){var r=n(363),o=n(178)((function(e,t){return null==e?{}:r(e,t)}));e.exports=o},function(e,t,n){var r=n(123),o=n(169),i=n(170);e.exports=function(e){return i(o(e,void 0,r),e+"")}},function(e,t,n){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.SqlDumper=void 0;const o=r(n(24)),i=r(n(72)),s=r(n(124)),a=r(n(367)),c=r(n(12)),u=r(n(73)),l=r(n(125));t.SqlDumper=class{constructor(e){this.s="",this.indentLevel=0,this.driver=e,this.dialect=e.dialect}endCommand(){this.putRaw(";\n")}putRaw(e){this.s+=e}escapeString(e){const t=this.dialect.stringEscapeChar;let n="";for(let r=0;r<e.length;r++){const o=e[r];o!=t&&"'"!=o||(n+=t),n+=o}return n}putStringValue(e){this.putRaw("'"),this.putRaw(this.escapeString(e)),this.putRaw("'")}putByteArrayValue(e){this.putRaw("NULL")}putValue(e){null===e?this.putRaw("NULL"):!0===e?this.putRaw("1"):!1===e?this.putRaw("0"):(0,i.default)(e)?this.putStringValue(e):(0,s.default)(e)?this.putRaw(e.toString()):(0,a.default)(e)?this.putStringValue(new Date(e).toISOString()):"Buffer"==(null==e?void 0:e.type)&&(0,c.default)(null==e?void 0:e.data)?this.putByteArrayValue(null==e?void 0:e.data):(0,u.default)(e)||(0,c.default)(e)?this.putStringValue(JSON.stringify(e)):this.putRaw("NULL")}putCmd(e,...t){this.put(e,...t),this.endCommand()}putFormattedValue(e,t){switch(e){case"s":null!=t&&this.putRaw(t.toString());break;case"i":this.putRaw(this.dialect.quoteIdentifier(t));break;case"k":t&&this.putRaw(t.toUpperCase());break;case"f":{const{schemaName:e,pureName:n}=t;e&&(this.putRaw(this.dialect.quoteIdentifier(e)),this.putRaw(".")),this.putRaw(this.dialect.quoteIdentifier(n))}break;case"v":this.putValue(t);break;case"c":t(this)}}putFormattedList(e,t){t&&this.putCollection(", ",t,t=>this.putFormattedValue(e,t))}put(e,...t){let n=0,r=0;const o=e.length;for(;n<o;){let i=e[n];switch(n++,i){case"^":for(;n<o&&e[n].match(/[a-z0-9_]/i);)this.putRaw(e[n].toUpperCase()),n++;break;case"%":switch(i=e[n],n++,i){case"%":this.putRaw("%");break;case",":i=e[n],n++,this.putFormattedList(i,t[r]);break;default:this.putFormattedValue(i,t[r])}r++;break;case"&":switch(i=e[n],n++,i){case"&":this.putRaw("&");break;case">":this.indentLevel++;break;case"<":this.indentLevel--;break;case"n":this.putRaw("\n"),this.putRaw(" ".repeat(2*this.indentLevel))}break;default:this.putRaw(i)}}}autoIncrement(){this.put(" ^auto_increment")}specialColumnOptions(e){}columnDefinition(e,{includeDefault:t=!0,includeNullable:n=!0,includeCollate:r=!0}={}){var o;if(e.computedExpression)return this.put("^as %s",e.computedExpression),void(e.isPersisted&&this.put(" ^persisted"));this.put("%k",e.dataType||this.dialect.fallbackDataType),e.autoIncrement&&this.autoIncrement(),this.putRaw(" "),this.specialColumnOptions(e),n&&this.put(e.notNull?"^not ^null":"^null"),t&&(null===(o=e.defaultValue)||void 0===o?void 0:o.trim())&&this.columnDefault(e)}columnDefault(e){null!=e.defaultConstraint?this.put(" ^constraint %i ^default %s ",e.defaultConstraint,e.defaultValue):this.put(" ^default %s ",e.defaultValue)}putCollection(e,t,n){if(!t)return;let r=!0;for(const o of t)r||this.put(e),r=!1,n(o)}createTable(e){this.put("^create ^table %f ( &>&n",e),this.putCollection(",&n",e.columns,e=>{this.put("%i ",e.columnName),this.columnDefinition(e)}),e.primaryKey&&(this.put(",&n"),e.primaryKey.constraintName&&this.put("^constraint %i",e.primaryKey.constraintName),this.put(" ^primary ^key (%,i)",e.primaryKey.columns.map(e=>e.columnName))),(e.foreignKeys||[]).forEach(e=>{this.put(",&n"),this.createForeignKeyFore(e)}),(e.uniques||[]).forEach(e=>{this.put(",&n"),this.createUniqueCore(e)}),(e.checks||[]).forEach(e=>{this.put(",&n"),this.createCheckCore(e)}),this.put("&<&n)"),this.endCommand(),(e.indexes||[]).forEach(e=>{this.createIndex(e)})}createForeignKeyFore(e){null!=e.constraintName&&this.put("^constraint %i ",e.constraintName),this.put("^foreign ^key (%,i) ^references %f (%,i)",e.columns.map(e=>e.columnName),{schemaName:e.refSchemaName,pureName:e.refTableName},e.columns.map(e=>e.refColumnName)),e.deleteAction&&this.put(" ^on ^delete %k",e.deleteAction),e.updateAction&&this.put(" ^on ^update %k",e.updateAction)}transform(e,t){t()}allowIdentityInsert(e,t){}enableConstraints(e,t){}comment(e){if(e)for(const t of e.split("\n"))this.put(" -- %s",t.trimRight())}createView(e){this.putRaw(e.createSql),this.endCommand()}dropView(e,{testIfExists:t=!1}){this.putCmd("^drop ^view %f",e)}alterView(e){this.putRaw(e.createSql.replace(/create\s+view/i,"ALTER VIEW")),this.endCommand()}changeViewSchema(e,t){}renameView(e,t){}createMatview(e){this.putRaw(e.createSql),this.endCommand()}dropMatview(e,{testIfExists:t=!1}){this.putCmd("^drop ^materialized ^view %f",e)}alterMatview(e){this.putRaw(e.createSql.replace(/create\s+view/i,"ALTER VIEW")),this.endCommand()}changeMatviewSchema(e,t){}renameMatview(e,t){}createProcedure(e){this.putRaw(e.createSql),this.endCommand()}dropProcedure(e,{testIfExists:t=!1}){this.putCmd("^drop ^procedure %f",e)}alterProcedure(e){this.putRaw(e.createSql.replace(/create\s+procedure/i,"ALTER PROCEDURE")),this.endCommand()}changeProcedureSchema(e,t){}renameProcedure(e,t){}createFunction(e){this.putRaw(e.createSql),this.endCommand()}dropFunction(e,{testIfExists:t=!1}){this.putCmd("^drop ^function %f",e)}alterFunction(e){this.putRaw(e.createSql.replace(/create\s+function/i,"ALTER FUNCTION")),this.endCommand()}changeFunctionSchema(e,t){}renameFunction(e,t){}createTrigger(e){this.putRaw(e.createSql),this.endCommand()}dropTrigger(e,{testIfExists:t=!1}){this.putCmd("^drop ^trigger %f",e)}alterTrigger(e){this.putRaw(e.createSql.replace(/create\s+trigger/i,"ALTER TRIGGER")),this.endCommand()}changeTriggerSchema(e,t){}renameTrigger(e,t){}dropConstraintCore(e){this.putCmd("^alter ^table %f ^drop ^constraint %i",e,e.constraintName)}dropConstraint(e){switch(e.constraintType){case"primaryKey":this.dropPrimaryKey(e);break;case"foreignKey":this.dropForeignKey(e);break;case"unique":this.dropUnique(e);break;case"check":this.dropCheck(e);break;case"index":this.dropIndex(e)}}createConstraint(e){switch(e.constraintType){case"primaryKey":this.createPrimaryKey(e);break;case"foreignKey":this.createForeignKey(e);break;case"unique":this.createUnique(e);break;case"check":this.createCheck(e);break;case"index":this.createIndex(e)}}changeConstraint(e,t){}dropForeignKey(e){this.dialect.explicitDropConstraint?this.putCmd("^alter ^table %f ^drop ^foreign ^key %i",e,e.constraintName):this.dropConstraintCore(e)}createForeignKey(e){this.put("^alter ^table %f ^add ",e),this.createForeignKeyFore(e),this.endCommand()}dropPrimaryKey(e){this.dialect.explicitDropConstraint?this.putCmd("^alter ^table %f ^drop ^primary ^key",e):this.dropConstraintCore(e)}createPrimaryKey(e){this.putCmd("^alter ^table %f ^add ^constraint %i ^primary ^key (%,i)",e,e.constraintName,e.columns.map(e=>e.columnName))}dropIndex(e){this.put("^drop ^index %i",e.constraintName),this.dialect.dropIndexContainsTableSpec&&this.put(" ^on %f",e),this.endCommand()}createIndex(e){this.put("^create"),e.isUnique&&this.put(" ^unique"),this.put(" ^index %i &n^on %f (&>&n",e.constraintName,e),this.putCollection(",&n",e.columns,e=>{this.put("%i %k",e.columnName,1==e.isDescending?"DESC":"ASC")}),this.put("&<&n)"),this.endCommand()}dropUnique(e){this.dropConstraintCore(e)}createUniqueCore(e){this.put("^constraint %i ^unique (%,i)",e.constraintName,e.columns.map(e=>e.columnName))}createUnique(e){this.put("^alter ^table %f ^add ",e),this.createUniqueCore(e),this.endCommand()}dropCheck(e){this.dropConstraintCore(e)}createCheckCore(e){this.put("^constraint %i ^check (%s)",e.constraintName,e.definition)}createCheck(e){this.put("^alter ^table %f ^add ",e),this.createCheckCore(e),this.endCommand()}renameConstraint(e,t){}createColumn(e,t){this.put("^alter ^table %f ^add %i ",e,e.columnName),this.columnDefinition(e),this.inlineConstraints(t),this.endCommand()}inlineConstraints(e){if(null!=e)for(const t of e)"primaryKey"==t.constraintType&&(null==t.constraintName||this.dialect.anonymousPrimaryKey||this.put(" ^constraint %i",t.constraintName),this.put(" ^primary ^key "))}dropColumn(e){this.putCmd("^alter ^table %f ^drop ^column %i",e,e.columnName)}renameColumn(e,t){}changeColumn(e,t,n){}dropTable(e,{testIfExists:t=!1}={}){this.putCmd("^drop ^table %f",e)}changeTableSchema(e,t){}renameTable(e,t){}beginTransaction(){this.putCmd("^begin ^transaction")}commitTransaction(){this.putCmd("^commit")}alterProlog(){}alterEpilog(){}selectTableIntoNewTable(e,t){this.putCmd("^select * ^into %f ^from %f",t,e)}truncateTable(e){this.putCmd("^delete ^from %f",e)}dropConstraints(e,t=!1){t&&this.dialect.dropForeignKey&&e.dependencies.forEach(e=>this.dropConstraint(e)),this.dialect.dropIndex&&e.indexes.forEach(e=>this.dropIndex(e)),this.dialect.dropForeignKey&&e.foreignKeys.forEach(e=>this.dropForeignKey(e)),this.dialect.dropPrimaryKey&&e.primaryKey&&this.dropPrimaryKey(e.primaryKey)}recreateTable(e,t){if(!e.pairingId||!t.pairingId||e.pairingId!=t.pairingId)throw new Error("Recreate is not possible: oldTable.paringId != newTable.paringId");const n=`temp_${(0,l.default)()}`,r=e.columns.map(e=>({oldcol:e,newcol:t.columns.find(t=>t.pairingId==e.pairingId)})).filter(e=>e.newcol);this.dropConstraints(e,!0),this.renameTable(e,n),this.createTable(t);const o=t.columns.find(e=>e.autoIncrement);o&&this.allowIdentityInsert(t,!0),this.putCmd("^insert ^into %f (%,i) select %,s ^from %f",t,r.map(e=>e.newcol.columnName),r.map(e=>e.oldcol.columnName),Object.assign(Object.assign({},e),{pureName:n})),o&&this.allowIdentityInsert(t,!1),this.dialect.dropForeignKey&&t.dependencies.forEach(e=>this.createConstraint(e)),this.dropTable(Object.assign(Object.assign({},e),{pureName:n}))}createSqlObject(e){this.putCmd(e.createSql)}getSqlObjectSqlName(e){switch(e){case"procedures":return"PROCEDURE";case"views":return"VIEW";case"functions":return"FUNCTION";case"triggers":return"TRIGGER";case"matviews":return"MATERIALIZED VIEW"}}dropSqlObject(e){this.putCmd("^drop %s %f",this.getSqlObjectSqlName(e.objectTypeField),e)}fillPreloadedRows(e,t,n,r,i){let s=!1;for(const a of n){const n=null==t?void 0:t.find(e=>r.every(t=>e[t]==a[t])),c=o.default.keys(a);if(n){const t=[];for(const e of c)a[e]==n[e]||(null==i?void 0:i.includes(e))||t.push(e);t.length>0&&(s&&this.put(";\n"),s=!0,this.put("^update %f ^set ",e),this.putCollection(", ",t,e=>this.put("%i=%v",e,a[e])),this.put(" ^where "),this.putCollection(" ^and ",r,e=>this.put("%i=%v",e,a[e])))}else s&&this.put(";\n"),s=!0,this.put("^insert ^into %f (%,i) ^values (%,v)",e,c,c.map(e=>a[e]))}s&&this.endCommand()}}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dumpSqlExpression=void 0;const r=n(126);t.dumpSqlExpression=function e(t,n){switch(n.exprType){case"column":n.source&&(0,r.dumpSqlSourceRef)(t,n.source)&&t.put("."),t.put("%i",n.columnName);break;case"placeholder":t.putRaw("{PLACEHOLDER}");break;case"value":t.put("%v",n.value);break;case"raw":t.put("%s",n.sql);break;case"call":t.put("%s(",n.func),n.argsPrefix&&t.put("%s ",n.argsPrefix),t.putCollection(",",n.args,n=>e(t,n)),t.put(")");break;case"transform":t.transform(n.transform,()=>e(t,n.expr));break;case"rowNumber":t.put(" ^row_number() ^over (^order ^by "),t.putCollection(", ",n.orderBy,n=>{e(t,n),t.put(" %k",n.direction)}),t.put(")")}}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.evaluateExpression=void 0,t.evaluateExpression=function(e,t){switch(e.exprType){case"column":return t[e.columnName];case"placeholder":return t.__placeholder;case"value":return e.value;case"raw":return e.sql;case"call":case"transform":return null}}},function(e,t,n){var r=n(117),o=n(166),i=n(167),s=n(118),a=n(381),c=n(122);e.exports=function(e,t,n){var u=-1,l=o,f=e.length,p=!0,d=[],h=d;if(n)p=!1,l=i;else if(f>=200){var m=t?null:a(e);if(m)return c(m);p=!1,l=s,h=new r}else h=t?[]:d;e:for(;++u<f;){var g=e[u],y=t?t(g):g;if(g=n||0!==g?g:0,p&&y==y){for(var b=h.length;b--;)if(h[b]===y)continue e;t&&h.push(y),d.push(g)}else l(h,y,n)||(h!==d&&h.push(y),d.push(g))}return d}},function(e,t,n){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isTableColumnUnique=t.extendDatabaseInfoFromApps=t.extendDatabaseInfo=t.extendTableInfo=t.addTableDependencies=void 0;const o=r(n(123));function i(e){const t=(0,o.default)(e.tables.map(e=>e.foreignKeys||[]));return Object.assign(Object.assign({},e),{tables:e.tables.map(e=>Object.assign(Object.assign({},e),{dependencies:t.filter(t=>t.refSchemaName==e.schemaName&&t.refTableName==e.pureName)}))})}function s(e){return Object.assign(Object.assign({},e),{objectTypeField:"tables",columns:(e.columns||[]).map(t=>Object.assign({pureName:e.pureName,schemaName:e.schemaName},t)),primaryKey:e.primaryKey?Object.assign(Object.assign({},e.primaryKey),{pureName:e.pureName,schemaName:e.schemaName,constraintType:"primaryKey"}):void 0,foreignKeys:(e.foreignKeys||[]).map(t=>Object.assign(Object.assign({},t),{pureName:e.pureName,schemaName:e.schemaName,constraintType:"foreignKey"})),indexes:(e.indexes||[]).map(t=>Object.assign(Object.assign({},t),{pureName:e.pureName,schemaName:e.schemaName,constraintType:"index"})),checks:(e.checks||[]).map(t=>Object.assign(Object.assign({},t),{pureName:e.pureName,schemaName:e.schemaName,constraintType:"check"})),uniques:(e.uniques||[]).map(t=>Object.assign(Object.assign({},t),{pureName:e.pureName,schemaName:e.schemaName,constraintType:"unique"}))})}t.addTableDependencies=i,t.extendTableInfo=s,t.extendDatabaseInfo=function(e){return function(e){return Object.assign(Object.assign({},e),{tables:(e.tables||[]).map(s),collections:(e.collections||[]).map(e=>Object.assign(Object.assign({},e),{objectTypeField:"collections"})),views:(e.views||[]).map(e=>Object.assign(Object.assign({},e),{objectTypeField:"views"})),matviews:(e.matviews||[]).map(e=>Object.assign(Object.assign({},e),{objectTypeField:"matviews"})),procedures:(e.procedures||[]).map(e=>Object.assign(Object.assign({},e),{objectTypeField:"procedures"})),functions:(e.functions||[]).map(e=>Object.assign(Object.assign({},e),{objectTypeField:"functions"})),triggers:(e.triggers||[]).map(e=>Object.assign(Object.assign({},e),{objectTypeField:"triggers"}))})}(i(e))},t.extendDatabaseInfoFromApps=function(e,t){return e&&t?i(Object.assign(Object.assign({},e),{tables:e.tables.map(e=>Object.assign(Object.assign({},e),{foreignKeys:[...e.foreignKeys||[],...(0,o.default)(t.map(e=>e.virtualReferences||[])).filter(t=>t.pureName==e.pureName&&t.schemaName==e.schemaName).map(e=>Object.assign(Object.assign({},e),{constraintType:"foreignKey",isVirtual:!0}))]}))})):e},t.isTableColumnUnique=function(e,t){return!(!e.primaryKey||1!=e.primaryKey.columns.length||e.primaryKey.columns[0].columnName!=t)||!![...e.uniques||[],...(e.indexes||[]).filter(e=>e.isUnique)].find(e=>1==e.columns.length&&e.columns[0].columnName==t)}},function(e,t,n){var r=n(51),o=n(147),i=n(392),s=n(39),a=n(48),c=n(395),u=n(178),l=n(159),f=u((function(e,t){var n={};if(null==e)return n;var u=!1;t=r(t,(function(t){return t=s(t,e),u||(u=t.length>1),t})),a(e,l(e),n),u&&(n=o(n,7,c));for(var f=t.length;f--;)i(n,t[f]);return n}));e.exports=f},function(e,t,n){var r=n(404),o=n(53),i=n(81),s=n(85),a=n(82),c=n(76),u=n(130),l=n(43),f=n(129),p=n(84),d=n(83),h=n(78),m=n(79),g=n(80),y=n(77);r.BSON_INT32_MAX=2147483647,r.BSON_INT32_MIN=-2147483648,r.BSON_INT64_MAX=Math.pow(2,63)-1,r.BSON_INT64_MIN=-Math.pow(2,63),r.JS_INT_MAX=9007199254740992,r.JS_INT_MIN=-9007199254740992,r.Binary=o,r.Code=i,r.DBRef=s,r.Decimal128=a,r.Double=c,r.Int32=u,r.Long=l,r.Map=f,r.MaxKey=p,r.MinKey=d,r.ObjectId=h,r.ObjectID=h,r.BSONRegExp=m,r.Symbol=g,r.Timestamp=y,e.exports=r},function(e,t){function n(e){var t=new Error("Cannot find module '"+e+"'");throw t.code="MODULE_NOT_FOUND",t}n.keys=function(){return[]},n.resolve=n,e.exports=n,n.id=186},function(e,t,n){"use strict";const r=n(8).EventEmitter,o=n(20),i=n(9).debugOptions,s=n(6).parseHeader,a=n(30).decompress,c=n(21).Response,u=n(45).BinMsg,l=n(3).MongoNetworkError,f=n(3).MongoNetworkTimeoutError,p=n(3).MongoError,d=n(16),h=n(6).opcodes.OP_COMPRESSED,m=n(6).opcodes.OP_MSG,g=n(6).MESSAGE_HEADER_SIZE,y=n(22).Buffer,b=n(21).Query,v=n(133);let S=0;const w=["host","port","size","keepAlive","keepAliveInitialDelay","noDelay","connectionTimeout","socketTimeout","ssl","ca","crl","cert","rejectUnauthorized","promoteLongs","promoteValues","promoteBuffers","checkServerIdentity"];let _=void 0,O=!1,T={};const C=["error","close","timeout","parseError"];function x(e){delete T[e],_&&_.deleteConnection(e)}function E(e,t){const n=s(t);if(n.opCode!==h){const r=n.opCode===m?u:c;return void e.emit("message",new r(e.bson,t,n,t.slice(g),e.responseOptions),e)}n.fromCompressed=!0;let r=g;n.opCode=t.readInt32LE(r),r+=4,n.length=t.readInt32LE(r),r+=4;const o=t[r];r++,a(o,t.slice(r),(r,o)=>{if(r)return void e.emit("error",r);if(o.length!==n.length)return void e.emit("error",new p("Decompressing a compressed message from the server failed. The message is corrupt."));const i=n.opCode===m?u:c;e.emit("message",new i(e.bson,t,n,o,e.responseOptions),e)})}e.exports=class extends r{constructor(e,t){if(super(),!(t=t||{}).bson)throw new TypeError("must pass in valid bson parser");this.id=S++,this.options=t,this.logger=d("Connection",t),this.bson=t.bson,this.tag=t.tag,this.maxBsonMessageSize=t.maxBsonMessageSize||67108864,this.port=t.port||27017,this.host=t.host||"localhost",this.socketTimeout="number"==typeof t.socketTimeout?t.socketTimeout:0,this.keepAlive="boolean"!=typeof t.keepAlive||t.keepAlive,this.keepAliveInitialDelay="number"==typeof t.keepAliveInitialDelay?t.keepAliveInitialDelay:12e4,this.connectionTimeout="number"==typeof t.connectionTimeout?t.connectionTimeout:3e4,this.keepAliveInitialDelay>this.socketTimeout&&(this.keepAliveInitialDelay=Math.round(this.socketTimeout/2)),this.logger.isDebug()&&this.logger.debug(`creating connection ${this.id} with options [${JSON.stringify(i(w,t))}]`),this.responseOptions={promoteLongs:"boolean"!=typeof t.promoteLongs||t.promoteLongs,promoteValues:"boolean"!=typeof t.promoteValues||t.promoteValues,promoteBuffers:"boolean"==typeof t.promoteBuffers&&t.promoteBuffers},this.flushing=!1,this.queue=[],this.writeStream=null,this.destroyed=!1,this.timedOut=!1;const n=o.createHash("sha1");var r,s,a;n.update(this.address),this.hashedName=n.digest("hex"),this.workItems=[],this.socket=e,this.socket.once("error",(r=this,function(e){O&&x(r.id),r.logger.isDebug()&&r.logger.debug(`connection ${r.id} for [${r.address}] errored out with [${JSON.stringify(e)}]`),r.emit("error",new l(e),r)})),this.socket.once("timeout",function(e){return function(){O&&x(e.id),e.logger.isDebug()&&e.logger.debug(`connection ${e.id} for [${e.address}] timed out`),e.timedOut=!0,e.emit("timeout",new f(`connection ${e.id} to ${e.address} timed out`,{beforeHandshake:null==e.ismaster}),e)}}(this)),this.socket.once("close",function(e){return function(t){O&&x(e.id),e.logger.isDebug()&&e.logger.debug(`connection ${e.id} with for [${e.address}] closed`),t||e.emit("close",new l(`connection ${e.id} to ${e.address} closed`),e)}}(this)),this.socket.on("data",function(e){return function(t){for(;t.length>0;)if(e.bytesRead>0&&e.sizeOfMessage>0){const n=e.sizeOfMessage-e.bytesRead;if(n>t.length)t.copy(e.buffer,e.bytesRead),e.bytesRead=e.bytesRead+t.length,t=y.alloc(0);else{t.copy(e.buffer,e.bytesRead,0,n),t=t.slice(n);const r=e.buffer;e.buffer=null,e.sizeOfMessage=0,e.bytesRead=0,e.stubBuffer=null,E(e,r)}}else if(null!=e.stubBuffer&&e.stubBuffer.length>0)if(e.stubBuffer.length+t.length>4){const n=y.alloc(e.stubBuffer.length+t.length);e.stubBuffer.copy(n,0),t.copy(n,e.stubBuffer.length),t=n,e.buffer=null,e.sizeOfMessage=0,e.bytesRead=0,e.stubBuffer=null}else{const n=y.alloc(e.stubBuffer.length+t.length);e.stubBuffer.copy(n,0),t.copy(n,e.stubBuffer.length),t=y.alloc(0)}else if(t.length>4){const n=t[0]|t[1]<<8|t[2]<<16|t[3]<<24;if(n<0||n>e.maxBsonMessageSize){const t={err:"socketHandler",trace:"",bin:e.buffer,parseState:{sizeOfMessage:n,bytesRead:e.bytesRead,stubBuffer:e.stubBuffer}};return void e.emit("parseError",t,e)}if(n>4&&n<e.maxBsonMessageSize&&n>t.length)e.buffer=y.alloc(n),t.copy(e.buffer,0),e.bytesRead=t.length,e.sizeOfMessage=n,e.stubBuffer=null,t=y.alloc(0);else if(n>4&&n<e.maxBsonMessageSize&&n===t.length){const n=t;e.buffer=null,e.sizeOfMessage=0,e.bytesRead=0,e.stubBuffer=null,t=y.alloc(0),E(e,n)}else if(n<=4||n>e.maxBsonMessageSize){const r={err:"socketHandler",trace:null,bin:t,parseState:{sizeOfMessage:n,bytesRead:0,buffer:null,stubBuffer:null}};e.emit("parseError",r,e),e.buffer=null,e.sizeOfMessage=0,e.bytesRead=0,e.stubBuffer=null,t=y.alloc(0)}else{const r=t.slice(0,n);e.buffer=null,e.sizeOfMessage=0,e.bytesRead=0,e.stubBuffer=null,t=t.slice(n),E(e,r)}}else e.stubBuffer=y.alloc(t.length),t.copy(e.stubBuffer,0),t=y.alloc(0)}}(this)),O&&(s=this.id,a=this,T[s]=a,_&&_.addConnection(s,a))}setSocketTimeout(e){this.socket&&this.socket.setTimeout(e)}resetSocketTimeout(){this.socket&&this.socket.setTimeout(this.socketTimeout)}static enableConnectionAccounting(e){e&&(_=e),O=!0,T={}}static disableConnectionAccounting(){O=!1,_=void 0}static connections(){return T}get address(){return`${this.host}:${this.port}`}unref(){null!=this.socket?this.socket.unref():this.once("connect",()=>this.socket.unref())}flush(e){for(;this.workItems.length>0;){const t=this.workItems.shift();t.cb&&t.cb(e)}}destroy(e,t){if("function"==typeof e&&(t=e,e={}),e=Object.assign({force:!1},e),O&&x(this.id),null!=this.socket)return e.force||this.timedOut?(this.socket.destroy(),this.destroyed=!0,void("function"==typeof t&&t(null,null))):void this.socket.end(e=>{this.destroyed=!0,"function"==typeof t&&t(e,null)});this.destroyed=!0}write(e){if(this.logger.isDebug())if(Array.isArray(e))for(let t=0;t<e.length;t++)this.logger.debug(`writing buffer [${e[t].toString("hex")}] to ${this.address}`);else this.logger.debug(`writing buffer [${e.toString("hex")}] to ${this.address}`);if(!1===this.socket.destroyed){if(!Array.isArray(e))return this.socket.write(e,"binary"),!0;for(let t=0;t<e.length;t++)this.socket.write(e[t],"binary");return!0}return!1}toString(){return""+this.id}toJSON(){return{id:this.id,host:this.host,port:this.port}}isConnected(){return!this.destroyed&&(!this.socket.destroyed&&this.socket.writable)}command(e,t,n,r){"function"==typeof n&&(r=n,n={});const o=this,i="number"==typeof n.socketTimeout?n.socketTimeout:0,s=o.options.bson,a=new b(s,e,t,{numberToSkip:0,numberToReturn:1}),c=()=>{};function u(e,t){r(e,t),r=c}function l(e){o.resetSocketTimeout(),C.forEach(e=>o.removeListener(e,l)),o.removeListener("message",f),null==e&&(e=new p(`runCommand failed for connection to '${o.address}'`)),o.on("error",c),u(e)}function f(e){if(e.responseTo!==a.requestId)return;o.resetSocketTimeout(),C.forEach(e=>o.removeListener(e,l)),o.removeListener("message",f),e.parse({promoteValues:!0});const t=e.documents[0];0===t.ok||t.$err||t.errmsg||t.code?u(new p(t)):u(void 0,new v(t,this,e))}o.setSocketTimeout(i),C.forEach(e=>o.once(e,l)),o.on("message",f),o.write(a.toBin())}}},function(e,t,n){"use strict";t.asyncIterator=function(){const e=this;return{next:function(){return Promise.resolve().then(()=>e.next()).then(t=>t?{value:t,done:!1}:e.close().then(()=>({value:t,done:!0})))}}}},function(e,t,n){"use strict";const r=n(13).ServerType,o=n(44).ServerDescription,i=n(190),s=n(13).TopologyType,a=i.MIN_SUPPORTED_SERVER_VERSION,c=i.MAX_SUPPORTED_SERVER_VERSION,u=i.MIN_SUPPORTED_WIRE_VERSION,l=i.MAX_SUPPORTED_WIRE_VERSION;class f{constructor(e,t,n,o,i,f,p){p=p||{},this.type=e||s.Unknown,this.setName=n||null,this.maxSetVersion=o||null,this.maxElectionId=i||null,this.servers=t||new Map,this.stale=!1,this.compatible=!0,this.compatibilityError=null,this.logicalSessionTimeoutMinutes=null,this.heartbeatFrequencyMS=p.heartbeatFrequencyMS||0,this.localThresholdMS=p.localThresholdMS||0,this.commonWireVersion=f||null,Object.defineProperty(this,"options",{value:p,enumberable:!1});for(const e of this.servers.values())if(e.type!==r.Unknown&&(e.minWireVersion>l&&(this.compatible=!1,this.compatibilityError=`Server at ${e.address} requires wire version ${e.minWireVersion}, but this version of the driver only supports up to ${l} (MongoDB ${c})`),e.maxWireVersion<u)){this.compatible=!1,this.compatibilityError=`Server at ${e.address} reports wire version ${e.maxWireVersion}, but this version of the driver requires at least ${u} (MongoDB ${a}).`;break}this.logicalSessionTimeoutMinutes=null;for(const e of this.servers){const t=e[1];if(t.isReadable){if(null==t.logicalSessionTimeoutMinutes){this.logicalSessionTimeoutMinutes=null;break}if(null==this.logicalSessionTimeoutMinutes){this.logicalSessionTimeoutMinutes=t.logicalSessionTimeoutMinutes;continue}this.logicalSessionTimeoutMinutes=Math.min(this.logicalSessionTimeoutMinutes,t.logicalSessionTimeoutMinutes)}}}updateFromSrvPollingEvent(e){const t=e.addresses(),n=new Map(this.servers);for(const e of this.servers)t.has(e[0])?t.delete(e[0]):n.delete(e[0]);if(n.size===this.servers.size&&0===t.size)return this;for(const e of t)n.set(e,new o(e));return new f(this.type,n,this.setName,this.maxSetVersion,this.maxElectionId,this.commonWireVersion,this.options,null)}update(e){const t=e.address;let n=this.type,i=this.setName,a=this.maxSetVersion,c=this.maxElectionId,u=this.commonWireVersion;e.setName&&i&&e.setName!==i&&(e=new o(t,null));const l=e.type;let h=new Map(this.servers);if(0!==e.maxWireVersion&&(u=null==u?e.maxWireVersion:Math.min(u,e.maxWireVersion)),h.set(t,e),n===s.Single)return new f(s.Single,h,i,a,c,u,this.options);if(n===s.Unknown&&(l===r.Standalone&&1!==this.servers.size?h.delete(t):n=function(e){if(e===r.Standalone)return s.Single;if(e===r.Mongos)return s.Sharded;if(e===r.RSPrimary)return s.ReplicaSetWithPrimary;if(e===r.RSGhost||e===r.Unknown)return s.Unknown;return s.ReplicaSetNoPrimary}(l)),n===s.Sharded&&-1===[r.Mongos,r.Unknown].indexOf(l)&&h.delete(t),n===s.ReplicaSetNoPrimary)if([r.Standalone,r.Mongos].indexOf(l)>=0&&h.delete(t),l===r.RSPrimary){const t=p(h,i,e,a,c);n=t[0],i=t[1],a=t[2],c=t[3]}else if([r.RSSecondary,r.RSArbiter,r.RSOther].indexOf(l)>=0){const t=function(e,t,n){let r=s.ReplicaSetNoPrimary;if((t=t||n.setName)!==n.setName)return e.delete(n.address),[r,t];n.allHosts.forEach(t=>{e.has(t)||e.set(t,new o(t))}),n.me&&n.address!==n.me&&e.delete(n.address);return[r,t]}(h,i,e);n=t[0],i=t[1]}if(n===s.ReplicaSetWithPrimary)if([r.Standalone,r.Mongos].indexOf(l)>=0)h.delete(t),n=d(h);else if(l===r.RSPrimary){const t=p(h,i,e,a,c);n=t[0],i=t[1],a=t[2],c=t[3]}else n=[r.RSSecondary,r.RSArbiter,r.RSOther].indexOf(l)>=0?function(e,t,n){if(null==t)throw new TypeError("setName is required");(t!==n.setName||n.me&&n.address!==n.me)&&e.delete(n.address);return d(e)}(h,i,e):d(h);return new f(n,h,i,a,c,u,this.options)}get error(){const e=Array.from(this.servers.values()).filter(e=>e.error);if(e.length>0)return e[0].error}get hasKnownServers(){return Array.from(this.servers.values()).some(e=>e.type!==r.Unknown)}get hasDataBearingServers(){return Array.from(this.servers.values()).some(e=>e.isDataBearing)}hasServer(e){return this.servers.has(e)}}function p(e,t,n,i,s){if((t=t||n.setName)!==n.setName)return e.delete(n.address),[d(e),t,i,s];const a=n.electionId?n.electionId:null;if(n.setVersion&&a){if(i&&s&&(i>n.setVersion||function(e,t){if(null==e)return-1;if(null==t)return 1;if(e.id instanceof Buffer&&t.id instanceof Buffer){const n=e.id,r=t.id;return n.compare(r)}const n=e.toString(),r=t.toString();return n.localeCompare(r)}(s,a)>0))return e.set(n.address,new o(n.address)),[d(e),t,i,s];s=n.electionId}null!=n.setVersion&&(null==i||n.setVersion>i)&&(i=n.setVersion);for(const t of e.keys()){const i=e.get(t);if(i.type===r.RSPrimary&&i.address!==n.address){e.set(t,new o(i.address));break}}n.allHosts.forEach(t=>{e.has(t)||e.set(t,new o(t))});const c=Array.from(e.keys()),u=n.allHosts;return c.filter(e=>-1===u.indexOf(e)).forEach(t=>{e.delete(t)}),[d(e),t,i,s]}function d(e){for(const t of e.keys())if(e.get(t).type===r.RSPrimary)return s.ReplicaSetWithPrimary;return s.ReplicaSetNoPrimary}e.exports={TopologyDescription:f}},function(e,t,n){"use strict";e.exports={MIN_SUPPORTED_SERVER_VERSION:"2.6",MAX_SUPPORTED_SERVER_VERSION:"4.4",MIN_SUPPORTED_WIRE_VERSION:2,MAX_SUPPORTED_WIRE_VERSION:9}},function(e,t,n){"use strict";const r=n(45).Msg,o=n(21).KillCursor,i=n(21).GetMore,s=n(0).calculateDurationInMs,a=new Set(["authenticate","saslStart","saslContinue","getnonce","createUser","updateUser","copydbgetnonce","copydbsaslstart","copydb"]),c=e=>Object.keys(e)[0],u=e=>e.ns,l=e=>e.ns.split(".")[0],f=e=>e.ns.split(".")[1],p=e=>e.options?`${e.options.host}:${e.options.port}`:e.address,d=(e,t)=>a.has(e)?{}:t,h={$query:"filter",$orderby:"sort",$hint:"hint",$comment:"comment",$maxScan:"maxScan",$max:"max",$min:"min",$returnKey:"returnKey",$showDiskLoc:"showRecordId",$maxTimeMS:"maxTimeMS",$snapshot:"snapshot"},m={numberToSkip:"skip",numberToReturn:"batchSize",returnFieldsSelector:"projection"},g=["tailable","oplogReplay","noCursorTimeout","awaitData","partial","exhaust"],y=e=>{if(e instanceof i)return{getMore:e.cursorId,collection:f(e),batchSize:e.numberToReturn};if(e instanceof o)return{killCursors:f(e),cursors:e.cursorIds};if(e instanceof r)return e.command;if(e.query&&e.query.$query){let t;return"admin.$cmd"===e.ns?t=Object.assign({},e.query.$query):(t={find:f(e)},Object.keys(h).forEach(n=>{void 0!==e.query[n]&&(t[h[n]]=e.query[n])})),Object.keys(m).forEach(n=>{void 0!==e[n]&&(t[m[n]]=e[n])}),g.forEach(n=>{e[n]&&(t[n]=e[n])}),void 0!==e.pre32Limit&&(t.limit=e.pre32Limit),e.query.$explain?{explain:t}:t}return e.query?e.query:e},b=(e,t)=>e instanceof i?{ok:1,cursor:{id:t.message.cursorId,ns:u(e),nextBatch:t.message.documents}}:e instanceof o?{ok:1,cursorsUnknown:e.cursorIds}:e.query&&void 0!==e.query.$query?{ok:1,cursor:{id:t.message.cursorId,ns:u(e),firstBatch:t.message.documents}}:t&&t.result?t.result:t,v=e=>{if((e=>e.s&&e.queue)(e))return{connectionId:p(e)};const t=e;return{address:t.address,connectionId:t.id}};e.exports={CommandStartedEvent:class{constructor(e,t){const n=y(t),r=c(n),o=v(e);a.has(r)&&(this.commandObj={},this.commandObj[r]=!0),Object.assign(this,o,{requestId:t.requestId,databaseName:l(t),commandName:r,command:n})}},CommandSucceededEvent:class{constructor(e,t,n,r){const o=y(t),i=c(o),a=v(e);Object.assign(this,a,{requestId:t.requestId,commandName:i,duration:s(r),reply:d(i,b(t,n))})}},CommandFailedEvent:class{constructor(e,t,n,r){const o=y(t),i=c(o),a=v(e);Object.assign(this,a,{requestId:t.requestId,commandName:i,duration:s(r),failure:d(i,n)})}}}},function(e,t){e.exports=require("tls")},function(e,t,n){"use strict";const r=n(194),o=n(195),i=n(196),s=n(197),a=n(87).ScramSHA1,c=n(87).ScramSHA256,u=n(420);e.exports={defaultAuthProviders:function(e){return{"mongodb-aws":new u(e),mongocr:new r(e),x509:new o(e),plain:new i(e),gssapi:new s(e),"scram-sha-1":new a(e),"scram-sha-256":new c(e)}}}},function(e,t,n){"use strict";const r=n(20),o=n(33).AuthProvider;e.exports=class extends o{auth(e,t){const n=e.connection,o=e.credentials,i=o.username,s=o.password,a=o.source;n.command(`${a}.$cmd`,{getnonce:1},(e,o)=>{let c=null,u=null;if(null==e){c=o.result.nonce;let e=r.createHash("md5");e.update(i+":mongo:"+s,"utf8");const t=e.digest("hex");e=r.createHash("md5"),e.update(c+i+t,"utf8"),u=e.digest("hex")}const l={authenticate:1,user:i,nonce:c,key:u};n.command(`${a}.$cmd`,l,t)})}}},function(e,t,n){"use strict";const r=n(33).AuthProvider;function o(e){const t={authenticate:1,mechanism:"MONGODB-X509"};return e.username&&Object.assign(t,{user:e.username}),t}e.exports=class extends r{prepare(e,t,n){const r=t.credentials;Object.assign(e,{speculativeAuthenticate:o(r)}),n(void 0,e)}auth(e,t){const n=e.connection,r=e.credentials;if(e.response.speculativeAuthenticate)return t();n.command("$external.$cmd",o(r),t)}}},function(e,t,n){"use strict";const r=n(9).retrieveBSON,o=n(33).AuthProvider,i=r().Binary;e.exports=class extends o{auth(e,t){const n=e.connection,r=e.credentials,o=r.username,s=r.password,a={saslStart:1,mechanism:"PLAIN",payload:new i(`\0${o}\0${s}`),autoAuthorize:1};n.command("$external.$cmd",a,t)}}},function(e,t,n){"use strict";const r=n(86),o=n(33).AuthProvider,i=n(4).retrieveKerberos,s=n(3).MongoError;let a;e.exports=class extends o{auth(e,t){const n=e.connection,o=e.credentials;if(null==o)return t(new s("credentials required"));const c=o.username;function u(e,t){return n.command("$external.$cmd",e,t)}!function(e,t){const n=e.options.host,o=e.options.port,c=e.credentials;if(!n||!o||!c)return t(new s(`Connection must specify: ${n?"host":""}, ${o?"port":""}, ${c?"host":"credentials"}.`));if(null==a)try{a=i()}catch(e){return t(e)}const u=c.username,l=c.password,f=c.mechanismProperties,p=f.gssapiservicename||f.gssapiServiceName||"mongodb";!function(e,t,n){if("boolean"!=typeof t.gssapiCanonicalizeHostName||!t.gssapiCanonicalizeHostName)return n(void 0,e);r.resolveCname(e,(t,r)=>t?n(t):Array.isArray(r)&&r.length>0?n(void 0,r[0]):void n(void 0,e))}(n,f,(e,n)=>{if(e)return t(e);const r={};null!=l&&Object.assign(r,{user:u,password:l}),a.initializeClient(`${p}${"win32"===process.platform?"/":"@"}${n}`,r,(e,n)=>{if(e)return t(new s(e));t(null,n)})})}(e,(e,n)=>e?t(e):null==n?t(new s("gssapi client missing")):void n.step("",(e,r)=>{if(e)return t(e);u(function(e){return{saslStart:1,mechanism:"GSSAPI",payload:e,autoAuthorize:1}}(r),(e,r)=>{if(e)return t(e);const o=r.result;!function e(t,n,r,o){t.step(r,(i,s)=>i&&0===n?o(i):i?e(t,n-1,r,o):void o(void 0,s||""))}(n,10,o.payload,(e,r)=>{if(e)return t(e);u(function(e,t){return{saslContinue:1,conversationId:t,payload:e}}(r,o.conversationId),(e,r)=>{if(e)return t(e);const o=r.result;!function(e,t,n,r){e.unwrap(n,(n,o)=>{if(n)return r(n);e.wrap(o||"",{user:t},(e,t)=>{if(e)return r(e);r(void 0,t)})})}(n,c,o.payload,(e,n)=>{if(e)return t(e);u({saslContinue:1,conversationId:o.conversationId,payload:n},(e,n)=>{if(e)return t(e);t(void 0,n)})})})})})}))}}},function(e,t,n){"use strict";function r(e){if(e){if(Array.isArray(e.saslSupportedMechs))return e.saslSupportedMechs.indexOf("SCRAM-SHA-256")>=0?"scram-sha-256":"scram-sha-1";if(e.maxWireVersion>=3)return"scram-sha-1"}return"mongocr"}class o{constructor(e){e=e||{},this.username=e.username,this.password=e.password,this.source=e.source||e.db,this.mechanism=e.mechanism||"default",this.mechanismProperties=e.mechanismProperties||{},this.mechanism.match(/MONGODB-AWS/i)&&(null==this.username&&process.env.AWS_ACCESS_KEY_ID&&(this.username=process.env.AWS_ACCESS_KEY_ID),null==this.password&&process.env.AWS_SECRET_ACCESS_KEY&&(this.password=process.env.AWS_SECRET_ACCESS_KEY),null==this.mechanismProperties.AWS_SESSION_TOKEN&&process.env.AWS_SESSION_TOKEN&&(this.mechanismProperties.AWS_SESSION_TOKEN=process.env.AWS_SESSION_TOKEN)),Object.freeze(this.mechanismProperties),Object.freeze(this)}equals(e){return this.mechanism===e.mechanism&&this.username===e.username&&this.password===e.password&&this.source===e.source}resolveAuthMechanism(e){return this.mechanism.match(/DEFAULT/i)?new o({username:this.username,password:this.password,source:this.source,mechanism:r(e),mechanismProperties:this.mechanismProperties}):this}}e.exports={MongoCredentials:o}},function(e,t,n){"use strict";const r=n(424);e.exports={insert:function(e,t,n,o,i){r(e,"insert","documents",t,n,o,i)},update:function(e,t,n,o,i){r(e,"update","updates",t,n,o,i)},remove:function(e,t,n,o,i){r(e,"delete","deletes",t,n,o,i)},killCursors:n(425),getMore:n(426),query:n(427),command:n(55)}},function(e,t,n){"use strict";e.exports={ServerDescriptionChangedEvent:class{constructor(e,t,n,r){Object.assign(this,{topologyId:e,address:t,previousDescription:n,newDescription:r})}},ServerOpeningEvent:class{constructor(e,t){Object.assign(this,{topologyId:e,address:t})}},ServerClosedEvent:class{constructor(e,t){Object.assign(this,{topologyId:e,address:t})}},TopologyDescriptionChangedEvent:class{constructor(e,t,n){Object.assign(this,{topologyId:e,previousDescription:t,newDescription:n})}},TopologyOpeningEvent:class{constructor(e){Object.assign(this,{topologyId:e})}},TopologyClosedEvent:class{constructor(e){Object.assign(this,{topologyId:e})}},ServerHeartbeatStartedEvent:class{constructor(e){Object.assign(this,{connectionId:e})}},ServerHeartbeatSucceededEvent:class{constructor(e,t,n){Object.assign(this,{connectionId:n,duration:e,reply:t})}},ServerHeartbeatFailedEvent:class{constructor(e,t,n){Object.assign(this,{connectionId:n,duration:e,failure:t})}}}},function(e,t,n){"use strict";const r=n(8),o=n(434),i=n(3).MongoError,s=n(3).MongoNetworkError,a=n(3).MongoNetworkTimeoutError,c=n(3).MongoWriteConcernError,u=n(133),l=n(441).StreamDescription,f=n(199),p=n(191),d=n(34).updateSessionFromResponse,h=n(4).uuidV4,m=n(0).now,g=n(0).calculateDurationInMs,y=Symbol("stream"),b=Symbol("queue"),v=Symbol("messageStream"),S=Symbol("generation"),w=Symbol("lastUseTime"),_=Symbol("clusterTime"),O=Symbol("description"),T=Symbol("ismaster"),C=Symbol("autoEncrypter");function x(e){const t={description:e.description,clusterTime:e[_],s:{bson:e.bson,pool:{write:E.bind(e),isConnected:()=>!0}}};return e[C]&&(t.autoEncrypter=e[C]),t}function E(e,t,n){"function"==typeof t&&(n=t),t=t||{};const r={requestId:e.requestId,cb:n,session:t.session,fullResult:"boolean"==typeof t.fullResult&&t.fullResult,noResponse:"boolean"==typeof t.noResponse&&t.noResponse,documentsReturnedIn:t.documentsReturnedIn,command:!!t.command,promoteLongs:"boolean"!=typeof t.promoteLongs||t.promoteLongs,promoteValues:"boolean"!=typeof t.promoteValues||t.promoteValues,promoteBuffers:"boolean"==typeof t.promoteBuffers&&t.promoteBuffers,raw:"boolean"==typeof t.raw&&t.raw};this[O]&&this[O].compressor&&(r.agreedCompressor=this[O].compressor,this[O].zlibCompressionLevel&&(r.zlibCompressionLevel=this[O].zlibCompressionLevel)),"number"==typeof t.socketTimeout&&(r.socketTimeoutOverride=!0,this[y].setTimeout(t.socketTimeout)),this.monitorCommands&&(this.emit("commandStarted",new p.CommandStartedEvent(this,e)),r.started=m(),r.cb=(t,o)=>{t?this.emit("commandFailed",new p.CommandFailedEvent(this,e,t,r.started)):o&&o.result&&(0===o.result.ok||o.result.$err)?this.emit("commandFailed",new p.CommandFailedEvent(this,e,o.result,r.started)):this.emit("commandSucceeded",new p.CommandSucceededEvent(this,e,o,r.started)),"function"==typeof n&&n(t,o)}),r.noResponse||this[b].set(r.requestId,r);try{this[v].writeCommand(e,r)}catch(e){if(!r.noResponse)return this[b].delete(r.requestId),void r.cb(e)}r.noResponse&&r.cb()}e.exports={Connection:class extends r{constructor(e,t){var n;super(t),this.id=t.id,this.address=function(e){if("function"==typeof e.address)return`${e.remoteAddress}:${e.remotePort}`;return h().toString("hex")}(e),this.bson=t.bson,this.socketTimeout="number"==typeof t.socketTimeout?t.socketTimeout:0,this.host=t.host||"localhost",this.port=t.port||27017,this.monitorCommands="boolean"==typeof t.monitorCommands&&t.monitorCommands,this.closed=!1,this.destroyed=!1,this[O]=new l(this.address,t),this[S]=t.generation,this[w]=m(),t.autoEncrypter&&(this[C]=t.autoEncrypter),this[b]=new Map,this[v]=new o(t),this[v].on("message",(n=this,function(e){if(n.emit("message",e),!n[b].has(e.responseTo))return;const t=n[b].get(e.responseTo),r=t.cb;n[b].delete(e.responseTo),e.moreToCome?n[b].set(e.requestId,t):t.socketTimeoutOverride&&n[y].setTimeout(n.socketTimeout);try{e.parse(t)}catch(e){return void r(new i(e))}if(e.documents[0]){const o=e.documents[0],s=t.session;if(s&&d(s,o),o.$clusterTime&&(n[_]=o.$clusterTime,n.emit("clusterTimeReceived",o.$clusterTime)),t.command){if(o.writeConcernError)return void r(new c(o.writeConcernError,o));if(0===o.ok||o.$err||o.errmsg||o.code)return void r(new i(o))}}r(void 0,new u(t.fullResult?e:e.documents[0],n,e))})),this[y]=e,e.on("error",()=>{}),e.on("close",()=>{this.closed||(this.closed=!0,this[b].forEach(e=>e.cb(new s(`connection ${this.id} to ${this.address} closed`))),this[b].clear(),this.emit("close"))}),e.on("timeout",()=>{this.closed||(e.destroy(),this.closed=!0,this[b].forEach(e=>e.cb(new a(`connection ${this.id} to ${this.address} timed out`,{beforeHandshake:null==this[T]}))),this[b].clear(),this.emit("close"))}),e.pipe(this[v]),this[v].pipe(e)}get description(){return this[O]}get ismaster(){return this[T]}set ismaster(e){this[O].receiveResponse(e),this[T]=e}get generation(){return this[S]||0}get idleTime(){return g(this[w])}get clusterTime(){return this[_]}get stream(){return this[y]}markAvailable(){this[w]=m()}destroy(e,t){return"function"==typeof e&&(t=e,e={}),e=Object.assign({force:!1},e),null==this[y]||this.destroyed?(this.destroyed=!0,void("function"==typeof t&&t())):e.force?(this[y].destroy(),this.destroyed=!0,void("function"==typeof t&&t())):void this[y].end(e=>{this.destroyed=!0,"function"==typeof t&&t(e)})}command(e,t,n,r){f.command(x(this),e,t,n,r)}query(e,t,n,r,o){f.query(x(this),e,t,n,r,o)}getMore(e,t,n,r,o){f.getMore(x(this),e,t,n,r,o)}killCursors(e,t,n){f.killCursors(x(this),e,t,n)}insert(e,t,n,r){f.insert(x(this),e,t,n,r)}update(e,t,n,r){f.update(x(this),e,t,n,r)}remove(e,t,n,r){f.remove(x(this),e,t,n,r)}}}},function(e,t,n){"use strict";var r=n(435).Duplex,o=n(5),i=n(22).Buffer;function s(e){if(!(this instanceof s))return new s(e);if(this._bufs=[],this.length=0,"function"==typeof e){this._callback=e;var t=function(e){this._callback&&(this._callback(e),this._callback=null)}.bind(this);this.on("pipe",(function(e){e.on("error",t)})),this.on("unpipe",(function(e){e.removeListener("error",t)}))}else this.append(e);r.call(this)}o.inherits(s,r),s.prototype._offset=function(e){var t,n=0,r=0;if(0===e)return[0,0];for(;r<this._bufs.length;r++){if(e<(t=n+this._bufs[r].length)||r==this._bufs.length-1)return[r,e-n];n=t}},s.prototype._reverseOffset=function(e){for(var t=e[0],n=e[1],r=0;r<t;r++)n+=this._bufs[r].length;return n},s.prototype.append=function(e){var t=0;if(i.isBuffer(e))this._appendBuffer(e);else if(Array.isArray(e))for(;t<e.length;t++)this.append(e[t]);else if(e instanceof s)for(;t<e._bufs.length;t++)this.append(e._bufs[t]);else null!=e&&("number"==typeof e&&(e=e.toString()),this._appendBuffer(i.from(e)));return this},s.prototype._appendBuffer=function(e){this._bufs.push(e),this.length+=e.length},s.prototype._write=function(e,t,n){this._appendBuffer(e),"function"==typeof n&&n()},s.prototype._read=function(e){if(!this.length)return this.push(null);e=Math.min(e,this.length),this.push(this.slice(0,e)),this.consume(e)},s.prototype.end=function(e){r.prototype.end.call(this,e),this._callback&&(this._callback(null,this.slice()),this._callback=null)},s.prototype.get=function(e){if(!(e>this.length||e<0)){var t=this._offset(e);return this._bufs[t[0]][t[1]]}},s.prototype.slice=function(e,t){return"number"==typeof e&&e<0&&(e+=this.length),"number"==typeof t&&t<0&&(t+=this.length),this.copy(null,0,e,t)},s.prototype.copy=function(e,t,n,r){if(("number"!=typeof n||n<0)&&(n=0),("number"!=typeof r||r>this.length)&&(r=this.length),n>=this.length)return e||i.alloc(0);if(r<=0)return e||i.alloc(0);var o,s,a=!!e,c=this._offset(n),u=r-n,l=u,f=a&&t||0,p=c[1];if(0===n&&r==this.length){if(!a)return 1===this._bufs.length?this._bufs[0]:i.concat(this._bufs,this.length);for(s=0;s<this._bufs.length;s++)this._bufs[s].copy(e,f),f+=this._bufs[s].length;return e}if(l<=this._bufs[c[0]].length-p)return a?this._bufs[c[0]].copy(e,t,p,p+l):this._bufs[c[0]].slice(p,p+l);for(a||(e=i.allocUnsafe(u)),s=c[0];s<this._bufs.length;s++){if(!(l>(o=this._bufs[s].length-p))){this._bufs[s].copy(e,f,p,p+l),f+=o;break}this._bufs[s].copy(e,f,p),f+=o,l-=o,p&&(p=0)}return e.length>f?e.slice(0,f):e},s.prototype.shallowSlice=function(e,t){if(e=e||0,t="number"!=typeof t?this.length:t,e<0&&(e+=this.length),t<0&&(t+=this.length),e===t)return new s;var n=this._offset(e),r=this._offset(t),o=this._bufs.slice(n[0],r[0]+1);return 0==r[1]?o.pop():o[o.length-1]=o[o.length-1].slice(0,r[1]),0!=n[1]&&(o[0]=o[0].slice(n[1])),new s(o)},s.prototype.toString=function(e,t,n){return this.slice(t,n).toString(e)},s.prototype.consume=function(e){if(e=Math.trunc(e),Number.isNaN(e)||e<=0)return this;for(;this._bufs.length;){if(!(e>=this._bufs[0].length)){this._bufs[0]=this._bufs[0].slice(e),this.length-=e;break}e-=this._bufs[0].length,this.length-=this._bufs[0].length,this._bufs.shift()}return this},s.prototype.duplicate=function(){for(var e=0,t=new s;e<this._bufs.length;e++)t.append(this._bufs[e]);return t},s.prototype.destroy=function(){this._bufs.length=0,this.length=0,this.push(null)},s.prototype.indexOf=function(e,t,n){if(void 0===n&&"string"==typeof t&&(n=t,t=void 0),"function"==typeof e||Array.isArray(e))throw new TypeError('The "value" argument must be one of type string, Buffer, BufferList, or Uint8Array.');if("number"==typeof e?e=i.from([e]):"string"==typeof e?e=i.from(e,n):e instanceof s?e=e.slice():i.isBuffer(e)||(e=i.from(e)),t=Number(t||0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),0===e.length)return t>this.length?this.length:t;for(var r=this._offset(t),o=r[0],a=r[1];o<this._bufs.length;o++){for(var c=this._bufs[o];a<c.length;){if(c.length-a>=e.length){var u=c.indexOf(e,a);if(-1!==u)return this._reverseOffset([o,u]);a=c.length-e.length+1}else{var l=this._reverseOffset([o,a]);if(this._match(l,e))return l;a++}}a=0}return-1},s.prototype._match=function(e,t){if(this.length-e<t.length)return!1;for(var n=0;n<t.length;n++)if(this.get(e+n)!==t[n])return!1;return!0},function(){var e={readDoubleBE:8,readDoubleLE:8,readFloatBE:4,readFloatLE:4,readInt32BE:4,readInt32LE:4,readUInt32BE:4,readUInt32LE:4,readInt16BE:2,readInt16LE:2,readUInt16BE:2,readUInt16LE:2,readInt8:1,readUInt8:1,readIntBE:null,readIntLE:null,readUIntBE:null,readUIntLE:null};for(var t in e)!function(t){s.prototype[t]=null===e[t]?function(e,n){return this.slice(e,e+n)[t](0,n)}:function(n){return this.slice(n,n+e[t])[t](0)}}(t)}(),e.exports=s},function(e,t,n){"use strict";var r=n(91);e.exports=b;var o,i=n(436);b.ReadableState=y;n(8).EventEmitter;var s=function(e,t){return e.listeners(t).length},a=n(204),c=n(92).Buffer,u=global.Uint8Array||function(){};var l=Object.create(n(57));l.inherits=n(58);var f=n(5),p=void 0;p=f&&f.debuglog?f.debuglog("stream"):function(){};var d,h=n(438),m=n(205);l.inherits(b,a);var g=["error","close","destroy","pause","resume"];function y(e,t){e=e||{};var r=t instanceof(o=o||n(47));this.objectMode=!!e.objectMode,r&&(this.objectMode=this.objectMode||!!e.readableObjectMode);var i=e.highWaterMark,s=e.readableHighWaterMark,a=this.objectMode?16:16384;this.highWaterMark=i||0===i?i:r&&(s||0===s)?s:a,this.highWaterMark=Math.floor(this.highWaterMark),this.buffer=new h,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.destroyed=!1,this.defaultEncoding=e.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,e.encoding&&(d||(d=n(207).StringDecoder),this.decoder=new d(e.encoding),this.encoding=e.encoding)}function b(e){if(o=o||n(47),!(this instanceof b))return new b(e);this._readableState=new y(e,this),this.readable=!0,e&&("function"==typeof e.read&&(this._read=e.read),"function"==typeof e.destroy&&(this._destroy=e.destroy)),a.call(this)}function v(e,t,n,r,o){var i,s=e._readableState;null===t?(s.reading=!1,function(e,t){if(t.ended)return;if(t.decoder){var n=t.decoder.end();n&&n.length&&(t.buffer.push(n),t.length+=t.objectMode?1:n.length)}t.ended=!0,_(e)}(e,s)):(o||(i=function(e,t){var n;r=t,c.isBuffer(r)||r instanceof u||"string"==typeof t||void 0===t||e.objectMode||(n=new TypeError("Invalid non-string/buffer chunk"));var r;return n}(s,t)),i?e.emit("error",i):s.objectMode||t&&t.length>0?("string"==typeof t||s.objectMode||Object.getPrototypeOf(t)===c.prototype||(t=function(e){return c.from(e)}(t)),r?s.endEmitted?e.emit("error",new Error("stream.unshift() after end event")):S(e,s,t,!0):s.ended?e.emit("error",new Error("stream.push() after EOF")):(s.reading=!1,s.decoder&&!n?(t=s.decoder.write(t),s.objectMode||0!==t.length?S(e,s,t,!1):T(e,s)):S(e,s,t,!1))):r||(s.reading=!1));return function(e){return!e.ended&&(e.needReadable||e.length<e.highWaterMark||0===e.length)}(s)}function S(e,t,n,r){t.flowing&&0===t.length&&!t.sync?(e.emit("data",n),e.read(0)):(t.length+=t.objectMode?1:n.length,r?t.buffer.unshift(n):t.buffer.push(n),t.needReadable&&_(e)),T(e,t)}Object.defineProperty(b.prototype,"destroyed",{get:function(){return void 0!==this._readableState&&this._readableState.destroyed},set:function(e){this._readableState&&(this._readableState.destroyed=e)}}),b.prototype.destroy=m.destroy,b.prototype._undestroy=m.undestroy,b.prototype._destroy=function(e,t){this.push(null),t(e)},b.prototype.push=function(e,t){var n,r=this._readableState;return r.objectMode?n=!0:"string"==typeof e&&((t=t||r.defaultEncoding)!==r.encoding&&(e=c.from(e,t),t=""),n=!0),v(this,e,t,!1,n)},b.prototype.unshift=function(e){return v(this,e,null,!0,!1)},b.prototype.isPaused=function(){return!1===this._readableState.flowing},b.prototype.setEncoding=function(e){return d||(d=n(207).StringDecoder),this._readableState.decoder=new d(e),this._readableState.encoding=e,this};function w(e,t){return e<=0||0===t.length&&t.ended?0:t.objectMode?1:e!=e?t.flowing&&t.length?t.buffer.head.data.length:t.length:(e>t.highWaterMark&&(t.highWaterMark=function(e){return e>=8388608?e=8388608:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function _(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(p("emitReadable",t.flowing),t.emittedReadable=!0,t.sync?r.nextTick(O,e):O(e))}function O(e){p("emit readable"),e.emit("readable"),N(e)}function T(e,t){t.readingMore||(t.readingMore=!0,r.nextTick(C,e,t))}function C(e,t){for(var n=t.length;!t.reading&&!t.flowing&&!t.ended&&t.length<t.highWaterMark&&(p("maybeReadMore read 0"),e.read(0),n!==t.length);)n=t.length;t.readingMore=!1}function x(e){p("readable nexttick read 0"),e.read(0)}function E(e,t){t.reading||(p("resume read 0"),e.read(0)),t.resumeScheduled=!1,t.awaitDrain=0,e.emit("resume"),N(e),t.flowing&&!t.reading&&e.read(0)}function N(e){var t=e._readableState;for(p("flow",t.flowing);t.flowing&&null!==e.read(););}function I(e,t){return 0===t.length?null:(t.objectMode?n=t.buffer.shift():!e||e>=t.length?(n=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.head.data:t.buffer.concat(t.length),t.buffer.clear()):n=function(e,t,n){var r;e<t.head.data.length?(r=t.head.data.slice(0,e),t.head.data=t.head.data.slice(e)):r=e===t.head.data.length?t.shift():n?function(e,t){var n=t.head,r=1,o=n.data;e-=o.length;for(;n=n.next;){var i=n.data,s=e>i.length?i.length:e;if(s===i.length?o+=i:o+=i.slice(0,e),0===(e-=s)){s===i.length?(++r,n.next?t.head=n.next:t.head=t.tail=null):(t.head=n,n.data=i.slice(s));break}++r}return t.length-=r,o}(e,t):function(e,t){var n=c.allocUnsafe(e),r=t.head,o=1;r.data.copy(n),e-=r.data.length;for(;r=r.next;){var i=r.data,s=e>i.length?i.length:e;if(i.copy(n,n.length-e,0,s),0===(e-=s)){s===i.length?(++o,r.next?t.head=r.next:t.head=t.tail=null):(t.head=r,r.data=i.slice(s));break}++o}return t.length-=o,n}(e,t);return r}(e,t.buffer,t.decoder),n);var n}function A(e){var t=e._readableState;if(t.length>0)throw new Error('"endReadable()" called on non-empty stream');t.endEmitted||(t.ended=!0,r.nextTick(k,t,e))}function k(e,t){e.endEmitted||0!==e.length||(e.endEmitted=!0,t.readable=!1,t.emit("end"))}function M(e,t){for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1}b.prototype.read=function(e){p("read",e),e=parseInt(e,10);var t=this._readableState,n=e;if(0!==e&&(t.emittedReadable=!1),0===e&&t.needReadable&&(t.length>=t.highWaterMark||t.ended))return p("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?A(this):_(this),null;if(0===(e=w(e,t))&&t.ended)return 0===t.length&&A(this),null;var r,o=t.needReadable;return p("need readable",o),(0===t.length||t.length-e<t.highWaterMark)&&p("length less than watermark",o=!0),t.ended||t.reading?p("reading or ended",o=!1):o&&(p("do read"),t.reading=!0,t.sync=!0,0===t.length&&(t.needReadable=!0),this._read(t.highWaterMark),t.sync=!1,t.reading||(e=w(n,t))),null===(r=e>0?I(e,t):null)?(t.needReadable=!0,e=0):t.length-=e,0===t.length&&(t.ended||(t.needReadable=!0),n!==e&&t.ended&&A(this)),null!==r&&this.emit("data",r),r},b.prototype._read=function(e){this.emit("error",new Error("_read() is not implemented"))},b.prototype.pipe=function(e,t){var n=this,o=this._readableState;switch(o.pipesCount){case 0:o.pipes=e;break;case 1:o.pipes=[o.pipes,e];break;default:o.pipes.push(e)}o.pipesCount+=1,p("pipe count=%d opts=%j",o.pipesCount,t);var a=(!t||!1!==t.end)&&e!==process.stdout&&e!==process.stderr?u:b;function c(t,r){p("onunpipe"),t===n&&r&&!1===r.hasUnpiped&&(r.hasUnpiped=!0,p("cleanup"),e.removeListener("close",g),e.removeListener("finish",y),e.removeListener("drain",l),e.removeListener("error",m),e.removeListener("unpipe",c),n.removeListener("end",u),n.removeListener("end",b),n.removeListener("data",h),f=!0,!o.awaitDrain||e._writableState&&!e._writableState.needDrain||l())}function u(){p("onend"),e.end()}o.endEmitted?r.nextTick(a):n.once("end",a),e.on("unpipe",c);var l=function(e){return function(){var t=e._readableState;p("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,0===t.awaitDrain&&s(e,"data")&&(t.flowing=!0,N(e))}}(n);e.on("drain",l);var f=!1;var d=!1;function h(t){p("ondata"),d=!1,!1!==e.write(t)||d||((1===o.pipesCount&&o.pipes===e||o.pipesCount>1&&-1!==M(o.pipes,e))&&!f&&(p("false write response, pause",n._readableState.awaitDrain),n._readableState.awaitDrain++,d=!0),n.pause())}function m(t){p("onerror",t),b(),e.removeListener("error",m),0===s(e,"error")&&e.emit("error",t)}function g(){e.removeListener("finish",y),b()}function y(){p("onfinish"),e.removeListener("close",g),b()}function b(){p("unpipe"),n.unpipe(e)}return n.on("data",h),function(e,t,n){if("function"==typeof e.prependListener)return e.prependListener(t,n);e._events&&e._events[t]?i(e._events[t])?e._events[t].unshift(n):e._events[t]=[n,e._events[t]]:e.on(t,n)}(e,"error",m),e.once("close",g),e.once("finish",y),e.emit("pipe",n),o.flowing||(p("pipe resume"),n.resume()),e},b.prototype.unpipe=function(e){var t=this._readableState,n={hasUnpiped:!1};if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes?this:(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this,n),this);if(!e){var r=t.pipes,o=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var i=0;i<o;i++)r[i].emit("unpipe",this,n);return this}var s=M(t.pipes,e);return-1===s?this:(t.pipes.splice(s,1),t.pipesCount-=1,1===t.pipesCount&&(t.pipes=t.pipes[0]),e.emit("unpipe",this,n),this)},b.prototype.on=function(e,t){var n=a.prototype.on.call(this,e,t);if("data"===e)!1!==this._readableState.flowing&&this.resume();else if("readable"===e){var o=this._readableState;o.endEmitted||o.readableListening||(o.readableListening=o.needReadable=!0,o.emittedReadable=!1,o.reading?o.length&&_(this):r.nextTick(x,this))}return n},b.prototype.addListener=b.prototype.on,b.prototype.resume=function(){var e=this._readableState;return e.flowing||(p("resume"),e.flowing=!0,function(e,t){t.resumeScheduled||(t.resumeScheduled=!0,r.nextTick(E,e,t))}(this,e)),this},b.prototype.pause=function(){return p("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(p("pause"),this._readableState.flowing=!1,this.emit("pause")),this},b.prototype.wrap=function(e){var t=this,n=this._readableState,r=!1;for(var o in e.on("end",(function(){if(p("wrapped end"),n.decoder&&!n.ended){var e=n.decoder.end();e&&e.length&&t.push(e)}t.push(null)})),e.on("data",(function(o){(p("wrapped data"),n.decoder&&(o=n.decoder.write(o)),n.objectMode&&null==o)||(n.objectMode||o&&o.length)&&(t.push(o)||(r=!0,e.pause()))})),e)void 0===this[o]&&"function"==typeof e[o]&&(this[o]=function(t){return function(){return e[t].apply(e,arguments)}}(o));for(var i=0;i<g.length;i++)e.on(g[i],this.emit.bind(this,g[i]));return this._read=function(t){p("wrapped _read",t),r&&(r=!1,e.resume())},this},Object.defineProperty(b.prototype,"readableHighWaterMark",{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),b._fromList=I},function(e,t,n){e.exports=n(18)},function(e,t,n){"use strict";var r=n(91);function o(e,t){e.emit("error",t)}e.exports={destroy:function(e,t){var n=this,i=this._readableState&&this._readableState.destroyed,s=this._writableState&&this._writableState.destroyed;return i||s?(t?t(e):!e||this._writableState&&this._writableState.errorEmitted||r.nextTick(o,this,e),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(e||null,(function(e){!t&&e?(r.nextTick(o,n,e),n._writableState&&(n._writableState.errorEmitted=!0)):t&&t(e)})),this)},undestroy:function(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}}},function(e,t,n){"use strict";var r=n(91);function o(e){var t=this;this.next=null,this.entry=null,this.finish=function(){!function(e,t,n){var r=e.entry;e.entry=null;for(;r;){var o=r.callback;t.pendingcb--,o(n),r=r.next}t.corkedRequestsFree?t.corkedRequestsFree.next=e:t.corkedRequestsFree=e}(t,e)}}e.exports=g;var i,s=!process.browser&&["v0.10","v0.9."].indexOf(process.version.slice(0,5))>-1?setImmediate:r.nextTick;g.WritableState=m;var a=Object.create(n(57));a.inherits=n(58);var c={deprecate:n(439)},u=n(204),l=n(92).Buffer,f=global.Uint8Array||function(){};var p,d=n(205);function h(){}function m(e,t){i=i||n(47),e=e||{};var a=t instanceof i;this.objectMode=!!e.objectMode,a&&(this.objectMode=this.objectMode||!!e.writableObjectMode);var c=e.highWaterMark,u=e.writableHighWaterMark,l=this.objectMode?16:16384;this.highWaterMark=c||0===c?c:a&&(u||0===u)?u:l,this.highWaterMark=Math.floor(this.highWaterMark),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var f=!1===e.decodeStrings;this.decodeStrings=!f,this.defaultEncoding=e.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){!function(e,t){var n=e._writableState,o=n.sync,i=n.writecb;if(function(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}(n),t)!function(e,t,n,o,i){--t.pendingcb,n?(r.nextTick(i,o),r.nextTick(_,e,t),e._writableState.errorEmitted=!0,e.emit("error",o)):(i(o),e._writableState.errorEmitted=!0,e.emit("error",o),_(e,t))}(e,n,o,t,i);else{var a=S(n);a||n.corked||n.bufferProcessing||!n.bufferedRequest||v(e,n),o?s(b,e,n,a,i):b(e,n,a,i)}}(t,e)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.bufferedRequestCount=0,this.corkedRequestsFree=new o(this)}function g(e){if(i=i||n(47),!(p.call(g,this)||this instanceof i))return new g(e);this._writableState=new m(e,this),this.writable=!0,e&&("function"==typeof e.write&&(this._write=e.write),"function"==typeof e.writev&&(this._writev=e.writev),"function"==typeof e.destroy&&(this._destroy=e.destroy),"function"==typeof e.final&&(this._final=e.final)),u.call(this)}function y(e,t,n,r,o,i,s){t.writelen=r,t.writecb=s,t.writing=!0,t.sync=!0,n?e._writev(o,t.onwrite):e._write(o,i,t.onwrite),t.sync=!1}function b(e,t,n,r){n||function(e,t){0===t.length&&t.needDrain&&(t.needDrain=!1,e.emit("drain"))}(e,t),t.pendingcb--,r(),_(e,t)}function v(e,t){t.bufferProcessing=!0;var n=t.bufferedRequest;if(e._writev&&n&&n.next){var r=t.bufferedRequestCount,i=new Array(r),s=t.corkedRequestsFree;s.entry=n;for(var a=0,c=!0;n;)i[a]=n,n.isBuf||(c=!1),n=n.next,a+=1;i.allBuffers=c,y(e,t,!0,t.length,i,"",s.finish),t.pendingcb++,t.lastBufferedRequest=null,s.next?(t.corkedRequestsFree=s.next,s.next=null):t.corkedRequestsFree=new o(t),t.bufferedRequestCount=0}else{for(;n;){var u=n.chunk,l=n.encoding,f=n.callback;if(y(e,t,!1,t.objectMode?1:u.length,u,l,f),n=n.next,t.bufferedRequestCount--,t.writing)break}null===n&&(t.lastBufferedRequest=null)}t.bufferedRequest=n,t.bufferProcessing=!1}function S(e){return e.ending&&0===e.length&&null===e.bufferedRequest&&!e.finished&&!e.writing}function w(e,t){e._final((function(n){t.pendingcb--,n&&e.emit("error",n),t.prefinished=!0,e.emit("prefinish"),_(e,t)}))}function _(e,t){var n=S(t);return n&&(!function(e,t){t.prefinished||t.finalCalled||("function"==typeof e._final?(t.pendingcb++,t.finalCalled=!0,r.nextTick(w,e,t)):(t.prefinished=!0,e.emit("prefinish")))}(e,t),0===t.pendingcb&&(t.finished=!0,e.emit("finish"))),n}a.inherits(g,u),m.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},function(){try{Object.defineProperty(m.prototype,"buffer",{get:c.deprecate((function(){return this.getBuffer()}),"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(e){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(p=Function.prototype[Symbol.hasInstance],Object.defineProperty(g,Symbol.hasInstance,{value:function(e){return!!p.call(this,e)||this===g&&(e&&e._writableState instanceof m)}})):p=function(e){return e instanceof this},g.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},g.prototype.write=function(e,t,n){var o,i=this._writableState,s=!1,a=!i.objectMode&&(o=e,l.isBuffer(o)||o instanceof f);return a&&!l.isBuffer(e)&&(e=function(e){return l.from(e)}(e)),"function"==typeof t&&(n=t,t=null),a?t="buffer":t||(t=i.defaultEncoding),"function"!=typeof n&&(n=h),i.ended?function(e,t){var n=new Error("write after end");e.emit("error",n),r.nextTick(t,n)}(this,n):(a||function(e,t,n,o){var i=!0,s=!1;return null===n?s=new TypeError("May not write null values to stream"):"string"==typeof n||void 0===n||t.objectMode||(s=new TypeError("Invalid non-string/buffer chunk")),s&&(e.emit("error",s),r.nextTick(o,s),i=!1),i}(this,i,e,n))&&(i.pendingcb++,s=function(e,t,n,r,o,i){if(!n){var s=function(e,t,n){e.objectMode||!1===e.decodeStrings||"string"!=typeof t||(t=l.from(t,n));return t}(t,r,o);r!==s&&(n=!0,o="buffer",r=s)}var a=t.objectMode?1:r.length;t.length+=a;var c=t.length<t.highWaterMark;c||(t.needDrain=!0);if(t.writing||t.corked){var u=t.lastBufferedRequest;t.lastBufferedRequest={chunk:r,encoding:o,isBuf:n,callback:i,next:null},u?u.next=t.lastBufferedRequest:t.bufferedRequest=t.lastBufferedRequest,t.bufferedRequestCount+=1}else y(e,t,!1,a,r,o,i);return c}(this,i,a,e,t,n)),s},g.prototype.cork=function(){this._writableState.corked++},g.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,e.writing||e.corked||e.finished||e.bufferProcessing||!e.bufferedRequest||v(this,e))},g.prototype.setDefaultEncoding=function(e){if("string"==typeof e&&(e=e.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+e);return this._writableState.defaultEncoding=e,this},Object.defineProperty(g.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),g.prototype._write=function(e,t,n){n(new Error("_write() is not implemented"))},g.prototype._writev=null,g.prototype.end=function(e,t,n){var o=this._writableState;"function"==typeof e?(n=e,e=null,t=null):"function"==typeof t&&(n=t,t=null),null!=e&&this.write(e,t),o.corked&&(o.corked=1,this.uncork()),o.ending||o.finished||function(e,t,n){t.ending=!0,_(e,t),n&&(t.finished?r.nextTick(n):e.once("finish",n));t.ended=!0,e.writable=!1}(this,o,n)},Object.defineProperty(g.prototype,"destroyed",{get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),g.prototype.destroy=d.destroy,g.prototype._undestroy=d.undestroy,g.prototype._destroy=function(e,t){this.end(),t(e)}},function(e,t,n){"use strict";var r=n(92).Buffer,o=r.isEncoding||function(e){switch((e=""+e)&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function i(e){var t;switch(this.encoding=function(e){var t=function(e){if(!e)return"utf8";for(var t;;)switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=!0}}(e);if("string"!=typeof t&&(r.isEncoding===o||!o(e)))throw new Error("Unknown encoding: "+e);return t||e}(e),this.encoding){case"utf16le":this.text=c,this.end=u,t=4;break;case"utf8":this.fillLast=a,t=4;break;case"base64":this.text=l,this.end=f,t=3;break;default:return this.write=p,void(this.end=d)}this.lastNeed=0,this.lastTotal=0,this.lastChar=r.allocUnsafe(t)}function s(e){return e<=127?0:e>>5==6?2:e>>4==14?3:e>>3==30?4:e>>6==2?-1:-2}function a(e){var t=this.lastTotal-this.lastNeed,n=function(e,t,n){if(128!=(192&t[0]))return e.lastNeed=0,"�";if(e.lastNeed>1&&t.length>1){if(128!=(192&t[1]))return e.lastNeed=1,"�";if(e.lastNeed>2&&t.length>2&&128!=(192&t[2]))return e.lastNeed=2,"�"}}(this,e);return void 0!==n?n:this.lastNeed<=e.length?(e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(e.copy(this.lastChar,t,0,e.length),void(this.lastNeed-=e.length))}function c(e,t){if((e.length-t)%2==0){var n=e.toString("utf16le",t);if(n){var r=n.charCodeAt(n.length-1);if(r>=55296&&r<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],n.slice(0,-1)}return n}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function u(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var n=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,n)}return t}function l(e,t){var n=(e.length-t)%3;return 0===n?e.toString("base64",t):(this.lastNeed=3-n,this.lastTotal=3,1===n?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-n))}function f(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function p(e){return e.toString(this.encoding)}function d(e){return e&&e.length?this.write(e):""}t.StringDecoder=i,i.prototype.write=function(e){if(0===e.length)return"";var t,n;if(this.lastNeed){if(void 0===(t=this.fillLast(e)))return"";n=this.lastNeed,this.lastNeed=0}else n=0;return n<e.length?t?t+this.text(e,n):this.text(e,n):t||""},i.prototype.end=function(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+"�":t},i.prototype.text=function(e,t){var n=function(e,t,n){var r=t.length-1;if(r<n)return 0;var o=s(t[r]);if(o>=0)return o>0&&(e.lastNeed=o-1),o;if(--r<n||-2===o)return 0;if((o=s(t[r]))>=0)return o>0&&(e.lastNeed=o-2),o;if(--r<n||-2===o)return 0;if((o=s(t[r]))>=0)return o>0&&(2===o?o=0:e.lastNeed=o-3),o;return 0}(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=n;var r=e.length-(n-this.lastNeed);return e.copy(this.lastChar,0,r),e.toString("utf8",t,r)},i.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length}},function(e,t,n){"use strict";e.exports=s;var r=n(47),o=Object.create(n(57));function i(e,t){var n=this._transformState;n.transforming=!1;var r=n.writecb;if(!r)return this.emit("error",new Error("write callback called multiple times"));n.writechunk=null,n.writecb=null,null!=t&&this.push(t),r(e);var o=this._readableState;o.reading=!1,(o.needReadable||o.length<o.highWaterMark)&&this._read(o.highWaterMark)}function s(e){if(!(this instanceof s))return new s(e);r.call(this,e),this._transformState={afterTransform:i.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=!0,this._readableState.sync=!1,e&&("function"==typeof e.transform&&(this._transform=e.transform),"function"==typeof e.flush&&(this._flush=e.flush)),this.on("prefinish",a)}function a(){var e=this;"function"==typeof this._flush?this._flush((function(t,n){c(e,t,n)})):c(this,null,null)}function c(e,t,n){if(t)return e.emit("error",t);if(null!=n&&e.push(n),e._writableState.length)throw new Error("Calling transform done when ws.length != 0");if(e._transformState.transforming)throw new Error("Calling transform done when still transforming");return e.push(null)}o.inherits=n(58),o.inherits(s,r),s.prototype.push=function(e,t){return this._transformState.needTransform=!1,r.prototype.push.call(this,e,t)},s.prototype._transform=function(e,t,n){throw new Error("_transform() is not implemented")},s.prototype._write=function(e,t,n){var r=this._transformState;if(r.writecb=n,r.writechunk=e,r.writeencoding=t,!r.transforming){var o=this._readableState;(r.needTransform||o.needReadable||o.length<o.highWaterMark)&&this._read(o.highWaterMark)}},s.prototype._read=function(e){var t=this._transformState;null!==t.writechunk&&t.writecb&&!t.transforming?(t.transforming=!0,this._transform(t.writechunk,t.writeencoding,t.afterTransform)):t.needTransform=!0},s.prototype._destroy=function(e,t){var n=this;r.prototype._destroy.call(this,e,(function(e){t(e),n.emit("close")}))}},function(e,t,n){"use strict";const r=n(0).applyRetryableWrites,o=n(0).applyWriteConcern,i=n(2).MongoError,s=n(1).OperationBase;e.exports=class extends s{constructor(e,t,n){super(n),this.collection=e,this.operations=t}execute(e){const t=this.collection,n=this.operations;let s=this.options;t.s.options.ignoreUndefined&&(s=Object.assign({},s),s.ignoreUndefined=t.s.options.ignoreUndefined);const a=!0===s.ordered||null==s.ordered?t.initializeOrderedBulkOp(s):t.initializeUnorderedBulkOp(s);let c=!1;try{for(let e=0;e<n.length;e++){const t=Object.keys(n[e])[0];n[e][t].collation&&(c=!0),a.raw(n[e])}}catch(t){return e(t,null)}let u=Object.assign({},s);u=r(u,t.s.db),u=o(u,{db:t.s.db,collection:t},s);const l=u.writeConcern?u.writeConcern:{},f=t.s.topology.capabilities();if(c&&f&&!f.commandsTakeCollation)return e(new i("server/primary/mongos does not support collation"));a.execute(l,u,(t,n)=>{if(!n&&t)return e(t,null);n.insertedCount=n.nInserted,n.matchedCount=n.nMatched,n.modifiedCount=n.nModified||0,n.deletedCount=n.nRemoved,n.upsertedCount=n.getUpsertedIds().length,n.upsertedIds={},n.insertedIds={},n.n=n.insertedCount;const r=n.getInsertedIds();for(let e=0;e<r.length;e++)n.insertedIds[r[e].index]=r[e]._id;const o=n.getUpsertedIds();for(let e=0;e<o.length;e++)n.upsertedIds[o[e].index]=o[e]._id;e(null,n)})}}},function(e,t,n){"use strict";const r=n(1).Aspect,o=n(1).defineAspects,i=n(27),s=n(2).MongoError,a=n(0).parseIndexOptions,c=n(4).maxWireVersion,u=new Set(["background","unique","name","partialFilterExpression","sparse","expireAfterSeconds","storageEngine","collation","weights","default_language","language_override","textIndexVersion","2dsphereIndexVersion","bits","min","max","bucketSize","wildcardProjection"]);class l extends i{constructor(e,t,n,r){if(super(e,r),this.collection=t,Array.isArray(n)&&!Array.isArray(n[0]))this.indexes=n;else{this.onlyReturnNameOfCreatedIndex=!0;const e=a(n),t={name:"string"==typeof r.name?r.name:e.name,key:e.fieldHash};for(let e in r)u.has(e)&&(t[e]=r[e]);this.indexes=[t]}}execute(e,t){const n=this.options,r=this.indexes,o=c(e);for(let n=0;n<r.length;n++){if(r[n].collation&&o<5)return void t(new s(`Server ${e.name}, which reports wire version ${o}, does not support collation`));if(null==r[n].name){const e=[];for(let t in r[n].key)e.push(`${t}_${r[n].key[t]}`);r[n].name=e.join("_")}}const i={createIndexes:this.collection,indexes:r};if(null!=n.commitQuorum){if(o<9)return void t(new s("`commitQuorum` option for `createIndexes` not supported on servers < 4.4"));i.commitQuorum=n.commitQuorum}this.options.collation=void 0,super.executeCommand(e,i,(e,n)=>{e?t(e):t(null,this.onlyReturnNameOfCreatedIndex?r[0].name:n)})}}o(l,[r.WRITE_OPERATION,r.EXECUTE_WITH_SELECTION]),e.exports=l},function(e,t,n){"use strict";const r=n(1).Aspect,o=n(1).defineAspects,i=n(23),s=n(0).applyWriteConcern,a=n(0).handleCallback;class c extends i{constructor(e,t,n){super(e.s.db,n,e),this.collection=e,this.indexName=t}_buildCommand(){const e=this.collection,t=this.indexName,n=this.options;let r={dropIndexes:e.collectionName,index:t};return r=s(r,{db:e.s.db,collection:e},n),r}execute(e){super.execute((t,n)=>{if("function"==typeof e)return t?a(e,t,null):void a(e,null,n)})}}o(c,r.WRITE_OPERATION),e.exports=c},function(e,t,n){"use strict";const r=n(1).OperationBase,o=n(14).indexInformation;e.exports=class extends r{constructor(e,t,n){super(n),this.db=e,this.name=t}execute(e){const t=this.db,n=this.name,r=this.options;o(t,n,r,e)}}},function(e,t,n){"use strict";const r=n(1).OperationBase,o=n(0).handleCallback,i=n(2).MongoError;e.exports=class extends r{constructor(e,t){super(t),this.collection=e}execute(e){const t=this.collection,n=this.options;t.s.db.listCollections({name:t.collectionName},n).toArray((n,r)=>n?o(e,n):0===r.length?o(e,i.create({message:`collection ${t.namespace} not found`,driver:!0})):void o(e,n,r[0].options||null))}}},function(e,t,n){"use strict";const r=n(1).Aspect,o=n(23),i=n(1).defineAspects,s=n(20),a=n(0).handleCallback,c=n(0).toError,u=n(0).emitWarning;class l extends o{constructor(e,t,n,r){super(e,r),this.username=t,this.password=n}_buildCommand(){const e=this.db,t=this.username,n=this.password,r=this.options;let o=[];Array.isArray(r.roles)&&(o=r.roles),"string"==typeof r.roles&&(o=[r.roles]),0===o.length&&u("Creating a user without roles is deprecated in MongoDB >= 2.6"),"admin"!==e.databaseName.toLowerCase()&&"admin"!==r.dbName||Array.isArray(r.roles)?Array.isArray(r.roles)||(o=["dbOwner"]):o=["root"];const i=e.s.topology.lastIsMaster().maxWireVersion>=7;let a=n;if(!i){const e=s.createHash("md5");e.update(t+":mongo:"+n),a=e.digest("hex")}const c={createUser:t,customData:r.customData||{},roles:o,digestPassword:i};return"string"==typeof n&&(c.pwd=a),c}execute(e){if(null!=this.options.digestPassword)return e(c("The digestPassword option is not supported via add_user. Please use db.command('createUser', ...) instead for this option."));super.execute((t,n)=>a(e,t,t?null:n))}}i(l,r.WRITE_OPERATION),e.exports=l},function(e,t,n){"use strict";const r=n(1).OperationBase,o=n(0).handleCallback,i=n(2).MongoError,s=n(0).MongoDBNamespace;e.exports=class extends r{constructor(e,t,n){super(n),this.db=e,this.selector=t}execute(e){const t=this.db,n=this.selector,r=this.options,a=new s("admin","$cmd");t.s.topology.command(a,n,r,(n,r)=>t.serverConfig&&t.serverConfig.isDestroyed()?e(new i("topology was destroyed")):n?o(e,n):void o(e,null,r.result))}}},function(e,t,n){"use strict";const r=n(1).Aspect,o=n(23),i=n(1).defineAspects,s=n(0).handleCallback,a=n(29);class c extends o{constructor(e,t,n){const r={},o=a.fromOptions(n);null!=o&&(r.writeConcern=o),n.dbName&&(r.dbName=n.dbName),"number"==typeof n.maxTimeMS&&(r.maxTimeMS=n.maxTimeMS),super(e,r),this.username=t}_buildCommand(){return{dropUser:this.username}}execute(e){super.execute((t,n)=>{if(t)return s(e,t,null);s(e,t,!!n.ok)})}}i(c,r.WRITE_OPERATION),e.exports=c},function(e,t,n){"use strict";const r=n(1).OperationBase,o=n(0).applyWriteConcern,i=n(0).checkCollectionName,s=n(11).executeDbAdminCommand,a=n(0).handleCallback,c=n(145).loadCollection,u=n(0).toError;e.exports=class extends r{constructor(e,t,n){super(n),this.collection=e,this.newName=t}execute(e){const t=this.collection,n=this.newName,r=this.options;let l=c();i(n);const f={renameCollection:t.namespace,to:t.s.namespace.withCollection(n).toString(),dropTarget:"boolean"==typeof r.dropTarget&&r.dropTarget};o(f,{db:t.s.db,collection:t},r),s(t.s.db.admin().s.db,f,r,(r,o)=>{if(r)return a(e,r,null);if(o.errmsg)return a(e,u(o),null);try{return a(e,null,new l(t.s.db,t.s.topology,t.s.namespace.db,n,t.s.pkFactory,t.s.options))}catch(r){return a(e,u(r),null)}})}}},function(e,t,n){"use strict";const r=n(0).applyWriteConcern,o=n(214),i=n(215),s=n(216),a=n(477),c=n(478),u=n(56);function l(e,t,n){if(!(this instanceof l))return new l(e,t);this.s={db:e,topology:t,promiseLibrary:n}}l.prototype.command=function(e,t,n){const r=Array.prototype.slice.call(arguments,1);n="function"==typeof r[r.length-1]?r.pop():void 0,t=r.length?r.shift():{};const o=new i(this.s.db,e,t);return u(this.s.db.s.topology,o,n)},l.prototype.buildInfo=function(e,t){"function"==typeof e&&(t=e,e={}),e=e||{};const n=new i(this.s.db,{buildinfo:1},e);return u(this.s.db.s.topology,n,t)},l.prototype.serverInfo=function(e,t){"function"==typeof e&&(t=e,e={}),e=e||{};const n=new i(this.s.db,{buildinfo:1},e);return u(this.s.db.s.topology,n,t)},l.prototype.serverStatus=function(e,t){"function"==typeof e&&(t=e,e={}),e=e||{};const n=new i(this.s.db,{serverStatus:1},e);return u(this.s.db.s.topology,n,t)},l.prototype.ping=function(e,t){"function"==typeof e&&(t=e,e={}),e=e||{};const n=new i(this.s.db,{ping:1},e);return u(this.s.db.s.topology,n,t)},l.prototype.addUser=function(e,t,n,i){const s=Array.prototype.slice.call(arguments,2);i="function"==typeof s[s.length-1]?s.pop():void 0,"string"==typeof e&&null!=t&&"object"==typeof t&&(n=t,t=null),n=s.length?s.shift():{},n=Object.assign({},n),(n=r(n,{db:this.s.db})).dbName="admin";const a=new o(this.s.db,e,t,n);return u(this.s.db.s.topology,a,i)},l.prototype.removeUser=function(e,t,n){const o=Array.prototype.slice.call(arguments,1);n="function"==typeof o[o.length-1]?o.pop():void 0,t=o.length?o.shift():{},t=Object.assign({},t),(t=r(t,{db:this.s.db})).dbName="admin";const i=new s(this.s.db,e,t);return u(this.s.db.s.topology,i,n)},l.prototype.validateCollection=function(e,t,n){"function"==typeof t&&(n=t,t={});const r=new a(this,e,t=t||{});return u(this.s.db.s.topology,r,n)},l.prototype.listDatabases=function(e,t){return"function"==typeof e&&(t=e,e={}),e=e||{},u(this.s.db.s.topology,new c(this.s.db,e),t)},l.prototype.replSetGetStatus=function(e,t){"function"==typeof e&&(t=e,e={}),e=e||{};const n=new i(this.s.db,{replSetGetStatus:1},e);return u(this.s.db.s.topology,n,t)},e.exports=l},function(e,t,n){"use strict";const r=n(2).Topology,o=n(35).ServerCapabilities,i=n(26),s=n(0).translateOptions;e.exports=class extends r{constructor(e,t){t=t||{};let n=Object.assign({},{cursorFactory:i,reconnect:!1,emitError:"boolean"!=typeof t.emitError||t.emitError,maxPoolSize:"number"==typeof t.maxPoolSize?t.maxPoolSize:"number"==typeof t.poolSize?t.poolSize:10,minPoolSize:"number"==typeof t.minPoolSize?t.minPoolSize:"number"==typeof t.minSize?t.minSize:0,monitorCommands:"boolean"==typeof t.monitorCommands&&t.monitorCommands});n=s(n,t);var r=t.socketOptions&&Object.keys(t.socketOptions).length>0?t.socketOptions:t;n=s(n,r),super(e,n)}capabilities(){return this.s.sCapabilities?this.s.sCapabilities:null==this.lastIsMaster()?null:(this.s.sCapabilities=new o(this.lastIsMaster()),this.s.sCapabilities)}command(e,t,n,r){super.command(e.toString(),t,n,r)}insert(e,t,n,r){super.insert(e.toString(),t,n,r)}update(e,t,n,r){super.update(e.toString(),t,n,r)}remove(e,t,n,r){super.remove(e.toString(),t,n,r)}}},function(e,t,n){"use strict";const r=n(5).deprecate,o=n(2).Logger,i=n(2).MongoCredentials,s=n(2).MongoError,a=n(221),c=n(219),u=n(2).parseConnectionString,l=n(46),f=n(2).ReadPreference,p=n(222),d=n(98),h=n(2).Sessions.ServerSessionPool,m=n(0).emitDeprecationWarning,g=n(0).emitWarningOnce,y=n(88),b=n(29),v=n(93).CMAP_EVENT_NAMES;let S;const w=r(n(484),"current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect."),_={DEFAULT:"default",PLAIN:"plain",GSSAPI:"gssapi","MONGODB-CR":"mongocr","MONGODB-X509":"x509","MONGODB-AWS":"mongodb-aws","SCRAM-SHA-1":"scram-sha-1","SCRAM-SHA-256":"scram-sha-256"},O=["timeout","close","serverOpening","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","serverClosed","topologyOpening","topologyClosed","topologyDescriptionChanged","commandStarted","commandSucceeded","commandFailed","joined","left","ping","ha","all","fullsetup","open"],T=new Set(["DEFAULT","PLAIN","GSSAPI","MONGODB-CR","MONGODB-X509","MONGODB-AWS","SCRAM-SHA-1","SCRAM-SHA-256"]),C=["poolSize","ssl","sslValidate","sslCA","sslCert","sslKey","sslPass","sslCRL","autoReconnect","noDelay","keepAlive","keepAliveInitialDelay","connectTimeoutMS","family","socketTimeoutMS","reconnectTries","reconnectInterval","ha","haInterval","replicaSet","secondaryAcceptableLatencyMS","acceptableLatencyMS","connectWithNoPrimary","authSource","w","wtimeout","j","writeConcern","forceServerObjectId","serializeFunctions","ignoreUndefined","raw","bufferMaxEntries","readPreference","pkFactory","promiseLibrary","readConcern","maxStalenessSeconds","loggerLevel","logger","promoteValues","promoteBuffers","promoteLongs","domainsEnabled","checkServerIdentity","validateOptions","appname","auth","user","password","authMechanism","compression","fsync","readPreferenceTags","numberOfRetries","auto_reconnect","minSize","monitorCommands","retryWrites","retryReads","useNewUrlParser","useUnifiedTopology","serverSelectionTimeoutMS","useRecoveryToken","autoEncryption","driverInfo","tls","tlsInsecure","tlsinsecure","tlsAllowInvalidCertificates","tlsAllowInvalidHostnames","tlsCAFile","tlsCertificateFile","tlsCertificateKeyFile","tlsCertificateKeyFilePassword","minHeartbeatFrequencyMS","heartbeatFrequencyMS","directConnection","appName","maxPoolSize","minPoolSize","maxIdleTimeMS","waitQueueTimeoutMS"],x=["native_parser"],E=["server","replset","replSet","mongos","db"];const N=C.reduce((e,t)=>(e[t.toLowerCase()]=t,e),{});function I(e,t){t.on("authenticated",M(e,"authenticated")),t.on("error",M(e,"error")),t.on("timeout",M(e,"timeout")),t.on("close",M(e,"close")),t.on("parseError",M(e,"parseError")),t.once("open",M(e,"open")),t.once("fullsetup",M(e,"fullsetup")),t.once("all",M(e,"all")),t.on("reconnect",M(e,"reconnect"))}function A(e,t){e.topology=t,t instanceof c||(t.s.sessionPool=new h(t.s.coreTopology))}function k(e,t){let r=(S||(S=n(59)),S);const o=[];return e instanceof r&&O.forEach(n=>{t.on(n,(t,r)=>{"open"===n?o.push({event:n,object1:e}):o.push({event:n,object1:t,object2:r})})}),o}function M(e,t){const n=new Set(["all","fullsetup","open","reconnect"]);return(r,o)=>{if(n.has(t))return e.emit(t,e);e.emit(t,r,o)}}const R=new Set(["reconnect","reconnectFailed","attemptReconnect","joined","left","ping","ha","all","fullsetup","open"]);function j(e,t,r,o){r.promiseLibrary=e.s.promiseLibrary;const i={};"unified"===t&&(i.createServers=!1);const s=z(r,i);if(null!=r.autoEncryption){const t=n(223).Encrypter;r.encrypter=new t(e,r),r.autoEncrypter=r.encrypter.autoEncrypter}let u;"mongos"===t?u=new a(s,r):"replicaset"===t?u=new p(s,r):"unified"===t&&(u=new c(r.servers,r),function(e){e.on("newListener",e=>{R.has(e)&&m(`The \`${e}\` event is no longer supported by the unified topology, please read more by visiting http://bit.ly/2D8WfT6`,"DeprecationWarning")})}(e)),I(e,u),q(e,u),A(e,u),r.autoEncrypter?r.autoEncrypter.init(e=>{e?o(e):u.connect(r,e=>{if(e)return u.close(!0),void o(e);r.encrypter.connectInternalClient(e=>{if(e)return o(e);o(void 0,u)})})}):u.connect(r,e=>{if(e)return u.close(!0),o(e);o(void 0,u)})}function D(e,t){const n=["mongos","server","db","replset","db_options","server_options","rs_options","mongos_options"],r=["readconcern","compression","autoencryption"],o=["w","wtimeout","j","journal","fsync","writeConcern"];for(const i in t)-1===o.indexOf(i.toLowerCase())&&(-1!==r.indexOf(i.toLowerCase())?e[i]=t[i]:-1!==n.indexOf(i.toLowerCase())?e=L(e,t[i],!1):!t[i]||"object"!=typeof t[i]||Buffer.isBuffer(t[i])||Array.isArray(t[i])?e[i]=t[i]:e=L(e,t[i],!0));const i=b.fromOptions(t);return i&&(e.writeConcern=Object.assign({},e.writeConcern,i)),e}function P(e,t,n,r){const o=(r=Object.assign({},r)).authSource||r.authdb||r.dbName,a=r.authMechanism||"DEFAULT",c=a.toUpperCase(),u=r.authMechanismProperties;if(!T.has(c))throw s.create({message:`authentication mechanism ${a} not supported', options.authMechanism`,driver:!0});return new i({mechanism:_[c],mechanismProperties:u,source:o,username:t,password:n})}function B(e){return L(D({},e),e,!1)}function L(e,t,n){for(const r in t)t[r]&&"object"==typeof t[r]&&n?e=L(e,t[r],n):e[r]=t[r];return e}function q(e,t){["commandStarted","commandSucceeded","commandFailed","serverOpening","serverClosed","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","topologyOpening","topologyClosed","topologyDescriptionChanged","joined","left","ping","ha"].concat(v).forEach(n=>{t.on(n,(t,r)=>{e.emit(n,t,r)})})}function U(e){let t=Object.assign({servers:e.hosts},e.options);for(let e in t){const n=N[e];n&&(t[n]=t[e])}const n=e.auth&&e.auth.username,r=e.options&&e.options.authMechanism;(n||r)&&(t.auth=Object.assign({},e.auth),t.auth.db&&(t.authSource=t.authSource||t.auth.db),t.auth.username&&(t.auth.user=t.auth.username)),e.defaultDatabase&&(t.dbName=e.defaultDatabase),t.maxPoolSize&&(t.poolSize=t.maxPoolSize),t.readConcernLevel&&(t.readConcern=new l(t.readConcernLevel)),t.wTimeoutMS&&(t.wtimeout=t.wTimeoutMS,t.wTimeoutMS=void 0),e.srvHost&&(t.srvHost=e.srvHost);const o=["w","wtimeout","j","journal","fsync"];for(const e of o)void 0!==t[e]&&(void 0===t.writeConcern&&(t.writeConcern={}),t.writeConcern[e]=t[e],t[e]=void 0);return t}function z(e,t){if(t=Object.assign({},{createServers:!0},t),"string"!=typeof e.readPreference&&"string"!=typeof e.read_preference||(e.readPreference=new f(e.readPreference||e.read_preference)),e.readPreference&&(e.readPreferenceTags||e.read_preference_tags)&&(e.readPreference.tags=e.readPreferenceTags||e.read_preference_tags),e.maxStalenessSeconds&&(e.readPreference.maxStalenessSeconds=e.maxStalenessSeconds),null==e.socketTimeoutMS&&(e.socketTimeoutMS=0),null==e.connectTimeoutMS&&(e.connectTimeoutMS=1e4),t.createServers)return e.servers.map(t=>t.domain_socket?new d(t.domain_socket,27017,e):new d(t.host,t.port,e))}e.exports={validOptions:function(e){const t=C.concat(E);for(const n in e)if(-1===x.indexOf(n)){if(-1===t.indexOf(n)){if(e.validateOptions)return new s(`option ${n} is not supported`);g(`the options [${n}] is not supported`)}-1!==E.indexOf(n)&&g("the server/replset/mongos/db options are deprecated, "+`all their options are supported at the top level of the options object [${C}]`)}},connect:function(e,t,n,r){if(n=Object.assign({},n),null==r)throw new Error("no callback function provided");let i=!1;const c=o("MongoClient",n);if(t instanceof d||t instanceof p||t instanceof a)return function(e,t,n,r){A(e,t),I(e,t),q(e,t);let o=Object.assign({},n);"string"!=typeof n.readPreference&&"string"!=typeof n.read_preference||(o.readPreference=new f(n.readPreference||n.read_preference));if((o.user||o.password||o.authMechanism)&&!o.credentials)try{o.credentials=P(e,o.user,o.password,o)}catch(e){return r(e,t)}return t.connect(o,r)}(e,t,n,m);const l=!1!==n.useNewUrlParser,h=l?U:B;function m(t,n){const o="seed list contains no mongos proxies, replicaset connections requires the parameter replicaSet to be supplied in the URI or options object, mongodb://server:port/db?replicaSet=name";if(t&&"no mongos proxies found in seed list"===t.message)return c.isWarn()&&c.warn(o),r(new s(o));i&&e.emit("authenticated",null,!0),r(t,n)}(l?u:w)(t,n,(t,o)=>{if(t)return r(t);const s=h(o),a=D(s,n);if(null==a.socketTimeoutMS&&(a.socketTimeoutMS=0),null==a.connectTimeoutMS&&(a.connectTimeoutMS=1e4),null==a.retryWrites&&(a.retryWrites=!0),null==a.useRecoveryToken&&(a.useRecoveryToken=!0),null==a.readPreference&&(a.readPreference="primary"),a.db_options&&a.db_options.auth&&delete a.db_options.auth,function(e){null!=e.tls&&["sslCA","sslKey","sslCert"].forEach(t=>{e[t]&&(e[t]=y.readFileSync(e[t]))})}(a),e.s.options=a,e.s.readPreference=f.fromOptions(a),e.s.writeConcern=b.fromOptions(a),0===s.servers.length)return r(new Error("connection string must contain at least one seed host"));if(a.auth&&!a.credentials)try{i=!0,a.credentials=P(e,a.auth.user,a.auth.password,a)}catch(t){return r(t)}return a.useUnifiedTopology?j(e,"unified",a,m):(g("Current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor."),a.replicaSet||a.rs_name?j(e,"replicaset",a,m):s.servers.length>1?j(e,"mongos",a,m):function(e,t,n){t.promiseLibrary=e.s.promiseLibrary;const r=z(t)[0],o=k(e,r);r.connect(t,(i,s)=>{if(i)return r.close(!0),n(i);!function(e){O.forEach(t=>e.removeAllListeners(t))}(r),q(e,r),I(e,r);const a=s.lastIsMaster();if(A(e,s),a&&"isdbgrid"===a.msg)return s.close(),j(e,"mongos",t,n);!function(e,t){for(let n=0;n<t.length;n++)e.emit(t[n].event,t[n].object1,t[n].object2)}(e,o),n(i,s)})}(e,a,m))})}}},function(e,t,n){"use strict";const r=n(35).TopologyBase,o=n(2).MongoError,i=n(2).Mongos,s=n(26),a=n(98),c=n(35).Store,u=n(0).MAX_JS_INT,l=n(0).translateOptions,f=n(0).filterOptions,p=n(0).mergeOptions;var d=["ha","haInterval","acceptableLatencyMS","poolSize","ssl","checkServerIdentity","sslValidate","sslCA","sslCRL","sslCert","ciphers","ecdhCurve","sslKey","sslPass","socketOptions","bufferMaxEntries","store","auto_reconnect","autoReconnect","emitError","keepAlive","keepAliveInitialDelay","noDelay","connectTimeoutMS","socketTimeoutMS","loggerLevel","logger","reconnectTries","appname","domainsEnabled","servername","promoteLongs","promoteValues","promoteBuffers","promiseLibrary","monitorCommands"];class h extends r{constructor(e,t){super();t=f(t=t||{},d);for(var n=0;n<e.length;n++)if(!(e[n]instanceof a))throw o.create({message:"all seed list instances must be of the Server type",driver:!0});var r={force:!1,bufferMaxEntries:"number"==typeof t.bufferMaxEntries?t.bufferMaxEntries:u},h=t.store||new c(this,r),m=e.map((function(e){return{host:e.host,port:e.port}})),g="boolean"!=typeof t.auto_reconnect||t.auto_reconnect;g="boolean"==typeof t.autoReconnect?t.autoReconnect:g;var y=p({},{disconnectHandler:h,cursorFactory:s,reconnect:g,emitError:"boolean"!=typeof t.emitError||t.emitError,size:"number"==typeof t.poolSize?t.poolSize:5,monitorCommands:"boolean"==typeof t.monitorCommands&&t.monitorCommands});y=l(y,t);var b=t.socketOptions&&Object.keys(t.socketOptions).length>0?t.socketOptions:t;y=l(y,b),this.s={coreTopology:new i(m,y),sCapabilities:null,debug:y.debug,storeOptions:r,clonedOptions:y,store:h,options:t,sessionPool:null,sessions:new Set,promiseLibrary:t.promiseLibrary||Promise}}connect(e,t){var n=this;"function"==typeof e&&(t=e,e={}),null==e&&(e={}),"function"!=typeof t&&(t=null),e=Object.assign({},this.s.clonedOptions,e),n.s.options=e,n.s.storeOptions.bufferMaxEntries="number"==typeof e.bufferMaxEntries?e.bufferMaxEntries:-1;var r=function(){return function(e){["timeout","error","close"].forEach((function(e){n.removeListener(e,r)})),n.s.coreTopology.removeListener("connect",r),n.close(!0);try{t(e)}catch(e){process.nextTick((function(){throw e}))}}},o=function(e){return function(t){"error"!==e&&n.emit(e,t)}},i=function(e){return function(t,r){n.emit(e,t,r)}};["timeout","error","close","serverOpening","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","serverClosed","topologyOpening","topologyClosed","topologyDescriptionChanged","commandStarted","commandSucceeded","commandFailed"].forEach((function(e){n.s.coreTopology.removeAllListeners(e)})),n.s.coreTopology.on("serverDescriptionChanged",i("serverDescriptionChanged")),n.s.coreTopology.on("serverHeartbeatStarted",i("serverHeartbeatStarted")),n.s.coreTopology.on("serverHeartbeatSucceeded",i("serverHeartbeatSucceeded")),n.s.coreTopology.on("serverHeartbeatFailed",i("serverHeartbeatFailed")),n.s.coreTopology.on("serverOpening",i("serverOpening")),n.s.coreTopology.on("serverClosed",i("serverClosed")),n.s.coreTopology.on("topologyOpening",i("topologyOpening")),n.s.coreTopology.on("topologyClosed",i("topologyClosed")),n.s.coreTopology.on("topologyDescriptionChanged",i("topologyDescriptionChanged")),n.s.coreTopology.on("commandStarted",i("commandStarted")),n.s.coreTopology.on("commandSucceeded",i("commandSucceeded")),n.s.coreTopology.on("commandFailed",i("commandFailed")),n.s.coreTopology.once("timeout",r("timeout")),n.s.coreTopology.once("error",r("error")),n.s.coreTopology.once("close",r("close")),n.s.coreTopology.once("connect",(function(){["timeout","error","close","fullsetup"].forEach((function(e){n.s.coreTopology.removeAllListeners(e)})),n.s.coreTopology.on("timeout",o("timeout")),n.s.coreTopology.on("error",o("error")),n.s.coreTopology.on("close",o("close")),n.s.coreTopology.on("fullsetup",(function(){n.emit("fullsetup",n)})),n.emit("open",null,n);try{t(null,n)}catch(e){process.nextTick((function(){throw e}))}})),n.s.coreTopology.on("joined",i("joined")),n.s.coreTopology.on("left",i("left")),n.s.coreTopology.on("reconnect",(function(){n.emit("reconnect"),n.s.store.execute()})),n.s.coreTopology.connect(e)}}Object.defineProperty(h.prototype,"haInterval",{enumerable:!0,get:function(){return this.s.coreTopology.s.haInterval}}),e.exports=h},function(e,t,n){"use strict";const r=n(98),o=n(26),i=n(2).MongoError,s=n(35).TopologyBase,a=n(35).Store,c=n(2).ReplSet,u=n(0).MAX_JS_INT,l=n(0).translateOptions,f=n(0).filterOptions,p=n(0).mergeOptions;var d=["ha","haInterval","replicaSet","rs_name","secondaryAcceptableLatencyMS","connectWithNoPrimary","poolSize","ssl","checkServerIdentity","sslValidate","sslCA","sslCert","ciphers","ecdhCurve","sslCRL","sslKey","sslPass","socketOptions","bufferMaxEntries","store","auto_reconnect","autoReconnect","emitError","keepAlive","keepAliveInitialDelay","noDelay","connectTimeoutMS","socketTimeoutMS","strategy","debug","family","loggerLevel","logger","reconnectTries","appname","domainsEnabled","servername","promoteLongs","promoteValues","promoteBuffers","maxStalenessSeconds","promiseLibrary","minSize","monitorCommands"];class h extends s{constructor(e,t){super();var n=this;t=f(t=t||{},d);for(var s=0;s<e.length;s++)if(!(e[s]instanceof r))throw i.create({message:"all seed list instances must be of the Server type",driver:!0});var h={force:!1,bufferMaxEntries:"number"==typeof t.bufferMaxEntries?t.bufferMaxEntries:u},m=t.store||new a(n,h),g=e.map((function(e){return{host:e.host,port:e.port}})),y=p({},{disconnectHandler:m,cursorFactory:o,reconnect:!1,emitError:"boolean"!=typeof t.emitError||t.emitError,size:"number"==typeof t.poolSize?t.poolSize:5,monitorCommands:"boolean"==typeof t.monitorCommands&&t.monitorCommands});y=l(y,t);var b=t.socketOptions&&Object.keys(t.socketOptions).length>0?t.socketOptions:t;y=l(y,b);var v=new c(g,y);v.on("reconnect",(function(){n.emit("reconnect"),m.execute()})),this.s={coreTopology:v,sCapabilities:null,tag:t.tag,storeOptions:h,clonedOptions:y,store:m,options:t,sessionPool:null,sessions:new Set,promiseLibrary:t.promiseLibrary||Promise},y.debug&&Object.defineProperty(this,"replset",{enumerable:!0,get:function(){return v}})}connect(e,t){var n=this;"function"==typeof e&&(t=e,e={}),null==e&&(e={}),"function"!=typeof t&&(t=null),e=Object.assign({},this.s.clonedOptions,e),n.s.options=e,n.s.storeOptions.bufferMaxEntries="number"==typeof e.bufferMaxEntries?e.bufferMaxEntries:-1;var r=function(e){return function(t){"error"!==e&&n.emit(e,t)}};["timeout","error","close","serverOpening","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","serverClosed","topologyOpening","topologyClosed","topologyDescriptionChanged","commandStarted","commandSucceeded","commandFailed","joined","left","ping","ha"].forEach((function(e){n.s.coreTopology.removeAllListeners(e)}));var o,i=function(e){return function(t,r){n.emit(e,t,r)}};n.s.coreTopology.on("joined",(o="joined",function(e,t){n.emit(o,e,t.lastIsMaster(),t)})),n.s.coreTopology.on("left",i("left")),n.s.coreTopology.on("ping",i("ping")),n.s.coreTopology.on("ha",(function(e,t){n.emit("ha",e,t),"start"===e?n.emit("ha_connect",e,t):"end"===e&&n.emit("ha_ismaster",e,t)})),n.s.coreTopology.on("serverDescriptionChanged",i("serverDescriptionChanged")),n.s.coreTopology.on("serverHeartbeatStarted",i("serverHeartbeatStarted")),n.s.coreTopology.on("serverHeartbeatSucceeded",i("serverHeartbeatSucceeded")),n.s.coreTopology.on("serverHeartbeatFailed",i("serverHeartbeatFailed")),n.s.coreTopology.on("serverOpening",i("serverOpening")),n.s.coreTopology.on("serverClosed",i("serverClosed")),n.s.coreTopology.on("topologyOpening",i("topologyOpening")),n.s.coreTopology.on("topologyClosed",i("topologyClosed")),n.s.coreTopology.on("topologyDescriptionChanged",i("topologyDescriptionChanged")),n.s.coreTopology.on("commandStarted",i("commandStarted")),n.s.coreTopology.on("commandSucceeded",i("commandSucceeded")),n.s.coreTopology.on("commandFailed",i("commandFailed")),n.s.coreTopology.on("fullsetup",(function(){n.emit("fullsetup",n,n)})),n.s.coreTopology.on("all",(function(){n.emit("all",null,n)}));var s=function(){return function(e){["timeout","error","close"].forEach((function(e){n.s.coreTopology.removeListener(e,s)})),n.s.coreTopology.removeListener("connect",s),n.s.coreTopology.destroy();try{t(e)}catch(e){n.s.coreTopology.isConnected()||process.nextTick((function(){throw e}))}}};n.s.coreTopology.once("timeout",s("timeout")),n.s.coreTopology.once("error",s("error")),n.s.coreTopology.once("close",s("close")),n.s.coreTopology.once("connect",(function(){n.s.coreTopology.once("timeout",r("timeout")),n.s.coreTopology.once("error",r("error")),n.s.coreTopology.once("close",r("close")),n.emit("open",null,n);try{t(null,n)}catch(e){process.nextTick((function(){throw e}))}})),n.s.coreTopology.connect(e)}close(e,t){["timeout","error","close","joined","left"].forEach(e=>this.removeAllListeners(e)),super.close(e,t)}}Object.defineProperty(h.prototype,"haInterval",{enumerable:!0,get:function(){return this.s.coreTopology.s.haInterval}}),e.exports=h},function(e,t,n){"use strict";const r=n(59),o=n(9).retrieveBSON(),i=n(3).MongoError,s=n(224);if("function"!=typeof s.extension)throw new i("loaded version of `mongodb-client-encryption` does not have property `extension`. Please make sure you are loading the correct version of `mongodb-client-encryption`");const a=s.extension(n(42)).AutoEncrypter,c=Symbol("internalClient");class u{constructor(e,t){this.bypassAutoEncryption=!!t.autoEncryption.bypassAutoEncryption,this.needsConnecting=!1,0===t.maxPoolSize&&null==t.autoEncryption.keyVaultClient?t.autoEncryption.keyVaultClient=e:null==t.autoEncryption.keyVaultClient&&(t.autoEncryption.keyVaultClient=this.getInternalClient(e)),this.bypassAutoEncryption?t.autoEncryption.metadataClient=void 0:0===t.maxPoolSize?t.autoEncryption.metadataClient=e:t.autoEncryption.metadataClient=this.getInternalClient(e),t.autoEncryption.bson=u.makeBSON(t),this.autoEncrypter=new a(e,t.autoEncryption)}getInternalClient(e){if(!this[c]){const t={};for(const n of Object.keys(e.s.options))-1===["autoEncryption","minPoolSize","servers","caseTranslate","dbName"].indexOf(n)&&(t[n]=e.s.options[n]);t.minPoolSize=0;const n=["commandStarted","commandSucceeded","commandFailed","serverOpening","serverClosed","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","topologyOpening","topologyClosed","topologyDescriptionChanged","joined","left","ping","ha","connectionPoolCreated","connectionPoolClosed","connectionCreated","connectionReady","connectionClosed","connectionCheckOutStarted","connectionCheckOutFailed","connectionCheckedOut","connectionCheckedIn","connectionPoolCleared"];this[c]=new r(e.s.url,t);for(const t of n)for(const n of e.listeners(t))this[c].on(t,n);e.on("newListener",(e,t)=>{this[c].on(e,t)}),this.needsConnecting=!0}return this[c]}connectInternalClient(e){return this.needsConnecting?(this.needsConnecting=!1,this[c].connect(e)):e()}close(e,t,n){this.autoEncrypter.teardown(r=>{if(this[c]&&e!==this[c])return this[c].close(t,n);n(r)})}static makeBSON(e){return(e||{}).bson||new o([o.Binary,o.Code,o.DBRef,o.Decimal128,o.Double,o.Int32,o.Long,o.Map,o.MaxKey,o.MinKey,o.ObjectId,o.BSONRegExp,o.Symbol,o.Timestamp])}}e.exports={Encrypter:u}},function(e,t,n){"use strict";let r;function o(){return r||(r=s(n(42))),r}const i=n(99).MongoCryptError;function s(e){const t={mongodb:e};return t.stateMachine=n(485)(t),t.autoEncrypter=n(486)(t),t.clientEncryption=n(490)(t),{AutoEncrypter:t.autoEncrypter.AutoEncrypter,ClientEncryption:t.clientEncryption.ClientEncryption,MongoCryptError:i}}e.exports={extension:s,MongoCryptError:i,get AutoEncrypter(){const t=o();return delete e.exports.AutoEncrypter,e.exports.AutoEncrypter=t.AutoEncrypter,t.AutoEncrypter},get ClientEncryption(){const t=o();return delete e.exports.ClientEncryption,e.exports.ClientEncryption=t.ClientEncryption,t.ClientEncryption}}},function(e,t,n){(function(r){var o=n(88),i=n(136),s=n(487),a=i.join,c=i.dirname,u=o.accessSync&&function(e){try{o.accessSync(e)}catch(e){return!1}return!0}||o.existsSync||i.existsSync,l={arrow:process.env.NODE_BINDINGS_ARROW||" → ",compiled:process.env.NODE_BINDINGS_COMPILED_DIR||"compiled",platform:process.platform,arch:process.arch,nodePreGyp:"node-v"+process.versions.modules+"-"+process.platform+"-"+process.arch,version:process.versions.node,bindings:"bindings.node",try:[["module_root","build","bindings"],["module_root","build","Debug","bindings"],["module_root","build","Release","bindings"],["module_root","out","Debug","bindings"],["module_root","Debug","bindings"],["module_root","out","Release","bindings"],["module_root","Release","bindings"],["module_root","build","default","bindings"],["module_root","compiled","version","platform","arch","bindings"],["module_root","addon-build","release","install-root","bindings"],["module_root","addon-build","debug","install-root","bindings"],["module_root","addon-build","default","install-root","bindings"],["module_root","lib","binding","nodePreGyp","bindings"]]};e.exports=t=function(e){"string"==typeof e?e={bindings:e}:e||(e={}),Object.keys(l).map((function(t){t in e||(e[t]=l[t])})),e.module_root||(e.module_root=t.getRoot(t.getFileName())),".node"!=i.extname(e.bindings)&&(e.bindings+=".node");for(var n,r,o,s=require,c=[],u=0,f=e.try.length;u<f;u++){n=a.apply(null,e.try[u].map((function(t){return e[t]||t}))),c.push(n);try{return r=e.path?s.resolve(n):s(n),e.path||(r.path=n),r}catch(e){if("MODULE_NOT_FOUND"!==e.code&&"QUALIFIED_PATH_RESOLUTION_FAILED"!==e.code&&!/not find/i.test(e.message))throw e}}throw(o=new Error("Could not locate the bindings file. Tried:\n"+c.map((function(t){return e.arrow+t})).join("\n"))).tries=c,o},t.getFileName=function(e){var t,n=Error.prepareStackTrace,o=Error.stackTraceLimit,i={};Error.stackTraceLimit=10,Error.prepareStackTrace=function(n,o){for(var i=0,s=o.length;i<s;i++)if((t=o[i].getFileName())!==r){if(!e)return;if(t!==e)return}},Error.captureStackTrace(i),Error.prepareStackTrace=n,Error.stackTraceLimit=o;return 0===t.indexOf("file://")&&(t=s(t)),t},t.getRoot=function(e){for(var t,n=c(e);;){if("."===n&&(n=process.cwd()),u(a(n,"package.json"))||u(a(n,"node_modules")))return n;if(t===n)throw new Error('Could not find module root given file: "'+e+'". Do you have a `package.json` file? ');t=n,n=a(n,"..")}}}).call(this,"/index.js")},function(e,t,n){"use strict";const r=n(20);function o(e){return(t,n,o)=>{let i;try{i=r.createHmac(e,t).update(n).digest()}catch(e){return e}return i.copy(o),i.length}}e.exports={aes256CbcEncryptHook:function(e,t,n,o){let i;try{let o=r.createCipheriv("aes-256-cbc",e,t);o.setAutoPadding(!1),i=o.update(n)}catch(e){return e}return i.copy(o),i.length},aes256CbcDecryptHook:function(e,t,n,o){let i;try{let o=r.createDecipheriv("aes-256-cbc",e,t);o.setAutoPadding(!1),i=o.update(n)}catch(e){return e}return i.copy(o),i.length},randomHook:"function"==typeof r.randomFillSync?function(e,t){try{r.randomFillSync(e,0,t)}catch(e){return e}return t}:function(e,t){let n;try{n=r.randomBytes(t)}catch(e){return e}return n.copy(e),t},hmacSha512Hook:o("sha512"),hmacSha256Hook:o("sha256"),sha256Hook:function(e,t){let n;try{n=r.createHash("sha256").update(e).digest()}catch(e){return e}return n.copy(t),n.length},signRsaSha256Hook:function(e,t,n){let o;try{const n=r.createSign("sha256WithRSAEncryption"),i=Buffer.from(`-----BEGIN PRIVATE KEY-----\n${e.toString("base64")}\n-----END PRIVATE KEY-----\n`);o=n.update(t).end().sign(i)}catch(e){return e}return o.copy(n),o.length}}},function(e,t,n){"use strict";var r=n(2).BSON.Binary,o=n(2).BSON.ObjectID,i=n(22).Buffer,s=function(e,t,n){if(!(this instanceof s))return new s(e,t);this.file=e;var a=null==t?{}:t;if(this.writeConcern=n||{w:1},this.objectId=null==a._id?new o:a._id,this.chunkNumber=null==a.n?0:a.n,this.data=new r,"string"==typeof a.data){var c=i.alloc(a.data.length);c.write(a.data,0,a.data.length,"binary"),this.data=new r(c)}else if(Array.isArray(a.data)){c=i.alloc(a.data.length);var u=a.data.join("");c.write(u,0,u.length,"binary"),this.data=new r(c)}else if(a.data&&"Binary"===a.data._bsontype)this.data=a.data;else if(!i.isBuffer(a.data)&&null!=a.data)throw Error("Illegal chunk format");this.internalPosition=0};s.prototype.write=function(e,t){return this.data.write(e,this.internalPosition,e.length,"binary"),this.internalPosition=this.data.length(),null!=t?t(null,this):this},s.prototype.read=function(e){if(e=null==e||0===e?this.length():e,this.length()-this.internalPosition+1>=e){var t=this.data.read(this.internalPosition,e);return this.internalPosition=this.internalPosition+e,t}return""},s.prototype.readSlice=function(e){if(this.length()-this.internalPosition>=e){var t=null;return null!=this.data.buffer?t=this.data.buffer.slice(this.internalPosition,this.internalPosition+e):(t=i.alloc(e),e=this.data.readInto(t,this.internalPosition)),this.internalPosition=this.internalPosition+e,t}return null},s.prototype.eof=function(){return this.internalPosition===this.length()},s.prototype.getc=function(){return this.read(1)},s.prototype.rewind=function(){this.internalPosition=0,this.data=new r},s.prototype.save=function(e,t){var n=this;"function"==typeof e&&(t=e,e={}),n.file.chunkCollection((function(r,o){if(r)return t(r);var i={upsert:!0};for(var s in e)i[s]=e[s];for(s in n.writeConcern)i[s]=n.writeConcern[s];n.data.length()>0?n.buildMongoObject((function(e){var r={forceServerObjectId:!0};for(var s in n.writeConcern)r[s]=n.writeConcern[s];o.replaceOne({_id:n.objectId},e,i,(function(e){t(e,n)}))})):t(null,n)}))},s.prototype.buildMongoObject=function(e){var t={files_id:this.file.fileId,n:this.chunkNumber,data:this.data};null!=this.objectId&&(t._id=this.objectId),e(t)},s.prototype.length=function(){return this.data.length()},Object.defineProperty(s.prototype,"position",{enumerable:!0,get:function(){return this.internalPosition},set:function(e){this.internalPosition=e}}),s.DEFAULT_CHUNK_SIZE=261120,e.exports=s},function(e,t,n){const r=n(229);e.exports={packageName:"dbgate-plugin-mongo",drivers:[r]}},function(module,exports,__webpack_require__){const _=__webpack_require__(24),stream=__webpack_require__(18),isPromise=__webpack_require__(230),driverBase=__webpack_require__(231),Analyser=__webpack_require__(233),MongoClient=__webpack_require__(42).MongoClient,ObjectId=__webpack_require__(42).ObjectId,Cursor=__webpack_require__(42).Cursor,createBulkInsertStream=__webpack_require__(495);function transformMongoData(e){return _.mapValues(e,e=>e&&e.constructor==ObjectId?{$oid:e.toString()}:e)}function readCursor(e,t){return new Promise(n=>{t.recordset({__isDynamicStructure:!0}),e.on("data",e=>t.row(transformMongoData(e))),e.on("end",()=>n())})}function convertObjectId(e){return _.cloneDeepWith(e,e=>{if(e&&e.$oid)return ObjectId(e.$oid)})}function findArrayResult(e){if(!_.isPlainObject(e))return null;const t=_.values(e).filter(e=>_.isArray(e));return 1==t.length?t[0]:null}async function getScriptableDb(e){const t=e.__getDatabase(),n=await t.listCollections().toArray();for(const e of n)t[e.name]=t.collection(e.name);return t}const driver={...driverBase,analyserClass:Analyser,async connect({server:e,port:t,user:n,password:r,database:o,useDatabaseUrl:i,databaseUrl:s,ssl:a}){const c=i?s:n?`mongodb://${n}:${r}@${e}:${t}`:`mongodb://${e}:${t}`,u={useUnifiedTopology:!0};a&&(u.tls=!0,u.tlsCAFile=a.ca,u.tlsCertificateKeyFile=a.cert||a.key,u.tlsCertificateKeyFilePassword=a.password,u.tlsAllowInvalidCertificates=!a.rejectUnauthorized);const l=new MongoClient(c,u);return await l.connect(),l.__getDatabase=o?()=>l.db(o):()=>l.db(),l.__databaseName=o,l},query:async(e,t)=>({rows:[],columns:[]}),async script(pool,sql){let func;func=eval(`(db,ObjectId) => { ${sql} }`);const db=await getScriptableDb(pool);func(db,ObjectId)},async stream(pool,sql,options){let func;try{func=eval(`(db,ObjectId) => ${sql}`)}catch(e){return options.info({message:"Error compiling expression: "+e.message,time:new Date,severity:"error"}),void options.done()}const db=await getScriptableDb(pool);let exprValue;try{exprValue=func(db,ObjectId)}catch(e){return options.info({message:"Error evaluating expression: "+e.message,time:new Date,severity:"error"}),void options.done()}if(exprValue instanceof Cursor)await readCursor(exprValue,options);else if(isPromise(exprValue))try{const e=await exprValue;options.info({message:"Command succesfully executed",time:new Date,severity:"info"});try{options.info({message:`Result: ${JSON.stringify(e)}`,time:new Date,severity:"info"})}catch(t){options.info({message:`Result: ${e}`,time:new Date,severity:"info"})}const t=findArrayResult(e);if(t){options.recordset({__isDynamicStructure:!0});for(const e of t)options.row(e)}}catch(e){options.info({message:"Error when running command: "+e.message,time:new Date,severity:"error"})}options.done()},async readQuery(pool,sql,structure){try{const e=JSON.parse(sql);e&&e.pureName&&(sql=`db.${e.pureName}.find()`)}catch(e){}func=eval(`(db,ObjectId) => ${sql}`);const db=await getScriptableDb(pool);return exprValue=func(db,ObjectId),exprValue},async writeTable(e,t,n){return createBulkInsertStream(this,stream,e,t,n)},async getVersion(e){const t=await e.__getDatabase().admin().serverInfo();return{...t,versionText:`MongoDB ${t.version}`}},listDatabases:async e=>(await e.__getDatabase().admin().listDatabases()).databases,async readCollection(e,t){try{const n=e.__getDatabase().collection(t.pureName);if(t.countDocuments){return{count:await n.countDocuments(convertObjectId(t.condition)||{})}}{let e=await n.find(convertObjectId(t.condition)||{});return t.sort&&(e=e.sort(t.sort)),t.skip&&(e=e.skip(t.skip)),t.limit&&(e=e.limit(t.limit)),{rows:(await e.toArray()).map(transformMongoData)}}}catch(e){return{errorMessage:e.message}}},async updateCollection(e,t){const n={inserted:[],updated:[],deleted:[],replaced:[]};try{const r=e.__getDatabase();for(const e of t.inserts){const t=r.collection(e.pureName),o={...e.document,...e.fields},i=await t.insert(convertObjectId(o));n.inserted.push(i._id)}for(const e of t.updates){const t=r.collection(e.pureName);if(e.document){const r={...e.document,...e.fields},o=await t.findOne(convertObjectId(e.condition));if(o){const i=await t.replaceOne(convertObjectId(e.condition),{...convertObjectId(r),_id:o._id});n.replaced.push(i._id)}}else{const r=await t.updateOne(convertObjectId(e.condition),{$set:convertObjectId(e.fields)});n.updated.push(r._id)}}for(const e of t.deletes){const t=r.collection(e.pureName),o=await t.deleteOne(convertObjectId(e.condition));n.deleted.push(o._id)}return n}catch(e){return{errorMessage:e.message}}},async createDatabase(e,t){const n=e.db(t);await n.createCollection("collection1")},async loadFieldValues(e,t,n,r){try{const o=e.__getDatabase().collection(t.pureName),i=[];if(r){const e=_.compact(r.split(" ").map(e=>e.trim()));e.length>0&&i.push({$match:{$and:e.map(e=>({[n]:{$regex:`.*${e}.*`,$options:"i"}}))}})}let s=await o.aggregate([...i,{$group:{_id:"$"+n}},{$sort:{_id:1}},{$limit:100}]);const a=await s.toArray();return _.uniqBy(a.map(transformMongoData).map(({_id:e})=>_.isArray(e)||_.isPlainObject(e)?{value:null}:{value:e}),e=>e.value)}catch(e){return{errorMessage:e.message}}},readJsonQuery(e,t,n){const{collection:r,condition:o,sort:i}=t;return e.__getDatabase().collection(r).find(o||{}).sort(i||{})}};module.exports=driver},function(e,t){function n(e){return!!e&&("object"==typeof e||"function"==typeof e)&&"function"==typeof e.then}e.exports=n,e.exports.default=n},function(e,t,n){const{driverBase:r}=global.DBGATE_TOOLS,o=n(232),{mongoSplitterOptions:i}=n(100);function s(e){return JSON.stringify(e,void 0,2).replace(/\{\s*\"\$oid\"\s*\:\s*\"([0-9a-f]+)\"\s*\}/g,(e,t)=>`ObjectId("${t}")`)}const a={...r,dumperClass:o,databaseEngineTypes:["document"],dialect:{limitSelect:!0,rangeSelect:!0,offsetFetchRangeSyntax:!0,stringEscapeChar:"'",fallbackDataType:"nvarchar(max)",quoteIdentifier:e=>`[${e}]`},engine:"mongo@dbgate-plugin-mongo",title:"MongoDB",defaultPort:27017,supportsDatabaseUrl:!0,databaseUrlPlaceholder:"e.g. mongodb://username:password@mongodb.mydomain.net/dbname",getQuerySplitterOptions:()=>i,showConnectionField:(e,t)=>"useDatabaseUrl"==e||(t.useDatabaseUrl?["databaseUrl","defaultDatabase","singleDatabase","isReadOnly"].includes(e):["server","port","user","password","defaultDatabase","singleDatabase","isReadOnly"].includes(e)),importExportArgs:[{type:"checkbox",name:"createStringId",label:"Create string _id attribute",apiName:"createStringId",direction:"target"}],getCollectionUpdateScript(e){let t="";for(const n of e.inserts)t+=`db.${n.pureName}.insert(${s({...n.document,...n.fields})});\n`;for(const n of e.updates)n.document?t+=`db.${n.pureName}.replaceOne(${s(n.condition)}, ${s({...n.document,...n.fields})});\n`:t+=`db.${n.pureName}.updateOne(${s(n.condition)}, ${s({$set:n.fields})});\n`;for(const n of e.deletes)t+=`db.${n.pureName}.deleteOne(${s(n.condition)});\n`;return t}};e.exports=a},function(e,t){const{SqlDumper:n}=global.DBGATE_TOOLS;e.exports=class extends n{}},function(e,t,n){const{DatabaseAnalyser:r}=n(234);e.exports=class extends r{constructor(e,t,n){super(e,t,n)}async _runAnalysis(){const e=await this.pool.__getDatabase().listCollections().toArray();return this.mergeAnalyseResult({collections:e.map(e=>({pureName:e.name}))})}}},function(e,t,n){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),o=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||r(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),o(n(235),t),o(n(236),t),o(n(146),t),o(n(163),t),o(n(318),t),o(n(119),t),o(n(366),t),o(n(179),t),o(n(377),t),o(n(379),t),o(n(183),t),o(n(383),t),o(n(385),t),o(n(128),t),o(n(397),t),o(n(398),t),o(n(399),t),o(n(400),t),o(n(401),t),o(n(402),t)},function(e,t,n){"use strict";function r(e){return e&&/int/i.test(e)}function o(e){return e&&/numeric|decimal/i.test(e)}function i(e){return e&&/float|single|double/i.test(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.isTypeDateTime=t.isTypeLogical=t.isTypeString=t.isTypeNumber=t.isTypeFloat=t.isTypeNumeric=t.isTypeInteger=void 0,t.isTypeInteger=r,t.isTypeNumeric=o,t.isTypeFloat=i,t.isTypeNumber=function(e){return r(e)||i(e)||o(e)},t.isTypeString=function(e){return e&&/char|binary/i.test(e)},t.isTypeLogical=function(e){return e&&/bit|boolean/i.test(e)},t.isTypeDateTime=function(e){return e&&/date|time|timestamp/i.test(e)}},function(e,t,n){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.fillConstraintNames=t.makeUniqueColumnNames=t.findForeignKeyForColumn=t.findObjectLike=t.equalStringLike=t.quoteFullName=t.fullNameToLabel=t.fullNameToString=t.fullNameFromString=void 0;const o=r(n(24));function i(e,t){return(e||"").toLowerCase().trim()==(t||"").toLowerCase().trim()}function s(e,t,n){return`${e}_${t.pureName}_${n.map(e=>e.columnName.replace(" ","_")).join("_")}`}t.fullNameFromString=function(e){const t=e.match(/\[([^\]]+)\]\.\[([^\]]+)\]/);return t?{schemaName:t[1],pureName:t[2]}:{schemaName:null,pureName:e}},t.fullNameToString=function({schemaName:e,pureName:t}){return e?`[${e}].[${t}]`:t},t.fullNameToLabel=function({schemaName:e,pureName:t}){return e?`${e}.${t}`:t},t.quoteFullName=function(e,{schemaName:t,pureName:n}){return t?`${e.quoteIdentifier(t)}.${e.quoteIdentifier(n)}`:`${e.quoteIdentifier(n)}`},t.equalStringLike=i,t.findObjectLike=function({pureName:e,schemaName:t},n,r){var o,s;return n?t?null===(o=n[r])||void 0===o?void 0:o.find(n=>i(n.pureName,e)&&i(n.schemaName,t)):null===(s=n[r])||void 0===s?void 0:s.find(t=>i(t.pureName,e)):null},t.findForeignKeyForColumn=function(e,t){return(e.foreignKeys||[]).find(e=>e.columns.find(e=>e.columnName==t.columnName))},t.makeUniqueColumnNames=function(e){const t=new Set;for(let n=0;n<e.length;n++){if(t.has(e[n].columnName)){let r=2;for(;t.has(`${e[n].columnName}${r}`);)r++;e[n].columnName=`${e[n].columnName}${r}`}t.add(e[n].columnName)}},t.fillConstraintNames=function(e,t){if(!e)return e;const n=o.default.cloneDeep(e);!n.primaryKey||n.primaryKey.constraintName||t.anonymousPrimaryKey||(n.primaryKey.constraintName=`PK_${n.pureName}`);for(const e of n.foreignKeys||[])e.constraintName||(e.constraintName=s("FK",n,e.columns));for(const e of n.indexes||[])e.constraintName||(e.constraintName=s("IX",n,e.columns));for(const e of n.uniques||[])e.constraintName||(e.constraintName=s("UQ",n,e.columns));return n}},function(e,t){e.exports=function(){this.__data__=[],this.size=0}},function(e,t,n){var r=n(64),o=Array.prototype.splice;e.exports=function(e){var t=this.__data__,n=r(t,e);return!(n<0)&&(n==t.length-1?t.pop():o.call(t,n,1),--this.size,!0)}},function(e,t,n){var r=n(64);e.exports=function(e){var t=this.__data__,n=r(t,e);return n<0?void 0:t[n][1]}},function(e,t,n){var r=n(64);e.exports=function(e){return r(this.__data__,e)>-1}},function(e,t,n){var r=n(64);e.exports=function(e,t){var n=this.__data__,o=r(n,e);return o<0?(++this.size,n.push([e,t])):n[o][1]=t,this}},function(e,t,n){var r=n(63);e.exports=function(){this.__data__=new r,this.size=0}},function(e,t){e.exports=function(e){var t=this.__data__,n=t.delete(e);return this.size=t.size,n}},function(e,t){e.exports=function(e){return this.__data__.get(e)}},function(e,t){e.exports=function(e){return this.__data__.has(e)}},function(e,t,n){var r=n(63),o=n(103),i=n(104);e.exports=function(e,t){var n=this.__data__;if(n instanceof r){var s=n.__data__;if(!o||s.length<199)return s.push([e,t]),this.size=++n.size,this;n=this.__data__=new i(s)}return n.set(e,t),this.size=n.size,this}},function(e,t,n){var r=n(148),o=n(250),i=n(28),s=n(150),a=/^\[object .+?Constructor\]$/,c=Function.prototype,u=Object.prototype,l=c.toString,f=u.hasOwnProperty,p=RegExp("^"+l.call(f).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");e.exports=function(e){return!(!i(e)||o(e))&&(r(e)?p:a).test(s(e))}},function(e,t,n){var r=n(36),o=Object.prototype,i=o.hasOwnProperty,s=o.toString,a=r?r.toStringTag:void 0;e.exports=function(e){var t=i.call(e,a),n=e[a];try{e[a]=void 0;var r=!0}catch(e){}var o=s.call(e);return r&&(t?e[a]=n:delete e[a]),o}},function(e,t){var n=Object.prototype.toString;e.exports=function(e){return n.call(e)}},function(e,t,n){var r,o=n(251),i=(r=/[^.]+$/.exec(o&&o.keys&&o.keys.IE_PROTO||""))?"Symbol(src)_1."+r:"";e.exports=function(e){return!!i&&i in e}},function(e,t,n){var r=n(19)["__core-js_shared__"];e.exports=r},function(e,t){e.exports=function(e,t){return null==e?void 0:e[t]}},function(e,t,n){var r=n(254),o=n(63),i=n(103);e.exports=function(){this.size=0,this.__data__={hash:new r,map:new(i||o),string:new r}}},function(e,t,n){var r=n(255),o=n(256),i=n(257),s=n(258),a=n(259);function c(e){var t=-1,n=null==e?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}c.prototype.clear=r,c.prototype.delete=o,c.prototype.get=i,c.prototype.has=s,c.prototype.set=a,e.exports=c},function(e,t,n){var r=n(66);e.exports=function(){this.__data__=r?r(null):{},this.size=0}},function(e,t){e.exports=function(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}},function(e,t,n){var r=n(66),o=Object.prototype.hasOwnProperty;e.exports=function(e){var t=this.__data__;if(r){var n=t[e];return"__lodash_hash_undefined__"===n?void 0:n}return o.call(t,e)?t[e]:void 0}},function(e,t,n){var r=n(66),o=Object.prototype.hasOwnProperty;e.exports=function(e){var t=this.__data__;return r?void 0!==t[e]:o.call(t,e)}},function(e,t,n){var r=n(66);e.exports=function(e,t){var n=this.__data__;return this.size+=this.has(e)?0:1,n[e]=r&&void 0===t?"__lodash_hash_undefined__":t,this}},function(e,t,n){var r=n(67);e.exports=function(e){var t=r(this,e).delete(e);return this.size-=t?1:0,t}},function(e,t){e.exports=function(e){var t=typeof e;return"string"==t||"number"==t||"symbol"==t||"boolean"==t?"__proto__"!==e:null===e}},function(e,t,n){var r=n(67);e.exports=function(e){return r(this,e).get(e)}},function(e,t,n){var r=n(67);e.exports=function(e){return r(this,e).has(e)}},function(e,t,n){var r=n(67);e.exports=function(e,t){var n=r(this,e),o=n.size;return n.set(e,t),this.size+=n.size==o?0:1,this}},function(e,t){e.exports=function(e,t){for(var n=-1,r=null==e?0:e.length;++n<r&&!1!==t(e[n],n,e););return e}},function(e,t,n){var r=n(48),o=n(49);e.exports=function(e,t){return e&&r(t,o(t),e)}},function(e,t){e.exports=function(e,t){for(var n=-1,r=Array(e);++n<e;)r[n]=t(n);return r}},function(e,t,n){var r=n(25),o=n(15);e.exports=function(e){return o(e)&&"[object Arguments]"==r(e)}},function(e,t){e.exports=function(){return!1}},function(e,t,n){var r=n(25),o=n(109),i=n(15),s={};s["[object Float32Array]"]=s["[object Float64Array]"]=s["[object Int8Array]"]=s["[object Int16Array]"]=s["[object Int32Array]"]=s["[object Uint8Array]"]=s["[object Uint8ClampedArray]"]=s["[object Uint16Array]"]=s["[object Uint32Array]"]=!0,s["[object Arguments]"]=s["[object Array]"]=s["[object ArrayBuffer]"]=s["[object Boolean]"]=s["[object DataView]"]=s["[object Date]"]=s["[object Error]"]=s["[object Function]"]=s["[object Map]"]=s["[object Number]"]=s["[object Object]"]=s["[object RegExp]"]=s["[object Set]"]=s["[object String]"]=s["[object WeakMap]"]=!1,e.exports=function(e){return i(e)&&o(e.length)&&!!s[r(e)]}},function(e,t,n){var r=n(110),o=n(272),i=Object.prototype.hasOwnProperty;e.exports=function(e){if(!r(e))return o(e);var t=[];for(var n in Object(e))i.call(e,n)&&"constructor"!=n&&t.push(n);return t}},function(e,t,n){var r=n(154)(Object.keys,Object);e.exports=r},function(e,t,n){var r=n(48),o=n(111);e.exports=function(e,t){return e&&r(t,o(t),e)}},function(e,t,n){var r=n(28),o=n(110),i=n(275),s=Object.prototype.hasOwnProperty;e.exports=function(e){if(!r(e))return i(e);var t=o(e),n=[];for(var a in e)("constructor"!=a||!t&&s.call(e,a))&&n.push(a);return n}},function(e,t){e.exports=function(e){var t=[];if(null!=e)for(var n in Object(e))t.push(n);return t}},function(e,t,n){(function(e){var r=n(19),o=t&&!t.nodeType&&t,i=o&&"object"==typeof e&&e&&!e.nodeType&&e,s=i&&i.exports===o?r.Buffer:void 0,a=s?s.allocUnsafe:void 0;e.exports=function(e,t){if(t)return e.slice();var n=e.length,r=a?a(n):new e.constructor(n);return e.copy(r),r}}).call(this,n(62)(e))},function(e,t){e.exports=function(e,t){var n=-1,r=e.length;for(t||(t=Array(r));++n<r;)t[n]=e[n];return t}},function(e,t,n){var r=n(48),o=n(112);e.exports=function(e,t){return r(e,o(e),t)}},function(e,t){e.exports=function(e,t){for(var n=-1,r=null==e?0:e.length,o=0,i=[];++n<r;){var s=e[n];t(s,n,e)&&(i[o++]=s)}return i}},function(e,t,n){var r=n(48),o=n(156);e.exports=function(e,t){return r(e,o(e),t)}},function(e,t,n){var r=n(31)(n(19),"DataView");e.exports=r},function(e,t,n){var r=n(31)(n(19),"Promise");e.exports=r},function(e,t,n){var r=n(31)(n(19),"WeakMap");e.exports=r},function(e,t){var n=Object.prototype.hasOwnProperty;e.exports=function(e){var t=e.length,r=new e.constructor(t);return t&&"string"==typeof e[0]&&n.call(e,"index")&&(r.index=e.index,r.input=e.input),r}},function(e,t,n){var r=n(115),o=n(286),i=n(287),s=n(288),a=n(289);e.exports=function(e,t,n){var c=e.constructor;switch(t){case"[object ArrayBuffer]":return r(e);case"[object Boolean]":case"[object Date]":return new c(+e);case"[object DataView]":return o(e,n);case"[object Float32Array]":case"[object Float64Array]":case"[object Int8Array]":case"[object Int16Array]":case"[object Int32Array]":case"[object Uint8Array]":case"[object Uint8ClampedArray]":case"[object Uint16Array]":case"[object Uint32Array]":return a(e,n);case"[object Map]":return new c;case"[object Number]":case"[object String]":return new c(e);case"[object RegExp]":return i(e);case"[object Set]":return new c;case"[object Symbol]":return s(e)}}},function(e,t,n){var r=n(115);e.exports=function(e,t){var n=t?r(e.buffer):e.buffer;return new e.constructor(n,e.byteOffset,e.byteLength)}},function(e,t){var n=/\w*$/;e.exports=function(e){var t=new e.constructor(e.source,n.exec(e));return t.lastIndex=e.lastIndex,t}},function(e,t,n){var r=n(36),o=r?r.prototype:void 0,i=o?o.valueOf:void 0;e.exports=function(e){return i?Object(i.call(e)):{}}},function(e,t,n){var r=n(115);e.exports=function(e,t){var n=t?r(e.buffer):e.buffer;return new e.constructor(n,e.byteOffset,e.length)}},function(e,t,n){var r=n(291),o=n(114),i=n(110);e.exports=function(e){return"function"!=typeof e.constructor||i(e)?{}:r(o(e))}},function(e,t,n){var r=n(28),o=Object.create,i=function(){function e(){}return function(t){if(!r(t))return{};if(o)return o(t);e.prototype=t;var n=new e;return e.prototype=void 0,n}}();e.exports=i},function(e,t,n){var r=n(293),o=n(37),i=n(69),s=i&&i.isMap,a=s?o(s):r;e.exports=a},function(e,t,n){var r=n(70),o=n(15);e.exports=function(e){return o(e)&&"[object Map]"==r(e)}},function(e,t,n){var r=n(295),o=n(37),i=n(69),s=i&&i.isSet,a=s?o(s):r;e.exports=a},function(e,t,n){var r=n(70),o=n(15);e.exports=function(e){return o(e)&&"[object Set]"==r(e)}},function(e,t){e.exports=function(e){for(var t=-1,n=null==e?0:e.length,r={};++t<n;){var o=e[t];r[o[0]]=o[1]}return r}},function(e,t,n){var r=n(298),o=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,i=/\\(\\)?/g,s=r((function(e){var t=[];return 46===e.charCodeAt(0)&&t.push(""),e.replace(o,(function(e,n,r,o){t.push(r?o.replace(i,"$1"):n||e)})),t}));e.exports=s},function(e,t,n){var r=n(299);e.exports=function(e){var t=r(e,(function(e){return 500===n.size&&n.clear(),e})),n=t.cache;return t}},function(e,t,n){var r=n(104);function o(e,t){if("function"!=typeof e||null!=t&&"function"!=typeof t)throw new TypeError("Expected a function");var n=function(){var r=arguments,o=t?t.apply(this,r):r[0],i=n.cache;if(i.has(o))return i.get(o);var s=e.apply(this,r);return n.cache=i.set(o,s)||i,s};return n.cache=new(o.Cache||r),n}o.Cache=r,e.exports=o},function(e,t,n){var r=n(36),o=n(51),i=n(12),s=n(71),a=r?r.prototype:void 0,c=a?a.toString:void 0;e.exports=function e(t){if("string"==typeof t)return t;if(i(t))return o(t,e)+"";if(s(t))return c?c.call(t):"";var n=t+"";return"0"==n&&1/t==-1/0?"-0":n}},function(e,t,n){var r=n(302),o=n(309)((function(e,t,n){return t=t.toLowerCase(),e+(n?r(t):t)}));e.exports=o},function(e,t,n){var r=n(40),o=n(303);e.exports=function(e){return o(r(e).toLowerCase())}},function(e,t,n){var r=n(304)("toUpperCase");e.exports=r},function(e,t,n){var r=n(305),o=n(165),i=n(306),s=n(40);e.exports=function(e){return function(t){t=s(t);var n=o(t)?i(t):void 0,a=n?n[0]:t.charAt(0),c=n?r(n,1).join(""):t.slice(1);return a[e]()+c}}},function(e,t,n){var r=n(164);e.exports=function(e,t,n){var o=e.length;return n=void 0===n?o:n,!t&&n>=o?e:r(e,t,n)}},function(e,t,n){var r=n(307),o=n(165),i=n(308);e.exports=function(e){return o(e)?i(e):r(e)}},function(e,t){e.exports=function(e){return e.split("")}},function(e,t){var n="[\\ud800-\\udfff]",r="[\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff]",o="\\ud83c[\\udffb-\\udfff]",i="[^\\ud800-\\udfff]",s="(?:\\ud83c[\\udde6-\\uddff]){2}",a="[\\ud800-\\udbff][\\udc00-\\udfff]",c="(?:"+r+"|"+o+")"+"?",u="[\\ufe0e\\ufe0f]?"+c+("(?:\\u200d(?:"+[i,s,a].join("|")+")[\\ufe0e\\ufe0f]?"+c+")*"),l="(?:"+[i+r+"?",r,s,a,n].join("|")+")",f=RegExp(o+"(?="+o+")|"+l+u,"g");e.exports=function(e){return e.match(f)||[]}},function(e,t,n){var r=n(310),o=n(311),i=n(314),s=RegExp("['’]","g");e.exports=function(e){return function(t){return r(i(o(t).replace(s,"")),e,"")}}},function(e,t){e.exports=function(e,t,n,r){var o=-1,i=null==e?0:e.length;for(r&&i&&(n=e[++o]);++o<i;)n=t(n,e[o],o,e);return n}},function(e,t,n){var r=n(312),o=n(40),i=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,s=RegExp("[\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff]","g");e.exports=function(e){return(e=o(e))&&e.replace(i,r).replace(s,"")}},function(e,t,n){var r=n(313)({"À":"A","Á":"A","Â":"A","Ã":"A","Ä":"A","Å":"A","à":"a","á":"a","â":"a","ã":"a","ä":"a","å":"a","Ç":"C","ç":"c","Ð":"D","ð":"d","È":"E","É":"E","Ê":"E","Ë":"E","è":"e","é":"e","ê":"e","ë":"e","Ì":"I","Í":"I","Î":"I","Ï":"I","ì":"i","í":"i","î":"i","ï":"i","Ñ":"N","ñ":"n","Ò":"O","Ó":"O","Ô":"O","Õ":"O","Ö":"O","Ø":"O","ò":"o","ó":"o","ô":"o","õ":"o","ö":"o","ø":"o","Ù":"U","Ú":"U","Û":"U","Ü":"U","ù":"u","ú":"u","û":"u","ü":"u","Ý":"Y","ý":"y","ÿ":"y","Æ":"Ae","æ":"ae","Þ":"Th","þ":"th","ß":"ss","Ā":"A","Ă":"A","Ą":"A","ā":"a","ă":"a","ą":"a","Ć":"C","Ĉ":"C","Ċ":"C","Č":"C","ć":"c","ĉ":"c","ċ":"c","č":"c","Ď":"D","Đ":"D","ď":"d","đ":"d","Ē":"E","Ĕ":"E","Ė":"E","Ę":"E","Ě":"E","ē":"e","ĕ":"e","ė":"e","ę":"e","ě":"e","Ĝ":"G","Ğ":"G","Ġ":"G","Ģ":"G","ĝ":"g","ğ":"g","ġ":"g","ģ":"g","Ĥ":"H","Ħ":"H","ĥ":"h","ħ":"h","Ĩ":"I","Ī":"I","Ĭ":"I","Į":"I","İ":"I","ĩ":"i","ī":"i","ĭ":"i","į":"i","ı":"i","Ĵ":"J","ĵ":"j","Ķ":"K","ķ":"k","ĸ":"k","Ĺ":"L","Ļ":"L","Ľ":"L","Ŀ":"L","Ł":"L","ĺ":"l","ļ":"l","ľ":"l","ŀ":"l","ł":"l","Ń":"N","Ņ":"N","Ň":"N","Ŋ":"N","ń":"n","ņ":"n","ň":"n","ŋ":"n","Ō":"O","Ŏ":"O","Ő":"O","ō":"o","ŏ":"o","ő":"o","Ŕ":"R","Ŗ":"R","Ř":"R","ŕ":"r","ŗ":"r","ř":"r","Ś":"S","Ŝ":"S","Ş":"S","Š":"S","ś":"s","ŝ":"s","ş":"s","š":"s","Ţ":"T","Ť":"T","Ŧ":"T","ţ":"t","ť":"t","ŧ":"t","Ũ":"U","Ū":"U","Ŭ":"U","Ů":"U","Ű":"U","Ų":"U","ũ":"u","ū":"u","ŭ":"u","ů":"u","ű":"u","ų":"u","Ŵ":"W","ŵ":"w","Ŷ":"Y","ŷ":"y","Ÿ":"Y","Ź":"Z","Ż":"Z","Ž":"Z","ź":"z","ż":"z","ž":"z","IJ":"IJ","ij":"ij","Œ":"Oe","œ":"oe","ʼn":"'n","ſ":"s"});e.exports=r},function(e,t){e.exports=function(e){return function(t){return null==e?void 0:e[t]}}},function(e,t,n){var r=n(315),o=n(316),i=n(40),s=n(317);e.exports=function(e,t,n){return e=i(e),void 0===(t=n?void 0:t)?o(e)?s(e):r(e):e.match(t)||[]}},function(e,t){var n=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g;e.exports=function(e){return e.match(n)||[]}},function(e,t){var n=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/;e.exports=function(e){return n.test(e)}},function(e,t){var n="\\xac\\xb1\\xd7\\xf7\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf\\u2000-\\u206f \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",r="["+n+"]",o="\\d+",i="[\\u2700-\\u27bf]",s="[a-z\\xdf-\\xf6\\xf8-\\xff]",a="[^\\ud800-\\udfff"+n+o+"\\u2700-\\u27bfa-z\\xdf-\\xf6\\xf8-\\xffA-Z\\xc0-\\xd6\\xd8-\\xde]",c="(?:\\ud83c[\\udde6-\\uddff]){2}",u="[\\ud800-\\udbff][\\udc00-\\udfff]",l="[A-Z\\xc0-\\xd6\\xd8-\\xde]",f="(?:"+s+"|"+a+")",p="(?:"+l+"|"+a+")",d="(?:[\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff]|\\ud83c[\\udffb-\\udfff])?",h="[\\ufe0e\\ufe0f]?"+d+("(?:\\u200d(?:"+["[^\\ud800-\\udfff]",c,u].join("|")+")[\\ufe0e\\ufe0f]?"+d+")*"),m="(?:"+[i,c,u].join("|")+")"+h,g=RegExp([l+"?"+s+"+(?:['’](?:d|ll|m|re|s|t|ve))?(?="+[r,l,"$"].join("|")+")",p+"+(?:['’](?:D|LL|M|RE|S|T|VE))?(?="+[r,l+f,"$"].join("|")+")",l+"?"+f+"+(?:['’](?:d|ll|m|re|s|t|ve))?",l+"+(?:['’](?:D|LL|M|RE|S|T|VE))?","\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])","\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",o,m].join("|"),"g");e.exports=function(e){return e.match(g)||[]}},function(e,t,n){"use strict";var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function s(e){try{c(r.next(e))}catch(e){i(e)}}function a(e){try{c(r.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((r=r.apply(e,t||[])).next())}))},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.createBulkInsertStreamBase=void 0;const i=o(n(319)),s=n(146);t.createBulkInsertStreamBase=function(e,t,n,o,a){const c=o.schemaName?`${e.dialect.quoteIdentifier(o.schemaName)}.${e.dialect.quoteIdentifier(o.pureName)}`:e.dialect.quoteIdentifier(o.pureName),u=new t.Writable({objectMode:!0});return u.buffer=[],u.structure=null,u.columnNames=null,u.requireFixedStructure=e.databaseEngineTypes.includes("sql"),u.addRow=e=>r(this,void 0,void 0,(function*(){u.structure?u.buffer.push(e):(u.structure=e,yield u.checkStructure())})),u.checkStructure=()=>r(this,void 0,void 0,(function*(){let t=yield e.analyseSingleTable(n,o);if(t&&a.dropIfExists&&(console.log(`Dropping table ${c}`),yield e.script(n,`DROP TABLE ${c}`)),a.createIfNotExists&&(!t||a.dropIfExists)){console.log(`Creating table ${c}`);const r=e.createDumper();r.createTable((0,s.prepareTableForImport)(Object.assign(Object.assign({},u.structure),o))),console.log(r.s),yield e.script(n,r.s),t=yield e.analyseSingleTable(n,o)}a.truncate&&(yield e.script(n,`TRUNCATE TABLE ${c}`)),u.columnNames=(0,i.default)(t.columns.map(e=>e.columnName),u.structure.columns.map(e=>e.columnName))})),u.send=()=>r(this,void 0,void 0,(function*(){const t=u.buffer;u.buffer=[];const r=e.createDumper();r.putRaw(`INSERT INTO ${c} (`),r.putCollection(",",u.columnNames,t=>r.putRaw(e.dialect.quoteIdentifier(t))),r.putRaw(")\n VALUES\n");let o=!1;for(const e of t)o&&r.putRaw(",\n"),r.putRaw("("),r.putCollection(",",u.columnNames,t=>r.putValue(e[t])),r.putRaw(")"),o=!0;r.putRaw(";"),yield e.query(n,r.s)})),u.sendIfFull=()=>r(this,void 0,void 0,(function*(){u.buffer.length>100&&(yield u.send())})),u._write=(e,t,n)=>r(this,void 0,void 0,(function*(){yield u.addRow(e),yield u.sendIfFull(),n()})),u._final=e=>r(this,void 0,void 0,(function*(){yield u.send(),e()})),u}},function(e,t,n){var r=n(51),o=n(320),i=n(168),s=n(331),a=i((function(e){var t=r(e,s);return t.length&&t[0]===e[0]?o(t):[]}));e.exports=a},function(e,t,n){var r=n(117),o=n(166),i=n(167),s=n(51),a=n(37),c=n(118),u=Math.min;e.exports=function(e,t,n){for(var l=n?i:o,f=e[0].length,p=e.length,d=p,h=Array(p),m=1/0,g=[];d--;){var y=e[d];d&&t&&(y=s(y,a(t))),m=u(y.length,m),h[d]=!n&&(t||f>=120&&y.length>=120)?new r(d&&y):void 0}y=e[0];var b=-1,v=h[0];e:for(;++b<f&&g.length<m;){var S=y[b],w=t?t(S):S;if(S=n||0!==S?S:0,!(v?c(v,w):l(g,w,n))){for(d=p;--d;){var _=h[d];if(!(_?c(_,w):l(e[d],w,n)))continue e}v&&v.push(w),g.push(S)}}return g}},function(e,t){e.exports=function(e){return this.__data__.set(e,"__lodash_hash_undefined__"),this}},function(e,t){e.exports=function(e){return this.__data__.has(e)}},function(e,t,n){var r=n(324),o=n(325),i=n(326);e.exports=function(e,t,n){return t==t?i(e,t,n):r(e,o,n)}},function(e,t){e.exports=function(e,t,n,r){for(var o=e.length,i=n+(r?1:-1);r?i--:++i<o;)if(t(e[i],i,e))return i;return-1}},function(e,t){e.exports=function(e){return e!=e}},function(e,t){e.exports=function(e,t,n){for(var r=n-1,o=e.length;++r<o;)if(e[r]===t)return r;return-1}},function(e,t){e.exports=function(e,t,n){switch(n.length){case 0:return e.call(t);case 1:return e.call(t,n[0]);case 2:return e.call(t,n[0],n[1]);case 3:return e.call(t,n[0],n[1],n[2])}return e.apply(t,n)}},function(e,t,n){var r=n(329),o=n(151),i=n(74),s=o?function(e,t){return o(e,"toString",{configurable:!0,enumerable:!1,value:r(t),writable:!0})}:i;e.exports=s},function(e,t){e.exports=function(e){return function(){return e}}},function(e,t){var n=Date.now;e.exports=function(e){var t=0,r=0;return function(){var o=n(),i=16-(o-r);if(r=o,i>0){if(++t>=800)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}},function(e,t,n){var r=n(332);e.exports=function(e){return r(e)?e:[]}},function(e,t,n){var r=n(38),o=n(15);e.exports=function(e){return o(e)&&r(e)}},function(e,t,n){var r=n(171),o=n(335),i=n(168),s=n(358),a=i((function(e,t){if(null==e)return[];var n=t.length;return n>1&&s(e,t[0],t[1])?t=[]:n>2&&s(t[0],t[1],t[2])&&(t=[t[0]]),o(e,r(t,1),[])}));e.exports=a},function(e,t,n){var r=n(36),o=n(107),i=n(12),s=r?r.isConcatSpreadable:void 0;e.exports=function(e){return i(e)||o(e)||!!(s&&e&&e[s])}},function(e,t,n){var r=n(51),o=n(50),i=n(120),s=n(350),a=n(355),c=n(37),u=n(356),l=n(74),f=n(12);e.exports=function(e,t,n){t=t.length?r(t,(function(e){return f(e)?function(t){return o(t,1===e.length?e[0]:e)}:e})):[l];var p=-1;t=r(t,c(i));var d=s(e,(function(e,n,o){return{criteria:r(t,(function(t){return t(e)})),index:++p,value:e}}));return a(d,(function(e,t){return u(e,t,n)}))}},function(e,t,n){var r=n(337),o=n(343),i=n(174);e.exports=function(e){var t=o(e);return 1==t.length&&t[0][2]?i(t[0][0],t[0][1]):function(n){return n===e||r(n,e,t)}}},function(e,t,n){var r=n(102),o=n(121);e.exports=function(e,t,n,i){var s=n.length,a=s,c=!i;if(null==e)return!a;for(e=Object(e);s--;){var u=n[s];if(c&&u[2]?u[1]!==e[u[0]]:!(u[0]in e))return!1}for(;++s<a;){var l=(u=n[s])[0],f=e[l],p=u[1];if(c&&u[2]){if(void 0===f&&!(l in e))return!1}else{var d=new r;if(i)var h=i(f,p,l,e,t,d);if(!(void 0===h?o(p,f,3,i,d):h))return!1}}return!0}},function(e,t,n){var r=n(102),o=n(172),i=n(340),s=n(342),a=n(70),c=n(12),u=n(108),l=n(153),f="[object Object]",p=Object.prototype.hasOwnProperty;e.exports=function(e,t,n,d,h,m){var g=c(e),y=c(t),b=g?"[object Array]":a(e),v=y?"[object Array]":a(t),S=(b="[object Arguments]"==b?f:b)==f,w=(v="[object Arguments]"==v?f:v)==f,_=b==v;if(_&&u(e)){if(!u(t))return!1;g=!0,S=!1}if(_&&!S)return m||(m=new r),g||l(e)?o(e,t,n,d,h,m):i(e,t,b,n,d,h,m);if(!(1&n)){var O=S&&p.call(e,"__wrapped__"),T=w&&p.call(t,"__wrapped__");if(O||T){var C=O?e.value():e,x=T?t.value():t;return m||(m=new r),h(C,x,n,d,m)}}return!!_&&(m||(m=new r),s(e,t,n,d,h,m))}},function(e,t){e.exports=function(e,t){for(var n=-1,r=null==e?0:e.length;++n<r;)if(t(e[n],n,e))return!0;return!1}},function(e,t,n){var r=n(36),o=n(161),i=n(65),s=n(172),a=n(341),c=n(122),u=r?r.prototype:void 0,l=u?u.valueOf:void 0;e.exports=function(e,t,n,r,u,f,p){switch(n){case"[object DataView]":if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case"[object ArrayBuffer]":return!(e.byteLength!=t.byteLength||!f(new o(e),new o(t)));case"[object Boolean]":case"[object Date]":case"[object Number]":return i(+e,+t);case"[object Error]":return e.name==t.name&&e.message==t.message;case"[object RegExp]":case"[object String]":return e==t+"";case"[object Map]":var d=a;case"[object Set]":var h=1&r;if(d||(d=c),e.size!=t.size&&!h)return!1;var m=p.get(e);if(m)return m==t;r|=2,p.set(e,t);var g=s(d(e),d(t),r,u,f,p);return p.delete(e),g;case"[object Symbol]":if(l)return l.call(e)==l.call(t)}return!1}},function(e,t){e.exports=function(e){var t=-1,n=Array(e.size);return e.forEach((function(e,r){n[++t]=[r,e]})),n}},function(e,t,n){var r=n(157),o=Object.prototype.hasOwnProperty;e.exports=function(e,t,n,i,s,a){var c=1&n,u=r(e),l=u.length;if(l!=r(t).length&&!c)return!1;for(var f=l;f--;){var p=u[f];if(!(c?p in t:o.call(t,p)))return!1}var d=a.get(e),h=a.get(t);if(d&&h)return d==t&&h==e;var m=!0;a.set(e,t),a.set(t,e);for(var g=c;++f<l;){var y=e[p=u[f]],b=t[p];if(i)var v=c?i(b,y,p,t,e,a):i(y,b,p,e,t,a);if(!(void 0===v?y===b||s(y,b,n,i,a):v)){m=!1;break}g||(g="constructor"==p)}if(m&&!g){var S=e.constructor,w=t.constructor;S!=w&&"constructor"in e&&"constructor"in t&&!("function"==typeof S&&S instanceof S&&"function"==typeof w&&w instanceof w)&&(m=!1)}return a.delete(e),a.delete(t),m}},function(e,t,n){var r=n(173),o=n(49);e.exports=function(e){for(var t=o(e),n=t.length;n--;){var i=t[n],s=e[i];t[n]=[i,s,r(s)]}return t}},function(e,t,n){var r=n(121),o=n(162),i=n(175),s=n(116),a=n(173),c=n(174),u=n(41);e.exports=function(e,t){return s(e)&&a(t)?c(u(e),t):function(n){var s=o(n,e);return void 0===s&&s===t?i(n,e):r(t,s,3)}}},function(e,t){e.exports=function(e,t){return null!=e&&t in Object(e)}},function(e,t,n){var r=n(39),o=n(107),i=n(12),s=n(68),a=n(109),c=n(41);e.exports=function(e,t,n){for(var u=-1,l=(t=r(t,e)).length,f=!1;++u<l;){var p=c(t[u]);if(!(f=null!=e&&n(e,p)))break;e=e[p]}return f||++u!=l?f:!!(l=null==e?0:e.length)&&a(l)&&s(p,l)&&(i(e)||o(e))}},function(e,t,n){var r=n(348),o=n(349),i=n(116),s=n(41);e.exports=function(e){return i(e)?r(s(e)):o(e)}},function(e,t){e.exports=function(e){return function(t){return null==t?void 0:t[e]}}},function(e,t,n){var r=n(50);e.exports=function(e){return function(t){return r(t,e)}}},function(e,t,n){var r=n(176),o=n(38);e.exports=function(e,t){var n=-1,i=o(e)?Array(e.length):[];return r(e,(function(e,r,o){i[++n]=t(e,r,o)})),i}},function(e,t,n){var r=n(352),o=n(49);e.exports=function(e,t){return e&&r(e,t,o)}},function(e,t,n){var r=n(353)();e.exports=r},function(e,t){e.exports=function(e){return function(t,n,r){for(var o=-1,i=Object(t),s=r(t),a=s.length;a--;){var c=s[e?a:++o];if(!1===n(i[c],c,i))break}return t}}},function(e,t,n){var r=n(38);e.exports=function(e,t){return function(n,o){if(null==n)return n;if(!r(n))return e(n,o);for(var i=n.length,s=t?i:-1,a=Object(n);(t?s--:++s<i)&&!1!==o(a[s],s,a););return n}}},function(e,t){e.exports=function(e,t){var n=e.length;for(e.sort(t);n--;)e[n]=e[n].value;return e}},function(e,t,n){var r=n(357);e.exports=function(e,t,n){for(var o=-1,i=e.criteria,s=t.criteria,a=i.length,c=n.length;++o<a;){var u=r(i[o],s[o]);if(u)return o>=c?u:u*("desc"==n[o]?-1:1)}return e.index-t.index}},function(e,t,n){var r=n(71);e.exports=function(e,t){if(e!==t){var n=void 0!==e,o=null===e,i=e==e,s=r(e),a=void 0!==t,c=null===t,u=t==t,l=r(t);if(!c&&!l&&!s&&e>t||s&&a&&u&&!c&&!l||o&&a&&u||!n&&u||!i)return 1;if(!o&&!s&&!l&&e<t||l&&n&&i&&!o&&!s||c&&n&&i||!a&&i||!u)return-1}return 0}},function(e,t,n){var r=n(65),o=n(38),i=n(68),s=n(28);e.exports=function(e,t,n){if(!s(n))return!1;var a=typeof t;return!!("number"==a?o(n)&&i(t,n.length):"string"==a&&t in n)&&r(n[t],e)}},function(e,t,n){var r=n(106),o=n(360),i=Object.prototype.hasOwnProperty,s=o((function(e,t,n){i.call(e,n)?e[n].push(t):r(e,n,[t])}));e.exports=s},function(e,t,n){var r=n(361),o=n(362),i=n(120),s=n(12);e.exports=function(e,t){return function(n,a){var c=s(n)?r:o,u=t?t():{};return c(n,e,i(a,2),u)}}},function(e,t){e.exports=function(e,t,n,r){for(var o=-1,i=null==e?0:e.length;++o<i;){var s=e[o];t(r,s,n(s),e)}return r}},function(e,t,n){var r=n(176);e.exports=function(e,t,n,o){return r(e,(function(e,r,i){t(o,e,n(e),i)})),o}},function(e,t,n){var r=n(364),o=n(175);e.exports=function(e,t){return r(e,t,(function(t,n){return o(e,n)}))}},function(e,t,n){var r=n(50),o=n(365),i=n(39);e.exports=function(e,t,n){for(var s=-1,a=t.length,c={};++s<a;){var u=t[s],l=r(e,u);n(l,u)&&o(c,i(u,e),l)}return c}},function(e,t,n){var r=n(105),o=n(39),i=n(68),s=n(28),a=n(41);e.exports=function(e,t,n,c){if(!s(e))return e;for(var u=-1,l=(t=o(t,e)).length,f=l-1,p=e;null!=p&&++u<l;){var d=a(t[u]),h=n;if("__proto__"===d||"constructor"===d||"prototype"===d)return e;if(u!=f){var m=p[d];void 0===(h=c?c(m,d,p):void 0)&&(h=s(m)?m:i(t[u+1])?[]:{})}r(p,d,h),p=p[d]}return e}},function(e,t,n){"use strict";var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function s(e){try{c(r.next(e))}catch(e){i(e)}}function a(e){try{c(r.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((r=r.apply(e,t||[])).next())}))},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.driverBase=void 0;const i=o(n(52)),s=n(179),a=n(371),c=n(373),u={limitSelect:!0,rangeSelect:!0,offsetFetchRangeSyntax:!0,stringEscapeChar:"'",fallbackDataType:"nvarchar(max)",quoteIdentifier:e=>e,columnProperties:{isSparse:!1,isPersisted:!1}};t.driverBase={analyserClass:null,dumperClass:s.SqlDumper,dialect:u,databaseEngineTypes:["sql"],analyseFull(e,t){return r(this,void 0,void 0,(function*(){return new this.analyserClass(e,this,t).fullAnalysis()}))},analyseSingleObject(e,t,n="tables"){return r(this,void 0,void 0,(function*(){return new this.analyserClass(e,this).singleObjectAnalysis(t,n)}))},analyseSingleTable(e,t){return this.analyseSingleObject(e,t,"tables")},analyseIncremental(e,t,n){return r(this,void 0,void 0,(function*(){return new this.analyserClass(e,this,n).incrementalAnalysis(t)}))},createDumper(e=null){return new this.dumperClass(this,e)},script(e,t){return r(this,void 0,void 0,(function*(){for(const n of(0,a.splitQuery)(t,this.getQuerySplitterOptions("script")))yield this.query(e,n,{discardResult:!0})}))},getNewObjectTemplates(){return this.databaseEngineTypes.includes("sql")?[{label:"New view",sql:"CREATE VIEW myview\nAS\nSELECT * FROM table1"}]:[]},loadFieldValues(e,t,n,o){return r(this,void 0,void 0,(function*(){const r=this.createDumper(),s={commandType:"select",distinct:!0,topRecords:100,from:{name:t},columns:[{exprType:"column",columnName:n,alias:"value"}],orderBy:[{exprType:"column",columnName:n}]};if(o){const e=(0,i.default)(o.split(" ").map(e=>e.trim()));e.length>0&&(s.where={conditionType:"and",conditions:e.map(e=>({conditionType:"like",left:{exprType:"column",columnName:n},right:{exprType:"value",value:`%${e}%`}}))})}return(0,c.dumpSqlSelect)(r,s),(yield this.query(e,r.s)).rows}))},readJsonQuery(e,t,n){const r=this.createDumper();return(0,c.dumpSqlSelect)(r,t),this.readQuery(e,r.s,n)}}},function(e,t,n){var r=n(368),o=n(37),i=n(69),s=i&&i.isDate,a=s?o(s):r;e.exports=a},function(e,t,n){var r=n(25),o=n(15);e.exports=function(e){return o(e)&&"[object Date]"==r(e)}},function(e,t,n){var r=n(20);e.exports=function(){return r.randomBytes(16)}},function(e,t){for(var n=[],r=0;r<256;++r)n[r]=(r+256).toString(16).substr(1);e.exports=function(e,t){var r=t||0,o=n;return[o[e[r++]],o[e[r++]],o[e[r++]],o[e[r++]],"-",o[e[r++]],o[e[r++]],"-",o[e[r++]],o[e[r++]],"-",o[e[r++]],o[e[r++]],"-",o[e[r++]],o[e[r++]],o[e[r++]],o[e[r++]],o[e[r++]],o[e[r++]]].join("")}},function(e,t,n){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),o=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||r(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),t.splitQuery=void 0;var i=n(372);Object.defineProperty(t,"splitQuery",{enumerable:!0,get:function(){return i.splitQuery}}),o(n(100),t)},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.splitQuery=t.finishSplitStream=t.getInitialDelimiter=t.splitQueryLine=void 0;const r=n(100);function o(e,t){if(e.options.returnRichInfo){let{source:n,position:r,line:o,column:i,streamPosition:s}=e;for(;t>0;)"\n"==n[r]?(o+=1,i=0):i+=1,r+=1,s+=1,t-=1;e.position=r,e.streamPosition=s,e.line=o,e.column=i}else e.position+=t}function i(e,t,n,r){return r?n==r?e[t]==n&&e[t+1]!=n:e[t]==n&&e[t-1]!=r:e[t]==n}const s={type:"whitespace",length:1},a={type:"eoln",length:1},c={type:"data",length:1};function u(e){let t=e.position;const n=e.source,r=n[t];if(e.options.stringsBegins.includes(r)){t++;const o=e.options.stringsEnds[r],s=e.options.stringEscapes[r];for(;t<e.end&&!i(n,t,o,s);)o==s&&n[t]==o&&n[t+1]==o?t+=2:t++;return{type:"string",length:t-e.position+1}}if(e.currentDelimiter&&n.slice(t).startsWith(e.currentDelimiter))return{type:"delimiter",length:e.currentDelimiter.length};if(" "==r||"\t"==r||"\r"==r)return s;if("\n"==r)return a;if(e.options.doubleDashComments&&"-"==r&&"-"==n[t+1]){for(;t<e.end&&"\n"!=n[t];)t++;return{type:"comment",length:t-e.position}}if(e.options.multilineComments&&"/"==r&&"*"==n[t+1]){for(t+=2;t<e.end&&("*"!=n[t]||"/"!=n[t+1]);)t++;return{type:"comment",length:t-e.position+2}}if(e.options.allowCustomDelimiter&&!e.wasDataOnLine){const e=n.slice(t).match(/^DELIMITER[ \t]+([^\n]+)/i);if(e)return{type:"set_delimiter",value:e[1].trim(),length:e[0].length}}if(e.options.allowGoDelimiter&&!e.wasDataOnLine){const e=n.slice(t).match(/^GO[\t\r ]*(\n|$)/i);if(e)return{type:"go_delimiter",length:e[0].length-1}}const o=function(e){if(!e.options.allowDollarDollarString)return null;let t=e.position;const n=e.source,r=/^(\$[a-zA-Z0-9_]*\$)/.exec(n.slice(t));if(!r)return null;const o=r[1];for(t+=o.length;t<e.end;){if(n.slice(t).startsWith(o))return{type:"string",length:t+o.length-e.position};t++}return null}(e);return o||c}function l(e){const t=(e.commandPart||"")+e.source.slice(e.currentCommandStart,e.position),n=t.trim();n&&(e.options.returnRichInfo?e.pushOutput(f(t,{text:n,start:{position:e.commandStartPosition,line:e.commandStartLine,column:e.commandStartColumn},end:{position:e.streamPosition,line:e.line,column:e.column}})):e.pushOutput(n))}function f(e,t){const n=e.indexOf(t.text),r=Object.assign({},t.start);for(let t=0;t<n;t+=1)"\n"==e[t]?(r.position+=1,r.line+=1,r.column=0):(r.position+=1,r.column+=1);return Object.assign(Object.assign({},t),{trimStart:r,trimEnd:t.end})}function p(e){e.options.returnRichInfo&&(e.commandStartPosition=e.streamPosition,e.commandStartLine=e.line,e.commandStartColumn=e.column)}function d(e){for(;e.position<e.end;){const t=u(e);if(t)switch(t.type){case"string":case"comment":o(e,t.length),e.wasDataOnLine=!0;break;case"eoln":o(e,t.length),e.wasDataOnLine=!1;break;case"data":o(e,t.length),e.wasDataOnLine=!0;break;case"whitespace":o(e,t.length);break;case"set_delimiter":l(e),e.commandPart="",e.currentDelimiter=t.value,o(e,t.length),e.currentCommandStart=e.position,p(e);break;case"go_delimiter":case"delimiter":l(e),e.commandPart="",o(e,t.length),e.currentCommandStart=e.position,p(e)}else o(e,1)}e.end>e.currentCommandStart&&(e.commandPart+=e.source.slice(e.currentCommandStart,e.position))}function h(e){return!1===(null==e?void 0:e.allowSemicolon)?null:";"}function m(e){const t=e.commandPart.trim();t&&(e.options.returnRichInfo?e.pushOutput(f(e.commandPart,{text:t,start:{position:e.commandStartPosition,line:e.commandStartLine,column:e.commandStartColumn},end:{position:e.streamPosition,line:e.line,column:e.column}})):e.pushOutput(t))}t.splitQueryLine=d,t.getInitialDelimiter=h,t.finishSplitStream=m,t.splitQuery=function(e,t=null){var n;const o=Object.assign(Object.assign({},r.defaultSplitterOptions),t);if(o.noSplit){if(o.returnRichInfo){const t=e.split("\n");return[{text:e,start:{position:0,line:0,column:0},end:{position:e.length,line:t.length,column:(null===(n=t[t.length-1])||void 0===n?void 0:n.length)||0}}]}return[e]}const i=[],s={source:e,end:e.length,currentDelimiter:h(t),position:0,column:0,line:0,currentCommandStart:0,commandStartLine:0,commandStartColumn:0,commandStartPosition:0,streamPosition:0,pushOutput:e=>i.push(e),wasDataOnLine:!1,options:o,commandPart:""};return d(s),m(s),i}},function(e,t,n){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),o=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||r(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),o(n(374),t),o(n(75),t),o(n(375),t),o(n(126),t),o(n(127),t),o(n(376),t),o(n(181),t)},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mergeConditions=t.scriptToSql=t.treeToSql=void 0;const r=n(75);t.treeToSql=function(e,t,n){const r=e.createDumper();return n(r,t),r.s},t.scriptToSql=function(e,t){const n=e.createDumper();for(const e of t)(0,r.dumpSqlCommand)(n,e),n.endCommand();return n.s},t.mergeConditions=function(e,t){return e?t?"and"==e.conditionType&&"and"==t.conditionType?{conditionType:"and",conditions:[...e.conditions,...t.conditions]}:"and"==e.conditionType?{conditionType:"and",conditions:[...e.conditions,t]}:"and"==t.conditionType?{conditionType:"and",conditions:[e,...t.conditions]}:{conditionType:"and",conditions:[e,t]}:e:t}},function(e,t,n){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.evaluateCondition=void 0;const o=r(n(24)),i=n(181);function s(e){return null==e||""==e.toString().trim()}function a(e,t){if(!e)return!1;if(!t)return!1;const n=new RegExp(`^${o.default.escapeRegExp(t).replace(/%/g,".*")}$`,"i");return!!e.toString().match(n)}t.evaluateCondition=function e(t,n){switch(t.conditionType){case"binary":const r=(0,i.evaluateExpression)(t.left,n),o=(0,i.evaluateExpression)(t.right,n);switch(t.operator){case"=":return r==o;case"!=":case"<>":return r!=o;case"<=":return r<=o;case">=":return r>=o;case"<":return r<o;case">":return r>o}break;case"isNull":return null==(0,i.evaluateExpression)(t.expr,n);case"isNotNull":return null!=(0,i.evaluateExpression)(t.expr,n);case"isEmpty":return s((0,i.evaluateExpression)(t.expr,n));case"isNotEmpty":return!s((0,i.evaluateExpression)(t.expr,n));case"and":return t.conditions.every(t=>e(t,n));case"or":return t.conditions.some(t=>e(t,n));case"like":return a((0,i.evaluateExpression)(t.left,n),(0,i.evaluateExpression)(t.right,n));case"notLike":return!a((0,i.evaluateExpression)(t.left,n),(0,i.evaluateExpression)(t.right,n));case"not":return!e(t.condition,n)}}},function(e,t,n){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.testPermission=t.compilePermissions=void 0;const o=r(n(378)),i=r(n(72)),s=r(n(52));function a(e){return 0==e.length?null:new RegExp(e.map(e=>"^"+(0,o.default)(e).replace(/\\\*/g,".*")+"$").join("|"))}t.compilePermissions=function(e){if(!e)return null;(0,i.default)(e)&&(e=e.split(","));const t=(e=(0,s.default)(e.map(e=>e.trim()))).filter(e=>e.startsWith("~")).map(e=>e.substring(1)),n=e.filter(e=>!e.startsWith("~"));return{revoke:a(t),allow:a(n)}},t.testPermission=function(e,t){return!t||(!t.revoke||!(e.match(t.revoke)&&!e.match(t.allow)))}},function(e,t,n){var r=n(40),o=/[\\^$.*+?()[\]{}|]/g,i=RegExp(o.source);e.exports=function(e){return(e=r(e))&&i.test(e)?e.replace(o,"\\$&"):e}},function(e,t,n){"use strict";var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function s(e){try{c(r.next(e))}catch(e){i(e)}}function a(e){try{c(r.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((r=r.apply(e,t||[])).next())}))},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.SqlGenerator=void 0;const i=o(n(123)),s=o(n(380)),a=n(183);t.SqlGenerator=class{constructor(e,t,n,r,o,i){this.options=t,this.objects=n,this.dmp=r,this.driver=o,this.pool=i,this.isTruncated=!1,this.isUnhandledException=!1,this.handleException=e=>{console.log("Unhandled error",e),this.isUnhandledException=!0},this.dbinfo=(0,a.extendDatabaseInfo)(e),this.tables=this.extract("tables"),this.views=this.extract("views"),this.matviews=this.extract("matviews"),this.procedures=this.extract("procedures"),this.functions=this.extract("functions"),this.triggers=this.extract("triggers")}dump(){return r(this,void 0,void 0,(function*(){try{if(process.on("uncaughtException",this.handleException),this.dropObjects(this.procedures,"Procedure"),this.checkDumper())return;if(this.dropObjects(this.functions,"Function"),this.checkDumper())return;if(this.dropObjects(this.views,"View"),this.checkDumper())return;if(this.dropObjects(this.matviews,"Matview"),this.checkDumper())return;if(this.dropObjects(this.triggers,"Trigger"),this.checkDumper())return;if(this.dropTables(),this.checkDumper())return;if(this.createTables(),this.checkDumper())return;if(this.truncateTables(),this.checkDumper())return;if(yield this.insertData(),this.checkDumper())return;if(this.createForeignKeys(),this.checkDumper())return;if(this.createObjects(this.procedures,"Procedure"),this.checkDumper())return;if(this.createObjects(this.functions,"Function"),this.checkDumper())return;if(this.createObjects(this.views,"View"),this.checkDumper())return;if(this.createObjects(this.matviews,"Matview"),this.checkDumper())return;if(this.createObjects(this.triggers,"Trigger"),this.checkDumper())return}finally{process.off("uncaughtException",this.handleException)}}))}createForeignKeys(){const e=[];this.options.createForeignKeys&&e.push(...(0,i.default)(this.tables.map(e=>e.foreignKeys||[]))),this.options.createReferences&&e.push(...(0,i.default)(this.tables.map(e=>e.dependencies||[])));for(const t of(0,s.default)(e,"constraintName"))if(this.dmp.createForeignKey(t),this.checkDumper())return}truncateTables(){if(this.options.truncate)for(const e of this.tables)if(this.dmp.truncateTable(e),this.checkDumper())return}createTables(){if(this.options.createTables)for(const e of this.tables)if(this.dmp.createTable(Object.assign(Object.assign({},e),{foreignKeys:[],dependencies:[],indexes:[]})),this.checkDumper())return;if(this.options.createIndexes)for(const e of(0,i.default)(this.tables.map(e=>e.indexes||[])))this.dmp.createIndex(e)}insertData(){return r(this,void 0,void 0,(function*(){if(this.options.insert){this.enableConstraints(!1);for(const e of this.tables)if(yield this.insertTableData(e),this.checkDumper())return;this.enableConstraints(!0)}}))}checkDumper(){return this.dmp.s.length>4e6&&(this.isTruncated||(this.dmp.putRaw("\n"),this.dmp.comment(" *************** SQL is truncated ******************"),this.dmp.putRaw("\n")),this.isTruncated=!0,!0)}dropObjects(e,t){if(this.options[`drop${t}s`])for(const n of e)if(this.dmp[`drop${t}`](n,{testIfExists:this.options[`checkIf${t}Exists`]}),this.checkDumper())return}createObjects(e,t){if(this.options[`create${t}s`])for(const n of e)if(this.dmp[`create${t}`](n),this.checkDumper())return}dropTables(){if(this.options.dropReferences)for(const e of(0,i.default)(this.tables.map(e=>e.dependencies||[])))this.dmp.dropForeignKey(e);if(this.options.dropTables)for(const e of this.tables)this.dmp.dropTable(e,{testIfExists:this.options.checkIfTableExists})}insertTableData(e){return r(this,void 0,void 0,(function*(){const t=this.driver.createDumper();t.put("^select * ^from %f",e);const n=e.columns.find(e=>e.autoIncrement);n&&!this.options.skipAutoincrementColumn&&this.dmp.allowIdentityInsert(e,!0);const r=yield this.driver.readQuery(this.pool,t.s,e);yield this.processReadable(e,r),n&&!this.options.skipAutoincrementColumn&&this.dmp.allowIdentityInsert(e,!1)}))}processReadable(e,t){const n=(this.options.skipAutoincrementColumn?e.columns.filter(e=>!e.autoIncrement):e.columns).map(e=>e.columnName);let r=!1,o=!1;return new Promise(i=>{t.on("data",s=>{if(r)return;if(!o)return void(o=!0);if(this.checkDumper())return r=!0,i(void 0),void t.destroy();const a=this.options.omitNulls?n.filter(e=>null!=s[e]):n;this.dmp.put("^insert ^into %f (%,i) ^values (%,v);&n",e,a,a.map(e=>s[e]))}),t.on("end",()=>{i(void 0)})})}extract(e){return this.dbinfo[e].filter(t=>this.objects.find(n=>t.pureName==n.pureName&&t.schemaName==n.schemaName&&n.objectTypeField==e))}enableConstraints(e){if(this.options.disableConstraints)if(this.driver.dialect.enableConstraintsPerTable)for(const t of this.tables)this.dmp.enableConstraints(t,e);else this.dmp.enableConstraints(null,e)}}},function(e,t,n){var r=n(120),o=n(182);e.exports=function(e,t){return e&&e.length?o(e,r(t,2)):[]}},function(e,t,n){var r=n(160),o=n(382),i=n(122),s=r&&1/i(new r([,-0]))[1]==1/0?function(e){return new r(e)}:o;e.exports=s},function(e,t){e.exports=function(){}},function(e,t,n){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.extractBoolSettingsValue=t.extractIntSettingsValue=void 0;const o=r(n(384)),i=r(n(124));t.extractIntSettingsValue=function(e,t,n,r=null,s=null){const a=parseInt(e[t]);return(0,o.default)(a)?n:(0,i.default)(a)?null!=r&&a<r?r:null!=s&&a>s?s:a:n},t.extractBoolSettingsValue=function(e,t,n){const r=e[t];return null==r?n:!!r}},function(e,t,n){var r=n(124);e.exports=function(e){return r(e)&&e!=+e}},function(e,t,n){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.filterName=void 0;const o=r(n(52));t.filterName=function(e,...t){if(!e)return!0;const n=e.split(" ").map(e=>e.trim()),r=(0,o.default)(t);for(const e of n){const t=e.toUpperCase();if(!r.find(e=>e.toUpperCase().includes(t)))return!1}return!0}},function(e,t,n){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.runAlterOperation=t.AlterPlan=void 0;const o=r(n(24)),i=n(128),s=n(387),a=n(119);function c(e,t){switch(e.operationType){case"createTable":t.createTable(e.newObject);break;case"changeColumn":t.changeColumn(e.oldObject,e.newObject);break;case"createColumn":t.createColumn(e.newObject,[]);break;case"dropColumn":t.dropColumn(e.oldObject);break;case"dropTable":t.dropTable(e.oldObject);break;case"changeConstraint":t.changeConstraint(e.oldObject,e.newObject);break;case"createConstraint":t.createConstraint(e.newObject);break;case"dropConstraint":t.dropConstraint(e.oldObject);break;case"renameColumn":t.renameColumn(e.object,e.newName);break;case"renameTable":t.renameTable(e.object,e.newName);break;case"renameConstraint":t.renameConstraint(e.object,e.newName);break;case"createSqlObject":t.createSqlObject(e.newObject);break;case"dropSqlObject":t.dropSqlObject(e.oldObject);break;case"fillPreloadedRows":t.fillPreloadedRows(e.table,e.oldRows,e.newRows,e.key,e.insertOnly);break;case"recreateTable":{const n=(0,i.generateTablePairingId)(e.table),r=o.default.cloneDeep(n),u=a.DatabaseAnalyser.createEmptyStructure();u.tables.push(r),e.operations.forEach(e=>c(e,new s.DatabaseInfoAlterProcessor(u))),t.recreateTable(n,r)}}}t.AlterPlan=class{constructor(e,t,n,r){this.wholeOldDb=e,this.wholeNewDb=t,this.dialect=n,this.opts=r,this.recreates={tables:0,constraints:0,sqlObjects:0},this.operations=[]}createTable(e){this.operations.push({operationType:"createTable",newObject:e})}dropTable(e){this.operations.push({operationType:"dropTable",oldObject:e})}createSqlObject(e){this.operations.push({operationType:"createSqlObject",newObject:e})}dropSqlObject(e){this.operations.push({operationType:"dropSqlObject",oldObject:e})}createColumn(e){this.operations.push({operationType:"createColumn",newObject:e})}changeColumn(e,t){this.operations.push({operationType:"changeColumn",oldObject:e,newObject:t})}dropColumn(e){this.operations.push({operationType:"dropColumn",oldObject:e})}createConstraint(e){this.operations.push({operationType:"createConstraint",newObject:e})}changeConstraint(e,t){this.operations.push({operationType:"changeConstraint",oldObject:e,newObject:t})}dropConstraint(e){this.operations.push({operationType:"dropConstraint",oldObject:e})}renameTable(e,t){this.operations.push({operationType:"renameTable",object:e,newName:t})}renameColumn(e,t){this.operations.push({operationType:"renameColumn",object:e,newName:t})}renameConstraint(e,t){this.operations.push({operationType:"renameConstraint",object:e,newName:t})}recreateTable(e,t){this.operations.push({operationType:"recreateTable",table:e,operations:t}),this.recreates.tables+=1}fillPreloadedRows(e,t,n,r,o){this.operations.push({operationType:"fillPreloadedRows",table:e,oldRows:t,newRows:n,key:r,insertOnly:o})}run(e){for(const t of this.operations)c(t,e)}_getDependendColumnConstraints(e,t){const n=this.wholeOldDb.tables.find(t=>t.pureName==e.pureName&&t.schemaName==e.schemaName);return n?[...(null==t?void 0:t.includes("dependencies"))?n.dependencies.filter(t=>t.columns.find(t=>t.refColumnName==e.columnName)):[],...o.default.compact([(null==t?void 0:t.includes("primaryKey"))?n.primaryKey:null,...(null==t?void 0:t.includes("foreignKeys"))?n.foreignKeys:[],...(null==t?void 0:t.includes("indexes"))?n.indexes:[],...(null==t?void 0:t.includes("uniques"))?n.uniques:[]]).filter(t=>t.columns.find(t=>t.columnName==e.columnName))]:[]}_addLogicalDependencies(){const e=this.operations.map(e=>{if("dropColumn"==e.operationType){const t=this._getDependendColumnConstraints(e.oldObject,this.dialect.dropColumnDependencies);return t.length>0&&this.opts.noDropConstraint?[]:[...t.map(e=>({operationType:"dropConstraint",oldObject:e})),e]}if("changeColumn"==e.operationType){const t=this._getDependendColumnConstraints(e.oldObject,this.dialect.changeColumnDependencies);if(t.length>0&&this.opts.noDropConstraint)return[];const n=[...t.map(e=>({operationType:"dropConstraint",oldObject:e})),e,...o.default.reverse([...t]).map(e=>({operationType:"createConstraint",newObject:e}))];return t.length>0&&(this.recreates.constraints+=1),n}if("dropTable"==e.operationType)return[...this.dialect.dropReferencesWhenDropTable?(e.oldObject.dependencies||[]).map(e=>({operationType:"dropConstraint",oldObject:e})):[],e];if("changeConstraint"==e.operationType){if(this.opts.noDropConstraint)return[];return this.recreates.constraints+=1,[{operationType:"dropConstraint",oldObject:e.oldObject},{operationType:"createConstraint",newObject:e.newObject}]}return[e]});return o.default.flatten(e)}_transformToImplementedOps(){const e=this.operations.map(e=>this._testTableRecreate(e,"createColumn",this.dialect.createColumn,"newObject")||this._testTableRecreate(e,"dropColumn",this.dialect.dropColumn,"oldObject")||this._testTableRecreate(e,"createConstraint",e=>this._canCreateConstraint(e),"newObject")||this._testTableRecreate(e,"dropConstraint",e=>this._canDropConstraint(e),"oldObject")||this._testTableRecreate(e,"changeColumn",this.dialect.changeColumn,"newObject")||[e]);return o.default.flatten(e)}_canCreateConstraint(e){return"primaryKey"==e.constraintType?this.dialect.createPrimaryKey:"foreignKey"==e.constraintType?this.dialect.createForeignKey:"index"==e.constraintType?this.dialect.createIndex:"unique"==e.constraintType?this.dialect.createUnique:"check"==e.constraintType?this.dialect.createCheck:null}_canDropConstraint(e){return"primaryKey"==e.constraintType?this.dialect.dropPrimaryKey:"foreignKey"==e.constraintType?this.dialect.dropForeignKey:"index"==e.constraintType?this.dialect.dropIndex:"unique"==e.constraintType?this.dialect.dropUnique:"check"==e.constraintType?this.dialect.dropCheck:null}_testTableRecreate(e,t,n,r){if(e.operationType==t){if(o.default.isFunction(n)){if(n(e[r]))return null}else if(n)return null;if(this.opts.noDropTable)return[];const t=this.wholeNewDb.tables.find(t=>t.pureName==e[r].pureName&&t.schemaName==e[r].schemaName);return this.recreates.tables+=1,[{operationType:"recreateTable",table:t,operations:[e]}]}return null}_groupTableRecreations(){const e=[],t={};for(const n of this.operations)if("recreateTable"==n.operationType&&n.table){const r=t[`${n.table.schemaName}||${n.table.pureName}`];if(r)r.operations.push(...n.operations);else{const r=Object.assign(Object.assign({},n),{operations:[...n.operations]});e.push(r),t[`${n.table.schemaName}||${n.table.pureName}`]=r}}else{const r=n.oldObject;if(r){const e=t[`${r.schemaName}||${r.pureName}`];if(e){e.operations.push(n);continue}}e.push(n)}return e}_moveForeignKeysToLast(){if(!this.dialect.createForeignKey)return this.operations;const e=[];return[...this.operations.map(t=>"createTable"==t.operationType?(e.push(...t.newObject.foreignKeys||[]),Object.assign(Object.assign({},t),{newObject:Object.assign(Object.assign({},t.newObject),{foreignKeys:[]})})):t),...e.map(e=>({operationType:"createConstraint",newObject:e}))]}_filterAllowedOperations(){return this.operations.filter(e=>(!this.opts.noDropColumn||"dropColumn"!=e.operationType)&&((!this.opts.noDropTable||"dropTable"!=e.operationType)&&((!this.opts.noDropTable||"recreateTable"!=e.operationType)&&((!this.opts.noDropConstraint||"dropConstraint"!=e.operationType)&&(!this.opts.noDropSqlObject||"dropSqlObject"!=e.operationType)))))}transformPlan(){this.operations=this._addLogicalDependencies(),this.operations=this._transformToImplementedOps(),this.operations=this._groupTableRecreations(),this.operations=this._moveForeignKeysToLast(),this.operations=this._filterAllowedOperations()}},t.runAlterOperation=c},function(e,t,n){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DatabaseInfoAlterProcessor=void 0;const o=r(n(24));t.DatabaseInfoAlterProcessor=class{constructor(e){this.db=e}createTable(e){this.db.tables.push(e)}dropTable(e){o.default.remove(this.db.tables,t=>t.pureName==e.pureName&&t.schemaName==e.schemaName)}createSqlObject(e){this.db[e.objectTypeField].push(e)}dropSqlObject(e){o.default.remove(this.db[e.objectTypeField],t=>t.pureName==e.pureName&&t.schemaName==e.schemaName)}createColumn(e){const t=this.db.tables.find(t=>t.pureName==e.pureName&&t.schemaName==e.schemaName);if(!t)throw new Error(`createColumn error, cannot find table: ${e.schemaName}.${e.pureName}`);t.columns.push(e)}changeColumn(e,t){const n=this.db.tables.find(t=>t.pureName==e.pureName&&t.schemaName==e.schemaName);if(!n)throw new Error(`changeColumn error, cannot find table: ${e.schemaName}.${e.pureName}`);n.columns=n.columns.map(n=>n.columnName==e.columnName?t:n)}dropColumn(e){const t=this.db.tables.find(t=>t.pureName==e.pureName&&t.schemaName==e.schemaName);if(!t)throw new Error(`dropColumn error, cannot find table: ${e.schemaName}.${e.pureName}`);o.default.remove(t.columns,t=>t.columnName==e.columnName)}createConstraint(e){const t=this.db.tables.find(t=>t.pureName==e.pureName&&t.schemaName==e.schemaName);switch(e.constraintType){case"primaryKey":t.primaryKey=e;break;case"foreignKey":t.foreignKeys.push(e);break;case"index":t.indexes.push(e);break;case"unique":t.uniques.push(e);break;case"check":t.checks.push(e)}}changeConstraint(e,t){this.db.tables.find(t=>t.pureName==e.pureName&&t.schemaName==e.schemaName)}dropConstraint(e){const t=this.db.tables.find(t=>t.pureName==e.pureName&&t.schemaName==e.schemaName);switch(e.constraintType){case"primaryKey":t.primaryKey=null;break;case"foreignKey":t.foreignKeys=t.foreignKeys.filter(t=>t.constraintName!=e.constraintName);break;case"index":t.indexes=t.indexes.filter(t=>t.constraintName!=e.constraintName);break;case"unique":t.uniques=t.uniques.filter(t=>t.constraintName!=e.constraintName);break;case"check":t.checks=t.checks.filter(t=>t.constraintName!=e.constraintName)}}renameTable(e,t){this.db.tables.find(t=>t.pureName==e.pureName&&t.schemaName==e.schemaName).pureName=t}renameColumn(e,t){this.db.tables.find(t=>t.pureName==e.pureName&&t.schemaName==e.schemaName).columns.find(t=>t.columnName==e.columnName).columnName=t}renameConstraint(e,t){}recreateTable(e,t){throw new Error("recreateTable not implemented for DatabaseInfoAlterProcessor")}fillPreloadedRows(e,t,n,r,o){const i=this.db.tables.find(t=>t.pureName==e.pureName&&t.schemaName==e.schemaName);i.preloadedRows=n,i.preloadedRowsKey=r,i.preloadedRowsInsertOnly=o}}},function(e,t,n){var r="undefined"!=typeof JSON?JSON:n(389);e.exports=function(e,t){t||(t={}),"function"==typeof t&&(t={cmp:t});var n=t.space||"";"number"==typeof n&&(n=Array(n+1).join(" "));var s,a="boolean"==typeof t.cycles&&t.cycles,c=t.replacer||function(e,t){return t},u=t.cmp&&(s=t.cmp,function(e){return function(t,n){var r={key:t,value:e[t]},o={key:n,value:e[n]};return s(r,o)}}),l=[];return function e(t,s,f,p){var d=n?"\n"+new Array(p+1).join(n):"",h=n?": ":":";if(f&&f.toJSON&&"function"==typeof f.toJSON&&(f=f.toJSON()),void 0!==(f=c.call(t,s,f))){if("object"!=typeof f||null===f)return r.stringify(f);if(o(f)){for(var m=[],g=0;g<f.length;g++){var y=e(f,g,f[g],p+1)||r.stringify(null);m.push(d+n+y)}return"["+m.join(",")+d+"]"}if(-1!==l.indexOf(f)){if(a)return r.stringify("__cycle__");throw new TypeError("Converting circular structure to JSON")}l.push(f);var b=i(f).sort(u&&u(f));for(m=[],g=0;g<b.length;g++){var v=e(f,s=b[g],f[s],p+1);if(v){var S=r.stringify(s)+h+v;m.push(d+n+S)}}return l.splice(l.indexOf(f),1),"{"+m.join(",")+d+"}"}}({"":e},"",e,0)};var o=Array.isArray||function(e){return"[object Array]"==={}.toString.call(e)},i=Object.keys||function(e){var t=Object.prototype.hasOwnProperty||function(){return!0},n=[];for(var r in e)t.call(e,r)&&n.push(r);return n}},function(e,t,n){t.parse=n(390),t.stringify=n(391)},function(e,t){var n,r,o,i,s={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:"\n",r:"\r",t:"\t"},a=function(e){throw{name:"SyntaxError",message:e,at:n,text:o}},c=function(e){return e&&e!==r&&a("Expected '"+e+"' instead of '"+r+"'"),r=o.charAt(n),n+=1,r},u=function(){var e,t="";for("-"===r&&(t="-",c("-"));r>="0"&&r<="9";)t+=r,c();if("."===r)for(t+=".";c()&&r>="0"&&r<="9";)t+=r;if("e"===r||"E"===r)for(t+=r,c(),"-"!==r&&"+"!==r||(t+=r,c());r>="0"&&r<="9";)t+=r,c();if(e=+t,isFinite(e))return e;a("Bad number")},l=function(){var e,t,n,o="";if('"'===r)for(;c();){if('"'===r)return c(),o;if("\\"===r)if(c(),"u"===r){for(n=0,t=0;t<4&&(e=parseInt(c(),16),isFinite(e));t+=1)n=16*n+e;o+=String.fromCharCode(n)}else{if("string"!=typeof s[r])break;o+=s[r]}else o+=r}a("Bad string")},f=function(){for(;r&&r<=" ";)c()};i=function(){switch(f(),r){case"{":return function(){var e,t={};if("{"===r){if(c("{"),f(),"}"===r)return c("}"),t;for(;r;){if(e=l(),f(),c(":"),Object.hasOwnProperty.call(t,e)&&a('Duplicate key "'+e+'"'),t[e]=i(),f(),"}"===r)return c("}"),t;c(","),f()}}a("Bad object")}();case"[":return function(){var e=[];if("["===r){if(c("["),f(),"]"===r)return c("]"),e;for(;r;){if(e.push(i()),f(),"]"===r)return c("]"),e;c(","),f()}}a("Bad array")}();case'"':return l();case"-":return u();default:return r>="0"&&r<="9"?u():function(){switch(r){case"t":return c("t"),c("r"),c("u"),c("e"),!0;case"f":return c("f"),c("a"),c("l"),c("s"),c("e"),!1;case"n":return c("n"),c("u"),c("l"),c("l"),null}a("Unexpected '"+r+"'")}()}},e.exports=function(e,t){var s;return o=e,n=0,r=" ",s=i(),f(),r&&a("Syntax error"),"function"==typeof t?function e(n,r){var o,i,s=n[r];if(s&&"object"==typeof s)for(o in s)Object.prototype.hasOwnProperty.call(s,o)&&(void 0!==(i=e(s,o))?s[o]=i:delete s[o]);return t.call(n,r,s)}({"":s},""):s}},function(e,t){var n,r,o,i=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,s={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"};function a(e){return i.lastIndex=0,i.test(e)?'"'+e.replace(i,(function(e){var t=s[e];return"string"==typeof t?t:"\\u"+("0000"+e.charCodeAt(0).toString(16)).slice(-4)}))+'"':'"'+e+'"'}e.exports=function(e,t,i){var s;if(n="",r="","number"==typeof i)for(s=0;s<i;s+=1)r+=" ";else"string"==typeof i&&(r=i);if(o=t,t&&"function"!=typeof t&&("object"!=typeof t||"number"!=typeof t.length))throw new Error("JSON.stringify");return function e(t,i){var s,c,u,l,f,p=n,d=i[t];switch(d&&"object"==typeof d&&"function"==typeof d.toJSON&&(d=d.toJSON(t)),"function"==typeof o&&(d=o.call(i,t,d)),typeof d){case"string":return a(d);case"number":return isFinite(d)?String(d):"null";case"boolean":case"null":return String(d);case"object":if(!d)return"null";if(n+=r,f=[],"[object Array]"===Object.prototype.toString.apply(d)){for(l=d.length,s=0;s<l;s+=1)f[s]=e(s,d)||"null";return u=0===f.length?"[]":n?"[\n"+n+f.join(",\n"+n)+"\n"+p+"]":"["+f.join(",")+"]",n=p,u}if(o&&"object"==typeof o)for(l=o.length,s=0;s<l;s+=1)"string"==typeof(c=o[s])&&(u=e(c,d))&&f.push(a(c)+(n?": ":":")+u);else for(c in d)Object.prototype.hasOwnProperty.call(d,c)&&(u=e(c,d))&&f.push(a(c)+(n?": ":":")+u);return u=0===f.length?"{}":n?"{\n"+n+f.join(",\n"+n)+"\n"+p+"}":"{"+f.join(",")+"}",n=p,u}}("",{"":e})}},function(e,t,n){var r=n(39),o=n(393),i=n(394),s=n(41);e.exports=function(e,t){return t=r(t,e),null==(e=i(e,t))||delete e[s(o(t))]}},function(e,t){e.exports=function(e){var t=null==e?0:e.length;return t?e[t-1]:void 0}},function(e,t,n){var r=n(50),o=n(164);e.exports=function(e,t){return t.length<2?e:r(e,o(t,0,-1))}},function(e,t,n){var r=n(73);e.exports=function(e){return r(e)?void 0:e}},function(e,t,n){var r=n(121);e.exports=function(e,t){return r(e,t)}},function(e,t,n){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.editorDeleteConstraint=t.editorModifyConstraint=t.editorAddConstraint=t.editorDeleteColumn=t.editorModifyColumn=t.editorAddColumn=t.fillEditorColumnInfo=void 0;const o=r(n(125)),i=r(n(184)),s=r(n(24));function a(e,t){var n,r;return Object.assign({isPrimaryKey:!!(null===(r=null===(n=null==t?void 0:t.primaryKey)||void 0===n?void 0:n.columns)||void 0===r?void 0:r.find(t=>t.columnName==e.columnName)),dataType:s.default.isEmpty(e)?"int":void 0},e)}function c(e,t,n){if(!(null==t?void 0:t.isPrimaryKey)&&(null==n?void 0:n.isPrimaryKey)){let t=null==e?void 0:e.primaryKey;return t||(t={constraintType:"primaryKey",pureName:e.pureName,schemaName:e.schemaName,columns:[]}),Object.assign(Object.assign({},e),{primaryKey:Object.assign(Object.assign({},t),{columns:[...t.columns,{columnName:n.columnName}]})})}if((null==t?void 0:t.isPrimaryKey)&&!(null==n?void 0:n.isPrimaryKey)){let n=null==e?void 0:e.primaryKey;if(n)return n=Object.assign(Object.assign({},n),{columns:e.primaryKey.columns.filter(e=>e.columnName!=t.columnName)}),0==n.columns.length?Object.assign(Object.assign({},e),{primaryKey:null}):Object.assign(Object.assign({},e),{primaryKey:n})}return e}t.fillEditorColumnInfo=a,t.editorAddColumn=function(e,t){let n=Object.assign(Object.assign({},e),{columns:[...(null==e?void 0:e.columns)||[],Object.assign(Object.assign({},t),{pairingId:(0,o.default)()})]});return n=c(n,null,t),n},t.editorModifyColumn=function(e,t){var n;const r=null===(n=null==e?void 0:e.columns)||void 0===n?void 0:n.find(e=>e.pairingId==t.pairingId);let o=Object.assign(Object.assign({},e),{columns:e.columns.map(e=>e.pairingId==t.pairingId?(0,i.default)(t,["isPrimaryKey"]):e)});return o=c(o,a(r,e),t),o},t.editorDeleteColumn=function(e,t){let n=Object.assign(Object.assign({},e),{columns:e.columns.filter(e=>e.pairingId!=t.pairingId)});return n=c(n,t,null),n},t.editorAddConstraint=function(e,t){const n=Object.assign({},e);return"primaryKey"==t.constraintType&&(n.primaryKey=Object.assign({pairingId:(0,o.default)()},t)),"foreignKey"==t.constraintType&&(n.foreignKeys=[...n.foreignKeys||[],Object.assign({pairingId:(0,o.default)()},t)]),"index"==t.constraintType&&(n.indexes=[...n.indexes||[],Object.assign({pairingId:(0,o.default)()},t)]),"unique"==t.constraintType&&(n.uniques=[...n.uniques||[],Object.assign({pairingId:(0,o.default)()},t)]),n},t.editorModifyConstraint=function(e,t){const n=Object.assign({},e);return"primaryKey"==t.constraintType&&(n.primaryKey=Object.assign(Object.assign({},n.primaryKey),t)),"foreignKey"==t.constraintType&&(n.foreignKeys=e.foreignKeys.map(e=>e.pairingId==t.pairingId?Object.assign(Object.assign({},e),t):e)),"index"==t.constraintType&&(n.indexes=e.indexes.map(e=>e.pairingId==t.pairingId?Object.assign(Object.assign({},e),t):e)),"unique"==t.constraintType&&(n.uniques=e.uniques.map(e=>e.pairingId==t.pairingId?Object.assign(Object.assign({},e),t):e)),n},t.editorDeleteConstraint=function(e,t){const n=Object.assign({},e);return"primaryKey"==t.constraintType&&(n.primaryKey=null),"foreignKey"==t.constraintType&&(n.foreignKeys=e.foreignKeys.filter(e=>e.pairingId!=t.pairingId)),"index"==t.constraintType&&(n.indexes=e.indexes.filter(e=>e.pairingId!=t.pairingId)),"unique"==t.constraintType&&(n.uniques=e.uniques.filter(e=>e.pairingId!=t.pairingId)),n}},function(e,t,n){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.databaseInfoFromYamlModel=t.tableInfoFromYaml=t.tableInfoToYaml=void 0;const o=r(n(101)),i=r(n(52)),s=n(119);function a(e,t){const n={pureName:e.name,columns:e.columns.map(t=>function(e,t){return{pureName:t.name,columnName:e.name,dataType:e.length?`${e.type}(${e.length})`:e.type,autoIncrement:e.autoIncrement,notNull:e.notNull||t.primaryKey&&t.primaryKey.includes(e.name)}}(t,e)),foreignKeys:(0,i.default)(e.columns.filter(e=>e.references).map(n=>function(e,t,n){const r=n.find(t=>t.name==e.references);return r&&r.primaryKey?{constraintType:"foreignKey",pureName:t.name,refTableName:e.references,columns:[{columnName:e.name,refColumnName:r.primaryKey[0]}]}:null}(n,e,t)))};return e.primaryKey&&(n.primaryKey={pureName:e.name,constraintType:"primaryKey",columns:e.primaryKey.map(e=>({columnName:e}))}),n.preloadedRows=e.data,n.preloadedRowsKey=e.insertKey,n.preloadedRowsInsertOnly=e.insertOnly,n}t.tableInfoToYaml=function(e){const t=(0,o.default)(e),n={name:t.pureName,columns:t.columns.map(e=>function(e,t){const n={name:e.columnName,type:e.dataType};e.autoIncrement&&(n.autoIncrement=!0),e.notNull&&(n.notNull=!0);const r=t.foreignKeys&&t.foreignKeys.find(t=>1==t.columns.length&&t.columns[0].columnName==e.columnName);return!r||r.deleteAction&&"NO ACTION"!=r.deleteAction||r.updateAction&&"NO ACTION"!=r.updateAction||(n.references=r.refTableName,r._dumped=!0),n}(e,t))};return t.primaryKey&&!t.primaryKey._dumped&&(n.primaryKey=t.primaryKey.columns.map(e=>e.columnName)),n},t.tableInfoFromYaml=a,t.databaseInfoFromYamlModel=function(e){const t=s.DatabaseAnalyser.createEmptyStructure(),n=[];for(const r of e)(r.name.endsWith(".table.yaml")||r.name.endsWith(".sql"))&&(r.name.endsWith(".table.yaml")&&n.push(r.json),r.name.endsWith(".view.sql")&&t.views.push({pureName:r.name.slice(0,-".view.sql".length),createSql:r.text,columns:[]}),r.name.endsWith(".matview.sql")&&t.matviews.push({pureName:r.name.slice(0,-".matview.sql".length),createSql:r.text,columns:[]}),r.name.endsWith(".proc.sql")&&t.procedures.push({pureName:r.name.slice(0,-".proc.sql".length),createSql:r.text}),r.name.endsWith(".func.sql")&&t.functions.push({pureName:r.name.slice(0,-".func.sql".length),createSql:r.text}),r.name.endsWith(".trigger.sql")&&t.triggers.push({pureName:r.name.slice(0,-".trigger.sql".length),createSql:r.text}));return t.tables=n.map(e=>a(e,n)),t}},function(e,t,n){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.getIconForRedisType=t.isJsonLikeLongString=t.safeJsonParse=t.stringifyCellValue=t.parseCellValue=t.hexStringToArray=t.arrayToHexString=void 0;const o=r(n(72)),i=r(n(12)),s=r(n(73));function a(e){return e.reduce((e,t)=>e+("0"+t.toString(16)).slice(-2),"").toUpperCase()}function c(e){for(var t=e.toString(),n=[],r=0;r<t.length;r+=2)n.push(parseInt(t.substr(r,2),16));return n}t.arrayToHexString=a,t.hexStringToArray=c,t.parseCellValue=function(e){if(!(0,o.default)(e))return e;if("(NULL)"==e)return null;if(e.match(/^0x([0-9a-fA-F][0-9a-fA-F])+$/))return{type:"Buffer",data:c(e.substring(2))};const t=e.match(/^ObjectId\("([0-9a-f]{24})"\)$/);return t?{$oid:t[1]}:e},t.stringifyCellValue=function(e){return null===e?"(NULL)":void 0===e?"(NoField)":"Buffer"==(null==e?void 0:e.type)&&(0,i.default)(e.data)?"0x"+a(e.data):(null==e?void 0:e.$oid)?`ObjectId("${null==e?void 0:e.$oid}")`:(0,s.default)(e)||(0,i.default)(e)?JSON.stringify(e):e},t.safeJsonParse=function(e,t,n=!1){try{return JSON.parse(e)}catch(r){return n&&console.error(`Error parsing JSON value "${e}"`,r),t}},t.isJsonLikeLongString=function(e){return(0,o.default)(e)&&e.length>100&&e.match(/^\s*\{.*\}\s*$|^\s*\[.*\]\s*$/)},t.getIconForRedisType=function(e){switch(e){case"dir":return"img folder";case"string":return"img type-string";case"hash":return"img type-hash";case"set":return"img type-set";case"list":return"img type-list";case"zset":return"img type-zset";case"stream":return"img type-stream";case"binary":return"img type-binary";case"ReJSON-RL":return"img type-rejson";default:return null}}},function(e,t,n){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.getCreateObjectScript=t.computeTableDiffColumns=t.computeDbDiffRows=t.DbDiffCompareDefs=t.computeDiffRowsCore=void 0;const o=n(128),i=r(n(24));function s(e,t,n){const r=[];for(const o of e){const e=t.find(e=>e.pairingId==o.pairingId);if(e){const t=n(o,e);r.push({source:o,target:e,state:t?"equal":"changed",__isChanged:!t})}else r.push({source:o,state:"added",__isAdded:!0})}for(const n of t){e.find(e=>e.pairingId==n.pairingId)||r.push({target:n,state:"removed",__isDeleted:!0})}return r}t.computeDiffRowsCore=s,t.DbDiffCompareDefs={tables:{test:o.testEqualTables,name:"Table",plural:"Tables",icon:"img table"},views:{test:o.testEqualSqlObjects,name:"View",plural:"Views",icon:"img view"},matviews:{test:o.testEqualSqlObjects,name:"Materialized view",plural:"Materialized views",icon:"img view"},procedures:{test:o.testEqualSqlObjects,name:"Procedure",plural:"Procedures",icon:"img procedure"},functions:{test:o.testEqualSqlObjects,name:"Function",plural:"Functions",icon:"img function"}},t.computeDbDiffRows=function(e,n,r,o){if(!e||!n||!o)return[];const a=[];for(const c of["tables","views","procedures","matviews","functions"]){const u=t.DbDiffCompareDefs[c];a.push(...i.default.sortBy(s(e[c],n[c],(t,i)=>u.test(t,i,r,e,n,o)).map(e=>{var t,n,r,o,i,s,a,l;return Object.assign(Object.assign({},e),{sourceSchemaName:null===(t=null==e?void 0:e.source)||void 0===t?void 0:t.schemaName,sourcePureName:null===(n=null==e?void 0:e.source)||void 0===n?void 0:n.pureName,targetSchemaName:null===(r=null==e?void 0:e.target)||void 0===r?void 0:r.schemaName,targetPureName:null===(o=null==e?void 0:e.target)||void 0===o?void 0:o.pureName,typeName:u.name,typeIcon:u.icon,identifier:`${(null===(i=null==e?void 0:e.source)||void 0===i?void 0:i.schemaName)||(null===(s=null==e?void 0:e.target)||void 0===s?void 0:s.schemaName)}.${(null===(a=null==e?void 0:e.source)||void 0===a?void 0:a.pureName)||(null===(l=null==e?void 0:e.target)||void 0===l?void 0:l.pureName)}`,objectTypeField:c})}),"identifier"))}return a},t.computeTableDiffColumns=function(e,t,n,r){return r?s((null==e?void 0:e.columns)||[],(null==t?void 0:t.columns)||[],(e,t)=>(0,o.testEqualColumns)(e,t,!0,!0,n)).map(e=>{var t,n,r,o,i,s;return Object.assign(Object.assign({},e),{sourceColumnName:null===(t=null==e?void 0:e.source)||void 0===t?void 0:t.columnName,targetColumnName:null===(n=null==e?void 0:e.target)||void 0===n?void 0:n.columnName,sourceDataType:null===(r=null==e?void 0:e.source)||void 0===r?void 0:r.dataType,targetDataType:null===(o=null==e?void 0:e.target)||void 0===o?void 0:o.dataType,sourceNotNull:null===(i=null==e?void 0:e.source)||void 0===i?void 0:i.notNull,targetNotNull:null===(s=null==e?void 0:e.target)||void 0===s?void 0:s.notNull})}):[]},t.getCreateObjectScript=function(e,t){if(!e||!t)return"";if("tables"==e.objectTypeField){const n=t.createDumper();return n.createTable(e),n.s}return e.createSql||""}},function(e,t,n){"use strict";var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function s(e){try{c(r.next(e))}catch(e){i(e)}}function a(e){try{c(r.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((r=r.apply(e,t||[])).next())}))},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.enrichWithPreloadedRows=void 0;const i=o(n(24));t.enrichWithPreloadedRows=function(e,t,n,o){var s,a,c;return r(this,void 0,void 0,(function*(){const r={};for(const i of t.tables){const t=e.tables.find(e=>e.pairingId==i.pairingId);if(0==((null===(s=null==t?void 0:t.preloadedRows)||void 0===s?void 0:s.length)||0))continue;const u=t.preloadedRowsKey||(null===(c=null===(a=t.primaryKey)||void 0===a?void 0:a.columns)||void 0===c?void 0:c.map(e=>e.columnName));if(0==((null==u?void 0:u.length)||0))continue;const l=o.createDumper();1==u.length?l.putCmd("^select * ^from %f ^where %i ^in (%,v)",i,u[0],t.preloadedRows.map(e=>e[u[0]])):(l.put("^select * ^from %f ^where",i),l.putCollection(" ^or ",t.preloadedRows,e=>{l.put("("),l.putCollection(" ^and ",u,t=>l.put("%i=%v",t,e[t])),l.put(")")}),l.endCommand());const f=yield o.query(n,l.s);r[i.pairingId]=Object.assign(Object.assign({},i),{preloadedRows:f.rows,preloadedRowsKey:u})}return i.default.isEmpty(r)?t:Object.assign(Object.assign({},t),{tables:t.tables.map(e=>r[e.pairingId]||e)})}))}},function(e,t,n){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.jsonScriptToJavascript=t.ScriptWriterJson=t.ScriptWriter=void 0;const o=r(n(403)),i=n(163);class s{constructor(e="0"){this.s="",this.packageNames=[],this.varCount=0,this.varCount=parseInt(e)||0}allocVariable(e="var"){return this.varCount+=1,`${e}${this.varCount}`}_put(e=""){this.s+=e,this.s+="\n"}endLine(){this._put()}assignCore(e,t,n){this._put(`const ${e} = await ${t}(${JSON.stringify(n)});`)}assign(e,t,n){this.assignCore(e,(0,i.extractShellApiFunctionName)(t),n),this.packageNames.push(...(0,i.extractShellApiPlugins)(t,n))}assignValue(e,t){this._put(`const ${e} = ${JSON.stringify(t)};`)}requirePackage(e){this.packageNames.push(e)}copyStream(e,t,n=null){n?this._put(`await dbgateApi.copyStream(${e}, ${t}, {columns: ${n}});`):this._put(`await dbgateApi.copyStream(${e}, ${t});`)}comment(e){this._put(`// ${e}`)}getScript(e=null){const t=this.packageNames;let n=(0,o.default)(t).map(e=>`// @require ${e}\n`).join("");return e&&(n+=`// @schedule ${e}`),n&&(n+="\n"),n+this.s}}t.ScriptWriter=s;t.ScriptWriterJson=class{constructor(e="0"){this.s="",this.packageNames=[],this.varCount=0,this.commands=[],this.varCount=parseInt(e)||0}allocVariable(e="var"){return this.varCount+=1,`${e}${this.varCount}`}endLine(){this.commands.push({type:"endline"})}assign(e,t,n){this.commands.push({type:"assign",variableName:e,functionName:(0,i.extractShellApiFunctionName)(t),props:n}),this.packageNames.push(...(0,i.extractShellApiPlugins)(t,n))}assignValue(e,t){this.commands.push({type:"assignValue",variableName:e,jsonValue:t})}copyStream(e,t,n=null){this.commands.push({type:"copyStream",sourceVar:e,targetVar:t,colmapVar:n})}comment(e){this.commands.push({type:"comment",text:e})}getScript(e=null){return{type:"json",schedule:e,commands:this.commands,packageNames:this.packageNames}}},t.jsonScriptToJavascript=function(e){const{schedule:t,commands:n,packageNames:r}=e,o=new s;for(const e of r){if(!/^dbgate-plugin-.*$/.test(e))throw new Error("Unallowed package name:"+e);o.packageNames.push(e)}for(const e of n)switch(e.type){case"assign":o.assignCore(e.variableName,e.functionName,e.props);break;case"assignValue":o.assignValue(e.variableName,e.jsonValue);break;case"copyStream":o.copyStream(e.sourceVar,e.targetVar,e.colmapVar);break;case"endLine":o.endLine();break;case"comment":o.comment(e.text)}return o.getScript(t)}},function(e,t,n){var r=n(182);e.exports=function(e){return e&&e.length?r(e):[]}},function(e,t,n){"use strict";var r=n(129),o=n(43),i=n(76),s=n(77),a=n(78),c=n(79),u=n(80),l=n(130),f=n(81),p=n(82),d=n(83),h=n(84),m=n(85),g=n(53),y=n(405),b=n(406),v=n(408),S=n(32),w=S.allocBuffer(17825792),_=function(){};_.prototype.serialize=function(e,t){var n="boolean"==typeof(t=t||{}).checkKeys&&t.checkKeys,r="boolean"==typeof t.serializeFunctions&&t.serializeFunctions,o="boolean"!=typeof t.ignoreUndefined||t.ignoreUndefined,i="number"==typeof t.minInternalBufferSize?t.minInternalBufferSize:17825792;w.length<i&&(w=S.allocBuffer(i));var s=b(w,e,n,0,0,r,o,[]),a=S.allocBuffer(s);return w.copy(a,0,0,a.length),a},_.prototype.serializeWithBufferAndIndex=function(e,t,n){var r="boolean"==typeof(n=n||{}).checkKeys&&n.checkKeys,o="boolean"==typeof n.serializeFunctions&&n.serializeFunctions,i="boolean"!=typeof n.ignoreUndefined||n.ignoreUndefined,s="number"==typeof n.index?n.index:0;return b(t,e,r,s||0,0,o,i)-1},_.prototype.deserialize=function(e,t){return y(e,t)},_.prototype.calculateObjectSize=function(e,t){var n="boolean"==typeof(t=t||{}).serializeFunctions&&t.serializeFunctions,r="boolean"!=typeof t.ignoreUndefined||t.ignoreUndefined;return v(e,n,r)},_.prototype.deserializeStream=function(e,t,n,r,o,i){i=null!=i?i:{};for(var s=t,a=0;a<n;a++){var c=e[s]|e[s+1]<<8|e[s+2]<<16|e[s+3]<<24;i.index=s,r[o+a]=this.deserialize(e,i),s+=c}return s},_.BSON_INT32_MAX=2147483647,_.BSON_INT32_MIN=-2147483648,_.BSON_INT64_MAX=Math.pow(2,63)-1,_.BSON_INT64_MIN=-Math.pow(2,63),_.JS_INT_MAX=9007199254740992,_.JS_INT_MIN=-9007199254740992,_.BSON_DATA_NUMBER=1,_.BSON_DATA_STRING=2,_.BSON_DATA_OBJECT=3,_.BSON_DATA_ARRAY=4,_.BSON_DATA_BINARY=5,_.BSON_DATA_OID=7,_.BSON_DATA_BOOLEAN=8,_.BSON_DATA_DATE=9,_.BSON_DATA_NULL=10,_.BSON_DATA_REGEXP=11,_.BSON_DATA_CODE=13,_.BSON_DATA_SYMBOL=14,_.BSON_DATA_CODE_W_SCOPE=15,_.BSON_DATA_INT=16,_.BSON_DATA_TIMESTAMP=17,_.BSON_DATA_LONG=18,_.BSON_DATA_MIN_KEY=255,_.BSON_DATA_MAX_KEY=127,_.BSON_BINARY_SUBTYPE_DEFAULT=0,_.BSON_BINARY_SUBTYPE_FUNCTION=1,_.BSON_BINARY_SUBTYPE_BYTE_ARRAY=2,_.BSON_BINARY_SUBTYPE_UUID=3,_.BSON_BINARY_SUBTYPE_MD5=4,_.BSON_BINARY_SUBTYPE_USER_DEFINED=128,e.exports=_,e.exports.Code=f,e.exports.Map=r,e.exports.Symbol=u,e.exports.BSON=_,e.exports.DBRef=m,e.exports.Binary=g,e.exports.ObjectID=a,e.exports.Long=o,e.exports.Timestamp=s,e.exports.Double=i,e.exports.Int32=l,e.exports.MinKey=d,e.exports.MaxKey=h,e.exports.BSONRegExp=c,e.exports.Decimal128=p},function(module,exports,__webpack_require__){"use strict";var Long=__webpack_require__(43).Long,Double=__webpack_require__(76).Double,Timestamp=__webpack_require__(77).Timestamp,ObjectID=__webpack_require__(78).ObjectID,Symbol=__webpack_require__(80).Symbol,Code=__webpack_require__(81).Code,MinKey=__webpack_require__(83).MinKey,MaxKey=__webpack_require__(84).MaxKey,Decimal128=__webpack_require__(82),Int32=__webpack_require__(130),DBRef=__webpack_require__(85).DBRef,BSONRegExp=__webpack_require__(79).BSONRegExp,Binary=__webpack_require__(53).Binary,utils=__webpack_require__(32),deserialize=function(e,t,n){var r=(t=null==t?{}:t)&&t.index?t.index:0,o=e[r]|e[r+1]<<8|e[r+2]<<16|e[r+3]<<24;if(o<5||e.length<o||o+r>e.length)throw new Error("corrupt bson message");if(0!==e[r+o-1])throw new Error("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00");return deserializeObject(e,r,t,n)},deserializeObject=function(e,t,n,r){var o=null!=n.evalFunctions&&n.evalFunctions,i=null!=n.cacheFunctions&&n.cacheFunctions,s=null!=n.cacheFunctionsCrc32&&n.cacheFunctionsCrc32;if(!s)var a=null;var c=null==n.fieldsAsRaw?null:n.fieldsAsRaw,u=null!=n.raw&&n.raw,l="boolean"==typeof n.bsonRegExp&&n.bsonRegExp,f=null!=n.promoteBuffers&&n.promoteBuffers,p=null==n.promoteLongs||n.promoteLongs,d=null==n.promoteValues||n.promoteValues,h=t;if(e.length<5)throw new Error("corrupt bson message < 5 bytes long");var m=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(m<5||m>e.length)throw new Error("corrupt bson message");for(var g=r?[]:{},y=0;;){var b=e[t++];if(0===b)break;for(var v=t;0!==e[v]&&v<e.length;)v++;if(v>=e.length)throw new Error("Bad BSON Document: illegal CString");var S=r?y++:e.toString("utf8",t,v);if(t=v+1,b===BSON.BSON_DATA_STRING){var w=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(w<=0||w>e.length-t||0!==e[t+w-1])throw new Error("bad string length in bson");g[S]=e.toString("utf8",t,t+w-1),t+=w}else if(b===BSON.BSON_DATA_OID){var _=utils.allocBuffer(12);e.copy(_,0,t,t+12),g[S]=new ObjectID(_),t+=12}else if(b===BSON.BSON_DATA_INT&&!1===d)g[S]=new Int32(e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24);else if(b===BSON.BSON_DATA_INT)g[S]=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;else if(b===BSON.BSON_DATA_NUMBER&&!1===d)g[S]=new Double(e.readDoubleLE(t)),t+=8;else if(b===BSON.BSON_DATA_NUMBER)g[S]=e.readDoubleLE(t),t+=8;else if(b===BSON.BSON_DATA_DATE){var O=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24,T=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;g[S]=new Date(new Long(O,T).toNumber())}else if(b===BSON.BSON_DATA_BOOLEAN){if(0!==e[t]&&1!==e[t])throw new Error("illegal boolean type value");g[S]=1===e[t++]}else if(b===BSON.BSON_DATA_OBJECT){var C=t,x=e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24;if(x<=0||x>e.length-t)throw new Error("bad embedded document length in bson");g[S]=u?e.slice(t,t+x):deserializeObject(e,C,n,!1),t+=x}else if(b===BSON.BSON_DATA_ARRAY){C=t;var E=n,N=t+(x=e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24);if(c&&c[S]){for(var I in E={},n)E[I]=n[I];E.raw=!0}if(g[S]=deserializeObject(e,C,E,!0),0!==e[(t+=x)-1])throw new Error("invalid array terminator byte");if(t!==N)throw new Error("corrupted array bson")}else if(b===BSON.BSON_DATA_UNDEFINED)g[S]=void 0;else if(b===BSON.BSON_DATA_NULL)g[S]=null;else if(b===BSON.BSON_DATA_LONG){O=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24,T=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;var A=new Long(O,T);g[S]=p&&!0===d&&A.lessThanOrEqual(JS_INT_MAX_LONG)&&A.greaterThanOrEqual(JS_INT_MIN_LONG)?A.toNumber():A}else if(b===BSON.BSON_DATA_DECIMAL128){var k=utils.allocBuffer(16);e.copy(k,0,t,t+16),t+=16;var M=new Decimal128(k);g[S]=M.toObject?M.toObject():M}else if(b===BSON.BSON_DATA_BINARY){var R=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24,j=R,D=e[t++];if(R<0)throw new Error("Negative binary type element size found");if(R>e.length)throw new Error("Binary type size larger than document size");if(null!=e.slice){if(D===Binary.SUBTYPE_BYTE_ARRAY){if((R=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24)<0)throw new Error("Negative binary type element size found for subtype 0x02");if(R>j-4)throw new Error("Binary type with subtype 0x02 contains to long binary size");if(R<j-4)throw new Error("Binary type with subtype 0x02 contains to short binary size")}g[S]=f&&d?e.slice(t,t+R):new Binary(e.slice(t,t+R),D)}else{var P="undefined"!=typeof Uint8Array?new Uint8Array(new ArrayBuffer(R)):new Array(R);if(D===Binary.SUBTYPE_BYTE_ARRAY){if((R=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24)<0)throw new Error("Negative binary type element size found for subtype 0x02");if(R>j-4)throw new Error("Binary type with subtype 0x02 contains to long binary size");if(R<j-4)throw new Error("Binary type with subtype 0x02 contains to short binary size")}for(v=0;v<R;v++)P[v]=e[t+v];g[S]=f&&d?P:new Binary(P,D)}t+=R}else if(b===BSON.BSON_DATA_REGEXP&&!1===l){for(v=t;0!==e[v]&&v<e.length;)v++;if(v>=e.length)throw new Error("Bad BSON Document: illegal CString");var B=e.toString("utf8",t,v);for(v=t=v+1;0!==e[v]&&v<e.length;)v++;if(v>=e.length)throw new Error("Bad BSON Document: illegal CString");var L=e.toString("utf8",t,v);t=v+1;var q=new Array(L.length);for(v=0;v<L.length;v++)switch(L[v]){case"m":q[v]="m";break;case"s":q[v]="g";break;case"i":q[v]="i"}g[S]=new RegExp(B,q.join(""))}else if(b===BSON.BSON_DATA_REGEXP&&!0===l){for(v=t;0!==e[v]&&v<e.length;)v++;if(v>=e.length)throw new Error("Bad BSON Document: illegal CString");for(B=e.toString("utf8",t,v),v=t=v+1;0!==e[v]&&v<e.length;)v++;if(v>=e.length)throw new Error("Bad BSON Document: illegal CString");L=e.toString("utf8",t,v),t=v+1,g[S]=new BSONRegExp(B,L)}else if(b===BSON.BSON_DATA_SYMBOL){if((w=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24)<=0||w>e.length-t||0!==e[t+w-1])throw new Error("bad string length in bson");g[S]=new Symbol(e.toString("utf8",t,t+w-1)),t+=w}else if(b===BSON.BSON_DATA_TIMESTAMP)O=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24,T=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24,g[S]=new Timestamp(O,T);else if(b===BSON.BSON_DATA_MIN_KEY)g[S]=new MinKey;else if(b===BSON.BSON_DATA_MAX_KEY)g[S]=new MaxKey;else if(b===BSON.BSON_DATA_CODE){if((w=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24)<=0||w>e.length-t||0!==e[t+w-1])throw new Error("bad string length in bson");var U=e.toString("utf8",t,t+w-1);if(o)if(i){var z=s?a(U):U;g[S]=isolateEvalWithHash(functionCache,z,U,g)}else g[S]=isolateEval(U);else g[S]=new Code(U);t+=w}else if(b===BSON.BSON_DATA_CODE_W_SCOPE){var $=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if($<13)throw new Error("code_w_scope total size shorter minimum expected length");if((w=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24)<=0||w>e.length-t||0!==e[t+w-1])throw new Error("bad string length in bson");U=e.toString("utf8",t,t+w-1),C=t+=w,x=e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24;var W=deserializeObject(e,C,n,!1);if(t+=x,$<8+x+w)throw new Error("code_w_scope total size is to short, truncating scope");if($>8+x+w)throw new Error("code_w_scope total size is to long, clips outer document");o?(i?(z=s?a(U):U,g[S]=isolateEvalWithHash(functionCache,z,U,g)):g[S]=isolateEval(U),g[S].scope=W):g[S]=new Code(U,W)}else{if(b!==BSON.BSON_DATA_DBPOINTER)throw new Error("Detected unknown BSON type "+b.toString(16)+' for fieldname "'+S+'", are you using the latest BSON parser');if((w=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24)<=0||w>e.length-t||0!==e[t+w-1])throw new Error("bad string length in bson");var F=e.toString("utf8",t,t+w-1);t+=w;var V=utils.allocBuffer(12);e.copy(V,0,t,t+12),_=new ObjectID(V),t+=12;var K=F.split("."),H=K.shift(),Y=K.join(".");g[S]=new DBRef(Y,_,H)}}if(m!==t-h){if(r)throw new Error("corrupt array bson");throw new Error("corrupt object bson")}return null!=g.$id&&(g=new DBRef(g.$ref,g.$id,g.$db)),g},isolateEvalWithHash=function(functionCache,hash,functionString,object){var value=null;return null==functionCache[hash]&&(eval("value = "+functionString),functionCache[hash]=value),functionCache[hash].bind(object)},isolateEval=function(functionString){var value=null;return eval("value = "+functionString),value},BSON={},functionCache=BSON.functionCache={};BSON.BSON_DATA_NUMBER=1,BSON.BSON_DATA_STRING=2,BSON.BSON_DATA_OBJECT=3,BSON.BSON_DATA_ARRAY=4,BSON.BSON_DATA_BINARY=5,BSON.BSON_DATA_UNDEFINED=6,BSON.BSON_DATA_OID=7,BSON.BSON_DATA_BOOLEAN=8,BSON.BSON_DATA_DATE=9,BSON.BSON_DATA_NULL=10,BSON.BSON_DATA_REGEXP=11,BSON.BSON_DATA_DBPOINTER=12,BSON.BSON_DATA_CODE=13,BSON.BSON_DATA_SYMBOL=14,BSON.BSON_DATA_CODE_W_SCOPE=15,BSON.BSON_DATA_INT=16,BSON.BSON_DATA_TIMESTAMP=17,BSON.BSON_DATA_LONG=18,BSON.BSON_DATA_DECIMAL128=19,BSON.BSON_DATA_MIN_KEY=255,BSON.BSON_DATA_MAX_KEY=127,BSON.BSON_BINARY_SUBTYPE_DEFAULT=0,BSON.BSON_BINARY_SUBTYPE_FUNCTION=1,BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY=2,BSON.BSON_BINARY_SUBTYPE_UUID=3,BSON.BSON_BINARY_SUBTYPE_MD5=4,BSON.BSON_BINARY_SUBTYPE_USER_DEFINED=128,BSON.BSON_INT32_MAX=2147483647,BSON.BSON_INT32_MIN=-2147483648,BSON.BSON_INT64_MAX=Math.pow(2,63)-1,BSON.BSON_INT64_MIN=-Math.pow(2,63),BSON.JS_INT_MAX=9007199254740992,BSON.JS_INT_MIN=-9007199254740992;var JS_INT_MAX_LONG=Long.fromNumber(9007199254740992),JS_INT_MIN_LONG=Long.fromNumber(-9007199254740992);module.exports=deserialize},function(e,t,n){"use strict";var r=n(407).writeIEEE754,o=n(43).Long,i=n(129),s=n(53).Binary,a=n(32).normalizedFunctionString,c=/\x00/,u=["$db","$ref","$id","$clusterTime"],l=function(e){return"object"==typeof e&&"[object Date]"===Object.prototype.toString.call(e)},f=function(e){return"[object RegExp]"===Object.prototype.toString.call(e)},p=function(e,t,n,r,o){e[r++]=R.BSON_DATA_STRING;var i=o?e.write(t,r,"ascii"):e.write(t,r,"utf8");e[(r=r+i+1)-1]=0;var s=e.write(n,r+4,"utf8");return e[r+3]=s+1>>24&255,e[r+2]=s+1>>16&255,e[r+1]=s+1>>8&255,e[r]=s+1&255,r=r+4+s,e[r++]=0,r},d=function(e,t,n,i,s){if(Math.floor(n)===n&&n>=R.JS_INT_MIN&&n<=R.JS_INT_MAX)if(n>=R.BSON_INT32_MIN&&n<=R.BSON_INT32_MAX){e[i++]=R.BSON_DATA_INT;var a=s?e.write(t,i,"ascii"):e.write(t,i,"utf8");i+=a,e[i++]=0,e[i++]=255&n,e[i++]=n>>8&255,e[i++]=n>>16&255,e[i++]=n>>24&255}else if(n>=R.JS_INT_MIN&&n<=R.JS_INT_MAX)e[i++]=R.BSON_DATA_NUMBER,i+=a=s?e.write(t,i,"ascii"):e.write(t,i,"utf8"),e[i++]=0,r(e,n,i,"little",52,8),i+=8;else{e[i++]=R.BSON_DATA_LONG,i+=a=s?e.write(t,i,"ascii"):e.write(t,i,"utf8"),e[i++]=0;var c=o.fromNumber(n),u=c.getLowBits(),l=c.getHighBits();e[i++]=255&u,e[i++]=u>>8&255,e[i++]=u>>16&255,e[i++]=u>>24&255,e[i++]=255&l,e[i++]=l>>8&255,e[i++]=l>>16&255,e[i++]=l>>24&255}else e[i++]=R.BSON_DATA_NUMBER,i+=a=s?e.write(t,i,"ascii"):e.write(t,i,"utf8"),e[i++]=0,r(e,n,i,"little",52,8),i+=8;return i},h=function(e,t,n,r,o){return e[r++]=R.BSON_DATA_NULL,r+=o?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0,r},m=function(e,t,n,r,o){return e[r++]=R.BSON_DATA_BOOLEAN,r+=o?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0,e[r++]=n?1:0,r},g=function(e,t,n,r,i){e[r++]=R.BSON_DATA_DATE,r+=i?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0;var s=o.fromNumber(n.getTime()),a=s.getLowBits(),c=s.getHighBits();return e[r++]=255&a,e[r++]=a>>8&255,e[r++]=a>>16&255,e[r++]=a>>24&255,e[r++]=255&c,e[r++]=c>>8&255,e[r++]=c>>16&255,e[r++]=c>>24&255,r},y=function(e,t,n,r,o){if(e[r++]=R.BSON_DATA_REGEXP,r+=o?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0,n.source&&null!=n.source.match(c))throw Error("value "+n.source+" must not contain null bytes");return r+=e.write(n.source,r,"utf8"),e[r++]=0,n.global&&(e[r++]=115),n.ignoreCase&&(e[r++]=105),n.multiline&&(e[r++]=109),e[r++]=0,r},b=function(e,t,n,r,o){if(e[r++]=R.BSON_DATA_REGEXP,r+=o?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0,null!=n.pattern.match(c))throw Error("pattern "+n.pattern+" must not contain null bytes");return r+=e.write(n.pattern,r,"utf8"),e[r++]=0,r+=e.write(n.options.split("").sort().join(""),r,"utf8"),e[r++]=0,r},v=function(e,t,n,r,o){return null===n?e[r++]=R.BSON_DATA_NULL:"MinKey"===n._bsontype?e[r++]=R.BSON_DATA_MIN_KEY:e[r++]=R.BSON_DATA_MAX_KEY,r+=o?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0,r},S=function(e,t,n,r,o){if(e[r++]=R.BSON_DATA_OID,r+=o?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0,"string"==typeof n.id)e.write(n.id,r,"binary");else{if(!n.id||!n.id.copy)throw new Error("object ["+JSON.stringify(n)+"] is not a valid ObjectId");n.id.copy(e,r,0,12)}return r+12},w=function(e,t,n,r,o){e[r++]=R.BSON_DATA_BINARY,r+=o?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0;var i=n.length;return e[r++]=255&i,e[r++]=i>>8&255,e[r++]=i>>16&255,e[r++]=i>>24&255,e[r++]=R.BSON_BINARY_SUBTYPE_DEFAULT,n.copy(e,r,0,i),r+=i},_=function(e,t,n,r,o,i,s,a,c,u){for(var l=0;l<u.length;l++)if(u[l]===n)throw new Error("cyclic dependency detected");u.push(n),e[r++]=Array.isArray(n)?R.BSON_DATA_ARRAY:R.BSON_DATA_OBJECT,r+=c?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0;var f=M(e,n,o,r,i+1,s,a,u);return u.pop(),f},O=function(e,t,n,r,o){return e[r++]=R.BSON_DATA_DECIMAL128,r+=o?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0,n.bytes.copy(e,r,0,16),r+16},T=function(e,t,n,r,o){e[r++]="Long"===n._bsontype?R.BSON_DATA_LONG:R.BSON_DATA_TIMESTAMP,r+=o?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0;var i=n.getLowBits(),s=n.getHighBits();return e[r++]=255&i,e[r++]=i>>8&255,e[r++]=i>>16&255,e[r++]=i>>24&255,e[r++]=255&s,e[r++]=s>>8&255,e[r++]=s>>16&255,e[r++]=s>>24&255,r},C=function(e,t,n,r,o){return e[r++]=R.BSON_DATA_INT,r+=o?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0,e[r++]=255&n,e[r++]=n>>8&255,e[r++]=n>>16&255,e[r++]=n>>24&255,r},x=function(e,t,n,o,i){return e[o++]=R.BSON_DATA_NUMBER,o+=i?e.write(t,o,"ascii"):e.write(t,o,"utf8"),e[o++]=0,r(e,n,o,"little",52,8),o+=8},E=function(e,t,n,r,o,i,s){e[r++]=R.BSON_DATA_CODE,r+=s?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0;var c=a(n),u=e.write(c,r+4,"utf8")+1;return e[r]=255&u,e[r+1]=u>>8&255,e[r+2]=u>>16&255,e[r+3]=u>>24&255,r=r+4+u-1,e[r++]=0,r},N=function(e,t,n,r,o,i,s,a,c){if(n.scope&&"object"==typeof n.scope){e[r++]=R.BSON_DATA_CODE_W_SCOPE;var u=c?e.write(t,r,"ascii"):e.write(t,r,"utf8");r+=u,e[r++]=0;var l=r,f="string"==typeof n.code?n.code:n.code.toString();r+=4;var p=e.write(f,r+4,"utf8")+1;e[r]=255&p,e[r+1]=p>>8&255,e[r+2]=p>>16&255,e[r+3]=p>>24&255,e[r+4+p-1]=0,r=r+p+4;var d=M(e,n.scope,o,r,i+1,s,a);r=d-1;var h=d-l;e[l++]=255&h,e[l++]=h>>8&255,e[l++]=h>>16&255,e[l++]=h>>24&255,e[r++]=0}else{e[r++]=R.BSON_DATA_CODE,r+=u=c?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0,f=n.code.toString();var m=e.write(f,r+4,"utf8")+1;e[r]=255&m,e[r+1]=m>>8&255,e[r+2]=m>>16&255,e[r+3]=m>>24&255,r=r+4+m-1,e[r++]=0}return r},I=function(e,t,n,r,o){e[r++]=R.BSON_DATA_BINARY,r+=o?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0;var i=n.value(!0),a=n.position;return n.sub_type===s.SUBTYPE_BYTE_ARRAY&&(a+=4),e[r++]=255&a,e[r++]=a>>8&255,e[r++]=a>>16&255,e[r++]=a>>24&255,e[r++]=n.sub_type,n.sub_type===s.SUBTYPE_BYTE_ARRAY&&(a-=4,e[r++]=255&a,e[r++]=a>>8&255,e[r++]=a>>16&255,e[r++]=a>>24&255),i.copy(e,r,0,n.position),r+=n.position},A=function(e,t,n,r,o){e[r++]=R.BSON_DATA_SYMBOL,r+=o?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0;var i=e.write(n.value,r+4,"utf8")+1;return e[r]=255&i,e[r+1]=i>>8&255,e[r+2]=i>>16&255,e[r+3]=i>>24&255,r=r+4+i-1,e[r++]=0,r},k=function(e,t,n,r,o,i,s){e[r++]=R.BSON_DATA_OBJECT,r+=s?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0;var a,c=r,u=(a=null!=n.db?M(e,{$ref:n.namespace,$id:n.oid,$db:n.db},!1,r,o+1,i):M(e,{$ref:n.namespace,$id:n.oid},!1,r,o+1,i))-c;return e[c++]=255&u,e[c++]=u>>8&255,e[c++]=u>>16&255,e[c++]=u>>24&255,a},M=function(e,t,n,r,o,s,a,M){r=r||0,(M=M||[]).push(t);var R=r+4;if(Array.isArray(t))for(var j=0;j<t.length;j++){var D=""+j,P=t[j];if(P&&P.toBSON){if("function"!=typeof P.toBSON)throw new Error("toBSON is not a function");P=P.toBSON()}var B=typeof P;if("string"===B)R=p(e,D,P,R,!0);else if("number"===B)R=d(e,D,P,R,!0);else{if("bigint"===B)throw new TypeError("Unsupported type BigInt, please use Decimal128");if("boolean"===B)R=m(e,D,P,R,!0);else if(P instanceof Date||l(P))R=g(e,D,P,R,!0);else if(void 0===P)R=h(e,D,0,R,!0);else if(null===P)R=h(e,D,0,R,!0);else if("ObjectID"===P._bsontype||"ObjectId"===P._bsontype)R=S(e,D,P,R,!0);else if(Buffer.isBuffer(P))R=w(e,D,P,R,!0);else if(P instanceof RegExp||f(P))R=y(e,D,P,R,!0);else if("object"===B&&null==P._bsontype)R=_(e,D,P,R,n,o,s,a,!0,M);else if("object"===B&&"Decimal128"===P._bsontype)R=O(e,D,P,R,!0);else if("Long"===P._bsontype||"Timestamp"===P._bsontype)R=T(e,D,P,R,!0);else if("Double"===P._bsontype)R=x(e,D,P,R,!0);else if("function"==typeof P&&s)R=E(e,D,P,R,0,0,s);else if("Code"===P._bsontype)R=N(e,D,P,R,n,o,s,a,!0);else if("Binary"===P._bsontype)R=I(e,D,P,R,!0);else if("Symbol"===P._bsontype)R=A(e,D,P,R,!0);else if("DBRef"===P._bsontype)R=k(e,D,P,R,o,s,!0);else if("BSONRegExp"===P._bsontype)R=b(e,D,P,R,!0);else if("Int32"===P._bsontype)R=C(e,D,P,R,!0);else if("MinKey"===P._bsontype||"MaxKey"===P._bsontype)R=v(e,D,P,R,!0);else if(void 0!==P._bsontype)throw new TypeError("Unrecognized or invalid _bsontype: "+P._bsontype)}}else if(t instanceof i)for(var L=t.entries(),q=!1;!q;){var U=L.next();if(!(q=U.done)){if(D=U.value[0],B=typeof(P=U.value[1]),"string"==typeof D&&-1===u.indexOf(D)){if(null!=D.match(c))throw Error("key "+D+" must not contain null bytes");if(n){if("$"===D[0])throw Error("key "+D+" must not start with '$'");if(~D.indexOf("."))throw Error("key "+D+" must not contain '.'")}}if("string"===B)R=p(e,D,P,R);else if("number"===B)R=d(e,D,P,R);else{if("bigint"===B)throw new TypeError("Unsupported type BigInt, please use Decimal128");if("boolean"===B)R=m(e,D,P,R);else if(P instanceof Date||l(P))R=g(e,D,P,R);else if(null===P||void 0===P&&!1===a)R=h(e,D,0,R);else if("ObjectID"===P._bsontype||"ObjectId"===P._bsontype)R=S(e,D,P,R);else if(Buffer.isBuffer(P))R=w(e,D,P,R);else if(P instanceof RegExp||f(P))R=y(e,D,P,R);else if("object"===B&&null==P._bsontype)R=_(e,D,P,R,n,o,s,a,!1,M);else if("object"===B&&"Decimal128"===P._bsontype)R=O(e,D,P,R);else if("Long"===P._bsontype||"Timestamp"===P._bsontype)R=T(e,D,P,R);else if("Double"===P._bsontype)R=x(e,D,P,R);else if("Code"===P._bsontype)R=N(e,D,P,R,n,o,s,a);else if("function"==typeof P&&s)R=E(e,D,P,R,0,0,s);else if("Binary"===P._bsontype)R=I(e,D,P,R);else if("Symbol"===P._bsontype)R=A(e,D,P,R);else if("DBRef"===P._bsontype)R=k(e,D,P,R,o,s);else if("BSONRegExp"===P._bsontype)R=b(e,D,P,R);else if("Int32"===P._bsontype)R=C(e,D,P,R);else if("MinKey"===P._bsontype||"MaxKey"===P._bsontype)R=v(e,D,P,R);else if(void 0!==P._bsontype)throw new TypeError("Unrecognized or invalid _bsontype: "+P._bsontype)}}}else{if(t.toBSON){if("function"!=typeof t.toBSON)throw new Error("toBSON is not a function");if(null!=(t=t.toBSON())&&"object"!=typeof t)throw new Error("toBSON function did not return an object")}for(D in t){if((P=t[D])&&P.toBSON){if("function"!=typeof P.toBSON)throw new Error("toBSON is not a function");P=P.toBSON()}if(B=typeof P,"string"==typeof D&&-1===u.indexOf(D)){if(null!=D.match(c))throw Error("key "+D+" must not contain null bytes");if(n){if("$"===D[0])throw Error("key "+D+" must not start with '$'");if(~D.indexOf("."))throw Error("key "+D+" must not contain '.'")}}if("string"===B)R=p(e,D,P,R);else if("number"===B)R=d(e,D,P,R);else{if("bigint"===B)throw new TypeError("Unsupported type BigInt, please use Decimal128");if("boolean"===B)R=m(e,D,P,R);else if(P instanceof Date||l(P))R=g(e,D,P,R);else if(void 0===P)!1===a&&(R=h(e,D,0,R));else if(null===P)R=h(e,D,0,R);else if("ObjectID"===P._bsontype||"ObjectId"===P._bsontype)R=S(e,D,P,R);else if(Buffer.isBuffer(P))R=w(e,D,P,R);else if(P instanceof RegExp||f(P))R=y(e,D,P,R);else if("object"===B&&null==P._bsontype)R=_(e,D,P,R,n,o,s,a,!1,M);else if("object"===B&&"Decimal128"===P._bsontype)R=O(e,D,P,R);else if("Long"===P._bsontype||"Timestamp"===P._bsontype)R=T(e,D,P,R);else if("Double"===P._bsontype)R=x(e,D,P,R);else if("Code"===P._bsontype)R=N(e,D,P,R,n,o,s,a);else if("function"==typeof P&&s)R=E(e,D,P,R,0,0,s);else if("Binary"===P._bsontype)R=I(e,D,P,R);else if("Symbol"===P._bsontype)R=A(e,D,P,R);else if("DBRef"===P._bsontype)R=k(e,D,P,R,o,s);else if("BSONRegExp"===P._bsontype)R=b(e,D,P,R);else if("Int32"===P._bsontype)R=C(e,D,P,R);else if("MinKey"===P._bsontype||"MaxKey"===P._bsontype)R=v(e,D,P,R);else if(void 0!==P._bsontype)throw new TypeError("Unrecognized or invalid _bsontype: "+P._bsontype)}}}M.pop(),e[R++]=0;var z=R-r;return e[r++]=255&z,e[r++]=z>>8&255,e[r++]=z>>16&255,e[r++]=z>>24&255,R},R={BSON_DATA_NUMBER:1,BSON_DATA_STRING:2,BSON_DATA_OBJECT:3,BSON_DATA_ARRAY:4,BSON_DATA_BINARY:5,BSON_DATA_UNDEFINED:6,BSON_DATA_OID:7,BSON_DATA_BOOLEAN:8,BSON_DATA_DATE:9,BSON_DATA_NULL:10,BSON_DATA_REGEXP:11,BSON_DATA_CODE:13,BSON_DATA_SYMBOL:14,BSON_DATA_CODE_W_SCOPE:15,BSON_DATA_INT:16,BSON_DATA_TIMESTAMP:17,BSON_DATA_LONG:18,BSON_DATA_DECIMAL128:19,BSON_DATA_MIN_KEY:255,BSON_DATA_MAX_KEY:127,BSON_BINARY_SUBTYPE_DEFAULT:0,BSON_BINARY_SUBTYPE_FUNCTION:1,BSON_BINARY_SUBTYPE_BYTE_ARRAY:2,BSON_BINARY_SUBTYPE_UUID:3,BSON_BINARY_SUBTYPE_MD5:4,BSON_BINARY_SUBTYPE_USER_DEFINED:128,BSON_INT32_MAX:2147483647,BSON_INT32_MIN:-2147483648};R.BSON_INT64_MAX=Math.pow(2,63)-1,R.BSON_INT64_MIN=-Math.pow(2,63),R.JS_INT_MAX=9007199254740992,R.JS_INT_MIN=-9007199254740992,e.exports=M},function(e,t){t.readIEEE754=function(e,t,n,r,o){var i,s,a="big"===n,c=8*o-r-1,u=(1<<c)-1,l=u>>1,f=-7,p=a?0:o-1,d=a?1:-1,h=e[t+p];for(p+=d,i=h&(1<<-f)-1,h>>=-f,f+=c;f>0;i=256*i+e[t+p],p+=d,f-=8);for(s=i&(1<<-f)-1,i>>=-f,f+=r;f>0;s=256*s+e[t+p],p+=d,f-=8);if(0===i)i=1-l;else{if(i===u)return s?NaN:1/0*(h?-1:1);s+=Math.pow(2,r),i-=l}return(h?-1:1)*s*Math.pow(2,i-r)},t.writeIEEE754=function(e,t,n,r,o,i){var s,a,c,u="big"===r,l=8*i-o-1,f=(1<<l)-1,p=f>>1,d=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,h=u?i-1:0,m=u?-1:1,g=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,s=f):(s=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-s))<1&&(s--,c*=2),(t+=s+p>=1?d/c:d*Math.pow(2,1-p))*c>=2&&(s++,c/=2),s+p>=f?(a=0,s=f):s+p>=1?(a=(t*c-1)*Math.pow(2,o),s+=p):(a=t*Math.pow(2,p-1)*Math.pow(2,o),s=0));o>=8;e[n+h]=255&a,h+=m,a/=256,o-=8);for(s=s<<o|a,l+=o;l>0;e[n+h]=255&s,h+=m,s/=256,l-=8);e[n+h-m]|=128*g}},function(e,t,n){"use strict";var r=n(43).Long,o=n(76).Double,i=n(77).Timestamp,s=n(78).ObjectID,a=n(80).Symbol,c=n(79).BSONRegExp,u=n(81).Code,l=n(82),f=n(83).MinKey,p=n(84).MaxKey,d=n(85).DBRef,h=n(53).Binary,m=n(32).normalizedFunctionString,g=function(e,t,n){var r=5;if(Array.isArray(e))for(var o=0;o<e.length;o++)r+=y(o.toString(),e[o],t,!0,n);else for(var i in e.toBSON&&(e=e.toBSON()),e)r+=y(i,e[i],t,!1,n);return r};function y(e,t,n,y,v){switch(t&&t.toBSON&&(t=t.toBSON()),typeof t){case"string":return 1+Buffer.byteLength(e,"utf8")+1+4+Buffer.byteLength(t,"utf8")+1;case"number":return Math.floor(t)===t&&t>=b.JS_INT_MIN&&t<=b.JS_INT_MAX&&t>=b.BSON_INT32_MIN&&t<=b.BSON_INT32_MAX?(null!=e?Buffer.byteLength(e,"utf8")+1:0)+5:(null!=e?Buffer.byteLength(e,"utf8")+1:0)+9;case"undefined":return y||!v?(null!=e?Buffer.byteLength(e,"utf8")+1:0)+1:0;case"boolean":return(null!=e?Buffer.byteLength(e,"utf8")+1:0)+2;case"object":if(null==t||t instanceof f||t instanceof p||"MinKey"===t._bsontype||"MaxKey"===t._bsontype)return(null!=e?Buffer.byteLength(e,"utf8")+1:0)+1;if(t instanceof s||"ObjectID"===t._bsontype||"ObjectId"===t._bsontype)return(null!=e?Buffer.byteLength(e,"utf8")+1:0)+13;if(t instanceof Date||"object"==typeof(w=t)&&"[object Date]"===Object.prototype.toString.call(w))return(null!=e?Buffer.byteLength(e,"utf8")+1:0)+9;if("undefined"!=typeof Buffer&&Buffer.isBuffer(t))return(null!=e?Buffer.byteLength(e,"utf8")+1:0)+6+t.length;if(t instanceof r||t instanceof o||t instanceof i||"Long"===t._bsontype||"Double"===t._bsontype||"Timestamp"===t._bsontype)return(null!=e?Buffer.byteLength(e,"utf8")+1:0)+9;if(t instanceof l||"Decimal128"===t._bsontype)return(null!=e?Buffer.byteLength(e,"utf8")+1:0)+17;if(t instanceof u||"Code"===t._bsontype)return null!=t.scope&&Object.keys(t.scope).length>0?(null!=e?Buffer.byteLength(e,"utf8")+1:0)+1+4+4+Buffer.byteLength(t.code.toString(),"utf8")+1+g(t.scope,n,v):(null!=e?Buffer.byteLength(e,"utf8")+1:0)+1+4+Buffer.byteLength(t.code.toString(),"utf8")+1;if(t instanceof h||"Binary"===t._bsontype)return t.sub_type===h.SUBTYPE_BYTE_ARRAY?(null!=e?Buffer.byteLength(e,"utf8")+1:0)+(t.position+1+4+1+4):(null!=e?Buffer.byteLength(e,"utf8")+1:0)+(t.position+1+4+1);if(t instanceof a||"Symbol"===t._bsontype)return(null!=e?Buffer.byteLength(e,"utf8")+1:0)+Buffer.byteLength(t.value,"utf8")+4+1+1;if(t instanceof d||"DBRef"===t._bsontype){var S={$ref:t.namespace,$id:t.oid};return null!=t.db&&(S.$db=t.db),(null!=e?Buffer.byteLength(e,"utf8")+1:0)+1+g(S,n,v)}return t instanceof RegExp||"[object RegExp]"===Object.prototype.toString.call(t)?(null!=e?Buffer.byteLength(e,"utf8")+1:0)+1+Buffer.byteLength(t.source,"utf8")+1+(t.global?1:0)+(t.ignoreCase?1:0)+(t.multiline?1:0)+1:t instanceof c||"BSONRegExp"===t._bsontype?(null!=e?Buffer.byteLength(e,"utf8")+1:0)+1+Buffer.byteLength(t.pattern,"utf8")+1+Buffer.byteLength(t.options,"utf8")+1:(null!=e?Buffer.byteLength(e,"utf8")+1:0)+g(t,n,v)+1;case"function":if(t instanceof RegExp||"[object RegExp]"===Object.prototype.toString.call(t)||"[object RegExp]"===String.call(t))return(null!=e?Buffer.byteLength(e,"utf8")+1:0)+1+Buffer.byteLength(t.source,"utf8")+1+(t.global?1:0)+(t.ignoreCase?1:0)+(t.multiline?1:0)+1;if(n&&null!=t.scope&&Object.keys(t.scope).length>0)return(null!=e?Buffer.byteLength(e,"utf8")+1:0)+1+4+4+Buffer.byteLength(m(t),"utf8")+1+g(t.scope,n,v);if(n)return(null!=e?Buffer.byteLength(e,"utf8")+1:0)+1+4+Buffer.byteLength(m(t),"utf8")+1}var w;return 0}var b={BSON_INT32_MAX:2147483647,BSON_INT32_MIN:-2147483648,JS_INT_MAX:9007199254740992,JS_INT_MIN:-9007199254740992};e.exports=g},function(e,t){e.exports=require("assert")},function(e,t){e.exports=require("os")},function(e){e.exports=JSON.parse('{"name":"mongodb","version":"3.6.6","description":"The official MongoDB driver for Node.js","main":"index.js","files":["index.js","lib"],"repository":{"type":"git","url":"git@github.com:mongodb/node-mongodb-native.git"},"keywords":["mongodb","driver","official"],"peerDependenciesMeta":{"kerberos":{"optional":true},"mongodb-client-encryption":{"optional":true},"mongodb-extjson":{"optional":true},"snappy":{"optional":true},"bson-ext":{"optional":true},"aws4":{"optional":true}},"dependencies":{"bl":"^2.2.1","bson":"^1.1.4","denque":"^1.4.1","optional-require":"^1.0.2","safe-buffer":"^5.1.2"},"devDependencies":{"chai":"^4.1.1","chai-subset":"^1.6.0","chalk":"^2.4.2","co":"4.6.0","coveralls":"^2.11.6","eslint":"^7.10.0","eslint-config-prettier":"^6.11.0","eslint-plugin-es":"^3.0.1","eslint-plugin-prettier":"^3.1.3","istanbul":"^0.4.5","jsdoc":"3.5.5","lodash.camelcase":"^4.3.0","mocha":"5.2.0","mocha-sinon":"^2.1.0","mongodb-extjson":"^2.1.1","mongodb-mock-server":"^1.0.1","prettier":"^1.19.1","semver":"^5.5.0","sinon":"^4.3.0","sinon-chai":"^3.2.0","snappy":"^6.3.4","spec-xunit-file":"0.0.1-3","standard-version":"^8.0.2","util.promisify":"^1.0.1","worker-farm":"^1.5.0","wtfnode":"^0.8.0","yargs":"^14.2.0"},"license":"Apache-2.0","engines":{"node":">=4"},"bugs":{"url":"https://github.com/mongodb/node-mongodb-native/issues"},"scripts":{"atlas":"mocha --opts \'{}\' ./test/manual/atlas_connectivity.test.js","check:kerberos":"mocha --opts \'{}\' -t 60000 test/manual/kerberos.test.js","check:ldap":"mocha --opts \'{}\' test/manual/ldap.test.js","check:tls":"mocha --opts \'{}\' test/manual/tls_support.test.js","test":"npm run lint && mocha --recursive test/functional test/unit","test-nolint":"mocha --recursive test/functional test/unit","coverage":"istanbul cover mongodb-test-runner -- -t 60000 test/unit test/functional","lint":"eslint -v && eslint lib test","format":"npm run lint -- --fix","bench":"node test/benchmarks/driverBench/","generate-evergreen":"node .evergreen/generate_evergreen_tasks.js","release":"standard-version -i HISTORY.md"},"homepage":"https://github.com/mongodb/node-mongodb-native","optionalDependencies":{"saslprep":"^1.0.0"}}')},function(e,t){function n(e){var t=new Error("Cannot find module '"+e+"'");throw t.code="MODULE_NOT_FOUND",t}n.keys=function(){return[]},n.resolve=n,e.exports=n,n.id=412},function(e,t){e.exports=require("zlib")},function(e,t,n){"use strict";const r=n(5).inherits,o=n(8).EventEmitter,i=n(3).MongoError,s=n(3).MongoTimeoutError,a=n(3).MongoWriteConcernError,c=n(16),u=n(5).format,l=n(45).Msg,f=n(133),p=n(6).MESSAGE_HEADER_SIZE,d=n(6).COMPRESSION_DETAILS_SIZE,h=n(6).opcodes,m=n(30).compress,g=n(30).compressorIDs,y=n(30).uncompressibleCommands,b=n(191),v=n(22).Buffer,S=n(135),w=n(34).updateSessionFromResponse,_=n(4).eachAsync,O=n(4).makeStateMachine,T=n(0).now,C="destroying",x="destroyed",E=O({disconnected:["connecting","draining","disconnected"],connecting:["connecting","connected","draining","disconnected"],connected:["connected","disconnected","draining"],draining:["draining",C,x],[C]:[C,x],[x]:[x]}),N=new Set(["error","close","timeout","parseError","connect","message"]);var I=0,A=function(e,t){if(o.call(this),this.topology=e,this.s={state:"disconnected",cancellationToken:new o},this.s.cancellationToken.setMaxListeners(1/0),this.options=Object.assign({host:"localhost",port:27017,size:5,minSize:0,connectionTimeout:3e4,socketTimeout:0,keepAlive:!0,keepAliveInitialDelay:12e4,noDelay:!0,ssl:!1,checkServerIdentity:!0,ca:null,crl:null,cert:null,key:null,passphrase:null,rejectUnauthorized:!1,promoteLongs:!0,promoteValues:!0,promoteBuffers:!1,reconnect:!0,reconnectInterval:1e3,reconnectTries:30,domainsEnabled:!1,legacyCompatMode:!0},t),this.id=I++,this.retriesLeft=this.options.reconnectTries,this.reconnectId=null,this.reconnectError=null,!t.bson||t.bson&&("function"!=typeof t.bson.serialize||"function"!=typeof t.bson.deserialize))throw new Error("must pass in valid bson parser");this.logger=c("Pool",t),this.availableConnections=[],this.inUseConnections=[],this.connectingConnections=0,this.executing=!1,this.queue=[],this.numberOfConsecutiveTimeouts=0,this.connectionIndex=0;const n=this;this._messageHandler=function(e){return function(t,n){for(var r=null,o=0;o<n.workItems.length;o++)n.workItems[o].requestId===t.responseTo&&(r=n.workItems[o],n.workItems.splice(o,1));function s(e,t,n,r){if(!e.options.domainsEnabled)return process.nextTick((function(){return t(n,r)}));t(n,r)}if(r&&r.monitoring&&j(n,e.inUseConnections,e.availableConnections),e.numberOfConsecutiveTimeouts=0,r&&r.socketTimeout&&n.resetSocketTimeout(),e.logger.isDebug()&&e.logger.debug(u("message [%s] received from %s:%s",t.raw.toString("hex"),e.options.host,e.options.port)),e.executing||process.nextTick((function(){$(e)()})),r&&!r.immediateRelease){try{t.parse(r)}catch(t){return s(e,r.cb,new i(t))}if(t.documents[0]){const n=t.documents[0],o=r.session;o&&w(o,n),e.topology&&n.$clusterTime&&(e.topology.clusterTime=n.$clusterTime)}if(r.command&&t.documents[0]){const n=t.documents[0];if(n.writeConcernError){const t=new a(n.writeConcernError,n);return s(e,r.cb,t)}if(0===n.ok||n.$err||n.errmsg||n.code)return s(e,r.cb,new i(n))}t.hashedName=n.hashedName,s(e,r.cb,null,new f(r.fullResult?t:t.documents[0],n,t))}}}(this),this._connectionCloseHandler=function(e){M(n,"close",e,this)},this._connectionErrorHandler=function(e){M(n,"error",e,this)},this._connectionTimeoutHandler=function(e){M(n,"timeout",e,this)},this._connectionParseErrorHandler=function(e){M(n,"parseError",e,this)}};function k(e){e.inUseConnections=[],e.availableConnections=[],e.connectingConnections=0,e.executing=!1,e.numberOfConsecutiveTimeouts=0,e.connectionIndex=0,e.retriesLeft=e.options.reconnectTries,e.reconnectId=null}function M(e,t,n,r){if(r){if(r._connectionFailHandled)return;r._connectionFailHandled=!0,r.destroy(),q(e,r),r.flush(n)}if("timeout"===t&&(e.numberOfConsecutiveTimeouts=e.numberOfConsecutiveTimeouts+1,e.numberOfConsecutiveTimeouts>e.options.reconnectTries))return e.numberOfConsecutiveTimeouts=0,e.destroy(!0),e.emit("close",e);0===e.socketCount()&&(e.state!==x&&e.state!==C&&"draining"!==e.state&&e.options.reconnect&&E(e,"disconnected"),t="error"===t?"close":t,e.emit(t,n)),!e.reconnectId&&e.options.reconnect&&(e.reconnectError=n,e.reconnectId=setTimeout(R(e),e.options.reconnectInterval)),D(e)<e.minSize&&U(e)}function R(e,t){return function(){if(e.emit("attemptReconnect",e),e.state!==x&&e.state!==C){if(e.retriesLeft=e.retriesLeft-1,e.retriesLeft<=0){e.destroy();const n=new s(`failed to reconnect after ${e.options.reconnectTries} attempts with interval ${e.options.reconnectInterval} ms`,e.reconnectError);return e.emit("reconnectFailed",n),void("function"==typeof t&&t(n))}e.reconnectId=null,U(e,(n,r)=>{null==n&&(e.reconnectId=null,e.retriesLeft=e.options.reconnectTries,e.emit("reconnect",e)),"function"==typeof t&&t(n,r)})}else"function"==typeof t&&t(new i("Cannot create connection when pool is destroyed"))}}function j(e,t,n){var r=t.indexOf(e);-1!==r&&(t.splice(r,1),n.push(e))}function D(e){return e.availableConnections.length+e.inUseConnections.length+e.connectingConnections}function P(e,t,n,r){E(e,C),e.s.cancellationToken.emit("cancel"),_(t,(e,t)=>{for(const t of N)e.removeAllListeners(t);e.on("error",()=>{}),e.destroy(n,t)},t=>{t?"function"==typeof r&&r(t,null):(k(e),e.queue=[],E(e,x),"function"==typeof r&&r(null,null))})}function B(e,t,n){const r=t.toBin();if(!!!e.options.agreedCompressor||!function(e){const t=e instanceof l?e.command:e.query,n=Object.keys(t)[0];return!y.has(n)}(t))return n(null,r);const o=v.concat(r),i=o.slice(p),s=o.readInt32LE(12);m(e,i,(function(r,o){if(r)return n(r,null);const a=v.alloc(p);a.writeInt32LE(p+d+o.length,0),a.writeInt32LE(t.requestId,4),a.writeInt32LE(0,8),a.writeInt32LE(h.OP_COMPRESSED,12);const c=v.alloc(d);return c.writeInt32LE(s,0),c.writeInt32LE(i.length,4),c.writeUInt8(g[e.options.agreedCompressor],8),n(null,[a,c,o])}))}function L(e,t){for(var n=0;n<t.length;n++)if(t[n]===e)return t.splice(n,1),!0}function q(e,t){L(t,e.availableConnections)||L(t,e.inUseConnections)}function U(e,t){e.state!==x&&e.state!==C?(e.connectingConnections++,S(e.options,e.s.cancellationToken,(n,r)=>(e.connectingConnections--,n?(e.logger.isDebug()&&e.logger.debug(`connection attempt failed with error [${JSON.stringify(n)}]`),!e.reconnectId&&e.options.reconnect?"connecting"===e.state&&e.options.legacyCompatMode?void t(n):(e.reconnectError=n,void(e.reconnectId=setTimeout(R(e,t),e.options.reconnectInterval))):void("function"==typeof t&&t(n))):e.state===x||e.state===C?("function"==typeof t&&t(new i("Pool was destroyed after connection creation")),void r.destroy()):(r.on("error",e._connectionErrorHandler),r.on("close",e._connectionCloseHandler),r.on("timeout",e._connectionTimeoutHandler),r.on("parseError",e._connectionParseErrorHandler),r.on("message",e._messageHandler),e.availableConnections.push(r),"function"==typeof t&&t(null,r),void $(e)())))):"function"==typeof t&&t(new i("Cannot create connection when pool is destroyed"))}function z(e){for(var t=0;t<e.length;t++)if(e[t].monitoring){var n=e[t];e.splice(t,1),n.cb(new i({message:"no connection available for monitoring",driver:!0}))}}function $(e){return function(){if(e.state!==x&&!e.executing)if(e.executing=!0,e.connectingConnections>0)e.executing=!1;else{for(;;){const s=D(e);if(0===e.availableConnections.length){z(e.queue),s<e.options.size&&e.queue.length>0&&U(e);break}if(0===e.queue.length)break;var t=null;const a=e.availableConnections.filter(e=>0===e.workItems.length);if(!(t=0===a.length?e.availableConnections[e.connectionIndex++%e.availableConnections.length]:a[e.connectionIndex++%a.length]).isConnected()){q(e,t),z(e.queue);break}var n=e.queue.shift();if(n.monitoring){var r=!1;for(let n=0;n<e.availableConnections.length;n++)if(e.availableConnections[n].isConnected()&&0===e.availableConnections[n].workItems.length){r=!0,t=e.availableConnections[n];break}if(!r){e.queue.unshift(n),s<e.options.size&&e.queue.length>0&&U(e),setTimeout(()=>$(e)(),10);break}}if(s<e.options.size&&t.workItems.length>0){e.queue.unshift(n),U(e);break}var o=n.buffer;n.monitoring&&j(t,e.availableConnections,e.inUseConnections),n.noResponse||t.workItems.push(n),n.immediateRelease||"number"!=typeof n.socketTimeout||t.setSocketTimeout(n.socketTimeout);var i=!0;if(Array.isArray(o))for(let e=0;e<o.length;e++)i=t.write(o[e]);else i=t.write(o);if(n.noResponse&&"function"==typeof n.cb&&n.cb(null,null),!1===i){e.queue.unshift(n),q(e,t),z(e.queue);break}}e.executing=!1}}}r(A,o),Object.defineProperty(A.prototype,"size",{enumerable:!0,get:function(){return this.options.size}}),Object.defineProperty(A.prototype,"minSize",{enumerable:!0,get:function(){return this.options.minSize}}),Object.defineProperty(A.prototype,"connectionTimeout",{enumerable:!0,get:function(){return this.options.connectionTimeout}}),Object.defineProperty(A.prototype,"socketTimeout",{enumerable:!0,get:function(){return this.options.socketTimeout}}),Object.defineProperty(A.prototype,"state",{enumerable:!0,get:function(){return this.s.state}}),A.prototype.socketCount=function(){return this.availableConnections.length+this.inUseConnections.length},A.prototype.allConnections=function(){return this.availableConnections.concat(this.inUseConnections)},A.prototype.get=function(){return this.allConnections()[0]},A.prototype.isConnected=function(){if(this.state===x||this.state===C)return!1;for(var e=this.availableConnections.concat(this.inUseConnections),t=0;t<e.length;t++)if(e[t].isConnected())return!0;return!1},A.prototype.isDestroyed=function(){return this.state===x||this.state===C},A.prototype.isDisconnected=function(){return"disconnected"===this.state},A.prototype.connect=function(e){if("disconnected"!==this.state)throw new i("connection in unlawful state "+this.state);E(this,"connecting"),U(this,(t,n)=>{if(t)return"function"==typeof e?(this.destroy(),void e(t)):("connecting"===this.state&&this.emit("error",t),void this.destroy());if(E(this,"connected"),this.minSize)for(let e=0;e<this.minSize;e++)U(this);"function"==typeof e?e(null,n):this.emit("connect",this,n)})},A.prototype.auth=function(e,t){"function"==typeof t&&t(null,null)},A.prototype.logout=function(e,t){"function"==typeof t&&t(null,null)},A.prototype.unref=function(){this.availableConnections.concat(this.inUseConnections).forEach((function(e){e.unref()}))},A.prototype.destroy=function(e,t){var n=this;if("function"==typeof e&&(t=e,e=!1),this.state!==x&&n.state!==C){if(E(this,"draining"),e){for(var r=n.availableConnections.concat(n.inUseConnections);n.queue.length>0;){var o=n.queue.shift();"function"==typeof o.cb&&o.cb(new i("Pool was force destroyed"))}return P(n,r,{force:!0},t)}this.reconnectId&&clearTimeout(this.reconnectId),function e(){if(n.state!==x&&n.state!==C)if(z(n.queue),0===n.queue.length){for(var r=n.availableConnections.concat(n.inUseConnections),o=0;o<r.length;o++)if(r[o].workItems.length>0)return setTimeout(e,1);P(n,r,{force:!1},t)}else $(n)(),setTimeout(e,1);else"function"==typeof t&&t()}()}else"function"==typeof t&&t(null,null)},A.prototype.reset=function(e){if("connected"!==this.s.state)return void("function"==typeof e&&e(new i("pool is not connected, reset aborted")));this.s.cancellationToken.emit("cancel");const t=this.availableConnections.concat(this.inUseConnections);_(t,(e,t)=>{for(const t of N)e.removeAllListeners(t);e.destroy({force:!0},t)},t=>{t&&"function"==typeof e?e(t,null):(k(this),U(this,()=>{"function"==typeof e&&e(null,null)}))})},A.prototype.write=function(e,t,n){var r=this;if("function"==typeof t&&(n=t),t=t||{},"function"!=typeof n&&!t.noResponse)throw new i("write method must provide a callback");if(this.state!==x&&this.state!==C)if("draining"!==this.state){if(this.options.domainsEnabled&&process.domain&&"function"==typeof n){var o=n;n=process.domain.bind((function(){for(var e=new Array(arguments.length),t=0;t<arguments.length;t++)e[t]=arguments[t];process.nextTick((function(){o.apply(null,e)}))}))}var s={cb:n,raw:!1,promoteLongs:!0,promoteValues:!0,promoteBuffers:!1,fullResult:!1};s.promoteLongs="boolean"!=typeof t.promoteLongs||t.promoteLongs,s.promoteValues="boolean"!=typeof t.promoteValues||t.promoteValues,s.promoteBuffers="boolean"==typeof t.promoteBuffers&&t.promoteBuffers,s.raw="boolean"==typeof t.raw&&t.raw,s.immediateRelease="boolean"==typeof t.immediateRelease&&t.immediateRelease,s.documentsReturnedIn=t.documentsReturnedIn,s.command="boolean"==typeof t.command&&t.command,s.fullResult="boolean"==typeof t.fullResult&&t.fullResult,s.noResponse="boolean"==typeof t.noResponse&&t.noResponse,s.session=t.session||null,s.socketTimeout=t.socketTimeout,s.monitoring=t.monitoring,s.requestId=e.requestId,r.options.monitorCommands&&(this.emit("commandStarted",new b.CommandStartedEvent(this,e)),s.started=T(),s.cb=(t,o)=>{t?r.emit("commandFailed",new b.CommandFailedEvent(this,e,t,s.started)):o&&o.result&&(0===o.result.ok||o.result.$err)?r.emit("commandFailed",new b.CommandFailedEvent(this,e,o.result,s.started)):r.emit("commandSucceeded",new b.CommandSucceededEvent(this,e,o,s.started)),"function"==typeof n&&n(t,o)}),B(r,e,(e,n)=>{if(e)throw e;s.buffer=n,t.monitoring?r.queue.unshift(s):r.queue.push(s),r.executing||process.nextTick((function(){$(r)()}))})}else n(new i("pool is draining, new operations prohibited"));else n(new i("pool destroyed"))},A._execute=$,e.exports=A},function(e,t){e.exports=require("net")},function(e,t,n){"use strict";const{unassigned_code_points:r,commonly_mapped_to_nothing:o,non_ASCII_space_characters:i,prohibited_characters:s,bidirectional_r_al:a,bidirectional_l:c}=n(417);e.exports=function(e,t={}){if("string"!=typeof e)throw new TypeError("Expected string.");if(0===e.length)return"";const n=p(e).map(e=>u.get(e)?32:e).filter(e=>!l.get(e)),o=String.fromCodePoint.apply(null,n).normalize("NFKC"),i=p(o);if(i.some(e=>s.get(e)))throw new Error("Prohibited character, see https://tools.ietf.org/html/rfc4013#section-2.3");if(!0!==t.allowUnassigned){if(i.some(e=>r.get(e)))throw new Error("Unassigned code point, see https://tools.ietf.org/html/rfc4013#section-2.5")}const d=i.some(e=>a.get(e)),h=i.some(e=>c.get(e));if(d&&h)throw new Error("String must not contain RandALCat and LCat at the same time, see https://tools.ietf.org/html/rfc3454#section-6");const m=a.get(f((y=o,y[0]))),g=a.get(f((e=>e[e.length-1])(o)));var y;if(d&&(!m||!g))throw new Error("Bidirectional RandALCat character must be the first and the last character of the string, see https://tools.ietf.org/html/rfc3454#section-6");return o};const u=i,l=o,f=e=>e.codePointAt(0);function p(e){const t=[],n=e.length;for(let r=0;r<n;r+=1){const o=e.charCodeAt(r);if(o>=55296&&o<=56319&&n>r+1){const n=e.charCodeAt(r+1);if(n>=56320&&n<=57343){t.push(1024*(o-55296)+n-56320+65536),r+=1;continue}}t.push(o)}return t}},function(e,t,n){"use strict";(function(t){const r=n(88),o=n(136),i=n(418),s=r.readFileSync(o.resolve(t,"../code-points.mem"));let a=0;function c(){const e=s.readUInt32BE(a);a+=4;const t=s.slice(a,a+e);return a+=e,i({buffer:t})}const u=c(),l=c(),f=c(),p=c(),d=c(),h=c();e.exports={unassigned_code_points:u,commonly_mapped_to_nothing:l,non_ASCII_space_characters:f,prohibited_characters:p,bidirectional_r_al:d,bidirectional_l:h}}).call(this,"/")},function(e,t,n){var r=n(419);function o(e){if(!(this instanceof o))return new o(e);if(e||(e={}),Buffer.isBuffer(e)&&(e={buffer:e}),this.pageOffset=e.pageOffset||0,this.pageSize=e.pageSize||1024,this.pages=e.pages||r(this.pageSize),this.byteLength=this.pages.length*this.pageSize,this.length=8*this.byteLength,(t=this.pageSize)&t-1)throw new Error("The page size should be a power of two");var t;if(this._trackUpdates=!!e.trackUpdates,this._pageMask=this.pageSize-1,e.buffer){for(var n=0;n<e.buffer.length;n+=this.pageSize)this.pages.set(n/this.pageSize,e.buffer.slice(n,n+this.pageSize));this.byteLength=e.buffer.length,this.length=8*this.byteLength}}e.exports=o,o.prototype.get=function(e){var t=7&e,n=(e-t)/8;return!!(this.getByte(n)&128>>t)},o.prototype.getByte=function(e){var t=e&this._pageMask,n=(e-t)/this.pageSize,r=this.pages.get(n,!0);return r?r.buffer[t+this.pageOffset]:0},o.prototype.set=function(e,t){var n=7&e,r=(e-n)/8,o=this.getByte(r);return this.setByte(r,t?o|128>>n:o&(255^128>>n))},o.prototype.toBuffer=function(){for(var e=function(e){if(Buffer.alloc)return Buffer.alloc(e);var t=new Buffer(e);return t.fill(0),t}(this.pages.length*this.pageSize),t=0;t<this.pages.length;t++){var n=this.pages.get(t,!0),r=t*this.pageSize;n&&n.buffer.copy(e,r,this.pageOffset,this.pageOffset+this.pageSize)}return e},o.prototype.setByte=function(e,t){var n=e&this._pageMask,r=(e-n)/this.pageSize,o=this.pages.get(r,!1);return n+=this.pageOffset,o.buffer[n]!==t&&(o.buffer[n]=t,e>=this.byteLength&&(this.byteLength=e+1,this.length=8*this.byteLength),this._trackUpdates&&this.pages.updated(o),!0)}},function(e,t){function n(e,t){if(!(this instanceof n))return new n(e,t);this.length=0,this.updates=[],this.path=new Uint16Array(4),this.pages=new Array(32768),this.maxPages=this.pages.length,this.level=0,this.pageSize=e||1024,this.deduplicate=t?t.deduplicate:null,this.zeros=this.deduplicate?r(this.deduplicate.length):null}function r(e){if(Buffer.alloc)return Buffer.alloc(e);var t=new Buffer(e);return t.fill(0),t}function o(e,t){this.offset=e*t.length,this.buffer=t,this.updated=!1,this.deduplicate=0}e.exports=n,n.prototype.updated=function(e){for(;this.deduplicate&&e.buffer[e.deduplicate]===this.deduplicate[e.deduplicate];)if(e.deduplicate++,e.deduplicate===this.deduplicate.length){e.deduplicate=0,e.buffer.equals&&e.buffer.equals(this.deduplicate)&&(e.buffer=this.deduplicate);break}!e.updated&&this.updates&&(e.updated=!0,this.updates.push(e))},n.prototype.lastUpdate=function(){if(!this.updates||!this.updates.length)return null;var e=this.updates.pop();return e.updated=!1,e},n.prototype._array=function(e,t){if(e>=this.maxPages){if(t)return;!function(e,t){for(;e.maxPages<t;){var n=e.pages;e.pages=new Array(32768),e.pages[0]=n,e.level++,e.maxPages*=32768}}(this,e)}var n,r;n=e,r=this.path,n=((n=(n-(r[0]=32767&n))/32768)-(r[1]=32767&n))/32768,r[3]=(n-(r[2]=32767&n))/32768&32767;for(var o=this.pages,i=this.level;i>0;i--){var s=this.path[i],a=o[s];if(!a){if(t)return;a=o[s]=new Array(32768)}o=a}return o},n.prototype.get=function(e,t){var n,i,s=this._array(e,t),a=this.path[0],c=s&&s[a];return c||t||(c=s[a]=new o(e,r(this.pageSize)),e>=this.length&&(this.length=e+1)),c&&c.buffer===this.deduplicate&&this.deduplicate&&!t&&(c.buffer=(n=c.buffer,i=Buffer.allocUnsafe?Buffer.allocUnsafe(n.length):new Buffer(n.length),n.copy(i),i),c.deduplicate=0),c},n.prototype.set=function(e,t){var n=this._array(e,!1),i=this.path[0];if(e>=this.length&&(this.length=e+1),!t||this.zeros&&t.equals&&t.equals(this.zeros))n[i]=void 0;else{this.deduplicate&&t.equals&&t.equals(this.deduplicate)&&(t=this.deduplicate);var s=n[i],a=function(e,t){if(e.length===t)return e;if(e.length>t)return e.slice(0,t);var n=r(t);return e.copy(n),n}(t,this.pageSize);s?s.buffer=a:n[i]=new o(e,a)}},n.prototype.toBuffer=function(){for(var e=new Array(this.length),t=r(this.pageSize),n=0;n<e.length;)for(var o=this._array(n,!0),i=0;i<32768&&n<e.length;i++)e[n++]=o&&o[i]?o[i].buffer:t;return Buffer.concat(e)}},function(e,t,n){"use strict";const r=n(33).AuthProvider,o=n(198).MongoCredentials,i=n(3).MongoError,s=n(20),a=n(421),c=n(4).maxWireVersion,u=n(89);let l;try{l=n(422)}catch(e){}const f="http://169.254.169.254",p="/latest/meta-data/iam/security-credentials";function d(e){const t=e.split(".");return 1===t.length||"amazonaws"===t[1]?"us-east-1":t[1]}function h(e,t,n){"function"==typeof t&&(n=t,t={}),t=Object.assign({method:"GET",timeout:1e4,json:!0},u.parse(e),t);const r=a.request(t,e=>{e.setEncoding("utf8");let r="";e.on("data",e=>r+=e),e.on("end",()=>{if(!1!==t.json)try{const e=JSON.parse(r);n(void 0,e)}catch(e){n(new i(`Invalid JSON response: "${r}"`))}else n(void 0,r)})});r.on("error",e=>n(e)),r.end()}e.exports=class extends r{auth(e,t){const n=e.connection,r=e.credentials;if(c(n)<9)return void t(new i("MONGODB-AWS authentication requires MongoDB version 4.4 or later"));if(null==l)return void t(new i("MONGODB-AWS authentication requires the `aws4` module, please install it as a dependency of your project"));if(null==r.username)return void function(e,t){function n(n){null!=n.AccessKeyId&&null!=n.SecretAccessKey&&null!=n.Token?t(void 0,new o({username:n.AccessKeyId,password:n.SecretAccessKey,source:e.source,mechanism:"MONGODB-AWS",mechanismProperties:{AWS_SESSION_TOKEN:n.Token}})):t(new i("Could not obtain temporary MONGODB-AWS credentials"))}if(process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI)return void h(`http://169.254.170.2${process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI}`,(e,r)=>{if(e)return t(e);n(r)});h(`${f}/latest/api/token`,{method:"PUT",json:!1,headers:{"X-aws-ec2-metadata-token-ttl-seconds":30}},(e,r)=>{if(e)return t(e);h(`${f}/${p}`,{json:!1,headers:{"X-aws-ec2-metadata-token":r}},(e,o)=>{if(e)return t(e);h(`${f}/${p}/${o}`,{headers:{"X-aws-ec2-metadata-token":r}},(e,r)=>{if(e)return t(e);n(r)})})})}(r,(n,r)=>{if(n)return t(n);e.credentials=r,this.auth(e,t)});const a=r.username,u=r.password,m=r.source,g=r.mechanismProperties.AWS_SESSION_TOKEN,y=this.bson;s.randomBytes(32,(e,r)=>{if(e)return void t(e);const o={saslStart:1,mechanism:"MONGODB-AWS",payload:y.serialize({r:r,p:110})};n.command(`${m}.$cmd`,o,(e,o)=>{if(e)return t(e);const s=o.result,c=y.deserialize(s.payload.buffer),f=c.h,p=c.s.buffer;if(64!==p.length)return void t(new i(`Invalid server nonce length ${p.length}, expected 64`));if(0!==p.compare(r,0,r.length,0,r.length))return void t(new i("Server nonce does not begin with client nonce"));if(f.length<1||f.length>255||-1!==f.indexOf(".."))return void t(new i(`Server returned an invalid host: "${f}"`));const h="Action=GetCallerIdentity&Version=2011-06-15",b=l.sign({method:"POST",host:f,region:d(c.h),service:"sts",headers:{"Content-Type":"application/x-www-form-urlencoded","Content-Length":h.length,"X-MongoDB-Server-Nonce":p.toString("base64"),"X-MongoDB-GS2-CB-Flag":"n"},path:"/",body:h},{accessKeyId:a,secretAccessKey:u,token:g}),v={a:b.headers.Authorization,d:b.headers["X-Amz-Date"]};g&&(v.t=g);const S={saslContinue:1,conversationId:1,payload:y.serialize(v)};n.command(`${m}.$cmd`,S,e=>{if(e)return t(e);t()})})})}}},function(e,t){e.exports=require("http")},function(e,t,n){var r=t,o=n(89),i=n(137),s=n(20),a=n(423)(1e3);function c(e,t,n){return s.createHmac("sha256",e).update(t,"utf8").digest(n)}function u(e,t){return s.createHash("sha256").update(e,"utf8").digest(t)}function l(e){return e.replace(/[!'()*]/g,(function(e){return"%"+e.charCodeAt(0).toString(16).toUpperCase()}))}function f(e){return l(encodeURIComponent(e))}function p(e,t){"string"==typeof e&&(e=o.parse(e));var n=e.headers=e.headers||{},r=this.matchHost(e.hostname||e.host||n.Host||n.host);this.request=e,this.credentials=t||this.defaultCredentials(),this.service=e.service||r[0]||"",this.region=e.region||r[1]||"us-east-1","email"===this.service&&(this.service="ses"),!e.method&&e.body&&(e.method="POST"),n.Host||n.host||(n.Host=e.hostname||e.host||this.createHost(),e.port&&(n.Host+=":"+e.port)),e.hostname||e.host||(e.hostname=n.Host||n.host),this.isCodeCommitGit="codecommit"===this.service&&"GIT"===e.method}p.prototype.matchHost=function(e){var t=((e||"").match(/([^\.]+)\.(?:([^\.]*)\.)?amazonaws\.com(\.cn)?$/)||[]).slice(1,3);return"es"===t[1]&&(t=t.reverse()),t},p.prototype.isSingleRegion=function(){return["s3","sdb"].indexOf(this.service)>=0&&"us-east-1"===this.region||["cloudfront","ls","route53","iam","importexport","sts"].indexOf(this.service)>=0},p.prototype.createHost=function(){var e=this.isSingleRegion()?"":("s3"===this.service&&"us-east-1"!==this.region?"-":".")+this.region;return("ses"===this.service?"email":this.service)+e+".amazonaws.com"},p.prototype.prepareRequest=function(){this.parsePath();var e,t=this.request,n=t.headers;t.signQuery?(this.parsedPath.query=e=this.parsedPath.query||{},this.credentials.sessionToken&&(e["X-Amz-Security-Token"]=this.credentials.sessionToken),"s3"!==this.service||e["X-Amz-Expires"]||(e["X-Amz-Expires"]=86400),e["X-Amz-Date"]?this.datetime=e["X-Amz-Date"]:e["X-Amz-Date"]=this.getDateTime(),e["X-Amz-Algorithm"]="AWS4-HMAC-SHA256",e["X-Amz-Credential"]=this.credentials.accessKeyId+"/"+this.credentialString(),e["X-Amz-SignedHeaders"]=this.signedHeaders()):(t.doNotModifyHeaders||this.isCodeCommitGit||(!t.body||n["Content-Type"]||n["content-type"]||(n["Content-Type"]="application/x-www-form-urlencoded; charset=utf-8"),!t.body||n["Content-Length"]||n["content-length"]||(n["Content-Length"]=Buffer.byteLength(t.body)),!this.credentials.sessionToken||n["X-Amz-Security-Token"]||n["x-amz-security-token"]||(n["X-Amz-Security-Token"]=this.credentials.sessionToken),"s3"!==this.service||n["X-Amz-Content-Sha256"]||n["x-amz-content-sha256"]||(n["X-Amz-Content-Sha256"]=u(this.request.body||"","hex")),n["X-Amz-Date"]||n["x-amz-date"]?this.datetime=n["X-Amz-Date"]||n["x-amz-date"]:n["X-Amz-Date"]=this.getDateTime()),delete n.Authorization,delete n.authorization)},p.prototype.sign=function(){return this.parsedPath||this.prepareRequest(),this.request.signQuery?this.parsedPath.query["X-Amz-Signature"]=this.signature():this.request.headers.Authorization=this.authHeader(),this.request.path=this.formatPath(),this.request},p.prototype.getDateTime=function(){if(!this.datetime){var e=this.request.headers,t=new Date(e.Date||e.date||new Date);this.datetime=t.toISOString().replace(/[:\-]|\.\d{3}/g,""),this.isCodeCommitGit&&(this.datetime=this.datetime.slice(0,-1))}return this.datetime},p.prototype.getDate=function(){return this.getDateTime().substr(0,8)},p.prototype.authHeader=function(){return["AWS4-HMAC-SHA256 Credential="+this.credentials.accessKeyId+"/"+this.credentialString(),"SignedHeaders="+this.signedHeaders(),"Signature="+this.signature()].join(", ")},p.prototype.signature=function(){var e,t,n,r=this.getDate(),o=[this.credentials.secretAccessKey,r,this.region,this.service].join(),i=a.get(o);return i||(e=c("AWS4"+this.credentials.secretAccessKey,r),t=c(e,this.region),n=c(t,this.service),i=c(n,"aws4_request"),a.set(o,i)),c(i,this.stringToSign(),"hex")},p.prototype.stringToSign=function(){return["AWS4-HMAC-SHA256",this.getDateTime(),this.credentialString(),u(this.canonicalString(),"hex")].join("\n")},p.prototype.canonicalString=function(){this.parsedPath||this.prepareRequest();var e,t=this.parsedPath.path,n=this.parsedPath.query,r=this.request.headers,o="",i="s3"!==this.service,s="s3"===this.service||this.request.doNotEncodePath,a="s3"===this.service,c="s3"===this.service;if(e="s3"===this.service&&this.request.signQuery?"UNSIGNED-PAYLOAD":this.isCodeCommitGit?"":r["X-Amz-Content-Sha256"]||r["x-amz-content-sha256"]||u(this.request.body||"","hex"),n){var l=Object.keys(n).reduce((function(e,t){return t?(e[f(t)]=Array.isArray(n[t])&&c?n[t][0]:n[t],e):e}),{}),p=[];Object.keys(l).sort().forEach((function(e){Array.isArray(l[e])?l[e].map(f).sort().forEach((function(t){p.push(e+"="+t)})):p.push(e+"="+f(l[e]))})),o=p.join("&")}return"/"!==t&&(i&&(t=t.replace(/\/{2,}/g,"/")),"/"!==(t=t.split("/").reduce((function(e,t){return i&&".."===t?e.pop():i&&"."===t||(s&&(t=decodeURIComponent(t).replace(/\+/g," ")),e.push(f(t))),e}),[]).join("/"))[0]&&(t="/"+t),a&&(t=t.replace(/%2F/g,"/"))),[this.request.method||"GET",t,o,this.canonicalHeaders()+"\n",this.signedHeaders(),e].join("\n")},p.prototype.canonicalHeaders=function(){var e=this.request.headers;return Object.keys(e).sort((function(e,t){return e.toLowerCase()<t.toLowerCase()?-1:1})).map((function(t){return t.toLowerCase()+":"+e[t].toString().trim().replace(/\s+/g," ")})).join("\n")},p.prototype.signedHeaders=function(){return Object.keys(this.request.headers).map((function(e){return e.toLowerCase()})).sort().join(";")},p.prototype.credentialString=function(){return[this.getDate(),this.region,this.service,"aws4_request"].join("/")},p.prototype.defaultCredentials=function(){var e=process.env;return{accessKeyId:e.AWS_ACCESS_KEY_ID||e.AWS_ACCESS_KEY,secretAccessKey:e.AWS_SECRET_ACCESS_KEY||e.AWS_SECRET_KEY,sessionToken:e.AWS_SESSION_TOKEN}},p.prototype.parsePath=function(){var e=this.request.path||"/";/[^0-9A-Za-z;,/?:@&=+$\-_.!~*'()#%]/.test(e)&&(e=encodeURI(decodeURI(e)));var t=e.indexOf("?"),n=null;t>=0&&(n=i.parse(e.slice(t+1)),e=e.slice(0,t)),this.parsedPath={path:e,query:n}},p.prototype.formatPath=function(){var e=this.parsedPath.path,t=this.parsedPath.query;return t?(null!=t[""]&&delete t[""],e+"?"+l(i.stringify(t))):e},r.RequestSigner=p,r.sign=function(e,t){return new p(e,t).sign()}},function(e,t){function n(e){this.capacity=0|e,this.map=Object.create(null),this.list=new r}function r(){this.firstNode=null,this.lastNode=null}function o(e,t){this.key=e,this.val=t,this.prev=null,this.next=null}e.exports=function(e){return new n(e)},n.prototype.get=function(e){var t=this.map[e];if(null!=t)return this.used(t),t.val},n.prototype.set=function(e,t){var n=this.map[e];if(null!=n)n.val=t;else{if(this.capacity||this.prune(),!this.capacity)return!1;n=new o(e,t),this.map[e]=n,this.capacity--}return this.used(n),!0},n.prototype.used=function(e){this.list.moveToFront(e)},n.prototype.prune=function(){var e=this.list.pop();null!=e&&(delete this.map[e.key],this.capacity++)},r.prototype.moveToFront=function(e){this.firstNode!=e&&(this.remove(e),null==this.firstNode?(this.firstNode=e,this.lastNode=e,e.prev=null,e.next=null):(e.prev=null,e.next=this.firstNode,e.next.prev=e,this.firstNode=e))},r.prototype.pop=function(){var e=this.lastNode;return null!=e&&this.remove(e),e},r.prototype.remove=function(e){this.firstNode==e?this.firstNode=e.next:null!=e.prev&&(e.prev.next=e.next),this.lastNode==e?this.lastNode=e.prev:null!=e.next&&(e.next.prev=e.prev)}},function(e,t,n){"use strict";const r=n(3).MongoError,o=n(6).collectionNamespace,i=n(55),s=n(0).decorateWithExplain,a=n(90).Explain;e.exports=function(e,t,n,c,u,l,f){if(0===u.length)throw new r(`${t} must contain at least one document`);"function"==typeof l&&(f=l,l={});const p="boolean"!=typeof(l=l||{}).ordered||l.ordered,d=l.writeConcern;let h={};if(h[t]=o(c),h[n]=u,h.ordered=p,d&&Object.keys(d).length>0&&(h.writeConcern=d),l.collation)for(let e=0;e<h[n].length;e++)h[n][e].collation||(h[n][e].collation=l.collation);!0===l.bypassDocumentValidation&&(h.bypassDocumentValidation=l.bypassDocumentValidation);const m=a.fromOptions(l);m&&(h=s(h,m));const g=Object.assign({checkKeys:"insert"===t,numberToReturn:1},l);i(e,c,h,g,f)}},function(e,t,n){"use strict";const r=n(21).KillCursor,o=n(3).MongoError,i=n(3).MongoNetworkError,s=n(6).collectionNamespace,a=n(4).maxWireVersion,c=n(4).emitWarning,u=n(55);e.exports=function(e,t,n,l){l="function"==typeof l?l:()=>{};const f=n.cursorId;if(a(e)<4){const o=e.s.bson,i=e.s.pool,s=new r(o,t,[f]),a={immediateRelease:!0,noResponse:!0};if("object"==typeof n.session&&(a.session=n.session),i&&i.isConnected())try{i.write(s,a,l)}catch(e){"function"==typeof l?l(e,null):c(e)}return}const p={killCursors:s(t),cursors:[f]},d={};"object"==typeof n.session&&(d.session=n.session),u(e,t,p,d,(e,t)=>{if(e)return l(e);const n=t.message;return n.cursorNotFound?l(new i("cursor killed or timed out"),null):Array.isArray(n.documents)&&0!==n.documents.length?void l(null,n.documents[0]):l(new o(`invalid killCursors result returned for cursor id ${f}`))})}},function(e,t,n){"use strict";const r=n(21).GetMore,o=n(9).retrieveBSON,i=n(3).MongoError,s=n(3).MongoNetworkError,a=o().Long,c=n(6).collectionNamespace,u=n(4).maxWireVersion,l=n(6).applyCommonQueryOptions,f=n(55);e.exports=function(e,t,n,o,p,d){p=p||{};const h=u(e);function m(e,t){if(e)return d(e);const r=t.message;if(r.cursorNotFound)return d(new s("cursor killed or timed out"),null);if(h<4){const e="number"==typeof r.cursorId?a.fromNumber(r.cursorId):r.cursorId;return n.documents=r.documents,n.cursorId=e,void d(null,null,r.connection)}if(0===r.documents[0].ok)return d(new i(r.documents[0]));const o="number"==typeof r.documents[0].cursor.id?a.fromNumber(r.documents[0].cursor.id):r.documents[0].cursor.id;n.documents=r.documents[0].cursor.nextBatch,n.cursorId=o,d(null,r.documents[0],r.connection)}if(h<4){const i=e.s.bson,s=new r(i,t,n.cursorId,{numberToReturn:o}),a=l({},n);return void e.s.pool.write(s,a,m)}const g={getMore:n.cursorId instanceof a?n.cursorId:a.fromNumber(n.cursorId),collection:c(t),batchSize:Math.abs(o)};n.cmd.tailable&&"number"==typeof n.cmd.maxAwaitTimeMS&&(g.maxTimeMS=n.cmd.maxAwaitTimeMS);const y=Object.assign({returnFieldSelector:null,documentsReturnedIn:"nextBatch"},p);n.session&&(y.session=n.session),f(e,t,g,y,m)}},function(e,t,n){"use strict";const r=n(21).Query,o=n(3).MongoError,i=n(6).getReadPreference,s=n(6).collectionNamespace,a=n(6).isSharded,c=n(4).maxWireVersion,u=n(6).applyCommonQueryOptions,l=n(55),f=n(0).decorateWithExplain,p=n(90).Explain;e.exports=function(e,t,n,d,h,m){if(h=h||{},null!=d.cursorId)return m();if(null==n)return m(new o(`command ${JSON.stringify(n)} does not return a cursor`));if(c(e)<4){const s=function(e,t,n,s,c){c=c||{};const u=e.s.bson,l=i(n,c);s.batchSize=n.batchSize||s.batchSize;let f=0;f=s.limit<0||0!==s.limit&&s.limit<s.batchSize||s.limit>0&&0===s.batchSize?s.limit:s.batchSize;const p=s.skip||0,d={};a(e)&&l&&(d.$readPreference=l.toJSON());n.sort&&(d.$orderby=n.sort);n.hint&&(d.$hint=n.hint);n.snapshot&&(d.$snapshot=n.snapshot);void 0!==n.returnKey&&(d.$returnKey=n.returnKey);n.maxScan&&(d.$maxScan=n.maxScan);n.min&&(d.$min=n.min);n.max&&(d.$max=n.max);void 0!==n.showDiskLoc&&(d.$showDiskLoc=n.showDiskLoc);n.comment&&(d.$comment=n.comment);n.maxTimeMS&&(d.$maxTimeMS=n.maxTimeMS);void 0!==c.explain&&(f=-Math.abs(n.limit||0),d.$explain=!0);if(d.$query=n.query,n.readConcern&&"local"!==n.readConcern.level)throw new o(`server find command does not support a readConcern level of ${n.readConcern.level}`);n.readConcern&&delete(n=Object.assign({},n)).readConcern;const h="boolean"==typeof c.serializeFunctions&&c.serializeFunctions,m="boolean"==typeof c.ignoreUndefined&&c.ignoreUndefined,g=new r(u,t,d,{numberToSkip:p,numberToReturn:f,pre32Limit:void 0!==n.limit?n.limit:void 0,checkKeys:!1,returnFieldSelector:n.fields,serializeFunctions:h,ignoreUndefined:m});"boolean"==typeof n.tailable&&(g.tailable=n.tailable);"boolean"==typeof n.oplogReplay&&(g.oplogReplay=n.oplogReplay);"boolean"==typeof n.noCursorTimeout&&(g.noCursorTimeout=n.noCursorTimeout);"boolean"==typeof n.awaitData&&(g.awaitData=n.awaitData);"boolean"==typeof n.partial&&(g.partial=n.partial);return g.slaveOk=l.slaveOk(),g}(e,t,n,d,h),c=u({},d);return"string"==typeof s.documentsReturnedIn&&(c.documentsReturnedIn=s.documentsReturnedIn),void e.s.pool.write(s,c,m)}const g=i(n,h);let y=function(e,t,n,r){r.batchSize=n.batchSize||r.batchSize;const o={find:s(t)};n.query&&(n.query.$query?o.filter=n.query.$query:o.filter=n.query);let i=n.sort;if(Array.isArray(i)){const e={};if(i.length>0&&!Array.isArray(i[0])){let t=i[1];"asc"===t?t=1:"desc"===t&&(t=-1),e[i[0]]=t}else for(let t=0;t<i.length;t++){let n=i[t][1];"asc"===n?n=1:"desc"===n&&(n=-1),e[i[t][0]]=n}i=e}"boolean"==typeof n.allowDiskUse&&(o.allowDiskUse=n.allowDiskUse);n.sort&&(o.sort=i);n.fields&&(o.projection=n.fields);n.hint&&(o.hint=n.hint);n.skip&&(o.skip=n.skip);n.limit&&(o.limit=n.limit);n.limit<0&&(o.limit=Math.abs(n.limit),o.singleBatch=!0);"number"==typeof n.batchSize&&(n.batchSize<0&&(0!==n.limit&&Math.abs(n.batchSize)<Math.abs(n.limit)&&(o.limit=Math.abs(n.batchSize)),o.singleBatch=!0),o.batchSize=Math.abs(n.batchSize));n.comment&&(o.comment=n.comment);n.maxScan&&(o.maxScan=n.maxScan);n.maxTimeMS&&(o.maxTimeMS=n.maxTimeMS);n.min&&(o.min=n.min);n.max&&(o.max=n.max);o.returnKey=!!n.returnKey&&n.returnKey,o.showRecordId=!!n.showDiskLoc&&n.showDiskLoc,n.snapshot&&(o.snapshot=n.snapshot);n.tailable&&(o.tailable=n.tailable);n.oplogReplay&&(o.oplogReplay=n.oplogReplay);n.noCursorTimeout&&(o.noCursorTimeout=n.noCursorTimeout);n.awaitData&&(o.awaitData=n.awaitData);n.awaitdata&&(o.awaitData=n.awaitdata);n.partial&&(o.partial=n.partial);n.collation&&(o.collation=n.collation);n.readConcern&&(o.readConcern=n.readConcern);return o}(0,t,n,d);const b=p.fromOptions(h);b&&(y=f(y,b)),n.virtual=!1;const v=Object.assign({documentsReturnedIn:"firstBatch",numberToReturn:1,slaveOk:g.slaveOk()},h);n.readPreference&&(v.readPreference=g),d.session&&(v.session=d.session),l(e,t,y,v,m)}},function(e,t,n){"use strict";const r=n(5).inherits,o=n(5).format,i=n(8).EventEmitter,s=n(10),a=n(17).CoreCursor,c=n(9).retrieveBSON,u=n(16),l=n(3).MongoError,f=n(134),p=n(429),d=n(7).Timeout,h=n(7).Interval,m=n(7).SessionMixins,g=n(7).isRetryableWritesSupported,y=n(4).relayEvents,b=c(),v=n(7).getMMAPError,S=n(4).makeClientMetadata,w=n(7).legacyIsRetryableWriteError,_=n(0).now,O=n(0).calculateDurationInMs;var T="destroyed";function C(e,t){var n={disconnected:["connecting",T,"disconnected"],connecting:["connecting",T,"connected","disconnected"],connected:["connected","disconnected",T,"unreferenced"],unreferenced:["unreferenced",T],destroyed:[T]}[e.state];n&&-1!==n.indexOf(t)?e.state=t:e.s.logger.error(o("Pool with id [%s] failed attempted illegal state transition from [%s] to [%s] only following state allowed [%s]",e.id,e.state,t,n))}var x=1,E=["connect","close","error","timeout","parseError"],N=function(e,t){var n=this;if(t=t||{},!Array.isArray(e))throw new l("seedlist must be an array");if(0===e.length)throw new l("seedlist must contain at least one entry");e.forEach((function(e){if("string"!=typeof e.host||"number"!=typeof e.port)throw new l("seedlist entry must contain a host and port")})),i.call(this),this.id=x++;var r=t.localThresholdMS||15;t.acceptableLatency&&(r=t.acceptableLatency);var s=u("ReplSet",t);this.s={options:Object.assign({metadata:S(t)},t),bson:t.bson||new b([b.Binary,b.Code,b.DBRef,b.Decimal128,b.Double,b.Int32,b.Long,b.Map,b.MaxKey,b.MinKey,b.ObjectId,b.BSONRegExp,b.Symbol,b.Timestamp]),Cursor:t.cursorFactory||a,logger:s,seedlist:e,replicaSetState:new p({id:this.id,setName:t.setName,acceptableLatency:r,heartbeatFrequencyMS:t.haInterval?t.haInterval:1e4,logger:s}),connectingServers:[],haInterval:t.haInterval?t.haInterval:1e4,minHeartbeatFrequencyMS:500,disconnectHandler:t.disconnectHandler,index:0,connectOptions:{},debug:"boolean"==typeof t.debug&&t.debug},this.s.replicaSetState.on("topologyDescriptionChanged",(function(e){n.emit("topologyDescriptionChanged",e)})),this.s.logger.isWarn()&&0!==this.s.options.socketTimeout&&this.s.options.socketTimeout<this.s.haInterval&&this.s.logger.warn(o("warning socketTimeout %s is less than haInterval %s. This might cause unnecessary server reconnections due to socket timeouts",this.s.options.socketTimeout,this.s.haInterval));["joined","left"].forEach((function(e){n.s.replicaSetState.on(e,(function(t,r){n.emit(e,t,r)}))})),this.initialConnectState={connect:!1,fullsetup:!1,all:!1},this.state="disconnected",this.haTimeoutId=null,this.ismaster=null,this.intervalIds=[],this.clusterTime=null};function I(e){e.s.replicaSetState.hasPrimaryAndSecondary()&&e.s.disconnectHandler?e.s.disconnectHandler.execute():e.s.replicaSetState.hasPrimary()&&e.s.disconnectHandler?e.s.disconnectHandler.execute({executePrimary:!0}):e.s.replicaSetState.hasSecondary()&&e.s.disconnectHandler&&e.s.disconnectHandler.execute({executeSecondary:!0})}function A(e,t,n){if(0===t.length)return n();var r=t.length,o=null;function i(){0===(r-=1)&&n(o)}var s=function(e,t){return function(n){if(e.state===T||"unreferenced"===e.state)return this.destroy({force:!0}),i();if("connect"===t)if(e.s.replicaSetState.update(this)){this.lastIsMaster()&&this.lastIsMaster().ismaster&&(e.ismaster=this.lastIsMaster());for(let e=0;e<E.length;e++)this.removeAllListeners(E[e]);this.on("error",j(e,"error")),this.on("close",j(e,"close")),this.on("timeout",j(e,"timeout")),this.on("parseError",j(e,"parseError")),k(this.lastIsMaster().me,e,{}),I(e)}else this.destroy({force:!0});else"error"===t&&(o=n);I(e),i()}};function a(t,n){setTimeout((function(){if(e.state===T||"unreferenced"===e.state)return;const n=e.s.connectingServers.findIndex(e=>e.name===t);if(n>=0){return e.s.connectingServers[n].destroy({force:!0}),e.s.connectingServers.splice(n,1),i()}var r=new f(Object.assign({},e.s.options,{host:t.split(":")[0],port:parseInt(t.split(":")[1],10),reconnect:!1,monitoring:!1,parent:e}));r.once("connect",s(e,"connect")),r.once("close",s(e,"close")),r.once("timeout",s(e,"timeout")),r.once("error",s(e,"error")),r.once("parseError",s(e,"parseError")),r.on("serverOpening",t=>e.emit("serverOpening",t)),r.on("serverDescriptionChanged",t=>e.emit("serverDescriptionChanged",t)),r.on("serverClosed",t=>e.emit("serverClosed",t)),y(r,e,["commandStarted","commandSucceeded","commandFailed"]),e.s.connectingServers.push(r),r.connect(e.s.connectOptions)}),n)}for(var c=0;c<t.length;c++)a(t[c],c)}r(N,i),Object.assign(N.prototype,m),Object.defineProperty(N.prototype,"type",{enumerable:!0,get:function(){return"replset"}}),Object.defineProperty(N.prototype,"parserType",{enumerable:!0,get:function(){return b.native?"c++":"js"}}),Object.defineProperty(N.prototype,"logicalSessionTimeoutMinutes",{enumerable:!0,get:function(){return this.s.replicaSetState.logicalSessionTimeoutMinutes||null}});var k=function(e,t,n){if(!n.haInterval)for(var r=0;r<t.intervalIds.length;r++)if(t.intervalIds[r].__host===e)return;var o=n.haInterval?d:h,i=n.haInterval?n.haInterval:t.s.haInterval,s=new o((function(){if(t.state!==T&&"unreferenced"!==t.state){var n=t.s.replicaSetState.get(e);return n?function(e,t,n){var r=(new Date).getTime();P(e,"serverHeartbeatStarted",{connectionId:t.name}),t.command("admin.$cmd",{ismaster:!0},{monitoring:!0,socketTimeout:e.s.options.connectionTimeout||2e3},(function(o,i){if(e.state===T||"unreferenced"===e.state)return t.destroy({force:!0}),n(o,i);var s=(new Date).getTime()-r;t.lastUpdateTime=_(),o?(P(e,"serverHeartbeatFailed",{durationMS:s,failure:o,connectionId:t.name}),e.s.replicaSetState.remove(t)):(t.ismaster=i.result,t.ismaster.lastWrite&&t.ismaster.lastWrite.lastWriteDate&&(t.lastWriteDate=t.ismaster.lastWrite.lastWriteDate.getTime()),-1===t.lastIsMasterMS?t.lastIsMasterMS=s:t.lastIsMasterMS&&(t.lastIsMasterMS=.2*s+.8*t.lastIsMasterMS),e.s.replicaSetState.update(t)&&t.lastIsMaster()&&t.lastIsMaster().ismaster&&(e.ismaster=t.lastIsMaster()),P(e,"serverHeartbeatSucceeded",{durationMS:s,reply:i.result,connectionId:t.name})),e.s.replicaSetState.updateServerMaxStaleness(t,e.s.haInterval),n(o,i)}))}(t,n,(function(e){e||(t.state!==T&&"unreferenced"!==t.state?(t.intervalIds=t.intervalIds.filter((function(e){return e.isRunning()})),o===d?"connecting"===t.state&&(t.s.replicaSetState.hasSecondary()&&t.s.options.secondaryOnlyConnectionAllowed||t.s.replicaSetState.hasPrimary())&&(C(t,"connected"),process.nextTick((function(){t.emit("connect",t)})),M(t,{})):"disconnected"===t.state&&(t.s.replicaSetState.hasSecondary()&&t.s.options.secondaryOnlyConnectionAllowed||t.s.replicaSetState.hasPrimary())&&(C(t,"connected"),I(t),process.nextTick((function(){t.emit("reconnect",t)}))),t.initialConnectState.connect&&!t.initialConnectState.fullsetup&&t.s.replicaSetState.hasPrimaryAndSecondary()&&(t.initialConnectState.fullsetup=!0,t.initialConnectState.all=!0,process.nextTick((function(){t.emit("fullsetup",t),t.emit("all",t)})))):s.stop())})):void 0}s.stop()}),i);s.start(),s.__host=e,t.intervalIds.push(s)};function M(e,t){if(e.state!==T&&"unreferenced"!==e.state){t=t||{};var n=Object.keys(e.s.replicaSetState.set),r=t.haInterval?d:h,o=t.haInterval?t.haInterval:e.s.haInterval;if(r===d)return A(e,e.s.replicaSetState.unknownServers,(function(r){if(e.state!==T&&"unreferenced"!==e.state){if(!e.s.replicaSetState.hasPrimary()&&!e.s.options.secondaryOnlyConnectionAllowed)return r?e.emit("error",r):(e.emit("error",new l("no primary found in replicaset or invalid replica set name")),e.destroy({force:!0}));if(!e.s.replicaSetState.hasSecondary()&&e.s.options.secondaryOnlyConnectionAllowed)return r?e.emit("error",r):(e.emit("error",new l("no secondary found in replicaset or invalid replica set name")),e.destroy({force:!0}));for(var o=0;o<n.length;o++)k(n[o],e,t)}}));for(var i=0;i<n.length;i++)k(n[i],e,t);var s=e.s.replicaSetState.hasPrimary()?o:e.s.minHeartbeatFrequencyMS;e.intervalIds.push(new d(function e(t){return function(){t.state!==T&&"unreferenced"!==t.state&&A(t,t.s.replicaSetState.unknownServers,(function(){var n=t.s.replicaSetState.hasPrimary()?o:t.s.minHeartbeatFrequencyMS;t.intervalIds.push(new d(e(t),n).start())}))}}(e),s).start())}}function R(e,t){for(var n=0;n<e.length;n++)if(e[n].name.toLowerCase()===t.name.toLowerCase())return!0;e.push(t)}function j(e,t){return function(){e.state!==T&&"unreferenced"!==e.state&&(e.s.logger.isDebug()&&e.s.logger.debug(o("handleEvent %s from server %s in replset with id %s",t,this.name,e.id)),e.s.replicaSetState.remove(this),e.state!==T&&"unreferenced"!==e.state&&((e.s.replicaSetState.hasPrimary()||e.s.replicaSetState.hasSecondary()||!e.s.options.secondaryOnlyConnectionAllowed)&&e.s.replicaSetState.hasPrimary()||C(e,"disconnected"),R(e.s.connectingServers,this)))}}function D(e,t){return function(){if(e.s.logger.isDebug()&&e.s.logger.debug(o("handleInitialConnectEvent %s from server %s in replset with id %s",t,this.name,e.id)),e.state===T||"unreferenced"===e.state)return this.destroy({force:!0});if("connect"===t){var n=e.s.replicaSetState.update(this);if(!0===n){this.lastIsMaster()&&this.lastIsMaster().ismaster&&(e.ismaster=this.lastIsMaster()),e.s.logger.isDebug()&&e.s.logger.debug(o("handleInitialConnectEvent %s from server %s in replset with id %s has state [%s]",t,this.name,e.id,JSON.stringify(e.s.replicaSetState.set)));for(let e=0;e<E.length;e++)this.removeAllListeners(E[e]);this.on("error",j(e,"error")),this.on("close",j(e,"close")),this.on("timeout",j(e,"timeout")),this.on("parseError",j(e,"parseError")),function(e){const t="connecting"===e.state,n=e.s.replicaSetState.hasPrimary(),r=e.s.replicaSetState.hasSecondary(),o=e.s.options.secondaryOnlyConnectionAllowed,i=e.s.connectOptions.readPreference&&e.s.connectOptions.readPreference.equals(s.secondary);return t&&(i&&r||!i&&n)||r&&o}(e)&&(C(e,"connected"),e.initialConnectState.connect=!0,process.nextTick((function(){e.emit("connect",e)})),M(e,{}))}else{if(n instanceof l)return this.destroy({force:!0}),e.destroy({force:!0}),e.emit("error",n);this.destroy({force:!0})}}else e.emit("failed",this),R(e.s.connectingServers,this),e.s.replicaSetState.remove(this);e.initialConnectState.connect&&!e.initialConnectState.fullsetup&&e.s.replicaSetState.hasPrimaryAndSecondary()&&(e.initialConnectState.fullsetup=!0,e.initialConnectState.all=!0,process.nextTick((function(){e.emit("fullsetup",e),e.emit("all",e)})));for(var r=0;r<e.s.connectingServers.length;r++)e.s.connectingServers[r].equals(this)&&e.s.connectingServers.splice(r,1);0===e.s.connectingServers.length&&"connecting"===e.state&&M(e,{haInterval:1})}}function P(e,t,n){e.listeners(t).length>0&&e.emit(t,n)}N.prototype.connect=function(e){var t=this;this.s.connectOptions=e||{},C(this,"connecting");var n=this.s.seedlist.map((function(n){return new f(Object.assign({},t.s.options,n,e,{reconnect:!1,monitoring:!1,parent:t}))}));if(this.s.options.socketTimeout>0&&this.s.options.socketTimeout<=this.s.options.haInterval)return t.emit("error",new l(o("haInterval [%s] MS must be set to less than socketTimeout [%s] MS",this.s.options.haInterval,this.s.options.socketTimeout)));P(this,"topologyOpening",{topologyId:this.id}),function(e,t){e.s.connectingServers=e.s.connectingServers.concat(t);var n=0;function r(t,n){setTimeout((function(){e.s.replicaSetState.update(t)&&t.lastIsMaster()&&t.lastIsMaster().ismaster&&(e.ismaster=t.lastIsMaster()),t.once("close",D(e,"close")),t.once("timeout",D(e,"timeout")),t.once("parseError",D(e,"parseError")),t.once("error",D(e,"error")),t.once("connect",D(e,"connect")),t.on("serverOpening",t=>e.emit("serverOpening",t)),t.on("serverDescriptionChanged",t=>e.emit("serverDescriptionChanged",t)),t.on("serverClosed",t=>e.emit("serverClosed",t)),y(t,e,["commandStarted","commandSucceeded","commandFailed"]),t.connect(e.s.connectOptions)}),n)}for(;t.length>0;)r(t.shift(),n++)}(t,n)},N.prototype.auth=function(e,t){"function"==typeof t&&t(null,null)},N.prototype.destroy=function(e,t){"function"==typeof e&&(t=e,e={}),e=e||{};let n=this.s.connectingServers.length+1;const r=()=>{n--,n>0||(P(this,"topologyClosed",{topologyId:this.id}),"function"==typeof t&&t(null,null))};if(this.state!==T){C(this,T),this.haTimeoutId&&clearTimeout(this.haTimeoutId);for(var o=0;o<this.intervalIds.length;o++)this.intervalIds[o].stop();this.intervalIds=[],0!==n?(this.s.replicaSetState.destroy(e,r),this.s.connectingServers.forEach((function(t){t.destroy(e,r)}))):r()}else"function"==typeof t&&t(null,null)},N.prototype.unref=function(){C(this,"unreferenced"),this.s.replicaSetState.allServers().forEach((function(e){e.unref()})),clearTimeout(this.haTimeoutId)},N.prototype.lastIsMaster=function(){return this.s.options.secondaryOnlyConnectionAllowed&&!this.s.replicaSetState.hasPrimary()&&this.s.replicaSetState.hasSecondary()?this.s.replicaSetState.secondaries[0].lastIsMaster():this.s.replicaSetState.primary?this.s.replicaSetState.primary.lastIsMaster():this.ismaster},N.prototype.connections=function(){for(var e=this.s.replicaSetState.allServers(),t=[],n=0;n<e.length;n++)t=t.concat(e[n].connections());return t},N.prototype.isConnected=function(e){return(e=e||{}).readPreference&&e.readPreference.equals(s.secondary)?this.s.replicaSetState.hasSecondary():e.readPreference&&e.readPreference.equals(s.primary)?this.s.replicaSetState.hasPrimary():e.readPreference&&e.readPreference.equals(s.primaryPreferred)?this.s.replicaSetState.hasSecondary()||this.s.replicaSetState.hasPrimary():e.readPreference&&e.readPreference.equals(s.secondaryPreferred)?this.s.replicaSetState.hasSecondary()||this.s.replicaSetState.hasPrimary():!(!this.s.options.secondaryOnlyConnectionAllowed||!this.s.replicaSetState.hasSecondary())||this.s.replicaSetState.hasPrimary()},N.prototype.isDestroyed=function(){return this.state===T};function B(e,t,n){"function"==typeof t&&(n=t,t={}),t=t||{};const r=e.self,i=e.op,s=e.ns,a=e.ops;if(r.state===T)return n(new l(o("topology was destroyed")));const c=!e.retrying&&!!t.retryWrites&&t.session&&g(r)&&!t.session.inTransaction()&&void 0===t.explain;if(!r.s.replicaSetState.hasPrimary()){if(r.s.disconnectHandler)return r.s.disconnectHandler.add(i,s,a,t,n);if(!c)return n(new l("no primary server found"))}const u=(o,i)=>{if(!o)return n(null,i);if(!w(o,r))return o=v(o),n(o);if(c){return B(Object.assign({},e,{retrying:!0}),t,n)}return r.s.replicaSetState.primary&&(r.s.replicaSetState.primary.destroy(),r.s.replicaSetState.remove(r.s.replicaSetState.primary,{force:!0})),n(o)};n.operationId&&(u.operationId=n.operationId),c&&(t.session.incrementTransactionNumber(),t.willRetryWrite=c),r.s.replicaSetState.primary[i](s,a,t,u)}N.prototype.selectServer=function(e,t,n){let r,o;"function"==typeof e&&void 0===n&&(n=e,e=void 0,t={}),"function"==typeof t&&(n=t,t=e),t=t||{},r=e instanceof s?e:t.readPreference||s.primary;const i=_(),a=()=>{if(O(i)>=1e4)return void(null!=o?n(o,null):n(new l("Server selection timed out")));const e=this.s.replicaSetState.pickServer(r);if(null!=e){if(!(e instanceof f))return o=e,void setTimeout(a,1e3);this.s.debug&&this.emit("pickedServer",t.readPreference,e),n(null,e)}else setTimeout(a,1e3)};a()},N.prototype.getServers=function(){return this.s.replicaSetState.allServers()},N.prototype.insert=function(e,t,n,r){B({self:this,op:"insert",ns:e,ops:t},n,r)},N.prototype.update=function(e,t,n,r){B({self:this,op:"update",ns:e,ops:t},n,r)},N.prototype.remove=function(e,t,n,r){B({self:this,op:"remove",ns:e,ops:t},n,r)};const L=["findAndModify","insert","update","delete"];N.prototype.command=function(e,t,n,r){if("function"==typeof n&&(r=n,n=(n={})||{}),this.state===T)return r(new l(o("topology was destroyed")));var i=this,a=n.readPreference?n.readPreference:s.primary;if("primary"===a.preference&&!this.s.replicaSetState.hasPrimary()&&null!=this.s.disconnectHandler)return this.s.disconnectHandler.add("command",e,t,n,r);if("secondary"===a.preference&&!this.s.replicaSetState.hasSecondary()&&null!=this.s.disconnectHandler)return this.s.disconnectHandler.add("command",e,t,n,r);if("primary"!==a.preference&&!this.s.replicaSetState.hasSecondary()&&!this.s.replicaSetState.hasPrimary()&&null!=this.s.disconnectHandler)return this.s.disconnectHandler.add("command",e,t,n,r);var c=this.s.replicaSetState.pickServer(a);if(!(c instanceof f))return r(c);if(i.s.debug&&i.emit("pickedServer",s.primary,c),null==c)return r(new l(o("no server found that matches the provided readPreference %s",a)));const u=!n.retrying&&!!n.retryWrites&&n.session&&g(i)&&!n.session.inTransaction()&&(p=t,L.some(e=>p[e]));var p;u&&(n.session.incrementTransactionNumber(),n.willRetryWrite=u),c.command(e,t,n,(o,s)=>{if(!o)return r(null,s);if(!w(o,i))return r(o);if(u){const o=Object.assign({},n,{retrying:!0});return this.command(e,t,o,r)}return this.s.replicaSetState.primary&&(this.s.replicaSetState.primary.destroy(),this.s.replicaSetState.remove(this.s.replicaSetState.primary,{force:!0})),r(o)})},N.prototype.cursor=function(e,t,n){const r=(n=n||{}).topology||this;return new(n.cursorFactory||this.s.Cursor)(r,e,t,n)},e.exports=N},function(e,t,n){"use strict";var r=n(5).inherits,o=n(5).format,i=n(7).diff,s=n(8).EventEmitter,a=n(16),c=n(10),u=n(3).MongoError,l=n(22).Buffer,f="ReplicaSetNoPrimary",p="ReplicaSetWithPrimary",d="Unknown",h="PossiblePrimary",m="RSPrimary",g="RSSecondary",y="RSArbiter",b="RSOther",v="RSGhost",S="Unknown",w=function(e){e=e||{},s.call(this),this.topologyType=f,this.setName=e.setName,this.set={},this.id=e.id,this.setName=e.setName,this.logger=e.logger||a("ReplSet",e),this.index=0,this.acceptableLatency=e.acceptableLatency||15,this.heartbeatFrequencyMS=e.heartbeatFrequencyMS||1e4,this.primary=null,this.secondaries=[],this.arbiters=[],this.passives=[],this.ghosts=[],this.unknownServers=[],this.set={},this.maxElectionId=null,this.maxSetVersion=0,this.replicasetDescription={topologyType:"Unknown",servers:[]},this.logicalSessionTimeoutMinutes=void 0};r(w,s),w.prototype.hasPrimaryAndSecondary=function(){return null!=this.primary&&this.secondaries.length>0},w.prototype.hasPrimaryOrSecondary=function(){return this.hasPrimary()||this.hasSecondary()},w.prototype.hasPrimary=function(){return null!=this.primary},w.prototype.hasSecondary=function(){return this.secondaries.length>0},w.prototype.get=function(e){for(var t=this.allServers(),n=0;n<t.length;n++)if(t[n].name.toLowerCase()===e.toLowerCase())return t[n];return null},w.prototype.allServers=function(e){e=e||{};var t=this.primary?[this.primary]:[];return t=t.concat(this.secondaries),e.ignoreArbiters||(t=t.concat(this.arbiters)),t=t.concat(this.passives)},w.prototype.destroy=function(e,t){const n=this.secondaries.concat(this.arbiters).concat(this.passives).concat(this.ghosts);this.primary&&n.push(this.primary);let r=n.length;const o=()=>{r--,r>0||(this.secondaries=[],this.arbiters=[],this.passives=[],this.ghosts=[],this.unknownServers=[],this.set={},this.primary=null,A(this),"function"==typeof t&&t(null,null))};0!==r?n.forEach(t=>t.destroy(e,o)):o()},w.prototype.remove=function(e,t){t=t||{};var n=e.name.toLowerCase(),r=this.primary?[this.primary]:[];r=(r=(r=r.concat(this.secondaries)).concat(this.arbiters)).concat(this.passives);for(var o=0;o<r.length;o++)if(!t.force&&r[o].equals(e)&&r[o].isConnected&&r[o].isConnected())return;this.set[n]&&(this.set[n].type=S,this.set[n].electionId=null,this.set[n].setName=null,this.set[n].setVersion=null);var i=null;this.primary&&this.primary.equals(e)&&(this.primary=null,this.topologyType=f,i="primary"),i=I(e,this.secondaries)?"secondary":i,i=I(e,this.arbiters)?"arbiter":i,i=I(e,this.passives)?"secondary":i,I(e,this.ghosts),I(e,this.unknownServers),this.unknownServers.push(n),i&&this.emit("left",i,e)};const _=e=>e.arbiterOnly&&e.setName;w.prototype.update=function(e){var t=e.lastIsMaster(),n=e.name.toLowerCase();if(t){var r=Array.isArray(t.hosts)?t.hosts:[];r=(r=(r=r.concat(Array.isArray(t.arbiters)?t.arbiters:[])).concat(Array.isArray(t.passives)?t.passives:[])).map((function(e){return e.toLowerCase()}));for(var i=0;i<r.length;i++)-1!==this.unknownServers.indexOf(r[i])||this.set[r[i]]&&this.set[r[i]].type!==S||this.unknownServers.push(r[i].toLowerCase()),this.set[r[i]]||(this.set[r[i]]={type:S,electionId:null,setName:null,setVersion:null})}if(!t&&!x(t,e,this.unknownServers))return this.set[n]={type:S,setVersion:null,electionId:null,setName:null},this.set[n].type=S,this.set[n].electionId=t?t.electionId:t,this.set[n].setName=t?t.setName:t,this.set[n].setVersion=t?t.setVersion:t,-1===this.unknownServers.indexOf(e.name)&&this.unknownServers.push(n),!1;if(void 0===t.logicalSessionTimeoutMinutes||_(t)||(void 0===this.logicalSessionTimeoutMinutes||null===t.logicalSessionTimeoutMinutes?this.logicalSessionTimeoutMinutes=t.logicalSessionTimeoutMinutes:this.logicalSessionTimeoutMinutes=Math.min(this.logicalSessionTimeoutMinutes,t.logicalSessionTimeoutMinutes)),t&&"isdbgrid"===t.msg)return this.primary&&this.primary.name===n&&(this.primary=null,this.topologyType=f),!1;if(t.isreplicaset)return this.set[n]={type:v,setVersion:null,electionId:null,setName:t.setName},this.primary&&this.primary.name===n&&(this.primary=null),this.topologyType=this.primary?p:f,t.setName&&(this.setName=t.setName),!1;if(t.setName&&t.hidden||t.setName&&!t.ismaster&&!t.secondary&&!t.arbiterOnly&&!t.passive)return this.set[n]={type:b,setVersion:null,electionId:null,setName:t.setName},this.topologyType=this.primary?p:f,t.setName&&(this.setName=t.setName),!1;if(t&&t.ismaster&&!t.setName)return this.topologyType=this.primary?p:d,this.remove(e,{force:!0}),!1;if(t&&!t.ismaster&&!t.secondary&&!t.arbiterOnly)return this.remove(e,{force:!0}),!1;if(t.me&&t.me.toLowerCase()!==n)return this.logger.isWarn()&&this.logger.warn(o("the seedlist server was removed due to its address %s not matching its ismaster.me address %s",e.name,t.me)),delete this.set[n],I(e,this.unknownServers),e.destroy({force:!0}),this.primary&&!this.primary.equals(e)?this.topologyType=p:this.topologyType=f,!this.primary&&t.primary&&(this.set[t.primary.toLowerCase()]={type:h,setName:null,electionId:null,setVersion:null}),!1;if(!this.primary&&t.ismaster&&t.setName){var s=e.lastIsMaster().electionId;if(this.setName&&this.setName!==t.setName)return this.topologyType=f,new u(o("setName from ismaster does not match provided connection setName [%s] != [%s]",t.setName,this.setName));if(!this.maxElectionId&&s)this.maxElectionId=s;else if(this.maxElectionId&&s){var a=N(this.maxElectionId,s),c=e.lastIsMaster().setVersion;if(1===a)return this.topologyType=f,!1;if(0===a&&c&&c<this.maxSetVersion)return this.topologyType=f,!1;this.maxSetVersion=c,this.maxElectionId=s}return-1!==t.hosts.map((function(e){return e.toLowerCase()})).indexOf(n)?(this.primary=e,this.set[n]={type:m,setVersion:t.setVersion,electionId:t.electionId,setName:t.setName},this.topologyType=p,t.setName&&(this.setName=t.setName),I(e,this.unknownServers),I(e,this.secondaries),I(e,this.passives),this.emit("joined","primary",e)):this.topologyType=f,A(this),!0}if(t.ismaster&&t.setName){var l=this.set[this.primary.name.toLowerCase()].electionId,w=this.set[this.primary.name.toLowerCase()].setVersion,O=this.set[this.primary.name.toLowerCase()].setName;s=e.lastIsMaster().electionId,c=e.lastIsMaster().setVersion;var T=e.lastIsMaster().setName;if(this.primary.equals(e)&&O===T)return!1;if(O&&O!==T)return this.primary.equals(e)?this.topologyType=f:this.topologyType=p,!1;if(l&&s){if(1===(a=N(l,s)))return!1;if(0===a&&w>c)return!1}else if(!l&&s&&c&&c<this.maxSetVersion)return!1;if(!this.maxElectionId&&s)this.maxElectionId=s;else if(this.maxElectionId&&s){if(1===(a=N(this.maxElectionId,s)))return!1;if(0===a&&w&&c){if(c<this.maxSetVersion)return!1}else if(c<this.maxSetVersion)return!1;this.maxElectionId=s,this.maxSetVersion=c}else this.maxSetVersion=c;return this.set[this.primary.name.toLowerCase()]={type:S,setVersion:null,electionId:null,setName:null},this.emit("left","primary",this.primary),this.primary.destroy({force:!0}),this.primary=e,this.set[n]={type:m,setVersion:t.setVersion,electionId:t.electionId,setName:t.setName},this.topologyType=p,t.setName&&(this.setName=t.setName),I(e,this.unknownServers),I(e,this.secondaries),I(e,this.passives),this.emit("joined","primary",e),A(this),!0}return!this.primary&&t.primary&&(this.set[t.primary.toLowerCase()]={type:h,setVersion:null,electionId:null,setName:null}),t.secondary&&t.setName&&!x(t,e,this.secondaries)&&this.setName&&this.setName===t.setName?(E(this,g,t,e,this.secondaries),this.topologyType=this.primary?p:f,t.setName&&(this.setName=t.setName),I(e,this.unknownServers),this.primary&&this.primary.name.toLowerCase()===n&&(e.destroy({force:!0}),this.primary=null,this.emit("left","primary",e)),this.emit("joined","secondary",e),A(this),!0):_(t)&&!x(t,e,this.arbiters)&&this.setName&&this.setName===t.setName?(E(this,y,t,e,this.arbiters),this.topologyType=this.primary?p:f,t.setName&&(this.setName=t.setName),I(e,this.unknownServers),this.emit("joined","arbiter",e),A(this),!0):t.passive&&t.setName&&!x(t,e,this.passives)&&this.setName&&this.setName===t.setName?(E(this,g,t,e,this.passives),this.topologyType=this.primary?p:f,t.setName&&(this.setName=t.setName),I(e,this.unknownServers),this.primary&&this.primary.name.toLowerCase()===n&&(e.destroy({force:!0}),this.primary=null,this.emit("left","primary",e)),this.emit("joined","secondary",e),A(this),!0):this.set[n]&&this.set[n].type===m?(this.emit("left","primary",this.primary),this.primary.destroy({force:!0}),this.primary=null,this.topologyType=f,!1):(this.topologyType=this.primary?p:f,!1)},w.prototype.updateServerMaxStaleness=function(e,t){for(var n=0,r=0;r<this.secondaries.length;r++)n=Math.max(n,this.secondaries[r].lastWriteDate);e.ismaster.maxWireVersion>=5&&e.ismaster.secondary&&this.hasPrimary()?e.staleness=e.lastUpdateTime-e.lastWriteDate-(this.primary.lastUpdateTime-this.primary.lastWriteDate)+t:e.ismaster.maxWireVersion>=5&&e.ismaster.secondary&&(e.staleness=n-e.lastWriteDate+t)},w.prototype.updateSecondariesMaxStaleness=function(e){for(var t=0;t<this.secondaries.length;t++)this.updateServerMaxStaleness(this.secondaries[t],e)},w.prototype.pickServer=function(e){if("primary"===(e=e||c.primary).preference&&null!=e.maxStalenessSeconds)return new u("primary readPreference incompatible with maxStalenessSeconds");var t=this.primary?[this.primary]:[];if(t=t.concat(this.secondaries),null!=e.maxStalenessSeconds)for(var n=0;n<t.length;n++)if(t[n].ismaster.maxWireVersion<5)return new u("maxStalenessSeconds not supported by at least one of the replicaset members");if("nearest"===e.preference&&null==e.maxStalenessSeconds)return C(this,e);if("nearest"===e.preference&&null!=e.maxStalenessSeconds)return T(this,e);var r=this.secondaries;if(e.equals(c.secondary)&&0===r.length)return new u("no secondary server available");if(e.equals(c.secondaryPreferred)&&0===r.length&&null==this.primary)return new u("no secondary or primary server available");if(e.equals(c.primary)&&null==this.primary)return new u("no primary server available");if(e.equals(c.secondaryPreferred)||e.equals(c.secondary)){if(r.length>0&&null==e.maxStalenessSeconds){var o=C(this,e);if(o)return o}else if(r.length>0&&null!=e.maxStalenessSeconds&&(o=T(this,e)))return o;return e.equals(c.secondaryPreferred)?this.primary:null}if(e.equals(c.primaryPreferred)){if(o=null,this.primary)return this.primary;if(r.length>0&&null==e.maxStalenessSeconds?o=C(this,e):r.length>0&&null!=e.maxStalenessSeconds&&(o=T(this,e)),o)return o}return this.primary};var O=function(e,t){if(null==e.tags)return t;for(var n=[],r=Array.isArray(e.tags)?e.tags:[e.tags],o=0;o<r.length;o++)for(var i=r[o],s=0;s<t.length;s++){var a=t[s].lastIsMaster().tags||{},c=!0;for(var u in i)a[u]!==i[u]&&(c=!1);c&&n.push(t[s])}return n};function T(e,t){var n=[],r=1e3*t.maxStalenessSeconds;if(r<9e4)return new u("maxStalenessSeconds must be set to at least 90 seconds");e.primary&&"secondary"!==t.preference&&"secondaryPreferred"!==t.preference&&n.push(e.primary);for(var o=0;o<e.secondaries.length;o++)n.push(e.secondaries[o]);if(e.primary&&0===n.length&&"secondaryPreferred"!==t.preference&&n.push(e.primary),(n=(n=O(t,n)).filter((function(e){return e.staleness<=r}))).sort((function(e,t){return e.lastIsMasterMS-t.lastIsMasterMS})),0===n.length)return null;e.index=e.index%n.length;var i=n[e.index];return e.index=e.index+1,i}function C(e,t){var n=[];e.primary&&"secondary"!==t.preference&&"secondaryPreferred"!==t.preference&&n.push(e.primary);for(var r=0;r<e.secondaries.length;r++)n.push(e.secondaries[r]);0===n.length&&e.primary&&"secondaryPreferred"!==t.preference&&n.push(e.primary),(n=O(t,n)).sort((function(e,t){return e.lastIsMasterMS-t.lastIsMasterMS}));var o=n.length>0?n[0].lastIsMasterMS:0;if(0===(n=n.filter((function(t){return t.lastIsMasterMS<=o+e.acceptableLatency}))).length)return null;e.index=e.index%n.length;var i=n[e.index];return e.index=e.index+1,i}function x(e,t,n){for(var r=0;r<n.length;r++)if(n[r]&&n[r].name&&n[r].name.toLowerCase()===t.name.toLowerCase())return!0;return!1}function E(e,t,n,r,o){var i=r.name.toLowerCase();e.set[i].type=t,e.set[i].electionId=n?n.electionId:n,e.set[i].setName=n?n.setName:n,e.set[i].setVersion=n?n.setVersion:n,o.push(r)}function N(e,t){var n=l.from(e.toHexString(),"hex"),r=l.from(t.toHexString(),"hex");if(n===r)return 0;if("function"==typeof l.compare)return l.compare(n,r);for(var o=n.length,i=r.length,s=Math.min(o,i),a=0;a<s&&n[a]===r[a];a++);return a!==s&&(o=n[a],i=r[a]),o<i?-1:i<o?1:0}function I(e,t){for(var n=0;n<t.length;n++){if(t[n].equals&&t[n].equals(e))return t.splice(n,1),!0;if("string"==typeof t[n]&&t[n].toLowerCase()===e.name.toLowerCase())return t.splice(n,1),!0}return!1}function A(e){if(e.listeners("topologyDescriptionChanged").length>0){var t="Unknown",n=e.setName;e.hasPrimaryAndSecondary()?t="ReplicaSetWithPrimary":!e.hasPrimary()&&e.hasSecondary()&&(t="ReplicaSetNoPrimary");var r={topologyType:t,setName:n,servers:[]};if(e.hasPrimary()){var o=e.primary.getDescription();o.type="RSPrimary",r.servers.push(o)}r.servers=r.servers.concat(e.secondaries.map((function(e){var t=e.getDescription();return t.type="RSSecondary",t}))),r.servers=r.servers.concat(e.arbiters.map((function(e){var t=e.getDescription();return t.type="RSArbiter",t}))),r.servers=r.servers.concat(e.passives.map((function(e){var t=e.getDescription();return t.type="RSSecondary",t})));var s=i(e.replicasetDescription,r),a={topologyId:e.id,previousDescription:e.replicasetDescription,newDescription:r,diff:s};e.emit("topologyDescriptionChanged",a),e.replicasetDescription=r}}e.exports=w},function(e,t,n){"use strict";const r=n(5).inherits,o=n(5).format,i=n(8).EventEmitter,s=n(17).CoreCursor,a=n(16),c=n(9).retrieveBSON,u=n(3).MongoError,l=n(134),f=n(7).diff,p=n(7).cloneOptions,d=n(7).SessionMixins,h=n(7).isRetryableWritesSupported,m=n(4).relayEvents,g=c(),y=n(7).getMMAPError,b=n(4).makeClientMetadata,v=n(7).legacyIsRetryableWriteError;var S="destroying",w="destroyed";function _(e,t){var n={disconnected:["connecting",S,w,"disconnected"],connecting:["connecting",S,w,"connected","disconnected"],connected:["connected","disconnected",S,w,"unreferenced"],unreferenced:["unreferenced",S,w],destroyed:[w]}[e.state];n&&-1!==n.indexOf(t)?e.state=t:e.s.logger.error(o("Mongos with id [%s] failed attempted illegal state transition from [%s] to [%s] only following state allowed [%s]",e.id,e.state,t,n))}var O=1,T=["connect","close","error","timeout","parseError"],C=function(e,t){t=t||{},this.id=O++,Array.isArray(e)&&(e=e.reduce((e,t)=>e.find(e=>e.host===t.host&&e.port===t.port)?e:(e.push(t),e),[])),this.s={options:Object.assign({metadata:b(t)},t),bson:t.bson||new g([g.Binary,g.Code,g.DBRef,g.Decimal128,g.Double,g.Int32,g.Long,g.Map,g.MaxKey,g.MinKey,g.ObjectId,g.BSONRegExp,g.Symbol,g.Timestamp]),Cursor:t.cursorFactory||s,logger:a("Mongos",t),seedlist:e,haInterval:t.haInterval?t.haInterval:1e4,disconnectHandler:t.disconnectHandler,index:0,connectOptions:{},debug:"boolean"==typeof t.debug&&t.debug,localThresholdMS:t.localThresholdMS||15},this.s.logger.isWarn()&&0!==this.s.options.socketTimeout&&this.s.options.socketTimeout<this.s.haInterval&&this.s.logger.warn(o("warning socketTimeout %s is less than haInterval %s. This might cause unnecessary server reconnections due to socket timeouts",this.s.options.socketTimeout,this.s.haInterval)),this.state="disconnected",this.connectingProxies=[],this.connectedProxies=[],this.disconnectedProxies=[],this.index=0,this.haTimeoutId=null,this.ismaster=null,this.topologyDescription={topologyType:"Unknown",servers:[]},this.clusterTime=null,i.call(this)};function x(e,t,n){e.listeners(t).length>0&&e.emit(t,n)}r(C,i),Object.assign(C.prototype,d),Object.defineProperty(C.prototype,"type",{enumerable:!0,get:function(){return"mongos"}}),Object.defineProperty(C.prototype,"parserType",{enumerable:!0,get:function(){return g.native?"c++":"js"}}),Object.defineProperty(C.prototype,"logicalSessionTimeoutMinutes",{enumerable:!0,get:function(){return this.ismaster&&this.ismaster.logicalSessionTimeoutMinutes||null}});const E=["serverDescriptionChanged","error","close","timeout","parseError"];function N(e,t,n){t=t||{},E.forEach(t=>e.removeAllListeners(t)),e.destroy(t,n)}function I(e){return function(){e.state!==w&&e.state!==S&&(M(e.connectedProxies,e.disconnectedProxies,this),B(e),e.emit("left","mongos",this),e.emit("serverClosed",{topologyId:e.id,address:this.name}))}}function A(e,t){return function(){if(e.state===w)return B(e),M(e.connectingProxies,e.disconnectedProxies,this),this.destroy();if("connect"===t)if(e.ismaster=this.lastIsMaster(),"isdbgrid"===e.ismaster.msg){for(let t=0;t<e.connectedProxies.length;t++)if(e.connectedProxies[t].name===this.name)return M(e.connectingProxies,e.disconnectedProxies,this),B(e),this.destroy(),e.emit("failed",this);for(let e=0;e<T.length;e++)this.removeAllListeners(T[e]);this.on("error",I(e)),this.on("close",I(e)),this.on("timeout",I(e)),this.on("parseError",I(e)),M(e.connectingProxies,e.connectedProxies,this),e.emit("joined","mongos",this)}else{if(e.s.logger.isWarn()){var n="expected mongos proxy, but found replicaset member mongod for server %s";e.ismaster.hosts||(n="expected mongos proxy, but found standalone mongod for server %s"),e.s.logger.warn(o(n,this.name))}this.destroy(!0),R(e.connectingProxies,this),e.emit("left","server",this),e.emit("failed",this)}else M(e.connectingProxies,e.disconnectedProxies,this),e.emit("left","mongos",this),e.emit("failed",this);if(B(e),0===e.connectingProxies.length){if(e.connectedProxies.length>0&&"connecting"===e.state)_(e,"connected"),e.emit("connect",e),e.emit("fullsetup",e),e.emit("all",e);else if(0===e.disconnectedProxies.length)return e.s.logger.isWarn()&&e.s.logger.warn(o("no mongos proxies found in seed list, did you mean to connect to a replicaset")),e.emit("error",new u("no mongos proxies found in seed list"));!function e(t,n){if(n=n||{},t.state===w||t.state===S||"unreferenced"===t.state)return;t.haTimeoutId=setTimeout((function(){if(t.state!==w&&t.state!==S&&"unreferenced"!==t.state){t.isConnected()&&t.s.disconnectHandler&&t.s.disconnectHandler.execute();var r=t.connectedProxies.slice(0),o=r.length;if(0===r.length)return t.listeners("close").length>0&&"connecting"===t.state?t.emit("error",new u("no mongos proxy available")):t.emit("close",t),j(t,t.disconnectedProxies,(function(){t.state!==w&&t.state!==S&&"unreferenced"!==t.state&&("connecting"===t.state&&n.firstConnect?(t.emit("connect",t),t.emit("fullsetup",t),t.emit("all",t)):t.isConnected()?t.emit("reconnect",t):!t.isConnected()&&t.listeners("close").length>0&&t.emit("close",t),e(t))}));for(var i=0;i<r.length;i++)s(0,r[i],(function(){if(0===(o-=1)){if(t.state===w||t.state===S||"unreferenced"===t.state)return;j(t,t.disconnectedProxies,(function(){t.state!==w&&t.state!==S&&"unreferenced"!==t.state&&e(t)}))}}))}function s(e,n,r){var o=(new Date).getTime();x(t,"serverHeartbeatStarted",{connectionId:n.name}),n.command("admin.$cmd",{ismaster:!0},{monitoring:!0,socketTimeout:t.s.options.connectionTimeout||2e3},(function(e,i){if(t.state===w||t.state===S||"unreferenced"===t.state)return M(t.connectedProxies,t.disconnectedProxies,n),n.destroy(),r(e,i);var s=(new Date).getTime()-o;e?(x(t,"serverHeartbeatFailed",{durationMS:s,failure:e,connectionId:n.name}),M(t.connectedProxies,t.disconnectedProxies,n)):(n.ismaster=i.result,n.lastIsMasterMS=s,x(t,"serverHeartbeatSucceeded",{durationMS:s,reply:i.result,connectionId:n.name})),r(e,i)}))}}),t.s.haInterval)}(e,{firstConnect:!0})}}}function k(e,t){const n=t&&t.transaction;if(n&&n.server){if(n.server.isConnected())return n.server;n.unpinServer()}for(var r=e.connectedProxies.slice(0),o=Number.MAX_VALUE,i=0;i<r.length;i++)r[i].lastIsMasterMS<o&&(o=r[i].lastIsMasterMS);let s;return 0===(r=r.filter((function(t){if(t.lastIsMasterMS<=o+e.s.localThresholdMS&&t.isConnected())return!0}))).length?s=e.connectedProxies[0]:(s=r[e.index%r.length],e.index=(e.index+1)%r.length),n&&n.isActive&&s&&s.isConnected()&&n.pinServer(s),s}function M(e,t,n){for(var r=0;r<e.length;r++)e[r].name===n.name&&e.splice(r,1);for(r=0;r<t.length;r++)t[r].name===n.name&&t.splice(r,1);t.push(n)}function R(e,t){for(var n=0;n<e.length;n++)e[n].name===t.name&&e.splice(n,1)}function j(e,t,n){var r=t.length,o=function(e,t){return function(){if(r-=1,e.state===w||e.state===S||"unreferenced"===e.state)return M(e.connectingProxies,e.disconnectedProxies,this),this.destroy();if("connect"===t){if(e.state===w||e.state===S||"unreferenced"===e.state)return M(e.connectingProxies,e.disconnectedProxies,this),this.destroy();for(var o=0;o<T.length;o++)this.removeAllListeners(T[o]);this.on("error",I(e)),this.on("close",I(e)),this.on("timeout",I(e)),this.on("parseError",I(e)),M(e.connectingProxies,e.connectedProxies,this),B(e),e.emit("joined","mongos",this)}else M(e.connectingProxies,e.disconnectedProxies,this),this.destroy();0===r&&n()}};if(0===r)return n();function i(t,n){setTimeout((function(){if(e.state!==w&&e.state!==S&&"unreferenced"!==e.state){var n=new l(Object.assign({},e.s.options,{host:t.name.split(":")[0],port:parseInt(t.name.split(":")[1],10),reconnect:!1,monitoring:!1,parent:e}));N(t,{force:!0}),R(e.disconnectedProxies,t),m(n,e,["serverDescriptionChanged"]),e.emit("serverOpening",{topologyId:-1!==n.s.topologyId?n.s.topologyId:e.id,address:n.name}),n.once("connect",o(e,"connect")),n.once("close",o(e,"close")),n.once("timeout",o(e,"timeout")),n.once("error",o(e,"error")),n.once("parseError",o(e,"parseError")),m(n,e,["commandStarted","commandSucceeded","commandFailed"]),e.connectingProxies.push(n),n.connect(e.s.connectOptions)}}),n)}for(var s=0;s<t.length;s++)i(t[s],s)}function D(e,t,n){"function"==typeof t&&(n=t,t={}),t=t||{};const r=e.self,o=e.op,i=e.ns,s=e.ops;let a=k(r,t.session);if(!a)return n(new u("no mongos proxy available"));const c=!e.retrying&&!!t.retryWrites&&t.session&&h(r)&&!t.session.inTransaction()&&void 0===t.explain,l=(o,i)=>{if(!o)return n(null,i);if(!v(o,r)||!c)return o=y(o),n(o);if(a=k(r,t.session),!a)return n(o);return D(Object.assign({},e,{retrying:!0}),t,n)};n.operationId&&(l.operationId=n.operationId),c&&(t.session.incrementTransactionNumber(),t.willRetryWrite=c),a[o](i,s,t,l)}C.prototype.connect=function(e){var t=this;this.s.connectOptions=e||{},_(this,"connecting");var n=this.s.seedlist.map((function(n){const r=new l(Object.assign({},t.s.options,n,e,{reconnect:!1,monitoring:!1,parent:t}));return m(r,t,["serverDescriptionChanged"]),r}));x(this,"topologyOpening",{topologyId:this.id}),function(e,t){e.connectingProxies=e.connectingProxies.concat(t);var n=0;t.forEach(t=>function(t,n){setTimeout((function(){e.emit("serverOpening",{topologyId:e.id,address:t.name}),B(e),t.once("close",A(e,"close")),t.once("timeout",A(e,"timeout")),t.once("parseError",A(e,"parseError")),t.once("error",A(e,"error")),t.once("connect",A(e,"connect")),m(t,e,["commandStarted","commandSucceeded","commandFailed"]),t.connect(e.s.connectOptions)}),n)}(t,n++))}(t,n)},C.prototype.auth=function(e,t){"function"==typeof t&&t(null,null)},C.prototype.lastIsMaster=function(){return this.ismaster},C.prototype.unref=function(){_(this,"unreferenced"),this.connectedProxies.concat(this.connectingProxies).forEach((function(e){e.unref()})),clearTimeout(this.haTimeoutId)},C.prototype.destroy=function(e,t){"function"==typeof e&&(t=e,e={}),e=e||{},_(this,S),this.haTimeoutId&&clearTimeout(this.haTimeoutId);const n=this.connectedProxies.concat(this.connectingProxies);let r=n.length;const o=()=>{r--,r>0||(B(this),x(this,"topologyClosed",{topologyId:this.id}),_(this,w),"function"==typeof t&&t(null,null))};0!==r?n.forEach(t=>{this.emit("serverClosed",{topologyId:this.id,address:t.name}),N(t,e,o),M(this.connectedProxies,this.disconnectedProxies,t)}):o()},C.prototype.isConnected=function(){return this.connectedProxies.length>0},C.prototype.isDestroyed=function(){return this.state===w},C.prototype.insert=function(e,t,n,r){return"function"==typeof n&&(r=n,n=(n={})||{}),this.state===w?r(new u(o("topology was destroyed"))):this.isConnected()||null==this.s.disconnectHandler?this.isConnected()?void D({self:this,op:"insert",ns:e,ops:t},n,r):r(new u("no mongos proxy available")):this.s.disconnectHandler.add("insert",e,t,n,r)},C.prototype.update=function(e,t,n,r){return"function"==typeof n&&(r=n,n=(n={})||{}),this.state===w?r(new u(o("topology was destroyed"))):this.isConnected()||null==this.s.disconnectHandler?this.isConnected()?void D({self:this,op:"update",ns:e,ops:t},n,r):r(new u("no mongos proxy available")):this.s.disconnectHandler.add("update",e,t,n,r)},C.prototype.remove=function(e,t,n,r){return"function"==typeof n&&(r=n,n=(n={})||{}),this.state===w?r(new u(o("topology was destroyed"))):this.isConnected()||null==this.s.disconnectHandler?this.isConnected()?void D({self:this,op:"remove",ns:e,ops:t},n,r):r(new u("no mongos proxy available")):this.s.disconnectHandler.add("remove",e,t,n,r)};const P=["findAndModify","insert","update","delete"];function B(e){if(e.listeners("topologyDescriptionChanged").length>0){var t="Unknown";e.connectedProxies.length>0&&(t="Sharded");var n={topologyType:t,servers:[]},r=e.disconnectedProxies.concat(e.connectingProxies);n.servers=n.servers.concat(r.map((function(e){var t=e.getDescription();return t.type="Unknown",t}))),n.servers=n.servers.concat(e.connectedProxies.map((function(e){var t=e.getDescription();return t.type="Mongos",t})));var o=f(e.topologyDescription,n),i={topologyId:e.id,previousDescription:e.topologyDescription,newDescription:n,diff:o};o.servers.length>0&&e.emit("topologyDescriptionChanged",i),e.topologyDescription=n}}C.prototype.command=function(e,t,n,r){if("function"==typeof n&&(r=n,n=(n={})||{}),this.state===w)return r(new u(o("topology was destroyed")));var i=this,s=k(i,n.session);if((null==s||!s.isConnected())&&null!=this.s.disconnectHandler)return this.s.disconnectHandler.add("command",e,t,n,r);if(null==s)return r(new u("no mongos proxy available"));var a=p(n);a.topology=i;const c=!n.retrying&&n.retryWrites&&n.session&&h(i)&&!n.session.inTransaction()&&(l=t,P.some(e=>l[e]));var l;c&&(a.session.incrementTransactionNumber(),a.willRetryWrite=c),s.command(e,t,a,(n,o)=>{if(!n)return r(null,o);if(!v(n,i))return r(n);if(c){const n=Object.assign({},a,{retrying:!0});return this.command(e,t,n,r)}return r(n)})},C.prototype.cursor=function(e,t,n){const r=(n=n||{}).topology||this;return new(n.cursorFactory||this.s.Cursor)(r,e,t,n)},C.prototype.selectServer=function(e,t,n){"function"==typeof e&&void 0===n&&(n=e,e=void 0,t={}),"function"==typeof t&&(n=t,t=e,e=void 0);const r=k(this,(t=t||{}).session);null!=r?(this.s.debug&&this.emit("pickedServer",null,r),n(null,r)):n(new u("server selection failed"))},C.prototype.connections=function(){for(var e=[],t=0;t<this.connectedProxies.length;t++)e=e.concat(this.connectedProxies[t].connections());return e},e.exports=C},function(e,t,n){"use strict";const r=n(138),o=n(8),i=n(44).ServerDescription,s=n(13).ServerType,a=n(189).TopologyDescription,c=n(13).TopologyType,u=n(200),l=n(432).Server,f=n(4).relayEvents,p=n(10),d=n(7).isRetryableWritesSupported,h=n(17).CoreCursor,m=n(5).deprecate,g=n(9).retrieveBSON(),y=n(7).createCompressionInfo,b=n(34).ClientSession,v=n(3).MongoError,S=n(3).MongoServerSelectionError,w=n(7).resolveClusterTime,_=n(444).SrvPoller,O=n(7).getMMAPError,T=n(4).makeStateMachine,C=n(4).eachAsync,x=n(0).emitDeprecationWarning,E=n(34).ServerSessionPool,N=n(4).makeClientMetadata,I=n(93).CMAP_EVENT_NAMES,A=n(44).compareTopologyVersion,k=n(0).emitWarning,M=n(13),R=M.drainTimerQueue,j=M.clearAndRemoveTimerFrom,D=n(445),P=D.readPreferenceServerSelector,B=D.writableServerSelector;let L=0;const q=["serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","commandStarted","commandSucceeded","commandFailed","monitoring"].concat(I),U=["connect","descriptionReceived","close","ended"],z=M.STATE_CLOSING,$=M.STATE_CLOSED,W=M.STATE_CONNECTING,F=M.STATE_CONNECTED,V=T({[$]:[$,W],[W]:[W,z,F,$],[F]:[F,z,$],[z]:[z,$]}),K=new Set(["autoReconnect","reconnectTries","reconnectInterval","bufferMaxEntries"]),H=Symbol("cancelled"),Y=Symbol("waitQueue");class G extends o{constructor(e,t){super(),void 0===t&&"string"!=typeof e&&(t=e,e=[],t.host&&e.push({host:t.host,port:t.port})),"string"==typeof(e=e||[])&&(e=function(e){return e.split(",").map(e=>({host:e.split(":")[0],port:e.split(":")[1]||27017}))}(e)),t=Object.assign({},M.TOPOLOGY_DEFAULTS,t),t=Object.freeze(Object.assign(t,{metadata:N(t),compression:{compressors:y(t)}})),K.forEach(e=>{t[e]&&x(`The option \`${e}\` is incompatible with the unified topology, please read more by visiting http://bit.ly/2D8WfT6`,"DeprecationWarning")});const n=function(e,t){if(t.directConnection)return c.Single;if(null==(t.replicaSet||t.setName||t.rs_name))return c.Unknown;return c.ReplicaSetNoPrimary}(0,t),o=L++,s=e.reduce((e,t)=>{t.domain_socket&&(t.host=t.domain_socket);const n=t.port?`${t.host}:${t.port}`:`${t.host}:27017`;return e.set(n,new i(n)),e},new Map);this[Y]=new r,this.s={id:o,options:t,seedlist:e,state:$,description:new a(n,s,t.replicaSet,null,null,null,t),serverSelectionTimeoutMS:t.serverSelectionTimeoutMS,heartbeatFrequencyMS:t.heartbeatFrequencyMS,minHeartbeatFrequencyMS:t.minHeartbeatFrequencyMS,Cursor:t.cursorFactory||h,bson:t.bson||new g([g.Binary,g.Code,g.DBRef,g.Decimal128,g.Double,g.Int32,g.Long,g.Map,g.MaxKey,g.MinKey,g.ObjectId,g.BSONRegExp,g.Symbol,g.Timestamp]),servers:new Map,sessionPool:new E(this),sessions:new Set,promiseLibrary:t.promiseLibrary||Promise,credentials:t.credentials,clusterTime:null,connectionTimers:new Set},t.srvHost&&(this.s.srvPoller=t.srvPoller||new _({heartbeatFrequencyMS:this.s.heartbeatFrequencyMS,srvHost:t.srvHost,logger:t.logger,loggerLevel:t.loggerLevel}),this.s.detectTopologyDescriptionChange=e=>{const t=e.previousDescription.type,n=e.newDescription.type;var r;t!==c.Sharded&&n===c.Sharded&&(this.s.handleSrvPolling=(r=this,function(e){const t=r.s.description;r.s.description=r.s.description.updateFromSrvPollingEvent(e),r.s.description!==t&&(Q(r),r.emit("topologyDescriptionChanged",new u.TopologyDescriptionChangedEvent(r.s.id,t,r.s.description)))}),this.s.srvPoller.on("srvRecordDiscovery",this.s.handleSrvPolling),this.s.srvPoller.start())},this.on("topologyDescriptionChanged",this.s.detectTopologyDescriptionChange)),this.setMaxListeners(1/0)}get description(){return this.s.description}get parserType(){return g.native?"c++":"js"}connect(e,t){if("function"==typeof e&&(t=e,e={}),e=e||{},this.s.state===F)return void("function"==typeof t&&t());var n,r;V(this,W),this.emit("topologyOpening",new u.TopologyOpeningEvent(this.s.id)),this.emit("topologyDescriptionChanged",new u.TopologyDescriptionChangedEvent(this.s.id,new a(c.Unknown),this.s.description)),n=this,r=Array.from(this.s.description.servers.values()),n.s.servers=r.reduce((e,t)=>{const r=Z(n,t);return e.set(t.address,r),e},new Map),p.translate(e);const o=e.readPreference||p.primary,i=e=>{if(e)return this.close(),void("function"==typeof t?t(e):this.emit("error",e));V(this,F),this.emit("open",e,this),this.emit("connect",this),"function"==typeof t&&t(e,this)};this.s.credentials?this.command("admin.$cmd",{ping:1},{readPreference:o},i):this.selectServer(P(o),e,i)}close(e,t){"function"==typeof e&&(t=e,e={}),"boolean"==typeof e&&(e={force:e}),e=e||{},this.s.state!==$&&this.s.state!==z?(V(this,z),ne(this[Y],new v("Topology closed")),R(this.s.connectionTimers),this.s.srvPoller&&(this.s.srvPoller.stop(),this.s.handleSrvPolling&&(this.s.srvPoller.removeListener("srvRecordDiscovery",this.s.handleSrvPolling),delete this.s.handleSrvPolling)),this.s.detectTopologyDescriptionChange&&(this.removeListener("topologyDescriptionChanged",this.s.detectTopologyDescriptionChange),delete this.s.detectTopologyDescriptionChange),this.s.sessions.forEach(e=>e.endSession()),this.s.sessionPool.endAllPooledSessions(()=>{C(Array.from(this.s.servers.values()),(t,n)=>X(t,this,e,n),e=>{this.s.servers.clear(),this.emit("topologyClosed",new u.TopologyClosedEvent(this.s.id)),V(this,$),this.emit("close"),"function"==typeof t&&t(e)})})):"function"==typeof t&&t()}selectServer(e,t,n){if("function"==typeof t)if(n=t,"function"!=typeof e){let n;t=e,e instanceof p?n=e:"string"==typeof e?n=new p(e):(p.translate(t),n=t.readPreference||p.primary),e=P(n)}else t={};t=Object.assign({},{serverSelectionTimeoutMS:this.s.serverSelectionTimeoutMS},t);const r=this.description.type===c.Sharded,o=t.session,i=o&&o.transaction;if(r&&i&&i.server)return void n(void 0,i.server);let s=e;if("object"==typeof e){const t=e.readPreference?e.readPreference:p.primary;s=P(t)}const a={serverSelector:s,transaction:i,callback:n},u=t.serverSelectionTimeoutMS;u&&(a.timer=setTimeout(()=>{a[H]=!0,a.timer=void 0;const e=new S(`Server selection timed out after ${u} ms`,this.description);a.callback(e)},u)),this[Y].push(a),re(this)}shouldCheckForSessionSupport(){return this.description.type===c.Single?!this.description.hasKnownServers:!this.description.hasDataBearingServers}hasSessionSupport(){return null!=this.description.logicalSessionTimeoutMinutes}startSession(e,t){const n=new b(this,this.s.sessionPool,e,t);return n.once("ended",()=>{this.s.sessions.delete(n)}),this.s.sessions.add(n),n}endSessions(e,t){Array.isArray(e)||(e=[e]),this.command("admin.$cmd",{endSessions:e},{readPreference:p.primaryPreferred,noResponse:!0},()=>{"function"==typeof t&&t()})}serverUpdateHandler(e){if(!this.s.description.hasServer(e.address))return;if(function(e,t){const n=e.servers.get(t.address).topologyVersion;return A(n,t.topologyVersion)>0}(this.s.description,e))return;const t=this.s.description,n=this.s.description.servers.get(e.address),r=e.$clusterTime;r&&w(this,r);const o=n&&n.equals(e);this.s.description=this.s.description.update(e),this.s.description.compatibilityError?this.emit("error",new v(this.s.description.compatibilityError)):(o||this.emit("serverDescriptionChanged",new u.ServerDescriptionChangedEvent(this.s.id,e.address,n,this.s.description.servers.get(e.address))),Q(this,e),this[Y].length>0&&re(this),o||this.emit("topologyDescriptionChanged",new u.TopologyDescriptionChangedEvent(this.s.id,t,this.s.description)))}auth(e,t){"function"==typeof e&&(t=e,e=null),"function"==typeof t&&t(null,!0)}logout(e){"function"==typeof e&&e(null,!0)}insert(e,t,n,r){ee({topology:this,op:"insert",ns:e,ops:t},n,r)}update(e,t,n,r){ee({topology:this,op:"update",ns:e,ops:t},n,r)}remove(e,t,n,r){ee({topology:this,op:"remove",ns:e,ops:t},n,r)}command(e,t,n,r){"function"==typeof n&&(r=n,n=(n={})||{}),p.translate(n);const o=n.readPreference||p.primary;this.selectServer(P(o),n,(o,i)=>{if(o)return void r(o);const s=!n.retrying&&!!n.retryWrites&&n.session&&d(this)&&!n.session.inTransaction()&&(a=t,J.some(e=>a[e]));var a;s&&(n.session.incrementTransactionNumber(),n.willRetryWrite=s),i.command(e,t,n,(o,i)=>{if(!o)return r(null,i);if(!te(o))return r(o);if(s){const o=Object.assign({},n,{retrying:!0});return this.command(e,t,o,r)}return r(o)})})}cursor(e,t,n){const r=(n=n||{}).topology||this,o=n.cursorFactory||this.s.Cursor;return p.translate(n),new o(r,e,t,n)}get clientMetadata(){return this.s.options.metadata}isConnected(){return this.s.state===F}isDestroyed(){return this.s.state===$}unref(){k("not implemented: `unref`")}lastIsMaster(){const e=Array.from(this.description.servers.values());return 0===e.length?{}:e.filter(e=>e.type!==s.Unknown)[0]||{maxWireVersion:this.description.commonWireVersion}}get logicalSessionTimeoutMinutes(){return this.description.logicalSessionTimeoutMinutes}get bson(){return this.s.bson}}Object.defineProperty(G.prototype,"clusterTime",{enumerable:!0,get:function(){return this.s.clusterTime},set:function(e){this.s.clusterTime=e}}),G.prototype.destroy=m(G.prototype.close,"destroy() is deprecated, please use close() instead");const J=["findAndModify","insert","update","delete"];function X(e,t,n,r){n=n||{},U.forEach(t=>e.removeAllListeners(t)),e.destroy(n,()=>{t.emit("serverClosed",new u.ServerClosedEvent(t.s.id,e.description.address)),q.forEach(t=>e.removeAllListeners(t)),"function"==typeof r&&r()})}function Z(e,t,n){e.emit("serverOpening",new u.ServerOpeningEvent(e.s.id,t.address));const r=new l(t,e.s.options,e);if(f(r,e,q),r.on("descriptionReceived",e.serverUpdateHandler.bind(e)),n){const t=setTimeout(()=>{j(t,e.s.connectionTimers),r.connect()},n);return e.s.connectionTimers.add(t),r}return r.connect(),r}function Q(e,t){if(t&&e.s.servers.has(t.address)){e.s.servers.get(t.address).s.description=t}for(const t of e.description.servers.values())if(!e.s.servers.has(t.address)){const n=Z(e,t);e.s.servers.set(t.address,n)}for(const t of e.s.servers){const n=t[0];if(e.description.hasServer(n))continue;const r=e.s.servers.get(n);e.s.servers.delete(n),X(r,e)}}function ee(e,t,n){"function"==typeof t&&(n=t,t={}),t=t||{};const r=e.topology,o=e.op,i=e.ns,s=e.ops,a=!e.retrying&&!!t.retryWrites&&t.session&&d(r)&&!t.session.inTransaction()&&void 0===t.explain;r.selectServer(B(),t,(r,c)=>{if(r)return void n(r,null);const u=(r,o)=>{if(!r)return n(null,o);if(!te(r))return r=O(r),n(r);if(a){return ee(Object.assign({},e,{retrying:!0}),t,n)}return n(r)};n.operationId&&(u.operationId=n.operationId),a&&(t.session.incrementTransactionNumber(),t.willRetryWrite=a),c[o](i,s,t,u)})}function te(e){return e instanceof v&&e.hasErrorLabel("RetryableWriteError")}function ne(e,t){for(;e.length;){const n=e.shift();clearTimeout(n.timer),n[H]||n.callback(t)}}function re(e){if(e.s.state===$)return void ne(e[Y],new v("Topology is closed, please connect"));const t=Array.from(e.description.servers.values()),n=e[Y].length;for(let o=0;o<n&&e[Y].length;++o){const n=e[Y].shift();if(n[H])continue;let o;try{const r=n.serverSelector;o=r?r(e.description,t):t}catch(e){clearTimeout(n.timer),n.callback(e);continue}if(0===o.length){e[Y].push(n);continue}const i=(r=o)[Math.floor(Math.random()*r.length)],s=e.s.servers.get(i.address),a=n.transaction;e.description.type===c.Sharded&&a&&a.isActive&&a.pinServer(s),clearTimeout(n.timer),n.callback(void 0,s)}var r;e[Y].length>0&&e.s.servers.forEach(e=>process.nextTick(()=>e.requestCheck()))}e.exports={Topology:G}},function(e,t,n){"use strict";const r=n(8),o=n(433).ConnectionPool,i=n(93).CMAP_EVENT_NAMES,s=n(3).MongoError,a=n(4).relayEvents,c=n(9).retrieveBSON(),u=n(16),l=n(44).ServerDescription,f=n(44).compareTopologyVersion,p=n(10),d=n(443).Monitor,h=n(3).MongoNetworkError,m=n(3).MongoNetworkTimeoutError,g=n(4).collationNotSupported,y=n(9).debugOptions,b=n(3).isSDAMUnrecoverableError,v=n(3).isRetryableWriteError,S=n(3).isNodeShuttingDownError,w=n(3).isNetworkErrorBeforeHandshake,_=n(4).maxWireVersion,O=n(4).makeStateMachine,T=n(13),C=T.ServerType,x=n(54).isTransactionCommand,E=["reconnect","reconnectTries","reconnectInterval","emitError","cursorFactory","host","port","size","keepAlive","keepAliveInitialDelay","noDelay","connectionTimeout","checkServerIdentity","socketTimeout","ssl","ca","crl","cert","key","rejectUnauthorized","promoteLongs","promoteValues","promoteBuffers","servername"],N=T.STATE_CLOSING,I=T.STATE_CLOSED,A=T.STATE_CONNECTING,k=T.STATE_CONNECTED,M=O({[I]:[I,A],[A]:[A,N,k,I],[k]:[k,N,I],[N]:[N,I]}),R=Symbol("monitor");class j extends r{constructor(e,t,n){super(),this.s={description:e,options:t,logger:u("Server",t),bson:t.bson||new c([c.Binary,c.Code,c.DBRef,c.Decimal128,c.Double,c.Int32,c.Long,c.Map,c.MaxKey,c.MinKey,c.ObjectId,c.BSONRegExp,c.Symbol,c.Timestamp]),state:I,credentials:t.credentials,topology:n};const r=Object.assign({host:this.description.host,port:this.description.port,bson:this.s.bson},t);this.s.pool=new o(r),a(this.s.pool,this,["commandStarted","commandSucceeded","commandFailed"].concat(i)),this.s.pool.on("clusterTimeReceived",e=>{this.clusterTime=e}),this[R]=new d(this,this.s.options),a(this[R],this,["serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","monitoring"]),this[R].on("resetConnectionPool",()=>{this.s.pool.clear()}),this[R].on("resetServer",e=>B(this,e)),this[R].on("serverHeartbeatSucceeded",e=>{this.emit("descriptionReceived",new l(this.description.address,e.reply,{roundTripTime:D(this.description.roundTripTime,e.duration)})),this.s.state===A&&(M(this,k),this.emit("connect",this))})}get description(){return this.s.description}get name(){return this.s.description.address}get autoEncrypter(){return this.s.options&&this.s.options.autoEncrypter?this.s.options.autoEncrypter:null}connect(){this.s.state===I&&(M(this,A),this[R].connect())}destroy(e,t){"function"==typeof e&&(t=e,e={}),e=Object.assign({},{force:!1},e),this.s.state!==I?(M(this,N),this[R].close(),this.s.pool.close(e,e=>{M(this,I),this.emit("closed"),"function"==typeof t&&t(e)})):"function"==typeof t&&t()}requestCheck(){this[R].requestCheck()}command(e,t,n,r){if("function"==typeof n&&(r=n,n=(n={})||{}),this.s.state===N||this.s.state===I)return void r(new s("server is closed"));const o=function(e,t){if(t.readPreference&&!(t.readPreference instanceof p))return new s("readPreference must be an instance of ReadPreference")}(0,n);if(o)return r(o);n=Object.assign({},n,{wireProtocolCommand:!1}),this.s.logger.isDebug()&&this.s.logger.debug(`executing command [${JSON.stringify({ns:e,cmd:t,options:y(E,n)})}] against ${this.name}`),g(this,t)?r(new s(`server ${this.name} does not support collation`)):this.s.pool.withConnection((r,o,i)=>{if(r)return B(this,r),i(r);o.command(e,t,n,q(this,o,t,n,i))},r)}query(e,t,n,r,o){this.s.state!==N&&this.s.state!==I?this.s.pool.withConnection((o,i,s)=>{if(o)return B(this,o),s(o);i.query(e,t,n,r,q(this,i,t,r,s))},o):o(new s("server is closed"))}getMore(e,t,n,r,o){this.s.state!==N&&this.s.state!==I?this.s.pool.withConnection((o,i,s)=>{if(o)return B(this,o),s(o);i.getMore(e,t,n,r,q(this,i,null,r,s))},o):o(new s("server is closed"))}killCursors(e,t,n){this.s.state!==N&&this.s.state!==I?this.s.pool.withConnection((n,r,o)=>{if(n)return B(this,n),o(n);r.killCursors(e,t,q(this,r,null,void 0,o))},n):"function"==typeof n&&n(new s("server is closed"))}insert(e,t,n,r){P({server:this,op:"insert",ns:e,ops:t},n,r)}update(e,t,n,r){P({server:this,op:"update",ns:e,ops:t},n,r)}remove(e,t,n,r){P({server:this,op:"remove",ns:e,ops:t},n,r)}}function D(e,t){if(-1===e)return t;return.2*t+.8*e}function P(e,t,n){"function"==typeof t&&(n=t,t={}),t=t||{};const r=e.server,o=e.op,i=e.ns,a=Array.isArray(e.ops)?e.ops:[e.ops];r.s.state!==N&&r.s.state!==I?g(r,t)?n(new s(`server ${r.name} does not support collation`)):!(t.writeConcern&&0===t.writeConcern.w||_(r)<5)||"update"!==o&&"remove"!==o||!a.find(e=>e.hint)?r.s.pool.withConnection((e,n,s)=>{if(e)return B(r,e),s(e);n[o](i,a,t,q(r,n,a,t,s))},n):n(new s(`servers < 3.4 do not support hint on ${o}`)):n(new s("server is closed"))}function B(e,t){t instanceof h&&!(t instanceof m)&&e[R].reset(),e.emit("descriptionReceived",new l(e.description.address,null,{error:t,topologyVersion:t&&t.topologyVersion?t.topologyVersion:e.description.topologyVersion}))}function L(e,t){return e&&e.inTransaction()&&!x(t)}function q(e,t,n,r,o){const i=r&&r.session;return function(r,s){r&&!function(e,t){return t.generation!==e.generation}(e.s.pool,t)&&(r instanceof h?(i&&!i.hasEnded&&(i.serverSession.isDirty=!0),function(e){return e.description.maxWireVersion>=6&&e.description.logicalSessionTimeoutMinutes&&e.description.type!==C.Standalone}(e)&&!L(i,n)&&r.addErrorLabel("RetryableWriteError"),r instanceof m&&!w(r)||(B(e,r),e.s.pool.clear())):(_(e)<9&&v(r)&&!L(i,n)&&r.addErrorLabel("RetryableWriteError"),b(r)&&function(e,t){const n=t.topologyVersion,r=e.description.topologyVersion;return f(r,n)<0}(e,r)&&((_(e)<=7||S(r))&&e.s.pool.clear(),B(e,r),process.nextTick(()=>e.requestCheck())))),o(r,s)}}Object.defineProperty(j.prototype,"clusterTime",{get:function(){return this.s.topology.clusterTime},set:function(e){this.s.topology.clusterTime=e}}),e.exports={Server:j}},function(e,t,n){"use strict";const r=n(138),o=n(8).EventEmitter,i=n(16),s=n(0).makeCounter,a=n(3).MongoError,c=n(201).Connection,u=n(4).eachAsync,l=n(135),f=n(4).relayEvents,p=n(442),d=p.PoolClosedError,h=p.WaitQueueTimeoutError,m=n(93),g=m.ConnectionPoolCreatedEvent,y=m.ConnectionPoolClosedEvent,b=m.ConnectionCreatedEvent,v=m.ConnectionReadyEvent,S=m.ConnectionClosedEvent,w=m.ConnectionCheckOutStartedEvent,_=m.ConnectionCheckOutFailedEvent,O=m.ConnectionCheckedOutEvent,T=m.ConnectionCheckedInEvent,C=m.ConnectionPoolClearedEvent,x=Symbol("logger"),E=Symbol("connections"),N=Symbol("permits"),I=Symbol("minPoolSizeTimer"),A=Symbol("generation"),k=Symbol("connectionCounter"),M=Symbol("cancellationToken"),R=Symbol("waitQueue"),j=Symbol("cancelled"),D=new Set(["ssl","bson","connectionType","monitorCommands","socketTimeout","credentials","compression","host","port","localAddress","localPort","family","hints","lookup","path","ca","cert","sigalgs","ciphers","clientCertEngine","crl","dhparam","ecdhCurve","honorCipherOrder","key","privateKeyEngine","privateKeyIdentifier","maxVersion","minVersion","passphrase","pfx","secureOptions","secureProtocol","sessionIdContext","allowHalfOpen","rejectUnauthorized","pskCallback","ALPNProtocols","servername","checkServerIdentity","session","minDHSize","secureContext","maxPoolSize","minPoolSize","maxIdleTimeMS","waitQueueTimeoutMS"]);function P(e,t){return t.generation!==e[A]}function B(e,t){return!!(e.options.maxIdleTimeMS&&t.idleTime>e.options.maxIdleTimeMS)}function L(e,t){const n=Object.assign({id:e[k].next().value,generation:e[A]},e.options);e[N]--,l(n,e[M],(n,r)=>{if(n)return e[N]++,e[x].debug(`connection attempt failed with error [${JSON.stringify(n)}]`),void("function"==typeof t&&t(n));e.closed?r.destroy({force:!0}):(f(r,e,["commandStarted","commandFailed","commandSucceeded","clusterTimeReceived"]),e.emit("connectionCreated",new b(e,r)),r.markAvailable(),e.emit("connectionReady",new v(e,r)),"function"!=typeof t?(e[E].push(r),process.nextTick(()=>U(e))):t(void 0,r))})}function q(e,t,n){e.emit("connectionClosed",new S(e,t,n)),e[N]++,process.nextTick(()=>t.destroy())}function U(e){if(e.closed)return;for(;e.waitQueueSize;){const t=e[R].peekFront();if(t[j]){e[R].shift();continue}if(!e.availableConnectionCount)break;const n=e[E].shift(),r=P(e,n),o=B(e,n);if(!r&&!o&&!n.closed)return e.emit("connectionCheckedOut",new O(e,n)),clearTimeout(t.timer),e[R].shift(),void t.callback(void 0,n);const i=n.closed?"error":r?"stale":"idle";q(e,n,i)}const t=e.options.maxPoolSize;e.waitQueueSize&&(t<=0||e.totalConnectionCount<t)&&L(e,(t,n)=>{const r=e[R].shift();null==r||r[j]?null==t&&e[E].push(n):(t?e.emit("connectionCheckOutFailed",new _(e,t)):e.emit("connectionCheckedOut",new O(e,n)),clearTimeout(r.timer),r.callback(t,n))})}e.exports={ConnectionPool:class extends o{constructor(e){if(super(),e=e||{},this.closed=!1,this.options=function(e,t){const n=Array.from(D).reduce((t,n)=>(Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]),t),{});return Object.freeze(Object.assign({},t,n))}(e,{connectionType:c,maxPoolSize:"number"==typeof e.maxPoolSize?e.maxPoolSize:100,minPoolSize:"number"==typeof e.minPoolSize?e.minPoolSize:0,maxIdleTimeMS:"number"==typeof e.maxIdleTimeMS?e.maxIdleTimeMS:0,waitQueueTimeoutMS:"number"==typeof e.waitQueueTimeoutMS?e.waitQueueTimeoutMS:0,autoEncrypter:e.autoEncrypter,metadata:e.metadata}),e.minSize>e.maxSize)throw new TypeError("Connection pool minimum size must not be greater than maxiumum pool size");this[x]=i("ConnectionPool",e),this[E]=new r,this[N]=this.options.maxPoolSize,this[I]=void 0,this[A]=0,this[k]=s(1),this[M]=new o,this[M].setMaxListeners(1/0),this[R]=new r,process.nextTick(()=>{this.emit("connectionPoolCreated",new g(this)),function e(t){if(t.closed||0===t.options.minPoolSize)return;const n=t.options.minPoolSize;for(let e=t.totalConnectionCount;e<n;++e)L(t);t[I]=setTimeout(()=>e(t),10)}(this)})}get address(){return`${this.options.host}:${this.options.port}`}get generation(){return this[A]}get totalConnectionCount(){return this[E].length+(this.options.maxPoolSize-this[N])}get availableConnectionCount(){return this[E].length}get waitQueueSize(){return this[R].length}checkOut(e){if(this.emit("connectionCheckOutStarted",new w(this)),this.closed)return this.emit("connectionCheckOutFailed",new _(this,"poolClosed")),void e(new d(this));const t={callback:e},n=this,r=this.options.waitQueueTimeoutMS;r&&(t.timer=setTimeout(()=>{t[j]=!0,t.timer=void 0,n.emit("connectionCheckOutFailed",new _(n,"timeout")),t.callback(new h(n))},r)),this[R].push(t),process.nextTick(()=>U(this))}checkIn(e){const t=this.closed,n=P(this,e),r=!!(t||n||e.closed);if(r||(e.markAvailable(),this[E].push(e)),this.emit("connectionCheckedIn",new T(this,e)),r){q(this,e,e.closed?"error":t?"poolClosed":"stale")}process.nextTick(()=>U(this))}clear(){this[A]+=1,this.emit("connectionPoolCleared",new C(this))}close(e,t){if("function"==typeof e&&(t=e),e=Object.assign({force:!1},e),this.closed)return t();for(this[M].emit("cancel");this.waitQueueSize;){const e=this[R].pop();clearTimeout(e.timer),e[j]||e.callback(new a("connection pool closed"))}this[I]&&clearTimeout(this[I]),"function"==typeof this[k].return&&this[k].return(),this.closed=!0,u(this[E].toArray(),(t,n)=>{this.emit("connectionClosed",new S(this,t,"poolClosed")),t.destroy(e,n)},e=>{this[E].clear(),this.emit("connectionPoolClosed",new y(this)),t(e)})}withConnection(e,t){this.checkOut((n,r)=>{e(n,r,(e,n)=>{"function"==typeof t&&(e?t(e):t(void 0,n)),r&&this.checkIn(r)})})}}}},function(e,t,n){"use strict";const r=n(18).Duplex,o=n(202),i=n(3).MongoParseError,s=n(30).decompress,a=n(21).Response,c=n(45).BinMsg,u=n(3).MongoError,l=n(6).opcodes.OP_COMPRESSED,f=n(6).opcodes.OP_MSG,p=n(6).MESSAGE_HEADER_SIZE,d=n(6).COMPRESSION_DETAILS_SIZE,h=n(6).opcodes,m=n(30).compress,g=n(30).compressorIDs,y=n(30).uncompressibleCommands,b=n(45).Msg,v=Symbol("buffer");e.exports=class extends r{constructor(e){super(e=e||{}),this.bson=e.bson,this.maxBsonMessageSize=e.maxBsonMessageSize||67108864,this[v]=new o}_write(e,t,n){this[v].append(e),function e(t,n){const r=t[v];if(r.length<4)return void n();const o=r.readInt32LE(0);if(o<0)return void n(new i(`Invalid message size: ${o}`));if(o>t.maxBsonMessageSize)return void n(new i(`Invalid message size: ${o}, max allowed: ${t.maxBsonMessageSize}`));if(o>r.length)return void n();const d=r.slice(0,o);r.consume(o);const h={length:d.readInt32LE(0),requestId:d.readInt32LE(4),responseTo:d.readInt32LE(8),opCode:d.readInt32LE(12)};let m=h.opCode===f?c:a;const g=t.responseOptions;if(h.opCode!==l){const o=d.slice(p);return t.emit("message",new m(t.bson,d,h,o,g)),void(r.length>=4?e(t,n):n())}h.fromCompressed=!0,h.opCode=d.readInt32LE(p),h.length=d.readInt32LE(p+4);const y=d[p+8],b=d.slice(p+9);m=h.opCode===f?c:a,s(y,b,(o,i)=>{o?n(o):i.length===h.length?(t.emit("message",new m(t.bson,d,h,i,g)),r.length>=4?e(t,n):n()):n(new u("Decompressing a compressed message from the server failed. The message is corrupt."))})}(this,n)}_read(){}writeCommand(e,t){if(!(t&&!!t.agreedCompressor)||!function(e){const t=e instanceof b?e.command:e.query,n=Object.keys(t)[0];return!y.has(n)}(e)){const t=e.toBin();return void this.push(Array.isArray(t)?Buffer.concat(t):t)}const n=Buffer.concat(e.toBin()),r=n.slice(p),o=n.readInt32LE(12);m({options:t},r,(n,i)=>{if(n)return void t.cb(n,null);const s=Buffer.alloc(p);s.writeInt32LE(p+d+i.length,0),s.writeInt32LE(e.requestId,4),s.writeInt32LE(0,8),s.writeInt32LE(h.OP_COMPRESSED,12);const a=Buffer.alloc(d);a.writeInt32LE(o,0),a.writeInt32LE(r.length,4),a.writeUInt8(g[t.agreedCompressor],8),this.push(Buffer.concat([s,a,i]))})}}},function(e,t,n){var r=n(18);"disable"===process.env.READABLE_STREAM&&r?(e.exports=r,(t=e.exports=r.Readable).Readable=r.Readable,t.Writable=r.Writable,t.Duplex=r.Duplex,t.Transform=r.Transform,t.PassThrough=r.PassThrough,t.Stream=r):((t=e.exports=n(203)).Stream=r||t,t.Readable=t,t.Writable=n(206),t.Duplex=n(47),t.Transform=n(208),t.PassThrough=n(440))},function(e,t){var n={}.toString;e.exports=Array.isArray||function(e){return"[object Array]"==n.call(e)}},function(e,t){"function"==typeof Object.create?e.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:e.exports=function(e,t){if(t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}}},function(e,t,n){"use strict";var r=n(92).Buffer,o=n(5);e.exports=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.head=null,this.tail=null,this.length=0}return e.prototype.push=function(e){var t={data:e,next:null};this.length>0?this.tail.next=t:this.head=t,this.tail=t,++this.length},e.prototype.unshift=function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length},e.prototype.shift=function(){if(0!==this.length){var e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}},e.prototype.clear=function(){this.head=this.tail=null,this.length=0},e.prototype.join=function(e){if(0===this.length)return"";for(var t=this.head,n=""+t.data;t=t.next;)n+=e+t.data;return n},e.prototype.concat=function(e){if(0===this.length)return r.alloc(0);if(1===this.length)return this.head.data;for(var t,n,o,i=r.allocUnsafe(e>>>0),s=this.head,a=0;s;)t=s.data,n=i,o=a,t.copy(n,o),a+=s.data.length,s=s.next;return i},e}(),o&&o.inspect&&o.inspect.custom&&(e.exports.prototype[o.inspect.custom]=function(){var e=o.inspect({length:this.length});return this.constructor.name+" "+e})},function(e,t,n){e.exports=n(5).deprecate},function(e,t,n){"use strict";e.exports=i;var r=n(208),o=Object.create(n(57));function i(e){if(!(this instanceof i))return new i(e);r.call(this,e)}o.inherits=n(58),o.inherits(i,r),i.prototype._transform=function(e,t,n){n(null,e)}},function(e,t,n){"use strict";const r=n(44).parseServerType,o=["minWireVersion","maxWireVersion","maxBsonObjectSize","maxMessageSizeBytes","maxWriteBatchSize","__nodejs_mock_server__"];e.exports={StreamDescription:class{constructor(e,t){this.address=e,this.type=r(null),this.minWireVersion=void 0,this.maxWireVersion=void 0,this.maxBsonObjectSize=16777216,this.maxMessageSizeBytes=48e6,this.maxWriteBatchSize=1e5,this.compressors=t&&t.compression&&Array.isArray(t.compression.compressors)?t.compression.compressors:[]}receiveResponse(e){this.type=r(e),o.forEach(t=>{void 0!==e[t]&&(this[t]=e[t])}),e.compression&&(this.compressor=this.compressors.filter(t=>-1!==e.compression.indexOf(t))[0])}}}},function(e,t,n){"use strict";const r=n(3).MongoError;e.exports={PoolClosedError:class extends r{constructor(e){super("Attempted to check out a connection from closed connection pool"),this.name="MongoPoolClosedError",this.address=e.address}},WaitQueueTimeoutError:class extends r{constructor(e){super("Timed out while checking out a connection from connection pool"),this.name="MongoWaitQueueTimeoutError",this.address=e.address}}}},function(e,t,n){"use strict";const r=n(13).ServerType,o=n(8),i=n(135),s=n(201).Connection,a=n(13),c=n(4).makeStateMachine,u=n(3).MongoNetworkError,l=n(9).retrieveBSON(),f=n(0).makeInterruptableAsyncInterval,p=n(0).calculateDurationInMs,d=n(0).now,h=n(200),m=h.ServerHeartbeatStartedEvent,g=h.ServerHeartbeatSucceededEvent,y=h.ServerHeartbeatFailedEvent,b=Symbol("server"),v=Symbol("monitorId"),S=Symbol("connection"),w=Symbol("cancellationToken"),_=Symbol("rttPinger"),O=Symbol("roundTripTime"),T=a.STATE_CLOSED,C=a.STATE_CLOSING,x=c({[C]:[C,"idle",T],[T]:[T,"monitoring"],idle:["idle","monitoring",C],monitoring:["monitoring","idle",C]}),E=new Set([C,T,"monitoring"]);function N(e){return e.s.state===T||e.s.state===C}function I(e){e[v]&&(e[v].stop(),e[v]=null),e[_]&&(e[_].close(),e[_]=void 0),e[w].emit("cancel"),e[v]&&(clearTimeout(e[v]),e[v]=void 0),e[S]&&e[S].destroy({force:!0})}function A(e,t){let n=d();function r(r){e[S]&&(e[S].destroy({force:!0}),e[S]=void 0),e.emit("serverHeartbeatFailed",new y(p(n),r,e.address)),e.emit("resetServer",r),e.emit("resetConnectionPool"),t(r)}if(e.emit("serverHeartbeatStarted",new m(e.address)),null!=e[S]&&!e[S].closed){const i=e.options.connectTimeoutMS,s=e.options.heartbeatFrequencyMS,a=e[b].description.topologyVersion,c=null!=a,u={ismaster:!0},f={socketTimeout:i};return c&&(u.maxAwaitTimeMS=s,u.topologyVersion={processId:(o=a).processId,counter:l.Long.fromNumber(o.counter)},i&&(f.socketTimeout=i+s),f.exhaustAllowed=!0,null==e[_]&&(e[_]=new M(e[w],e.connectOptions))),void e[S].command("admin.$cmd",u,f,(o,i)=>{if(o)return void r(o);const s=i.result,a=e[_],u=c&&a?a.roundTripTime:p(n);e.emit("serverHeartbeatSucceeded",new g(u,s,e.address)),c&&s.topologyVersion?(e.emit("serverHeartbeatStarted",new m(e.address)),n=d()):(e[_]&&(e[_].close(),e[_]=void 0),t(void 0,s))})}var o;i(e.connectOptions,e[w],(o,i)=>{if(i&&N(e))i.destroy({force:!0});else{if(o)return e[S]=void 0,o instanceof u||e.emit("resetConnectionPool"),void r(o);e[S]=i,e.emit("serverHeartbeatSucceeded",new g(p(n),i.ismaster,e.address)),t(void 0,i.ismaster)}})}function k(e){return t=>{function n(){N(e)||x(e,"idle"),t()}x(e,"monitoring"),process.nextTick(()=>e.emit("monitoring",e[b])),A(e,(t,o)=>{if(t&&e[b].description.type===r.Unknown)return e.emit("resetServer",t),n();o&&o.topologyVersion&&setTimeout(()=>{N(e)||e[v].wake()}),n()})}}class M{constructor(e,t){this[S]=null,this[w]=e,this[O]=0,this.closed=!1;const n=t.heartbeatFrequencyMS;this[v]=setTimeout(()=>function e(t,n){const r=d(),o=t[w],s=n.heartbeatFrequencyMS;if(t.closed)return;function a(o){t.closed?o.destroy({force:!0}):(null==t[S]&&(t[S]=o),t[O]=p(r),t[v]=setTimeout(()=>e(t,n),s))}if(null==t[S])return void i(n,o,(e,n)=>{if(e)return t[S]=void 0,void(t[O]=0);a(n)});t[S].command("admin.$cmd",{ismaster:1},e=>{if(e)return t[S]=void 0,void(t[O]=0);a()})}(this,t),n)}get roundTripTime(){return this[O]}close(){this.closed=!0,clearTimeout(this[v]),this[v]=void 0,this[S]&&this[S].destroy({force:!0})}}e.exports={Monitor:class extends o{constructor(e,t){super(t),this[b]=e,this[S]=void 0,this[w]=new o,this[w].setMaxListeners(1/0),this[v]=null,this.s={state:T},this.address=e.description.address,this.options=Object.freeze({connectTimeoutMS:"number"==typeof t.connectionTimeout?t.connectionTimeout:"number"==typeof t.connectTimeoutMS?t.connectTimeoutMS:1e4,heartbeatFrequencyMS:"number"==typeof t.heartbeatFrequencyMS?t.heartbeatFrequencyMS:1e4,minHeartbeatFrequencyMS:"number"==typeof t.minHeartbeatFrequencyMS?t.minHeartbeatFrequencyMS:500});const n=Object.assign({id:"<monitor>",host:e.description.host,port:e.description.port,bson:e.s.bson,connectionType:s},e.s.options,this.options,{raw:!1,promoteLongs:!0,promoteValues:!0,promoteBuffers:!0});delete n.credentials,delete n.autoEncrypter,this.connectOptions=Object.freeze(n)}connect(){if(this.s.state!==T)return;const e=this.options.heartbeatFrequencyMS,t=this.options.minHeartbeatFrequencyMS;this[v]=f(k(this),{interval:e,minInterval:t,immediate:!0})}requestCheck(){E.has(this.s.state)||this[v].wake()}reset(){const e=this[b].description.topologyVersion;if(N(this)||null==e)return;x(this,C),I(this),x(this,"idle");const t=this.options.heartbeatFrequencyMS,n=this.options.minHeartbeatFrequencyMS;this[v]=f(k(this),{interval:t,minInterval:n})}close(){N(this)||(x(this,C),I(this),this.emit("close"),x(this,T))}}}},function(e,t,n){"use strict";const r=n(16),o=n(8).EventEmitter,i=n(86);class s{constructor(e){this.srvRecords=e}addresses(){return new Set(this.srvRecords.map(e=>`${e.name}:${e.port}`))}}e.exports.SrvPollingEvent=s,e.exports.SrvPoller=class extends o{constructor(e){if(super(),!e||!e.srvHost)throw new TypeError("options for SrvPoller must exist and include srvHost");this.srvHost=e.srvHost,this.rescanSrvIntervalMS=6e4,this.heartbeatFrequencyMS=e.heartbeatFrequencyMS||1e4,this.logger=r("srvPoller",e),this.haMode=!1,this.generation=0,this._timeout=null}get srvAddress(){return`_mongodb._tcp.${this.srvHost}`}get intervalMS(){return this.haMode?this.heartbeatFrequencyMS:this.rescanSrvIntervalMS}start(){this._timeout||this.schedule()}stop(){this._timeout&&(clearTimeout(this._timeout),this.generation+=1,this._timeout=null)}schedule(){clearTimeout(this._timeout),this._timeout=setTimeout(()=>this._poll(),this.intervalMS)}success(e){this.haMode=!1,this.schedule(),this.emit("srvRecordDiscovery",new s(e))}failure(e,t){this.logger.warn(e,t),this.haMode=!0,this.schedule()}parentDomainMismatch(e){this.logger.warn(`parent domain mismatch on SRV record (${e.name}:${e.port})`,e)}_poll(){const e=this.generation;i.resolveSrv(this.srvAddress,(t,n)=>{if(e!==this.generation)return;if(t)return void this.failure("DNS error",t);const r=[];n.forEach(e=>{!function(e,t){const n=/^.*?\./,r=`.${e.replace(n,"")}`,o=`.${t.replace(n,"")}`;return r.endsWith(o)}(e.name,this.srvHost)?this.parentDomainMismatch(e):r.push(e)}),r.length?this.success(r):this.failure("No valid addresses found at host")})}}},function(e,t,n){"use strict";const r=n(13).ServerType,o=n(13).TopologyType,i=n(10),s=n(3).MongoError;function a(e,t){const n=Object.keys(e),r=Object.keys(t);for(let o=0;o<n.length;++o){const i=n[o];if(-1===r.indexOf(i)||t[i]!==e[i])return!1}return!0}function c(e,t){const n=t.reduce((e,t)=>-1===e?t.roundTripTime:Math.min(t.roundTripTime,e),-1),r=n+e.localThresholdMS;return t.reduce((e,t)=>(t.roundTripTime<=r&&t.roundTripTime>=n&&e.push(t),e),[])}function u(e){return e.type===r.RSPrimary}function l(e){return e.type===r.RSSecondary}function f(e){return e.type===r.RSSecondary||e.type===r.RSPrimary}function p(e){return e.type!==r.Unknown}e.exports={writableServerSelector:function(){return function(e,t){return c(e,t.filter(e=>e.isWritable))}},readPreferenceServerSelector:function(e){if(!e.isValid())throw new TypeError("Invalid read preference specified");return function(t,n){const r=t.commonWireVersion;if(r&&e.minWireVersion&&e.minWireVersion>r)throw new s(`Minimum wire version '${e.minWireVersion}' required, but found '${r}'`);if(t.type===o.Unknown)return[];if(t.type===o.Single||t.type===o.Sharded)return c(t,n.filter(p));const d=e.mode;if(d===i.PRIMARY)return n.filter(u);if(d===i.PRIMARY_PREFERRED){const e=n.filter(u);if(e.length)return e}const h=d===i.NEAREST?f:l,m=c(t,function(e,t){if(null==e.tags||Array.isArray(e.tags)&&0===e.tags.length)return t;for(let n=0;n<e.tags.length;++n){const r=e.tags[n],o=t.reduce((e,t)=>(a(r,t.tags)&&e.push(t),e),[]);if(o.length)return o}return[]}(e,function(e,t,n){if(null==e.maxStalenessSeconds||e.maxStalenessSeconds<0)return n;const r=e.maxStalenessSeconds,i=(t.heartbeatFrequencyMS+1e4)/1e3;if(r<i)throw new s(`maxStalenessSeconds must be at least ${i} seconds`);if(r<90)throw new s("maxStalenessSeconds must be at least 90 seconds");if(t.type===o.ReplicaSetWithPrimary){const r=Array.from(t.servers.values()).filter(u)[0];return n.reduce((n,o)=>((o.lastUpdateTime-o.lastWriteDate-(r.lastUpdateTime-r.lastWriteDate)+t.heartbeatFrequencyMS)/1e3<=e.maxStalenessSeconds&&n.push(o),n),[])}if(t.type===o.ReplicaSetNoPrimary){if(0===n.length)return n;const r=n.reduce((e,t)=>t.lastWriteDate>e.lastWriteDate?t:e);return n.reduce((n,o)=>((r.lastWriteDate-o.lastWriteDate+t.heartbeatFrequencyMS)/1e3<=e.maxStalenessSeconds&&n.push(o),n),[])}return n}(e,t,n.filter(h))));return d===i.SECONDARY_PREFERRED&&0===m.length?n.filter(u):m}}}},function(e,t,n){"use strict";const r=n(89),o=n(137),i=n(86),s=n(3).MongoParseError,a=n(10),c=n(0).emitWarningOnce,u=/(mongodb(?:\+srv|)):\/\/(?: (?:[^:]*) (?: : ([^@]*) )? @ )?([^/?]*)(?:\/|)(.*)/,l=new Set(["sslCA","sslCert","sslKey","tlsCAFile","tlsCertificateKeyFile"].map(e=>e.toLowerCase()));function f(e,t){const n=/^.*?\./,r=`.${e.replace(n,"")}`,o=`.${t.replace(n,"")}`;return r.endsWith(o)}function p(e,t){if(Array.isArray(t))1===(t=t.filter((e,n)=>t.indexOf(e)===n)).length&&(t=t[0]);else if(t.indexOf(":")>0)t=t.split(",").reduce((t,n)=>{const r=n.split(":");return t[r[0]]=p(e,r[1]),t},{});else if(t.indexOf(",")>0)t=t.split(",").map(t=>p(e,t));else if("true"===t.toLowerCase()||"false"===t.toLowerCase())t="true"===t.toLowerCase();else if(!Number.isNaN(t)&&!h.has(e)){const e=parseFloat(t);Number.isNaN(e)||(t=parseFloat(t))}return t}const d=new Set(["slaveok","slave_ok","sslvalidate","fsync","safe","retrywrites","j"]),h=new Set(["authsource","replicaset"]),m=new Set(["GSSAPI","MONGODB-AWS","MONGODB-X509","MONGODB-CR","DEFAULT","SCRAM-SHA-1","SCRAM-SHA-256","PLAIN"]),g={replicaset:"replicaSet",connecttimeoutms:"connectTimeoutMS",sockettimeoutms:"socketTimeoutMS",maxpoolsize:"maxPoolSize",minpoolsize:"minPoolSize",maxidletimems:"maxIdleTimeMS",waitqueuemultiple:"waitQueueMultiple",waitqueuetimeoutms:"waitQueueTimeoutMS",wtimeoutms:"wtimeoutMS",readconcern:"readConcern",readconcernlevel:"readConcernLevel",readpreference:"readPreference",maxstalenessseconds:"maxStalenessSeconds",readpreferencetags:"readPreferenceTags",authsource:"authSource",authmechanism:"authMechanism",authmechanismproperties:"authMechanismProperties",gssapiservicename:"gssapiServiceName",localthresholdms:"localThresholdMS",serverselectiontimeoutms:"serverSelectionTimeoutMS",serverselectiontryonce:"serverSelectionTryOnce",heartbeatfrequencyms:"heartbeatFrequencyMS",retrywrites:"retryWrites",uuidrepresentation:"uuidRepresentation",zlibcompressionlevel:"zlibCompressionLevel",tlsallowinvalidcertificates:"tlsAllowInvalidCertificates",tlsallowinvalidhostnames:"tlsAllowInvalidHostnames",tlsinsecure:"tlsInsecure",tlscafile:"tlsCAFile",tlscertificatekeyfile:"tlsCertificateKeyFile",tlscertificatekeyfilepassword:"tlsCertificateKeyFilePassword",wtimeout:"wTimeoutMS",j:"journal",directconnection:"directConnection"};function y(e,t,n,r){if("journal"===t?t="j":"wtimeoutms"===t&&(t="wtimeout"),d.has(t)?n="true"===n||!0===n:"appname"===t?n=decodeURIComponent(n):"readconcernlevel"===t&&(e.readConcernLevel=n,t="readconcern",n={level:n}),"compressors"===t&&!(n=Array.isArray(n)?n:[n]).every(e=>"snappy"===e||"zlib"===e))throw new s("Value for `compressors` must be at least one of: `snappy`, `zlib`");if("authmechanism"===t&&!m.has(n))throw new s(`Value for authMechanism must be one of: ${Array.from(m).join(", ")}, found: ${n}`);if("readpreference"===t&&!a.isValid(n))throw new s("Value for `readPreference` must be one of: `primary`, `primaryPreferred`, `secondary`, `secondaryPreferred`, `nearest`");if("zlibcompressionlevel"===t&&(n<-1||n>9))throw new s("zlibCompressionLevel must be an integer between -1 and 9");"compressors"!==t&&"zlibcompressionlevel"!==t||(e.compression=e.compression||{},e=e.compression),"authmechanismproperties"===t&&("string"==typeof n.SERVICE_NAME&&(e.gssapiServiceName=n.SERVICE_NAME),"string"==typeof n.SERVICE_REALM&&(e.gssapiServiceRealm=n.SERVICE_REALM),void 0!==n.CANONICALIZE_HOST_NAME&&(e.gssapiCanonicalizeHostName=n.CANONICALIZE_HOST_NAME)),"readpreferencetags"===t&&(n=Array.isArray(n)?function(e){const t=[];for(let n=0;n<e.length;n++)t[n]={},e[n].split(",").forEach(e=>{const r=e.split(":");t[n][r[0]]=r[1]});return t}(n):[n]),r.caseTranslate&&g[t]?e[g[t]]=n:e[t]=n}const b=new Set(["GSSAPI","MONGODB-CR","PLAIN","SCRAM-SHA-1","SCRAM-SHA-256"]);function v(e,t){const n={};let r=o.parse(e);!function(e){const t=Object.keys(e);if(-1!==t.indexOf("tlsInsecure")&&(-1!==t.indexOf("tlsAllowInvalidCertificates")||-1!==t.indexOf("tlsAllowInvalidHostnames")))throw new s("The `tlsInsecure` option cannot be used with `tlsAllowInvalidCertificates` or `tlsAllowInvalidHostnames`.");const n=S("tls",e,t),r=S("ssl",e,t);if(null!=n&&null!=r&&n!==r)throw new s("All values of `tls` and `ssl` must be the same.")}(r);for(const e in r){const o=r[e];if(""===o||null==o)throw new s("Incomplete key value pair for option");const i=e.toLowerCase();y(n,i,l.has(i)?o:p(i,o),t)}return n.wtimeout&&n.wtimeoutms&&(delete n.wtimeout,c("Unsupported option `wtimeout` specified")),Object.keys(n).length?n:null}function S(e,t,n){const r=-1!==n.indexOf(e);let o;if(o=Array.isArray(t[e])?t[e][0]:t[e],r&&Array.isArray(t[e])){const n=t[e][0];t[e].forEach(t=>{if(t!==n)throw new s(`All values of ${e} must be the same.`)})}return o}const w="mongodb+srv",_=["mongodb",w];function O(e,t,n){"function"==typeof t&&(n=t,t={}),t=Object.assign({},{caseTranslate:!0},t);try{r.parse(e)}catch(e){return n(new s("URI malformed, cannot be parsed"))}const a=e.match(u);if(!a)return n(new s("Invalid connection string"));const c=a[1];if(-1===_.indexOf(c))return n(new s("Invalid protocol provided"));const l=a[4].split("?"),p=l.length>0?l[0]:null,d=l.length>1?l[1]:null;let h;try{h=v(d,t)}catch(e){return n(e)}if(h=Object.assign({},h,t),c===w)return function(e,t,n){const a=r.parse(e,!0);if(t.directConnection||t.directconnection)return n(new s("directConnection not supported with SRV URI"));if(a.hostname.split(".").length<3)return n(new s("URI does not have hostname, domain name and tld"));if(a.domainLength=a.hostname.split(".").length,a.pathname&&a.pathname.match(","))return n(new s("Invalid URI, cannot contain multiple hostnames"));if(a.port)return n(new s(`Ports not accepted with '${w}' URIs`));const c=a.host;i.resolveSrv(`_mongodb._tcp.${c}`,(e,u)=>{if(e)return n(e);if(0===u.length)return n(new s("No addresses found at host"));for(let e=0;e<u.length;e++)if(!f(u[e].name,a.hostname,a.domainLength))return n(new s("Server record does not share hostname with parent URI"));a.protocol="mongodb",a.host=u.map(e=>`${e.name}:${e.port}`).join(","),"ssl"in t||a.search&&"ssl"in a.query&&null!==a.query.ssl||(a.query.ssl=!0),i.resolveTxt(c,(e,i)=>{if(e){if("ENODATA"!==e.code&&"ENOTFOUND"!==e.code)return n(e);i=null}if(i){if(i.length>1)return n(new s("Multiple text records not allowed"));if(i=o.parse(i[0].join("")),Object.keys(i).some(e=>"authSource"!==e&&"replicaSet"!==e))return n(new s("Text record must only set `authSource` or `replicaSet`"));a.query=Object.assign({},i,a.query)}a.search=o.stringify(a.query),O(r.format(a),t,(e,t)=>{e?n(e):n(null,Object.assign({},t,{srvHost:c}))})})})}(e,h,n);const m={username:null,password:null,db:p&&""!==p?o.unescape(p):null};if(h.auth?(h.auth.username&&(m.username=h.auth.username),h.auth.user&&(m.username=h.auth.user),h.auth.password&&(m.password=h.auth.password)):(h.username&&(m.username=h.username),h.user&&(m.username=h.user),h.password&&(m.password=h.password)),-1!==a[4].split("?")[0].indexOf("@"))return n(new s("Unescaped slash in userinfo section"));const g=a[3].split("@");if(g.length>2)return n(new s("Unescaped at-sign in authority section"));if(null==g[0]||""===g[0])return n(new s("No username provided in authority section"));if(g.length>1){const e=g.shift().split(":");if(e.length>2)return n(new s("Unescaped colon in authority section"));if(""===e[0])return n(new s("Invalid empty username provided"));m.username||(m.username=o.unescape(e[0])),m.password||(m.password=e[1]?o.unescape(e[1]):null)}let y=null;const S=g.shift().split(",").map(e=>{let t=r.parse(`mongodb://${e}`);if("/:"===t.path)return y=new s("Double colon in host identifier"),null;if(e.match(/\.sock/)&&(t.hostname=o.unescape(e),t.port=null),Number.isNaN(t.port))return void(y=new s("Invalid port (non-numeric string)"));const n={host:t.hostname,port:t.port?parseInt(t.port):27017};if(0!==n.port)if(n.port>65535)y=new s("Invalid port (larger than 65535) with hostname");else{if(!(n.port<0))return n;y=new s("Invalid port (negative number)")}else y=new s("Invalid port (zero) with hostname")}).filter(e=>!!e);if(y)return n(y);if(0===S.length||""===S[0].host||null===S[0].host)return n(new s("No hostname or hostnames provided in connection string"));if(!!h.directConnection&&1!==S.length)return n(new s("directConnection option requires exactly one host"));null==h.directConnection&&1===S.length&&null==h.replicaSet&&(h.directConnection=!0);const T={hosts:S,auth:m.db||m.username?m:null,options:Object.keys(h).length?h:null};var C;T.auth&&T.auth.db?T.defaultDatabase=T.auth.db:T.defaultDatabase="test",T.options=((C=T.options).tls&&(C.ssl=C.tls),C.tlsInsecure?(C.checkServerIdentity=!1,C.sslValidate=!1):Object.assign(C,{checkServerIdentity:!C.tlsAllowInvalidHostnames,sslValidate:!C.tlsAllowInvalidCertificates}),C.tlsCAFile&&(C.ssl=!0,C.sslCA=C.tlsCAFile),C.tlsCertificateKeyFile&&(C.ssl=!0,C.tlsCertificateFile?(C.sslCert=C.tlsCertificateFile,C.sslKey=C.tlsCertificateKeyFile):(C.sslKey=C.tlsCertificateKeyFile,C.sslCert=C.tlsCertificateKeyFile)),C.tlsCertificateKeyFilePassword&&(C.ssl=!0,C.sslPass=C.tlsCertificateKeyFilePassword),C);try{!function(e){if(null==e.options)return;const t=e.options,n=t.authsource||t.authSource;null!=n&&(e.auth=Object.assign({},e.auth,{db:n}));const r=t.authmechanism||t.authMechanism;if(null!=r){if(b.has(r)&&(!e.auth||null==e.auth.username))throw new s(`Username required for mechanism \`${r}\``);if("GSSAPI"===r){if(null!=n&&"$external"!==n)throw new s(`Invalid source \`${n}\` for mechanism \`${r}\` specified.`);e.auth=Object.assign({},e.auth,{db:"$external"})}if("MONGODB-AWS"===r){if(null!=n&&"$external"!==n)throw new s(`Invalid source \`${n}\` for mechanism \`${r}\` specified.`);e.auth=Object.assign({},e.auth,{db:"$external"})}if("MONGODB-X509"===r){if(e.auth&&null!=e.auth.password)throw new s(`Password not allowed for mechanism \`${r}\``);if(null!=n&&"$external"!==n)throw new s(`Invalid source \`${n}\` for mechanism \`${r}\` specified.`);e.auth=Object.assign({},e.auth,{db:"$external"})}"PLAIN"===r&&e.auth&&null==e.auth.db&&(e.auth=Object.assign({},e.auth,{db:"$external"}))}e.auth&&null==e.auth.db&&(e.auth=Object.assign({},e.auth,{db:"admin"}))}(T)}catch(e){return n(e)}n(null,T)}e.exports=O},function(e,t,n){"use strict";const r=n(8).EventEmitter;e.exports=class extends r{constructor(){super()}instrument(e,t){this.$MongoClient=e;const n=this.$prototypeConnect=e.prototype.connect,r=this;e.prototype.connect=function(e){return this.s.options.monitorCommands=!0,this.on("commandStarted",e=>r.emit("started",e)),this.on("commandSucceeded",e=>r.emit("succeeded",e)),this.on("commandFailed",e=>r.emit("failed",e)),n.call(this,e)},"function"==typeof t&&t(null,this)}uninstrument(){this.$MongoClient.prototype.connect=this.$prototypeConnect}}},function(e,t,n){"use strict";const r=n(60).buildCountCommand,o=n(0).handleCallback,i=n(2).MongoError,s=Array.prototype.push,a=n(17).CursorState;function c(e,t){if(0!==e.bufferedCount())return e._next(t),c}e.exports={count:function(e,t,n,o){t&&("number"==typeof e.cursorSkip()&&(n.skip=e.cursorSkip()),"number"==typeof e.cursorLimit()&&(n.limit=e.cursorLimit())),n.readPreference&&e.setReadPreference(n.readPreference),"number"!=typeof n.maxTimeMS&&e.cmd&&"number"==typeof e.cmd.maxTimeMS&&(n.maxTimeMS=e.cmd.maxTimeMS);let i,s={};s.skip=n.skip,s.limit=n.limit,s.hint=n.hint,s.maxTimeMS=n.maxTimeMS,s.collectionName=e.namespace.collection;try{i=r(e,e.cmd.query,s)}catch(e){return o(e)}e.server=e.topology.s.coreTopology,e.topology.command(e.namespace.withCollection("$cmd"),i,e.options,(e,t)=>{o(e,t?t.result.n:null)})},each:function e(t,n){if(!n)throw i.create({message:"callback is mandatory",driver:!0});if(t.isNotified())return;if(t.s.state===a.CLOSED||t.isDead())return o(n,i.create({message:"Cursor is closed",driver:!0}));t.s.state===a.INIT&&(t.s.state=a.OPEN);let r=null;if(t.bufferedCount()>0){for(;r=c(t,n);)r(t,n);e(t,n)}else t.next((r,i)=>r?o(n,r):null==i?t.close({skipKillCursors:!0},()=>o(n,null,null)):void(!1!==o(n,null,i)&&e(t,n)))},toArray:function(e,t){const n=[];e.rewind(),e.s.state=a.INIT;const r=()=>{e._next((i,a)=>{if(i)return o(t,i);if(null==a)return e.close({skipKillCursors:!0},()=>o(t,null,n));if(n.push(a),e.bufferedCount()>0){let t=e.readBufferedDocuments(e.bufferedCount());e.s.transforms&&"function"==typeof e.s.transforms.doc&&(t=t.map(e.s.transforms.doc)),s.apply(n,t)}r()})};r()}}},function(e,t,n){"use strict";const r=n(14).buildCountCommand,o=n(1).OperationBase;e.exports=class extends o{constructor(e,t,n){super(n),this.cursor=e,this.applySkipLimit=t}execute(e){const t=this.cursor,n=this.applySkipLimit,o=this.options;n&&("number"==typeof t.cursorSkip()&&(o.skip=t.cursorSkip()),"number"==typeof t.cursorLimit()&&(o.limit=t.cursorLimit())),o.readPreference&&t.setReadPreference(o.readPreference),"number"!=typeof o.maxTimeMS&&t.cmd&&"number"==typeof t.cmd.maxTimeMS&&(o.maxTimeMS=t.cmd.maxTimeMS);let i,s={};s.skip=o.skip,s.limit=o.limit,s.hint=o.hint,s.maxTimeMS=o.maxTimeMS,s.collectionName=t.namespace.collection;try{i=r(t,t.cmd.query,s)}catch(t){return e(t)}t.server=t.topology.s.coreTopology,t.topology.command(t.namespace.withCollection("$cmd"),i,t.options,(t,n)=>{e(t,n?n.result.n:null)})}}},function(e,t,n){"use strict";const r=n(141),o=r.BulkOperationBase,i=r.Batch,s=r.bson,a=n(0).toError;function c(e,t,n){const o=s.calculateObjectSize(n,{checkKeys:!1,ignoreUndefined:!1});if(o>=e.s.maxBsonObjectSize)throw a("document is larger than the maximum size "+e.s.maxBsonObjectSize);e.s.currentBatch=null,t===r.INSERT?e.s.currentBatch=e.s.currentInsertBatch:t===r.UPDATE?e.s.currentBatch=e.s.currentUpdateBatch:t===r.REMOVE&&(e.s.currentBatch=e.s.currentRemoveBatch);const c=e.s.maxKeySize;if(null==e.s.currentBatch&&(e.s.currentBatch=new i(t,e.s.currentIndex)),(e.s.currentBatch.size+1>=e.s.maxWriteBatchSize||e.s.currentBatch.size>0&&e.s.currentBatch.sizeBytes+c+o>=e.s.maxBatchSizeBytes||e.s.currentBatch.batchType!==t)&&(e.s.batches.push(e.s.currentBatch),e.s.currentBatch=new i(t,e.s.currentIndex)),Array.isArray(n))throw a("operation passed in cannot be an Array");return e.s.currentBatch.operations.push(n),e.s.currentBatch.originalIndexes.push(e.s.currentIndex),e.s.currentIndex=e.s.currentIndex+1,t===r.INSERT?(e.s.currentInsertBatch=e.s.currentBatch,e.s.bulkResult.insertedIds.push({index:e.s.bulkResult.insertedIds.length,_id:n._id})):t===r.UPDATE?e.s.currentUpdateBatch=e.s.currentBatch:t===r.REMOVE&&(e.s.currentRemoveBatch=e.s.currentBatch),e.s.currentBatch.size+=1,e.s.currentBatch.sizeBytes+=c+o,e}class u extends o{constructor(e,t,n){n=n||{},super(e,t,n=Object.assign(n,{addToOperationsList:c}),!1)}handleWriteError(e,t){return!this.s.batches.length&&super.handleWriteError(e,t)}}function l(e,t,n){return new u(e,t,n)}l.UnorderedBulkOperation=u,e.exports=l,e.exports.Bulk=u},function(e,t,n){"use strict";const r=n(141),o=r.BulkOperationBase,i=r.Batch,s=r.bson,a=n(0).toError;function c(e,t,n){const o=s.calculateObjectSize(n,{checkKeys:!1,ignoreUndefined:!1});if(o>=e.s.maxBsonObjectSize)throw a("document is larger than the maximum size "+e.s.maxBsonObjectSize);null==e.s.currentBatch&&(e.s.currentBatch=new i(t,e.s.currentIndex));const c=e.s.maxKeySize;if((e.s.currentBatchSize+1>=e.s.maxWriteBatchSize||e.s.currentBatchSize>0&&e.s.currentBatchSizeBytes+c+o>=e.s.maxBatchSizeBytes||e.s.currentBatch.batchType!==t)&&(e.s.batches.push(e.s.currentBatch),e.s.currentBatch=new i(t,e.s.currentIndex),e.s.currentBatchSize=0,e.s.currentBatchSizeBytes=0),t===r.INSERT&&e.s.bulkResult.insertedIds.push({index:e.s.currentIndex,_id:n._id}),Array.isArray(n))throw a("operation passed in cannot be an Array");return e.s.currentBatch.originalIndexes.push(e.s.currentIndex),e.s.currentBatch.operations.push(n),e.s.currentBatchSize+=1,e.s.currentBatchSizeBytes+=c+o,e.s.currentIndex+=1,e}class u extends o{constructor(e,t,n){n=n||{},super(e,t,n=Object.assign(n,{addToOperationsList:c}),!0)}}function l(e,t,n){return new u(e,t,n)}l.OrderedBulkOperation=u,e.exports=l,e.exports.Bulk=u},function(e,t,n){"use strict";const r=n(95);e.exports=class extends r{constructor(e,t,n){const r=[{$match:t}];"number"==typeof n.skip&&r.push({$skip:n.skip}),"number"==typeof n.limit&&r.push({$limit:n.limit}),r.push({$group:{_id:1,n:{$sum:1}}}),super(e,r,n)}execute(e,t){super.execute(e,(e,n)=>{if(e)return void t(e,null);const r=n.result;if(null==r.cursor||null==r.cursor.firstBatch)return void t(null,0);const o=r.cursor.firstBatch;t(null,o.length?o[0].n:0)})}}},function(e,t,n){"use strict";const r=n(1).OperationBase,o=n(14).removeDocuments,i=n(1).Aspect;class s extends r{constructor(e,t,n){super(n),this.collection=e,this.filter=t}execute(e){const t=this.collection,n=this.filter,r=this.options;r.single=!1,o(t,n,r,(t,n)=>{if(null!=e){if(t&&e)return e(t);if(null==n)return e(null,{result:{ok:1}});if(this.explain)return e(void 0,n.result);n.deletedCount=n.result.n,e(null,n)}})}}(0,n(1).defineAspects)(s,[i.EXPLAINABLE]),e.exports=s},function(e,t,n){"use strict";const r=n(1).OperationBase,o=n(14).removeDocuments,i=n(1).Aspect;class s extends r{constructor(e,t,n){super(n),this.collection=e,this.filter=t}execute(e){const t=this.collection,n=this.filter,r=this.options;r.single=!0,o(t,n,r,(t,n)=>{if(null!=e){if(t&&e)return e(t);if(null==n)return e(null,{result:{ok:1}});if(this.explain)return e(void 0,n.result);n.deletedCount=n.result.n,e(null,n)}})}}(0,n(1).defineAspects)(s,[i.EXPLAINABLE]),e.exports=s},function(e,t,n){"use strict";const r=n(1).Aspect,o=n(1).defineAspects,i=n(27),s=n(0).decorateWithCollation,a=n(0).decorateWithReadConcern,c=n(4).maxWireVersion,u=n(94).MongoError;class l extends i{constructor(e,t,n,r){super(e,r),this.collection=e,this.key=t,this.query=n}execute(e,t){const n=this.collection,r=this.key,o=this.query,i=this.options,l={distinct:n.collectionName,key:r,query:o};"number"==typeof i.maxTimeMS&&(l.maxTimeMS=i.maxTimeMS),a(l,n,i);try{s(l,n,i)}catch(e){return t(e,null)}this.explain&&c(e)<4?t(new u("server does not support explain on distinct")):super.executeCommand(e,l,(e,n)=>{e?t(e):t(null,this.options.full||this.explain?n:n.values)})}}o(l,[r.READ_OPERATION,r.RETRYABLE,r.EXECUTE_WITH_SELECTION,r.EXPLAINABLE]),e.exports=l},function(e,t,n){"use strict";const r=n(1).Aspect,o=n(1).defineAspects,i=n(211),s=n(0).handleCallback;class a extends i{constructor(e,t){super(e,"*",t)}execute(e){super.execute(t=>{if(t)return s(e,t,!1);s(e,null,!0)})}}o(a,r.WRITE_OPERATION),e.exports=a},function(e,t,n){"use strict";const r=n(1).Aspect,o=n(1).defineAspects,i=n(27);class s extends i{constructor(e,t,n){void 0===n&&(n=t,t=void 0),super(e,n),this.collectionName=e.s.namespace.collection,t&&(this.query=t)}execute(e,t){const n=this.options,r={count:this.collectionName};this.query&&(r.query=this.query),"number"==typeof n.skip&&(r.skip=n.skip),"number"==typeof n.limit&&(r.limit=n.limit),n.hint&&(r.hint=n.hint),super.executeCommand(e,r,(e,n)=>{e?t(e):t(null,n.n)})}}o(s,[r.READ_OPERATION,r.RETRYABLE,r.EXECUTE_WITH_SELECTION]),e.exports=s},function(e,t,n){"use strict";const r=n(1).OperationBase,o=n(1).Aspect,i=n(1).defineAspects,s=n(2).ReadPreference,a=n(4).maxWireVersion,c=n(3).MongoError;class u extends r{constructor(e,t,n,r){super(r),this.ns=t,this.cmd=n,this.readPreference=s.resolve(e,this.options)}execute(e,t){if(this.server=e,this.readPreference=s.resolve(this,this.options),void 0!==this.cmd.allowDiskUse&&a(e)<4)return void t(new c("The `allowDiskUse` option is not supported on MongoDB < 3.2"));this.explain&&(this.options.explain=this.explain.verbosity);const n=this.cursorState||{};e.query(this.ns.toString(),this.cmd,n,this.options,t)}}i(u,[o.READ_OPERATION,o.RETRYABLE,o.EXECUTE_WITH_SELECTION,o.EXPLAINABLE]),e.exports=u},function(e,t,n){"use strict";const r=n(0).handleCallback,o=n(1).OperationBase,i=n(0).toError,s=n(1).Aspect;class a extends o{constructor(e,t,n){super(n),this.collection=e,this.query=t}execute(e){const t=this.collection,n=this.query,o=this.options;try{t.find(n,o).limit(-1).batchSize(1).next((t,n)=>{if(null!=t)return r(e,i(t),null);r(e,null,n)})}catch(t){e(t)}}}(0,n(1).defineAspects)(a,[s.EXPLAINABLE]),e.exports=a},function(e,t,n){"use strict";const r=n(96);e.exports=class extends r{constructor(e,t,n){const r=Object.assign({},n);if(r.fields=n.projection,r.remove=!0,null==t||"object"!=typeof t)throw new TypeError("Filter parameter must be an object");super(e,t,r.sort,null,r)}}},function(e,t,n){"use strict";const r=n(96),o=n(0).hasAtomicOperators;e.exports=class extends r{constructor(e,t,n,r){const i=Object.assign({},r);if(i.fields=r.projection,i.update=!0,i.new=void 0!==r.returnOriginal&&!r.returnOriginal,i.upsert=void 0!==r.upsert&&!!r.upsert,null==t||"object"!=typeof t)throw new TypeError("Filter parameter must be an object");if(null==n||"object"!=typeof n)throw new TypeError("Replacement parameter must be an object");if(o(n))throw new TypeError("Replacement document must not contain atomic operators");super(e,t,i.sort,n,i)}}},function(e,t,n){"use strict";const r=n(96),o=n(0).hasAtomicOperators;e.exports=class extends r{constructor(e,t,n,r){const i=Object.assign({},r);if(i.fields=r.projection,i.update=!0,i.new="boolean"==typeof r.returnOriginal&&!r.returnOriginal,i.upsert="boolean"==typeof r.upsert&&r.upsert,null==t||"object"!=typeof t)throw new TypeError("Filter parameter must be an object");if(null==n||"object"!=typeof n)throw new TypeError("Update parameter must be an object");if(!o(n))throw new TypeError("Update document requires atomic operators");super(e,t,i.sort,n,i)}}},function(e,t,n){"use strict";const r=n(1).Aspect,o=n(1).defineAspects,i=n(1).OperationBase,s=n(0).decorateCommand,a=n(0).decorateWithReadConcern,c=n(11).executeCommand,u=n(0).handleCallback,l=n(2).ReadPreference,f=n(0).toError;class p extends i{constructor(e,t,n,r){super(r),this.collection=e,this.x=t,this.y=n}execute(e){const t=this.collection,n=this.x,r=this.y;let o=this.options,i={geoSearch:t.collectionName,near:[n,r]};i=s(i,o,["readPreference","session"]),o=Object.assign({},o),o.readPreference=l.resolve(t,o),a(i,t,o),c(t.s.db,i,o,(t,n)=>{if(t)return u(e,t);(n.err||n.errmsg)&&u(e,f(n)),u(e,null,n)})}}o(p,r.READ_OPERATION),e.exports=p},function(e,t,n){"use strict";const r=n(1).OperationBase,o=n(14).indexInformation;e.exports=class extends r{constructor(e,t){super(t),this.collection=e}execute(e){const t=this.collection;let n=this.options;n=Object.assign({},{full:!0},n),o(t.s.db,t.collectionName,n,e)}}},function(e,t,n){"use strict";const r=n(1).OperationBase,o=n(0).handleCallback,i=n(11).indexInformation;e.exports=class extends r{constructor(e,t,n){super(n),this.collection=e,this.indexes=t}execute(e){const t=this.collection,n=this.indexes,r=this.options;i(t.s.db,t.collectionName,r,(t,r)=>{if(null!=t)return o(e,t,null);if(!Array.isArray(n))return o(e,null,null!=r[n]);for(let t=0;t<n.length;t++)if(null==r[n[t]])return o(e,null,!1);return o(e,null,!0)})}}},function(e,t,n){"use strict";const r=n(1).OperationBase,o=n(209),i=n(2).MongoError,s=n(14).prepareDocs;e.exports=class extends r{constructor(e,t,n){super(n),this.collection=e,this.docs=t}execute(e){const t=this.collection;let n=this.docs;const r=this.options;if(!Array.isArray(n))return e(i.create({message:"docs parameter must be an array of documents",driver:!0}));r.serializeFunctions=r.serializeFunctions||t.s.serializeFunctions,n=s(t,n,r),new o(t,[{insertMany:n}],r).execute((t,r)=>{if(t)return e(t,null);e(null,function(e,t){const n={result:{ok:1,n:t.insertedCount},ops:e,insertedCount:t.insertedCount,insertedIds:t.insertedIds};t.getLastOp()&&(n.result.opTime=t.getLastOp());return n}(n,r))})}}},function(e,t,n){"use strict";const r=n(2).MongoError,o=n(1).OperationBase,i=n(14).insertDocuments;e.exports=class extends o{constructor(e,t,n){super(n),this.collection=e,this.doc=t}execute(e){const t=this.collection,n=this.doc,o=this.options;if(Array.isArray(n))return e(r.create({message:"doc parameter must be an object",driver:!0}));i(t,[n],o,(t,r)=>{if(null!=e){if(t&&e)return e(t);if(null==r)return e(null,{result:{ok:1}});r.insertedCount=r.result.n,r.insertedId=n._id,e&&e(null,r)}})}}},function(e,t,n){"use strict";const r=n(213),o=n(0).handleCallback;e.exports=class extends r{constructor(e,t){super(e,t)}execute(e){super.execute((t,n)=>{if(t)return o(e,t);o(e,null,!(!n||!n.capped))})}}},function(e,t,n){"use strict";const r=n(27),o=n(1).Aspect,i=n(1).defineAspects,s=n(4).maxWireVersion;class a extends r{constructor(e,t){super(e,t,{fullResponse:!0}),this.collectionNamespace=e.s.namespace}execute(e,t){if(s(e)<3){const n=this.collectionNamespace.withCollection("system.indexes").toString(),r=this.collectionNamespace.toString();return void e.query(n,{query:{ns:r}},{},this.options,t)}const n=this.options.batchSize?{batchSize:this.options.batchSize}:{};super.executeCommand(e,{listIndexes:this.collectionNamespace.collection,cursor:n},t)}}i(a,[o.READ_OPERATION,o.RETRYABLE,o.EXECUTE_WITH_SELECTION]),e.exports=a},function(e,t,n){"use strict";const r=n(0).applyWriteConcern,o=n(2).BSON.Code,i=n(0).decorateWithCollation,s=n(0).decorateWithReadConcern,a=n(11).executeCommand,c=n(0).handleCallback,u=n(0).isObject,l=n(145).loadDb,f=n(1).OperationBase,p=n(2).ReadPreference,d=n(0).toError,h=n(1).Aspect,m=n(1).defineAspects,g=n(0).decorateWithExplain,y=n(4).maxWireVersion,b=n(94).MongoError,v=["explain","readPreference","session","bypassDocumentValidation","w","wtimeout","j","writeConcern"];class S extends f{constructor(e,t,n,r){super(r),this.collection=e,this.map=t,this.reduce=n}execute(e){const t=this.collection,n=this.map,o=this.reduce;let u=this.options,f={mapReduce:t.collectionName,map:n,reduce:o};for(let e in u)"scope"===e?f[e]=w(u[e]):-1===v.indexOf(e)&&(f[e]=u[e]);u=Object.assign({},u),u.readPreference=p.resolve(t,u),!1!==u.readPreference&&"primary"!==u.readPreference&&u.out&&1!==u.out.inline&&"inline"!==u.out?(u.readPreference="primary",r(f,{db:t.s.db,collection:t},u)):s(f,t,u),!0===u.bypassDocumentValidation&&(f.bypassDocumentValidation=u.bypassDocumentValidation);try{i(f,t,u)}catch(t){return e(t,null)}if(this.explain){if(y(t.s.topology)<9)return void e(new b("server does not support explain on mapReduce"));f=g(f,this.explain)}a(t.s.db,f,u,(n,r)=>{if(n)return c(e,n);if(1!==r.ok||r.err||r.errmsg)return c(e,d(r));if(this.explain)return e(void 0,r);const o={};if(r.timeMillis&&(o.processtime=r.timeMillis),r.counts&&(o.counts=r.counts),r.timing&&(o.timing=r.timing),r.results)return null!=u.verbose&&u.verbose?c(e,null,{results:r.results,stats:o}):c(e,null,r.results);let i=null;if(null!=r.result&&"object"==typeof r.result){const e=r.result;i=new(l())(e.db,t.s.db.s.topology,t.s.db.s.options).collection(e.collection)}else i=t.s.db.collection(r.result);if(null==u.verbose||!u.verbose)return c(e,n,i);c(e,n,{collection:i,stats:o})})}}function w(e){if(!u(e)||"ObjectID"===e._bsontype)return e;const t=Object.keys(e);let n;const r={};for(let i=t.length-1;i>=0;i--)n=t[i],"function"==typeof e[n]?r[n]=new o(String(e[n])):r[n]=w(e[n]);return r}m(S,[h.EXPLAINABLE]),e.exports=S},function(e,t,n){"use strict";const r=n(1).OperationBase,o=n(0).handleCallback;let i;e.exports=class extends r{constructor(e,t){super(t),this.db=e}execute(e){const t=this.db;let r=this.options,s=(i||(i=n(61)),i);r=Object.assign({},r,{nameOnly:!0}),t.listCollections({},r).toArray((n,r)=>{if(null!=n)return o(e,n,null);r=r.filter(e=>-1===e.name.indexOf("$")),o(e,null,r.map(e=>new s(t,t.s.topology,t.databaseName,e.name,t.s.pkFactory,t.s.options)))})}}},function(e,t,n){"use strict";const r=n(27),o=n(1).defineAspects,i=n(1).Aspect;class s extends r{constructor(e,t,n){super(e,n),this.command=t}execute(e,t){const n=this.command;this.executeCommand(e,n,t)}}o(s,[i.EXECUTE_WITH_SELECTION,i.NO_INHERIT_OPTIONS]),e.exports=s},function(e,t,n){"use strict";const r=n(1).Aspect,o=n(1).defineAspects,i=n(23),s=n(0).applyWriteConcern,a=n(145).loadCollection,c=n(2).MongoError,u=n(2).ReadPreference,l=new Set(["w","wtimeout","j","fsync","autoIndexId","strict","serializeFunctions","pkFactory","raw","readPreference","session","readConcern","writeConcern"]);class f extends i{constructor(e,t,n){super(e,n),this.name=t}_buildCommand(){const e=this.name,t=this.options,n={create:e};for(let e in t)null==t[e]||"function"==typeof t[e]||l.has(e)||(n[e]=t[e]);return n}execute(e){const t=this.db,n=this.name,r=this.options,o=a();let i=Object.assign({nameOnly:!0,strict:!1},r);function l(i){if(i)return e(i);try{e(null,new o(t,t.s.topology,t.databaseName,n,t.s.pkFactory,r))}catch(i){e(i)}}i=s(i,{db:t},i),i.strict?t.listCollections({name:n},i).setReadPreference(u.PRIMARY).toArray((t,r)=>t?e(t):r.length>0?e(new c(`Collection ${n} already exists. Currently in strict mode.`)):void super.execute(l)):super.execute(l)}}o(f,r.WRITE_OPERATION),e.exports=f},function(e,t,n){"use strict";const r=n(27),o=n(1).Aspect,i=n(1).defineAspects,s=n(4).maxWireVersion,a=n(140);class c extends r{constructor(e,t,n){super(e,n,{fullResponse:!0}),this.db=e,this.filter=t,this.nameOnly=!!this.options.nameOnly,"number"==typeof this.options.batchSize&&(this.batchSize=this.options.batchSize)}execute(e,t){if(s(e)<3){let n=this.filter;const r=this.db.s.namespace.db;"string"!=typeof n.name||new RegExp("^"+r+"\\.").test(n.name)||(n=Object.assign({},n),n.name=this.db.s.namespace.withCollection(n.name).toString()),null==n&&(n.name=`/${r}/`),n=n.name?{$and:[{name:n.name},{name:/^((?!\$).)*$/}]}:{name:/^((?!\$).)*$/};const o=function(e){const t=`${e}.`;return{doc:e=>{const n=e.name.indexOf(t);return e.name&&0===n&&(e.name=e.name.substr(n+t.length)),e}}}(r);return void e.query(`${r}.${a.SYSTEM_NAMESPACE_COLLECTION}`,{query:n},{batchSize:this.batchSize||1e3},{},(e,n)=>{n&&n.message&&n.message.documents&&Array.isArray(n.message.documents)&&(n.message.documents=n.message.documents.map(o.doc)),t(e,n)})}const n={listCollections:1,filter:this.filter,cursor:this.batchSize?{batchSize:this.batchSize}:{},nameOnly:this.nameOnly};return super.executeCommand(e,n,t)}}i(c,[o.READ_OPERATION,o.RETRYABLE,o.EXECUTE_WITH_SELECTION]),e.exports=c},function(e,t,n){"use strict";const r=n(23);e.exports=class extends r{constructor(e,t,n){super(e,n)}_buildCommand(){return{profile:-1}}execute(e){super.execute((t,n)=>{if(null==t&&1===n.ok){const t=n.was;return 0===t?e(null,"off"):1===t?e(null,"slow_only"):2===t?e(null,"all"):e(new Error("Error: illegal profiling level value "+t),null)}e(null!=t?t:new Error("Error with profile command"),null)})}}},function(e,t,n){"use strict";const r=n(23),o=new Set(["off","slow_only","all"]);e.exports=class extends r{constructor(e,t,n){let r=0;"off"===t?r=0:"slow_only"===t?r=1:"all"===t&&(r=2),super(e,n),this.level=t,this.profile=r}_buildCommand(){return{profile:this.profile}}execute(e){const t=this.level;if(!o.has(t))return e(new Error("Error: illegal profiling level value "+t));super.execute((n,r)=>null==n&&1===r.ok?e(null,t):e(null!=n?n:new Error("Error with profile command"),null))}}},function(e,t,n){"use strict";const r=n(23);e.exports=class extends r{constructor(e,t,n){let r={validate:t};const o=Object.keys(n);for(let e=0;e<o.length;e++)Object.prototype.hasOwnProperty.call(n,o[e])&&"session"!==o[e]&&(r[o[e]]=n[o[e]]);super(e.s.db,n,null,r),this.collectionName=t}execute(e){const t=this.collectionName;super.execute((n,r)=>null!=n?e(n,null):0===r.ok?e(new Error("Error with validate command"),null):null!=r.result&&r.result.constructor!==String?e(new Error("Error with validation data"),null):null!=r.result&&null!=r.result.match(/exception|corrupt/)?e(new Error("Error: invalid collection "+t),null):null==r.valid||r.valid?e(null,r):e(new Error("Error: invalid collection "+t),null))}}},function(e,t,n){"use strict";const r=n(27),o=n(1).Aspect,i=n(1).defineAspects,s=n(0).MongoDBNamespace;class a extends r{constructor(e,t){super(e,t),this.ns=new s("admin","$cmd")}execute(e,t){const n={listDatabases:1};this.options.nameOnly&&(n.nameOnly=Number(n.nameOnly)),this.options.filter&&(n.filter=this.options.filter),"boolean"==typeof this.options.authorizedDatabases&&(n.authorizedDatabases=this.options.authorizedDatabases),super.executeCommand(e,n,t)}}i(a,[o.READ_OPERATION,o.RETRYABLE,o.EXECUTE_WITH_SELECTION]),e.exports=a},function(e,t,n){"use strict";const r=n(1).Aspect,o=n(1).defineAspects,i=n(27),s=n(13).serverType,a=n(13).ServerType,c=n(2).MongoError;class u extends i{constructor(e,t){super(e,t),this.collectionName=e.collectionName}execute(e,t){s(e)===a.Standalone?super.executeCommand(e,{reIndex:this.collectionName},(e,n)=>{e?t(e):t(null,!!n.ok)}):t(new c("reIndex can only be executed on standalone servers."))}}o(u,[r.EXECUTE_WITH_SELECTION]),e.exports=u},function(e,t,n){"use strict";const r=n(1).OperationBase,o=n(14).updateDocuments,i=n(0).hasAtomicOperators;e.exports=class extends r{constructor(e,t,n,r){if(super(r),i(n))throw new TypeError("Replacement document must not contain atomic operators");this.collection=e,this.filter=t,this.replacement=n}execute(e){const t=this.collection,n=this.filter,r=this.replacement,i=this.options;i.multi=!1,o(t,n,r,i,(t,n)=>function(e,t,n,r){if(null==r)return;if(e&&r)return r(e);if(null==t)return r(null,{result:{ok:1}});t.modifiedCount=null!=t.result.nModified?t.result.nModified:t.result.n,t.upsertedId=Array.isArray(t.result.upserted)&&t.result.upserted.length>0?t.result.upserted[0]:null,t.upsertedCount=Array.isArray(t.result.upserted)&&t.result.upserted.length?t.result.upserted.length:0,t.matchedCount=Array.isArray(t.result.upserted)&&t.result.upserted.length>0?0:t.result.n,t.ops=[n],r&&r(null,t)}(t,n,r,e))}}},function(e,t,n){"use strict";const r=n(1).Aspect,o=n(23);class i extends o{constructor(e,t){super(e.s.db,t,e)}_buildCommand(){const e=this.collection,t=this.options,n={collStats:e.collectionName};return null!=t.scale&&(n.scale=t.scale),n}}(0,n(1).defineAspects)(i,r.READ_OPERATION),e.exports=i},function(e,t,n){"use strict";const r=n(1).OperationBase,o=n(14).updateDocuments,i=n(0).hasAtomicOperators,s=n(1).Aspect;class a extends r{constructor(e,t,n,r){if(super(r),!i(n))throw new TypeError("Update document requires atomic operators");this.collection=e,this.filter=t,this.update=n}execute(e){const t=this.collection,n=this.filter,r=this.update,i=this.options;i.multi=!0,o(t,n,r,i,(t,n)=>{if(null!=e){if(t)return e(t);if(null==n)return e(null,{result:{ok:1}});if(this.explain)return e(void 0,n.result);n.modifiedCount=null!=n.result.nModified?n.result.nModified:n.result.n,n.upsertedId=Array.isArray(n.result.upserted)&&n.result.upserted.length>0?n.result.upserted[0]:null,n.upsertedCount=Array.isArray(n.result.upserted)&&n.result.upserted.length?n.result.upserted.length:0,n.matchedCount=Array.isArray(n.result.upserted)&&n.result.upserted.length>0?0:n.result.n,e(null,n)}})}}(0,n(1).defineAspects)(a,[s.EXPLAINABLE]),e.exports=a},function(e,t,n){"use strict";const r=n(1).OperationBase,o=n(14).updateDocuments,i=n(0).hasAtomicOperators,s=n(1).Aspect;class a extends r{constructor(e,t,n,r){if(super(r),!i(n))throw new TypeError("Update document requires atomic operators");this.collection=e,this.filter=t,this.update=n}execute(e){const t=this.collection,n=this.filter,r=this.update,i=this.options;i.multi=!1,o(t,n,r,i,(t,n)=>{if(null!=e){if(t)return e(t);if(null==n)return e(null,{result:{ok:1}});if(this.explain)return e(void 0,n.result);n.modifiedCount=null!=n.result.nModified?n.result.nModified:n.result.n,n.upsertedId=Array.isArray(n.result.upserted)&&n.result.upserted.length>0?n.result.upserted[0]:null,n.upsertedCount=Array.isArray(n.result.upserted)&&n.result.upserted.length?n.result.upserted.length:0,n.matchedCount=Array.isArray(n.result.upserted)&&n.result.upserted.length>0?0:n.result.n,e(null,n)}})}}(0,n(1).defineAspects)(a,[s.EXPLAINABLE]),e.exports=a},function(e,t,n){"use strict";const r=n(2).ReadPreference,o=n(89),i=n(5).format,s=n(2).Logger,a=n(86),c=n(46),u=n(137),l=n(3).MongoParseError;function f(e,t){let n=/^.*?\./,r=`.${e.replace(n,"")}`,o=`.${t.replace(n,"")}`;return!!r.endsWith(o)}function p(e,t,n){let a,u;try{a=function(e,t){let n="",a="",u="",l="admin",f=o.parse(e,!0);if((null==f.hostname||""===f.hostname)&&-1===e.indexOf(".sock"))throw new Error("No hostname or hostnames provided in connection string");if("0"===f.port)throw new Error("Invalid port (zero) with hostname");if(!isNaN(parseInt(f.port,10))&&parseInt(f.port,10)>65535)throw new Error("Invalid port (larger than 65535) with hostname");if(f.path&&f.path.length>0&&"/"!==f.path[0]&&-1===e.indexOf(".sock"))throw new Error("Missing delimiting slash between hosts and options");if(f.query)for(let e in f.query){if(-1!==e.indexOf("::"))throw new Error("Double colon in host identifier");if(""===f.query[e])throw new Error("Query parameter "+e+" is an incomplete value pair")}if(f.auth){let t=f.auth.split(":");if(-1!==e.indexOf(f.auth)&&t.length>2)throw new Error("Username with password containing an unescaped colon");if(-1!==e.indexOf(f.auth)&&-1!==f.auth.indexOf("@"))throw new Error("Username containing an unescaped at-sign")}let p=e.split("?").shift().split(","),d=[];for(let e=0;e<p.length;e++){let t=p[e];-1!==t.indexOf("mongodb")?-1!==t.indexOf("@")?d.push(t.split("@").pop()):d.push(t.substr("mongodb://".length)):-1!==t.indexOf("/")?d.push(t.split("/").shift()):-1===t.indexOf("/")&&d.push(t.trim())}for(let e=0;e<d.length;e++){let t=o.parse(i("mongodb://%s",d[e].trim()));if((!t.path||-1===t.path.indexOf(".sock"))&&(t.path&&-1!==t.path.indexOf(":")))throw t.path.split("/").length>1&&-1===t.path.indexOf("::")?new Error("Slash in host identifier"):new Error("Double colon in host identifier")}-1!==e.indexOf("?")?(u=e.substr(e.indexOf("?")+1),n=e.substring("mongodb://".length,e.indexOf("?"))):n=e.substring("mongodb://".length);-1!==n.indexOf("@")&&(a=n.split("@")[0],n=n.split("@")[1]);if(n.split("/").length>2)throw new Error("Unsupported host '"+n.split("?")[0]+"', hosts must be URL encoded and contain at most one unencoded slash");if(-1!==n.indexOf(".sock")){if(-1!==n.indexOf(".sock/")){if(l=n.split(".sock/")[1],-1!==l.indexOf("/")){if(2===l.split("/").length&&0===l.split("/")[1].length)throw new Error("Illegal trailing backslash after database name");throw new Error("More than 1 database name in URL")}n=n.split("/",n.indexOf(".sock")+".sock".length)}}else if(-1!==n.indexOf("/")){if(n.split("/").length>2){if(0===n.split("/")[2].length)throw new Error("Illegal trailing backslash after database name");throw new Error("More than 1 database name in URL")}l=n.split("/")[1],n=n.split("/")[0]}n=decodeURIComponent(n);let h,m,g,y,b={},v=a||"",S=v.split(":",2),w=decodeURIComponent(S[0]);if(S[0]!==encodeURIComponent(w))throw new Error("Username contains an illegal unescaped character");if(S[0]=w,S[1]){let e=decodeURIComponent(S[1]);if(S[1]!==encodeURIComponent(e))throw new Error("Password contains an illegal unescaped character");S[1]=e}2===S.length&&(b.auth={user:S[0],password:S[1]});t&&null!=t.auth&&(b.auth=t.auth);let _={socketOptions:{}},O={read_preference_tags:[]},T={socketOptions:{}},C={socketOptions:{}};if(b.server_options=_,b.db_options=O,b.rs_options=T,b.mongos_options=C,e.match(/\.sock/)){let t=e.substring(e.indexOf("mongodb://")+"mongodb://".length,e.lastIndexOf(".sock")+".sock".length);-1!==t.indexOf("@")&&(t=t.split("@")[1]),t=decodeURIComponent(t),g=[{domain_socket:t}]}else{h=n;let e={};g=h.split(",").map((function(t){let n,r,o;if(o=/\[([^\]]+)\](?::(.+))?/.exec(t))n=o[1],r=parseInt(o[2],10)||27017;else{let e=t.split(":",2);n=e[0]||"localhost",r=null!=e[1]?parseInt(e[1],10):27017,-1!==n.indexOf("?")&&(n=n.split(/\?/)[0])}return e[n+"_"+r]?null:(e[n+"_"+r]=1,{host:n,port:r})})).filter((function(e){return null!=e}))}b.dbName=l||"admin",m=(u||"").split(/[&;]/),m.forEach((function(e){if(e){var t=e.split("="),n=t[0],o=t[1];switch(n){case"slaveOk":case"slave_ok":_.slave_ok="true"===o,O.slaveOk="true"===o;break;case"maxPoolSize":case"poolSize":_.poolSize=parseInt(o,10),T.poolSize=parseInt(o,10);break;case"appname":b.appname=decodeURIComponent(o);break;case"autoReconnect":case"auto_reconnect":_.auto_reconnect="true"===o;break;case"ssl":if("prefer"===o){_.ssl=o,T.ssl=o,C.ssl=o;break}_.ssl="true"===o,T.ssl="true"===o,C.ssl="true"===o;break;case"sslValidate":_.sslValidate="true"===o,T.sslValidate="true"===o,C.sslValidate="true"===o;break;case"replicaSet":case"rs_name":T.rs_name=o;break;case"reconnectWait":T.reconnectWait=parseInt(o,10);break;case"retries":T.retries=parseInt(o,10);break;case"readSecondary":case"read_secondary":T.read_secondary="true"===o;break;case"fsync":O.fsync="true"===o;break;case"journal":O.j="true"===o;break;case"safe":O.safe="true"===o;break;case"nativeParser":case"native_parser":O.native_parser="true"===o;break;case"readConcernLevel":O.readConcern=new c(o);break;case"connectTimeoutMS":_.socketOptions.connectTimeoutMS=parseInt(o,10),T.socketOptions.connectTimeoutMS=parseInt(o,10),C.socketOptions.connectTimeoutMS=parseInt(o,10);break;case"socketTimeoutMS":_.socketOptions.socketTimeoutMS=parseInt(o,10),T.socketOptions.socketTimeoutMS=parseInt(o,10),C.socketOptions.socketTimeoutMS=parseInt(o,10);break;case"w":O.w=parseInt(o,10),isNaN(O.w)&&(O.w=o);break;case"authSource":O.authSource=o;break;case"gssapiServiceName":O.gssapiServiceName=o;break;case"authMechanism":if("GSSAPI"===o)if(null==b.auth){let e=decodeURIComponent(v);if(-1===e.indexOf("@"))throw new Error("GSSAPI requires a provided principal");b.auth={user:e,password:null}}else b.auth.user=decodeURIComponent(b.auth.user);else"MONGODB-X509"===o&&(b.auth={user:decodeURIComponent(v)});if("GSSAPI"!==o&&"MONGODB-X509"!==o&&"MONGODB-CR"!==o&&"DEFAULT"!==o&&"SCRAM-SHA-1"!==o&&"SCRAM-SHA-256"!==o&&"PLAIN"!==o)throw new Error("Only DEFAULT, GSSAPI, PLAIN, MONGODB-X509, or SCRAM-SHA-1 is supported by authMechanism");O.authMechanism=o;break;case"authMechanismProperties":{let e=o.split(","),t={};e.forEach((function(e){let n=e.split(":");t[n[0]]=n[1]})),O.authMechanismProperties=t,"string"==typeof t.SERVICE_NAME&&(O.gssapiServiceName=t.SERVICE_NAME),"string"==typeof t.SERVICE_REALM&&(O.gssapiServiceRealm=t.SERVICE_REALM),"string"==typeof t.CANONICALIZE_HOST_NAME&&(O.gssapiCanonicalizeHostName="true"===t.CANONICALIZE_HOST_NAME)}break;case"wtimeoutMS":O.wtimeout=parseInt(o,10);break;case"readPreference":if(!r.isValid(o))throw new Error("readPreference must be either primary/primaryPreferred/secondary/secondaryPreferred/nearest");O.readPreference=o;break;case"maxStalenessSeconds":O.maxStalenessSeconds=parseInt(o,10);break;case"readPreferenceTags":{let e={};if(null==(o=decodeURIComponent(o))||""===o){O.read_preference_tags.push(e);break}let t=o.split(/,/);for(let n=0;n<t.length;n++){let r=t[n].trim().split(/:/);e[r[0]]=r[1]}O.read_preference_tags.push(e)}break;case"compressors":{y=_.compression||{};let e=o.split(",");if(!e.every((function(e){return"snappy"===e||"zlib"===e})))throw new Error("Compressors must be at least one of snappy or zlib");y.compressors=e,_.compression=y}break;case"zlibCompressionLevel":{y=_.compression||{};let e=parseInt(o,10);if(e<-1||e>9)throw new Error("zlibCompressionLevel must be an integer between -1 and 9");y.zlibCompressionLevel=e,_.compression=y}break;case"retryWrites":O.retryWrites="true"===o;break;case"minSize":O.minSize=parseInt(o,10);break;default:s("URL Parser").warn(`${n} is not supported as a connection string option`)}}})),0===O.read_preference_tags.length&&(O.read_preference_tags=null);if(!(-1!==O.w&&0!==O.w||!0!==O.journal&&!0!==O.fsync&&!0!==O.safe))throw new Error("w set to -1 or 0 cannot be combined with safe/w/journal/fsync");O.readPreference||(O.readPreference="primary");return O=Object.assign(O,t),b.servers=g,b}(e,t)}catch(e){u=e}return u?n(u,null):n(null,a)}e.exports=function(e,t,n){let r;"function"==typeof t&&(n=t,t={}),t=t||{};try{r=o.parse(e,!0)}catch(e){return n(new Error("URL malformed, cannot be parsed"))}if("mongodb:"!==r.protocol&&"mongodb+srv:"!==r.protocol)return n(new Error("Invalid schema, expected `mongodb` or `mongodb+srv`"));if("mongodb:"===r.protocol)return p(e,t,n);if(r.hostname.split(".").length<3)return n(new Error("URI does not have hostname, domain name and tld"));if(r.domainLength=r.hostname.split(".").length,r.pathname&&r.pathname.match(","))return n(new Error("Invalid URI, cannot contain multiple hostnames"));if(r.port)return n(new Error("Ports not accepted with `mongodb+srv` URIs"));let i=`_mongodb._tcp.${r.host}`;a.resolveSrv(i,(function(e,o){if(e)return n(e);if(0===o.length)return n(new Error("No addresses found at host"));for(let e=0;e<o.length;e++)if(!f(o[e].name,r.hostname,r.domainLength))return n(new Error("Server record does not share hostname with parent URI"));let i=r.auth?`mongodb://${r.auth}@`:"mongodb://",s=o.map((function(e,t){return 0===t?`${i}${e.name}:${e.port}`:`${e.name}:${e.port}`})).join(",")+"/",c=[];if(r.path){let e=r.path.slice(1);-1!==e.indexOf("?")&&(e=e.slice(0,e.indexOf("?"))),s+=e}(t.ssl||r.search)&&(t.ssl||!r.search||r.search.match("ssl"))||c.push("ssl=true"),r.search&&c.push(r.search.replace("?","")),a.resolveTxt(r.host,(function(e,r){if(e&&"ENODATA"!==e.code&&"ENOTFOUND"!==e.code)return n(e);if(e&&"ENODATA"===e.code&&(r=null),r){if(r.length>1)return n(new l("Multiple text records not allowed"));r=r[0].join("");const e=u.parse(r),t=Object.keys(e);if(t.some(e=>"authSource"!==e&&"replicaSet"!==e))return n(new l("Text record must only set `authSource` or `replicaSet`"));t.length>0&&c.push(r)}c.length&&(s+=`?${c.join("&")}`),p(s,t,n)}))}))}},function(e,t,n){"use strict";e.exports=function(e){const t=n(192),r=e.mongodb.MongoTimeoutError,o=n(99),i=o.debug,s=o.databaseNamespace,a=o.collectionNamespace,c=o.MongoCryptError,u=n(202),l=new Map([[0,"MONGOCRYPT_CTX_ERROR"],[1,"MONGOCRYPT_CTX_NEED_MONGO_COLLINFO"],[2,"MONGOCRYPT_CTX_NEED_MONGO_MARKINGS"],[3,"MONGOCRYPT_CTX_NEED_MONGO_KEYS"],[4,"MONGOCRYPT_CTX_NEED_KMS"],[5,"MONGOCRYPT_CTX_READY"],[6,"MONGOCRYPT_CTX_DONE"]]);return{StateMachine:class{constructor(e){this.options=e||{},this.bson=e.bson}execute(e,t,n){const o=this.bson,s=e._keyVaultNamespace,a=e._keyVaultClient,u=e._metaDataClient,f=e._mongocryptdClient,p=e._mongocryptdManager;switch(i(`[context#${t.id}] ${l.get(t.state)||t.state}`),t.state){case 1:{const r=o.deserialize(t.nextMongoOperation());return void this.fetchCollectionInfo(u,t.ns,r,(r,o)=>{if(r)return n(r,null);o&&t.addMongoOperationResponse(o),t.finishMongoOperation(),this.execute(e,t,n)})}case 2:{const o=t.nextMongoOperation();return void this.markCommand(f,t.ns,o,(i,s)=>{if(i)return i instanceof r&&p&&!p.bypassSpawn?void p.spawn(()=>{this.markCommand(f,t.ns,o,(r,o)=>{if(r)return n(r,null);t.addMongoOperationResponse(o),t.finishMongoOperation(),this.execute(e,t,n)})}):n(i,null);t.addMongoOperationResponse(s),t.finishMongoOperation(),this.execute(e,t,n)})}case 3:{const r=t.nextMongoOperation();return void this.fetchKeys(a,s,r,(r,i)=>{if(r)return n(r,null);i.forEach(e=>{t.addMongoOperationResponse(o.serialize(e))}),t.finishMongoOperation(),this.execute(e,t,n)})}case 4:{const r=[];let o;for(;o=t.nextKMSRequest();)r.push(this.kmsRequest(o));return void Promise.all(r).then(()=>{t.finishKMSRequests(),this.execute(e,t,n)}).catch(e=>{n(e,null)})}case 5:{const e=t.finalize();if(0===t.state){const e=t.status.message||"Finalization error";return void n(new c(e))}return void n(null,o.deserialize(e,this.options))}case 0:{const e=t.status.message;return void n(new c(e))}case 6:return;default:return void n(new c(`Unknown state: ${t.state}`))}}kmsRequest(e){const n=e.endpoint.split(":"),r=null!=n[1]?Number.parseInt(n[1],10):443,o={host:n[0],servername:n[0],port:r},i=e.message;return new Promise((n,r)=>{const s=new u,a=t.connect(o,()=>{a.write(i)});a.once("timeout",()=>{a.removeAllListeners(),a.destroy(),r(new c("KMS request timed out"))}),a.once("error",e=>{a.removeAllListeners(),a.destroy();const t=new c("KMS request failed");t.originalError=e,r(t)}),a.on("data",t=>{for(s.append(t);e.bytesNeeded>0&&s.length;){const t=Math.min(e.bytesNeeded,s.length);e.addResponse(s.slice(0,t)),s.consume(t)}e.bytesNeeded<=0&&a.end(n)})})}fetchCollectionInfo(e,t,n,r){const o=this.bson,i=s(t);e.db(i).listCollections(n).toArray((e,t)=>{if(e)return void r(e,null);const n=t.length>0?o.serialize(t[0]):null;r(null,n)})}markCommand(e,t,n,r){const o=this.bson,i=s(t),a=o.deserialize(n,{promoteLongs:!1,promoteValues:!1});e.db(i).command(a,(e,t)=>{r(e,e?null:o.serialize(t,this.options))})}fetchKeys(e,t,n,r){const o=this.bson,i=s(t),c=a(t);n=o.deserialize(n),e.db(i).collection(c,{readConcern:{level:"majority"}}).find(n).toArray((e,t)=>{e?r(e,null):r(null,t)})}}}}},function(e,t,n){"use strict";e.exports=function(e){const t=n(225)("mongocrypt"),r=n(99).databaseNamespace,o=e.stateMachine.StateMachine,i=n(488).MongocryptdManager,s=e.mongodb.MongoClient,a=e.mongodb.MongoError,c=n(226);return{AutoEncrypter:class{constructor(e,n){this._client=e,this._bson=n.bson||e.topology.bson,this._mongocryptdManager=new i(n.extraOptions),this._mongocryptdClient=new s(this._mongocryptdManager.uri,{useNewUrlParser:!0,useUnifiedTopology:!0,serverSelectionTimeoutMS:1e3}),this._keyVaultNamespace=n.keyVaultNamespace||"admin.datakeys",this._keyVaultClient=n.keyVaultClient||e,this._metaDataClient=n.metadataClient||e,this._bypassEncryption="boolean"==typeof n.bypassAutoEncryption&&n.bypassAutoEncryption;const r={};n.schemaMap&&(r.schemaMap=Buffer.isBuffer(n.schemaMap)?n.schemaMap:this._bson.serialize(n.schemaMap)),n.kmsProviders&&(r.kmsProviders=Buffer.isBuffer(n.kmsProviders)?n.kmsProviders:this._bson.serialize(n.kmsProviders)),n.logger&&(r.logger=n.logger),Object.assign(r,{cryptoCallbacks:c}),this._mongocrypt=new t.MongoCrypt(r),this._contextCounter=0}init(e){const t=(t,n)=>{t&&t.message&&(t.message.match(/timed out after/)||t.message.match(/ENOTFOUND/))?e(new a("Unable to connect to `mongocryptd`, please make sure it is running or in your PATH for auto-spawn")):e(t,n)};if(this._mongocryptdManager.bypassSpawn)return this._mongocryptdClient.connect(t);this._mongocryptdManager.spawn(()=>this._mongocryptdClient.connect(t))}teardown(e,t){this._mongocryptdClient.close(e,t)}encrypt(e,t,n,i){if("string"!=typeof e)throw new TypeError("Parameter `ns` must be a string");if("object"!=typeof t)throw new TypeError("Parameter `cmd` must be an object");if("function"==typeof n&&null==i&&(i=n,n={}),this._bypassEncryption)return void i(void 0,t);const s=this._bson,a=Buffer.isBuffer(t)?t:s.serialize(t,n);let c;try{c=this._mongocrypt.makeEncryptionContext(r(e),a)}catch(e){return void i(e,null)}c.id=this._contextCounter++,c.ns=e,c.document=t,new o(Object.assign({bson:s},n)).execute(this,c,i)}decrypt(e,t,n){"function"==typeof t&&null==n&&(n=t,t={});const r=this._bson,i=Buffer.isBuffer(e)?e:r.serialize(e,t);let s;try{s=this._mongocrypt.makeDecryptionContext(i)}catch(e){return void n(e,null)}s.id=this._contextCounter++,new o(Object.assign({bson:r},t)).execute(this,s,n)}}}}},function(e,t,n){var r=n(136).sep||"/";e.exports=function(e){if("string"!=typeof e||e.length<=7||"file://"!=e.substring(0,7))throw new TypeError("must pass in a file:// URI to convert to a file path");var t=decodeURI(e.substring(7)),n=t.indexOf("/"),o=t.substring(0,n),i=t.substring(n+1);"localhost"==o&&(o="");o&&(o=r+r+o);i=i.replace(/^(.+)\|/,"$1:"),"\\"==r&&(i=i.replace(/\//g,"\\"));/^.+\:/.test(i)||(i=r+i);return o+i}},function(e,t,n){"use strict";const r=n(489).spawn;e.exports={MongocryptdManager:class{constructor(e){(e=e||{}).mongocryptdURI?this.uri=e.mongocryptdURI:this.uri="mongodb://localhost:27020/?serverSelectionTimeoutMS=1000",this.bypassSpawn=!!e.mongocryptdBypassSpawn,this.spawnPath=e.mongocryptdSpawnPath||"",this.spawnArgs=[],Array.isArray(e.mongocryptdSpawnArgs)&&(this.spawnArgs=this.spawnArgs.concat(e.mongocryptdSpawnArgs)),this.spawnArgs.filter(e=>"string"==typeof e).every(e=>e.indexOf("--idleShutdownTimeoutSecs")<0)&&this.spawnArgs.push("--idleShutdownTimeoutSecs",60)}spawn(e){const t=this.spawnPath||"mongocryptd";this._child=r(t,this.spawnArgs,{stdio:"ignore",detached:!0}),this._child.on("error",()=>{}),this._child.unref(),process.nextTick(e)}}}},function(e,t){e.exports=require("child_process")},function(e,t,n){"use strict";e.exports=function(e){const t=n(225)("mongocrypt"),r=n(99),o=r.databaseNamespace,i=r.collectionNamespace,s=r.promiseOrCallback,a=e.stateMachine.StateMachine,c=n(226);return{ClientEncryption:class{constructor(e,n){if(this._client=e,this._bson=n.bson||e.topology.bson,null==n.keyVaultNamespace)throw new TypeError("Missing required option `keyVaultNamespace`");Object.assign(n,{cryptoCallbacks:c}),n.kmsProviders&&!Buffer.isBuffer(n.kmsProviders)&&(n.kmsProviders=this._bson.serialize(n.kmsProviders)),this._keyVaultNamespace=n.keyVaultNamespace,this._keyVaultClient=n.keyVaultClient||e,this._mongoCrypt=new t.MongoCrypt(n)}createDataKey(e,t,n){"function"==typeof t&&(n=t,t={});const r=this._bson;t=function(e,t){if((t=Object.assign({},t)).keyAltNames){if(!Array.isArray(t.keyAltNames))throw new TypeError(`Option "keyAltNames" must be an array of string, but was of type ${typeof t.keyAltNames}.`);const n=[];for(let r=0;r<t.keyAltNames.length;r+=1){const o=t.keyAltNames[r],i=typeof o;if("string"!==i)throw new TypeError(`Option "keyAltNames" must be an array of string, but item at index ${r} was of type ${i} `);n.push(e.serialize({keyAltName:o}))}t.keyAltNames=n}else null==t.keyAltNames&&delete t.keyAltNames;return t}(r,t);const c=r.serialize(Object.assign({provider:e},t.masterKey)),u=this._mongoCrypt.makeDataKeyContext(c),l=new a({bson:r});return s(n,e=>{l.execute(this,u,(t,n)=>{if(t)return void e(t,null);const r=o(this._keyVaultNamespace),s=i(this._keyVaultNamespace);this._keyVaultClient.db(r).collection(s).insertOne(n,{w:"majority"},(t,n)=>{t?e(t,null):e(null,n.insertedId)})})})}encrypt(e,t,n){const r=this._bson,o=r.serialize({v:e}),i=Object.assign({},t);if(t.keyId&&(i.keyId=t.keyId.buffer),t.keyAltName){const e=t.keyAltName;if(t.keyId)throw new TypeError('"options" cannot contain both "keyId" and "keyAltName"');const n=typeof e;if("string"!==n)throw new TypeError(`"options.keyAltName" must be of type string, but was of type ${n}`);i.keyAltName=r.serialize({keyAltName:e})}const c=new a({bson:r}),u=this._mongoCrypt.makeExplicitEncryptionContext(o,i);return s(n,e=>{c.execute(this,u,(t,n)=>{t?e(t,null):e(null,n.v)})})}decrypt(e,t){const n=this._bson,r=n.serialize({v:e}),o=this._mongoCrypt.makeExplicitDecryptionContext(r),i=new a({bson:n});return s(t,e=>{i.execute(this,o,(t,n)=>{t?e(t,null):e(null,n.v)})})}}}}},function(e,t,n){"use strict";const r=n(227),o=n(2).BSON.ObjectID,i=n(2).ReadPreference,s=n(22).Buffer,a=n(88),c=n(5).format,u=n(5),l=n(2).MongoError,f=u.inherits,p=n(18).Duplex,d=n(0).shallowClone,h=n(0).executeLegacyOperation,m=n(5).deprecate;const g=m(()=>{},"GridStore is deprecated, and will be removed in a future version. Please use GridFSBucket instead");var y=function e(t,n,s,a,c){if(g(),!(this instanceof e))return new e(t,n,s,a,c);this.db=t,void 0===c&&(c={}),void 0===a?(a=s,s=void 0):"object"==typeof a&&(c=a,a=s,s=void 0),n&&"ObjectID"===n._bsontype?(this.referenceBy=1,this.fileId=n,this.filename=s):void 0===s?(this.referenceBy=0,this.filename=n,null!=a.indexOf("w")&&(this.fileId=new o)):(this.referenceBy=1,this.fileId=n,this.filename=s),this.mode=null==a?"r":a,this.options=c||{},this.isOpen=!1,this.root=null==this.options.root?e.DEFAULT_ROOT_COLLECTION:this.options.root,this.position=0,this.readPreference=this.options.readPreference||t.options.readPreference||i.primary,this.writeConcern=U(t,this.options),this.internalChunkSize=null==this.options.chunkSize?r.DEFAULT_CHUNK_SIZE:this.options.chunkSize;var u=this.options.promiseLibrary||Promise;this.promiseLibrary=u,Object.defineProperty(this,"chunkSize",{enumerable:!0,get:function(){return this.internalChunkSize},set:function(e){"w"!==this.mode[0]||0!==this.position||null!=this.uploadDate?this.internalChunkSize=this.internalChunkSize:this.internalChunkSize=e}}),Object.defineProperty(this,"md5",{enumerable:!0,get:function(){return this.internalMd5}}),Object.defineProperty(this,"chunkNumber",{enumerable:!0,get:function(){return this.currentChunk&&this.currentChunk.chunkNumber?this.currentChunk.chunkNumber:null}})};y.prototype.open=function(e,t){if("function"==typeof e&&(t=e,e={}),e=e||{},"w"!==this.mode&&"w+"!==this.mode&&"r"!==this.mode)throw l.create({message:"Illegal mode "+this.mode,driver:!0});return h(this.db.s.topology,b,[this,e,t],{skipSessions:!0})};var b=function(e,t,n){var r=U(e.db,e.options);"w"===e.mode||"w+"===e.mode?e.collection().ensureIndex([["filename",1]],r,(function(){var t=e.chunkCollection(),o=d(r);o.unique=!0,t.ensureIndex([["files_id",1],["n",1]],o,(function(){E(e,r,(function(t,r){if(t)return n(t);e.isOpen=!0,n(t,r)}))}))})):E(e,r,(function(t,r){if(t)return n(t);e.isOpen=!0,n(t,r)}))};y.prototype.eof=function(){return this.position===this.length},y.prototype.getc=function(e,t){return"function"==typeof e&&(t=e,e={}),e=e||{},h(this.db.s.topology,v,[this,e,t],{skipSessions:!0})};var v=function(e,t,n){e.eof()?n(null,null):e.currentChunk.eof()?A(e,e.currentChunk.chunkNumber+1,(function(t,r){e.currentChunk=r,e.position=e.position+1,n(t,e.currentChunk.getc())})):(e.position=e.position+1,n(null,e.currentChunk.getc()))};y.prototype.puts=function(e,t,n){"function"==typeof t&&(n=t,t={}),t=t||{};var r=null==e.match(/\n$/)?e+"\n":e;return h(this.db.s.topology,this.write.bind(this),[r,t,n],{skipSessions:!0})},y.prototype.stream=function(){return new z(this)},y.prototype.write=function(e,t,n,r){return"function"==typeof n&&(r=n,n={}),n=n||{},h(this.db.s.topology,L,[this,e,t,n,r],{skipSessions:!0})},y.prototype.destroy=function(){this.writable&&(this.readable=!1,this.writable&&(this.writable=!1,this._q.length=0,this.emit("close")))},y.prototype.writeFile=function(e,t,n){return"function"==typeof t&&(n=t,t={}),t=t||{},h(this.db.s.topology,S,[this,e,t,n],{skipSessions:!0})};var S=function(e,t,n,o){"string"!=typeof t?e.open((function(e,n){if(e)return o(e,n);a.fstat(t,(function(e,i){if(e)return o(e,n);var c=0,u=0,l=function(){var e=s.alloc(n.chunkSize);a.read(t,e,0,e.length,c,(function(e,s,f){if(e)return o(e,n);c+=s,new r(n,{n:u++},n.writeConcern).write(f.slice(0,s),(function(e,r){if(e)return o(e,n);r.save({},(function(e){return e?o(e,n):(n.position=n.position+s,n.currentChunk=r,c>=i.size?void a.close(t,(function(e){if(e)return o(e);n.close((function(e){return o(e||null,n)}))})):process.nextTick(l))}))}))}))};process.nextTick(l)}))})):a.open(t,"r",(function(t,n){if(t)return o(t);e.writeFile(n,o)}))};y.prototype.close=function(e,t){return"function"==typeof e&&(t=e,e={}),e=e||{},h(this.db.s.topology,w,[this,e,t],{skipSessions:!0})};var w=function(e,t,n){"w"===e.mode[0]?(t=Object.assign({},e.writeConcern,t),null!=e.currentChunk&&e.currentChunk.position>0?e.currentChunk.save({},(function(r){if(r&&"function"==typeof n)return n(r);e.collection((function(r,o){if(r&&"function"==typeof n)return n(r);null!=e.uploadDate?I(e,(function(e,r){if(e){if("function"==typeof n)return n(e);throw e}o.save(r,t,(function(e){"function"==typeof n&&n(e,r)}))})):(e.uploadDate=new Date,I(e,(function(e,r){if(e){if("function"==typeof n)return n(e);throw e}o.save(r,t,(function(e){"function"==typeof n&&n(e,r)}))})))}))})):e.collection((function(r,o){if(r&&"function"==typeof n)return n(r);e.uploadDate=new Date,I(e,(function(e,r){if(e){if("function"==typeof n)return n(e);throw e}o.save(r,t,(function(e){"function"==typeof n&&n(e,r)}))}))}))):"r"===e.mode[0]?"function"==typeof n&&n(null,null):"function"==typeof n&&n(l.create({message:c("Illegal mode %s",e.mode),driver:!0}))};y.prototype.chunkCollection=function(e){return"function"==typeof e?this.db.collection(this.root+".chunks",e):this.db.collection(this.root+".chunks")},y.prototype.unlink=function(e,t){return"function"==typeof e&&(t=e,e={}),e=e||{},h(this.db.s.topology,_,[this,e,t],{skipSessions:!0})};var _=function(e,t,n){M(e,(function(t){if(null!==t)return t.message="at deleteChunks: "+t.message,n(t);e.collection((function(t,r){if(null!==t)return t.message="at collection: "+t.message,n(t);r.remove({_id:e.fileId},e.writeConcern,(function(t){n(t,e)}))}))}))};y.prototype.collection=function(e){return"function"==typeof e&&this.db.collection(this.root+".files",e),this.db.collection(this.root+".files")},y.prototype.readlines=function(e,t,n){var r=Array.prototype.slice.call(arguments,0);return n="function"==typeof r[r.length-1]?r.pop():void 0,e=(e=r.length?r.shift():"\n")||"\n",t=r.length?r.shift():{},h(this.db.s.topology,O,[this,e,t,n],{skipSessions:!0})};var O=function(e,t,n,r){e.read((function(e,n){if(e)return r(e);var o=n.toString().split(t);o=o.length>0?o.splice(0,o.length-1):[];for(var i=0;i<o.length;i++)o[i]=o[i]+t;r(null,o)}))};y.prototype.rewind=function(e,t){return"function"==typeof e&&(t=e,e={}),e=e||{},h(this.db.s.topology,T,[this,e,t],{skipSessions:!0})};var T=function(e,t,n){0!==e.currentChunk.chunkNumber?"w"===e.mode[0]?M(e,(function(t){if(t)return n(t);e.currentChunk=new r(e,{n:0},e.writeConcern),e.position=0,n(null,e)})):e.currentChunk(0,(function(t,r){if(t)return n(t);e.currentChunk=r,e.currentChunk.rewind(),e.position=0,n(null,e)})):(e.currentChunk.rewind(),e.position=0,n(null,e))};y.prototype.read=function(e,t,n,r){var o=Array.prototype.slice.call(arguments,0);return r="function"==typeof o[o.length-1]?o.pop():void 0,e=o.length?o.shift():null,t=o.length?o.shift():null,n=o.length?o.shift():{},h(this.db.s.topology,C,[this,e,t,n,r],{skipSessions:!0})};var C=function(e,t,n,r,o){var i=null==t?e.length-e.position:t,a=null==n?s.alloc(i):n;if(a._index=null!=n&&null!=n._index?n._index:0,e.currentChunk.length()-e.currentChunk.position+a._index>=i){var c=e.currentChunk.readSlice(i-a._index);return c.copy(a,a._index),e.position=e.position+a.length,0===i&&0===a.length?o(l.create({message:"File does not exist",driver:!0}),null):o(null,a)}(c=e.currentChunk.readSlice(e.currentChunk.length()-e.currentChunk.position)).copy(a,a._index),a._index+=c.length,A(e,e.currentChunk.chunkNumber+1,(function(n,r){if(n)return o(n);r.length()>0?(e.currentChunk=r,e.read(t,a,o)):a._index>0?o(null,a):o(l.create({message:"no chunks found for file, possibly corrupt",driver:!0}),null)}))};y.prototype.tell=function(e){var t=this;return"function"==typeof e?e(null,this.position):new t.promiseLibrary((function(e){e(t.position)}))},y.prototype.seek=function(e,t,n,r){var o=Array.prototype.slice.call(arguments,1);return r="function"==typeof o[o.length-1]?o.pop():void 0,t=o.length?o.shift():null,n=o.length?o.shift():{},h(this.db.s.topology,x,[this,e,t,n,r],{skipSessions:!0})};var x=function(e,t,n,r,o){if("r"!==e.mode)return o(l.create({message:"seek is only supported for mode r",driver:!0}));var i=null==n?y.IO_SEEK_SET:n,s=t,a=0;a=i===y.IO_SEEK_CUR?e.position+s:i===y.IO_SEEK_END?e.length+s:s;var c=Math.floor(a/e.chunkSize);A(e,c,(function(t,n){return t?o(t,null):null==n?o(new Error("no chunk found")):(e.currentChunk=n,e.position=a,e.currentChunk.position=e.position%e.chunkSize,void o(t,e))}))},E=function(e,t,n){var i=e.collection(),s=1===e.referenceBy?{_id:e.fileId}:{filename:e.filename};function a(e){a.err||n(a.err=e)}s=null==e.fileId&&null==e.filename?null:s,t.readPreference=e.readPreference,null!=s?i.findOne(s,t,(function(i,s){if(i)return a(i);if(null!=s)e.fileId=s._id,e.filename="r"===e.mode||void 0===e.filename?s.filename:e.filename,e.contentType=s.contentType,e.internalChunkSize=s.chunkSize,e.uploadDate=s.uploadDate,e.aliases=s.aliases,e.length=s.length,e.metadata=s.metadata,e.internalMd5=s.md5;else{if("r"===e.mode){e.length=0;var u="ObjectID"===e.fileId._bsontype?e.fileId.toHexString():e.fileId;return a(l.create({message:c("file with id %s not opened for writing",1===e.referenceBy?u:e.filename),driver:!0}))}e.fileId=null==e.fileId?new o:e.fileId,e.contentType=y.DEFAULT_CONTENT_TYPE,e.internalChunkSize=null==e.internalChunkSize?r.DEFAULT_CHUNK_SIZE:e.internalChunkSize,e.length=0}"r"===e.mode?A(e,0,t,(function(t,r){if(t)return a(t);e.currentChunk=r,e.position=0,n(null,e)})):"w"===e.mode&&s?M(e,t,(function(t){if(t)return a(t);e.currentChunk=new r(e,{n:0},e.writeConcern),e.contentType=null==e.options.content_type?e.contentType:e.options.content_type,e.internalChunkSize=null==e.options.chunk_size?e.internalChunkSize:e.options.chunk_size,e.metadata=null==e.options.metadata?e.metadata:e.options.metadata,e.aliases=null==e.options.aliases?e.aliases:e.options.aliases,e.position=0,n(null,e)})):"w"===e.mode?(e.currentChunk=new r(e,{n:0},e.writeConcern),e.contentType=null==e.options.content_type?e.contentType:e.options.content_type,e.internalChunkSize=null==e.options.chunk_size?e.internalChunkSize:e.options.chunk_size,e.metadata=null==e.options.metadata?e.metadata:e.options.metadata,e.aliases=null==e.options.aliases?e.aliases:e.options.aliases,e.position=0,n(null,e)):"w+"===e.mode&&A(e,k(e),t,(function(t,o){if(t)return a(t);e.currentChunk=null==o?new r(e,{n:0},e.writeConcern):o,e.currentChunk.position=e.currentChunk.data.length(),e.metadata=null==e.options.metadata?e.metadata:e.options.metadata,e.aliases=null==e.options.aliases?e.aliases:e.options.aliases,e.position=e.length,n(null,e)}))})):(e.fileId=null==e.fileId?new o:e.fileId,e.contentType=y.DEFAULT_CONTENT_TYPE,e.internalChunkSize=null==e.internalChunkSize?r.DEFAULT_CHUNK_SIZE:e.internalChunkSize,e.length=0,"w"===e.mode?M(e,t,(function(t){if(t)return a(t);e.currentChunk=new r(e,{n:0},e.writeConcern),e.contentType=null==e.options.content_type?e.contentType:e.options.content_type,e.internalChunkSize=null==e.options.chunk_size?e.internalChunkSize:e.options.chunk_size,e.metadata=null==e.options.metadata?e.metadata:e.options.metadata,e.aliases=null==e.options.aliases?e.aliases:e.options.aliases,e.position=0,n(null,e)})):"w+"===e.mode&&A(e,k(e),t,(function(t,o){if(t)return a(t);e.currentChunk=null==o?new r(e,{n:0},e.writeConcern):o,e.currentChunk.position=e.currentChunk.data.length(),e.metadata=null==e.options.metadata?e.metadata:e.options.metadata,e.aliases=null==e.options.aliases?e.aliases:e.options.aliases,e.position=e.length,n(null,e)})))},N=function(e,t,n,o){"function"==typeof n&&(o=n,n=null);var i="boolean"==typeof n&&n;if("w"!==e.mode)o(l.create({message:c("file with id %s not opened for writing",1===e.referenceBy?e.referenceBy:e.filename),driver:!0}),null);else{if(!(e.currentChunk.position+t.length>=e.chunkSize))return e.position=e.position+t.length,e.currentChunk.write(t),i?e.close((function(t){o(t,e)})):o(null,e);for(var s=e.currentChunk.chunkNumber,a=e.chunkSize-e.currentChunk.position,u=t.slice(0,a),f=t.slice(a),p=[e.currentChunk.write(u)];f.length>=e.chunkSize;){var d=new r(e,{n:s+1},e.writeConcern);u=f.slice(0,e.chunkSize),f=f.slice(e.chunkSize),s+=1,d.write(u),p.push(d)}e.currentChunk=new r(e,{n:s+1},e.writeConcern),f.length>0&&e.currentChunk.write(f),e.position=e.position+t.length;for(var h=p.length,m=0;m<p.length;m++)p[m].save({},(function(t){return t?o(t):(h-=1)<=0?i?e.close((function(t){o(t,e)})):o(null,e):void 0}))}},I=function(e,t){var n={_id:e.fileId,filename:e.filename,contentType:e.contentType,length:e.position?e.position:0,chunkSize:e.chunkSize,uploadDate:e.uploadDate,aliases:e.aliases,metadata:e.metadata},r={filemd5:e.fileId,root:e.root};e.db.command(r,(function(e,r){if(e)return t(e);n.md5=r.md5,t(null,n)}))},A=function(e,t,n,o){"function"==typeof n&&(o=n,n={}),(n=n||e.writeConcern).readPreference=e.readPreference,e.chunkCollection().findOne({files_id:e.fileId,n:t},n,(function(t,n){if(t)return o(t);o(null,new r(e,null==n?{}:n,e.writeConcern))}))},k=function(e){return Math.floor((e.length?e.length-1:0)/e.chunkSize)},M=function(e,t,n){"function"==typeof t&&(n=t,t={}),t=t||e.writeConcern,null!=e.fileId?e.chunkCollection().remove({files_id:e.fileId},t,(function(e){if(e)return n(e,!1);n(null,!0)})):n(null,!0)};y.DEFAULT_ROOT_COLLECTION="fs",y.DEFAULT_CONTENT_TYPE="binary/octet-stream",y.IO_SEEK_SET=0,y.IO_SEEK_CUR=1,y.IO_SEEK_END=2,y.exist=function(e,t,n,r,o){var i=Array.prototype.slice.call(arguments,2);return o="function"==typeof i[i.length-1]?i.pop():void 0,n=i.length?i.shift():null,r=(r=i.length?i.shift():{})||{},h(e.s.topology,R,[e,t,n,r,o],{skipSessions:!0})};var R=function(e,t,n,r,o){var s=r.readPreference||i.PRIMARY,a=null!=n?n:y.DEFAULT_ROOT_COLLECTION;e.collection(a+".files",(function(e,n){if(e)return o(e);var r="string"==typeof t||"[object RegExp]"===Object.prototype.toString.call(t)?{filename:t}:{_id:t};null!=t&&"object"==typeof t&&"[object RegExp]"!==Object.prototype.toString.call(t)&&(r=t),n.findOne(r,{readPreference:s},(function(e,t){if(e)return o(e);o(null,null!=t)}))}))};y.list=function(e,t,n,r){var o=Array.prototype.slice.call(arguments,1);return r="function"==typeof o[o.length-1]?o.pop():void 0,t=o.length?o.shift():null,n=(n=o.length?o.shift():{})||{},h(e.s.topology,j,[e,t,n,r],{skipSessions:!0})};var j=function(e,t,n,r){null!=t&&"object"==typeof t&&(n=t,t=null);var o=n.readPreference||i.primary,s=null!=n.id&&n.id,a=null!=t?t:y.DEFAULT_ROOT_COLLECTION,c=[];e.collection(a+".files",(function(e,t){if(e)return r(e);t.find({},{readPreference:o},(function(e,t){if(e)return r(e);t.each((function(e,t){null!=t?c.push(s?t._id:t.filename):r(e,c)}))}))}))};y.read=function(e,t,n,r,o,i){var s=Array.prototype.slice.call(arguments,2);return i="function"==typeof s[s.length-1]?s.pop():void 0,n=s.length?s.shift():null,r=s.length?s.shift():null,o=(o=s.length?s.shift():null)||{},h(e.s.topology,D,[e,t,n,r,o,i],{skipSessions:!0})};var D=function(e,t,n,r,o,i){new y(e,t,"r",o).open((function(e,t){return e?i(e):r&&r>=t.length?i("offset larger than size of file",null):n&&n>t.length?i("length is larger than the size of the file",null):r&&n&&r+n>t.length?i("offset and length is larger than the size of the file",null):void(null!=r?t.seek(r,(function(e,t){if(e)return i(e);t.read(n,i)})):t.read(n,i))}))};y.readlines=function(e,t,n,r,o){var i=Array.prototype.slice.call(arguments,2);return o="function"==typeof i[i.length-1]?i.pop():void 0,n=i.length?i.shift():null,r=(r=i.length?i.shift():null)||{},h(e.s.topology,P,[e,t,n,r,o],{skipSessions:!0})};var P=function(e,t,n,r,o){var i=null==n?"\n":n;new y(e,t,"r",r).open((function(e,t){if(e)return o(e);t.readlines(i,o)}))};y.unlink=function(e,t,n,r){var o=Array.prototype.slice.call(arguments,2);return r="function"==typeof o[o.length-1]?o.pop():void 0,n=(n=o.length?o.shift():{})||{},h(e.s.topology,B,[this,e,t,n,r],{skipSessions:!0})};var B=function(e,t,n,r,o){var i=U(t,r);if(n.constructor===Array)for(var s=0,a=0;a<n.length;a++)++s,y.unlink(t,n[a],r,(function(){0==--s&&o(null,e)}));else new y(t,n,"w",r).open((function(t,n){if(t)return o(t);M(n,(function(t){if(t)return o(t);n.collection((function(t,r){if(t)return o(t);r.remove({_id:n.fileId},i,(function(t){o(t,e)}))}))}))}))},L=function(e,t,n,r,o){return s.isBuffer(t)?N(e,t,n,o):N(e,s.from(t,"binary"),n,o)},q=function(e){const t=Object.assign(e,e.writeConcern);var n={};return null!=t.w&&(n.w=t.w),!0===t.journal&&(n.j=t.journal),!0===t.j&&(n.j=t.j),!0===t.fsync&&(n.fsync=t.fsync),null!=t.wtimeout&&(n.wtimeout=t.wtimeout),n},U=function(e,t){var n={w:1};if(null!=(t=t||{}).writeConcern||null!=t.w||"boolean"==typeof t.j||"boolean"==typeof t.journal||"boolean"==typeof t.fsync?n=q(t):null!=t.safe&&"object"==typeof t.safe?n=q(t.safe):"boolean"==typeof t.safe?n={w:t.safe?1:0}:null!=e.options.writeConcern||null!=e.options.w||"boolean"==typeof e.options.j||"boolean"==typeof e.options.journal||"boolean"==typeof e.options.fsync?n=q(e.options):!e.safe||null==e.safe.w&&"boolean"!=typeof e.safe.j&&"boolean"!=typeof e.safe.journal&&"boolean"!=typeof e.safe.fsync?"boolean"==typeof e.safe&&(n={w:e.safe?1:0}):n=q(e.safe),n.w<1&&(!0===n.journal||!0===n.j||!0===n.fsync))throw l.create({message:"No acknowledgement using w < 1 cannot be combined with journal:true or fsync:true",driver:!0});return n},z=function(e){p.call(this),this.gs=e,this.endCalled=!1,this.totalBytesToRead=this.gs.length-this.gs.position,this.seekPosition=this.gs.position};f(z,p),z.prototype._pipe=z.prototype.pipe,z.prototype.pipe=function(e){var t=this;return t.gs.isOpen?(t.totalBytesToRead=t.gs.length-t.gs.position,t._pipe.apply(t,[e])):t.gs.open((function(n){if(n)return t.emit("error",n);t.totalBytesToRead=t.gs.length-t.gs.position,t._pipe.apply(t,[e])})),e},z.prototype._read=function(){var e=this,t=function(){e.gs.read(n,(function(t,n){return t&&!e.endCalled?e.emit("error",t):e.endCalled||null==n?e.push(null):(n.length<=e.totalBytesToRead?(e.totalBytesToRead=e.totalBytesToRead-n.length,e.push(n)):n.length>e.totalBytesToRead&&(e.totalBytesToRead=e.totalBytesToRead-n._index,e.push(n.slice(0,n._index))),void(e.totalBytesToRead<=0&&(e.endCalled=!0)))}))},n=e.gs.length<e.gs.chunkSize?e.gs.length-e.seekPosition:e.gs.chunkSize;e.gs.isOpen?t():e.gs.open((function(n){if(e.totalBytesToRead=e.gs.length-e.gs.position,n)return e.emit("error",n);t()}))},z.prototype.destroy=function(){this.pause(),this.endCalled=!0,this.gs.close(),this.emit("end")},z.prototype.write=function(e){var t=this;return t.endCalled?t.emit("error",l.create({message:"attempting to write to stream after end called",driver:!0})):t.gs.isOpen?(t.gs.write(e,(function(){t.emit("drain")})),!0):(t.gs.open((function(){t.gs.isOpen=!0,t.gs.write(e,(function(){process.nextTick((function(){t.emit("drain")}))}))})),!1)},z.prototype.end=function(e,t,n){var r=this,o=Array.prototype.slice.call(arguments,0);n="function"==typeof o[o.length-1]?o.pop():void 0,e=o.length?o.shift():null,t=o.length?o.shift():null,r.endCalled=!0,e&&r.gs.write(e,(function(){r.gs.close((function(){"function"==typeof n&&n(),r.emit("end")}))})),r.gs.close((function(){"function"==typeof n&&n(),r.emit("end")}))},e.exports=y},function(e,t,n){"use strict";var r=n(8).EventEmitter,o=n(493),i=n(494),s=n(0).shallowClone,a=n(0).toError,c=n(5),u=n(0).executeLegacyOperation,l={bucketName:"fs",chunkSizeBytes:261120};function f(e,t){if(r.apply(this),this.setMaxListeners(0),t&&"object"==typeof t){t=s(t);for(var n=Object.keys(l),o=0;o<n.length;++o)t[n[o]]||(t[n[o]]=l[n[o]])}else t=l;this.s={db:e,options:t,_chunksCollection:e.collection(t.bucketName+".chunks"),_filesCollection:e.collection(t.bucketName+".files"),checkedIndexes:!1,calledOpenUploadStream:!1,promiseLibrary:e.s.promiseLibrary||Promise}}function p(e,t,n){e.s._filesCollection.deleteOne({_id:t},(function(r,o){if(r)return n(r);e.s._chunksCollection.deleteMany({files_id:t},(function(e){return e?n(e):o.result.n?void n():n(new Error("FileNotFound: no file with id "+t+" found"))}))}))}function d(e,t,n,r){var o={_id:t},i={$set:{filename:n}};e.s._filesCollection.updateOne(o,i,(function(e,n){return e?r(e):n.result.n?void r():r(a("File with id "+t+" not found"))}))}function h(e,t){e.s._filesCollection.drop((function(n){if(n)return t(n);e.s._chunksCollection.drop((function(e){return e?t(e):t()}))}))}e.exports=f,c.inherits(f,r),f.prototype.openUploadStream=function(e,t){return(t=t?s(t):{}).chunkSizeBytes||(t.chunkSizeBytes=this.s.options.chunkSizeBytes),new i(this,e,t)},f.prototype.openUploadStreamWithId=function(e,t,n){return(n=n?s(n):{}).chunkSizeBytes||(n.chunkSizeBytes=this.s.options.chunkSizeBytes),n.id=e,new i(this,t,n)},f.prototype.openDownloadStream=function(e,t){var n={_id:e};return t={start:t&&t.start,end:t&&t.end},new o(this.s._chunksCollection,this.s._filesCollection,this.s.options.readPreference,n,t)},f.prototype.delete=function(e,t){return u(this.s.db.s.topology,p,[this,e,t],{skipSessions:!0})},f.prototype.find=function(e,t){e=e||{},t=t||{};var n=this.s._filesCollection.find(e);return null!=t.batchSize&&n.batchSize(t.batchSize),null!=t.limit&&n.limit(t.limit),null!=t.maxTimeMS&&n.maxTimeMS(t.maxTimeMS),null!=t.noCursorTimeout&&n.addCursorFlag("noCursorTimeout",t.noCursorTimeout),null!=t.skip&&n.skip(t.skip),null!=t.sort&&n.sort(t.sort),n},f.prototype.openDownloadStreamByName=function(e,t){var n={uploadDate:-1},r=null;t&&null!=t.revision&&(t.revision>=0?(n={uploadDate:1},r=t.revision):r=-t.revision-1);var i={filename:e};return t={sort:n,skip:r,start:t&&t.start,end:t&&t.end},new o(this.s._chunksCollection,this.s._filesCollection,this.s.options.readPreference,i,t)},f.prototype.rename=function(e,t,n){return u(this.s.db.s.topology,d,[this,e,t,n],{skipSessions:!0})},f.prototype.drop=function(e){return u(this.s.db.s.topology,h,[this,e],{skipSessions:!0})},f.prototype.getLogger=function(){return this.s.db.s.logger}},function(e,t,n){"use strict";var r=n(18),o=n(5);function i(e,t,n,o,i){this.s={bytesRead:0,chunks:e,cursor:null,expected:0,files:t,filter:o,init:!1,expectedEnd:0,file:null,options:i,readPreference:n},r.Readable.call(this)}function s(e){if(e.s.init)throw new Error("You cannot change options after the stream has enteredflowing mode!")}function a(e,t){e.emit("error",t)}e.exports=i,o.inherits(i,r.Readable),i.prototype._read=function(){var e=this;this.destroyed||function(e,t){if(e.s.file)return t();e.s.init||(!function(e){var t={};e.s.readPreference&&(t.readPreference=e.s.readPreference);e.s.options&&e.s.options.sort&&(t.sort=e.s.options.sort);e.s.options&&e.s.options.skip&&(t.skip=e.s.options.skip);e.s.files.findOne(e.s.filter,t,(function(t,n){if(t)return a(e,t);if(!n){var r=e.s.filter._id?e.s.filter._id.toString():e.s.filter.filename,o=new Error("FileNotFound: file "+r+" was not found");return o.code="ENOENT",a(e,o)}if(n.length<=0)e.push(null);else if(e.destroyed)e.emit("close");else{try{e.s.bytesToSkip=function(e,t,n){if(n&&null!=n.start){if(n.start>t.length)throw new Error("Stream start ("+n.start+") must not be more than the length of the file ("+t.length+")");if(n.start<0)throw new Error("Stream start ("+n.start+") must not be negative");if(null!=n.end&&n.end<n.start)throw new Error("Stream start ("+n.start+") must not be greater than stream end ("+n.end+")");return e.s.bytesRead=Math.floor(n.start/t.chunkSize)*t.chunkSize,e.s.expected=Math.floor(n.start/t.chunkSize),n.start-e.s.bytesRead}}(e,n,e.s.options)}catch(t){return a(e,t)}var i={files_id:n._id};if(e.s.options&&null!=e.s.options.start){var s=Math.floor(e.s.options.start/n.chunkSize);s>0&&(i.n={$gte:s})}e.s.cursor=e.s.chunks.find(i).sort({n:1}),e.s.readPreference&&e.s.cursor.setReadPreference(e.s.readPreference),e.s.expectedEnd=Math.ceil(n.length/n.chunkSize),e.s.file=n;try{e.s.bytesToTrim=function(e,t,n,r){if(r&&null!=r.end){if(r.end>t.length)throw new Error("Stream end ("+r.end+") must not be more than the length of the file ("+t.length+")");if(r.start<0)throw new Error("Stream end ("+r.end+") must not be negative");var o=null!=r.start?Math.floor(r.start/t.chunkSize):0;return n.limit(Math.ceil(r.end/t.chunkSize)-o),e.s.expectedEnd=Math.ceil(r.end/t.chunkSize),Math.ceil(r.end/t.chunkSize)*t.chunkSize-r.end}}(e,n,e.s.cursor,e.s.options)}catch(t){return a(e,t)}e.emit("file",n)}}))}(e),e.s.init=!0);e.once("file",(function(){t()}))}(e,(function(){!function(e){if(e.destroyed)return;e.s.cursor.next((function(t,n){if(e.destroyed)return;if(t)return a(e,t);if(!n)return e.push(null),void process.nextTick(()=>{e.s.cursor.close((function(t){t?a(e,t):e.emit("close")}))});var r=e.s.file.length-e.s.bytesRead,o=e.s.expected++,i=Math.min(e.s.file.chunkSize,r);if(n.n>o){var s="ChunkIsMissing: Got unexpected n: "+n.n+", expected: "+o;return a(e,new Error(s))}if(n.n<o)return s="ExtraChunk: Got unexpected n: "+n.n+", expected: "+o,a(e,new Error(s));var c=Buffer.isBuffer(n.data)?n.data:n.data.buffer;if(c.length!==i)return r<=0?(s="ExtraChunk: Got unexpected n: "+n.n,a(e,new Error(s))):(s="ChunkIsWrongSize: Got unexpected length: "+c.length+", expected: "+i,a(e,new Error(s)));if(e.s.bytesRead+=c.length,0===c.length)return e.push(null);var u=null,l=null;null!=e.s.bytesToSkip&&(u=e.s.bytesToSkip,e.s.bytesToSkip=0);const f=o===e.s.expectedEnd-1,p=e.s.options.end-e.s.bytesToSkip;f&&null!=e.s.bytesToTrim?l=e.s.file.chunkSize-e.s.bytesToTrim:e.s.options.end&&p<n.data.length()&&(l=p),null==u&&null==l||(c=c.slice(u||0,l||c.length)),e.push(c)}))}(e)}))},i.prototype.start=function(e){return s(this),this.s.options.start=e,this},i.prototype.end=function(e){return s(this),this.s.options.end=e,this},i.prototype.abort=function(e){var t=this;this.push(null),this.destroyed=!0,this.s.cursor?this.s.cursor.close((function(n){t.emit("close"),e&&e(n)})):(this.s.init||t.emit("close"),e&&e())}},function(e,t,n){"use strict";var r=n(2),o=n(20),i=n(18),s=n(5),a=n(22).Buffer;function c(e,t,n){if(n=n||{},i.Writable.call(this,n),this.bucket=e,this.chunks=e.s._chunksCollection,this.filename=t,this.files=e.s._filesCollection,this.options=n,this.done=!1,this.id=n.id?n.id:r.BSON.ObjectId(),this.chunkSizeBytes=this.options.chunkSizeBytes,this.bufToStore=a.alloc(this.chunkSizeBytes),this.length=0,this.md5=!n.disableMD5&&o.createHash("md5"),this.n=0,this.pos=0,this.state={streamEnd:!1,outstandingRequests:0,errored:!1,aborted:!1,promiseLibrary:this.bucket.s.promiseLibrary},!this.bucket.s.calledOpenUploadStream){this.bucket.s.calledOpenUploadStream=!0;var s=this;!function(e,t){e.files.findOne({},{_id:1},(function(n,r){return n?t(n):r?t():void e.files.listIndexes().toArray((function(n,r){if(n){if(26===n.code){var o={filename:1,uploadDate:1};return void e.files.createIndex(o,{background:!1},(function(n){if(n)return t(n);f(e,t)}))}return t(n)}var i=!1;if(r.forEach((function(e){2===Object.keys(e.key).length&&1===e.key.filename&&1===e.key.uploadDate&&(i=!0)})),i)f(e,t);else{o={filename:1,uploadDate:1};var s=d(e);s.background=!1,e.files.createIndex(o,s,(function(n){if(n)return t(n);f(e,t)}))}}))}))}(this,(function(){s.bucket.s.checkedIndexes=!0,s.bucket.emit("index")}))}}function u(e,t,n){if(!e.state.errored){if(e.state.errored=!0,n)return n(t);e.emit("error",t)}}function l(e,t,n){return{_id:r.BSON.ObjectId(),files_id:e,n:t,data:n}}function f(e,t){e.chunks.listIndexes().toArray((function(n,r){if(n){if(26===n.code){var o={files_id:1,n:1};return void e.chunks.createIndex(o,{background:!1,unique:!0},(function(e){if(e)return t(e);t()}))}return t(n)}var i=!1;if(r.forEach((function(e){e.key&&(2===Object.keys(e.key).length&&1===e.key.files_id&&1===e.key.n&&(i=!0))})),i)t();else{o={files_id:1,n:1};var s=d(e);s.background=!1,s.unique=!0,e.chunks.createIndex(o,s,(function(e){if(e)return t(e);t()}))}}))}function p(e,t){if(e.done)return!0;if(e.state.streamEnd&&0===e.state.outstandingRequests&&!e.state.errored){e.done=!0;var n=function(e,t,n,r,o,i,s,a){var c={_id:e,length:t,chunkSize:n,uploadDate:new Date,filename:o};r&&(c.md5=r);i&&(c.contentType=i);s&&(c.aliases=s);a&&(c.metadata=a);return c}(e.id,e.length,e.chunkSizeBytes,e.md5&&e.md5.digest("hex"),e.filename,e.options.contentType,e.options.aliases,e.options.metadata);return!g(e,t)&&(e.files.insertOne(n,d(e),(function(r){if(r)return u(e,r,t);e.emit("finish",n),e.emit("close")})),!0)}return!1}function d(e){var t={};return e.options.writeConcern&&(t.w=e.options.writeConcern.w,t.wtimeout=e.options.writeConcern.wtimeout,t.j=e.options.writeConcern.j),t}function h(e,t){return e.bucket.s.checkedIndexes?t(!1):(e.bucket.once("index",(function(){t(!0)})),!0)}function m(e,t){if(0===e.pos)return p(e,t);++e.state.outstandingRequests;var n=a.alloc(e.pos);e.bufToStore.copy(n,0,0,e.pos),e.md5&&e.md5.update(n);var r=l(e.id,e.n,n);if(g(e,t))return!1;e.chunks.insertOne(r,d(e),(function(t){if(t)return u(e,t);--e.state.outstandingRequests,p(e)}))}function g(e,t){return!!e.state.aborted&&("function"==typeof t&&t(new Error("this stream has been aborted")),!0)}e.exports=c,s.inherits(c,i.Writable),c.prototype.write=function(e,t,n){var r=this;return h(this,(function(){return function(e,t,n,r){if(g(e,r))return!1;var o=a.isBuffer(t)?t:a.from(t,n);if(e.length+=o.length,e.pos+o.length<e.chunkSizeBytes)return o.copy(e.bufToStore,e.pos),e.pos+=o.length,r&&r(),!0;var i=o.length,s=e.chunkSizeBytes-e.pos,c=Math.min(s,o.length),f=0;for(;i>0;){var h=o.length-i;if(o.copy(e.bufToStore,e.pos,h,h+c),e.pos+=c,0===(s-=c)){e.md5&&e.md5.update(e.bufToStore);var m=l(e.id,e.n,a.from(e.bufToStore));if(++e.state.outstandingRequests,++f,g(e,r))return!1;e.chunks.insertOne(m,d(e),(function(t){if(t)return u(e,t);--e.state.outstandingRequests,--f||(e.emit("drain",m),r&&r(),p(e))})),s=e.chunkSizeBytes,e.pos=0,++e.n}i-=c,c=Math.min(s,i)}return!1}(r,e,t,n)}))},c.prototype.abort=function(e){if(this.state.streamEnd){var t=new Error("Cannot abort a stream that has already completed");return"function"==typeof e?e(t):this.state.promiseLibrary.reject(t)}if(this.state.aborted)return t=new Error("Cannot call abort() on a stream twice"),"function"==typeof e?e(t):this.state.promiseLibrary.reject(t);this.state.aborted=!0,this.chunks.deleteMany({files_id:this.id},(function(t){"function"==typeof e&&e(t)}))},c.prototype.end=function(e,t,n){var r=this;"function"==typeof e?(n=e,e=null,t=null):"function"==typeof t&&(n=t,t=null),g(this,n)||(this.state.streamEnd=!0,n&&this.once("finish",(function(e){n(null,e)})),e?this.write(e,t,(function(){m(r)})):h(this,(function(){m(r)})))}},function(e,t,n){const r=n(42).ObjectId;e.exports=function(e,t,n,o,i){const s=o.pureName,a=n.__getDatabase(),c=new t.Writable({objectMode:!0});return c.buffer=[],c.wasHeader=!1,c.addRow=e=>{!c.wasHeader&&(c.wasHeader=!0,e.__isStreamHeader)||(i.createStringId&&(e={_id:(new r).toString(),...e}),c.buffer.push(e))},c.checkStructure=async()=>{i.dropIfExists&&(console.log(`Dropping collection ${s}`),await a.collection(s).drop()),i.truncate&&(console.log(`Truncating collection ${s}`),await a.collection(s).deleteMany({}))},c.send=async()=>{const e=c.buffer;c.buffer=[],await a.collection(s).insertMany(e)},c.sendIfFull=async()=>{c.buffer.length>100&&await c.send()},c._write=async(e,t,n)=>{c.addRow(e),await c.sendIfFull(),n()},c._final=async e=>{await c.send(),e()},c}}]);
|
|
9
|
+
*/(function(){var o="Expected a function",i="__lodash_placeholder__",s=[["ary",128],["bind",1],["bindKey",2],["curry",8],["curryRight",16],["flip",512],["partial",32],["partialRight",64],["rearg",256]],a="[object Arguments]",c="[object Array]",u="[object Boolean]",l="[object Date]",f="[object Error]",p="[object Function]",d="[object GeneratorFunction]",h="[object Map]",m="[object Number]",g="[object Object]",y="[object RegExp]",b="[object Set]",v="[object String]",S="[object Symbol]",w="[object WeakMap]",_="[object ArrayBuffer]",O="[object DataView]",T="[object Float32Array]",C="[object Float64Array]",x="[object Int8Array]",E="[object Int16Array]",N="[object Int32Array]",I="[object Uint8Array]",A="[object Uint16Array]",k="[object Uint32Array]",M=/\b__p \+= '';/g,R=/\b(__p \+=) '' \+/g,j=/(__e\(.*?\)|\b__t\)) \+\n'';/g,D=/&(?:amp|lt|gt|quot|#39);/g,P=/[&<>"']/g,B=RegExp(D.source),L=RegExp(P.source),q=/<%-([\s\S]+?)%>/g,U=/<%([\s\S]+?)%>/g,z=/<%=([\s\S]+?)%>/g,$=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,W=/^\w*$/,F=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,V=/[\\^$.*+?()[\]{}|]/g,K=RegExp(V.source),H=/^\s+/,Y=/\s/,G=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,J=/\{\n\/\* \[wrapped with (.+)\] \*/,X=/,? & /,Z=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,Q=/[()=,{}\[\]\/\s]/,ee=/\\(\\)?/g,te=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,ne=/\w*$/,re=/^[-+]0x[0-9a-f]+$/i,oe=/^0b[01]+$/i,ie=/^\[object .+?Constructor\]$/,se=/^0o[0-7]+$/i,ae=/^(?:0|[1-9]\d*)$/,ce=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,ue=/($^)/,le=/['\n\r\u2028\u2029\\]/g,fe="\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff",pe="\\xac\\xb1\\xd7\\xf7\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf\\u2000-\\u206f \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",de="[\\ud800-\\udfff]",he="["+pe+"]",me="["+fe+"]",ge="\\d+",ye="[\\u2700-\\u27bf]",be="[a-z\\xdf-\\xf6\\xf8-\\xff]",ve="[^\\ud800-\\udfff"+pe+ge+"\\u2700-\\u27bfa-z\\xdf-\\xf6\\xf8-\\xffA-Z\\xc0-\\xd6\\xd8-\\xde]",Se="\\ud83c[\\udffb-\\udfff]",we="[^\\ud800-\\udfff]",_e="(?:\\ud83c[\\udde6-\\uddff]){2}",Oe="[\\ud800-\\udbff][\\udc00-\\udfff]",Te="[A-Z\\xc0-\\xd6\\xd8-\\xde]",Ce="(?:"+be+"|"+ve+")",xe="(?:"+Te+"|"+ve+")",Ee="(?:"+me+"|"+Se+")"+"?",Ne="[\\ufe0e\\ufe0f]?"+Ee+("(?:\\u200d(?:"+[we,_e,Oe].join("|")+")[\\ufe0e\\ufe0f]?"+Ee+")*"),Ie="(?:"+[ye,_e,Oe].join("|")+")"+Ne,Ae="(?:"+[we+me+"?",me,_e,Oe,de].join("|")+")",ke=RegExp("['’]","g"),Me=RegExp(me,"g"),Re=RegExp(Se+"(?="+Se+")|"+Ae+Ne,"g"),je=RegExp([Te+"?"+be+"+(?:['’](?:d|ll|m|re|s|t|ve))?(?="+[he,Te,"$"].join("|")+")",xe+"+(?:['’](?:D|LL|M|RE|S|T|VE))?(?="+[he,Te+Ce,"$"].join("|")+")",Te+"?"+Ce+"+(?:['’](?:d|ll|m|re|s|t|ve))?",Te+"+(?:['’](?:D|LL|M|RE|S|T|VE))?","\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])","\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",ge,Ie].join("|"),"g"),De=RegExp("[\\u200d\\ud800-\\udfff"+fe+"\\ufe0e\\ufe0f]"),Pe=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,Be=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],Le=-1,qe={};qe[T]=qe[C]=qe[x]=qe[E]=qe[N]=qe[I]=qe["[object Uint8ClampedArray]"]=qe[A]=qe[k]=!0,qe[a]=qe[c]=qe[_]=qe[u]=qe[O]=qe[l]=qe[f]=qe[p]=qe[h]=qe[m]=qe[g]=qe[y]=qe[b]=qe[v]=qe[w]=!1;var Ue={};Ue[a]=Ue[c]=Ue[_]=Ue[O]=Ue[u]=Ue[l]=Ue[T]=Ue[C]=Ue[x]=Ue[E]=Ue[N]=Ue[h]=Ue[m]=Ue[g]=Ue[y]=Ue[b]=Ue[v]=Ue[S]=Ue[I]=Ue["[object Uint8ClampedArray]"]=Ue[A]=Ue[k]=!0,Ue[f]=Ue[p]=Ue[w]=!1;var ze={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},$e=parseFloat,We=parseInt,Fe="object"==typeof global&&global&&global.Object===Object&&global,Ve="object"==typeof self&&self&&self.Object===Object&&self,Ke=Fe||Ve||Function("return this")(),He=t&&!t.nodeType&&t,Ye=He&&"object"==typeof e&&e&&!e.nodeType&&e,Ge=Ye&&Ye.exports===He,Je=Ge&&Fe.process,Xe=function(){try{var e=Ye&&Ye.require&&Ye.require("util").types;return e||Je&&Je.binding&&Je.binding("util")}catch(e){}}(),Ze=Xe&&Xe.isArrayBuffer,Qe=Xe&&Xe.isDate,et=Xe&&Xe.isMap,tt=Xe&&Xe.isRegExp,nt=Xe&&Xe.isSet,rt=Xe&&Xe.isTypedArray;function ot(e,t,n){switch(n.length){case 0:return e.call(t);case 1:return e.call(t,n[0]);case 2:return e.call(t,n[0],n[1]);case 3:return e.call(t,n[0],n[1],n[2])}return e.apply(t,n)}function it(e,t,n,r){for(var o=-1,i=null==e?0:e.length;++o<i;){var s=e[o];t(r,s,n(s),e)}return r}function st(e,t){for(var n=-1,r=null==e?0:e.length;++n<r&&!1!==t(e[n],n,e););return e}function at(e,t){for(var n=null==e?0:e.length;n--&&!1!==t(e[n],n,e););return e}function ct(e,t){for(var n=-1,r=null==e?0:e.length;++n<r;)if(!t(e[n],n,e))return!1;return!0}function ut(e,t){for(var n=-1,r=null==e?0:e.length,o=0,i=[];++n<r;){var s=e[n];t(s,n,e)&&(i[o++]=s)}return i}function lt(e,t){return!!(null==e?0:e.length)&&St(e,t,0)>-1}function ft(e,t,n){for(var r=-1,o=null==e?0:e.length;++r<o;)if(n(t,e[r]))return!0;return!1}function pt(e,t){for(var n=-1,r=null==e?0:e.length,o=Array(r);++n<r;)o[n]=t(e[n],n,e);return o}function dt(e,t){for(var n=-1,r=t.length,o=e.length;++n<r;)e[o+n]=t[n];return e}function ht(e,t,n,r){var o=-1,i=null==e?0:e.length;for(r&&i&&(n=e[++o]);++o<i;)n=t(n,e[o],o,e);return n}function mt(e,t,n,r){var o=null==e?0:e.length;for(r&&o&&(n=e[--o]);o--;)n=t(n,e[o],o,e);return n}function gt(e,t){for(var n=-1,r=null==e?0:e.length;++n<r;)if(t(e[n],n,e))return!0;return!1}var yt=Tt("length");function bt(e,t,n){var r;return n(e,(function(e,n,o){if(t(e,n,o))return r=n,!1})),r}function vt(e,t,n,r){for(var o=e.length,i=n+(r?1:-1);r?i--:++i<o;)if(t(e[i],i,e))return i;return-1}function St(e,t,n){return t==t?function(e,t,n){var r=n-1,o=e.length;for(;++r<o;)if(e[r]===t)return r;return-1}(e,t,n):vt(e,_t,n)}function wt(e,t,n,r){for(var o=n-1,i=e.length;++o<i;)if(r(e[o],t))return o;return-1}function _t(e){return e!=e}function Ot(e,t){var n=null==e?0:e.length;return n?Et(e,t)/n:NaN}function Tt(e){return function(t){return null==t?void 0:t[e]}}function Ct(e){return function(t){return null==e?void 0:e[t]}}function xt(e,t,n,r,o){return o(e,(function(e,o,i){n=r?(r=!1,e):t(n,e,o,i)})),n}function Et(e,t){for(var n,r=-1,o=e.length;++r<o;){var i=t(e[r]);void 0!==i&&(n=void 0===n?i:n+i)}return n}function Nt(e,t){for(var n=-1,r=Array(e);++n<e;)r[n]=t(n);return r}function It(e){return e?e.slice(0,Ht(e)+1).replace(H,""):e}function At(e){return function(t){return e(t)}}function kt(e,t){return pt(t,(function(t){return e[t]}))}function Mt(e,t){return e.has(t)}function Rt(e,t){for(var n=-1,r=e.length;++n<r&&St(t,e[n],0)>-1;);return n}function jt(e,t){for(var n=e.length;n--&&St(t,e[n],0)>-1;);return n}function Dt(e,t){for(var n=e.length,r=0;n--;)e[n]===t&&++r;return r}var Pt=Ct({"À":"A","Á":"A","Â":"A","Ã":"A","Ä":"A","Å":"A","à":"a","á":"a","â":"a","ã":"a","ä":"a","å":"a","Ç":"C","ç":"c","Ð":"D","ð":"d","È":"E","É":"E","Ê":"E","Ë":"E","è":"e","é":"e","ê":"e","ë":"e","Ì":"I","Í":"I","Î":"I","Ï":"I","ì":"i","í":"i","î":"i","ï":"i","Ñ":"N","ñ":"n","Ò":"O","Ó":"O","Ô":"O","Õ":"O","Ö":"O","Ø":"O","ò":"o","ó":"o","ô":"o","õ":"o","ö":"o","ø":"o","Ù":"U","Ú":"U","Û":"U","Ü":"U","ù":"u","ú":"u","û":"u","ü":"u","Ý":"Y","ý":"y","ÿ":"y","Æ":"Ae","æ":"ae","Þ":"Th","þ":"th","ß":"ss","Ā":"A","Ă":"A","Ą":"A","ā":"a","ă":"a","ą":"a","Ć":"C","Ĉ":"C","Ċ":"C","Č":"C","ć":"c","ĉ":"c","ċ":"c","č":"c","Ď":"D","Đ":"D","ď":"d","đ":"d","Ē":"E","Ĕ":"E","Ė":"E","Ę":"E","Ě":"E","ē":"e","ĕ":"e","ė":"e","ę":"e","ě":"e","Ĝ":"G","Ğ":"G","Ġ":"G","Ģ":"G","ĝ":"g","ğ":"g","ġ":"g","ģ":"g","Ĥ":"H","Ħ":"H","ĥ":"h","ħ":"h","Ĩ":"I","Ī":"I","Ĭ":"I","Į":"I","İ":"I","ĩ":"i","ī":"i","ĭ":"i","į":"i","ı":"i","Ĵ":"J","ĵ":"j","Ķ":"K","ķ":"k","ĸ":"k","Ĺ":"L","Ļ":"L","Ľ":"L","Ŀ":"L","Ł":"L","ĺ":"l","ļ":"l","ľ":"l","ŀ":"l","ł":"l","Ń":"N","Ņ":"N","Ň":"N","Ŋ":"N","ń":"n","ņ":"n","ň":"n","ŋ":"n","Ō":"O","Ŏ":"O","Ő":"O","ō":"o","ŏ":"o","ő":"o","Ŕ":"R","Ŗ":"R","Ř":"R","ŕ":"r","ŗ":"r","ř":"r","Ś":"S","Ŝ":"S","Ş":"S","Š":"S","ś":"s","ŝ":"s","ş":"s","š":"s","Ţ":"T","Ť":"T","Ŧ":"T","ţ":"t","ť":"t","ŧ":"t","Ũ":"U","Ū":"U","Ŭ":"U","Ů":"U","Ű":"U","Ų":"U","ũ":"u","ū":"u","ŭ":"u","ů":"u","ű":"u","ų":"u","Ŵ":"W","ŵ":"w","Ŷ":"Y","ŷ":"y","Ÿ":"Y","Ź":"Z","Ż":"Z","Ž":"Z","ź":"z","ż":"z","ž":"z","IJ":"IJ","ij":"ij","Œ":"Oe","œ":"oe","ʼn":"'n","ſ":"s"}),Bt=Ct({"&":"&","<":"<",">":">",'"':""","'":"'"});function Lt(e){return"\\"+ze[e]}function qt(e){return De.test(e)}function Ut(e){var t=-1,n=Array(e.size);return e.forEach((function(e,r){n[++t]=[r,e]})),n}function zt(e,t){return function(n){return e(t(n))}}function $t(e,t){for(var n=-1,r=e.length,o=0,s=[];++n<r;){var a=e[n];a!==t&&a!==i||(e[n]=i,s[o++]=n)}return s}function Wt(e){var t=-1,n=Array(e.size);return e.forEach((function(e){n[++t]=e})),n}function Ft(e){var t=-1,n=Array(e.size);return e.forEach((function(e){n[++t]=[e,e]})),n}function Vt(e){return qt(e)?function(e){var t=Re.lastIndex=0;for(;Re.test(e);)++t;return t}(e):yt(e)}function Kt(e){return qt(e)?function(e){return e.match(Re)||[]}(e):function(e){return e.split("")}(e)}function Ht(e){for(var t=e.length;t--&&Y.test(e.charAt(t)););return t}var Yt=Ct({"&":"&","<":"<",">":">",""":'"',"'":"'"});var Gt=function e(t){var n,r=(t=null==t?Ke:Gt.defaults(Ke.Object(),t,Gt.pick(Ke,Be))).Array,Y=t.Date,fe=t.Error,pe=t.Function,de=t.Math,he=t.Object,me=t.RegExp,ge=t.String,ye=t.TypeError,be=r.prototype,ve=pe.prototype,Se=he.prototype,we=t["__core-js_shared__"],_e=ve.toString,Oe=Se.hasOwnProperty,Te=0,Ce=(n=/[^.]+$/.exec(we&&we.keys&&we.keys.IE_PROTO||""))?"Symbol(src)_1."+n:"",xe=Se.toString,Ee=_e.call(he),Ne=Ke._,Ie=me("^"+_e.call(Oe).replace(V,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Ae=Ge?t.Buffer:void 0,Re=t.Symbol,De=t.Uint8Array,ze=Ae?Ae.allocUnsafe:void 0,Fe=zt(he.getPrototypeOf,he),Ve=he.create,He=Se.propertyIsEnumerable,Ye=be.splice,Je=Re?Re.isConcatSpreadable:void 0,Xe=Re?Re.iterator:void 0,yt=Re?Re.toStringTag:void 0,Ct=function(){try{var e=ti(he,"defineProperty");return e({},"",{}),e}catch(e){}}(),Jt=t.clearTimeout!==Ke.clearTimeout&&t.clearTimeout,Xt=Y&&Y.now!==Ke.Date.now&&Y.now,Zt=t.setTimeout!==Ke.setTimeout&&t.setTimeout,Qt=de.ceil,en=de.floor,tn=he.getOwnPropertySymbols,nn=Ae?Ae.isBuffer:void 0,rn=t.isFinite,on=be.join,sn=zt(he.keys,he),an=de.max,cn=de.min,un=Y.now,ln=t.parseInt,fn=de.random,pn=be.reverse,dn=ti(t,"DataView"),hn=ti(t,"Map"),mn=ti(t,"Promise"),gn=ti(t,"Set"),yn=ti(t,"WeakMap"),bn=ti(he,"create"),vn=yn&&new yn,Sn={},wn=Ni(dn),_n=Ni(hn),On=Ni(mn),Tn=Ni(gn),Cn=Ni(yn),xn=Re?Re.prototype:void 0,En=xn?xn.valueOf:void 0,Nn=xn?xn.toString:void 0;function In(e){if(Vs(e)&&!js(e)&&!(e instanceof Rn)){if(e instanceof Mn)return e;if(Oe.call(e,"__wrapped__"))return Ii(e)}return new Mn(e)}var An=function(){function e(){}return function(t){if(!Fs(t))return{};if(Ve)return Ve(t);e.prototype=t;var n=new e;return e.prototype=void 0,n}}();function kn(){}function Mn(e,t){this.__wrapped__=e,this.__actions__=[],this.__chain__=!!t,this.__index__=0,this.__values__=void 0}function Rn(e){this.__wrapped__=e,this.__actions__=[],this.__dir__=1,this.__filtered__=!1,this.__iteratees__=[],this.__takeCount__=4294967295,this.__views__=[]}function jn(e){var t=-1,n=null==e?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}function Dn(e){var t=-1,n=null==e?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}function Pn(e){var t=-1,n=null==e?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}function Bn(e){var t=-1,n=null==e?0:e.length;for(this.__data__=new Pn;++t<n;)this.add(e[t])}function Ln(e){var t=this.__data__=new Dn(e);this.size=t.size}function qn(e,t){var n=js(e),r=!n&&Rs(e),o=!n&&!r&&Ls(e),i=!n&&!r&&!o&&Qs(e),s=n||r||o||i,a=s?Nt(e.length,ge):[],c=a.length;for(var u in e)!t&&!Oe.call(e,u)||s&&("length"==u||o&&("offset"==u||"parent"==u)||i&&("buffer"==u||"byteLength"==u||"byteOffset"==u)||ci(u,c))||a.push(u);return a}function Un(e){var t=e.length;return t?e[Br(0,t-1)]:void 0}function zn(e,t){return Ci(vo(e),Jn(t,0,e.length))}function $n(e){return Ci(vo(e))}function Wn(e,t,n){(void 0===n||As(e[t],n))&&(void 0!==n||t in e)||Yn(e,t,n)}function Fn(e,t,n){var r=e[t];Oe.call(e,t)&&As(r,n)&&(void 0!==n||t in e)||Yn(e,t,n)}function Vn(e,t){for(var n=e.length;n--;)if(As(e[n][0],t))return n;return-1}function Kn(e,t,n,r){return tr(e,(function(e,o,i){t(r,e,n(e),i)})),r}function Hn(e,t){return e&&So(t,wa(t),e)}function Yn(e,t,n){"__proto__"==t&&Ct?Ct(e,t,{configurable:!0,enumerable:!0,value:n,writable:!0}):e[t]=n}function Gn(e,t){for(var n=-1,o=t.length,i=r(o),s=null==e;++n<o;)i[n]=s?void 0:ga(e,t[n]);return i}function Jn(e,t,n){return e==e&&(void 0!==n&&(e=e<=n?e:n),void 0!==t&&(e=e>=t?e:t)),e}function Xn(e,t,n,r,o,i){var s,c=1&t,f=2&t,w=4&t;if(n&&(s=o?n(e,r,o,i):n(e)),void 0!==s)return s;if(!Fs(e))return e;var M=js(e);if(M){if(s=function(e){var t=e.length,n=new e.constructor(t);t&&"string"==typeof e[0]&&Oe.call(e,"index")&&(n.index=e.index,n.input=e.input);return n}(e),!c)return vo(e,s)}else{var R=oi(e),j=R==p||R==d;if(Ls(e))return po(e,c);if(R==g||R==a||j&&!o){if(s=f||j?{}:si(e),!c)return f?function(e,t){return So(e,ri(e),t)}(e,function(e,t){return e&&So(t,_a(t),e)}(s,e)):function(e,t){return So(e,ni(e),t)}(e,Hn(s,e))}else{if(!Ue[R])return o?e:{};s=function(e,t,n){var r=e.constructor;switch(t){case _:return ho(e);case u:case l:return new r(+e);case O:return function(e,t){var n=t?ho(e.buffer):e.buffer;return new e.constructor(n,e.byteOffset,e.byteLength)}(e,n);case T:case C:case x:case E:case N:case I:case"[object Uint8ClampedArray]":case A:case k:return mo(e,n);case h:return new r;case m:case v:return new r(e);case y:return function(e){var t=new e.constructor(e.source,ne.exec(e));return t.lastIndex=e.lastIndex,t}(e);case b:return new r;case S:return o=e,En?he(En.call(o)):{}}var o}(e,R,c)}}i||(i=new Ln);var D=i.get(e);if(D)return D;i.set(e,s),Js(e)?e.forEach((function(r){s.add(Xn(r,t,n,r,e,i))})):Ks(e)&&e.forEach((function(r,o){s.set(o,Xn(r,t,n,o,e,i))}));var P=M?void 0:(w?f?Yo:Ho:f?_a:wa)(e);return st(P||e,(function(r,o){P&&(r=e[o=r]),Fn(s,o,Xn(r,t,n,o,e,i))})),s}function Zn(e,t,n){var r=n.length;if(null==e)return!r;for(e=he(e);r--;){var o=n[r],i=t[o],s=e[o];if(void 0===s&&!(o in e)||!i(s))return!1}return!0}function Qn(e,t,n){if("function"!=typeof e)throw new ye(o);return wi((function(){e.apply(void 0,n)}),t)}function er(e,t,n,r){var o=-1,i=lt,s=!0,a=e.length,c=[],u=t.length;if(!a)return c;n&&(t=pt(t,At(n))),r?(i=ft,s=!1):t.length>=200&&(i=Mt,s=!1,t=new Bn(t));e:for(;++o<a;){var l=e[o],f=null==n?l:n(l);if(l=r||0!==l?l:0,s&&f==f){for(var p=u;p--;)if(t[p]===f)continue e;c.push(l)}else i(t,f,r)||c.push(l)}return c}In.templateSettings={escape:q,evaluate:U,interpolate:z,variable:"",imports:{_:In}},In.prototype=kn.prototype,In.prototype.constructor=In,Mn.prototype=An(kn.prototype),Mn.prototype.constructor=Mn,Rn.prototype=An(kn.prototype),Rn.prototype.constructor=Rn,jn.prototype.clear=function(){this.__data__=bn?bn(null):{},this.size=0},jn.prototype.delete=function(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t},jn.prototype.get=function(e){var t=this.__data__;if(bn){var n=t[e];return"__lodash_hash_undefined__"===n?void 0:n}return Oe.call(t,e)?t[e]:void 0},jn.prototype.has=function(e){var t=this.__data__;return bn?void 0!==t[e]:Oe.call(t,e)},jn.prototype.set=function(e,t){var n=this.__data__;return this.size+=this.has(e)?0:1,n[e]=bn&&void 0===t?"__lodash_hash_undefined__":t,this},Dn.prototype.clear=function(){this.__data__=[],this.size=0},Dn.prototype.delete=function(e){var t=this.__data__,n=Vn(t,e);return!(n<0)&&(n==t.length-1?t.pop():Ye.call(t,n,1),--this.size,!0)},Dn.prototype.get=function(e){var t=this.__data__,n=Vn(t,e);return n<0?void 0:t[n][1]},Dn.prototype.has=function(e){return Vn(this.__data__,e)>-1},Dn.prototype.set=function(e,t){var n=this.__data__,r=Vn(n,e);return r<0?(++this.size,n.push([e,t])):n[r][1]=t,this},Pn.prototype.clear=function(){this.size=0,this.__data__={hash:new jn,map:new(hn||Dn),string:new jn}},Pn.prototype.delete=function(e){var t=Qo(this,e).delete(e);return this.size-=t?1:0,t},Pn.prototype.get=function(e){return Qo(this,e).get(e)},Pn.prototype.has=function(e){return Qo(this,e).has(e)},Pn.prototype.set=function(e,t){var n=Qo(this,e),r=n.size;return n.set(e,t),this.size+=n.size==r?0:1,this},Bn.prototype.add=Bn.prototype.push=function(e){return this.__data__.set(e,"__lodash_hash_undefined__"),this},Bn.prototype.has=function(e){return this.__data__.has(e)},Ln.prototype.clear=function(){this.__data__=new Dn,this.size=0},Ln.prototype.delete=function(e){var t=this.__data__,n=t.delete(e);return this.size=t.size,n},Ln.prototype.get=function(e){return this.__data__.get(e)},Ln.prototype.has=function(e){return this.__data__.has(e)},Ln.prototype.set=function(e,t){var n=this.__data__;if(n instanceof Dn){var r=n.__data__;if(!hn||r.length<199)return r.push([e,t]),this.size=++n.size,this;n=this.__data__=new Pn(r)}return n.set(e,t),this.size=n.size,this};var tr=Oo(ur),nr=Oo(lr,!0);function rr(e,t){var n=!0;return tr(e,(function(e,r,o){return n=!!t(e,r,o)})),n}function or(e,t,n){for(var r=-1,o=e.length;++r<o;){var i=e[r],s=t(i);if(null!=s&&(void 0===a?s==s&&!Zs(s):n(s,a)))var a=s,c=i}return c}function ir(e,t){var n=[];return tr(e,(function(e,r,o){t(e,r,o)&&n.push(e)})),n}function sr(e,t,n,r,o){var i=-1,s=e.length;for(n||(n=ai),o||(o=[]);++i<s;){var a=e[i];t>0&&n(a)?t>1?sr(a,t-1,n,r,o):dt(o,a):r||(o[o.length]=a)}return o}var ar=To(),cr=To(!0);function ur(e,t){return e&&ar(e,t,wa)}function lr(e,t){return e&&cr(e,t,wa)}function fr(e,t){return ut(t,(function(t){return zs(e[t])}))}function pr(e,t){for(var n=0,r=(t=co(t,e)).length;null!=e&&n<r;)e=e[Ei(t[n++])];return n&&n==r?e:void 0}function dr(e,t,n){var r=t(e);return js(e)?r:dt(r,n(e))}function hr(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":yt&&yt in he(e)?function(e){var t=Oe.call(e,yt),n=e[yt];try{e[yt]=void 0;var r=!0}catch(e){}var o=xe.call(e);r&&(t?e[yt]=n:delete e[yt]);return o}(e):function(e){return xe.call(e)}(e)}function mr(e,t){return e>t}function gr(e,t){return null!=e&&Oe.call(e,t)}function yr(e,t){return null!=e&&t in he(e)}function br(e,t,n){for(var o=n?ft:lt,i=e[0].length,s=e.length,a=s,c=r(s),u=1/0,l=[];a--;){var f=e[a];a&&t&&(f=pt(f,At(t))),u=cn(f.length,u),c[a]=!n&&(t||i>=120&&f.length>=120)?new Bn(a&&f):void 0}f=e[0];var p=-1,d=c[0];e:for(;++p<i&&l.length<u;){var h=f[p],m=t?t(h):h;if(h=n||0!==h?h:0,!(d?Mt(d,m):o(l,m,n))){for(a=s;--a;){var g=c[a];if(!(g?Mt(g,m):o(e[a],m,n)))continue e}d&&d.push(m),l.push(h)}}return l}function vr(e,t,n){var r=null==(e=yi(e,t=co(t,e)))?e:e[Ei(Ui(t))];return null==r?void 0:ot(r,e,n)}function Sr(e){return Vs(e)&&hr(e)==a}function wr(e,t,n,r,o){return e===t||(null==e||null==t||!Vs(e)&&!Vs(t)?e!=e&&t!=t:function(e,t,n,r,o,i){var s=js(e),p=js(t),d=s?c:oi(e),w=p?c:oi(t),T=(d=d==a?g:d)==g,C=(w=w==a?g:w)==g,x=d==w;if(x&&Ls(e)){if(!Ls(t))return!1;s=!0,T=!1}if(x&&!T)return i||(i=new Ln),s||Qs(e)?Vo(e,t,n,r,o,i):function(e,t,n,r,o,i,s){switch(n){case O:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case _:return!(e.byteLength!=t.byteLength||!i(new De(e),new De(t)));case u:case l:case m:return As(+e,+t);case f:return e.name==t.name&&e.message==t.message;case y:case v:return e==t+"";case h:var a=Ut;case b:var c=1&r;if(a||(a=Wt),e.size!=t.size&&!c)return!1;var p=s.get(e);if(p)return p==t;r|=2,s.set(e,t);var d=Vo(a(e),a(t),r,o,i,s);return s.delete(e),d;case S:if(En)return En.call(e)==En.call(t)}return!1}(e,t,d,n,r,o,i);if(!(1&n)){var E=T&&Oe.call(e,"__wrapped__"),N=C&&Oe.call(t,"__wrapped__");if(E||N){var I=E?e.value():e,A=N?t.value():t;return i||(i=new Ln),o(I,A,n,r,i)}}if(!x)return!1;return i||(i=new Ln),function(e,t,n,r,o,i){var s=1&n,a=Ho(e),c=a.length,u=Ho(t).length;if(c!=u&&!s)return!1;var l=c;for(;l--;){var f=a[l];if(!(s?f in t:Oe.call(t,f)))return!1}var p=i.get(e),d=i.get(t);if(p&&d)return p==t&&d==e;var h=!0;i.set(e,t),i.set(t,e);var m=s;for(;++l<c;){f=a[l];var g=e[f],y=t[f];if(r)var b=s?r(y,g,f,t,e,i):r(g,y,f,e,t,i);if(!(void 0===b?g===y||o(g,y,n,r,i):b)){h=!1;break}m||(m="constructor"==f)}if(h&&!m){var v=e.constructor,S=t.constructor;v!=S&&"constructor"in e&&"constructor"in t&&!("function"==typeof v&&v instanceof v&&"function"==typeof S&&S instanceof S)&&(h=!1)}return i.delete(e),i.delete(t),h}(e,t,n,r,o,i)}(e,t,n,r,wr,o))}function _r(e,t,n,r){var o=n.length,i=o,s=!r;if(null==e)return!i;for(e=he(e);o--;){var a=n[o];if(s&&a[2]?a[1]!==e[a[0]]:!(a[0]in e))return!1}for(;++o<i;){var c=(a=n[o])[0],u=e[c],l=a[1];if(s&&a[2]){if(void 0===u&&!(c in e))return!1}else{var f=new Ln;if(r)var p=r(u,l,c,e,t,f);if(!(void 0===p?wr(l,u,3,r,f):p))return!1}}return!0}function Or(e){return!(!Fs(e)||function(e){return!!Ce&&Ce in e}(e))&&(zs(e)?Ie:ie).test(Ni(e))}function Tr(e){return"function"==typeof e?e:null==e?Ha:"object"==typeof e?js(e)?Ar(e[0],e[1]):Ir(e):nc(e)}function Cr(e){if(!di(e))return sn(e);var t=[];for(var n in he(e))Oe.call(e,n)&&"constructor"!=n&&t.push(n);return t}function xr(e){if(!Fs(e))return function(e){var t=[];if(null!=e)for(var n in he(e))t.push(n);return t}(e);var t=di(e),n=[];for(var r in e)("constructor"!=r||!t&&Oe.call(e,r))&&n.push(r);return n}function Er(e,t){return e<t}function Nr(e,t){var n=-1,o=Ps(e)?r(e.length):[];return tr(e,(function(e,r,i){o[++n]=t(e,r,i)})),o}function Ir(e){var t=ei(e);return 1==t.length&&t[0][2]?mi(t[0][0],t[0][1]):function(n){return n===e||_r(n,e,t)}}function Ar(e,t){return li(e)&&hi(t)?mi(Ei(e),t):function(n){var r=ga(n,e);return void 0===r&&r===t?ya(n,e):wr(t,r,3)}}function kr(e,t,n,r,o){e!==t&&ar(t,(function(i,s){if(o||(o=new Ln),Fs(i))!function(e,t,n,r,o,i,s){var a=vi(e,n),c=vi(t,n),u=s.get(c);if(u)return void Wn(e,n,u);var l=i?i(a,c,n+"",e,t,s):void 0,f=void 0===l;if(f){var p=js(c),d=!p&&Ls(c),h=!p&&!d&&Qs(c);l=c,p||d||h?js(a)?l=a:Bs(a)?l=vo(a):d?(f=!1,l=po(c,!0)):h?(f=!1,l=mo(c,!0)):l=[]:Ys(c)||Rs(c)?(l=a,Rs(a)?l=aa(a):Fs(a)&&!zs(a)||(l=si(c))):f=!1}f&&(s.set(c,l),o(l,c,r,i,s),s.delete(c));Wn(e,n,l)}(e,t,s,n,kr,r,o);else{var a=r?r(vi(e,s),i,s+"",e,t,o):void 0;void 0===a&&(a=i),Wn(e,s,a)}}),_a)}function Mr(e,t){var n=e.length;if(n)return ci(t+=t<0?n:0,n)?e[t]:void 0}function Rr(e,t,n){t=t.length?pt(t,(function(e){return js(e)?function(t){return pr(t,1===e.length?e[0]:e)}:e})):[Ha];var r=-1;return t=pt(t,At(Zo())),function(e,t){var n=e.length;for(e.sort(t);n--;)e[n]=e[n].value;return e}(Nr(e,(function(e,n,o){return{criteria:pt(t,(function(t){return t(e)})),index:++r,value:e}})),(function(e,t){return function(e,t,n){var r=-1,o=e.criteria,i=t.criteria,s=o.length,a=n.length;for(;++r<s;){var c=go(o[r],i[r]);if(c){if(r>=a)return c;var u=n[r];return c*("desc"==u?-1:1)}}return e.index-t.index}(e,t,n)}))}function jr(e,t,n){for(var r=-1,o=t.length,i={};++r<o;){var s=t[r],a=pr(e,s);n(a,s)&&$r(i,co(s,e),a)}return i}function Dr(e,t,n,r){var o=r?wt:St,i=-1,s=t.length,a=e;for(e===t&&(t=vo(t)),n&&(a=pt(e,At(n)));++i<s;)for(var c=0,u=t[i],l=n?n(u):u;(c=o(a,l,c,r))>-1;)a!==e&&Ye.call(a,c,1),Ye.call(e,c,1);return e}function Pr(e,t){for(var n=e?t.length:0,r=n-1;n--;){var o=t[n];if(n==r||o!==i){var i=o;ci(o)?Ye.call(e,o,1):eo(e,o)}}return e}function Br(e,t){return e+en(fn()*(t-e+1))}function Lr(e,t){var n="";if(!e||t<1||t>9007199254740991)return n;do{t%2&&(n+=e),(t=en(t/2))&&(e+=e)}while(t);return n}function qr(e,t){return _i(gi(e,t,Ha),e+"")}function Ur(e){return Un(Aa(e))}function zr(e,t){var n=Aa(e);return Ci(n,Jn(t,0,n.length))}function $r(e,t,n,r){if(!Fs(e))return e;for(var o=-1,i=(t=co(t,e)).length,s=i-1,a=e;null!=a&&++o<i;){var c=Ei(t[o]),u=n;if("__proto__"===c||"constructor"===c||"prototype"===c)return e;if(o!=s){var l=a[c];void 0===(u=r?r(l,c,a):void 0)&&(u=Fs(l)?l:ci(t[o+1])?[]:{})}Fn(a,c,u),a=a[c]}return e}var Wr=vn?function(e,t){return vn.set(e,t),e}:Ha,Fr=Ct?function(e,t){return Ct(e,"toString",{configurable:!0,enumerable:!1,value:Fa(t),writable:!0})}:Ha;function Vr(e){return Ci(Aa(e))}function Kr(e,t,n){var o=-1,i=e.length;t<0&&(t=-t>i?0:i+t),(n=n>i?i:n)<0&&(n+=i),i=t>n?0:n-t>>>0,t>>>=0;for(var s=r(i);++o<i;)s[o]=e[o+t];return s}function Hr(e,t){var n;return tr(e,(function(e,r,o){return!(n=t(e,r,o))})),!!n}function Yr(e,t,n){var r=0,o=null==e?r:e.length;if("number"==typeof t&&t==t&&o<=2147483647){for(;r<o;){var i=r+o>>>1,s=e[i];null!==s&&!Zs(s)&&(n?s<=t:s<t)?r=i+1:o=i}return o}return Gr(e,t,Ha,n)}function Gr(e,t,n,r){var o=0,i=null==e?0:e.length;if(0===i)return 0;for(var s=(t=n(t))!=t,a=null===t,c=Zs(t),u=void 0===t;o<i;){var l=en((o+i)/2),f=n(e[l]),p=void 0!==f,d=null===f,h=f==f,m=Zs(f);if(s)var g=r||h;else g=u?h&&(r||p):a?h&&p&&(r||!d):c?h&&p&&!d&&(r||!m):!d&&!m&&(r?f<=t:f<t);g?o=l+1:i=l}return cn(i,4294967294)}function Jr(e,t){for(var n=-1,r=e.length,o=0,i=[];++n<r;){var s=e[n],a=t?t(s):s;if(!n||!As(a,c)){var c=a;i[o++]=0===s?0:s}}return i}function Xr(e){return"number"==typeof e?e:Zs(e)?NaN:+e}function Zr(e){if("string"==typeof e)return e;if(js(e))return pt(e,Zr)+"";if(Zs(e))return Nn?Nn.call(e):"";var t=e+"";return"0"==t&&1/e==-1/0?"-0":t}function Qr(e,t,n){var r=-1,o=lt,i=e.length,s=!0,a=[],c=a;if(n)s=!1,o=ft;else if(i>=200){var u=t?null:qo(e);if(u)return Wt(u);s=!1,o=Mt,c=new Bn}else c=t?[]:a;e:for(;++r<i;){var l=e[r],f=t?t(l):l;if(l=n||0!==l?l:0,s&&f==f){for(var p=c.length;p--;)if(c[p]===f)continue e;t&&c.push(f),a.push(l)}else o(c,f,n)||(c!==a&&c.push(f),a.push(l))}return a}function eo(e,t){return null==(e=yi(e,t=co(t,e)))||delete e[Ei(Ui(t))]}function to(e,t,n,r){return $r(e,t,n(pr(e,t)),r)}function no(e,t,n,r){for(var o=e.length,i=r?o:-1;(r?i--:++i<o)&&t(e[i],i,e););return n?Kr(e,r?0:i,r?i+1:o):Kr(e,r?i+1:0,r?o:i)}function ro(e,t){var n=e;return n instanceof Rn&&(n=n.value()),ht(t,(function(e,t){return t.func.apply(t.thisArg,dt([e],t.args))}),n)}function oo(e,t,n){var o=e.length;if(o<2)return o?Qr(e[0]):[];for(var i=-1,s=r(o);++i<o;)for(var a=e[i],c=-1;++c<o;)c!=i&&(s[i]=er(s[i]||a,e[c],t,n));return Qr(sr(s,1),t,n)}function io(e,t,n){for(var r=-1,o=e.length,i=t.length,s={};++r<o;){var a=r<i?t[r]:void 0;n(s,e[r],a)}return s}function so(e){return Bs(e)?e:[]}function ao(e){return"function"==typeof e?e:Ha}function co(e,t){return js(e)?e:li(e,t)?[e]:xi(ca(e))}var uo=qr;function lo(e,t,n){var r=e.length;return n=void 0===n?r:n,!t&&n>=r?e:Kr(e,t,n)}var fo=Jt||function(e){return Ke.clearTimeout(e)};function po(e,t){if(t)return e.slice();var n=e.length,r=ze?ze(n):new e.constructor(n);return e.copy(r),r}function ho(e){var t=new e.constructor(e.byteLength);return new De(t).set(new De(e)),t}function mo(e,t){var n=t?ho(e.buffer):e.buffer;return new e.constructor(n,e.byteOffset,e.length)}function go(e,t){if(e!==t){var n=void 0!==e,r=null===e,o=e==e,i=Zs(e),s=void 0!==t,a=null===t,c=t==t,u=Zs(t);if(!a&&!u&&!i&&e>t||i&&s&&c&&!a&&!u||r&&s&&c||!n&&c||!o)return 1;if(!r&&!i&&!u&&e<t||u&&n&&o&&!r&&!i||a&&n&&o||!s&&o||!c)return-1}return 0}function yo(e,t,n,o){for(var i=-1,s=e.length,a=n.length,c=-1,u=t.length,l=an(s-a,0),f=r(u+l),p=!o;++c<u;)f[c]=t[c];for(;++i<a;)(p||i<s)&&(f[n[i]]=e[i]);for(;l--;)f[c++]=e[i++];return f}function bo(e,t,n,o){for(var i=-1,s=e.length,a=-1,c=n.length,u=-1,l=t.length,f=an(s-c,0),p=r(f+l),d=!o;++i<f;)p[i]=e[i];for(var h=i;++u<l;)p[h+u]=t[u];for(;++a<c;)(d||i<s)&&(p[h+n[a]]=e[i++]);return p}function vo(e,t){var n=-1,o=e.length;for(t||(t=r(o));++n<o;)t[n]=e[n];return t}function So(e,t,n,r){var o=!n;n||(n={});for(var i=-1,s=t.length;++i<s;){var a=t[i],c=r?r(n[a],e[a],a,n,e):void 0;void 0===c&&(c=e[a]),o?Yn(n,a,c):Fn(n,a,c)}return n}function wo(e,t){return function(n,r){var o=js(n)?it:Kn,i=t?t():{};return o(n,e,Zo(r,2),i)}}function _o(e){return qr((function(t,n){var r=-1,o=n.length,i=o>1?n[o-1]:void 0,s=o>2?n[2]:void 0;for(i=e.length>3&&"function"==typeof i?(o--,i):void 0,s&&ui(n[0],n[1],s)&&(i=o<3?void 0:i,o=1),t=he(t);++r<o;){var a=n[r];a&&e(t,a,r,i)}return t}))}function Oo(e,t){return function(n,r){if(null==n)return n;if(!Ps(n))return e(n,r);for(var o=n.length,i=t?o:-1,s=he(n);(t?i--:++i<o)&&!1!==r(s[i],i,s););return n}}function To(e){return function(t,n,r){for(var o=-1,i=he(t),s=r(t),a=s.length;a--;){var c=s[e?a:++o];if(!1===n(i[c],c,i))break}return t}}function Co(e){return function(t){var n=qt(t=ca(t))?Kt(t):void 0,r=n?n[0]:t.charAt(0),o=n?lo(n,1).join(""):t.slice(1);return r[e]()+o}}function xo(e){return function(t){return ht(za(Ra(t).replace(ke,"")),e,"")}}function Eo(e){return function(){var t=arguments;switch(t.length){case 0:return new e;case 1:return new e(t[0]);case 2:return new e(t[0],t[1]);case 3:return new e(t[0],t[1],t[2]);case 4:return new e(t[0],t[1],t[2],t[3]);case 5:return new e(t[0],t[1],t[2],t[3],t[4]);case 6:return new e(t[0],t[1],t[2],t[3],t[4],t[5]);case 7:return new e(t[0],t[1],t[2],t[3],t[4],t[5],t[6])}var n=An(e.prototype),r=e.apply(n,t);return Fs(r)?r:n}}function No(e){return function(t,n,r){var o=he(t);if(!Ps(t)){var i=Zo(n,3);t=wa(t),n=function(e){return i(o[e],e,o)}}var s=e(t,n,r);return s>-1?o[i?t[s]:s]:void 0}}function Io(e){return Ko((function(t){var n=t.length,r=n,i=Mn.prototype.thru;for(e&&t.reverse();r--;){var s=t[r];if("function"!=typeof s)throw new ye(o);if(i&&!a&&"wrapper"==Jo(s))var a=new Mn([],!0)}for(r=a?r:n;++r<n;){var c=Jo(s=t[r]),u="wrapper"==c?Go(s):void 0;a=u&&fi(u[0])&&424==u[1]&&!u[4].length&&1==u[9]?a[Jo(u[0])].apply(a,u[3]):1==s.length&&fi(s)?a[c]():a.thru(s)}return function(){var e=arguments,r=e[0];if(a&&1==e.length&&js(r))return a.plant(r).value();for(var o=0,i=n?t[o].apply(this,e):r;++o<n;)i=t[o].call(this,i);return i}}))}function Ao(e,t,n,o,i,s,a,c,u,l){var f=128&t,p=1&t,d=2&t,h=24&t,m=512&t,g=d?void 0:Eo(e);return function y(){for(var b=arguments.length,v=r(b),S=b;S--;)v[S]=arguments[S];if(h)var w=Xo(y),_=Dt(v,w);if(o&&(v=yo(v,o,i,h)),s&&(v=bo(v,s,a,h)),b-=_,h&&b<l){var O=$t(v,w);return Bo(e,t,Ao,y.placeholder,n,v,O,c,u,l-b)}var T=p?n:this,C=d?T[e]:e;return b=v.length,c?v=bi(v,c):m&&b>1&&v.reverse(),f&&u<b&&(v.length=u),this&&this!==Ke&&this instanceof y&&(C=g||Eo(C)),C.apply(T,v)}}function ko(e,t){return function(n,r){return function(e,t,n,r){return ur(e,(function(e,o,i){t(r,n(e),o,i)})),r}(n,e,t(r),{})}}function Mo(e,t){return function(n,r){var o;if(void 0===n&&void 0===r)return t;if(void 0!==n&&(o=n),void 0!==r){if(void 0===o)return r;"string"==typeof n||"string"==typeof r?(n=Zr(n),r=Zr(r)):(n=Xr(n),r=Xr(r)),o=e(n,r)}return o}}function Ro(e){return Ko((function(t){return t=pt(t,At(Zo())),qr((function(n){var r=this;return e(t,(function(e){return ot(e,r,n)}))}))}))}function jo(e,t){var n=(t=void 0===t?" ":Zr(t)).length;if(n<2)return n?Lr(t,e):t;var r=Lr(t,Qt(e/Vt(t)));return qt(t)?lo(Kt(r),0,e).join(""):r.slice(0,e)}function Do(e){return function(t,n,o){return o&&"number"!=typeof o&&ui(t,n,o)&&(n=o=void 0),t=ra(t),void 0===n?(n=t,t=0):n=ra(n),function(e,t,n,o){for(var i=-1,s=an(Qt((t-e)/(n||1)),0),a=r(s);s--;)a[o?s:++i]=e,e+=n;return a}(t,n,o=void 0===o?t<n?1:-1:ra(o),e)}}function Po(e){return function(t,n){return"string"==typeof t&&"string"==typeof n||(t=sa(t),n=sa(n)),e(t,n)}}function Bo(e,t,n,r,o,i,s,a,c,u){var l=8&t;t|=l?32:64,4&(t&=~(l?64:32))||(t&=-4);var f=[e,t,o,l?i:void 0,l?s:void 0,l?void 0:i,l?void 0:s,a,c,u],p=n.apply(void 0,f);return fi(e)&&Si(p,f),p.placeholder=r,Oi(p,e,t)}function Lo(e){var t=de[e];return function(e,n){if(e=sa(e),(n=null==n?0:cn(oa(n),292))&&rn(e)){var r=(ca(e)+"e").split("e");return+((r=(ca(t(r[0]+"e"+(+r[1]+n)))+"e").split("e"))[0]+"e"+(+r[1]-n))}return t(e)}}var qo=gn&&1/Wt(new gn([,-0]))[1]==1/0?function(e){return new gn(e)}:Za;function Uo(e){return function(t){var n=oi(t);return n==h?Ut(t):n==b?Ft(t):function(e,t){return pt(t,(function(t){return[t,e[t]]}))}(t,e(t))}}function zo(e,t,n,s,a,c,u,l){var f=2&t;if(!f&&"function"!=typeof e)throw new ye(o);var p=s?s.length:0;if(p||(t&=-97,s=a=void 0),u=void 0===u?u:an(oa(u),0),l=void 0===l?l:oa(l),p-=a?a.length:0,64&t){var d=s,h=a;s=a=void 0}var m=f?void 0:Go(e),g=[e,t,n,s,a,d,h,c,u,l];if(m&&function(e,t){var n=e[1],r=t[1],o=n|r,s=o<131,a=128==r&&8==n||128==r&&256==n&&e[7].length<=t[8]||384==r&&t[7].length<=t[8]&&8==n;if(!s&&!a)return e;1&r&&(e[2]=t[2],o|=1&n?0:4);var c=t[3];if(c){var u=e[3];e[3]=u?yo(u,c,t[4]):c,e[4]=u?$t(e[3],i):t[4]}(c=t[5])&&(u=e[5],e[5]=u?bo(u,c,t[6]):c,e[6]=u?$t(e[5],i):t[6]);(c=t[7])&&(e[7]=c);128&r&&(e[8]=null==e[8]?t[8]:cn(e[8],t[8]));null==e[9]&&(e[9]=t[9]);e[0]=t[0],e[1]=o}(g,m),e=g[0],t=g[1],n=g[2],s=g[3],a=g[4],!(l=g[9]=void 0===g[9]?f?0:e.length:an(g[9]-p,0))&&24&t&&(t&=-25),t&&1!=t)y=8==t||16==t?function(e,t,n){var o=Eo(e);return function i(){for(var s=arguments.length,a=r(s),c=s,u=Xo(i);c--;)a[c]=arguments[c];var l=s<3&&a[0]!==u&&a[s-1]!==u?[]:$t(a,u);if((s-=l.length)<n)return Bo(e,t,Ao,i.placeholder,void 0,a,l,void 0,void 0,n-s);var f=this&&this!==Ke&&this instanceof i?o:e;return ot(f,this,a)}}(e,t,l):32!=t&&33!=t||a.length?Ao.apply(void 0,g):function(e,t,n,o){var i=1&t,s=Eo(e);return function t(){for(var a=-1,c=arguments.length,u=-1,l=o.length,f=r(l+c),p=this&&this!==Ke&&this instanceof t?s:e;++u<l;)f[u]=o[u];for(;c--;)f[u++]=arguments[++a];return ot(p,i?n:this,f)}}(e,t,n,s);else var y=function(e,t,n){var r=1&t,o=Eo(e);return function t(){var i=this&&this!==Ke&&this instanceof t?o:e;return i.apply(r?n:this,arguments)}}(e,t,n);return Oi((m?Wr:Si)(y,g),e,t)}function $o(e,t,n,r){return void 0===e||As(e,Se[n])&&!Oe.call(r,n)?t:e}function Wo(e,t,n,r,o,i){return Fs(e)&&Fs(t)&&(i.set(t,e),kr(e,t,void 0,Wo,i),i.delete(t)),e}function Fo(e){return Ys(e)?void 0:e}function Vo(e,t,n,r,o,i){var s=1&n,a=e.length,c=t.length;if(a!=c&&!(s&&c>a))return!1;var u=i.get(e),l=i.get(t);if(u&&l)return u==t&&l==e;var f=-1,p=!0,d=2&n?new Bn:void 0;for(i.set(e,t),i.set(t,e);++f<a;){var h=e[f],m=t[f];if(r)var g=s?r(m,h,f,t,e,i):r(h,m,f,e,t,i);if(void 0!==g){if(g)continue;p=!1;break}if(d){if(!gt(t,(function(e,t){if(!Mt(d,t)&&(h===e||o(h,e,n,r,i)))return d.push(t)}))){p=!1;break}}else if(h!==m&&!o(h,m,n,r,i)){p=!1;break}}return i.delete(e),i.delete(t),p}function Ko(e){return _i(gi(e,void 0,Di),e+"")}function Ho(e){return dr(e,wa,ni)}function Yo(e){return dr(e,_a,ri)}var Go=vn?function(e){return vn.get(e)}:Za;function Jo(e){for(var t=e.name+"",n=Sn[t],r=Oe.call(Sn,t)?n.length:0;r--;){var o=n[r],i=o.func;if(null==i||i==e)return o.name}return t}function Xo(e){return(Oe.call(In,"placeholder")?In:e).placeholder}function Zo(){var e=In.iteratee||Ya;return e=e===Ya?Tr:e,arguments.length?e(arguments[0],arguments[1]):e}function Qo(e,t){var n,r,o=e.__data__;return("string"==(r=typeof(n=t))||"number"==r||"symbol"==r||"boolean"==r?"__proto__"!==n:null===n)?o["string"==typeof t?"string":"hash"]:o.map}function ei(e){for(var t=wa(e),n=t.length;n--;){var r=t[n],o=e[r];t[n]=[r,o,hi(o)]}return t}function ti(e,t){var n=function(e,t){return null==e?void 0:e[t]}(e,t);return Or(n)?n:void 0}var ni=tn?function(e){return null==e?[]:(e=he(e),ut(tn(e),(function(t){return He.call(e,t)})))}:ic,ri=tn?function(e){for(var t=[];e;)dt(t,ni(e)),e=Fe(e);return t}:ic,oi=hr;function ii(e,t,n){for(var r=-1,o=(t=co(t,e)).length,i=!1;++r<o;){var s=Ei(t[r]);if(!(i=null!=e&&n(e,s)))break;e=e[s]}return i||++r!=o?i:!!(o=null==e?0:e.length)&&Ws(o)&&ci(s,o)&&(js(e)||Rs(e))}function si(e){return"function"!=typeof e.constructor||di(e)?{}:An(Fe(e))}function ai(e){return js(e)||Rs(e)||!!(Je&&e&&e[Je])}function ci(e,t){var n=typeof e;return!!(t=null==t?9007199254740991:t)&&("number"==n||"symbol"!=n&&ae.test(e))&&e>-1&&e%1==0&&e<t}function ui(e,t,n){if(!Fs(n))return!1;var r=typeof t;return!!("number"==r?Ps(n)&&ci(t,n.length):"string"==r&&t in n)&&As(n[t],e)}function li(e,t){if(js(e))return!1;var n=typeof e;return!("number"!=n&&"symbol"!=n&&"boolean"!=n&&null!=e&&!Zs(e))||(W.test(e)||!$.test(e)||null!=t&&e in he(t))}function fi(e){var t=Jo(e),n=In[t];if("function"!=typeof n||!(t in Rn.prototype))return!1;if(e===n)return!0;var r=Go(n);return!!r&&e===r[0]}(dn&&oi(new dn(new ArrayBuffer(1)))!=O||hn&&oi(new hn)!=h||mn&&"[object Promise]"!=oi(mn.resolve())||gn&&oi(new gn)!=b||yn&&oi(new yn)!=w)&&(oi=function(e){var t=hr(e),n=t==g?e.constructor:void 0,r=n?Ni(n):"";if(r)switch(r){case wn:return O;case _n:return h;case On:return"[object Promise]";case Tn:return b;case Cn:return w}return t});var pi=we?zs:sc;function di(e){var t=e&&e.constructor;return e===("function"==typeof t&&t.prototype||Se)}function hi(e){return e==e&&!Fs(e)}function mi(e,t){return function(n){return null!=n&&(n[e]===t&&(void 0!==t||e in he(n)))}}function gi(e,t,n){return t=an(void 0===t?e.length-1:t,0),function(){for(var o=arguments,i=-1,s=an(o.length-t,0),a=r(s);++i<s;)a[i]=o[t+i];i=-1;for(var c=r(t+1);++i<t;)c[i]=o[i];return c[t]=n(a),ot(e,this,c)}}function yi(e,t){return t.length<2?e:pr(e,Kr(t,0,-1))}function bi(e,t){for(var n=e.length,r=cn(t.length,n),o=vo(e);r--;){var i=t[r];e[r]=ci(i,n)?o[i]:void 0}return e}function vi(e,t){if(("constructor"!==t||"function"!=typeof e[t])&&"__proto__"!=t)return e[t]}var Si=Ti(Wr),wi=Zt||function(e,t){return Ke.setTimeout(e,t)},_i=Ti(Fr);function Oi(e,t,n){var r=t+"";return _i(e,function(e,t){var n=t.length;if(!n)return e;var r=n-1;return t[r]=(n>1?"& ":"")+t[r],t=t.join(n>2?", ":" "),e.replace(G,"{\n/* [wrapped with "+t+"] */\n")}(r,function(e,t){return st(s,(function(n){var r="_."+n[0];t&n[1]&&!lt(e,r)&&e.push(r)})),e.sort()}(function(e){var t=e.match(J);return t?t[1].split(X):[]}(r),n)))}function Ti(e){var t=0,n=0;return function(){var r=un(),o=16-(r-n);if(n=r,o>0){if(++t>=800)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}function Ci(e,t){var n=-1,r=e.length,o=r-1;for(t=void 0===t?r:t;++n<t;){var i=Br(n,o),s=e[i];e[i]=e[n],e[n]=s}return e.length=t,e}var xi=function(e){var t=Ts(e,(function(e){return 500===n.size&&n.clear(),e})),n=t.cache;return t}((function(e){var t=[];return 46===e.charCodeAt(0)&&t.push(""),e.replace(F,(function(e,n,r,o){t.push(r?o.replace(ee,"$1"):n||e)})),t}));function Ei(e){if("string"==typeof e||Zs(e))return e;var t=e+"";return"0"==t&&1/e==-1/0?"-0":t}function Ni(e){if(null!=e){try{return _e.call(e)}catch(e){}try{return e+""}catch(e){}}return""}function Ii(e){if(e instanceof Rn)return e.clone();var t=new Mn(e.__wrapped__,e.__chain__);return t.__actions__=vo(e.__actions__),t.__index__=e.__index__,t.__values__=e.__values__,t}var Ai=qr((function(e,t){return Bs(e)?er(e,sr(t,1,Bs,!0)):[]})),ki=qr((function(e,t){var n=Ui(t);return Bs(n)&&(n=void 0),Bs(e)?er(e,sr(t,1,Bs,!0),Zo(n,2)):[]})),Mi=qr((function(e,t){var n=Ui(t);return Bs(n)&&(n=void 0),Bs(e)?er(e,sr(t,1,Bs,!0),void 0,n):[]}));function Ri(e,t,n){var r=null==e?0:e.length;if(!r)return-1;var o=null==n?0:oa(n);return o<0&&(o=an(r+o,0)),vt(e,Zo(t,3),o)}function ji(e,t,n){var r=null==e?0:e.length;if(!r)return-1;var o=r-1;return void 0!==n&&(o=oa(n),o=n<0?an(r+o,0):cn(o,r-1)),vt(e,Zo(t,3),o,!0)}function Di(e){return(null==e?0:e.length)?sr(e,1):[]}function Pi(e){return e&&e.length?e[0]:void 0}var Bi=qr((function(e){var t=pt(e,so);return t.length&&t[0]===e[0]?br(t):[]})),Li=qr((function(e){var t=Ui(e),n=pt(e,so);return t===Ui(n)?t=void 0:n.pop(),n.length&&n[0]===e[0]?br(n,Zo(t,2)):[]})),qi=qr((function(e){var t=Ui(e),n=pt(e,so);return(t="function"==typeof t?t:void 0)&&n.pop(),n.length&&n[0]===e[0]?br(n,void 0,t):[]}));function Ui(e){var t=null==e?0:e.length;return t?e[t-1]:void 0}var zi=qr($i);function $i(e,t){return e&&e.length&&t&&t.length?Dr(e,t):e}var Wi=Ko((function(e,t){var n=null==e?0:e.length,r=Gn(e,t);return Pr(e,pt(t,(function(e){return ci(e,n)?+e:e})).sort(go)),r}));function Fi(e){return null==e?e:pn.call(e)}var Vi=qr((function(e){return Qr(sr(e,1,Bs,!0))})),Ki=qr((function(e){var t=Ui(e);return Bs(t)&&(t=void 0),Qr(sr(e,1,Bs,!0),Zo(t,2))})),Hi=qr((function(e){var t=Ui(e);return t="function"==typeof t?t:void 0,Qr(sr(e,1,Bs,!0),void 0,t)}));function Yi(e){if(!e||!e.length)return[];var t=0;return e=ut(e,(function(e){if(Bs(e))return t=an(e.length,t),!0})),Nt(t,(function(t){return pt(e,Tt(t))}))}function Gi(e,t){if(!e||!e.length)return[];var n=Yi(e);return null==t?n:pt(n,(function(e){return ot(t,void 0,e)}))}var Ji=qr((function(e,t){return Bs(e)?er(e,t):[]})),Xi=qr((function(e){return oo(ut(e,Bs))})),Zi=qr((function(e){var t=Ui(e);return Bs(t)&&(t=void 0),oo(ut(e,Bs),Zo(t,2))})),Qi=qr((function(e){var t=Ui(e);return t="function"==typeof t?t:void 0,oo(ut(e,Bs),void 0,t)})),es=qr(Yi);var ts=qr((function(e){var t=e.length,n=t>1?e[t-1]:void 0;return n="function"==typeof n?(e.pop(),n):void 0,Gi(e,n)}));function ns(e){var t=In(e);return t.__chain__=!0,t}function rs(e,t){return t(e)}var os=Ko((function(e){var t=e.length,n=t?e[0]:0,r=this.__wrapped__,o=function(t){return Gn(t,e)};return!(t>1||this.__actions__.length)&&r instanceof Rn&&ci(n)?((r=r.slice(n,+n+(t?1:0))).__actions__.push({func:rs,args:[o],thisArg:void 0}),new Mn(r,this.__chain__).thru((function(e){return t&&!e.length&&e.push(void 0),e}))):this.thru(o)}));var is=wo((function(e,t,n){Oe.call(e,n)?++e[n]:Yn(e,n,1)}));var ss=No(Ri),as=No(ji);function cs(e,t){return(js(e)?st:tr)(e,Zo(t,3))}function us(e,t){return(js(e)?at:nr)(e,Zo(t,3))}var ls=wo((function(e,t,n){Oe.call(e,n)?e[n].push(t):Yn(e,n,[t])}));var fs=qr((function(e,t,n){var o=-1,i="function"==typeof t,s=Ps(e)?r(e.length):[];return tr(e,(function(e){s[++o]=i?ot(t,e,n):vr(e,t,n)})),s})),ps=wo((function(e,t,n){Yn(e,n,t)}));function ds(e,t){return(js(e)?pt:Nr)(e,Zo(t,3))}var hs=wo((function(e,t,n){e[n?0:1].push(t)}),(function(){return[[],[]]}));var ms=qr((function(e,t){if(null==e)return[];var n=t.length;return n>1&&ui(e,t[0],t[1])?t=[]:n>2&&ui(t[0],t[1],t[2])&&(t=[t[0]]),Rr(e,sr(t,1),[])})),gs=Xt||function(){return Ke.Date.now()};function ys(e,t,n){return t=n?void 0:t,zo(e,128,void 0,void 0,void 0,void 0,t=e&&null==t?e.length:t)}function bs(e,t){var n;if("function"!=typeof t)throw new ye(o);return e=oa(e),function(){return--e>0&&(n=t.apply(this,arguments)),e<=1&&(t=void 0),n}}var vs=qr((function(e,t,n){var r=1;if(n.length){var o=$t(n,Xo(vs));r|=32}return zo(e,r,t,n,o)})),Ss=qr((function(e,t,n){var r=3;if(n.length){var o=$t(n,Xo(Ss));r|=32}return zo(t,r,e,n,o)}));function ws(e,t,n){var r,i,s,a,c,u,l=0,f=!1,p=!1,d=!0;if("function"!=typeof e)throw new ye(o);function h(t){var n=r,o=i;return r=i=void 0,l=t,a=e.apply(o,n)}function m(e){return l=e,c=wi(y,t),f?h(e):a}function g(e){var n=e-u;return void 0===u||n>=t||n<0||p&&e-l>=s}function y(){var e=gs();if(g(e))return b(e);c=wi(y,function(e){var n=t-(e-u);return p?cn(n,s-(e-l)):n}(e))}function b(e){return c=void 0,d&&r?h(e):(r=i=void 0,a)}function v(){var e=gs(),n=g(e);if(r=arguments,i=this,u=e,n){if(void 0===c)return m(u);if(p)return fo(c),c=wi(y,t),h(u)}return void 0===c&&(c=wi(y,t)),a}return t=sa(t)||0,Fs(n)&&(f=!!n.leading,s=(p="maxWait"in n)?an(sa(n.maxWait)||0,t):s,d="trailing"in n?!!n.trailing:d),v.cancel=function(){void 0!==c&&fo(c),l=0,r=u=i=c=void 0},v.flush=function(){return void 0===c?a:b(gs())},v}var _s=qr((function(e,t){return Qn(e,1,t)})),Os=qr((function(e,t,n){return Qn(e,sa(t)||0,n)}));function Ts(e,t){if("function"!=typeof e||null!=t&&"function"!=typeof t)throw new ye(o);var n=function(){var r=arguments,o=t?t.apply(this,r):r[0],i=n.cache;if(i.has(o))return i.get(o);var s=e.apply(this,r);return n.cache=i.set(o,s)||i,s};return n.cache=new(Ts.Cache||Pn),n}function Cs(e){if("function"!=typeof e)throw new ye(o);return function(){var t=arguments;switch(t.length){case 0:return!e.call(this);case 1:return!e.call(this,t[0]);case 2:return!e.call(this,t[0],t[1]);case 3:return!e.call(this,t[0],t[1],t[2])}return!e.apply(this,t)}}Ts.Cache=Pn;var xs=uo((function(e,t){var n=(t=1==t.length&&js(t[0])?pt(t[0],At(Zo())):pt(sr(t,1),At(Zo()))).length;return qr((function(r){for(var o=-1,i=cn(r.length,n);++o<i;)r[o]=t[o].call(this,r[o]);return ot(e,this,r)}))})),Es=qr((function(e,t){return zo(e,32,void 0,t,$t(t,Xo(Es)))})),Ns=qr((function(e,t){return zo(e,64,void 0,t,$t(t,Xo(Ns)))})),Is=Ko((function(e,t){return zo(e,256,void 0,void 0,void 0,t)}));function As(e,t){return e===t||e!=e&&t!=t}var ks=Po(mr),Ms=Po((function(e,t){return e>=t})),Rs=Sr(function(){return arguments}())?Sr:function(e){return Vs(e)&&Oe.call(e,"callee")&&!He.call(e,"callee")},js=r.isArray,Ds=Ze?At(Ze):function(e){return Vs(e)&&hr(e)==_};function Ps(e){return null!=e&&Ws(e.length)&&!zs(e)}function Bs(e){return Vs(e)&&Ps(e)}var Ls=nn||sc,qs=Qe?At(Qe):function(e){return Vs(e)&&hr(e)==l};function Us(e){if(!Vs(e))return!1;var t=hr(e);return t==f||"[object DOMException]"==t||"string"==typeof e.message&&"string"==typeof e.name&&!Ys(e)}function zs(e){if(!Fs(e))return!1;var t=hr(e);return t==p||t==d||"[object AsyncFunction]"==t||"[object Proxy]"==t}function $s(e){return"number"==typeof e&&e==oa(e)}function Ws(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=9007199254740991}function Fs(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}function Vs(e){return null!=e&&"object"==typeof e}var Ks=et?At(et):function(e){return Vs(e)&&oi(e)==h};function Hs(e){return"number"==typeof e||Vs(e)&&hr(e)==m}function Ys(e){if(!Vs(e)||hr(e)!=g)return!1;var t=Fe(e);if(null===t)return!0;var n=Oe.call(t,"constructor")&&t.constructor;return"function"==typeof n&&n instanceof n&&_e.call(n)==Ee}var Gs=tt?At(tt):function(e){return Vs(e)&&hr(e)==y};var Js=nt?At(nt):function(e){return Vs(e)&&oi(e)==b};function Xs(e){return"string"==typeof e||!js(e)&&Vs(e)&&hr(e)==v}function Zs(e){return"symbol"==typeof e||Vs(e)&&hr(e)==S}var Qs=rt?At(rt):function(e){return Vs(e)&&Ws(e.length)&&!!qe[hr(e)]};var ea=Po(Er),ta=Po((function(e,t){return e<=t}));function na(e){if(!e)return[];if(Ps(e))return Xs(e)?Kt(e):vo(e);if(Xe&&e[Xe])return function(e){for(var t,n=[];!(t=e.next()).done;)n.push(t.value);return n}(e[Xe]());var t=oi(e);return(t==h?Ut:t==b?Wt:Aa)(e)}function ra(e){return e?(e=sa(e))===1/0||e===-1/0?17976931348623157e292*(e<0?-1:1):e==e?e:0:0===e?e:0}function oa(e){var t=ra(e),n=t%1;return t==t?n?t-n:t:0}function ia(e){return e?Jn(oa(e),0,4294967295):0}function sa(e){if("number"==typeof e)return e;if(Zs(e))return NaN;if(Fs(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=Fs(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=It(e);var n=oe.test(e);return n||se.test(e)?We(e.slice(2),n?2:8):re.test(e)?NaN:+e}function aa(e){return So(e,_a(e))}function ca(e){return null==e?"":Zr(e)}var ua=_o((function(e,t){if(di(t)||Ps(t))So(t,wa(t),e);else for(var n in t)Oe.call(t,n)&&Fn(e,n,t[n])})),la=_o((function(e,t){So(t,_a(t),e)})),fa=_o((function(e,t,n,r){So(t,_a(t),e,r)})),pa=_o((function(e,t,n,r){So(t,wa(t),e,r)})),da=Ko(Gn);var ha=qr((function(e,t){e=he(e);var n=-1,r=t.length,o=r>2?t[2]:void 0;for(o&&ui(t[0],t[1],o)&&(r=1);++n<r;)for(var i=t[n],s=_a(i),a=-1,c=s.length;++a<c;){var u=s[a],l=e[u];(void 0===l||As(l,Se[u])&&!Oe.call(e,u))&&(e[u]=i[u])}return e})),ma=qr((function(e){return e.push(void 0,Wo),ot(Ta,void 0,e)}));function ga(e,t,n){var r=null==e?void 0:pr(e,t);return void 0===r?n:r}function ya(e,t){return null!=e&&ii(e,t,yr)}var ba=ko((function(e,t,n){null!=t&&"function"!=typeof t.toString&&(t=xe.call(t)),e[t]=n}),Fa(Ha)),va=ko((function(e,t,n){null!=t&&"function"!=typeof t.toString&&(t=xe.call(t)),Oe.call(e,t)?e[t].push(n):e[t]=[n]}),Zo),Sa=qr(vr);function wa(e){return Ps(e)?qn(e):Cr(e)}function _a(e){return Ps(e)?qn(e,!0):xr(e)}var Oa=_o((function(e,t,n){kr(e,t,n)})),Ta=_o((function(e,t,n,r){kr(e,t,n,r)})),Ca=Ko((function(e,t){var n={};if(null==e)return n;var r=!1;t=pt(t,(function(t){return t=co(t,e),r||(r=t.length>1),t})),So(e,Yo(e),n),r&&(n=Xn(n,7,Fo));for(var o=t.length;o--;)eo(n,t[o]);return n}));var xa=Ko((function(e,t){return null==e?{}:function(e,t){return jr(e,t,(function(t,n){return ya(e,n)}))}(e,t)}));function Ea(e,t){if(null==e)return{};var n=pt(Yo(e),(function(e){return[e]}));return t=Zo(t),jr(e,n,(function(e,n){return t(e,n[0])}))}var Na=Uo(wa),Ia=Uo(_a);function Aa(e){return null==e?[]:kt(e,wa(e))}var ka=xo((function(e,t,n){return t=t.toLowerCase(),e+(n?Ma(t):t)}));function Ma(e){return Ua(ca(e).toLowerCase())}function Ra(e){return(e=ca(e))&&e.replace(ce,Pt).replace(Me,"")}var ja=xo((function(e,t,n){return e+(n?"-":"")+t.toLowerCase()})),Da=xo((function(e,t,n){return e+(n?" ":"")+t.toLowerCase()})),Pa=Co("toLowerCase");var Ba=xo((function(e,t,n){return e+(n?"_":"")+t.toLowerCase()}));var La=xo((function(e,t,n){return e+(n?" ":"")+Ua(t)}));var qa=xo((function(e,t,n){return e+(n?" ":"")+t.toUpperCase()})),Ua=Co("toUpperCase");function za(e,t,n){return e=ca(e),void 0===(t=n?void 0:t)?function(e){return Pe.test(e)}(e)?function(e){return e.match(je)||[]}(e):function(e){return e.match(Z)||[]}(e):e.match(t)||[]}var $a=qr((function(e,t){try{return ot(e,void 0,t)}catch(e){return Us(e)?e:new fe(e)}})),Wa=Ko((function(e,t){return st(t,(function(t){t=Ei(t),Yn(e,t,vs(e[t],e))})),e}));function Fa(e){return function(){return e}}var Va=Io(),Ka=Io(!0);function Ha(e){return e}function Ya(e){return Tr("function"==typeof e?e:Xn(e,1))}var Ga=qr((function(e,t){return function(n){return vr(n,e,t)}})),Ja=qr((function(e,t){return function(n){return vr(e,n,t)}}));function Xa(e,t,n){var r=wa(t),o=fr(t,r);null!=n||Fs(t)&&(o.length||!r.length)||(n=t,t=e,e=this,o=fr(t,wa(t)));var i=!(Fs(n)&&"chain"in n&&!n.chain),s=zs(e);return st(o,(function(n){var r=t[n];e[n]=r,s&&(e.prototype[n]=function(){var t=this.__chain__;if(i||t){var n=e(this.__wrapped__),o=n.__actions__=vo(this.__actions__);return o.push({func:r,args:arguments,thisArg:e}),n.__chain__=t,n}return r.apply(e,dt([this.value()],arguments))})})),e}function Za(){}var Qa=Ro(pt),ec=Ro(ct),tc=Ro(gt);function nc(e){return li(e)?Tt(Ei(e)):function(e){return function(t){return pr(t,e)}}(e)}var rc=Do(),oc=Do(!0);function ic(){return[]}function sc(){return!1}var ac=Mo((function(e,t){return e+t}),0),cc=Lo("ceil"),uc=Mo((function(e,t){return e/t}),1),lc=Lo("floor");var fc,pc=Mo((function(e,t){return e*t}),1),dc=Lo("round"),hc=Mo((function(e,t){return e-t}),0);return In.after=function(e,t){if("function"!=typeof t)throw new ye(o);return e=oa(e),function(){if(--e<1)return t.apply(this,arguments)}},In.ary=ys,In.assign=ua,In.assignIn=la,In.assignInWith=fa,In.assignWith=pa,In.at=da,In.before=bs,In.bind=vs,In.bindAll=Wa,In.bindKey=Ss,In.castArray=function(){if(!arguments.length)return[];var e=arguments[0];return js(e)?e:[e]},In.chain=ns,In.chunk=function(e,t,n){t=(n?ui(e,t,n):void 0===t)?1:an(oa(t),0);var o=null==e?0:e.length;if(!o||t<1)return[];for(var i=0,s=0,a=r(Qt(o/t));i<o;)a[s++]=Kr(e,i,i+=t);return a},In.compact=function(e){for(var t=-1,n=null==e?0:e.length,r=0,o=[];++t<n;){var i=e[t];i&&(o[r++]=i)}return o},In.concat=function(){var e=arguments.length;if(!e)return[];for(var t=r(e-1),n=arguments[0],o=e;o--;)t[o-1]=arguments[o];return dt(js(n)?vo(n):[n],sr(t,1))},In.cond=function(e){var t=null==e?0:e.length,n=Zo();return e=t?pt(e,(function(e){if("function"!=typeof e[1])throw new ye(o);return[n(e[0]),e[1]]})):[],qr((function(n){for(var r=-1;++r<t;){var o=e[r];if(ot(o[0],this,n))return ot(o[1],this,n)}}))},In.conforms=function(e){return function(e){var t=wa(e);return function(n){return Zn(n,e,t)}}(Xn(e,1))},In.constant=Fa,In.countBy=is,In.create=function(e,t){var n=An(e);return null==t?n:Hn(n,t)},In.curry=function e(t,n,r){var o=zo(t,8,void 0,void 0,void 0,void 0,void 0,n=r?void 0:n);return o.placeholder=e.placeholder,o},In.curryRight=function e(t,n,r){var o=zo(t,16,void 0,void 0,void 0,void 0,void 0,n=r?void 0:n);return o.placeholder=e.placeholder,o},In.debounce=ws,In.defaults=ha,In.defaultsDeep=ma,In.defer=_s,In.delay=Os,In.difference=Ai,In.differenceBy=ki,In.differenceWith=Mi,In.drop=function(e,t,n){var r=null==e?0:e.length;return r?Kr(e,(t=n||void 0===t?1:oa(t))<0?0:t,r):[]},In.dropRight=function(e,t,n){var r=null==e?0:e.length;return r?Kr(e,0,(t=r-(t=n||void 0===t?1:oa(t)))<0?0:t):[]},In.dropRightWhile=function(e,t){return e&&e.length?no(e,Zo(t,3),!0,!0):[]},In.dropWhile=function(e,t){return e&&e.length?no(e,Zo(t,3),!0):[]},In.fill=function(e,t,n,r){var o=null==e?0:e.length;return o?(n&&"number"!=typeof n&&ui(e,t,n)&&(n=0,r=o),function(e,t,n,r){var o=e.length;for((n=oa(n))<0&&(n=-n>o?0:o+n),(r=void 0===r||r>o?o:oa(r))<0&&(r+=o),r=n>r?0:ia(r);n<r;)e[n++]=t;return e}(e,t,n,r)):[]},In.filter=function(e,t){return(js(e)?ut:ir)(e,Zo(t,3))},In.flatMap=function(e,t){return sr(ds(e,t),1)},In.flatMapDeep=function(e,t){return sr(ds(e,t),1/0)},In.flatMapDepth=function(e,t,n){return n=void 0===n?1:oa(n),sr(ds(e,t),n)},In.flatten=Di,In.flattenDeep=function(e){return(null==e?0:e.length)?sr(e,1/0):[]},In.flattenDepth=function(e,t){return(null==e?0:e.length)?sr(e,t=void 0===t?1:oa(t)):[]},In.flip=function(e){return zo(e,512)},In.flow=Va,In.flowRight=Ka,In.fromPairs=function(e){for(var t=-1,n=null==e?0:e.length,r={};++t<n;){var o=e[t];r[o[0]]=o[1]}return r},In.functions=function(e){return null==e?[]:fr(e,wa(e))},In.functionsIn=function(e){return null==e?[]:fr(e,_a(e))},In.groupBy=ls,In.initial=function(e){return(null==e?0:e.length)?Kr(e,0,-1):[]},In.intersection=Bi,In.intersectionBy=Li,In.intersectionWith=qi,In.invert=ba,In.invertBy=va,In.invokeMap=fs,In.iteratee=Ya,In.keyBy=ps,In.keys=wa,In.keysIn=_a,In.map=ds,In.mapKeys=function(e,t){var n={};return t=Zo(t,3),ur(e,(function(e,r,o){Yn(n,t(e,r,o),e)})),n},In.mapValues=function(e,t){var n={};return t=Zo(t,3),ur(e,(function(e,r,o){Yn(n,r,t(e,r,o))})),n},In.matches=function(e){return Ir(Xn(e,1))},In.matchesProperty=function(e,t){return Ar(e,Xn(t,1))},In.memoize=Ts,In.merge=Oa,In.mergeWith=Ta,In.method=Ga,In.methodOf=Ja,In.mixin=Xa,In.negate=Cs,In.nthArg=function(e){return e=oa(e),qr((function(t){return Mr(t,e)}))},In.omit=Ca,In.omitBy=function(e,t){return Ea(e,Cs(Zo(t)))},In.once=function(e){return bs(2,e)},In.orderBy=function(e,t,n,r){return null==e?[]:(js(t)||(t=null==t?[]:[t]),js(n=r?void 0:n)||(n=null==n?[]:[n]),Rr(e,t,n))},In.over=Qa,In.overArgs=xs,In.overEvery=ec,In.overSome=tc,In.partial=Es,In.partialRight=Ns,In.partition=hs,In.pick=xa,In.pickBy=Ea,In.property=nc,In.propertyOf=function(e){return function(t){return null==e?void 0:pr(e,t)}},In.pull=zi,In.pullAll=$i,In.pullAllBy=function(e,t,n){return e&&e.length&&t&&t.length?Dr(e,t,Zo(n,2)):e},In.pullAllWith=function(e,t,n){return e&&e.length&&t&&t.length?Dr(e,t,void 0,n):e},In.pullAt=Wi,In.range=rc,In.rangeRight=oc,In.rearg=Is,In.reject=function(e,t){return(js(e)?ut:ir)(e,Cs(Zo(t,3)))},In.remove=function(e,t){var n=[];if(!e||!e.length)return n;var r=-1,o=[],i=e.length;for(t=Zo(t,3);++r<i;){var s=e[r];t(s,r,e)&&(n.push(s),o.push(r))}return Pr(e,o),n},In.rest=function(e,t){if("function"!=typeof e)throw new ye(o);return qr(e,t=void 0===t?t:oa(t))},In.reverse=Fi,In.sampleSize=function(e,t,n){return t=(n?ui(e,t,n):void 0===t)?1:oa(t),(js(e)?zn:zr)(e,t)},In.set=function(e,t,n){return null==e?e:$r(e,t,n)},In.setWith=function(e,t,n,r){return r="function"==typeof r?r:void 0,null==e?e:$r(e,t,n,r)},In.shuffle=function(e){return(js(e)?$n:Vr)(e)},In.slice=function(e,t,n){var r=null==e?0:e.length;return r?(n&&"number"!=typeof n&&ui(e,t,n)?(t=0,n=r):(t=null==t?0:oa(t),n=void 0===n?r:oa(n)),Kr(e,t,n)):[]},In.sortBy=ms,In.sortedUniq=function(e){return e&&e.length?Jr(e):[]},In.sortedUniqBy=function(e,t){return e&&e.length?Jr(e,Zo(t,2)):[]},In.split=function(e,t,n){return n&&"number"!=typeof n&&ui(e,t,n)&&(t=n=void 0),(n=void 0===n?4294967295:n>>>0)?(e=ca(e))&&("string"==typeof t||null!=t&&!Gs(t))&&!(t=Zr(t))&&qt(e)?lo(Kt(e),0,n):e.split(t,n):[]},In.spread=function(e,t){if("function"!=typeof e)throw new ye(o);return t=null==t?0:an(oa(t),0),qr((function(n){var r=n[t],o=lo(n,0,t);return r&&dt(o,r),ot(e,this,o)}))},In.tail=function(e){var t=null==e?0:e.length;return t?Kr(e,1,t):[]},In.take=function(e,t,n){return e&&e.length?Kr(e,0,(t=n||void 0===t?1:oa(t))<0?0:t):[]},In.takeRight=function(e,t,n){var r=null==e?0:e.length;return r?Kr(e,(t=r-(t=n||void 0===t?1:oa(t)))<0?0:t,r):[]},In.takeRightWhile=function(e,t){return e&&e.length?no(e,Zo(t,3),!1,!0):[]},In.takeWhile=function(e,t){return e&&e.length?no(e,Zo(t,3)):[]},In.tap=function(e,t){return t(e),e},In.throttle=function(e,t,n){var r=!0,i=!0;if("function"!=typeof e)throw new ye(o);return Fs(n)&&(r="leading"in n?!!n.leading:r,i="trailing"in n?!!n.trailing:i),ws(e,t,{leading:r,maxWait:t,trailing:i})},In.thru=rs,In.toArray=na,In.toPairs=Na,In.toPairsIn=Ia,In.toPath=function(e){return js(e)?pt(e,Ei):Zs(e)?[e]:vo(xi(ca(e)))},In.toPlainObject=aa,In.transform=function(e,t,n){var r=js(e),o=r||Ls(e)||Qs(e);if(t=Zo(t,4),null==n){var i=e&&e.constructor;n=o?r?new i:[]:Fs(e)&&zs(i)?An(Fe(e)):{}}return(o?st:ur)(e,(function(e,r,o){return t(n,e,r,o)})),n},In.unary=function(e){return ys(e,1)},In.union=Vi,In.unionBy=Ki,In.unionWith=Hi,In.uniq=function(e){return e&&e.length?Qr(e):[]},In.uniqBy=function(e,t){return e&&e.length?Qr(e,Zo(t,2)):[]},In.uniqWith=function(e,t){return t="function"==typeof t?t:void 0,e&&e.length?Qr(e,void 0,t):[]},In.unset=function(e,t){return null==e||eo(e,t)},In.unzip=Yi,In.unzipWith=Gi,In.update=function(e,t,n){return null==e?e:to(e,t,ao(n))},In.updateWith=function(e,t,n,r){return r="function"==typeof r?r:void 0,null==e?e:to(e,t,ao(n),r)},In.values=Aa,In.valuesIn=function(e){return null==e?[]:kt(e,_a(e))},In.without=Ji,In.words=za,In.wrap=function(e,t){return Es(ao(t),e)},In.xor=Xi,In.xorBy=Zi,In.xorWith=Qi,In.zip=es,In.zipObject=function(e,t){return io(e||[],t||[],Fn)},In.zipObjectDeep=function(e,t){return io(e||[],t||[],$r)},In.zipWith=ts,In.entries=Na,In.entriesIn=Ia,In.extend=la,In.extendWith=fa,Xa(In,In),In.add=ac,In.attempt=$a,In.camelCase=ka,In.capitalize=Ma,In.ceil=cc,In.clamp=function(e,t,n){return void 0===n&&(n=t,t=void 0),void 0!==n&&(n=(n=sa(n))==n?n:0),void 0!==t&&(t=(t=sa(t))==t?t:0),Jn(sa(e),t,n)},In.clone=function(e){return Xn(e,4)},In.cloneDeep=function(e){return Xn(e,5)},In.cloneDeepWith=function(e,t){return Xn(e,5,t="function"==typeof t?t:void 0)},In.cloneWith=function(e,t){return Xn(e,4,t="function"==typeof t?t:void 0)},In.conformsTo=function(e,t){return null==t||Zn(e,t,wa(t))},In.deburr=Ra,In.defaultTo=function(e,t){return null==e||e!=e?t:e},In.divide=uc,In.endsWith=function(e,t,n){e=ca(e),t=Zr(t);var r=e.length,o=n=void 0===n?r:Jn(oa(n),0,r);return(n-=t.length)>=0&&e.slice(n,o)==t},In.eq=As,In.escape=function(e){return(e=ca(e))&&L.test(e)?e.replace(P,Bt):e},In.escapeRegExp=function(e){return(e=ca(e))&&K.test(e)?e.replace(V,"\\$&"):e},In.every=function(e,t,n){var r=js(e)?ct:rr;return n&&ui(e,t,n)&&(t=void 0),r(e,Zo(t,3))},In.find=ss,In.findIndex=Ri,In.findKey=function(e,t){return bt(e,Zo(t,3),ur)},In.findLast=as,In.findLastIndex=ji,In.findLastKey=function(e,t){return bt(e,Zo(t,3),lr)},In.floor=lc,In.forEach=cs,In.forEachRight=us,In.forIn=function(e,t){return null==e?e:ar(e,Zo(t,3),_a)},In.forInRight=function(e,t){return null==e?e:cr(e,Zo(t,3),_a)},In.forOwn=function(e,t){return e&&ur(e,Zo(t,3))},In.forOwnRight=function(e,t){return e&&lr(e,Zo(t,3))},In.get=ga,In.gt=ks,In.gte=Ms,In.has=function(e,t){return null!=e&&ii(e,t,gr)},In.hasIn=ya,In.head=Pi,In.identity=Ha,In.includes=function(e,t,n,r){e=Ps(e)?e:Aa(e),n=n&&!r?oa(n):0;var o=e.length;return n<0&&(n=an(o+n,0)),Xs(e)?n<=o&&e.indexOf(t,n)>-1:!!o&&St(e,t,n)>-1},In.indexOf=function(e,t,n){var r=null==e?0:e.length;if(!r)return-1;var o=null==n?0:oa(n);return o<0&&(o=an(r+o,0)),St(e,t,o)},In.inRange=function(e,t,n){return t=ra(t),void 0===n?(n=t,t=0):n=ra(n),function(e,t,n){return e>=cn(t,n)&&e<an(t,n)}(e=sa(e),t,n)},In.invoke=Sa,In.isArguments=Rs,In.isArray=js,In.isArrayBuffer=Ds,In.isArrayLike=Ps,In.isArrayLikeObject=Bs,In.isBoolean=function(e){return!0===e||!1===e||Vs(e)&&hr(e)==u},In.isBuffer=Ls,In.isDate=qs,In.isElement=function(e){return Vs(e)&&1===e.nodeType&&!Ys(e)},In.isEmpty=function(e){if(null==e)return!0;if(Ps(e)&&(js(e)||"string"==typeof e||"function"==typeof e.splice||Ls(e)||Qs(e)||Rs(e)))return!e.length;var t=oi(e);if(t==h||t==b)return!e.size;if(di(e))return!Cr(e).length;for(var n in e)if(Oe.call(e,n))return!1;return!0},In.isEqual=function(e,t){return wr(e,t)},In.isEqualWith=function(e,t,n){var r=(n="function"==typeof n?n:void 0)?n(e,t):void 0;return void 0===r?wr(e,t,void 0,n):!!r},In.isError=Us,In.isFinite=function(e){return"number"==typeof e&&rn(e)},In.isFunction=zs,In.isInteger=$s,In.isLength=Ws,In.isMap=Ks,In.isMatch=function(e,t){return e===t||_r(e,t,ei(t))},In.isMatchWith=function(e,t,n){return n="function"==typeof n?n:void 0,_r(e,t,ei(t),n)},In.isNaN=function(e){return Hs(e)&&e!=+e},In.isNative=function(e){if(pi(e))throw new fe("Unsupported core-js use. Try https://npms.io/search?q=ponyfill.");return Or(e)},In.isNil=function(e){return null==e},In.isNull=function(e){return null===e},In.isNumber=Hs,In.isObject=Fs,In.isObjectLike=Vs,In.isPlainObject=Ys,In.isRegExp=Gs,In.isSafeInteger=function(e){return $s(e)&&e>=-9007199254740991&&e<=9007199254740991},In.isSet=Js,In.isString=Xs,In.isSymbol=Zs,In.isTypedArray=Qs,In.isUndefined=function(e){return void 0===e},In.isWeakMap=function(e){return Vs(e)&&oi(e)==w},In.isWeakSet=function(e){return Vs(e)&&"[object WeakSet]"==hr(e)},In.join=function(e,t){return null==e?"":on.call(e,t)},In.kebabCase=ja,In.last=Ui,In.lastIndexOf=function(e,t,n){var r=null==e?0:e.length;if(!r)return-1;var o=r;return void 0!==n&&(o=(o=oa(n))<0?an(r+o,0):cn(o,r-1)),t==t?function(e,t,n){for(var r=n+1;r--;)if(e[r]===t)return r;return r}(e,t,o):vt(e,_t,o,!0)},In.lowerCase=Da,In.lowerFirst=Pa,In.lt=ea,In.lte=ta,In.max=function(e){return e&&e.length?or(e,Ha,mr):void 0},In.maxBy=function(e,t){return e&&e.length?or(e,Zo(t,2),mr):void 0},In.mean=function(e){return Ot(e,Ha)},In.meanBy=function(e,t){return Ot(e,Zo(t,2))},In.min=function(e){return e&&e.length?or(e,Ha,Er):void 0},In.minBy=function(e,t){return e&&e.length?or(e,Zo(t,2),Er):void 0},In.stubArray=ic,In.stubFalse=sc,In.stubObject=function(){return{}},In.stubString=function(){return""},In.stubTrue=function(){return!0},In.multiply=pc,In.nth=function(e,t){return e&&e.length?Mr(e,oa(t)):void 0},In.noConflict=function(){return Ke._===this&&(Ke._=Ne),this},In.noop=Za,In.now=gs,In.pad=function(e,t,n){e=ca(e);var r=(t=oa(t))?Vt(e):0;if(!t||r>=t)return e;var o=(t-r)/2;return jo(en(o),n)+e+jo(Qt(o),n)},In.padEnd=function(e,t,n){e=ca(e);var r=(t=oa(t))?Vt(e):0;return t&&r<t?e+jo(t-r,n):e},In.padStart=function(e,t,n){e=ca(e);var r=(t=oa(t))?Vt(e):0;return t&&r<t?jo(t-r,n)+e:e},In.parseInt=function(e,t,n){return n||null==t?t=0:t&&(t=+t),ln(ca(e).replace(H,""),t||0)},In.random=function(e,t,n){if(n&&"boolean"!=typeof n&&ui(e,t,n)&&(t=n=void 0),void 0===n&&("boolean"==typeof t?(n=t,t=void 0):"boolean"==typeof e&&(n=e,e=void 0)),void 0===e&&void 0===t?(e=0,t=1):(e=ra(e),void 0===t?(t=e,e=0):t=ra(t)),e>t){var r=e;e=t,t=r}if(n||e%1||t%1){var o=fn();return cn(e+o*(t-e+$e("1e-"+((o+"").length-1))),t)}return Br(e,t)},In.reduce=function(e,t,n){var r=js(e)?ht:xt,o=arguments.length<3;return r(e,Zo(t,4),n,o,tr)},In.reduceRight=function(e,t,n){var r=js(e)?mt:xt,o=arguments.length<3;return r(e,Zo(t,4),n,o,nr)},In.repeat=function(e,t,n){return t=(n?ui(e,t,n):void 0===t)?1:oa(t),Lr(ca(e),t)},In.replace=function(){var e=arguments,t=ca(e[0]);return e.length<3?t:t.replace(e[1],e[2])},In.result=function(e,t,n){var r=-1,o=(t=co(t,e)).length;for(o||(o=1,e=void 0);++r<o;){var i=null==e?void 0:e[Ei(t[r])];void 0===i&&(r=o,i=n),e=zs(i)?i.call(e):i}return e},In.round=dc,In.runInContext=e,In.sample=function(e){return(js(e)?Un:Ur)(e)},In.size=function(e){if(null==e)return 0;if(Ps(e))return Xs(e)?Vt(e):e.length;var t=oi(e);return t==h||t==b?e.size:Cr(e).length},In.snakeCase=Ba,In.some=function(e,t,n){var r=js(e)?gt:Hr;return n&&ui(e,t,n)&&(t=void 0),r(e,Zo(t,3))},In.sortedIndex=function(e,t){return Yr(e,t)},In.sortedIndexBy=function(e,t,n){return Gr(e,t,Zo(n,2))},In.sortedIndexOf=function(e,t){var n=null==e?0:e.length;if(n){var r=Yr(e,t);if(r<n&&As(e[r],t))return r}return-1},In.sortedLastIndex=function(e,t){return Yr(e,t,!0)},In.sortedLastIndexBy=function(e,t,n){return Gr(e,t,Zo(n,2),!0)},In.sortedLastIndexOf=function(e,t){if(null==e?0:e.length){var n=Yr(e,t,!0)-1;if(As(e[n],t))return n}return-1},In.startCase=La,In.startsWith=function(e,t,n){return e=ca(e),n=null==n?0:Jn(oa(n),0,e.length),t=Zr(t),e.slice(n,n+t.length)==t},In.subtract=hc,In.sum=function(e){return e&&e.length?Et(e,Ha):0},In.sumBy=function(e,t){return e&&e.length?Et(e,Zo(t,2)):0},In.template=function(e,t,n){var r=In.templateSettings;n&&ui(e,t,n)&&(t=void 0),e=ca(e),t=fa({},t,r,$o);var o,i,s=fa({},t.imports,r.imports,$o),a=wa(s),c=kt(s,a),u=0,l=t.interpolate||ue,f="__p += '",p=me((t.escape||ue).source+"|"+l.source+"|"+(l===z?te:ue).source+"|"+(t.evaluate||ue).source+"|$","g"),d="//# sourceURL="+(Oe.call(t,"sourceURL")?(t.sourceURL+"").replace(/\s/g," "):"lodash.templateSources["+ ++Le+"]")+"\n";e.replace(p,(function(t,n,r,s,a,c){return r||(r=s),f+=e.slice(u,c).replace(le,Lt),n&&(o=!0,f+="' +\n__e("+n+") +\n'"),a&&(i=!0,f+="';\n"+a+";\n__p += '"),r&&(f+="' +\n((__t = ("+r+")) == null ? '' : __t) +\n'"),u=c+t.length,t})),f+="';\n";var h=Oe.call(t,"variable")&&t.variable;if(h){if(Q.test(h))throw new fe("Invalid `variable` option passed into `_.template`")}else f="with (obj) {\n"+f+"\n}\n";f=(i?f.replace(M,""):f).replace(R,"$1").replace(j,"$1;"),f="function("+(h||"obj")+") {\n"+(h?"":"obj || (obj = {});\n")+"var __t, __p = ''"+(o?", __e = _.escape":"")+(i?", __j = Array.prototype.join;\nfunction print() { __p += __j.call(arguments, '') }\n":";\n")+f+"return __p\n}";var m=$a((function(){return pe(a,d+"return "+f).apply(void 0,c)}));if(m.source=f,Us(m))throw m;return m},In.times=function(e,t){if((e=oa(e))<1||e>9007199254740991)return[];var n=4294967295,r=cn(e,4294967295);e-=4294967295;for(var o=Nt(r,t=Zo(t));++n<e;)t(n);return o},In.toFinite=ra,In.toInteger=oa,In.toLength=ia,In.toLower=function(e){return ca(e).toLowerCase()},In.toNumber=sa,In.toSafeInteger=function(e){return e?Jn(oa(e),-9007199254740991,9007199254740991):0===e?e:0},In.toString=ca,In.toUpper=function(e){return ca(e).toUpperCase()},In.trim=function(e,t,n){if((e=ca(e))&&(n||void 0===t))return It(e);if(!e||!(t=Zr(t)))return e;var r=Kt(e),o=Kt(t);return lo(r,Rt(r,o),jt(r,o)+1).join("")},In.trimEnd=function(e,t,n){if((e=ca(e))&&(n||void 0===t))return e.slice(0,Ht(e)+1);if(!e||!(t=Zr(t)))return e;var r=Kt(e);return lo(r,0,jt(r,Kt(t))+1).join("")},In.trimStart=function(e,t,n){if((e=ca(e))&&(n||void 0===t))return e.replace(H,"");if(!e||!(t=Zr(t)))return e;var r=Kt(e);return lo(r,Rt(r,Kt(t))).join("")},In.truncate=function(e,t){var n=30,r="...";if(Fs(t)){var o="separator"in t?t.separator:o;n="length"in t?oa(t.length):n,r="omission"in t?Zr(t.omission):r}var i=(e=ca(e)).length;if(qt(e)){var s=Kt(e);i=s.length}if(n>=i)return e;var a=n-Vt(r);if(a<1)return r;var c=s?lo(s,0,a).join(""):e.slice(0,a);if(void 0===o)return c+r;if(s&&(a+=c.length-a),Gs(o)){if(e.slice(a).search(o)){var u,l=c;for(o.global||(o=me(o.source,ca(ne.exec(o))+"g")),o.lastIndex=0;u=o.exec(l);)var f=u.index;c=c.slice(0,void 0===f?a:f)}}else if(e.indexOf(Zr(o),a)!=a){var p=c.lastIndexOf(o);p>-1&&(c=c.slice(0,p))}return c+r},In.unescape=function(e){return(e=ca(e))&&B.test(e)?e.replace(D,Yt):e},In.uniqueId=function(e){var t=++Te;return ca(e)+t},In.upperCase=qa,In.upperFirst=Ua,In.each=cs,In.eachRight=us,In.first=Pi,Xa(In,(fc={},ur(In,(function(e,t){Oe.call(In.prototype,t)||(fc[t]=e)})),fc),{chain:!1}),In.VERSION="4.17.21",st(["bind","bindKey","curry","curryRight","partial","partialRight"],(function(e){In[e].placeholder=In})),st(["drop","take"],(function(e,t){Rn.prototype[e]=function(n){n=void 0===n?1:an(oa(n),0);var r=this.__filtered__&&!t?new Rn(this):this.clone();return r.__filtered__?r.__takeCount__=cn(n,r.__takeCount__):r.__views__.push({size:cn(n,4294967295),type:e+(r.__dir__<0?"Right":"")}),r},Rn.prototype[e+"Right"]=function(t){return this.reverse()[e](t).reverse()}})),st(["filter","map","takeWhile"],(function(e,t){var n=t+1,r=1==n||3==n;Rn.prototype[e]=function(e){var t=this.clone();return t.__iteratees__.push({iteratee:Zo(e,3),type:n}),t.__filtered__=t.__filtered__||r,t}})),st(["head","last"],(function(e,t){var n="take"+(t?"Right":"");Rn.prototype[e]=function(){return this[n](1).value()[0]}})),st(["initial","tail"],(function(e,t){var n="drop"+(t?"":"Right");Rn.prototype[e]=function(){return this.__filtered__?new Rn(this):this[n](1)}})),Rn.prototype.compact=function(){return this.filter(Ha)},Rn.prototype.find=function(e){return this.filter(e).head()},Rn.prototype.findLast=function(e){return this.reverse().find(e)},Rn.prototype.invokeMap=qr((function(e,t){return"function"==typeof e?new Rn(this):this.map((function(n){return vr(n,e,t)}))})),Rn.prototype.reject=function(e){return this.filter(Cs(Zo(e)))},Rn.prototype.slice=function(e,t){e=oa(e);var n=this;return n.__filtered__&&(e>0||t<0)?new Rn(n):(e<0?n=n.takeRight(-e):e&&(n=n.drop(e)),void 0!==t&&(n=(t=oa(t))<0?n.dropRight(-t):n.take(t-e)),n)},Rn.prototype.takeRightWhile=function(e){return this.reverse().takeWhile(e).reverse()},Rn.prototype.toArray=function(){return this.take(4294967295)},ur(Rn.prototype,(function(e,t){var n=/^(?:filter|find|map|reject)|While$/.test(t),r=/^(?:head|last)$/.test(t),o=In[r?"take"+("last"==t?"Right":""):t],i=r||/^find/.test(t);o&&(In.prototype[t]=function(){var t=this.__wrapped__,s=r?[1]:arguments,a=t instanceof Rn,c=s[0],u=a||js(t),l=function(e){var t=o.apply(In,dt([e],s));return r&&f?t[0]:t};u&&n&&"function"==typeof c&&1!=c.length&&(a=u=!1);var f=this.__chain__,p=!!this.__actions__.length,d=i&&!f,h=a&&!p;if(!i&&u){t=h?t:new Rn(this);var m=e.apply(t,s);return m.__actions__.push({func:rs,args:[l],thisArg:void 0}),new Mn(m,f)}return d&&h?e.apply(this,s):(m=this.thru(l),d?r?m.value()[0]:m.value():m)})})),st(["pop","push","shift","sort","splice","unshift"],(function(e){var t=be[e],n=/^(?:push|sort|unshift)$/.test(e)?"tap":"thru",r=/^(?:pop|shift)$/.test(e);In.prototype[e]=function(){var e=arguments;if(r&&!this.__chain__){var o=this.value();return t.apply(js(o)?o:[],e)}return this[n]((function(n){return t.apply(js(n)?n:[],e)}))}})),ur(Rn.prototype,(function(e,t){var n=In[t];if(n){var r=n.name+"";Oe.call(Sn,r)||(Sn[r]=[]),Sn[r].push({name:t,func:n})}})),Sn[Ao(void 0,2).name]=[{name:"wrapper",func:void 0}],Rn.prototype.clone=function(){var e=new Rn(this.__wrapped__);return e.__actions__=vo(this.__actions__),e.__dir__=this.__dir__,e.__filtered__=this.__filtered__,e.__iteratees__=vo(this.__iteratees__),e.__takeCount__=this.__takeCount__,e.__views__=vo(this.__views__),e},Rn.prototype.reverse=function(){if(this.__filtered__){var e=new Rn(this);e.__dir__=-1,e.__filtered__=!0}else(e=this.clone()).__dir__*=-1;return e},Rn.prototype.value=function(){var e=this.__wrapped__.value(),t=this.__dir__,n=js(e),r=t<0,o=n?e.length:0,i=function(e,t,n){var r=-1,o=n.length;for(;++r<o;){var i=n[r],s=i.size;switch(i.type){case"drop":e+=s;break;case"dropRight":t-=s;break;case"take":t=cn(t,e+s);break;case"takeRight":e=an(e,t-s)}}return{start:e,end:t}}(0,o,this.__views__),s=i.start,a=i.end,c=a-s,u=r?a:s-1,l=this.__iteratees__,f=l.length,p=0,d=cn(c,this.__takeCount__);if(!n||!r&&o==c&&d==c)return ro(e,this.__actions__);var h=[];e:for(;c--&&p<d;){for(var m=-1,g=e[u+=t];++m<f;){var y=l[m],b=y.iteratee,v=y.type,S=b(g);if(2==v)g=S;else if(!S){if(1==v)continue e;break e}}h[p++]=g}return h},In.prototype.at=os,In.prototype.chain=function(){return ns(this)},In.prototype.commit=function(){return new Mn(this.value(),this.__chain__)},In.prototype.next=function(){void 0===this.__values__&&(this.__values__=na(this.value()));var e=this.__index__>=this.__values__.length;return{done:e,value:e?void 0:this.__values__[this.__index__++]}},In.prototype.plant=function(e){for(var t,n=this;n instanceof kn;){var r=Ii(n);r.__index__=0,r.__values__=void 0,t?o.__wrapped__=r:t=r;var o=r;n=n.__wrapped__}return o.__wrapped__=e,t},In.prototype.reverse=function(){var e=this.__wrapped__;if(e instanceof Rn){var t=e;return this.__actions__.length&&(t=new Rn(this)),(t=t.reverse()).__actions__.push({func:rs,args:[Fi],thisArg:void 0}),new Mn(t,this.__chain__)}return this.thru(Fi)},In.prototype.toJSON=In.prototype.valueOf=In.prototype.value=function(){return ro(this.__wrapped__,this.__actions__)},In.prototype.first=In.prototype.head,Xe&&(In.prototype[Xe]=function(){return this}),In}();Ke._=Gt,void 0===(r=function(){return Gt}.call(t,n,t,e))||(e.exports=r)}).call(this)}).call(this,n(62)(e))},function(e,t,n){var r=n(36),o=n(248),i=n(249),s=r?r.toStringTag:void 0;e.exports=function(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":s&&s in Object(e)?o(e):i(e)}},function(e,t,n){"use strict";const r=n(18).Transform,o=n(18).PassThrough,i=n(5).deprecate,s=n(0).handleCallback,a=n(2).ReadPreference,c=n(2).MongoError,u=n(17).CoreCursor,l=n(17).CursorState,f=n(2).BSON.Map,p=n(0).maybePromise,d=n(56),h=n(0).formattedOrderClause,m=n(91).Explain,g=n(1).Aspect,y=n(448).each,b=n(449),v=["tailable","oplogReplay","noCursorTimeout","awaitData","exhaust","partial"],S=["numberOfRetries","tailableRetryInterval"];class w extends u{constructor(e,t,n,r){super(e,t,n,r),this.operation&&(r=this.operation.options);const o=r.numberOfRetries||5,i=r.tailableRetryInterval||500,s=o,a=r.promiseLibrary||Promise;this.s={numberOfRetries:o,tailableRetryInterval:i,currentNumberOfRetries:s,state:l.INIT,promiseLibrary:a,explicitlyIgnoreSession:!!r.explicitlyIgnoreSession},!r.explicitlyIgnoreSession&&r.session&&(this.cursorState.session=r.session),!0===this.options.noCursorTimeout&&this.addCursorFlag("noCursorTimeout",!0);let c=1e3;this.cmd.cursor&&this.cmd.cursor.batchSize?c=this.cmd.cursor.batchSize:r.cursor&&r.cursor.batchSize?c=r.cursor.batchSize:"number"==typeof r.batchSize&&(c=r.batchSize),this.setCursorBatchSize(c)}get readPreference(){return this.operation?this.operation.readPreference:this.options.readPreference}get sortValue(){return this.cmd.sort}_initializeCursor(e){this.operation&&null!=this.operation.session?this.cursorState.session=this.operation.session:this.s.explicitlyIgnoreSession||this.cursorState.session||!this.topology.hasSessionSupport()||(this.cursorState.session=this.topology.startSession({owner:this}),this.operation&&(this.operation.session=this.cursorState.session)),super._initializeCursor(e)}hasNext(e){if(this.s.state===l.CLOSED||this.isDead&&this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return p(this,e,e=>{const t=this;if(t.isNotified())return e(null,!1);t._next((n,r)=>n?e(n):null==r||t.s.state===w.CLOSED||t.isDead()?e(null,!1):(t.s.state=l.OPEN,t.cursorState.cursorIndex--,t.cursorState.limit>0&&t.cursorState.currentLimit--,void e(null,!0)))})}next(e){return p(this,e,e=>{const t=this;if(t.s.state===l.CLOSED||t.isDead&&t.isDead())e(c.create({message:"Cursor is closed",driver:!0}));else{if(t.s.state===l.INIT&&t.cmd.sort)try{t.cmd.sort=h(t.cmd.sort)}catch(t){return e(t)}t._next((n,r)=>{if(n)return e(n);t.s.state=l.OPEN,e(null,r)})}})}filter(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.query=e,this}maxScan(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.maxScan=e,this}hint(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.hint=e,this}min(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.min=e,this}max(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.max=e,this}returnKey(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.returnKey=e,this}showRecordId(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.showDiskLoc=e,this}snapshot(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.snapshot=e,this}setCursorOption(e,t){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});if(-1===S.indexOf(e))throw c.create({message:`option ${e} is not a supported option ${S}`,driver:!0});return this.s[e]=t,"numberOfRetries"===e&&(this.s.currentNumberOfRetries=t),this}addCursorFlag(e,t){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});if(-1===v.indexOf(e))throw c.create({message:`flag ${e} is not a supported flag ${v}`,driver:!0});if("boolean"!=typeof t)throw c.create({message:`flag ${e} must be a boolean value`,driver:!0});return this.cmd[e]=t,this}addQueryModifier(e,t){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});if("$"!==e[0])throw c.create({message:`${e} is not a valid query modifier`,driver:!0});const n=e.substr(1);return this.cmd[n]=t,"orderby"===n&&(this.cmd.sort=this.cmd[n]),this}comment(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.comment=e,this}maxAwaitTimeMS(e){if("number"!=typeof e)throw c.create({message:"maxAwaitTimeMS must be a number",driver:!0});if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.maxAwaitTimeMS=e,this}maxTimeMS(e){if("number"!=typeof e)throw c.create({message:"maxTimeMS must be a number",driver:!0});if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.maxTimeMS=e,this}project(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.fields=e,this}sort(e,t){if(this.options.tailable)throw c.create({message:"Tailable cursor doesn't support sorting",driver:!0});if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});let n=e;return Array.isArray(n)&&Array.isArray(n[0])&&(n=new f(n.map(e=>{const t=[e[0],null];if("asc"===e[1])t[1]=1;else if("desc"===e[1])t[1]=-1;else{if(1!==e[1]&&-1!==e[1]&&!e[1].$meta)throw new c("Illegal sort clause, must be of the form [['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]");t[1]=e[1]}return t}))),null!=t&&(n=[[e,t]]),this.cmd.sort=n,this}batchSize(e){if(this.options.tailable)throw c.create({message:"Tailable cursor doesn't support batchSize",driver:!0});if(this.s.state===l.CLOSED||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});if("number"!=typeof e)throw c.create({message:"batchSize requires an integer",driver:!0});return this.cmd.batchSize=e,this.setCursorBatchSize(e),this}collation(e){return this.cmd.collation=e,this}limit(e){if(this.options.tailable)throw c.create({message:"Tailable cursor doesn't support limit",driver:!0});if(this.s.state===l.OPEN||this.s.state===l.CLOSED||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});if("number"!=typeof e)throw c.create({message:"limit requires an integer",driver:!0});return this.cmd.limit=e,this.setCursorLimit(e),this}skip(e){if(this.options.tailable)throw c.create({message:"Tailable cursor doesn't support skip",driver:!0});if(this.s.state===l.OPEN||this.s.state===l.CLOSED||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});if("number"!=typeof e)throw c.create({message:"skip requires an integer",driver:!0});return this.cmd.skip=e,this.setCursorSkip(e),this}each(e){this.rewind(),this.s.state=l.INIT,y(this,e)}forEach(e,t){if(this.rewind(),this.s.state=l.INIT,"function"!=typeof t)return new this.s.promiseLibrary((t,n)=>{y(this,(r,o)=>r?(n(r),!1):null==o?(t(null),!1):(e(o),!0))});y(this,(n,r)=>{if(n)return t(n),!1;if(null!=r)return e(r),!0;if(null==r&&t){const e=t;return t=null,e(null),!1}})}setReadPreference(e){if(this.s.state!==l.INIT)throw c.create({message:"cannot change cursor readPreference after cursor has been accessed",driver:!0});if(e instanceof a)this.options.readPreference=e;else{if("string"!=typeof e)throw new TypeError("Invalid read preference: "+e);this.options.readPreference=new a(e)}return this}toArray(e){if(this.options.tailable)throw c.create({message:"Tailable cursor cannot be converted to array",driver:!0});return p(this,e,e=>{const t=this,n=[];t.rewind(),t.s.state=l.INIT;const r=()=>{t._next((o,i)=>{if(o)return s(e,o);if(null==i)return t.close({skipKillCursors:!0},()=>s(e,null,n));if(n.push(i),t.bufferedCount()>0){let e=t.readBufferedDocuments(t.bufferedCount());Array.prototype.push.apply(n,e)}r()})};r()})}count(e,t,n){if(null==this.cmd.query)throw c.create({message:"count can only be used with find command",driver:!0});"function"==typeof t&&(n=t,t={}),t=t||{},"function"==typeof e&&(n=e,e=!0),this.cursorState.session&&(t=Object.assign({},t,{session:this.cursorState.session}));const r=new b(this,e,t);return d(this.topology,r,n)}close(e,t){return"function"==typeof e&&(t=e,e={}),e=Object.assign({},{skipKillCursors:!1},e),p(this,t,t=>{this.s.state=l.CLOSED,e.skipKillCursors||this.kill(),this._endSession(()=>{this.emit("close"),t(null,this)})})}map(e){if(this.cursorState.transforms&&this.cursorState.transforms.doc){const t=this.cursorState.transforms.doc;this.cursorState.transforms.doc=n=>e(t(n))}else this.cursorState.transforms={doc:e};return this}isClosed(){return this.isDead()}destroy(e){e&&this.emit("error",e),this.pause(),this.close()}stream(e){return this.cursorState.streamOptions=e||{},this}transformStream(e){const t=e||{};if("function"==typeof t.transform){const e=new r({objectMode:!0,transform:function(e,n,r){this.push(t.transform(e)),r()}});return this.pipe(e)}return this.pipe(new o({objectMode:!0}))}explain(e,t){if("function"==typeof e&&(t=e,e=!0),void 0===e&&(e=!0),!this.operation||!this.operation.hasAspect(g.EXPLAINABLE))throw new c("This command cannot be explained");return this.operation.explain=new m(e),p(this,t,e=>{u.prototype._next.apply(this,[e])})}getLogger(){return this.logger}}w.prototype.maxTimeMs=w.prototype.maxTimeMS,i(w.prototype.each,"Cursor.each is deprecated. Use Cursor.forEach instead."),i(w.prototype.maxScan,"Cursor.maxScan is deprecated, and will be removed in a later version"),i(w.prototype.snapshot,"Cursor Snapshot is deprecated, and will be removed in a later version"),e.exports=w},function(e,t,n){"use strict";const r=n(1).Aspect,o=n(1).OperationBase,i=n(2).ReadPreference,s=n(46),a=n(29),c=n(4).maxWireVersion,u=n(0).decorateWithExplain,l=n(34).commandSupportsReadConcern,f=n(3).MongoError;e.exports=class extends o{constructor(e,t,n){super(t),this.ns=e.s.namespace.withCollection("$cmd");const o=this.hasAspect(r.NO_INHERIT_OPTIONS)?void 0:e;this.readPreference=this.hasAspect(r.WRITE_OPERATION)?i.primary:i.resolve(o,this.options),this.readConcern=function(e,t){return s.fromOptions(t)||e&&e.readConcern}(o,this.options),this.writeConcern=function(e,t){return a.fromOptions(t)||e&&e.writeConcern}(o,this.options),n&&"boolean"==typeof n.fullResponse&&(this.fullResponse=!0),this.options.readPreference=this.readPreference,e.s.logger?this.logger=e.s.logger:e.s.db&&e.s.db.logger&&(this.logger=e.s.db.logger)}executeCommand(e,t,n){this.server=e;const o=this.options,i=c(e),s=this.session&&this.session.inTransaction();this.readConcern&&l(t)&&!s&&Object.assign(t,{readConcern:this.readConcern}),o.collation&&i<5?n(new f(`Server ${e.name}, which reports wire version ${i}, does not support collation`)):(i>=5&&(this.writeConcern&&this.hasAspect(r.WRITE_OPERATION)&&Object.assign(t,{writeConcern:this.writeConcern}),o.collation&&"object"==typeof o.collation&&Object.assign(t,{collation:o.collation})),"number"==typeof o.maxTimeMS&&(t.maxTimeMS=o.maxTimeMS),"string"==typeof o.comment&&(t.comment=o.comment),this.hasAspect(r.EXPLAINABLE)&&this.explain&&(i<6&&t.aggregate?t.explain=!0:t=u(t,this.explain)),this.logger&&this.logger.isDebug()&&this.logger.debug(`executing command ${JSON.stringify(t)} against ${this.ns}`),e.command(this.ns.toString(),t,this.options,(e,t)=>{e?n(e,null):this.fullResponse?n(null,t):n(null,t.result)}))}}},function(e,t){e.exports=function(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}},function(e,t,n){"use strict";const r=new Set(["w","wtimeout","j","journal","fsync"]);let o;class i{constructor(e,t,n,r){null!=e&&(this.w=e),null!=t&&(this.wtimeout=t),null!=n&&(this.j=n),null!=r&&(this.fsync=r)}static fromOptions(e){if(null!=e&&(null!=e.writeConcern||null!=e.w||null!=e.wtimeout||null!=e.j||null!=e.journal||null!=e.fsync)){if(e.writeConcern){if("string"==typeof e.writeConcern)return new i(e.writeConcern);if(!Object.keys(e.writeConcern).some(e=>r.has(e)))return;return new i(e.writeConcern.w,e.writeConcern.wtimeout,e.writeConcern.j||e.writeConcern.journal,e.writeConcern.fsync)}return o||(o=n(0)),o.emitWarningOnce("Top-level use of w, wtimeout, j, and fsync is deprecated. Use writeConcern instead."),new i(e.w,e.wtimeout,e.j||e.journal,e.fsync)}}}e.exports=i},function(e,t,n){"use strict";const r=n(9).retrieveSnappy(),o=n(413),i={snappy:1,zlib:2},s=new Set(["ismaster","saslStart","saslContinue","getnonce","authenticate","createUser","updateUser","copydbSaslStart","copydbgetnonce","copydb"]);e.exports={compressorIDs:i,uncompressibleCommands:s,compress:function(e,t,n){switch(e.options.agreedCompressor){case"snappy":r.compress(t,n);break;case"zlib":var i={};e.options.zlibCompressionLevel&&(i.level=e.options.zlibCompressionLevel),o.deflate(t,i,n);break;default:throw new Error('Attempt to compress message using unknown compressor "'+e.options.agreedCompressor+'".')}},decompress:function(e,t,n){if(e<0||e>i.length)throw new Error("Server sent message compressed using an unsupported compressor. (Received compressor ID "+e+")");switch(e){case i.snappy:r.uncompress(t,n);break;case i.zlib:o.inflate(t,n);break;default:n(null,t)}}}},function(e,t,n){var r=n(247),o=n(252);e.exports=function(e,t){var n=o(e,t);return r(n)?n:void 0}},function(e,t,n){"use strict";function r(e,t){return new Buffer(e,t)}e.exports={normalizedFunctionString:function(e){return e.toString().replace(/function *\(/,"function (")},allocBuffer:"function"==typeof Buffer.alloc?function(){return Buffer.alloc.apply(Buffer,arguments)}:r,toBuffer:"function"==typeof Buffer.from?function(){return Buffer.from.apply(Buffer,arguments)}:r}},function(e,t,n){"use strict";e.exports={AuthContext:class{constructor(e,t,n){this.connection=e,this.credentials=t,this.options=n}},AuthProvider:class{constructor(e){this.bson=e}prepare(e,t,n){n(void 0,e)}auth(e,t){t(new TypeError("`auth` method must be overridden by subclass"))}}}},function(e,t,n){"use strict";const r=n(9).retrieveBSON,o=n(8),i=r(),s=i.Binary,a=n(4).uuidV4,c=n(3).MongoError,u=n(3).isRetryableError,l=n(3).MongoNetworkError,f=n(3).MongoWriteConcernError,p=n(54).Transaction,d=n(54).TxnState,h=n(4).isPromiseLike,m=n(10),g=n(0).maybePromise,y=n(54).isTransactionCommand,b=n(7).resolveClusterTime,v=n(6).isSharded,S=n(4).maxWireVersion,w=n(0).now,_=n(0).calculateDurationInMs;function O(e,t){if(null==e.serverSession){const e=new c("Cannot use a session that has ended");if("function"==typeof t)return t(e,null),!1;throw e}return!0}const T=Symbol("serverSession");class C extends o{constructor(e,t,n,r){if(super(),null==e)throw new Error("ClientSession requires a topology");if(null==t||!(t instanceof R))throw new Error("ClientSession requires a ServerSessionPool");n=n||{},r=r||{},this.topology=e,this.sessionPool=t,this.hasEnded=!1,this.clientOptions=r,this[T]=void 0,this.supports={causalConsistency:void 0===n.causalConsistency||n.causalConsistency},this.clusterTime=n.initialClusterTime,this.operationTime=null,this.explicit=!!n.explicit,this.owner=n.owner,this.defaultTransactionOptions=Object.assign({},n.defaultTransactionOptions),this.transaction=new p}get id(){return this.serverSession.id}get serverSession(){return null==this[T]&&(this[T]=this.sessionPool.acquire()),this[T]}endSession(e,t){"function"==typeof e&&(t=e,e={}),e=e||{};const n=this;return g(this,t,e=>{if(n.hasEnded)return e();function t(){n.sessionPool.release(n.serverSession),n[T]=void 0,n.hasEnded=!0,n.emit("ended",n),e()}n.serverSession&&n.inTransaction()?n.abortTransaction(n=>{if(n)return e(n);t()}):t()})}advanceOperationTime(e){null!=this.operationTime?e.greaterThan(this.operationTime)&&(this.operationTime=e):this.operationTime=e}equals(e){return e instanceof C&&this.id.id.buffer.equals(e.id.id.buffer)}incrementTransactionNumber(){this.serverSession.txnNumber++}inTransaction(){return this.transaction.isActive}startTransaction(e){if(O(this),this.inTransaction())throw new c("Transaction already in progress");const t=S(this.topology);if(v(this.topology)&&null!=t&&t<8)throw new c("Transactions are not supported on sharded clusters in MongoDB < 4.2.");this.incrementTransactionNumber(),this.transaction=new p(Object.assign({},this.clientOptions,e||this.defaultTransactionOptions)),this.transaction.transition(d.STARTING_TRANSACTION)}commitTransaction(e){return g(this,e,e=>k(this,"commitTransaction",e))}abortTransaction(e){return g(this,e,e=>k(this,"abortTransaction",e))}toBSON(){throw new Error("ClientSession cannot be serialized to BSON.")}withTransaction(e,t){return A(this,w(),e,t)}}const x=new Set(["CannotSatisfyWriteConcern","UnknownReplWriteConcern","UnsatisfiableWriteConcern"]);function E(e,t){return _(e)<t}function N(e){return null!=e&&(50===e.code||e.writeConcernError&&50===e.writeConcernError.code)}const I=new Set([d.NO_TRANSACTION,d.TRANSACTION_COMMITTED,d.TRANSACTION_ABORTED]);function A(e,t,n,r){let o;e.startTransaction(r);try{o=n(e)}catch(e){o=Promise.reject(e)}if(!h(o))throw e.abortTransaction(),new TypeError("Function provided to `withTransaction` must return a Promise");return o.then(()=>{if(!function(e){return I.has(e.transaction.state)}(e))return function e(t,n,r,o){return t.commitTransaction().catch(i=>{if(i instanceof c&&E(n,12e4)&&!N(i)){if(i.hasErrorLabel("UnknownTransactionCommitResult"))return e(t,n,r,o);if(i.hasErrorLabel("TransientTransactionError"))return A(t,n,r,o)}throw i})}(e,t,n,r)}).catch(o=>{function i(o){if(o instanceof c&&o.hasErrorLabel("TransientTransactionError")&&E(t,12e4))return A(e,t,n,r);throw N(o)&&o.addErrorLabel("UnknownTransactionCommitResult"),o}return e.transaction.isActive?e.abortTransaction().then(()=>i(o)):i(o)})}function k(e,t,n){if(!O(e,n))return;let r=e.transaction.state;if(r===d.NO_TRANSACTION)return void n(new c("No transaction started"));if("commitTransaction"===t){if(r===d.STARTING_TRANSACTION||r===d.TRANSACTION_COMMITTED_EMPTY)return e.transaction.transition(d.TRANSACTION_COMMITTED_EMPTY),void n(null,null);if(r===d.TRANSACTION_ABORTED)return void n(new c("Cannot call commitTransaction after calling abortTransaction"))}else{if(r===d.STARTING_TRANSACTION)return e.transaction.transition(d.TRANSACTION_ABORTED),void n(null,null);if(r===d.TRANSACTION_ABORTED)return void n(new c("Cannot call abortTransaction twice"));if(r===d.TRANSACTION_COMMITTED||r===d.TRANSACTION_COMMITTED_EMPTY)return void n(new c("Cannot call abortTransaction after calling commitTransaction"))}const o={[t]:1};let i;function s(r,o){var i;"commitTransaction"===t?(e.transaction.transition(d.TRANSACTION_COMMITTED),r&&(r instanceof l||r instanceof f||u(r)||N(r))&&(N(i=r)||!x.has(i.codeName)&&100!==i.code&&79!==i.code)&&(r.addErrorLabel("UnknownTransactionCommitResult"),e.transaction.unpinServer())):e.transaction.transition(d.TRANSACTION_ABORTED),n(r,o)}function a(e){return"commitTransaction"===t?e:null}e.transaction.options.writeConcern?i=Object.assign({},e.transaction.options.writeConcern):e.clientOptions&&e.clientOptions.w&&(i={w:e.clientOptions.w}),r===d.TRANSACTION_COMMITTED&&(i=Object.assign({wtimeout:1e4},i,{w:"majority"})),i&&Object.assign(o,{writeConcern:i}),"commitTransaction"===t&&e.transaction.options.maxTimeMS&&Object.assign(o,{maxTimeMS:e.transaction.options.maxTimeMS}),e.transaction.recoveryToken&&function(e){return!!e.topology.s.options.useRecoveryToken}(e)&&(o.recoveryToken=e.transaction.recoveryToken),e.topology.command("admin.$cmd",o,{session:e},(t,n)=>{if(t&&u(t))return o.commitTransaction&&(e.transaction.unpinServer(),o.writeConcern=Object.assign({wtimeout:1e4},o.writeConcern,{w:"majority"})),e.topology.command("admin.$cmd",o,{session:e},(e,t)=>s(a(e),t));s(a(t),n)})}class M{constructor(){this.id={id:new s(a(),s.SUBTYPE_UUID)},this.lastUse=w(),this.txnNumber=0,this.isDirty=!1}hasTimedOut(e){return Math.round(_(this.lastUse)%864e5%36e5/6e4)>e-1}}class R{constructor(e){if(null==e)throw new Error("ServerSessionPool requires a topology");this.topology=e,this.sessions=[]}endAllPooledSessions(e){this.sessions.length?this.topology.endSessions(this.sessions.map(e=>e.id),()=>{this.sessions=[],"function"==typeof e&&e()}):"function"==typeof e&&e()}acquire(){const e=this.topology.logicalSessionTimeoutMinutes;for(;this.sessions.length;){const t=this.sessions.shift();if(!t.hasTimedOut(e))return t}return new M}release(e){const t=this.topology.logicalSessionTimeoutMinutes;for(;this.sessions.length;){if(!this.sessions[this.sessions.length-1].hasTimedOut(t))break;this.sessions.pop()}if(!e.hasTimedOut(t)){if(e.isDirty)return;this.sessions.unshift(e)}}}function j(e,t){return!!(e.aggregate||e.count||e.distinct||e.find||e.parallelCollectionScan||e.geoNear||e.geoSearch)||!(!(e.mapReduce&&t&&t.out)||1!==t.out.inline&&"inline"!==t.out)}e.exports={ClientSession:C,ServerSession:M,ServerSessionPool:R,TxnState:d,applySession:function(e,t,n){if(e.hasEnded)return new c("Cannot use a session that has ended");if(n&&n.writeConcern&&0===n.writeConcern.w)return;const r=e.serverSession;r.lastUse=w(),t.lsid=r.id;const o=e.inTransaction()||y(t),s=n.willRetryWrite,a=j(t,n);if(r.txnNumber&&(s||o)&&(t.txnNumber=i.Long.fromNumber(r.txnNumber)),!o)return e.transaction.state!==d.NO_TRANSACTION&&e.transaction.transition(d.NO_TRANSACTION),void(e.supports.causalConsistency&&e.operationTime&&a&&(t.readConcern=t.readConcern||{},Object.assign(t.readConcern,{afterClusterTime:e.operationTime})));if(n.readPreference&&!n.readPreference.equals(m.primary))return new c(`Read preference in a transaction must be primary, not: ${n.readPreference.mode}`);if(t.autocommit=!1,e.transaction.state===d.STARTING_TRANSACTION){e.transaction.transition(d.TRANSACTION_IN_PROGRESS),t.startTransaction=!0;const n=e.transaction.options.readConcern||e.clientOptions.readConcern;n&&(t.readConcern=n),e.supports.causalConsistency&&e.operationTime&&(t.readConcern=t.readConcern||{},Object.assign(t.readConcern,{afterClusterTime:e.operationTime}))}},updateSessionFromResponse:function(e,t){t.$clusterTime&&b(e,t.$clusterTime),t.operationTime&&e&&e.supports.causalConsistency&&e.advanceOperationTime(t.operationTime),t.recoveryToken&&e&&e.inTransaction()&&(e.transaction._recoveryToken=t.recoveryToken)},commandSupportsReadConcern:j}},function(e,t,n){"use strict";const r=n(8),o=n(2).MongoError,i=n(5).format,s=n(2).ReadPreference,a=n(2).Sessions.ClientSession;var c=function(e,t){var n=this;t=t||{force:!1,bufferMaxEntries:-1},this.s={storedOps:[],storeOptions:t,topology:e},Object.defineProperty(this,"length",{enumerable:!0,get:function(){return n.s.storedOps.length}})};c.prototype.add=function(e,t,n,r,s){if(this.s.storeOptions.force)return s(o.create({message:"db closed by application",driver:!0}));if(0===this.s.storeOptions.bufferMaxEntries)return s(o.create({message:i("no connection available for operation and number of stored operation > %s",this.s.storeOptions.bufferMaxEntries),driver:!0}));if(this.s.storeOptions.bufferMaxEntries>0&&this.s.storedOps.length>this.s.storeOptions.bufferMaxEntries)for(;this.s.storedOps.length>0;){this.s.storedOps.shift().c(o.create({message:i("no connection available for operation and number of stored operation > %s",this.s.storeOptions.bufferMaxEntries),driver:!0}))}else this.s.storedOps.push({t:e,n:t,o:n,op:r,c:s})},c.prototype.addObjectAndMethod=function(e,t,n,r,s){if(this.s.storeOptions.force)return s(o.create({message:"db closed by application",driver:!0}));if(0===this.s.storeOptions.bufferMaxEntries)return s(o.create({message:i("no connection available for operation and number of stored operation > %s",this.s.storeOptions.bufferMaxEntries),driver:!0}));if(this.s.storeOptions.bufferMaxEntries>0&&this.s.storedOps.length>this.s.storeOptions.bufferMaxEntries)for(;this.s.storedOps.length>0;){this.s.storedOps.shift().c(o.create({message:i("no connection available for operation and number of stored operation > %s",this.s.storeOptions.bufferMaxEntries),driver:!0}))}else this.s.storedOps.push({t:e,m:n,o:t,p:r,c:s})},c.prototype.flush=function(e){for(;this.s.storedOps.length>0;)this.s.storedOps.shift().c(e||o.create({message:i("no connection available for operation"),driver:!0}))};var u=["primary","primaryPreferred","nearest","secondaryPreferred"],l=["secondary","secondaryPreferred"];c.prototype.execute=function(e){e=e||{};var t=this.s.storedOps;this.s.storedOps=[];for(var n="boolean"!=typeof e.executePrimary||e.executePrimary,r="boolean"!=typeof e.executeSecondary||e.executeSecondary;t.length>0;){var o=t.shift();"cursor"===o.t?n&&r?o.o[o.m].apply(o.o,o.p):n&&o.o.options&&o.o.options.readPreference&&-1!==u.indexOf(o.o.options.readPreference.mode)?o.o[o.m].apply(o.o,o.p):!n&&r&&o.o.options&&o.o.options.readPreference&&-1!==l.indexOf(o.o.options.readPreference.mode)&&o.o[o.m].apply(o.o,o.p):"auth"===o.t?this.s.topology[o.t].apply(this.s.topology,o.o):n&&r?this.s.topology[o.t](o.n,o.o,o.op,o.c):n&&o.op&&o.op.readPreference&&-1!==u.indexOf(o.op.readPreference.mode)?this.s.topology[o.t](o.n,o.o,o.op,o.c):!n&&r&&o.op&&o.op.readPreference&&-1!==l.indexOf(o.op.readPreference.mode)&&this.s.topology[o.t](o.n,o.o,o.op,o.c)}},c.prototype.all=function(){return this.s.storedOps};var f=function(e){var t=function(e,t,n){Object.defineProperty(e,t,{enumerable:!0,get:function(){return n}})},n=!1,r=!1,o=!1,i=!1,s=!1,a=!1,c=e.maxWriteBatchSize||1e3,u=!1,l=!1;e.minWireVersion>=0&&(o=!0),e.maxWireVersion>=1&&(n=!0,i=!0),e.maxWireVersion>=2&&(r=!0),e.maxWireVersion>=3&&(s=!0,a=!0),e.maxWireVersion>=5&&(u=!0,l=!0),null==e.minWireVersion&&(e.minWireVersion=0),null==e.maxWireVersion&&(e.maxWireVersion=0),t(this,"hasAggregationCursor",n),t(this,"hasWriteCommands",r),t(this,"hasTextSearch",o),t(this,"hasAuthCommands",i),t(this,"hasListCollectionsCommand",s),t(this,"hasListIndexesCommand",a),t(this,"minWireVersion",e.minWireVersion),t(this,"maxWireVersion",e.maxWireVersion),t(this,"maxNumberOfDocsInBatch",c),t(this,"commandsTakeWriteConcern",u),t(this,"commandsTakeCollation",l)};class p extends r{constructor(){super(),this.setMaxListeners(1/0)}hasSessionSupport(){return null!=this.logicalSessionTimeoutMinutes}startSession(e,t){const n=new a(this,this.s.sessionPool,e,t);return n.once("ended",()=>{this.s.sessions.delete(n)}),this.s.sessions.add(n),n}endSessions(e,t){return this.s.coreTopology.endSessions(e,t)}get clientMetadata(){return this.s.coreTopology.s.options.metadata}capabilities(){return this.s.sCapabilities?this.s.sCapabilities:null==this.s.coreTopology.lastIsMaster()?null:(this.s.sCapabilities=new f(this.s.coreTopology.lastIsMaster()),this.s.sCapabilities)}command(e,t,n,r){this.s.coreTopology.command(e.toString(),t,s.translate(n),r)}insert(e,t,n,r){this.s.coreTopology.insert(e.toString(),t,n,r)}update(e,t,n,r){this.s.coreTopology.update(e.toString(),t,n,r)}remove(e,t,n,r){this.s.coreTopology.remove(e.toString(),t,n,r)}isConnected(e){return e=e||{},e=s.translate(e),this.s.coreTopology.isConnected(e)}isDestroyed(){return this.s.coreTopology.isDestroyed()}cursor(e,t,n){return n=n||{},(n=s.translate(n)).disconnectHandler=this.s.store,n.topology=this,this.s.coreTopology.cursor(e,t,n)}lastIsMaster(){return this.s.coreTopology.lastIsMaster()}selectServer(e,t,n){return this.s.coreTopology.selectServer(e,t,n)}unref(){return this.s.coreTopology.unref()}connections(){return this.s.coreTopology.connections()}close(e,t){this.s.sessions.forEach(e=>e.endSession()),this.s.sessionPool&&this.s.sessionPool.endAllPooledSessions(),!0===e&&(this.s.storeOptions.force=e,this.s.store.flush()),this.s.coreTopology.destroy({force:"boolean"==typeof e&&e},t)}}Object.defineProperty(p.prototype,"bson",{enumerable:!0,get:function(){return this.s.coreTopology.s.bson}}),Object.defineProperty(p.prototype,"parserType",{enumerable:!0,get:function(){return this.s.coreTopology.parserType}}),Object.defineProperty(p.prototype,"logicalSessionTimeoutMinutes",{enumerable:!0,get:function(){return this.s.coreTopology.logicalSessionTimeoutMinutes}}),Object.defineProperty(p.prototype,"type",{enumerable:!0,get:function(){return this.s.coreTopology.type}}),t.Store=c,t.ServerCapabilities=f,t.TopologyBase=p},function(e,t,n){var r=n(19).Symbol;e.exports=r},function(e,t){e.exports=function(e){return function(t){return e(t)}}},function(e,t,n){var r=n(148),o=n(110);e.exports=function(e){return null!=e&&o(e.length)&&!r(e)}},function(e,t,n){var r=n(12),o=n(117),i=n(297),s=n(40);e.exports=function(e,t){return r(e)?e:o(e,t)?[e]:i(s(e))}},function(e,t,n){var r=n(300);e.exports=function(e){return null==e?"":r(e)}},function(e,t,n){var r=n(71);e.exports=function(e){if("string"==typeof e||r(e))return e;var t=e+"";return"0"==t&&1/e==-1/0?"-0":t}},function(e,t,n){"use strict";const r=n(2),o=n(447),i=n(59).connect;i.MongoError=r.MongoError,i.MongoNetworkError=r.MongoNetworkError,i.MongoTimeoutError=r.MongoTimeoutError,i.MongoServerSelectionError=r.MongoServerSelectionError,i.MongoParseError=r.MongoParseError,i.MongoWriteConcernError=r.MongoWriteConcernError,i.MongoBulkWriteError=n(141).BulkWriteError,i.BulkWriteError=i.MongoBulkWriteError,i.Admin=n(218),i.MongoClient=n(59),i.Db=n(98),i.Collection=n(61),i.Server=n(99),i.ReplSet=n(222),i.Mongos=n(221),i.ReadPreference=r.ReadPreference,i.GridStore=n(491),i.Chunk=n(227),i.Logger=r.Logger,i.AggregationCursor=n(142),i.CommandCursor=n(143),i.Cursor=n(26),i.GridFSBucket=n(492),i.CoreServer=r.Server,i.CoreConnection=r.Connection,i.Binary=r.BSON.Binary,i.Code=r.BSON.Code,i.Map=r.BSON.Map,i.DBRef=r.BSON.DBRef,i.Double=r.BSON.Double,i.Int32=r.BSON.Int32,i.Long=r.BSON.Long,i.MinKey=r.BSON.MinKey,i.MaxKey=r.BSON.MaxKey,i.ObjectID=r.BSON.ObjectID,i.ObjectId=r.BSON.ObjectID,i.Symbol=r.BSON.Symbol,i.Timestamp=r.BSON.Timestamp,i.BSONRegExp=r.BSON.BSONRegExp,i.Decimal128=r.BSON.Decimal128,i.connect=i,i.instrument=function(e,t){"function"==typeof e&&(t=e,e={});const n=new o;return n.instrument(i.MongoClient,t),n},e.exports=i},function(e,t){function n(e,t){if(!(this instanceof n))return new n(e,t);this._bsontype="Long",this.low_=0|e,this.high_=0|t}n.prototype.toInt=function(){return this.low_},n.prototype.toNumber=function(){return this.high_*n.TWO_PWR_32_DBL_+this.getLowBitsUnsigned()},n.prototype.toBigInt=function(){return BigInt(this.toString())},n.prototype.toJSON=function(){return this.toString()},n.prototype.toString=function(e){var t=e||10;if(t<2||36<t)throw Error("radix out of range: "+t);if(this.isZero())return"0";if(this.isNegative()){if(this.equals(n.MIN_VALUE)){var r=n.fromNumber(t),o=this.div(r),i=o.multiply(r).subtract(this);return o.toString(t)+i.toInt().toString(t)}return"-"+this.negate().toString(t)}var s=n.fromNumber(Math.pow(t,6));i=this;for(var a="";!i.isZero();){var c=i.div(s),u=i.subtract(c.multiply(s)).toInt().toString(t);if((i=c).isZero())return u+a;for(;u.length<6;)u="0"+u;a=""+u+a}},n.prototype.getHighBits=function(){return this.high_},n.prototype.getLowBits=function(){return this.low_},n.prototype.getLowBitsUnsigned=function(){return this.low_>=0?this.low_:n.TWO_PWR_32_DBL_+this.low_},n.prototype.getNumBitsAbs=function(){if(this.isNegative())return this.equals(n.MIN_VALUE)?64:this.negate().getNumBitsAbs();for(var e=0!==this.high_?this.high_:this.low_,t=31;t>0&&0==(e&1<<t);t--);return 0!==this.high_?t+33:t+1},n.prototype.isZero=function(){return 0===this.high_&&0===this.low_},n.prototype.isNegative=function(){return this.high_<0},n.prototype.isOdd=function(){return 1==(1&this.low_)},n.prototype.equals=function(e){return this.high_===e.high_&&this.low_===e.low_},n.prototype.notEquals=function(e){return this.high_!==e.high_||this.low_!==e.low_},n.prototype.lessThan=function(e){return this.compare(e)<0},n.prototype.lessThanOrEqual=function(e){return this.compare(e)<=0},n.prototype.greaterThan=function(e){return this.compare(e)>0},n.prototype.greaterThanOrEqual=function(e){return this.compare(e)>=0},n.prototype.compare=function(e){if(this.equals(e))return 0;var t=this.isNegative(),n=e.isNegative();return t&&!n?-1:!t&&n?1:this.subtract(e).isNegative()?-1:1},n.prototype.negate=function(){return this.equals(n.MIN_VALUE)?n.MIN_VALUE:this.not().add(n.ONE)},n.prototype.add=function(e){var t=this.high_>>>16,r=65535&this.high_,o=this.low_>>>16,i=65535&this.low_,s=e.high_>>>16,a=65535&e.high_,c=e.low_>>>16,u=0,l=0,f=0,p=0;return f+=(p+=i+(65535&e.low_))>>>16,p&=65535,l+=(f+=o+c)>>>16,f&=65535,u+=(l+=r+a)>>>16,l&=65535,u+=t+s,u&=65535,n.fromBits(f<<16|p,u<<16|l)},n.prototype.subtract=function(e){return this.add(e.negate())},n.prototype.multiply=function(e){if(this.isZero())return n.ZERO;if(e.isZero())return n.ZERO;if(this.equals(n.MIN_VALUE))return e.isOdd()?n.MIN_VALUE:n.ZERO;if(e.equals(n.MIN_VALUE))return this.isOdd()?n.MIN_VALUE:n.ZERO;if(this.isNegative())return e.isNegative()?this.negate().multiply(e.negate()):this.negate().multiply(e).negate();if(e.isNegative())return this.multiply(e.negate()).negate();if(this.lessThan(n.TWO_PWR_24_)&&e.lessThan(n.TWO_PWR_24_))return n.fromNumber(this.toNumber()*e.toNumber());var t=this.high_>>>16,r=65535&this.high_,o=this.low_>>>16,i=65535&this.low_,s=e.high_>>>16,a=65535&e.high_,c=e.low_>>>16,u=65535&e.low_,l=0,f=0,p=0,d=0;return p+=(d+=i*u)>>>16,d&=65535,f+=(p+=o*u)>>>16,p&=65535,f+=(p+=i*c)>>>16,p&=65535,l+=(f+=r*u)>>>16,f&=65535,l+=(f+=o*c)>>>16,f&=65535,l+=(f+=i*a)>>>16,f&=65535,l+=t*u+r*c+o*a+i*s,l&=65535,n.fromBits(p<<16|d,l<<16|f)},n.prototype.div=function(e){if(e.isZero())throw Error("division by zero");if(this.isZero())return n.ZERO;if(this.equals(n.MIN_VALUE)){if(e.equals(n.ONE)||e.equals(n.NEG_ONE))return n.MIN_VALUE;if(e.equals(n.MIN_VALUE))return n.ONE;var t=this.shiftRight(1).div(e).shiftLeft(1);if(t.equals(n.ZERO))return e.isNegative()?n.ONE:n.NEG_ONE;var r=this.subtract(e.multiply(t));return t.add(r.div(e))}if(e.equals(n.MIN_VALUE))return n.ZERO;if(this.isNegative())return e.isNegative()?this.negate().div(e.negate()):this.negate().div(e).negate();if(e.isNegative())return this.div(e.negate()).negate();var o=n.ZERO;for(r=this;r.greaterThanOrEqual(e);){t=Math.max(1,Math.floor(r.toNumber()/e.toNumber()));for(var i=Math.ceil(Math.log(t)/Math.LN2),s=i<=48?1:Math.pow(2,i-48),a=n.fromNumber(t),c=a.multiply(e);c.isNegative()||c.greaterThan(r);)t-=s,c=(a=n.fromNumber(t)).multiply(e);a.isZero()&&(a=n.ONE),o=o.add(a),r=r.subtract(c)}return o},n.prototype.modulo=function(e){return this.subtract(this.div(e).multiply(e))},n.prototype.not=function(){return n.fromBits(~this.low_,~this.high_)},n.prototype.and=function(e){return n.fromBits(this.low_&e.low_,this.high_&e.high_)},n.prototype.or=function(e){return n.fromBits(this.low_|e.low_,this.high_|e.high_)},n.prototype.xor=function(e){return n.fromBits(this.low_^e.low_,this.high_^e.high_)},n.prototype.shiftLeft=function(e){if(0===(e&=63))return this;var t=this.low_;if(e<32){var r=this.high_;return n.fromBits(t<<e,r<<e|t>>>32-e)}return n.fromBits(0,t<<e-32)},n.prototype.shiftRight=function(e){if(0===(e&=63))return this;var t=this.high_;if(e<32){var r=this.low_;return n.fromBits(r>>>e|t<<32-e,t>>e)}return n.fromBits(t>>e-32,t>=0?0:-1)},n.prototype.shiftRightUnsigned=function(e){if(0===(e&=63))return this;var t=this.high_;if(e<32){var r=this.low_;return n.fromBits(r>>>e|t<<32-e,t>>>e)}return 32===e?n.fromBits(t,0):n.fromBits(t>>>e-32,0)},n.fromInt=function(e){if(-128<=e&&e<128){var t=n.INT_CACHE_[e];if(t)return t}var r=new n(0|e,e<0?-1:0);return-128<=e&&e<128&&(n.INT_CACHE_[e]=r),r},n.fromNumber=function(e){return isNaN(e)||!isFinite(e)?n.ZERO:e<=-n.TWO_PWR_63_DBL_?n.MIN_VALUE:e+1>=n.TWO_PWR_63_DBL_?n.MAX_VALUE:e<0?n.fromNumber(-e).negate():new n(e%n.TWO_PWR_32_DBL_|0,e/n.TWO_PWR_32_DBL_|0)},n.fromBigInt=function(e){return n.fromString(e.toString(10),10)},n.fromBits=function(e,t){return new n(e,t)},n.fromString=function(e,t){if(0===e.length)throw Error("number format error: empty string");var r=t||10;if(r<2||36<r)throw Error("radix out of range: "+r);if("-"===e.charAt(0))return n.fromString(e.substring(1),r).negate();if(e.indexOf("-")>=0)throw Error('number format error: interior "-" character: '+e);for(var o=n.fromNumber(Math.pow(r,8)),i=n.ZERO,s=0;s<e.length;s+=8){var a=Math.min(8,e.length-s),c=parseInt(e.substring(s,s+a),r);if(a<8){var u=n.fromNumber(Math.pow(r,a));i=i.multiply(u).add(n.fromNumber(c))}else i=(i=i.multiply(o)).add(n.fromNumber(c))}return i},n.INT_CACHE_={},n.TWO_PWR_16_DBL_=65536,n.TWO_PWR_24_DBL_=1<<24,n.TWO_PWR_32_DBL_=n.TWO_PWR_16_DBL_*n.TWO_PWR_16_DBL_,n.TWO_PWR_31_DBL_=n.TWO_PWR_32_DBL_/2,n.TWO_PWR_48_DBL_=n.TWO_PWR_32_DBL_*n.TWO_PWR_16_DBL_,n.TWO_PWR_64_DBL_=n.TWO_PWR_32_DBL_*n.TWO_PWR_32_DBL_,n.TWO_PWR_63_DBL_=n.TWO_PWR_64_DBL_/2,n.ZERO=n.fromInt(0),n.ONE=n.fromInt(1),n.NEG_ONE=n.fromInt(-1),n.MAX_VALUE=n.fromBits(-1,2147483647),n.MIN_VALUE=n.fromBits(0,-2147483648),n.TWO_PWR_24_=n.fromInt(1<<24),e.exports=n,e.exports.Long=n},function(e,t,n){"use strict";const r=n(4).arrayStrictEqual,o=n(4).tagsStrictEqual,i=n(4).errorStrictEqual,s=n(13).ServerType,a=n(0).now,c=new Set([s.RSPrimary,s.Standalone,s.Mongos]),u=new Set([s.RSPrimary,s.RSSecondary,s.Mongos,s.Standalone]),l=["minWireVersion","maxWireVersion","maxBsonObjectSize","maxMessageSizeBytes","maxWriteBatchSize","compression","me","hosts","passives","arbiters","tags","setName","setVersion","electionId","primary","logicalSessionTimeoutMinutes","saslSupportedMechs","__nodejs_mock_server__","$clusterTime"];function f(e){return e&&e.ok?e.isreplicaset?s.RSGhost:e.msg&&"isdbgrid"===e.msg?s.Mongos:e.setName?e.hidden?s.RSOther:e.ismaster?s.RSPrimary:e.secondary?s.RSSecondary:e.arbiterOnly?s.RSArbiter:s.RSOther:s.Standalone:s.Unknown}function p(e,t){return null==e||null==t?-1:e.processId.equals(t.processId)?e.counter===t.counter?0:e.counter<t.counter?-1:1:-1}e.exports={ServerDescription:class{constructor(e,t,n){n=n||{},t=Object.assign({minWireVersion:0,maxWireVersion:0,hosts:[],passives:[],arbiters:[],tags:[]},t),this.address=e,this.error=n.error,this.roundTripTime=n.roundTripTime||-1,this.lastUpdateTime=a(),this.lastWriteDate=t.lastWrite?t.lastWrite.lastWriteDate:null,this.opTime=t.lastWrite?t.lastWrite.opTime:null,this.type=f(t),this.topologyVersion=n.topologyVersion||t.topologyVersion,l.forEach(e=>{void 0!==t[e]&&(this[e]=t[e])}),this.me&&(this.me=this.me.toLowerCase()),this.hosts=this.hosts.map(e=>e.toLowerCase()),this.passives=this.passives.map(e=>e.toLowerCase()),this.arbiters=this.arbiters.map(e=>e.toLowerCase())}get allHosts(){return this.hosts.concat(this.arbiters).concat(this.passives)}get isReadable(){return this.type===s.RSSecondary||this.isWritable}get isDataBearing(){return u.has(this.type)}get isWritable(){return c.has(this.type)}get host(){const e=`:${this.port}`.length;return this.address.slice(0,-e)}get port(){const e=this.address.split(":").pop();return e?Number.parseInt(e,10):e}equals(e){const t=this.topologyVersion===e.topologyVersion||0===p(this.topologyVersion,e.topologyVersion);return null!=e&&i(this.error,e.error)&&this.type===e.type&&this.minWireVersion===e.minWireVersion&&this.me===e.me&&r(this.hosts,e.hosts)&&o(this.tags,e.tags)&&this.setName===e.setName&&this.setVersion===e.setVersion&&(this.electionId?e.electionId&&this.electionId.equals(e.electionId):this.electionId===e.electionId)&&this.primary===e.primary&&this.logicalSessionTimeoutMinutes===e.logicalSessionTimeoutMinutes&&t}},parseServerType:f,compareTopologyVersion:p}},function(e,t,n){"use strict";const r=n(22).Buffer,o=n(6).opcodes,i=n(6).databaseNamespace,s=n(10),a=n(3).MongoError;let c=0;class u{constructor(e,t,n,r){if(null==n)throw new Error("query must be specified for query");this.bson=e,this.ns=t,this.command=n,this.command.$db=i(t),r.readPreference&&r.readPreference.mode!==s.PRIMARY&&(this.command.$readPreference=r.readPreference.toJSON()),this.options=r||{},this.requestId=r.requestId?r.requestId:u.getRequestId(),this.serializeFunctions="boolean"==typeof r.serializeFunctions&&r.serializeFunctions,this.ignoreUndefined="boolean"==typeof r.ignoreUndefined&&r.ignoreUndefined,this.checkKeys="boolean"==typeof r.checkKeys&&r.checkKeys,this.maxBsonSize=r.maxBsonSize||16777216,this.checksumPresent=!1,this.moreToCome=r.moreToCome||!1,this.exhaustAllowed="boolean"==typeof r.exhaustAllowed&&r.exhaustAllowed}toBin(){const e=[];let t=0;this.checksumPresent&&(t|=1),this.moreToCome&&(t|=2),this.exhaustAllowed&&(t|=65536);const n=r.alloc(20);e.push(n);let i=n.length;const s=this.command;return i+=this.makeDocumentSegment(e,s),n.writeInt32LE(i,0),n.writeInt32LE(this.requestId,4),n.writeInt32LE(0,8),n.writeInt32LE(o.OP_MSG,12),n.writeUInt32LE(t,16),e}makeDocumentSegment(e,t){const n=r.alloc(1);n[0]=0;const o=this.serializeBson(t);return e.push(n),e.push(o),n.length+o.length}serializeBson(e){return this.bson.serialize(e,{checkKeys:this.checkKeys,serializeFunctions:this.serializeFunctions,ignoreUndefined:this.ignoreUndefined})}}u.getRequestId=function(){return c=c+1&2147483647,c};e.exports={Msg:u,BinMsg:class{constructor(e,t,n,r,o){o=o||{promoteLongs:!0,promoteValues:!0,promoteBuffers:!1},this.parsed=!1,this.raw=t,this.data=r,this.bson=e,this.opts=o,this.length=n.length,this.requestId=n.requestId,this.responseTo=n.responseTo,this.opCode=n.opCode,this.fromCompressed=n.fromCompressed,this.responseFlags=r.readInt32LE(0),this.checksumPresent=0!=(1&this.responseFlags),this.moreToCome=0!=(2&this.responseFlags),this.exhaustAllowed=0!=(65536&this.responseFlags),this.promoteLongs="boolean"!=typeof o.promoteLongs||o.promoteLongs,this.promoteValues="boolean"!=typeof o.promoteValues||o.promoteValues,this.promoteBuffers="boolean"==typeof o.promoteBuffers&&o.promoteBuffers,this.documents=[]}isParsed(){return this.parsed}parse(e){if(this.parsed)return;e=e||{},this.index=4;const t=e.raw||!1,n=e.documentsReturnedIn||null,r={promoteLongs:"boolean"==typeof e.promoteLongs?e.promoteLongs:this.opts.promoteLongs,promoteValues:"boolean"==typeof e.promoteValues?e.promoteValues:this.opts.promoteValues,promoteBuffers:"boolean"==typeof e.promoteBuffers?e.promoteBuffers:this.opts.promoteBuffers};for(;this.index<this.data.length;){const e=this.data.readUInt8(this.index++);if(1===e)throw new a("OP_MSG Payload Type 1 detected unsupported protocol");if(0===e){const e=this.data.readUInt32LE(this.index),n=this.data.slice(this.index,this.index+e);this.documents.push(t?n:this.bson.deserialize(n,r)),this.index+=e}}if(1===this.documents.length&&null!=n&&t){const e={};e[n]=!0,r.fieldsAsRaw=e;const t=this.bson.deserialize(this.documents[0],r);this.documents=[t]}this.parsed=!0}}}},function(e,t,n){"use strict";class r{constructor(e){null!=e&&(this.level=e)}static fromOptions(e){if(null!=e)return e.readConcern?e.readConcern instanceof r?e.readConcern:new r(e.readConcern.level):e.level?new r(e.level):void 0}static get MAJORITY(){return"majority"}static get AVAILABLE(){return"available"}static get LINEARIZABLE(){return"linearizable"}static get SNAPSHOT(){return"snapshot"}}e.exports=r},function(e,t,n){"use strict";var r=n(92),o=Object.keys||function(e){var t=[];for(var n in e)t.push(n);return t};e.exports=f;var i=Object.create(n(57));i.inherits=n(58);var s=n(203),a=n(206);i.inherits(f,s);for(var c=o(a.prototype),u=0;u<c.length;u++){var l=c[u];f.prototype[l]||(f.prototype[l]=a.prototype[l])}function f(e){if(!(this instanceof f))return new f(e);s.call(this,e),a.call(this,e),e&&!1===e.readable&&(this.readable=!1),e&&!1===e.writable&&(this.writable=!1),this.allowHalfOpen=!0,e&&!1===e.allowHalfOpen&&(this.allowHalfOpen=!1),this.once("end",p)}function p(){this.allowHalfOpen||this._writableState.ended||r.nextTick(d,this)}function d(e){e.end()}Object.defineProperty(f.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Object.defineProperty(f.prototype,"destroyed",{get:function(){return void 0!==this._readableState&&void 0!==this._writableState&&(this._readableState.destroyed&&this._writableState.destroyed)},set:function(e){void 0!==this._readableState&&void 0!==this._writableState&&(this._readableState.destroyed=e,this._writableState.destroyed=e)}}),f.prototype._destroy=function(e,t){this.push(null),this.end(),r.nextTick(t,e)}},function(e,t,n){var r=n(106),o=n(107);e.exports=function(e,t,n,i){var s=!n;n||(n={});for(var a=-1,c=t.length;++a<c;){var u=t[a],l=i?i(n[u],e[u],u,n,e):void 0;void 0===l&&(l=e[u]),s?o(n,u,l):r(n,u,l)}return n}},function(e,t,n){var r=n(152),o=n(271),i=n(38);e.exports=function(e){return i(e)?r(e):o(e)}},function(e,t,n){var r=n(39),o=n(41);e.exports=function(e,t){for(var n=0,i=(t=r(t,e)).length;null!=e&&n<i;)e=e[o(t[n++])];return n&&n==i?e:void 0}},function(e,t){e.exports=function(e,t){for(var n=-1,r=null==e?0:e.length,o=Array(r);++n<r;)o[n]=t(e[n],n,e);return o}},function(e,t){e.exports=function(e){for(var t=-1,n=null==e?0:e.length,r=0,o=[];++t<n;){var i=e[t];i&&(o[r++]=i)}return o}},function(e,t,n){if("undefined"!=typeof global)var r=n(131).Buffer;var o=n(32);function i(e,t){if(!(this instanceof i))return new i(e,t);if(!(null==e||"string"==typeof e||r.isBuffer(e)||e instanceof Uint8Array||Array.isArray(e)))throw new Error("only String, Buffer, Uint8Array or Array accepted");if(this._bsontype="Binary",e instanceof Number?(this.sub_type=e,this.position=0):(this.sub_type=null==t?s:t,this.position=0),null==e||e instanceof Number)void 0!==r?this.buffer=o.allocBuffer(i.BUFFER_SIZE):"undefined"!=typeof Uint8Array?this.buffer=new Uint8Array(new ArrayBuffer(i.BUFFER_SIZE)):this.buffer=new Array(i.BUFFER_SIZE),this.position=0;else{if("string"==typeof e)if(void 0!==r)this.buffer=o.toBuffer(e);else{if("undefined"==typeof Uint8Array&&"[object Array]"!==Object.prototype.toString.call(e))throw new Error("only String, Buffer, Uint8Array or Array accepted");this.buffer=a(e)}else this.buffer=e;this.position=e.length}}i.prototype.put=function(e){if(null!=e.length&&"number"!=typeof e&&1!==e.length)throw new Error("only accepts single character String, Uint8Array or Array");if("number"!=typeof e&&e<0||e>255)throw new Error("only accepts number in a valid unsigned byte range 0-255");var t=null;if(t="string"==typeof e?e.charCodeAt(0):null!=e.length?e[0]:e,this.buffer.length>this.position)this.buffer[this.position++]=t;else if(void 0!==r&&r.isBuffer(this.buffer)){var n=o.allocBuffer(i.BUFFER_SIZE+this.buffer.length);this.buffer.copy(n,0,0,this.buffer.length),this.buffer=n,this.buffer[this.position++]=t}else{n=null,n="[object Uint8Array]"===Object.prototype.toString.call(this.buffer)?new Uint8Array(new ArrayBuffer(i.BUFFER_SIZE+this.buffer.length)):new Array(i.BUFFER_SIZE+this.buffer.length);for(var s=0;s<this.buffer.length;s++)n[s]=this.buffer[s];this.buffer=n,this.buffer[this.position++]=t}},i.prototype.write=function(e,t){if(t="number"==typeof t?t:this.position,this.buffer.length<t+e.length){var n=null;if(void 0!==r&&r.isBuffer(this.buffer))n=o.allocBuffer(this.buffer.length+e.length),this.buffer.copy(n,0,0,this.buffer.length);else if("[object Uint8Array]"===Object.prototype.toString.call(this.buffer)){n=new Uint8Array(new ArrayBuffer(this.buffer.length+e.length));for(var i=0;i<this.position;i++)n[i]=this.buffer[i]}this.buffer=n}if(void 0!==r&&r.isBuffer(e)&&r.isBuffer(this.buffer))e.copy(this.buffer,t,0,e.length),this.position=t+e.length>this.position?t+e.length:this.position;else if(void 0!==r&&"string"==typeof e&&r.isBuffer(this.buffer))this.buffer.write(e,t,"binary"),this.position=t+e.length>this.position?t+e.length:this.position;else if("[object Uint8Array]"===Object.prototype.toString.call(e)||"[object Array]"===Object.prototype.toString.call(e)&&"string"!=typeof e){for(i=0;i<e.length;i++)this.buffer[t++]=e[i];this.position=t>this.position?t:this.position}else if("string"==typeof e){for(i=0;i<e.length;i++)this.buffer[t++]=e.charCodeAt(i);this.position=t>this.position?t:this.position}},i.prototype.read=function(e,t){if(t=t&&t>0?t:this.position,this.buffer.slice)return this.buffer.slice(e,e+t);for(var n="undefined"!=typeof Uint8Array?new Uint8Array(new ArrayBuffer(t)):new Array(t),r=0;r<t;r++)n[r]=this.buffer[e++];return n},i.prototype.value=function(e){if((e=null!=e&&e)&&void 0!==r&&r.isBuffer(this.buffer)&&this.buffer.length===this.position)return this.buffer;if(void 0!==r&&r.isBuffer(this.buffer))return e?this.buffer.slice(0,this.position):this.buffer.toString("binary",0,this.position);if(e){if(null!=this.buffer.slice)return this.buffer.slice(0,this.position);for(var t="[object Uint8Array]"===Object.prototype.toString.call(this.buffer)?new Uint8Array(new ArrayBuffer(this.position)):new Array(this.position),n=0;n<this.position;n++)t[n]=this.buffer[n];return t}return c(this.buffer,0,this.position)},i.prototype.length=function(){return this.position},i.prototype.toJSON=function(){return null!=this.buffer?this.buffer.toString("base64"):""},i.prototype.toString=function(e){return null!=this.buffer?this.buffer.slice(0,this.position).toString(e):""};var s=0,a=function(e){for(var t="undefined"!=typeof Uint8Array?new Uint8Array(new ArrayBuffer(e.length)):new Array(e.length),n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t},c=function(e,t,n){for(var r="",o=t;o<n;o++)r+=String.fromCharCode(e[o]);return r};i.BUFFER_SIZE=256,i.SUBTYPE_DEFAULT=0,i.SUBTYPE_FUNCTION=1,i.SUBTYPE_BYTE_ARRAY=2,i.SUBTYPE_UUID_OLD=3,i.SUBTYPE_UUID=4,i.SUBTYPE_MD5=5,i.SUBTYPE_USER_DEFINED=128,e.exports=i,e.exports.Binary=i},function(e,t,n){"use strict";const r=n(3).MongoError,o=n(10),i=n(46),s=n(29);let a,c;a={NO_TRANSACTION:"NO_TRANSACTION",STARTING_TRANSACTION:"STARTING_TRANSACTION",TRANSACTION_IN_PROGRESS:"TRANSACTION_IN_PROGRESS",TRANSACTION_COMMITTED:"TRANSACTION_COMMITTED",TRANSACTION_COMMITTED_EMPTY:"TRANSACTION_COMMITTED_EMPTY",TRANSACTION_ABORTED:"TRANSACTION_ABORTED"},c={NO_TRANSACTION:["NO_TRANSACTION","STARTING_TRANSACTION"],STARTING_TRANSACTION:["TRANSACTION_IN_PROGRESS","TRANSACTION_COMMITTED","TRANSACTION_COMMITTED_EMPTY","TRANSACTION_ABORTED"],TRANSACTION_IN_PROGRESS:["TRANSACTION_IN_PROGRESS","TRANSACTION_COMMITTED","TRANSACTION_ABORTED"],TRANSACTION_COMMITTED:["TRANSACTION_COMMITTED","TRANSACTION_COMMITTED_EMPTY","STARTING_TRANSACTION","NO_TRANSACTION"],TRANSACTION_ABORTED:["STARTING_TRANSACTION","NO_TRANSACTION"],TRANSACTION_COMMITTED_EMPTY:["TRANSACTION_COMMITTED_EMPTY","NO_TRANSACTION"]};e.exports={TxnState:a,Transaction:class{constructor(e){e=e||{},this.state=a.NO_TRANSACTION,this.options={};const t=s.fromOptions(e);if(t){if(t.w<=0)throw new r("Transactions do not support unacknowledged write concern");this.options.writeConcern=t}e.readConcern&&(this.options.readConcern=i.fromOptions(e)),e.readPreference&&(this.options.readPreference=o.fromOptions(e)),e.maxCommitTimeMS&&(this.options.maxTimeMS=e.maxCommitTimeMS),this._pinnedServer=void 0,this._recoveryToken=void 0}get server(){return this._pinnedServer}get recoveryToken(){return this._recoveryToken}get isPinned(){return!!this.server}get isActive(){return-1!==[a.STARTING_TRANSACTION,a.TRANSACTION_IN_PROGRESS].indexOf(this.state)}transition(e){const t=c[this.state];if(t&&-1!==t.indexOf(e))return this.state=e,void(this.state!==a.NO_TRANSACTION&&this.state!==a.STARTING_TRANSACTION||this.unpinServer());throw new r(`Attempted illegal state transition from [${this.state}] to [${e}]`)}pinServer(e){this.isActive&&(this._pinnedServer=e)}unpinServer(){this._pinnedServer=void 0}},isTransactionCommand:function(e){return!(!e.commitTransaction&&!e.abortTransaction)}}},function(e,t,n){"use strict";const r=n(21).Query,o=n(45).Msg,i=n(3).MongoError,s=n(6).getReadPreference,a=n(6).isSharded,c=n(6).databaseNamespace,u=n(54).isTransactionCommand,l=n(34).applySession,f=n(3).MongoNetworkError,p=n(4).maxWireVersion;function d(e,t,n,p,d){const h=e.s.bson,m=e.s.pool,g=s(n,p),y=function(e){const t=e.ismaster?e.ismaster:e.description;if(null==t)return!1;return t.maxWireVersion>=6&&null==t.__nodejs_mock_server__}(e),b=p.session;let v=e.clusterTime,S=Object.assign({},n);if(function(e){if(null==e)return!1;if(e.description)return e.description.maxWireVersion>=6;return null!=e.ismaster&&e.ismaster.maxWireVersion>=6}(e)&&b){b.clusterTime&&b.clusterTime.clusterTime.greaterThan(v.clusterTime)&&(v=b.clusterTime);const e=l(b,S,p);if(e)return d(e)}v&&(S.$clusterTime=v),a(e)&&!y&&g&&"primary"!==g.mode&&(S={$query:S,$readPreference:g.toJSON()});const w=Object.assign({command:!0,numberToSkip:0,numberToReturn:-1,checkKeys:!1},p);w.slaveOk=g.slaveOk();const _=`${c(t)}.$cmd`,O=y?new o(h,_,S,w):new r(h,_,S,w),T=b&&(b.inTransaction()||u(S))?function(e){return e&&e instanceof f&&!e.hasErrorLabel("TransientTransactionError")&&e.addErrorLabel("TransientTransactionError"),!n.commitTransaction&&e&&e instanceof i&&e.hasErrorLabel("TransientTransactionError")&&b.transaction.unpinServer(),d.apply(null,arguments)}:d;try{m.write(O,w,T)}catch(e){T(e)}}e.exports=function(e,t,n,r,o){if("function"==typeof r&&(o=r,r={}),r=r||{},null==n)return o(new i(`command ${JSON.stringify(n)} does not return a cursor`));if(!function(e){return p(e)&&e.autoEncrypter}(e))return void d(e,t,n,r,o);const s=p(e);"number"!=typeof s||s<8?o(new i("Auto-encryption requires a minimum MongoDB version of 4.2")):function(e,t,n,r,o){const i=e.autoEncrypter;function s(e,t){e||null==t?o(e,t):i.decrypt(t.result,r,(e,n)=>{e?o(e,null):(t.result=n,t.message.documents=[n],o(null,t))})}i.encrypt(t,n,r,(n,i)=>{n?o(n,null):d(e,t,i,r,s)})}(e,t,n,r,o)}},function(e,t,n){"use strict";const r=n(0).maybePromise,o=n(3).MongoError,i=n(1).Aspect,s=n(1).OperationBase,a=n(10),c=n(3).isRetryableError,u=n(4).maxWireVersion,l=n(4).isUnifiedTopology;function f(e,t,n){if(null==e)throw new TypeError("This method requires a valid topology instance");if(!(t instanceof s))throw new TypeError("This method requires a valid operation instance");return r(e,n,n=>{if(l(e)&&e.shouldCheckForSessionSupport())return function(e,t,n){e.selectServer(a.primaryPreferred,r=>{if(r)return n(r);f(e,t,n)})}(e,t,n);let r,s;if(e.hasSessionSupport()){if(null==t.session)s=Symbol(),r=e.startSession({owner:s}),t.session=r;else if(t.session.hasEnded)return n(new o("Use of expired sessions is not permitted"))}else if(t.session)return n(new o("Current topology does not support sessions"));function u(e,o){r&&r.owner===s&&(r.endSession(),t.session===r&&t.clearSession()),n(e,o)}try{t.hasAspect(i.EXECUTE_WITH_SELECTION)?function(e,t,n){const r=t.readPreference||a.primary,s=t.session&&t.session.inTransaction();if(s&&!r.equals(a.primary))return void n(new o(`Read preference in a transaction must be primary, not: ${r.mode}`));const u={readPreference:r,session:t.session};function l(r,o){return null==r?n(null,o):c(r)?void e.selectServer(u,(e,r)=>{!e&&p(r)?t.execute(r,n):n(e,null)}):n(r)}e.selectServer(u,(r,o)=>{if(r)return void n(r,null);const a=!1!==e.s.options.retryReads&&t.session&&!s&&p(o)&&t.canRetryRead;t.hasAspect(i.RETRYABLE)&&a?t.execute(o,l):t.execute(o,n)})}(e,t,u):t.execute(u)}catch(e){r&&r.owner===s&&(r.endSession(),t.session===r&&t.clearSession()),n(e)}})}function p(e){return u(e)>=6}e.exports=f},function(e,t){function n(e){return Object.prototype.toString.call(e)}t.isArray=function(e){return Array.isArray?Array.isArray(e):"[object Array]"===n(e)},t.isBoolean=function(e){return"boolean"==typeof e},t.isNull=function(e){return null===e},t.isNullOrUndefined=function(e){return null==e},t.isNumber=function(e){return"number"==typeof e},t.isString=function(e){return"string"==typeof e},t.isSymbol=function(e){return"symbol"==typeof e},t.isUndefined=function(e){return void 0===e},t.isRegExp=function(e){return"[object RegExp]"===n(e)},t.isObject=function(e){return"object"==typeof e&&null!==e},t.isDate=function(e){return"[object Date]"===n(e)},t.isError=function(e){return"[object Error]"===n(e)||e instanceof Error},t.isFunction=function(e){return"function"==typeof e},t.isPrimitive=function(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||void 0===e},t.isBuffer=Buffer.isBuffer},function(e,t,n){try{var r=n(5);if("function"!=typeof r.inherits)throw"";e.exports=r.inherits}catch(t){e.exports=n(437)}},function(e,t,n){"use strict";const r=n(139),o=n(98),i=n(8).EventEmitter,s=n(5).inherits,a=n(2).MongoError,c=n(5).deprecate,u=n(29),l=n(0).MongoDBNamespace,f=n(10),p=n(0).maybePromise,d=n(219),h=n(220).connect,m=n(220).validOptions;function g(e,t){if(!(this instanceof g))return new g(e,t);i.call(this),t&&t.autoEncryption&&n(223),this.s={url:e,options:t||{},promiseLibrary:t&&t.promiseLibrary||Promise,dbCache:new Map,sessions:new Set,writeConcern:u.fromOptions(t),readPreference:f.fromOptions(t)||f.primary,namespace:new l("admin")}}s(g,i),Object.defineProperty(g.prototype,"writeConcern",{enumerable:!0,get:function(){return this.s.writeConcern}}),Object.defineProperty(g.prototype,"readPreference",{enumerable:!0,get:function(){return this.s.readPreference}}),g.prototype.connect=function(e){if("string"==typeof e)throw new TypeError("`connect` only accepts a callback");const t=this;return p(this,e,e=>{const n=m(t.s.options);if(n)return e(n);h(t,t.s.url,t.s.options,n=>{if(n)return e(n);e(null,t)})})},g.prototype.logout=c((function(e,t){"function"==typeof e&&(t=e,e={}),"function"==typeof t&&t(null,!0)}),"Multiple authentication is prohibited on a connected client, please only authenticate once per MongoClient"),g.prototype.close=function(e,t){"function"==typeof e&&(t=e,e=!1);const n=this;return p(this,t,t=>{const r=e=>{if(n.emit("close",n),!(n.topology instanceof d))for(const e of n.s.dbCache)e[1].emit("close",n);n.removeAllListeners("close"),t(e)};null!=n.topology?n.topology.close(e,t=>{const o=n.topology.s.options.encrypter;if(o)return o.close(n,e,e=>{r(t||e)});r(t)}):r()})},g.prototype.db=function(e,t){t=t||{},e||(e=this.s.options.dbName);const n=Object.assign({},this.s.options,t);if(this.s.dbCache.has(e)&&!0!==n.returnNonCachedInstance)return this.s.dbCache.get(e);if(n.promiseLibrary=this.s.promiseLibrary,!this.topology)throw new a("MongoClient must be connected before calling MongoClient.prototype.db");const r=new o(e,this.topology,n);return this.s.dbCache.set(e,r),r},g.prototype.isConnected=function(e){return e=e||{},!!this.topology&&this.topology.isConnected(e)},g.connect=function(e,t,n){const r=Array.prototype.slice.call(arguments,1);n="function"==typeof r[r.length-1]?r.pop():void 0;const o=new g(e,t=(t=r.length?r.shift():null)||{});return o.connect(n)},g.prototype.startSession=function(e){if(e=Object.assign({explicit:!0},e),!this.topology)throw new a("Must connect to a server before calling this method");return this.topology.startSession(e,this.s.options)},g.prototype.withSession=function(e,t){"function"==typeof e&&(t=e,e=void 0);const n=this.startSession(e);let r=(e,t,o)=>{if(r=()=>{throw new ReferenceError("cleanupHandler was called too many times")},o=Object.assign({throw:!0},o),n.endSession(),e){if(o.throw)throw e;return Promise.reject(e)}};try{const e=t(n);return Promise.resolve(e).then(e=>r(null,e)).catch(e=>r(e,null,{throw:!0}))}catch(e){return r(e,null,{throw:!1})}},g.prototype.watch=function(e,t){return e=e||[],t=t||{},Array.isArray(e)||(t=e,e=[]),new r(this,e,t)},g.prototype.getLogger=function(){return this.s.options.logger},e.exports=g},function(e,t,n){"use strict";const r=n(0).applyWriteConcern,o=n(2).BSON.Code,i=n(11).createIndex,s=n(0).decorateWithCollation,a=n(0).decorateWithReadConcern,c=n(11).ensureIndex,u=n(11).evaluate,l=n(11).executeCommand,f=n(0).handleCallback,p=n(11).indexInformation,d=n(2).BSON.Long,h=n(2).MongoError,m=n(2).ReadPreference,g=n(14).insertDocuments,y=n(14).updateDocuments;function b(e,t,n){p(e.s.db,e.collectionName,t,n)}e.exports={createIndex:function(e,t,n,r){i(e.s.db,e.collectionName,t,n,r)},createIndexes:function(e,t,n,r){const o=e.s.topology.capabilities();for(let e=0;e<t.length;e++)if(null==t[e].name){const n=[];if(t[e].collation&&o&&!o.commandsTakeCollation)return r(new h("server/primary/mongos does not support collation"));for(let r in t[e].key)n.push(`${r}_${t[e].key[r]}`);t[e].name=n.join("_")}n=Object.assign({},n,{readPreference:m.PRIMARY}),l(e.s.db,{createIndexes:e.collectionName,indexes:t},n,r)},ensureIndex:function(e,t,n,r){c(e.s.db,e.collectionName,t,n,r)},group:function(e,t,n,r,i,c,p,d,h){if(p){const u=i&&"Code"===i._bsontype?i:new o(i),p={group:{ns:e.collectionName,$reduce:u,cond:n,initial:r,out:"inline"}};if(null!=c&&(p.group.finalize=c),"function"==typeof t||t&&"Code"===t._bsontype)p.group.$keyf=t&&"Code"===t._bsontype?t:new o(t);else{const e={};t.forEach(t=>{e[t]=1}),p.group.key=e}(d=Object.assign({},d)).readPreference=m.resolve(e,d),a(p,e,d);try{s(p,e,d)}catch(e){return h(e,null)}l(e.s.db,p,d,(e,t)=>{if(e)return f(h,e,null);f(h,null,t.retval)})}else{const s=null!=i&&"Code"===i._bsontype?i.scope:{};s.ns=e.collectionName,s.keys=t,s.condition=n,s.initial=r;const a='function () {\nvar c = db[ns].find(condition);\nvar map = new Map();\nvar reduce_function = reduce;\n\nwhile (c.hasNext()) {\nvar obj = c.next();\nvar key = {};\n\nfor (var i = 0, len = keys.length; i < len; ++i) {\nvar k = keys[i];\nkey[k] = obj[k];\n}\n\nvar aggObj = map.get(key);\n\nif (aggObj == null) {\nvar newObj = Object.extend({}, key);\naggObj = Object.extend(newObj, initial);\nmap.put(key, aggObj);\n}\n\nreduce_function(obj, aggObj);\n}\n\nreturn { "result": map.values() };\n}'.replace(/ reduce;/,i.toString()+";");u(e.s.db,new o(a,s),null,d,(e,t)=>{if(e)return f(h,e,null);f(h,null,t.result||t)})}},indexes:function(e,t,n){t=Object.assign({},{full:!0},t),p(e.s.db,e.collectionName,t,n)},indexExists:function(e,t,n,r){b(e,n,(e,n)=>{if(null!=e)return f(r,e,null);if(!Array.isArray(t))return f(r,null,null!=n[t]);for(let e=0;e<t.length;e++)if(null==n[t[e]])return f(r,null,!1);return f(r,null,!0)})},indexInformation:b,parallelCollectionScan:function(e,t,n){const r={parallelCollectionScan:e.collectionName,numCursors:t.numCursors};a(r,e,t);const o=t.raw;delete t.raw,l(e.s.db,r,t,(r,i)=>{if(r)return f(n,r,null);if(null==i)return f(n,new Error("no result returned for parallelCollectionScan"),null);t=Object.assign({explicitlyIgnoreSession:!0},t);const s=[];o&&(t.raw=o);for(let n=0;n<i.cursors.length;n++){const r=i.cursors[n].cursor.id,o="number"==typeof r?d.fromNumber(r):r;s.push(e.s.topology.cursor(e.namespace,o,t))}f(n,null,s)})},save:function(e,t,n,o){const i=r(Object.assign({},n),{db:e.s.db,collection:e},n);if(null!=t._id)return i.upsert=!0,y(e,{_id:t._id},t,i,o);g(e,[t],i,(e,n)=>{if(null!=o)return null==t?f(o,null,null):e?f(o,e,null):void f(o,null,n)})}}},function(e,t,n){"use strict";const r=n(5).deprecate,o=n(0).deprecateOptions,i=n(0).emitWarningOnce,s=n(0).checkCollectionName,a=n(2).BSON.ObjectID,c=n(2).MongoError,u=n(0).normalizeHintField,l=n(0).decorateCommand,f=n(0).decorateWithCollation,p=n(0).decorateWithReadConcern,d=n(0).formattedOrderClause,h=n(2).ReadPreference,m=n(450),g=n(451),y=n(139),b=n(0).executeLegacyOperation,v=n(29),S=n(46),w=n(0).MongoDBNamespace,_=n(142),O=n(143),T=n(60).ensureIndex,C=n(60).group,x=n(60).parallelCollectionScan,E=n(14).removeDocuments,N=n(60).save,I=n(14).updateDocuments,A=n(96),k=n(209),M=n(452),R=n(210),j=n(453),D=n(454),P=n(455),B=n(144).DropCollectionOperation,L=n(211),q=n(456),U=n(457),z=n(458),$=n(459),W=n(97),F=n(460),V=n(461),K=n(462),H=n(463),Y=n(464),G=n(465),J=n(212),X=n(466),Z=n(467),Q=n(468),ee=n(469),te=n(470),ne=n(213),re=n(217),oe=n(479),ie=n(480),se=n(481),ae=n(482),ce=n(483),ue=n(56),le=["ignoreUndefined"];function fe(e,t,n,r,o,i){s(r);const c=null==i||null==i.slaveOk?e.slaveOk:i.slaveOk,u=null==i||null==i.serializeFunctions?e.s.options.serializeFunctions:i.serializeFunctions,l=null==i||null==i.raw?e.s.options.raw:i.raw,f=null==i||null==i.promoteLongs?e.s.options.promoteLongs:i.promoteLongs,p=null==i||null==i.promoteValues?e.s.options.promoteValues:i.promoteValues,d=null==i||null==i.promoteBuffers?e.s.options.promoteBuffers:i.promoteBuffers,m=new w(n,r),g=i.promiseLibrary||Promise;o=null==o?a:o,this.s={pkFactory:o,db:e,topology:t,options:i,namespace:m,readPreference:h.fromOptions(i),slaveOk:c,serializeFunctions:u,raw:l,promoteLongs:f,promoteValues:p,promoteBuffers:d,internalHint:null,collectionHint:null,promiseLibrary:g,readConcern:S.fromOptions(i),writeConcern:v.fromOptions(i)}}Object.defineProperty(fe.prototype,"dbName",{enumerable:!0,get:function(){return this.s.namespace.db}}),Object.defineProperty(fe.prototype,"collectionName",{enumerable:!0,get:function(){return this.s.namespace.collection}}),Object.defineProperty(fe.prototype,"namespace",{enumerable:!0,get:function(){return this.s.namespace.toString()}}),Object.defineProperty(fe.prototype,"readConcern",{enumerable:!0,get:function(){return null==this.s.readConcern?this.s.db.readConcern:this.s.readConcern}}),Object.defineProperty(fe.prototype,"readPreference",{enumerable:!0,get:function(){return null==this.s.readPreference?this.s.db.readPreference:this.s.readPreference}}),Object.defineProperty(fe.prototype,"writeConcern",{enumerable:!0,get:function(){return null==this.s.writeConcern?this.s.db.writeConcern:this.s.writeConcern}}),Object.defineProperty(fe.prototype,"hint",{enumerable:!0,get:function(){return this.s.collectionHint},set:function(e){this.s.collectionHint=u(e)}});const pe=["maxScan","fields","snapshot","oplogReplay"];function de(e,t,n,r,o){const i=Array.prototype.slice.call(arguments,1);return o="function"==typeof i[i.length-1]?i.pop():void 0,t=i.length&&i.shift()||[],n=i.length?i.shift():null,r=i.length&&i.shift()||{},(r=Object.assign({},r)).readPreference=h.PRIMARY,ue(this.s.topology,new W(this,e,t,n,r),o)}fe.prototype.find=o({name:"collection.find",deprecatedOptions:pe,optionsIndex:1},(function(e,t,n){"object"==typeof n&&i("Third parameter to `find()` must be a callback or undefined");let r=e;"function"!=typeof n&&("function"==typeof t?(n=t,t=void 0):null==t&&(n="function"==typeof r?r:void 0,r="object"==typeof r?r:void 0)),r=null==r?{}:r;const o=r;if(Buffer.isBuffer(o)){const e=o[0]|o[1]<<8|o[2]<<16|o[3]<<24;if(e!==o.length){const t=new Error("query selector raw message size does not match message header size ["+o.length+"] != ["+e+"]");throw t.name="MongoError",t}}null!=r&&"ObjectID"===r._bsontype&&(r={_id:r}),t||(t={});let s=t.projection||t.fields;s&&!Buffer.isBuffer(s)&&Array.isArray(s)&&(s=s.length?s.reduce((e,t)=>(e[t]=1,e),{}):{_id:1});let a=Object.assign({},t);for(let e in this.s.options)-1!==le.indexOf(e)&&(a[e]=this.s.options[e]);if(a.skip=t.skip?t.skip:0,a.limit=t.limit?t.limit:0,a.raw="boolean"==typeof t.raw?t.raw:this.s.raw,a.hint=null!=t.hint?u(t.hint):this.s.collectionHint,a.timeout=void 0===t.timeout?void 0:t.timeout,a.slaveOk=null!=t.slaveOk?t.slaveOk:this.s.db.slaveOk,a.readPreference=h.resolve(this,a),null==a.readPreference||"primary"===a.readPreference&&"primary"===a.readPreference.mode||(a.slaveOk=!0),null!=r&&"object"!=typeof r)throw c.create({message:"query selector must be an object",driver:!0});const m={find:this.s.namespace.toString(),limit:a.limit,skip:a.skip,query:r};"boolean"==typeof t.allowDiskUse&&(m.allowDiskUse=t.allowDiskUse),"boolean"==typeof a.awaitdata&&(a.awaitData=a.awaitdata),"boolean"==typeof a.timeout&&(a.noCursorTimeout=!a.timeout),l(m,a,["session","collation"]),s&&(m.fields=s),a.db=this.s.db,a.promiseLibrary=this.s.promiseLibrary,null==a.raw&&"boolean"==typeof this.s.raw&&(a.raw=this.s.raw),null==a.promoteLongs&&"boolean"==typeof this.s.promoteLongs&&(a.promoteLongs=this.s.promoteLongs),null==a.promoteValues&&"boolean"==typeof this.s.promoteValues&&(a.promoteValues=this.s.promoteValues),null==a.promoteBuffers&&"boolean"==typeof this.s.promoteBuffers&&(a.promoteBuffers=this.s.promoteBuffers),m.sort&&(m.sort=d(m.sort)),p(m,this,t);try{f(m,this,t)}catch(e){if("function"==typeof n)return n(e,null);throw e}const g=this.s.topology.cursor(new z(this,this.s.namespace,m,a),a);if("function"!=typeof n)return g;n(null,g)})),fe.prototype.insertOne=function(e,t,n){"function"==typeof t&&(n=t,t={}),t=t||{},this.s.options.ignoreUndefined&&((t=Object.assign({},t)).ignoreUndefined=this.s.options.ignoreUndefined);const r=new Z(this,e,t);return ue(this.s.topology,r,n)},fe.prototype.insertMany=function(e,t,n){"function"==typeof t&&(n=t,t={}),t=t?Object.assign({},t):{ordered:!0};const r=new X(this,e,t);return ue(this.s.topology,r,n)},fe.prototype.bulkWrite=function(e,t,n){if("function"==typeof t&&(n=t,t={}),t=t||{ordered:!0},!Array.isArray(e))throw c.create({message:"operations must be an array of documents",driver:!0});const r=new k(this,e,t);return ue(this.s.topology,r,n)},fe.prototype.insert=r((function(e,t,n){return"function"==typeof t&&(n=t,t={}),t=t||{ordered:!1},e=Array.isArray(e)?e:[e],!0===t.keepGoing&&(t.ordered=!1),this.insertMany(e,t,n)}),"collection.insert is deprecated. Use insertOne, insertMany or bulkWrite instead."),fe.prototype.updateOne=function(e,t,n,r){return"function"==typeof n&&(r=n,n={}),n=Object.assign({},n),this.s.options.ignoreUndefined&&((n=Object.assign({},n)).ignoreUndefined=this.s.options.ignoreUndefined),ue(this.s.topology,new ce(this,e,t,n),r)},fe.prototype.replaceOne=function(e,t,n,r){return"function"==typeof n&&(r=n,n={}),n=Object.assign({},n),this.s.options.ignoreUndefined&&((n=Object.assign({},n)).ignoreUndefined=this.s.options.ignoreUndefined),ue(this.s.topology,new ie(this,e,t,n),r)},fe.prototype.updateMany=function(e,t,n,r){return"function"==typeof n&&(r=n,n={}),n=Object.assign({},n),this.s.options.ignoreUndefined&&((n=Object.assign({},n)).ignoreUndefined=this.s.options.ignoreUndefined),ue(this.s.topology,new ae(this,e,t,n),r)},fe.prototype.update=r((function(e,t,n,r){return"function"==typeof n&&(r=n,n={}),n=n||{},this.s.options.ignoreUndefined&&((n=Object.assign({},n)).ignoreUndefined=this.s.options.ignoreUndefined),b(this.s.topology,I,[this,e,t,n,r])}),"collection.update is deprecated. Use updateOne, updateMany, or bulkWrite instead."),fe.prototype.deleteOne=function(e,t,n){"function"==typeof t&&(n=t,t={}),t=Object.assign({},t),this.s.options.ignoreUndefined&&((t=Object.assign({},t)).ignoreUndefined=this.s.options.ignoreUndefined);const r=new D(this,e,t);return ue(this.s.topology,r,n)},fe.prototype.removeOne=fe.prototype.deleteOne,fe.prototype.deleteMany=function(e,t,n){"function"==typeof t&&(n=t,t={}),t=Object.assign({},t),this.s.options.ignoreUndefined&&((t=Object.assign({},t)).ignoreUndefined=this.s.options.ignoreUndefined);const r=new j(this,e,t);return ue(this.s.topology,r,n)},fe.prototype.removeMany=fe.prototype.deleteMany,fe.prototype.remove=r((function(e,t,n){return"function"==typeof t&&(n=t,t={}),t=t||{},this.s.options.ignoreUndefined&&((t=Object.assign({},t)).ignoreUndefined=this.s.options.ignoreUndefined),b(this.s.topology,E,[this,e,t,n])}),"collection.remove is deprecated. Use deleteOne, deleteMany, or bulkWrite instead."),fe.prototype.save=r((function(e,t,n){return"function"==typeof t&&(n=t,t={}),t=t||{},this.s.options.ignoreUndefined&&((t=Object.assign({},t)).ignoreUndefined=this.s.options.ignoreUndefined),b(this.s.topology,N,[this,e,t,n])}),"collection.save is deprecated. Use insertOne, insertMany, updateOne, or updateMany instead."),fe.prototype.findOne=o({name:"collection.find",deprecatedOptions:pe,optionsIndex:1},(function(e,t,n){"object"==typeof n&&i("Third parameter to `findOne()` must be a callback or undefined"),"function"==typeof e&&(n=e,e={},t={}),"function"==typeof t&&(n=t,t={});const r=new $(this,e=e||{},t=t||{});return ue(this.s.topology,r,n)})),fe.prototype.rename=function(e,t,n){"function"==typeof t&&(n=t,t={}),t=Object.assign({},t,{readPreference:h.PRIMARY});const r=new re(this,e,t);return ue(this.s.topology,r,n)},fe.prototype.drop=function(e,t){"function"==typeof e&&(t=e,e={}),e=e||{};const n=new B(this.s.db,this.collectionName,e);return ue(this.s.topology,n,t)},fe.prototype.options=function(e,t){"function"==typeof e&&(t=e,e={});const n=new ne(this,e=e||{});return ue(this.s.topology,n,t)},fe.prototype.isCapped=function(e,t){"function"==typeof e&&(t=e,e={});const n=new Q(this,e=e||{});return ue(this.s.topology,n,t)},fe.prototype.createIndex=function(e,t,n){"function"==typeof t&&(n=t,t={}),t=t||{};const r=new R(this,this.collectionName,e,t);return ue(this.s.topology,r,n)},fe.prototype.createIndexes=function(e,t,n){"function"==typeof t&&(n=t,t={}),"number"!=typeof(t=t?Object.assign({},t):{}).maxTimeMS&&delete t.maxTimeMS;const r=new R(this,this.collectionName,e,t);return ue(this.s.topology,r,n)},fe.prototype.dropIndex=function(e,t,n){const r=Array.prototype.slice.call(arguments,1);n="function"==typeof r[r.length-1]?r.pop():void 0,(t=r.length&&r.shift()||{}).readPreference=h.PRIMARY;const o=new L(this,e,t);return ue(this.s.topology,o,n)},fe.prototype.dropIndexes=function(e,t){"function"==typeof e&&(t=e,e={}),"number"!=typeof(e=e?Object.assign({},e):{}).maxTimeMS&&delete e.maxTimeMS;const n=new q(this,e);return ue(this.s.topology,n,t)},fe.prototype.dropAllIndexes=r(fe.prototype.dropIndexes,"collection.dropAllIndexes is deprecated. Use dropIndexes instead."),fe.prototype.reIndex=r((function(e,t){"function"==typeof e&&(t=e,e={});const n=new oe(this,e=e||{});return ue(this.s.topology,n,t)}),"collection.reIndex is deprecated. Use db.command instead."),fe.prototype.listIndexes=function(e){return new O(this.s.topology,new ee(this,e),e)},fe.prototype.ensureIndex=r((function(e,t,n){return"function"==typeof t&&(n=t,t={}),t=t||{},b(this.s.topology,T,[this,e,t,n])}),"collection.ensureIndex is deprecated. Use createIndexes instead."),fe.prototype.indexExists=function(e,t,n){"function"==typeof t&&(n=t,t={});const r=new G(this,e,t=t||{});return ue(this.s.topology,r,n)},fe.prototype.indexInformation=function(e,t){const n=Array.prototype.slice.call(arguments,0);t="function"==typeof n[n.length-1]?n.pop():void 0,e=n.length&&n.shift()||{};const r=new J(this.s.db,this.collectionName,e);return ue(this.s.topology,r,t)},fe.prototype.count=r((function(e,t,n){const r=Array.prototype.slice.call(arguments,0);return n="function"==typeof r[r.length-1]?r.pop():void 0,e=r.length&&r.shift()||{},"function"==typeof(t=r.length&&r.shift()||{})&&(n=t,t={}),t=t||{},ue(this.s.topology,new U(this,e,t),n)}),"collection.count is deprecated, and will be removed in a future version. Use Collection.countDocuments or Collection.estimatedDocumentCount instead"),fe.prototype.estimatedDocumentCount=function(e,t){"function"==typeof e&&(t=e,e={});const n=new U(this,e=e||{});return ue(this.s.topology,n,t)},fe.prototype.countDocuments=function(e,t,n){const r=Array.prototype.slice.call(arguments,0);n="function"==typeof r[r.length-1]?r.pop():void 0,e=r.length&&r.shift()||{},t=r.length&&r.shift()||{};const o=new M(this,e,t);return ue(this.s.topology,o,n)},fe.prototype.distinct=function(e,t,n,r){const o=Array.prototype.slice.call(arguments,1);r="function"==typeof o[o.length-1]?o.pop():void 0;const i=o.length&&o.shift()||{},s=o.length&&o.shift()||{},a=new P(this,e,i,s);return ue(this.s.topology,a,r)},fe.prototype.indexes=function(e,t){"function"==typeof e&&(t=e,e={});const n=new Y(this,e=e||{});return ue(this.s.topology,n,t)},fe.prototype.stats=function(e,t){const n=Array.prototype.slice.call(arguments,0);t="function"==typeof n[n.length-1]?n.pop():void 0,e=n.length&&n.shift()||{};const r=new se(this,e);return ue(this.s.topology,r,t)},fe.prototype.findOneAndDelete=function(e,t,n){return"function"==typeof t&&(n=t,t={}),t=t||{},this.s.options.ignoreUndefined&&((t=Object.assign({},t)).ignoreUndefined=this.s.options.ignoreUndefined),ue(this.s.topology,new F(this,e,t),n)},fe.prototype.findOneAndReplace=function(e,t,n,r){return"function"==typeof n&&(r=n,n={}),n=n||{},this.s.options.ignoreUndefined&&((n=Object.assign({},n)).ignoreUndefined=this.s.options.ignoreUndefined),ue(this.s.topology,new V(this,e,t,n),r)},fe.prototype.findOneAndUpdate=function(e,t,n,r){return"function"==typeof n&&(r=n,n={}),n=n||{},this.s.options.ignoreUndefined&&((n=Object.assign({},n)).ignoreUndefined=this.s.options.ignoreUndefined),ue(this.s.topology,new K(this,e,t,n),r)},fe.prototype.findAndModify=r(de,"collection.findAndModify is deprecated. Use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead."),fe.prototype._findAndModify=de,fe.prototype.findAndRemove=r((function(e,t,n,r){const o=Array.prototype.slice.call(arguments,1);return r="function"==typeof o[o.length-1]?o.pop():void 0,t=o.length&&o.shift()||[],(n=o.length&&o.shift()||{}).remove=!0,ue(this.s.topology,new W(this,e,t,null,n),r)}),"collection.findAndRemove is deprecated. Use findOneAndDelete instead."),fe.prototype.aggregate=function(e,t,n){if(Array.isArray(e))"function"==typeof t&&(n=t,t={}),null==t&&null==n&&(t={});else{const r=Array.prototype.slice.call(arguments,0);n=r.pop();const o=r[r.length-1];t=o&&(o.readPreference||o.explain||o.cursor||o.out||o.maxTimeMS||o.hint||o.allowDiskUse)?r.pop():{},e=r}const r=new _(this.s.topology,new A(this,e,t),t);if("function"!=typeof n)return r;n(null,r)},fe.prototype.watch=function(e,t){return e=e||[],t=t||{},Array.isArray(e)||(t=e,e=[]),new y(this,e,t)},fe.prototype.parallelCollectionScan=r((function(e,t){return"function"==typeof e&&(t=e,e={numCursors:1}),e.numCursors=e.numCursors||1,e.batchSize=e.batchSize||1e3,(e=Object.assign({},e)).readPreference=h.resolve(this,e),e.promiseLibrary=this.s.promiseLibrary,e.session&&(e.session=void 0),b(this.s.topology,x,[this,e,t],{skipSessions:!0})}),"parallelCollectionScan is deprecated in MongoDB v4.1"),fe.prototype.geoHaystackSearch=r((function(e,t,n,r){const o=Array.prototype.slice.call(arguments,2);r="function"==typeof o[o.length-1]?o.pop():void 0,n=o.length&&o.shift()||{};const i=new H(this,e,t,n);return ue(this.s.topology,i,r)}),"geoHaystackSearch is deprecated, and will be removed in a future version."),fe.prototype.group=r((function(e,t,n,r,o,i,s,a){const c=Array.prototype.slice.call(arguments,3);return a="function"==typeof c[c.length-1]?c.pop():void 0,r=c.length?c.shift():null,o=c.length?c.shift():null,i=c.length?c.shift():null,s=c.length&&c.shift()||{},"function"!=typeof o&&(i=o,o=null),!Array.isArray(e)&&e instanceof Object&&"function"!=typeof e&&"Code"!==e._bsontype&&(e=Object.keys(e)),"function"==typeof r&&(r=r.toString()),"function"==typeof o&&(o=o.toString()),i=null==i||i,b(this.s.topology,C,[this,e,t,n,r,o,i,s,a])}),"MongoDB 3.6 or higher no longer supports the group command. We recommend rewriting using the aggregation framework."),fe.prototype.mapReduce=function(e,t,n,r){if("function"==typeof n&&(r=n,n={}),null==n.out)throw new Error("the out option parameter must be defined, see mongodb docs for possible values");"function"==typeof e&&(e=e.toString()),"function"==typeof t&&(t=t.toString()),"function"==typeof n.finalize&&(n.finalize=n.finalize.toString());const o=new te(this,e,t,n);return ue(this.s.topology,o,r)},fe.prototype.initializeUnorderedBulkOp=function(e){return null==(e=e||{}).ignoreUndefined&&(e.ignoreUndefined=this.s.options.ignoreUndefined),e.promiseLibrary=this.s.promiseLibrary,m(this.s.topology,this,e)},fe.prototype.initializeOrderedBulkOp=function(e){return null==(e=e||{}).ignoreUndefined&&(e.ignoreUndefined=this.s.options.ignoreUndefined),e.promiseLibrary=this.s.promiseLibrary,g(this.s.topology,this,e)},fe.prototype.getLogger=function(){return this.s.db.s.logger},e.exports=fe},function(e,t){e.exports=function(e){return e.webpackPolyfill||(e.deprecate=function(){},e.paths=[],e.children||(e.children=[]),Object.defineProperty(e,"loaded",{enumerable:!0,get:function(){return e.l}}),Object.defineProperty(e,"id",{enumerable:!0,get:function(){return e.i}}),e.webpackPolyfill=1),e}},function(e,t,n){var r=n(237),o=n(238),i=n(239),s=n(240),a=n(241);function c(e){var t=-1,n=null==e?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}c.prototype.clear=r,c.prototype.delete=o,c.prototype.get=i,c.prototype.has=s,c.prototype.set=a,e.exports=c},function(e,t,n){var r=n(65);e.exports=function(e,t){for(var n=e.length;n--;)if(r(e[n][0],t))return n;return-1}},function(e,t){e.exports=function(e,t){return e===t||e!=e&&t!=t}},function(e,t,n){var r=n(31)(Object,"create");e.exports=r},function(e,t,n){var r=n(261);e.exports=function(e,t){var n=e.__data__;return r(t)?n["string"==typeof t?"string":"hash"]:n.map}},function(e,t){var n=/^(?:0|[1-9]\d*)$/;e.exports=function(e,t){var r=typeof e;return!!(t=null==t?9007199254740991:t)&&("number"==r||"symbol"!=r&&n.test(e))&&e>-1&&e%1==0&&e<t}},function(e,t,n){(function(e){var r=n(149),o=t&&!t.nodeType&&t,i=o&&"object"==typeof e&&e&&!e.nodeType&&e,s=i&&i.exports===o&&r.process,a=function(){try{var e=i&&i.require&&i.require("util").types;return e||s&&s.binding&&s.binding("util")}catch(e){}}();e.exports=a}).call(this,n(62)(e))},function(e,t,n){var r=n(281),o=n(104),i=n(282),s=n(160),a=n(283),c=n(25),u=n(150),l=u(r),f=u(o),p=u(i),d=u(s),h=u(a),m=c;(r&&"[object DataView]"!=m(new r(new ArrayBuffer(1)))||o&&"[object Map]"!=m(new o)||i&&"[object Promise]"!=m(i.resolve())||s&&"[object Set]"!=m(new s)||a&&"[object WeakMap]"!=m(new a))&&(m=function(e){var t=c(e),n="[object Object]"==t?e.constructor:void 0,r=n?u(n):"";if(r)switch(r){case l:return"[object DataView]";case f:return"[object Map]";case p:return"[object Promise]";case d:return"[object Set]";case h:return"[object WeakMap]"}return t}),e.exports=m},function(e,t,n){var r=n(25),o=n(15);e.exports=function(e){return"symbol"==typeof e||o(e)&&"[object Symbol]"==r(e)}},function(e,t,n){var r=n(25),o=n(12),i=n(15);e.exports=function(e){return"string"==typeof e||!o(e)&&i(e)&&"[object String]"==r(e)}},function(e,t,n){var r=n(25),o=n(115),i=n(15),s=Function.prototype,a=Object.prototype,c=s.toString,u=a.hasOwnProperty,l=c.call(Object);e.exports=function(e){if(!i(e)||"[object Object]"!=r(e))return!1;var t=o(e);if(null===t)return!0;var n=u.call(t,"constructor")&&t.constructor;return"function"==typeof n&&n instanceof n&&c.call(n)==l}},function(e,t){e.exports=function(e){return e}},function(e,t,n){var r=n(171);e.exports=function(e){return(null==e?0:e.length)?r(e,1):[]}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dumpSqlCommand=t.dumpSqlInsert=t.dumpSqlDelete=t.dumpSqlUpdate=t.dumpSqlSelect=void 0;const r=n(180),o=n(126),i=n(127);function s(e,t){e.put("^select "),t.distinct&&e.put("^distinct "),t.topRecords&&(e.dialect.rangeSelect&&!e.dialect.offsetFetchRangeSyntax||e.put("^top %s ",t.topRecords)),t.selectAll&&e.put("* "),t.columns&&(t.selectAll&&e.put("&n,"),e.put("&>&n"),e.putCollection(",&n",t.columns,t=>{(0,r.dumpSqlExpression)(e,t),t.alias&&e.put(" ^as %i",t.alias)}),e.put("&n&<")),e.put("^from "),(0,o.dumpSqlFromDefinition)(e,t.from),t.where&&(e.put("&n^where "),(0,i.dumpSqlCondition)(e,t.where),e.put("&n")),t.groupBy&&(e.put("&n^group ^by "),e.putCollection(", ",t.groupBy,t=>(0,r.dumpSqlExpression)(e,t)),e.put("&n")),t.having&&(e.put("&n^having "),(0,i.dumpSqlCondition)(e,t.having),e.put("&n")),t.orderBy&&(e.put("&n^order ^by "),e.putCollection(", ",t.orderBy,t=>{(0,r.dumpSqlExpression)(e,t),e.put(" %k",t.direction)}),e.put("&n")),t.range&&(e.dialect.offsetFetchRangeSyntax?e.put("^offset %s ^rows ^fetch ^next %s ^rows ^only",t.range.offset,t.range.limit):e.put("^limit %s ^offset %s ",t.range.limit,t.range.offset)),t.topRecords&&e.dialect.rangeSelect&&!e.dialect.offsetFetchRangeSyntax&&e.put("^limit %s ",t.topRecords)}function a(e,t){e.put("^update "),(0,o.dumpSqlSourceRef)(e,t.from),e.put("&n^set "),e.put("&>"),e.putCollection(", ",t.fields,t=>{e.put("%i=",t.targetColumn),(0,r.dumpSqlExpression)(e,t)}),e.put("&<"),t.where&&(e.put("&n^where "),(0,i.dumpSqlCondition)(e,t.where),e.put("&n"))}function c(e,t){e.put("^delete ^from "),(0,o.dumpSqlSourceRef)(e,t.from),t.where&&(e.put("&n^where "),(0,i.dumpSqlCondition)(e,t.where),e.put("&n"))}function u(e,t){e.put("^insert ^into %f (%,i) ^values (",t.targetTable,t.fields.map(e=>e.targetColumn)),e.putCollection(",",t.fields,t=>(0,r.dumpSqlExpression)(e,t)),e.put(")")}t.dumpSqlSelect=s,t.dumpSqlUpdate=a,t.dumpSqlDelete=c,t.dumpSqlInsert=u,t.dumpSqlCommand=function(e,t){switch(t.commandType){case"select":s(e,t);break;case"update":a(e,t);break;case"delete":c(e,t);break;case"insert":u(e,t);break;case"allowIdentityInsert":e.allowIdentityInsert(t.targetTable,t.allow)}}},function(e,t){function n(e){if(!(this instanceof n))return new n(e);this._bsontype="Double",this.value=e}n.prototype.valueOf=function(){return this.value},n.prototype.toJSON=function(){return this.value},e.exports=n,e.exports.Double=n},function(e,t){function n(e,t){if(!(this instanceof n))return new n(e,t);this._bsontype="Timestamp",this.low_=0|e,this.high_=0|t}n.prototype.toInt=function(){return this.low_},n.prototype.toNumber=function(){return this.high_*n.TWO_PWR_32_DBL_+this.getLowBitsUnsigned()},n.prototype.toJSON=function(){return this.toString()},n.prototype.toString=function(e){var t=e||10;if(t<2||36<t)throw Error("radix out of range: "+t);if(this.isZero())return"0";if(this.isNegative()){if(this.equals(n.MIN_VALUE)){var r=n.fromNumber(t),o=this.div(r),i=o.multiply(r).subtract(this);return o.toString(t)+i.toInt().toString(t)}return"-"+this.negate().toString(t)}var s=n.fromNumber(Math.pow(t,6));i=this;for(var a="";!i.isZero();){var c=i.div(s),u=i.subtract(c.multiply(s)).toInt().toString(t);if((i=c).isZero())return u+a;for(;u.length<6;)u="0"+u;a=""+u+a}},n.prototype.getHighBits=function(){return this.high_},n.prototype.getLowBits=function(){return this.low_},n.prototype.getLowBitsUnsigned=function(){return this.low_>=0?this.low_:n.TWO_PWR_32_DBL_+this.low_},n.prototype.getNumBitsAbs=function(){if(this.isNegative())return this.equals(n.MIN_VALUE)?64:this.negate().getNumBitsAbs();for(var e=0!==this.high_?this.high_:this.low_,t=31;t>0&&0==(e&1<<t);t--);return 0!==this.high_?t+33:t+1},n.prototype.isZero=function(){return 0===this.high_&&0===this.low_},n.prototype.isNegative=function(){return this.high_<0},n.prototype.isOdd=function(){return 1==(1&this.low_)},n.prototype.equals=function(e){return this.high_===e.high_&&this.low_===e.low_},n.prototype.notEquals=function(e){return this.high_!==e.high_||this.low_!==e.low_},n.prototype.lessThan=function(e){return this.compare(e)<0},n.prototype.lessThanOrEqual=function(e){return this.compare(e)<=0},n.prototype.greaterThan=function(e){return this.compare(e)>0},n.prototype.greaterThanOrEqual=function(e){return this.compare(e)>=0},n.prototype.compare=function(e){if(this.equals(e))return 0;var t=this.isNegative(),n=e.isNegative();return t&&!n?-1:!t&&n?1:this.subtract(e).isNegative()?-1:1},n.prototype.negate=function(){return this.equals(n.MIN_VALUE)?n.MIN_VALUE:this.not().add(n.ONE)},n.prototype.add=function(e){var t=this.high_>>>16,r=65535&this.high_,o=this.low_>>>16,i=65535&this.low_,s=e.high_>>>16,a=65535&e.high_,c=e.low_>>>16,u=0,l=0,f=0,p=0;return f+=(p+=i+(65535&e.low_))>>>16,p&=65535,l+=(f+=o+c)>>>16,f&=65535,u+=(l+=r+a)>>>16,l&=65535,u+=t+s,u&=65535,n.fromBits(f<<16|p,u<<16|l)},n.prototype.subtract=function(e){return this.add(e.negate())},n.prototype.multiply=function(e){if(this.isZero())return n.ZERO;if(e.isZero())return n.ZERO;if(this.equals(n.MIN_VALUE))return e.isOdd()?n.MIN_VALUE:n.ZERO;if(e.equals(n.MIN_VALUE))return this.isOdd()?n.MIN_VALUE:n.ZERO;if(this.isNegative())return e.isNegative()?this.negate().multiply(e.negate()):this.negate().multiply(e).negate();if(e.isNegative())return this.multiply(e.negate()).negate();if(this.lessThan(n.TWO_PWR_24_)&&e.lessThan(n.TWO_PWR_24_))return n.fromNumber(this.toNumber()*e.toNumber());var t=this.high_>>>16,r=65535&this.high_,o=this.low_>>>16,i=65535&this.low_,s=e.high_>>>16,a=65535&e.high_,c=e.low_>>>16,u=65535&e.low_,l=0,f=0,p=0,d=0;return p+=(d+=i*u)>>>16,d&=65535,f+=(p+=o*u)>>>16,p&=65535,f+=(p+=i*c)>>>16,p&=65535,l+=(f+=r*u)>>>16,f&=65535,l+=(f+=o*c)>>>16,f&=65535,l+=(f+=i*a)>>>16,f&=65535,l+=t*u+r*c+o*a+i*s,l&=65535,n.fromBits(p<<16|d,l<<16|f)},n.prototype.div=function(e){if(e.isZero())throw Error("division by zero");if(this.isZero())return n.ZERO;if(this.equals(n.MIN_VALUE)){if(e.equals(n.ONE)||e.equals(n.NEG_ONE))return n.MIN_VALUE;if(e.equals(n.MIN_VALUE))return n.ONE;var t=this.shiftRight(1).div(e).shiftLeft(1);if(t.equals(n.ZERO))return e.isNegative()?n.ONE:n.NEG_ONE;var r=this.subtract(e.multiply(t));return t.add(r.div(e))}if(e.equals(n.MIN_VALUE))return n.ZERO;if(this.isNegative())return e.isNegative()?this.negate().div(e.negate()):this.negate().div(e).negate();if(e.isNegative())return this.div(e.negate()).negate();var o=n.ZERO;for(r=this;r.greaterThanOrEqual(e);){t=Math.max(1,Math.floor(r.toNumber()/e.toNumber()));for(var i=Math.ceil(Math.log(t)/Math.LN2),s=i<=48?1:Math.pow(2,i-48),a=n.fromNumber(t),c=a.multiply(e);c.isNegative()||c.greaterThan(r);)t-=s,c=(a=n.fromNumber(t)).multiply(e);a.isZero()&&(a=n.ONE),o=o.add(a),r=r.subtract(c)}return o},n.prototype.modulo=function(e){return this.subtract(this.div(e).multiply(e))},n.prototype.not=function(){return n.fromBits(~this.low_,~this.high_)},n.prototype.and=function(e){return n.fromBits(this.low_&e.low_,this.high_&e.high_)},n.prototype.or=function(e){return n.fromBits(this.low_|e.low_,this.high_|e.high_)},n.prototype.xor=function(e){return n.fromBits(this.low_^e.low_,this.high_^e.high_)},n.prototype.shiftLeft=function(e){if(0===(e&=63))return this;var t=this.low_;if(e<32){var r=this.high_;return n.fromBits(t<<e,r<<e|t>>>32-e)}return n.fromBits(0,t<<e-32)},n.prototype.shiftRight=function(e){if(0===(e&=63))return this;var t=this.high_;if(e<32){var r=this.low_;return n.fromBits(r>>>e|t<<32-e,t>>e)}return n.fromBits(t>>e-32,t>=0?0:-1)},n.prototype.shiftRightUnsigned=function(e){if(0===(e&=63))return this;var t=this.high_;if(e<32){var r=this.low_;return n.fromBits(r>>>e|t<<32-e,t>>>e)}return 32===e?n.fromBits(t,0):n.fromBits(t>>>e-32,0)},n.fromInt=function(e){if(-128<=e&&e<128){var t=n.INT_CACHE_[e];if(t)return t}var r=new n(0|e,e<0?-1:0);return-128<=e&&e<128&&(n.INT_CACHE_[e]=r),r},n.fromNumber=function(e){return isNaN(e)||!isFinite(e)?n.ZERO:e<=-n.TWO_PWR_63_DBL_?n.MIN_VALUE:e+1>=n.TWO_PWR_63_DBL_?n.MAX_VALUE:e<0?n.fromNumber(-e).negate():new n(e%n.TWO_PWR_32_DBL_|0,e/n.TWO_PWR_32_DBL_|0)},n.fromBits=function(e,t){return new n(e,t)},n.fromString=function(e,t){if(0===e.length)throw Error("number format error: empty string");var r=t||10;if(r<2||36<r)throw Error("radix out of range: "+r);if("-"===e.charAt(0))return n.fromString(e.substring(1),r).negate();if(e.indexOf("-")>=0)throw Error('number format error: interior "-" character: '+e);for(var o=n.fromNumber(Math.pow(r,8)),i=n.ZERO,s=0;s<e.length;s+=8){var a=Math.min(8,e.length-s),c=parseInt(e.substring(s,s+a),r);if(a<8){var u=n.fromNumber(Math.pow(r,a));i=i.multiply(u).add(n.fromNumber(c))}else i=(i=i.multiply(o)).add(n.fromNumber(c))}return i},n.INT_CACHE_={},n.TWO_PWR_16_DBL_=65536,n.TWO_PWR_24_DBL_=1<<24,n.TWO_PWR_32_DBL_=n.TWO_PWR_16_DBL_*n.TWO_PWR_16_DBL_,n.TWO_PWR_31_DBL_=n.TWO_PWR_32_DBL_/2,n.TWO_PWR_48_DBL_=n.TWO_PWR_32_DBL_*n.TWO_PWR_16_DBL_,n.TWO_PWR_64_DBL_=n.TWO_PWR_32_DBL_*n.TWO_PWR_32_DBL_,n.TWO_PWR_63_DBL_=n.TWO_PWR_64_DBL_/2,n.ZERO=n.fromInt(0),n.ONE=n.fromInt(1),n.NEG_ONE=n.fromInt(-1),n.MAX_VALUE=n.fromBits(-1,2147483647),n.MIN_VALUE=n.fromBits(0,-2147483648),n.TWO_PWR_24_=n.fromInt(1<<24),e.exports=n,e.exports.Timestamp=n},function(e,t,n){var r="inspect",o=n(32),i=parseInt(16777215*Math.random(),10),s=new RegExp("^[0-9a-fA-F]{24}$");try{if(Buffer&&Buffer.from){var a=!0;r=n(5).inspect.custom||"inspect"}}catch(e){a=!1}for(var c=function e(t){if(t instanceof e)return t;if(!(this instanceof e))return new e(t);if(this._bsontype="ObjectID",null==t||"number"==typeof t)return this.id=this.generate(t),void(e.cacheHexString&&(this.__id=this.toString("hex")));var n=e.isValid(t);if(!n&&null!=t)throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters");if(n&&"string"==typeof t&&24===t.length&&a)return new e(o.toBuffer(t,"hex"));if(n&&"string"==typeof t&&24===t.length)return e.createFromHexString(t);if(null==t||12!==t.length){if(null!=t&&"function"==typeof t.toHexString)return t;throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters")}this.id=t,e.cacheHexString&&(this.__id=this.toString("hex"))},u=[],l=0;l<256;l++)u[l]=(l<=15?"0":"")+l.toString(16);c.prototype.toHexString=function(){if(c.cacheHexString&&this.__id)return this.__id;var e="";if(!this.id||!this.id.length)throw new Error("invalid ObjectId, ObjectId.id must be either a string or a Buffer, but is ["+JSON.stringify(this.id)+"]");if(this.id instanceof p)return e=d(this.id),c.cacheHexString&&(this.__id=e),e;for(var t=0;t<this.id.length;t++)e+=u[this.id.charCodeAt(t)];return c.cacheHexString&&(this.__id=e),e},c.prototype.get_inc=function(){return c.index=(c.index+1)%16777215},c.prototype.getInc=function(){return this.get_inc()},c.prototype.generate=function(e){"number"!=typeof e&&(e=~~(Date.now()/1e3));var t=("undefined"==typeof process||1===process.pid?Math.floor(1e5*Math.random()):process.pid)%65535,n=this.get_inc(),r=o.allocBuffer(12);return r[3]=255&e,r[2]=e>>8&255,r[1]=e>>16&255,r[0]=e>>24&255,r[6]=255&i,r[5]=i>>8&255,r[4]=i>>16&255,r[8]=255&t,r[7]=t>>8&255,r[11]=255&n,r[10]=n>>8&255,r[9]=n>>16&255,r},c.prototype.toString=function(e){return this.id&&this.id.copy?this.id.toString("string"==typeof e?e:"hex"):this.toHexString()},c.prototype[r]=c.prototype.toString,c.prototype.toJSON=function(){return this.toHexString()},c.prototype.equals=function(e){return e instanceof c?this.toString()===e.toString():"string"==typeof e&&c.isValid(e)&&12===e.length&&this.id instanceof p?e===this.id.toString("binary"):"string"==typeof e&&c.isValid(e)&&24===e.length?e.toLowerCase()===this.toHexString():"string"==typeof e&&c.isValid(e)&&12===e.length?e===this.id:!(null==e||!(e instanceof c||e.toHexString))&&e.toHexString()===this.toHexString()},c.prototype.getTimestamp=function(){var e=new Date,t=this.id[3]|this.id[2]<<8|this.id[1]<<16|this.id[0]<<24;return e.setTime(1e3*Math.floor(t)),e},c.index=~~(16777215*Math.random()),c.createPk=function(){return new c},c.createFromTime=function(e){var t=o.toBuffer([0,0,0,0,0,0,0,0,0,0,0,0]);return t[3]=255&e,t[2]=e>>8&255,t[1]=e>>16&255,t[0]=e>>24&255,new c(t)};var f=[];for(l=0;l<10;)f[48+l]=l++;for(;l<16;)f[55+l]=f[87+l]=l++;var p=Buffer,d=function(e){return e.toString("hex")};c.createFromHexString=function(e){if(void 0===e||null!=e&&24!==e.length)throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters");if(a)return new c(o.toBuffer(e,"hex"));for(var t=new p(12),n=0,r=0;r<24;)t[n++]=f[e.charCodeAt(r++)]<<4|f[e.charCodeAt(r++)];return new c(t)},c.isValid=function(e){return null!=e&&("number"==typeof e||("string"==typeof e?12===e.length||24===e.length&&s.test(e):e instanceof c||(e instanceof p||"function"==typeof e.toHexString&&(e.id instanceof p||"string"==typeof e.id)&&(12===e.id.length||24===e.id.length&&s.test(e.id)))))},Object.defineProperty(c.prototype,"generationTime",{enumerable:!0,get:function(){return this.id[3]|this.id[2]<<8|this.id[1]<<16|this.id[0]<<24},set:function(e){this.id[3]=255&e,this.id[2]=e>>8&255,this.id[1]=e>>16&255,this.id[0]=e>>24&255}}),e.exports=c,e.exports.ObjectID=c,e.exports.ObjectId=c},function(e,t){function n(e,t){if(!(this instanceof n))return new n;this._bsontype="BSONRegExp",this.pattern=e||"",this.options=t||"";for(var r=0;r<this.options.length;r++)if("i"!==this.options[r]&&"m"!==this.options[r]&&"x"!==this.options[r]&&"l"!==this.options[r]&&"s"!==this.options[r]&&"u"!==this.options[r])throw new Error("the regular expression options ["+this.options[r]+"] is not supported")}e.exports=n,e.exports.BSONRegExp=n},function(e,t,n){var r=Buffer&&n(5).inspect.custom||"inspect";function o(e){if(!(this instanceof o))return new o(e);this._bsontype="Symbol",this.value=e}o.prototype.valueOf=function(){return this.value},o.prototype.toString=function(){return this.value},o.prototype[r]=function(){return this.value},o.prototype.toJSON=function(){return this.value},e.exports=o,e.exports.Symbol=o},function(e,t){var n=function e(t,n){if(!(this instanceof e))return new e(t,n);this._bsontype="Code",this.code=t,this.scope=n};n.prototype.toJSON=function(){return{scope:this.scope,code:this.code}},e.exports=n,e.exports.Code=n},function(e,t,n){"use strict";var r=n(43),o=/^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/,i=/^(\+|-)?(Infinity|inf)$/i,s=/^(\+|-)?NaN$/i,a=6176,c=[124,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse(),u=[248,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse(),l=[120,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse(),f=/^([-+])?(\d+)?$/,p=n(32),d=function(e){return!isNaN(parseInt(e,10))},h=function(e){var t=r.fromNumber(1e9),n=r.fromNumber(0),o=0;if(!(e.parts[0]||e.parts[1]||e.parts[2]||e.parts[3]))return{quotient:e,rem:n};for(o=0;o<=3;o++)n=(n=n.shiftLeft(32)).add(new r(e.parts[o],0)),e.parts[o]=n.div(t).low_,n=n.modulo(t);return{quotient:e,rem:n}},m=function(e){this._bsontype="Decimal128",this.bytes=e};m.fromString=function(e){var t,n=!1,h=!1,g=!1,y=0,b=0,v=0,S=0,w=0,_=[0],O=0,T=0,C=0,x=0,E=0,N=0,I=[0,0],A=[0,0],k=0;if((e=e.trim()).length>=7e3)throw new Error(e+" not a valid Decimal128 string");var M=e.match(o),R=e.match(i),j=e.match(s);if(!M&&!R&&!j||0===e.length)throw new Error(e+" not a valid Decimal128 string");if(M&&M[4]&&void 0===M[2])throw new Error(e+" not a valid Decimal128 string");if("+"!==e[k]&&"-"!==e[k]||(n="-"===e[k++]),!d(e[k])&&"."!==e[k]){if("i"===e[k]||"I"===e[k])return new m(p.toBuffer(n?u:l));if("N"===e[k])return new m(p.toBuffer(c))}for(;d(e[k])||"."===e[k];)if("."!==e[k])O<34&&("0"!==e[k]||g)&&(g||(w=b),g=!0,_[T++]=parseInt(e[k],10),O+=1),g&&(v+=1),h&&(S+=1),b+=1,k+=1;else{if(h)return new m(p.toBuffer(c));h=!0,k+=1}if(h&&!b)throw new Error(e+" not a valid Decimal128 string");if("e"===e[k]||"E"===e[k]){var D=e.substr(++k).match(f);if(!D||!D[2])return new m(p.toBuffer(c));E=parseInt(D[0],10),k+=D[0].length}if(e[k])return new m(p.toBuffer(c));if(C=0,O){if(x=O-1,y=v,0!==E&&1!==y)for(;"0"===e[w+y-1];)y-=1}else C=0,x=0,_[0]=0,v=1,O=1,y=0;for(E<=S&&S-E>16384?E=-6176:E-=S;E>6111;){if((x+=1)-C>34){var P=_.join("");if(P.match(/^0+$/)){E=6111;break}return new m(p.toBuffer(n?u:l))}E-=1}for(;E<-6176||O<v;){if(0===x){E=-6176,y=0;break}if(O<v?v-=1:x-=1,!(E<6111)){if((P=_.join("")).match(/^0+$/)){E=6111;break}return new m(p.toBuffer(n?u:l))}E+=1}if(x-C+1<y&&"0"!==e[y]){var B=b;h&&-6176===E&&(w+=1,B+=1);var L=parseInt(e[w+x+1],10),q=0;if(L>=5&&(q=1,5===L))for(q=_[x]%2==1,N=w+x+2;N<B;N++)if(parseInt(e[N],10)){q=1;break}if(q)for(var U=x;U>=0&&++_[U]>9;U--)if(_[U]=0,0===U){if(!(E<6111))return new m(p.toBuffer(n?u:l));E+=1,_[U]=1}}if(I=r.fromNumber(0),A=r.fromNumber(0),0===y)I=r.fromNumber(0),A=r.fromNumber(0);else if(x-C<17)for(U=C,A=r.fromNumber(_[U++]),I=new r(0,0);U<=x;U++)A=(A=A.multiply(r.fromNumber(10))).add(r.fromNumber(_[U]));else{for(U=C,I=r.fromNumber(_[U++]);U<=x-17;U++)I=(I=I.multiply(r.fromNumber(10))).add(r.fromNumber(_[U]));for(A=r.fromNumber(_[U++]);U<=x;U++)A=(A=A.multiply(r.fromNumber(10))).add(r.fromNumber(_[U]))}var z,$,W,F,V=function(e,t){if(!e&&!t)return{high:r.fromNumber(0),low:r.fromNumber(0)};var n=e.shiftRightUnsigned(32),o=new r(e.getLowBits(),0),i=t.shiftRightUnsigned(32),s=new r(t.getLowBits(),0),a=n.multiply(i),c=n.multiply(s),u=o.multiply(i),l=o.multiply(s);return a=a.add(c.shiftRightUnsigned(32)),c=new r(c.getLowBits(),0).add(u).add(l.shiftRightUnsigned(32)),{high:a=a.add(c.shiftRightUnsigned(32)),low:l=c.shiftLeft(32).add(new r(l.getLowBits(),0))}}(I,r.fromString("100000000000000000"));V.low=V.low.add(A),z=V.low,$=A,W=z.high_>>>0,F=$.high_>>>0,(W<F||W===F&&z.low_>>>0<$.low_>>>0)&&(V.high=V.high.add(r.fromNumber(1))),t=E+a;var K={low:r.fromNumber(0),high:r.fromNumber(0)};V.high.shiftRightUnsigned(49).and(r.fromNumber(1)).equals(r.fromNumber)?(K.high=K.high.or(r.fromNumber(3).shiftLeft(61)),K.high=K.high.or(r.fromNumber(t).and(r.fromNumber(16383).shiftLeft(47))),K.high=K.high.or(V.high.and(r.fromNumber(0x7fffffffffff)))):(K.high=K.high.or(r.fromNumber(16383&t).shiftLeft(49)),K.high=K.high.or(V.high.and(r.fromNumber(562949953421311)))),K.low=V.low,n&&(K.high=K.high.or(r.fromString("9223372036854775808")));var H=p.allocBuffer(16);return k=0,H[k++]=255&K.low.low_,H[k++]=K.low.low_>>8&255,H[k++]=K.low.low_>>16&255,H[k++]=K.low.low_>>24&255,H[k++]=255&K.low.high_,H[k++]=K.low.high_>>8&255,H[k++]=K.low.high_>>16&255,H[k++]=K.low.high_>>24&255,H[k++]=255&K.high.low_,H[k++]=K.high.low_>>8&255,H[k++]=K.high.low_>>16&255,H[k++]=K.high.low_>>24&255,H[k++]=255&K.high.high_,H[k++]=K.high.high_>>8&255,H[k++]=K.high.high_>>16&255,H[k++]=K.high.high_>>24&255,new m(H)};a=6176,m.prototype.toString=function(){for(var e,t,n,o,i,s,c=0,u=new Array(36),l=0;l<u.length;l++)u[l]=0;var f,p,d,m,g,y=0,b=!1,v={parts:new Array(4)},S=[];y=0;var w=this.bytes;if(o=w[y++]|w[y++]<<8|w[y++]<<16|w[y++]<<24,n=w[y++]|w[y++]<<8|w[y++]<<16|w[y++]<<24,t=w[y++]|w[y++]<<8|w[y++]<<16|w[y++]<<24,e=w[y++]|w[y++]<<8|w[y++]<<16|w[y++]<<24,y=0,{low:new r(o,n),high:new r(t,e)}.high.lessThan(r.ZERO)&&S.push("-"),(i=e>>26&31)>>3==3){if(30===i)return S.join("")+"Infinity";if(31===i)return"NaN";s=e>>15&16383,d=8+(e>>14&1)}else d=e>>14&7,s=e>>17&16383;if(f=s-a,v.parts[0]=(16383&e)+((15&d)<<14),v.parts[1]=t,v.parts[2]=n,v.parts[3]=o,0===v.parts[0]&&0===v.parts[1]&&0===v.parts[2]&&0===v.parts[3])b=!0;else for(g=3;g>=0;g--){var _=0,O=h(v);if(v=O.quotient,_=O.rem.low_)for(m=8;m>=0;m--)u[9*g+m]=_%10,_=Math.floor(_/10)}if(b)c=1,u[y]=0;else for(c=36,l=0;!u[y];)l++,c-=1,y+=1;if((p=c-1+f)>=34||p<=-7||f>0){for(S.push(u[y++]),(c-=1)&&S.push("."),l=0;l<c;l++)S.push(u[y++]);S.push("E"),p>0?S.push("+"+p):S.push(p)}else if(f>=0)for(l=0;l<c;l++)S.push(u[y++]);else{var T=c+f;if(T>0)for(l=0;l<T;l++)S.push(u[y++]);else S.push("0");for(S.push(".");T++<0;)S.push("0");for(l=0;l<c-Math.max(T-1,0);l++)S.push(u[y++])}return S.join("")},m.prototype.toJSON=function(){return{$numberDecimal:this.toString()}},e.exports=m,e.exports.Decimal128=m},function(e,t){function n(){if(!(this instanceof n))return new n;this._bsontype="MinKey"}e.exports=n,e.exports.MinKey=n},function(e,t){function n(){if(!(this instanceof n))return new n;this._bsontype="MaxKey"}e.exports=n,e.exports.MaxKey=n},function(e,t){function n(e,t,r){if(!(this instanceof n))return new n(e,t,r);this._bsontype="DBRef",this.namespace=e,this.oid=t,this.db=r}n.prototype.toJSON=function(){return{$ref:this.namespace,$id:this.oid,$db:null==this.db?"":this.db}},e.exports=n,e.exports.DBRef=n},function(e,t){e.exports=require("dns")},function(e,t,n){"use strict";const r=n(20),o=n(22).Buffer,i=n(9).retrieveBSON,s=n(3).MongoError,a=n(33).AuthProvider,c=n(0).emitWarning,u=i().Binary;let l;try{l=n(416)}catch(e){}class f extends a{constructor(e,t){super(e),this.cryptoMethod=t||"sha1"}prepare(e,t,n){const o=this.cryptoMethod;"sha256"===o&&null==l&&c("Warning: no saslprep library specified. Passwords will not be sanitized"),r.randomBytes(24,(r,i)=>{if(r)return n(r);Object.assign(t,{nonce:i});const s=t.credentials,a=Object.assign({},e,{speculativeAuthenticate:Object.assign(h(o,s,i),{db:s.source})});n(void 0,a)})}auth(e,t){const n=e.response;n&&n.speculativeAuthenticate?m(this.cryptoMethod,n.speculativeAuthenticate,e,t):function(e,t,n){const r=t.connection,o=t.credentials,i=t.nonce,s=o.source,a=h(e,o,i);r.command(`${s}.$cmd`,a,(r,o)=>{const i=w(r,o);if(i)return n(i);m(e,o.result,t,n)})}(this.cryptoMethod,e,t)}}function p(e){return e.replace("=","=3D").replace(",","=2C")}function d(e,t){return o.concat([o.from("n=","utf8"),o.from(e,"utf8"),o.from(",r=","utf8"),o.from(t.toString("base64"),"utf8")])}function h(e,t,n){const r=p(t.username);return{saslStart:1,mechanism:"sha1"===e?"SCRAM-SHA-1":"SCRAM-SHA-256",payload:new u(o.concat([o.from("n,,","utf8"),d(r,n)])),autoAuthorize:1,options:{skipEmptyExchange:!0}}}function m(e,t,n,i){const a=n.connection,c=n.credentials,f=n.nonce,h=c.source,m=p(c.username),_=c.password;let O;if("sha256"===e)O=l?l(_):_;else try{O=function(e,t){if("string"!=typeof e)throw new s("username must be a string");if("string"!=typeof t)throw new s("password must be a string");if(0===t.length)throw new s("password cannot be empty");const n=r.createHash("md5");return n.update(`${e}:mongo:${t}`,"utf8"),n.digest("hex")}(m,_)}catch(e){return i(e)}const T=o.isBuffer(t.payload)?new u(t.payload):t.payload,C=g(T.value()),x=parseInt(C.i,10);if(x&&x<4096)return void i(new s(`Server returned an invalid iteration count ${x}`),!1);const E=C.s,N=C.r;if(N.startsWith("nonce"))return void i(new s(`Server returned an invalid nonce: ${N}`),!1);const I=`c=biws,r=${N}`,A=function(e,t,n,o){const i=[e,t.toString("base64"),n].join("_");if(void 0!==b[i])return b[i];const s=r.pbkdf2Sync(e,t,n,S[o],o);v>=200&&(b={},v=0);return b[i]=s,v+=1,s}(O,o.from(E,"base64"),x,e),k=y(e,A,"Client Key"),M=y(e,A,"Server Key"),R=(j=e,D=k,r.createHash(j).update(D).digest());var j,D;const P=[d(m,f),T.value().toString("base64"),I].join(","),B=[I,`p=${function(e,t){o.isBuffer(e)||(e=o.from(e));o.isBuffer(t)||(t=o.from(t));const n=Math.max(e.length,t.length),r=[];for(let o=0;o<n;o+=1)r.push(e[o]^t[o]);return o.from(r).toString("base64")}(k,y(e,R,P))}`].join(","),L=y(e,M,P),q={saslContinue:1,conversationId:t.conversationId,payload:new u(o.from(B))};a.command(`${h}.$cmd`,q,(e,t)=>{const n=w(e,t);if(n)return i(n);const c=t.result,u=g(c.payload.value());if(!function(e,t){if(e.length!==t.length)return!1;if("function"==typeof r.timingSafeEqual)return r.timingSafeEqual(e,t);let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return 0===n}(o.from(u.v,"base64"),L))return void i(new s("Server returned an invalid signature"));if(!c||!1!==c.done)return i(n,c);const l={saslContinue:1,conversationId:c.conversationId,payload:o.alloc(0)};a.command(`${h}.$cmd`,l,i)})}function g(e){const t={},n=e.split(",");for(let e=0;e<n.length;e++){const r=n[e].split("=");t[r[0]]=r[1]}return t}function y(e,t,n){return r.createHmac(e,t).update(n).digest()}let b={},v=0;const S={sha256:32,sha1:20};function w(e,t){if(e)return e;const n=t.result;return n.$err||n.errmsg?new s(n):void 0}e.exports={ScramSHA1:class extends f{constructor(e){super(e,"sha1")}},ScramSHA256:class extends f{constructor(e){super(e,"sha256")}}}},function(e,t){e.exports=require("fs")},function(e,t){e.exports=require("url")},function(e,t,n){"use strict";const r=n(3).MongoError,o={queryPlanner:"queryPlanner",queryPlannerExtended:"queryPlannerExtended",executionStats:"executionStats",allPlansExecution:"allPlansExecution"};class i{constructor(e){this.verbosity="boolean"==typeof e?e?"allPlansExecution":"queryPlanner":e}static fromOptions(e){if(null==e||void 0===e.explain)return;const t=e.explain;if("boolean"==typeof t||t in o)return new i(e.explain);throw new r(`explain must be one of ${Object.keys(o)} or a boolean`)}}e.exports={Explain:i}},function(e,t,n){"use strict";"undefined"==typeof process||!process.version||0===process.version.indexOf("v0.")||0===process.version.indexOf("v1.")&&0!==process.version.indexOf("v1.8.")?e.exports={nextTick:function(e,t,n,r){if("function"!=typeof e)throw new TypeError('"callback" argument must be a function');var o,i,s=arguments.length;switch(s){case 0:case 1:return process.nextTick(e);case 2:return process.nextTick((function(){e.call(null,t)}));case 3:return process.nextTick((function(){e.call(null,t,n)}));case 4:return process.nextTick((function(){e.call(null,t,n,r)}));default:for(o=new Array(s-1),i=0;i<o.length;)o[i++]=arguments[i];return process.nextTick((function(){e.apply(null,o)}))}}}:e.exports=process},function(e,t,n){var r=n(131),o=r.Buffer;function i(e,t){for(var n in e)t[n]=e[n]}function s(e,t,n){return o(e,t,n)}o.from&&o.alloc&&o.allocUnsafe&&o.allocUnsafeSlow?e.exports=r:(i(r,t),t.Buffer=s),i(o,s),s.from=function(e,t,n){if("number"==typeof e)throw new TypeError("Argument must not be a number");return o(e,t,n)},s.alloc=function(e,t,n){if("number"!=typeof e)throw new TypeError("Argument must be a number");var r=o(e);return void 0!==t?"string"==typeof n?r.fill(t,n):r.fill(t):r.fill(0),r},s.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return o(e)},s.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return r.SlowBuffer(e)}},function(e,t,n){"use strict";class r{constructor(e){this.time=new Date,this.address=e.address}}e.exports={CMAP_EVENT_NAMES:["connectionPoolCreated","connectionPoolClosed","connectionCreated","connectionReady","connectionClosed","connectionCheckOutStarted","connectionCheckOutFailed","connectionCheckedOut","connectionCheckedIn","connectionPoolCleared"],ConnectionPoolCreatedEvent:class extends r{constructor(e){super(e),this.options=e.options}},ConnectionPoolClosedEvent:class extends r{constructor(e){super(e)}},ConnectionCreatedEvent:class extends r{constructor(e,t){super(e),this.connectionId=t.id}},ConnectionReadyEvent:class extends r{constructor(e,t){super(e),this.connectionId=t.id}},ConnectionClosedEvent:class extends r{constructor(e,t,n){super(e),this.connectionId=t.id,this.reason=n||"unknown"}},ConnectionCheckOutStartedEvent:class extends r{constructor(e){super(e)}},ConnectionCheckOutFailedEvent:class extends r{constructor(e,t){super(e),this.reason=t}},ConnectionCheckedOutEvent:class extends r{constructor(e,t){super(e),this.connectionId=t.id}},ConnectionCheckedInEvent:class extends r{constructor(e,t){super(e),this.connectionId=t.id}},ConnectionPoolClearedEvent:class extends r{constructor(e){super(e)}}}},function(e,t,n){"use strict";const r=n(2).MongoNetworkError,o=new Set([6,7,89,91,189,262,9001,10107,11600,11602,13435,13436,63,150,13388,234,133,43]);e.exports={GET_MORE_RESUMABLE_CODES:o,isResumableError:function(e,t){return e instanceof r||(t>=9?43===e.code||e.hasErrorLabel("ResumableChangeStreamError"):o.has(e.code))}}},function(e,t,n){"use strict";const r=n(27),o=n(2).MongoError,i=n(4).maxWireVersion,s=n(2).ReadPreference,a=n(1).Aspect,c=n(1).defineAspects;class u extends r{constructor(e,t,n){if(super(e,n,{fullResponse:!0}),this.target=e.s.namespace&&e.s.namespace.collection?e.s.namespace.collection:1,this.pipeline=t,this.hasWriteStage=!1,"string"==typeof n.out)this.pipeline=this.pipeline.concat({$out:n.out}),this.hasWriteStage=!0;else if(t.length>0){const e=t[t.length-1];(e.$out||e.$merge)&&(this.hasWriteStage=!0)}if(this.hasWriteStage&&(this.readPreference=s.primary),this.explain&&this.writeConcern)throw new o('"explain" cannot be used on an aggregate call with writeConcern');if(null!=n.cursor&&"object"!=typeof n.cursor)throw new o("cursor options must be an object")}get canRetryRead(){return!this.hasWriteStage}addToPipeline(e){this.pipeline.push(e)}execute(e,t){const n=this.options,r=i(e),o={aggregate:this.target,pipeline:this.pipeline};this.hasWriteStage&&r<8&&(this.readConcern=null),r>=5&&this.hasWriteStage&&this.writeConcern&&Object.assign(o,{writeConcern:this.writeConcern}),!0===n.bypassDocumentValidation&&(o.bypassDocumentValidation=n.bypassDocumentValidation),"boolean"==typeof n.allowDiskUse&&(o.allowDiskUse=n.allowDiskUse),n.hint&&(o.hint=n.hint),this.explain&&(n.full=!1),o.cursor=n.cursor||{},n.batchSize&&!this.hasWriteStage&&(o.cursor.batchSize=n.batchSize),super.executeCommand(e,o,t)}}c(u,[a.READ_OPERATION,a.RETRYABLE,a.EXECUTE_WITH_SELECTION,a.EXPLAINABLE]),e.exports=u},function(e,t,n){"use strict";const r=n(1).OperationBase,o=n(0).applyRetryableWrites,i=n(0).applyWriteConcern,s=n(0).decorateWithCollation,a=n(11).executeCommand,c=n(0).formattedOrderClause,u=n(0).handleCallback,l=n(2).ReadPreference,f=n(4).maxWireVersion,p=n(95).MongoError,d=n(1).Aspect,h=n(1).defineAspects,m=n(0).decorateWithExplain;class g extends r{constructor(e,t,n,r,o){super(o),this.collection=e,this.query=t,this.sort=n,this.doc=r}execute(e){const t=this.collection,n=this.query,r=c(this.sort),d=this.doc;let h=this.options,g={findAndModify:t.collectionName,query:n};r&&(g.sort=r),g.new=!!h.new,g.remove=!!h.remove,g.upsert=!!h.upsert;const y=h.projection||h.fields;y&&(g.fields=y),h.arrayFilters&&(g.arrayFilters=h.arrayFilters),d&&!h.remove&&(g.update=d),h.maxTimeMS&&(g.maxTimeMS=h.maxTimeMS),h.serializeFunctions=h.serializeFunctions||t.s.serializeFunctions,h.checkKeys=!1,h=o(h,t.s.db),h=i(h,{db:t.s.db,collection:t},h),h.writeConcern&&(g.writeConcern=h.writeConcern),!0===h.bypassDocumentValidation&&(g.bypassDocumentValidation=h.bypassDocumentValidation),h.readPreference=l.primary;try{s(g,t,h)}catch(t){return e(t,null)}if(h.hint){if(h.writeConcern&&0===h.writeConcern.w||f(t.s.topology)<8)return void e(new p("The current topology does not support a hint on findAndModify commands"));g.hint=h.hint}if(this.explain){if(f(t.s.topology)<4)return void e(new p("server does not support explain on findAndModify"));g=m(g,this.explain)}a(t.s.db,g,h,(t,n)=>t?u(e,t,null):u(e,null,n))}}h(g,[d.EXPLAINABLE]),e.exports=g},function(e,t,n){"use strict";const r=n(8).EventEmitter,o=n(5).inherits,i=n(0).getSingleProperty,s=n(143),a=n(0).handleCallback,c=n(0).filterOptions,u=n(0).toError,l=n(2).ReadPreference,f=n(2).MongoError,p=n(2).ObjectID,d=n(2).Logger,h=n(61),m=n(0).conditionallyMergeWriteConcern,g=n(0).executeLegacyOperation,y=n(139),b=n(5).deprecate,v=n(0).deprecateOptions,S=n(0).MongoDBNamespace,w=n(140),_=n(29),O=n(46),T=n(142),C=n(11).createListener,x=n(11).ensureIndex,E=n(11).evaluate,N=n(11).profilingInfo,I=n(11).validateDatabaseName,A=n(96),k=n(214),M=n(471),R=n(23),j=n(472),D=n(473),P=n(210),B=n(144).DropCollectionOperation,L=n(144).DropDatabaseOperation,q=n(215),U=n(212),z=n(474),$=n(475),W=n(216),F=n(217),V=n(476),K=n(56),H=["w","wtimeout","fsync","j","writeConcern","readPreference","readPreferenceTags","native_parser","forceServerObjectId","pkFactory","serializeFunctions","raw","bufferMaxEntries","authSource","ignoreUndefined","promoteLongs","promiseLibrary","readConcern","retryMiliSeconds","numberOfRetries","parentDb","noListener","loggerLevel","logger","promoteBuffers","promoteLongs","promoteValues","compression","retryWrites"];function Y(e,t,n){if(n=n||{},!(this instanceof Y))return new Y(e,t,n);r.call(this);const o=n.promiseLibrary||Promise;(n=c(n,H)).promiseLibrary=o,this.s={dbCache:{},children:[],topology:t,options:n,logger:d("Db",n),bson:t?t.bson:null,readPreference:l.fromOptions(n),bufferMaxEntries:"number"==typeof n.bufferMaxEntries?n.bufferMaxEntries:-1,parentDb:n.parentDb||null,pkFactory:n.pkFactory||p,nativeParser:n.nativeParser||n.native_parser,promiseLibrary:o,noListener:"boolean"==typeof n.noListener&&n.noListener,readConcern:O.fromOptions(n),writeConcern:_.fromOptions(n),namespace:new S(e)},I(e),i(this,"serverConfig",this.s.topology),i(this,"bufferMaxEntries",this.s.bufferMaxEntries),i(this,"databaseName",this.s.namespace.db),n.parentDb||this.s.noListener||(t.on("error",C(this,"error",this)),t.on("timeout",C(this,"timeout",this)),t.on("close",C(this,"close",this)),t.on("parseError",C(this,"parseError",this)),t.once("open",C(this,"open",this)),t.once("fullsetup",C(this,"fullsetup",this)),t.once("all",C(this,"all",this)),t.on("reconnect",C(this,"reconnect",this)))}o(Y,r),Y.prototype.on=b((function(){return Y.super_.prototype.on.apply(this,arguments)}),"Listening to events on the Db class has been deprecated and will be removed in the next major version."),Y.prototype.once=b((function(){return Y.super_.prototype.once.apply(this,arguments)}),"Listening to events on the Db class has been deprecated and will be removed in the next major version."),Object.defineProperty(Y.prototype,"topology",{enumerable:!0,get:function(){return this.s.topology}}),Object.defineProperty(Y.prototype,"options",{enumerable:!0,get:function(){return this.s.options}}),Object.defineProperty(Y.prototype,"slaveOk",{enumerable:!0,get:function(){return null!=this.s.options.readPreference&&("primary"!==this.s.options.readPreference||"primary"!==this.s.options.readPreference.mode)}}),Object.defineProperty(Y.prototype,"readConcern",{enumerable:!0,get:function(){return this.s.readConcern}}),Object.defineProperty(Y.prototype,"readPreference",{enumerable:!0,get:function(){return null==this.s.readPreference?l.primary:this.s.readPreference}}),Object.defineProperty(Y.prototype,"writeConcern",{enumerable:!0,get:function(){return this.s.writeConcern}}),Object.defineProperty(Y.prototype,"namespace",{enumerable:!0,get:function(){return this.s.namespace.toString()}}),Y.prototype.command=function(e,t,n){"function"==typeof t&&(n=t,t={}),t=Object.assign({},t);const r=new j(this,e,t);return K(this.s.topology,r,n)},Y.prototype.aggregate=function(e,t,n){"function"==typeof t&&(n=t,t={}),null==t&&null==n&&(t={});const r=new T(this.s.topology,new A(this,e,t),t);if("function"!=typeof n)return r;n(null,r)},Y.prototype.admin=function(){return new(n(218))(this,this.s.topology,this.s.promiseLibrary)};const G=["pkFactory","readPreference","serializeFunctions","strict","readConcern","ignoreUndefined","promoteValues","promoteBuffers","promoteLongs"];Y.prototype.collection=function(e,t,n){"function"==typeof t&&(n=t,t={}),t=t||{},(t=Object.assign({},t)).promiseLibrary=this.s.promiseLibrary,t.readConcern=t.readConcern?new O(t.readConcern.level):this.readConcern,this.s.options.ignoreUndefined&&(t.ignoreUndefined=this.s.options.ignoreUndefined);for(const e of G)e in t||void 0===this.s.options[e]||(t[e]=this.s.options[e]);if(null==(t=m(t,this.s.options))||!t.strict)try{const r=new h(this,this.s.topology,this.databaseName,e,this.s.pkFactory,t);return n&&n(null,r),r}catch(e){if(e instanceof f&&n)return n(e);throw e}if("function"!=typeof n)throw u(`A callback is required in strict mode. While getting collection ${e}`);if(this.serverConfig&&this.serverConfig.isDestroyed())return n(new f("topology was destroyed"));const r=Object.assign({},t,{nameOnly:!0});this.listCollections({name:e},r).toArray((r,o)=>{if(null!=r)return a(n,r,null);if(0===o.length)return a(n,u(`Collection ${e} does not exist. Currently in strict mode.`),null);try{return a(n,null,new h(this,this.s.topology,this.databaseName,e,this.s.pkFactory,t))}catch(r){return a(n,r,null)}})},Y.prototype.createCollection=v({name:"Db.createCollection",deprecatedOptions:["autoIndexId","strict","w","wtimeout","j"],optionsIndex:1},(function(e,t,n){"function"==typeof t&&(n=t,t={}),(t=t||{}).promiseLibrary=t.promiseLibrary||this.s.promiseLibrary,t.readConcern=t.readConcern?new O(t.readConcern.level):this.readConcern;const r=new D(this,e,t);return K(this.s.topology,r,n)})),Y.prototype.stats=function(e,t){"function"==typeof e&&(t=e,e={});const n={dbStats:!0};null!=(e=e||{}).scale&&(n.scale=e.scale),null==e.readPreference&&this.s.readPreference&&(e.readPreference=this.s.readPreference);const r=new R(this,e,null,n);return K(this.s.topology,r,t)},Y.prototype.listCollections=function(e,t){return e=e||{},t=t||{},new s(this.s.topology,new z(this,e,t),t)},Y.prototype.eval=b((function(e,t,n,r){const o=Array.prototype.slice.call(arguments,1);return r="function"==typeof o[o.length-1]?o.pop():void 0,t=o.length?o.shift():t,n=o.length&&o.shift()||{},g(this.s.topology,E,[this,e,t,n,r])}),"Db.eval is deprecated as of MongoDB version 3.2"),Y.prototype.renameCollection=function(e,t,n,r){"function"==typeof n&&(r=n,n={}),(n=Object.assign({},n,{readPreference:l.PRIMARY})).new_collection=!0;const o=new F(this.collection(e),t,n);return K(this.s.topology,o,r)},Y.prototype.dropCollection=function(e,t,n){"function"==typeof t&&(n=t,t={});const r=new B(this,e,t=t||{});return K(this.s.topology,r,n)},Y.prototype.dropDatabase=function(e,t){"function"==typeof e&&(t=e,e={});const n=new L(this,e=e||{});return K(this.s.topology,n,t)},Y.prototype.collections=function(e,t){"function"==typeof e&&(t=e,e={});const n=new M(this,e=e||{});return K(this.s.topology,n,t)},Y.prototype.executeDbAdminCommand=function(e,t,n){"function"==typeof t&&(n=t,t={}),(t=t||{}).readPreference=l.resolve(this,t);const r=new q(this,e,t);return K(this.s.topology,r,n)},Y.prototype.createIndex=function(e,t,n,r){"function"==typeof n&&(r=n,n={}),n=n?Object.assign({},n):{};const o=new P(this,e,t,n);return K(this.s.topology,o,r)},Y.prototype.ensureIndex=b((function(e,t,n,r){return"function"==typeof n&&(r=n,n={}),n=n||{},g(this.s.topology,x,[this,e,t,n,r])}),"Db.ensureIndex is deprecated as of MongoDB version 3.0 / driver version 2.0"),Y.prototype.addChild=function(e){if(this.s.parentDb)return this.s.parentDb.addChild(e);this.s.children.push(e)},Y.prototype.addUser=function(e,t,n,r){"function"==typeof n&&(r=n,n={}),n=n||{},"string"==typeof e&&null!=t&&"object"==typeof t&&(n=t,t=null);const o=new k(this,e,t,n);return K(this.s.topology,o,r)},Y.prototype.removeUser=function(e,t,n){"function"==typeof t&&(n=t,t={});const r=new W(this,e,t=t||{});return K(this.s.topology,r,n)},Y.prototype.setProfilingLevel=function(e,t,n){"function"==typeof t&&(n=t,t={});const r=new V(this,e,t=t||{});return K(this.s.topology,r,n)},Y.prototype.profilingInfo=b((function(e,t){return"function"==typeof e&&(t=e,e={}),e=e||{},g(this.s.topology,N,[this,e,t])}),"Db.profilingInfo is deprecated. Query the system.profile collection directly."),Y.prototype.profilingLevel=function(e,t){"function"==typeof e&&(t=e,e={});const n=new $(this,e=e||{});return K(this.s.topology,n,t)},Y.prototype.indexInformation=function(e,t,n){"function"==typeof t&&(n=t,t={});const r=new U(this,e,t=t||{});return K(this.s.topology,r,n)},Y.prototype.unref=function(){this.s.topology.unref()},Y.prototype.watch=function(e,t){return e=e||[],t=t||{},Array.isArray(e)||(t=e,e=[]),new y(this,e,t)},Y.prototype.getLogger=function(){return this.s.logger},Y.SYSTEM_NAMESPACE_COLLECTION=w.SYSTEM_NAMESPACE_COLLECTION,Y.SYSTEM_INDEX_COLLECTION=w.SYSTEM_INDEX_COLLECTION,Y.SYSTEM_PROFILE_COLLECTION=w.SYSTEM_PROFILE_COLLECTION,Y.SYSTEM_USER_COLLECTION=w.SYSTEM_USER_COLLECTION,Y.SYSTEM_COMMAND_COLLECTION=w.SYSTEM_COMMAND_COLLECTION,Y.SYSTEM_JS_COLLECTION=w.SYSTEM_JS_COLLECTION,e.exports=Y},function(e,t,n){"use strict";const r=n(2).Server,o=n(26),i=n(35).TopologyBase,s=n(35).Store,a=n(2).MongoError,c=n(0).MAX_JS_INT,u=n(0).translateOptions,l=n(0).filterOptions,f=n(0).mergeOptions;var p=["ha","haInterval","acceptableLatencyMS","poolSize","ssl","checkServerIdentity","sslValidate","sslCA","sslCRL","sslCert","ciphers","ecdhCurve","sslKey","sslPass","socketOptions","bufferMaxEntries","store","auto_reconnect","autoReconnect","emitError","keepAlive","keepAliveInitialDelay","noDelay","connectTimeoutMS","socketTimeoutMS","family","loggerLevel","logger","reconnectTries","reconnectInterval","monitoring","appname","domainsEnabled","servername","promoteLongs","promoteValues","promoteBuffers","compression","promiseLibrary","monitorCommands"];class d extends i{constructor(e,t,n){super();const i=(n=l(n,p)).promiseLibrary;var d={force:!1,bufferMaxEntries:"number"==typeof n.bufferMaxEntries?n.bufferMaxEntries:c},h=n.store||new s(this,d);if(-1!==e.indexOf("/"))null!=t&&"object"==typeof t&&(n=t,t=null);else if(null==t)throw a.create({message:"port must be specified",driver:!0});var m="boolean"!=typeof n.auto_reconnect||n.auto_reconnect;m="boolean"==typeof n.autoReconnect?n.autoReconnect:m;var g=f({},{host:e,port:t,disconnectHandler:h,cursorFactory:o,reconnect:m,emitError:"boolean"!=typeof n.emitError||n.emitError,size:"number"==typeof n.poolSize?n.poolSize:5,monitorCommands:"boolean"==typeof n.monitorCommands&&n.monitorCommands});g=u(g,n);var y=n.socketOptions&&Object.keys(n.socketOptions).length>0?n.socketOptions:n;g=u(g,y),this.s={coreTopology:new r(g),sCapabilities:null,clonedOptions:g,reconnect:g.reconnect,emitError:g.emitError,poolSize:g.size,storeOptions:d,store:h,host:e,port:t,options:n,sessionPool:null,sessions:new Set,promiseLibrary:i||Promise}}connect(e,t){var n=this;"function"==typeof e&&(t=e,e={}),null==e&&(e=this.s.clonedOptions),"function"!=typeof t&&(t=null),e=Object.assign({},this.s.clonedOptions,e),n.s.options=e,n.s.storeOptions.bufferMaxEntries="number"==typeof e.bufferMaxEntries?e.bufferMaxEntries:-1;var r=function(){return function(e){["timeout","error","close"].forEach((function(e){n.s.coreTopology.removeListener(e,a[e])})),n.s.coreTopology.removeListener("connect",r);try{t(e)}catch(e){process.nextTick((function(){throw e}))}}},o=function(e){return function(t){"error"!==e&&n.emit(e,t)}},i=function(){n.s.store.flush()},s=function(e){return function(t,r){n.emit(e,t,r)}},a={timeout:r("timeout"),error:r("error"),close:r("close")};["timeout","error","close","serverOpening","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","serverClosed","topologyOpening","topologyClosed","topologyDescriptionChanged","commandStarted","commandSucceeded","commandFailed"].forEach((function(e){n.s.coreTopology.removeAllListeners(e)})),n.s.coreTopology.once("timeout",a.timeout),n.s.coreTopology.once("error",a.error),n.s.coreTopology.once("close",a.close),n.s.coreTopology.once("connect",(function(){["timeout","error","close","destroy"].forEach((function(e){n.s.coreTopology.removeAllListeners(e)})),n.s.coreTopology.on("timeout",o("timeout")),n.s.coreTopology.once("error",o("error")),n.s.coreTopology.on("close",o("close")),n.s.coreTopology.on("destroy",i),n.emit("open",null,n);try{t(null,n)}catch(e){process.nextTick((function(){throw e}))}})),n.s.coreTopology.on("reconnect",(function(){n.emit("reconnect",n),n.s.store.execute()})),n.s.coreTopology.on("reconnectFailed",(function(e){n.emit("reconnectFailed",e),n.s.store.flush(e)})),n.s.coreTopology.on("serverDescriptionChanged",s("serverDescriptionChanged")),n.s.coreTopology.on("serverHeartbeatStarted",s("serverHeartbeatStarted")),n.s.coreTopology.on("serverHeartbeatSucceeded",s("serverHeartbeatSucceeded")),n.s.coreTopology.on("serverHeartbeatFailed",s("serverHeartbeatFailed")),n.s.coreTopology.on("serverOpening",s("serverOpening")),n.s.coreTopology.on("serverClosed",s("serverClosed")),n.s.coreTopology.on("topologyOpening",s("topologyOpening")),n.s.coreTopology.on("topologyClosed",s("topologyClosed")),n.s.coreTopology.on("topologyDescriptionChanged",s("topologyDescriptionChanged")),n.s.coreTopology.on("commandStarted",s("commandStarted")),n.s.coreTopology.on("commandSucceeded",s("commandSucceeded")),n.s.coreTopology.on("commandFailed",s("commandFailed")),n.s.coreTopology.on("attemptReconnect",s("attemptReconnect")),n.s.coreTopology.on("monitoring",s("monitoring")),n.s.coreTopology.connect(e)}}Object.defineProperty(d.prototype,"poolSize",{enumerable:!0,get:function(){return this.s.coreTopology.connections().length}}),Object.defineProperty(d.prototype,"autoReconnect",{enumerable:!0,get:function(){return this.s.reconnect}}),Object.defineProperty(d.prototype,"host",{enumerable:!0,get:function(){return this.s.host}}),Object.defineProperty(d.prototype,"port",{enumerable:!0,get:function(){return this.s.port}}),e.exports=d},function(e,t,n){"use strict";class r extends Error{constructor(e){super(e),this.name="MongoCryptError",Error.captureStackTrace(this,this.constructor)}}e.exports={debug:function(e){process.env.MONGODB_CRYPT_DEBUG&&console.log(e)},databaseNamespace:function(e){return e.split(".")[0]},collectionNamespace:function(e){return e.split(".").slice(1).join(".")},MongoCryptError:r,promiseOrCallback:function(e,t){if("function"!=typeof e)return new Promise((e,n)=>{t((function(t,r){return null!=t?n(t):arguments.length>2?e(Array.prototype.slice.call(arguments,1)):void e(r)}))});t((function(t){if(null==t)e.apply(this,arguments);else try{e(t)}catch(e){return process.nextTick(()=>{throw e})}}))}}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.noSplitSplitterOptions=t.mongoSplitterOptions=t.sqliteSplitterOptions=t.postgreSplitterOptions=t.mssqlSplitterOptions=t.mysqlSplitterOptions=t.defaultSplitterOptions=void 0,t.defaultSplitterOptions={stringsBegins:["'"],stringsEnds:{"'":"'"},stringEscapes:{"'":"'"},allowSemicolon:!0,allowCustomDelimiter:!1,allowGoDelimiter:!1,allowDollarDollarString:!1,noSplit:!1,doubleDashComments:!0,multilineComments:!0,javaScriptComments:!1,returnRichInfo:!1},t.mysqlSplitterOptions=Object.assign(Object.assign({},t.defaultSplitterOptions),{allowCustomDelimiter:!0,stringsBegins:["'","`"],stringsEnds:{"'":"'","`":"`"},stringEscapes:{"'":"\\","`":"`"}}),t.mssqlSplitterOptions=Object.assign(Object.assign({},t.defaultSplitterOptions),{allowSemicolon:!1,allowGoDelimiter:!0,stringsBegins:["'","["],stringsEnds:{"'":"'","[":"]"},stringEscapes:{"'":"'"}}),t.postgreSplitterOptions=Object.assign(Object.assign({},t.defaultSplitterOptions),{allowDollarDollarString:!0,stringsBegins:["'",'"'],stringsEnds:{"'":"'",'"':'"'},stringEscapes:{"'":"'",'"':'"'}}),t.sqliteSplitterOptions=Object.assign(Object.assign({},t.defaultSplitterOptions),{stringsBegins:["'",'"'],stringsEnds:{"'":"'",'"':'"'},stringEscapes:{"'":"'",'"':'"'}}),t.mongoSplitterOptions=Object.assign(Object.assign({},t.defaultSplitterOptions),{stringsBegins:["'",'"'],stringsEnds:{"'":"'",'"':'"'},stringEscapes:{"'":"\\",'"':"\\"}}),t.noSplitSplitterOptions=Object.assign(Object.assign({},t.defaultSplitterOptions),{noSplit:!0})},function(e,t,n){var r=n(147);e.exports=function(e){return r(e,5)}},function(e,t,n){var r=n(63),o=n(242),i=n(243),s=n(244),a=n(245),c=n(246);function u(e){var t=this.__data__=new r(e);this.size=t.size}u.prototype.clear=o,u.prototype.delete=i,u.prototype.get=s,u.prototype.has=a,u.prototype.set=c,e.exports=u},function(e,t,n){var r=n(31)(n(19),"Map");e.exports=r},function(e,t,n){var r=n(253),o=n(260),i=n(262),s=n(263),a=n(264);function c(e){var t=-1,n=null==e?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}c.prototype.clear=r,c.prototype.delete=o,c.prototype.get=i,c.prototype.has=s,c.prototype.set=a,e.exports=c},function(e,t,n){var r=n(107),o=n(65),i=Object.prototype.hasOwnProperty;e.exports=function(e,t,n){var s=e[t];i.call(e,t)&&o(s,n)&&(void 0!==n||t in e)||r(e,t,n)}},function(e,t,n){var r=n(151);e.exports=function(e,t,n){"__proto__"==t&&r?r(e,t,{configurable:!0,enumerable:!0,value:n,writable:!0}):e[t]=n}},function(e,t,n){var r=n(268),o=n(15),i=Object.prototype,s=i.hasOwnProperty,a=i.propertyIsEnumerable,c=r(function(){return arguments}())?r:function(e){return o(e)&&s.call(e,"callee")&&!a.call(e,"callee")};e.exports=c},function(e,t,n){(function(e){var r=n(19),o=n(269),i=t&&!t.nodeType&&t,s=i&&"object"==typeof e&&e&&!e.nodeType&&e,a=s&&s.exports===i?r.Buffer:void 0,c=(a?a.isBuffer:void 0)||o;e.exports=c}).call(this,n(62)(e))},function(e,t){e.exports=function(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=9007199254740991}},function(e,t){var n=Object.prototype;e.exports=function(e){var t=e&&e.constructor;return e===("function"==typeof t&&t.prototype||n)}},function(e,t,n){var r=n(152),o=n(274),i=n(38);e.exports=function(e){return i(e)?r(e,!0):o(e)}},function(e,t,n){var r=n(279),o=n(155),i=Object.prototype.propertyIsEnumerable,s=Object.getOwnPropertySymbols,a=s?function(e){return null==e?[]:(e=Object(e),r(s(e),(function(t){return i.call(e,t)})))}:o;e.exports=a},function(e,t){e.exports=function(e,t){for(var n=-1,r=t.length,o=e.length;++n<r;)e[o+n]=t[n];return e}},function(e,t,n){var r=n(154)(Object.getPrototypeOf,Object);e.exports=r},function(e,t,n){var r=n(161);e.exports=function(e){var t=new e.constructor(e.byteLength);return new r(t).set(new r(e)),t}},function(e,t,n){var r=n(12),o=n(71),i=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,s=/^\w*$/;e.exports=function(e,t){if(r(e))return!1;var n=typeof e;return!("number"!=n&&"symbol"!=n&&"boolean"!=n&&null!=e&&!o(e))||(s.test(e)||!i.test(e)||null!=t&&e in Object(t))}},function(e,t,n){var r=n(105),o=n(321),i=n(322);function s(e){var t=-1,n=null==e?0:e.length;for(this.__data__=new r;++t<n;)this.add(e[t])}s.prototype.add=s.prototype.push=o,s.prototype.has=i,e.exports=s},function(e,t){e.exports=function(e,t){return e.has(t)}},function(e,t,n){"use strict";var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function s(e){try{c(r.next(e))}catch(e){i(e)}}function a(e){try{c(r.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((r=r.apply(e,t||[])).next())}))},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DatabaseAnalyser=void 0;const i=o(n(333)),s=o(n(359)),a=o(n(177)),c=o(n(52)),u=["tables","collections","views","matviews","functions","procedures","triggers"],l=e=>t=>(0,a.default)(t,e);class f{constructor(e,t,n){this.pool=e,this.driver=t,this.singleObjectId=null,this.dialect=(null==t?void 0:t.dialectByVersion)&&(null==t?void 0:t.dialectByVersion(n))||(null==t?void 0:t.dialect)}_runAnalysis(){return r(this,void 0,void 0,(function*(){return f.createEmptyStructure()}))}_getFastSnapshot(){return r(this,void 0,void 0,(function*(){return null}))}_computeSingleObjectId(){return r(this,void 0,void 0,(function*(){}))}addEngineField(e){var t;if(null===(t=this.driver)||void 0===t?void 0:t.engine){for(const t of u)if(e[t])for(const n of e[t])n.engine=this.driver.engine;return e.engine=this.driver.engine,e}}fullAnalysis(){return r(this,void 0,void 0,(function*(){return this.addEngineField(yield this._runAnalysis())}))}singleObjectAnalysis(e,t){var n,o;return r(this,void 0,void 0,(function*(){this.singleObjectFilter=Object.assign(Object.assign({},e),{typeField:t}),yield this._computeSingleObjectId();const r=this.addEngineField(yield this._runAnalysis());return 1==(null===(n=r[t])||void 0===n?void 0:n.length)?r[t][0]:null===(o=r[t])||void 0===o?void 0:o.find(t=>t.pureName==e.pureName&&t.schemaName==e.schemaName)}))}incrementalAnalysis(e){return r(this,void 0,void 0,(function*(){this.structure=e;const t=yield this.getModifications();if(null==t)return this.structure=null,this.addEngineField(yield this._runAnalysis());const n=t.filter(e=>"setTableRowCounts"!=e.action),r=t.find(e=>"setTableRowCounts"==e.action);let o=null;if(r){const t=(i=e,s=r.rowCounts,Object.assign(Object.assign({},i),{tables:(i.tables||[]).map(e=>{var t,n;return Object.assign(Object.assign({},e),{tableRowCount:null!==(n=null===(t=s.find(t=>t.objectId==e.objectId))||void 0===t?void 0:t.tableRowCount)&&void 0!==n?n:e.tableRowCount})})}));(function(e,t){for(const n of e.tables||[]){const e=(t.tables||[]).find(e=>e.objectId==n.objectId);if((null==n?void 0:n.tableRowCount)!==(null==e?void 0:e.tableRowCount))return!0}return!1})(e,t)&&(o=t)}var i,s;return 0==n.length?o?this.addEngineField(o):null:(this.modifications=n,o&&(this.structure=o),console.log("DB modifications detected:",this.modifications),this.addEngineField(this.mergeAnalyseResult(yield this._runAnalysis())))}))}mergeAnalyseResult(e){if(null==this.structure)return Object.assign(Object.assign({},f.createEmptyStructure()),e);const t={};for(const n of u){const r=this.modifications.filter(e=>"remove"==e.action&&e.objectTypeField==n).map(e=>e.objectId),o=e[n]||[],s=[...r,...o.map(e=>e.objectId)];t[n]=(0,i.default)([...(this.structure[n]||[]).filter(e=>!s.includes(e.objectId)),...o],e=>e.pureName);for(const e of t[n]){const t=(this.structure[n]||[]).find(t=>t.objectId==e.objectId);if(t)for(const n in t)e[n]||(e[n]=t[n])}}return t}getRequestedObjectPureNames(e,t){if(this.singleObjectFilter){const{typeField:t,pureName:n}=this.singleObjectFilter;if(t==e)return[n]}return this.modifications?this.modifications.filter(t=>t.objectTypeField==e).filter(e=>e.newName).map(e=>e.newName.pureName):t}createQuery(e,t){if(this.singleObjectFilter){const{typeField:n}=this.singleObjectFilter;return this.singleObjectId&&(t&&t.includes(n))?e.replace(/=OBJECT_ID_CONDITION/g,` = '${this.singleObjectId}'`):null}if(!this.modifications||!t||0==this.modifications.length)return e.replace(/=OBJECT_ID_CONDITION/g," is not null");if(this.modifications.some(e=>t.includes(e.objectTypeField)&&"all"==e.action))return e.replace(/=OBJECT_ID_CONDITION/g," is not null");const n=this.modifications.filter(e=>t.includes(e.objectTypeField)&&("add"==e.action||"change"==e.action)).map(e=>e.objectId);return 0==n.length?e.replace(/=OBJECT_ID_CONDITION/g," = '0'"):e.replace(/=OBJECT_ID_CONDITION/g,` in (${n.map(e=>`'${e}'`).join(",")})`)}getDeletedObjectsForField(e,t){const n=e[t];return n&&this.structure[t]?this.structure[t].filter(e=>!n.find(t=>e.objectId==t.objectId)).map(e=>({oldName:(0,a.default)(e,["schemaName","pureName"]),objectId:e.objectId,action:"remove",objectTypeField:t})):[]}getDeletedObjects(e){return[...this.getDeletedObjectsForField(e,"tables"),...this.getDeletedObjectsForField(e,"collections"),...this.getDeletedObjectsForField(e,"views"),...this.getDeletedObjectsForField(e,"matviews"),...this.getDeletedObjectsForField(e,"procedures"),...this.getDeletedObjectsForField(e,"functions"),...this.getDeletedObjectsForField(e,"triggers")]}getModifications(){return r(this,void 0,void 0,(function*(){const e=yield this._getFastSnapshot();if(!e)return null;const t=[];for(const n in e){const r=e[n];if(null!==r){if(void 0!==r)for(const e of r){const{objectId:r,schemaName:o,pureName:i,contentHash:s}=e,c=this.structure[n].find(e=>e.objectId==r);if(c&&s&&c.contentHash==s)continue;const u=c?{newName:{schemaName:o,pureName:i},oldName:(0,a.default)(c,["schemaName","pureName"]),action:"change",objectTypeField:n,objectId:r}:{newName:{schemaName:o,pureName:i},action:"add",objectTypeField:n,objectId:r};t.push(u)}}else t.push({objectTypeField:n,action:"all"})}const n=(e.tables||[]).filter(e=>null!=e.tableRowCount).map(e=>({objectId:e.objectId,tableRowCount:e.tableRowCount}));return n.length>0&&t.push({action:"setTableRowCounts",rowCounts:n}),[...(0,c.default)(t),...this.getDeletedObjects(e)]}))}safeQuery(e){return r(this,void 0,void 0,(function*(){try{return yield this.driver.query(this.pool,e)}catch(e){return console.log("Error running analyser query",e.message),{rows:[]}}}))}static createEmptyStructure(){return{tables:[],collections:[],views:[],matviews:[],functions:[],procedures:[],triggers:[],schemas:[]}}static byTableFilter(e){return t=>t.pureName==e.pureName&&t.schemaName==t.schemaName}static extractPrimaryKeys(e,t){const n=t.filter(f.byTableFilter(e));if(0!=n.length)return Object.assign(Object.assign({},(0,a.default)(n[0],["constraintName","schemaName","pureName"])),{constraintType:"primaryKey",columns:n.map(l("columnName"))})}static extractForeignKeys(e,t){const n=(0,s.default)(t.filter(f.byTableFilter(e)),"constraintName");return Object.keys(n).map(e=>Object.assign(Object.assign({constraintName:e,constraintType:"foreignKey"},(0,a.default)(n[e][0],["constraintName","schemaName","pureName","refSchemaName","refTableName","updateAction","deleteAction"])),{columns:n[e].map(l(["columnName","refColumnName"]))}))}}t.DatabaseAnalyser=f},function(e,t,n){var r=n(336),o=n(344),i=n(74),s=n(12),a=n(347);e.exports=function(e){return"function"==typeof e?e:null==e?i:"object"==typeof e?s(e)?o(e[0],e[1]):r(e):a(e)}},function(e,t,n){var r=n(338),o=n(15);e.exports=function e(t,n,i,s,a){return t===n||(null==t||null==n||!o(t)&&!o(n)?t!=t&&n!=n:r(t,n,i,s,e,a))}},function(e,t){e.exports=function(e){var t=-1,n=Array(e.size);return e.forEach((function(e){n[++t]=e})),n}},function(e,t,n){var r=n(25),o=n(15);e.exports=function(e){return"number"==typeof e||o(e)&&"[object Number]"==r(e)}},function(e,t,n){var r,o,i=n(369),s=n(370),a=0,c=0;e.exports=function(e,t,n){var u=t&&n||0,l=t||[],f=(e=e||{}).node||r,p=void 0!==e.clockseq?e.clockseq:o;if(null==f||null==p){var d=i();null==f&&(f=r=[1|d[0],d[1],d[2],d[3],d[4],d[5]]),null==p&&(p=o=16383&(d[6]<<8|d[7]))}var h=void 0!==e.msecs?e.msecs:(new Date).getTime(),m=void 0!==e.nsecs?e.nsecs:c+1,g=h-a+(m-c)/1e4;if(g<0&&void 0===e.clockseq&&(p=p+1&16383),(g<0||h>a)&&void 0===e.nsecs&&(m=0),m>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");a=h,c=m,o=p;var y=(1e4*(268435455&(h+=122192928e5))+m)%4294967296;l[u++]=y>>>24&255,l[u++]=y>>>16&255,l[u++]=y>>>8&255,l[u++]=255&y;var b=h/4294967296*1e4&268435455;l[u++]=b>>>8&255,l[u++]=255&b,l[u++]=b>>>24&15|16,l[u++]=b>>>16&255,l[u++]=p>>>8|128,l[u++]=255&p;for(var v=0;v<6;++v)l[u+v]=f[v];return t||s(l)}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dumpSqlFromDefinition=t.dumpSqlRelation=t.dumpSqlSourceRef=t.dumpSqlSourceDef=void 0;const r=n(76),o=n(127);function i(e,t){let n=0;if(null!=t.name&&n++,null!=t.subQuery&&n++,null!=t.subQueryString&&n++,1!=n)throw new Error("sqltree.Source should have exactly one source");null!=t.name&&e.put("%f",t.name),t.subQuery&&(e.put("("),(0,r.dumpSqlSelect)(e,t.subQuery),e.put(")")),t.subQueryString&&(e.put("("),e.putRaw(t.subQueryString),e.put(")")),t.alias&&e.put(" %i",t.alias)}function s(e,t){e.put("&n %k ",t.joinType),i(e,t),t.conditions&&t.conditions.length>0&&(e.put(" ^on "),e.putCollection(" ^and ",t.conditions,t=>(0,o.dumpSqlCondition)(e,t)))}t.dumpSqlSourceDef=i,t.dumpSqlSourceRef=function(e,t){return t.alias?(e.put("%i",t.alias),!0):!!t.name&&(e.put("%f",t.name),!0)},t.dumpSqlRelation=s,t.dumpSqlFromDefinition=function(e,t){i(e,t),e.put(" "),t.relations&&t.relations.forEach(t=>s(e,t))}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dumpSqlCondition=void 0;const r=n(180),o=n(76);t.dumpSqlCondition=function e(t,n){switch(n.conditionType){case"binary":(0,r.dumpSqlExpression)(t,n.left),t.put(" %s ",n.operator),(0,r.dumpSqlExpression)(t,n.right);break;case"isNull":(0,r.dumpSqlExpression)(t,n.expr),t.put(" ^is ^null");break;case"isNotNull":(0,r.dumpSqlExpression)(t,n.expr),t.put(" ^is ^not ^null");break;case"isEmpty":t.put("^trim("),(0,r.dumpSqlExpression)(t,n.expr),t.put(") = ''");break;case"isNotEmpty":t.put("^trim("),(0,r.dumpSqlExpression)(t,n.expr),t.put(") <> ''");break;case"and":case"or":t.putCollection(` ^${n.conditionType} `,n.conditions,n=>{t.putRaw("("),e(t,n),t.putRaw(")")});break;case"like":(0,r.dumpSqlExpression)(t,n.left),t.put(t.dialect.ilike?" ^ilike ":" ^like "),(0,r.dumpSqlExpression)(t,n.right);break;case"notLike":(0,r.dumpSqlExpression)(t,n.left),t.put(" ^not ^like "),(0,r.dumpSqlExpression)(t,n.right);break;case"not":t.put("^not ("),e(t,n.condition),t.put(")");break;case"exists":t.put("^exists ("),(0,o.dumpSqlSelect)(t,n.subQuery),t.put(")");break;case"notExists":t.put("^not ^exists ("),(0,o.dumpSqlSelect)(t,n.subQuery),t.put(")");break;case"between":(0,r.dumpSqlExpression)(t,n.expr),t.put(" ^between "),(0,r.dumpSqlExpression)(t,n.left),t.put(" ^and "),(0,r.dumpSqlExpression)(t,n.right)}}},function(e,t,n){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.modelCompareDbDiffOptions=t.matchPairedObjects=t.getAlterDatabaseScript=t.getAlterTableScript=t.createAlterDatabasePlan=t.createAlterTablePlan=t.testEqualSqlObjects=t.testEqualTables=t.testEqualTypes=t.testEqualColumns=t.generateDbPairingId=t.generateTablePairingId=void 0;const o=r(n(125)),i=n(386),s=r(n(388)),a=r(n(184)),c=r(n(102)),u=r(n(396)),l=r(n(177));function f(e){var t,n,r,i,s;return e?e.pairingId?e:Object.assign(Object.assign({},e),{columns:null===(t=e.columns)||void 0===t?void 0:t.map(e=>Object.assign(Object.assign({},e),{pairingId:e.pairingId||(0,o.default)()})),foreignKeys:null===(n=e.foreignKeys)||void 0===n?void 0:n.map(e=>Object.assign(Object.assign({},e),{pairingId:e.pairingId||(0,o.default)()})),checks:null===(r=e.checks)||void 0===r?void 0:r.map(e=>Object.assign(Object.assign({},e),{pairingId:e.pairingId||(0,o.default)()})),indexes:null===(i=e.indexes)||void 0===i?void 0:i.map(e=>Object.assign(Object.assign({},e),{pairingId:e.pairingId||(0,o.default)()})),uniques:null===(s=e.uniques)||void 0===s?void 0:s.map(e=>Object.assign(Object.assign({},e),{pairingId:e.pairingId||(0,o.default)()})),pairingId:e.pairingId||(0,o.default)()}):e}function p(e){return e.objectTypeField?Object.assign(Object.assign({},e),{pairingId:e.pairingId||(0,o.default)()}):e}function d(e,t,n){return n.ignoreCase?(e||"").toLowerCase()==(t||"").toLowerCase():e==t}function h(e,t,n){return null==e||null==t?e==t:function(e,t,n){return"ignore"==n.schemaMode&&(e=null),"ignoreImplicit"==n.schemaMode&&e==n.leftImplicitSchema&&(e=null),"ignore"==n.schemaMode&&(t=null),"ignoreImplicit"==n.schemaMode&&t==n.rightImplicitSchema&&(t=null),d(e,t,n)}(e.schemaName,t.schemaName,n)&&d(e.pureName,t.pureName,n)}function m(e,t,n,r,o={}){if(n&&!d(e.columnName,t.columnName,o))return!1;if(e.computedExpression!=t.computedExpression)return console.debug(`Column ${e.pureName}.${e.columnName}, ${t.pureName}.${t.columnName}: different computed expression: ${e.computedExpression}, ${t.computedExpression}`),!1;if(null!=e.computedExpression)return!0;if(r){if(null==e.defaultValue){if(e.defaultValue!=t.defaultValue)return console.debug(`Column ${e.pureName}.${e.columnName}, ${t.pureName}.${t.columnName}: different default value: ${e.defaultValue}, ${t.defaultValue}`),!1}else if(e.defaultValue!=t.defaultValue)return console.debug(`Column ${e.pureName}.${e.columnName}, ${t.pureName}.${t.columnName}: different default value: ${e.defaultValue}, ${t.defaultValue}`),!1;if(e.defaultConstraint!=t.defaultConstraint)return console.debug(`Column ${e.pureName}.${e.columnName}, ${t.pureName}.${t.columnName}: different default constraint: ${e.defaultConstraint}, ${t.defaultConstraint}`),!1}return(e.notNull||!1)!=(t.notNull||!1)?(console.debug(`Column ${e.pureName}.${e.columnName}, ${t.pureName}.${t.columnName}: different nullability: ${e.notNull}, ${t.notNull}`),!1):(e.autoIncrement||!1)!=(t.autoIncrement||!1)?(console.debug(`Column ${e.pureName}.${e.columnName}, ${t.pureName}.${t.columnName}: different autoincrement: ${e.autoIncrement}, ${t.autoIncrement}`),!1):(e.isSparse||!1)!=(t.isSparse||!1)?(console.debug(`Column ${e.pureName}.${e.columnName}, ${t.pureName}.${t.columnName}: different is_sparse: ${e.isSparse}, ${t.isSparse}`),!1):(e.isUnsigned||!1)!=(t.isUnsigned||!1)?(console.debug(`Column ${e.pureName}.${e.columnName}, ${t.pureName}.${t.columnName}: different unsigned: ${e.isUnsigned}, ${t.isUnsigned}`),!1):(e.isZerofill||!1)!=(t.isZerofill||!1)?(console.debug(`Column ${e.pureName}.${e.columnName}, ${t.pureName}.${t.columnName}: different zerofill: ${e.isZerofill}, ${t.isZerofill}`),!1):(e.columnComment||"")!=(t.columnComment||"")?(console.debug(`Column ${e.pureName}.${e.columnName}, ${t.pureName}.${t.columnName}: different comment: ${e.columnComment}, ${t.columnComment}`),!1):!!g(e,t,o)}function g(e,t,n={}){return!!n.ignoreDataTypes||((e.dataType||"").toLowerCase()==(t.dataType||"").toLowerCase()||(console.debug(`Column ${e.pureName}.${e.columnName}, ${t.pureName}.${t.columnName}: different data type: ${e.dataType}, ${t.dataType}`),!1))}function y(e){const t=[];return e.primaryKey&&t.push(e.primaryKey),e.foreignKeys&&t.push(...e.foreignKeys),e.indexes&&t.push(...e.indexes),e.uniques&&t.push(...e.uniques),e.checks&&t.push(...e.checks),t}function b(e,t,n=null){const r=[];for(const o of e){const e=t.find(e=>e.pairingId==o.pairingId||n&&n(o,e));e?r.push([o,e]):r.push([o,null])}for(const e of t)r.find(t=>t[1]==e)||r.push([null,e]);return r}function v(e,t,n){var r,o,i;const s=n.preloadedRowsKey||(null===(o=null===(r=n.primaryKey)||void 0===r?void 0:r.columns)||void 0===o?void 0:o.map(e=>e.columnName));(null===(i=n.preloadedRows)||void 0===i?void 0:i.length)>0&&(null==s?void 0:s.length)>0&&e.fillPreloadedRows(n,null==t?void 0:t.preloadedRows,n.preloadedRows,s,n.preloadedRowsInsertOnly)}function S(e,t,n,r){const o=b(t.columns,n.columns),i=b(y(t),y(n),(e,t)=>"primaryKey"==e.constraintType&&"primaryKey"==t.constraintType);r.noDropConstraint||i.filter(e=>null==e[1]).forEach(t=>e.dropConstraint(t[0])),r.noDropColumn||o.filter(e=>null==e[1]).forEach(t=>e.dropColumn(t[0])),h(t,n,r)||r.noRenameTable||e.renameTable(t,n.pureName),o.filter(e=>null==e[0]).forEach(t=>e.createColumn(t[1])),o.filter(e=>e[0]&&e[1]).forEach(t=>{m(t[0],t[1],!0,!0,r)||(m(t[0],t[1],!1,!0,r)&&!r.noRenameColumn?e.renameColumn(t[0],t[1].columnName):e.changeColumn(t[0],t[1]))}),i.filter(e=>e[0]&&e[1]).forEach(t=>{(function(e,t,n={}){const r=[];return n.ignoreForeignKeyActions&&(r.push("updateAction"),r.push("deleteAction")),n.ignoreConstraintNames&&r.push("constraintName"),"ignore"==n.schemaMode&&(r.push("schemaName"),r.push("refSchemaName")),(0,s.default)((0,a.default)(e,r))==(0,s.default)((0,a.default)(t,r))})(t[0],t[1],r)||e.changeConstraint(t[0],t[1])}),i.filter(e=>null==e[0]).forEach(t=>e.createConstraint(t[1])),v(e,t,n)}function w(e,t,n){return e.createSql==t.createSql}function _(e,t,n,r,o,s){const a=new i.AlterPlan(r,o,s.dialect,n);return null==e?(a.createTable(t),v(a,null,t)):null==t?a.dropTable(e):S(a,e,t,n),a.transformPlan(),a}function O(e,t,n,r,o,s){const a=new i.AlterPlan(r,o,s.dialect,n);for(const r of["tables","views","procedures","matviews","functions"]){for(const o of e[r]||[]){const e=(t[r]||[]).find(e=>e.pairingId==o.pairingId);"tables"==r?null==e?n.noDropTable||a.dropTable(o):S(a,o,e,n):null==e?n.noDropSqlObject||a.dropSqlObject(o):w(o.createSql,e.createSql)||(a.recreates.sqlObjects+=1,n.noDropSqlObject||a.dropSqlObject(o),a.createSqlObject(e))}for(const n of t[r]||[]){const t=(e[r]||[]).find(e=>e.pairingId==n.pairingId);"tables"==r?null==t&&(a.createTable(n),v(a,null,n)):null==t&&a.createSqlObject(n)}}return a.transformPlan(),a}t.generateTablePairingId=f,t.generateDbPairingId=function(e){var t,n,r,o,i,s;return e?Object.assign(Object.assign({},e),{tables:null===(t=e.tables)||void 0===t?void 0:t.map(f),views:null===(n=e.views)||void 0===n?void 0:n.map(p),procedures:null===(r=e.procedures)||void 0===r?void 0:r.map(p),functions:null===(o=e.functions)||void 0===o?void 0:o.map(p),triggers:null===(i=e.triggers)||void 0===i?void 0:i.map(p),matviews:null===(s=e.matviews)||void 0===s?void 0:s.map(p)}):e},t.testEqualColumns=m,t.testEqualTypes=g,t.testEqualTables=function(e,t,n,r,o,s){const a=new i.AlterPlan(r,o,s.dialect,n);return S(a,e,t,n),0==a.operations.length},t.testEqualSqlObjects=w,t.createAlterTablePlan=_,t.createAlterDatabasePlan=O,t.getAlterTableScript=function(e,t,n,r,o,i){if(!e&&!t||!i)return{sql:"",recreates:[]};const s=_(e,t,n,r,o,i),a=i.createDumper({useHardSeparator:!0});return i.dialect.disableExplicitTransaction||a.beginTransaction(),s.run(a),i.dialect.disableExplicitTransaction||a.commitTransaction(),{sql:a.s,recreates:s.recreates}},t.getAlterDatabaseScript=function(e,t,n,r,o,i){const s=O(e,t,n,r,o,i),a=i.createDumper({useHardSeparator:!0});return i.dialect.disableExplicitTransaction||a.beginTransaction(),s.run(a),i.dialect.disableExplicitTransaction||a.commitTransaction(),{sql:a.s,recreates:s.recreates,isEmpty:0==s.operations.length}},t.matchPairedObjects=function(e,t,n){if(!e||!t)return null;const r=(0,c.default)(t);for(const t of["tables","views","procedures","matviews","functions"])for(const o of r[t]||[]){const r=e[t].find(e=>h(e,o,n));if(r&&(o.pairingId=r.pairingId,"tables"==t)){for(const e of o.columns){const t=r.columns.find(t=>d(t.columnName,e.columnName,n));t&&(e.pairingId=t.pairingId)}for(const e of o.foreignKeys){const t=r.foreignKeys.find(t=>d(t.refTableName,e.refTableName,n)&&(0,u.default)(t.columns.map(e=>(0,l.default)(e,["columnName","refColumnName"])),e.columns.map(e=>(0,l.default)(e,["columnName","refColumnName"]))));t&&(e.pairingId=t.pairingId)}for(const e of o.uniques){const t=r.uniques.find(t=>(0,u.default)(t.columns.map(e=>(0,l.default)(e,["columnName"])),e.columns.map(e=>(0,l.default)(e,["columnName"]))));t&&(e.pairingId=t.pairingId)}for(const e of o.indexes){const t=r.indexes.find(t=>d(t.constraintName,e.constraintName,n));t&&(e.pairingId=t.pairingId)}}}return r},t.modelCompareDbDiffOptions={ignoreCase:!0,schemaMode:"ignore",ignoreConstraintNames:!0,ignoreForeignKeyActions:!0,ignoreDataTypes:!0}},function(e,t,n){"use strict";if(void 0!==global.Map)e.exports=global.Map,e.exports.Map=global.Map;else{var r=function(e){this._keys=[],this._values={};for(var t=0;t<e.length;t++)if(null!=e[t]){var n=e[t],r=n[0],o=n[1];this._keys.push(r),this._values[r]={v:o,i:this._keys.length-1}}};r.prototype.clear=function(){this._keys=[],this._values={}},r.prototype.delete=function(e){var t=this._values[e];return null!=t&&(delete this._values[e],this._keys.splice(t.i,1),!0)},r.prototype.entries=function(){var e=this,t=0;return{next:function(){var n=e._keys[t++];return{value:void 0!==n?[n,e._values[n].v]:void 0,done:void 0===n}}}},r.prototype.forEach=function(e,t){t=t||this;for(var n=0;n<this._keys.length;n++){var r=this._keys[n];e.call(t,this._values[r].v,r,t)}},r.prototype.get=function(e){return this._values[e]?this._values[e].v:void 0},r.prototype.has=function(e){return null!=this._values[e]},r.prototype.keys=function(){var e=this,t=0;return{next:function(){var n=e._keys[t++];return{value:void 0!==n?n:void 0,done:void 0===n}}}},r.prototype.set=function(e,t){return this._values[e]?(this._values[e].v=t,this):(this._keys.push(e),this._values[e]={v:t,i:this._keys.length-1},this)},r.prototype.values=function(){var e=this,t=0;return{next:function(){var n=e._keys[t++];return{value:void 0!==n?e._values[n].v:void 0,done:void 0===n}}}},Object.defineProperty(r.prototype,"size",{enumerable:!0,get:function(){return this._keys.length}}),e.exports=r,e.exports.Map=r}},function(e,t){var n=function(e){if(!(this instanceof n))return new n(e);this._bsontype="Int32",this.value=e};n.prototype.valueOf=function(){return this.value},n.prototype.toJSON=function(){return this.value},e.exports=n,e.exports.Int32=n},function(e,t){e.exports=require("buffer")},function(e,t,n){"use strict";const r=n(409);function o(e,t,n,o){let i;"object"==typeof o?(i=o,r(!(i.hasOwnProperty("notFound")&&i.hasOwnProperty("default")),"optionalRequire: options set with both `notFound` and `default`")):i={message:o};try{return t?e.resolve(n):e(n)}catch(e){if("MODULE_NOT_FOUND"!==e.code||!function(e,t){const n=e.message.split("\n")[0];return n&&(n.includes(`'${t}'`)||n.includes(` ${t} `)||n.includes(` ${t}. `)||n.includes(` ${t}, `))}(e,n)){if("function"==typeof i.fail)return i.fail(e);throw e}if(i.message){const e="string"==typeof i.message?`${i.message} - `:"",r=t?"resolved":"found";a.log(`${e}optional module not ${r}`,n)}return"function"==typeof i.notFound?i.notFound(e):i.default}}const i=(e,t,n)=>o(e,!1,t,n),s=(e,t,n)=>o(e,!0,t,n);function a(e){const t=(t,n)=>i(e,t,n);return t.resolve=(t,n)=>s(e,t,n),t}a.try=i,a.tryResolve=s,a.resolve=s,a.log=(e,t)=>console.log(`Just FYI: ${e}; Path "${t}"`),e.exports=a},function(e,t,n){"use strict";var r=function(e,t,n){this.result=e,this.connection=t,this.message=n};r.prototype.toJSON=function(){let e=Object.assign({},this,this.result);return delete e.message,e},r.prototype.toString=function(){return JSON.stringify(this.toJSON())},e.exports=r},function(e,t,n){"use strict";var r=n(5).inherits,o=n(5).format,i=n(8).EventEmitter,s=n(10),a=n(16),c=n(9).debugOptions,u=n(9).retrieveBSON,l=n(414),f=n(3).MongoError,p=n(3).MongoNetworkError,d=n(199),h=n(17).CoreCursor,m=n(7),g=n(7).createCompressionInfo,y=n(7).resolveClusterTime,b=n(7).SessionMixins,v=n(4).relayEvents;const S=n(4).collationNotSupported,w=n(4).makeClientMetadata;var _=["reconnect","reconnectTries","reconnectInterval","emitError","cursorFactory","host","port","size","keepAlive","keepAliveInitialDelay","noDelay","connectionTimeout","checkServerIdentity","socketTimeout","ssl","ca","crl","cert","key","rejectUnauthorized","promoteLongs","promoteValues","promoteBuffers","servername"],O=0,T=!1,C={},x=u();function E(e){return null==e.s.parent?e.id:e.s.parent.id}var N=function(e){e=e||{},i.call(this),this.id=O++,this.s={options:Object.assign({metadata:w(e)},e),logger:a("Server",e),Cursor:e.cursorFactory||h,bson:e.bson||new x([x.Binary,x.Code,x.DBRef,x.Decimal128,x.Double,x.Int32,x.Long,x.Map,x.MaxKey,x.MinKey,x.ObjectId,x.BSONRegExp,x.Symbol,x.Timestamp]),pool:null,disconnectHandler:e.disconnectHandler,monitoring:"boolean"!=typeof e.monitoring||e.monitoring,inTopology:!!e.parent,monitoringInterval:"number"==typeof e.monitoringInterval?e.monitoringInterval:5e3,compression:{compressors:g(e)},parent:e.parent},this.s.parent||(this.s.clusterTime=null),this.ismaster=null,this.lastIsMasterMS=-1,this.monitoringProcessId=null,this.initialConnect=!0,this._type="server",this.lastUpdateTime=0,this.lastWriteDate=0,this.staleness=0};function I(e,t,n,r,i,s){return e.s.pool.isConnected()||!e.s.options.reconnect||null==e.s.disconnectHandler||i.monitoring?e.s.pool.isConnected()?void 0:(s(new f(o("no connection available to server %s",e.name))),!0):(e.s.disconnectHandler.add(t,n,r,i,s),!0)}r(N,i),Object.assign(N.prototype,b),Object.defineProperty(N.prototype,"type",{enumerable:!0,get:function(){return this._type}}),Object.defineProperty(N.prototype,"parserType",{enumerable:!0,get:function(){return x.native?"c++":"js"}}),Object.defineProperty(N.prototype,"logicalSessionTimeoutMinutes",{enumerable:!0,get:function(){return this.ismaster&&this.ismaster.logicalSessionTimeoutMinutes||null}}),Object.defineProperty(N.prototype,"clientMetadata",{enumerable:!0,get:function(){return this.s.options.metadata}}),Object.defineProperty(N.prototype,"clusterTime",{enumerable:!0,set:function(e){const t=this.s.parent?this.s.parent:this.s;y(t,e)},get:function(){return(this.s.parent?this.s.parent:this.s).clusterTime||null}}),N.enableServerAccounting=function(){T=!0,C={}},N.disableServerAccounting=function(){T=!1},N.servers=function(){return C},Object.defineProperty(N.prototype,"name",{enumerable:!0,get:function(){return this.s.options.host+":"+this.s.options.port}});var A=function(e,t){return function(n,r){if(e.s.logger.isInfo()){var i=n instanceof f?JSON.stringify(n):{};e.s.logger.info(o("server %s fired event %s out with message %s",e.name,t,i))}if("connect"===t){if(e.initialConnect=!1,e.ismaster=r.ismaster,e.lastIsMasterMS=r.lastIsMasterMS,r.agreedCompressor&&(e.s.pool.options.agreedCompressor=r.agreedCompressor),r.zlibCompressionLevel&&(e.s.pool.options.zlibCompressionLevel=r.zlibCompressionLevel),r.ismaster.$clusterTime){const t=r.ismaster.$clusterTime;e.clusterTime=t}"isdbgrid"===e.ismaster.msg&&(e._type="mongos"),e.s.monitoring&&(e.monitoringProcessId=setTimeout(function e(t){return function(){if(!t.s.pool.isDestroyed()){t.emit("monitoring",t);var n=(new Date).getTime();t.command("admin.$cmd",{ismaster:!0},{socketTimeout:"number"!=typeof t.s.options.connectionTimeout?2e3:t.s.options.connectionTimeout,monitoring:!0},(r,o)=>{t.lastIsMasterMS=(new Date).getTime()-n,t.s.pool.isDestroyed()||(o&&(t.ismaster=o.result),t.monitoringProcessId=setTimeout(e(t),t.s.monitoringInterval))})}}}(e),e.s.monitoringInterval)),m.emitServerDescriptionChanged(e,{address:e.name,arbiters:[],hosts:[],passives:[],type:m.getTopologyType(e)}),e.s.inTopology||m.emitTopologyDescriptionChanged(e,{topologyType:"Single",servers:[{address:e.name,arbiters:[],hosts:[],passives:[],type:m.getTopologyType(e)}]}),e.s.logger.isInfo()&&e.s.logger.info(o("server %s connected with ismaster [%s]",e.name,JSON.stringify(e.ismaster))),e.emit("connect",e)}else if("error"===t||"parseError"===t||"close"===t||"timeout"===t||"reconnect"===t||"attemptReconnect"===t||"reconnectFailed"===t){if(T&&-1!==["close","timeout","error","parseError","reconnectFailed"].indexOf(t)&&(e.s.inTopology||e.emit("topologyOpening",{topologyId:e.id}),delete C[e.id]),"close"===t&&m.emitServerDescriptionChanged(e,{address:e.name,arbiters:[],hosts:[],passives:[],type:"Unknown"}),"reconnectFailed"===t)return e.emit("reconnectFailed",n),void(e.listeners("error").length>0&&e.emit("error",n));if(-1!==["disconnected","connecting"].indexOf(e.s.pool.state)&&e.initialConnect&&-1!==["close","timeout","error","parseError"].indexOf(t))return e.initialConnect=!1,e.emit("error",new p(o("failed to connect to server [%s] on first connect [%s]",e.name,n)));if("reconnect"===t)return m.emitServerDescriptionChanged(e,{address:e.name,arbiters:[],hosts:[],passives:[],type:m.getTopologyType(e)}),e.emit(t,e);e.emit(t,n)}}};function k(e){return e.s.pool?e.s.pool.isDestroyed()?new f("server instance pool was destroyed"):void 0:new f("server instance is not connected")}N.prototype.connect=function(e){if(e=e||{},T&&(C[this.id]=this),this.s.pool&&!this.s.pool.isDisconnected()&&!this.s.pool.isDestroyed())throw new f(o("server instance in invalid state %s",this.s.pool.state));this.s.pool=new l(this,Object.assign(this.s.options,e,{bson:this.s.bson})),this.s.pool.on("close",A(this,"close")),this.s.pool.on("error",A(this,"error")),this.s.pool.on("timeout",A(this,"timeout")),this.s.pool.on("parseError",A(this,"parseError")),this.s.pool.on("connect",A(this,"connect")),this.s.pool.on("reconnect",A(this,"reconnect")),this.s.pool.on("reconnectFailed",A(this,"reconnectFailed")),v(this.s.pool,this,["commandStarted","commandSucceeded","commandFailed"]),this.s.inTopology||this.emit("topologyOpening",{topologyId:E(this)}),this.emit("serverOpening",{topologyId:E(this),address:this.name}),this.s.pool.connect()},N.prototype.auth=function(e,t){"function"==typeof t&&t(null,null)},N.prototype.getDescription=function(){var e=this.ismaster||{},t={type:m.getTopologyType(this),address:this.name};return e.hosts&&(t.hosts=e.hosts),e.arbiters&&(t.arbiters=e.arbiters),e.passives&&(t.passives=e.passives),e.setName&&(t.setName=e.setName),t},N.prototype.lastIsMaster=function(){return this.ismaster},N.prototype.unref=function(){this.s.pool.unref()},N.prototype.isConnected=function(){return!!this.s.pool&&this.s.pool.isConnected()},N.prototype.isDestroyed=function(){return!!this.s.pool&&this.s.pool.isDestroyed()},N.prototype.command=function(e,t,n,r){"function"==typeof n&&(r=n,n=(n={})||{});var i=function(e,t){if(k(e),t.readPreference&&!(t.readPreference instanceof s))throw new Error("readPreference must be an instance of ReadPreference")}(this,n);return i?r(i):(n=Object.assign({},n,{wireProtocolCommand:!1}),this.s.logger.isDebug()&&this.s.logger.debug(o("executing command [%s] against %s",JSON.stringify({ns:e,cmd:t,options:c(_,n)}),this.name)),I(this,"command",e,t,n,r)?void 0:S(this,t)?r(new f(`server ${this.name} does not support collation`)):void d.command(this,e,t,n,r))},N.prototype.query=function(e,t,n,r,o){d.query(this,e,t,n,r,o)},N.prototype.getMore=function(e,t,n,r,o){d.getMore(this,e,t,n,r,o)},N.prototype.killCursors=function(e,t,n){d.killCursors(this,e,t,n)},N.prototype.insert=function(e,t,n,r){"function"==typeof n&&(r=n,n=(n={})||{});var o=k(this);return o?r(o):I(this,"insert",e,t,n,r)?void 0:(t=Array.isArray(t)?t:[t],d.insert(this,e,t,n,r))},N.prototype.update=function(e,t,n,r){"function"==typeof n&&(r=n,n=(n={})||{});var o=k(this);return o?r(o):I(this,"update",e,t,n,r)?void 0:S(this,n)?r(new f(`server ${this.name} does not support collation`)):(t=Array.isArray(t)?t:[t],d.update(this,e,t,n,r))},N.prototype.remove=function(e,t,n,r){"function"==typeof n&&(r=n,n=(n={})||{});var o=k(this);return o?r(o):I(this,"remove",e,t,n,r)?void 0:S(this,n)?r(new f(`server ${this.name} does not support collation`)):(t=Array.isArray(t)?t:[t],d.remove(this,e,t,n,r))},N.prototype.cursor=function(e,t,n){const r=(n=n||{}).topology||this;return new(n.cursorFactory||this.s.Cursor)(r,e,t,n)},N.prototype.equals=function(e){return"string"==typeof e?this.name.toLowerCase()===e.toLowerCase():!!e.name&&this.name.toLowerCase()===e.name.toLowerCase()},N.prototype.connections=function(){return this.s.pool.allConnections()},N.prototype.selectServer=function(e,t,n){"function"==typeof e&&void 0===n&&(n=e,e=void 0,t={}),"function"==typeof t&&(n=t,t=e,e=void 0),n(null,this)};var M=["close","error","timeout","parseError","connect"];N.prototype.destroy=function(e,t){if(this._destroyed)"function"==typeof t&&t(null,null);else{"function"==typeof e&&(t=e,e={}),e=e||{};var n=this;if(T&&delete C[this.id],this.monitoringProcessId&&clearTimeout(this.monitoringProcessId),!n.s.pool||this._destroyed)return this._destroyed=!0,void("function"==typeof t&&t(null,null));this._destroyed=!0,e.emitClose&&n.emit("close",n),e.emitDestroy&&n.emit("destroy",n),M.forEach((function(e){n.s.pool.removeAllListeners(e)})),n.listeners("serverClosed").length>0&&n.emit("serverClosed",{topologyId:E(n),address:n.name}),n.listeners("topologyClosed").length>0&&!n.s.inTopology&&n.emit("topologyClosed",{topologyId:E(n)}),n.s.logger.isDebug()&&n.s.logger.debug(o("destroy called on server %s",n.name)),this.s.pool.destroy(e.force,t)}},e.exports=N},function(e,t,n){"use strict";const r=n(415),o=n(192),i=n(187),s=n(3).MongoError,a=n(3).MongoNetworkError,c=n(3).MongoNetworkTimeoutError,u=n(193).defaultAuthProviders,l=n(33).AuthContext,f=n(190),p=n(4).makeClientMetadata,d=f.MAX_SUPPORTED_WIRE_VERSION,h=f.MAX_SUPPORTED_SERVER_VERSION,m=f.MIN_SUPPORTED_WIRE_VERSION,g=f.MIN_SUPPORTED_SERVER_VERSION;let y;const b=["pfx","key","passphrase","cert","ca","ciphers","NPNProtocols","ALPNProtocols","servername","ecdhCurve","secureProtocol","secureContext","session","minDHSize","crl","rejectUnauthorized"];function v(e,t){const n="string"==typeof t.host?t.host:"localhost";return-1!==n.indexOf("/")?{path:n}:{family:e,host:n,port:"number"==typeof t.port?t.port:27017,rejectUnauthorized:!1}}const S=new Set(["error","close","timeout","parseError"]);e.exports=function(e,t,n){"function"==typeof t&&(n=t,t=void 0);const f=e&&e.connectionType?e.connectionType:i;null==y&&(y=u(e.bson)),function(e,t,n,i){const s="boolean"==typeof t.ssl&&t.ssl,u="boolean"!=typeof t.keepAlive||t.keepAlive;let l="number"==typeof t.keepAliveInitialDelay?t.keepAliveInitialDelay:12e4;const f="boolean"!=typeof t.noDelay||t.noDelay,p="number"==typeof t.connectionTimeout?t.connectionTimeout:"number"==typeof t.connectTimeoutMS?t.connectTimeoutMS:3e4,d="number"==typeof t.socketTimeout?t.socketTimeout:0,h="boolean"!=typeof t.rejectUnauthorized||t.rejectUnauthorized;l>d&&(l=Math.round(d/2));let m;const g=function(e,t){e&&m&&m.destroy(),i(e,t)};try{s?(m=o.connect(function(e,t){const n=v(e,t);for(const e in t)null!=t[e]&&-1!==b.indexOf(e)&&(n[e]=t[e]);!1===t.checkServerIdentity?n.checkServerIdentity=function(){}:"function"==typeof t.checkServerIdentity&&(n.checkServerIdentity=t.checkServerIdentity);null!=n.servername||r.isIP(n.host)||(n.servername=n.host);return n}(e,t)),"function"==typeof m.disableRenegotiation&&m.disableRenegotiation()):m=r.createConnection(v(e,t))}catch(e){return g(e)}m.setKeepAlive(u,l),m.setTimeout(p),m.setNoDelay(f);const y=s?"secureConnect":"connect";let w;function _(e){return t=>{S.forEach(e=>m.removeAllListeners(e)),w&&n.removeListener("cancel",w),m.removeListener(y,O),g(function(e,t){switch(e){case"error":return new a(t);case"timeout":return new c("connection timed out");case"close":return new a("connection closed");case"cancel":return new a("connection establishment was cancelled");default:return new a("unknown network error")}}(e,t))}}function O(){if(S.forEach(e=>m.removeAllListeners(e)),w&&n.removeListener("cancel",w),m.authorizationError&&h)return g(m.authorizationError);m.setTimeout(d),g(null,m)}S.forEach(e=>m.once(e,_(e))),n&&(w=_("cancel"),n.once("cancel",w));m.once(y,O)}(void 0!==e.family?e.family:0,e,t,(t,r)=>{t?n(t,r):function(e,t,n){const r=function(t,r){t&&e&&e.destroy(),n(t,r)},o=t.credentials;if(o&&!o.mechanism.match(/DEFAULT/i)&&!y[o.mechanism])return void r(new s(`authMechanism '${o.mechanism}' not supported`));const a=new l(e,o,t);!function(e,t){const n=e.options,r=n.compression&&n.compression.compressors?n.compression.compressors:[],o={ismaster:!0,client:n.metadata||p(n),compression:r},i=e.credentials;if(i){if(i.mechanism.match(/DEFAULT/i)&&i.username)return Object.assign(o,{saslSupportedMechs:`${i.source}.${i.username}`}),void y["scram-sha-256"].prepare(o,e,t);return void y[i.mechanism].prepare(o,e,t)}t(void 0,o)}(a,(n,c)=>{if(n)return r(n);const u=Object.assign({},t);(t.connectTimeoutMS||t.connectionTimeout)&&(u.socketTimeout=t.connectTimeoutMS||t.connectionTimeout);const l=(new Date).getTime();e.command("admin.$cmd",c,u,(n,u)=>{if(n)return void r(n);const f=u.result;if(0===f.ok)return void r(new s(f));const p=function(e,t){const n=e&&"number"==typeof e.maxWireVersion&&e.maxWireVersion>=m,r=e&&"number"==typeof e.minWireVersion&&e.minWireVersion<=d;if(n){if(r)return null;const n=`Server at ${t.host}:${t.port} reports minimum wire version ${e.minWireVersion}, but this version of the Node.js Driver requires at most ${d} (MongoDB ${h})`;return new s(n)}const o=`Server at ${t.host}:${t.port} reports maximum wire version ${e.maxWireVersion||0}, but this version of the Node.js Driver requires at least ${m} (MongoDB ${g})`;return new s(o)}(f,t);if(p)r(p);else{if(!function(e){return!(e instanceof i)}(e)&&f.compression){const n=c.compression.filter(e=>-1!==f.compression.indexOf(e));n.length&&(e.agreedCompressor=n[0]),t.compression&&t.compression.zlibCompressionLevel&&(e.zlibCompressionLevel=t.compression.zlibCompressionLevel)}if(e.ismaster=f,e.lastIsMasterMS=(new Date).getTime()-l,f.arbiterOnly||!o)r(void 0,e);else{Object.assign(a,{response:f});const t=o.resolveAuthMechanism(f);y[t.mechanism].auth(a,t=>{if(t)return r(t);r(void 0,e)})}}})})}(new f(r,e),e,n)})}},function(e,t){e.exports=require("path")},function(e,t){e.exports=require("querystring")},function(e,t,n){"use strict";function r(e,t){t=t||{};this._head=0,this._tail=0,this._capacity=t.capacity,this._capacityMask=3,this._list=new Array(4),Array.isArray(e)&&this._fromArray(e)}r.prototype.peekAt=function(e){var t=e;if(t===(0|t)){var n=this.size();if(!(t>=n||t<-n))return t<0&&(t+=n),t=this._head+t&this._capacityMask,this._list[t]}},r.prototype.get=function(e){return this.peekAt(e)},r.prototype.peek=function(){if(this._head!==this._tail)return this._list[this._head]},r.prototype.peekFront=function(){return this.peek()},r.prototype.peekBack=function(){return this.peekAt(-1)},Object.defineProperty(r.prototype,"length",{get:function(){return this.size()}}),r.prototype.size=function(){return this._head===this._tail?0:this._head<this._tail?this._tail-this._head:this._capacityMask+1-(this._head-this._tail)},r.prototype.unshift=function(e){if(void 0===e)return this.size();var t=this._list.length;return this._head=this._head-1+t&this._capacityMask,this._list[this._head]=e,this._tail===this._head&&this._growArray(),this._capacity&&this.size()>this._capacity&&this.pop(),this._head<this._tail?this._tail-this._head:this._capacityMask+1-(this._head-this._tail)},r.prototype.shift=function(){var e=this._head;if(e!==this._tail){var t=this._list[e];return this._list[e]=void 0,this._head=e+1&this._capacityMask,e<2&&this._tail>1e4&&this._tail<=this._list.length>>>2&&this._shrinkArray(),t}},r.prototype.push=function(e){if(void 0===e)return this.size();var t=this._tail;return this._list[t]=e,this._tail=t+1&this._capacityMask,this._tail===this._head&&this._growArray(),this._capacity&&this.size()>this._capacity&&this.shift(),this._head<this._tail?this._tail-this._head:this._capacityMask+1-(this._head-this._tail)},r.prototype.pop=function(){var e=this._tail;if(e!==this._head){var t=this._list.length;this._tail=e-1+t&this._capacityMask;var n=this._list[this._tail];return this._list[this._tail]=void 0,this._head<2&&e>1e4&&e<=t>>>2&&this._shrinkArray(),n}},r.prototype.removeOne=function(e){var t=e;if(t===(0|t)&&this._head!==this._tail){var n=this.size(),r=this._list.length;if(!(t>=n||t<-n)){t<0&&(t+=n),t=this._head+t&this._capacityMask;var o,i=this._list[t];if(e<n/2){for(o=e;o>0;o--)this._list[t]=this._list[t=t-1+r&this._capacityMask];this._list[t]=void 0,this._head=this._head+1+r&this._capacityMask}else{for(o=n-1-e;o>0;o--)this._list[t]=this._list[t=t+1+r&this._capacityMask];this._list[t]=void 0,this._tail=this._tail-1+r&this._capacityMask}return i}}},r.prototype.remove=function(e,t){var n,r=e,o=t;if(r===(0|r)&&this._head!==this._tail){var i=this.size(),s=this._list.length;if(!(r>=i||r<-i||t<1)){if(r<0&&(r+=i),1===t||!t)return(n=new Array(1))[0]=this.removeOne(r),n;if(0===r&&r+t>=i)return n=this.toArray(),this.clear(),n;var a;for(r+t>i&&(t=i-r),n=new Array(t),a=0;a<t;a++)n[a]=this._list[this._head+r+a&this._capacityMask];if(r=this._head+r&this._capacityMask,e+t===i){for(this._tail=this._tail-t+s&this._capacityMask,a=t;a>0;a--)this._list[r=r+1+s&this._capacityMask]=void 0;return n}if(0===e){for(this._head=this._head+t+s&this._capacityMask,a=t-1;a>0;a--)this._list[r=r+1+s&this._capacityMask]=void 0;return n}if(r<i/2){for(this._head=this._head+e+t+s&this._capacityMask,a=e;a>0;a--)this.unshift(this._list[r=r-1+s&this._capacityMask]);for(r=this._head-1+s&this._capacityMask;o>0;)this._list[r=r-1+s&this._capacityMask]=void 0,o--;e<0&&(this._tail=r)}else{for(this._tail=r,r=r+t+s&this._capacityMask,a=i-(t+e);a>0;a--)this.push(this._list[r++]);for(r=this._tail;o>0;)this._list[r=r+1+s&this._capacityMask]=void 0,o--}return this._head<2&&this._tail>1e4&&this._tail<=s>>>2&&this._shrinkArray(),n}}},r.prototype.splice=function(e,t){var n=e;if(n===(0|n)){var r=this.size();if(n<0&&(n+=r),!(n>r)){if(arguments.length>2){var o,i,s,a=arguments.length,c=this._list.length,u=2;if(!r||n<r/2){for(i=new Array(n),o=0;o<n;o++)i[o]=this._list[this._head+o&this._capacityMask];for(0===t?(s=[],n>0&&(this._head=this._head+n+c&this._capacityMask)):(s=this.remove(n,t),this._head=this._head+n+c&this._capacityMask);a>u;)this.unshift(arguments[--a]);for(o=n;o>0;o--)this.unshift(i[o-1])}else{var l=(i=new Array(r-(n+t))).length;for(o=0;o<l;o++)i[o]=this._list[this._head+n+t+o&this._capacityMask];for(0===t?(s=[],n!=r&&(this._tail=this._head+n+c&this._capacityMask)):(s=this.remove(n,t),this._tail=this._tail-l+c&this._capacityMask);u<a;)this.push(arguments[u++]);for(o=0;o<l;o++)this.push(i[o])}return s}return this.remove(n,t)}}},r.prototype.clear=function(){this._head=0,this._tail=0},r.prototype.isEmpty=function(){return this._head===this._tail},r.prototype.toArray=function(){return this._copyArray(!1)},r.prototype._fromArray=function(e){for(var t=0;t<e.length;t++)this.push(e[t])},r.prototype._copyArray=function(e){var t,n=[],r=this._list,o=r.length;if(e||this._head>this._tail){for(t=this._head;t<o;t++)n.push(r[t]);for(t=0;t<this._tail;t++)n.push(r[t])}else for(t=this._head;t<this._tail;t++)n.push(r[t]);return n},r.prototype._growArray=function(){this._head&&(this._list=this._copyArray(!0),this._head=0),this._tail=this._list.length,this._list.length*=2,this._capacityMask=this._capacityMask<<1|1},r.prototype._shrinkArray=function(){this._list.length>>>=1,this._capacityMask>>>=1},e.exports=r},function(e,t,n){"use strict";const r=n(138),o=n(8),i=n(95).isResumableError,s=n(2).MongoError,a=n(26),c=n(4).relayEvents,u=n(4).maxWireVersion,l=n(0).maybePromise,f=n(0).now,p=n(0).calculateDurationInMs,d=n(96),h=Symbol("resumeQueue"),m=["resumeAfter","startAfter","startAtOperationTime","fullDocument"],g=["batchSize","maxAwaitTimeMS","collation","readPreference"].concat(m),y={COLLECTION:Symbol("Collection"),DATABASE:Symbol("Database"),CLUSTER:Symbol("Cluster")};class b extends a{constructor(e,t,n){super(e,t,n),n=n||{},this._resumeToken=null,this.startAtOperationTime=n.startAtOperationTime,n.startAfter?this.resumeToken=n.startAfter:n.resumeAfter&&(this.resumeToken=n.resumeAfter)}set resumeToken(e){this._resumeToken=e,this.emit("resumeTokenChanged",e)}get resumeToken(){return this._resumeToken}get resumeOptions(){const e={};for(const t of g)this.options[t]&&(e[t]=this.options[t]);if(this.resumeToken||this.startAtOperationTime)if(["resumeAfter","startAfter","startAtOperationTime"].forEach(t=>delete e[t]),this.resumeToken){const t=this.options.startAfter&&!this.hasReceived?"startAfter":"resumeAfter";e[t]=this.resumeToken}else this.startAtOperationTime&&u(this.server)>=7&&(e.startAtOperationTime=this.startAtOperationTime);return e}cacheResumeToken(e){0===this.bufferedCount()&&this.cursorState.postBatchResumeToken?this.resumeToken=this.cursorState.postBatchResumeToken:this.resumeToken=e,this.hasReceived=!0}_processBatch(e,t){const n=t.cursor;n.postBatchResumeToken&&(this.cursorState.postBatchResumeToken=n.postBatchResumeToken,0===n[e].length&&(this.resumeToken=n.postBatchResumeToken))}_initializeCursor(e){super._initializeCursor((t,n)=>{if(t||null==n)return void e(t,n);const r=n.documents[0];null==this.startAtOperationTime&&null==this.resumeAfter&&null==this.startAfter&&u(this.server)>=7&&(this.startAtOperationTime=r.operationTime),this._processBatch("firstBatch",r),this.emit("init",n),this.emit("response"),e(t,n)})}_getMore(e){super._getMore((t,n)=>{t?e(t):(this._processBatch("nextBatch",n),this.emit("more",n),this.emit("response"),e(t,n))})}}function v(e,t){const n={fullDocument:t.fullDocument||"default"};S(n,t,m),e.type===y.CLUSTER&&(n.allChangesForCluster=!0);const r=[{$changeStream:n}].concat(e.pipeline),o=S({},t,g),i=new b(e.topology,new d(e.parent,r,t),o);if(c(i,e,["resumeTokenChanged","end","close"]),e.listenerCount("change")>0&&i.on("data",(function(t){w(e,t)})),i.on("error",(function(t){_(e,t)})),e.pipeDestinations){const t=i.stream(e.streamOptions);for(let n of e.pipeDestinations)t.pipe(n)}return i}function S(e,t,n){return n.forEach(n=>{t[n]&&(e[n]=t[n])}),e}function w(e,t,n){const r=e.cursor;if(null==t&&(e.closed=!0),!e.closed){if(t&&!t._id){const t=new Error("A change stream document has been received that lacks a resume token (_id).");return n?n(t):e.emit("error",t)}return r.cacheResumeToken(t._id),e.options.startAtOperationTime=void 0,n?n(void 0,t):e.emit("change",t)}n&&n(new s("ChangeStream is closed"))}function _(e,t,n){const r=e.topology,o=e.cursor;if(!e.closed)return o&&i(t,u(o.server))?(e.cursor=void 0,["data","close","end","error"].forEach(e=>o.removeAllListeners(e)),o.close(),void function e(t,n,r){setTimeout(()=>{n&&null==n.start&&(n.start=f());const o=n.start||f(),i=n.timeout||3e4,a=n.readPreference;return t.isConnected({readPreference:a})?r():p(o)>i?r(new s("Timed out waiting for connection")):void e(t,n,r)},500)}(r,{readPreference:o.options.readPreference},t=>{if(t)return c(t);const r=v(e,o.resumeOptions);if(!n)return a(r);r.hasNext(e=>{if(e)return c(e);a(r)})})):n?n(t):e.emit("error",t);function a(t){e.cursor=t,T(e)}function c(t){n||(e.emit("error",t),e.emit("close")),T(e,t),e.closed=!0}n&&n(new s("ChangeStream is closed"))}function O(e,t){e.isClosed()?t(new s("ChangeStream is closed.")):e.cursor?t(void 0,e.cursor):e[h].push(t)}function T(e,t){for(;e[h].length;){const n=e[h].pop();if(e.isClosed()&&!t)return void n(new s("Change Stream is not open."));n(t,e.cursor)}}e.exports=class extends o{constructor(e,t,o){super();const i=n(61),s=n(98),a=n(59);if(this.pipeline=t||[],this.options=o||{},this.parent=e,this.namespace=e.s.namespace,e instanceof i)this.type=y.COLLECTION,this.topology=e.s.db.serverConfig;else if(e instanceof s)this.type=y.DATABASE,this.topology=e.serverConfig;else{if(!(e instanceof a))throw new TypeError("parent provided to ChangeStream constructor is not an instance of Collection, Db, or MongoClient");this.type=y.CLUSTER,this.topology=e.topology}this.promiseLibrary=e.s.promiseLibrary,!this.options.readPreference&&e.s.readPreference&&(this.options.readPreference=e.s.readPreference),this[h]=new r,this.cursor=v(this,o),this.closed=!1,this.on("newListener",e=>{"change"===e&&this.cursor&&0===this.listenerCount("change")&&this.cursor.on("data",e=>w(this,e))}),this.on("removeListener",e=>{"change"===e&&0===this.listenerCount("change")&&this.cursor&&this.cursor.removeAllListeners("data")})}get resumeToken(){return this.cursor.resumeToken}hasNext(e){return l(this.parent,e,e=>{O(this,(t,n)=>{if(t)return e(t);n.hasNext(e)})})}next(e){return l(this.parent,e,e=>{O(this,(t,n)=>{if(t)return e(t);n.next((t,n)=>{if(t)return this[h].push(()=>this.next(e)),void _(this,t,e);w(this,n,e)})})})}isClosed(){return this.closed||this.cursor&&this.cursor.isClosed()}close(e){return l(this.parent,e,e=>{if(this.closed)return e();if(this.closed=!0,!this.cursor)return e();const t=this.cursor;return t.close(n=>(["data","close","end","error"].forEach(e=>t.removeAllListeners(e)),this.cursor=void 0,e(n)))})}pipe(e,t){return this.pipeDestinations||(this.pipeDestinations=[]),this.pipeDestinations.push(e),this.cursor.pipe(e,t)}unpipe(e){return this.pipeDestinations&&this.pipeDestinations.indexOf(e)>-1&&this.pipeDestinations.splice(this.pipeDestinations.indexOf(e),1),this.cursor.unpipe(e)}stream(e){return this.streamOptions=e,this.cursor.stream(e)}pause(){return this.cursor.pause()}resume(){return this.cursor.resume()}}},function(e,t,n){"use strict";e.exports={SYSTEM_NAMESPACE_COLLECTION:"system.namespaces",SYSTEM_INDEX_COLLECTION:"system.indexes",SYSTEM_PROFILE_COLLECTION:"system.profile",SYSTEM_USER_COLLECTION:"system.users",SYSTEM_COMMAND_COLLECTION:"$cmd",SYSTEM_JS_COLLECTION:"system.js"}},function(e,t,n){"use strict";const r=n(2).BSON.Long,o=n(2).MongoError,i=n(2).BSON.ObjectID,s=n(2).BSON,a=n(2).MongoWriteConcernError,c=n(0).toError,u=n(0).handleCallback,l=n(0).applyRetryableWrites,f=n(0).applyWriteConcern,p=n(0).executeLegacyOperation,d=n(0).isPromiseLike,h=n(0).hasAtomicOperators,m=n(4).maxWireVersion,g=new s([s.Binary,s.Code,s.DBRef,s.Decimal128,s.Double,s.Int32,s.Long,s.Map,s.MaxKey,s.MinKey,s.ObjectId,s.BSONRegExp,s.Symbol,s.Timestamp]);class y{constructor(e){this.result=e}get ok(){return this.result.ok}get nInserted(){return this.result.nInserted}get nUpserted(){return this.result.nUpserted}get nMatched(){return this.result.nMatched}get nModified(){return this.result.nModified}get nRemoved(){return this.result.nRemoved}getInsertedIds(){return this.result.insertedIds}getUpsertedIds(){return this.result.upserted}getUpsertedIdAt(e){return this.result.upserted[e]}getRawResponse(){return this.result}hasWriteErrors(){return this.result.writeErrors.length>0}getWriteErrorCount(){return this.result.writeErrors.length}getWriteErrorAt(e){return e<this.result.writeErrors.length?this.result.writeErrors[e]:null}getWriteErrors(){return this.result.writeErrors}getLastOp(){return this.result.lastOp}getWriteConcernError(){if(0===this.result.writeConcernErrors.length)return null;if(1===this.result.writeConcernErrors.length)return this.result.writeConcernErrors[0];{let e="";for(let t=0;t<this.result.writeConcernErrors.length;t++){e+=this.result.writeConcernErrors[t].errmsg,0===t&&(e+=" and ")}return new b({errmsg:e,code:64})}}toJSON(){return this.result}toString(){return`BulkWriteResult(${this.toJSON(this.result)})`}isOk(){return 1===this.result.ok}}class b{constructor(e){this.err=e}get code(){return this.err.code}get errmsg(){return this.err.errmsg}toJSON(){return{code:this.err.code,errmsg:this.err.errmsg}}toString(){return`WriteConcernError(${this.err.errmsg})`}}class v{constructor(e){this.err=e}get code(){return this.err.code}get index(){return this.err.index}get errmsg(){return this.err.errmsg}getOperation(){return this.err.op}toJSON(){return{code:this.err.code,index:this.err.index,errmsg:this.err.errmsg,op:this.err.op}}toString(){return`WriteError(${JSON.stringify(this.toJSON())})`}}function S(e,t,n,o){if(n)o=n;else if(o&&o.result)o=o.result;else if(null==o)return;if(0===o.ok&&1===t.ok){t.ok=0;const n={index:0,code:o.code||0,errmsg:o.message,op:e.operations[0]};return void t.writeErrors.push(new v(n))}if(0===o.ok&&0===t.ok)return;if(o.opTime||o.lastOp){const e=o.lastOp||o.opTime;let n=null,i=null;if(e&&"Timestamp"===e._bsontype)null==t.lastOp?t.lastOp=e:e.greaterThan(t.lastOp)&&(t.lastOp=e);else{t.lastOp&&(n="number"==typeof t.lastOp.ts?r.fromNumber(t.lastOp.ts):t.lastOp.ts,i="number"==typeof t.lastOp.t?r.fromNumber(t.lastOp.t):t.lastOp.t);const o="number"==typeof e.ts?r.fromNumber(e.ts):e.ts,s="number"==typeof e.t?r.fromNumber(e.t):e.t;null==t.lastOp?t.lastOp=e:o.greaterThan(n)?t.lastOp=e:o.equals(n)&&s.greaterThan(i)&&(t.lastOp=e)}}1===e.batchType&&o.n&&(t.nInserted=t.nInserted+o.n),3===e.batchType&&o.n&&(t.nRemoved=t.nRemoved+o.n);let i=0;if(Array.isArray(o.upserted)){i=o.upserted.length;for(let n=0;n<o.upserted.length;n++)t.upserted.push({index:o.upserted[n].index+e.originalZeroIndex,_id:o.upserted[n]._id})}else o.upserted&&(i=1,t.upserted.push({index:e.originalZeroIndex,_id:o.upserted}));if(2===e.batchType&&o.n){const e=o.nModified;t.nUpserted=t.nUpserted+i,t.nMatched=t.nMatched+(o.n-i),t.nModified="number"==typeof e?t.nModified+e:null}if(Array.isArray(o.writeErrors))for(let n=0;n<o.writeErrors.length;n++){const r={index:e.originalIndexes[o.writeErrors[n].index],code:o.writeErrors[n].code,errmsg:o.writeErrors[n].errmsg,op:e.operations[o.writeErrors[n].index]};t.writeErrors.push(new v(r))}o.writeConcernError&&t.writeConcernErrors.push(new b(o.writeConcernError))}function w(e,t,n){if(0===e.s.batches.length)return u(n,null,new y(e.s.bulkResult));const r=e.s.batches.shift();e.finalOptionsHandler({options:t,batch:r,resultHandler:function(o,i){if((o&&o.driver||o&&o.message)&&!(o instanceof a))return u(n,o);if(o&&(o.ok=0),o instanceof a)return function(e,t,n,r){S(e,t,null,n.result);const o=new b({errmsg:n.result.writeConcernError.errmsg,code:n.result.writeConcernError.result});return u(r,new _(c(o),new y(t)),null)}(r,e.s.bulkResult,o,n);const s=new y(e.s.bulkResult);if(null!=S(r,e.s.bulkResult,o,i))return u(n,null,s);e.handleWriteError(n,s)||w(e,t,n)}},n)}class _ extends o{constructor(e,t){super(e.err||e.errmsg||e.errMessage||e),Object.assign(this,e),this.name="BulkWriteError",this.result=t}}class O{constructor(e){this.s=e.s}update(e){const t="boolean"==typeof this.s.currentOp.upsert&&this.s.currentOp.upsert,n={q:this.s.currentOp.selector,u:e,multi:!0,upsert:t};return e.hint&&(n.hint=e.hint),this.s.currentOp=null,this.s.options.addToOperationsList(this,2,n)}updateOne(e){const t="boolean"==typeof this.s.currentOp.upsert&&this.s.currentOp.upsert,n={q:this.s.currentOp.selector,u:e,multi:!1,upsert:t};if(e.hint&&(n.hint=e.hint),!h(e))throw new TypeError("Update document requires atomic operators");return this.s.currentOp=null,this.s.options.addToOperationsList(this,2,n)}replaceOne(e){const t="boolean"==typeof this.s.currentOp.upsert&&this.s.currentOp.upsert,n={q:this.s.currentOp.selector,u:e,multi:!1,upsert:t};if(e.hint&&(n.hint=e.hint),h(e))throw new TypeError("Replacement document must not use atomic operators");return this.s.currentOp=null,this.s.options.addToOperationsList(this,2,n)}upsert(){return this.s.currentOp.upsert=!0,this}deleteOne(){const e={q:this.s.currentOp.selector,limit:1};return this.s.currentOp=null,this.s.options.addToOperationsList(this,3,e)}delete(){const e={q:this.s.currentOp.selector,limit:0};return this.s.currentOp=null,this.s.options.addToOperationsList(this,3,e)}removeOne(){return this.deleteOne()}remove(){return this.delete()}}class T{constructor(e,t,n,r){this.isOrdered=r,n=null==n?{}:n;const o=t.s.namespace,i=e.bson,s=e.lastIsMaster(),a=!(!e.s.options||!e.s.options.autoEncrypter),c=s&&s.maxBsonObjectSize?s.maxBsonObjectSize:16777216,u=a?2097152:c,p=s&&s.maxWriteBatchSize?s.maxWriteBatchSize:1e3,d=(p-1).toString(10).length+2;let h=Object.assign({},n);h=l(h,t.s.db),h=f(h,{collection:t},n);const m=h.writeConcern,g=n.promiseLibrary||Promise;this.s={bulkResult:{ok:1,writeErrors:[],writeConcernErrors:[],insertedIds:[],nInserted:0,nUpserted:0,nMatched:0,nModified:0,nRemoved:0,upserted:[]},currentBatch:null,currentIndex:0,currentBatchSize:0,currentBatchSizeBytes:0,currentInsertBatch:null,currentUpdateBatch:null,currentRemoveBatch:null,batches:[],writeConcern:m,maxBsonObjectSize:c,maxBatchSizeBytes:u,maxWriteBatchSize:p,maxKeySize:d,namespace:o,bson:i,topology:e,options:h,currentOp:null,executed:!1,collection:t,promiseLibrary:g,err:null,checkKeys:"boolean"!=typeof n.checkKeys||n.checkKeys},!0===n.bypassDocumentValidation&&(this.s.bypassDocumentValidation=!0)}insert(e){return!0!==this.s.collection.s.db.options.forceServerObjectId&&null==e._id&&(e._id=new i),this.s.options.addToOperationsList(this,1,e)}find(e){if(!e)throw c("Bulk find operation must specify a selector");return this.s.currentOp={selector:e},new O(this)}raw(e){const t=Object.keys(e)[0],n="boolean"==typeof this.s.options.forceServerObjectId?this.s.options.forceServerObjectId:this.s.collection.s.db.options.forceServerObjectId;if(e.updateOne&&e.updateOne.q||e.updateMany&&e.updateMany.q||e.replaceOne&&e.replaceOne.q)return e[t].multi=!e.updateOne&&!e.replaceOne,this.s.options.addToOperationsList(this,2,e[t]);if(e.updateOne||e.updateMany||e.replaceOne){if(e.replaceOne&&h(e[t].replacement))throw new TypeError("Replacement document must not use atomic operators");if((e.updateOne||e.updateMany)&&!h(e[t].update))throw new TypeError("Update document requires atomic operators");const n=!e.updateOne&&!e.replaceOne,r={q:e[t].filter,u:e[t].update||e[t].replacement,multi:n};if(e[t].hint&&(r.hint=e[t].hint),this.isOrdered?(r.upsert=!!e[t].upsert,e.collation&&(r.collation=e.collation)):e[t].upsert&&(r.upsert=!0),e[t].arrayFilters){if(m(this.s.topology)<6)throw new TypeError("arrayFilters are only supported on MongoDB 3.6+");r.arrayFilters=e[t].arrayFilters}return this.s.options.addToOperationsList(this,2,r)}if(e.removeOne||e.removeMany||e.deleteOne&&e.deleteOne.q||e.deleteMany&&e.deleteMany.q)return e[t].limit=e.removeOne?1:0,this.s.options.addToOperationsList(this,3,e[t]);if(e.deleteOne||e.deleteMany){const n=e.deleteOne?1:0,r={q:e[t].filter,limit:n};return e[t].hint&&(r.hint=e[t].hint),this.isOrdered&&e.collation&&(r.collation=e.collation),this.s.options.addToOperationsList(this,3,r)}if(e.insertOne&&null==e.insertOne.document)return!0!==n&&null==e.insertOne._id&&(e.insertOne._id=new i),this.s.options.addToOperationsList(this,1,e.insertOne);if(e.insertOne&&e.insertOne.document)return!0!==n&&null==e.insertOne.document._id&&(e.insertOne.document._id=new i),this.s.options.addToOperationsList(this,1,e.insertOne.document);if(!e.insertMany)throw c("bulkWrite only supports insertOne, insertMany, updateOne, updateMany, removeOne, removeMany, deleteOne, deleteMany");for(let t=0;t<e.insertMany.length;t++)!0!==n&&null==e.insertMany[t]._id&&(e.insertMany[t]._id=new i),this.s.options.addToOperationsList(this,1,e.insertMany[t])}_handleEarlyError(e,t){if("function"!=typeof t)return this.s.promiseLibrary.reject(e);t(e,null)}bulkExecute(e,t,n){if("function"==typeof t&&(n=t,t={}),t=t||{},"function"==typeof e?n=e:e&&"object"==typeof e&&(this.s.writeConcern=e),this.s.executed){const e=c("batch cannot be re-executed");return this._handleEarlyError(e,n)}if(this.isOrdered?this.s.currentBatch&&this.s.batches.push(this.s.currentBatch):(this.s.currentInsertBatch&&this.s.batches.push(this.s.currentInsertBatch),this.s.currentUpdateBatch&&this.s.batches.push(this.s.currentUpdateBatch),this.s.currentRemoveBatch&&this.s.batches.push(this.s.currentRemoveBatch)),0===this.s.batches.length){const e=c("Invalid Operation, no operations specified");return this._handleEarlyError(e,n)}return{options:t,callback:n}}execute(e,t,n){const r=this.bulkExecute(e,t,n);return!r||d(r)?r:(t=r.options,n=r.callback,p(this.s.topology,w,[this,t,n]))}finalOptionsHandler(e,t){const n=Object.assign({ordered:this.isOrdered},e.options);null!=this.s.writeConcern&&(n.writeConcern=this.s.writeConcern),!0!==n.bypassDocumentValidation&&delete n.bypassDocumentValidation,this.operationId&&(e.resultHandler.operationId=this.operationId),this.s.options.serializeFunctions&&(n.serializeFunctions=!0),this.s.options.ignoreUndefined&&(n.ignoreUndefined=!0),!0===this.s.bypassDocumentValidation&&(n.bypassDocumentValidation=!0),!1===this.s.checkKeys&&(n.checkKeys=!1),n.retryWrites&&(2===e.batch.batchType&&(n.retryWrites=n.retryWrites&&!e.batch.operations.some(e=>e.multi)),3===e.batch.batchType&&(n.retryWrites=n.retryWrites&&!e.batch.operations.some(e=>0===e.limit)));try{1===e.batch.batchType?this.s.topology.insert(this.s.namespace,e.batch.operations,n,e.resultHandler):2===e.batch.batchType?this.s.topology.update(this.s.namespace,e.batch.operations,n,e.resultHandler):3===e.batch.batchType&&this.s.topology.remove(this.s.namespace,e.batch.operations,n,e.resultHandler)}catch(n){n.ok=0,u(t,null,S(e.batch,this.s.bulkResult,n,null))}}handleWriteError(e,t){if(this.s.bulkResult.writeErrors.length>0){const n=this.s.bulkResult.writeErrors[0].errmsg?this.s.bulkResult.writeErrors[0].errmsg:"write operation failed";return u(e,new _(c({message:n,code:this.s.bulkResult.writeErrors[0].code,writeErrors:this.s.bulkResult.writeErrors}),t),null),!0}if(t.getWriteConcernError())return u(e,new _(c(t.getWriteConcernError()),t),null),!0}}Object.defineProperty(T.prototype,"length",{enumerable:!0,get:function(){return this.s.currentIndex}}),e.exports={Batch:class{constructor(e,t){this.originalZeroIndex=t,this.currentIndex=0,this.originalIndexes=[],this.batchType=e,this.operations=[],this.size=0,this.sizeBytes=0}},BulkOperationBase:T,bson:g,INSERT:1,UPDATE:2,REMOVE:3,BulkWriteError:_}},function(e,t,n){"use strict";const r=n(2).MongoError,o=n(26),i=n(17).CursorState;class s extends o{constructor(e,t,n){super(e,t,n)}batchSize(e){if(this.s.state===i.CLOSED||this.isDead())throw r.create({message:"Cursor is closed",driver:!0});if("number"!=typeof e)throw r.create({message:"batchSize requires an integer",driver:!0});return this.operation.options.batchSize=e,this.setCursorBatchSize(e),this}geoNear(e){return this.operation.addToPipeline({$geoNear:e}),this}group(e){return this.operation.addToPipeline({$group:e}),this}limit(e){return this.operation.addToPipeline({$limit:e}),this}match(e){return this.operation.addToPipeline({$match:e}),this}maxTimeMS(e){return this.operation.options.maxTimeMS=e,this}out(e){return this.operation.addToPipeline({$out:e}),this}project(e){return this.operation.addToPipeline({$project:e}),this}lookup(e){return this.operation.addToPipeline({$lookup:e}),this}redact(e){return this.operation.addToPipeline({$redact:e}),this}skip(e){return this.operation.addToPipeline({$skip:e}),this}sort(e){return this.operation.addToPipeline({$sort:e}),this}unwind(e){return this.operation.addToPipeline({$unwind:e}),this}getLogger(){return this.logger}}s.prototype.get=s.prototype.toArray,e.exports=s},function(e,t,n){"use strict";const r=n(2).ReadPreference,o=n(2).MongoError,i=n(26),s=n(17).CursorState;class a extends i{constructor(e,t,n,r){super(e,t,n,r)}setReadPreference(e){if(this.s.state===s.CLOSED||this.isDead())throw o.create({message:"Cursor is closed",driver:!0});if(this.s.state!==s.INIT)throw o.create({message:"cannot change cursor readPreference after cursor has been accessed",driver:!0});if(e instanceof r)this.options.readPreference=e;else{if("string"!=typeof e)throw new TypeError("Invalid read preference: "+e);this.options.readPreference=new r(e)}return this}batchSize(e){if(this.s.state===s.CLOSED||this.isDead())throw o.create({message:"Cursor is closed",driver:!0});if("number"!=typeof e)throw o.create({message:"batchSize requires an integer",driver:!0});return this.cmd.cursor&&(this.cmd.cursor.batchSize=e),this.setCursorBatchSize(e),this}maxTimeMS(e){return this.topology.lastIsMaster().minWireVersion>2&&(this.cmd.maxTimeMS=e),this}getLogger(){return this.logger}}a.prototype.get=a.prototype.toArray,e.exports=a},function(e,t,n){"use strict";const r=n(1).Aspect,o=n(23),i=n(1).defineAspects,s=n(0).handleCallback;class a extends o{constructor(e,t){const n=Object.assign({},t,e.s.options);t.session&&(n.session=t.session),super(e,n)}execute(e){super.execute((t,n)=>t?s(e,t):n.ok?s(e,null,!0):void s(e,null,!1))}}i(a,r.WRITE_OPERATION);e.exports={DropOperation:a,DropCollectionOperation:class extends a{constructor(e,t,n){super(e,n),this.name=t,this.namespace=`${e.namespace}.${t}`}_buildCommand(){return{drop:this.name}}},DropDatabaseOperation:class extends a{_buildCommand(){return{dropDatabase:1}}}}},function(e,t,n){"use strict";let r,o,i;e.exports={loadCollection:function(){return r||(r=n(61)),r},loadCursor:function(){return o||(o=n(26)),o},loadDb:function(){return i||(i=n(98)),i}}},function(e,t,n){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.transformRowUsingColumnMap=t.prepareTableForImport=void 0;const o=r(n(102)),i=r(n(296)),s=r(n(162));t.prepareTableForImport=function(e){const t=(0,o.default)(e);return t.foreignKeys=[],t.indexes=[],t.uniques=[],t.checks=[],t.primaryKey&&(t.primaryKey.constraintName=null),t},t.transformRowUsingColumnMap=function(e,t){return(0,i.default)(t.map(t=>[t.dst,(0,s.default)(e,t.src)]))}},function(e,t,n){var r=n(103),o=n(265),i=n(106),s=n(266),a=n(273),c=n(276),u=n(277),l=n(278),f=n(280),p=n(157),d=n(159),h=n(70),m=n(284),g=n(285),y=n(290),b=n(12),v=n(109),S=n(292),w=n(28),_=n(294),O=n(49),T=n(112),C={};C["[object Arguments]"]=C["[object Array]"]=C["[object ArrayBuffer]"]=C["[object DataView]"]=C["[object Boolean]"]=C["[object Date]"]=C["[object Float32Array]"]=C["[object Float64Array]"]=C["[object Int8Array]"]=C["[object Int16Array]"]=C["[object Int32Array]"]=C["[object Map]"]=C["[object Number]"]=C["[object Object]"]=C["[object RegExp]"]=C["[object Set]"]=C["[object String]"]=C["[object Symbol]"]=C["[object Uint8Array]"]=C["[object Uint8ClampedArray]"]=C["[object Uint16Array]"]=C["[object Uint32Array]"]=!0,C["[object Error]"]=C["[object Function]"]=C["[object WeakMap]"]=!1,e.exports=function e(t,n,x,E,N,I){var A,k=1&n,M=2&n,R=4&n;if(x&&(A=N?x(t,E,N,I):x(t)),void 0!==A)return A;if(!w(t))return t;var j=b(t);if(j){if(A=m(t),!k)return u(t,A)}else{var D=h(t),P="[object Function]"==D||"[object GeneratorFunction]"==D;if(v(t))return c(t,k);if("[object Object]"==D||"[object Arguments]"==D||P&&!N){if(A=M||P?{}:y(t),!k)return M?f(t,a(A,t)):l(t,s(A,t))}else{if(!C[D])return N?t:{};A=g(t,D,k)}}I||(I=new r);var B=I.get(t);if(B)return B;I.set(t,A),_(t)?t.forEach((function(r){A.add(e(r,n,x,r,t,I))})):S(t)&&t.forEach((function(r,o){A.set(o,e(r,n,x,o,t,I))}));var L=j?void 0:(R?M?d:p:M?T:O)(t);return o(L||t,(function(r,o){L&&(r=t[o=r]),i(A,o,e(r,n,x,o,t,I))})),A}},function(e,t,n){var r=n(25),o=n(28);e.exports=function(e){if(!o(e))return!1;var t=r(e);return"[object Function]"==t||"[object GeneratorFunction]"==t||"[object AsyncFunction]"==t||"[object Proxy]"==t}},function(e,t){var n="object"==typeof global&&global&&global.Object===Object&&global;e.exports=n},function(e,t){var n=Function.prototype.toString;e.exports=function(e){if(null!=e){try{return n.call(e)}catch(e){}try{return e+""}catch(e){}}return""}},function(e,t,n){var r=n(31),o=function(){try{var e=r(Object,"defineProperty");return e({},"",{}),e}catch(e){}}();e.exports=o},function(e,t,n){var r=n(267),o=n(108),i=n(12),s=n(109),a=n(68),c=n(153),u=Object.prototype.hasOwnProperty;e.exports=function(e,t){var n=i(e),l=!n&&o(e),f=!n&&!l&&s(e),p=!n&&!l&&!f&&c(e),d=n||l||f||p,h=d?r(e.length,String):[],m=h.length;for(var g in e)!t&&!u.call(e,g)||d&&("length"==g||f&&("offset"==g||"parent"==g)||p&&("buffer"==g||"byteLength"==g||"byteOffset"==g)||a(g,m))||h.push(g);return h}},function(e,t,n){var r=n(270),o=n(37),i=n(69),s=i&&i.isTypedArray,a=s?o(s):r;e.exports=a},function(e,t){e.exports=function(e,t){return function(n){return e(t(n))}}},function(e,t){e.exports=function(){return[]}},function(e,t,n){var r=n(114),o=n(115),i=n(113),s=n(155),a=Object.getOwnPropertySymbols?function(e){for(var t=[];e;)r(t,i(e)),e=o(e);return t}:s;e.exports=a},function(e,t,n){var r=n(158),o=n(113),i=n(49);e.exports=function(e){return r(e,i,o)}},function(e,t,n){var r=n(114),o=n(12);e.exports=function(e,t,n){var i=t(e);return o(e)?i:r(i,n(e))}},function(e,t,n){var r=n(158),o=n(156),i=n(112);e.exports=function(e){return r(e,i,o)}},function(e,t,n){var r=n(31)(n(19),"Set");e.exports=r},function(e,t,n){var r=n(19).Uint8Array;e.exports=r},function(e,t,n){var r=n(50);e.exports=function(e,t,n){var o=null==e?void 0:r(e,t);return void 0===o?n:o}},function(e,t,n){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.findEngineDriver=t.extractShellApiFunctionName=t.extractPackageName=t.extractShellApiPlugins=void 0;const o=r(n(301)),i=r(n(72)),s=r(n(73));t.extractShellApiPlugins=function(e,t){const n=[],r=e.match(/^([^@]+)@([^@]+)/);if(r&&n.push(r[2]),t&&t.connection&&t.connection.engine){const e=t.connection.engine.match(/^([^@]+)@([^@]+)/);e&&n.push(e[2])}return n},t.extractPackageName=function(e){if(!e)return null;const t=e.match(/^([^@]+)@([^@]+)/);return t?t[2]:null},t.extractShellApiFunctionName=function(e){const t=e.match(/^([^@]+)@([^@]+)/);return t?`${(0,o.default)(t[2])}.shellApi.${t[1]}`:`dbgateApi.${e}`},t.findEngineDriver=function(e,t){if((0,i.default)(e))return t.drivers.find(t=>t.engine==e);if((0,s.default)(e)){const{engine:n}=e;if(n)return t.drivers.find(e=>e.engine==n)}return null}},function(e,t){e.exports=function(e,t,n){var r=-1,o=e.length;t<0&&(t=-t>o?0:o+t),(n=n>o?o:n)<0&&(n+=o),o=t>n?0:n-t>>>0,t>>>=0;for(var i=Array(o);++r<o;)i[r]=e[r+t];return i}},function(e,t){var n=RegExp("[\\u200d\\ud800-\\udfff\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff\\ufe0e\\ufe0f]");e.exports=function(e){return n.test(e)}},function(e,t,n){var r=n(323);e.exports=function(e,t){return!!(null==e?0:e.length)&&r(e,t,0)>-1}},function(e,t){e.exports=function(e,t,n){for(var r=-1,o=null==e?0:e.length;++r<o;)if(n(t,e[r]))return!0;return!1}},function(e,t,n){var r=n(74),o=n(169),i=n(170);e.exports=function(e,t){return i(o(e,t,r),e+"")}},function(e,t,n){var r=n(327),o=Math.max;e.exports=function(e,t,n){return t=o(void 0===t?e.length-1:t,0),function(){for(var i=arguments,s=-1,a=o(i.length-t,0),c=Array(a);++s<a;)c[s]=i[t+s];s=-1;for(var u=Array(t+1);++s<t;)u[s]=i[s];return u[t]=n(c),r(e,this,u)}}},function(e,t,n){var r=n(328),o=n(330)(r);e.exports=o},function(e,t,n){var r=n(114),o=n(334);e.exports=function e(t,n,i,s,a){var c=-1,u=t.length;for(i||(i=o),a||(a=[]);++c<u;){var l=t[c];n>0&&i(l)?n>1?e(l,n-1,i,s,a):r(a,l):s||(a[a.length]=l)}return a}},function(e,t,n){var r=n(118),o=n(339),i=n(119);e.exports=function(e,t,n,s,a,c){var u=1&n,l=e.length,f=t.length;if(l!=f&&!(u&&f>l))return!1;var p=c.get(e),d=c.get(t);if(p&&d)return p==t&&d==e;var h=-1,m=!0,g=2&n?new r:void 0;for(c.set(e,t),c.set(t,e);++h<l;){var y=e[h],b=t[h];if(s)var v=u?s(b,y,h,t,e,c):s(y,b,h,e,t,c);if(void 0!==v){if(v)continue;m=!1;break}if(g){if(!o(t,(function(e,t){if(!i(g,t)&&(y===e||a(y,e,n,s,c)))return g.push(t)}))){m=!1;break}}else if(y!==b&&!a(y,b,n,s,c)){m=!1;break}}return c.delete(e),c.delete(t),m}},function(e,t,n){var r=n(28);e.exports=function(e){return e==e&&!r(e)}},function(e,t){e.exports=function(e,t){return function(n){return null!=n&&(n[e]===t&&(void 0!==t||e in Object(n)))}}},function(e,t,n){var r=n(345),o=n(346);e.exports=function(e,t){return null!=e&&o(e,t,r)}},function(e,t,n){var r=n(351),o=n(354)(r);e.exports=o},function(e,t,n){var r=n(363),o=n(178)((function(e,t){return null==e?{}:r(e,t)}));e.exports=o},function(e,t,n){var r=n(75),o=n(169),i=n(170);e.exports=function(e){return i(o(e,void 0,r),e+"")}},function(e,t,n){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.SqlDumper=void 0;const o=r(n(24)),i=r(n(72)),s=r(n(124)),a=r(n(367)),c=r(n(12)),u=r(n(73)),l=r(n(125));t.SqlDumper=class{constructor(e){this.s="",this.indentLevel=0,this.driver=e,this.dialect=e.dialect}endCommand(){this.putRaw(";\n")}putRaw(e){this.s+=e}escapeString(e){const t=this.dialect.stringEscapeChar;let n="";for(let r=0;r<e.length;r++){const o=e[r];o!=t&&"'"!=o||(n+=t),n+=o}return n}putStringValue(e){this.putRaw("'"),this.putRaw(this.escapeString(e)),this.putRaw("'")}putByteArrayValue(e){this.putRaw("NULL")}putValue(e){null===e?this.putRaw("NULL"):!0===e?this.putRaw("1"):!1===e?this.putRaw("0"):(0,i.default)(e)?this.putStringValue(e):(0,s.default)(e)?this.putRaw(e.toString()):(0,a.default)(e)?this.putStringValue(new Date(e).toISOString()):"Buffer"==(null==e?void 0:e.type)&&(0,c.default)(null==e?void 0:e.data)?this.putByteArrayValue(null==e?void 0:e.data):(0,u.default)(e)||(0,c.default)(e)?this.putStringValue(JSON.stringify(e)):this.putRaw("NULL")}putCmd(e,...t){this.put(e,...t),this.endCommand()}putFormattedValue(e,t){switch(e){case"s":null!=t&&this.putRaw(t.toString());break;case"i":this.putRaw(this.dialect.quoteIdentifier(t));break;case"k":t&&this.putRaw(t.toUpperCase());break;case"f":{const{schemaName:e,pureName:n}=t;e&&(this.putRaw(this.dialect.quoteIdentifier(e)),this.putRaw(".")),this.putRaw(this.dialect.quoteIdentifier(n))}break;case"v":this.putValue(t);break;case"c":t(this)}}putFormattedList(e,t){t&&this.putCollection(", ",t,t=>this.putFormattedValue(e,t))}put(e,...t){let n=0,r=0;const o=e.length;for(;n<o;){let i=e[n];switch(n++,i){case"^":for(;n<o&&e[n].match(/[a-z0-9_]/i);)this.putRaw(e[n].toUpperCase()),n++;break;case"%":switch(i=e[n],n++,i){case"%":this.putRaw("%");break;case",":i=e[n],n++,this.putFormattedList(i,t[r]);break;default:this.putFormattedValue(i,t[r])}r++;break;case"&":switch(i=e[n],n++,i){case"&":this.putRaw("&");break;case">":this.indentLevel++;break;case"<":this.indentLevel--;break;case"n":this.putRaw("\n"),this.putRaw(" ".repeat(2*this.indentLevel))}break;default:this.putRaw(i)}}}autoIncrement(){this.put(" ^auto_increment")}specialColumnOptions(e){}columnDefinition(e,{includeDefault:t=!0,includeNullable:n=!0,includeCollate:r=!0}={}){var o;if(e.computedExpression)return this.put("^as %s",e.computedExpression),void(e.isPersisted&&this.put(" ^persisted"));this.put("%k",e.dataType||this.dialect.fallbackDataType),e.autoIncrement&&this.autoIncrement(),this.putRaw(" "),this.specialColumnOptions(e),n&&this.put(e.notNull?"^not ^null":"^null"),t&&(null===(o=e.defaultValue)||void 0===o?void 0:o.trim())&&this.columnDefault(e)}columnDefault(e){null!=e.defaultConstraint?this.put(" ^constraint %i ^default %s ",e.defaultConstraint,e.defaultValue):this.put(" ^default %s ",e.defaultValue)}putCollection(e,t,n){if(!t)return;let r=!0;for(const o of t)r||this.put(e),r=!1,n(o)}createTable(e){this.put("^create ^table %f ( &>&n",e),this.putCollection(",&n",e.columns,e=>{this.put("%i ",e.columnName),this.columnDefinition(e)}),e.primaryKey&&(this.put(",&n"),e.primaryKey.constraintName&&this.put("^constraint %i",e.primaryKey.constraintName),this.put(" ^primary ^key (%,i)",e.primaryKey.columns.map(e=>e.columnName))),(e.foreignKeys||[]).forEach(e=>{this.put(",&n"),this.createForeignKeyFore(e)}),(e.uniques||[]).forEach(e=>{this.put(",&n"),this.createUniqueCore(e)}),(e.checks||[]).forEach(e=>{this.put(",&n"),this.createCheckCore(e)}),this.put("&<&n)"),this.endCommand(),(e.indexes||[]).forEach(e=>{this.createIndex(e)})}createForeignKeyFore(e){null!=e.constraintName&&this.put("^constraint %i ",e.constraintName),this.put("^foreign ^key (%,i) ^references %f (%,i)",e.columns.map(e=>e.columnName),{schemaName:e.refSchemaName,pureName:e.refTableName},e.columns.map(e=>e.refColumnName)),e.deleteAction&&this.put(" ^on ^delete %k",e.deleteAction),e.updateAction&&this.put(" ^on ^update %k",e.updateAction)}transform(e,t){t()}allowIdentityInsert(e,t){}enableConstraints(e,t){}comment(e){if(e)for(const t of e.split("\n"))this.put(" -- %s",t.trimRight())}createView(e){this.putRaw(e.createSql),this.endCommand()}dropView(e,{testIfExists:t=!1}){this.putCmd("^drop ^view %f",e)}alterView(e){this.putRaw(e.createSql.replace(/create\s+view/i,"ALTER VIEW")),this.endCommand()}changeViewSchema(e,t){}renameView(e,t){}createMatview(e){this.putRaw(e.createSql),this.endCommand()}dropMatview(e,{testIfExists:t=!1}){this.putCmd("^drop ^materialized ^view %f",e)}alterMatview(e){this.putRaw(e.createSql.replace(/create\s+view/i,"ALTER VIEW")),this.endCommand()}changeMatviewSchema(e,t){}renameMatview(e,t){}createProcedure(e){this.putRaw(e.createSql),this.endCommand()}dropProcedure(e,{testIfExists:t=!1}){this.putCmd("^drop ^procedure %f",e)}alterProcedure(e){this.putRaw(e.createSql.replace(/create\s+procedure/i,"ALTER PROCEDURE")),this.endCommand()}changeProcedureSchema(e,t){}renameProcedure(e,t){}createFunction(e){this.putRaw(e.createSql),this.endCommand()}dropFunction(e,{testIfExists:t=!1}){this.putCmd("^drop ^function %f",e)}alterFunction(e){this.putRaw(e.createSql.replace(/create\s+function/i,"ALTER FUNCTION")),this.endCommand()}changeFunctionSchema(e,t){}renameFunction(e,t){}createTrigger(e){this.putRaw(e.createSql),this.endCommand()}dropTrigger(e,{testIfExists:t=!1}){this.putCmd("^drop ^trigger %f",e)}alterTrigger(e){this.putRaw(e.createSql.replace(/create\s+trigger/i,"ALTER TRIGGER")),this.endCommand()}changeTriggerSchema(e,t){}renameTrigger(e,t){}dropConstraintCore(e){this.putCmd("^alter ^table %f ^drop ^constraint %i",e,e.constraintName)}dropConstraint(e){switch(e.constraintType){case"primaryKey":this.dropPrimaryKey(e);break;case"foreignKey":this.dropForeignKey(e);break;case"unique":this.dropUnique(e);break;case"check":this.dropCheck(e);break;case"index":this.dropIndex(e)}}createConstraint(e){switch(e.constraintType){case"primaryKey":this.createPrimaryKey(e);break;case"foreignKey":this.createForeignKey(e);break;case"unique":this.createUnique(e);break;case"check":this.createCheck(e);break;case"index":this.createIndex(e)}}changeConstraint(e,t){}dropForeignKey(e){this.dialect.explicitDropConstraint?this.putCmd("^alter ^table %f ^drop ^foreign ^key %i",e,e.constraintName):this.dropConstraintCore(e)}createForeignKey(e){this.put("^alter ^table %f ^add ",e),this.createForeignKeyFore(e),this.endCommand()}dropPrimaryKey(e){this.dialect.explicitDropConstraint?this.putCmd("^alter ^table %f ^drop ^primary ^key",e):this.dropConstraintCore(e)}createPrimaryKey(e){this.putCmd("^alter ^table %f ^add ^constraint %i ^primary ^key (%,i)",e,e.constraintName,e.columns.map(e=>e.columnName))}dropIndex(e){this.put("^drop ^index %i",e.constraintName),this.dialect.dropIndexContainsTableSpec&&this.put(" ^on %f",e),this.endCommand()}createIndex(e){this.put("^create"),e.isUnique&&this.put(" ^unique"),this.put(" ^index %i &n^on %f (&>&n",e.constraintName,e),this.putCollection(",&n",e.columns,e=>{this.put("%i %k",e.columnName,1==e.isDescending?"DESC":"ASC")}),this.put("&<&n)"),this.endCommand()}dropUnique(e){this.dropConstraintCore(e)}createUniqueCore(e){this.put("^constraint %i ^unique (%,i)",e.constraintName,e.columns.map(e=>e.columnName))}createUnique(e){this.put("^alter ^table %f ^add ",e),this.createUniqueCore(e),this.endCommand()}dropCheck(e){this.dropConstraintCore(e)}createCheckCore(e){this.put("^constraint %i ^check (%s)",e.constraintName,e.definition)}createCheck(e){this.put("^alter ^table %f ^add ",e),this.createCheckCore(e),this.endCommand()}renameConstraint(e,t){}createColumn(e,t){this.put("^alter ^table %f ^add %i ",e,e.columnName),this.columnDefinition(e),this.inlineConstraints(t),this.endCommand()}inlineConstraints(e){if(null!=e)for(const t of e)"primaryKey"==t.constraintType&&(null==t.constraintName||this.dialect.anonymousPrimaryKey||this.put(" ^constraint %i",t.constraintName),this.put(" ^primary ^key "))}dropColumn(e){this.putCmd("^alter ^table %f ^drop ^column %i",e,e.columnName)}renameColumn(e,t){}changeColumn(e,t,n){}dropTable(e,{testIfExists:t=!1}={}){this.putCmd("^drop ^table %f",e)}changeTableSchema(e,t){}renameTable(e,t){}beginTransaction(){this.putCmd("^begin ^transaction")}commitTransaction(){this.putCmd("^commit")}alterProlog(){}alterEpilog(){}selectTableIntoNewTable(e,t){this.putCmd("^select * ^into %f ^from %f",t,e)}truncateTable(e){this.putCmd("^delete ^from %f",e)}dropConstraints(e,t=!1){t&&this.dialect.dropForeignKey&&e.dependencies.forEach(e=>this.dropConstraint(e)),this.dialect.dropIndex&&e.indexes.forEach(e=>this.dropIndex(e)),this.dialect.dropForeignKey&&e.foreignKeys.forEach(e=>this.dropForeignKey(e)),this.dialect.dropPrimaryKey&&e.primaryKey&&this.dropPrimaryKey(e.primaryKey)}recreateTable(e,t){if(!e.pairingId||!t.pairingId||e.pairingId!=t.pairingId)throw new Error("Recreate is not possible: oldTable.paringId != newTable.paringId");const n=`temp_${(0,l.default)()}`,r=e.columns.map(e=>({oldcol:e,newcol:t.columns.find(t=>t.pairingId==e.pairingId)})).filter(e=>e.newcol);this.dropConstraints(e,!0),this.renameTable(e,n),this.createTable(t);const o=t.columns.find(e=>e.autoIncrement);o&&this.allowIdentityInsert(t,!0),this.putCmd("^insert ^into %f (%,i) select %,s ^from %f",t,r.map(e=>e.newcol.columnName),r.map(e=>e.oldcol.columnName),Object.assign(Object.assign({},e),{pureName:n})),o&&this.allowIdentityInsert(t,!1),this.dialect.dropForeignKey&&t.dependencies.forEach(e=>this.createConstraint(e)),this.dropTable(Object.assign(Object.assign({},e),{pureName:n}))}createSqlObject(e){this.putCmd(e.createSql)}getSqlObjectSqlName(e){switch(e){case"procedures":return"PROCEDURE";case"views":return"VIEW";case"functions":return"FUNCTION";case"triggers":return"TRIGGER";case"matviews":return"MATERIALIZED VIEW"}}dropSqlObject(e){this.putCmd("^drop %s %f",this.getSqlObjectSqlName(e.objectTypeField),e)}fillPreloadedRows(e,t,n,r,i){let s=!1;for(const a of n){const n=null==t?void 0:t.find(e=>r.every(t=>e[t]==a[t])),c=o.default.keys(a);if(n){const t=[];for(const e of c)a[e]==n[e]||(null==i?void 0:i.includes(e))||t.push(e);t.length>0&&(s&&this.put(";\n"),s=!0,this.put("^update %f ^set ",e),this.putCollection(", ",t,e=>this.put("%i=%v",e,a[e])),this.put(" ^where "),this.putCollection(" ^and ",r,e=>this.put("%i=%v",e,a[e])))}else s&&this.put(";\n"),s=!0,this.put("^insert ^into %f (%,i) ^values (%,v)",e,c,c.map(e=>a[e]))}s&&this.endCommand()}}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dumpSqlExpression=void 0;const r=n(126);t.dumpSqlExpression=function e(t,n){switch(n.exprType){case"column":n.source&&(0,r.dumpSqlSourceRef)(t,n.source)&&t.put("."),t.put("%i",n.columnName);break;case"placeholder":t.putRaw("{PLACEHOLDER}");break;case"value":t.put("%v",n.value);break;case"raw":t.put("%s",n.sql);break;case"call":t.put("%s(",n.func),n.argsPrefix&&t.put("%s ",n.argsPrefix),t.putCollection(",",n.args,n=>e(t,n)),t.put(")");break;case"transform":t.transform(n.transform,()=>e(t,n.expr));break;case"rowNumber":t.put(" ^row_number() ^over (^order ^by "),t.putCollection(", ",n.orderBy,n=>{e(t,n),t.put(" %k",n.direction)}),t.put(")")}}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.evaluateExpression=void 0,t.evaluateExpression=function(e,t){switch(e.exprType){case"column":return t[e.columnName];case"placeholder":return t.__placeholder;case"value":return e.value;case"raw":return e.sql;case"call":case"transform":return null}}},function(e,t,n){var r=n(118),o=n(166),i=n(167),s=n(119),a=n(381),c=n(123);e.exports=function(e,t,n){var u=-1,l=o,f=e.length,p=!0,d=[],h=d;if(n)p=!1,l=i;else if(f>=200){var m=t?null:a(e);if(m)return c(m);p=!1,l=s,h=new r}else h=t?[]:d;e:for(;++u<f;){var g=e[u],y=t?t(g):g;if(g=n||0!==g?g:0,p&&y==y){for(var b=h.length;b--;)if(h[b]===y)continue e;t&&h.push(y),d.push(g)}else l(h,y,n)||(h!==d&&h.push(y),d.push(g))}return d}},function(e,t,n){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isTableColumnUnique=t.extendDatabaseInfoFromApps=t.extendDatabaseInfo=t.extendTableInfo=t.addTableDependencies=void 0;const o=r(n(75));function i(e){const t=(0,o.default)(e.tables.map(e=>e.foreignKeys||[]));return Object.assign(Object.assign({},e),{tables:e.tables.map(e=>Object.assign(Object.assign({},e),{dependencies:t.filter(t=>t.refSchemaName==e.schemaName&&t.refTableName==e.pureName)}))})}function s(e){return Object.assign(Object.assign({},e),{objectTypeField:"tables",columns:(e.columns||[]).map(t=>Object.assign({pureName:e.pureName,schemaName:e.schemaName},t)),primaryKey:e.primaryKey?Object.assign(Object.assign({},e.primaryKey),{pureName:e.pureName,schemaName:e.schemaName,constraintType:"primaryKey"}):void 0,foreignKeys:(e.foreignKeys||[]).map(t=>Object.assign(Object.assign({},t),{pureName:e.pureName,schemaName:e.schemaName,constraintType:"foreignKey"})),indexes:(e.indexes||[]).map(t=>Object.assign(Object.assign({},t),{pureName:e.pureName,schemaName:e.schemaName,constraintType:"index"})),checks:(e.checks||[]).map(t=>Object.assign(Object.assign({},t),{pureName:e.pureName,schemaName:e.schemaName,constraintType:"check"})),uniques:(e.uniques||[]).map(t=>Object.assign(Object.assign({},t),{pureName:e.pureName,schemaName:e.schemaName,constraintType:"unique"}))})}t.addTableDependencies=i,t.extendTableInfo=s,t.extendDatabaseInfo=function(e){return function(e){return Object.assign(Object.assign({},e),{tables:(e.tables||[]).map(s),collections:(e.collections||[]).map(e=>Object.assign(Object.assign({},e),{objectTypeField:"collections"})),views:(e.views||[]).map(e=>Object.assign(Object.assign({},e),{objectTypeField:"views"})),matviews:(e.matviews||[]).map(e=>Object.assign(Object.assign({},e),{objectTypeField:"matviews"})),procedures:(e.procedures||[]).map(e=>Object.assign(Object.assign({},e),{objectTypeField:"procedures"})),functions:(e.functions||[]).map(e=>Object.assign(Object.assign({},e),{objectTypeField:"functions"})),triggers:(e.triggers||[]).map(e=>Object.assign(Object.assign({},e),{objectTypeField:"triggers"}))})}(i(e))},t.extendDatabaseInfoFromApps=function(e,t){return e&&t?i(Object.assign(Object.assign({},e),{tables:e.tables.map(e=>Object.assign(Object.assign({},e),{foreignKeys:[...e.foreignKeys||[],...(0,o.default)(t.map(e=>e.virtualReferences||[])).filter(t=>t.pureName==e.pureName&&t.schemaName==e.schemaName).map(e=>Object.assign(Object.assign({},e),{constraintType:"foreignKey",isVirtual:!0}))]}))})):e},t.isTableColumnUnique=function(e,t){return!(!e.primaryKey||1!=e.primaryKey.columns.length||e.primaryKey.columns[0].columnName!=t)||!![...e.uniques||[],...(e.indexes||[]).filter(e=>e.isUnique)].find(e=>1==e.columns.length&&e.columns[0].columnName==t)}},function(e,t,n){var r=n(51),o=n(147),i=n(392),s=n(39),a=n(48),c=n(395),u=n(178),l=n(159),f=u((function(e,t){var n={};if(null==e)return n;var u=!1;t=r(t,(function(t){return t=s(t,e),u||(u=t.length>1),t})),a(e,l(e),n),u&&(n=o(n,7,c));for(var f=t.length;f--;)i(n,t[f]);return n}));e.exports=f},function(e,t,n){var r=n(404),o=n(53),i=n(82),s=n(86),a=n(83),c=n(77),u=n(130),l=n(43),f=n(129),p=n(85),d=n(84),h=n(79),m=n(80),g=n(81),y=n(78);r.BSON_INT32_MAX=2147483647,r.BSON_INT32_MIN=-2147483648,r.BSON_INT64_MAX=Math.pow(2,63)-1,r.BSON_INT64_MIN=-Math.pow(2,63),r.JS_INT_MAX=9007199254740992,r.JS_INT_MIN=-9007199254740992,r.Binary=o,r.Code=i,r.DBRef=s,r.Decimal128=a,r.Double=c,r.Int32=u,r.Long=l,r.Map=f,r.MaxKey=p,r.MinKey=d,r.ObjectId=h,r.ObjectID=h,r.BSONRegExp=m,r.Symbol=g,r.Timestamp=y,e.exports=r},function(e,t){function n(e){var t=new Error("Cannot find module '"+e+"'");throw t.code="MODULE_NOT_FOUND",t}n.keys=function(){return[]},n.resolve=n,e.exports=n,n.id=186},function(e,t,n){"use strict";const r=n(8).EventEmitter,o=n(20),i=n(9).debugOptions,s=n(6).parseHeader,a=n(30).decompress,c=n(21).Response,u=n(45).BinMsg,l=n(3).MongoNetworkError,f=n(3).MongoNetworkTimeoutError,p=n(3).MongoError,d=n(16),h=n(6).opcodes.OP_COMPRESSED,m=n(6).opcodes.OP_MSG,g=n(6).MESSAGE_HEADER_SIZE,y=n(22).Buffer,b=n(21).Query,v=n(133);let S=0;const w=["host","port","size","keepAlive","keepAliveInitialDelay","noDelay","connectionTimeout","socketTimeout","ssl","ca","crl","cert","rejectUnauthorized","promoteLongs","promoteValues","promoteBuffers","checkServerIdentity"];let _=void 0,O=!1,T={};const C=["error","close","timeout","parseError"];function x(e){delete T[e],_&&_.deleteConnection(e)}function E(e,t){const n=s(t);if(n.opCode!==h){const r=n.opCode===m?u:c;return void e.emit("message",new r(e.bson,t,n,t.slice(g),e.responseOptions),e)}n.fromCompressed=!0;let r=g;n.opCode=t.readInt32LE(r),r+=4,n.length=t.readInt32LE(r),r+=4;const o=t[r];r++,a(o,t.slice(r),(r,o)=>{if(r)return void e.emit("error",r);if(o.length!==n.length)return void e.emit("error",new p("Decompressing a compressed message from the server failed. The message is corrupt."));const i=n.opCode===m?u:c;e.emit("message",new i(e.bson,t,n,o,e.responseOptions),e)})}e.exports=class extends r{constructor(e,t){if(super(),!(t=t||{}).bson)throw new TypeError("must pass in valid bson parser");this.id=S++,this.options=t,this.logger=d("Connection",t),this.bson=t.bson,this.tag=t.tag,this.maxBsonMessageSize=t.maxBsonMessageSize||67108864,this.port=t.port||27017,this.host=t.host||"localhost",this.socketTimeout="number"==typeof t.socketTimeout?t.socketTimeout:0,this.keepAlive="boolean"!=typeof t.keepAlive||t.keepAlive,this.keepAliveInitialDelay="number"==typeof t.keepAliveInitialDelay?t.keepAliveInitialDelay:12e4,this.connectionTimeout="number"==typeof t.connectionTimeout?t.connectionTimeout:3e4,this.keepAliveInitialDelay>this.socketTimeout&&(this.keepAliveInitialDelay=Math.round(this.socketTimeout/2)),this.logger.isDebug()&&this.logger.debug(`creating connection ${this.id} with options [${JSON.stringify(i(w,t))}]`),this.responseOptions={promoteLongs:"boolean"!=typeof t.promoteLongs||t.promoteLongs,promoteValues:"boolean"!=typeof t.promoteValues||t.promoteValues,promoteBuffers:"boolean"==typeof t.promoteBuffers&&t.promoteBuffers},this.flushing=!1,this.queue=[],this.writeStream=null,this.destroyed=!1,this.timedOut=!1;const n=o.createHash("sha1");var r,s,a;n.update(this.address),this.hashedName=n.digest("hex"),this.workItems=[],this.socket=e,this.socket.once("error",(r=this,function(e){O&&x(r.id),r.logger.isDebug()&&r.logger.debug(`connection ${r.id} for [${r.address}] errored out with [${JSON.stringify(e)}]`),r.emit("error",new l(e),r)})),this.socket.once("timeout",function(e){return function(){O&&x(e.id),e.logger.isDebug()&&e.logger.debug(`connection ${e.id} for [${e.address}] timed out`),e.timedOut=!0,e.emit("timeout",new f(`connection ${e.id} to ${e.address} timed out`,{beforeHandshake:null==e.ismaster}),e)}}(this)),this.socket.once("close",function(e){return function(t){O&&x(e.id),e.logger.isDebug()&&e.logger.debug(`connection ${e.id} with for [${e.address}] closed`),t||e.emit("close",new l(`connection ${e.id} to ${e.address} closed`),e)}}(this)),this.socket.on("data",function(e){return function(t){for(;t.length>0;)if(e.bytesRead>0&&e.sizeOfMessage>0){const n=e.sizeOfMessage-e.bytesRead;if(n>t.length)t.copy(e.buffer,e.bytesRead),e.bytesRead=e.bytesRead+t.length,t=y.alloc(0);else{t.copy(e.buffer,e.bytesRead,0,n),t=t.slice(n);const r=e.buffer;e.buffer=null,e.sizeOfMessage=0,e.bytesRead=0,e.stubBuffer=null,E(e,r)}}else if(null!=e.stubBuffer&&e.stubBuffer.length>0)if(e.stubBuffer.length+t.length>4){const n=y.alloc(e.stubBuffer.length+t.length);e.stubBuffer.copy(n,0),t.copy(n,e.stubBuffer.length),t=n,e.buffer=null,e.sizeOfMessage=0,e.bytesRead=0,e.stubBuffer=null}else{const n=y.alloc(e.stubBuffer.length+t.length);e.stubBuffer.copy(n,0),t.copy(n,e.stubBuffer.length),t=y.alloc(0)}else if(t.length>4){const n=t[0]|t[1]<<8|t[2]<<16|t[3]<<24;if(n<0||n>e.maxBsonMessageSize){const t={err:"socketHandler",trace:"",bin:e.buffer,parseState:{sizeOfMessage:n,bytesRead:e.bytesRead,stubBuffer:e.stubBuffer}};return void e.emit("parseError",t,e)}if(n>4&&n<e.maxBsonMessageSize&&n>t.length)e.buffer=y.alloc(n),t.copy(e.buffer,0),e.bytesRead=t.length,e.sizeOfMessage=n,e.stubBuffer=null,t=y.alloc(0);else if(n>4&&n<e.maxBsonMessageSize&&n===t.length){const n=t;e.buffer=null,e.sizeOfMessage=0,e.bytesRead=0,e.stubBuffer=null,t=y.alloc(0),E(e,n)}else if(n<=4||n>e.maxBsonMessageSize){const r={err:"socketHandler",trace:null,bin:t,parseState:{sizeOfMessage:n,bytesRead:0,buffer:null,stubBuffer:null}};e.emit("parseError",r,e),e.buffer=null,e.sizeOfMessage=0,e.bytesRead=0,e.stubBuffer=null,t=y.alloc(0)}else{const r=t.slice(0,n);e.buffer=null,e.sizeOfMessage=0,e.bytesRead=0,e.stubBuffer=null,t=t.slice(n),E(e,r)}}else e.stubBuffer=y.alloc(t.length),t.copy(e.stubBuffer,0),t=y.alloc(0)}}(this)),O&&(s=this.id,a=this,T[s]=a,_&&_.addConnection(s,a))}setSocketTimeout(e){this.socket&&this.socket.setTimeout(e)}resetSocketTimeout(){this.socket&&this.socket.setTimeout(this.socketTimeout)}static enableConnectionAccounting(e){e&&(_=e),O=!0,T={}}static disableConnectionAccounting(){O=!1,_=void 0}static connections(){return T}get address(){return`${this.host}:${this.port}`}unref(){null!=this.socket?this.socket.unref():this.once("connect",()=>this.socket.unref())}flush(e){for(;this.workItems.length>0;){const t=this.workItems.shift();t.cb&&t.cb(e)}}destroy(e,t){if("function"==typeof e&&(t=e,e={}),e=Object.assign({force:!1},e),O&&x(this.id),null!=this.socket)return e.force||this.timedOut?(this.socket.destroy(),this.destroyed=!0,void("function"==typeof t&&t(null,null))):void this.socket.end(e=>{this.destroyed=!0,"function"==typeof t&&t(e,null)});this.destroyed=!0}write(e){if(this.logger.isDebug())if(Array.isArray(e))for(let t=0;t<e.length;t++)this.logger.debug(`writing buffer [${e[t].toString("hex")}] to ${this.address}`);else this.logger.debug(`writing buffer [${e.toString("hex")}] to ${this.address}`);if(!1===this.socket.destroyed){if(!Array.isArray(e))return this.socket.write(e,"binary"),!0;for(let t=0;t<e.length;t++)this.socket.write(e[t],"binary");return!0}return!1}toString(){return""+this.id}toJSON(){return{id:this.id,host:this.host,port:this.port}}isConnected(){return!this.destroyed&&(!this.socket.destroyed&&this.socket.writable)}command(e,t,n,r){"function"==typeof n&&(r=n,n={});const o=this,i="number"==typeof n.socketTimeout?n.socketTimeout:0,s=o.options.bson,a=new b(s,e,t,{numberToSkip:0,numberToReturn:1}),c=()=>{};function u(e,t){r(e,t),r=c}function l(e){o.resetSocketTimeout(),C.forEach(e=>o.removeListener(e,l)),o.removeListener("message",f),null==e&&(e=new p(`runCommand failed for connection to '${o.address}'`)),o.on("error",c),u(e)}function f(e){if(e.responseTo!==a.requestId)return;o.resetSocketTimeout(),C.forEach(e=>o.removeListener(e,l)),o.removeListener("message",f),e.parse({promoteValues:!0});const t=e.documents[0];0===t.ok||t.$err||t.errmsg||t.code?u(new p(t)):u(void 0,new v(t,this,e))}o.setSocketTimeout(i),C.forEach(e=>o.once(e,l)),o.on("message",f),o.write(a.toBin())}}},function(e,t,n){"use strict";t.asyncIterator=function(){const e=this;return{next:function(){return Promise.resolve().then(()=>e.next()).then(t=>t?{value:t,done:!1}:e.close().then(()=>({value:t,done:!0})))}}}},function(e,t,n){"use strict";const r=n(13).ServerType,o=n(44).ServerDescription,i=n(190),s=n(13).TopologyType,a=i.MIN_SUPPORTED_SERVER_VERSION,c=i.MAX_SUPPORTED_SERVER_VERSION,u=i.MIN_SUPPORTED_WIRE_VERSION,l=i.MAX_SUPPORTED_WIRE_VERSION;class f{constructor(e,t,n,o,i,f,p){p=p||{},this.type=e||s.Unknown,this.setName=n||null,this.maxSetVersion=o||null,this.maxElectionId=i||null,this.servers=t||new Map,this.stale=!1,this.compatible=!0,this.compatibilityError=null,this.logicalSessionTimeoutMinutes=null,this.heartbeatFrequencyMS=p.heartbeatFrequencyMS||0,this.localThresholdMS=p.localThresholdMS||0,this.commonWireVersion=f||null,Object.defineProperty(this,"options",{value:p,enumberable:!1});for(const e of this.servers.values())if(e.type!==r.Unknown&&(e.minWireVersion>l&&(this.compatible=!1,this.compatibilityError=`Server at ${e.address} requires wire version ${e.minWireVersion}, but this version of the driver only supports up to ${l} (MongoDB ${c})`),e.maxWireVersion<u)){this.compatible=!1,this.compatibilityError=`Server at ${e.address} reports wire version ${e.maxWireVersion}, but this version of the driver requires at least ${u} (MongoDB ${a}).`;break}this.logicalSessionTimeoutMinutes=null;for(const e of this.servers){const t=e[1];if(t.isReadable){if(null==t.logicalSessionTimeoutMinutes){this.logicalSessionTimeoutMinutes=null;break}if(null==this.logicalSessionTimeoutMinutes){this.logicalSessionTimeoutMinutes=t.logicalSessionTimeoutMinutes;continue}this.logicalSessionTimeoutMinutes=Math.min(this.logicalSessionTimeoutMinutes,t.logicalSessionTimeoutMinutes)}}}updateFromSrvPollingEvent(e){const t=e.addresses(),n=new Map(this.servers);for(const e of this.servers)t.has(e[0])?t.delete(e[0]):n.delete(e[0]);if(n.size===this.servers.size&&0===t.size)return this;for(const e of t)n.set(e,new o(e));return new f(this.type,n,this.setName,this.maxSetVersion,this.maxElectionId,this.commonWireVersion,this.options,null)}update(e){const t=e.address;let n=this.type,i=this.setName,a=this.maxSetVersion,c=this.maxElectionId,u=this.commonWireVersion;e.setName&&i&&e.setName!==i&&(e=new o(t,null));const l=e.type;let h=new Map(this.servers);if(0!==e.maxWireVersion&&(u=null==u?e.maxWireVersion:Math.min(u,e.maxWireVersion)),h.set(t,e),n===s.Single)return new f(s.Single,h,i,a,c,u,this.options);if(n===s.Unknown&&(l===r.Standalone&&1!==this.servers.size?h.delete(t):n=function(e){if(e===r.Standalone)return s.Single;if(e===r.Mongos)return s.Sharded;if(e===r.RSPrimary)return s.ReplicaSetWithPrimary;if(e===r.RSGhost||e===r.Unknown)return s.Unknown;return s.ReplicaSetNoPrimary}(l)),n===s.Sharded&&-1===[r.Mongos,r.Unknown].indexOf(l)&&h.delete(t),n===s.ReplicaSetNoPrimary)if([r.Standalone,r.Mongos].indexOf(l)>=0&&h.delete(t),l===r.RSPrimary){const t=p(h,i,e,a,c);n=t[0],i=t[1],a=t[2],c=t[3]}else if([r.RSSecondary,r.RSArbiter,r.RSOther].indexOf(l)>=0){const t=function(e,t,n){let r=s.ReplicaSetNoPrimary;if((t=t||n.setName)!==n.setName)return e.delete(n.address),[r,t];n.allHosts.forEach(t=>{e.has(t)||e.set(t,new o(t))}),n.me&&n.address!==n.me&&e.delete(n.address);return[r,t]}(h,i,e);n=t[0],i=t[1]}if(n===s.ReplicaSetWithPrimary)if([r.Standalone,r.Mongos].indexOf(l)>=0)h.delete(t),n=d(h);else if(l===r.RSPrimary){const t=p(h,i,e,a,c);n=t[0],i=t[1],a=t[2],c=t[3]}else n=[r.RSSecondary,r.RSArbiter,r.RSOther].indexOf(l)>=0?function(e,t,n){if(null==t)throw new TypeError("setName is required");(t!==n.setName||n.me&&n.address!==n.me)&&e.delete(n.address);return d(e)}(h,i,e):d(h);return new f(n,h,i,a,c,u,this.options)}get error(){const e=Array.from(this.servers.values()).filter(e=>e.error);if(e.length>0)return e[0].error}get hasKnownServers(){return Array.from(this.servers.values()).some(e=>e.type!==r.Unknown)}get hasDataBearingServers(){return Array.from(this.servers.values()).some(e=>e.isDataBearing)}hasServer(e){return this.servers.has(e)}}function p(e,t,n,i,s){if((t=t||n.setName)!==n.setName)return e.delete(n.address),[d(e),t,i,s];const a=n.electionId?n.electionId:null;if(n.setVersion&&a){if(i&&s&&(i>n.setVersion||function(e,t){if(null==e)return-1;if(null==t)return 1;if(e.id instanceof Buffer&&t.id instanceof Buffer){const n=e.id,r=t.id;return n.compare(r)}const n=e.toString(),r=t.toString();return n.localeCompare(r)}(s,a)>0))return e.set(n.address,new o(n.address)),[d(e),t,i,s];s=n.electionId}null!=n.setVersion&&(null==i||n.setVersion>i)&&(i=n.setVersion);for(const t of e.keys()){const i=e.get(t);if(i.type===r.RSPrimary&&i.address!==n.address){e.set(t,new o(i.address));break}}n.allHosts.forEach(t=>{e.has(t)||e.set(t,new o(t))});const c=Array.from(e.keys()),u=n.allHosts;return c.filter(e=>-1===u.indexOf(e)).forEach(t=>{e.delete(t)}),[d(e),t,i,s]}function d(e){for(const t of e.keys())if(e.get(t).type===r.RSPrimary)return s.ReplicaSetWithPrimary;return s.ReplicaSetNoPrimary}e.exports={TopologyDescription:f}},function(e,t,n){"use strict";e.exports={MIN_SUPPORTED_SERVER_VERSION:"2.6",MAX_SUPPORTED_SERVER_VERSION:"4.4",MIN_SUPPORTED_WIRE_VERSION:2,MAX_SUPPORTED_WIRE_VERSION:9}},function(e,t,n){"use strict";const r=n(45).Msg,o=n(21).KillCursor,i=n(21).GetMore,s=n(0).calculateDurationInMs,a=new Set(["authenticate","saslStart","saslContinue","getnonce","createUser","updateUser","copydbgetnonce","copydbsaslstart","copydb"]),c=e=>Object.keys(e)[0],u=e=>e.ns,l=e=>e.ns.split(".")[0],f=e=>e.ns.split(".")[1],p=e=>e.options?`${e.options.host}:${e.options.port}`:e.address,d=(e,t)=>a.has(e)?{}:t,h={$query:"filter",$orderby:"sort",$hint:"hint",$comment:"comment",$maxScan:"maxScan",$max:"max",$min:"min",$returnKey:"returnKey",$showDiskLoc:"showRecordId",$maxTimeMS:"maxTimeMS",$snapshot:"snapshot"},m={numberToSkip:"skip",numberToReturn:"batchSize",returnFieldsSelector:"projection"},g=["tailable","oplogReplay","noCursorTimeout","awaitData","partial","exhaust"],y=e=>{if(e instanceof i)return{getMore:e.cursorId,collection:f(e),batchSize:e.numberToReturn};if(e instanceof o)return{killCursors:f(e),cursors:e.cursorIds};if(e instanceof r)return e.command;if(e.query&&e.query.$query){let t;return"admin.$cmd"===e.ns?t=Object.assign({},e.query.$query):(t={find:f(e)},Object.keys(h).forEach(n=>{void 0!==e.query[n]&&(t[h[n]]=e.query[n])})),Object.keys(m).forEach(n=>{void 0!==e[n]&&(t[m[n]]=e[n])}),g.forEach(n=>{e[n]&&(t[n]=e[n])}),void 0!==e.pre32Limit&&(t.limit=e.pre32Limit),e.query.$explain?{explain:t}:t}return e.query?e.query:e},b=(e,t)=>e instanceof i?{ok:1,cursor:{id:t.message.cursorId,ns:u(e),nextBatch:t.message.documents}}:e instanceof o?{ok:1,cursorsUnknown:e.cursorIds}:e.query&&void 0!==e.query.$query?{ok:1,cursor:{id:t.message.cursorId,ns:u(e),firstBatch:t.message.documents}}:t&&t.result?t.result:t,v=e=>{if((e=>e.s&&e.queue)(e))return{connectionId:p(e)};const t=e;return{address:t.address,connectionId:t.id}};e.exports={CommandStartedEvent:class{constructor(e,t){const n=y(t),r=c(n),o=v(e);a.has(r)&&(this.commandObj={},this.commandObj[r]=!0),Object.assign(this,o,{requestId:t.requestId,databaseName:l(t),commandName:r,command:n})}},CommandSucceededEvent:class{constructor(e,t,n,r){const o=y(t),i=c(o),a=v(e);Object.assign(this,a,{requestId:t.requestId,commandName:i,duration:s(r),reply:d(i,b(t,n))})}},CommandFailedEvent:class{constructor(e,t,n,r){const o=y(t),i=c(o),a=v(e);Object.assign(this,a,{requestId:t.requestId,commandName:i,duration:s(r),failure:d(i,n)})}}}},function(e,t){e.exports=require("tls")},function(e,t,n){"use strict";const r=n(194),o=n(195),i=n(196),s=n(197),a=n(88).ScramSHA1,c=n(88).ScramSHA256,u=n(420);e.exports={defaultAuthProviders:function(e){return{"mongodb-aws":new u(e),mongocr:new r(e),x509:new o(e),plain:new i(e),gssapi:new s(e),"scram-sha-1":new a(e),"scram-sha-256":new c(e)}}}},function(e,t,n){"use strict";const r=n(20),o=n(33).AuthProvider;e.exports=class extends o{auth(e,t){const n=e.connection,o=e.credentials,i=o.username,s=o.password,a=o.source;n.command(`${a}.$cmd`,{getnonce:1},(e,o)=>{let c=null,u=null;if(null==e){c=o.result.nonce;let e=r.createHash("md5");e.update(i+":mongo:"+s,"utf8");const t=e.digest("hex");e=r.createHash("md5"),e.update(c+i+t,"utf8"),u=e.digest("hex")}const l={authenticate:1,user:i,nonce:c,key:u};n.command(`${a}.$cmd`,l,t)})}}},function(e,t,n){"use strict";const r=n(33).AuthProvider;function o(e){const t={authenticate:1,mechanism:"MONGODB-X509"};return e.username&&Object.assign(t,{user:e.username}),t}e.exports=class extends r{prepare(e,t,n){const r=t.credentials;Object.assign(e,{speculativeAuthenticate:o(r)}),n(void 0,e)}auth(e,t){const n=e.connection,r=e.credentials;if(e.response.speculativeAuthenticate)return t();n.command("$external.$cmd",o(r),t)}}},function(e,t,n){"use strict";const r=n(9).retrieveBSON,o=n(33).AuthProvider,i=r().Binary;e.exports=class extends o{auth(e,t){const n=e.connection,r=e.credentials,o=r.username,s=r.password,a={saslStart:1,mechanism:"PLAIN",payload:new i(`\0${o}\0${s}`),autoAuthorize:1};n.command("$external.$cmd",a,t)}}},function(e,t,n){"use strict";const r=n(87),o=n(33).AuthProvider,i=n(4).retrieveKerberos,s=n(3).MongoError;let a;e.exports=class extends o{auth(e,t){const n=e.connection,o=e.credentials;if(null==o)return t(new s("credentials required"));const c=o.username;function u(e,t){return n.command("$external.$cmd",e,t)}!function(e,t){const n=e.options.host,o=e.options.port,c=e.credentials;if(!n||!o||!c)return t(new s(`Connection must specify: ${n?"host":""}, ${o?"port":""}, ${c?"host":"credentials"}.`));if(null==a)try{a=i()}catch(e){return t(e)}const u=c.username,l=c.password,f=c.mechanismProperties,p=f.gssapiservicename||f.gssapiServiceName||"mongodb";!function(e,t,n){if("boolean"!=typeof t.gssapiCanonicalizeHostName||!t.gssapiCanonicalizeHostName)return n(void 0,e);r.resolveCname(e,(t,r)=>t?n(t):Array.isArray(r)&&r.length>0?n(void 0,r[0]):void n(void 0,e))}(n,f,(e,n)=>{if(e)return t(e);const r={};null!=l&&Object.assign(r,{user:u,password:l}),a.initializeClient(`${p}${"win32"===process.platform?"/":"@"}${n}`,r,(e,n)=>{if(e)return t(new s(e));t(null,n)})})}(e,(e,n)=>e?t(e):null==n?t(new s("gssapi client missing")):void n.step("",(e,r)=>{if(e)return t(e);u(function(e){return{saslStart:1,mechanism:"GSSAPI",payload:e,autoAuthorize:1}}(r),(e,r)=>{if(e)return t(e);const o=r.result;!function e(t,n,r,o){t.step(r,(i,s)=>i&&0===n?o(i):i?e(t,n-1,r,o):void o(void 0,s||""))}(n,10,o.payload,(e,r)=>{if(e)return t(e);u(function(e,t){return{saslContinue:1,conversationId:t,payload:e}}(r,o.conversationId),(e,r)=>{if(e)return t(e);const o=r.result;!function(e,t,n,r){e.unwrap(n,(n,o)=>{if(n)return r(n);e.wrap(o||"",{user:t},(e,t)=>{if(e)return r(e);r(void 0,t)})})}(n,c,o.payload,(e,n)=>{if(e)return t(e);u({saslContinue:1,conversationId:o.conversationId,payload:n},(e,n)=>{if(e)return t(e);t(void 0,n)})})})})})}))}}},function(e,t,n){"use strict";function r(e){if(e){if(Array.isArray(e.saslSupportedMechs))return e.saslSupportedMechs.indexOf("SCRAM-SHA-256")>=0?"scram-sha-256":"scram-sha-1";if(e.maxWireVersion>=3)return"scram-sha-1"}return"mongocr"}class o{constructor(e){e=e||{},this.username=e.username,this.password=e.password,this.source=e.source||e.db,this.mechanism=e.mechanism||"default",this.mechanismProperties=e.mechanismProperties||{},this.mechanism.match(/MONGODB-AWS/i)&&(null==this.username&&process.env.AWS_ACCESS_KEY_ID&&(this.username=process.env.AWS_ACCESS_KEY_ID),null==this.password&&process.env.AWS_SECRET_ACCESS_KEY&&(this.password=process.env.AWS_SECRET_ACCESS_KEY),null==this.mechanismProperties.AWS_SESSION_TOKEN&&process.env.AWS_SESSION_TOKEN&&(this.mechanismProperties.AWS_SESSION_TOKEN=process.env.AWS_SESSION_TOKEN)),Object.freeze(this.mechanismProperties),Object.freeze(this)}equals(e){return this.mechanism===e.mechanism&&this.username===e.username&&this.password===e.password&&this.source===e.source}resolveAuthMechanism(e){return this.mechanism.match(/DEFAULT/i)?new o({username:this.username,password:this.password,source:this.source,mechanism:r(e),mechanismProperties:this.mechanismProperties}):this}}e.exports={MongoCredentials:o}},function(e,t,n){"use strict";const r=n(424);e.exports={insert:function(e,t,n,o,i){r(e,"insert","documents",t,n,o,i)},update:function(e,t,n,o,i){r(e,"update","updates",t,n,o,i)},remove:function(e,t,n,o,i){r(e,"delete","deletes",t,n,o,i)},killCursors:n(425),getMore:n(426),query:n(427),command:n(55)}},function(e,t,n){"use strict";e.exports={ServerDescriptionChangedEvent:class{constructor(e,t,n,r){Object.assign(this,{topologyId:e,address:t,previousDescription:n,newDescription:r})}},ServerOpeningEvent:class{constructor(e,t){Object.assign(this,{topologyId:e,address:t})}},ServerClosedEvent:class{constructor(e,t){Object.assign(this,{topologyId:e,address:t})}},TopologyDescriptionChangedEvent:class{constructor(e,t,n){Object.assign(this,{topologyId:e,previousDescription:t,newDescription:n})}},TopologyOpeningEvent:class{constructor(e){Object.assign(this,{topologyId:e})}},TopologyClosedEvent:class{constructor(e){Object.assign(this,{topologyId:e})}},ServerHeartbeatStartedEvent:class{constructor(e){Object.assign(this,{connectionId:e})}},ServerHeartbeatSucceededEvent:class{constructor(e,t,n){Object.assign(this,{connectionId:n,duration:e,reply:t})}},ServerHeartbeatFailedEvent:class{constructor(e,t,n){Object.assign(this,{connectionId:n,duration:e,failure:t})}}}},function(e,t,n){"use strict";const r=n(8),o=n(434),i=n(3).MongoError,s=n(3).MongoNetworkError,a=n(3).MongoNetworkTimeoutError,c=n(3).MongoWriteConcernError,u=n(133),l=n(441).StreamDescription,f=n(199),p=n(191),d=n(34).updateSessionFromResponse,h=n(4).uuidV4,m=n(0).now,g=n(0).calculateDurationInMs,y=Symbol("stream"),b=Symbol("queue"),v=Symbol("messageStream"),S=Symbol("generation"),w=Symbol("lastUseTime"),_=Symbol("clusterTime"),O=Symbol("description"),T=Symbol("ismaster"),C=Symbol("autoEncrypter");function x(e){const t={description:e.description,clusterTime:e[_],s:{bson:e.bson,pool:{write:E.bind(e),isConnected:()=>!0}}};return e[C]&&(t.autoEncrypter=e[C]),t}function E(e,t,n){"function"==typeof t&&(n=t),t=t||{};const r={requestId:e.requestId,cb:n,session:t.session,fullResult:"boolean"==typeof t.fullResult&&t.fullResult,noResponse:"boolean"==typeof t.noResponse&&t.noResponse,documentsReturnedIn:t.documentsReturnedIn,command:!!t.command,promoteLongs:"boolean"!=typeof t.promoteLongs||t.promoteLongs,promoteValues:"boolean"!=typeof t.promoteValues||t.promoteValues,promoteBuffers:"boolean"==typeof t.promoteBuffers&&t.promoteBuffers,raw:"boolean"==typeof t.raw&&t.raw};this[O]&&this[O].compressor&&(r.agreedCompressor=this[O].compressor,this[O].zlibCompressionLevel&&(r.zlibCompressionLevel=this[O].zlibCompressionLevel)),"number"==typeof t.socketTimeout&&(r.socketTimeoutOverride=!0,this[y].setTimeout(t.socketTimeout)),this.monitorCommands&&(this.emit("commandStarted",new p.CommandStartedEvent(this,e)),r.started=m(),r.cb=(t,o)=>{t?this.emit("commandFailed",new p.CommandFailedEvent(this,e,t,r.started)):o&&o.result&&(0===o.result.ok||o.result.$err)?this.emit("commandFailed",new p.CommandFailedEvent(this,e,o.result,r.started)):this.emit("commandSucceeded",new p.CommandSucceededEvent(this,e,o,r.started)),"function"==typeof n&&n(t,o)}),r.noResponse||this[b].set(r.requestId,r);try{this[v].writeCommand(e,r)}catch(e){if(!r.noResponse)return this[b].delete(r.requestId),void r.cb(e)}r.noResponse&&r.cb()}e.exports={Connection:class extends r{constructor(e,t){var n;super(t),this.id=t.id,this.address=function(e){if("function"==typeof e.address)return`${e.remoteAddress}:${e.remotePort}`;return h().toString("hex")}(e),this.bson=t.bson,this.socketTimeout="number"==typeof t.socketTimeout?t.socketTimeout:0,this.host=t.host||"localhost",this.port=t.port||27017,this.monitorCommands="boolean"==typeof t.monitorCommands&&t.monitorCommands,this.closed=!1,this.destroyed=!1,this[O]=new l(this.address,t),this[S]=t.generation,this[w]=m(),t.autoEncrypter&&(this[C]=t.autoEncrypter),this[b]=new Map,this[v]=new o(t),this[v].on("message",(n=this,function(e){if(n.emit("message",e),!n[b].has(e.responseTo))return;const t=n[b].get(e.responseTo),r=t.cb;n[b].delete(e.responseTo),e.moreToCome?n[b].set(e.requestId,t):t.socketTimeoutOverride&&n[y].setTimeout(n.socketTimeout);try{e.parse(t)}catch(e){return void r(new i(e))}if(e.documents[0]){const o=e.documents[0],s=t.session;if(s&&d(s,o),o.$clusterTime&&(n[_]=o.$clusterTime,n.emit("clusterTimeReceived",o.$clusterTime)),t.command){if(o.writeConcernError)return void r(new c(o.writeConcernError,o));if(0===o.ok||o.$err||o.errmsg||o.code)return void r(new i(o))}}r(void 0,new u(t.fullResult?e:e.documents[0],n,e))})),this[y]=e,e.on("error",()=>{}),e.on("close",()=>{this.closed||(this.closed=!0,this[b].forEach(e=>e.cb(new s(`connection ${this.id} to ${this.address} closed`))),this[b].clear(),this.emit("close"))}),e.on("timeout",()=>{this.closed||(e.destroy(),this.closed=!0,this[b].forEach(e=>e.cb(new a(`connection ${this.id} to ${this.address} timed out`,{beforeHandshake:null==this[T]}))),this[b].clear(),this.emit("close"))}),e.pipe(this[v]),this[v].pipe(e)}get description(){return this[O]}get ismaster(){return this[T]}set ismaster(e){this[O].receiveResponse(e),this[T]=e}get generation(){return this[S]||0}get idleTime(){return g(this[w])}get clusterTime(){return this[_]}get stream(){return this[y]}markAvailable(){this[w]=m()}destroy(e,t){return"function"==typeof e&&(t=e,e={}),e=Object.assign({force:!1},e),null==this[y]||this.destroyed?(this.destroyed=!0,void("function"==typeof t&&t())):e.force?(this[y].destroy(),this.destroyed=!0,void("function"==typeof t&&t())):void this[y].end(e=>{this.destroyed=!0,"function"==typeof t&&t(e)})}command(e,t,n,r){f.command(x(this),e,t,n,r)}query(e,t,n,r,o){f.query(x(this),e,t,n,r,o)}getMore(e,t,n,r,o){f.getMore(x(this),e,t,n,r,o)}killCursors(e,t,n){f.killCursors(x(this),e,t,n)}insert(e,t,n,r){f.insert(x(this),e,t,n,r)}update(e,t,n,r){f.update(x(this),e,t,n,r)}remove(e,t,n,r){f.remove(x(this),e,t,n,r)}}}},function(e,t,n){"use strict";var r=n(435).Duplex,o=n(5),i=n(22).Buffer;function s(e){if(!(this instanceof s))return new s(e);if(this._bufs=[],this.length=0,"function"==typeof e){this._callback=e;var t=function(e){this._callback&&(this._callback(e),this._callback=null)}.bind(this);this.on("pipe",(function(e){e.on("error",t)})),this.on("unpipe",(function(e){e.removeListener("error",t)}))}else this.append(e);r.call(this)}o.inherits(s,r),s.prototype._offset=function(e){var t,n=0,r=0;if(0===e)return[0,0];for(;r<this._bufs.length;r++){if(e<(t=n+this._bufs[r].length)||r==this._bufs.length-1)return[r,e-n];n=t}},s.prototype._reverseOffset=function(e){for(var t=e[0],n=e[1],r=0;r<t;r++)n+=this._bufs[r].length;return n},s.prototype.append=function(e){var t=0;if(i.isBuffer(e))this._appendBuffer(e);else if(Array.isArray(e))for(;t<e.length;t++)this.append(e[t]);else if(e instanceof s)for(;t<e._bufs.length;t++)this.append(e._bufs[t]);else null!=e&&("number"==typeof e&&(e=e.toString()),this._appendBuffer(i.from(e)));return this},s.prototype._appendBuffer=function(e){this._bufs.push(e),this.length+=e.length},s.prototype._write=function(e,t,n){this._appendBuffer(e),"function"==typeof n&&n()},s.prototype._read=function(e){if(!this.length)return this.push(null);e=Math.min(e,this.length),this.push(this.slice(0,e)),this.consume(e)},s.prototype.end=function(e){r.prototype.end.call(this,e),this._callback&&(this._callback(null,this.slice()),this._callback=null)},s.prototype.get=function(e){if(!(e>this.length||e<0)){var t=this._offset(e);return this._bufs[t[0]][t[1]]}},s.prototype.slice=function(e,t){return"number"==typeof e&&e<0&&(e+=this.length),"number"==typeof t&&t<0&&(t+=this.length),this.copy(null,0,e,t)},s.prototype.copy=function(e,t,n,r){if(("number"!=typeof n||n<0)&&(n=0),("number"!=typeof r||r>this.length)&&(r=this.length),n>=this.length)return e||i.alloc(0);if(r<=0)return e||i.alloc(0);var o,s,a=!!e,c=this._offset(n),u=r-n,l=u,f=a&&t||0,p=c[1];if(0===n&&r==this.length){if(!a)return 1===this._bufs.length?this._bufs[0]:i.concat(this._bufs,this.length);for(s=0;s<this._bufs.length;s++)this._bufs[s].copy(e,f),f+=this._bufs[s].length;return e}if(l<=this._bufs[c[0]].length-p)return a?this._bufs[c[0]].copy(e,t,p,p+l):this._bufs[c[0]].slice(p,p+l);for(a||(e=i.allocUnsafe(u)),s=c[0];s<this._bufs.length;s++){if(!(l>(o=this._bufs[s].length-p))){this._bufs[s].copy(e,f,p,p+l),f+=o;break}this._bufs[s].copy(e,f,p),f+=o,l-=o,p&&(p=0)}return e.length>f?e.slice(0,f):e},s.prototype.shallowSlice=function(e,t){if(e=e||0,t="number"!=typeof t?this.length:t,e<0&&(e+=this.length),t<0&&(t+=this.length),e===t)return new s;var n=this._offset(e),r=this._offset(t),o=this._bufs.slice(n[0],r[0]+1);return 0==r[1]?o.pop():o[o.length-1]=o[o.length-1].slice(0,r[1]),0!=n[1]&&(o[0]=o[0].slice(n[1])),new s(o)},s.prototype.toString=function(e,t,n){return this.slice(t,n).toString(e)},s.prototype.consume=function(e){if(e=Math.trunc(e),Number.isNaN(e)||e<=0)return this;for(;this._bufs.length;){if(!(e>=this._bufs[0].length)){this._bufs[0]=this._bufs[0].slice(e),this.length-=e;break}e-=this._bufs[0].length,this.length-=this._bufs[0].length,this._bufs.shift()}return this},s.prototype.duplicate=function(){for(var e=0,t=new s;e<this._bufs.length;e++)t.append(this._bufs[e]);return t},s.prototype.destroy=function(){this._bufs.length=0,this.length=0,this.push(null)},s.prototype.indexOf=function(e,t,n){if(void 0===n&&"string"==typeof t&&(n=t,t=void 0),"function"==typeof e||Array.isArray(e))throw new TypeError('The "value" argument must be one of type string, Buffer, BufferList, or Uint8Array.');if("number"==typeof e?e=i.from([e]):"string"==typeof e?e=i.from(e,n):e instanceof s?e=e.slice():i.isBuffer(e)||(e=i.from(e)),t=Number(t||0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),0===e.length)return t>this.length?this.length:t;for(var r=this._offset(t),o=r[0],a=r[1];o<this._bufs.length;o++){for(var c=this._bufs[o];a<c.length;){if(c.length-a>=e.length){var u=c.indexOf(e,a);if(-1!==u)return this._reverseOffset([o,u]);a=c.length-e.length+1}else{var l=this._reverseOffset([o,a]);if(this._match(l,e))return l;a++}}a=0}return-1},s.prototype._match=function(e,t){if(this.length-e<t.length)return!1;for(var n=0;n<t.length;n++)if(this.get(e+n)!==t[n])return!1;return!0},function(){var e={readDoubleBE:8,readDoubleLE:8,readFloatBE:4,readFloatLE:4,readInt32BE:4,readInt32LE:4,readUInt32BE:4,readUInt32LE:4,readInt16BE:2,readInt16LE:2,readUInt16BE:2,readUInt16LE:2,readInt8:1,readUInt8:1,readIntBE:null,readIntLE:null,readUIntBE:null,readUIntLE:null};for(var t in e)!function(t){s.prototype[t]=null===e[t]?function(e,n){return this.slice(e,e+n)[t](0,n)}:function(n){return this.slice(n,n+e[t])[t](0)}}(t)}(),e.exports=s},function(e,t,n){"use strict";var r=n(92);e.exports=b;var o,i=n(436);b.ReadableState=y;n(8).EventEmitter;var s=function(e,t){return e.listeners(t).length},a=n(204),c=n(93).Buffer,u=global.Uint8Array||function(){};var l=Object.create(n(57));l.inherits=n(58);var f=n(5),p=void 0;p=f&&f.debuglog?f.debuglog("stream"):function(){};var d,h=n(438),m=n(205);l.inherits(b,a);var g=["error","close","destroy","pause","resume"];function y(e,t){e=e||{};var r=t instanceof(o=o||n(47));this.objectMode=!!e.objectMode,r&&(this.objectMode=this.objectMode||!!e.readableObjectMode);var i=e.highWaterMark,s=e.readableHighWaterMark,a=this.objectMode?16:16384;this.highWaterMark=i||0===i?i:r&&(s||0===s)?s:a,this.highWaterMark=Math.floor(this.highWaterMark),this.buffer=new h,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.destroyed=!1,this.defaultEncoding=e.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,e.encoding&&(d||(d=n(207).StringDecoder),this.decoder=new d(e.encoding),this.encoding=e.encoding)}function b(e){if(o=o||n(47),!(this instanceof b))return new b(e);this._readableState=new y(e,this),this.readable=!0,e&&("function"==typeof e.read&&(this._read=e.read),"function"==typeof e.destroy&&(this._destroy=e.destroy)),a.call(this)}function v(e,t,n,r,o){var i,s=e._readableState;null===t?(s.reading=!1,function(e,t){if(t.ended)return;if(t.decoder){var n=t.decoder.end();n&&n.length&&(t.buffer.push(n),t.length+=t.objectMode?1:n.length)}t.ended=!0,_(e)}(e,s)):(o||(i=function(e,t){var n;r=t,c.isBuffer(r)||r instanceof u||"string"==typeof t||void 0===t||e.objectMode||(n=new TypeError("Invalid non-string/buffer chunk"));var r;return n}(s,t)),i?e.emit("error",i):s.objectMode||t&&t.length>0?("string"==typeof t||s.objectMode||Object.getPrototypeOf(t)===c.prototype||(t=function(e){return c.from(e)}(t)),r?s.endEmitted?e.emit("error",new Error("stream.unshift() after end event")):S(e,s,t,!0):s.ended?e.emit("error",new Error("stream.push() after EOF")):(s.reading=!1,s.decoder&&!n?(t=s.decoder.write(t),s.objectMode||0!==t.length?S(e,s,t,!1):T(e,s)):S(e,s,t,!1))):r||(s.reading=!1));return function(e){return!e.ended&&(e.needReadable||e.length<e.highWaterMark||0===e.length)}(s)}function S(e,t,n,r){t.flowing&&0===t.length&&!t.sync?(e.emit("data",n),e.read(0)):(t.length+=t.objectMode?1:n.length,r?t.buffer.unshift(n):t.buffer.push(n),t.needReadable&&_(e)),T(e,t)}Object.defineProperty(b.prototype,"destroyed",{get:function(){return void 0!==this._readableState&&this._readableState.destroyed},set:function(e){this._readableState&&(this._readableState.destroyed=e)}}),b.prototype.destroy=m.destroy,b.prototype._undestroy=m.undestroy,b.prototype._destroy=function(e,t){this.push(null),t(e)},b.prototype.push=function(e,t){var n,r=this._readableState;return r.objectMode?n=!0:"string"==typeof e&&((t=t||r.defaultEncoding)!==r.encoding&&(e=c.from(e,t),t=""),n=!0),v(this,e,t,!1,n)},b.prototype.unshift=function(e){return v(this,e,null,!0,!1)},b.prototype.isPaused=function(){return!1===this._readableState.flowing},b.prototype.setEncoding=function(e){return d||(d=n(207).StringDecoder),this._readableState.decoder=new d(e),this._readableState.encoding=e,this};function w(e,t){return e<=0||0===t.length&&t.ended?0:t.objectMode?1:e!=e?t.flowing&&t.length?t.buffer.head.data.length:t.length:(e>t.highWaterMark&&(t.highWaterMark=function(e){return e>=8388608?e=8388608:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function _(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(p("emitReadable",t.flowing),t.emittedReadable=!0,t.sync?r.nextTick(O,e):O(e))}function O(e){p("emit readable"),e.emit("readable"),N(e)}function T(e,t){t.readingMore||(t.readingMore=!0,r.nextTick(C,e,t))}function C(e,t){for(var n=t.length;!t.reading&&!t.flowing&&!t.ended&&t.length<t.highWaterMark&&(p("maybeReadMore read 0"),e.read(0),n!==t.length);)n=t.length;t.readingMore=!1}function x(e){p("readable nexttick read 0"),e.read(0)}function E(e,t){t.reading||(p("resume read 0"),e.read(0)),t.resumeScheduled=!1,t.awaitDrain=0,e.emit("resume"),N(e),t.flowing&&!t.reading&&e.read(0)}function N(e){var t=e._readableState;for(p("flow",t.flowing);t.flowing&&null!==e.read(););}function I(e,t){return 0===t.length?null:(t.objectMode?n=t.buffer.shift():!e||e>=t.length?(n=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.head.data:t.buffer.concat(t.length),t.buffer.clear()):n=function(e,t,n){var r;e<t.head.data.length?(r=t.head.data.slice(0,e),t.head.data=t.head.data.slice(e)):r=e===t.head.data.length?t.shift():n?function(e,t){var n=t.head,r=1,o=n.data;e-=o.length;for(;n=n.next;){var i=n.data,s=e>i.length?i.length:e;if(s===i.length?o+=i:o+=i.slice(0,e),0===(e-=s)){s===i.length?(++r,n.next?t.head=n.next:t.head=t.tail=null):(t.head=n,n.data=i.slice(s));break}++r}return t.length-=r,o}(e,t):function(e,t){var n=c.allocUnsafe(e),r=t.head,o=1;r.data.copy(n),e-=r.data.length;for(;r=r.next;){var i=r.data,s=e>i.length?i.length:e;if(i.copy(n,n.length-e,0,s),0===(e-=s)){s===i.length?(++o,r.next?t.head=r.next:t.head=t.tail=null):(t.head=r,r.data=i.slice(s));break}++o}return t.length-=o,n}(e,t);return r}(e,t.buffer,t.decoder),n);var n}function A(e){var t=e._readableState;if(t.length>0)throw new Error('"endReadable()" called on non-empty stream');t.endEmitted||(t.ended=!0,r.nextTick(k,t,e))}function k(e,t){e.endEmitted||0!==e.length||(e.endEmitted=!0,t.readable=!1,t.emit("end"))}function M(e,t){for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1}b.prototype.read=function(e){p("read",e),e=parseInt(e,10);var t=this._readableState,n=e;if(0!==e&&(t.emittedReadable=!1),0===e&&t.needReadable&&(t.length>=t.highWaterMark||t.ended))return p("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?A(this):_(this),null;if(0===(e=w(e,t))&&t.ended)return 0===t.length&&A(this),null;var r,o=t.needReadable;return p("need readable",o),(0===t.length||t.length-e<t.highWaterMark)&&p("length less than watermark",o=!0),t.ended||t.reading?p("reading or ended",o=!1):o&&(p("do read"),t.reading=!0,t.sync=!0,0===t.length&&(t.needReadable=!0),this._read(t.highWaterMark),t.sync=!1,t.reading||(e=w(n,t))),null===(r=e>0?I(e,t):null)?(t.needReadable=!0,e=0):t.length-=e,0===t.length&&(t.ended||(t.needReadable=!0),n!==e&&t.ended&&A(this)),null!==r&&this.emit("data",r),r},b.prototype._read=function(e){this.emit("error",new Error("_read() is not implemented"))},b.prototype.pipe=function(e,t){var n=this,o=this._readableState;switch(o.pipesCount){case 0:o.pipes=e;break;case 1:o.pipes=[o.pipes,e];break;default:o.pipes.push(e)}o.pipesCount+=1,p("pipe count=%d opts=%j",o.pipesCount,t);var a=(!t||!1!==t.end)&&e!==process.stdout&&e!==process.stderr?u:b;function c(t,r){p("onunpipe"),t===n&&r&&!1===r.hasUnpiped&&(r.hasUnpiped=!0,p("cleanup"),e.removeListener("close",g),e.removeListener("finish",y),e.removeListener("drain",l),e.removeListener("error",m),e.removeListener("unpipe",c),n.removeListener("end",u),n.removeListener("end",b),n.removeListener("data",h),f=!0,!o.awaitDrain||e._writableState&&!e._writableState.needDrain||l())}function u(){p("onend"),e.end()}o.endEmitted?r.nextTick(a):n.once("end",a),e.on("unpipe",c);var l=function(e){return function(){var t=e._readableState;p("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,0===t.awaitDrain&&s(e,"data")&&(t.flowing=!0,N(e))}}(n);e.on("drain",l);var f=!1;var d=!1;function h(t){p("ondata"),d=!1,!1!==e.write(t)||d||((1===o.pipesCount&&o.pipes===e||o.pipesCount>1&&-1!==M(o.pipes,e))&&!f&&(p("false write response, pause",n._readableState.awaitDrain),n._readableState.awaitDrain++,d=!0),n.pause())}function m(t){p("onerror",t),b(),e.removeListener("error",m),0===s(e,"error")&&e.emit("error",t)}function g(){e.removeListener("finish",y),b()}function y(){p("onfinish"),e.removeListener("close",g),b()}function b(){p("unpipe"),n.unpipe(e)}return n.on("data",h),function(e,t,n){if("function"==typeof e.prependListener)return e.prependListener(t,n);e._events&&e._events[t]?i(e._events[t])?e._events[t].unshift(n):e._events[t]=[n,e._events[t]]:e.on(t,n)}(e,"error",m),e.once("close",g),e.once("finish",y),e.emit("pipe",n),o.flowing||(p("pipe resume"),n.resume()),e},b.prototype.unpipe=function(e){var t=this._readableState,n={hasUnpiped:!1};if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes?this:(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this,n),this);if(!e){var r=t.pipes,o=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var i=0;i<o;i++)r[i].emit("unpipe",this,n);return this}var s=M(t.pipes,e);return-1===s?this:(t.pipes.splice(s,1),t.pipesCount-=1,1===t.pipesCount&&(t.pipes=t.pipes[0]),e.emit("unpipe",this,n),this)},b.prototype.on=function(e,t){var n=a.prototype.on.call(this,e,t);if("data"===e)!1!==this._readableState.flowing&&this.resume();else if("readable"===e){var o=this._readableState;o.endEmitted||o.readableListening||(o.readableListening=o.needReadable=!0,o.emittedReadable=!1,o.reading?o.length&&_(this):r.nextTick(x,this))}return n},b.prototype.addListener=b.prototype.on,b.prototype.resume=function(){var e=this._readableState;return e.flowing||(p("resume"),e.flowing=!0,function(e,t){t.resumeScheduled||(t.resumeScheduled=!0,r.nextTick(E,e,t))}(this,e)),this},b.prototype.pause=function(){return p("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(p("pause"),this._readableState.flowing=!1,this.emit("pause")),this},b.prototype.wrap=function(e){var t=this,n=this._readableState,r=!1;for(var o in e.on("end",(function(){if(p("wrapped end"),n.decoder&&!n.ended){var e=n.decoder.end();e&&e.length&&t.push(e)}t.push(null)})),e.on("data",(function(o){(p("wrapped data"),n.decoder&&(o=n.decoder.write(o)),n.objectMode&&null==o)||(n.objectMode||o&&o.length)&&(t.push(o)||(r=!0,e.pause()))})),e)void 0===this[o]&&"function"==typeof e[o]&&(this[o]=function(t){return function(){return e[t].apply(e,arguments)}}(o));for(var i=0;i<g.length;i++)e.on(g[i],this.emit.bind(this,g[i]));return this._read=function(t){p("wrapped _read",t),r&&(r=!1,e.resume())},this},Object.defineProperty(b.prototype,"readableHighWaterMark",{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),b._fromList=I},function(e,t,n){e.exports=n(18)},function(e,t,n){"use strict";var r=n(92);function o(e,t){e.emit("error",t)}e.exports={destroy:function(e,t){var n=this,i=this._readableState&&this._readableState.destroyed,s=this._writableState&&this._writableState.destroyed;return i||s?(t?t(e):!e||this._writableState&&this._writableState.errorEmitted||r.nextTick(o,this,e),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(e||null,(function(e){!t&&e?(r.nextTick(o,n,e),n._writableState&&(n._writableState.errorEmitted=!0)):t&&t(e)})),this)},undestroy:function(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}}},function(e,t,n){"use strict";var r=n(92);function o(e){var t=this;this.next=null,this.entry=null,this.finish=function(){!function(e,t,n){var r=e.entry;e.entry=null;for(;r;){var o=r.callback;t.pendingcb--,o(n),r=r.next}t.corkedRequestsFree?t.corkedRequestsFree.next=e:t.corkedRequestsFree=e}(t,e)}}e.exports=g;var i,s=!process.browser&&["v0.10","v0.9."].indexOf(process.version.slice(0,5))>-1?setImmediate:r.nextTick;g.WritableState=m;var a=Object.create(n(57));a.inherits=n(58);var c={deprecate:n(439)},u=n(204),l=n(93).Buffer,f=global.Uint8Array||function(){};var p,d=n(205);function h(){}function m(e,t){i=i||n(47),e=e||{};var a=t instanceof i;this.objectMode=!!e.objectMode,a&&(this.objectMode=this.objectMode||!!e.writableObjectMode);var c=e.highWaterMark,u=e.writableHighWaterMark,l=this.objectMode?16:16384;this.highWaterMark=c||0===c?c:a&&(u||0===u)?u:l,this.highWaterMark=Math.floor(this.highWaterMark),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var f=!1===e.decodeStrings;this.decodeStrings=!f,this.defaultEncoding=e.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){!function(e,t){var n=e._writableState,o=n.sync,i=n.writecb;if(function(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}(n),t)!function(e,t,n,o,i){--t.pendingcb,n?(r.nextTick(i,o),r.nextTick(_,e,t),e._writableState.errorEmitted=!0,e.emit("error",o)):(i(o),e._writableState.errorEmitted=!0,e.emit("error",o),_(e,t))}(e,n,o,t,i);else{var a=S(n);a||n.corked||n.bufferProcessing||!n.bufferedRequest||v(e,n),o?s(b,e,n,a,i):b(e,n,a,i)}}(t,e)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.bufferedRequestCount=0,this.corkedRequestsFree=new o(this)}function g(e){if(i=i||n(47),!(p.call(g,this)||this instanceof i))return new g(e);this._writableState=new m(e,this),this.writable=!0,e&&("function"==typeof e.write&&(this._write=e.write),"function"==typeof e.writev&&(this._writev=e.writev),"function"==typeof e.destroy&&(this._destroy=e.destroy),"function"==typeof e.final&&(this._final=e.final)),u.call(this)}function y(e,t,n,r,o,i,s){t.writelen=r,t.writecb=s,t.writing=!0,t.sync=!0,n?e._writev(o,t.onwrite):e._write(o,i,t.onwrite),t.sync=!1}function b(e,t,n,r){n||function(e,t){0===t.length&&t.needDrain&&(t.needDrain=!1,e.emit("drain"))}(e,t),t.pendingcb--,r(),_(e,t)}function v(e,t){t.bufferProcessing=!0;var n=t.bufferedRequest;if(e._writev&&n&&n.next){var r=t.bufferedRequestCount,i=new Array(r),s=t.corkedRequestsFree;s.entry=n;for(var a=0,c=!0;n;)i[a]=n,n.isBuf||(c=!1),n=n.next,a+=1;i.allBuffers=c,y(e,t,!0,t.length,i,"",s.finish),t.pendingcb++,t.lastBufferedRequest=null,s.next?(t.corkedRequestsFree=s.next,s.next=null):t.corkedRequestsFree=new o(t),t.bufferedRequestCount=0}else{for(;n;){var u=n.chunk,l=n.encoding,f=n.callback;if(y(e,t,!1,t.objectMode?1:u.length,u,l,f),n=n.next,t.bufferedRequestCount--,t.writing)break}null===n&&(t.lastBufferedRequest=null)}t.bufferedRequest=n,t.bufferProcessing=!1}function S(e){return e.ending&&0===e.length&&null===e.bufferedRequest&&!e.finished&&!e.writing}function w(e,t){e._final((function(n){t.pendingcb--,n&&e.emit("error",n),t.prefinished=!0,e.emit("prefinish"),_(e,t)}))}function _(e,t){var n=S(t);return n&&(!function(e,t){t.prefinished||t.finalCalled||("function"==typeof e._final?(t.pendingcb++,t.finalCalled=!0,r.nextTick(w,e,t)):(t.prefinished=!0,e.emit("prefinish")))}(e,t),0===t.pendingcb&&(t.finished=!0,e.emit("finish"))),n}a.inherits(g,u),m.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},function(){try{Object.defineProperty(m.prototype,"buffer",{get:c.deprecate((function(){return this.getBuffer()}),"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(e){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(p=Function.prototype[Symbol.hasInstance],Object.defineProperty(g,Symbol.hasInstance,{value:function(e){return!!p.call(this,e)||this===g&&(e&&e._writableState instanceof m)}})):p=function(e){return e instanceof this},g.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},g.prototype.write=function(e,t,n){var o,i=this._writableState,s=!1,a=!i.objectMode&&(o=e,l.isBuffer(o)||o instanceof f);return a&&!l.isBuffer(e)&&(e=function(e){return l.from(e)}(e)),"function"==typeof t&&(n=t,t=null),a?t="buffer":t||(t=i.defaultEncoding),"function"!=typeof n&&(n=h),i.ended?function(e,t){var n=new Error("write after end");e.emit("error",n),r.nextTick(t,n)}(this,n):(a||function(e,t,n,o){var i=!0,s=!1;return null===n?s=new TypeError("May not write null values to stream"):"string"==typeof n||void 0===n||t.objectMode||(s=new TypeError("Invalid non-string/buffer chunk")),s&&(e.emit("error",s),r.nextTick(o,s),i=!1),i}(this,i,e,n))&&(i.pendingcb++,s=function(e,t,n,r,o,i){if(!n){var s=function(e,t,n){e.objectMode||!1===e.decodeStrings||"string"!=typeof t||(t=l.from(t,n));return t}(t,r,o);r!==s&&(n=!0,o="buffer",r=s)}var a=t.objectMode?1:r.length;t.length+=a;var c=t.length<t.highWaterMark;c||(t.needDrain=!0);if(t.writing||t.corked){var u=t.lastBufferedRequest;t.lastBufferedRequest={chunk:r,encoding:o,isBuf:n,callback:i,next:null},u?u.next=t.lastBufferedRequest:t.bufferedRequest=t.lastBufferedRequest,t.bufferedRequestCount+=1}else y(e,t,!1,a,r,o,i);return c}(this,i,a,e,t,n)),s},g.prototype.cork=function(){this._writableState.corked++},g.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,e.writing||e.corked||e.finished||e.bufferProcessing||!e.bufferedRequest||v(this,e))},g.prototype.setDefaultEncoding=function(e){if("string"==typeof e&&(e=e.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+e);return this._writableState.defaultEncoding=e,this},Object.defineProperty(g.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),g.prototype._write=function(e,t,n){n(new Error("_write() is not implemented"))},g.prototype._writev=null,g.prototype.end=function(e,t,n){var o=this._writableState;"function"==typeof e?(n=e,e=null,t=null):"function"==typeof t&&(n=t,t=null),null!=e&&this.write(e,t),o.corked&&(o.corked=1,this.uncork()),o.ending||o.finished||function(e,t,n){t.ending=!0,_(e,t),n&&(t.finished?r.nextTick(n):e.once("finish",n));t.ended=!0,e.writable=!1}(this,o,n)},Object.defineProperty(g.prototype,"destroyed",{get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),g.prototype.destroy=d.destroy,g.prototype._undestroy=d.undestroy,g.prototype._destroy=function(e,t){this.end(),t(e)}},function(e,t,n){"use strict";var r=n(93).Buffer,o=r.isEncoding||function(e){switch((e=""+e)&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function i(e){var t;switch(this.encoding=function(e){var t=function(e){if(!e)return"utf8";for(var t;;)switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=!0}}(e);if("string"!=typeof t&&(r.isEncoding===o||!o(e)))throw new Error("Unknown encoding: "+e);return t||e}(e),this.encoding){case"utf16le":this.text=c,this.end=u,t=4;break;case"utf8":this.fillLast=a,t=4;break;case"base64":this.text=l,this.end=f,t=3;break;default:return this.write=p,void(this.end=d)}this.lastNeed=0,this.lastTotal=0,this.lastChar=r.allocUnsafe(t)}function s(e){return e<=127?0:e>>5==6?2:e>>4==14?3:e>>3==30?4:e>>6==2?-1:-2}function a(e){var t=this.lastTotal-this.lastNeed,n=function(e,t,n){if(128!=(192&t[0]))return e.lastNeed=0,"�";if(e.lastNeed>1&&t.length>1){if(128!=(192&t[1]))return e.lastNeed=1,"�";if(e.lastNeed>2&&t.length>2&&128!=(192&t[2]))return e.lastNeed=2,"�"}}(this,e);return void 0!==n?n:this.lastNeed<=e.length?(e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(e.copy(this.lastChar,t,0,e.length),void(this.lastNeed-=e.length))}function c(e,t){if((e.length-t)%2==0){var n=e.toString("utf16le",t);if(n){var r=n.charCodeAt(n.length-1);if(r>=55296&&r<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],n.slice(0,-1)}return n}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function u(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var n=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,n)}return t}function l(e,t){var n=(e.length-t)%3;return 0===n?e.toString("base64",t):(this.lastNeed=3-n,this.lastTotal=3,1===n?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-n))}function f(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function p(e){return e.toString(this.encoding)}function d(e){return e&&e.length?this.write(e):""}t.StringDecoder=i,i.prototype.write=function(e){if(0===e.length)return"";var t,n;if(this.lastNeed){if(void 0===(t=this.fillLast(e)))return"";n=this.lastNeed,this.lastNeed=0}else n=0;return n<e.length?t?t+this.text(e,n):this.text(e,n):t||""},i.prototype.end=function(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+"�":t},i.prototype.text=function(e,t){var n=function(e,t,n){var r=t.length-1;if(r<n)return 0;var o=s(t[r]);if(o>=0)return o>0&&(e.lastNeed=o-1),o;if(--r<n||-2===o)return 0;if((o=s(t[r]))>=0)return o>0&&(e.lastNeed=o-2),o;if(--r<n||-2===o)return 0;if((o=s(t[r]))>=0)return o>0&&(2===o?o=0:e.lastNeed=o-3),o;return 0}(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=n;var r=e.length-(n-this.lastNeed);return e.copy(this.lastChar,0,r),e.toString("utf8",t,r)},i.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length}},function(e,t,n){"use strict";e.exports=s;var r=n(47),o=Object.create(n(57));function i(e,t){var n=this._transformState;n.transforming=!1;var r=n.writecb;if(!r)return this.emit("error",new Error("write callback called multiple times"));n.writechunk=null,n.writecb=null,null!=t&&this.push(t),r(e);var o=this._readableState;o.reading=!1,(o.needReadable||o.length<o.highWaterMark)&&this._read(o.highWaterMark)}function s(e){if(!(this instanceof s))return new s(e);r.call(this,e),this._transformState={afterTransform:i.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=!0,this._readableState.sync=!1,e&&("function"==typeof e.transform&&(this._transform=e.transform),"function"==typeof e.flush&&(this._flush=e.flush)),this.on("prefinish",a)}function a(){var e=this;"function"==typeof this._flush?this._flush((function(t,n){c(e,t,n)})):c(this,null,null)}function c(e,t,n){if(t)return e.emit("error",t);if(null!=n&&e.push(n),e._writableState.length)throw new Error("Calling transform done when ws.length != 0");if(e._transformState.transforming)throw new Error("Calling transform done when still transforming");return e.push(null)}o.inherits=n(58),o.inherits(s,r),s.prototype.push=function(e,t){return this._transformState.needTransform=!1,r.prototype.push.call(this,e,t)},s.prototype._transform=function(e,t,n){throw new Error("_transform() is not implemented")},s.prototype._write=function(e,t,n){var r=this._transformState;if(r.writecb=n,r.writechunk=e,r.writeencoding=t,!r.transforming){var o=this._readableState;(r.needTransform||o.needReadable||o.length<o.highWaterMark)&&this._read(o.highWaterMark)}},s.prototype._read=function(e){var t=this._transformState;null!==t.writechunk&&t.writecb&&!t.transforming?(t.transforming=!0,this._transform(t.writechunk,t.writeencoding,t.afterTransform)):t.needTransform=!0},s.prototype._destroy=function(e,t){var n=this;r.prototype._destroy.call(this,e,(function(e){t(e),n.emit("close")}))}},function(e,t,n){"use strict";const r=n(0).applyRetryableWrites,o=n(0).applyWriteConcern,i=n(2).MongoError,s=n(1).OperationBase;e.exports=class extends s{constructor(e,t,n){super(n),this.collection=e,this.operations=t}execute(e){const t=this.collection,n=this.operations;let s=this.options;t.s.options.ignoreUndefined&&(s=Object.assign({},s),s.ignoreUndefined=t.s.options.ignoreUndefined);const a=!0===s.ordered||null==s.ordered?t.initializeOrderedBulkOp(s):t.initializeUnorderedBulkOp(s);let c=!1;try{for(let e=0;e<n.length;e++){const t=Object.keys(n[e])[0];n[e][t].collation&&(c=!0),a.raw(n[e])}}catch(t){return e(t,null)}let u=Object.assign({},s);u=r(u,t.s.db),u=o(u,{db:t.s.db,collection:t},s);const l=u.writeConcern?u.writeConcern:{},f=t.s.topology.capabilities();if(c&&f&&!f.commandsTakeCollation)return e(new i("server/primary/mongos does not support collation"));a.execute(l,u,(t,n)=>{if(!n&&t)return e(t,null);n.insertedCount=n.nInserted,n.matchedCount=n.nMatched,n.modifiedCount=n.nModified||0,n.deletedCount=n.nRemoved,n.upsertedCount=n.getUpsertedIds().length,n.upsertedIds={},n.insertedIds={},n.n=n.insertedCount;const r=n.getInsertedIds();for(let e=0;e<r.length;e++)n.insertedIds[r[e].index]=r[e]._id;const o=n.getUpsertedIds();for(let e=0;e<o.length;e++)n.upsertedIds[o[e].index]=o[e]._id;e(null,n)})}}},function(e,t,n){"use strict";const r=n(1).Aspect,o=n(1).defineAspects,i=n(27),s=n(2).MongoError,a=n(0).parseIndexOptions,c=n(4).maxWireVersion,u=new Set(["background","unique","name","partialFilterExpression","sparse","expireAfterSeconds","storageEngine","collation","weights","default_language","language_override","textIndexVersion","2dsphereIndexVersion","bits","min","max","bucketSize","wildcardProjection"]);class l extends i{constructor(e,t,n,r){if(super(e,r),this.collection=t,Array.isArray(n)&&!Array.isArray(n[0]))this.indexes=n;else{this.onlyReturnNameOfCreatedIndex=!0;const e=a(n),t={name:"string"==typeof r.name?r.name:e.name,key:e.fieldHash};for(let e in r)u.has(e)&&(t[e]=r[e]);this.indexes=[t]}}execute(e,t){const n=this.options,r=this.indexes,o=c(e);for(let n=0;n<r.length;n++){if(r[n].collation&&o<5)return void t(new s(`Server ${e.name}, which reports wire version ${o}, does not support collation`));if(null==r[n].name){const e=[];for(let t in r[n].key)e.push(`${t}_${r[n].key[t]}`);r[n].name=e.join("_")}}const i={createIndexes:this.collection,indexes:r};if(null!=n.commitQuorum){if(o<9)return void t(new s("`commitQuorum` option for `createIndexes` not supported on servers < 4.4"));i.commitQuorum=n.commitQuorum}this.options.collation=void 0,super.executeCommand(e,i,(e,n)=>{e?t(e):t(null,this.onlyReturnNameOfCreatedIndex?r[0].name:n)})}}o(l,[r.WRITE_OPERATION,r.EXECUTE_WITH_SELECTION]),e.exports=l},function(e,t,n){"use strict";const r=n(1).Aspect,o=n(1).defineAspects,i=n(23),s=n(0).applyWriteConcern,a=n(0).handleCallback;class c extends i{constructor(e,t,n){super(e.s.db,n,e),this.collection=e,this.indexName=t}_buildCommand(){const e=this.collection,t=this.indexName,n=this.options;let r={dropIndexes:e.collectionName,index:t};return r=s(r,{db:e.s.db,collection:e},n),r}execute(e){super.execute((t,n)=>{if("function"==typeof e)return t?a(e,t,null):void a(e,null,n)})}}o(c,r.WRITE_OPERATION),e.exports=c},function(e,t,n){"use strict";const r=n(1).OperationBase,o=n(14).indexInformation;e.exports=class extends r{constructor(e,t,n){super(n),this.db=e,this.name=t}execute(e){const t=this.db,n=this.name,r=this.options;o(t,n,r,e)}}},function(e,t,n){"use strict";const r=n(1).OperationBase,o=n(0).handleCallback,i=n(2).MongoError;e.exports=class extends r{constructor(e,t){super(t),this.collection=e}execute(e){const t=this.collection,n=this.options;t.s.db.listCollections({name:t.collectionName},n).toArray((n,r)=>n?o(e,n):0===r.length?o(e,i.create({message:`collection ${t.namespace} not found`,driver:!0})):void o(e,n,r[0].options||null))}}},function(e,t,n){"use strict";const r=n(1).Aspect,o=n(23),i=n(1).defineAspects,s=n(20),a=n(0).handleCallback,c=n(0).toError,u=n(0).emitWarning;class l extends o{constructor(e,t,n,r){super(e,r),this.username=t,this.password=n}_buildCommand(){const e=this.db,t=this.username,n=this.password,r=this.options;let o=[];Array.isArray(r.roles)&&(o=r.roles),"string"==typeof r.roles&&(o=[r.roles]),0===o.length&&u("Creating a user without roles is deprecated in MongoDB >= 2.6"),"admin"!==e.databaseName.toLowerCase()&&"admin"!==r.dbName||Array.isArray(r.roles)?Array.isArray(r.roles)||(o=["dbOwner"]):o=["root"];const i=e.s.topology.lastIsMaster().maxWireVersion>=7;let a=n;if(!i){const e=s.createHash("md5");e.update(t+":mongo:"+n),a=e.digest("hex")}const c={createUser:t,customData:r.customData||{},roles:o,digestPassword:i};return"string"==typeof n&&(c.pwd=a),c}execute(e){if(null!=this.options.digestPassword)return e(c("The digestPassword option is not supported via add_user. Please use db.command('createUser', ...) instead for this option."));super.execute((t,n)=>a(e,t,t?null:n))}}i(l,r.WRITE_OPERATION),e.exports=l},function(e,t,n){"use strict";const r=n(1).OperationBase,o=n(0).handleCallback,i=n(2).MongoError,s=n(0).MongoDBNamespace;e.exports=class extends r{constructor(e,t,n){super(n),this.db=e,this.selector=t}execute(e){const t=this.db,n=this.selector,r=this.options,a=new s("admin","$cmd");t.s.topology.command(a,n,r,(n,r)=>t.serverConfig&&t.serverConfig.isDestroyed()?e(new i("topology was destroyed")):n?o(e,n):void o(e,null,r.result))}}},function(e,t,n){"use strict";const r=n(1).Aspect,o=n(23),i=n(1).defineAspects,s=n(0).handleCallback,a=n(29);class c extends o{constructor(e,t,n){const r={},o=a.fromOptions(n);null!=o&&(r.writeConcern=o),n.dbName&&(r.dbName=n.dbName),"number"==typeof n.maxTimeMS&&(r.maxTimeMS=n.maxTimeMS),super(e,r),this.username=t}_buildCommand(){return{dropUser:this.username}}execute(e){super.execute((t,n)=>{if(t)return s(e,t,null);s(e,t,!!n.ok)})}}i(c,r.WRITE_OPERATION),e.exports=c},function(e,t,n){"use strict";const r=n(1).OperationBase,o=n(0).applyWriteConcern,i=n(0).checkCollectionName,s=n(11).executeDbAdminCommand,a=n(0).handleCallback,c=n(145).loadCollection,u=n(0).toError;e.exports=class extends r{constructor(e,t,n){super(n),this.collection=e,this.newName=t}execute(e){const t=this.collection,n=this.newName,r=this.options;let l=c();i(n);const f={renameCollection:t.namespace,to:t.s.namespace.withCollection(n).toString(),dropTarget:"boolean"==typeof r.dropTarget&&r.dropTarget};o(f,{db:t.s.db,collection:t},r),s(t.s.db.admin().s.db,f,r,(r,o)=>{if(r)return a(e,r,null);if(o.errmsg)return a(e,u(o),null);try{return a(e,null,new l(t.s.db,t.s.topology,t.s.namespace.db,n,t.s.pkFactory,t.s.options))}catch(r){return a(e,u(r),null)}})}}},function(e,t,n){"use strict";const r=n(0).applyWriteConcern,o=n(214),i=n(215),s=n(216),a=n(477),c=n(478),u=n(56);function l(e,t,n){if(!(this instanceof l))return new l(e,t);this.s={db:e,topology:t,promiseLibrary:n}}l.prototype.command=function(e,t,n){const r=Array.prototype.slice.call(arguments,1);n="function"==typeof r[r.length-1]?r.pop():void 0,t=r.length?r.shift():{};const o=new i(this.s.db,e,t);return u(this.s.db.s.topology,o,n)},l.prototype.buildInfo=function(e,t){"function"==typeof e&&(t=e,e={}),e=e||{};const n=new i(this.s.db,{buildinfo:1},e);return u(this.s.db.s.topology,n,t)},l.prototype.serverInfo=function(e,t){"function"==typeof e&&(t=e,e={}),e=e||{};const n=new i(this.s.db,{buildinfo:1},e);return u(this.s.db.s.topology,n,t)},l.prototype.serverStatus=function(e,t){"function"==typeof e&&(t=e,e={}),e=e||{};const n=new i(this.s.db,{serverStatus:1},e);return u(this.s.db.s.topology,n,t)},l.prototype.ping=function(e,t){"function"==typeof e&&(t=e,e={}),e=e||{};const n=new i(this.s.db,{ping:1},e);return u(this.s.db.s.topology,n,t)},l.prototype.addUser=function(e,t,n,i){const s=Array.prototype.slice.call(arguments,2);i="function"==typeof s[s.length-1]?s.pop():void 0,"string"==typeof e&&null!=t&&"object"==typeof t&&(n=t,t=null),n=s.length?s.shift():{},n=Object.assign({},n),(n=r(n,{db:this.s.db})).dbName="admin";const a=new o(this.s.db,e,t,n);return u(this.s.db.s.topology,a,i)},l.prototype.removeUser=function(e,t,n){const o=Array.prototype.slice.call(arguments,1);n="function"==typeof o[o.length-1]?o.pop():void 0,t=o.length?o.shift():{},t=Object.assign({},t),(t=r(t,{db:this.s.db})).dbName="admin";const i=new s(this.s.db,e,t);return u(this.s.db.s.topology,i,n)},l.prototype.validateCollection=function(e,t,n){"function"==typeof t&&(n=t,t={});const r=new a(this,e,t=t||{});return u(this.s.db.s.topology,r,n)},l.prototype.listDatabases=function(e,t){return"function"==typeof e&&(t=e,e={}),e=e||{},u(this.s.db.s.topology,new c(this.s.db,e),t)},l.prototype.replSetGetStatus=function(e,t){"function"==typeof e&&(t=e,e={}),e=e||{};const n=new i(this.s.db,{replSetGetStatus:1},e);return u(this.s.db.s.topology,n,t)},e.exports=l},function(e,t,n){"use strict";const r=n(2).Topology,o=n(35).ServerCapabilities,i=n(26),s=n(0).translateOptions;e.exports=class extends r{constructor(e,t){t=t||{};let n=Object.assign({},{cursorFactory:i,reconnect:!1,emitError:"boolean"!=typeof t.emitError||t.emitError,maxPoolSize:"number"==typeof t.maxPoolSize?t.maxPoolSize:"number"==typeof t.poolSize?t.poolSize:10,minPoolSize:"number"==typeof t.minPoolSize?t.minPoolSize:"number"==typeof t.minSize?t.minSize:0,monitorCommands:"boolean"==typeof t.monitorCommands&&t.monitorCommands});n=s(n,t);var r=t.socketOptions&&Object.keys(t.socketOptions).length>0?t.socketOptions:t;n=s(n,r),super(e,n)}capabilities(){return this.s.sCapabilities?this.s.sCapabilities:null==this.lastIsMaster()?null:(this.s.sCapabilities=new o(this.lastIsMaster()),this.s.sCapabilities)}command(e,t,n,r){super.command(e.toString(),t,n,r)}insert(e,t,n,r){super.insert(e.toString(),t,n,r)}update(e,t,n,r){super.update(e.toString(),t,n,r)}remove(e,t,n,r){super.remove(e.toString(),t,n,r)}}},function(e,t,n){"use strict";const r=n(5).deprecate,o=n(2).Logger,i=n(2).MongoCredentials,s=n(2).MongoError,a=n(221),c=n(219),u=n(2).parseConnectionString,l=n(46),f=n(2).ReadPreference,p=n(222),d=n(99),h=n(2).Sessions.ServerSessionPool,m=n(0).emitDeprecationWarning,g=n(0).emitWarningOnce,y=n(89),b=n(29),v=n(94).CMAP_EVENT_NAMES;let S;const w=r(n(484),"current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect."),_={DEFAULT:"default",PLAIN:"plain",GSSAPI:"gssapi","MONGODB-CR":"mongocr","MONGODB-X509":"x509","MONGODB-AWS":"mongodb-aws","SCRAM-SHA-1":"scram-sha-1","SCRAM-SHA-256":"scram-sha-256"},O=["timeout","close","serverOpening","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","serverClosed","topologyOpening","topologyClosed","topologyDescriptionChanged","commandStarted","commandSucceeded","commandFailed","joined","left","ping","ha","all","fullsetup","open"],T=new Set(["DEFAULT","PLAIN","GSSAPI","MONGODB-CR","MONGODB-X509","MONGODB-AWS","SCRAM-SHA-1","SCRAM-SHA-256"]),C=["poolSize","ssl","sslValidate","sslCA","sslCert","sslKey","sslPass","sslCRL","autoReconnect","noDelay","keepAlive","keepAliveInitialDelay","connectTimeoutMS","family","socketTimeoutMS","reconnectTries","reconnectInterval","ha","haInterval","replicaSet","secondaryAcceptableLatencyMS","acceptableLatencyMS","connectWithNoPrimary","authSource","w","wtimeout","j","writeConcern","forceServerObjectId","serializeFunctions","ignoreUndefined","raw","bufferMaxEntries","readPreference","pkFactory","promiseLibrary","readConcern","maxStalenessSeconds","loggerLevel","logger","promoteValues","promoteBuffers","promoteLongs","domainsEnabled","checkServerIdentity","validateOptions","appname","auth","user","password","authMechanism","compression","fsync","readPreferenceTags","numberOfRetries","auto_reconnect","minSize","monitorCommands","retryWrites","retryReads","useNewUrlParser","useUnifiedTopology","serverSelectionTimeoutMS","useRecoveryToken","autoEncryption","driverInfo","tls","tlsInsecure","tlsinsecure","tlsAllowInvalidCertificates","tlsAllowInvalidHostnames","tlsCAFile","tlsCertificateFile","tlsCertificateKeyFile","tlsCertificateKeyFilePassword","minHeartbeatFrequencyMS","heartbeatFrequencyMS","directConnection","appName","maxPoolSize","minPoolSize","maxIdleTimeMS","waitQueueTimeoutMS"],x=["native_parser"],E=["server","replset","replSet","mongos","db"];const N=C.reduce((e,t)=>(e[t.toLowerCase()]=t,e),{});function I(e,t){t.on("authenticated",M(e,"authenticated")),t.on("error",M(e,"error")),t.on("timeout",M(e,"timeout")),t.on("close",M(e,"close")),t.on("parseError",M(e,"parseError")),t.once("open",M(e,"open")),t.once("fullsetup",M(e,"fullsetup")),t.once("all",M(e,"all")),t.on("reconnect",M(e,"reconnect"))}function A(e,t){e.topology=t,t instanceof c||(t.s.sessionPool=new h(t.s.coreTopology))}function k(e,t){let r=(S||(S=n(59)),S);const o=[];return e instanceof r&&O.forEach(n=>{t.on(n,(t,r)=>{"open"===n?o.push({event:n,object1:e}):o.push({event:n,object1:t,object2:r})})}),o}function M(e,t){const n=new Set(["all","fullsetup","open","reconnect"]);return(r,o)=>{if(n.has(t))return e.emit(t,e);e.emit(t,r,o)}}const R=new Set(["reconnect","reconnectFailed","attemptReconnect","joined","left","ping","ha","all","fullsetup","open"]);function j(e,t,r,o){r.promiseLibrary=e.s.promiseLibrary;const i={};"unified"===t&&(i.createServers=!1);const s=z(r,i);if(null!=r.autoEncryption){const t=n(223).Encrypter;r.encrypter=new t(e,r),r.autoEncrypter=r.encrypter.autoEncrypter}let u;"mongos"===t?u=new a(s,r):"replicaset"===t?u=new p(s,r):"unified"===t&&(u=new c(r.servers,r),function(e){e.on("newListener",e=>{R.has(e)&&m(`The \`${e}\` event is no longer supported by the unified topology, please read more by visiting http://bit.ly/2D8WfT6`,"DeprecationWarning")})}(e)),I(e,u),q(e,u),A(e,u),r.autoEncrypter?r.autoEncrypter.init(e=>{e?o(e):u.connect(r,e=>{if(e)return u.close(!0),void o(e);r.encrypter.connectInternalClient(e=>{if(e)return o(e);o(void 0,u)})})}):u.connect(r,e=>{if(e)return u.close(!0),o(e);o(void 0,u)})}function D(e,t){const n=["mongos","server","db","replset","db_options","server_options","rs_options","mongos_options"],r=["readconcern","compression","autoencryption"],o=["w","wtimeout","j","journal","fsync","writeConcern"];for(const i in t)-1===o.indexOf(i.toLowerCase())&&(-1!==r.indexOf(i.toLowerCase())?e[i]=t[i]:-1!==n.indexOf(i.toLowerCase())?e=L(e,t[i],!1):!t[i]||"object"!=typeof t[i]||Buffer.isBuffer(t[i])||Array.isArray(t[i])?e[i]=t[i]:e=L(e,t[i],!0));const i=b.fromOptions(t);return i&&(e.writeConcern=Object.assign({},e.writeConcern,i)),e}function P(e,t,n,r){const o=(r=Object.assign({},r)).authSource||r.authdb||r.dbName,a=r.authMechanism||"DEFAULT",c=a.toUpperCase(),u=r.authMechanismProperties;if(!T.has(c))throw s.create({message:`authentication mechanism ${a} not supported', options.authMechanism`,driver:!0});return new i({mechanism:_[c],mechanismProperties:u,source:o,username:t,password:n})}function B(e){return L(D({},e),e,!1)}function L(e,t,n){for(const r in t)t[r]&&"object"==typeof t[r]&&n?e=L(e,t[r],n):e[r]=t[r];return e}function q(e,t){["commandStarted","commandSucceeded","commandFailed","serverOpening","serverClosed","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","topologyOpening","topologyClosed","topologyDescriptionChanged","joined","left","ping","ha"].concat(v).forEach(n=>{t.on(n,(t,r)=>{e.emit(n,t,r)})})}function U(e){let t=Object.assign({servers:e.hosts},e.options);for(let e in t){const n=N[e];n&&(t[n]=t[e])}const n=e.auth&&e.auth.username,r=e.options&&e.options.authMechanism;(n||r)&&(t.auth=Object.assign({},e.auth),t.auth.db&&(t.authSource=t.authSource||t.auth.db),t.auth.username&&(t.auth.user=t.auth.username)),e.defaultDatabase&&(t.dbName=e.defaultDatabase),t.maxPoolSize&&(t.poolSize=t.maxPoolSize),t.readConcernLevel&&(t.readConcern=new l(t.readConcernLevel)),t.wTimeoutMS&&(t.wtimeout=t.wTimeoutMS,t.wTimeoutMS=void 0),e.srvHost&&(t.srvHost=e.srvHost);const o=["w","wtimeout","j","journal","fsync"];for(const e of o)void 0!==t[e]&&(void 0===t.writeConcern&&(t.writeConcern={}),t.writeConcern[e]=t[e],t[e]=void 0);return t}function z(e,t){if(t=Object.assign({},{createServers:!0},t),"string"!=typeof e.readPreference&&"string"!=typeof e.read_preference||(e.readPreference=new f(e.readPreference||e.read_preference)),e.readPreference&&(e.readPreferenceTags||e.read_preference_tags)&&(e.readPreference.tags=e.readPreferenceTags||e.read_preference_tags),e.maxStalenessSeconds&&(e.readPreference.maxStalenessSeconds=e.maxStalenessSeconds),null==e.socketTimeoutMS&&(e.socketTimeoutMS=0),null==e.connectTimeoutMS&&(e.connectTimeoutMS=1e4),t.createServers)return e.servers.map(t=>t.domain_socket?new d(t.domain_socket,27017,e):new d(t.host,t.port,e))}e.exports={validOptions:function(e){const t=C.concat(E);for(const n in e)if(-1===x.indexOf(n)){if(-1===t.indexOf(n)){if(e.validateOptions)return new s(`option ${n} is not supported`);g(`the options [${n}] is not supported`)}-1!==E.indexOf(n)&&g("the server/replset/mongos/db options are deprecated, "+`all their options are supported at the top level of the options object [${C}]`)}},connect:function(e,t,n,r){if(n=Object.assign({},n),null==r)throw new Error("no callback function provided");let i=!1;const c=o("MongoClient",n);if(t instanceof d||t instanceof p||t instanceof a)return function(e,t,n,r){A(e,t),I(e,t),q(e,t);let o=Object.assign({},n);"string"!=typeof n.readPreference&&"string"!=typeof n.read_preference||(o.readPreference=new f(n.readPreference||n.read_preference));if((o.user||o.password||o.authMechanism)&&!o.credentials)try{o.credentials=P(e,o.user,o.password,o)}catch(e){return r(e,t)}return t.connect(o,r)}(e,t,n,m);const l=!1!==n.useNewUrlParser,h=l?U:B;function m(t,n){const o="seed list contains no mongos proxies, replicaset connections requires the parameter replicaSet to be supplied in the URI or options object, mongodb://server:port/db?replicaSet=name";if(t&&"no mongos proxies found in seed list"===t.message)return c.isWarn()&&c.warn(o),r(new s(o));i&&e.emit("authenticated",null,!0),r(t,n)}(l?u:w)(t,n,(t,o)=>{if(t)return r(t);const s=h(o),a=D(s,n);if(null==a.socketTimeoutMS&&(a.socketTimeoutMS=0),null==a.connectTimeoutMS&&(a.connectTimeoutMS=1e4),null==a.retryWrites&&(a.retryWrites=!0),null==a.useRecoveryToken&&(a.useRecoveryToken=!0),null==a.readPreference&&(a.readPreference="primary"),a.db_options&&a.db_options.auth&&delete a.db_options.auth,function(e){null!=e.tls&&["sslCA","sslKey","sslCert"].forEach(t=>{e[t]&&(e[t]=y.readFileSync(e[t]))})}(a),e.s.options=a,e.s.readPreference=f.fromOptions(a),e.s.writeConcern=b.fromOptions(a),0===s.servers.length)return r(new Error("connection string must contain at least one seed host"));if(a.auth&&!a.credentials)try{i=!0,a.credentials=P(e,a.auth.user,a.auth.password,a)}catch(t){return r(t)}return a.useUnifiedTopology?j(e,"unified",a,m):(g("Current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor."),a.replicaSet||a.rs_name?j(e,"replicaset",a,m):s.servers.length>1?j(e,"mongos",a,m):function(e,t,n){t.promiseLibrary=e.s.promiseLibrary;const r=z(t)[0],o=k(e,r);r.connect(t,(i,s)=>{if(i)return r.close(!0),n(i);!function(e){O.forEach(t=>e.removeAllListeners(t))}(r),q(e,r),I(e,r);const a=s.lastIsMaster();if(A(e,s),a&&"isdbgrid"===a.msg)return s.close(),j(e,"mongos",t,n);!function(e,t){for(let n=0;n<t.length;n++)e.emit(t[n].event,t[n].object1,t[n].object2)}(e,o),n(i,s)})}(e,a,m))})}}},function(e,t,n){"use strict";const r=n(35).TopologyBase,o=n(2).MongoError,i=n(2).Mongos,s=n(26),a=n(99),c=n(35).Store,u=n(0).MAX_JS_INT,l=n(0).translateOptions,f=n(0).filterOptions,p=n(0).mergeOptions;var d=["ha","haInterval","acceptableLatencyMS","poolSize","ssl","checkServerIdentity","sslValidate","sslCA","sslCRL","sslCert","ciphers","ecdhCurve","sslKey","sslPass","socketOptions","bufferMaxEntries","store","auto_reconnect","autoReconnect","emitError","keepAlive","keepAliveInitialDelay","noDelay","connectTimeoutMS","socketTimeoutMS","loggerLevel","logger","reconnectTries","appname","domainsEnabled","servername","promoteLongs","promoteValues","promoteBuffers","promiseLibrary","monitorCommands"];class h extends r{constructor(e,t){super();t=f(t=t||{},d);for(var n=0;n<e.length;n++)if(!(e[n]instanceof a))throw o.create({message:"all seed list instances must be of the Server type",driver:!0});var r={force:!1,bufferMaxEntries:"number"==typeof t.bufferMaxEntries?t.bufferMaxEntries:u},h=t.store||new c(this,r),m=e.map((function(e){return{host:e.host,port:e.port}})),g="boolean"!=typeof t.auto_reconnect||t.auto_reconnect;g="boolean"==typeof t.autoReconnect?t.autoReconnect:g;var y=p({},{disconnectHandler:h,cursorFactory:s,reconnect:g,emitError:"boolean"!=typeof t.emitError||t.emitError,size:"number"==typeof t.poolSize?t.poolSize:5,monitorCommands:"boolean"==typeof t.monitorCommands&&t.monitorCommands});y=l(y,t);var b=t.socketOptions&&Object.keys(t.socketOptions).length>0?t.socketOptions:t;y=l(y,b),this.s={coreTopology:new i(m,y),sCapabilities:null,debug:y.debug,storeOptions:r,clonedOptions:y,store:h,options:t,sessionPool:null,sessions:new Set,promiseLibrary:t.promiseLibrary||Promise}}connect(e,t){var n=this;"function"==typeof e&&(t=e,e={}),null==e&&(e={}),"function"!=typeof t&&(t=null),e=Object.assign({},this.s.clonedOptions,e),n.s.options=e,n.s.storeOptions.bufferMaxEntries="number"==typeof e.bufferMaxEntries?e.bufferMaxEntries:-1;var r=function(){return function(e){["timeout","error","close"].forEach((function(e){n.removeListener(e,r)})),n.s.coreTopology.removeListener("connect",r),n.close(!0);try{t(e)}catch(e){process.nextTick((function(){throw e}))}}},o=function(e){return function(t){"error"!==e&&n.emit(e,t)}},i=function(e){return function(t,r){n.emit(e,t,r)}};["timeout","error","close","serverOpening","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","serverClosed","topologyOpening","topologyClosed","topologyDescriptionChanged","commandStarted","commandSucceeded","commandFailed"].forEach((function(e){n.s.coreTopology.removeAllListeners(e)})),n.s.coreTopology.on("serverDescriptionChanged",i("serverDescriptionChanged")),n.s.coreTopology.on("serverHeartbeatStarted",i("serverHeartbeatStarted")),n.s.coreTopology.on("serverHeartbeatSucceeded",i("serverHeartbeatSucceeded")),n.s.coreTopology.on("serverHeartbeatFailed",i("serverHeartbeatFailed")),n.s.coreTopology.on("serverOpening",i("serverOpening")),n.s.coreTopology.on("serverClosed",i("serverClosed")),n.s.coreTopology.on("topologyOpening",i("topologyOpening")),n.s.coreTopology.on("topologyClosed",i("topologyClosed")),n.s.coreTopology.on("topologyDescriptionChanged",i("topologyDescriptionChanged")),n.s.coreTopology.on("commandStarted",i("commandStarted")),n.s.coreTopology.on("commandSucceeded",i("commandSucceeded")),n.s.coreTopology.on("commandFailed",i("commandFailed")),n.s.coreTopology.once("timeout",r("timeout")),n.s.coreTopology.once("error",r("error")),n.s.coreTopology.once("close",r("close")),n.s.coreTopology.once("connect",(function(){["timeout","error","close","fullsetup"].forEach((function(e){n.s.coreTopology.removeAllListeners(e)})),n.s.coreTopology.on("timeout",o("timeout")),n.s.coreTopology.on("error",o("error")),n.s.coreTopology.on("close",o("close")),n.s.coreTopology.on("fullsetup",(function(){n.emit("fullsetup",n)})),n.emit("open",null,n);try{t(null,n)}catch(e){process.nextTick((function(){throw e}))}})),n.s.coreTopology.on("joined",i("joined")),n.s.coreTopology.on("left",i("left")),n.s.coreTopology.on("reconnect",(function(){n.emit("reconnect"),n.s.store.execute()})),n.s.coreTopology.connect(e)}}Object.defineProperty(h.prototype,"haInterval",{enumerable:!0,get:function(){return this.s.coreTopology.s.haInterval}}),e.exports=h},function(e,t,n){"use strict";const r=n(99),o=n(26),i=n(2).MongoError,s=n(35).TopologyBase,a=n(35).Store,c=n(2).ReplSet,u=n(0).MAX_JS_INT,l=n(0).translateOptions,f=n(0).filterOptions,p=n(0).mergeOptions;var d=["ha","haInterval","replicaSet","rs_name","secondaryAcceptableLatencyMS","connectWithNoPrimary","poolSize","ssl","checkServerIdentity","sslValidate","sslCA","sslCert","ciphers","ecdhCurve","sslCRL","sslKey","sslPass","socketOptions","bufferMaxEntries","store","auto_reconnect","autoReconnect","emitError","keepAlive","keepAliveInitialDelay","noDelay","connectTimeoutMS","socketTimeoutMS","strategy","debug","family","loggerLevel","logger","reconnectTries","appname","domainsEnabled","servername","promoteLongs","promoteValues","promoteBuffers","maxStalenessSeconds","promiseLibrary","minSize","monitorCommands"];class h extends s{constructor(e,t){super();var n=this;t=f(t=t||{},d);for(var s=0;s<e.length;s++)if(!(e[s]instanceof r))throw i.create({message:"all seed list instances must be of the Server type",driver:!0});var h={force:!1,bufferMaxEntries:"number"==typeof t.bufferMaxEntries?t.bufferMaxEntries:u},m=t.store||new a(n,h),g=e.map((function(e){return{host:e.host,port:e.port}})),y=p({},{disconnectHandler:m,cursorFactory:o,reconnect:!1,emitError:"boolean"!=typeof t.emitError||t.emitError,size:"number"==typeof t.poolSize?t.poolSize:5,monitorCommands:"boolean"==typeof t.monitorCommands&&t.monitorCommands});y=l(y,t);var b=t.socketOptions&&Object.keys(t.socketOptions).length>0?t.socketOptions:t;y=l(y,b);var v=new c(g,y);v.on("reconnect",(function(){n.emit("reconnect"),m.execute()})),this.s={coreTopology:v,sCapabilities:null,tag:t.tag,storeOptions:h,clonedOptions:y,store:m,options:t,sessionPool:null,sessions:new Set,promiseLibrary:t.promiseLibrary||Promise},y.debug&&Object.defineProperty(this,"replset",{enumerable:!0,get:function(){return v}})}connect(e,t){var n=this;"function"==typeof e&&(t=e,e={}),null==e&&(e={}),"function"!=typeof t&&(t=null),e=Object.assign({},this.s.clonedOptions,e),n.s.options=e,n.s.storeOptions.bufferMaxEntries="number"==typeof e.bufferMaxEntries?e.bufferMaxEntries:-1;var r=function(e){return function(t){"error"!==e&&n.emit(e,t)}};["timeout","error","close","serverOpening","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","serverClosed","topologyOpening","topologyClosed","topologyDescriptionChanged","commandStarted","commandSucceeded","commandFailed","joined","left","ping","ha"].forEach((function(e){n.s.coreTopology.removeAllListeners(e)}));var o,i=function(e){return function(t,r){n.emit(e,t,r)}};n.s.coreTopology.on("joined",(o="joined",function(e,t){n.emit(o,e,t.lastIsMaster(),t)})),n.s.coreTopology.on("left",i("left")),n.s.coreTopology.on("ping",i("ping")),n.s.coreTopology.on("ha",(function(e,t){n.emit("ha",e,t),"start"===e?n.emit("ha_connect",e,t):"end"===e&&n.emit("ha_ismaster",e,t)})),n.s.coreTopology.on("serverDescriptionChanged",i("serverDescriptionChanged")),n.s.coreTopology.on("serverHeartbeatStarted",i("serverHeartbeatStarted")),n.s.coreTopology.on("serverHeartbeatSucceeded",i("serverHeartbeatSucceeded")),n.s.coreTopology.on("serverHeartbeatFailed",i("serverHeartbeatFailed")),n.s.coreTopology.on("serverOpening",i("serverOpening")),n.s.coreTopology.on("serverClosed",i("serverClosed")),n.s.coreTopology.on("topologyOpening",i("topologyOpening")),n.s.coreTopology.on("topologyClosed",i("topologyClosed")),n.s.coreTopology.on("topologyDescriptionChanged",i("topologyDescriptionChanged")),n.s.coreTopology.on("commandStarted",i("commandStarted")),n.s.coreTopology.on("commandSucceeded",i("commandSucceeded")),n.s.coreTopology.on("commandFailed",i("commandFailed")),n.s.coreTopology.on("fullsetup",(function(){n.emit("fullsetup",n,n)})),n.s.coreTopology.on("all",(function(){n.emit("all",null,n)}));var s=function(){return function(e){["timeout","error","close"].forEach((function(e){n.s.coreTopology.removeListener(e,s)})),n.s.coreTopology.removeListener("connect",s),n.s.coreTopology.destroy();try{t(e)}catch(e){n.s.coreTopology.isConnected()||process.nextTick((function(){throw e}))}}};n.s.coreTopology.once("timeout",s("timeout")),n.s.coreTopology.once("error",s("error")),n.s.coreTopology.once("close",s("close")),n.s.coreTopology.once("connect",(function(){n.s.coreTopology.once("timeout",r("timeout")),n.s.coreTopology.once("error",r("error")),n.s.coreTopology.once("close",r("close")),n.emit("open",null,n);try{t(null,n)}catch(e){process.nextTick((function(){throw e}))}})),n.s.coreTopology.connect(e)}close(e,t){["timeout","error","close","joined","left"].forEach(e=>this.removeAllListeners(e)),super.close(e,t)}}Object.defineProperty(h.prototype,"haInterval",{enumerable:!0,get:function(){return this.s.coreTopology.s.haInterval}}),e.exports=h},function(e,t,n){"use strict";const r=n(59),o=n(9).retrieveBSON(),i=n(3).MongoError,s=n(224);if("function"!=typeof s.extension)throw new i("loaded version of `mongodb-client-encryption` does not have property `extension`. Please make sure you are loading the correct version of `mongodb-client-encryption`");const a=s.extension(n(42)).AutoEncrypter,c=Symbol("internalClient");class u{constructor(e,t){this.bypassAutoEncryption=!!t.autoEncryption.bypassAutoEncryption,this.needsConnecting=!1,0===t.maxPoolSize&&null==t.autoEncryption.keyVaultClient?t.autoEncryption.keyVaultClient=e:null==t.autoEncryption.keyVaultClient&&(t.autoEncryption.keyVaultClient=this.getInternalClient(e)),this.bypassAutoEncryption?t.autoEncryption.metadataClient=void 0:0===t.maxPoolSize?t.autoEncryption.metadataClient=e:t.autoEncryption.metadataClient=this.getInternalClient(e),t.autoEncryption.bson=u.makeBSON(t),this.autoEncrypter=new a(e,t.autoEncryption)}getInternalClient(e){if(!this[c]){const t={};for(const n of Object.keys(e.s.options))-1===["autoEncryption","minPoolSize","servers","caseTranslate","dbName"].indexOf(n)&&(t[n]=e.s.options[n]);t.minPoolSize=0;const n=["commandStarted","commandSucceeded","commandFailed","serverOpening","serverClosed","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","topologyOpening","topologyClosed","topologyDescriptionChanged","joined","left","ping","ha","connectionPoolCreated","connectionPoolClosed","connectionCreated","connectionReady","connectionClosed","connectionCheckOutStarted","connectionCheckOutFailed","connectionCheckedOut","connectionCheckedIn","connectionPoolCleared"];this[c]=new r(e.s.url,t);for(const t of n)for(const n of e.listeners(t))this[c].on(t,n);e.on("newListener",(e,t)=>{this[c].on(e,t)}),this.needsConnecting=!0}return this[c]}connectInternalClient(e){return this.needsConnecting?(this.needsConnecting=!1,this[c].connect(e)):e()}close(e,t,n){this.autoEncrypter.teardown(r=>{if(this[c]&&e!==this[c])return this[c].close(t,n);n(r)})}static makeBSON(e){return(e||{}).bson||new o([o.Binary,o.Code,o.DBRef,o.Decimal128,o.Double,o.Int32,o.Long,o.Map,o.MaxKey,o.MinKey,o.ObjectId,o.BSONRegExp,o.Symbol,o.Timestamp])}}e.exports={Encrypter:u}},function(e,t,n){"use strict";let r;function o(){return r||(r=s(n(42))),r}const i=n(100).MongoCryptError;function s(e){const t={mongodb:e};return t.stateMachine=n(485)(t),t.autoEncrypter=n(486)(t),t.clientEncryption=n(490)(t),{AutoEncrypter:t.autoEncrypter.AutoEncrypter,ClientEncryption:t.clientEncryption.ClientEncryption,MongoCryptError:i}}e.exports={extension:s,MongoCryptError:i,get AutoEncrypter(){const t=o();return delete e.exports.AutoEncrypter,e.exports.AutoEncrypter=t.AutoEncrypter,t.AutoEncrypter},get ClientEncryption(){const t=o();return delete e.exports.ClientEncryption,e.exports.ClientEncryption=t.ClientEncryption,t.ClientEncryption}}},function(e,t,n){(function(r){var o=n(89),i=n(136),s=n(487),a=i.join,c=i.dirname,u=o.accessSync&&function(e){try{o.accessSync(e)}catch(e){return!1}return!0}||o.existsSync||i.existsSync,l={arrow:process.env.NODE_BINDINGS_ARROW||" → ",compiled:process.env.NODE_BINDINGS_COMPILED_DIR||"compiled",platform:process.platform,arch:process.arch,nodePreGyp:"node-v"+process.versions.modules+"-"+process.platform+"-"+process.arch,version:process.versions.node,bindings:"bindings.node",try:[["module_root","build","bindings"],["module_root","build","Debug","bindings"],["module_root","build","Release","bindings"],["module_root","out","Debug","bindings"],["module_root","Debug","bindings"],["module_root","out","Release","bindings"],["module_root","Release","bindings"],["module_root","build","default","bindings"],["module_root","compiled","version","platform","arch","bindings"],["module_root","addon-build","release","install-root","bindings"],["module_root","addon-build","debug","install-root","bindings"],["module_root","addon-build","default","install-root","bindings"],["module_root","lib","binding","nodePreGyp","bindings"]]};e.exports=t=function(e){"string"==typeof e?e={bindings:e}:e||(e={}),Object.keys(l).map((function(t){t in e||(e[t]=l[t])})),e.module_root||(e.module_root=t.getRoot(t.getFileName())),".node"!=i.extname(e.bindings)&&(e.bindings+=".node");for(var n,r,o,s=require,c=[],u=0,f=e.try.length;u<f;u++){n=a.apply(null,e.try[u].map((function(t){return e[t]||t}))),c.push(n);try{return r=e.path?s.resolve(n):s(n),e.path||(r.path=n),r}catch(e){if("MODULE_NOT_FOUND"!==e.code&&"QUALIFIED_PATH_RESOLUTION_FAILED"!==e.code&&!/not find/i.test(e.message))throw e}}throw(o=new Error("Could not locate the bindings file. Tried:\n"+c.map((function(t){return e.arrow+t})).join("\n"))).tries=c,o},t.getFileName=function(e){var t,n=Error.prepareStackTrace,o=Error.stackTraceLimit,i={};Error.stackTraceLimit=10,Error.prepareStackTrace=function(n,o){for(var i=0,s=o.length;i<s;i++)if((t=o[i].getFileName())!==r){if(!e)return;if(t!==e)return}},Error.captureStackTrace(i),Error.prepareStackTrace=n,Error.stackTraceLimit=o;return 0===t.indexOf("file://")&&(t=s(t)),t},t.getRoot=function(e){for(var t,n=c(e);;){if("."===n&&(n=process.cwd()),u(a(n,"package.json"))||u(a(n,"node_modules")))return n;if(t===n)throw new Error('Could not find module root given file: "'+e+'". Do you have a `package.json` file? ');t=n,n=a(n,"..")}}}).call(this,"/index.js")},function(e,t,n){"use strict";const r=n(20);function o(e){return(t,n,o)=>{let i;try{i=r.createHmac(e,t).update(n).digest()}catch(e){return e}return i.copy(o),i.length}}e.exports={aes256CbcEncryptHook:function(e,t,n,o){let i;try{let o=r.createCipheriv("aes-256-cbc",e,t);o.setAutoPadding(!1),i=o.update(n)}catch(e){return e}return i.copy(o),i.length},aes256CbcDecryptHook:function(e,t,n,o){let i;try{let o=r.createDecipheriv("aes-256-cbc",e,t);o.setAutoPadding(!1),i=o.update(n)}catch(e){return e}return i.copy(o),i.length},randomHook:"function"==typeof r.randomFillSync?function(e,t){try{r.randomFillSync(e,0,t)}catch(e){return e}return t}:function(e,t){let n;try{n=r.randomBytes(t)}catch(e){return e}return n.copy(e),t},hmacSha512Hook:o("sha512"),hmacSha256Hook:o("sha256"),sha256Hook:function(e,t){let n;try{n=r.createHash("sha256").update(e).digest()}catch(e){return e}return n.copy(t),n.length},signRsaSha256Hook:function(e,t,n){let o;try{const n=r.createSign("sha256WithRSAEncryption"),i=Buffer.from(`-----BEGIN PRIVATE KEY-----\n${e.toString("base64")}\n-----END PRIVATE KEY-----\n`);o=n.update(t).end().sign(i)}catch(e){return e}return o.copy(n),o.length}}},function(e,t,n){"use strict";var r=n(2).BSON.Binary,o=n(2).BSON.ObjectID,i=n(22).Buffer,s=function(e,t,n){if(!(this instanceof s))return new s(e,t);this.file=e;var a=null==t?{}:t;if(this.writeConcern=n||{w:1},this.objectId=null==a._id?new o:a._id,this.chunkNumber=null==a.n?0:a.n,this.data=new r,"string"==typeof a.data){var c=i.alloc(a.data.length);c.write(a.data,0,a.data.length,"binary"),this.data=new r(c)}else if(Array.isArray(a.data)){c=i.alloc(a.data.length);var u=a.data.join("");c.write(u,0,u.length,"binary"),this.data=new r(c)}else if(a.data&&"Binary"===a.data._bsontype)this.data=a.data;else if(!i.isBuffer(a.data)&&null!=a.data)throw Error("Illegal chunk format");this.internalPosition=0};s.prototype.write=function(e,t){return this.data.write(e,this.internalPosition,e.length,"binary"),this.internalPosition=this.data.length(),null!=t?t(null,this):this},s.prototype.read=function(e){if(e=null==e||0===e?this.length():e,this.length()-this.internalPosition+1>=e){var t=this.data.read(this.internalPosition,e);return this.internalPosition=this.internalPosition+e,t}return""},s.prototype.readSlice=function(e){if(this.length()-this.internalPosition>=e){var t=null;return null!=this.data.buffer?t=this.data.buffer.slice(this.internalPosition,this.internalPosition+e):(t=i.alloc(e),e=this.data.readInto(t,this.internalPosition)),this.internalPosition=this.internalPosition+e,t}return null},s.prototype.eof=function(){return this.internalPosition===this.length()},s.prototype.getc=function(){return this.read(1)},s.prototype.rewind=function(){this.internalPosition=0,this.data=new r},s.prototype.save=function(e,t){var n=this;"function"==typeof e&&(t=e,e={}),n.file.chunkCollection((function(r,o){if(r)return t(r);var i={upsert:!0};for(var s in e)i[s]=e[s];for(s in n.writeConcern)i[s]=n.writeConcern[s];n.data.length()>0?n.buildMongoObject((function(e){var r={forceServerObjectId:!0};for(var s in n.writeConcern)r[s]=n.writeConcern[s];o.replaceOne({_id:n.objectId},e,i,(function(e){t(e,n)}))})):t(null,n)}))},s.prototype.buildMongoObject=function(e){var t={files_id:this.file.fileId,n:this.chunkNumber,data:this.data};null!=this.objectId&&(t._id=this.objectId),e(t)},s.prototype.length=function(){return this.data.length()},Object.defineProperty(s.prototype,"position",{enumerable:!0,get:function(){return this.internalPosition},set:function(e){this.internalPosition=e}}),s.DEFAULT_CHUNK_SIZE=261120,e.exports=s},function(e,t,n){const r=n(229);e.exports={packageName:"dbgate-plugin-mongo",drivers:[r]}},function(module,exports,__webpack_require__){const _=__webpack_require__(24),stream=__webpack_require__(18),isPromise=__webpack_require__(230),driverBase=__webpack_require__(231),Analyser=__webpack_require__(233),MongoClient=__webpack_require__(42).MongoClient,ObjectId=__webpack_require__(42).ObjectId,Cursor=__webpack_require__(42).Cursor,createBulkInsertStream=__webpack_require__(495);function transformMongoData(e){return _.mapValues(e,e=>e&&e.constructor==ObjectId?{$oid:e.toString()}:e)}function readCursor(e,t){return new Promise(n=>{t.recordset({__isDynamicStructure:!0}),e.on("data",e=>t.row(transformMongoData(e))),e.on("end",()=>n())})}function convertObjectId(e){return _.cloneDeepWith(e,e=>{if(e&&e.$oid)return ObjectId(e.$oid)})}function findArrayResult(e){if(!_.isPlainObject(e))return null;const t=_.values(e).filter(e=>_.isArray(e));return 1==t.length?t[0]:null}async function getScriptableDb(e){const t=e.__getDatabase(),n=await t.listCollections().toArray();for(const e of n)t[e.name]=t.collection(e.name);return t}const driver={...driverBase,analyserClass:Analyser,async connect({server:e,port:t,user:n,password:r,database:o,useDatabaseUrl:i,databaseUrl:s,ssl:a}){const c=i?s:n?`mongodb://${n}:${r}@${e}:${t}`:`mongodb://${e}:${t}`,u={useUnifiedTopology:!0};a&&(u.tls=!0,u.tlsCAFile=a.ca,u.tlsCertificateKeyFile=a.cert||a.key,u.tlsCertificateKeyFilePassword=a.password,u.tlsAllowInvalidCertificates=!a.rejectUnauthorized);const l=new MongoClient(c,u);return await l.connect(),l.__getDatabase=o?()=>l.db(o):()=>l.db(),l.__databaseName=o,l},query:async(e,t)=>({rows:[],columns:[]}),async script(pool,sql){let func;func=eval(`(db,ObjectId) => { ${sql} }`);const db=await getScriptableDb(pool);func(db,ObjectId)},async stream(pool,sql,options){let func;try{func=eval(`(db,ObjectId) => ${sql}`)}catch(e){return options.info({message:"Error compiling expression: "+e.message,time:new Date,severity:"error"}),void options.done()}const db=await getScriptableDb(pool);let exprValue;try{exprValue=func(db,ObjectId)}catch(e){return options.info({message:"Error evaluating expression: "+e.message,time:new Date,severity:"error"}),void options.done()}if(exprValue instanceof Cursor)await readCursor(exprValue,options);else if(isPromise(exprValue))try{const e=await exprValue;options.info({message:"Command succesfully executed",time:new Date,severity:"info"});try{options.info({message:`Result: ${JSON.stringify(e)}`,time:new Date,severity:"info"})}catch(t){options.info({message:`Result: ${e}`,time:new Date,severity:"info"})}const t=findArrayResult(e);if(t){options.recordset({__isDynamicStructure:!0});for(const e of t)options.row(e)}}catch(e){options.info({message:"Error when running command: "+e.message,time:new Date,severity:"error"})}options.done()},async readQuery(pool,sql,structure){try{const e=JSON.parse(sql);e&&e.pureName&&(sql=`db.${e.pureName}.find()`)}catch(e){}func=eval(`(db,ObjectId) => ${sql}`);const db=await getScriptableDb(pool);return exprValue=func(db,ObjectId),exprValue},async writeTable(e,t,n){return createBulkInsertStream(this,stream,e,t,n)},async getVersion(e){const t=await e.__getDatabase().admin().serverInfo();return{...t,versionText:`MongoDB ${t.version}`}},listDatabases:async e=>(await e.__getDatabase().admin().listDatabases()).databases,async readCollection(e,t){try{const n=e.__getDatabase().collection(t.pureName);if(t.countDocuments){return{count:await n.countDocuments(convertObjectId(t.condition)||{})}}{let e=await n.find(convertObjectId(t.condition)||{});return t.sort&&(e=e.sort(t.sort)),t.skip&&(e=e.skip(t.skip)),t.limit&&(e=e.limit(t.limit)),{rows:(await e.toArray()).map(transformMongoData)}}}catch(e){return{errorMessage:e.message}}},async updateCollection(e,t){const n={inserted:[],updated:[],deleted:[],replaced:[]};try{const r=e.__getDatabase();for(const e of t.inserts){const t=r.collection(e.pureName),o={...e.document,...e.fields},i=await t.insert(convertObjectId(o));n.inserted.push(i._id)}for(const e of t.updates){const t=r.collection(e.pureName);if(e.document){const r={...e.document,...e.fields},o=await t.findOne(convertObjectId(e.condition));if(o){const i=await t.replaceOne(convertObjectId(e.condition),{...convertObjectId(r),_id:o._id});n.replaced.push(i._id)}}else{const r=await t.updateOne(convertObjectId(e.condition),{$set:convertObjectId(e.fields)});n.updated.push(r._id)}}for(const e of t.deletes){const t=r.collection(e.pureName),o=await t.deleteOne(convertObjectId(e.condition));n.deleted.push(o._id)}return n}catch(e){return{errorMessage:e.message}}},async createDatabase(e,t){const n=e.db(t);await n.createCollection("collection1")},async loadFieldValues(e,t,n,r){try{const o=e.__getDatabase().collection(t.pureName),i=[];if(r){const e=_.compact(r.split(" ").map(e=>e.trim()));e.length>0&&i.push({$match:{$and:e.map(e=>({[n]:{$regex:`.*${e}.*`,$options:"i"}}))}})}let s=await o.aggregate([...i,{$group:{_id:"$"+n}},{$sort:{_id:1}},{$limit:100}]);const a=await s.toArray();return _.uniqBy(a.map(transformMongoData).map(({_id:e})=>_.isArray(e)||_.isPlainObject(e)?{value:null}:{value:e}),e=>e.value)}catch(e){return{errorMessage:e.message}}},readJsonQuery(e,t,n){const{collection:r,condition:o,sort:i}=t;return e.__getDatabase().collection(r).find(o||{}).sort(i||{})}};module.exports=driver},function(e,t){function n(e){return!!e&&("object"==typeof e||"function"==typeof e)&&"function"==typeof e.then}e.exports=n,e.exports.default=n},function(e,t,n){const{driverBase:r}=global.DBGATE_TOOLS,o=n(232),{mongoSplitterOptions:i}=n(101);function s(e){return JSON.stringify(e,void 0,2).replace(/\{\s*\"\$oid\"\s*\:\s*\"([0-9a-f]+)\"\s*\}/g,(e,t)=>`ObjectId("${t}")`)}const a={...r,dumperClass:o,databaseEngineTypes:["document"],dialect:{limitSelect:!0,rangeSelect:!0,offsetFetchRangeSyntax:!0,stringEscapeChar:"'",fallbackDataType:"nvarchar(max)",quoteIdentifier:e=>`[${e}]`},engine:"mongo@dbgate-plugin-mongo",title:"MongoDB",defaultPort:27017,supportsDatabaseUrl:!0,databaseUrlPlaceholder:"e.g. mongodb://username:password@mongodb.mydomain.net/dbname",getQuerySplitterOptions:()=>i,showConnectionField:(e,t)=>"useDatabaseUrl"==e||(t.useDatabaseUrl?["databaseUrl","defaultDatabase","singleDatabase","isReadOnly"].includes(e):["server","port","user","password","defaultDatabase","singleDatabase","isReadOnly"].includes(e)),importExportArgs:[{type:"checkbox",name:"createStringId",label:"Create string _id attribute",apiName:"createStringId",direction:"target"}],getCollectionUpdateScript(e){let t="";for(const n of e.inserts)t+=`db.${n.pureName}.insert(${s({...n.document,...n.fields})});\n`;for(const n of e.updates)n.document?t+=`db.${n.pureName}.replaceOne(${s(n.condition)}, ${s({...n.document,...n.fields})});\n`:t+=`db.${n.pureName}.updateOne(${s(n.condition)}, ${s({$set:n.fields})});\n`;for(const n of e.deletes)t+=`db.${n.pureName}.deleteOne(${s(n.condition)});\n`;return t}};e.exports=a},function(e,t){const{SqlDumper:n}=global.DBGATE_TOOLS;e.exports=class extends n{}},function(e,t,n){const{DatabaseAnalyser:r}=n(234);e.exports=class extends r{constructor(e,t,n){super(e,t,n)}async _runAnalysis(){const e=await this.pool.__getDatabase().listCollections().toArray();return this.mergeAnalyseResult({collections:e.map(e=>({pureName:e.name}))})}}},function(e,t,n){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),o=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||r(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),o(n(235),t),o(n(236),t),o(n(146),t),o(n(163),t),o(n(318),t),o(n(120),t),o(n(366),t),o(n(179),t),o(n(377),t),o(n(379),t),o(n(183),t),o(n(383),t),o(n(385),t),o(n(128),t),o(n(397),t),o(n(398),t),o(n(399),t),o(n(400),t),o(n(401),t),o(n(402),t)},function(e,t,n){"use strict";function r(e){return e&&/int/i.test(e)}function o(e){return e&&/numeric|decimal/i.test(e)}function i(e){return e&&/float|single|double/i.test(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.isTypeDateTime=t.isTypeLogical=t.isTypeString=t.isTypeNumber=t.isTypeFloat=t.isTypeNumeric=t.isTypeInteger=void 0,t.isTypeInteger=r,t.isTypeNumeric=o,t.isTypeFloat=i,t.isTypeNumber=function(e){return r(e)||i(e)||o(e)},t.isTypeString=function(e){return e&&/char|binary/i.test(e)},t.isTypeLogical=function(e){return e&&/bit|boolean/i.test(e)},t.isTypeDateTime=function(e){return e&&/date|time|timestamp/i.test(e)}},function(e,t,n){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.fillConstraintNames=t.makeUniqueColumnNames=t.findForeignKeyForColumn=t.findObjectLike=t.equalStringLike=t.quoteFullName=t.fullNameToLabel=t.fullNameToString=t.fullNameFromString=void 0;const o=r(n(24));function i(e,t){return(e||"").toLowerCase().trim()==(t||"").toLowerCase().trim()}function s(e,t,n){return`${e}_${t.pureName}_${n.map(e=>e.columnName.replace(" ","_")).join("_")}`}t.fullNameFromString=function(e){const t=e.match(/\[([^\]]+)\]\.\[([^\]]+)\]/);return t?{schemaName:t[1],pureName:t[2]}:{schemaName:null,pureName:e}},t.fullNameToString=function({schemaName:e,pureName:t}){return e?`[${e}].[${t}]`:t},t.fullNameToLabel=function({schemaName:e,pureName:t}){return e?`${e}.${t}`:t},t.quoteFullName=function(e,{schemaName:t,pureName:n}){return t?`${e.quoteIdentifier(t)}.${e.quoteIdentifier(n)}`:`${e.quoteIdentifier(n)}`},t.equalStringLike=i,t.findObjectLike=function({pureName:e,schemaName:t},n,r){var o,s;return n?t?null===(o=n[r])||void 0===o?void 0:o.find(n=>i(n.pureName,e)&&i(n.schemaName,t)):null===(s=n[r])||void 0===s?void 0:s.find(t=>i(t.pureName,e)):null},t.findForeignKeyForColumn=function(e,t){return(e.foreignKeys||[]).find(e=>e.columns.find(e=>e.columnName==t.columnName))},t.makeUniqueColumnNames=function(e){const t=new Set;for(let n=0;n<e.length;n++){if(t.has(e[n].columnName)){let r=2;for(;t.has(`${e[n].columnName}${r}`);)r++;e[n].columnName=`${e[n].columnName}${r}`}t.add(e[n].columnName)}},t.fillConstraintNames=function(e,t){if(!e)return e;const n=o.default.cloneDeep(e);!n.primaryKey||n.primaryKey.constraintName||t.anonymousPrimaryKey||(n.primaryKey.constraintName=`PK_${n.pureName}`);for(const e of n.foreignKeys||[])e.constraintName||(e.constraintName=s("FK",n,e.columns));for(const e of n.indexes||[])e.constraintName||(e.constraintName=s("IX",n,e.columns));for(const e of n.uniques||[])e.constraintName||(e.constraintName=s("UQ",n,e.columns));return n}},function(e,t){e.exports=function(){this.__data__=[],this.size=0}},function(e,t,n){var r=n(64),o=Array.prototype.splice;e.exports=function(e){var t=this.__data__,n=r(t,e);return!(n<0)&&(n==t.length-1?t.pop():o.call(t,n,1),--this.size,!0)}},function(e,t,n){var r=n(64);e.exports=function(e){var t=this.__data__,n=r(t,e);return n<0?void 0:t[n][1]}},function(e,t,n){var r=n(64);e.exports=function(e){return r(this.__data__,e)>-1}},function(e,t,n){var r=n(64);e.exports=function(e,t){var n=this.__data__,o=r(n,e);return o<0?(++this.size,n.push([e,t])):n[o][1]=t,this}},function(e,t,n){var r=n(63);e.exports=function(){this.__data__=new r,this.size=0}},function(e,t){e.exports=function(e){var t=this.__data__,n=t.delete(e);return this.size=t.size,n}},function(e,t){e.exports=function(e){return this.__data__.get(e)}},function(e,t){e.exports=function(e){return this.__data__.has(e)}},function(e,t,n){var r=n(63),o=n(104),i=n(105);e.exports=function(e,t){var n=this.__data__;if(n instanceof r){var s=n.__data__;if(!o||s.length<199)return s.push([e,t]),this.size=++n.size,this;n=this.__data__=new i(s)}return n.set(e,t),this.size=n.size,this}},function(e,t,n){var r=n(148),o=n(250),i=n(28),s=n(150),a=/^\[object .+?Constructor\]$/,c=Function.prototype,u=Object.prototype,l=c.toString,f=u.hasOwnProperty,p=RegExp("^"+l.call(f).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");e.exports=function(e){return!(!i(e)||o(e))&&(r(e)?p:a).test(s(e))}},function(e,t,n){var r=n(36),o=Object.prototype,i=o.hasOwnProperty,s=o.toString,a=r?r.toStringTag:void 0;e.exports=function(e){var t=i.call(e,a),n=e[a];try{e[a]=void 0;var r=!0}catch(e){}var o=s.call(e);return r&&(t?e[a]=n:delete e[a]),o}},function(e,t){var n=Object.prototype.toString;e.exports=function(e){return n.call(e)}},function(e,t,n){var r,o=n(251),i=(r=/[^.]+$/.exec(o&&o.keys&&o.keys.IE_PROTO||""))?"Symbol(src)_1."+r:"";e.exports=function(e){return!!i&&i in e}},function(e,t,n){var r=n(19)["__core-js_shared__"];e.exports=r},function(e,t){e.exports=function(e,t){return null==e?void 0:e[t]}},function(e,t,n){var r=n(254),o=n(63),i=n(104);e.exports=function(){this.size=0,this.__data__={hash:new r,map:new(i||o),string:new r}}},function(e,t,n){var r=n(255),o=n(256),i=n(257),s=n(258),a=n(259);function c(e){var t=-1,n=null==e?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}c.prototype.clear=r,c.prototype.delete=o,c.prototype.get=i,c.prototype.has=s,c.prototype.set=a,e.exports=c},function(e,t,n){var r=n(66);e.exports=function(){this.__data__=r?r(null):{},this.size=0}},function(e,t){e.exports=function(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}},function(e,t,n){var r=n(66),o=Object.prototype.hasOwnProperty;e.exports=function(e){var t=this.__data__;if(r){var n=t[e];return"__lodash_hash_undefined__"===n?void 0:n}return o.call(t,e)?t[e]:void 0}},function(e,t,n){var r=n(66),o=Object.prototype.hasOwnProperty;e.exports=function(e){var t=this.__data__;return r?void 0!==t[e]:o.call(t,e)}},function(e,t,n){var r=n(66);e.exports=function(e,t){var n=this.__data__;return this.size+=this.has(e)?0:1,n[e]=r&&void 0===t?"__lodash_hash_undefined__":t,this}},function(e,t,n){var r=n(67);e.exports=function(e){var t=r(this,e).delete(e);return this.size-=t?1:0,t}},function(e,t){e.exports=function(e){var t=typeof e;return"string"==t||"number"==t||"symbol"==t||"boolean"==t?"__proto__"!==e:null===e}},function(e,t,n){var r=n(67);e.exports=function(e){return r(this,e).get(e)}},function(e,t,n){var r=n(67);e.exports=function(e){return r(this,e).has(e)}},function(e,t,n){var r=n(67);e.exports=function(e,t){var n=r(this,e),o=n.size;return n.set(e,t),this.size+=n.size==o?0:1,this}},function(e,t){e.exports=function(e,t){for(var n=-1,r=null==e?0:e.length;++n<r&&!1!==t(e[n],n,e););return e}},function(e,t,n){var r=n(48),o=n(49);e.exports=function(e,t){return e&&r(t,o(t),e)}},function(e,t){e.exports=function(e,t){for(var n=-1,r=Array(e);++n<e;)r[n]=t(n);return r}},function(e,t,n){var r=n(25),o=n(15);e.exports=function(e){return o(e)&&"[object Arguments]"==r(e)}},function(e,t){e.exports=function(){return!1}},function(e,t,n){var r=n(25),o=n(110),i=n(15),s={};s["[object Float32Array]"]=s["[object Float64Array]"]=s["[object Int8Array]"]=s["[object Int16Array]"]=s["[object Int32Array]"]=s["[object Uint8Array]"]=s["[object Uint8ClampedArray]"]=s["[object Uint16Array]"]=s["[object Uint32Array]"]=!0,s["[object Arguments]"]=s["[object Array]"]=s["[object ArrayBuffer]"]=s["[object Boolean]"]=s["[object DataView]"]=s["[object Date]"]=s["[object Error]"]=s["[object Function]"]=s["[object Map]"]=s["[object Number]"]=s["[object Object]"]=s["[object RegExp]"]=s["[object Set]"]=s["[object String]"]=s["[object WeakMap]"]=!1,e.exports=function(e){return i(e)&&o(e.length)&&!!s[r(e)]}},function(e,t,n){var r=n(111),o=n(272),i=Object.prototype.hasOwnProperty;e.exports=function(e){if(!r(e))return o(e);var t=[];for(var n in Object(e))i.call(e,n)&&"constructor"!=n&&t.push(n);return t}},function(e,t,n){var r=n(154)(Object.keys,Object);e.exports=r},function(e,t,n){var r=n(48),o=n(112);e.exports=function(e,t){return e&&r(t,o(t),e)}},function(e,t,n){var r=n(28),o=n(111),i=n(275),s=Object.prototype.hasOwnProperty;e.exports=function(e){if(!r(e))return i(e);var t=o(e),n=[];for(var a in e)("constructor"!=a||!t&&s.call(e,a))&&n.push(a);return n}},function(e,t){e.exports=function(e){var t=[];if(null!=e)for(var n in Object(e))t.push(n);return t}},function(e,t,n){(function(e){var r=n(19),o=t&&!t.nodeType&&t,i=o&&"object"==typeof e&&e&&!e.nodeType&&e,s=i&&i.exports===o?r.Buffer:void 0,a=s?s.allocUnsafe:void 0;e.exports=function(e,t){if(t)return e.slice();var n=e.length,r=a?a(n):new e.constructor(n);return e.copy(r),r}}).call(this,n(62)(e))},function(e,t){e.exports=function(e,t){var n=-1,r=e.length;for(t||(t=Array(r));++n<r;)t[n]=e[n];return t}},function(e,t,n){var r=n(48),o=n(113);e.exports=function(e,t){return r(e,o(e),t)}},function(e,t){e.exports=function(e,t){for(var n=-1,r=null==e?0:e.length,o=0,i=[];++n<r;){var s=e[n];t(s,n,e)&&(i[o++]=s)}return i}},function(e,t,n){var r=n(48),o=n(156);e.exports=function(e,t){return r(e,o(e),t)}},function(e,t,n){var r=n(31)(n(19),"DataView");e.exports=r},function(e,t,n){var r=n(31)(n(19),"Promise");e.exports=r},function(e,t,n){var r=n(31)(n(19),"WeakMap");e.exports=r},function(e,t){var n=Object.prototype.hasOwnProperty;e.exports=function(e){var t=e.length,r=new e.constructor(t);return t&&"string"==typeof e[0]&&n.call(e,"index")&&(r.index=e.index,r.input=e.input),r}},function(e,t,n){var r=n(116),o=n(286),i=n(287),s=n(288),a=n(289);e.exports=function(e,t,n){var c=e.constructor;switch(t){case"[object ArrayBuffer]":return r(e);case"[object Boolean]":case"[object Date]":return new c(+e);case"[object DataView]":return o(e,n);case"[object Float32Array]":case"[object Float64Array]":case"[object Int8Array]":case"[object Int16Array]":case"[object Int32Array]":case"[object Uint8Array]":case"[object Uint8ClampedArray]":case"[object Uint16Array]":case"[object Uint32Array]":return a(e,n);case"[object Map]":return new c;case"[object Number]":case"[object String]":return new c(e);case"[object RegExp]":return i(e);case"[object Set]":return new c;case"[object Symbol]":return s(e)}}},function(e,t,n){var r=n(116);e.exports=function(e,t){var n=t?r(e.buffer):e.buffer;return new e.constructor(n,e.byteOffset,e.byteLength)}},function(e,t){var n=/\w*$/;e.exports=function(e){var t=new e.constructor(e.source,n.exec(e));return t.lastIndex=e.lastIndex,t}},function(e,t,n){var r=n(36),o=r?r.prototype:void 0,i=o?o.valueOf:void 0;e.exports=function(e){return i?Object(i.call(e)):{}}},function(e,t,n){var r=n(116);e.exports=function(e,t){var n=t?r(e.buffer):e.buffer;return new e.constructor(n,e.byteOffset,e.length)}},function(e,t,n){var r=n(291),o=n(115),i=n(111);e.exports=function(e){return"function"!=typeof e.constructor||i(e)?{}:r(o(e))}},function(e,t,n){var r=n(28),o=Object.create,i=function(){function e(){}return function(t){if(!r(t))return{};if(o)return o(t);e.prototype=t;var n=new e;return e.prototype=void 0,n}}();e.exports=i},function(e,t,n){var r=n(293),o=n(37),i=n(69),s=i&&i.isMap,a=s?o(s):r;e.exports=a},function(e,t,n){var r=n(70),o=n(15);e.exports=function(e){return o(e)&&"[object Map]"==r(e)}},function(e,t,n){var r=n(295),o=n(37),i=n(69),s=i&&i.isSet,a=s?o(s):r;e.exports=a},function(e,t,n){var r=n(70),o=n(15);e.exports=function(e){return o(e)&&"[object Set]"==r(e)}},function(e,t){e.exports=function(e){for(var t=-1,n=null==e?0:e.length,r={};++t<n;){var o=e[t];r[o[0]]=o[1]}return r}},function(e,t,n){var r=n(298),o=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,i=/\\(\\)?/g,s=r((function(e){var t=[];return 46===e.charCodeAt(0)&&t.push(""),e.replace(o,(function(e,n,r,o){t.push(r?o.replace(i,"$1"):n||e)})),t}));e.exports=s},function(e,t,n){var r=n(299);e.exports=function(e){var t=r(e,(function(e){return 500===n.size&&n.clear(),e})),n=t.cache;return t}},function(e,t,n){var r=n(105);function o(e,t){if("function"!=typeof e||null!=t&&"function"!=typeof t)throw new TypeError("Expected a function");var n=function(){var r=arguments,o=t?t.apply(this,r):r[0],i=n.cache;if(i.has(o))return i.get(o);var s=e.apply(this,r);return n.cache=i.set(o,s)||i,s};return n.cache=new(o.Cache||r),n}o.Cache=r,e.exports=o},function(e,t,n){var r=n(36),o=n(51),i=n(12),s=n(71),a=r?r.prototype:void 0,c=a?a.toString:void 0;e.exports=function e(t){if("string"==typeof t)return t;if(i(t))return o(t,e)+"";if(s(t))return c?c.call(t):"";var n=t+"";return"0"==n&&1/t==-1/0?"-0":n}},function(e,t,n){var r=n(302),o=n(309)((function(e,t,n){return t=t.toLowerCase(),e+(n?r(t):t)}));e.exports=o},function(e,t,n){var r=n(40),o=n(303);e.exports=function(e){return o(r(e).toLowerCase())}},function(e,t,n){var r=n(304)("toUpperCase");e.exports=r},function(e,t,n){var r=n(305),o=n(165),i=n(306),s=n(40);e.exports=function(e){return function(t){t=s(t);var n=o(t)?i(t):void 0,a=n?n[0]:t.charAt(0),c=n?r(n,1).join(""):t.slice(1);return a[e]()+c}}},function(e,t,n){var r=n(164);e.exports=function(e,t,n){var o=e.length;return n=void 0===n?o:n,!t&&n>=o?e:r(e,t,n)}},function(e,t,n){var r=n(307),o=n(165),i=n(308);e.exports=function(e){return o(e)?i(e):r(e)}},function(e,t){e.exports=function(e){return e.split("")}},function(e,t){var n="[\\ud800-\\udfff]",r="[\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff]",o="\\ud83c[\\udffb-\\udfff]",i="[^\\ud800-\\udfff]",s="(?:\\ud83c[\\udde6-\\uddff]){2}",a="[\\ud800-\\udbff][\\udc00-\\udfff]",c="(?:"+r+"|"+o+")"+"?",u="[\\ufe0e\\ufe0f]?"+c+("(?:\\u200d(?:"+[i,s,a].join("|")+")[\\ufe0e\\ufe0f]?"+c+")*"),l="(?:"+[i+r+"?",r,s,a,n].join("|")+")",f=RegExp(o+"(?="+o+")|"+l+u,"g");e.exports=function(e){return e.match(f)||[]}},function(e,t,n){var r=n(310),o=n(311),i=n(314),s=RegExp("['’]","g");e.exports=function(e){return function(t){return r(i(o(t).replace(s,"")),e,"")}}},function(e,t){e.exports=function(e,t,n,r){var o=-1,i=null==e?0:e.length;for(r&&i&&(n=e[++o]);++o<i;)n=t(n,e[o],o,e);return n}},function(e,t,n){var r=n(312),o=n(40),i=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,s=RegExp("[\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff]","g");e.exports=function(e){return(e=o(e))&&e.replace(i,r).replace(s,"")}},function(e,t,n){var r=n(313)({"À":"A","Á":"A","Â":"A","Ã":"A","Ä":"A","Å":"A","à":"a","á":"a","â":"a","ã":"a","ä":"a","å":"a","Ç":"C","ç":"c","Ð":"D","ð":"d","È":"E","É":"E","Ê":"E","Ë":"E","è":"e","é":"e","ê":"e","ë":"e","Ì":"I","Í":"I","Î":"I","Ï":"I","ì":"i","í":"i","î":"i","ï":"i","Ñ":"N","ñ":"n","Ò":"O","Ó":"O","Ô":"O","Õ":"O","Ö":"O","Ø":"O","ò":"o","ó":"o","ô":"o","õ":"o","ö":"o","ø":"o","Ù":"U","Ú":"U","Û":"U","Ü":"U","ù":"u","ú":"u","û":"u","ü":"u","Ý":"Y","ý":"y","ÿ":"y","Æ":"Ae","æ":"ae","Þ":"Th","þ":"th","ß":"ss","Ā":"A","Ă":"A","Ą":"A","ā":"a","ă":"a","ą":"a","Ć":"C","Ĉ":"C","Ċ":"C","Č":"C","ć":"c","ĉ":"c","ċ":"c","č":"c","Ď":"D","Đ":"D","ď":"d","đ":"d","Ē":"E","Ĕ":"E","Ė":"E","Ę":"E","Ě":"E","ē":"e","ĕ":"e","ė":"e","ę":"e","ě":"e","Ĝ":"G","Ğ":"G","Ġ":"G","Ģ":"G","ĝ":"g","ğ":"g","ġ":"g","ģ":"g","Ĥ":"H","Ħ":"H","ĥ":"h","ħ":"h","Ĩ":"I","Ī":"I","Ĭ":"I","Į":"I","İ":"I","ĩ":"i","ī":"i","ĭ":"i","į":"i","ı":"i","Ĵ":"J","ĵ":"j","Ķ":"K","ķ":"k","ĸ":"k","Ĺ":"L","Ļ":"L","Ľ":"L","Ŀ":"L","Ł":"L","ĺ":"l","ļ":"l","ľ":"l","ŀ":"l","ł":"l","Ń":"N","Ņ":"N","Ň":"N","Ŋ":"N","ń":"n","ņ":"n","ň":"n","ŋ":"n","Ō":"O","Ŏ":"O","Ő":"O","ō":"o","ŏ":"o","ő":"o","Ŕ":"R","Ŗ":"R","Ř":"R","ŕ":"r","ŗ":"r","ř":"r","Ś":"S","Ŝ":"S","Ş":"S","Š":"S","ś":"s","ŝ":"s","ş":"s","š":"s","Ţ":"T","Ť":"T","Ŧ":"T","ţ":"t","ť":"t","ŧ":"t","Ũ":"U","Ū":"U","Ŭ":"U","Ů":"U","Ű":"U","Ų":"U","ũ":"u","ū":"u","ŭ":"u","ů":"u","ű":"u","ų":"u","Ŵ":"W","ŵ":"w","Ŷ":"Y","ŷ":"y","Ÿ":"Y","Ź":"Z","Ż":"Z","Ž":"Z","ź":"z","ż":"z","ž":"z","IJ":"IJ","ij":"ij","Œ":"Oe","œ":"oe","ʼn":"'n","ſ":"s"});e.exports=r},function(e,t){e.exports=function(e){return function(t){return null==e?void 0:e[t]}}},function(e,t,n){var r=n(315),o=n(316),i=n(40),s=n(317);e.exports=function(e,t,n){return e=i(e),void 0===(t=n?void 0:t)?o(e)?s(e):r(e):e.match(t)||[]}},function(e,t){var n=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g;e.exports=function(e){return e.match(n)||[]}},function(e,t){var n=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/;e.exports=function(e){return n.test(e)}},function(e,t){var n="\\xac\\xb1\\xd7\\xf7\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf\\u2000-\\u206f \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",r="["+n+"]",o="\\d+",i="[\\u2700-\\u27bf]",s="[a-z\\xdf-\\xf6\\xf8-\\xff]",a="[^\\ud800-\\udfff"+n+o+"\\u2700-\\u27bfa-z\\xdf-\\xf6\\xf8-\\xffA-Z\\xc0-\\xd6\\xd8-\\xde]",c="(?:\\ud83c[\\udde6-\\uddff]){2}",u="[\\ud800-\\udbff][\\udc00-\\udfff]",l="[A-Z\\xc0-\\xd6\\xd8-\\xde]",f="(?:"+s+"|"+a+")",p="(?:"+l+"|"+a+")",d="(?:[\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff]|\\ud83c[\\udffb-\\udfff])?",h="[\\ufe0e\\ufe0f]?"+d+("(?:\\u200d(?:"+["[^\\ud800-\\udfff]",c,u].join("|")+")[\\ufe0e\\ufe0f]?"+d+")*"),m="(?:"+[i,c,u].join("|")+")"+h,g=RegExp([l+"?"+s+"+(?:['’](?:d|ll|m|re|s|t|ve))?(?="+[r,l,"$"].join("|")+")",p+"+(?:['’](?:D|LL|M|RE|S|T|VE))?(?="+[r,l+f,"$"].join("|")+")",l+"?"+f+"+(?:['’](?:d|ll|m|re|s|t|ve))?",l+"+(?:['’](?:D|LL|M|RE|S|T|VE))?","\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])","\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",o,m].join("|"),"g");e.exports=function(e){return e.match(g)||[]}},function(e,t,n){"use strict";var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function s(e){try{c(r.next(e))}catch(e){i(e)}}function a(e){try{c(r.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((r=r.apply(e,t||[])).next())}))},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.createBulkInsertStreamBase=void 0;const i=o(n(319)),s=n(146);t.createBulkInsertStreamBase=function(e,t,n,o,a){const c=o.schemaName?`${e.dialect.quoteIdentifier(o.schemaName)}.${e.dialect.quoteIdentifier(o.pureName)}`:e.dialect.quoteIdentifier(o.pureName),u=new t.Writable({objectMode:!0});return u.buffer=[],u.structure=null,u.columnNames=null,u.requireFixedStructure=e.databaseEngineTypes.includes("sql"),u.addRow=e=>r(this,void 0,void 0,(function*(){u.structure?u.buffer.push(e):(u.structure=e,yield u.checkStructure())})),u.checkStructure=()=>r(this,void 0,void 0,(function*(){let t=yield e.analyseSingleTable(n,o);if(t&&a.dropIfExists&&(console.log(`Dropping table ${c}`),yield e.script(n,`DROP TABLE ${c}`)),a.createIfNotExists&&(!t||a.dropIfExists)){console.log(`Creating table ${c}`);const r=e.createDumper();r.createTable((0,s.prepareTableForImport)(Object.assign(Object.assign({},u.structure),o))),console.log(r.s),yield e.script(n,r.s),t=yield e.analyseSingleTable(n,o)}a.truncate&&(yield e.script(n,`TRUNCATE TABLE ${c}`)),u.columnNames=(0,i.default)(t.columns.map(e=>e.columnName),u.structure.columns.map(e=>e.columnName))})),u.send=()=>r(this,void 0,void 0,(function*(){const t=u.buffer;u.buffer=[];const r=e.createDumper();r.putRaw(`INSERT INTO ${c} (`),r.putCollection(",",u.columnNames,t=>r.putRaw(e.dialect.quoteIdentifier(t))),r.putRaw(")\n VALUES\n");let o=!1;for(const e of t)o&&r.putRaw(",\n"),r.putRaw("("),r.putCollection(",",u.columnNames,t=>r.putValue(e[t])),r.putRaw(")"),o=!0;r.putRaw(";"),yield e.query(n,r.s)})),u.sendIfFull=()=>r(this,void 0,void 0,(function*(){u.buffer.length>100&&(yield u.send())})),u._write=(e,t,n)=>r(this,void 0,void 0,(function*(){yield u.addRow(e),yield u.sendIfFull(),n()})),u._final=e=>r(this,void 0,void 0,(function*(){yield u.send(),e()})),u}},function(e,t,n){var r=n(51),o=n(320),i=n(168),s=n(331),a=i((function(e){var t=r(e,s);return t.length&&t[0]===e[0]?o(t):[]}));e.exports=a},function(e,t,n){var r=n(118),o=n(166),i=n(167),s=n(51),a=n(37),c=n(119),u=Math.min;e.exports=function(e,t,n){for(var l=n?i:o,f=e[0].length,p=e.length,d=p,h=Array(p),m=1/0,g=[];d--;){var y=e[d];d&&t&&(y=s(y,a(t))),m=u(y.length,m),h[d]=!n&&(t||f>=120&&y.length>=120)?new r(d&&y):void 0}y=e[0];var b=-1,v=h[0];e:for(;++b<f&&g.length<m;){var S=y[b],w=t?t(S):S;if(S=n||0!==S?S:0,!(v?c(v,w):l(g,w,n))){for(d=p;--d;){var _=h[d];if(!(_?c(_,w):l(e[d],w,n)))continue e}v&&v.push(w),g.push(S)}}return g}},function(e,t){e.exports=function(e){return this.__data__.set(e,"__lodash_hash_undefined__"),this}},function(e,t){e.exports=function(e){return this.__data__.has(e)}},function(e,t,n){var r=n(324),o=n(325),i=n(326);e.exports=function(e,t,n){return t==t?i(e,t,n):r(e,o,n)}},function(e,t){e.exports=function(e,t,n,r){for(var o=e.length,i=n+(r?1:-1);r?i--:++i<o;)if(t(e[i],i,e))return i;return-1}},function(e,t){e.exports=function(e){return e!=e}},function(e,t){e.exports=function(e,t,n){for(var r=n-1,o=e.length;++r<o;)if(e[r]===t)return r;return-1}},function(e,t){e.exports=function(e,t,n){switch(n.length){case 0:return e.call(t);case 1:return e.call(t,n[0]);case 2:return e.call(t,n[0],n[1]);case 3:return e.call(t,n[0],n[1],n[2])}return e.apply(t,n)}},function(e,t,n){var r=n(329),o=n(151),i=n(74),s=o?function(e,t){return o(e,"toString",{configurable:!0,enumerable:!1,value:r(t),writable:!0})}:i;e.exports=s},function(e,t){e.exports=function(e){return function(){return e}}},function(e,t){var n=Date.now;e.exports=function(e){var t=0,r=0;return function(){var o=n(),i=16-(o-r);if(r=o,i>0){if(++t>=800)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}},function(e,t,n){var r=n(332);e.exports=function(e){return r(e)?e:[]}},function(e,t,n){var r=n(38),o=n(15);e.exports=function(e){return o(e)&&r(e)}},function(e,t,n){var r=n(171),o=n(335),i=n(168),s=n(358),a=i((function(e,t){if(null==e)return[];var n=t.length;return n>1&&s(e,t[0],t[1])?t=[]:n>2&&s(t[0],t[1],t[2])&&(t=[t[0]]),o(e,r(t,1),[])}));e.exports=a},function(e,t,n){var r=n(36),o=n(108),i=n(12),s=r?r.isConcatSpreadable:void 0;e.exports=function(e){return i(e)||o(e)||!!(s&&e&&e[s])}},function(e,t,n){var r=n(51),o=n(50),i=n(121),s=n(350),a=n(355),c=n(37),u=n(356),l=n(74),f=n(12);e.exports=function(e,t,n){t=t.length?r(t,(function(e){return f(e)?function(t){return o(t,1===e.length?e[0]:e)}:e})):[l];var p=-1;t=r(t,c(i));var d=s(e,(function(e,n,o){return{criteria:r(t,(function(t){return t(e)})),index:++p,value:e}}));return a(d,(function(e,t){return u(e,t,n)}))}},function(e,t,n){var r=n(337),o=n(343),i=n(174);e.exports=function(e){var t=o(e);return 1==t.length&&t[0][2]?i(t[0][0],t[0][1]):function(n){return n===e||r(n,e,t)}}},function(e,t,n){var r=n(103),o=n(122);e.exports=function(e,t,n,i){var s=n.length,a=s,c=!i;if(null==e)return!a;for(e=Object(e);s--;){var u=n[s];if(c&&u[2]?u[1]!==e[u[0]]:!(u[0]in e))return!1}for(;++s<a;){var l=(u=n[s])[0],f=e[l],p=u[1];if(c&&u[2]){if(void 0===f&&!(l in e))return!1}else{var d=new r;if(i)var h=i(f,p,l,e,t,d);if(!(void 0===h?o(p,f,3,i,d):h))return!1}}return!0}},function(e,t,n){var r=n(103),o=n(172),i=n(340),s=n(342),a=n(70),c=n(12),u=n(109),l=n(153),f="[object Object]",p=Object.prototype.hasOwnProperty;e.exports=function(e,t,n,d,h,m){var g=c(e),y=c(t),b=g?"[object Array]":a(e),v=y?"[object Array]":a(t),S=(b="[object Arguments]"==b?f:b)==f,w=(v="[object Arguments]"==v?f:v)==f,_=b==v;if(_&&u(e)){if(!u(t))return!1;g=!0,S=!1}if(_&&!S)return m||(m=new r),g||l(e)?o(e,t,n,d,h,m):i(e,t,b,n,d,h,m);if(!(1&n)){var O=S&&p.call(e,"__wrapped__"),T=w&&p.call(t,"__wrapped__");if(O||T){var C=O?e.value():e,x=T?t.value():t;return m||(m=new r),h(C,x,n,d,m)}}return!!_&&(m||(m=new r),s(e,t,n,d,h,m))}},function(e,t){e.exports=function(e,t){for(var n=-1,r=null==e?0:e.length;++n<r;)if(t(e[n],n,e))return!0;return!1}},function(e,t,n){var r=n(36),o=n(161),i=n(65),s=n(172),a=n(341),c=n(123),u=r?r.prototype:void 0,l=u?u.valueOf:void 0;e.exports=function(e,t,n,r,u,f,p){switch(n){case"[object DataView]":if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case"[object ArrayBuffer]":return!(e.byteLength!=t.byteLength||!f(new o(e),new o(t)));case"[object Boolean]":case"[object Date]":case"[object Number]":return i(+e,+t);case"[object Error]":return e.name==t.name&&e.message==t.message;case"[object RegExp]":case"[object String]":return e==t+"";case"[object Map]":var d=a;case"[object Set]":var h=1&r;if(d||(d=c),e.size!=t.size&&!h)return!1;var m=p.get(e);if(m)return m==t;r|=2,p.set(e,t);var g=s(d(e),d(t),r,u,f,p);return p.delete(e),g;case"[object Symbol]":if(l)return l.call(e)==l.call(t)}return!1}},function(e,t){e.exports=function(e){var t=-1,n=Array(e.size);return e.forEach((function(e,r){n[++t]=[r,e]})),n}},function(e,t,n){var r=n(157),o=Object.prototype.hasOwnProperty;e.exports=function(e,t,n,i,s,a){var c=1&n,u=r(e),l=u.length;if(l!=r(t).length&&!c)return!1;for(var f=l;f--;){var p=u[f];if(!(c?p in t:o.call(t,p)))return!1}var d=a.get(e),h=a.get(t);if(d&&h)return d==t&&h==e;var m=!0;a.set(e,t),a.set(t,e);for(var g=c;++f<l;){var y=e[p=u[f]],b=t[p];if(i)var v=c?i(b,y,p,t,e,a):i(y,b,p,e,t,a);if(!(void 0===v?y===b||s(y,b,n,i,a):v)){m=!1;break}g||(g="constructor"==p)}if(m&&!g){var S=e.constructor,w=t.constructor;S!=w&&"constructor"in e&&"constructor"in t&&!("function"==typeof S&&S instanceof S&&"function"==typeof w&&w instanceof w)&&(m=!1)}return a.delete(e),a.delete(t),m}},function(e,t,n){var r=n(173),o=n(49);e.exports=function(e){for(var t=o(e),n=t.length;n--;){var i=t[n],s=e[i];t[n]=[i,s,r(s)]}return t}},function(e,t,n){var r=n(122),o=n(162),i=n(175),s=n(117),a=n(173),c=n(174),u=n(41);e.exports=function(e,t){return s(e)&&a(t)?c(u(e),t):function(n){var s=o(n,e);return void 0===s&&s===t?i(n,e):r(t,s,3)}}},function(e,t){e.exports=function(e,t){return null!=e&&t in Object(e)}},function(e,t,n){var r=n(39),o=n(108),i=n(12),s=n(68),a=n(110),c=n(41);e.exports=function(e,t,n){for(var u=-1,l=(t=r(t,e)).length,f=!1;++u<l;){var p=c(t[u]);if(!(f=null!=e&&n(e,p)))break;e=e[p]}return f||++u!=l?f:!!(l=null==e?0:e.length)&&a(l)&&s(p,l)&&(i(e)||o(e))}},function(e,t,n){var r=n(348),o=n(349),i=n(117),s=n(41);e.exports=function(e){return i(e)?r(s(e)):o(e)}},function(e,t){e.exports=function(e){return function(t){return null==t?void 0:t[e]}}},function(e,t,n){var r=n(50);e.exports=function(e){return function(t){return r(t,e)}}},function(e,t,n){var r=n(176),o=n(38);e.exports=function(e,t){var n=-1,i=o(e)?Array(e.length):[];return r(e,(function(e,r,o){i[++n]=t(e,r,o)})),i}},function(e,t,n){var r=n(352),o=n(49);e.exports=function(e,t){return e&&r(e,t,o)}},function(e,t,n){var r=n(353)();e.exports=r},function(e,t){e.exports=function(e){return function(t,n,r){for(var o=-1,i=Object(t),s=r(t),a=s.length;a--;){var c=s[e?a:++o];if(!1===n(i[c],c,i))break}return t}}},function(e,t,n){var r=n(38);e.exports=function(e,t){return function(n,o){if(null==n)return n;if(!r(n))return e(n,o);for(var i=n.length,s=t?i:-1,a=Object(n);(t?s--:++s<i)&&!1!==o(a[s],s,a););return n}}},function(e,t){e.exports=function(e,t){var n=e.length;for(e.sort(t);n--;)e[n]=e[n].value;return e}},function(e,t,n){var r=n(357);e.exports=function(e,t,n){for(var o=-1,i=e.criteria,s=t.criteria,a=i.length,c=n.length;++o<a;){var u=r(i[o],s[o]);if(u)return o>=c?u:u*("desc"==n[o]?-1:1)}return e.index-t.index}},function(e,t,n){var r=n(71);e.exports=function(e,t){if(e!==t){var n=void 0!==e,o=null===e,i=e==e,s=r(e),a=void 0!==t,c=null===t,u=t==t,l=r(t);if(!c&&!l&&!s&&e>t||s&&a&&u&&!c&&!l||o&&a&&u||!n&&u||!i)return 1;if(!o&&!s&&!l&&e<t||l&&n&&i&&!o&&!s||c&&n&&i||!a&&i||!u)return-1}return 0}},function(e,t,n){var r=n(65),o=n(38),i=n(68),s=n(28);e.exports=function(e,t,n){if(!s(n))return!1;var a=typeof t;return!!("number"==a?o(n)&&i(t,n.length):"string"==a&&t in n)&&r(n[t],e)}},function(e,t,n){var r=n(107),o=n(360),i=Object.prototype.hasOwnProperty,s=o((function(e,t,n){i.call(e,n)?e[n].push(t):r(e,n,[t])}));e.exports=s},function(e,t,n){var r=n(361),o=n(362),i=n(121),s=n(12);e.exports=function(e,t){return function(n,a){var c=s(n)?r:o,u=t?t():{};return c(n,e,i(a,2),u)}}},function(e,t){e.exports=function(e,t,n,r){for(var o=-1,i=null==e?0:e.length;++o<i;){var s=e[o];t(r,s,n(s),e)}return r}},function(e,t,n){var r=n(176);e.exports=function(e,t,n,o){return r(e,(function(e,r,i){t(o,e,n(e),i)})),o}},function(e,t,n){var r=n(364),o=n(175);e.exports=function(e,t){return r(e,t,(function(t,n){return o(e,n)}))}},function(e,t,n){var r=n(50),o=n(365),i=n(39);e.exports=function(e,t,n){for(var s=-1,a=t.length,c={};++s<a;){var u=t[s],l=r(e,u);n(l,u)&&o(c,i(u,e),l)}return c}},function(e,t,n){var r=n(106),o=n(39),i=n(68),s=n(28),a=n(41);e.exports=function(e,t,n,c){if(!s(e))return e;for(var u=-1,l=(t=o(t,e)).length,f=l-1,p=e;null!=p&&++u<l;){var d=a(t[u]),h=n;if("__proto__"===d||"constructor"===d||"prototype"===d)return e;if(u!=f){var m=p[d];void 0===(h=c?c(m,d,p):void 0)&&(h=s(m)?m:i(t[u+1])?[]:{})}r(p,d,h),p=p[d]}return e}},function(e,t,n){"use strict";var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function s(e){try{c(r.next(e))}catch(e){i(e)}}function a(e){try{c(r.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((r=r.apply(e,t||[])).next())}))},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.driverBase=void 0;const i=o(n(52)),s=n(179),a=n(371),c=n(373),u={limitSelect:!0,rangeSelect:!0,offsetFetchRangeSyntax:!0,stringEscapeChar:"'",fallbackDataType:"nvarchar(max)",quoteIdentifier:e=>e,columnProperties:{isSparse:!1,isPersisted:!1}};t.driverBase={analyserClass:null,dumperClass:s.SqlDumper,dialect:u,databaseEngineTypes:["sql"],analyseFull(e,t){return r(this,void 0,void 0,(function*(){return new this.analyserClass(e,this,t).fullAnalysis()}))},analyseSingleObject(e,t,n="tables"){return r(this,void 0,void 0,(function*(){return new this.analyserClass(e,this).singleObjectAnalysis(t,n)}))},analyseSingleTable(e,t){return this.analyseSingleObject(e,t,"tables")},analyseIncremental(e,t,n){return r(this,void 0,void 0,(function*(){return new this.analyserClass(e,this,n).incrementalAnalysis(t)}))},createDumper(e=null){return new this.dumperClass(this,e)},script(e,t){return r(this,void 0,void 0,(function*(){for(const n of(0,a.splitQuery)(t,this.getQuerySplitterOptions("script")))yield this.query(e,n,{discardResult:!0})}))},getNewObjectTemplates(){return this.databaseEngineTypes.includes("sql")?[{label:"New view",sql:"CREATE VIEW myview\nAS\nSELECT * FROM table1"}]:[]},loadFieldValues(e,t,n,o){return r(this,void 0,void 0,(function*(){const r=this.createDumper(),s={commandType:"select",distinct:!0,topRecords:100,from:{name:t},columns:[{exprType:"column",columnName:n,alias:"value"}],orderBy:[{exprType:"column",columnName:n}]};if(o){const e=(0,i.default)(o.split(" ").map(e=>e.trim()));e.length>0&&(s.where={conditionType:"and",conditions:e.map(e=>({conditionType:"like",left:{exprType:"column",columnName:n},right:{exprType:"value",value:`%${e}%`}}))})}return(0,c.dumpSqlSelect)(r,s),(yield this.query(e,r.s)).rows}))},readJsonQuery(e,t,n){const r=this.createDumper();return(0,c.dumpSqlSelect)(r,t),this.readQuery(e,r.s,n)}}},function(e,t,n){var r=n(368),o=n(37),i=n(69),s=i&&i.isDate,a=s?o(s):r;e.exports=a},function(e,t,n){var r=n(25),o=n(15);e.exports=function(e){return o(e)&&"[object Date]"==r(e)}},function(e,t,n){var r=n(20);e.exports=function(){return r.randomBytes(16)}},function(e,t){for(var n=[],r=0;r<256;++r)n[r]=(r+256).toString(16).substr(1);e.exports=function(e,t){var r=t||0,o=n;return[o[e[r++]],o[e[r++]],o[e[r++]],o[e[r++]],"-",o[e[r++]],o[e[r++]],"-",o[e[r++]],o[e[r++]],"-",o[e[r++]],o[e[r++]],"-",o[e[r++]],o[e[r++]],o[e[r++]],o[e[r++]],o[e[r++]],o[e[r++]]].join("")}},function(e,t,n){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),o=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||r(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),t.splitQuery=void 0;var i=n(372);Object.defineProperty(t,"splitQuery",{enumerable:!0,get:function(){return i.splitQuery}}),o(n(101),t)},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.splitQuery=t.finishSplitStream=t.getInitialDelimiter=t.splitQueryLine=void 0;const r=n(101);function o(e,t){if(e.options.returnRichInfo){let{source:n,position:r,line:o,column:i,streamPosition:s}=e;for(;t>0;)"\n"==n[r]?(o+=1,i=0):i+=1,r+=1,s+=1,t-=1;e.position=r,e.streamPosition=s,e.line=o,e.column=i}else e.position+=t}function i(e,t,n,r){return r?n==r?e[t]==n&&e[t+1]!=n:e[t]==n&&e[t-1]!=r:e[t]==n}const s={type:"whitespace",length:1},a={type:"eoln",length:1},c={type:"data",length:1};function u(e){let t=e.position;const n=e.source,r=n[t];if(e.options.stringsBegins.includes(r)){t++;const o=e.options.stringsEnds[r],s=e.options.stringEscapes[r];for(;t<e.end&&!i(n,t,o,s);)o==s&&n[t]==o&&n[t+1]==o?t+=2:t++;return{type:"string",length:t-e.position+1}}if(e.currentDelimiter&&n.slice(t).startsWith(e.currentDelimiter))return{type:"delimiter",length:e.currentDelimiter.length};if(" "==r||"\t"==r||"\r"==r)return s;if("\n"==r)return a;if(e.options.doubleDashComments&&"-"==r&&"-"==n[t+1]){for(;t<e.end&&"\n"!=n[t];)t++;return{type:"comment",length:t-e.position}}if(e.options.multilineComments&&"/"==r&&"*"==n[t+1]){for(t+=2;t<e.end&&("*"!=n[t]||"/"!=n[t+1]);)t++;return{type:"comment",length:t-e.position+2}}if(e.options.allowCustomDelimiter&&!e.wasDataOnLine){const e=n.slice(t).match(/^DELIMITER[ \t]+([^\n]+)/i);if(e)return{type:"set_delimiter",value:e[1].trim(),length:e[0].length}}if(e.options.allowGoDelimiter&&!e.wasDataOnLine){const e=n.slice(t).match(/^GO[\t\r ]*(\n|$)/i);if(e)return{type:"go_delimiter",length:e[0].length-1}}const o=function(e){if(!e.options.allowDollarDollarString)return null;let t=e.position;const n=e.source,r=/^(\$[a-zA-Z0-9_]*\$)/.exec(n.slice(t));if(!r)return null;const o=r[1];for(t+=o.length;t<e.end;){if(n.slice(t).startsWith(o))return{type:"string",length:t+o.length-e.position};t++}return null}(e);return o||c}function l(e){const t=(e.commandPart||"")+e.source.slice(e.currentCommandStart,e.position),n=t.trim();n&&(e.options.returnRichInfo?e.pushOutput(f(t,{text:n,start:{position:e.commandStartPosition,line:e.commandStartLine,column:e.commandStartColumn},end:{position:e.streamPosition,line:e.line,column:e.column}})):e.pushOutput(n))}function f(e,t){const n=e.indexOf(t.text),r=Object.assign({},t.start);for(let t=0;t<n;t+=1)"\n"==e[t]?(r.position+=1,r.line+=1,r.column=0):(r.position+=1,r.column+=1);return Object.assign(Object.assign({},t),{trimStart:r,trimEnd:t.end})}function p(e){e.options.returnRichInfo&&(e.commandStartPosition=e.streamPosition,e.commandStartLine=e.line,e.commandStartColumn=e.column)}function d(e){for(;e.position<e.end;){const t=u(e);if(t)switch(t.type){case"string":case"comment":o(e,t.length),e.wasDataOnLine=!0;break;case"eoln":o(e,t.length),e.wasDataOnLine=!1;break;case"data":o(e,t.length),e.wasDataOnLine=!0;break;case"whitespace":o(e,t.length);break;case"set_delimiter":l(e),e.commandPart="",e.currentDelimiter=t.value,o(e,t.length),e.currentCommandStart=e.position,p(e);break;case"go_delimiter":case"delimiter":l(e),e.commandPart="",o(e,t.length),e.currentCommandStart=e.position,p(e)}else o(e,1)}e.end>e.currentCommandStart&&(e.commandPart+=e.source.slice(e.currentCommandStart,e.position))}function h(e){return!1===(null==e?void 0:e.allowSemicolon)?null:";"}function m(e){const t=e.commandPart.trim();t&&(e.options.returnRichInfo?e.pushOutput(f(e.commandPart,{text:t,start:{position:e.commandStartPosition,line:e.commandStartLine,column:e.commandStartColumn},end:{position:e.streamPosition,line:e.line,column:e.column}})):e.pushOutput(t))}t.splitQueryLine=d,t.getInitialDelimiter=h,t.finishSplitStream=m,t.splitQuery=function(e,t=null){var n;const o=Object.assign(Object.assign({},r.defaultSplitterOptions),t);if(o.noSplit){if(o.returnRichInfo){const t=e.split("\n");return[{text:e,start:{position:0,line:0,column:0},end:{position:e.length,line:t.length,column:(null===(n=t[t.length-1])||void 0===n?void 0:n.length)||0}}]}return[e]}const i=[],s={source:e,end:e.length,currentDelimiter:h(t),position:0,column:0,line:0,currentCommandStart:0,commandStartLine:0,commandStartColumn:0,commandStartPosition:0,streamPosition:0,pushOutput:e=>i.push(e),wasDataOnLine:!1,options:o,commandPart:""};return d(s),m(s),i}},function(e,t,n){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),o=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||r(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),o(n(374),t),o(n(76),t),o(n(375),t),o(n(126),t),o(n(127),t),o(n(376),t),o(n(181),t)},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.mergeConditions=t.scriptToSql=t.treeToSql=void 0;const r=n(76);t.treeToSql=function(e,t,n){const r=e.createDumper();return n(r,t),r.s},t.scriptToSql=function(e,t){const n=e.createDumper();for(const e of t)(0,r.dumpSqlCommand)(n,e),n.endCommand();return n.s},t.mergeConditions=function(e,t){return e?t?"and"==e.conditionType&&"and"==t.conditionType?{conditionType:"and",conditions:[...e.conditions,...t.conditions]}:"and"==e.conditionType?{conditionType:"and",conditions:[...e.conditions,t]}:"and"==t.conditionType?{conditionType:"and",conditions:[e,...t.conditions]}:{conditionType:"and",conditions:[e,t]}:e:t}},function(e,t,n){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.evaluateCondition=void 0;const o=r(n(24)),i=n(181);function s(e){return null==e||""==e.toString().trim()}function a(e,t){if(!e)return!1;if(!t)return!1;const n=new RegExp(`^${o.default.escapeRegExp(t).replace(/%/g,".*")}$`,"i");return!!e.toString().match(n)}t.evaluateCondition=function e(t,n){switch(t.conditionType){case"binary":const r=(0,i.evaluateExpression)(t.left,n),o=(0,i.evaluateExpression)(t.right,n);switch(t.operator){case"=":return r==o;case"!=":case"<>":return r!=o;case"<=":return r<=o;case">=":return r>=o;case"<":return r<o;case">":return r>o}break;case"isNull":return null==(0,i.evaluateExpression)(t.expr,n);case"isNotNull":return null!=(0,i.evaluateExpression)(t.expr,n);case"isEmpty":return s((0,i.evaluateExpression)(t.expr,n));case"isNotEmpty":return!s((0,i.evaluateExpression)(t.expr,n));case"and":return t.conditions.every(t=>e(t,n));case"or":return t.conditions.some(t=>e(t,n));case"like":return a((0,i.evaluateExpression)(t.left,n),(0,i.evaluateExpression)(t.right,n));case"notLike":return!a((0,i.evaluateExpression)(t.left,n),(0,i.evaluateExpression)(t.right,n));case"not":return!e(t.condition,n)}}},function(e,t,n){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.testPermission=t.compilePermissions=void 0;const o=r(n(378)),i=r(n(72)),s=r(n(52)),a=r(n(75));function c(e){return 0==e.length?null:new RegExp(e.map(e=>"^"+(0,o.default)(e).replace(/\\\*/g,".*")+"$").join("|"))}t.compilePermissions=function(e){if(!e)return null;e=(0,i.default)(e)?e.split(/,|;|\||\s/):(0,a.default)(e.map(e=>e.split(/,|;|\||\s/))),e=(0,s.default)(e.map(e=>e.trim()));let t=null,n=[];const r={levels:[]};for(const o of e){const e=o.startsWith("~")?"deny":"allow",i=o.startsWith("~")?o.substring(1):o;null!=t&&e!=t&&(r.levels.push({re:c(n),type:t}),n=[]),n.push(i),t=e}return n.length>0&&r.levels.push({re:c(n),type:t}),r},t.testPermission=function(e,t){let n=!0;if(!t)return!0;for(const r of t.levels)e.match(r.re)&&("allow"==r.type&&(n=!0),"deny"==r.type&&(n=!1));return n}},function(e,t,n){var r=n(40),o=/[\\^$.*+?()[\]{}|]/g,i=RegExp(o.source);e.exports=function(e){return(e=r(e))&&i.test(e)?e.replace(o,"\\$&"):e}},function(e,t,n){"use strict";var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function s(e){try{c(r.next(e))}catch(e){i(e)}}function a(e){try{c(r.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((r=r.apply(e,t||[])).next())}))},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.SqlGenerator=void 0;const i=o(n(75)),s=o(n(380)),a=n(183);t.SqlGenerator=class{constructor(e,t,n,r,o,i){this.options=t,this.objects=n,this.dmp=r,this.driver=o,this.pool=i,this.isTruncated=!1,this.isUnhandledException=!1,this.handleException=e=>{console.log("Unhandled error",e),this.isUnhandledException=!0},this.dbinfo=(0,a.extendDatabaseInfo)(e),this.tables=this.extract("tables"),this.views=this.extract("views"),this.matviews=this.extract("matviews"),this.procedures=this.extract("procedures"),this.functions=this.extract("functions"),this.triggers=this.extract("triggers")}dump(){return r(this,void 0,void 0,(function*(){try{if(process.on("uncaughtException",this.handleException),this.dropObjects(this.procedures,"Procedure"),this.checkDumper())return;if(this.dropObjects(this.functions,"Function"),this.checkDumper())return;if(this.dropObjects(this.views,"View"),this.checkDumper())return;if(this.dropObjects(this.matviews,"Matview"),this.checkDumper())return;if(this.dropObjects(this.triggers,"Trigger"),this.checkDumper())return;if(this.dropTables(),this.checkDumper())return;if(this.createTables(),this.checkDumper())return;if(this.truncateTables(),this.checkDumper())return;if(yield this.insertData(),this.checkDumper())return;if(this.createForeignKeys(),this.checkDumper())return;if(this.createObjects(this.procedures,"Procedure"),this.checkDumper())return;if(this.createObjects(this.functions,"Function"),this.checkDumper())return;if(this.createObjects(this.views,"View"),this.checkDumper())return;if(this.createObjects(this.matviews,"Matview"),this.checkDumper())return;if(this.createObjects(this.triggers,"Trigger"),this.checkDumper())return}finally{process.off("uncaughtException",this.handleException)}}))}createForeignKeys(){const e=[];this.options.createForeignKeys&&e.push(...(0,i.default)(this.tables.map(e=>e.foreignKeys||[]))),this.options.createReferences&&e.push(...(0,i.default)(this.tables.map(e=>e.dependencies||[])));for(const t of(0,s.default)(e,"constraintName"))if(this.dmp.createForeignKey(t),this.checkDumper())return}truncateTables(){if(this.options.truncate)for(const e of this.tables)if(this.dmp.truncateTable(e),this.checkDumper())return}createTables(){if(this.options.createTables)for(const e of this.tables)if(this.dmp.createTable(Object.assign(Object.assign({},e),{foreignKeys:[],dependencies:[],indexes:[]})),this.checkDumper())return;if(this.options.createIndexes)for(const e of(0,i.default)(this.tables.map(e=>e.indexes||[])))this.dmp.createIndex(e)}insertData(){return r(this,void 0,void 0,(function*(){if(this.options.insert){this.enableConstraints(!1);for(const e of this.tables)if(yield this.insertTableData(e),this.checkDumper())return;this.enableConstraints(!0)}}))}checkDumper(){return this.dmp.s.length>4e6&&(this.isTruncated||(this.dmp.putRaw("\n"),this.dmp.comment(" *************** SQL is truncated ******************"),this.dmp.putRaw("\n")),this.isTruncated=!0,!0)}dropObjects(e,t){if(this.options[`drop${t}s`])for(const n of e)if(this.dmp[`drop${t}`](n,{testIfExists:this.options[`checkIf${t}Exists`]}),this.checkDumper())return}createObjects(e,t){if(this.options[`create${t}s`])for(const n of e)if(this.dmp[`create${t}`](n),this.checkDumper())return}dropTables(){if(this.options.dropReferences)for(const e of(0,i.default)(this.tables.map(e=>e.dependencies||[])))this.dmp.dropForeignKey(e);if(this.options.dropTables)for(const e of this.tables)this.dmp.dropTable(e,{testIfExists:this.options.checkIfTableExists})}insertTableData(e){return r(this,void 0,void 0,(function*(){const t=this.driver.createDumper();t.put("^select * ^from %f",e);const n=e.columns.find(e=>e.autoIncrement);n&&!this.options.skipAutoincrementColumn&&this.dmp.allowIdentityInsert(e,!0);const r=yield this.driver.readQuery(this.pool,t.s,e);yield this.processReadable(e,r),n&&!this.options.skipAutoincrementColumn&&this.dmp.allowIdentityInsert(e,!1)}))}processReadable(e,t){const n=(this.options.skipAutoincrementColumn?e.columns.filter(e=>!e.autoIncrement):e.columns).map(e=>e.columnName);let r=!1,o=!1;return new Promise(i=>{t.on("data",s=>{if(r)return;if(!o)return void(o=!0);if(this.checkDumper())return r=!0,i(void 0),void t.destroy();const a=this.options.omitNulls?n.filter(e=>null!=s[e]):n;this.dmp.put("^insert ^into %f (%,i) ^values (%,v);&n",e,a,a.map(e=>s[e]))}),t.on("end",()=>{i(void 0)})})}extract(e){return this.dbinfo[e].filter(t=>this.objects.find(n=>t.pureName==n.pureName&&t.schemaName==n.schemaName&&n.objectTypeField==e))}enableConstraints(e){if(this.options.disableConstraints)if(this.driver.dialect.enableConstraintsPerTable)for(const t of this.tables)this.dmp.enableConstraints(t,e);else this.dmp.enableConstraints(null,e)}}},function(e,t,n){var r=n(121),o=n(182);e.exports=function(e,t){return e&&e.length?o(e,r(t,2)):[]}},function(e,t,n){var r=n(160),o=n(382),i=n(123),s=r&&1/i(new r([,-0]))[1]==1/0?function(e){return new r(e)}:o;e.exports=s},function(e,t){e.exports=function(){}},function(e,t,n){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.extractBoolSettingsValue=t.extractIntSettingsValue=void 0;const o=r(n(384)),i=r(n(124));t.extractIntSettingsValue=function(e,t,n,r=null,s=null){const a=parseInt(e[t]);return(0,o.default)(a)?n:(0,i.default)(a)?null!=r&&a<r?r:null!=s&&a>s?s:a:n},t.extractBoolSettingsValue=function(e,t,n){const r=e[t];return null==r?n:!!r}},function(e,t,n){var r=n(124);e.exports=function(e){return r(e)&&e!=+e}},function(e,t,n){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.filterName=void 0;const o=r(n(52));function i(e,t){var n=t.length,r=e.length;if(r>n)return!1;if(r===n)return e===t;e:for(var o=0,i=0;o<r;o++){for(var s=e.charCodeAt(o);i<n;)if(t.charCodeAt(i++)===s)continue e;return!1}return!0}t.filterName=function(e,...t){if(!e)return!0;const n=e.split(" ").map(e=>e.trim()),r=(0,o.default)(t);for(const e of n){const t=e.toUpperCase();if(!r.find(e=>i(t,e.toUpperCase())))return!1}return!0}},function(e,t,n){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.runAlterOperation=t.AlterPlan=void 0;const o=r(n(24)),i=n(128),s=n(387),a=n(120);function c(e,t){switch(e.operationType){case"createTable":t.createTable(e.newObject);break;case"changeColumn":t.changeColumn(e.oldObject,e.newObject);break;case"createColumn":t.createColumn(e.newObject,[]);break;case"dropColumn":t.dropColumn(e.oldObject);break;case"dropTable":t.dropTable(e.oldObject);break;case"changeConstraint":t.changeConstraint(e.oldObject,e.newObject);break;case"createConstraint":t.createConstraint(e.newObject);break;case"dropConstraint":t.dropConstraint(e.oldObject);break;case"renameColumn":t.renameColumn(e.object,e.newName);break;case"renameTable":t.renameTable(e.object,e.newName);break;case"renameConstraint":t.renameConstraint(e.object,e.newName);break;case"createSqlObject":t.createSqlObject(e.newObject);break;case"dropSqlObject":t.dropSqlObject(e.oldObject);break;case"fillPreloadedRows":t.fillPreloadedRows(e.table,e.oldRows,e.newRows,e.key,e.insertOnly);break;case"recreateTable":{const n=(0,i.generateTablePairingId)(e.table),r=o.default.cloneDeep(n),u=a.DatabaseAnalyser.createEmptyStructure();u.tables.push(r),e.operations.forEach(e=>c(e,new s.DatabaseInfoAlterProcessor(u))),t.recreateTable(n,r)}}}t.AlterPlan=class{constructor(e,t,n,r){this.wholeOldDb=e,this.wholeNewDb=t,this.dialect=n,this.opts=r,this.recreates={tables:0,constraints:0,sqlObjects:0},this.operations=[]}createTable(e){this.operations.push({operationType:"createTable",newObject:e})}dropTable(e){this.operations.push({operationType:"dropTable",oldObject:e})}createSqlObject(e){this.operations.push({operationType:"createSqlObject",newObject:e})}dropSqlObject(e){this.operations.push({operationType:"dropSqlObject",oldObject:e})}createColumn(e){this.operations.push({operationType:"createColumn",newObject:e})}changeColumn(e,t){this.operations.push({operationType:"changeColumn",oldObject:e,newObject:t})}dropColumn(e){this.operations.push({operationType:"dropColumn",oldObject:e})}createConstraint(e){this.operations.push({operationType:"createConstraint",newObject:e})}changeConstraint(e,t){this.operations.push({operationType:"changeConstraint",oldObject:e,newObject:t})}dropConstraint(e){this.operations.push({operationType:"dropConstraint",oldObject:e})}renameTable(e,t){this.operations.push({operationType:"renameTable",object:e,newName:t})}renameColumn(e,t){this.operations.push({operationType:"renameColumn",object:e,newName:t})}renameConstraint(e,t){this.operations.push({operationType:"renameConstraint",object:e,newName:t})}recreateTable(e,t){this.operations.push({operationType:"recreateTable",table:e,operations:t}),this.recreates.tables+=1}fillPreloadedRows(e,t,n,r,o){this.operations.push({operationType:"fillPreloadedRows",table:e,oldRows:t,newRows:n,key:r,insertOnly:o})}run(e){for(const t of this.operations)c(t,e)}_getDependendColumnConstraints(e,t){const n=this.wholeOldDb.tables.find(t=>t.pureName==e.pureName&&t.schemaName==e.schemaName);return n?[...(null==t?void 0:t.includes("dependencies"))?n.dependencies.filter(t=>t.columns.find(t=>t.refColumnName==e.columnName)):[],...o.default.compact([(null==t?void 0:t.includes("primaryKey"))?n.primaryKey:null,...(null==t?void 0:t.includes("foreignKeys"))?n.foreignKeys:[],...(null==t?void 0:t.includes("indexes"))?n.indexes:[],...(null==t?void 0:t.includes("uniques"))?n.uniques:[]]).filter(t=>t.columns.find(t=>t.columnName==e.columnName))]:[]}_addLogicalDependencies(){const e=this.operations.map(e=>{if("dropColumn"==e.operationType){const t=this._getDependendColumnConstraints(e.oldObject,this.dialect.dropColumnDependencies);return t.length>0&&this.opts.noDropConstraint?[]:[...t.map(e=>({operationType:"dropConstraint",oldObject:e})),e]}if("changeColumn"==e.operationType){const t=this._getDependendColumnConstraints(e.oldObject,this.dialect.changeColumnDependencies);if(t.length>0&&this.opts.noDropConstraint)return[];const n=[...t.map(e=>({operationType:"dropConstraint",oldObject:e})),e,...o.default.reverse([...t]).map(e=>({operationType:"createConstraint",newObject:e}))];return t.length>0&&(this.recreates.constraints+=1),n}if("dropTable"==e.operationType)return[...this.dialect.dropReferencesWhenDropTable?(e.oldObject.dependencies||[]).map(e=>({operationType:"dropConstraint",oldObject:e})):[],e];if("changeConstraint"==e.operationType){if(this.opts.noDropConstraint)return[];return this.recreates.constraints+=1,[{operationType:"dropConstraint",oldObject:e.oldObject},{operationType:"createConstraint",newObject:e.newObject}]}return[e]});return o.default.flatten(e)}_transformToImplementedOps(){const e=this.operations.map(e=>this._testTableRecreate(e,"createColumn",this.dialect.createColumn,"newObject")||this._testTableRecreate(e,"dropColumn",this.dialect.dropColumn,"oldObject")||this._testTableRecreate(e,"createConstraint",e=>this._canCreateConstraint(e),"newObject")||this._testTableRecreate(e,"dropConstraint",e=>this._canDropConstraint(e),"oldObject")||this._testTableRecreate(e,"changeColumn",this.dialect.changeColumn,"newObject")||[e]);return o.default.flatten(e)}_canCreateConstraint(e){return"primaryKey"==e.constraintType?this.dialect.createPrimaryKey:"foreignKey"==e.constraintType?this.dialect.createForeignKey:"index"==e.constraintType?this.dialect.createIndex:"unique"==e.constraintType?this.dialect.createUnique:"check"==e.constraintType?this.dialect.createCheck:null}_canDropConstraint(e){return"primaryKey"==e.constraintType?this.dialect.dropPrimaryKey:"foreignKey"==e.constraintType?this.dialect.dropForeignKey:"index"==e.constraintType?this.dialect.dropIndex:"unique"==e.constraintType?this.dialect.dropUnique:"check"==e.constraintType?this.dialect.dropCheck:null}_testTableRecreate(e,t,n,r){if(e.operationType==t){if(o.default.isFunction(n)){if(n(e[r]))return null}else if(n)return null;if(this.opts.noDropTable)return[];const t=this.wholeNewDb.tables.find(t=>t.pureName==e[r].pureName&&t.schemaName==e[r].schemaName);return this.recreates.tables+=1,[{operationType:"recreateTable",table:t,operations:[e]}]}return null}_groupTableRecreations(){const e=[],t={};for(const n of this.operations)if("recreateTable"==n.operationType&&n.table){const r=t[`${n.table.schemaName}||${n.table.pureName}`];if(r)r.operations.push(...n.operations);else{const r=Object.assign(Object.assign({},n),{operations:[...n.operations]});e.push(r),t[`${n.table.schemaName}||${n.table.pureName}`]=r}}else{const r=n.oldObject;if(r){const e=t[`${r.schemaName}||${r.pureName}`];if(e){e.operations.push(n);continue}}e.push(n)}return e}_moveForeignKeysToLast(){if(!this.dialect.createForeignKey)return this.operations;const e=[];return[...this.operations.map(t=>"createTable"==t.operationType?(e.push(...t.newObject.foreignKeys||[]),Object.assign(Object.assign({},t),{newObject:Object.assign(Object.assign({},t.newObject),{foreignKeys:[]})})):t),...e.map(e=>({operationType:"createConstraint",newObject:e}))]}_filterAllowedOperations(){return this.operations.filter(e=>(!this.opts.noDropColumn||"dropColumn"!=e.operationType)&&((!this.opts.noDropTable||"dropTable"!=e.operationType)&&((!this.opts.noDropTable||"recreateTable"!=e.operationType)&&((!this.opts.noDropConstraint||"dropConstraint"!=e.operationType)&&(!this.opts.noDropSqlObject||"dropSqlObject"!=e.operationType)))))}transformPlan(){this.operations=this._addLogicalDependencies(),this.operations=this._transformToImplementedOps(),this.operations=this._groupTableRecreations(),this.operations=this._moveForeignKeysToLast(),this.operations=this._filterAllowedOperations()}},t.runAlterOperation=c},function(e,t,n){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DatabaseInfoAlterProcessor=void 0;const o=r(n(24));t.DatabaseInfoAlterProcessor=class{constructor(e){this.db=e}createTable(e){this.db.tables.push(e)}dropTable(e){o.default.remove(this.db.tables,t=>t.pureName==e.pureName&&t.schemaName==e.schemaName)}createSqlObject(e){this.db[e.objectTypeField].push(e)}dropSqlObject(e){o.default.remove(this.db[e.objectTypeField],t=>t.pureName==e.pureName&&t.schemaName==e.schemaName)}createColumn(e){const t=this.db.tables.find(t=>t.pureName==e.pureName&&t.schemaName==e.schemaName);if(!t)throw new Error(`createColumn error, cannot find table: ${e.schemaName}.${e.pureName}`);t.columns.push(e)}changeColumn(e,t){const n=this.db.tables.find(t=>t.pureName==e.pureName&&t.schemaName==e.schemaName);if(!n)throw new Error(`changeColumn error, cannot find table: ${e.schemaName}.${e.pureName}`);n.columns=n.columns.map(n=>n.columnName==e.columnName?t:n)}dropColumn(e){const t=this.db.tables.find(t=>t.pureName==e.pureName&&t.schemaName==e.schemaName);if(!t)throw new Error(`dropColumn error, cannot find table: ${e.schemaName}.${e.pureName}`);o.default.remove(t.columns,t=>t.columnName==e.columnName)}createConstraint(e){const t=this.db.tables.find(t=>t.pureName==e.pureName&&t.schemaName==e.schemaName);switch(e.constraintType){case"primaryKey":t.primaryKey=e;break;case"foreignKey":t.foreignKeys.push(e);break;case"index":t.indexes.push(e);break;case"unique":t.uniques.push(e);break;case"check":t.checks.push(e)}}changeConstraint(e,t){this.db.tables.find(t=>t.pureName==e.pureName&&t.schemaName==e.schemaName)}dropConstraint(e){const t=this.db.tables.find(t=>t.pureName==e.pureName&&t.schemaName==e.schemaName);switch(e.constraintType){case"primaryKey":t.primaryKey=null;break;case"foreignKey":t.foreignKeys=t.foreignKeys.filter(t=>t.constraintName!=e.constraintName);break;case"index":t.indexes=t.indexes.filter(t=>t.constraintName!=e.constraintName);break;case"unique":t.uniques=t.uniques.filter(t=>t.constraintName!=e.constraintName);break;case"check":t.checks=t.checks.filter(t=>t.constraintName!=e.constraintName)}}renameTable(e,t){this.db.tables.find(t=>t.pureName==e.pureName&&t.schemaName==e.schemaName).pureName=t}renameColumn(e,t){this.db.tables.find(t=>t.pureName==e.pureName&&t.schemaName==e.schemaName).columns.find(t=>t.columnName==e.columnName).columnName=t}renameConstraint(e,t){}recreateTable(e,t){throw new Error("recreateTable not implemented for DatabaseInfoAlterProcessor")}fillPreloadedRows(e,t,n,r,o){const i=this.db.tables.find(t=>t.pureName==e.pureName&&t.schemaName==e.schemaName);i.preloadedRows=n,i.preloadedRowsKey=r,i.preloadedRowsInsertOnly=o}}},function(e,t,n){var r="undefined"!=typeof JSON?JSON:n(389);e.exports=function(e,t){t||(t={}),"function"==typeof t&&(t={cmp:t});var n=t.space||"";"number"==typeof n&&(n=Array(n+1).join(" "));var s,a="boolean"==typeof t.cycles&&t.cycles,c=t.replacer||function(e,t){return t},u=t.cmp&&(s=t.cmp,function(e){return function(t,n){var r={key:t,value:e[t]},o={key:n,value:e[n]};return s(r,o)}}),l=[];return function e(t,s,f,p){var d=n?"\n"+new Array(p+1).join(n):"",h=n?": ":":";if(f&&f.toJSON&&"function"==typeof f.toJSON&&(f=f.toJSON()),void 0!==(f=c.call(t,s,f))){if("object"!=typeof f||null===f)return r.stringify(f);if(o(f)){for(var m=[],g=0;g<f.length;g++){var y=e(f,g,f[g],p+1)||r.stringify(null);m.push(d+n+y)}return"["+m.join(",")+d+"]"}if(-1!==l.indexOf(f)){if(a)return r.stringify("__cycle__");throw new TypeError("Converting circular structure to JSON")}l.push(f);var b=i(f).sort(u&&u(f));for(m=[],g=0;g<b.length;g++){var v=e(f,s=b[g],f[s],p+1);if(v){var S=r.stringify(s)+h+v;m.push(d+n+S)}}return l.splice(l.indexOf(f),1),"{"+m.join(",")+d+"}"}}({"":e},"",e,0)};var o=Array.isArray||function(e){return"[object Array]"==={}.toString.call(e)},i=Object.keys||function(e){var t=Object.prototype.hasOwnProperty||function(){return!0},n=[];for(var r in e)t.call(e,r)&&n.push(r);return n}},function(e,t,n){t.parse=n(390),t.stringify=n(391)},function(e,t){var n,r,o,i,s={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:"\n",r:"\r",t:"\t"},a=function(e){throw{name:"SyntaxError",message:e,at:n,text:o}},c=function(e){return e&&e!==r&&a("Expected '"+e+"' instead of '"+r+"'"),r=o.charAt(n),n+=1,r},u=function(){var e,t="";for("-"===r&&(t="-",c("-"));r>="0"&&r<="9";)t+=r,c();if("."===r)for(t+=".";c()&&r>="0"&&r<="9";)t+=r;if("e"===r||"E"===r)for(t+=r,c(),"-"!==r&&"+"!==r||(t+=r,c());r>="0"&&r<="9";)t+=r,c();if(e=+t,isFinite(e))return e;a("Bad number")},l=function(){var e,t,n,o="";if('"'===r)for(;c();){if('"'===r)return c(),o;if("\\"===r)if(c(),"u"===r){for(n=0,t=0;t<4&&(e=parseInt(c(),16),isFinite(e));t+=1)n=16*n+e;o+=String.fromCharCode(n)}else{if("string"!=typeof s[r])break;o+=s[r]}else o+=r}a("Bad string")},f=function(){for(;r&&r<=" ";)c()};i=function(){switch(f(),r){case"{":return function(){var e,t={};if("{"===r){if(c("{"),f(),"}"===r)return c("}"),t;for(;r;){if(e=l(),f(),c(":"),Object.hasOwnProperty.call(t,e)&&a('Duplicate key "'+e+'"'),t[e]=i(),f(),"}"===r)return c("}"),t;c(","),f()}}a("Bad object")}();case"[":return function(){var e=[];if("["===r){if(c("["),f(),"]"===r)return c("]"),e;for(;r;){if(e.push(i()),f(),"]"===r)return c("]"),e;c(","),f()}}a("Bad array")}();case'"':return l();case"-":return u();default:return r>="0"&&r<="9"?u():function(){switch(r){case"t":return c("t"),c("r"),c("u"),c("e"),!0;case"f":return c("f"),c("a"),c("l"),c("s"),c("e"),!1;case"n":return c("n"),c("u"),c("l"),c("l"),null}a("Unexpected '"+r+"'")}()}},e.exports=function(e,t){var s;return o=e,n=0,r=" ",s=i(),f(),r&&a("Syntax error"),"function"==typeof t?function e(n,r){var o,i,s=n[r];if(s&&"object"==typeof s)for(o in s)Object.prototype.hasOwnProperty.call(s,o)&&(void 0!==(i=e(s,o))?s[o]=i:delete s[o]);return t.call(n,r,s)}({"":s},""):s}},function(e,t){var n,r,o,i=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,s={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"};function a(e){return i.lastIndex=0,i.test(e)?'"'+e.replace(i,(function(e){var t=s[e];return"string"==typeof t?t:"\\u"+("0000"+e.charCodeAt(0).toString(16)).slice(-4)}))+'"':'"'+e+'"'}e.exports=function(e,t,i){var s;if(n="",r="","number"==typeof i)for(s=0;s<i;s+=1)r+=" ";else"string"==typeof i&&(r=i);if(o=t,t&&"function"!=typeof t&&("object"!=typeof t||"number"!=typeof t.length))throw new Error("JSON.stringify");return function e(t,i){var s,c,u,l,f,p=n,d=i[t];switch(d&&"object"==typeof d&&"function"==typeof d.toJSON&&(d=d.toJSON(t)),"function"==typeof o&&(d=o.call(i,t,d)),typeof d){case"string":return a(d);case"number":return isFinite(d)?String(d):"null";case"boolean":case"null":return String(d);case"object":if(!d)return"null";if(n+=r,f=[],"[object Array]"===Object.prototype.toString.apply(d)){for(l=d.length,s=0;s<l;s+=1)f[s]=e(s,d)||"null";return u=0===f.length?"[]":n?"[\n"+n+f.join(",\n"+n)+"\n"+p+"]":"["+f.join(",")+"]",n=p,u}if(o&&"object"==typeof o)for(l=o.length,s=0;s<l;s+=1)"string"==typeof(c=o[s])&&(u=e(c,d))&&f.push(a(c)+(n?": ":":")+u);else for(c in d)Object.prototype.hasOwnProperty.call(d,c)&&(u=e(c,d))&&f.push(a(c)+(n?": ":":")+u);return u=0===f.length?"{}":n?"{\n"+n+f.join(",\n"+n)+"\n"+p+"}":"{"+f.join(",")+"}",n=p,u}}("",{"":e})}},function(e,t,n){var r=n(39),o=n(393),i=n(394),s=n(41);e.exports=function(e,t){return t=r(t,e),null==(e=i(e,t))||delete e[s(o(t))]}},function(e,t){e.exports=function(e){var t=null==e?0:e.length;return t?e[t-1]:void 0}},function(e,t,n){var r=n(50),o=n(164);e.exports=function(e,t){return t.length<2?e:r(e,o(t,0,-1))}},function(e,t,n){var r=n(73);e.exports=function(e){return r(e)?void 0:e}},function(e,t,n){var r=n(122);e.exports=function(e,t){return r(e,t)}},function(e,t,n){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.editorDeleteConstraint=t.editorModifyConstraint=t.editorAddConstraint=t.editorDeleteColumn=t.editorModifyColumn=t.editorAddColumn=t.fillEditorColumnInfo=void 0;const o=r(n(125)),i=r(n(184)),s=r(n(24));function a(e,t){var n,r;return Object.assign({isPrimaryKey:!!(null===(r=null===(n=null==t?void 0:t.primaryKey)||void 0===n?void 0:n.columns)||void 0===r?void 0:r.find(t=>t.columnName==e.columnName)),dataType:s.default.isEmpty(e)?"int":void 0},e)}function c(e,t,n){if(!(null==t?void 0:t.isPrimaryKey)&&(null==n?void 0:n.isPrimaryKey)){let t=null==e?void 0:e.primaryKey;return t||(t={constraintType:"primaryKey",pureName:e.pureName,schemaName:e.schemaName,columns:[]}),Object.assign(Object.assign({},e),{primaryKey:Object.assign(Object.assign({},t),{columns:[...t.columns,{columnName:n.columnName}]})})}if((null==t?void 0:t.isPrimaryKey)&&!(null==n?void 0:n.isPrimaryKey)){let n=null==e?void 0:e.primaryKey;if(n)return n=Object.assign(Object.assign({},n),{columns:e.primaryKey.columns.filter(e=>e.columnName!=t.columnName)}),0==n.columns.length?Object.assign(Object.assign({},e),{primaryKey:null}):Object.assign(Object.assign({},e),{primaryKey:n})}return e}t.fillEditorColumnInfo=a,t.editorAddColumn=function(e,t){let n=Object.assign(Object.assign({},e),{columns:[...(null==e?void 0:e.columns)||[],Object.assign(Object.assign({},t),{pairingId:(0,o.default)()})]});return n=c(n,null,t),n},t.editorModifyColumn=function(e,t){var n;const r=null===(n=null==e?void 0:e.columns)||void 0===n?void 0:n.find(e=>e.pairingId==t.pairingId);let o=Object.assign(Object.assign({},e),{columns:e.columns.map(e=>e.pairingId==t.pairingId?(0,i.default)(t,["isPrimaryKey"]):e)});return o=c(o,a(r,e),t),o},t.editorDeleteColumn=function(e,t){let n=Object.assign(Object.assign({},e),{columns:e.columns.filter(e=>e.pairingId!=t.pairingId)});return n=c(n,t,null),n},t.editorAddConstraint=function(e,t){const n=Object.assign({},e);return"primaryKey"==t.constraintType&&(n.primaryKey=Object.assign({pairingId:(0,o.default)()},t)),"foreignKey"==t.constraintType&&(n.foreignKeys=[...n.foreignKeys||[],Object.assign({pairingId:(0,o.default)()},t)]),"index"==t.constraintType&&(n.indexes=[...n.indexes||[],Object.assign({pairingId:(0,o.default)()},t)]),"unique"==t.constraintType&&(n.uniques=[...n.uniques||[],Object.assign({pairingId:(0,o.default)()},t)]),n},t.editorModifyConstraint=function(e,t){const n=Object.assign({},e);return"primaryKey"==t.constraintType&&(n.primaryKey=Object.assign(Object.assign({},n.primaryKey),t)),"foreignKey"==t.constraintType&&(n.foreignKeys=e.foreignKeys.map(e=>e.pairingId==t.pairingId?Object.assign(Object.assign({},e),t):e)),"index"==t.constraintType&&(n.indexes=e.indexes.map(e=>e.pairingId==t.pairingId?Object.assign(Object.assign({},e),t):e)),"unique"==t.constraintType&&(n.uniques=e.uniques.map(e=>e.pairingId==t.pairingId?Object.assign(Object.assign({},e),t):e)),n},t.editorDeleteConstraint=function(e,t){const n=Object.assign({},e);return"primaryKey"==t.constraintType&&(n.primaryKey=null),"foreignKey"==t.constraintType&&(n.foreignKeys=e.foreignKeys.filter(e=>e.pairingId!=t.pairingId)),"index"==t.constraintType&&(n.indexes=e.indexes.filter(e=>e.pairingId!=t.pairingId)),"unique"==t.constraintType&&(n.uniques=e.uniques.filter(e=>e.pairingId!=t.pairingId)),n}},function(e,t,n){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.databaseInfoFromYamlModel=t.tableInfoFromYaml=t.tableInfoToYaml=void 0;const o=r(n(102)),i=r(n(52)),s=n(120);function a(e,t){const n={pureName:e.name,columns:e.columns.map(t=>function(e,t){return{pureName:t.name,columnName:e.name,dataType:e.length?`${e.type}(${e.length})`:e.type,autoIncrement:e.autoIncrement,notNull:e.notNull||t.primaryKey&&t.primaryKey.includes(e.name)}}(t,e)),foreignKeys:(0,i.default)(e.columns.filter(e=>e.references).map(n=>function(e,t,n){const r=n.find(t=>t.name==e.references);return r&&r.primaryKey?{constraintType:"foreignKey",pureName:t.name,refTableName:e.references,columns:[{columnName:e.name,refColumnName:r.primaryKey[0]}]}:null}(n,e,t)))};return e.primaryKey&&(n.primaryKey={pureName:e.name,constraintType:"primaryKey",columns:e.primaryKey.map(e=>({columnName:e}))}),n.preloadedRows=e.data,n.preloadedRowsKey=e.insertKey,n.preloadedRowsInsertOnly=e.insertOnly,n}t.tableInfoToYaml=function(e){const t=(0,o.default)(e),n={name:t.pureName,columns:t.columns.map(e=>function(e,t){const n={name:e.columnName,type:e.dataType};e.autoIncrement&&(n.autoIncrement=!0),e.notNull&&(n.notNull=!0);const r=t.foreignKeys&&t.foreignKeys.find(t=>1==t.columns.length&&t.columns[0].columnName==e.columnName);return!r||r.deleteAction&&"NO ACTION"!=r.deleteAction||r.updateAction&&"NO ACTION"!=r.updateAction||(n.references=r.refTableName,r._dumped=!0),n}(e,t))};return t.primaryKey&&!t.primaryKey._dumped&&(n.primaryKey=t.primaryKey.columns.map(e=>e.columnName)),n},t.tableInfoFromYaml=a,t.databaseInfoFromYamlModel=function(e){const t=s.DatabaseAnalyser.createEmptyStructure(),n=[];for(const r of e)(r.name.endsWith(".table.yaml")||r.name.endsWith(".sql"))&&(r.name.endsWith(".table.yaml")&&n.push(r.json),r.name.endsWith(".view.sql")&&t.views.push({pureName:r.name.slice(0,-".view.sql".length),createSql:r.text,columns:[]}),r.name.endsWith(".matview.sql")&&t.matviews.push({pureName:r.name.slice(0,-".matview.sql".length),createSql:r.text,columns:[]}),r.name.endsWith(".proc.sql")&&t.procedures.push({pureName:r.name.slice(0,-".proc.sql".length),createSql:r.text}),r.name.endsWith(".func.sql")&&t.functions.push({pureName:r.name.slice(0,-".func.sql".length),createSql:r.text}),r.name.endsWith(".trigger.sql")&&t.triggers.push({pureName:r.name.slice(0,-".trigger.sql".length),createSql:r.text}));return t.tables=n.map(e=>a(e,n)),t}},function(e,t,n){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.getIconForRedisType=t.isJsonLikeLongString=t.safeJsonParse=t.stringifyCellValue=t.parseCellValue=t.hexStringToArray=t.arrayToHexString=void 0;const o=r(n(72)),i=r(n(12)),s=r(n(73));function a(e){return e.reduce((e,t)=>e+("0"+t.toString(16)).slice(-2),"").toUpperCase()}function c(e){for(var t=e.toString(),n=[],r=0;r<t.length;r+=2)n.push(parseInt(t.substr(r,2),16));return n}t.arrayToHexString=a,t.hexStringToArray=c,t.parseCellValue=function(e){if(!(0,o.default)(e))return e;if("(NULL)"==e)return null;if(e.match(/^0x([0-9a-fA-F][0-9a-fA-F])+$/))return{type:"Buffer",data:c(e.substring(2))};const t=e.match(/^ObjectId\("([0-9a-f]{24})"\)$/);return t?{$oid:t[1]}:e},t.stringifyCellValue=function(e){return null===e?"(NULL)":void 0===e?"(NoField)":"Buffer"==(null==e?void 0:e.type)&&(0,i.default)(e.data)?"0x"+a(e.data):(null==e?void 0:e.$oid)?`ObjectId("${null==e?void 0:e.$oid}")`:(0,s.default)(e)||(0,i.default)(e)?JSON.stringify(e):e},t.safeJsonParse=function(e,t,n=!1){try{return JSON.parse(e)}catch(r){return n&&console.error(`Error parsing JSON value "${e}"`,r),t}},t.isJsonLikeLongString=function(e){return(0,o.default)(e)&&e.length>100&&e.match(/^\s*\{.*\}\s*$|^\s*\[.*\]\s*$/)},t.getIconForRedisType=function(e){switch(e){case"dir":return"img folder";case"string":return"img type-string";case"hash":return"img type-hash";case"set":return"img type-set";case"list":return"img type-list";case"zset":return"img type-zset";case"stream":return"img type-stream";case"binary":return"img type-binary";case"ReJSON-RL":return"img type-rejson";default:return null}}},function(e,t,n){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.getCreateObjectScript=t.computeTableDiffColumns=t.computeDbDiffRows=t.DbDiffCompareDefs=t.computeDiffRowsCore=void 0;const o=n(128),i=r(n(24));function s(e,t,n){const r=[];for(const o of e){const e=t.find(e=>e.pairingId==o.pairingId);if(e){const t=n(o,e);r.push({source:o,target:e,state:t?"equal":"changed",__isChanged:!t})}else r.push({source:o,state:"added",__isAdded:!0})}for(const n of t){e.find(e=>e.pairingId==n.pairingId)||r.push({target:n,state:"removed",__isDeleted:!0})}return r}t.computeDiffRowsCore=s,t.DbDiffCompareDefs={tables:{test:o.testEqualTables,name:"Table",plural:"Tables",icon:"img table"},views:{test:o.testEqualSqlObjects,name:"View",plural:"Views",icon:"img view"},matviews:{test:o.testEqualSqlObjects,name:"Materialized view",plural:"Materialized views",icon:"img view"},procedures:{test:o.testEqualSqlObjects,name:"Procedure",plural:"Procedures",icon:"img procedure"},functions:{test:o.testEqualSqlObjects,name:"Function",plural:"Functions",icon:"img function"}},t.computeDbDiffRows=function(e,n,r,o){if(!e||!n||!o)return[];const a=[];for(const c of["tables","views","procedures","matviews","functions"]){const u=t.DbDiffCompareDefs[c];a.push(...i.default.sortBy(s(e[c],n[c],(t,i)=>u.test(t,i,r,e,n,o)).map(e=>{var t,n,r,o,i,s,a,l;return Object.assign(Object.assign({},e),{sourceSchemaName:null===(t=null==e?void 0:e.source)||void 0===t?void 0:t.schemaName,sourcePureName:null===(n=null==e?void 0:e.source)||void 0===n?void 0:n.pureName,targetSchemaName:null===(r=null==e?void 0:e.target)||void 0===r?void 0:r.schemaName,targetPureName:null===(o=null==e?void 0:e.target)||void 0===o?void 0:o.pureName,typeName:u.name,typeIcon:u.icon,identifier:`${(null===(i=null==e?void 0:e.source)||void 0===i?void 0:i.schemaName)||(null===(s=null==e?void 0:e.target)||void 0===s?void 0:s.schemaName)}.${(null===(a=null==e?void 0:e.source)||void 0===a?void 0:a.pureName)||(null===(l=null==e?void 0:e.target)||void 0===l?void 0:l.pureName)}`,objectTypeField:c})}),"identifier"))}return a},t.computeTableDiffColumns=function(e,t,n,r){return r?s((null==e?void 0:e.columns)||[],(null==t?void 0:t.columns)||[],(e,t)=>(0,o.testEqualColumns)(e,t,!0,!0,n)).map(e=>{var t,n,r,o,i,s;return Object.assign(Object.assign({},e),{sourceColumnName:null===(t=null==e?void 0:e.source)||void 0===t?void 0:t.columnName,targetColumnName:null===(n=null==e?void 0:e.target)||void 0===n?void 0:n.columnName,sourceDataType:null===(r=null==e?void 0:e.source)||void 0===r?void 0:r.dataType,targetDataType:null===(o=null==e?void 0:e.target)||void 0===o?void 0:o.dataType,sourceNotNull:null===(i=null==e?void 0:e.source)||void 0===i?void 0:i.notNull,targetNotNull:null===(s=null==e?void 0:e.target)||void 0===s?void 0:s.notNull})}):[]},t.getCreateObjectScript=function(e,t){if(!e||!t)return"";if("tables"==e.objectTypeField){const n=t.createDumper();return n.createTable(e),n.s}return e.createSql||""}},function(e,t,n){"use strict";var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function s(e){try{c(r.next(e))}catch(e){i(e)}}function a(e){try{c(r.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((r=r.apply(e,t||[])).next())}))},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.enrichWithPreloadedRows=void 0;const i=o(n(24));t.enrichWithPreloadedRows=function(e,t,n,o){var s,a,c;return r(this,void 0,void 0,(function*(){const r={};for(const i of t.tables){const t=e.tables.find(e=>e.pairingId==i.pairingId);if(0==((null===(s=null==t?void 0:t.preloadedRows)||void 0===s?void 0:s.length)||0))continue;const u=t.preloadedRowsKey||(null===(c=null===(a=t.primaryKey)||void 0===a?void 0:a.columns)||void 0===c?void 0:c.map(e=>e.columnName));if(0==((null==u?void 0:u.length)||0))continue;const l=o.createDumper();1==u.length?l.putCmd("^select * ^from %f ^where %i ^in (%,v)",i,u[0],t.preloadedRows.map(e=>e[u[0]])):(l.put("^select * ^from %f ^where",i),l.putCollection(" ^or ",t.preloadedRows,e=>{l.put("("),l.putCollection(" ^and ",u,t=>l.put("%i=%v",t,e[t])),l.put(")")}),l.endCommand());const f=yield o.query(n,l.s);r[i.pairingId]=Object.assign(Object.assign({},i),{preloadedRows:f.rows,preloadedRowsKey:u})}return i.default.isEmpty(r)?t:Object.assign(Object.assign({},t),{tables:t.tables.map(e=>r[e.pairingId]||e)})}))}},function(e,t,n){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.jsonScriptToJavascript=t.ScriptWriterJson=t.ScriptWriter=void 0;const o=r(n(403)),i=n(163);class s{constructor(e="0"){this.s="",this.packageNames=[],this.varCount=0,this.varCount=parseInt(e)||0}allocVariable(e="var"){return this.varCount+=1,`${e}${this.varCount}`}_put(e=""){this.s+=e,this.s+="\n"}endLine(){this._put()}assignCore(e,t,n){this._put(`const ${e} = await ${t}(${JSON.stringify(n)});`)}assign(e,t,n){this.assignCore(e,(0,i.extractShellApiFunctionName)(t),n),this.packageNames.push(...(0,i.extractShellApiPlugins)(t,n))}assignValue(e,t){this._put(`const ${e} = ${JSON.stringify(t)};`)}requirePackage(e){this.packageNames.push(e)}copyStream(e,t,n=null){n?this._put(`await dbgateApi.copyStream(${e}, ${t}, {columns: ${n}});`):this._put(`await dbgateApi.copyStream(${e}, ${t});`)}comment(e){this._put(`// ${e}`)}getScript(e=null){const t=this.packageNames;let n=(0,o.default)(t).map(e=>`// @require ${e}\n`).join("");return e&&(n+=`// @schedule ${e}`),n&&(n+="\n"),n+this.s}}t.ScriptWriter=s;t.ScriptWriterJson=class{constructor(e="0"){this.s="",this.packageNames=[],this.varCount=0,this.commands=[],this.varCount=parseInt(e)||0}allocVariable(e="var"){return this.varCount+=1,`${e}${this.varCount}`}endLine(){this.commands.push({type:"endline"})}assign(e,t,n){this.commands.push({type:"assign",variableName:e,functionName:(0,i.extractShellApiFunctionName)(t),props:n}),this.packageNames.push(...(0,i.extractShellApiPlugins)(t,n))}assignValue(e,t){this.commands.push({type:"assignValue",variableName:e,jsonValue:t})}copyStream(e,t,n=null){this.commands.push({type:"copyStream",sourceVar:e,targetVar:t,colmapVar:n})}comment(e){this.commands.push({type:"comment",text:e})}getScript(e=null){return{type:"json",schedule:e,commands:this.commands,packageNames:this.packageNames}}},t.jsonScriptToJavascript=function(e){const{schedule:t,commands:n,packageNames:r}=e,o=new s;for(const e of r){if(!/^dbgate-plugin-.*$/.test(e))throw new Error("Unallowed package name:"+e);o.packageNames.push(e)}for(const e of n)switch(e.type){case"assign":o.assignCore(e.variableName,e.functionName,e.props);break;case"assignValue":o.assignValue(e.variableName,e.jsonValue);break;case"copyStream":o.copyStream(e.sourceVar,e.targetVar,e.colmapVar);break;case"endLine":o.endLine();break;case"comment":o.comment(e.text)}return o.getScript(t)}},function(e,t,n){var r=n(182);e.exports=function(e){return e&&e.length?r(e):[]}},function(e,t,n){"use strict";var r=n(129),o=n(43),i=n(77),s=n(78),a=n(79),c=n(80),u=n(81),l=n(130),f=n(82),p=n(83),d=n(84),h=n(85),m=n(86),g=n(53),y=n(405),b=n(406),v=n(408),S=n(32),w=S.allocBuffer(17825792),_=function(){};_.prototype.serialize=function(e,t){var n="boolean"==typeof(t=t||{}).checkKeys&&t.checkKeys,r="boolean"==typeof t.serializeFunctions&&t.serializeFunctions,o="boolean"!=typeof t.ignoreUndefined||t.ignoreUndefined,i="number"==typeof t.minInternalBufferSize?t.minInternalBufferSize:17825792;w.length<i&&(w=S.allocBuffer(i));var s=b(w,e,n,0,0,r,o,[]),a=S.allocBuffer(s);return w.copy(a,0,0,a.length),a},_.prototype.serializeWithBufferAndIndex=function(e,t,n){var r="boolean"==typeof(n=n||{}).checkKeys&&n.checkKeys,o="boolean"==typeof n.serializeFunctions&&n.serializeFunctions,i="boolean"!=typeof n.ignoreUndefined||n.ignoreUndefined,s="number"==typeof n.index?n.index:0;return b(t,e,r,s||0,0,o,i)-1},_.prototype.deserialize=function(e,t){return y(e,t)},_.prototype.calculateObjectSize=function(e,t){var n="boolean"==typeof(t=t||{}).serializeFunctions&&t.serializeFunctions,r="boolean"!=typeof t.ignoreUndefined||t.ignoreUndefined;return v(e,n,r)},_.prototype.deserializeStream=function(e,t,n,r,o,i){i=null!=i?i:{};for(var s=t,a=0;a<n;a++){var c=e[s]|e[s+1]<<8|e[s+2]<<16|e[s+3]<<24;i.index=s,r[o+a]=this.deserialize(e,i),s+=c}return s},_.BSON_INT32_MAX=2147483647,_.BSON_INT32_MIN=-2147483648,_.BSON_INT64_MAX=Math.pow(2,63)-1,_.BSON_INT64_MIN=-Math.pow(2,63),_.JS_INT_MAX=9007199254740992,_.JS_INT_MIN=-9007199254740992,_.BSON_DATA_NUMBER=1,_.BSON_DATA_STRING=2,_.BSON_DATA_OBJECT=3,_.BSON_DATA_ARRAY=4,_.BSON_DATA_BINARY=5,_.BSON_DATA_OID=7,_.BSON_DATA_BOOLEAN=8,_.BSON_DATA_DATE=9,_.BSON_DATA_NULL=10,_.BSON_DATA_REGEXP=11,_.BSON_DATA_CODE=13,_.BSON_DATA_SYMBOL=14,_.BSON_DATA_CODE_W_SCOPE=15,_.BSON_DATA_INT=16,_.BSON_DATA_TIMESTAMP=17,_.BSON_DATA_LONG=18,_.BSON_DATA_MIN_KEY=255,_.BSON_DATA_MAX_KEY=127,_.BSON_BINARY_SUBTYPE_DEFAULT=0,_.BSON_BINARY_SUBTYPE_FUNCTION=1,_.BSON_BINARY_SUBTYPE_BYTE_ARRAY=2,_.BSON_BINARY_SUBTYPE_UUID=3,_.BSON_BINARY_SUBTYPE_MD5=4,_.BSON_BINARY_SUBTYPE_USER_DEFINED=128,e.exports=_,e.exports.Code=f,e.exports.Map=r,e.exports.Symbol=u,e.exports.BSON=_,e.exports.DBRef=m,e.exports.Binary=g,e.exports.ObjectID=a,e.exports.Long=o,e.exports.Timestamp=s,e.exports.Double=i,e.exports.Int32=l,e.exports.MinKey=d,e.exports.MaxKey=h,e.exports.BSONRegExp=c,e.exports.Decimal128=p},function(module,exports,__webpack_require__){"use strict";var Long=__webpack_require__(43).Long,Double=__webpack_require__(77).Double,Timestamp=__webpack_require__(78).Timestamp,ObjectID=__webpack_require__(79).ObjectID,Symbol=__webpack_require__(81).Symbol,Code=__webpack_require__(82).Code,MinKey=__webpack_require__(84).MinKey,MaxKey=__webpack_require__(85).MaxKey,Decimal128=__webpack_require__(83),Int32=__webpack_require__(130),DBRef=__webpack_require__(86).DBRef,BSONRegExp=__webpack_require__(80).BSONRegExp,Binary=__webpack_require__(53).Binary,utils=__webpack_require__(32),deserialize=function(e,t,n){var r=(t=null==t?{}:t)&&t.index?t.index:0,o=e[r]|e[r+1]<<8|e[r+2]<<16|e[r+3]<<24;if(o<5||e.length<o||o+r>e.length)throw new Error("corrupt bson message");if(0!==e[r+o-1])throw new Error("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00");return deserializeObject(e,r,t,n)},deserializeObject=function(e,t,n,r){var o=null!=n.evalFunctions&&n.evalFunctions,i=null!=n.cacheFunctions&&n.cacheFunctions,s=null!=n.cacheFunctionsCrc32&&n.cacheFunctionsCrc32;if(!s)var a=null;var c=null==n.fieldsAsRaw?null:n.fieldsAsRaw,u=null!=n.raw&&n.raw,l="boolean"==typeof n.bsonRegExp&&n.bsonRegExp,f=null!=n.promoteBuffers&&n.promoteBuffers,p=null==n.promoteLongs||n.promoteLongs,d=null==n.promoteValues||n.promoteValues,h=t;if(e.length<5)throw new Error("corrupt bson message < 5 bytes long");var m=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(m<5||m>e.length)throw new Error("corrupt bson message");for(var g=r?[]:{},y=0;;){var b=e[t++];if(0===b)break;for(var v=t;0!==e[v]&&v<e.length;)v++;if(v>=e.length)throw new Error("Bad BSON Document: illegal CString");var S=r?y++:e.toString("utf8",t,v);if(t=v+1,b===BSON.BSON_DATA_STRING){var w=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(w<=0||w>e.length-t||0!==e[t+w-1])throw new Error("bad string length in bson");g[S]=e.toString("utf8",t,t+w-1),t+=w}else if(b===BSON.BSON_DATA_OID){var _=utils.allocBuffer(12);e.copy(_,0,t,t+12),g[S]=new ObjectID(_),t+=12}else if(b===BSON.BSON_DATA_INT&&!1===d)g[S]=new Int32(e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24);else if(b===BSON.BSON_DATA_INT)g[S]=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;else if(b===BSON.BSON_DATA_NUMBER&&!1===d)g[S]=new Double(e.readDoubleLE(t)),t+=8;else if(b===BSON.BSON_DATA_NUMBER)g[S]=e.readDoubleLE(t),t+=8;else if(b===BSON.BSON_DATA_DATE){var O=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24,T=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;g[S]=new Date(new Long(O,T).toNumber())}else if(b===BSON.BSON_DATA_BOOLEAN){if(0!==e[t]&&1!==e[t])throw new Error("illegal boolean type value");g[S]=1===e[t++]}else if(b===BSON.BSON_DATA_OBJECT){var C=t,x=e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24;if(x<=0||x>e.length-t)throw new Error("bad embedded document length in bson");g[S]=u?e.slice(t,t+x):deserializeObject(e,C,n,!1),t+=x}else if(b===BSON.BSON_DATA_ARRAY){C=t;var E=n,N=t+(x=e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24);if(c&&c[S]){for(var I in E={},n)E[I]=n[I];E.raw=!0}if(g[S]=deserializeObject(e,C,E,!0),0!==e[(t+=x)-1])throw new Error("invalid array terminator byte");if(t!==N)throw new Error("corrupted array bson")}else if(b===BSON.BSON_DATA_UNDEFINED)g[S]=void 0;else if(b===BSON.BSON_DATA_NULL)g[S]=null;else if(b===BSON.BSON_DATA_LONG){O=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24,T=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;var A=new Long(O,T);g[S]=p&&!0===d&&A.lessThanOrEqual(JS_INT_MAX_LONG)&&A.greaterThanOrEqual(JS_INT_MIN_LONG)?A.toNumber():A}else if(b===BSON.BSON_DATA_DECIMAL128){var k=utils.allocBuffer(16);e.copy(k,0,t,t+16),t+=16;var M=new Decimal128(k);g[S]=M.toObject?M.toObject():M}else if(b===BSON.BSON_DATA_BINARY){var R=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24,j=R,D=e[t++];if(R<0)throw new Error("Negative binary type element size found");if(R>e.length)throw new Error("Binary type size larger than document size");if(null!=e.slice){if(D===Binary.SUBTYPE_BYTE_ARRAY){if((R=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24)<0)throw new Error("Negative binary type element size found for subtype 0x02");if(R>j-4)throw new Error("Binary type with subtype 0x02 contains to long binary size");if(R<j-4)throw new Error("Binary type with subtype 0x02 contains to short binary size")}g[S]=f&&d?e.slice(t,t+R):new Binary(e.slice(t,t+R),D)}else{var P="undefined"!=typeof Uint8Array?new Uint8Array(new ArrayBuffer(R)):new Array(R);if(D===Binary.SUBTYPE_BYTE_ARRAY){if((R=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24)<0)throw new Error("Negative binary type element size found for subtype 0x02");if(R>j-4)throw new Error("Binary type with subtype 0x02 contains to long binary size");if(R<j-4)throw new Error("Binary type with subtype 0x02 contains to short binary size")}for(v=0;v<R;v++)P[v]=e[t+v];g[S]=f&&d?P:new Binary(P,D)}t+=R}else if(b===BSON.BSON_DATA_REGEXP&&!1===l){for(v=t;0!==e[v]&&v<e.length;)v++;if(v>=e.length)throw new Error("Bad BSON Document: illegal CString");var B=e.toString("utf8",t,v);for(v=t=v+1;0!==e[v]&&v<e.length;)v++;if(v>=e.length)throw new Error("Bad BSON Document: illegal CString");var L=e.toString("utf8",t,v);t=v+1;var q=new Array(L.length);for(v=0;v<L.length;v++)switch(L[v]){case"m":q[v]="m";break;case"s":q[v]="g";break;case"i":q[v]="i"}g[S]=new RegExp(B,q.join(""))}else if(b===BSON.BSON_DATA_REGEXP&&!0===l){for(v=t;0!==e[v]&&v<e.length;)v++;if(v>=e.length)throw new Error("Bad BSON Document: illegal CString");for(B=e.toString("utf8",t,v),v=t=v+1;0!==e[v]&&v<e.length;)v++;if(v>=e.length)throw new Error("Bad BSON Document: illegal CString");L=e.toString("utf8",t,v),t=v+1,g[S]=new BSONRegExp(B,L)}else if(b===BSON.BSON_DATA_SYMBOL){if((w=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24)<=0||w>e.length-t||0!==e[t+w-1])throw new Error("bad string length in bson");g[S]=new Symbol(e.toString("utf8",t,t+w-1)),t+=w}else if(b===BSON.BSON_DATA_TIMESTAMP)O=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24,T=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24,g[S]=new Timestamp(O,T);else if(b===BSON.BSON_DATA_MIN_KEY)g[S]=new MinKey;else if(b===BSON.BSON_DATA_MAX_KEY)g[S]=new MaxKey;else if(b===BSON.BSON_DATA_CODE){if((w=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24)<=0||w>e.length-t||0!==e[t+w-1])throw new Error("bad string length in bson");var U=e.toString("utf8",t,t+w-1);if(o)if(i){var z=s?a(U):U;g[S]=isolateEvalWithHash(functionCache,z,U,g)}else g[S]=isolateEval(U);else g[S]=new Code(U);t+=w}else if(b===BSON.BSON_DATA_CODE_W_SCOPE){var $=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if($<13)throw new Error("code_w_scope total size shorter minimum expected length");if((w=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24)<=0||w>e.length-t||0!==e[t+w-1])throw new Error("bad string length in bson");U=e.toString("utf8",t,t+w-1),C=t+=w,x=e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24;var W=deserializeObject(e,C,n,!1);if(t+=x,$<8+x+w)throw new Error("code_w_scope total size is to short, truncating scope");if($>8+x+w)throw new Error("code_w_scope total size is to long, clips outer document");o?(i?(z=s?a(U):U,g[S]=isolateEvalWithHash(functionCache,z,U,g)):g[S]=isolateEval(U),g[S].scope=W):g[S]=new Code(U,W)}else{if(b!==BSON.BSON_DATA_DBPOINTER)throw new Error("Detected unknown BSON type "+b.toString(16)+' for fieldname "'+S+'", are you using the latest BSON parser');if((w=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24)<=0||w>e.length-t||0!==e[t+w-1])throw new Error("bad string length in bson");var F=e.toString("utf8",t,t+w-1);t+=w;var V=utils.allocBuffer(12);e.copy(V,0,t,t+12),_=new ObjectID(V),t+=12;var K=F.split("."),H=K.shift(),Y=K.join(".");g[S]=new DBRef(Y,_,H)}}if(m!==t-h){if(r)throw new Error("corrupt array bson");throw new Error("corrupt object bson")}return null!=g.$id&&(g=new DBRef(g.$ref,g.$id,g.$db)),g},isolateEvalWithHash=function(functionCache,hash,functionString,object){var value=null;return null==functionCache[hash]&&(eval("value = "+functionString),functionCache[hash]=value),functionCache[hash].bind(object)},isolateEval=function(functionString){var value=null;return eval("value = "+functionString),value},BSON={},functionCache=BSON.functionCache={};BSON.BSON_DATA_NUMBER=1,BSON.BSON_DATA_STRING=2,BSON.BSON_DATA_OBJECT=3,BSON.BSON_DATA_ARRAY=4,BSON.BSON_DATA_BINARY=5,BSON.BSON_DATA_UNDEFINED=6,BSON.BSON_DATA_OID=7,BSON.BSON_DATA_BOOLEAN=8,BSON.BSON_DATA_DATE=9,BSON.BSON_DATA_NULL=10,BSON.BSON_DATA_REGEXP=11,BSON.BSON_DATA_DBPOINTER=12,BSON.BSON_DATA_CODE=13,BSON.BSON_DATA_SYMBOL=14,BSON.BSON_DATA_CODE_W_SCOPE=15,BSON.BSON_DATA_INT=16,BSON.BSON_DATA_TIMESTAMP=17,BSON.BSON_DATA_LONG=18,BSON.BSON_DATA_DECIMAL128=19,BSON.BSON_DATA_MIN_KEY=255,BSON.BSON_DATA_MAX_KEY=127,BSON.BSON_BINARY_SUBTYPE_DEFAULT=0,BSON.BSON_BINARY_SUBTYPE_FUNCTION=1,BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY=2,BSON.BSON_BINARY_SUBTYPE_UUID=3,BSON.BSON_BINARY_SUBTYPE_MD5=4,BSON.BSON_BINARY_SUBTYPE_USER_DEFINED=128,BSON.BSON_INT32_MAX=2147483647,BSON.BSON_INT32_MIN=-2147483648,BSON.BSON_INT64_MAX=Math.pow(2,63)-1,BSON.BSON_INT64_MIN=-Math.pow(2,63),BSON.JS_INT_MAX=9007199254740992,BSON.JS_INT_MIN=-9007199254740992;var JS_INT_MAX_LONG=Long.fromNumber(9007199254740992),JS_INT_MIN_LONG=Long.fromNumber(-9007199254740992);module.exports=deserialize},function(e,t,n){"use strict";var r=n(407).writeIEEE754,o=n(43).Long,i=n(129),s=n(53).Binary,a=n(32).normalizedFunctionString,c=/\x00/,u=["$db","$ref","$id","$clusterTime"],l=function(e){return"object"==typeof e&&"[object Date]"===Object.prototype.toString.call(e)},f=function(e){return"[object RegExp]"===Object.prototype.toString.call(e)},p=function(e,t,n,r,o){e[r++]=R.BSON_DATA_STRING;var i=o?e.write(t,r,"ascii"):e.write(t,r,"utf8");e[(r=r+i+1)-1]=0;var s=e.write(n,r+4,"utf8");return e[r+3]=s+1>>24&255,e[r+2]=s+1>>16&255,e[r+1]=s+1>>8&255,e[r]=s+1&255,r=r+4+s,e[r++]=0,r},d=function(e,t,n,i,s){if(Math.floor(n)===n&&n>=R.JS_INT_MIN&&n<=R.JS_INT_MAX)if(n>=R.BSON_INT32_MIN&&n<=R.BSON_INT32_MAX){e[i++]=R.BSON_DATA_INT;var a=s?e.write(t,i,"ascii"):e.write(t,i,"utf8");i+=a,e[i++]=0,e[i++]=255&n,e[i++]=n>>8&255,e[i++]=n>>16&255,e[i++]=n>>24&255}else if(n>=R.JS_INT_MIN&&n<=R.JS_INT_MAX)e[i++]=R.BSON_DATA_NUMBER,i+=a=s?e.write(t,i,"ascii"):e.write(t,i,"utf8"),e[i++]=0,r(e,n,i,"little",52,8),i+=8;else{e[i++]=R.BSON_DATA_LONG,i+=a=s?e.write(t,i,"ascii"):e.write(t,i,"utf8"),e[i++]=0;var c=o.fromNumber(n),u=c.getLowBits(),l=c.getHighBits();e[i++]=255&u,e[i++]=u>>8&255,e[i++]=u>>16&255,e[i++]=u>>24&255,e[i++]=255&l,e[i++]=l>>8&255,e[i++]=l>>16&255,e[i++]=l>>24&255}else e[i++]=R.BSON_DATA_NUMBER,i+=a=s?e.write(t,i,"ascii"):e.write(t,i,"utf8"),e[i++]=0,r(e,n,i,"little",52,8),i+=8;return i},h=function(e,t,n,r,o){return e[r++]=R.BSON_DATA_NULL,r+=o?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0,r},m=function(e,t,n,r,o){return e[r++]=R.BSON_DATA_BOOLEAN,r+=o?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0,e[r++]=n?1:0,r},g=function(e,t,n,r,i){e[r++]=R.BSON_DATA_DATE,r+=i?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0;var s=o.fromNumber(n.getTime()),a=s.getLowBits(),c=s.getHighBits();return e[r++]=255&a,e[r++]=a>>8&255,e[r++]=a>>16&255,e[r++]=a>>24&255,e[r++]=255&c,e[r++]=c>>8&255,e[r++]=c>>16&255,e[r++]=c>>24&255,r},y=function(e,t,n,r,o){if(e[r++]=R.BSON_DATA_REGEXP,r+=o?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0,n.source&&null!=n.source.match(c))throw Error("value "+n.source+" must not contain null bytes");return r+=e.write(n.source,r,"utf8"),e[r++]=0,n.global&&(e[r++]=115),n.ignoreCase&&(e[r++]=105),n.multiline&&(e[r++]=109),e[r++]=0,r},b=function(e,t,n,r,o){if(e[r++]=R.BSON_DATA_REGEXP,r+=o?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0,null!=n.pattern.match(c))throw Error("pattern "+n.pattern+" must not contain null bytes");return r+=e.write(n.pattern,r,"utf8"),e[r++]=0,r+=e.write(n.options.split("").sort().join(""),r,"utf8"),e[r++]=0,r},v=function(e,t,n,r,o){return null===n?e[r++]=R.BSON_DATA_NULL:"MinKey"===n._bsontype?e[r++]=R.BSON_DATA_MIN_KEY:e[r++]=R.BSON_DATA_MAX_KEY,r+=o?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0,r},S=function(e,t,n,r,o){if(e[r++]=R.BSON_DATA_OID,r+=o?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0,"string"==typeof n.id)e.write(n.id,r,"binary");else{if(!n.id||!n.id.copy)throw new Error("object ["+JSON.stringify(n)+"] is not a valid ObjectId");n.id.copy(e,r,0,12)}return r+12},w=function(e,t,n,r,o){e[r++]=R.BSON_DATA_BINARY,r+=o?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0;var i=n.length;return e[r++]=255&i,e[r++]=i>>8&255,e[r++]=i>>16&255,e[r++]=i>>24&255,e[r++]=R.BSON_BINARY_SUBTYPE_DEFAULT,n.copy(e,r,0,i),r+=i},_=function(e,t,n,r,o,i,s,a,c,u){for(var l=0;l<u.length;l++)if(u[l]===n)throw new Error("cyclic dependency detected");u.push(n),e[r++]=Array.isArray(n)?R.BSON_DATA_ARRAY:R.BSON_DATA_OBJECT,r+=c?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0;var f=M(e,n,o,r,i+1,s,a,u);return u.pop(),f},O=function(e,t,n,r,o){return e[r++]=R.BSON_DATA_DECIMAL128,r+=o?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0,n.bytes.copy(e,r,0,16),r+16},T=function(e,t,n,r,o){e[r++]="Long"===n._bsontype?R.BSON_DATA_LONG:R.BSON_DATA_TIMESTAMP,r+=o?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0;var i=n.getLowBits(),s=n.getHighBits();return e[r++]=255&i,e[r++]=i>>8&255,e[r++]=i>>16&255,e[r++]=i>>24&255,e[r++]=255&s,e[r++]=s>>8&255,e[r++]=s>>16&255,e[r++]=s>>24&255,r},C=function(e,t,n,r,o){return e[r++]=R.BSON_DATA_INT,r+=o?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0,e[r++]=255&n,e[r++]=n>>8&255,e[r++]=n>>16&255,e[r++]=n>>24&255,r},x=function(e,t,n,o,i){return e[o++]=R.BSON_DATA_NUMBER,o+=i?e.write(t,o,"ascii"):e.write(t,o,"utf8"),e[o++]=0,r(e,n,o,"little",52,8),o+=8},E=function(e,t,n,r,o,i,s){e[r++]=R.BSON_DATA_CODE,r+=s?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0;var c=a(n),u=e.write(c,r+4,"utf8")+1;return e[r]=255&u,e[r+1]=u>>8&255,e[r+2]=u>>16&255,e[r+3]=u>>24&255,r=r+4+u-1,e[r++]=0,r},N=function(e,t,n,r,o,i,s,a,c){if(n.scope&&"object"==typeof n.scope){e[r++]=R.BSON_DATA_CODE_W_SCOPE;var u=c?e.write(t,r,"ascii"):e.write(t,r,"utf8");r+=u,e[r++]=0;var l=r,f="string"==typeof n.code?n.code:n.code.toString();r+=4;var p=e.write(f,r+4,"utf8")+1;e[r]=255&p,e[r+1]=p>>8&255,e[r+2]=p>>16&255,e[r+3]=p>>24&255,e[r+4+p-1]=0,r=r+p+4;var d=M(e,n.scope,o,r,i+1,s,a);r=d-1;var h=d-l;e[l++]=255&h,e[l++]=h>>8&255,e[l++]=h>>16&255,e[l++]=h>>24&255,e[r++]=0}else{e[r++]=R.BSON_DATA_CODE,r+=u=c?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0,f=n.code.toString();var m=e.write(f,r+4,"utf8")+1;e[r]=255&m,e[r+1]=m>>8&255,e[r+2]=m>>16&255,e[r+3]=m>>24&255,r=r+4+m-1,e[r++]=0}return r},I=function(e,t,n,r,o){e[r++]=R.BSON_DATA_BINARY,r+=o?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0;var i=n.value(!0),a=n.position;return n.sub_type===s.SUBTYPE_BYTE_ARRAY&&(a+=4),e[r++]=255&a,e[r++]=a>>8&255,e[r++]=a>>16&255,e[r++]=a>>24&255,e[r++]=n.sub_type,n.sub_type===s.SUBTYPE_BYTE_ARRAY&&(a-=4,e[r++]=255&a,e[r++]=a>>8&255,e[r++]=a>>16&255,e[r++]=a>>24&255),i.copy(e,r,0,n.position),r+=n.position},A=function(e,t,n,r,o){e[r++]=R.BSON_DATA_SYMBOL,r+=o?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0;var i=e.write(n.value,r+4,"utf8")+1;return e[r]=255&i,e[r+1]=i>>8&255,e[r+2]=i>>16&255,e[r+3]=i>>24&255,r=r+4+i-1,e[r++]=0,r},k=function(e,t,n,r,o,i,s){e[r++]=R.BSON_DATA_OBJECT,r+=s?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0;var a,c=r,u=(a=null!=n.db?M(e,{$ref:n.namespace,$id:n.oid,$db:n.db},!1,r,o+1,i):M(e,{$ref:n.namespace,$id:n.oid},!1,r,o+1,i))-c;return e[c++]=255&u,e[c++]=u>>8&255,e[c++]=u>>16&255,e[c++]=u>>24&255,a},M=function(e,t,n,r,o,s,a,M){r=r||0,(M=M||[]).push(t);var R=r+4;if(Array.isArray(t))for(var j=0;j<t.length;j++){var D=""+j,P=t[j];if(P&&P.toBSON){if("function"!=typeof P.toBSON)throw new Error("toBSON is not a function");P=P.toBSON()}var B=typeof P;if("string"===B)R=p(e,D,P,R,!0);else if("number"===B)R=d(e,D,P,R,!0);else{if("bigint"===B)throw new TypeError("Unsupported type BigInt, please use Decimal128");if("boolean"===B)R=m(e,D,P,R,!0);else if(P instanceof Date||l(P))R=g(e,D,P,R,!0);else if(void 0===P)R=h(e,D,0,R,!0);else if(null===P)R=h(e,D,0,R,!0);else if("ObjectID"===P._bsontype||"ObjectId"===P._bsontype)R=S(e,D,P,R,!0);else if(Buffer.isBuffer(P))R=w(e,D,P,R,!0);else if(P instanceof RegExp||f(P))R=y(e,D,P,R,!0);else if("object"===B&&null==P._bsontype)R=_(e,D,P,R,n,o,s,a,!0,M);else if("object"===B&&"Decimal128"===P._bsontype)R=O(e,D,P,R,!0);else if("Long"===P._bsontype||"Timestamp"===P._bsontype)R=T(e,D,P,R,!0);else if("Double"===P._bsontype)R=x(e,D,P,R,!0);else if("function"==typeof P&&s)R=E(e,D,P,R,0,0,s);else if("Code"===P._bsontype)R=N(e,D,P,R,n,o,s,a,!0);else if("Binary"===P._bsontype)R=I(e,D,P,R,!0);else if("Symbol"===P._bsontype)R=A(e,D,P,R,!0);else if("DBRef"===P._bsontype)R=k(e,D,P,R,o,s,!0);else if("BSONRegExp"===P._bsontype)R=b(e,D,P,R,!0);else if("Int32"===P._bsontype)R=C(e,D,P,R,!0);else if("MinKey"===P._bsontype||"MaxKey"===P._bsontype)R=v(e,D,P,R,!0);else if(void 0!==P._bsontype)throw new TypeError("Unrecognized or invalid _bsontype: "+P._bsontype)}}else if(t instanceof i)for(var L=t.entries(),q=!1;!q;){var U=L.next();if(!(q=U.done)){if(D=U.value[0],B=typeof(P=U.value[1]),"string"==typeof D&&-1===u.indexOf(D)){if(null!=D.match(c))throw Error("key "+D+" must not contain null bytes");if(n){if("$"===D[0])throw Error("key "+D+" must not start with '$'");if(~D.indexOf("."))throw Error("key "+D+" must not contain '.'")}}if("string"===B)R=p(e,D,P,R);else if("number"===B)R=d(e,D,P,R);else{if("bigint"===B)throw new TypeError("Unsupported type BigInt, please use Decimal128");if("boolean"===B)R=m(e,D,P,R);else if(P instanceof Date||l(P))R=g(e,D,P,R);else if(null===P||void 0===P&&!1===a)R=h(e,D,0,R);else if("ObjectID"===P._bsontype||"ObjectId"===P._bsontype)R=S(e,D,P,R);else if(Buffer.isBuffer(P))R=w(e,D,P,R);else if(P instanceof RegExp||f(P))R=y(e,D,P,R);else if("object"===B&&null==P._bsontype)R=_(e,D,P,R,n,o,s,a,!1,M);else if("object"===B&&"Decimal128"===P._bsontype)R=O(e,D,P,R);else if("Long"===P._bsontype||"Timestamp"===P._bsontype)R=T(e,D,P,R);else if("Double"===P._bsontype)R=x(e,D,P,R);else if("Code"===P._bsontype)R=N(e,D,P,R,n,o,s,a);else if("function"==typeof P&&s)R=E(e,D,P,R,0,0,s);else if("Binary"===P._bsontype)R=I(e,D,P,R);else if("Symbol"===P._bsontype)R=A(e,D,P,R);else if("DBRef"===P._bsontype)R=k(e,D,P,R,o,s);else if("BSONRegExp"===P._bsontype)R=b(e,D,P,R);else if("Int32"===P._bsontype)R=C(e,D,P,R);else if("MinKey"===P._bsontype||"MaxKey"===P._bsontype)R=v(e,D,P,R);else if(void 0!==P._bsontype)throw new TypeError("Unrecognized or invalid _bsontype: "+P._bsontype)}}}else{if(t.toBSON){if("function"!=typeof t.toBSON)throw new Error("toBSON is not a function");if(null!=(t=t.toBSON())&&"object"!=typeof t)throw new Error("toBSON function did not return an object")}for(D in t){if((P=t[D])&&P.toBSON){if("function"!=typeof P.toBSON)throw new Error("toBSON is not a function");P=P.toBSON()}if(B=typeof P,"string"==typeof D&&-1===u.indexOf(D)){if(null!=D.match(c))throw Error("key "+D+" must not contain null bytes");if(n){if("$"===D[0])throw Error("key "+D+" must not start with '$'");if(~D.indexOf("."))throw Error("key "+D+" must not contain '.'")}}if("string"===B)R=p(e,D,P,R);else if("number"===B)R=d(e,D,P,R);else{if("bigint"===B)throw new TypeError("Unsupported type BigInt, please use Decimal128");if("boolean"===B)R=m(e,D,P,R);else if(P instanceof Date||l(P))R=g(e,D,P,R);else if(void 0===P)!1===a&&(R=h(e,D,0,R));else if(null===P)R=h(e,D,0,R);else if("ObjectID"===P._bsontype||"ObjectId"===P._bsontype)R=S(e,D,P,R);else if(Buffer.isBuffer(P))R=w(e,D,P,R);else if(P instanceof RegExp||f(P))R=y(e,D,P,R);else if("object"===B&&null==P._bsontype)R=_(e,D,P,R,n,o,s,a,!1,M);else if("object"===B&&"Decimal128"===P._bsontype)R=O(e,D,P,R);else if("Long"===P._bsontype||"Timestamp"===P._bsontype)R=T(e,D,P,R);else if("Double"===P._bsontype)R=x(e,D,P,R);else if("Code"===P._bsontype)R=N(e,D,P,R,n,o,s,a);else if("function"==typeof P&&s)R=E(e,D,P,R,0,0,s);else if("Binary"===P._bsontype)R=I(e,D,P,R);else if("Symbol"===P._bsontype)R=A(e,D,P,R);else if("DBRef"===P._bsontype)R=k(e,D,P,R,o,s);else if("BSONRegExp"===P._bsontype)R=b(e,D,P,R);else if("Int32"===P._bsontype)R=C(e,D,P,R);else if("MinKey"===P._bsontype||"MaxKey"===P._bsontype)R=v(e,D,P,R);else if(void 0!==P._bsontype)throw new TypeError("Unrecognized or invalid _bsontype: "+P._bsontype)}}}M.pop(),e[R++]=0;var z=R-r;return e[r++]=255&z,e[r++]=z>>8&255,e[r++]=z>>16&255,e[r++]=z>>24&255,R},R={BSON_DATA_NUMBER:1,BSON_DATA_STRING:2,BSON_DATA_OBJECT:3,BSON_DATA_ARRAY:4,BSON_DATA_BINARY:5,BSON_DATA_UNDEFINED:6,BSON_DATA_OID:7,BSON_DATA_BOOLEAN:8,BSON_DATA_DATE:9,BSON_DATA_NULL:10,BSON_DATA_REGEXP:11,BSON_DATA_CODE:13,BSON_DATA_SYMBOL:14,BSON_DATA_CODE_W_SCOPE:15,BSON_DATA_INT:16,BSON_DATA_TIMESTAMP:17,BSON_DATA_LONG:18,BSON_DATA_DECIMAL128:19,BSON_DATA_MIN_KEY:255,BSON_DATA_MAX_KEY:127,BSON_BINARY_SUBTYPE_DEFAULT:0,BSON_BINARY_SUBTYPE_FUNCTION:1,BSON_BINARY_SUBTYPE_BYTE_ARRAY:2,BSON_BINARY_SUBTYPE_UUID:3,BSON_BINARY_SUBTYPE_MD5:4,BSON_BINARY_SUBTYPE_USER_DEFINED:128,BSON_INT32_MAX:2147483647,BSON_INT32_MIN:-2147483648};R.BSON_INT64_MAX=Math.pow(2,63)-1,R.BSON_INT64_MIN=-Math.pow(2,63),R.JS_INT_MAX=9007199254740992,R.JS_INT_MIN=-9007199254740992,e.exports=M},function(e,t){t.readIEEE754=function(e,t,n,r,o){var i,s,a="big"===n,c=8*o-r-1,u=(1<<c)-1,l=u>>1,f=-7,p=a?0:o-1,d=a?1:-1,h=e[t+p];for(p+=d,i=h&(1<<-f)-1,h>>=-f,f+=c;f>0;i=256*i+e[t+p],p+=d,f-=8);for(s=i&(1<<-f)-1,i>>=-f,f+=r;f>0;s=256*s+e[t+p],p+=d,f-=8);if(0===i)i=1-l;else{if(i===u)return s?NaN:1/0*(h?-1:1);s+=Math.pow(2,r),i-=l}return(h?-1:1)*s*Math.pow(2,i-r)},t.writeIEEE754=function(e,t,n,r,o,i){var s,a,c,u="big"===r,l=8*i-o-1,f=(1<<l)-1,p=f>>1,d=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,h=u?i-1:0,m=u?-1:1,g=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,s=f):(s=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-s))<1&&(s--,c*=2),(t+=s+p>=1?d/c:d*Math.pow(2,1-p))*c>=2&&(s++,c/=2),s+p>=f?(a=0,s=f):s+p>=1?(a=(t*c-1)*Math.pow(2,o),s+=p):(a=t*Math.pow(2,p-1)*Math.pow(2,o),s=0));o>=8;e[n+h]=255&a,h+=m,a/=256,o-=8);for(s=s<<o|a,l+=o;l>0;e[n+h]=255&s,h+=m,s/=256,l-=8);e[n+h-m]|=128*g}},function(e,t,n){"use strict";var r=n(43).Long,o=n(77).Double,i=n(78).Timestamp,s=n(79).ObjectID,a=n(81).Symbol,c=n(80).BSONRegExp,u=n(82).Code,l=n(83),f=n(84).MinKey,p=n(85).MaxKey,d=n(86).DBRef,h=n(53).Binary,m=n(32).normalizedFunctionString,g=function(e,t,n){var r=5;if(Array.isArray(e))for(var o=0;o<e.length;o++)r+=y(o.toString(),e[o],t,!0,n);else for(var i in e.toBSON&&(e=e.toBSON()),e)r+=y(i,e[i],t,!1,n);return r};function y(e,t,n,y,v){switch(t&&t.toBSON&&(t=t.toBSON()),typeof t){case"string":return 1+Buffer.byteLength(e,"utf8")+1+4+Buffer.byteLength(t,"utf8")+1;case"number":return Math.floor(t)===t&&t>=b.JS_INT_MIN&&t<=b.JS_INT_MAX&&t>=b.BSON_INT32_MIN&&t<=b.BSON_INT32_MAX?(null!=e?Buffer.byteLength(e,"utf8")+1:0)+5:(null!=e?Buffer.byteLength(e,"utf8")+1:0)+9;case"undefined":return y||!v?(null!=e?Buffer.byteLength(e,"utf8")+1:0)+1:0;case"boolean":return(null!=e?Buffer.byteLength(e,"utf8")+1:0)+2;case"object":if(null==t||t instanceof f||t instanceof p||"MinKey"===t._bsontype||"MaxKey"===t._bsontype)return(null!=e?Buffer.byteLength(e,"utf8")+1:0)+1;if(t instanceof s||"ObjectID"===t._bsontype||"ObjectId"===t._bsontype)return(null!=e?Buffer.byteLength(e,"utf8")+1:0)+13;if(t instanceof Date||"object"==typeof(w=t)&&"[object Date]"===Object.prototype.toString.call(w))return(null!=e?Buffer.byteLength(e,"utf8")+1:0)+9;if("undefined"!=typeof Buffer&&Buffer.isBuffer(t))return(null!=e?Buffer.byteLength(e,"utf8")+1:0)+6+t.length;if(t instanceof r||t instanceof o||t instanceof i||"Long"===t._bsontype||"Double"===t._bsontype||"Timestamp"===t._bsontype)return(null!=e?Buffer.byteLength(e,"utf8")+1:0)+9;if(t instanceof l||"Decimal128"===t._bsontype)return(null!=e?Buffer.byteLength(e,"utf8")+1:0)+17;if(t instanceof u||"Code"===t._bsontype)return null!=t.scope&&Object.keys(t.scope).length>0?(null!=e?Buffer.byteLength(e,"utf8")+1:0)+1+4+4+Buffer.byteLength(t.code.toString(),"utf8")+1+g(t.scope,n,v):(null!=e?Buffer.byteLength(e,"utf8")+1:0)+1+4+Buffer.byteLength(t.code.toString(),"utf8")+1;if(t instanceof h||"Binary"===t._bsontype)return t.sub_type===h.SUBTYPE_BYTE_ARRAY?(null!=e?Buffer.byteLength(e,"utf8")+1:0)+(t.position+1+4+1+4):(null!=e?Buffer.byteLength(e,"utf8")+1:0)+(t.position+1+4+1);if(t instanceof a||"Symbol"===t._bsontype)return(null!=e?Buffer.byteLength(e,"utf8")+1:0)+Buffer.byteLength(t.value,"utf8")+4+1+1;if(t instanceof d||"DBRef"===t._bsontype){var S={$ref:t.namespace,$id:t.oid};return null!=t.db&&(S.$db=t.db),(null!=e?Buffer.byteLength(e,"utf8")+1:0)+1+g(S,n,v)}return t instanceof RegExp||"[object RegExp]"===Object.prototype.toString.call(t)?(null!=e?Buffer.byteLength(e,"utf8")+1:0)+1+Buffer.byteLength(t.source,"utf8")+1+(t.global?1:0)+(t.ignoreCase?1:0)+(t.multiline?1:0)+1:t instanceof c||"BSONRegExp"===t._bsontype?(null!=e?Buffer.byteLength(e,"utf8")+1:0)+1+Buffer.byteLength(t.pattern,"utf8")+1+Buffer.byteLength(t.options,"utf8")+1:(null!=e?Buffer.byteLength(e,"utf8")+1:0)+g(t,n,v)+1;case"function":if(t instanceof RegExp||"[object RegExp]"===Object.prototype.toString.call(t)||"[object RegExp]"===String.call(t))return(null!=e?Buffer.byteLength(e,"utf8")+1:0)+1+Buffer.byteLength(t.source,"utf8")+1+(t.global?1:0)+(t.ignoreCase?1:0)+(t.multiline?1:0)+1;if(n&&null!=t.scope&&Object.keys(t.scope).length>0)return(null!=e?Buffer.byteLength(e,"utf8")+1:0)+1+4+4+Buffer.byteLength(m(t),"utf8")+1+g(t.scope,n,v);if(n)return(null!=e?Buffer.byteLength(e,"utf8")+1:0)+1+4+Buffer.byteLength(m(t),"utf8")+1}var w;return 0}var b={BSON_INT32_MAX:2147483647,BSON_INT32_MIN:-2147483648,JS_INT_MAX:9007199254740992,JS_INT_MIN:-9007199254740992};e.exports=g},function(e,t){e.exports=require("assert")},function(e,t){e.exports=require("os")},function(e){e.exports=JSON.parse('{"name":"mongodb","version":"3.6.6","description":"The official MongoDB driver for Node.js","main":"index.js","files":["index.js","lib"],"repository":{"type":"git","url":"git@github.com:mongodb/node-mongodb-native.git"},"keywords":["mongodb","driver","official"],"peerDependenciesMeta":{"kerberos":{"optional":true},"mongodb-client-encryption":{"optional":true},"mongodb-extjson":{"optional":true},"snappy":{"optional":true},"bson-ext":{"optional":true},"aws4":{"optional":true}},"dependencies":{"bl":"^2.2.1","bson":"^1.1.4","denque":"^1.4.1","optional-require":"^1.0.2","safe-buffer":"^5.1.2"},"devDependencies":{"chai":"^4.1.1","chai-subset":"^1.6.0","chalk":"^2.4.2","co":"4.6.0","coveralls":"^2.11.6","eslint":"^7.10.0","eslint-config-prettier":"^6.11.0","eslint-plugin-es":"^3.0.1","eslint-plugin-prettier":"^3.1.3","istanbul":"^0.4.5","jsdoc":"3.5.5","lodash.camelcase":"^4.3.0","mocha":"5.2.0","mocha-sinon":"^2.1.0","mongodb-extjson":"^2.1.1","mongodb-mock-server":"^1.0.1","prettier":"^1.19.1","semver":"^5.5.0","sinon":"^4.3.0","sinon-chai":"^3.2.0","snappy":"^6.3.4","spec-xunit-file":"0.0.1-3","standard-version":"^8.0.2","util.promisify":"^1.0.1","worker-farm":"^1.5.0","wtfnode":"^0.8.0","yargs":"^14.2.0"},"license":"Apache-2.0","engines":{"node":">=4"},"bugs":{"url":"https://github.com/mongodb/node-mongodb-native/issues"},"scripts":{"atlas":"mocha --opts \'{}\' ./test/manual/atlas_connectivity.test.js","check:kerberos":"mocha --opts \'{}\' -t 60000 test/manual/kerberos.test.js","check:ldap":"mocha --opts \'{}\' test/manual/ldap.test.js","check:tls":"mocha --opts \'{}\' test/manual/tls_support.test.js","test":"npm run lint && mocha --recursive test/functional test/unit","test-nolint":"mocha --recursive test/functional test/unit","coverage":"istanbul cover mongodb-test-runner -- -t 60000 test/unit test/functional","lint":"eslint -v && eslint lib test","format":"npm run lint -- --fix","bench":"node test/benchmarks/driverBench/","generate-evergreen":"node .evergreen/generate_evergreen_tasks.js","release":"standard-version -i HISTORY.md"},"homepage":"https://github.com/mongodb/node-mongodb-native","optionalDependencies":{"saslprep":"^1.0.0"}}')},function(e,t){function n(e){var t=new Error("Cannot find module '"+e+"'");throw t.code="MODULE_NOT_FOUND",t}n.keys=function(){return[]},n.resolve=n,e.exports=n,n.id=412},function(e,t){e.exports=require("zlib")},function(e,t,n){"use strict";const r=n(5).inherits,o=n(8).EventEmitter,i=n(3).MongoError,s=n(3).MongoTimeoutError,a=n(3).MongoWriteConcernError,c=n(16),u=n(5).format,l=n(45).Msg,f=n(133),p=n(6).MESSAGE_HEADER_SIZE,d=n(6).COMPRESSION_DETAILS_SIZE,h=n(6).opcodes,m=n(30).compress,g=n(30).compressorIDs,y=n(30).uncompressibleCommands,b=n(191),v=n(22).Buffer,S=n(135),w=n(34).updateSessionFromResponse,_=n(4).eachAsync,O=n(4).makeStateMachine,T=n(0).now,C="destroying",x="destroyed",E=O({disconnected:["connecting","draining","disconnected"],connecting:["connecting","connected","draining","disconnected"],connected:["connected","disconnected","draining"],draining:["draining",C,x],[C]:[C,x],[x]:[x]}),N=new Set(["error","close","timeout","parseError","connect","message"]);var I=0,A=function(e,t){if(o.call(this),this.topology=e,this.s={state:"disconnected",cancellationToken:new o},this.s.cancellationToken.setMaxListeners(1/0),this.options=Object.assign({host:"localhost",port:27017,size:5,minSize:0,connectionTimeout:3e4,socketTimeout:0,keepAlive:!0,keepAliveInitialDelay:12e4,noDelay:!0,ssl:!1,checkServerIdentity:!0,ca:null,crl:null,cert:null,key:null,passphrase:null,rejectUnauthorized:!1,promoteLongs:!0,promoteValues:!0,promoteBuffers:!1,reconnect:!0,reconnectInterval:1e3,reconnectTries:30,domainsEnabled:!1,legacyCompatMode:!0},t),this.id=I++,this.retriesLeft=this.options.reconnectTries,this.reconnectId=null,this.reconnectError=null,!t.bson||t.bson&&("function"!=typeof t.bson.serialize||"function"!=typeof t.bson.deserialize))throw new Error("must pass in valid bson parser");this.logger=c("Pool",t),this.availableConnections=[],this.inUseConnections=[],this.connectingConnections=0,this.executing=!1,this.queue=[],this.numberOfConsecutiveTimeouts=0,this.connectionIndex=0;const n=this;this._messageHandler=function(e){return function(t,n){for(var r=null,o=0;o<n.workItems.length;o++)n.workItems[o].requestId===t.responseTo&&(r=n.workItems[o],n.workItems.splice(o,1));function s(e,t,n,r){if(!e.options.domainsEnabled)return process.nextTick((function(){return t(n,r)}));t(n,r)}if(r&&r.monitoring&&j(n,e.inUseConnections,e.availableConnections),e.numberOfConsecutiveTimeouts=0,r&&r.socketTimeout&&n.resetSocketTimeout(),e.logger.isDebug()&&e.logger.debug(u("message [%s] received from %s:%s",t.raw.toString("hex"),e.options.host,e.options.port)),e.executing||process.nextTick((function(){$(e)()})),r&&!r.immediateRelease){try{t.parse(r)}catch(t){return s(e,r.cb,new i(t))}if(t.documents[0]){const n=t.documents[0],o=r.session;o&&w(o,n),e.topology&&n.$clusterTime&&(e.topology.clusterTime=n.$clusterTime)}if(r.command&&t.documents[0]){const n=t.documents[0];if(n.writeConcernError){const t=new a(n.writeConcernError,n);return s(e,r.cb,t)}if(0===n.ok||n.$err||n.errmsg||n.code)return s(e,r.cb,new i(n))}t.hashedName=n.hashedName,s(e,r.cb,null,new f(r.fullResult?t:t.documents[0],n,t))}}}(this),this._connectionCloseHandler=function(e){M(n,"close",e,this)},this._connectionErrorHandler=function(e){M(n,"error",e,this)},this._connectionTimeoutHandler=function(e){M(n,"timeout",e,this)},this._connectionParseErrorHandler=function(e){M(n,"parseError",e,this)}};function k(e){e.inUseConnections=[],e.availableConnections=[],e.connectingConnections=0,e.executing=!1,e.numberOfConsecutiveTimeouts=0,e.connectionIndex=0,e.retriesLeft=e.options.reconnectTries,e.reconnectId=null}function M(e,t,n,r){if(r){if(r._connectionFailHandled)return;r._connectionFailHandled=!0,r.destroy(),q(e,r),r.flush(n)}if("timeout"===t&&(e.numberOfConsecutiveTimeouts=e.numberOfConsecutiveTimeouts+1,e.numberOfConsecutiveTimeouts>e.options.reconnectTries))return e.numberOfConsecutiveTimeouts=0,e.destroy(!0),e.emit("close",e);0===e.socketCount()&&(e.state!==x&&e.state!==C&&"draining"!==e.state&&e.options.reconnect&&E(e,"disconnected"),t="error"===t?"close":t,e.emit(t,n)),!e.reconnectId&&e.options.reconnect&&(e.reconnectError=n,e.reconnectId=setTimeout(R(e),e.options.reconnectInterval)),D(e)<e.minSize&&U(e)}function R(e,t){return function(){if(e.emit("attemptReconnect",e),e.state!==x&&e.state!==C){if(e.retriesLeft=e.retriesLeft-1,e.retriesLeft<=0){e.destroy();const n=new s(`failed to reconnect after ${e.options.reconnectTries} attempts with interval ${e.options.reconnectInterval} ms`,e.reconnectError);return e.emit("reconnectFailed",n),void("function"==typeof t&&t(n))}e.reconnectId=null,U(e,(n,r)=>{null==n&&(e.reconnectId=null,e.retriesLeft=e.options.reconnectTries,e.emit("reconnect",e)),"function"==typeof t&&t(n,r)})}else"function"==typeof t&&t(new i("Cannot create connection when pool is destroyed"))}}function j(e,t,n){var r=t.indexOf(e);-1!==r&&(t.splice(r,1),n.push(e))}function D(e){return e.availableConnections.length+e.inUseConnections.length+e.connectingConnections}function P(e,t,n,r){E(e,C),e.s.cancellationToken.emit("cancel"),_(t,(e,t)=>{for(const t of N)e.removeAllListeners(t);e.on("error",()=>{}),e.destroy(n,t)},t=>{t?"function"==typeof r&&r(t,null):(k(e),e.queue=[],E(e,x),"function"==typeof r&&r(null,null))})}function B(e,t,n){const r=t.toBin();if(!!!e.options.agreedCompressor||!function(e){const t=e instanceof l?e.command:e.query,n=Object.keys(t)[0];return!y.has(n)}(t))return n(null,r);const o=v.concat(r),i=o.slice(p),s=o.readInt32LE(12);m(e,i,(function(r,o){if(r)return n(r,null);const a=v.alloc(p);a.writeInt32LE(p+d+o.length,0),a.writeInt32LE(t.requestId,4),a.writeInt32LE(0,8),a.writeInt32LE(h.OP_COMPRESSED,12);const c=v.alloc(d);return c.writeInt32LE(s,0),c.writeInt32LE(i.length,4),c.writeUInt8(g[e.options.agreedCompressor],8),n(null,[a,c,o])}))}function L(e,t){for(var n=0;n<t.length;n++)if(t[n]===e)return t.splice(n,1),!0}function q(e,t){L(t,e.availableConnections)||L(t,e.inUseConnections)}function U(e,t){e.state!==x&&e.state!==C?(e.connectingConnections++,S(e.options,e.s.cancellationToken,(n,r)=>(e.connectingConnections--,n?(e.logger.isDebug()&&e.logger.debug(`connection attempt failed with error [${JSON.stringify(n)}]`),!e.reconnectId&&e.options.reconnect?"connecting"===e.state&&e.options.legacyCompatMode?void t(n):(e.reconnectError=n,void(e.reconnectId=setTimeout(R(e,t),e.options.reconnectInterval))):void("function"==typeof t&&t(n))):e.state===x||e.state===C?("function"==typeof t&&t(new i("Pool was destroyed after connection creation")),void r.destroy()):(r.on("error",e._connectionErrorHandler),r.on("close",e._connectionCloseHandler),r.on("timeout",e._connectionTimeoutHandler),r.on("parseError",e._connectionParseErrorHandler),r.on("message",e._messageHandler),e.availableConnections.push(r),"function"==typeof t&&t(null,r),void $(e)())))):"function"==typeof t&&t(new i("Cannot create connection when pool is destroyed"))}function z(e){for(var t=0;t<e.length;t++)if(e[t].monitoring){var n=e[t];e.splice(t,1),n.cb(new i({message:"no connection available for monitoring",driver:!0}))}}function $(e){return function(){if(e.state!==x&&!e.executing)if(e.executing=!0,e.connectingConnections>0)e.executing=!1;else{for(;;){const s=D(e);if(0===e.availableConnections.length){z(e.queue),s<e.options.size&&e.queue.length>0&&U(e);break}if(0===e.queue.length)break;var t=null;const a=e.availableConnections.filter(e=>0===e.workItems.length);if(!(t=0===a.length?e.availableConnections[e.connectionIndex++%e.availableConnections.length]:a[e.connectionIndex++%a.length]).isConnected()){q(e,t),z(e.queue);break}var n=e.queue.shift();if(n.monitoring){var r=!1;for(let n=0;n<e.availableConnections.length;n++)if(e.availableConnections[n].isConnected()&&0===e.availableConnections[n].workItems.length){r=!0,t=e.availableConnections[n];break}if(!r){e.queue.unshift(n),s<e.options.size&&e.queue.length>0&&U(e),setTimeout(()=>$(e)(),10);break}}if(s<e.options.size&&t.workItems.length>0){e.queue.unshift(n),U(e);break}var o=n.buffer;n.monitoring&&j(t,e.availableConnections,e.inUseConnections),n.noResponse||t.workItems.push(n),n.immediateRelease||"number"!=typeof n.socketTimeout||t.setSocketTimeout(n.socketTimeout);var i=!0;if(Array.isArray(o))for(let e=0;e<o.length;e++)i=t.write(o[e]);else i=t.write(o);if(n.noResponse&&"function"==typeof n.cb&&n.cb(null,null),!1===i){e.queue.unshift(n),q(e,t),z(e.queue);break}}e.executing=!1}}}r(A,o),Object.defineProperty(A.prototype,"size",{enumerable:!0,get:function(){return this.options.size}}),Object.defineProperty(A.prototype,"minSize",{enumerable:!0,get:function(){return this.options.minSize}}),Object.defineProperty(A.prototype,"connectionTimeout",{enumerable:!0,get:function(){return this.options.connectionTimeout}}),Object.defineProperty(A.prototype,"socketTimeout",{enumerable:!0,get:function(){return this.options.socketTimeout}}),Object.defineProperty(A.prototype,"state",{enumerable:!0,get:function(){return this.s.state}}),A.prototype.socketCount=function(){return this.availableConnections.length+this.inUseConnections.length},A.prototype.allConnections=function(){return this.availableConnections.concat(this.inUseConnections)},A.prototype.get=function(){return this.allConnections()[0]},A.prototype.isConnected=function(){if(this.state===x||this.state===C)return!1;for(var e=this.availableConnections.concat(this.inUseConnections),t=0;t<e.length;t++)if(e[t].isConnected())return!0;return!1},A.prototype.isDestroyed=function(){return this.state===x||this.state===C},A.prototype.isDisconnected=function(){return"disconnected"===this.state},A.prototype.connect=function(e){if("disconnected"!==this.state)throw new i("connection in unlawful state "+this.state);E(this,"connecting"),U(this,(t,n)=>{if(t)return"function"==typeof e?(this.destroy(),void e(t)):("connecting"===this.state&&this.emit("error",t),void this.destroy());if(E(this,"connected"),this.minSize)for(let e=0;e<this.minSize;e++)U(this);"function"==typeof e?e(null,n):this.emit("connect",this,n)})},A.prototype.auth=function(e,t){"function"==typeof t&&t(null,null)},A.prototype.logout=function(e,t){"function"==typeof t&&t(null,null)},A.prototype.unref=function(){this.availableConnections.concat(this.inUseConnections).forEach((function(e){e.unref()}))},A.prototype.destroy=function(e,t){var n=this;if("function"==typeof e&&(t=e,e=!1),this.state!==x&&n.state!==C){if(E(this,"draining"),e){for(var r=n.availableConnections.concat(n.inUseConnections);n.queue.length>0;){var o=n.queue.shift();"function"==typeof o.cb&&o.cb(new i("Pool was force destroyed"))}return P(n,r,{force:!0},t)}this.reconnectId&&clearTimeout(this.reconnectId),function e(){if(n.state!==x&&n.state!==C)if(z(n.queue),0===n.queue.length){for(var r=n.availableConnections.concat(n.inUseConnections),o=0;o<r.length;o++)if(r[o].workItems.length>0)return setTimeout(e,1);P(n,r,{force:!1},t)}else $(n)(),setTimeout(e,1);else"function"==typeof t&&t()}()}else"function"==typeof t&&t(null,null)},A.prototype.reset=function(e){if("connected"!==this.s.state)return void("function"==typeof e&&e(new i("pool is not connected, reset aborted")));this.s.cancellationToken.emit("cancel");const t=this.availableConnections.concat(this.inUseConnections);_(t,(e,t)=>{for(const t of N)e.removeAllListeners(t);e.destroy({force:!0},t)},t=>{t&&"function"==typeof e?e(t,null):(k(this),U(this,()=>{"function"==typeof e&&e(null,null)}))})},A.prototype.write=function(e,t,n){var r=this;if("function"==typeof t&&(n=t),t=t||{},"function"!=typeof n&&!t.noResponse)throw new i("write method must provide a callback");if(this.state!==x&&this.state!==C)if("draining"!==this.state){if(this.options.domainsEnabled&&process.domain&&"function"==typeof n){var o=n;n=process.domain.bind((function(){for(var e=new Array(arguments.length),t=0;t<arguments.length;t++)e[t]=arguments[t];process.nextTick((function(){o.apply(null,e)}))}))}var s={cb:n,raw:!1,promoteLongs:!0,promoteValues:!0,promoteBuffers:!1,fullResult:!1};s.promoteLongs="boolean"!=typeof t.promoteLongs||t.promoteLongs,s.promoteValues="boolean"!=typeof t.promoteValues||t.promoteValues,s.promoteBuffers="boolean"==typeof t.promoteBuffers&&t.promoteBuffers,s.raw="boolean"==typeof t.raw&&t.raw,s.immediateRelease="boolean"==typeof t.immediateRelease&&t.immediateRelease,s.documentsReturnedIn=t.documentsReturnedIn,s.command="boolean"==typeof t.command&&t.command,s.fullResult="boolean"==typeof t.fullResult&&t.fullResult,s.noResponse="boolean"==typeof t.noResponse&&t.noResponse,s.session=t.session||null,s.socketTimeout=t.socketTimeout,s.monitoring=t.monitoring,s.requestId=e.requestId,r.options.monitorCommands&&(this.emit("commandStarted",new b.CommandStartedEvent(this,e)),s.started=T(),s.cb=(t,o)=>{t?r.emit("commandFailed",new b.CommandFailedEvent(this,e,t,s.started)):o&&o.result&&(0===o.result.ok||o.result.$err)?r.emit("commandFailed",new b.CommandFailedEvent(this,e,o.result,s.started)):r.emit("commandSucceeded",new b.CommandSucceededEvent(this,e,o,s.started)),"function"==typeof n&&n(t,o)}),B(r,e,(e,n)=>{if(e)throw e;s.buffer=n,t.monitoring?r.queue.unshift(s):r.queue.push(s),r.executing||process.nextTick((function(){$(r)()}))})}else n(new i("pool is draining, new operations prohibited"));else n(new i("pool destroyed"))},A._execute=$,e.exports=A},function(e,t){e.exports=require("net")},function(e,t,n){"use strict";const{unassigned_code_points:r,commonly_mapped_to_nothing:o,non_ASCII_space_characters:i,prohibited_characters:s,bidirectional_r_al:a,bidirectional_l:c}=n(417);e.exports=function(e,t={}){if("string"!=typeof e)throw new TypeError("Expected string.");if(0===e.length)return"";const n=p(e).map(e=>u.get(e)?32:e).filter(e=>!l.get(e)),o=String.fromCodePoint.apply(null,n).normalize("NFKC"),i=p(o);if(i.some(e=>s.get(e)))throw new Error("Prohibited character, see https://tools.ietf.org/html/rfc4013#section-2.3");if(!0!==t.allowUnassigned){if(i.some(e=>r.get(e)))throw new Error("Unassigned code point, see https://tools.ietf.org/html/rfc4013#section-2.5")}const d=i.some(e=>a.get(e)),h=i.some(e=>c.get(e));if(d&&h)throw new Error("String must not contain RandALCat and LCat at the same time, see https://tools.ietf.org/html/rfc3454#section-6");const m=a.get(f((y=o,y[0]))),g=a.get(f((e=>e[e.length-1])(o)));var y;if(d&&(!m||!g))throw new Error("Bidirectional RandALCat character must be the first and the last character of the string, see https://tools.ietf.org/html/rfc3454#section-6");return o};const u=i,l=o,f=e=>e.codePointAt(0);function p(e){const t=[],n=e.length;for(let r=0;r<n;r+=1){const o=e.charCodeAt(r);if(o>=55296&&o<=56319&&n>r+1){const n=e.charCodeAt(r+1);if(n>=56320&&n<=57343){t.push(1024*(o-55296)+n-56320+65536),r+=1;continue}}t.push(o)}return t}},function(e,t,n){"use strict";(function(t){const r=n(89),o=n(136),i=n(418),s=r.readFileSync(o.resolve(t,"../code-points.mem"));let a=0;function c(){const e=s.readUInt32BE(a);a+=4;const t=s.slice(a,a+e);return a+=e,i({buffer:t})}const u=c(),l=c(),f=c(),p=c(),d=c(),h=c();e.exports={unassigned_code_points:u,commonly_mapped_to_nothing:l,non_ASCII_space_characters:f,prohibited_characters:p,bidirectional_r_al:d,bidirectional_l:h}}).call(this,"/")},function(e,t,n){var r=n(419);function o(e){if(!(this instanceof o))return new o(e);if(e||(e={}),Buffer.isBuffer(e)&&(e={buffer:e}),this.pageOffset=e.pageOffset||0,this.pageSize=e.pageSize||1024,this.pages=e.pages||r(this.pageSize),this.byteLength=this.pages.length*this.pageSize,this.length=8*this.byteLength,(t=this.pageSize)&t-1)throw new Error("The page size should be a power of two");var t;if(this._trackUpdates=!!e.trackUpdates,this._pageMask=this.pageSize-1,e.buffer){for(var n=0;n<e.buffer.length;n+=this.pageSize)this.pages.set(n/this.pageSize,e.buffer.slice(n,n+this.pageSize));this.byteLength=e.buffer.length,this.length=8*this.byteLength}}e.exports=o,o.prototype.get=function(e){var t=7&e,n=(e-t)/8;return!!(this.getByte(n)&128>>t)},o.prototype.getByte=function(e){var t=e&this._pageMask,n=(e-t)/this.pageSize,r=this.pages.get(n,!0);return r?r.buffer[t+this.pageOffset]:0},o.prototype.set=function(e,t){var n=7&e,r=(e-n)/8,o=this.getByte(r);return this.setByte(r,t?o|128>>n:o&(255^128>>n))},o.prototype.toBuffer=function(){for(var e=function(e){if(Buffer.alloc)return Buffer.alloc(e);var t=new Buffer(e);return t.fill(0),t}(this.pages.length*this.pageSize),t=0;t<this.pages.length;t++){var n=this.pages.get(t,!0),r=t*this.pageSize;n&&n.buffer.copy(e,r,this.pageOffset,this.pageOffset+this.pageSize)}return e},o.prototype.setByte=function(e,t){var n=e&this._pageMask,r=(e-n)/this.pageSize,o=this.pages.get(r,!1);return n+=this.pageOffset,o.buffer[n]!==t&&(o.buffer[n]=t,e>=this.byteLength&&(this.byteLength=e+1,this.length=8*this.byteLength),this._trackUpdates&&this.pages.updated(o),!0)}},function(e,t){function n(e,t){if(!(this instanceof n))return new n(e,t);this.length=0,this.updates=[],this.path=new Uint16Array(4),this.pages=new Array(32768),this.maxPages=this.pages.length,this.level=0,this.pageSize=e||1024,this.deduplicate=t?t.deduplicate:null,this.zeros=this.deduplicate?r(this.deduplicate.length):null}function r(e){if(Buffer.alloc)return Buffer.alloc(e);var t=new Buffer(e);return t.fill(0),t}function o(e,t){this.offset=e*t.length,this.buffer=t,this.updated=!1,this.deduplicate=0}e.exports=n,n.prototype.updated=function(e){for(;this.deduplicate&&e.buffer[e.deduplicate]===this.deduplicate[e.deduplicate];)if(e.deduplicate++,e.deduplicate===this.deduplicate.length){e.deduplicate=0,e.buffer.equals&&e.buffer.equals(this.deduplicate)&&(e.buffer=this.deduplicate);break}!e.updated&&this.updates&&(e.updated=!0,this.updates.push(e))},n.prototype.lastUpdate=function(){if(!this.updates||!this.updates.length)return null;var e=this.updates.pop();return e.updated=!1,e},n.prototype._array=function(e,t){if(e>=this.maxPages){if(t)return;!function(e,t){for(;e.maxPages<t;){var n=e.pages;e.pages=new Array(32768),e.pages[0]=n,e.level++,e.maxPages*=32768}}(this,e)}var n,r;n=e,r=this.path,n=((n=(n-(r[0]=32767&n))/32768)-(r[1]=32767&n))/32768,r[3]=(n-(r[2]=32767&n))/32768&32767;for(var o=this.pages,i=this.level;i>0;i--){var s=this.path[i],a=o[s];if(!a){if(t)return;a=o[s]=new Array(32768)}o=a}return o},n.prototype.get=function(e,t){var n,i,s=this._array(e,t),a=this.path[0],c=s&&s[a];return c||t||(c=s[a]=new o(e,r(this.pageSize)),e>=this.length&&(this.length=e+1)),c&&c.buffer===this.deduplicate&&this.deduplicate&&!t&&(c.buffer=(n=c.buffer,i=Buffer.allocUnsafe?Buffer.allocUnsafe(n.length):new Buffer(n.length),n.copy(i),i),c.deduplicate=0),c},n.prototype.set=function(e,t){var n=this._array(e,!1),i=this.path[0];if(e>=this.length&&(this.length=e+1),!t||this.zeros&&t.equals&&t.equals(this.zeros))n[i]=void 0;else{this.deduplicate&&t.equals&&t.equals(this.deduplicate)&&(t=this.deduplicate);var s=n[i],a=function(e,t){if(e.length===t)return e;if(e.length>t)return e.slice(0,t);var n=r(t);return e.copy(n),n}(t,this.pageSize);s?s.buffer=a:n[i]=new o(e,a)}},n.prototype.toBuffer=function(){for(var e=new Array(this.length),t=r(this.pageSize),n=0;n<e.length;)for(var o=this._array(n,!0),i=0;i<32768&&n<e.length;i++)e[n++]=o&&o[i]?o[i].buffer:t;return Buffer.concat(e)}},function(e,t,n){"use strict";const r=n(33).AuthProvider,o=n(198).MongoCredentials,i=n(3).MongoError,s=n(20),a=n(421),c=n(4).maxWireVersion,u=n(90);let l;try{l=n(422)}catch(e){}const f="http://169.254.169.254",p="/latest/meta-data/iam/security-credentials";function d(e){const t=e.split(".");return 1===t.length||"amazonaws"===t[1]?"us-east-1":t[1]}function h(e,t,n){"function"==typeof t&&(n=t,t={}),t=Object.assign({method:"GET",timeout:1e4,json:!0},u.parse(e),t);const r=a.request(t,e=>{e.setEncoding("utf8");let r="";e.on("data",e=>r+=e),e.on("end",()=>{if(!1!==t.json)try{const e=JSON.parse(r);n(void 0,e)}catch(e){n(new i(`Invalid JSON response: "${r}"`))}else n(void 0,r)})});r.on("error",e=>n(e)),r.end()}e.exports=class extends r{auth(e,t){const n=e.connection,r=e.credentials;if(c(n)<9)return void t(new i("MONGODB-AWS authentication requires MongoDB version 4.4 or later"));if(null==l)return void t(new i("MONGODB-AWS authentication requires the `aws4` module, please install it as a dependency of your project"));if(null==r.username)return void function(e,t){function n(n){null!=n.AccessKeyId&&null!=n.SecretAccessKey&&null!=n.Token?t(void 0,new o({username:n.AccessKeyId,password:n.SecretAccessKey,source:e.source,mechanism:"MONGODB-AWS",mechanismProperties:{AWS_SESSION_TOKEN:n.Token}})):t(new i("Could not obtain temporary MONGODB-AWS credentials"))}if(process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI)return void h(`http://169.254.170.2${process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI}`,(e,r)=>{if(e)return t(e);n(r)});h(`${f}/latest/api/token`,{method:"PUT",json:!1,headers:{"X-aws-ec2-metadata-token-ttl-seconds":30}},(e,r)=>{if(e)return t(e);h(`${f}/${p}`,{json:!1,headers:{"X-aws-ec2-metadata-token":r}},(e,o)=>{if(e)return t(e);h(`${f}/${p}/${o}`,{headers:{"X-aws-ec2-metadata-token":r}},(e,r)=>{if(e)return t(e);n(r)})})})}(r,(n,r)=>{if(n)return t(n);e.credentials=r,this.auth(e,t)});const a=r.username,u=r.password,m=r.source,g=r.mechanismProperties.AWS_SESSION_TOKEN,y=this.bson;s.randomBytes(32,(e,r)=>{if(e)return void t(e);const o={saslStart:1,mechanism:"MONGODB-AWS",payload:y.serialize({r:r,p:110})};n.command(`${m}.$cmd`,o,(e,o)=>{if(e)return t(e);const s=o.result,c=y.deserialize(s.payload.buffer),f=c.h,p=c.s.buffer;if(64!==p.length)return void t(new i(`Invalid server nonce length ${p.length}, expected 64`));if(0!==p.compare(r,0,r.length,0,r.length))return void t(new i("Server nonce does not begin with client nonce"));if(f.length<1||f.length>255||-1!==f.indexOf(".."))return void t(new i(`Server returned an invalid host: "${f}"`));const h="Action=GetCallerIdentity&Version=2011-06-15",b=l.sign({method:"POST",host:f,region:d(c.h),service:"sts",headers:{"Content-Type":"application/x-www-form-urlencoded","Content-Length":h.length,"X-MongoDB-Server-Nonce":p.toString("base64"),"X-MongoDB-GS2-CB-Flag":"n"},path:"/",body:h},{accessKeyId:a,secretAccessKey:u,token:g}),v={a:b.headers.Authorization,d:b.headers["X-Amz-Date"]};g&&(v.t=g);const S={saslContinue:1,conversationId:1,payload:y.serialize(v)};n.command(`${m}.$cmd`,S,e=>{if(e)return t(e);t()})})})}}},function(e,t){e.exports=require("http")},function(e,t,n){var r=t,o=n(90),i=n(137),s=n(20),a=n(423)(1e3);function c(e,t,n){return s.createHmac("sha256",e).update(t,"utf8").digest(n)}function u(e,t){return s.createHash("sha256").update(e,"utf8").digest(t)}function l(e){return e.replace(/[!'()*]/g,(function(e){return"%"+e.charCodeAt(0).toString(16).toUpperCase()}))}function f(e){return l(encodeURIComponent(e))}function p(e,t){"string"==typeof e&&(e=o.parse(e));var n=e.headers=e.headers||{},r=this.matchHost(e.hostname||e.host||n.Host||n.host);this.request=e,this.credentials=t||this.defaultCredentials(),this.service=e.service||r[0]||"",this.region=e.region||r[1]||"us-east-1","email"===this.service&&(this.service="ses"),!e.method&&e.body&&(e.method="POST"),n.Host||n.host||(n.Host=e.hostname||e.host||this.createHost(),e.port&&(n.Host+=":"+e.port)),e.hostname||e.host||(e.hostname=n.Host||n.host),this.isCodeCommitGit="codecommit"===this.service&&"GIT"===e.method}p.prototype.matchHost=function(e){var t=((e||"").match(/([^\.]+)\.(?:([^\.]*)\.)?amazonaws\.com(\.cn)?$/)||[]).slice(1,3);return"es"===t[1]&&(t=t.reverse()),t},p.prototype.isSingleRegion=function(){return["s3","sdb"].indexOf(this.service)>=0&&"us-east-1"===this.region||["cloudfront","ls","route53","iam","importexport","sts"].indexOf(this.service)>=0},p.prototype.createHost=function(){var e=this.isSingleRegion()?"":("s3"===this.service&&"us-east-1"!==this.region?"-":".")+this.region;return("ses"===this.service?"email":this.service)+e+".amazonaws.com"},p.prototype.prepareRequest=function(){this.parsePath();var e,t=this.request,n=t.headers;t.signQuery?(this.parsedPath.query=e=this.parsedPath.query||{},this.credentials.sessionToken&&(e["X-Amz-Security-Token"]=this.credentials.sessionToken),"s3"!==this.service||e["X-Amz-Expires"]||(e["X-Amz-Expires"]=86400),e["X-Amz-Date"]?this.datetime=e["X-Amz-Date"]:e["X-Amz-Date"]=this.getDateTime(),e["X-Amz-Algorithm"]="AWS4-HMAC-SHA256",e["X-Amz-Credential"]=this.credentials.accessKeyId+"/"+this.credentialString(),e["X-Amz-SignedHeaders"]=this.signedHeaders()):(t.doNotModifyHeaders||this.isCodeCommitGit||(!t.body||n["Content-Type"]||n["content-type"]||(n["Content-Type"]="application/x-www-form-urlencoded; charset=utf-8"),!t.body||n["Content-Length"]||n["content-length"]||(n["Content-Length"]=Buffer.byteLength(t.body)),!this.credentials.sessionToken||n["X-Amz-Security-Token"]||n["x-amz-security-token"]||(n["X-Amz-Security-Token"]=this.credentials.sessionToken),"s3"!==this.service||n["X-Amz-Content-Sha256"]||n["x-amz-content-sha256"]||(n["X-Amz-Content-Sha256"]=u(this.request.body||"","hex")),n["X-Amz-Date"]||n["x-amz-date"]?this.datetime=n["X-Amz-Date"]||n["x-amz-date"]:n["X-Amz-Date"]=this.getDateTime()),delete n.Authorization,delete n.authorization)},p.prototype.sign=function(){return this.parsedPath||this.prepareRequest(),this.request.signQuery?this.parsedPath.query["X-Amz-Signature"]=this.signature():this.request.headers.Authorization=this.authHeader(),this.request.path=this.formatPath(),this.request},p.prototype.getDateTime=function(){if(!this.datetime){var e=this.request.headers,t=new Date(e.Date||e.date||new Date);this.datetime=t.toISOString().replace(/[:\-]|\.\d{3}/g,""),this.isCodeCommitGit&&(this.datetime=this.datetime.slice(0,-1))}return this.datetime},p.prototype.getDate=function(){return this.getDateTime().substr(0,8)},p.prototype.authHeader=function(){return["AWS4-HMAC-SHA256 Credential="+this.credentials.accessKeyId+"/"+this.credentialString(),"SignedHeaders="+this.signedHeaders(),"Signature="+this.signature()].join(", ")},p.prototype.signature=function(){var e,t,n,r=this.getDate(),o=[this.credentials.secretAccessKey,r,this.region,this.service].join(),i=a.get(o);return i||(e=c("AWS4"+this.credentials.secretAccessKey,r),t=c(e,this.region),n=c(t,this.service),i=c(n,"aws4_request"),a.set(o,i)),c(i,this.stringToSign(),"hex")},p.prototype.stringToSign=function(){return["AWS4-HMAC-SHA256",this.getDateTime(),this.credentialString(),u(this.canonicalString(),"hex")].join("\n")},p.prototype.canonicalString=function(){this.parsedPath||this.prepareRequest();var e,t=this.parsedPath.path,n=this.parsedPath.query,r=this.request.headers,o="",i="s3"!==this.service,s="s3"===this.service||this.request.doNotEncodePath,a="s3"===this.service,c="s3"===this.service;if(e="s3"===this.service&&this.request.signQuery?"UNSIGNED-PAYLOAD":this.isCodeCommitGit?"":r["X-Amz-Content-Sha256"]||r["x-amz-content-sha256"]||u(this.request.body||"","hex"),n){var l=Object.keys(n).reduce((function(e,t){return t?(e[f(t)]=Array.isArray(n[t])&&c?n[t][0]:n[t],e):e}),{}),p=[];Object.keys(l).sort().forEach((function(e){Array.isArray(l[e])?l[e].map(f).sort().forEach((function(t){p.push(e+"="+t)})):p.push(e+"="+f(l[e]))})),o=p.join("&")}return"/"!==t&&(i&&(t=t.replace(/\/{2,}/g,"/")),"/"!==(t=t.split("/").reduce((function(e,t){return i&&".."===t?e.pop():i&&"."===t||(s&&(t=decodeURIComponent(t).replace(/\+/g," ")),e.push(f(t))),e}),[]).join("/"))[0]&&(t="/"+t),a&&(t=t.replace(/%2F/g,"/"))),[this.request.method||"GET",t,o,this.canonicalHeaders()+"\n",this.signedHeaders(),e].join("\n")},p.prototype.canonicalHeaders=function(){var e=this.request.headers;return Object.keys(e).sort((function(e,t){return e.toLowerCase()<t.toLowerCase()?-1:1})).map((function(t){return t.toLowerCase()+":"+e[t].toString().trim().replace(/\s+/g," ")})).join("\n")},p.prototype.signedHeaders=function(){return Object.keys(this.request.headers).map((function(e){return e.toLowerCase()})).sort().join(";")},p.prototype.credentialString=function(){return[this.getDate(),this.region,this.service,"aws4_request"].join("/")},p.prototype.defaultCredentials=function(){var e=process.env;return{accessKeyId:e.AWS_ACCESS_KEY_ID||e.AWS_ACCESS_KEY,secretAccessKey:e.AWS_SECRET_ACCESS_KEY||e.AWS_SECRET_KEY,sessionToken:e.AWS_SESSION_TOKEN}},p.prototype.parsePath=function(){var e=this.request.path||"/";/[^0-9A-Za-z;,/?:@&=+$\-_.!~*'()#%]/.test(e)&&(e=encodeURI(decodeURI(e)));var t=e.indexOf("?"),n=null;t>=0&&(n=i.parse(e.slice(t+1)),e=e.slice(0,t)),this.parsedPath={path:e,query:n}},p.prototype.formatPath=function(){var e=this.parsedPath.path,t=this.parsedPath.query;return t?(null!=t[""]&&delete t[""],e+"?"+l(i.stringify(t))):e},r.RequestSigner=p,r.sign=function(e,t){return new p(e,t).sign()}},function(e,t){function n(e){this.capacity=0|e,this.map=Object.create(null),this.list=new r}function r(){this.firstNode=null,this.lastNode=null}function o(e,t){this.key=e,this.val=t,this.prev=null,this.next=null}e.exports=function(e){return new n(e)},n.prototype.get=function(e){var t=this.map[e];if(null!=t)return this.used(t),t.val},n.prototype.set=function(e,t){var n=this.map[e];if(null!=n)n.val=t;else{if(this.capacity||this.prune(),!this.capacity)return!1;n=new o(e,t),this.map[e]=n,this.capacity--}return this.used(n),!0},n.prototype.used=function(e){this.list.moveToFront(e)},n.prototype.prune=function(){var e=this.list.pop();null!=e&&(delete this.map[e.key],this.capacity++)},r.prototype.moveToFront=function(e){this.firstNode!=e&&(this.remove(e),null==this.firstNode?(this.firstNode=e,this.lastNode=e,e.prev=null,e.next=null):(e.prev=null,e.next=this.firstNode,e.next.prev=e,this.firstNode=e))},r.prototype.pop=function(){var e=this.lastNode;return null!=e&&this.remove(e),e},r.prototype.remove=function(e){this.firstNode==e?this.firstNode=e.next:null!=e.prev&&(e.prev.next=e.next),this.lastNode==e?this.lastNode=e.prev:null!=e.next&&(e.next.prev=e.prev)}},function(e,t,n){"use strict";const r=n(3).MongoError,o=n(6).collectionNamespace,i=n(55),s=n(0).decorateWithExplain,a=n(91).Explain;e.exports=function(e,t,n,c,u,l,f){if(0===u.length)throw new r(`${t} must contain at least one document`);"function"==typeof l&&(f=l,l={});const p="boolean"!=typeof(l=l||{}).ordered||l.ordered,d=l.writeConcern;let h={};if(h[t]=o(c),h[n]=u,h.ordered=p,d&&Object.keys(d).length>0&&(h.writeConcern=d),l.collation)for(let e=0;e<h[n].length;e++)h[n][e].collation||(h[n][e].collation=l.collation);!0===l.bypassDocumentValidation&&(h.bypassDocumentValidation=l.bypassDocumentValidation);const m=a.fromOptions(l);m&&(h=s(h,m));const g=Object.assign({checkKeys:"insert"===t,numberToReturn:1},l);i(e,c,h,g,f)}},function(e,t,n){"use strict";const r=n(21).KillCursor,o=n(3).MongoError,i=n(3).MongoNetworkError,s=n(6).collectionNamespace,a=n(4).maxWireVersion,c=n(4).emitWarning,u=n(55);e.exports=function(e,t,n,l){l="function"==typeof l?l:()=>{};const f=n.cursorId;if(a(e)<4){const o=e.s.bson,i=e.s.pool,s=new r(o,t,[f]),a={immediateRelease:!0,noResponse:!0};if("object"==typeof n.session&&(a.session=n.session),i&&i.isConnected())try{i.write(s,a,l)}catch(e){"function"==typeof l?l(e,null):c(e)}return}const p={killCursors:s(t),cursors:[f]},d={};"object"==typeof n.session&&(d.session=n.session),u(e,t,p,d,(e,t)=>{if(e)return l(e);const n=t.message;return n.cursorNotFound?l(new i("cursor killed or timed out"),null):Array.isArray(n.documents)&&0!==n.documents.length?void l(null,n.documents[0]):l(new o(`invalid killCursors result returned for cursor id ${f}`))})}},function(e,t,n){"use strict";const r=n(21).GetMore,o=n(9).retrieveBSON,i=n(3).MongoError,s=n(3).MongoNetworkError,a=o().Long,c=n(6).collectionNamespace,u=n(4).maxWireVersion,l=n(6).applyCommonQueryOptions,f=n(55);e.exports=function(e,t,n,o,p,d){p=p||{};const h=u(e);function m(e,t){if(e)return d(e);const r=t.message;if(r.cursorNotFound)return d(new s("cursor killed or timed out"),null);if(h<4){const e="number"==typeof r.cursorId?a.fromNumber(r.cursorId):r.cursorId;return n.documents=r.documents,n.cursorId=e,void d(null,null,r.connection)}if(0===r.documents[0].ok)return d(new i(r.documents[0]));const o="number"==typeof r.documents[0].cursor.id?a.fromNumber(r.documents[0].cursor.id):r.documents[0].cursor.id;n.documents=r.documents[0].cursor.nextBatch,n.cursorId=o,d(null,r.documents[0],r.connection)}if(h<4){const i=e.s.bson,s=new r(i,t,n.cursorId,{numberToReturn:o}),a=l({},n);return void e.s.pool.write(s,a,m)}const g={getMore:n.cursorId instanceof a?n.cursorId:a.fromNumber(n.cursorId),collection:c(t),batchSize:Math.abs(o)};n.cmd.tailable&&"number"==typeof n.cmd.maxAwaitTimeMS&&(g.maxTimeMS=n.cmd.maxAwaitTimeMS);const y=Object.assign({returnFieldSelector:null,documentsReturnedIn:"nextBatch"},p);n.session&&(y.session=n.session),f(e,t,g,y,m)}},function(e,t,n){"use strict";const r=n(21).Query,o=n(3).MongoError,i=n(6).getReadPreference,s=n(6).collectionNamespace,a=n(6).isSharded,c=n(4).maxWireVersion,u=n(6).applyCommonQueryOptions,l=n(55),f=n(0).decorateWithExplain,p=n(91).Explain;e.exports=function(e,t,n,d,h,m){if(h=h||{},null!=d.cursorId)return m();if(null==n)return m(new o(`command ${JSON.stringify(n)} does not return a cursor`));if(c(e)<4){const s=function(e,t,n,s,c){c=c||{};const u=e.s.bson,l=i(n,c);s.batchSize=n.batchSize||s.batchSize;let f=0;f=s.limit<0||0!==s.limit&&s.limit<s.batchSize||s.limit>0&&0===s.batchSize?s.limit:s.batchSize;const p=s.skip||0,d={};a(e)&&l&&(d.$readPreference=l.toJSON());n.sort&&(d.$orderby=n.sort);n.hint&&(d.$hint=n.hint);n.snapshot&&(d.$snapshot=n.snapshot);void 0!==n.returnKey&&(d.$returnKey=n.returnKey);n.maxScan&&(d.$maxScan=n.maxScan);n.min&&(d.$min=n.min);n.max&&(d.$max=n.max);void 0!==n.showDiskLoc&&(d.$showDiskLoc=n.showDiskLoc);n.comment&&(d.$comment=n.comment);n.maxTimeMS&&(d.$maxTimeMS=n.maxTimeMS);void 0!==c.explain&&(f=-Math.abs(n.limit||0),d.$explain=!0);if(d.$query=n.query,n.readConcern&&"local"!==n.readConcern.level)throw new o(`server find command does not support a readConcern level of ${n.readConcern.level}`);n.readConcern&&delete(n=Object.assign({},n)).readConcern;const h="boolean"==typeof c.serializeFunctions&&c.serializeFunctions,m="boolean"==typeof c.ignoreUndefined&&c.ignoreUndefined,g=new r(u,t,d,{numberToSkip:p,numberToReturn:f,pre32Limit:void 0!==n.limit?n.limit:void 0,checkKeys:!1,returnFieldSelector:n.fields,serializeFunctions:h,ignoreUndefined:m});"boolean"==typeof n.tailable&&(g.tailable=n.tailable);"boolean"==typeof n.oplogReplay&&(g.oplogReplay=n.oplogReplay);"boolean"==typeof n.noCursorTimeout&&(g.noCursorTimeout=n.noCursorTimeout);"boolean"==typeof n.awaitData&&(g.awaitData=n.awaitData);"boolean"==typeof n.partial&&(g.partial=n.partial);return g.slaveOk=l.slaveOk(),g}(e,t,n,d,h),c=u({},d);return"string"==typeof s.documentsReturnedIn&&(c.documentsReturnedIn=s.documentsReturnedIn),void e.s.pool.write(s,c,m)}const g=i(n,h);let y=function(e,t,n,r){r.batchSize=n.batchSize||r.batchSize;const o={find:s(t)};n.query&&(n.query.$query?o.filter=n.query.$query:o.filter=n.query);let i=n.sort;if(Array.isArray(i)){const e={};if(i.length>0&&!Array.isArray(i[0])){let t=i[1];"asc"===t?t=1:"desc"===t&&(t=-1),e[i[0]]=t}else for(let t=0;t<i.length;t++){let n=i[t][1];"asc"===n?n=1:"desc"===n&&(n=-1),e[i[t][0]]=n}i=e}"boolean"==typeof n.allowDiskUse&&(o.allowDiskUse=n.allowDiskUse);n.sort&&(o.sort=i);n.fields&&(o.projection=n.fields);n.hint&&(o.hint=n.hint);n.skip&&(o.skip=n.skip);n.limit&&(o.limit=n.limit);n.limit<0&&(o.limit=Math.abs(n.limit),o.singleBatch=!0);"number"==typeof n.batchSize&&(n.batchSize<0&&(0!==n.limit&&Math.abs(n.batchSize)<Math.abs(n.limit)&&(o.limit=Math.abs(n.batchSize)),o.singleBatch=!0),o.batchSize=Math.abs(n.batchSize));n.comment&&(o.comment=n.comment);n.maxScan&&(o.maxScan=n.maxScan);n.maxTimeMS&&(o.maxTimeMS=n.maxTimeMS);n.min&&(o.min=n.min);n.max&&(o.max=n.max);o.returnKey=!!n.returnKey&&n.returnKey,o.showRecordId=!!n.showDiskLoc&&n.showDiskLoc,n.snapshot&&(o.snapshot=n.snapshot);n.tailable&&(o.tailable=n.tailable);n.oplogReplay&&(o.oplogReplay=n.oplogReplay);n.noCursorTimeout&&(o.noCursorTimeout=n.noCursorTimeout);n.awaitData&&(o.awaitData=n.awaitData);n.awaitdata&&(o.awaitData=n.awaitdata);n.partial&&(o.partial=n.partial);n.collation&&(o.collation=n.collation);n.readConcern&&(o.readConcern=n.readConcern);return o}(0,t,n,d);const b=p.fromOptions(h);b&&(y=f(y,b)),n.virtual=!1;const v=Object.assign({documentsReturnedIn:"firstBatch",numberToReturn:1,slaveOk:g.slaveOk()},h);n.readPreference&&(v.readPreference=g),d.session&&(v.session=d.session),l(e,t,y,v,m)}},function(e,t,n){"use strict";const r=n(5).inherits,o=n(5).format,i=n(8).EventEmitter,s=n(10),a=n(17).CoreCursor,c=n(9).retrieveBSON,u=n(16),l=n(3).MongoError,f=n(134),p=n(429),d=n(7).Timeout,h=n(7).Interval,m=n(7).SessionMixins,g=n(7).isRetryableWritesSupported,y=n(4).relayEvents,b=c(),v=n(7).getMMAPError,S=n(4).makeClientMetadata,w=n(7).legacyIsRetryableWriteError,_=n(0).now,O=n(0).calculateDurationInMs;var T="destroyed";function C(e,t){var n={disconnected:["connecting",T,"disconnected"],connecting:["connecting",T,"connected","disconnected"],connected:["connected","disconnected",T,"unreferenced"],unreferenced:["unreferenced",T],destroyed:[T]}[e.state];n&&-1!==n.indexOf(t)?e.state=t:e.s.logger.error(o("Pool with id [%s] failed attempted illegal state transition from [%s] to [%s] only following state allowed [%s]",e.id,e.state,t,n))}var x=1,E=["connect","close","error","timeout","parseError"],N=function(e,t){var n=this;if(t=t||{},!Array.isArray(e))throw new l("seedlist must be an array");if(0===e.length)throw new l("seedlist must contain at least one entry");e.forEach((function(e){if("string"!=typeof e.host||"number"!=typeof e.port)throw new l("seedlist entry must contain a host and port")})),i.call(this),this.id=x++;var r=t.localThresholdMS||15;t.acceptableLatency&&(r=t.acceptableLatency);var s=u("ReplSet",t);this.s={options:Object.assign({metadata:S(t)},t),bson:t.bson||new b([b.Binary,b.Code,b.DBRef,b.Decimal128,b.Double,b.Int32,b.Long,b.Map,b.MaxKey,b.MinKey,b.ObjectId,b.BSONRegExp,b.Symbol,b.Timestamp]),Cursor:t.cursorFactory||a,logger:s,seedlist:e,replicaSetState:new p({id:this.id,setName:t.setName,acceptableLatency:r,heartbeatFrequencyMS:t.haInterval?t.haInterval:1e4,logger:s}),connectingServers:[],haInterval:t.haInterval?t.haInterval:1e4,minHeartbeatFrequencyMS:500,disconnectHandler:t.disconnectHandler,index:0,connectOptions:{},debug:"boolean"==typeof t.debug&&t.debug},this.s.replicaSetState.on("topologyDescriptionChanged",(function(e){n.emit("topologyDescriptionChanged",e)})),this.s.logger.isWarn()&&0!==this.s.options.socketTimeout&&this.s.options.socketTimeout<this.s.haInterval&&this.s.logger.warn(o("warning socketTimeout %s is less than haInterval %s. This might cause unnecessary server reconnections due to socket timeouts",this.s.options.socketTimeout,this.s.haInterval));["joined","left"].forEach((function(e){n.s.replicaSetState.on(e,(function(t,r){n.emit(e,t,r)}))})),this.initialConnectState={connect:!1,fullsetup:!1,all:!1},this.state="disconnected",this.haTimeoutId=null,this.ismaster=null,this.intervalIds=[],this.clusterTime=null};function I(e){e.s.replicaSetState.hasPrimaryAndSecondary()&&e.s.disconnectHandler?e.s.disconnectHandler.execute():e.s.replicaSetState.hasPrimary()&&e.s.disconnectHandler?e.s.disconnectHandler.execute({executePrimary:!0}):e.s.replicaSetState.hasSecondary()&&e.s.disconnectHandler&&e.s.disconnectHandler.execute({executeSecondary:!0})}function A(e,t,n){if(0===t.length)return n();var r=t.length,o=null;function i(){0===(r-=1)&&n(o)}var s=function(e,t){return function(n){if(e.state===T||"unreferenced"===e.state)return this.destroy({force:!0}),i();if("connect"===t)if(e.s.replicaSetState.update(this)){this.lastIsMaster()&&this.lastIsMaster().ismaster&&(e.ismaster=this.lastIsMaster());for(let e=0;e<E.length;e++)this.removeAllListeners(E[e]);this.on("error",j(e,"error")),this.on("close",j(e,"close")),this.on("timeout",j(e,"timeout")),this.on("parseError",j(e,"parseError")),k(this.lastIsMaster().me,e,{}),I(e)}else this.destroy({force:!0});else"error"===t&&(o=n);I(e),i()}};function a(t,n){setTimeout((function(){if(e.state===T||"unreferenced"===e.state)return;const n=e.s.connectingServers.findIndex(e=>e.name===t);if(n>=0){return e.s.connectingServers[n].destroy({force:!0}),e.s.connectingServers.splice(n,1),i()}var r=new f(Object.assign({},e.s.options,{host:t.split(":")[0],port:parseInt(t.split(":")[1],10),reconnect:!1,monitoring:!1,parent:e}));r.once("connect",s(e,"connect")),r.once("close",s(e,"close")),r.once("timeout",s(e,"timeout")),r.once("error",s(e,"error")),r.once("parseError",s(e,"parseError")),r.on("serverOpening",t=>e.emit("serverOpening",t)),r.on("serverDescriptionChanged",t=>e.emit("serverDescriptionChanged",t)),r.on("serverClosed",t=>e.emit("serverClosed",t)),y(r,e,["commandStarted","commandSucceeded","commandFailed"]),e.s.connectingServers.push(r),r.connect(e.s.connectOptions)}),n)}for(var c=0;c<t.length;c++)a(t[c],c)}r(N,i),Object.assign(N.prototype,m),Object.defineProperty(N.prototype,"type",{enumerable:!0,get:function(){return"replset"}}),Object.defineProperty(N.prototype,"parserType",{enumerable:!0,get:function(){return b.native?"c++":"js"}}),Object.defineProperty(N.prototype,"logicalSessionTimeoutMinutes",{enumerable:!0,get:function(){return this.s.replicaSetState.logicalSessionTimeoutMinutes||null}});var k=function(e,t,n){if(!n.haInterval)for(var r=0;r<t.intervalIds.length;r++)if(t.intervalIds[r].__host===e)return;var o=n.haInterval?d:h,i=n.haInterval?n.haInterval:t.s.haInterval,s=new o((function(){if(t.state!==T&&"unreferenced"!==t.state){var n=t.s.replicaSetState.get(e);return n?function(e,t,n){var r=(new Date).getTime();P(e,"serverHeartbeatStarted",{connectionId:t.name}),t.command("admin.$cmd",{ismaster:!0},{monitoring:!0,socketTimeout:e.s.options.connectionTimeout||2e3},(function(o,i){if(e.state===T||"unreferenced"===e.state)return t.destroy({force:!0}),n(o,i);var s=(new Date).getTime()-r;t.lastUpdateTime=_(),o?(P(e,"serverHeartbeatFailed",{durationMS:s,failure:o,connectionId:t.name}),e.s.replicaSetState.remove(t)):(t.ismaster=i.result,t.ismaster.lastWrite&&t.ismaster.lastWrite.lastWriteDate&&(t.lastWriteDate=t.ismaster.lastWrite.lastWriteDate.getTime()),-1===t.lastIsMasterMS?t.lastIsMasterMS=s:t.lastIsMasterMS&&(t.lastIsMasterMS=.2*s+.8*t.lastIsMasterMS),e.s.replicaSetState.update(t)&&t.lastIsMaster()&&t.lastIsMaster().ismaster&&(e.ismaster=t.lastIsMaster()),P(e,"serverHeartbeatSucceeded",{durationMS:s,reply:i.result,connectionId:t.name})),e.s.replicaSetState.updateServerMaxStaleness(t,e.s.haInterval),n(o,i)}))}(t,n,(function(e){e||(t.state!==T&&"unreferenced"!==t.state?(t.intervalIds=t.intervalIds.filter((function(e){return e.isRunning()})),o===d?"connecting"===t.state&&(t.s.replicaSetState.hasSecondary()&&t.s.options.secondaryOnlyConnectionAllowed||t.s.replicaSetState.hasPrimary())&&(C(t,"connected"),process.nextTick((function(){t.emit("connect",t)})),M(t,{})):"disconnected"===t.state&&(t.s.replicaSetState.hasSecondary()&&t.s.options.secondaryOnlyConnectionAllowed||t.s.replicaSetState.hasPrimary())&&(C(t,"connected"),I(t),process.nextTick((function(){t.emit("reconnect",t)}))),t.initialConnectState.connect&&!t.initialConnectState.fullsetup&&t.s.replicaSetState.hasPrimaryAndSecondary()&&(t.initialConnectState.fullsetup=!0,t.initialConnectState.all=!0,process.nextTick((function(){t.emit("fullsetup",t),t.emit("all",t)})))):s.stop())})):void 0}s.stop()}),i);s.start(),s.__host=e,t.intervalIds.push(s)};function M(e,t){if(e.state!==T&&"unreferenced"!==e.state){t=t||{};var n=Object.keys(e.s.replicaSetState.set),r=t.haInterval?d:h,o=t.haInterval?t.haInterval:e.s.haInterval;if(r===d)return A(e,e.s.replicaSetState.unknownServers,(function(r){if(e.state!==T&&"unreferenced"!==e.state){if(!e.s.replicaSetState.hasPrimary()&&!e.s.options.secondaryOnlyConnectionAllowed)return r?e.emit("error",r):(e.emit("error",new l("no primary found in replicaset or invalid replica set name")),e.destroy({force:!0}));if(!e.s.replicaSetState.hasSecondary()&&e.s.options.secondaryOnlyConnectionAllowed)return r?e.emit("error",r):(e.emit("error",new l("no secondary found in replicaset or invalid replica set name")),e.destroy({force:!0}));for(var o=0;o<n.length;o++)k(n[o],e,t)}}));for(var i=0;i<n.length;i++)k(n[i],e,t);var s=e.s.replicaSetState.hasPrimary()?o:e.s.minHeartbeatFrequencyMS;e.intervalIds.push(new d(function e(t){return function(){t.state!==T&&"unreferenced"!==t.state&&A(t,t.s.replicaSetState.unknownServers,(function(){var n=t.s.replicaSetState.hasPrimary()?o:t.s.minHeartbeatFrequencyMS;t.intervalIds.push(new d(e(t),n).start())}))}}(e),s).start())}}function R(e,t){for(var n=0;n<e.length;n++)if(e[n].name.toLowerCase()===t.name.toLowerCase())return!0;e.push(t)}function j(e,t){return function(){e.state!==T&&"unreferenced"!==e.state&&(e.s.logger.isDebug()&&e.s.logger.debug(o("handleEvent %s from server %s in replset with id %s",t,this.name,e.id)),e.s.replicaSetState.remove(this),e.state!==T&&"unreferenced"!==e.state&&((e.s.replicaSetState.hasPrimary()||e.s.replicaSetState.hasSecondary()||!e.s.options.secondaryOnlyConnectionAllowed)&&e.s.replicaSetState.hasPrimary()||C(e,"disconnected"),R(e.s.connectingServers,this)))}}function D(e,t){return function(){if(e.s.logger.isDebug()&&e.s.logger.debug(o("handleInitialConnectEvent %s from server %s in replset with id %s",t,this.name,e.id)),e.state===T||"unreferenced"===e.state)return this.destroy({force:!0});if("connect"===t){var n=e.s.replicaSetState.update(this);if(!0===n){this.lastIsMaster()&&this.lastIsMaster().ismaster&&(e.ismaster=this.lastIsMaster()),e.s.logger.isDebug()&&e.s.logger.debug(o("handleInitialConnectEvent %s from server %s in replset with id %s has state [%s]",t,this.name,e.id,JSON.stringify(e.s.replicaSetState.set)));for(let e=0;e<E.length;e++)this.removeAllListeners(E[e]);this.on("error",j(e,"error")),this.on("close",j(e,"close")),this.on("timeout",j(e,"timeout")),this.on("parseError",j(e,"parseError")),function(e){const t="connecting"===e.state,n=e.s.replicaSetState.hasPrimary(),r=e.s.replicaSetState.hasSecondary(),o=e.s.options.secondaryOnlyConnectionAllowed,i=e.s.connectOptions.readPreference&&e.s.connectOptions.readPreference.equals(s.secondary);return t&&(i&&r||!i&&n)||r&&o}(e)&&(C(e,"connected"),e.initialConnectState.connect=!0,process.nextTick((function(){e.emit("connect",e)})),M(e,{}))}else{if(n instanceof l)return this.destroy({force:!0}),e.destroy({force:!0}),e.emit("error",n);this.destroy({force:!0})}}else e.emit("failed",this),R(e.s.connectingServers,this),e.s.replicaSetState.remove(this);e.initialConnectState.connect&&!e.initialConnectState.fullsetup&&e.s.replicaSetState.hasPrimaryAndSecondary()&&(e.initialConnectState.fullsetup=!0,e.initialConnectState.all=!0,process.nextTick((function(){e.emit("fullsetup",e),e.emit("all",e)})));for(var r=0;r<e.s.connectingServers.length;r++)e.s.connectingServers[r].equals(this)&&e.s.connectingServers.splice(r,1);0===e.s.connectingServers.length&&"connecting"===e.state&&M(e,{haInterval:1})}}function P(e,t,n){e.listeners(t).length>0&&e.emit(t,n)}N.prototype.connect=function(e){var t=this;this.s.connectOptions=e||{},C(this,"connecting");var n=this.s.seedlist.map((function(n){return new f(Object.assign({},t.s.options,n,e,{reconnect:!1,monitoring:!1,parent:t}))}));if(this.s.options.socketTimeout>0&&this.s.options.socketTimeout<=this.s.options.haInterval)return t.emit("error",new l(o("haInterval [%s] MS must be set to less than socketTimeout [%s] MS",this.s.options.haInterval,this.s.options.socketTimeout)));P(this,"topologyOpening",{topologyId:this.id}),function(e,t){e.s.connectingServers=e.s.connectingServers.concat(t);var n=0;function r(t,n){setTimeout((function(){e.s.replicaSetState.update(t)&&t.lastIsMaster()&&t.lastIsMaster().ismaster&&(e.ismaster=t.lastIsMaster()),t.once("close",D(e,"close")),t.once("timeout",D(e,"timeout")),t.once("parseError",D(e,"parseError")),t.once("error",D(e,"error")),t.once("connect",D(e,"connect")),t.on("serverOpening",t=>e.emit("serverOpening",t)),t.on("serverDescriptionChanged",t=>e.emit("serverDescriptionChanged",t)),t.on("serverClosed",t=>e.emit("serverClosed",t)),y(t,e,["commandStarted","commandSucceeded","commandFailed"]),t.connect(e.s.connectOptions)}),n)}for(;t.length>0;)r(t.shift(),n++)}(t,n)},N.prototype.auth=function(e,t){"function"==typeof t&&t(null,null)},N.prototype.destroy=function(e,t){"function"==typeof e&&(t=e,e={}),e=e||{};let n=this.s.connectingServers.length+1;const r=()=>{n--,n>0||(P(this,"topologyClosed",{topologyId:this.id}),"function"==typeof t&&t(null,null))};if(this.state!==T){C(this,T),this.haTimeoutId&&clearTimeout(this.haTimeoutId);for(var o=0;o<this.intervalIds.length;o++)this.intervalIds[o].stop();this.intervalIds=[],0!==n?(this.s.replicaSetState.destroy(e,r),this.s.connectingServers.forEach((function(t){t.destroy(e,r)}))):r()}else"function"==typeof t&&t(null,null)},N.prototype.unref=function(){C(this,"unreferenced"),this.s.replicaSetState.allServers().forEach((function(e){e.unref()})),clearTimeout(this.haTimeoutId)},N.prototype.lastIsMaster=function(){return this.s.options.secondaryOnlyConnectionAllowed&&!this.s.replicaSetState.hasPrimary()&&this.s.replicaSetState.hasSecondary()?this.s.replicaSetState.secondaries[0].lastIsMaster():this.s.replicaSetState.primary?this.s.replicaSetState.primary.lastIsMaster():this.ismaster},N.prototype.connections=function(){for(var e=this.s.replicaSetState.allServers(),t=[],n=0;n<e.length;n++)t=t.concat(e[n].connections());return t},N.prototype.isConnected=function(e){return(e=e||{}).readPreference&&e.readPreference.equals(s.secondary)?this.s.replicaSetState.hasSecondary():e.readPreference&&e.readPreference.equals(s.primary)?this.s.replicaSetState.hasPrimary():e.readPreference&&e.readPreference.equals(s.primaryPreferred)?this.s.replicaSetState.hasSecondary()||this.s.replicaSetState.hasPrimary():e.readPreference&&e.readPreference.equals(s.secondaryPreferred)?this.s.replicaSetState.hasSecondary()||this.s.replicaSetState.hasPrimary():!(!this.s.options.secondaryOnlyConnectionAllowed||!this.s.replicaSetState.hasSecondary())||this.s.replicaSetState.hasPrimary()},N.prototype.isDestroyed=function(){return this.state===T};function B(e,t,n){"function"==typeof t&&(n=t,t={}),t=t||{};const r=e.self,i=e.op,s=e.ns,a=e.ops;if(r.state===T)return n(new l(o("topology was destroyed")));const c=!e.retrying&&!!t.retryWrites&&t.session&&g(r)&&!t.session.inTransaction()&&void 0===t.explain;if(!r.s.replicaSetState.hasPrimary()){if(r.s.disconnectHandler)return r.s.disconnectHandler.add(i,s,a,t,n);if(!c)return n(new l("no primary server found"))}const u=(o,i)=>{if(!o)return n(null,i);if(!w(o,r))return o=v(o),n(o);if(c){return B(Object.assign({},e,{retrying:!0}),t,n)}return r.s.replicaSetState.primary&&(r.s.replicaSetState.primary.destroy(),r.s.replicaSetState.remove(r.s.replicaSetState.primary,{force:!0})),n(o)};n.operationId&&(u.operationId=n.operationId),c&&(t.session.incrementTransactionNumber(),t.willRetryWrite=c),r.s.replicaSetState.primary[i](s,a,t,u)}N.prototype.selectServer=function(e,t,n){let r,o;"function"==typeof e&&void 0===n&&(n=e,e=void 0,t={}),"function"==typeof t&&(n=t,t=e),t=t||{},r=e instanceof s?e:t.readPreference||s.primary;const i=_(),a=()=>{if(O(i)>=1e4)return void(null!=o?n(o,null):n(new l("Server selection timed out")));const e=this.s.replicaSetState.pickServer(r);if(null!=e){if(!(e instanceof f))return o=e,void setTimeout(a,1e3);this.s.debug&&this.emit("pickedServer",t.readPreference,e),n(null,e)}else setTimeout(a,1e3)};a()},N.prototype.getServers=function(){return this.s.replicaSetState.allServers()},N.prototype.insert=function(e,t,n,r){B({self:this,op:"insert",ns:e,ops:t},n,r)},N.prototype.update=function(e,t,n,r){B({self:this,op:"update",ns:e,ops:t},n,r)},N.prototype.remove=function(e,t,n,r){B({self:this,op:"remove",ns:e,ops:t},n,r)};const L=["findAndModify","insert","update","delete"];N.prototype.command=function(e,t,n,r){if("function"==typeof n&&(r=n,n=(n={})||{}),this.state===T)return r(new l(o("topology was destroyed")));var i=this,a=n.readPreference?n.readPreference:s.primary;if("primary"===a.preference&&!this.s.replicaSetState.hasPrimary()&&null!=this.s.disconnectHandler)return this.s.disconnectHandler.add("command",e,t,n,r);if("secondary"===a.preference&&!this.s.replicaSetState.hasSecondary()&&null!=this.s.disconnectHandler)return this.s.disconnectHandler.add("command",e,t,n,r);if("primary"!==a.preference&&!this.s.replicaSetState.hasSecondary()&&!this.s.replicaSetState.hasPrimary()&&null!=this.s.disconnectHandler)return this.s.disconnectHandler.add("command",e,t,n,r);var c=this.s.replicaSetState.pickServer(a);if(!(c instanceof f))return r(c);if(i.s.debug&&i.emit("pickedServer",s.primary,c),null==c)return r(new l(o("no server found that matches the provided readPreference %s",a)));const u=!n.retrying&&!!n.retryWrites&&n.session&&g(i)&&!n.session.inTransaction()&&(p=t,L.some(e=>p[e]));var p;u&&(n.session.incrementTransactionNumber(),n.willRetryWrite=u),c.command(e,t,n,(o,s)=>{if(!o)return r(null,s);if(!w(o,i))return r(o);if(u){const o=Object.assign({},n,{retrying:!0});return this.command(e,t,o,r)}return this.s.replicaSetState.primary&&(this.s.replicaSetState.primary.destroy(),this.s.replicaSetState.remove(this.s.replicaSetState.primary,{force:!0})),r(o)})},N.prototype.cursor=function(e,t,n){const r=(n=n||{}).topology||this;return new(n.cursorFactory||this.s.Cursor)(r,e,t,n)},e.exports=N},function(e,t,n){"use strict";var r=n(5).inherits,o=n(5).format,i=n(7).diff,s=n(8).EventEmitter,a=n(16),c=n(10),u=n(3).MongoError,l=n(22).Buffer,f="ReplicaSetNoPrimary",p="ReplicaSetWithPrimary",d="Unknown",h="PossiblePrimary",m="RSPrimary",g="RSSecondary",y="RSArbiter",b="RSOther",v="RSGhost",S="Unknown",w=function(e){e=e||{},s.call(this),this.topologyType=f,this.setName=e.setName,this.set={},this.id=e.id,this.setName=e.setName,this.logger=e.logger||a("ReplSet",e),this.index=0,this.acceptableLatency=e.acceptableLatency||15,this.heartbeatFrequencyMS=e.heartbeatFrequencyMS||1e4,this.primary=null,this.secondaries=[],this.arbiters=[],this.passives=[],this.ghosts=[],this.unknownServers=[],this.set={},this.maxElectionId=null,this.maxSetVersion=0,this.replicasetDescription={topologyType:"Unknown",servers:[]},this.logicalSessionTimeoutMinutes=void 0};r(w,s),w.prototype.hasPrimaryAndSecondary=function(){return null!=this.primary&&this.secondaries.length>0},w.prototype.hasPrimaryOrSecondary=function(){return this.hasPrimary()||this.hasSecondary()},w.prototype.hasPrimary=function(){return null!=this.primary},w.prototype.hasSecondary=function(){return this.secondaries.length>0},w.prototype.get=function(e){for(var t=this.allServers(),n=0;n<t.length;n++)if(t[n].name.toLowerCase()===e.toLowerCase())return t[n];return null},w.prototype.allServers=function(e){e=e||{};var t=this.primary?[this.primary]:[];return t=t.concat(this.secondaries),e.ignoreArbiters||(t=t.concat(this.arbiters)),t=t.concat(this.passives)},w.prototype.destroy=function(e,t){const n=this.secondaries.concat(this.arbiters).concat(this.passives).concat(this.ghosts);this.primary&&n.push(this.primary);let r=n.length;const o=()=>{r--,r>0||(this.secondaries=[],this.arbiters=[],this.passives=[],this.ghosts=[],this.unknownServers=[],this.set={},this.primary=null,A(this),"function"==typeof t&&t(null,null))};0!==r?n.forEach(t=>t.destroy(e,o)):o()},w.prototype.remove=function(e,t){t=t||{};var n=e.name.toLowerCase(),r=this.primary?[this.primary]:[];r=(r=(r=r.concat(this.secondaries)).concat(this.arbiters)).concat(this.passives);for(var o=0;o<r.length;o++)if(!t.force&&r[o].equals(e)&&r[o].isConnected&&r[o].isConnected())return;this.set[n]&&(this.set[n].type=S,this.set[n].electionId=null,this.set[n].setName=null,this.set[n].setVersion=null);var i=null;this.primary&&this.primary.equals(e)&&(this.primary=null,this.topologyType=f,i="primary"),i=I(e,this.secondaries)?"secondary":i,i=I(e,this.arbiters)?"arbiter":i,i=I(e,this.passives)?"secondary":i,I(e,this.ghosts),I(e,this.unknownServers),this.unknownServers.push(n),i&&this.emit("left",i,e)};const _=e=>e.arbiterOnly&&e.setName;w.prototype.update=function(e){var t=e.lastIsMaster(),n=e.name.toLowerCase();if(t){var r=Array.isArray(t.hosts)?t.hosts:[];r=(r=(r=r.concat(Array.isArray(t.arbiters)?t.arbiters:[])).concat(Array.isArray(t.passives)?t.passives:[])).map((function(e){return e.toLowerCase()}));for(var i=0;i<r.length;i++)-1!==this.unknownServers.indexOf(r[i])||this.set[r[i]]&&this.set[r[i]].type!==S||this.unknownServers.push(r[i].toLowerCase()),this.set[r[i]]||(this.set[r[i]]={type:S,electionId:null,setName:null,setVersion:null})}if(!t&&!x(t,e,this.unknownServers))return this.set[n]={type:S,setVersion:null,electionId:null,setName:null},this.set[n].type=S,this.set[n].electionId=t?t.electionId:t,this.set[n].setName=t?t.setName:t,this.set[n].setVersion=t?t.setVersion:t,-1===this.unknownServers.indexOf(e.name)&&this.unknownServers.push(n),!1;if(void 0===t.logicalSessionTimeoutMinutes||_(t)||(void 0===this.logicalSessionTimeoutMinutes||null===t.logicalSessionTimeoutMinutes?this.logicalSessionTimeoutMinutes=t.logicalSessionTimeoutMinutes:this.logicalSessionTimeoutMinutes=Math.min(this.logicalSessionTimeoutMinutes,t.logicalSessionTimeoutMinutes)),t&&"isdbgrid"===t.msg)return this.primary&&this.primary.name===n&&(this.primary=null,this.topologyType=f),!1;if(t.isreplicaset)return this.set[n]={type:v,setVersion:null,electionId:null,setName:t.setName},this.primary&&this.primary.name===n&&(this.primary=null),this.topologyType=this.primary?p:f,t.setName&&(this.setName=t.setName),!1;if(t.setName&&t.hidden||t.setName&&!t.ismaster&&!t.secondary&&!t.arbiterOnly&&!t.passive)return this.set[n]={type:b,setVersion:null,electionId:null,setName:t.setName},this.topologyType=this.primary?p:f,t.setName&&(this.setName=t.setName),!1;if(t&&t.ismaster&&!t.setName)return this.topologyType=this.primary?p:d,this.remove(e,{force:!0}),!1;if(t&&!t.ismaster&&!t.secondary&&!t.arbiterOnly)return this.remove(e,{force:!0}),!1;if(t.me&&t.me.toLowerCase()!==n)return this.logger.isWarn()&&this.logger.warn(o("the seedlist server was removed due to its address %s not matching its ismaster.me address %s",e.name,t.me)),delete this.set[n],I(e,this.unknownServers),e.destroy({force:!0}),this.primary&&!this.primary.equals(e)?this.topologyType=p:this.topologyType=f,!this.primary&&t.primary&&(this.set[t.primary.toLowerCase()]={type:h,setName:null,electionId:null,setVersion:null}),!1;if(!this.primary&&t.ismaster&&t.setName){var s=e.lastIsMaster().electionId;if(this.setName&&this.setName!==t.setName)return this.topologyType=f,new u(o("setName from ismaster does not match provided connection setName [%s] != [%s]",t.setName,this.setName));if(!this.maxElectionId&&s)this.maxElectionId=s;else if(this.maxElectionId&&s){var a=N(this.maxElectionId,s),c=e.lastIsMaster().setVersion;if(1===a)return this.topologyType=f,!1;if(0===a&&c&&c<this.maxSetVersion)return this.topologyType=f,!1;this.maxSetVersion=c,this.maxElectionId=s}return-1!==t.hosts.map((function(e){return e.toLowerCase()})).indexOf(n)?(this.primary=e,this.set[n]={type:m,setVersion:t.setVersion,electionId:t.electionId,setName:t.setName},this.topologyType=p,t.setName&&(this.setName=t.setName),I(e,this.unknownServers),I(e,this.secondaries),I(e,this.passives),this.emit("joined","primary",e)):this.topologyType=f,A(this),!0}if(t.ismaster&&t.setName){var l=this.set[this.primary.name.toLowerCase()].electionId,w=this.set[this.primary.name.toLowerCase()].setVersion,O=this.set[this.primary.name.toLowerCase()].setName;s=e.lastIsMaster().electionId,c=e.lastIsMaster().setVersion;var T=e.lastIsMaster().setName;if(this.primary.equals(e)&&O===T)return!1;if(O&&O!==T)return this.primary.equals(e)?this.topologyType=f:this.topologyType=p,!1;if(l&&s){if(1===(a=N(l,s)))return!1;if(0===a&&w>c)return!1}else if(!l&&s&&c&&c<this.maxSetVersion)return!1;if(!this.maxElectionId&&s)this.maxElectionId=s;else if(this.maxElectionId&&s){if(1===(a=N(this.maxElectionId,s)))return!1;if(0===a&&w&&c){if(c<this.maxSetVersion)return!1}else if(c<this.maxSetVersion)return!1;this.maxElectionId=s,this.maxSetVersion=c}else this.maxSetVersion=c;return this.set[this.primary.name.toLowerCase()]={type:S,setVersion:null,electionId:null,setName:null},this.emit("left","primary",this.primary),this.primary.destroy({force:!0}),this.primary=e,this.set[n]={type:m,setVersion:t.setVersion,electionId:t.electionId,setName:t.setName},this.topologyType=p,t.setName&&(this.setName=t.setName),I(e,this.unknownServers),I(e,this.secondaries),I(e,this.passives),this.emit("joined","primary",e),A(this),!0}return!this.primary&&t.primary&&(this.set[t.primary.toLowerCase()]={type:h,setVersion:null,electionId:null,setName:null}),t.secondary&&t.setName&&!x(t,e,this.secondaries)&&this.setName&&this.setName===t.setName?(E(this,g,t,e,this.secondaries),this.topologyType=this.primary?p:f,t.setName&&(this.setName=t.setName),I(e,this.unknownServers),this.primary&&this.primary.name.toLowerCase()===n&&(e.destroy({force:!0}),this.primary=null,this.emit("left","primary",e)),this.emit("joined","secondary",e),A(this),!0):_(t)&&!x(t,e,this.arbiters)&&this.setName&&this.setName===t.setName?(E(this,y,t,e,this.arbiters),this.topologyType=this.primary?p:f,t.setName&&(this.setName=t.setName),I(e,this.unknownServers),this.emit("joined","arbiter",e),A(this),!0):t.passive&&t.setName&&!x(t,e,this.passives)&&this.setName&&this.setName===t.setName?(E(this,g,t,e,this.passives),this.topologyType=this.primary?p:f,t.setName&&(this.setName=t.setName),I(e,this.unknownServers),this.primary&&this.primary.name.toLowerCase()===n&&(e.destroy({force:!0}),this.primary=null,this.emit("left","primary",e)),this.emit("joined","secondary",e),A(this),!0):this.set[n]&&this.set[n].type===m?(this.emit("left","primary",this.primary),this.primary.destroy({force:!0}),this.primary=null,this.topologyType=f,!1):(this.topologyType=this.primary?p:f,!1)},w.prototype.updateServerMaxStaleness=function(e,t){for(var n=0,r=0;r<this.secondaries.length;r++)n=Math.max(n,this.secondaries[r].lastWriteDate);e.ismaster.maxWireVersion>=5&&e.ismaster.secondary&&this.hasPrimary()?e.staleness=e.lastUpdateTime-e.lastWriteDate-(this.primary.lastUpdateTime-this.primary.lastWriteDate)+t:e.ismaster.maxWireVersion>=5&&e.ismaster.secondary&&(e.staleness=n-e.lastWriteDate+t)},w.prototype.updateSecondariesMaxStaleness=function(e){for(var t=0;t<this.secondaries.length;t++)this.updateServerMaxStaleness(this.secondaries[t],e)},w.prototype.pickServer=function(e){if("primary"===(e=e||c.primary).preference&&null!=e.maxStalenessSeconds)return new u("primary readPreference incompatible with maxStalenessSeconds");var t=this.primary?[this.primary]:[];if(t=t.concat(this.secondaries),null!=e.maxStalenessSeconds)for(var n=0;n<t.length;n++)if(t[n].ismaster.maxWireVersion<5)return new u("maxStalenessSeconds not supported by at least one of the replicaset members");if("nearest"===e.preference&&null==e.maxStalenessSeconds)return C(this,e);if("nearest"===e.preference&&null!=e.maxStalenessSeconds)return T(this,e);var r=this.secondaries;if(e.equals(c.secondary)&&0===r.length)return new u("no secondary server available");if(e.equals(c.secondaryPreferred)&&0===r.length&&null==this.primary)return new u("no secondary or primary server available");if(e.equals(c.primary)&&null==this.primary)return new u("no primary server available");if(e.equals(c.secondaryPreferred)||e.equals(c.secondary)){if(r.length>0&&null==e.maxStalenessSeconds){var o=C(this,e);if(o)return o}else if(r.length>0&&null!=e.maxStalenessSeconds&&(o=T(this,e)))return o;return e.equals(c.secondaryPreferred)?this.primary:null}if(e.equals(c.primaryPreferred)){if(o=null,this.primary)return this.primary;if(r.length>0&&null==e.maxStalenessSeconds?o=C(this,e):r.length>0&&null!=e.maxStalenessSeconds&&(o=T(this,e)),o)return o}return this.primary};var O=function(e,t){if(null==e.tags)return t;for(var n=[],r=Array.isArray(e.tags)?e.tags:[e.tags],o=0;o<r.length;o++)for(var i=r[o],s=0;s<t.length;s++){var a=t[s].lastIsMaster().tags||{},c=!0;for(var u in i)a[u]!==i[u]&&(c=!1);c&&n.push(t[s])}return n};function T(e,t){var n=[],r=1e3*t.maxStalenessSeconds;if(r<9e4)return new u("maxStalenessSeconds must be set to at least 90 seconds");e.primary&&"secondary"!==t.preference&&"secondaryPreferred"!==t.preference&&n.push(e.primary);for(var o=0;o<e.secondaries.length;o++)n.push(e.secondaries[o]);if(e.primary&&0===n.length&&"secondaryPreferred"!==t.preference&&n.push(e.primary),(n=(n=O(t,n)).filter((function(e){return e.staleness<=r}))).sort((function(e,t){return e.lastIsMasterMS-t.lastIsMasterMS})),0===n.length)return null;e.index=e.index%n.length;var i=n[e.index];return e.index=e.index+1,i}function C(e,t){var n=[];e.primary&&"secondary"!==t.preference&&"secondaryPreferred"!==t.preference&&n.push(e.primary);for(var r=0;r<e.secondaries.length;r++)n.push(e.secondaries[r]);0===n.length&&e.primary&&"secondaryPreferred"!==t.preference&&n.push(e.primary),(n=O(t,n)).sort((function(e,t){return e.lastIsMasterMS-t.lastIsMasterMS}));var o=n.length>0?n[0].lastIsMasterMS:0;if(0===(n=n.filter((function(t){return t.lastIsMasterMS<=o+e.acceptableLatency}))).length)return null;e.index=e.index%n.length;var i=n[e.index];return e.index=e.index+1,i}function x(e,t,n){for(var r=0;r<n.length;r++)if(n[r]&&n[r].name&&n[r].name.toLowerCase()===t.name.toLowerCase())return!0;return!1}function E(e,t,n,r,o){var i=r.name.toLowerCase();e.set[i].type=t,e.set[i].electionId=n?n.electionId:n,e.set[i].setName=n?n.setName:n,e.set[i].setVersion=n?n.setVersion:n,o.push(r)}function N(e,t){var n=l.from(e.toHexString(),"hex"),r=l.from(t.toHexString(),"hex");if(n===r)return 0;if("function"==typeof l.compare)return l.compare(n,r);for(var o=n.length,i=r.length,s=Math.min(o,i),a=0;a<s&&n[a]===r[a];a++);return a!==s&&(o=n[a],i=r[a]),o<i?-1:i<o?1:0}function I(e,t){for(var n=0;n<t.length;n++){if(t[n].equals&&t[n].equals(e))return t.splice(n,1),!0;if("string"==typeof t[n]&&t[n].toLowerCase()===e.name.toLowerCase())return t.splice(n,1),!0}return!1}function A(e){if(e.listeners("topologyDescriptionChanged").length>0){var t="Unknown",n=e.setName;e.hasPrimaryAndSecondary()?t="ReplicaSetWithPrimary":!e.hasPrimary()&&e.hasSecondary()&&(t="ReplicaSetNoPrimary");var r={topologyType:t,setName:n,servers:[]};if(e.hasPrimary()){var o=e.primary.getDescription();o.type="RSPrimary",r.servers.push(o)}r.servers=r.servers.concat(e.secondaries.map((function(e){var t=e.getDescription();return t.type="RSSecondary",t}))),r.servers=r.servers.concat(e.arbiters.map((function(e){var t=e.getDescription();return t.type="RSArbiter",t}))),r.servers=r.servers.concat(e.passives.map((function(e){var t=e.getDescription();return t.type="RSSecondary",t})));var s=i(e.replicasetDescription,r),a={topologyId:e.id,previousDescription:e.replicasetDescription,newDescription:r,diff:s};e.emit("topologyDescriptionChanged",a),e.replicasetDescription=r}}e.exports=w},function(e,t,n){"use strict";const r=n(5).inherits,o=n(5).format,i=n(8).EventEmitter,s=n(17).CoreCursor,a=n(16),c=n(9).retrieveBSON,u=n(3).MongoError,l=n(134),f=n(7).diff,p=n(7).cloneOptions,d=n(7).SessionMixins,h=n(7).isRetryableWritesSupported,m=n(4).relayEvents,g=c(),y=n(7).getMMAPError,b=n(4).makeClientMetadata,v=n(7).legacyIsRetryableWriteError;var S="destroying",w="destroyed";function _(e,t){var n={disconnected:["connecting",S,w,"disconnected"],connecting:["connecting",S,w,"connected","disconnected"],connected:["connected","disconnected",S,w,"unreferenced"],unreferenced:["unreferenced",S,w],destroyed:[w]}[e.state];n&&-1!==n.indexOf(t)?e.state=t:e.s.logger.error(o("Mongos with id [%s] failed attempted illegal state transition from [%s] to [%s] only following state allowed [%s]",e.id,e.state,t,n))}var O=1,T=["connect","close","error","timeout","parseError"],C=function(e,t){t=t||{},this.id=O++,Array.isArray(e)&&(e=e.reduce((e,t)=>e.find(e=>e.host===t.host&&e.port===t.port)?e:(e.push(t),e),[])),this.s={options:Object.assign({metadata:b(t)},t),bson:t.bson||new g([g.Binary,g.Code,g.DBRef,g.Decimal128,g.Double,g.Int32,g.Long,g.Map,g.MaxKey,g.MinKey,g.ObjectId,g.BSONRegExp,g.Symbol,g.Timestamp]),Cursor:t.cursorFactory||s,logger:a("Mongos",t),seedlist:e,haInterval:t.haInterval?t.haInterval:1e4,disconnectHandler:t.disconnectHandler,index:0,connectOptions:{},debug:"boolean"==typeof t.debug&&t.debug,localThresholdMS:t.localThresholdMS||15},this.s.logger.isWarn()&&0!==this.s.options.socketTimeout&&this.s.options.socketTimeout<this.s.haInterval&&this.s.logger.warn(o("warning socketTimeout %s is less than haInterval %s. This might cause unnecessary server reconnections due to socket timeouts",this.s.options.socketTimeout,this.s.haInterval)),this.state="disconnected",this.connectingProxies=[],this.connectedProxies=[],this.disconnectedProxies=[],this.index=0,this.haTimeoutId=null,this.ismaster=null,this.topologyDescription={topologyType:"Unknown",servers:[]},this.clusterTime=null,i.call(this)};function x(e,t,n){e.listeners(t).length>0&&e.emit(t,n)}r(C,i),Object.assign(C.prototype,d),Object.defineProperty(C.prototype,"type",{enumerable:!0,get:function(){return"mongos"}}),Object.defineProperty(C.prototype,"parserType",{enumerable:!0,get:function(){return g.native?"c++":"js"}}),Object.defineProperty(C.prototype,"logicalSessionTimeoutMinutes",{enumerable:!0,get:function(){return this.ismaster&&this.ismaster.logicalSessionTimeoutMinutes||null}});const E=["serverDescriptionChanged","error","close","timeout","parseError"];function N(e,t,n){t=t||{},E.forEach(t=>e.removeAllListeners(t)),e.destroy(t,n)}function I(e){return function(){e.state!==w&&e.state!==S&&(M(e.connectedProxies,e.disconnectedProxies,this),B(e),e.emit("left","mongos",this),e.emit("serverClosed",{topologyId:e.id,address:this.name}))}}function A(e,t){return function(){if(e.state===w)return B(e),M(e.connectingProxies,e.disconnectedProxies,this),this.destroy();if("connect"===t)if(e.ismaster=this.lastIsMaster(),"isdbgrid"===e.ismaster.msg){for(let t=0;t<e.connectedProxies.length;t++)if(e.connectedProxies[t].name===this.name)return M(e.connectingProxies,e.disconnectedProxies,this),B(e),this.destroy(),e.emit("failed",this);for(let e=0;e<T.length;e++)this.removeAllListeners(T[e]);this.on("error",I(e)),this.on("close",I(e)),this.on("timeout",I(e)),this.on("parseError",I(e)),M(e.connectingProxies,e.connectedProxies,this),e.emit("joined","mongos",this)}else{if(e.s.logger.isWarn()){var n="expected mongos proxy, but found replicaset member mongod for server %s";e.ismaster.hosts||(n="expected mongos proxy, but found standalone mongod for server %s"),e.s.logger.warn(o(n,this.name))}this.destroy(!0),R(e.connectingProxies,this),e.emit("left","server",this),e.emit("failed",this)}else M(e.connectingProxies,e.disconnectedProxies,this),e.emit("left","mongos",this),e.emit("failed",this);if(B(e),0===e.connectingProxies.length){if(e.connectedProxies.length>0&&"connecting"===e.state)_(e,"connected"),e.emit("connect",e),e.emit("fullsetup",e),e.emit("all",e);else if(0===e.disconnectedProxies.length)return e.s.logger.isWarn()&&e.s.logger.warn(o("no mongos proxies found in seed list, did you mean to connect to a replicaset")),e.emit("error",new u("no mongos proxies found in seed list"));!function e(t,n){if(n=n||{},t.state===w||t.state===S||"unreferenced"===t.state)return;t.haTimeoutId=setTimeout((function(){if(t.state!==w&&t.state!==S&&"unreferenced"!==t.state){t.isConnected()&&t.s.disconnectHandler&&t.s.disconnectHandler.execute();var r=t.connectedProxies.slice(0),o=r.length;if(0===r.length)return t.listeners("close").length>0&&"connecting"===t.state?t.emit("error",new u("no mongos proxy available")):t.emit("close",t),j(t,t.disconnectedProxies,(function(){t.state!==w&&t.state!==S&&"unreferenced"!==t.state&&("connecting"===t.state&&n.firstConnect?(t.emit("connect",t),t.emit("fullsetup",t),t.emit("all",t)):t.isConnected()?t.emit("reconnect",t):!t.isConnected()&&t.listeners("close").length>0&&t.emit("close",t),e(t))}));for(var i=0;i<r.length;i++)s(0,r[i],(function(){if(0===(o-=1)){if(t.state===w||t.state===S||"unreferenced"===t.state)return;j(t,t.disconnectedProxies,(function(){t.state!==w&&t.state!==S&&"unreferenced"!==t.state&&e(t)}))}}))}function s(e,n,r){var o=(new Date).getTime();x(t,"serverHeartbeatStarted",{connectionId:n.name}),n.command("admin.$cmd",{ismaster:!0},{monitoring:!0,socketTimeout:t.s.options.connectionTimeout||2e3},(function(e,i){if(t.state===w||t.state===S||"unreferenced"===t.state)return M(t.connectedProxies,t.disconnectedProxies,n),n.destroy(),r(e,i);var s=(new Date).getTime()-o;e?(x(t,"serverHeartbeatFailed",{durationMS:s,failure:e,connectionId:n.name}),M(t.connectedProxies,t.disconnectedProxies,n)):(n.ismaster=i.result,n.lastIsMasterMS=s,x(t,"serverHeartbeatSucceeded",{durationMS:s,reply:i.result,connectionId:n.name})),r(e,i)}))}}),t.s.haInterval)}(e,{firstConnect:!0})}}}function k(e,t){const n=t&&t.transaction;if(n&&n.server){if(n.server.isConnected())return n.server;n.unpinServer()}for(var r=e.connectedProxies.slice(0),o=Number.MAX_VALUE,i=0;i<r.length;i++)r[i].lastIsMasterMS<o&&(o=r[i].lastIsMasterMS);let s;return 0===(r=r.filter((function(t){if(t.lastIsMasterMS<=o+e.s.localThresholdMS&&t.isConnected())return!0}))).length?s=e.connectedProxies[0]:(s=r[e.index%r.length],e.index=(e.index+1)%r.length),n&&n.isActive&&s&&s.isConnected()&&n.pinServer(s),s}function M(e,t,n){for(var r=0;r<e.length;r++)e[r].name===n.name&&e.splice(r,1);for(r=0;r<t.length;r++)t[r].name===n.name&&t.splice(r,1);t.push(n)}function R(e,t){for(var n=0;n<e.length;n++)e[n].name===t.name&&e.splice(n,1)}function j(e,t,n){var r=t.length,o=function(e,t){return function(){if(r-=1,e.state===w||e.state===S||"unreferenced"===e.state)return M(e.connectingProxies,e.disconnectedProxies,this),this.destroy();if("connect"===t){if(e.state===w||e.state===S||"unreferenced"===e.state)return M(e.connectingProxies,e.disconnectedProxies,this),this.destroy();for(var o=0;o<T.length;o++)this.removeAllListeners(T[o]);this.on("error",I(e)),this.on("close",I(e)),this.on("timeout",I(e)),this.on("parseError",I(e)),M(e.connectingProxies,e.connectedProxies,this),B(e),e.emit("joined","mongos",this)}else M(e.connectingProxies,e.disconnectedProxies,this),this.destroy();0===r&&n()}};if(0===r)return n();function i(t,n){setTimeout((function(){if(e.state!==w&&e.state!==S&&"unreferenced"!==e.state){var n=new l(Object.assign({},e.s.options,{host:t.name.split(":")[0],port:parseInt(t.name.split(":")[1],10),reconnect:!1,monitoring:!1,parent:e}));N(t,{force:!0}),R(e.disconnectedProxies,t),m(n,e,["serverDescriptionChanged"]),e.emit("serverOpening",{topologyId:-1!==n.s.topologyId?n.s.topologyId:e.id,address:n.name}),n.once("connect",o(e,"connect")),n.once("close",o(e,"close")),n.once("timeout",o(e,"timeout")),n.once("error",o(e,"error")),n.once("parseError",o(e,"parseError")),m(n,e,["commandStarted","commandSucceeded","commandFailed"]),e.connectingProxies.push(n),n.connect(e.s.connectOptions)}}),n)}for(var s=0;s<t.length;s++)i(t[s],s)}function D(e,t,n){"function"==typeof t&&(n=t,t={}),t=t||{};const r=e.self,o=e.op,i=e.ns,s=e.ops;let a=k(r,t.session);if(!a)return n(new u("no mongos proxy available"));const c=!e.retrying&&!!t.retryWrites&&t.session&&h(r)&&!t.session.inTransaction()&&void 0===t.explain,l=(o,i)=>{if(!o)return n(null,i);if(!v(o,r)||!c)return o=y(o),n(o);if(a=k(r,t.session),!a)return n(o);return D(Object.assign({},e,{retrying:!0}),t,n)};n.operationId&&(l.operationId=n.operationId),c&&(t.session.incrementTransactionNumber(),t.willRetryWrite=c),a[o](i,s,t,l)}C.prototype.connect=function(e){var t=this;this.s.connectOptions=e||{},_(this,"connecting");var n=this.s.seedlist.map((function(n){const r=new l(Object.assign({},t.s.options,n,e,{reconnect:!1,monitoring:!1,parent:t}));return m(r,t,["serverDescriptionChanged"]),r}));x(this,"topologyOpening",{topologyId:this.id}),function(e,t){e.connectingProxies=e.connectingProxies.concat(t);var n=0;t.forEach(t=>function(t,n){setTimeout((function(){e.emit("serverOpening",{topologyId:e.id,address:t.name}),B(e),t.once("close",A(e,"close")),t.once("timeout",A(e,"timeout")),t.once("parseError",A(e,"parseError")),t.once("error",A(e,"error")),t.once("connect",A(e,"connect")),m(t,e,["commandStarted","commandSucceeded","commandFailed"]),t.connect(e.s.connectOptions)}),n)}(t,n++))}(t,n)},C.prototype.auth=function(e,t){"function"==typeof t&&t(null,null)},C.prototype.lastIsMaster=function(){return this.ismaster},C.prototype.unref=function(){_(this,"unreferenced"),this.connectedProxies.concat(this.connectingProxies).forEach((function(e){e.unref()})),clearTimeout(this.haTimeoutId)},C.prototype.destroy=function(e,t){"function"==typeof e&&(t=e,e={}),e=e||{},_(this,S),this.haTimeoutId&&clearTimeout(this.haTimeoutId);const n=this.connectedProxies.concat(this.connectingProxies);let r=n.length;const o=()=>{r--,r>0||(B(this),x(this,"topologyClosed",{topologyId:this.id}),_(this,w),"function"==typeof t&&t(null,null))};0!==r?n.forEach(t=>{this.emit("serverClosed",{topologyId:this.id,address:t.name}),N(t,e,o),M(this.connectedProxies,this.disconnectedProxies,t)}):o()},C.prototype.isConnected=function(){return this.connectedProxies.length>0},C.prototype.isDestroyed=function(){return this.state===w},C.prototype.insert=function(e,t,n,r){return"function"==typeof n&&(r=n,n=(n={})||{}),this.state===w?r(new u(o("topology was destroyed"))):this.isConnected()||null==this.s.disconnectHandler?this.isConnected()?void D({self:this,op:"insert",ns:e,ops:t},n,r):r(new u("no mongos proxy available")):this.s.disconnectHandler.add("insert",e,t,n,r)},C.prototype.update=function(e,t,n,r){return"function"==typeof n&&(r=n,n=(n={})||{}),this.state===w?r(new u(o("topology was destroyed"))):this.isConnected()||null==this.s.disconnectHandler?this.isConnected()?void D({self:this,op:"update",ns:e,ops:t},n,r):r(new u("no mongos proxy available")):this.s.disconnectHandler.add("update",e,t,n,r)},C.prototype.remove=function(e,t,n,r){return"function"==typeof n&&(r=n,n=(n={})||{}),this.state===w?r(new u(o("topology was destroyed"))):this.isConnected()||null==this.s.disconnectHandler?this.isConnected()?void D({self:this,op:"remove",ns:e,ops:t},n,r):r(new u("no mongos proxy available")):this.s.disconnectHandler.add("remove",e,t,n,r)};const P=["findAndModify","insert","update","delete"];function B(e){if(e.listeners("topologyDescriptionChanged").length>0){var t="Unknown";e.connectedProxies.length>0&&(t="Sharded");var n={topologyType:t,servers:[]},r=e.disconnectedProxies.concat(e.connectingProxies);n.servers=n.servers.concat(r.map((function(e){var t=e.getDescription();return t.type="Unknown",t}))),n.servers=n.servers.concat(e.connectedProxies.map((function(e){var t=e.getDescription();return t.type="Mongos",t})));var o=f(e.topologyDescription,n),i={topologyId:e.id,previousDescription:e.topologyDescription,newDescription:n,diff:o};o.servers.length>0&&e.emit("topologyDescriptionChanged",i),e.topologyDescription=n}}C.prototype.command=function(e,t,n,r){if("function"==typeof n&&(r=n,n=(n={})||{}),this.state===w)return r(new u(o("topology was destroyed")));var i=this,s=k(i,n.session);if((null==s||!s.isConnected())&&null!=this.s.disconnectHandler)return this.s.disconnectHandler.add("command",e,t,n,r);if(null==s)return r(new u("no mongos proxy available"));var a=p(n);a.topology=i;const c=!n.retrying&&n.retryWrites&&n.session&&h(i)&&!n.session.inTransaction()&&(l=t,P.some(e=>l[e]));var l;c&&(a.session.incrementTransactionNumber(),a.willRetryWrite=c),s.command(e,t,a,(n,o)=>{if(!n)return r(null,o);if(!v(n,i))return r(n);if(c){const n=Object.assign({},a,{retrying:!0});return this.command(e,t,n,r)}return r(n)})},C.prototype.cursor=function(e,t,n){const r=(n=n||{}).topology||this;return new(n.cursorFactory||this.s.Cursor)(r,e,t,n)},C.prototype.selectServer=function(e,t,n){"function"==typeof e&&void 0===n&&(n=e,e=void 0,t={}),"function"==typeof t&&(n=t,t=e,e=void 0);const r=k(this,(t=t||{}).session);null!=r?(this.s.debug&&this.emit("pickedServer",null,r),n(null,r)):n(new u("server selection failed"))},C.prototype.connections=function(){for(var e=[],t=0;t<this.connectedProxies.length;t++)e=e.concat(this.connectedProxies[t].connections());return e},e.exports=C},function(e,t,n){"use strict";const r=n(138),o=n(8),i=n(44).ServerDescription,s=n(13).ServerType,a=n(189).TopologyDescription,c=n(13).TopologyType,u=n(200),l=n(432).Server,f=n(4).relayEvents,p=n(10),d=n(7).isRetryableWritesSupported,h=n(17).CoreCursor,m=n(5).deprecate,g=n(9).retrieveBSON(),y=n(7).createCompressionInfo,b=n(34).ClientSession,v=n(3).MongoError,S=n(3).MongoServerSelectionError,w=n(7).resolveClusterTime,_=n(444).SrvPoller,O=n(7).getMMAPError,T=n(4).makeStateMachine,C=n(4).eachAsync,x=n(0).emitDeprecationWarning,E=n(34).ServerSessionPool,N=n(4).makeClientMetadata,I=n(94).CMAP_EVENT_NAMES,A=n(44).compareTopologyVersion,k=n(0).emitWarning,M=n(13),R=M.drainTimerQueue,j=M.clearAndRemoveTimerFrom,D=n(445),P=D.readPreferenceServerSelector,B=D.writableServerSelector;let L=0;const q=["serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","commandStarted","commandSucceeded","commandFailed","monitoring"].concat(I),U=["connect","descriptionReceived","close","ended"],z=M.STATE_CLOSING,$=M.STATE_CLOSED,W=M.STATE_CONNECTING,F=M.STATE_CONNECTED,V=T({[$]:[$,W],[W]:[W,z,F,$],[F]:[F,z,$],[z]:[z,$]}),K=new Set(["autoReconnect","reconnectTries","reconnectInterval","bufferMaxEntries"]),H=Symbol("cancelled"),Y=Symbol("waitQueue");class G extends o{constructor(e,t){super(),void 0===t&&"string"!=typeof e&&(t=e,e=[],t.host&&e.push({host:t.host,port:t.port})),"string"==typeof(e=e||[])&&(e=function(e){return e.split(",").map(e=>({host:e.split(":")[0],port:e.split(":")[1]||27017}))}(e)),t=Object.assign({},M.TOPOLOGY_DEFAULTS,t),t=Object.freeze(Object.assign(t,{metadata:N(t),compression:{compressors:y(t)}})),K.forEach(e=>{t[e]&&x(`The option \`${e}\` is incompatible with the unified topology, please read more by visiting http://bit.ly/2D8WfT6`,"DeprecationWarning")});const n=function(e,t){if(t.directConnection)return c.Single;if(null==(t.replicaSet||t.setName||t.rs_name))return c.Unknown;return c.ReplicaSetNoPrimary}(0,t),o=L++,s=e.reduce((e,t)=>{t.domain_socket&&(t.host=t.domain_socket);const n=t.port?`${t.host}:${t.port}`:`${t.host}:27017`;return e.set(n,new i(n)),e},new Map);this[Y]=new r,this.s={id:o,options:t,seedlist:e,state:$,description:new a(n,s,t.replicaSet,null,null,null,t),serverSelectionTimeoutMS:t.serverSelectionTimeoutMS,heartbeatFrequencyMS:t.heartbeatFrequencyMS,minHeartbeatFrequencyMS:t.minHeartbeatFrequencyMS,Cursor:t.cursorFactory||h,bson:t.bson||new g([g.Binary,g.Code,g.DBRef,g.Decimal128,g.Double,g.Int32,g.Long,g.Map,g.MaxKey,g.MinKey,g.ObjectId,g.BSONRegExp,g.Symbol,g.Timestamp]),servers:new Map,sessionPool:new E(this),sessions:new Set,promiseLibrary:t.promiseLibrary||Promise,credentials:t.credentials,clusterTime:null,connectionTimers:new Set},t.srvHost&&(this.s.srvPoller=t.srvPoller||new _({heartbeatFrequencyMS:this.s.heartbeatFrequencyMS,srvHost:t.srvHost,logger:t.logger,loggerLevel:t.loggerLevel}),this.s.detectTopologyDescriptionChange=e=>{const t=e.previousDescription.type,n=e.newDescription.type;var r;t!==c.Sharded&&n===c.Sharded&&(this.s.handleSrvPolling=(r=this,function(e){const t=r.s.description;r.s.description=r.s.description.updateFromSrvPollingEvent(e),r.s.description!==t&&(Q(r),r.emit("topologyDescriptionChanged",new u.TopologyDescriptionChangedEvent(r.s.id,t,r.s.description)))}),this.s.srvPoller.on("srvRecordDiscovery",this.s.handleSrvPolling),this.s.srvPoller.start())},this.on("topologyDescriptionChanged",this.s.detectTopologyDescriptionChange)),this.setMaxListeners(1/0)}get description(){return this.s.description}get parserType(){return g.native?"c++":"js"}connect(e,t){if("function"==typeof e&&(t=e,e={}),e=e||{},this.s.state===F)return void("function"==typeof t&&t());var n,r;V(this,W),this.emit("topologyOpening",new u.TopologyOpeningEvent(this.s.id)),this.emit("topologyDescriptionChanged",new u.TopologyDescriptionChangedEvent(this.s.id,new a(c.Unknown),this.s.description)),n=this,r=Array.from(this.s.description.servers.values()),n.s.servers=r.reduce((e,t)=>{const r=Z(n,t);return e.set(t.address,r),e},new Map),p.translate(e);const o=e.readPreference||p.primary,i=e=>{if(e)return this.close(),void("function"==typeof t?t(e):this.emit("error",e));V(this,F),this.emit("open",e,this),this.emit("connect",this),"function"==typeof t&&t(e,this)};this.s.credentials?this.command("admin.$cmd",{ping:1},{readPreference:o},i):this.selectServer(P(o),e,i)}close(e,t){"function"==typeof e&&(t=e,e={}),"boolean"==typeof e&&(e={force:e}),e=e||{},this.s.state!==$&&this.s.state!==z?(V(this,z),ne(this[Y],new v("Topology closed")),R(this.s.connectionTimers),this.s.srvPoller&&(this.s.srvPoller.stop(),this.s.handleSrvPolling&&(this.s.srvPoller.removeListener("srvRecordDiscovery",this.s.handleSrvPolling),delete this.s.handleSrvPolling)),this.s.detectTopologyDescriptionChange&&(this.removeListener("topologyDescriptionChanged",this.s.detectTopologyDescriptionChange),delete this.s.detectTopologyDescriptionChange),this.s.sessions.forEach(e=>e.endSession()),this.s.sessionPool.endAllPooledSessions(()=>{C(Array.from(this.s.servers.values()),(t,n)=>X(t,this,e,n),e=>{this.s.servers.clear(),this.emit("topologyClosed",new u.TopologyClosedEvent(this.s.id)),V(this,$),this.emit("close"),"function"==typeof t&&t(e)})})):"function"==typeof t&&t()}selectServer(e,t,n){if("function"==typeof t)if(n=t,"function"!=typeof e){let n;t=e,e instanceof p?n=e:"string"==typeof e?n=new p(e):(p.translate(t),n=t.readPreference||p.primary),e=P(n)}else t={};t=Object.assign({},{serverSelectionTimeoutMS:this.s.serverSelectionTimeoutMS},t);const r=this.description.type===c.Sharded,o=t.session,i=o&&o.transaction;if(r&&i&&i.server)return void n(void 0,i.server);let s=e;if("object"==typeof e){const t=e.readPreference?e.readPreference:p.primary;s=P(t)}const a={serverSelector:s,transaction:i,callback:n},u=t.serverSelectionTimeoutMS;u&&(a.timer=setTimeout(()=>{a[H]=!0,a.timer=void 0;const e=new S(`Server selection timed out after ${u} ms`,this.description);a.callback(e)},u)),this[Y].push(a),re(this)}shouldCheckForSessionSupport(){return this.description.type===c.Single?!this.description.hasKnownServers:!this.description.hasDataBearingServers}hasSessionSupport(){return null!=this.description.logicalSessionTimeoutMinutes}startSession(e,t){const n=new b(this,this.s.sessionPool,e,t);return n.once("ended",()=>{this.s.sessions.delete(n)}),this.s.sessions.add(n),n}endSessions(e,t){Array.isArray(e)||(e=[e]),this.command("admin.$cmd",{endSessions:e},{readPreference:p.primaryPreferred,noResponse:!0},()=>{"function"==typeof t&&t()})}serverUpdateHandler(e){if(!this.s.description.hasServer(e.address))return;if(function(e,t){const n=e.servers.get(t.address).topologyVersion;return A(n,t.topologyVersion)>0}(this.s.description,e))return;const t=this.s.description,n=this.s.description.servers.get(e.address),r=e.$clusterTime;r&&w(this,r);const o=n&&n.equals(e);this.s.description=this.s.description.update(e),this.s.description.compatibilityError?this.emit("error",new v(this.s.description.compatibilityError)):(o||this.emit("serverDescriptionChanged",new u.ServerDescriptionChangedEvent(this.s.id,e.address,n,this.s.description.servers.get(e.address))),Q(this,e),this[Y].length>0&&re(this),o||this.emit("topologyDescriptionChanged",new u.TopologyDescriptionChangedEvent(this.s.id,t,this.s.description)))}auth(e,t){"function"==typeof e&&(t=e,e=null),"function"==typeof t&&t(null,!0)}logout(e){"function"==typeof e&&e(null,!0)}insert(e,t,n,r){ee({topology:this,op:"insert",ns:e,ops:t},n,r)}update(e,t,n,r){ee({topology:this,op:"update",ns:e,ops:t},n,r)}remove(e,t,n,r){ee({topology:this,op:"remove",ns:e,ops:t},n,r)}command(e,t,n,r){"function"==typeof n&&(r=n,n=(n={})||{}),p.translate(n);const o=n.readPreference||p.primary;this.selectServer(P(o),n,(o,i)=>{if(o)return void r(o);const s=!n.retrying&&!!n.retryWrites&&n.session&&d(this)&&!n.session.inTransaction()&&(a=t,J.some(e=>a[e]));var a;s&&(n.session.incrementTransactionNumber(),n.willRetryWrite=s),i.command(e,t,n,(o,i)=>{if(!o)return r(null,i);if(!te(o))return r(o);if(s){const o=Object.assign({},n,{retrying:!0});return this.command(e,t,o,r)}return r(o)})})}cursor(e,t,n){const r=(n=n||{}).topology||this,o=n.cursorFactory||this.s.Cursor;return p.translate(n),new o(r,e,t,n)}get clientMetadata(){return this.s.options.metadata}isConnected(){return this.s.state===F}isDestroyed(){return this.s.state===$}unref(){k("not implemented: `unref`")}lastIsMaster(){const e=Array.from(this.description.servers.values());return 0===e.length?{}:e.filter(e=>e.type!==s.Unknown)[0]||{maxWireVersion:this.description.commonWireVersion}}get logicalSessionTimeoutMinutes(){return this.description.logicalSessionTimeoutMinutes}get bson(){return this.s.bson}}Object.defineProperty(G.prototype,"clusterTime",{enumerable:!0,get:function(){return this.s.clusterTime},set:function(e){this.s.clusterTime=e}}),G.prototype.destroy=m(G.prototype.close,"destroy() is deprecated, please use close() instead");const J=["findAndModify","insert","update","delete"];function X(e,t,n,r){n=n||{},U.forEach(t=>e.removeAllListeners(t)),e.destroy(n,()=>{t.emit("serverClosed",new u.ServerClosedEvent(t.s.id,e.description.address)),q.forEach(t=>e.removeAllListeners(t)),"function"==typeof r&&r()})}function Z(e,t,n){e.emit("serverOpening",new u.ServerOpeningEvent(e.s.id,t.address));const r=new l(t,e.s.options,e);if(f(r,e,q),r.on("descriptionReceived",e.serverUpdateHandler.bind(e)),n){const t=setTimeout(()=>{j(t,e.s.connectionTimers),r.connect()},n);return e.s.connectionTimers.add(t),r}return r.connect(),r}function Q(e,t){if(t&&e.s.servers.has(t.address)){e.s.servers.get(t.address).s.description=t}for(const t of e.description.servers.values())if(!e.s.servers.has(t.address)){const n=Z(e,t);e.s.servers.set(t.address,n)}for(const t of e.s.servers){const n=t[0];if(e.description.hasServer(n))continue;const r=e.s.servers.get(n);e.s.servers.delete(n),X(r,e)}}function ee(e,t,n){"function"==typeof t&&(n=t,t={}),t=t||{};const r=e.topology,o=e.op,i=e.ns,s=e.ops,a=!e.retrying&&!!t.retryWrites&&t.session&&d(r)&&!t.session.inTransaction()&&void 0===t.explain;r.selectServer(B(),t,(r,c)=>{if(r)return void n(r,null);const u=(r,o)=>{if(!r)return n(null,o);if(!te(r))return r=O(r),n(r);if(a){return ee(Object.assign({},e,{retrying:!0}),t,n)}return n(r)};n.operationId&&(u.operationId=n.operationId),a&&(t.session.incrementTransactionNumber(),t.willRetryWrite=a),c[o](i,s,t,u)})}function te(e){return e instanceof v&&e.hasErrorLabel("RetryableWriteError")}function ne(e,t){for(;e.length;){const n=e.shift();clearTimeout(n.timer),n[H]||n.callback(t)}}function re(e){if(e.s.state===$)return void ne(e[Y],new v("Topology is closed, please connect"));const t=Array.from(e.description.servers.values()),n=e[Y].length;for(let o=0;o<n&&e[Y].length;++o){const n=e[Y].shift();if(n[H])continue;let o;try{const r=n.serverSelector;o=r?r(e.description,t):t}catch(e){clearTimeout(n.timer),n.callback(e);continue}if(0===o.length){e[Y].push(n);continue}const i=(r=o)[Math.floor(Math.random()*r.length)],s=e.s.servers.get(i.address),a=n.transaction;e.description.type===c.Sharded&&a&&a.isActive&&a.pinServer(s),clearTimeout(n.timer),n.callback(void 0,s)}var r;e[Y].length>0&&e.s.servers.forEach(e=>process.nextTick(()=>e.requestCheck()))}e.exports={Topology:G}},function(e,t,n){"use strict";const r=n(8),o=n(433).ConnectionPool,i=n(94).CMAP_EVENT_NAMES,s=n(3).MongoError,a=n(4).relayEvents,c=n(9).retrieveBSON(),u=n(16),l=n(44).ServerDescription,f=n(44).compareTopologyVersion,p=n(10),d=n(443).Monitor,h=n(3).MongoNetworkError,m=n(3).MongoNetworkTimeoutError,g=n(4).collationNotSupported,y=n(9).debugOptions,b=n(3).isSDAMUnrecoverableError,v=n(3).isRetryableWriteError,S=n(3).isNodeShuttingDownError,w=n(3).isNetworkErrorBeforeHandshake,_=n(4).maxWireVersion,O=n(4).makeStateMachine,T=n(13),C=T.ServerType,x=n(54).isTransactionCommand,E=["reconnect","reconnectTries","reconnectInterval","emitError","cursorFactory","host","port","size","keepAlive","keepAliveInitialDelay","noDelay","connectionTimeout","checkServerIdentity","socketTimeout","ssl","ca","crl","cert","key","rejectUnauthorized","promoteLongs","promoteValues","promoteBuffers","servername"],N=T.STATE_CLOSING,I=T.STATE_CLOSED,A=T.STATE_CONNECTING,k=T.STATE_CONNECTED,M=O({[I]:[I,A],[A]:[A,N,k,I],[k]:[k,N,I],[N]:[N,I]}),R=Symbol("monitor");class j extends r{constructor(e,t,n){super(),this.s={description:e,options:t,logger:u("Server",t),bson:t.bson||new c([c.Binary,c.Code,c.DBRef,c.Decimal128,c.Double,c.Int32,c.Long,c.Map,c.MaxKey,c.MinKey,c.ObjectId,c.BSONRegExp,c.Symbol,c.Timestamp]),state:I,credentials:t.credentials,topology:n};const r=Object.assign({host:this.description.host,port:this.description.port,bson:this.s.bson},t);this.s.pool=new o(r),a(this.s.pool,this,["commandStarted","commandSucceeded","commandFailed"].concat(i)),this.s.pool.on("clusterTimeReceived",e=>{this.clusterTime=e}),this[R]=new d(this,this.s.options),a(this[R],this,["serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","monitoring"]),this[R].on("resetConnectionPool",()=>{this.s.pool.clear()}),this[R].on("resetServer",e=>B(this,e)),this[R].on("serverHeartbeatSucceeded",e=>{this.emit("descriptionReceived",new l(this.description.address,e.reply,{roundTripTime:D(this.description.roundTripTime,e.duration)})),this.s.state===A&&(M(this,k),this.emit("connect",this))})}get description(){return this.s.description}get name(){return this.s.description.address}get autoEncrypter(){return this.s.options&&this.s.options.autoEncrypter?this.s.options.autoEncrypter:null}connect(){this.s.state===I&&(M(this,A),this[R].connect())}destroy(e,t){"function"==typeof e&&(t=e,e={}),e=Object.assign({},{force:!1},e),this.s.state!==I?(M(this,N),this[R].close(),this.s.pool.close(e,e=>{M(this,I),this.emit("closed"),"function"==typeof t&&t(e)})):"function"==typeof t&&t()}requestCheck(){this[R].requestCheck()}command(e,t,n,r){if("function"==typeof n&&(r=n,n=(n={})||{}),this.s.state===N||this.s.state===I)return void r(new s("server is closed"));const o=function(e,t){if(t.readPreference&&!(t.readPreference instanceof p))return new s("readPreference must be an instance of ReadPreference")}(0,n);if(o)return r(o);n=Object.assign({},n,{wireProtocolCommand:!1}),this.s.logger.isDebug()&&this.s.logger.debug(`executing command [${JSON.stringify({ns:e,cmd:t,options:y(E,n)})}] against ${this.name}`),g(this,t)?r(new s(`server ${this.name} does not support collation`)):this.s.pool.withConnection((r,o,i)=>{if(r)return B(this,r),i(r);o.command(e,t,n,q(this,o,t,n,i))},r)}query(e,t,n,r,o){this.s.state!==N&&this.s.state!==I?this.s.pool.withConnection((o,i,s)=>{if(o)return B(this,o),s(o);i.query(e,t,n,r,q(this,i,t,r,s))},o):o(new s("server is closed"))}getMore(e,t,n,r,o){this.s.state!==N&&this.s.state!==I?this.s.pool.withConnection((o,i,s)=>{if(o)return B(this,o),s(o);i.getMore(e,t,n,r,q(this,i,null,r,s))},o):o(new s("server is closed"))}killCursors(e,t,n){this.s.state!==N&&this.s.state!==I?this.s.pool.withConnection((n,r,o)=>{if(n)return B(this,n),o(n);r.killCursors(e,t,q(this,r,null,void 0,o))},n):"function"==typeof n&&n(new s("server is closed"))}insert(e,t,n,r){P({server:this,op:"insert",ns:e,ops:t},n,r)}update(e,t,n,r){P({server:this,op:"update",ns:e,ops:t},n,r)}remove(e,t,n,r){P({server:this,op:"remove",ns:e,ops:t},n,r)}}function D(e,t){if(-1===e)return t;return.2*t+.8*e}function P(e,t,n){"function"==typeof t&&(n=t,t={}),t=t||{};const r=e.server,o=e.op,i=e.ns,a=Array.isArray(e.ops)?e.ops:[e.ops];r.s.state!==N&&r.s.state!==I?g(r,t)?n(new s(`server ${r.name} does not support collation`)):!(t.writeConcern&&0===t.writeConcern.w||_(r)<5)||"update"!==o&&"remove"!==o||!a.find(e=>e.hint)?r.s.pool.withConnection((e,n,s)=>{if(e)return B(r,e),s(e);n[o](i,a,t,q(r,n,a,t,s))},n):n(new s(`servers < 3.4 do not support hint on ${o}`)):n(new s("server is closed"))}function B(e,t){t instanceof h&&!(t instanceof m)&&e[R].reset(),e.emit("descriptionReceived",new l(e.description.address,null,{error:t,topologyVersion:t&&t.topologyVersion?t.topologyVersion:e.description.topologyVersion}))}function L(e,t){return e&&e.inTransaction()&&!x(t)}function q(e,t,n,r,o){const i=r&&r.session;return function(r,s){r&&!function(e,t){return t.generation!==e.generation}(e.s.pool,t)&&(r instanceof h?(i&&!i.hasEnded&&(i.serverSession.isDirty=!0),function(e){return e.description.maxWireVersion>=6&&e.description.logicalSessionTimeoutMinutes&&e.description.type!==C.Standalone}(e)&&!L(i,n)&&r.addErrorLabel("RetryableWriteError"),r instanceof m&&!w(r)||(B(e,r),e.s.pool.clear())):(_(e)<9&&v(r)&&!L(i,n)&&r.addErrorLabel("RetryableWriteError"),b(r)&&function(e,t){const n=t.topologyVersion,r=e.description.topologyVersion;return f(r,n)<0}(e,r)&&((_(e)<=7||S(r))&&e.s.pool.clear(),B(e,r),process.nextTick(()=>e.requestCheck())))),o(r,s)}}Object.defineProperty(j.prototype,"clusterTime",{get:function(){return this.s.topology.clusterTime},set:function(e){this.s.topology.clusterTime=e}}),e.exports={Server:j}},function(e,t,n){"use strict";const r=n(138),o=n(8).EventEmitter,i=n(16),s=n(0).makeCounter,a=n(3).MongoError,c=n(201).Connection,u=n(4).eachAsync,l=n(135),f=n(4).relayEvents,p=n(442),d=p.PoolClosedError,h=p.WaitQueueTimeoutError,m=n(94),g=m.ConnectionPoolCreatedEvent,y=m.ConnectionPoolClosedEvent,b=m.ConnectionCreatedEvent,v=m.ConnectionReadyEvent,S=m.ConnectionClosedEvent,w=m.ConnectionCheckOutStartedEvent,_=m.ConnectionCheckOutFailedEvent,O=m.ConnectionCheckedOutEvent,T=m.ConnectionCheckedInEvent,C=m.ConnectionPoolClearedEvent,x=Symbol("logger"),E=Symbol("connections"),N=Symbol("permits"),I=Symbol("minPoolSizeTimer"),A=Symbol("generation"),k=Symbol("connectionCounter"),M=Symbol("cancellationToken"),R=Symbol("waitQueue"),j=Symbol("cancelled"),D=new Set(["ssl","bson","connectionType","monitorCommands","socketTimeout","credentials","compression","host","port","localAddress","localPort","family","hints","lookup","path","ca","cert","sigalgs","ciphers","clientCertEngine","crl","dhparam","ecdhCurve","honorCipherOrder","key","privateKeyEngine","privateKeyIdentifier","maxVersion","minVersion","passphrase","pfx","secureOptions","secureProtocol","sessionIdContext","allowHalfOpen","rejectUnauthorized","pskCallback","ALPNProtocols","servername","checkServerIdentity","session","minDHSize","secureContext","maxPoolSize","minPoolSize","maxIdleTimeMS","waitQueueTimeoutMS"]);function P(e,t){return t.generation!==e[A]}function B(e,t){return!!(e.options.maxIdleTimeMS&&t.idleTime>e.options.maxIdleTimeMS)}function L(e,t){const n=Object.assign({id:e[k].next().value,generation:e[A]},e.options);e[N]--,l(n,e[M],(n,r)=>{if(n)return e[N]++,e[x].debug(`connection attempt failed with error [${JSON.stringify(n)}]`),void("function"==typeof t&&t(n));e.closed?r.destroy({force:!0}):(f(r,e,["commandStarted","commandFailed","commandSucceeded","clusterTimeReceived"]),e.emit("connectionCreated",new b(e,r)),r.markAvailable(),e.emit("connectionReady",new v(e,r)),"function"!=typeof t?(e[E].push(r),process.nextTick(()=>U(e))):t(void 0,r))})}function q(e,t,n){e.emit("connectionClosed",new S(e,t,n)),e[N]++,process.nextTick(()=>t.destroy())}function U(e){if(e.closed)return;for(;e.waitQueueSize;){const t=e[R].peekFront();if(t[j]){e[R].shift();continue}if(!e.availableConnectionCount)break;const n=e[E].shift(),r=P(e,n),o=B(e,n);if(!r&&!o&&!n.closed)return e.emit("connectionCheckedOut",new O(e,n)),clearTimeout(t.timer),e[R].shift(),void t.callback(void 0,n);const i=n.closed?"error":r?"stale":"idle";q(e,n,i)}const t=e.options.maxPoolSize;e.waitQueueSize&&(t<=0||e.totalConnectionCount<t)&&L(e,(t,n)=>{const r=e[R].shift();null==r||r[j]?null==t&&e[E].push(n):(t?e.emit("connectionCheckOutFailed",new _(e,t)):e.emit("connectionCheckedOut",new O(e,n)),clearTimeout(r.timer),r.callback(t,n))})}e.exports={ConnectionPool:class extends o{constructor(e){if(super(),e=e||{},this.closed=!1,this.options=function(e,t){const n=Array.from(D).reduce((t,n)=>(Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]),t),{});return Object.freeze(Object.assign({},t,n))}(e,{connectionType:c,maxPoolSize:"number"==typeof e.maxPoolSize?e.maxPoolSize:100,minPoolSize:"number"==typeof e.minPoolSize?e.minPoolSize:0,maxIdleTimeMS:"number"==typeof e.maxIdleTimeMS?e.maxIdleTimeMS:0,waitQueueTimeoutMS:"number"==typeof e.waitQueueTimeoutMS?e.waitQueueTimeoutMS:0,autoEncrypter:e.autoEncrypter,metadata:e.metadata}),e.minSize>e.maxSize)throw new TypeError("Connection pool minimum size must not be greater than maxiumum pool size");this[x]=i("ConnectionPool",e),this[E]=new r,this[N]=this.options.maxPoolSize,this[I]=void 0,this[A]=0,this[k]=s(1),this[M]=new o,this[M].setMaxListeners(1/0),this[R]=new r,process.nextTick(()=>{this.emit("connectionPoolCreated",new g(this)),function e(t){if(t.closed||0===t.options.minPoolSize)return;const n=t.options.minPoolSize;for(let e=t.totalConnectionCount;e<n;++e)L(t);t[I]=setTimeout(()=>e(t),10)}(this)})}get address(){return`${this.options.host}:${this.options.port}`}get generation(){return this[A]}get totalConnectionCount(){return this[E].length+(this.options.maxPoolSize-this[N])}get availableConnectionCount(){return this[E].length}get waitQueueSize(){return this[R].length}checkOut(e){if(this.emit("connectionCheckOutStarted",new w(this)),this.closed)return this.emit("connectionCheckOutFailed",new _(this,"poolClosed")),void e(new d(this));const t={callback:e},n=this,r=this.options.waitQueueTimeoutMS;r&&(t.timer=setTimeout(()=>{t[j]=!0,t.timer=void 0,n.emit("connectionCheckOutFailed",new _(n,"timeout")),t.callback(new h(n))},r)),this[R].push(t),process.nextTick(()=>U(this))}checkIn(e){const t=this.closed,n=P(this,e),r=!!(t||n||e.closed);if(r||(e.markAvailable(),this[E].push(e)),this.emit("connectionCheckedIn",new T(this,e)),r){q(this,e,e.closed?"error":t?"poolClosed":"stale")}process.nextTick(()=>U(this))}clear(){this[A]+=1,this.emit("connectionPoolCleared",new C(this))}close(e,t){if("function"==typeof e&&(t=e),e=Object.assign({force:!1},e),this.closed)return t();for(this[M].emit("cancel");this.waitQueueSize;){const e=this[R].pop();clearTimeout(e.timer),e[j]||e.callback(new a("connection pool closed"))}this[I]&&clearTimeout(this[I]),"function"==typeof this[k].return&&this[k].return(),this.closed=!0,u(this[E].toArray(),(t,n)=>{this.emit("connectionClosed",new S(this,t,"poolClosed")),t.destroy(e,n)},e=>{this[E].clear(),this.emit("connectionPoolClosed",new y(this)),t(e)})}withConnection(e,t){this.checkOut((n,r)=>{e(n,r,(e,n)=>{"function"==typeof t&&(e?t(e):t(void 0,n)),r&&this.checkIn(r)})})}}}},function(e,t,n){"use strict";const r=n(18).Duplex,o=n(202),i=n(3).MongoParseError,s=n(30).decompress,a=n(21).Response,c=n(45).BinMsg,u=n(3).MongoError,l=n(6).opcodes.OP_COMPRESSED,f=n(6).opcodes.OP_MSG,p=n(6).MESSAGE_HEADER_SIZE,d=n(6).COMPRESSION_DETAILS_SIZE,h=n(6).opcodes,m=n(30).compress,g=n(30).compressorIDs,y=n(30).uncompressibleCommands,b=n(45).Msg,v=Symbol("buffer");e.exports=class extends r{constructor(e){super(e=e||{}),this.bson=e.bson,this.maxBsonMessageSize=e.maxBsonMessageSize||67108864,this[v]=new o}_write(e,t,n){this[v].append(e),function e(t,n){const r=t[v];if(r.length<4)return void n();const o=r.readInt32LE(0);if(o<0)return void n(new i(`Invalid message size: ${o}`));if(o>t.maxBsonMessageSize)return void n(new i(`Invalid message size: ${o}, max allowed: ${t.maxBsonMessageSize}`));if(o>r.length)return void n();const d=r.slice(0,o);r.consume(o);const h={length:d.readInt32LE(0),requestId:d.readInt32LE(4),responseTo:d.readInt32LE(8),opCode:d.readInt32LE(12)};let m=h.opCode===f?c:a;const g=t.responseOptions;if(h.opCode!==l){const o=d.slice(p);return t.emit("message",new m(t.bson,d,h,o,g)),void(r.length>=4?e(t,n):n())}h.fromCompressed=!0,h.opCode=d.readInt32LE(p),h.length=d.readInt32LE(p+4);const y=d[p+8],b=d.slice(p+9);m=h.opCode===f?c:a,s(y,b,(o,i)=>{o?n(o):i.length===h.length?(t.emit("message",new m(t.bson,d,h,i,g)),r.length>=4?e(t,n):n()):n(new u("Decompressing a compressed message from the server failed. The message is corrupt."))})}(this,n)}_read(){}writeCommand(e,t){if(!(t&&!!t.agreedCompressor)||!function(e){const t=e instanceof b?e.command:e.query,n=Object.keys(t)[0];return!y.has(n)}(e)){const t=e.toBin();return void this.push(Array.isArray(t)?Buffer.concat(t):t)}const n=Buffer.concat(e.toBin()),r=n.slice(p),o=n.readInt32LE(12);m({options:t},r,(n,i)=>{if(n)return void t.cb(n,null);const s=Buffer.alloc(p);s.writeInt32LE(p+d+i.length,0),s.writeInt32LE(e.requestId,4),s.writeInt32LE(0,8),s.writeInt32LE(h.OP_COMPRESSED,12);const a=Buffer.alloc(d);a.writeInt32LE(o,0),a.writeInt32LE(r.length,4),a.writeUInt8(g[t.agreedCompressor],8),this.push(Buffer.concat([s,a,i]))})}}},function(e,t,n){var r=n(18);"disable"===process.env.READABLE_STREAM&&r?(e.exports=r,(t=e.exports=r.Readable).Readable=r.Readable,t.Writable=r.Writable,t.Duplex=r.Duplex,t.Transform=r.Transform,t.PassThrough=r.PassThrough,t.Stream=r):((t=e.exports=n(203)).Stream=r||t,t.Readable=t,t.Writable=n(206),t.Duplex=n(47),t.Transform=n(208),t.PassThrough=n(440))},function(e,t){var n={}.toString;e.exports=Array.isArray||function(e){return"[object Array]"==n.call(e)}},function(e,t){"function"==typeof Object.create?e.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:e.exports=function(e,t){if(t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}}},function(e,t,n){"use strict";var r=n(93).Buffer,o=n(5);e.exports=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.head=null,this.tail=null,this.length=0}return e.prototype.push=function(e){var t={data:e,next:null};this.length>0?this.tail.next=t:this.head=t,this.tail=t,++this.length},e.prototype.unshift=function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length},e.prototype.shift=function(){if(0!==this.length){var e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}},e.prototype.clear=function(){this.head=this.tail=null,this.length=0},e.prototype.join=function(e){if(0===this.length)return"";for(var t=this.head,n=""+t.data;t=t.next;)n+=e+t.data;return n},e.prototype.concat=function(e){if(0===this.length)return r.alloc(0);if(1===this.length)return this.head.data;for(var t,n,o,i=r.allocUnsafe(e>>>0),s=this.head,a=0;s;)t=s.data,n=i,o=a,t.copy(n,o),a+=s.data.length,s=s.next;return i},e}(),o&&o.inspect&&o.inspect.custom&&(e.exports.prototype[o.inspect.custom]=function(){var e=o.inspect({length:this.length});return this.constructor.name+" "+e})},function(e,t,n){e.exports=n(5).deprecate},function(e,t,n){"use strict";e.exports=i;var r=n(208),o=Object.create(n(57));function i(e){if(!(this instanceof i))return new i(e);r.call(this,e)}o.inherits=n(58),o.inherits(i,r),i.prototype._transform=function(e,t,n){n(null,e)}},function(e,t,n){"use strict";const r=n(44).parseServerType,o=["minWireVersion","maxWireVersion","maxBsonObjectSize","maxMessageSizeBytes","maxWriteBatchSize","__nodejs_mock_server__"];e.exports={StreamDescription:class{constructor(e,t){this.address=e,this.type=r(null),this.minWireVersion=void 0,this.maxWireVersion=void 0,this.maxBsonObjectSize=16777216,this.maxMessageSizeBytes=48e6,this.maxWriteBatchSize=1e5,this.compressors=t&&t.compression&&Array.isArray(t.compression.compressors)?t.compression.compressors:[]}receiveResponse(e){this.type=r(e),o.forEach(t=>{void 0!==e[t]&&(this[t]=e[t])}),e.compression&&(this.compressor=this.compressors.filter(t=>-1!==e.compression.indexOf(t))[0])}}}},function(e,t,n){"use strict";const r=n(3).MongoError;e.exports={PoolClosedError:class extends r{constructor(e){super("Attempted to check out a connection from closed connection pool"),this.name="MongoPoolClosedError",this.address=e.address}},WaitQueueTimeoutError:class extends r{constructor(e){super("Timed out while checking out a connection from connection pool"),this.name="MongoWaitQueueTimeoutError",this.address=e.address}}}},function(e,t,n){"use strict";const r=n(13).ServerType,o=n(8),i=n(135),s=n(201).Connection,a=n(13),c=n(4).makeStateMachine,u=n(3).MongoNetworkError,l=n(9).retrieveBSON(),f=n(0).makeInterruptableAsyncInterval,p=n(0).calculateDurationInMs,d=n(0).now,h=n(200),m=h.ServerHeartbeatStartedEvent,g=h.ServerHeartbeatSucceededEvent,y=h.ServerHeartbeatFailedEvent,b=Symbol("server"),v=Symbol("monitorId"),S=Symbol("connection"),w=Symbol("cancellationToken"),_=Symbol("rttPinger"),O=Symbol("roundTripTime"),T=a.STATE_CLOSED,C=a.STATE_CLOSING,x=c({[C]:[C,"idle",T],[T]:[T,"monitoring"],idle:["idle","monitoring",C],monitoring:["monitoring","idle",C]}),E=new Set([C,T,"monitoring"]);function N(e){return e.s.state===T||e.s.state===C}function I(e){e[v]&&(e[v].stop(),e[v]=null),e[_]&&(e[_].close(),e[_]=void 0),e[w].emit("cancel"),e[v]&&(clearTimeout(e[v]),e[v]=void 0),e[S]&&e[S].destroy({force:!0})}function A(e,t){let n=d();function r(r){e[S]&&(e[S].destroy({force:!0}),e[S]=void 0),e.emit("serverHeartbeatFailed",new y(p(n),r,e.address)),e.emit("resetServer",r),e.emit("resetConnectionPool"),t(r)}if(e.emit("serverHeartbeatStarted",new m(e.address)),null!=e[S]&&!e[S].closed){const i=e.options.connectTimeoutMS,s=e.options.heartbeatFrequencyMS,a=e[b].description.topologyVersion,c=null!=a,u={ismaster:!0},f={socketTimeout:i};return c&&(u.maxAwaitTimeMS=s,u.topologyVersion={processId:(o=a).processId,counter:l.Long.fromNumber(o.counter)},i&&(f.socketTimeout=i+s),f.exhaustAllowed=!0,null==e[_]&&(e[_]=new M(e[w],e.connectOptions))),void e[S].command("admin.$cmd",u,f,(o,i)=>{if(o)return void r(o);const s=i.result,a=e[_],u=c&&a?a.roundTripTime:p(n);e.emit("serverHeartbeatSucceeded",new g(u,s,e.address)),c&&s.topologyVersion?(e.emit("serverHeartbeatStarted",new m(e.address)),n=d()):(e[_]&&(e[_].close(),e[_]=void 0),t(void 0,s))})}var o;i(e.connectOptions,e[w],(o,i)=>{if(i&&N(e))i.destroy({force:!0});else{if(o)return e[S]=void 0,o instanceof u||e.emit("resetConnectionPool"),void r(o);e[S]=i,e.emit("serverHeartbeatSucceeded",new g(p(n),i.ismaster,e.address)),t(void 0,i.ismaster)}})}function k(e){return t=>{function n(){N(e)||x(e,"idle"),t()}x(e,"monitoring"),process.nextTick(()=>e.emit("monitoring",e[b])),A(e,(t,o)=>{if(t&&e[b].description.type===r.Unknown)return e.emit("resetServer",t),n();o&&o.topologyVersion&&setTimeout(()=>{N(e)||e[v].wake()}),n()})}}class M{constructor(e,t){this[S]=null,this[w]=e,this[O]=0,this.closed=!1;const n=t.heartbeatFrequencyMS;this[v]=setTimeout(()=>function e(t,n){const r=d(),o=t[w],s=n.heartbeatFrequencyMS;if(t.closed)return;function a(o){t.closed?o.destroy({force:!0}):(null==t[S]&&(t[S]=o),t[O]=p(r),t[v]=setTimeout(()=>e(t,n),s))}if(null==t[S])return void i(n,o,(e,n)=>{if(e)return t[S]=void 0,void(t[O]=0);a(n)});t[S].command("admin.$cmd",{ismaster:1},e=>{if(e)return t[S]=void 0,void(t[O]=0);a()})}(this,t),n)}get roundTripTime(){return this[O]}close(){this.closed=!0,clearTimeout(this[v]),this[v]=void 0,this[S]&&this[S].destroy({force:!0})}}e.exports={Monitor:class extends o{constructor(e,t){super(t),this[b]=e,this[S]=void 0,this[w]=new o,this[w].setMaxListeners(1/0),this[v]=null,this.s={state:T},this.address=e.description.address,this.options=Object.freeze({connectTimeoutMS:"number"==typeof t.connectionTimeout?t.connectionTimeout:"number"==typeof t.connectTimeoutMS?t.connectTimeoutMS:1e4,heartbeatFrequencyMS:"number"==typeof t.heartbeatFrequencyMS?t.heartbeatFrequencyMS:1e4,minHeartbeatFrequencyMS:"number"==typeof t.minHeartbeatFrequencyMS?t.minHeartbeatFrequencyMS:500});const n=Object.assign({id:"<monitor>",host:e.description.host,port:e.description.port,bson:e.s.bson,connectionType:s},e.s.options,this.options,{raw:!1,promoteLongs:!0,promoteValues:!0,promoteBuffers:!0});delete n.credentials,delete n.autoEncrypter,this.connectOptions=Object.freeze(n)}connect(){if(this.s.state!==T)return;const e=this.options.heartbeatFrequencyMS,t=this.options.minHeartbeatFrequencyMS;this[v]=f(k(this),{interval:e,minInterval:t,immediate:!0})}requestCheck(){E.has(this.s.state)||this[v].wake()}reset(){const e=this[b].description.topologyVersion;if(N(this)||null==e)return;x(this,C),I(this),x(this,"idle");const t=this.options.heartbeatFrequencyMS,n=this.options.minHeartbeatFrequencyMS;this[v]=f(k(this),{interval:t,minInterval:n})}close(){N(this)||(x(this,C),I(this),this.emit("close"),x(this,T))}}}},function(e,t,n){"use strict";const r=n(16),o=n(8).EventEmitter,i=n(87);class s{constructor(e){this.srvRecords=e}addresses(){return new Set(this.srvRecords.map(e=>`${e.name}:${e.port}`))}}e.exports.SrvPollingEvent=s,e.exports.SrvPoller=class extends o{constructor(e){if(super(),!e||!e.srvHost)throw new TypeError("options for SrvPoller must exist and include srvHost");this.srvHost=e.srvHost,this.rescanSrvIntervalMS=6e4,this.heartbeatFrequencyMS=e.heartbeatFrequencyMS||1e4,this.logger=r("srvPoller",e),this.haMode=!1,this.generation=0,this._timeout=null}get srvAddress(){return`_mongodb._tcp.${this.srvHost}`}get intervalMS(){return this.haMode?this.heartbeatFrequencyMS:this.rescanSrvIntervalMS}start(){this._timeout||this.schedule()}stop(){this._timeout&&(clearTimeout(this._timeout),this.generation+=1,this._timeout=null)}schedule(){clearTimeout(this._timeout),this._timeout=setTimeout(()=>this._poll(),this.intervalMS)}success(e){this.haMode=!1,this.schedule(),this.emit("srvRecordDiscovery",new s(e))}failure(e,t){this.logger.warn(e,t),this.haMode=!0,this.schedule()}parentDomainMismatch(e){this.logger.warn(`parent domain mismatch on SRV record (${e.name}:${e.port})`,e)}_poll(){const e=this.generation;i.resolveSrv(this.srvAddress,(t,n)=>{if(e!==this.generation)return;if(t)return void this.failure("DNS error",t);const r=[];n.forEach(e=>{!function(e,t){const n=/^.*?\./,r=`.${e.replace(n,"")}`,o=`.${t.replace(n,"")}`;return r.endsWith(o)}(e.name,this.srvHost)?this.parentDomainMismatch(e):r.push(e)}),r.length?this.success(r):this.failure("No valid addresses found at host")})}}},function(e,t,n){"use strict";const r=n(13).ServerType,o=n(13).TopologyType,i=n(10),s=n(3).MongoError;function a(e,t){const n=Object.keys(e),r=Object.keys(t);for(let o=0;o<n.length;++o){const i=n[o];if(-1===r.indexOf(i)||t[i]!==e[i])return!1}return!0}function c(e,t){const n=t.reduce((e,t)=>-1===e?t.roundTripTime:Math.min(t.roundTripTime,e),-1),r=n+e.localThresholdMS;return t.reduce((e,t)=>(t.roundTripTime<=r&&t.roundTripTime>=n&&e.push(t),e),[])}function u(e){return e.type===r.RSPrimary}function l(e){return e.type===r.RSSecondary}function f(e){return e.type===r.RSSecondary||e.type===r.RSPrimary}function p(e){return e.type!==r.Unknown}e.exports={writableServerSelector:function(){return function(e,t){return c(e,t.filter(e=>e.isWritable))}},readPreferenceServerSelector:function(e){if(!e.isValid())throw new TypeError("Invalid read preference specified");return function(t,n){const r=t.commonWireVersion;if(r&&e.minWireVersion&&e.minWireVersion>r)throw new s(`Minimum wire version '${e.minWireVersion}' required, but found '${r}'`);if(t.type===o.Unknown)return[];if(t.type===o.Single||t.type===o.Sharded)return c(t,n.filter(p));const d=e.mode;if(d===i.PRIMARY)return n.filter(u);if(d===i.PRIMARY_PREFERRED){const e=n.filter(u);if(e.length)return e}const h=d===i.NEAREST?f:l,m=c(t,function(e,t){if(null==e.tags||Array.isArray(e.tags)&&0===e.tags.length)return t;for(let n=0;n<e.tags.length;++n){const r=e.tags[n],o=t.reduce((e,t)=>(a(r,t.tags)&&e.push(t),e),[]);if(o.length)return o}return[]}(e,function(e,t,n){if(null==e.maxStalenessSeconds||e.maxStalenessSeconds<0)return n;const r=e.maxStalenessSeconds,i=(t.heartbeatFrequencyMS+1e4)/1e3;if(r<i)throw new s(`maxStalenessSeconds must be at least ${i} seconds`);if(r<90)throw new s("maxStalenessSeconds must be at least 90 seconds");if(t.type===o.ReplicaSetWithPrimary){const r=Array.from(t.servers.values()).filter(u)[0];return n.reduce((n,o)=>((o.lastUpdateTime-o.lastWriteDate-(r.lastUpdateTime-r.lastWriteDate)+t.heartbeatFrequencyMS)/1e3<=e.maxStalenessSeconds&&n.push(o),n),[])}if(t.type===o.ReplicaSetNoPrimary){if(0===n.length)return n;const r=n.reduce((e,t)=>t.lastWriteDate>e.lastWriteDate?t:e);return n.reduce((n,o)=>((r.lastWriteDate-o.lastWriteDate+t.heartbeatFrequencyMS)/1e3<=e.maxStalenessSeconds&&n.push(o),n),[])}return n}(e,t,n.filter(h))));return d===i.SECONDARY_PREFERRED&&0===m.length?n.filter(u):m}}}},function(e,t,n){"use strict";const r=n(90),o=n(137),i=n(87),s=n(3).MongoParseError,a=n(10),c=n(0).emitWarningOnce,u=/(mongodb(?:\+srv|)):\/\/(?: (?:[^:]*) (?: : ([^@]*) )? @ )?([^/?]*)(?:\/|)(.*)/,l=new Set(["sslCA","sslCert","sslKey","tlsCAFile","tlsCertificateKeyFile"].map(e=>e.toLowerCase()));function f(e,t){const n=/^.*?\./,r=`.${e.replace(n,"")}`,o=`.${t.replace(n,"")}`;return r.endsWith(o)}function p(e,t){if(Array.isArray(t))1===(t=t.filter((e,n)=>t.indexOf(e)===n)).length&&(t=t[0]);else if(t.indexOf(":")>0)t=t.split(",").reduce((t,n)=>{const r=n.split(":");return t[r[0]]=p(e,r[1]),t},{});else if(t.indexOf(",")>0)t=t.split(",").map(t=>p(e,t));else if("true"===t.toLowerCase()||"false"===t.toLowerCase())t="true"===t.toLowerCase();else if(!Number.isNaN(t)&&!h.has(e)){const e=parseFloat(t);Number.isNaN(e)||(t=parseFloat(t))}return t}const d=new Set(["slaveok","slave_ok","sslvalidate","fsync","safe","retrywrites","j"]),h=new Set(["authsource","replicaset"]),m=new Set(["GSSAPI","MONGODB-AWS","MONGODB-X509","MONGODB-CR","DEFAULT","SCRAM-SHA-1","SCRAM-SHA-256","PLAIN"]),g={replicaset:"replicaSet",connecttimeoutms:"connectTimeoutMS",sockettimeoutms:"socketTimeoutMS",maxpoolsize:"maxPoolSize",minpoolsize:"minPoolSize",maxidletimems:"maxIdleTimeMS",waitqueuemultiple:"waitQueueMultiple",waitqueuetimeoutms:"waitQueueTimeoutMS",wtimeoutms:"wtimeoutMS",readconcern:"readConcern",readconcernlevel:"readConcernLevel",readpreference:"readPreference",maxstalenessseconds:"maxStalenessSeconds",readpreferencetags:"readPreferenceTags",authsource:"authSource",authmechanism:"authMechanism",authmechanismproperties:"authMechanismProperties",gssapiservicename:"gssapiServiceName",localthresholdms:"localThresholdMS",serverselectiontimeoutms:"serverSelectionTimeoutMS",serverselectiontryonce:"serverSelectionTryOnce",heartbeatfrequencyms:"heartbeatFrequencyMS",retrywrites:"retryWrites",uuidrepresentation:"uuidRepresentation",zlibcompressionlevel:"zlibCompressionLevel",tlsallowinvalidcertificates:"tlsAllowInvalidCertificates",tlsallowinvalidhostnames:"tlsAllowInvalidHostnames",tlsinsecure:"tlsInsecure",tlscafile:"tlsCAFile",tlscertificatekeyfile:"tlsCertificateKeyFile",tlscertificatekeyfilepassword:"tlsCertificateKeyFilePassword",wtimeout:"wTimeoutMS",j:"journal",directconnection:"directConnection"};function y(e,t,n,r){if("journal"===t?t="j":"wtimeoutms"===t&&(t="wtimeout"),d.has(t)?n="true"===n||!0===n:"appname"===t?n=decodeURIComponent(n):"readconcernlevel"===t&&(e.readConcernLevel=n,t="readconcern",n={level:n}),"compressors"===t&&!(n=Array.isArray(n)?n:[n]).every(e=>"snappy"===e||"zlib"===e))throw new s("Value for `compressors` must be at least one of: `snappy`, `zlib`");if("authmechanism"===t&&!m.has(n))throw new s(`Value for authMechanism must be one of: ${Array.from(m).join(", ")}, found: ${n}`);if("readpreference"===t&&!a.isValid(n))throw new s("Value for `readPreference` must be one of: `primary`, `primaryPreferred`, `secondary`, `secondaryPreferred`, `nearest`");if("zlibcompressionlevel"===t&&(n<-1||n>9))throw new s("zlibCompressionLevel must be an integer between -1 and 9");"compressors"!==t&&"zlibcompressionlevel"!==t||(e.compression=e.compression||{},e=e.compression),"authmechanismproperties"===t&&("string"==typeof n.SERVICE_NAME&&(e.gssapiServiceName=n.SERVICE_NAME),"string"==typeof n.SERVICE_REALM&&(e.gssapiServiceRealm=n.SERVICE_REALM),void 0!==n.CANONICALIZE_HOST_NAME&&(e.gssapiCanonicalizeHostName=n.CANONICALIZE_HOST_NAME)),"readpreferencetags"===t&&(n=Array.isArray(n)?function(e){const t=[];for(let n=0;n<e.length;n++)t[n]={},e[n].split(",").forEach(e=>{const r=e.split(":");t[n][r[0]]=r[1]});return t}(n):[n]),r.caseTranslate&&g[t]?e[g[t]]=n:e[t]=n}const b=new Set(["GSSAPI","MONGODB-CR","PLAIN","SCRAM-SHA-1","SCRAM-SHA-256"]);function v(e,t){const n={};let r=o.parse(e);!function(e){const t=Object.keys(e);if(-1!==t.indexOf("tlsInsecure")&&(-1!==t.indexOf("tlsAllowInvalidCertificates")||-1!==t.indexOf("tlsAllowInvalidHostnames")))throw new s("The `tlsInsecure` option cannot be used with `tlsAllowInvalidCertificates` or `tlsAllowInvalidHostnames`.");const n=S("tls",e,t),r=S("ssl",e,t);if(null!=n&&null!=r&&n!==r)throw new s("All values of `tls` and `ssl` must be the same.")}(r);for(const e in r){const o=r[e];if(""===o||null==o)throw new s("Incomplete key value pair for option");const i=e.toLowerCase();y(n,i,l.has(i)?o:p(i,o),t)}return n.wtimeout&&n.wtimeoutms&&(delete n.wtimeout,c("Unsupported option `wtimeout` specified")),Object.keys(n).length?n:null}function S(e,t,n){const r=-1!==n.indexOf(e);let o;if(o=Array.isArray(t[e])?t[e][0]:t[e],r&&Array.isArray(t[e])){const n=t[e][0];t[e].forEach(t=>{if(t!==n)throw new s(`All values of ${e} must be the same.`)})}return o}const w="mongodb+srv",_=["mongodb",w];function O(e,t,n){"function"==typeof t&&(n=t,t={}),t=Object.assign({},{caseTranslate:!0},t);try{r.parse(e)}catch(e){return n(new s("URI malformed, cannot be parsed"))}const a=e.match(u);if(!a)return n(new s("Invalid connection string"));const c=a[1];if(-1===_.indexOf(c))return n(new s("Invalid protocol provided"));const l=a[4].split("?"),p=l.length>0?l[0]:null,d=l.length>1?l[1]:null;let h;try{h=v(d,t)}catch(e){return n(e)}if(h=Object.assign({},h,t),c===w)return function(e,t,n){const a=r.parse(e,!0);if(t.directConnection||t.directconnection)return n(new s("directConnection not supported with SRV URI"));if(a.hostname.split(".").length<3)return n(new s("URI does not have hostname, domain name and tld"));if(a.domainLength=a.hostname.split(".").length,a.pathname&&a.pathname.match(","))return n(new s("Invalid URI, cannot contain multiple hostnames"));if(a.port)return n(new s(`Ports not accepted with '${w}' URIs`));const c=a.host;i.resolveSrv(`_mongodb._tcp.${c}`,(e,u)=>{if(e)return n(e);if(0===u.length)return n(new s("No addresses found at host"));for(let e=0;e<u.length;e++)if(!f(u[e].name,a.hostname,a.domainLength))return n(new s("Server record does not share hostname with parent URI"));a.protocol="mongodb",a.host=u.map(e=>`${e.name}:${e.port}`).join(","),"ssl"in t||a.search&&"ssl"in a.query&&null!==a.query.ssl||(a.query.ssl=!0),i.resolveTxt(c,(e,i)=>{if(e){if("ENODATA"!==e.code&&"ENOTFOUND"!==e.code)return n(e);i=null}if(i){if(i.length>1)return n(new s("Multiple text records not allowed"));if(i=o.parse(i[0].join("")),Object.keys(i).some(e=>"authSource"!==e&&"replicaSet"!==e))return n(new s("Text record must only set `authSource` or `replicaSet`"));a.query=Object.assign({},i,a.query)}a.search=o.stringify(a.query),O(r.format(a),t,(e,t)=>{e?n(e):n(null,Object.assign({},t,{srvHost:c}))})})})}(e,h,n);const m={username:null,password:null,db:p&&""!==p?o.unescape(p):null};if(h.auth?(h.auth.username&&(m.username=h.auth.username),h.auth.user&&(m.username=h.auth.user),h.auth.password&&(m.password=h.auth.password)):(h.username&&(m.username=h.username),h.user&&(m.username=h.user),h.password&&(m.password=h.password)),-1!==a[4].split("?")[0].indexOf("@"))return n(new s("Unescaped slash in userinfo section"));const g=a[3].split("@");if(g.length>2)return n(new s("Unescaped at-sign in authority section"));if(null==g[0]||""===g[0])return n(new s("No username provided in authority section"));if(g.length>1){const e=g.shift().split(":");if(e.length>2)return n(new s("Unescaped colon in authority section"));if(""===e[0])return n(new s("Invalid empty username provided"));m.username||(m.username=o.unescape(e[0])),m.password||(m.password=e[1]?o.unescape(e[1]):null)}let y=null;const S=g.shift().split(",").map(e=>{let t=r.parse(`mongodb://${e}`);if("/:"===t.path)return y=new s("Double colon in host identifier"),null;if(e.match(/\.sock/)&&(t.hostname=o.unescape(e),t.port=null),Number.isNaN(t.port))return void(y=new s("Invalid port (non-numeric string)"));const n={host:t.hostname,port:t.port?parseInt(t.port):27017};if(0!==n.port)if(n.port>65535)y=new s("Invalid port (larger than 65535) with hostname");else{if(!(n.port<0))return n;y=new s("Invalid port (negative number)")}else y=new s("Invalid port (zero) with hostname")}).filter(e=>!!e);if(y)return n(y);if(0===S.length||""===S[0].host||null===S[0].host)return n(new s("No hostname or hostnames provided in connection string"));if(!!h.directConnection&&1!==S.length)return n(new s("directConnection option requires exactly one host"));null==h.directConnection&&1===S.length&&null==h.replicaSet&&(h.directConnection=!0);const T={hosts:S,auth:m.db||m.username?m:null,options:Object.keys(h).length?h:null};var C;T.auth&&T.auth.db?T.defaultDatabase=T.auth.db:T.defaultDatabase="test",T.options=((C=T.options).tls&&(C.ssl=C.tls),C.tlsInsecure?(C.checkServerIdentity=!1,C.sslValidate=!1):Object.assign(C,{checkServerIdentity:!C.tlsAllowInvalidHostnames,sslValidate:!C.tlsAllowInvalidCertificates}),C.tlsCAFile&&(C.ssl=!0,C.sslCA=C.tlsCAFile),C.tlsCertificateKeyFile&&(C.ssl=!0,C.tlsCertificateFile?(C.sslCert=C.tlsCertificateFile,C.sslKey=C.tlsCertificateKeyFile):(C.sslKey=C.tlsCertificateKeyFile,C.sslCert=C.tlsCertificateKeyFile)),C.tlsCertificateKeyFilePassword&&(C.ssl=!0,C.sslPass=C.tlsCertificateKeyFilePassword),C);try{!function(e){if(null==e.options)return;const t=e.options,n=t.authsource||t.authSource;null!=n&&(e.auth=Object.assign({},e.auth,{db:n}));const r=t.authmechanism||t.authMechanism;if(null!=r){if(b.has(r)&&(!e.auth||null==e.auth.username))throw new s(`Username required for mechanism \`${r}\``);if("GSSAPI"===r){if(null!=n&&"$external"!==n)throw new s(`Invalid source \`${n}\` for mechanism \`${r}\` specified.`);e.auth=Object.assign({},e.auth,{db:"$external"})}if("MONGODB-AWS"===r){if(null!=n&&"$external"!==n)throw new s(`Invalid source \`${n}\` for mechanism \`${r}\` specified.`);e.auth=Object.assign({},e.auth,{db:"$external"})}if("MONGODB-X509"===r){if(e.auth&&null!=e.auth.password)throw new s(`Password not allowed for mechanism \`${r}\``);if(null!=n&&"$external"!==n)throw new s(`Invalid source \`${n}\` for mechanism \`${r}\` specified.`);e.auth=Object.assign({},e.auth,{db:"$external"})}"PLAIN"===r&&e.auth&&null==e.auth.db&&(e.auth=Object.assign({},e.auth,{db:"$external"}))}e.auth&&null==e.auth.db&&(e.auth=Object.assign({},e.auth,{db:"admin"}))}(T)}catch(e){return n(e)}n(null,T)}e.exports=O},function(e,t,n){"use strict";const r=n(8).EventEmitter;e.exports=class extends r{constructor(){super()}instrument(e,t){this.$MongoClient=e;const n=this.$prototypeConnect=e.prototype.connect,r=this;e.prototype.connect=function(e){return this.s.options.monitorCommands=!0,this.on("commandStarted",e=>r.emit("started",e)),this.on("commandSucceeded",e=>r.emit("succeeded",e)),this.on("commandFailed",e=>r.emit("failed",e)),n.call(this,e)},"function"==typeof t&&t(null,this)}uninstrument(){this.$MongoClient.prototype.connect=this.$prototypeConnect}}},function(e,t,n){"use strict";const r=n(60).buildCountCommand,o=n(0).handleCallback,i=n(2).MongoError,s=Array.prototype.push,a=n(17).CursorState;function c(e,t){if(0!==e.bufferedCount())return e._next(t),c}e.exports={count:function(e,t,n,o){t&&("number"==typeof e.cursorSkip()&&(n.skip=e.cursorSkip()),"number"==typeof e.cursorLimit()&&(n.limit=e.cursorLimit())),n.readPreference&&e.setReadPreference(n.readPreference),"number"!=typeof n.maxTimeMS&&e.cmd&&"number"==typeof e.cmd.maxTimeMS&&(n.maxTimeMS=e.cmd.maxTimeMS);let i,s={};s.skip=n.skip,s.limit=n.limit,s.hint=n.hint,s.maxTimeMS=n.maxTimeMS,s.collectionName=e.namespace.collection;try{i=r(e,e.cmd.query,s)}catch(e){return o(e)}e.server=e.topology.s.coreTopology,e.topology.command(e.namespace.withCollection("$cmd"),i,e.options,(e,t)=>{o(e,t?t.result.n:null)})},each:function e(t,n){if(!n)throw i.create({message:"callback is mandatory",driver:!0});if(t.isNotified())return;if(t.s.state===a.CLOSED||t.isDead())return o(n,i.create({message:"Cursor is closed",driver:!0}));t.s.state===a.INIT&&(t.s.state=a.OPEN);let r=null;if(t.bufferedCount()>0){for(;r=c(t,n);)r(t,n);e(t,n)}else t.next((r,i)=>r?o(n,r):null==i?t.close({skipKillCursors:!0},()=>o(n,null,null)):void(!1!==o(n,null,i)&&e(t,n)))},toArray:function(e,t){const n=[];e.rewind(),e.s.state=a.INIT;const r=()=>{e._next((i,a)=>{if(i)return o(t,i);if(null==a)return e.close({skipKillCursors:!0},()=>o(t,null,n));if(n.push(a),e.bufferedCount()>0){let t=e.readBufferedDocuments(e.bufferedCount());e.s.transforms&&"function"==typeof e.s.transforms.doc&&(t=t.map(e.s.transforms.doc)),s.apply(n,t)}r()})};r()}}},function(e,t,n){"use strict";const r=n(14).buildCountCommand,o=n(1).OperationBase;e.exports=class extends o{constructor(e,t,n){super(n),this.cursor=e,this.applySkipLimit=t}execute(e){const t=this.cursor,n=this.applySkipLimit,o=this.options;n&&("number"==typeof t.cursorSkip()&&(o.skip=t.cursorSkip()),"number"==typeof t.cursorLimit()&&(o.limit=t.cursorLimit())),o.readPreference&&t.setReadPreference(o.readPreference),"number"!=typeof o.maxTimeMS&&t.cmd&&"number"==typeof t.cmd.maxTimeMS&&(o.maxTimeMS=t.cmd.maxTimeMS);let i,s={};s.skip=o.skip,s.limit=o.limit,s.hint=o.hint,s.maxTimeMS=o.maxTimeMS,s.collectionName=t.namespace.collection;try{i=r(t,t.cmd.query,s)}catch(t){return e(t)}t.server=t.topology.s.coreTopology,t.topology.command(t.namespace.withCollection("$cmd"),i,t.options,(t,n)=>{e(t,n?n.result.n:null)})}}},function(e,t,n){"use strict";const r=n(141),o=r.BulkOperationBase,i=r.Batch,s=r.bson,a=n(0).toError;function c(e,t,n){const o=s.calculateObjectSize(n,{checkKeys:!1,ignoreUndefined:!1});if(o>=e.s.maxBsonObjectSize)throw a("document is larger than the maximum size "+e.s.maxBsonObjectSize);e.s.currentBatch=null,t===r.INSERT?e.s.currentBatch=e.s.currentInsertBatch:t===r.UPDATE?e.s.currentBatch=e.s.currentUpdateBatch:t===r.REMOVE&&(e.s.currentBatch=e.s.currentRemoveBatch);const c=e.s.maxKeySize;if(null==e.s.currentBatch&&(e.s.currentBatch=new i(t,e.s.currentIndex)),(e.s.currentBatch.size+1>=e.s.maxWriteBatchSize||e.s.currentBatch.size>0&&e.s.currentBatch.sizeBytes+c+o>=e.s.maxBatchSizeBytes||e.s.currentBatch.batchType!==t)&&(e.s.batches.push(e.s.currentBatch),e.s.currentBatch=new i(t,e.s.currentIndex)),Array.isArray(n))throw a("operation passed in cannot be an Array");return e.s.currentBatch.operations.push(n),e.s.currentBatch.originalIndexes.push(e.s.currentIndex),e.s.currentIndex=e.s.currentIndex+1,t===r.INSERT?(e.s.currentInsertBatch=e.s.currentBatch,e.s.bulkResult.insertedIds.push({index:e.s.bulkResult.insertedIds.length,_id:n._id})):t===r.UPDATE?e.s.currentUpdateBatch=e.s.currentBatch:t===r.REMOVE&&(e.s.currentRemoveBatch=e.s.currentBatch),e.s.currentBatch.size+=1,e.s.currentBatch.sizeBytes+=c+o,e}class u extends o{constructor(e,t,n){n=n||{},super(e,t,n=Object.assign(n,{addToOperationsList:c}),!1)}handleWriteError(e,t){return!this.s.batches.length&&super.handleWriteError(e,t)}}function l(e,t,n){return new u(e,t,n)}l.UnorderedBulkOperation=u,e.exports=l,e.exports.Bulk=u},function(e,t,n){"use strict";const r=n(141),o=r.BulkOperationBase,i=r.Batch,s=r.bson,a=n(0).toError;function c(e,t,n){const o=s.calculateObjectSize(n,{checkKeys:!1,ignoreUndefined:!1});if(o>=e.s.maxBsonObjectSize)throw a("document is larger than the maximum size "+e.s.maxBsonObjectSize);null==e.s.currentBatch&&(e.s.currentBatch=new i(t,e.s.currentIndex));const c=e.s.maxKeySize;if((e.s.currentBatchSize+1>=e.s.maxWriteBatchSize||e.s.currentBatchSize>0&&e.s.currentBatchSizeBytes+c+o>=e.s.maxBatchSizeBytes||e.s.currentBatch.batchType!==t)&&(e.s.batches.push(e.s.currentBatch),e.s.currentBatch=new i(t,e.s.currentIndex),e.s.currentBatchSize=0,e.s.currentBatchSizeBytes=0),t===r.INSERT&&e.s.bulkResult.insertedIds.push({index:e.s.currentIndex,_id:n._id}),Array.isArray(n))throw a("operation passed in cannot be an Array");return e.s.currentBatch.originalIndexes.push(e.s.currentIndex),e.s.currentBatch.operations.push(n),e.s.currentBatchSize+=1,e.s.currentBatchSizeBytes+=c+o,e.s.currentIndex+=1,e}class u extends o{constructor(e,t,n){n=n||{},super(e,t,n=Object.assign(n,{addToOperationsList:c}),!0)}}function l(e,t,n){return new u(e,t,n)}l.OrderedBulkOperation=u,e.exports=l,e.exports.Bulk=u},function(e,t,n){"use strict";const r=n(96);e.exports=class extends r{constructor(e,t,n){const r=[{$match:t}];"number"==typeof n.skip&&r.push({$skip:n.skip}),"number"==typeof n.limit&&r.push({$limit:n.limit}),r.push({$group:{_id:1,n:{$sum:1}}}),super(e,r,n)}execute(e,t){super.execute(e,(e,n)=>{if(e)return void t(e,null);const r=n.result;if(null==r.cursor||null==r.cursor.firstBatch)return void t(null,0);const o=r.cursor.firstBatch;t(null,o.length?o[0].n:0)})}}},function(e,t,n){"use strict";const r=n(1).OperationBase,o=n(14).removeDocuments,i=n(1).Aspect;class s extends r{constructor(e,t,n){super(n),this.collection=e,this.filter=t}execute(e){const t=this.collection,n=this.filter,r=this.options;r.single=!1,o(t,n,r,(t,n)=>{if(null!=e){if(t&&e)return e(t);if(null==n)return e(null,{result:{ok:1}});if(this.explain)return e(void 0,n.result);n.deletedCount=n.result.n,e(null,n)}})}}(0,n(1).defineAspects)(s,[i.EXPLAINABLE]),e.exports=s},function(e,t,n){"use strict";const r=n(1).OperationBase,o=n(14).removeDocuments,i=n(1).Aspect;class s extends r{constructor(e,t,n){super(n),this.collection=e,this.filter=t}execute(e){const t=this.collection,n=this.filter,r=this.options;r.single=!0,o(t,n,r,(t,n)=>{if(null!=e){if(t&&e)return e(t);if(null==n)return e(null,{result:{ok:1}});if(this.explain)return e(void 0,n.result);n.deletedCount=n.result.n,e(null,n)}})}}(0,n(1).defineAspects)(s,[i.EXPLAINABLE]),e.exports=s},function(e,t,n){"use strict";const r=n(1).Aspect,o=n(1).defineAspects,i=n(27),s=n(0).decorateWithCollation,a=n(0).decorateWithReadConcern,c=n(4).maxWireVersion,u=n(95).MongoError;class l extends i{constructor(e,t,n,r){super(e,r),this.collection=e,this.key=t,this.query=n}execute(e,t){const n=this.collection,r=this.key,o=this.query,i=this.options,l={distinct:n.collectionName,key:r,query:o};"number"==typeof i.maxTimeMS&&(l.maxTimeMS=i.maxTimeMS),a(l,n,i);try{s(l,n,i)}catch(e){return t(e,null)}this.explain&&c(e)<4?t(new u("server does not support explain on distinct")):super.executeCommand(e,l,(e,n)=>{e?t(e):t(null,this.options.full||this.explain?n:n.values)})}}o(l,[r.READ_OPERATION,r.RETRYABLE,r.EXECUTE_WITH_SELECTION,r.EXPLAINABLE]),e.exports=l},function(e,t,n){"use strict";const r=n(1).Aspect,o=n(1).defineAspects,i=n(211),s=n(0).handleCallback;class a extends i{constructor(e,t){super(e,"*",t)}execute(e){super.execute(t=>{if(t)return s(e,t,!1);s(e,null,!0)})}}o(a,r.WRITE_OPERATION),e.exports=a},function(e,t,n){"use strict";const r=n(1).Aspect,o=n(1).defineAspects,i=n(27);class s extends i{constructor(e,t,n){void 0===n&&(n=t,t=void 0),super(e,n),this.collectionName=e.s.namespace.collection,t&&(this.query=t)}execute(e,t){const n=this.options,r={count:this.collectionName};this.query&&(r.query=this.query),"number"==typeof n.skip&&(r.skip=n.skip),"number"==typeof n.limit&&(r.limit=n.limit),n.hint&&(r.hint=n.hint),super.executeCommand(e,r,(e,n)=>{e?t(e):t(null,n.n)})}}o(s,[r.READ_OPERATION,r.RETRYABLE,r.EXECUTE_WITH_SELECTION]),e.exports=s},function(e,t,n){"use strict";const r=n(1).OperationBase,o=n(1).Aspect,i=n(1).defineAspects,s=n(2).ReadPreference,a=n(4).maxWireVersion,c=n(3).MongoError;class u extends r{constructor(e,t,n,r){super(r),this.ns=t,this.cmd=n,this.readPreference=s.resolve(e,this.options)}execute(e,t){if(this.server=e,this.readPreference=s.resolve(this,this.options),void 0!==this.cmd.allowDiskUse&&a(e)<4)return void t(new c("The `allowDiskUse` option is not supported on MongoDB < 3.2"));this.explain&&(this.options.explain=this.explain.verbosity);const n=this.cursorState||{};e.query(this.ns.toString(),this.cmd,n,this.options,t)}}i(u,[o.READ_OPERATION,o.RETRYABLE,o.EXECUTE_WITH_SELECTION,o.EXPLAINABLE]),e.exports=u},function(e,t,n){"use strict";const r=n(0).handleCallback,o=n(1).OperationBase,i=n(0).toError,s=n(1).Aspect;class a extends o{constructor(e,t,n){super(n),this.collection=e,this.query=t}execute(e){const t=this.collection,n=this.query,o=this.options;try{t.find(n,o).limit(-1).batchSize(1).next((t,n)=>{if(null!=t)return r(e,i(t),null);r(e,null,n)})}catch(t){e(t)}}}(0,n(1).defineAspects)(a,[s.EXPLAINABLE]),e.exports=a},function(e,t,n){"use strict";const r=n(97);e.exports=class extends r{constructor(e,t,n){const r=Object.assign({},n);if(r.fields=n.projection,r.remove=!0,null==t||"object"!=typeof t)throw new TypeError("Filter parameter must be an object");super(e,t,r.sort,null,r)}}},function(e,t,n){"use strict";const r=n(97),o=n(0).hasAtomicOperators;e.exports=class extends r{constructor(e,t,n,r){const i=Object.assign({},r);if(i.fields=r.projection,i.update=!0,i.new=void 0!==r.returnOriginal&&!r.returnOriginal,i.upsert=void 0!==r.upsert&&!!r.upsert,null==t||"object"!=typeof t)throw new TypeError("Filter parameter must be an object");if(null==n||"object"!=typeof n)throw new TypeError("Replacement parameter must be an object");if(o(n))throw new TypeError("Replacement document must not contain atomic operators");super(e,t,i.sort,n,i)}}},function(e,t,n){"use strict";const r=n(97),o=n(0).hasAtomicOperators;e.exports=class extends r{constructor(e,t,n,r){const i=Object.assign({},r);if(i.fields=r.projection,i.update=!0,i.new="boolean"==typeof r.returnOriginal&&!r.returnOriginal,i.upsert="boolean"==typeof r.upsert&&r.upsert,null==t||"object"!=typeof t)throw new TypeError("Filter parameter must be an object");if(null==n||"object"!=typeof n)throw new TypeError("Update parameter must be an object");if(!o(n))throw new TypeError("Update document requires atomic operators");super(e,t,i.sort,n,i)}}},function(e,t,n){"use strict";const r=n(1).Aspect,o=n(1).defineAspects,i=n(1).OperationBase,s=n(0).decorateCommand,a=n(0).decorateWithReadConcern,c=n(11).executeCommand,u=n(0).handleCallback,l=n(2).ReadPreference,f=n(0).toError;class p extends i{constructor(e,t,n,r){super(r),this.collection=e,this.x=t,this.y=n}execute(e){const t=this.collection,n=this.x,r=this.y;let o=this.options,i={geoSearch:t.collectionName,near:[n,r]};i=s(i,o,["readPreference","session"]),o=Object.assign({},o),o.readPreference=l.resolve(t,o),a(i,t,o),c(t.s.db,i,o,(t,n)=>{if(t)return u(e,t);(n.err||n.errmsg)&&u(e,f(n)),u(e,null,n)})}}o(p,r.READ_OPERATION),e.exports=p},function(e,t,n){"use strict";const r=n(1).OperationBase,o=n(14).indexInformation;e.exports=class extends r{constructor(e,t){super(t),this.collection=e}execute(e){const t=this.collection;let n=this.options;n=Object.assign({},{full:!0},n),o(t.s.db,t.collectionName,n,e)}}},function(e,t,n){"use strict";const r=n(1).OperationBase,o=n(0).handleCallback,i=n(11).indexInformation;e.exports=class extends r{constructor(e,t,n){super(n),this.collection=e,this.indexes=t}execute(e){const t=this.collection,n=this.indexes,r=this.options;i(t.s.db,t.collectionName,r,(t,r)=>{if(null!=t)return o(e,t,null);if(!Array.isArray(n))return o(e,null,null!=r[n]);for(let t=0;t<n.length;t++)if(null==r[n[t]])return o(e,null,!1);return o(e,null,!0)})}}},function(e,t,n){"use strict";const r=n(1).OperationBase,o=n(209),i=n(2).MongoError,s=n(14).prepareDocs;e.exports=class extends r{constructor(e,t,n){super(n),this.collection=e,this.docs=t}execute(e){const t=this.collection;let n=this.docs;const r=this.options;if(!Array.isArray(n))return e(i.create({message:"docs parameter must be an array of documents",driver:!0}));r.serializeFunctions=r.serializeFunctions||t.s.serializeFunctions,n=s(t,n,r),new o(t,[{insertMany:n}],r).execute((t,r)=>{if(t)return e(t,null);e(null,function(e,t){const n={result:{ok:1,n:t.insertedCount},ops:e,insertedCount:t.insertedCount,insertedIds:t.insertedIds};t.getLastOp()&&(n.result.opTime=t.getLastOp());return n}(n,r))})}}},function(e,t,n){"use strict";const r=n(2).MongoError,o=n(1).OperationBase,i=n(14).insertDocuments;e.exports=class extends o{constructor(e,t,n){super(n),this.collection=e,this.doc=t}execute(e){const t=this.collection,n=this.doc,o=this.options;if(Array.isArray(n))return e(r.create({message:"doc parameter must be an object",driver:!0}));i(t,[n],o,(t,r)=>{if(null!=e){if(t&&e)return e(t);if(null==r)return e(null,{result:{ok:1}});r.insertedCount=r.result.n,r.insertedId=n._id,e&&e(null,r)}})}}},function(e,t,n){"use strict";const r=n(213),o=n(0).handleCallback;e.exports=class extends r{constructor(e,t){super(e,t)}execute(e){super.execute((t,n)=>{if(t)return o(e,t);o(e,null,!(!n||!n.capped))})}}},function(e,t,n){"use strict";const r=n(27),o=n(1).Aspect,i=n(1).defineAspects,s=n(4).maxWireVersion;class a extends r{constructor(e,t){super(e,t,{fullResponse:!0}),this.collectionNamespace=e.s.namespace}execute(e,t){if(s(e)<3){const n=this.collectionNamespace.withCollection("system.indexes").toString(),r=this.collectionNamespace.toString();return void e.query(n,{query:{ns:r}},{},this.options,t)}const n=this.options.batchSize?{batchSize:this.options.batchSize}:{};super.executeCommand(e,{listIndexes:this.collectionNamespace.collection,cursor:n},t)}}i(a,[o.READ_OPERATION,o.RETRYABLE,o.EXECUTE_WITH_SELECTION]),e.exports=a},function(e,t,n){"use strict";const r=n(0).applyWriteConcern,o=n(2).BSON.Code,i=n(0).decorateWithCollation,s=n(0).decorateWithReadConcern,a=n(11).executeCommand,c=n(0).handleCallback,u=n(0).isObject,l=n(145).loadDb,f=n(1).OperationBase,p=n(2).ReadPreference,d=n(0).toError,h=n(1).Aspect,m=n(1).defineAspects,g=n(0).decorateWithExplain,y=n(4).maxWireVersion,b=n(95).MongoError,v=["explain","readPreference","session","bypassDocumentValidation","w","wtimeout","j","writeConcern"];class S extends f{constructor(e,t,n,r){super(r),this.collection=e,this.map=t,this.reduce=n}execute(e){const t=this.collection,n=this.map,o=this.reduce;let u=this.options,f={mapReduce:t.collectionName,map:n,reduce:o};for(let e in u)"scope"===e?f[e]=w(u[e]):-1===v.indexOf(e)&&(f[e]=u[e]);u=Object.assign({},u),u.readPreference=p.resolve(t,u),!1!==u.readPreference&&"primary"!==u.readPreference&&u.out&&1!==u.out.inline&&"inline"!==u.out?(u.readPreference="primary",r(f,{db:t.s.db,collection:t},u)):s(f,t,u),!0===u.bypassDocumentValidation&&(f.bypassDocumentValidation=u.bypassDocumentValidation);try{i(f,t,u)}catch(t){return e(t,null)}if(this.explain){if(y(t.s.topology)<9)return void e(new b("server does not support explain on mapReduce"));f=g(f,this.explain)}a(t.s.db,f,u,(n,r)=>{if(n)return c(e,n);if(1!==r.ok||r.err||r.errmsg)return c(e,d(r));if(this.explain)return e(void 0,r);const o={};if(r.timeMillis&&(o.processtime=r.timeMillis),r.counts&&(o.counts=r.counts),r.timing&&(o.timing=r.timing),r.results)return null!=u.verbose&&u.verbose?c(e,null,{results:r.results,stats:o}):c(e,null,r.results);let i=null;if(null!=r.result&&"object"==typeof r.result){const e=r.result;i=new(l())(e.db,t.s.db.s.topology,t.s.db.s.options).collection(e.collection)}else i=t.s.db.collection(r.result);if(null==u.verbose||!u.verbose)return c(e,n,i);c(e,n,{collection:i,stats:o})})}}function w(e){if(!u(e)||"ObjectID"===e._bsontype)return e;const t=Object.keys(e);let n;const r={};for(let i=t.length-1;i>=0;i--)n=t[i],"function"==typeof e[n]?r[n]=new o(String(e[n])):r[n]=w(e[n]);return r}m(S,[h.EXPLAINABLE]),e.exports=S},function(e,t,n){"use strict";const r=n(1).OperationBase,o=n(0).handleCallback;let i;e.exports=class extends r{constructor(e,t){super(t),this.db=e}execute(e){const t=this.db;let r=this.options,s=(i||(i=n(61)),i);r=Object.assign({},r,{nameOnly:!0}),t.listCollections({},r).toArray((n,r)=>{if(null!=n)return o(e,n,null);r=r.filter(e=>-1===e.name.indexOf("$")),o(e,null,r.map(e=>new s(t,t.s.topology,t.databaseName,e.name,t.s.pkFactory,t.s.options)))})}}},function(e,t,n){"use strict";const r=n(27),o=n(1).defineAspects,i=n(1).Aspect;class s extends r{constructor(e,t,n){super(e,n),this.command=t}execute(e,t){const n=this.command;this.executeCommand(e,n,t)}}o(s,[i.EXECUTE_WITH_SELECTION,i.NO_INHERIT_OPTIONS]),e.exports=s},function(e,t,n){"use strict";const r=n(1).Aspect,o=n(1).defineAspects,i=n(23),s=n(0).applyWriteConcern,a=n(145).loadCollection,c=n(2).MongoError,u=n(2).ReadPreference,l=new Set(["w","wtimeout","j","fsync","autoIndexId","strict","serializeFunctions","pkFactory","raw","readPreference","session","readConcern","writeConcern"]);class f extends i{constructor(e,t,n){super(e,n),this.name=t}_buildCommand(){const e=this.name,t=this.options,n={create:e};for(let e in t)null==t[e]||"function"==typeof t[e]||l.has(e)||(n[e]=t[e]);return n}execute(e){const t=this.db,n=this.name,r=this.options,o=a();let i=Object.assign({nameOnly:!0,strict:!1},r);function l(i){if(i)return e(i);try{e(null,new o(t,t.s.topology,t.databaseName,n,t.s.pkFactory,r))}catch(i){e(i)}}i=s(i,{db:t},i),i.strict?t.listCollections({name:n},i).setReadPreference(u.PRIMARY).toArray((t,r)=>t?e(t):r.length>0?e(new c(`Collection ${n} already exists. Currently in strict mode.`)):void super.execute(l)):super.execute(l)}}o(f,r.WRITE_OPERATION),e.exports=f},function(e,t,n){"use strict";const r=n(27),o=n(1).Aspect,i=n(1).defineAspects,s=n(4).maxWireVersion,a=n(140);class c extends r{constructor(e,t,n){super(e,n,{fullResponse:!0}),this.db=e,this.filter=t,this.nameOnly=!!this.options.nameOnly,"number"==typeof this.options.batchSize&&(this.batchSize=this.options.batchSize)}execute(e,t){if(s(e)<3){let n=this.filter;const r=this.db.s.namespace.db;"string"!=typeof n.name||new RegExp("^"+r+"\\.").test(n.name)||(n=Object.assign({},n),n.name=this.db.s.namespace.withCollection(n.name).toString()),null==n&&(n.name=`/${r}/`),n=n.name?{$and:[{name:n.name},{name:/^((?!\$).)*$/}]}:{name:/^((?!\$).)*$/};const o=function(e){const t=`${e}.`;return{doc:e=>{const n=e.name.indexOf(t);return e.name&&0===n&&(e.name=e.name.substr(n+t.length)),e}}}(r);return void e.query(`${r}.${a.SYSTEM_NAMESPACE_COLLECTION}`,{query:n},{batchSize:this.batchSize||1e3},{},(e,n)=>{n&&n.message&&n.message.documents&&Array.isArray(n.message.documents)&&(n.message.documents=n.message.documents.map(o.doc)),t(e,n)})}const n={listCollections:1,filter:this.filter,cursor:this.batchSize?{batchSize:this.batchSize}:{},nameOnly:this.nameOnly};return super.executeCommand(e,n,t)}}i(c,[o.READ_OPERATION,o.RETRYABLE,o.EXECUTE_WITH_SELECTION]),e.exports=c},function(e,t,n){"use strict";const r=n(23);e.exports=class extends r{constructor(e,t,n){super(e,n)}_buildCommand(){return{profile:-1}}execute(e){super.execute((t,n)=>{if(null==t&&1===n.ok){const t=n.was;return 0===t?e(null,"off"):1===t?e(null,"slow_only"):2===t?e(null,"all"):e(new Error("Error: illegal profiling level value "+t),null)}e(null!=t?t:new Error("Error with profile command"),null)})}}},function(e,t,n){"use strict";const r=n(23),o=new Set(["off","slow_only","all"]);e.exports=class extends r{constructor(e,t,n){let r=0;"off"===t?r=0:"slow_only"===t?r=1:"all"===t&&(r=2),super(e,n),this.level=t,this.profile=r}_buildCommand(){return{profile:this.profile}}execute(e){const t=this.level;if(!o.has(t))return e(new Error("Error: illegal profiling level value "+t));super.execute((n,r)=>null==n&&1===r.ok?e(null,t):e(null!=n?n:new Error("Error with profile command"),null))}}},function(e,t,n){"use strict";const r=n(23);e.exports=class extends r{constructor(e,t,n){let r={validate:t};const o=Object.keys(n);for(let e=0;e<o.length;e++)Object.prototype.hasOwnProperty.call(n,o[e])&&"session"!==o[e]&&(r[o[e]]=n[o[e]]);super(e.s.db,n,null,r),this.collectionName=t}execute(e){const t=this.collectionName;super.execute((n,r)=>null!=n?e(n,null):0===r.ok?e(new Error("Error with validate command"),null):null!=r.result&&r.result.constructor!==String?e(new Error("Error with validation data"),null):null!=r.result&&null!=r.result.match(/exception|corrupt/)?e(new Error("Error: invalid collection "+t),null):null==r.valid||r.valid?e(null,r):e(new Error("Error: invalid collection "+t),null))}}},function(e,t,n){"use strict";const r=n(27),o=n(1).Aspect,i=n(1).defineAspects,s=n(0).MongoDBNamespace;class a extends r{constructor(e,t){super(e,t),this.ns=new s("admin","$cmd")}execute(e,t){const n={listDatabases:1};this.options.nameOnly&&(n.nameOnly=Number(n.nameOnly)),this.options.filter&&(n.filter=this.options.filter),"boolean"==typeof this.options.authorizedDatabases&&(n.authorizedDatabases=this.options.authorizedDatabases),super.executeCommand(e,n,t)}}i(a,[o.READ_OPERATION,o.RETRYABLE,o.EXECUTE_WITH_SELECTION]),e.exports=a},function(e,t,n){"use strict";const r=n(1).Aspect,o=n(1).defineAspects,i=n(27),s=n(13).serverType,a=n(13).ServerType,c=n(2).MongoError;class u extends i{constructor(e,t){super(e,t),this.collectionName=e.collectionName}execute(e,t){s(e)===a.Standalone?super.executeCommand(e,{reIndex:this.collectionName},(e,n)=>{e?t(e):t(null,!!n.ok)}):t(new c("reIndex can only be executed on standalone servers."))}}o(u,[r.EXECUTE_WITH_SELECTION]),e.exports=u},function(e,t,n){"use strict";const r=n(1).OperationBase,o=n(14).updateDocuments,i=n(0).hasAtomicOperators;e.exports=class extends r{constructor(e,t,n,r){if(super(r),i(n))throw new TypeError("Replacement document must not contain atomic operators");this.collection=e,this.filter=t,this.replacement=n}execute(e){const t=this.collection,n=this.filter,r=this.replacement,i=this.options;i.multi=!1,o(t,n,r,i,(t,n)=>function(e,t,n,r){if(null==r)return;if(e&&r)return r(e);if(null==t)return r(null,{result:{ok:1}});t.modifiedCount=null!=t.result.nModified?t.result.nModified:t.result.n,t.upsertedId=Array.isArray(t.result.upserted)&&t.result.upserted.length>0?t.result.upserted[0]:null,t.upsertedCount=Array.isArray(t.result.upserted)&&t.result.upserted.length?t.result.upserted.length:0,t.matchedCount=Array.isArray(t.result.upserted)&&t.result.upserted.length>0?0:t.result.n,t.ops=[n],r&&r(null,t)}(t,n,r,e))}}},function(e,t,n){"use strict";const r=n(1).Aspect,o=n(23);class i extends o{constructor(e,t){super(e.s.db,t,e)}_buildCommand(){const e=this.collection,t=this.options,n={collStats:e.collectionName};return null!=t.scale&&(n.scale=t.scale),n}}(0,n(1).defineAspects)(i,r.READ_OPERATION),e.exports=i},function(e,t,n){"use strict";const r=n(1).OperationBase,o=n(14).updateDocuments,i=n(0).hasAtomicOperators,s=n(1).Aspect;class a extends r{constructor(e,t,n,r){if(super(r),!i(n))throw new TypeError("Update document requires atomic operators");this.collection=e,this.filter=t,this.update=n}execute(e){const t=this.collection,n=this.filter,r=this.update,i=this.options;i.multi=!0,o(t,n,r,i,(t,n)=>{if(null!=e){if(t)return e(t);if(null==n)return e(null,{result:{ok:1}});if(this.explain)return e(void 0,n.result);n.modifiedCount=null!=n.result.nModified?n.result.nModified:n.result.n,n.upsertedId=Array.isArray(n.result.upserted)&&n.result.upserted.length>0?n.result.upserted[0]:null,n.upsertedCount=Array.isArray(n.result.upserted)&&n.result.upserted.length?n.result.upserted.length:0,n.matchedCount=Array.isArray(n.result.upserted)&&n.result.upserted.length>0?0:n.result.n,e(null,n)}})}}(0,n(1).defineAspects)(a,[s.EXPLAINABLE]),e.exports=a},function(e,t,n){"use strict";const r=n(1).OperationBase,o=n(14).updateDocuments,i=n(0).hasAtomicOperators,s=n(1).Aspect;class a extends r{constructor(e,t,n,r){if(super(r),!i(n))throw new TypeError("Update document requires atomic operators");this.collection=e,this.filter=t,this.update=n}execute(e){const t=this.collection,n=this.filter,r=this.update,i=this.options;i.multi=!1,o(t,n,r,i,(t,n)=>{if(null!=e){if(t)return e(t);if(null==n)return e(null,{result:{ok:1}});if(this.explain)return e(void 0,n.result);n.modifiedCount=null!=n.result.nModified?n.result.nModified:n.result.n,n.upsertedId=Array.isArray(n.result.upserted)&&n.result.upserted.length>0?n.result.upserted[0]:null,n.upsertedCount=Array.isArray(n.result.upserted)&&n.result.upserted.length?n.result.upserted.length:0,n.matchedCount=Array.isArray(n.result.upserted)&&n.result.upserted.length>0?0:n.result.n,e(null,n)}})}}(0,n(1).defineAspects)(a,[s.EXPLAINABLE]),e.exports=a},function(e,t,n){"use strict";const r=n(2).ReadPreference,o=n(90),i=n(5).format,s=n(2).Logger,a=n(87),c=n(46),u=n(137),l=n(3).MongoParseError;function f(e,t){let n=/^.*?\./,r=`.${e.replace(n,"")}`,o=`.${t.replace(n,"")}`;return!!r.endsWith(o)}function p(e,t,n){let a,u;try{a=function(e,t){let n="",a="",u="",l="admin",f=o.parse(e,!0);if((null==f.hostname||""===f.hostname)&&-1===e.indexOf(".sock"))throw new Error("No hostname or hostnames provided in connection string");if("0"===f.port)throw new Error("Invalid port (zero) with hostname");if(!isNaN(parseInt(f.port,10))&&parseInt(f.port,10)>65535)throw new Error("Invalid port (larger than 65535) with hostname");if(f.path&&f.path.length>0&&"/"!==f.path[0]&&-1===e.indexOf(".sock"))throw new Error("Missing delimiting slash between hosts and options");if(f.query)for(let e in f.query){if(-1!==e.indexOf("::"))throw new Error("Double colon in host identifier");if(""===f.query[e])throw new Error("Query parameter "+e+" is an incomplete value pair")}if(f.auth){let t=f.auth.split(":");if(-1!==e.indexOf(f.auth)&&t.length>2)throw new Error("Username with password containing an unescaped colon");if(-1!==e.indexOf(f.auth)&&-1!==f.auth.indexOf("@"))throw new Error("Username containing an unescaped at-sign")}let p=e.split("?").shift().split(","),d=[];for(let e=0;e<p.length;e++){let t=p[e];-1!==t.indexOf("mongodb")?-1!==t.indexOf("@")?d.push(t.split("@").pop()):d.push(t.substr("mongodb://".length)):-1!==t.indexOf("/")?d.push(t.split("/").shift()):-1===t.indexOf("/")&&d.push(t.trim())}for(let e=0;e<d.length;e++){let t=o.parse(i("mongodb://%s",d[e].trim()));if((!t.path||-1===t.path.indexOf(".sock"))&&(t.path&&-1!==t.path.indexOf(":")))throw t.path.split("/").length>1&&-1===t.path.indexOf("::")?new Error("Slash in host identifier"):new Error("Double colon in host identifier")}-1!==e.indexOf("?")?(u=e.substr(e.indexOf("?")+1),n=e.substring("mongodb://".length,e.indexOf("?"))):n=e.substring("mongodb://".length);-1!==n.indexOf("@")&&(a=n.split("@")[0],n=n.split("@")[1]);if(n.split("/").length>2)throw new Error("Unsupported host '"+n.split("?")[0]+"', hosts must be URL encoded and contain at most one unencoded slash");if(-1!==n.indexOf(".sock")){if(-1!==n.indexOf(".sock/")){if(l=n.split(".sock/")[1],-1!==l.indexOf("/")){if(2===l.split("/").length&&0===l.split("/")[1].length)throw new Error("Illegal trailing backslash after database name");throw new Error("More than 1 database name in URL")}n=n.split("/",n.indexOf(".sock")+".sock".length)}}else if(-1!==n.indexOf("/")){if(n.split("/").length>2){if(0===n.split("/")[2].length)throw new Error("Illegal trailing backslash after database name");throw new Error("More than 1 database name in URL")}l=n.split("/")[1],n=n.split("/")[0]}n=decodeURIComponent(n);let h,m,g,y,b={},v=a||"",S=v.split(":",2),w=decodeURIComponent(S[0]);if(S[0]!==encodeURIComponent(w))throw new Error("Username contains an illegal unescaped character");if(S[0]=w,S[1]){let e=decodeURIComponent(S[1]);if(S[1]!==encodeURIComponent(e))throw new Error("Password contains an illegal unescaped character");S[1]=e}2===S.length&&(b.auth={user:S[0],password:S[1]});t&&null!=t.auth&&(b.auth=t.auth);let _={socketOptions:{}},O={read_preference_tags:[]},T={socketOptions:{}},C={socketOptions:{}};if(b.server_options=_,b.db_options=O,b.rs_options=T,b.mongos_options=C,e.match(/\.sock/)){let t=e.substring(e.indexOf("mongodb://")+"mongodb://".length,e.lastIndexOf(".sock")+".sock".length);-1!==t.indexOf("@")&&(t=t.split("@")[1]),t=decodeURIComponent(t),g=[{domain_socket:t}]}else{h=n;let e={};g=h.split(",").map((function(t){let n,r,o;if(o=/\[([^\]]+)\](?::(.+))?/.exec(t))n=o[1],r=parseInt(o[2],10)||27017;else{let e=t.split(":",2);n=e[0]||"localhost",r=null!=e[1]?parseInt(e[1],10):27017,-1!==n.indexOf("?")&&(n=n.split(/\?/)[0])}return e[n+"_"+r]?null:(e[n+"_"+r]=1,{host:n,port:r})})).filter((function(e){return null!=e}))}b.dbName=l||"admin",m=(u||"").split(/[&;]/),m.forEach((function(e){if(e){var t=e.split("="),n=t[0],o=t[1];switch(n){case"slaveOk":case"slave_ok":_.slave_ok="true"===o,O.slaveOk="true"===o;break;case"maxPoolSize":case"poolSize":_.poolSize=parseInt(o,10),T.poolSize=parseInt(o,10);break;case"appname":b.appname=decodeURIComponent(o);break;case"autoReconnect":case"auto_reconnect":_.auto_reconnect="true"===o;break;case"ssl":if("prefer"===o){_.ssl=o,T.ssl=o,C.ssl=o;break}_.ssl="true"===o,T.ssl="true"===o,C.ssl="true"===o;break;case"sslValidate":_.sslValidate="true"===o,T.sslValidate="true"===o,C.sslValidate="true"===o;break;case"replicaSet":case"rs_name":T.rs_name=o;break;case"reconnectWait":T.reconnectWait=parseInt(o,10);break;case"retries":T.retries=parseInt(o,10);break;case"readSecondary":case"read_secondary":T.read_secondary="true"===o;break;case"fsync":O.fsync="true"===o;break;case"journal":O.j="true"===o;break;case"safe":O.safe="true"===o;break;case"nativeParser":case"native_parser":O.native_parser="true"===o;break;case"readConcernLevel":O.readConcern=new c(o);break;case"connectTimeoutMS":_.socketOptions.connectTimeoutMS=parseInt(o,10),T.socketOptions.connectTimeoutMS=parseInt(o,10),C.socketOptions.connectTimeoutMS=parseInt(o,10);break;case"socketTimeoutMS":_.socketOptions.socketTimeoutMS=parseInt(o,10),T.socketOptions.socketTimeoutMS=parseInt(o,10),C.socketOptions.socketTimeoutMS=parseInt(o,10);break;case"w":O.w=parseInt(o,10),isNaN(O.w)&&(O.w=o);break;case"authSource":O.authSource=o;break;case"gssapiServiceName":O.gssapiServiceName=o;break;case"authMechanism":if("GSSAPI"===o)if(null==b.auth){let e=decodeURIComponent(v);if(-1===e.indexOf("@"))throw new Error("GSSAPI requires a provided principal");b.auth={user:e,password:null}}else b.auth.user=decodeURIComponent(b.auth.user);else"MONGODB-X509"===o&&(b.auth={user:decodeURIComponent(v)});if("GSSAPI"!==o&&"MONGODB-X509"!==o&&"MONGODB-CR"!==o&&"DEFAULT"!==o&&"SCRAM-SHA-1"!==o&&"SCRAM-SHA-256"!==o&&"PLAIN"!==o)throw new Error("Only DEFAULT, GSSAPI, PLAIN, MONGODB-X509, or SCRAM-SHA-1 is supported by authMechanism");O.authMechanism=o;break;case"authMechanismProperties":{let e=o.split(","),t={};e.forEach((function(e){let n=e.split(":");t[n[0]]=n[1]})),O.authMechanismProperties=t,"string"==typeof t.SERVICE_NAME&&(O.gssapiServiceName=t.SERVICE_NAME),"string"==typeof t.SERVICE_REALM&&(O.gssapiServiceRealm=t.SERVICE_REALM),"string"==typeof t.CANONICALIZE_HOST_NAME&&(O.gssapiCanonicalizeHostName="true"===t.CANONICALIZE_HOST_NAME)}break;case"wtimeoutMS":O.wtimeout=parseInt(o,10);break;case"readPreference":if(!r.isValid(o))throw new Error("readPreference must be either primary/primaryPreferred/secondary/secondaryPreferred/nearest");O.readPreference=o;break;case"maxStalenessSeconds":O.maxStalenessSeconds=parseInt(o,10);break;case"readPreferenceTags":{let e={};if(null==(o=decodeURIComponent(o))||""===o){O.read_preference_tags.push(e);break}let t=o.split(/,/);for(let n=0;n<t.length;n++){let r=t[n].trim().split(/:/);e[r[0]]=r[1]}O.read_preference_tags.push(e)}break;case"compressors":{y=_.compression||{};let e=o.split(",");if(!e.every((function(e){return"snappy"===e||"zlib"===e})))throw new Error("Compressors must be at least one of snappy or zlib");y.compressors=e,_.compression=y}break;case"zlibCompressionLevel":{y=_.compression||{};let e=parseInt(o,10);if(e<-1||e>9)throw new Error("zlibCompressionLevel must be an integer between -1 and 9");y.zlibCompressionLevel=e,_.compression=y}break;case"retryWrites":O.retryWrites="true"===o;break;case"minSize":O.minSize=parseInt(o,10);break;default:s("URL Parser").warn(`${n} is not supported as a connection string option`)}}})),0===O.read_preference_tags.length&&(O.read_preference_tags=null);if(!(-1!==O.w&&0!==O.w||!0!==O.journal&&!0!==O.fsync&&!0!==O.safe))throw new Error("w set to -1 or 0 cannot be combined with safe/w/journal/fsync");O.readPreference||(O.readPreference="primary");return O=Object.assign(O,t),b.servers=g,b}(e,t)}catch(e){u=e}return u?n(u,null):n(null,a)}e.exports=function(e,t,n){let r;"function"==typeof t&&(n=t,t={}),t=t||{};try{r=o.parse(e,!0)}catch(e){return n(new Error("URL malformed, cannot be parsed"))}if("mongodb:"!==r.protocol&&"mongodb+srv:"!==r.protocol)return n(new Error("Invalid schema, expected `mongodb` or `mongodb+srv`"));if("mongodb:"===r.protocol)return p(e,t,n);if(r.hostname.split(".").length<3)return n(new Error("URI does not have hostname, domain name and tld"));if(r.domainLength=r.hostname.split(".").length,r.pathname&&r.pathname.match(","))return n(new Error("Invalid URI, cannot contain multiple hostnames"));if(r.port)return n(new Error("Ports not accepted with `mongodb+srv` URIs"));let i=`_mongodb._tcp.${r.host}`;a.resolveSrv(i,(function(e,o){if(e)return n(e);if(0===o.length)return n(new Error("No addresses found at host"));for(let e=0;e<o.length;e++)if(!f(o[e].name,r.hostname,r.domainLength))return n(new Error("Server record does not share hostname with parent URI"));let i=r.auth?`mongodb://${r.auth}@`:"mongodb://",s=o.map((function(e,t){return 0===t?`${i}${e.name}:${e.port}`:`${e.name}:${e.port}`})).join(",")+"/",c=[];if(r.path){let e=r.path.slice(1);-1!==e.indexOf("?")&&(e=e.slice(0,e.indexOf("?"))),s+=e}(t.ssl||r.search)&&(t.ssl||!r.search||r.search.match("ssl"))||c.push("ssl=true"),r.search&&c.push(r.search.replace("?","")),a.resolveTxt(r.host,(function(e,r){if(e&&"ENODATA"!==e.code&&"ENOTFOUND"!==e.code)return n(e);if(e&&"ENODATA"===e.code&&(r=null),r){if(r.length>1)return n(new l("Multiple text records not allowed"));r=r[0].join("");const e=u.parse(r),t=Object.keys(e);if(t.some(e=>"authSource"!==e&&"replicaSet"!==e))return n(new l("Text record must only set `authSource` or `replicaSet`"));t.length>0&&c.push(r)}c.length&&(s+=`?${c.join("&")}`),p(s,t,n)}))}))}},function(e,t,n){"use strict";e.exports=function(e){const t=n(192),r=e.mongodb.MongoTimeoutError,o=n(100),i=o.debug,s=o.databaseNamespace,a=o.collectionNamespace,c=o.MongoCryptError,u=n(202),l=new Map([[0,"MONGOCRYPT_CTX_ERROR"],[1,"MONGOCRYPT_CTX_NEED_MONGO_COLLINFO"],[2,"MONGOCRYPT_CTX_NEED_MONGO_MARKINGS"],[3,"MONGOCRYPT_CTX_NEED_MONGO_KEYS"],[4,"MONGOCRYPT_CTX_NEED_KMS"],[5,"MONGOCRYPT_CTX_READY"],[6,"MONGOCRYPT_CTX_DONE"]]);return{StateMachine:class{constructor(e){this.options=e||{},this.bson=e.bson}execute(e,t,n){const o=this.bson,s=e._keyVaultNamespace,a=e._keyVaultClient,u=e._metaDataClient,f=e._mongocryptdClient,p=e._mongocryptdManager;switch(i(`[context#${t.id}] ${l.get(t.state)||t.state}`),t.state){case 1:{const r=o.deserialize(t.nextMongoOperation());return void this.fetchCollectionInfo(u,t.ns,r,(r,o)=>{if(r)return n(r,null);o&&t.addMongoOperationResponse(o),t.finishMongoOperation(),this.execute(e,t,n)})}case 2:{const o=t.nextMongoOperation();return void this.markCommand(f,t.ns,o,(i,s)=>{if(i)return i instanceof r&&p&&!p.bypassSpawn?void p.spawn(()=>{this.markCommand(f,t.ns,o,(r,o)=>{if(r)return n(r,null);t.addMongoOperationResponse(o),t.finishMongoOperation(),this.execute(e,t,n)})}):n(i,null);t.addMongoOperationResponse(s),t.finishMongoOperation(),this.execute(e,t,n)})}case 3:{const r=t.nextMongoOperation();return void this.fetchKeys(a,s,r,(r,i)=>{if(r)return n(r,null);i.forEach(e=>{t.addMongoOperationResponse(o.serialize(e))}),t.finishMongoOperation(),this.execute(e,t,n)})}case 4:{const r=[];let o;for(;o=t.nextKMSRequest();)r.push(this.kmsRequest(o));return void Promise.all(r).then(()=>{t.finishKMSRequests(),this.execute(e,t,n)}).catch(e=>{n(e,null)})}case 5:{const e=t.finalize();if(0===t.state){const e=t.status.message||"Finalization error";return void n(new c(e))}return void n(null,o.deserialize(e,this.options))}case 0:{const e=t.status.message;return void n(new c(e))}case 6:return;default:return void n(new c(`Unknown state: ${t.state}`))}}kmsRequest(e){const n=e.endpoint.split(":"),r=null!=n[1]?Number.parseInt(n[1],10):443,o={host:n[0],servername:n[0],port:r},i=e.message;return new Promise((n,r)=>{const s=new u,a=t.connect(o,()=>{a.write(i)});a.once("timeout",()=>{a.removeAllListeners(),a.destroy(),r(new c("KMS request timed out"))}),a.once("error",e=>{a.removeAllListeners(),a.destroy();const t=new c("KMS request failed");t.originalError=e,r(t)}),a.on("data",t=>{for(s.append(t);e.bytesNeeded>0&&s.length;){const t=Math.min(e.bytesNeeded,s.length);e.addResponse(s.slice(0,t)),s.consume(t)}e.bytesNeeded<=0&&a.end(n)})})}fetchCollectionInfo(e,t,n,r){const o=this.bson,i=s(t);e.db(i).listCollections(n).toArray((e,t)=>{if(e)return void r(e,null);const n=t.length>0?o.serialize(t[0]):null;r(null,n)})}markCommand(e,t,n,r){const o=this.bson,i=s(t),a=o.deserialize(n,{promoteLongs:!1,promoteValues:!1});e.db(i).command(a,(e,t)=>{r(e,e?null:o.serialize(t,this.options))})}fetchKeys(e,t,n,r){const o=this.bson,i=s(t),c=a(t);n=o.deserialize(n),e.db(i).collection(c,{readConcern:{level:"majority"}}).find(n).toArray((e,t)=>{e?r(e,null):r(null,t)})}}}}},function(e,t,n){"use strict";e.exports=function(e){const t=n(225)("mongocrypt"),r=n(100).databaseNamespace,o=e.stateMachine.StateMachine,i=n(488).MongocryptdManager,s=e.mongodb.MongoClient,a=e.mongodb.MongoError,c=n(226);return{AutoEncrypter:class{constructor(e,n){this._client=e,this._bson=n.bson||e.topology.bson,this._mongocryptdManager=new i(n.extraOptions),this._mongocryptdClient=new s(this._mongocryptdManager.uri,{useNewUrlParser:!0,useUnifiedTopology:!0,serverSelectionTimeoutMS:1e3}),this._keyVaultNamespace=n.keyVaultNamespace||"admin.datakeys",this._keyVaultClient=n.keyVaultClient||e,this._metaDataClient=n.metadataClient||e,this._bypassEncryption="boolean"==typeof n.bypassAutoEncryption&&n.bypassAutoEncryption;const r={};n.schemaMap&&(r.schemaMap=Buffer.isBuffer(n.schemaMap)?n.schemaMap:this._bson.serialize(n.schemaMap)),n.kmsProviders&&(r.kmsProviders=Buffer.isBuffer(n.kmsProviders)?n.kmsProviders:this._bson.serialize(n.kmsProviders)),n.logger&&(r.logger=n.logger),Object.assign(r,{cryptoCallbacks:c}),this._mongocrypt=new t.MongoCrypt(r),this._contextCounter=0}init(e){const t=(t,n)=>{t&&t.message&&(t.message.match(/timed out after/)||t.message.match(/ENOTFOUND/))?e(new a("Unable to connect to `mongocryptd`, please make sure it is running or in your PATH for auto-spawn")):e(t,n)};if(this._mongocryptdManager.bypassSpawn)return this._mongocryptdClient.connect(t);this._mongocryptdManager.spawn(()=>this._mongocryptdClient.connect(t))}teardown(e,t){this._mongocryptdClient.close(e,t)}encrypt(e,t,n,i){if("string"!=typeof e)throw new TypeError("Parameter `ns` must be a string");if("object"!=typeof t)throw new TypeError("Parameter `cmd` must be an object");if("function"==typeof n&&null==i&&(i=n,n={}),this._bypassEncryption)return void i(void 0,t);const s=this._bson,a=Buffer.isBuffer(t)?t:s.serialize(t,n);let c;try{c=this._mongocrypt.makeEncryptionContext(r(e),a)}catch(e){return void i(e,null)}c.id=this._contextCounter++,c.ns=e,c.document=t,new o(Object.assign({bson:s},n)).execute(this,c,i)}decrypt(e,t,n){"function"==typeof t&&null==n&&(n=t,t={});const r=this._bson,i=Buffer.isBuffer(e)?e:r.serialize(e,t);let s;try{s=this._mongocrypt.makeDecryptionContext(i)}catch(e){return void n(e,null)}s.id=this._contextCounter++,new o(Object.assign({bson:r},t)).execute(this,s,n)}}}}},function(e,t,n){var r=n(136).sep||"/";e.exports=function(e){if("string"!=typeof e||e.length<=7||"file://"!=e.substring(0,7))throw new TypeError("must pass in a file:// URI to convert to a file path");var t=decodeURI(e.substring(7)),n=t.indexOf("/"),o=t.substring(0,n),i=t.substring(n+1);"localhost"==o&&(o="");o&&(o=r+r+o);i=i.replace(/^(.+)\|/,"$1:"),"\\"==r&&(i=i.replace(/\//g,"\\"));/^.+\:/.test(i)||(i=r+i);return o+i}},function(e,t,n){"use strict";const r=n(489).spawn;e.exports={MongocryptdManager:class{constructor(e){(e=e||{}).mongocryptdURI?this.uri=e.mongocryptdURI:this.uri="mongodb://localhost:27020/?serverSelectionTimeoutMS=1000",this.bypassSpawn=!!e.mongocryptdBypassSpawn,this.spawnPath=e.mongocryptdSpawnPath||"",this.spawnArgs=[],Array.isArray(e.mongocryptdSpawnArgs)&&(this.spawnArgs=this.spawnArgs.concat(e.mongocryptdSpawnArgs)),this.spawnArgs.filter(e=>"string"==typeof e).every(e=>e.indexOf("--idleShutdownTimeoutSecs")<0)&&this.spawnArgs.push("--idleShutdownTimeoutSecs",60)}spawn(e){const t=this.spawnPath||"mongocryptd";this._child=r(t,this.spawnArgs,{stdio:"ignore",detached:!0}),this._child.on("error",()=>{}),this._child.unref(),process.nextTick(e)}}}},function(e,t){e.exports=require("child_process")},function(e,t,n){"use strict";e.exports=function(e){const t=n(225)("mongocrypt"),r=n(100),o=r.databaseNamespace,i=r.collectionNamespace,s=r.promiseOrCallback,a=e.stateMachine.StateMachine,c=n(226);return{ClientEncryption:class{constructor(e,n){if(this._client=e,this._bson=n.bson||e.topology.bson,null==n.keyVaultNamespace)throw new TypeError("Missing required option `keyVaultNamespace`");Object.assign(n,{cryptoCallbacks:c}),n.kmsProviders&&!Buffer.isBuffer(n.kmsProviders)&&(n.kmsProviders=this._bson.serialize(n.kmsProviders)),this._keyVaultNamespace=n.keyVaultNamespace,this._keyVaultClient=n.keyVaultClient||e,this._mongoCrypt=new t.MongoCrypt(n)}createDataKey(e,t,n){"function"==typeof t&&(n=t,t={});const r=this._bson;t=function(e,t){if((t=Object.assign({},t)).keyAltNames){if(!Array.isArray(t.keyAltNames))throw new TypeError(`Option "keyAltNames" must be an array of string, but was of type ${typeof t.keyAltNames}.`);const n=[];for(let r=0;r<t.keyAltNames.length;r+=1){const o=t.keyAltNames[r],i=typeof o;if("string"!==i)throw new TypeError(`Option "keyAltNames" must be an array of string, but item at index ${r} was of type ${i} `);n.push(e.serialize({keyAltName:o}))}t.keyAltNames=n}else null==t.keyAltNames&&delete t.keyAltNames;return t}(r,t);const c=r.serialize(Object.assign({provider:e},t.masterKey)),u=this._mongoCrypt.makeDataKeyContext(c),l=new a({bson:r});return s(n,e=>{l.execute(this,u,(t,n)=>{if(t)return void e(t,null);const r=o(this._keyVaultNamespace),s=i(this._keyVaultNamespace);this._keyVaultClient.db(r).collection(s).insertOne(n,{w:"majority"},(t,n)=>{t?e(t,null):e(null,n.insertedId)})})})}encrypt(e,t,n){const r=this._bson,o=r.serialize({v:e}),i=Object.assign({},t);if(t.keyId&&(i.keyId=t.keyId.buffer),t.keyAltName){const e=t.keyAltName;if(t.keyId)throw new TypeError('"options" cannot contain both "keyId" and "keyAltName"');const n=typeof e;if("string"!==n)throw new TypeError(`"options.keyAltName" must be of type string, but was of type ${n}`);i.keyAltName=r.serialize({keyAltName:e})}const c=new a({bson:r}),u=this._mongoCrypt.makeExplicitEncryptionContext(o,i);return s(n,e=>{c.execute(this,u,(t,n)=>{t?e(t,null):e(null,n.v)})})}decrypt(e,t){const n=this._bson,r=n.serialize({v:e}),o=this._mongoCrypt.makeExplicitDecryptionContext(r),i=new a({bson:n});return s(t,e=>{i.execute(this,o,(t,n)=>{t?e(t,null):e(null,n.v)})})}}}}},function(e,t,n){"use strict";const r=n(227),o=n(2).BSON.ObjectID,i=n(2).ReadPreference,s=n(22).Buffer,a=n(89),c=n(5).format,u=n(5),l=n(2).MongoError,f=u.inherits,p=n(18).Duplex,d=n(0).shallowClone,h=n(0).executeLegacyOperation,m=n(5).deprecate;const g=m(()=>{},"GridStore is deprecated, and will be removed in a future version. Please use GridFSBucket instead");var y=function e(t,n,s,a,c){if(g(),!(this instanceof e))return new e(t,n,s,a,c);this.db=t,void 0===c&&(c={}),void 0===a?(a=s,s=void 0):"object"==typeof a&&(c=a,a=s,s=void 0),n&&"ObjectID"===n._bsontype?(this.referenceBy=1,this.fileId=n,this.filename=s):void 0===s?(this.referenceBy=0,this.filename=n,null!=a.indexOf("w")&&(this.fileId=new o)):(this.referenceBy=1,this.fileId=n,this.filename=s),this.mode=null==a?"r":a,this.options=c||{},this.isOpen=!1,this.root=null==this.options.root?e.DEFAULT_ROOT_COLLECTION:this.options.root,this.position=0,this.readPreference=this.options.readPreference||t.options.readPreference||i.primary,this.writeConcern=U(t,this.options),this.internalChunkSize=null==this.options.chunkSize?r.DEFAULT_CHUNK_SIZE:this.options.chunkSize;var u=this.options.promiseLibrary||Promise;this.promiseLibrary=u,Object.defineProperty(this,"chunkSize",{enumerable:!0,get:function(){return this.internalChunkSize},set:function(e){"w"!==this.mode[0]||0!==this.position||null!=this.uploadDate?this.internalChunkSize=this.internalChunkSize:this.internalChunkSize=e}}),Object.defineProperty(this,"md5",{enumerable:!0,get:function(){return this.internalMd5}}),Object.defineProperty(this,"chunkNumber",{enumerable:!0,get:function(){return this.currentChunk&&this.currentChunk.chunkNumber?this.currentChunk.chunkNumber:null}})};y.prototype.open=function(e,t){if("function"==typeof e&&(t=e,e={}),e=e||{},"w"!==this.mode&&"w+"!==this.mode&&"r"!==this.mode)throw l.create({message:"Illegal mode "+this.mode,driver:!0});return h(this.db.s.topology,b,[this,e,t],{skipSessions:!0})};var b=function(e,t,n){var r=U(e.db,e.options);"w"===e.mode||"w+"===e.mode?e.collection().ensureIndex([["filename",1]],r,(function(){var t=e.chunkCollection(),o=d(r);o.unique=!0,t.ensureIndex([["files_id",1],["n",1]],o,(function(){E(e,r,(function(t,r){if(t)return n(t);e.isOpen=!0,n(t,r)}))}))})):E(e,r,(function(t,r){if(t)return n(t);e.isOpen=!0,n(t,r)}))};y.prototype.eof=function(){return this.position===this.length},y.prototype.getc=function(e,t){return"function"==typeof e&&(t=e,e={}),e=e||{},h(this.db.s.topology,v,[this,e,t],{skipSessions:!0})};var v=function(e,t,n){e.eof()?n(null,null):e.currentChunk.eof()?A(e,e.currentChunk.chunkNumber+1,(function(t,r){e.currentChunk=r,e.position=e.position+1,n(t,e.currentChunk.getc())})):(e.position=e.position+1,n(null,e.currentChunk.getc()))};y.prototype.puts=function(e,t,n){"function"==typeof t&&(n=t,t={}),t=t||{};var r=null==e.match(/\n$/)?e+"\n":e;return h(this.db.s.topology,this.write.bind(this),[r,t,n],{skipSessions:!0})},y.prototype.stream=function(){return new z(this)},y.prototype.write=function(e,t,n,r){return"function"==typeof n&&(r=n,n={}),n=n||{},h(this.db.s.topology,L,[this,e,t,n,r],{skipSessions:!0})},y.prototype.destroy=function(){this.writable&&(this.readable=!1,this.writable&&(this.writable=!1,this._q.length=0,this.emit("close")))},y.prototype.writeFile=function(e,t,n){return"function"==typeof t&&(n=t,t={}),t=t||{},h(this.db.s.topology,S,[this,e,t,n],{skipSessions:!0})};var S=function(e,t,n,o){"string"!=typeof t?e.open((function(e,n){if(e)return o(e,n);a.fstat(t,(function(e,i){if(e)return o(e,n);var c=0,u=0,l=function(){var e=s.alloc(n.chunkSize);a.read(t,e,0,e.length,c,(function(e,s,f){if(e)return o(e,n);c+=s,new r(n,{n:u++},n.writeConcern).write(f.slice(0,s),(function(e,r){if(e)return o(e,n);r.save({},(function(e){return e?o(e,n):(n.position=n.position+s,n.currentChunk=r,c>=i.size?void a.close(t,(function(e){if(e)return o(e);n.close((function(e){return o(e||null,n)}))})):process.nextTick(l))}))}))}))};process.nextTick(l)}))})):a.open(t,"r",(function(t,n){if(t)return o(t);e.writeFile(n,o)}))};y.prototype.close=function(e,t){return"function"==typeof e&&(t=e,e={}),e=e||{},h(this.db.s.topology,w,[this,e,t],{skipSessions:!0})};var w=function(e,t,n){"w"===e.mode[0]?(t=Object.assign({},e.writeConcern,t),null!=e.currentChunk&&e.currentChunk.position>0?e.currentChunk.save({},(function(r){if(r&&"function"==typeof n)return n(r);e.collection((function(r,o){if(r&&"function"==typeof n)return n(r);null!=e.uploadDate?I(e,(function(e,r){if(e){if("function"==typeof n)return n(e);throw e}o.save(r,t,(function(e){"function"==typeof n&&n(e,r)}))})):(e.uploadDate=new Date,I(e,(function(e,r){if(e){if("function"==typeof n)return n(e);throw e}o.save(r,t,(function(e){"function"==typeof n&&n(e,r)}))})))}))})):e.collection((function(r,o){if(r&&"function"==typeof n)return n(r);e.uploadDate=new Date,I(e,(function(e,r){if(e){if("function"==typeof n)return n(e);throw e}o.save(r,t,(function(e){"function"==typeof n&&n(e,r)}))}))}))):"r"===e.mode[0]?"function"==typeof n&&n(null,null):"function"==typeof n&&n(l.create({message:c("Illegal mode %s",e.mode),driver:!0}))};y.prototype.chunkCollection=function(e){return"function"==typeof e?this.db.collection(this.root+".chunks",e):this.db.collection(this.root+".chunks")},y.prototype.unlink=function(e,t){return"function"==typeof e&&(t=e,e={}),e=e||{},h(this.db.s.topology,_,[this,e,t],{skipSessions:!0})};var _=function(e,t,n){M(e,(function(t){if(null!==t)return t.message="at deleteChunks: "+t.message,n(t);e.collection((function(t,r){if(null!==t)return t.message="at collection: "+t.message,n(t);r.remove({_id:e.fileId},e.writeConcern,(function(t){n(t,e)}))}))}))};y.prototype.collection=function(e){return"function"==typeof e&&this.db.collection(this.root+".files",e),this.db.collection(this.root+".files")},y.prototype.readlines=function(e,t,n){var r=Array.prototype.slice.call(arguments,0);return n="function"==typeof r[r.length-1]?r.pop():void 0,e=(e=r.length?r.shift():"\n")||"\n",t=r.length?r.shift():{},h(this.db.s.topology,O,[this,e,t,n],{skipSessions:!0})};var O=function(e,t,n,r){e.read((function(e,n){if(e)return r(e);var o=n.toString().split(t);o=o.length>0?o.splice(0,o.length-1):[];for(var i=0;i<o.length;i++)o[i]=o[i]+t;r(null,o)}))};y.prototype.rewind=function(e,t){return"function"==typeof e&&(t=e,e={}),e=e||{},h(this.db.s.topology,T,[this,e,t],{skipSessions:!0})};var T=function(e,t,n){0!==e.currentChunk.chunkNumber?"w"===e.mode[0]?M(e,(function(t){if(t)return n(t);e.currentChunk=new r(e,{n:0},e.writeConcern),e.position=0,n(null,e)})):e.currentChunk(0,(function(t,r){if(t)return n(t);e.currentChunk=r,e.currentChunk.rewind(),e.position=0,n(null,e)})):(e.currentChunk.rewind(),e.position=0,n(null,e))};y.prototype.read=function(e,t,n,r){var o=Array.prototype.slice.call(arguments,0);return r="function"==typeof o[o.length-1]?o.pop():void 0,e=o.length?o.shift():null,t=o.length?o.shift():null,n=o.length?o.shift():{},h(this.db.s.topology,C,[this,e,t,n,r],{skipSessions:!0})};var C=function(e,t,n,r,o){var i=null==t?e.length-e.position:t,a=null==n?s.alloc(i):n;if(a._index=null!=n&&null!=n._index?n._index:0,e.currentChunk.length()-e.currentChunk.position+a._index>=i){var c=e.currentChunk.readSlice(i-a._index);return c.copy(a,a._index),e.position=e.position+a.length,0===i&&0===a.length?o(l.create({message:"File does not exist",driver:!0}),null):o(null,a)}(c=e.currentChunk.readSlice(e.currentChunk.length()-e.currentChunk.position)).copy(a,a._index),a._index+=c.length,A(e,e.currentChunk.chunkNumber+1,(function(n,r){if(n)return o(n);r.length()>0?(e.currentChunk=r,e.read(t,a,o)):a._index>0?o(null,a):o(l.create({message:"no chunks found for file, possibly corrupt",driver:!0}),null)}))};y.prototype.tell=function(e){var t=this;return"function"==typeof e?e(null,this.position):new t.promiseLibrary((function(e){e(t.position)}))},y.prototype.seek=function(e,t,n,r){var o=Array.prototype.slice.call(arguments,1);return r="function"==typeof o[o.length-1]?o.pop():void 0,t=o.length?o.shift():null,n=o.length?o.shift():{},h(this.db.s.topology,x,[this,e,t,n,r],{skipSessions:!0})};var x=function(e,t,n,r,o){if("r"!==e.mode)return o(l.create({message:"seek is only supported for mode r",driver:!0}));var i=null==n?y.IO_SEEK_SET:n,s=t,a=0;a=i===y.IO_SEEK_CUR?e.position+s:i===y.IO_SEEK_END?e.length+s:s;var c=Math.floor(a/e.chunkSize);A(e,c,(function(t,n){return t?o(t,null):null==n?o(new Error("no chunk found")):(e.currentChunk=n,e.position=a,e.currentChunk.position=e.position%e.chunkSize,void o(t,e))}))},E=function(e,t,n){var i=e.collection(),s=1===e.referenceBy?{_id:e.fileId}:{filename:e.filename};function a(e){a.err||n(a.err=e)}s=null==e.fileId&&null==e.filename?null:s,t.readPreference=e.readPreference,null!=s?i.findOne(s,t,(function(i,s){if(i)return a(i);if(null!=s)e.fileId=s._id,e.filename="r"===e.mode||void 0===e.filename?s.filename:e.filename,e.contentType=s.contentType,e.internalChunkSize=s.chunkSize,e.uploadDate=s.uploadDate,e.aliases=s.aliases,e.length=s.length,e.metadata=s.metadata,e.internalMd5=s.md5;else{if("r"===e.mode){e.length=0;var u="ObjectID"===e.fileId._bsontype?e.fileId.toHexString():e.fileId;return a(l.create({message:c("file with id %s not opened for writing",1===e.referenceBy?u:e.filename),driver:!0}))}e.fileId=null==e.fileId?new o:e.fileId,e.contentType=y.DEFAULT_CONTENT_TYPE,e.internalChunkSize=null==e.internalChunkSize?r.DEFAULT_CHUNK_SIZE:e.internalChunkSize,e.length=0}"r"===e.mode?A(e,0,t,(function(t,r){if(t)return a(t);e.currentChunk=r,e.position=0,n(null,e)})):"w"===e.mode&&s?M(e,t,(function(t){if(t)return a(t);e.currentChunk=new r(e,{n:0},e.writeConcern),e.contentType=null==e.options.content_type?e.contentType:e.options.content_type,e.internalChunkSize=null==e.options.chunk_size?e.internalChunkSize:e.options.chunk_size,e.metadata=null==e.options.metadata?e.metadata:e.options.metadata,e.aliases=null==e.options.aliases?e.aliases:e.options.aliases,e.position=0,n(null,e)})):"w"===e.mode?(e.currentChunk=new r(e,{n:0},e.writeConcern),e.contentType=null==e.options.content_type?e.contentType:e.options.content_type,e.internalChunkSize=null==e.options.chunk_size?e.internalChunkSize:e.options.chunk_size,e.metadata=null==e.options.metadata?e.metadata:e.options.metadata,e.aliases=null==e.options.aliases?e.aliases:e.options.aliases,e.position=0,n(null,e)):"w+"===e.mode&&A(e,k(e),t,(function(t,o){if(t)return a(t);e.currentChunk=null==o?new r(e,{n:0},e.writeConcern):o,e.currentChunk.position=e.currentChunk.data.length(),e.metadata=null==e.options.metadata?e.metadata:e.options.metadata,e.aliases=null==e.options.aliases?e.aliases:e.options.aliases,e.position=e.length,n(null,e)}))})):(e.fileId=null==e.fileId?new o:e.fileId,e.contentType=y.DEFAULT_CONTENT_TYPE,e.internalChunkSize=null==e.internalChunkSize?r.DEFAULT_CHUNK_SIZE:e.internalChunkSize,e.length=0,"w"===e.mode?M(e,t,(function(t){if(t)return a(t);e.currentChunk=new r(e,{n:0},e.writeConcern),e.contentType=null==e.options.content_type?e.contentType:e.options.content_type,e.internalChunkSize=null==e.options.chunk_size?e.internalChunkSize:e.options.chunk_size,e.metadata=null==e.options.metadata?e.metadata:e.options.metadata,e.aliases=null==e.options.aliases?e.aliases:e.options.aliases,e.position=0,n(null,e)})):"w+"===e.mode&&A(e,k(e),t,(function(t,o){if(t)return a(t);e.currentChunk=null==o?new r(e,{n:0},e.writeConcern):o,e.currentChunk.position=e.currentChunk.data.length(),e.metadata=null==e.options.metadata?e.metadata:e.options.metadata,e.aliases=null==e.options.aliases?e.aliases:e.options.aliases,e.position=e.length,n(null,e)})))},N=function(e,t,n,o){"function"==typeof n&&(o=n,n=null);var i="boolean"==typeof n&&n;if("w"!==e.mode)o(l.create({message:c("file with id %s not opened for writing",1===e.referenceBy?e.referenceBy:e.filename),driver:!0}),null);else{if(!(e.currentChunk.position+t.length>=e.chunkSize))return e.position=e.position+t.length,e.currentChunk.write(t),i?e.close((function(t){o(t,e)})):o(null,e);for(var s=e.currentChunk.chunkNumber,a=e.chunkSize-e.currentChunk.position,u=t.slice(0,a),f=t.slice(a),p=[e.currentChunk.write(u)];f.length>=e.chunkSize;){var d=new r(e,{n:s+1},e.writeConcern);u=f.slice(0,e.chunkSize),f=f.slice(e.chunkSize),s+=1,d.write(u),p.push(d)}e.currentChunk=new r(e,{n:s+1},e.writeConcern),f.length>0&&e.currentChunk.write(f),e.position=e.position+t.length;for(var h=p.length,m=0;m<p.length;m++)p[m].save({},(function(t){return t?o(t):(h-=1)<=0?i?e.close((function(t){o(t,e)})):o(null,e):void 0}))}},I=function(e,t){var n={_id:e.fileId,filename:e.filename,contentType:e.contentType,length:e.position?e.position:0,chunkSize:e.chunkSize,uploadDate:e.uploadDate,aliases:e.aliases,metadata:e.metadata},r={filemd5:e.fileId,root:e.root};e.db.command(r,(function(e,r){if(e)return t(e);n.md5=r.md5,t(null,n)}))},A=function(e,t,n,o){"function"==typeof n&&(o=n,n={}),(n=n||e.writeConcern).readPreference=e.readPreference,e.chunkCollection().findOne({files_id:e.fileId,n:t},n,(function(t,n){if(t)return o(t);o(null,new r(e,null==n?{}:n,e.writeConcern))}))},k=function(e){return Math.floor((e.length?e.length-1:0)/e.chunkSize)},M=function(e,t,n){"function"==typeof t&&(n=t,t={}),t=t||e.writeConcern,null!=e.fileId?e.chunkCollection().remove({files_id:e.fileId},t,(function(e){if(e)return n(e,!1);n(null,!0)})):n(null,!0)};y.DEFAULT_ROOT_COLLECTION="fs",y.DEFAULT_CONTENT_TYPE="binary/octet-stream",y.IO_SEEK_SET=0,y.IO_SEEK_CUR=1,y.IO_SEEK_END=2,y.exist=function(e,t,n,r,o){var i=Array.prototype.slice.call(arguments,2);return o="function"==typeof i[i.length-1]?i.pop():void 0,n=i.length?i.shift():null,r=(r=i.length?i.shift():{})||{},h(e.s.topology,R,[e,t,n,r,o],{skipSessions:!0})};var R=function(e,t,n,r,o){var s=r.readPreference||i.PRIMARY,a=null!=n?n:y.DEFAULT_ROOT_COLLECTION;e.collection(a+".files",(function(e,n){if(e)return o(e);var r="string"==typeof t||"[object RegExp]"===Object.prototype.toString.call(t)?{filename:t}:{_id:t};null!=t&&"object"==typeof t&&"[object RegExp]"!==Object.prototype.toString.call(t)&&(r=t),n.findOne(r,{readPreference:s},(function(e,t){if(e)return o(e);o(null,null!=t)}))}))};y.list=function(e,t,n,r){var o=Array.prototype.slice.call(arguments,1);return r="function"==typeof o[o.length-1]?o.pop():void 0,t=o.length?o.shift():null,n=(n=o.length?o.shift():{})||{},h(e.s.topology,j,[e,t,n,r],{skipSessions:!0})};var j=function(e,t,n,r){null!=t&&"object"==typeof t&&(n=t,t=null);var o=n.readPreference||i.primary,s=null!=n.id&&n.id,a=null!=t?t:y.DEFAULT_ROOT_COLLECTION,c=[];e.collection(a+".files",(function(e,t){if(e)return r(e);t.find({},{readPreference:o},(function(e,t){if(e)return r(e);t.each((function(e,t){null!=t?c.push(s?t._id:t.filename):r(e,c)}))}))}))};y.read=function(e,t,n,r,o,i){var s=Array.prototype.slice.call(arguments,2);return i="function"==typeof s[s.length-1]?s.pop():void 0,n=s.length?s.shift():null,r=s.length?s.shift():null,o=(o=s.length?s.shift():null)||{},h(e.s.topology,D,[e,t,n,r,o,i],{skipSessions:!0})};var D=function(e,t,n,r,o,i){new y(e,t,"r",o).open((function(e,t){return e?i(e):r&&r>=t.length?i("offset larger than size of file",null):n&&n>t.length?i("length is larger than the size of the file",null):r&&n&&r+n>t.length?i("offset and length is larger than the size of the file",null):void(null!=r?t.seek(r,(function(e,t){if(e)return i(e);t.read(n,i)})):t.read(n,i))}))};y.readlines=function(e,t,n,r,o){var i=Array.prototype.slice.call(arguments,2);return o="function"==typeof i[i.length-1]?i.pop():void 0,n=i.length?i.shift():null,r=(r=i.length?i.shift():null)||{},h(e.s.topology,P,[e,t,n,r,o],{skipSessions:!0})};var P=function(e,t,n,r,o){var i=null==n?"\n":n;new y(e,t,"r",r).open((function(e,t){if(e)return o(e);t.readlines(i,o)}))};y.unlink=function(e,t,n,r){var o=Array.prototype.slice.call(arguments,2);return r="function"==typeof o[o.length-1]?o.pop():void 0,n=(n=o.length?o.shift():{})||{},h(e.s.topology,B,[this,e,t,n,r],{skipSessions:!0})};var B=function(e,t,n,r,o){var i=U(t,r);if(n.constructor===Array)for(var s=0,a=0;a<n.length;a++)++s,y.unlink(t,n[a],r,(function(){0==--s&&o(null,e)}));else new y(t,n,"w",r).open((function(t,n){if(t)return o(t);M(n,(function(t){if(t)return o(t);n.collection((function(t,r){if(t)return o(t);r.remove({_id:n.fileId},i,(function(t){o(t,e)}))}))}))}))},L=function(e,t,n,r,o){return s.isBuffer(t)?N(e,t,n,o):N(e,s.from(t,"binary"),n,o)},q=function(e){const t=Object.assign(e,e.writeConcern);var n={};return null!=t.w&&(n.w=t.w),!0===t.journal&&(n.j=t.journal),!0===t.j&&(n.j=t.j),!0===t.fsync&&(n.fsync=t.fsync),null!=t.wtimeout&&(n.wtimeout=t.wtimeout),n},U=function(e,t){var n={w:1};if(null!=(t=t||{}).writeConcern||null!=t.w||"boolean"==typeof t.j||"boolean"==typeof t.journal||"boolean"==typeof t.fsync?n=q(t):null!=t.safe&&"object"==typeof t.safe?n=q(t.safe):"boolean"==typeof t.safe?n={w:t.safe?1:0}:null!=e.options.writeConcern||null!=e.options.w||"boolean"==typeof e.options.j||"boolean"==typeof e.options.journal||"boolean"==typeof e.options.fsync?n=q(e.options):!e.safe||null==e.safe.w&&"boolean"!=typeof e.safe.j&&"boolean"!=typeof e.safe.journal&&"boolean"!=typeof e.safe.fsync?"boolean"==typeof e.safe&&(n={w:e.safe?1:0}):n=q(e.safe),n.w<1&&(!0===n.journal||!0===n.j||!0===n.fsync))throw l.create({message:"No acknowledgement using w < 1 cannot be combined with journal:true or fsync:true",driver:!0});return n},z=function(e){p.call(this),this.gs=e,this.endCalled=!1,this.totalBytesToRead=this.gs.length-this.gs.position,this.seekPosition=this.gs.position};f(z,p),z.prototype._pipe=z.prototype.pipe,z.prototype.pipe=function(e){var t=this;return t.gs.isOpen?(t.totalBytesToRead=t.gs.length-t.gs.position,t._pipe.apply(t,[e])):t.gs.open((function(n){if(n)return t.emit("error",n);t.totalBytesToRead=t.gs.length-t.gs.position,t._pipe.apply(t,[e])})),e},z.prototype._read=function(){var e=this,t=function(){e.gs.read(n,(function(t,n){return t&&!e.endCalled?e.emit("error",t):e.endCalled||null==n?e.push(null):(n.length<=e.totalBytesToRead?(e.totalBytesToRead=e.totalBytesToRead-n.length,e.push(n)):n.length>e.totalBytesToRead&&(e.totalBytesToRead=e.totalBytesToRead-n._index,e.push(n.slice(0,n._index))),void(e.totalBytesToRead<=0&&(e.endCalled=!0)))}))},n=e.gs.length<e.gs.chunkSize?e.gs.length-e.seekPosition:e.gs.chunkSize;e.gs.isOpen?t():e.gs.open((function(n){if(e.totalBytesToRead=e.gs.length-e.gs.position,n)return e.emit("error",n);t()}))},z.prototype.destroy=function(){this.pause(),this.endCalled=!0,this.gs.close(),this.emit("end")},z.prototype.write=function(e){var t=this;return t.endCalled?t.emit("error",l.create({message:"attempting to write to stream after end called",driver:!0})):t.gs.isOpen?(t.gs.write(e,(function(){t.emit("drain")})),!0):(t.gs.open((function(){t.gs.isOpen=!0,t.gs.write(e,(function(){process.nextTick((function(){t.emit("drain")}))}))})),!1)},z.prototype.end=function(e,t,n){var r=this,o=Array.prototype.slice.call(arguments,0);n="function"==typeof o[o.length-1]?o.pop():void 0,e=o.length?o.shift():null,t=o.length?o.shift():null,r.endCalled=!0,e&&r.gs.write(e,(function(){r.gs.close((function(){"function"==typeof n&&n(),r.emit("end")}))})),r.gs.close((function(){"function"==typeof n&&n(),r.emit("end")}))},e.exports=y},function(e,t,n){"use strict";var r=n(8).EventEmitter,o=n(493),i=n(494),s=n(0).shallowClone,a=n(0).toError,c=n(5),u=n(0).executeLegacyOperation,l={bucketName:"fs",chunkSizeBytes:261120};function f(e,t){if(r.apply(this),this.setMaxListeners(0),t&&"object"==typeof t){t=s(t);for(var n=Object.keys(l),o=0;o<n.length;++o)t[n[o]]||(t[n[o]]=l[n[o]])}else t=l;this.s={db:e,options:t,_chunksCollection:e.collection(t.bucketName+".chunks"),_filesCollection:e.collection(t.bucketName+".files"),checkedIndexes:!1,calledOpenUploadStream:!1,promiseLibrary:e.s.promiseLibrary||Promise}}function p(e,t,n){e.s._filesCollection.deleteOne({_id:t},(function(r,o){if(r)return n(r);e.s._chunksCollection.deleteMany({files_id:t},(function(e){return e?n(e):o.result.n?void n():n(new Error("FileNotFound: no file with id "+t+" found"))}))}))}function d(e,t,n,r){var o={_id:t},i={$set:{filename:n}};e.s._filesCollection.updateOne(o,i,(function(e,n){return e?r(e):n.result.n?void r():r(a("File with id "+t+" not found"))}))}function h(e,t){e.s._filesCollection.drop((function(n){if(n)return t(n);e.s._chunksCollection.drop((function(e){return e?t(e):t()}))}))}e.exports=f,c.inherits(f,r),f.prototype.openUploadStream=function(e,t){return(t=t?s(t):{}).chunkSizeBytes||(t.chunkSizeBytes=this.s.options.chunkSizeBytes),new i(this,e,t)},f.prototype.openUploadStreamWithId=function(e,t,n){return(n=n?s(n):{}).chunkSizeBytes||(n.chunkSizeBytes=this.s.options.chunkSizeBytes),n.id=e,new i(this,t,n)},f.prototype.openDownloadStream=function(e,t){var n={_id:e};return t={start:t&&t.start,end:t&&t.end},new o(this.s._chunksCollection,this.s._filesCollection,this.s.options.readPreference,n,t)},f.prototype.delete=function(e,t){return u(this.s.db.s.topology,p,[this,e,t],{skipSessions:!0})},f.prototype.find=function(e,t){e=e||{},t=t||{};var n=this.s._filesCollection.find(e);return null!=t.batchSize&&n.batchSize(t.batchSize),null!=t.limit&&n.limit(t.limit),null!=t.maxTimeMS&&n.maxTimeMS(t.maxTimeMS),null!=t.noCursorTimeout&&n.addCursorFlag("noCursorTimeout",t.noCursorTimeout),null!=t.skip&&n.skip(t.skip),null!=t.sort&&n.sort(t.sort),n},f.prototype.openDownloadStreamByName=function(e,t){var n={uploadDate:-1},r=null;t&&null!=t.revision&&(t.revision>=0?(n={uploadDate:1},r=t.revision):r=-t.revision-1);var i={filename:e};return t={sort:n,skip:r,start:t&&t.start,end:t&&t.end},new o(this.s._chunksCollection,this.s._filesCollection,this.s.options.readPreference,i,t)},f.prototype.rename=function(e,t,n){return u(this.s.db.s.topology,d,[this,e,t,n],{skipSessions:!0})},f.prototype.drop=function(e){return u(this.s.db.s.topology,h,[this,e],{skipSessions:!0})},f.prototype.getLogger=function(){return this.s.db.s.logger}},function(e,t,n){"use strict";var r=n(18),o=n(5);function i(e,t,n,o,i){this.s={bytesRead:0,chunks:e,cursor:null,expected:0,files:t,filter:o,init:!1,expectedEnd:0,file:null,options:i,readPreference:n},r.Readable.call(this)}function s(e){if(e.s.init)throw new Error("You cannot change options after the stream has enteredflowing mode!")}function a(e,t){e.emit("error",t)}e.exports=i,o.inherits(i,r.Readable),i.prototype._read=function(){var e=this;this.destroyed||function(e,t){if(e.s.file)return t();e.s.init||(!function(e){var t={};e.s.readPreference&&(t.readPreference=e.s.readPreference);e.s.options&&e.s.options.sort&&(t.sort=e.s.options.sort);e.s.options&&e.s.options.skip&&(t.skip=e.s.options.skip);e.s.files.findOne(e.s.filter,t,(function(t,n){if(t)return a(e,t);if(!n){var r=e.s.filter._id?e.s.filter._id.toString():e.s.filter.filename,o=new Error("FileNotFound: file "+r+" was not found");return o.code="ENOENT",a(e,o)}if(n.length<=0)e.push(null);else if(e.destroyed)e.emit("close");else{try{e.s.bytesToSkip=function(e,t,n){if(n&&null!=n.start){if(n.start>t.length)throw new Error("Stream start ("+n.start+") must not be more than the length of the file ("+t.length+")");if(n.start<0)throw new Error("Stream start ("+n.start+") must not be negative");if(null!=n.end&&n.end<n.start)throw new Error("Stream start ("+n.start+") must not be greater than stream end ("+n.end+")");return e.s.bytesRead=Math.floor(n.start/t.chunkSize)*t.chunkSize,e.s.expected=Math.floor(n.start/t.chunkSize),n.start-e.s.bytesRead}}(e,n,e.s.options)}catch(t){return a(e,t)}var i={files_id:n._id};if(e.s.options&&null!=e.s.options.start){var s=Math.floor(e.s.options.start/n.chunkSize);s>0&&(i.n={$gte:s})}e.s.cursor=e.s.chunks.find(i).sort({n:1}),e.s.readPreference&&e.s.cursor.setReadPreference(e.s.readPreference),e.s.expectedEnd=Math.ceil(n.length/n.chunkSize),e.s.file=n;try{e.s.bytesToTrim=function(e,t,n,r){if(r&&null!=r.end){if(r.end>t.length)throw new Error("Stream end ("+r.end+") must not be more than the length of the file ("+t.length+")");if(r.start<0)throw new Error("Stream end ("+r.end+") must not be negative");var o=null!=r.start?Math.floor(r.start/t.chunkSize):0;return n.limit(Math.ceil(r.end/t.chunkSize)-o),e.s.expectedEnd=Math.ceil(r.end/t.chunkSize),Math.ceil(r.end/t.chunkSize)*t.chunkSize-r.end}}(e,n,e.s.cursor,e.s.options)}catch(t){return a(e,t)}e.emit("file",n)}}))}(e),e.s.init=!0);e.once("file",(function(){t()}))}(e,(function(){!function(e){if(e.destroyed)return;e.s.cursor.next((function(t,n){if(e.destroyed)return;if(t)return a(e,t);if(!n)return e.push(null),void process.nextTick(()=>{e.s.cursor.close((function(t){t?a(e,t):e.emit("close")}))});var r=e.s.file.length-e.s.bytesRead,o=e.s.expected++,i=Math.min(e.s.file.chunkSize,r);if(n.n>o){var s="ChunkIsMissing: Got unexpected n: "+n.n+", expected: "+o;return a(e,new Error(s))}if(n.n<o)return s="ExtraChunk: Got unexpected n: "+n.n+", expected: "+o,a(e,new Error(s));var c=Buffer.isBuffer(n.data)?n.data:n.data.buffer;if(c.length!==i)return r<=0?(s="ExtraChunk: Got unexpected n: "+n.n,a(e,new Error(s))):(s="ChunkIsWrongSize: Got unexpected length: "+c.length+", expected: "+i,a(e,new Error(s)));if(e.s.bytesRead+=c.length,0===c.length)return e.push(null);var u=null,l=null;null!=e.s.bytesToSkip&&(u=e.s.bytesToSkip,e.s.bytesToSkip=0);const f=o===e.s.expectedEnd-1,p=e.s.options.end-e.s.bytesToSkip;f&&null!=e.s.bytesToTrim?l=e.s.file.chunkSize-e.s.bytesToTrim:e.s.options.end&&p<n.data.length()&&(l=p),null==u&&null==l||(c=c.slice(u||0,l||c.length)),e.push(c)}))}(e)}))},i.prototype.start=function(e){return s(this),this.s.options.start=e,this},i.prototype.end=function(e){return s(this),this.s.options.end=e,this},i.prototype.abort=function(e){var t=this;this.push(null),this.destroyed=!0,this.s.cursor?this.s.cursor.close((function(n){t.emit("close"),e&&e(n)})):(this.s.init||t.emit("close"),e&&e())}},function(e,t,n){"use strict";var r=n(2),o=n(20),i=n(18),s=n(5),a=n(22).Buffer;function c(e,t,n){if(n=n||{},i.Writable.call(this,n),this.bucket=e,this.chunks=e.s._chunksCollection,this.filename=t,this.files=e.s._filesCollection,this.options=n,this.done=!1,this.id=n.id?n.id:r.BSON.ObjectId(),this.chunkSizeBytes=this.options.chunkSizeBytes,this.bufToStore=a.alloc(this.chunkSizeBytes),this.length=0,this.md5=!n.disableMD5&&o.createHash("md5"),this.n=0,this.pos=0,this.state={streamEnd:!1,outstandingRequests:0,errored:!1,aborted:!1,promiseLibrary:this.bucket.s.promiseLibrary},!this.bucket.s.calledOpenUploadStream){this.bucket.s.calledOpenUploadStream=!0;var s=this;!function(e,t){e.files.findOne({},{_id:1},(function(n,r){return n?t(n):r?t():void e.files.listIndexes().toArray((function(n,r){if(n){if(26===n.code){var o={filename:1,uploadDate:1};return void e.files.createIndex(o,{background:!1},(function(n){if(n)return t(n);f(e,t)}))}return t(n)}var i=!1;if(r.forEach((function(e){2===Object.keys(e.key).length&&1===e.key.filename&&1===e.key.uploadDate&&(i=!0)})),i)f(e,t);else{o={filename:1,uploadDate:1};var s=d(e);s.background=!1,e.files.createIndex(o,s,(function(n){if(n)return t(n);f(e,t)}))}}))}))}(this,(function(){s.bucket.s.checkedIndexes=!0,s.bucket.emit("index")}))}}function u(e,t,n){if(!e.state.errored){if(e.state.errored=!0,n)return n(t);e.emit("error",t)}}function l(e,t,n){return{_id:r.BSON.ObjectId(),files_id:e,n:t,data:n}}function f(e,t){e.chunks.listIndexes().toArray((function(n,r){if(n){if(26===n.code){var o={files_id:1,n:1};return void e.chunks.createIndex(o,{background:!1,unique:!0},(function(e){if(e)return t(e);t()}))}return t(n)}var i=!1;if(r.forEach((function(e){e.key&&(2===Object.keys(e.key).length&&1===e.key.files_id&&1===e.key.n&&(i=!0))})),i)t();else{o={files_id:1,n:1};var s=d(e);s.background=!1,s.unique=!0,e.chunks.createIndex(o,s,(function(e){if(e)return t(e);t()}))}}))}function p(e,t){if(e.done)return!0;if(e.state.streamEnd&&0===e.state.outstandingRequests&&!e.state.errored){e.done=!0;var n=function(e,t,n,r,o,i,s,a){var c={_id:e,length:t,chunkSize:n,uploadDate:new Date,filename:o};r&&(c.md5=r);i&&(c.contentType=i);s&&(c.aliases=s);a&&(c.metadata=a);return c}(e.id,e.length,e.chunkSizeBytes,e.md5&&e.md5.digest("hex"),e.filename,e.options.contentType,e.options.aliases,e.options.metadata);return!g(e,t)&&(e.files.insertOne(n,d(e),(function(r){if(r)return u(e,r,t);e.emit("finish",n),e.emit("close")})),!0)}return!1}function d(e){var t={};return e.options.writeConcern&&(t.w=e.options.writeConcern.w,t.wtimeout=e.options.writeConcern.wtimeout,t.j=e.options.writeConcern.j),t}function h(e,t){return e.bucket.s.checkedIndexes?t(!1):(e.bucket.once("index",(function(){t(!0)})),!0)}function m(e,t){if(0===e.pos)return p(e,t);++e.state.outstandingRequests;var n=a.alloc(e.pos);e.bufToStore.copy(n,0,0,e.pos),e.md5&&e.md5.update(n);var r=l(e.id,e.n,n);if(g(e,t))return!1;e.chunks.insertOne(r,d(e),(function(t){if(t)return u(e,t);--e.state.outstandingRequests,p(e)}))}function g(e,t){return!!e.state.aborted&&("function"==typeof t&&t(new Error("this stream has been aborted")),!0)}e.exports=c,s.inherits(c,i.Writable),c.prototype.write=function(e,t,n){var r=this;return h(this,(function(){return function(e,t,n,r){if(g(e,r))return!1;var o=a.isBuffer(t)?t:a.from(t,n);if(e.length+=o.length,e.pos+o.length<e.chunkSizeBytes)return o.copy(e.bufToStore,e.pos),e.pos+=o.length,r&&r(),!0;var i=o.length,s=e.chunkSizeBytes-e.pos,c=Math.min(s,o.length),f=0;for(;i>0;){var h=o.length-i;if(o.copy(e.bufToStore,e.pos,h,h+c),e.pos+=c,0===(s-=c)){e.md5&&e.md5.update(e.bufToStore);var m=l(e.id,e.n,a.from(e.bufToStore));if(++e.state.outstandingRequests,++f,g(e,r))return!1;e.chunks.insertOne(m,d(e),(function(t){if(t)return u(e,t);--e.state.outstandingRequests,--f||(e.emit("drain",m),r&&r(),p(e))})),s=e.chunkSizeBytes,e.pos=0,++e.n}i-=c,c=Math.min(s,i)}return!1}(r,e,t,n)}))},c.prototype.abort=function(e){if(this.state.streamEnd){var t=new Error("Cannot abort a stream that has already completed");return"function"==typeof e?e(t):this.state.promiseLibrary.reject(t)}if(this.state.aborted)return t=new Error("Cannot call abort() on a stream twice"),"function"==typeof e?e(t):this.state.promiseLibrary.reject(t);this.state.aborted=!0,this.chunks.deleteMany({files_id:this.id},(function(t){"function"==typeof e&&e(t)}))},c.prototype.end=function(e,t,n){var r=this;"function"==typeof e?(n=e,e=null,t=null):"function"==typeof t&&(n=t,t=null),g(this,n)||(this.state.streamEnd=!0,n&&this.once("finish",(function(e){n(null,e)})),e?this.write(e,t,(function(){m(r)})):h(this,(function(){m(r)})))}},function(e,t,n){const r=n(42).ObjectId;e.exports=function(e,t,n,o,i){const s=o.pureName,a=n.__getDatabase(),c=new t.Writable({objectMode:!0});return c.buffer=[],c.wasHeader=!1,c.addRow=e=>{!c.wasHeader&&(c.wasHeader=!0,e.__isStreamHeader)||(i.createStringId&&(e={_id:(new r).toString(),...e}),c.buffer.push(e))},c.checkStructure=async()=>{i.dropIfExists&&(console.log(`Dropping collection ${s}`),await a.collection(s).drop()),i.truncate&&(console.log(`Truncating collection ${s}`),await a.collection(s).deleteMany({}))},c.send=async()=>{const e=c.buffer;c.buffer=[],await a.collection(s).insertMany(e)},c.sendIfFull=async()=>{c.buffer.length>100&&await c.send()},c._write=async(e,t,n)=>{c.addRow(e),await c.sendIfFull(),n()},c._final=async e=>{await c.send(),e()},c}}]);
|