@mongodb-js/compass-web 0.30.4 → 0.31.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/dist/10.1f1a54d3a40efd8c2017.mjs +2 -0
  2. package/dist/17.362fcb811ee2ff871d32.mjs +2 -0
  3. package/dist/{305.mjs → 273.f8171afff21603205990.mjs} +2 -2
  4. package/dist/276.30ea2a26f486be6e78b1.mjs +1 -0
  5. package/dist/414.1038db81de0771ae4f6c.mjs +371 -0
  6. package/dist/{737.mjs.LICENSE.txt → 414.1038db81de0771ae4f6c.mjs.LICENSE.txt} +10 -0
  7. package/dist/423.45723618046344488182.mjs +2 -0
  8. package/dist/{427.mjs → 427.ea0869d385dd7ebc1ee3.mjs} +1 -1
  9. package/dist/752.be311c1a6bd153169544.mjs +2 -0
  10. package/dist/887.a7a72716c079e9aa117e.mjs +2 -0
  11. package/dist/assets-manifest.json +13 -0
  12. package/dist/compass-web.d.ts +35 -12
  13. package/dist/compass-web.mjs +22 -22
  14. package/dist/{index-bde52cb3.mjs → index-bde52cb3.0f5ab0c9a2dfc578bd9d.mjs} +1 -1
  15. package/dist/tsdoc-metadata.json +1 -1
  16. package/package.json +45 -42
  17. package/dist/120.mjs +0 -2
  18. package/dist/680f69f3c2e6b90c1812.png +0 -0
  19. package/dist/737.mjs +0 -352
  20. package/dist/752.mjs +0 -2
  21. package/dist/790.mjs +0 -2
  22. package/dist/7ea3a6d428136b87ab95.png +0 -0
  23. package/dist/858.mjs +0 -2
  24. package/dist/955.mjs +0 -2
  25. package/dist/a4e0eb7ad904a4858361.svg +0 -156
  26. /package/dist/{858.mjs.LICENSE.txt → 10.1f1a54d3a40efd8c2017.mjs.LICENSE.txt} +0 -0
  27. /package/dist/{790.mjs.LICENSE.txt → 17.362fcb811ee2ff871d32.mjs.LICENSE.txt} +0 -0
  28. /package/dist/{305.mjs.LICENSE.txt → 273.f8171afff21603205990.mjs.LICENSE.txt} +0 -0
  29. /package/dist/{955.mjs.LICENSE.txt → 423.45723618046344488182.mjs.LICENSE.txt} +0 -0
  30. /package/dist/{427.mjs.LICENSE.txt → 427.ea0869d385dd7ebc1ee3.mjs.LICENSE.txt} +0 -0
  31. /package/dist/{752.mjs.LICENSE.txt → 752.be311c1a6bd153169544.mjs.LICENSE.txt} +0 -0
  32. /package/dist/{120.mjs.LICENSE.txt → 887.a7a72716c079e9aa117e.mjs.LICENSE.txt} +0 -0
package/dist/955.mjs DELETED
@@ -1,2 +0,0 @@
1
- /*! For license information please see 955.mjs.LICENSE.txt */
2
- export const __webpack_esm_id__=955;export const __webpack_esm_ids__=[955];export const __webpack_esm_modules__={145:(e,t,r)=>{var n=r(67787).Buffer,o=r(65994).e;Object.defineProperty(t,"__esModule",{value:!0}),t.kDispose=t.randomBytes=t.COSMOS_DB_MSG=t.DOCUMENT_DB_MSG=t.COSMOS_DB_CHECK=t.DOCUMENT_DB_CHECK=t.MONGODB_WARNING_CODE=t.DEFAULT_PK_FACTORY=t.HostAddress=t.BufferPool=t.List=t.MongoDBCollectionNamespace=t.MongoDBNamespace=t.ByteUtils=void 0,t.isUint8Array=function(e){return null!=e&&"object"==typeof e&&Symbol.toStringTag in e&&"Uint8Array"===e[Symbol.toStringTag]},t.hostMatchesWildcards=function(e,t){for(const r of t)if(e===r||r.startsWith("*.")&&e?.endsWith(r.substring(2,r.length))||r.startsWith("*/")&&e?.endsWith(r.substring(2,r.length)))return!0;return!1},t.normalizeHintField=function(e){let t;if("string"==typeof e)t=e;else if(Array.isArray(e))t={},e.forEach((e=>{t[e]=1}));else if(null!=e&&"object"==typeof e){t={};for(const r in e)t[r]=e[r]}return t},t.isObject=C,t.mergeOptions=function(e,t){return{...e,...t}},t.filterOptions=function(e,t){const r={};for(const n in e)t.includes(n)&&(r[n]=e[n]);return r},t.applyRetryableWrites=function(e,t){return t&&t.s.options?.retryWrites&&(e.retryWrites=!0),e},t.isPromiseLike=function(e){return null!=e&&"object"==typeof e&&"then"in e&&"function"==typeof e.then},t.decorateWithCollation=function(e,t,r){const n=M(t).capabilities;if(r.collation&&"object"==typeof r.collation){if(!n||!n.commandsTakeCollation)throw new f.MongoCompatibilityError("Current topology does not support collation");e.collation=r.collation}},t.decorateWithReadConcern=function(e,t,r){if(r&&r.session&&r.session.inTransaction())return;const n=Object.assign({},e.readConcern||{});t.s.readConcern&&Object.assign(n,t.s.readConcern),Object.keys(n).length>0&&Object.assign(e,{readConcern:n})},t.getTopology=M,t.ns=function(e){return T.fromString(e)},t.makeCounter=function*(e=0){let t=e;for(;;){const e=t;t+=1,yield e}},t.uuidV4=function(){const e=i.randomBytes(16);return e[6]=15&e[6]|64,e[8]=63&e[8]|128,e},t.maxWireVersion=function(e){if(e){if(e.loadBalanced||e.serverApi?.version)return p.MAX_SUPPORTED_WIRE_VERSION;if(e.hello)return e.hello.maxWireVersion;if("lastHello"in e&&"function"==typeof e.lastHello){const t=e.lastHello();if(t)return t.maxWireVersion}if(e.description&&"maxWireVersion"in e.description&&null!=e.description.maxWireVersion)return e.description.maxWireVersion}return 0},t.arrayStrictEqual=function(e,t){return!(!Array.isArray(e)||!Array.isArray(t))&&(e.length===t.length&&e.every(((e,r)=>e===t[r])))},t.errorStrictEqual=function(e,t){return e===t||(e&&t?!(null==e&&null!=t||null!=e&&null==t)&&(e.constructor.name===t.constructor.name&&e.message===t.message):e===t)},t.makeStateMachine=function(e){return function(t,r){const n=e[t.s.state];if(n&&n.indexOf(r)<0)throw new f.MongoRuntimeError(`illegal state transition from [${t.s.state}] => [${r}], allowed: [${n}]`);t.emit("stateChanged",t.s.state,r),t.s.state=r}},t.now=v,t.calculateDurationInMs=function(e){if("number"!=typeof e)return-1;const t=v()-e;return t<0?0:t},t.hasAtomicOperators=function e(t,r){if(Array.isArray(t)){for(const r of t)if(e(r))return!0;return!1}const n=Object.keys(t);if(r?.ignoreUndefined){let e=!0;for(const r of n)if(void 0!==t[r]){e=!1;break}if(e)throw new f.MongoInvalidArgumentError("Update operations require that all atomic operators have defined values, but none were provided.")}return n.length>0&&"$"===n[0][0]},t.resolveTimeoutOptions=function(e,t){const{socketTimeoutMS:r,serverSelectionTimeoutMS:n,waitQueueTimeoutMS:o,timeoutMS:i}=e.s.options;return{socketTimeoutMS:r,serverSelectionTimeoutMS:n,waitQueueTimeoutMS:o,timeoutMS:i,...t}},t.resolveOptions=function(e,t){const r=Object.assign({},t,(0,h.resolveBSONOptions)(t,e)),n=t?.timeoutMS??e?.timeoutMS,o=t?.session;if(!o?.inTransaction()){const o=g.ReadConcern.fromOptions(t)??e?.readConcern;o&&(r.readConcern=o);let i=O.WriteConcern.fromOptions(t)??e?.writeConcern;i&&(null!=n&&(i=O.WriteConcern.fromOptions({writeConcern:{...i,wtimeout:void 0,wtimeoutMS:void 0}})),r.writeConcern=i)}r.timeoutMS=n;const i=E.ReadPreference.fromOptions(t)??e?.readPreference;if(i&&(r.readPreference=i),o?.explicit&&null!=o?.timeoutContext&&null!=t?.timeoutMS)throw new f.MongoInvalidArgumentError("An operation cannot be given a timeoutMS setting when inside a withTransaction call that has a timeoutMS setting");return r},t.isSuperset=b,t.isHello=function(e){return!(!e[m.LEGACY_HELLO_COMMAND]&&!e.hello)},t.setDifference=function(e,t){const r=new Set(e);for(const e of t)r.delete(e);return r},t.isRecord=function(e,t=void 0){if(!C(e))return!1;const r=e.constructor;if(r&&r.prototype){if(!C(r.prototype))return!1;if(!_(r.prototype,"isPrototypeOf"))return!1}return!t||b(Object.keys(e),t)},t.emitWarning=N,t.emitWarningOnce=function(e){if(!I.has(e))return I.add(e),N(e)},t.enumToString=function(e){return Object.values(e).join(", ")},t.supportsRetryableWrites=function(e){return!!e&&(!!e.loadBalanced||null!=e.description.logicalSessionTimeoutMinutes&&e.description.type!==S.ServerType.Standalone)},t.shuffle=function(e,t=0){const r=Array.from(e);if(t>r.length)throw new f.MongoRuntimeError("Limit must be less than the number of items");let n=r.length;const o=t%r.length==0?1:r.length-t;for(;n>o;){const e=Math.floor(Math.random()*n);n-=1;const t=r[n];r[n]=r[e],r[e]=t}return t%r.length==0?r:r.slice(o)},t.commandSupportsReadConcern=function(e){return!!(e.aggregate||e.count||e.distinct||e.find||e.geoNear)},t.compareObjectId=function(e,r){return null==e&&null==r?0:null==e?-1:null==r?1:t.ByteUtils.compare(e.id,r.id)},t.parseInteger=P,t.parseUnsignedInteger=function(e){const t=P(e);return null!=t&&t>=0?t:null},t.checkParentDomainMatch=function(e,t){const r=e.endsWith(".")?e.slice(0,e.length-1):e,n=t.endsWith(".")?t.slice(0,t.length-1):t,o=/^.*?\./,i=n.split(".").length<3,s=`.${r.replace(o,"")}`;let a=i?n:`.${n.replace(o,"")}`;if(a.startsWith(".")||(a="."+a),i&&r.split(".").length<=n.split(".").length)throw new f.MongoAPIError("Server record does not have at least one more domain level than parent URI");if(!s.endsWith(a))throw new f.MongoAPIError("Server record does not share hostname with parent URI")},t.get=function(e,t={}){return new Promise(((r,n)=>{let o;const i=a.get(e,t,(e=>{e.setEncoding("utf8");let t="";e.on("data",(e=>t+=e)),e.on("end",(()=>{(0,c.clearTimeout)(o),r({status:e.statusCode,body:t})}))})).on("error",(e=>{(0,c.clearTimeout)(o),n(e)})).end();o=(0,c.setTimeout)((()=>{i.destroy(new f.MongoNetworkTimeoutError("request timed out after 10 seconds"))}),1e4)}))},t.request=async function(e,t={}){return await new Promise(((r,n)=>{const o={method:"GET",timeout:1e4,json:!0,...u.parse(e),...t},i=a.request(o,(e=>{e.setEncoding("utf8");let o="";e.on("data",(e=>{o+=e})),e.once("end",(()=>{if(!1!==t.json)try{const e=JSON.parse(o);r(e)}catch{n(new f.MongoRuntimeError(`Invalid JSON response: "${o}"`))}else r(o)}))}));i.once("timeout",(()=>i.destroy(new f.MongoNetworkTimeoutError(`Network request to ${e} timed out after ${t.timeout} ms`)))),i.once("error",(e=>n(e))),i.end()}))},t.isHostMatch=function(e,t){return!(!t||!e.test(t.toLowerCase()))},t.promiseWithResolvers=x,t.squashError=function(e){},t.once=async function(e,r,n){n?.signal?.throwIfAborted();const{promise:o,resolve:i,reject:s}=x(),a=e=>i(e),c=e=>s(e),u=D(n?.signal,(function(){s(this.reason)}));e.once(r,a).once("error",c);try{return await o}finally{e.off(r,a),e.off("error",c),u?.[t.kDispose]()}},t.maybeAddIdToDocuments=function(e,t,r){return(r.forceServerObjectId??e.s.db.options?.forceServerObjectId)||null==t._id&&(t._id=e.s.pkFactory.createPk()),t},t.fileIsAccessible=async function(e,t){try{return await s.promises.access(e,t),!0}catch{return!1}},t.csotMin=function(e,t){return 0===e?t:0===t?e:Math.min(e,t)},t.noop=function(){},t.decorateDecryptionResult=function e(t,r,o=!0){if(o&&(n.isBuffer(r)&&(r=(0,h.deserialize)(r)),n.isBuffer(t)))throw new f.MongoRuntimeError("Expected result of decryption to be deserialized BSON object");if(t&&"object"==typeof t)for(const n of Object.keys(t)){const o=r[n];o&&"Binary"===o._bsontype&&6===o.sub_type?(t[m.kDecoratedKeys]||Object.defineProperty(t,m.kDecoratedKeys,{value:[],configurable:!0,enumerable:!1,writable:!1}),t[m.kDecoratedKeys].push(n)):e(t[n],o,!1)}},t.addAbortListener=D,t.abortable=async function(e,{signal:r}){if(null==r)return await e;const{promise:n,reject:o}=x(),i=r.aborted?o(r.reason):D(r,(function(){o(this.reason)}));try{return await Promise.race([e,n])}finally{i?.[t.kDispose]()}};const i=r(27348),s=r(36374),a=r(7742),c=r(37668),u=r(9606),l=r(9606),d=r(98437),h=r(75080),p=r(96856),m=r(91869),f=r(17562),g=r(28541),E=r(13700),S=r(89167),O=r(40012);t.ByteUtils={toLocalBufferType:e=>n.isBuffer(e)?e:n.from(e.buffer,e.byteOffset,e.byteLength),equals:(e,r)=>t.ByteUtils.toLocalBufferType(e).equals(r),compare:(e,r)=>t.ByteUtils.toLocalBufferType(e).compare(r),toBase64:e=>t.ByteUtils.toLocalBufferType(e).toString("base64")};const y=e=>Object.prototype.toString.call(e);function C(e){return"[object Object]"===y(e)}function M(e){if("topology"in e&&e.topology)return e.topology;if("client"in e&&e.client.topology)return e.client.topology;throw new f.MongoNotConnectedError("MongoClient must be connected to perform this operation")}class T{constructor(e,t){this.db=e,this.collection=""===t?void 0:t}toString(){return this.collection?`${this.db}.${this.collection}`:this.db}withCollection(e){return new w(this.db,e)}static fromString(e){if("string"!=typeof e||""===e)throw new f.MongoRuntimeError(`Cannot parse namespace from "${e}"`);const[t,...r]=e.split("."),n=r.join(".");return new T(t,""===n?void 0:n)}}t.MongoDBNamespace=T;class w extends T{constructor(e,t){super(e,t),this.collection=t}static fromString(e){return super.fromString(e)}}function v(){const e=o.hrtime();return Math.floor(1e3*e[0]+e[1]/1e6)}function b(e,t){e=Array.isArray(e)?new Set(e):e,t=Array.isArray(t)?new Set(t):t;for(const r of t)if(!e.has(r))return!1;return!0}t.MongoDBCollectionNamespace=w;const _=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);class R{get length(){return this.count}get[Symbol.toStringTag](){return"List"}constructor(){this.count=0,this.head={next:null,prev:null,value:null},this.head.next=this.head,this.head.prev=this.head}toArray(){return Array.from(this)}toString(){return`head <=> ${this.toArray().join(" <=> ")} <=> head`}*[Symbol.iterator](){for(const e of this.nodes())yield e.value}*nodes(){let e=this.head.next;for(;e!==this.head;){const{next:t}=e;yield e,e=t}}push(e){this.count+=1;const t={next:this.head,prev:this.head.prev,value:e};this.head.prev.next=t,this.head.prev=t}pushMany(e){for(const t of e)this.push(t)}unshift(e){this.count+=1;const t={next:this.head.next,prev:this.head,value:e};this.head.next.prev=t,this.head.next=t}remove(e){if(e===this.head||0===this.length)return null;this.count-=1;const t=e.prev,r=e.next;return t.next=r,r.prev=t,e.value}shift(){return this.remove(this.head.next)}pop(){return this.remove(this.head.prev)}prune(e){for(const t of this.nodes())e(t.value)&&this.remove(t)}clear(){this.count=0,this.head.next=this.head,this.head.prev=this.head}first(){return this.head.next.value}last(){return this.head.prev.value}}t.List=R,t.BufferPool=class{constructor(){this.buffers=new R,this.totalByteLength=0}get length(){return this.totalByteLength}append(e){this.buffers.push(e),this.totalByteLength+=e.length}getInt32(){if(this.totalByteLength<4)return null;const e=this.buffers.first();if(null!=e&&e.byteLength>=4)return e.readInt32LE(0);const t=this.read(4),r=t.readInt32LE(0);return this.totalByteLength+=4,this.buffers.unshift(t),r}read(e){if("number"!=typeof e||e<0)throw new f.MongoInvalidArgumentError('Argument "size" must be a non-negative number');if(e>this.totalByteLength)return n.alloc(0);const t=n.allocUnsafe(e);for(let r=0;r<e;){const n=this.buffers.shift();if(null==n)break;const o=e-r,i=Math.min(o,n.byteLength),s=n.subarray(0,i);t.set(s,r),r+=i,this.totalByteLength-=i,i<n.byteLength&&this.buffers.unshift(n.subarray(i))}return t}};class A{constructor(e){this.host=void 0,this.port=void 0,this.socketPath=void 0,this.isIPv6=!1;const t=e.split(" ").join("%20");if(t.endsWith(".sock"))return void(this.socketPath=decodeURIComponent(t));const r=`iLoveJS://${t}`;let n;try{n=new l.URL(r)}catch(e){const r=new f.MongoRuntimeError(`Unable to parse ${t} with URL`);throw r.cause=e,r}const o=n.hostname,i=n.port;let s=decodeURIComponent(o).toLowerCase();if(s.startsWith("[")&&s.endsWith("]")&&(this.isIPv6=!0,s=s.substring(1,o.length-1)),this.host=s.toLowerCase(),this.port="number"==typeof i?i:"string"==typeof i&&""!==i?Number.parseInt(i,10):27017,0===this.port)throw new f.MongoParseError("Invalid port (zero) with hostname");Object.freeze(this)}[Symbol.for("nodejs.util.inspect.custom")](){return this.inspect()}inspect(){return`new HostAddress('${this.toString()}')`}toString(){return"string"==typeof this.host?this.isIPv6?`[${this.host}]:${this.port}`:`${this.host}:${this.port}`:`${this.socketPath}`}static fromString(e){return new A(e)}static fromHostPort(e,t){return e.includes(":")&&(e=`[${e}]`),A.fromString(`${e}:${t}`)}static fromSrvRecord({name:e,port:t}){return A.fromHostPort(e,t)}toHostPort(){return this.socketPath?{host:this.socketPath,port:0}:{host:this.host??"",port:this.port??0}}}function N(e){return o.emitWarning(e,{code:t.MONGODB_WARNING_CODE})}t.HostAddress=A,t.DEFAULT_PK_FACTORY={createPk:()=>new h.ObjectId},t.MONGODB_WARNING_CODE="MONGODB DRIVER";const I=new Set;function P(e){if("number"==typeof e)return Math.trunc(e);const t=Number.parseInt(String(e),10);return Number.isNaN(t)?null:t}function x(){let e,t;return{promise:new Promise((function(r,n){e=r,t=n})),resolve:e,reject:t}}function D(e,r){if(null!=e)return e.addEventListener("abort",r,{once:!0}),{[t.kDispose]:()=>e.removeEventListener("abort",r)}}t.DOCUMENT_DB_CHECK=/(\.docdb\.amazonaws\.com$)|(\.docdb-elastic\.amazonaws\.com$)/,t.COSMOS_DB_CHECK=/\.cosmos\.azure\.com$/,t.DOCUMENT_DB_MSG="You appear to be connected to a DocumentDB cluster. For more information regarding feature compatibility and support please visit https://www.mongodb.com/supportability/documentdb",t.COSMOS_DB_MSG="You appear to be connected to a CosmosDB cluster. For more information regarding feature compatibility and support please visit https://www.mongodb.com/supportability/cosmosdb",t.randomBytes=(0,d.promisify)(i.randomBytes),t.kDispose=Symbol.dispose??Symbol("dispose")},287:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ConnectionPoolClearedEvent=t.ConnectionCheckedInEvent=t.ConnectionCheckedOutEvent=t.ConnectionCheckOutFailedEvent=t.ConnectionCheckOutStartedEvent=t.ConnectionClosedEvent=t.ConnectionReadyEvent=t.ConnectionCreatedEvent=t.ConnectionPoolClosedEvent=t.ConnectionPoolReadyEvent=t.ConnectionPoolCreatedEvent=t.ConnectionPoolMonitoringEvent=void 0;const n=r(91869),o=r(145);class i{constructor(e){this.time=new Date,this.address=e.address}}t.ConnectionPoolMonitoringEvent=i,t.ConnectionPoolCreatedEvent=class extends i{constructor(e){super(e),this.name=n.CONNECTION_POOL_CREATED;const{maxConnecting:t,maxPoolSize:r,minPoolSize:o,maxIdleTimeMS:i,waitQueueTimeoutMS:s}=e.options;this.options={maxConnecting:t,maxPoolSize:r,minPoolSize:o,maxIdleTimeMS:i,waitQueueTimeoutMS:s}}},t.ConnectionPoolReadyEvent=class extends i{constructor(e){super(e),this.name=n.CONNECTION_POOL_READY}},t.ConnectionPoolClosedEvent=class extends i{constructor(e){super(e),this.name=n.CONNECTION_POOL_CLOSED}},t.ConnectionCreatedEvent=class extends i{constructor(e,t){super(e),this.name=n.CONNECTION_CREATED,this.connectionId=t.id}},t.ConnectionReadyEvent=class extends i{constructor(e,t,r){super(e),this.name=n.CONNECTION_READY,this.durationMS=(0,o.now)()-r,this.connectionId=t.id}},t.ConnectionClosedEvent=class extends i{constructor(e,t,r,o){super(e),this.name=n.CONNECTION_CLOSED,this.connectionId=t.id,this.reason=r,this.serviceId=t.serviceId,this.error=o??null}},t.ConnectionCheckOutStartedEvent=class extends i{constructor(e){super(e),this.name=n.CONNECTION_CHECK_OUT_STARTED}},t.ConnectionCheckOutFailedEvent=class extends i{constructor(e,t,r,i){super(e),this.name=n.CONNECTION_CHECK_OUT_FAILED,this.durationMS=(0,o.now)()-r,this.reason=t,this.error=i}},t.ConnectionCheckedOutEvent=class extends i{constructor(e,t,r){super(e),this.name=n.CONNECTION_CHECKED_OUT,this.durationMS=(0,o.now)()-r,this.connectionId=t.id}},t.ConnectionCheckedInEvent=class extends i{constructor(e,t){super(e),this.name=n.CONNECTION_CHECKED_IN,this.connectionId=t.id}},t.ConnectionPoolClearedEvent=class extends i{constructor(e,t={}){super(e),this.name=n.CONNECTION_POOL_CLEARED,this.serviceId=t.serviceId,this.interruptInUseConnections=t.interruptInUseConnections}}},815:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DistinctOperation=void 0;const n=r(75725),o=r(78130),i=r(35394);class s extends o.CommandOperation{constructor(e,t,r,o){super(e,o),this.SERVER_COMMAND_RESPONSE_TYPE=n.MongoDBResponse,this.options=o??{},this.collection=e,this.key=t,this.query=r}get commandName(){return"distinct"}buildCommandDocument(e){const t={distinct:this.collection.collectionName,key:this.key,query:this.query};return void 0!==this.options.comment&&(t.comment=this.options.comment),null!=this.options.hint&&(t.hint=this.options.hint),t}handleOk(e){return this.explain?e.toObject(this.bsonOptions):e.toObject(this.bsonOptions).values}}t.DistinctOperation=s,(0,i.defineAspects)(s,[i.Aspect.READ_OPERATION,i.Aspect.RETRYABLE,i.Aspect.EXPLAINABLE])},1755:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.KillCursorsOperation=void 0;const n=r(75725),o=r(17562),i=r(35394);class s extends i.AbstractOperation{constructor(e,t,r,o){super(o),this.SERVER_COMMAND_RESPONSE_TYPE=n.MongoDBResponse,this.ns=t,this.cursorId=e,this.server=r}get commandName(){return"killCursors"}buildCommand(e,t){const r=this.ns.collection;if(null==r)throw new o.MongoRuntimeError("A collection name must be determined before killCursors");return{killCursors:r,cursors:[this.cursorId]}}buildOptions(e){return{session:this.session,timeoutContext:e}}handleError(e){}}t.KillCursorsOperation=s,(0,i.defineAspects)(s,[i.Aspect.MUST_SELECT_SAME_SERVER])},1759:(e,t,r)=>{var n=r(65994).e;Object.defineProperty(t,"__esModule",{value:!0}),t.ServerCapabilities=t.Topology=void 0;const o=r(6875),i=r(91869),s=r(17562),a=r(93347),c=r(4642),u=r(13700),l=r(7799),d=r(145),h=r(89167),p=r(43135),m=r(5369),f=r(9188),g=r(30588),E=r(3906),S=r(4313),O=r(97194);let y=0;const C=(0,d.makeStateMachine)({[h.STATE_CLOSED]:[h.STATE_CLOSED,h.STATE_CONNECTING],[h.STATE_CONNECTING]:[h.STATE_CONNECTING,h.STATE_CLOSING,h.STATE_CONNECTED,h.STATE_CLOSED],[h.STATE_CONNECTED]:[h.STATE_CONNECTED,h.STATE_CLOSING,h.STATE_CLOSED],[h.STATE_CLOSING]:[h.STATE_CLOSING,h.STATE_CLOSED]});class M extends c.TypedEventEmitter{constructor(e,t,r){super(),this.on("error",d.noop),this.client=e,r=r??{hosts:[d.HostAddress.fromString("localhost:27017")],...Object.fromEntries(o.DEFAULT_OPTIONS.entries())},"string"==typeof t?t=[d.HostAddress.fromString(t)]:Array.isArray(t)||(t=[t]);const n=[];for(const e of t)if("string"==typeof e)n.push(d.HostAddress.fromString(e));else{if(!(e instanceof d.HostAddress))throw new s.MongoRuntimeError(`Topology cannot be constructed from ${JSON.stringify(e)}`);n.push(e)}const i=function(e){return e?.directConnection?h.TopologyType.Single:e?.replicaSet?h.TopologyType.ReplicaSetNoPrimary:e?.loadBalanced?h.TopologyType.LoadBalanced:h.TopologyType.Unknown}(r),a=y++,c=null==r.srvMaxHosts||0===r.srvMaxHosts||r.srvMaxHosts>=n.length?n:(0,d.shuffle)(n,r.srvMaxHosts),u=new Map;for(const e of c)u.set(e.toString(),new f.ServerDescription(e));this.waitQueue=new d.List,this.s={id:a,options:r,seedlist:n,state:h.STATE_CLOSED,description:new O.TopologyDescription(i,u,r.replicaSet,void 0,void 0,void 0,r),serverSelectionTimeoutMS:r.serverSelectionTimeoutMS,heartbeatFrequencyMS:r.heartbeatFrequencyMS,minHeartbeatFrequencyMS:r.minHeartbeatFrequencyMS,servers:new Map,credentials:r?.credentials,clusterTime:void 0,detectShardedTopology:e=>this.detectShardedTopology(e),detectSrvRecords:e=>this.detectSrvRecords(e)},this.mongoLogger=e.mongoLogger,this.component="topology",r.srvHost&&!r.loadBalanced&&(this.s.srvPoller=r.srvPoller??new S.SrvPoller({heartbeatFrequencyMS:this.s.heartbeatFrequencyMS,srvHost:r.srvHost,srvMaxHosts:r.srvMaxHosts,srvServiceName:r.srvServiceName}),this.on(M.TOPOLOGY_DESCRIPTION_CHANGED,this.s.detectShardedTopology)),this.connectionLock=void 0}detectShardedTopology(e){const t=e.previousDescription.type,r=e.newDescription.type,n=t!==h.TopologyType.Sharded&&r===h.TopologyType.Sharded,o=this.s.srvPoller?.listeners(S.SrvPoller.SRV_RECORD_DISCOVERY),i=!!o?.includes(this.s.detectSrvRecords);n&&!i&&(this.s.srvPoller?.on(S.SrvPoller.SRV_RECORD_DISCOVERY,this.s.detectSrvRecords),this.s.srvPoller?.start())}detectSrvRecords(e){const t=this.s.description;this.s.description=this.s.description.updateFromSrvPollingEvent(e,this.s.options.srvMaxHosts),this.s.description!==t&&(v(this),this.emitAndLog(M.TOPOLOGY_DESCRIPTION_CHANGED,new p.TopologyDescriptionChangedEvent(this.s.id,t,this.s.description)))}get description(){return this.s.description}get loadBalanced(){return this.s.options.loadBalanced}get serverApi(){return this.s.options.serverApi}get capabilities(){return new R(this.lastHello())}async connect(e){this.connectionLock??=this._connect(e);try{return await this.connectionLock,this}finally{this.connectionLock=void 0}}async _connect(e){if(e=e??{},this.s.state===h.STATE_CONNECTED)return this;C(this,h.STATE_CONNECTING),this.emitAndLog(M.TOPOLOGY_OPENING,new p.TopologyOpeningEvent(this.s.id)),this.emitAndLog(M.TOPOLOGY_DESCRIPTION_CHANGED,new p.TopologyDescriptionChangedEvent(this.s.id,new O.TopologyDescription(h.TopologyType.Unknown),this.s.description));const t=Array.from(this.s.description.servers.values());if(this.s.servers=new Map(t.map((e=>[e.address,w(this,e)]))),this.s.options.loadBalanced)for(const e of t){const t=new f.ServerDescription(e.hostAddress,void 0,{loadBalanced:this.s.options.loadBalanced});this.serverUpdateHandler(t)}const r=this.client.s.options.serverSelectionTimeoutMS,n=e.readPreference??u.ReadPreference.primary,o=l.TimeoutContext.create({timeoutMS:void 0,serverSelectionTimeoutMS:r,waitQueueTimeoutMS:this.client.s.options.waitQueueTimeoutMS}),i={operationName:"handshake",...e,timeoutContext:o};try{const e=await this.selectServer((0,g.readPreferenceServerSelector)(n),i);if(!0!==this.s.options.__skipPingOnConnect&&this.s.credentials){const t=await e.pool.checkOut({timeoutContext:o});return e.pool.checkIn(t),C(this,h.STATE_CONNECTED),this.emit(M.OPEN,this),this.emit(M.CONNECT,this),this}return C(this,h.STATE_CONNECTED),this.emit(M.OPEN,this),this.emit(M.CONNECT,this),this}catch(e){throw this.close(),e}}closeCheckedOutConnections(){for(const e of this.s.servers.values())return e.closeCheckedOutConnections()}close(){if(this.s.state!==h.STATE_CLOSED&&this.s.state!==h.STATE_CLOSING){for(const e of this.s.servers.values())T(e,this);this.s.servers.clear(),C(this,h.STATE_CLOSING),b(this.waitQueue,new s.MongoTopologyClosedError),this.s.srvPoller&&(this.s.srvPoller.stop(),this.s.srvPoller.removeListener(S.SrvPoller.SRV_RECORD_DISCOVERY,this.s.detectSrvRecords)),this.removeListener(M.TOPOLOGY_DESCRIPTION_CHANGED,this.s.detectShardedTopology),C(this,h.STATE_CLOSED),this.emitAndLog(M.TOPOLOGY_CLOSED,new p.TopologyClosedEvent(this.s.id))}}async selectServer(e,t){let r,n;if("function"!=typeof e)if("string"==typeof e)r=(0,g.readPreferenceServerSelector)(u.ReadPreference.fromString(e));else{let n;e instanceof u.ReadPreference?n=e:(u.ReadPreference.translate(t),n=t.readPreference||u.ReadPreference.primary),r=(0,g.readPreferenceServerSelector)(n)}else r=e;t={serverSelectionTimeoutMS:this.s.serverSelectionTimeoutMS,...t},this.client.mongoLogger?.willLog(a.MongoLoggableComponent.SERVER_SELECTION,a.SeverityLevel.DEBUG)&&this.client.mongoLogger?.debug(a.MongoLoggableComponent.SERVER_SELECTION,new E.ServerSelectionStartedEvent(e,this.description,t.operationName)),n=t.timeoutContext?t.timeoutContext.serverSelectionTimeout:l.Timeout.expires(t.serverSelectionTimeoutMS??0);const o=this.description.type===h.TopologyType.Sharded,i=t.session,c=i&&i.transaction;if(o&&c&&c.server)return this.client.mongoLogger?.willLog(a.MongoLoggableComponent.SERVER_SELECTION,a.SeverityLevel.DEBUG)&&this.client.mongoLogger?.debug(a.MongoLoggableComponent.SERVER_SELECTION,new E.ServerSelectionSucceededEvent(e,this.description,c.server.pool.address,t.operationName)),t.timeoutContext?.clearServerSelectionTimeout&&n?.clear(),c.server;const{promise:p,resolve:m,reject:f}=(0,d.promiseWithResolvers)(),S={serverSelector:r,topologyDescription:this.description,mongoLogger:this.client.mongoLogger,transaction:c,resolve:m,reject:f,cancelled:!1,startTime:(0,d.now)(),operationName:t.operationName,waitingLogged:!1,previousServer:t.previousServer},O=(0,d.addAbortListener)(t.signal,(function(){S.cancelled=!0,f(this.reason)}));this.waitQueue.push(S),_(this);try{n?.throwIfExpired();const e=await(n?Promise.race([p,n]):p);return t.timeoutContext?.csotEnabled()&&0!==e.description.minRoundTripTime&&(t.timeoutContext.minRoundTripTime=e.description.minRoundTripTime),e}catch(r){if(l.TimeoutError.is(r)){S.cancelled=!0;const r=new s.MongoServerSelectionError(`Server selection timed out after ${n?.duration} ms`,this.description);if(this.client.mongoLogger?.willLog(a.MongoLoggableComponent.SERVER_SELECTION,a.SeverityLevel.DEBUG)&&this.client.mongoLogger?.debug(a.MongoLoggableComponent.SERVER_SELECTION,new E.ServerSelectionFailedEvent(e,this.description,r,t.operationName)),t.timeoutContext?.csotEnabled())throw new s.MongoOperationTimeoutError("Timed out during server selection",{cause:r});throw r}throw r}finally{O?.[d.kDispose](),t.timeoutContext?.clearServerSelectionTimeout&&n?.clear()}}serverUpdateHandler(e){if(!this.s.description.hasServer(e.address))return;if(function(e,t){const r=e.servers.get(t.address),n=r?.topologyVersion;return(0,f.compareTopologyVersion)(n,t.topologyVersion)>0}(this.s.description,e))return;const t=this.s.description,r=this.s.description.servers.get(e.address);if(!r)return;const n=e.$clusterTime;n&&(0,h._advanceClusterTime)(this,n);const o=r&&r.equals(e);if(this.s.description=this.s.description.update(e),this.s.description.compatibilityError)this.emit(M.ERROR,new s.MongoCompatibilityError(this.s.description.compatibilityError));else{if(!o){const t=this.s.description.servers.get(e.address);t&&this.emit(M.SERVER_DESCRIPTION_CHANGED,new p.ServerDescriptionChangedEvent(this.s.id,e.address,r,t))}v(this,e),this.waitQueue.length>0&&_(this),o||this.emitAndLog(M.TOPOLOGY_DESCRIPTION_CHANGED,new p.TopologyDescriptionChangedEvent(this.s.id,t,this.s.description))}}auth(e,t){"function"==typeof e&&(t=e,e=void 0),"function"==typeof t&&t(void 0,!0)}get clientMetadata(){return this.s.options.metadata}isConnected(){return this.s.state===h.STATE_CONNECTED}isDestroyed(){return this.s.state===h.STATE_CLOSED}lastHello(){const e=Array.from(this.description.servers.values());return 0===e.length?{}:e.filter((e=>e.type!==h.ServerType.Unknown))[0]||{maxWireVersion:this.description.commonWireVersion}}get commonWireVersion(){return this.description.commonWireVersion}get logicalSessionTimeoutMinutes(){return this.description.logicalSessionTimeoutMinutes}get clusterTime(){return this.s.clusterTime}set clusterTime(e){this.s.clusterTime=e}}function T(e,t){for(const t of i.LOCAL_SERVER_EVENTS)e.removeAllListeners(t);e.close(),t.emitAndLog(M.SERVER_CLOSED,new p.ServerClosedEvent(t.s.id,e.description.address));for(const t of i.SERVER_RELAY_EVENTS)e.removeAllListeners(t)}function w(e,t){e.emitAndLog(M.SERVER_OPENING,new p.ServerOpeningEvent(e.s.id,t.address));const r=new m.Server(e,t,e.s.options);for(const t of i.SERVER_RELAY_EVENTS)r.on(t,(r=>e.emit(t,r)));return r.on(m.Server.DESCRIPTION_RECEIVED,(t=>e.serverUpdateHandler(t))),r.connect(),r}function v(e,t){if(t&&e.s.servers.has(t.address)){const r=e.s.servers.get(t.address);if(r)if(r.s.description=t,t.error instanceof s.MongoError&&t.error.hasErrorLabel(s.MongoErrorLabel.ResetPool)){const e=t.error.hasErrorLabel(s.MongoErrorLabel.InterruptInUseConnections);r.pool.clear({interruptInUseConnections:e})}else if(null==t.error){const n=e.s.description.type;(t.isDataBearing||t.type!==h.ServerType.Unknown&&n===h.TopologyType.Single)&&r.pool.ready()}}for(const t of e.description.servers.values())if(!e.s.servers.has(t.address)){const r=w(e,t);e.s.servers.set(t.address,r)}for(const t of e.s.servers){const r=t[0];if(e.description.hasServer(r))continue;if(!e.s.servers.has(r))continue;const n=e.s.servers.get(r);e.s.servers.delete(r),n&&T(n,e)}}function b(e,t){for(;e.length;){const r=e.shift();r&&(r.cancelled||(r.mongoLogger?.willLog(a.MongoLoggableComponent.SERVER_SELECTION,a.SeverityLevel.DEBUG)&&r.mongoLogger?.debug(a.MongoLoggableComponent.SERVER_SELECTION,new E.ServerSelectionFailedEvent(r.serverSelector,r.topologyDescription,t,r.operationName)),r.reject(t)))}}function _(e){if(e.s.state===h.STATE_CLOSED)return void b(e.waitQueue,new s.MongoTopologyClosedError);const t=e.description.type===h.TopologyType.Sharded,r=Array.from(e.description.servers.values()),o=e.waitQueue.length;for(let n=0;n<o;++n){const n=e.waitQueue.shift();if(!n)continue;if(n.cancelled)continue;let o,i;try{const t=n.serverSelector,i=n.previousServer;o=t?t(e.description,r,i?[i]:[]):r}catch(t){e.client.mongoLogger?.willLog(a.MongoLoggableComponent.SERVER_SELECTION,a.SeverityLevel.DEBUG)&&e.client.mongoLogger?.debug(a.MongoLoggableComponent.SERVER_SELECTION,new E.ServerSelectionFailedEvent(n.serverSelector,e.description,t,n.operationName)),n.reject(t);continue}if(0===o.length){n.waitingLogged||(e.client.mongoLogger?.willLog(a.MongoLoggableComponent.SERVER_SELECTION,a.SeverityLevel.INFORMATIONAL)&&e.client.mongoLogger?.info(a.MongoLoggableComponent.SERVER_SELECTION,new E.WaitingForSuitableServerEvent(n.serverSelector,e.description,0!==e.s.serverSelectionTimeoutMS?e.s.serverSelectionTimeoutMS-((0,d.now)()-n.startTime):-1,n.operationName)),n.waitingLogged=!0),e.waitQueue.push(n);continue}if(1===o.length)i=e.s.servers.get(o[0].address);else{const t=(0,d.shuffle)(o,2),r=e.s.servers.get(t[0].address),n=e.s.servers.get(t[1].address);i=r&&n&&r.s.operationCount<n.s.operationCount?r:n}if(!i){const t=new s.MongoServerSelectionError("server selection returned a server description but the server was not found in the topology",e.description);return e.client.mongoLogger?.willLog(a.MongoLoggableComponent.SERVER_SELECTION,a.SeverityLevel.DEBUG)&&e.client.mongoLogger?.debug(a.MongoLoggableComponent.SERVER_SELECTION,new E.ServerSelectionFailedEvent(n.serverSelector,e.description,t,n.operationName)),void n.reject(t)}const c=n.transaction;t&&c&&c.isActive&&i&&c.pinServer(i),e.client.mongoLogger?.willLog(a.MongoLoggableComponent.SERVER_SELECTION,a.SeverityLevel.DEBUG)&&e.client.mongoLogger?.debug(a.MongoLoggableComponent.SERVER_SELECTION,new E.ServerSelectionSucceededEvent(n.serverSelector,n.topologyDescription,i.pool.address,n.operationName)),n.resolve(i)}if(e.waitQueue.length>0)for(const[,t]of e.s.servers)n.nextTick((function(){return t.requestCheck()}))}t.Topology=M,M.SERVER_OPENING=i.SERVER_OPENING,M.SERVER_CLOSED=i.SERVER_CLOSED,M.SERVER_DESCRIPTION_CHANGED=i.SERVER_DESCRIPTION_CHANGED,M.TOPOLOGY_OPENING=i.TOPOLOGY_OPENING,M.TOPOLOGY_CLOSED=i.TOPOLOGY_CLOSED,M.TOPOLOGY_DESCRIPTION_CHANGED=i.TOPOLOGY_DESCRIPTION_CHANGED,M.ERROR=i.ERROR,M.OPEN=i.OPEN,M.CONNECT=i.CONNECT,M.CLOSE=i.CLOSE,M.TIMEOUT=i.TIMEOUT;class R{constructor(e){this.minWireVersion=e.minWireVersion||0,this.maxWireVersion=e.maxWireVersion||0}get hasAggregationCursor(){return this.maxWireVersion>=1}get hasWriteCommands(){return this.maxWireVersion>=2}get hasTextSearch(){return this.minWireVersion>=0}get hasAuthCommands(){return this.maxWireVersion>=1}get hasListCollectionsCommand(){return this.maxWireVersion>=3}get hasListIndexesCommand(){return this.maxWireVersion>=3}get supportsSnapshotReads(){return this.maxWireVersion>=13}get commandsTakeWriteConcern(){return this.maxWireVersion>=5}get commandsTakeCollation(){return this.maxWireVersion>=5}}t.ServerCapabilities=R},3906:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WaitingForSuitableServerEvent=t.ServerSelectionSucceededEvent=t.ServerSelectionFailedEvent=t.ServerSelectionStartedEvent=t.ServerSelectionEvent=void 0;const n=r(145),o=r(91869);class i{constructor(e,t,r){this.selector=e,this.operation=r,this.topologyDescription=t}}t.ServerSelectionEvent=i,t.ServerSelectionStartedEvent=class extends i{constructor(e,t,r){super(e,t,r),this.name=o.SERVER_SELECTION_STARTED,this.message="Server selection started"}},t.ServerSelectionFailedEvent=class extends i{constructor(e,t,r,n){super(e,t,n),this.name=o.SERVER_SELECTION_FAILED,this.message="Server selection failed",this.failure=r}},t.ServerSelectionSucceededEvent=class extends i{constructor(e,t,r,i){super(e,t,i),this.name=o.SERVER_SELECTION_SUCCEEDED,this.message="Server selection succeeded";const{host:s,port:a}=n.HostAddress.fromString(r).toHostPort();this.serverHost=s,this.serverPort=a}},t.WaitingForSuitableServerEvent=class extends i{constructor(e,t,r,n){super(e,t,n),this.name=o.WAITING_FOR_SUITABLE_SERVER,this.message="Waiting for suitable server to become available",this.remainingTimeMS=r}}},4313:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SrvPoller=t.SrvPollingEvent=void 0;const n=r(95136),o=r(37668),i=r(17562),s=r(4642),a=r(145);class c{constructor(e){this.srvRecords=e}hostnames(){return new Set(this.srvRecords.map((e=>a.HostAddress.fromSrvRecord(e).toString())))}}t.SrvPollingEvent=c;class u extends s.TypedEventEmitter{constructor(e){if(super(),this.on("error",a.noop),!e||!e.srvHost)throw new i.MongoRuntimeError("Options for SrvPoller must exist and include srvHost");this.srvHost=e.srvHost,this.srvMaxHosts=e.srvMaxHosts??0,this.srvServiceName=e.srvServiceName??"mongodb",this.rescanSrvIntervalMS=6e4,this.heartbeatFrequencyMS=e.heartbeatFrequencyMS??1e4,this.haMode=!1,this.generation=0,this._timeout=void 0}get srvAddress(){return`_${this.srvServiceName}._tcp.${this.srvHost}`}get intervalMS(){return this.haMode?this.heartbeatFrequencyMS:this.rescanSrvIntervalMS}start(){this._timeout||this.schedule()}stop(){this._timeout&&((0,o.clearTimeout)(this._timeout),this.generation+=1,this._timeout=void 0)}schedule(){this._timeout&&(0,o.clearTimeout)(this._timeout),this._timeout=(0,o.setTimeout)((()=>{this._poll().then(void 0,a.squashError)}),this.intervalMS)}success(e){this.haMode=!1,this.schedule(),this.emit(u.SRV_RECORD_DISCOVERY,new c(e))}failure(){this.haMode=!0,this.schedule()}async _poll(){const e=this.generation;let t;try{t=await n.promises.resolveSrv(this.srvAddress)}catch{return void this.failure()}if(e!==this.generation)return;const r=[];for(const e of t)try{(0,a.checkParentDomainMatch)(e.name,this.srvHost),r.push(e)}catch(e){(0,a.squashError)(e)}r.length?this.success(r):this.failure()}}t.SrvPoller=u,u.SRV_RECORD_DISCOVERY="srvRecordDiscovery"},4642:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CancellationToken=t.TypedEventEmitter=void 0;const n=r(8763),o=r(93347),i=r(145);class s extends n.EventEmitter{emitAndLog(e,...t){this.emit(e,...t),this.component&&this.mongoLogger?.debug(this.component,t[0])}emitAndLogHeartbeat(e,t,r,...n){if(this.emit(e,...n),this.component){const e={topologyId:t,serverConnectionId:r??null,...n[0]};this.mongoLogger?.debug(this.component,e)}}emitAndLogCommand(e,t,r,n,...i){if(e&&this.emit(t,...i),n){const e={databaseName:r,...i[0]};this.mongoLogger?.debug(o.MongoLoggableComponent.COMMAND,e)}}}t.TypedEventEmitter=s,t.CancellationToken=class extends s{constructor(...e){super(...e),this.on("error",i.noop)}}},4752:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DeleteManyOperation=t.DeleteOneOperation=t.DeleteOperation=void 0,t.makeDeleteStatement=l;const n=r(75725),o=r(17562),i=r(78130),s=r(35394);class a extends i.CommandOperation{constructor(e,t,r){super(void 0,r),this.SERVER_COMMAND_RESPONSE_TYPE=n.MongoDBResponse,this.options=r,this.ns=e,this.statements=t}get commandName(){return"delete"}get canRetryWrite(){return!1!==super.canRetryWrite&&this.statements.every((e=>null==e.limit||e.limit>0))}buildCommandDocument(e,t){const r=this.options,n="boolean"!=typeof r.ordered||r.ordered,i={delete:this.ns.collection,deletes:this.statements,ordered:n};if(r.let&&(i.let=r.let),void 0!==r.comment&&(i.comment=r.comment),this.writeConcern&&0===this.writeConcern.w&&this.statements.find((e=>e.hint)))throw new o.MongoCompatibilityError("hint is not supported with unacknowledged writes");return i}}t.DeleteOperation=a;class c extends a{constructor(e,t,r){super(e,[l(t,{...r,limit:1})],r)}handleOk(e){const t=super.handleOk(e);if(this.explain)return t;if(t.code)throw new o.MongoServerError(t);if(t.writeErrors)throw new o.MongoServerError(t.writeErrors[0]);return{acknowledged:0!==this.writeConcern?.w,deletedCount:t.n}}}t.DeleteOneOperation=c;class u extends a{constructor(e,t,r){super(e,[l(t,r)],r)}handleOk(e){const t=super.handleOk(e);if(this.explain)return t;if(t.code)throw new o.MongoServerError(t);if(t.writeErrors)throw new o.MongoServerError(t.writeErrors[0]);return{acknowledged:0!==this.writeConcern?.w,deletedCount:t.n}}}function l(e,t){const r={q:e,limit:"number"==typeof t.limit?t.limit:0};return t.collation&&(r.collation=t.collation),t.hint&&(r.hint=t.hint),r}t.DeleteManyOperation=u,(0,s.defineAspects)(a,[s.Aspect.RETRYABLE,s.Aspect.WRITE_OPERATION]),(0,s.defineAspects)(c,[s.Aspect.RETRYABLE,s.Aspect.WRITE_OPERATION,s.Aspect.EXPLAINABLE,s.Aspect.SKIP_COLLATION]),(0,s.defineAspects)(u,[s.Aspect.WRITE_OPERATION,s.Aspect.EXPLAINABLE,s.Aspect.SKIP_COLLATION])},5136:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DbStatsOperation=void 0;const n=r(75725),o=r(78130),i=r(35394);class s extends o.CommandOperation{constructor(e,t){super(e,t),this.SERVER_COMMAND_RESPONSE_TYPE=n.MongoDBResponse,this.options=t}get commandName(){return"dbStats"}buildCommandDocument(e){const t={dbStats:!0};return null!=this.options.scale&&(t.scale=this.options.scale),t}}t.DbStatsOperation=s,(0,i.defineAspects)(s,[i.Aspect.READ_OPERATION])},5369:(e,t,r)=>{var n=r(65994).e;Object.defineProperty(t,"__esModule",{value:!0}),t.Server=void 0;const o=r(71470),i=r(75755),s=r(76013),a=r(91869),c=r(17562),u=r(4642),l=r(62016),d=r(85759),h=r(145),p=r(40012),m=r(89167),f=r(57590),g=r(9188),E=r(30588),S=(0,h.makeStateMachine)({[m.STATE_CLOSED]:[m.STATE_CLOSED,m.STATE_CONNECTING],[m.STATE_CONNECTING]:[m.STATE_CONNECTING,m.STATE_CLOSING,m.STATE_CONNECTED,m.STATE_CLOSED],[m.STATE_CONNECTED]:[m.STATE_CONNECTED,m.STATE_CLOSING,m.STATE_CLOSED],[m.STATE_CLOSING]:[m.STATE_CLOSING,m.STATE_CLOSED]});class O extends u.TypedEventEmitter{constructor(e,t,r){super(),this.on("error",h.noop),this.serverApi=r.serverApi;const n={hostAddress:t.hostAddress,...r};this.topology=e,this.pool=new i.ConnectionPool(this,n),this.s={description:t,options:r,state:m.STATE_CLOSED,operationCount:0};for(const e of[...a.CMAP_EVENTS,...a.APM_EVENTS])this.pool.on(e,(t=>this.emit(e,t)));if(this.pool.on(o.Connection.CLUSTER_TIME_RECEIVED,(e=>{this.clusterTime=e})),this.loadBalanced)this.monitor=null;else{this.monitor=new f.Monitor(this,this.s.options);for(const e of a.HEARTBEAT_EVENTS)this.monitor.on(e,(t=>this.emit(e,t)));this.monitor.on("resetServer",(e=>y(this,e))),this.monitor.on(O.SERVER_HEARTBEAT_SUCCEEDED,(e=>{this.emit(O.DESCRIPTION_RECEIVED,new g.ServerDescription(this.description.hostAddress,e.reply,{roundTripTime:this.monitor?.roundTripTime,minRoundTripTime:this.monitor?.minRoundTripTime})),this.s.state===m.STATE_CONNECTING&&(S(this,m.STATE_CONNECTED),this.emit(O.CONNECT,this))}))}}get clusterTime(){return this.topology.clusterTime}set clusterTime(e){this.topology.clusterTime=e}get description(){return this.s.description}get name(){return this.s.description.address}get autoEncrypter(){if(this.s.options&&this.s.options.autoEncrypter)return this.s.options.autoEncrypter}get loadBalanced(){return this.topology.description.type===m.TopologyType.LoadBalanced}connect(){this.s.state===m.STATE_CLOSED&&(S(this,m.STATE_CONNECTING),this.loadBalanced?(S(this,m.STATE_CONNECTED),this.emit(O.CONNECT,this)):this.monitor?.connect())}closeCheckedOutConnections(){return this.pool.closeCheckedOutConnections()}close(){this.s.state!==m.STATE_CLOSED&&(S(this,m.STATE_CLOSING),this.loadBalanced||this.monitor?.close(),this.pool.close(),S(this,m.STATE_CLOSED),this.emit("closed"))}requestCheck(){this.loadBalanced||this.monitor?.requestCheck()}async command(e,t){if(this.s.state===m.STATE_CLOSING||this.s.state===m.STATE_CLOSED)throw new c.MongoServerClosedError;const r=e.session;let n=r?.pinnedConnection;if(this.incrementOperationCount(),null==n)try{n=await this.pool.checkOut({timeoutContext:t,signal:e.options.signal})}catch(e){throw this.decrementOperationCount(),e instanceof s.PoolClearedError||this.handleError(e),e}let o=null;const i=()=>{if(this.decrementOperationCount(),r?.pinnedConnection!==n)if(null!=o){const e=()=>{this.pool.checkIn(n)};o.then(e,e)}else this.pool.checkIn(n)};let a;try{a=e.buildCommand(n,r)}catch(e){throw i(),e}const u=e.buildOptions(t),d=e.ns;this.loadBalanced&&function(e,t){return!!t&&(t.inTransaction()||t.transaction.isCommitted&&"commitTransaction"in e||"aggregate"in e||"find"in e||"getMore"in e||"listCollections"in e||"listIndexes"in e||"bulkWrite"in e)}(a,r)&&!r?.pinnedConnection&&r?.pin(n),u.directConnection=this.topology.s.options.directConnection,e instanceof l.AggregateOperation&&e.hasWriteStage&&(0,h.maxWireVersion)(n)<E.MIN_SECONDARY_WRITE_WIRE_VERSION&&delete u.readPreference,this.description.iscryptd&&(u.omitMaxTimeMS=!0);try{try{const t=await n.command(d,a,u,e.SERVER_COMMAND_RESPONSE_TYPE);return(0,p.throwIfWriteConcernError)(t),t}catch(e){throw this.decorateCommandError(n,a,u,e)}}catch(t){if(!(t instanceof c.MongoError&&t.code===c.MONGODB_ERROR_CODES.Reauthenticate))throw t;o=this.pool.reauthenticate(n),o.then(void 0,(e=>{o=null,(0,h.squashError)(e)})),await(0,h.abortable)(o,u),o=null;try{const t=await n.command(d,a,u,e.SERVER_COMMAND_RESPONSE_TYPE);return(0,p.throwIfWriteConcernError)(t),t}catch(e){throw this.decorateCommandError(n,a,u,e)}}finally{i()}}handleError(e,t){if(!(e instanceof c.MongoError))return;if(e.connectionGeneration&&e.connectionGeneration<this.pool.generation)return;const r=e instanceof c.MongoNetworkError&&!(e instanceof c.MongoNetworkTimeoutError),o=e instanceof c.MongoNetworkError&&e.beforeHandshake,i=e.hasErrorLabel(c.MongoErrorLabel.HandshakeError);if(r||o||i)this.loadBalanced?t&&this.pool.clear({serviceId:t.serviceId}):(e.addErrorLabel(c.MongoErrorLabel.ResetPool),y(this,e));else if((0,c.isSDAMUnrecoverableError)(e)&&function(e,t){const r=t.topologyVersion,n=e.description.topologyVersion;return(0,g.compareTopologyVersion)(n,r)<0}(this,e)){const r=(0,h.maxWireVersion)(this)<=7||(0,c.isNodeShuttingDownError)(e);this.loadBalanced&&t&&r&&this.pool.clear({serviceId:t.serviceId}),this.loadBalanced||(r&&e.addErrorLabel(c.MongoErrorLabel.ResetPool),y(this,e),n.nextTick((()=>this.requestCheck())))}}decorateCommandError(e,t,r,n){if("object"!=typeof n||null==n||!("name"in n))throw new c.MongoRuntimeError("An unexpected error type: "+typeof n);if("AbortError"===n.name&&"cause"in n&&n.cause instanceof c.MongoError&&(n=n.cause),!(n instanceof c.MongoError))return n;if(function(e,t){return t.serviceId?t.generation!==e.serviceGenerations.get(t.serviceId.toHexString()):t.generation!==e.generation}(this.pool,e))return n;const o=r?.session;return n instanceof c.MongoNetworkError?(o&&!o.hasEnded&&o.serverSession&&(o.serverSession.isDirty=!0),C(o,t)&&!n.hasErrorLabel(c.MongoErrorLabel.TransientTransactionError)&&n.addErrorLabel(c.MongoErrorLabel.TransientTransactionError),(M(this.topology)||(0,d.isTransactionCommand)(t))&&(0,h.supportsRetryableWrites)(this)&&!C(o,t)&&n.addErrorLabel(c.MongoErrorLabel.RetryableWriteError)):(M(this.topology)||(0,d.isTransactionCommand)(t))&&(0,c.needsRetryableWriteLabel)(n,(0,h.maxWireVersion)(this),this.description.type)&&!C(o,t)&&n.addErrorLabel(c.MongoErrorLabel.RetryableWriteError),o&&o.isPinned&&n.hasErrorLabel(c.MongoErrorLabel.TransientTransactionError)&&o.unpin({force:!0}),this.handleError(n,e),n}decrementOperationCount(){return this.s.operationCount-=1}incrementOperationCount(){return this.s.operationCount+=1}}function y(e,t){e.loadBalanced||(t instanceof c.MongoNetworkError&&!(t instanceof c.MongoNetworkTimeoutError)&&e.monitor?.reset(),e.emit(O.DESCRIPTION_RECEIVED,new g.ServerDescription(e.description.hostAddress,void 0,{error:t})))}function C(e,t){return e&&e.inTransaction()&&!(0,d.isTransactionCommand)(t)}function M(e){return!1!==e.s.options.retryWrites}t.Server=O,O.SERVER_HEARTBEAT_STARTED=a.SERVER_HEARTBEAT_STARTED,O.SERVER_HEARTBEAT_SUCCEEDED=a.SERVER_HEARTBEAT_SUCCEEDED,O.SERVER_HEARTBEAT_FAILED=a.SERVER_HEARTBEAT_FAILED,O.CONNECT=a.CONNECT,O.DESCRIPTION_RECEIVED=a.DESCRIPTION_RECEIVED,O.CLOSED=a.CLOSED,O.ENDED=a.ENDED},5465:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.FindCursor=t.FLAGS=void 0;const n=r(75725),o=r(17562),i=r(36411),s=r(17172),a=r(96357),c=r(50440),u=r(30770),l=r(145),d=r(36649);t.FLAGS=["tailable","oplogReplay","noCursorTimeout","awaitData","exhaust","partial"];class h extends d.ExplainableCursor{constructor(e,t,r={},n={}){super(e,t,n),this.numReturned=0,this.cursorFilter=r,this.findOptions=n,null!=n.sort&&(this.findOptions.sort=(0,u.formatSort)(n.sort))}clone(){const e=(0,l.mergeOptions)({},this.findOptions);return delete e.session,new h(this.client,this.namespace,this.cursorFilter,{...e})}map(e){return super.map(e)}async _initialize(e){const t={...this.findOptions,...this.cursorOptions,session:e,signal:this.signal};if(t.explain)try{(0,i.validateExplainTimeoutOptions)(t,i.Explain.fromOptions(t))}catch{throw new o.MongoAPIError("timeoutMS cannot be used with explain when explain is specified in findOptions")}const r=new c.FindOperation(this.namespace,this.cursorFilter,t),n=await(0,a.executeOperation)(this.client,r,this.timeoutContext);return this.numReturned=n.batchSize,{server:r.server,session:e,response:n}}async getMore(e){const t=this.numReturned;if(t){const r=this.findOptions.limit;if((e=r&&r>0&&t+e>r?r-t:e)<=0){try{await this.close()}catch(e){(0,l.squashError)(e)}return n.CursorResponse.emptyGetMore}}const r=await super.getMore(e);return this.numReturned=this.numReturned+r.batchSize,r}async count(e){if((0,l.emitWarningOnce)("cursor.count is deprecated and will be removed in the next major version, please use `collection.estimatedDocumentCount` or `collection.countDocuments` instead "),"boolean"==typeof e)throw new o.MongoInvalidArgumentError("Invalid first parameter to count");return await(0,a.executeOperation)(this.client,new s.CountOperation(this.namespace,this.cursorFilter,{...this.findOptions,...this.cursorOptions,...e}))}async explain(e,t){const{explain:r,timeout:n}=this.resolveExplainTimeoutOptions(e,t);return(await(0,a.executeOperation)(this.client,new c.FindOperation(this.namespace,this.cursorFilter,{...this.findOptions,...this.cursorOptions,...n,explain:r??!0}))).shift(this.deserializationOptions)}filter(e){return this.throwIfInitialized(),this.cursorFilter=e,this}hint(e){return this.throwIfInitialized(),this.findOptions.hint=e,this}min(e){return this.throwIfInitialized(),this.findOptions.min=e,this}max(e){return this.throwIfInitialized(),this.findOptions.max=e,this}returnKey(e){return this.throwIfInitialized(),this.findOptions.returnKey=e,this}showRecordId(e){return this.throwIfInitialized(),this.findOptions.showRecordId=e,this}addQueryModifier(e,t){if(this.throwIfInitialized(),"$"!==e[0])throw new o.MongoInvalidArgumentError(`${e} is not a valid query modifier`);switch(e.substr(1)){case"comment":this.findOptions.comment=t;break;case"explain":this.findOptions.explain=t;break;case"hint":this.findOptions.hint=t;break;case"max":this.findOptions.max=t;break;case"maxTimeMS":this.findOptions.maxTimeMS=t;break;case"min":this.findOptions.min=t;break;case"orderby":this.findOptions.sort=(0,u.formatSort)(t);break;case"query":this.cursorFilter=t;break;case"returnKey":this.findOptions.returnKey=t;break;case"showDiskLoc":this.findOptions.showRecordId=t;break;default:throw new o.MongoInvalidArgumentError(`Invalid query modifier: ${e}`)}return this}comment(e){return this.throwIfInitialized(),this.findOptions.comment=e,this}maxAwaitTimeMS(e){if(this.throwIfInitialized(),"number"!=typeof e)throw new o.MongoInvalidArgumentError("Argument for maxAwaitTimeMS must be a number");return this.findOptions.maxAwaitTimeMS=e,this}maxTimeMS(e){if(this.throwIfInitialized(),"number"!=typeof e)throw new o.MongoInvalidArgumentError("Argument for maxTimeMS must be a number");return this.findOptions.maxTimeMS=e,this}project(e){return this.throwIfInitialized(),this.findOptions.projection=e,this}sort(e,t){if(this.throwIfInitialized(),this.findOptions.tailable)throw new o.MongoTailableCursorError("Tailable cursor does not support sorting");return this.findOptions.sort=(0,u.formatSort)(e,t),this}allowDiskUse(e=!0){if(this.throwIfInitialized(),!this.findOptions.sort)throw new o.MongoInvalidArgumentError('Option "allowDiskUse" requires a sort specification');return e?(this.findOptions.allowDiskUse=!0,this):(this.findOptions.allowDiskUse=!1,this)}collation(e){return this.throwIfInitialized(),this.findOptions.collation=e,this}limit(e){if(this.throwIfInitialized(),this.findOptions.tailable)throw new o.MongoTailableCursorError("Tailable cursor does not support limit");if("number"!=typeof e)throw new o.MongoInvalidArgumentError('Operation "limit" requires an integer');return this.findOptions.limit=e,this}skip(e){if(this.throwIfInitialized(),this.findOptions.tailable)throw new o.MongoTailableCursorError("Tailable cursor does not support skip");if("number"!=typeof e)throw new o.MongoInvalidArgumentError('Operation "skip" requires an integer');return this.findOptions.skip=e,this}}t.FindCursor=h},6875:(e,t,r)=>{var n=r(65994).e;Object.defineProperty(t,"__esModule",{value:!0}),t.DEFAULT_OPTIONS=t.OPTIONS=void 0,t.resolveSRVRecord=async function(e){if("string"!=typeof e.srvHost)throw new h.MongoAPIError('Option "srvHost" must not be empty');const t=e.srvHost,r=b(t);r.then(void 0,S.squashError);const n=`_${e.srvServiceName}._tcp.${t}`,o=await v(n);if(0===o.length)throw new h.MongoAPIError("No addresses found at host");for(const{name:e}of o)(0,S.checkParentDomainMatch)(e,t);const i=o.map((e=>S.HostAddress.fromString(`${e.name}:${e.port??27017}`)));let u;P(i,e,!0);try{u=await r}catch(e){if("ENODATA"!==e.code&&"ENOTFOUND"!==e.code)throw e;return i}if(u.length>1)throw new h.MongoParseError("Multiple text records not allowed");const l=new s.URLSearchParams(u[0].join(""));if([...l.keys()].some((e=>!y.includes(e))))throw new h.MongoParseError(`Text record may only set any of: ${y.join(", ")}`);if(y.some((e=>""===l.get(e))))throw new h.MongoParseError("Cannot have empty URI params in DNS TXT Record");const d=l.get("authSource")??void 0,p=l.get("replicaSet")??void 0,m=l.get("loadBalanced")??void 0;if(!e.userSpecifiedAuthSource&&d&&e.credentials&&!c.AUTH_MECHS_AUTH_SRC_EXTERNAL.has(e.credentials.mechanism)&&(e.credentials=a.MongoCredentials.merge(e.credentials,{source:d})),!e.userSpecifiedReplicaSet&&p&&(e.replicaSet=p),"true"===m&&(e.loadBalanced=!0),e.replicaSet&&e.srvMaxHosts>0)throw new h.MongoParseError("Cannot combine replicaSet option with srvMaxHosts");return P(i,e,!0),i},t.parseOptions=function(e,r=void 0,o={}){if(null==r||r instanceof p.MongoClient||(o=r,r=void 0),o.useBigInt64&&"boolean"==typeof o.promoteLongs&&!o.promoteLongs)throw new h.MongoAPIError("Must request either bigint or Long for int64 deserialization");if(o.useBigInt64&&"boolean"==typeof o.promoteValues&&!o.promoteValues)throw new h.MongoAPIError("Must request either bigint or Long for int64 deserialization");const s=new i.default(e),{hosts:l,isSRV:f}=s,g=Object.create(null);g.hosts=f?[]:l.map(S.HostAddress.fromString);const E=new I;if("/"!==s.pathname&&""!==s.pathname){const e=decodeURIComponent("/"===s.pathname[0]?s.pathname.slice(1):s.pathname);e&&E.set("dbName",[e])}if(""!==s.username){const e={username:decodeURIComponent(s.username)};"string"==typeof s.password&&(e.password=decodeURIComponent(s.password)),E.set("auth",[e])}for(const e of s.searchParams.keys()){const t=s.searchParams.getAll(e),r=/readPreferenceTags/i.test(e);if(!r&&t.length>1)throw new h.MongoInvalidArgumentError(`URI option "${e}" cannot appear more than once in the connection string`);if(!r&&t.includes(""))throw new h.MongoAPIError(`URI option "${e}" cannot be specified with no value`);E.has(e)||E.set(e,t)}const O=new I(Object.entries(o).filter((([,e])=>null!=e)));if(E.has("serverApi"))throw new h.MongoParseError("URI cannot contain `serverApi`, it can only be passed to the client");const y=E.get("authMechanismProperties");if(y)for(const e of y)if(/(^|,)ALLOWED_HOSTS:/.test(e))throw new h.MongoParseError("Auth mechanism property ALLOWED_HOSTS is not allowed in the connection string.");if(O.has("loadBalanced"))throw new h.MongoParseError("loadBalanced is only a valid option in the URI");const C=new I,M=new Set([...E.keys(),...O.keys()]);for(const e of M){const t=[],r=O.get(e);null!=r&&t.push(r);const n=E.get(e)??[];t.push(...n),C.set(e,t)}if(C.has("tls")||C.has("ssl")){const e=(C.get("tls")||[]).concat(C.get("ssl")||[]).map(_.bind(null,"tls/ssl"));if(1!==new Set(e).size)throw new h.MongoParseError("All values of tls/ssl must be the same.")}!function(e){if(!e)return;const t=(t,r)=>{if(e.has(t)&&e.has(r))throw new h.MongoAPIError(`The '${t}' option cannot be used with the '${r}' option`)};t("tlsInsecure","tlsAllowInvalidCertificates"),t("tlsInsecure","tlsAllowInvalidHostnames")}(C);const T=(0,S.setDifference)(M,Array.from(Object.keys(t.OPTIONS)).map((e=>e.toLowerCase())));if(0!==T.size){const e=T.size>1?"options":"option",t=T.size>1?"are":"is";throw new h.MongoParseError(`${e} ${Array.from(T).join(", ")} ${t} not supported`)}for(const[e,r]of Object.entries(t.OPTIONS)){const n=C.get(e);if(n&&0!==n.length){const{deprecated:t}=r;if(t){const r="string"==typeof t?`: ${t}`:"";(0,S.emitWarning)(`${e} is a deprecated option${r}`)}x(g,e,r,n)}else t.DEFAULT_OPTIONS.has(e)&&x(g,e,r,[t.DEFAULT_OPTIONS.get(e)])}if(g.credentials){const e=g.credentials.mechanism===c.AuthMechanism.MONGODB_GSSAPI,t=g.credentials.mechanism===c.AuthMechanism.MONGODB_X509,r=g.credentials.mechanism===c.AuthMechanism.MONGODB_AWS,n=g.credentials.mechanism===c.AuthMechanism.MONGODB_OIDC;if((e||t)&&C.has("authSource")&&"$external"!==g.credentials.source)throw new h.MongoParseError(`authMechanism ${g.credentials.mechanism} requires an authSource of '$external'`);if(e||t||r||n||!g.dbName||C.has("authSource")||(g.credentials=a.MongoCredentials.merge(g.credentials,{source:g.dbName})),r&&g.credentials.username&&!g.credentials.password)throw new h.MongoMissingCredentialsError(`When using ${g.credentials.mechanism} password must be set when a username is specified`);g.credentials.validate(),""===g.credentials.password&&""===g.credentials.username&&g.credentials.mechanism===c.AuthMechanism.MONGODB_DEFAULT&&0===Object.keys(g.credentials.mechanismProperties).length&&delete g.credentials}if(g.dbName||(g.dbName="test"),P(l,g,f),r&&g.autoEncryption&&(d.Encrypter.checkForMongoCrypt(),g.encrypter=new d.Encrypter(r,e,o),g.autoEncrypter=g.encrypter.autoEncrypter),g.userSpecifiedAuthSource=O.has("authSource")||E.has("authSource"),g.userSpecifiedReplicaSet=O.has("replicaSet")||E.has("replicaSet"),f){if(g.srvHost=l[0],g.directConnection)throw new h.MongoAPIError("SRV URI does not support directConnection");if(g.srvMaxHosts>0&&"string"==typeof g.replicaSet)throw new h.MongoParseError("Cannot use srvMaxHosts option with replicaSet");const e=!O.has("tls")&&!E.has("tls"),t=!O.has("ssl")&&!E.has("ssl");e&&t&&(g.tls=!0)}else if(E.has("srvMaxHosts")||O.has("srvMaxHosts")||E.has("srvServiceName")||O.has("srvServiceName"))throw new h.MongoParseError("Cannot use srvMaxHosts or srvServiceName with a non-srv connection string");if(g.directConnection&&1!==g.hosts.length)throw new h.MongoParseError("directConnection option requires exactly one host");if(!g.proxyHost&&(g.proxyPort||g.proxyUsername||g.proxyPassword))throw new h.MongoParseError("Must specify proxyHost if other proxy options are passed");if(g.proxyUsername&&!g.proxyPassword||!g.proxyUsername&&g.proxyPassword)throw new h.MongoParseError("Can only specify both of proxy username/password or neither");if(["proxyHost","proxyPort","proxyUsername","proxyPassword"].map((e=>E.get(e)??[])).some((e=>e.length>1)))throw new h.MongoParseError("Proxy options cannot be specified multiple times in the connection string");return g.mongoLoggerOptions=m.MongoLogger.resolveOptions({MONGODB_LOG_COMMAND:n.env.MONGODB_LOG_COMMAND,MONGODB_LOG_TOPOLOGY:n.env.MONGODB_LOG_TOPOLOGY,MONGODB_LOG_SERVER_SELECTION:n.env.MONGODB_LOG_SERVER_SELECTION,MONGODB_LOG_CONNECTION:n.env.MONGODB_LOG_CONNECTION,MONGODB_LOG_CLIENT:n.env.MONGODB_LOG_CLIENT,MONGODB_LOG_ALL:n.env.MONGODB_LOG_ALL,MONGODB_LOG_MAX_DOCUMENT_LENGTH:n.env.MONGODB_LOG_MAX_DOCUMENT_LENGTH,MONGODB_LOG_PATH:n.env.MONGODB_LOG_PATH},{mongodbLogPath:g.mongodbLogPath,mongodbLogComponentSeverities:g.mongodbLogComponentSeverities,mongodbLogMaxDocumentLength:g.mongodbLogMaxDocumentLength}),g.additionalDriverInfo=[],g.metadata=(0,u.makeClientMetadata)(g),g.extendedMetadata=(0,u.addContainerMetadata)(g.metadata).then(void 0,S.squashError),g};const o=r(95136),i=r(65031),s=r(9606),a=r(91566),c=r(93065),u=r(56463),l=r(64515),d=r(48758),h=r(17562),p=r(22220),m=r(93347),f=r(28541),g=r(13700),E=r(57590),S=r(145),O=r(40012),y=["authSource","replicaSet","loadBalanced"],C="loadBalanced option only supported with a single host in the URI",M="loadBalanced option not supported with a replicaSet option",T="loadBalanced option not supported when directConnection is provided";function w(e){return async function(t){try{return await o.promises[e](t)}catch(r){if(r.code===o.TIMEOUT)return await o.promises[e](t);throw r}}}const v=w("resolveSrv"),b=w("resolveTxt");function _(e,t){if("boolean"==typeof t)return t;switch(t){case"true":return!0;case"false":return!1;default:throw new h.MongoParseError(`${e} must be either "true" or "false"`)}}function R(e,t){const r=(0,S.parseInteger)(t);if(null!=r)return r;throw new h.MongoParseError(`Expected ${e} to be stringified int value, got: ${t}`)}function A(e,t){const r=R(e,t);if(r<0)throw new h.MongoParseError(`${e} can only be a positive int value, got: ${t}`);return r}function*N(e){if(""===e)return;const t=e.split(",");for(const e of t){const[t,r]=e.split(/:(.*)/);if(null==r)throw new h.MongoParseError("Cannot have undefined values in key value pairs");yield[t,r]}}class I extends Map{constructor(e=[]){super(e.map((([e,t])=>[e.toLowerCase(),t])))}has(e){return super.has(e.toLowerCase())}get(e){return super.get(e.toLowerCase())}set(e,t){return super.set(e.toLowerCase(),t)}delete(e){return super.delete(e.toLowerCase())}}function P(e,t,r){if(t.loadBalanced){if(e.length>1)throw new h.MongoParseError(C);if(t.replicaSet)throw new h.MongoParseError(M);if(t.directConnection)throw new h.MongoParseError(T);if(r&&t.srvMaxHosts>0)throw new h.MongoParseError("Cannot limit srv hosts with loadBalanced enabled")}}function x(e,t,r,n){const{target:o,type:i,transform:s}=r,a=o??t;switch(i){case"boolean":e[a]=_(a,n[0]);break;case"int":e[a]=R(a,n[0]);break;case"uint":e[a]=A(a,n[0]);break;case"string":if(null==n[0])break;e[a]=String(n[0]);break;case"record":if(!(0,S.isRecord)(n[0]))throw new h.MongoParseError(`${a} must be an object`);e[a]=n[0];break;case"any":e[a]=n[0];break;default:{if(!s)throw new h.MongoParseError("Descriptors missing a type must define a transform");const t=s({name:a,options:e,values:n});e[a]=t;break}}}t.OPTIONS={appName:{type:"string"},auth:{target:"credentials",transform({name:e,options:t,values:[r]}){if(!(0,S.isRecord)(r,["username","password"]))throw new h.MongoParseError(`${e} must be an object with 'username' and 'password' properties`);return a.MongoCredentials.merge(t.credentials,{username:r.username,password:r.password})}},authMechanism:{target:"credentials",transform({options:e,values:[t]}){const r=Object.values(c.AuthMechanism),[n]=r.filter((e=>e.match(RegExp(String.raw`\b${t}\b`,"i"))));if(!n)throw new h.MongoParseError(`authMechanism one of ${r}, got ${t}`);let o=e.credentials?.source;(n===c.AuthMechanism.MONGODB_PLAIN||c.AUTH_MECHS_AUTH_SRC_EXTERNAL.has(n))&&(o="$external");let i=e.credentials?.password;return n===c.AuthMechanism.MONGODB_X509&&""===i&&(i=void 0),a.MongoCredentials.merge(e.credentials,{mechanism:n,source:o,password:i})}},authMechanismProperties:{target:"credentials",transform({options:e,values:t}){let r=Object.create(null);for(const e of t)if("string"==typeof e)for(const[t,n]of N(e))try{r[t]=_(t,n)}catch{r[t]=n}else{if(!(0,S.isRecord)(e))throw new h.MongoParseError("AuthMechanismProperties must be an object");r={...e}}return a.MongoCredentials.merge(e.credentials,{mechanismProperties:r})}},authSource:{target:"credentials",transform({options:e,values:[t]}){const r=String(t);return a.MongoCredentials.merge(e.credentials,{source:r})}},autoEncryption:{type:"record"},autoSelectFamily:{type:"boolean",default:!0},autoSelectFamilyAttemptTimeout:{type:"uint"},bsonRegExp:{type:"boolean"},serverApi:{target:"serverApi",transform({values:[e]}){const t="string"==typeof e?{version:e}:e,r=t&&t.version;if(!r)throw new h.MongoParseError(`Invalid \`serverApi\` property; must specify a version from the following enum: ["${Object.values(p.ServerApiVersion).join('", "')}"]`);if(!Object.values(p.ServerApiVersion).some((e=>e===r)))throw new h.MongoParseError(`Invalid server API version=${r}; must be in the following enum: ["${Object.values(p.ServerApiVersion).join('", "')}"]`);return t}},checkKeys:{type:"boolean"},compressors:{default:"none",target:"compressors",transform({values:e}){const t=new Set;for(const r of e){const e="string"==typeof r?r.split(","):r;if(!Array.isArray(e))throw new h.MongoInvalidArgumentError("compressors must be an array or a comma-delimited list of strings");for(const r of e){if(!Object.keys(l.Compressor).includes(String(r)))throw new h.MongoInvalidArgumentError(`${r} is not a valid compression mechanism. Must be one of: ${Object.keys(l.Compressor)}.`);t.add(String(r))}}return[...t]}},connectTimeoutMS:{default:3e4,type:"uint"},dbName:{type:"string"},directConnection:{default:!1,type:"boolean"},driverInfo:{default:{},type:"record"},enableUtf8Validation:{type:"boolean",default:!0},family:{transform({name:e,values:[t]}){const r=R(e,t);if(4===r||6===r)return r;throw new h.MongoParseError(`Option 'family' must be 4 or 6 got ${r}.`)}},fieldsAsRaw:{type:"record"},forceServerObjectId:{default:!1,type:"boolean"},fsync:{deprecated:"Please use journal instead",target:"writeConcern",transform({name:e,options:t,values:[r]}){const n=O.WriteConcern.fromOptions({writeConcern:{...t.writeConcern,fsync:_(e,r)}});if(!n)throw new h.MongoParseError(`Unable to make a writeConcern from fsync=${r}`);return n}},heartbeatFrequencyMS:{default:1e4,type:"uint"},ignoreUndefined:{type:"boolean"},j:{deprecated:"Please use journal instead",target:"writeConcern",transform({name:e,options:t,values:[r]}){const n=O.WriteConcern.fromOptions({writeConcern:{...t.writeConcern,journal:_(e,r)}});if(!n)throw new h.MongoParseError(`Unable to make a writeConcern from journal=${r}`);return n}},journal:{target:"writeConcern",transform({name:e,options:t,values:[r]}){const n=O.WriteConcern.fromOptions({writeConcern:{...t.writeConcern,journal:_(e,r)}});if(!n)throw new h.MongoParseError(`Unable to make a writeConcern from journal=${r}`);return n}},loadBalanced:{default:!1,type:"boolean"},localThresholdMS:{default:15,type:"uint"},maxConnecting:{default:2,transform({name:e,values:[t]}){const r=A(e,t);if(0===r)throw new h.MongoInvalidArgumentError("maxConnecting must be > 0 if specified");return r}},maxIdleTimeMS:{default:0,type:"uint"},maxPoolSize:{default:100,type:"uint"},maxStalenessSeconds:{target:"readPreference",transform({name:e,options:t,values:[r]}){const n=A(e,r);return t.readPreference?g.ReadPreference.fromOptions({readPreference:{...t.readPreference,maxStalenessSeconds:n}}):new g.ReadPreference("secondary",void 0,{maxStalenessSeconds:n})}},minInternalBufferSize:{type:"uint"},minPoolSize:{default:0,type:"uint"},minHeartbeatFrequencyMS:{default:500,type:"uint"},monitorCommands:{default:!1,type:"boolean"},name:{target:"driverInfo",transform:({values:[e],options:t})=>({...t.driverInfo,name:String(e)})},noDelay:{default:!0,type:"boolean"},pkFactory:{default:S.DEFAULT_PK_FACTORY,transform({values:[e]}){if((0,S.isRecord)(e,["createPk"])&&"function"==typeof e.createPk)return e;throw new h.MongoParseError(`Option pkFactory must be an object with a createPk function, got ${e}`)}},promoteBuffers:{type:"boolean"},promoteLongs:{type:"boolean"},promoteValues:{type:"boolean"},useBigInt64:{type:"boolean"},proxyHost:{type:"string"},proxyPassword:{type:"string"},proxyPort:{type:"uint"},proxyUsername:{type:"string"},raw:{default:!1,type:"boolean"},readConcern:{transform({values:[e],options:t}){if(e instanceof f.ReadConcern||(0,S.isRecord)(e,["level"]))return f.ReadConcern.fromOptions({...t.readConcern,...e});throw new h.MongoParseError(`ReadConcern must be an object, got ${JSON.stringify(e)}`)}},readConcernLevel:{target:"readConcern",transform:({values:[e],options:t})=>f.ReadConcern.fromOptions({...t.readConcern,level:e})},readPreference:{default:g.ReadPreference.primary,transform({values:[e],options:t}){if(e instanceof g.ReadPreference)return g.ReadPreference.fromOptions({readPreference:{...t.readPreference,...e},...e});if((0,S.isRecord)(e,["mode"])){const r=g.ReadPreference.fromOptions({readPreference:{...t.readPreference,...e},...e});if(r)return r;throw new h.MongoParseError(`Cannot make read preference from ${JSON.stringify(e)}`)}if("string"==typeof e){const r={hedge:t.readPreference?.hedge,maxStalenessSeconds:t.readPreference?.maxStalenessSeconds};return new g.ReadPreference(e,t.readPreference?.tags,r)}throw new h.MongoParseError(`Unknown ReadPreference value: ${e}`)}},readPreferenceTags:{target:"readPreference",transform({values:e,options:t}){const r=Array.isArray(e[0])?e[0]:e,n=[];for(const e of r){const t=Object.create(null);if("string"==typeof e)for(const[r,n]of N(e))t[r]=n;if((0,S.isRecord)(e))for(const[r,n]of Object.entries(e))t[r]=n;n.push(t)}return g.ReadPreference.fromOptions({readPreference:t.readPreference,readPreferenceTags:n})}},replicaSet:{type:"string"},retryReads:{default:!0,type:"boolean"},retryWrites:{default:!0,type:"boolean"},serializeFunctions:{type:"boolean"},serverMonitoringMode:{default:"auto",transform({values:[e]}){if(!Object.values(E.ServerMonitoringMode).includes(e))throw new h.MongoParseError("serverMonitoringMode must be one of `auto`, `poll`, or `stream`");return e}},serverSelectionTimeoutMS:{default:3e4,type:"uint"},servername:{type:"string"},socketTimeoutMS:{default:0,type:"uint"},srvMaxHosts:{type:"uint",default:0},srvServiceName:{type:"string",default:"mongodb"},ssl:{target:"tls",type:"boolean"},timeoutMS:{type:"uint"},tls:{type:"boolean"},tlsAllowInvalidCertificates:{target:"rejectUnauthorized",transform:({name:e,values:[t]})=>!_(e,t)},tlsAllowInvalidHostnames:{target:"checkServerIdentity",transform:({name:e,values:[t]})=>_(e,t)?()=>{}:void 0},tlsCAFile:{type:"string"},tlsCRLFile:{type:"string"},tlsCertificateKeyFile:{type:"string"},tlsCertificateKeyFilePassword:{target:"passphrase",type:"any"},tlsInsecure:{transform({name:e,options:t,values:[r]}){const n=_(e,r);return n?(t.checkServerIdentity=()=>{},t.rejectUnauthorized=!1):(t.checkServerIdentity=t.tlsAllowInvalidHostnames?()=>{}:void 0,t.rejectUnauthorized=!t.tlsAllowInvalidCertificates),n}},w:{target:"writeConcern",transform:({values:[e],options:t})=>O.WriteConcern.fromOptions({writeConcern:{...t.writeConcern,w:e}})},waitQueueTimeoutMS:{default:0,type:"uint"},writeConcern:{target:"writeConcern",transform({values:[e],options:t}){if((0,S.isRecord)(e)||e instanceof O.WriteConcern)return O.WriteConcern.fromOptions({writeConcern:{...t.writeConcern,...e}});if("majority"===e||"number"==typeof e)return O.WriteConcern.fromOptions({writeConcern:{...t.writeConcern,w:e}});throw new h.MongoParseError(`Invalid WriteConcern cannot parse: ${JSON.stringify(e)}`)}},wtimeout:{deprecated:"Please use wtimeoutMS instead",target:"writeConcern",transform({values:[e],options:t}){const r=O.WriteConcern.fromOptions({writeConcern:{...t.writeConcern,wtimeout:A("wtimeout",e)}});if(r)return r;throw new h.MongoParseError("Cannot make WriteConcern from wtimeout")}},wtimeoutMS:{target:"writeConcern",transform({values:[e],options:t}){const r=O.WriteConcern.fromOptions({writeConcern:{...t.writeConcern,wtimeoutMS:A("wtimeoutMS",e)}});if(r)return r;throw new h.MongoParseError("Cannot make WriteConcern from wtimeout")}},zlibCompressionLevel:{default:0,type:"int"},mongodbLogPath:{transform({values:[e]}){if(!("string"==typeof e&&["stderr","stdout"].includes(e)||e&&"object"==typeof e&&"write"in e&&"function"==typeof e.write))throw new h.MongoAPIError("Option 'mongodbLogPath' must be of type 'stderr' | 'stdout' | MongoDBLogWritable");return e}},mongodbLogComponentSeverities:{transform({values:[e]}){if("object"!=typeof e||!e)throw new h.MongoAPIError("Option 'mongodbLogComponentSeverities' must be a non-null object");for(const[t,r]of Object.entries(e)){if("string"!=typeof r||"string"!=typeof t)throw new h.MongoAPIError("User input for option 'mongodbLogComponentSeverities' object cannot include a non-string key or value");if(!Object.values(m.MongoLoggableComponent).some((e=>e===t))&&"default"!==t)throw new h.MongoAPIError(`User input for option 'mongodbLogComponentSeverities' contains invalid key: ${t}`);if(!Object.values(m.SeverityLevel).some((e=>e===r)))throw new h.MongoAPIError(`Option 'mongodbLogComponentSeverities' does not support ${r} as a value for ${t}`)}return e}},mongodbLogMaxDocumentLength:{type:"uint"},connectionType:{type:"any"},srvPoller:{type:"any"},allowPartialTrustChain:{type:"any"},minDHSize:{type:"any"},pskCallback:{type:"any"},secureContext:{type:"any"},enableTrace:{type:"any"},requestCert:{type:"any"},rejectUnauthorized:{type:"any"},checkServerIdentity:{type:"any"},keepAliveInitialDelay:{type:"any"},ALPNProtocols:{type:"any"},SNICallback:{type:"any"},session:{type:"any"},requestOCSP:{type:"any"},localAddress:{type:"any"},localPort:{type:"any"},hints:{type:"any"},lookup:{type:"any"},ca:{type:"any"},cert:{type:"any"},ciphers:{type:"any"},crl:{type:"any"},ecdhCurve:{type:"any"},key:{type:"any"},passphrase:{type:"any"},pfx:{type:"any"},secureProtocol:{type:"any"},index:{type:"any"},useNewUrlParser:{type:"boolean",deprecated:"useNewUrlParser has no effect since Node.js Driver version 4.0.0 and will be removed in the next major version"},useUnifiedTopology:{type:"boolean",deprecated:"useUnifiedTopology has no effect since Node.js Driver version 4.0.0 and will be removed in the next major version"},__skipPingOnConnect:{type:"boolean"}},t.DEFAULT_OPTIONS=new I(Object.entries(t.OPTIONS).filter((([,e])=>null!=e.default)).map((([e,t])=>[e,t.default])))},6987:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ClientBulkWriteResultsMerger=void 0;const n=r(16360),o=r(17562),i={acknowledged:!1,insertedCount:0,upsertedCount:0,matchedCount:0,modifiedCount:0,deletedCount:0,insertResults:void 0,updateResults:void 0,deleteResults:void 0};t.ClientBulkWriteResultsMerger=class{static unacknowledged(){return i}constructor(e){this.options=e,this.currentBatchOffset=0,this.writeConcernErrors=[],this.writeErrors=new Map,this.result={acknowledged:!0,insertedCount:0,upsertedCount:0,matchedCount:0,modifiedCount:0,deletedCount:0,insertResults:void 0,updateResults:void 0,deleteResults:void 0},e.verboseResults&&(this.result.insertResults=new Map,this.result.updateResults=new Map,this.result.deleteResults=new Map)}get bulkWriteResult(){return{acknowledged:this.result.acknowledged,insertedCount:this.result.insertedCount,upsertedCount:this.result.upsertedCount,matchedCount:this.result.matchedCount,modifiedCount:this.result.modifiedCount,deletedCount:this.result.deletedCount,insertResults:this.result.insertResults,updateResults:this.result.updateResults,deleteResults:this.result.deleteResults}}async merge(e){let t;try{for await(const t of e)if(1===t.ok)this.options.verboseResults&&this.processDocument(e,t);else{if(this.options.ordered){const e=new o.MongoClientBulkWriteError({message:"Mongo client ordered bulk write encountered a write error."});throw e.writeErrors.set(t.idx+this.currentBatchOffset,{code:t.code,message:t.errmsg}),e.partialResult=this.result,e}this.writeErrors.set(t.idx+this.currentBatchOffset,{code:t.code,message:t.errmsg})}}catch(r){if(!(r instanceof n.MongoWriteConcernError))throw r;{const n=r.result;if(t={insertedCount:n.nInserted,upsertedCount:n.nUpserted,matchedCount:n.nMatched,modifiedCount:n.nModified,deletedCount:n.nDeleted,writeConcernError:n.writeConcernError},this.options.verboseResults&&n.cursor.firstBatch)for(const t of n.cursor.firstBatch)1===t.ok&&this.processDocument(e,t)}}finally{if(e.response){const t=e.response;this.incrementCounts(t)}this.currentBatchOffset+=e.operations.length}if(t){const e=t.writeConcernError;this.incrementCounts(t),this.writeConcernErrors.push({code:e.code,message:e.errmsg})}return this.result}processDocument(e,t){const r=e.operations[t.idx];if("insert"in r&&this.result.insertResults?.set(t.idx+this.currentBatchOffset,{insertedId:r.document._id}),"update"in r){const e={matchedCount:t.n,modifiedCount:t.nModified??0,didUpsert:null!=t.upserted};t.upserted&&(e.upsertedId=t.upserted._id),this.result.updateResults?.set(t.idx+this.currentBatchOffset,e)}"delete"in r&&this.result.deleteResults?.set(t.idx+this.currentBatchOffset,{deletedCount:t.n})}incrementCounts(e){this.result.insertedCount+=e.insertedCount,this.result.upsertedCount+=e.upsertedCount,this.result.matchedCount+=e.matchedCount,this.result.modifiedCount+=e.modifiedCount,this.result.deletedCount+=e.deletedCount}}},7180:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ClientBulkWriteCursor=void 0;const n=r(34080),o=r(96357),i=r(145),s=r(61066);class a extends s.AbstractCursor{constructor(e,t,r={}){super(e,new i.MongoDBNamespace("admin","$cmd"),r),this.commandBuilder=t,this.clientBulkWriteOptions=r}get response(){return this.cursorResponse?this.cursorResponse:null}get operations(){return this.commandBuilder.lastOperations}clone(){const e=(0,i.mergeOptions)({},this.clientBulkWriteOptions);return delete e.session,new a(this.client,this.commandBuilder,{...e})}async _initialize(e){const t=new n.ClientBulkWriteOperation(this.commandBuilder,{...this.clientBulkWriteOptions,...this.cursorOptions,session:e}),r=await(0,o.executeOperation)(this.client,t,this.timeoutContext);return this.cursorResponse=r,{server:t.server,session:e,response:r}}}t.ClientBulkWriteCursor=a},7799:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.LegacyTimeoutContext=t.CSOTTimeoutContext=t.TimeoutContext=t.Timeout=t.TimeoutError=void 0;const n=r(37668),o=r(17562),i=r(145);class s extends Error{get name(){return"TimeoutError"}constructor(e,t){super(e,t),this.duration=t.duration}static is(e){return null!=e&&"object"==typeof e&&"name"in e&&"TimeoutError"===e.name}}t.TimeoutError=s;class a extends Promise{get remainingTime(){return this.timedOut?0:0===this.duration?1/0:this.start+this.duration-Math.trunc(performance.now())}get timeElapsed(){return Math.trunc(performance.now())-this.start}constructor(e=()=>null,t){const r=t?.duration??0,a=!!t?.unref,c=t?.rejection;if(r<0)throw new o.MongoInvalidArgumentError("Cannot create a Timeout with a negative duration");let u;super(((t,r)=>{u=r,e(i.noop,r)})),this.ended=null,this.timedOut=!1,this.cleared=!1,this.duration=r,this.start=Math.trunc(performance.now()),null==c&&this.duration>0?(this.id=(0,n.setTimeout)((()=>{this.ended=Math.trunc(performance.now()),this.timedOut=!0,u(new s(`Expired after ${r}ms`,{duration:r}))}),this.duration),"function"==typeof this.id.unref&&a&&this.id.unref()):null!=c&&(this.ended=Math.trunc(performance.now()),this.timedOut=!0,u(c))}clear(){(0,n.clearTimeout)(this.id),this.id=void 0,this.timedOut=!1,this.cleared=!0}throwIfExpired(){if(this.timedOut)throw this.then(void 0,i.squashError),new s("Timed out",{duration:this.duration})}static expires(e,t){return new a(void 0,{duration:e,unref:t})}static reject(e){return new a(void 0,{duration:0,unref:!0,rejection:e})}}t.Timeout=a;class c{static create(e){if(null!=e.session?.timeoutContext)return e.session?.timeoutContext;if(null!=(t=e)&&"object"==typeof t&&"serverSelectionTimeoutMS"in t&&"number"==typeof t.serverSelectionTimeoutMS&&"timeoutMS"in t&&"number"==typeof t.timeoutMS)return new u(e);if(function(e){return null!=e&&"object"==typeof e&&"serverSelectionTimeoutMS"in e&&"number"==typeof e.serverSelectionTimeoutMS&&"waitQueueTimeoutMS"in e&&"number"==typeof e.waitQueueTimeoutMS}(e))return new l(e);throw new o.MongoRuntimeError("Unrecognized options");var t}}t.TimeoutContext=c;class u extends c{constructor(e){super(),this.minRoundTripTime=0,this.start=Math.trunc(performance.now()),this.timeoutMS=e.timeoutMS,this.serverSelectionTimeoutMS=e.serverSelectionTimeoutMS,this.socketTimeoutMS=e.socketTimeoutMS,this.clearServerSelectionTimeout=!1}get maxTimeMS(){return this.remainingTimeMS-this.minRoundTripTime}get remainingTimeMS(){const e=Math.trunc(performance.now())-this.start;return this.timeoutMS<=0?1/0:this.timeoutMS-e}csotEnabled(){return!0}get serverSelectionTimeout(){if("object"!=typeof this._serverSelectionTimeout||this._serverSelectionTimeout?.cleared){const{remainingTimeMS:e,serverSelectionTimeoutMS:t}=this;if(e<=0)return a.reject(new o.MongoOperationTimeoutError(`Timed out in server selection after ${this.timeoutMS}ms`));0!==t&&(0,i.csotMin)(e,t)===t?this._serverSelectionTimeout=a.expires(t):e>0&&Number.isFinite(e)?this._serverSelectionTimeout=a.expires(e):this._serverSelectionTimeout=null}return this._serverSelectionTimeout}get connectionCheckoutTimeout(){if("object"!=typeof this._connectionCheckoutTimeout||this._connectionCheckoutTimeout?.cleared){if("object"!=typeof this._serverSelectionTimeout)throw new o.MongoRuntimeError("Unreachable. If you are seeing this error, please file a ticket on the NODE driver project on Jira");this._connectionCheckoutTimeout=this._serverSelectionTimeout}return this._connectionCheckoutTimeout}get timeoutForSocketWrite(){const{remainingTimeMS:e}=this;return Number.isFinite(e)?e>0?a.expires(e):a.reject(new o.MongoOperationTimeoutError("Timed out before socket write")):null}get timeoutForSocketRead(){const{remainingTimeMS:e}=this;return Number.isFinite(e)?e>0?a.expires(e):a.reject(new o.MongoOperationTimeoutError("Timed out before socket read")):null}refresh(){this.start=Math.trunc(performance.now()),this.minRoundTripTime=0,this._serverSelectionTimeout?.clear(),this._connectionCheckoutTimeout?.clear()}clear(){this._serverSelectionTimeout?.clear(),this._connectionCheckoutTimeout?.clear()}getRemainingTimeMSOrThrow(e){const{remainingTimeMS:t}=this;if(t<=0)throw new o.MongoOperationTimeoutError(e??`Expired after ${this.timeoutMS}ms`);return t}clone(){const e=new u({timeoutMS:this.timeoutMS,serverSelectionTimeoutMS:this.serverSelectionTimeoutMS});return e.start=this.start,e}refreshed(){return new u(this)}addMaxTimeMSToCommand(e,t){if(t.omitMaxTimeMS)return;const r=this.remainingTimeMS-this.minRoundTripTime;r>0&&Number.isFinite(r)&&(e.maxTimeMS=r)}getSocketTimeoutMS(){return 0}}t.CSOTTimeoutContext=u;class l extends c{constructor(e){super(),this.options=e,this.clearServerSelectionTimeout=!0}csotEnabled(){return!1}get serverSelectionTimeout(){return null!=this.options.serverSelectionTimeoutMS&&this.options.serverSelectionTimeoutMS>0?a.expires(this.options.serverSelectionTimeoutMS):null}get connectionCheckoutTimeout(){return null!=this.options.waitQueueTimeoutMS&&this.options.waitQueueTimeoutMS>0?a.expires(this.options.waitQueueTimeoutMS):null}get timeoutForSocketWrite(){return null}get timeoutForSocketRead(){return null}refresh(){}clear(){}get maxTimeMS(){return null}refreshed(){return new l(this.options)}addMaxTimeMSToCommand(e,t){}getSocketTimeoutMS(){return this.options.socketTimeoutMS}}t.LegacyTimeoutContext=l},8294:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TokenCache=void 0;const n=r(17562);class o extends n.MongoDriverError{}t.TokenCache=class{get hasAccessToken(){return!!this.accessToken}get hasRefreshToken(){return!!this.refreshToken}get hasIdpInfo(){return!!this.idpInfo}getAccessToken(){if(!this.accessToken)throw new o("Attempted to get an access token when none exists.");return this.accessToken}getRefreshToken(){if(!this.refreshToken)throw new o("Attempted to get a refresh token when none exists.");return this.refreshToken}getIdpInfo(){if(!this.idpInfo)throw new o("Attempted to get IDP information when none exists.");return this.idpInfo}put(e,t){this.accessToken=e.accessToken,this.refreshToken=e.refreshToken,this.expiresInSeconds=e.expiresInSeconds,t&&(this.idpInfo=t)}removeAccessToken(){this.accessToken=void 0}removeRefreshToken(){this.refreshToken=void 0}}},8500:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.aws4=void 0,t.getKerberos=function(){let e;try{e=r(96751)}catch(t){e=o(new n.MongoMissingDependencyError("Optional module `kerberos` not found. Please install it to enable kerberos authentication",{cause:t,dependencyName:"kerberos"}))}return e},t.getZstdLibrary=function(){let e;try{e=r(96751)}catch(t){e=o(new n.MongoMissingDependencyError("Optional module `@mongodb-js/zstd` not found. Please install it to enable zstd compression",{cause:t,dependencyName:"zstd"}))}return e},t.getAwsCredentialProvider=function(){try{return r(96751)}catch(e){return o(new n.MongoMissingDependencyError("Optional module `@aws-sdk/credential-providers` not found. Please install it to enable getting aws credentials via the official sdk.",{cause:e,dependencyName:"@aws-sdk/credential-providers"}))}},t.getGcpMetadata=function(){try{return r(96751)}catch(e){return o(new n.MongoMissingDependencyError("Optional module `gcp-metadata` not found. Please install it to enable getting gcp credentials via the official sdk.",{cause:e,dependencyName:"gcp-metadata"}))}},t.getSnappy=function(){try{return r(96751)}catch(e){return{kModuleError:new n.MongoMissingDependencyError("Optional module `snappy` not found. Please install it to enable snappy compression",{cause:e,dependencyName:"snappy"})}}},t.getSocks=function(){try{return r(96751)}catch(e){return{kModuleError:new n.MongoMissingDependencyError("Optional module `socks` not found. Please install it to connections over a SOCKS5 proxy",{cause:e,dependencyName:"socks"})}}},t.getMongoDBClientEncryption=function(){let e=null;try{e=r(96751)}catch(e){return{kModuleError:new n.MongoMissingDependencyError("Optional module `mongodb-client-encryption` not found. Please install it to use auto encryption or ClientEncryption.",{cause:e,dependencyName:"mongodb-client-encryption"})}}return e};const n=r(17562);function o(e){return new Proxy(e?{kModuleError:e}:{},{get:(t,r)=>{if("kModuleError"===r)return e;throw e},set:()=>{throw e}})}t.aws4=function(){let e;try{e=r(96751)}catch(t){e=o(new n.MongoMissingDependencyError("Optional module `aws4` not found. Please install it to enable AWS authentication",{cause:t,dependencyName:"aws4"}))}return e}()},9188:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ServerDescription=void 0,t.parseServerType=u,t.compareTopologyVersion=l;const n=r(75080),o=r(17562),i=r(145),s=r(89167),a=new Set([s.ServerType.RSPrimary,s.ServerType.Standalone,s.ServerType.Mongos,s.ServerType.LoadBalancer]),c=new Set([s.ServerType.RSPrimary,s.ServerType.RSSecondary,s.ServerType.Mongos,s.ServerType.Standalone,s.ServerType.LoadBalancer]);function u(e,t){return t?.loadBalanced?s.ServerType.LoadBalancer:e&&e.ok?e.isreplicaset?s.ServerType.RSGhost:e.msg&&"isdbgrid"===e.msg?s.ServerType.Mongos:e.setName?e.hidden?s.ServerType.RSOther:e.isWritablePrimary?s.ServerType.RSPrimary:e.secondary?s.ServerType.RSSecondary:e.arbiterOnly?s.ServerType.RSArbiter:s.ServerType.RSOther:s.ServerType.Standalone:s.ServerType.Unknown}function l(e,t){if(null==e||null==t)return-1;if(!e.processId.equals(t.processId))return-1;const r="bigint"==typeof e.counter?n.Long.fromBigInt(e.counter):n.Long.isLong(e.counter)?e.counter:n.Long.fromNumber(e.counter),o="bigint"==typeof t.counter?n.Long.fromBigInt(t.counter):n.Long.isLong(t.counter)?t.counter:n.Long.fromNumber(t.counter);return r.compare(o)}t.ServerDescription=class{constructor(e,t,r={}){if(null==e||""===e)throw new o.MongoRuntimeError("ServerDescription must be provided with a non-empty address");this.address="string"==typeof e?i.HostAddress.fromString(e).toString():e.toString(),this.type=u(t,r),this.hosts=t?.hosts?.map((e=>e.toLowerCase()))??[],this.passives=t?.passives?.map((e=>e.toLowerCase()))??[],this.arbiters=t?.arbiters?.map((e=>e.toLowerCase()))??[],this.tags=t?.tags??{},this.minWireVersion=t?.minWireVersion??0,this.maxWireVersion=t?.maxWireVersion??0,this.roundTripTime=r?.roundTripTime??-1,this.minRoundTripTime=r?.minRoundTripTime??0,this.lastUpdateTime=(0,i.now)(),this.lastWriteDate=t?.lastWrite?.lastWriteDate??0,this.error=r.error??null,this.error,this.topologyVersion=this.error?.topologyVersion??t?.topologyVersion??null,this.setName=t?.setName??null,this.setVersion=t?.setVersion??null,this.electionId=t?.electionId??null,this.logicalSessionTimeoutMinutes=t?.logicalSessionTimeoutMinutes??null,this.maxMessageSizeBytes=t?.maxMessageSizeBytes??null,this.maxWriteBatchSize=t?.maxWriteBatchSize??null,this.maxBsonObjectSize=t?.maxBsonObjectSize??null,this.primary=t?.primary??null,this.me=t?.me?.toLowerCase()??null,this.$clusterTime=t?.$clusterTime??null,this.iscryptd=Boolean(t?.iscryptd)}get hostAddress(){return i.HostAddress.fromString(this.address)}get allHosts(){return this.hosts.concat(this.arbiters).concat(this.passives)}get isReadable(){return this.type===s.ServerType.RSSecondary||this.isWritable}get isDataBearing(){return c.has(this.type)}get isWritable(){return a.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):27017}equals(e){const t=this.topologyVersion===e?.topologyVersion||0===l(this.topologyVersion,e?.topologyVersion),r=null!=this.electionId&&null!=e?.electionId?0===(0,i.compareObjectId)(this.electionId,e.electionId):this.electionId===e?.electionId;return null!=e&&e.iscryptd===this.iscryptd&&(0,i.errorStrictEqual)(this.error,e.error)&&this.type===e.type&&this.minWireVersion===e.minWireVersion&&(0,i.arrayStrictEqual)(this.hosts,e.hosts)&&function(e,t){const r=Object.keys(e),n=Object.keys(t);return r.length===n.length&&r.every((r=>t[r]===e[r]))}(this.tags,e.tags)&&this.setName===e.setName&&this.setVersion===e.setVersion&&r&&this.primary===e.primary&&this.logicalSessionTimeoutMinutes===e.logicalSessionTimeoutMinutes&&t}}},9284:(e,t,r)=>{var n=r(9606).URL;Object.defineProperty(t,"__esModule",{value:!0}),t.callback=void 0;const o=r(17562),i=r(145),s=Object.freeze({"Metadata-Flavor":"Google"});t.callback=async e=>{const t=e.tokenAudience;if(!t)throw new o.MongoGCPError("TOKEN_RESOURCE must be set in the auth mechanism properties when ENVIRONMENT is gcp.");return await async function(e){const t=new n("http://metadata/computeMetadata/v1/instance/service-accounts/default/identity");t.searchParams.append("audience",e);const r=await(0,i.get)(t,{headers:s});if(200!==r.status)throw new o.MongoGCPError(`Status code ${r.status} returned from the GCP endpoint. Response body: ${r.body}`);return{accessToken:r.body}}(t)}},9326:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.InsertOneOperation=t.InsertOperation=void 0;const n=r(75725),o=r(17562),i=r(145),s=r(78130),a=r(35394);class c extends s.CommandOperation{constructor(e,t,r){super(void 0,r),this.SERVER_COMMAND_RESPONSE_TYPE=n.MongoDBResponse,this.options={...r,checkKeys:r.checkKeys??!1},this.ns=e,this.documents=t}get commandName(){return"insert"}buildCommandDocument(e,t){const r=this.options??{},n="boolean"!=typeof r.ordered||r.ordered,o={insert:this.ns.collection,documents:this.documents,ordered:n};return"boolean"==typeof r.bypassDocumentValidation&&(o.bypassDocumentValidation=r.bypassDocumentValidation),void 0!==r.comment&&(o.comment=r.comment),o}}t.InsertOperation=c;class u extends c{constructor(e,t,r){super(e.s.namespace,[(0,i.maybeAddIdToDocuments)(e,t,r)],r)}handleOk(e){const t=super.handleOk(e);if(t.code)throw new o.MongoServerError(t);if(t.writeErrors)throw new o.MongoServerError(t.writeErrors[0]);return{acknowledged:0!==this.writeConcern?.w,insertedId:this.documents[0]._id}}}t.InsertOneOperation=u,(0,a.defineAspects)(c,[a.Aspect.RETRYABLE,a.Aspect.WRITE_OPERATION]),(0,a.defineAspects)(u,[a.Aspect.RETRYABLE,a.Aspect.WRITE_OPERATION])},10089:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.UnorderedBulkOperation=void 0;const n=r(75080),o=r(17562),i=r(54564);class s extends i.BulkOperationBase{constructor(e,t){super(e,t,!1)}handleWriteError(e){if(!this.s.batches.length)return super.handleWriteError(e)}addToOperationsList(e,t){const r=n.calculateObjectSize(t,{checkKeys:!1,ignoreUndefined:!1});if(r>=this.s.maxBsonObjectSize)throw new o.MongoInvalidArgumentError(`Document is larger than the maximum size ${this.s.maxBsonObjectSize}`);this.s.currentBatch=void 0,e===i.BatchType.INSERT?this.s.currentBatch=this.s.currentInsertBatch:e===i.BatchType.UPDATE?this.s.currentBatch=this.s.currentUpdateBatch:e===i.BatchType.DELETE&&(this.s.currentBatch=this.s.currentRemoveBatch);const s=this.s.maxKeySize;if(null==this.s.currentBatch&&(this.s.currentBatch=new i.Batch(e,this.s.currentIndex)),(this.s.currentBatch.size+1>=this.s.maxWriteBatchSize||this.s.currentBatch.size>0&&this.s.currentBatch.sizeBytes+s+r>=this.s.maxBatchSizeBytes||this.s.currentBatch.batchType!==e)&&(this.s.batches.push(this.s.currentBatch),this.s.currentBatch=new i.Batch(e,this.s.currentIndex)),Array.isArray(t))throw new o.MongoInvalidArgumentError("Operation passed in cannot be an Array");return this.s.currentBatch.operations.push(t),this.s.currentBatch.originalIndexes.push(this.s.currentIndex),this.s.currentIndex=this.s.currentIndex+1,e===i.BatchType.INSERT?(this.s.currentInsertBatch=this.s.currentBatch,this.s.bulkResult.insertedIds.push({index:this.s.bulkResult.insertedIds.length,_id:t._id})):e===i.BatchType.UPDATE?this.s.currentUpdateBatch=this.s.currentBatch:e===i.BatchType.DELETE&&(this.s.currentRemoveBatch=this.s.currentBatch),this.s.currentBatch.size+=1,this.s.currentBatch.sizeBytes+=s+r,this}}t.UnorderedBulkOperation=s},10557:(e,t,r)=>{var n=r(67787).Buffer,o=r(65994).e;Object.defineProperty(t,"__esModule",{value:!0}),t.GridFSBucketWriteStream=void 0;const i=r(93874),s=r(75080),a=r(61066),c=r(17562),u=r(7799),l=r(145),d=r(40012);class h extends i.Writable{constructor(e,t,r){super(),this.gridFSFile=null,r=r??{},this.bucket=e,this.chunks=e.s._chunksCollection,this.filename=t,this.files=e.s._filesCollection,this.options=r,this.writeConcern=d.WriteConcern.fromOptions(r)||e.s.options.writeConcern,this.done=!1,this.id=r.id?r.id:new s.ObjectId,this.chunkSizeBytes=r.chunkSizeBytes||this.bucket.s.options.chunkSizeBytes,this.bufToStore=n.alloc(this.chunkSizeBytes),this.length=0,this.n=0,this.pos=0,this.state={streamEnd:!1,outstandingRequests:0,errored:!1,aborted:!1},null!=r.timeoutMS&&(this.timeoutContext=new u.CSOTTimeoutContext({timeoutMS:r.timeoutMS,serverSelectionTimeoutMS:(0,l.resolveTimeoutOptions)(this.bucket.s.db.client,{}).serverSelectionTimeoutMS}))}_construct(e){if(this.bucket.s.calledOpenUploadStream)return o.nextTick(e);this.bucket.s.calledOpenUploadStream=!0,async function(e){let t=e.timeoutContext?.getRemainingTimeMSOrThrow(`Upload timed out after ${e.timeoutContext?.timeoutMS}ms`);if(null!=await e.files.findOne({},{projection:{_id:1},timeoutMS:t}))return;let r;t=e.timeoutContext?.getRemainingTimeMSOrThrow(`Upload timed out after ${e.timeoutContext?.timeoutMS}ms`);const n={timeoutMode:null!=t?a.CursorTimeoutMode.LIFETIME:void 0,timeoutMS:t};try{r=await e.files.listIndexes(n).toArray()}catch(e){if(!(e instanceof c.MongoError&&e.code===c.MONGODB_ERROR_CODES.NamespaceNotFound))throw e;r=[]}r.find((e=>2===Object.keys(e.key).length&&1===e.key.filename&&1===e.key.uploadDate))||(t=e.timeoutContext?.getRemainingTimeMSOrThrow(`Upload timed out after ${e.timeoutContext?.timeoutMS}ms`),await e.files.createIndex({filename:1,uploadDate:1},{background:!1,timeoutMS:t})),await async function(e){let t,r;t=e.timeoutContext?.getRemainingTimeMSOrThrow(`Upload timed out after ${e.timeoutContext?.timeoutMS}ms`);try{r=await e.chunks.listIndexes({timeoutMode:null!=t?a.CursorTimeoutMode.LIFETIME:void 0,timeoutMS:t}).toArray()}catch(e){if(!(e instanceof c.MongoError&&e.code===c.MONGODB_ERROR_CODES.NamespaceNotFound))throw e;r=[]}const n=!!r.find((e=>2===Object.keys(e.key).length&&1===e.key.files_id&&1===e.key.n));n||(t=e.timeoutContext?.getRemainingTimeMSOrThrow(`Upload timed out after ${e.timeoutContext?.timeoutMS}ms`),await e.chunks.createIndex({files_id:1,n:1},{...e.writeConcern,background:!0,unique:!0,timeoutMS:t}))}(e)}(this).then((()=>{this.bucket.s.checkedIndexes=!0,this.bucket.emit("index"),e()}),(t=>{if(t instanceof c.MongoOperationTimeoutError)return p(this,t,e);(0,l.squashError)(t),e()}))}_write(e,t,r){!function(e,t,r,i){if(g(e,i))return;const s=n.isBuffer(t)?t:n.from(t,r);if(e.length+=s.length,e.pos+s.length<e.chunkSizeBytes)return s.copy(e.bufToStore,e.pos),e.pos+=s.length,void o.nextTick(i);let a=s.length,u=e.chunkSizeBytes-e.pos,l=Math.min(u,s.length),d=0;for(;a>0;){const t=s.length-a;let r;if(s.copy(e.bufToStore,e.pos,t,t+l),e.pos+=l,u-=l,0===u){r=m(e.id,e.n,n.from(e.bufToStore));const t=e.timeoutContext?.remainingTimeMS;if(null!=t&&t<=0)return p(e,new c.MongoOperationTimeoutError(`Upload timed out after ${e.timeoutContext?.timeoutMS}ms`),i);if(++e.state.outstandingRequests,++d,g(e,i))return;e.chunks.insertOne(r,{writeConcern:e.writeConcern,timeoutMS:t}).then((()=>{--e.state.outstandingRequests,--d,d||f(e,i)}),(t=>p(e,t,i))),u=e.chunkSizeBytes,e.pos=0,++e.n}a-=l,l=Math.min(u,a)}}(this,e,t,r)}_final(e){if(this.state.streamEnd)return o.nextTick(e);this.state.streamEnd=!0,function(e,t){if(0===e.pos)return f(e,t);const r=n.alloc(e.pos);e.bufToStore.copy(r,0,0,e.pos);const o=m(e.id,e.n,r);if(g(e,t))return;const i=e.timeoutContext?.remainingTimeMS;if(null!=i&&i<=0)return p(e,new c.MongoOperationTimeoutError(`Upload timed out after ${e.timeoutContext?.timeoutMS}ms`),t);++e.state.outstandingRequests,e.chunks.insertOne(o,{writeConcern:e.writeConcern,timeoutMS:i}).then((()=>{--e.state.outstandingRequests,f(e,t)}),(r=>p(e,r,t)))}(this,e)}async abort(){if(this.state.streamEnd)throw new c.MongoAPIError("Cannot abort a stream that has already completed");if(this.state.aborted)throw new c.MongoAPIError("Cannot call abort() on a stream twice");this.state.aborted=!0;const e=this.timeoutContext?.getRemainingTimeMSOrThrow(`Upload timed out after ${this.timeoutContext?.timeoutMS}ms`);await this.chunks.deleteMany({files_id:this.id},{timeoutMS:e})}}function p(e,t,r){e.state.errored?o.nextTick(r):(e.state.errored=!0,o.nextTick(r,t))}function m(e,t,r){return{_id:new s.ObjectId,files_id:e,n:t,data:r}}function f(e,t){if(e.done)return o.nextTick(t);if(e.state.streamEnd&&0===e.state.outstandingRequests&&!e.state.errored){e.done=!0;const r=function(e,t,r,n,o,i,s){const a={_id:e,length:t,chunkSize:r,uploadDate:new Date,filename:n};return o&&(a.contentType=o),i&&(a.aliases=i),s&&(a.metadata=s),a}(e.id,e.length,e.chunkSizeBytes,e.filename,e.options.contentType,e.options.aliases,e.options.metadata);if(g(e,t))return;const n=e.timeoutContext?.remainingTimeMS;return null!=n&&n<=0?p(e,new c.MongoOperationTimeoutError(`Upload timed out after ${e.timeoutContext?.timeoutMS}ms`),t):void e.files.insertOne(r,{writeConcern:e.writeConcern,timeoutMS:n}).then((()=>{e.gridFSFile=r,t()}),(r=>p(e,r,t)))}o.nextTick(t)}function g(e,t){return!!e.state.aborted&&(o.nextTick(t,new c.MongoAPIError("Stream has been aborted")),!0)}t.GridFSBucketWriteStream=h},11706:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ListDatabasesOperation=void 0;const n=r(75725),o=r(145),i=r(78130),s=r(35394);class a extends i.CommandOperation{constructor(e,t){super(e,t),this.SERVER_COMMAND_RESPONSE_TYPE=n.MongoDBResponse,this.options=t??{},this.ns=new o.MongoDBNamespace("admin","$cmd")}get commandName(){return"listDatabases"}buildCommandDocument(e,t){const r={listDatabases:1};return"boolean"==typeof this.options.nameOnly&&(r.nameOnly=this.options.nameOnly),this.options.filter&&(r.filter=this.options.filter),"boolean"==typeof this.options.authorizedDatabases&&(r.authorizedDatabases=this.options.authorizedDatabases),(0,o.maxWireVersion)(e)>=9&&void 0!==this.options.comment&&(r.comment=this.options.comment),r}}t.ListDatabasesOperation=a,(0,s.defineAspects)(a,[s.Aspect.READ_OPERATION,s.Aspect.RETRYABLE])},11737:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.buildReplaceOneOperation=t.buildUpdateManyOperation=t.buildUpdateOneOperation=t.buildDeleteManyOperation=t.buildDeleteOneOperation=t.buildInsertOneOperation=t.ClientBulkWriteCommandBuilder=void 0,t.buildOperation=d;const n=r(75080),o=r(15620),i=r(17562),s=r(30770),a=r(145);function c(e,t,r){if(t.length>r)throw new i.MongoInvalidArgumentError(`Client bulk write operation ${e} of length ${t.length} exceeds the max bson object size of ${r}`)}function u(e,t,r){const n={delete:t,multi:r,filter:e.filter};return e.hint&&(n.hint=e.hint),e.collation&&(n.collation=e.collation),n}function l(e,t,r,n){!function(e,t){if(!(0,a.hasAtomicOperators)(e,t))throw new i.MongoAPIError("Client bulk write update models must only contain atomic modifiers (start with $) and must not be empty.")}(e.update,n);const o={update:t,multi:r,filter:e.filter,updateMods:e.update};return e.hint&&(o.hint=e.hint),e.upsert&&(o.upsert=e.upsert),e.arrayFilters&&(o.arrayFilters=e.arrayFilters),e.collation&&(o.collation=e.collation),!r&&"sort"in e&&null!=e.sort&&(o.sort=(0,s.formatSort)(e.sort)),o}function d(e,r,n,o){switch(e.name){case"insertOne":return(0,t.buildInsertOneOperation)(e,r,n);case"deleteOne":return(0,t.buildDeleteOneOperation)(e,r);case"deleteMany":return(0,t.buildDeleteManyOperation)(e,r);case"updateOne":return(0,t.buildUpdateOneOperation)(e,r,o);case"updateMany":return(0,t.buildUpdateManyOperation)(e,r,o);case"replaceOne":return(0,t.buildReplaceOneOperation)(e,r)}}t.ClientBulkWriteCommandBuilder=class{constructor(e,t,r){this.models=e,this.options=t,this.pkFactory=r??a.DEFAULT_PK_FACTORY,this.currentModelIndex=0,this.previousModelIndex=0,this.lastOperations=[],this.isBatchRetryable=!0}get errorsOnly(){return!("verboseResults"in this.options)||!this.options.verboseResults}hasNextBatch(){return this.currentModelIndex<this.models.length}resetBatch(){return this.currentModelIndex=this.previousModelIndex,!0}buildBatch(e,t,r){this.isBatchRetryable=!0;let o=0,s=0;const a=this.baseCommand(),u=new Map;for(this.previousModelIndex=this.currentModelIndex;this.currentModelIndex<this.models.length;){const l=this.models[this.currentModelIndex],h=l.namespace,p=u.get(h);if("deleteMany"!==l.name&&"updateMany"!==l.name||(this.isBatchRetryable=!1),null!=p){const s=d(l,p,this.pkFactory,this.options);let u;try{u=n.BSON.serialize(s)}catch(e){throw new i.MongoInvalidArgumentError("Could not serialize operation to BSON",{cause:e})}if(c("ops",u,r),!(o+u.length<e&&a.ops.documents.length<t))break;o=1e3+a.ops.push(s,u),this.currentModelIndex++}else{u.set(h,s);const p={ns:h},m=d(l,s,this.pkFactory,this.options);let f,g;try{f=n.BSON.serialize(p),g=n.BSON.serialize(m)}catch(e){throw new i.MongoInvalidArgumentError("Could not serialize ns info to BSON",{cause:e})}if(c("nsInfo",f,r),c("ops",g,r),!(o+f.length+g.length<e&&a.ops.documents.length<t))break;o=1e3+a.nsInfo.push(p,f)+a.ops.push(m,g),s++,this.currentModelIndex++}}return this.lastOperations=a.ops.documents,a}baseCommand(){const e={bulkWrite:1,errorsOnly:this.errorsOnly,ordered:this.options.ordered??!0,ops:new o.DocumentSequence("ops"),nsInfo:new o.DocumentSequence("nsInfo")};return null!=this.options.bypassDocumentValidation&&(e.bypassDocumentValidation=this.options.bypassDocumentValidation),this.options.let&&(e.let=this.options.let),void 0!==this.options.comment&&(e.comment=this.options.comment),e}},t.buildInsertOneOperation=(e,t,r)=>{const n={insert:t,document:e.document};return n.document._id=e.document._id??r.createPk(),n},t.buildDeleteOneOperation=(e,t)=>u(e,t,!1),t.buildDeleteManyOperation=(e,t)=>u(e,t,!0),t.buildUpdateOneOperation=(e,t,r)=>l(e,t,!1,r),t.buildUpdateManyOperation=(e,t,r)=>l(e,t,!0,r),t.buildReplaceOneOperation=(e,t)=>{if((0,a.hasAtomicOperators)(e.replacement))throw new i.MongoAPIError("Client bulk write replace models must not contain atomic modifiers (start with $) and must not be empty.");const r={update:t,multi:!1,filter:e.filter,updateMods:e.replacement};return e.hint&&(r.hint=e.hint),e.upsert&&(r.upsert=e.upsert),e.collation&&(r.collation=e.collation),null!=e.sort&&(r.sort=(0,s.formatSort)(e.sort)),r}},13700:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ReadPreference=t.ReadPreferenceMode=void 0;const n=r(17562);t.ReadPreferenceMode=Object.freeze({primary:"primary",primaryPreferred:"primaryPreferred",secondary:"secondary",secondaryPreferred:"secondaryPreferred",nearest:"nearest"});class o{constructor(e,t,r){if(!o.isValid(e))throw new n.MongoInvalidArgumentError(`Invalid read preference mode ${JSON.stringify(e)}`);if(null!=r||"object"!=typeof t||Array.isArray(t)){if(t&&!Array.isArray(t))throw new n.MongoInvalidArgumentError("ReadPreference tags must be an array")}else r=t,t=void 0;if(this.mode=e,this.tags=t,this.hedge=r?.hedge,this.maxStalenessSeconds=void 0,this.minWireVersion=void 0,null!=(r=r??{}).maxStalenessSeconds){if(r.maxStalenessSeconds<=0)throw new n.MongoInvalidArgumentError("maxStalenessSeconds must be a positive integer");this.maxStalenessSeconds=r.maxStalenessSeconds,this.minWireVersion=5}if(this.mode===o.PRIMARY){if(this.tags&&Array.isArray(this.tags)&&this.tags.length>0)throw new n.MongoInvalidArgumentError("Primary read preference cannot be combined with tags");if(this.maxStalenessSeconds)throw new n.MongoInvalidArgumentError("Primary read preference cannot be combined with maxStalenessSeconds");if(this.hedge)throw new n.MongoInvalidArgumentError("Primary read preference cannot be combined with hedge")}}get preference(){return this.mode}static fromString(e){return new o(e)}static fromOptions(e){if(!e)return;const t=e.readPreference??e.session?.transaction.options.readPreference,r=e.readPreferenceTags;if(null!=t){if("string"==typeof t)return new o(t,r,{maxStalenessSeconds:e.maxStalenessSeconds,hedge:e.hedge});if(!(t instanceof o)&&"object"==typeof t){const n=t.mode||t.preference;if(n&&"string"==typeof n)return new o(n,t.tags??r,{maxStalenessSeconds:t.maxStalenessSeconds,hedge:e.hedge})}return r&&(t.tags=r),t}}static translate(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 n.MongoInvalidArgumentError(`Invalid read preference: ${t}`)}else{const r=t.mode||t.preference;r&&"string"==typeof r&&(e.readPreference=new o(r,t.tags,{maxStalenessSeconds:t.maxStalenessSeconds}))}return e}static isValid(e){return new Set([o.PRIMARY,o.PRIMARY_PREFERRED,o.SECONDARY,o.SECONDARY_PREFERRED,o.NEAREST,null]).has(e)}isValid(e){return o.isValid("string"==typeof e?e:this.mode)}secondaryOk(){return new Set([o.PRIMARY_PREFERRED,o.SECONDARY,o.SECONDARY_PREFERRED,o.NEAREST]).has(this.mode)}equals(e){return e.mode===this.mode}toJSON(){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}}t.ReadPreference=o,o.PRIMARY=t.ReadPreferenceMode.primary,o.PRIMARY_PREFERRED=t.ReadPreferenceMode.primaryPreferred,o.SECONDARY=t.ReadPreferenceMode.secondary,o.SECONDARY_PREFERRED=t.ReadPreferenceMode.secondaryPreferred,o.NEAREST=t.ReadPreferenceMode.nearest,o.primary=new o(t.ReadPreferenceMode.primary),o.primaryPreferred=new o(t.ReadPreferenceMode.primaryPreferred),o.secondary=new o(t.ReadPreferenceMode.secondary),o.secondaryPreferred=new o(t.ReadPreferenceMode.secondaryPreferred),o.nearest=new o(t.ReadPreferenceMode.nearest)},14019:(e,t,r)=>{var n=r(67787).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.ServerSessionPool=t.ServerSession=t.ClientSession=void 0,t.maybeClearPinnedConnection=v,t.applySession=function(e,t,r){if(e.hasEnded)return new c.MongoExpiredSessionError;const n=e.serverSession;if(null==n)return new c.MongoRuntimeError("Unable to acquire server session");if(0===r.writeConcern?.w)return e&&e.explicit?new c.MongoAPIError("Cannot have explicit session with unacknowledged writes"):void 0;n.lastUse=(0,S.now)(),t.lsid=n.id;const i=e.inTransaction()||(0,E.isTransactionCommand)(t);if((r.willRetryWrite||i)&&(n.txnNumber+=e.txnNumberIncrement,e.txnNumberIncrement=0,t.txnNumber=o.Long.fromNumber(n.txnNumber)),!i)return e.transaction.state!==E.TxnState.NO_TRANSACTION&&e.transaction.transition(E.TxnState.NO_TRANSACTION),void(e.supports.causalConsistency&&e.operationTime&&(0,S.commandSupportsReadConcern)(t)?(t.readConcern=t.readConcern||{},Object.assign(t.readConcern,{afterClusterTime:e.operationTime})):e.snapshotEnabled&&(t.readConcern=t.readConcern||{level:h.ReadConcernLevel.snapshot},null!=e.snapshotTime&&Object.assign(t.readConcern,{atClusterTime:e.snapshotTime})));if(t.autocommit=!1,e.transaction.state===E.TxnState.STARTING_TRANSACTION){e.transaction.transition(E.TxnState.TRANSACTION_IN_PROGRESS),t.startTransaction=!0;const r=e.transaction.options.readConcern||e?.clientOptions?.readConcern;r&&(t.readConcern=r),e.supports.causalConsistency&&e.operationTime&&(t.readConcern=t.readConcern||{},Object.assign(t.readConcern,{afterClusterTime:e.operationTime}))}},t.updateSessionFromResponse=function(e,t){if(t.$clusterTime&&(0,f._advanceClusterTime)(e,t.$clusterTime),t.operationTime&&e&&e.supports.causalConsistency&&e.advanceOperationTime(t.operationTime),t.recoveryToken&&e&&e.inTransaction()&&(e.transaction._recoveryToken=t.recoveryToken),e?.snapshotEnabled&&null==e.snapshotTime){const r=t.atClusterTime;r&&(e.snapshotTime=r)}};const o=r(75080),i=r(55741),s=r(61428),a=r(91869),c=r(17562),u=r(4642),l=r(96357),d=r(17668),h=r(28541),p=r(13700),m=r(31790),f=r(89167),g=r(7799),E=r(85759),S=r(145),O=r(40012);class y extends u.TypedEventEmitter{constructor(e,t,r,n){if(super(),this.timeoutContext=null,this.on("error",S.noop),null==e)throw new c.MongoRuntimeError("ClientSession requires a MongoClient");if(null==t||!(t instanceof R))throw new c.MongoRuntimeError("ClientSession requires a ServerSessionPool");if(r=r??{},this.snapshotEnabled=!0===r.snapshot,!0===r.causalConsistency&&this.snapshotEnabled)throw new c.MongoInvalidArgumentError('Properties "causalConsistency" and "snapshot" are mutually exclusive');this.client=e,this.sessionPool=t,this.hasEnded=!1,this.clientOptions=n,this.timeoutMS=r.defaultTimeoutMS??e.s.options?.timeoutMS,this.explicit=!!r.explicit,this._serverSession=this.explicit?this.sessionPool.acquire():null,this.txnNumberIncrement=0;const o=this.explicit&&!0!==r.snapshot;this.supports={causalConsistency:r.causalConsistency??o},this.clusterTime=r.initialClusterTime,this.operationTime=void 0,this.owner=r.owner,this.defaultTransactionOptions={...r.defaultTransactionOptions},this.transaction=new E.Transaction}get id(){return this.serverSession?.id}get serverSession(){let e=this._serverSession;if(null==e){if(this.explicit)throw new c.MongoRuntimeError("Unexpected null serverSession for an explicit session");if(this.hasEnded)throw new c.MongoRuntimeError("Unexpected null serverSession for an ended implicit session");e=this.sessionPool.acquire(),this._serverSession=e}return e}get loadBalanced(){return this.client.topology?.description.type===f.TopologyType.LoadBalanced}pin(e){if(this.pinnedConnection)throw TypeError("Cannot pin multiple connections to the same session");this.pinnedConnection=e,e.emit(a.PINNED,this.inTransaction()?i.ConnectionPoolMetrics.TXN:i.ConnectionPoolMetrics.CURSOR)}unpin(e){if(this.loadBalanced)return v(this,e);this.transaction.unpinServer()}get isPinned(){return this.loadBalanced?!!this.pinnedConnection:this.transaction.isPinned}async endSession(e){try{this.inTransaction()&&await this.abortTransaction({...e,throwTimeout:!0})}catch(e){if("MongoOperationTimeoutError"===e.name)throw e;(0,S.squashError)(e)}finally{if(!this.hasEnded){const e=this.serverSession;null!=e&&(this.sessionPool.release(e),this._serverSession=new _(e)),this.hasEnded=!0,this.emit("ended",this)}v(this,{force:!0,...e})}}async asyncDispose(){await this.endSession({force:!0})}advanceOperationTime(e){null!=this.operationTime?e.greaterThan(this.operationTime)&&(this.operationTime=e):this.operationTime=e}advanceClusterTime(e){if(!e||"object"!=typeof e)throw new c.MongoInvalidArgumentError("input cluster time must be an object");if(!e.clusterTime||"Timestamp"!==e.clusterTime._bsontype)throw new c.MongoInvalidArgumentError('input cluster time "clusterTime" property must be a valid BSON Timestamp');if(!e.signature||"Binary"!==e.signature.hash?._bsontype||"bigint"!=typeof e.signature.keyId&&"number"!=typeof e.signature.keyId&&"Long"!==e.signature.keyId?._bsontype)throw new c.MongoInvalidArgumentError('input cluster time must have a valid "signature" property with BSON Binary hash and BSON Long keyId');(0,f._advanceClusterTime)(this,e)}equals(e){return e instanceof y&&null!=this.id&&null!=e.id&&S.ByteUtils.equals(this.id.id.buffer,e.id.id.buffer)}incrementTransactionNumber(){this.txnNumberIncrement+=1}inTransaction(){return this.transaction.isActive}startTransaction(e){if(this.snapshotEnabled)throw new c.MongoCompatibilityError("Transactions are not supported in snapshot sessions");if(this.inTransaction())throw new c.MongoTransactionError("Transaction already in progress");this.isPinned&&this.transaction.isCommitted&&this.unpin();const t=(0,S.maxWireVersion)(this.client.topology);if((0,s.isSharded)(this.client.topology)&&null!=t&&t<8)throw new c.MongoCompatibilityError("Transactions are not supported on sharded clusters in MongoDB < 4.2.");this.commitAttempted=!1,this.incrementTransactionNumber(),this.transaction=new E.Transaction({readConcern:e?.readConcern??this.defaultTransactionOptions.readConcern??this.clientOptions?.readConcern,writeConcern:e?.writeConcern??this.defaultTransactionOptions.writeConcern??this.clientOptions?.writeConcern,readPreference:e?.readPreference??this.defaultTransactionOptions.readPreference??this.clientOptions?.readPreference,maxCommitTimeMS:e?.maxCommitTimeMS??this.defaultTransactionOptions.maxCommitTimeMS}),this.transaction.transition(E.TxnState.STARTING_TRANSACTION)}async commitTransaction(e){if(this.transaction.state===E.TxnState.NO_TRANSACTION)throw new c.MongoTransactionError("No transaction started");if(this.transaction.state===E.TxnState.STARTING_TRANSACTION||this.transaction.state===E.TxnState.TRANSACTION_COMMITTED_EMPTY)return void this.transaction.transition(E.TxnState.TRANSACTION_COMMITTED_EMPTY);if(this.transaction.state===E.TxnState.TRANSACTION_ABORTED)throw new c.MongoTransactionError("Cannot call commitTransaction after calling abortTransaction");const t={commitTransaction:1},r="number"==typeof e?.timeoutMS?e.timeoutMS:"number"==typeof this.timeoutMS?this.timeoutMS:null,n=this.transaction.options.writeConcern??this.clientOptions?.writeConcern;if(null!=n)if(null==r&&null==this.timeoutContext)O.WriteConcern.apply(t,{wtimeoutMS:1e4,w:"majority",...n});else{const e=Object.keys(n);(e.length>2||!e.includes("wtimeoutMS")&&!e.includes("wTimeoutMS"))&&O.WriteConcern.apply(t,{...n,wtimeoutMS:void 0})}(this.transaction.state===E.TxnState.TRANSACTION_COMMITTED||this.commitAttempted)&&(null==r&&null==this.timeoutContext?O.WriteConcern.apply(t,{wtimeoutMS:1e4,...n,w:"majority"}):O.WriteConcern.apply(t,{w:"majority",...n,wtimeoutMS:void 0})),"number"==typeof this.transaction.options.maxTimeMS&&(t.maxTimeMS=this.transaction.options.maxTimeMS),this.transaction.recoveryToken&&(t.recoveryToken=this.transaction.recoveryToken);const o=new d.RunCommandOperation(new S.MongoDBNamespace("admin"),t,{session:this,readPreference:p.ReadPreference.primary,bypassPinningCheck:!0}),i=this.timeoutContext??("number"==typeof r?g.TimeoutContext.create({serverSelectionTimeoutMS:this.clientOptions.serverSelectionTimeoutMS,socketTimeoutMS:this.clientOptions.socketTimeoutMS,timeoutMS:r}):null);try{return await(0,l.executeOperation)(this.client,o,i),void(this.commitAttempted=void 0)}catch(e){if(this.commitAttempted=!0,e instanceof c.MongoError&&(0,c.isRetryableWriteError)(e)){O.WriteConcern.apply(t,{wtimeoutMS:1e4,...n,w:"majority"}),this.unpin({force:!0});try{return void await(0,l.executeOperation)(this.client,new d.RunCommandOperation(new S.MongoDBNamespace("admin"),t,{session:this,readPreference:p.ReadPreference.primary,bypassPinningCheck:!0}),i)}catch(e){throw T(e)&&e.addErrorLabel(c.MongoErrorLabel.UnknownTransactionCommitResult),M(e)&&this.unpin({error:e}),e}}throw T(e)&&e.addErrorLabel(c.MongoErrorLabel.UnknownTransactionCommitResult),M(e)&&this.unpin({error:e}),e}finally{this.transaction.transition(E.TxnState.TRANSACTION_COMMITTED)}}async abortTransaction(e){if(this.transaction.state===E.TxnState.NO_TRANSACTION)throw new c.MongoTransactionError("No transaction started");if(this.transaction.state===E.TxnState.STARTING_TRANSACTION)return void this.transaction.transition(E.TxnState.TRANSACTION_ABORTED);if(this.transaction.state===E.TxnState.TRANSACTION_ABORTED)throw new c.MongoTransactionError("Cannot call abortTransaction twice");if(this.transaction.state===E.TxnState.TRANSACTION_COMMITTED||this.transaction.state===E.TxnState.TRANSACTION_COMMITTED_EMPTY)throw new c.MongoTransactionError("Cannot call abortTransaction after calling commitTransaction");const t={abortTransaction:1},r="number"==typeof e?.timeoutMS?e.timeoutMS:this.timeoutContext?.csotEnabled()?this.timeoutContext.timeoutMS:"number"==typeof this.timeoutMS?this.timeoutMS:null,n=null!=r?g.TimeoutContext.create({timeoutMS:r,serverSelectionTimeoutMS:this.clientOptions.serverSelectionTimeoutMS,socketTimeoutMS:this.clientOptions.socketTimeoutMS}):null,o=this.transaction.options.writeConcern??this.clientOptions?.writeConcern;null!=o&&null==r&&O.WriteConcern.apply(t,{wtimeoutMS:1e4,w:"majority",...o}),this.transaction.recoveryToken&&(t.recoveryToken=this.transaction.recoveryToken);const i=new d.RunCommandOperation(new S.MongoDBNamespace("admin"),t,{session:this,readPreference:p.ReadPreference.primary,bypassPinningCheck:!0});try{return await(0,l.executeOperation)(this.client,i,n),void this.unpin()}catch(t){if(this.unpin(),"MongoRuntimeError"===t.name)throw t;if(e?.throwTimeout&&"MongoOperationTimeoutError"===t.name)throw t;if(t instanceof c.MongoError&&(0,c.isRetryableWriteError)(t))try{return void await(0,l.executeOperation)(this.client,i,n)}catch(t){if("MongoRuntimeError"===t.name)throw t;if(e?.throwTimeout&&"MongoOperationTimeoutError"===t.name)throw t}}finally{this.transaction.transition(E.TxnState.TRANSACTION_ABORTED),this.loadBalanced&&v(this,{force:!1})}}toBSON(){throw new c.MongoRuntimeError("ClientSession cannot be serialized to BSON.")}async withTransaction(e,t){const r=12e4,n=t?.timeoutMS??this.timeoutMS??null;this.timeoutContext=null!=n?g.TimeoutContext.create({timeoutMS:n,serverSelectionTimeoutMS:this.clientOptions.serverSelectionTimeoutMS,socketTimeoutMS:this.clientOptions.socketTimeoutMS}):null;const o=this.timeoutContext?.csotEnabled()?this.timeoutContext.start:(0,S.now)();let i,s=!1;try{for(;!s;){this.startTransaction(t);try{const t=e(this);if(!(0,S.isPromiseLike)(t))throw new c.MongoInvalidArgumentError("Function provided to `withTransaction` must return a Promise");if(i=await t,this.transaction.state===E.TxnState.NO_TRANSACTION||this.transaction.state===E.TxnState.TRANSACTION_COMMITTED||this.transaction.state===E.TxnState.TRANSACTION_ABORTED)return i}catch(e){if(!(e instanceof c.MongoError)||e instanceof c.MongoInvalidArgumentError)throw await this.abortTransaction(),e;if(this.transaction.state!==E.TxnState.STARTING_TRANSACTION&&this.transaction.state!==E.TxnState.TRANSACTION_IN_PROGRESS||await this.abortTransaction(),e.hasErrorLabel(c.MongoErrorLabel.TransientTransactionError)&&(null!=this.timeoutContext||(0,S.now)()-o<r))continue;throw e}for(;!s;)try{await this.commitTransaction(),s=!0}catch(e){if(!b(e)&&e.hasErrorLabel(c.MongoErrorLabel.UnknownTransactionCommitResult)&&(null!=this.timeoutContext||(0,S.now)()-o<r))continue;if(e.hasErrorLabel(c.MongoErrorLabel.TransientTransactionError)&&(null!=this.timeoutContext||(0,S.now)()-o<r))break;throw e}}return i}finally{this.timeoutContext=null}}}t.ClientSession=y,(0,m.configureResourceManagement)(y.prototype);const C=new Set(["CannotSatisfyWriteConcern","UnknownReplWriteConcern","UnsatisfiableWriteConcern"]);function M(e){if(e instanceof c.MongoError)if((0,c.isRetryableWriteError)(e)||e instanceof c.MongoWriteConcernError||b(e)){if(w(e))return!0}else if(e.hasErrorLabel(c.MongoErrorLabel.TransientTransactionError))return!0;return!1}function T(e){let t=(0,c.isRetryableWriteError)(e);return t||=e instanceof c.MongoWriteConcernError,t||=b(e),t&&=w(e),t}function w(e){const t=e instanceof c.MongoServerError&&e.codeName&&C.has(e.codeName);return b(e)||!t&&e.code!==c.MONGODB_ERROR_CODES.UnsatisfiableWriteConcern&&e.code!==c.MONGODB_ERROR_CODES.UnknownReplWriteConcern}function v(e,t){const r=e.pinnedConnection,n=t?.error;if(e.inTransaction()&&n&&n instanceof c.MongoError&&n.hasErrorLabel(c.MongoErrorLabel.TransientTransactionError))return;const o=e.client.topology;if(r&&null!=o){const n=Array.from(o.s.servers.values())[0];(null==t?.error||t?.force)&&(n.pool.checkIn(r),e.pinnedConnection=void 0,r.emit(a.UNPINNED,e.transaction.state!==E.TxnState.NO_TRANSACTION?i.ConnectionPoolMetrics.TXN:i.ConnectionPoolMetrics.CURSOR),t?.forceClear&&n.pool.clear({serviceId:r.serviceId}))}}function b(e){return null!=e&&e instanceof c.MongoServerError&&(e.code===c.MONGODB_ERROR_CODES.MaxTimeMSExpired||e.writeConcernError?.code===c.MONGODB_ERROR_CODES.MaxTimeMSExpired)}class _{constructor(e){if(null!=e){const t=n.allocUnsafe(16);return t.set(e.id.id.buffer),this.id={id:new o.Binary(t,e.id.id.sub_type)},this.lastUse=e.lastUse,this.txnNumber=e.txnNumber,void(this.isDirty=e.isDirty)}this.id={id:new o.Binary((0,S.uuidV4)(),o.Binary.SUBTYPE_UUID)},this.lastUse=(0,S.now)(),this.txnNumber=0,this.isDirty=!1}hasTimedOut(e){return Math.round((0,S.calculateDurationInMs)(this.lastUse)%864e5%36e5/6e4)>e-1}}t.ServerSession=_;class R{constructor(e){if(null==e)throw new c.MongoRuntimeError("ServerSessionPool requires a MongoClient");this.client=e,this.sessions=new S.List}acquire(){const e=this.client.topology?.logicalSessionTimeoutMinutes??10;let t=null;for(;this.sessions.length>0;){const r=this.sessions.shift();if(null!=r&&(this.client.topology?.loadBalanced||!r.hasTimedOut(e))){t=r;break}}return null==t&&(t=new _),t}release(e){const t=this.client.topology?.logicalSessionTimeoutMinutes??10;if(this.client.topology?.loadBalanced&&!t&&this.sessions.unshift(e),t&&(this.sessions.prune((e=>e.hasTimedOut(t))),!e.hasTimedOut(t))){if(e.isDirty)return;this.sessions.unshift(e)}}}t.ServerSessionPool=R},15620:(e,t,r)=>{var n=r(67787).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.OpCompressedRequest=t.OpMsgResponse=t.OpMsgRequest=t.DocumentSequence=t.OpReply=t.OpQueryRequest=void 0;const o=r(75080),i=r(17562),s=r(64515),a=r(96856);let c=0;const u=o.BSON.onDemand.ByteUtils.encodeUTF8Into;class l{constructor(e,t,r){this.moreToCome=!1;const n=`${e}.$cmd`;if("string"!=typeof e)throw new i.MongoRuntimeError("Database name must be a string for a query");if(null==t)throw new i.MongoRuntimeError("A query document must be specified for query");if(-1!==n.indexOf("\0"))throw new i.MongoRuntimeError("Namespace cannot contain a null character");this.databaseName=e,this.query=t,this.ns=n,this.numberToSkip=r.numberToSkip||0,this.numberToReturn=r.numberToReturn||0,this.returnFieldSelector=r.returnFieldSelector||void 0,this.requestId=r.requestId??l.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.secondaryOk="boolean"==typeof r.secondaryOk&&r.secondaryOk,this.oplogReplay=!1,this.noCursorTimeout=!1,this.awaitData=!1,this.exhaust=!1,this.partial=!1}incRequestId(){this.requestId=c++}nextRequestId(){return c+1}static getRequestId(){return++c}toBin(){const e=[];let t=null,r=0;this.tailable&&(r|=2),this.secondaryOk&&(r|=4),this.oplogReplay&&(r|=8),this.noCursorTimeout&&(r|=16),this.awaitData&&(r|=32),this.exhaust&&(r|=64),this.partial&&(r|=128),this.batchSize!==this.numberToReturn&&(this.numberToReturn=this.batchSize);const i=n.alloc(20+n.byteLength(this.ns)+1+4+4);e.push(i);const s=o.serialize(this.query,{checkKeys:this.checkKeys,serializeFunctions:this.serializeFunctions,ignoreUndefined:this.ignoreUndefined});e.push(s),this.returnFieldSelector&&Object.keys(this.returnFieldSelector).length>0&&(t=o.serialize(this.returnFieldSelector,{checkKeys:this.checkKeys,serializeFunctions:this.serializeFunctions,ignoreUndefined:this.ignoreUndefined}),e.push(t));const c=i.length+s.length+(t?t.length:0);let u=4;return i[3]=c>>24&255,i[2]=c>>16&255,i[1]=c>>8&255,i[0]=255&c,i[u+3]=this.requestId>>24&255,i[u+2]=this.requestId>>16&255,i[u+1]=this.requestId>>8&255,i[u]=255&this.requestId,u+=4,i[u+3]=0,i[u+2]=0,i[u+1]=0,i[u]=0,u+=4,i[u+3]=a.OP_QUERY>>24&255,i[u+2]=a.OP_QUERY>>16&255,i[u+1]=a.OP_QUERY>>8&255,i[u]=255&a.OP_QUERY,u+=4,i[u+3]=r>>24&255,i[u+2]=r>>16&255,i[u+1]=r>>8&255,i[u]=255&r,u+=4,u=u+i.write(this.ns,u,"utf8")+1,i[u-1]=0,i[u+3]=this.numberToSkip>>24&255,i[u+2]=this.numberToSkip>>16&255,i[u+1]=this.numberToSkip>>8&255,i[u]=255&this.numberToSkip,u+=4,i[u+3]=this.numberToReturn>>24&255,i[u+2]=this.numberToReturn>>16&255,i[u+1]=this.numberToReturn>>8&255,i[u]=255&this.numberToReturn,u+=4,e}}t.OpQueryRequest=l,t.OpReply=class{constructor(e,t,r,n){this.index=0,this.sections=[],this.moreToCome=!1,this.parsed=!1,this.raw=e,this.data=r,this.opts=n??{useBigInt64:!1,promoteLongs:!0,promoteValues:!0,promoteBuffers:!1,bsonRegExp:!1},this.length=t.length,this.requestId=t.requestId,this.responseTo=t.responseTo,this.opCode=t.opCode,this.fromCompressed=t.fromCompressed,this.useBigInt64="boolean"==typeof this.opts.useBigInt64&&this.opts.useBigInt64,this.promoteLongs="boolean"!=typeof this.opts.promoteLongs||this.opts.promoteLongs,this.promoteValues="boolean"!=typeof this.opts.promoteValues||this.opts.promoteValues,this.promoteBuffers="boolean"==typeof this.opts.promoteBuffers&&this.opts.promoteBuffers,this.bsonRegExp="boolean"==typeof this.opts.bsonRegExp&&this.opts.bsonRegExp}isParsed(){return this.parsed}parse(){if(this.parsed)return this.sections[0];if(this.index=20,this.responseFlags=this.data.readInt32LE(0),this.cursorId=new o.Long(this.data.readInt32LE(4),this.data.readInt32LE(8)),this.startingFrom=this.data.readInt32LE(12),this.numberReturned=this.data.readInt32LE(16),this.numberReturned<0||this.numberReturned>2**32-1)throw new RangeError(`OP_REPLY numberReturned is an invalid array length ${this.numberReturned}`);this.cursorNotFound=!!(1&this.responseFlags),this.queryFailure=!!(2&this.responseFlags),this.shardConfigStale=!!(4&this.responseFlags),this.awaitCapable=!!(8&this.responseFlags);for(let e=0;e<this.numberReturned;e++){const e=this.data[this.index]|this.data[this.index+1]<<8|this.data[this.index+2]<<16|this.data[this.index+3]<<24,t=this.data.subarray(this.index,this.index+e);this.sections.push(t),this.index=this.index+e}return this.parsed=!0,this.sections[0]}};class d{constructor(e,t){this.field=e,this.documents=[],this.chunks=[],this.serializedDocumentsLength=0;const r=n.allocUnsafe(5+this.field.length+1);if(r[0]=1,u(r,`${this.field}\0`,5),this.chunks.push(r),this.header=r,t)for(const e of t)this.push(e,o.serialize(e))}push(e,t){return this.serializedDocumentsLength+=t.length,this.documents.push(e),this.chunks.push(t),this.header?.writeInt32LE(4+this.field.length+1+this.serializedDocumentsLength,1),this.serializedDocumentsLength+this.header.length}toBin(){return n.concat(this.chunks)}}t.DocumentSequence=d;class h{constructor(e,t,r){if(null==t)throw new i.MongoInvalidArgumentError("Query document must be specified for query");this.databaseName=e,this.command=t,this.command.$db=e,this.options=r??{},this.requestId=r.requestId?r.requestId:h.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??0===t.writeConcern?.w,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 r=n.alloc(20);e.push(r);let o=r.length;const i=this.command;return o+=this.makeSections(e,i),r.writeInt32LE(o,0),r.writeInt32LE(this.requestId,4),r.writeInt32LE(0,8),r.writeInt32LE(a.OP_MSG,12),r.writeUInt32LE(t,16),e}makeSections(e,t){const r=this.extractDocumentSequences(t),o=n.allocUnsafe(1);o[0]=0;const i=this.serializeBson(t);return e.push(o),e.push(i),e.push(r),o.length+i.length+r.length}extractDocumentSequences(e){const t=[];for(const[r,n]of Object.entries(e))n instanceof d&&(t.push(n.toBin()),delete e[r]);return t.length>0?n.concat(t):n.alloc(0)}serializeBson(e){return o.serialize(e,{checkKeys:this.checkKeys,serializeFunctions:this.serializeFunctions,ignoreUndefined:this.ignoreUndefined})}static getRequestId(){return c=c+1&2147483647,c}}t.OpMsgRequest=h,t.OpMsgResponse=class{constructor(e,t,r,n){this.index=0,this.sections=[],this.parsed=!1,this.raw=e,this.data=r,this.opts=n??{useBigInt64:!1,promoteLongs:!0,promoteValues:!0,promoteBuffers:!1,bsonRegExp:!1},this.length=t.length,this.requestId=t.requestId,this.responseTo=t.responseTo,this.opCode=t.opCode,this.fromCompressed=t.fromCompressed,this.responseFlags=r.readInt32LE(0),this.checksumPresent=!!(1&this.responseFlags),this.moreToCome=!!(2&this.responseFlags),this.exhaustAllowed=!!(65536&this.responseFlags),this.useBigInt64="boolean"==typeof this.opts.useBigInt64&&this.opts.useBigInt64,this.promoteLongs="boolean"!=typeof this.opts.promoteLongs||this.opts.promoteLongs,this.promoteValues="boolean"!=typeof this.opts.promoteValues||this.opts.promoteValues,this.promoteBuffers="boolean"==typeof this.opts.promoteBuffers&&this.opts.promoteBuffers,this.bsonRegExp="boolean"==typeof this.opts.bsonRegExp&&this.opts.bsonRegExp}isParsed(){return this.parsed}parse(){if(this.parsed)return this.sections[0];for(this.index=4;this.index<this.data.length;){const e=this.data.readUInt8(this.index++);if(0===e){const e=this.data.readUInt32LE(this.index),t=this.data.subarray(this.index,this.index+e);this.sections.push(t),this.index+=e}else if(1===e)throw new i.MongoRuntimeError("OP_MSG Payload Type 1 detected unsupported protocol")}return this.parsed=!0,this.sections[0]}},t.OpCompressedRequest=class{constructor(e,t){this.command=e,this.options={zlibCompressionLevel:t.zlibCompressionLevel,agreedCompressor:t.agreedCompressor}}static canCompress(e){const t=e instanceof h?e.command:e.query,r=Object.keys(t)[0];return!s.uncompressibleCommands.has(r)}async toBin(){const e=n.concat(this.command.toBin()),t=e.slice(16),r=e.readInt32LE(12),o=await(0,s.compress)(this.options,t),i=n.alloc(16);i.writeInt32LE(25+o.length,0),i.writeInt32LE(this.command.requestId,4),i.writeInt32LE(0,8),i.writeInt32LE(a.OP_COMPRESSED,12);const c=n.alloc(9);return c.writeInt32LE(r,0),c.writeInt32LE(t.length,4),c.writeUInt8(s.Compressor[this.options.agreedCompressor],8),[i,c,o]}}},16360:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MongoRuntimeError=t.MongoParseError=t.MongoOperationTimeoutError=t.MongoOIDCError=t.MongoNotConnectedError=t.MongoNetworkTimeoutError=t.MongoNetworkError=t.MongoMissingDependencyError=t.MongoMissingCredentialsError=t.MongoKerberosError=t.MongoInvalidArgumentError=t.MongoGridFSStreamError=t.MongoGridFSChunkError=t.MongoGCPError=t.MongoExpiredSessionError=t.MongoError=t.MongoDriverError=t.MongoDecompressionError=t.MongoCursorInUseError=t.MongoCursorExhaustedError=t.MongoCompatibilityError=t.MongoClientClosedError=t.MongoClientBulkWriteExecutionError=t.MongoClientBulkWriteError=t.MongoClientBulkWriteCursorError=t.MongoChangeStreamError=t.MongoBatchReExecutionError=t.MongoAzureError=t.MongoAWSError=t.MongoAPIError=t.ExplainableCursor=t.ChangeStreamCursor=t.ClientEncryption=t.MongoBulkWriteError=t.UUID=t.Timestamp=t.ObjectId=t.MinKey=t.MaxKey=t.Long=t.Int32=t.Double=t.Decimal128=t.DBRef=t.Code=t.BSONType=t.BSONSymbol=t.BSONRegExp=t.Binary=t.BSON=void 0,t.CommandFailedEvent=t.WriteConcern=t.ReadPreference=t.ReadConcern=t.TopologyType=t.ServerType=t.ReadPreferenceMode=t.ReadConcernLevel=t.ProfilingLevel=t.ReturnDocument=t.SeverityLevel=t.MongoLoggableComponent=t.ServerApiVersion=t.ExplainVerbosity=t.MongoErrorLabel=t.CursorTimeoutMode=t.CURSOR_FLAGS=t.Compressor=t.AuthMechanism=t.GSSAPICanonicalizationValue=t.AutoEncryptionLoggerLevel=t.BatchType=t.UnorderedBulkOperation=t.OrderedBulkOperation=t.MongoClient=t.ListIndexesCursor=t.ListCollectionsCursor=t.GridFSBucketWriteStream=t.GridFSBucketReadStream=t.GridFSBucket=t.FindCursor=t.Db=t.Collection=t.ClientSession=t.ChangeStream=t.CancellationToken=t.AggregationCursor=t.Admin=t.AbstractCursor=t.configureExplicitResourceManagement=t.MongoWriteConcernError=t.MongoUnexpectedServerResponseError=t.MongoTransactionError=t.MongoTopologyClosedError=t.MongoTailableCursorError=t.MongoSystemError=t.MongoStalePrimaryError=t.MongoServerSelectionError=t.MongoServerError=t.MongoServerClosedError=void 0,t.MongoClientAuthProviders=t.MongoCryptKMSRequestNetworkTimeoutError=t.MongoCryptInvalidArgumentError=t.MongoCryptError=t.MongoCryptCreateEncryptedCollectionError=t.MongoCryptCreateDataKeyError=t.MongoCryptAzureKMSRequestError=t.SrvPollingEvent=t.WaitingForSuitableServerEvent=t.ServerSelectionSucceededEvent=t.ServerSelectionStartedEvent=t.ServerSelectionFailedEvent=t.ServerSelectionEvent=t.TopologyOpeningEvent=t.TopologyDescriptionChangedEvent=t.TopologyClosedEvent=t.ServerOpeningEvent=t.ServerHeartbeatSucceededEvent=t.ServerHeartbeatStartedEvent=t.ServerHeartbeatFailedEvent=t.ServerDescriptionChangedEvent=t.ServerClosedEvent=t.ConnectionReadyEvent=t.ConnectionPoolReadyEvent=t.ConnectionPoolMonitoringEvent=t.ConnectionPoolCreatedEvent=t.ConnectionPoolClosedEvent=t.ConnectionPoolClearedEvent=t.ConnectionCreatedEvent=t.ConnectionClosedEvent=t.ConnectionCheckOutStartedEvent=t.ConnectionCheckOutFailedEvent=t.ConnectionCheckedOutEvent=t.ConnectionCheckedInEvent=t.CommandSucceededEvent=t.CommandStartedEvent=void 0;const n=r(71235);Object.defineProperty(t,"Admin",{enumerable:!0,get:function(){return n.Admin}});const o=r(29348);Object.defineProperty(t,"OrderedBulkOperation",{enumerable:!0,get:function(){return o.OrderedBulkOperation}});const i=r(10089);Object.defineProperty(t,"UnorderedBulkOperation",{enumerable:!0,get:function(){return i.UnorderedBulkOperation}});const s=r(22345);Object.defineProperty(t,"ChangeStream",{enumerable:!0,get:function(){return s.ChangeStream}});const a=r(19498);Object.defineProperty(t,"Collection",{enumerable:!0,get:function(){return a.Collection}});const c=r(61066);Object.defineProperty(t,"AbstractCursor",{enumerable:!0,get:function(){return c.AbstractCursor}});const u=r(68526);Object.defineProperty(t,"AggregationCursor",{enumerable:!0,get:function(){return u.AggregationCursor}});const l=r(5465);Object.defineProperty(t,"FindCursor",{enumerable:!0,get:function(){return l.FindCursor}});const d=r(55546);Object.defineProperty(t,"ListCollectionsCursor",{enumerable:!0,get:function(){return d.ListCollectionsCursor}});const h=r(32361);Object.defineProperty(t,"ListIndexesCursor",{enumerable:!0,get:function(){return h.ListIndexesCursor}});const p=r(44120);Object.defineProperty(t,"Db",{enumerable:!0,get:function(){return p.Db}});const m=r(74158);Object.defineProperty(t,"GridFSBucket",{enumerable:!0,get:function(){return m.GridFSBucket}});const f=r(33104);Object.defineProperty(t,"GridFSBucketReadStream",{enumerable:!0,get:function(){return f.GridFSBucketReadStream}});const g=r(10557);Object.defineProperty(t,"GridFSBucketWriteStream",{enumerable:!0,get:function(){return g.GridFSBucketWriteStream}});const E=r(22220);Object.defineProperty(t,"MongoClient",{enumerable:!0,get:function(){return E.MongoClient}});const S=r(4642);Object.defineProperty(t,"CancellationToken",{enumerable:!0,get:function(){return S.CancellationToken}});const O=r(14019);Object.defineProperty(t,"ClientSession",{enumerable:!0,get:function(){return O.ClientSession}});var y=r(75080);Object.defineProperty(t,"BSON",{enumerable:!0,get:function(){return y.BSON}});var C=r(75080);Object.defineProperty(t,"Binary",{enumerable:!0,get:function(){return C.Binary}}),Object.defineProperty(t,"BSONRegExp",{enumerable:!0,get:function(){return C.BSONRegExp}}),Object.defineProperty(t,"BSONSymbol",{enumerable:!0,get:function(){return C.BSONSymbol}}),Object.defineProperty(t,"BSONType",{enumerable:!0,get:function(){return C.BSONType}}),Object.defineProperty(t,"Code",{enumerable:!0,get:function(){return C.Code}}),Object.defineProperty(t,"DBRef",{enumerable:!0,get:function(){return C.DBRef}}),Object.defineProperty(t,"Decimal128",{enumerable:!0,get:function(){return C.Decimal128}}),Object.defineProperty(t,"Double",{enumerable:!0,get:function(){return C.Double}}),Object.defineProperty(t,"Int32",{enumerable:!0,get:function(){return C.Int32}}),Object.defineProperty(t,"Long",{enumerable:!0,get:function(){return C.Long}}),Object.defineProperty(t,"MaxKey",{enumerable:!0,get:function(){return C.MaxKey}}),Object.defineProperty(t,"MinKey",{enumerable:!0,get:function(){return C.MinKey}}),Object.defineProperty(t,"ObjectId",{enumerable:!0,get:function(){return C.ObjectId}}),Object.defineProperty(t,"Timestamp",{enumerable:!0,get:function(){return C.Timestamp}}),Object.defineProperty(t,"UUID",{enumerable:!0,get:function(){return C.UUID}});var M=r(54564);Object.defineProperty(t,"MongoBulkWriteError",{enumerable:!0,get:function(){return M.MongoBulkWriteError}});var T=r(73357);Object.defineProperty(t,"ClientEncryption",{enumerable:!0,get:function(){return T.ClientEncryption}});var w=r(40251);Object.defineProperty(t,"ChangeStreamCursor",{enumerable:!0,get:function(){return w.ChangeStreamCursor}});var v=r(36649);Object.defineProperty(t,"ExplainableCursor",{enumerable:!0,get:function(){return v.ExplainableCursor}});var b=r(17562);Object.defineProperty(t,"MongoAPIError",{enumerable:!0,get:function(){return b.MongoAPIError}}),Object.defineProperty(t,"MongoAWSError",{enumerable:!0,get:function(){return b.MongoAWSError}}),Object.defineProperty(t,"MongoAzureError",{enumerable:!0,get:function(){return b.MongoAzureError}}),Object.defineProperty(t,"MongoBatchReExecutionError",{enumerable:!0,get:function(){return b.MongoBatchReExecutionError}}),Object.defineProperty(t,"MongoChangeStreamError",{enumerable:!0,get:function(){return b.MongoChangeStreamError}}),Object.defineProperty(t,"MongoClientBulkWriteCursorError",{enumerable:!0,get:function(){return b.MongoClientBulkWriteCursorError}}),Object.defineProperty(t,"MongoClientBulkWriteError",{enumerable:!0,get:function(){return b.MongoClientBulkWriteError}}),Object.defineProperty(t,"MongoClientBulkWriteExecutionError",{enumerable:!0,get:function(){return b.MongoClientBulkWriteExecutionError}}),Object.defineProperty(t,"MongoClientClosedError",{enumerable:!0,get:function(){return b.MongoClientClosedError}}),Object.defineProperty(t,"MongoCompatibilityError",{enumerable:!0,get:function(){return b.MongoCompatibilityError}}),Object.defineProperty(t,"MongoCursorExhaustedError",{enumerable:!0,get:function(){return b.MongoCursorExhaustedError}}),Object.defineProperty(t,"MongoCursorInUseError",{enumerable:!0,get:function(){return b.MongoCursorInUseError}}),Object.defineProperty(t,"MongoDecompressionError",{enumerable:!0,get:function(){return b.MongoDecompressionError}}),Object.defineProperty(t,"MongoDriverError",{enumerable:!0,get:function(){return b.MongoDriverError}}),Object.defineProperty(t,"MongoError",{enumerable:!0,get:function(){return b.MongoError}}),Object.defineProperty(t,"MongoExpiredSessionError",{enumerable:!0,get:function(){return b.MongoExpiredSessionError}}),Object.defineProperty(t,"MongoGCPError",{enumerable:!0,get:function(){return b.MongoGCPError}}),Object.defineProperty(t,"MongoGridFSChunkError",{enumerable:!0,get:function(){return b.MongoGridFSChunkError}}),Object.defineProperty(t,"MongoGridFSStreamError",{enumerable:!0,get:function(){return b.MongoGridFSStreamError}}),Object.defineProperty(t,"MongoInvalidArgumentError",{enumerable:!0,get:function(){return b.MongoInvalidArgumentError}}),Object.defineProperty(t,"MongoKerberosError",{enumerable:!0,get:function(){return b.MongoKerberosError}}),Object.defineProperty(t,"MongoMissingCredentialsError",{enumerable:!0,get:function(){return b.MongoMissingCredentialsError}}),Object.defineProperty(t,"MongoMissingDependencyError",{enumerable:!0,get:function(){return b.MongoMissingDependencyError}}),Object.defineProperty(t,"MongoNetworkError",{enumerable:!0,get:function(){return b.MongoNetworkError}}),Object.defineProperty(t,"MongoNetworkTimeoutError",{enumerable:!0,get:function(){return b.MongoNetworkTimeoutError}}),Object.defineProperty(t,"MongoNotConnectedError",{enumerable:!0,get:function(){return b.MongoNotConnectedError}}),Object.defineProperty(t,"MongoOIDCError",{enumerable:!0,get:function(){return b.MongoOIDCError}}),Object.defineProperty(t,"MongoOperationTimeoutError",{enumerable:!0,get:function(){return b.MongoOperationTimeoutError}}),Object.defineProperty(t,"MongoParseError",{enumerable:!0,get:function(){return b.MongoParseError}}),Object.defineProperty(t,"MongoRuntimeError",{enumerable:!0,get:function(){return b.MongoRuntimeError}}),Object.defineProperty(t,"MongoServerClosedError",{enumerable:!0,get:function(){return b.MongoServerClosedError}}),Object.defineProperty(t,"MongoServerError",{enumerable:!0,get:function(){return b.MongoServerError}}),Object.defineProperty(t,"MongoServerSelectionError",{enumerable:!0,get:function(){return b.MongoServerSelectionError}}),Object.defineProperty(t,"MongoStalePrimaryError",{enumerable:!0,get:function(){return b.MongoStalePrimaryError}}),Object.defineProperty(t,"MongoSystemError",{enumerable:!0,get:function(){return b.MongoSystemError}}),Object.defineProperty(t,"MongoTailableCursorError",{enumerable:!0,get:function(){return b.MongoTailableCursorError}}),Object.defineProperty(t,"MongoTopologyClosedError",{enumerable:!0,get:function(){return b.MongoTopologyClosedError}}),Object.defineProperty(t,"MongoTransactionError",{enumerable:!0,get:function(){return b.MongoTransactionError}}),Object.defineProperty(t,"MongoUnexpectedServerResponseError",{enumerable:!0,get:function(){return b.MongoUnexpectedServerResponseError}}),Object.defineProperty(t,"MongoWriteConcernError",{enumerable:!0,get:function(){return b.MongoWriteConcernError}});var _=r(31790);Object.defineProperty(t,"configureExplicitResourceManagement",{enumerable:!0,get:function(){return _.configureExplicitResourceManagement}});var R=r(54564);Object.defineProperty(t,"BatchType",{enumerable:!0,get:function(){return R.BatchType}});var A=r(70136);Object.defineProperty(t,"AutoEncryptionLoggerLevel",{enumerable:!0,get:function(){return A.AutoEncryptionLoggerLevel}});var N=r(95750);Object.defineProperty(t,"GSSAPICanonicalizationValue",{enumerable:!0,get:function(){return N.GSSAPICanonicalizationValue}});var I=r(93065);Object.defineProperty(t,"AuthMechanism",{enumerable:!0,get:function(){return I.AuthMechanism}});var P=r(64515);Object.defineProperty(t,"Compressor",{enumerable:!0,get:function(){return P.Compressor}});var x=r(61066);Object.defineProperty(t,"CURSOR_FLAGS",{enumerable:!0,get:function(){return x.CURSOR_FLAGS}}),Object.defineProperty(t,"CursorTimeoutMode",{enumerable:!0,get:function(){return x.CursorTimeoutMode}});var D=r(17562);Object.defineProperty(t,"MongoErrorLabel",{enumerable:!0,get:function(){return D.MongoErrorLabel}});var k=r(36411);Object.defineProperty(t,"ExplainVerbosity",{enumerable:!0,get:function(){return k.ExplainVerbosity}});var L=r(22220);Object.defineProperty(t,"ServerApiVersion",{enumerable:!0,get:function(){return L.ServerApiVersion}});var B=r(93347);Object.defineProperty(t,"MongoLoggableComponent",{enumerable:!0,get:function(){return B.MongoLoggableComponent}}),Object.defineProperty(t,"SeverityLevel",{enumerable:!0,get:function(){return B.SeverityLevel}});var j=r(61635);Object.defineProperty(t,"ReturnDocument",{enumerable:!0,get:function(){return j.ReturnDocument}});var U=r(58127);Object.defineProperty(t,"ProfilingLevel",{enumerable:!0,get:function(){return U.ProfilingLevel}});var G=r(28541);Object.defineProperty(t,"ReadConcernLevel",{enumerable:!0,get:function(){return G.ReadConcernLevel}});var W=r(13700);Object.defineProperty(t,"ReadPreferenceMode",{enumerable:!0,get:function(){return W.ReadPreferenceMode}});var V=r(89167);Object.defineProperty(t,"ServerType",{enumerable:!0,get:function(){return V.ServerType}}),Object.defineProperty(t,"TopologyType",{enumerable:!0,get:function(){return V.TopologyType}});var F=r(28541);Object.defineProperty(t,"ReadConcern",{enumerable:!0,get:function(){return F.ReadConcern}});var z=r(13700);Object.defineProperty(t,"ReadPreference",{enumerable:!0,get:function(){return z.ReadPreference}});var $=r(40012);Object.defineProperty(t,"WriteConcern",{enumerable:!0,get:function(){return $.WriteConcern}});var H=r(38216);Object.defineProperty(t,"CommandFailedEvent",{enumerable:!0,get:function(){return H.CommandFailedEvent}}),Object.defineProperty(t,"CommandStartedEvent",{enumerable:!0,get:function(){return H.CommandStartedEvent}}),Object.defineProperty(t,"CommandSucceededEvent",{enumerable:!0,get:function(){return H.CommandSucceededEvent}});var K=r(287);Object.defineProperty(t,"ConnectionCheckedInEvent",{enumerable:!0,get:function(){return K.ConnectionCheckedInEvent}}),Object.defineProperty(t,"ConnectionCheckedOutEvent",{enumerable:!0,get:function(){return K.ConnectionCheckedOutEvent}}),Object.defineProperty(t,"ConnectionCheckOutFailedEvent",{enumerable:!0,get:function(){return K.ConnectionCheckOutFailedEvent}}),Object.defineProperty(t,"ConnectionCheckOutStartedEvent",{enumerable:!0,get:function(){return K.ConnectionCheckOutStartedEvent}}),Object.defineProperty(t,"ConnectionClosedEvent",{enumerable:!0,get:function(){return K.ConnectionClosedEvent}}),Object.defineProperty(t,"ConnectionCreatedEvent",{enumerable:!0,get:function(){return K.ConnectionCreatedEvent}}),Object.defineProperty(t,"ConnectionPoolClearedEvent",{enumerable:!0,get:function(){return K.ConnectionPoolClearedEvent}}),Object.defineProperty(t,"ConnectionPoolClosedEvent",{enumerable:!0,get:function(){return K.ConnectionPoolClosedEvent}}),Object.defineProperty(t,"ConnectionPoolCreatedEvent",{enumerable:!0,get:function(){return K.ConnectionPoolCreatedEvent}}),Object.defineProperty(t,"ConnectionPoolMonitoringEvent",{enumerable:!0,get:function(){return K.ConnectionPoolMonitoringEvent}}),Object.defineProperty(t,"ConnectionPoolReadyEvent",{enumerable:!0,get:function(){return K.ConnectionPoolReadyEvent}}),Object.defineProperty(t,"ConnectionReadyEvent",{enumerable:!0,get:function(){return K.ConnectionReadyEvent}});var q=r(43135);Object.defineProperty(t,"ServerClosedEvent",{enumerable:!0,get:function(){return q.ServerClosedEvent}}),Object.defineProperty(t,"ServerDescriptionChangedEvent",{enumerable:!0,get:function(){return q.ServerDescriptionChangedEvent}}),Object.defineProperty(t,"ServerHeartbeatFailedEvent",{enumerable:!0,get:function(){return q.ServerHeartbeatFailedEvent}}),Object.defineProperty(t,"ServerHeartbeatStartedEvent",{enumerable:!0,get:function(){return q.ServerHeartbeatStartedEvent}}),Object.defineProperty(t,"ServerHeartbeatSucceededEvent",{enumerable:!0,get:function(){return q.ServerHeartbeatSucceededEvent}}),Object.defineProperty(t,"ServerOpeningEvent",{enumerable:!0,get:function(){return q.ServerOpeningEvent}}),Object.defineProperty(t,"TopologyClosedEvent",{enumerable:!0,get:function(){return q.TopologyClosedEvent}}),Object.defineProperty(t,"TopologyDescriptionChangedEvent",{enumerable:!0,get:function(){return q.TopologyDescriptionChangedEvent}}),Object.defineProperty(t,"TopologyOpeningEvent",{enumerable:!0,get:function(){return q.TopologyOpeningEvent}});var Y=r(3906);Object.defineProperty(t,"ServerSelectionEvent",{enumerable:!0,get:function(){return Y.ServerSelectionEvent}}),Object.defineProperty(t,"ServerSelectionFailedEvent",{enumerable:!0,get:function(){return Y.ServerSelectionFailedEvent}}),Object.defineProperty(t,"ServerSelectionStartedEvent",{enumerable:!0,get:function(){return Y.ServerSelectionStartedEvent}}),Object.defineProperty(t,"ServerSelectionSucceededEvent",{enumerable:!0,get:function(){return Y.ServerSelectionSucceededEvent}}),Object.defineProperty(t,"WaitingForSuitableServerEvent",{enumerable:!0,get:function(){return Y.WaitingForSuitableServerEvent}});var Q=r(4313);Object.defineProperty(t,"SrvPollingEvent",{enumerable:!0,get:function(){return Q.SrvPollingEvent}});var X=r(86981);Object.defineProperty(t,"MongoCryptAzureKMSRequestError",{enumerable:!0,get:function(){return X.MongoCryptAzureKMSRequestError}}),Object.defineProperty(t,"MongoCryptCreateDataKeyError",{enumerable:!0,get:function(){return X.MongoCryptCreateDataKeyError}}),Object.defineProperty(t,"MongoCryptCreateEncryptedCollectionError",{enumerable:!0,get:function(){return X.MongoCryptCreateEncryptedCollectionError}}),Object.defineProperty(t,"MongoCryptError",{enumerable:!0,get:function(){return X.MongoCryptError}}),Object.defineProperty(t,"MongoCryptInvalidArgumentError",{enumerable:!0,get:function(){return X.MongoCryptInvalidArgumentError}}),Object.defineProperty(t,"MongoCryptKMSRequestNetworkTimeoutError",{enumerable:!0,get:function(){return X.MongoCryptKMSRequestNetworkTimeoutError}});var J=r(38944);Object.defineProperty(t,"MongoClientAuthProviders",{enumerable:!0,get:function(){return J.MongoClientAuthProviders}})},17172:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CountOperation=void 0;const n=r(75725),o=r(78130),i=r(35394);class s extends o.CommandOperation{constructor(e,t,r){super({s:{namespace:e}},r),this.SERVER_COMMAND_RESPONSE_TYPE=n.MongoDBResponse,this.options=r,this.collectionName=e.collection,this.query=t}get commandName(){return"count"}buildCommandDocument(e,t){const r=this.options,n={count:this.collectionName,query:this.query};return"number"==typeof r.limit&&(n.limit=r.limit),"number"==typeof r.skip&&(n.skip=r.skip),null!=r.hint&&(n.hint=r.hint),"number"==typeof r.maxTimeMS&&(n.maxTimeMS=r.maxTimeMS),n}handleOk(e){return e.getNumber("n")??0}}t.CountOperation=s,(0,i.defineAspects)(s,[i.Aspect.READ_OPERATION,i.Aspect.RETRYABLE])},17309:(e,t,r)=>{var n=r(65994).e;Object.defineProperty(t,"__esModule",{value:!0}),t.callback=void 0;const o=r(36374),i=r(17562);t.callback=async()=>{const e=n.env.OIDC_TOKEN_FILE;if(!e)throw new i.MongoAWSError("OIDC_TOKEN_FILE must be set in the environment.");return{accessToken:await o.promises.readFile(e,"utf8")}}},17562:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MongoWriteConcernError=t.MongoServerSelectionError=t.MongoSystemError=t.MongoMissingDependencyError=t.MongoMissingCredentialsError=t.MongoCompatibilityError=t.MongoInvalidArgumentError=t.MongoParseError=t.MongoNetworkTimeoutError=t.MongoNetworkError=t.MongoClientClosedError=t.MongoTopologyClosedError=t.MongoCursorExhaustedError=t.MongoServerClosedError=t.MongoCursorInUseError=t.MongoOperationTimeoutError=t.MongoUnexpectedServerResponseError=t.MongoGridFSChunkError=t.MongoGridFSStreamError=t.MongoTailableCursorError=t.MongoChangeStreamError=t.MongoClientBulkWriteExecutionError=t.MongoClientBulkWriteCursorError=t.MongoClientBulkWriteError=t.MongoGCPError=t.MongoAzureError=t.MongoOIDCError=t.MongoAWSError=t.MongoKerberosError=t.MongoExpiredSessionError=t.MongoTransactionError=t.MongoNotConnectedError=t.MongoDecompressionError=t.MongoBatchReExecutionError=t.MongoStalePrimaryError=t.MongoRuntimeError=t.MongoAPIError=t.MongoDriverError=t.MongoServerError=t.MongoError=t.MongoErrorLabel=t.GET_MORE_RESUMABLE_CODES=t.MONGODB_ERROR_CODES=t.NODE_IS_RECOVERING_ERROR_MESSAGE=t.LEGACY_NOT_PRIMARY_OR_SECONDARY_ERROR_MESSAGE=t.LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE=void 0,t.needsRetryableWriteLabel=function(e,n,o){if(e instanceof c)return!0;if(e instanceof r&&(n>=9||m(e))&&!e.hasErrorLabel(t.MongoErrorLabel.HandshakeError))return!1;if(e instanceof d){if("Mongos"===o&&n<9)return p.has(e.result.code??0);const t=e.result.writeConcernError.code??Number(e.code);return p.has(Number.isNaN(t)?0:t)}if(e instanceof r)return p.has(Number(e.code));return!!t.LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE.test(e.message)||!!t.NODE_IS_RECOVERING_ERROR_MESSAGE.test(e.message)},t.isRetryableWriteError=m,t.isRetryableReadError=function(e){if("number"==typeof e.code&&h.has(e.code))return!0;if(e instanceof c)return!0;return!!t.LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE.test(e.message)||!!t.NODE_IS_RECOVERING_ERROR_MESSAGE.test(e.message)},t.isNodeShuttingDownError=function(e){return!("number"!=typeof e.code||!E.has(e.code))},t.isSDAMUnrecoverableError=function(e){return e instanceof u||null==e||(S(e)||("number"==typeof(r=e).code?g.has(r.code):!S(r)&&t.LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE.test(r.message)));var r},t.isNetworkTimeoutError=function(e){return!!(e instanceof c&&e.message.match(/timed out/))},t.isResumableError=function(e,n){return null!=e&&e instanceof r&&(e instanceof c||(null!=n&&n>=9?e.code===t.MONGODB_ERROR_CODES.CursorNotFound||e.hasErrorLabel(t.MongoErrorLabel.ResumableChangeStreamError):"number"==typeof e.code&&t.GET_MORE_RESUMABLE_CODES.has(e.code)))},t.LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE=new RegExp("not master","i"),t.LEGACY_NOT_PRIMARY_OR_SECONDARY_ERROR_MESSAGE=new RegExp("not master or secondary","i"),t.NODE_IS_RECOVERING_ERROR_MESSAGE=new RegExp("node is recovering","i"),t.MONGODB_ERROR_CODES=Object.freeze({HostUnreachable:6,HostNotFound:7,AuthenticationFailed:18,NetworkTimeout:89,ShutdownInProgress:91,PrimarySteppedDown:189,ExceededTimeLimit:262,SocketException:9001,NotWritablePrimary:10107,InterruptedAtShutdown:11600,InterruptedDueToReplStateChange:11602,NotPrimaryNoSecondaryOk:13435,NotPrimaryOrSecondary:13436,StaleShardVersion:63,StaleEpoch:150,StaleConfig:13388,RetryChangeStream:234,FailedToSatisfyReadPreference:133,CursorNotFound:43,LegacyNotPrimary:10058,WriteConcernTimeout:64,NamespaceNotFound:26,IllegalOperation:20,MaxTimeMSExpired:50,UnknownReplWriteConcern:79,UnsatisfiableWriteConcern:100,Reauthenticate:391,ReadConcernMajorityNotAvailableYet:134}),t.GET_MORE_RESUMABLE_CODES=new Set([t.MONGODB_ERROR_CODES.HostUnreachable,t.MONGODB_ERROR_CODES.HostNotFound,t.MONGODB_ERROR_CODES.NetworkTimeout,t.MONGODB_ERROR_CODES.ShutdownInProgress,t.MONGODB_ERROR_CODES.PrimarySteppedDown,t.MONGODB_ERROR_CODES.ExceededTimeLimit,t.MONGODB_ERROR_CODES.SocketException,t.MONGODB_ERROR_CODES.NotWritablePrimary,t.MONGODB_ERROR_CODES.InterruptedAtShutdown,t.MONGODB_ERROR_CODES.InterruptedDueToReplStateChange,t.MONGODB_ERROR_CODES.NotPrimaryNoSecondaryOk,t.MONGODB_ERROR_CODES.NotPrimaryOrSecondary,t.MONGODB_ERROR_CODES.StaleShardVersion,t.MONGODB_ERROR_CODES.StaleEpoch,t.MONGODB_ERROR_CODES.StaleConfig,t.MONGODB_ERROR_CODES.RetryChangeStream,t.MONGODB_ERROR_CODES.FailedToSatisfyReadPreference,t.MONGODB_ERROR_CODES.CursorNotFound]),t.MongoErrorLabel=Object.freeze({RetryableWriteError:"RetryableWriteError",TransientTransactionError:"TransientTransactionError",UnknownTransactionCommitResult:"UnknownTransactionCommitResult",ResumableChangeStreamError:"ResumableChangeStreamError",HandshakeError:"HandshakeError",ResetPool:"ResetPool",PoolRequstedRetry:"PoolRequstedRetry",InterruptInUseConnections:"InterruptInUseConnections",NoWritesPerformed:"NoWritesPerformed"});class r extends Error{get errorLabels(){return Array.from(this.errorLabelSet)}constructor(e,t){super(e,t),this.errorLabelSet=new Set}static buildErrorMessage(e){return"string"==typeof e?e:function(e){return null!=e&&"object"==typeof e&&"errors"in e&&Array.isArray(e.errors)}(e)&&0===e.message.length?0===e.errors.length?"AggregateError has an empty errors array. Please check the `cause` property for more information.":e.errors.map((({message:e})=>e)).join(", "):null!=e&&"object"==typeof e&&"message"in e&&"string"==typeof e.message?e.message:"empty error message"}get name(){return"MongoError"}get errmsg(){return this.message}hasErrorLabel(e){return this.errorLabelSet.has(e)}addErrorLabel(e){this.errorLabelSet.add(e)}}t.MongoError=r;class n extends r{constructor(e){if(super(e.message||e.errmsg||e.$err||"n/a"),e.errorLabels)for(const t of e.errorLabels)this.addErrorLabel(t);this.errorResponse=e;for(const t in e)"errorLabels"!==t&&"errmsg"!==t&&"message"!==t&&"errorResponse"!==t&&(this[t]=e[t])}get name(){return"MongoServerError"}}t.MongoServerError=n;class o extends r{constructor(e,t){super(e,t)}get name(){return"MongoDriverError"}}t.MongoDriverError=o;class i extends o{constructor(e,t){super(e,t)}get name(){return"MongoAPIError"}}t.MongoAPIError=i;class s extends o{constructor(e,t){super(e,t)}get name(){return"MongoRuntimeError"}}t.MongoRuntimeError=s,t.MongoStalePrimaryError=class extends s{constructor(e,t){super(e,t)}get name(){return"MongoStalePrimaryError"}},t.MongoBatchReExecutionError=class extends i{constructor(e="This batch has already been executed, create new batch to execute"){super(e)}get name(){return"MongoBatchReExecutionError"}},t.MongoDecompressionError=class extends s{constructor(e){super(e)}get name(){return"MongoDecompressionError"}},t.MongoNotConnectedError=class extends i{constructor(e){super(e)}get name(){return"MongoNotConnectedError"}},t.MongoTransactionError=class extends i{constructor(e){super(e)}get name(){return"MongoTransactionError"}},t.MongoExpiredSessionError=class extends i{constructor(e="Cannot use a session that has ended"){super(e)}get name(){return"MongoExpiredSessionError"}},t.MongoKerberosError=class extends s{constructor(e){super(e)}get name(){return"MongoKerberosError"}},t.MongoAWSError=class extends s{constructor(e,t){super(e,t)}get name(){return"MongoAWSError"}};class a extends s{constructor(e){super(e)}get name(){return"MongoOIDCError"}}t.MongoOIDCError=a,t.MongoAzureError=class extends a{constructor(e){super(e)}get name(){return"MongoAzureError"}},t.MongoGCPError=class extends a{constructor(e){super(e)}get name(){return"MongoGCPError"}},t.MongoClientBulkWriteError=class extends n{constructor(e){super(e),this.writeConcernErrors=[],this.writeErrors=new Map}get name(){return"MongoClientBulkWriteError"}},t.MongoClientBulkWriteCursorError=class extends s{constructor(e){super(e)}get name(){return"MongoClientBulkWriteCursorError"}},t.MongoClientBulkWriteExecutionError=class extends s{constructor(e){super(e)}get name(){return"MongoClientBulkWriteExecutionError"}},t.MongoChangeStreamError=class extends s{constructor(e){super(e)}get name(){return"MongoChangeStreamError"}},t.MongoTailableCursorError=class extends i{constructor(e="Tailable cursor does not support this operation"){super(e)}get name(){return"MongoTailableCursorError"}},t.MongoGridFSStreamError=class extends s{constructor(e){super(e)}get name(){return"MongoGridFSStreamError"}},t.MongoGridFSChunkError=class extends s{constructor(e){super(e)}get name(){return"MongoGridFSChunkError"}},t.MongoUnexpectedServerResponseError=class extends s{constructor(e,t){super(e,t)}get name(){return"MongoUnexpectedServerResponseError"}},t.MongoOperationTimeoutError=class extends o{get name(){return"MongoOperationTimeoutError"}},t.MongoCursorInUseError=class extends i{constructor(e="Cursor is already initialized"){super(e)}get name(){return"MongoCursorInUseError"}},t.MongoServerClosedError=class extends i{constructor(e="Server is closed"){super(e)}get name(){return"MongoServerClosedError"}},t.MongoCursorExhaustedError=class extends i{constructor(e){super(e||"Cursor is exhausted")}get name(){return"MongoCursorExhaustedError"}},t.MongoTopologyClosedError=class extends i{constructor(e="Topology is closed"){super(e)}get name(){return"MongoTopologyClosedError"}},t.MongoClientClosedError=class extends i{constructor(){super("Operation interrupted because client was closed")}get name(){return"MongoClientClosedError"}};class c extends r{constructor(e,t){super(e,{cause:t?.cause}),this.beforeHandshake=!!t?.beforeHandshake}get name(){return"MongoNetworkError"}}t.MongoNetworkError=c,t.MongoNetworkTimeoutError=class extends c{constructor(e,t){super(e,t)}get name(){return"MongoNetworkTimeoutError"}};class u extends o{constructor(e){super(e)}get name(){return"MongoParseError"}}t.MongoParseError=u,t.MongoInvalidArgumentError=class extends i{constructor(e,t){super(e,t)}get name(){return"MongoInvalidArgumentError"}},t.MongoCompatibilityError=class extends i{constructor(e){super(e)}get name(){return"MongoCompatibilityError"}},t.MongoMissingCredentialsError=class extends i{constructor(e){super(e)}get name(){return"MongoMissingCredentialsError"}},t.MongoMissingDependencyError=class extends i{constructor(e,t){super(e,t),this.dependencyName=t.dependencyName}get name(){return"MongoMissingDependencyError"}};class l extends r{constructor(e,t){t&&t.error?super(r.buildErrorMessage(t.error.message||t.error),{cause:t.error}):super(e),t&&(this.reason=t),this.code=t.error?.code}get name(){return"MongoSystemError"}}t.MongoSystemError=l,t.MongoServerSelectionError=class extends l{constructor(e,t){super(e,t)}get name(){return"MongoServerSelectionError"}};class d extends n{constructor(e){super({...e.writeConcernError,...e}),this.errInfo=e.writeConcernError.errInfo,this.result=e}get name(){return"MongoWriteConcernError"}}t.MongoWriteConcernError=d;const h=new Set([t.MONGODB_ERROR_CODES.HostUnreachable,t.MONGODB_ERROR_CODES.HostNotFound,t.MONGODB_ERROR_CODES.NetworkTimeout,t.MONGODB_ERROR_CODES.ShutdownInProgress,t.MONGODB_ERROR_CODES.PrimarySteppedDown,t.MONGODB_ERROR_CODES.SocketException,t.MONGODB_ERROR_CODES.NotWritablePrimary,t.MONGODB_ERROR_CODES.InterruptedAtShutdown,t.MONGODB_ERROR_CODES.InterruptedDueToReplStateChange,t.MONGODB_ERROR_CODES.NotPrimaryNoSecondaryOk,t.MONGODB_ERROR_CODES.NotPrimaryOrSecondary,t.MONGODB_ERROR_CODES.ExceededTimeLimit,t.MONGODB_ERROR_CODES.ReadConcernMajorityNotAvailableYet]),p=h;function m(e){return e.hasErrorLabel(t.MongoErrorLabel.RetryableWriteError)||e.hasErrorLabel(t.MongoErrorLabel.PoolRequstedRetry)}const f=new Set([t.MONGODB_ERROR_CODES.ShutdownInProgress,t.MONGODB_ERROR_CODES.PrimarySteppedDown,t.MONGODB_ERROR_CODES.InterruptedAtShutdown,t.MONGODB_ERROR_CODES.InterruptedDueToReplStateChange,t.MONGODB_ERROR_CODES.NotPrimaryOrSecondary]),g=new Set([t.MONGODB_ERROR_CODES.NotWritablePrimary,t.MONGODB_ERROR_CODES.NotPrimaryNoSecondaryOk,t.MONGODB_ERROR_CODES.LegacyNotPrimary]),E=new Set([t.MONGODB_ERROR_CODES.InterruptedAtShutdown,t.MONGODB_ERROR_CODES.ShutdownInProgress]);function S(e){return"number"==typeof e.code?f.has(e.code):t.LEGACY_NOT_PRIMARY_OR_SECONDARY_ERROR_MESSAGE.test(e.message)||t.NODE_IS_RECOVERING_ERROR_MESSAGE.test(e.message)}},17642:(e,t,r)=>{var n=r(65994).e;function o(e){if("string"!=typeof e)throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}function i(e,t){for(var r,n="",o=0,i=-1,s=0,a=0;a<=e.length;++a){if(a<e.length)r=e.charCodeAt(a);else{if(47===r)break;r=47}if(47===r){if(i===a-1||1===s);else if(i!==a-1&&2===s){if(n.length<2||2!==o||46!==n.charCodeAt(n.length-1)||46!==n.charCodeAt(n.length-2))if(n.length>2){var c=n.lastIndexOf("/");if(c!==n.length-1){-1===c?(n="",o=0):o=(n=n.slice(0,c)).length-1-n.lastIndexOf("/"),i=a,s=0;continue}}else if(2===n.length||1===n.length){n="",o=0,i=a,s=0;continue}t&&(n.length>0?n+="/..":n="..",o=2)}else n.length>0?n+="/"+e.slice(i+1,a):n=e.slice(i+1,a),o=a-i-1;i=a,s=0}else 46===r&&-1!==s?++s:s=-1}return n}var s={resolve:function(){for(var e,t="",r=!1,s=arguments.length-1;s>=-1&&!r;s--){var a;s>=0?a=arguments[s]:(void 0===e&&(e=n.cwd()),a=e),o(a),0!==a.length&&(t=a+"/"+t,r=47===a.charCodeAt(0))}return t=i(t,!r),r?t.length>0?"/"+t:"/":t.length>0?t:"."},normalize:function(e){if(o(e),0===e.length)return".";var t=47===e.charCodeAt(0),r=47===e.charCodeAt(e.length-1);return 0!==(e=i(e,!t)).length||t||(e="."),e.length>0&&r&&(e+="/"),t?"/"+e:e},isAbsolute:function(e){return o(e),e.length>0&&47===e.charCodeAt(0)},join:function(){if(0===arguments.length)return".";for(var e,t=0;t<arguments.length;++t){var r=arguments[t];o(r),r.length>0&&(void 0===e?e=r:e+="/"+r)}return void 0===e?".":s.normalize(e)},relative:function(e,t){if(o(e),o(t),e===t)return"";if((e=s.resolve(e))===(t=s.resolve(t)))return"";for(var r=1;r<e.length&&47===e.charCodeAt(r);++r);for(var n=e.length,i=n-r,a=1;a<t.length&&47===t.charCodeAt(a);++a);for(var c=t.length-a,u=i<c?i:c,l=-1,d=0;d<=u;++d){if(d===u){if(c>u){if(47===t.charCodeAt(a+d))return t.slice(a+d+1);if(0===d)return t.slice(a+d)}else i>u&&(47===e.charCodeAt(r+d)?l=d:0===d&&(l=0));break}var h=e.charCodeAt(r+d);if(h!==t.charCodeAt(a+d))break;47===h&&(l=d)}var p="";for(d=r+l+1;d<=n;++d)d!==n&&47!==e.charCodeAt(d)||(0===p.length?p+="..":p+="/..");return p.length>0?p+t.slice(a+l):(a+=l,47===t.charCodeAt(a)&&++a,t.slice(a))},_makeLong:function(e){return e},dirname:function(e){if(o(e),0===e.length)return".";for(var t=e.charCodeAt(0),r=47===t,n=-1,i=!0,s=e.length-1;s>=1;--s)if(47===(t=e.charCodeAt(s))){if(!i){n=s;break}}else i=!1;return-1===n?r?"/":".":r&&1===n?"//":e.slice(0,n)},basename:function(e,t){if(void 0!==t&&"string"!=typeof t)throw new TypeError('"ext" argument must be a string');o(e);var r,n=0,i=-1,s=!0;if(void 0!==t&&t.length>0&&t.length<=e.length){if(t.length===e.length&&t===e)return"";var a=t.length-1,c=-1;for(r=e.length-1;r>=0;--r){var u=e.charCodeAt(r);if(47===u){if(!s){n=r+1;break}}else-1===c&&(s=!1,c=r+1),a>=0&&(u===t.charCodeAt(a)?-1==--a&&(i=r):(a=-1,i=c))}return n===i?i=c:-1===i&&(i=e.length),e.slice(n,i)}for(r=e.length-1;r>=0;--r)if(47===e.charCodeAt(r)){if(!s){n=r+1;break}}else-1===i&&(s=!1,i=r+1);return-1===i?"":e.slice(n,i)},extname:function(e){o(e);for(var t=-1,r=0,n=-1,i=!0,s=0,a=e.length-1;a>=0;--a){var c=e.charCodeAt(a);if(47!==c)-1===n&&(i=!1,n=a+1),46===c?-1===t?t=a:1!==s&&(s=1):-1!==t&&(s=-1);else if(!i){r=a+1;break}}return-1===t||-1===n||0===s||1===s&&t===n-1&&t===r+1?"":e.slice(t,n)},format:function(e){if(null===e||"object"!=typeof e)throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof e);return function(e,t){var r=t.dir||t.root,n=t.base||(t.name||"")+(t.ext||"");return r?r===t.root?r+n:r+"/"+n:n}(0,e)},parse:function(e){o(e);var t={root:"",dir:"",base:"",ext:"",name:""};if(0===e.length)return t;var r,n=e.charCodeAt(0),i=47===n;i?(t.root="/",r=1):r=0;for(var s=-1,a=0,c=-1,u=!0,l=e.length-1,d=0;l>=r;--l)if(47!==(n=e.charCodeAt(l)))-1===c&&(u=!1,c=l+1),46===n?-1===s?s=l:1!==d&&(d=1):-1!==s&&(d=-1);else if(!u){a=l+1;break}return-1===s||-1===c||0===d||1===d&&s===c-1&&s===a+1?-1!==c&&(t.base=t.name=0===a&&i?e.slice(1,c):e.slice(a,c)):(0===a&&i?(t.name=e.slice(1,s),t.base=e.slice(1,c)):(t.name=e.slice(a,s),t.base=e.slice(a,c)),t.ext=e.slice(s,c)),a>0?t.dir=e.slice(0,a-1):i&&(t.dir="/"),t},sep:"/",delimiter:":",win32:null,posix:null};s.posix=s,e.exports=s},17668:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.RunCursorCommandOperation=t.RunCommandOperation=void 0;const n=r(75725),o=r(35394);class i extends o.AbstractOperation{constructor(e,t,r){super(r),this.SERVER_COMMAND_RESPONSE_TYPE=n.MongoDBResponse,this.command=t,this.options=r,this.ns=e.withCollection("$cmd")}get commandName(){return"runCommand"}buildCommand(e,t){return this.command}buildOptions(e){return{...this.options,session:this.session,timeoutContext:e,signal:this.options.signal,readPreference:this.options.readPreference}}}t.RunCommandOperation=i,t.RunCursorCommandOperation=class extends i{constructor(){super(...arguments),this.SERVER_COMMAND_RESPONSE_TYPE=n.CursorResponse}handleOk(e){return e}}},19043:(e,t,r)=>{var n=r(65994).e;Object.defineProperty(t,"__esModule",{value:!0}),t.LegacyAWSTemporaryCredentialProvider=t.AWSSDKCredentialProvider=t.AWSTemporaryCredentialProvider=void 0;const o=r(8500),i=r(17562),s=r(145),a="http://169.254.169.254",c="/latest/meta-data/iam/security-credentials";class u{static get awsSDK(){return u._awsSDK??=(0,o.getAwsCredentialProvider)(),u._awsSDK}static get isAWSSDKInstalled(){return!("kModuleError"in u.awsSDK)}}t.AWSTemporaryCredentialProvider=u,t.AWSSDKCredentialProvider=class extends u{constructor(e){super(),e&&(this._provider=e)}get provider(){if("kModuleError"in u.awsSDK)throw u.awsSDK.kModuleError;if(this._provider)return this._provider;let{AWS_STS_REGIONAL_ENDPOINTS:e="",AWS_REGION:t=""}=n.env;e=e.toLowerCase(),t=t.toLowerCase();const r=0!==t.length&&0!==e.length,o=new Set(["ap-northeast-1","ap-south-1","ap-southeast-1","ap-southeast-2","aws-global","ca-central-1","eu-central-1","eu-north-1","eu-west-1","eu-west-2","eu-west-3","sa-east-1","us-east-1","us-east-2","us-west-1","us-west-2"]),i="regional"===e||"legacy"===e&&!o.has(t);return this._provider=r&&i?u.awsSDK.fromNodeProviderChain({clientConfig:{region:t}}):u.awsSDK.fromNodeProviderChain(),this._provider}async getCredentials(){try{const e=await this.provider();return{AccessKeyId:e.accessKeyId,SecretAccessKey:e.secretAccessKey,Token:e.sessionToken,Expiration:e.expiration}}catch(e){throw new i.MongoAWSError(e.message,{cause:e})}}},t.LegacyAWSTemporaryCredentialProvider=class extends u{async getCredentials(){if(n.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI)return await(0,s.request)(`http://169.254.170.2${n.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI}`);const e=await(0,s.request)(`${a}/latest/api/token`,{method:"PUT",json:!1,headers:{"X-aws-ec2-metadata-token-ttl-seconds":30}}),t=await(0,s.request)(`${a}/${c}`,{json:!1,headers:{"X-aws-ec2-metadata-token":e}});return await(0,s.request)(`${a}/${c}/${t}`,{headers:{"X-aws-ec2-metadata-token":e}})}}},19498:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Collection=void 0;const n=r(75080),o=r(29348),i=r(10089),s=r(22345),a=r(68526),c=r(5465),u=r(32361),l=r(71906),d=r(17562),h=r(17172),p=r(4752),m=r(815),f=r(93549),g=r(96357),E=r(61635),S=r(22847),O=r(9326),y=r(61861),C=r(32443),M=r(97350),T=r(40866),w=r(94330),v=r(28541),b=r(13700),_=r(145),R=r(40012);t.Collection=class{constructor(e,t,r){this.s={db:e,options:r,namespace:new _.MongoDBCollectionNamespace(e.databaseName,t),pkFactory:e.options?.pkFactory??_.DEFAULT_PK_FACTORY,readPreference:b.ReadPreference.fromOptions(r),bsonOptions:(0,n.resolveBSONOptions)(r,e),readConcern:v.ReadConcern.fromOptions(r),writeConcern:R.WriteConcern.fromOptions(r)},this.client=e.client}get dbName(){return this.s.namespace.db}get collectionName(){return this.s.namespace.collection}get namespace(){return this.fullNamespace.toString()}get fullNamespace(){return this.s.namespace}get readConcern(){return null==this.s.readConcern?this.s.db.readConcern:this.s.readConcern}get readPreference(){return null==this.s.readPreference?this.s.db.readPreference:this.s.readPreference}get bsonOptions(){return this.s.bsonOptions}get writeConcern(){return null==this.s.writeConcern?this.s.db.writeConcern:this.s.writeConcern}get hint(){return this.s.collectionHint}set hint(e){this.s.collectionHint=(0,_.normalizeHintField)(e)}get timeoutMS(){return this.s.options.timeoutMS}async insertOne(e,t){return await(0,g.executeOperation)(this.client,new O.InsertOneOperation(this,e,(0,_.resolveOptions)(this,t)))}async insertMany(e,t){if(!Array.isArray(e))throw new d.MongoInvalidArgumentError('Argument "docs" must be an array of documents');t=(0,_.resolveOptions)(this,t??{});const r=0!==R.WriteConcern.fromOptions(t)?.w;try{const n=await this.bulkWrite(e.map((e=>({insertOne:{document:e}}))),t);return{acknowledged:r,insertedCount:n.insertedCount,insertedIds:n.insertedIds}}catch(e){if(e&&"Operation must be an object with an operation key"===e.message)throw new d.MongoInvalidArgumentError("Collection.insertMany() cannot be called with an array that has null/undefined values");throw e}}async bulkWrite(e,t){if(!Array.isArray(e))throw new d.MongoInvalidArgumentError('Argument "operations" must be an array of documents');t=(0,_.resolveOptions)(this,t??{}),null!=this.client.topology||await(0,g.autoConnect)(this.client);const r=!1===t.ordered?this.initializeUnorderedBulkOp(t):this.initializeOrderedBulkOp(t);for(const t of e)r.raw(t);return await r.execute({...t})}async updateOne(e,t,r){return await(0,g.executeOperation)(this.client,new w.UpdateOneOperation(this.s.namespace,e,t,(0,_.resolveOptions)(this,r)))}async replaceOne(e,t,r){return await(0,g.executeOperation)(this.client,new w.ReplaceOneOperation(this.s.namespace,e,t,(0,_.resolveOptions)(this,r)))}async updateMany(e,t,r){return await(0,g.executeOperation)(this.client,new w.UpdateManyOperation(this.s.namespace,e,t,(0,_.resolveOptions)(this,r)))}async deleteOne(e={},t={}){return await(0,g.executeOperation)(this.client,new p.DeleteOneOperation(this.s.namespace,e,(0,_.resolveOptions)(this,t)))}async deleteMany(e={},t={}){return await(0,g.executeOperation)(this.client,new p.DeleteManyOperation(this.s.namespace,e,(0,_.resolveOptions)(this,t)))}async rename(e,t){return await(0,g.executeOperation)(this.client,new y.RenameOperation(this,e,(0,_.resolveOptions)(void 0,{...t,readPreference:b.ReadPreference.PRIMARY})))}async drop(e){return await this.s.db.dropCollection(this.collectionName,e)}async findOne(e={},t={}){const{batchSize:r,noCursorTimeout:n,...o}=t;o.singleBatch=!0;const i=this.find(e,o).limit(1),s=await i.next();return await i.close(),s}find(e={},t={}){return new c.FindCursor(this.client,this.s.namespace,e,(0,_.resolveOptions)(this,t))}async options(e){e=(0,_.resolveOptions)(this,e);const[t]=await this.s.db.listCollections({name:this.collectionName},{...e,nameOnly:!1}).toArray();if(null==t||null==t.options)throw new d.MongoAPIError(`collection ${this.namespace} not found`);return t.options}async isCapped(e){const{capped:t}=await this.options(e);return Boolean(t)}async createIndex(e,t){return(await(0,g.executeOperation)(this.client,S.CreateIndexesOperation.fromIndexSpecification(this,this.collectionName,e,(0,_.resolveOptions)(this,t))))[0]}async createIndexes(e,t){return await(0,g.executeOperation)(this.client,S.CreateIndexesOperation.fromIndexDescriptionArray(this,this.collectionName,e,(0,_.resolveOptions)(this,{...t,maxTimeMS:void 0})))}async dropIndex(e,t){return await(0,g.executeOperation)(this.client,new S.DropIndexOperation(this,e,{...(0,_.resolveOptions)(this,t),readPreference:b.ReadPreference.primary}))}async dropIndexes(e){try{return await(0,g.executeOperation)(this.client,new S.DropIndexOperation(this,"*",(0,_.resolveOptions)(this,e))),!0}catch(e){if(e instanceof d.MongoOperationTimeoutError)throw e;return!1}}listIndexes(e){return new u.ListIndexesCursor(this,(0,_.resolveOptions)(this,e))}async indexExists(e,t){const r=Array.isArray(e)?e:[e],n=new Set(await this.listIndexes(t).map((({name:e})=>e)).toArray());return r.every((e=>n.has(e)))}async indexInformation(e){return await this.indexes({...e,full:e?.full??!1})}async estimatedDocumentCount(e){return await(0,g.executeOperation)(this.client,new f.EstimatedDocumentCountOperation(this,(0,_.resolveOptions)(this,e)))}async countDocuments(e={},t={}){const r=[];r.push({$match:e}),"number"==typeof t.skip&&r.push({$skip:t.skip}),"number"==typeof t.limit&&r.push({$limit:t.limit}),r.push({$group:{_id:1,n:{$sum:1}}});const n=this.aggregate(r,t),o=await n.next();return await n.close(),o?.n??0}async distinct(e,t={},r={}){return await(0,g.executeOperation)(this.client,new m.DistinctOperation(this,e,t,(0,_.resolveOptions)(this,r)))}async indexes(e){const t=await this.listIndexes(e).toArray();return e?.full??1?t:Object.fromEntries(t.map((({name:e,key:t})=>[e,Object.entries(t)])))}async findOneAndDelete(e,t){return await(0,g.executeOperation)(this.client,new E.FindOneAndDeleteOperation(this,e,(0,_.resolveOptions)(this,t)))}async findOneAndReplace(e,t,r){return await(0,g.executeOperation)(this.client,new E.FindOneAndReplaceOperation(this,e,t,(0,_.resolveOptions)(this,r)))}async findOneAndUpdate(e,t,r){return await(0,g.executeOperation)(this.client,new E.FindOneAndUpdateOperation(this,e,t,(0,_.resolveOptions)(this,r)))}aggregate(e=[],t){if(!Array.isArray(e))throw new d.MongoInvalidArgumentError('Argument "pipeline" must be an array of aggregation stages');return new a.AggregationCursor(this.client,this.s.namespace,e,(0,_.resolveOptions)(this,t))}watch(e=[],t={}){return Array.isArray(e)||(t=e,e=[]),new s.ChangeStream(this,e,(0,_.resolveOptions)(this,t))}initializeUnorderedBulkOp(e){return new i.UnorderedBulkOperation(this,(0,_.resolveOptions)(this,e))}initializeOrderedBulkOp(e){return new o.OrderedBulkOperation(this,(0,_.resolveOptions)(this,e))}async count(e={},t={}){return await(0,g.executeOperation)(this.client,new h.CountOperation(this.fullNamespace,e,(0,_.resolveOptions)(this,t)))}listSearchIndexes(e,t){t="object"==typeof e?e:null==t?{}:t;const r=null==e||"object"==typeof e?null:e;return new l.ListSearchIndexesCursor(this,r,t)}async createSearchIndex(e){const[t]=await this.createSearchIndexes([e]);return t}async createSearchIndexes(e){return await(0,g.executeOperation)(this.client,new C.CreateSearchIndexesOperation(this,e))}async dropSearchIndex(e){return await(0,g.executeOperation)(this.client,new M.DropSearchIndexOperation(this,e))}async updateSearchIndex(e,t){return await(0,g.executeOperation)(this.client,new T.UpdateSearchIndexOperation(this,e,t))}}},19917:(e,t,r)=>{var n;r.d(t,{s:()=>n}),function(e){e[e.UNSET=0]="UNSET",e[e.OK=1]="OK",e[e.ERROR=2]="ERROR"}(n||(n={}))},21119:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MongoDBAWS=void 0;const n=r(75080),o=r(8500),i=r(17562),s=r(145),a=r(31057),c=r(19043),u=r(91566),l=r(93065),d={useBigInt64:!1,promoteLongs:!0,promoteValues:!0,promoteBuffers:!1,bsonRegExp:!1};class h extends a.AuthProvider{constructor(e){super(),this.credentialProvider=e,this.credentialFetcher=c.AWSTemporaryCredentialProvider.isAWSSDKInstalled?new c.AWSSDKCredentialProvider(e):new c.LegacyAWSTemporaryCredentialProvider}async auth(e){const{connection:t}=e;if(!e.credentials)throw new i.MongoMissingCredentialsError("AuthContext must provide credentials.");if("kModuleError"in o.aws4)throw o.aws4.kModuleError;const{sign:r}=o.aws4;if((0,s.maxWireVersion)(t)<9)throw new i.MongoCompatibilityError("MONGODB-AWS authentication requires MongoDB version 4.4 or later");e.credentials.username||(e.credentials=await async function(e,t){return function(t){if(!t.AccessKeyId||!t.SecretAccessKey)throw new i.MongoMissingCredentialsError("Could not obtain temporary MONGODB-AWS credentials");return new u.MongoCredentials({username:t.AccessKeyId,password:t.SecretAccessKey,source:e.source,mechanism:l.AuthMechanism.MONGODB_AWS,mechanismProperties:{AWS_SESSION_TOKEN:t.Token}})}(await t.getCredentials())}(e.credentials,this.credentialFetcher));const{credentials:a}=e,c=a.username,h=a.password,m=a.mechanismProperties.AWS_SESSION_TOKEN,f=c&&h&&m?{accessKeyId:c,secretAccessKey:h,sessionToken:m}:c&&h?{accessKeyId:c,secretAccessKey:h}:void 0,g=a.source,E=await(0,s.randomBytes)(32),S={saslStart:1,mechanism:"MONGODB-AWS",payload:n.serialize({r:E,p:110},d)},O=await t.command((0,s.ns)(`${g}.$cmd`),S,void 0),y=n.deserialize(O.payload.buffer,d),C=y.h,M=y.s.buffer;if(64!==M.length)throw new i.MongoRuntimeError(`Invalid server nonce length ${M.length}, expected 64`);if(!s.ByteUtils.equals(M.subarray(0,E.byteLength),E))throw new i.MongoRuntimeError("Server nonce does not begin with client nonce");if(C.length<1||C.length>255||-1!==C.indexOf(".."))throw new i.MongoRuntimeError(`Server returned an invalid host: "${C}"`);const T=r({method:"POST",host:C,region:p(y.h),service:"sts",headers:{"Content-Type":"application/x-www-form-urlencoded","Content-Length":43,"X-MongoDB-Server-Nonce":s.ByteUtils.toBase64(M),"X-MongoDB-GS2-CB-Flag":"n"},path:"/",body:"Action=GetCallerIdentity&Version=2011-06-15"},f),w={a:T.headers.Authorization,d:T.headers["X-Amz-Date"]};m&&(w.t=m);const v={saslContinue:1,conversationId:O.conversationId,payload:n.serialize(w,d)};await t.command((0,s.ns)(`${g}.$cmd`),v,void 0)}}function p(e){const t=e.split(".");return 1===t.length||"amazonaws"===t[1]?"us-east-1":t[1]}t.MongoDBAWS=h},22220:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MongoClient=t.ServerApiVersion=void 0;const n=r(36374),o=r(75080),i=r(22345),s=r(91566),a=r(93065),c=r(56463),u=r(75725),l=r(6875),d=r(91869),h=r(44120),p=r(17562),m=r(38944),f=r(93347),g=r(4642),E=r(47523),S=r(96357),O=r(35394),y=r(13700),C=r(31790),M=r(30588),T=r(1759),w=r(14019),v=r(145);t.ServerApiVersion=Object.freeze({v1:"1"});class b extends g.TypedEventEmitter{constructor(e,t){super(),this.on("error",v.noop),this.options=(0,l.parseOptions)(e,this,t);const r=Object.values(this.options.mongoLoggerOptions.componentSeverities).some((e=>e!==f.SeverityLevel.OFF));this.mongoLogger=r?new f.MongoLogger(this.options.mongoLoggerOptions):void 0;const n=this;this.s={url:e,bsonOptions:(0,o.resolveBSONOptions)(this.options),namespace:(0,v.ns)("admin"),hasBeenClosed:!1,sessionPool:new w.ServerSessionPool(this),activeSessions:new Set,activeCursors:new Set,authProviders:new m.MongoClientAuthProviders,get options(){return n.options},get readConcern(){return n.options.readConcern},get writeConcern(){return n.options.writeConcern},get readPreference(){return n.options.readPreference},get isMongoClient(){return!0}},this.checkForNonGenuineHosts()}async asyncDispose(){await this.close()}appendMetadata(e){this.options.additionalDriverInfo.push(e),this.options.metadata=(0,c.makeClientMetadata)(this.options),this.options.extendedMetadata=(0,c.addContainerMetadata)(this.options.metadata).then(void 0,v.squashError).then((e=>e??{}))}checkForNonGenuineHosts(){const e=this.options.hosts.filter((e=>(0,v.isHostMatch)(v.DOCUMENT_DB_CHECK,e.host))),t=(0,v.isHostMatch)(v.DOCUMENT_DB_CHECK,this.options.srvHost),r=this.options.hosts.filter((e=>(0,v.isHostMatch)(v.COSMOS_DB_CHECK,e.host))),n=(0,v.isHostMatch)(v.COSMOS_DB_CHECK,this.options.srvHost);0!==e.length||t?this.mongoLogger?.info("client",v.DOCUMENT_DB_MSG):(0!==r.length||n)&&this.mongoLogger?.info("client",v.COSMOS_DB_MSG)}get serverApi(){return this.options.serverApi&&Object.freeze({...this.options.serverApi})}get monitorCommands(){return this.options.monitorCommands}set monitorCommands(e){this.options.monitorCommands=e}get autoEncrypter(){return this.options.autoEncrypter}get readConcern(){return this.s.readConcern}get writeConcern(){return this.s.writeConcern}get readPreference(){return this.s.readPreference}get bsonOptions(){return this.s.bsonOptions}get timeoutMS(){return this.s.options.timeoutMS}async bulkWrite(e,t){if(this.autoEncrypter)throw new p.MongoInvalidArgumentError("MongoClient bulkWrite does not currently support automatic encryption.");return await new E.ClientBulkWriteExecutor(this,e,(0,v.resolveOptions)(this,t)).execute()}async connect(){if(this.connectionLock)return await this.connectionLock;try{this.connectionLock=this._connect(),await this.connectionLock}finally{this.connectionLock=void 0}return this}async _connect(){if(this.topology&&this.topology.isConnected())return this;const e=this.options;if(e.tls&&("string"==typeof e.tlsCAFile&&(e.ca??=await n.promises.readFile(e.tlsCAFile)),"string"==typeof e.tlsCRLFile&&(e.crl??=await n.promises.readFile(e.tlsCRLFile)),!("string"!=typeof e.tlsCertificateKeyFile||e.key&&e.cert))){const t=await n.promises.readFile(e.tlsCertificateKeyFile);e.key??=t,e.cert??=t}if("string"==typeof e.srvHost){const t=await(0,l.resolveSRVRecord)(e);for(const[r,n]of t.entries())e.hosts[r]=n}if(e.credentials?.mechanism===a.AuthMechanism.MONGODB_OIDC){const t=e.credentials?.mechanismProperties?.ALLOWED_HOSTS||s.DEFAULT_ALLOWED_HOSTS;if(!e.credentials?.mechanismProperties?.ENVIRONMENT)for(const r of e.hosts)if(!(0,v.hostMatchesWildcards)(r.toHostPort().host,t))throw new p.MongoInvalidArgumentError(`Host '${r}' is not valid for OIDC authentication with ALLOWED_HOSTS of '${t.join(",")}'`)}this.topology=new T.Topology(this,e.hosts,e),this.topology.once(T.Topology.OPEN,(()=>this.emit("open",this)));for(const e of d.MONGO_CLIENT_EVENTS)this.topology.on(e,((...t)=>this.emit(e,...t)));const t=async()=>{try{await(this.topology?.connect(e))}catch(e){throw this.topology?.close(),e}};return this.autoEncrypter?(await(this.autoEncrypter?.init()),await t(),await e.encrypter.connectInternalClient()):await t(),this}async close(e=!1){if(this.closeLock)return await this.closeLock;try{this.closeLock=this._close(),await this.closeLock}finally{this.closeLock=void 0}}async _close(){Object.defineProperty(this.s,"hasBeenClosed",{value:!0,enumerable:!0,configurable:!1,writable:!1}),this.topology?.closeCheckedOutConnections();const e=Array.from(this.s.activeCursors,(e=>e.close()));this.s.activeCursors.clear(),await Promise.all(e);const t=Array.from(this.s.activeSessions,(e=>e.endSession()));if(this.s.activeSessions.clear(),await Promise.all(t),null==this.topology)return;const r=(0,M.readPreferenceServerSelector)(y.ReadPreference.primaryPreferred),n=this.topology.description,o=Array.from(n.servers.values());if(0!==r(n,o).length){const e=Array.from(this.s.sessionPool.sessions,(({id:e})=>e));if(0!==e.length)try{class t extends O.AbstractOperation{constructor(){super(...arguments),this.ns=v.MongoDBNamespace.fromString("admin.$cmd"),this.SERVER_COMMAND_RESPONSE_TYPE=u.MongoDBResponse}buildCommand(t,r){return{endSessions:e}}buildOptions(e){return{timeoutContext:e,readPreference:y.ReadPreference.primaryPreferred,noResponse:!0}}get commandName(){return"endSessions"}}await(0,S.executeOperation)(this,new t)}catch(e){(0,v.squashError)(e)}}const i=this.topology;this.topology=void 0,i.close();const{encrypter:s}=this.options;s&&await s.close(this)}db(e,t){t=t??{},e||(e=this.s.options.dbName);const r=Object.assign({},this.options,t);return new h.Db(this,e,r)}static async connect(e,t){const r=new this(e,t);return await r.connect()}startSession(e){const t=new w.ClientSession(this,this.s.sessionPool,{explicit:!0,...e},this.options);return this.s.activeSessions.add(t),t.once("ended",(()=>{this.s.activeSessions.delete(t)})),t}async withSession(e,t){const r={owner:Symbol(),..."object"==typeof e?e:{}},n="function"==typeof e?e:t;if(null==n)throw new p.MongoInvalidArgumentError("Missing required callback parameter");const o=this.startSession(r);try{return await n(o)}finally{try{await o.endSession()}catch(e){(0,v.squashError)(e)}}}watch(e=[],t={}){return Array.isArray(e)||(t=e,e=[]),new i.ChangeStream(this,e,(0,v.resolveOptions)(this,t))}}t.MongoClient=b,(0,C.configureResourceManagement)(b.prototype)},22345:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ChangeStream=void 0;const n=r(19498),o=r(91869),i=r(61066),s=r(40251),a=r(44120),c=r(17562),u=r(22220),l=r(4642),d=r(31790),h=r(7799),p=r(145),m=["resumeAfter","startAfter","startAtOperationTime","fullDocument","fullDocumentBeforeChange","showExpandedEvents"],f={COLLECTION:Symbol("Collection"),DATABASE:Symbol("Database"),CLUSTER:Symbol("Cluster")},g=[o.RESUME_TOKEN_CHANGED,o.END,o.CLOSE],E="ChangeStream is closed";class S extends l.TypedEventEmitter{async asyncDispose(){await this.close()}constructor(e,t=[],r={}){let o;if(super(),this.pipeline=t,this.options={...r},delete this.options.writeConcern,e instanceof n.Collection)this.type=f.COLLECTION,o=e.s.db.client.options.serverSelectionTimeoutMS;else if(e instanceof a.Db)this.type=f.DATABASE,o=e.client.options.serverSelectionTimeoutMS;else{if(!(e instanceof u.MongoClient))throw new c.MongoChangeStreamError("Parent provided to ChangeStream constructor must be an instance of Collection, Db, or MongoClient");this.type=f.CLUSTER,o=e.options.serverSelectionTimeoutMS}this.contextOwner=Symbol(),this.parent=e,this.namespace=e.s.namespace,!this.options.readPreference&&e.readPreference&&(this.options.readPreference=e.readPreference),this.cursor=this._createChangeStreamCursor(r),this.isClosed=!1,this.mode=!1,this.on("newListener",(e=>{"change"===e&&this.cursor&&0===this.listenerCount("change")&&this._streamEvents(this.cursor)})),this.on("removeListener",(e=>{"change"===e&&0===this.listenerCount("change")&&this.cursor&&this.cursorStream?.removeAllListeners("data")})),null!=this.options.timeoutMS&&(this.timeoutContext=new h.CSOTTimeoutContext({timeoutMS:this.options.timeoutMS,serverSelectionTimeoutMS:o}))}get resumeToken(){return this.cursor?.resumeToken}async hasNext(){this._setIsIterator(),this.timeoutContext?.refresh();try{for(;;)try{return await this.cursor.hasNext()}catch(e){try{await this._processErrorIteratorMode(e,null!=this.cursor.id)}catch(e){if(e instanceof c.MongoOperationTimeoutError&&null==this.cursor.id)throw e;try{await this.close()}catch(e){(0,p.squashError)(e)}throw e}}}finally{this.timeoutContext?.clear()}}async next(){this._setIsIterator(),this.timeoutContext?.refresh();try{for(;;)try{const e=await this.cursor.next();return this._processChange(e??null)}catch(e){try{await this._processErrorIteratorMode(e,null!=this.cursor.id)}catch(e){if(e instanceof c.MongoOperationTimeoutError&&null==this.cursor.id)throw e;try{await this.close()}catch(e){(0,p.squashError)(e)}throw e}}}finally{this.timeoutContext?.clear()}}async tryNext(){this._setIsIterator(),this.timeoutContext?.refresh();try{for(;;)try{return await this.cursor.tryNext()??null}catch(e){try{await this._processErrorIteratorMode(e,null!=this.cursor.id)}catch(e){if(e instanceof c.MongoOperationTimeoutError&&null==this.cursor.id)throw e;try{await this.close()}catch(e){(0,p.squashError)(e)}throw e}}}finally{this.timeoutContext?.clear()}}async*[Symbol.asyncIterator](){if(!this.closed)try{for(;;)yield await this.next()}finally{try{await this.close()}catch(e){(0,p.squashError)(e)}}}get closed(){return this.isClosed||this.cursor.closed}async close(){this.timeoutContext?.clear(),this.timeoutContext=void 0,this.isClosed=!0;const e=this.cursor;try{await e.close()}finally{this._endStream()}}stream(e){if(this.closed)throw new c.MongoChangeStreamError(E);return this.streamOptions=e,this.cursor.stream(e)}_setIsEmitter(){if("iterator"===this.mode)throw new c.MongoAPIError("ChangeStream cannot be used as an EventEmitter after being used as an iterator");this.mode="emitter"}_setIsIterator(){if("emitter"===this.mode)throw new c.MongoAPIError("ChangeStream cannot be used as an iterator after being used as an EventEmitter");this.mode="iterator"}_createChangeStreamCursor(e){const t=(0,p.filterOptions)(e,m);this.type===f.CLUSTER&&(t.allChangesForCluster=!0);const r=[{$changeStream:t},...this.pipeline],n=this.type===f.CLUSTER?this.parent:this.type===f.DATABASE||this.type===f.COLLECTION?this.parent.client:null;if(null==n)throw new c.MongoRuntimeError(`Changestream type should only be one of cluster, database, collection. Found ${this.type.toString()}`);const o=new s.ChangeStreamCursor(n,this.namespace,r,{...e,timeoutContext:this.timeoutContext?new i.CursorTimeoutContext(this.timeoutContext,this.contextOwner):void 0});for(const e of g)o.on(e,(t=>this.emit(e,t)));return this.listenerCount(S.CHANGE)>0&&this._streamEvents(o),o}_closeEmitterModeWithError(e){this.emit(S.ERROR,e),this.close().then(void 0,p.squashError)}_streamEvents(e){this._setIsEmitter();const t=this.cursorStream??e.stream();this.cursorStream=t,t.on("data",(e=>{try{const t=this._processChange(e);this.emit(S.CHANGE,t)}catch(e){this.emit(S.ERROR,e)}this.timeoutContext?.refresh()})),t.on("error",(e=>this._processErrorStreamMode(e,null!=this.cursor.id)))}_endStream(){this.cursorStream?.removeAllListeners("data"),this.cursorStream?.removeAllListeners("close"),this.cursorStream?.removeAllListeners("end"),this.cursorStream?.destroy(),this.cursorStream=void 0}_processChange(e){if(this.isClosed)throw new c.MongoAPIError(E);if(null==e)throw new c.MongoRuntimeError(E);if(e&&!e._id)throw new c.MongoChangeStreamError("A change stream document has been received that lacks a resume token (_id).");return this.cursor.cacheResumeToken(e._id),this.options.startAtOperationTime=void 0,e}_processErrorStreamMode(e,t){this.isClosed||(t&&((0,c.isResumableError)(e,this.cursor.maxWireVersion)||e instanceof c.MongoOperationTimeoutError)?(this._endStream(),this.cursor.close().then((()=>this._resume(e)),(t=>((0,p.squashError)(t),this._resume(e)))).then((()=>{e instanceof c.MongoOperationTimeoutError&&this.emit(S.ERROR,e)}),(()=>this._closeEmitterModeWithError(e)))):this._closeEmitterModeWithError(e))}async _processErrorIteratorMode(e,t){if(this.isClosed)throw new c.MongoAPIError(E);if(!t||!((0,c.isResumableError)(e,this.cursor.maxWireVersion)||e instanceof c.MongoOperationTimeoutError)){try{await this.close()}catch(e){(0,p.squashError)(e)}throw e}try{await this.cursor.close()}catch(e){(0,p.squashError)(e)}if(await this._resume(e),e instanceof c.MongoOperationTimeoutError)throw e}async _resume(e){this.timeoutContext?.refresh();const t=(0,p.getTopology)(this.parent);try{await t.selectServer(this.cursor.readPreference,{operationName:"reconnect topology in change stream",timeoutContext:this.timeoutContext}),this.cursor=this._createChangeStreamCursor(this.cursor.resumeOptions)}catch{throw await this.close(),e}}}t.ChangeStream=S,S.RESPONSE=o.RESPONSE,S.MORE=o.MORE,S.INIT=o.INIT,S.CLOSE=o.CLOSE,S.CHANGE=o.CHANGE,S.END=o.END,S.ERROR=o.ERROR,S.RESUME_TOKEN_CHANGED=o.RESUME_TOKEN_CHANGED,(0,d.configureResourceManagement)(S.prototype)},22847:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ListIndexesOperation=t.DropIndexOperation=t.CreateIndexesOperation=void 0;const n=r(75725),o=r(17562),i=r(145),s=r(78130),a=r(35394),c=new Set(["background","unique","name","partialFilterExpression","sparse","hidden","expireAfterSeconds","storageEngine","collation","version","weights","default_language","language_override","textIndexVersion","2dsphereIndexVersion","bits","min","max","bucketSize","wildcardProjection"]);class u extends s.CommandOperation{constructor(e,t,r,o){super(e,o),this.SERVER_COMMAND_RESPONSE_TYPE=n.MongoDBResponse,this.options=o??{},this.options.collation=void 0,this.collectionName=t,this.indexes=r.map((e=>{const t=e.key instanceof Map?e.key:new Map(Object.entries(e.key)),r=e.name??Array.from(t).flat().join("_"),n=function(e){const t=Object.entries(e).filter((([e])=>c.has(e)));return Object.fromEntries(t.map((([e,t])=>"version"===e?["v",t]:[e,t])))}(e);return{...n,name:r,key:t}})),this.ns=e.s.namespace}static fromIndexDescriptionArray(e,t,r,n){return new u(e,t,r,n)}static fromIndexSpecification(e,t,r,n={}){const o=function(e){const t=new Map,r=Array.isArray(e)&&(n=e,!Array.isArray(n)||2!==n.length||"number"!=typeof(o=n[1])&&"2d"!==o&&"2dsphere"!==o&&"text"!==o&&"geoHaystack"!==o)?e:[e];var n,o;for(const e of r)if("string"==typeof e)t.set(e,1);else if(Array.isArray(e))t.set(e[0],e[1]??1);else if(e instanceof Map)for(const[r,n]of e)t.set(r,n);else if((0,i.isObject)(e))for(const[r,n]of Object.entries(e))t.set(r,n);return t}(r),s={...n,key:o};return new u(e,t,[s],n)}get commandName(){return"createIndexes"}buildCommandDocument(e){const t=this.options,r=this.indexes,n=(0,i.maxWireVersion)(e),s={createIndexes:this.collectionName,indexes:r};if(null!=t.commitQuorum){if(n<9)throw new o.MongoCompatibilityError("Option `commitQuorum` for `createIndexes` not supported on servers < 4.4");s.commitQuorum=t.commitQuorum}return s}handleOk(e){return this.indexes.map((e=>e.name||""))}}t.CreateIndexesOperation=u;class l extends s.CommandOperation{constructor(e,t,r){super(e,r),this.SERVER_COMMAND_RESPONSE_TYPE=n.MongoDBResponse,this.options=r??{},this.collection=e,this.indexName=t,this.ns=e.fullNamespace}get commandName(){return"dropIndexes"}buildCommandDocument(e){return{dropIndexes:this.collection.collectionName,index:this.indexName}}}t.DropIndexOperation=l;class d extends s.CommandOperation{constructor(e,t){super(e,t),this.SERVER_COMMAND_RESPONSE_TYPE=n.CursorResponse,this.options={...t},delete this.options.writeConcern,this.collectionNamespace=e.s.namespace}get commandName(){return"listIndexes"}buildCommandDocument(e){const t=(0,i.maxWireVersion)(e),r=this.options.batchSize?{batchSize:this.options.batchSize}:{},n={listIndexes:this.collectionNamespace.collection,cursor:r};return t>=9&&void 0!==this.options.comment&&(n.comment=this.options.comment),n}handleOk(e){return e}}t.ListIndexesOperation=d,(0,a.defineAspects)(d,[a.Aspect.READ_OPERATION,a.Aspect.RETRYABLE,a.Aspect.CURSOR_CREATING]),(0,a.defineAspects)(u,[a.Aspect.WRITE_OPERATION]),(0,a.defineAspects)(l,[a.Aspect.WRITE_OPERATION])},23611:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StreamDescription=void 0;const n=r(75080),o=r(89167),i=r(9188),s=["minWireVersion","maxWireVersion","maxBsonObjectSize","maxMessageSizeBytes","maxWriteBatchSize","logicalSessionTimeoutMinutes"];t.StreamDescription=class{constructor(e,t){this.hello=null,this.address=e,this.type=o.ServerType.Unknown,this.minWireVersion=void 0,this.maxWireVersion=void 0,this.maxBsonObjectSize=16777216,this.maxMessageSizeBytes=48e6,this.maxWriteBatchSize=1e5,this.logicalSessionTimeoutMinutes=t?.logicalSessionTimeoutMinutes,this.loadBalanced=!!t?.loadBalanced,this.compressors=t&&t.compressors&&Array.isArray(t.compressors)?t.compressors:[],this.serverConnectionId=null}receiveResponse(e){if(null!=e){this.hello=e,this.type=(0,i.parseServerType)(e),this.serverConnectionId="connectionId"in e?this.parseServerConnectionID(e.connectionId):null;for(const t of s)null!=e[t]&&(this[t]=e[t]),"__nodejs_mock_server__"in e&&(this.__nodejs_mock_server__=e.__nodejs_mock_server__);e.compression&&(this.compressor=this.compressors.filter((t=>e.compression?.includes(t)))[0])}}parseServerConnectionID(e){return n.Long.isLong(e)?e.toBigInt():BigInt(e)}}},26767:(e,t,r)=>{r.d(t,{u:()=>$});var n="object"==typeof globalThis?globalThis:"object"==typeof self?self:"object"==typeof window?window:"object"==typeof r.g?r.g:{},o="1.9.0",i=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/,s=function(e){var t=new Set([e]),r=new Set,n=e.match(i);if(!n)return function(){return!1};var o=+n[1],s=+n[2],a=+n[3];if(null!=n[4])return function(t){return t===e};function c(e){return r.add(e),!1}function u(e){return t.add(e),!0}return function(e){if(t.has(e))return!0;if(r.has(e))return!1;var n=e.match(i);if(!n)return c(e);var l=+n[1],d=+n[2],h=+n[3];return null!=n[4]||o!==l?c(e):0===o?s===d&&a<=h?u(e):c(e):s<=d?u(e):c(e)}}(o),a=o.split(".")[0],c=Symbol.for("opentelemetry.js.api."+a),u=n;function l(e,t,r,n){var i;void 0===n&&(n=!1);var s=u[c]=null!==(i=u[c])&&void 0!==i?i:{version:o};if(!n&&s[e]){var a=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+e);return r.error(a.stack||a.message),!1}return s.version!==o?(a=new Error("@opentelemetry/api: Registration of version v"+s.version+" for "+e+" does not match previously registered API v"+o),r.error(a.stack||a.message),!1):(s[e]=t,r.debug("@opentelemetry/api: Registered a global for "+e+" v"+o+"."),!0)}function d(e){var t,r,n=null===(t=u[c])||void 0===t?void 0:t.version;if(n&&s(n))return null===(r=u[c])||void 0===r?void 0:r[e]}function h(e,t){t.debug("@opentelemetry/api: Unregistering a global for "+e+" v"+o+".");var r=u[c];r&&delete r[e]}var p,m=new function e(t){var r=this;r._currentContext=t?new Map(t):new Map,r.getValue=function(e){return r._currentContext.get(e)},r.setValue=function(t,n){var o=new e(r._currentContext);return o._currentContext.set(t,n),o},r.deleteValue=function(t){var n=new e(r._currentContext);return n._currentContext.delete(t),n}},f=function(){function e(){}return e.prototype.active=function(){return m},e.prototype.with=function(e,t,r){for(var n=[],o=3;o<arguments.length;o++)n[o-3]=arguments[o];return t.call.apply(t,function(e,t,r){if(r||2===arguments.length)for(var n,o=0,i=t.length;o<i;o++)!n&&o in t||(n||(n=Array.prototype.slice.call(t,0,o)),n[o]=t[o]);return e.concat(n||Array.prototype.slice.call(t))}([r],function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,o,i=r.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(n=i.next()).done;)s.push(n.value)}catch(e){o={error:e}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(o)throw o.error}}return s}(n),!1))},e.prototype.bind=function(e,t){return t},e.prototype.enable=function(){return this},e.prototype.disable=function(){return this},e}(),g=function(){function e(e){this._namespace=e.namespace||"DiagComponentLogger"}return e.prototype.debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return E("debug",this._namespace,e)},e.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return E("error",this._namespace,e)},e.prototype.info=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return E("info",this._namespace,e)},e.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return E("warn",this._namespace,e)},e.prototype.verbose=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return E("verbose",this._namespace,e)},e}();function E(e,t,r){var n=d("diag");if(n)return r.unshift(t),n[e].apply(n,function(e,t,r){if(r||2===arguments.length)for(var n,o=0,i=t.length;o<i;o++)!n&&o in t||(n||(n=Array.prototype.slice.call(t,0,o)),n[o]=t[o]);return e.concat(n||Array.prototype.slice.call(t))}([],function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,o,i=r.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(n=i.next()).done;)s.push(n.value)}catch(e){o={error:e}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(o)throw o.error}}return s}(r),!1))}!function(e){e[e.NONE=0]="NONE",e[e.ERROR=30]="ERROR",e[e.WARN=50]="WARN",e[e.INFO=60]="INFO",e[e.DEBUG=70]="DEBUG",e[e.VERBOSE=80]="VERBOSE",e[e.ALL=9999]="ALL"}(p||(p={}));var S,O=function(){function e(){function e(e){return function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];var n=d("diag");if(n)return n[e].apply(n,function(e,t,r){if(r||2===arguments.length)for(var n,o=0,i=t.length;o<i;o++)!n&&o in t||(n||(n=Array.prototype.slice.call(t,0,o)),n[o]=t[o]);return e.concat(n||Array.prototype.slice.call(t))}([],function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,o,i=r.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(n=i.next()).done;)s.push(n.value)}catch(e){o={error:e}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(o)throw o.error}}return s}(t),!1))}}var t=this;t.setLogger=function(e,r){var n,o,i;if(void 0===r&&(r={logLevel:p.INFO}),e===t){var s=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return t.error(null!==(n=s.stack)&&void 0!==n?n:s.message),!1}"number"==typeof r&&(r={logLevel:r});var a=d("diag"),c=function(e,t){function r(r,n){var o=t[r];return"function"==typeof o&&e>=n?o.bind(t):function(){}}return e<p.NONE?e=p.NONE:e>p.ALL&&(e=p.ALL),t=t||{},{error:r("error",p.ERROR),warn:r("warn",p.WARN),info:r("info",p.INFO),debug:r("debug",p.DEBUG),verbose:r("verbose",p.VERBOSE)}}(null!==(o=r.logLevel)&&void 0!==o?o:p.INFO,e);if(a&&!r.suppressOverrideMessage){var u=null!==(i=(new Error).stack)&&void 0!==i?i:"<failed to generate stacktrace>";a.warn("Current logger will be overwritten from "+u),c.warn("Current logger will overwrite one already registered from "+u)}return l("diag",c,t,!0)},t.disable=function(){h("diag",t)},t.createComponentLogger=function(e){return new g(e)},t.verbose=e("verbose"),t.debug=e("debug"),t.info=e("info"),t.warn=e("warn"),t.error=e("error")}return e.instance=function(){return this._instance||(this._instance=new e),this._instance},e}(),y="context",C=new f,M=function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalContextManager=function(e){return l(y,e,O.instance())},e.prototype.active=function(){return this._getContextManager().active()},e.prototype.with=function(e,t,r){for(var n,o=[],i=3;i<arguments.length;i++)o[i-3]=arguments[i];return(n=this._getContextManager()).with.apply(n,function(e,t,r){if(r||2===arguments.length)for(var n,o=0,i=t.length;o<i;o++)!n&&o in t||(n||(n=Array.prototype.slice.call(t,0,o)),n[o]=t[o]);return e.concat(n||Array.prototype.slice.call(t))}([e,t,r],function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,o,i=r.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(n=i.next()).done;)s.push(n.value)}catch(e){o={error:e}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(o)throw o.error}}return s}(o),!1))},e.prototype.bind=function(e,t){return this._getContextManager().bind(e,t)},e.prototype._getContextManager=function(){return d(y)||C},e.prototype.disable=function(){this._getContextManager().disable(),h(y,O.instance())},e}();!function(e){e[e.NONE=0]="NONE",e[e.SAMPLED=1]="SAMPLED"}(S||(S={}));var T="0000000000000000",w="00000000000000000000000000000000",v={traceId:w,spanId:T,traceFlags:S.NONE},b=function(){function e(e){void 0===e&&(e=v),this._spanContext=e}return e.prototype.spanContext=function(){return this._spanContext},e.prototype.setAttribute=function(e,t){return this},e.prototype.setAttributes=function(e){return this},e.prototype.addEvent=function(e,t){return this},e.prototype.addLink=function(e){return this},e.prototype.addLinks=function(e){return this},e.prototype.setStatus=function(e){return this},e.prototype.updateName=function(e){return this},e.prototype.end=function(e){},e.prototype.isRecording=function(){return!1},e.prototype.recordException=function(e,t){},e}(),_=Symbol.for("OpenTelemetry Context Key SPAN");function R(e){return e.getValue(_)||void 0}function A(){return R(M.getInstance().active())}function N(e,t){return e.setValue(_,t)}function I(e){return e.deleteValue(_)}function P(e,t){return N(e,new b(t))}function x(e){var t;return null===(t=R(e))||void 0===t?void 0:t.spanContext()}var D=/^([0-9a-f]{32})$/i,k=/^[0-9a-f]{16}$/i;function L(e){return r=e.traceId,D.test(r)&&r!==w&&(t=e.spanId,k.test(t)&&t!==T);var t,r}function B(e){return new b(e)}var j=M.getInstance(),U=function(){function e(){}return e.prototype.startSpan=function(e,t,r){if(void 0===r&&(r=j.active()),Boolean(null==t?void 0:t.root))return new b;var n,o=r&&x(r);return"object"==typeof(n=o)&&"string"==typeof n.spanId&&"string"==typeof n.traceId&&"number"==typeof n.traceFlags&&L(o)?new b(o):new b},e.prototype.startActiveSpan=function(e,t,r,n){var o,i,s;if(!(arguments.length<2)){2===arguments.length?s=t:3===arguments.length?(o=t,s=r):(o=t,i=r,s=n);var a=null!=i?i:j.active(),c=this.startSpan(e,o,a),u=N(a,c);return j.with(u,s,void 0,c)}},e}(),G=new U,W=function(){function e(e,t,r,n){this._provider=e,this.name=t,this.version=r,this.options=n}return e.prototype.startSpan=function(e,t,r){return this._getTracer().startSpan(e,t,r)},e.prototype.startActiveSpan=function(e,t,r,n){var o=this._getTracer();return Reflect.apply(o.startActiveSpan,o,arguments)},e.prototype._getTracer=function(){if(this._delegate)return this._delegate;var e=this._provider.getDelegateTracer(this.name,this.version,this.options);return e?(this._delegate=e,this._delegate):G},e}(),V=new(function(){function e(){}return e.prototype.getTracer=function(e,t,r){return new U},e}()),F=function(){function e(){}return e.prototype.getTracer=function(e,t,r){var n;return null!==(n=this.getDelegateTracer(e,t,r))&&void 0!==n?n:new W(this,e,t,r)},e.prototype.getDelegate=function(){var e;return null!==(e=this._delegate)&&void 0!==e?e:V},e.prototype.setDelegate=function(e){this._delegate=e},e.prototype.getDelegateTracer=function(e,t,r){var n;return null===(n=this._delegate)||void 0===n?void 0:n.getTracer(e,t,r)},e}(),z="trace",$=function(){function e(){this._proxyTracerProvider=new F,this.wrapSpanContext=B,this.isSpanContextValid=L,this.deleteSpan=I,this.getSpan=R,this.getActiveSpan=A,this.getSpanContext=x,this.setSpan=N,this.setSpanContext=P}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalTracerProvider=function(e){var t=l(z,this._proxyTracerProvider,O.instance());return t&&this._proxyTracerProvider.setDelegate(e),t},e.prototype.getTracerProvider=function(){return d(z)||this._proxyTracerProvider},e.prototype.getTracer=function(e,t){return this.getTracerProvider().getTracer(e,t)},e.prototype.disable=function(){h(z,O.instance()),this._proxyTracerProvider=new F},e}().getInstance()},28113:(e,t,r)=>{var n=r(92992),o=r(81892),i=r(40642),s=r(90686),a=r(76023),c=r(79696).Buffer;function u(e){var t;"object"!=typeof e||c.isBuffer(e)||(t=e.passphrase,e=e.key),"string"==typeof e&&(e=c.from(e));var r,u,l=i(e,t),d=l.tag,h=l.data;switch(d){case"CERTIFICATE":u=n.certificate.decode(h,"der").tbsCertificate.subjectPublicKeyInfo;case"PUBLIC KEY":switch(u||(u=n.PublicKey.decode(h,"der")),r=u.algorithm.algorithm.join(".")){case"1.2.840.113549.1.1.1":return n.RSAPublicKey.decode(u.subjectPublicKey.data,"der");case"1.2.840.10045.2.1":return u.subjectPrivateKey=u.subjectPublicKey,{type:"ec",data:u};case"1.2.840.10040.4.1":return u.algorithm.params.pub_key=n.DSAparam.decode(u.subjectPublicKey.data,"der"),{type:"dsa",data:u.algorithm.params};default:throw new Error("unknown key id "+r)}case"ENCRYPTED PRIVATE KEY":h=function(e,t){var r=e.algorithm.decrypt.kde.kdeparams.salt,n=parseInt(e.algorithm.decrypt.kde.kdeparams.iters.toString(),10),i=o[e.algorithm.decrypt.cipher.algo.join(".")],u=e.algorithm.decrypt.cipher.iv,l=e.subjectPrivateKey,d=parseInt(i.split("-")[1],10)/8,h=a.pbkdf2Sync(t,r,n,d,"sha1"),p=s.createDecipheriv(i,h,u),m=[];return m.push(p.update(l)),m.push(p.final()),c.concat(m)}(h=n.EncryptedPrivateKey.decode(h,"der"),t);case"PRIVATE KEY":switch(r=(u=n.PrivateKey.decode(h,"der")).algorithm.algorithm.join(".")){case"1.2.840.113549.1.1.1":return n.RSAPrivateKey.decode(u.subjectPrivateKey,"der");case"1.2.840.10045.2.1":return{curve:u.algorithm.curve,privateKey:n.ECPrivateKey.decode(u.subjectPrivateKey,"der").privateKey};case"1.2.840.10040.4.1":return u.algorithm.params.priv_key=n.DSAparam.decode(u.subjectPrivateKey,"der"),{type:"dsa",params:u.algorithm.params};default:throw new Error("unknown key id "+r)}case"RSA PUBLIC KEY":return n.RSAPublicKey.decode(h,"der");case"RSA PRIVATE KEY":return n.RSAPrivateKey.decode(h,"der");case"DSA PRIVATE KEY":return{type:"dsa",params:n.DSAPrivateKey.decode(h,"der")};case"EC PRIVATE KEY":return{curve:(h=n.ECPrivateKey.decode(h,"der")).parameters.value,privateKey:h.privateKey};default:throw new Error("unknown key type "+d)}}u.signature=n.signature,e.exports=u},28541:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ReadConcern=t.ReadConcernLevel=void 0,t.ReadConcernLevel=Object.freeze({local:"local",majority:"majority",linearizable:"linearizable",available:"available",snapshot:"snapshot"});class r{constructor(e){this.level=t.ReadConcernLevel[e]??e}static fromOptions(e){if(null!=e){if(e.readConcern){const{readConcern:t}=e;if(t instanceof r)return t;if("string"==typeof t)return new r(t);if("level"in t&&t.level)return new r(t.level)}return e.level?new r(e.level):void 0}}static get MAJORITY(){return t.ReadConcernLevel.majority}static get AVAILABLE(){return t.ReadConcernLevel.available}static get LINEARIZABLE(){return t.ReadConcernLevel.linearizable}static get SNAPSHOT(){return t.ReadConcernLevel.snapshot}toJSON(){return{level:this.level}}}t.ReadConcern=r},29348:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OrderedBulkOperation=void 0;const n=r(75080),o=r(17562),i=r(54564);class s extends i.BulkOperationBase{constructor(e,t){super(e,t,!0)}addToOperationsList(e,t){const r=n.calculateObjectSize(t,{checkKeys:!1,ignoreUndefined:!1});if(r>=this.s.maxBsonObjectSize)throw new o.MongoInvalidArgumentError(`Document is larger than the maximum size ${this.s.maxBsonObjectSize}`);null==this.s.currentBatch&&(this.s.currentBatch=new i.Batch(e,this.s.currentIndex));const s=this.s.maxKeySize;if((this.s.currentBatchSize+1>=this.s.maxWriteBatchSize||this.s.currentBatchSize>0&&this.s.currentBatchSizeBytes+s+r>=this.s.maxBatchSizeBytes||this.s.currentBatch.batchType!==e)&&(this.s.batches.push(this.s.currentBatch),this.s.currentBatch=new i.Batch(e,this.s.currentIndex),this.s.currentBatchSize=0,this.s.currentBatchSizeBytes=0),e===i.BatchType.INSERT&&this.s.bulkResult.insertedIds.push({index:this.s.currentIndex,_id:t._id}),Array.isArray(t))throw new o.MongoInvalidArgumentError("Operation passed in cannot be an Array");return this.s.currentBatch.originalIndexes.push(this.s.currentIndex),this.s.currentBatch.operations.push(t),this.s.currentBatchSize+=1,this.s.currentBatchSizeBytes+=s+r,this.s.currentIndex+=1,this}}t.OrderedBulkOperation=s},30588:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MIN_SECONDARY_WRITE_WIRE_VERSION=void 0,t.writableServerSelector=function(){return function(e,t){return u(e,t.filter((e=>e.isWritable)))}},t.sameServerSelector=function(e){return function(t,r){return e?r.filter((t=>t.address===e.address&&t.type!==i.ServerType.Unknown)):[]}},t.secondaryWritableServerSelector=function(e,r){return!r||!e||e&&e<t.MIN_SECONDARY_WRITE_WIRE_VERSION?f(o.ReadPreference.primary):f(r)},t.readPreferenceServerSelector=f;const n=r(17562),o=r(13700),i=r(89167),s=1e4,a=90;function c(e,t){const r=Object.keys(e),n=Object.keys(t);for(let o=0;o<r.length;++o){const i=r[o];if(-1===n.indexOf(i)||t[i]!==e[i])return!1}return!0}function u(e,t){const r=t.reduce(((e,t)=>Math.min(t.roundTripTime,e)),1/0),n=r+e.localThresholdMS;return t.reduce(((e,t)=>(t.roundTripTime<=n&&t.roundTripTime>=r&&e.push(t),e)),[])}function l(e){return e.type===i.ServerType.RSPrimary}function d(e){return e.type===i.ServerType.RSSecondary}function h(e){return e.type===i.ServerType.RSSecondary||e.type===i.ServerType.RSPrimary}function p(e){return e.type!==i.ServerType.Unknown}function m(e){return e.type===i.ServerType.LoadBalancer}function f(e){if(!e.isValid())throw new n.MongoInvalidArgumentError("Invalid read preference specified");return function(t,r,f=[]){const g=t.commonWireVersion;if(g&&e.minWireVersion&&e.minWireVersion>g)throw new n.MongoCompatibilityError(`Minimum wire version '${e.minWireVersion}' required, but found '${g}'`);if(t.type===i.TopologyType.LoadBalanced)return r.filter(m);if(t.type===i.TopologyType.Unknown)return[];if(t.type===i.TopologyType.Single)return u(t,r.filter(p));if(t.type===i.TopologyType.Sharded){const e=r.filter((e=>!f.includes(e)));return u(t,(e.length>0?e:f).filter(p))}const E=e.mode;if(E===o.ReadPreference.PRIMARY)return r.filter(l);if(E===o.ReadPreference.PRIMARY_PREFERRED){const e=r.filter(l);if(e.length)return e}const S=E===o.ReadPreference.NEAREST?h:d,O=u(t,function(e,t){if(null==e.tags||Array.isArray(e.tags)&&0===e.tags.length)return t;for(let r=0;r<e.tags.length;++r){const n=e.tags[r],o=t.reduce(((e,t)=>(c(n,t.tags)&&e.push(t),e)),[]);if(o.length)return o}return[]}(e,function(e,t,r){if(null==e.maxStalenessSeconds||e.maxStalenessSeconds<0)return r;const o=e.maxStalenessSeconds,c=(t.heartbeatFrequencyMS+s)/1e3;if(o<c)throw new n.MongoInvalidArgumentError(`Option "maxStalenessSeconds" must be at least ${c} seconds`);if(o<a)throw new n.MongoInvalidArgumentError(`Option "maxStalenessSeconds" must be at least ${a} seconds`);if(t.type===i.TopologyType.ReplicaSetWithPrimary){const n=Array.from(t.servers.values()).filter(l)[0];return r.reduce(((r,o)=>((o.lastUpdateTime-o.lastWriteDate-(n.lastUpdateTime-n.lastWriteDate)+t.heartbeatFrequencyMS)/1e3<=(e.maxStalenessSeconds??0)&&r.push(o),r)),[])}if(t.type===i.TopologyType.ReplicaSetNoPrimary){if(0===r.length)return r;const n=r.reduce(((e,t)=>t.lastWriteDate>e.lastWriteDate?t:e));return r.reduce(((r,o)=>((n.lastWriteDate-o.lastWriteDate+t.heartbeatFrequencyMS)/1e3<=(e.maxStalenessSeconds??0)&&r.push(o),r)),[])}return r}(e,t,r.filter(S))));return E===o.ReadPreference.SECONDARY_PREFERRED&&0===O.length?r.filter(l):O}}t.MIN_SECONDARY_WRITE_WIRE_VERSION=13},30770:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.formatSort=function(e,t){if(null!=e){if("string"==typeof e)return new Map([[e,o(t)]]);if("object"!=typeof e)throw new n.MongoInvalidArgumentError(`Invalid sort format: ${JSON.stringify(e)} Sort must be a valid object`);return i=e,Array.isArray(i)?e.length?function(e){return Array.isArray(e)&&Array.isArray(e[0])}(e)?function(e){const t=e.map((([e,t])=>[`${e}`,o(t)]));return new Map(t)}(e):function(e){if(Array.isArray(e)&&2===e.length)try{return o(e[1]),!0}catch{return!1}return!1}(e)?(s=e,new Map([[`${s[0]}`,o([s[1]])]])):function(e){const t=e.map((e=>[`${e}`,1]));return new Map(t)}(e):void 0:(r=e)instanceof Map&&r.size>0?function(e){const t=Array.from(e).map((([e,t])=>[`${e}`,o(t)]));return new Map(t)}(e):Object.keys(e).length?function(e){const t=Object.entries(e).map((([e,t])=>[`${e}`,o(t)]));return new Map(t)}(e):void 0;var r,i,s}};const n=r(17562);function o(e=1){const t=`${e}`.toLowerCase();if("object"==typeof(r=e)&&null!=r&&"$meta"in r&&"string"==typeof r.$meta)return e;var r;switch(t){case"ascending":case"asc":case"1":return 1;case"descending":case"desc":case"-1":return-1;default:throw new n.MongoInvalidArgumentError(`Invalid sort direction: ${JSON.stringify(e)}`)}}},31057:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AuthProvider=t.AuthContext=void 0;const n=r(17562);t.AuthContext=class{constructor(e,t,r){this.reauthenticating=!1,this.connection=e,this.credentials=t,this.options=r}},t.AuthProvider=class{async prepare(e,t){return e}async reauth(e){if(e.reauthenticating)throw new n.MongoRuntimeError("Reauthentication already in progress.");try{e.reauthenticating=!0,await this.auth(e)}finally{e.reauthenticating=!1}}}},31480:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ValidateCollectionOperation=void 0;const n=r(75725),o=r(17562),i=r(78130);class s extends i.CommandOperation{constructor(e,t,r){super(e.s.db,r),this.SERVER_COMMAND_RESPONSE_TYPE=n.MongoDBResponse,this.options=r,this.collectionName=t}get commandName(){return"validate"}buildCommandDocument(e,t){return{validate:this.collectionName,...Object.fromEntries(Object.entries(this.options).filter((e=>"session"!==e[0])))}}handleOk(e){const t=super.handleOk(e);if(null!=t.result&&"string"!=typeof t.result)throw new o.MongoUnexpectedServerResponseError("Error with validation data");if(null!=t.result&&null!=t.result.match(/exception|corrupt/))throw new o.MongoUnexpectedServerResponseError(`Invalid collection ${this.collectionName}`);if(null!=t.valid&&!t.valid)throw new o.MongoUnexpectedServerResponseError(`Invalid collection ${this.collectionName}`);return e}}t.ValidateCollectionOperation=s},31790:(e,t,r)=>{function n(e){Symbol.asyncDispose&&Object.defineProperty(e,Symbol.asyncDispose,{value:async function(){await this.asyncDispose()},enumerable:!1,configurable:!0,writable:!0})}Object.defineProperty(t,"__esModule",{value:!0}),t.configureResourceManagement=n,t.configureExplicitResourceManagement=function(){const{MongoClient:e}=r(22220),{ClientSession:t}=r(14019),{AbstractCursor:o}=r(61066),{ChangeStream:i}=r(22345);n(e.prototype),n(t.prototype),n(o.prototype),n(i.prototype)}},32361:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ListIndexesCursor=void 0;const n=r(96357),o=r(22847),i=r(61066);class s extends i.AbstractCursor{constructor(e,t){super(e.client,e.s.namespace,t),this.parent=e,this.options=t}clone(){return new s(this.parent,{...this.options,...this.cursorOptions})}async _initialize(e){const t=new o.ListIndexesOperation(this.parent,{...this.cursorOptions,...this.options,session:e}),r=await(0,n.executeOperation)(this.parent.client,t,this.timeoutContext);return{server:t.server,session:e,response:r}}}t.ListIndexesCursor=s},32443:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CreateSearchIndexesOperation=void 0;const n=r(75725),o=r(35394);class i extends o.AbstractOperation{constructor(e,t){super(),this.SERVER_COMMAND_RESPONSE_TYPE=n.MongoDBResponse,this.collection=e,this.descriptions=t,this.ns=e.fullNamespace}get commandName(){return"createSearchIndexes"}buildCommand(e,t){return{createSearchIndexes:this.collection.fullNamespace.collection,indexes:this.descriptions}}handleOk(e){return super.handleOk(e).indexesCreated.map((e=>e.name))}buildOptions(e){return{session:this.session,timeoutContext:e}}}t.CreateSearchIndexesOperation=i},33104:(e,t,r)=>{var n=r(67787).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.GridFSBucketReadStream=void 0;const o=r(93874),i=r(61066),s=r(17562),a=r(7799);class c extends o.Readable{constructor(e,t,r,n,o){super({emitClose:!0}),this.s={bytesToTrim:0,bytesToSkip:0,bytesRead:0,chunks:e,expected:0,files:t,filter:n,init:!1,expectedEnd:0,options:{start:0,end:0,...o},readPreference:r,timeoutContext:null!=o?.timeoutMS?new a.CSOTTimeoutContext({timeoutMS:o.timeoutMS,serverSelectionTimeoutMS:0}):void 0}}_read(){this.destroyed||function(e,t){if(e.s.file)return t();e.s.init||(function(e){const 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);let r;try{r=e.s.timeoutContext?.getRemainingTimeMSOrThrow(`Download timed out after ${e.s.timeoutContext?.timeoutMS}ms`)}catch(t){return void(e.destroyed||e.destroy(t))}t.timeoutMS=r,e.s.files.findOne(e.s.filter,t).then((t=>{if(e.destroyed)return;if(!t){const t=`FileNotFound: file ${e.s.filter._id?e.s.filter._id.toString():e.s.filter.filename} was not found`,r=new s.MongoRuntimeError(t);return r.code="ENOENT",e.destroy(r)}if(t.length<=0)return void e.push(null);if(e.destroyed)return void e.destroy();try{e.s.bytesToSkip=function(e,t,r){if(r&&null!=r.start){if(r.start>t.length)throw new s.MongoInvalidArgumentError(`Stream start (${r.start}) must not be more than the length of the file (${t.length})`);if(r.start<0)throw new s.MongoInvalidArgumentError(`Stream start (${r.start}) must not be negative`);if(null!=r.end&&r.end<r.start)throw new s.MongoInvalidArgumentError(`Stream start (${r.start}) must not be greater than stream end (${r.end})`);return e.s.bytesRead=Math.floor(r.start/t.chunkSize)*t.chunkSize,e.s.expected=Math.floor(r.start/t.chunkSize),r.start-e.s.bytesRead}throw new s.MongoInvalidArgumentError("Start option must be defined")}(e,t,e.s.options)}catch(t){return e.destroy(t)}const r={files_id:t._id};if(e.s.options&&null!=e.s.options.start){const n=Math.floor(e.s.options.start/t.chunkSize);n>0&&(r.n={$gte:n})}let n;try{n=e.s.timeoutContext?.getRemainingTimeMSOrThrow(`Download timed out after ${e.s.timeoutContext?.timeoutMS}ms`)}catch(t){return e.destroy(t)}e.s.cursor=e.s.chunks.find(r,{timeoutMode:null!=e.s.options.timeoutMS?i.CursorTimeoutMode.LIFETIME:void 0,timeoutMS:n}).sort({n:1}),e.s.readPreference&&e.s.cursor.withReadPreference(e.s.readPreference),e.s.expectedEnd=Math.ceil(t.length/t.chunkSize),e.s.file=t;try{e.s.bytesToTrim=function(e,t,r,n){if(n&&null!=n.end){if(n.end>t.length)throw new s.MongoInvalidArgumentError(`Stream end (${n.end}) must not be more than the length of the file (${t.length})`);if(null==n.start||n.start<0)throw new s.MongoInvalidArgumentError(`Stream end (${n.end}) must not be negative`);const o=null!=n.start?Math.floor(n.start/t.chunkSize):0;return r.limit(Math.ceil(n.end/t.chunkSize)-o),e.s.expectedEnd=Math.ceil(n.end/t.chunkSize),Math.ceil(n.end/t.chunkSize)*t.chunkSize-n.end}throw new s.MongoInvalidArgumentError("End option must be defined")}(e,t,e.s.cursor,e.s.options)}catch(t){return e.destroy(t)}e.emit(c.FILE,t)}),(t=>{e.destroyed||e.destroy(t)}))}(e),e.s.init=!0),e.once("file",(()=>{t()}))}(this,(()=>function(e){if(e.destroyed)return;if(!e.s.cursor)return;if(!e.s.file)return;e.s.cursor.next().then((t=>{if(e.destroyed)return;if(!t)return e.push(null),void e.s.cursor?.close().then(void 0,(t=>e.destroy(t)));if(!e.s.file)return;const r=e.s.file.length-e.s.bytesRead,o=e.s.expected++,i=Math.min(e.s.file.chunkSize,r);if(t.n>o)return e.destroy(new s.MongoGridFSChunkError(`ChunkIsMissing: Got unexpected n: ${t.n}, expected: ${o}`));if(t.n<o)return e.destroy(new s.MongoGridFSChunkError(`ExtraChunk: Got unexpected n: ${t.n}, expected: ${o}`));let a=n.isBuffer(t.data)?t.data:t.data.buffer;if(a.byteLength!==i)return r<=0?e.destroy(new s.MongoGridFSChunkError(`ExtraChunk: Got unexpected n: ${t.n}, expected file length ${e.s.file.length} bytes but already read ${e.s.bytesRead} bytes`)):e.destroy(new s.MongoGridFSChunkError(`ChunkIsWrongSize: Got unexpected length: ${a.byteLength}, expected: ${i}`));if(e.s.bytesRead+=a.byteLength,0===a.byteLength)return e.push(null);let c=null,u=null;null!=e.s.bytesToSkip&&(c=e.s.bytesToSkip,e.s.bytesToSkip=0);const l=o===e.s.expectedEnd-1,d=e.s.options.end-e.s.bytesToSkip;l&&null!=e.s.bytesToTrim?u=e.s.file.chunkSize-e.s.bytesToTrim:e.s.options.end&&d<t.data.byteLength&&(u=d),null==c&&null==u||(a=a.slice(c||0,u||a.byteLength)),e.push(a)}),(t=>{e.destroyed||e.destroy(t)}))}(this)))}start(e=0){return u(this),this.s.options.start=e,this}end(e=0){return u(this),this.s.options.end=e,this}async abort(){this.push(null),this.destroy();const e=this.s.timeoutContext?.getRemainingTimeMSOrThrow();await(this.s.cursor?.close({timeoutMS:e}))}}function u(e){if(e.s.init)throw new s.MongoGridFSStreamError("Options cannot be changed after the stream is initialized")}t.GridFSBucketReadStream=c,c.FILE="file"},34080:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ClientBulkWriteOperation=void 0;const n=r(75725),o=r(145),i=r(78130),s=r(35394);class a extends i.CommandOperation{get commandName(){return"bulkWrite"}constructor(e,t){super(void 0,t),this.SERVER_COMMAND_RESPONSE_TYPE=n.ClientBulkWriteCursorResponse,this.commandBuilder=e,this.options=t,this.ns=new o.MongoDBNamespace("admin","$cmd")}resetBatch(){return this.commandBuilder.resetBatch()}get canRetryWrite(){return this.commandBuilder.isBatchRetryable}handleOk(e){return e}buildCommandDocument(e,t){const r=this.commandBuilder.buildBatch(e.description.maxMessageSizeBytes,e.description.maxWriteBatchSize,e.description.maxBsonObjectSize);return this.canRetryWrite||(this.options.willRetryWrite=!1),r}}t.ClientBulkWriteOperation=a,(0,s.defineAspects)(a,[s.Aspect.WRITE_OPERATION,s.Aspect.SKIP_COLLATION,s.Aspect.CURSOR_CREATING,s.Aspect.RETRYABLE,s.Aspect.COMMAND_BATCHING])},34563:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.loadGCPCredentials=async function(e){const t=(0,n.getGcpMetadata)();if("kModuleError"in t)return e;const{access_token:r}=await t.instance({property:"service-accounts/default/token"});return{...e,gcp:{accessToken:r}}};const n=r(8500)},35293:(e,t,r)=>{var n=r(67787).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.ScramSHA256=t.ScramSHA1=void 0;const o=r(21242),i=r(27348),s=r(75080),a=r(17562),c=r(145),u=r(31057),l=r(93065);class d extends u.AuthProvider{constructor(e){super(),this.cryptoMethod=e||"sha1"}async prepare(e,t){const r=this.cryptoMethod,n=t.credentials;if(!n)throw new a.MongoMissingCredentialsError("AuthContext must provide credentials.");const o=await(0,c.randomBytes)(24);return t.nonce=o,{...e,speculativeAuthenticate:{...m(r,n,o),db:n.source}}}async auth(e){const{reauthenticating:t,response:r}=e;return r?.speculativeAuthenticate&&!t?await f(this.cryptoMethod,r.speculativeAuthenticate,e):await async function(e,t){const{connection:r,credentials:n}=t;if(!n)throw new a.MongoMissingCredentialsError("AuthContext must provide credentials.");if(!t.nonce)throw new a.MongoInvalidArgumentError("AuthContext must contain a valid nonce property");const o=t.nonce,i=n.source,s=m(e,n,o),u=await r.command((0,c.ns)(`${i}.$cmd`),s,void 0);await f(e,u,t)}(this.cryptoMethod,e)}}function h(e){return e.replace("=","=3D").replace(",","=2C")}function p(e,t){return n.concat([n.from("n=","utf8"),n.from(e,"utf8"),n.from(",r=","utf8"),n.from(t.toString("base64"),"utf8")])}function m(e,t,r){const o=h(t.username);return{saslStart:1,mechanism:"sha1"===e?l.AuthMechanism.MONGODB_SCRAM_SHA1:l.AuthMechanism.MONGODB_SCRAM_SHA256,payload:new s.Binary(n.concat([n.from("n,,","utf8"),p(o,r)])),autoAuthorize:1,options:{skipEmptyExchange:!0}}}async function f(e,t,r){const u=r.connection,l=r.credentials;if(!l)throw new a.MongoMissingCredentialsError("AuthContext must provide credentials.");if(!r.nonce)throw new a.MongoInvalidArgumentError("Unable to continue SCRAM without valid nonce");const d=r.nonce,m=l.source,f=h(l.username),C=l.password,M="sha256"===e?(0,o.saslprep)(C):function(e,t){if("string"!=typeof e)throw new a.MongoInvalidArgumentError("Username must be a string");if("string"!=typeof t)throw new a.MongoInvalidArgumentError("Password must be a string");if(0===t.length)throw new a.MongoInvalidArgumentError("Password cannot be empty");let r;try{r=i.createHash("md5")}catch(e){if(i.getFips())throw new Error("Auth mechanism SCRAM-SHA-1 is not supported in FIPS mode");throw e}return r.update(`${e}:mongo:${t}`,"utf8"),r.digest("hex")}(f,C),T=n.isBuffer(t.payload)?new s.Binary(t.payload):t.payload,w=g(T),v=parseInt(w.i,10);if(v&&v<4096)throw new a.MongoRuntimeError(`Server returned an invalid iteration count ${v}`);const b=w.s,_=w.r;if(_.startsWith("nonce"))throw new a.MongoRuntimeError(`Server returned an invalid nonce: ${_}`);const R=`c=biws,r=${_}`,A=function(e,t,r,n){const o=[e,t.toString("base64"),r].join("_");if(null!=S[o])return S[o];const s=i.pbkdf2Sync(e,t,r,y[n],n);return O>=200&&(S={},O=0),S[o]=s,O+=1,s}(M,n.from(b,"base64"),v,e),N=E(e,A,"Client Key"),I=E(e,A,"Server Key"),P=(x=e,D=N,i.createHash(x).update(D).digest());var x,D;const k=[p(f,d),T.toString("utf8"),R].join(","),L=[R,`p=${function(e,t){n.isBuffer(e)||(e=n.from(e)),n.isBuffer(t)||(t=n.from(t));const r=Math.max(e.length,t.length),o=[];for(let n=0;n<r;n+=1)o.push(e[n]^t[n]);return n.from(o).toString("base64")}(N,E(e,P,k))}`].join(","),B=E(e,I,k),j={saslContinue:1,conversationId:t.conversationId,payload:new s.Binary(n.from(L))},U=await u.command((0,c.ns)(`${m}.$cmd`),j,void 0),G=g(U.payload);if(!function(e,t){if(e.length!==t.length)return!1;if("function"==typeof i.timingSafeEqual)return i.timingSafeEqual(e,t);let r=0;for(let n=0;n<e.length;n++)r|=e[n]^t[n];return 0===r}(n.from(G.v,"base64"),B))throw new a.MongoRuntimeError("Server returned an invalid signature");if(!1!==U.done)return;const W={saslContinue:1,conversationId:U.conversationId,payload:n.alloc(0)};await u.command((0,c.ns)(`${m}.$cmd`),W,void 0)}function g(e){const t={},r=e.toString("utf8").split(",");for(let e=0;e<r.length;e++){const n=(r[e].match(/^([^=]*)=(.*)$/)??[]).slice(1);t[n[0]]=n[1]}return t}function E(e,t,r){return i.createHmac(e,t).update(r).digest()}let S={},O=0;const y={sha256:32,sha1:20};t.ScramSHA1=class extends d{constructor(){super("sha1")}},t.ScramSHA256=class extends d{constructor(){super("sha256")}}},35369:(e,t)=>{t.endianness=function(){return"LE"},t.hostname=function(){return"undefined"!=typeof location?location.hostname:""},t.loadavg=function(){return[]},t.uptime=function(){return 0},t.freemem=function(){return Number.MAX_VALUE},t.totalmem=function(){return Number.MAX_VALUE},t.cpus=function(){return[]},t.type=function(){return"Browser"},t.release=function(){return"undefined"!=typeof navigator?navigator.appVersion:""},t.networkInterfaces=t.getNetworkInterfaces=function(){return{}},t.arch=function(){return"javascript"},t.platform=function(){return"browser"},t.tmpdir=t.tmpDir=function(){return"/tmp"},t.EOL="\n",t.homedir=function(){return"/"}},35394:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractOperation=t.Aspect=void 0,t.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};const n=r(75080),o=r(13700);t.Aspect={READ_OPERATION:Symbol("READ_OPERATION"),WRITE_OPERATION:Symbol("WRITE_OPERATION"),RETRYABLE:Symbol("RETRYABLE"),EXPLAINABLE:Symbol("EXPLAINABLE"),SKIP_COLLATION:Symbol("SKIP_COLLATION"),CURSOR_CREATING:Symbol("CURSOR_CREATING"),MUST_SELECT_SAME_SERVER:Symbol("MUST_SELECT_SAME_SERVER"),COMMAND_BATCHING:Symbol("COMMAND_BATCHING")},t.AbstractOperation=class{constructor(e={}){this.readPreference=this.hasAspect(t.Aspect.WRITE_OPERATION)?o.ReadPreference.primary:o.ReadPreference.fromOptions(e)??o.ReadPreference.primary,this.bsonOptions=(0,n.resolveBSONOptions)(e),this._session=null!=e.session?e.session:void 0,this.options=e,this.bypassPinningCheck=!!e.bypassPinningCheck}hasAspect(e){const t=this.constructor;return null!=t.aspects&&t.aspects.has(e)}get session(){return this._session}set session(e){this._session=e}clearSession(){this._session=void 0}resetBatch(){return!0}get canRetryRead(){return this.hasAspect(t.Aspect.RETRYABLE)&&this.hasAspect(t.Aspect.READ_OPERATION)}get canRetryWrite(){return this.hasAspect(t.Aspect.RETRYABLE)&&this.hasAspect(t.Aspect.WRITE_OPERATION)}handleOk(e){return e.toObject(this.bsonOptions)}handleError(e){throw e}}},36411:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Explain=t.ExplainVerbosity=void 0,t.validateExplainTimeoutOptions=function(e,t){const{maxTimeMS:r,timeoutMS:o}=e;if(null!=o&&(null!=r||null!=t?.maxTimeMS))throw new n.MongoAPIError("Cannot use maxTimeMS with timeoutMS for explain commands.")},t.decorateWithExplain=function(e,t){const{verbosity:r,maxTimeMS:n}=t,o={explain:e,verbosity:r};return"number"==typeof n&&(o.maxTimeMS=n),o};const n=r(17562);t.ExplainVerbosity=Object.freeze({queryPlanner:"queryPlanner",queryPlannerExtended:"queryPlannerExtended",executionStats:"executionStats",allPlansExecution:"allPlansExecution"});class o{constructor(e,r){this.verbosity="boolean"==typeof e?e?t.ExplainVerbosity.allPlansExecution:t.ExplainVerbosity.queryPlanner:e,this.maxTimeMS=r}static fromOptions({explain:e}={}){if(null==e)return;if("boolean"==typeof e||"string"==typeof e)return new o(e);const{verbosity:t,maxTimeMS:r}=e;return new o(t,r)}}t.Explain=o},36649:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ExplainableCursor=void 0;const n=r(61066);class o extends n.AbstractCursor{resolveExplainTimeoutOptions(e,t){let r,n;return null==e&&null==t?(r=void 0,n=void 0):null!=e&&null==t?(r="object"!=typeof e||"verbosity"in e?e:void 0,n="object"==typeof e&&"timeoutMS"in e?e:void 0):(r=e,n=t),{timeout:n,explain:r}}}t.ExplainableCursor=o},38216:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SENSITIVE_COMMANDS=t.CommandFailedEvent=t.CommandSucceededEvent=t.CommandStartedEvent=void 0;const n=r(91869),o=r(145),i=r(15620);t.CommandStartedEvent=class{constructor(e,r,o){this.name=n.COMMAND_STARTED;const i=h(r),s=a(i),{address:c,connectionId:l,serviceId:d}=p(e);t.SENSITIVE_COMMANDS.has(s)&&(this.commandObj={},this.commandObj[s]=!0),this.address=c,this.connectionId=l,this.serviceId=d,this.requestId=r.requestId,this.databaseName=r.databaseName,this.commandName=s,this.command=u(s,i,i),this.serverConnectionId=o}get hasServiceId(){return!!this.serviceId}},t.CommandSucceededEvent=class{constructor(e,t,r,i,s){this.name=n.COMMAND_SUCCEEDED;const c=h(t),l=a(c),{address:d,connectionId:m,serviceId:f}=p(e);this.address=d,this.connectionId=m,this.serviceId=f,this.requestId=t.requestId,this.commandName=l,this.duration=(0,o.calculateDurationInMs)(i),this.reply=u(l,c,function(e){return e&&e.result?e.result:e}(r)),this.serverConnectionId=s,this.databaseName=t.databaseName}get hasServiceId(){return!!this.serviceId}},t.CommandFailedEvent=class{constructor(e,t,r,i,s){this.name=n.COMMAND_FAILED;const c=h(t),l=a(c),{address:d,connectionId:m,serviceId:f}=p(e);this.address=d,this.connectionId=m,this.serviceId=f,this.requestId=t.requestId,this.commandName=l,this.duration=(0,o.calculateDurationInMs)(i),this.failure=u(l,c,r),this.serverConnectionId=s,this.databaseName=t.databaseName}get hasServiceId(){return!!this.serviceId}},t.SENSITIVE_COMMANDS=new Set(["authenticate","saslStart","saslContinue","getnonce","createUser","updateUser","copydbgetnonce","copydbsaslstart","copydb"]);const s=new Set(["hello",n.LEGACY_HELLO_COMMAND,n.LEGACY_HELLO_COMMAND_CAMEL_CASE]),a=e=>Object.keys(e)[0],c=e=>e.ns.split(".")[1],u=(e,r,n)=>t.SENSITIVE_COMMANDS.has(e)||s.has(e)&&r.speculativeAuthenticate?{}:n,l={$query:"filter",$orderby:"sort",$hint:"hint",$comment:"comment",$maxScan:"maxScan",$max:"max",$min:"min",$returnKey:"returnKey",$showDiskLoc:"showRecordId",$maxTimeMS:"maxTimeMS",$snapshot:"snapshot"},d={numberToSkip:"skip",numberToReturn:"batchSize",returnFieldSelector:"projection"};function h(e){if(e instanceof i.OpMsgRequest){const t={...e.command};return t.ops instanceof i.DocumentSequence&&(t.ops=t.ops.documents),t.nsInfo instanceof i.DocumentSequence&&(t.nsInfo=t.nsInfo.documents),t}if(e.query?.$query){let t;return"admin.$cmd"===e.ns?t=Object.assign({},e.query.$query):(t={find:c(e)},Object.keys(l).forEach((r=>{null!=e.query[r]&&(t[l[r]]={...e.query[r]})}))),Object.keys(d).forEach((r=>{const n=r;null!=e[n]&&(t[d[n]]=e[n])})),t}let t={};const r={...e};return e.query&&(t={...e.query},r.query=t),e.query?t:r}function p(e){let t;return"id"in e&&(t=e.id),{address:e.address,serviceId:e.serviceId,connectionId:t}}},38944:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MongoClientAuthProviders=void 0;const n=r(95750),o=r(21119),i=r(63257),s=r(88822),a=r(50373),c=r(8294),u=r(70839),l=r(93065),d=r(35293),h=r(64647),p=r(17562),m=new Map([[l.AuthMechanism.MONGODB_AWS,({AWS_CREDENTIAL_PROVIDER:e})=>new o.MongoDBAWS(e)],[l.AuthMechanism.MONGODB_CR,()=>{throw new p.MongoInvalidArgumentError("MONGODB-CR is no longer a supported auth mechanism in MongoDB 4.0+")}],[l.AuthMechanism.MONGODB_GSSAPI,()=>new n.GSSAPI],[l.AuthMechanism.MONGODB_OIDC,e=>new i.MongoDBOIDC(function(e){if(e.OIDC_HUMAN_CALLBACK)return new a.HumanCallbackWorkflow(new c.TokenCache,e.OIDC_HUMAN_CALLBACK);if(e.OIDC_CALLBACK)return new s.AutomatedCallbackWorkflow(new c.TokenCache,e.OIDC_CALLBACK);{const t=e.ENVIRONMENT,r=i.OIDC_WORKFLOWS.get(t)?.();if(!r)throw new p.MongoInvalidArgumentError(`Could not load workflow for environment ${e.ENVIRONMENT}`);return r}}(e))],[l.AuthMechanism.MONGODB_PLAIN,()=>new u.Plain],[l.AuthMechanism.MONGODB_SCRAM_SHA1,()=>new d.ScramSHA1],[l.AuthMechanism.MONGODB_SCRAM_SHA256,()=>new d.ScramSHA256],[l.AuthMechanism.MONGODB_X509,()=>new h.X509]]);t.MongoClientAuthProviders=class{constructor(){this.existingProviders=new Map}getOrCreateProvider(e,t){const r=this.existingProviders.get(e);if(r)return r;const n=m.get(e);if(!n)throw new p.MongoInvalidArgumentError(`authMechanism ${e} not supported`);const o=n(t);return this.existingProviders.set(e,o),o}}},40012:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WriteConcern=t.WRITE_CONCERN_KEYS=void 0,t.throwIfWriteConcernError=function(e){if("object"==typeof e&&null!=e){const t=n.MongoDBResponse.is(e)&&e.has("writeConcernError")?e.toObject():!n.MongoDBResponse.is(e)&&"writeConcernError"in e?e:null;if(null!=t)throw new o.MongoWriteConcernError(t)}};const n=r(75725),o=r(17562);t.WRITE_CONCERN_KEYS=["w","wtimeout","j","journal","fsync"];class i{constructor(e,t,r,n){null!=e&&(Number.isNaN(Number(e))?this.w=e:this.w=Number(e)),null!=t&&(this.wtimeoutMS=this.wtimeout=t),null!=r&&(this.journal=this.j=r),null!=n&&(this.journal=this.j=!!n)}static apply(e,t){const r={};return null!=t.w&&(r.w=t.w),null!=t.wtimeoutMS&&(r.wtimeout=t.wtimeoutMS),null!=t.journal&&(r.j=t.j),e.writeConcern=r,e}static fromOptions(e,t){if(null==e)return;let r;t=t??{},r="string"==typeof e||"number"==typeof e?{w:e}:e instanceof i?e:e.writeConcern;const n={...t instanceof i?t:t.writeConcern,...r},{w:o,wtimeout:s,j:a,fsync:c,journal:u,wtimeoutMS:l}=n;return null!=o||null!=s||null!=l||null!=a||null!=u||null!=c?new i(o,s??l,a??u,c):void 0}}t.WriteConcern=i},40251:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ChangeStreamCursor=void 0;const n=r(22345),o=r(91869),i=r(62016),s=r(96357),a=r(145),c=r(61066);class u extends c.AbstractCursor{constructor(e,t,r=[],n={}){super(e,t,{...n,tailable:!0,awaitData:!0}),this.pipeline=r,this.changeStreamCursorOptions=n,this._resumeToken=null,this.startAtOperationTime=n.startAtOperationTime??null,n.startAfter?this.resumeToken=n.startAfter:n.resumeAfter&&(this.resumeToken=n.resumeAfter)}set resumeToken(e){this._resumeToken=e,this.emit(n.ChangeStream.RESUME_TOKEN_CHANGED,e)}get resumeToken(){return this._resumeToken}get resumeOptions(){const e={...this.changeStreamCursorOptions};for(const t of["resumeAfter","startAfter","startAtOperationTime"])delete e[t];return null!=this.resumeToken?this.changeStreamCursorOptions.startAfter&&!this.hasReceived?e.startAfter=this.resumeToken:e.resumeAfter=this.resumeToken:null!=this.startAtOperationTime&&(0,a.maxWireVersion)(this.server)>=7&&(e.startAtOperationTime=this.startAtOperationTime),e}cacheResumeToken(e){0===this.bufferedCount()&&this.postBatchResumeToken?this.resumeToken=this.postBatchResumeToken:this.resumeToken=e,this.hasReceived=!0}_processBatch(e){const{postBatchResumeToken:t}=e;t&&(this.postBatchResumeToken=t,0===e.batchSize&&(this.resumeToken=t))}clone(){return new u(this.client,this.namespace,this.pipeline,{...this.cursorOptions})}async _initialize(e){const t=new i.AggregateOperation(this.namespace,this.pipeline,{...this.cursorOptions,...this.changeStreamCursorOptions,session:e}),r=await(0,s.executeOperation)(e.client,t,this.timeoutContext),n=t.server;return this.maxWireVersion=(0,a.maxWireVersion)(n),null==this.startAtOperationTime&&null==this.changeStreamCursorOptions.resumeAfter&&null==this.changeStreamCursorOptions.startAfter&&this.maxWireVersion>=7&&(this.startAtOperationTime=r.operationTime),this._processBatch(r),this.emit(o.INIT,r),this.emit(o.RESPONSE),{server:n,session:e,response:r}}async getMore(e){const t=await super.getMore(e);return this.maxWireVersion=(0,a.maxWireVersion)(this.server),this._processBatch(t),this.emit(n.ChangeStream.MORE,t),this.emit(n.ChangeStream.RESPONSE),t}}t.ChangeStreamCursor=u},40642:(e,t,r)=>{var n=/Proc-Type: 4,ENCRYPTED[\n\r]+DEK-Info: AES-((?:128)|(?:192)|(?:256))-CBC,([0-9A-H]+)[\n\r]+([0-9A-z\n\r+/=]+)[\n\r]+/m,o=/^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----/m,i=/^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----([0-9A-z\n\r+/=]+)-----END \1-----$/m,s=r(23457),a=r(90686),c=r(79696).Buffer;e.exports=function(e,t){var r,u=e.toString(),l=u.match(n);if(l){var d="aes"+l[1],h=c.from(l[2],"hex"),p=c.from(l[3].replace(/[\r\n]/g,""),"base64"),m=s(t,h.slice(0,8),parseInt(l[1],10)).key,f=[],g=a.createDecipheriv(d,m,h);f.push(g.update(p)),f.push(g.final()),r=c.concat(f)}else{var E=u.match(i);r=c.from(E[2].replace(/[\r\n]/g,""),"base64")}return{tag:u.match(o)[1],data:r}}},40866:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.UpdateSearchIndexOperation=void 0;const n=r(75725),o=r(35394);class i extends o.AbstractOperation{constructor(e,t,r){super(),this.SERVER_COMMAND_RESPONSE_TYPE=n.MongoDBResponse,this.collection=e,this.name=t,this.definition=r,this.ns=e.fullNamespace}get commandName(){return"updateSearchIndex"}buildCommand(e,t){return{updateSearchIndex:this.collection.fullNamespace.collection,name:this.name,definition:this.definition}}handleOk(e){}buildOptions(e){return{session:this.session,timeoutContext:e}}}t.UpdateSearchIndexOperation=i},43135:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ServerHeartbeatFailedEvent=t.ServerHeartbeatSucceededEvent=t.ServerHeartbeatStartedEvent=t.TopologyClosedEvent=t.TopologyOpeningEvent=t.TopologyDescriptionChangedEvent=t.ServerClosedEvent=t.ServerOpeningEvent=t.ServerDescriptionChangedEvent=void 0;const n=r(91869);t.ServerDescriptionChangedEvent=class{constructor(e,t,r,o){this.name=n.SERVER_DESCRIPTION_CHANGED,this.topologyId=e,this.address=t,this.previousDescription=r,this.newDescription=o}},t.ServerOpeningEvent=class{constructor(e,t){this.name=n.SERVER_OPENING,this.topologyId=e,this.address=t}},t.ServerClosedEvent=class{constructor(e,t){this.name=n.SERVER_CLOSED,this.topologyId=e,this.address=t}},t.TopologyDescriptionChangedEvent=class{constructor(e,t,r){this.name=n.TOPOLOGY_DESCRIPTION_CHANGED,this.topologyId=e,this.previousDescription=t,this.newDescription=r}},t.TopologyOpeningEvent=class{constructor(e){this.name=n.TOPOLOGY_OPENING,this.topologyId=e}},t.TopologyClosedEvent=class{constructor(e){this.name=n.TOPOLOGY_CLOSED,this.topologyId=e}},t.ServerHeartbeatStartedEvent=class{constructor(e,t){this.name=n.SERVER_HEARTBEAT_STARTED,this.connectionId=e,this.awaited=t}},t.ServerHeartbeatSucceededEvent=class{constructor(e,t,r,o){this.name=n.SERVER_HEARTBEAT_SUCCEEDED,this.connectionId=e,this.duration=t,this.reply=r??{},this.awaited=o}},t.ServerHeartbeatFailedEvent=class{constructor(e,t,r,o){this.name=n.SERVER_HEARTBEAT_FAILED,this.connectionId=e,this.duration=t,this.failure=r,this.awaited=o}}},44120:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Db=void 0;const n=r(71235),o=r(75080),i=r(22345),s=r(19498),a=r(91869),c=r(68526),u=r(55546),l=r(69429),d=r(17562),h=r(69878),p=r(95662),m=r(96357),f=r(22847),g=r(88536),E=r(64125),S=r(61861),O=r(17668),y=r(58127),C=r(5136),M=r(28541),T=r(13700),w=r(145),v=r(40012),b=["writeConcern","readPreference","readPreferenceTags","native_parser","forceServerObjectId","pkFactory","serializeFunctions","raw","authSource","ignoreUndefined","readConcern","retryMiliSeconds","numberOfRetries","useBigInt64","promoteBuffers","promoteLongs","bsonRegExp","enableUtf8Validation","promoteValues","compression","retryWrites","timeoutMS"];class _{constructor(e,t,r){if(r=r??{},r=(0,w.filterOptions)(r,b),"string"==typeof t&&t.includes("."))throw new d.MongoInvalidArgumentError("Database names cannot contain the character '.'");this.s={options:r,readPreference:T.ReadPreference.fromOptions(r),bsonOptions:(0,o.resolveBSONOptions)(r,e),pkFactory:r?.pkFactory??w.DEFAULT_PK_FACTORY,readConcern:M.ReadConcern.fromOptions(r),writeConcern:v.WriteConcern.fromOptions(r),namespace:new w.MongoDBNamespace(t)},this.client=e}get databaseName(){return this.s.namespace.db}get options(){return this.s.options}get secondaryOk(){return"primary"!==this.s.readPreference?.preference||!1}get readConcern(){return this.s.readConcern}get readPreference(){return null==this.s.readPreference?this.client.readPreference:this.s.readPreference}get bsonOptions(){return this.s.bsonOptions}get writeConcern(){return this.s.writeConcern}get namespace(){return this.s.namespace.toString()}get timeoutMS(){return this.s.options?.timeoutMS}async createCollection(e,t){return t=(0,w.resolveOptions)(this,t),await(0,h.createCollections)(this,e,t)}async command(e,t){return await(0,m.executeOperation)(this.client,new O.RunCommandOperation(this.s.namespace,e,(0,w.resolveOptions)(void 0,{...(0,o.resolveBSONOptions)(t),timeoutMS:t?.timeoutMS??this.timeoutMS,session:t?.session,readPreference:t?.readPreference,signal:t?.signal})))}aggregate(e=[],t){return new c.AggregationCursor(this.client,this.s.namespace,e,(0,w.resolveOptions)(this,t))}admin(){return new n.Admin(this)}collection(e,t={}){if("function"==typeof t)throw new d.MongoInvalidArgumentError("The callback form of this helper has been removed.");return new s.Collection(this,e,(0,w.resolveOptions)(this,t))}async stats(e){return await(0,m.executeOperation)(this.client,new C.DbStatsOperation(this,(0,w.resolveOptions)(this,e)))}listCollections(e={},t={}){return new u.ListCollectionsCursor(this,e,(0,w.resolveOptions)(this,t))}async renameCollection(e,t,r){return await(0,m.executeOperation)(this.client,new S.RenameOperation(this.collection(e),t,(0,w.resolveOptions)(void 0,{...r,new_collection:!0,readPreference:T.ReadPreference.primary})))}async dropCollection(e,t){return t=(0,w.resolveOptions)(this,t),await(0,p.dropCollections)(this,e,t)}async dropDatabase(e){return await(0,m.executeOperation)(this.client,new p.DropDatabaseOperation(this,(0,w.resolveOptions)(this,e)))}async collections(e){return e=(0,w.resolveOptions)(this,e),(await this.listCollections({},{...e,nameOnly:!0}).toArray()).filter((({name:e})=>!e.includes("$"))).map((({name:e})=>new s.Collection(this,e,this.s.options)))}async createIndex(e,t,r){return(await(0,m.executeOperation)(this.client,f.CreateIndexesOperation.fromIndexSpecification(this,e,t,r)))[0]}async removeUser(e,t){return await(0,m.executeOperation)(this.client,new E.RemoveUserOperation(this,e,(0,w.resolveOptions)(this,t)))}async setProfilingLevel(e,t){return await(0,m.executeOperation)(this.client,new y.SetProfilingLevelOperation(this,e,(0,w.resolveOptions)(this,t)))}async profilingLevel(e){return await(0,m.executeOperation)(this.client,new g.ProfilingLevelOperation(this,(0,w.resolveOptions)(this,e)))}async indexInformation(e,t){return await this.collection(e).indexInformation((0,w.resolveOptions)(this,t))}watch(e=[],t={}){return Array.isArray(e)||(t=e,e=[]),new i.ChangeStream(this,e,(0,w.resolveOptions)(this,t))}runCursorCommand(e,t){return new l.RunCommandCursor(this,e,t)}}t.Db=_,_.SYSTEM_NAMESPACE_COLLECTION=a.SYSTEM_NAMESPACE_COLLECTION,_.SYSTEM_INDEX_COLLECTION=a.SYSTEM_INDEX_COLLECTION,_.SYSTEM_PROFILE_COLLECTION=a.SYSTEM_PROFILE_COLLECTION,_.SYSTEM_USER_COLLECTION=a.SYSTEM_USER_COLLECTION,_.SYSTEM_COMMAND_COLLECTION=a.SYSTEM_COMMAND_COLLECTION,_.SYSTEM_JS_COLLECTION=a.SYSTEM_JS_COLLECTION},46195:e=>{e.exports={rE:"6.19.0"}},47523:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ClientBulkWriteExecutor=void 0;const n=r(61066),o=r(7180),i=r(17562),s=r(7799),a=r(145),c=r(40012),u=r(96357),l=r(34080),d=r(11737),h=r(6987);t.ClientBulkWriteExecutor=class{constructor(e,t,r){if(0===t.length)throw new i.MongoClientBulkWriteExecutionError("No client bulk write models were provided.");if(this.client=e,this.operations=t,this.options={ordered:!0,bypassDocumentValidation:!1,verboseResults:!1,...r},this.options.writeConcern||(this.options.writeConcern=c.WriteConcern.fromOptions(this.client.s.options)),0===this.options.writeConcern?.w){if(this.options.verboseResults)throw new i.MongoInvalidArgumentError("Cannot request unacknowledged write concern and verbose results");if(this.options.ordered)throw new i.MongoInvalidArgumentError("Cannot request unacknowledged write concern and ordered writes")}}async execute(){const e=this.client.s.options.pkFactory,t=new d.ClientBulkWriteCommandBuilder(this.operations,this.options,e),r=(0,a.resolveTimeoutOptions)(this.client,this.options),c=s.TimeoutContext.create(r);if(0===this.options.writeConcern?.w){for(;t.hasNextBatch();){const e=new l.ClientBulkWriteOperation(t,this.options);await(0,u.executeOperation)(this.client,e,c)}return h.ClientBulkWriteResultsMerger.unacknowledged()}{const e=new h.ClientBulkWriteResultsMerger(this.options);for(;t.hasNextBatch();){const s=new n.CursorTimeoutContext(c,Symbol()),a={...this.options,timeoutContext:s,...null!=r.timeoutMS&&{timeoutMode:n.CursorTimeoutMode.LIFETIME}},u=new o.ClientBulkWriteCursor(this.client,t,a);try{await e.merge(u)}catch(t){if(t instanceof i.MongoServerError&&!(t instanceof i.MongoClientBulkWriteError)){const r=new i.MongoClientBulkWriteError({message:"Mongo client bulk write encountered an error during execution"});throw r.cause=t,r.partialResult=e.bulkWriteResult,r}throw t}}if(e.writeConcernErrors.length>0||e.writeErrors.size>0){const t=new i.MongoClientBulkWriteError({message:"Mongo client bulk write encountered errors during execution."});throw t.writeConcernErrors=e.writeConcernErrors,t.writeErrors=e.writeErrors,t.partialResult=e.bulkWriteResult,t}return e.bulkWriteResult}}}},48758:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Encrypter=void 0;const n=r(70136),o=r(91869),i=r(8500),s=r(17562),a=r(22220);t.Encrypter=class{constructor(e,t,r){if("object"!=typeof r.autoEncryption)throw new s.MongoInvalidArgumentError('Option "autoEncryption" must be specified');this.internalClient=null,this.bypassAutoEncryption=!!r.autoEncryption.bypassAutoEncryption,this.needsConnecting=!1,0===r.maxPoolSize&&null==r.autoEncryption.keyVaultClient?r.autoEncryption.keyVaultClient=e:null==r.autoEncryption.keyVaultClient&&(r.autoEncryption.keyVaultClient=this.getInternalClient(e,t,r)),this.bypassAutoEncryption?r.autoEncryption.metadataClient=void 0:0===r.maxPoolSize?r.autoEncryption.metadataClient=e:r.autoEncryption.metadataClient=this.getInternalClient(e,t,r),r.proxyHost&&(r.autoEncryption.proxyOptions={proxyHost:r.proxyHost,proxyPort:r.proxyPort,proxyUsername:r.proxyUsername,proxyPassword:r.proxyPassword}),this.autoEncrypter=new n.AutoEncrypter(e,r.autoEncryption)}getInternalClient(e,t,r){let n=this.internalClient;if(null==n){const i={};for(const e of[...Object.getOwnPropertyNames(r),...Object.getOwnPropertySymbols(r)])["autoEncryption","minPoolSize","servers","caseTranslate","dbName"].includes(e)||Reflect.set(i,e,Reflect.get(r,e));i.minPoolSize=0,n=new a.MongoClient(t,i),this.internalClient=n;for(const t of o.MONGO_CLIENT_EVENTS)for(const r of e.listeners(t))n.on(t,r);e.on("newListener",((e,t)=>{n?.on(e,t)})),this.needsConnecting=!0}return n}async connectInternalClient(){const e=this.internalClient;this.needsConnecting&&null!=e&&(this.needsConnecting=!1,await e.connect())}async close(e){let t;try{await this.autoEncrypter.close()}catch(e){t=e}const r=this.internalClient;if(null!=r&&e!==r)return await r.close();if(null!=t)throw t}static checkForMongoCrypt(){const e=(0,i.getMongoDBClientEncryption)();if("kModuleError"in e)throw new s.MongoMissingDependencyError("Auto-encryption requested, but the module is not installed. Please add `mongodb-client-encryption` as a dependency of your project",{cause:e.kModuleError,dependencyName:"mongodb-client-encryption"})}}},49683:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CallbackWorkflow=t.AUTOMATED_TIMEOUT_MS=t.HUMAN_TIMEOUT_MS=void 0;const n=r(37668),o=r(17562),i=r(145),s=r(63178);t.HUMAN_TIMEOUT_MS=3e5,t.AUTOMATED_TIMEOUT_MS=6e4;const a=["accessToken","expiresInSeconds","refreshToken"];t.CallbackWorkflow=class{constructor(e,t){this.cache=e,this.callback=this.withLock(t),this.lastExecutionTime=Date.now()-100}async speculativeAuth(e,t){if(this.cache.hasAccessToken){const r=this.cache.getAccessToken();e.accessToken=r;const n=(0,s.finishCommandDocument)(r);return n.db=t.source,{speculativeAuthenticate:n}}return{}}async reauthenticate(e,t){this.cache.hasAccessToken&&(e.accessToken===this.cache.getAccessToken()?(this.cache.removeAccessToken(),delete e.accessToken):e.accessToken=this.cache.getAccessToken()),await this.execute(e,t)}async startAuthentication(e,t,r){let n;return n=r?.speculativeAuthenticate?r.speculativeAuthenticate:await e.command((0,i.ns)(t.source),(0,s.startCommandDocument)(t),void 0),n}async finishAuthentication(e,t,r,n){await e.command((0,i.ns)(t.source),(0,s.finishCommandDocument)(r,n),void 0)}async executeAndValidateCallback(e){const t=await this.callback(e);if(null==(r=t)||"object"!=typeof r||!("accessToken"in r)||!Object.getOwnPropertyNames(r).every((e=>a.includes(e))))throw new o.MongoMissingCredentialsError("User provided OIDC callbacks must return a valid object with an accessToken.");var r;return t}withLock(e){let t=Promise.resolve();return async r=>(await t,t=t.catch((()=>null)).then((async()=>{const t=Date.now()-this.lastExecutionTime;return t<=100&&await(0,n.setTimeout)(100-t,{signal:r.timeoutContext}),this.lastExecutionTime=Date.now(),await e(r)})),await t)}}},50373:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HumanCallbackWorkflow=void 0;const n=r(75080),o=r(17562),i=r(7799),s=r(63257),a=r(49683);class c extends a.CallbackWorkflow{constructor(e,t){super(e,t)}async execute(e,t){if(this.cache.hasAccessToken){const r=this.cache.getAccessToken();e.accessToken=r;try{return await this.finishAuthentication(e,t,r)}catch(r){if(r instanceof o.MongoError&&r.code===o.MONGODB_ERROR_CODES.AuthenticationFailed)return this.cache.removeAccessToken(),delete e.accessToken,await this.execute(e,t);throw r}}if(this.cache.hasRefreshToken){const r=this.cache.getRefreshToken(),n=await this.fetchAccessToken(this.cache.getIdpInfo(),t,r);this.cache.put(n),e.accessToken=n.accessToken;try{return await this.finishAuthentication(e,t,n.accessToken)}catch(r){if(r instanceof o.MongoError&&r.code===o.MONGODB_ERROR_CODES.AuthenticationFailed)return this.cache.removeRefreshToken(),delete e.accessToken,await this.execute(e,t);throw r}}const r=await this.startAuthentication(e,t),i=r.conversationId,s=n.BSON.deserialize(r.payload.buffer),a=await this.fetchAccessToken(s,t);return this.cache.put(a,s),e.accessToken=a.accessToken,await this.finishAuthentication(e,t,a.accessToken,i)}async fetchAccessToken(e,t,r){const n=new AbortController,c={timeoutContext:n.signal,version:s.OIDC_VERSION,idpInfo:e};t.username&&(c.username=t.username),r&&(c.refreshToken=r);const u=i.Timeout.expires(a.HUMAN_TIMEOUT_MS);try{return await Promise.race([this.executeAndValidateCallback(c),u])}catch(e){if(i.TimeoutError.is(e))throw n.abort(),new o.MongoOIDCError(`OIDC callback timed out after ${a.HUMAN_TIMEOUT_MS}ms.`);throw e}finally{u.clear()}}}t.HumanCallbackWorkflow=c},50440:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.FindOperation=void 0;const n=r(75725),o=r(17562),i=r(30770),s=r(145),a=r(78130),c=r(35394);class u extends a.CommandOperation{constructor(e,t={},r={}){if(super(void 0,r),this.SERVER_COMMAND_RESPONSE_TYPE=n.CursorResponse,this.options={...r},delete this.options.writeConcern,this.ns=e,"object"!=typeof t||Array.isArray(t))throw new o.MongoInvalidArgumentError("Query filter must be a plain object or ObjectId");this.filter=null!=t&&"ObjectId"===t._bsontype?{_id:t}:t,this.SERVER_COMMAND_RESPONSE_TYPE=this.explain?n.ExplainedCursorResponse:n.CursorResponse}get commandName(){return"find"}buildOptions(e){return{...this.options,...this.bsonOptions,documentsReturnedIn:"firstBatch",session:this.session,timeoutContext:e}}handleOk(e){return e}buildCommandDocument(){return function(e,t,r){const n={find:e.collection,filter:t};if(r.sort&&(n.sort=(0,i.formatSort)(r.sort)),r.projection){let e=r.projection;e&&Array.isArray(e)&&(e=e.length?e.reduce(((e,t)=>(e[t]=1,e)),{}):{_id:1}),n.projection=e}return r.hint&&(n.hint=(0,s.normalizeHintField)(r.hint)),"number"==typeof r.skip&&(n.skip=r.skip),"number"==typeof r.limit&&(r.limit<0?(n.limit=-r.limit,n.singleBatch=!0):n.limit=r.limit),"number"==typeof r.batchSize&&(r.batchSize<0?n.limit=-r.batchSize:r.batchSize===r.limit?n.batchSize=r.batchSize+1:n.batchSize=r.batchSize),"boolean"==typeof r.singleBatch&&(n.singleBatch=r.singleBatch),void 0!==r.comment&&(n.comment=r.comment),r.max&&(n.max=r.max),r.min&&(n.min=r.min),"boolean"==typeof r.returnKey&&(n.returnKey=r.returnKey),"boolean"==typeof r.showRecordId&&(n.showRecordId=r.showRecordId),"boolean"==typeof r.tailable&&(n.tailable=r.tailable),"boolean"==typeof r.oplogReplay&&(n.oplogReplay=r.oplogReplay),"boolean"==typeof r.timeout?n.noCursorTimeout=!r.timeout:"boolean"==typeof r.noCursorTimeout&&(n.noCursorTimeout=r.noCursorTimeout),"boolean"==typeof r.awaitData&&(n.awaitData=r.awaitData),"boolean"==typeof r.allowPartialResults&&(n.allowPartialResults=r.allowPartialResults),"boolean"==typeof r.allowDiskUse&&(n.allowDiskUse=r.allowDiskUse),r.let&&(n.let=r.let),n}(this.ns,this.filter,this.options)}}t.FindOperation=u,(0,c.defineAspects)(u,[c.Aspect.READ_OPERATION,c.Aspect.RETRYABLE,c.Aspect.EXPLAINABLE,c.Aspect.CURSOR_CREATING])},51825:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isEmptyCredentials=s,t.refreshKMSCredentials=async function(e,t){let r=e;return s("aws",e)&&(r=await(0,n.loadAWSCredentials)(r,t?.aws)),s("gcp",e)&&(r=await(0,i.loadGCPCredentials)(r)),s("azure",e)&&(r=await(0,o.loadAzureCredentials)(r)),r};const n=r(59888),o=r(79790),i=r(34563);function s(e,t){const r=t[e];return null!=r&&"object"==typeof r&&0===Object.keys(r).length}},54564:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BulkOperationBase=t.FindOperators=t.MongoBulkWriteError=t.WriteError=t.WriteConcernError=t.BulkWriteResult=t.Batch=t.BatchType=void 0,t.mergeBatchResults=f;const n=r(75080),o=r(17562),i=r(4752),s=r(96357),a=r(9326),c=r(94330),u=r(7799),l=r(145),d=r(40012);t.BatchType=Object.freeze({INSERT:1,UPDATE:2,DELETE:3}),t.Batch=class{constructor(e,t){this.originalZeroIndex=t,this.currentIndex=0,this.originalIndexes=[],this.batchType=e,this.operations=[],this.size=0,this.sizeBytes=0}};class h{static generateIdMap(e){const t={};for(const r of e)t[r.index]=r._id;return t}constructor(e,t){this.result=e,this.insertedCount=this.result.nInserted??0,this.matchedCount=this.result.nMatched??0,this.modifiedCount=this.result.nModified??0,this.deletedCount=this.result.nRemoved??0,this.upsertedCount=this.result.upserted.length??0,this.upsertedIds=h.generateIdMap(this.result.upserted),this.insertedIds=h.generateIdMap(this.getSuccessfullyInsertedIds(e,t)),Object.defineProperty(this,"result",{value:this.result,enumerable:!1})}get ok(){return this.result.ok}getSuccessfullyInsertedIds(e,t){return 0===e.writeErrors.length?e.insertedIds:t?e.insertedIds.slice(0,e.writeErrors[0].index):e.insertedIds.filter((({index:t})=>!e.writeErrors.some((e=>t===e.index))))}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]:void 0}getWriteErrors(){return this.result.writeErrors}getWriteConcernError(){if(0!==this.result.writeConcernErrors.length){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 p({errmsg:e,code:o.MONGODB_ERROR_CODES.WriteConcernTimeout})}}}toString(){return`BulkWriteResult(${n.EJSON.stringify(this.result)})`}isOk(){return 1===this.result.ok}}t.BulkWriteResult=h;class p{constructor(e){this.serverError=e}get code(){return this.serverError.code}get errmsg(){return this.serverError.errmsg}get errInfo(){return this.serverError.errInfo}toJSON(){return this.serverError}toString(){return`WriteConcernError(${this.errmsg})`}}t.WriteConcernError=p;class m{constructor(e){this.err=e}get code(){return this.err.code}get index(){return this.err.index}get errmsg(){return this.err.errmsg}get errInfo(){return this.err.errInfo}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 f(e,t,r,n){if(r?n=r:n&&n.result&&(n=n.result),null==n)return;if(0===n.ok&&1===t.ok){t.ok=0;const r={index:0,code:n.code||0,errmsg:n.message,errInfo:n.errInfo,op:e.operations[0]};return void t.writeErrors.push(new m(r))}if(0===n.ok&&0===t.ok)return;O(e)&&n.n&&(t.nInserted=t.nInserted+n.n),C(e)&&n.n&&(t.nRemoved=t.nRemoved+n.n);let o=0;if(Array.isArray(n.upserted)){o=n.upserted.length;for(let r=0;r<n.upserted.length;r++)t.upserted.push({index:n.upserted[r].index+e.originalZeroIndex,_id:n.upserted[r]._id})}else n.upserted&&(o=1,t.upserted.push({index:e.originalZeroIndex,_id:n.upserted}));if(y(e)&&n.n){const e=n.nModified;t.nUpserted=t.nUpserted+o,t.nMatched=t.nMatched+(n.n-o),t.nModified="number"==typeof e?t.nModified+e:0}if(Array.isArray(n.writeErrors))for(let r=0;r<n.writeErrors.length;r++){const o={index:e.originalIndexes[n.writeErrors[r].index],code:n.writeErrors[r].code,errmsg:n.writeErrors[r].errmsg,errInfo:n.writeErrors[r].errInfo,op:e.operations[n.writeErrors[r].index]};t.writeErrors.push(new m(o))}n.writeConcernError&&t.writeConcernErrors.push(new p(n.writeConcernError))}async function g(e,t){if(0===e.s.batches.length)return new h(e.s.bulkResult,e.isOrdered);for(const r of e.s.batches){const n=(0,l.resolveOptions)(e,{...t,ordered:e.isOrdered});!0!==n.bypassDocumentValidation&&delete n.bypassDocumentValidation,!0===e.s.bypassDocumentValidation&&(n.bypassDocumentValidation=!0),!1===e.s.checkKeys&&(n.checkKeys=!1),n.retryWrites&&(y(r)&&(n.retryWrites=n.retryWrites&&!r.operations.some((e=>e.multi))),C(r)&&(n.retryWrites=n.retryWrites&&!r.operations.some((e=>0===e.limit))));const u=O(r)?new a.InsertOperation(e.s.namespace,r.operations,n):y(r)?new c.UpdateOperation(e.s.namespace,r.operations,n):C(r)?new i.DeleteOperation(e.s.namespace,r.operations,n):null;if(null==u)throw new o.MongoRuntimeError(`Unknown batchType: ${r.batchType}`);let d,p=null;try{d=await(0,s.executeOperation)(e.s.collection.client,u,n.timeoutContext)}catch(e){p=e}if(null!=p){if(p instanceof o.MongoWriteConcernError){f(r,e.s.bulkResult,p,d);const t=new h(e.s.bulkResult,e.isOrdered);throw new E({message:p.result.writeConcernError.errmsg,code:p.result.writeConcernError.code},t)}throw new E(p,new h(e.s.bulkResult,e.isOrdered))}f(r,e.s.bulkResult,p,d);const m=new h(e.s.bulkResult,e.isOrdered);e.handleWriteError(m)}e.s.batches.length=0;const r=new h(e.s.bulkResult,e.isOrdered);return e.handleWriteError(r),r}t.WriteError=m;class E extends o.MongoServerError{constructor(e,t){super(e),this.writeErrors=[],e instanceof p?this.err=e:e instanceof Error||(this.message=e.message,this.code=e.code,this.writeErrors=e.writeErrors??[]),this.result=t,Object.assign(this,e)}get name(){return"MongoBulkWriteError"}get insertedCount(){return this.result.insertedCount}get matchedCount(){return this.result.matchedCount}get modifiedCount(){return this.result.modifiedCount}get deletedCount(){return this.result.deletedCount}get upsertedCount(){return this.result.upsertedCount}get insertedIds(){return this.result.insertedIds}get upsertedIds(){return this.result.upsertedIds}}t.MongoBulkWriteError=E;class S{constructor(e){this.bulkOperation=e}update(e){const r=M(this.bulkOperation);return this.bulkOperation.addToOperationsList(t.BatchType.UPDATE,(0,c.makeUpdateStatement)(r.selector,e,{...r,multi:!0}))}updateOne(e){if(!(0,l.hasAtomicOperators)(e,this.bulkOperation.bsonOptions))throw new o.MongoInvalidArgumentError("Update document requires atomic operators");const r=M(this.bulkOperation);return this.bulkOperation.addToOperationsList(t.BatchType.UPDATE,(0,c.makeUpdateStatement)(r.selector,e,{...r,multi:!1}))}replaceOne(e){if((0,l.hasAtomicOperators)(e))throw new o.MongoInvalidArgumentError("Replacement document must not use atomic operators");const r=M(this.bulkOperation);return this.bulkOperation.addToOperationsList(t.BatchType.UPDATE,(0,c.makeUpdateStatement)(r.selector,e,{...r,multi:!1}))}deleteOne(){const e=M(this.bulkOperation);return this.bulkOperation.addToOperationsList(t.BatchType.DELETE,(0,i.makeDeleteStatement)(e.selector,{...e,limit:1}))}delete(){const e=M(this.bulkOperation);return this.bulkOperation.addToOperationsList(t.BatchType.DELETE,(0,i.makeDeleteStatement)(e.selector,{...e,limit:0}))}upsert(){return this.bulkOperation.s.currentOp||(this.bulkOperation.s.currentOp={}),this.bulkOperation.s.currentOp.upsert=!0,this}collation(e){return this.bulkOperation.s.currentOp||(this.bulkOperation.s.currentOp={}),this.bulkOperation.s.currentOp.collation=e,this}arrayFilters(e){return this.bulkOperation.s.currentOp||(this.bulkOperation.s.currentOp={}),this.bulkOperation.s.currentOp.arrayFilters=e,this}hint(e){return this.bulkOperation.s.currentOp||(this.bulkOperation.s.currentOp={}),this.bulkOperation.s.currentOp.hint=e,this}}function O(e){return e.batchType===t.BatchType.INSERT}function y(e){return e.batchType===t.BatchType.UPDATE}function C(e){return e.batchType===t.BatchType.DELETE}function M(e){let{currentOp:t}=e.s;return e.s.currentOp=void 0,t||(t={}),t}t.FindOperators=S,t.BulkOperationBase=class{constructor(e,t,r){this.collection=e,this.isOrdered=r;const o=(0,l.getTopology)(e);t=null==t?{}:t;const i=e.s.namespace,s=o.lastHello(),a=!(!o.s.options||!o.s.options.autoEncrypter),c=s&&s.maxBsonObjectSize?s.maxBsonObjectSize:16777216,u=a?2097152:c,h=s&&s.maxWriteBatchSize?s.maxWriteBatchSize:1e3,p=(h-1).toString(10).length+2;let m=Object.assign({},t);m=(0,l.applyRetryableWrites)(m,e.s.db),this.s={bulkResult:{ok:1,writeErrors:[],writeConcernErrors:[],insertedIds:[],nInserted:0,nUpserted:0,nMatched:0,nModified:0,nRemoved:0,upserted:[]},currentBatch:void 0,currentIndex:0,currentBatchSize:0,currentBatchSizeBytes:0,currentInsertBatch:void 0,currentUpdateBatch:void 0,currentRemoveBatch:void 0,batches:[],writeConcern:d.WriteConcern.fromOptions(t),maxBsonObjectSize:c,maxBatchSizeBytes:u,maxWriteBatchSize:h,maxKeySize:p,namespace:i,topology:o,options:m,bsonOptions:(0,n.resolveBSONOptions)(t),currentOp:void 0,executed:!1,collection:e,err:void 0,checkKeys:"boolean"==typeof t.checkKeys&&t.checkKeys},!0===t.bypassDocumentValidation&&(this.s.bypassDocumentValidation=!0)}insert(e){return(0,l.maybeAddIdToDocuments)(this.collection,e,{forceServerObjectId:this.shouldForceServerObjectId()}),this.addToOperationsList(t.BatchType.INSERT,e)}find(e){if(!e)throw new o.MongoInvalidArgumentError("Bulk find operation must specify a selector");return this.s.currentOp={selector:e},new S(this)}raw(e){if(null==e||"object"!=typeof e)throw new o.MongoInvalidArgumentError("Operation must be an object with an operation key");if("insertOne"in e){const r=this.shouldForceServerObjectId(),n=e.insertOne&&null==e.insertOne.document?e.insertOne:e.insertOne.document;return(0,l.maybeAddIdToDocuments)(this.collection,n,{forceServerObjectId:r}),this.addToOperationsList(t.BatchType.INSERT,n)}if("replaceOne"in e||"updateOne"in e||"updateMany"in e){if("replaceOne"in e){if("q"in e.replaceOne)throw new o.MongoInvalidArgumentError("Raw operations are not allowed");const r=(0,c.makeUpdateStatement)(e.replaceOne.filter,e.replaceOne.replacement,{...e.replaceOne,multi:!1});if((0,l.hasAtomicOperators)(r.u))throw new o.MongoInvalidArgumentError("Replacement document must not use atomic operators");return this.addToOperationsList(t.BatchType.UPDATE,r)}if("updateOne"in e){if("q"in e.updateOne)throw new o.MongoInvalidArgumentError("Raw operations are not allowed");const r=(0,c.makeUpdateStatement)(e.updateOne.filter,e.updateOne.update,{...e.updateOne,multi:!1});if(!(0,l.hasAtomicOperators)(r.u,this.bsonOptions))throw new o.MongoInvalidArgumentError("Update document requires atomic operators");return this.addToOperationsList(t.BatchType.UPDATE,r)}if("updateMany"in e){if("q"in e.updateMany)throw new o.MongoInvalidArgumentError("Raw operations are not allowed");const r=(0,c.makeUpdateStatement)(e.updateMany.filter,e.updateMany.update,{...e.updateMany,multi:!0});if(!(0,l.hasAtomicOperators)(r.u,this.bsonOptions))throw new o.MongoInvalidArgumentError("Update document requires atomic operators");return this.addToOperationsList(t.BatchType.UPDATE,r)}}if("deleteOne"in e){if("q"in e.deleteOne)throw new o.MongoInvalidArgumentError("Raw operations are not allowed");return this.addToOperationsList(t.BatchType.DELETE,(0,i.makeDeleteStatement)(e.deleteOne.filter,{...e.deleteOne,limit:1}))}if("deleteMany"in e){if("q"in e.deleteMany)throw new o.MongoInvalidArgumentError("Raw operations are not allowed");return this.addToOperationsList(t.BatchType.DELETE,(0,i.makeDeleteStatement)(e.deleteMany.filter,{...e.deleteMany,limit:0}))}throw new o.MongoInvalidArgumentError("bulkWrite only supports insertOne, updateOne, updateMany, deleteOne, deleteMany")}get length(){return this.s.currentIndex}get bsonOptions(){return this.s.bsonOptions}get writeConcern(){return this.s.writeConcern}get batches(){const e=[...this.s.batches];return this.isOrdered?this.s.currentBatch&&e.push(this.s.currentBatch):(this.s.currentInsertBatch&&e.push(this.s.currentInsertBatch),this.s.currentUpdateBatch&&e.push(this.s.currentUpdateBatch),this.s.currentRemoveBatch&&e.push(this.s.currentRemoveBatch)),e}async execute(e={}){if(this.s.executed)throw new o.MongoBatchReExecutionError;const t=d.WriteConcern.fromOptions(e);if(t&&(this.s.writeConcern=t),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)throw new o.MongoInvalidArgumentError("Invalid BulkOperation, Batch cannot be empty");this.s.executed=!0;const r=(0,l.resolveOptions)(this.collection,{...this.s.options,...e});return r.timeoutContext??=u.TimeoutContext.create({session:r.session,timeoutMS:r.timeoutMS,serverSelectionTimeoutMS:this.collection.client.s.options.serverSelectionTimeoutMS,waitQueueTimeoutMS:this.collection.client.s.options.waitQueueTimeoutMS}),null==r.session?await this.collection.client.withSession({explicit:!1},(async e=>await g(this,{...r,session:e}))):await g(this,{...r})}handleWriteError(e){if(this.s.bulkResult.writeErrors.length>0){const t=this.s.bulkResult.writeErrors[0].errmsg?this.s.bulkResult.writeErrors[0].errmsg:"write operation failed";throw new E({message:t,code:this.s.bulkResult.writeErrors[0].code,writeErrors:this.s.bulkResult.writeErrors},e)}const t=e.getWriteConcernError();if(t)throw new E(t,e)}shouldForceServerObjectId(){return!0===this.s.options.forceServerObjectId||!0===this.s.collection.s.db.options?.forceServerObjectId}}},55546:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ListCollectionsCursor=void 0;const n=r(96357),o=r(88913),i=r(61066);class s extends i.AbstractCursor{constructor(e,t,r){super(e.client,e.s.namespace,r),this.parent=e,this.filter=t,this.options=r}clone(){return new s(this.parent,this.filter,{...this.options,...this.cursorOptions})}async _initialize(e){const t=new o.ListCollectionsOperation(this.parent,this.filter,{...this.cursorOptions,...this.options,session:e,signal:this.signal}),r=await(0,n.executeOperation)(this.parent.client,t,this.timeoutContext);return{server:t.server,session:e,response:r}}}t.ListCollectionsCursor=s},55741:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ConnectionPoolMetrics=void 0;class r{constructor(){this.txnConnections=0,this.cursorConnections=0,this.otherConnections=0}markPinned(e){e===r.TXN?this.txnConnections+=1:e===r.CURSOR?this.cursorConnections+=1:this.otherConnections+=1}markUnpinned(e){e===r.TXN?this.txnConnections-=1:e===r.CURSOR?this.cursorConnections-=1:this.otherConnections-=1}info(e){return`Timed out while checking out a connection from connection pool: maxPoolSize: ${e}, connections in use by cursors: ${this.cursorConnections}, connections in use by transactions: ${this.txnConnections}, connections in use by other operations: ${this.otherConnections}`}reset(){this.txnConnections=0,this.cursorConnections=0,this.otherConnections=0}}t.ConnectionPoolMetrics=r,r.TXN="txn",r.CURSOR="cursor",r.OTHER="other"},56463:(e,t,r)=>{var n=r(67787).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.LimitedSizeDocument=void 0,t.makeClientMetadata=function(e){const t=new l(512),{appName:r=""}=e;if(r.length>0){const o=n.byteLength(r,"utf8")<=128?e.appName:n.from(r,"utf8").subarray(0,128).toString("utf8");t.ifItFitsItSits("application",{name:o})}const{name:s="",version:c="",platform:d=""}=e.driverInfo,p={name:s.length>0?`nodejs|${s}`:"nodejs",version:c.length>0?`${u}|${c}`:u};if(null==e.additionalDriverInfo)throw new a.MongoRuntimeError("Client options `additionalDriverInfo` must always default to an empty array");for(const{name:t="",version:r=""}of e.additionalDriverInfo)t.length>0&&(p.name=`${p.name}|${t}`),r.length>0&&(p.version=`${p.version}|${r}`);if(!t.ifItFitsItSits("driver",p))throw new a.MongoInvalidArgumentError("Unable to include driverInfo name and version, metadata cannot exceed 512 bytes");let m="Deno"in globalThis?`Deno v${"string"==typeof Deno?.version?.deno?Deno?.version?.deno:"0.0.0-unknown"}, ${o.endianness()}`:"Bun"in globalThis?`Bun v${"string"==typeof Bun?.version?Bun?.version:"0.0.0-unknown"}, ${o.endianness()}`:`Node.js ${i.version}, ${o.endianness()}`;d.length>0&&(m=`${m}|${d}`);for(const{platform:t=""}of e.additionalDriverInfo)t.length>0&&(m=`${m}|${t}`);if(!t.ifItFitsItSits("platform",m))throw new a.MongoInvalidArgumentError("Unable to include driverInfo platform, metadata cannot exceed 512 bytes");const f=(new Map).set("name",i.platform).set("architecture",i.arch).set("version",o.release()).set("type",o.type());if(!t.ifItFitsItSits("os",f))for(const e of f.keys()){if(f.delete(e),0===f.size)break;if(t.ifItFitsItSits("os",f))break}const g=h();if(null!=g&&!t.ifItFitsItSits("env",g))for(const e of g.keys()){if(g.delete(e),0===g.size)break;if(t.ifItFitsItSits("env",g))break}return t.toObject()},t.addContainerMetadata=async function(e){const t=await async function(){const e={};d??=(0,c.fileIsAccessible)("/.dockerenv");const t=await d,{KUBERNETES_SERVICE_HOST:r=""}=i.env,n=r.length>0;return t&&(e.runtime="docker"),n&&(e.orchestrator="kubernetes"),e}();if(0===Object.keys(t).length)return e;const r=new l(512),n={...e?.env,container:t};for(const[t,o]of Object.entries(e))"env"!==t?r.ifItFitsItSits(t,o):r.ifItFitsItSits("env",n)||r.ifItFitsItSits("env",o);return"env"in e||r.ifItFitsItSits("env",n),r.toObject()},t.getFAASEnv=h;const o=r(35369),i=r(98999),s=r(75080),a=r(17562),c=r(145),u=r(46195).rE;class l{constructor(e){this.document=new Map,this.documentSize=5,this.maxSize=e}ifItFitsItSits(e,t){const r=s.BSON.serialize((new Map).set(e,t)).byteLength-5;return!(r+this.documentSize>this.maxSize||(this.documentSize+=r,this.document.set(e,t),0))}toObject(){return s.BSON.deserialize(s.BSON.serialize(this.document),{promoteLongs:!1,promoteBuffers:!1,promoteValues:!1,useBigInt64:!1})}}let d;function h(){const{AWS_EXECUTION_ENV:e="",AWS_LAMBDA_RUNTIME_API:t="",FUNCTIONS_WORKER_RUNTIME:r="",K_SERVICE:n="",FUNCTION_NAME:o="",VERCEL:a="",AWS_LAMBDA_FUNCTION_MEMORY_SIZE:c="",AWS_REGION:u="",FUNCTION_MEMORY_MB:l="",FUNCTION_REGION:d="",FUNCTION_TIMEOUT_SEC:h="",VERCEL_REGION:p=""}=i.env,m=e.startsWith("AWS_Lambda_")||t.length>0,f=r.length>0,g=n.length>0||o.length>0,E=a.length>0,S=new Map;return!E||f||g?m&&!(f||g||E)?(u.length>0&&S.set("region",u),c.length>0&&Number.isInteger(+c)&&S.set("memory_mb",new s.Int32(c)),S.set("name","aws.lambda"),S):f&&!(g||m||E)?(S.set("name","azure.func"),S):g&&!(f||m||E)?(d.length>0&&S.set("region",d),l.length>0&&Number.isInteger(+l)&&S.set("memory_mb",new s.Int32(l)),h.length>0&&Number.isInteger(+h)&&S.set("timeout_sec",new s.Int32(h)),S.set("name","gcp.func"),S):null:(p.length>0&&S.set("region",p),S.set("name","vercel"),S)}t.LimitedSizeDocument=l},57590:(e,t,r)=>{var n=r(65994).e;Object.defineProperty(t,"__esModule",{value:!0}),t.RTTSampler=t.MonitorInterval=t.RTTPinger=t.Monitor=t.ServerMonitoringMode=void 0;const o=r(37668),i=r(75080),s=r(87758),a=r(56463),c=r(91869),u=r(17562),l=r(93347),d=r(4642),h=r(145),p=r(89167),m=r(43135),f=r(5369),g="idle",E="monitoring",S=(0,h.makeStateMachine)({[p.STATE_CLOSING]:[p.STATE_CLOSING,g,p.STATE_CLOSED],[p.STATE_CLOSED]:[p.STATE_CLOSED,E],[g]:[g,E,p.STATE_CLOSING],[E]:[E,g,p.STATE_CLOSING]}),O=new Set([p.STATE_CLOSING,p.STATE_CLOSED,E]);function y(e){return e.s.state===p.STATE_CLOSED||e.s.state===p.STATE_CLOSING}t.ServerMonitoringMode=Object.freeze({auto:"auto",poll:"poll",stream:"stream"});class C extends d.TypedEventEmitter{constructor(e,t){super(),this.component=l.MongoLoggableComponent.TOPOLOGY,this.on("error",h.noop),this.server=e,this.connection=null,this.cancellationToken=new d.CancellationToken,this.cancellationToken.setMaxListeners(1/0),this.monitorId=void 0,this.s={state:p.STATE_CLOSED},this.address=e.description.address,this.options=Object.freeze({connectTimeoutMS:t.connectTimeoutMS??1e4,heartbeatFrequencyMS:t.heartbeatFrequencyMS??1e4,minHeartbeatFrequencyMS:t.minHeartbeatFrequencyMS??500,serverMonitoringMode:t.serverMonitoringMode}),this.isRunningInFaasEnv=null!=(0,a.getFAASEnv)(),this.mongoLogger=this.server.topology.client?.mongoLogger,this.rttSampler=new _(10);const r=this.cancellationToken,n={id:"<monitor>",generation:e.pool.generation,cancellationToken:r,hostAddress:e.description.hostAddress,...t,raw:!1,useBigInt64:!1,promoteLongs:!0,promoteValues:!0,promoteBuffers:!0};delete n.credentials,n.autoEncrypter&&delete n.autoEncrypter,this.connectOptions=Object.freeze(n)}connect(){if(this.s.state!==p.STATE_CLOSED)return;const e=this.options.heartbeatFrequencyMS,t=this.options.minHeartbeatFrequencyMS;this.monitorId=new b(w(this),{heartbeatFrequencyMS:e,minHeartbeatFrequencyMS:t,immediate:!0})}requestCheck(){O.has(this.s.state)||this.monitorId?.wake()}reset(){const e=this.server.description.topologyVersion;if(y(this)||null==e)return;S(this,p.STATE_CLOSING),M(this),S(this,g);const t=this.options.heartbeatFrequencyMS,r=this.options.minHeartbeatFrequencyMS;this.monitorId=new b(w(this),{heartbeatFrequencyMS:t,minHeartbeatFrequencyMS:r})}close(){y(this)||(S(this,p.STATE_CLOSING),M(this),this.emit("close"),S(this,p.STATE_CLOSED))}get roundTripTime(){return this.rttSampler.average()}get minRoundTripTime(){return this.rttSampler.min()}get latestRtt(){return this.rttSampler.last}addRttSample(e){this.rttSampler.addSample(e)}clearRttSamples(){this.rttSampler.clear()}}function M(e){e.monitorId?.stop(),e.monitorId=void 0,e.rttPinger?.close(),e.rttPinger=void 0,e.cancellationToken.emit("cancel"),e.connection?.destroy(),e.connection=null,e.clearRttSamples()}function T(e,r){if(null==r)return!1;const n=e.options.serverMonitoringMode;return n!==t.ServerMonitoringMode.poll&&(n===t.ServerMonitoringMode.stream||!e.isRunningInFaasEnv)}function w(e){return t=>{function r(){y(e)||S(e,g),t()}e.s.state!==E?(S(e,E),function(e,t){let r,n;const o=e.server.description.topologyVersion,a=T(e,o);function l(o){e.connection?.destroy(),e.connection=null,e.emitAndLogHeartbeat(f.Server.SERVER_HEARTBEAT_FAILED,e.server.topology.s.id,void 0,new m.ServerHeartbeatFailedEvent(e.address,(0,h.calculateDurationInMs)(r),o,n));const i=o instanceof u.MongoError?o:new u.MongoError(u.MongoError.buildErrorMessage(o),{cause:o});i.addErrorLabel(u.MongoErrorLabel.ResetPool),i instanceof u.MongoNetworkTimeoutError&&i.addErrorLabel(u.MongoErrorLabel.InterruptInUseConnections),e.emit("resetServer",i),t(o)}function d(n){"isWritablePrimary"in n||(n.isWritablePrimary=n[c.LEGACY_HELLO_COMMAND]);const o=a&&e.rttPinger?e.rttPinger.latestRtt??(0,h.calculateDurationInMs)(r):(0,h.calculateDurationInMs)(r);e.addRttSample(o),e.emitAndLogHeartbeat(f.Server.SERVER_HEARTBEAT_SUCCEEDED,e.server.topology.s.id,n.connectionId,new m.ServerHeartbeatSucceededEvent(e.address,o,n,a)),a?(e.emitAndLogHeartbeat(f.Server.SERVER_HEARTBEAT_STARTED,e.server.topology.s.id,void 0,new m.ServerHeartbeatStartedEvent(e.address,!0)),r=(0,h.now)()):(e.rttPinger?.close(),e.rttPinger=void 0,t(void 0,n))}e.emitAndLogHeartbeat(f.Server.SERVER_HEARTBEAT_STARTED,e.server.topology.s.id,void 0,new m.ServerHeartbeatStartedEvent(e.address,a));const{connection:p}=e;if(p&&!p.closed){const{serverApi:t,helloOk:s}=p,u=e.options.connectTimeoutMS,m=e.options.heartbeatFrequencyMS,f={[t?.version||s?"hello":c.LEGACY_HELLO_COMMAND]:1,...a&&o?{maxAwaitTimeMS:m,topologyVersion:(g=o,{processId:g.processId,counter:i.Long.isLong(g.counter)?g.counter:i.Long.fromNumber(g.counter)})}:{}},E=a?{socketTimeoutMS:u?u+m:0,exhaustAllowed:!0}:{socketTimeoutMS:u};return a&&null==e.rttPinger&&(e.rttPinger=new v(e)),r=(0,h.now)(),a?(n=!0,p.exhaustCommand((0,h.ns)("admin.$cmd"),f,E,((e,t)=>e?l(e):d(t)))):(n=!1,void p.command((0,h.ns)("admin.$cmd"),f,E).then(d,l))}var g;(async()=>{const t=await(0,s.makeSocket)(e.connectOptions),n=(0,s.makeConnection)(e.connectOptions,t);r=(0,h.now)();try{return await(0,s.performInitialHandshake)(n,e.connectOptions),n}catch(e){throw n.destroy(),e}})().then((n=>{if(y(e))return void n.destroy();const o=(0,h.calculateDurationInMs)(r);e.addRttSample(o),e.connection=n,e.emitAndLogHeartbeat(f.Server.SERVER_HEARTBEAT_SUCCEEDED,e.server.topology.s.id,n.hello?.connectionId,new m.ServerHeartbeatSucceededEvent(e.address,o,n.hello,T(e,n.hello?.topologyVersion))),t(void 0,n.hello)}),(t=>{e.connection=null,n=!1,l(t)}))}(e,((t,n)=>{if(t&&e.server.description.type===p.ServerType.Unknown)return r();T(e,n?.topologyVersion)&&(0,o.setTimeout)((()=>{y(e)||e.monitorId?.wake()}),0),r()}))):n.nextTick(t)}}t.Monitor=C;class v{constructor(e){this.connection=void 0,this.cancellationToken=e.cancellationToken,this.closed=!1,this.monitor=e,this.latestRtt=e.latestRtt??void 0;const t=e.options.heartbeatFrequencyMS;this.monitorId=(0,o.setTimeout)((()=>this.measureRoundTripTime()),t)}get roundTripTime(){return this.monitor.roundTripTime}get minRoundTripTime(){return this.monitor.minRoundTripTime}close(){this.closed=!0,(0,o.clearTimeout)(this.monitorId),this.connection?.destroy(),this.connection=void 0}measureAndReschedule(e,t){this.closed?t?.destroy():(null==this.connection&&(this.connection=t),this.latestRtt=(0,h.calculateDurationInMs)(e),this.monitorId=(0,o.setTimeout)((()=>this.measureRoundTripTime()),this.monitor.options.heartbeatFrequencyMS))}measureRoundTripTime(){const e=(0,h.now)();if(this.closed)return;const t=this.connection;if(null==t)return void(0,s.connect)(this.monitor.connectOptions).then((t=>{this.measureAndReschedule(e,t)}),(()=>{this.connection=void 0}));const r=t.serverApi?.version||t.helloOk?"hello":c.LEGACY_HELLO_COMMAND;t.command((0,h.ns)("admin.$cmd"),{[r]:1},void 0).then((()=>this.measureAndReschedule(e)),(()=>{this.connection?.destroy(),this.connection=void 0}))}}t.RTTPinger=v;class b{constructor(e,t={}){this.isExpeditedCallToFnScheduled=!1,this.stopped=!1,this.isExecutionInProgress=!1,this.hasExecutedOnce=!1,this._executeAndReschedule=()=>{this.stopped||(this.timerId&&(0,o.clearTimeout)(this.timerId),this.isExpeditedCallToFnScheduled=!1,this.isExecutionInProgress=!0,this.fn((()=>{this.lastExecutionEnded=(0,h.now)(),this.isExecutionInProgress=!1,this._reschedule(this.heartbeatFrequencyMS)})))},this.fn=e,this.lastExecutionEnded=-1/0,this.heartbeatFrequencyMS=t.heartbeatFrequencyMS??1e3,this.minHeartbeatFrequencyMS=t.minHeartbeatFrequencyMS??500,t.immediate?this._executeAndReschedule():this._reschedule(void 0)}wake(){const e=(0,h.now)()-this.lastExecutionEnded;return e<0?this._executeAndReschedule():this.isExecutionInProgress||this.isExpeditedCallToFnScheduled?void 0:e<this.minHeartbeatFrequencyMS?(this.isExpeditedCallToFnScheduled=!0,void this._reschedule(this.minHeartbeatFrequencyMS-e)):void this._executeAndReschedule()}stop(){this.stopped=!0,this.timerId&&((0,o.clearTimeout)(this.timerId),this.timerId=void 0),this.lastExecutionEnded=-1/0,this.isExpeditedCallToFnScheduled=!1}toString(){return JSON.stringify(this)}toJSON(){const e=(0,h.now)(),t=e-this.lastExecutionEnded;return{timerId:null!=this.timerId?"set":"cleared",lastCallTime:this.lastExecutionEnded,isExpeditedCheckScheduled:this.isExpeditedCallToFnScheduled,stopped:this.stopped,heartbeatFrequencyMS:this.heartbeatFrequencyMS,minHeartbeatFrequencyMS:this.minHeartbeatFrequencyMS,currentTime:e,timeSinceLastCall:t}}_reschedule(e){this.stopped||(this.timerId&&(0,o.clearTimeout)(this.timerId),this.timerId=(0,o.setTimeout)(this._executeAndReschedule,e||this.heartbeatFrequencyMS))}}t.MonitorInterval=b;class _{constructor(e=10){this.rttSamples=new Float64Array(e),this.length=0,this.writeIndex=0}addSample(e){this.rttSamples[this.writeIndex++]=e,this.length<this.rttSamples.length&&this.length++,this.writeIndex%=this.rttSamples.length}min(){if(this.length<2)return 0;let e=this.rttSamples[0];for(let t=1;t<this.length;t++)this.rttSamples[t]<e&&(e=this.rttSamples[t]);return e}average(){if(0===this.length)return 0;let e=0;for(let t=0;t<this.length;t++)e+=this.rttSamples[t];return e/this.length}get last(){return 0===this.length?null:this.rttSamples[0===this.writeIndex?this.length-1:this.writeIndex-1]}clear(){this.length=0,this.writeIndex=0}}t.RTTSampler=_},58127:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SetProfilingLevelOperation=t.ProfilingLevel=void 0;const n=r(75725),o=r(17562),i=r(145),s=r(78130),a=new Set(["off","slow_only","all"]);t.ProfilingLevel=Object.freeze({off:"off",slowOnly:"slow_only",all:"all"});class c extends s.CommandOperation{constructor(e,r,o){switch(super(e,o),this.SERVER_COMMAND_RESPONSE_TYPE=n.MongoDBResponse,this.options=o,r){case t.ProfilingLevel.off:this.profile=0;break;case t.ProfilingLevel.slowOnly:this.profile=1;break;case t.ProfilingLevel.all:this.profile=2;break;default:this.profile=0}this.level=r}get commandName(){return"profile"}buildCommandDocument(e){const r=this.level;if(!a.has(r))throw new o.MongoInvalidArgumentError(`Profiling level must be one of "${(0,i.enumToString)(t.ProfilingLevel)}"`);return{profile:this.profile}}handleOk(e){return this.level}}t.SetProfilingLevelOperation=c},58782:(e,t,r)=>{var n=r(44775),o=n.define("Time",(function(){this.choice({utcTime:this.utctime(),generalTime:this.gentime()})})),i=n.define("AttributeTypeValue",(function(){this.seq().obj(this.key("type").objid(),this.key("value").any())})),s=n.define("AlgorithmIdentifier",(function(){this.seq().obj(this.key("algorithm").objid(),this.key("parameters").optional(),this.key("curve").objid().optional())})),a=n.define("SubjectPublicKeyInfo",(function(){this.seq().obj(this.key("algorithm").use(s),this.key("subjectPublicKey").bitstr())})),c=n.define("RelativeDistinguishedName",(function(){this.setof(i)})),u=n.define("RDNSequence",(function(){this.seqof(c)})),l=n.define("Name",(function(){this.choice({rdnSequence:this.use(u)})})),d=n.define("Validity",(function(){this.seq().obj(this.key("notBefore").use(o),this.key("notAfter").use(o))})),h=n.define("Extension",(function(){this.seq().obj(this.key("extnID").objid(),this.key("critical").bool().def(!1),this.key("extnValue").octstr())})),p=n.define("TBSCertificate",(function(){this.seq().obj(this.key("version").explicit(0).int().optional(),this.key("serialNumber").int(),this.key("signature").use(s),this.key("issuer").use(l),this.key("validity").use(d),this.key("subject").use(l),this.key("subjectPublicKeyInfo").use(a),this.key("issuerUniqueID").implicit(1).bitstr().optional(),this.key("subjectUniqueID").implicit(2).bitstr().optional(),this.key("extensions").explicit(3).seqof(h).optional())})),m=n.define("X509Certificate",(function(){this.seq().obj(this.key("tbsCertificate").use(p),this.key("signatureAlgorithm").use(s),this.key("signatureValue").bitstr())}));e.exports=m},59888:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.loadAWSCredentials=async function(e,t){const r=new n.AWSSDKCredentialProvider(t),{SecretAccessKey:o="",AccessKeyId:i="",Token:s}=await r.getCredentials(),a={secretAccessKey:o,accessKeyId:i};return null!=s&&(a.sessionToken=s),{...e,aws:a}};const n=r(19043)},61066:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CursorTimeoutContext=t.AbstractCursor=t.CursorTimeoutMode=t.CURSOR_FLAGS=void 0;const n=r(93874),o=r(75080),i=r(17562),s=r(4642),a=r(96357),c=r(68923),u=r(1755),l=r(28541),d=r(13700),h=r(31790),p=r(14019),m=r(7799),f=r(145);function g(){this.client.s.activeCursors.delete(this)}t.CURSOR_FLAGS=["tailable","oplogReplay","noCursorTimeout","awaitData","exhaust","partial"],t.CursorTimeoutMode=Object.freeze({ITERATION:"iteration",LIFETIME:"cursorLifetime"});class E extends s.TypedEventEmitter{constructor(e,r,n={}){if(super(),this.documents=null,this.hasEmittedClose=!1,this.on("error",f.noop),!e.s.isMongoClient)throw new i.MongoRuntimeError("Cursor must be constructed with MongoClient");if(this.cursorClient=e,this.cursorNamespace=r,this.cursorId=null,this.initialized=!1,this.isClosed=!1,this.isKilled=!1,this.cursorOptions={readPreference:n.readPreference&&n.readPreference instanceof d.ReadPreference?n.readPreference:d.ReadPreference.primary,...(0,o.pluckBSONSerializeOptions)(n),timeoutMS:n?.timeoutContext?.csotEnabled()?n.timeoutContext.timeoutMS:n.timeoutMS,tailable:n.tailable,awaitData:n.awaitData},null!=this.cursorOptions.timeoutMS)if(null==n.timeoutMode)if(n.tailable){if(n.awaitData&&null!=n.maxAwaitTimeMS&&n.maxAwaitTimeMS>=this.cursorOptions.timeoutMS)throw new i.MongoInvalidArgumentError("Cannot specify maxAwaitTimeMS >= timeoutMS for a tailable awaitData cursor");this.cursorOptions.timeoutMode=t.CursorTimeoutMode.ITERATION}else this.cursorOptions.timeoutMode=t.CursorTimeoutMode.LIFETIME;else{if(n.tailable&&n.timeoutMode===t.CursorTimeoutMode.LIFETIME)throw new i.MongoInvalidArgumentError("Cannot set tailable cursor's timeoutMode to LIFETIME");this.cursorOptions.timeoutMode=n.timeoutMode}else if(null!=n.timeoutMode)throw new i.MongoInvalidArgumentError("Cannot set timeoutMode without setting timeoutMS");this.cursorOptions.omitMaxTimeMS=null!=this.cursorOptions.timeoutMS&&(this.cursorOptions.timeoutMode===t.CursorTimeoutMode.ITERATION&&!this.cursorOptions.tailable||this.cursorOptions.tailable&&!this.cursorOptions.awaitData);const s=l.ReadConcern.fromOptions(n);s&&(this.cursorOptions.readConcern=s),"number"==typeof n.batchSize&&(this.cursorOptions.batchSize=n.batchSize),void 0!==n.comment&&(this.cursorOptions.comment=n.comment),"number"==typeof n.maxTimeMS&&(this.cursorOptions.maxTimeMS=n.maxTimeMS),"number"==typeof n.maxAwaitTimeMS&&(this.cursorOptions.maxAwaitTimeMS=n.maxAwaitTimeMS),this.cursorSession=n.session??null,this.deserializationOptions={...this.cursorOptions,validation:{utf8:!1!==n?.enableUtf8Validation}},this.timeoutContext=n.timeoutContext,this.signal=n.signal,this.abortListener=(0,f.addAbortListener)(this.signal,(()=>{this.close().then(void 0,f.squashError)})),this.trackCursor()}get id(){return this.cursorId??void 0}get isDead(){return(this.cursorId?.isZero()??!1)||this.isClosed||this.isKilled}get client(){return this.cursorClient}get server(){return this.selectedServer}get namespace(){return this.cursorNamespace}get readPreference(){return this.cursorOptions.readPreference}get readConcern(){return this.cursorOptions.readConcern}get session(){return this.cursorSession}set session(e){this.cursorSession=e}get closed(){return this.isClosed&&0===(this.documents?.length??0)}get killed(){return this.isKilled}get loadBalanced(){return!!this.cursorClient.topology?.loadBalanced}async asyncDispose(){await this.close()}trackCursor(){this.cursorClient.s.activeCursors.add(this),this.listeners("close").includes(g)||this.once("close",g)}bufferedCount(){return this.documents?.length??0}readBufferedDocuments(e){const t=[],r=Math.min(e??this.documents?.length??0,this.documents?.length??0);for(let e=0;e<r;e++){const e=this.documents?.shift(this.deserializationOptions);null!=e&&t.push(e)}return t}async*[Symbol.asyncIterator](){if(this.signal?.throwIfAborted(),!this.closed)try{for(;;){if(this.isKilled)return;if(this.closed)return;if(null!=this.cursorId&&this.isDead&&0===(this.documents?.length??0))return;const e=await this.next();if(null===e)return;yield e,this.signal?.throwIfAborted()}}finally{if(!this.isClosed)try{await this.close()}catch(e){(0,f.squashError)(e)}}}stream(e){const t=new S(this),r=(0,f.addAbortListener)(this.signal,(function(){t.destroy(this.reason)}));if(t.once("end",(()=>{r?.[f.kDispose]()})),e?.transform){const r=e.transform,o=t.pipe(new n.Transform({objectMode:!0,highWaterMark:1,transform(e,t,n){try{n(void 0,r(e))}catch(e){n(e)}}}));return t.on("error",(e=>o.emit("error",e))),o}return t}async hasNext(){if(this.signal?.throwIfAborted(),this.cursorId===o.Long.ZERO)return!1;this.cursorOptions.timeoutMode===t.CursorTimeoutMode.ITERATION&&null!=this.cursorId&&this.timeoutContext?.refresh();try{do{if(0!==(this.documents?.length??0))return!0;await this.fetchBatch()}while(!this.isDead||0!==(this.documents?.length??0))}finally{this.cursorOptions.timeoutMode===t.CursorTimeoutMode.ITERATION&&this.timeoutContext?.clear()}return!1}async next(){if(this.signal?.throwIfAborted(),this.cursorId===o.Long.ZERO)throw new i.MongoCursorExhaustedError;this.cursorOptions.timeoutMode===t.CursorTimeoutMode.ITERATION&&null!=this.cursorId&&this.timeoutContext?.refresh();try{do{const e=this.documents?.shift(this.deserializationOptions);if(null!=e)return null!=this.transform?await this.transformDocument(e):e;await this.fetchBatch()}while(!this.isDead||0!==(this.documents?.length??0))}finally{this.cursorOptions.timeoutMode===t.CursorTimeoutMode.ITERATION&&this.timeoutContext?.clear()}return null}async tryNext(){if(this.signal?.throwIfAborted(),this.cursorId===o.Long.ZERO)throw new i.MongoCursorExhaustedError;this.cursorOptions.timeoutMode===t.CursorTimeoutMode.ITERATION&&null!=this.cursorId&&this.timeoutContext?.refresh();try{let e=this.documents?.shift(this.deserializationOptions);if(null!=e)return null!=this.transform?await this.transformDocument(e):e;if(await this.fetchBatch(),e=this.documents?.shift(this.deserializationOptions),null!=e)return null!=this.transform?await this.transformDocument(e):e}finally{this.cursorOptions.timeoutMode===t.CursorTimeoutMode.ITERATION&&this.timeoutContext?.clear()}return null}async forEach(e){if(this.signal?.throwIfAborted(),"function"!=typeof e)throw new i.MongoInvalidArgumentError('Argument "iterator" must be a function');for await(const t of this)if(!1===e(t))break}async close(e){await this.cleanup(e?.timeoutMS)}async toArray(){this.signal?.throwIfAborted();const e=[];for await(const t of this){e.push(t);const r=this.readBufferedDocuments();if(null!=this.transform)for(const t of r)e.push(await this.transformDocument(t));else e.push(...r)}return e}addCursorFlag(e,r){if(this.throwIfInitialized(),!t.CURSOR_FLAGS.includes(e))throw new i.MongoInvalidArgumentError(`Flag ${e} is not one of ${t.CURSOR_FLAGS}`);if("boolean"!=typeof r)throw new i.MongoInvalidArgumentError(`Flag ${e} must be a boolean value`);return this.cursorOptions[e]=r,this}map(e){this.throwIfInitialized();const t=this.transform;return this.transform=t?r=>e(t(r)):e,this}withReadPreference(e){if(this.throwIfInitialized(),e instanceof d.ReadPreference)this.cursorOptions.readPreference=e;else{if("string"!=typeof e)throw new i.MongoInvalidArgumentError(`Invalid read preference: ${e}`);this.cursorOptions.readPreference=d.ReadPreference.fromString(e)}return this}withReadConcern(e){this.throwIfInitialized();const t=l.ReadConcern.fromOptions({readConcern:e});return t&&(this.cursorOptions.readConcern=t),this}maxTimeMS(e){if(this.throwIfInitialized(),"number"!=typeof e)throw new i.MongoInvalidArgumentError("Argument for maxTimeMS must be a number");return this.cursorOptions.maxTimeMS=e,this}batchSize(e){if(this.throwIfInitialized(),this.cursorOptions.tailable)throw new i.MongoTailableCursorError("Tailable cursor does not support batchSize");if("number"!=typeof e)throw new i.MongoInvalidArgumentError('Operation "batchSize" requires an integer');return this.cursorOptions.batchSize=e,this}rewind(){if(this.timeoutContext&&this.timeoutContext.owner!==this)throw new i.MongoAPIError("Cannot rewind cursor that does not own its timeout context.");this.initialized&&(this.cursorId=null,this.documents?.clear(),this.timeoutContext?.clear(),this.timeoutContext=void 0,this.isClosed=!1,this.isKilled=!1,this.initialized=!1,this.hasEmittedClose=!1,this.trackCursor(),!1===this.cursorSession?.explicit&&(this.cursorSession.hasEnded||this.cursorSession.endSession().then(void 0,f.squashError),this.cursorSession=null))}async getMore(e){if(null==this.cursorId)throw new i.MongoRuntimeError("Unexpected null cursor id. A cursor creating command should have set this");if(null==this.selectedServer)throw new i.MongoRuntimeError("Unexpected null selectedServer. A cursor creating command should have set this");if(null==this.cursorSession)throw new i.MongoRuntimeError("Unexpected null session. A cursor creating command should have set this");const t={...this.cursorOptions,session:this.cursorSession,batchSize:e},r=new c.GetMoreOperation(this.cursorNamespace,this.cursorId,this.selectedServer,t);return await(0,a.executeOperation)(this.cursorClient,r,this.timeoutContext)}async cursorInit(){null!=this.cursorOptions.timeoutMS&&(this.timeoutContext??=new O(m.TimeoutContext.create({serverSelectionTimeoutMS:this.client.s.options.serverSelectionTimeoutMS,timeoutMS:this.cursorOptions.timeoutMS}),this));try{this.cursorSession??=this.cursorClient.startSession({owner:this,explicit:!1});const e=await this._initialize(this.cursorSession);this.cursorOptions.omitMaxTimeMS=null!=this.cursorOptions.timeoutMS;const t=e.response;this.selectedServer=e.server,this.cursorId=t.id,this.cursorNamespace=t.ns??this.namespace,this.documents=t,this.initialized=!0}catch(e){throw this.initialized=!0,await this.cleanup(void 0,e),e}this.isDead&&await this.cleanup()}async fetchBatch(){if(this.isClosed)return;if(this.isDead)return void await this.cleanup();if(null==this.cursorId&&(await this.cursorInit(),0!==(this.documents?.length??0)||this.isDead))return;const e=this.cursorOptions.batchSize||1e3;try{const t=await this.getMore(e);this.cursorId=t.id,this.documents=t}catch(e){try{await this.cleanup(void 0,e)}catch(e){(0,f.squashError)(e)}throw e}this.isDead&&await this.cleanup()}async cleanup(e,t){this.abortListener?.[f.kDispose](),this.isClosed=!0;const r=()=>null!=e?(this.timeoutContext?.clear(),new O(m.TimeoutContext.create({serverSelectionTimeoutMS:this.client.s.options.serverSelectionTimeoutMS,timeoutMS:e}),this)):this.timeoutContext?.refreshed();await(async e=>{try{await e()}finally{this.emitClose()}})((async()=>{const e=this.cursorSession;if(e)try{if(!this.isKilled&&this.cursorId&&!this.cursorId.isZero()&&this.cursorNamespace&&this.selectedServer&&!e.hasEnded){this.isKilled=!0;const t=this.cursorId;this.cursorId=o.Long.ZERO,await(0,a.executeOperation)(this.cursorClient,new u.KillCursorsOperation(t,this.cursorNamespace,this.selectedServer,{session:e}),r())}}catch(e){(0,f.squashError)(e)}finally{e.owner===this&&await e.endSession({error:t}),e.inTransaction()||(0,p.maybeClearPinnedConnection)(e,{error:t})}}))}emitClose(){try{this.hasEmittedClose||0!==(this.documents?.length??0)&&!this.isClosed||this.emit("close")}finally{this.hasEmittedClose=!0}}async transformDocument(e){if(null==this.transform)return e;try{const t=this.transform(e);if(null===t){const e="Cursor returned a `null` document, but the cursor is not exhausted. Mapping documents to `null` is not supported in the cursor transform.";throw new i.MongoAPIError(e)}return t}catch(e){try{await this.close()}catch(e){(0,f.squashError)(e)}throw e}}throwIfInitialized(){if(this.initialized)throw new i.MongoCursorInUseError}}t.AbstractCursor=E,E.CLOSE="close";class S extends n.Readable{constructor(e){super({objectMode:!0,autoDestroy:!1,highWaterMark:1}),this._readInProgress=!1,this._cursor=e}_read(e){this._readInProgress||(this._readInProgress=!0,this._readNext())}_destroy(e,t){this._cursor.close().then((()=>t(e)),(e=>t(e)))}_readNext(){this._cursor.id!==o.Long.ZERO?this._cursor.next().then((e=>{if(null==e)this.push(null);else if(this.destroyed)this._cursor.close().then(void 0,f.squashError);else{if(this.push(e))return this._readNext();this._readInProgress=!1}}),(e=>e.message.match(/server is closed/)?(this._cursor.close().then(void 0,f.squashError),this.push(null)):e.message.match(/operation was interrupted/)?this.push(null):this.destroy(e))).catch((e=>{this._readInProgress=!1,this.destroy(e)})):this.push(null)}}(0,h.configureResourceManagement)(E.prototype);class O extends m.TimeoutContext{constructor(e,t){super(),this.timeoutContext=e,this.owner=t}get serverSelectionTimeout(){return this.timeoutContext.serverSelectionTimeout}get connectionCheckoutTimeout(){return this.timeoutContext.connectionCheckoutTimeout}get clearServerSelectionTimeout(){return this.timeoutContext.clearServerSelectionTimeout}get timeoutForSocketWrite(){return this.timeoutContext.timeoutForSocketWrite}get timeoutForSocketRead(){return this.timeoutContext.timeoutForSocketRead}csotEnabled(){return this.timeoutContext.csotEnabled()}refresh(){if("symbol"!=typeof this.owner)return this.timeoutContext.refresh()}clear(){if("symbol"!=typeof this.owner)return this.timeoutContext.clear()}get maxTimeMS(){return this.timeoutContext.maxTimeMS}get timeoutMS(){return this.timeoutContext.csotEnabled()?this.timeoutContext.timeoutMS:null}refreshed(){return new O(this.timeoutContext.refreshed(),this.owner)}addMaxTimeMSToCommand(e,t){this.timeoutContext.addMaxTimeMSToCommand(e,t)}getSocketTimeoutMS(){return this.timeoutContext.getSocketTimeoutMS()}}t.CursorTimeoutContext=O},61428:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getReadPreference=function(e){let t=e?.readPreference??o.ReadPreference.primary;if("string"==typeof t&&(t=o.ReadPreference.fromString(t)),!(t instanceof o.ReadPreference))throw new n.MongoInvalidArgumentError('Option "readPreference" must be a ReadPreference instance');return t},t.isSharded=function(e){return null!=e&&(!(!e.description||e.description.type!==i.ServerType.Mongos)||!!(e.description&&e.description instanceof s.TopologyDescription)&&Array.from(e.description.servers.values()).some((e=>e.type===i.ServerType.Mongos)))};const n=r(17562),o=r(13700),i=r(89167),s=r(97194)},61635:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.FindOneAndUpdateOperation=t.FindOneAndReplaceOperation=t.FindOneAndDeleteOperation=t.FindAndModifyOperation=t.ReturnDocument=void 0;const n=r(75725),o=r(17562),i=r(13700),s=r(30770),a=r(145),c=r(78130),u=r(35394);function l(e,r){return e.new=r.returnDocument===t.ReturnDocument.AFTER,e.upsert=!0===r.upsert,!0===r.bypassDocumentValidation&&(e.bypassDocumentValidation=r.bypassDocumentValidation),e}t.ReturnDocument=Object.freeze({BEFORE:"before",AFTER:"after"});class d extends c.CommandOperation{constructor(e,t,r){super(e,r),this.SERVER_COMMAND_RESPONSE_TYPE=n.MongoDBResponse,this.options=r,this.readPreference=i.ReadPreference.primary,this.collection=e,this.query=t}get commandName(){return"findAndModify"}buildCommandDocument(e,t){const r=this.options,n={findAndModify:this.collection.collectionName,query:this.query,remove:!1,new:!1,upsert:!1};r.includeResultMetadata??=!1;const i=(0,s.formatSort)(r.sort);if(i&&(n.sort=i),r.projection&&(n.fields=r.projection),r.maxTimeMS&&(n.maxTimeMS=r.maxTimeMS),r.writeConcern&&(n.writeConcern=r.writeConcern),r.let&&(n.let=r.let),void 0!==r.comment&&(n.comment=r.comment),(0,a.decorateWithCollation)(n,this.collection,r),r.hint){if(0===this.writeConcern?.w)throw new o.MongoCompatibilityError("The current topology does not support a hint on findAndModify commands");n.hint=r.hint}return n}handleOk(e){const t=super.handleOk(e);return this.options.includeResultMetadata?t:t.value??null}}t.FindAndModifyOperation=d,t.FindOneAndDeleteOperation=class extends d{constructor(e,t,r){if(null==t||"object"!=typeof t)throw new o.MongoInvalidArgumentError('Argument "filter" must be an object');super(e,t,r)}buildCommandDocument(e,t){const r=super.buildCommandDocument(e,t);return r.remove=!0,r}},t.FindOneAndReplaceOperation=class extends d{constructor(e,t,r,n){if(null==t||"object"!=typeof t)throw new o.MongoInvalidArgumentError('Argument "filter" must be an object');if(null==r||"object"!=typeof r)throw new o.MongoInvalidArgumentError('Argument "replacement" must be an object');if((0,a.hasAtomicOperators)(r))throw new o.MongoInvalidArgumentError("Replacement document must not contain atomic operators");super(e,t,n),this.replacement=r}buildCommandDocument(e,t){const r=super.buildCommandDocument(e,t);return r.update=this.replacement,l(r,this.options),r}},t.FindOneAndUpdateOperation=class extends d{constructor(e,t,r,n){if(null==t||"object"!=typeof t)throw new o.MongoInvalidArgumentError('Argument "filter" must be an object');if(null==r||"object"!=typeof r)throw new o.MongoInvalidArgumentError('Argument "update" must be an object');if(!(0,a.hasAtomicOperators)(r,n))throw new o.MongoInvalidArgumentError("Update document requires atomic operators");super(e,t,n),this.update=r,this.options=n}buildCommandDocument(e,t){const r=super.buildCommandDocument(e,t);return r.update=this.update,l(r,this.options),this.options.arrayFilters&&(r.arrayFilters=this.options.arrayFilters),r}},(0,u.defineAspects)(d,[u.Aspect.WRITE_OPERATION,u.Aspect.RETRYABLE,u.Aspect.EXPLAINABLE])},61861:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.RenameOperation=void 0;const n=r(75725),o=r(19498),i=r(145),s=r(78130),a=r(35394);class c extends s.CommandOperation{constructor(e,t,r){super(e,r),this.SERVER_COMMAND_RESPONSE_TYPE=n.MongoDBResponse,this.collection=e,this.newName=t,this.options=r,this.ns=new i.MongoDBNamespace("admin","$cmd")}get commandName(){return"renameCollection"}buildCommandDocument(e,t){return{renameCollection:this.collection.namespace,to:this.collection.s.namespace.withCollection(this.newName).toString(),dropTarget:"boolean"==typeof this.options.dropTarget&&this.options.dropTarget}}handleOk(e){return new o.Collection(this.collection.s.db,this.newName,this.collection.s.options)}}t.RenameOperation=c,(0,a.defineAspects)(c,[a.Aspect.WRITE_OPERATION])},62016:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AggregateOperation=t.DB_AGGREGATE_COLLECTION=void 0;const n=r(75725),o=r(17562),i=r(145),s=r(40012),a=r(78130),c=r(35394);t.DB_AGGREGATE_COLLECTION=1;class u extends a.CommandOperation{constructor(e,r,i){if(super(void 0,{...i,dbName:e.db}),this.SERVER_COMMAND_RESPONSE_TYPE=n.CursorResponse,this.options={...i},this.target=e.collection||t.DB_AGGREGATE_COLLECTION,this.pipeline=r,this.hasWriteStage=!1,"string"==typeof i?.out)this.pipeline=this.pipeline.concat({$out:i.out}),this.hasWriteStage=!0;else if(r.length>0){const e=r[r.length-1];(e.$out||e.$merge)&&(this.hasWriteStage=!0)}if(this.hasWriteStage||delete this.options.writeConcern,this.explain&&this.writeConcern)throw new o.MongoInvalidArgumentError('Option "explain" cannot be used on an aggregate call with writeConcern');if(null!=i?.cursor&&"object"!=typeof i.cursor)throw new o.MongoInvalidArgumentError("Cursor options must be an object");this.SERVER_COMMAND_RESPONSE_TYPE=this.explain?n.ExplainedCursorResponse:n.CursorResponse}get commandName(){return"aggregate"}get canRetryRead(){return!this.hasWriteStage}addToPipeline(e){this.pipeline.push(e)}buildCommandDocument(e){const t=this.options,r=(0,i.maxWireVersion)(e),n={aggregate:this.target,pipeline:this.pipeline};return this.hasWriteStage&&r<8&&(this.readConcern=void 0),this.hasWriteStage&&this.writeConcern&&s.WriteConcern.apply(n,this.writeConcern),!0===t.bypassDocumentValidation&&(n.bypassDocumentValidation=t.bypassDocumentValidation),"boolean"==typeof t.allowDiskUse&&(n.allowDiskUse=t.allowDiskUse),t.hint&&(n.hint=t.hint),t.let&&(n.let=t.let),void 0!==t.comment&&(n.comment=t.comment),n.cursor=t.cursor||{},t.batchSize&&!this.hasWriteStage&&(n.cursor.batchSize=t.batchSize),n}handleOk(e){return e}}t.AggregateOperation=u,(0,c.defineAspects)(u,[c.Aspect.READ_OPERATION,c.Aspect.RETRYABLE,c.Aspect.EXPLAINABLE,c.Aspect.CURSOR_CREATING])},63178:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.finishCommandDocument=function(e,t){return null!=t?{saslContinue:1,conversationId:t,payload:new n.Binary(n.BSON.serialize({jwt:e}))}:{saslStart:1,mechanism:o.AuthMechanism.MONGODB_OIDC,payload:new n.Binary(n.BSON.serialize({jwt:e}))}},t.startCommandDocument=function(e){const t={};return e.username&&(t.n=e.username),{saslStart:1,autoAuthorize:1,mechanism:o.AuthMechanism.MONGODB_OIDC,payload:new n.Binary(n.BSON.serialize(t))}};const n=r(75080),o=r(93065)},63257:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MongoDBOIDC=t.OIDC_WORKFLOWS=t.OIDC_VERSION=void 0;const n=r(17562),o=r(31057),i=r(88822),s=r(73619),a=r(9284),c=r(80890),u=r(8294),l=r(17309);t.OIDC_VERSION=1,t.OIDC_WORKFLOWS=new Map,t.OIDC_WORKFLOWS.set("test",(()=>new i.AutomatedCallbackWorkflow(new u.TokenCache,l.callback))),t.OIDC_WORKFLOWS.set("azure",(()=>new i.AutomatedCallbackWorkflow(new u.TokenCache,s.callback))),t.OIDC_WORKFLOWS.set("gcp",(()=>new i.AutomatedCallbackWorkflow(new u.TokenCache,a.callback))),t.OIDC_WORKFLOWS.set("k8s",(()=>new i.AutomatedCallbackWorkflow(new u.TokenCache,c.callback)));class d extends o.AuthProvider{constructor(e){if(super(),!e)throw new n.MongoInvalidArgumentError("No workflow provided to the OIDC auth provider.");this.workflow=e}async auth(e){const{connection:t,reauthenticating:r,response:n}=e;if(n?.speculativeAuthenticate?.done&&!r)return;const o=h(e);r?await this.workflow.reauthenticate(t,o):await this.workflow.execute(t,o,n)}async prepare(e,t){const{connection:r}=t,n=h(t);return{...e,...await this.workflow.speculativeAuth(r,n)}}}function h(e){const{credentials:t}=e;if(!t)throw new n.MongoMissingCredentialsError("AuthContext must provide credentials.");return t}t.MongoDBOIDC=d},64125:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.RemoveUserOperation=void 0;const n=r(75725),o=r(78130),i=r(35394);class s extends o.CommandOperation{constructor(e,t,r){super(e,r),this.SERVER_COMMAND_RESPONSE_TYPE=n.MongoDBResponse,this.options=r,this.username=t}get commandName(){return"dropUser"}buildCommandDocument(e){return{dropUser:this.username}}handleOk(e){return!0}}t.RemoveUserOperation=s,(0,i.defineAspects)(s,[i.Aspect.WRITE_OPERATION])},64515:(e,t,r)=>{var n=r(67787).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.uncompressibleCommands=t.Compressor=void 0,t.compress=async function(e,t){const r={};switch(e.agreedCompressor){case"snappy":return f??=g(),await f.compress(t);case"zstd":if(S(),"kModuleError"in m)throw m.kModuleError;return await m.compress(t,d);case"zlib":return e.zlibCompressionLevel&&(r.level=e.zlibCompressionLevel),await p(t,r);default:throw new c.MongoInvalidArgumentError(`Unknown compressor ${e.agreedCompressor} failed to compress`)}},t.decompress=E,t.compressCommand=async function(e,t){const r="none"!==t.agreedCompressor&&u.OpCompressedRequest.canCompress(e)?new u.OpCompressedRequest(e,{agreedCompressor:t.agreedCompressor??"none",zlibCompressionLevel:t.zlibCompressionLevel??0}):e,o=await r.toBin();return n.concat(o)},t.decompressResponse=async function(e){const t={length:e.readInt32LE(0),requestId:e.readInt32LE(4),responseTo:e.readInt32LE(8),opCode:e.readInt32LE(12)};if(t.opCode!==l.OP_COMPRESSED){const r=t.opCode===l.OP_MSG?u.OpMsgResponse:u.OpReply,n=e.subarray(O);return new r(e,t,n)}const r={...t,fromCompressed:!0,opCode:e.readInt32LE(O),length:e.readInt32LE(O+4)},n=e[O+8],o=e.slice(O+9),i=r.opCode===l.OP_MSG?u.OpMsgResponse:u.OpReply,s=await E(n,o);if(s.length!==r.length)throw new c.MongoDecompressionError("Message body and message header must be the same length");return new i(e,r,s)};const o=r(98437),i=r(25900),s=r(91869),a=r(8500),c=r(17562),u=r(15620),l=r(96856);t.Compressor=Object.freeze({none:0,snappy:1,zlib:2,zstd:3}),t.uncompressibleCommands=new Set([s.LEGACY_HELLO_COMMAND,"saslStart","saslContinue","getnonce","authenticate","createUser","updateUser","copydbSaslStart","copydbgetnonce","copydb"]);const d=3,h=(0,o.promisify)(i.inflate.bind(i)),p=(0,o.promisify)(i.deflate.bind(i));let m,f=null;function g(){if(null==f){const e=(0,a.getSnappy)();if("kModuleError"in e)throw e.kModuleError;f=e}return f}async function E(e,r){if(e!==t.Compressor.snappy&&e!==t.Compressor.zstd&&e!==t.Compressor.zlib&&e!==t.Compressor.none)throw new c.MongoDecompressionError(`Server sent message compressed using an unsupported compressor. (Received compressor ID ${e})`);switch(e){case t.Compressor.snappy:return f??=g(),await f.uncompress(r,{asBuffer:!0});case t.Compressor.zstd:if(S(),"kModuleError"in m)throw m.kModuleError;return await m.decompress(r);case t.Compressor.zlib:return await h(r);default:return r}}function S(){m||(m=(0,a.getZstdLibrary)())}const O=16},64647:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.X509=void 0;const n=r(17562),o=r(145),i=r(31057);class s extends i.AuthProvider{async prepare(e,t){const{credentials:r}=t;if(!r)throw new n.MongoMissingCredentialsError("AuthContext must provide credentials.");return{...e,speculativeAuthenticate:a(r)}}async auth(e){const t=e.connection,r=e.credentials;if(!r)throw new n.MongoMissingCredentialsError("AuthContext must provide credentials.");const i=e.response;i?.speculativeAuthenticate||await t.command((0,o.ns)("$external.$cmd"),a(r),void 0)}}function a(e){const t={authenticate:1,mechanism:"MONGODB-X509"};return e.username&&(t.user=e.username),t}t.X509=s},68526:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AggregationCursor=void 0;const n=r(17562),o=r(36411),i=r(62016),s=r(96357),a=r(145),c=r(61066),u=r(36649);class l extends u.ExplainableCursor{constructor(e,t,r=[],o={}){super(e,t,o),this.pipeline=r,this.aggregateOptions=o;const i=this.pipeline[this.pipeline.length-1];if(null!=this.cursorOptions.timeoutMS&&this.cursorOptions.timeoutMode===c.CursorTimeoutMode.ITERATION&&(null!=i?.$merge||null!=i?.$out))throw new n.MongoAPIError("Cannot use $out or $merge stage with ITERATION timeoutMode")}clone(){const e=(0,a.mergeOptions)({},this.aggregateOptions);return delete e.session,new l(this.client,this.namespace,this.pipeline,{...e})}map(e){return super.map(e)}async _initialize(e){const t={...this.aggregateOptions,...this.cursorOptions,session:e,signal:this.signal};if(t.explain)try{(0,o.validateExplainTimeoutOptions)(t,o.Explain.fromOptions(t))}catch{throw new n.MongoAPIError("timeoutMS cannot be used with explain when explain is specified in aggregateOptions")}const r=new i.AggregateOperation(this.namespace,this.pipeline,t),a=await(0,s.executeOperation)(this.client,r,this.timeoutContext);return{server:r.server,session:e,response:a}}async explain(e,t){const{explain:r,timeout:n}=this.resolveExplainTimeoutOptions(e,t);return(await(0,s.executeOperation)(this.client,new i.AggregateOperation(this.namespace,this.pipeline,{...this.aggregateOptions,...this.cursorOptions,...n,explain:r??!0}))).shift(this.deserializationOptions)}addStage(e){if(this.throwIfInitialized(),null!=this.cursorOptions.timeoutMS&&this.cursorOptions.timeoutMode===c.CursorTimeoutMode.ITERATION&&(null!=e.$out||null!=e.$merge))throw new n.MongoAPIError("Cannot use $out or $merge stage with ITERATION timeoutMode");return this.pipeline.push(e),this}group(e){return this.addStage({$group:e})}limit(e){return this.addStage({$limit:e})}match(e){return this.addStage({$match:e})}out(e){return this.addStage({$out:e})}project(e){return this.addStage({$project:e})}lookup(e){return this.addStage({$lookup:e})}redact(e){return this.addStage({$redact:e})}skip(e){return this.addStage({$skip:e})}sort(e){return this.addStage({$sort:e})}unwind(e){return this.addStage({$unwind:e})}geoNear(e){return this.addStage({$geoNear:e})}}t.AggregationCursor=l},68746:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OnDemandDocument=void 0;const n=r(75080);class o{constructor(e,t=0,r=!1,o){this.cache=Object.create(null),this.indexFound=Object.create(null),this.bson=e,this.offset=t,this.isArray=r,this.elements=o??(0,n.parseToElementsToArray)(this.bson,t)}isElementName(e,t){const r=t[2],n=t[1];if(e.length!==r)return!1;const o=n+r;for(let t=n,r=0;r<e.length&&t<o;r++,t++)if(this.bson[t]!==e.charCodeAt(r))return!1;return!0}getElement(e){const t=this.cache[e];if(!1===t)return null;if(null!=t)return t;if("number"==typeof e){if(this.isArray){if(e<this.elements.length){const t={element:this.elements[e],value:void 0};return this.cache[e]=t,this.indexFound[e]=!0,t}return null}return null}for(let t=0;t<this.elements.length;t++){const r=this.elements[t];if(!(t in this.indexFound)&&this.isElementName(e,r)){const n={element:r,value:void 0};return this.cache[e]=n,this.indexFound[t]=!0,n}}return this.cache[e]=!1,null}toJSValue(e,t){const r=e[0],i=e[3],s=e[4];if(t!==r)return null;switch(t){case n.BSONType.null:case n.BSONType.undefined:return null;case n.BSONType.double:return(0,n.getFloat64LE)(this.bson,i);case n.BSONType.int:return(0,n.getInt32LE)(this.bson,i);case n.BSONType.long:return(0,n.getBigInt64LE)(this.bson,i);case n.BSONType.bool:return Boolean(this.bson[i]);case n.BSONType.objectId:return new n.ObjectId(this.bson.subarray(i,i+12));case n.BSONType.timestamp:return new n.Timestamp((0,n.getBigInt64LE)(this.bson,i));case n.BSONType.string:return(0,n.toUTF8)(this.bson,i+4,i+s-1,!1);case n.BSONType.binData:{const e=(0,n.getInt32LE)(this.bson,i),t=this.bson[i+4];if(2===t){const t=(0,n.getInt32LE)(this.bson,i+1+4);if(t<0)throw new n.BSONError("Negative binary type element size found for subtype 0x02");if(t>e-4)throw new n.BSONError("Binary type with subtype 0x02 contains too long binary size");if(t<e-4)throw new n.BSONError("Binary type with subtype 0x02 contains too short binary size");return new n.Binary(this.bson.subarray(i+1+4+4,i+1+4+4+t),2)}return new n.Binary(this.bson.subarray(i+1+4,i+1+4+e),t)}case n.BSONType.date:return new Date(Number((0,n.getBigInt64LE)(this.bson,i)));case n.BSONType.object:return new o(this.bson,i);case n.BSONType.array:return new o(this.bson,i,!0);default:throw new n.BSONError(`Unsupported BSON type: ${t}`)}}size(){return this.elements.length}has(e){const t=this.cache[e];return!1!==t&&(null!=t||null!=this.getElement(e))}get(e,t,r){const o=this.getElement(e);if(null==o){if(!0===r)throw new n.BSONError(`BSON element "${e}" is missing`);return null}if(null==o.value){const i=this.toJSValue(o.element,t);if(null==i){if(!0===r)throw new n.BSONError(`BSON element "${e}" is missing`);return null}o.value=i}return o.value}getNumber(e,t){const r=this.get(e,n.BSONType.bool),o=null==r?null:r?1:0,i=this.get(e,n.BSONType.long),s=null==i?null:Number(i),a=o??s??this.get(e,n.BSONType.int)??this.get(e,n.BSONType.double);if(!0===t&&null==a)throw new n.BSONError(`BSON element "${e}" is missing`);return a}toObject(e){return(0,n.deserialize)(this.bson,{...e,index:this.offset,allowObjectSmallerThanBufferSize:!0})}toBytes(){const e=(0,n.getInt32LE)(this.bson,this.offset);return this.bson.subarray(this.offset,this.offset+e)}}t.OnDemandDocument=o},68838:function(e,t){var r;(function(){var n,o={},i={currentLanguage:"en",zeroFormat:null,nullFormat:null,defaultFormat:"0,0"},s={currentLanguage:i.currentLanguage,zeroFormat:i.zeroFormat,nullFormat:i.nullFormat,defaultFormat:i.defaultFormat},a={bytes:["B","KB","MB","GB","TB","PB","EB","ZB","YB"],iec:["B","KiB","MiB","GiB","TiB","PiB","EiB","ZiB","YiB"]};function c(e){this._value=e}function u(e,t,r,n){var o,i,s,a,c=e.toString().split("."),u=t-(n||0);return o=2===c.length?Math.min(Math.max(c[1].length,u),t):u,a=(r(e*(s=Math.pow(10,o)))/s).toFixed(o),n>t-o&&(i=new RegExp("\\.?0{1,"+(n-(t-o))+"}$"),a=a.replace(i,"")),a}function l(e,t,r){var n,i,a,c,l=!1,d=!1,h=!1,p="",m=!1,f=!1,g=!1,E=!1,S=!1,O="",y=!1;return null===e&&(e=0),n=Math.abs(e),t.indexOf("(")>-1?(l=!0,t=t.slice(1,-1)):t.indexOf("+")>-1&&(d=!0,t=t.replace(/\+/g,"")),t.indexOf("a")>-1&&(m=t.indexOf("aK")>=0,f=t.indexOf("aM")>=0,g=t.indexOf("aB")>=0,E=t.indexOf("aT")>=0,S=m||f||g||E,t.indexOf(" a")>-1&&(p=" "),t=t.replace(new RegExp(p+"a[KMBT]?"),""),n>=Math.pow(10,12)&&!S||E?(p+=o[s.currentLanguage].abbreviations.trillion,e/=Math.pow(10,12)):n<Math.pow(10,12)&&n>=Math.pow(10,9)&&!S||g?(p+=o[s.currentLanguage].abbreviations.billion,e/=Math.pow(10,9)):n<Math.pow(10,9)&&n>=Math.pow(10,6)&&!S||f?(p+=o[s.currentLanguage].abbreviations.million,e/=Math.pow(10,6)):(n<Math.pow(10,6)&&n>=Math.pow(10,3)&&!S||m)&&(p+=o[s.currentLanguage].abbreviations.thousand,e/=Math.pow(10,3))),t.indexOf("[.]")>-1&&(h=!0,t=t.replace("[.]",".")),i=e.toString().split(".")[0],a=t.split(".")[1],c=t.indexOf(","),a?(i=(O=a.indexOf("[")>-1?u(e,(a=(a=a.replace("]","")).split("["))[0].length+a[1].length,r,a[1].length):u(e,a.length,r)).split(".")[0],O=O.indexOf(".")>-1?o[s.currentLanguage].delimiters.decimal+O.split(".")[1]:"",h&&0===Number(O.slice(1))&&(O="")):i=u(e,null,r),i.indexOf("-")>-1&&(i=i.slice(1),y=!0),c>-1&&(i=i.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g,"$1"+o[s.currentLanguage].delimiters.thousands)),0===t.indexOf(".")&&(i=""),(l&&y?"(":"")+(!l&&y?"-":"")+(!y&&d?"+":"")+i+O+(p||"")+(l&&y?")":"")}function d(e){var t=e.toString().split(".");return t.length<2?1:Math.pow(10,t[1].length)}function h(){return Array.prototype.slice.call(arguments).reduce((function(e,t){var r=d(e),n=d(t);return r>n?r:n}),-1/0)}(n=function(e){return new c(e=n.isNumeral(e)?e.value():0===e||void 0===e?0:null===e?null:Number(e)?Number(e):n.fn.unformat(e))}).version="1.5.6",n.isNumeral=function(e){return e instanceof c},n.language=function(e,t){if(!e)return s.currentLanguage;if((e=e.toLowerCase())&&!t){if(!o[e])throw new Error("Unknown language : "+e);s.currentLanguage=e}return!t&&o[e]||function(e,t){o[e]=t}(e,t),n},n.reset=function(){for(var e in i)s[e]=i[e]},n.languageData=function(e){if(!e)return o[s.currentLanguage];if(!o[e])throw new Error("Unknown language : "+e);return o[e]},n.language("en",{delimiters:{thousands:",",decimal:"."},abbreviations:{thousand:"k",million:"m",billion:"b",trillion:"t"},ordinal:function(e){var t=e%10;return 1==~~(e%100/10)?"th":1===t?"st":2===t?"nd":3===t?"rd":"th"},currency:{symbol:"$"}}),n.zeroFormat=function(e){s.zeroFormat="string"==typeof e?e:null},n.nullFormat=function(e){s.nullFormat="string"==typeof e?e:null},n.defaultFormat=function(e){s.defaultFormat="string"==typeof e?e:"0.0"},n.validate=function(e,t){var r,o,i,s,a,c,u,l;if("string"!=typeof e&&(e+="",console.warn&&console.warn("Numeral.js: Value is not string. It has been co-erced to: ",e)),(e=e.trim()).match(/^\d+$/))return!0;if(""===e)return!1;try{u=n.languageData(t)}catch(e){u=n.languageData(n.language())}return i=u.currency.symbol,a=u.abbreviations,r=u.delimiters.decimal,o="."===u.delimiters.thousands?"\\.":u.delimiters.thousands,!(null!==(l=e.match(/^[^\d]+/))&&(e=e.substr(1),l[0]!==i)||null!==(l=e.match(/[^\d]+$/))&&(e=e.slice(0,-1),l[0]!==a.thousand&&l[0]!==a.million&&l[0]!==a.billion&&l[0]!==a.trillion)||(c=new RegExp(o+"{2}"),e.match(/[^\d.,]/g)||(s=e.split(r)).length>2||(s.length<2?!s[0].match(/^\d+.*\d$/)||s[0].match(c):1===s[0].length?!s[0].match(/^\d+$/)||s[0].match(c)||!s[1].match(/^\d+$/):!s[0].match(/^\d+.*\d$/)||s[0].match(c)||!s[1].match(/^\d+$/))))},Array.prototype.reduce||(Array.prototype.reduce=function(e){if(null===this)throw new TypeError("Array.prototype.reduce called on null or undefined");if("function"!=typeof e)throw new TypeError(e+" is not a function");var t,r=Object(this),n=r.length>>>0,o=0;if(2===arguments.length)t=arguments[1];else{for(;o<n&&!(o in r);)o++;if(o>=n)throw new TypeError("Reduce of empty array with no initial value");t=r[o++]}for(;o<n;o++)o in r&&(t=e(t,r[o],o,r));return t}),n.fn=c.prototype={clone:function(){return n(this)},format:function(e,t){return function(e,t,r){return 0===e._value&&null!==s.zeroFormat?s.zeroFormat:null===e._value&&null!==s.nullFormat?s.nullFormat:t.indexOf("$")>-1?function(e,t,r){var n,i,a=t.indexOf("$"),c=t.indexOf("("),u=t.indexOf("-"),d="";return t.indexOf(" $")>-1?(d=" ",t=t.replace(" $","")):t.indexOf("$ ")>-1?(d=" ",t=t.replace("$ ","")):t=t.replace("$",""),i=l(e._value,t,r),a<=1?i.indexOf("(")>-1||i.indexOf("-")>-1?(n=1,(a<c||a<u)&&(n=0),(i=i.split("")).splice(n,0,o[s.currentLanguage].currency.symbol+d),i=i.join("")):i=o[s.currentLanguage].currency.symbol+d+i:i.indexOf(")")>-1?((i=i.split("")).splice(-1,0,d+o[s.currentLanguage].currency.symbol),i=i.join("")):i=i+d+o[s.currentLanguage].currency.symbol,i}(e,t,r):t.indexOf("%")>-1?function(e,t,r){var n,o="",i=100*e._value;return t.indexOf(" %")>-1?(o=" ",t=t.replace(" %","")):t=t.replace("%",""),(n=l(i,t,r)).indexOf(")")>-1?((n=n.split("")).splice(-1,0,o+"%"),n=n.join("")):n=n+o+"%",n}(e,t,r):t.indexOf(":")>-1?function(e){var t=Math.floor(e._value/60/60),r=Math.floor((e._value-60*t*60)/60),n=Math.round(e._value-60*t*60-60*r);return t+":"+(r<10?"0"+r:r)+":"+(n<10?"0"+n:n)}(e):t.indexOf("b")>-1||t.indexOf("ib")>-1?function(e,t,r){var n,o,i,s=t.indexOf("ib")>-1?a.iec:a.bytes,c=e._value,u="";for(t.indexOf(" b")>-1||t.indexOf(" ib")>-1?(u=" ",t=t.replace(" ib","").replace(" b","")):t=t.replace("ib","").replace("b",""),n=0;n<=s.length;n++)if(o=Math.pow(1024,n),i=Math.pow(1024,n+1),null===c||0===c||c>=o&&c<i){u+=s[n],o>0&&(c/=o);break}return l(c,t,r)+u}(e,t,r):t.indexOf("o")>-1?function(e,t,r){var n="";return t.indexOf(" o")>-1?(n=" ",t=t.replace(" o","")):t=t.replace("o",""),n+=o[s.currentLanguage].ordinal(e._value),l(e._value,t,r)+n}(e,t,r):l(e._value,t,r)}(this,e||s.defaultFormat,void 0!==t?t:Math.round)},unformat:function(e){return"[object Number]"===Object.prototype.toString.call(e)?e:function(e,t){var r,n,i,c,u,l,d=t,h=!1;if(t.indexOf(":")>-1)l=function(e){var t=e.split(":"),r=0;return 3===t.length?(r+=60*Number(t[0])*60,r+=60*Number(t[1]),r+=Number(t[2])):2===t.length&&(r+=60*Number(t[0]),r+=Number(t[1])),Number(r)}(t);else if(t===s.zeroFormat||t===s.nullFormat)l=0;else{for("."!==o[s.currentLanguage].delimiters.decimal&&(t=t.replace(/\./g,"").replace(o[s.currentLanguage].delimiters.decimal,".")),r=new RegExp("[^a-zA-Z]"+o[s.currentLanguage].abbreviations.thousand+"(?:\\)|(\\"+o[s.currentLanguage].currency.symbol+")?(?:\\))?)?$"),n=new RegExp("[^a-zA-Z]"+o[s.currentLanguage].abbreviations.million+"(?:\\)|(\\"+o[s.currentLanguage].currency.symbol+")?(?:\\))?)?$"),i=new RegExp("[^a-zA-Z]"+o[s.currentLanguage].abbreviations.billion+"(?:\\)|(\\"+o[s.currentLanguage].currency.symbol+")?(?:\\))?)?$"),c=new RegExp("[^a-zA-Z]"+o[s.currentLanguage].abbreviations.trillion+"(?:\\)|(\\"+o[s.currentLanguage].currency.symbol+")?(?:\\))?)?$"),u=1;u<=a.bytes.length&&!(h=(t.indexOf(a.bytes[u])>-1||t.indexOf(a.iec[u])>-1)&&Math.pow(1024,u));u++);l=h||1,l*=d.match(r)?Math.pow(10,3):1,l*=d.match(n)?Math.pow(10,6):1,l*=d.match(i)?Math.pow(10,9):1,l*=d.match(c)?Math.pow(10,12):1,l*=t.indexOf("%")>-1?.01:1,l*=(t.split("-").length+Math.min(t.split("(").length-1,t.split(")").length-1))%2?1:-1,l*=Number(t.replace(/[^0-9\.]+/g,"")),l=h?Math.ceil(l):l}return e._value=l,e._value}(this,e||s.defaultFormat)},value:function(){return this._value},valueOf:function(){return this._value},set:function(e){return this._value=Number(e),this},add:function(e){var t=h.call(null,this._value,e);return this._value=[this._value,e].reduce((function(e,r,n,o){return e+t*r}),0)/t,this},subtract:function(e){var t=h.call(null,this._value,e);return this._value=[e].reduce((function(e,r,n,o){return e-t*r}),this._value*t)/t,this},multiply:function(e){return this._value=[this._value,e].reduce((function(e,t,r,n){var o=h(e,t);return e*o*(t*o)/(o*o)}),1),this},divide:function(e){return this._value=[this._value,e].reduce((function(e,t,r,n){var o=h(e,t);return e*o/(t*o)})),this},difference:function(e){return Math.abs(n(this._value).subtract(e).value())}},e.exports&&(e.exports=n),"undefined"==typeof ender&&(this.numeral=n),void 0===(r=function(){return n}.apply(t,[]))||(e.exports=r)}).call(this)},68923:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.GetMoreOperation=void 0;const n=r(75725),o=r(17562),i=r(145),s=r(35394);class a extends s.AbstractOperation{constructor(e,t,r,o){super(o),this.SERVER_COMMAND_RESPONSE_TYPE=n.CursorResponse,this.options=o,this.ns=e,this.cursorId=t,this.server=r}get commandName(){return"getMore"}buildCommand(e){if(null==this.cursorId||this.cursorId.isZero())throw new o.MongoRuntimeError("Unable to iterate cursor with no id");const t=this.ns.collection;if(null==t)throw new o.MongoRuntimeError("A collection name must be determined before getMore");const r={getMore:this.cursorId,collection:t};return"number"==typeof this.options.batchSize&&(r.batchSize=Math.abs(this.options.batchSize)),"number"==typeof this.options.maxAwaitTimeMS&&(r.maxTimeMS=this.options.maxAwaitTimeMS),void 0!==this.options.comment&&(0,i.maxWireVersion)(e)>=9&&(r.comment=this.options.comment),r}buildOptions(e){return{returnFieldSelector:null,documentsReturnedIn:"nextBatch",timeoutContext:e,...this.options}}handleOk(e){return e}}t.GetMoreOperation=a,(0,s.defineAspects)(a,[s.Aspect.READ_OPERATION,s.Aspect.MUST_SELECT_SAME_SERVER])},69429:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.RunCommandCursor=void 0;const n=r(17562),o=r(96357),i=r(68923),s=r(17668),a=r(145),c=r(61066);class u extends c.AbstractCursor{setComment(e){return this.getMoreOptions.comment=e,this}setMaxTimeMS(e){return this.getMoreOptions.maxAwaitTimeMS=e,this}setBatchSize(e){return this.getMoreOptions.batchSize=e,this}clone(){throw new n.MongoAPIError("Clone not supported, create a new cursor with db.runCursorCommand")}withReadConcern(e){throw new n.MongoAPIError("RunCommandCursor does not support readConcern it must be attached to the command being run")}addCursorFlag(e,t){throw new n.MongoAPIError("RunCommandCursor does not support cursor flags, they must be attached to the command being run")}maxTimeMS(e){throw new n.MongoAPIError("maxTimeMS must be configured on the command document directly, to configure getMore.maxTimeMS use cursor.setMaxTimeMS()")}batchSize(e){throw new n.MongoAPIError("batchSize must be configured on the command document directly, to configure getMore.batchSize use cursor.setBatchSize()")}constructor(e,t,r={}){super(e.client,(0,a.ns)(e.namespace),r),this.getMoreOptions={},this.db=e,this.command=Object.freeze({...t})}async _initialize(e){const t=new s.RunCursorCommandOperation(this.db.s.namespace,this.command,{...this.cursorOptions,session:e,readPreference:this.cursorOptions.readPreference}),r=await(0,o.executeOperation)(this.client,t,this.timeoutContext);return{server:t.server,session:e,response:r}}async getMore(e){if(!this.session)throw new n.MongoRuntimeError("Unexpected null session. A cursor creating command should have set this");const t=new i.GetMoreOperation(this.namespace,this.id,this.server,{...this.cursorOptions,session:this.session,...this.getMoreOptions});return await(0,o.executeOperation)(this.client,t,this.timeoutContext)}}t.RunCommandCursor=u},69878:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CreateCollectionOperation=void 0,t.createCollections=async function(e,t,r){const o=a.TimeoutContext.create({session:r.session,serverSelectionTimeoutMS:e.client.s.options.serverSelectionTimeoutMS,waitQueueTimeoutMS:e.client.s.options.waitQueueTimeoutMS,timeoutMS:r.timeoutMS}),i=r.encryptedFields??e.client.s.options.autoEncryption?.encryptedFieldsMap?.[`${e.databaseName}.${t}`];if(i){class a extends f{buildCommandDocument(e,t){if(!e.description.loadBalanced&&(0,c.maxWireVersion)(e)<n.MIN_SUPPORTED_QE_WIRE_VERSION)throw new s.MongoCompatibilityError(`${m} The minimum server version required is ${n.MIN_SUPPORTED_QE_SERVER_VERSION}`);return super.buildCommandDocument(e,t)}}const u=i.escCollection??`enxcol_.${t}.esc`,d=i.ecocCollection??`enxcol_.${t}.ecoc`;for(const t of[u,d]){const n=new a(e,t,{clusteredIndex:{key:{_id:1},unique:!0},session:r.session});await(0,l.executeOperation)(e.client,n,o)}r.encryptedFields||(r={...r,encryptedFields:i})}const u=await(0,l.executeOperation)(e.client,new f(e,t,r),o);if(i){const n=d.CreateIndexesOperation.fromIndexSpecification(e,t,{__safeContent__:1},{session:r.session});await(0,l.executeOperation)(e.client,n,o)}return u};const n=r(96856),o=r(75725),i=r(19498),s=r(17562),a=r(7799),c=r(145),u=r(78130),l=r(96357),d=r(22847),h=r(35394),p=new Set(["w","wtimeout","timeoutMS","j","fsync","autoIndexId","pkFactory","raw","readPreference","session","readConcern","writeConcern","raw","fieldsAsRaw","useBigInt64","promoteLongs","promoteValues","promoteBuffers","bsonRegExp","serializeFunctions","ignoreUndefined","enableUtf8Validation"]),m="Driver support of Queryable Encryption is incompatible with server. Upgrade server to use Queryable Encryption.";class f extends u.CommandOperation{constructor(e,t,r={}){super(e,r),this.SERVER_COMMAND_RESPONSE_TYPE=o.MongoDBResponse,this.options=r,this.db=e,this.name=t}get commandName(){return"create"}buildCommandDocument(e,t){return{create:this.name,...Object.fromEntries(Object.entries(this.options).filter((([e,t])=>null!=t&&"function"!=typeof t&&!p.has(e))))}}handleOk(e){return new i.Collection(this.db,this.name,this.options)}}t.CreateCollectionOperation=f,(0,h.defineAspects)(f,[h.Aspect.WRITE_OPERATION])},70136:(e,t,r)=>{var n,o=r(67787).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.AutoEncrypter=t.AutoEncryptionLoggerLevel=void 0;const i=r(26272),s=r(75080),a=r(91869),c=r(8500),u=r(17562),l=r(22220),d=r(145),h=r(73357),p=r(93992),m=r(86981),f=r(95724),g=r(51825),E=r(97515);t.AutoEncryptionLoggerLevel=Object.freeze({FatalError:0,Error:1,Warning:2,Info:3,Trace:4});class S{static getMongoCrypt(){const e=(0,c.getMongoDBClientEncryption)();if("kModuleError"in e)throw e.kModuleError;return e.MongoCrypt}constructor(e,t){if(this[n]=!1,this._client=e,this._bypassEncryption=!0===t.bypassAutoEncryption,this._keyVaultNamespace=t.keyVaultNamespace||"admin.datakeys",this._keyVaultClient=t.keyVaultClient||e,this._metaDataClient=t.metadataClient||e,this._proxyOptions=t.proxyOptions||{},this._tlsOptions=t.tlsOptions||{},this._kmsProviders=t.kmsProviders||{},this._credentialProviders=t.credentialProviders,t.credentialProviders?.aws&&!(0,g.isEmptyCredentials)("aws",this._kmsProviders))throw new m.MongoCryptInvalidArgumentError("Can only provide a custom AWS credential provider when the state machine is configured for automatic AWS credential fetching");const r={enableMultipleCollinfo:!0,cryptoCallbacks:p};t.schemaMap&&(r.schemaMap=o.isBuffer(t.schemaMap)?t.schemaMap:(0,s.serialize)(t.schemaMap)),t.encryptedFieldsMap&&(r.encryptedFieldsMap=o.isBuffer(t.encryptedFieldsMap)?t.encryptedFieldsMap:(0,s.serialize)(t.encryptedFieldsMap)),r.kmsProviders=o.isBuffer(this._kmsProviders)?this._kmsProviders:(0,s.serialize)(this._kmsProviders),t.options?.logger&&(r.logger=t.options.logger),t.extraOptions&&t.extraOptions.cryptSharedLibPath&&(r.cryptSharedLibPath=t.extraOptions.cryptSharedLibPath),t.bypassQueryAnalysis&&(r.bypassQueryAnalysis=t.bypassQueryAnalysis),null!=t.keyExpirationMS&&(r.keyExpirationMS=t.keyExpirationMS),this._bypassMongocryptdAndCryptShared=this._bypassEncryption||!!t.bypassQueryAnalysis,t.extraOptions&&t.extraOptions.cryptSharedLibSearchPaths?r.cryptSharedLibSearchPaths=t.extraOptions.cryptSharedLibSearchPaths:this._bypassMongocryptdAndCryptShared||(r.cryptSharedLibSearchPaths=["$SYSTEM"]);const a=S.getMongoCrypt();if(this._mongocrypt=new a(r),this._contextCounter=0,t.extraOptions&&t.extraOptions.cryptSharedLibRequired&&!this.cryptSharedLibVersionInfo)throw new m.MongoCryptInvalidArgumentError("`cryptSharedLibRequired` set but no crypt_shared library loaded");if(!this._bypassMongocryptdAndCryptShared&&!this.cryptSharedLibVersionInfo){this._mongocryptdManager=new f.MongocryptdManager(t.extraOptions);const e={serverSelectionTimeoutMS:1e4};null!=t.extraOptions&&"string"==typeof t.extraOptions.mongocryptdURI||i.getDefaultAutoSelectFamily||(e.family=4),i.getDefaultAutoSelectFamily&&Object.assign(e,(0,h.autoSelectSocketOptions)(this._client.s?.options??{})),this._mongocryptdClient=new l.MongoClient(this._mongocryptdManager.uri,e)}}async init(){if(!this._bypassMongocryptdAndCryptShared&&!this.cryptSharedLibVersionInfo){if(!this._mongocryptdManager)throw new u.MongoRuntimeError("Reached impossible state: mongocryptdManager is undefined when neither bypassSpawn nor the shared lib are specified.");if(!this._mongocryptdClient)throw new u.MongoRuntimeError("Reached impossible state: mongocryptdClient is undefined when neither bypassSpawn nor the shared lib are specified.");this._mongocryptdManager.bypassSpawn||await this._mongocryptdManager.spawn();try{return await this._mongocryptdClient.connect()}catch(e){throw new u.MongoRuntimeError("Unable to connect to `mongocryptd`, please make sure it is running or in your PATH for auto-spawn",{cause:e})}}}async close(){await(this._mongocryptdClient?.close())}async encrypt(e,t,r={}){if(r.signal?.throwIfAborted(),this._bypassEncryption)return t;const n=o.isBuffer(t)?t:(0,s.serialize)(t,r),i=this._mongocrypt.makeEncryptionContext(d.MongoDBCollectionNamespace.fromString(e).db,n);i.id=this._contextCounter++,i.ns=e,i.document=t;const a=new E.StateMachine({promoteValues:!1,promoteLongs:!1,proxyOptions:this._proxyOptions,tlsOptions:this._tlsOptions,socketOptions:(0,h.autoSelectSocketOptions)(this._client.s.options)});return(0,s.deserialize)(await a.execute(this,i,r),{promoteValues:!1,promoteLongs:!1})}async decrypt(e,t={}){t.signal?.throwIfAborted();const r=this._mongocrypt.makeDecryptionContext(e);r.id=this._contextCounter++;const n=new E.StateMachine({...t,proxyOptions:this._proxyOptions,tlsOptions:this._tlsOptions,socketOptions:(0,h.autoSelectSocketOptions)(this._client.s.options)});return await n.execute(this,r,t)}async askForKMSCredentials(){return await(0,g.refreshKMSCredentials)(this._kmsProviders,this._credentialProviders)}get cryptSharedLibVersionInfo(){return this._mongocrypt.cryptSharedLibVersionInfo}static get libmongocryptVersion(){return S.getMongoCrypt().libmongocryptVersion}}t.AutoEncrypter=S,n=a.kDecorateResult},70839:(e,t,r)=>{var n=r(67787).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.Plain=void 0;const o=r(75080),i=r(17562),s=r(145),a=r(31057);class c extends a.AuthProvider{async auth(e){const{connection:t,credentials:r}=e;if(!r)throw new i.MongoMissingCredentialsError("AuthContext must provide credentials.");const{username:a,password:c}=r,u={saslStart:1,mechanism:"PLAIN",payload:new o.Binary(n.from(`\0${a}\0${c}`)),autoAuthorize:1};await t.command((0,s.ns)("$external.$cmd"),u,void 0)}}t.Plain=c},71235:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Admin=void 0;const n=r(75080),o=r(96357),i=r(11706),s=r(64125),a=r(17668),c=r(31480),u=r(145);t.Admin=class{constructor(e){this.s={db:e}}async command(e,t){return await(0,o.executeOperation)(this.s.db.client,new a.RunCommandOperation(new u.MongoDBNamespace("admin"),e,{...(0,n.resolveBSONOptions)(t),session:t?.session,readPreference:t?.readPreference,timeoutMS:t?.timeoutMS??this.s.db.timeoutMS}))}async buildInfo(e){return await this.command({buildinfo:1},e)}async serverInfo(e){return await this.command({buildinfo:1},e)}async serverStatus(e){return await this.command({serverStatus:1},e)}async ping(e){return await this.command({ping:1},e)}async removeUser(e,t){return await(0,o.executeOperation)(this.s.db.client,new s.RemoveUserOperation(this.s.db,e,{dbName:"admin",...t}))}async validateCollection(e,t={}){return await(0,o.executeOperation)(this.s.db.client,new c.ValidateCollectionOperation(this,e,t))}async listDatabases(e){return await(0,o.executeOperation)(this.s.db.client,new i.ListDatabasesOperation(this.s.db,{timeoutMS:this.s.db.timeoutMS,...e}))}async replSetGetStatus(e){return await this.command({replSetGetStatus:1},e)}}},71470:(e,t,r)=>{var n=r(67787).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.CryptoConnection=t.SizedMessageTransform=t.Connection=void 0,t.hasSessionSupport=function(e){return null!=e.description.logicalSessionTimeoutMinutes};const o=r(93874),i=r(37668),s=r(75080),a=r(91869),c=r(17562),u=r(93347),l=r(4642),d=r(13700),h=r(89167),p=r(14019),m=r(7799),f=r(145),g=r(38216),E=r(15620),S=r(23611),O=r(64515),y=r(97531),C=r(75725),M=r(61428);class T extends l.TypedEventEmitter{constructor(e,t){super(),this.lastHelloMS=-1,this.helloOk=!1,this.delayedTimeoutId=null,this.closed=!1,this.clusterTime=null,this.error=null,this.dataEvents=null,this.on("error",f.noop),this.socket=e,this.id=t.id,this.address=function(e,t){if(t.proxyHost)return t.hostAddress.toString();const{remoteAddress:r,remotePort:n}=e;return"string"==typeof r&&"number"==typeof n?f.HostAddress.fromHostPort(r,n).toString():(0,f.uuidV4)().toString("hex")}(e,t),this.socketTimeoutMS=t.socketTimeoutMS??0,this.monitorCommands=t.monitorCommands,this.serverApi=t.serverApi,this.mongoLogger=t.mongoLogger,this.established=!1,this.description=new S.StreamDescription(this.address,t),this.generation=t.generation,this.lastUseTime=(0,f.now)(),this.messageStream=this.socket.on("error",this.onSocketError.bind(this)).pipe(new w({connection:this})).on("error",this.onTransformError.bind(this)),this.socket.on("close",this.onClose.bind(this)),this.socket.on("timeout",this.onTimeout.bind(this)),this.messageStream.pause()}get hello(){return this.description.hello}set hello(e){this.description.receiveResponse(e),Object.freeze(this.description)}get serviceId(){return this.hello?.serviceId}get loadBalanced(){return this.description.loadBalanced}get idleTime(){return(0,f.calculateDurationInMs)(this.lastUseTime)}get hasSessionSupport(){return null!=this.description.logicalSessionTimeoutMinutes}get supportsOpMsg(){return null!=this.description&&(0,f.maxWireVersion)(this)>=6&&!this.description.__nodejs_mock_server__}get shouldEmitAndLogCommand(){return(this.monitorCommands||this.established&&!this.authContext?.reauthenticating&&this.mongoLogger?.willLog(u.MongoLoggableComponent.COMMAND,u.SeverityLevel.DEBUG))??!1}markAvailable(){this.lastUseTime=(0,f.now)()}onSocketError(e){this.onError(new c.MongoNetworkError(e.message,{cause:e}))}onTransformError(e){this.onError(e)}onError(e){this.cleanup(e)}onClose(){const e=`connection ${this.id} to ${this.address} closed`;this.cleanup(new c.MongoNetworkError(e))}onTimeout(){this.delayedTimeoutId=(0,i.setTimeout)((()=>{const e=`connection ${this.id} to ${this.address} timed out`,t=null==this.hello;this.cleanup(new c.MongoNetworkTimeoutError(e,{beforeHandshake:t}))}),1).unref()}destroy(){if(this.closed)return;this.removeAllListeners(T.PINNED),this.removeAllListeners(T.UNPINNED);const e=`connection ${this.id} to ${this.address} closed`;this.cleanup(new c.MongoNetworkError(e))}cleanup(e){this.closed||(this.socket.destroy(),this.error=e,this.dataEvents?.throw(e).then(void 0,f.squashError),this.closed=!0,this.emit(T.CLOSE))}prepareCommand(e,t,r){let n={...t};const o=(0,M.getReadPreference)(r),i=r?.session;let s=this.clusterTime;if(this.serverApi){const{version:e,strict:t,deprecationErrors:r}=this.serverApi;n.apiVersion=e,null!=t&&(n.apiStrict=t),null!=r&&(n.apiDeprecationErrors=r)}if(this.hasSessionSupport&&i){i.clusterTime&&s&&i.clusterTime.clusterTime.greaterThan(s.clusterTime)&&(s=i.clusterTime);const e=(0,p.applySession)(i,n,r);if(e)throw e}else if(i?.explicit)throw new c.MongoCompatibilityError("Current topology does not support sessions");s&&(n.$clusterTime=s),this.description.type!==h.ServerType.Standalone&&((0,M.isSharded)(this)||this.description.loadBalanced||!this.supportsOpMsg||!0!==r.directConnection||"primary"!==o?.mode?(0,M.isSharded)(this)&&!this.supportsOpMsg&&"primary"!==o?.mode?n={$query:n,$readPreference:o.toJSON()}:"primary"!==o?.mode&&(n.$readPreference=o.toJSON()):n.$readPreference=d.ReadPreference.primaryPreferred.toJSON());const a={numberToSkip:0,numberToReturn:-1,checkKeys:!1,secondaryOk:o.secondaryOk(),...r};return r.timeoutContext?.addMaxTimeMSToCommand(n,r),this.supportsOpMsg?new E.OpMsgRequest(e,n,a):new E.OpQueryRequest(e,n,a)}async*sendWire(e,t,r){this.throwIfAborted();const n=t.socketTimeoutMS??t?.timeoutContext?.getSocketTimeoutMS()??this.socketTimeoutMS;this.socket.setTimeout(n);try{if(await this.writeCommand(e,{agreedCompressor:this.description.compressor??"none",zlibCompressionLevel:this.description.zlibCompressionLevel,timeoutContext:t.timeoutContext,signal:t.signal}),t.noResponse||e.moreToCome)return void(yield C.MongoDBResponse.empty);if(this.throwIfAborted(),t.timeoutContext?.csotEnabled()&&null!=t.timeoutContext.minRoundTripTime&&t.timeoutContext.remainingTimeMS<t.timeoutContext.minRoundTripTime)throw new c.MongoOperationTimeoutError("Server roundtrip time is greater than the time remaining");for await(const e of this.readMany(t)){this.socket.setTimeout(0);const t=e.parse(),o=(r??C.MongoDBResponse).make(t);yield o,this.throwIfAborted(),this.socket.setTimeout(n)}}finally{this.socket.setTimeout(0)}}async*sendCommand(e,t,r,n){r?.signal?.throwIfAborted();const o=this.prepareCommand(e.db,t,r);let i=0;this.shouldEmitAndLogCommand&&(i=(0,f.now)(),this.emitAndLogCommand(this.monitorCommands,T.COMMAND_STARTED,o.databaseName,this.established,new g.CommandStartedEvent(this,o,this.description.serverConnectionId)));const s=null!=r.documentsReturnedIn&&r.raw?{...r,raw:!1,fieldsAsRaw:{[r.documentsReturnedIn]:!0}}:r;let a,u;try{for await(a of(this.throwIfAborted(),this.sendWire(o,r,n))){if(u=void 0,null!=r.session&&(0,p.updateSessionFromResponse)(r.session,a),a.$clusterTime&&(this.clusterTime=a.$clusterTime,this.emit(T.CLUSTER_TIME_RECEIVED,a.$clusterTime)),0===a.ok){if(r.timeoutContext?.csotEnabled()&&a.isMaxTimeExpiredError)throw new c.MongoOperationTimeoutError("Server reported a timeout error",{cause:new c.MongoServerError(u??=a.toObject(s))});throw new c.MongoServerError(u??=a.toObject(s))}this.shouldEmitAndLogCommand&&this.emitAndLogCommand(this.monitorCommands,T.COMMAND_SUCCEEDED,o.databaseName,this.established,new g.CommandSucceededEvent(this,o,r.noResponse?void 0:o.moreToCome?{ok:1}:u??=a.toObject(s),i,this.description.serverConnectionId)),null==n?yield u??=a.toObject(s):yield a,this.throwIfAborted()}}catch(e){throw this.shouldEmitAndLogCommand&&this.emitAndLogCommand(this.monitorCommands,T.COMMAND_FAILED,o.databaseName,this.established,new g.CommandFailedEvent(this,o,e,i,this.description.serverConnectionId)),e}}async command(e,t,r={},n){this.throwIfAborted(),r.signal?.throwIfAborted();for await(const o of this.sendCommand(e,t,r,n)){if(r.timeoutContext?.csotEnabled())if(C.MongoDBResponse.is(o)){if(o.isMaxTimeExpiredError)throw new c.MongoOperationTimeoutError("Server reported a timeout error",{cause:new c.MongoServerError(o.toObject())})}else if(Array.isArray(o?.writeErrors)&&o.writeErrors.some((e=>e?.code===c.MONGODB_ERROR_CODES.MaxTimeMSExpired))||o?.writeConcernError?.code===c.MONGODB_ERROR_CODES.MaxTimeMSExpired)throw new c.MongoOperationTimeoutError("Server reported a timeout error",{cause:new c.MongoServerError(o)});return o}throw new c.MongoUnexpectedServerResponseError("Unable to get response from server")}exhaustCommand(e,t,r,n){(async()=>{this.throwIfAborted();for await(const o of this.sendCommand(e,t,r))n(void 0,o),this.throwIfAborted();throw new c.MongoUnexpectedServerResponseError("Server ended moreToCome unexpectedly")})().then(void 0,n)}throwIfAborted(){if(this.error)throw this.error}async writeCommand(e,t){const r="none"!==t.agreedCompressor&&E.OpCompressedRequest.canCompress(e)?new E.OpCompressedRequest(e,{agreedCompressor:t.agreedCompressor??"none",zlibCompressionLevel:t.zlibCompressionLevel??0}):e,o=n.concat(await r.toBin());if(t.timeoutContext?.csotEnabled()&&null!=t.timeoutContext.minRoundTripTime&&t.timeoutContext.remainingTimeMS<t.timeoutContext.minRoundTripTime)throw new c.MongoOperationTimeoutError("Server roundtrip time is greater than the time remaining");if(this.socket.write(o))return;const i=(0,f.once)(this.socket,"drain",t),s=t?.timeoutContext?.timeoutForSocketWrite,a=s?Promise.race([i,s]):i;try{return await a}catch(e){if(m.TimeoutError.is(e)){const e=new c.MongoOperationTimeoutError("Timed out at socket write");throw this.onError(e),e}throw e===t.signal?.reason&&this.onError(e),e}finally{s?.clear()}}async*readMany(e){try{this.dataEvents=(0,y.onData)(this.messageStream,e),this.messageStream.resume();for await(const e of this.dataEvents){const t=await(0,O.decompressResponse)(e);if(yield t,!t.moreToCome)return}}catch(t){if(m.TimeoutError.is(t)){const e=new c.MongoOperationTimeoutError(`Timed out during socket read (${t.duration}ms)`);throw this.dataEvents=null,this.onError(e),e}throw t===e.signal?.reason&&this.onError(t),t}finally{this.dataEvents=null,this.messageStream.pause()}}}t.Connection=T,T.COMMAND_STARTED=a.COMMAND_STARTED,T.COMMAND_SUCCEEDED=a.COMMAND_SUCCEEDED,T.COMMAND_FAILED=a.COMMAND_FAILED,T.CLUSTER_TIME_RECEIVED=a.CLUSTER_TIME_RECEIVED,T.CLOSE=a.CLOSE,T.PINNED=a.PINNED,T.UNPINNED=a.UNPINNED;class w extends o.Transform{constructor({connection:e}){super({writableObjectMode:!1,readableObjectMode:!0}),this.bufferPool=new f.BufferPool,this.connection=e}_transform(e,t,r){for(null!=this.connection.delayedTimeoutId&&((0,i.clearTimeout)(this.connection.delayedTimeoutId),this.connection.delayedTimeoutId=null),this.bufferPool.append(e);this.bufferPool.length;){const e=this.bufferPool.getInt32();if(null==e)break;if(e<0)return r(new c.MongoParseError(`Message size cannot be negative: ${e}`));if(e>this.bufferPool.length)break;const t=this.bufferPool.read(e);if(!this.push(t))return r(new c.MongoRuntimeError("SizedMessageTransform does not support backpressure"))}r()}}t.SizedMessageTransform=w,t.CryptoConnection=class extends T{constructor(e,t){super(e,t),this.autoEncrypter=t.autoEncrypter}async command(e,t,r,n){const{autoEncrypter:o}=this;if(!o)throw new c.MongoMissingDependencyError("No AutoEncrypter available for encryption",{dependencyName:"n/a"});const i=(0,f.maxWireVersion)(this);if(0===i)return await super.command(e,t,r,n);if(i<8)throw new c.MongoCompatibilityError("Auto-encryption requires a minimum MongoDB version of 4.2");const u=t.find||t.findAndModify?t.sort:null,l=t.createIndexes?t.indexes.map((e=>e.key)):null,d=await o.encrypt(e.toString(),t,r);if(null!=u&&(t.find||t.findAndModify)&&(d.sort=u),null!=l&&t.createIndexes)for(const[e,t]of l.entries())d.indexes[e].key=t;const h=await super.command(e,d,r,n??C.MongoDBResponse),p=await o.decrypt(h.toBytes(),r),m=n?.make(p)??(0,s.deserialize)(p,r);return o[a.kDecorateResult]&&(null==n?(0,f.decorateDecryptionResult)(m,h.toObject(),!0):m instanceof C.CursorResponse&&(m.encryptedResponse=h)),m}}},71906:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ListSearchIndexesCursor=void 0;const n=r(68526);class o extends n.AggregationCursor{constructor({fullNamespace:e,client:t},r,n={}){super(t,e,null==r?[{$listSearchIndexes:{}}]:[{$listSearchIndexes:{name:r}}],n)}}t.ListSearchIndexesCursor=o},73357:(e,t,r)=>{var n=r(67787).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.ClientEncryption=void 0,t.autoSelectSocketOptions=p;const o=r(75080),i=r(8500),s=r(7799),a=r(145),c=r(93992),u=r(86981),l=r(51825),d=r(97515);class h{static getMongoCrypt(){const e=(0,i.getMongoDBClientEncryption)();if("kModuleError"in e)throw e.kModuleError;return e.MongoCrypt}constructor(e,t){this._client=e,this._proxyOptions=t.proxyOptions??{},this._tlsOptions=t.tlsOptions??{},this._kmsProviders=t.kmsProviders||{};const{timeoutMS:r}=(0,a.resolveTimeoutOptions)(e,t);if(this._timeoutMS=r,this._credentialProviders=t.credentialProviders,t.credentialProviders?.aws&&!(0,l.isEmptyCredentials)("aws",this._kmsProviders))throw new u.MongoCryptInvalidArgumentError("Can only provide a custom AWS credential provider when the state machine is configured for automatic AWS credential fetching");if(null==t.keyVaultNamespace)throw new u.MongoCryptInvalidArgumentError("Missing required option `keyVaultNamespace`");const i={...t,cryptoCallbacks:c,kmsProviders:n.isBuffer(this._kmsProviders)?this._kmsProviders:(0,o.serialize)(this._kmsProviders)};this._keyVaultNamespace=t.keyVaultNamespace,this._keyVaultClient=t.keyVaultClient||e;const s=h.getMongoCrypt();this._mongoCrypt=new s(i)}async createDataKey(e,t={}){if(t.keyAltNames&&!Array.isArray(t.keyAltNames))throw new u.MongoCryptInvalidArgumentError(`Option "keyAltNames" must be an array of strings, but was of type ${typeof t.keyAltNames}.`);let r,n;t.keyAltNames&&t.keyAltNames.length>0&&(r=t.keyAltNames.map(((e,t)=>{if("string"!=typeof e)throw new u.MongoCryptInvalidArgumentError(`Option "keyAltNames" must be an array of strings, but item at index ${t} was of type ${typeof e}`);return(0,o.serialize)({keyAltName:e})}))),t.keyMaterial&&(n=(0,o.serialize)({keyMaterial:t.keyMaterial}));const i=(0,o.serialize)({provider:e,...t.masterKey}),c=this._mongoCrypt.makeDataKeyContext(i,{keyAltNames:r,keyMaterial:n}),l=new d.StateMachine({proxyOptions:this._proxyOptions,tlsOptions:this._tlsOptions,socketOptions:p(this._client.s.options)}),h=t?.timeoutContext??s.TimeoutContext.create((0,a.resolveTimeoutOptions)(this._client,{timeoutMS:this._timeoutMS})),m=(0,o.deserialize)(await l.execute(this,c,{timeoutContext:h})),{db:f,collection:g}=a.MongoDBCollectionNamespace.fromString(this._keyVaultNamespace),{insertedId:E}=await this._keyVaultClient.db(f).collection(g).insertOne(m,{writeConcern:{w:"majority"},timeoutMS:h?.csotEnabled()?h?.getRemainingTimeMSOrThrow():void 0});return E}async rewrapManyDataKey(e,t){let r;if(t){const e=Object.assign({provider:t.provider},t.masterKey);r=(0,o.serialize)(e)}const n=(0,o.serialize)(e),i=this._mongoCrypt.makeRewrapManyDataKeyContext(n,r),c=new d.StateMachine({proxyOptions:this._proxyOptions,tlsOptions:this._tlsOptions,socketOptions:p(this._client.s.options)}),u=s.TimeoutContext.create((0,a.resolveTimeoutOptions)(this._client,{timeoutMS:this._timeoutMS})),{v:l}=(0,o.deserialize)(await c.execute(this,i,{timeoutContext:u}));if(0===l.length)return{};const{db:h,collection:m}=a.MongoDBCollectionNamespace.fromString(this._keyVaultNamespace),f=l.map((e=>({updateOne:{filter:{_id:e._id},update:{$set:{masterKey:e.masterKey,keyMaterial:e.keyMaterial},$currentDate:{updateDate:!0}}}})));return{bulkWriteResult:await this._keyVaultClient.db(h).collection(m).bulkWrite(f,{writeConcern:{w:"majority"},timeoutMS:u.csotEnabled()?u?.remainingTimeMS:void 0})}}async deleteKey(e){const{db:t,collection:r}=a.MongoDBCollectionNamespace.fromString(this._keyVaultNamespace);return await this._keyVaultClient.db(t).collection(r).deleteOne({_id:e},{writeConcern:{w:"majority"},timeoutMS:this._timeoutMS})}getKeys(){const{db:e,collection:t}=a.MongoDBCollectionNamespace.fromString(this._keyVaultNamespace);return this._keyVaultClient.db(e).collection(t).find({},{readConcern:{level:"majority"},timeoutMS:this._timeoutMS})}async getKey(e){const{db:t,collection:r}=a.MongoDBCollectionNamespace.fromString(this._keyVaultNamespace);return await this._keyVaultClient.db(t).collection(r).findOne({_id:e},{readConcern:{level:"majority"},timeoutMS:this._timeoutMS})}async getKeyByAltName(e){const{db:t,collection:r}=a.MongoDBCollectionNamespace.fromString(this._keyVaultNamespace);return await this._keyVaultClient.db(t).collection(r).findOne({keyAltNames:e},{readConcern:{level:"majority"},timeoutMS:this._timeoutMS})}async addKeyAltName(e,t){const{db:r,collection:n}=a.MongoDBCollectionNamespace.fromString(this._keyVaultNamespace);return await this._keyVaultClient.db(r).collection(n).findOneAndUpdate({_id:e},{$addToSet:{keyAltNames:t}},{writeConcern:{w:"majority"},returnDocument:"before",timeoutMS:this._timeoutMS})}async removeKeyAltName(e,t){const{db:r,collection:n}=a.MongoDBCollectionNamespace.fromString(this._keyVaultNamespace),o=[{$set:{keyAltNames:{$cond:[{$eq:["$keyAltNames",[t]]},"$$REMOVE",{$filter:{input:"$keyAltNames",cond:{$ne:["$$this",t]}}}]}}}];return await this._keyVaultClient.db(r).collection(n).findOneAndUpdate({_id:e},o,{writeConcern:{w:"majority"},returnDocument:"before",timeoutMS:this._timeoutMS})}async createEncryptedCollection(e,t,r){const{provider:n,masterKey:o,createCollectionOptions:{encryptedFields:{...i},...c}}=r,l=null!=this._timeoutMS?s.TimeoutContext.create((0,a.resolveTimeoutOptions)(this._client,{timeoutMS:this._timeoutMS})):void 0;if(Array.isArray(i.fields)){const e=i.fields.map((async e=>null==e||"object"!=typeof e||null!=e.keyId?e:{...e,keyId:await this.createDataKey(n,{masterKey:o,timeoutContext:l?.csotEnabled()?l?.clone():void 0})})),t=await Promise.allSettled(e);i.fields=t.map(((e,t)=>"fulfilled"===e.status?e.value:i.fields[t]));const r=t.find((e=>"rejected"===e.status));if(null!=r)throw new u.MongoCryptCreateDataKeyError(i,{cause:r.reason})}try{return{collection:await e.createCollection(t,{...c,encryptedFields:i,timeoutMS:l?.csotEnabled()?l?.getRemainingTimeMSOrThrow():void 0}),encryptedFields:i}}catch(e){throw new u.MongoCryptCreateEncryptedCollectionError(i,{cause:e})}}async encrypt(e,t){return await this._encrypt(e,!1,t)}async encryptExpression(e,t){return await this._encrypt(e,!0,t)}async decrypt(e){const t=(0,o.serialize)({v:e}),r=this._mongoCrypt.makeExplicitDecryptionContext(t),n=new d.StateMachine({proxyOptions:this._proxyOptions,tlsOptions:this._tlsOptions,socketOptions:p(this._client.s.options)}),i=null!=this._timeoutMS?s.TimeoutContext.create((0,a.resolveTimeoutOptions)(this._client,{timeoutMS:this._timeoutMS})):void 0,{v:c}=(0,o.deserialize)(await n.execute(this,r,{timeoutContext:i}));return c}async askForKMSCredentials(){return await(0,l.refreshKMSCredentials)(this._kmsProviders,this._credentialProviders)}static get libmongocryptVersion(){return h.getMongoCrypt().libmongocryptVersion}async _encrypt(e,t,r){const{algorithm:n,keyId:i,keyAltName:c,contentionFactor:l,queryType:h,rangeOptions:m,textOptions:f}=r,g={expressionMode:t,algorithm:n};if(i&&(g.keyId=i.buffer),c){if(i)throw new u.MongoCryptInvalidArgumentError('"options" cannot contain both "keyId" and "keyAltName"');if("string"!=typeof c)throw new u.MongoCryptInvalidArgumentError('"options.keyAltName" must be of type string, but was of type '+typeof c);g.keyAltName=(0,o.serialize)({keyAltName:c})}"number"!=typeof l&&"bigint"!=typeof l||(g.contentionFactor=l),"string"==typeof h&&(g.queryType=h),"object"==typeof m&&(g.rangeOptions=(0,o.serialize)(m)),"object"==typeof f&&(g.textOptions=(0,o.serialize)(f));const E=(0,o.serialize)({v:e}),S=new d.StateMachine({proxyOptions:this._proxyOptions,tlsOptions:this._tlsOptions,socketOptions:p(this._client.s.options)}),O=this._mongoCrypt.makeExplicitEncryptionContext(E,g),y=null!=this._timeoutMS?s.TimeoutContext.create((0,a.resolveTimeoutOptions)(this._client,{timeoutMS:this._timeoutMS})):void 0,{v:C}=(0,o.deserialize)(await S.execute(this,O,{timeoutContext:y}));return C}}function p(e){const t={autoSelectFamily:!0};return"autoSelectFamily"in e&&(t.autoSelectFamily=e.autoSelectFamily),"autoSelectFamilyAttemptTimeout"in e&&(t.autoSelectFamilyAttemptTimeout=e.autoSelectFamilyAttemptTimeout),t}t.ClientEncryption=h},73619:(e,t,r)=>{var n=r(9606).URL;Object.defineProperty(t,"__esModule",{value:!0}),t.callback=void 0;const o=r(79790),i=r(17562),s=r(145),a=Object.freeze({Metadata:"true",Accept:"application/json"});t.callback=async e=>{const t=e.tokenAudience,r=e.username;if(!t)throw new i.MongoAzureError("TOKEN_RESOURCE must be set in the auth mechanism properties when ENVIRONMENT is azure.");const c=await async function(e,t){const r=new n(o.AZURE_BASE_URL);(0,o.addAzureParams)(r,e,t);const c=await(0,s.get)(r,{headers:a});if(200!==c.status)throw new i.MongoAzureError(`Status code ${c.status} returned from the Azure endpoint. Response body: ${c.body}`);const u=JSON.parse(c.body);return{accessToken:u.access_token,expiresInSeconds:Number(u.expires_in)}}(t,r);if(null==(u=c)||"object"!=typeof u||!("accessToken"in u)||"string"!=typeof u.accessToken||!("expiresInSeconds"in u)||"number"!=typeof u.expiresInSeconds)throw new i.MongoAzureError("Azure endpoint did not return a value with only access_token and expires_in properties");var u;return c}},74158:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.GridFSBucket=void 0;const n=r(17562),o=r(4642),i=r(7799),s=r(145),a=r(40012),c=r(33104),u=r(10557),l={bucketName:"fs",chunkSizeBytes:261120};class d extends o.TypedEventEmitter{constructor(e,t){super(),this.on("error",s.noop),this.setMaxListeners(0);const r=(0,s.resolveOptions)(e,{...l,...t,writeConcern:a.WriteConcern.fromOptions(t)});this.s={db:e,options:r,_chunksCollection:e.collection(r.bucketName+".chunks"),_filesCollection:e.collection(r.bucketName+".files"),checkedIndexes:!1,calledOpenUploadStream:!1}}openUploadStream(e,t){return new u.GridFSBucketWriteStream(this,e,{timeoutMS:this.s.options.timeoutMS,...t})}openUploadStreamWithId(e,t,r){return new u.GridFSBucketWriteStream(this,t,{timeoutMS:this.s.options.timeoutMS,...r,id:e})}openDownloadStream(e,t){return new c.GridFSBucketReadStream(this.s._chunksCollection,this.s._filesCollection,this.s.options.readPreference,{_id:e},{timeoutMS:this.s.options.timeoutMS,...t})}async delete(e,t){const{timeoutMS:r}=(0,s.resolveOptions)(this.s.db,t);let o;r&&(o=new i.CSOTTimeoutContext({timeoutMS:r,serverSelectionTimeoutMS:this.s.db.client.s.options.serverSelectionTimeoutMS}));const{deletedCount:a}=await this.s._filesCollection.deleteOne({_id:e},{timeoutMS:o?.remainingTimeMS}),c=o?.remainingTimeMS;if(null!=c&&c<=0)throw new n.MongoOperationTimeoutError(`Timed out after ${r}ms`);if(await this.s._chunksCollection.deleteMany({files_id:e},{timeoutMS:c}),0===a)throw new n.MongoRuntimeError(`File not found for id ${e}`)}find(e={},t={}){return this.s._filesCollection.find(e,t)}openDownloadStreamByName(e,t){let r,n={uploadDate:-1};return t&&null!=t.revision&&(t.revision>=0?(n={uploadDate:1},r=t.revision):r=-t.revision-1),new c.GridFSBucketReadStream(this.s._chunksCollection,this.s._filesCollection,this.s.options.readPreference,{filename:e},{timeoutMS:this.s.options.timeoutMS,...t,sort:n,skip:r})}async rename(e,t,r){const o={_id:e},i={$set:{filename:t}},{matchedCount:s}=await this.s._filesCollection.updateOne(o,i,r);if(0===s)throw new n.MongoRuntimeError(`File with id ${e} not found`)}async drop(e){const{timeoutMS:t}=(0,s.resolveOptions)(this.s.db,e);let r;if(t&&(r=new i.CSOTTimeoutContext({timeoutMS:t,serverSelectionTimeoutMS:this.s.db.client.s.options.serverSelectionTimeoutMS})),r){await this.s._filesCollection.drop({timeoutMS:r.remainingTimeMS});const e=r.getRemainingTimeMSOrThrow(`Timed out after ${t}ms`);await this.s._chunksCollection.drop({timeoutMS:e})}else await this.s._filesCollection.drop(),await this.s._chunksCollection.drop()}}t.GridFSBucket=d,d.INDEX="index"},75080:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toUTF8=t.getBigInt64LE=t.getFloat64LE=t.getInt32LE=t.UUID=t.Timestamp=t.serialize=t.ObjectId=t.MinKey=t.MaxKey=t.Long=t.Int32=t.EJSON=t.Double=t.deserialize=t.Decimal128=t.DBRef=t.Code=t.calculateObjectSize=t.BSONType=t.BSONSymbol=t.BSONRegExp=t.BSONError=t.BSON=t.Binary=void 0,t.parseToElementsToArray=function(e,t){const r=n.BSON.onDemand.parseToElements(e,t);return Array.isArray(r)?r:[...r]},t.pluckBSONSerializeOptions=function(e){const{fieldsAsRaw:t,useBigInt64:r,promoteValues:n,promoteBuffers:o,promoteLongs:i,serializeFunctions:s,ignoreUndefined:a,bsonRegExp:c,raw:u,enableUtf8Validation:l}=e;return{fieldsAsRaw:t,useBigInt64:r,promoteValues:n,promoteBuffers:o,promoteLongs:i,serializeFunctions:s,ignoreUndefined:a,bsonRegExp:c,raw:u,enableUtf8Validation:l}},t.resolveBSONOptions=function(e,t){const r=t?.bsonOptions;return{raw:e?.raw??r?.raw??!1,useBigInt64:e?.useBigInt64??r?.useBigInt64??!1,promoteLongs:e?.promoteLongs??r?.promoteLongs??!0,promoteValues:e?.promoteValues??r?.promoteValues??!0,promoteBuffers:e?.promoteBuffers??r?.promoteBuffers??!1,ignoreUndefined:e?.ignoreUndefined??r?.ignoreUndefined??!1,bsonRegExp:e?.bsonRegExp??r?.bsonRegExp??!1,serializeFunctions:e?.serializeFunctions??r?.serializeFunctions??!1,fieldsAsRaw:e?.fieldsAsRaw??r?.fieldsAsRaw??{},enableUtf8Validation:e?.enableUtf8Validation??r?.enableUtf8Validation??!0}},t.parseUtf8ValidationOption=function(e){const t=e?.enableUtf8Validation;return!1===t?{utf8:!1}:{utf8:{writeErrors:!1}}};const n=r(62444);var o=r(62444);Object.defineProperty(t,"Binary",{enumerable:!0,get:function(){return o.Binary}}),Object.defineProperty(t,"BSON",{enumerable:!0,get:function(){return o.BSON}}),Object.defineProperty(t,"BSONError",{enumerable:!0,get:function(){return o.BSONError}}),Object.defineProperty(t,"BSONRegExp",{enumerable:!0,get:function(){return o.BSONRegExp}}),Object.defineProperty(t,"BSONSymbol",{enumerable:!0,get:function(){return o.BSONSymbol}}),Object.defineProperty(t,"BSONType",{enumerable:!0,get:function(){return o.BSONType}}),Object.defineProperty(t,"calculateObjectSize",{enumerable:!0,get:function(){return o.calculateObjectSize}}),Object.defineProperty(t,"Code",{enumerable:!0,get:function(){return o.Code}}),Object.defineProperty(t,"DBRef",{enumerable:!0,get:function(){return o.DBRef}}),Object.defineProperty(t,"Decimal128",{enumerable:!0,get:function(){return o.Decimal128}}),Object.defineProperty(t,"deserialize",{enumerable:!0,get:function(){return o.deserialize}}),Object.defineProperty(t,"Double",{enumerable:!0,get:function(){return o.Double}}),Object.defineProperty(t,"EJSON",{enumerable:!0,get:function(){return o.EJSON}}),Object.defineProperty(t,"Int32",{enumerable:!0,get:function(){return o.Int32}}),Object.defineProperty(t,"Long",{enumerable:!0,get:function(){return o.Long}}),Object.defineProperty(t,"MaxKey",{enumerable:!0,get:function(){return o.MaxKey}}),Object.defineProperty(t,"MinKey",{enumerable:!0,get:function(){return o.MinKey}}),Object.defineProperty(t,"ObjectId",{enumerable:!0,get:function(){return o.ObjectId}}),Object.defineProperty(t,"serialize",{enumerable:!0,get:function(){return o.serialize}}),Object.defineProperty(t,"Timestamp",{enumerable:!0,get:function(){return o.Timestamp}}),Object.defineProperty(t,"UUID",{enumerable:!0,get:function(){return o.UUID}}),t.getInt32LE=n.BSON.onDemand.NumberUtils.getInt32LE,t.getFloat64LE=n.BSON.onDemand.NumberUtils.getFloat64LE,t.getBigInt64LE=n.BSON.onDemand.NumberUtils.getBigInt64LE,t.toUTF8=n.BSON.onDemand.ByteUtils.toUTF8},75725:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ClientBulkWriteCursorResponse=t.ExplainedCursorResponse=t.CursorResponse=t.MongoDBResponse=void 0,t.isErrorResponse=c;const n=r(75080),o=r(17562),i=r(145),s=r(68746),a={type:0,nameOffset:1,nameLength:2,offset:3,length:4};function c(e,t){for(let r=0;r<t.length;r++){const n=t[r];if(2===n[a.nameLength]){const t=n[a.nameOffset];if(111===e[t]&&107===e[t+1]){const t=n[a.offset],r=n[a.length];for(let n=t;n<t+r;n++)if(0!==e[n])return!1;return!0}}}return!0}class u extends s.OnDemandDocument{get(e,t,r){try{return super.get(e,t,r)}catch(e){throw new o.MongoUnexpectedServerResponseError(e.message,{cause:e})}}static is(e){return e instanceof u}static make(e){const t=(0,n.parseToElementsToArray)(e,0);return c(e,t)?new u(e,0,!1,t):new this(e,0,!1,t)}get isMaxTimeExpiredError(){if(0===this.ok&&this.code===o.MONGODB_ERROR_CODES.MaxTimeMSExpired)return!0;if(0===this.ok)return!1;if(this.get("writeConcernError",n.BSONType.object)?.getNumber("code")===o.MONGODB_ERROR_CODES.MaxTimeMSExpired)return!0;const e=this.get("writeErrors",n.BSONType.array);if(e?.size())for(let t=0;t<e.size();t++)if(e.get(t,n.BSONType.object)?.getNumber("code")===o.MONGODB_ERROR_CODES.MaxTimeMSExpired)return!0;return!1}get recoveryToken(){return this.get("recoveryToken",n.BSONType.object)?.toObject({promoteValues:!1,promoteLongs:!1,promoteBuffers:!1,validation:{utf8:!0}})??null}get atClusterTime(){return this.get("cursor",n.BSONType.object)?.get("atClusterTime",n.BSONType.timestamp)??this.get("atClusterTime",n.BSONType.timestamp)}get operationTime(){return this.get("operationTime",n.BSONType.timestamp)}get ok(){return this.getNumber("ok")?1:0}get $err(){return this.get("$err",n.BSONType.string)}get errmsg(){return this.get("errmsg",n.BSONType.string)}get code(){return this.getNumber("code")}get $clusterTime(){if(!("clusterTime"in this)){const e=this.get("$clusterTime",n.BSONType.object);if(null==e)return this.clusterTime=null,null;const t=e.get("clusterTime",n.BSONType.timestamp,!0),r=e.get("signature",n.BSONType.object)?.toObject();this.clusterTime={clusterTime:t,signature:r}}return this.clusterTime??null}toObject(e){const t={...(0,n.pluckBSONSerializeOptions)(e??{}),validation:(0,n.parseUtf8ValidationOption)(e)};return super.toObject(t)}}t.MongoDBResponse=u,u.empty=new u(new Uint8Array([13,0,0,0,16,111,107,0,1,0,0,0,0]));class l extends u{constructor(){super(...arguments),this._batch=null,this.iterated=0,this._encryptedBatch=null}static get emptyGetMore(){return new l((0,n.serialize)({ok:1,cursor:{id:0n,nextBatch:[]}}))}static is(e){return e instanceof l||e===l.emptyGetMore}get cursor(){return this.get("cursor",n.BSONType.object,!0)}get id(){try{return n.Long.fromBigInt(this.cursor.get("id",n.BSONType.long,!0))}catch(e){throw new o.MongoUnexpectedServerResponseError(e.message,{cause:e})}}get ns(){const e=this.cursor.get("ns",n.BSONType.string);return null!=e?(0,i.ns)(e):null}get length(){return Math.max(this.batchSize-this.iterated,0)}get encryptedBatch(){if(null==this.encryptedResponse)return null;if(null!=this._encryptedBatch)return this._encryptedBatch;const e=this.encryptedResponse?.get("cursor",n.BSONType.object);if(e?.has("firstBatch"))this._encryptedBatch=e.get("firstBatch",n.BSONType.array,!0);else{if(!e?.has("nextBatch"))throw new o.MongoUnexpectedServerResponseError("Cursor document did not contain a batch");this._encryptedBatch=e.get("nextBatch",n.BSONType.array,!0)}return this._encryptedBatch}get batch(){if(null!=this._batch)return this._batch;const e=this.cursor;if(e.has("firstBatch"))this._batch=e.get("firstBatch",n.BSONType.array,!0);else{if(!e.has("nextBatch"))throw new o.MongoUnexpectedServerResponseError("Cursor document did not contain a batch");this._batch=e.get("nextBatch",n.BSONType.array,!0)}return this._batch}get batchSize(){return this.batch?.size()}get postBatchResumeToken(){return this.cursor.get("postBatchResumeToken",n.BSONType.object)?.toObject({promoteValues:!1,promoteLongs:!1,promoteBuffers:!1,validation:{utf8:!0}})??null}shift(e){if(this.iterated>=this.batchSize)return null;const t=this.batch.get(this.iterated,n.BSONType.object,!0)??null,r=this.encryptedBatch?.get(this.iterated,n.BSONType.object,!0)??null;if(this.iterated+=1,e?.raw)return t.toBytes();{const n=t.toObject(e);return r&&(0,i.decorateDecryptionResult)(n,r.toObject(e),!0),n}}clear(){this.iterated=this.batchSize}}t.CursorResponse=l,t.ExplainedCursorResponse=class extends l{constructor(){super(...arguments),this.isExplain=!0,this._length=1}get id(){return n.Long.fromBigInt(0n)}get batchSize(){return 0}get ns(){return null}get length(){return this._length}shift(e){return 0===this._length?null:(this._length-=1,this.toObject(e))}},t.ClientBulkWriteCursorResponse=class extends l{get insertedCount(){return this.get("nInserted",n.BSONType.int,!0)}get upsertedCount(){return this.get("nUpserted",n.BSONType.int,!0)}get matchedCount(){return this.get("nMatched",n.BSONType.int,!0)}get modifiedCount(){return this.get("nModified",n.BSONType.int,!0)}get deletedCount(){return this.get("nDeleted",n.BSONType.int,!0)}get writeConcernError(){return this.get("writeConcernError",n.BSONType.object,!1)}}},75755:(e,t,r)=>{var n=r(65994).e;Object.defineProperty(t,"__esModule",{value:!0}),t.ConnectionPool=t.PoolState=void 0;const o=r(37668),i=r(91869),s=r(17562),a=r(4642),c=r(7799),u=r(145),l=r(87758),d=r(71470),h=r(287),p=r(76013),m=r(55741);t.PoolState=Object.freeze({paused:"paused",ready:"ready",closed:"closed"});class f extends a.TypedEventEmitter{constructor(e,r){if(super(),this.on("error",u.noop),this.options=Object.freeze({connectionType:d.Connection,...r,maxPoolSize:r.maxPoolSize??100,minPoolSize:r.minPoolSize??0,maxConnecting:r.maxConnecting??2,maxIdleTimeMS:r.maxIdleTimeMS??0,waitQueueTimeoutMS:r.waitQueueTimeoutMS??0,minPoolSizeCheckFrequencyMS:r.minPoolSizeCheckFrequencyMS??100,autoEncrypter:r.autoEncrypter}),this.options.minPoolSize>this.options.maxPoolSize)throw new s.MongoInvalidArgumentError("Connection pool minimum size must not be greater than maximum pool size");this.poolState=t.PoolState.paused,this.server=e,this.connections=new u.List,this.pending=0,this.checkedOut=new Set,this.minPoolSizeTimer=void 0,this.generation=0,this.serviceGenerations=new Map,this.connectionCounter=(0,u.makeCounter)(1),this.cancellationToken=new a.CancellationToken,this.cancellationToken.setMaxListeners(1/0),this.waitQueue=new u.List,this.metrics=new m.ConnectionPoolMetrics,this.processingWaitQueue=!1,this.mongoLogger=this.server.topology.client?.mongoLogger,this.component="connection",n.nextTick((()=>{this.emitAndLog(f.CONNECTION_POOL_CREATED,new h.ConnectionPoolCreatedEvent(this))}))}get address(){return this.options.hostAddress.toString()}get closed(){return this.poolState===t.PoolState.closed}get totalConnectionCount(){return this.availableConnectionCount+this.pendingConnectionCount+this.currentCheckedOutCount}get availableConnectionCount(){return this.connections.length}get pendingConnectionCount(){return this.pending}get currentCheckedOutCount(){return this.checkedOut.size}get waitQueueSize(){return this.waitQueue.length}get loadBalanced(){return this.options.loadBalanced}get serverError(){return this.server.description.error}get checkedOutConnections(){return this.checkedOut}waitQueueErrorMetrics(){return this.metrics.info(this.options.maxPoolSize)}ready(){this.poolState===t.PoolState.paused&&(this.poolState=t.PoolState.ready,this.emitAndLog(f.CONNECTION_POOL_READY,new h.ConnectionPoolReadyEvent(this)),(0,o.clearTimeout)(this.minPoolSizeTimer),this.ensureMinPoolSize())}async checkOut(e){const t=(0,u.now)();this.emitAndLog(f.CONNECTION_CHECK_OUT_STARTED,new h.ConnectionCheckOutStartedEvent(this));const{promise:r,resolve:o,reject:i}=(0,u.promiseWithResolvers)(),a=e.timeoutContext.connectionCheckoutTimeout,l={resolve:o,reject:i,cancelled:!1,checkoutTime:t},d=(0,u.addAbortListener)(e.signal,(function(){l.cancelled=!0,i(this.reason)}));this.waitQueue.push(l),n.nextTick((()=>this.processWaitQueue()));try{return a?.throwIfExpired(),await(a?Promise.race([r,a]):r)}catch(t){if(c.TimeoutError.is(t)){a?.clear(),l.cancelled=!0,this.emitAndLog(f.CONNECTION_CHECK_OUT_FAILED,new h.ConnectionCheckOutFailedEvent(this,"timeout",l.checkoutTime));const t=new p.WaitQueueTimeoutError(this.loadBalanced?this.waitQueueErrorMetrics():"Timed out while checking out a connection from connection pool",this.address);if(e.timeoutContext.csotEnabled())throw new s.MongoOperationTimeoutError("Timed out during connection checkout",{cause:t});throw t}throw t}finally{d?.[u.kDispose](),a?.clear()}}checkIn(e){if(!this.checkedOut.has(e))return;const t=this.closed,r=this.connectionIsStale(e),o=!!(t||r||e.closed);if(o||(e.markAvailable(),this.connections.unshift(e)),this.checkedOut.delete(e),this.emitAndLog(f.CONNECTION_CHECKED_IN,new h.ConnectionCheckedInEvent(this,e)),o){const r=e.closed?"error":t?"poolClosed":"stale";this.destroyConnection(e,r)}n.nextTick((()=>this.processWaitQueue()))}clear(e={}){if(this.closed)return;if(this.loadBalanced){const{serviceId:t}=e;if(!t)throw new s.MongoRuntimeError("ConnectionPool.clear() called in load balanced mode with no serviceId.");const r=t.toHexString(),n=this.serviceGenerations.get(r);if(null==n)throw new s.MongoRuntimeError("Service generations are required in load balancer mode.");return this.serviceGenerations.set(r,n+1),void this.emitAndLog(f.CONNECTION_POOL_CLEARED,new h.ConnectionPoolClearedEvent(this,{serviceId:t}))}const r=e.interruptInUseConnections??!1,o=this.generation;this.generation+=1;const i=this.poolState===t.PoolState.paused;this.poolState=t.PoolState.paused,this.clearMinPoolSizeTimer(),i||this.emitAndLog(f.CONNECTION_POOL_CLEARED,new h.ConnectionPoolClearedEvent(this,{interruptInUseConnections:r})),r&&n.nextTick((()=>this.interruptInUseConnections(o))),this.processWaitQueue()}interruptInUseConnections(e){for(const t of this.checkedOut)t.generation<=e&&t.onError(new p.PoolClearedOnNetworkError(this))}closeCheckedOutConnections(){for(const e of this.checkedOut)e.onError(new s.MongoClientClosedError)}close(){if(!this.closed){this.cancellationToken.emit("cancel"),"function"==typeof this.connectionCounter.return&&this.connectionCounter.return(void 0),this.poolState=t.PoolState.closed,this.clearMinPoolSizeTimer(),this.processWaitQueue();for(const e of this.connections)this.emitAndLog(f.CONNECTION_CLOSED,new h.ConnectionClosedEvent(this,e,"poolClosed")),e.destroy();this.connections.clear(),this.emitAndLog(f.CONNECTION_POOL_CLOSED,new h.ConnectionPoolClosedEvent(this))}}async reauthenticate(e){const t=e.authContext;if(!t)throw new s.MongoRuntimeError("No auth context found on connection.");const r=t.credentials;if(!r)throw new s.MongoMissingCredentialsError("Connection is missing credentials when asked to reauthenticate");const n=r.resolveAuthMechanism(e.hello),o=this.server.topology.client.s.authProviders.getOrCreateProvider(n.mechanism,n.mechanismProperties);if(!o)throw new s.MongoMissingCredentialsError(`Reauthenticate failed due to no auth provider for ${r.mechanism}`);await o.reauth(t)}clearMinPoolSizeTimer(){const e=this.minPoolSizeTimer;e&&(0,o.clearTimeout)(e)}destroyConnection(e,t){this.emitAndLog(f.CONNECTION_CLOSED,new h.ConnectionClosedEvent(this,e,t)),e.destroy()}connectionIsStale(e){const t=e.serviceId;if(this.loadBalanced&&t){const r=t.toHexString(),n=this.serviceGenerations.get(r);return e.generation!==n}return e.generation!==this.generation}connectionIsIdle(e){return!!(this.options.maxIdleTimeMS&&e.idleTime>this.options.maxIdleTimeMS)}destroyConnectionIfPerished(e){const t=this.connectionIsStale(e),r=this.connectionIsIdle(e);if(!t&&!r&&!e.closed)return!1;const n=e.closed?"error":t?"stale":"idle";return this.destroyConnection(e,n),!0}createConnection(e){const r={...this.options,id:this.connectionCounter.next().value,generation:this.generation,cancellationToken:this.cancellationToken,mongoLogger:this.mongoLogger,authProviders:this.server.topology.client.s.authProviders,extendedMetadata:this.server.topology.client.options.extendedMetadata};this.pending++;const n=(0,u.now)();this.emitAndLog(f.CONNECTION_CREATED,new h.ConnectionCreatedEvent(this,{id:r.id})),(0,l.connect)(r).then((r=>{if(this.poolState!==t.PoolState.ready)return this.pending--,r.destroy(),void e(this.closed?new p.PoolClosedError(this):new p.PoolClearedError(this));for(const e of[...i.APM_EVENTS,d.Connection.CLUSTER_TIME_RECEIVED])r.on(e,(t=>this.emit(e,t)));if(this.loadBalanced){r.on(d.Connection.PINNED,(e=>this.metrics.markPinned(e))),r.on(d.Connection.UNPINNED,(e=>this.metrics.markUnpinned(e)));const e=r.serviceId;if(e){let t;const n=e.toHexString();(t=this.serviceGenerations.get(n))?r.generation=t:(this.serviceGenerations.set(n,0),r.generation=0)}}r.markAvailable(),this.emitAndLog(f.CONNECTION_READY,new h.ConnectionReadyEvent(this,r,n)),this.pending--,e(void 0,r)}),(t=>{this.pending--,this.server.handleError(t),this.emitAndLog(f.CONNECTION_CLOSED,new h.ConnectionClosedEvent(this,{id:r.id,serviceId:void 0},"error",t)),(t instanceof s.MongoNetworkError||t instanceof s.MongoServerError)&&(t.connectionGeneration=r.generation),e(t??new s.MongoRuntimeError("Connection creation failed without error"))}))}ensureMinPoolSize(){const e=this.options.minPoolSize;this.poolState===t.PoolState.ready&&(this.connections.prune((e=>this.destroyConnectionIfPerished(e))),this.totalConnectionCount<e&&this.pendingConnectionCount<this.options.maxConnecting?this.createConnection(((e,r)=>{!e&&r&&(this.connections.push(r),n.nextTick((()=>this.processWaitQueue()))),this.poolState===t.PoolState.ready&&((0,o.clearTimeout)(this.minPoolSizeTimer),this.minPoolSizeTimer=(0,o.setTimeout)((()=>this.ensureMinPoolSize()),this.options.minPoolSizeCheckFrequencyMS))})):((0,o.clearTimeout)(this.minPoolSizeTimer),this.minPoolSizeTimer=(0,o.setTimeout)((()=>this.ensureMinPoolSize()),this.options.minPoolSizeCheckFrequencyMS)))}processWaitQueue(){if(this.processingWaitQueue)return;for(this.processingWaitQueue=!0;this.waitQueueSize;){const e=this.waitQueue.first();if(!e){this.waitQueue.shift();continue}if(e.cancelled){this.waitQueue.shift();continue}if(this.poolState!==t.PoolState.ready){const t=this.closed?"poolClosed":"connectionError",r=this.closed?new p.PoolClosedError(this):new p.PoolClearedError(this);this.emitAndLog(f.CONNECTION_CHECK_OUT_FAILED,new h.ConnectionCheckOutFailedEvent(this,t,e.checkoutTime,r)),this.waitQueue.shift(),e.reject(r);continue}if(!this.availableConnectionCount)break;const r=this.connections.shift();if(!r)break;this.destroyConnectionIfPerished(r)||(this.checkedOut.add(r),this.emitAndLog(f.CONNECTION_CHECKED_OUT,new h.ConnectionCheckedOutEvent(this,r,e.checkoutTime)),this.waitQueue.shift(),e.resolve(r))}const{maxPoolSize:e,maxConnecting:r}=this.options;for(;this.waitQueueSize>0&&this.pendingConnectionCount<r&&(0===e||this.totalConnectionCount<e);){const e=this.waitQueue.shift();e&&!e.cancelled&&this.createConnection(((t,r)=>{e.cancelled?!t&&r&&this.connections.push(r):t?(this.emitAndLog(f.CONNECTION_CHECK_OUT_FAILED,new h.ConnectionCheckOutFailedEvent(this,"connectionError",e.checkoutTime,t)),e.reject(t)):r&&(this.checkedOut.add(r),this.emitAndLog(f.CONNECTION_CHECKED_OUT,new h.ConnectionCheckedOutEvent(this,r,e.checkoutTime)),e.resolve(r)),n.nextTick((()=>this.processWaitQueue()))}))}this.processingWaitQueue=!1}}t.ConnectionPool=f,f.CONNECTION_POOL_CREATED=i.CONNECTION_POOL_CREATED,f.CONNECTION_POOL_CLOSED=i.CONNECTION_POOL_CLOSED,f.CONNECTION_POOL_CLEARED=i.CONNECTION_POOL_CLEARED,f.CONNECTION_POOL_READY=i.CONNECTION_POOL_READY,f.CONNECTION_CREATED=i.CONNECTION_CREATED,f.CONNECTION_READY=i.CONNECTION_READY,f.CONNECTION_CLOSED=i.CONNECTION_CLOSED,f.CONNECTION_CHECK_OUT_STARTED=i.CONNECTION_CHECK_OUT_STARTED,f.CONNECTION_CHECK_OUT_FAILED=i.CONNECTION_CHECK_OUT_FAILED,f.CONNECTION_CHECKED_OUT=i.CONNECTION_CHECKED_OUT,f.CONNECTION_CHECKED_IN=i.CONNECTION_CHECKED_IN},76013:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WaitQueueTimeoutError=t.PoolClearedOnNetworkError=t.PoolClearedError=t.PoolClosedError=void 0;const n=r(17562);class o extends n.MongoDriverError{constructor(e){super("Attempted to check out a connection from closed connection pool"),this.address=e.address}get name(){return"MongoPoolClosedError"}}t.PoolClosedError=o;class i extends n.MongoNetworkError{constructor(e,t){super(t||`Connection pool for ${e.address} was cleared because another operation failed with: "${e.serverError?.message}"`,e.serverError?{cause:e.serverError}:void 0),this.address=e.address,this.addErrorLabel(n.MongoErrorLabel.PoolRequstedRetry)}get name(){return"MongoPoolClearedError"}}t.PoolClearedError=i,t.PoolClearedOnNetworkError=class extends i{constructor(e){super(e,`Connection to ${e.address} interrupted due to server monitor timeout`)}get name(){return"PoolClearedOnNetworkError"}};class s extends n.MongoDriverError{constructor(e,t){super(e),this.address=t}get name(){return"MongoWaitQueueTimeoutError"}}t.WaitQueueTimeoutError=s},78130:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CommandOperation=void 0;const n=r(17562),o=r(36411),i=r(28541),s=r(145),a=r(40012),c=r(35394);class u extends c.AbstractOperation{constructor(e,t){super(t),this.options=t??{};const r=t?.dbName||t?.authdb;if(this.ns=r?new s.MongoDBNamespace(r,"$cmd"):e?e.s.namespace.withCollection("$cmd"):new s.MongoDBNamespace("admin","$cmd"),this.readConcern=i.ReadConcern.fromOptions(t),this.writeConcern=a.WriteConcern.fromOptions(t),this.hasAspect(c.Aspect.EXPLAINABLE))this.explain=o.Explain.fromOptions(t),this.explain&&(0,o.validateExplainTimeoutOptions)(this.options,this.explain);else if(null!=t?.explain)throw new n.MongoInvalidArgumentError('Option "explain" is not supported on this command')}get canRetryWrite(){return this.hasAspect(c.Aspect.EXPLAINABLE)?null==this.explain:super.canRetryWrite}buildOptions(e){return{...this.options,...this.bsonOptions,timeoutContext:e,readPreference:this.readPreference,session:this.session}}buildCommand(e,t){const r=this.buildCommandDocument(e,t),n=this.session&&this.session.inTransaction();return this.readConcern&&(0,s.commandSupportsReadConcern)(r)&&!n&&Object.assign(r,{readConcern:this.readConcern}),this.writeConcern&&this.hasAspect(c.Aspect.WRITE_OPERATION)&&!n&&a.WriteConcern.apply(r,this.writeConcern),this.options.collation&&"object"==typeof this.options.collation&&!this.hasAspect(c.Aspect.SKIP_COLLATION)&&Object.assign(r,{collation:this.options.collation}),"number"==typeof this.options.maxTimeMS&&(r.maxTimeMS=this.options.maxTimeMS),this.hasAspect(c.Aspect.EXPLAINABLE)&&this.explain?(0,o.decorateWithExplain)(r,this.explain):r}}t.CommandOperation=u},79790:(e,t,r)=>{var n=r(9606).URL;Object.defineProperty(t,"__esModule",{value:!0}),t.tokenCache=t.AzureCredentialCache=t.AZURE_BASE_URL=void 0,t.addAzureParams=c,t.prepareRequest=u,t.fetchAzureKMSToken=l,t.loadAzureCredentials=async function(e){return{...e,azure:await t.tokenCache.getToken()}};const o=r(17562),i=r(145),s=r(86981);t.AZURE_BASE_URL="http://169.254.169.254/metadata/identity/oauth2/token?";class a{constructor(){this.cachedToken=null}async getToken(){return(null==this.cachedToken||this.needsRefresh(this.cachedToken))&&(this.cachedToken=await this._getToken()),{accessToken:this.cachedToken.accessToken}}needsRefresh(e){return e.expiresOnTimestamp-Date.now()<=6e3}resetCache(){this.cachedToken=null}_getToken(){return l()}}function c(e,t,r){return e.searchParams.append("api-version","2018-02-01"),e.searchParams.append("resource",t),r&&e.searchParams.append("client_id",r),e}function u(e){const r=new n(e.url?.toString()??t.AZURE_BASE_URL);return c(r,"https://vault.azure.net"),{headers:{...e.headers,"Content-Type":"application/json",Metadata:!0},url:r}}async function l(e={}){const{headers:t,url:r}=u(e);try{const e=await(0,i.get)(r,{headers:t});return await async function(e){const{status:t,body:r}=e,n=(()=>{try{return JSON.parse(r)}catch{throw new s.MongoCryptAzureKMSRequestError("Malformed JSON body in GET request.")}})();if(200!==t)throw new s.MongoCryptAzureKMSRequestError("Unable to complete request.",n);if(!n.access_token)throw new s.MongoCryptAzureKMSRequestError("Malformed response body - missing field `access_token`.");if(!n.expires_in)throw new s.MongoCryptAzureKMSRequestError("Malformed response body - missing field `expires_in`.");const o=1e3*Number(n.expires_in);if(Number.isNaN(o))throw new s.MongoCryptAzureKMSRequestError("Malformed response body - unable to parse int from `expires_in` field.");return{accessToken:n.access_token,expiresOnTimestamp:Date.now()+o}}(e)}catch(e){if(e instanceof o.MongoNetworkTimeoutError)throw new s.MongoCryptAzureKMSRequestError(`[Azure KMS] ${e.message}`);throw e}}t.AzureCredentialCache=a,t.tokenCache=new a},80890:(e,t,r)=>{var n=r(65994).e;Object.defineProperty(t,"__esModule",{value:!0}),t.callback=void 0;const o=r(65981),i="AZURE_FEDERATED_TOKEN_FILE",s="AWS_WEB_IDENTITY_TOKEN_FILE";t.callback=async()=>{let e;return e=n.env[i]?n.env[i]:n.env[s]?n.env[s]:"/var/run/secrets/kubernetes.io/serviceaccount/token",{accessToken:await(0,o.readFile)(e,"utf8")}}},81892:e=>{e.exports=JSON.parse('{"2.16.840.1.101.3.4.1.1":"aes-128-ecb","2.16.840.1.101.3.4.1.2":"aes-128-cbc","2.16.840.1.101.3.4.1.3":"aes-128-ofb","2.16.840.1.101.3.4.1.4":"aes-128-cfb","2.16.840.1.101.3.4.1.21":"aes-192-ecb","2.16.840.1.101.3.4.1.22":"aes-192-cbc","2.16.840.1.101.3.4.1.23":"aes-192-ofb","2.16.840.1.101.3.4.1.24":"aes-192-cfb","2.16.840.1.101.3.4.1.41":"aes-256-ecb","2.16.840.1.101.3.4.1.42":"aes-256-cbc","2.16.840.1.101.3.4.1.43":"aes-256-ofb","2.16.840.1.101.3.4.1.44":"aes-256-cfb"}')},82630:e=>{var t=1e3,r=60*t,n=60*r,o=24*n,i=7*o;function s(e,t,r,n){var o=t>=1.5*r;return Math.round(e/r)+" "+n+(o?"s":"")}e.exports=function(e,a){a=a||{};var c,u,l=typeof e;if("string"===l&&e.length>0)return function(e){if(!((e=String(e)).length>100)){var s=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(s){var a=parseFloat(s[1]);switch((s[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*a;case"weeks":case"week":case"w":return a*i;case"days":case"day":case"d":return a*o;case"hours":case"hour":case"hrs":case"hr":case"h":return a*n;case"minutes":case"minute":case"mins":case"min":case"m":return a*r;case"seconds":case"second":case"secs":case"sec":case"s":return a*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return a;default:return}}}}(e);if("number"===l&&isFinite(e))return a.long?(c=e,(u=Math.abs(c))>=o?s(c,u,o,"day"):u>=n?s(c,u,n,"hour"):u>=r?s(c,u,r,"minute"):u>=t?s(c,u,t,"second"):c+" ms"):function(e){var i=Math.abs(e);return i>=o?Math.round(e/o)+"d":i>=n?Math.round(e/n)+"h":i>=r?Math.round(e/r)+"m":i>=t?Math.round(e/t)+"s":e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}},85759:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Transaction=t.TxnState=void 0,t.isTransactionCommand=function(e){return!(!e.commitTransaction&&!e.abortTransaction)};const n=r(17562),o=r(28541),i=r(13700),s=r(40012);t.TxnState=Object.freeze({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"});const a={[t.TxnState.NO_TRANSACTION]:[t.TxnState.NO_TRANSACTION,t.TxnState.STARTING_TRANSACTION],[t.TxnState.STARTING_TRANSACTION]:[t.TxnState.TRANSACTION_IN_PROGRESS,t.TxnState.TRANSACTION_COMMITTED,t.TxnState.TRANSACTION_COMMITTED_EMPTY,t.TxnState.TRANSACTION_ABORTED],[t.TxnState.TRANSACTION_IN_PROGRESS]:[t.TxnState.TRANSACTION_IN_PROGRESS,t.TxnState.TRANSACTION_COMMITTED,t.TxnState.TRANSACTION_ABORTED],[t.TxnState.TRANSACTION_COMMITTED]:[t.TxnState.TRANSACTION_COMMITTED,t.TxnState.TRANSACTION_COMMITTED_EMPTY,t.TxnState.STARTING_TRANSACTION,t.TxnState.NO_TRANSACTION],[t.TxnState.TRANSACTION_ABORTED]:[t.TxnState.STARTING_TRANSACTION,t.TxnState.NO_TRANSACTION],[t.TxnState.TRANSACTION_COMMITTED_EMPTY]:[t.TxnState.TRANSACTION_COMMITTED_EMPTY,t.TxnState.NO_TRANSACTION]},c=new Set([t.TxnState.STARTING_TRANSACTION,t.TxnState.TRANSACTION_IN_PROGRESS]),u=new Set([t.TxnState.TRANSACTION_COMMITTED,t.TxnState.TRANSACTION_COMMITTED_EMPTY,t.TxnState.TRANSACTION_ABORTED]);t.Transaction=class{constructor(e){e=e??{},this.state=t.TxnState.NO_TRANSACTION,this.options={};const r=s.WriteConcern.fromOptions(e);if(r){if(0===r.w)throw new n.MongoTransactionError("Transactions do not support unacknowledged write concern");this.options.writeConcern=r}e.readConcern&&(this.options.readConcern=o.ReadConcern.fromOptions(e)),e.readPreference&&(this.options.readPreference=i.ReadPreference.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 isStarting(){return this.state===t.TxnState.STARTING_TRANSACTION}get isActive(){return c.has(this.state)}get isCommitted(){return u.has(this.state)}transition(e){const r=a[this.state];if(r&&r.includes(e))return this.state=e,void(this.state!==t.TxnState.NO_TRANSACTION&&this.state!==t.TxnState.STARTING_TRANSACTION&&this.state!==t.TxnState.TRANSACTION_ABORTED||this.unpinServer());throw new n.MongoRuntimeError(`Attempted illegal state transition from [${this.state}] to [${e}]`)}pinServer(e){this.isActive&&(this._pinnedServer=e)}unpinServer(){this._pinnedServer=void 0}}},86981:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MongoCryptKMSRequestNetworkTimeoutError=t.MongoCryptAzureKMSRequestError=t.MongoCryptCreateEncryptedCollectionError=t.MongoCryptCreateDataKeyError=t.MongoCryptInvalidArgumentError=t.MongoCryptError=void 0;const n=r(17562);class o extends n.MongoError{constructor(e,t={}){super(e,t)}get name(){return"MongoCryptError"}}t.MongoCryptError=o,t.MongoCryptInvalidArgumentError=class extends o{constructor(e){super(e)}get name(){return"MongoCryptInvalidArgumentError"}},t.MongoCryptCreateDataKeyError=class extends o{constructor(e,{cause:t}){super(`Unable to complete creating data keys: ${t.message}`,{cause:t}),this.encryptedFields=e}get name(){return"MongoCryptCreateDataKeyError"}},t.MongoCryptCreateEncryptedCollectionError=class extends o{constructor(e,{cause:t}){super(`Unable to create collection: ${t.message}`,{cause:t}),this.encryptedFields=e}get name(){return"MongoCryptCreateEncryptedCollectionError"}},t.MongoCryptAzureKMSRequestError=class extends o{constructor(e,t){super(e),this.body=t}get name(){return"MongoCryptAzureKMSRequestError"}},t.MongoCryptKMSRequestNetworkTimeoutError=class extends o{get name(){return"MongoCryptKMSRequestNetworkTimeoutError"}}},87758:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.LEGAL_TCP_SOCKET_OPTIONS=t.LEGAL_TLS_SOCKET_OPTIONS=void 0,t.connect=async function(e){let t=null;try{return t=p(e,await E(e)),await m(t,e),t}catch(e){throw t?.destroy(),e}},t.makeConnection=p,t.performInitialHandshake=m,t.prepareHandshakeDocument=f,t.makeSocket=E;const n=r(26272),o=r(386),i=r(91869),s=r(8500),a=r(17562),c=r(145),u=r(31057),l=r(93065),d=r(71470),h=r(96856);function p(e,t){let r=e.connectionType??d.Connection;return e.autoEncrypter&&(r=d.CryptoConnection),new r(t,e)}async function m(e,t){const r=t.credentials;if(r&&r.mechanism!==l.AuthMechanism.MONGODB_DEFAULT&&!t.authProviders.getOrCreateProvider(r.mechanism,r.mechanismProperties))throw new a.MongoInvalidArgumentError(`AuthMechanism '${r.mechanism}' not supported`);const n=new u.AuthContext(e,r,t);e.authContext=n;const o=await f(n),s={...t,raw:!1};"number"==typeof t.connectTimeoutMS&&(s.socketTimeoutMS=t.connectTimeoutMS);const d=(new Date).getTime(),p=await async function(t,r){try{return await e.command((0,c.ns)("admin.$cmd"),t,r)}catch(e){throw e instanceof a.MongoError&&e.addErrorLabel(a.MongoErrorLabel.HandshakeError),e}}(o,s);"isWritablePrimary"in p||(p.isWritablePrimary=p[i.LEGACY_HELLO_COMMAND]),p.helloOk&&(e.helloOk=!0);const m=function(e,t){const r=Number(e.maxWireVersion),n=Number(e.minWireVersion),o=!Number.isNaN(r)&&r>=h.MIN_SUPPORTED_WIRE_VERSION,i=!Number.isNaN(n)&&n<=h.MAX_SUPPORTED_WIRE_VERSION;if(o){if(i)return null;const r=`Server at ${t.hostAddress} reports minimum wire version ${JSON.stringify(e.minWireVersion)}, but this version of the Node.js Driver requires at most ${h.MAX_SUPPORTED_WIRE_VERSION} (MongoDB ${h.MAX_SUPPORTED_SERVER_VERSION})`;return new a.MongoCompatibilityError(r)}const s=`Server at ${t.hostAddress} reports maximum wire version ${JSON.stringify(e.maxWireVersion)??0}, but this version of the Node.js Driver requires at least ${h.MIN_SUPPORTED_WIRE_VERSION} (MongoDB ${h.MIN_SUPPORTED_SERVER_VERSION})`;return new a.MongoCompatibilityError(s)}(p,t);if(m)throw m;if(t.loadBalanced&&!p.serviceId)throw new a.MongoCompatibilityError("Driver attempted to initialize in load balancing mode, but the server does not support this mode.");if(e.hello=p,e.lastHelloMS=(new Date).getTime()-d,!p.arbiterOnly&&r){n.response=p;const o=r.resolveAuthMechanism(p),i=t.authProviders.getOrCreateProvider(o.mechanism,o.mechanismProperties);if(!i)throw new a.MongoInvalidArgumentError(`No AuthProvider for ${o.mechanism} defined.`);try{await i.auth(n)}catch(t){throw t instanceof a.MongoError&&(t.addErrorLabel(a.MongoErrorLabel.HandshakeError),(0,a.needsRetryableWriteLabel)(t,p.maxWireVersion,e.description.type)&&t.addErrorLabel(a.MongoErrorLabel.RetryableWriteError)),t}}e.established=!0}async function f(e){const t=e.options,r=t.compressors?t.compressors:[],{serverApi:n}=e.connection,o=await t.extendedMetadata,s={[n?.version||!0===t.loadBalanced?"hello":i.LEGACY_HELLO_COMMAND]:1,helloOk:!0,client:o,compression:r};!0===t.loadBalanced&&(s.loadBalanced=!0);const c=e.credentials;if(c){if(c.mechanism===l.AuthMechanism.MONGODB_DEFAULT&&c.username){s.saslSupportedMechs=`${c.source}.${c.username}`;const t=e.options.authProviders.getOrCreateProvider(l.AuthMechanism.MONGODB_SCRAM_SHA256,c.mechanismProperties);if(!t)throw new a.MongoInvalidArgumentError(`No AuthProvider for ${l.AuthMechanism.MONGODB_SCRAM_SHA256} defined.`);return await t.prepare(s,e)}const t=e.options.authProviders.getOrCreateProvider(c.mechanism,c.mechanismProperties);if(!t)throw new a.MongoInvalidArgumentError(`No AuthProvider for ${c.mechanism} defined.`);return await t.prepare(s,e)}return s}function g(e){const r=e.hostAddress;if(!r)throw new a.MongoInvalidArgumentError('Option "hostAddress" is required');const n={};for(const r of t.LEGAL_TCP_SOCKET_OPTIONS)null!=e[r]&&(n[r]=e[r]);if(n.keepAliveInitialDelay??=12e4,n.keepAlive=!0,n.noDelay=e.noDelay??!0,"string"==typeof r.socketPath)return n.path=r.socketPath,n;if("string"==typeof r.host)return n.host=r.host,n.port=r.port,n;throw new a.MongoRuntimeError(`Unexpected HostAddress ${JSON.stringify(r)}`)}async function E(e){const r=e.tls??!1,i=e.connectTimeoutMS??3e4,u=e.existingSocket;let l;if(null!=e.proxyHost)return await async function(e){const t=c.HostAddress.fromHostPort(e.proxyHost??"",e.proxyPort??1080),r=await E({...e,hostAddress:t,tls:!1,proxyHost:void 0}),n=g(e);if("string"!=typeof n.host||"number"!=typeof n.port)throw new a.MongoInvalidArgumentError("Can only make Socks5 connections to TCP hosts");let o;S??=function(){if(null==S){const e=(0,s.getSocks)();if("kModuleError"in e)throw e.kModuleError;S=e}return S}();try{o=(await S.SocksClient.createConnection({existing_socket:r,timeout:e.connectTimeoutMS,command:"connect",destination:{host:n.host,port:n.port},proxy:{host:"iLoveJavaScript",port:0,type:5,userId:e.proxyUsername||void 0,password:e.proxyPassword||void 0}})).socket}catch(e){throw new a.MongoNetworkError(a.MongoError.buildErrorMessage(e),{cause:e})}return await E({...e,existingSocket:o,proxyHost:void 0})}({...e,connectTimeoutMS:i});if(r){const r=o.connect(function(e){const r=g(e);for(const n of t.LEGAL_TLS_SOCKET_OPTIONS)null!=e[n]&&(r[n]=e[n]);return e.existingSocket&&(r.socket=e.existingSocket),null==r.servername&&r.host&&!n.isIP(r.host)&&(r.servername=r.host),r}(e));"function"==typeof r.disableRenegotiation&&r.disableRenegotiation(),l=r}else l=u||n.createConnection(g(e));l.setTimeout(i);let d=null;const{promise:h,resolve:p,reject:m}=(0,c.promiseWithResolvers)();if(u)p(l);else{const t=performance.now(),n=r?"secureConnect":"connect";l.once(n,(()=>p(l))).once("error",(e=>m(new a.MongoNetworkError(a.MongoError.buildErrorMessage(e),{cause:e})))).once("timeout",(()=>{m(new a.MongoNetworkTimeoutError(`Socket '${n}' timed out after ${performance.now()-t|0}ms (connectTimeoutMS: ${i})`))})).once("close",(()=>m(new a.MongoNetworkError(`Socket closed after ${performance.now()-t|0} during connection establishment`)))),null!=e.cancellationToken&&(d=()=>m(new a.MongoNetworkError("Socket connection establishment was cancelled after "+(performance.now()-t|0))),e.cancellationToken.once("cancel",d))}try{return l=await h,l}catch(e){throw l.destroy(),e}finally{l.setTimeout(0),null!=d&&e.cancellationToken?.removeListener("cancel",d)}}t.LEGAL_TLS_SOCKET_OPTIONS=["allowPartialTrustChain","ALPNProtocols","ca","cert","checkServerIdentity","ciphers","crl","ecdhCurve","key","minDHSize","passphrase","pfx","rejectUnauthorized","secureContext","secureProtocol","servername","session"],t.LEGAL_TCP_SOCKET_OPTIONS=["autoSelectFamily","autoSelectFamilyAttemptTimeout","keepAliveInitialDelay","family","hints","localAddress","localPort","lookup"];let S=null},88536:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ProfilingLevelOperation=void 0;const n=r(75080),o=r(75725),i=r(17562),s=r(78130);class a extends o.MongoDBResponse{get was(){return this.get("was",n.BSONType.int,!0)}}class c extends s.CommandOperation{constructor(e,t){super(e,t),this.SERVER_COMMAND_RESPONSE_TYPE=a,this.options=t}get commandName(){return"profile"}buildCommandDocument(e){return{profile:-1}}handleOk(e){if(1===e.ok){const t=e.was;if(0===t)return"off";if(1===t)return"slow_only";if(2===t)return"all";throw new i.MongoUnexpectedServerResponseError(`Illegal profiling level value ${t}`)}throw new i.MongoUnexpectedServerResponseError("Error with profile command")}}t.ProfilingLevelOperation=c},88822:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AutomatedCallbackWorkflow=void 0;const n=r(17562),o=r(7799),i=r(63257),s=r(49683);class a extends s.CallbackWorkflow{constructor(e,t){super(e,t)}async execute(e,t){if(this.cache.hasAccessToken){const r=this.cache.getAccessToken();e.accessToken||(e.accessToken=r);try{return await this.finishAuthentication(e,t,r)}catch(r){if(r instanceof n.MongoError&&r.code===n.MONGODB_ERROR_CODES.AuthenticationFailed)return this.cache.removeAccessToken(),await this.execute(e,t);throw r}}const r=await this.fetchAccessToken(t);this.cache.put(r),e.accessToken=r.accessToken,await this.finishAuthentication(e,t,r.accessToken)}async fetchAccessToken(e){const t=new AbortController,r={timeoutContext:t.signal,version:i.OIDC_VERSION};e.username&&(r.username=e.username),e.mechanismProperties.TOKEN_RESOURCE&&(r.tokenAudience=e.mechanismProperties.TOKEN_RESOURCE);const a=o.Timeout.expires(s.AUTOMATED_TIMEOUT_MS);try{return await Promise.race([this.executeAndValidateCallback(r),a])}catch(e){if(o.TimeoutError.is(e))throw t.abort(),new n.MongoOIDCError(`OIDC callback timed out after ${s.AUTOMATED_TIMEOUT_MS}ms.`);throw e}finally{a.clear()}}}t.AutomatedCallbackWorkflow=a},88913:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ListCollectionsOperation=void 0;const n=r(75725),o=r(145),i=r(78130),s=r(35394);class a extends i.CommandOperation{constructor(e,t,r){super(e,r),this.SERVER_COMMAND_RESPONSE_TYPE=n.CursorResponse,this.options={...r},delete this.options.writeConcern,this.db=e,this.filter=t,this.nameOnly=!!this.options.nameOnly,this.authorizedCollections=!!this.options.authorizedCollections,"number"==typeof this.options.batchSize&&(this.batchSize=this.options.batchSize),this.SERVER_COMMAND_RESPONSE_TYPE=this.explain?n.ExplainedCursorResponse:n.CursorResponse}get commandName(){return"listCollections"}buildCommandDocument(e){const t={listCollections:1,filter:this.filter,cursor:this.batchSize?{batchSize:this.batchSize}:{},nameOnly:this.nameOnly,authorizedCollections:this.authorizedCollections};return(0,o.maxWireVersion)(e)>=9&&void 0!==this.options.comment&&(t.comment=this.options.comment),t}handleOk(e){return e}}t.ListCollectionsOperation=a,(0,s.defineAspects)(a,[s.Aspect.READ_OPERATION,s.Aspect.RETRYABLE,s.Aspect.CURSOR_CREATING])},89167:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ServerType=t.TopologyType=t.STATE_CONNECTED=t.STATE_CONNECTING=t.STATE_CLOSED=t.STATE_CLOSING=void 0,t._advanceClusterTime=function(e,t){(null==e.clusterTime||t.clusterTime.greaterThan(e.clusterTime.clusterTime))&&(e.clusterTime=t)},t.STATE_CLOSING="closing",t.STATE_CLOSED="closed",t.STATE_CONNECTING="connecting",t.STATE_CONNECTED="connected",t.TopologyType=Object.freeze({Single:"Single",ReplicaSetNoPrimary:"ReplicaSetNoPrimary",ReplicaSetWithPrimary:"ReplicaSetWithPrimary",Sharded:"Sharded",Unknown:"Unknown",LoadBalanced:"LoadBalanced"}),t.ServerType=Object.freeze({Standalone:"Standalone",Mongos:"Mongos",PossiblePrimary:"PossiblePrimary",RSPrimary:"RSPrimary",RSSecondary:"RSSecondary",RSArbiter:"RSArbiter",RSOther:"RSOther",RSGhost:"RSGhost",Unknown:"Unknown",LoadBalancer:"LoadBalancer"})},91566:(e,t,r)=>{var n=r(65994).e;Object.defineProperty(t,"__esModule",{value:!0}),t.MongoCredentials=t.DEFAULT_ALLOWED_HOSTS=void 0;const o=r(17562),i=r(95750),s=r(93065);function a(e){return e&&Array.isArray(e.saslSupportedMechs)?e.saslSupportedMechs.includes(s.AuthMechanism.MONGODB_SCRAM_SHA256)?s.AuthMechanism.MONGODB_SCRAM_SHA256:s.AuthMechanism.MONGODB_SCRAM_SHA1:s.AuthMechanism.MONGODB_SCRAM_SHA256}const c=["test","azure","gcp","k8s"],u="Auth mechanism property ALLOWED_HOSTS must be an array of strings.";t.DEFAULT_ALLOWED_HOSTS=["*.mongodb.net","*.mongodb-qa.net","*.mongodb-dev.net","*.mongodbgov.net","localhost","127.0.0.1","::1"];class l{constructor(e){this.username=e.username??"",this.password=e.password,this.source=e.source,!this.source&&e.db&&(this.source=e.db),this.mechanism=e.mechanism||s.AuthMechanism.MONGODB_DEFAULT,this.mechanismProperties=e.mechanismProperties||{},this.mechanism.match(/MONGODB-AWS/i)&&(!this.username&&n.env.AWS_ACCESS_KEY_ID&&(this.username=n.env.AWS_ACCESS_KEY_ID),!this.password&&n.env.AWS_SECRET_ACCESS_KEY&&(this.password=n.env.AWS_SECRET_ACCESS_KEY),null==this.mechanismProperties.AWS_SESSION_TOKEN&&null!=n.env.AWS_SESSION_TOKEN&&(this.mechanismProperties={...this.mechanismProperties,AWS_SESSION_TOKEN:n.env.AWS_SESSION_TOKEN})),this.mechanism!==s.AuthMechanism.MONGODB_OIDC||this.mechanismProperties.ALLOWED_HOSTS||(this.mechanismProperties={...this.mechanismProperties,ALLOWED_HOSTS:t.DEFAULT_ALLOWED_HOSTS}),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 l({username:this.username,password:this.password,source:this.source,mechanism:a(e),mechanismProperties:this.mechanismProperties}):this}validate(){if((this.mechanism===s.AuthMechanism.MONGODB_GSSAPI||this.mechanism===s.AuthMechanism.MONGODB_PLAIN||this.mechanism===s.AuthMechanism.MONGODB_SCRAM_SHA1||this.mechanism===s.AuthMechanism.MONGODB_SCRAM_SHA256)&&!this.username)throw new o.MongoMissingCredentialsError(`Username required for mechanism '${this.mechanism}'`);if(this.mechanism===s.AuthMechanism.MONGODB_OIDC){if(this.username&&this.mechanismProperties.ENVIRONMENT&&"azure"!==this.mechanismProperties.ENVIRONMENT)throw new o.MongoInvalidArgumentError(`username and ENVIRONMENT '${this.mechanismProperties.ENVIRONMENT}' may not be used together for mechanism '${this.mechanism}'.`);if(this.username&&this.password)throw new o.MongoInvalidArgumentError(`No password is allowed in ENVIRONMENT '${this.mechanismProperties.ENVIRONMENT}' for '${this.mechanism}'.`);if(("azure"===this.mechanismProperties.ENVIRONMENT||"gcp"===this.mechanismProperties.ENVIRONMENT)&&!this.mechanismProperties.TOKEN_RESOURCE)throw new o.MongoInvalidArgumentError("TOKEN_RESOURCE must be set in the auth mechanism properties when ENVIRONMENT is azure or gcp.");if(this.mechanismProperties.ENVIRONMENT&&!c.includes(this.mechanismProperties.ENVIRONMENT))throw new o.MongoInvalidArgumentError(`Currently only a ENVIRONMENT in ${c.join(",")} is supported for mechanism '${this.mechanism}'.`);if(!this.mechanismProperties.ENVIRONMENT&&!this.mechanismProperties.OIDC_CALLBACK&&!this.mechanismProperties.OIDC_HUMAN_CALLBACK)throw new o.MongoInvalidArgumentError(`Either a ENVIRONMENT, OIDC_CALLBACK, or OIDC_HUMAN_CALLBACK must be specified for mechanism '${this.mechanism}'.`);if(this.mechanismProperties.ALLOWED_HOSTS){const e=this.mechanismProperties.ALLOWED_HOSTS;if(!Array.isArray(e))throw new o.MongoInvalidArgumentError(u);for(const t of e)if("string"!=typeof t)throw new o.MongoInvalidArgumentError(u)}}if(s.AUTH_MECHS_AUTH_SRC_EXTERNAL.has(this.mechanism)&&null!=this.source&&"$external"!==this.source)throw new o.MongoAPIError(`Invalid source '${this.source}' for mechanism '${this.mechanism}' specified.`);if(this.mechanism===s.AuthMechanism.MONGODB_PLAIN&&null==this.source)throw new o.MongoAPIError("PLAIN Authentication Mechanism needs an auth source");if(this.mechanism===s.AuthMechanism.MONGODB_X509&&null!=this.password){if(""===this.password)return void Reflect.set(this,"password",void 0);throw new o.MongoAPIError("Password not allowed for mechanism MONGODB-X509")}const e=this.mechanismProperties.CANONICALIZE_HOST_NAME??!1;if(!Object.values(i.GSSAPICanonicalizationValue).includes(e))throw new o.MongoAPIError(`Invalid CANONICALIZE_HOST_NAME value: ${e}`)}static merge(e,t){return new l({username:t.username??e?.username??"",password:t.password??e?.password??"",mechanism:t.mechanism??e?.mechanism??s.AuthMechanism.MONGODB_DEFAULT,mechanismProperties:t.mechanismProperties??e?.mechanismProperties??{},source:t.source??t.db??e?.source??"admin"})}}t.MongoCredentials=l},91869:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.END=t.CHANGE=t.INIT=t.MORE=t.RESPONSE=t.SERVER_HEARTBEAT_FAILED=t.SERVER_HEARTBEAT_SUCCEEDED=t.SERVER_HEARTBEAT_STARTED=t.COMMAND_FAILED=t.COMMAND_SUCCEEDED=t.COMMAND_STARTED=t.CLUSTER_TIME_RECEIVED=t.CONNECTION_CHECKED_IN=t.CONNECTION_CHECKED_OUT=t.CONNECTION_CHECK_OUT_FAILED=t.CONNECTION_CHECK_OUT_STARTED=t.CONNECTION_CLOSED=t.CONNECTION_READY=t.CONNECTION_CREATED=t.CONNECTION_POOL_READY=t.CONNECTION_POOL_CLEARED=t.CONNECTION_POOL_CLOSED=t.CONNECTION_POOL_CREATED=t.WAITING_FOR_SUITABLE_SERVER=t.SERVER_SELECTION_SUCCEEDED=t.SERVER_SELECTION_FAILED=t.SERVER_SELECTION_STARTED=t.TOPOLOGY_DESCRIPTION_CHANGED=t.TOPOLOGY_CLOSED=t.TOPOLOGY_OPENING=t.SERVER_DESCRIPTION_CHANGED=t.SERVER_CLOSED=t.SERVER_OPENING=t.DESCRIPTION_RECEIVED=t.UNPINNED=t.PINNED=t.MESSAGE=t.ENDED=t.CLOSED=t.CONNECT=t.OPEN=t.CLOSE=t.TIMEOUT=t.ERROR=t.SYSTEM_JS_COLLECTION=t.SYSTEM_COMMAND_COLLECTION=t.SYSTEM_USER_COLLECTION=t.SYSTEM_PROFILE_COLLECTION=t.SYSTEM_INDEX_COLLECTION=t.SYSTEM_NAMESPACE_COLLECTION=void 0,t.kDecoratedKeys=t.kDecorateResult=t.LEGACY_HELLO_COMMAND_CAMEL_CASE=t.LEGACY_HELLO_COMMAND=t.MONGO_CLIENT_EVENTS=t.LOCAL_SERVER_EVENTS=t.SERVER_RELAY_EVENTS=t.APM_EVENTS=t.TOPOLOGY_EVENTS=t.CMAP_EVENTS=t.HEARTBEAT_EVENTS=t.RESUME_TOKEN_CHANGED=void 0,t.SYSTEM_NAMESPACE_COLLECTION="system.namespaces",t.SYSTEM_INDEX_COLLECTION="system.indexes",t.SYSTEM_PROFILE_COLLECTION="system.profile",t.SYSTEM_USER_COLLECTION="system.users",t.SYSTEM_COMMAND_COLLECTION="$cmd",t.SYSTEM_JS_COLLECTION="system.js",t.ERROR="error",t.TIMEOUT="timeout",t.CLOSE="close",t.OPEN="open",t.CONNECT="connect",t.CLOSED="closed",t.ENDED="ended",t.MESSAGE="message",t.PINNED="pinned",t.UNPINNED="unpinned",t.DESCRIPTION_RECEIVED="descriptionReceived",t.SERVER_OPENING="serverOpening",t.SERVER_CLOSED="serverClosed",t.SERVER_DESCRIPTION_CHANGED="serverDescriptionChanged",t.TOPOLOGY_OPENING="topologyOpening",t.TOPOLOGY_CLOSED="topologyClosed",t.TOPOLOGY_DESCRIPTION_CHANGED="topologyDescriptionChanged",t.SERVER_SELECTION_STARTED="serverSelectionStarted",t.SERVER_SELECTION_FAILED="serverSelectionFailed",t.SERVER_SELECTION_SUCCEEDED="serverSelectionSucceeded",t.WAITING_FOR_SUITABLE_SERVER="waitingForSuitableServer",t.CONNECTION_POOL_CREATED="connectionPoolCreated",t.CONNECTION_POOL_CLOSED="connectionPoolClosed",t.CONNECTION_POOL_CLEARED="connectionPoolCleared",t.CONNECTION_POOL_READY="connectionPoolReady",t.CONNECTION_CREATED="connectionCreated",t.CONNECTION_READY="connectionReady",t.CONNECTION_CLOSED="connectionClosed",t.CONNECTION_CHECK_OUT_STARTED="connectionCheckOutStarted",t.CONNECTION_CHECK_OUT_FAILED="connectionCheckOutFailed",t.CONNECTION_CHECKED_OUT="connectionCheckedOut",t.CONNECTION_CHECKED_IN="connectionCheckedIn",t.CLUSTER_TIME_RECEIVED="clusterTimeReceived",t.COMMAND_STARTED="commandStarted",t.COMMAND_SUCCEEDED="commandSucceeded",t.COMMAND_FAILED="commandFailed",t.SERVER_HEARTBEAT_STARTED="serverHeartbeatStarted",t.SERVER_HEARTBEAT_SUCCEEDED="serverHeartbeatSucceeded",t.SERVER_HEARTBEAT_FAILED="serverHeartbeatFailed",t.RESPONSE="response",t.MORE="more",t.INIT="init",t.CHANGE="change",t.END="end",t.RESUME_TOKEN_CHANGED="resumeTokenChanged",t.HEARTBEAT_EVENTS=Object.freeze([t.SERVER_HEARTBEAT_STARTED,t.SERVER_HEARTBEAT_SUCCEEDED,t.SERVER_HEARTBEAT_FAILED]),t.CMAP_EVENTS=Object.freeze([t.CONNECTION_POOL_CREATED,t.CONNECTION_POOL_READY,t.CONNECTION_POOL_CLEARED,t.CONNECTION_POOL_CLOSED,t.CONNECTION_CREATED,t.CONNECTION_READY,t.CONNECTION_CLOSED,t.CONNECTION_CHECK_OUT_STARTED,t.CONNECTION_CHECK_OUT_FAILED,t.CONNECTION_CHECKED_OUT,t.CONNECTION_CHECKED_IN]),t.TOPOLOGY_EVENTS=Object.freeze([t.SERVER_OPENING,t.SERVER_CLOSED,t.SERVER_DESCRIPTION_CHANGED,t.TOPOLOGY_OPENING,t.TOPOLOGY_CLOSED,t.TOPOLOGY_DESCRIPTION_CHANGED,t.ERROR,t.TIMEOUT,t.CLOSE]),t.APM_EVENTS=Object.freeze([t.COMMAND_STARTED,t.COMMAND_SUCCEEDED,t.COMMAND_FAILED]),t.SERVER_RELAY_EVENTS=Object.freeze([t.SERVER_HEARTBEAT_STARTED,t.SERVER_HEARTBEAT_SUCCEEDED,t.SERVER_HEARTBEAT_FAILED,t.COMMAND_STARTED,t.COMMAND_SUCCEEDED,t.COMMAND_FAILED,...t.CMAP_EVENTS]),t.LOCAL_SERVER_EVENTS=Object.freeze([t.CONNECT,t.DESCRIPTION_RECEIVED,t.CLOSED,t.ENDED]),t.MONGO_CLIENT_EVENTS=Object.freeze([...t.CMAP_EVENTS,...t.APM_EVENTS,...t.TOPOLOGY_EVENTS,...t.HEARTBEAT_EVENTS]),t.LEGACY_HELLO_COMMAND="ismaster",t.LEGACY_HELLO_COMMAND_CAMEL_CASE="isMaster",t.kDecorateResult=Symbol.for("@@mdb.decorateDecryptionResult"),t.kDecoratedKeys=Symbol.for("@@mdb.decryptedKeys")},92992:(e,t,r)=>{var n=r(44775);t.certificate=r(58782);var o=n.define("RSAPrivateKey",(function(){this.seq().obj(this.key("version").int(),this.key("modulus").int(),this.key("publicExponent").int(),this.key("privateExponent").int(),this.key("prime1").int(),this.key("prime2").int(),this.key("exponent1").int(),this.key("exponent2").int(),this.key("coefficient").int())}));t.RSAPrivateKey=o;var i=n.define("RSAPublicKey",(function(){this.seq().obj(this.key("modulus").int(),this.key("publicExponent").int())}));t.RSAPublicKey=i;var s=n.define("AlgorithmIdentifier",(function(){this.seq().obj(this.key("algorithm").objid(),this.key("none").null_().optional(),this.key("curve").objid().optional(),this.key("params").seq().obj(this.key("p").int(),this.key("q").int(),this.key("g").int()).optional())})),a=n.define("SubjectPublicKeyInfo",(function(){this.seq().obj(this.key("algorithm").use(s),this.key("subjectPublicKey").bitstr())}));t.PublicKey=a;var c=n.define("PrivateKeyInfo",(function(){this.seq().obj(this.key("version").int(),this.key("algorithm").use(s),this.key("subjectPrivateKey").octstr())}));t.PrivateKey=c;var u=n.define("EncryptedPrivateKeyInfo",(function(){this.seq().obj(this.key("algorithm").seq().obj(this.key("id").objid(),this.key("decrypt").seq().obj(this.key("kde").seq().obj(this.key("id").objid(),this.key("kdeparams").seq().obj(this.key("salt").octstr(),this.key("iters").int())),this.key("cipher").seq().obj(this.key("algo").objid(),this.key("iv").octstr()))),this.key("subjectPrivateKey").octstr())}));t.EncryptedPrivateKey=u;var l=n.define("DSAPrivateKey",(function(){this.seq().obj(this.key("version").int(),this.key("p").int(),this.key("q").int(),this.key("g").int(),this.key("pub_key").int(),this.key("priv_key").int())}));t.DSAPrivateKey=l,t.DSAparam=n.define("DSAparam",(function(){this.int()}));var d=n.define("ECParameters",(function(){this.choice({namedCurve:this.objid()})})),h=n.define("ECPrivateKey",(function(){this.seq().obj(this.key("version").int(),this.key("privateKey").octstr(),this.key("parameters").optional().explicit(0).use(d),this.key("publicKey").optional().explicit(1).bitstr())}));t.ECPrivateKey=h,t.signature=n.define("signature",(function(){this.seq().obj(this.key("r").int(),this.key("s").int())}))},93065:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AUTH_MECHS_AUTH_SRC_EXTERNAL=t.AuthMechanism=void 0,t.AuthMechanism=Object.freeze({MONGODB_AWS:"MONGODB-AWS",MONGODB_CR:"MONGODB-CR",MONGODB_DEFAULT:"DEFAULT",MONGODB_GSSAPI:"GSSAPI",MONGODB_PLAIN:"PLAIN",MONGODB_SCRAM_SHA1:"SCRAM-SHA-1",MONGODB_SCRAM_SHA256:"SCRAM-SHA-256",MONGODB_X509:"MONGODB-X509",MONGODB_OIDC:"MONGODB-OIDC"}),t.AUTH_MECHS_AUTH_SRC_EXTERNAL=new Set([t.AuthMechanism.MONGODB_GSSAPI,t.AuthMechanism.MONGODB_AWS,t.AuthMechanism.MONGODB_OIDC,t.AuthMechanism.MONGODB_X509])},93347:(e,t,r)=>{var n=r(65994).e;Object.defineProperty(t,"__esModule",{value:!0}),t.MongoLogger=t.MongoLoggableComponent=t.SEVERITY_LEVEL_MAP=t.DEFAULT_MAX_DOCUMENT_LENGTH=t.SeverityLevel=void 0,t.parseSeverityFromString=u,t.createStdioLogger=l,t.stringifyWithMaxLen=p,t.defaultLogTransform=O;const o=r(98437),i=r(75080),s=r(91869),a=r(145);t.SeverityLevel=Object.freeze({EMERGENCY:"emergency",ALERT:"alert",CRITICAL:"critical",ERROR:"error",WARNING:"warn",NOTICE:"notice",INFORMATIONAL:"info",DEBUG:"debug",TRACE:"trace",OFF:"off"}),t.DEFAULT_MAX_DOCUMENT_LENGTH=1e3;class c extends Map{constructor(e){const t=[];for(const[r,n]of e)t.push([n,r]);t.push(...e),super(t)}getNumericSeverityLevel(e){return this.get(e)}getSeverityLevelName(e){return this.get(e)}}function u(e){const r=Object.values(t.SeverityLevel),n=e?.toLowerCase();return null!=n&&r.includes(n)?n:null}function l(e){return{write:(0,o.promisify)(((t,r)=>{const n=(0,o.inspect)(t,{compact:!0,breakLength:1/0});e.write(`${n}\n`,"utf-8",r)}))}}function d(e,t,r){return u(e)??u(t)??r}function h(e,r){const n=t.SEVERITY_LEVEL_MAP.getNumericSeverityLevel(e),o=t.SEVERITY_LEVEL_MAP.getNumericSeverityLevel(r);return n<o?-1:n>o?1:0}function p(e,t,r={}){let n="",o=0;const s=function(e,r){if(!(o>=t)){if(""===e)return o+=1,r;if(o+=e.length+4,null==r)return r;switch(typeof r){case"string":o+=r.length+2;break;case"number":case"bigint":o+=String(r).length;break;case"boolean":o+=r?4:5;break;case"object":if((0,a.isUint8Array)(r))o+=22+r.byteLength+.33*r.byteLength+18|0;else if("_bsontype"in r){const e=r;switch(e._bsontype){case"Int32":o+=String(e.value).length;break;case"Double":o+=(0|e.value)===e.value?String(e.value).length+2:String(e.value).length;break;case"Long":o+=e.toString().length;break;case"ObjectId":o+=35;break;case"MaxKey":case"MinKey":o+=13;break;case"Binary":o+=22+r.position+.33*r.position+18|0;break;case"Timestamp":o+=19+String(e.t).length+5+String(e.i).length+2;break;case"Code":null==e.scope?o+=e.code.length+10+2:o+=e.code.length+10+11;break;case"BSONRegExp":o+=34+e.pattern.length+13+e.options.length+3}}}return r}};if("string"==typeof e)n=e;else if("function"==typeof e)n=e.name;else try{n=0!==t?i.EJSON.stringify(e,s,0,r):i.EJSON.stringify(e,r)}catch(e){n=`Extended JSON serialization failed with: ${e.message}`}return 0!==t&&n.length>t&&n.charCodeAt(t-1)!==n.codePointAt(t-1)&&0==--t?"":0!==t&&n.length>t?`${n.slice(0,t)}...`:n}function m(e,r,n=t.DEFAULT_MAX_DOCUMENT_LENGTH){const{selector:o,operation:i,topologyDescription:s,message:a}=r;return e.selector=p(o,n),e.operation=i,e.topologyDescription=p(s,n),e.message=a,e}function f(e,t){e.commandName=t.commandName,e.requestId=t.requestId,e.driverConnectionId=t.connectionId;const{host:r,port:n}=a.HostAddress.fromString(t.address).toHostPort();return e.serverHost=r,e.serverPort=n,t?.serviceId&&(e.serviceId=t.serviceId.toHexString()),e.databaseName=t.databaseName,e.serverConnectionId=t.serverConnectionId,e}function g(e,t){const{host:r,port:n}=a.HostAddress.fromString(t.address).toHostPort();return e.serverHost=r,e.serverPort=n,e}function E(e,t){return e.topologyId=t.topologyId,e}function S(e,t){const{awaited:r,connectionId:n}=t;e.awaited=r,e.driverConnectionId=t.connectionId;const{host:o,port:i}=a.HostAddress.fromString(n).toHostPort();return e.serverHost=o,e.serverPort=i,e}function O(e,r=t.DEFAULT_MAX_DOCUMENT_LENGTH){let n=Object.create(null);switch(e.name){case s.SERVER_SELECTION_STARTED:return n=m(n,e,r),n;case s.SERVER_SELECTION_FAILED:return n=m(n,e,r),n.failure=e.failure?.message,n;case s.SERVER_SELECTION_SUCCEEDED:return n=m(n,e,r),n.serverHost=e.serverHost,n.serverPort=e.serverPort,n;case s.WAITING_FOR_SUITABLE_SERVER:return n=m(n,e,r),n.remainingTimeMS=e.remainingTimeMS,n;case s.COMMAND_STARTED:return n=f(n,e),n.message="Command started",n.command=p(e.command,r,{relaxed:!0}),n.databaseName=e.databaseName,n;case s.COMMAND_SUCCEEDED:return n=f(n,e),n.message="Command succeeded",n.durationMS=e.duration,n.reply=p(e.reply,r,{relaxed:!0}),n;case s.COMMAND_FAILED:return n=f(n,e),n.message="Command failed",n.durationMS=e.duration,n.failure=e.failure?.message??"(redacted)",n;case s.CONNECTION_POOL_CREATED:if(n=g(n,e),n.message="Connection pool created",e.options){const{maxIdleTimeMS:t,minPoolSize:r,maxPoolSize:o,maxConnecting:i,waitQueueTimeoutMS:s}=e.options;n={...n,maxIdleTimeMS:t,minPoolSize:r,maxPoolSize:o,maxConnecting:i,waitQueueTimeoutMS:s}}return n;case s.CONNECTION_POOL_READY:return n=g(n,e),n.message="Connection pool ready",n;case s.CONNECTION_POOL_CLEARED:return n=g(n,e),n.message="Connection pool cleared","ObjectId"===e.serviceId?._bsontype&&(n.serviceId=e.serviceId?.toHexString()),n;case s.CONNECTION_POOL_CLOSED:return n=g(n,e),n.message="Connection pool closed",n;case s.CONNECTION_CREATED:return n=g(n,e),n.message="Connection created",n.driverConnectionId=e.connectionId,n;case s.CONNECTION_READY:return n=g(n,e),n.message="Connection ready",n.driverConnectionId=e.connectionId,n.durationMS=e.durationMS,n;case s.CONNECTION_CLOSED:switch(n=g(n,e),n.message="Connection closed",n.driverConnectionId=e.connectionId,e.reason){case"stale":n.reason="Connection became stale because the pool was cleared";break;case"idle":n.reason="Connection has been available but unused for longer than the configured max idle time";break;case"error":n.reason="An error occurred while using the connection",e.error&&(n.error=e.error);break;case"poolClosed":n.reason="Connection pool was closed";break;default:n.reason=`Unknown close reason: ${e.reason}`}return n;case s.CONNECTION_CHECK_OUT_STARTED:return n=g(n,e),n.message="Connection checkout started",n;case s.CONNECTION_CHECK_OUT_FAILED:switch(n=g(n,e),n.message="Connection checkout failed",e.reason){case"poolClosed":n.reason="Connection pool was closed";break;case"timeout":n.reason="Wait queue timeout elapsed without a connection becoming available";break;case"connectionError":n.reason="An error occurred while trying to establish a new connection",e.error&&(n.error=e.error);break;default:n.reason=`Unknown close reason: ${e.reason}`}return n.durationMS=e.durationMS,n;case s.CONNECTION_CHECKED_OUT:return n=g(n,e),n.message="Connection checked out",n.driverConnectionId=e.connectionId,n.durationMS=e.durationMS,n;case s.CONNECTION_CHECKED_IN:return n=g(n,e),n.message="Connection checked in",n.driverConnectionId=e.connectionId,n;case s.SERVER_OPENING:return n=E(n,e),n=g(n,e),n.message="Starting server monitoring",n;case s.SERVER_CLOSED:return n=E(n,e),n=g(n,e),n.message="Stopped server monitoring",n;case s.SERVER_HEARTBEAT_STARTED:return n=E(n,e),n=S(n,e),n.message="Server heartbeat started",n;case s.SERVER_HEARTBEAT_SUCCEEDED:return n=E(n,e),n=S(n,e),n.message="Server heartbeat succeeded",n.durationMS=e.duration,n.serverConnectionId=e.serverConnectionId,n.reply=p(e.reply,r,{relaxed:!0}),n;case s.SERVER_HEARTBEAT_FAILED:return n=E(n,e),n=S(n,e),n.message="Server heartbeat failed",n.durationMS=e.duration,n.failure=e.failure?.message,n;case s.TOPOLOGY_OPENING:return n=E(n,e),n.message="Starting topology monitoring",n;case s.TOPOLOGY_CLOSED:return n=E(n,e),n.message="Stopped topology monitoring",n;case s.TOPOLOGY_DESCRIPTION_CHANGED:return n=E(n,e),n.message="Topology description changed",n.previousDescription=n.reply=p(e.previousDescription,r),n.newDescription=n.reply=p(e.newDescription,r),n;default:for(const[t,r]of Object.entries(e))null!=r&&(n[t]=r)}return n}t.SEVERITY_LEVEL_MAP=new c([[t.SeverityLevel.OFF,-1/0],[t.SeverityLevel.EMERGENCY,0],[t.SeverityLevel.ALERT,1],[t.SeverityLevel.CRITICAL,2],[t.SeverityLevel.ERROR,3],[t.SeverityLevel.WARNING,4],[t.SeverityLevel.NOTICE,5],[t.SeverityLevel.INFORMATIONAL,6],[t.SeverityLevel.DEBUG,7],[t.SeverityLevel.TRACE,8]]),t.MongoLoggableComponent=Object.freeze({COMMAND:"command",TOPOLOGY:"topology",SERVER_SELECTION:"serverSelection",CONNECTION:"connection",CLIENT:"client"}),t.MongoLogger=class{constructor(e){this.pendingLog=null,this.error=this.log.bind(this,"error"),this.warn=this.log.bind(this,"warn"),this.info=this.log.bind(this,"info"),this.debug=this.log.bind(this,"debug"),this.trace=this.log.bind(this,"trace"),this.componentSeverities=e.componentSeverities,this.maxDocumentLength=e.maxDocumentLength,this.logDestination=e.logDestination,this.logDestinationIsStdErr=e.logDestinationIsStdErr,this.severities=this.createLoggingSeverities()}createLoggingSeverities(){const e=Object();for(const r of Object.values(t.MongoLoggableComponent)){e[r]={};for(const n of Object.values(t.SeverityLevel))e[r][n]=h(n,this.componentSeverities[r])<=0}return e}turnOffSeverities(){for(const e of Object.values(t.MongoLoggableComponent)){this.componentSeverities[e]=t.SeverityLevel.OFF;for(const r of Object.values(t.SeverityLevel))this.severities[e][r]=!1}}logWriteFailureHandler(e){if(this.logDestinationIsStdErr)return this.turnOffSeverities(),void this.clearPendingLog();this.logDestination=l(n.stderr),this.logDestinationIsStdErr=!0,this.clearPendingLog(),this.error(t.MongoLoggableComponent.CLIENT,{toLog:function(){return{message:"User input for mongodbLogPath is now invalid. Logging is halted.",error:e.message}}}),this.turnOffSeverities(),this.clearPendingLog()}clearPendingLog(){this.pendingLog=null}willLog(e,r){return r!==t.SeverityLevel.OFF&&this.severities[e][r]}log(e,t,r){if(!this.willLog(t,e))return;let n={t:new Date,c:t,s:e};if("string"==typeof r?n.message=r:"object"==typeof r&&(n=function(e){const t=e;return void 0!==t.toLog&&"function"==typeof t.toLog}(r)?{...n,...r.toLog()}:{...n,...O(r,this.maxDocumentLength)}),(0,a.isPromiseLike)(this.pendingLog))this.pendingLog=this.pendingLog.then((()=>this.logDestination.write(n))).then(this.clearPendingLog.bind(this),this.logWriteFailureHandler.bind(this));else try{const e=this.logDestination.write(n);(0,a.isPromiseLike)(e)&&(this.pendingLog=e.then(this.clearPendingLog.bind(this),this.logWriteFailureHandler.bind(this)))}catch(e){this.logWriteFailureHandler(e)}}static resolveOptions(e,r){const o=function({MONGODB_LOG_PATH:e},{mongodbLogPath:t}){return"string"==typeof t&&/^stderr$/i.test(t)?{mongodbLogPath:l(n.stderr),mongodbLogPathIsStdErr:!0}:"string"==typeof t&&/^stdout$/i.test(t)?{mongodbLogPath:l(n.stdout),mongodbLogPathIsStdErr:!1}:"object"==typeof t&&"function"==typeof t?.write?{mongodbLogPath:t,mongodbLogPathIsStdErr:!1}:e&&/^stderr$/i.test(e)?{mongodbLogPath:l(n.stderr),mongodbLogPathIsStdErr:!0}:e&&/^stdout$/i.test(e)?{mongodbLogPath:l(n.stdout),mongodbLogPathIsStdErr:!1}:{mongodbLogPath:l(n.stderr),mongodbLogPathIsStdErr:!0}}(e,r),i={...e,...r,mongodbLogPath:o.mongodbLogPath,mongodbLogPathIsStdErr:o.mongodbLogPathIsStdErr},s=d(i.mongodbLogComponentSeverities?.default,i.MONGODB_LOG_ALL,t.SeverityLevel.OFF);return{componentSeverities:{command:d(i.mongodbLogComponentSeverities?.command,i.MONGODB_LOG_COMMAND,s),topology:d(i.mongodbLogComponentSeverities?.topology,i.MONGODB_LOG_TOPOLOGY,s),serverSelection:d(i.mongodbLogComponentSeverities?.serverSelection,i.MONGODB_LOG_SERVER_SELECTION,s),connection:d(i.mongodbLogComponentSeverities?.connection,i.MONGODB_LOG_CONNECTION,s),client:d(i.mongodbLogComponentSeverities?.client,i.MONGODB_LOG_CLIENT,s),default:s},maxDocumentLength:i.mongodbLogMaxDocumentLength??(0,a.parseUnsignedInteger)(i.MONGODB_LOG_MAX_DOCUMENT_LENGTH)??1e3,logDestination:i.mongodbLogPath,logDestinationIsStdErr:i.mongodbLogPathIsStdErr}}}},93549:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EstimatedDocumentCountOperation=void 0;const n=r(75725),o=r(78130),i=r(35394);class s extends o.CommandOperation{constructor(e,t={}){super(e,t),this.SERVER_COMMAND_RESPONSE_TYPE=n.MongoDBResponse,this.options=t,this.collectionName=e.collectionName}get commandName(){return"count"}buildCommandDocument(e,t){const r={count:this.collectionName};return"number"==typeof this.options.maxTimeMS&&(r.maxTimeMS=this.options.maxTimeMS),void 0!==this.options.comment&&(r.comment=this.options.comment),r}handleOk(e){return e.getNumber("n")??0}}t.EstimatedDocumentCountOperation=s,(0,i.defineAspects)(s,[i.Aspect.READ_OPERATION,i.Aspect.RETRYABLE,i.Aspect.CURSOR_CREATING])},93992:(e,t,r)=>{var n=r(67787).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.hmacSha256Hook=t.hmacSha512Hook=t.aes256CtrDecryptHook=t.aes256CtrEncryptHook=t.aes256CbcDecryptHook=t.aes256CbcEncryptHook=void 0,t.makeAES256Hook=i,t.randomHook=function(e,t){try{o.randomFillSync(e,0,t)}catch(e){return e}return t},t.sha256Hook=function(e,t){let r;try{r=o.createHash("sha256").update(e).digest()}catch(e){return e}return r.copy(t),r.length},t.makeHmacHook=s,t.signRsaSha256Hook=function(e,t,r){let i;try{const r=o.createSign("sha256WithRSAEncryption"),s=n.from(`-----BEGIN PRIVATE KEY-----\n${e.toString("base64")}\n-----END PRIVATE KEY-----\n`);i=r.update(t).end().sign(s)}catch(e){return e}return i.copy(r),i.length};const o=r(27348);function i(e,t){return function(r,i,s,a){let c;try{const a=o[e](t,r,i);a.setAutoPadding(!1),c=a.update(s);const u=a.final();u.length>0&&(c=n.concat([c,u]))}catch(e){return e}return c.copy(a),c.length}}function s(e){return(t,r,n)=>{let i;try{i=o.createHmac(e,t).update(r).digest()}catch(e){return e}return i.copy(n),i.length}}t.aes256CbcEncryptHook=i("createCipheriv","aes-256-cbc"),t.aes256CbcDecryptHook=i("createDecipheriv","aes-256-cbc"),t.aes256CtrEncryptHook=i("createCipheriv","aes-256-ctr"),t.aes256CtrDecryptHook=i("createDecipheriv","aes-256-ctr"),t.hmacSha512Hook=s("sha512"),t.hmacSha256Hook=s("sha256")},94330:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ReplaceOneOperation=t.UpdateManyOperation=t.UpdateOneOperation=t.UpdateOperation=void 0,t.makeUpdateStatement=p;const n=r(75725),o=r(17562),i=r(30770),s=r(145),a=r(78130),c=r(35394);class u extends a.CommandOperation{constructor(e,t,r){super(void 0,r),this.SERVER_COMMAND_RESPONSE_TYPE=n.MongoDBResponse,this.options=r,this.ns=e,this.statements=t}get commandName(){return"update"}get canRetryWrite(){return!1!==super.canRetryWrite&&this.statements.every((e=>null==e.multi||!1===e.multi))}buildCommandDocument(e,t){const r=this.options,n={update:this.ns.collection,updates:this.statements,ordered:r.ordered??!0};if("boolean"==typeof r.bypassDocumentValidation&&(n.bypassDocumentValidation=r.bypassDocumentValidation),r.let&&(n.let=r.let),void 0!==r.comment&&(n.comment=r.comment),0===this.writeConcern?.w&&this.statements.find((e=>e.hint)))throw new o.MongoCompatibilityError("hint is not supported with unacknowledged writes");return n}}t.UpdateOperation=u;class l extends u{constructor(e,t,r,n){if(super(e,[p(t,r,{...n,multi:!1})],n),!(0,s.hasAtomicOperators)(r,n))throw new o.MongoInvalidArgumentError("Update document requires atomic operators")}handleOk(e){const t=super.handleOk(e);if(null!=this.explain)return t;if(t.code)throw new o.MongoServerError(t);if(t.writeErrors)throw new o.MongoServerError(t.writeErrors[0]);return{acknowledged:0!==this.writeConcern?.w,modifiedCount:t.nModified??t.n,upsertedId:Array.isArray(t.upserted)&&t.upserted.length>0?t.upserted[0]._id:null,upsertedCount:Array.isArray(t.upserted)&&t.upserted.length?t.upserted.length:0,matchedCount:Array.isArray(t.upserted)&&t.upserted.length>0?0:t.n}}}t.UpdateOneOperation=l;class d extends u{constructor(e,t,r,n){if(super(e,[p(t,r,{...n,multi:!0})],n),!(0,s.hasAtomicOperators)(r,n))throw new o.MongoInvalidArgumentError("Update document requires atomic operators")}handleOk(e){const t=super.handleOk(e);if(null!=this.explain)return t;if(t.code)throw new o.MongoServerError(t);if(t.writeErrors)throw new o.MongoServerError(t.writeErrors[0]);return{acknowledged:0!==this.writeConcern?.w,modifiedCount:t.nModified??t.n,upsertedId:Array.isArray(t.upserted)&&t.upserted.length>0?t.upserted[0]._id:null,upsertedCount:Array.isArray(t.upserted)&&t.upserted.length?t.upserted.length:0,matchedCount:Array.isArray(t.upserted)&&t.upserted.length>0?0:t.n}}}t.UpdateManyOperation=d;class h extends u{constructor(e,t,r,n){if(super(e,[p(t,r,{...n,multi:!1})],n),(0,s.hasAtomicOperators)(r))throw new o.MongoInvalidArgumentError("Replacement document must not contain atomic operators")}handleOk(e){const t=super.handleOk(e);if(null!=this.explain)return t;if(t.code)throw new o.MongoServerError(t);if(t.writeErrors)throw new o.MongoServerError(t.writeErrors[0]);return{acknowledged:0!==this.writeConcern?.w,modifiedCount:t.nModified??t.n,upsertedId:Array.isArray(t.upserted)&&t.upserted.length>0?t.upserted[0]._id:null,upsertedCount:Array.isArray(t.upserted)&&t.upserted.length?t.upserted.length:0,matchedCount:Array.isArray(t.upserted)&&t.upserted.length>0?0:t.n}}}function p(e,t,r){if(null==e||"object"!=typeof e)throw new o.MongoInvalidArgumentError("Selector must be a valid JavaScript object");if(null==t||"object"!=typeof t)throw new o.MongoInvalidArgumentError("Document must be a valid JavaScript object");const n={q:e,u:t};return"boolean"==typeof r.upsert&&(n.upsert=r.upsert),r.multi&&(n.multi=r.multi),r.hint&&(n.hint=r.hint),r.arrayFilters&&(n.arrayFilters=r.arrayFilters),r.collation&&(n.collation=r.collation),r.multi||null==r.sort||(n.sort=(0,i.formatSort)(r.sort)),n}t.ReplaceOneOperation=h,(0,c.defineAspects)(u,[c.Aspect.RETRYABLE,c.Aspect.WRITE_OPERATION,c.Aspect.SKIP_COLLATION]),(0,c.defineAspects)(l,[c.Aspect.RETRYABLE,c.Aspect.WRITE_OPERATION,c.Aspect.EXPLAINABLE,c.Aspect.SKIP_COLLATION]),(0,c.defineAspects)(d,[c.Aspect.WRITE_OPERATION,c.Aspect.EXPLAINABLE,c.Aspect.SKIP_COLLATION]),(0,c.defineAspects)(h,[c.Aspect.RETRYABLE,c.Aspect.WRITE_OPERATION,c.Aspect.SKIP_COLLATION])},95421:e=>{var t=Object.getOwnPropertySymbols,r=Object.prototype.hasOwnProperty,n=Object.prototype.propertyIsEnumerable;e.exports=function(){try{if(!Object.assign)return!1;var e=new String("abc");if(e[5]="de","5"===Object.getOwnPropertyNames(e)[0])return!1;for(var t={},r=0;r<10;r++)t["_"+String.fromCharCode(r)]=r;if("0123456789"!==Object.getOwnPropertyNames(t).map((function(e){return t[e]})).join(""))return!1;var n={};return"abcdefghijklmnopqrst".split("").forEach((function(e){n[e]=e})),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},n)).join("")}catch(e){return!1}}()?Object.assign:function(e,o){for(var i,s,a=function(e){if(null==e)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}(e),c=1;c<arguments.length;c++){for(var u in i=Object(arguments[c]))r.call(i,u)&&(a[u]=i[u]);if(t){s=t(i);for(var l=0;l<s.length;l++)n.call(i,s[l])&&(a[s[l]]=i[s[l]])}}return a}},95662:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DropDatabaseOperation=t.DropCollectionOperation=void 0,t.dropCollections=async function(e,t,r){const o=a.TimeoutContext.create({session:r.session,serverSelectionTimeoutMS:e.client.s.options.serverSelectionTimeoutMS,waitQueueTimeoutMS:e.client.s.options.waitQueueTimeoutMS,timeoutMS:r.timeoutMS}),c=e.client.s.options.autoEncryption?.encryptedFieldsMap;let l=r.encryptedFields??c?.[`${e.databaseName}.${t}`];if(!l&&c){const n=await e.listCollections({name:t},{nameOnly:!1,session:r.session,timeoutContext:new i.CursorTimeoutContext(o,Symbol())}).toArray();l=n?.[0]?.options?.encryptedFields}if(l){const i=l.escCollection||`enxcol_.${t}.esc`,a=l.ecocCollection||`enxcol_.${t}.ecoc`;for(const t of[i,a]){const i=new d(e,t,r);try{await(0,u.executeOperation)(e.client,i,o)}catch(e){if(!(e instanceof n.MongoServerError)||e.code!==s.MONGODB_ERROR_CODES.NamespaceNotFound)throw e}}}return await(0,u.executeOperation)(e.client,new d(e,t,r),o)};const n=r(16360),o=r(75725),i=r(61066),s=r(17562),a=r(7799),c=r(78130),u=r(96357),l=r(35394);class d extends c.CommandOperation{constructor(e,t,r={}){super(e,r),this.SERVER_COMMAND_RESPONSE_TYPE=o.MongoDBResponse,this.options=r,this.name=t}get commandName(){return"drop"}buildCommandDocument(e,t){return{drop:this.name}}handleOk(e){return!0}}t.DropCollectionOperation=d;class h extends c.CommandOperation{constructor(e,t){super(e,t),this.SERVER_COMMAND_RESPONSE_TYPE=o.MongoDBResponse,this.options=t}get commandName(){return"dropDatabase"}buildCommandDocument(e,t){return{dropDatabase:1}}handleOk(e){return!0}}t.DropDatabaseOperation=h,(0,l.defineAspects)(d,[l.Aspect.WRITE_OPERATION]),(0,l.defineAspects)(h,[l.Aspect.WRITE_OPERATION])},95724:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MongocryptdManager=void 0;const n=r(17562);class o{constructor(e={}){this.spawnPath="",this.spawnArgs=[],this.uri="string"==typeof e.mongocryptdURI&&e.mongocryptdURI.length>0?e.mongocryptdURI:o.DEFAULT_MONGOCRYPTD_URI,this.bypassSpawn=!!e.mongocryptdBypassSpawn,Object.hasOwn(e,"mongocryptdSpawnPath")&&e.mongocryptdSpawnPath&&(this.spawnPath=e.mongocryptdSpawnPath),Object.hasOwn(e,"mongocryptdSpawnArgs")&&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")}async spawn(){const e=this.spawnPath||"mongocryptd",{spawn:t}=r(16154);this._child=t(e,this.spawnArgs,{stdio:"ignore",detached:!0}),this._child.on("error",(()=>{})),this._child.unref()}async withRespawn(e){try{return await e()}catch(e){if(!(e instanceof n.MongoNetworkTimeoutError)||this.bypassSpawn)throw e}return await this.spawn(),await e()}}t.MongocryptdManager=o,o.DEFAULT_MONGOCRYPTD_URI="mongodb://localhost:27020"},95750:(e,t,r)=>{var n=r(65994).e;Object.defineProperty(t,"__esModule",{value:!0}),t.GSSAPI=t.GSSAPICanonicalizationValue=void 0,t.performGSSAPICanonicalizeHostName=p,t.resolveCname=m;const o=r(95136),i=r(8500),s=r(17562),a=r(145),c=r(31057);async function u(e,t){return await e.command((0,a.ns)("$external.$cmd"),t)}let l;t.GSSAPICanonicalizationValue=Object.freeze({on:!0,off:!1,none:"none",forward:"forward",forwardAndReverse:"forwardAndReverse"});class d extends c.AuthProvider{async auth(e){const{connection:t,credentials:r}=e;if(null==r)throw new s.MongoMissingCredentialsError("Credentials required for GSSAPI authentication");const{username:o}=r,a=await async function(e){const{hostAddress:t}=e.options,{credentials:r}=e;if(!t||"string"!=typeof t.host||!r)throw new s.MongoInvalidArgumentError("Connection must have host and port and credentials defined.");if(l||(l=(0,i.getKerberos)()),"kModuleError"in l)throw l.kModuleError;const{initializeClient:o}=l,{username:a,password:c}=r,u=r.mechanismProperties,d=u.SERVICE_NAME??"mongodb",h=await p(t.host,u),m={};null!=c&&Object.assign(m,{user:a,password:c});const f=u.SERVICE_HOST??h;let g=`${d}${"win32"===n.platform?"/":"@"}${f}`;return"SERVICE_REALM"in u&&(g=`${g}@${u.SERVICE_REALM}`),await o(g,m)}(e),c=await a.step(""),d=await u(t,function(e){return{saslStart:1,mechanism:"GSSAPI",payload:e,autoAuthorize:1}}(c)),m=await h(a,10,d.payload),f=await u(t,function(e,t){return{saslContinue:1,conversationId:t,payload:e}}(m,d.conversationId)),g=await async function(e,t,r){const n=await e.unwrap(r);return await e.wrap(n||"",{user:t})}(a,o,f.payload);await u(t,{saslContinue:1,conversationId:f.conversationId,payload:g})}}async function h(e,t,r){try{return await e.step(r)||""}catch(n){if(0===t)throw n;return await h(e,t-1,r)}}async function p(e,r){const n=r.CANONICALIZE_HOST_NAME;if(!n||n===t.GSSAPICanonicalizationValue.none)return e;if(n!==t.GSSAPICanonicalizationValue.on&&n!==t.GSSAPICanonicalizationValue.forwardAndReverse)return await m(e);{const{address:t}=await o.promises.lookup(e);try{const r=await o.promises.resolvePtr(t);return r.length>0?r[0]:e}catch{return await m(e)}}}async function m(e){try{const t=await o.promises.resolveCname(e);return t.length>0?t[0]:e}catch{return e}}t.GSSAPI=d},96357:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.executeOperation=async function(e,t,r){if(!(t instanceof u.AbstractOperation))throw new n.MongoRuntimeError("This method requires a valid operation instance");const p=null==e.topology?await(0,a.abortable)(h(e),t.options):e.topology;let m,f=t.session;if(null==f)m=Symbol(),f=e.startSession({owner:m,explicit:!1});else{if(f.hasEnded)throw new n.MongoExpiredSessionError("Use of expired sessions is not permitted");if(f.snapshotEnabled&&!p.capabilities.supportsSnapshotReads)throw new n.MongoCompatibilityError("Snapshot reads require MongoDB 5.0 or later");if(f.client!==e)throw new n.MongoInvalidArgumentError("ClientSession must be from the same MongoClient")}t.session??=f;const g=t.readPreference??o.ReadPreference.primary,E=!!f?.inTransaction(),S=t.hasAspect(u.Aspect.READ_OPERATION);if(E&&!g.equals(o.ReadPreference.primary)&&(S||"runCommand"===t.commandName))throw new n.MongoTransactionError(`Read preference in a transaction must be primary, not: ${g.mode}`);f?.isPinned&&f.transaction.isCommitted&&!t.bypassPinningCheck&&f.unpin(),r??=s.TimeoutContext.create({session:f,serverSelectionTimeoutMS:e.s.options.serverSelectionTimeoutMS,waitQueueTimeoutMS:e.s.options.waitQueueTimeoutMS,timeoutMS:t.options.timeoutMS});try{return await async function(e,{topology:t,timeoutContext:r,session:o,readPreference:s}){let h;h=e.hasAspect(u.Aspect.MUST_SELECT_SAME_SERVER)?(0,i.sameServerSelector)(e.server?.description):e instanceof c.AggregateOperation&&e.hasWriteStage?(0,i.secondaryWritableServerSelector)(t.commonWireVersion,s):s;let p=await t.selectServer(h,{session:o,operationName:e.commandName,timeoutContext:r,signal:e.options.signal});const m=e.hasAspect(u.Aspect.READ_OPERATION),f=e.hasAspect(u.Aspect.WRITE_OPERATION),g=o?.inTransaction()??!1,E=t.s.options.retryReads&&!g&&e.canRetryRead,S=t.s.options.retryWrites&&!g&&(0,a.supportsRetryableWrites)(p)&&e.canRetryWrite,O=e.hasAspect(u.Aspect.RETRYABLE)&&null!=o&&(m&&E||f&&S);f&&S&&null!=o&&(e.options.willRetryWrite=!0,o.incrementTransactionNumber());const y=O?r.csotEnabled()?1/0:2:1;let C,M;for(let i=0;i<y;i++){if(C){if(f&&C.code===l)throw new n.MongoServerError({message:d,errmsg:d,originalError:C});if(e.hasAspect(u.Aspect.COMMAND_BATCHING)&&!e.canRetryWrite)throw C;if(f&&!(0,n.isRetryableWriteError)(C))throw C;if(m&&!(0,n.isRetryableReadError)(C))throw C;if(C instanceof n.MongoNetworkError&&e.hasAspect(u.Aspect.CURSOR_CREATING)&&null!=o&&o.isPinned&&!o.inTransaction()&&o.unpin({force:!0,forceClear:!0}),p=await t.selectServer(h,{session:o,operationName:e.commandName,previousServer:M,signal:e.options.signal}),f&&!(0,a.supportsRetryableWrites)(p))throw new n.MongoUnexpectedServerResponseError("Selected server does not support retryable writes")}e.server=p;try{i>0&&e.hasAspect(u.Aspect.COMMAND_BATCHING)&&e.resetBatch();try{const t=await p.command(e,r);return e.handleOk(t)}catch(t){return e.handleError(t)}}catch(e){if(!(e instanceof n.MongoError))throw e;if(null!=C&&e.hasErrorLabel(n.MongoErrorLabel.NoWritesPerformed))throw C;M=p.description,C=e,r.clear()}}throw C??new n.MongoRuntimeError("Tried to propagate retryability error, but no error was found.")}(t,{topology:p,timeoutContext:r,session:f,readPreference:g})}finally{null!=f?.owner&&f.owner===m&&await f.endSession()}},t.autoConnect=h;const n=r(17562),o=r(13700),i=r(30588),s=r(7799),a=r(145),c=r(62016),u=r(35394),l=n.MONGODB_ERROR_CODES.IllegalOperation,d="This MongoDB deployment does not support retryable writes. Please add retryWrites=false to your connection string.";async function h(e){if(null==e.topology){if(e.s.hasBeenClosed)throw new n.MongoNotConnectedError("Client must be connected before running operations");e.s.options.__skipPingOnConnect=!0;try{if(await e.connect(),null==e.topology)throw new n.MongoRuntimeError("client.connect did not create a topology but also did not throw");return e.topology}finally{delete e.s.options.__skipPingOnConnect}}return e.topology}},96856:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OP_MSG=t.OP_COMPRESSED=t.OP_DELETE=t.OP_QUERY=t.OP_INSERT=t.OP_UPDATE=t.OP_REPLY=t.MIN_SUPPORTED_QE_SERVER_VERSION=t.MIN_SUPPORTED_QE_WIRE_VERSION=t.MAX_SUPPORTED_WIRE_VERSION=t.MIN_SUPPORTED_WIRE_VERSION=t.MAX_SUPPORTED_SERVER_VERSION=t.MIN_SUPPORTED_SERVER_VERSION=void 0,t.MIN_SUPPORTED_SERVER_VERSION="4.2",t.MAX_SUPPORTED_SERVER_VERSION="8.0",t.MIN_SUPPORTED_WIRE_VERSION=8,t.MAX_SUPPORTED_WIRE_VERSION=25,t.MIN_SUPPORTED_QE_WIRE_VERSION=21,t.MIN_SUPPORTED_QE_SERVER_VERSION="7.0",t.OP_REPLY=1,t.OP_UPDATE=2001,t.OP_INSERT=2002,t.OP_QUERY=2004,t.OP_DELETE=2006,t.OP_COMPRESSED=2012,t.OP_MSG=2013},97194:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TopologyDescription=void 0;const n=r(75080),o=r(96856),i=r(17562),s=r(145),a=r(89167),c=r(9188),u=o.MIN_SUPPORTED_SERVER_VERSION,l=o.MAX_SUPPORTED_SERVER_VERSION,d=o.MIN_SUPPORTED_WIRE_VERSION,h=o.MAX_SUPPORTED_WIRE_VERSION,p=new Set([a.ServerType.Mongos,a.ServerType.Unknown]),m=new Set([a.ServerType.Mongos,a.ServerType.Standalone]),f=new Set([a.ServerType.RSSecondary,a.ServerType.RSArbiter,a.ServerType.RSOther]);class g{constructor(e,t=null,r=null,n=null,o=null,i=null,s=null){s=s??{},this.type=e??a.TopologyType.Unknown,this.servers=t??new Map,this.stale=!1,this.compatible=!0,this.heartbeatFrequencyMS=s.heartbeatFrequencyMS??0,this.localThresholdMS=s.localThresholdMS??15,this.setName=r??null,this.maxElectionId=o??null,this.maxSetVersion=n??null,this.commonWireVersion=i??0;for(const e of this.servers.values())if(e.type!==a.ServerType.Unknown&&e.type!==a.ServerType.LoadBalancer&&(e.minWireVersion>h&&(this.compatible=!1,this.compatibilityError=`Server at ${e.address} requires wire version ${e.minWireVersion}, but this version of the driver only supports up to ${h} (MongoDB ${l})`),e.maxWireVersion<d)){this.compatible=!1,this.compatibilityError=`Server at ${e.address} reports wire version ${e.maxWireVersion}, but this version of the driver requires at least ${d} (MongoDB ${u}).`;break}this.logicalSessionTimeoutMinutes=null;for(const[,e]of this.servers)if(e.isReadable){if(null==e.logicalSessionTimeoutMinutes){this.logicalSessionTimeoutMinutes=null;break}if(null==this.logicalSessionTimeoutMinutes){this.logicalSessionTimeoutMinutes=e.logicalSessionTimeoutMinutes;continue}this.logicalSessionTimeoutMinutes=Math.min(this.logicalSessionTimeoutMinutes,e.logicalSessionTimeoutMinutes)}}updateFromSrvPollingEvent(e,t=0){const r=e.hostnames(),n=new Set(this.servers.keys()),o=new Set(r),i=new Set;for(const e of n)o.delete(e),r.has(e)||i.add(e);if(0===o.size&&0===i.size)return this;const a=new Map(this.servers);for(const e of i)a.delete(e);if(o.size>0)if(0===t)for(const e of o)a.set(e,new c.ServerDescription(e));else if(a.size<t){const e=(0,s.shuffle)(o,t-a.size);for(const t of e)a.set(t,new c.ServerDescription(t))}return new g(this.type,a,this.setName,this.maxSetVersion,this.maxElectionId,this.commonWireVersion,{heartbeatFrequencyMS:this.heartbeatFrequencyMS,localThresholdMS:this.localThresholdMS})}update(e){const t=e.address;let{type:r,setName:n,maxSetVersion:o,maxElectionId:s,commonWireVersion:u}=this;const l=e.type,d=new Map(this.servers);if(0!==e.maxWireVersion&&(u=null==u?e.maxWireVersion:Math.min(u,e.maxWireVersion)),"string"==typeof e.setName&&"string"==typeof n&&e.setName!==n&&(r===a.TopologyType.Single?e=new c.ServerDescription(t):d.delete(t)),d.set(t,e),r===a.TopologyType.Single)return new g(a.TopologyType.Single,d,n,o,s,u,{heartbeatFrequencyMS:this.heartbeatFrequencyMS,localThresholdMS:this.localThresholdMS});if(r===a.TopologyType.Unknown&&(l===a.ServerType.Standalone&&1!==this.servers.size?d.delete(t):r=function(e){switch(e){case a.ServerType.Standalone:return a.TopologyType.Single;case a.ServerType.Mongos:return a.TopologyType.Sharded;case a.ServerType.RSPrimary:return a.TopologyType.ReplicaSetWithPrimary;case a.ServerType.RSOther:case a.ServerType.RSSecondary:return a.TopologyType.ReplicaSetNoPrimary;default:return a.TopologyType.Unknown}}(l)),r===a.TopologyType.Sharded&&(p.has(l)||d.delete(t)),r===a.TopologyType.ReplicaSetNoPrimary)if(m.has(l)&&d.delete(t),l===a.ServerType.RSPrimary){const t=E(d,e,n,o,s);r=t[0],n=t[1],o=t[2],s=t[3]}else if(f.has(l)){const t=function(e,t,r=null){const n=a.TopologyType.ReplicaSetNoPrimary;return(r=r??t.setName)!==t.setName?(e.delete(t.address),[n,r]):(t.allHosts.forEach((t=>{e.has(t)||e.set(t,new c.ServerDescription(t))})),t.me&&t.address!==t.me&&e.delete(t.address),[n,r])}(d,e,n);r=t[0],n=t[1]}if(r===a.TopologyType.ReplicaSetWithPrimary)if(m.has(l))d.delete(t),r=S(d);else if(l===a.ServerType.RSPrimary){const t=E(d,e,n,o,s);r=t[0],n=t[1],o=t[2],s=t[3]}else r=f.has(l)?function(e,t,r=null){if(null==r)throw new i.MongoRuntimeError('Argument "setName" is required if connected to a replica set');return(r!==t.setName||t.me&&t.address!==t.me)&&e.delete(t.address),S(e)}(d,e,n):S(d);return new g(r,d,n,o,s,u,{heartbeatFrequencyMS:this.heartbeatFrequencyMS,localThresholdMS:this.localThresholdMS})}get error(){const e=Array.from(this.servers.values()).filter((e=>e.error));return e.length>0?e[0].error:null}get hasKnownServers(){return Array.from(this.servers.values()).some((e=>e.type!==a.ServerType.Unknown))}get hasDataBearingServers(){return Array.from(this.servers.values()).some((e=>e.isDataBearing))}hasServer(e){return this.servers.has(e)}toJSON(){return n.EJSON.serialize(this)}}function E(e,t,r=null,n=null,o=null){const u=(e,t,r)=>`primary marked stale due to electionId/setVersion mismatch: server setVersion: ${e.setVersion}, server electionId: ${e.electionId}, topology setVersion: ${t}, topology electionId: ${r}`;if((r=r||t.setName)!==t.setName)return e.delete(t.address),[S(e),r,n,o];if(t.maxWireVersion>=17){const a=(0,s.compareObjectId)(o,t.electionId),l=0===a,d=-1===a,h=(n??-1)<=(t.setVersion??-1);if(!(d||l&&h))return e.set(t.address,new c.ServerDescription(t.address,void 0,{error:new i.MongoStalePrimaryError(u(t,n,o))})),[S(e),r,n,o];o=t.electionId,n=t.setVersion}else{const a=t.electionId?t.electionId:null;if(t.setVersion&&a){if(n&&o&&(n>t.setVersion||(0,s.compareObjectId)(o,a)>0))return e.set(t.address,new c.ServerDescription(t.address,void 0,{error:new i.MongoStalePrimaryError(u(t,n,o))})),[S(e),r,n,o];o=t.electionId}null!=t.setVersion&&(null==n||t.setVersion>n)&&(n=t.setVersion)}for(const[r,n]of e)if(n.type===a.ServerType.RSPrimary&&n.address!==t.address){e.set(r,new c.ServerDescription(n.address,void 0,{error:new i.MongoStalePrimaryError("primary marked stale due to discovery of newer primary")}));break}t.allHosts.forEach((t=>{e.has(t)||e.set(t,new c.ServerDescription(t))}));const l=Array.from(e.keys()),d=t.allHosts;return l.filter((e=>-1===d.indexOf(e))).forEach((t=>{e.delete(t)})),[S(e),r,n,o]}function S(e){for(const t of e.values())if(t.type===a.ServerType.RSPrimary)return a.TopologyType.ReplicaSetWithPrimary;return a.TopologyType.ReplicaSetNoPrimary}t.TopologyDescription=g},97350:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DropSearchIndexOperation=void 0;const n=r(75725),o=r(17562),i=r(35394);class s extends i.AbstractOperation{constructor(e,t){super(),this.SERVER_COMMAND_RESPONSE_TYPE=n.MongoDBResponse,this.collection=e,this.name=t,this.ns=e.fullNamespace}get commandName(){return"dropSearchIndex"}buildCommand(e,t){const r={dropSearchIndex:this.collection.fullNamespace.collection};return"string"==typeof this.name&&(r.name=this.name),r}handleOk(e){}buildOptions(e){return{session:this.session,timeoutContext:e}}handleError(e){if(!(e instanceof o.MongoServerError&&e.code===o.MONGODB_ERROR_CODES.NamespaceNotFound))throw e}}t.DropSearchIndexOperation=s},97515:(e,t,r)=>{var n=r(65994).e;Object.defineProperty(t,"__esModule",{value:!0}),t.StateMachine=void 0;const o=r(65981),i=r(26272),s=r(386),a=r(75080),c=r(61066),u=r(8500),l=r(17562),d=r(7799),h=r(145),p=r(73357),m=r(86981);let f=null;const g=new Map([[0,"MONGOCRYPT_CTX_ERROR"],[1,"MONGOCRYPT_CTX_NEED_MONGO_COLLINFO"],[2,"MONGOCRYPT_CTX_NEED_MONGO_MARKINGS"],[3,"MONGOCRYPT_CTX_NEED_MONGO_KEYS"],[7,"MONGOCRYPT_CTX_NEED_KMS_CREDENTIALS"],[4,"MONGOCRYPT_CTX_NEED_KMS"],[5,"MONGOCRYPT_CTX_READY"],[6,"MONGOCRYPT_CTX_DONE"]]),E=["tlsInsecure","tlsAllowInvalidCertificates","tlsAllowInvalidHostnames"];function S(e){n.env.MONGODB_CRYPT_DEBUG&&console.error(e)}let O;t.StateMachine=class{constructor(e,t=(0,a.pluckBSONSerializeOptions)(e)){this.options=e,this.bsonOptions=t}async execute(e,t,r){const n=e._keyVaultNamespace,o=e._keyVaultClient,i=e._metaDataClient,s=e._mongocryptdClient,c=e._mongocryptdManager;let u=null;const l=()=>t.status,d=()=>t.state;for(;6!==d()&&0!==d();)switch(r.signal?.throwIfAborted(),S(`[context#${t.id}] ${g.get(d())||d()}`),d()){case 1:{const e=(0,a.deserialize)(t.nextMongoOperation());if(!i)throw new m.MongoCryptError("unreachable state machine state: entered MONGOCRYPT_CTX_NEED_MONGO_COLLINFO but metadata client is undefined");const n=this.fetchCollectionInfo(i,t.ns,e,r);for await(const e of n)if(t.addMongoOperationResponse((0,a.serialize)(e)),0===d())break;if(0===d())break;t.finishMongoOperation();break}case 2:{const e=t.nextMongoOperation();if(0===d())break;if(!s)throw new m.MongoCryptError("unreachable state machine state: entered MONGOCRYPT_CTX_NEED_MONGO_MARKINGS but mongocryptdClient is undefined");const n=c?await c.withRespawn(this.markCommand.bind(this,s,t.ns,e,r)):await this.markCommand(s,t.ns,e,r);t.addMongoOperationResponse(n),t.finishMongoOperation();break}case 3:{const e=t.nextMongoOperation(),i=await this.fetchKeys(o,n,e,r);0===i.length&&(u=O??=(0,a.serialize)({v:[]}));for(const e of i)t.addMongoOperationResponse((0,a.serialize)(e));t.finishMongoOperation();break}case 7:{const r=await e.askForKMSCredentials();t.provideKMSProviders((0,a.serialize)(r));break}case 4:await Promise.all(this.requests(t,r)),t.finishKMSRequests();break;case 5:{const e=t.finalize();if(0===d()){const e=l().message||"Finalization error";throw new m.MongoCryptError(e)}u=e;break}default:throw new m.MongoCryptError(`Unknown state: ${d()}`)}if(0===d()||null==u){const e=l().message;throw e||S("unidentifiable error in MongoCrypt - received an error status from `libmongocrypt` but received no error message."),new m.MongoCryptError(e??"unidentifiable error in MongoCrypt - received an error status from `libmongocrypt` but received no error message.")}return u}async kmsRequest(e,t){const r=e.endpoint.split(":"),n=null!=r[1]?Number.parseInt(r[1],10):443,o={host:r[0],servername:r[0],port:n,...(0,p.autoSelectSocketOptions)(this.options.socketOptions||{})},a=e.message,c=new h.BufferPool;let g,E;function S(){for(const e of[E,g])e&&e.destroy()}function O(e){return new m.MongoCryptError("KMS request failed",{cause:e})}function y(){return new m.MongoCryptError("KMS request closed")}const C=this.options.tlsOptions;if(C){const t=e.kmsProvider,r=C[t];if(r){const e=this.validateTlsOptions(t,r);if(e)throw e;try{await this.setTlsOptions(r,o)}catch(e){throw O(e)}}}let M;try{if(this.options.proxyOptions&&this.options.proxyOptions.proxyHost){g=new i.Socket;const{promise:e,reject:t,resolve:r}=(0,h.promiseWithResolvers)();g.once("error",(e=>t(O(e)))).once("close",(()=>t(y()))).once("connect",(()=>r()));const n={...o,host:this.options.proxyOptions.proxyHost,port:this.options.proxyOptions.proxyPort||1080};g.connect(n),await e;try{f??=function(){if(null==f){const e=(0,u.getSocks)();if("kModuleError"in e)throw e.kModuleError;f=e}return f}(),o.socket=(await f.SocksClient.createConnection({existing_socket:g,command:"connect",destination:{host:o.host,port:o.port},proxy:{host:"iLoveJavaScript",port:0,type:5,userId:this.options.proxyOptions.proxyUsername,password:this.options.proxyOptions.proxyPassword}})).socket}catch(e){throw O(e)}}E=s.connect(o,(()=>{E.write(a)}));const{promise:r,reject:n,resolve:l}=(0,h.promiseWithResolvers)();M=(0,h.addAbortListener)(t?.signal,(function(){S(),n(this.reason)})),E.once("error",(e=>n(O(e)))).once("close",(()=>n(y()))).on("data",(t=>{for(c.append(t);e.bytesNeeded>0&&c.length;){const t=Math.min(e.bytesNeeded,c.length);e.addResponse(c.read(t))}e.bytesNeeded<=0&&l()})),await(t?.timeoutContext?.csotEnabled()?Promise.all([r,d.Timeout.expires(t.timeoutContext?.remainingTimeMS)]):r)}catch(e){if(e instanceof d.TimeoutError)throw new l.MongoOperationTimeoutError("KMS request timed out");throw e}finally{S(),M?.[h.kDispose]()}}*requests(e,t){for(let r=e.nextKMSRequest();null!=r;r=e.nextKMSRequest())yield this.kmsRequest(r,t)}validateTlsOptions(e,t){const r=Object.keys(t);for(const t of E)if(r.includes(t))return new m.MongoCryptError(`Insecure TLS options prohibited for ${e}: ${t}`)}async setTlsOptions(e,t){if(e.secureContext&&(t.secureContext=e.secureContext),e.tlsCertificateKeyFile){const r=await o.readFile(e.tlsCertificateKeyFile);t.cert=t.key=r}e.tlsCAFile&&(t.ca=await o.readFile(e.tlsCAFile)),e.tlsCertificateKeyFilePassword&&(t.passphrase=e.tlsCertificateKeyFilePassword)}fetchCollectionInfo(e,t,r,n){const{db:o}=h.MongoDBCollectionNamespace.fromString(t);return e.db(o).listCollections(r,{promoteLongs:!1,promoteValues:!1,timeoutContext:n?.timeoutContext&&new c.CursorTimeoutContext(n?.timeoutContext,Symbol()),signal:n?.signal,nameOnly:!1})}async markCommand(e,t,r,n){const{db:o}=h.MongoDBCollectionNamespace.fromString(t),i={promoteLongs:!1,promoteValues:!1},s=(0,a.deserialize)(r,i),c={timeoutMS:void 0,signal:void 0};n?.timeoutContext?.csotEnabled()&&(c.timeoutMS=n.timeoutContext.remainingTimeMS),n?.signal&&(c.signal=n.signal);const u=await e.db(o).command(s,{...i,...c});return(0,a.serialize)(u,this.bsonOptions)}fetchKeys(e,t,r,n){const{db:o,collection:i}=h.MongoDBCollectionNamespace.fromString(t),s={timeoutContext:void 0,signal:void 0};return null!=n?.timeoutContext&&(s.timeoutContext=new c.CursorTimeoutContext(n.timeoutContext,Symbol())),null!=n?.signal&&(s.signal=n.signal),e.db(o).collection(i,{readConcern:{level:"majority"}}).find((0,a.deserialize)(r),s).toArray()}}},97531:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onData=function(e,{timeoutContext:t,signal:r}){r?.throwIfAborted();const o=new n.List,i=new n.List;let s=null,a=!1;const c={next(){const e=o.shift();if(null!=e)return Promise.resolve({value:e,done:!1});if(null!=s){const e=Promise.reject(s);return s=null,e}if(a)return p();const{promise:t,resolve:r,reject:c}=(0,n.promiseWithResolvers)();return i.push({resolve:r,reject:c}),t},return:()=>p(),throw:e=>(h(e),Promise.resolve({value:void 0,done:!0})),[Symbol.asyncIterator](){return this},async[Symbol.asyncDispose](){await p()}};e.on("data",d),e.on("error",h);const u=(0,n.addAbortListener)(r,(function(){h(this.reason)})),l=t?.timeoutForSocketRead;return l?.throwIfExpired(),l?.then(void 0,h),c;function d(e){const t=i.shift();null!=t?t.resolve({value:e,done:!1}):o.push(e)}function h(e){const t=i.shift();null!=t?t.reject(e):s=e,p()}function p(){e.off("data",d),e.off("error",h),u?.[n.kDispose](),a=!0,l?.clear();const t={value:void 0,done:a};for(const e of i)e.resolve(t);return Promise.resolve(t)}};const n=r(145)}};