@mongodb-js/compass-web 0.31.1 → 0.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +0,0 @@
1
- /*! For license information please see 423.45723618046344488182.mjs.LICENSE.txt */
2
- export const __webpack_esm_id__=423;export const __webpack_esm_ids__=[423];export const __webpack_esm_modules__={145:(e,t,n)=>{var r=n(67787).Buffer,o=n(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 n of t)if(e===n||n.startsWith("*.")&&e?.endsWith(n.substring(2,n.length))||n.startsWith("*/")&&e?.endsWith(n.substring(2,n.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 n in e)t[n]=e[n]}return t},t.isObject=C,t.mergeOptions=function(e,t){return{...e,...t}},t.filterOptions=function(e,t){const n={};for(const r in e)t.includes(r)&&(n[r]=e[r]);return n},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,n){const r=v(t).capabilities;if(n.collation&&"object"==typeof n.collation){if(!r||!r.commandsTakeCollation)throw new f.MongoCompatibilityError("Current topology does not support collation");e.collation=n.collation}},t.decorateWithReadConcern=function(e,t,n){if(n&&n.session&&n.session.inTransaction())return;const r=Object.assign({},e.readConcern||{});t.s.readConcern&&Object.assign(r,t.s.readConcern),Object.keys(r).length>0&&Object.assign(e,{readConcern:r})},t.getTopology=v,t.ns=function(e){return b.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,n)=>e===t[n])))},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,n){const r=e[t.s.state];if(r&&r.indexOf(n)<0)throw new f.MongoRuntimeError(`illegal state transition from [${t.s.state}] => [${n}], allowed: [${r}]`);t.emit("stateChanged",t.s.state,n),t.s.state=n}},t.now=M,t.calculateDurationInMs=function(e){if("number"!=typeof e)return-1;const t=M()-e;return t<0?0:t},t.hasAtomicOperators=function e(t,n){if(Array.isArray(t)){for(const n of t)if(e(n))return!0;return!1}const r=Object.keys(t);if(n?.ignoreUndefined){let e=!0;for(const n of r)if(void 0!==t[n]){e=!1;break}if(e)throw new f.MongoInvalidArgumentError("Update operations require that all atomic operators have defined values, but none were provided.")}return r.length>0&&"$"===r[0][0]},t.resolveTimeoutOptions=function(e,t){const{socketTimeoutMS:n,serverSelectionTimeoutMS:r,waitQueueTimeoutMS:o,timeoutMS:i}=e.s.options;return{socketTimeoutMS:n,serverSelectionTimeoutMS:r,waitQueueTimeoutMS:o,timeoutMS:i,...t}},t.resolveOptions=function(e,t){const n=Object.assign({},t,(0,d.resolveBSONOptions)(t,e)),r=t?.timeoutMS??e?.timeoutMS,o=t?.session;if(!o?.inTransaction()){const o=g.ReadConcern.fromOptions(t)??e?.readConcern;o&&(n.readConcern=o);let i=S.WriteConcern.fromOptions(t)??e?.writeConcern;i&&(null!=r&&(i=S.WriteConcern.fromOptions({writeConcern:{...i,wtimeout:void 0,wtimeoutMS:void 0}})),n.writeConcern=i)}n.timeoutMS=r;const i=y.ReadPreference.fromOptions(t)??e?.readPreference;if(i&&(n.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 n},t.isSuperset=T,t.isHello=function(e){return!(!e[m.LEGACY_HELLO_COMMAND]&&!e.hello)},t.setDifference=function(e,t){const n=new Set(e);for(const e of t)n.delete(e);return n},t.isRecord=function(e,t=void 0){if(!C(e))return!1;const n=e.constructor;if(n&&n.prototype){if(!C(n.prototype))return!1;if(!_(n.prototype,"isPrototypeOf"))return!1}return!t||T(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!==E.ServerType.Standalone)},t.shuffle=function(e,t=0){const n=Array.from(e);if(t>n.length)throw new f.MongoRuntimeError("Limit must be less than the number of items");let r=n.length;const o=t%n.length==0?1:n.length-t;for(;r>o;){const e=Math.floor(Math.random()*r);r-=1;const t=n[r];n[r]=n[e],n[e]=t}return t%n.length==0?n:n.slice(o)},t.commandSupportsReadConcern=function(e){return!!(e.aggregate||e.count||e.distinct||e.find||e.geoNear)},t.compareObjectId=function(e,n){return null==e&&null==n?0:null==e?-1:null==n?1:t.ByteUtils.compare(e.id,n.id)},t.parseInteger=x,t.parseUnsignedInteger=function(e){const t=x(e);return null!=t&&t>=0?t:null},t.checkParentDomainMatch=function(e,t){const n=e.endsWith(".")?e.slice(0,e.length-1):e,r=t.endsWith(".")?t.slice(0,t.length-1):t,o=/^.*?\./,i=r.split(".").length<3,s=`.${n.replace(o,"")}`;let a=i?r:`.${r.replace(o,"")}`;if(a.startsWith(".")||(a="."+a),i&&n.split(".").length<=r.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(((n,r)=>{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),n({status:e.statusCode,body:t})}))})).on("error",(e=>{(0,c.clearTimeout)(o),r(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(((n,r)=>{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);n(e)}catch{r(new f.MongoRuntimeError(`Invalid JSON response: "${o}"`))}else n(o)}))}));i.once("timeout",(()=>i.destroy(new f.MongoNetworkTimeoutError(`Network request to ${e} timed out after ${t.timeout} ms`)))),i.once("error",(e=>r(e))),i.end()}))},t.isHostMatch=function(e,t){return!(!t||!e.test(t.toLowerCase()))},t.promiseWithResolvers=P,t.squashError=function(e){},t.once=async function(e,n,r){r?.signal?.throwIfAborted();const{promise:o,resolve:i,reject:s}=P(),a=e=>i(e),c=e=>s(e),u=k(r?.signal,(function(){s(this.reason)}));e.once(n,a).once("error",c);try{return await o}finally{e.off(n,a),e.off("error",c),u?.[t.kDispose]()}},t.maybeAddIdToDocuments=function(e,t,n){return(n.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,n,o=!0){if(o&&(r.isBuffer(n)&&(n=(0,d.deserialize)(n)),r.isBuffer(t)))throw new f.MongoRuntimeError("Expected result of decryption to be deserialized BSON object");if(t&&"object"==typeof t)for(const r of Object.keys(t)){const o=n[r];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(r)):e(t[r],o,!1)}},t.addAbortListener=k,t.abortable=async function(e,{signal:n}){if(null==n)return await e;const{promise:r,reject:o}=P(),i=n.aborted?o(n.reason):k(n,(function(){o(this.reason)}));try{return await Promise.race([e,r])}finally{i?.[t.kDispose]()}};const i=n(27348),s=n(36374),a=n(7742),c=n(37668),u=n(9606),l=n(9606),h=n(98437),d=n(75080),p=n(96856),m=n(91869),f=n(17562),g=n(28541),y=n(13700),E=n(89167),S=n(40012);t.ByteUtils={toLocalBufferType:e=>r.isBuffer(e)?e:r.from(e.buffer,e.byteOffset,e.byteLength),equals:(e,n)=>t.ByteUtils.toLocalBufferType(e).equals(n),compare:(e,n)=>t.ByteUtils.toLocalBufferType(e).compare(n),toBase64:e=>t.ByteUtils.toLocalBufferType(e).toString("base64")};const O=e=>Object.prototype.toString.call(e);function C(e){return"[object Object]"===O(e)}function v(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 b{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,...n]=e.split("."),r=n.join(".");return new b(t,""===r?void 0:r)}}t.MongoDBNamespace=b;class w extends b{constructor(e,t){super(e,t),this.collection=t}static fromString(e){return super.fromString(e)}}function M(){const e=o.hrtime();return Math.floor(1e3*e[0]+e[1]/1e6)}function T(e,t){e=Array.isArray(e)?new Set(e):e,t=Array.isArray(t)?new Set(t):t;for(const n of t)if(!e.has(n))return!1;return!0}t.MongoDBCollectionNamespace=w;const _=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);class A{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,n=e.next;return t.next=n,n.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=A,t.BufferPool=class{constructor(){this.buffers=new A,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),n=t.readInt32LE(0);return this.totalByteLength+=4,this.buffers.unshift(t),n}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 r.alloc(0);const t=r.allocUnsafe(e);for(let n=0;n<e;){const r=this.buffers.shift();if(null==r)break;const o=e-n,i=Math.min(o,r.byteLength),s=r.subarray(0,i);t.set(s,n),n+=i,this.totalByteLength-=i,i<r.byteLength&&this.buffers.unshift(r.subarray(i))}return t}};class R{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 n=`iLoveJS://${t}`;let r;try{r=new l.URL(n)}catch(e){const n=new f.MongoRuntimeError(`Unable to parse ${t} with URL`);throw n.cause=e,n}const o=r.hostname,i=r.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 R(e)}static fromHostPort(e,t){return e.includes(":")&&(e=`[${e}]`),R.fromString(`${e}:${t}`)}static fromSrvRecord({name:e,port:t}){return R.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=R,t.DEFAULT_PK_FACTORY={createPk:()=>new d.ObjectId},t.MONGODB_WARNING_CODE="MONGODB DRIVER";const I=new Set;function x(e){if("number"==typeof e)return Math.trunc(e);const t=Number.parseInt(String(e),10);return Number.isNaN(t)?null:t}function P(){let e,t;return{promise:new Promise((function(n,r){e=n,t=r})),resolve:e,reject:t}}function k(e,n){if(null!=e)return e.addEventListener("abort",n,{once:!0}),{[t.kDispose]:()=>e.removeEventListener("abort",n)}}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,h.promisify)(i.randomBytes),t.kDispose=Symbol.dispose??Symbol("dispose")},287:(e,t,n)=>{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 r=n(91869),o=n(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=r.CONNECTION_POOL_CREATED;const{maxConnecting:t,maxPoolSize:n,minPoolSize:o,maxIdleTimeMS:i,waitQueueTimeoutMS:s}=e.options;this.options={maxConnecting:t,maxPoolSize:n,minPoolSize:o,maxIdleTimeMS:i,waitQueueTimeoutMS:s}}},t.ConnectionPoolReadyEvent=class extends i{constructor(e){super(e),this.name=r.CONNECTION_POOL_READY}},t.ConnectionPoolClosedEvent=class extends i{constructor(e){super(e),this.name=r.CONNECTION_POOL_CLOSED}},t.ConnectionCreatedEvent=class extends i{constructor(e,t){super(e),this.name=r.CONNECTION_CREATED,this.connectionId=t.id}},t.ConnectionReadyEvent=class extends i{constructor(e,t,n){super(e),this.name=r.CONNECTION_READY,this.durationMS=(0,o.now)()-n,this.connectionId=t.id}},t.ConnectionClosedEvent=class extends i{constructor(e,t,n,o){super(e),this.name=r.CONNECTION_CLOSED,this.connectionId=t.id,this.reason=n,this.serviceId=t.serviceId,this.error=o??null}},t.ConnectionCheckOutStartedEvent=class extends i{constructor(e){super(e),this.name=r.CONNECTION_CHECK_OUT_STARTED}},t.ConnectionCheckOutFailedEvent=class extends i{constructor(e,t,n,i){super(e),this.name=r.CONNECTION_CHECK_OUT_FAILED,this.durationMS=(0,o.now)()-n,this.reason=t,this.error=i}},t.ConnectionCheckedOutEvent=class extends i{constructor(e,t,n){super(e),this.name=r.CONNECTION_CHECKED_OUT,this.durationMS=(0,o.now)()-n,this.connectionId=t.id}},t.ConnectionCheckedInEvent=class extends i{constructor(e,t){super(e),this.name=r.CONNECTION_CHECKED_IN,this.connectionId=t.id}},t.ConnectionPoolClearedEvent=class extends i{constructor(e,t={}){super(e),this.name=r.CONNECTION_POOL_CLEARED,this.serviceId=t.serviceId,this.interruptInUseConnections=t.interruptInUseConnections}}},815:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DistinctOperation=void 0;const r=n(75725),o=n(78130),i=n(35394);class s extends o.CommandOperation{constructor(e,t,n,o){super(e,o),this.SERVER_COMMAND_RESPONSE_TYPE=r.MongoDBResponse,this.options=o??{},this.collection=e,this.key=t,this.query=n}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,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.KillCursorsOperation=void 0;const r=n(75725),o=n(17562),i=n(35394);class s extends i.AbstractOperation{constructor(e,t,n,o){super(o),this.SERVER_COMMAND_RESPONSE_TYPE=r.MongoDBResponse,this.ns=t,this.cursorId=e,this.server=n}get commandName(){return"killCursors"}buildCommand(e,t){const n=this.ns.collection;if(null==n)throw new o.MongoRuntimeError("A collection name must be determined before killCursors");return{killCursors:n,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,n)=>{var r=n(65994).e;Object.defineProperty(t,"__esModule",{value:!0}),t.ServerCapabilities=t.Topology=void 0;const o=n(6875),i=n(91869),s=n(17562),a=n(93347),c=n(4642),u=n(13700),l=n(7799),h=n(145),d=n(89167),p=n(43135),m=n(5369),f=n(9188),g=n(30588),y=n(3906),E=n(4313),S=n(97194);let O=0;const C=(0,h.makeStateMachine)({[d.STATE_CLOSED]:[d.STATE_CLOSED,d.STATE_CONNECTING],[d.STATE_CONNECTING]:[d.STATE_CONNECTING,d.STATE_CLOSING,d.STATE_CONNECTED,d.STATE_CLOSED],[d.STATE_CONNECTED]:[d.STATE_CONNECTED,d.STATE_CLOSING,d.STATE_CLOSED],[d.STATE_CLOSING]:[d.STATE_CLOSING,d.STATE_CLOSED]});class v extends c.TypedEventEmitter{constructor(e,t,n){super(),this.on("error",h.noop),this.client=e,n=n??{hosts:[h.HostAddress.fromString("localhost:27017")],...Object.fromEntries(o.DEFAULT_OPTIONS.entries())},"string"==typeof t?t=[h.HostAddress.fromString(t)]:Array.isArray(t)||(t=[t]);const r=[];for(const e of t)if("string"==typeof e)r.push(h.HostAddress.fromString(e));else{if(!(e instanceof h.HostAddress))throw new s.MongoRuntimeError(`Topology cannot be constructed from ${JSON.stringify(e)}`);r.push(e)}const i=function(e){return e?.directConnection?d.TopologyType.Single:e?.replicaSet?d.TopologyType.ReplicaSetNoPrimary:e?.loadBalanced?d.TopologyType.LoadBalanced:d.TopologyType.Unknown}(n),a=O++,c=null==n.srvMaxHosts||0===n.srvMaxHosts||n.srvMaxHosts>=r.length?r:(0,h.shuffle)(r,n.srvMaxHosts),u=new Map;for(const e of c)u.set(e.toString(),new f.ServerDescription(e));this.waitQueue=new h.List,this.s={id:a,options:n,seedlist:r,state:d.STATE_CLOSED,description:new S.TopologyDescription(i,u,n.replicaSet,void 0,void 0,void 0,n),serverSelectionTimeoutMS:n.serverSelectionTimeoutMS,heartbeatFrequencyMS:n.heartbeatFrequencyMS,minHeartbeatFrequencyMS:n.minHeartbeatFrequencyMS,servers:new Map,credentials:n?.credentials,clusterTime:void 0,detectShardedTopology:e=>this.detectShardedTopology(e),detectSrvRecords:e=>this.detectSrvRecords(e)},this.mongoLogger=e.mongoLogger,this.component="topology",n.srvHost&&!n.loadBalanced&&(this.s.srvPoller=n.srvPoller??new E.SrvPoller({heartbeatFrequencyMS:this.s.heartbeatFrequencyMS,srvHost:n.srvHost,srvMaxHosts:n.srvMaxHosts,srvServiceName:n.srvServiceName}),this.on(v.TOPOLOGY_DESCRIPTION_CHANGED,this.s.detectShardedTopology)),this.connectionLock=void 0}detectShardedTopology(e){const t=e.previousDescription.type,n=e.newDescription.type,r=t!==d.TopologyType.Sharded&&n===d.TopologyType.Sharded,o=this.s.srvPoller?.listeners(E.SrvPoller.SRV_RECORD_DISCOVERY),i=!!o?.includes(this.s.detectSrvRecords);r&&!i&&(this.s.srvPoller?.on(E.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&&(M(this),this.emitAndLog(v.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 A(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===d.STATE_CONNECTED)return this;C(this,d.STATE_CONNECTING),this.emitAndLog(v.TOPOLOGY_OPENING,new p.TopologyOpeningEvent(this.s.id)),this.emitAndLog(v.TOPOLOGY_DESCRIPTION_CHANGED,new p.TopologyDescriptionChangedEvent(this.s.id,new S.TopologyDescription(d.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 n=this.client.s.options.serverSelectionTimeoutMS,r=e.readPreference??u.ReadPreference.primary,o=l.TimeoutContext.create({timeoutMS:void 0,serverSelectionTimeoutMS:n,waitQueueTimeoutMS:this.client.s.options.waitQueueTimeoutMS}),i={operationName:"handshake",...e,timeoutContext:o};try{const e=await this.selectServer((0,g.readPreferenceServerSelector)(r),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,d.STATE_CONNECTED),this.emit(v.OPEN,this),this.emit(v.CONNECT,this),this}return C(this,d.STATE_CONNECTED),this.emit(v.OPEN,this),this.emit(v.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!==d.STATE_CLOSED&&this.s.state!==d.STATE_CLOSING){for(const e of this.s.servers.values())b(e,this);this.s.servers.clear(),C(this,d.STATE_CLOSING),T(this.waitQueue,new s.MongoTopologyClosedError),this.s.srvPoller&&(this.s.srvPoller.stop(),this.s.srvPoller.removeListener(E.SrvPoller.SRV_RECORD_DISCOVERY,this.s.detectSrvRecords)),this.removeListener(v.TOPOLOGY_DESCRIPTION_CHANGED,this.s.detectShardedTopology),C(this,d.STATE_CLOSED),this.emitAndLog(v.TOPOLOGY_CLOSED,new p.TopologyClosedEvent(this.s.id))}}async selectServer(e,t){let n,r;if("function"!=typeof e)if("string"==typeof e)n=(0,g.readPreferenceServerSelector)(u.ReadPreference.fromString(e));else{let r;e instanceof u.ReadPreference?r=e:(u.ReadPreference.translate(t),r=t.readPreference||u.ReadPreference.primary),n=(0,g.readPreferenceServerSelector)(r)}else n=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 y.ServerSelectionStartedEvent(e,this.description,t.operationName)),r=t.timeoutContext?t.timeoutContext.serverSelectionTimeout:l.Timeout.expires(t.serverSelectionTimeoutMS??0);const o=this.description.type===d.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 y.ServerSelectionSucceededEvent(e,this.description,c.server.pool.address,t.operationName)),t.timeoutContext?.clearServerSelectionTimeout&&r?.clear(),c.server;const{promise:p,resolve:m,reject:f}=(0,h.promiseWithResolvers)(),E={serverSelector:n,topologyDescription:this.description,mongoLogger:this.client.mongoLogger,transaction:c,resolve:m,reject:f,cancelled:!1,startTime:(0,h.now)(),operationName:t.operationName,waitingLogged:!1,previousServer:t.previousServer},S=(0,h.addAbortListener)(t.signal,(function(){E.cancelled=!0,f(this.reason)}));this.waitQueue.push(E),_(this);try{r?.throwIfExpired();const e=await(r?Promise.race([p,r]):p);return t.timeoutContext?.csotEnabled()&&0!==e.description.minRoundTripTime&&(t.timeoutContext.minRoundTripTime=e.description.minRoundTripTime),e}catch(n){if(l.TimeoutError.is(n)){E.cancelled=!0;const n=new s.MongoServerSelectionError(`Server selection timed out after ${r?.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 y.ServerSelectionFailedEvent(e,this.description,n,t.operationName)),t.timeoutContext?.csotEnabled())throw new s.MongoOperationTimeoutError("Timed out during server selection",{cause:n});throw n}throw n}finally{S?.[h.kDispose](),t.timeoutContext?.clearServerSelectionTimeout&&r?.clear()}}serverUpdateHandler(e){if(!this.s.description.hasServer(e.address))return;if(function(e,t){const n=e.servers.get(t.address),r=n?.topologyVersion;return(0,f.compareTopologyVersion)(r,t.topologyVersion)>0}(this.s.description,e))return;const t=this.s.description,n=this.s.description.servers.get(e.address);if(!n)return;const r=e.$clusterTime;r&&(0,d._advanceClusterTime)(this,r);const o=n&&n.equals(e);if(this.s.description=this.s.description.update(e),this.s.description.compatibilityError)this.emit(v.ERROR,new s.MongoCompatibilityError(this.s.description.compatibilityError));else{if(!o){const t=this.s.description.servers.get(e.address);t&&this.emit(v.SERVER_DESCRIPTION_CHANGED,new p.ServerDescriptionChangedEvent(this.s.id,e.address,n,t))}M(this,e),this.waitQueue.length>0&&_(this),o||this.emitAndLog(v.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===d.STATE_CONNECTED}isDestroyed(){return this.s.state===d.STATE_CLOSED}lastHello(){const e=Array.from(this.description.servers.values());return 0===e.length?{}:e.filter((e=>e.type!==d.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 b(e,t){for(const t of i.LOCAL_SERVER_EVENTS)e.removeAllListeners(t);e.close(),t.emitAndLog(v.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(v.SERVER_OPENING,new p.ServerOpeningEvent(e.s.id,t.address));const n=new m.Server(e,t,e.s.options);for(const t of i.SERVER_RELAY_EVENTS)n.on(t,(n=>e.emit(t,n)));return n.on(m.Server.DESCRIPTION_RECEIVED,(t=>e.serverUpdateHandler(t))),n.connect(),n}function M(e,t){if(t&&e.s.servers.has(t.address)){const n=e.s.servers.get(t.address);if(n)if(n.s.description=t,t.error instanceof s.MongoError&&t.error.hasErrorLabel(s.MongoErrorLabel.ResetPool)){const e=t.error.hasErrorLabel(s.MongoErrorLabel.InterruptInUseConnections);n.pool.clear({interruptInUseConnections:e})}else if(null==t.error){const r=e.s.description.type;(t.isDataBearing||t.type!==d.ServerType.Unknown&&r===d.TopologyType.Single)&&n.pool.ready()}}for(const t of e.description.servers.values())if(!e.s.servers.has(t.address)){const n=w(e,t);e.s.servers.set(t.address,n)}for(const t of e.s.servers){const n=t[0];if(e.description.hasServer(n))continue;if(!e.s.servers.has(n))continue;const r=e.s.servers.get(n);e.s.servers.delete(n),r&&b(r,e)}}function T(e,t){for(;e.length;){const n=e.shift();n&&(n.cancelled||(n.mongoLogger?.willLog(a.MongoLoggableComponent.SERVER_SELECTION,a.SeverityLevel.DEBUG)&&n.mongoLogger?.debug(a.MongoLoggableComponent.SERVER_SELECTION,new y.ServerSelectionFailedEvent(n.serverSelector,n.topologyDescription,t,n.operationName)),n.reject(t)))}}function _(e){if(e.s.state===d.STATE_CLOSED)return void T(e.waitQueue,new s.MongoTopologyClosedError);const t=e.description.type===d.TopologyType.Sharded,n=Array.from(e.description.servers.values()),o=e.waitQueue.length;for(let r=0;r<o;++r){const r=e.waitQueue.shift();if(!r)continue;if(r.cancelled)continue;let o,i;try{const t=r.serverSelector,i=r.previousServer;o=t?t(e.description,n,i?[i]:[]):n}catch(t){e.client.mongoLogger?.willLog(a.MongoLoggableComponent.SERVER_SELECTION,a.SeverityLevel.DEBUG)&&e.client.mongoLogger?.debug(a.MongoLoggableComponent.SERVER_SELECTION,new y.ServerSelectionFailedEvent(r.serverSelector,e.description,t,r.operationName)),r.reject(t);continue}if(0===o.length){r.waitingLogged||(e.client.mongoLogger?.willLog(a.MongoLoggableComponent.SERVER_SELECTION,a.SeverityLevel.INFORMATIONAL)&&e.client.mongoLogger?.info(a.MongoLoggableComponent.SERVER_SELECTION,new y.WaitingForSuitableServerEvent(r.serverSelector,e.description,0!==e.s.serverSelectionTimeoutMS?e.s.serverSelectionTimeoutMS-((0,h.now)()-r.startTime):-1,r.operationName)),r.waitingLogged=!0),e.waitQueue.push(r);continue}if(1===o.length)i=e.s.servers.get(o[0].address);else{const t=(0,h.shuffle)(o,2),n=e.s.servers.get(t[0].address),r=e.s.servers.get(t[1].address);i=n&&r&&n.s.operationCount<r.s.operationCount?n:r}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 y.ServerSelectionFailedEvent(r.serverSelector,e.description,t,r.operationName)),void r.reject(t)}const c=r.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 y.ServerSelectionSucceededEvent(r.serverSelector,r.topologyDescription,i.pool.address,r.operationName)),r.resolve(i)}if(e.waitQueue.length>0)for(const[,t]of e.s.servers)r.nextTick((function(){return t.requestCheck()}))}t.Topology=v,v.SERVER_OPENING=i.SERVER_OPENING,v.SERVER_CLOSED=i.SERVER_CLOSED,v.SERVER_DESCRIPTION_CHANGED=i.SERVER_DESCRIPTION_CHANGED,v.TOPOLOGY_OPENING=i.TOPOLOGY_OPENING,v.TOPOLOGY_CLOSED=i.TOPOLOGY_CLOSED,v.TOPOLOGY_DESCRIPTION_CHANGED=i.TOPOLOGY_DESCRIPTION_CHANGED,v.ERROR=i.ERROR,v.OPEN=i.OPEN,v.CONNECT=i.CONNECT,v.CLOSE=i.CLOSE,v.TIMEOUT=i.TIMEOUT;class A{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=A},3079:(e,t,n)=>{n.d(t,{_:()=>v});var r=n(66596);function o(e){const t=[];let n=-1,o=0,i=0;for(;++n<e.length;){const s=e.charCodeAt(n);let a="";if(37===s&&(0,r.lV)(e.charCodeAt(n+1))&&(0,r.lV)(e.charCodeAt(n+2)))i=2;else if(s<128)/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(s))||(a=String.fromCharCode(s));else if(s>55295&&s<57344){const t=e.charCodeAt(n+1);s<56320&&t>56319&&t<57344?(a=String.fromCharCode(s,t),i=1):a="�"}else a=String.fromCharCode(s);a&&(t.push(e.slice(o,n),encodeURIComponent(a)),o=n+i+1,a=""),i&&(n+=i,i=0)}return t.join("")+e.slice(o)}var i=n(38411),s=n(2563),a=n(73429);const c={}.hasOwnProperty;function u(e){return String(e||"").toUpperCase()}function l(e,t){const n=String(t.identifier).toUpperCase(),r=o(n.toLowerCase()),i=e.footnoteOrder.indexOf(n);let s;-1===i?(e.footnoteOrder.push(n),e.footnoteCounts[n]=1,s=e.footnoteOrder.length):(e.footnoteCounts[n]++,s=i+1);const a=e.footnoteCounts[n],c={type:"element",tagName:"a",properties:{href:"#"+e.clobberPrefix+"fn-"+r,id:e.clobberPrefix+"fnref-"+r+(a>1?"-"+a:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(s)}]};e.patch(t,c);const u={type:"element",tagName:"sup",properties:{},children:[c]};return e.patch(t,u),e.applyData(t,u)}function h(e,t){const n=t.referenceType;let r="]";if("collapsed"===n?r+="[]":"full"===n&&(r+="["+(t.label||t.identifier)+"]"),"imageReference"===t.type)return{type:"text",value:"!["+t.alt+r};const o=e.all(t),i=o[0];i&&"text"===i.type?i.value="["+i.value:o.unshift({type:"text",value:"["});const s=o[o.length-1];return s&&"text"===s.type?s.value+=r:o.push({type:"text",value:r}),o}function d(e){const t=e.spread;return null==t?e.children.length>1:t}var p=n(10743);const m={blockquote:function(e,t){const n={type:"element",tagName:"blockquote",properties:{},children:e.wrap(e.all(t),!0)};return e.patch(t,n),e.applyData(t,n)},break:function(e,t){const n={type:"element",tagName:"br",properties:{},children:[]};return e.patch(t,n),[e.applyData(t,n),{type:"text",value:"\n"}]},code:function(e,t){const n=t.value?t.value+"\n":"",r=t.lang?t.lang.match(/^[^ \t]+(?=[ \t]|$)/):null,o={};r&&(o.className=["language-"+r]);let i={type:"element",tagName:"code",properties:o,children:[{type:"text",value:n}]};return t.meta&&(i.data={meta:t.meta}),e.patch(t,i),i=e.applyData(t,i),i={type:"element",tagName:"pre",properties:{},children:[i]},e.patch(t,i),i},delete:function(e,t){const n={type:"element",tagName:"del",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)},emphasis:function(e,t){const n={type:"element",tagName:"em",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)},footnoteReference:l,footnote:function(e,t){const n=e.footnoteById;let r=1;for(;r in n;)r++;const o=String(r);return n[o]={type:"footnoteDefinition",identifier:o,children:[{type:"paragraph",children:t.children}],position:t.position},l(e,{type:"footnoteReference",identifier:o,position:t.position})},heading:function(e,t){const n={type:"element",tagName:"h"+t.depth,properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)},html:function(e,t){if(e.dangerous){const n={type:"raw",value:t.value};return e.patch(t,n),e.applyData(t,n)}return null},imageReference:function(e,t){const n=e.definition(t.identifier);if(!n)return h(e,t);const r={src:o(n.url||""),alt:t.alt};null!==n.title&&void 0!==n.title&&(r.title=n.title);const i={type:"element",tagName:"img",properties:r,children:[]};return e.patch(t,i),e.applyData(t,i)},image:function(e,t){const n={src:o(t.url)};null!==t.alt&&void 0!==t.alt&&(n.alt=t.alt),null!==t.title&&void 0!==t.title&&(n.title=t.title);const r={type:"element",tagName:"img",properties:n,children:[]};return e.patch(t,r),e.applyData(t,r)},inlineCode:function(e,t){const n={type:"text",value:t.value.replace(/\r?\n|\r/g," ")};e.patch(t,n);const r={type:"element",tagName:"code",properties:{},children:[n]};return e.patch(t,r),e.applyData(t,r)},linkReference:function(e,t){const n=e.definition(t.identifier);if(!n)return h(e,t);const r={href:o(n.url||"")};null!==n.title&&void 0!==n.title&&(r.title=n.title);const i={type:"element",tagName:"a",properties:r,children:e.all(t)};return e.patch(t,i),e.applyData(t,i)},link:function(e,t){const n={href:o(t.url)};null!==t.title&&void 0!==t.title&&(n.title=t.title);const r={type:"element",tagName:"a",properties:n,children:e.all(t)};return e.patch(t,r),e.applyData(t,r)},listItem:function(e,t,n){const r=e.all(t),o=n?function(e){let t=!1;if("list"===e.type){t=e.spread||!1;const n=e.children;let r=-1;for(;!t&&++r<n.length;)t=d(n[r])}return t}(n):d(t),i={},s=[];if("boolean"==typeof t.checked){const e=r[0];let n;e&&"element"===e.type&&"p"===e.tagName?n=e:(n={type:"element",tagName:"p",properties:{},children:[]},r.unshift(n)),n.children.length>0&&n.children.unshift({type:"text",value:" "}),n.children.unshift({type:"element",tagName:"input",properties:{type:"checkbox",checked:t.checked,disabled:!0},children:[]}),i.className=["task-list-item"]}let a=-1;for(;++a<r.length;){const e=r[a];(o||0!==a||"element"!==e.type||"p"!==e.tagName)&&s.push({type:"text",value:"\n"}),"element"!==e.type||"p"!==e.tagName||o?s.push(e):s.push(...e.children)}const c=r[r.length-1];c&&(o||"element"!==c.type||"p"!==c.tagName)&&s.push({type:"text",value:"\n"});const u={type:"element",tagName:"li",properties:i,children:s};return e.patch(t,u),e.applyData(t,u)},list:function(e,t){const n={},r=e.all(t);let o=-1;for("number"==typeof t.start&&1!==t.start&&(n.start=t.start);++o<r.length;){const e=r[o];if("element"===e.type&&"li"===e.tagName&&e.properties&&Array.isArray(e.properties.className)&&e.properties.className.includes("task-list-item")){n.className=["contains-task-list"];break}}const i={type:"element",tagName:t.ordered?"ol":"ul",properties:n,children:e.wrap(r,!0)};return e.patch(t,i),e.applyData(t,i)},paragraph:function(e,t){const n={type:"element",tagName:"p",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)},root:function(e,t){const n={type:"root",children:e.wrap(e.all(t))};return e.patch(t,n),e.applyData(t,n)},strong:function(e,t){const n={type:"element",tagName:"strong",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)},table:function(e,t){const n=e.all(t),r=n.shift(),o=[];if(r){const n={type:"element",tagName:"thead",properties:{},children:e.wrap([r],!0)};e.patch(t.children[0],n),o.push(n)}if(n.length>0){const r={type:"element",tagName:"tbody",properties:{},children:e.wrap(n,!0)},i=(0,s.PW)(t.children[1]),a=(0,s.Y)(t.children[t.children.length-1]);i.line&&a.line&&(r.position={start:i,end:a}),o.push(r)}const i={type:"element",tagName:"table",properties:{},children:e.wrap(o,!0)};return e.patch(t,i),e.applyData(t,i)},tableCell:function(e,t){const n={type:"element",tagName:"td",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)},tableRow:function(e,t,n){const r=n?n.children:void 0,o=0===(r?r.indexOf(t):1)?"th":"td",i=n&&"table"===n.type?n.align:void 0,s=i?i.length:t.children.length;let a=-1;const c=[];for(;++a<s;){const n=t.children[a],r={},s=i?i[a]:void 0;s&&(r.align=s);let u={type:"element",tagName:o,properties:r,children:[]};n&&(u.children=e.all(n),e.patch(n,u),u=e.applyData(t,u)),c.push(u)}const u={type:"element",tagName:"tr",properties:{},children:e.wrap(c,!0)};return e.patch(t,u),e.applyData(t,u)},text:function(e,t){const n={type:"text",value:(0,p.E)(String(t.value))};return e.patch(t,n),e.applyData(t,n)},thematicBreak:function(e,t){const n={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(t,n),e.applyData(t,n)},toml:f,yaml:f,definition:f,footnoteDefinition:f};function f(){return null}const g={}.hasOwnProperty;function y(e,t){e.position&&(t.position=(0,s.G1)(e))}function E(e,t){let n=t;if(e&&e.data){const t=e.data.hName,r=e.data.hChildren,o=e.data.hProperties;"string"==typeof t&&("element"===n.type?n.tagName=t:n={type:"element",tagName:t,properties:{},children:[]}),"element"===n.type&&o&&(n.properties={...n.properties,...o}),"children"in n&&n.children&&null!=r&&(n.children=r)}return n}function S(e,t,n){const r=t&&t.type;if(!r)throw new Error("Expected node, got `"+t+"`");return g.call(e.handlers,r)?e.handlers[r](e,t,n):e.passThrough&&e.passThrough.includes(r)?"children"in t?{...t,children:O(e,t)}:t:e.unknownHandler?e.unknownHandler(e,t,n):function(e,t){const n=t.data||{},r=!("value"in t)||g.call(n,"hProperties")||g.call(n,"hChildren")?{type:"element",tagName:"div",properties:{},children:O(e,t)}:{type:"text",value:t.value};return e.patch(t,r),e.applyData(t,r)}(e,t)}function O(e,t){const n=[];if("children"in t){const r=t.children;let o=-1;for(;++o<r.length;){const i=S(e,r[o],t);if(i){if(o&&"break"===r[o-1].type&&(Array.isArray(i)||"text"!==i.type||(i.value=i.value.replace(/^\s+/,"")),!Array.isArray(i)&&"element"===i.type)){const e=i.children[0];e&&"text"===e.type&&(e.value=e.value.replace(/^\s+/,""))}Array.isArray(i)?n.push(...i):n.push(i)}}}return n}function C(e,t){const n=[];let r=-1;for(t&&n.push({type:"text",value:"\n"});++r<e.length;)r&&n.push({type:"text",value:"\n"}),n.push(e[r]);return t&&e.length>0&&n.push({type:"text",value:"\n"}),n}function v(e,t){const n=function(e,t){const n=t||{},r=n.allowDangerousHtml||!1,o={};return h.dangerous=r,h.clobberPrefix=void 0===n.clobberPrefix||null===n.clobberPrefix?"user-content-":n.clobberPrefix,h.footnoteLabel=n.footnoteLabel||"Footnotes",h.footnoteLabelTagName=n.footnoteLabelTagName||"h2",h.footnoteLabelProperties=n.footnoteLabelProperties||{className:["sr-only"]},h.footnoteBackLabel=n.footnoteBackLabel||"Back to content",h.unknownHandler=n.unknownHandler,h.passThrough=n.passThrough,h.handlers={...m,...n.handlers},h.definition=function(e){const t=Object.create(null);if(!e||!e.type)throw new Error("mdast-util-definitions expected node");return(0,i.YR)(e,"definition",(e=>{const n=u(e.identifier);n&&!c.call(t,n)&&(t[n]=e)})),function(e){const n=u(e);return n&&c.call(t,n)?t[n]:null}}(e),h.footnoteById=o,h.footnoteOrder=[],h.footnoteCounts={},h.patch=y,h.applyData=E,h.one=function(e,t){return S(h,e,t)},h.all=function(e){return O(h,e)},h.wrap=C,h.augment=l,(0,i.YR)(e,"footnoteDefinition",(e=>{const t=String(e.identifier).toUpperCase();g.call(o,t)||(o[t]=e)})),h;function l(e,t){if(e&&"data"in e&&e.data){const n=e.data;n.hName&&("element"!==t.type&&(t={type:"element",tagName:"",properties:{},children:[]}),t.tagName=n.hName),"element"===t.type&&n.hProperties&&(t.properties={...t.properties,...n.hProperties}),"children"in t&&t.children&&n.hChildren&&(t.children=n.hChildren)}if(e){const n="type"in e?e:{position:e};(0,a.g)(n)||(t.position={start:(0,s.PW)(n),end:(0,s.Y)(n)})}return t}function h(e,t,n,r){return Array.isArray(n)&&(r=n,n={}),l(e,{type:"element",tagName:t,properties:n||{},children:r||[]})}}(e,t),r=n.one(e,null),l=function(e){const t=[];let n=-1;for(;++n<e.footnoteOrder.length;){const r=e.footnoteById[e.footnoteOrder[n]];if(!r)continue;const i=e.all(r),s=String(r.identifier).toUpperCase(),a=o(s.toLowerCase());let c=0;const u=[];for(;++c<=e.footnoteCounts[s];){const t={type:"element",tagName:"a",properties:{href:"#"+e.clobberPrefix+"fnref-"+a+(c>1?"-"+c:""),dataFootnoteBackref:!0,className:["data-footnote-backref"],ariaLabel:e.footnoteBackLabel},children:[{type:"text",value:"↩"}]};c>1&&t.children.push({type:"element",tagName:"sup",children:[{type:"text",value:String(c)}]}),u.length>0&&u.push({type:"text",value:" "}),u.push(t)}const l=i[i.length-1];if(l&&"element"===l.type&&"p"===l.tagName){const e=l.children[l.children.length-1];e&&"text"===e.type?e.value+=" ":l.children.push({type:"text",value:" "}),l.children.push(...u)}else i.push(...u);const h={type:"element",tagName:"li",properties:{id:e.clobberPrefix+"fn-"+a},children:e.wrap(i,!0)};e.patch(r,h),t.push(h)}if(0!==t.length)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:e.footnoteLabelTagName,properties:{...JSON.parse(JSON.stringify(e.footnoteLabelProperties)),id:"footnote-label"},children:[{type:"text",value:e.footnoteLabel}]},{type:"text",value:"\n"},{type:"element",tagName:"ol",properties:{},children:e.wrap(t,!0)},{type:"text",value:"\n"}]}}(n);return l&&r.children.push({type:"text",value:"\n"},l),Array.isArray(r)?{type:"root",children:r}:r}},3357:(e,t,n)=>{var r=n(33433),o=n(372);function i(e){this.rand=e||new o.Rand}e.exports=i,i.create=function(e){return new i(e)},i.prototype._randbelow=function(e){var t=e.bitLength(),n=Math.ceil(t/8);do{var o=new r(this.rand.generate(n))}while(o.cmp(e)>=0);return o},i.prototype._randrange=function(e,t){var n=t.sub(e);return e.add(this._randbelow(n))},i.prototype.test=function(e,t,n){var o=e.bitLength(),i=r.mont(e),s=new r(1).toRed(i);t||(t=Math.max(1,o/48|0));for(var a=e.subn(1),c=0;!a.testn(c);c++);for(var u=e.shrn(c),l=a.toRed(i);t>0;t--){var h=this._randrange(new r(2),a);n&&n(h);var d=h.toRed(i).redPow(u);if(0!==d.cmp(s)&&0!==d.cmp(l)){for(var p=1;p<c;p++){if(0===(d=d.redSqr()).cmp(s))return!1;if(0===d.cmp(l))break}if(p===c)return!1}}return!0},i.prototype.getDivisor=function(e,t){var n=e.bitLength(),o=r.mont(e),i=new r(1).toRed(o);t||(t=Math.max(1,n/48|0));for(var s=e.subn(1),a=0;!s.testn(a);a++);for(var c=e.shrn(a),u=s.toRed(o);t>0;t--){var l=this._randrange(new r(2),s),h=e.gcd(l);if(0!==h.cmpn(1))return h;var d=l.toRed(o).redPow(c);if(0!==d.cmp(i)&&0!==d.cmp(u)){for(var p=1;p<a;p++){if(0===(d=d.redSqr()).cmp(i))return d.fromRed().subn(1).gcd(e);if(0===d.cmp(u))break}if(p===a)return(d=d.redSqr()).fromRed().subn(1).gcd(e)}}return!1}},3906:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WaitingForSuitableServerEvent=t.ServerSelectionSucceededEvent=t.ServerSelectionFailedEvent=t.ServerSelectionStartedEvent=t.ServerSelectionEvent=void 0;const r=n(145),o=n(91869);class i{constructor(e,t,n){this.selector=e,this.operation=n,this.topologyDescription=t}}t.ServerSelectionEvent=i,t.ServerSelectionStartedEvent=class extends i{constructor(e,t,n){super(e,t,n),this.name=o.SERVER_SELECTION_STARTED,this.message="Server selection started"}},t.ServerSelectionFailedEvent=class extends i{constructor(e,t,n,r){super(e,t,r),this.name=o.SERVER_SELECTION_FAILED,this.message="Server selection failed",this.failure=n}},t.ServerSelectionSucceededEvent=class extends i{constructor(e,t,n,i){super(e,t,i),this.name=o.SERVER_SELECTION_SUCCEEDED,this.message="Server selection succeeded";const{host:s,port:a}=r.HostAddress.fromString(n).toHostPort();this.serverHost=s,this.serverPort=a}},t.WaitingForSuitableServerEvent=class extends i{constructor(e,t,n,r){super(e,t,r),this.name=o.WAITING_FOR_SUITABLE_SERVER,this.message="Waiting for suitable server to become available",this.remainingTimeMS=n}}},4313:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SrvPoller=t.SrvPollingEvent=void 0;const r=n(95136),o=n(37668),i=n(17562),s=n(4642),a=n(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 r.promises.resolveSrv(this.srvAddress)}catch{return void this.failure()}if(e!==this.generation)return;const n=[];for(const e of t)try{(0,a.checkParentDomainMatch)(e.name,this.srvHost),n.push(e)}catch(e){(0,a.squashError)(e)}n.length?this.success(n):this.failure()}}t.SrvPoller=u,u.SRV_RECORD_DISCOVERY="srvRecordDiscovery"},4429:(e,t,n)=>{n.d(t,{$Z:()=>s,AO:()=>f,Ay:()=>o,GH:()=>a,Kz:()=>p,Yr:()=>h,aN:()=>m,e1:()=>i,eH:()=>c,mj:()=>u,ol:()=>l,r4:()=>d,tf:()=>g});var r=n(25364);const o=r.default,i=r.DEFAULT_COLLATION,s=r.DEFAULT_FILTER,a=r.DEFAULT_HINT,c=r.DEFAULT_LIMIT,u=r.DEFAULT_MAX_TIME_MS,l=r.DEFAULT_PROJECT,h=r.DEFAULT_SKIP,d=r.DEFAULT_SORT,p=r.isCollationValid,m=(r.isFilterValid,r.isHintValid,r.isLimitValid,r.isMaxTimeMSValid,r.isProjectValid,r.isSkipValid,r.isSortValid,r.parseCollation,r.parseFilter),f=(r.parseProject,r.parseSort,r.stringify,r.toJSString),g=r.validate},4642:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CancellationToken=t.TypedEventEmitter=void 0;const r=n(8763),o=n(93347),i=n(145);class s extends r.EventEmitter{emitAndLog(e,...t){this.emit(e,...t),this.component&&this.mongoLogger?.debug(this.component,t[0])}emitAndLogHeartbeat(e,t,n,...r){if(this.emit(e,...r),this.component){const e={topologyId:t,serverConnectionId:n??null,...r[0]};this.mongoLogger?.debug(this.component,e)}}emitAndLogCommand(e,t,n,r,...i){if(e&&this.emit(t,...i),r){const e={databaseName:n,...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,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DeleteManyOperation=t.DeleteOneOperation=t.DeleteOperation=void 0,t.makeDeleteStatement=l;const r=n(75725),o=n(17562),i=n(78130),s=n(35394);class a extends i.CommandOperation{constructor(e,t,n){super(void 0,n),this.SERVER_COMMAND_RESPONSE_TYPE=r.MongoDBResponse,this.options=n,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 n=this.options,r="boolean"!=typeof n.ordered||n.ordered,i={delete:this.ns.collection,deletes:this.statements,ordered:r};if(n.let&&(i.let=n.let),void 0!==n.comment&&(i.comment=n.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,n){super(e,[l(t,{...n,limit:1})],n)}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,n){super(e,[l(t,n)],n)}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 n={q:e,limit:"number"==typeof t.limit?t.limit:0};return t.collation&&(n.collation=t.collation),t.hint&&(n.hint=t.hint),n}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,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DbStatsOperation=void 0;const r=n(75725),o=n(78130),i=n(35394);class s extends o.CommandOperation{constructor(e,t){super(e,t),this.SERVER_COMMAND_RESPONSE_TYPE=r.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,n)=>{var r=n(65994).e;Object.defineProperty(t,"__esModule",{value:!0}),t.Server=void 0;const o=n(71470),i=n(75755),s=n(76013),a=n(91869),c=n(17562),u=n(4642),l=n(62016),h=n(85759),d=n(145),p=n(40012),m=n(89167),f=n(57590),g=n(9188),y=n(30588),E=(0,d.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 S extends u.TypedEventEmitter{constructor(e,t,n){super(),this.on("error",d.noop),this.serverApi=n.serverApi;const r={hostAddress:t.hostAddress,...n};this.topology=e,this.pool=new i.ConnectionPool(this,r),this.s={description:t,options:n,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=>O(this,e))),this.monitor.on(S.SERVER_HEARTBEAT_SUCCEEDED,(e=>{this.emit(S.DESCRIPTION_RECEIVED,new g.ServerDescription(this.description.hostAddress,e.reply,{roundTripTime:this.monitor?.roundTripTime,minRoundTripTime:this.monitor?.minRoundTripTime})),this.s.state===m.STATE_CONNECTING&&(E(this,m.STATE_CONNECTED),this.emit(S.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&&(E(this,m.STATE_CONNECTING),this.loadBalanced?(E(this,m.STATE_CONNECTED),this.emit(S.CONNECT,this)):this.monitor?.connect())}closeCheckedOutConnections(){return this.pool.closeCheckedOutConnections()}close(){this.s.state!==m.STATE_CLOSED&&(E(this,m.STATE_CLOSING),this.loadBalanced||this.monitor?.close(),this.pool.close(),E(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 n=e.session;let r=n?.pinnedConnection;if(this.incrementOperationCount(),null==r)try{r=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(),n?.pinnedConnection!==r)if(null!=o){const e=()=>{this.pool.checkIn(r)};o.then(e,e)}else this.pool.checkIn(r)};let a;try{a=e.buildCommand(r,n)}catch(e){throw i(),e}const u=e.buildOptions(t),h=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,n)&&!n?.pinnedConnection&&n?.pin(r),u.directConnection=this.topology.s.options.directConnection,e instanceof l.AggregateOperation&&e.hasWriteStage&&(0,d.maxWireVersion)(r)<y.MIN_SECONDARY_WRITE_WIRE_VERSION&&delete u.readPreference,this.description.iscryptd&&(u.omitMaxTimeMS=!0);try{try{const t=await r.command(h,a,u,e.SERVER_COMMAND_RESPONSE_TYPE);return(0,p.throwIfWriteConcernError)(t),t}catch(e){throw this.decorateCommandError(r,a,u,e)}}catch(t){if(!(t instanceof c.MongoError&&t.code===c.MONGODB_ERROR_CODES.Reauthenticate))throw t;o=this.pool.reauthenticate(r),o.then(void 0,(e=>{o=null,(0,d.squashError)(e)})),await(0,d.abortable)(o,u),o=null;try{const t=await r.command(h,a,u,e.SERVER_COMMAND_RESPONSE_TYPE);return(0,p.throwIfWriteConcernError)(t),t}catch(e){throw this.decorateCommandError(r,a,u,e)}}finally{i()}}handleError(e,t){if(!(e instanceof c.MongoError))return;if(e.connectionGeneration&&e.connectionGeneration<this.pool.generation)return;const n=e instanceof c.MongoNetworkError&&!(e instanceof c.MongoNetworkTimeoutError),o=e instanceof c.MongoNetworkError&&e.beforeHandshake,i=e.hasErrorLabel(c.MongoErrorLabel.HandshakeError);if(n||o||i)this.loadBalanced?t&&this.pool.clear({serviceId:t.serviceId}):(e.addErrorLabel(c.MongoErrorLabel.ResetPool),O(this,e));else if((0,c.isSDAMUnrecoverableError)(e)&&function(e,t){const n=t.topologyVersion,r=e.description.topologyVersion;return(0,g.compareTopologyVersion)(r,n)<0}(this,e)){const n=(0,d.maxWireVersion)(this)<=7||(0,c.isNodeShuttingDownError)(e);this.loadBalanced&&t&&n&&this.pool.clear({serviceId:t.serviceId}),this.loadBalanced||(n&&e.addErrorLabel(c.MongoErrorLabel.ResetPool),O(this,e),r.nextTick((()=>this.requestCheck())))}}decorateCommandError(e,t,n,r){if("object"!=typeof r||null==r||!("name"in r))throw new c.MongoRuntimeError("An unexpected error type: "+typeof r);if("AbortError"===r.name&&"cause"in r&&r.cause instanceof c.MongoError&&(r=r.cause),!(r instanceof c.MongoError))return r;if(function(e,t){return t.serviceId?t.generation!==e.serviceGenerations.get(t.serviceId.toHexString()):t.generation!==e.generation}(this.pool,e))return r;const o=n?.session;return r instanceof c.MongoNetworkError?(o&&!o.hasEnded&&o.serverSession&&(o.serverSession.isDirty=!0),C(o,t)&&!r.hasErrorLabel(c.MongoErrorLabel.TransientTransactionError)&&r.addErrorLabel(c.MongoErrorLabel.TransientTransactionError),(v(this.topology)||(0,h.isTransactionCommand)(t))&&(0,d.supportsRetryableWrites)(this)&&!C(o,t)&&r.addErrorLabel(c.MongoErrorLabel.RetryableWriteError)):(v(this.topology)||(0,h.isTransactionCommand)(t))&&(0,c.needsRetryableWriteLabel)(r,(0,d.maxWireVersion)(this),this.description.type)&&!C(o,t)&&r.addErrorLabel(c.MongoErrorLabel.RetryableWriteError),o&&o.isPinned&&r.hasErrorLabel(c.MongoErrorLabel.TransientTransactionError)&&o.unpin({force:!0}),this.handleError(r,e),r}decrementOperationCount(){return this.s.operationCount-=1}incrementOperationCount(){return this.s.operationCount+=1}}function O(e,t){e.loadBalanced||(t instanceof c.MongoNetworkError&&!(t instanceof c.MongoNetworkTimeoutError)&&e.monitor?.reset(),e.emit(S.DESCRIPTION_RECEIVED,new g.ServerDescription(e.description.hostAddress,void 0,{error:t})))}function C(e,t){return e&&e.inTransaction()&&!(0,h.isTransactionCommand)(t)}function v(e){return!1!==e.s.options.retryWrites}t.Server=S,S.SERVER_HEARTBEAT_STARTED=a.SERVER_HEARTBEAT_STARTED,S.SERVER_HEARTBEAT_SUCCEEDED=a.SERVER_HEARTBEAT_SUCCEEDED,S.SERVER_HEARTBEAT_FAILED=a.SERVER_HEARTBEAT_FAILED,S.CONNECT=a.CONNECT,S.DESCRIPTION_RECEIVED=a.DESCRIPTION_RECEIVED,S.CLOSED=a.CLOSED,S.ENDED=a.ENDED},5465:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.FindCursor=t.FLAGS=void 0;const r=n(75725),o=n(17562),i=n(36411),s=n(17172),a=n(96357),c=n(50440),u=n(30770),l=n(145),h=n(36649);t.FLAGS=["tailable","oplogReplay","noCursorTimeout","awaitData","exhaust","partial"];class d extends h.ExplainableCursor{constructor(e,t,n={},r={}){super(e,t,r),this.numReturned=0,this.cursorFilter=n,this.findOptions=r,null!=r.sort&&(this.findOptions.sort=(0,u.formatSort)(r.sort))}clone(){const e=(0,l.mergeOptions)({},this.findOptions);return delete e.session,new d(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 n=new c.FindOperation(this.namespace,this.cursorFilter,t),r=await(0,a.executeOperation)(this.client,n,this.timeoutContext);return this.numReturned=r.batchSize,{server:n.server,session:e,response:r}}async getMore(e){const t=this.numReturned;if(t){const n=this.findOptions.limit;if((e=n&&n>0&&t+e>n?n-t:e)<=0){try{await this.close()}catch(e){(0,l.squashError)(e)}return r.CursorResponse.emptyGetMore}}const n=await super.getMore(e);return this.numReturned=this.numReturned+n.batchSize,n}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:n,timeout:r}=this.resolveExplainTimeoutOptions(e,t);return(await(0,a.executeOperation)(this.client,new c.FindOperation(this.namespace,this.cursorFilter,{...this.findOptions,...this.cursorOptions,...r,explain:n??!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=d},6875:(e,t,n)=>{var r=n(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 d.MongoAPIError('Option "srvHost" must not be empty');const t=e.srvHost,n=T(t);n.then(void 0,E.squashError);const r=`_${e.srvServiceName}._tcp.${t}`,o=await M(r);if(0===o.length)throw new d.MongoAPIError("No addresses found at host");for(const{name:e}of o)(0,E.checkParentDomainMatch)(e,t);const i=o.map((e=>E.HostAddress.fromString(`${e.name}:${e.port??27017}`)));let u;x(i,e,!0);try{u=await n}catch(e){if("ENODATA"!==e.code&&"ENOTFOUND"!==e.code)throw e;return i}if(u.length>1)throw new d.MongoParseError("Multiple text records not allowed");const l=new s.URLSearchParams(u[0].join(""));if([...l.keys()].some((e=>!O.includes(e))))throw new d.MongoParseError(`Text record may only set any of: ${O.join(", ")}`);if(O.some((e=>""===l.get(e))))throw new d.MongoParseError("Cannot have empty URI params in DNS TXT Record");const h=l.get("authSource")??void 0,p=l.get("replicaSet")??void 0,m=l.get("loadBalanced")??void 0;if(!e.userSpecifiedAuthSource&&h&&e.credentials&&!c.AUTH_MECHS_AUTH_SRC_EXTERNAL.has(e.credentials.mechanism)&&(e.credentials=a.MongoCredentials.merge(e.credentials,{source:h})),!e.userSpecifiedReplicaSet&&p&&(e.replicaSet=p),"true"===m&&(e.loadBalanced=!0),e.replicaSet&&e.srvMaxHosts>0)throw new d.MongoParseError("Cannot combine replicaSet option with srvMaxHosts");return x(i,e,!0),i},t.parseOptions=function(e,n=void 0,o={}){if(null==n||n instanceof p.MongoClient||(o=n,n=void 0),o.useBigInt64&&"boolean"==typeof o.promoteLongs&&!o.promoteLongs)throw new d.MongoAPIError("Must request either bigint or Long for int64 deserialization");if(o.useBigInt64&&"boolean"==typeof o.promoteValues&&!o.promoteValues)throw new d.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(E.HostAddress.fromString);const y=new I;if("/"!==s.pathname&&""!==s.pathname){const e=decodeURIComponent("/"===s.pathname[0]?s.pathname.slice(1):s.pathname);e&&y.set("dbName",[e])}if(""!==s.username){const e={username:decodeURIComponent(s.username)};"string"==typeof s.password&&(e.password=decodeURIComponent(s.password)),y.set("auth",[e])}for(const e of s.searchParams.keys()){const t=s.searchParams.getAll(e),n=/readPreferenceTags/i.test(e);if(!n&&t.length>1)throw new d.MongoInvalidArgumentError(`URI option "${e}" cannot appear more than once in the connection string`);if(!n&&t.includes(""))throw new d.MongoAPIError(`URI option "${e}" cannot be specified with no value`);y.has(e)||y.set(e,t)}const S=new I(Object.entries(o).filter((([,e])=>null!=e)));if(y.has("serverApi"))throw new d.MongoParseError("URI cannot contain `serverApi`, it can only be passed to the client");const O=y.get("authMechanismProperties");if(O)for(const e of O)if(/(^|,)ALLOWED_HOSTS:/.test(e))throw new d.MongoParseError("Auth mechanism property ALLOWED_HOSTS is not allowed in the connection string.");if(S.has("loadBalanced"))throw new d.MongoParseError("loadBalanced is only a valid option in the URI");const C=new I,v=new Set([...y.keys(),...S.keys()]);for(const e of v){const t=[],n=S.get(e);null!=n&&t.push(n);const r=y.get(e)??[];t.push(...r),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 d.MongoParseError("All values of tls/ssl must be the same.")}!function(e){if(!e)return;const t=(t,n)=>{if(e.has(t)&&e.has(n))throw new d.MongoAPIError(`The '${t}' option cannot be used with the '${n}' option`)};t("tlsInsecure","tlsAllowInvalidCertificates"),t("tlsInsecure","tlsAllowInvalidHostnames")}(C);const b=(0,E.setDifference)(v,Array.from(Object.keys(t.OPTIONS)).map((e=>e.toLowerCase())));if(0!==b.size){const e=b.size>1?"options":"option",t=b.size>1?"are":"is";throw new d.MongoParseError(`${e} ${Array.from(b).join(", ")} ${t} not supported`)}for(const[e,n]of Object.entries(t.OPTIONS)){const r=C.get(e);if(r&&0!==r.length){const{deprecated:t}=n;if(t){const n="string"==typeof t?`: ${t}`:"";(0,E.emitWarning)(`${e} is a deprecated option${n}`)}P(g,e,n,r)}else t.DEFAULT_OPTIONS.has(e)&&P(g,e,n,[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,n=g.credentials.mechanism===c.AuthMechanism.MONGODB_AWS,r=g.credentials.mechanism===c.AuthMechanism.MONGODB_OIDC;if((e||t)&&C.has("authSource")&&"$external"!==g.credentials.source)throw new d.MongoParseError(`authMechanism ${g.credentials.mechanism} requires an authSource of '$external'`);if(e||t||n||r||!g.dbName||C.has("authSource")||(g.credentials=a.MongoCredentials.merge(g.credentials,{source:g.dbName})),n&&g.credentials.username&&!g.credentials.password)throw new d.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"),x(l,g,f),n&&g.autoEncryption&&(h.Encrypter.checkForMongoCrypt(),g.encrypter=new h.Encrypter(n,e,o),g.autoEncrypter=g.encrypter.autoEncrypter),g.userSpecifiedAuthSource=S.has("authSource")||y.has("authSource"),g.userSpecifiedReplicaSet=S.has("replicaSet")||y.has("replicaSet"),f){if(g.srvHost=l[0],g.directConnection)throw new d.MongoAPIError("SRV URI does not support directConnection");if(g.srvMaxHosts>0&&"string"==typeof g.replicaSet)throw new d.MongoParseError("Cannot use srvMaxHosts option with replicaSet");const e=!S.has("tls")&&!y.has("tls"),t=!S.has("ssl")&&!y.has("ssl");e&&t&&(g.tls=!0)}else if(y.has("srvMaxHosts")||S.has("srvMaxHosts")||y.has("srvServiceName")||S.has("srvServiceName"))throw new d.MongoParseError("Cannot use srvMaxHosts or srvServiceName with a non-srv connection string");if(g.directConnection&&1!==g.hosts.length)throw new d.MongoParseError("directConnection option requires exactly one host");if(!g.proxyHost&&(g.proxyPort||g.proxyUsername||g.proxyPassword))throw new d.MongoParseError("Must specify proxyHost if other proxy options are passed");if(g.proxyUsername&&!g.proxyPassword||!g.proxyUsername&&g.proxyPassword)throw new d.MongoParseError("Can only specify both of proxy username/password or neither");if(["proxyHost","proxyPort","proxyUsername","proxyPassword"].map((e=>y.get(e)??[])).some((e=>e.length>1)))throw new d.MongoParseError("Proxy options cannot be specified multiple times in the connection string");return g.mongoLoggerOptions=m.MongoLogger.resolveOptions({MONGODB_LOG_COMMAND:r.env.MONGODB_LOG_COMMAND,MONGODB_LOG_TOPOLOGY:r.env.MONGODB_LOG_TOPOLOGY,MONGODB_LOG_SERVER_SELECTION:r.env.MONGODB_LOG_SERVER_SELECTION,MONGODB_LOG_CONNECTION:r.env.MONGODB_LOG_CONNECTION,MONGODB_LOG_CLIENT:r.env.MONGODB_LOG_CLIENT,MONGODB_LOG_ALL:r.env.MONGODB_LOG_ALL,MONGODB_LOG_MAX_DOCUMENT_LENGTH:r.env.MONGODB_LOG_MAX_DOCUMENT_LENGTH,MONGODB_LOG_PATH:r.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,E.squashError),g};const o=n(95136),i=n(65031),s=n(9606),a=n(91566),c=n(93065),u=n(56463),l=n(64515),h=n(48758),d=n(17562),p=n(22220),m=n(93347),f=n(28541),g=n(13700),y=n(57590),E=n(145),S=n(40012),O=["authSource","replicaSet","loadBalanced"],C="loadBalanced option only supported with a single host in the URI",v="loadBalanced option not supported with a replicaSet option",b="loadBalanced option not supported when directConnection is provided";function w(e){return async function(t){try{return await o.promises[e](t)}catch(n){if(n.code===o.TIMEOUT)return await o.promises[e](t);throw n}}}const M=w("resolveSrv"),T=w("resolveTxt");function _(e,t){if("boolean"==typeof t)return t;switch(t){case"true":return!0;case"false":return!1;default:throw new d.MongoParseError(`${e} must be either "true" or "false"`)}}function A(e,t){const n=(0,E.parseInteger)(t);if(null!=n)return n;throw new d.MongoParseError(`Expected ${e} to be stringified int value, got: ${t}`)}function R(e,t){const n=A(e,t);if(n<0)throw new d.MongoParseError(`${e} can only be a positive int value, got: ${t}`);return n}function*N(e){if(""===e)return;const t=e.split(",");for(const e of t){const[t,n]=e.split(/:(.*)/);if(null==n)throw new d.MongoParseError("Cannot have undefined values in key value pairs");yield[t,n]}}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 x(e,t,n){if(t.loadBalanced){if(e.length>1)throw new d.MongoParseError(C);if(t.replicaSet)throw new d.MongoParseError(v);if(t.directConnection)throw new d.MongoParseError(b);if(n&&t.srvMaxHosts>0)throw new d.MongoParseError("Cannot limit srv hosts with loadBalanced enabled")}}function P(e,t,n,r){const{target:o,type:i,transform:s}=n,a=o??t;switch(i){case"boolean":e[a]=_(a,r[0]);break;case"int":e[a]=A(a,r[0]);break;case"uint":e[a]=R(a,r[0]);break;case"string":if(null==r[0])break;e[a]=String(r[0]);break;case"record":if(!(0,E.isRecord)(r[0]))throw new d.MongoParseError(`${a} must be an object`);e[a]=r[0];break;case"any":e[a]=r[0];break;default:{if(!s)throw new d.MongoParseError("Descriptors missing a type must define a transform");const t=s({name:a,options:e,values:r});e[a]=t;break}}}t.OPTIONS={appName:{type:"string"},auth:{target:"credentials",transform({name:e,options:t,values:[n]}){if(!(0,E.isRecord)(n,["username","password"]))throw new d.MongoParseError(`${e} must be an object with 'username' and 'password' properties`);return a.MongoCredentials.merge(t.credentials,{username:n.username,password:n.password})}},authMechanism:{target:"credentials",transform({options:e,values:[t]}){const n=Object.values(c.AuthMechanism),[r]=n.filter((e=>e.match(RegExp(String.raw`\b${t}\b`,"i"))));if(!r)throw new d.MongoParseError(`authMechanism one of ${n}, got ${t}`);let o=e.credentials?.source;(r===c.AuthMechanism.MONGODB_PLAIN||c.AUTH_MECHS_AUTH_SRC_EXTERNAL.has(r))&&(o="$external");let i=e.credentials?.password;return r===c.AuthMechanism.MONGODB_X509&&""===i&&(i=void 0),a.MongoCredentials.merge(e.credentials,{mechanism:r,source:o,password:i})}},authMechanismProperties:{target:"credentials",transform({options:e,values:t}){let n=Object.create(null);for(const e of t)if("string"==typeof e)for(const[t,r]of N(e))try{n[t]=_(t,r)}catch{n[t]=r}else{if(!(0,E.isRecord)(e))throw new d.MongoParseError("AuthMechanismProperties must be an object");n={...e}}return a.MongoCredentials.merge(e.credentials,{mechanismProperties:n})}},authSource:{target:"credentials",transform({options:e,values:[t]}){const n=String(t);return a.MongoCredentials.merge(e.credentials,{source:n})}},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,n=t&&t.version;if(!n)throw new d.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===n)))throw new d.MongoParseError(`Invalid server API version=${n}; 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 n of e){const e="string"==typeof n?n.split(","):n;if(!Array.isArray(e))throw new d.MongoInvalidArgumentError("compressors must be an array or a comma-delimited list of strings");for(const n of e){if(!Object.keys(l.Compressor).includes(String(n)))throw new d.MongoInvalidArgumentError(`${n} is not a valid compression mechanism. Must be one of: ${Object.keys(l.Compressor)}.`);t.add(String(n))}}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 n=A(e,t);if(4===n||6===n)return n;throw new d.MongoParseError(`Option 'family' must be 4 or 6 got ${n}.`)}},fieldsAsRaw:{type:"record"},forceServerObjectId:{default:!1,type:"boolean"},fsync:{deprecated:"Please use journal instead",target:"writeConcern",transform({name:e,options:t,values:[n]}){const r=S.WriteConcern.fromOptions({writeConcern:{...t.writeConcern,fsync:_(e,n)}});if(!r)throw new d.MongoParseError(`Unable to make a writeConcern from fsync=${n}`);return r}},heartbeatFrequencyMS:{default:1e4,type:"uint"},ignoreUndefined:{type:"boolean"},j:{deprecated:"Please use journal instead",target:"writeConcern",transform({name:e,options:t,values:[n]}){const r=S.WriteConcern.fromOptions({writeConcern:{...t.writeConcern,journal:_(e,n)}});if(!r)throw new d.MongoParseError(`Unable to make a writeConcern from journal=${n}`);return r}},journal:{target:"writeConcern",transform({name:e,options:t,values:[n]}){const r=S.WriteConcern.fromOptions({writeConcern:{...t.writeConcern,journal:_(e,n)}});if(!r)throw new d.MongoParseError(`Unable to make a writeConcern from journal=${n}`);return r}},loadBalanced:{default:!1,type:"boolean"},localThresholdMS:{default:15,type:"uint"},maxConnecting:{default:2,transform({name:e,values:[t]}){const n=R(e,t);if(0===n)throw new d.MongoInvalidArgumentError("maxConnecting must be > 0 if specified");return n}},maxIdleTimeMS:{default:0,type:"uint"},maxPoolSize:{default:100,type:"uint"},maxStalenessSeconds:{target:"readPreference",transform({name:e,options:t,values:[n]}){const r=R(e,n);return t.readPreference?g.ReadPreference.fromOptions({readPreference:{...t.readPreference,maxStalenessSeconds:r}}):new g.ReadPreference("secondary",void 0,{maxStalenessSeconds:r})}},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:E.DEFAULT_PK_FACTORY,transform({values:[e]}){if((0,E.isRecord)(e,["createPk"])&&"function"==typeof e.createPk)return e;throw new d.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,E.isRecord)(e,["level"]))return f.ReadConcern.fromOptions({...t.readConcern,...e});throw new d.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,E.isRecord)(e,["mode"])){const n=g.ReadPreference.fromOptions({readPreference:{...t.readPreference,...e},...e});if(n)return n;throw new d.MongoParseError(`Cannot make read preference from ${JSON.stringify(e)}`)}if("string"==typeof e){const n={hedge:t.readPreference?.hedge,maxStalenessSeconds:t.readPreference?.maxStalenessSeconds};return new g.ReadPreference(e,t.readPreference?.tags,n)}throw new d.MongoParseError(`Unknown ReadPreference value: ${e}`)}},readPreferenceTags:{target:"readPreference",transform({values:e,options:t}){const n=Array.isArray(e[0])?e[0]:e,r=[];for(const e of n){const t=Object.create(null);if("string"==typeof e)for(const[n,r]of N(e))t[n]=r;if((0,E.isRecord)(e))for(const[n,r]of Object.entries(e))t[n]=r;r.push(t)}return g.ReadPreference.fromOptions({readPreference:t.readPreference,readPreferenceTags:r})}},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(y.ServerMonitoringMode).includes(e))throw new d.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:[n]}){const r=_(e,n);return r?(t.checkServerIdentity=()=>{},t.rejectUnauthorized=!1):(t.checkServerIdentity=t.tlsAllowInvalidHostnames?()=>{}:void 0,t.rejectUnauthorized=!t.tlsAllowInvalidCertificates),r}},w:{target:"writeConcern",transform:({values:[e],options:t})=>S.WriteConcern.fromOptions({writeConcern:{...t.writeConcern,w:e}})},waitQueueTimeoutMS:{default:0,type:"uint"},writeConcern:{target:"writeConcern",transform({values:[e],options:t}){if((0,E.isRecord)(e)||e instanceof S.WriteConcern)return S.WriteConcern.fromOptions({writeConcern:{...t.writeConcern,...e}});if("majority"===e||"number"==typeof e)return S.WriteConcern.fromOptions({writeConcern:{...t.writeConcern,w:e}});throw new d.MongoParseError(`Invalid WriteConcern cannot parse: ${JSON.stringify(e)}`)}},wtimeout:{deprecated:"Please use wtimeoutMS instead",target:"writeConcern",transform({values:[e],options:t}){const n=S.WriteConcern.fromOptions({writeConcern:{...t.writeConcern,wtimeout:R("wtimeout",e)}});if(n)return n;throw new d.MongoParseError("Cannot make WriteConcern from wtimeout")}},wtimeoutMS:{target:"writeConcern",transform({values:[e],options:t}){const n=S.WriteConcern.fromOptions({writeConcern:{...t.writeConcern,wtimeoutMS:R("wtimeoutMS",e)}});if(n)return n;throw new d.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 d.MongoAPIError("Option 'mongodbLogPath' must be of type 'stderr' | 'stdout' | MongoDBLogWritable");return e}},mongodbLogComponentSeverities:{transform({values:[e]}){if("object"!=typeof e||!e)throw new d.MongoAPIError("Option 'mongodbLogComponentSeverities' must be a non-null object");for(const[t,n]of Object.entries(e)){if("string"!=typeof n||"string"!=typeof t)throw new d.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 d.MongoAPIError(`User input for option 'mongodbLogComponentSeverities' contains invalid key: ${t}`);if(!Object.values(m.SeverityLevel).some((e=>e===n)))throw new d.MongoAPIError(`Option 'mongodbLogComponentSeverities' does not support ${n} 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,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ClientBulkWriteResultsMerger=void 0;const r=n(16360),o=n(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(n){if(!(n instanceof r.MongoWriteConcernError))throw n;{const r=n.result;if(t={insertedCount:r.nInserted,upsertedCount:r.nUpserted,matchedCount:r.nMatched,modifiedCount:r.nModified,deletedCount:r.nDeleted,writeConcernError:r.writeConcernError},this.options.verboseResults&&r.cursor.firstBatch)for(const t of r.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 n=e.operations[t.idx];if("insert"in n&&this.result.insertResults?.set(t.idx+this.currentBatchOffset,{insertedId:n.document._id}),"update"in n){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 n&&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,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ClientBulkWriteCursor=void 0;const r=n(34080),o=n(96357),i=n(145),s=n(61066);class a extends s.AbstractCursor{constructor(e,t,n={}){super(e,new i.MongoDBNamespace("admin","$cmd"),n),this.commandBuilder=t,this.clientBulkWriteOptions=n}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 r.ClientBulkWriteOperation(this.commandBuilder,{...this.clientBulkWriteOptions,...this.cursorOptions,session:e}),n=await(0,o.executeOperation)(this.client,t,this.timeoutContext);return this.cursorResponse=n,{server:t.server,session:e,response:n}}}t.ClientBulkWriteCursor=a},7799:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.LegacyTimeoutContext=t.CSOTTimeoutContext=t.TimeoutContext=t.Timeout=t.TimeoutError=void 0;const r=n(37668),o=n(17562),i=n(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 n=t?.duration??0,a=!!t?.unref,c=t?.rejection;if(n<0)throw new o.MongoInvalidArgumentError("Cannot create a Timeout with a negative duration");let u;super(((t,n)=>{u=n,e(i.noop,n)})),this.ended=null,this.timedOut=!1,this.cleared=!1,this.duration=n,this.start=Math.trunc(performance.now()),null==c&&this.duration>0?(this.id=(0,r.setTimeout)((()=>{this.ended=Math.trunc(performance.now()),this.timedOut=!0,u(new s(`Expired after ${n}ms`,{duration:n}))}),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,r.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 n=this.remainingTimeMS-this.minRoundTripTime;n>0&&Number.isFinite(n)&&(e.maxTimeMS=n)}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,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TokenCache=void 0;const r=n(17562);class o extends r.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,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.aws4=void 0,t.getKerberos=function(){let e;try{e=n(96751)}catch(t){e=o(new r.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=n(96751)}catch(t){e=o(new r.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 n(96751)}catch(e){return o(new r.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 n(96751)}catch(e){return o(new r.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 n(96751)}catch(e){return{kModuleError:new r.MongoMissingDependencyError("Optional module `snappy` not found. Please install it to enable snappy compression",{cause:e,dependencyName:"snappy"})}}},t.getSocks=function(){try{return n(96751)}catch(e){return{kModuleError:new r.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=n(96751)}catch(e){return{kModuleError:new r.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 r=n(17562);function o(e){return new Proxy(e?{kModuleError:e}:{},{get:(t,n)=>{if("kModuleError"===n)return e;throw e},set:()=>{throw e}})}t.aws4=function(){let e;try{e=n(96751)}catch(t){e=o(new r.MongoMissingDependencyError("Optional module `aws4` not found. Please install it to enable AWS authentication",{cause:t,dependencyName:"aws4"}))}return e}()},9188:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ServerDescription=void 0,t.parseServerType=u,t.compareTopologyVersion=l;const r=n(75080),o=n(17562),i=n(145),s=n(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 n="bigint"==typeof e.counter?r.Long.fromBigInt(e.counter):r.Long.isLong(e.counter)?e.counter:r.Long.fromNumber(e.counter),o="bigint"==typeof t.counter?r.Long.fromBigInt(t.counter):r.Long.isLong(t.counter)?t.counter:r.Long.fromNumber(t.counter);return n.compare(o)}t.ServerDescription=class{constructor(e,t,n={}){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,n),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=n?.roundTripTime??-1,this.minRoundTripTime=n?.minRoundTripTime??0,this.lastUpdateTime=(0,i.now)(),this.lastWriteDate=t?.lastWrite?.lastWriteDate??0,this.error=n.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),n=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 n=Object.keys(e),r=Object.keys(t);return n.length===r.length&&n.every((n=>t[n]===e[n]))}(this.tags,e.tags)&&this.setName===e.setName&&this.setVersion===e.setVersion&&n&&this.primary===e.primary&&this.logicalSessionTimeoutMinutes===e.logicalSessionTimeoutMinutes&&t}}},9284:(e,t,n)=>{var r=n(9606).URL;Object.defineProperty(t,"__esModule",{value:!0}),t.callback=void 0;const o=n(17562),i=n(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 r("http://metadata/computeMetadata/v1/instance/service-accounts/default/identity");t.searchParams.append("audience",e);const n=await(0,i.get)(t,{headers:s});if(200!==n.status)throw new o.MongoGCPError(`Status code ${n.status} returned from the GCP endpoint. Response body: ${n.body}`);return{accessToken:n.body}}(t)}},9326:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.InsertOneOperation=t.InsertOperation=void 0;const r=n(75725),o=n(17562),i=n(145),s=n(78130),a=n(35394);class c extends s.CommandOperation{constructor(e,t,n){super(void 0,n),this.SERVER_COMMAND_RESPONSE_TYPE=r.MongoDBResponse,this.options={...n,checkKeys:n.checkKeys??!1},this.ns=e,this.documents=t}get commandName(){return"insert"}buildCommandDocument(e,t){const n=this.options??{},r="boolean"!=typeof n.ordered||n.ordered,o={insert:this.ns.collection,documents:this.documents,ordered:r};return"boolean"==typeof n.bypassDocumentValidation&&(o.bypassDocumentValidation=n.bypassDocumentValidation),void 0!==n.comment&&(o.comment=n.comment),o}}t.InsertOperation=c;class u extends c{constructor(e,t,n){super(e.s.namespace,[(0,i.maybeAddIdToDocuments)(e,t,n)],n)}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])},9651:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ParseMode=void 0,t.parse=a;const r=n(84537),o=n(40967),i=n(54553),s=n(86577);function a(e,t){const n=(0,s.buildOptions)(t),{hasComments:a,ast:c}=function(e){let t=!1;return{ast:(0,r.parse)(e,{ecmaVersion:6,onComment:()=>t=!0,locations:!0,ranges:!0,sourceFile:e}),hasComments:t}}(`(\n${e}\n)`);return a&&!n.allowComments||!(0,o.checkTree)(c,n)?"":(0,i.executeAST)(c)}Object.defineProperty(t,"ParseMode",{enumerable:!0,get:function(){return s.ParseMode}}),t.default=a},10089:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.UnorderedBulkOperation=void 0;const r=n(75080),o=n(17562),i=n(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 n=r.calculateObjectSize(t,{checkKeys:!1,ignoreUndefined:!1});if(n>=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+n>=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+n,this}}t.UnorderedBulkOperation=s},10557:(e,t,n)=>{var r=n(67787).Buffer,o=n(65994).e;Object.defineProperty(t,"__esModule",{value:!0}),t.GridFSBucketWriteStream=void 0;const i=n(93874),s=n(75080),a=n(61066),c=n(17562),u=n(7799),l=n(145),h=n(40012);class d extends i.Writable{constructor(e,t,n){super(),this.gridFSFile=null,n=n??{},this.bucket=e,this.chunks=e.s._chunksCollection,this.filename=t,this.files=e.s._filesCollection,this.options=n,this.writeConcern=h.WriteConcern.fromOptions(n)||e.s.options.writeConcern,this.done=!1,this.id=n.id?n.id:new s.ObjectId,this.chunkSizeBytes=n.chunkSizeBytes||this.bucket.s.options.chunkSizeBytes,this.bufToStore=r.alloc(this.chunkSizeBytes),this.length=0,this.n=0,this.pos=0,this.state={streamEnd:!1,outstandingRequests:0,errored:!1,aborted:!1},null!=n.timeoutMS&&(this.timeoutContext=new u.CSOTTimeoutContext({timeoutMS:n.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 n;t=e.timeoutContext?.getRemainingTimeMSOrThrow(`Upload timed out after ${e.timeoutContext?.timeoutMS}ms`);const r={timeoutMode:null!=t?a.CursorTimeoutMode.LIFETIME:void 0,timeoutMS:t};try{n=await e.files.listIndexes(r).toArray()}catch(e){if(!(e instanceof c.MongoError&&e.code===c.MONGODB_ERROR_CODES.NamespaceNotFound))throw e;n=[]}n.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,n;t=e.timeoutContext?.getRemainingTimeMSOrThrow(`Upload timed out after ${e.timeoutContext?.timeoutMS}ms`);try{n=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;n=[]}const r=!!n.find((e=>2===Object.keys(e.key).length&&1===e.key.files_id&&1===e.key.n));r||(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,n){!function(e,t,n,i){if(g(e,i))return;const s=r.isBuffer(t)?t:r.from(t,n);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),h=0;for(;a>0;){const t=s.length-a;let n;if(s.copy(e.bufToStore,e.pos,t,t+l),e.pos+=l,u-=l,0===u){n=m(e.id,e.n,r.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,++h,g(e,i))return;e.chunks.insertOne(n,{writeConcern:e.writeConcern,timeoutMS:t}).then((()=>{--e.state.outstandingRequests,--h,h||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,n)}_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 n=r.alloc(e.pos);e.bufToStore.copy(n,0,0,e.pos);const o=m(e.id,e.n,n);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)}),(n=>p(e,n,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,n){e.state.errored?o.nextTick(n):(e.state.errored=!0,o.nextTick(n,t))}function m(e,t,n){return{_id:new s.ObjectId,files_id:e,n:t,data:n}}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 n=function(e,t,n,r,o,i,s){const a={_id:e,length:t,chunkSize:n,uploadDate:new Date,filename:r};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 r=e.timeoutContext?.remainingTimeMS;return null!=r&&r<=0?p(e,new c.MongoOperationTimeoutError(`Upload timed out after ${e.timeoutContext?.timeoutMS}ms`),t):void e.files.insertOne(n,{writeConcern:e.writeConcern,timeoutMS:r}).then((()=>{e.gridFSFile=n,t()}),(n=>p(e,n,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=d},11706:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ListDatabasesOperation=void 0;const r=n(75725),o=n(145),i=n(78130),s=n(35394);class a extends i.CommandOperation{constructor(e,t){super(e,t),this.SERVER_COMMAND_RESPONSE_TYPE=r.MongoDBResponse,this.options=t??{},this.ns=new o.MongoDBNamespace("admin","$cmd")}get commandName(){return"listDatabases"}buildCommandDocument(e,t){const n={listDatabases:1};return"boolean"==typeof this.options.nameOnly&&(n.nameOnly=this.options.nameOnly),this.options.filter&&(n.filter=this.options.filter),"boolean"==typeof this.options.authorizedDatabases&&(n.authorizedDatabases=this.options.authorizedDatabases),(0,o.maxWireVersion)(e)>=9&&void 0!==this.options.comment&&(n.comment=this.options.comment),n}}t.ListDatabasesOperation=a,(0,s.defineAspects)(a,[s.Aspect.READ_OPERATION,s.Aspect.RETRYABLE])},11737:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.buildReplaceOneOperation=t.buildUpdateManyOperation=t.buildUpdateOneOperation=t.buildDeleteManyOperation=t.buildDeleteOneOperation=t.buildInsertOneOperation=t.ClientBulkWriteCommandBuilder=void 0,t.buildOperation=h;const r=n(75080),o=n(15620),i=n(17562),s=n(30770),a=n(145);function c(e,t,n){if(t.length>n)throw new i.MongoInvalidArgumentError(`Client bulk write operation ${e} of length ${t.length} exceeds the max bson object size of ${n}`)}function u(e,t,n){const r={delete:t,multi:n,filter:e.filter};return e.hint&&(r.hint=e.hint),e.collation&&(r.collation=e.collation),r}function l(e,t,n,r){!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,r);const o={update:t,multi:n,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),!n&&"sort"in e&&null!=e.sort&&(o.sort=(0,s.formatSort)(e.sort)),o}function h(e,n,r,o){switch(e.name){case"insertOne":return(0,t.buildInsertOneOperation)(e,n,r);case"deleteOne":return(0,t.buildDeleteOneOperation)(e,n);case"deleteMany":return(0,t.buildDeleteManyOperation)(e,n);case"updateOne":return(0,t.buildUpdateOneOperation)(e,n,o);case"updateMany":return(0,t.buildUpdateManyOperation)(e,n,o);case"replaceOne":return(0,t.buildReplaceOneOperation)(e,n)}}t.ClientBulkWriteCommandBuilder=class{constructor(e,t,n){this.models=e,this.options=t,this.pkFactory=n??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,n){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],d=l.namespace,p=u.get(d);if("deleteMany"!==l.name&&"updateMany"!==l.name||(this.isBatchRetryable=!1),null!=p){const s=h(l,p,this.pkFactory,this.options);let u;try{u=r.BSON.serialize(s)}catch(e){throw new i.MongoInvalidArgumentError("Could not serialize operation to BSON",{cause:e})}if(c("ops",u,n),!(o+u.length<e&&a.ops.documents.length<t))break;o=1e3+a.ops.push(s,u),this.currentModelIndex++}else{u.set(d,s);const p={ns:d},m=h(l,s,this.pkFactory,this.options);let f,g;try{f=r.BSON.serialize(p),g=r.BSON.serialize(m)}catch(e){throw new i.MongoInvalidArgumentError("Could not serialize ns info to BSON",{cause:e})}if(c("nsInfo",f,n),c("ops",g,n),!(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,n)=>{const r={insert:t,document:e.document};return r.document._id=e.document._id??n.createPk(),r},t.buildDeleteOneOperation=(e,t)=>u(e,t,!1),t.buildDeleteManyOperation=(e,t)=>u(e,t,!0),t.buildUpdateOneOperation=(e,t,n)=>l(e,t,!1,n),t.buildUpdateManyOperation=(e,t,n)=>l(e,t,!0,n),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 n={update:t,multi:!1,filter:e.filter,updateMods:e.replacement};return e.hint&&(n.hint=e.hint),e.upsert&&(n.upsert=e.upsert),e.collation&&(n.collation=e.collation),null!=e.sort&&(n.sort=(0,s.formatSort)(e.sort)),n}},12453:e=>{const t=function(e){return e=e.toString(),this instanceof t?(this.ns=e,this.dotIndex=e.indexOf("."),-1===this.dotIndex?(this.database=e,this.collection=""):(this.database=e.slice(0,this.dotIndex),this.collection=e.slice(this.dotIndex+1)),this.system=/^(?:system(?!\.profile$).*|enxcol_)\./.test(this.collection),this.oplog=/local\.oplog\.(\$main|rs)/.test(e),this.command="$cmd"===this.collection||0===this.collection.indexOf("$cmd.sys"),this.special=this.oplog||this.command||this.system||"config"===this.database||/^__mdb_internal_\w/.test(this.database),this.specialish=this.special||["local","admin"].indexOf(this.database)>-1,this.normal=this.oplog||-1===this.ns.indexOf("$"),this.validDatabaseName=new RegExp('^[^\\\\/". ]*$').test(this.database)&&this.database.length<=t.MAX_DATABASE_NAME_LENGTH,this.validCollectionName=this.collection.length>0&&(this.oplog||/^[^\0$]*$/.test(this.collection)),this.databaseHash=7,this.ns.split("").every(((e,t)=>"."!==e&&(this.databaseHash+=11*this.ns.charCodeAt(t),this.databaseHash*=3,!0))),this):new t(e)};t.prototype.database="",t.prototype.databaseHash=0,t.prototype.collection="",t.prototype.command=!1,t.prototype.special=!1,t.prototype.system=!1,t.prototype.oplog=!1,t.prototype.normal=!1,t.prototype.specialish=!1,t.prototype.isCommand=function(){return this.command},t.prototype.isSpecial=function(){return this.special},t.prototype.isSystem=function(){return this.system},t.prototype.isNormal=function(){return this.normal},t.prototype.isOplog=function(){return this.oplog},t.prototype.isConf=function(){},t.prototype.toString=function(){return this.ns},t.MAX_DATABASE_NAME_LENGTH=128,t.sort=function(e){return e.sort((function(e,n){return new t(e).specialish&&new t(n).specialish?0:new t(e).specialish&&!new t(n).specialish?1:!new t(e).specialish&&new t(n).specialish?-1:e>n?1:-1})),e},e.exports=t},13700:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ReadPreference=t.ReadPreferenceMode=void 0;const r=n(17562);t.ReadPreferenceMode=Object.freeze({primary:"primary",primaryPreferred:"primaryPreferred",secondary:"secondary",secondaryPreferred:"secondaryPreferred",nearest:"nearest"});class o{constructor(e,t,n){if(!o.isValid(e))throw new r.MongoInvalidArgumentError(`Invalid read preference mode ${JSON.stringify(e)}`);if(null!=n||"object"!=typeof t||Array.isArray(t)){if(t&&!Array.isArray(t))throw new r.MongoInvalidArgumentError("ReadPreference tags must be an array")}else n=t,t=void 0;if(this.mode=e,this.tags=t,this.hedge=n?.hedge,this.maxStalenessSeconds=void 0,this.minWireVersion=void 0,null!=(n=n??{}).maxStalenessSeconds){if(n.maxStalenessSeconds<=0)throw new r.MongoInvalidArgumentError("maxStalenessSeconds must be a positive integer");this.maxStalenessSeconds=n.maxStalenessSeconds,this.minWireVersion=5}if(this.mode===o.PRIMARY){if(this.tags&&Array.isArray(this.tags)&&this.tags.length>0)throw new r.MongoInvalidArgumentError("Primary read preference cannot be combined with tags");if(this.maxStalenessSeconds)throw new r.MongoInvalidArgumentError("Primary read preference cannot be combined with maxStalenessSeconds");if(this.hedge)throw new r.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,n=e.readPreferenceTags;if(null!=t){if("string"==typeof t)return new o(t,n,{maxStalenessSeconds:e.maxStalenessSeconds,hedge:e.hedge});if(!(t instanceof o)&&"object"==typeof t){const r=t.mode||t.preference;if(r&&"string"==typeof r)return new o(r,t.tags??n,{maxStalenessSeconds:t.maxStalenessSeconds,hedge:e.hedge})}return n&&(t.tags=n),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 r.MongoInvalidArgumentError(`Invalid read preference: ${t}`)}else{const n=t.mode||t.preference;n&&"string"==typeof n&&(e.readPreference=new o(n,t.tags,{maxStalenessSeconds:t.maxStalenessSeconds}))}return e}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)},14012:e=>{function t(e,t){if(!e)throw new Error(t||"Assertion failed")}e.exports=t,t.equal=function(e,t,n){if(e!=t)throw new Error(n||"Assertion failed: "+e+" != "+t)}},14019:(e,t,n)=>{var r=n(67787).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.ServerSessionPool=t.ServerSession=t.ClientSession=void 0,t.maybeClearPinnedConnection=M,t.applySession=function(e,t,n){if(e.hasEnded)return new c.MongoExpiredSessionError;const r=e.serverSession;if(null==r)return new c.MongoRuntimeError("Unable to acquire server session");if(0===n.writeConcern?.w)return e&&e.explicit?new c.MongoAPIError("Cannot have explicit session with unacknowledged writes"):void 0;r.lastUse=(0,E.now)(),t.lsid=r.id;const i=e.inTransaction()||(0,y.isTransactionCommand)(t);if((n.willRetryWrite||i)&&(r.txnNumber+=e.txnNumberIncrement,e.txnNumberIncrement=0,t.txnNumber=o.Long.fromNumber(r.txnNumber)),!i)return e.transaction.state!==y.TxnState.NO_TRANSACTION&&e.transaction.transition(y.TxnState.NO_TRANSACTION),void(e.supports.causalConsistency&&e.operationTime&&(0,E.commandSupportsReadConcern)(t)?(t.readConcern=t.readConcern||{},Object.assign(t.readConcern,{afterClusterTime:e.operationTime})):e.snapshotEnabled&&(t.readConcern=t.readConcern||{level:d.ReadConcernLevel.snapshot},null!=e.snapshotTime&&Object.assign(t.readConcern,{atClusterTime:e.snapshotTime})));if(t.autocommit=!1,e.transaction.state===y.TxnState.STARTING_TRANSACTION){e.transaction.transition(y.TxnState.TRANSACTION_IN_PROGRESS),t.startTransaction=!0;const n=e.transaction.options.readConcern||e?.clientOptions?.readConcern;n&&(t.readConcern=n),e.supports.causalConsistency&&e.operationTime&&(t.readConcern=t.readConcern||{},Object.assign(t.readConcern,{afterClusterTime:e.operationTime}))}},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 n=t.atClusterTime;n&&(e.snapshotTime=n)}};const o=n(75080),i=n(55741),s=n(61428),a=n(91869),c=n(17562),u=n(4642),l=n(96357),h=n(17668),d=n(28541),p=n(13700),m=n(31790),f=n(89167),g=n(7799),y=n(85759),E=n(145),S=n(40012);class O extends u.TypedEventEmitter{constructor(e,t,n,r){if(super(),this.timeoutContext=null,this.on("error",E.noop),null==e)throw new c.MongoRuntimeError("ClientSession requires a MongoClient");if(null==t||!(t instanceof A))throw new c.MongoRuntimeError("ClientSession requires a ServerSessionPool");if(n=n??{},this.snapshotEnabled=!0===n.snapshot,!0===n.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=r,this.timeoutMS=n.defaultTimeoutMS??e.s.options?.timeoutMS,this.explicit=!!n.explicit,this._serverSession=this.explicit?this.sessionPool.acquire():null,this.txnNumberIncrement=0;const o=this.explicit&&!0!==n.snapshot;this.supports={causalConsistency:n.causalConsistency??o},this.clusterTime=n.initialClusterTime,this.operationTime=void 0,this.owner=n.owner,this.defaultTransactionOptions={...n.defaultTransactionOptions},this.transaction=new y.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 M(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,E.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)}M(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 O&&null!=this.id&&null!=e.id&&E.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,E.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 y.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(y.TxnState.STARTING_TRANSACTION)}async commitTransaction(e){if(this.transaction.state===y.TxnState.NO_TRANSACTION)throw new c.MongoTransactionError("No transaction started");if(this.transaction.state===y.TxnState.STARTING_TRANSACTION||this.transaction.state===y.TxnState.TRANSACTION_COMMITTED_EMPTY)return void this.transaction.transition(y.TxnState.TRANSACTION_COMMITTED_EMPTY);if(this.transaction.state===y.TxnState.TRANSACTION_ABORTED)throw new c.MongoTransactionError("Cannot call commitTransaction after calling abortTransaction");const t={commitTransaction:1},n="number"==typeof e?.timeoutMS?e.timeoutMS:"number"==typeof this.timeoutMS?this.timeoutMS:null,r=this.transaction.options.writeConcern??this.clientOptions?.writeConcern;if(null!=r)if(null==n&&null==this.timeoutContext)S.WriteConcern.apply(t,{wtimeoutMS:1e4,w:"majority",...r});else{const e=Object.keys(r);(e.length>2||!e.includes("wtimeoutMS")&&!e.includes("wTimeoutMS"))&&S.WriteConcern.apply(t,{...r,wtimeoutMS:void 0})}(this.transaction.state===y.TxnState.TRANSACTION_COMMITTED||this.commitAttempted)&&(null==n&&null==this.timeoutContext?S.WriteConcern.apply(t,{wtimeoutMS:1e4,...r,w:"majority"}):S.WriteConcern.apply(t,{w:"majority",...r,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 h.RunCommandOperation(new E.MongoDBNamespace("admin"),t,{session:this,readPreference:p.ReadPreference.primary,bypassPinningCheck:!0}),i=this.timeoutContext??("number"==typeof n?g.TimeoutContext.create({serverSelectionTimeoutMS:this.clientOptions.serverSelectionTimeoutMS,socketTimeoutMS:this.clientOptions.socketTimeoutMS,timeoutMS:n}):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)){S.WriteConcern.apply(t,{wtimeoutMS:1e4,...r,w:"majority"}),this.unpin({force:!0});try{return void await(0,l.executeOperation)(this.client,new h.RunCommandOperation(new E.MongoDBNamespace("admin"),t,{session:this,readPreference:p.ReadPreference.primary,bypassPinningCheck:!0}),i)}catch(e){throw b(e)&&e.addErrorLabel(c.MongoErrorLabel.UnknownTransactionCommitResult),v(e)&&this.unpin({error:e}),e}}throw b(e)&&e.addErrorLabel(c.MongoErrorLabel.UnknownTransactionCommitResult),v(e)&&this.unpin({error:e}),e}finally{this.transaction.transition(y.TxnState.TRANSACTION_COMMITTED)}}async abortTransaction(e){if(this.transaction.state===y.TxnState.NO_TRANSACTION)throw new c.MongoTransactionError("No transaction started");if(this.transaction.state===y.TxnState.STARTING_TRANSACTION)return void this.transaction.transition(y.TxnState.TRANSACTION_ABORTED);if(this.transaction.state===y.TxnState.TRANSACTION_ABORTED)throw new c.MongoTransactionError("Cannot call abortTransaction twice");if(this.transaction.state===y.TxnState.TRANSACTION_COMMITTED||this.transaction.state===y.TxnState.TRANSACTION_COMMITTED_EMPTY)throw new c.MongoTransactionError("Cannot call abortTransaction after calling commitTransaction");const t={abortTransaction:1},n="number"==typeof e?.timeoutMS?e.timeoutMS:this.timeoutContext?.csotEnabled()?this.timeoutContext.timeoutMS:"number"==typeof this.timeoutMS?this.timeoutMS:null,r=null!=n?g.TimeoutContext.create({timeoutMS:n,serverSelectionTimeoutMS:this.clientOptions.serverSelectionTimeoutMS,socketTimeoutMS:this.clientOptions.socketTimeoutMS}):null,o=this.transaction.options.writeConcern??this.clientOptions?.writeConcern;null!=o&&null==n&&S.WriteConcern.apply(t,{wtimeoutMS:1e4,w:"majority",...o}),this.transaction.recoveryToken&&(t.recoveryToken=this.transaction.recoveryToken);const i=new h.RunCommandOperation(new E.MongoDBNamespace("admin"),t,{session:this,readPreference:p.ReadPreference.primary,bypassPinningCheck:!0});try{return await(0,l.executeOperation)(this.client,i,r),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,r)}catch(t){if("MongoRuntimeError"===t.name)throw t;if(e?.throwTimeout&&"MongoOperationTimeoutError"===t.name)throw t}}finally{this.transaction.transition(y.TxnState.TRANSACTION_ABORTED),this.loadBalanced&&M(this,{force:!1})}}toBSON(){throw new c.MongoRuntimeError("ClientSession cannot be serialized to BSON.")}async withTransaction(e,t){const n=12e4,r=t?.timeoutMS??this.timeoutMS??null;this.timeoutContext=null!=r?g.TimeoutContext.create({timeoutMS:r,serverSelectionTimeoutMS:this.clientOptions.serverSelectionTimeoutMS,socketTimeoutMS:this.clientOptions.socketTimeoutMS}):null;const o=this.timeoutContext?.csotEnabled()?this.timeoutContext.start:(0,E.now)();let i,s=!1;try{for(;!s;){this.startTransaction(t);try{const t=e(this);if(!(0,E.isPromiseLike)(t))throw new c.MongoInvalidArgumentError("Function provided to `withTransaction` must return a Promise");if(i=await t,this.transaction.state===y.TxnState.NO_TRANSACTION||this.transaction.state===y.TxnState.TRANSACTION_COMMITTED||this.transaction.state===y.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!==y.TxnState.STARTING_TRANSACTION&&this.transaction.state!==y.TxnState.TRANSACTION_IN_PROGRESS||await this.abortTransaction(),e.hasErrorLabel(c.MongoErrorLabel.TransientTransactionError)&&(null!=this.timeoutContext||(0,E.now)()-o<n))continue;throw e}for(;!s;)try{await this.commitTransaction(),s=!0}catch(e){if(!T(e)&&e.hasErrorLabel(c.MongoErrorLabel.UnknownTransactionCommitResult)&&(null!=this.timeoutContext||(0,E.now)()-o<n))continue;if(e.hasErrorLabel(c.MongoErrorLabel.TransientTransactionError)&&(null!=this.timeoutContext||(0,E.now)()-o<n))break;throw e}}return i}finally{this.timeoutContext=null}}}t.ClientSession=O,(0,m.configureResourceManagement)(O.prototype);const C=new Set(["CannotSatisfyWriteConcern","UnknownReplWriteConcern","UnsatisfiableWriteConcern"]);function v(e){if(e instanceof c.MongoError)if((0,c.isRetryableWriteError)(e)||e instanceof c.MongoWriteConcernError||T(e)){if(w(e))return!0}else if(e.hasErrorLabel(c.MongoErrorLabel.TransientTransactionError))return!0;return!1}function b(e){let t=(0,c.isRetryableWriteError)(e);return t||=e instanceof c.MongoWriteConcernError,t||=T(e),t&&=w(e),t}function w(e){const t=e instanceof c.MongoServerError&&e.codeName&&C.has(e.codeName);return T(e)||!t&&e.code!==c.MONGODB_ERROR_CODES.UnsatisfiableWriteConcern&&e.code!==c.MONGODB_ERROR_CODES.UnknownReplWriteConcern}function M(e,t){const n=e.pinnedConnection,r=t?.error;if(e.inTransaction()&&r&&r instanceof c.MongoError&&r.hasErrorLabel(c.MongoErrorLabel.TransientTransactionError))return;const o=e.client.topology;if(n&&null!=o){const r=Array.from(o.s.servers.values())[0];(null==t?.error||t?.force)&&(r.pool.checkIn(n),e.pinnedConnection=void 0,n.emit(a.UNPINNED,e.transaction.state!==y.TxnState.NO_TRANSACTION?i.ConnectionPoolMetrics.TXN:i.ConnectionPoolMetrics.CURSOR),t?.forceClear&&r.pool.clear({serviceId:n.serviceId}))}}function T(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=r.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,E.uuidV4)(),o.Binary.SUBTYPE_UUID)},this.lastUse=(0,E.now)(),this.txnNumber=0,this.isDirty=!1}hasTimedOut(e){return Math.round((0,E.calculateDurationInMs)(this.lastUse)%864e5%36e5/6e4)>e-1}}t.ServerSession=_;class A{constructor(e){if(null==e)throw new c.MongoRuntimeError("ServerSessionPool requires a MongoClient");this.client=e,this.sessions=new E.List}acquire(){const e=this.client.topology?.logicalSessionTimeoutMinutes??10;let t=null;for(;this.sessions.length>0;){const n=this.sessions.shift();if(null!=n&&(this.client.topology?.loadBalanced||!n.hasTimedOut(e))){t=n;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=A},15620:(e,t,n)=>{var r=n(67787).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.OpCompressedRequest=t.OpMsgResponse=t.OpMsgRequest=t.DocumentSequence=t.OpReply=t.OpQueryRequest=void 0;const o=n(75080),i=n(17562),s=n(64515),a=n(96856);let c=0;const u=o.BSON.onDemand.ByteUtils.encodeUTF8Into;class l{constructor(e,t,n){this.moreToCome=!1;const r=`${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!==r.indexOf("\0"))throw new i.MongoRuntimeError("Namespace cannot contain a null character");this.databaseName=e,this.query=t,this.ns=r,this.numberToSkip=n.numberToSkip||0,this.numberToReturn=n.numberToReturn||0,this.returnFieldSelector=n.returnFieldSelector||void 0,this.requestId=n.requestId??l.getRequestId(),this.pre32Limit=n.pre32Limit,this.serializeFunctions="boolean"==typeof n.serializeFunctions&&n.serializeFunctions,this.ignoreUndefined="boolean"==typeof n.ignoreUndefined&&n.ignoreUndefined,this.maxBsonSize=n.maxBsonSize||16777216,this.checkKeys="boolean"==typeof n.checkKeys&&n.checkKeys,this.batchSize=this.numberToReturn,this.tailable=!1,this.secondaryOk="boolean"==typeof n.secondaryOk&&n.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,n=0;this.tailable&&(n|=2),this.secondaryOk&&(n|=4),this.oplogReplay&&(n|=8),this.noCursorTimeout&&(n|=16),this.awaitData&&(n|=32),this.exhaust&&(n|=64),this.partial&&(n|=128),this.batchSize!==this.numberToReturn&&(this.numberToReturn=this.batchSize);const i=r.alloc(20+r.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]=n>>24&255,i[u+2]=n>>16&255,i[u+1]=n>>8&255,i[u]=255&n,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,n,r){this.index=0,this.sections=[],this.moreToCome=!1,this.parsed=!1,this.raw=e,this.data=n,this.opts=r??{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 h{constructor(e,t){this.field=e,this.documents=[],this.chunks=[],this.serializedDocumentsLength=0;const n=r.allocUnsafe(5+this.field.length+1);if(n[0]=1,u(n,`${this.field}\0`,5),this.chunks.push(n),this.header=n,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 r.concat(this.chunks)}}t.DocumentSequence=h;class d{constructor(e,t,n){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=n??{},this.requestId=n.requestId?n.requestId:d.getRequestId(),this.serializeFunctions="boolean"==typeof n.serializeFunctions&&n.serializeFunctions,this.ignoreUndefined="boolean"==typeof n.ignoreUndefined&&n.ignoreUndefined,this.checkKeys="boolean"==typeof n.checkKeys&&n.checkKeys,this.maxBsonSize=n.maxBsonSize||16777216,this.checksumPresent=!1,this.moreToCome=n.moreToCome??0===t.writeConcern?.w,this.exhaustAllowed="boolean"==typeof n.exhaustAllowed&&n.exhaustAllowed}toBin(){const e=[];let t=0;this.checksumPresent&&(t|=1),this.moreToCome&&(t|=2),this.exhaustAllowed&&(t|=65536);const n=r.alloc(20);e.push(n);let o=n.length;const i=this.command;return o+=this.makeSections(e,i),n.writeInt32LE(o,0),n.writeInt32LE(this.requestId,4),n.writeInt32LE(0,8),n.writeInt32LE(a.OP_MSG,12),n.writeUInt32LE(t,16),e}makeSections(e,t){const n=this.extractDocumentSequences(t),o=r.allocUnsafe(1);o[0]=0;const i=this.serializeBson(t);return e.push(o),e.push(i),e.push(n),o.length+i.length+n.length}extractDocumentSequences(e){const t=[];for(const[n,r]of Object.entries(e))r instanceof h&&(t.push(r.toBin()),delete e[n]);return t.length>0?r.concat(t):r.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=d,t.OpMsgResponse=class{constructor(e,t,n,r){this.index=0,this.sections=[],this.parsed=!1,this.raw=e,this.data=n,this.opts=r??{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=n.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 d?e.command:e.query,n=Object.keys(t)[0];return!s.uncompressibleCommands.has(n)}async toBin(){const e=r.concat(this.command.toBin()),t=e.slice(16),n=e.readInt32LE(12),o=await(0,s.compress)(this.options,t),i=r.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=r.alloc(9);return c.writeInt32LE(n,0),c.writeInt32LE(t.length,4),c.writeUInt8(s.Compressor[this.options.agreedCompressor],8),[i,c,o]}}},16360:(e,t,n)=>{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 r=n(71235);Object.defineProperty(t,"Admin",{enumerable:!0,get:function(){return r.Admin}});const o=n(29348);Object.defineProperty(t,"OrderedBulkOperation",{enumerable:!0,get:function(){return o.OrderedBulkOperation}});const i=n(10089);Object.defineProperty(t,"UnorderedBulkOperation",{enumerable:!0,get:function(){return i.UnorderedBulkOperation}});const s=n(22345);Object.defineProperty(t,"ChangeStream",{enumerable:!0,get:function(){return s.ChangeStream}});const a=n(19498);Object.defineProperty(t,"Collection",{enumerable:!0,get:function(){return a.Collection}});const c=n(61066);Object.defineProperty(t,"AbstractCursor",{enumerable:!0,get:function(){return c.AbstractCursor}});const u=n(68526);Object.defineProperty(t,"AggregationCursor",{enumerable:!0,get:function(){return u.AggregationCursor}});const l=n(5465);Object.defineProperty(t,"FindCursor",{enumerable:!0,get:function(){return l.FindCursor}});const h=n(55546);Object.defineProperty(t,"ListCollectionsCursor",{enumerable:!0,get:function(){return h.ListCollectionsCursor}});const d=n(32361);Object.defineProperty(t,"ListIndexesCursor",{enumerable:!0,get:function(){return d.ListIndexesCursor}});const p=n(44120);Object.defineProperty(t,"Db",{enumerable:!0,get:function(){return p.Db}});const m=n(74158);Object.defineProperty(t,"GridFSBucket",{enumerable:!0,get:function(){return m.GridFSBucket}});const f=n(33104);Object.defineProperty(t,"GridFSBucketReadStream",{enumerable:!0,get:function(){return f.GridFSBucketReadStream}});const g=n(10557);Object.defineProperty(t,"GridFSBucketWriteStream",{enumerable:!0,get:function(){return g.GridFSBucketWriteStream}});const y=n(22220);Object.defineProperty(t,"MongoClient",{enumerable:!0,get:function(){return y.MongoClient}});const E=n(4642);Object.defineProperty(t,"CancellationToken",{enumerable:!0,get:function(){return E.CancellationToken}});const S=n(14019);Object.defineProperty(t,"ClientSession",{enumerable:!0,get:function(){return S.ClientSession}});var O=n(75080);Object.defineProperty(t,"BSON",{enumerable:!0,get:function(){return O.BSON}});var C=n(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 v=n(54564);Object.defineProperty(t,"MongoBulkWriteError",{enumerable:!0,get:function(){return v.MongoBulkWriteError}});var b=n(95738);Object.defineProperty(t,"ClientEncryption",{enumerable:!0,get:function(){return b.ClientEncryption}});var w=n(40251);Object.defineProperty(t,"ChangeStreamCursor",{enumerable:!0,get:function(){return w.ChangeStreamCursor}});var M=n(36649);Object.defineProperty(t,"ExplainableCursor",{enumerable:!0,get:function(){return M.ExplainableCursor}});var T=n(17562);Object.defineProperty(t,"MongoAPIError",{enumerable:!0,get:function(){return T.MongoAPIError}}),Object.defineProperty(t,"MongoAWSError",{enumerable:!0,get:function(){return T.MongoAWSError}}),Object.defineProperty(t,"MongoAzureError",{enumerable:!0,get:function(){return T.MongoAzureError}}),Object.defineProperty(t,"MongoBatchReExecutionError",{enumerable:!0,get:function(){return T.MongoBatchReExecutionError}}),Object.defineProperty(t,"MongoChangeStreamError",{enumerable:!0,get:function(){return T.MongoChangeStreamError}}),Object.defineProperty(t,"MongoClientBulkWriteCursorError",{enumerable:!0,get:function(){return T.MongoClientBulkWriteCursorError}}),Object.defineProperty(t,"MongoClientBulkWriteError",{enumerable:!0,get:function(){return T.MongoClientBulkWriteError}}),Object.defineProperty(t,"MongoClientBulkWriteExecutionError",{enumerable:!0,get:function(){return T.MongoClientBulkWriteExecutionError}}),Object.defineProperty(t,"MongoClientClosedError",{enumerable:!0,get:function(){return T.MongoClientClosedError}}),Object.defineProperty(t,"MongoCompatibilityError",{enumerable:!0,get:function(){return T.MongoCompatibilityError}}),Object.defineProperty(t,"MongoCursorExhaustedError",{enumerable:!0,get:function(){return T.MongoCursorExhaustedError}}),Object.defineProperty(t,"MongoCursorInUseError",{enumerable:!0,get:function(){return T.MongoCursorInUseError}}),Object.defineProperty(t,"MongoDecompressionError",{enumerable:!0,get:function(){return T.MongoDecompressionError}}),Object.defineProperty(t,"MongoDriverError",{enumerable:!0,get:function(){return T.MongoDriverError}}),Object.defineProperty(t,"MongoError",{enumerable:!0,get:function(){return T.MongoError}}),Object.defineProperty(t,"MongoExpiredSessionError",{enumerable:!0,get:function(){return T.MongoExpiredSessionError}}),Object.defineProperty(t,"MongoGCPError",{enumerable:!0,get:function(){return T.MongoGCPError}}),Object.defineProperty(t,"MongoGridFSChunkError",{enumerable:!0,get:function(){return T.MongoGridFSChunkError}}),Object.defineProperty(t,"MongoGridFSStreamError",{enumerable:!0,get:function(){return T.MongoGridFSStreamError}}),Object.defineProperty(t,"MongoInvalidArgumentError",{enumerable:!0,get:function(){return T.MongoInvalidArgumentError}}),Object.defineProperty(t,"MongoKerberosError",{enumerable:!0,get:function(){return T.MongoKerberosError}}),Object.defineProperty(t,"MongoMissingCredentialsError",{enumerable:!0,get:function(){return T.MongoMissingCredentialsError}}),Object.defineProperty(t,"MongoMissingDependencyError",{enumerable:!0,get:function(){return T.MongoMissingDependencyError}}),Object.defineProperty(t,"MongoNetworkError",{enumerable:!0,get:function(){return T.MongoNetworkError}}),Object.defineProperty(t,"MongoNetworkTimeoutError",{enumerable:!0,get:function(){return T.MongoNetworkTimeoutError}}),Object.defineProperty(t,"MongoNotConnectedError",{enumerable:!0,get:function(){return T.MongoNotConnectedError}}),Object.defineProperty(t,"MongoOIDCError",{enumerable:!0,get:function(){return T.MongoOIDCError}}),Object.defineProperty(t,"MongoOperationTimeoutError",{enumerable:!0,get:function(){return T.MongoOperationTimeoutError}}),Object.defineProperty(t,"MongoParseError",{enumerable:!0,get:function(){return T.MongoParseError}}),Object.defineProperty(t,"MongoRuntimeError",{enumerable:!0,get:function(){return T.MongoRuntimeError}}),Object.defineProperty(t,"MongoServerClosedError",{enumerable:!0,get:function(){return T.MongoServerClosedError}}),Object.defineProperty(t,"MongoServerError",{enumerable:!0,get:function(){return T.MongoServerError}}),Object.defineProperty(t,"MongoServerSelectionError",{enumerable:!0,get:function(){return T.MongoServerSelectionError}}),Object.defineProperty(t,"MongoStalePrimaryError",{enumerable:!0,get:function(){return T.MongoStalePrimaryError}}),Object.defineProperty(t,"MongoSystemError",{enumerable:!0,get:function(){return T.MongoSystemError}}),Object.defineProperty(t,"MongoTailableCursorError",{enumerable:!0,get:function(){return T.MongoTailableCursorError}}),Object.defineProperty(t,"MongoTopologyClosedError",{enumerable:!0,get:function(){return T.MongoTopologyClosedError}}),Object.defineProperty(t,"MongoTransactionError",{enumerable:!0,get:function(){return T.MongoTransactionError}}),Object.defineProperty(t,"MongoUnexpectedServerResponseError",{enumerable:!0,get:function(){return T.MongoUnexpectedServerResponseError}}),Object.defineProperty(t,"MongoWriteConcernError",{enumerable:!0,get:function(){return T.MongoWriteConcernError}});var _=n(31790);Object.defineProperty(t,"configureExplicitResourceManagement",{enumerable:!0,get:function(){return _.configureExplicitResourceManagement}});var A=n(54564);Object.defineProperty(t,"BatchType",{enumerable:!0,get:function(){return A.BatchType}});var R=n(70136);Object.defineProperty(t,"AutoEncryptionLoggerLevel",{enumerable:!0,get:function(){return R.AutoEncryptionLoggerLevel}});var N=n(95750);Object.defineProperty(t,"GSSAPICanonicalizationValue",{enumerable:!0,get:function(){return N.GSSAPICanonicalizationValue}});var I=n(93065);Object.defineProperty(t,"AuthMechanism",{enumerable:!0,get:function(){return I.AuthMechanism}});var x=n(64515);Object.defineProperty(t,"Compressor",{enumerable:!0,get:function(){return x.Compressor}});var P=n(61066);Object.defineProperty(t,"CURSOR_FLAGS",{enumerable:!0,get:function(){return P.CURSOR_FLAGS}}),Object.defineProperty(t,"CursorTimeoutMode",{enumerable:!0,get:function(){return P.CursorTimeoutMode}});var k=n(17562);Object.defineProperty(t,"MongoErrorLabel",{enumerable:!0,get:function(){return k.MongoErrorLabel}});var D=n(36411);Object.defineProperty(t,"ExplainVerbosity",{enumerable:!0,get:function(){return D.ExplainVerbosity}});var L=n(22220);Object.defineProperty(t,"ServerApiVersion",{enumerable:!0,get:function(){return L.ServerApiVersion}});var B=n(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=n(61635);Object.defineProperty(t,"ReturnDocument",{enumerable:!0,get:function(){return j.ReturnDocument}});var F=n(58127);Object.defineProperty(t,"ProfilingLevel",{enumerable:!0,get:function(){return F.ProfilingLevel}});var U=n(28541);Object.defineProperty(t,"ReadConcernLevel",{enumerable:!0,get:function(){return U.ReadConcernLevel}});var z=n(13700);Object.defineProperty(t,"ReadPreferenceMode",{enumerable:!0,get:function(){return z.ReadPreferenceMode}});var V=n(89167);Object.defineProperty(t,"ServerType",{enumerable:!0,get:function(){return V.ServerType}}),Object.defineProperty(t,"TopologyType",{enumerable:!0,get:function(){return V.TopologyType}});var $=n(28541);Object.defineProperty(t,"ReadConcern",{enumerable:!0,get:function(){return $.ReadConcern}});var W=n(13700);Object.defineProperty(t,"ReadPreference",{enumerable:!0,get:function(){return W.ReadPreference}});var G=n(40012);Object.defineProperty(t,"WriteConcern",{enumerable:!0,get:function(){return G.WriteConcern}});var H=n(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 q=n(287);Object.defineProperty(t,"ConnectionCheckedInEvent",{enumerable:!0,get:function(){return q.ConnectionCheckedInEvent}}),Object.defineProperty(t,"ConnectionCheckedOutEvent",{enumerable:!0,get:function(){return q.ConnectionCheckedOutEvent}}),Object.defineProperty(t,"ConnectionCheckOutFailedEvent",{enumerable:!0,get:function(){return q.ConnectionCheckOutFailedEvent}}),Object.defineProperty(t,"ConnectionCheckOutStartedEvent",{enumerable:!0,get:function(){return q.ConnectionCheckOutStartedEvent}}),Object.defineProperty(t,"ConnectionClosedEvent",{enumerable:!0,get:function(){return q.ConnectionClosedEvent}}),Object.defineProperty(t,"ConnectionCreatedEvent",{enumerable:!0,get:function(){return q.ConnectionCreatedEvent}}),Object.defineProperty(t,"ConnectionPoolClearedEvent",{enumerable:!0,get:function(){return q.ConnectionPoolClearedEvent}}),Object.defineProperty(t,"ConnectionPoolClosedEvent",{enumerable:!0,get:function(){return q.ConnectionPoolClosedEvent}}),Object.defineProperty(t,"ConnectionPoolCreatedEvent",{enumerable:!0,get:function(){return q.ConnectionPoolCreatedEvent}}),Object.defineProperty(t,"ConnectionPoolMonitoringEvent",{enumerable:!0,get:function(){return q.ConnectionPoolMonitoringEvent}}),Object.defineProperty(t,"ConnectionPoolReadyEvent",{enumerable:!0,get:function(){return q.ConnectionPoolReadyEvent}}),Object.defineProperty(t,"ConnectionReadyEvent",{enumerable:!0,get:function(){return q.ConnectionReadyEvent}});var K=n(43135);Object.defineProperty(t,"ServerClosedEvent",{enumerable:!0,get:function(){return K.ServerClosedEvent}}),Object.defineProperty(t,"ServerDescriptionChangedEvent",{enumerable:!0,get:function(){return K.ServerDescriptionChangedEvent}}),Object.defineProperty(t,"ServerHeartbeatFailedEvent",{enumerable:!0,get:function(){return K.ServerHeartbeatFailedEvent}}),Object.defineProperty(t,"ServerHeartbeatStartedEvent",{enumerable:!0,get:function(){return K.ServerHeartbeatStartedEvent}}),Object.defineProperty(t,"ServerHeartbeatSucceededEvent",{enumerable:!0,get:function(){return K.ServerHeartbeatSucceededEvent}}),Object.defineProperty(t,"ServerOpeningEvent",{enumerable:!0,get:function(){return K.ServerOpeningEvent}}),Object.defineProperty(t,"TopologyClosedEvent",{enumerable:!0,get:function(){return K.TopologyClosedEvent}}),Object.defineProperty(t,"TopologyDescriptionChangedEvent",{enumerable:!0,get:function(){return K.TopologyDescriptionChangedEvent}}),Object.defineProperty(t,"TopologyOpeningEvent",{enumerable:!0,get:function(){return K.TopologyOpeningEvent}});var Y=n(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=n(4313);Object.defineProperty(t,"SrvPollingEvent",{enumerable:!0,get:function(){return Q.SrvPollingEvent}});var X=n(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=n(38944);Object.defineProperty(t,"MongoClientAuthProviders",{enumerable:!0,get:function(){return J.MongoClientAuthProviders}})},17172:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CountOperation=void 0;const r=n(75725),o=n(78130),i=n(35394);class s extends o.CommandOperation{constructor(e,t,n){super({s:{namespace:e}},n),this.SERVER_COMMAND_RESPONSE_TYPE=r.MongoDBResponse,this.options=n,this.collectionName=e.collection,this.query=t}get commandName(){return"count"}buildCommandDocument(e,t){const n=this.options,r={count:this.collectionName,query:this.query};return"number"==typeof n.limit&&(r.limit=n.limit),"number"==typeof n.skip&&(r.skip=n.skip),null!=n.hint&&(r.hint=n.hint),"number"==typeof n.maxTimeMS&&(r.maxTimeMS=n.maxTimeMS),r}handleOk(e){return e.getNumber("n")??0}}t.CountOperation=s,(0,i.defineAspects)(s,[i.Aspect.READ_OPERATION,i.Aspect.RETRYABLE])},17309:(e,t,n)=>{var r=n(65994).e;Object.defineProperty(t,"__esModule",{value:!0}),t.callback=void 0;const o=n(36374),i=n(17562);t.callback=async()=>{const e=r.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,r,o){if(e instanceof c)return!0;if(e instanceof n&&(r>=9||m(e))&&!e.hasErrorLabel(t.MongoErrorLabel.HandshakeError))return!1;if(e instanceof h){if("Mongos"===o&&r<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 n)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&&d.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||!y.has(e.code))},t.isSDAMUnrecoverableError=function(e){return e instanceof u||null==e||(E(e)||("number"==typeof(n=e).code?g.has(n.code):!E(n)&&t.LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE.test(n.message)));var n},t.isNetworkTimeoutError=function(e){return!!(e instanceof c&&e.message.match(/timed out/))},t.isResumableError=function(e,r){return null!=e&&e instanceof n&&(e instanceof c||(null!=r&&r>=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 n 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=n;class r extends n{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=r;class o extends n{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 r{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 n{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 n{constructor(e,t){t&&t.error?super(n.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 h extends r{constructor(e){super({...e.writeConcernError,...e}),this.errInfo=e.writeConcernError.errInfo,this.result=e}get name(){return"MongoWriteConcernError"}}t.MongoWriteConcernError=h;const d=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=d;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]),y=new Set([t.MONGODB_ERROR_CODES.InterruptedAtShutdown,t.MONGODB_ERROR_CODES.ShutdownInProgress]);function E(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,n)=>{var r=n(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 n,r="",o=0,i=-1,s=0,a=0;a<=e.length;++a){if(a<e.length)n=e.charCodeAt(a);else{if(47===n)break;n=47}if(47===n){if(i===a-1||1===s);else if(i!==a-1&&2===s){if(r.length<2||2!==o||46!==r.charCodeAt(r.length-1)||46!==r.charCodeAt(r.length-2))if(r.length>2){var c=r.lastIndexOf("/");if(c!==r.length-1){-1===c?(r="",o=0):o=(r=r.slice(0,c)).length-1-r.lastIndexOf("/"),i=a,s=0;continue}}else if(2===r.length||1===r.length){r="",o=0,i=a,s=0;continue}t&&(r.length>0?r+="/..":r="..",o=2)}else r.length>0?r+="/"+e.slice(i+1,a):r=e.slice(i+1,a),o=a-i-1;i=a,s=0}else 46===n&&-1!==s?++s:s=-1}return r}var s={resolve:function(){for(var e,t="",n=!1,s=arguments.length-1;s>=-1&&!n;s--){var a;s>=0?a=arguments[s]:(void 0===e&&(e=r.cwd()),a=e),o(a),0!==a.length&&(t=a+"/"+t,n=47===a.charCodeAt(0))}return t=i(t,!n),n?t.length>0?"/"+t:"/":t.length>0?t:"."},normalize:function(e){if(o(e),0===e.length)return".";var t=47===e.charCodeAt(0),n=47===e.charCodeAt(e.length-1);return 0!==(e=i(e,!t)).length||t||(e="."),e.length>0&&n&&(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 n=arguments[t];o(n),n.length>0&&(void 0===e?e=n:e+="/"+n)}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 n=1;n<e.length&&47===e.charCodeAt(n);++n);for(var r=e.length,i=r-n,a=1;a<t.length&&47===t.charCodeAt(a);++a);for(var c=t.length-a,u=i<c?i:c,l=-1,h=0;h<=u;++h){if(h===u){if(c>u){if(47===t.charCodeAt(a+h))return t.slice(a+h+1);if(0===h)return t.slice(a+h)}else i>u&&(47===e.charCodeAt(n+h)?l=h:0===h&&(l=0));break}var d=e.charCodeAt(n+h);if(d!==t.charCodeAt(a+h))break;47===d&&(l=h)}var p="";for(h=n+l+1;h<=r;++h)h!==r&&47!==e.charCodeAt(h)||(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),n=47===t,r=-1,i=!0,s=e.length-1;s>=1;--s)if(47===(t=e.charCodeAt(s))){if(!i){r=s;break}}else i=!1;return-1===r?n?"/":".":n&&1===r?"//":e.slice(0,r)},basename:function(e,t){if(void 0!==t&&"string"!=typeof t)throw new TypeError('"ext" argument must be a string');o(e);var n,r=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(n=e.length-1;n>=0;--n){var u=e.charCodeAt(n);if(47===u){if(!s){r=n+1;break}}else-1===c&&(s=!1,c=n+1),a>=0&&(u===t.charCodeAt(a)?-1==--a&&(i=n):(a=-1,i=c))}return r===i?i=c:-1===i&&(i=e.length),e.slice(r,i)}for(n=e.length-1;n>=0;--n)if(47===e.charCodeAt(n)){if(!s){r=n+1;break}}else-1===i&&(s=!1,i=n+1);return-1===i?"":e.slice(r,i)},extname:function(e){o(e);for(var t=-1,n=0,r=-1,i=!0,s=0,a=e.length-1;a>=0;--a){var c=e.charCodeAt(a);if(47!==c)-1===r&&(i=!1,r=a+1),46===c?-1===t?t=a:1!==s&&(s=1):-1!==t&&(s=-1);else if(!i){n=a+1;break}}return-1===t||-1===r||0===s||1===s&&t===r-1&&t===n+1?"":e.slice(t,r)},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 n=t.dir||t.root,r=t.base||(t.name||"")+(t.ext||"");return n?n===t.root?n+r:n+"/"+r:r}(0,e)},parse:function(e){o(e);var t={root:"",dir:"",base:"",ext:"",name:""};if(0===e.length)return t;var n,r=e.charCodeAt(0),i=47===r;i?(t.root="/",n=1):n=0;for(var s=-1,a=0,c=-1,u=!0,l=e.length-1,h=0;l>=n;--l)if(47!==(r=e.charCodeAt(l)))-1===c&&(u=!1,c=l+1),46===r?-1===s?s=l:1!==h&&(h=1):-1!==s&&(h=-1);else if(!u){a=l+1;break}return-1===s||-1===c||0===h||1===h&&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,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.RunCursorCommandOperation=t.RunCommandOperation=void 0;const r=n(75725),o=n(35394);class i extends o.AbstractOperation{constructor(e,t,n){super(n),this.SERVER_COMMAND_RESPONSE_TYPE=r.MongoDBResponse,this.command=t,this.options=n,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=r.CursorResponse}handleOk(e){return e}}},17846:(e,t)=>{var n=t;function r(e){return 1===e.length?"0"+e:e}function o(e){for(var t="",n=0;n<e.length;n++)t+=r(e[n].toString(16));return t}n.toArray=function(e,t){if(Array.isArray(e))return e.slice();if(!e)return[];var n=[];if("string"!=typeof e){for(var r=0;r<e.length;r++)n[r]=0|e[r];return n}if("hex"===t)for((e=e.replace(/[^a-z0-9]+/gi,"")).length%2!=0&&(e="0"+e),r=0;r<e.length;r+=2)n.push(parseInt(e[r]+e[r+1],16));else for(r=0;r<e.length;r++){var o=e.charCodeAt(r),i=o>>8,s=255&o;i?n.push(i,s):n.push(s)}return n},n.zero2=r,n.toHex=o,n.encode=function(e,t){return"hex"===t?o(e):e}},17851:function(e,t,n){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.MongoLogManager=void 0;const o=r(n(17642)),i=n(62444),s=n(8763),a=n(36374),c=n(25900),u=n(93974),l=n(97557),h=n(93874);t.MongoLogManager=class{constructor(e){if(e.prefix&&!/^[a-z0-9_]+$/i.test(e.prefix))throw new Error("Prefix must only contain letters, numbers, and underscores");this._options=e}async deleteFile(e){try{await a.promises.unlink(e)}catch(t){"ENOENT"!==t?.code&&this._options.onerror(t,e)}}get prefix(){return this._options.prefix??""}async cleanupOldLogFiles(e=5e3,t=1){const n=Date.now(),r=n-86400*this._options.retentionDays*1e3,s=this._options.directory;let c;try{c=await a.promises.opendir(s)}catch{return}const l=new u.Heap(((e,t)=>e.fileTimestamp-t.fileTimestamp)),h=!!this._options.retentionGB&&isFinite(this._options.retentionGB),d=!!this._options.maxLogFileCount&&isFinite(this._options.maxLogFileCount);let p=h?0:-1/0;try{for await(const t of c){if(Date.now()-n>e)break;if(!t.isFile())continue;const c=new RegExp(`^${this.prefix}(?<id>[a-f0-9]{24})_log(\\.gz)?$`,"i"),{id:u}=c.exec(t.name)?.groups??{};if(!u)continue;const m=+new i.ObjectId(u).getTimestamp(),f=o.default.join(s,t.name);if(m<r){await this.deleteFile(f);continue}let g;if(h)try{g=(await a.promises.stat(f)).size,p+=g}catch(e){this._options.onerror(e,f);continue}if((d||h)&&l.push({fullPath:f,fileTimestamp:m,fileSize:g}),d&&this._options.maxLogFileCount&&l.size()>this._options.maxLogFileCount){const e=l.pop();if(!e)continue;await this.deleteFile(e.fullPath),p-=e.fileSize??0}}}catch(r){"ENOENT"===r.code&&t>0&&await this.cleanupOldLogFiles(e-(Date.now()-n),t-1)}if(h&&this._options.retentionGB){const t=1024*this._options.retentionGB*1024*1024;for(const r of l){if(Date.now()-n>e)break;if(p<=t)break;r.fileSize&&(await this.deleteFile(r.fullPath),p-=r.fileSize)}}}async createLogWriter(){const e=(new i.ObjectId).toString(),t=!!this._options.gzip,n=o.default.join(this._options.directory,`${this.prefix}${e}_log${t?".gz":""}`);let r,u,d;try{u=(0,a.createWriteStream)(n,{mode:384}),r=u,await(0,s.once)(u,"ready"),t?(u=(0,c.createGzip)({flush:c.constants.Z_SYNC_FLUSH,level:c.constants.Z_MAX_LEVEL}),u.pipe(r)):u.on("finish",(()=>u.emit("log-finish")))}catch(t){this._options.onwarn(t,n),u=new h.Writable({write(e,t,n){n()}}),r=u,d=new l.MongoLogWriter(e,null,u)}return d||(d=new l.MongoLogWriter(e,n,u)),r.on("finish",(()=>d?.emit("log-finish"))),d}}},18758:(e,t,n)=>{n.d(t,{oW:()=>o});var r=n(91174);r.MongoLogManager,r.MongoLogWriter;const o=r.mongoLogId},19043:(e,t,n)=>{var r=n(65994).e;Object.defineProperty(t,"__esModule",{value:!0}),t.LegacyAWSTemporaryCredentialProvider=t.AWSSDKCredentialProvider=t.AWSTemporaryCredentialProvider=void 0;const o=n(8500),i=n(17562),s=n(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=""}=r.env;e=e.toLowerCase(),t=t.toLowerCase();const n=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=n&&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(r.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI)return await(0,s.request)(`http://169.254.170.2${r.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,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Collection=void 0;const r=n(75080),o=n(29348),i=n(10089),s=n(22345),a=n(68526),c=n(5465),u=n(32361),l=n(71906),h=n(17562),d=n(17172),p=n(4752),m=n(815),f=n(93549),g=n(96357),y=n(61635),E=n(22847),S=n(9326),O=n(61861),C=n(32443),v=n(97350),b=n(40866),w=n(94330),M=n(28541),T=n(13700),_=n(145),A=n(40012);t.Collection=class{constructor(e,t,n){this.s={db:e,options:n,namespace:new _.MongoDBCollectionNamespace(e.databaseName,t),pkFactory:e.options?.pkFactory??_.DEFAULT_PK_FACTORY,readPreference:T.ReadPreference.fromOptions(n),bsonOptions:(0,r.resolveBSONOptions)(n,e),readConcern:M.ReadConcern.fromOptions(n),writeConcern:A.WriteConcern.fromOptions(n)},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 S.InsertOneOperation(this,e,(0,_.resolveOptions)(this,t)))}async insertMany(e,t){if(!Array.isArray(e))throw new h.MongoInvalidArgumentError('Argument "docs" must be an array of documents');t=(0,_.resolveOptions)(this,t??{});const n=0!==A.WriteConcern.fromOptions(t)?.w;try{const r=await this.bulkWrite(e.map((e=>({insertOne:{document:e}}))),t);return{acknowledged:n,insertedCount:r.insertedCount,insertedIds:r.insertedIds}}catch(e){if(e&&"Operation must be an object with an operation key"===e.message)throw new h.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 h.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 n=!1===t.ordered?this.initializeUnorderedBulkOp(t):this.initializeOrderedBulkOp(t);for(const t of e)n.raw(t);return await n.execute({...t})}async updateOne(e,t,n){return await(0,g.executeOperation)(this.client,new w.UpdateOneOperation(this.s.namespace,e,t,(0,_.resolveOptions)(this,n)))}async replaceOne(e,t,n){return await(0,g.executeOperation)(this.client,new w.ReplaceOneOperation(this.s.namespace,e,t,(0,_.resolveOptions)(this,n)))}async updateMany(e,t,n){return await(0,g.executeOperation)(this.client,new w.UpdateManyOperation(this.s.namespace,e,t,(0,_.resolveOptions)(this,n)))}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 O.RenameOperation(this,e,(0,_.resolveOptions)(void 0,{...t,readPreference:T.ReadPreference.PRIMARY})))}async drop(e){return await this.s.db.dropCollection(this.collectionName,e)}async findOne(e={},t={}){const{batchSize:n,noCursorTimeout:r,...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 h.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,E.CreateIndexesOperation.fromIndexSpecification(this,this.collectionName,e,(0,_.resolveOptions)(this,t))))[0]}async createIndexes(e,t){return await(0,g.executeOperation)(this.client,E.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 E.DropIndexOperation(this,e,{...(0,_.resolveOptions)(this,t),readPreference:T.ReadPreference.primary}))}async dropIndexes(e){try{return await(0,g.executeOperation)(this.client,new E.DropIndexOperation(this,"*",(0,_.resolveOptions)(this,e))),!0}catch(e){if(e instanceof h.MongoOperationTimeoutError)throw e;return!1}}listIndexes(e){return new u.ListIndexesCursor(this,(0,_.resolveOptions)(this,e))}async indexExists(e,t){const n=Array.isArray(e)?e:[e],r=new Set(await this.listIndexes(t).map((({name:e})=>e)).toArray());return n.every((e=>r.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 n=[];n.push({$match:e}),"number"==typeof t.skip&&n.push({$skip:t.skip}),"number"==typeof t.limit&&n.push({$limit:t.limit}),n.push({$group:{_id:1,n:{$sum:1}}});const r=this.aggregate(n,t),o=await r.next();return await r.close(),o?.n??0}async distinct(e,t={},n={}){return await(0,g.executeOperation)(this.client,new m.DistinctOperation(this,e,t,(0,_.resolveOptions)(this,n)))}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 y.FindOneAndDeleteOperation(this,e,(0,_.resolveOptions)(this,t)))}async findOneAndReplace(e,t,n){return await(0,g.executeOperation)(this.client,new y.FindOneAndReplaceOperation(this,e,t,(0,_.resolveOptions)(this,n)))}async findOneAndUpdate(e,t,n){return await(0,g.executeOperation)(this.client,new y.FindOneAndUpdateOperation(this,e,t,(0,_.resolveOptions)(this,n)))}aggregate(e=[],t){if(!Array.isArray(e))throw new h.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 d.CountOperation(this.fullNamespace,e,(0,_.resolveOptions)(this,t)))}listSearchIndexes(e,t){t="object"==typeof e?e:null==t?{}:t;const n=null==e||"object"==typeof e?null:e;return new l.ListSearchIndexesCursor(this,n,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 v.DropSearchIndexOperation(this,e))}async updateSearchIndex(e,t){return await(0,g.executeOperation)(this.client,new b.UpdateSearchIndexOperation(this,e,t))}}},19917:(e,t,n)=>{var r;n.d(t,{s:()=>r}),function(e){e[e.UNSET=0]="UNSET",e[e.OK=1]="OK",e[e.ERROR=2]="ERROR"}(r||(r={}))},21119:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MongoDBAWS=void 0;const r=n(75080),o=n(8500),i=n(17562),s=n(145),a=n(31057),c=n(19043),u=n(91566),l=n(93065),h={useBigInt64:!1,promoteLongs:!0,promoteValues:!0,promoteBuffers:!1,bsonRegExp:!1};class d 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:n}=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,d=a.password,m=a.mechanismProperties.AWS_SESSION_TOKEN,f=c&&d&&m?{accessKeyId:c,secretAccessKey:d,sessionToken:m}:c&&d?{accessKeyId:c,secretAccessKey:d}:void 0,g=a.source,y=await(0,s.randomBytes)(32),E={saslStart:1,mechanism:"MONGODB-AWS",payload:r.serialize({r:y,p:110},h)},S=await t.command((0,s.ns)(`${g}.$cmd`),E,void 0),O=r.deserialize(S.payload.buffer,h),C=O.h,v=O.s.buffer;if(64!==v.length)throw new i.MongoRuntimeError(`Invalid server nonce length ${v.length}, expected 64`);if(!s.ByteUtils.equals(v.subarray(0,y.byteLength),y))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 b=n({method:"POST",host:C,region:p(O.h),service:"sts",headers:{"Content-Type":"application/x-www-form-urlencoded","Content-Length":43,"X-MongoDB-Server-Nonce":s.ByteUtils.toBase64(v),"X-MongoDB-GS2-CB-Flag":"n"},path:"/",body:"Action=GetCallerIdentity&Version=2011-06-15"},f),w={a:b.headers.Authorization,d:b.headers["X-Amz-Date"]};m&&(w.t=m);const M={saslContinue:1,conversationId:S.conversationId,payload:r.serialize(w,h)};await t.command((0,s.ns)(`${g}.$cmd`),M,void 0)}}function p(e){const t=e.split(".");return 1===t.length||"amazonaws"===t[1]?"us-east-1":t[1]}t.MongoDBAWS=d},22220:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MongoClient=t.ServerApiVersion=void 0;const r=n(36374),o=n(75080),i=n(22345),s=n(91566),a=n(93065),c=n(56463),u=n(75725),l=n(6875),h=n(91869),d=n(44120),p=n(17562),m=n(38944),f=n(93347),g=n(4642),y=n(47523),E=n(96357),S=n(35394),O=n(13700),C=n(31790),v=n(30588),b=n(1759),w=n(14019),M=n(145);t.ServerApiVersion=Object.freeze({v1:"1"});class T extends g.TypedEventEmitter{constructor(e,t){super(),this.on("error",M.noop),this.options=(0,l.parseOptions)(e,this,t);const n=Object.values(this.options.mongoLoggerOptions.componentSeverities).some((e=>e!==f.SeverityLevel.OFF));this.mongoLogger=n?new f.MongoLogger(this.options.mongoLoggerOptions):void 0;const r=this;this.s={url:e,bsonOptions:(0,o.resolveBSONOptions)(this.options),namespace:(0,M.ns)("admin"),hasBeenClosed:!1,sessionPool:new w.ServerSessionPool(this),activeSessions:new Set,activeCursors:new Set,authProviders:new m.MongoClientAuthProviders,get options(){return r.options},get readConcern(){return r.options.readConcern},get writeConcern(){return r.options.writeConcern},get readPreference(){return r.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,M.squashError).then((e=>e??{}))}checkForNonGenuineHosts(){const e=this.options.hosts.filter((e=>(0,M.isHostMatch)(M.DOCUMENT_DB_CHECK,e.host))),t=(0,M.isHostMatch)(M.DOCUMENT_DB_CHECK,this.options.srvHost),n=this.options.hosts.filter((e=>(0,M.isHostMatch)(M.COSMOS_DB_CHECK,e.host))),r=(0,M.isHostMatch)(M.COSMOS_DB_CHECK,this.options.srvHost);0!==e.length||t?this.mongoLogger?.info("client",M.DOCUMENT_DB_MSG):(0!==n.length||r)&&this.mongoLogger?.info("client",M.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 y.ClientBulkWriteExecutor(this,e,(0,M.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 r.promises.readFile(e.tlsCAFile)),"string"==typeof e.tlsCRLFile&&(e.crl??=await r.promises.readFile(e.tlsCRLFile)),!("string"!=typeof e.tlsCertificateKeyFile||e.key&&e.cert))){const t=await r.promises.readFile(e.tlsCertificateKeyFile);e.key??=t,e.cert??=t}if("string"==typeof e.srvHost){const t=await(0,l.resolveSRVRecord)(e);for(const[n,r]of t.entries())e.hosts[n]=r}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 n of e.hosts)if(!(0,M.hostMatchesWildcards)(n.toHostPort().host,t))throw new p.MongoInvalidArgumentError(`Host '${n}' is not valid for OIDC authentication with ALLOWED_HOSTS of '${t.join(",")}'`)}this.topology=new b.Topology(this,e.hosts,e),this.topology.once(b.Topology.OPEN,(()=>this.emit("open",this)));for(const e of h.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 n=(0,v.readPreferenceServerSelector)(O.ReadPreference.primaryPreferred),r=this.topology.description,o=Array.from(r.servers.values());if(0!==n(r,o).length){const e=Array.from(this.s.sessionPool.sessions,(({id:e})=>e));if(0!==e.length)try{class t extends S.AbstractOperation{constructor(){super(...arguments),this.ns=M.MongoDBNamespace.fromString("admin.$cmd"),this.SERVER_COMMAND_RESPONSE_TYPE=u.MongoDBResponse}buildCommand(t,n){return{endSessions:e}}buildOptions(e){return{timeoutContext:e,readPreference:O.ReadPreference.primaryPreferred,noResponse:!0}}get commandName(){return"endSessions"}}await(0,E.executeOperation)(this,new t)}catch(e){(0,M.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 n=Object.assign({},this.options,t);return new d.Db(this,e,n)}static async connect(e,t){const n=new this(e,t);return await n.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 n={owner:Symbol(),..."object"==typeof e?e:{}},r="function"==typeof e?e:t;if(null==r)throw new p.MongoInvalidArgumentError("Missing required callback parameter");const o=this.startSession(n);try{return await r(o)}finally{try{await o.endSession()}catch(e){(0,M.squashError)(e)}}}watch(e=[],t={}){return Array.isArray(e)||(t=e,e=[]),new i.ChangeStream(this,e,(0,M.resolveOptions)(this,t))}}t.MongoClient=T,(0,C.configureResourceManagement)(T.prototype)},22345:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ChangeStream=void 0;const r=n(19498),o=n(91869),i=n(61066),s=n(40251),a=n(44120),c=n(17562),u=n(22220),l=n(4642),h=n(31790),d=n(7799),p=n(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],y="ChangeStream is closed";class E extends l.TypedEventEmitter{async asyncDispose(){await this.close()}constructor(e,t=[],n={}){let o;if(super(),this.pipeline=t,this.options={...n},delete this.options.writeConcern,e instanceof r.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(n),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 d.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(y);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 n=[{$changeStream:t},...this.pipeline],r=this.type===f.CLUSTER?this.parent:this.type===f.DATABASE||this.type===f.COLLECTION?this.parent.client:null;if(null==r)throw new c.MongoRuntimeError(`Changestream type should only be one of cluster, database, collection. Found ${this.type.toString()}`);const o=new s.ChangeStreamCursor(r,this.namespace,n,{...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(E.CHANGE)>0&&this._streamEvents(o),o}_closeEmitterModeWithError(e){this.emit(E.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(E.CHANGE,t)}catch(e){this.emit(E.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(y);if(null==e)throw new c.MongoRuntimeError(y);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(E.ERROR,e)}),(()=>this._closeEmitterModeWithError(e)))):this._closeEmitterModeWithError(e))}async _processErrorIteratorMode(e,t){if(this.isClosed)throw new c.MongoAPIError(y);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=E,E.RESPONSE=o.RESPONSE,E.MORE=o.MORE,E.INIT=o.INIT,E.CLOSE=o.CLOSE,E.CHANGE=o.CHANGE,E.END=o.END,E.ERROR=o.ERROR,E.RESUME_TOKEN_CHANGED=o.RESUME_TOKEN_CHANGED,(0,h.configureResourceManagement)(E.prototype)},22847:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ListIndexesOperation=t.DropIndexOperation=t.CreateIndexesOperation=void 0;const r=n(75725),o=n(17562),i=n(145),s=n(78130),a=n(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,n,o){super(e,o),this.SERVER_COMMAND_RESPONSE_TYPE=r.MongoDBResponse,this.options=o??{},this.options.collation=void 0,this.collectionName=t,this.indexes=n.map((e=>{const t=e.key instanceof Map?e.key:new Map(Object.entries(e.key)),n=e.name??Array.from(t).flat().join("_"),r=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{...r,name:n,key:t}})),this.ns=e.s.namespace}static fromIndexDescriptionArray(e,t,n,r){return new u(e,t,n,r)}static fromIndexSpecification(e,t,n,r={}){const o=function(e){const t=new Map,n=Array.isArray(e)&&(r=e,!Array.isArray(r)||2!==r.length||"number"!=typeof(o=r[1])&&"2d"!==o&&"2dsphere"!==o&&"text"!==o&&"geoHaystack"!==o)?e:[e];var r,o;for(const e of n)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[n,r]of e)t.set(n,r);else if((0,i.isObject)(e))for(const[n,r]of Object.entries(e))t.set(n,r);return t}(n),s={...r,key:o};return new u(e,t,[s],r)}get commandName(){return"createIndexes"}buildCommandDocument(e){const t=this.options,n=this.indexes,r=(0,i.maxWireVersion)(e),s={createIndexes:this.collectionName,indexes:n};if(null!=t.commitQuorum){if(r<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,n){super(e,n),this.SERVER_COMMAND_RESPONSE_TYPE=r.MongoDBResponse,this.options=n??{},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 h extends s.CommandOperation{constructor(e,t){super(e,t),this.SERVER_COMMAND_RESPONSE_TYPE=r.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),n=this.options.batchSize?{batchSize:this.options.batchSize}:{},r={listIndexes:this.collectionNamespace.collection,cursor:n};return t>=9&&void 0!==this.options.comment&&(r.comment=this.options.comment),r}handleOk(e){return e}}t.ListIndexesOperation=h,(0,a.defineAspects)(h,[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,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StreamDescription=void 0;const r=n(75080),o=n(89167),i=n(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 r.Long.isLong(e)?e.toBigInt():BigInt(e)}}},25220:(e,t,n)=>{n.d(t,{Ay:()=>o});var r=n(12453);const o=r;r.MAX_DATABASE_NAME_LENGTH,r.sort},25364:function(e,t,n){var r,o=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var o=Object.getOwnPropertyDescriptor(t,n);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,o)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||(r=function(e){return r=Object.getOwnPropertyNames||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[t.length]=n);return t},r(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n=r(e),s=0;s<n.length;s++)"default"!==n[s]&&o(t,e,n[s]);return i(t,e),t}),a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.DEFAULT_HINT=t.DEFAULT_MAX_TIME_MS=t.DEFAULT_COLLATION=t.DEFAULT_PROJECT=t.DEFAULT_SKIP=t.DEFAULT_LIMIT=t.DEFAULT_SORT=t.DEFAULT_FILTER=t.toJSString=t.stringify=void 0,t.parseSort=T,t.parseFilter=function(e){return v(e)?m:A(e)},t.parseCollation=function(e){return v(e)?S:M(e)},t.isFilterValid=R,t.isCollationValid=N,t.parseProject=function(e){return v(e)?E:w(e)},t.isProjectValid=x,t.isSortValid=L,t.isHintValid=B,t.isMaxTimeMSValid=j,t.isSkipValid=F,t.isLimitValid=U,t.validate=function(e,t){const n=z[`is${u.default.upperFirst(e)}Valid`];return n?n(t):(p("Do not know how to validate `%s`. Returning false.",e),!1)},t.default=function(e,t=E){return 1===arguments.length&&u.default.isString(e)?A(e):{filter:A(e),project:t!==E?w(t):t}};const c=s(n(9651)),u=a(n(20990)),l=a(n(46696)),h=n(79193),d=n(60313);Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return d.stringify}}),Object.defineProperty(t,"toJSString",{enumerable:!0,get:function(){return d.toJSString}});const p=(0,l.default)("mongodb-query-parser"),m={};t.DEFAULT_FILTER=m;const f=null;t.DEFAULT_SORT=f;const g=0;t.DEFAULT_LIMIT=g;const y=0;t.DEFAULT_SKIP=y;const E=null;t.DEFAULT_PROJECT=E;const S=null;t.DEFAULT_COLLATION=S;const O=6e4;t.DEFAULT_MAX_TIME_MS=O;const C=null;function v(e){if(null==e)return!0;const t=u.default.trim("number"==typeof e?`${e}`:e);return"{}"===t||u.default.isEmpty(t)}function b(e){return v(e)?0:!!/^\d+$/.test(`${e}`)&&parseInt(`${e}`,10)}function w(e){return(0,c.default)(e,{mode:c.ParseMode.Loose})}function M(e){return(0,c.default)(e,{mode:c.ParseMode.Loose})}function T(e){return v(e)?f:(0,c.default)(e,{mode:c.ParseMode.Loose})}function _(){return!0}function A(e){return(0,c.default)(e,{mode:c.ParseMode.Loose,allowMethods:!0})}function R(e){if(v(e))return m;try{return A(e)}catch(t){return p('Filter "%s" is invalid',e,t),!1}}function N(e){if(v(e))return S;try{return function(e){for(const[t,n]of Object.entries(e)){if(!h.COLLATION_OPTIONS[t])return p('Collation "%s" is invalid bc of its keys',e),!1;if(!1===h.COLLATION_OPTIONS[t].includes(n))return p('Collation "%s" is invalid bc of its values',e),!1}return e}(M(e))}catch(t){return p('Collation "%s" is invalid',e,t),!1}}function I(){return!0}function x(e){if(v(e))return E;try{const t=w(e);return u.default.isObject(t)?u.default.every(t,I)?t:(p('Project "%s" is invalid bc of its values',e),!1):(p('Project "%s" is invalid. Only documents are allowed',e),!1)}catch(t){return p('Project "%s" is invalid',e,t),!1}}t.DEFAULT_HINT=C;const P=[1,-1,"asc","desc"];function k(e){return u.default.includes(P,e)||!(!u.default.isObject(e)||!e.$meta)}function D(e){return u.default.isArray(e)&&2===e.length&&u.default.isString(e[0])&&k(e[1])}function L(e){try{const t=T(e);return v(t)?f:u.default.isArray(t)&&u.default.every(t,D)||u.default.isObject(t)&&!u.default.isArray(t)&&u.default.every(t,k)?t:(p('Sort "%s" is invalid bc of its values',e),!1)}catch(t){return p('Sort "%s" is invalid',e,t),!1}}function B(e){if(v(e))return C;try{const t=function(e){return(0,c.default)(e,{mode:c.ParseMode.Loose})}(e);return u.default.isString(t)?t:u.default.isArray(t)||!u.default.isObject(t)?(p('Hint "%s" is invalid. Only strings or documents are allowed',e),!1):u.default.every(t,_)?t:(p('Hint "%s" is invalid bc of its values',e),!1)}catch(t){return p('Hint "%s" is invalid',e,t),!1}}function j(e){return v(e)?O:b(e)}function F(e){return v(e)?y:b(e)}function U(e){return v(e)?g:b(e)}const z={isMaxTimeMSValid:j,isFilterValid:R,isProjectValid:x,isSortValid:L,isLimitValid:U,isSkipValid:F,isCollationValid:N,isNumberValid:b,isHintValid:B}},26767:(e,t,n)=>{n.d(t,{u:()=>G});var r="object"==typeof globalThis?globalThis:"object"==typeof self?self:"object"==typeof window?window:"object"==typeof n.g?n.g:{},o="1.9.0",i=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/,s=function(e){var t=new Set([e]),n=new Set,r=e.match(i);if(!r)return function(){return!1};var o=+r[1],s=+r[2],a=+r[3];if(null!=r[4])return function(t){return t===e};function c(e){return n.add(e),!1}function u(e){return t.add(e),!0}return function(e){if(t.has(e))return!0;if(n.has(e))return!1;var r=e.match(i);if(!r)return c(e);var l=+r[1],h=+r[2],d=+r[3];return null!=r[4]||o!==l?c(e):0===o?s===h&&a<=d?u(e):c(e):s<=h?u(e):c(e)}}(o),a=o.split(".")[0],c=Symbol.for("opentelemetry.js.api."+a),u=r;function l(e,t,n,r){var i;void 0===r&&(r=!1);var s=u[c]=null!==(i=u[c])&&void 0!==i?i:{version:o};if(!r&&s[e]){var a=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+e);return n.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),n.error(a.stack||a.message),!1):(s[e]=t,n.debug("@opentelemetry/api: Registered a global for "+e+" v"+o+"."),!0)}function h(e){var t,n,r=null===(t=u[c])||void 0===t?void 0:t.version;if(r&&s(r))return null===(n=u[c])||void 0===n?void 0:n[e]}function d(e,t){t.debug("@opentelemetry/api: Unregistering a global for "+e+" v"+o+".");var n=u[c];n&&delete n[e]}var p,m=new function e(t){var n=this;n._currentContext=t?new Map(t):new Map,n.getValue=function(e){return n._currentContext.get(e)},n.setValue=function(t,r){var o=new e(n._currentContext);return o._currentContext.set(t,r),o},n.deleteValue=function(t){var r=new e(n._currentContext);return r._currentContext.delete(t),r}},f=function(){function e(){}return e.prototype.active=function(){return m},e.prototype.with=function(e,t,n){for(var r=[],o=3;o<arguments.length;o++)r[o-3]=arguments[o];return t.call.apply(t,function(e,t,n){if(n||2===arguments.length)for(var r,o=0,i=t.length;o<i;o++)!r&&o in t||(r||(r=Array.prototype.slice.call(t,0,o)),r[o]=t[o]);return e.concat(r||Array.prototype.slice.call(t))}([n],function(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,o,i=n.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(r=i.next()).done;)s.push(r.value)}catch(e){o={error:e}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(o)throw o.error}}return s}(r),!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 y("debug",this._namespace,e)},e.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return y("error",this._namespace,e)},e.prototype.info=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return y("info",this._namespace,e)},e.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return y("warn",this._namespace,e)},e.prototype.verbose=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return y("verbose",this._namespace,e)},e}();function y(e,t,n){var r=h("diag");if(r)return n.unshift(t),r[e].apply(r,function(e,t,n){if(n||2===arguments.length)for(var r,o=0,i=t.length;o<i;o++)!r&&o in t||(r||(r=Array.prototype.slice.call(t,0,o)),r[o]=t[o]);return e.concat(r||Array.prototype.slice.call(t))}([],function(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,o,i=n.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(r=i.next()).done;)s.push(r.value)}catch(e){o={error:e}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(o)throw o.error}}return s}(n),!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 E,S=function(){function e(){function e(e){return function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];var r=h("diag");if(r)return r[e].apply(r,function(e,t,n){if(n||2===arguments.length)for(var r,o=0,i=t.length;o<i;o++)!r&&o in t||(r||(r=Array.prototype.slice.call(t,0,o)),r[o]=t[o]);return e.concat(r||Array.prototype.slice.call(t))}([],function(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,o,i=n.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(r=i.next()).done;)s.push(r.value)}catch(e){o={error:e}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(o)throw o.error}}return s}(t),!1))}}var t=this;t.setLogger=function(e,n){var r,o,i;if(void 0===n&&(n={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!==(r=s.stack)&&void 0!==r?r:s.message),!1}"number"==typeof n&&(n={logLevel:n});var a=h("diag"),c=function(e,t){function n(n,r){var o=t[n];return"function"==typeof o&&e>=r?o.bind(t):function(){}}return e<p.NONE?e=p.NONE:e>p.ALL&&(e=p.ALL),t=t||{},{error:n("error",p.ERROR),warn:n("warn",p.WARN),info:n("info",p.INFO),debug:n("debug",p.DEBUG),verbose:n("verbose",p.VERBOSE)}}(null!==(o=n.logLevel)&&void 0!==o?o:p.INFO,e);if(a&&!n.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(){d("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}(),O="context",C=new f,v=function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalContextManager=function(e){return l(O,e,S.instance())},e.prototype.active=function(){return this._getContextManager().active()},e.prototype.with=function(e,t,n){for(var r,o=[],i=3;i<arguments.length;i++)o[i-3]=arguments[i];return(r=this._getContextManager()).with.apply(r,function(e,t,n){if(n||2===arguments.length)for(var r,o=0,i=t.length;o<i;o++)!r&&o in t||(r||(r=Array.prototype.slice.call(t,0,o)),r[o]=t[o]);return e.concat(r||Array.prototype.slice.call(t))}([e,t,n],function(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,o,i=n.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(r=i.next()).done;)s.push(r.value)}catch(e){o={error:e}}finally{try{r&&!r.done&&(n=i.return)&&n.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 h(O)||C},e.prototype.disable=function(){this._getContextManager().disable(),d(O,S.instance())},e}();!function(e){e[e.NONE=0]="NONE",e[e.SAMPLED=1]="SAMPLED"}(E||(E={}));var b="0000000000000000",w="00000000000000000000000000000000",M={traceId:w,spanId:b,traceFlags:E.NONE},T=function(){function e(e){void 0===e&&(e=M),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 A(e){return e.getValue(_)||void 0}function R(){return A(v.getInstance().active())}function N(e,t){return e.setValue(_,t)}function I(e){return e.deleteValue(_)}function x(e,t){return N(e,new T(t))}function P(e){var t;return null===(t=A(e))||void 0===t?void 0:t.spanContext()}var k=/^([0-9a-f]{32})$/i,D=/^[0-9a-f]{16}$/i;function L(e){return n=e.traceId,k.test(n)&&n!==w&&(t=e.spanId,D.test(t)&&t!==b);var t,n}function B(e){return new T(e)}var j=v.getInstance(),F=function(){function e(){}return e.prototype.startSpan=function(e,t,n){if(void 0===n&&(n=j.active()),Boolean(null==t?void 0:t.root))return new T;var r,o=n&&P(n);return"object"==typeof(r=o)&&"string"==typeof r.spanId&&"string"==typeof r.traceId&&"number"==typeof r.traceFlags&&L(o)?new T(o):new T},e.prototype.startActiveSpan=function(e,t,n,r){var o,i,s;if(!(arguments.length<2)){2===arguments.length?s=t:3===arguments.length?(o=t,s=n):(o=t,i=n,s=r);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}(),U=new F,z=function(){function e(e,t,n,r){this._provider=e,this.name=t,this.version=n,this.options=r}return e.prototype.startSpan=function(e,t,n){return this._getTracer().startSpan(e,t,n)},e.prototype.startActiveSpan=function(e,t,n,r){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):U},e}(),V=new(function(){function e(){}return e.prototype.getTracer=function(e,t,n){return new F},e}()),$=function(){function e(){}return e.prototype.getTracer=function(e,t,n){var r;return null!==(r=this.getDelegateTracer(e,t,n))&&void 0!==r?r:new z(this,e,t,n)},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,n){var r;return null===(r=this._delegate)||void 0===r?void 0:r.getTracer(e,t,n)},e}(),W="trace",G=function(){function e(){this._proxyTracerProvider=new $,this.wrapSpanContext=B,this.isSpanContextValid=L,this.deleteSpan=I,this.getSpan=A,this.getActiveSpan=R,this.getSpanContext=P,this.setSpan=N,this.setSpanContext=x}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalTracerProvider=function(e){var t=l(W,this._proxyTracerProvider,S.instance());return t&&this._proxyTracerProvider.setDelegate(e),t},e.prototype.getTracerProvider=function(){return h(W)||this._proxyTracerProvider},e.prototype.getTracer=function(e,t){return this.getTracerProvider().getTracer(e,t)},e.prototype.disable=function(){d(W,S.instance()),this._proxyTracerProvider=new $},e}().getInstance()},28113:(e,t,n)=>{var r=n(92992),o=n(81892),i=n(40642),s=n(90686),a=n(76023),c=n(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 n,u,l=i(e,t),h=l.tag,d=l.data;switch(h){case"CERTIFICATE":u=r.certificate.decode(d,"der").tbsCertificate.subjectPublicKeyInfo;case"PUBLIC KEY":switch(u||(u=r.PublicKey.decode(d,"der")),n=u.algorithm.algorithm.join(".")){case"1.2.840.113549.1.1.1":return r.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=r.DSAparam.decode(u.subjectPublicKey.data,"der"),{type:"dsa",data:u.algorithm.params};default:throw new Error("unknown key id "+n)}case"ENCRYPTED PRIVATE KEY":d=function(e,t){var n=e.algorithm.decrypt.kde.kdeparams.salt,r=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,h=parseInt(i.split("-")[1],10)/8,d=a.pbkdf2Sync(t,n,r,h,"sha1"),p=s.createDecipheriv(i,d,u),m=[];return m.push(p.update(l)),m.push(p.final()),c.concat(m)}(d=r.EncryptedPrivateKey.decode(d,"der"),t);case"PRIVATE KEY":switch(n=(u=r.PrivateKey.decode(d,"der")).algorithm.algorithm.join(".")){case"1.2.840.113549.1.1.1":return r.RSAPrivateKey.decode(u.subjectPrivateKey,"der");case"1.2.840.10045.2.1":return{curve:u.algorithm.curve,privateKey:r.ECPrivateKey.decode(u.subjectPrivateKey,"der").privateKey};case"1.2.840.10040.4.1":return u.algorithm.params.priv_key=r.DSAparam.decode(u.subjectPrivateKey,"der"),{type:"dsa",params:u.algorithm.params};default:throw new Error("unknown key id "+n)}case"RSA PUBLIC KEY":return r.RSAPublicKey.decode(d,"der");case"RSA PRIVATE KEY":return r.RSAPrivateKey.decode(d,"der");case"DSA PRIVATE KEY":return{type:"dsa",params:r.DSAPrivateKey.decode(d,"der")};case"EC PRIVATE KEY":return{curve:(d=r.ECPrivateKey.decode(d,"der")).parameters.value,privateKey:d.privateKey};default:throw new Error("unknown key type "+h)}}u.signature=r.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 n{constructor(e){this.level=t.ReadConcernLevel[e]??e}static fromOptions(e){if(null!=e){if(e.readConcern){const{readConcern:t}=e;if(t instanceof n)return t;if("string"==typeof t)return new n(t);if("level"in t&&t.level)return new n(t.level)}return e.level?new n(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=n},29009:function(e,t,n){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.getDataLake=function(e){return p(e)&&p(e.dataLake)&&"string"==typeof e.dataLake.version?{isDataLake:!0,dlVersion:e.dataLake.version}:{isDataLake:!1,dlVersion:null}},t.isEnterprise=function(e){return!!p(e)&&(!("string"!=typeof e.gitVersion||!e.gitVersion.match(/enterprise/))||!(!Array.isArray(e.modules)||-1===e.modules.indexOf("enterprise")))},t.isAtlas=function(e){return!!f(e).match(s)},t.isLocalAtlas=async function(e){try{return await e("admin","atlascli",{managedClusterType:"atlasCliLocalDevCluster"})>0}catch{return!1}},t.isAtlasStream=function(e){const t=f(e);return!(!t.match(s)||!t.match(a))},t.isLocalhost=function(e){return!!f(e).match(c)},t.isDigitalOcean=function(e){return!!f(e).match(u)},t.getGenuineMongoDB=function(e){const t=f(e);return t.match(l)?{isGenuine:!1,serverName:"cosmosdb"}:t.match(h)?{isGenuine:!1,serverName:"documentdb"}:{isGenuine:!0,serverName:"mongodb"}},t.identifyServerName=async function({connectionString:e,adminCommand:t}){try{const n=f(e);if(n.match(s))return"mongodb";if(n.match(l))return"cosmosdb";if(n.match(h))return"documentdb";if(n.match(d))return"firestore";const r=await Promise.all([t({buildInfo:1}).then((e=>"ferretdb"in e?["ferretdb"]:[]),(e=>(i("buildInfo command failed %O",e),[]))),t({getParameter:"foo"}).then((()=>[]),(e=>e instanceof Error&&/documentdb_api/.test(e.message)?["pg_documentdb"]:[]))]).then((e=>e.flat()));return 0===r.length?"mongodb":1===r.length?r[0]:"unknown"}catch(e){return i("Failed to identify server name",e),"unknown"}},t.getBuildEnv=function(e){if(!p(e)||!p(e.buildEnvironment))return{serverOs:null,serverArch:null};const{buildEnvironment:t}=e;return{serverOs:"string"==typeof t.target_os?t.target_os:null,serverArch:"string"==typeof t.target_arch?t.target_arch:null}};const o=r(n(65031)),i=(0,n(46696).debug)("mongodb-build-info"),s=/\.mongodb(-dev|-qa|-stage)?\.net$/i,a=/^atlas-stream-.+/i,c=/^(localhost|127\.([01]?[0-9][0-9]?|2[0-4][0-9]|25[0-5])\.([01]?[0-9][0-9]?|2[0-4][0-9]|25[0-5])\.([01]?[0-9][0-9]?|2[0-4][0-9]|25[0-5])|0\.0\.0\.0|(?:0*:)*?:?0*1)$/i,u=/\.mongo\.ondigitalocean\.com$/i,l=/\.cosmos\.azure\.com$/i,h=/docdb(-elastic)?\.amazonaws\.com$/i,d=/\.firestore.goog$/i;function p(e){return"object"==typeof e&&null!==e}function m(e){return e.startsWith("[")?e.substring(1).split("]")[0]:e.split(":")[0]}function f(e){if("string"!=typeof e)return"";try{return m(new o.default(e).hosts[0])}catch(t){return m(e)}}},29348:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OrderedBulkOperation=void 0;const r=n(75080),o=n(17562),i=n(54564);class s extends i.BulkOperationBase{constructor(e,t){super(e,t,!0)}addToOperationsList(e,t){const n=r.calculateObjectSize(t,{checkKeys:!1,ignoreUndefined:!1});if(n>=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+n>=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+n,this.s.currentIndex+=1,this}}t.OrderedBulkOperation=s},30588:(e,t,n)=>{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,n){return e?n.filter((t=>t.address===e.address&&t.type!==i.ServerType.Unknown)):[]}},t.secondaryWritableServerSelector=function(e,n){return!n||!e||e&&e<t.MIN_SECONDARY_WRITE_WIRE_VERSION?f(o.ReadPreference.primary):f(n)},t.readPreferenceServerSelector=f;const r=n(17562),o=n(13700),i=n(89167),s=1e4,a=90;function c(e,t){const n=Object.keys(e),r=Object.keys(t);for(let o=0;o<n.length;++o){const i=n[o];if(-1===r.indexOf(i)||t[i]!==e[i])return!1}return!0}function u(e,t){const n=t.reduce(((e,t)=>Math.min(t.roundTripTime,e)),1/0),r=n+e.localThresholdMS;return t.reduce(((e,t)=>(t.roundTripTime<=r&&t.roundTripTime>=n&&e.push(t),e)),[])}function l(e){return e.type===i.ServerType.RSPrimary}function h(e){return e.type===i.ServerType.RSSecondary}function d(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 r.MongoInvalidArgumentError("Invalid read preference specified");return function(t,n,f=[]){const g=t.commonWireVersion;if(g&&e.minWireVersion&&e.minWireVersion>g)throw new r.MongoCompatibilityError(`Minimum wire version '${e.minWireVersion}' required, but found '${g}'`);if(t.type===i.TopologyType.LoadBalanced)return n.filter(m);if(t.type===i.TopologyType.Unknown)return[];if(t.type===i.TopologyType.Single)return u(t,n.filter(p));if(t.type===i.TopologyType.Sharded){const e=n.filter((e=>!f.includes(e)));return u(t,(e.length>0?e:f).filter(p))}const y=e.mode;if(y===o.ReadPreference.PRIMARY)return n.filter(l);if(y===o.ReadPreference.PRIMARY_PREFERRED){const e=n.filter(l);if(e.length)return e}const E=y===o.ReadPreference.NEAREST?d:h,S=u(t,function(e,t){if(null==e.tags||Array.isArray(e.tags)&&0===e.tags.length)return t;for(let n=0;n<e.tags.length;++n){const r=e.tags[n],o=t.reduce(((e,t)=>(c(r,t.tags)&&e.push(t),e)),[]);if(o.length)return o}return[]}(e,function(e,t,n){if(null==e.maxStalenessSeconds||e.maxStalenessSeconds<0)return n;const o=e.maxStalenessSeconds,c=(t.heartbeatFrequencyMS+s)/1e3;if(o<c)throw new r.MongoInvalidArgumentError(`Option "maxStalenessSeconds" must be at least ${c} seconds`);if(o<a)throw new r.MongoInvalidArgumentError(`Option "maxStalenessSeconds" must be at least ${a} seconds`);if(t.type===i.TopologyType.ReplicaSetWithPrimary){const r=Array.from(t.servers.values()).filter(l)[0];return n.reduce(((n,o)=>((o.lastUpdateTime-o.lastWriteDate-(r.lastUpdateTime-r.lastWriteDate)+t.heartbeatFrequencyMS)/1e3<=(e.maxStalenessSeconds??0)&&n.push(o),n)),[])}if(t.type===i.TopologyType.ReplicaSetNoPrimary){if(0===n.length)return n;const r=n.reduce(((e,t)=>t.lastWriteDate>e.lastWriteDate?t:e));return n.reduce(((n,o)=>((r.lastWriteDate-o.lastWriteDate+t.heartbeatFrequencyMS)/1e3<=(e.maxStalenessSeconds??0)&&n.push(o),n)),[])}return n}(e,t,n.filter(E))));return y===o.ReadPreference.SECONDARY_PREFERRED&&0===S.length?n.filter(l):S}}t.MIN_SECONDARY_WRITE_WIRE_VERSION=13},30770:(e,t,n)=>{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 r.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:(n=e)instanceof Map&&n.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 n,i,s}};const r=n(17562);function o(e=1){const t=`${e}`.toLowerCase();if("object"==typeof(n=e)&&null!=n&&"$meta"in n&&"string"==typeof n.$meta)return e;var n;switch(t){case"ascending":case"asc":case"1":return 1;case"descending":case"desc":case"-1":return-1;default:throw new r.MongoInvalidArgumentError(`Invalid sort direction: ${JSON.stringify(e)}`)}}},31057:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AuthProvider=t.AuthContext=void 0;const r=n(17562);t.AuthContext=class{constructor(e,t,n){this.reauthenticating=!1,this.connection=e,this.credentials=t,this.options=n}},t.AuthProvider=class{async prepare(e,t){return e}async reauth(e){if(e.reauthenticating)throw new r.MongoRuntimeError("Reauthentication already in progress.");try{e.reauthenticating=!0,await this.auth(e)}finally{e.reauthenticating=!1}}}},31480:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ValidateCollectionOperation=void 0;const r=n(75725),o=n(17562),i=n(78130);class s extends i.CommandOperation{constructor(e,t,n){super(e.s.db,n),this.SERVER_COMMAND_RESPONSE_TYPE=r.MongoDBResponse,this.options=n,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,n)=>{function r(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=r,t.configureExplicitResourceManagement=function(){const{MongoClient:e}=n(22220),{ClientSession:t}=n(14019),{AbstractCursor:o}=n(61066),{ChangeStream:i}=n(22345);r(e.prototype),r(t.prototype),r(o.prototype),r(i.prototype)}},32361:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ListIndexesCursor=void 0;const r=n(96357),o=n(22847),i=n(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}),n=await(0,r.executeOperation)(this.parent.client,t,this.timeoutContext);return{server:t.server,session:e,response:n}}}t.ListIndexesCursor=s},32443:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CreateSearchIndexesOperation=void 0;const r=n(75725),o=n(35394);class i extends o.AbstractOperation{constructor(e,t){super(),this.SERVER_COMMAND_RESPONSE_TYPE=r.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,n)=>{var r=n(67787).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.GridFSBucketReadStream=void 0;const o=n(93874),i=n(61066),s=n(17562),a=n(7799);class c extends o.Readable{constructor(e,t,n,r,o){super({emitClose:!0}),this.s={bytesToTrim:0,bytesToSkip:0,bytesRead:0,chunks:e,expected:0,files:t,filter:r,init:!1,expectedEnd:0,options:{start:0,end:0,...o},readPreference:n,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 n;try{n=e.s.timeoutContext?.getRemainingTimeMSOrThrow(`Download timed out after ${e.s.timeoutContext?.timeoutMS}ms`)}catch(t){return void(e.destroyed||e.destroy(t))}t.timeoutMS=n,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`,n=new s.MongoRuntimeError(t);return n.code="ENOENT",e.destroy(n)}if(t.length<=0)return void e.push(null);if(e.destroyed)return void e.destroy();try{e.s.bytesToSkip=function(e,t,n){if(n&&null!=n.start){if(n.start>t.length)throw new s.MongoInvalidArgumentError(`Stream start (${n.start}) must not be more than the length of the file (${t.length})`);if(n.start<0)throw new s.MongoInvalidArgumentError(`Stream start (${n.start}) must not be negative`);if(null!=n.end&&n.end<n.start)throw new s.MongoInvalidArgumentError(`Stream start (${n.start}) must not be greater than stream end (${n.end})`);return e.s.bytesRead=Math.floor(n.start/t.chunkSize)*t.chunkSize,e.s.expected=Math.floor(n.start/t.chunkSize),n.start-e.s.bytesRead}throw new s.MongoInvalidArgumentError("Start option must be defined")}(e,t,e.s.options)}catch(t){return e.destroy(t)}const n={files_id:t._id};if(e.s.options&&null!=e.s.options.start){const r=Math.floor(e.s.options.start/t.chunkSize);r>0&&(n.n={$gte:r})}let r;try{r=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(n,{timeoutMode:null!=e.s.options.timeoutMS?i.CursorTimeoutMode.LIFETIME:void 0,timeoutMS:r}).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,n,r){if(r&&null!=r.end){if(r.end>t.length)throw new s.MongoInvalidArgumentError(`Stream end (${r.end}) must not be more than the length of the file (${t.length})`);if(null==r.start||r.start<0)throw new s.MongoInvalidArgumentError(`Stream end (${r.end}) must not be negative`);const o=null!=r.start?Math.floor(r.start/t.chunkSize):0;return n.limit(Math.ceil(r.end/t.chunkSize)-o),e.s.expectedEnd=Math.ceil(r.end/t.chunkSize),Math.ceil(r.end/t.chunkSize)*t.chunkSize-r.end}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 n=e.s.file.length-e.s.bytesRead,o=e.s.expected++,i=Math.min(e.s.file.chunkSize,n);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=r.isBuffer(t.data)?t.data:t.data.buffer;if(a.byteLength!==i)return n<=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,h=e.s.options.end-e.s.bytesToSkip;l&&null!=e.s.bytesToTrim?u=e.s.file.chunkSize-e.s.bytesToTrim:e.s.options.end&&h<t.data.byteLength&&(u=h),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"},33168:function(e,t,n){var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var o=Object.getOwnPropertyDescriptor(t,n);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,o)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),i=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&r(t,e,n);return o(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.toTypescriptTypeDefinition=t.schemaStats=t.SchemaAnalyzer=t.getSimplifiedSchema=t.getSchemaPaths=t.analyzeDocuments=t.parseSchema=void 0;const s=n(37057),a=n(75996);Object.defineProperty(t,"SchemaAnalyzer",{enumerable:!0,get:function(){return a.SchemaAnalyzer}});const c=n(79059),u=n(59942),l=n(61283),h=i(n(33787));t.schemaStats=h;const d=n(33859);async function p(e,t){return(await(0,a.getCompletedSchemaAnalyzer)(e,t)).getResult()}Object.defineProperty(t,"toTypescriptTypeDefinition",{enumerable:!0,get:function(){return d.toTypescriptTypeDefinition}}),t.analyzeDocuments=async function(e,t){const n=(await(0,a.getCompletedSchemaAnalyzer)(e,t)).getResult();return new s.InternalSchemaBasedAccessor(n,{internalToStandard:l.convertInternalToStandard,internalToMongoDB:u.convertInternalToMongodb,internalToExpanded:c.convertInternalToExpanded})},t.parseSchema=p,t.getSchemaPaths=async function(e){return(await(0,a.getCompletedSchemaAnalyzer)(e)).getSchemaPaths()},t.getSimplifiedSchema=async function(e){return(await(0,a.getCompletedSchemaAnalyzer)(e)).getSimplifiedSchema()},t.default=p},33433:function(e,t,n){!function(e,t){function r(e,t){if(!e)throw new Error(t||"Assertion failed")}function o(e,t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}function i(e,t,n){if(i.isBN(e))return e;this.negative=0,this.words=null,this.length=0,this.red=null,null!==e&&("le"!==t&&"be"!==t||(n=t,t=10),this._init(e||0,t||10,n||"be"))}var s;"object"==typeof e?e.exports=i:t.BN=i,i.BN=i,i.wordSize=26;try{s="undefined"!=typeof window&&void 0!==window.Buffer?window.Buffer:n(67787).Buffer}catch(e){}function a(e,t){var n=e.charCodeAt(t);return n>=65&&n<=70?n-55:n>=97&&n<=102?n-87:n-48&15}function c(e,t,n){var r=a(e,n);return n-1>=t&&(r|=a(e,n-1)<<4),r}function u(e,t,n,r){for(var o=0,i=Math.min(e.length,n),s=t;s<i;s++){var a=e.charCodeAt(s)-48;o*=r,o+=a>=49?a-49+10:a>=17?a-17+10:a}return o}i.isBN=function(e){return e instanceof i||null!==e&&"object"==typeof e&&e.constructor.wordSize===i.wordSize&&Array.isArray(e.words)},i.max=function(e,t){return e.cmp(t)>0?e:t},i.min=function(e,t){return e.cmp(t)<0?e:t},i.prototype._init=function(e,t,n){if("number"==typeof e)return this._initNumber(e,t,n);if("object"==typeof e)return this._initArray(e,t,n);"hex"===t&&(t=16),r(t===(0|t)&&t>=2&&t<=36);var o=0;"-"===(e=e.toString().replace(/\s+/g,""))[0]&&(o++,this.negative=1),o<e.length&&(16===t?this._parseHex(e,o,n):(this._parseBase(e,t,o),"le"===n&&this._initArray(this.toArray(),t,n)))},i.prototype._initNumber=function(e,t,n){e<0&&(this.negative=1,e=-e),e<67108864?(this.words=[67108863&e],this.length=1):e<4503599627370496?(this.words=[67108863&e,e/67108864&67108863],this.length=2):(r(e<9007199254740992),this.words=[67108863&e,e/67108864&67108863,1],this.length=3),"le"===n&&this._initArray(this.toArray(),t,n)},i.prototype._initArray=function(e,t,n){if(r("number"==typeof e.length),e.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(e.length/3),this.words=new Array(this.length);for(var o=0;o<this.length;o++)this.words[o]=0;var i,s,a=0;if("be"===n)for(o=e.length-1,i=0;o>=0;o-=3)s=e[o]|e[o-1]<<8|e[o-2]<<16,this.words[i]|=s<<a&67108863,this.words[i+1]=s>>>26-a&67108863,(a+=24)>=26&&(a-=26,i++);else if("le"===n)for(o=0,i=0;o<e.length;o+=3)s=e[o]|e[o+1]<<8|e[o+2]<<16,this.words[i]|=s<<a&67108863,this.words[i+1]=s>>>26-a&67108863,(a+=24)>=26&&(a-=26,i++);return this.strip()},i.prototype._parseHex=function(e,t,n){this.length=Math.ceil((e.length-t)/6),this.words=new Array(this.length);for(var r=0;r<this.length;r++)this.words[r]=0;var o,i=0,s=0;if("be"===n)for(r=e.length-1;r>=t;r-=2)o=c(e,t,r)<<i,this.words[s]|=67108863&o,i>=18?(i-=18,s+=1,this.words[s]|=o>>>26):i+=8;else for(r=(e.length-t)%2==0?t+1:t;r<e.length;r+=2)o=c(e,t,r)<<i,this.words[s]|=67108863&o,i>=18?(i-=18,s+=1,this.words[s]|=o>>>26):i+=8;this.strip()},i.prototype._parseBase=function(e,t,n){this.words=[0],this.length=1;for(var r=0,o=1;o<=67108863;o*=t)r++;r--,o=o/t|0;for(var i=e.length-n,s=i%r,a=Math.min(i,i-s)+n,c=0,l=n;l<a;l+=r)c=u(e,l,l+r,t),this.imuln(o),this.words[0]+c<67108864?this.words[0]+=c:this._iaddn(c);if(0!==s){var h=1;for(c=u(e,l,e.length,t),l=0;l<s;l++)h*=t;this.imuln(h),this.words[0]+c<67108864?this.words[0]+=c:this._iaddn(c)}this.strip()},i.prototype.copy=function(e){e.words=new Array(this.length);for(var t=0;t<this.length;t++)e.words[t]=this.words[t];e.length=this.length,e.negative=this.negative,e.red=this.red},i.prototype.clone=function(){var e=new i(null);return this.copy(e),e},i.prototype._expand=function(e){for(;this.length<e;)this.words[this.length++]=0;return this},i.prototype.strip=function(){for(;this.length>1&&0===this.words[this.length-1];)this.length--;return this._normSign()},i.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},i.prototype.inspect=function(){return(this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"};var l=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],h=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],d=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function p(e,t,n){n.negative=t.negative^e.negative;var r=e.length+t.length|0;n.length=r,r=r-1|0;var o=0|e.words[0],i=0|t.words[0],s=o*i,a=67108863&s,c=s/67108864|0;n.words[0]=a;for(var u=1;u<r;u++){for(var l=c>>>26,h=67108863&c,d=Math.min(u,t.length-1),p=Math.max(0,u-e.length+1);p<=d;p++){var m=u-p|0;l+=(s=(o=0|e.words[m])*(i=0|t.words[p])+h)/67108864|0,h=67108863&s}n.words[u]=0|h,c=0|l}return 0!==c?n.words[u]=0|c:n.length--,n.strip()}i.prototype.toString=function(e,t){var n;if(t=0|t||1,16===(e=e||10)||"hex"===e){n="";for(var o=0,i=0,s=0;s<this.length;s++){var a=this.words[s],c=(16777215&(a<<o|i)).toString(16);n=0!=(i=a>>>24-o&16777215)||s!==this.length-1?l[6-c.length]+c+n:c+n,(o+=2)>=26&&(o-=26,s--)}for(0!==i&&(n=i.toString(16)+n);n.length%t!=0;)n="0"+n;return 0!==this.negative&&(n="-"+n),n}if(e===(0|e)&&e>=2&&e<=36){var u=h[e],p=d[e];n="";var m=this.clone();for(m.negative=0;!m.isZero();){var f=m.modn(p).toString(e);n=(m=m.idivn(p)).isZero()?f+n:l[u-f.length]+f+n}for(this.isZero()&&(n="0"+n);n.length%t!=0;)n="0"+n;return 0!==this.negative&&(n="-"+n),n}r(!1,"Base should be between 2 and 36")},i.prototype.toNumber=function(){var e=this.words[0];return 2===this.length?e+=67108864*this.words[1]:3===this.length&&1===this.words[2]?e+=4503599627370496+67108864*this.words[1]:this.length>2&&r(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-e:e},i.prototype.toJSON=function(){return this.toString(16)},i.prototype.toBuffer=function(e,t){return r(void 0!==s),this.toArrayLike(s,e,t)},i.prototype.toArray=function(e,t){return this.toArrayLike(Array,e,t)},i.prototype.toArrayLike=function(e,t,n){var o=this.byteLength(),i=n||Math.max(1,o);r(o<=i,"byte array longer than desired length"),r(i>0,"Requested array length <= 0"),this.strip();var s,a,c="le"===t,u=new e(i),l=this.clone();if(c){for(a=0;!l.isZero();a++)s=l.andln(255),l.iushrn(8),u[a]=s;for(;a<i;a++)u[a]=0}else{for(a=0;a<i-o;a++)u[a]=0;for(a=0;!l.isZero();a++)s=l.andln(255),l.iushrn(8),u[i-a-1]=s}return u},Math.clz32?i.prototype._countBits=function(e){return 32-Math.clz32(e)}:i.prototype._countBits=function(e){var t=e,n=0;return t>=4096&&(n+=13,t>>>=13),t>=64&&(n+=7,t>>>=7),t>=8&&(n+=4,t>>>=4),t>=2&&(n+=2,t>>>=2),n+t},i.prototype._zeroBits=function(e){if(0===e)return 26;var t=e,n=0;return 8191&t||(n+=13,t>>>=13),127&t||(n+=7,t>>>=7),15&t||(n+=4,t>>>=4),3&t||(n+=2,t>>>=2),1&t||n++,n},i.prototype.bitLength=function(){var e=this.words[this.length-1],t=this._countBits(e);return 26*(this.length-1)+t},i.prototype.zeroBits=function(){if(this.isZero())return 0;for(var e=0,t=0;t<this.length;t++){var n=this._zeroBits(this.words[t]);if(e+=n,26!==n)break}return e},i.prototype.byteLength=function(){return Math.ceil(this.bitLength()/8)},i.prototype.toTwos=function(e){return 0!==this.negative?this.abs().inotn(e).iaddn(1):this.clone()},i.prototype.fromTwos=function(e){return this.testn(e-1)?this.notn(e).iaddn(1).ineg():this.clone()},i.prototype.isNeg=function(){return 0!==this.negative},i.prototype.neg=function(){return this.clone().ineg()},i.prototype.ineg=function(){return this.isZero()||(this.negative^=1),this},i.prototype.iuor=function(e){for(;this.length<e.length;)this.words[this.length++]=0;for(var t=0;t<e.length;t++)this.words[t]=this.words[t]|e.words[t];return this.strip()},i.prototype.ior=function(e){return r(!(this.negative|e.negative)),this.iuor(e)},i.prototype.or=function(e){return this.length>e.length?this.clone().ior(e):e.clone().ior(this)},i.prototype.uor=function(e){return this.length>e.length?this.clone().iuor(e):e.clone().iuor(this)},i.prototype.iuand=function(e){var t;t=this.length>e.length?e:this;for(var n=0;n<t.length;n++)this.words[n]=this.words[n]&e.words[n];return this.length=t.length,this.strip()},i.prototype.iand=function(e){return r(!(this.negative|e.negative)),this.iuand(e)},i.prototype.and=function(e){return this.length>e.length?this.clone().iand(e):e.clone().iand(this)},i.prototype.uand=function(e){return this.length>e.length?this.clone().iuand(e):e.clone().iuand(this)},i.prototype.iuxor=function(e){var t,n;this.length>e.length?(t=this,n=e):(t=e,n=this);for(var r=0;r<n.length;r++)this.words[r]=t.words[r]^n.words[r];if(this!==t)for(;r<t.length;r++)this.words[r]=t.words[r];return this.length=t.length,this.strip()},i.prototype.ixor=function(e){return r(!(this.negative|e.negative)),this.iuxor(e)},i.prototype.xor=function(e){return this.length>e.length?this.clone().ixor(e):e.clone().ixor(this)},i.prototype.uxor=function(e){return this.length>e.length?this.clone().iuxor(e):e.clone().iuxor(this)},i.prototype.inotn=function(e){r("number"==typeof e&&e>=0);var t=0|Math.ceil(e/26),n=e%26;this._expand(t),n>0&&t--;for(var o=0;o<t;o++)this.words[o]=67108863&~this.words[o];return n>0&&(this.words[o]=~this.words[o]&67108863>>26-n),this.strip()},i.prototype.notn=function(e){return this.clone().inotn(e)},i.prototype.setn=function(e,t){r("number"==typeof e&&e>=0);var n=e/26|0,o=e%26;return this._expand(n+1),this.words[n]=t?this.words[n]|1<<o:this.words[n]&~(1<<o),this.strip()},i.prototype.iadd=function(e){var t,n,r;if(0!==this.negative&&0===e.negative)return this.negative=0,t=this.isub(e),this.negative^=1,this._normSign();if(0===this.negative&&0!==e.negative)return e.negative=0,t=this.isub(e),e.negative=1,t._normSign();this.length>e.length?(n=this,r=e):(n=e,r=this);for(var o=0,i=0;i<r.length;i++)t=(0|n.words[i])+(0|r.words[i])+o,this.words[i]=67108863&t,o=t>>>26;for(;0!==o&&i<n.length;i++)t=(0|n.words[i])+o,this.words[i]=67108863&t,o=t>>>26;if(this.length=n.length,0!==o)this.words[this.length]=o,this.length++;else if(n!==this)for(;i<n.length;i++)this.words[i]=n.words[i];return this},i.prototype.add=function(e){var t;return 0!==e.negative&&0===this.negative?(e.negative=0,t=this.sub(e),e.negative^=1,t):0===e.negative&&0!==this.negative?(this.negative=0,t=e.sub(this),this.negative=1,t):this.length>e.length?this.clone().iadd(e):e.clone().iadd(this)},i.prototype.isub=function(e){if(0!==e.negative){e.negative=0;var t=this.iadd(e);return e.negative=1,t._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(e),this.negative=1,this._normSign();var n,r,o=this.cmp(e);if(0===o)return this.negative=0,this.length=1,this.words[0]=0,this;o>0?(n=this,r=e):(n=e,r=this);for(var i=0,s=0;s<r.length;s++)i=(t=(0|n.words[s])-(0|r.words[s])+i)>>26,this.words[s]=67108863&t;for(;0!==i&&s<n.length;s++)i=(t=(0|n.words[s])+i)>>26,this.words[s]=67108863&t;if(0===i&&s<n.length&&n!==this)for(;s<n.length;s++)this.words[s]=n.words[s];return this.length=Math.max(this.length,s),n!==this&&(this.negative=1),this.strip()},i.prototype.sub=function(e){return this.clone().isub(e)};var m=function(e,t,n){var r,o,i,s=e.words,a=t.words,c=n.words,u=0,l=0|s[0],h=8191&l,d=l>>>13,p=0|s[1],m=8191&p,f=p>>>13,g=0|s[2],y=8191&g,E=g>>>13,S=0|s[3],O=8191&S,C=S>>>13,v=0|s[4],b=8191&v,w=v>>>13,M=0|s[5],T=8191&M,_=M>>>13,A=0|s[6],R=8191&A,N=A>>>13,I=0|s[7],x=8191&I,P=I>>>13,k=0|s[8],D=8191&k,L=k>>>13,B=0|s[9],j=8191&B,F=B>>>13,U=0|a[0],z=8191&U,V=U>>>13,$=0|a[1],W=8191&$,G=$>>>13,H=0|a[2],q=8191&H,K=H>>>13,Y=0|a[3],Q=8191&Y,X=Y>>>13,J=0|a[4],Z=8191&J,ee=J>>>13,te=0|a[5],ne=8191&te,re=te>>>13,oe=0|a[6],ie=8191&oe,se=oe>>>13,ae=0|a[7],ce=8191&ae,ue=ae>>>13,le=0|a[8],he=8191&le,de=le>>>13,pe=0|a[9],me=8191&pe,fe=pe>>>13;n.negative=e.negative^t.negative,n.length=19;var ge=(u+(r=Math.imul(h,z))|0)+((8191&(o=(o=Math.imul(h,V))+Math.imul(d,z)|0))<<13)|0;u=((i=Math.imul(d,V))+(o>>>13)|0)+(ge>>>26)|0,ge&=67108863,r=Math.imul(m,z),o=(o=Math.imul(m,V))+Math.imul(f,z)|0,i=Math.imul(f,V);var ye=(u+(r=r+Math.imul(h,W)|0)|0)+((8191&(o=(o=o+Math.imul(h,G)|0)+Math.imul(d,W)|0))<<13)|0;u=((i=i+Math.imul(d,G)|0)+(o>>>13)|0)+(ye>>>26)|0,ye&=67108863,r=Math.imul(y,z),o=(o=Math.imul(y,V))+Math.imul(E,z)|0,i=Math.imul(E,V),r=r+Math.imul(m,W)|0,o=(o=o+Math.imul(m,G)|0)+Math.imul(f,W)|0,i=i+Math.imul(f,G)|0;var Ee=(u+(r=r+Math.imul(h,q)|0)|0)+((8191&(o=(o=o+Math.imul(h,K)|0)+Math.imul(d,q)|0))<<13)|0;u=((i=i+Math.imul(d,K)|0)+(o>>>13)|0)+(Ee>>>26)|0,Ee&=67108863,r=Math.imul(O,z),o=(o=Math.imul(O,V))+Math.imul(C,z)|0,i=Math.imul(C,V),r=r+Math.imul(y,W)|0,o=(o=o+Math.imul(y,G)|0)+Math.imul(E,W)|0,i=i+Math.imul(E,G)|0,r=r+Math.imul(m,q)|0,o=(o=o+Math.imul(m,K)|0)+Math.imul(f,q)|0,i=i+Math.imul(f,K)|0;var Se=(u+(r=r+Math.imul(h,Q)|0)|0)+((8191&(o=(o=o+Math.imul(h,X)|0)+Math.imul(d,Q)|0))<<13)|0;u=((i=i+Math.imul(d,X)|0)+(o>>>13)|0)+(Se>>>26)|0,Se&=67108863,r=Math.imul(b,z),o=(o=Math.imul(b,V))+Math.imul(w,z)|0,i=Math.imul(w,V),r=r+Math.imul(O,W)|0,o=(o=o+Math.imul(O,G)|0)+Math.imul(C,W)|0,i=i+Math.imul(C,G)|0,r=r+Math.imul(y,q)|0,o=(o=o+Math.imul(y,K)|0)+Math.imul(E,q)|0,i=i+Math.imul(E,K)|0,r=r+Math.imul(m,Q)|0,o=(o=o+Math.imul(m,X)|0)+Math.imul(f,Q)|0,i=i+Math.imul(f,X)|0;var Oe=(u+(r=r+Math.imul(h,Z)|0)|0)+((8191&(o=(o=o+Math.imul(h,ee)|0)+Math.imul(d,Z)|0))<<13)|0;u=((i=i+Math.imul(d,ee)|0)+(o>>>13)|0)+(Oe>>>26)|0,Oe&=67108863,r=Math.imul(T,z),o=(o=Math.imul(T,V))+Math.imul(_,z)|0,i=Math.imul(_,V),r=r+Math.imul(b,W)|0,o=(o=o+Math.imul(b,G)|0)+Math.imul(w,W)|0,i=i+Math.imul(w,G)|0,r=r+Math.imul(O,q)|0,o=(o=o+Math.imul(O,K)|0)+Math.imul(C,q)|0,i=i+Math.imul(C,K)|0,r=r+Math.imul(y,Q)|0,o=(o=o+Math.imul(y,X)|0)+Math.imul(E,Q)|0,i=i+Math.imul(E,X)|0,r=r+Math.imul(m,Z)|0,o=(o=o+Math.imul(m,ee)|0)+Math.imul(f,Z)|0,i=i+Math.imul(f,ee)|0;var Ce=(u+(r=r+Math.imul(h,ne)|0)|0)+((8191&(o=(o=o+Math.imul(h,re)|0)+Math.imul(d,ne)|0))<<13)|0;u=((i=i+Math.imul(d,re)|0)+(o>>>13)|0)+(Ce>>>26)|0,Ce&=67108863,r=Math.imul(R,z),o=(o=Math.imul(R,V))+Math.imul(N,z)|0,i=Math.imul(N,V),r=r+Math.imul(T,W)|0,o=(o=o+Math.imul(T,G)|0)+Math.imul(_,W)|0,i=i+Math.imul(_,G)|0,r=r+Math.imul(b,q)|0,o=(o=o+Math.imul(b,K)|0)+Math.imul(w,q)|0,i=i+Math.imul(w,K)|0,r=r+Math.imul(O,Q)|0,o=(o=o+Math.imul(O,X)|0)+Math.imul(C,Q)|0,i=i+Math.imul(C,X)|0,r=r+Math.imul(y,Z)|0,o=(o=o+Math.imul(y,ee)|0)+Math.imul(E,Z)|0,i=i+Math.imul(E,ee)|0,r=r+Math.imul(m,ne)|0,o=(o=o+Math.imul(m,re)|0)+Math.imul(f,ne)|0,i=i+Math.imul(f,re)|0;var ve=(u+(r=r+Math.imul(h,ie)|0)|0)+((8191&(o=(o=o+Math.imul(h,se)|0)+Math.imul(d,ie)|0))<<13)|0;u=((i=i+Math.imul(d,se)|0)+(o>>>13)|0)+(ve>>>26)|0,ve&=67108863,r=Math.imul(x,z),o=(o=Math.imul(x,V))+Math.imul(P,z)|0,i=Math.imul(P,V),r=r+Math.imul(R,W)|0,o=(o=o+Math.imul(R,G)|0)+Math.imul(N,W)|0,i=i+Math.imul(N,G)|0,r=r+Math.imul(T,q)|0,o=(o=o+Math.imul(T,K)|0)+Math.imul(_,q)|0,i=i+Math.imul(_,K)|0,r=r+Math.imul(b,Q)|0,o=(o=o+Math.imul(b,X)|0)+Math.imul(w,Q)|0,i=i+Math.imul(w,X)|0,r=r+Math.imul(O,Z)|0,o=(o=o+Math.imul(O,ee)|0)+Math.imul(C,Z)|0,i=i+Math.imul(C,ee)|0,r=r+Math.imul(y,ne)|0,o=(o=o+Math.imul(y,re)|0)+Math.imul(E,ne)|0,i=i+Math.imul(E,re)|0,r=r+Math.imul(m,ie)|0,o=(o=o+Math.imul(m,se)|0)+Math.imul(f,ie)|0,i=i+Math.imul(f,se)|0;var be=(u+(r=r+Math.imul(h,ce)|0)|0)+((8191&(o=(o=o+Math.imul(h,ue)|0)+Math.imul(d,ce)|0))<<13)|0;u=((i=i+Math.imul(d,ue)|0)+(o>>>13)|0)+(be>>>26)|0,be&=67108863,r=Math.imul(D,z),o=(o=Math.imul(D,V))+Math.imul(L,z)|0,i=Math.imul(L,V),r=r+Math.imul(x,W)|0,o=(o=o+Math.imul(x,G)|0)+Math.imul(P,W)|0,i=i+Math.imul(P,G)|0,r=r+Math.imul(R,q)|0,o=(o=o+Math.imul(R,K)|0)+Math.imul(N,q)|0,i=i+Math.imul(N,K)|0,r=r+Math.imul(T,Q)|0,o=(o=o+Math.imul(T,X)|0)+Math.imul(_,Q)|0,i=i+Math.imul(_,X)|0,r=r+Math.imul(b,Z)|0,o=(o=o+Math.imul(b,ee)|0)+Math.imul(w,Z)|0,i=i+Math.imul(w,ee)|0,r=r+Math.imul(O,ne)|0,o=(o=o+Math.imul(O,re)|0)+Math.imul(C,ne)|0,i=i+Math.imul(C,re)|0,r=r+Math.imul(y,ie)|0,o=(o=o+Math.imul(y,se)|0)+Math.imul(E,ie)|0,i=i+Math.imul(E,se)|0,r=r+Math.imul(m,ce)|0,o=(o=o+Math.imul(m,ue)|0)+Math.imul(f,ce)|0,i=i+Math.imul(f,ue)|0;var we=(u+(r=r+Math.imul(h,he)|0)|0)+((8191&(o=(o=o+Math.imul(h,de)|0)+Math.imul(d,he)|0))<<13)|0;u=((i=i+Math.imul(d,de)|0)+(o>>>13)|0)+(we>>>26)|0,we&=67108863,r=Math.imul(j,z),o=(o=Math.imul(j,V))+Math.imul(F,z)|0,i=Math.imul(F,V),r=r+Math.imul(D,W)|0,o=(o=o+Math.imul(D,G)|0)+Math.imul(L,W)|0,i=i+Math.imul(L,G)|0,r=r+Math.imul(x,q)|0,o=(o=o+Math.imul(x,K)|0)+Math.imul(P,q)|0,i=i+Math.imul(P,K)|0,r=r+Math.imul(R,Q)|0,o=(o=o+Math.imul(R,X)|0)+Math.imul(N,Q)|0,i=i+Math.imul(N,X)|0,r=r+Math.imul(T,Z)|0,o=(o=o+Math.imul(T,ee)|0)+Math.imul(_,Z)|0,i=i+Math.imul(_,ee)|0,r=r+Math.imul(b,ne)|0,o=(o=o+Math.imul(b,re)|0)+Math.imul(w,ne)|0,i=i+Math.imul(w,re)|0,r=r+Math.imul(O,ie)|0,o=(o=o+Math.imul(O,se)|0)+Math.imul(C,ie)|0,i=i+Math.imul(C,se)|0,r=r+Math.imul(y,ce)|0,o=(o=o+Math.imul(y,ue)|0)+Math.imul(E,ce)|0,i=i+Math.imul(E,ue)|0,r=r+Math.imul(m,he)|0,o=(o=o+Math.imul(m,de)|0)+Math.imul(f,he)|0,i=i+Math.imul(f,de)|0;var Me=(u+(r=r+Math.imul(h,me)|0)|0)+((8191&(o=(o=o+Math.imul(h,fe)|0)+Math.imul(d,me)|0))<<13)|0;u=((i=i+Math.imul(d,fe)|0)+(o>>>13)|0)+(Me>>>26)|0,Me&=67108863,r=Math.imul(j,W),o=(o=Math.imul(j,G))+Math.imul(F,W)|0,i=Math.imul(F,G),r=r+Math.imul(D,q)|0,o=(o=o+Math.imul(D,K)|0)+Math.imul(L,q)|0,i=i+Math.imul(L,K)|0,r=r+Math.imul(x,Q)|0,o=(o=o+Math.imul(x,X)|0)+Math.imul(P,Q)|0,i=i+Math.imul(P,X)|0,r=r+Math.imul(R,Z)|0,o=(o=o+Math.imul(R,ee)|0)+Math.imul(N,Z)|0,i=i+Math.imul(N,ee)|0,r=r+Math.imul(T,ne)|0,o=(o=o+Math.imul(T,re)|0)+Math.imul(_,ne)|0,i=i+Math.imul(_,re)|0,r=r+Math.imul(b,ie)|0,o=(o=o+Math.imul(b,se)|0)+Math.imul(w,ie)|0,i=i+Math.imul(w,se)|0,r=r+Math.imul(O,ce)|0,o=(o=o+Math.imul(O,ue)|0)+Math.imul(C,ce)|0,i=i+Math.imul(C,ue)|0,r=r+Math.imul(y,he)|0,o=(o=o+Math.imul(y,de)|0)+Math.imul(E,he)|0,i=i+Math.imul(E,de)|0;var Te=(u+(r=r+Math.imul(m,me)|0)|0)+((8191&(o=(o=o+Math.imul(m,fe)|0)+Math.imul(f,me)|0))<<13)|0;u=((i=i+Math.imul(f,fe)|0)+(o>>>13)|0)+(Te>>>26)|0,Te&=67108863,r=Math.imul(j,q),o=(o=Math.imul(j,K))+Math.imul(F,q)|0,i=Math.imul(F,K),r=r+Math.imul(D,Q)|0,o=(o=o+Math.imul(D,X)|0)+Math.imul(L,Q)|0,i=i+Math.imul(L,X)|0,r=r+Math.imul(x,Z)|0,o=(o=o+Math.imul(x,ee)|0)+Math.imul(P,Z)|0,i=i+Math.imul(P,ee)|0,r=r+Math.imul(R,ne)|0,o=(o=o+Math.imul(R,re)|0)+Math.imul(N,ne)|0,i=i+Math.imul(N,re)|0,r=r+Math.imul(T,ie)|0,o=(o=o+Math.imul(T,se)|0)+Math.imul(_,ie)|0,i=i+Math.imul(_,se)|0,r=r+Math.imul(b,ce)|0,o=(o=o+Math.imul(b,ue)|0)+Math.imul(w,ce)|0,i=i+Math.imul(w,ue)|0,r=r+Math.imul(O,he)|0,o=(o=o+Math.imul(O,de)|0)+Math.imul(C,he)|0,i=i+Math.imul(C,de)|0;var _e=(u+(r=r+Math.imul(y,me)|0)|0)+((8191&(o=(o=o+Math.imul(y,fe)|0)+Math.imul(E,me)|0))<<13)|0;u=((i=i+Math.imul(E,fe)|0)+(o>>>13)|0)+(_e>>>26)|0,_e&=67108863,r=Math.imul(j,Q),o=(o=Math.imul(j,X))+Math.imul(F,Q)|0,i=Math.imul(F,X),r=r+Math.imul(D,Z)|0,o=(o=o+Math.imul(D,ee)|0)+Math.imul(L,Z)|0,i=i+Math.imul(L,ee)|0,r=r+Math.imul(x,ne)|0,o=(o=o+Math.imul(x,re)|0)+Math.imul(P,ne)|0,i=i+Math.imul(P,re)|0,r=r+Math.imul(R,ie)|0,o=(o=o+Math.imul(R,se)|0)+Math.imul(N,ie)|0,i=i+Math.imul(N,se)|0,r=r+Math.imul(T,ce)|0,o=(o=o+Math.imul(T,ue)|0)+Math.imul(_,ce)|0,i=i+Math.imul(_,ue)|0,r=r+Math.imul(b,he)|0,o=(o=o+Math.imul(b,de)|0)+Math.imul(w,he)|0,i=i+Math.imul(w,de)|0;var Ae=(u+(r=r+Math.imul(O,me)|0)|0)+((8191&(o=(o=o+Math.imul(O,fe)|0)+Math.imul(C,me)|0))<<13)|0;u=((i=i+Math.imul(C,fe)|0)+(o>>>13)|0)+(Ae>>>26)|0,Ae&=67108863,r=Math.imul(j,Z),o=(o=Math.imul(j,ee))+Math.imul(F,Z)|0,i=Math.imul(F,ee),r=r+Math.imul(D,ne)|0,o=(o=o+Math.imul(D,re)|0)+Math.imul(L,ne)|0,i=i+Math.imul(L,re)|0,r=r+Math.imul(x,ie)|0,o=(o=o+Math.imul(x,se)|0)+Math.imul(P,ie)|0,i=i+Math.imul(P,se)|0,r=r+Math.imul(R,ce)|0,o=(o=o+Math.imul(R,ue)|0)+Math.imul(N,ce)|0,i=i+Math.imul(N,ue)|0,r=r+Math.imul(T,he)|0,o=(o=o+Math.imul(T,de)|0)+Math.imul(_,he)|0,i=i+Math.imul(_,de)|0;var Re=(u+(r=r+Math.imul(b,me)|0)|0)+((8191&(o=(o=o+Math.imul(b,fe)|0)+Math.imul(w,me)|0))<<13)|0;u=((i=i+Math.imul(w,fe)|0)+(o>>>13)|0)+(Re>>>26)|0,Re&=67108863,r=Math.imul(j,ne),o=(o=Math.imul(j,re))+Math.imul(F,ne)|0,i=Math.imul(F,re),r=r+Math.imul(D,ie)|0,o=(o=o+Math.imul(D,se)|0)+Math.imul(L,ie)|0,i=i+Math.imul(L,se)|0,r=r+Math.imul(x,ce)|0,o=(o=o+Math.imul(x,ue)|0)+Math.imul(P,ce)|0,i=i+Math.imul(P,ue)|0,r=r+Math.imul(R,he)|0,o=(o=o+Math.imul(R,de)|0)+Math.imul(N,he)|0,i=i+Math.imul(N,de)|0;var Ne=(u+(r=r+Math.imul(T,me)|0)|0)+((8191&(o=(o=o+Math.imul(T,fe)|0)+Math.imul(_,me)|0))<<13)|0;u=((i=i+Math.imul(_,fe)|0)+(o>>>13)|0)+(Ne>>>26)|0,Ne&=67108863,r=Math.imul(j,ie),o=(o=Math.imul(j,se))+Math.imul(F,ie)|0,i=Math.imul(F,se),r=r+Math.imul(D,ce)|0,o=(o=o+Math.imul(D,ue)|0)+Math.imul(L,ce)|0,i=i+Math.imul(L,ue)|0,r=r+Math.imul(x,he)|0,o=(o=o+Math.imul(x,de)|0)+Math.imul(P,he)|0,i=i+Math.imul(P,de)|0;var Ie=(u+(r=r+Math.imul(R,me)|0)|0)+((8191&(o=(o=o+Math.imul(R,fe)|0)+Math.imul(N,me)|0))<<13)|0;u=((i=i+Math.imul(N,fe)|0)+(o>>>13)|0)+(Ie>>>26)|0,Ie&=67108863,r=Math.imul(j,ce),o=(o=Math.imul(j,ue))+Math.imul(F,ce)|0,i=Math.imul(F,ue),r=r+Math.imul(D,he)|0,o=(o=o+Math.imul(D,de)|0)+Math.imul(L,he)|0,i=i+Math.imul(L,de)|0;var xe=(u+(r=r+Math.imul(x,me)|0)|0)+((8191&(o=(o=o+Math.imul(x,fe)|0)+Math.imul(P,me)|0))<<13)|0;u=((i=i+Math.imul(P,fe)|0)+(o>>>13)|0)+(xe>>>26)|0,xe&=67108863,r=Math.imul(j,he),o=(o=Math.imul(j,de))+Math.imul(F,he)|0,i=Math.imul(F,de);var Pe=(u+(r=r+Math.imul(D,me)|0)|0)+((8191&(o=(o=o+Math.imul(D,fe)|0)+Math.imul(L,me)|0))<<13)|0;u=((i=i+Math.imul(L,fe)|0)+(o>>>13)|0)+(Pe>>>26)|0,Pe&=67108863;var ke=(u+(r=Math.imul(j,me))|0)+((8191&(o=(o=Math.imul(j,fe))+Math.imul(F,me)|0))<<13)|0;return u=((i=Math.imul(F,fe))+(o>>>13)|0)+(ke>>>26)|0,ke&=67108863,c[0]=ge,c[1]=ye,c[2]=Ee,c[3]=Se,c[4]=Oe,c[5]=Ce,c[6]=ve,c[7]=be,c[8]=we,c[9]=Me,c[10]=Te,c[11]=_e,c[12]=Ae,c[13]=Re,c[14]=Ne,c[15]=Ie,c[16]=xe,c[17]=Pe,c[18]=ke,0!==u&&(c[19]=u,n.length++),n};function f(e,t,n){return(new g).mulp(e,t,n)}function g(e,t){this.x=e,this.y=t}Math.imul||(m=p),i.prototype.mulTo=function(e,t){var n,r=this.length+e.length;return n=10===this.length&&10===e.length?m(this,e,t):r<63?p(this,e,t):r<1024?function(e,t,n){n.negative=t.negative^e.negative,n.length=e.length+t.length;for(var r=0,o=0,i=0;i<n.length-1;i++){var s=o;o=0;for(var a=67108863&r,c=Math.min(i,t.length-1),u=Math.max(0,i-e.length+1);u<=c;u++){var l=i-u,h=(0|e.words[l])*(0|t.words[u]),d=67108863&h;a=67108863&(d=d+a|0),o+=(s=(s=s+(h/67108864|0)|0)+(d>>>26)|0)>>>26,s&=67108863}n.words[i]=a,r=s,s=o}return 0!==r?n.words[i]=r:n.length--,n.strip()}(this,e,t):f(this,e,t),n},g.prototype.makeRBT=function(e){for(var t=new Array(e),n=i.prototype._countBits(e)-1,r=0;r<e;r++)t[r]=this.revBin(r,n,e);return t},g.prototype.revBin=function(e,t,n){if(0===e||e===n-1)return e;for(var r=0,o=0;o<t;o++)r|=(1&e)<<t-o-1,e>>=1;return r},g.prototype.permute=function(e,t,n,r,o,i){for(var s=0;s<i;s++)r[s]=t[e[s]],o[s]=n[e[s]]},g.prototype.transform=function(e,t,n,r,o,i){this.permute(i,e,t,n,r,o);for(var s=1;s<o;s<<=1)for(var a=s<<1,c=Math.cos(2*Math.PI/a),u=Math.sin(2*Math.PI/a),l=0;l<o;l+=a)for(var h=c,d=u,p=0;p<s;p++){var m=n[l+p],f=r[l+p],g=n[l+p+s],y=r[l+p+s],E=h*g-d*y;y=h*y+d*g,g=E,n[l+p]=m+g,r[l+p]=f+y,n[l+p+s]=m-g,r[l+p+s]=f-y,p!==a&&(E=c*h-u*d,d=c*d+u*h,h=E)}},g.prototype.guessLen13b=function(e,t){var n=1|Math.max(t,e),r=1&n,o=0;for(n=n/2|0;n;n>>>=1)o++;return 1<<o+1+r},g.prototype.conjugate=function(e,t,n){if(!(n<=1))for(var r=0;r<n/2;r++){var o=e[r];e[r]=e[n-r-1],e[n-r-1]=o,o=t[r],t[r]=-t[n-r-1],t[n-r-1]=-o}},g.prototype.normalize13b=function(e,t){for(var n=0,r=0;r<t/2;r++){var o=8192*Math.round(e[2*r+1]/t)+Math.round(e[2*r]/t)+n;e[r]=67108863&o,n=o<67108864?0:o/67108864|0}return e},g.prototype.convert13b=function(e,t,n,o){for(var i=0,s=0;s<t;s++)i+=0|e[s],n[2*s]=8191&i,i>>>=13,n[2*s+1]=8191&i,i>>>=13;for(s=2*t;s<o;++s)n[s]=0;r(0===i),r(!(-8192&i))},g.prototype.stub=function(e){for(var t=new Array(e),n=0;n<e;n++)t[n]=0;return t},g.prototype.mulp=function(e,t,n){var r=2*this.guessLen13b(e.length,t.length),o=this.makeRBT(r),i=this.stub(r),s=new Array(r),a=new Array(r),c=new Array(r),u=new Array(r),l=new Array(r),h=new Array(r),d=n.words;d.length=r,this.convert13b(e.words,e.length,s,r),this.convert13b(t.words,t.length,u,r),this.transform(s,i,a,c,r,o),this.transform(u,i,l,h,r,o);for(var p=0;p<r;p++){var m=a[p]*l[p]-c[p]*h[p];c[p]=a[p]*h[p]+c[p]*l[p],a[p]=m}return this.conjugate(a,c,r),this.transform(a,c,d,i,r,o),this.conjugate(d,i,r),this.normalize13b(d,r),n.negative=e.negative^t.negative,n.length=e.length+t.length,n.strip()},i.prototype.mul=function(e){var t=new i(null);return t.words=new Array(this.length+e.length),this.mulTo(e,t)},i.prototype.mulf=function(e){var t=new i(null);return t.words=new Array(this.length+e.length),f(this,e,t)},i.prototype.imul=function(e){return this.clone().mulTo(e,this)},i.prototype.imuln=function(e){r("number"==typeof e),r(e<67108864);for(var t=0,n=0;n<this.length;n++){var o=(0|this.words[n])*e,i=(67108863&o)+(67108863&t);t>>=26,t+=o/67108864|0,t+=i>>>26,this.words[n]=67108863&i}return 0!==t&&(this.words[n]=t,this.length++),this},i.prototype.muln=function(e){return this.clone().imuln(e)},i.prototype.sqr=function(){return this.mul(this)},i.prototype.isqr=function(){return this.imul(this.clone())},i.prototype.pow=function(e){var t=function(e){for(var t=new Array(e.bitLength()),n=0;n<t.length;n++){var r=n/26|0,o=n%26;t[n]=(e.words[r]&1<<o)>>>o}return t}(e);if(0===t.length)return new i(1);for(var n=this,r=0;r<t.length&&0===t[r];r++,n=n.sqr());if(++r<t.length)for(var o=n.sqr();r<t.length;r++,o=o.sqr())0!==t[r]&&(n=n.mul(o));return n},i.prototype.iushln=function(e){r("number"==typeof e&&e>=0);var t,n=e%26,o=(e-n)/26,i=67108863>>>26-n<<26-n;if(0!==n){var s=0;for(t=0;t<this.length;t++){var a=this.words[t]&i,c=(0|this.words[t])-a<<n;this.words[t]=c|s,s=a>>>26-n}s&&(this.words[t]=s,this.length++)}if(0!==o){for(t=this.length-1;t>=0;t--)this.words[t+o]=this.words[t];for(t=0;t<o;t++)this.words[t]=0;this.length+=o}return this.strip()},i.prototype.ishln=function(e){return r(0===this.negative),this.iushln(e)},i.prototype.iushrn=function(e,t,n){var o;r("number"==typeof e&&e>=0),o=t?(t-t%26)/26:0;var i=e%26,s=Math.min((e-i)/26,this.length),a=67108863^67108863>>>i<<i,c=n;if(o-=s,o=Math.max(0,o),c){for(var u=0;u<s;u++)c.words[u]=this.words[u];c.length=s}if(0===s);else if(this.length>s)for(this.length-=s,u=0;u<this.length;u++)this.words[u]=this.words[u+s];else this.words[0]=0,this.length=1;var l=0;for(u=this.length-1;u>=0&&(0!==l||u>=o);u--){var h=0|this.words[u];this.words[u]=l<<26-i|h>>>i,l=h&a}return c&&0!==l&&(c.words[c.length++]=l),0===this.length&&(this.words[0]=0,this.length=1),this.strip()},i.prototype.ishrn=function(e,t,n){return r(0===this.negative),this.iushrn(e,t,n)},i.prototype.shln=function(e){return this.clone().ishln(e)},i.prototype.ushln=function(e){return this.clone().iushln(e)},i.prototype.shrn=function(e){return this.clone().ishrn(e)},i.prototype.ushrn=function(e){return this.clone().iushrn(e)},i.prototype.testn=function(e){r("number"==typeof e&&e>=0);var t=e%26,n=(e-t)/26,o=1<<t;return!(this.length<=n||!(this.words[n]&o))},i.prototype.imaskn=function(e){r("number"==typeof e&&e>=0);var t=e%26,n=(e-t)/26;if(r(0===this.negative,"imaskn works only with positive numbers"),this.length<=n)return this;if(0!==t&&n++,this.length=Math.min(n,this.length),0!==t){var o=67108863^67108863>>>t<<t;this.words[this.length-1]&=o}return this.strip()},i.prototype.maskn=function(e){return this.clone().imaskn(e)},i.prototype.iaddn=function(e){return r("number"==typeof e),r(e<67108864),e<0?this.isubn(-e):0!==this.negative?1===this.length&&(0|this.words[0])<e?(this.words[0]=e-(0|this.words[0]),this.negative=0,this):(this.negative=0,this.isubn(e),this.negative=1,this):this._iaddn(e)},i.prototype._iaddn=function(e){this.words[0]+=e;for(var t=0;t<this.length&&this.words[t]>=67108864;t++)this.words[t]-=67108864,t===this.length-1?this.words[t+1]=1:this.words[t+1]++;return this.length=Math.max(this.length,t+1),this},i.prototype.isubn=function(e){if(r("number"==typeof e),r(e<67108864),e<0)return this.iaddn(-e);if(0!==this.negative)return this.negative=0,this.iaddn(e),this.negative=1,this;if(this.words[0]-=e,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var t=0;t<this.length&&this.words[t]<0;t++)this.words[t]+=67108864,this.words[t+1]-=1;return this.strip()},i.prototype.addn=function(e){return this.clone().iaddn(e)},i.prototype.subn=function(e){return this.clone().isubn(e)},i.prototype.iabs=function(){return this.negative=0,this},i.prototype.abs=function(){return this.clone().iabs()},i.prototype._ishlnsubmul=function(e,t,n){var o,i,s=e.length+n;this._expand(s);var a=0;for(o=0;o<e.length;o++){i=(0|this.words[o+n])+a;var c=(0|e.words[o])*t;a=((i-=67108863&c)>>26)-(c/67108864|0),this.words[o+n]=67108863&i}for(;o<this.length-n;o++)a=(i=(0|this.words[o+n])+a)>>26,this.words[o+n]=67108863&i;if(0===a)return this.strip();for(r(-1===a),a=0,o=0;o<this.length;o++)a=(i=-(0|this.words[o])+a)>>26,this.words[o]=67108863&i;return this.negative=1,this.strip()},i.prototype._wordDiv=function(e,t){var n=(this.length,e.length),r=this.clone(),o=e,s=0|o.words[o.length-1];0!=(n=26-this._countBits(s))&&(o=o.ushln(n),r.iushln(n),s=0|o.words[o.length-1]);var a,c=r.length-o.length;if("mod"!==t){(a=new i(null)).length=c+1,a.words=new Array(a.length);for(var u=0;u<a.length;u++)a.words[u]=0}var l=r.clone()._ishlnsubmul(o,1,c);0===l.negative&&(r=l,a&&(a.words[c]=1));for(var h=c-1;h>=0;h--){var d=67108864*(0|r.words[o.length+h])+(0|r.words[o.length+h-1]);for(d=Math.min(d/s|0,67108863),r._ishlnsubmul(o,d,h);0!==r.negative;)d--,r.negative=0,r._ishlnsubmul(o,1,h),r.isZero()||(r.negative^=1);a&&(a.words[h]=d)}return a&&a.strip(),r.strip(),"div"!==t&&0!==n&&r.iushrn(n),{div:a||null,mod:r}},i.prototype.divmod=function(e,t,n){return r(!e.isZero()),this.isZero()?{div:new i(0),mod:new i(0)}:0!==this.negative&&0===e.negative?(a=this.neg().divmod(e,t),"mod"!==t&&(o=a.div.neg()),"div"!==t&&(s=a.mod.neg(),n&&0!==s.negative&&s.iadd(e)),{div:o,mod:s}):0===this.negative&&0!==e.negative?(a=this.divmod(e.neg(),t),"mod"!==t&&(o=a.div.neg()),{div:o,mod:a.mod}):this.negative&e.negative?(a=this.neg().divmod(e.neg(),t),"div"!==t&&(s=a.mod.neg(),n&&0!==s.negative&&s.isub(e)),{div:a.div,mod:s}):e.length>this.length||this.cmp(e)<0?{div:new i(0),mod:this}:1===e.length?"div"===t?{div:this.divn(e.words[0]),mod:null}:"mod"===t?{div:null,mod:new i(this.modn(e.words[0]))}:{div:this.divn(e.words[0]),mod:new i(this.modn(e.words[0]))}:this._wordDiv(e,t);var o,s,a},i.prototype.div=function(e){return this.divmod(e,"div",!1).div},i.prototype.mod=function(e){return this.divmod(e,"mod",!1).mod},i.prototype.umod=function(e){return this.divmod(e,"mod",!0).mod},i.prototype.divRound=function(e){var t=this.divmod(e);if(t.mod.isZero())return t.div;var n=0!==t.div.negative?t.mod.isub(e):t.mod,r=e.ushrn(1),o=e.andln(1),i=n.cmp(r);return i<0||1===o&&0===i?t.div:0!==t.div.negative?t.div.isubn(1):t.div.iaddn(1)},i.prototype.modn=function(e){r(e<=67108863);for(var t=(1<<26)%e,n=0,o=this.length-1;o>=0;o--)n=(t*n+(0|this.words[o]))%e;return n},i.prototype.idivn=function(e){r(e<=67108863);for(var t=0,n=this.length-1;n>=0;n--){var o=(0|this.words[n])+67108864*t;this.words[n]=o/e|0,t=o%e}return this.strip()},i.prototype.divn=function(e){return this.clone().idivn(e)},i.prototype.egcd=function(e){r(0===e.negative),r(!e.isZero());var t=this,n=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var o=new i(1),s=new i(0),a=new i(0),c=new i(1),u=0;t.isEven()&&n.isEven();)t.iushrn(1),n.iushrn(1),++u;for(var l=n.clone(),h=t.clone();!t.isZero();){for(var d=0,p=1;!(t.words[0]&p)&&d<26;++d,p<<=1);if(d>0)for(t.iushrn(d);d-- >0;)(o.isOdd()||s.isOdd())&&(o.iadd(l),s.isub(h)),o.iushrn(1),s.iushrn(1);for(var m=0,f=1;!(n.words[0]&f)&&m<26;++m,f<<=1);if(m>0)for(n.iushrn(m);m-- >0;)(a.isOdd()||c.isOdd())&&(a.iadd(l),c.isub(h)),a.iushrn(1),c.iushrn(1);t.cmp(n)>=0?(t.isub(n),o.isub(a),s.isub(c)):(n.isub(t),a.isub(o),c.isub(s))}return{a,b:c,gcd:n.iushln(u)}},i.prototype._invmp=function(e){r(0===e.negative),r(!e.isZero());var t=this,n=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var o,s=new i(1),a=new i(0),c=n.clone();t.cmpn(1)>0&&n.cmpn(1)>0;){for(var u=0,l=1;!(t.words[0]&l)&&u<26;++u,l<<=1);if(u>0)for(t.iushrn(u);u-- >0;)s.isOdd()&&s.iadd(c),s.iushrn(1);for(var h=0,d=1;!(n.words[0]&d)&&h<26;++h,d<<=1);if(h>0)for(n.iushrn(h);h-- >0;)a.isOdd()&&a.iadd(c),a.iushrn(1);t.cmp(n)>=0?(t.isub(n),s.isub(a)):(n.isub(t),a.isub(s))}return(o=0===t.cmpn(1)?s:a).cmpn(0)<0&&o.iadd(e),o},i.prototype.gcd=function(e){if(this.isZero())return e.abs();if(e.isZero())return this.abs();var t=this.clone(),n=e.clone();t.negative=0,n.negative=0;for(var r=0;t.isEven()&&n.isEven();r++)t.iushrn(1),n.iushrn(1);for(;;){for(;t.isEven();)t.iushrn(1);for(;n.isEven();)n.iushrn(1);var o=t.cmp(n);if(o<0){var i=t;t=n,n=i}else if(0===o||0===n.cmpn(1))break;t.isub(n)}return n.iushln(r)},i.prototype.invm=function(e){return this.egcd(e).a.umod(e)},i.prototype.isEven=function(){return!(1&this.words[0])},i.prototype.isOdd=function(){return!(1&~this.words[0])},i.prototype.andln=function(e){return this.words[0]&e},i.prototype.bincn=function(e){r("number"==typeof e);var t=e%26,n=(e-t)/26,o=1<<t;if(this.length<=n)return this._expand(n+1),this.words[n]|=o,this;for(var i=o,s=n;0!==i&&s<this.length;s++){var a=0|this.words[s];i=(a+=i)>>>26,a&=67108863,this.words[s]=a}return 0!==i&&(this.words[s]=i,this.length++),this},i.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},i.prototype.cmpn=function(e){var t,n=e<0;if(0!==this.negative&&!n)return-1;if(0===this.negative&&n)return 1;if(this.strip(),this.length>1)t=1;else{n&&(e=-e),r(e<=67108863,"Number is too big");var o=0|this.words[0];t=o===e?0:o<e?-1:1}return 0!==this.negative?0|-t:t},i.prototype.cmp=function(e){if(0!==this.negative&&0===e.negative)return-1;if(0===this.negative&&0!==e.negative)return 1;var t=this.ucmp(e);return 0!==this.negative?0|-t:t},i.prototype.ucmp=function(e){if(this.length>e.length)return 1;if(this.length<e.length)return-1;for(var t=0,n=this.length-1;n>=0;n--){var r=0|this.words[n],o=0|e.words[n];if(r!==o){r<o?t=-1:r>o&&(t=1);break}}return t},i.prototype.gtn=function(e){return 1===this.cmpn(e)},i.prototype.gt=function(e){return 1===this.cmp(e)},i.prototype.gten=function(e){return this.cmpn(e)>=0},i.prototype.gte=function(e){return this.cmp(e)>=0},i.prototype.ltn=function(e){return-1===this.cmpn(e)},i.prototype.lt=function(e){return-1===this.cmp(e)},i.prototype.lten=function(e){return this.cmpn(e)<=0},i.prototype.lte=function(e){return this.cmp(e)<=0},i.prototype.eqn=function(e){return 0===this.cmpn(e)},i.prototype.eq=function(e){return 0===this.cmp(e)},i.red=function(e){return new b(e)},i.prototype.toRed=function(e){return r(!this.red,"Already a number in reduction context"),r(0===this.negative,"red works only with positives"),e.convertTo(this)._forceRed(e)},i.prototype.fromRed=function(){return r(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},i.prototype._forceRed=function(e){return this.red=e,this},i.prototype.forceRed=function(e){return r(!this.red,"Already a number in reduction context"),this._forceRed(e)},i.prototype.redAdd=function(e){return r(this.red,"redAdd works only with red numbers"),this.red.add(this,e)},i.prototype.redIAdd=function(e){return r(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,e)},i.prototype.redSub=function(e){return r(this.red,"redSub works only with red numbers"),this.red.sub(this,e)},i.prototype.redISub=function(e){return r(this.red,"redISub works only with red numbers"),this.red.isub(this,e)},i.prototype.redShl=function(e){return r(this.red,"redShl works only with red numbers"),this.red.shl(this,e)},i.prototype.redMul=function(e){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.mul(this,e)},i.prototype.redIMul=function(e){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.imul(this,e)},i.prototype.redSqr=function(){return r(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},i.prototype.redISqr=function(){return r(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},i.prototype.redSqrt=function(){return r(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},i.prototype.redInvm=function(){return r(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},i.prototype.redNeg=function(){return r(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},i.prototype.redPow=function(e){return r(this.red&&!e.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,e)};var y={k256:null,p224:null,p192:null,p25519:null};function E(e,t){this.name=e,this.p=new i(t,16),this.n=this.p.bitLength(),this.k=new i(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function S(){E.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function O(){E.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function C(){E.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function v(){E.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function b(e){if("string"==typeof e){var t=i._prime(e);this.m=t.p,this.prime=t}else r(e.gtn(1),"modulus must be greater than 1"),this.m=e,this.prime=null}function w(e){b.call(this,e),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new i(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}E.prototype._tmp=function(){var e=new i(null);return e.words=new Array(Math.ceil(this.n/13)),e},E.prototype.ireduce=function(e){var t,n=e;do{this.split(n,this.tmp),t=(n=(n=this.imulK(n)).iadd(this.tmp)).bitLength()}while(t>this.n);var r=t<this.n?-1:n.ucmp(this.p);return 0===r?(n.words[0]=0,n.length=1):r>0?n.isub(this.p):void 0!==n.strip?n.strip():n._strip(),n},E.prototype.split=function(e,t){e.iushrn(this.n,0,t)},E.prototype.imulK=function(e){return e.imul(this.k)},o(S,E),S.prototype.split=function(e,t){for(var n=4194303,r=Math.min(e.length,9),o=0;o<r;o++)t.words[o]=e.words[o];if(t.length=r,e.length<=9)return e.words[0]=0,void(e.length=1);var i=e.words[9];for(t.words[t.length++]=i&n,o=10;o<e.length;o++){var s=0|e.words[o];e.words[o-10]=(s&n)<<4|i>>>22,i=s}i>>>=22,e.words[o-10]=i,0===i&&e.length>10?e.length-=10:e.length-=9},S.prototype.imulK=function(e){e.words[e.length]=0,e.words[e.length+1]=0,e.length+=2;for(var t=0,n=0;n<e.length;n++){var r=0|e.words[n];t+=977*r,e.words[n]=67108863&t,t=64*r+(t/67108864|0)}return 0===e.words[e.length-1]&&(e.length--,0===e.words[e.length-1]&&e.length--),e},o(O,E),o(C,E),o(v,E),v.prototype.imulK=function(e){for(var t=0,n=0;n<e.length;n++){var r=19*(0|e.words[n])+t,o=67108863&r;r>>>=26,e.words[n]=o,t=r}return 0!==t&&(e.words[e.length++]=t),e},i._prime=function(e){if(y[e])return y[e];var t;if("k256"===e)t=new S;else if("p224"===e)t=new O;else if("p192"===e)t=new C;else{if("p25519"!==e)throw new Error("Unknown prime "+e);t=new v}return y[e]=t,t},b.prototype._verify1=function(e){r(0===e.negative,"red works only with positives"),r(e.red,"red works only with red numbers")},b.prototype._verify2=function(e,t){r(!(e.negative|t.negative),"red works only with positives"),r(e.red&&e.red===t.red,"red works only with red numbers")},b.prototype.imod=function(e){return this.prime?this.prime.ireduce(e)._forceRed(this):e.umod(this.m)._forceRed(this)},b.prototype.neg=function(e){return e.isZero()?e.clone():this.m.sub(e)._forceRed(this)},b.prototype.add=function(e,t){this._verify2(e,t);var n=e.add(t);return n.cmp(this.m)>=0&&n.isub(this.m),n._forceRed(this)},b.prototype.iadd=function(e,t){this._verify2(e,t);var n=e.iadd(t);return n.cmp(this.m)>=0&&n.isub(this.m),n},b.prototype.sub=function(e,t){this._verify2(e,t);var n=e.sub(t);return n.cmpn(0)<0&&n.iadd(this.m),n._forceRed(this)},b.prototype.isub=function(e,t){this._verify2(e,t);var n=e.isub(t);return n.cmpn(0)<0&&n.iadd(this.m),n},b.prototype.shl=function(e,t){return this._verify1(e),this.imod(e.ushln(t))},b.prototype.imul=function(e,t){return this._verify2(e,t),this.imod(e.imul(t))},b.prototype.mul=function(e,t){return this._verify2(e,t),this.imod(e.mul(t))},b.prototype.isqr=function(e){return this.imul(e,e.clone())},b.prototype.sqr=function(e){return this.mul(e,e)},b.prototype.sqrt=function(e){if(e.isZero())return e.clone();var t=this.m.andln(3);if(r(t%2==1),3===t){var n=this.m.add(new i(1)).iushrn(2);return this.pow(e,n)}for(var o=this.m.subn(1),s=0;!o.isZero()&&0===o.andln(1);)s++,o.iushrn(1);r(!o.isZero());var a=new i(1).toRed(this),c=a.redNeg(),u=this.m.subn(1).iushrn(1),l=this.m.bitLength();for(l=new i(2*l*l).toRed(this);0!==this.pow(l,u).cmp(c);)l.redIAdd(c);for(var h=this.pow(l,o),d=this.pow(e,o.addn(1).iushrn(1)),p=this.pow(e,o),m=s;0!==p.cmp(a);){for(var f=p,g=0;0!==f.cmp(a);g++)f=f.redSqr();r(g<m);var y=this.pow(h,new i(1).iushln(m-g-1));d=d.redMul(y),h=y.redSqr(),p=p.redMul(h),m=g}return d},b.prototype.invm=function(e){var t=e._invmp(this.m);return 0!==t.negative?(t.negative=0,this.imod(t).redNeg()):this.imod(t)},b.prototype.pow=function(e,t){if(t.isZero())return new i(1).toRed(this);if(0===t.cmpn(1))return e.clone();var n=new Array(16);n[0]=new i(1).toRed(this),n[1]=e;for(var r=2;r<n.length;r++)n[r]=this.mul(n[r-1],e);var o=n[0],s=0,a=0,c=t.bitLength()%26;for(0===c&&(c=26),r=t.length-1;r>=0;r--){for(var u=t.words[r],l=c-1;l>=0;l--){var h=u>>l&1;o!==n[0]&&(o=this.sqr(o)),0!==h||0!==s?(s<<=1,s|=h,(4==++a||0===r&&0===l)&&(o=this.mul(o,n[s]),a=0,s=0)):a=0}c=26}return o},b.prototype.convertTo=function(e){var t=e.umod(this.m);return t===e?t.clone():t},b.prototype.convertFrom=function(e){var t=e.clone();return t.red=null,t},i.mont=function(e){return new w(e)},o(w,b),w.prototype.convertTo=function(e){return this.imod(e.ushln(this.shift))},w.prototype.convertFrom=function(e){var t=this.imod(e.mul(this.rinv));return t.red=null,t},w.prototype.imul=function(e,t){if(e.isZero()||t.isZero())return e.words[0]=0,e.length=1,e;var n=e.imul(t),r=n.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),o=n.isub(r).iushrn(this.shift),i=o;return o.cmp(this.m)>=0?i=o.isub(this.m):o.cmpn(0)<0&&(i=o.iadd(this.m)),i._forceRed(this)},w.prototype.mul=function(e,t){if(e.isZero()||t.isZero())return new i(0)._forceRed(this);var n=e.mul(t),r=n.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),o=n.isub(r).iushrn(this.shift),s=o;return o.cmp(this.m)>=0?s=o.isub(this.m):o.cmpn(0)<0&&(s=o.iadd(this.m)),s._forceRed(this)},w.prototype.invm=function(e){return this.imod(e._invmp(this.m).mul(this.r2))._forceRed(this)}}(e=n.nmd(e),this)},33787:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default={width:function e(t){var n;let r=0;return t?(void 0===t.fields||(r+=t.fields.length,r+=t.fields.map((t=>e(t.types.find((e=>"Document"===e.name))))).reduce(((e,t)=>e+t||0),0),r+=null!==(n=t.fields.map((t=>{const n=t.types.find((e=>"Array"===e.name));if(n)return e(n.types.find((e=>"Document"===e.name)))})).reduce(((e,t)=>(null!=e?e:0)+(null!=t?t:0)||0),0))&&void 0!==n?n:0),r):r},depth:function e(t){if(!t)return 0;let n=0;return void 0!==t.fields&&t.fields.length>0&&(n=1+Math.max(Math.max(...t.fields.map((t=>e(t.types.find((e=>"Document"===e.name)))))),Math.max(...t.fields.map((t=>{const n=t.types.find((e=>"Array"===e.name));return n?e(n.types.find((e=>"Document"===e.name))):0}))))),n},branch:function e(t){const n=[];let r;return t?(void 0!==t.fields&&t.fields.length>0&&(n.push(t.fields.length),r=t.fields.map((function(t){return e(t.types.find((e=>"Document"===e.name)))})),n.push(...r.flat(1/0)),r=t.fields.map((function(t){const n=t.types.find((e=>"Array"===e.name));return n?e(n.types.find((e=>"Document"===e.name))):[]})),n.push(...r.flat(1/0))),n.sort().reverse()):n}}},33859:(e,t)=>{function n(e){return e.bsonType||e.type}function r(e,t){if(null==e)throw new Error(t)}function o(e){const t=n(e),r=(Array.isArray(t)?t:[null!=t?t:"any"]).map((e=>function(e){switch(e){case"string":return"string";case"number":case"integer":return"number";case"boolean":case"bool":return"boolean";case"null":return"null";case"double":return["bson.Double","number"];case"binData":return"bson.Binary";case"objectId":return"bson.ObjectId";case"date":return"bson.Date";case"regex":return"bson.BSONRegExp";case"symbol":return"bson.BSONSymbol";case"javascript":case"javascriptWithScope":return"bson.Code";case"int":return["bson.Int32","number"];case"timestamp":return"bson.Timestamp";case"long":return["bson.Long","number"];case"decimal":return"bson.Decimal128";case"minKey":return"bson.MinKey";case"maxKey":return"bson.MaxKey";case"dbPointer":return"bson.DBPointer";case"undefined":return"undefined";default:return"any"}}(e))).flat();return new Set(r.flat())}function i(e){const t=[];for(let n=0;n<e;n++)t.push(" ");return t.join("")}function s(e,t){return`{\n${Object.entries(e).map((([e,a])=>{switch(n(a)){case"array":return r(a.items,"schema.items must be defined"),`${i(t)}${e}?: ${c=[...o(a.items)],1===c.length?`${c[0]}[]`:`${c.join(" | ")})[]`}`;case"object":return r(a.properties,"schema.properties must be defined"),`${i(t)}${e}?: ${s(a.properties,t+1)}`;default:return`${i(t)}${e}?: ${[...o(a)].join(" | ")}`}var c})).join(";\n")};\n${i(t-1)}}`}Object.defineProperty(t,"__esModule",{value:!0}),t.toTypescriptTypeDefinition=void 0,t.toTypescriptTypeDefinition=function(e){return r(e.properties,"schema.properties must be defined"),s(e.properties,1)}},34080:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ClientBulkWriteOperation=void 0;const r=n(75725),o=n(145),i=n(78130),s=n(35394);class a extends i.CommandOperation{get commandName(){return"bulkWrite"}constructor(e,t){super(void 0,t),this.SERVER_COMMAND_RESPONSE_TYPE=r.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 n=this.commandBuilder.buildBatch(e.description.maxMessageSizeBytes,e.description.maxWriteBatchSize,e.description.maxBsonObjectSize);return this.canRetryWrite||(this.options.willRetryWrite=!1),n}}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,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.loadGCPCredentials=async function(e){const t=(0,r.getGcpMetadata)();if("kModuleError"in t)return e;const{access_token:n}=await t.instance({property:"service-accounts/default/token"});return{...e,gcp:{accessToken:n}}};const r=n(8500)},34995:function(e,t,n){var r,o=n(67787).Buffer,i=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var o=Object.getOwnPropertyDescriptor(t,n);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,o)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||(r=function(e){return r=Object.getOwnPropertyNames||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[t.length]=n);return t},r(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n=r(e),o=0;o<n.length;o++)"default"!==n[o]&&i(t,e,n[o]);return s(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.GLOBAL_FUNCTIONS=t.GLOBALS=void 0,t.getScopeFunction=function(e,t){if(t&&d[e])return d[e];if(!t&&h[e])return h[e];if(p[e])return p[e];throw new Error(`Attempted to access scope property '${e}' that doesn't exist`)},t.isMethodWhitelisted=function(e,t){if(Object.prototype.hasOwnProperty.call(m,e)){const n=m[e].allowedMethods;return"string"==typeof n?m[n].allowedMethods[t]:n[t]}return!1},t.getClass=function(e){if(Object.prototype.hasOwnProperty.call(m,e))return m[e].class;throw new Error(`Attempted to access member '${e}' that doesn't exist`)};const c=a(n(62444));function u(e){return Object.freeze(Object.create(null,Object.getOwnPropertyDescriptors(e)))}function l(e){return"string"==typeof e?c.Long.fromString(e):c.Long.fromNumber(e)}const h=u({Date:function(...e){return Date(...e)}}),d=u({Date:function(...e){return new Date(...e)}}),p=u({RegExp,Binary:function(e,t){return new c.Binary(e,t)},LegacyJavaUUID:function(e){void 0===e&&(e=(new c.UUID).toHexString());let t=String.prototype.replace.call(e,/[{}-]/g,(()=>"")),n=String.prototype.substring.call(t,0,16),r=String.prototype.substring.call(t,16,32);n=String.prototype.substring.call(n,14,16)+String.prototype.substring.call(n,12,14)+String.prototype.substring.call(n,10,12)+String.prototype.substring.call(n,8,10)+String.prototype.substring.call(n,6,8)+String.prototype.substring.call(n,4,6)+String.prototype.substring.call(n,2,4)+String.prototype.substring.call(n,0,2),r=String.prototype.substring.call(r,14,16)+String.prototype.substring.call(r,12,14)+String.prototype.substring.call(r,10,12)+String.prototype.substring.call(r,8,10)+String.prototype.substring.call(r,6,8)+String.prototype.substring.call(r,4,6)+String.prototype.substring.call(r,2,4)+String.prototype.substring.call(r,0,2),t=n+r;const i=o.from(t,"hex");return new c.Binary(i,3)},LegacyCSharpUUID:function(e){void 0===e&&(e=(new c.UUID).toHexString());let t=String.prototype.replace.call(e,/[{}-]/g,(()=>""));t=String.prototype.substring.call(t,6,8)+String.prototype.substring.call(t,4,6)+String.prototype.substring.call(t,2,4)+String.prototype.substring.call(t,0,2)+(String.prototype.substring.call(t,10,12)+String.prototype.substring.call(t,8,10))+(String.prototype.substring.call(t,14,16)+String.prototype.substring.call(t,12,14))+String.prototype.substring.call(t,16,32);const n=o.from(t,"hex");return new c.Binary(n,3)},LegacyPythonUUID:function(e){return void 0===e?new c.Binary((new c.UUID).toBinary().buffer,3):new c.Binary(o.from(String.prototype.replace.call(e,/[{}-]/g,(()=>"")),"hex"),3)},BinData:function(e,t){return new c.Binary(o.from(t,"base64"),e)},UUID:function(e){return void 0===e?(new c.UUID).toBinary():new c.Binary(o.from(e.replace(/-/g,""),"hex"),4)},Code:function(e,t){return new c.Code(e,t)},DBRef:function(e,t,n,r){return new c.DBRef(e,t,n,r)},Decimal128:function(e){return c.Decimal128.fromString(e)},NumberDecimal:function(e){return c.Decimal128.fromString(e)},Double:function(e){return new c.Double(e)},Int32:function(e){return new c.Int32(e)},NumberInt:function(e){return new c.Int32(e)},Long:function(e,t){return new c.Long(e,t)},NumberLong:l,Int64:l,Map:function(e){return new(c.Map??Map)(e)},MaxKey:function(){return new c.MaxKey},MinKey:function(){return new c.MinKey},ObjectID:function(e){return new c.ObjectId(e)},ObjectId:function(e){return new c.ObjectId(e)},Symbol:function(e){return new c.BSONSymbol(e)},Timestamp:function(e,t){return"number"==typeof e&&"number"==typeof t||void 0!==t?new c.Timestamp({t:e,i:t}):new c.Timestamp(e)},ISODate:function(e){if(void 0===e)return new Date;if("string"!=typeof e)return new Date(e);const t=e.match(/^(?<Y>\d{4})-?(?<M>\d{2})-?(?<D>\d{2})([T ](?<h>\d{2})(:?(?<m>\d{2})(:?((?<s>\d{2})(\.(?<ms>\d+))?))?)?(?<tz>Z|([+-])(\d{2}):?(\d{2})?)?)?$/);if(null!==t&&void 0!==t.groups){const{Y:e,M:n,D:r,h:o,m:i,s,ms:a,tz:c}=t.groups,u=new Date(`${e}-${n}-${r}T${o||"00"}:${i||"00"}:${s||"00"}.${a||"000"}${c||"Z"}`);if(u.getTime()>=-621672192e5&&u.getTime()<=0xe677d21fdbff)return u}throw new Error(`${JSON.stringify(e)} is not a valid ISODate`)}});t.GLOBALS=u({Infinity:1/0,NaN:NaN,undefined:void 0});const m=u({Math:u({class:Math,allowedMethods:u({abs:!0,acos:!0,acosh:!0,asin:!0,asinh:!0,atan:!0,atan2:!0,atanh:!0,cbrt:!0,ceil:!0,clz32:!0,cos:!0,cosh:!0,exp:!0,expm1:!0,floor:!0,fround:!0,hypot:!0,imul:!0,log:!0,log10:!0,log1p:!0,log2:!0,max:!0,min:!0,pow:!0,round:!0,sign:!0,sin:!0,sinh:!0,sqrt:!0,tan:!0,tanh:!0,trunc:!0})}),Date:u({class:Date,allowedMethods:u({getDate:!0,getDay:!0,getFullYear:!0,getHours:!0,getMilliseconds:!0,getMinutes:!0,getMonth:!0,getSeconds:!0,getTime:!0,getTimezoneOffset:!0,getUTCDate:!0,getUTCDay:!0,getUTCFullYear:!0,getUTCHours:!0,getUTCMilliseconds:!0,getUTCMinutes:!0,getUTCMonth:!0,getUTCSeconds:!0,getYear:!0,now:!0,setDate:!0,setFullYear:!0,setHours:!0,setMilliseconds:!0,setMinutes:!0,setMonth:!0,setSeconds:!0,setTime:!0,setUTCDate:!0,setUTCFullYear:!0,setUTCHours:!0,setUTCMilliseconds:!0,setUTCMinutes:!0,setUTCMonth:!0,setUTCSeconds:!0,setYear:!0,toISOString:!0,valueOf:!0})}),ISODate:u({class:Date,allowedMethods:"Date"}),Binary:u({class:c.Binary,allowedMethods:{createFromHexString:!0,createFromBase64:!0}})});t.GLOBAL_FUNCTIONS=Object.freeze([...Object.keys(p),...Object.keys(d),...Object.keys(h)])},35293:(e,t,n)=>{var r=n(67787).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.ScramSHA256=t.ScramSHA1=void 0;const o=n(21242),i=n(27348),s=n(75080),a=n(17562),c=n(145),u=n(31057),l=n(93065);class h extends u.AuthProvider{constructor(e){super(),this.cryptoMethod=e||"sha1"}async prepare(e,t){const n=this.cryptoMethod,r=t.credentials;if(!r)throw new a.MongoMissingCredentialsError("AuthContext must provide credentials.");const o=await(0,c.randomBytes)(24);return t.nonce=o,{...e,speculativeAuthenticate:{...m(n,r,o),db:r.source}}}async auth(e){const{reauthenticating:t,response:n}=e;return n?.speculativeAuthenticate&&!t?await f(this.cryptoMethod,n.speculativeAuthenticate,e):await async function(e,t){const{connection:n,credentials:r}=t;if(!r)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=r.source,s=m(e,r,o),u=await n.command((0,c.ns)(`${i}.$cmd`),s,void 0);await f(e,u,t)}(this.cryptoMethod,e)}}function d(e){return e.replace("=","=3D").replace(",","=2C")}function p(e,t){return r.concat([r.from("n=","utf8"),r.from(e,"utf8"),r.from(",r=","utf8"),r.from(t.toString("base64"),"utf8")])}function m(e,t,n){const o=d(t.username);return{saslStart:1,mechanism:"sha1"===e?l.AuthMechanism.MONGODB_SCRAM_SHA1:l.AuthMechanism.MONGODB_SCRAM_SHA256,payload:new s.Binary(r.concat([r.from("n,,","utf8"),p(o,n)])),autoAuthorize:1,options:{skipEmptyExchange:!0}}}async function f(e,t,n){const u=n.connection,l=n.credentials;if(!l)throw new a.MongoMissingCredentialsError("AuthContext must provide credentials.");if(!n.nonce)throw new a.MongoInvalidArgumentError("Unable to continue SCRAM without valid nonce");const h=n.nonce,m=l.source,f=d(l.username),C=l.password,v="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 n;try{n=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 n.update(`${e}:mongo:${t}`,"utf8"),n.digest("hex")}(f,C),b=r.isBuffer(t.payload)?new s.Binary(t.payload):t.payload,w=g(b),M=parseInt(w.i,10);if(M&&M<4096)throw new a.MongoRuntimeError(`Server returned an invalid iteration count ${M}`);const T=w.s,_=w.r;if(_.startsWith("nonce"))throw new a.MongoRuntimeError(`Server returned an invalid nonce: ${_}`);const A=`c=biws,r=${_}`,R=function(e,t,n,r){const o=[e,t.toString("base64"),n].join("_");if(null!=E[o])return E[o];const s=i.pbkdf2Sync(e,t,n,O[r],r);return S>=200&&(E={},S=0),E[o]=s,S+=1,s}(v,r.from(T,"base64"),M,e),N=y(e,R,"Client Key"),I=y(e,R,"Server Key"),x=(P=e,k=N,i.createHash(P).update(k).digest());var P,k;const D=[p(f,h),b.toString("utf8"),A].join(","),L=[A,`p=${function(e,t){r.isBuffer(e)||(e=r.from(e)),r.isBuffer(t)||(t=r.from(t));const n=Math.max(e.length,t.length),o=[];for(let r=0;r<n;r+=1)o.push(e[r]^t[r]);return r.from(o).toString("base64")}(N,y(e,x,D))}`].join(","),B=y(e,I,D),j={saslContinue:1,conversationId:t.conversationId,payload:new s.Binary(r.from(L))},F=await u.command((0,c.ns)(`${m}.$cmd`),j,void 0),U=g(F.payload);if(!function(e,t){if(e.length!==t.length)return!1;if("function"==typeof i.timingSafeEqual)return i.timingSafeEqual(e,t);let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return 0===n}(r.from(U.v,"base64"),B))throw new a.MongoRuntimeError("Server returned an invalid signature");if(!1!==F.done)return;const z={saslContinue:1,conversationId:F.conversationId,payload:r.alloc(0)};await u.command((0,c.ns)(`${m}.$cmd`),z,void 0)}function g(e){const t={},n=e.toString("utf8").split(",");for(let e=0;e<n.length;e++){const r=(n[e].match(/^([^=]*)=(.*)$/)??[]).slice(1);t[r[0]]=r[1]}return t}function y(e,t,n){return i.createHmac(e,t).update(n).digest()}let E={},S=0;const O={sha256:32,sha1:20};t.ScramSHA1=class extends h{constructor(){super("sha1")}},t.ScramSHA256=class extends h{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,n)=>{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 r=n(75080),o=n(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,r.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,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Explain=t.ExplainVerbosity=void 0,t.validateExplainTimeoutOptions=function(e,t){const{maxTimeMS:n,timeoutMS:o}=e;if(null!=o&&(null!=n||null!=t?.maxTimeMS))throw new r.MongoAPIError("Cannot use maxTimeMS with timeoutMS for explain commands.")},t.decorateWithExplain=function(e,t){const{verbosity:n,maxTimeMS:r}=t,o={explain:e,verbosity:n};return"number"==typeof r&&(o.maxTimeMS=r),o};const r=n(17562);t.ExplainVerbosity=Object.freeze({queryPlanner:"queryPlanner",queryPlannerExtended:"queryPlannerExtended",executionStats:"executionStats",allPlansExecution:"allPlansExecution"});class o{constructor(e,n){this.verbosity="boolean"==typeof e?e?t.ExplainVerbosity.allPlansExecution:t.ExplainVerbosity.queryPlanner:e,this.maxTimeMS=n}static fromOptions({explain:e}={}){if(null==e)return;if("boolean"==typeof e||"string"==typeof e)return new o(e);const{verbosity:t,maxTimeMS:n}=e;return new o(t,n)}}t.Explain=o},36649:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ExplainableCursor=void 0;const r=n(61066);class o extends r.AbstractCursor{resolveExplainTimeoutOptions(e,t){let n,r;return null==e&&null==t?(n=void 0,r=void 0):null!=e&&null==t?(n="object"!=typeof e||"verbosity"in e?e:void 0,r="object"==typeof e&&"timeoutMS"in e?e:void 0):(n=e,r=t),{timeout:r,explain:n}}}t.ExplainableCursor=o},37057:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.InternalSchemaBasedAccessor=void 0,t.InternalSchemaBasedAccessor=class{constructor(e,t){this.internalSchema=e,this.converters=t}async getInternalSchema(){return this.internalSchema}async getStandardJsonSchema(e={}){var t;return null!==(t=this.standardJSONSchema)&&void 0!==t?t:this.standardJSONSchema=await this.converters.internalToStandard(this.internalSchema,e)}async getMongoDBJsonSchema(e={}){var t;return null!==(t=this.mongodbJSONSchema)&&void 0!==t?t:this.mongodbJSONSchema=await this.converters.internalToMongoDB(this.internalSchema,e)}async getExpandedJSONSchema(e={}){var t;return null!==(t=this.expandedJSONSchema)&&void 0!==t?t:this.expandedJSONSchema=await this.converters.internalToExpanded(this.internalSchema,e)}}},38216:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SENSITIVE_COMMANDS=t.CommandFailedEvent=t.CommandSucceededEvent=t.CommandStartedEvent=void 0;const r=n(91869),o=n(145),i=n(15620);t.CommandStartedEvent=class{constructor(e,n,o){this.name=r.COMMAND_STARTED;const i=d(n),s=a(i),{address:c,connectionId:l,serviceId:h}=p(e);t.SENSITIVE_COMMANDS.has(s)&&(this.commandObj={},this.commandObj[s]=!0),this.address=c,this.connectionId=l,this.serviceId=h,this.requestId=n.requestId,this.databaseName=n.databaseName,this.commandName=s,this.command=u(s,i,i),this.serverConnectionId=o}get hasServiceId(){return!!this.serviceId}},t.CommandSucceededEvent=class{constructor(e,t,n,i,s){this.name=r.COMMAND_SUCCEEDED;const c=d(t),l=a(c),{address:h,connectionId:m,serviceId:f}=p(e);this.address=h,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}(n)),this.serverConnectionId=s,this.databaseName=t.databaseName}get hasServiceId(){return!!this.serviceId}},t.CommandFailedEvent=class{constructor(e,t,n,i,s){this.name=r.COMMAND_FAILED;const c=d(t),l=a(c),{address:h,connectionId:m,serviceId:f}=p(e);this.address=h,this.connectionId=m,this.serviceId=f,this.requestId=t.requestId,this.commandName=l,this.duration=(0,o.calculateDurationInMs)(i),this.failure=u(l,c,n),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",r.LEGACY_HELLO_COMMAND,r.LEGACY_HELLO_COMMAND_CAMEL_CASE]),a=e=>Object.keys(e)[0],c=e=>e.ns.split(".")[1],u=(e,n,r)=>t.SENSITIVE_COMMANDS.has(e)||s.has(e)&&n.speculativeAuthenticate?{}:r,l={$query:"filter",$orderby:"sort",$hint:"hint",$comment:"comment",$maxScan:"maxScan",$max:"max",$min:"min",$returnKey:"returnKey",$showDiskLoc:"showRecordId",$maxTimeMS:"maxTimeMS",$snapshot:"snapshot"},h={numberToSkip:"skip",numberToReturn:"batchSize",returnFieldSelector:"projection"};function d(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((n=>{null!=e.query[n]&&(t[l[n]]={...e.query[n]})}))),Object.keys(h).forEach((n=>{const r=n;null!=e[r]&&(t[h[r]]=e[r])})),t}let t={};const n={...e};return e.query&&(t={...e.query},n.query=t),e.query?t:n}function p(e){let t;return"id"in e&&(t=e.id),{address:e.address,serviceId:e.serviceId,connectionId:t}}},38944:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MongoClientAuthProviders=void 0;const r=n(95750),o=n(21119),i=n(63257),s=n(88822),a=n(50373),c=n(8294),u=n(70839),l=n(93065),h=n(35293),d=n(64647),p=n(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 r.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,n=i.OIDC_WORKFLOWS.get(t)?.();if(!n)throw new p.MongoInvalidArgumentError(`Could not load workflow for environment ${e.ENVIRONMENT}`);return n}}(e))],[l.AuthMechanism.MONGODB_PLAIN,()=>new u.Plain],[l.AuthMechanism.MONGODB_SCRAM_SHA1,()=>new h.ScramSHA1],[l.AuthMechanism.MONGODB_SCRAM_SHA256,()=>new h.ScramSHA256],[l.AuthMechanism.MONGODB_X509,()=>new d.X509]]);t.MongoClientAuthProviders=class{constructor(){this.existingProviders=new Map}getOrCreateProvider(e,t){const n=this.existingProviders.get(e);if(n)return n;const r=m.get(e);if(!r)throw new p.MongoInvalidArgumentError(`authMechanism ${e} not supported`);const o=r(t);return this.existingProviders.set(e,o),o}}},40012:(e,t,n)=>{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=r.MongoDBResponse.is(e)&&e.has("writeConcernError")?e.toObject():!r.MongoDBResponse.is(e)&&"writeConcernError"in e?e:null;if(null!=t)throw new o.MongoWriteConcernError(t)}};const r=n(75725),o=n(17562);t.WRITE_CONCERN_KEYS=["w","wtimeout","j","journal","fsync"];class i{constructor(e,t,n,r){null!=e&&(Number.isNaN(Number(e))?this.w=e:this.w=Number(e)),null!=t&&(this.wtimeoutMS=this.wtimeout=t),null!=n&&(this.journal=this.j=n),null!=r&&(this.journal=this.j=!!r)}static apply(e,t){const n={};return null!=t.w&&(n.w=t.w),null!=t.wtimeoutMS&&(n.wtimeout=t.wtimeoutMS),null!=t.journal&&(n.j=t.j),e.writeConcern=n,e}static fromOptions(e,t){if(null==e)return;let n;t=t??{},n="string"==typeof e||"number"==typeof e?{w:e}:e instanceof i?e:e.writeConcern;const r={...t instanceof i?t:t.writeConcern,...n},{w:o,wtimeout:s,j:a,fsync:c,journal:u,wtimeoutMS:l}=r;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},40165:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0});const r=n(86493);t.default={Email:r.isEmail}},40251:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ChangeStreamCursor=void 0;const r=n(22345),o=n(91869),i=n(62016),s=n(96357),a=n(145),c=n(61066);class u extends c.AbstractCursor{constructor(e,t,n=[],r={}){super(e,t,{...r,tailable:!0,awaitData:!0}),this.pipeline=n,this.changeStreamCursorOptions=r,this._resumeToken=null,this.startAtOperationTime=r.startAtOperationTime??null,r.startAfter?this.resumeToken=r.startAfter:r.resumeAfter&&(this.resumeToken=r.resumeAfter)}set resumeToken(e){this._resumeToken=e,this.emit(r.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}),n=await(0,s.executeOperation)(e.client,t,this.timeoutContext),r=t.server;return this.maxWireVersion=(0,a.maxWireVersion)(r),null==this.startAtOperationTime&&null==this.changeStreamCursorOptions.resumeAfter&&null==this.changeStreamCursorOptions.startAfter&&this.maxWireVersion>=7&&(this.startAtOperationTime=n.operationTime),this._processBatch(n),this.emit(o.INIT,n),this.emit(o.RESPONSE),{server:r,session:e,response:n}}async getMore(e){const t=await super.getMore(e);return this.maxWireVersion=(0,a.maxWireVersion)(this.server),this._processBatch(t),this.emit(r.ChangeStream.MORE,t),this.emit(r.ChangeStream.RESPONSE),t}}t.ChangeStreamCursor=u},40642:(e,t,n)=>{var r=/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=n(23457),a=n(90686),c=n(79696).Buffer;e.exports=function(e,t){var n,u=e.toString(),l=u.match(r);if(l){var h="aes"+l[1],d=c.from(l[2],"hex"),p=c.from(l[3].replace(/[\r\n]/g,""),"base64"),m=s(t,d.slice(0,8),parseInt(l[1],10)).key,f=[],g=a.createDecipheriv(h,m,d);f.push(g.update(p)),f.push(g.final()),n=c.concat(f)}else{var y=u.match(i);n=c.from(y[2].replace(/[\r\n]/g,""),"base64")}return{tag:u.match(o)[1],data:n}}},40866:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.UpdateSearchIndexOperation=void 0;const r=n(75725),o=n(35394);class i extends o.AbstractOperation{constructor(e,t,n){super(),this.SERVER_COMMAND_RESPONSE_TYPE=r.MongoDBResponse,this.collection=e,this.name=t,this.definition=n,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},40967:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.checkTree=void 0;const r=n(34995);class o{constructor(e){this.options=e,this.checkSafeCall=e=>{const t=this.options.allowMethods;if("Identifier"===e.callee.type)return r.GLOBAL_FUNCTIONS.indexOf(e.callee.name)>=0&&e.arguments.every(this.checkSafeExpression);if(t&&"MemberExpression"===e.callee.type){const t=e.callee.object,n=e.callee.property;if("Identifier"===t.type&&"Identifier"===n.type)return(0,r.isMethodWhitelisted)(t.name,n.name)&&e.arguments.every(this.checkSafeExpression);if("NewExpression"!==t.type&&"CallExpression"!==t.type||"Identifier"!==t.callee.type)return this.checkSafeExpression(t)&&e.arguments.every(this.checkSafeExpression);{const o=t.callee;return(0,r.isMethodWhitelisted)(o.name,n.name)&&e.arguments.every(this.checkSafeExpression)}}return!1},this.checkSafeExpression=e=>{switch(e?.type){case"Identifier":return Object.prototype.hasOwnProperty.call(r.GLOBALS,e.name);case"Literal":return!0;case"ArrayExpression":return e.elements.every(this.checkSafeExpression);case"UnaryExpression":return this.checkSafeExpression(e.argument);case"BinaryExpression":return this.checkSafeExpression(e.left)&&this.checkSafeExpression(e.right);case"CallExpression":case"NewExpression":return this.checkSafeCall(e);case"ObjectExpression":return e.properties.every((e=>!("computed"in e&&e.computed||"method"in e&&e.method)&&!(!("key"in e)||!["Literal","Identifier"].includes(e.key.type))&&"value"in e&&(["FunctionExpression","ArrowFunctionExpression"].includes(e.value.type)||this.checkSafeExpression(e.value))));default:return!1}}}}t.checkTree=(e,t)=>"Program"===e.type&&1===e.body.length&&"ExpressionStatement"===e.body[0].type&&new o(t).checkSafeExpression(e.body[0].expression)},43135:(e,t,n)=>{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 r=n(91869);t.ServerDescriptionChangedEvent=class{constructor(e,t,n,o){this.name=r.SERVER_DESCRIPTION_CHANGED,this.topologyId=e,this.address=t,this.previousDescription=n,this.newDescription=o}},t.ServerOpeningEvent=class{constructor(e,t){this.name=r.SERVER_OPENING,this.topologyId=e,this.address=t}},t.ServerClosedEvent=class{constructor(e,t){this.name=r.SERVER_CLOSED,this.topologyId=e,this.address=t}},t.TopologyDescriptionChangedEvent=class{constructor(e,t,n){this.name=r.TOPOLOGY_DESCRIPTION_CHANGED,this.topologyId=e,this.previousDescription=t,this.newDescription=n}},t.TopologyOpeningEvent=class{constructor(e){this.name=r.TOPOLOGY_OPENING,this.topologyId=e}},t.TopologyClosedEvent=class{constructor(e){this.name=r.TOPOLOGY_CLOSED,this.topologyId=e}},t.ServerHeartbeatStartedEvent=class{constructor(e,t){this.name=r.SERVER_HEARTBEAT_STARTED,this.connectionId=e,this.awaited=t}},t.ServerHeartbeatSucceededEvent=class{constructor(e,t,n,o){this.name=r.SERVER_HEARTBEAT_SUCCEEDED,this.connectionId=e,this.duration=t,this.reply=n??{},this.awaited=o}},t.ServerHeartbeatFailedEvent=class{constructor(e,t,n,o){this.name=r.SERVER_HEARTBEAT_FAILED,this.connectionId=e,this.duration=t,this.failure=n,this.awaited=o}}},43802:(e,t,n)=>{t.On=t.R5=void 0;var r=n(44558);Object.defineProperty(t,"R5",{enumerable:!0,get:function(){return r.extractProxySecrets}}),Object.defineProperty(t,"On",{enumerable:!0,get:function(){return r.mergeProxySecrets}})},44120:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Db=void 0;const r=n(71235),o=n(75080),i=n(22345),s=n(19498),a=n(91869),c=n(68526),u=n(55546),l=n(69429),h=n(17562),d=n(69878),p=n(95662),m=n(96357),f=n(22847),g=n(88536),y=n(64125),E=n(61861),S=n(17668),O=n(58127),C=n(5136),v=n(28541),b=n(13700),w=n(145),M=n(40012),T=["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,n){if(n=n??{},n=(0,w.filterOptions)(n,T),"string"==typeof t&&t.includes("."))throw new h.MongoInvalidArgumentError("Database names cannot contain the character '.'");this.s={options:n,readPreference:b.ReadPreference.fromOptions(n),bsonOptions:(0,o.resolveBSONOptions)(n,e),pkFactory:n?.pkFactory??w.DEFAULT_PK_FACTORY,readConcern:v.ReadConcern.fromOptions(n),writeConcern:M.WriteConcern.fromOptions(n),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,d.createCollections)(this,e,t)}async command(e,t){return await(0,m.executeOperation)(this.client,new S.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 r.Admin(this)}collection(e,t={}){if("function"==typeof t)throw new h.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,n){return await(0,m.executeOperation)(this.client,new E.RenameOperation(this.collection(e),t,(0,w.resolveOptions)(void 0,{...n,new_collection:!0,readPreference:b.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,n){return(await(0,m.executeOperation)(this.client,f.CreateIndexesOperation.fromIndexSpecification(this,e,t,n)))[0]}async removeUser(e,t){return await(0,m.executeOperation)(this.client,new y.RemoveUserOperation(this,e,(0,w.resolveOptions)(this,t)))}async setProfilingLevel(e,t){return await(0,m.executeOperation)(this.client,new O.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},44558:(e,t,n)=>{var r=n(9606).URL,o=n(65994).e;function i(e){const t=new Map;let n="";for(const[r,o]of Object.entries(e)){if(void 0===o)continue;const e=r.toUpperCase();e.endsWith("_PROXY")&&"NO_PROXY"!==e&&t.set(e.replace(/_PROXY$/,"").toLowerCase(),o||"direct://"),"NO_PROXY"===e&&(n=o)}return{map:t,noProxy:n}}function s(e,t){if(!e)return!0;if("*"===e)return!1;for(const n of e.split(/[\s,]/)){let{host:e,port:r}=n.match(/(?<host>.+)(:(?<port>\d+)$)?/)?.groups??{};if(e||(e=n,r=""),(!r||t.port===r)&&(e===t.hostname||e.startsWith("*")&&t.hostname.endsWith(e.substring(1))))return!1}return!0}function a(e,t,n){if(e.proxy){const n=e.proxy;return"direct:"===new r(n).protocol?"":s(e.noProxyHosts||"",new r(t))?n:""}if(e.useEnvironmentVariableProxies){const{map:a,noProxy:c}=i(e.env??o.env),u=new r(t),l=(n?.overrideProtocol??u.protocol).replace(/:$/,""),h=[c,e.noProxyHosts].filter(Boolean).join(","),d=a.get(l)||a.get("all");return d&&s(h,u)?d:""}return""}function c(e){if("ssh:"===(e=new r(e.toString())).protocol)throw new Error(`Using ssh:// proxies for generic browser proxy usage is not supported (translating '${u(e)}')`);if(e.username||e.password)throw new Error(`Using authenticated proxies for generic browser proxy usage is not supported (translating '${u(e)}')`);if("http:"!==e.protocol&&"https:"!==e.protocol&&"socks5:"!==e.protocol)throw new Error(`Unsupported proxy protocol (translating '${u(e)}')`);if(e.search||e.hash)throw new Error(`Unsupported URL extensions in proxy specification (translating '${u(e)}')`);if(""===e.pathname)return e.toString();if("/"!==e.pathname)throw new Error(`Unsupported URL pathname in proxy specification (translating '${u(e)}')`);return e.toString().replace(/\/$/,"")}function u(e){const t=new r(e.toString());return t.password&&(t.password="(credential)"),t.toString()}Object.defineProperty(t,"__esModule",{value:!0}),t.proxyConfForEnvVars=i,t.proxyForUrl=a,t.translateToElectronProxyConfig=function(e){if(e.proxy){let t=e.proxy;return new r(t).protocol.startsWith("pac+")?(t=t.replace("pac+",""),{mode:"pac_script",pacScript:t.toString(),proxyBypassRules:e.noProxyHosts}):{mode:"fixed_servers",proxyRules:c(t),proxyBypassRules:e.noProxyHosts}}if(e.useEnvironmentVariableProxies){const t=[],n=[e.noProxyHosts],{map:r,noProxy:s}=i(e.env??o.env);for(const e of["http","https","ftp"]){const n=r.get(e)||r.get("all");n&&t.push(`${e}=${c(n)}`)}n.push(s);const a=t.join(";"),u=n.filter(Boolean).join(",")||void 0;return a?{mode:"fixed_servers",proxyBypassRules:u,proxyRules:a}:u?{proxyBypassRules:u}:{}}return{}},t.getSocks5OnlyProxyOptions=function(e,t){let n;if(void 0!==t?n=a(e,t):e.noProxyHosts||(n=e.proxy),!n)return;const o=new r(n);return"socks5:"!==o.protocol?void 0:{proxyHost:decodeURIComponent(o.hostname),proxyPort:+(o.port||1080),proxyUsername:decodeURIComponent(o.username)||void 0,proxyPassword:decodeURIComponent(o.password)||void 0}},t.extractProxySecrets=function(e){const t={};if(e.proxy){const n=new r(e.proxy);t.password=n.password,n.password="",e={...e,proxy:n.toString()}}return e.sshOptions&&(t.sshIdentityKeyPassphrase=e.sshOptions.identityKeyPassphrase,e={...e,sshOptions:{...e.sshOptions,identityKeyPassphrase:void 0}}),{secrets:JSON.stringify(t),proxyOptions:e}},t.mergeProxySecrets=function({proxyOptions:e,secrets:t}){const n=JSON.parse(t||"{}");if((n.username||n.password)&&e.proxy){const t=new r(e.proxy);t.password=n.password||"",e={...e,proxy:t.toString()}}return n.sshIdentityKeyPassphrase&&(e={...e,sshOptions:{...e.sshOptions,identityKeyPassphrase:n.sshIdentityKeyPassphrase}}),e},t.redactUrl=u},46195:e=>{e.exports={rE:"6.19.0"}},47523:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ClientBulkWriteExecutor=void 0;const r=n(61066),o=n(7180),i=n(17562),s=n(7799),a=n(145),c=n(40012),u=n(96357),l=n(34080),h=n(11737),d=n(6987);t.ClientBulkWriteExecutor=class{constructor(e,t,n){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,...n},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 h.ClientBulkWriteCommandBuilder(this.operations,this.options,e),n=(0,a.resolveTimeoutOptions)(this.client,this.options),c=s.TimeoutContext.create(n);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 d.ClientBulkWriteResultsMerger.unacknowledged()}{const e=new d.ClientBulkWriteResultsMerger(this.options);for(;t.hasNextBatch();){const s=new r.CursorTimeoutContext(c,Symbol()),a={...this.options,timeoutContext:s,...null!=n.timeoutMS&&{timeoutMode:r.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 n=new i.MongoClientBulkWriteError({message:"Mongo client bulk write encountered an error during execution"});throw n.cause=t,n.partialResult=e.bulkWriteResult,n}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,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Encrypter=void 0;const r=n(70136),o=n(91869),i=n(8500),s=n(17562),a=n(22220);t.Encrypter=class{constructor(e,t,n){if("object"!=typeof n.autoEncryption)throw new s.MongoInvalidArgumentError('Option "autoEncryption" must be specified');this.internalClient=null,this.bypassAutoEncryption=!!n.autoEncryption.bypassAutoEncryption,this.needsConnecting=!1,0===n.maxPoolSize&&null==n.autoEncryption.keyVaultClient?n.autoEncryption.keyVaultClient=e:null==n.autoEncryption.keyVaultClient&&(n.autoEncryption.keyVaultClient=this.getInternalClient(e,t,n)),this.bypassAutoEncryption?n.autoEncryption.metadataClient=void 0:0===n.maxPoolSize?n.autoEncryption.metadataClient=e:n.autoEncryption.metadataClient=this.getInternalClient(e,t,n),n.proxyHost&&(n.autoEncryption.proxyOptions={proxyHost:n.proxyHost,proxyPort:n.proxyPort,proxyUsername:n.proxyUsername,proxyPassword:n.proxyPassword}),this.autoEncrypter=new r.AutoEncrypter(e,n.autoEncryption)}getInternalClient(e,t,n){let r=this.internalClient;if(null==r){const i={};for(const e of[...Object.getOwnPropertyNames(n),...Object.getOwnPropertySymbols(n)])["autoEncryption","minPoolSize","servers","caseTranslate","dbName"].includes(e)||Reflect.set(i,e,Reflect.get(n,e));i.minPoolSize=0,r=new a.MongoClient(t,i),this.internalClient=r;for(const t of o.MONGO_CLIENT_EVENTS)for(const n of e.listeners(t))r.on(t,n);e.on("newListener",((e,t)=>{r?.on(e,t)})),this.needsConnecting=!0}return r}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 n=this.internalClient;if(null!=n&&e!==n)return await n.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,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CallbackWorkflow=t.AUTOMATED_TIMEOUT_MS=t.HUMAN_TIMEOUT_MS=void 0;const r=n(37668),o=n(17562),i=n(145),s=n(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 n=this.cache.getAccessToken();e.accessToken=n;const r=(0,s.finishCommandDocument)(n);return r.db=t.source,{speculativeAuthenticate:r}}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,n){let r;return r=n?.speculativeAuthenticate?n.speculativeAuthenticate:await e.command((0,i.ns)(t.source),(0,s.startCommandDocument)(t),void 0),r}async finishAuthentication(e,t,n,r){await e.command((0,i.ns)(t.source),(0,s.finishCommandDocument)(n,r),void 0)}async executeAndValidateCallback(e){const t=await this.callback(e);if(null==(n=t)||"object"!=typeof n||!("accessToken"in n)||!Object.getOwnPropertyNames(n).every((e=>a.includes(e))))throw new o.MongoMissingCredentialsError("User provided OIDC callbacks must return a valid object with an accessToken.");var n;return t}withLock(e){let t=Promise.resolve();return async n=>(await t,t=t.catch((()=>null)).then((async()=>{const t=Date.now()-this.lastExecutionTime;return t<=100&&await(0,r.setTimeout)(100-t,{signal:n.timeoutContext}),this.lastExecutionTime=Date.now(),await e(n)})),await t)}}},50373:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HumanCallbackWorkflow=void 0;const r=n(75080),o=n(17562),i=n(7799),s=n(63257),a=n(49683);class c extends a.CallbackWorkflow{constructor(e,t){super(e,t)}async execute(e,t){if(this.cache.hasAccessToken){const n=this.cache.getAccessToken();e.accessToken=n;try{return await this.finishAuthentication(e,t,n)}catch(n){if(n instanceof o.MongoError&&n.code===o.MONGODB_ERROR_CODES.AuthenticationFailed)return this.cache.removeAccessToken(),delete e.accessToken,await this.execute(e,t);throw n}}if(this.cache.hasRefreshToken){const n=this.cache.getRefreshToken(),r=await this.fetchAccessToken(this.cache.getIdpInfo(),t,n);this.cache.put(r),e.accessToken=r.accessToken;try{return await this.finishAuthentication(e,t,r.accessToken)}catch(n){if(n instanceof o.MongoError&&n.code===o.MONGODB_ERROR_CODES.AuthenticationFailed)return this.cache.removeRefreshToken(),delete e.accessToken,await this.execute(e,t);throw n}}const n=await this.startAuthentication(e,t),i=n.conversationId,s=r.BSON.deserialize(n.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,n){const r=new AbortController,c={timeoutContext:r.signal,version:s.OIDC_VERSION,idpInfo:e};t.username&&(c.username=t.username),n&&(c.refreshToken=n);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 r.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,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.FindOperation=void 0;const r=n(75725),o=n(17562),i=n(30770),s=n(145),a=n(78130),c=n(35394);class u extends a.CommandOperation{constructor(e,t={},n={}){if(super(void 0,n),this.SERVER_COMMAND_RESPONSE_TYPE=r.CursorResponse,this.options={...n},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?r.ExplainedCursorResponse:r.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,n){const r={find:e.collection,filter:t};if(n.sort&&(r.sort=(0,i.formatSort)(n.sort)),n.projection){let e=n.projection;e&&Array.isArray(e)&&(e=e.length?e.reduce(((e,t)=>(e[t]=1,e)),{}):{_id:1}),r.projection=e}return n.hint&&(r.hint=(0,s.normalizeHintField)(n.hint)),"number"==typeof n.skip&&(r.skip=n.skip),"number"==typeof n.limit&&(n.limit<0?(r.limit=-n.limit,r.singleBatch=!0):r.limit=n.limit),"number"==typeof n.batchSize&&(n.batchSize<0?r.limit=-n.batchSize:n.batchSize===n.limit?r.batchSize=n.batchSize+1:r.batchSize=n.batchSize),"boolean"==typeof n.singleBatch&&(r.singleBatch=n.singleBatch),void 0!==n.comment&&(r.comment=n.comment),n.max&&(r.max=n.max),n.min&&(r.min=n.min),"boolean"==typeof n.returnKey&&(r.returnKey=n.returnKey),"boolean"==typeof n.showRecordId&&(r.showRecordId=n.showRecordId),"boolean"==typeof n.tailable&&(r.tailable=n.tailable),"boolean"==typeof n.oplogReplay&&(r.oplogReplay=n.oplogReplay),"boolean"==typeof n.timeout?r.noCursorTimeout=!n.timeout:"boolean"==typeof n.noCursorTimeout&&(r.noCursorTimeout=n.noCursorTimeout),"boolean"==typeof n.awaitData&&(r.awaitData=n.awaitData),"boolean"==typeof n.allowPartialResults&&(r.allowPartialResults=n.allowPartialResults),"boolean"==typeof n.allowDiskUse&&(r.allowDiskUse=n.allowDiskUse),n.let&&(r.let=n.let),r}(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,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isEmptyCredentials=s,t.refreshKMSCredentials=async function(e,t){let n=e;return s("aws",e)&&(n=await(0,r.loadAWSCredentials)(n,t?.aws)),s("gcp",e)&&(n=await(0,i.loadGCPCredentials)(n)),s("azure",e)&&(n=await(0,o.loadAzureCredentials)(n)),n};const r=n(59888),o=n(79790),i=n(34563);function s(e,t){const n=t[e];return null!=n&&"object"==typeof n&&0===Object.keys(n).length}},53162:function(e,t,n){var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var o=Object.getOwnPropertyDescriptor(t,n);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,o)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),i=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&r(t,e,n);return o(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.redactConnectionString=t.redactValidConnectionString=void 0;const s=i(n(65031));t.redactValidConnectionString=function(e,t){var n,r;const o=e.clone(),i=null!==(n=null==t?void 0:t.replacementString)&&void 0!==n?n:"_credentials_",a=null===(r=null==t?void 0:t.redactUsernames)||void 0===r||r;if((o.username||o.password)&&a?(o.username=i,o.password=""):o.password&&(o.password=i),o.searchParams.has("authMechanismProperties")){const e=new s.CommaAndColonSeparatedRecord(o.searchParams.get("authMechanismProperties"));e.get("AWS_SESSION_TOKEN")&&(e.set("AWS_SESSION_TOKEN",i),o.searchParams.set("authMechanismProperties",e.toString()))}return o.searchParams.has("tlsCertificateKeyFilePassword")&&o.searchParams.set("tlsCertificateKeyFilePassword",i),o.searchParams.has("proxyUsername")&&a&&o.searchParams.set("proxyUsername",i),o.searchParams.has("proxyPassword")&&o.searchParams.set("proxyPassword",i),o},t.redactConnectionString=function(e,t){var n,r;const o=null!==(n=null==t?void 0:t.replacementString)&&void 0!==n?n:"<credentials>",i=null===(r=null==t?void 0:t.redactUsernames)||void 0===r||r;let a;try{a=new s.default(e)}catch(e){}if(a)return t={...t,replacementString:"___credentials___"},a.redact(t).toString().replace(/___credentials___/g,o);const c=o,u=[e=>e.replace(i?/(\/\/)(.*)(@)/g:/(\/\/[^@]*:)(.*)(@)/g,`$1${c}$3`),e=>e.replace(/(AWS_SESSION_TOKEN(:|%3A))([^,&]+)/gi,`$1${c}`),e=>e.replace(/(tlsCertificateKeyFilePassword=)([^&]+)/gi,`$1${c}`),e=>i?e.replace(/(proxyUsername=)([^&]+)/gi,`$1${c}`):e,e=>e.replace(/(proxyPassword=)([^&]+)/gi,`$1${c}`)];for(const t of u)e=t(e);return e}},54553:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.executeAST=void 0;const r=n(34995),o=(e,t)=>{switch(e.callee.type){case"Identifier":{const n=(0,r.getScopeFunction)(e.callee.name,t),o=e.arguments.map((e=>i(e)));return n.apply(n,o)}case"MemberExpression":{const t="Identifier"===e.callee.object.type?(0,r.getClass)(e.callee.object.name):i(e.callee.object),n="Identifier"===e.callee.property.type&&e.callee.property.name;if(!n)throw new Error("Expected CallExpression property to be an identifier");const o=e.arguments.map((e=>i(e)));return t[n](...o)}default:throw new Error("Should not evaluate invalid expressions")}},i=e=>{switch(e?.type){case"Identifier":if(Object.prototype.hasOwnProperty.call(r.GLOBALS,e.name))return r.GLOBALS[e.name];throw new Error(`${e.name} is not a valid Identifier`);case"Literal":return e.value;case"UnaryExpression":return(e=>{if(!e.prefix)throw new Error("Malformed UnaryExpression");switch(e.operator){case"-":return-i(e.argument);case"+":return+i(e.argument);case"!":return!i(e.argument);case"~":return~i(e.argument);default:throw new Error(`Invalid UnaryExpression Provided: '${e.operator}'`)}})(e);case"BinaryExpression":return(e=>{const{left:t,right:n}=e;switch(e.operator){case"==":return i(t)==i(n);case"!=":return i(t)!=i(n);case"===":return i(t)===i(n);case"!==":return i(t)!==i(n);case"<":return i(t)<i(n);case"<=":return i(t)<=i(n);case">":return i(t)>i(n);case">=":return i(t)>=i(n);case"<<":return i(t)<<i(n);case">>":return i(t)>>i(n);case">>>":return i(t)>>>i(n);case"+":return i(t)+i(n);case"-":return i(t)-i(n);case"*":return i(t)*i(n);case"/":return i(t)/i(n);case"%":return i(t)%i(n);case"**":return i(t)**i(n);case"|":return i(t)|i(n);case"^":return i(t)^i(n);case"&":return i(t)&i(n);case"in":return i(t)in i(n);case"instanceof":return i(t)instanceof i(n);default:throw new Error(`Invalid BinaryExpression Provided: '${String(e.operator)}'`)}})(e);case"ArrayExpression":return e.elements.map((e=>i(e)));case"CallExpression":return o(e,!1);case"NewExpression":return o(e,!0);case"ObjectExpression":{const t=Object.create(null);for(const n of e.properties)"key"in n&&(t["Identifier"===n.key.type?n.key.name:i(n.key)]=i(n.value));return{...t}}case"FunctionExpression":case"ArrowFunctionExpression":return(e=>{const t=e.loc?.source||"",n=e.range||[];return t.slice(n[0],n[1])})(e);default:throw new Error}};t.executeAST=e=>{if("Program"===e.type&&1===e.body.length&&"ExpressionStatement"===e.body[0].type)return i(e.body[0].expression);throw new Error("Invalid AST Found")}},54564:(e,t,n)=>{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 r=n(75080),o=n(17562),i=n(4752),s=n(96357),a=n(9326),c=n(94330),u=n(7799),l=n(145),h=n(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 d{static generateIdMap(e){const t={};for(const n of e)t[n.index]=n._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=d.generateIdMap(this.result.upserted),this.insertedIds=d.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(${r.EJSON.stringify(this.result)})`}isOk(){return 1===this.result.ok}}t.BulkWriteResult=d;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,n,r){if(n?r=n:r&&r.result&&(r=r.result),null==r)return;if(0===r.ok&&1===t.ok){t.ok=0;const n={index:0,code:r.code||0,errmsg:r.message,errInfo:r.errInfo,op:e.operations[0]};return void t.writeErrors.push(new m(n))}if(0===r.ok&&0===t.ok)return;S(e)&&r.n&&(t.nInserted=t.nInserted+r.n),C(e)&&r.n&&(t.nRemoved=t.nRemoved+r.n);let o=0;if(Array.isArray(r.upserted)){o=r.upserted.length;for(let n=0;n<r.upserted.length;n++)t.upserted.push({index:r.upserted[n].index+e.originalZeroIndex,_id:r.upserted[n]._id})}else r.upserted&&(o=1,t.upserted.push({index:e.originalZeroIndex,_id:r.upserted}));if(O(e)&&r.n){const e=r.nModified;t.nUpserted=t.nUpserted+o,t.nMatched=t.nMatched+(r.n-o),t.nModified="number"==typeof e?t.nModified+e:0}if(Array.isArray(r.writeErrors))for(let n=0;n<r.writeErrors.length;n++){const o={index:e.originalIndexes[r.writeErrors[n].index],code:r.writeErrors[n].code,errmsg:r.writeErrors[n].errmsg,errInfo:r.writeErrors[n].errInfo,op:e.operations[r.writeErrors[n].index]};t.writeErrors.push(new m(o))}r.writeConcernError&&t.writeConcernErrors.push(new p(r.writeConcernError))}async function g(e,t){if(0===e.s.batches.length)return new d(e.s.bulkResult,e.isOrdered);for(const n of e.s.batches){const r=(0,l.resolveOptions)(e,{...t,ordered:e.isOrdered});!0!==r.bypassDocumentValidation&&delete r.bypassDocumentValidation,!0===e.s.bypassDocumentValidation&&(r.bypassDocumentValidation=!0),!1===e.s.checkKeys&&(r.checkKeys=!1),r.retryWrites&&(O(n)&&(r.retryWrites=r.retryWrites&&!n.operations.some((e=>e.multi))),C(n)&&(r.retryWrites=r.retryWrites&&!n.operations.some((e=>0===e.limit))));const u=S(n)?new a.InsertOperation(e.s.namespace,n.operations,r):O(n)?new c.UpdateOperation(e.s.namespace,n.operations,r):C(n)?new i.DeleteOperation(e.s.namespace,n.operations,r):null;if(null==u)throw new o.MongoRuntimeError(`Unknown batchType: ${n.batchType}`);let h,p=null;try{h=await(0,s.executeOperation)(e.s.collection.client,u,r.timeoutContext)}catch(e){p=e}if(null!=p){if(p instanceof o.MongoWriteConcernError){f(n,e.s.bulkResult,p,h);const t=new d(e.s.bulkResult,e.isOrdered);throw new y({message:p.result.writeConcernError.errmsg,code:p.result.writeConcernError.code},t)}throw new y(p,new d(e.s.bulkResult,e.isOrdered))}f(n,e.s.bulkResult,p,h);const m=new d(e.s.bulkResult,e.isOrdered);e.handleWriteError(m)}e.s.batches.length=0;const n=new d(e.s.bulkResult,e.isOrdered);return e.handleWriteError(n),n}t.WriteError=m;class y 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=y;class E{constructor(e){this.bulkOperation=e}update(e){const n=v(this.bulkOperation);return this.bulkOperation.addToOperationsList(t.BatchType.UPDATE,(0,c.makeUpdateStatement)(n.selector,e,{...n,multi:!0}))}updateOne(e){if(!(0,l.hasAtomicOperators)(e,this.bulkOperation.bsonOptions))throw new o.MongoInvalidArgumentError("Update document requires atomic operators");const n=v(this.bulkOperation);return this.bulkOperation.addToOperationsList(t.BatchType.UPDATE,(0,c.makeUpdateStatement)(n.selector,e,{...n,multi:!1}))}replaceOne(e){if((0,l.hasAtomicOperators)(e))throw new o.MongoInvalidArgumentError("Replacement document must not use atomic operators");const n=v(this.bulkOperation);return this.bulkOperation.addToOperationsList(t.BatchType.UPDATE,(0,c.makeUpdateStatement)(n.selector,e,{...n,multi:!1}))}deleteOne(){const e=v(this.bulkOperation);return this.bulkOperation.addToOperationsList(t.BatchType.DELETE,(0,i.makeDeleteStatement)(e.selector,{...e,limit:1}))}delete(){const e=v(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 S(e){return e.batchType===t.BatchType.INSERT}function O(e){return e.batchType===t.BatchType.UPDATE}function C(e){return e.batchType===t.BatchType.DELETE}function v(e){let{currentOp:t}=e.s;return e.s.currentOp=void 0,t||(t={}),t}t.FindOperators=E,t.BulkOperationBase=class{constructor(e,t,n){this.collection=e,this.isOrdered=n;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,d=s&&s.maxWriteBatchSize?s.maxWriteBatchSize:1e3,p=(d-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:h.WriteConcern.fromOptions(t),maxBsonObjectSize:c,maxBatchSizeBytes:u,maxWriteBatchSize:d,maxKeySize:p,namespace:i,topology:o,options:m,bsonOptions:(0,r.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 E(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 n=this.shouldForceServerObjectId(),r=e.insertOne&&null==e.insertOne.document?e.insertOne:e.insertOne.document;return(0,l.maybeAddIdToDocuments)(this.collection,r,{forceServerObjectId:n}),this.addToOperationsList(t.BatchType.INSERT,r)}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 n=(0,c.makeUpdateStatement)(e.replaceOne.filter,e.replaceOne.replacement,{...e.replaceOne,multi:!1});if((0,l.hasAtomicOperators)(n.u))throw new o.MongoInvalidArgumentError("Replacement document must not use atomic operators");return this.addToOperationsList(t.BatchType.UPDATE,n)}if("updateOne"in e){if("q"in e.updateOne)throw new o.MongoInvalidArgumentError("Raw operations are not allowed");const n=(0,c.makeUpdateStatement)(e.updateOne.filter,e.updateOne.update,{...e.updateOne,multi:!1});if(!(0,l.hasAtomicOperators)(n.u,this.bsonOptions))throw new o.MongoInvalidArgumentError("Update document requires atomic operators");return this.addToOperationsList(t.BatchType.UPDATE,n)}if("updateMany"in e){if("q"in e.updateMany)throw new o.MongoInvalidArgumentError("Raw operations are not allowed");const n=(0,c.makeUpdateStatement)(e.updateMany.filter,e.updateMany.update,{...e.updateMany,multi:!0});if(!(0,l.hasAtomicOperators)(n.u,this.bsonOptions))throw new o.MongoInvalidArgumentError("Update document requires atomic operators");return this.addToOperationsList(t.BatchType.UPDATE,n)}}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=h.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 n=(0,l.resolveOptions)(this.collection,{...this.s.options,...e});return n.timeoutContext??=u.TimeoutContext.create({session:n.session,timeoutMS:n.timeoutMS,serverSelectionTimeoutMS:this.collection.client.s.options.serverSelectionTimeoutMS,waitQueueTimeoutMS:this.collection.client.s.options.waitQueueTimeoutMS}),null==n.session?await this.collection.client.withSession({explicit:!1},(async e=>await g(this,{...n,session:e}))):await g(this,{...n})}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 y({message:t,code:this.s.bulkResult.writeErrors[0].code,writeErrors:this.s.bulkResult.writeErrors},e)}const t=e.getWriteConcernError();if(t)throw new y(t,e)}shouldForceServerObjectId(){return!0===this.s.options.forceServerObjectId||!0===this.s.collection.s.db.options?.forceServerObjectId}}},55546:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ListCollectionsCursor=void 0;const r=n(96357),o=n(88913),i=n(61066);class s extends i.AbstractCursor{constructor(e,t,n){super(e.client,e.s.namespace,n),this.parent=e,this.filter=t,this.options=n}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}),n=await(0,r.executeOperation)(this.parent.client,t,this.timeoutContext);return{server:t.server,session:e,response:n}}}t.ListCollectionsCursor=s},55741:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ConnectionPoolMetrics=void 0;class n{constructor(){this.txnConnections=0,this.cursorConnections=0,this.otherConnections=0}markPinned(e){e===n.TXN?this.txnConnections+=1:e===n.CURSOR?this.cursorConnections+=1:this.otherConnections+=1}markUnpinned(e){e===n.TXN?this.txnConnections-=1:e===n.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=n,n.TXN="txn",n.CURSOR="cursor",n.OTHER="other"},56463:(e,t,n)=>{var r=n(67787).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.LimitedSizeDocument=void 0,t.makeClientMetadata=function(e){const t=new l(512),{appName:n=""}=e;if(n.length>0){const o=r.byteLength(n,"utf8")<=128?e.appName:r.from(n,"utf8").subarray(0,128).toString("utf8");t.ifItFitsItSits("application",{name:o})}const{name:s="",version:c="",platform:h=""}=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:n=""}of e.additionalDriverInfo)t.length>0&&(p.name=`${p.name}|${t}`),n.length>0&&(p.version=`${p.version}|${n}`);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()}`;h.length>0&&(m=`${m}|${h}`);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=d();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={};h??=(0,c.fileIsAccessible)("/.dockerenv");const t=await h,{KUBERNETES_SERVICE_HOST:n=""}=i.env,r=n.length>0;return t&&(e.runtime="docker"),r&&(e.orchestrator="kubernetes"),e}();if(0===Object.keys(t).length)return e;const n=new l(512),r={...e?.env,container:t};for(const[t,o]of Object.entries(e))"env"!==t?n.ifItFitsItSits(t,o):n.ifItFitsItSits("env",r)||n.ifItFitsItSits("env",o);return"env"in e||n.ifItFitsItSits("env",r),n.toObject()},t.getFAASEnv=d;const o=n(35369),i=n(98999),s=n(75080),a=n(17562),c=n(145),u=n(46195).rE;class l{constructor(e){this.document=new Map,this.documentSize=5,this.maxSize=e}ifItFitsItSits(e,t){const n=s.BSON.serialize((new Map).set(e,t)).byteLength-5;return!(n+this.documentSize>this.maxSize||(this.documentSize+=n,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 h;function d(){const{AWS_EXECUTION_ENV:e="",AWS_LAMBDA_RUNTIME_API:t="",FUNCTIONS_WORKER_RUNTIME:n="",K_SERVICE:r="",FUNCTION_NAME:o="",VERCEL:a="",AWS_LAMBDA_FUNCTION_MEMORY_SIZE:c="",AWS_REGION:u="",FUNCTION_MEMORY_MB:l="",FUNCTION_REGION:h="",FUNCTION_TIMEOUT_SEC:d="",VERCEL_REGION:p=""}=i.env,m=e.startsWith("AWS_Lambda_")||t.length>0,f=n.length>0,g=r.length>0||o.length>0,y=a.length>0,E=new Map;return!y||f||g?m&&!(f||g||y)?(u.length>0&&E.set("region",u),c.length>0&&Number.isInteger(+c)&&E.set("memory_mb",new s.Int32(c)),E.set("name","aws.lambda"),E):f&&!(g||m||y)?(E.set("name","azure.func"),E):g&&!(f||m||y)?(h.length>0&&E.set("region",h),l.length>0&&Number.isInteger(+l)&&E.set("memory_mb",new s.Int32(l)),d.length>0&&Number.isInteger(+d)&&E.set("timeout_sec",new s.Int32(d)),E.set("name","gcp.func"),E):null:(p.length>0&&E.set("region",p),E.set("name","vercel"),E)}t.LimitedSizeDocument=l},57590:(e,t,n)=>{var r=n(65994).e;Object.defineProperty(t,"__esModule",{value:!0}),t.RTTSampler=t.MonitorInterval=t.RTTPinger=t.Monitor=t.ServerMonitoringMode=void 0;const o=n(37668),i=n(75080),s=n(87758),a=n(56463),c=n(91869),u=n(17562),l=n(93347),h=n(4642),d=n(145),p=n(89167),m=n(43135),f=n(5369),g="idle",y="monitoring",E=(0,d.makeStateMachine)({[p.STATE_CLOSING]:[p.STATE_CLOSING,g,p.STATE_CLOSED],[p.STATE_CLOSED]:[p.STATE_CLOSED,y],[g]:[g,y,p.STATE_CLOSING],[y]:[y,g,p.STATE_CLOSING]}),S=new Set([p.STATE_CLOSING,p.STATE_CLOSED,y]);function O(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 h.TypedEventEmitter{constructor(e,t){super(),this.component=l.MongoLoggableComponent.TOPOLOGY,this.on("error",d.noop),this.server=e,this.connection=null,this.cancellationToken=new h.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 n=this.cancellationToken,r={id:"<monitor>",generation:e.pool.generation,cancellationToken:n,hostAddress:e.description.hostAddress,...t,raw:!1,useBigInt64:!1,promoteLongs:!0,promoteValues:!0,promoteBuffers:!0};delete r.credentials,r.autoEncrypter&&delete r.autoEncrypter,this.connectOptions=Object.freeze(r)}connect(){if(this.s.state!==p.STATE_CLOSED)return;const e=this.options.heartbeatFrequencyMS,t=this.options.minHeartbeatFrequencyMS;this.monitorId=new T(w(this),{heartbeatFrequencyMS:e,minHeartbeatFrequencyMS:t,immediate:!0})}requestCheck(){S.has(this.s.state)||this.monitorId?.wake()}reset(){const e=this.server.description.topologyVersion;if(O(this)||null==e)return;E(this,p.STATE_CLOSING),v(this),E(this,g);const t=this.options.heartbeatFrequencyMS,n=this.options.minHeartbeatFrequencyMS;this.monitorId=new T(w(this),{heartbeatFrequencyMS:t,minHeartbeatFrequencyMS:n})}close(){O(this)||(E(this,p.STATE_CLOSING),v(this),this.emit("close"),E(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 v(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 b(e,n){if(null==n)return!1;const r=e.options.serverMonitoringMode;return r!==t.ServerMonitoringMode.poll&&(r===t.ServerMonitoringMode.stream||!e.isRunningInFaasEnv)}function w(e){return t=>{function n(){O(e)||E(e,g),t()}e.s.state!==y?(E(e,y),function(e,t){let n,r;const o=e.server.description.topologyVersion,a=b(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,d.calculateDurationInMs)(n),o,r));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 h(r){"isWritablePrimary"in r||(r.isWritablePrimary=r[c.LEGACY_HELLO_COMMAND]);const o=a&&e.rttPinger?e.rttPinger.latestRtt??(0,d.calculateDurationInMs)(n):(0,d.calculateDurationInMs)(n);e.addRttSample(o),e.emitAndLogHeartbeat(f.Server.SERVER_HEARTBEAT_SUCCEEDED,e.server.topology.s.id,r.connectionId,new m.ServerHeartbeatSucceededEvent(e.address,o,r,a)),a?(e.emitAndLogHeartbeat(f.Server.SERVER_HEARTBEAT_STARTED,e.server.topology.s.id,void 0,new m.ServerHeartbeatStartedEvent(e.address,!0)),n=(0,d.now)()):(e.rttPinger?.close(),e.rttPinger=void 0,t(void 0,r))}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)})}:{}},y=a?{socketTimeoutMS:u?u+m:0,exhaustAllowed:!0}:{socketTimeoutMS:u};return a&&null==e.rttPinger&&(e.rttPinger=new M(e)),n=(0,d.now)(),a?(r=!0,p.exhaustCommand((0,d.ns)("admin.$cmd"),f,y,((e,t)=>e?l(e):h(t)))):(r=!1,void p.command((0,d.ns)("admin.$cmd"),f,y).then(h,l))}var g;(async()=>{const t=await(0,s.makeSocket)(e.connectOptions),r=(0,s.makeConnection)(e.connectOptions,t);n=(0,d.now)();try{return await(0,s.performInitialHandshake)(r,e.connectOptions),r}catch(e){throw r.destroy(),e}})().then((r=>{if(O(e))return void r.destroy();const o=(0,d.calculateDurationInMs)(n);e.addRttSample(o),e.connection=r,e.emitAndLogHeartbeat(f.Server.SERVER_HEARTBEAT_SUCCEEDED,e.server.topology.s.id,r.hello?.connectionId,new m.ServerHeartbeatSucceededEvent(e.address,o,r.hello,b(e,r.hello?.topologyVersion))),t(void 0,r.hello)}),(t=>{e.connection=null,r=!1,l(t)}))}(e,((t,r)=>{if(t&&e.server.description.type===p.ServerType.Unknown)return n();b(e,r?.topologyVersion)&&(0,o.setTimeout)((()=>{O(e)||e.monitorId?.wake()}),0),n()}))):r.nextTick(t)}}t.Monitor=C;class M{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,d.calculateDurationInMs)(e),this.monitorId=(0,o.setTimeout)((()=>this.measureRoundTripTime()),this.monitor.options.heartbeatFrequencyMS))}measureRoundTripTime(){const e=(0,d.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 n=t.serverApi?.version||t.helloOk?"hello":c.LEGACY_HELLO_COMMAND;t.command((0,d.ns)("admin.$cmd"),{[n]:1},void 0).then((()=>this.measureAndReschedule(e)),(()=>{this.connection?.destroy(),this.connection=void 0}))}}t.RTTPinger=M;class T{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,d.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,d.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,d.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=T;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,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SetProfilingLevelOperation=t.ProfilingLevel=void 0;const r=n(75725),o=n(17562),i=n(145),s=n(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,n,o){switch(super(e,o),this.SERVER_COMMAND_RESPONSE_TYPE=r.MongoDBResponse,this.options=o,n){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=n}get commandName(){return"profile"}buildCommandDocument(e){const n=this.level;if(!a.has(n))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},58716:(e,t,n)=>{n.d(t,{A:()=>i});var r=Number.isNaN||function(e){return"number"==typeof e&&e!=e};function o(e,t){if(e.length!==t.length)return!1;for(var n=0;n<e.length;n++)if(!((o=e[n])===(i=t[n])||r(o)&&r(i)))return!1;var o,i;return!0}const i=function(e,t){var n;void 0===t&&(t=o);var r,i=[],s=!1;return function(){for(var o=[],a=0;a<arguments.length;a++)o[a]=arguments[a];return s&&n===this&&t(o,i)||(r=e.apply(this,o),s=!0,n=this,i=o),r}}},58782:(e,t,n)=>{var r=n(44775),o=r.define("Time",(function(){this.choice({utcTime:this.utctime(),generalTime:this.gentime()})})),i=r.define("AttributeTypeValue",(function(){this.seq().obj(this.key("type").objid(),this.key("value").any())})),s=r.define("AlgorithmIdentifier",(function(){this.seq().obj(this.key("algorithm").objid(),this.key("parameters").optional(),this.key("curve").objid().optional())})),a=r.define("SubjectPublicKeyInfo",(function(){this.seq().obj(this.key("algorithm").use(s),this.key("subjectPublicKey").bitstr())})),c=r.define("RelativeDistinguishedName",(function(){this.setof(i)})),u=r.define("RDNSequence",(function(){this.seqof(c)})),l=r.define("Name",(function(){this.choice({rdnSequence:this.use(u)})})),h=r.define("Validity",(function(){this.seq().obj(this.key("notBefore").use(o),this.key("notAfter").use(o))})),d=r.define("Extension",(function(){this.seq().obj(this.key("extnID").objid(),this.key("critical").bool().def(!1),this.key("extnValue").octstr())})),p=r.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(h),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(d).optional())})),m=r.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,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.loadAWSCredentials=async function(e,t){const n=new r.AWSSDKCredentialProvider(t),{SecretAccessKey:o="",AccessKeyId:i="",Token:s}=await n.getCredentials(),a={secretAccessKey:o,accessKeyId:i};return null!=s&&(a.sessionToken=s),{...e,aws:a}};const r=n(19043)},59942:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.convertInternalToMongodb=t.InternalTypeToBsonTypeMap=void 0;const r=n(72506);t.InternalTypeToBsonTypeMap={Double:"double",Number:"double",String:"string",Document:"object",Array:"array",Binary:"binData",Undefined:"undefined",ObjectId:"objectId",Boolean:"bool",Date:"date",Null:"null",RegExp:"regex",BSONRegExp:"regex",DBRef:"dbPointer",BSONSymbol:"symbol",Symbol:"symbol",Code:"javascript",CodeWScope:"javascriptWithScope",Int32:"int",Timestamp:"timestamp",Long:"long",Decimal128:"decimal",MinKey:"minKey",MaxKey:"maxKey"};const o=e=>{const n=t.InternalTypeToBsonTypeMap[e];if(!n)throw new Error(`Encountered unknown type: ${e}`);return n};async function i(e,t){var n;await(0,r.allowAbort)(t);const i={bsonType:o(e.bsonType)};if("Array"===e.bsonType){const t=await s(e.types);(!t.bsonType||(null===(n=t.bsonType)||void 0===n?void 0:n.length)>0)&&(i.items=t)}else"Document"===e.bsonType&&Object.assign(i,await a(e.fields,t));return i}async function s(e,t){await(0,r.allowAbort)(t);const n=e.filter((e=>"undefined"!==e.bsonType.toLowerCase()));if(1===n.length)return i(n[0],t);const o=await Promise.all(n.map((e=>i(e,t))));return function(e){return e.every((e=>!!e.bsonType&&1===Object.keys(e).length))}(o)?{bsonType:o.map((({bsonType:e})=>e))}:{anyOf:o}}async function a(e,t){const n=[],r={};for(const o of e)1===o.probability&&n.push(o.name),r[o.name]=await s(o.types,t);return{properties:r,...n.length>0?{required:n}:{}}}t.convertInternalToMongodb=async function(e,t={}){const{required:n,properties:r}=await a(e.fields,t.signal);return{bsonType:"object",...void 0===n?{}:{required:n},properties:r}}},60040:(e,t,n)=>{n.d(t,{Ay:()=>o,X6:()=>i});var r=n(9651);const o=r.default,i=r.ParseMode;r.parse},60313:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toJSString=s,t.stringify=function(e){return s(e,1)?.replace(/ ?\n ? ?/g,"").replace(/ {2,}/g," ")};const r=n(17230),o=new Map([["[object Array]","Array"],["[object Object]","Object"],["[object String]","String"],["[object Date]","Date"],["[object Number]","Number"],["[object Function]","Function"],["[object RegExp]","RegExp"],["[object Boolean]","Boolean"],["[object Null]","Null"],["[object Undefined]","Undefined"]]);const i={Code:function(e){return e.scope?`Code('${e.code}',${JSON.stringify(e.scope)})`:`Code('${e.code}')`},ObjectID:function(e){return`ObjectId('${e.toString("hex")}')`},ObjectId:function(e){return`ObjectId('${e.toString("hex")}')`},Binary:function(e){const t=e.sub_type;if(4===t&&16===e.buffer.length){let t="";try{t=e.toUUID().toString()}catch{t=e.toString("hex")}return`UUID('${t}')`}return`BinData(${t.toString(10)}, '${e.toString("base64")}')`},DBRef:function(e){return e.db?`DBRef('${e.collection}', '${e.oid.toString()}', '${e.db}')`:`DBRef('${e.collection}', '${e.oid.toString()}')`},Timestamp:function(e){return`Timestamp({ t: ${e.high}, i: ${e.low} })`},Long:function(e){return`NumberLong('${e.toString()}')`},Decimal128:function(e){return`NumberDecimal('${e.toString()}')`},Double:function(e){return`Double('${e.toString()}')`},Int32:function(e){return`NumberInt('${e.toString()}')`},MaxKey:function(){return"MaxKey()"},MinKey:function(){return"MinKey()"},Date:function(e){return i.ISODate(e)},ISODate:function(e){try{return`ISODate('${e.toISOString()}')`}catch(t){return`ISODate('${e.toString()}')`}},RegExp:function(e){let t="",n=!1;return e.global&&(n=!0,t+="g"),e.ignoreCase&&(n=!0,t+="i"),e.multiline&&(n=!0,t+="m"),`RegExp(${JSON.stringify(e.source)}${n?`, '${t}'`:""})`},BSONRegExp:function(e){const t=e.options&&e.options?.length>0;let n="RegExp";try{RegExp(e.pattern,e.options||void 0)}catch{n="BSONRegExp"}return`${n}(${JSON.stringify(e.pattern)}${t?`, '${e.options}'`:""})`}};function s(e,t=2){return(0,r.stringify)(e,(function(e,t,n){const r=function(e){const t=function(e){return o.get(Object.prototype.toString.call(e))}(e),n="Object"===t&&e._bsontype;return{type:n||t,isBSON:!!n}}(e),s=i[r.type];return s?s(e):n(e)}),t)}},60620:(e,t,n)=>{n.d(t,{Db:()=>i,JV:()=>u,M8:()=>l,Sy:()=>o,kA:()=>c,mu:()=>s,qY:()=>a});var r=n(29009);r.getBuildEnv;const o=r.getDataLake,i=(r.getGenuineMongoDB,r.identifyServerName),s=r.isAtlas,a=r.isAtlasStream,c=(r.isDigitalOcean,r.isEnterprise),u=r.isLocalAtlas,l=r.isLocalhost},61066:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CursorTimeoutContext=t.AbstractCursor=t.CursorTimeoutMode=t.CURSOR_FLAGS=void 0;const r=n(93874),o=n(75080),i=n(17562),s=n(4642),a=n(96357),c=n(68923),u=n(1755),l=n(28541),h=n(13700),d=n(31790),p=n(14019),m=n(7799),f=n(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 y extends s.TypedEventEmitter{constructor(e,n,r={}){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=n,this.cursorId=null,this.initialized=!1,this.isClosed=!1,this.isKilled=!1,this.cursorOptions={readPreference:r.readPreference&&r.readPreference instanceof h.ReadPreference?r.readPreference:h.ReadPreference.primary,...(0,o.pluckBSONSerializeOptions)(r),timeoutMS:r?.timeoutContext?.csotEnabled()?r.timeoutContext.timeoutMS:r.timeoutMS,tailable:r.tailable,awaitData:r.awaitData},null!=this.cursorOptions.timeoutMS)if(null==r.timeoutMode)if(r.tailable){if(r.awaitData&&null!=r.maxAwaitTimeMS&&r.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(r.tailable&&r.timeoutMode===t.CursorTimeoutMode.LIFETIME)throw new i.MongoInvalidArgumentError("Cannot set tailable cursor's timeoutMode to LIFETIME");this.cursorOptions.timeoutMode=r.timeoutMode}else if(null!=r.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(r);s&&(this.cursorOptions.readConcern=s),"number"==typeof r.batchSize&&(this.cursorOptions.batchSize=r.batchSize),void 0!==r.comment&&(this.cursorOptions.comment=r.comment),"number"==typeof r.maxTimeMS&&(this.cursorOptions.maxTimeMS=r.maxTimeMS),"number"==typeof r.maxAwaitTimeMS&&(this.cursorOptions.maxAwaitTimeMS=r.maxAwaitTimeMS),this.cursorSession=r.session??null,this.deserializationOptions={...this.cursorOptions,validation:{utf8:!1!==r?.enableUtf8Validation}},this.timeoutContext=r.timeoutContext,this.signal=r.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=[],n=Math.min(e??this.documents?.length??0,this.documents?.length??0);for(let e=0;e<n;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 E(this),n=(0,f.addAbortListener)(this.signal,(function(){t.destroy(this.reason)}));if(t.once("end",(()=>{n?.[f.kDispose]()})),e?.transform){const n=e.transform,o=t.pipe(new r.Transform({objectMode:!0,highWaterMark:1,transform(e,t,r){try{r(void 0,n(e))}catch(e){r(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 n=this.readBufferedDocuments();if(null!=this.transform)for(const t of n)e.push(await this.transformDocument(t));else e.push(...n)}return e}addCursorFlag(e,n){if(this.throwIfInitialized(),!t.CURSOR_FLAGS.includes(e))throw new i.MongoInvalidArgumentError(`Flag ${e} is not one of ${t.CURSOR_FLAGS}`);if("boolean"!=typeof n)throw new i.MongoInvalidArgumentError(`Flag ${e} must be a boolean value`);return this.cursorOptions[e]=n,this}map(e){this.throwIfInitialized();const t=this.transform;return this.transform=t?n=>e(t(n)):e,this}withReadPreference(e){if(this.throwIfInitialized(),e instanceof h.ReadPreference)this.cursorOptions.readPreference=e;else{if("string"!=typeof e)throw new i.MongoInvalidArgumentError(`Invalid read preference: ${e}`);this.cursorOptions.readPreference=h.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},n=new c.GetMoreOperation(this.cursorNamespace,this.cursorId,this.selectedServer,t);return await(0,a.executeOperation)(this.cursorClient,n,this.timeoutContext)}async cursorInit(){null!=this.cursorOptions.timeoutMS&&(this.timeoutContext??=new S(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 n=()=>null!=e?(this.timeoutContext?.clear(),new S(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}),n())}}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=y,y.CLOSE="close";class E extends r.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,d.configureResourceManagement)(y.prototype);class S 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 S(this.timeoutContext.refreshed(),this.owner)}addMaxTimeMSToCommand(e,t){this.timeoutContext.addMaxTimeMSToCommand(e,t)}getSocketTimeoutMS(){return this.timeoutContext.getSocketTimeoutMS()}}t.CursorTimeoutContext=S},61283:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.convertInternalToStandard=t.RELAXED_EJSON_DEFINITIONS=t.InternalTypeToStandardTypeMap=void 0;const r=n(72506);t.InternalTypeToStandardTypeMap={Double:{$ref:"#/$defs/Double"},Number:{$ref:"#/$defs/Double"},String:{type:"string"},Document:{type:"object"},Array:{type:"array"},Binary:{$ref:"#/$defs/Binary"},Undefined:{$ref:"#/$defs/Undefined"},ObjectId:{$ref:"#/$defs/ObjectId"},Boolean:{type:"boolean"},Date:{$ref:"#/$defs/Date"},Null:{type:"null"},RegExp:{$ref:"#/$defs/RegExp"},BSONRegExp:{$ref:"#/$defs/RegExp"},DBRef:{$ref:"#/$defs/DBRef"},DBPointer:{$ref:"#/$defs/DBPointer"},BSONSymbol:{$ref:"#/$defs/BSONSymbol"},Code:{$ref:"#/$defs/Code"},CodeWScope:{$ref:"#/$defs/CodeWScope"},Int32:{type:"integer"},Timestamp:{$ref:"#/$defs/Timestamp"},Long:{type:"integer"},Decimal128:{$ref:"#/$defs/Decimal128"},MinKey:{$ref:"#/$defs/MinKey"},MaxKey:{$ref:"#/$defs/MaxKey"}},t.RELAXED_EJSON_DEFINITIONS={ObjectId:{type:"object",properties:{$oid:{type:"string",pattern:"^[0-9a-fA-F]{24}$"}},required:["$oid"],additionalProperties:!1},BSONSymbol:{type:"object",properties:{$symbol:{type:"string"}},required:["$symbol"],additionalProperties:!1},Double:{oneOf:[{type:"number"},{type:"object",properties:{$numberDouble:{enum:["Infinity","-Infinity","NaN"]}}}]},Decimal128:{type:"object",properties:{$numberDecimal:{type:"string"}},required:["$numberDecimal"],additionalProperties:!1},Binary:{type:"object",properties:{$binary:{type:"object",properties:{base64:{type:"string"},subType:{type:"string",pattern:"^[0-9a-fA-F]{1,2}$"}},required:["base64","subType"],additionalProperties:!1}},required:["$binary"],additionalProperties:!1},Code:{type:"object",properties:{$code:{type:"string"}},required:["$code"],additionalProperties:!1},CodeWScope:{type:"object",properties:{$code:{type:"string"},$scope:{type:"object"}},required:["$code","$scope"],additionalProperties:!1},Timestamp:{type:"object",properties:{$timestamp:{type:"object",properties:{t:{type:"integer",minimum:0},i:{type:"integer",minimum:0}},required:["t","i"],additionalProperties:!1}},required:["$timestamp"],additionalProperties:!1},RegExp:{type:"object",properties:{$regularExpression:{type:"object",properties:{pattern:{type:"string"},options:{type:"string",pattern:"^[gimuy]*$"}},required:["pattern"],additionalProperties:!1}},required:["$regularExpression"],additionalProperties:!1},DBPointer:{type:"object",properties:{$dbPointer:{type:"object",properties:{$ref:{type:"string"},$id:{$ref:"#/$defs/ObjectId"}},required:["$ref","$id"],additionalProperties:!1}},required:["$dbPointer"],additionalProperties:!1},Date:{type:"object",properties:{$date:{type:"string",format:"date-time"}},required:["$date"],additionalProperties:!1},DBRef:{type:"object",properties:{$ref:{type:"string"},$id:{},$db:{type:"string"}},required:["$ref","$id"],additionalProperties:!0},MinKey:{type:"object",properties:{$minKey:{type:"integer",const:1}},required:["$minKey"],additionalProperties:!1},MaxKey:{type:"object",properties:{$maxKey:{type:"integer",const:1}},required:["$maxKey"],additionalProperties:!1},Undefined:{type:"object",properties:{$undefined:{type:"boolean",const:!0}},required:["$undefined"],additionalProperties:!1}};t.convertInternalToStandard=function(e,n={}){return function(){const e=new Set;function n(){const n=Object.fromEntries(Object.entries(t.RELAXED_EJSON_DEFINITIONS).filter((([t])=>e.has(t))));return Object.freeze(n)}async function o(n,o){await(0,r.allowAbort)(o);const a=function(e){const n=t.InternalTypeToStandardTypeMap[e];if(!n)throw new Error(`Encountered unknown type: ${e}`);return{...n}}(n.bsonType);var c;switch(a.$ref&&(c=a.$ref,e.add(c.split("/")[2])),n.bsonType){case"Array":a.items=await i(n.types,o);break;case"Document":Object.assign(a,await s(n.fields,o))}return a}async function i(e,t){await(0,r.allowAbort)(t);const n=e.filter((e=>"undefined"!==e.bsonType.toLowerCase()));if(1===n.length)return o(n[0],t);const i=await Promise.all(n.map((e=>o(e,t))));return function(e){return e.every((e=>!!e.type&&1===Object.keys(e).length))}(i)?{type:i.map((({type:e})=>e))}:{anyOf:i}}async function s(e,t){const n=[],r={};for(const o of e)1===o.probability&&n.push(o.name),r[o.name]=await i(o.types,t);return{required:n,properties:r}}return async function(e,t={}){const{required:r,properties:o}=await s(e.fields,t.signal);return{$schema:"https://json-schema.org/draft/2020-12/schema",type:"object",required:r,properties:o,$defs:n()}}}()(e,n)}},61428:(e,t,n)=>{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 r.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 r=n(17562),o=n(13700),i=n(89167),s=n(97194)},61635:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.FindOneAndUpdateOperation=t.FindOneAndReplaceOperation=t.FindOneAndDeleteOperation=t.FindAndModifyOperation=t.ReturnDocument=void 0;const r=n(75725),o=n(17562),i=n(13700),s=n(30770),a=n(145),c=n(78130),u=n(35394);function l(e,n){return e.new=n.returnDocument===t.ReturnDocument.AFTER,e.upsert=!0===n.upsert,!0===n.bypassDocumentValidation&&(e.bypassDocumentValidation=n.bypassDocumentValidation),e}t.ReturnDocument=Object.freeze({BEFORE:"before",AFTER:"after"});class h extends c.CommandOperation{constructor(e,t,n){super(e,n),this.SERVER_COMMAND_RESPONSE_TYPE=r.MongoDBResponse,this.options=n,this.readPreference=i.ReadPreference.primary,this.collection=e,this.query=t}get commandName(){return"findAndModify"}buildCommandDocument(e,t){const n=this.options,r={findAndModify:this.collection.collectionName,query:this.query,remove:!1,new:!1,upsert:!1};n.includeResultMetadata??=!1;const i=(0,s.formatSort)(n.sort);if(i&&(r.sort=i),n.projection&&(r.fields=n.projection),n.maxTimeMS&&(r.maxTimeMS=n.maxTimeMS),n.writeConcern&&(r.writeConcern=n.writeConcern),n.let&&(r.let=n.let),void 0!==n.comment&&(r.comment=n.comment),(0,a.decorateWithCollation)(r,this.collection,n),n.hint){if(0===this.writeConcern?.w)throw new o.MongoCompatibilityError("The current topology does not support a hint on findAndModify commands");r.hint=n.hint}return r}handleOk(e){const t=super.handleOk(e);return this.options.includeResultMetadata?t:t.value??null}}t.FindAndModifyOperation=h,t.FindOneAndDeleteOperation=class extends h{constructor(e,t,n){if(null==t||"object"!=typeof t)throw new o.MongoInvalidArgumentError('Argument "filter" must be an object');super(e,t,n)}buildCommandDocument(e,t){const n=super.buildCommandDocument(e,t);return n.remove=!0,n}},t.FindOneAndReplaceOperation=class extends h{constructor(e,t,n,r){if(null==t||"object"!=typeof t)throw new o.MongoInvalidArgumentError('Argument "filter" must be an object');if(null==n||"object"!=typeof n)throw new o.MongoInvalidArgumentError('Argument "replacement" must be an object');if((0,a.hasAtomicOperators)(n))throw new o.MongoInvalidArgumentError("Replacement document must not contain atomic operators");super(e,t,r),this.replacement=n}buildCommandDocument(e,t){const n=super.buildCommandDocument(e,t);return n.update=this.replacement,l(n,this.options),n}},t.FindOneAndUpdateOperation=class extends h{constructor(e,t,n,r){if(null==t||"object"!=typeof t)throw new o.MongoInvalidArgumentError('Argument "filter" must be an object');if(null==n||"object"!=typeof n)throw new o.MongoInvalidArgumentError('Argument "update" must be an object');if(!(0,a.hasAtomicOperators)(n,r))throw new o.MongoInvalidArgumentError("Update document requires atomic operators");super(e,t,r),this.update=n,this.options=r}buildCommandDocument(e,t){const n=super.buildCommandDocument(e,t);return n.update=this.update,l(n,this.options),this.options.arrayFilters&&(n.arrayFilters=this.options.arrayFilters),n}},(0,u.defineAspects)(h,[u.Aspect.WRITE_OPERATION,u.Aspect.RETRYABLE,u.Aspect.EXPLAINABLE])},61861:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.RenameOperation=void 0;const r=n(75725),o=n(19498),i=n(145),s=n(78130),a=n(35394);class c extends s.CommandOperation{constructor(e,t,n){super(e,n),this.SERVER_COMMAND_RESPONSE_TYPE=r.MongoDBResponse,this.collection=e,this.newName=t,this.options=n,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,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AggregateOperation=t.DB_AGGREGATE_COLLECTION=void 0;const r=n(75725),o=n(17562),i=n(145),s=n(40012),a=n(78130),c=n(35394);t.DB_AGGREGATE_COLLECTION=1;class u extends a.CommandOperation{constructor(e,n,i){if(super(void 0,{...i,dbName:e.db}),this.SERVER_COMMAND_RESPONSE_TYPE=r.CursorResponse,this.options={...i},this.target=e.collection||t.DB_AGGREGATE_COLLECTION,this.pipeline=n,this.hasWriteStage=!1,"string"==typeof i?.out)this.pipeline=this.pipeline.concat({$out:i.out}),this.hasWriteStage=!0;else if(n.length>0){const e=n[n.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?r.ExplainedCursorResponse:r.CursorResponse}get commandName(){return"aggregate"}get canRetryRead(){return!this.hasWriteStage}addToPipeline(e){this.pipeline.push(e)}buildCommandDocument(e){const t=this.options,n=(0,i.maxWireVersion)(e),r={aggregate:this.target,pipeline:this.pipeline};return this.hasWriteStage&&n<8&&(this.readConcern=void 0),this.hasWriteStage&&this.writeConcern&&s.WriteConcern.apply(r,this.writeConcern),!0===t.bypassDocumentValidation&&(r.bypassDocumentValidation=t.bypassDocumentValidation),"boolean"==typeof t.allowDiskUse&&(r.allowDiskUse=t.allowDiskUse),t.hint&&(r.hint=t.hint),t.let&&(r.let=t.let),void 0!==t.comment&&(r.comment=t.comment),r.cursor=t.cursor||{},t.batchSize&&!this.hasWriteStage&&(r.cursor.batchSize=t.batchSize),r}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,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.finishCommandDocument=function(e,t){return null!=t?{saslContinue:1,conversationId:t,payload:new r.Binary(r.BSON.serialize({jwt:e}))}:{saslStart:1,mechanism:o.AuthMechanism.MONGODB_OIDC,payload:new r.Binary(r.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 r.Binary(r.BSON.serialize(t))}};const r=n(75080),o=n(93065)},63257:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MongoDBOIDC=t.OIDC_WORKFLOWS=t.OIDC_VERSION=void 0;const r=n(17562),o=n(31057),i=n(88822),s=n(73619),a=n(9284),c=n(80890),u=n(8294),l=n(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 h extends o.AuthProvider{constructor(e){if(super(),!e)throw new r.MongoInvalidArgumentError("No workflow provided to the OIDC auth provider.");this.workflow=e}async auth(e){const{connection:t,reauthenticating:n,response:r}=e;if(r?.speculativeAuthenticate?.done&&!n)return;const o=d(e);n?await this.workflow.reauthenticate(t,o):await this.workflow.execute(t,o,r)}async prepare(e,t){const{connection:n}=t,r=d(t);return{...e,...await this.workflow.speculativeAuth(n,r)}}}function d(e){const{credentials:t}=e;if(!t)throw new r.MongoMissingCredentialsError("AuthContext must provide credentials.");return t}t.MongoDBOIDC=h},64125:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.RemoveUserOperation=void 0;const r=n(75725),o=n(78130),i=n(35394);class s extends o.CommandOperation{constructor(e,t,n){super(e,n),this.SERVER_COMMAND_RESPONSE_TYPE=r.MongoDBResponse,this.options=n,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,n)=>{var r=n(67787).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.uncompressibleCommands=t.Compressor=void 0,t.compress=async function(e,t){const n={};switch(e.agreedCompressor){case"snappy":return f??=g(),await f.compress(t);case"zstd":if(E(),"kModuleError"in m)throw m.kModuleError;return await m.compress(t,h);case"zlib":return e.zlibCompressionLevel&&(n.level=e.zlibCompressionLevel),await p(t,n);default:throw new c.MongoInvalidArgumentError(`Unknown compressor ${e.agreedCompressor} failed to compress`)}},t.decompress=y,t.compressCommand=async function(e,t){const n="none"!==t.agreedCompressor&&u.OpCompressedRequest.canCompress(e)?new u.OpCompressedRequest(e,{agreedCompressor:t.agreedCompressor??"none",zlibCompressionLevel:t.zlibCompressionLevel??0}):e,o=await n.toBin();return r.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 n=t.opCode===l.OP_MSG?u.OpMsgResponse:u.OpReply,r=e.subarray(S);return new n(e,t,r)}const n={...t,fromCompressed:!0,opCode:e.readInt32LE(S),length:e.readInt32LE(S+4)},r=e[S+8],o=e.slice(S+9),i=n.opCode===l.OP_MSG?u.OpMsgResponse:u.OpReply,s=await y(r,o);if(s.length!==n.length)throw new c.MongoDecompressionError("Message body and message header must be the same length");return new i(e,n,s)};const o=n(98437),i=n(25900),s=n(91869),a=n(8500),c=n(17562),u=n(15620),l=n(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 h=3,d=(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 y(e,n){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(n,{asBuffer:!0});case t.Compressor.zstd:if(E(),"kModuleError"in m)throw m.kModuleError;return await m.decompress(n);case t.Compressor.zlib:return await d(n);default:return n}}function E(){m||(m=(0,a.getZstdLibrary)())}const S=16},64647:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.X509=void 0;const r=n(17562),o=n(145),i=n(31057);class s extends i.AuthProvider{async prepare(e,t){const{credentials:n}=t;if(!n)throw new r.MongoMissingCredentialsError("AuthContext must provide credentials.");return{...e,speculativeAuthenticate:a(n)}}async auth(e){const t=e.connection,n=e.credentials;if(!n)throw new r.MongoMissingCredentialsError("AuthContext must provide credentials.");const i=e.response;i?.speculativeAuthenticate||await t.command((0,o.ns)("$external.$cmd"),a(n),void 0)}}function a(e){const t={authenticate:1,mechanism:"MONGODB-X509"};return e.username&&(t.user=e.username),t}t.X509=s},65031:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CommaAndColonSeparatedRecord=t.ConnectionString=t.redactConnectionString=void 0;const r=n(9606),o=n(53162);Object.defineProperty(t,"redactConnectionString",{enumerable:!0,get:function(){return o.redactConnectionString}});const i="__this_is_a_placeholder__",s=/^(?<protocol>[^/]+):\/\/(?:(?<username>[^:@]*)(?::(?<password>[^@]*))?@)?(?<hosts>(?!:)[^/?@]*)(?<rest>.*)/;class a extends Map{delete(e){return super.delete(this._normalizeKey(e))}get(e){return super.get(this._normalizeKey(e))}has(e){return super.has(this._normalizeKey(e))}set(e,t){return super.set(this._normalizeKey(e),t)}_normalizeKey(e){e=`${e}`;for(const t of this.keys())if(t.toLowerCase()===e.toLowerCase()){e=t;break}return e}}class c extends r.URL{}class u extends Error{get name(){return"MongoParseError"}}class l extends c{constructor(e,t={}){var n;const{looseValidation:r}=t;if(!r&&!(o=e).startsWith("mongodb://")&&!o.startsWith("mongodb+srv://"))throw new u('Invalid scheme, expected connection string to start with "mongodb://" or "mongodb+srv://"');var o;const c=e.match(s);if(!c)throw new u(`Invalid connection string "${e}"`);const{protocol:h,username:d,password:p,hosts:m,rest:f}=null!==(n=c.groups)&&void 0!==n?n:{};if(!r){if(!h||!m)throw new u(`Protocol and host list are required in "${e}"`);try{decodeURIComponent(null!=d?d:""),decodeURIComponent(null!=p?p:"")}catch(e){throw new u(e.message)}const t=/[:/?#[\]@]/gi;if(null==d?void 0:d.match(t))throw new u(`Username contains unescaped characters ${d}`);if(!d||!p){const t=e.replace(`${h}://`,"");if(t.startsWith("@")||t.startsWith(":"))throw new u("URI contained empty userinfo section")}if(null==p?void 0:p.match(t))throw new u("Password contains unescaped characters")}let g="";"string"==typeof d&&(g+=d),"string"==typeof p&&(g+=`:${p}`),g&&(g+="@");try{super(`${h.toLowerCase()}://${g}${i}${f}`)}catch(n){throw r&&new l(e,{...t,looseValidation:!1}),"string"==typeof n.message&&(n.message=n.message.replace(i,m)),n}if(this._hosts=m.split(","),!r){if(this.isSRV&&1!==this.hosts.length)throw new u("mongodb+srv URI cannot have multiple service names");if(this.isSRV&&this.hosts.some((e=>e.includes(":"))))throw new u("mongodb+srv URI cannot have port number")}var y;this.pathname||(this.pathname="/"),Object.setPrototypeOf(this.searchParams,(y=this.searchParams.constructor,class extends y{append(e,t){return super.append(this._normalizeKey(e),t)}delete(e){return super.delete(this._normalizeKey(e))}get(e){return super.get(this._normalizeKey(e))}getAll(e){return super.getAll(this._normalizeKey(e))}has(e){return super.has(this._normalizeKey(e))}set(e,t){return super.set(this._normalizeKey(e),t)}keys(){return super.keys()}values(){return super.values()}entries(){return super.entries()}[Symbol.iterator](){return super[Symbol.iterator]()}_normalizeKey(e){return a.prototype._normalizeKey.call(this,e)}}).prototype)}get host(){return i}set host(e){throw new Error("No single host for connection string")}get hostname(){return i}set hostname(e){throw new Error("No single host for connection string")}get port(){return""}set port(e){throw new Error("No single host for connection string")}get href(){return this.toString()}set href(e){throw new Error("Cannot set href for connection strings")}get isSRV(){return this.protocol.includes("srv")}get hosts(){return this._hosts}set hosts(e){this._hosts=e}toString(){return super.toString().replace(i,this.hosts.join(","))}clone(){return new l(this.toString(),{looseValidation:!0})}redact(e){return(0,o.redactValidConnectionString)(this,e)}typedSearchParams(){return this.searchParams}[Symbol.for("nodejs.util.inspect.custom")](){const{href:e,origin:t,protocol:n,username:r,password:o,hosts:i,pathname:s,search:a,searchParams:c,hash:u}=this;return{href:e,origin:t,protocol:n,username:r,password:o,hosts:i,pathname:s,search:a,searchParams:c,hash:u}}}t.ConnectionString=l,t.CommaAndColonSeparatedRecord=class extends a{constructor(e){super();for(const t of(null!=e?e:"").split(",")){if(!t)continue;const e=t.indexOf(":");-1===e?this.set(t,""):this.set(t.slice(0,e),t.slice(e+1))}}toString(){return[...this].map((e=>e.join(":"))).join(",")}},t.default=l},66596:(e,t,n)=>{n.d(t,{CW:()=>r,lV:()=>o,cx:()=>i,JQ:()=>s,BM:()=>a,ok:()=>c,ol:()=>u,HP:()=>l,Ee:()=>h,On:()=>d,es:()=>p,Ny:()=>m});const r=f(/[A-Za-z]/),o=f(/[\dA-Za-z]/),i=f(/[#-'*+\--9=?A-Z^-~]/);function s(e){return null!==e&&(e<32||127===e)}const a=f(/\d/),c=f(/[\dA-Fa-f]/),u=f(/[!-/:-@[-`{-~]/);function l(e){return null!==e&&e<-2}function h(e){return null!==e&&(e<0||32===e)}function d(e){return-2===e||-1===e||32===e}const p=f(/[!-\/:-@\[-`\{-~\xA1\xA7\xAB\xB6\xB7\xBB\xBF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061D-\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u09FD\u0A76\u0AF0\u0C77\u0C84\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166E\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1B7D\u1B7E\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2010-\u2027\u2030-\u2043\u2045-\u2051\u2053-\u205E\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E4F\u2E52-\u2E5D\u3001-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]/),m=f(/\s/);function f(e){return function(t){return null!==t&&e.test(String.fromCharCode(t))}}},67399:(e,t,n)=>{n.d(t,{Cv:()=>i,D0:()=>s,Dy:()=>o});var r=n(33168);r.default,r.SchemaAnalyzer;const o=r.analyzeDocuments,i=(r.getSchemaPaths,r.getSimplifiedSchema),s=r.parseSchema;r.schemaStats,r.toTypescriptTypeDefinition},68526:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AggregationCursor=void 0;const r=n(17562),o=n(36411),i=n(62016),s=n(96357),a=n(145),c=n(61066),u=n(36649);class l extends u.ExplainableCursor{constructor(e,t,n=[],o={}){super(e,t,o),this.pipeline=n,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 r.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 r.MongoAPIError("timeoutMS cannot be used with explain when explain is specified in aggregateOptions")}const n=new i.AggregateOperation(this.namespace,this.pipeline,t),a=await(0,s.executeOperation)(this.client,n,this.timeoutContext);return{server:n.server,session:e,response:a}}async explain(e,t){const{explain:n,timeout:r}=this.resolveExplainTimeoutOptions(e,t);return(await(0,s.executeOperation)(this.client,new i.AggregateOperation(this.namespace,this.pipeline,{...this.aggregateOptions,...this.cursorOptions,...r,explain:n??!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 r.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,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OnDemandDocument=void 0;const r=n(75080);class o{constructor(e,t=0,n=!1,o){this.cache=Object.create(null),this.indexFound=Object.create(null),this.bson=e,this.offset=t,this.isArray=n,this.elements=o??(0,r.parseToElementsToArray)(this.bson,t)}isElementName(e,t){const n=t[2],r=t[1];if(e.length!==n)return!1;const o=r+n;for(let t=r,n=0;n<e.length&&t<o;n++,t++)if(this.bson[t]!==e.charCodeAt(n))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 n=this.elements[t];if(!(t in this.indexFound)&&this.isElementName(e,n)){const r={element:n,value:void 0};return this.cache[e]=r,this.indexFound[t]=!0,r}}return this.cache[e]=!1,null}toJSValue(e,t){const n=e[0],i=e[3],s=e[4];if(t!==n)return null;switch(t){case r.BSONType.null:case r.BSONType.undefined:return null;case r.BSONType.double:return(0,r.getFloat64LE)(this.bson,i);case r.BSONType.int:return(0,r.getInt32LE)(this.bson,i);case r.BSONType.long:return(0,r.getBigInt64LE)(this.bson,i);case r.BSONType.bool:return Boolean(this.bson[i]);case r.BSONType.objectId:return new r.ObjectId(this.bson.subarray(i,i+12));case r.BSONType.timestamp:return new r.Timestamp((0,r.getBigInt64LE)(this.bson,i));case r.BSONType.string:return(0,r.toUTF8)(this.bson,i+4,i+s-1,!1);case r.BSONType.binData:{const e=(0,r.getInt32LE)(this.bson,i),t=this.bson[i+4];if(2===t){const t=(0,r.getInt32LE)(this.bson,i+1+4);if(t<0)throw new r.BSONError("Negative binary type element size found for subtype 0x02");if(t>e-4)throw new r.BSONError("Binary type with subtype 0x02 contains too long binary size");if(t<e-4)throw new r.BSONError("Binary type with subtype 0x02 contains too short binary size");return new r.Binary(this.bson.subarray(i+1+4+4,i+1+4+4+t),2)}return new r.Binary(this.bson.subarray(i+1+4,i+1+4+e),t)}case r.BSONType.date:return new Date(Number((0,r.getBigInt64LE)(this.bson,i)));case r.BSONType.object:return new o(this.bson,i);case r.BSONType.array:return new o(this.bson,i,!0);default:throw new r.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,n){const o=this.getElement(e);if(null==o){if(!0===n)throw new r.BSONError(`BSON element "${e}" is missing`);return null}if(null==o.value){const i=this.toJSValue(o.element,t);if(null==i){if(!0===n)throw new r.BSONError(`BSON element "${e}" is missing`);return null}o.value=i}return o.value}getNumber(e,t){const n=this.get(e,r.BSONType.bool),o=null==n?null:n?1:0,i=this.get(e,r.BSONType.long),s=null==i?null:Number(i),a=o??s??this.get(e,r.BSONType.int)??this.get(e,r.BSONType.double);if(!0===t&&null==a)throw new r.BSONError(`BSON element "${e}" is missing`);return a}toObject(e){return(0,r.deserialize)(this.bson,{...e,index:this.offset,allowObjectSmallerThanBufferSize:!0})}toBytes(){const e=(0,r.getInt32LE)(this.bson,this.offset);return this.bson.subarray(this.offset,this.offset+e)}}t.OnDemandDocument=o},68838:function(e,t){var n;(function(){var r,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,n,r){var o,i,s,a,c=e.toString().split("."),u=t-(r||0);return o=2===c.length?Math.min(Math.max(c[1].length,u),t):u,a=(n(e*(s=Math.pow(10,o)))/s).toFixed(o),r>t-o&&(i=new RegExp("\\.?0{1,"+(r-(t-o))+"}$"),a=a.replace(i,"")),a}function l(e,t,n){var r,i,a,c,l=!1,h=!1,d=!1,p="",m=!1,f=!1,g=!1,y=!1,E=!1,S="",O=!1;return null===e&&(e=0),r=Math.abs(e),t.indexOf("(")>-1?(l=!0,t=t.slice(1,-1)):t.indexOf("+")>-1&&(h=!0,t=t.replace(/\+/g,"")),t.indexOf("a")>-1&&(m=t.indexOf("aK")>=0,f=t.indexOf("aM")>=0,g=t.indexOf("aB")>=0,y=t.indexOf("aT")>=0,E=m||f||g||y,t.indexOf(" a")>-1&&(p=" "),t=t.replace(new RegExp(p+"a[KMBT]?"),""),r>=Math.pow(10,12)&&!E||y?(p+=o[s.currentLanguage].abbreviations.trillion,e/=Math.pow(10,12)):r<Math.pow(10,12)&&r>=Math.pow(10,9)&&!E||g?(p+=o[s.currentLanguage].abbreviations.billion,e/=Math.pow(10,9)):r<Math.pow(10,9)&&r>=Math.pow(10,6)&&!E||f?(p+=o[s.currentLanguage].abbreviations.million,e/=Math.pow(10,6)):(r<Math.pow(10,6)&&r>=Math.pow(10,3)&&!E||m)&&(p+=o[s.currentLanguage].abbreviations.thousand,e/=Math.pow(10,3))),t.indexOf("[.]")>-1&&(d=!0,t=t.replace("[.]",".")),i=e.toString().split(".")[0],a=t.split(".")[1],c=t.indexOf(","),a?(i=(S=a.indexOf("[")>-1?u(e,(a=(a=a.replace("]","")).split("["))[0].length+a[1].length,n,a[1].length):u(e,a.length,n)).split(".")[0],S=S.indexOf(".")>-1?o[s.currentLanguage].delimiters.decimal+S.split(".")[1]:"",d&&0===Number(S.slice(1))&&(S="")):i=u(e,null,n),i.indexOf("-")>-1&&(i=i.slice(1),O=!0),c>-1&&(i=i.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g,"$1"+o[s.currentLanguage].delimiters.thousands)),0===t.indexOf(".")&&(i=""),(l&&O?"(":"")+(!l&&O?"-":"")+(!O&&h?"+":"")+i+S+(p||"")+(l&&O?")":"")}function h(e){var t=e.toString().split(".");return t.length<2?1:Math.pow(10,t[1].length)}function d(){return Array.prototype.slice.call(arguments).reduce((function(e,t){var n=h(e),r=h(t);return n>r?n:r}),-1/0)}(r=function(e){return new c(e=r.isNumeral(e)?e.value():0===e||void 0===e?0:null===e?null:Number(e)?Number(e):r.fn.unformat(e))}).version="1.5.6",r.isNumeral=function(e){return e instanceof c},r.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),r},r.reset=function(){for(var e in i)s[e]=i[e]},r.languageData=function(e){if(!e)return o[s.currentLanguage];if(!o[e])throw new Error("Unknown language : "+e);return o[e]},r.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:"$"}}),r.zeroFormat=function(e){s.zeroFormat="string"==typeof e?e:null},r.nullFormat=function(e){s.nullFormat="string"==typeof e?e:null},r.defaultFormat=function(e){s.defaultFormat="string"==typeof e?e:"0.0"},r.validate=function(e,t){var n,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=r.languageData(t)}catch(e){u=r.languageData(r.language())}return i=u.currency.symbol,a=u.abbreviations,n=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(n)).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,n=Object(this),r=n.length>>>0,o=0;if(2===arguments.length)t=arguments[1];else{for(;o<r&&!(o in n);)o++;if(o>=r)throw new TypeError("Reduce of empty array with no initial value");t=n[o++]}for(;o<r;o++)o in n&&(t=e(t,n[o],o,n));return t}),r.fn=c.prototype={clone:function(){return r(this)},format:function(e,t){return function(e,t,n){return 0===e._value&&null!==s.zeroFormat?s.zeroFormat:null===e._value&&null!==s.nullFormat?s.nullFormat:t.indexOf("$")>-1?function(e,t,n){var r,i,a=t.indexOf("$"),c=t.indexOf("("),u=t.indexOf("-"),h="";return t.indexOf(" $")>-1?(h=" ",t=t.replace(" $","")):t.indexOf("$ ")>-1?(h=" ",t=t.replace("$ ","")):t=t.replace("$",""),i=l(e._value,t,n),a<=1?i.indexOf("(")>-1||i.indexOf("-")>-1?(r=1,(a<c||a<u)&&(r=0),(i=i.split("")).splice(r,0,o[s.currentLanguage].currency.symbol+h),i=i.join("")):i=o[s.currentLanguage].currency.symbol+h+i:i.indexOf(")")>-1?((i=i.split("")).splice(-1,0,h+o[s.currentLanguage].currency.symbol),i=i.join("")):i=i+h+o[s.currentLanguage].currency.symbol,i}(e,t,n):t.indexOf("%")>-1?function(e,t,n){var r,o="",i=100*e._value;return t.indexOf(" %")>-1?(o=" ",t=t.replace(" %","")):t=t.replace("%",""),(r=l(i,t,n)).indexOf(")")>-1?((r=r.split("")).splice(-1,0,o+"%"),r=r.join("")):r=r+o+"%",r}(e,t,n):t.indexOf(":")>-1?function(e){var t=Math.floor(e._value/60/60),n=Math.floor((e._value-60*t*60)/60),r=Math.round(e._value-60*t*60-60*n);return t+":"+(n<10?"0"+n:n)+":"+(r<10?"0"+r:r)}(e):t.indexOf("b")>-1||t.indexOf("ib")>-1?function(e,t,n){var r,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",""),r=0;r<=s.length;r++)if(o=Math.pow(1024,r),i=Math.pow(1024,r+1),null===c||0===c||c>=o&&c<i){u+=s[r],o>0&&(c/=o);break}return l(c,t,n)+u}(e,t,n):t.indexOf("o")>-1?function(e,t,n){var r="";return t.indexOf(" o")>-1?(r=" ",t=t.replace(" o","")):t=t.replace("o",""),r+=o[s.currentLanguage].ordinal(e._value),l(e._value,t,n)+r}(e,t,n):l(e._value,t,n)}(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 n,r,i,c,u,l,h=t,d=!1;if(t.indexOf(":")>-1)l=function(e){var t=e.split(":"),n=0;return 3===t.length?(n+=60*Number(t[0])*60,n+=60*Number(t[1]),n+=Number(t[2])):2===t.length&&(n+=60*Number(t[0]),n+=Number(t[1])),Number(n)}(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,".")),n=new RegExp("[^a-zA-Z]"+o[s.currentLanguage].abbreviations.thousand+"(?:\\)|(\\"+o[s.currentLanguage].currency.symbol+")?(?:\\))?)?$"),r=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&&!(d=(t.indexOf(a.bytes[u])>-1||t.indexOf(a.iec[u])>-1)&&Math.pow(1024,u));u++);l=d||1,l*=h.match(n)?Math.pow(10,3):1,l*=h.match(r)?Math.pow(10,6):1,l*=h.match(i)?Math.pow(10,9):1,l*=h.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=d?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=d.call(null,this._value,e);return this._value=[this._value,e].reduce((function(e,n,r,o){return e+t*n}),0)/t,this},subtract:function(e){var t=d.call(null,this._value,e);return this._value=[e].reduce((function(e,n,r,o){return e-t*n}),this._value*t)/t,this},multiply:function(e){return this._value=[this._value,e].reduce((function(e,t,n,r){var o=d(e,t);return e*o*(t*o)/(o*o)}),1),this},divide:function(e){return this._value=[this._value,e].reduce((function(e,t,n,r){var o=d(e,t);return e*o/(t*o)})),this},difference:function(e){return Math.abs(r(this._value).subtract(e).value())}},e.exports&&(e.exports=r),"undefined"==typeof ender&&(this.numeral=r),void 0===(n=function(){return r}.apply(t,[]))||(e.exports=n)}).call(this)},68923:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.GetMoreOperation=void 0;const r=n(75725),o=n(17562),i=n(145),s=n(35394);class a extends s.AbstractOperation{constructor(e,t,n,o){super(o),this.SERVER_COMMAND_RESPONSE_TYPE=r.CursorResponse,this.options=o,this.ns=e,this.cursorId=t,this.server=n}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 n={getMore:this.cursorId,collection:t};return"number"==typeof this.options.batchSize&&(n.batchSize=Math.abs(this.options.batchSize)),"number"==typeof this.options.maxAwaitTimeMS&&(n.maxTimeMS=this.options.maxAwaitTimeMS),void 0!==this.options.comment&&(0,i.maxWireVersion)(e)>=9&&(n.comment=this.options.comment),n}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,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.RunCommandCursor=void 0;const r=n(17562),o=n(96357),i=n(68923),s=n(17668),a=n(145),c=n(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 r.MongoAPIError("Clone not supported, create a new cursor with db.runCursorCommand")}withReadConcern(e){throw new r.MongoAPIError("RunCommandCursor does not support readConcern it must be attached to the command being run")}addCursorFlag(e,t){throw new r.MongoAPIError("RunCommandCursor does not support cursor flags, they must be attached to the command being run")}maxTimeMS(e){throw new r.MongoAPIError("maxTimeMS must be configured on the command document directly, to configure getMore.maxTimeMS use cursor.setMaxTimeMS()")}batchSize(e){throw new r.MongoAPIError("batchSize must be configured on the command document directly, to configure getMore.batchSize use cursor.setBatchSize()")}constructor(e,t,n={}){super(e.client,(0,a.ns)(e.namespace),n),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}),n=await(0,o.executeOperation)(this.client,t,this.timeoutContext);return{server:t.server,session:e,response:n}}async getMore(e){if(!this.session)throw new r.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,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CreateCollectionOperation=void 0,t.createCollections=async function(e,t,n){const o=a.TimeoutContext.create({session:n.session,serverSelectionTimeoutMS:e.client.s.options.serverSelectionTimeoutMS,waitQueueTimeoutMS:e.client.s.options.waitQueueTimeoutMS,timeoutMS:n.timeoutMS}),i=n.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)<r.MIN_SUPPORTED_QE_WIRE_VERSION)throw new s.MongoCompatibilityError(`${m} The minimum server version required is ${r.MIN_SUPPORTED_QE_SERVER_VERSION}`);return super.buildCommandDocument(e,t)}}const u=i.escCollection??`enxcol_.${t}.esc`,h=i.ecocCollection??`enxcol_.${t}.ecoc`;for(const t of[u,h]){const r=new a(e,t,{clusteredIndex:{key:{_id:1},unique:!0},session:n.session});await(0,l.executeOperation)(e.client,r,o)}n.encryptedFields||(n={...n,encryptedFields:i})}const u=await(0,l.executeOperation)(e.client,new f(e,t,n),o);if(i){const r=h.CreateIndexesOperation.fromIndexSpecification(e,t,{__safeContent__:1},{session:n.session});await(0,l.executeOperation)(e.client,r,o)}return u};const r=n(96856),o=n(75725),i=n(19498),s=n(17562),a=n(7799),c=n(145),u=n(78130),l=n(96357),h=n(22847),d=n(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,n={}){super(e,n),this.SERVER_COMMAND_RESPONSE_TYPE=o.MongoDBResponse,this.options=n,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,d.defineAspects)(f,[d.Aspect.WRITE_OPERATION])},70136:(e,t,n)=>{var r,o=n(67787).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.AutoEncrypter=t.AutoEncryptionLoggerLevel=void 0;const i=n(26272),s=n(75080),a=n(91869),c=n(8500),u=n(17562),l=n(22220),h=n(145),d=n(95738),p=n(93992),m=n(86981),f=n(95724),g=n(51825),y=n(97515);t.AutoEncryptionLoggerLevel=Object.freeze({FatalError:0,Error:1,Warning:2,Info:3,Trace:4});class E{static getMongoCrypt(){const e=(0,c.getMongoDBClientEncryption)();if("kModuleError"in e)throw e.kModuleError;return e.MongoCrypt}constructor(e,t){if(this[r]=!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 n={enableMultipleCollinfo:!0,cryptoCallbacks:p};t.schemaMap&&(n.schemaMap=o.isBuffer(t.schemaMap)?t.schemaMap:(0,s.serialize)(t.schemaMap)),t.encryptedFieldsMap&&(n.encryptedFieldsMap=o.isBuffer(t.encryptedFieldsMap)?t.encryptedFieldsMap:(0,s.serialize)(t.encryptedFieldsMap)),n.kmsProviders=o.isBuffer(this._kmsProviders)?this._kmsProviders:(0,s.serialize)(this._kmsProviders),t.options?.logger&&(n.logger=t.options.logger),t.extraOptions&&t.extraOptions.cryptSharedLibPath&&(n.cryptSharedLibPath=t.extraOptions.cryptSharedLibPath),t.bypassQueryAnalysis&&(n.bypassQueryAnalysis=t.bypassQueryAnalysis),null!=t.keyExpirationMS&&(n.keyExpirationMS=t.keyExpirationMS),this._bypassMongocryptdAndCryptShared=this._bypassEncryption||!!t.bypassQueryAnalysis,t.extraOptions&&t.extraOptions.cryptSharedLibSearchPaths?n.cryptSharedLibSearchPaths=t.extraOptions.cryptSharedLibSearchPaths:this._bypassMongocryptdAndCryptShared||(n.cryptSharedLibSearchPaths=["$SYSTEM"]);const a=E.getMongoCrypt();if(this._mongocrypt=new a(n),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,d.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,n={}){if(n.signal?.throwIfAborted(),this._bypassEncryption)return t;const r=o.isBuffer(t)?t:(0,s.serialize)(t,n),i=this._mongocrypt.makeEncryptionContext(h.MongoDBCollectionNamespace.fromString(e).db,r);i.id=this._contextCounter++,i.ns=e,i.document=t;const a=new y.StateMachine({promoteValues:!1,promoteLongs:!1,proxyOptions:this._proxyOptions,tlsOptions:this._tlsOptions,socketOptions:(0,d.autoSelectSocketOptions)(this._client.s.options)});return(0,s.deserialize)(await a.execute(this,i,n),{promoteValues:!1,promoteLongs:!1})}async decrypt(e,t={}){t.signal?.throwIfAborted();const n=this._mongocrypt.makeDecryptionContext(e);n.id=this._contextCounter++;const r=new y.StateMachine({...t,proxyOptions:this._proxyOptions,tlsOptions:this._tlsOptions,socketOptions:(0,d.autoSelectSocketOptions)(this._client.s.options)});return await r.execute(this,n,t)}async askForKMSCredentials(){return await(0,g.refreshKMSCredentials)(this._kmsProviders,this._credentialProviders)}get cryptSharedLibVersionInfo(){return this._mongocrypt.cryptSharedLibVersionInfo}static get libmongocryptVersion(){return E.getMongoCrypt().libmongocryptVersion}}t.AutoEncrypter=E,r=a.kDecorateResult},70839:(e,t,n)=>{var r=n(67787).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.Plain=void 0;const o=n(75080),i=n(17562),s=n(145),a=n(31057);class c extends a.AuthProvider{async auth(e){const{connection:t,credentials:n}=e;if(!n)throw new i.MongoMissingCredentialsError("AuthContext must provide credentials.");const{username:a,password:c}=n,u={saslStart:1,mechanism:"PLAIN",payload:new o.Binary(r.from(`\0${a}\0${c}`)),autoAuthorize:1};await t.command((0,s.ns)("$external.$cmd"),u,void 0)}}t.Plain=c},71235:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Admin=void 0;const r=n(75080),o=n(96357),i=n(11706),s=n(64125),a=n(17668),c=n(31480),u=n(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,r.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,n)=>{var r=n(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=n(93874),i=n(37668),s=n(75080),a=n(91869),c=n(17562),u=n(93347),l=n(4642),h=n(13700),d=n(89167),p=n(14019),m=n(7799),f=n(145),g=n(38216),y=n(15620),E=n(23611),S=n(64515),O=n(97531),C=n(75725),v=n(61428);class b 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:n,remotePort:r}=e;return"string"==typeof n&&"number"==typeof r?f.HostAddress.fromHostPort(n,r).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 E.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(b.PINNED),this.removeAllListeners(b.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(b.CLOSE))}prepareCommand(e,t,n){let r={...t};const o=(0,v.getReadPreference)(n),i=n?.session;let s=this.clusterTime;if(this.serverApi){const{version:e,strict:t,deprecationErrors:n}=this.serverApi;r.apiVersion=e,null!=t&&(r.apiStrict=t),null!=n&&(r.apiDeprecationErrors=n)}if(this.hasSessionSupport&&i){i.clusterTime&&s&&i.clusterTime.clusterTime.greaterThan(s.clusterTime)&&(s=i.clusterTime);const e=(0,p.applySession)(i,r,n);if(e)throw e}else if(i?.explicit)throw new c.MongoCompatibilityError("Current topology does not support sessions");s&&(r.$clusterTime=s),this.description.type!==d.ServerType.Standalone&&((0,v.isSharded)(this)||this.description.loadBalanced||!this.supportsOpMsg||!0!==n.directConnection||"primary"!==o?.mode?(0,v.isSharded)(this)&&!this.supportsOpMsg&&"primary"!==o?.mode?r={$query:r,$readPreference:o.toJSON()}:"primary"!==o?.mode&&(r.$readPreference=o.toJSON()):r.$readPreference=h.ReadPreference.primaryPreferred.toJSON());const a={numberToSkip:0,numberToReturn:-1,checkKeys:!1,secondaryOk:o.secondaryOk(),...n};return n.timeoutContext?.addMaxTimeMSToCommand(r,n),this.supportsOpMsg?new y.OpMsgRequest(e,r,a):new y.OpQueryRequest(e,r,a)}async*sendWire(e,t,n){this.throwIfAborted();const r=t.socketTimeoutMS??t?.timeoutContext?.getSocketTimeoutMS()??this.socketTimeoutMS;this.socket.setTimeout(r);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=(n??C.MongoDBResponse).make(t);yield o,this.throwIfAborted(),this.socket.setTimeout(r)}}finally{this.socket.setTimeout(0)}}async*sendCommand(e,t,n,r){n?.signal?.throwIfAborted();const o=this.prepareCommand(e.db,t,n);let i=0;this.shouldEmitAndLogCommand&&(i=(0,f.now)(),this.emitAndLogCommand(this.monitorCommands,b.COMMAND_STARTED,o.databaseName,this.established,new g.CommandStartedEvent(this,o,this.description.serverConnectionId)));const s=null!=n.documentsReturnedIn&&n.raw?{...n,raw:!1,fieldsAsRaw:{[n.documentsReturnedIn]:!0}}:n;let a,u;try{for await(a of(this.throwIfAborted(),this.sendWire(o,n,r))){if(u=void 0,null!=n.session&&(0,p.updateSessionFromResponse)(n.session,a),a.$clusterTime&&(this.clusterTime=a.$clusterTime,this.emit(b.CLUSTER_TIME_RECEIVED,a.$clusterTime)),0===a.ok){if(n.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,b.COMMAND_SUCCEEDED,o.databaseName,this.established,new g.CommandSucceededEvent(this,o,n.noResponse?void 0:o.moreToCome?{ok:1}:u??=a.toObject(s),i,this.description.serverConnectionId)),null==r?yield u??=a.toObject(s):yield a,this.throwIfAborted()}}catch(e){throw this.shouldEmitAndLogCommand&&this.emitAndLogCommand(this.monitorCommands,b.COMMAND_FAILED,o.databaseName,this.established,new g.CommandFailedEvent(this,o,e,i,this.description.serverConnectionId)),e}}async command(e,t,n={},r){this.throwIfAborted(),n.signal?.throwIfAborted();for await(const o of this.sendCommand(e,t,n,r)){if(n.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,n,r){(async()=>{this.throwIfAborted();for await(const o of this.sendCommand(e,t,n))r(void 0,o),this.throwIfAborted();throw new c.MongoUnexpectedServerResponseError("Server ended moreToCome unexpectedly")})().then(void 0,r)}throwIfAborted(){if(this.error)throw this.error}async writeCommand(e,t){const n="none"!==t.agreedCompressor&&y.OpCompressedRequest.canCompress(e)?new y.OpCompressedRequest(e,{agreedCompressor:t.agreedCompressor??"none",zlibCompressionLevel:t.zlibCompressionLevel??0}):e,o=r.concat(await n.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,O.onData)(this.messageStream,e),this.messageStream.resume();for await(const e of this.dataEvents){const t=await(0,S.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=b,b.COMMAND_STARTED=a.COMMAND_STARTED,b.COMMAND_SUCCEEDED=a.COMMAND_SUCCEEDED,b.COMMAND_FAILED=a.COMMAND_FAILED,b.CLUSTER_TIME_RECEIVED=a.CLUSTER_TIME_RECEIVED,b.CLOSE=a.CLOSE,b.PINNED=a.PINNED,b.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,n){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 n(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 n(new c.MongoRuntimeError("SizedMessageTransform does not support backpressure"))}n()}}t.SizedMessageTransform=w,t.CryptoConnection=class extends b{constructor(e,t){super(e,t),this.autoEncrypter=t.autoEncrypter}async command(e,t,n,r){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,n,r);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,h=await o.encrypt(e.toString(),t,n);if(null!=u&&(t.find||t.findAndModify)&&(h.sort=u),null!=l&&t.createIndexes)for(const[e,t]of l.entries())h.indexes[e].key=t;const d=await super.command(e,h,n,r??C.MongoDBResponse),p=await o.decrypt(d.toBytes(),n),m=r?.make(p)??(0,s.deserialize)(p,n);return o[a.kDecorateResult]&&(null==r?(0,f.decorateDecryptionResult)(m,d.toObject(),!0):m instanceof C.CursorResponse&&(m.encryptedResponse=d)),m}}},71906:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ListSearchIndexesCursor=void 0;const r=n(68526);class o extends r.AggregationCursor{constructor({fullNamespace:e,client:t},n,r={}){super(t,e,null==n?[{$listSearchIndexes:{}}]:[{$listSearchIndexes:{name:n}}],r)}}t.ListSearchIndexesCursor=o},72506:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.allowAbort=t.ALLOW_ABORT_INTERVAL_COUNT=void 0,t.ALLOW_ABORT_INTERVAL_COUNT=1e3,t.allowAbort=async function(e){return new Promise(((t,n)=>setTimeout((()=>{if(null==e?void 0:e.aborted)return n((null==e?void 0:e.reason)||new Error("Operation aborted"));t()}))))}},73619:(e,t,n)=>{var r=n(9606).URL;Object.defineProperty(t,"__esModule",{value:!0}),t.callback=void 0;const o=n(79790),i=n(17562),s=n(145),a=Object.freeze({Metadata:"true",Accept:"application/json"});t.callback=async e=>{const t=e.tokenAudience,n=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 n=new r(o.AZURE_BASE_URL);(0,o.addAzureParams)(n,e,t);const c=await(0,s.get)(n,{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,n);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,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.GridFSBucket=void 0;const r=n(17562),o=n(4642),i=n(7799),s=n(145),a=n(40012),c=n(33104),u=n(10557),l={bucketName:"fs",chunkSizeBytes:261120};class h extends o.TypedEventEmitter{constructor(e,t){super(),this.on("error",s.noop),this.setMaxListeners(0);const n=(0,s.resolveOptions)(e,{...l,...t,writeConcern:a.WriteConcern.fromOptions(t)});this.s={db:e,options:n,_chunksCollection:e.collection(n.bucketName+".chunks"),_filesCollection:e.collection(n.bucketName+".files"),checkedIndexes:!1,calledOpenUploadStream:!1}}openUploadStream(e,t){return new u.GridFSBucketWriteStream(this,e,{timeoutMS:this.s.options.timeoutMS,...t})}openUploadStreamWithId(e,t,n){return new u.GridFSBucketWriteStream(this,t,{timeoutMS:this.s.options.timeoutMS,...n,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:n}=(0,s.resolveOptions)(this.s.db,t);let o;n&&(o=new i.CSOTTimeoutContext({timeoutMS:n,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 r.MongoOperationTimeoutError(`Timed out after ${n}ms`);if(await this.s._chunksCollection.deleteMany({files_id:e},{timeoutMS:c}),0===a)throw new r.MongoRuntimeError(`File not found for id ${e}`)}find(e={},t={}){return this.s._filesCollection.find(e,t)}openDownloadStreamByName(e,t){let n,r={uploadDate:-1};return t&&null!=t.revision&&(t.revision>=0?(r={uploadDate:1},n=t.revision):n=-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:r,skip:n})}async rename(e,t,n){const o={_id:e},i={$set:{filename:t}},{matchedCount:s}=await this.s._filesCollection.updateOne(o,i,n);if(0===s)throw new r.MongoRuntimeError(`File with id ${e} not found`)}async drop(e){const{timeoutMS:t}=(0,s.resolveOptions)(this.s.db,e);let n;if(t&&(n=new i.CSOTTimeoutContext({timeoutMS:t,serverSelectionTimeoutMS:this.s.db.client.s.options.serverSelectionTimeoutMS})),n){await this.s._filesCollection.drop({timeoutMS:n.remainingTimeMS});const e=n.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=h,h.INDEX="index"},75080:(e,t,n)=>{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 n=r.BSON.onDemand.parseToElements(e,t);return Array.isArray(n)?n:[...n]},t.pluckBSONSerializeOptions=function(e){const{fieldsAsRaw:t,useBigInt64:n,promoteValues:r,promoteBuffers:o,promoteLongs:i,serializeFunctions:s,ignoreUndefined:a,bsonRegExp:c,raw:u,enableUtf8Validation:l}=e;return{fieldsAsRaw:t,useBigInt64:n,promoteValues:r,promoteBuffers:o,promoteLongs:i,serializeFunctions:s,ignoreUndefined:a,bsonRegExp:c,raw:u,enableUtf8Validation:l}},t.resolveBSONOptions=function(e,t){const n=t?.bsonOptions;return{raw:e?.raw??n?.raw??!1,useBigInt64:e?.useBigInt64??n?.useBigInt64??!1,promoteLongs:e?.promoteLongs??n?.promoteLongs??!0,promoteValues:e?.promoteValues??n?.promoteValues??!0,promoteBuffers:e?.promoteBuffers??n?.promoteBuffers??!1,ignoreUndefined:e?.ignoreUndefined??n?.ignoreUndefined??!1,bsonRegExp:e?.bsonRegExp??n?.bsonRegExp??!1,serializeFunctions:e?.serializeFunctions??n?.serializeFunctions??!1,fieldsAsRaw:e?.fieldsAsRaw??n?.fieldsAsRaw??{},enableUtf8Validation:e?.enableUtf8Validation??n?.enableUtf8Validation??!0}},t.parseUtf8ValidationOption=function(e){const t=e?.enableUtf8Validation;return!1===t?{utf8:!1}:{utf8:{writeErrors:!1}}};const r=n(62444);var o=n(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=r.BSON.onDemand.NumberUtils.getInt32LE,t.getFloat64LE=r.BSON.onDemand.NumberUtils.getFloat64LE,t.getBigInt64LE=r.BSON.onDemand.NumberUtils.getBigInt64LE,t.toUTF8=r.BSON.onDemand.ByteUtils.toUTF8},75725:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ClientBulkWriteCursorResponse=t.ExplainedCursorResponse=t.CursorResponse=t.MongoDBResponse=void 0,t.isErrorResponse=c;const r=n(75080),o=n(17562),i=n(145),s=n(68746),a={type:0,nameOffset:1,nameLength:2,offset:3,length:4};function c(e,t){for(let n=0;n<t.length;n++){const r=t[n];if(2===r[a.nameLength]){const t=r[a.nameOffset];if(111===e[t]&&107===e[t+1]){const t=r[a.offset],n=r[a.length];for(let r=t;r<t+n;r++)if(0!==e[r])return!1;return!0}}}return!0}class u extends s.OnDemandDocument{get(e,t,n){try{return super.get(e,t,n)}catch(e){throw new o.MongoUnexpectedServerResponseError(e.message,{cause:e})}}static is(e){return e instanceof u}static make(e){const t=(0,r.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",r.BSONType.object)?.getNumber("code")===o.MONGODB_ERROR_CODES.MaxTimeMSExpired)return!0;const e=this.get("writeErrors",r.BSONType.array);if(e?.size())for(let t=0;t<e.size();t++)if(e.get(t,r.BSONType.object)?.getNumber("code")===o.MONGODB_ERROR_CODES.MaxTimeMSExpired)return!0;return!1}get recoveryToken(){return this.get("recoveryToken",r.BSONType.object)?.toObject({promoteValues:!1,promoteLongs:!1,promoteBuffers:!1,validation:{utf8:!0}})??null}get atClusterTime(){return this.get("cursor",r.BSONType.object)?.get("atClusterTime",r.BSONType.timestamp)??this.get("atClusterTime",r.BSONType.timestamp)}get operationTime(){return this.get("operationTime",r.BSONType.timestamp)}get ok(){return this.getNumber("ok")?1:0}get $err(){return this.get("$err",r.BSONType.string)}get errmsg(){return this.get("errmsg",r.BSONType.string)}get code(){return this.getNumber("code")}get $clusterTime(){if(!("clusterTime"in this)){const e=this.get("$clusterTime",r.BSONType.object);if(null==e)return this.clusterTime=null,null;const t=e.get("clusterTime",r.BSONType.timestamp,!0),n=e.get("signature",r.BSONType.object)?.toObject();this.clusterTime={clusterTime:t,signature:n}}return this.clusterTime??null}toObject(e){const t={...(0,r.pluckBSONSerializeOptions)(e??{}),validation:(0,r.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,r.serialize)({ok:1,cursor:{id:0n,nextBatch:[]}}))}static is(e){return e instanceof l||e===l.emptyGetMore}get cursor(){return this.get("cursor",r.BSONType.object,!0)}get id(){try{return r.Long.fromBigInt(this.cursor.get("id",r.BSONType.long,!0))}catch(e){throw new o.MongoUnexpectedServerResponseError(e.message,{cause:e})}}get ns(){const e=this.cursor.get("ns",r.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",r.BSONType.object);if(e?.has("firstBatch"))this._encryptedBatch=e.get("firstBatch",r.BSONType.array,!0);else{if(!e?.has("nextBatch"))throw new o.MongoUnexpectedServerResponseError("Cursor document did not contain a batch");this._encryptedBatch=e.get("nextBatch",r.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",r.BSONType.array,!0);else{if(!e.has("nextBatch"))throw new o.MongoUnexpectedServerResponseError("Cursor document did not contain a batch");this._batch=e.get("nextBatch",r.BSONType.array,!0)}return this._batch}get batchSize(){return this.batch?.size()}get postBatchResumeToken(){return this.cursor.get("postBatchResumeToken",r.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,r.BSONType.object,!0)??null,n=this.encryptedBatch?.get(this.iterated,r.BSONType.object,!0)??null;if(this.iterated+=1,e?.raw)return t.toBytes();{const r=t.toObject(e);return n&&(0,i.decorateDecryptionResult)(r,n.toObject(e),!0),r}}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 r.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",r.BSONType.int,!0)}get upsertedCount(){return this.get("nUpserted",r.BSONType.int,!0)}get matchedCount(){return this.get("nMatched",r.BSONType.int,!0)}get modifiedCount(){return this.get("nModified",r.BSONType.int,!0)}get deletedCount(){return this.get("nDeleted",r.BSONType.int,!0)}get writeConcernError(){return this.get("writeConcernError",r.BSONType.object,!1)}}},75755:(e,t,n)=>{var r=n(65994).e;Object.defineProperty(t,"__esModule",{value:!0}),t.ConnectionPool=t.PoolState=void 0;const o=n(37668),i=n(91869),s=n(17562),a=n(4642),c=n(7799),u=n(145),l=n(87758),h=n(71470),d=n(287),p=n(76013),m=n(55741);t.PoolState=Object.freeze({paused:"paused",ready:"ready",closed:"closed"});class f extends a.TypedEventEmitter{constructor(e,n){if(super(),this.on("error",u.noop),this.options=Object.freeze({connectionType:h.Connection,...n,maxPoolSize:n.maxPoolSize??100,minPoolSize:n.minPoolSize??0,maxConnecting:n.maxConnecting??2,maxIdleTimeMS:n.maxIdleTimeMS??0,waitQueueTimeoutMS:n.waitQueueTimeoutMS??0,minPoolSizeCheckFrequencyMS:n.minPoolSizeCheckFrequencyMS??100,autoEncrypter:n.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",r.nextTick((()=>{this.emitAndLog(f.CONNECTION_POOL_CREATED,new d.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 d.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 d.ConnectionCheckOutStartedEvent(this));const{promise:n,resolve:o,reject:i}=(0,u.promiseWithResolvers)(),a=e.timeoutContext.connectionCheckoutTimeout,l={resolve:o,reject:i,cancelled:!1,checkoutTime:t},h=(0,u.addAbortListener)(e.signal,(function(){l.cancelled=!0,i(this.reason)}));this.waitQueue.push(l),r.nextTick((()=>this.processWaitQueue()));try{return a?.throwIfExpired(),await(a?Promise.race([n,a]):n)}catch(t){if(c.TimeoutError.is(t)){a?.clear(),l.cancelled=!0,this.emitAndLog(f.CONNECTION_CHECK_OUT_FAILED,new d.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{h?.[u.kDispose](),a?.clear()}}checkIn(e){if(!this.checkedOut.has(e))return;const t=this.closed,n=this.connectionIsStale(e),o=!!(t||n||e.closed);if(o||(e.markAvailable(),this.connections.unshift(e)),this.checkedOut.delete(e),this.emitAndLog(f.CONNECTION_CHECKED_IN,new d.ConnectionCheckedInEvent(this,e)),o){const n=e.closed?"error":t?"poolClosed":"stale";this.destroyConnection(e,n)}r.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 n=t.toHexString(),r=this.serviceGenerations.get(n);if(null==r)throw new s.MongoRuntimeError("Service generations are required in load balancer mode.");return this.serviceGenerations.set(n,r+1),void this.emitAndLog(f.CONNECTION_POOL_CLEARED,new d.ConnectionPoolClearedEvent(this,{serviceId:t}))}const n=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 d.ConnectionPoolClearedEvent(this,{interruptInUseConnections:n})),n&&r.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 d.ConnectionClosedEvent(this,e,"poolClosed")),e.destroy();this.connections.clear(),this.emitAndLog(f.CONNECTION_POOL_CLOSED,new d.ConnectionPoolClosedEvent(this))}}async reauthenticate(e){const t=e.authContext;if(!t)throw new s.MongoRuntimeError("No auth context found on connection.");const n=t.credentials;if(!n)throw new s.MongoMissingCredentialsError("Connection is missing credentials when asked to reauthenticate");const r=n.resolveAuthMechanism(e.hello),o=this.server.topology.client.s.authProviders.getOrCreateProvider(r.mechanism,r.mechanismProperties);if(!o)throw new s.MongoMissingCredentialsError(`Reauthenticate failed due to no auth provider for ${n.mechanism}`);await o.reauth(t)}clearMinPoolSizeTimer(){const e=this.minPoolSizeTimer;e&&(0,o.clearTimeout)(e)}destroyConnection(e,t){this.emitAndLog(f.CONNECTION_CLOSED,new d.ConnectionClosedEvent(this,e,t)),e.destroy()}connectionIsStale(e){const t=e.serviceId;if(this.loadBalanced&&t){const n=t.toHexString(),r=this.serviceGenerations.get(n);return e.generation!==r}return e.generation!==this.generation}connectionIsIdle(e){return!!(this.options.maxIdleTimeMS&&e.idleTime>this.options.maxIdleTimeMS)}destroyConnectionIfPerished(e){const t=this.connectionIsStale(e),n=this.connectionIsIdle(e);if(!t&&!n&&!e.closed)return!1;const r=e.closed?"error":t?"stale":"idle";return this.destroyConnection(e,r),!0}createConnection(e){const n={...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 r=(0,u.now)();this.emitAndLog(f.CONNECTION_CREATED,new d.ConnectionCreatedEvent(this,{id:n.id})),(0,l.connect)(n).then((n=>{if(this.poolState!==t.PoolState.ready)return this.pending--,n.destroy(),void e(this.closed?new p.PoolClosedError(this):new p.PoolClearedError(this));for(const e of[...i.APM_EVENTS,h.Connection.CLUSTER_TIME_RECEIVED])n.on(e,(t=>this.emit(e,t)));if(this.loadBalanced){n.on(h.Connection.PINNED,(e=>this.metrics.markPinned(e))),n.on(h.Connection.UNPINNED,(e=>this.metrics.markUnpinned(e)));const e=n.serviceId;if(e){let t;const r=e.toHexString();(t=this.serviceGenerations.get(r))?n.generation=t:(this.serviceGenerations.set(r,0),n.generation=0)}}n.markAvailable(),this.emitAndLog(f.CONNECTION_READY,new d.ConnectionReadyEvent(this,n,r)),this.pending--,e(void 0,n)}),(t=>{this.pending--,this.server.handleError(t),this.emitAndLog(f.CONNECTION_CLOSED,new d.ConnectionClosedEvent(this,{id:n.id,serviceId:void 0},"error",t)),(t instanceof s.MongoNetworkError||t instanceof s.MongoServerError)&&(t.connectionGeneration=n.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,n)=>{!e&&n&&(this.connections.push(n),r.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",n=this.closed?new p.PoolClosedError(this):new p.PoolClearedError(this);this.emitAndLog(f.CONNECTION_CHECK_OUT_FAILED,new d.ConnectionCheckOutFailedEvent(this,t,e.checkoutTime,n)),this.waitQueue.shift(),e.reject(n);continue}if(!this.availableConnectionCount)break;const n=this.connections.shift();if(!n)break;this.destroyConnectionIfPerished(n)||(this.checkedOut.add(n),this.emitAndLog(f.CONNECTION_CHECKED_OUT,new d.ConnectionCheckedOutEvent(this,n,e.checkoutTime)),this.waitQueue.shift(),e.resolve(n))}const{maxPoolSize:e,maxConnecting:n}=this.options;for(;this.waitQueueSize>0&&this.pendingConnectionCount<n&&(0===e||this.totalConnectionCount<e);){const e=this.waitQueue.shift();e&&!e.cancelled&&this.createConnection(((t,n)=>{e.cancelled?!t&&n&&this.connections.push(n):t?(this.emitAndLog(f.CONNECTION_CHECK_OUT_FAILED,new d.ConnectionCheckOutFailedEvent(this,"connectionError",e.checkoutTime,t)),e.reject(t)):n&&(this.checkedOut.add(n),this.emitAndLog(f.CONNECTION_CHECKED_OUT,new d.ConnectionCheckedOutEvent(this,n,e.checkoutTime)),e.resolve(n)),r.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},75996:function(e,t,n){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.getCompletedSchemaAnalyzer=t.verifyStreamSource=t.SchemaAnalyzer=void 0;const o=r(n(57282)),i=n(62444),s=r(n(40165)),a=n(72506),c={semanticTypes:!1,storeValues:!0,storedValuesLengthLimit:1e4};function u(e){if(null==e?void 0:e._bsontype){if(["Decimal128","Long"].includes(e._bsontype))return e.toString();if(["Double","Int32"].includes(e._bsontype))return String(e.value)}return"string"==typeof e?e:String(e)}function l(e,t){const n=e.name,r=t.name;return"_id"===n?-1:"_id"===r?1:n.toLowerCase()<r.toLowerCase()?-1:1}function h(e){return"Null"===e.name}function d(e){return"Array"===e.name}function p(e){return"Document"===e.name}function m(e,t=[]){const n=[],r=Object.values(e).sort(l);for(const e of r){const r=[...t,e.name];n.push(r);const o=Object.values(e.types).find((e=>"Document"===e.bsonType));o&&n.push(...m(o.fields,r));const i=Object.values(e.types).find((e=>"Array"===e.bsonType));if(i){const e=Object.values(i.types).find((e=>"Document"===e.bsonType));e&&n.push(...m(e.fields,r))}}return n}function f(e){function t(e){return Object.values(e).sort(((e,t)=>t.count-e.count)).map((e=>({bsonType:e.bsonType,...d(e)?{types:t(e.types)}:{},...p(e)?{fields:n(e.fields)}:{}})))}function n(e){const n=Object.create(null);return Object.values(e).forEach((e=>{const r=t(e.types);n[e.name]={types:r}})),n}return n(e)}function g(e,t){return t<1?"":e.charCodeAt(t-1)===e.codePointAt(t-1)?e.slice(0,t):e.slice(0,t-1)}function y(e,t){return h(e)?e.count>0:e.values?t!==e.values.length:void 0}function E(e){function t(e){const t=Object.values(e.types).map((e=>e.count)).reduce(((e,t)=>e+t),0);return{types:n(e.types,t),totalCount:t,lengths:e.lengths,averageLength:t/e.lengths.length}}function n(e,n){return Object.values(e).map((e=>{const o=function(e){return h(e)?0===e.count?0:1:e.values?new Set(e.values.map(u)).size:void 0}(e);return{name:e.name,path:e.path,count:e.count,probability:e.count/n,unique:o,hasDuplicates:y(e,o),values:h(e)?void 0:e.values,bsonType:e.bsonType,...d(e)?t(e):{},...p(e)?{fields:r(e.fields,e.count)}:{}}})).sort(((e,t)=>t.probability-e.probability))}function r(e,t){return Object.values(e).map((e=>{const r=n(e.types,t),o=t-e.count;return o>0&&r.push({name:"Undefined",bsonType:"Undefined",unique:o>1?0:1,hasDuplicates:o>1,path:e.path,count:o,probability:o/t}),{name:e.name,path:e.path,count:e.count,type:1===r.length?r[0].name:r.map((e=>e.name)),probability:e.count/t,hasDuplicates:!!r.find((e=>e.hasDuplicates)),types:r}})).sort(l)}return r(e.fields,e.count)}class S{constructor(e){if(this.documentsAnalyzed=0,this.fieldsCount=0,this.schemaAnalysisRoot={fields:Object.create(null),count:0},this.finalized=!0,this.schemaResult={count:0,fields:[]},this.fieldAndTypeAnalysisCounter=0,this.options={...c,...e},this.semanticTypes={...s.default},"object"==typeof this.options.semanticTypes){const e=Object.entries(this.options.semanticTypes).filter((([,e])=>"boolean"==typeof e&&e)).map((([e])=>e.toLowerCase()));this.semanticTypes={...Object.entries(this.semanticTypes).filter((([t])=>e.includes(t.toLowerCase()))).reduce(((e,[t,n])=>({...e,[t]:n})),Object.create(null))},Object.entries(this.options.semanticTypes).filter((([,e])=>"function"==typeof e)).forEach((([e,t])=>{this.semanticTypes[e]=t}))}}allowAbortDuringAnalysis(){this.fieldAndTypeAnalysisCounter++%a.ALLOW_ABORT_INTERVAL_COUNT==0&&(0,a.allowAbort)()}increaseFieldCount(){if(this.options.distinctFieldsAbortThreshold&&(this.fieldsCount++,this.fieldsCount>this.options.distinctFieldsAbortThreshold))throw new Error(`Schema analysis aborted: Fields count above ${this.options.distinctFieldsAbortThreshold}`)}getSemanticType(e,t){return Object.entries(this.semanticTypes).filter((([,n])=>n(e,t))).map((([e])=>e))[0]}async analyzeDoc(e){this.finalized=!1;const t=async(e,r,s)=>{var a,c,u;await this.allowAbortDuringAnalysis();const l=function(e){const t=(null==e?void 0:e._bsontype)?e._bsontype:Object.prototype.toString.call(e).replace(/^\[object (\w+)\]$/,"$1");return"Object"===t?"Document":"Code"===t&&e.scope?"CodeWScope":t}(r),m=this.options.semanticTypes&&this.getSemanticType(r,e)||l;s[m]||(s[m]={name:m,bsonType:l,path:e,count:0});const f=s[m];if(f.count++,d(f)){f.types=null!==(a=f.types)&&void 0!==a?a:Object.create(null),f.lengths=null!==(c=f.lengths)&&void 0!==c?c:[],f.lengths.push(r.length);for(const n of r)await t(e,n,f.types)}else if(p(f)){f.fields=null!==(u=f.fields)&&void 0!==u?u:Object.create(null);for(const[t,o]of Object.entries(r))await n(t,[...e,t],o,f.fields)}else this.options.storeValues&&!h(f)&&(f.values||(f.values=["String","Binary","Code"].includes(l)?(0,o.default)(100):(0,o.default)(1e4)),f.values.pushSome(function(e,t,n){return"String"===e?g(t,n):"Binary"===e?t.buffer.length>n?new i.Binary(t.buffer.slice(0,n),t.sub_type):t:"Code"===e&&t.code.length>=n?new i.Code(g(t.code,n),t.scope):t}(f.bsonType,r,this.options.storedValuesLengthLimit)))},n=async(e,n,r,o)=>{await this.allowAbortDuringAnalysis(),o[e]||(o[e]={name:e,path:n,count:0,types:Object.create(null)},this.increaseFieldCount());const i=o[e];i.count++,await t(n,r,i.types)};for(const t of Object.keys(e))await n(t,[t],e[t],this.schemaAnalysisRoot.fields);this.schemaAnalysisRoot.count+=1}getResult(){return this.finalized||(this.schemaResult={count:this.schemaAnalysisRoot.count,fields:E(this.schemaAnalysisRoot)},this.finalized=!0),this.schemaResult}getSchemaPaths(){return m(this.schemaAnalysisRoot.fields)}getSimplifiedSchema(){return f(this.schemaAnalysisRoot.fields)}}function O(e){if(!(Symbol.iterator in e)&&!(Symbol.asyncIterator in e))throw new Error("Unknown input type for `docs`. Must be an array, stream or MongoDB Cursor.");return e}t.SchemaAnalyzer=S,t.verifyStreamSource=O,t.getCompletedSchemaAnalyzer=async function(e,t){var n;const r=new S(t);for await(const o of O(e)){if(null===(n=null==t?void 0:t.signal)||void 0===n?void 0:n.aborted)throw t.signal.reason;await r.analyzeDoc(o)}return r}},76013:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WaitQueueTimeoutError=t.PoolClearedOnNetworkError=t.PoolClearedError=t.PoolClosedError=void 0;const r=n(17562);class o extends r.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 r.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(r.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 r.MongoDriverError{constructor(e,t){super(e),this.address=t}get name(){return"MongoWaitQueueTimeoutError"}}t.WaitQueueTimeoutError=s},78130:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CommandOperation=void 0;const r=n(17562),o=n(36411),i=n(28541),s=n(145),a=n(40012),c=n(35394);class u extends c.AbstractOperation{constructor(e,t){super(t),this.options=t??{};const n=t?.dbName||t?.authdb;if(this.ns=n?new s.MongoDBNamespace(n,"$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 r.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 n=this.buildCommandDocument(e,t),r=this.session&&this.session.inTransaction();return this.readConcern&&(0,s.commandSupportsReadConcern)(n)&&!r&&Object.assign(n,{readConcern:this.readConcern}),this.writeConcern&&this.hasAspect(c.Aspect.WRITE_OPERATION)&&!r&&a.WriteConcern.apply(n,this.writeConcern),this.options.collation&&"object"==typeof this.options.collation&&!this.hasAspect(c.Aspect.SKIP_COLLATION)&&Object.assign(n,{collation:this.options.collation}),"number"==typeof this.options.maxTimeMS&&(n.maxTimeMS=this.options.maxTimeMS),this.hasAspect(c.Aspect.EXPLAINABLE)&&this.explain?(0,o.decorateWithExplain)(n,this.explain):n}}t.CommandOperation=u},79059:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.convertInternalToExpanded=void 0;const r=n(61283),o=n(59942),i=n(72506);t.convertInternalToExpanded=function(e,t={}){return function(){const e=new Set;function t(){const t=Object.fromEntries(Object.entries(r.RELAXED_EJSON_DEFINITIONS).filter((([t])=>e.has(t))));return Object.freeze(t)}function n(e){const t=r.InternalTypeToStandardTypeMap[e];if(!t)throw new Error(`Encountered unknown type: ${e}`);return{...t}}function s(e){const t=o.InternalTypeToBsonTypeMap[e];if(!t)throw new Error(`Encountered unknown type: ${e}`);return t}async function a(t,r){await(0,i.allowAbort)(r);const o={...n(t.bsonType),"x-bsonType":s(t.bsonType),"x-metadata":c(t)};var a;switch("values"in t&&t.values&&(o["x-sampleValues"]=t.values),o.$ref&&(a=o.$ref,e.add(a.split("/")[2])),t.bsonType){case"Array":o.items=await u(t.types,r);break;case"Document":Object.assign(o,await l(t.fields,r))}return o}function c({hasDuplicates:e,probability:t,count:n}){return{..."boolean"==typeof e?{hasDuplicates:e}:{},probability:t,count:n}}async function u(e,t){await(0,i.allowAbort)(t);const n=e.filter((e=>"undefined"!==e.bsonType.toLowerCase()));return 1===n.length?a(n[0],t):{anyOf:await Promise.all(n.map((e=>a(e,t))))}}async function l(e,t){const n=[],r={};for(const o of e)1===o.probability&&n.push(o.name),r[o.name]={...await u(o.types,t),"x-metadata":c(o)};return{required:n,properties:r}}return async function(e,n={}){const{required:r,properties:o}=await l(e.fields,n.signal);return{type:"object","x-bsonType":"object",required:r,properties:o,$defs:t()}}}()(e,t)}},79193:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.COLLATION_OPTIONS=void 0,t.COLLATION_OPTIONS={locale:["af","sq","am","ar","ar@collation=compat","hy","as","az","az@collation=search","be","bn","bn@collation=traditional","bs","bs@collation=search","bs_Cyrl","bg","my","ca","ca@collation=search","chr","zh","zh@collation=big5han","zh@collation=gb2312han","zh@collation=pinyin","zh@collation=unihan","zh@collation=zhuyin","zh_Hant","zh_Hant@collation=stroke","hr","hr@collation=search","cs","cs@collation=search","da","da@collation=search","nl","dz","en","en_US","en_US_POSIX","eo","et","ee","fo","fil","fi_FI","fi_FI@collation=search","fi_FI@collation=traditional","fr","fr_CA","gl","gl@collation=search","ka","de","de@collation=search","de@collation=eor","de@collation=phonebook","de_AT","de_AT@collation=phonebook","el","gu","ha","haw","he","he@collation=search","hi","hu","is","is@collation=search","ig","smn","smn@collation=search","id","ga","it","ja","ja@collation=unihan","kl","kl@collation=search","kn","kn@collation=traditional","kk","km","kok","ko","ko@collation=search","ko@collation=searchjl","ko@collation=unihan","ky","lk","lo","lv","li","li@collation=phonetic","lt","dsb","lb","mk","ms","ml","mt","mr","mn","ne","se","se@collation=search","nb","nb@collation=search","nn","nn@collation=search","or","om","ps","fa","fa_AF","pl","pt","pa","ro","ru","sr","sr_Latn","sr_Latn@collation=search","si","si@collation=dictionary","sk","sk@collation=search","sl","es","es@collation=search","es@collation=traditional","sw","sv","sv@collation=search","ta","te","th","bo","to","tr","tr@collation=search","uk","hsb","ur","ug","vi","vi@collation=traditional","wae","cy","yi","yi@collation=search","yo","zu","simple"],strength:[1,2,3,4,5],caseLevel:[!0,!1],caseFirst:["upper","lower","off"],numericOrdering:[!0,!1],alternate:["non-ignorable","shifted"],maxVariable:[!0,!1],backwards:[!0,!1],normalization:[!0,!1]}},79790:(e,t,n)=>{var r=n(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=n(17562),i=n(145),s=n(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,n){return e.searchParams.append("api-version","2018-02-01"),e.searchParams.append("resource",t),n&&e.searchParams.append("client_id",n),e}function u(e){const n=new r(e.url?.toString()??t.AZURE_BASE_URL);return c(n,"https://vault.azure.net"),{headers:{...e.headers,"Content-Type":"application/json",Metadata:!0},url:n}}async function l(e={}){const{headers:t,url:n}=u(e);try{const e=await(0,i.get)(n,{headers:t});return await async function(e){const{status:t,body:n}=e,r=(()=>{try{return JSON.parse(n)}catch{throw new s.MongoCryptAzureKMSRequestError("Malformed JSON body in GET request.")}})();if(200!==t)throw new s.MongoCryptAzureKMSRequestError("Unable to complete request.",r);if(!r.access_token)throw new s.MongoCryptAzureKMSRequestError("Malformed response body - missing field `access_token`.");if(!r.expires_in)throw new s.MongoCryptAzureKMSRequestError("Malformed response body - missing field `expires_in`.");const o=1e3*Number(r.expires_in);if(Number.isNaN(o))throw new s.MongoCryptAzureKMSRequestError("Malformed response body - unable to parse int from `expires_in` field.");return{accessToken:r.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,n)=>{var r=n(65994).e;Object.defineProperty(t,"__esModule",{value:!0}),t.callback=void 0;const o=n(65981),i="AZURE_FEDERATED_TOKEN_FILE",s="AWS_WEB_IDENTITY_TOKEN_FILE";t.callback=async()=>{let e;return e=r.env[i]?r.env[i]:r.env[s]?r.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,n=60*t,r=60*n,o=24*r,i=7*o;function s(e,t,n,r){var o=t>=1.5*n;return Math.round(e/n)+" "+r+(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*r;case"minutes":case"minute":case"mins":case"min":case"m":return a*n;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>=r?s(c,u,r,"hour"):u>=n?s(c,u,n,"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>=r?Math.round(e/r)+"h":i>=n?Math.round(e/n)+"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))}},84157:(e,t,n)=>{n.d(t,{Y:()=>xe});var r={};n.r(r),n.d(r,{attentionMarkers:()=>we,contentInitial:()=>Ee,disable:()=>Me,document:()=>ye,flow:()=>Oe,flowInitial:()=>Se,insideSpan:()=>be,string:()=>Ce,text:()=>ve});const o={};function i(e,t,n){if(function(e){return Boolean(e&&"object"==typeof e)}(e)){if("value"in e)return"html"!==e.type||n?e.value:"";if(t&&"alt"in e&&e.alt)return e.alt;if("children"in e)return s(e.children,t,n)}return Array.isArray(e)?s(e,t,n):""}function s(e,t,n){const r=[];let o=-1;for(;++o<e.length;)r[o]=i(e[o],t,n);return r.join("")}function a(e,t,n,r){const o=e.length;let i,s=0;if(t=t<0?-t>o?0:o+t:t>o?o:t,n=n>0?n:0,r.length<1e4)i=Array.from(r),i.unshift(t,n),e.splice(...i);else for(n&&e.splice(t,n);s<r.length;)i=r.slice(s,s+1e4),i.unshift(t,0),e.splice(...i),s+=1e4,t+=1e4}function c(e,t){return e.length>0?(a(e,e.length,0,t),e):t}const u={}.hasOwnProperty;function l(e,t){let n;for(n in t){const r=(u.call(e,n)?e[n]:void 0)||(e[n]={}),o=t[n];let i;if(o)for(i in o){u.call(r,i)||(r[i]=[]);const e=o[i];h(r[i],Array.isArray(e)?e:e?[e]:[])}}}function h(e,t){let n=-1;const r=[];for(;++n<t.length;)("after"===t[n].add?e:r).push(t[n]);a(e,0,0,r)}var d=n(66596);function p(e,t,n,r){const o=r?r-1:Number.POSITIVE_INFINITY;let i=0;return function(r){return(0,d.On)(r)?(e.enter(n),s(r)):t(r)};function s(r){return(0,d.On)(r)&&i++<o?(e.consume(r),s):(e.exit(n),t(r))}}const m={tokenize:function(e){const t=e.attempt(this.parser.constructs.contentInitial,(function(n){if(null!==n)return e.enter("lineEnding"),e.consume(n),e.exit("lineEnding"),p(e,t,"linePrefix");e.consume(n)}),(function(t){return e.enter("paragraph"),r(t)}));let n;return t;function r(t){const r=e.enter("chunkText",{contentType:"text",previous:n});return n&&(n.next=r),n=r,o(t)}function o(t){return null===t?(e.exit("chunkText"),e.exit("paragraph"),void e.consume(t)):(0,d.HP)(t)?(e.consume(t),e.exit("chunkText"),r):(e.consume(t),o)}}},f={tokenize:function(e){const t=this,n=[];let r,o,i,s=0;return c;function c(r){if(s<n.length){const o=n[s];return t.containerState=o[1],e.attempt(o[0].continuation,u,l)(r)}return l(r)}function u(e){if(s++,t.containerState._closeFlow){t.containerState._closeFlow=void 0,r&&C();const n=t.events.length;let o,i=n;for(;i--;)if("exit"===t.events[i][0]&&"chunkFlow"===t.events[i][1].type){o=t.events[i][1].end;break}O(s);let c=n;for(;c<t.events.length;)t.events[c][1].end=Object.assign({},o),c++;return a(t.events,i+1,0,t.events.slice(n)),t.events.length=c,l(e)}return c(e)}function l(o){if(s===n.length){if(!r)return m(o);if(r.currentConstruct&&r.currentConstruct.concrete)return y(o);t.interrupt=Boolean(r.currentConstruct&&!r._gfmTableDynamicInterruptHack)}return t.containerState={},e.check(g,h,p)(o)}function h(e){return r&&C(),O(s),m(e)}function p(e){return t.parser.lazy[t.now().line]=s!==n.length,i=t.now().offset,y(e)}function m(n){return t.containerState={},e.attempt(g,f,y)(n)}function f(e){return s++,n.push([t.currentConstruct,t.containerState]),m(e)}function y(n){return null===n?(r&&C(),O(0),void e.consume(n)):(r=r||t.parser.flow(t.now()),e.enter("chunkFlow",{contentType:"flow",previous:o,_tokenizer:r}),E(n))}function E(n){return null===n?(S(e.exit("chunkFlow"),!0),O(0),void e.consume(n)):(0,d.HP)(n)?(e.consume(n),S(e.exit("chunkFlow")),s=0,t.interrupt=void 0,c):(e.consume(n),E)}function S(e,n){const c=t.sliceStream(e);if(n&&c.push(null),e.previous=o,o&&(o.next=e),o=e,r.defineSkip(e.start),r.write(c),t.parser.lazy[e.start.line]){let e=r.events.length;for(;e--;)if(r.events[e][1].start.offset<i&&(!r.events[e][1].end||r.events[e][1].end.offset>i))return;const n=t.events.length;let o,c,u=n;for(;u--;)if("exit"===t.events[u][0]&&"chunkFlow"===t.events[u][1].type){if(o){c=t.events[u][1].end;break}o=!0}for(O(s),e=n;e<t.events.length;)t.events[e][1].end=Object.assign({},c),e++;a(t.events,u+1,0,t.events.slice(n)),t.events.length=e}}function O(r){let o=n.length;for(;o-- >r;){const r=n[o];t.containerState=r[1],r[0].exit.call(t,e)}n.length=r}function C(){r.write([null]),o=void 0,r=void 0,t.containerState._closeFlow=void 0}}},g={tokenize:function(e,t,n){return p(e,e.attempt(this.parser.constructs.document,t,n),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}},y={tokenize:function(e,t,n){return function(t){return(0,d.On)(t)?p(e,r,"linePrefix")(t):r(t)};function r(e){return null===e||(0,d.HP)(e)?t(e):n(e)}},partial:!0};function E(e){const t={};let n,r,o,i,s,c,u,l=-1;for(;++l<e.length;){for(;l in t;)l=t[l];if(n=e[l],l&&"chunkFlow"===n[1].type&&"listItemPrefix"===e[l-1][1].type&&(c=n[1]._tokenizer.events,o=0,o<c.length&&"lineEndingBlank"===c[o][1].type&&(o+=2),o<c.length&&"content"===c[o][1].type))for(;++o<c.length&&"content"!==c[o][1].type;)"chunkText"===c[o][1].type&&(c[o][1]._isInFirstContentOfListItem=!0,o++);if("enter"===n[0])n[1].contentType&&(Object.assign(t,S(e,l)),l=t[l],u=!0);else if(n[1]._container){for(o=l,r=void 0;o--&&(i=e[o],"lineEnding"===i[1].type||"lineEndingBlank"===i[1].type);)"enter"===i[0]&&(r&&(e[r][1].type="lineEndingBlank"),i[1].type="lineEnding",r=o);r&&(n[1].end=Object.assign({},e[r][1].start),s=e.slice(r,l),s.unshift(n),a(e,r,l-r+1,s))}}return!u}function S(e,t){const n=e[t][1],r=e[t][2];let o=t-1;const i=[],s=n._tokenizer||r.parser[n.contentType](n.start),c=s.events,u=[],l={};let h,d,p=-1,m=n,f=0,g=0;const y=[g];for(;m;){for(;e[++o][1]!==m;);i.push(o),m._tokenizer||(h=r.sliceStream(m),m.next||h.push(null),d&&s.defineSkip(m.start),m._isInFirstContentOfListItem&&(s._gfmTasklistFirstContentOfListItem=!0),s.write(h),m._isInFirstContentOfListItem&&(s._gfmTasklistFirstContentOfListItem=void 0)),d=m,m=m.next}for(m=n;++p<c.length;)"exit"===c[p][0]&&"enter"===c[p-1][0]&&c[p][1].type===c[p-1][1].type&&c[p][1].start.line!==c[p][1].end.line&&(g=p+1,y.push(g),m._tokenizer=void 0,m.previous=void 0,m=m.next);for(s.events=[],m?(m._tokenizer=void 0,m.previous=void 0):y.pop(),p=y.length;p--;){const t=c.slice(y[p],y[p+1]),n=i.pop();u.unshift([n,n+t.length-1]),a(e,n,2,t)}for(p=-1;++p<u.length;)l[f+u[p][0]]=f+u[p][1],f+=u[p][1]-u[p][0]-1;return l}const O={tokenize:function(e,t){let n;return function(t){return e.enter("content"),n=e.enter("chunkContent",{contentType:"content"}),r(t)};function r(t){return null===t?o(t):(0,d.HP)(t)?e.check(C,i,o)(t):(e.consume(t),r)}function o(n){return e.exit("chunkContent"),e.exit("content"),t(n)}function i(t){return e.consume(t),e.exit("chunkContent"),n.next=e.enter("chunkContent",{contentType:"content",previous:n}),n=n.next,r}},resolve:function(e){return E(e),e}},C={tokenize:function(e,t,n){const r=this;return function(t){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),p(e,o,"linePrefix")};function o(o){if(null===o||(0,d.HP)(o))return n(o);const i=r.events[r.events.length-1];return!r.parser.constructs.disable.null.includes("codeIndented")&&i&&"linePrefix"===i[1].type&&i[2].sliceSerialize(i[1],!0).length>=4?t(o):e.interrupt(r.parser.constructs.flow,n,t)(o)}},partial:!0},v={tokenize:function(e){const t=this,n=e.attempt(y,(function(r){if(null!==r)return e.enter("lineEndingBlank"),e.consume(r),e.exit("lineEndingBlank"),t.currentConstruct=void 0,n;e.consume(r)}),e.attempt(this.parser.constructs.flowInitial,r,p(e,e.attempt(this.parser.constructs.flow,r,e.attempt(O,r)),"linePrefix")));return n;function r(r){if(null!==r)return e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),t.currentConstruct=void 0,n;e.consume(r)}}},b={resolveAll:_()},w=T("string"),M=T("text");function T(e){return{tokenize:function(t){const n=this,r=this.parser.constructs[e],o=t.attempt(r,i,s);return i;function i(e){return c(e)?o(e):s(e)}function s(e){if(null!==e)return t.enter("data"),t.consume(e),a;t.consume(e)}function a(e){return c(e)?(t.exit("data"),o(e)):(t.consume(e),a)}function c(e){if(null===e)return!0;const t=r[e];let o=-1;if(t)for(;++o<t.length;){const e=t[o];if(!e.previous||e.previous.call(n,n.previous))return!0}return!1}},resolveAll:_("text"===e?A:void 0)}}function _(e){return function(t,n){let r,o=-1;for(;++o<=t.length;)void 0===r?t[o]&&"data"===t[o][1].type&&(r=o,o++):t[o]&&"data"===t[o][1].type||(o!==r+2&&(t[r][1].end=t[o-1][1].end,t.splice(r+2,o-r-2),o=r+2),r=void 0);return e?e(t,n):t}}function A(e,t){let n=0;for(;++n<=e.length;)if((n===e.length||"lineEnding"===e[n][1].type)&&"data"===e[n-1][1].type){const r=e[n-1][1],o=t.sliceStream(r);let i,s=o.length,a=-1,c=0;for(;s--;){const e=o[s];if("string"==typeof e){for(a=e.length;32===e.charCodeAt(a-1);)c++,a--;if(a)break;a=-1}else if(-2===e)i=!0,c++;else if(-1!==e){s++;break}}if(c){const o={type:n===e.length||i||c<2?"lineSuffix":"hardBreakTrailing",start:{line:r.end.line,column:r.end.column-c,offset:r.end.offset-c,_index:r.start._index+s,_bufferIndex:s?a:r.start._bufferIndex+a},end:Object.assign({},r.end)};r.end=Object.assign({},o.start),r.start.offset===r.end.offset?Object.assign(r,o):(e.splice(n,0,["enter",o,t],["exit",o,t]),n+=2)}n++}return e}function R(e,t,n){const r=[];let o=-1;for(;++o<e.length;){const i=e[o].resolveAll;i&&!r.includes(i)&&(t=i(t,n),r.push(i))}return t}function N(e,t,n){let r=Object.assign(n?Object.assign({},n):{line:1,column:1,offset:0},{_index:0,_bufferIndex:-1});const o={},i=[];let s=[],u=[],l=!0;const h={consume:function(e){(0,d.HP)(e)?(r.line++,r.column=1,r.offset+=-3===e?2:1,v()):-1!==e&&(r.column++,r.offset++),r._bufferIndex<0?r._index++:(r._bufferIndex++,r._bufferIndex===s[r._index].length&&(r._bufferIndex=-1,r._index++)),p.previous=e,l=!0},enter:function(e,t){const n=t||{};return n.type=e,n.start=y(),p.events.push(["enter",n,p]),u.push(n),n},exit:function(e){const t=u.pop();return t.end=y(),p.events.push(["exit",t,p]),t},attempt:O((function(e,t){C(e,t.from)})),check:O(S),interrupt:O(S,{interrupt:!0})},p={previous:null,code:null,containerState:{},events:[],parser:e,sliceStream:g,sliceSerialize:function(e,t){return function(e,t){let n=-1;const r=[];let o;for(;++n<e.length;){const i=e[n];let s;if("string"==typeof i)s=i;else switch(i){case-5:s="\r";break;case-4:s="\n";break;case-3:s="\r\n";break;case-2:s=t?" ":"\t";break;case-1:if(!t&&o)continue;s=" ";break;default:s=String.fromCharCode(i)}o=-2===i,r.push(s)}return r.join("")}(g(e),t)},now:y,defineSkip:function(e){o[e.line]=e.column,v()},write:function(e){return s=c(s,e),function(){let e;for(;r._index<s.length;){const t=s[r._index];if("string"==typeof t)for(e=r._index,r._bufferIndex<0&&(r._bufferIndex=0);r._index===e&&r._bufferIndex<t.length;)E(t.charCodeAt(r._bufferIndex));else E(t)}}(),null!==s[s.length-1]?[]:(C(t,0),p.events=R(i,p.events,p),p.events)}};let m,f=t.tokenize.call(p,h);return t.resolveAll&&i.push(t),p;function g(e){return function(e,t){const n=t.start._index,r=t.start._bufferIndex,o=t.end._index,i=t.end._bufferIndex;let s;if(n===o)s=[e[n].slice(r,i)];else{if(s=e.slice(n,o),r>-1){const e=s[0];"string"==typeof e?s[0]=e.slice(r):s.shift()}i>0&&s.push(e[o].slice(0,i))}return s}(s,e)}function y(){const{line:e,column:t,offset:n,_index:o,_bufferIndex:i}=r;return{line:e,column:t,offset:n,_index:o,_bufferIndex:i}}function E(e){l=void 0,m=e,f=f(e)}function S(e,t){t.restore()}function O(e,t){return function(n,o,i){let s,a,c,d;return Array.isArray(n)?f(n):"tokenize"in n?f([n]):(m=n,function(e){const t=null!==e&&m[e],n=null!==e&&m.null;return f([...Array.isArray(t)?t:t?[t]:[],...Array.isArray(n)?n:n?[n]:[]])(e)});var m;function f(e){return s=e,a=0,0===e.length?i:g(e[a])}function g(e){return function(n){return d=function(){const e=y(),t=p.previous,n=p.currentConstruct,o=p.events.length,i=Array.from(u);return{restore:function(){r=e,p.previous=t,p.currentConstruct=n,p.events.length=o,u=i,v()},from:o}}(),c=e,e.partial||(p.currentConstruct=e),e.name&&p.parser.constructs.disable.null.includes(e.name)?S():e.tokenize.call(t?Object.assign(Object.create(p),t):p,h,E,S)(n)}}function E(t){return l=!0,e(c,d),o}function S(e){return l=!0,d.restore(),++a<s.length?g(s[a]):i}}}function C(e,t){e.resolveAll&&!i.includes(e)&&i.push(e),e.resolve&&a(p.events,t,p.events.length-t,e.resolve(p.events.slice(t),p)),e.resolveTo&&(p.events=e.resolveTo(p.events,p))}function v(){r.line in o&&r.column<2&&(r.column=o[r.line],r.offset+=o[r.line]-1)}}const I={name:"thematicBreak",tokenize:function(e,t,n){let r,o=0;return function(t){return e.enter("thematicBreak"),function(e){return r=e,i(e)}(t)};function i(i){return i===r?(e.enter("thematicBreakSequence"),s(i)):o>=3&&(null===i||(0,d.HP)(i))?(e.exit("thematicBreak"),t(i)):n(i)}function s(t){return t===r?(e.consume(t),o++,s):(e.exit("thematicBreakSequence"),(0,d.On)(t)?p(e,i,"whitespace")(t):i(t))}}},x={name:"list",tokenize:function(e,t,n){const r=this,o=r.events[r.events.length-1];let i=o&&"linePrefix"===o[1].type?o[2].sliceSerialize(o[1],!0).length:0,s=0;return function(t){const o=r.containerState.type||(42===t||43===t||45===t?"listUnordered":"listOrdered");if("listUnordered"===o?!r.containerState.marker||t===r.containerState.marker:(0,d.BM)(t)){if(r.containerState.type||(r.containerState.type=o,e.enter(o,{_container:!0})),"listUnordered"===o)return e.enter("listItemPrefix"),42===t||45===t?e.check(I,n,c)(t):c(t);if(!r.interrupt||49===t)return e.enter("listItemPrefix"),e.enter("listItemValue"),a(t)}return n(t)};function a(t){return(0,d.BM)(t)&&++s<10?(e.consume(t),a):(!r.interrupt||s<2)&&(r.containerState.marker?t===r.containerState.marker:41===t||46===t)?(e.exit("listItemValue"),c(t)):n(t)}function c(t){return e.enter("listItemMarker"),e.consume(t),e.exit("listItemMarker"),r.containerState.marker=r.containerState.marker||t,e.check(y,r.interrupt?n:u,e.attempt(P,h,l))}function u(e){return r.containerState.initialBlankLine=!0,i++,h(e)}function l(t){return(0,d.On)(t)?(e.enter("listItemPrefixWhitespace"),e.consume(t),e.exit("listItemPrefixWhitespace"),h):n(t)}function h(n){return r.containerState.size=i+r.sliceSerialize(e.exit("listItemPrefix"),!0).length,t(n)}},continuation:{tokenize:function(e,t,n){const r=this;return r.containerState._closeFlow=void 0,e.check(y,(function(n){return r.containerState.furtherBlankLines=r.containerState.furtherBlankLines||r.containerState.initialBlankLine,p(e,t,"listItemIndent",r.containerState.size+1)(n)}),(function(n){return r.containerState.furtherBlankLines||!(0,d.On)(n)?(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,o(n)):(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,e.attempt(k,t,o)(n))}));function o(o){return r.containerState._closeFlow=!0,r.interrupt=void 0,p(e,e.attempt(x,t,n),"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(o)}}},exit:function(e){e.exit(this.containerState.type)}},P={tokenize:function(e,t,n){const r=this;return p(e,(function(e){const o=r.events[r.events.length-1];return!(0,d.On)(e)&&o&&"listItemPrefixWhitespace"===o[1].type?t(e):n(e)}),"listItemPrefixWhitespace",r.parser.constructs.disable.null.includes("codeIndented")?void 0:5)},partial:!0},k={tokenize:function(e,t,n){const r=this;return p(e,(function(e){const o=r.events[r.events.length-1];return o&&"listItemIndent"===o[1].type&&o[2].sliceSerialize(o[1],!0).length===r.containerState.size?t(e):n(e)}),"listItemIndent",r.containerState.size+1)},partial:!0},D={name:"blockQuote",tokenize:function(e,t,n){const r=this;return function(t){if(62===t){const n=r.containerState;return n.open||(e.enter("blockQuote",{_container:!0}),n.open=!0),e.enter("blockQuotePrefix"),e.enter("blockQuoteMarker"),e.consume(t),e.exit("blockQuoteMarker"),o}return n(t)};function o(n){return(0,d.On)(n)?(e.enter("blockQuotePrefixWhitespace"),e.consume(n),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),t):(e.exit("blockQuotePrefix"),t(n))}},continuation:{tokenize:function(e,t,n){const r=this;return function(t){return(0,d.On)(t)?p(e,o,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(t):o(t)};function o(r){return e.attempt(D,t,n)(r)}}},exit:function(e){e.exit("blockQuote")}};function L(e,t,n,r,o,i,s,a,c){const u=c||Number.POSITIVE_INFINITY;let l=0;return function(t){return 60===t?(e.enter(r),e.enter(o),e.enter(i),e.consume(t),e.exit(i),h):null===t||32===t||41===t||(0,d.JQ)(t)?n(t):(e.enter(r),e.enter(s),e.enter(a),e.enter("chunkString",{contentType:"string"}),f(t))};function h(n){return 62===n?(e.enter(i),e.consume(n),e.exit(i),e.exit(o),e.exit(r),t):(e.enter(a),e.enter("chunkString",{contentType:"string"}),p(n))}function p(t){return 62===t?(e.exit("chunkString"),e.exit(a),h(t)):null===t||60===t||(0,d.HP)(t)?n(t):(e.consume(t),92===t?m:p)}function m(t){return 60===t||62===t||92===t?(e.consume(t),p):p(t)}function f(o){return l||null!==o&&41!==o&&!(0,d.Ee)(o)?l<u&&40===o?(e.consume(o),l++,f):41===o?(e.consume(o),l--,f):null===o||32===o||40===o||(0,d.JQ)(o)?n(o):(e.consume(o),92===o?g:f):(e.exit("chunkString"),e.exit(a),e.exit(s),e.exit(r),t(o))}function g(t){return 40===t||41===t||92===t?(e.consume(t),f):f(t)}}function B(e,t,n,r,o,i){const s=this;let a,c=0;return function(t){return e.enter(r),e.enter(o),e.consume(t),e.exit(o),e.enter(i),u};function u(h){return c>999||null===h||91===h||93===h&&!a||94===h&&!c&&"_hiddenFootnoteSupport"in s.parser.constructs?n(h):93===h?(e.exit(i),e.enter(o),e.consume(h),e.exit(o),e.exit(r),t):(0,d.HP)(h)?(e.enter("lineEnding"),e.consume(h),e.exit("lineEnding"),u):(e.enter("chunkString",{contentType:"string"}),l(h))}function l(t){return null===t||91===t||93===t||(0,d.HP)(t)||c++>999?(e.exit("chunkString"),u(t)):(e.consume(t),a||(a=!(0,d.On)(t)),92===t?h:l)}function h(t){return 91===t||92===t||93===t?(e.consume(t),c++,l):l(t)}}function j(e,t,n,r,o,i){let s;return function(t){return 34===t||39===t||40===t?(e.enter(r),e.enter(o),e.consume(t),e.exit(o),s=40===t?41:t,a):n(t)};function a(n){return n===s?(e.enter(o),e.consume(n),e.exit(o),e.exit(r),t):(e.enter(i),c(n))}function c(t){return t===s?(e.exit(i),a(s)):null===t?n(t):(0,d.HP)(t)?(e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),p(e,c,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),u(t))}function u(t){return t===s||null===t||(0,d.HP)(t)?(e.exit("chunkString"),c(t)):(e.consume(t),92===t?l:u)}function l(t){return t===s||92===t?(e.consume(t),u):u(t)}}function F(e,t){let n;return function r(o){return(0,d.HP)(o)?(e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),n=!0,r):(0,d.On)(o)?p(e,r,n?"linePrefix":"lineSuffix")(o):t(o)}}function U(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const z={name:"definition",tokenize:function(e,t,n){const r=this;let o;return function(t){return e.enter("definition"),function(t){return B.call(r,e,i,n,"definitionLabel","definitionLabelMarker","definitionLabelString")(t)}(t)};function i(t){return o=U(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)),58===t?(e.enter("definitionMarker"),e.consume(t),e.exit("definitionMarker"),s):n(t)}function s(t){return(0,d.Ee)(t)?F(e,a)(t):a(t)}function a(t){return L(e,c,n,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(t)}function c(t){return e.attempt(V,u,u)(t)}function u(t){return(0,d.On)(t)?p(e,l,"whitespace")(t):l(t)}function l(i){return null===i||(0,d.HP)(i)?(e.exit("definition"),r.parser.defined.push(o),t(i)):n(i)}}},V={tokenize:function(e,t,n){return function(t){return(0,d.Ee)(t)?F(e,r)(t):n(t)};function r(t){return j(e,o,n,"definitionTitle","definitionTitleMarker","definitionTitleString")(t)}function o(t){return(0,d.On)(t)?p(e,i,"whitespace")(t):i(t)}function i(e){return null===e||(0,d.HP)(e)?t(e):n(e)}},partial:!0},$={name:"codeIndented",tokenize:function(e,t,n){const r=this;return function(t){return e.enter("codeIndented"),p(e,o,"linePrefix",5)(t)};function o(e){const t=r.events[r.events.length-1];return t&&"linePrefix"===t[1].type&&t[2].sliceSerialize(t[1],!0).length>=4?i(e):n(e)}function i(t){return null===t?a(t):(0,d.HP)(t)?e.attempt(W,i,a)(t):(e.enter("codeFlowValue"),s(t))}function s(t){return null===t||(0,d.HP)(t)?(e.exit("codeFlowValue"),i(t)):(e.consume(t),s)}function a(n){return e.exit("codeIndented"),t(n)}}},W={tokenize:function(e,t,n){const r=this;return o;function o(t){return r.parser.lazy[r.now().line]?n(t):(0,d.HP)(t)?(e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),o):p(e,i,"linePrefix",5)(t)}function i(e){const i=r.events[r.events.length-1];return i&&"linePrefix"===i[1].type&&i[2].sliceSerialize(i[1],!0).length>=4?t(e):(0,d.HP)(e)?o(e):n(e)}},partial:!0},G={name:"headingAtx",tokenize:function(e,t,n){let r=0;return function(t){return e.enter("atxHeading"),function(t){return e.enter("atxHeadingSequence"),o(t)}(t)};function o(t){return 35===t&&r++<6?(e.consume(t),o):null===t||(0,d.Ee)(t)?(e.exit("atxHeadingSequence"),i(t)):n(t)}function i(n){return 35===n?(e.enter("atxHeadingSequence"),s(n)):null===n||(0,d.HP)(n)?(e.exit("atxHeading"),t(n)):(0,d.On)(n)?p(e,i,"whitespace")(n):(e.enter("atxHeadingText"),a(n))}function s(t){return 35===t?(e.consume(t),s):(e.exit("atxHeadingSequence"),i(t))}function a(t){return null===t||35===t||(0,d.Ee)(t)?(e.exit("atxHeadingText"),i(t)):(e.consume(t),a)}},resolve:function(e,t){let n,r,o=e.length-2,i=3;return"whitespace"===e[i][1].type&&(i+=2),o-2>i&&"whitespace"===e[o][1].type&&(o-=2),"atxHeadingSequence"===e[o][1].type&&(i===o-1||o-4>i&&"whitespace"===e[o-2][1].type)&&(o-=i+1===o?2:4),o>i&&(n={type:"atxHeadingText",start:e[i][1].start,end:e[o][1].end},r={type:"chunkText",start:e[i][1].start,end:e[o][1].end,contentType:"text"},a(e,i,o-i+1,[["enter",n,t],["enter",r,t],["exit",r,t],["exit",n,t]])),e}},H={name:"setextUnderline",tokenize:function(e,t,n){const r=this;let o;return function(t){let s,a=r.events.length;for(;a--;)if("lineEnding"!==r.events[a][1].type&&"linePrefix"!==r.events[a][1].type&&"content"!==r.events[a][1].type){s="paragraph"===r.events[a][1].type;break}return r.parser.lazy[r.now().line]||!r.interrupt&&!s?n(t):(e.enter("setextHeadingLine"),o=t,function(t){return e.enter("setextHeadingLineSequence"),i(t)}(t))};function i(t){return t===o?(e.consume(t),i):(e.exit("setextHeadingLineSequence"),(0,d.On)(t)?p(e,s,"lineSuffix")(t):s(t))}function s(r){return null===r||(0,d.HP)(r)?(e.exit("setextHeadingLine"),t(r)):n(r)}},resolveTo:function(e,t){let n,r,o,i=e.length;for(;i--;)if("enter"===e[i][0]){if("content"===e[i][1].type){n=i;break}"paragraph"===e[i][1].type&&(r=i)}else"content"===e[i][1].type&&e.splice(i,1),o||"definition"!==e[i][1].type||(o=i);const s={type:"setextHeading",start:Object.assign({},e[r][1].start),end:Object.assign({},e[e.length-1][1].end)};return e[r][1].type="setextHeadingText",o?(e.splice(r,0,["enter",s,t]),e.splice(o+1,0,["exit",e[n][1],t]),e[n][1].end=Object.assign({},e[o][1].end)):e[n][1]=s,e.push(["exit",s,t]),e}},q=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],K=["pre","script","style","textarea"],Y={name:"htmlFlow",tokenize:function(e,t,n){const r=this;let o,i,s,a,c;return function(t){return function(t){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(t),u}(t)};function u(a){return 33===a?(e.consume(a),l):47===a?(e.consume(a),i=!0,m):63===a?(e.consume(a),o=3,r.interrupt?t:D):(0,d.CW)(a)?(e.consume(a),s=String.fromCharCode(a),f):n(a)}function l(i){return 45===i?(e.consume(i),o=2,h):91===i?(e.consume(i),o=5,a=0,p):(0,d.CW)(i)?(e.consume(i),o=4,r.interrupt?t:D):n(i)}function h(o){return 45===o?(e.consume(o),r.interrupt?t:D):n(o)}function p(o){return o==="CDATA[".charCodeAt(a++)?(e.consume(o),6===a?r.interrupt?t:_:p):n(o)}function m(t){return(0,d.CW)(t)?(e.consume(t),s=String.fromCharCode(t),f):n(t)}function f(a){if(null===a||47===a||62===a||(0,d.Ee)(a)){const c=47===a,u=s.toLowerCase();return c||i||!K.includes(u)?q.includes(s.toLowerCase())?(o=6,c?(e.consume(a),g):r.interrupt?t(a):_(a)):(o=7,r.interrupt&&!r.parser.lazy[r.now().line]?n(a):i?y(a):E(a)):(o=1,r.interrupt?t(a):_(a))}return 45===a||(0,d.lV)(a)?(e.consume(a),s+=String.fromCharCode(a),f):n(a)}function g(o){return 62===o?(e.consume(o),r.interrupt?t:_):n(o)}function y(t){return(0,d.On)(t)?(e.consume(t),y):M(t)}function E(t){return 47===t?(e.consume(t),M):58===t||95===t||(0,d.CW)(t)?(e.consume(t),S):(0,d.On)(t)?(e.consume(t),E):M(t)}function S(t){return 45===t||46===t||58===t||95===t||(0,d.lV)(t)?(e.consume(t),S):O(t)}function O(t){return 61===t?(e.consume(t),C):(0,d.On)(t)?(e.consume(t),O):E(t)}function C(t){return null===t||60===t||61===t||62===t||96===t?n(t):34===t||39===t?(e.consume(t),c=t,v):(0,d.On)(t)?(e.consume(t),C):b(t)}function v(t){return t===c?(e.consume(t),c=null,w):null===t||(0,d.HP)(t)?n(t):(e.consume(t),v)}function b(t){return null===t||34===t||39===t||47===t||60===t||61===t||62===t||96===t||(0,d.Ee)(t)?O(t):(e.consume(t),b)}function w(e){return 47===e||62===e||(0,d.On)(e)?E(e):n(e)}function M(t){return 62===t?(e.consume(t),T):n(t)}function T(t){return null===t||(0,d.HP)(t)?_(t):(0,d.On)(t)?(e.consume(t),T):n(t)}function _(t){return 45===t&&2===o?(e.consume(t),I):60===t&&1===o?(e.consume(t),x):62===t&&4===o?(e.consume(t),L):63===t&&3===o?(e.consume(t),D):93===t&&5===o?(e.consume(t),k):!(0,d.HP)(t)||6!==o&&7!==o?null===t||(0,d.HP)(t)?(e.exit("htmlFlowData"),A(t)):(e.consume(t),_):(e.exit("htmlFlowData"),e.check(Q,B,A)(t))}function A(t){return e.check(X,R,B)(t)}function R(t){return e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),N}function N(t){return null===t||(0,d.HP)(t)?A(t):(e.enter("htmlFlowData"),_(t))}function I(t){return 45===t?(e.consume(t),D):_(t)}function x(t){return 47===t?(e.consume(t),s="",P):_(t)}function P(t){if(62===t){const n=s.toLowerCase();return K.includes(n)?(e.consume(t),L):_(t)}return(0,d.CW)(t)&&s.length<8?(e.consume(t),s+=String.fromCharCode(t),P):_(t)}function k(t){return 93===t?(e.consume(t),D):_(t)}function D(t){return 62===t?(e.consume(t),L):45===t&&2===o?(e.consume(t),D):_(t)}function L(t){return null===t||(0,d.HP)(t)?(e.exit("htmlFlowData"),B(t)):(e.consume(t),L)}function B(n){return e.exit("htmlFlow"),t(n)}},resolveTo:function(e){let t=e.length;for(;t--&&("enter"!==e[t][0]||"htmlFlow"!==e[t][1].type););return t>1&&"linePrefix"===e[t-2][1].type&&(e[t][1].start=e[t-2][1].start,e[t+1][1].start=e[t-2][1].start,e.splice(t-2,2)),e},concrete:!0},Q={tokenize:function(e,t,n){return function(r){return e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),e.attempt(y,t,n)}},partial:!0},X={tokenize:function(e,t,n){const r=this;return function(t){return(0,d.HP)(t)?(e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),o):n(t)};function o(e){return r.parser.lazy[r.now().line]?n(e):t(e)}},partial:!0},J={tokenize:function(e,t,n){const r=this;return function(t){return null===t?n(t):(e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),o)};function o(e){return r.parser.lazy[r.now().line]?n(e):t(e)}},partial:!0},Z={name:"codeFenced",tokenize:function(e,t,n){const r=this,o={tokenize:function(e,t,n){let o=0;return function(t){return e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),s};function s(t){return e.enter("codeFencedFence"),(0,d.On)(t)?p(e,c,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(t):c(t)}function c(t){return t===i?(e.enter("codeFencedFenceSequence"),u(t)):n(t)}function u(t){return t===i?(o++,e.consume(t),u):o>=a?(e.exit("codeFencedFenceSequence"),(0,d.On)(t)?p(e,l,"whitespace")(t):l(t)):n(t)}function l(r){return null===r||(0,d.HP)(r)?(e.exit("codeFencedFence"),t(r)):n(r)}},partial:!0};let i,s=0,a=0;return function(t){return function(t){const n=r.events[r.events.length-1];return s=n&&"linePrefix"===n[1].type?n[2].sliceSerialize(n[1],!0).length:0,i=t,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),c(t)}(t)};function c(t){return t===i?(a++,e.consume(t),c):a<3?n(t):(e.exit("codeFencedFenceSequence"),(0,d.On)(t)?p(e,u,"whitespace")(t):u(t))}function u(n){return null===n||(0,d.HP)(n)?(e.exit("codeFencedFence"),r.interrupt?t(n):e.check(J,f,O)(n)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),l(n))}function l(t){return null===t||(0,d.HP)(t)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),u(t)):(0,d.On)(t)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),p(e,h,"whitespace")(t)):96===t&&t===i?n(t):(e.consume(t),l)}function h(t){return null===t||(0,d.HP)(t)?u(t):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),m(t))}function m(t){return null===t||(0,d.HP)(t)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),u(t)):96===t&&t===i?n(t):(e.consume(t),m)}function f(t){return e.attempt(o,O,g)(t)}function g(t){return e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),y}function y(t){return s>0&&(0,d.On)(t)?p(e,E,"linePrefix",s+1)(t):E(t)}function E(t){return null===t||(0,d.HP)(t)?e.check(J,f,O)(t):(e.enter("codeFlowValue"),S(t))}function S(t){return null===t||(0,d.HP)(t)?(e.exit("codeFlowValue"),E(t)):(e.consume(t),S)}function O(n){return e.exit("codeFenced"),t(n)}},concrete:!0};var ee=n(98915);const te={name:"characterReference",tokenize:function(e,t,n){const r=this;let o,i,s=0;return function(t){return e.enter("characterReference"),e.enter("characterReferenceMarker"),e.consume(t),e.exit("characterReferenceMarker"),a};function a(t){return 35===t?(e.enter("characterReferenceMarkerNumeric"),e.consume(t),e.exit("characterReferenceMarkerNumeric"),c):(e.enter("characterReferenceValue"),o=31,i=d.lV,u(t))}function c(t){return 88===t||120===t?(e.enter("characterReferenceMarkerHexadecimal"),e.consume(t),e.exit("characterReferenceMarkerHexadecimal"),e.enter("characterReferenceValue"),o=6,i=d.ok,u):(e.enter("characterReferenceValue"),o=7,i=d.BM,u(t))}function u(a){if(59===a&&s){const o=e.exit("characterReferenceValue");return i!==d.lV||(0,ee.s)(r.sliceSerialize(o))?(e.enter("characterReferenceMarker"),e.consume(a),e.exit("characterReferenceMarker"),e.exit("characterReference"),t):n(a)}return i(a)&&s++<o?(e.consume(a),u):n(a)}}},ne={name:"characterEscape",tokenize:function(e,t,n){return function(t){return e.enter("characterEscape"),e.enter("escapeMarker"),e.consume(t),e.exit("escapeMarker"),r};function r(r){return(0,d.ol)(r)?(e.enter("characterEscapeValue"),e.consume(r),e.exit("characterEscapeValue"),e.exit("characterEscape"),t):n(r)}}},re={name:"lineEnding",tokenize:function(e,t){return function(n){return e.enter("lineEnding"),e.consume(n),e.exit("lineEnding"),p(e,t,"linePrefix")}}},oe={name:"labelEnd",tokenize:function(e,t,n){const r=this;let o,i,s=r.events.length;for(;s--;)if(("labelImage"===r.events[s][1].type||"labelLink"===r.events[s][1].type)&&!r.events[s][1]._balanced){o=r.events[s][1];break}return function(t){return o?o._inactive?l(t):(i=r.parser.defined.includes(U(r.sliceSerialize({start:o.end,end:r.now()}))),e.enter("labelEnd"),e.enter("labelMarker"),e.consume(t),e.exit("labelMarker"),e.exit("labelEnd"),a):n(t)};function a(t){return 40===t?e.attempt(ie,u,i?u:l)(t):91===t?e.attempt(se,u,i?c:l)(t):i?u(t):l(t)}function c(t){return e.attempt(ae,u,l)(t)}function u(e){return t(e)}function l(e){return o._balanced=!0,n(e)}},resolveTo:function(e,t){let n,r,o,i,s=e.length,u=0;for(;s--;)if(n=e[s][1],r){if("link"===n.type||"labelLink"===n.type&&n._inactive)break;"enter"===e[s][0]&&"labelLink"===n.type&&(n._inactive=!0)}else if(o){if("enter"===e[s][0]&&("labelImage"===n.type||"labelLink"===n.type)&&!n._balanced&&(r=s,"labelLink"!==n.type)){u=2;break}}else"labelEnd"===n.type&&(o=s);const l={type:"labelLink"===e[r][1].type?"link":"image",start:Object.assign({},e[r][1].start),end:Object.assign({},e[e.length-1][1].end)},h={type:"label",start:Object.assign({},e[r][1].start),end:Object.assign({},e[o][1].end)},d={type:"labelText",start:Object.assign({},e[r+u+2][1].end),end:Object.assign({},e[o-2][1].start)};return i=[["enter",l,t],["enter",h,t]],i=c(i,e.slice(r+1,r+u+3)),i=c(i,[["enter",d,t]]),i=c(i,R(t.parser.constructs.insideSpan.null,e.slice(r+u+4,o-3),t)),i=c(i,[["exit",d,t],e[o-2],e[o-1],["exit",h,t]]),i=c(i,e.slice(o+1)),i=c(i,[["exit",l,t]]),a(e,r,e.length,i),e},resolveAll:function(e){let t=-1;for(;++t<e.length;){const n=e[t][1];"labelImage"!==n.type&&"labelLink"!==n.type&&"labelEnd"!==n.type||(e.splice(t+1,"labelImage"===n.type?4:2),n.type="data",t++)}return e}},ie={tokenize:function(e,t,n){return function(t){return e.enter("resource"),e.enter("resourceMarker"),e.consume(t),e.exit("resourceMarker"),r};function r(t){return(0,d.Ee)(t)?F(e,o)(t):o(t)}function o(t){return 41===t?u(t):L(e,i,s,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(t)}function i(t){return(0,d.Ee)(t)?F(e,a)(t):u(t)}function s(e){return n(e)}function a(t){return 34===t||39===t||40===t?j(e,c,n,"resourceTitle","resourceTitleMarker","resourceTitleString")(t):u(t)}function c(t){return(0,d.Ee)(t)?F(e,u)(t):u(t)}function u(r){return 41===r?(e.enter("resourceMarker"),e.consume(r),e.exit("resourceMarker"),e.exit("resource"),t):n(r)}}},se={tokenize:function(e,t,n){const r=this;return function(t){return B.call(r,e,o,i,"reference","referenceMarker","referenceString")(t)};function o(e){return r.parser.defined.includes(U(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)))?t(e):n(e)}function i(e){return n(e)}}},ae={tokenize:function(e,t,n){return function(t){return e.enter("reference"),e.enter("referenceMarker"),e.consume(t),e.exit("referenceMarker"),r};function r(r){return 93===r?(e.enter("referenceMarker"),e.consume(r),e.exit("referenceMarker"),e.exit("reference"),t):n(r)}}},ce={name:"labelStartImage",tokenize:function(e,t,n){const r=this;return function(t){return e.enter("labelImage"),e.enter("labelImageMarker"),e.consume(t),e.exit("labelImageMarker"),o};function o(t){return 91===t?(e.enter("labelMarker"),e.consume(t),e.exit("labelMarker"),e.exit("labelImage"),i):n(t)}function i(e){return 94===e&&"_hiddenFootnoteSupport"in r.parser.constructs?n(e):t(e)}},resolveAll:oe.resolveAll};function ue(e){return null===e||(0,d.Ee)(e)||(0,d.Ny)(e)?1:(0,d.es)(e)?2:void 0}const le={name:"attention",tokenize:function(e,t){const n=this.parser.constructs.attentionMarkers.null,r=this.previous,o=ue(r);let i;return function(t){return i=t,e.enter("attentionSequence"),s(t)};function s(a){if(a===i)return e.consume(a),s;const c=e.exit("attentionSequence"),u=ue(a),l=!u||2===u&&o||n.includes(a),h=!o||2===o&&u||n.includes(r);return c._open=Boolean(42===i?l:l&&(o||!h)),c._close=Boolean(42===i?h:h&&(u||!l)),t(a)}},resolveAll:function(e,t){let n,r,o,i,s,u,l,h,d=-1;for(;++d<e.length;)if("enter"===e[d][0]&&"attentionSequence"===e[d][1].type&&e[d][1]._close)for(n=d;n--;)if("exit"===e[n][0]&&"attentionSequence"===e[n][1].type&&e[n][1]._open&&t.sliceSerialize(e[n][1]).charCodeAt(0)===t.sliceSerialize(e[d][1]).charCodeAt(0)){if((e[n][1]._close||e[d][1]._open)&&(e[d][1].end.offset-e[d][1].start.offset)%3&&!((e[n][1].end.offset-e[n][1].start.offset+e[d][1].end.offset-e[d][1].start.offset)%3))continue;u=e[n][1].end.offset-e[n][1].start.offset>1&&e[d][1].end.offset-e[d][1].start.offset>1?2:1;const p=Object.assign({},e[n][1].end),m=Object.assign({},e[d][1].start);he(p,-u),he(m,u),i={type:u>1?"strongSequence":"emphasisSequence",start:p,end:Object.assign({},e[n][1].end)},s={type:u>1?"strongSequence":"emphasisSequence",start:Object.assign({},e[d][1].start),end:m},o={type:u>1?"strongText":"emphasisText",start:Object.assign({},e[n][1].end),end:Object.assign({},e[d][1].start)},r={type:u>1?"strong":"emphasis",start:Object.assign({},i.start),end:Object.assign({},s.end)},e[n][1].end=Object.assign({},i.start),e[d][1].start=Object.assign({},s.end),l=[],e[n][1].end.offset-e[n][1].start.offset&&(l=c(l,[["enter",e[n][1],t],["exit",e[n][1],t]])),l=c(l,[["enter",r,t],["enter",i,t],["exit",i,t],["enter",o,t]]),l=c(l,R(t.parser.constructs.insideSpan.null,e.slice(n+1,d),t)),l=c(l,[["exit",o,t],["enter",s,t],["exit",s,t],["exit",r,t]]),e[d][1].end.offset-e[d][1].start.offset?(h=2,l=c(l,[["enter",e[d][1],t],["exit",e[d][1],t]])):h=0,a(e,n-1,d-n+3,l),d=n+l.length-h-2;break}for(d=-1;++d<e.length;)"attentionSequence"===e[d][1].type&&(e[d][1].type="data");return e}};function he(e,t){e.column+=t,e.offset+=t,e._bufferIndex+=t}const de={name:"autolink",tokenize:function(e,t,n){let r=0;return function(t){return e.enter("autolink"),e.enter("autolinkMarker"),e.consume(t),e.exit("autolinkMarker"),e.enter("autolinkProtocol"),o};function o(t){return(0,d.CW)(t)?(e.consume(t),i):c(t)}function i(e){return 43===e||45===e||46===e||(0,d.lV)(e)?(r=1,s(e)):c(e)}function s(t){return 58===t?(e.consume(t),r=0,a):(43===t||45===t||46===t||(0,d.lV)(t))&&r++<32?(e.consume(t),s):(r=0,c(t))}function a(r){return 62===r?(e.exit("autolinkProtocol"),e.enter("autolinkMarker"),e.consume(r),e.exit("autolinkMarker"),e.exit("autolink"),t):null===r||32===r||60===r||(0,d.JQ)(r)?n(r):(e.consume(r),a)}function c(t){return 64===t?(e.consume(t),u):(0,d.cx)(t)?(e.consume(t),c):n(t)}function u(e){return(0,d.lV)(e)?l(e):n(e)}function l(n){return 46===n?(e.consume(n),r=0,u):62===n?(e.exit("autolinkProtocol").type="autolinkEmail",e.enter("autolinkMarker"),e.consume(n),e.exit("autolinkMarker"),e.exit("autolink"),t):h(n)}function h(t){if((45===t||(0,d.lV)(t))&&r++<63){const n=45===t?h:l;return e.consume(t),n}return n(t)}}},pe={name:"htmlText",tokenize:function(e,t,n){const r=this;let o,i,s;return function(t){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(t),a};function a(t){return 33===t?(e.consume(t),c):47===t?(e.consume(t),v):63===t?(e.consume(t),O):(0,d.CW)(t)?(e.consume(t),M):n(t)}function c(t){return 45===t?(e.consume(t),u):91===t?(e.consume(t),i=0,f):(0,d.CW)(t)?(e.consume(t),S):n(t)}function u(t){return 45===t?(e.consume(t),m):n(t)}function l(t){return null===t?n(t):45===t?(e.consume(t),h):(0,d.HP)(t)?(s=l,k(t)):(e.consume(t),l)}function h(t){return 45===t?(e.consume(t),m):l(t)}function m(e){return 62===e?P(e):45===e?h(e):l(e)}function f(t){return t==="CDATA[".charCodeAt(i++)?(e.consume(t),6===i?g:f):n(t)}function g(t){return null===t?n(t):93===t?(e.consume(t),y):(0,d.HP)(t)?(s=g,k(t)):(e.consume(t),g)}function y(t){return 93===t?(e.consume(t),E):g(t)}function E(t){return 62===t?P(t):93===t?(e.consume(t),E):g(t)}function S(t){return null===t||62===t?P(t):(0,d.HP)(t)?(s=S,k(t)):(e.consume(t),S)}function O(t){return null===t?n(t):63===t?(e.consume(t),C):(0,d.HP)(t)?(s=O,k(t)):(e.consume(t),O)}function C(e){return 62===e?P(e):O(e)}function v(t){return(0,d.CW)(t)?(e.consume(t),b):n(t)}function b(t){return 45===t||(0,d.lV)(t)?(e.consume(t),b):w(t)}function w(t){return(0,d.HP)(t)?(s=w,k(t)):(0,d.On)(t)?(e.consume(t),w):P(t)}function M(t){return 45===t||(0,d.lV)(t)?(e.consume(t),M):47===t||62===t||(0,d.Ee)(t)?T(t):n(t)}function T(t){return 47===t?(e.consume(t),P):58===t||95===t||(0,d.CW)(t)?(e.consume(t),_):(0,d.HP)(t)?(s=T,k(t)):(0,d.On)(t)?(e.consume(t),T):P(t)}function _(t){return 45===t||46===t||58===t||95===t||(0,d.lV)(t)?(e.consume(t),_):A(t)}function A(t){return 61===t?(e.consume(t),R):(0,d.HP)(t)?(s=A,k(t)):(0,d.On)(t)?(e.consume(t),A):T(t)}function R(t){return null===t||60===t||61===t||62===t||96===t?n(t):34===t||39===t?(e.consume(t),o=t,N):(0,d.HP)(t)?(s=R,k(t)):(0,d.On)(t)?(e.consume(t),R):(e.consume(t),I)}function N(t){return t===o?(e.consume(t),o=void 0,x):null===t?n(t):(0,d.HP)(t)?(s=N,k(t)):(e.consume(t),N)}function I(t){return null===t||34===t||39===t||60===t||61===t||96===t?n(t):47===t||62===t||(0,d.Ee)(t)?T(t):(e.consume(t),I)}function x(e){return 47===e||62===e||(0,d.Ee)(e)?T(e):n(e)}function P(r){return 62===r?(e.consume(r),e.exit("htmlTextData"),e.exit("htmlText"),t):n(r)}function k(t){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),D}function D(t){return(0,d.On)(t)?p(e,L,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(t):L(t)}function L(t){return e.enter("htmlTextData"),s(t)}}},me={name:"labelStartLink",tokenize:function(e,t,n){const r=this;return function(t){return e.enter("labelLink"),e.enter("labelMarker"),e.consume(t),e.exit("labelMarker"),e.exit("labelLink"),o};function o(e){return 94===e&&"_hiddenFootnoteSupport"in r.parser.constructs?n(e):t(e)}},resolveAll:oe.resolveAll},fe={name:"hardBreakEscape",tokenize:function(e,t,n){return function(t){return e.enter("hardBreakEscape"),e.consume(t),r};function r(r){return(0,d.HP)(r)?(e.exit("hardBreakEscape"),t(r)):n(r)}}},ge={name:"codeText",tokenize:function(e,t,n){let r,o,i=0;return function(t){return e.enter("codeText"),e.enter("codeTextSequence"),s(t)};function s(t){return 96===t?(e.consume(t),i++,s):(e.exit("codeTextSequence"),a(t))}function a(t){return null===t?n(t):32===t?(e.enter("space"),e.consume(t),e.exit("space"),a):96===t?(o=e.enter("codeTextSequence"),r=0,u(t)):(0,d.HP)(t)?(e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),a):(e.enter("codeTextData"),c(t))}function c(t){return null===t||32===t||96===t||(0,d.HP)(t)?(e.exit("codeTextData"),a(t)):(e.consume(t),c)}function u(n){return 96===n?(e.consume(n),r++,u):r===i?(e.exit("codeTextSequence"),e.exit("codeText"),t(n)):(o.type="codeTextData",c(n))}},resolve:function(e){let t,n,r=e.length-4,o=3;if(!("lineEnding"!==e[o][1].type&&"space"!==e[o][1].type||"lineEnding"!==e[r][1].type&&"space"!==e[r][1].type))for(t=o;++t<r;)if("codeTextData"===e[t][1].type){e[o][1].type="codeTextPadding",e[r][1].type="codeTextPadding",o+=2,r-=2;break}for(t=o-1,r++;++t<=r;)void 0===n?t!==r&&"lineEnding"!==e[t][1].type&&(n=t):t!==r&&"lineEnding"!==e[t][1].type||(e[n][1].type="codeTextData",t!==n+2&&(e[n][1].end=e[t-1][1].end,e.splice(n+2,t-n-2),r-=t-n-2,t=n+2),n=void 0);return e},previous:function(e){return 96!==e||"characterEscape"===this.events[this.events.length-1][1].type}},ye={42:x,43:x,45:x,48:x,49:x,50:x,51:x,52:x,53:x,54:x,55:x,56:x,57:x,62:D},Ee={91:z},Se={[-2]:$,[-1]:$,32:$},Oe={35:G,42:I,45:[H,I],60:Y,61:H,95:I,96:Z,126:Z},Ce={38:te,92:ne},ve={[-5]:re,[-4]:re,[-3]:re,33:ce,38:te,42:le,60:[de,pe],91:me,92:[fe,ne],93:oe,95:le,96:ge},be={null:[le,b]},we={null:[42,95]},Me={null:[]};const Te=/[\0\t\n\r]/g;function _e(e,t){const n=Number.parseInt(e,t);return n<9||11===n||n>13&&n<32||n>126&&n<160||n>55295&&n<57344||n>64975&&n<65008||!(65535&~n)||65534==(65535&n)||n>1114111?"�":String.fromCharCode(n)}const Ae=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function Re(e,t,n){if(t)return t;if(35===n.charCodeAt(0)){const e=n.charCodeAt(1),t=120===e||88===e;return _e(n.slice(t?2:1),t?16:10)}return(0,ee.s)(n)||e}var Ne=n(94271);const Ie={}.hasOwnProperty,xe=function(e,t,n){return"string"!=typeof t&&(n=t,t=void 0),function(e){const t={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:c(v),autolinkProtocol:m,autolinkEmail:m,atxHeading:c(S),blockQuote:c((function(){return{type:"blockquote",children:[]}})),characterEscape:m,characterReference:m,codeFenced:c(E),codeFencedFenceInfo:u,codeFencedFenceMeta:u,codeIndented:c(E,u),codeText:c((function(){return{type:"inlineCode",value:""}}),u),codeTextData:m,data:m,codeFlowValue:m,definition:c((function(){return{type:"definition",identifier:"",label:null,title:null,url:""}})),definitionDestinationString:u,definitionLabelString:u,definitionTitleString:u,emphasis:c((function(){return{type:"emphasis",children:[]}})),hardBreakEscape:c(O),hardBreakTrailing:c(O),htmlFlow:c(C,u),htmlFlowData:m,htmlText:c(C,u),htmlTextData:m,image:c((function(){return{type:"image",title:null,url:"",alt:null}})),label:u,link:c(v),listItem:c((function(e){return{type:"listItem",spread:e._spread,checked:null,children:[]}})),listItemValue:function(e){a("expectingFirstListItemValue")&&(this.stack[this.stack.length-2].start=Number.parseInt(this.sliceSerialize(e),10),s("expectingFirstListItemValue"))},listOrdered:c(b,(function(){s("expectingFirstListItemValue",!0)})),listUnordered:c(b),paragraph:c((function(){return{type:"paragraph",children:[]}})),reference:function(){s("referenceType","collapsed")},referenceString:u,resourceDestinationString:u,resourceTitleString:u,setextHeading:c(S),strong:c((function(){return{type:"strong",children:[]}})),thematicBreak:c((function(){return{type:"thematicBreak"}}))},exit:{atxHeading:h(),atxHeadingSequence:function(e){const t=this.stack[this.stack.length-1];if(!t.depth){const n=this.sliceSerialize(e).length;t.depth=n}},autolink:h(),autolinkEmail:function(e){f.call(this,e),this.stack[this.stack.length-1].url="mailto:"+this.sliceSerialize(e)},autolinkProtocol:function(e){f.call(this,e),this.stack[this.stack.length-1].url=this.sliceSerialize(e)},blockQuote:h(),characterEscapeValue:f,characterReferenceMarkerHexadecimal:y,characterReferenceMarkerNumeric:y,characterReferenceValue:function(e){const t=this.sliceSerialize(e),n=a("characterReferenceType");let r;n?(r=_e(t,"characterReferenceMarkerNumeric"===n?10:16),s("characterReferenceType")):r=(0,ee.s)(t);const o=this.stack.pop();o.value+=r,o.position.end=Pe(e.end)},codeFenced:h((function(){const e=this.resume();this.stack[this.stack.length-1].value=e.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),s("flowCodeInside")})),codeFencedFence:function(){a("flowCodeInside")||(this.buffer(),s("flowCodeInside",!0))},codeFencedFenceInfo:function(){const e=this.resume();this.stack[this.stack.length-1].lang=e},codeFencedFenceMeta:function(){const e=this.resume();this.stack[this.stack.length-1].meta=e},codeFlowValue:f,codeIndented:h((function(){const e=this.resume();this.stack[this.stack.length-1].value=e.replace(/(\r?\n|\r)$/g,"")})),codeText:h((function(){const e=this.resume();this.stack[this.stack.length-1].value=e})),codeTextData:f,data:f,definition:h(),definitionDestinationString:function(){const e=this.resume();this.stack[this.stack.length-1].url=e},definitionLabelString:function(e){const t=this.resume(),n=this.stack[this.stack.length-1];n.label=t,n.identifier=U(this.sliceSerialize(e)).toLowerCase()},definitionTitleString:function(){const e=this.resume();this.stack[this.stack.length-1].title=e},emphasis:h(),hardBreakEscape:h(g),hardBreakTrailing:h(g),htmlFlow:h((function(){const e=this.resume();this.stack[this.stack.length-1].value=e})),htmlFlowData:f,htmlText:h((function(){const e=this.resume();this.stack[this.stack.length-1].value=e})),htmlTextData:f,image:h((function(){const e=this.stack[this.stack.length-1];if(a("inReference")){const t=a("referenceType")||"shortcut";e.type+="Reference",e.referenceType=t,delete e.url,delete e.title}else delete e.identifier,delete e.label;s("referenceType")})),label:function(){const e=this.stack[this.stack.length-1],t=this.resume(),n=this.stack[this.stack.length-1];if(s("inReference",!0),"link"===n.type){const t=e.children;n.children=t}else n.alt=t},labelText:function(e){const t=this.sliceSerialize(e),n=this.stack[this.stack.length-2];n.label=function(e){return e.replace(Ae,Re)}(t),n.identifier=U(t).toLowerCase()},lineEnding:function(e){const n=this.stack[this.stack.length-1];if(a("atHardBreak"))return n.children[n.children.length-1].position.end=Pe(e.end),void s("atHardBreak");!a("setextHeadingSlurpLineEnding")&&t.canContainEols.includes(n.type)&&(m.call(this,e),f.call(this,e))},link:h((function(){const e=this.stack[this.stack.length-1];if(a("inReference")){const t=a("referenceType")||"shortcut";e.type+="Reference",e.referenceType=t,delete e.url,delete e.title}else delete e.identifier,delete e.label;s("referenceType")})),listItem:h(),listOrdered:h(),listUnordered:h(),paragraph:h(),referenceString:function(e){const t=this.resume(),n=this.stack[this.stack.length-1];n.label=t,n.identifier=U(this.sliceSerialize(e)).toLowerCase(),s("referenceType","full")},resourceDestinationString:function(){const e=this.resume();this.stack[this.stack.length-1].url=e},resourceTitleString:function(){const e=this.resume();this.stack[this.stack.length-1].title=e},resource:function(){s("inReference")},setextHeading:h((function(){s("setextHeadingSlurpLineEnding")})),setextHeadingLineSequence:function(e){this.stack[this.stack.length-1].depth=61===this.sliceSerialize(e).charCodeAt(0)?1:2},setextHeadingText:function(){s("setextHeadingSlurpLineEnding",!0)},strong:h(),thematicBreak:h()}};ke(t,(e||{}).mdastExtensions||[]);const n={};return function(e){let n={type:"root",children:[]};const o={stack:[n],tokenStack:[],config:t,enter:l,exit:d,buffer:u,resume:p,setData:s,getData:a},i=[];let c=-1;for(;++c<e.length;)"listOrdered"!==e[c][1].type&&"listUnordered"!==e[c][1].type||("enter"===e[c][0]?i.push(c):c=r(e,i.pop(),c));for(c=-1;++c<e.length;){const n=t[e[c][0]];Ie.call(n,e[c][1].type)&&n[e[c][1].type].call(Object.assign({sliceSerialize:e[c][2].sliceSerialize},o),e[c][1])}if(o.tokenStack.length>0){const e=o.tokenStack[o.tokenStack.length-1];(e[1]||Le).call(o,void 0,e[0])}for(n.position={start:Pe(e.length>0?e[0][1].start:{line:1,column:1,offset:0}),end:Pe(e.length>0?e[e.length-2][1].end:{line:1,column:1,offset:0})},c=-1;++c<t.transforms.length;)n=t.transforms[c](n)||n;return n};function r(e,t,n){let r,o,i,s,a=t-1,c=-1,u=!1;for(;++a<=n;){const t=e[a];if("listUnordered"===t[1].type||"listOrdered"===t[1].type||"blockQuote"===t[1].type?("enter"===t[0]?c++:c--,s=void 0):"lineEndingBlank"===t[1].type?"enter"===t[0]&&(!r||s||c||i||(i=a),s=void 0):"linePrefix"===t[1].type||"listItemValue"===t[1].type||"listItemMarker"===t[1].type||"listItemPrefix"===t[1].type||"listItemPrefixWhitespace"===t[1].type||(s=void 0),!c&&"enter"===t[0]&&"listItemPrefix"===t[1].type||-1===c&&"exit"===t[0]&&("listUnordered"===t[1].type||"listOrdered"===t[1].type)){if(r){let s=a;for(o=void 0;s--;){const t=e[s];if("lineEnding"===t[1].type||"lineEndingBlank"===t[1].type){if("exit"===t[0])continue;o&&(e[o][1].type="lineEndingBlank",u=!0),t[1].type="lineEnding",o=s}else if("linePrefix"!==t[1].type&&"blockQuotePrefix"!==t[1].type&&"blockQuotePrefixWhitespace"!==t[1].type&&"blockQuoteMarker"!==t[1].type&&"listItemIndent"!==t[1].type)break}i&&(!o||i<o)&&(r._spread=!0),r.end=Object.assign({},o?e[o][1].start:t[1].end),e.splice(o||a,0,["exit",r,t[2]]),a++,n++}"listItemPrefix"===t[1].type&&(r={type:"listItem",_spread:!1,start:Object.assign({},t[1].start),end:void 0},e.splice(a,0,["enter",r,t[2]]),a++,n++,i=void 0,s=!0)}}return e[t][1]._spread=u,n}function s(e,t){n[e]=t}function a(e){return n[e]}function c(e,t){return function(n){l.call(this,e(n),n),t&&t.call(this,n)}}function u(){this.stack.push({type:"fragment",children:[]})}function l(e,t,n){return this.stack[this.stack.length-1].children.push(e),this.stack.push(e),this.tokenStack.push([t,n]),e.position={start:Pe(t.start)},e}function h(e){return function(t){e&&e.call(this,t),d.call(this,t)}}function d(e,t){const n=this.stack.pop(),r=this.tokenStack.pop();if(!r)throw new Error("Cannot close `"+e.type+"` ("+(0,Ne.L)({start:e.start,end:e.end})+"): it’s not open");return r[0].type!==e.type&&(t?t.call(this,e,r[0]):(r[1]||Le).call(this,e,r[0])),n.position.end=Pe(e.end),n}function p(){return function(e){return i(e,"boolean"!=typeof o.includeImageAlt||o.includeImageAlt,"boolean"!=typeof o.includeHtml||o.includeHtml)}(this.stack.pop())}function m(e){const t=this.stack[this.stack.length-1];let n=t.children[t.children.length-1];n&&"text"===n.type||(n={type:"text",value:""},n.position={start:Pe(e.start)},t.children.push(n)),this.stack.push(n)}function f(e){const t=this.stack.pop();t.value+=this.sliceSerialize(e),t.position.end=Pe(e.end)}function g(){s("atHardBreak",!0)}function y(e){s("characterReferenceType",e.type)}function E(){return{type:"code",lang:null,meta:null,value:""}}function S(){return{type:"heading",depth:void 0,children:[]}}function O(){return{type:"break"}}function C(){return{type:"html",value:""}}function v(){return{type:"link",title:null,url:"",children:[]}}function b(e){return{type:"list",ordered:"listOrdered"===e.type,start:null,spread:e._spread,children:[]}}}(n)(function(e){for(;!E(e););return e}(function(e){const t={defined:[],lazy:{},constructs:function(e){const t={};let n=-1;for(;++n<e.length;)l(t,e[n]);return t}([r,...(e||{}).extensions||[]]),content:n(m),document:n(f),flow:n(v),string:n(w),text:n(M)};return t;function n(e){return function(n){return N(t,e,n)}}}(n).document().write(function(){let e,t=1,n="",r=!0;return function(o,i,s){const a=[];let c,u,l,h,d;for(o=n+o.toString(i),l=0,n="",r&&(65279===o.charCodeAt(0)&&l++,r=void 0);l<o.length;){if(Te.lastIndex=l,c=Te.exec(o),h=c&&void 0!==c.index?c.index:o.length,d=o.charCodeAt(h),!c){n=o.slice(l);break}if(10===d&&l===h&&e)a.push(-3),e=void 0;else switch(e&&(a.push(-5),e=void 0),l<h&&(a.push(o.slice(l,h)),t+=h-l),d){case 0:a.push(65533),t++;break;case 9:for(u=4*Math.ceil(t/4),a.push(-2);t++<u;)a.push(-1);break;case 10:a.push(-4),t=1;break;default:e=!0,t=1}l=h+1}return s&&(e&&a.push(-5),n&&a.push(n),a.push(null)),a}}()(e,t,!0))))};function Pe(e){return{line:e.line,column:e.column,offset:e.offset}}function ke(e,t){let n=-1;for(;++n<t.length;){const r=t[n];Array.isArray(r)?ke(e,r):De(e,r)}}function De(e,t){let n;for(n in t)if(Ie.call(t,n))if("canContainEols"===n){const r=t[n];r&&e[n].push(...r)}else if("transforms"===n){const r=t[n];r&&e[n].push(...r)}else if("enter"===n||"exit"===n){const r=t[n];r&&Object.assign(e[n],r)}}function Le(e,t){throw e?new Error("Cannot close `"+e.type+"` ("+(0,Ne.L)({start:e.start,end:e.end})+"): a different token (`"+t.type+"`, "+(0,Ne.L)({start:t.start,end:t.end})+") is open"):new Error("Cannot close document, a token (`"+t.type+"`, "+(0,Ne.L)({start:t.start,end:t.end})+") is still open")}},85759:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Transaction=t.TxnState=void 0,t.isTransactionCommand=function(e){return!(!e.commitTransaction&&!e.abortTransaction)};const r=n(17562),o=n(28541),i=n(13700),s=n(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 n=s.WriteConcern.fromOptions(e);if(n){if(0===n.w)throw new r.MongoTransactionError("Transactions do not support unacknowledged write concern");this.options.writeConcern=n}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 n=a[this.state];if(n&&n.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 r.MongoRuntimeError(`Attempted illegal state transition from [${this.state}] to [${e}]`)}pinServer(e){this.isActive&&(this._pinnedServer=e)}unpinServer(){this._pinnedServer=void 0}}},86493:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isEmail=void 0;const n=/[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;t.isEmail=function(e){return n.test(e)}},86577:(e,t)=>{var n;Object.defineProperty(t,"__esModule",{value:!0}),t.ParseMode=void 0,t.buildOptions=function(e){return{...a,...s(e&&e.mode||n.Strict),...e}},function(e){e.Strict="strict",e.Extended="extended",e.Loose="loose"}(n||(t.ParseMode=n={}));const r={allowMethods:!1,allowComments:!1},o={allowMethods:!0},i={allowMethods:!0,allowComments:!0};function s(e){switch(e){case n.Strict:return r;case n.Extended:return o;case n.Loose:return i}}const a={mode:n.Strict,...r}},86981:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MongoCryptKMSRequestNetworkTimeoutError=t.MongoCryptAzureKMSRequestError=t.MongoCryptCreateEncryptedCollectionError=t.MongoCryptCreateDataKeyError=t.MongoCryptInvalidArgumentError=t.MongoCryptError=void 0;const r=n(17562);class o extends r.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,n)=>{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 y(e)),await m(t,e),t}catch(e){throw t?.destroy(),e}},t.makeConnection=p,t.performInitialHandshake=m,t.prepareHandshakeDocument=f,t.makeSocket=y;const r=n(26272),o=n(386),i=n(91869),s=n(8500),a=n(17562),c=n(145),u=n(31057),l=n(93065),h=n(71470),d=n(96856);function p(e,t){let n=e.connectionType??h.Connection;return e.autoEncrypter&&(n=h.CryptoConnection),new n(t,e)}async function m(e,t){const n=t.credentials;if(n&&n.mechanism!==l.AuthMechanism.MONGODB_DEFAULT&&!t.authProviders.getOrCreateProvider(n.mechanism,n.mechanismProperties))throw new a.MongoInvalidArgumentError(`AuthMechanism '${n.mechanism}' not supported`);const r=new u.AuthContext(e,n,t);e.authContext=r;const o=await f(r),s={...t,raw:!1};"number"==typeof t.connectTimeoutMS&&(s.socketTimeoutMS=t.connectTimeoutMS);const h=(new Date).getTime(),p=await async function(t,n){try{return await e.command((0,c.ns)("admin.$cmd"),t,n)}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 n=Number(e.maxWireVersion),r=Number(e.minWireVersion),o=!Number.isNaN(n)&&n>=d.MIN_SUPPORTED_WIRE_VERSION,i=!Number.isNaN(r)&&r<=d.MAX_SUPPORTED_WIRE_VERSION;if(o){if(i)return null;const n=`Server at ${t.hostAddress} reports minimum wire version ${JSON.stringify(e.minWireVersion)}, but this version of the Node.js Driver requires at most ${d.MAX_SUPPORTED_WIRE_VERSION} (MongoDB ${d.MAX_SUPPORTED_SERVER_VERSION})`;return new a.MongoCompatibilityError(n)}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 ${d.MIN_SUPPORTED_WIRE_VERSION} (MongoDB ${d.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()-h,!p.arbiterOnly&&n){r.response=p;const o=n.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(r)}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,n=t.compressors?t.compressors:[],{serverApi:r}=e.connection,o=await t.extendedMetadata,s={[r?.version||!0===t.loadBalanced?"hello":i.LEGACY_HELLO_COMMAND]:1,helloOk:!0,client:o,compression:n};!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 n=e.hostAddress;if(!n)throw new a.MongoInvalidArgumentError('Option "hostAddress" is required');const r={};for(const n of t.LEGAL_TCP_SOCKET_OPTIONS)null!=e[n]&&(r[n]=e[n]);if(r.keepAliveInitialDelay??=12e4,r.keepAlive=!0,r.noDelay=e.noDelay??!0,"string"==typeof n.socketPath)return r.path=n.socketPath,r;if("string"==typeof n.host)return r.host=n.host,r.port=n.port,r;throw new a.MongoRuntimeError(`Unexpected HostAddress ${JSON.stringify(n)}`)}async function y(e){const n=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),n=await y({...e,hostAddress:t,tls:!1,proxyHost:void 0}),r=g(e);if("string"!=typeof r.host||"number"!=typeof r.port)throw new a.MongoInvalidArgumentError("Can only make Socks5 connections to TCP hosts");let o;E??=function(){if(null==E){const e=(0,s.getSocks)();if("kModuleError"in e)throw e.kModuleError;E=e}return E}();try{o=(await E.SocksClient.createConnection({existing_socket:n,timeout:e.connectTimeoutMS,command:"connect",destination:{host:r.host,port:r.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 y({...e,existingSocket:o,proxyHost:void 0})}({...e,connectTimeoutMS:i});if(n){const n=o.connect(function(e){const n=g(e);for(const r of t.LEGAL_TLS_SOCKET_OPTIONS)null!=e[r]&&(n[r]=e[r]);return e.existingSocket&&(n.socket=e.existingSocket),null==n.servername&&n.host&&!r.isIP(n.host)&&(n.servername=n.host),n}(e));"function"==typeof n.disableRenegotiation&&n.disableRenegotiation(),l=n}else l=u||r.createConnection(g(e));l.setTimeout(i);let h=null;const{promise:d,resolve:p,reject:m}=(0,c.promiseWithResolvers)();if(u)p(l);else{const t=performance.now(),r=n?"secureConnect":"connect";l.once(r,(()=>p(l))).once("error",(e=>m(new a.MongoNetworkError(a.MongoError.buildErrorMessage(e),{cause:e})))).once("timeout",(()=>{m(new a.MongoNetworkTimeoutError(`Socket '${r}' 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&&(h=()=>m(new a.MongoNetworkError("Socket connection establishment was cancelled after "+(performance.now()-t|0))),e.cancellationToken.once("cancel",h))}try{return l=await d,l}catch(e){throw l.destroy(),e}finally{l.setTimeout(0),null!=h&&e.cancellationToken?.removeListener("cancel",h)}}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 E=null},88536:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ProfilingLevelOperation=void 0;const r=n(75080),o=n(75725),i=n(17562),s=n(78130);class a extends o.MongoDBResponse{get was(){return this.get("was",r.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,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AutomatedCallbackWorkflow=void 0;const r=n(17562),o=n(7799),i=n(63257),s=n(49683);class a extends s.CallbackWorkflow{constructor(e,t){super(e,t)}async execute(e,t){if(this.cache.hasAccessToken){const n=this.cache.getAccessToken();e.accessToken||(e.accessToken=n);try{return await this.finishAuthentication(e,t,n)}catch(n){if(n instanceof r.MongoError&&n.code===r.MONGODB_ERROR_CODES.AuthenticationFailed)return this.cache.removeAccessToken(),await this.execute(e,t);throw n}}const n=await this.fetchAccessToken(t);this.cache.put(n),e.accessToken=n.accessToken,await this.finishAuthentication(e,t,n.accessToken)}async fetchAccessToken(e){const t=new AbortController,n={timeoutContext:t.signal,version:i.OIDC_VERSION};e.username&&(n.username=e.username),e.mechanismProperties.TOKEN_RESOURCE&&(n.tokenAudience=e.mechanismProperties.TOKEN_RESOURCE);const a=o.Timeout.expires(s.AUTOMATED_TIMEOUT_MS);try{return await Promise.race([this.executeAndValidateCallback(n),a])}catch(e){if(o.TimeoutError.is(e))throw t.abort(),new r.MongoOIDCError(`OIDC callback timed out after ${s.AUTOMATED_TIMEOUT_MS}ms.`);throw e}finally{a.clear()}}}t.AutomatedCallbackWorkflow=a},88913:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ListCollectionsOperation=void 0;const r=n(75725),o=n(145),i=n(78130),s=n(35394);class a extends i.CommandOperation{constructor(e,t,n){super(e,n),this.SERVER_COMMAND_RESPONSE_TYPE=r.CursorResponse,this.options={...n},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?r.ExplainedCursorResponse:r.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"})},91174:function(e,t,n){var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var o=Object.getOwnPropertyDescriptor(t,n);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,o)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),o=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||r(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),o(n(17851),t),o(n(97557),t)},91566:(e,t,n)=>{var r=n(65994).e;Object.defineProperty(t,"__esModule",{value:!0}),t.MongoCredentials=t.DEFAULT_ALLOWED_HOSTS=void 0;const o=n(17562),i=n(95750),s=n(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&&r.env.AWS_ACCESS_KEY_ID&&(this.username=r.env.AWS_ACCESS_KEY_ID),!this.password&&r.env.AWS_SECRET_ACCESS_KEY&&(this.password=r.env.AWS_SECRET_ACCESS_KEY),null==this.mechanismProperties.AWS_SESSION_TOKEN&&null!=r.env.AWS_SESSION_TOKEN&&(this.mechanismProperties={...this.mechanismProperties,AWS_SESSION_TOKEN:r.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,n)=>{var r=n(44775);t.certificate=n(58782);var o=r.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=r.define("RSAPublicKey",(function(){this.seq().obj(this.key("modulus").int(),this.key("publicExponent").int())}));t.RSAPublicKey=i;var s=r.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=r.define("SubjectPublicKeyInfo",(function(){this.seq().obj(this.key("algorithm").use(s),this.key("subjectPublicKey").bitstr())}));t.PublicKey=a;var c=r.define("PrivateKeyInfo",(function(){this.seq().obj(this.key("version").int(),this.key("algorithm").use(s),this.key("subjectPrivateKey").octstr())}));t.PrivateKey=c;var u=r.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=r.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=r.define("DSAparam",(function(){this.int()}));var h=r.define("ECParameters",(function(){this.choice({namedCurve:this.objid()})})),d=r.define("ECPrivateKey",(function(){this.seq().obj(this.key("version").int(),this.key("privateKey").octstr(),this.key("parameters").optional().explicit(0).use(h),this.key("publicKey").optional().explicit(1).bitstr())}));t.ECPrivateKey=d,t.signature=r.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,n)=>{var r=n(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=S;const o=n(98437),i=n(75080),s=n(91869),a=n(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[n,r]of e)t.push([r,n]);t.push(...e),super(t)}getNumericSeverityLevel(e){return this.get(e)}getSeverityLevelName(e){return this.get(e)}}function u(e){const n=Object.values(t.SeverityLevel),r=e?.toLowerCase();return null!=r&&n.includes(r)?r:null}function l(e){return{write:(0,o.promisify)(((t,n)=>{const r=(0,o.inspect)(t,{compact:!0,breakLength:1/0});e.write(`${r}\n`,"utf-8",n)}))}}function h(e,t,n){return u(e)??u(t)??n}function d(e,n){const r=t.SEVERITY_LEVEL_MAP.getNumericSeverityLevel(e),o=t.SEVERITY_LEVEL_MAP.getNumericSeverityLevel(n);return r<o?-1:r>o?1:0}function p(e,t,n={}){let r="",o=0;const s=function(e,n){if(!(o>=t)){if(""===e)return o+=1,n;if(o+=e.length+4,null==n)return n;switch(typeof n){case"string":o+=n.length+2;break;case"number":case"bigint":o+=String(n).length;break;case"boolean":o+=n?4:5;break;case"object":if((0,a.isUint8Array)(n))o+=22+n.byteLength+.33*n.byteLength+18|0;else if("_bsontype"in n){const e=n;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+n.position+.33*n.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 n}};if("string"==typeof e)r=e;else if("function"==typeof e)r=e.name;else try{r=0!==t?i.EJSON.stringify(e,s,0,n):i.EJSON.stringify(e,n)}catch(e){r=`Extended JSON serialization failed with: ${e.message}`}return 0!==t&&r.length>t&&r.charCodeAt(t-1)!==r.codePointAt(t-1)&&0==--t?"":0!==t&&r.length>t?`${r.slice(0,t)}...`:r}function m(e,n,r=t.DEFAULT_MAX_DOCUMENT_LENGTH){const{selector:o,operation:i,topologyDescription:s,message:a}=n;return e.selector=p(o,r),e.operation=i,e.topologyDescription=p(s,r),e.message=a,e}function f(e,t){e.commandName=t.commandName,e.requestId=t.requestId,e.driverConnectionId=t.connectionId;const{host:n,port:r}=a.HostAddress.fromString(t.address).toHostPort();return e.serverHost=n,e.serverPort=r,t?.serviceId&&(e.serviceId=t.serviceId.toHexString()),e.databaseName=t.databaseName,e.serverConnectionId=t.serverConnectionId,e}function g(e,t){const{host:n,port:r}=a.HostAddress.fromString(t.address).toHostPort();return e.serverHost=n,e.serverPort=r,e}function y(e,t){return e.topologyId=t.topologyId,e}function E(e,t){const{awaited:n,connectionId:r}=t;e.awaited=n,e.driverConnectionId=t.connectionId;const{host:o,port:i}=a.HostAddress.fromString(r).toHostPort();return e.serverHost=o,e.serverPort=i,e}function S(e,n=t.DEFAULT_MAX_DOCUMENT_LENGTH){let r=Object.create(null);switch(e.name){case s.SERVER_SELECTION_STARTED:return r=m(r,e,n),r;case s.SERVER_SELECTION_FAILED:return r=m(r,e,n),r.failure=e.failure?.message,r;case s.SERVER_SELECTION_SUCCEEDED:return r=m(r,e,n),r.serverHost=e.serverHost,r.serverPort=e.serverPort,r;case s.WAITING_FOR_SUITABLE_SERVER:return r=m(r,e,n),r.remainingTimeMS=e.remainingTimeMS,r;case s.COMMAND_STARTED:return r=f(r,e),r.message="Command started",r.command=p(e.command,n,{relaxed:!0}),r.databaseName=e.databaseName,r;case s.COMMAND_SUCCEEDED:return r=f(r,e),r.message="Command succeeded",r.durationMS=e.duration,r.reply=p(e.reply,n,{relaxed:!0}),r;case s.COMMAND_FAILED:return r=f(r,e),r.message="Command failed",r.durationMS=e.duration,r.failure=e.failure?.message??"(redacted)",r;case s.CONNECTION_POOL_CREATED:if(r=g(r,e),r.message="Connection pool created",e.options){const{maxIdleTimeMS:t,minPoolSize:n,maxPoolSize:o,maxConnecting:i,waitQueueTimeoutMS:s}=e.options;r={...r,maxIdleTimeMS:t,minPoolSize:n,maxPoolSize:o,maxConnecting:i,waitQueueTimeoutMS:s}}return r;case s.CONNECTION_POOL_READY:return r=g(r,e),r.message="Connection pool ready",r;case s.CONNECTION_POOL_CLEARED:return r=g(r,e),r.message="Connection pool cleared","ObjectId"===e.serviceId?._bsontype&&(r.serviceId=e.serviceId?.toHexString()),r;case s.CONNECTION_POOL_CLOSED:return r=g(r,e),r.message="Connection pool closed",r;case s.CONNECTION_CREATED:return r=g(r,e),r.message="Connection created",r.driverConnectionId=e.connectionId,r;case s.CONNECTION_READY:return r=g(r,e),r.message="Connection ready",r.driverConnectionId=e.connectionId,r.durationMS=e.durationMS,r;case s.CONNECTION_CLOSED:switch(r=g(r,e),r.message="Connection closed",r.driverConnectionId=e.connectionId,e.reason){case"stale":r.reason="Connection became stale because the pool was cleared";break;case"idle":r.reason="Connection has been available but unused for longer than the configured max idle time";break;case"error":r.reason="An error occurred while using the connection",e.error&&(r.error=e.error);break;case"poolClosed":r.reason="Connection pool was closed";break;default:r.reason=`Unknown close reason: ${e.reason}`}return r;case s.CONNECTION_CHECK_OUT_STARTED:return r=g(r,e),r.message="Connection checkout started",r;case s.CONNECTION_CHECK_OUT_FAILED:switch(r=g(r,e),r.message="Connection checkout failed",e.reason){case"poolClosed":r.reason="Connection pool was closed";break;case"timeout":r.reason="Wait queue timeout elapsed without a connection becoming available";break;case"connectionError":r.reason="An error occurred while trying to establish a new connection",e.error&&(r.error=e.error);break;default:r.reason=`Unknown close reason: ${e.reason}`}return r.durationMS=e.durationMS,r;case s.CONNECTION_CHECKED_OUT:return r=g(r,e),r.message="Connection checked out",r.driverConnectionId=e.connectionId,r.durationMS=e.durationMS,r;case s.CONNECTION_CHECKED_IN:return r=g(r,e),r.message="Connection checked in",r.driverConnectionId=e.connectionId,r;case s.SERVER_OPENING:return r=y(r,e),r=g(r,e),r.message="Starting server monitoring",r;case s.SERVER_CLOSED:return r=y(r,e),r=g(r,e),r.message="Stopped server monitoring",r;case s.SERVER_HEARTBEAT_STARTED:return r=y(r,e),r=E(r,e),r.message="Server heartbeat started",r;case s.SERVER_HEARTBEAT_SUCCEEDED:return r=y(r,e),r=E(r,e),r.message="Server heartbeat succeeded",r.durationMS=e.duration,r.serverConnectionId=e.serverConnectionId,r.reply=p(e.reply,n,{relaxed:!0}),r;case s.SERVER_HEARTBEAT_FAILED:return r=y(r,e),r=E(r,e),r.message="Server heartbeat failed",r.durationMS=e.duration,r.failure=e.failure?.message,r;case s.TOPOLOGY_OPENING:return r=y(r,e),r.message="Starting topology monitoring",r;case s.TOPOLOGY_CLOSED:return r=y(r,e),r.message="Stopped topology monitoring",r;case s.TOPOLOGY_DESCRIPTION_CHANGED:return r=y(r,e),r.message="Topology description changed",r.previousDescription=r.reply=p(e.previousDescription,n),r.newDescription=r.reply=p(e.newDescription,n),r;default:for(const[t,n]of Object.entries(e))null!=n&&(r[t]=n)}return r}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 n of Object.values(t.MongoLoggableComponent)){e[n]={};for(const r of Object.values(t.SeverityLevel))e[n][r]=d(r,this.componentSeverities[n])<=0}return e}turnOffSeverities(){for(const e of Object.values(t.MongoLoggableComponent)){this.componentSeverities[e]=t.SeverityLevel.OFF;for(const n of Object.values(t.SeverityLevel))this.severities[e][n]=!1}}logWriteFailureHandler(e){if(this.logDestinationIsStdErr)return this.turnOffSeverities(),void this.clearPendingLog();this.logDestination=l(r.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,n){return n!==t.SeverityLevel.OFF&&this.severities[e][n]}log(e,t,n){if(!this.willLog(t,e))return;let r={t:new Date,c:t,s:e};if("string"==typeof n?r.message=n:"object"==typeof n&&(r=function(e){const t=e;return void 0!==t.toLog&&"function"==typeof t.toLog}(n)?{...r,...n.toLog()}:{...r,...S(n,this.maxDocumentLength)}),(0,a.isPromiseLike)(this.pendingLog))this.pendingLog=this.pendingLog.then((()=>this.logDestination.write(r))).then(this.clearPendingLog.bind(this),this.logWriteFailureHandler.bind(this));else try{const e=this.logDestination.write(r);(0,a.isPromiseLike)(e)&&(this.pendingLog=e.then(this.clearPendingLog.bind(this),this.logWriteFailureHandler.bind(this)))}catch(e){this.logWriteFailureHandler(e)}}static resolveOptions(e,n){const o=function({MONGODB_LOG_PATH:e},{mongodbLogPath:t}){return"string"==typeof t&&/^stderr$/i.test(t)?{mongodbLogPath:l(r.stderr),mongodbLogPathIsStdErr:!0}:"string"==typeof t&&/^stdout$/i.test(t)?{mongodbLogPath:l(r.stdout),mongodbLogPathIsStdErr:!1}:"object"==typeof t&&"function"==typeof t?.write?{mongodbLogPath:t,mongodbLogPathIsStdErr:!1}:e&&/^stderr$/i.test(e)?{mongodbLogPath:l(r.stderr),mongodbLogPathIsStdErr:!0}:e&&/^stdout$/i.test(e)?{mongodbLogPath:l(r.stdout),mongodbLogPathIsStdErr:!1}:{mongodbLogPath:l(r.stderr),mongodbLogPathIsStdErr:!0}}(e,n),i={...e,...n,mongodbLogPath:o.mongodbLogPath,mongodbLogPathIsStdErr:o.mongodbLogPathIsStdErr},s=h(i.mongodbLogComponentSeverities?.default,i.MONGODB_LOG_ALL,t.SeverityLevel.OFF);return{componentSeverities:{command:h(i.mongodbLogComponentSeverities?.command,i.MONGODB_LOG_COMMAND,s),topology:h(i.mongodbLogComponentSeverities?.topology,i.MONGODB_LOG_TOPOLOGY,s),serverSelection:h(i.mongodbLogComponentSeverities?.serverSelection,i.MONGODB_LOG_SERVER_SELECTION,s),connection:h(i.mongodbLogComponentSeverities?.connection,i.MONGODB_LOG_CONNECTION,s),client:h(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,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EstimatedDocumentCountOperation=void 0;const r=n(75725),o=n(78130),i=n(35394);class s extends o.CommandOperation{constructor(e,t={}){super(e,t),this.SERVER_COMMAND_RESPONSE_TYPE=r.MongoDBResponse,this.options=t,this.collectionName=e.collectionName}get commandName(){return"count"}buildCommandDocument(e,t){const n={count:this.collectionName};return"number"==typeof this.options.maxTimeMS&&(n.maxTimeMS=this.options.maxTimeMS),void 0!==this.options.comment&&(n.comment=this.options.comment),n}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,n)=>{var r=n(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 n;try{n=o.createHash("sha256").update(e).digest()}catch(e){return e}return n.copy(t),n.length},t.makeHmacHook=s,t.signRsaSha256Hook=function(e,t,n){let i;try{const n=o.createSign("sha256WithRSAEncryption"),s=r.from(`-----BEGIN PRIVATE KEY-----\n${e.toString("base64")}\n-----END PRIVATE KEY-----\n`);i=n.update(t).end().sign(s)}catch(e){return e}return i.copy(n),i.length};const o=n(27348);function i(e,t){return function(n,i,s,a){let c;try{const a=o[e](t,n,i);a.setAutoPadding(!1),c=a.update(s);const u=a.final();u.length>0&&(c=r.concat([c,u]))}catch(e){return e}return c.copy(a),c.length}}function s(e){return(t,n,r)=>{let i;try{i=o.createHmac(e,t).update(n).digest()}catch(e){return e}return i.copy(r),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,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ReplaceOneOperation=t.UpdateManyOperation=t.UpdateOneOperation=t.UpdateOperation=void 0,t.makeUpdateStatement=p;const r=n(75725),o=n(17562),i=n(30770),s=n(145),a=n(78130),c=n(35394);class u extends a.CommandOperation{constructor(e,t,n){super(void 0,n),this.SERVER_COMMAND_RESPONSE_TYPE=r.MongoDBResponse,this.options=n,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 n=this.options,r={update:this.ns.collection,updates:this.statements,ordered:n.ordered??!0};if("boolean"==typeof n.bypassDocumentValidation&&(r.bypassDocumentValidation=n.bypassDocumentValidation),n.let&&(r.let=n.let),void 0!==n.comment&&(r.comment=n.comment),0===this.writeConcern?.w&&this.statements.find((e=>e.hint)))throw new o.MongoCompatibilityError("hint is not supported with unacknowledged writes");return r}}t.UpdateOperation=u;class l extends u{constructor(e,t,n,r){if(super(e,[p(t,n,{...r,multi:!1})],r),!(0,s.hasAtomicOperators)(n,r))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 h extends u{constructor(e,t,n,r){if(super(e,[p(t,n,{...r,multi:!0})],r),!(0,s.hasAtomicOperators)(n,r))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=h;class d extends u{constructor(e,t,n,r){if(super(e,[p(t,n,{...r,multi:!1})],r),(0,s.hasAtomicOperators)(n))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,n){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 r={q:e,u:t};return"boolean"==typeof n.upsert&&(r.upsert=n.upsert),n.multi&&(r.multi=n.multi),n.hint&&(r.hint=n.hint),n.arrayFilters&&(r.arrayFilters=n.arrayFilters),n.collation&&(r.collation=n.collation),n.multi||null==n.sort||(r.sort=(0,i.formatSort)(n.sort)),r}t.ReplaceOneOperation=d,(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)(h,[c.Aspect.WRITE_OPERATION,c.Aspect.EXPLAINABLE,c.Aspect.SKIP_COLLATION]),(0,c.defineAspects)(d,[c.Aspect.RETRYABLE,c.Aspect.WRITE_OPERATION,c.Aspect.SKIP_COLLATION])},95421:e=>{var t=Object.getOwnPropertySymbols,n=Object.prototype.hasOwnProperty,r=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={},n=0;n<10;n++)t["_"+String.fromCharCode(n)]=n;if("0123456789"!==Object.getOwnPropertyNames(t).map((function(e){return t[e]})).join(""))return!1;var r={};return"abcdefghijklmnopqrst".split("").forEach((function(e){r[e]=e})),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},r)).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]))n.call(i,u)&&(a[u]=i[u]);if(t){s=t(i);for(var l=0;l<s.length;l++)r.call(i,s[l])&&(a[s[l]]=i[s[l]])}}return a}},95662:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DropDatabaseOperation=t.DropCollectionOperation=void 0,t.dropCollections=async function(e,t,n){const o=a.TimeoutContext.create({session:n.session,serverSelectionTimeoutMS:e.client.s.options.serverSelectionTimeoutMS,waitQueueTimeoutMS:e.client.s.options.waitQueueTimeoutMS,timeoutMS:n.timeoutMS}),c=e.client.s.options.autoEncryption?.encryptedFieldsMap;let l=n.encryptedFields??c?.[`${e.databaseName}.${t}`];if(!l&&c){const r=await e.listCollections({name:t},{nameOnly:!1,session:n.session,timeoutContext:new i.CursorTimeoutContext(o,Symbol())}).toArray();l=r?.[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 h(e,t,n);try{await(0,u.executeOperation)(e.client,i,o)}catch(e){if(!(e instanceof r.MongoServerError)||e.code!==s.MONGODB_ERROR_CODES.NamespaceNotFound)throw e}}}return await(0,u.executeOperation)(e.client,new h(e,t,n),o)};const r=n(16360),o=n(75725),i=n(61066),s=n(17562),a=n(7799),c=n(78130),u=n(96357),l=n(35394);class h extends c.CommandOperation{constructor(e,t,n={}){super(e,n),this.SERVER_COMMAND_RESPONSE_TYPE=o.MongoDBResponse,this.options=n,this.name=t}get commandName(){return"drop"}buildCommandDocument(e,t){return{drop:this.name}}handleOk(e){return!0}}t.DropCollectionOperation=h;class d 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=d,(0,l.defineAspects)(h,[l.Aspect.WRITE_OPERATION]),(0,l.defineAspects)(d,[l.Aspect.WRITE_OPERATION])},95724:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MongocryptdManager=void 0;const r=n(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}=n(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 r.MongoNetworkTimeoutError)||this.bypassSpawn)throw e}return await this.spawn(),await e()}}t.MongocryptdManager=o,o.DEFAULT_MONGOCRYPTD_URI="mongodb://localhost:27020"},95738:(e,t,n)=>{var r=n(67787).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.ClientEncryption=void 0,t.autoSelectSocketOptions=p;const o=n(75080),i=n(8500),s=n(7799),a=n(145),c=n(93992),u=n(86981),l=n(51825),h=n(97515);class d{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:n}=(0,a.resolveTimeoutOptions)(e,t);if(this._timeoutMS=n,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:r.isBuffer(this._kmsProviders)?this._kmsProviders:(0,o.serialize)(this._kmsProviders)};this._keyVaultNamespace=t.keyVaultNamespace,this._keyVaultClient=t.keyVaultClient||e;const s=d.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 n,r;t.keyAltNames&&t.keyAltNames.length>0&&(n=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&&(r=(0,o.serialize)({keyMaterial:t.keyMaterial}));const i=(0,o.serialize)({provider:e,...t.masterKey}),c=this._mongoCrypt.makeDataKeyContext(i,{keyAltNames:n,keyMaterial:r}),l=new h.StateMachine({proxyOptions:this._proxyOptions,tlsOptions:this._tlsOptions,socketOptions:p(this._client.s.options)}),d=t?.timeoutContext??s.TimeoutContext.create((0,a.resolveTimeoutOptions)(this._client,{timeoutMS:this._timeoutMS})),m=(0,o.deserialize)(await l.execute(this,c,{timeoutContext:d})),{db:f,collection:g}=a.MongoDBCollectionNamespace.fromString(this._keyVaultNamespace),{insertedId:y}=await this._keyVaultClient.db(f).collection(g).insertOne(m,{writeConcern:{w:"majority"},timeoutMS:d?.csotEnabled()?d?.getRemainingTimeMSOrThrow():void 0});return y}async rewrapManyDataKey(e,t){let n;if(t){const e=Object.assign({provider:t.provider},t.masterKey);n=(0,o.serialize)(e)}const r=(0,o.serialize)(e),i=this._mongoCrypt.makeRewrapManyDataKeyContext(r,n),c=new h.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:d,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(d).collection(m).bulkWrite(f,{writeConcern:{w:"majority"},timeoutMS:u.csotEnabled()?u?.remainingTimeMS:void 0})}}async deleteKey(e){const{db:t,collection:n}=a.MongoDBCollectionNamespace.fromString(this._keyVaultNamespace);return await this._keyVaultClient.db(t).collection(n).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:n}=a.MongoDBCollectionNamespace.fromString(this._keyVaultNamespace);return await this._keyVaultClient.db(t).collection(n).findOne({_id:e},{readConcern:{level:"majority"},timeoutMS:this._timeoutMS})}async getKeyByAltName(e){const{db:t,collection:n}=a.MongoDBCollectionNamespace.fromString(this._keyVaultNamespace);return await this._keyVaultClient.db(t).collection(n).findOne({keyAltNames:e},{readConcern:{level:"majority"},timeoutMS:this._timeoutMS})}async addKeyAltName(e,t){const{db:n,collection:r}=a.MongoDBCollectionNamespace.fromString(this._keyVaultNamespace);return await this._keyVaultClient.db(n).collection(r).findOneAndUpdate({_id:e},{$addToSet:{keyAltNames:t}},{writeConcern:{w:"majority"},returnDocument:"before",timeoutMS:this._timeoutMS})}async removeKeyAltName(e,t){const{db:n,collection:r}=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(n).collection(r).findOneAndUpdate({_id:e},o,{writeConcern:{w:"majority"},returnDocument:"before",timeoutMS:this._timeoutMS})}async createEncryptedCollection(e,t,n){const{provider:r,masterKey:o,createCollectionOptions:{encryptedFields:{...i},...c}}=n,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(r,{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 n=t.find((e=>"rejected"===e.status));if(null!=n)throw new u.MongoCryptCreateDataKeyError(i,{cause:n.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}),n=this._mongoCrypt.makeExplicitDecryptionContext(t),r=new h.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 r.execute(this,n,{timeoutContext:i}));return c}async askForKMSCredentials(){return await(0,l.refreshKMSCredentials)(this._kmsProviders,this._credentialProviders)}static get libmongocryptVersion(){return d.getMongoCrypt().libmongocryptVersion}async _encrypt(e,t,n){const{algorithm:r,keyId:i,keyAltName:c,contentionFactor:l,queryType:d,rangeOptions:m,textOptions:f}=n,g={expressionMode:t,algorithm:r};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 d&&(g.queryType=d),"object"==typeof m&&(g.rangeOptions=(0,o.serialize)(m)),"object"==typeof f&&(g.textOptions=(0,o.serialize)(f));const y=(0,o.serialize)({v:e}),E=new h.StateMachine({proxyOptions:this._proxyOptions,tlsOptions:this._tlsOptions,socketOptions:p(this._client.s.options)}),S=this._mongoCrypt.makeExplicitEncryptionContext(y,g),O=null!=this._timeoutMS?s.TimeoutContext.create((0,a.resolveTimeoutOptions)(this._client,{timeoutMS:this._timeoutMS})):void 0,{v:C}=(0,o.deserialize)(await E.execute(this,S,{timeoutContext:O}));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=d},95750:(e,t,n)=>{var r=n(65994).e;Object.defineProperty(t,"__esModule",{value:!0}),t.GSSAPI=t.GSSAPICanonicalizationValue=void 0,t.performGSSAPICanonicalizeHostName=p,t.resolveCname=m;const o=n(95136),i=n(8500),s=n(17562),a=n(145),c=n(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 h extends c.AuthProvider{async auth(e){const{connection:t,credentials:n}=e;if(null==n)throw new s.MongoMissingCredentialsError("Credentials required for GSSAPI authentication");const{username:o}=n,a=await async function(e){const{hostAddress:t}=e.options,{credentials:n}=e;if(!t||"string"!=typeof t.host||!n)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}=n,u=n.mechanismProperties,h=u.SERVICE_NAME??"mongodb",d=await p(t.host,u),m={};null!=c&&Object.assign(m,{user:a,password:c});const f=u.SERVICE_HOST??d;let g=`${h}${"win32"===r.platform?"/":"@"}${f}`;return"SERVICE_REALM"in u&&(g=`${g}@${u.SERVICE_REALM}`),await o(g,m)}(e),c=await a.step(""),h=await u(t,function(e){return{saslStart:1,mechanism:"GSSAPI",payload:e,autoAuthorize:1}}(c)),m=await d(a,10,h.payload),f=await u(t,function(e,t){return{saslContinue:1,conversationId:t,payload:e}}(m,h.conversationId)),g=await async function(e,t,n){const r=await e.unwrap(n);return await e.wrap(r||"",{user:t})}(a,o,f.payload);await u(t,{saslContinue:1,conversationId:f.conversationId,payload:g})}}async function d(e,t,n){try{return await e.step(n)||""}catch(r){if(0===t)throw r;return await d(e,t-1,n)}}async function p(e,n){const r=n.CANONICALIZE_HOST_NAME;if(!r||r===t.GSSAPICanonicalizationValue.none)return e;if(r!==t.GSSAPICanonicalizationValue.on&&r!==t.GSSAPICanonicalizationValue.forwardAndReverse)return await m(e);{const{address:t}=await o.promises.lookup(e);try{const n=await o.promises.resolvePtr(t);return n.length>0?n[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=h},96357:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.executeOperation=async function(e,t,n){if(!(t instanceof u.AbstractOperation))throw new r.MongoRuntimeError("This method requires a valid operation instance");const p=null==e.topology?await(0,a.abortable)(d(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 r.MongoExpiredSessionError("Use of expired sessions is not permitted");if(f.snapshotEnabled&&!p.capabilities.supportsSnapshotReads)throw new r.MongoCompatibilityError("Snapshot reads require MongoDB 5.0 or later");if(f.client!==e)throw new r.MongoInvalidArgumentError("ClientSession must be from the same MongoClient")}t.session??=f;const g=t.readPreference??o.ReadPreference.primary,y=!!f?.inTransaction(),E=t.hasAspect(u.Aspect.READ_OPERATION);if(y&&!g.equals(o.ReadPreference.primary)&&(E||"runCommand"===t.commandName))throw new r.MongoTransactionError(`Read preference in a transaction must be primary, not: ${g.mode}`);f?.isPinned&&f.transaction.isCommitted&&!t.bypassPinningCheck&&f.unpin(),n??=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:n,session:o,readPreference:s}){let d;d=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(d,{session:o,operationName:e.commandName,timeoutContext:n,signal:e.options.signal});const m=e.hasAspect(u.Aspect.READ_OPERATION),f=e.hasAspect(u.Aspect.WRITE_OPERATION),g=o?.inTransaction()??!1,y=t.s.options.retryReads&&!g&&e.canRetryRead,E=t.s.options.retryWrites&&!g&&(0,a.supportsRetryableWrites)(p)&&e.canRetryWrite,S=e.hasAspect(u.Aspect.RETRYABLE)&&null!=o&&(m&&y||f&&E);f&&E&&null!=o&&(e.options.willRetryWrite=!0,o.incrementTransactionNumber());const O=S?n.csotEnabled()?1/0:2:1;let C,v;for(let i=0;i<O;i++){if(C){if(f&&C.code===l)throw new r.MongoServerError({message:h,errmsg:h,originalError:C});if(e.hasAspect(u.Aspect.COMMAND_BATCHING)&&!e.canRetryWrite)throw C;if(f&&!(0,r.isRetryableWriteError)(C))throw C;if(m&&!(0,r.isRetryableReadError)(C))throw C;if(C instanceof r.MongoNetworkError&&e.hasAspect(u.Aspect.CURSOR_CREATING)&&null!=o&&o.isPinned&&!o.inTransaction()&&o.unpin({force:!0,forceClear:!0}),p=await t.selectServer(d,{session:o,operationName:e.commandName,previousServer:v,signal:e.options.signal}),f&&!(0,a.supportsRetryableWrites)(p))throw new r.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,n);return e.handleOk(t)}catch(t){return e.handleError(t)}}catch(e){if(!(e instanceof r.MongoError))throw e;if(null!=C&&e.hasErrorLabel(r.MongoErrorLabel.NoWritesPerformed))throw C;v=p.description,C=e,n.clear()}}throw C??new r.MongoRuntimeError("Tried to propagate retryability error, but no error was found.")}(t,{topology:p,timeoutContext:n,session:f,readPreference:g})}finally{null!=f?.owner&&f.owner===m&&await f.endSession()}},t.autoConnect=d;const r=n(17562),o=n(13700),i=n(30588),s=n(7799),a=n(145),c=n(62016),u=n(35394),l=r.MONGODB_ERROR_CODES.IllegalOperation,h="This MongoDB deployment does not support retryable writes. Please add retryWrites=false to your connection string.";async function d(e){if(null==e.topology){if(e.s.hasBeenClosed)throw new r.MongoNotConnectedError("Client must be connected before running operations");e.s.options.__skipPingOnConnect=!0;try{if(await e.connect(),null==e.topology)throw new r.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,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TopologyDescription=void 0;const r=n(75080),o=n(96856),i=n(17562),s=n(145),a=n(89167),c=n(9188),u=o.MIN_SUPPORTED_SERVER_VERSION,l=o.MAX_SUPPORTED_SERVER_VERSION,h=o.MIN_SUPPORTED_WIRE_VERSION,d=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,n=null,r=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=n??null,this.maxElectionId=o??null,this.maxSetVersion=r??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>d&&(this.compatible=!1,this.compatibilityError=`Server at ${e.address} requires wire version ${e.minWireVersion}, but this version of the driver only supports up to ${d} (MongoDB ${l})`),e.maxWireVersion<h)){this.compatible=!1,this.compatibilityError=`Server at ${e.address} reports wire version ${e.maxWireVersion}, but this version of the driver requires at least ${h} (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 n=e.hostnames(),r=new Set(this.servers.keys()),o=new Set(n),i=new Set;for(const e of r)o.delete(e),n.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:n,setName:r,maxSetVersion:o,maxElectionId:s,commonWireVersion:u}=this;const l=e.type,h=new Map(this.servers);if(0!==e.maxWireVersion&&(u=null==u?e.maxWireVersion:Math.min(u,e.maxWireVersion)),"string"==typeof e.setName&&"string"==typeof r&&e.setName!==r&&(n===a.TopologyType.Single?e=new c.ServerDescription(t):h.delete(t)),h.set(t,e),n===a.TopologyType.Single)return new g(a.TopologyType.Single,h,r,o,s,u,{heartbeatFrequencyMS:this.heartbeatFrequencyMS,localThresholdMS:this.localThresholdMS});if(n===a.TopologyType.Unknown&&(l===a.ServerType.Standalone&&1!==this.servers.size?h.delete(t):n=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)),n===a.TopologyType.Sharded&&(p.has(l)||h.delete(t)),n===a.TopologyType.ReplicaSetNoPrimary)if(m.has(l)&&h.delete(t),l===a.ServerType.RSPrimary){const t=y(h,e,r,o,s);n=t[0],r=t[1],o=t[2],s=t[3]}else if(f.has(l)){const t=function(e,t,n=null){const r=a.TopologyType.ReplicaSetNoPrimary;return(n=n??t.setName)!==t.setName?(e.delete(t.address),[r,n]):(t.allHosts.forEach((t=>{e.has(t)||e.set(t,new c.ServerDescription(t))})),t.me&&t.address!==t.me&&e.delete(t.address),[r,n])}(h,e,r);n=t[0],r=t[1]}if(n===a.TopologyType.ReplicaSetWithPrimary)if(m.has(l))h.delete(t),n=E(h);else if(l===a.ServerType.RSPrimary){const t=y(h,e,r,o,s);n=t[0],r=t[1],o=t[2],s=t[3]}else n=f.has(l)?function(e,t,n=null){if(null==n)throw new i.MongoRuntimeError('Argument "setName" is required if connected to a replica set');return(n!==t.setName||t.me&&t.address!==t.me)&&e.delete(t.address),E(e)}(h,e,r):E(h);return new g(n,h,r,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 r.EJSON.serialize(this)}}function y(e,t,n=null,r=null,o=null){const u=(e,t,n)=>`primary marked stale due to electionId/setVersion mismatch: server setVersion: ${e.setVersion}, server electionId: ${e.electionId}, topology setVersion: ${t}, topology electionId: ${n}`;if((n=n||t.setName)!==t.setName)return e.delete(t.address),[E(e),n,r,o];if(t.maxWireVersion>=17){const a=(0,s.compareObjectId)(o,t.electionId),l=0===a,h=-1===a,d=(r??-1)<=(t.setVersion??-1);if(!(h||l&&d))return e.set(t.address,new c.ServerDescription(t.address,void 0,{error:new i.MongoStalePrimaryError(u(t,r,o))})),[E(e),n,r,o];o=t.electionId,r=t.setVersion}else{const a=t.electionId?t.electionId:null;if(t.setVersion&&a){if(r&&o&&(r>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,r,o))})),[E(e),n,r,o];o=t.electionId}null!=t.setVersion&&(null==r||t.setVersion>r)&&(r=t.setVersion)}for(const[n,r]of e)if(r.type===a.ServerType.RSPrimary&&r.address!==t.address){e.set(n,new c.ServerDescription(r.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()),h=t.allHosts;return l.filter((e=>-1===h.indexOf(e))).forEach((t=>{e.delete(t)})),[E(e),n,r,o]}function E(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,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DropSearchIndexOperation=void 0;const r=n(75725),o=n(17562),i=n(35394);class s extends i.AbstractOperation{constructor(e,t){super(),this.SERVER_COMMAND_RESPONSE_TYPE=r.MongoDBResponse,this.collection=e,this.name=t,this.ns=e.fullNamespace}get commandName(){return"dropSearchIndex"}buildCommand(e,t){const n={dropSearchIndex:this.collection.fullNamespace.collection};return"string"==typeof this.name&&(n.name=this.name),n}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,n)=>{var r=n(65994).e;Object.defineProperty(t,"__esModule",{value:!0}),t.StateMachine=void 0;const o=n(65981),i=n(26272),s=n(386),a=n(75080),c=n(61066),u=n(8500),l=n(17562),h=n(7799),d=n(145),p=n(95738),m=n(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"]]),y=["tlsInsecure","tlsAllowInvalidCertificates","tlsAllowInvalidHostnames"];function E(e){r.env.MONGODB_CRYPT_DEBUG&&console.error(e)}let S;t.StateMachine=class{constructor(e,t=(0,a.pluckBSONSerializeOptions)(e)){this.options=e,this.bsonOptions=t}async execute(e,t,n){const r=e._keyVaultNamespace,o=e._keyVaultClient,i=e._metaDataClient,s=e._mongocryptdClient,c=e._mongocryptdManager;let u=null;const l=()=>t.status,h=()=>t.state;for(;6!==h()&&0!==h();)switch(n.signal?.throwIfAborted(),E(`[context#${t.id}] ${g.get(h())||h()}`),h()){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 r=this.fetchCollectionInfo(i,t.ns,e,n);for await(const e of r)if(t.addMongoOperationResponse((0,a.serialize)(e)),0===h())break;if(0===h())break;t.finishMongoOperation();break}case 2:{const e=t.nextMongoOperation();if(0===h())break;if(!s)throw new m.MongoCryptError("unreachable state machine state: entered MONGOCRYPT_CTX_NEED_MONGO_MARKINGS but mongocryptdClient is undefined");const r=c?await c.withRespawn(this.markCommand.bind(this,s,t.ns,e,n)):await this.markCommand(s,t.ns,e,n);t.addMongoOperationResponse(r),t.finishMongoOperation();break}case 3:{const e=t.nextMongoOperation(),i=await this.fetchKeys(o,r,e,n);0===i.length&&(u=S??=(0,a.serialize)({v:[]}));for(const e of i)t.addMongoOperationResponse((0,a.serialize)(e));t.finishMongoOperation();break}case 7:{const n=await e.askForKMSCredentials();t.provideKMSProviders((0,a.serialize)(n));break}case 4:await Promise.all(this.requests(t,n)),t.finishKMSRequests();break;case 5:{const e=t.finalize();if(0===h()){const e=l().message||"Finalization error";throw new m.MongoCryptError(e)}u=e;break}default:throw new m.MongoCryptError(`Unknown state: ${h()}`)}if(0===h()||null==u){const e=l().message;throw e||E("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 n=e.endpoint.split(":"),r=null!=n[1]?Number.parseInt(n[1],10):443,o={host:n[0],servername:n[0],port:r,...(0,p.autoSelectSocketOptions)(this.options.socketOptions||{})},a=e.message,c=new d.BufferPool;let g,y;function E(){for(const e of[y,g])e&&e.destroy()}function S(e){return new m.MongoCryptError("KMS request failed",{cause:e})}function O(){return new m.MongoCryptError("KMS request closed")}const C=this.options.tlsOptions;if(C){const t=e.kmsProvider,n=C[t];if(n){const e=this.validateTlsOptions(t,n);if(e)throw e;try{await this.setTlsOptions(n,o)}catch(e){throw S(e)}}}let v;try{if(this.options.proxyOptions&&this.options.proxyOptions.proxyHost){g=new i.Socket;const{promise:e,reject:t,resolve:n}=(0,d.promiseWithResolvers)();g.once("error",(e=>t(S(e)))).once("close",(()=>t(O()))).once("connect",(()=>n()));const r={...o,host:this.options.proxyOptions.proxyHost,port:this.options.proxyOptions.proxyPort||1080};g.connect(r),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 S(e)}}y=s.connect(o,(()=>{y.write(a)}));const{promise:n,reject:r,resolve:l}=(0,d.promiseWithResolvers)();v=(0,d.addAbortListener)(t?.signal,(function(){E(),r(this.reason)})),y.once("error",(e=>r(S(e)))).once("close",(()=>r(O()))).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([n,h.Timeout.expires(t.timeoutContext?.remainingTimeMS)]):n)}catch(e){if(e instanceof h.TimeoutError)throw new l.MongoOperationTimeoutError("KMS request timed out");throw e}finally{E(),v?.[d.kDispose]()}}*requests(e,t){for(let n=e.nextKMSRequest();null!=n;n=e.nextKMSRequest())yield this.kmsRequest(n,t)}validateTlsOptions(e,t){const n=Object.keys(t);for(const t of y)if(n.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 n=await o.readFile(e.tlsCertificateKeyFile);t.cert=t.key=n}e.tlsCAFile&&(t.ca=await o.readFile(e.tlsCAFile)),e.tlsCertificateKeyFilePassword&&(t.passphrase=e.tlsCertificateKeyFilePassword)}fetchCollectionInfo(e,t,n,r){const{db:o}=d.MongoDBCollectionNamespace.fromString(t);return e.db(o).listCollections(n,{promoteLongs:!1,promoteValues:!1,timeoutContext:r?.timeoutContext&&new c.CursorTimeoutContext(r?.timeoutContext,Symbol()),signal:r?.signal,nameOnly:!1})}async markCommand(e,t,n,r){const{db:o}=d.MongoDBCollectionNamespace.fromString(t),i={promoteLongs:!1,promoteValues:!1},s=(0,a.deserialize)(n,i),c={timeoutMS:void 0,signal:void 0};r?.timeoutContext?.csotEnabled()&&(c.timeoutMS=r.timeoutContext.remainingTimeMS),r?.signal&&(c.signal=r.signal);const u=await e.db(o).command(s,{...i,...c});return(0,a.serialize)(u,this.bsonOptions)}fetchKeys(e,t,n,r){const{db:o,collection:i}=d.MongoDBCollectionNamespace.fromString(t),s={timeoutContext:void 0,signal:void 0};return null!=r?.timeoutContext&&(s.timeoutContext=new c.CursorTimeoutContext(r.timeoutContext,Symbol())),null!=r?.signal&&(s.signal=r.signal),e.db(o).collection(i,{readConcern:{level:"majority"}}).find((0,a.deserialize)(n),s).toArray()}}},97531:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onData=function(e,{timeoutContext:t,signal:n}){n?.throwIfAborted();const o=new r.List,i=new r.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:n,reject:c}=(0,r.promiseWithResolvers)();return i.push({resolve:n,reject:c}),t},return:()=>p(),throw:e=>(d(e),Promise.resolve({value:void 0,done:!0})),[Symbol.asyncIterator](){return this},async[Symbol.asyncDispose](){await p()}};e.on("data",h),e.on("error",d);const u=(0,r.addAbortListener)(n,(function(){d(this.reason)})),l=t?.timeoutForSocketRead;return l?.throwIfExpired(),l?.then(void 0,d),c;function h(e){const t=i.shift();null!=t?t.resolve({value:e,done:!1}):o.push(e)}function d(e){const t=i.shift();null!=t?t.reject(e):s=e,p()}function p(){e.off("data",h),e.off("error",d),u?.[r.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 r=n(145)},97557:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MongoLogWriter=void 0,t.mongoLogId=a;const r=n(62444),o=n(93874),i=n(98437),s=Symbol("kFlushDummy");function a(e){return{__value:e}}class c extends o.Writable{constructor(e,t,n,r){super({objectMode:!0}),this.mongoLogId=a,this._logId=e,this._logFilePath=t,this._target=n,this._now=r??(()=>new Date)}get logId(){return this._logId}get logFilePath(){return this._logFilePath}get target(){return this._target}_write(e,t,o){if(e===s)return void this._target.write("",o);const a=function(e){return"string"!=typeof e.s?new TypeError("Cannot log messages without a severity field"):"string"!=typeof e.c?new TypeError("Cannot log messages without a component field"):"number"!=typeof e.id?.__value?new TypeError("Cannot log messages without an id field"):"string"!=typeof e.ctx?new TypeError("Cannot log messages without a context field"):"string"!=typeof e.msg?new TypeError("Cannot log messages without a message field"):null}(e);if(a)return void o(a);const c={t:e.t??this._now(),s:e.s,c:e.c,id:e.id.__value,ctx:e.ctx,msg:e.msg};e.attr&&("[object Error]"===Object.prototype.toString.call(e.attr)?c.attr={stack:e.attr.stack,name:e.attr.name,message:e.attr.message,code:e.attr.code,...e.attr}:c.attr=e.attr),this.emit("log",c);try{r.EJSON.stringify(c.attr)}catch{try{const e=n(96062),t=e.deserialize(e.serialize(c.attr));r.EJSON.stringify(t),c.attr=t}catch{try{const e=JSON.parse(JSON.stringify(c.attr));r.EJSON.stringify(e),c.attr=e}catch{c.attr={_inspected:(0,i.inspect)(c.attr)}}}}this._target.write(r.EJSON.stringify(c,{relaxed:!0})+"\n",o)}_final(e){this._target.end(e)}async flush(){await new Promise((e=>this.write(s,e)))}info(e,t,n,r,o){const i={s:"I",c:e,id:t,ctx:n,msg:r,attr:o};this.write(i)}warn(e,t,n,r,o){const i={s:"W",c:e,id:t,ctx:n,msg:r,attr:o};this.write(i)}error(e,t,n,r,o){const i={s:"E",c:e,id:t,ctx:n,msg:r,attr:o};this.write(i)}fatal(e,t,n,r,o){const i={s:"F",c:e,id:t,ctx:n,msg:r,attr:o};this.write(i)}debug(e,t,n,r,o,i=1){const s={s:`D${i}`,c:e,id:t,ctx:n,msg:r,attr:o};this.write(s)}bindComponent(e){return{unbound:this,component:e,write:(t,n)=>this.write({c:e,...t},n),info:this.info.bind(this,e),warn:this.warn.bind(this,e),error:this.error.bind(this,e),fatal:this.fatal.bind(this,e),debug:this.debug.bind(this,e)}}}t.MongoLogWriter=c},98362:(e,t,n)=>{n.d(t,{Ay:()=>o,J0:()=>a,QZ:()=>s,Y6:()=>i});var r=n(65031);const o=r.default,i=r.CommaAndColonSeparatedRecord,s=r.ConnectionString,a=r.redactConnectionString}};