odm-client 0.0.17 → 0.0.18
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cloudbase.cjs +1 -1
- package/dist/cloudbase.js +2 -1
- package/dist/generate.cjs +5 -4
- package/dist/generate.js +17 -16
- package/dist/mongodb.cjs +2 -2
- package/dist/mongodb.js +3 -2
- package/package.json +3 -2
- /package/dist/deps/{_commonjsHelpers-KaVRbhAgd4-k7xu9f3be.js → _commonjsHelpers-KaVRbhAgd4-03ar4sqy5.js} +0 -0
- /package/dist/deps/{_commonjsHelpers-KaVRbhAgd4-n6ibh2onf.js → _commonjsHelpers-KaVRbhAgd4-fdb59sc98.js} +0 -0
- /package/dist/deps/{acorn-DYjaOAP8Gz-0l3eiitjk.js → acorn-DYjaOAP8Gz-mprj6jnxi.js} +0 -0
- /package/dist/deps/{acorn-DYjaOAP8Gz-qiwhnpenq.js → acorn-DYjaOAP8Gz-p8kmidf20.js} +0 -0
- /package/dist/deps/{angular-1bp1uAROl4-xi8mak4yk.js → angular-1bp1uAROl4-c5htyp0di.js} +0 -0
- /package/dist/deps/{angular-1bp1uAROl4-7l21w46cs.js → angular-1bp1uAROl4-u3ml7ap3h.js} +0 -0
- /package/dist/deps/{babel-_P9jsDBVVy-i7snanhj4.js → babel-_P9jsDBVVy-pjc422kzy.js} +0 -0
- /package/dist/deps/{babel-_P9jsDBVVy-v4ypuim9t.js → babel-_P9jsDBVVy-x3d4xx9qd.js} +0 -0
- /package/dist/deps/{estree-Q-oFBmJEml-4vkbucmdi.js → estree-Q-oFBmJEml-ma8g33dzz.js} +0 -0
- /package/dist/deps/{estree-Q-oFBmJEml-906aaz9hr.js → estree-Q-oFBmJEml-vfehdwrya.js} +0 -0
- /package/dist/deps/{flow-j77MFvzLrn-ego53bkq8.js → flow-j77MFvzLrn-2ad2bmbdd.js} +0 -0
- /package/dist/deps/{flow-j77MFvzLrn-z9uvt0xam.js → flow-j77MFvzLrn-r36w4e2zx.js} +0 -0
- /package/dist/deps/{glimmer-ewQPb5nTUl-zq6jsxdvg.js → glimmer-ewQPb5nTUl-3rgm5q14v.js} +0 -0
- /package/dist/deps/{glimmer-ewQPb5nTUl-yf2zjnmny.js → glimmer-ewQPb5nTUl-481baxyy3.js} +0 -0
- /package/dist/deps/{graphql-8EXR1_taGG-fgbb1yizz.js → graphql-8EXR1_taGG-lnxgcb0w9.js} +0 -0
- /package/dist/deps/{graphql-8EXR1_taGG-c8wbixo5f.js → graphql-8EXR1_taGG-rzymqt8fy.js} +0 -0
- /package/dist/deps/{html-dGbiW_CFWL-kir66ndee.js → html-dGbiW_CFWL-40yu2u4e6.js} +0 -0
- /package/dist/deps/{html-dGbiW_CFWL-4zlivfsh2.js → html-dGbiW_CFWL-dzlhzg9pz.js} +0 -0
- /package/dist/deps/{markdown-vAYIRClyWZ-iwh0lu9pv.js → markdown-vAYIRClyWZ-1fmyewm6z.js} +0 -0
- /package/dist/deps/{markdown-vAYIRClyWZ-orec5aiwm.js → markdown-vAYIRClyWZ-zf9xwz1sq.js} +0 -0
- /package/dist/deps/{meriyah-d5_qqf88x--s2lz6m6tn.js → meriyah-d5_qqf88x--m61ty912m.js} +0 -0
- /package/dist/deps/{meriyah-d5_qqf88x--jarb5mxpb.js → meriyah-d5_qqf88x--uvavpzqnv.js} +0 -0
- /package/dist/deps/{postcss-Vz5bDQ3hJO-7w3qaz1hk.js → postcss-Vz5bDQ3hJO-86j58fvex.js} +0 -0
- /package/dist/deps/{postcss-Vz5bDQ3hJO-bt2jfhksq.js → postcss-Vz5bDQ3hJO-ho5uxa5fm.js} +0 -0
- /package/dist/deps/{query-builder-h6B2D2BCoQ-fdhmp9vaj.js → query-builder-h6B2D2BCoQ-0q1h4k5qp.js} +0 -0
- /package/dist/deps/{query-builder-h6B2D2BCoQ-92aesjjj2.js → query-builder-h6B2D2BCoQ-fwdekajgq.js} +0 -0
- /package/dist/deps/{typescript-2hCq12HCbJ-8xhrv2djr.js → typescript-2hCq12HCbJ-hkh5nls6s.js} +0 -0
- /package/dist/deps/{typescript-2hCq12HCbJ-ssg42eo1c.js → typescript-2hCq12HCbJ-lq3vsk4t6.js} +0 -0
- /package/dist/deps/{yaml-I5o0CrcX7J-dp5rovmi5.js → yaml-I5o0CrcX7J-9wwc5lde7.js} +0 -0
- /package/dist/deps/{yaml-I5o0CrcX7J-6cj7ocyif.js → yaml-I5o0CrcX7J-l75btumtu.js} +0 -0
package/dist/mongodb.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var Ql=Object.defineProperty;var Zl=(e,t,r)=>t in e?Ql(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var se=(e,t,r)=>Zl(e,typeof t!="symbol"?t+"":t,r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const pt=require("./deps/query-builder-h6B2D2BCoQ-92aesjjj2.js"),En=require("timers"),bc=require("crypto"),_1=require("fs"),$l=require("http"),Ar=require("process"),uo=require("stream"),e2=require("events"),t2=require("util"),Mc=require("timers/promises"),D1=require("dns"),Fc=require("os"),Ye=require("./deps/_commonjsHelpers-KaVRbhAgd4-k7xu9f3be.js"),r2=require("url"),Rc=require("zlib"),T1=require("net"),Nc=require("fs/promises"),Ic=require("tls"),n2=require("child_process");var ns={},$n={},pe={},Oe={};const i2=(()=>{const e=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),Symbol.toStringTag).get;return t=>e.call(t)})();function hr(e){return i2(e)==="Uint8Array"}function B1(e){return typeof e=="object"&&e!=null&&Symbol.toStringTag in e&&(e[Symbol.toStringTag]==="ArrayBuffer"||e[Symbol.toStringTag]==="SharedArrayBuffer")}function sn(e){return e instanceof RegExp||Object.prototype.toString.call(e)==="[object RegExp]"}function b1(e){return typeof e=="object"&&e!=null&&Symbol.toStringTag in e&&e[Symbol.toStringTag]==="Map"}function un(e){return e instanceof Date||Object.prototype.toString.call(e)==="[object Date]"}function gt(e,t){return JSON.stringify(e,(r,n)=>typeof n=="bigint"?{$numberLong:`${n}`}:b1(n)?Object.fromEntries(n):n)}function o2(e){if(e!=null&&typeof e=="object"&&"stylize"in e&&typeof e.stylize=="function")return e.stylize}const Fr=7,hn=Symbol.for("@@mdb.bson.version"),ei=2147483647,ti=-2147483648,vc=Math.pow(2,63)-1,Pc=-Math.pow(2,63),Lc=Math.pow(2,53),kc=-Math.pow(2,53),M1=1,Uc=2,F1=3,jc=4,R1=5,s2=6,xc=7,zc=8,Vc=9,N1=10,Ki=11,u2=12,I1=13,Wc=14,Gc=15,qn=16,qc=17,v1=18,Hc=19,Kc=255,Yc=127,a2=0,P1=4,Xc=Object.freeze({double:1,string:2,object:3,array:4,binData:5,undefined:6,objectId:7,bool:8,date:9,null:10,regex:11,dbPointer:12,javascript:13,symbol:14,javascriptWithScope:15,int:16,timestamp:17,long:18,decimal:19,minKey:-1,maxKey:127});class q extends Error{get bsonError(){return!0}get name(){return"BSONError"}constructor(t,r){super(t,r)}static isBSONError(t){return t!=null&&typeof t=="object"&&"bsonError"in t&&t.bsonError===!0&&"name"in t&&"message"in t&&"stack"in t}}class Rr extends q{get name(){return"BSONVersionError"}constructor(){super(`Unsupported BSON version, bson types must be from bson ${Fr}.x.x`)}}class Yi extends q{get name(){return"BSONRuntimeError"}constructor(t){super(t)}}class zt extends q{constructor(r,n,i){super(`${r}. offset: ${n}`,i);se(this,"offset");this.offset=n}get name(){return"BSONOffsetError"}}let Fu,Ru;function Jc(e,t,r,n){if(n){Fu??(Fu=new TextDecoder("utf8",{fatal:!0}));try{return Fu.decode(e.subarray(t,r))}catch(i){throw new q("Invalid UTF-8 string in BSON document",{cause:i})}}return Ru??(Ru=new TextDecoder("utf8",{fatal:!1})),Ru.decode(e.subarray(t,r))}function Qc(e,t,r){if(e.length===0)return"";const n=r-t;if(n===0)return"";if(n>20)return null;if(n===1&&e[t]<128)return String.fromCharCode(e[t]);if(n===2&&e[t]<128&&e[t+1]<128)return String.fromCharCode(e[t])+String.fromCharCode(e[t+1]);if(n===3&&e[t]<128&&e[t+1]<128&&e[t+2]<128)return String.fromCharCode(e[t])+String.fromCharCode(e[t+1])+String.fromCharCode(e[t+2]);const i=[];for(let o=t;o<r;o++){const u=e[o];if(u>127)return null;i.push(u)}return String.fromCharCode(...i)}function c2(e,t,r){if(t.length===0)return 0;if(t.length>25||e.length-r<t.length)return null;for(let n=0,i=r;n<t.length;n++,i++){const o=t.charCodeAt(n);if(o>127)return null;e[i]=o}return t.length}function l2(e){return wt.fromNumberArray(Array.from({length:e},()=>Math.floor(Math.random()*256)))}function h2(e){return crypto.getRandomValues(wt.allocate(e))}const d2=(()=>{const{crypto:e}=globalThis;return e!=null&&typeof e.getRandomValues=="function"?h2:l2})(),wt={isUint8Array:hr,toLocalBufferType(e){if(Buffer.isBuffer(e))return e;if(ArrayBuffer.isView(e))return Buffer.from(e.buffer,e.byteOffset,e.byteLength);const t=(e==null?void 0:e[Symbol.toStringTag])??Object.prototype.toString.call(e);if(t==="ArrayBuffer"||t==="SharedArrayBuffer"||t==="[object ArrayBuffer]"||t==="[object SharedArrayBuffer]")return Buffer.from(e);throw new q("Cannot create Buffer from the passed potentialBuffer.")},allocate(e){return Buffer.alloc(e)},allocateUnsafe(e){return Buffer.allocUnsafe(e)},compare(e,t){return wt.toLocalBufferType(e).compare(t)},concat(e){return Buffer.concat(e)},copy(e,t,r,n,i){return wt.toLocalBufferType(e).copy(t,r??0,n??0,i??e.length)},equals(e,t){return wt.toLocalBufferType(e).equals(t)},fromNumberArray(e){return Buffer.from(e)},fromBase64(e){return Buffer.from(e,"base64")},fromUTF8(e){return Buffer.from(e,"utf8")},toBase64(e){return wt.toLocalBufferType(e).toString("base64")},fromISO88591(e){return Buffer.from(e,"binary")},toISO88591(e){return wt.toLocalBufferType(e).toString("binary")},fromHex(e){return Buffer.from(e,"hex")},toHex(e){return wt.toLocalBufferType(e).toString("hex")},toUTF8(e,t,r,n){const i=r-t<=20?Qc(e,t,r):null;if(i!=null)return i;const o=wt.toLocalBufferType(e).toString("utf8",t,r);if(n){for(let u=0;u<o.length;u++)if(o.charCodeAt(u)===65533){Jc(e,t,r,!0);break}}return o},utf8ByteLength(e){return Buffer.byteLength(e,"utf8")},encodeUTF8Into(e,t,r){const n=c2(e,t,r);return n??wt.toLocalBufferType(e).write(t,r,void 0,"utf8")},randomBytes:d2,swap32(e){return wt.toLocalBufferType(e).swap32()}};function f2(){const{navigator:e}=globalThis;return typeof e=="object"&&e.product==="ReactNative"}function m2(e){if(e<0)throw new RangeError(`The argument 'byteLength' is invalid. Received ${e}`);return br.fromNumberArray(Array.from({length:e},()=>Math.floor(Math.random()*256)))}const E2=(()=>{var t;const{crypto:e}=globalThis;if(e!=null&&typeof e.getRandomValues=="function")return r=>e.getRandomValues(br.allocate(r));if(f2()){const{console:r}=globalThis;(t=r==null?void 0:r.warn)==null||t.call(r,"BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.")}return m2})(),Nu=/(\d|[a-f])/i,br={isUint8Array:hr,toLocalBufferType(e){const t=(e==null?void 0:e[Symbol.toStringTag])??Object.prototype.toString.call(e);if(t==="Uint8Array")return e;if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength));if(t==="ArrayBuffer"||t==="SharedArrayBuffer"||t==="[object ArrayBuffer]"||t==="[object SharedArrayBuffer]")return new Uint8Array(e);throw new q("Cannot make a Uint8Array from passed potentialBuffer.")},allocate(e){if(typeof e!="number")throw new TypeError(`The "size" argument must be of type number. Received ${String(e)}`);return new Uint8Array(e)},allocateUnsafe(e){return br.allocate(e)},compare(e,t){if(e===t)return 0;const r=Math.min(e.length,t.length);for(let n=0;n<r;n++){if(e[n]<t[n])return-1;if(e[n]>t[n])return 1}return e.length<t.length?-1:e.length>t.length?1:0},concat(e){if(e.length===0)return br.allocate(0);let t=0;for(const i of e)t+=i.length;const r=br.allocate(t);let n=0;for(const i of e)r.set(i,n),n+=i.length;return r},copy(e,t,r,n,i){if(i!==void 0&&i<0)throw new RangeError(`The value of "sourceEnd" is out of range. It must be >= 0. Received ${i}`);if(i=i??e.length,n!==void 0&&(n<0||n>i))throw new RangeError(`The value of "sourceStart" is out of range. It must be >= 0 and <= ${i}. Received ${n}`);if(n=n??0,r!==void 0&&r<0)throw new RangeError(`The value of "targetStart" is out of range. It must be >= 0. Received ${r}`);r=r??0;const o=e.subarray(n,i),u=Math.min(o.length,t.length-r);return u<=0?0:(t.set(o.subarray(0,u),r),u)},equals(e,t){if(e.byteLength!==t.byteLength)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0},fromNumberArray(e){return Uint8Array.from(e)},fromBase64(e){return Uint8Array.from(atob(e),t=>t.charCodeAt(0))},fromUTF8(e){return new TextEncoder().encode(e)},toBase64(e){return btoa(br.toISO88591(e))},fromISO88591(e){return Uint8Array.from(e,t=>t.charCodeAt(0)&255)},toISO88591(e){return Array.from(Uint16Array.from(e),t=>String.fromCharCode(t)).join("")},fromHex(e){const t=e.length%2===0?e:e.slice(0,e.length-1),r=[];for(let n=0;n<t.length;n+=2){const i=t[n],o=t[n+1];if(!Nu.test(i)||!Nu.test(o))break;const u=Number.parseInt(`${i}${o}`,16);r.push(u)}return Uint8Array.from(r)},toHex(e){return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")},toUTF8(e,t,r,n){const i=r-t<=20?Qc(e,t,r):null;return i??Jc(e,t,r,n)},utf8ByteLength(e){return new TextEncoder().encode(e).byteLength},encodeUTF8Into(e,t,r){const n=new TextEncoder().encode(t);return e.set(n,r),n.byteLength},randomBytes:E2,swap32(e){if(e.length%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let t=0;t<e.length;t+=4){const r=e[t],n=e[t+1],i=e[t+2],o=e[t+3];e[t]=o,e[t+1]=i,e[t+2]=n,e[t+3]=r}return e}};var Bc;const g2=typeof Buffer=="function"&&((Bc=Buffer.prototype)==null?void 0:Bc._isBuffer)!==!0,W=g2?wt:br,ao=Symbol.for("@@mdb.bson.type");class ct{get[ao](){return this._bsontype}get[hn](){return Fr}[Symbol.for("nodejs.util.inspect.custom")](t,r,n){return this.inspect(t,r,n)}}const an=new Float64Array(1),we=new Uint8Array(an.buffer,0,8);an[0]=-1;const is=we[7]===0,ue={isBigEndian:is,getNonnegativeInt32LE(e,t){if(e[t+3]>127)throw new RangeError(`Size cannot be negative at offset: ${t}`);return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24},getInt32LE(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24},getUint32LE(e,t){return e[t]+e[t+1]*256+e[t+2]*65536+e[t+3]*16777216},getUint32BE(e,t){return e[t+3]+e[t+2]*256+e[t+1]*65536+e[t]*16777216},getBigInt64LE(e,t){const r=BigInt(e[t+4]+e[t+5]*256+e[t+6]*65536+(e[t+7]<<24)),n=BigInt(e[t]+e[t+1]*256+e[t+2]*65536+e[t+3]*16777216);return(r<<32n)+n},getFloat64LE:is?(e,t)=>(we[7]=e[t],we[6]=e[t+1],we[5]=e[t+2],we[4]=e[t+3],we[3]=e[t+4],we[2]=e[t+5],we[1]=e[t+6],we[0]=e[t+7],an[0]):(e,t)=>(we[0]=e[t],we[1]=e[t+1],we[2]=e[t+2],we[3]=e[t+3],we[4]=e[t+4],we[5]=e[t+5],we[6]=e[t+6],we[7]=e[t+7],an[0]),setInt32BE(e,t,r){return e[t+3]=r,r>>>=8,e[t+2]=r,r>>>=8,e[t+1]=r,r>>>=8,e[t]=r,4},setInt32LE(e,t,r){return e[t]=r,r>>>=8,e[t+1]=r,r>>>=8,e[t+2]=r,r>>>=8,e[t+3]=r,4},setBigInt64LE(e,t,r){const n=0xffffffffn;let i=Number(r&n);e[t]=i,i>>=8,e[t+1]=i,i>>=8,e[t+2]=i,i>>=8,e[t+3]=i;let o=Number(r>>32n&n);return e[t+4]=o,o>>=8,e[t+5]=o,o>>=8,e[t+6]=o,o>>=8,e[t+7]=o,8},setFloat64LE:is?(e,t,r)=>(an[0]=r,e[t]=we[7],e[t+1]=we[6],e[t+2]=we[5],e[t+3]=we[4],e[t+4]=we[3],e[t+5]=we[2],e[t+6]=we[1],e[t+7]=we[0],8):(e,t,r)=>(an[0]=r,e[t]=we[0],e[t+1]=we[1],e[t+2]=we[2],e[t+3]=we[3],e[t+4]=we[4],e[t+5]=we[5],e[t+6]=we[6],e[t+7]=we[7],8)},ge=class ge extends ct{constructor(r,n){super();se(this,"buffer");se(this,"sub_type");se(this,"position");if(r!=null&&typeof r=="string"&&!ArrayBuffer.isView(r)&&!B1(r)&&!Array.isArray(r))throw new q("Binary can only be constructed from Uint8Array or number[]");this.sub_type=n??ge.BSON_BINARY_SUBTYPE_DEFAULT,r==null?(this.buffer=W.allocate(ge.BUFFER_SIZE),this.position=0):(this.buffer=Array.isArray(r)?W.fromNumberArray(r):W.toLocalBufferType(r),this.position=this.buffer.byteLength)}get _bsontype(){return"Binary"}put(r){if(typeof r=="string"&&r.length!==1)throw new q("only accepts single character String");if(typeof r!="number"&&r.length!==1)throw new q("only accepts single character Uint8Array or Array");let n;if(typeof r=="string"?n=r.charCodeAt(0):typeof r=="number"?n=r:n=r[0],n<0||n>255)throw new q("only accepts number in a valid unsigned byte range 0-255");if(this.buffer.byteLength>this.position)this.buffer[this.position++]=n;else{const i=W.allocate(ge.BUFFER_SIZE+this.buffer.length);i.set(this.buffer,0),this.buffer=i,this.buffer[this.position++]=n}}write(r,n){if(n=typeof n=="number"?n:this.position,this.buffer.byteLength<n+r.length){const i=W.allocate(this.buffer.byteLength+r.length);i.set(this.buffer,0),this.buffer=i}if(ArrayBuffer.isView(r))this.buffer.set(W.toLocalBufferType(r),n),this.position=n+r.byteLength>this.position?n+r.length:this.position;else if(typeof r=="string")throw new q("input cannot be string")}read(r,n){n=n&&n>0?n:this.position;const i=r+n;return this.buffer.subarray(r,i>this.position?this.position:i)}value(){return this.buffer.length===this.position?this.buffer:this.buffer.subarray(0,this.position)}length(){return this.position}toJSON(){return W.toBase64(this.buffer.subarray(0,this.position))}toString(r){return r==="hex"?W.toHex(this.buffer.subarray(0,this.position)):r==="base64"?W.toBase64(this.buffer.subarray(0,this.position)):r==="utf8"||r==="utf-8"?W.toUTF8(this.buffer,0,this.position,!1):W.toUTF8(this.buffer,0,this.position,!1)}toExtendedJSON(r){r=r||{},this.sub_type===ge.SUBTYPE_VECTOR&&Yt(this);const n=W.toBase64(this.buffer),i=Number(this.sub_type).toString(16);return r.legacy?{$binary:n,$type:i.length===1?"0"+i:i}:{$binary:{base64:n,subType:i.length===1?"0"+i:i}}}toUUID(){if(this.sub_type===ge.SUBTYPE_UUID)return new Je(this.buffer.subarray(0,this.position));throw new q(`Binary sub_type "${this.sub_type}" is not supported for converting to UUID. Only "${ge.SUBTYPE_UUID}" is currently supported.`)}static createFromHexString(r,n){return new ge(W.fromHex(r),n)}static createFromBase64(r,n){return new ge(W.fromBase64(r),n)}static fromExtendedJSON(r,n){n=n||{};let i,o;if("$binary"in r?n.legacy&&typeof r.$binary=="string"&&"$type"in r?(o=r.$type?parseInt(r.$type,16):0,i=W.fromBase64(r.$binary)):typeof r.$binary!="string"&&(o=r.$binary.subType?parseInt(r.$binary.subType,16):0,i=W.fromBase64(r.$binary.base64)):"$uuid"in r&&(o=4,i=Je.bytesFromString(r.$uuid)),!i)throw new q(`Unexpected Binary Extended JSON format ${JSON.stringify(r)}`);return o===P1?new Je(i):new ge(i,o)}inspect(r,n,i){i??(i=gt);const o=W.toBase64(this.buffer.subarray(0,this.position)),u=i(o,n),c=i(this.sub_type,n);return`Binary.createFromBase64(${u}, ${c})`}toInt8Array(){if(this.sub_type!==ge.SUBTYPE_VECTOR)throw new q("Binary sub_type is not Vector");if(this.buffer[0]!==ge.VECTOR_TYPE.Int8)throw new q("Binary datatype field is not Int8");return Yt(this),new Int8Array(this.buffer.buffer.slice(this.buffer.byteOffset+2,this.buffer.byteOffset+this.position))}toFloat32Array(){if(this.sub_type!==ge.SUBTYPE_VECTOR)throw new q("Binary sub_type is not Vector");if(this.buffer[0]!==ge.VECTOR_TYPE.Float32)throw new q("Binary datatype field is not Float32");Yt(this);const r=new Uint8Array(this.buffer.buffer.slice(this.buffer.byteOffset+2,this.buffer.byteOffset+this.position));return ue.isBigEndian&&W.swap32(r),new Float32Array(r.buffer)}toPackedBits(){if(this.sub_type!==ge.SUBTYPE_VECTOR)throw new q("Binary sub_type is not Vector");if(this.buffer[0]!==ge.VECTOR_TYPE.PackedBit)throw new q("Binary datatype field is not packed bit");return Yt(this),new Uint8Array(this.buffer.buffer.slice(this.buffer.byteOffset+2,this.buffer.byteOffset+this.position))}toBits(){if(this.sub_type!==ge.SUBTYPE_VECTOR)throw new q("Binary sub_type is not Vector");if(this.buffer[0]!==ge.VECTOR_TYPE.PackedBit)throw new q("Binary datatype field is not packed bit");Yt(this);const n=(this.length()-2)*8-this.buffer[1],i=new Int8Array(n);for(let o=0;o<i.length;o++){const u=o/8|0,c=this.buffer[u+2],s=7-o%8,a=c>>s&1;i[o]=a}return i}static fromInt8Array(r){const n=W.allocate(r.byteLength+2);n[0]=ge.VECTOR_TYPE.Int8,n[1]=0;const i=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);n.set(i,2);const o=new this(n,this.SUBTYPE_VECTOR);return Yt(o),o}static fromFloat32Array(r){const n=W.allocate(r.byteLength+2);n[0]=ge.VECTOR_TYPE.Float32,n[1]=0;const i=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);n.set(i,2),ue.isBigEndian&&W.swap32(new Uint8Array(n.buffer,2));const o=new this(n,this.SUBTYPE_VECTOR);return Yt(o),o}static fromPackedBits(r,n=0){const i=W.allocate(r.byteLength+2);i[0]=ge.VECTOR_TYPE.PackedBit,i[1]=n,i.set(r,2);const o=new this(i,this.SUBTYPE_VECTOR);return Yt(o),o}static fromBits(r){const n=r.length+7>>>3,i=new Uint8Array(n+2);i[0]=ge.VECTOR_TYPE.PackedBit;const o=r.length%8;i[1]=o===0?0:8-o;for(let u=0;u<r.length;u++){const c=u>>>3,s=r[u];if(s!==0&&s!==1)throw new q(`Invalid bit value at ${u}: must be 0 or 1, found ${r[u]}`);if(s===0)continue;const a=7-u%8;i[c+2]|=s<<a}return new this(i,ge.SUBTYPE_VECTOR)}};se(ge,"BSON_BINARY_SUBTYPE_DEFAULT",0),se(ge,"BUFFER_SIZE",256),se(ge,"SUBTYPE_DEFAULT",0),se(ge,"SUBTYPE_FUNCTION",1),se(ge,"SUBTYPE_BYTE_ARRAY",2),se(ge,"SUBTYPE_UUID_OLD",3),se(ge,"SUBTYPE_UUID",4),se(ge,"SUBTYPE_MD5",5),se(ge,"SUBTYPE_ENCRYPTED",6),se(ge,"SUBTYPE_COLUMN",7),se(ge,"SUBTYPE_SENSITIVE",8),se(ge,"SUBTYPE_VECTOR",9),se(ge,"SUBTYPE_USER_DEFINED",128),se(ge,"VECTOR_TYPE",Object.freeze({Int8:3,Float32:39,PackedBit:16}));let je=ge;function Yt(e){if(e.sub_type!==je.SUBTYPE_VECTOR)return;const t=e.position,r=e.buffer[0],n=e.buffer[1];if((r===je.VECTOR_TYPE.Float32||r===je.VECTOR_TYPE.Int8)&&n!==0)throw new q("Invalid Vector: padding must be zero for int8 and float32 vectors");if(r===je.VECTOR_TYPE.Float32&&t!==0&&t-2!==0&&(t-2)%4!==0)throw new q("Invalid Vector: Float32 vector must contain a multiple of 4 bytes");if(r===je.VECTOR_TYPE.PackedBit&&n!==0&&t===2)throw new q("Invalid Vector: padding must be zero for packed bit vectors that are empty");if(r===je.VECTOR_TYPE.PackedBit&&n>7)throw new q(`Invalid Vector: padding must be a value between 0 and 7. found: ${n}`)}const os=16,A2=/^[0-9A-F]{32}$/i,p2=/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i;class Je extends je{constructor(t){let r;if(t==null)r=Je.generate();else if(t instanceof Je)r=W.toLocalBufferType(new Uint8Array(t.buffer));else if(ArrayBuffer.isView(t)&&t.byteLength===os)r=W.toLocalBufferType(t);else if(typeof t=="string")r=Je.bytesFromString(t);else throw new q("Argument passed in UUID constructor must be a UUID, a 16 byte Buffer or a 32/36 character hex string (dashes excluded/included, format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).");super(r,P1)}get id(){return this.buffer}set id(t){this.buffer=t}toHexString(t=!0){return t?[W.toHex(this.buffer.subarray(0,4)),W.toHex(this.buffer.subarray(4,6)),W.toHex(this.buffer.subarray(6,8)),W.toHex(this.buffer.subarray(8,10)),W.toHex(this.buffer.subarray(10,16))].join("-"):W.toHex(this.buffer)}toString(t){return t==="hex"?W.toHex(this.id):t==="base64"?W.toBase64(this.id):this.toHexString()}toJSON(){return this.toHexString()}equals(t){if(!t)return!1;if(t instanceof Je)return W.equals(t.id,this.id);try{return W.equals(new Je(t).id,this.id)}catch{return!1}}toBinary(){return new je(this.id,je.SUBTYPE_UUID)}static generate(){const t=W.randomBytes(os);return t[6]=t[6]&15|64,t[8]=t[8]&63|128,t}static isValid(t){return t?typeof t=="string"?Je.isValidUUIDString(t):hr(t)?t.byteLength===os:t._bsontype==="Binary"&&t.sub_type===this.SUBTYPE_UUID&&t.buffer.byteLength===16:!1}static createFromHexString(t){const r=Je.bytesFromString(t);return new Je(r)}static createFromBase64(t){return new Je(W.fromBase64(t))}static bytesFromString(t){if(!Je.isValidUUIDString(t))throw new q("UUID string representation must be 32 hex digits or canonical hyphenated representation");return W.fromHex(t.replace(/-/g,""))}static isValidUUIDString(t){return A2.test(t)||p2.test(t)}inspect(t,r,n){return n??(n=gt),`new UUID(${n(this.toHexString(),r)})`}}class $t extends ct{constructor(r,n){super();se(this,"code");se(this,"scope");this.code=r.toString(),this.scope=n??null}get _bsontype(){return"Code"}toJSON(){return this.scope!=null?{code:this.code,scope:this.scope}:{code:this.code}}toExtendedJSON(){return this.scope?{$code:this.code,$scope:this.scope}:{$code:this.code}}static fromExtendedJSON(r){return new $t(r.$code,r.$scope)}inspect(r,n,i){i??(i=gt);let o=i(this.code,n);const u=o.includes(`
|
|
1
|
+
"use strict";var Ql=Object.defineProperty;var Zl=(e,t,r)=>t in e?Ql(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var se=(e,t,r)=>Zl(e,typeof t!="symbol"?t+"":t,r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const pt=require("./deps/query-builder-h6B2D2BCoQ-fwdekajgq.js"),En=require("timers"),bc=require("crypto"),_1=require("fs"),$l=require("http"),Ar=require("process"),uo=require("stream"),e2=require("events"),t2=require("util"),Mc=require("timers/promises"),D1=require("dns"),Fc=require("os"),Ye=require("./deps/_commonjsHelpers-KaVRbhAgd4-03ar4sqy5.js"),r2=require("url"),Rc=require("zlib"),T1=require("net"),Nc=require("fs/promises"),Ic=require("tls"),n2=require("child_process");var ns={},$n={},pe={},Oe={};const i2=(()=>{const e=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),Symbol.toStringTag).get;return t=>e.call(t)})();function hr(e){return i2(e)==="Uint8Array"}function B1(e){return typeof e=="object"&&e!=null&&Symbol.toStringTag in e&&(e[Symbol.toStringTag]==="ArrayBuffer"||e[Symbol.toStringTag]==="SharedArrayBuffer")}function sn(e){return e instanceof RegExp||Object.prototype.toString.call(e)==="[object RegExp]"}function b1(e){return typeof e=="object"&&e!=null&&Symbol.toStringTag in e&&e[Symbol.toStringTag]==="Map"}function un(e){return e instanceof Date||Object.prototype.toString.call(e)==="[object Date]"}function gt(e,t){return JSON.stringify(e,(r,n)=>typeof n=="bigint"?{$numberLong:`${n}`}:b1(n)?Object.fromEntries(n):n)}function o2(e){if(e!=null&&typeof e=="object"&&"stylize"in e&&typeof e.stylize=="function")return e.stylize}const Fr=7,hn=Symbol.for("@@mdb.bson.version"),ei=2147483647,ti=-2147483648,vc=Math.pow(2,63)-1,Pc=-Math.pow(2,63),Lc=Math.pow(2,53),kc=-Math.pow(2,53),M1=1,Uc=2,F1=3,jc=4,R1=5,s2=6,xc=7,zc=8,Vc=9,N1=10,Ki=11,u2=12,I1=13,Wc=14,Gc=15,qn=16,qc=17,v1=18,Hc=19,Kc=255,Yc=127,a2=0,P1=4,Xc=Object.freeze({double:1,string:2,object:3,array:4,binData:5,undefined:6,objectId:7,bool:8,date:9,null:10,regex:11,dbPointer:12,javascript:13,symbol:14,javascriptWithScope:15,int:16,timestamp:17,long:18,decimal:19,minKey:-1,maxKey:127});class q extends Error{get bsonError(){return!0}get name(){return"BSONError"}constructor(t,r){super(t,r)}static isBSONError(t){return t!=null&&typeof t=="object"&&"bsonError"in t&&t.bsonError===!0&&"name"in t&&"message"in t&&"stack"in t}}class Rr extends q{get name(){return"BSONVersionError"}constructor(){super(`Unsupported BSON version, bson types must be from bson ${Fr}.x.x`)}}class Yi extends q{get name(){return"BSONRuntimeError"}constructor(t){super(t)}}class zt extends q{constructor(r,n,i){super(`${r}. offset: ${n}`,i);se(this,"offset");this.offset=n}get name(){return"BSONOffsetError"}}let Fu,Ru;function Jc(e,t,r,n){if(n){Fu??(Fu=new TextDecoder("utf8",{fatal:!0}));try{return Fu.decode(e.subarray(t,r))}catch(i){throw new q("Invalid UTF-8 string in BSON document",{cause:i})}}return Ru??(Ru=new TextDecoder("utf8",{fatal:!1})),Ru.decode(e.subarray(t,r))}function Qc(e,t,r){if(e.length===0)return"";const n=r-t;if(n===0)return"";if(n>20)return null;if(n===1&&e[t]<128)return String.fromCharCode(e[t]);if(n===2&&e[t]<128&&e[t+1]<128)return String.fromCharCode(e[t])+String.fromCharCode(e[t+1]);if(n===3&&e[t]<128&&e[t+1]<128&&e[t+2]<128)return String.fromCharCode(e[t])+String.fromCharCode(e[t+1])+String.fromCharCode(e[t+2]);const i=[];for(let o=t;o<r;o++){const u=e[o];if(u>127)return null;i.push(u)}return String.fromCharCode(...i)}function c2(e,t,r){if(t.length===0)return 0;if(t.length>25||e.length-r<t.length)return null;for(let n=0,i=r;n<t.length;n++,i++){const o=t.charCodeAt(n);if(o>127)return null;e[i]=o}return t.length}function l2(e){return wt.fromNumberArray(Array.from({length:e},()=>Math.floor(Math.random()*256)))}function h2(e){return crypto.getRandomValues(wt.allocate(e))}const d2=(()=>{const{crypto:e}=globalThis;return e!=null&&typeof e.getRandomValues=="function"?h2:l2})(),wt={isUint8Array:hr,toLocalBufferType(e){if(Buffer.isBuffer(e))return e;if(ArrayBuffer.isView(e))return Buffer.from(e.buffer,e.byteOffset,e.byteLength);const t=(e==null?void 0:e[Symbol.toStringTag])??Object.prototype.toString.call(e);if(t==="ArrayBuffer"||t==="SharedArrayBuffer"||t==="[object ArrayBuffer]"||t==="[object SharedArrayBuffer]")return Buffer.from(e);throw new q("Cannot create Buffer from the passed potentialBuffer.")},allocate(e){return Buffer.alloc(e)},allocateUnsafe(e){return Buffer.allocUnsafe(e)},compare(e,t){return wt.toLocalBufferType(e).compare(t)},concat(e){return Buffer.concat(e)},copy(e,t,r,n,i){return wt.toLocalBufferType(e).copy(t,r??0,n??0,i??e.length)},equals(e,t){return wt.toLocalBufferType(e).equals(t)},fromNumberArray(e){return Buffer.from(e)},fromBase64(e){return Buffer.from(e,"base64")},fromUTF8(e){return Buffer.from(e,"utf8")},toBase64(e){return wt.toLocalBufferType(e).toString("base64")},fromISO88591(e){return Buffer.from(e,"binary")},toISO88591(e){return wt.toLocalBufferType(e).toString("binary")},fromHex(e){return Buffer.from(e,"hex")},toHex(e){return wt.toLocalBufferType(e).toString("hex")},toUTF8(e,t,r,n){const i=r-t<=20?Qc(e,t,r):null;if(i!=null)return i;const o=wt.toLocalBufferType(e).toString("utf8",t,r);if(n){for(let u=0;u<o.length;u++)if(o.charCodeAt(u)===65533){Jc(e,t,r,!0);break}}return o},utf8ByteLength(e){return Buffer.byteLength(e,"utf8")},encodeUTF8Into(e,t,r){const n=c2(e,t,r);return n??wt.toLocalBufferType(e).write(t,r,void 0,"utf8")},randomBytes:d2,swap32(e){return wt.toLocalBufferType(e).swap32()}};function f2(){const{navigator:e}=globalThis;return typeof e=="object"&&e.product==="ReactNative"}function m2(e){if(e<0)throw new RangeError(`The argument 'byteLength' is invalid. Received ${e}`);return br.fromNumberArray(Array.from({length:e},()=>Math.floor(Math.random()*256)))}const E2=(()=>{var t;const{crypto:e}=globalThis;if(e!=null&&typeof e.getRandomValues=="function")return r=>e.getRandomValues(br.allocate(r));if(f2()){const{console:r}=globalThis;(t=r==null?void 0:r.warn)==null||t.call(r,"BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.")}return m2})(),Nu=/(\d|[a-f])/i,br={isUint8Array:hr,toLocalBufferType(e){const t=(e==null?void 0:e[Symbol.toStringTag])??Object.prototype.toString.call(e);if(t==="Uint8Array")return e;if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength));if(t==="ArrayBuffer"||t==="SharedArrayBuffer"||t==="[object ArrayBuffer]"||t==="[object SharedArrayBuffer]")return new Uint8Array(e);throw new q("Cannot make a Uint8Array from passed potentialBuffer.")},allocate(e){if(typeof e!="number")throw new TypeError(`The "size" argument must be of type number. Received ${String(e)}`);return new Uint8Array(e)},allocateUnsafe(e){return br.allocate(e)},compare(e,t){if(e===t)return 0;const r=Math.min(e.length,t.length);for(let n=0;n<r;n++){if(e[n]<t[n])return-1;if(e[n]>t[n])return 1}return e.length<t.length?-1:e.length>t.length?1:0},concat(e){if(e.length===0)return br.allocate(0);let t=0;for(const i of e)t+=i.length;const r=br.allocate(t);let n=0;for(const i of e)r.set(i,n),n+=i.length;return r},copy(e,t,r,n,i){if(i!==void 0&&i<0)throw new RangeError(`The value of "sourceEnd" is out of range. It must be >= 0. Received ${i}`);if(i=i??e.length,n!==void 0&&(n<0||n>i))throw new RangeError(`The value of "sourceStart" is out of range. It must be >= 0 and <= ${i}. Received ${n}`);if(n=n??0,r!==void 0&&r<0)throw new RangeError(`The value of "targetStart" is out of range. It must be >= 0. Received ${r}`);r=r??0;const o=e.subarray(n,i),u=Math.min(o.length,t.length-r);return u<=0?0:(t.set(o.subarray(0,u),r),u)},equals(e,t){if(e.byteLength!==t.byteLength)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0},fromNumberArray(e){return Uint8Array.from(e)},fromBase64(e){return Uint8Array.from(atob(e),t=>t.charCodeAt(0))},fromUTF8(e){return new TextEncoder().encode(e)},toBase64(e){return btoa(br.toISO88591(e))},fromISO88591(e){return Uint8Array.from(e,t=>t.charCodeAt(0)&255)},toISO88591(e){return Array.from(Uint16Array.from(e),t=>String.fromCharCode(t)).join("")},fromHex(e){const t=e.length%2===0?e:e.slice(0,e.length-1),r=[];for(let n=0;n<t.length;n+=2){const i=t[n],o=t[n+1];if(!Nu.test(i)||!Nu.test(o))break;const u=Number.parseInt(`${i}${o}`,16);r.push(u)}return Uint8Array.from(r)},toHex(e){return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")},toUTF8(e,t,r,n){const i=r-t<=20?Qc(e,t,r):null;return i??Jc(e,t,r,n)},utf8ByteLength(e){return new TextEncoder().encode(e).byteLength},encodeUTF8Into(e,t,r){const n=new TextEncoder().encode(t);return e.set(n,r),n.byteLength},randomBytes:E2,swap32(e){if(e.length%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let t=0;t<e.length;t+=4){const r=e[t],n=e[t+1],i=e[t+2],o=e[t+3];e[t]=o,e[t+1]=i,e[t+2]=n,e[t+3]=r}return e}};var Bc;const g2=typeof Buffer=="function"&&((Bc=Buffer.prototype)==null?void 0:Bc._isBuffer)!==!0,W=g2?wt:br,ao=Symbol.for("@@mdb.bson.type");class ct{get[ao](){return this._bsontype}get[hn](){return Fr}[Symbol.for("nodejs.util.inspect.custom")](t,r,n){return this.inspect(t,r,n)}}const an=new Float64Array(1),we=new Uint8Array(an.buffer,0,8);an[0]=-1;const is=we[7]===0,ue={isBigEndian:is,getNonnegativeInt32LE(e,t){if(e[t+3]>127)throw new RangeError(`Size cannot be negative at offset: ${t}`);return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24},getInt32LE(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24},getUint32LE(e,t){return e[t]+e[t+1]*256+e[t+2]*65536+e[t+3]*16777216},getUint32BE(e,t){return e[t+3]+e[t+2]*256+e[t+1]*65536+e[t]*16777216},getBigInt64LE(e,t){const r=BigInt(e[t+4]+e[t+5]*256+e[t+6]*65536+(e[t+7]<<24)),n=BigInt(e[t]+e[t+1]*256+e[t+2]*65536+e[t+3]*16777216);return(r<<32n)+n},getFloat64LE:is?(e,t)=>(we[7]=e[t],we[6]=e[t+1],we[5]=e[t+2],we[4]=e[t+3],we[3]=e[t+4],we[2]=e[t+5],we[1]=e[t+6],we[0]=e[t+7],an[0]):(e,t)=>(we[0]=e[t],we[1]=e[t+1],we[2]=e[t+2],we[3]=e[t+3],we[4]=e[t+4],we[5]=e[t+5],we[6]=e[t+6],we[7]=e[t+7],an[0]),setInt32BE(e,t,r){return e[t+3]=r,r>>>=8,e[t+2]=r,r>>>=8,e[t+1]=r,r>>>=8,e[t]=r,4},setInt32LE(e,t,r){return e[t]=r,r>>>=8,e[t+1]=r,r>>>=8,e[t+2]=r,r>>>=8,e[t+3]=r,4},setBigInt64LE(e,t,r){const n=0xffffffffn;let i=Number(r&n);e[t]=i,i>>=8,e[t+1]=i,i>>=8,e[t+2]=i,i>>=8,e[t+3]=i;let o=Number(r>>32n&n);return e[t+4]=o,o>>=8,e[t+5]=o,o>>=8,e[t+6]=o,o>>=8,e[t+7]=o,8},setFloat64LE:is?(e,t,r)=>(an[0]=r,e[t]=we[7],e[t+1]=we[6],e[t+2]=we[5],e[t+3]=we[4],e[t+4]=we[3],e[t+5]=we[2],e[t+6]=we[1],e[t+7]=we[0],8):(e,t,r)=>(an[0]=r,e[t]=we[0],e[t+1]=we[1],e[t+2]=we[2],e[t+3]=we[3],e[t+4]=we[4],e[t+5]=we[5],e[t+6]=we[6],e[t+7]=we[7],8)},ge=class ge extends ct{constructor(r,n){super();se(this,"buffer");se(this,"sub_type");se(this,"position");if(r!=null&&typeof r=="string"&&!ArrayBuffer.isView(r)&&!B1(r)&&!Array.isArray(r))throw new q("Binary can only be constructed from Uint8Array or number[]");this.sub_type=n??ge.BSON_BINARY_SUBTYPE_DEFAULT,r==null?(this.buffer=W.allocate(ge.BUFFER_SIZE),this.position=0):(this.buffer=Array.isArray(r)?W.fromNumberArray(r):W.toLocalBufferType(r),this.position=this.buffer.byteLength)}get _bsontype(){return"Binary"}put(r){if(typeof r=="string"&&r.length!==1)throw new q("only accepts single character String");if(typeof r!="number"&&r.length!==1)throw new q("only accepts single character Uint8Array or Array");let n;if(typeof r=="string"?n=r.charCodeAt(0):typeof r=="number"?n=r:n=r[0],n<0||n>255)throw new q("only accepts number in a valid unsigned byte range 0-255");if(this.buffer.byteLength>this.position)this.buffer[this.position++]=n;else{const i=W.allocate(ge.BUFFER_SIZE+this.buffer.length);i.set(this.buffer,0),this.buffer=i,this.buffer[this.position++]=n}}write(r,n){if(n=typeof n=="number"?n:this.position,this.buffer.byteLength<n+r.length){const i=W.allocate(this.buffer.byteLength+r.length);i.set(this.buffer,0),this.buffer=i}if(ArrayBuffer.isView(r))this.buffer.set(W.toLocalBufferType(r),n),this.position=n+r.byteLength>this.position?n+r.length:this.position;else if(typeof r=="string")throw new q("input cannot be string")}read(r,n){n=n&&n>0?n:this.position;const i=r+n;return this.buffer.subarray(r,i>this.position?this.position:i)}value(){return this.buffer.length===this.position?this.buffer:this.buffer.subarray(0,this.position)}length(){return this.position}toJSON(){return W.toBase64(this.buffer.subarray(0,this.position))}toString(r){return r==="hex"?W.toHex(this.buffer.subarray(0,this.position)):r==="base64"?W.toBase64(this.buffer.subarray(0,this.position)):r==="utf8"||r==="utf-8"?W.toUTF8(this.buffer,0,this.position,!1):W.toUTF8(this.buffer,0,this.position,!1)}toExtendedJSON(r){r=r||{},this.sub_type===ge.SUBTYPE_VECTOR&&Yt(this);const n=W.toBase64(this.buffer),i=Number(this.sub_type).toString(16);return r.legacy?{$binary:n,$type:i.length===1?"0"+i:i}:{$binary:{base64:n,subType:i.length===1?"0"+i:i}}}toUUID(){if(this.sub_type===ge.SUBTYPE_UUID)return new Je(this.buffer.subarray(0,this.position));throw new q(`Binary sub_type "${this.sub_type}" is not supported for converting to UUID. Only "${ge.SUBTYPE_UUID}" is currently supported.`)}static createFromHexString(r,n){return new ge(W.fromHex(r),n)}static createFromBase64(r,n){return new ge(W.fromBase64(r),n)}static fromExtendedJSON(r,n){n=n||{};let i,o;if("$binary"in r?n.legacy&&typeof r.$binary=="string"&&"$type"in r?(o=r.$type?parseInt(r.$type,16):0,i=W.fromBase64(r.$binary)):typeof r.$binary!="string"&&(o=r.$binary.subType?parseInt(r.$binary.subType,16):0,i=W.fromBase64(r.$binary.base64)):"$uuid"in r&&(o=4,i=Je.bytesFromString(r.$uuid)),!i)throw new q(`Unexpected Binary Extended JSON format ${JSON.stringify(r)}`);return o===P1?new Je(i):new ge(i,o)}inspect(r,n,i){i??(i=gt);const o=W.toBase64(this.buffer.subarray(0,this.position)),u=i(o,n),c=i(this.sub_type,n);return`Binary.createFromBase64(${u}, ${c})`}toInt8Array(){if(this.sub_type!==ge.SUBTYPE_VECTOR)throw new q("Binary sub_type is not Vector");if(this.buffer[0]!==ge.VECTOR_TYPE.Int8)throw new q("Binary datatype field is not Int8");return Yt(this),new Int8Array(this.buffer.buffer.slice(this.buffer.byteOffset+2,this.buffer.byteOffset+this.position))}toFloat32Array(){if(this.sub_type!==ge.SUBTYPE_VECTOR)throw new q("Binary sub_type is not Vector");if(this.buffer[0]!==ge.VECTOR_TYPE.Float32)throw new q("Binary datatype field is not Float32");Yt(this);const r=new Uint8Array(this.buffer.buffer.slice(this.buffer.byteOffset+2,this.buffer.byteOffset+this.position));return ue.isBigEndian&&W.swap32(r),new Float32Array(r.buffer)}toPackedBits(){if(this.sub_type!==ge.SUBTYPE_VECTOR)throw new q("Binary sub_type is not Vector");if(this.buffer[0]!==ge.VECTOR_TYPE.PackedBit)throw new q("Binary datatype field is not packed bit");return Yt(this),new Uint8Array(this.buffer.buffer.slice(this.buffer.byteOffset+2,this.buffer.byteOffset+this.position))}toBits(){if(this.sub_type!==ge.SUBTYPE_VECTOR)throw new q("Binary sub_type is not Vector");if(this.buffer[0]!==ge.VECTOR_TYPE.PackedBit)throw new q("Binary datatype field is not packed bit");Yt(this);const n=(this.length()-2)*8-this.buffer[1],i=new Int8Array(n);for(let o=0;o<i.length;o++){const u=o/8|0,c=this.buffer[u+2],s=7-o%8,a=c>>s&1;i[o]=a}return i}static fromInt8Array(r){const n=W.allocate(r.byteLength+2);n[0]=ge.VECTOR_TYPE.Int8,n[1]=0;const i=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);n.set(i,2);const o=new this(n,this.SUBTYPE_VECTOR);return Yt(o),o}static fromFloat32Array(r){const n=W.allocate(r.byteLength+2);n[0]=ge.VECTOR_TYPE.Float32,n[1]=0;const i=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);n.set(i,2),ue.isBigEndian&&W.swap32(new Uint8Array(n.buffer,2));const o=new this(n,this.SUBTYPE_VECTOR);return Yt(o),o}static fromPackedBits(r,n=0){const i=W.allocate(r.byteLength+2);i[0]=ge.VECTOR_TYPE.PackedBit,i[1]=n,i.set(r,2);const o=new this(i,this.SUBTYPE_VECTOR);return Yt(o),o}static fromBits(r){const n=r.length+7>>>3,i=new Uint8Array(n+2);i[0]=ge.VECTOR_TYPE.PackedBit;const o=r.length%8;i[1]=o===0?0:8-o;for(let u=0;u<r.length;u++){const c=u>>>3,s=r[u];if(s!==0&&s!==1)throw new q(`Invalid bit value at ${u}: must be 0 or 1, found ${r[u]}`);if(s===0)continue;const a=7-u%8;i[c+2]|=s<<a}return new this(i,ge.SUBTYPE_VECTOR)}};se(ge,"BSON_BINARY_SUBTYPE_DEFAULT",0),se(ge,"BUFFER_SIZE",256),se(ge,"SUBTYPE_DEFAULT",0),se(ge,"SUBTYPE_FUNCTION",1),se(ge,"SUBTYPE_BYTE_ARRAY",2),se(ge,"SUBTYPE_UUID_OLD",3),se(ge,"SUBTYPE_UUID",4),se(ge,"SUBTYPE_MD5",5),se(ge,"SUBTYPE_ENCRYPTED",6),se(ge,"SUBTYPE_COLUMN",7),se(ge,"SUBTYPE_SENSITIVE",8),se(ge,"SUBTYPE_VECTOR",9),se(ge,"SUBTYPE_USER_DEFINED",128),se(ge,"VECTOR_TYPE",Object.freeze({Int8:3,Float32:39,PackedBit:16}));let je=ge;function Yt(e){if(e.sub_type!==je.SUBTYPE_VECTOR)return;const t=e.position,r=e.buffer[0],n=e.buffer[1];if((r===je.VECTOR_TYPE.Float32||r===je.VECTOR_TYPE.Int8)&&n!==0)throw new q("Invalid Vector: padding must be zero for int8 and float32 vectors");if(r===je.VECTOR_TYPE.Float32&&t!==0&&t-2!==0&&(t-2)%4!==0)throw new q("Invalid Vector: Float32 vector must contain a multiple of 4 bytes");if(r===je.VECTOR_TYPE.PackedBit&&n!==0&&t===2)throw new q("Invalid Vector: padding must be zero for packed bit vectors that are empty");if(r===je.VECTOR_TYPE.PackedBit&&n>7)throw new q(`Invalid Vector: padding must be a value between 0 and 7. found: ${n}`)}const os=16,A2=/^[0-9A-F]{32}$/i,p2=/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i;class Je extends je{constructor(t){let r;if(t==null)r=Je.generate();else if(t instanceof Je)r=W.toLocalBufferType(new Uint8Array(t.buffer));else if(ArrayBuffer.isView(t)&&t.byteLength===os)r=W.toLocalBufferType(t);else if(typeof t=="string")r=Je.bytesFromString(t);else throw new q("Argument passed in UUID constructor must be a UUID, a 16 byte Buffer or a 32/36 character hex string (dashes excluded/included, format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).");super(r,P1)}get id(){return this.buffer}set id(t){this.buffer=t}toHexString(t=!0){return t?[W.toHex(this.buffer.subarray(0,4)),W.toHex(this.buffer.subarray(4,6)),W.toHex(this.buffer.subarray(6,8)),W.toHex(this.buffer.subarray(8,10)),W.toHex(this.buffer.subarray(10,16))].join("-"):W.toHex(this.buffer)}toString(t){return t==="hex"?W.toHex(this.id):t==="base64"?W.toBase64(this.id):this.toHexString()}toJSON(){return this.toHexString()}equals(t){if(!t)return!1;if(t instanceof Je)return W.equals(t.id,this.id);try{return W.equals(new Je(t).id,this.id)}catch{return!1}}toBinary(){return new je(this.id,je.SUBTYPE_UUID)}static generate(){const t=W.randomBytes(os);return t[6]=t[6]&15|64,t[8]=t[8]&63|128,t}static isValid(t){return t?typeof t=="string"?Je.isValidUUIDString(t):hr(t)?t.byteLength===os:t._bsontype==="Binary"&&t.sub_type===this.SUBTYPE_UUID&&t.buffer.byteLength===16:!1}static createFromHexString(t){const r=Je.bytesFromString(t);return new Je(r)}static createFromBase64(t){return new Je(W.fromBase64(t))}static bytesFromString(t){if(!Je.isValidUUIDString(t))throw new q("UUID string representation must be 32 hex digits or canonical hyphenated representation");return W.fromHex(t.replace(/-/g,""))}static isValidUUIDString(t){return A2.test(t)||p2.test(t)}inspect(t,r,n){return n??(n=gt),`new UUID(${n(this.toHexString(),r)})`}}class $t extends ct{constructor(r,n){super();se(this,"code");se(this,"scope");this.code=r.toString(),this.scope=n??null}get _bsontype(){return"Code"}toJSON(){return this.scope!=null?{code:this.code,scope:this.scope}:{code:this.code}}toExtendedJSON(){return this.scope?{$code:this.code,$scope:this.scope}:{$code:this.code}}static fromExtendedJSON(r){return new $t(r.$code,r.$scope)}inspect(r,n,i){i??(i=gt);let o=i(this.code,n);const u=o.includes(`
|
|
2
2
|
`);this.scope!=null&&(o+=`,${u?`
|
|
3
3
|
`:" "}${i(this.scope,n)}`);const c=u&&this.scope===null;return`new Code(${u?`
|
|
4
4
|
`:""}${o}${c?`
|
|
@@ -9,4 +9,4 @@
|
|
|
9
9
|
`),h=Array.from(s.keys()).map(w=>w.toLowerCase()).sort().join(";"),g=await Za(e.body),m=[o,u,c,a+`
|
|
10
10
|
`,h,g].join(`
|
|
11
11
|
`),C=await Za(m),S="AWS4-HMAC-SHA256",D=`${i}/${e.region}/${e.service}/aws4_request`,O=[S,n,D,C].join(`
|
|
12
|
-
`),M=await Ln("AWS4"+t.secretAccessKey,i),p=await Ln(M,e.region),B=await Ln(p,e.service),d=await Ln(B,"aws4_request"),b=await Ln(d,O),f=to.BSON.onDemand.ByteUtils.toHex(b);return{Authorization:["AWS4-HMAC-SHA256 Credential="+t.accessKeyId+"/"+D,"SignedHeaders="+h,"Signature="+f].join(", "),"X-Amz-Date":n}}Object.defineProperty(xo,"__esModule",{value:!0});xo.MongoDBAWS=void 0;const $s=pe,on=Q,nn=ne(),wm=Bt,_m=gi,Dm=Ou,Tm=Mo,Bm=Ht,bm=110,e1={useBigInt64:!1,promoteLongs:!0,promoteValues:!0,promoteBuffers:!1,bsonRegExp:!1};class Mm extends wm.AuthProvider{constructor(t){super(),this.credentialFetcher=new _m.AWSSDKCredentialProvider(t)}async auth(t){const{connection:r}=t;if(!t.credentials)throw new on.MongoMissingCredentialsError("AuthContext must provide credentials.");if((0,nn.maxWireVersion)(r)<9)throw new on.MongoCompatibilityError("MONGODB-AWS authentication requires MongoDB version 4.4 or later");t.credentials=await Fm(t.credentials,this.credentialFetcher);const{credentials:n}=t,i=n.username,o=n.password,u=n.mechanismProperties.AWS_SESSION_TOKEN,c=u?{accessKeyId:i,secretAccessKey:o,sessionToken:u}:{accessKeyId:i,secretAccessKey:o},s=n.source,a=await(0,nn.randomBytes)(32),E={saslStart:1,mechanism:"MONGODB-AWS",payload:$s.serialize({r:a,p:bm},e1)},h=await r.command((0,nn.ns)(`${s}.$cmd`),E,void 0),g=$s.deserialize(h.payload.buffer,e1),m=g.h,C=g.s.buffer;if(C.length!==64)throw new on.MongoRuntimeError(`Invalid server nonce length ${C.length}, expected 64`);if(!nn.ByteUtils.equals(C.subarray(0,a.byteLength),a))throw new on.MongoRuntimeError("Server nonce does not begin with client nonce");if(m.length<1||m.length>255||m.indexOf("..")!==-1)throw new on.MongoRuntimeError(`Server returned an invalid host: "${m}"`);const S="Action=GetCallerIdentity&Version=2011-06-15",D=await(0,Dm.aws4Sign)({method:"POST",host:m,region:Rm(g.h),service:"sts",headers:{"Content-Type":"application/x-www-form-urlencoded","Content-Length":S.length,"X-MongoDB-Server-Nonce":nn.ByteUtils.toBase64(C),"X-MongoDB-GS2-CB-Flag":"n"},path:"/",body:S,date:new Date},c),O={a:D.Authorization,d:D["X-Amz-Date"]};u&&(O.t=u);const M={saslContinue:1,conversationId:h.conversationId,payload:$s.serialize(O,e1)};await r.command((0,nn.ns)(`${s}.$cmd`),M,void 0)}}xo.MongoDBAWS=Mm;async function Fm(e,t){function r(i){if(!i.AccessKeyId||!i.SecretAccessKey)throw new on.MongoMissingCredentialsError("Could not obtain temporary MONGODB-AWS credentials");return new Tm.MongoCredentials({username:i.AccessKeyId,password:i.SecretAccessKey,source:e.source,mechanism:Bm.AuthMechanism.MONGODB_AWS,mechanismProperties:{AWS_SESSION_TOKEN:i.Token}})}const n=await t.getCredentials();return r(n)}function Rm(e){const t=e.split(".");return t.length===1||t[1]==="amazonaws"?"us-east-1":t[1]}var t1={},kn={},Zt={},zo={};Object.defineProperty(zo,"__esModule",{value:!0});zo.finishCommandDocument=Nm;zo.startCommandDocument=Im;const ln=pe,Dl=Ht;function Nm(e,t){return t!=null?{saslContinue:1,conversationId:t,payload:new ln.Binary(ln.BSON.serialize({jwt:e}))}:{saslStart:1,mechanism:Dl.AuthMechanism.MONGODB_OIDC,payload:new ln.Binary(ln.BSON.serialize({jwt:e}))}}function Im(e){const t={};return e.username&&(t.n=e.username),{saslStart:1,autoAuthorize:1,mechanism:Dl.AuthMechanism.MONGODB_OIDC,payload:new ln.Binary(ln.BSON.serialize(t))}}Object.defineProperty(Zt,"__esModule",{value:!0});Zt.CallbackWorkflow=Zt.AUTOMATED_TIMEOUT_MS=Zt.HUMAN_TIMEOUT_MS=void 0;const vm=Mc,Pm=Q,$a=ne(),r1=zo;Zt.HUMAN_TIMEOUT_MS=3e5;Zt.AUTOMATED_TIMEOUT_MS=6e4;const Lm=["accessToken","expiresInSeconds","refreshToken"],km="User provided OIDC callbacks must return a valid object with an accessToken.",n1=100;class Um{constructor(t,r){this.cache=t,this.callback=this.withLock(r),this.lastExecutionTime=Date.now()-n1}async speculativeAuth(t,r){if(this.cache.hasAccessToken){const n=this.cache.getAccessToken();t.accessToken=n;const i=(0,r1.finishCommandDocument)(n);return i.db=r.source,{speculativeAuthenticate:i}}return{}}async reauthenticate(t,r){this.cache.hasAccessToken&&(t.accessToken===this.cache.getAccessToken()?(this.cache.removeAccessToken(),delete t.accessToken):t.accessToken=this.cache.getAccessToken()),await this.execute(t,r)}async startAuthentication(t,r,n){let i;return n!=null&&n.speculativeAuthenticate?i=n.speculativeAuthenticate:i=await t.command((0,$a.ns)(r.source),(0,r1.startCommandDocument)(r),void 0),i}async finishAuthentication(t,r,n,i){await t.command((0,$a.ns)(r.source),(0,r1.finishCommandDocument)(n,i),void 0)}async executeAndValidateCallback(t){const r=await this.callback(t);if(jm(r))throw new Pm.MongoMissingCredentialsError(km);return r}withLock(t){let r=Promise.resolve();return async n=>(await r,r=r.catch(()=>null).then(async()=>{const i=Date.now()-this.lastExecutionTime;return i<=n1&&await(0,vm.setTimeout)(n1-i,{signal:n.timeoutContext}),this.lastExecutionTime=Date.now(),await t(n)}),await r)}}Zt.CallbackWorkflow=Um;function jm(e){return e==null||typeof e!="object"||!("accessToken"in e)?!0:!Object.getOwnPropertyNames(e).every(t=>Lm.includes(t))}var ec;function Tl(){if(ec)return kn;ec=1,Object.defineProperty(kn,"__esModule",{value:!0}),kn.AutomatedCallbackWorkflow=void 0;const e=Q,t=Te,r=wu(),n=Zt;class i extends n.CallbackWorkflow{constructor(u,c){super(u,c)}async execute(u,c){if(this.cache.hasAccessToken){const a=this.cache.getAccessToken();u.accessToken||(u.accessToken=a);try{return await this.finishAuthentication(u,c,a)}catch(E){if(E instanceof e.MongoError&&E.code===e.MONGODB_ERROR_CODES.AuthenticationFailed)return this.cache.removeAccessToken(),await this.execute(u,c);throw E}}const s=await this.fetchAccessToken(c);this.cache.put(s),u.accessToken=s.accessToken,await this.finishAuthentication(u,c,s.accessToken)}async fetchAccessToken(u){const c=new AbortController,s={timeoutContext:c.signal,version:r.OIDC_VERSION};u.username&&(s.username=u.username),u.mechanismProperties.TOKEN_RESOURCE&&(s.tokenAudience=u.mechanismProperties.TOKEN_RESOURCE);const a=t.Timeout.expires(n.AUTOMATED_TIMEOUT_MS);try{return await Promise.race([this.executeAndValidateCallback(s),a])}catch(E){throw t.TimeoutError.is(E)?(c.abort(),new e.MongoOIDCError(`OIDC callback timed out after ${n.AUTOMATED_TIMEOUT_MS}ms.`)):E}finally{a.clear()}}}return kn.AutomatedCallbackWorkflow=i,kn}var Vo={};Object.defineProperty(Vo,"__esModule",{value:!0});Vo.callback=void 0;const tc=Eu,p1=Q,xm=ne(),zm=Object.freeze({Metadata:"true",Accept:"application/json"}),Vm="Azure endpoint did not return a value with only access_token and expires_in properties",Wm="TOKEN_RESOURCE must be set in the auth mechanism properties when ENVIRONMENT is azure.",Gm=async e=>{const t=e.tokenAudience,r=e.username;if(!t)throw new p1.MongoAzureError(Wm);const n=await qm(t,r);if(!Hm(n))throw new p1.MongoAzureError(Vm);return n};Vo.callback=Gm;async function qm(e,t){const r=new URL(tc.AZURE_BASE_URL);(0,tc.addAzureParams)(r,e,t);const n=await(0,xm.get)(r,{headers:zm});if(n.status!==200)throw new p1.MongoAzureError(`Status code ${n.status} returned from the Azure endpoint. Response body: ${n.body}`);const i=JSON.parse(n.body);return{accessToken:i.access_token,expiresInSeconds:Number(i.expires_in)}}function Hm(e){return e==null||typeof e!="object"?!1:"accessToken"in e&&typeof e.accessToken=="string"&&"expiresInSeconds"in e&&typeof e.expiresInSeconds=="number"}var Wo={};Object.defineProperty(Wo,"__esModule",{value:!0});Wo.callback=void 0;const Bl=Q,Km=ne(),Ym="http://metadata/computeMetadata/v1/instance/service-accounts/default/identity",Xm=Object.freeze({"Metadata-Flavor":"Google"}),Jm="TOKEN_RESOURCE must be set in the auth mechanism properties when ENVIRONMENT is gcp.",Qm=async e=>{const t=e.tokenAudience;if(!t)throw new Bl.MongoGCPError(Jm);return await Zm(t)};Wo.callback=Qm;async function Zm(e){const t=new URL(Ym);t.searchParams.append("audience",e);const r=await(0,Km.get)(t,{headers:Xm});if(r.status!==200)throw new Bl.MongoGCPError(`Status code ${r.status} returned from the GCP endpoint. Response body: ${r.body}`);return{accessToken:r.body}}var Go={};Object.defineProperty(Go,"__esModule",{value:!0});Go.callback=void 0;const $m=Nc,Li=Ar,eE="/var/run/secrets/kubernetes.io/serviceaccount/token",rc="AZURE_FEDERATED_TOKEN_FILE",nc="AWS_WEB_IDENTITY_TOKEN_FILE",tE=async()=>{let e;return Li.env[rc]?e=Li.env[rc]:Li.env[nc]?e=Li.env[nc]:e=eE,{accessToken:await(0,$m.readFile)(e,"utf8")}};Go.callback=tE;var Ci={};Object.defineProperty(Ci,"__esModule",{value:!0});Ci.TokenCache=void 0;const rE=Q;class i1 extends rE.MongoDriverError{}class nE{get hasAccessToken(){return!!this.accessToken}get hasRefreshToken(){return!!this.refreshToken}get hasIdpInfo(){return!!this.idpInfo}getAccessToken(){if(!this.accessToken)throw new i1("Attempted to get an access token when none exists.");return this.accessToken}getRefreshToken(){if(!this.refreshToken)throw new i1("Attempted to get a refresh token when none exists.");return this.refreshToken}getIdpInfo(){if(!this.idpInfo)throw new i1("Attempted to get IDP information when none exists.");return this.idpInfo}put(t,r){this.accessToken=t.accessToken,this.refreshToken=t.refreshToken,this.expiresInSeconds=t.expiresInSeconds,r&&(this.idpInfo=r)}removeAccessToken(){this.accessToken=void 0}removeRefreshToken(){this.refreshToken=void 0}}Ci.TokenCache=nE;var qo={};Object.defineProperty(qo,"__esModule",{value:!0});qo.callback=void 0;const iE=_1,oE=Ar,sE=Q,uE="OIDC_TOKEN_FILE must be set in the environment.",aE=async()=>{const e=oE.env.OIDC_TOKEN_FILE;if(!e)throw new sE.MongoAWSError(uE);return{accessToken:await iE.promises.readFile(e,"utf8")}};qo.callback=aE;var ic;function wu(){return ic||(ic=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.MongoDBOIDC=e.OIDC_WORKFLOWS=e.OIDC_VERSION=void 0;const t=Q,r=Bt,n=Tl(),i=Vo,o=Wo,u=Go,c=Ci,s=qo,a="AuthContext must provide credentials.";e.OIDC_VERSION=1,e.OIDC_WORKFLOWS=new Map,e.OIDC_WORKFLOWS.set("test",()=>new n.AutomatedCallbackWorkflow(new c.TokenCache,s.callback)),e.OIDC_WORKFLOWS.set("azure",()=>new n.AutomatedCallbackWorkflow(new c.TokenCache,i.callback)),e.OIDC_WORKFLOWS.set("gcp",()=>new n.AutomatedCallbackWorkflow(new c.TokenCache,o.callback)),e.OIDC_WORKFLOWS.set("k8s",()=>new n.AutomatedCallbackWorkflow(new c.TokenCache,u.callback));class E extends r.AuthProvider{constructor(m){if(super(),!m)throw new t.MongoInvalidArgumentError("No workflow provided to the OIDC auth provider.");this.workflow=m}async auth(m){var M;const{connection:C,reauthenticating:S,response:D}=m;if((M=D==null?void 0:D.speculativeAuthenticate)!=null&&M.done&&!S)return;const O=h(m);S?await this.workflow.reauthenticate(C,O):await this.workflow.execute(C,O,D)}async prepare(m,C){const{connection:S}=C,D=h(C),O=await this.workflow.speculativeAuth(S,D);return{...m,...O}}}e.MongoDBOIDC=E;function h(g){const{credentials:m}=g;if(!m)throw new t.MongoMissingCredentialsError(a);return m}}(t1)),t1}var Ho={};Object.defineProperty(Ho,"__esModule",{value:!0});Ho.HumanCallbackWorkflow=void 0;const cE=pe,Un=Q,oc=Te,lE=wu(),o1=Zt;class hE extends o1.CallbackWorkflow{constructor(t,r){super(t,r)}async execute(t,r){if(this.cache.hasAccessToken){const c=this.cache.getAccessToken();t.accessToken=c;try{return await this.finishAuthentication(t,r,c)}catch(s){if(s instanceof Un.MongoError&&s.code===Un.MONGODB_ERROR_CODES.AuthenticationFailed)return this.cache.removeAccessToken(),delete t.accessToken,await this.execute(t,r);throw s}}if(this.cache.hasRefreshToken){const c=this.cache.getRefreshToken(),s=await this.fetchAccessToken(this.cache.getIdpInfo(),r,c);this.cache.put(s),t.accessToken=s.accessToken;try{return await this.finishAuthentication(t,r,s.accessToken)}catch(a){if(a instanceof Un.MongoError&&a.code===Un.MONGODB_ERROR_CODES.AuthenticationFailed)return this.cache.removeRefreshToken(),delete t.accessToken,await this.execute(t,r);throw a}}const n=await this.startAuthentication(t,r),i=n.conversationId,o=cE.BSON.deserialize(n.payload.buffer),u=await this.fetchAccessToken(o,r);return this.cache.put(u,o),t.accessToken=u.accessToken,await this.finishAuthentication(t,r,u.accessToken,i)}async fetchAccessToken(t,r,n){const i=new AbortController,o={timeoutContext:i.signal,version:lE.OIDC_VERSION,idpInfo:t};r.username&&(o.username=r.username),n&&(o.refreshToken=n);const u=oc.Timeout.expires(o1.HUMAN_TIMEOUT_MS);try{return await Promise.race([this.executeAndValidateCallback(o),u])}catch(c){throw oc.TimeoutError.is(c)?(i.abort(),new Un.MongoOIDCError(`OIDC callback timed out after ${o1.HUMAN_TIMEOUT_MS}ms.`)):c}finally{u.clear()}}}Ho.HumanCallbackWorkflow=hE;var Ko={};Object.defineProperty(Ko,"__esModule",{value:!0});Ko.Plain=void 0;const dE=pe,fE=Q,mE=ne(),EE=Bt;class gE extends EE.AuthProvider{async auth(t){const{connection:r,credentials:n}=t;if(!n)throw new fE.MongoMissingCredentialsError("AuthContext must provide credentials.");const{username:i,password:o}=n,c={saslStart:1,mechanism:"PLAIN",payload:new dE.Binary(Buffer.from(`\0${i}\0${o}`)),autoAuthorize:1};await r.command((0,mE.ns)("$external.$cmd"),c,void 0)}}Ko.Plain=gE;var fn={};const sc=e=>e.codePointAt(0),AE=e=>e[0],pE=e=>e[e.length-1];function uc(e){const t=[],r=e.length;for(let n=0;n<r;n+=1){const i=e.charCodeAt(n);if(i>=55296&&i<=56319&&r>n+1){const o=e.charCodeAt(n+1);if(o>=56320&&o<=57343){t.push((i-55296)*1024+o-56320+65536),n+=1;continue}}t.push(i)}return t}function Qn({unassigned_code_points:e,commonly_mapped_to_nothing:t,non_ASCII_space_characters:r,prohibited_characters:n,bidirectional_r_al:i,bidirectional_l:o},u,c={}){const s=r,a=t;if(typeof u!="string")throw new TypeError("Expected string.");if(u.length===0)return"";const E=uc(u).map(M=>s.get(M)?32:M).filter(M=>!a.get(M)),h=String.fromCodePoint.apply(null,E).normalize("NFKC"),g=uc(h);if(g.some(M=>n.get(M)))throw new Error("Prohibited character, see https://tools.ietf.org/html/rfc4013#section-2.3");if(c.allowUnassigned!==!0&&g.some(p=>e.get(p)))throw new Error("Unassigned code point, see https://tools.ietf.org/html/rfc4013#section-2.5");const C=g.some(M=>i.get(M)),S=g.some(M=>o.get(M));if(C&&S)throw new Error("String must not contain RandALCat and LCat at the same time, see https://tools.ietf.org/html/rfc3454#section-6");const D=i.get(sc(AE(h))),O=i.get(sc(pE(h)));if(C&&!(D&&O))throw new Error("Bidirectional RandALCat character must be the first and the last character of the string, see https://tools.ietf.org/html/rfc3454#section-6");return h}Qn.saslprep=Qn;Qn.default=Qn;var CE=Qn,_u={},SE=rr;function rr(e,t){if(!(this instanceof rr))return new rr(e,t);this.length=0,this.updates=[],this.path=new Uint16Array(4),this.pages=new Array(32768),this.maxPages=this.pages.length,this.level=0,this.pageSize=e||1024,this.deduplicate=t?t.deduplicate:null,this.zeros=this.deduplicate?Yo(this.deduplicate.length):null}rr.prototype.updated=function(e){for(;this.deduplicate&&e.buffer[e.deduplicate]===this.deduplicate[e.deduplicate];)if(e.deduplicate++,e.deduplicate===this.deduplicate.length){e.deduplicate=0,e.buffer.equals&&e.buffer.equals(this.deduplicate)&&(e.buffer=this.deduplicate);break}e.updated||!this.updates||(e.updated=!0,this.updates.push(e))};rr.prototype.lastUpdate=function(){if(!this.updates||!this.updates.length)return null;var e=this.updates.pop();return e.updated=!1,e};rr.prototype._array=function(e,t){if(e>=this.maxPages){if(t)return;yE(this,e)}_E(e,this.path);for(var r=this.pages,n=this.level;n>0;n--){var i=this.path[n],o=r[i];if(!o){if(t)return;o=r[i]=new Array(32768)}r=o}return r};rr.prototype.get=function(e,t){var r=this._array(e,t),n=this.path[0],i=r&&r[n];return!i&&!t&&(i=r[n]=new bl(e,Yo(this.pageSize)),e>=this.length&&(this.length=e+1)),i&&i.buffer===this.deduplicate&&this.deduplicate&&!t&&(i.buffer=wE(i.buffer),i.deduplicate=0),i};rr.prototype.set=function(e,t){var r=this._array(e,!1),n=this.path[0];if(e>=this.length&&(this.length=e+1),!t||this.zeros&&t.equals&&t.equals(this.zeros)){r[n]=void 0;return}this.deduplicate&&t.equals&&t.equals(this.deduplicate)&&(t=this.deduplicate);var i=r[n],o=OE(t,this.pageSize);i?i.buffer=o:r[n]=new bl(e,o)};rr.prototype.toBuffer=function(){for(var e=new Array(this.length),t=Yo(this.pageSize),r=0;r<e.length;)for(var n=this._array(r,!0),i=0;i<32768&&r<e.length;i++)e[r++]=n&&n[i]?n[i].buffer:t;return Buffer.concat(e)};function yE(e,t){for(;e.maxPages<t;){var r=e.pages;e.pages=new Array(32768),e.pages[0]=r,e.level++,e.maxPages*=32768}}function OE(e,t){if(e.length===t)return e;if(e.length>t)return e.slice(0,t);var r=Yo(t);return e.copy(r),r}function Yo(e){if(Buffer.alloc)return Buffer.alloc(e);var t=new Buffer(e);return t.fill(0),t}function wE(e){var t=Buffer.allocUnsafe?Buffer.allocUnsafe(e.length):new Buffer(e.length);return e.copy(t),t}function bl(e,t){this.offset=e*t.length,this.buffer=t,this.updated=!1,this.deduplicate=0}function _E(e,t){e=(e-(t[0]=e&32767))/32768,e=(e-(t[1]=e&32767))/32768,t[3]=(e-(t[2]=e&32767))/32768&32767}var DE=SE,TE=gr;function gr(e){if(!(this instanceof gr))return new gr(e);if(e||(e={}),Buffer.isBuffer(e)&&(e={buffer:e}),this.pageOffset=e.pageOffset||0,this.pageSize=e.pageSize||1024,this.pages=e.pages||DE(this.pageSize),this.byteLength=this.pages.length*this.pageSize,this.length=8*this.byteLength,!bE(this.pageSize))throw new Error("The page size should be a power of two");if(this._trackUpdates=!!e.trackUpdates,this._pageMask=this.pageSize-1,e.buffer){for(var t=0;t<e.buffer.length;t+=this.pageSize)this.pages.set(t/this.pageSize,e.buffer.slice(t,t+this.pageSize));this.byteLength=e.buffer.length,this.length=8*this.byteLength}}gr.prototype.get=function(e){var t=e&7,r=(e-t)/8;return!!(this.getByte(r)&128>>t)};gr.prototype.getByte=function(e){var t=e&this._pageMask,r=(e-t)/this.pageSize,n=this.pages.get(r,!0);return n?n.buffer[t+this.pageOffset]:0};gr.prototype.set=function(e,t){var r=e&7,n=(e-r)/8,i=this.getByte(n);return this.setByte(n,t?i|128>>r:i&(255^128>>r))};gr.prototype.toBuffer=function(){for(var e=BE(this.pages.length*this.pageSize),t=0;t<this.pages.length;t++){var r=this.pages.get(t,!0),n=t*this.pageSize;r&&r.buffer.copy(e,n,this.pageOffset,this.pageOffset+this.pageSize)}return e};gr.prototype.setByte=function(e,t){var r=e&this._pageMask,n=(e-r)/this.pageSize,i=this.pages.get(n,!1);return r+=this.pageOffset,i.buffer[r]===t?!1:(i.buffer[r]=t,e>=this.byteLength&&(this.byteLength=e+1,this.length=this.byteLength*8),this._trackUpdates&&this.pages.updated(i),!0)};function BE(e){if(Buffer.alloc)return Buffer.alloc(e);var t=new Buffer(e);return t.fill(0),t}function bE(e){return!(e&e-1)}var ME=Ye.commonjsGlobal&&Ye.commonjsGlobal.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(_u,"__esModule",{value:!0});_u.createMemoryCodePoints=RE;const FE=ME(TE);function RE(e){let t=0;function r(){const a=e.readUInt32BE(t);t+=4;const E=e.slice(t,t+a);return t+=a,(0,FE.default)({buffer:E})}const n=r(),i=r(),o=r(),u=r(),c=r(),s=r();return{unassigned_code_points:n,commonly_mapped_to_nothing:i,non_ASCII_space_characters:o,prohibited_characters:u,bidirectional_r_al:c,bidirectional_l:s}}var Du={};Object.defineProperty(Du,"__esModule",{value:!0});const NE=Rc;Du.default=(0,NE.gunzipSync)(Buffer.from("H4sIAAAAAAACA+3dTYgcaRkA4LemO9Mhxm0FITnE9Cwr4jHgwgZ22B6YywqCJ0HQg5CL4sGTuOjCtGSF4CkHEW856MlTQHD3EJnWkU0Owh5VxE3LHlYQdNxd2U6mU59UV/d09fw4M2EySSXPAzNdP1/9fX/99bzVNZEN4jisRDulVFnQmLxm1aXF9Id/2/xMxNJ4XZlg576yuYlGt9gupV6xoFf8jhu9YvulVrFlp5XSx+lfvYhORGPXvqIRWSxERKtIm8bKFd10WNfKDS5Fo9jJWrq2+M2IlW+8uHgl/+BsROfPF4v5L7148Ur68Sha6dqZpYiVVy8tvLCWXo80Sf/lS89dGX2wHGvpzoXVn75/YWH5wmqe8uika82ViJXTy83Ve2k5Urozm38wm4/ls6t5uT6yfsTSJ7J3T0VKt8c5ExEXI8aFkH729c3eT+7EC6ca8cVULZUiYacX0R5PNWNxlh9L1y90q5kyzrpyy+9WcvOV6URntqw7La9sNVstXyczWVaWYbaaTYqzOHpr7pyiNT3/YzKuT63Z/FqKZlFTiuXtFM2vVOtIq7jiyKJbWZaOWD0euz0yoV2Z7kY0xq2x0YhfzVpmM5px9nTEH7JZ0ot5u39p0ma75Z472/s/H+2yr2inYyuq7fMvJivH2rM72N/Z3lyL31F2b1ya1P0zn816k2KP6JU9UzseucdQH5YqVeH/lFajSN2udg+TLJ9rksNxlvV2lki19rXKI43TPLejFu4ov7k3nMbhyhfY3Xb37f8BAGCf0eMTOH5szf154KmnNgKcnLb+Fzi2AfXktbN7fJelwTAiO/W5uQ2KINXRYu+znqo/WTAdLadURHmy3qciazd3bra4T3w16/f7t7Ms9U5gfJu10955sx1r3vmhBAAAAAAAgId20J1iZbDowNvIjuH427Gr5l/eiC+8OplZON8sVjx/qr9y+Pj+YRItT+NqAM+kkZs3AAAAAID6yfx1FwCAI97/dCh1/ub6SA0AAAAAAAAAgNoT/wcAAAAAAACA+hP/BwAAAAAAAID6E/8HAAAAAAAAgPoT/wcAAAAAAACA+hP/BwAAAAAAAID6E/8HAAAAAAAAgPoT/wcAAAAAAACA+hP/BwAAAAAAAID6E/8HAAAAAAAAgPoT/wcAAAAAAACA+hutp5SiQpYAAAAAAAAAQO2MIpZiT804flnAE2fhwjOeAZXr76kOAAAAAAAA8FjNf4N/l0NE3U/vuVQskLpSd4/Yh2xu9xTu0tFeeNYsLI2f/VMdNxTzj6Je9E/+6pp6Nn3awW3A54goe4Bss6v+PGsjQGMAAAAAAOBp5XEgwH6e7J7rwEQHRb/XvAMAAAAAAAA8yzoDeQDwVGjIAgAAAAAAAACoPfF/AAAAAAAAAKg/8X8AAAAAAAAAqD/xfwAAAAAAAACoP/F/AAAAAAAAAKg/8X8AAAAAAAAAqD/xfwAAAAAAAACoP/F/AAAAAAAAAKg/8X8AAAAAAAAAqD/xfwAAAAAAAACoP/F/AAAAAAAAAKg/8X8AAAAAAAAAqL/GSkSkClkCAAAAAAAAALXTSAAAAAAAAABA3Y1kAQAAAAAAAADUX8RSXZ9dsHC9+M8Fg2Ex/em1lAZpEBGttcrVjZqLEa+k0XpKw9mG4zWx4ukPUMhkAQAAAAAAABzBqbSe3//rXOS9HxGdo4TqR2XkutCdBu+LaPZw/lBbO7cbHnh2C7N7AIo4evEznllqLqWUp/LnYOtpM2bnOH66wI1+9GO4sOuISwv/TOlumu56FDv3NZhc4mR9v7zYIrafr40j/Cccvj9Xns3t3mu99E7qxUv3bqS0/ouNH/08++RGemfQ+nsx/5uNXsQPGulynPvv3ZTW37zd+1ovrqaYpP/122X6Xpx779Z3zr/3YOPKW1lkaRDf31pPaf3j/msRsVGkL+d/f+/m4sJsPm1cfSsr16e8m9Ldj/KsnyIuR3nXw83Is3EhxLd/2V773ks3m/cj/THKUummdP9qKhIOImuOU0Xjwb3y+oqt735rpTetVbF9n8R4x9crRfO77TKqVOZpDclv5bfK18lMnk+q0K18UpxF/RrGXE0Zxtqx3tWSj+vxbL4XaasfKb0dRbtLW73JsfPGg177H+OmGKlfvS1msllt7JEJm9XOJqXR+Fkfo1H66uy5H1v3Xx5+uJmGLw9jro2u7Loj4PnuR6+f+e3d261+eazNhzrL7X83MohoHpS4PddV8ki1it61//pw1g7z6p1U/26Nm2llST57B5rUvuG0XqSU/rPd7jYrqWcbd+beJQ77BgPMDwn37/8BAGCf0eMTOH4cPlufv9VGgJOzqf8Fjm1APXkd7B7f5dF57GPMaWy/MTvjvNvtXj6h8W2+GXvnzXaseeeHEgAAAAAAAB7aQXeKlcGiadBoEOeLb2dtpGOL2MyOtf391a3P/zD96c3JzIP3t4oV797vrh8+vn+YRL5bBuj/AQAAAABqJvfHXQAAHkX82zfXAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACeAgkAAAAAAAAAqLuRLAAAAAAAAACA2hv9D1iu/VAYaAYA","base64"));var Ml=Ye.commonjsGlobal&&Ye.commonjsGlobal.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};const IE=Ml(CE),vE=_u,PE=Ml(Du),LE=(0,vE.createMemoryCodePoints)(PE.default);function Zn(e,t){return(0,IE.default)(LE,e,t)}Zn.saslprep=Zn;Zn.default=Zn;var kE=Zn;Object.defineProperty(fn,"__esModule",{value:!0});fn.ScramSHA256=fn.ScramSHA1=void 0;const UE=kE,Lr=bc,C1=pe,Rt=Q,ro=ne(),jE=Bt,ac=Ht;class Fl extends jE.AuthProvider{constructor(t){super(),this.cryptoMethod=t||"sha1"}async prepare(t,r){const n=this.cryptoMethod,i=r.credentials;if(!i)throw new Rt.MongoMissingCredentialsError("AuthContext must provide credentials.");const o=await(0,ro.randomBytes)(24);return r.nonce=o,{...t,speculativeAuthenticate:{...Il(n,i,o),db:i.source}}}async auth(t){const{reauthenticating:r,response:n}=t;return n!=null&&n.speculativeAuthenticate&&!r?await vl(this.cryptoMethod,n.speculativeAuthenticate,t):await xE(this.cryptoMethod,t)}}function Rl(e){return e.replace("=","=3D").replace(",","=2C")}function Nl(e,t){return Buffer.concat([Buffer.from("n=","utf8"),Buffer.from(e,"utf8"),Buffer.from(",r=","utf8"),Buffer.from(t.toString("base64"),"utf8")])}function Il(e,t,r){const n=Rl(t.username);return{saslStart:1,mechanism:e==="sha1"?ac.AuthMechanism.MONGODB_SCRAM_SHA1:ac.AuthMechanism.MONGODB_SCRAM_SHA256,payload:new C1.Binary(Buffer.concat([Buffer.from("n,,","utf8"),Nl(n,r)])),autoAuthorize:1,options:{skipEmptyExchange:!0}}}async function xE(e,t){const{connection:r,credentials:n}=t;if(!n)throw new Rt.MongoMissingCredentialsError("AuthContext must provide credentials.");if(!t.nonce)throw new Rt.MongoInvalidArgumentError("AuthContext must contain a valid nonce property");const i=t.nonce,o=n.source,u=Il(e,n,i),c=await r.command((0,ro.ns)(`${o}.$cmd`),u,void 0);await vl(e,c,t)}async function vl(e,t,r){const n=r.connection,i=r.credentials;if(!i)throw new Rt.MongoMissingCredentialsError("AuthContext must provide credentials.");if(!r.nonce)throw new Rt.MongoInvalidArgumentError("Unable to continue SCRAM without valid nonce");const o=r.nonce,u=i.source,c=Rl(i.username),s=i.password,a=e==="sha256"?(0,UE.saslprep)(s):zE(c,s),E=Buffer.isBuffer(t.payload)?new C1.Binary(t.payload):t.payload,h=cc(E),g=parseInt(h.i,10);if(g&&g<4096)throw new Rt.MongoRuntimeError(`Server returned an invalid iteration count ${g}`);const m=h.s,C=h.r;if(C.startsWith("nonce"))throw new Rt.MongoRuntimeError(`Server returned an invalid nonce: ${C}`);const S=`c=biws,r=${C}`,D=HE(a,Buffer.from(m,"base64"),g,e),O=ki(e,D,"Client Key"),M=ki(e,D,"Server Key"),p=WE(e,O),B=[Nl(c,o),E.toString("utf8"),S].join(","),d=ki(e,p,B),b=`p=${VE(O,d)}`,f=[S,b].join(","),l=ki(e,M,B),w={saslContinue:1,conversationId:t.conversationId,payload:new C1.Binary(Buffer.from(f))},T=await n.command((0,ro.ns)(`${u}.$cmd`),w,void 0),_=cc(T.payload);if(!KE(Buffer.from(_.v,"base64"),l))throw new Rt.MongoRuntimeError("Server returned an invalid signature");if(T.done!==!1)return;const A={saslContinue:1,conversationId:T.conversationId,payload:Buffer.alloc(0)};await n.command((0,ro.ns)(`${u}.$cmd`),A,void 0)}function cc(e){const t=e.toString("utf8"),r={},n=t.split(",");for(let i=0;i<n.length;i++){const o=(n[i].match(/^([^=]*)=(.*)$/)??[]).slice(1);r[o[0]]=o[1]}return r}function zE(e,t){if(typeof e!="string")throw new Rt.MongoInvalidArgumentError("Username must be a string");if(typeof t!="string")throw new Rt.MongoInvalidArgumentError("Password must be a string");if(t.length===0)throw new Rt.MongoInvalidArgumentError("Password cannot be empty");let r;try{r=Lr.createHash("md5")}catch(n){throw Lr.getFips()?new Error("Auth mechanism SCRAM-SHA-1 is not supported in FIPS mode"):n}return r.update(`${e}:mongo:${t}`,"utf8"),r.digest("hex")}function VE(e,t){Buffer.isBuffer(e)||(e=Buffer.from(e)),Buffer.isBuffer(t)||(t=Buffer.from(t));const r=Math.max(e.length,t.length),n=[];for(let i=0;i<r;i+=1)n.push(e[i]^t[i]);return Buffer.from(n).toString("base64")}function WE(e,t){return Lr.createHash(e).update(t).digest()}function ki(e,t,r){return Lr.createHmac(e,t).update(r).digest()}let Hi={},S1=0;function GE(){Hi={},S1=0}const qE={sha256:32,sha1:20};function HE(e,t,r,n){const i=[e,t.toString("base64"),r].join("_");if(Hi[i]!=null)return Hi[i];const o=Lr.pbkdf2Sync(e,t,r,qE[n],n);return S1>=200&&GE(),Hi[i]=o,S1+=1,o}function KE(e,t){if(e.length!==t.length)return!1;if(typeof Lr.timingSafeEqual=="function")return Lr.timingSafeEqual(e,t);let r=0;for(let n=0;n<e.length;n++)r|=e[n]^t[n];return r===0}class YE extends Fl{constructor(){super("sha1")}}fn.ScramSHA1=YE;class XE extends Fl{constructor(){super("sha256")}}fn.ScramSHA256=XE;var Xo={};Object.defineProperty(Xo,"__esModule",{value:!0});Xo.X509=void 0;const lc=Q,JE=ne(),QE=Bt;class ZE extends QE.AuthProvider{async prepare(t,r){const{credentials:n}=r;if(!n)throw new lc.MongoMissingCredentialsError("AuthContext must provide credentials.");return{...t,speculativeAuthenticate:hc(n)}}async auth(t){const r=t.connection,n=t.credentials;if(!n)throw new lc.MongoMissingCredentialsError("AuthContext must provide credentials.");const i=t.response;i!=null&&i.speculativeAuthenticate||await r.command((0,JE.ns)("$external.$cmd"),hc(n),void 0)}}Xo.X509=ZE;function hc(e){const t={authenticate:1,mechanism:"MONGODB-X509"};return e.username&&(t.user=e.username),t}Object.defineProperty(pi,"__esModule",{value:!0});pi.MongoClientAuthProviders=void 0;const $E=Fo,e4=xo,Pl=wu(),t4=Tl(),r4=Ho,dc=Ci,n4=Ko,Dr=Ht,fc=fn,i4=Xo,Ll=Q,o4=new Map([[Dr.AuthMechanism.MONGODB_AWS,({AWS_CREDENTIAL_PROVIDER:e})=>new e4.MongoDBAWS(e)],[Dr.AuthMechanism.MONGODB_GSSAPI,()=>new $E.GSSAPI],[Dr.AuthMechanism.MONGODB_OIDC,e=>new Pl.MongoDBOIDC(u4(e))],[Dr.AuthMechanism.MONGODB_PLAIN,()=>new n4.Plain],[Dr.AuthMechanism.MONGODB_SCRAM_SHA1,()=>new fc.ScramSHA1],[Dr.AuthMechanism.MONGODB_SCRAM_SHA256,()=>new fc.ScramSHA256],[Dr.AuthMechanism.MONGODB_X509,()=>new i4.X509]]);class s4{constructor(){this.existingProviders=new Map}getOrCreateProvider(t,r){const n=this.existingProviders.get(t);if(n)return n;const i=o4.get(t);if(!i)throw new Ll.MongoInvalidArgumentError(`authMechanism ${t} not supported`);const o=i(r);return this.existingProviders.set(t,o),o}}pi.MongoClientAuthProviders=s4;function u4(e){var t;if(e.OIDC_HUMAN_CALLBACK)return new r4.HumanCallbackWorkflow(new dc.TokenCache,e.OIDC_HUMAN_CALLBACK);if(e.OIDC_CALLBACK)return new t4.AutomatedCallbackWorkflow(new dc.TokenCache,e.OIDC_CALLBACK);{const r=e.ENVIRONMENT,n=(t=Pl.OIDC_WORKFLOWS.get(r))==null?void 0:t();if(!n)throw new Ll.MongoInvalidArgumentError(`Could not load workflow for environment ${e.ENVIRONMENT}`);return n}}var jn={},Jo={},Si={};Object.defineProperty(Si,"__esModule",{value:!0});Si.ClientBulkWriteOperation=void 0;const a4=De(),c4=ne(),l4=Ie,Tr=Me;class kl extends l4.CommandOperation{get commandName(){return"bulkWrite"}constructor(t,r){super(void 0,r),this.SERVER_COMMAND_RESPONSE_TYPE=a4.ClientBulkWriteCursorResponse,this.commandBuilder=t,this.options=r,this.ns=new c4.MongoDBNamespace("admin","$cmd")}resetBatch(){return this.commandBuilder.resetBatch()}get canRetryWrite(){return this.commandBuilder.isBatchRetryable}handleOk(t){return t}buildCommandDocument(t,r){const n=this.commandBuilder.buildBatch(t.description.maxMessageSizeBytes,t.description.maxWriteBatchSize,t.description.maxBsonObjectSize);return this.canRetryWrite||(this.options.willRetryWrite=!1),n}}Si.ClientBulkWriteOperation=kl;(0,Tr.defineAspects)(kl,[Tr.Aspect.WRITE_OPERATION,Tr.Aspect.SKIP_COLLATION,Tr.Aspect.CURSOR_CREATING,Tr.Aspect.RETRYABLE,Tr.Aspect.COMMAND_BATCHING,Tr.Aspect.SUPPORTS_RAW_DATA]);Object.defineProperty(Jo,"__esModule",{value:!0});Jo.ClientBulkWriteCursor=void 0;const h4=Si,d4=qe,mc=ne(),f4=rt;class Tu extends f4.AbstractCursor{constructor(t,r,n={}){super(t,new mc.MongoDBNamespace("admin","$cmd"),n),this.commandBuilder=r,this.clientBulkWriteOptions=n}get response(){return this.cursorResponse?this.cursorResponse:null}get operations(){return this.commandBuilder.lastOperations}clone(){const t=(0,mc.mergeOptions)({},this.clientBulkWriteOptions);return delete t.session,new Tu(this.client,this.commandBuilder,{...t})}async _initialize(t){const r=new h4.ClientBulkWriteOperation(this.commandBuilder,{...this.clientBulkWriteOptions,...this.cursorOptions,session:t}),n=await(0,d4.executeOperation)(this.client,r,this.timeoutContext);return this.cursorResponse=n,{server:r.server,session:t,response:n}}}Jo.ClientBulkWriteCursor=Tu;var Ul={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.buildReplaceOneOperation=e.buildUpdateManyOperation=e.buildUpdateOneOperation=e.buildDeleteManyOperation=e.buildDeleteOneOperation=e.buildInsertOneOperation=e.ClientBulkWriteCommandBuilder=void 0,e.buildOperation=M;const t=pe,r=vo(),n=Q,i=Wr,o=ne(),u=1e3;class c{constructor(B,d,b){this.models=B,this.options=d,this.pkFactory=b??o.DEFAULT_PK_FACTORY,this.currentModelIndex=0,this.previousModelIndex=0,this.lastOperations=[],this.isBatchRetryable=!0}get errorsOnly(){return"verboseResults"in this.options?!this.options.verboseResults:!0}hasNextBatch(){return this.currentModelIndex<this.models.length}resetBatch(){return this.currentModelIndex=this.previousModelIndex,!0}buildBatch(B,d,b){this.isBatchRetryable=!0;let f=0,l=0;const w=this.baseCommand(),T=new Map;for(this.previousModelIndex=this.currentModelIndex;this.currentModelIndex<this.models.length;){const _=this.models[this.currentModelIndex],A=_.namespace,y=T.get(A);if((_.name==="deleteMany"||_.name==="updateMany")&&(this.isBatchRetryable=!1),y!=null){const F=M(_,y,this.pkFactory,this.options);let R;try{R=t.BSON.serialize(F)}catch(v){throw new n.MongoInvalidArgumentError("Could not serialize operation to BSON",{cause:v})}if(s("ops",R,b),f+R.length<B&&w.ops.documents.length<d)f=u+w.ops.push(F,R),this.currentModelIndex++;else break}else{T.set(A,l);const F={ns:A},R=M(_,l,this.pkFactory,this.options);let v,J;try{v=t.BSON.serialize(F),J=t.BSON.serialize(R)}catch(I){throw new n.MongoInvalidArgumentError("Could not serialize ns info to BSON",{cause:I})}if(s("nsInfo",v,b),s("ops",J,b),f+v.length+J.length<B&&w.ops.documents.length<d)f=u+w.nsInfo.push(F,v)+w.ops.push(R,J),l++,this.currentModelIndex++;else break}}return this.lastOperations=w.ops.documents,w}baseCommand(){const B={bulkWrite:1,errorsOnly:this.errorsOnly,ordered:this.options.ordered??!0,ops:new r.DocumentSequence("ops"),nsInfo:new r.DocumentSequence("nsInfo")};return this.options.bypassDocumentValidation!=null&&(B.bypassDocumentValidation=this.options.bypassDocumentValidation),this.options.let&&(B.let=this.options.let),this.options.comment!==void 0&&(B.comment=this.options.comment),B}}e.ClientBulkWriteCommandBuilder=c;function s(p,B,d){if(B.length>d)throw new n.MongoInvalidArgumentError(`Client bulk write operation ${p} of length ${B.length} exceeds the max bson object size of ${d}`)}const a=(p,B,d)=>{const b={insert:B,document:p.document};return b.document._id=p.document._id??d.createPk(),b};e.buildInsertOneOperation=a;const E=(p,B)=>g(p,B,!1);e.buildDeleteOneOperation=E;const h=(p,B)=>g(p,B,!0);e.buildDeleteManyOperation=h;function g(p,B,d){const b={delete:B,multi:d,filter:p.filter};return p.hint&&(b.hint=p.hint),p.collation&&(b.collation=p.collation),b}const m=(p,B,d)=>D(p,B,!1,d);e.buildUpdateOneOperation=m;const C=(p,B,d)=>D(p,B,!0,d);e.buildUpdateManyOperation=C;function S(p,B){if(!(0,o.hasAtomicOperators)(p,B))throw new n.MongoAPIError("Client bulk write update models must only contain atomic modifiers (start with $) and must not be empty.")}function D(p,B,d,b){S(p.update,b);const f={update:B,multi:d,filter:p.filter,updateMods:p.update};return p.hint&&(f.hint=p.hint),p.upsert&&(f.upsert=p.upsert),p.arrayFilters&&(f.arrayFilters=p.arrayFilters),p.collation&&(f.collation=p.collation),!d&&"sort"in p&&p.sort!=null&&(f.sort=(0,i.formatSort)(p.sort)),f}const O=(p,B)=>{if((0,o.hasAtomicOperators)(p.replacement))throw new n.MongoAPIError("Client bulk write replace models must not contain atomic modifiers (start with $) and must not be empty.");const d={update:B,multi:!1,filter:p.filter,updateMods:p.replacement};return p.hint&&(d.hint=p.hint),p.upsert&&(d.upsert=p.upsert),p.collation&&(d.collation=p.collation),p.sort!=null&&(d.sort=(0,i.formatSort)(p.sort)),d};e.buildReplaceOneOperation=O;function M(p,B,d,b){switch(p.name){case"insertOne":return(0,e.buildInsertOneOperation)(p,B,d);case"deleteOne":return(0,e.buildDeleteOneOperation)(p,B);case"deleteMany":return(0,e.buildDeleteManyOperation)(p,B);case"updateOne":return(0,e.buildUpdateOneOperation)(p,B,b);case"updateMany":return(0,e.buildUpdateManyOperation)(p,B,b);case"replaceOne":return(0,e.buildReplaceOneOperation)(p,B)}}})(Ul);var xn={},Ec;function m4(){if(Ec)return xn;Ec=1,Object.defineProperty(xn,"__esModule",{value:!0}),xn.ClientBulkWriteResultsMerger=void 0;const e=es(),t=Q,r={acknowledged:!1,insertedCount:0,upsertedCount:0,matchedCount:0,modifiedCount:0,deletedCount:0,insertResults:void 0,updateResults:void 0,deleteResults:void 0};class n{static unacknowledged(){return r}constructor(o){this.options=o,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},o.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(o){let u;try{for await(const c of o)if(c.ok===1)this.options.verboseResults&&this.processDocument(o,c);else if(this.options.ordered){const s=new t.MongoClientBulkWriteError({message:"Mongo client ordered bulk write encountered a write error."});throw s.writeErrors.set(c.idx+this.currentBatchOffset,{code:c.code,message:c.errmsg}),s.partialResult=this.result,s}else this.writeErrors.set(c.idx+this.currentBatchOffset,{code:c.code,message:c.errmsg})}catch(c){if(c instanceof e.MongoWriteConcernError){const s=c.result;if(u={insertedCount:s.nInserted,upsertedCount:s.nUpserted,matchedCount:s.nMatched,modifiedCount:s.nModified,deletedCount:s.nDeleted,writeConcernError:s.writeConcernError},this.options.verboseResults&&s.cursor.firstBatch)for(const a of s.cursor.firstBatch)a.ok===1&&this.processDocument(o,a)}else throw c}finally{if(o.response){const c=o.response;this.incrementCounts(c)}this.currentBatchOffset+=o.operations.length}if(u){const c=u.writeConcernError;this.incrementCounts(u),this.writeConcernErrors.push({code:c.code,message:c.errmsg})}return this.result}processDocument(o,u){var s,a,E;const c=o.operations[u.idx];if("insert"in c&&((s=this.result.insertResults)==null||s.set(u.idx+this.currentBatchOffset,{insertedId:c.document._id})),"update"in c){const h={matchedCount:u.n,modifiedCount:u.nModified??0,didUpsert:u.upserted!=null};u.upserted&&(h.upsertedId=u.upserted._id),(a=this.result.updateResults)==null||a.set(u.idx+this.currentBatchOffset,h)}"delete"in c&&((E=this.result.deleteResults)==null||E.set(u.idx+this.currentBatchOffset,{deletedCount:u.n}))}incrementCounts(o){this.result.insertedCount+=o.insertedCount,this.result.upsertedCount+=o.upsertedCount,this.result.matchedCount+=o.matchedCount,this.result.modifiedCount+=o.modifiedCount,this.result.deletedCount+=o.deletedCount}}return xn.ClientBulkWriteResultsMerger=n,xn}var gc;function E4(){if(gc)return jn;gc=1,Object.defineProperty(jn,"__esModule",{value:!0}),jn.ClientBulkWriteExecutor=void 0;const e=rt,t=Jo,r=Q,n=Te,i=ne(),o=lt(),u=qe,c=Si,s=Ul,a=m4();class E{constructor(g,m,C){var S;if(m.length===0)throw new r.MongoClientBulkWriteExecutionError("No client bulk write models were provided.");if(this.client=g,this.operations=m,this.options={ordered:!0,bypassDocumentValidation:!1,verboseResults:!1,...C},this.options.writeConcern||(this.options.writeConcern=o.WriteConcern.fromOptions(this.client.s.options)),((S=this.options.writeConcern)==null?void 0:S.w)===0){if(this.options.verboseResults)throw new r.MongoInvalidArgumentError("Cannot request unacknowledged write concern and verbose results");if(this.options.ordered)throw new r.MongoInvalidArgumentError("Cannot request unacknowledged write concern and ordered writes")}}async execute(){var D;const g=this.client.s.options.pkFactory,m=new s.ClientBulkWriteCommandBuilder(this.operations,this.options,g),C=(0,i.resolveTimeoutOptions)(this.client,this.options),S=n.TimeoutContext.create(C);if(((D=this.options.writeConcern)==null?void 0:D.w)===0){for(;m.hasNextBatch();){const O=new c.ClientBulkWriteOperation(m,this.options);await(0,u.executeOperation)(this.client,O,S)}return a.ClientBulkWriteResultsMerger.unacknowledged()}else{const O=new a.ClientBulkWriteResultsMerger(this.options);for(;m.hasNextBatch();){const M=new e.CursorTimeoutContext(S,Symbol()),p={...this.options,timeoutContext:M,...C.timeoutMS!=null&&{timeoutMode:e.CursorTimeoutMode.LIFETIME}},B=new t.ClientBulkWriteCursor(this.client,m,p);try{await O.merge(B)}catch(d){if(d instanceof r.MongoServerError&&!(d instanceof r.MongoClientBulkWriteError)){const b=new r.MongoClientBulkWriteError({message:"Mongo client bulk write encountered an error during execution"});throw b.cause=d,b.partialResult=O.bulkWriteResult,b}else throw d}}if(O.writeConcernErrors.length>0||O.writeErrors.size>0){const M=new r.MongoClientBulkWriteError({message:"Mongo client bulk write encountered errors during execution."});throw M.writeConcernErrors=O.writeConcernErrors,M.writeErrors=O.writeErrors,M.partialResult=O.bulkWriteResult,M}return O.bulkWriteResult}}}return jn.ClientBulkWriteExecutor=E,jn}var Qo={};Object.defineProperty(Qo,"__esModule",{value:!0});Qo.EndSessionsOperation=void 0;const g4=De(),A4=Ie,p4=Ke,C4=ne(),Ac=Me;class jl extends A4.CommandOperation{constructor(t){super(),this.writeConcern={w:0},this.ns=C4.MongoDBNamespace.fromString("admin.$cmd"),this.SERVER_COMMAND_RESPONSE_TYPE=g4.MongoDBResponse,this.sessions=t}buildCommandDocument(t,r){return{endSessions:this.sessions}}buildOptions(t){return{timeoutContext:t,readPreference:p4.ReadPreference.primaryPreferred}}get commandName(){return"endSessions"}}Qo.EndSessionsOperation=jl;(0,Ac.defineAspects)(jl,Ac.Aspect.WRITE_OPERATION);var zn={},mt={};Object.defineProperty(mt,"__esModule",{value:!0});mt.WaitingForSuitableServerEvent=mt.ServerSelectionSucceededEvent=mt.ServerSelectionFailedEvent=mt.ServerSelectionStartedEvent=mt.ServerSelectionEvent=void 0;const S4=ne(),Zo=Ve;class yi{constructor(t,r,n){this.selector=t,this.operation=n,this.topologyDescription=r}}mt.ServerSelectionEvent=yi;class y4 extends yi{constructor(t,r,n){super(t,r,n),this.name=Zo.SERVER_SELECTION_STARTED,this.message="Server selection started"}}mt.ServerSelectionStartedEvent=y4;class O4 extends yi{constructor(t,r,n,i){super(t,r,i),this.name=Zo.SERVER_SELECTION_FAILED,this.message="Server selection failed",this.failure=n}}mt.ServerSelectionFailedEvent=O4;class w4 extends yi{constructor(t,r,n,i){super(t,r,i),this.name=Zo.SERVER_SELECTION_SUCCEEDED,this.message="Server selection succeeded";const{host:o,port:u}=S4.HostAddress.fromString(n).toHostPort();this.serverHost=o,this.serverPort=u}}mt.ServerSelectionSucceededEvent=w4;class _4 extends yi{constructor(t,r,n,i){super(t,r,i),this.name=Zo.WAITING_FOR_SUITABLE_SERVER,this.message="Waiting for suitable server to become available",this.remainingTimeMS=n}}mt.WaitingForSuitableServerEvent=_4;var kr={};Object.defineProperty(kr,"__esModule",{value:!0});kr.SrvPoller=kr.SrvPollingEvent=void 0;const D4=D1,s1=En,T4=Q,B4=Qe,Vn=ne();class xl{constructor(t){this.srvRecords=t}hostnames(){return new Set(this.srvRecords.map(t=>Vn.HostAddress.fromSrvRecord(t).toString()))}}kr.SrvPollingEvent=xl;const so=class so extends B4.TypedEventEmitter{constructor(t){if(super(),this.on("error",Vn.noop),!t||!t.srvHost)throw new T4.MongoRuntimeError("Options for SrvPoller must exist and include srvHost");this.srvHost=t.srvHost,this.srvMaxHosts=t.srvMaxHosts??0,this.srvServiceName=t.srvServiceName??"mongodb",this.rescanSrvIntervalMS=6e4,this.heartbeatFrequencyMS=t.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,s1.clearTimeout)(this._timeout),this.generation+=1,this._timeout=void 0)}schedule(){this._timeout&&(0,s1.clearTimeout)(this._timeout),this._timeout=(0,s1.setTimeout)(()=>{this._poll().then(void 0,Vn.squashError)},this.intervalMS)}success(t){this.haMode=!1,this.schedule(),this.emit(so.SRV_RECORD_DISCOVERY,new xl(t))}failure(){this.haMode=!0,this.schedule()}async _poll(){const t=this.generation;let r;try{r=await D4.promises.resolveSrv(this.srvAddress)}catch{this.failure();return}if(t!==this.generation)return;const n=[];for(const i of r)try{(0,Vn.checkParentDomainMatch)(i.name,this.srvHost),n.push(i)}catch(o){(0,Vn.squashError)(o)}if(!n.length){this.failure();return}this.success(n)}};so.SRV_RECORD_DISCOVERY="srvRecordDiscovery";let y1=so;kr.SrvPoller=y1;var pc;function b4(){if(pc)return zn;pc=1,Object.defineProperty(zn,"__esModule",{value:!0}),zn.Topology=void 0;const e=_l(),t=Ve,r=Q,n=pr,i=Qe,o=Ke,u=Te,c=ne(),s=Ne,a=Ue,E=Ol(),h=nr,g=An,m=mt,C=kr,S=Ai;let D=0;const O=(0,c.makeStateMachine)({[s.STATE_CLOSED]:[s.STATE_CLOSED,s.STATE_CONNECTING],[s.STATE_CONNECTING]:[s.STATE_CONNECTING,s.STATE_CLOSING,s.STATE_CONNECTED,s.STATE_CLOSED],[s.STATE_CONNECTED]:[s.STATE_CONNECTED,s.STATE_CLOSING,s.STATE_CLOSED],[s.STATE_CLOSING]:[s.STATE_CLOSING,s.STATE_CLOSED]}),T=class T extends i.TypedEventEmitter{constructor(A,y,F){super(),this.on("error",c.noop),this.client=A,F=F??{hosts:[c.HostAddress.fromString("localhost:27017")],...Object.fromEntries(e.DEFAULT_OPTIONS.entries())},typeof y=="string"?y=[c.HostAddress.fromString(y)]:Array.isArray(y)||(y=[y]);const R=[];for(const j of y)if(typeof j=="string")R.push(c.HostAddress.fromString(j));else if(j instanceof c.HostAddress)R.push(j);else throw new r.MongoRuntimeError(`Topology cannot be constructed from ${JSON.stringify(j)}`);const v=B(F),J=D++,I=F.srvMaxHosts==null||F.srvMaxHosts===0||F.srvMaxHosts>=R.length?R:(0,c.shuffle)(R,F.srvMaxHosts),N=new Map;for(const j of I)N.set(j.toString(),new h.ServerDescription(j));this.waitQueue=new c.List,this.s={id:J,options:F,seedlist:R,state:s.STATE_CLOSED,description:new S.TopologyDescription(v,N,F.replicaSet,void 0,void 0,void 0,F),serverSelectionTimeoutMS:F.serverSelectionTimeoutMS,heartbeatFrequencyMS:F.heartbeatFrequencyMS,minHeartbeatFrequencyMS:F.minHeartbeatFrequencyMS,servers:new Map,credentials:F==null?void 0:F.credentials,clusterTime:void 0,detectShardedTopology:j=>this.detectShardedTopology(j),detectSrvRecords:j=>this.detectSrvRecords(j)},this.mongoLogger=A.mongoLogger,this.component="topology",F.srvHost&&!F.loadBalanced&&(this.s.srvPoller=F.srvPoller??new C.SrvPoller({heartbeatFrequencyMS:this.s.heartbeatFrequencyMS,srvHost:F.srvHost,srvMaxHosts:F.srvMaxHosts,srvServiceName:F.srvServiceName}),this.on(T.TOPOLOGY_DESCRIPTION_CHANGED,this.s.detectShardedTopology)),this.connectionLock=void 0}detectShardedTopology(A){var I,N,j;const y=A.previousDescription.type,F=A.newDescription.type,R=y!==s.TopologyType.Sharded&&F===s.TopologyType.Sharded,v=(I=this.s.srvPoller)==null?void 0:I.listeners(C.SrvPoller.SRV_RECORD_DISCOVERY),J=!!(v!=null&&v.includes(this.s.detectSrvRecords));R&&!J&&((N=this.s.srvPoller)==null||N.on(C.SrvPoller.SRV_RECORD_DISCOVERY,this.s.detectSrvRecords),(j=this.s.srvPoller)==null||j.start())}detectSrvRecords(A){const y=this.s.description;this.s.description=this.s.description.updateFromSrvPollingEvent(A,this.s.options.srvMaxHosts),this.s.description!==y&&(b(this),this.emitAndLog(T.TOPOLOGY_DESCRIPTION_CHANGED,new a.TopologyDescriptionChangedEvent(this.s.id,y,this.s.description)))}get description(){return this.s.description}get loadBalanced(){return this.s.options.loadBalanced}get serverApi(){return this.s.options.serverApi}async connect(A){this.connectionLock??(this.connectionLock=this._connect(A));try{return await this.connectionLock,this}finally{this.connectionLock=void 0}}async _connect(A){if(A=A??{},this.s.state===s.STATE_CONNECTED)return this;O(this,s.STATE_CONNECTING),this.emitAndLog(T.TOPOLOGY_OPENING,new a.TopologyOpeningEvent(this.s.id)),this.emitAndLog(T.TOPOLOGY_DESCRIPTION_CHANGED,new a.TopologyDescriptionChangedEvent(this.s.id,new S.TopologyDescription(s.TopologyType.Unknown),this.s.description));const y=Array.from(this.s.description.servers.values());if(this.s.servers=new Map(y.map(I=>[I.address,d(this,I)])),this.s.options.loadBalanced)for(const I of y){const N=new h.ServerDescription(I.hostAddress,void 0,{loadBalanced:this.s.options.loadBalanced});this.serverUpdateHandler(N)}const F=this.client.s.options.serverSelectionTimeoutMS,R=A.readPreference??o.ReadPreference.primary,v=u.TimeoutContext.create({timeoutMS:void 0,serverSelectionTimeoutMS:F,waitQueueTimeoutMS:this.client.s.options.waitQueueTimeoutMS}),J={operationName:"handshake",...A,timeoutContext:v,deprioritizedServers:new g.DeprioritizedServers};try{const I=await this.selectServer((0,g.readPreferenceServerSelector)(R),J);if(!(this.s.options.__skipPingOnConnect===!0)){const j=await I.pool.checkOut({timeoutContext:v});return I.pool.checkIn(j),O(this,s.STATE_CONNECTED),this.emit(T.OPEN,this),this.emit(T.CONNECT,this),this}return O(this,s.STATE_CONNECTED),this.emit(T.OPEN,this),this.emit(T.CONNECT,this),this}catch(I){throw this.close(),I}}closeCheckedOutConnections(){for(const A of this.s.servers.values())return A.closeCheckedOutConnections()}close(){if(!(this.s.state===s.STATE_CLOSED||this.s.state===s.STATE_CLOSING)){for(const A of this.s.servers.values())p(A,this);this.s.servers.clear(),O(this,s.STATE_CLOSING),f(this.waitQueue,new r.MongoTopologyClosedError),this.s.srvPoller&&(this.s.srvPoller.stop(),this.s.srvPoller.removeListener(C.SrvPoller.SRV_RECORD_DISCOVERY,this.s.detectSrvRecords)),this.removeListener(T.TOPOLOGY_DESCRIPTION_CHANGED,this.s.detectShardedTopology),O(this,s.STATE_CLOSED),this.emitAndLog(T.TOPOLOGY_CLOSED,new a.TopologyClosedEvent(this.s.id))}}async selectServer(A,y){var K,ee,ae,ye,ce,le,he,Ee,re,Ce;let F;if(typeof A!="function")if(typeof A=="string")F=(0,g.readPreferenceServerSelector)(o.ReadPreference.fromString(A));else{let _e;A instanceof o.ReadPreference?_e=A:(o.ReadPreference.translate(y),_e=y.readPreference||o.ReadPreference.primary),F=(0,g.readPreferenceServerSelector)(_e)}else F=A;y={serverSelectionTimeoutMS:this.s.serverSelectionTimeoutMS,...y},(K=this.client.mongoLogger)!=null&&K.willLog(n.MongoLoggableComponent.SERVER_SELECTION,n.SeverityLevel.DEBUG)&&((ee=this.client.mongoLogger)==null||ee.debug(n.MongoLoggableComponent.SERVER_SELECTION,new m.ServerSelectionStartedEvent(A,this.description,y.operationName)));let R;y.timeoutContext?R=y.timeoutContext.serverSelectionTimeout:R=u.Timeout.expires(y.serverSelectionTimeoutMS??0);const v=this.description.type===s.TopologyType.Sharded,J=y.session,I=J&&J.transaction;if(v&&I&&I.server)return(ae=this.client.mongoLogger)!=null&&ae.willLog(n.MongoLoggableComponent.SERVER_SELECTION,n.SeverityLevel.DEBUG)&&((ye=this.client.mongoLogger)==null||ye.debug(n.MongoLoggableComponent.SERVER_SELECTION,new m.ServerSelectionSucceededEvent(A,this.description,I.server.pool.address,y.operationName))),(ce=y.timeoutContext)!=null&&ce.clearServerSelectionTimeout&&(R==null||R.clear()),I.server;const{promise:N,resolve:j,reject:x}=(0,c.promiseWithResolvers)(),Y={serverSelector:F,topologyDescription:this.description,mongoLogger:this.client.mongoLogger,transaction:I,resolve:j,reject:x,cancelled:!1,startTime:(0,c.processTimeMS)(),operationName:y.operationName,waitingLogged:!1,deprioritizedServers:y.deprioritizedServers},$=(0,c.addAbortListener)(y.signal,function(){Y.cancelled=!0,x(this.reason)});this.waitQueue.push(Y),l(this);try{R==null||R.throwIfExpired();const _e=await(R?Promise.race([N,R]):N);return(le=y.timeoutContext)!=null&&le.csotEnabled()&&_e.description.minRoundTripTime!==0&&(y.timeoutContext.minRoundTripTime=_e.description.minRoundTripTime),_e}catch(_e){if(u.TimeoutError.is(_e)){Y.cancelled=!0;const He=new r.MongoServerSelectionError(`Server selection timed out after ${R==null?void 0:R.duration} ms`,this.description);throw(he=this.client.mongoLogger)!=null&&he.willLog(n.MongoLoggableComponent.SERVER_SELECTION,n.SeverityLevel.DEBUG)&&((Ee=this.client.mongoLogger)==null||Ee.debug(n.MongoLoggableComponent.SERVER_SELECTION,new m.ServerSelectionFailedEvent(A,this.description,He,y.operationName))),(re=y.timeoutContext)!=null&&re.csotEnabled()?new r.MongoOperationTimeoutError("Timed out during server selection",{cause:He}):He}throw _e}finally{$==null||$[c.kDispose](),(Ce=y.timeoutContext)!=null&&Ce.clearServerSelectionTimeout&&(R==null||R.clear())}}serverUpdateHandler(A){if(!this.s.description.hasServer(A.address)||w(this.s.description,A))return;const y=this.s.description,F=this.s.description.servers.get(A.address);if(!F)return;const R=A.$clusterTime;R&&(0,s._advanceClusterTime)(this,R);const v=F&&F.equals(A);if(this.s.description=this.s.description.update(A),this.s.description.compatibilityError){this.emit(T.ERROR,new r.MongoCompatibilityError(this.s.description.compatibilityError));return}if(!v){const J=this.s.description.servers.get(A.address);J&&this.emit(T.SERVER_DESCRIPTION_CHANGED,new a.ServerDescriptionChangedEvent(this.s.id,A.address,F,J))}b(this,A),this.waitQueue.length>0&&l(this),v||this.emitAndLog(T.TOPOLOGY_DESCRIPTION_CHANGED,new a.TopologyDescriptionChangedEvent(this.s.id,y,this.s.description))}auth(A,y){typeof A=="function"&&(y=A,A=void 0),typeof y=="function"&&y(void 0,!0)}isConnected(){return this.s.state===s.STATE_CONNECTED}isDestroyed(){return this.s.state===s.STATE_CLOSED}lastHello(){const A=Array.from(this.description.servers.values());return A.length===0?{}:A.filter(R=>R.type!==s.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(A){this.s.clusterTime=A}};T.SERVER_OPENING=t.SERVER_OPENING,T.SERVER_CLOSED=t.SERVER_CLOSED,T.SERVER_DESCRIPTION_CHANGED=t.SERVER_DESCRIPTION_CHANGED,T.TOPOLOGY_OPENING=t.TOPOLOGY_OPENING,T.TOPOLOGY_CLOSED=t.TOPOLOGY_CLOSED,T.TOPOLOGY_DESCRIPTION_CHANGED=t.TOPOLOGY_DESCRIPTION_CHANGED,T.ERROR=t.ERROR,T.OPEN=t.OPEN,T.CONNECT=t.CONNECT,T.CLOSE=t.CLOSE,T.TIMEOUT=t.TIMEOUT;let M=T;zn.Topology=M;function p(_,A){for(const y of t.LOCAL_SERVER_EVENTS)_.removeAllListeners(y);_.close(),A.emitAndLog(M.SERVER_CLOSED,new a.ServerClosedEvent(A.s.id,_.description.address));for(const y of t.SERVER_RELAY_EVENTS)_.removeAllListeners(y)}function B(_){return _!=null&&_.directConnection?s.TopologyType.Single:_!=null&&_.replicaSet?s.TopologyType.ReplicaSetNoPrimary:_!=null&&_.loadBalanced?s.TopologyType.LoadBalanced:s.TopologyType.Unknown}function d(_,A){_.emitAndLog(M.SERVER_OPENING,new a.ServerOpeningEvent(_.s.id,A.address));const y=new E.Server(_,A,_.s.options);for(const F of t.SERVER_RELAY_EVENTS)y.on(F,R=>_.emit(F,R));return y.on(E.Server.DESCRIPTION_RECEIVED,F=>_.serverUpdateHandler(F)),y.connect(),y}function b(_,A){if(A&&_.s.servers.has(A.address)){const y=_.s.servers.get(A.address);if(y){if(y.s.description=A,A.error instanceof r.MongoError&&A.error.hasErrorLabel(r.MongoErrorLabel.ResetPool)){const F=A.error.hasErrorLabel(r.MongoErrorLabel.InterruptInUseConnections);y.pool.clear({interruptInUseConnections:F})}else if(A.error==null){const F=_.s.description.type;(A.isDataBearing||A.type!==s.ServerType.Unknown&&F===s.TopologyType.Single)&&y.pool.ready()}}}for(const y of _.description.servers.values())if(!_.s.servers.has(y.address)){const F=d(_,y);_.s.servers.set(y.address,F)}for(const y of _.s.servers){const F=y[0];if(_.description.hasServer(F)||!_.s.servers.has(F))continue;const R=_.s.servers.get(F);_.s.servers.delete(F),R&&p(R,_)}}function f(_,A){var y,F;for(;_.length;){const R=_.shift();R&&(R.cancelled||((y=R.mongoLogger)!=null&&y.willLog(n.MongoLoggableComponent.SERVER_SELECTION,n.SeverityLevel.DEBUG)&&((F=R.mongoLogger)==null||F.debug(n.MongoLoggableComponent.SERVER_SELECTION,new m.ServerSelectionFailedEvent(R.serverSelector,R.topologyDescription,A,R.operationName))),R.reject(A)))}}function l(_){var R,v,J,I,N,j,x,Y;if(_.s.state===s.STATE_CLOSED){f(_.waitQueue,new r.MongoTopologyClosedError);return}const A=_.description.type===s.TopologyType.Sharded,y=Array.from(_.description.servers.values()),F=_.waitQueue.length;for(let $=0;$<F;++$){const K=_.waitQueue.shift();if(!K||K.cancelled)continue;let ee;try{const ce=K.serverSelector,le=K.deprioritizedServers;ee=ce?ce(_.description,y,le):y}catch(ce){(R=_.client.mongoLogger)!=null&&R.willLog(n.MongoLoggableComponent.SERVER_SELECTION,n.SeverityLevel.DEBUG)&&((v=_.client.mongoLogger)==null||v.debug(n.MongoLoggableComponent.SERVER_SELECTION,new m.ServerSelectionFailedEvent(K.serverSelector,_.description,ce,K.operationName))),K.reject(ce);continue}let ae;if(ee.length===0){K.waitingLogged||((J=_.client.mongoLogger)!=null&&J.willLog(n.MongoLoggableComponent.SERVER_SELECTION,n.SeverityLevel.INFORMATIONAL)&&((I=_.client.mongoLogger)==null||I.info(n.MongoLoggableComponent.SERVER_SELECTION,new m.WaitingForSuitableServerEvent(K.serverSelector,_.description,_.s.serverSelectionTimeoutMS!==0?_.s.serverSelectionTimeoutMS-((0,c.processTimeMS)()-K.startTime):-1,K.operationName))),K.waitingLogged=!0),_.waitQueue.push(K);continue}else if(ee.length===1)ae=_.s.servers.get(ee[0].address);else{const ce=(0,c.shuffle)(ee,2),le=_.s.servers.get(ce[0].address),he=_.s.servers.get(ce[1].address);ae=le&&he&&le.s.operationCount<he.s.operationCount?le:he}if(!ae){const ce=new r.MongoServerSelectionError("server selection returned a server description but the server was not found in the topology",_.description);(N=_.client.mongoLogger)!=null&&N.willLog(n.MongoLoggableComponent.SERVER_SELECTION,n.SeverityLevel.DEBUG)&&((j=_.client.mongoLogger)==null||j.debug(n.MongoLoggableComponent.SERVER_SELECTION,new m.ServerSelectionFailedEvent(K.serverSelector,_.description,ce,K.operationName))),K.reject(ce);return}const ye=K.transaction;A&&ye&&ye.isActive&&ae&&ye.pinServer(ae),(x=_.client.mongoLogger)!=null&&x.willLog(n.MongoLoggableComponent.SERVER_SELECTION,n.SeverityLevel.DEBUG)&&((Y=_.client.mongoLogger)==null||Y.debug(n.MongoLoggableComponent.SERVER_SELECTION,new m.ServerSelectionSucceededEvent(K.serverSelector,K.topologyDescription,ae.pool.address,K.operationName))),K.resolve(ae)}if(_.waitQueue.length>0)for(const[,$]of _.s.servers)queueMicrotask(function(){return $.requestCheck()})}function w(_,A){const y=_.servers.get(A.address),F=y==null?void 0:y.topologyVersion;return(0,h.compareTopologyVersion)(F,A.topologyVersion)>0}return zn}var Cc;function mn(){if(Cc)return Or;Cc=1,Object.defineProperty(Or,"__esModule",{value:!0}),Or.MongoClient=Or.ServerApiVersion=void 0;const e=_1,t=es(),r=pe,n=Oi(),i=Mo,o=Ht,u=Cr,c=_l(),s=Ve,a=Z1(),E=Q,h=pi,g=pr,m=Qe,C=E4(),S=Qo,D=qe,O=Ke,M=An,p=b4(),B=at,d=ne();Or.ServerApiVersion=Object.freeze({v1:"1"});class b extends m.TypedEventEmitter{constructor(l,w){super(),this.driverInfoList=[],this.on("error",d.noop),this.options=(0,c.parseOptions)(l,this,w),this.appendMetadata(this.options.driverInfo);const T=Object.values(this.options.mongoLoggerOptions.componentSeverities).some(A=>A!==g.SeverityLevel.OFF);this.mongoLogger=T?new g.MongoLogger(this.options.mongoLoggerOptions):void 0;const _=this;this.s={url:l,bsonOptions:(0,r.resolveBSONOptions)(this.options),namespace:(0,d.ns)("admin"),hasBeenClosed:!1,sessionPool:new B.ServerSessionPool(this),activeSessions:new Set,activeCursors:new Set,authProviders:new h.MongoClientAuthProviders,get options(){return _.options},get readConcern(){return _.options.readConcern},get writeConcern(){return _.options.writeConcern},get readPreference(){return _.options.readPreference},get isMongoClient(){return!0}},this.checkForNonGenuineHosts()}async[Symbol.asyncDispose](){await this.close()}appendMetadata(l){this.driverInfoList.some(T=>(0,u.isDriverInfoEqual)(T,l))||(this.driverInfoList.push(l),this.options.metadata=(0,u.makeClientMetadata)(this.driverInfoList,this.options).then(void 0,d.squashError).then(T=>T??{}))}checkForNonGenuineHosts(){var A,y;const l=this.options.hosts.filter(F=>(0,d.isHostMatch)(d.DOCUMENT_DB_CHECK,F.host)),w=(0,d.isHostMatch)(d.DOCUMENT_DB_CHECK,this.options.srvHost),T=this.options.hosts.filter(F=>(0,d.isHostMatch)(d.COSMOS_DB_CHECK,F.host)),_=(0,d.isHostMatch)(d.COSMOS_DB_CHECK,this.options.srvHost);l.length!==0||w?(A=this.mongoLogger)==null||A.info("client",d.DOCUMENT_DB_MSG):(T.length!==0||_)&&((y=this.mongoLogger)==null||y.info("client",d.COSMOS_DB_MSG))}get serverApi(){return this.options.serverApi&&Object.freeze({...this.options.serverApi})}get monitorCommands(){return this.options.monitorCommands}set monitorCommands(l){this.options.monitorCommands=l}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(l,w){if(this.autoEncrypter)throw new E.MongoInvalidArgumentError("MongoClient bulkWrite does not currently support automatic encryption.");return await new C.ClientBulkWriteExecutor(this,l,(0,d.resolveOptions)(this,w)).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(){var T,_,A,y,F,R;if(this.topology&&this.topology.isConnected())return this;const l=this.options;if(l.tls&&(typeof l.tlsCAFile=="string"&&(l.ca??(l.ca=await e.promises.readFile(l.tlsCAFile))),typeof l.tlsCRLFile=="string"&&(l.crl??(l.crl=await e.promises.readFile(l.tlsCRLFile))),typeof l.tlsCertificateKeyFile=="string"&&(!l.key||!l.cert))){const v=await e.promises.readFile(l.tlsCertificateKeyFile);l.key??(l.key=v),l.cert??(l.cert=v)}if(typeof l.srvHost=="string"){const v=await(0,c.resolveSRVRecord)(l);for(const[J,I]of v.entries())l.hosts[J]=I}if(((T=l.credentials)==null?void 0:T.mechanism)===o.AuthMechanism.MONGODB_OIDC){const v=((A=(_=l.credentials)==null?void 0:_.mechanismProperties)==null?void 0:A.ALLOWED_HOSTS)||i.DEFAULT_ALLOWED_HOSTS;if(!!!((F=(y=l.credentials)==null?void 0:y.mechanismProperties)!=null&&F.ENVIRONMENT)){for(const I of l.hosts)if(!(0,d.hostMatchesWildcards)(I.toHostPort().host,v))throw new E.MongoInvalidArgumentError(`Host '${I}' is not valid for OIDC authentication with ALLOWED_HOSTS of '${v.join(",")}'`)}}this.topology=new p.Topology(this,l.hosts,l),this.topology.once(p.Topology.OPEN,()=>this.emit("open",this));for(const v of s.MONGO_CLIENT_EVENTS)this.topology.on(v,(...J)=>this.emit(v,...J));const w=async()=>{var v,J;try{await((v=this.topology)==null?void 0:v.connect(l))}catch(I){throw(J=this.topology)==null||J.close(),I}};return this.autoEncrypter?(await((R=this.autoEncrypter)==null?void 0:R.init()),await w(),await l.encrypter.connectInternalClient()):await w(),this}async close(l=!1){if(this.closeLock)return await this.closeLock;try{this.closeLock=this._close(),await this.closeLock}finally{this.closeLock=void 0}}async _close(){var F;Object.defineProperty(this.s,"hasBeenClosed",{value:!0,enumerable:!0,configurable:!1,writable:!1}),(F=this.topology)==null||F.closeCheckedOutConnections();const l=Array.from(this.s.activeCursors,R=>R.close());this.s.activeCursors.clear(),await Promise.all(l);const w=Array.from(this.s.activeSessions,R=>R.endSession());if(this.s.activeSessions.clear(),await Promise.all(w),this.topology==null)return;(this.topology.description.type===t.TopologyType.LoadBalanced||this.topology.description.logicalSessionTimeoutMinutes!=null)&&await y(this,this.topology);const _=this.topology;this.topology=void 0,_.close();const{encrypter:A}=this.options;A&&await A.close(this);async function y(R,{description:v}){const J=(0,M.readPreferenceServerSelector)(O.ReadPreference.primaryPreferred),I=Array.from(v.servers.values());if(J(v,I,new M.DeprioritizedServers).length!==0){const j=Array.from(R.s.sessionPool.sessions,({id:x})=>x);if(j.length!==0)try{await(0,D.executeOperation)(R,new S.EndSessionsOperation(j))}catch(x){(0,d.squashError)(x)}}}}db(l,w){w=w??{},l||(l=this.s.options.dbName);const T=Object.assign({},this.options,w);return new a.Db(this,l,T)}static async connect(l,w){return await new this(l,w).connect()}startSession(l){const w=new B.ClientSession(this,this.s.sessionPool,{explicit:!0,...l},this.options);return this.s.activeSessions.add(w),w.once("ended",()=>{this.s.activeSessions.delete(w)}),w}async withSession(l,w){const T={owner:Symbol(),...typeof l=="object"?l:{}},_=typeof l=="function"?l:w;if(_==null)throw new E.MongoInvalidArgumentError("Missing required callback parameter");const A=this.startSession(T);try{return await _(A)}finally{try{await A.endSession()}catch(y){(0,d.squashError)(y)}}}watch(l=[],w={}){return Array.isArray(l)||(w=l,l=[]),new n.ChangeStream(this,l,(0,d.resolveOptions)(this,w))}}return Or.MongoClient=b,Or}var Sc;function Oi(){if(Sc)return Xr;Sc=1,Object.defineProperty(Xr,"__esModule",{value:!0}),Xr.ChangeStream=void 0,Xr.filterOutOptions=D;const e=fi(),t=Ve,r=rt,n=k0(),i=Z1(),o=Q,u=mn(),c=Qe,s=An,a=Te,E=ne(),h={COLLECTION:Symbol("Collection"),DATABASE:Symbol("Database"),CLUSTER:Symbol("Cluster")},g=[t.RESUME_TOKEN_CHANGED,t.END,t.CLOSE],m="A change stream document has been received that lacks a resume token (_id).",C="ChangeStream is closed",S=M();function D(B){return Object.fromEntries(Object.entries(B).filter(([d,b])=>!S.has(d)))}const p=class p extends c.TypedEventEmitter{async[Symbol.asyncDispose](){await this.close()}constructor(d,b=[],f={}){super(),this.pipeline=b,this.options={...f};let l;if(delete this.options.writeConcern,d instanceof e.Collection)this.type=h.COLLECTION,l=d.s.db.client.options.serverSelectionTimeoutMS;else if(d instanceof i.Db)this.type=h.DATABASE,l=d.client.options.serverSelectionTimeoutMS;else if(d instanceof u.MongoClient)this.type=h.CLUSTER,l=d.options.serverSelectionTimeoutMS;else throw new o.MongoChangeStreamError("Parent provided to ChangeStream constructor must be an instance of Collection, Db, or MongoClient");this.contextOwner=Symbol(),this.parent=d,this.namespace=d.s.namespace,!this.options.readPreference&&d.readPreference&&(this.options.readPreference=d.readPreference),this.cursor=this._createChangeStreamCursor(f),this.isClosed=!1,this.mode=!1,this.on("newListener",w=>{w==="change"&&this.cursor&&this.listenerCount("change")===0&&this._streamEvents(this.cursor)}),this.on("removeListener",w=>{var T;w==="change"&&this.listenerCount("change")===0&&this.cursor&&((T=this.cursorStream)==null||T.removeAllListeners("data"))}),this.options.timeoutMS!=null&&(this.timeoutContext=new a.CSOTTimeoutContext({timeoutMS:this.options.timeoutMS,serverSelectionTimeoutMS:l}))}get resumeToken(){var d;return(d=this.cursor)==null?void 0:d.resumeToken}async hasNext(){var d,b;this._setIsIterator(),(d=this.timeoutContext)==null||d.refresh();try{for(;;)try{return await this.cursor.hasNext()}catch(f){try{await this._processErrorIteratorMode(f,this.cursor.id!=null)}catch(l){if(l instanceof o.MongoOperationTimeoutError&&this.cursor.id==null)throw l;try{await this.close()}catch(w){(0,E.squashError)(w)}throw l}}}finally{(b=this.timeoutContext)==null||b.clear()}}async next(){var d,b;this._setIsIterator(),(d=this.timeoutContext)==null||d.refresh();try{for(;;)try{const f=await this.cursor.next();return this._processChange(f??null)}catch(f){try{await this._processErrorIteratorMode(f,this.cursor.id!=null)}catch(l){if(l instanceof o.MongoOperationTimeoutError&&this.cursor.id==null)throw l;try{await this.close()}catch(w){(0,E.squashError)(w)}throw l}}}finally{(b=this.timeoutContext)==null||b.clear()}}async tryNext(){var d,b;this._setIsIterator(),(d=this.timeoutContext)==null||d.refresh();try{for(;;)try{const f=await this.cursor.tryNext();return f?this._processChange(f):null}catch(f){try{await this._processErrorIteratorMode(f,this.cursor.id!=null)}catch(l){if(l instanceof o.MongoOperationTimeoutError&&this.cursor.id==null)throw l;try{await this.close()}catch(w){(0,E.squashError)(w)}throw l}}}finally{(b=this.timeoutContext)==null||b.clear()}}async*[Symbol.asyncIterator](){if(!this.closed)try{for(;;)yield await this.next()}finally{try{await this.close()}catch(d){(0,E.squashError)(d)}}}get closed(){return this.isClosed||this.cursor.closed}async close(){var b;(b=this.timeoutContext)==null||b.clear(),this.timeoutContext=void 0,this.isClosed=!0;const d=this.cursor;try{await d.close()}finally{this._endStream()}}stream(){if(this.closed)throw new o.MongoChangeStreamError(C);return this.cursor.stream()}_setIsEmitter(){if(this.mode==="iterator")throw new o.MongoAPIError("ChangeStream cannot be used as an EventEmitter after being used as an iterator");this.mode="emitter"}_setIsIterator(){if(this.mode==="emitter")throw new o.MongoAPIError("ChangeStream cannot be used as an iterator after being used as an EventEmitter");this.mode="iterator"}_createChangeStreamCursor(d){const b=D(d);this.type===h.CLUSTER&&(b.allChangesForCluster=!0);const f=[{$changeStream:b},...this.pipeline],l=this.type===h.CLUSTER?this.parent:this.type===h.DATABASE?this.parent.client:this.type===h.COLLECTION?this.parent.client:null;if(l==null)throw new o.MongoRuntimeError(`Changestream type should only be one of cluster, database, collection. Found ${this.type.toString()}`);const w=new n.ChangeStreamCursor(l,this.namespace,f,{...d,timeoutContext:this.timeoutContext?new r.CursorTimeoutContext(this.timeoutContext,this.contextOwner):void 0});for(const T of g)w.on(T,_=>this.emit(T,_));return this.listenerCount(p.CHANGE)>0&&this._streamEvents(w),w}_closeEmitterModeWithError(d){this.emit(p.ERROR,d),this.close().then(void 0,E.squashError)}_streamEvents(d){this._setIsEmitter();const b=this.cursorStream??d.stream();this.cursorStream=b,b.on("data",f=>{var l;try{const w=this._processChange(f);this.emit(p.CHANGE,w)}catch(w){this.emit(p.ERROR,w)}(l=this.timeoutContext)==null||l.refresh()}),b.on("error",f=>this._processErrorStreamMode(f,this.cursor.id!=null))}_endStream(){var d,b,f,l;(d=this.cursorStream)==null||d.removeAllListeners("data"),(b=this.cursorStream)==null||b.removeAllListeners("close"),(f=this.cursorStream)==null||f.removeAllListeners("end"),(l=this.cursorStream)==null||l.destroy(),this.cursorStream=void 0}_processChange(d){if(this.isClosed)throw new o.MongoAPIError(C);if(d==null)throw new o.MongoRuntimeError(C);if(d&&!d._id)throw new o.MongoChangeStreamError(m);return this.cursor.cacheResumeToken(d._id),this.options.startAtOperationTime=void 0,d}_processErrorStreamMode(d,b){this.isClosed||(b&&((0,o.isResumableError)(d,this.cursor.maxWireVersion)||d instanceof o.MongoOperationTimeoutError)?(this._endStream(),this.cursor.close().then(()=>this._resume(d),f=>((0,E.squashError)(f),this._resume(d))).then(()=>{d instanceof o.MongoOperationTimeoutError&&this.emit(p.ERROR,d)},()=>this._closeEmitterModeWithError(d))):this._closeEmitterModeWithError(d))}async _processErrorIteratorMode(d,b){if(this.isClosed)throw new o.MongoAPIError(C);if(b&&((0,o.isResumableError)(d,this.cursor.maxWireVersion)||d instanceof o.MongoOperationTimeoutError)){try{await this.cursor.close()}catch(f){(0,E.squashError)(f)}if(await this._resume(d),d instanceof o.MongoOperationTimeoutError)throw d}else{try{await this.close()}catch(f){(0,E.squashError)(f)}throw d}}async _resume(d){var f;(f=this.timeoutContext)==null||f.refresh();const b=(0,E.getTopology)(this.parent);try{await b.selectServer(this.cursor.readPreference,{operationName:"reconnect topology in change stream",timeoutContext:this.timeoutContext,deprioritizedServers:new s.DeprioritizedServers}),this.cursor=this._createChangeStreamCursor(this.cursor.resumeOptions)}catch{throw await this.close(),d}}};p.RESPONSE=t.RESPONSE,p.MORE=t.MORE,p.INIT=t.INIT,p.CLOSE=t.CLOSE,p.CHANGE=t.CHANGE,p.END=t.END,p.ERROR=t.ERROR,p.RESUME_TOKEN_CHANGED=t.RESUME_TOKEN_CHANGED;let O=p;Xr.ChangeStream=O;function M(){const B={allowDiskUse:"",authdb:"",batchSize:"",bsonRegExp:"",bypassDocumentValidation:"",bypassPinningCheck:"",checkKeys:"",collation:"",comment:"",cursor:"",dbName:"",enableUtf8Validation:"",explain:"",fieldsAsRaw:"",hint:"",ignoreUndefined:"",let:"",maxAwaitTimeMS:"",maxTimeMS:"",omitMaxTimeMS:"",out:"",promoteBuffers:"",promoteLongs:"",promoteValues:"",raw:"",rawData:"",readConcern:"",readPreference:"",serializeFunctions:"",session:"",timeoutContext:"",timeoutMS:"",timeoutMode:"",useBigInt64:"",willRetryWrite:"",writeConcern:""};return new Set(Object.keys(B))}return Xr}var $o={},wi={};Object.defineProperty(wi,"__esModule",{value:!0});wi.GridFSBucketReadStream=void 0;const M4=uo,F4=rt,Et=Q,R4=Te,Bu=class Bu extends M4.Readable{constructor(t,r,n,i,o){super({emitClose:!0}),this.s={bytesToTrim:0,bytesToSkip:0,bytesRead:0,chunks:t,expected:0,files:r,filter:i,init:!1,expectedEnd:0,options:{start:0,end:0,...o},readPreference:n,timeoutContext:(o==null?void 0:o.timeoutMS)!=null?new R4.CSOTTimeoutContext({timeoutMS:o.timeoutMS,serverSelectionTimeoutMS:0}):void 0}}_read(){this.destroyed||v4(this,()=>N4(this))}start(t=0){return yc(this),this.s.options.start=t,this}end(t=0){return yc(this),this.s.options.end=t,this}async abort(){var r,n;this.push(null),this.destroy();const t=(r=this.s.timeoutContext)==null?void 0:r.getRemainingTimeMSOrThrow();await((n=this.s.cursor)==null?void 0:n.close({timeoutMS:t}))}};Bu.FILE="file";let no=Bu;wi.GridFSBucketReadStream=no;function yc(e){if(e.s.init)throw new Et.MongoGridFSStreamError("Options cannot be changed after the stream is initialized")}function N4(e){if(e.destroyed||!e.s.cursor||!e.s.file)return;const t=r=>{var h;if(e.destroyed)return;if(!r){e.push(null),(h=e.s.cursor)==null||h.close().then(void 0,g=>e.destroy(g));return}if(!e.s.file)return;const n=e.s.file.length-e.s.bytesRead,i=e.s.expected++,o=Math.min(e.s.file.chunkSize,n);if(r.n>i)return e.destroy(new Et.MongoGridFSChunkError(`ChunkIsMissing: Got unexpected n: ${r.n}, expected: ${i}`));if(r.n<i)return e.destroy(new Et.MongoGridFSChunkError(`ExtraChunk: Got unexpected n: ${r.n}, expected: ${i}`));let u=Buffer.isBuffer(r.data)?r.data:r.data.buffer;if(u.byteLength!==o)return n<=0?e.destroy(new Et.MongoGridFSChunkError(`ExtraChunk: Got unexpected n: ${r.n}, expected file length ${e.s.file.length} bytes but already read ${e.s.bytesRead} bytes`)):e.destroy(new Et.MongoGridFSChunkError(`ChunkIsWrongSize: Got unexpected length: ${u.byteLength}, expected: ${o}`));if(e.s.bytesRead+=u.byteLength,u.byteLength===0)return e.push(null);let c=null,s=null;e.s.bytesToSkip!=null&&(c=e.s.bytesToSkip,e.s.bytesToSkip=0);const a=i===e.s.expectedEnd-1,E=e.s.options.end-e.s.bytesToSkip;a&&e.s.bytesToTrim!=null?s=e.s.file.chunkSize-e.s.bytesToTrim:e.s.options.end&&E<r.data.byteLength&&(s=E),(c!=null||s!=null)&&(u=u.slice(c||0,s||u.byteLength)),e.push(u)};e.s.cursor.next().then(t,r=>{e.destroyed||e.destroy(r)})}function I4(e){var i,o;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);const r=u=>{var a,E;if(e.destroyed)return;if(!u){const g=`FileNotFound: file ${e.s.filter._id?e.s.filter._id.toString():e.s.filter.filename} was not found`,m=new Et.MongoRuntimeError(g);return m.code="ENOENT",e.destroy(m)}if(u.length<=0){e.push(null);return}if(e.destroyed){e.destroy();return}try{e.s.bytesToSkip=P4(e,u,e.s.options)}catch(h){return e.destroy(h)}const c={files_id:u._id};if(e.s.options&&e.s.options.start!=null){const h=Math.floor(e.s.options.start/u.chunkSize);h>0&&(c.n={$gte:h})}let s;try{s=(E=e.s.timeoutContext)==null?void 0:E.getRemainingTimeMSOrThrow(`Download timed out after ${(a=e.s.timeoutContext)==null?void 0:a.timeoutMS}ms`)}catch(h){return e.destroy(h)}e.s.cursor=e.s.chunks.find(c,{timeoutMode:e.s.options.timeoutMS!=null?F4.CursorTimeoutMode.LIFETIME:void 0,timeoutMS:s}).sort({n:1}),e.s.readPreference&&e.s.cursor.withReadPreference(e.s.readPreference),e.s.expectedEnd=Math.ceil(u.length/u.chunkSize),e.s.file=u;try{e.s.bytesToTrim=L4(e,u,e.s.cursor,e.s.options)}catch(h){return e.destroy(h)}e.emit(no.FILE,u)};let n;try{n=(o=e.s.timeoutContext)==null?void 0:o.getRemainingTimeMSOrThrow(`Download timed out after ${(i=e.s.timeoutContext)==null?void 0:i.timeoutMS}ms`)}catch(u){e.destroyed||e.destroy(u);return}t.timeoutMS=n,e.s.files.findOne(e.s.filter,t).then(r,u=>{e.destroyed||e.destroy(u)})}function v4(e,t){if(e.s.file)return t();e.s.init||(I4(e),e.s.init=!0),e.once("file",()=>{t()})}function P4(e,t,r){if(r&&r.start!=null){if(r.start>t.length)throw new Et.MongoInvalidArgumentError(`Stream start (${r.start}) must not be more than the length of the file (${t.length})`);if(r.start<0)throw new Et.MongoInvalidArgumentError(`Stream start (${r.start}) must not be negative`);if(r.end!=null&&r.end<r.start)throw new Et.MongoInvalidArgumentError(`Stream start (${r.start}) must not be greater than stream end (${r.end})`);return e.s.bytesRead=Math.floor(r.start/t.chunkSize)*t.chunkSize,e.s.expected=Math.floor(r.start/t.chunkSize),r.start-e.s.bytesRead}throw new Et.MongoInvalidArgumentError("Start option must be defined")}function L4(e,t,r,n){if(n&&n.end!=null){if(n.end>t.length)throw new Et.MongoInvalidArgumentError(`Stream end (${n.end}) must not be more than the length of the file (${t.length})`);if(n.start==null||n.start<0)throw new Et.MongoInvalidArgumentError(`Stream end (${n.end}) must not be negative`);const i=n.start!=null?Math.floor(n.start/t.chunkSize):0;return r.limit(Math.ceil(n.end/t.chunkSize)-i),e.s.expectedEnd=Math.ceil(n.end/t.chunkSize),Math.ceil(n.end/t.chunkSize)*t.chunkSize-n.end}throw new Et.MongoInvalidArgumentError("End option must be defined")}var _i={};Object.defineProperty(_i,"__esModule",{value:!0});_i.GridFSBucketWriteStream=void 0;const k4=uo,zl=pe,Vl=rt,Lt=Q,U4=Te,Oc=ne(),j4=lt();class x4 extends k4.Writable{constructor(t,r,n){super(),this.gridFSFile=null,n=n??{},this.bucket=t,this.chunks=t.s._chunksCollection,this.filename=r,this.files=t.s._filesCollection,this.options=n,this.writeConcern=j4.WriteConcern.fromOptions(n)||t.s.options.writeConcern,this.done=!1,this.id=n.id?n.id:new zl.ObjectId,this.chunkSizeBytes=n.chunkSizeBytes||this.bucket.s.options.chunkSizeBytes,this.bufToStore=Buffer.alloc(this.chunkSizeBytes),this.length=0,this.n=0,this.pos=0,this.state={streamEnd:!1,outstandingRequests:0,errored:!1,aborted:!1},n.timeoutMS!=null&&(this.timeoutContext=new U4.CSOTTimeoutContext({timeoutMS:n.timeoutMS,serverSelectionTimeoutMS:(0,Oc.resolveTimeoutOptions)(this.bucket.s.db.client,{}).serverSelectionTimeoutMS}))}_construct(t){if(!this.bucket.s.calledOpenUploadStream)this.bucket.s.calledOpenUploadStream=!0,V4(this).then(()=>{this.bucket.s.checkedIndexes=!0,this.bucket.emit("index"),t()},r=>{if(r instanceof Lt.MongoOperationTimeoutError)return Ur(this,r,t);(0,Oc.squashError)(r),t()});else return queueMicrotask(t)}_write(t,r,n){G4(this,t,r,n)}_final(t){if(this.state.streamEnd)return queueMicrotask(t);this.state.streamEnd=!0,q4(this,t)}async abort(){var r,n;if(this.state.streamEnd)throw new Lt.MongoAPIError("Cannot abort a stream that has already completed");if(this.state.aborted)throw new Lt.MongoAPIError("Cannot call abort() on a stream twice");this.state.aborted=!0;const t=(n=this.timeoutContext)==null?void 0:n.getRemainingTimeMSOrThrow(`Upload timed out after ${(r=this.timeoutContext)==null?void 0:r.timeoutMS}ms`);await this.chunks.deleteMany({files_id:this.id},{timeoutMS:t})}}_i.GridFSBucketWriteStream=x4;function Ur(e,t,r){if(e.state.errored){queueMicrotask(r);return}e.state.errored=!0,queueMicrotask(()=>r(t))}function Wl(e,t,r){return{_id:new zl.ObjectId,files_id:e,n:t,data:r}}async function z4(e){var o,u,c,s;const t={files_id:1,n:1};let r;r=(u=e.timeoutContext)==null?void 0:u.getRemainingTimeMSOrThrow(`Upload timed out after ${(o=e.timeoutContext)==null?void 0:o.timeoutMS}ms`);let n;try{n=await e.chunks.listIndexes({timeoutMode:r!=null?Vl.CursorTimeoutMode.LIFETIME:void 0,timeoutMS:r}).toArray()}catch(a){if(a instanceof Lt.MongoError&&a.code===Lt.MONGODB_ERROR_CODES.NamespaceNotFound)n=[];else throw a}!!n.find(a=>Object.keys(a.key).length===2&&a.key.files_id===1&&a.key.n===1)||(r=(s=e.timeoutContext)==null?void 0:s.getRemainingTimeMSOrThrow(`Upload timed out after ${(c=e.timeoutContext)==null?void 0:c.timeoutMS}ms`),await e.chunks.createIndex(t,{...e.writeConcern,background:!0,unique:!0,timeoutMS:r}))}function O1(e,t){var r,n;if(e.done)return queueMicrotask(t);if(e.state.streamEnd&&e.state.outstandingRequests===0&&!e.state.errored){e.done=!0;const i=W4(e.id,e.length,e.chunkSizeBytes,e.filename,e.options.metadata);if(io(e,t))return;const o=(r=e.timeoutContext)==null?void 0:r.remainingTimeMS;if(o!=null&&o<=0)return Ur(e,new Lt.MongoOperationTimeoutError(`Upload timed out after ${(n=e.timeoutContext)==null?void 0:n.timeoutMS}ms`),t);e.files.insertOne(i,{writeConcern:e.writeConcern,timeoutMS:o}).then(()=>{e.gridFSFile=i,t()},u=>Ur(e,u,t));return}queueMicrotask(t)}async function V4(e){var c,s,a,E,h,g;let t=(s=e.timeoutContext)==null?void 0:s.getRemainingTimeMSOrThrow(`Upload timed out after ${(c=e.timeoutContext)==null?void 0:c.timeoutMS}ms`);if(await e.files.findOne({},{projection:{_id:1},timeoutMS:t})!=null)return;const n={filename:1,uploadDate:1};let i;t=(E=e.timeoutContext)==null?void 0:E.getRemainingTimeMSOrThrow(`Upload timed out after ${(a=e.timeoutContext)==null?void 0:a.timeoutMS}ms`);const o={timeoutMode:t!=null?Vl.CursorTimeoutMode.LIFETIME:void 0,timeoutMS:t};try{i=await e.files.listIndexes(o).toArray()}catch(m){if(m instanceof Lt.MongoError&&m.code===Lt.MONGODB_ERROR_CODES.NamespaceNotFound)i=[];else throw m}!!i.find(m=>Object.keys(m.key).length===2&&m.key.filename===1&&m.key.uploadDate===1)||(t=(g=e.timeoutContext)==null?void 0:g.getRemainingTimeMSOrThrow(`Upload timed out after ${(h=e.timeoutContext)==null?void 0:h.timeoutMS}ms`),await e.files.createIndex(n,{background:!1,timeoutMS:t})),await z4(e)}function W4(e,t,r,n,i){const o={_id:e,length:t,chunkSize:r,uploadDate:new Date,filename:n};return i&&(o.metadata=i),o}function G4(e,t,r,n){var a,E;if(io(e,n))return;const i=Buffer.isBuffer(t)?t:Buffer.from(t,r);if(e.length+=i.length,e.pos+i.length<e.chunkSizeBytes){i.copy(e.bufToStore,e.pos),e.pos+=i.length,queueMicrotask(n);return}let o=i.length,u=e.chunkSizeBytes-e.pos,c=Math.min(u,i.length),s=0;for(;o>0;){const h=i.length-o;i.copy(e.bufToStore,e.pos,h,h+c),e.pos+=c,u-=c;let g;if(u===0){g=Wl(e.id,e.n,Buffer.from(e.bufToStore));const m=(a=e.timeoutContext)==null?void 0:a.remainingTimeMS;if(m!=null&&m<=0)return Ur(e,new Lt.MongoOperationTimeoutError(`Upload timed out after ${(E=e.timeoutContext)==null?void 0:E.timeoutMS}ms`),n);if(++e.state.outstandingRequests,++s,io(e,n))return;e.chunks.insertOne(g,{writeConcern:e.writeConcern,timeoutMS:m}).then(()=>{--e.state.outstandingRequests,--s,s||O1(e,n)},C=>Ur(e,C,n)),u=e.chunkSizeBytes,e.pos=0,++e.n}o-=c,c=Math.min(u,o)}}function q4(e,t){var o,u;if(e.pos===0)return O1(e,t);const r=Buffer.alloc(e.pos);e.bufToStore.copy(r,0,0,e.pos);const n=Wl(e.id,e.n,r);if(io(e,t))return;const i=(o=e.timeoutContext)==null?void 0:o.remainingTimeMS;if(i!=null&&i<=0)return Ur(e,new Lt.MongoOperationTimeoutError(`Upload timed out after ${(u=e.timeoutContext)==null?void 0:u.timeoutMS}ms`),t);++e.state.outstandingRequests,e.chunks.insertOne(n,{writeConcern:e.writeConcern,timeoutMS:i}).then(()=>{--e.state.outstandingRequests,O1(e,t)},c=>Ur(e,c,t))}function io(e,t){return e.state.aborted?(queueMicrotask(()=>t(new Lt.MongoAPIError("Stream has been aborted"))),!0):!1}Object.defineProperty($o,"__esModule",{value:!0});$o.GridFSBucket=void 0;const u1=Q,H4=Qe,wc=Te,Ui=ne(),K4=lt(),_c=wi,Dc=_i,Y4={bucketName:"fs",chunkSizeBytes:255*1024},bu=class bu extends H4.TypedEventEmitter{constructor(t,r){super(),this.on("error",Ui.noop),this.setMaxListeners(0);const n=(0,Ui.resolveOptions)(t,{...Y4,...r,writeConcern:K4.WriteConcern.fromOptions(r)});this.s={db:t,options:n,_chunksCollection:t.collection(n.bucketName+".chunks"),_filesCollection:t.collection(n.bucketName+".files"),checkedIndexes:!1,calledOpenUploadStream:!1}}openUploadStream(t,r){return new Dc.GridFSBucketWriteStream(this,t,{timeoutMS:this.s.options.timeoutMS,...r})}openUploadStreamWithId(t,r,n){return new Dc.GridFSBucketWriteStream(this,r,{timeoutMS:this.s.options.timeoutMS,...n,id:t})}openDownloadStream(t,r){return new _c.GridFSBucketReadStream(this.s._chunksCollection,this.s._filesCollection,this.s.options.readPreference,{_id:t},{timeoutMS:this.s.options.timeoutMS,...r})}async delete(t,r){const{timeoutMS:n}=(0,Ui.resolveOptions)(this.s.db,r);let i;n&&(i=new wc.CSOTTimeoutContext({timeoutMS:n,serverSelectionTimeoutMS:this.s.db.client.s.options.serverSelectionTimeoutMS}));const{deletedCount:o}=await this.s._filesCollection.deleteOne({_id:t},{timeoutMS:i==null?void 0:i.remainingTimeMS}),u=i==null?void 0:i.remainingTimeMS;if(u!=null&&u<=0)throw new u1.MongoOperationTimeoutError(`Timed out after ${n}ms`);if(await this.s._chunksCollection.deleteMany({files_id:t},{timeoutMS:u}),o===0)throw new u1.MongoRuntimeError(`File not found for id ${t}`)}find(t={},r={}){return this.s._filesCollection.find(t,r)}openDownloadStreamByName(t,r){let n={uploadDate:-1},i;return r&&r.revision!=null&&(r.revision>=0?(n={uploadDate:1},i=r.revision):i=-r.revision-1),new _c.GridFSBucketReadStream(this.s._chunksCollection,this.s._filesCollection,this.s.options.readPreference,{filename:t},{timeoutMS:this.s.options.timeoutMS,...r,sort:n,skip:i})}async rename(t,r,n){const i={_id:t},o={$set:{filename:r}},{matchedCount:u}=await this.s._filesCollection.updateOne(i,o,n);if(u===0)throw new u1.MongoRuntimeError(`File with id ${t} not found`)}async drop(t){const{timeoutMS:r}=(0,Ui.resolveOptions)(this.s.db,t);let n;if(r&&(n=new wc.CSOTTimeoutContext({timeoutMS:r,serverSelectionTimeoutMS:this.s.db.client.s.options.serverSelectionTimeoutMS})),n){await this.s._filesCollection.drop({timeoutMS:n.remainingTimeMS});const i=n.getRemainingTimeMSOrThrow(`Timed out after ${r}ms`);await this.s._chunksCollection.drop({timeoutMS:i})}else await this.s._filesCollection.drop(),await this.s._chunksCollection.drop()}};bu.INDEX="index";let w1=bu;$o.GridFSBucket=w1;var Tc;function es(){return Tc||(Tc=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.MongoRuntimeError=e.MongoParseError=e.MongoOperationTimeoutError=e.MongoOIDCError=e.MongoNotConnectedError=e.MongoNetworkTimeoutError=e.MongoNetworkError=e.MongoMissingDependencyError=e.MongoMissingCredentialsError=e.MongoKerberosError=e.MongoInvalidArgumentError=e.MongoGridFSStreamError=e.MongoGridFSChunkError=e.MongoGCPError=e.MongoExpiredSessionError=e.MongoError=e.MongoDriverError=e.MongoDecompressionError=e.MongoCursorInUseError=e.MongoCursorExhaustedError=e.MongoCompatibilityError=e.MongoClientClosedError=e.MongoClientBulkWriteExecutionError=e.MongoClientBulkWriteError=e.MongoClientBulkWriteCursorError=e.MongoChangeStreamError=e.MongoBatchReExecutionError=e.MongoAzureError=e.MongoAWSError=e.MongoAPIError=e.ExplainableCursor=e.ChangeStreamCursor=e.ClientEncryption=e.MongoBulkWriteError=e.UUID=e.Timestamp=e.ObjectId=e.MinKey=e.MaxKey=e.Long=e.Int32=e.Double=e.Decimal128=e.DBRef=e.Code=e.BSONType=e.BSONSymbol=e.BSONRegExp=e.Binary=e.BSON=void 0,e.CommandStartedEvent=e.CommandFailedEvent=e.WriteConcern=e.ReadPreference=e.ReadConcern=e.TopologyType=e.ServerType=e.ReadPreferenceMode=e.ReadConcernLevel=e.ProfilingLevel=e.ReturnDocument=e.SeverityLevel=e.MongoLoggableComponent=e.ServerApiVersion=e.ExplainVerbosity=e.MongoErrorLabel=e.CursorTimeoutMode=e.CURSOR_FLAGS=e.Compressor=e.AuthMechanism=e.GSSAPICanonicalizationValue=e.AutoEncryptionLoggerLevel=e.BatchType=e.UnorderedBulkOperation=e.OrderedBulkOperation=e.MongoClient=e.ListIndexesCursor=e.ListCollectionsCursor=e.GridFSBucketWriteStream=e.GridFSBucketReadStream=e.GridFSBucket=e.FindCursor=e.Db=e.Collection=e.ClientSession=e.ChangeStream=e.CancellationToken=e.AggregationCursor=e.Admin=e.AbstractCursor=e.MongoWriteConcernError=e.MongoUnexpectedServerResponseError=e.MongoTransactionError=e.MongoTopologyClosedError=e.MongoTailableCursorError=e.MongoSystemError=e.MongoStalePrimaryError=e.MongoServerSelectionError=e.MongoServerError=e.MongoServerClosedError=void 0,e.MongoClientAuthProviders=e.MongoCryptKMSRequestNetworkTimeoutError=e.MongoCryptInvalidArgumentError=e.MongoCryptError=e.MongoCryptCreateEncryptedCollectionError=e.MongoCryptCreateDataKeyError=e.MongoCryptAzureKMSRequestError=e.SrvPollingEvent=e.WaitingForSuitableServerEvent=e.ServerSelectionSucceededEvent=e.ServerSelectionStartedEvent=e.ServerSelectionFailedEvent=e.ServerSelectionEvent=e.TopologyOpeningEvent=e.TopologyDescriptionChangedEvent=e.TopologyClosedEvent=e.ServerOpeningEvent=e.ServerHeartbeatSucceededEvent=e.ServerHeartbeatStartedEvent=e.ServerHeartbeatFailedEvent=e.ServerDescriptionChangedEvent=e.ServerClosedEvent=e.ConnectionReadyEvent=e.ConnectionPoolReadyEvent=e.ConnectionPoolMonitoringEvent=e.ConnectionPoolCreatedEvent=e.ConnectionPoolClosedEvent=e.ConnectionPoolClearedEvent=e.ConnectionCreatedEvent=e.ConnectionClosedEvent=e.ConnectionCheckOutStartedEvent=e.ConnectionCheckOutFailedEvent=e.ConnectionCheckedOutEvent=e.ConnectionCheckedInEvent=e.CommandSucceededEvent=void 0;const t=$n;Object.defineProperty(e,"Admin",{enumerable:!0,get:function(){return t.Admin}});const r=si;Object.defineProperty(e,"OrderedBulkOperation",{enumerable:!0,get:function(){return r.OrderedBulkOperation}});const n=ai;Object.defineProperty(e,"UnorderedBulkOperation",{enumerable:!0,get:function(){return n.UnorderedBulkOperation}});const i=Oi();Object.defineProperty(e,"ChangeStream",{enumerable:!0,get:function(){return i.ChangeStream}});const o=fi();Object.defineProperty(e,"Collection",{enumerable:!0,get:function(){return o.Collection}});const u=rt;Object.defineProperty(e,"AbstractCursor",{enumerable:!0,get:function(){return u.AbstractCursor}});const c=Gr;Object.defineProperty(e,"AggregationCursor",{enumerable:!0,get:function(){return c.AggregationCursor}});const s=Pr;Object.defineProperty(e,"FindCursor",{enumerable:!0,get:function(){return s.FindCursor}});const a=mi;Object.defineProperty(e,"ListCollectionsCursor",{enumerable:!0,get:function(){return a.ListCollectionsCursor}});const E=di;Object.defineProperty(e,"ListIndexesCursor",{enumerable:!0,get:function(){return E.ListIndexesCursor}});const h=Z1();Object.defineProperty(e,"Db",{enumerable:!0,get:function(){return h.Db}});const g=$o;Object.defineProperty(e,"GridFSBucket",{enumerable:!0,get:function(){return g.GridFSBucket}});const m=wi;Object.defineProperty(e,"GridFSBucketReadStream",{enumerable:!0,get:function(){return m.GridFSBucketReadStream}});const C=_i;Object.defineProperty(e,"GridFSBucketWriteStream",{enumerable:!0,get:function(){return C.GridFSBucketWriteStream}});const S=mn();Object.defineProperty(e,"MongoClient",{enumerable:!0,get:function(){return S.MongoClient}});const D=Qe;Object.defineProperty(e,"CancellationToken",{enumerable:!0,get:function(){return D.CancellationToken}});const O=at;Object.defineProperty(e,"ClientSession",{enumerable:!0,get:function(){return O.ClientSession}});var M=pe;Object.defineProperty(e,"BSON",{enumerable:!0,get:function(){return M.BSON}});var p=pe;Object.defineProperty(e,"Binary",{enumerable:!0,get:function(){return p.Binary}}),Object.defineProperty(e,"BSONRegExp",{enumerable:!0,get:function(){return p.BSONRegExp}}),Object.defineProperty(e,"BSONSymbol",{enumerable:!0,get:function(){return p.BSONSymbol}}),Object.defineProperty(e,"BSONType",{enumerable:!0,get:function(){return p.BSONType}}),Object.defineProperty(e,"Code",{enumerable:!0,get:function(){return p.Code}}),Object.defineProperty(e,"DBRef",{enumerable:!0,get:function(){return p.DBRef}}),Object.defineProperty(e,"Decimal128",{enumerable:!0,get:function(){return p.Decimal128}}),Object.defineProperty(e,"Double",{enumerable:!0,get:function(){return p.Double}}),Object.defineProperty(e,"Int32",{enumerable:!0,get:function(){return p.Int32}}),Object.defineProperty(e,"Long",{enumerable:!0,get:function(){return p.Long}}),Object.defineProperty(e,"MaxKey",{enumerable:!0,get:function(){return p.MaxKey}}),Object.defineProperty(e,"MinKey",{enumerable:!0,get:function(){return p.MinKey}}),Object.defineProperty(e,"ObjectId",{enumerable:!0,get:function(){return p.ObjectId}}),Object.defineProperty(e,"Timestamp",{enumerable:!0,get:function(){return p.Timestamp}}),Object.defineProperty(e,"UUID",{enumerable:!0,get:function(){return p.UUID}});var B=Kn;Object.defineProperty(e,"MongoBulkWriteError",{enumerable:!0,get:function(){return B.MongoBulkWriteError}});var d=Au();Object.defineProperty(e,"ClientEncryption",{enumerable:!0,get:function(){return d.ClientEncryption}});var b=k0();Object.defineProperty(e,"ChangeStreamCursor",{enumerable:!0,get:function(){return b.ChangeStreamCursor}});var f=Cn;Object.defineProperty(e,"ExplainableCursor",{enumerable:!0,get:function(){return f.ExplainableCursor}});var l=Q;Object.defineProperty(e,"MongoAPIError",{enumerable:!0,get:function(){return l.MongoAPIError}}),Object.defineProperty(e,"MongoAWSError",{enumerable:!0,get:function(){return l.MongoAWSError}}),Object.defineProperty(e,"MongoAzureError",{enumerable:!0,get:function(){return l.MongoAzureError}}),Object.defineProperty(e,"MongoBatchReExecutionError",{enumerable:!0,get:function(){return l.MongoBatchReExecutionError}}),Object.defineProperty(e,"MongoChangeStreamError",{enumerable:!0,get:function(){return l.MongoChangeStreamError}}),Object.defineProperty(e,"MongoClientBulkWriteCursorError",{enumerable:!0,get:function(){return l.MongoClientBulkWriteCursorError}}),Object.defineProperty(e,"MongoClientBulkWriteError",{enumerable:!0,get:function(){return l.MongoClientBulkWriteError}}),Object.defineProperty(e,"MongoClientBulkWriteExecutionError",{enumerable:!0,get:function(){return l.MongoClientBulkWriteExecutionError}}),Object.defineProperty(e,"MongoClientClosedError",{enumerable:!0,get:function(){return l.MongoClientClosedError}}),Object.defineProperty(e,"MongoCompatibilityError",{enumerable:!0,get:function(){return l.MongoCompatibilityError}}),Object.defineProperty(e,"MongoCursorExhaustedError",{enumerable:!0,get:function(){return l.MongoCursorExhaustedError}}),Object.defineProperty(e,"MongoCursorInUseError",{enumerable:!0,get:function(){return l.MongoCursorInUseError}}),Object.defineProperty(e,"MongoDecompressionError",{enumerable:!0,get:function(){return l.MongoDecompressionError}}),Object.defineProperty(e,"MongoDriverError",{enumerable:!0,get:function(){return l.MongoDriverError}}),Object.defineProperty(e,"MongoError",{enumerable:!0,get:function(){return l.MongoError}}),Object.defineProperty(e,"MongoExpiredSessionError",{enumerable:!0,get:function(){return l.MongoExpiredSessionError}}),Object.defineProperty(e,"MongoGCPError",{enumerable:!0,get:function(){return l.MongoGCPError}}),Object.defineProperty(e,"MongoGridFSChunkError",{enumerable:!0,get:function(){return l.MongoGridFSChunkError}}),Object.defineProperty(e,"MongoGridFSStreamError",{enumerable:!0,get:function(){return l.MongoGridFSStreamError}}),Object.defineProperty(e,"MongoInvalidArgumentError",{enumerable:!0,get:function(){return l.MongoInvalidArgumentError}}),Object.defineProperty(e,"MongoKerberosError",{enumerable:!0,get:function(){return l.MongoKerberosError}}),Object.defineProperty(e,"MongoMissingCredentialsError",{enumerable:!0,get:function(){return l.MongoMissingCredentialsError}}),Object.defineProperty(e,"MongoMissingDependencyError",{enumerable:!0,get:function(){return l.MongoMissingDependencyError}}),Object.defineProperty(e,"MongoNetworkError",{enumerable:!0,get:function(){return l.MongoNetworkError}}),Object.defineProperty(e,"MongoNetworkTimeoutError",{enumerable:!0,get:function(){return l.MongoNetworkTimeoutError}}),Object.defineProperty(e,"MongoNotConnectedError",{enumerable:!0,get:function(){return l.MongoNotConnectedError}}),Object.defineProperty(e,"MongoOIDCError",{enumerable:!0,get:function(){return l.MongoOIDCError}}),Object.defineProperty(e,"MongoOperationTimeoutError",{enumerable:!0,get:function(){return l.MongoOperationTimeoutError}}),Object.defineProperty(e,"MongoParseError",{enumerable:!0,get:function(){return l.MongoParseError}}),Object.defineProperty(e,"MongoRuntimeError",{enumerable:!0,get:function(){return l.MongoRuntimeError}}),Object.defineProperty(e,"MongoServerClosedError",{enumerable:!0,get:function(){return l.MongoServerClosedError}}),Object.defineProperty(e,"MongoServerError",{enumerable:!0,get:function(){return l.MongoServerError}}),Object.defineProperty(e,"MongoServerSelectionError",{enumerable:!0,get:function(){return l.MongoServerSelectionError}}),Object.defineProperty(e,"MongoStalePrimaryError",{enumerable:!0,get:function(){return l.MongoStalePrimaryError}}),Object.defineProperty(e,"MongoSystemError",{enumerable:!0,get:function(){return l.MongoSystemError}}),Object.defineProperty(e,"MongoTailableCursorError",{enumerable:!0,get:function(){return l.MongoTailableCursorError}}),Object.defineProperty(e,"MongoTopologyClosedError",{enumerable:!0,get:function(){return l.MongoTopologyClosedError}}),Object.defineProperty(e,"MongoTransactionError",{enumerable:!0,get:function(){return l.MongoTransactionError}}),Object.defineProperty(e,"MongoUnexpectedServerResponseError",{enumerable:!0,get:function(){return l.MongoUnexpectedServerResponseError}}),Object.defineProperty(e,"MongoWriteConcernError",{enumerable:!0,get:function(){return l.MongoWriteConcernError}});var w=Kn;Object.defineProperty(e,"BatchType",{enumerable:!0,get:function(){return w.BatchType}});var T=El();Object.defineProperty(e,"AutoEncryptionLoggerLevel",{enumerable:!0,get:function(){return T.AutoEncryptionLoggerLevel}});var _=Fo;Object.defineProperty(e,"GSSAPICanonicalizationValue",{enumerable:!0,get:function(){return _.GSSAPICanonicalizationValue}});var A=Ht;Object.defineProperty(e,"AuthMechanism",{enumerable:!0,get:function(){return A.AuthMechanism}});var y=Po();Object.defineProperty(e,"Compressor",{enumerable:!0,get:function(){return y.Compressor}});var F=rt;Object.defineProperty(e,"CURSOR_FLAGS",{enumerable:!0,get:function(){return F.CURSOR_FLAGS}}),Object.defineProperty(e,"CursorTimeoutMode",{enumerable:!0,get:function(){return F.CursorTimeoutMode}});var R=Q;Object.defineProperty(e,"MongoErrorLabel",{enumerable:!0,get:function(){return R.MongoErrorLabel}});var v=ii;Object.defineProperty(e,"ExplainVerbosity",{enumerable:!0,get:function(){return v.ExplainVerbosity}});var J=mn();Object.defineProperty(e,"ServerApiVersion",{enumerable:!0,get:function(){return J.ServerApiVersion}});var I=pr;Object.defineProperty(e,"MongoLoggableComponent",{enumerable:!0,get:function(){return I.MongoLoggableComponent}}),Object.defineProperty(e,"SeverityLevel",{enumerable:!0,get:function(){return I.SeverityLevel}});var N=X1;Object.defineProperty(e,"ReturnDocument",{enumerable:!0,get:function(){return N.ReturnDocument}});var j=Q1;Object.defineProperty(e,"ProfilingLevel",{enumerable:!0,get:function(){return j.ProfilingLevel}});var x=kt;Object.defineProperty(e,"ReadConcernLevel",{enumerable:!0,get:function(){return x.ReadConcernLevel}});var Y=Ke;Object.defineProperty(e,"ReadPreferenceMode",{enumerable:!0,get:function(){return Y.ReadPreferenceMode}});var $=Ne;Object.defineProperty(e,"ServerType",{enumerable:!0,get:function(){return $.ServerType}}),Object.defineProperty(e,"TopologyType",{enumerable:!0,get:function(){return $.TopologyType}});var K=kt;Object.defineProperty(e,"ReadConcern",{enumerable:!0,get:function(){return K.ReadConcern}});var ee=Ke;Object.defineProperty(e,"ReadPreference",{enumerable:!0,get:function(){return ee.ReadPreference}});var ae=lt();Object.defineProperty(e,"WriteConcern",{enumerable:!0,get:function(){return ae.WriteConcern}});var ye=Cu;Object.defineProperty(e,"CommandFailedEvent",{enumerable:!0,get:function(){return ye.CommandFailedEvent}}),Object.defineProperty(e,"CommandStartedEvent",{enumerable:!0,get:function(){return ye.CommandStartedEvent}}),Object.defineProperty(e,"CommandSucceededEvent",{enumerable:!0,get:function(){return ye.CommandSucceededEvent}});var ce=Fe;Object.defineProperty(e,"ConnectionCheckedInEvent",{enumerable:!0,get:function(){return ce.ConnectionCheckedInEvent}}),Object.defineProperty(e,"ConnectionCheckedOutEvent",{enumerable:!0,get:function(){return ce.ConnectionCheckedOutEvent}}),Object.defineProperty(e,"ConnectionCheckOutFailedEvent",{enumerable:!0,get:function(){return ce.ConnectionCheckOutFailedEvent}}),Object.defineProperty(e,"ConnectionCheckOutStartedEvent",{enumerable:!0,get:function(){return ce.ConnectionCheckOutStartedEvent}}),Object.defineProperty(e,"ConnectionClosedEvent",{enumerable:!0,get:function(){return ce.ConnectionClosedEvent}}),Object.defineProperty(e,"ConnectionCreatedEvent",{enumerable:!0,get:function(){return ce.ConnectionCreatedEvent}}),Object.defineProperty(e,"ConnectionPoolClearedEvent",{enumerable:!0,get:function(){return ce.ConnectionPoolClearedEvent}}),Object.defineProperty(e,"ConnectionPoolClosedEvent",{enumerable:!0,get:function(){return ce.ConnectionPoolClosedEvent}}),Object.defineProperty(e,"ConnectionPoolCreatedEvent",{enumerable:!0,get:function(){return ce.ConnectionPoolCreatedEvent}}),Object.defineProperty(e,"ConnectionPoolMonitoringEvent",{enumerable:!0,get:function(){return ce.ConnectionPoolMonitoringEvent}}),Object.defineProperty(e,"ConnectionPoolReadyEvent",{enumerable:!0,get:function(){return ce.ConnectionPoolReadyEvent}}),Object.defineProperty(e,"ConnectionReadyEvent",{enumerable:!0,get:function(){return ce.ConnectionReadyEvent}});var le=Ue;Object.defineProperty(e,"ServerClosedEvent",{enumerable:!0,get:function(){return le.ServerClosedEvent}}),Object.defineProperty(e,"ServerDescriptionChangedEvent",{enumerable:!0,get:function(){return le.ServerDescriptionChangedEvent}}),Object.defineProperty(e,"ServerHeartbeatFailedEvent",{enumerable:!0,get:function(){return le.ServerHeartbeatFailedEvent}}),Object.defineProperty(e,"ServerHeartbeatStartedEvent",{enumerable:!0,get:function(){return le.ServerHeartbeatStartedEvent}}),Object.defineProperty(e,"ServerHeartbeatSucceededEvent",{enumerable:!0,get:function(){return le.ServerHeartbeatSucceededEvent}}),Object.defineProperty(e,"ServerOpeningEvent",{enumerable:!0,get:function(){return le.ServerOpeningEvent}}),Object.defineProperty(e,"TopologyClosedEvent",{enumerable:!0,get:function(){return le.TopologyClosedEvent}}),Object.defineProperty(e,"TopologyDescriptionChangedEvent",{enumerable:!0,get:function(){return le.TopologyDescriptionChangedEvent}}),Object.defineProperty(e,"TopologyOpeningEvent",{enumerable:!0,get:function(){return le.TopologyOpeningEvent}});var he=mt;Object.defineProperty(e,"ServerSelectionEvent",{enumerable:!0,get:function(){return he.ServerSelectionEvent}}),Object.defineProperty(e,"ServerSelectionFailedEvent",{enumerable:!0,get:function(){return he.ServerSelectionFailedEvent}}),Object.defineProperty(e,"ServerSelectionStartedEvent",{enumerable:!0,get:function(){return he.ServerSelectionStartedEvent}}),Object.defineProperty(e,"ServerSelectionSucceededEvent",{enumerable:!0,get:function(){return he.ServerSelectionSucceededEvent}}),Object.defineProperty(e,"WaitingForSuitableServerEvent",{enumerable:!0,get:function(){return he.WaitingForSuitableServerEvent}});var Ee=kr;Object.defineProperty(e,"SrvPollingEvent",{enumerable:!0,get:function(){return Ee.SrvPollingEvent}});var re=Ge;Object.defineProperty(e,"MongoCryptAzureKMSRequestError",{enumerable:!0,get:function(){return re.MongoCryptAzureKMSRequestError}}),Object.defineProperty(e,"MongoCryptCreateDataKeyError",{enumerable:!0,get:function(){return re.MongoCryptCreateDataKeyError}}),Object.defineProperty(e,"MongoCryptCreateEncryptedCollectionError",{enumerable:!0,get:function(){return re.MongoCryptCreateEncryptedCollectionError}}),Object.defineProperty(e,"MongoCryptError",{enumerable:!0,get:function(){return re.MongoCryptError}}),Object.defineProperty(e,"MongoCryptInvalidArgumentError",{enumerable:!0,get:function(){return re.MongoCryptInvalidArgumentError}}),Object.defineProperty(e,"MongoCryptKMSRequestNetworkTimeoutError",{enumerable:!0,get:function(){return re.MongoCryptKMSRequestNetworkTimeoutError}});var Ce=pi;Object.defineProperty(e,"MongoClientAuthProviders",{enumerable:!0,get:function(){return Ce.MongoClientAuthProviders}})}(ns)),ns}var a1=es();class X4{constructor(t,r,n,i){se(this,"client");se(this,"schemaMeta");se(this,"context");se(this,"fieldMetaMap",{});se(this,"idField","_id");se(this,"dbName","");se(this,"session");this.client=t,this.schemaMeta=r,this.context=n,this.session=i,this.dbName=t.options.dbName,this.fieldMetaMap=Object.entries(r).reduce((o,[u,c])=>(o[u]=c.columns.reduce((s,a)=>(s[a.name]=a,s),{}),o),{})}getObjectId(t){return new a1.ObjectId(t)}getCollection(t){return this.client.db(this.dbName).collection(t)}normalizeId(t){return typeof t=="string"&&a1.ObjectId.isValid(t)?new a1.ObjectId(t):t}buildSort(t){const r={};return t.forEach(n=>{r[n.fieldName]=n.order==="asc"?1:-1}),r}buildFindOptions(t){const r={};if(t!=null&&t.select&&(r.projection=t.select),(t==null?void 0:t.offset)!=null&&(r.skip=t.offset),(t==null?void 0:t.limit)!=null&&(r.limit=t.limit),t!=null&&t.orderBy){const n=pt.QueryBuilder.getOrderByArray(t.orderBy);n.length>0&&(r.sort=this.buildSort(n))}return r}transformResultData(t){return t&&pt.isPlainObject(t)?Object.entries(t).reduce((r,[n,i])=>{var o;return n===this.idField&&typeof i=="object"&&i?r[n]=((o=i==null?void 0:i.toString)==null?void 0:o.call(i))??i:r[n]=i,r},{}):t}async findUnique(t,{where:r,select:n}){const i=this.getCollection(t),o=Object.keys(r??{});if(o.length===1&&o[0]===this.idField){const a={[this.idField]:this.normalizeId(r[this.idField])},E={};n&&(E.projection=n);const h=await i.findOne(a,{...E,session:this.session});return this.transformResultData(h)}const u=pt.QueryBuilder.buildMongodbQuery(r,this.fieldMetaMap[t],this.getObjectId),c={};n&&(c.projection=n);const s=await i.find(u,{...c,limit:1,session:this.session}).toArray();return this.transformResultData(s[0]??null)}async findUniqueOrThrow(t,{where:r,select:n}){const i=await this.findUnique(t,{where:r,select:n});if(!i)throw new Error("Data Not Found");return i}async findFirst(t,r){const n=this.getCollection(t),i=pt.QueryBuilder.buildMongodbQuery((r==null?void 0:r.where)??{},this.fieldMetaMap[t],this.getObjectId),o=this.buildFindOptions({...r,limit:1}),u=await n.findOne(i,{...o,session:this.session});return this.transformResultData(u)}async findFirstOrThrow(t,r){const n=await this.findFirst(t,r);if(!n)throw new Error("Data Not Found");return n}async findManyInner(t,r){const n=this.getCollection(t),i=pt.QueryBuilder.buildMongodbQuery((r==null?void 0:r.where)??{},this.fieldMetaMap[t],this.getObjectId),o=this.buildFindOptions(r);return{data:(await n.find(i,{...o,session:this.session}).toArray()).map(c=>this.transformResultData(c))}}async findMany(t,r){const n=r==null?void 0:r.where,i=r==null?void 0:r.orderBy,o=r==null?void 0:r.select,{data:u}=await this.findManyInner(t,{where:n,orderBy:i,select:o,limit:1e3,offset:0});return u}async findPage(t,r){const i=(r==null?void 0:r.limit)||10;if(i>1e3)throw new Error("limit must be less than or equal to 1000");const o=r==null?void 0:r.where,u=r==null?void 0:r.orderBy,c=(r==null?void 0:r.page)||1,s=r==null?void 0:r.select,a=(c-1)*i,E=this.findManyInner(t,{where:o,orderBy:u,select:s,limit:i,offset:a}),h=this.count(t,{where:o}),{data:g}=await E,m=await h,C=Math.ceil(m/i);return{data:g,total:m,page:c,pageCount:C,limit:i,hasPrev:c>1,hasNext:c<C}}async create(t,{data:r}){const n=this.getCollection(t),i=pt.applyDefaultValues(r,this.schemaMeta[t],this.context);return{_id:(await n.insertOne(i,{session:this.session})).insertedId.toString()}}transformUpdateData(t){const r=["$set","$inc","$mul","$remove","$push","$pop","$unshift","$shift"];return Object.entries(t??[]).reduce((n,[i,o])=>(i==="$set"||(r.includes(i)?n[i]=o:n.$set[i]=o),n),{$set:{...(t==null?void 0:t.$set)??{}}})}async update(t,{where:r,data:n}){const i=this.getCollection(t),o=this.transformUpdateData(pt.applyUpdateValues(n,this.schemaMeta[t])),u=Object.keys(r??{});if(u.length===1&&u[0]===this.idField){const s={[this.idField]:this.normalizeId(r[this.idField])};await i.updateOne(s,o,{session:this.session});return}const c=pt.QueryBuilder.buildMongodbQuery(r,this.fieldMetaMap[t],this.getObjectId);await i.updateMany(c,o,{session:this.session})}async updateAndReturn(t,{where:r,data:n}){const i=this.getCollection(t),o=this.transformUpdateData(pt.applyUpdateValues(n,this.schemaMeta[t])),u=pt.QueryBuilder.buildMongodbQuery(r,this.fieldMetaMap[t],this.getObjectId),c=await i.findOneAndUpdate(u,o,{session:this.session,returnDocument:"after"});return this.transformResultData(c??null)}async delete(t,{where:r}){const n=this.getCollection(t),i=Object.keys(r??{});if(i.length===1&&i[0]===this.idField){const u={[this.idField]:this.normalizeId(r[this.idField])};await n.deleteOne(u,{session:this.session});return}const o=pt.QueryBuilder.buildMongodbQuery(r,this.fieldMetaMap[t],this.getObjectId);await n.deleteMany(o,{session:this.session})}async count(t,r){try{const n=this.getCollection(t),i=pt.QueryBuilder.buildMongodbQuery((r==null?void 0:r.where)??{},this.fieldMetaMap[t],this.getObjectId);return await n.countDocuments(i,{session:this.session})}catch(n){throw console.error("count error:",n),n}}async aggregate(t,r){const i=await this.getCollection(t).aggregate(r,{session:this.session}).toArray();return(i==null?void 0:i.map(o=>this.transformResultData(o)))??[]}}function Gl(e,t,r,n){const i=new X4(e,t,r,n),o={$dbClient:e};return Object.keys(t).forEach(u=>{o[u]={findUnique:c=>i.findUnique(u,c),findUniqueOrThrow:c=>i.findUniqueOrThrow(u,c),findFirst:c=>i.findFirst(u,c),findFirstOrThrow:c=>i.findFirstOrThrow(u,c),findMany:c=>i.findMany(u,c),findPage:c=>i.findPage(u,c),create:c=>i.create(u,c),update:c=>i.update(u,c),updateMany:c=>i.update(u,c),updateAndReturn:c=>i.updateAndReturn(u,c),delete:c=>i.delete(u,c),count:c=>i.count(u,c),aggregate:c=>i.aggregate(u,c)}}),o.$transaction=async u=>{const c=e.startSession();try{c.startTransaction();const s=Gl(e,t,r,c);s.$transaction=void 0;const a=await u(s);return await c.commitTransaction(),await c.endSession(),a}catch(s){throw await c.abortTransaction(),await c.endSession(),s}},o}function J4(e,t,r){return Gl(e,t,r)}exports.createMongoDBClient=J4;
|
|
12
|
+
`),M=await Ln("AWS4"+t.secretAccessKey,i),p=await Ln(M,e.region),B=await Ln(p,e.service),d=await Ln(B,"aws4_request"),b=await Ln(d,O),f=to.BSON.onDemand.ByteUtils.toHex(b);return{Authorization:["AWS4-HMAC-SHA256 Credential="+t.accessKeyId+"/"+D,"SignedHeaders="+h,"Signature="+f].join(", "),"X-Amz-Date":n}}Object.defineProperty(xo,"__esModule",{value:!0});xo.MongoDBAWS=void 0;const $s=pe,on=Q,nn=ne(),wm=Bt,_m=gi,Dm=Ou,Tm=Mo,Bm=Ht,bm=110,e1={useBigInt64:!1,promoteLongs:!0,promoteValues:!0,promoteBuffers:!1,bsonRegExp:!1};class Mm extends wm.AuthProvider{constructor(t){super(),this.credentialFetcher=new _m.AWSSDKCredentialProvider(t)}async auth(t){const{connection:r}=t;if(!t.credentials)throw new on.MongoMissingCredentialsError("AuthContext must provide credentials.");if((0,nn.maxWireVersion)(r)<9)throw new on.MongoCompatibilityError("MONGODB-AWS authentication requires MongoDB version 4.4 or later");t.credentials=await Fm(t.credentials,this.credentialFetcher);const{credentials:n}=t,i=n.username,o=n.password,u=n.mechanismProperties.AWS_SESSION_TOKEN,c=u?{accessKeyId:i,secretAccessKey:o,sessionToken:u}:{accessKeyId:i,secretAccessKey:o},s=n.source,a=await(0,nn.randomBytes)(32),E={saslStart:1,mechanism:"MONGODB-AWS",payload:$s.serialize({r:a,p:bm},e1)},h=await r.command((0,nn.ns)(`${s}.$cmd`),E,void 0),g=$s.deserialize(h.payload.buffer,e1),m=g.h,C=g.s.buffer;if(C.length!==64)throw new on.MongoRuntimeError(`Invalid server nonce length ${C.length}, expected 64`);if(!nn.ByteUtils.equals(C.subarray(0,a.byteLength),a))throw new on.MongoRuntimeError("Server nonce does not begin with client nonce");if(m.length<1||m.length>255||m.indexOf("..")!==-1)throw new on.MongoRuntimeError(`Server returned an invalid host: "${m}"`);const S="Action=GetCallerIdentity&Version=2011-06-15",D=await(0,Dm.aws4Sign)({method:"POST",host:m,region:Rm(g.h),service:"sts",headers:{"Content-Type":"application/x-www-form-urlencoded","Content-Length":S.length,"X-MongoDB-Server-Nonce":nn.ByteUtils.toBase64(C),"X-MongoDB-GS2-CB-Flag":"n"},path:"/",body:S,date:new Date},c),O={a:D.Authorization,d:D["X-Amz-Date"]};u&&(O.t=u);const M={saslContinue:1,conversationId:h.conversationId,payload:$s.serialize(O,e1)};await r.command((0,nn.ns)(`${s}.$cmd`),M,void 0)}}xo.MongoDBAWS=Mm;async function Fm(e,t){function r(i){if(!i.AccessKeyId||!i.SecretAccessKey)throw new on.MongoMissingCredentialsError("Could not obtain temporary MONGODB-AWS credentials");return new Tm.MongoCredentials({username:i.AccessKeyId,password:i.SecretAccessKey,source:e.source,mechanism:Bm.AuthMechanism.MONGODB_AWS,mechanismProperties:{AWS_SESSION_TOKEN:i.Token}})}const n=await t.getCredentials();return r(n)}function Rm(e){const t=e.split(".");return t.length===1||t[1]==="amazonaws"?"us-east-1":t[1]}var t1={},kn={},Zt={},zo={};Object.defineProperty(zo,"__esModule",{value:!0});zo.finishCommandDocument=Nm;zo.startCommandDocument=Im;const ln=pe,Dl=Ht;function Nm(e,t){return t!=null?{saslContinue:1,conversationId:t,payload:new ln.Binary(ln.BSON.serialize({jwt:e}))}:{saslStart:1,mechanism:Dl.AuthMechanism.MONGODB_OIDC,payload:new ln.Binary(ln.BSON.serialize({jwt:e}))}}function Im(e){const t={};return e.username&&(t.n=e.username),{saslStart:1,autoAuthorize:1,mechanism:Dl.AuthMechanism.MONGODB_OIDC,payload:new ln.Binary(ln.BSON.serialize(t))}}Object.defineProperty(Zt,"__esModule",{value:!0});Zt.CallbackWorkflow=Zt.AUTOMATED_TIMEOUT_MS=Zt.HUMAN_TIMEOUT_MS=void 0;const vm=Mc,Pm=Q,$a=ne(),r1=zo;Zt.HUMAN_TIMEOUT_MS=3e5;Zt.AUTOMATED_TIMEOUT_MS=6e4;const Lm=["accessToken","expiresInSeconds","refreshToken"],km="User provided OIDC callbacks must return a valid object with an accessToken.",n1=100;class Um{constructor(t,r){this.cache=t,this.callback=this.withLock(r),this.lastExecutionTime=Date.now()-n1}async speculativeAuth(t,r){if(this.cache.hasAccessToken){const n=this.cache.getAccessToken();t.accessToken=n;const i=(0,r1.finishCommandDocument)(n);return i.db=r.source,{speculativeAuthenticate:i}}return{}}async reauthenticate(t,r){this.cache.hasAccessToken&&(t.accessToken===this.cache.getAccessToken()?(this.cache.removeAccessToken(),delete t.accessToken):t.accessToken=this.cache.getAccessToken()),await this.execute(t,r)}async startAuthentication(t,r,n){let i;return n!=null&&n.speculativeAuthenticate?i=n.speculativeAuthenticate:i=await t.command((0,$a.ns)(r.source),(0,r1.startCommandDocument)(r),void 0),i}async finishAuthentication(t,r,n,i){await t.command((0,$a.ns)(r.source),(0,r1.finishCommandDocument)(n,i),void 0)}async executeAndValidateCallback(t){const r=await this.callback(t);if(jm(r))throw new Pm.MongoMissingCredentialsError(km);return r}withLock(t){let r=Promise.resolve();return async n=>(await r,r=r.catch(()=>null).then(async()=>{const i=Date.now()-this.lastExecutionTime;return i<=n1&&await(0,vm.setTimeout)(n1-i,{signal:n.timeoutContext}),this.lastExecutionTime=Date.now(),await t(n)}),await r)}}Zt.CallbackWorkflow=Um;function jm(e){return e==null||typeof e!="object"||!("accessToken"in e)?!0:!Object.getOwnPropertyNames(e).every(t=>Lm.includes(t))}var ec;function Tl(){if(ec)return kn;ec=1,Object.defineProperty(kn,"__esModule",{value:!0}),kn.AutomatedCallbackWorkflow=void 0;const e=Q,t=Te,r=wu(),n=Zt;class i extends n.CallbackWorkflow{constructor(u,c){super(u,c)}async execute(u,c){if(this.cache.hasAccessToken){const a=this.cache.getAccessToken();u.accessToken||(u.accessToken=a);try{return await this.finishAuthentication(u,c,a)}catch(E){if(E instanceof e.MongoError&&E.code===e.MONGODB_ERROR_CODES.AuthenticationFailed)return this.cache.removeAccessToken(),await this.execute(u,c);throw E}}const s=await this.fetchAccessToken(c);this.cache.put(s),u.accessToken=s.accessToken,await this.finishAuthentication(u,c,s.accessToken)}async fetchAccessToken(u){const c=new AbortController,s={timeoutContext:c.signal,version:r.OIDC_VERSION};u.username&&(s.username=u.username),u.mechanismProperties.TOKEN_RESOURCE&&(s.tokenAudience=u.mechanismProperties.TOKEN_RESOURCE);const a=t.Timeout.expires(n.AUTOMATED_TIMEOUT_MS);try{return await Promise.race([this.executeAndValidateCallback(s),a])}catch(E){throw t.TimeoutError.is(E)?(c.abort(),new e.MongoOIDCError(`OIDC callback timed out after ${n.AUTOMATED_TIMEOUT_MS}ms.`)):E}finally{a.clear()}}}return kn.AutomatedCallbackWorkflow=i,kn}var Vo={};Object.defineProperty(Vo,"__esModule",{value:!0});Vo.callback=void 0;const tc=Eu,p1=Q,xm=ne(),zm=Object.freeze({Metadata:"true",Accept:"application/json"}),Vm="Azure endpoint did not return a value with only access_token and expires_in properties",Wm="TOKEN_RESOURCE must be set in the auth mechanism properties when ENVIRONMENT is azure.",Gm=async e=>{const t=e.tokenAudience,r=e.username;if(!t)throw new p1.MongoAzureError(Wm);const n=await qm(t,r);if(!Hm(n))throw new p1.MongoAzureError(Vm);return n};Vo.callback=Gm;async function qm(e,t){const r=new URL(tc.AZURE_BASE_URL);(0,tc.addAzureParams)(r,e,t);const n=await(0,xm.get)(r,{headers:zm});if(n.status!==200)throw new p1.MongoAzureError(`Status code ${n.status} returned from the Azure endpoint. Response body: ${n.body}`);const i=JSON.parse(n.body);return{accessToken:i.access_token,expiresInSeconds:Number(i.expires_in)}}function Hm(e){return e==null||typeof e!="object"?!1:"accessToken"in e&&typeof e.accessToken=="string"&&"expiresInSeconds"in e&&typeof e.expiresInSeconds=="number"}var Wo={};Object.defineProperty(Wo,"__esModule",{value:!0});Wo.callback=void 0;const Bl=Q,Km=ne(),Ym="http://metadata/computeMetadata/v1/instance/service-accounts/default/identity",Xm=Object.freeze({"Metadata-Flavor":"Google"}),Jm="TOKEN_RESOURCE must be set in the auth mechanism properties when ENVIRONMENT is gcp.",Qm=async e=>{const t=e.tokenAudience;if(!t)throw new Bl.MongoGCPError(Jm);return await Zm(t)};Wo.callback=Qm;async function Zm(e){const t=new URL(Ym);t.searchParams.append("audience",e);const r=await(0,Km.get)(t,{headers:Xm});if(r.status!==200)throw new Bl.MongoGCPError(`Status code ${r.status} returned from the GCP endpoint. Response body: ${r.body}`);return{accessToken:r.body}}var Go={};Object.defineProperty(Go,"__esModule",{value:!0});Go.callback=void 0;const $m=Nc,Li=Ar,eE="/var/run/secrets/kubernetes.io/serviceaccount/token",rc="AZURE_FEDERATED_TOKEN_FILE",nc="AWS_WEB_IDENTITY_TOKEN_FILE",tE=async()=>{let e;return Li.env[rc]?e=Li.env[rc]:Li.env[nc]?e=Li.env[nc]:e=eE,{accessToken:await(0,$m.readFile)(e,"utf8")}};Go.callback=tE;var Ci={};Object.defineProperty(Ci,"__esModule",{value:!0});Ci.TokenCache=void 0;const rE=Q;class i1 extends rE.MongoDriverError{}class nE{get hasAccessToken(){return!!this.accessToken}get hasRefreshToken(){return!!this.refreshToken}get hasIdpInfo(){return!!this.idpInfo}getAccessToken(){if(!this.accessToken)throw new i1("Attempted to get an access token when none exists.");return this.accessToken}getRefreshToken(){if(!this.refreshToken)throw new i1("Attempted to get a refresh token when none exists.");return this.refreshToken}getIdpInfo(){if(!this.idpInfo)throw new i1("Attempted to get IDP information when none exists.");return this.idpInfo}put(t,r){this.accessToken=t.accessToken,this.refreshToken=t.refreshToken,this.expiresInSeconds=t.expiresInSeconds,r&&(this.idpInfo=r)}removeAccessToken(){this.accessToken=void 0}removeRefreshToken(){this.refreshToken=void 0}}Ci.TokenCache=nE;var qo={};Object.defineProperty(qo,"__esModule",{value:!0});qo.callback=void 0;const iE=_1,oE=Ar,sE=Q,uE="OIDC_TOKEN_FILE must be set in the environment.",aE=async()=>{const e=oE.env.OIDC_TOKEN_FILE;if(!e)throw new sE.MongoAWSError(uE);return{accessToken:await iE.promises.readFile(e,"utf8")}};qo.callback=aE;var ic;function wu(){return ic||(ic=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.MongoDBOIDC=e.OIDC_WORKFLOWS=e.OIDC_VERSION=void 0;const t=Q,r=Bt,n=Tl(),i=Vo,o=Wo,u=Go,c=Ci,s=qo,a="AuthContext must provide credentials.";e.OIDC_VERSION=1,e.OIDC_WORKFLOWS=new Map,e.OIDC_WORKFLOWS.set("test",()=>new n.AutomatedCallbackWorkflow(new c.TokenCache,s.callback)),e.OIDC_WORKFLOWS.set("azure",()=>new n.AutomatedCallbackWorkflow(new c.TokenCache,i.callback)),e.OIDC_WORKFLOWS.set("gcp",()=>new n.AutomatedCallbackWorkflow(new c.TokenCache,o.callback)),e.OIDC_WORKFLOWS.set("k8s",()=>new n.AutomatedCallbackWorkflow(new c.TokenCache,u.callback));class E extends r.AuthProvider{constructor(m){if(super(),!m)throw new t.MongoInvalidArgumentError("No workflow provided to the OIDC auth provider.");this.workflow=m}async auth(m){var M;const{connection:C,reauthenticating:S,response:D}=m;if((M=D==null?void 0:D.speculativeAuthenticate)!=null&&M.done&&!S)return;const O=h(m);S?await this.workflow.reauthenticate(C,O):await this.workflow.execute(C,O,D)}async prepare(m,C){const{connection:S}=C,D=h(C),O=await this.workflow.speculativeAuth(S,D);return{...m,...O}}}e.MongoDBOIDC=E;function h(g){const{credentials:m}=g;if(!m)throw new t.MongoMissingCredentialsError(a);return m}}(t1)),t1}var Ho={};Object.defineProperty(Ho,"__esModule",{value:!0});Ho.HumanCallbackWorkflow=void 0;const cE=pe,Un=Q,oc=Te,lE=wu(),o1=Zt;class hE extends o1.CallbackWorkflow{constructor(t,r){super(t,r)}async execute(t,r){if(this.cache.hasAccessToken){const c=this.cache.getAccessToken();t.accessToken=c;try{return await this.finishAuthentication(t,r,c)}catch(s){if(s instanceof Un.MongoError&&s.code===Un.MONGODB_ERROR_CODES.AuthenticationFailed)return this.cache.removeAccessToken(),delete t.accessToken,await this.execute(t,r);throw s}}if(this.cache.hasRefreshToken){const c=this.cache.getRefreshToken(),s=await this.fetchAccessToken(this.cache.getIdpInfo(),r,c);this.cache.put(s),t.accessToken=s.accessToken;try{return await this.finishAuthentication(t,r,s.accessToken)}catch(a){if(a instanceof Un.MongoError&&a.code===Un.MONGODB_ERROR_CODES.AuthenticationFailed)return this.cache.removeRefreshToken(),delete t.accessToken,await this.execute(t,r);throw a}}const n=await this.startAuthentication(t,r),i=n.conversationId,o=cE.BSON.deserialize(n.payload.buffer),u=await this.fetchAccessToken(o,r);return this.cache.put(u,o),t.accessToken=u.accessToken,await this.finishAuthentication(t,r,u.accessToken,i)}async fetchAccessToken(t,r,n){const i=new AbortController,o={timeoutContext:i.signal,version:lE.OIDC_VERSION,idpInfo:t};r.username&&(o.username=r.username),n&&(o.refreshToken=n);const u=oc.Timeout.expires(o1.HUMAN_TIMEOUT_MS);try{return await Promise.race([this.executeAndValidateCallback(o),u])}catch(c){throw oc.TimeoutError.is(c)?(i.abort(),new Un.MongoOIDCError(`OIDC callback timed out after ${o1.HUMAN_TIMEOUT_MS}ms.`)):c}finally{u.clear()}}}Ho.HumanCallbackWorkflow=hE;var Ko={};Object.defineProperty(Ko,"__esModule",{value:!0});Ko.Plain=void 0;const dE=pe,fE=Q,mE=ne(),EE=Bt;class gE extends EE.AuthProvider{async auth(t){const{connection:r,credentials:n}=t;if(!n)throw new fE.MongoMissingCredentialsError("AuthContext must provide credentials.");const{username:i,password:o}=n,c={saslStart:1,mechanism:"PLAIN",payload:new dE.Binary(Buffer.from(`\0${i}\0${o}`)),autoAuthorize:1};await r.command((0,mE.ns)("$external.$cmd"),c,void 0)}}Ko.Plain=gE;var fn={};const sc=e=>e.codePointAt(0),AE=e=>e[0],pE=e=>e[e.length-1];function uc(e){const t=[],r=e.length;for(let n=0;n<r;n+=1){const i=e.charCodeAt(n);if(i>=55296&&i<=56319&&r>n+1){const o=e.charCodeAt(n+1);if(o>=56320&&o<=57343){t.push((i-55296)*1024+o-56320+65536),n+=1;continue}}t.push(i)}return t}function Qn({unassigned_code_points:e,commonly_mapped_to_nothing:t,non_ASCII_space_characters:r,prohibited_characters:n,bidirectional_r_al:i,bidirectional_l:o},u,c={}){const s=r,a=t;if(typeof u!="string")throw new TypeError("Expected string.");if(u.length===0)return"";const E=uc(u).map(M=>s.get(M)?32:M).filter(M=>!a.get(M)),h=String.fromCodePoint.apply(null,E).normalize("NFKC"),g=uc(h);if(g.some(M=>n.get(M)))throw new Error("Prohibited character, see https://tools.ietf.org/html/rfc4013#section-2.3");if(c.allowUnassigned!==!0&&g.some(p=>e.get(p)))throw new Error("Unassigned code point, see https://tools.ietf.org/html/rfc4013#section-2.5");const C=g.some(M=>i.get(M)),S=g.some(M=>o.get(M));if(C&&S)throw new Error("String must not contain RandALCat and LCat at the same time, see https://tools.ietf.org/html/rfc3454#section-6");const D=i.get(sc(AE(h))),O=i.get(sc(pE(h)));if(C&&!(D&&O))throw new Error("Bidirectional RandALCat character must be the first and the last character of the string, see https://tools.ietf.org/html/rfc3454#section-6");return h}Qn.saslprep=Qn;Qn.default=Qn;var CE=Qn,_u={},SE=rr;function rr(e,t){if(!(this instanceof rr))return new rr(e,t);this.length=0,this.updates=[],this.path=new Uint16Array(4),this.pages=new Array(32768),this.maxPages=this.pages.length,this.level=0,this.pageSize=e||1024,this.deduplicate=t?t.deduplicate:null,this.zeros=this.deduplicate?Yo(this.deduplicate.length):null}rr.prototype.updated=function(e){for(;this.deduplicate&&e.buffer[e.deduplicate]===this.deduplicate[e.deduplicate];)if(e.deduplicate++,e.deduplicate===this.deduplicate.length){e.deduplicate=0,e.buffer.equals&&e.buffer.equals(this.deduplicate)&&(e.buffer=this.deduplicate);break}e.updated||!this.updates||(e.updated=!0,this.updates.push(e))};rr.prototype.lastUpdate=function(){if(!this.updates||!this.updates.length)return null;var e=this.updates.pop();return e.updated=!1,e};rr.prototype._array=function(e,t){if(e>=this.maxPages){if(t)return;yE(this,e)}_E(e,this.path);for(var r=this.pages,n=this.level;n>0;n--){var i=this.path[n],o=r[i];if(!o){if(t)return;o=r[i]=new Array(32768)}r=o}return r};rr.prototype.get=function(e,t){var r=this._array(e,t),n=this.path[0],i=r&&r[n];return!i&&!t&&(i=r[n]=new bl(e,Yo(this.pageSize)),e>=this.length&&(this.length=e+1)),i&&i.buffer===this.deduplicate&&this.deduplicate&&!t&&(i.buffer=wE(i.buffer),i.deduplicate=0),i};rr.prototype.set=function(e,t){var r=this._array(e,!1),n=this.path[0];if(e>=this.length&&(this.length=e+1),!t||this.zeros&&t.equals&&t.equals(this.zeros)){r[n]=void 0;return}this.deduplicate&&t.equals&&t.equals(this.deduplicate)&&(t=this.deduplicate);var i=r[n],o=OE(t,this.pageSize);i?i.buffer=o:r[n]=new bl(e,o)};rr.prototype.toBuffer=function(){for(var e=new Array(this.length),t=Yo(this.pageSize),r=0;r<e.length;)for(var n=this._array(r,!0),i=0;i<32768&&r<e.length;i++)e[r++]=n&&n[i]?n[i].buffer:t;return Buffer.concat(e)};function yE(e,t){for(;e.maxPages<t;){var r=e.pages;e.pages=new Array(32768),e.pages[0]=r,e.level++,e.maxPages*=32768}}function OE(e,t){if(e.length===t)return e;if(e.length>t)return e.slice(0,t);var r=Yo(t);return e.copy(r),r}function Yo(e){if(Buffer.alloc)return Buffer.alloc(e);var t=new Buffer(e);return t.fill(0),t}function wE(e){var t=Buffer.allocUnsafe?Buffer.allocUnsafe(e.length):new Buffer(e.length);return e.copy(t),t}function bl(e,t){this.offset=e*t.length,this.buffer=t,this.updated=!1,this.deduplicate=0}function _E(e,t){e=(e-(t[0]=e&32767))/32768,e=(e-(t[1]=e&32767))/32768,t[3]=(e-(t[2]=e&32767))/32768&32767}var DE=SE,TE=gr;function gr(e){if(!(this instanceof gr))return new gr(e);if(e||(e={}),Buffer.isBuffer(e)&&(e={buffer:e}),this.pageOffset=e.pageOffset||0,this.pageSize=e.pageSize||1024,this.pages=e.pages||DE(this.pageSize),this.byteLength=this.pages.length*this.pageSize,this.length=8*this.byteLength,!bE(this.pageSize))throw new Error("The page size should be a power of two");if(this._trackUpdates=!!e.trackUpdates,this._pageMask=this.pageSize-1,e.buffer){for(var t=0;t<e.buffer.length;t+=this.pageSize)this.pages.set(t/this.pageSize,e.buffer.slice(t,t+this.pageSize));this.byteLength=e.buffer.length,this.length=8*this.byteLength}}gr.prototype.get=function(e){var t=e&7,r=(e-t)/8;return!!(this.getByte(r)&128>>t)};gr.prototype.getByte=function(e){var t=e&this._pageMask,r=(e-t)/this.pageSize,n=this.pages.get(r,!0);return n?n.buffer[t+this.pageOffset]:0};gr.prototype.set=function(e,t){var r=e&7,n=(e-r)/8,i=this.getByte(n);return this.setByte(n,t?i|128>>r:i&(255^128>>r))};gr.prototype.toBuffer=function(){for(var e=BE(this.pages.length*this.pageSize),t=0;t<this.pages.length;t++){var r=this.pages.get(t,!0),n=t*this.pageSize;r&&r.buffer.copy(e,n,this.pageOffset,this.pageOffset+this.pageSize)}return e};gr.prototype.setByte=function(e,t){var r=e&this._pageMask,n=(e-r)/this.pageSize,i=this.pages.get(n,!1);return r+=this.pageOffset,i.buffer[r]===t?!1:(i.buffer[r]=t,e>=this.byteLength&&(this.byteLength=e+1,this.length=this.byteLength*8),this._trackUpdates&&this.pages.updated(i),!0)};function BE(e){if(Buffer.alloc)return Buffer.alloc(e);var t=new Buffer(e);return t.fill(0),t}function bE(e){return!(e&e-1)}var ME=Ye.commonjsGlobal&&Ye.commonjsGlobal.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(_u,"__esModule",{value:!0});_u.createMemoryCodePoints=RE;const FE=ME(TE);function RE(e){let t=0;function r(){const a=e.readUInt32BE(t);t+=4;const E=e.slice(t,t+a);return t+=a,(0,FE.default)({buffer:E})}const n=r(),i=r(),o=r(),u=r(),c=r(),s=r();return{unassigned_code_points:n,commonly_mapped_to_nothing:i,non_ASCII_space_characters:o,prohibited_characters:u,bidirectional_r_al:c,bidirectional_l:s}}var Du={};Object.defineProperty(Du,"__esModule",{value:!0});const NE=Rc;Du.default=(0,NE.gunzipSync)(Buffer.from("H4sIAAAAAAACA+3dTYgcaRkA4LemO9Mhxm0FITnE9Cwr4jHgwgZ22B6YywqCJ0HQg5CL4sGTuOjCtGSF4CkHEW856MlTQHD3EJnWkU0Owh5VxE3LHlYQdNxd2U6mU59UV/d09fw4M2EySSXPAzNdP1/9fX/99bzVNZEN4jisRDulVFnQmLxm1aXF9Id/2/xMxNJ4XZlg576yuYlGt9gupV6xoFf8jhu9YvulVrFlp5XSx+lfvYhORGPXvqIRWSxERKtIm8bKFd10WNfKDS5Fo9jJWrq2+M2IlW+8uHgl/+BsROfPF4v5L7148Ur68Sha6dqZpYiVVy8tvLCWXo80Sf/lS89dGX2wHGvpzoXVn75/YWH5wmqe8uika82ViJXTy83Ve2k5Urozm38wm4/ls6t5uT6yfsTSJ7J3T0VKt8c5ExEXI8aFkH729c3eT+7EC6ca8cVULZUiYacX0R5PNWNxlh9L1y90q5kyzrpyy+9WcvOV6URntqw7La9sNVstXyczWVaWYbaaTYqzOHpr7pyiNT3/YzKuT63Z/FqKZlFTiuXtFM2vVOtIq7jiyKJbWZaOWD0euz0yoV2Z7kY0xq2x0YhfzVpmM5px9nTEH7JZ0ot5u39p0ma75Z472/s/H+2yr2inYyuq7fMvJivH2rM72N/Z3lyL31F2b1ya1P0zn816k2KP6JU9UzseucdQH5YqVeH/lFajSN2udg+TLJ9rksNxlvV2lki19rXKI43TPLejFu4ov7k3nMbhyhfY3Xb37f8BAGCf0eMTOH5szf154KmnNgKcnLb+Fzi2AfXktbN7fJelwTAiO/W5uQ2KINXRYu+znqo/WTAdLadURHmy3qciazd3bra4T3w16/f7t7Ms9U5gfJu10955sx1r3vmhBAAAAAAAgId20J1iZbDowNvIjuH427Gr5l/eiC+8OplZON8sVjx/qr9y+Pj+YRItT+NqAM+kkZs3AAAAAID6yfx1FwCAI97/dCh1/ub6SA0AAAAAAAAAgNoT/wcAAAAAAACA+hP/BwAAAAAAAID6E/8HAAAAAAAAgPoT/wcAAAAAAACA+hP/BwAAAAAAAID6E/8HAAAAAAAAgPoT/wcAAAAAAACA+hP/BwAAAAAAAID6E/8HAAAAAAAAgPoT/wcAAAAAAACA+hutp5SiQpYAAAAAAAAAQO2MIpZiT804flnAE2fhwjOeAZXr76kOAAAAAAAA8FjNf4N/l0NE3U/vuVQskLpSd4/Yh2xu9xTu0tFeeNYsLI2f/VMdNxTzj6Je9E/+6pp6Nn3awW3A54goe4Bss6v+PGsjQGMAAAAAAOBp5XEgwH6e7J7rwEQHRb/XvAMAAAAAAAA8yzoDeQDwVGjIAgAAAAAAAACoPfF/AAAAAAAAAKg/8X8AAAAAAAAAqD/xfwAAAAAAAACoP/F/AAAAAAAAAKg/8X8AAAAAAAAAqD/xfwAAAAAAAACoP/F/AAAAAAAAAKg/8X8AAAAAAAAAqD/xfwAAAAAAAACoP/F/AAAAAAAAAKg/8X8AAAAAAAAAqL/GSkSkClkCAAAAAAAAALXTSAAAAAAAAABA3Y1kAQAAAAAAAADUX8RSXZ9dsHC9+M8Fg2Ex/em1lAZpEBGttcrVjZqLEa+k0XpKw9mG4zWx4ukPUMhkAQAAAAAAABzBqbSe3//rXOS9HxGdo4TqR2XkutCdBu+LaPZw/lBbO7cbHnh2C7N7AIo4evEznllqLqWUp/LnYOtpM2bnOH66wI1+9GO4sOuISwv/TOlumu56FDv3NZhc4mR9v7zYIrafr40j/Cccvj9Xns3t3mu99E7qxUv3bqS0/ouNH/08++RGemfQ+nsx/5uNXsQPGulynPvv3ZTW37zd+1ovrqaYpP/122X6Xpx779Z3zr/3YOPKW1lkaRDf31pPaf3j/msRsVGkL+d/f+/m4sJsPm1cfSsr16e8m9Ldj/KsnyIuR3nXw83Is3EhxLd/2V773ks3m/cj/THKUummdP9qKhIOImuOU0Xjwb3y+oqt735rpTetVbF9n8R4x9crRfO77TKqVOZpDclv5bfK18lMnk+q0K18UpxF/RrGXE0Zxtqx3tWSj+vxbL4XaasfKb0dRbtLW73JsfPGg177H+OmGKlfvS1msllt7JEJm9XOJqXR+Fkfo1H66uy5H1v3Xx5+uJmGLw9jro2u7Loj4PnuR6+f+e3d261+eazNhzrL7X83MohoHpS4PddV8ki1it61//pw1g7z6p1U/26Nm2llST57B5rUvuG0XqSU/rPd7jYrqWcbd+beJQ77BgPMDwn37/8BAGCf0eMTOH4cPlufv9VGgJOzqf8Fjm1APXkd7B7f5dF57GPMaWy/MTvjvNvtXj6h8W2+GXvnzXaseeeHEgAAAAAAAB7aQXeKlcGiadBoEOeLb2dtpGOL2MyOtf391a3P/zD96c3JzIP3t4oV797vrh8+vn+YRL5bBuj/AQAAAABqJvfHXQAAHkX82zfXAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACeAgkAAAAAAAAAqLuRLAAAAAAAAACA2hv9D1iu/VAYaAYA","base64"));var Ml=Ye.commonjsGlobal&&Ye.commonjsGlobal.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};const IE=Ml(CE),vE=_u,PE=Ml(Du),LE=(0,vE.createMemoryCodePoints)(PE.default);function Zn(e,t){return(0,IE.default)(LE,e,t)}Zn.saslprep=Zn;Zn.default=Zn;var kE=Zn;Object.defineProperty(fn,"__esModule",{value:!0});fn.ScramSHA256=fn.ScramSHA1=void 0;const UE=kE,Lr=bc,C1=pe,Rt=Q,ro=ne(),jE=Bt,ac=Ht;class Fl extends jE.AuthProvider{constructor(t){super(),this.cryptoMethod=t||"sha1"}async prepare(t,r){const n=this.cryptoMethod,i=r.credentials;if(!i)throw new Rt.MongoMissingCredentialsError("AuthContext must provide credentials.");const o=await(0,ro.randomBytes)(24);return r.nonce=o,{...t,speculativeAuthenticate:{...Il(n,i,o),db:i.source}}}async auth(t){const{reauthenticating:r,response:n}=t;return n!=null&&n.speculativeAuthenticate&&!r?await vl(this.cryptoMethod,n.speculativeAuthenticate,t):await xE(this.cryptoMethod,t)}}function Rl(e){return e.replace("=","=3D").replace(",","=2C")}function Nl(e,t){return Buffer.concat([Buffer.from("n=","utf8"),Buffer.from(e,"utf8"),Buffer.from(",r=","utf8"),Buffer.from(t.toString("base64"),"utf8")])}function Il(e,t,r){const n=Rl(t.username);return{saslStart:1,mechanism:e==="sha1"?ac.AuthMechanism.MONGODB_SCRAM_SHA1:ac.AuthMechanism.MONGODB_SCRAM_SHA256,payload:new C1.Binary(Buffer.concat([Buffer.from("n,,","utf8"),Nl(n,r)])),autoAuthorize:1,options:{skipEmptyExchange:!0}}}async function xE(e,t){const{connection:r,credentials:n}=t;if(!n)throw new Rt.MongoMissingCredentialsError("AuthContext must provide credentials.");if(!t.nonce)throw new Rt.MongoInvalidArgumentError("AuthContext must contain a valid nonce property");const i=t.nonce,o=n.source,u=Il(e,n,i),c=await r.command((0,ro.ns)(`${o}.$cmd`),u,void 0);await vl(e,c,t)}async function vl(e,t,r){const n=r.connection,i=r.credentials;if(!i)throw new Rt.MongoMissingCredentialsError("AuthContext must provide credentials.");if(!r.nonce)throw new Rt.MongoInvalidArgumentError("Unable to continue SCRAM without valid nonce");const o=r.nonce,u=i.source,c=Rl(i.username),s=i.password,a=e==="sha256"?(0,UE.saslprep)(s):zE(c,s),E=Buffer.isBuffer(t.payload)?new C1.Binary(t.payload):t.payload,h=cc(E),g=parseInt(h.i,10);if(g&&g<4096)throw new Rt.MongoRuntimeError(`Server returned an invalid iteration count ${g}`);const m=h.s,C=h.r;if(C.startsWith("nonce"))throw new Rt.MongoRuntimeError(`Server returned an invalid nonce: ${C}`);const S=`c=biws,r=${C}`,D=HE(a,Buffer.from(m,"base64"),g,e),O=ki(e,D,"Client Key"),M=ki(e,D,"Server Key"),p=WE(e,O),B=[Nl(c,o),E.toString("utf8"),S].join(","),d=ki(e,p,B),b=`p=${VE(O,d)}`,f=[S,b].join(","),l=ki(e,M,B),w={saslContinue:1,conversationId:t.conversationId,payload:new C1.Binary(Buffer.from(f))},T=await n.command((0,ro.ns)(`${u}.$cmd`),w,void 0),_=cc(T.payload);if(!KE(Buffer.from(_.v,"base64"),l))throw new Rt.MongoRuntimeError("Server returned an invalid signature");if(T.done!==!1)return;const A={saslContinue:1,conversationId:T.conversationId,payload:Buffer.alloc(0)};await n.command((0,ro.ns)(`${u}.$cmd`),A,void 0)}function cc(e){const t=e.toString("utf8"),r={},n=t.split(",");for(let i=0;i<n.length;i++){const o=(n[i].match(/^([^=]*)=(.*)$/)??[]).slice(1);r[o[0]]=o[1]}return r}function zE(e,t){if(typeof e!="string")throw new Rt.MongoInvalidArgumentError("Username must be a string");if(typeof t!="string")throw new Rt.MongoInvalidArgumentError("Password must be a string");if(t.length===0)throw new Rt.MongoInvalidArgumentError("Password cannot be empty");let r;try{r=Lr.createHash("md5")}catch(n){throw Lr.getFips()?new Error("Auth mechanism SCRAM-SHA-1 is not supported in FIPS mode"):n}return r.update(`${e}:mongo:${t}`,"utf8"),r.digest("hex")}function VE(e,t){Buffer.isBuffer(e)||(e=Buffer.from(e)),Buffer.isBuffer(t)||(t=Buffer.from(t));const r=Math.max(e.length,t.length),n=[];for(let i=0;i<r;i+=1)n.push(e[i]^t[i]);return Buffer.from(n).toString("base64")}function WE(e,t){return Lr.createHash(e).update(t).digest()}function ki(e,t,r){return Lr.createHmac(e,t).update(r).digest()}let Hi={},S1=0;function GE(){Hi={},S1=0}const qE={sha256:32,sha1:20};function HE(e,t,r,n){const i=[e,t.toString("base64"),r].join("_");if(Hi[i]!=null)return Hi[i];const o=Lr.pbkdf2Sync(e,t,r,qE[n],n);return S1>=200&&GE(),Hi[i]=o,S1+=1,o}function KE(e,t){if(e.length!==t.length)return!1;if(typeof Lr.timingSafeEqual=="function")return Lr.timingSafeEqual(e,t);let r=0;for(let n=0;n<e.length;n++)r|=e[n]^t[n];return r===0}class YE extends Fl{constructor(){super("sha1")}}fn.ScramSHA1=YE;class XE extends Fl{constructor(){super("sha256")}}fn.ScramSHA256=XE;var Xo={};Object.defineProperty(Xo,"__esModule",{value:!0});Xo.X509=void 0;const lc=Q,JE=ne(),QE=Bt;class ZE extends QE.AuthProvider{async prepare(t,r){const{credentials:n}=r;if(!n)throw new lc.MongoMissingCredentialsError("AuthContext must provide credentials.");return{...t,speculativeAuthenticate:hc(n)}}async auth(t){const r=t.connection,n=t.credentials;if(!n)throw new lc.MongoMissingCredentialsError("AuthContext must provide credentials.");const i=t.response;i!=null&&i.speculativeAuthenticate||await r.command((0,JE.ns)("$external.$cmd"),hc(n),void 0)}}Xo.X509=ZE;function hc(e){const t={authenticate:1,mechanism:"MONGODB-X509"};return e.username&&(t.user=e.username),t}Object.defineProperty(pi,"__esModule",{value:!0});pi.MongoClientAuthProviders=void 0;const $E=Fo,e4=xo,Pl=wu(),t4=Tl(),r4=Ho,dc=Ci,n4=Ko,Dr=Ht,fc=fn,i4=Xo,Ll=Q,o4=new Map([[Dr.AuthMechanism.MONGODB_AWS,({AWS_CREDENTIAL_PROVIDER:e})=>new e4.MongoDBAWS(e)],[Dr.AuthMechanism.MONGODB_GSSAPI,()=>new $E.GSSAPI],[Dr.AuthMechanism.MONGODB_OIDC,e=>new Pl.MongoDBOIDC(u4(e))],[Dr.AuthMechanism.MONGODB_PLAIN,()=>new n4.Plain],[Dr.AuthMechanism.MONGODB_SCRAM_SHA1,()=>new fc.ScramSHA1],[Dr.AuthMechanism.MONGODB_SCRAM_SHA256,()=>new fc.ScramSHA256],[Dr.AuthMechanism.MONGODB_X509,()=>new i4.X509]]);class s4{constructor(){this.existingProviders=new Map}getOrCreateProvider(t,r){const n=this.existingProviders.get(t);if(n)return n;const i=o4.get(t);if(!i)throw new Ll.MongoInvalidArgumentError(`authMechanism ${t} not supported`);const o=i(r);return this.existingProviders.set(t,o),o}}pi.MongoClientAuthProviders=s4;function u4(e){var t;if(e.OIDC_HUMAN_CALLBACK)return new r4.HumanCallbackWorkflow(new dc.TokenCache,e.OIDC_HUMAN_CALLBACK);if(e.OIDC_CALLBACK)return new t4.AutomatedCallbackWorkflow(new dc.TokenCache,e.OIDC_CALLBACK);{const r=e.ENVIRONMENT,n=(t=Pl.OIDC_WORKFLOWS.get(r))==null?void 0:t();if(!n)throw new Ll.MongoInvalidArgumentError(`Could not load workflow for environment ${e.ENVIRONMENT}`);return n}}var jn={},Jo={},Si={};Object.defineProperty(Si,"__esModule",{value:!0});Si.ClientBulkWriteOperation=void 0;const a4=De(),c4=ne(),l4=Ie,Tr=Me;class kl extends l4.CommandOperation{get commandName(){return"bulkWrite"}constructor(t,r){super(void 0,r),this.SERVER_COMMAND_RESPONSE_TYPE=a4.ClientBulkWriteCursorResponse,this.commandBuilder=t,this.options=r,this.ns=new c4.MongoDBNamespace("admin","$cmd")}resetBatch(){return this.commandBuilder.resetBatch()}get canRetryWrite(){return this.commandBuilder.isBatchRetryable}handleOk(t){return t}buildCommandDocument(t,r){const n=this.commandBuilder.buildBatch(t.description.maxMessageSizeBytes,t.description.maxWriteBatchSize,t.description.maxBsonObjectSize);return this.canRetryWrite||(this.options.willRetryWrite=!1),n}}Si.ClientBulkWriteOperation=kl;(0,Tr.defineAspects)(kl,[Tr.Aspect.WRITE_OPERATION,Tr.Aspect.SKIP_COLLATION,Tr.Aspect.CURSOR_CREATING,Tr.Aspect.RETRYABLE,Tr.Aspect.COMMAND_BATCHING,Tr.Aspect.SUPPORTS_RAW_DATA]);Object.defineProperty(Jo,"__esModule",{value:!0});Jo.ClientBulkWriteCursor=void 0;const h4=Si,d4=qe,mc=ne(),f4=rt;class Tu extends f4.AbstractCursor{constructor(t,r,n={}){super(t,new mc.MongoDBNamespace("admin","$cmd"),n),this.commandBuilder=r,this.clientBulkWriteOptions=n}get response(){return this.cursorResponse?this.cursorResponse:null}get operations(){return this.commandBuilder.lastOperations}clone(){const t=(0,mc.mergeOptions)({},this.clientBulkWriteOptions);return delete t.session,new Tu(this.client,this.commandBuilder,{...t})}async _initialize(t){const r=new h4.ClientBulkWriteOperation(this.commandBuilder,{...this.clientBulkWriteOptions,...this.cursorOptions,session:t}),n=await(0,d4.executeOperation)(this.client,r,this.timeoutContext);return this.cursorResponse=n,{server:r.server,session:t,response:n}}}Jo.ClientBulkWriteCursor=Tu;var Ul={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.buildReplaceOneOperation=e.buildUpdateManyOperation=e.buildUpdateOneOperation=e.buildDeleteManyOperation=e.buildDeleteOneOperation=e.buildInsertOneOperation=e.ClientBulkWriteCommandBuilder=void 0,e.buildOperation=M;const t=pe,r=vo(),n=Q,i=Wr,o=ne(),u=1e3;class c{constructor(B,d,b){this.models=B,this.options=d,this.pkFactory=b??o.DEFAULT_PK_FACTORY,this.currentModelIndex=0,this.previousModelIndex=0,this.lastOperations=[],this.isBatchRetryable=!0}get errorsOnly(){return"verboseResults"in this.options?!this.options.verboseResults:!0}hasNextBatch(){return this.currentModelIndex<this.models.length}resetBatch(){return this.currentModelIndex=this.previousModelIndex,!0}buildBatch(B,d,b){this.isBatchRetryable=!0;let f=0,l=0;const w=this.baseCommand(),T=new Map;for(this.previousModelIndex=this.currentModelIndex;this.currentModelIndex<this.models.length;){const _=this.models[this.currentModelIndex],A=_.namespace,y=T.get(A);if((_.name==="deleteMany"||_.name==="updateMany")&&(this.isBatchRetryable=!1),y!=null){const F=M(_,y,this.pkFactory,this.options);let R;try{R=t.BSON.serialize(F)}catch(v){throw new n.MongoInvalidArgumentError("Could not serialize operation to BSON",{cause:v})}if(s("ops",R,b),f+R.length<B&&w.ops.documents.length<d)f=u+w.ops.push(F,R),this.currentModelIndex++;else break}else{T.set(A,l);const F={ns:A},R=M(_,l,this.pkFactory,this.options);let v,J;try{v=t.BSON.serialize(F),J=t.BSON.serialize(R)}catch(I){throw new n.MongoInvalidArgumentError("Could not serialize ns info to BSON",{cause:I})}if(s("nsInfo",v,b),s("ops",J,b),f+v.length+J.length<B&&w.ops.documents.length<d)f=u+w.nsInfo.push(F,v)+w.ops.push(R,J),l++,this.currentModelIndex++;else break}}return this.lastOperations=w.ops.documents,w}baseCommand(){const B={bulkWrite:1,errorsOnly:this.errorsOnly,ordered:this.options.ordered??!0,ops:new r.DocumentSequence("ops"),nsInfo:new r.DocumentSequence("nsInfo")};return this.options.bypassDocumentValidation!=null&&(B.bypassDocumentValidation=this.options.bypassDocumentValidation),this.options.let&&(B.let=this.options.let),this.options.comment!==void 0&&(B.comment=this.options.comment),B}}e.ClientBulkWriteCommandBuilder=c;function s(p,B,d){if(B.length>d)throw new n.MongoInvalidArgumentError(`Client bulk write operation ${p} of length ${B.length} exceeds the max bson object size of ${d}`)}const a=(p,B,d)=>{const b={insert:B,document:p.document};return b.document._id=p.document._id??d.createPk(),b};e.buildInsertOneOperation=a;const E=(p,B)=>g(p,B,!1);e.buildDeleteOneOperation=E;const h=(p,B)=>g(p,B,!0);e.buildDeleteManyOperation=h;function g(p,B,d){const b={delete:B,multi:d,filter:p.filter};return p.hint&&(b.hint=p.hint),p.collation&&(b.collation=p.collation),b}const m=(p,B,d)=>D(p,B,!1,d);e.buildUpdateOneOperation=m;const C=(p,B,d)=>D(p,B,!0,d);e.buildUpdateManyOperation=C;function S(p,B){if(!(0,o.hasAtomicOperators)(p,B))throw new n.MongoAPIError("Client bulk write update models must only contain atomic modifiers (start with $) and must not be empty.")}function D(p,B,d,b){S(p.update,b);const f={update:B,multi:d,filter:p.filter,updateMods:p.update};return p.hint&&(f.hint=p.hint),p.upsert&&(f.upsert=p.upsert),p.arrayFilters&&(f.arrayFilters=p.arrayFilters),p.collation&&(f.collation=p.collation),!d&&"sort"in p&&p.sort!=null&&(f.sort=(0,i.formatSort)(p.sort)),f}const O=(p,B)=>{if((0,o.hasAtomicOperators)(p.replacement))throw new n.MongoAPIError("Client bulk write replace models must not contain atomic modifiers (start with $) and must not be empty.");const d={update:B,multi:!1,filter:p.filter,updateMods:p.replacement};return p.hint&&(d.hint=p.hint),p.upsert&&(d.upsert=p.upsert),p.collation&&(d.collation=p.collation),p.sort!=null&&(d.sort=(0,i.formatSort)(p.sort)),d};e.buildReplaceOneOperation=O;function M(p,B,d,b){switch(p.name){case"insertOne":return(0,e.buildInsertOneOperation)(p,B,d);case"deleteOne":return(0,e.buildDeleteOneOperation)(p,B);case"deleteMany":return(0,e.buildDeleteManyOperation)(p,B);case"updateOne":return(0,e.buildUpdateOneOperation)(p,B,b);case"updateMany":return(0,e.buildUpdateManyOperation)(p,B,b);case"replaceOne":return(0,e.buildReplaceOneOperation)(p,B)}}})(Ul);var xn={},Ec;function m4(){if(Ec)return xn;Ec=1,Object.defineProperty(xn,"__esModule",{value:!0}),xn.ClientBulkWriteResultsMerger=void 0;const e=es(),t=Q,r={acknowledged:!1,insertedCount:0,upsertedCount:0,matchedCount:0,modifiedCount:0,deletedCount:0,insertResults:void 0,updateResults:void 0,deleteResults:void 0};class n{static unacknowledged(){return r}constructor(o){this.options=o,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},o.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(o){let u;try{for await(const c of o)if(c.ok===1)this.options.verboseResults&&this.processDocument(o,c);else if(this.options.ordered){const s=new t.MongoClientBulkWriteError({message:"Mongo client ordered bulk write encountered a write error."});throw s.writeErrors.set(c.idx+this.currentBatchOffset,{code:c.code,message:c.errmsg}),s.partialResult=this.result,s}else this.writeErrors.set(c.idx+this.currentBatchOffset,{code:c.code,message:c.errmsg})}catch(c){if(c instanceof e.MongoWriteConcernError){const s=c.result;if(u={insertedCount:s.nInserted,upsertedCount:s.nUpserted,matchedCount:s.nMatched,modifiedCount:s.nModified,deletedCount:s.nDeleted,writeConcernError:s.writeConcernError},this.options.verboseResults&&s.cursor.firstBatch)for(const a of s.cursor.firstBatch)a.ok===1&&this.processDocument(o,a)}else throw c}finally{if(o.response){const c=o.response;this.incrementCounts(c)}this.currentBatchOffset+=o.operations.length}if(u){const c=u.writeConcernError;this.incrementCounts(u),this.writeConcernErrors.push({code:c.code,message:c.errmsg})}return this.result}processDocument(o,u){var s,a,E;const c=o.operations[u.idx];if("insert"in c&&((s=this.result.insertResults)==null||s.set(u.idx+this.currentBatchOffset,{insertedId:c.document._id})),"update"in c){const h={matchedCount:u.n,modifiedCount:u.nModified??0,didUpsert:u.upserted!=null};u.upserted&&(h.upsertedId=u.upserted._id),(a=this.result.updateResults)==null||a.set(u.idx+this.currentBatchOffset,h)}"delete"in c&&((E=this.result.deleteResults)==null||E.set(u.idx+this.currentBatchOffset,{deletedCount:u.n}))}incrementCounts(o){this.result.insertedCount+=o.insertedCount,this.result.upsertedCount+=o.upsertedCount,this.result.matchedCount+=o.matchedCount,this.result.modifiedCount+=o.modifiedCount,this.result.deletedCount+=o.deletedCount}}return xn.ClientBulkWriteResultsMerger=n,xn}var gc;function E4(){if(gc)return jn;gc=1,Object.defineProperty(jn,"__esModule",{value:!0}),jn.ClientBulkWriteExecutor=void 0;const e=rt,t=Jo,r=Q,n=Te,i=ne(),o=lt(),u=qe,c=Si,s=Ul,a=m4();class E{constructor(g,m,C){var S;if(m.length===0)throw new r.MongoClientBulkWriteExecutionError("No client bulk write models were provided.");if(this.client=g,this.operations=m,this.options={ordered:!0,bypassDocumentValidation:!1,verboseResults:!1,...C},this.options.writeConcern||(this.options.writeConcern=o.WriteConcern.fromOptions(this.client.s.options)),((S=this.options.writeConcern)==null?void 0:S.w)===0){if(this.options.verboseResults)throw new r.MongoInvalidArgumentError("Cannot request unacknowledged write concern and verbose results");if(this.options.ordered)throw new r.MongoInvalidArgumentError("Cannot request unacknowledged write concern and ordered writes")}}async execute(){var D;const g=this.client.s.options.pkFactory,m=new s.ClientBulkWriteCommandBuilder(this.operations,this.options,g),C=(0,i.resolveTimeoutOptions)(this.client,this.options),S=n.TimeoutContext.create(C);if(((D=this.options.writeConcern)==null?void 0:D.w)===0){for(;m.hasNextBatch();){const O=new c.ClientBulkWriteOperation(m,this.options);await(0,u.executeOperation)(this.client,O,S)}return a.ClientBulkWriteResultsMerger.unacknowledged()}else{const O=new a.ClientBulkWriteResultsMerger(this.options);for(;m.hasNextBatch();){const M=new e.CursorTimeoutContext(S,Symbol()),p={...this.options,timeoutContext:M,...C.timeoutMS!=null&&{timeoutMode:e.CursorTimeoutMode.LIFETIME}},B=new t.ClientBulkWriteCursor(this.client,m,p);try{await O.merge(B)}catch(d){if(d instanceof r.MongoServerError&&!(d instanceof r.MongoClientBulkWriteError)){const b=new r.MongoClientBulkWriteError({message:"Mongo client bulk write encountered an error during execution"});throw b.cause=d,b.partialResult=O.bulkWriteResult,b}else throw d}}if(O.writeConcernErrors.length>0||O.writeErrors.size>0){const M=new r.MongoClientBulkWriteError({message:"Mongo client bulk write encountered errors during execution."});throw M.writeConcernErrors=O.writeConcernErrors,M.writeErrors=O.writeErrors,M.partialResult=O.bulkWriteResult,M}return O.bulkWriteResult}}}return jn.ClientBulkWriteExecutor=E,jn}var Qo={};Object.defineProperty(Qo,"__esModule",{value:!0});Qo.EndSessionsOperation=void 0;const g4=De(),A4=Ie,p4=Ke,C4=ne(),Ac=Me;class jl extends A4.CommandOperation{constructor(t){super(),this.writeConcern={w:0},this.ns=C4.MongoDBNamespace.fromString("admin.$cmd"),this.SERVER_COMMAND_RESPONSE_TYPE=g4.MongoDBResponse,this.sessions=t}buildCommandDocument(t,r){return{endSessions:this.sessions}}buildOptions(t){return{timeoutContext:t,readPreference:p4.ReadPreference.primaryPreferred}}get commandName(){return"endSessions"}}Qo.EndSessionsOperation=jl;(0,Ac.defineAspects)(jl,Ac.Aspect.WRITE_OPERATION);var zn={},mt={};Object.defineProperty(mt,"__esModule",{value:!0});mt.WaitingForSuitableServerEvent=mt.ServerSelectionSucceededEvent=mt.ServerSelectionFailedEvent=mt.ServerSelectionStartedEvent=mt.ServerSelectionEvent=void 0;const S4=ne(),Zo=Ve;class yi{constructor(t,r,n){this.selector=t,this.operation=n,this.topologyDescription=r}}mt.ServerSelectionEvent=yi;class y4 extends yi{constructor(t,r,n){super(t,r,n),this.name=Zo.SERVER_SELECTION_STARTED,this.message="Server selection started"}}mt.ServerSelectionStartedEvent=y4;class O4 extends yi{constructor(t,r,n,i){super(t,r,i),this.name=Zo.SERVER_SELECTION_FAILED,this.message="Server selection failed",this.failure=n}}mt.ServerSelectionFailedEvent=O4;class w4 extends yi{constructor(t,r,n,i){super(t,r,i),this.name=Zo.SERVER_SELECTION_SUCCEEDED,this.message="Server selection succeeded";const{host:o,port:u}=S4.HostAddress.fromString(n).toHostPort();this.serverHost=o,this.serverPort=u}}mt.ServerSelectionSucceededEvent=w4;class _4 extends yi{constructor(t,r,n,i){super(t,r,i),this.name=Zo.WAITING_FOR_SUITABLE_SERVER,this.message="Waiting for suitable server to become available",this.remainingTimeMS=n}}mt.WaitingForSuitableServerEvent=_4;var kr={};Object.defineProperty(kr,"__esModule",{value:!0});kr.SrvPoller=kr.SrvPollingEvent=void 0;const D4=D1,s1=En,T4=Q,B4=Qe,Vn=ne();class xl{constructor(t){this.srvRecords=t}hostnames(){return new Set(this.srvRecords.map(t=>Vn.HostAddress.fromSrvRecord(t).toString()))}}kr.SrvPollingEvent=xl;const so=class so extends B4.TypedEventEmitter{constructor(t){if(super(),this.on("error",Vn.noop),!t||!t.srvHost)throw new T4.MongoRuntimeError("Options for SrvPoller must exist and include srvHost");this.srvHost=t.srvHost,this.srvMaxHosts=t.srvMaxHosts??0,this.srvServiceName=t.srvServiceName??"mongodb",this.rescanSrvIntervalMS=6e4,this.heartbeatFrequencyMS=t.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,s1.clearTimeout)(this._timeout),this.generation+=1,this._timeout=void 0)}schedule(){this._timeout&&(0,s1.clearTimeout)(this._timeout),this._timeout=(0,s1.setTimeout)(()=>{this._poll().then(void 0,Vn.squashError)},this.intervalMS)}success(t){this.haMode=!1,this.schedule(),this.emit(so.SRV_RECORD_DISCOVERY,new xl(t))}failure(){this.haMode=!0,this.schedule()}async _poll(){const t=this.generation;let r;try{r=await D4.promises.resolveSrv(this.srvAddress)}catch{this.failure();return}if(t!==this.generation)return;const n=[];for(const i of r)try{(0,Vn.checkParentDomainMatch)(i.name,this.srvHost),n.push(i)}catch(o){(0,Vn.squashError)(o)}if(!n.length){this.failure();return}this.success(n)}};so.SRV_RECORD_DISCOVERY="srvRecordDiscovery";let y1=so;kr.SrvPoller=y1;var pc;function b4(){if(pc)return zn;pc=1,Object.defineProperty(zn,"__esModule",{value:!0}),zn.Topology=void 0;const e=_l(),t=Ve,r=Q,n=pr,i=Qe,o=Ke,u=Te,c=ne(),s=Ne,a=Ue,E=Ol(),h=nr,g=An,m=mt,C=kr,S=Ai;let D=0;const O=(0,c.makeStateMachine)({[s.STATE_CLOSED]:[s.STATE_CLOSED,s.STATE_CONNECTING],[s.STATE_CONNECTING]:[s.STATE_CONNECTING,s.STATE_CLOSING,s.STATE_CONNECTED,s.STATE_CLOSED],[s.STATE_CONNECTED]:[s.STATE_CONNECTED,s.STATE_CLOSING,s.STATE_CLOSED],[s.STATE_CLOSING]:[s.STATE_CLOSING,s.STATE_CLOSED]}),T=class T extends i.TypedEventEmitter{constructor(A,y,F){super(),this.on("error",c.noop),this.client=A,F=F??{hosts:[c.HostAddress.fromString("localhost:27017")],...Object.fromEntries(e.DEFAULT_OPTIONS.entries())},typeof y=="string"?y=[c.HostAddress.fromString(y)]:Array.isArray(y)||(y=[y]);const R=[];for(const j of y)if(typeof j=="string")R.push(c.HostAddress.fromString(j));else if(j instanceof c.HostAddress)R.push(j);else throw new r.MongoRuntimeError(`Topology cannot be constructed from ${JSON.stringify(j)}`);const v=B(F),J=D++,I=F.srvMaxHosts==null||F.srvMaxHosts===0||F.srvMaxHosts>=R.length?R:(0,c.shuffle)(R,F.srvMaxHosts),N=new Map;for(const j of I)N.set(j.toString(),new h.ServerDescription(j));this.waitQueue=new c.List,this.s={id:J,options:F,seedlist:R,state:s.STATE_CLOSED,description:new S.TopologyDescription(v,N,F.replicaSet,void 0,void 0,void 0,F),serverSelectionTimeoutMS:F.serverSelectionTimeoutMS,heartbeatFrequencyMS:F.heartbeatFrequencyMS,minHeartbeatFrequencyMS:F.minHeartbeatFrequencyMS,servers:new Map,credentials:F==null?void 0:F.credentials,clusterTime:void 0,detectShardedTopology:j=>this.detectShardedTopology(j),detectSrvRecords:j=>this.detectSrvRecords(j)},this.mongoLogger=A.mongoLogger,this.component="topology",F.srvHost&&!F.loadBalanced&&(this.s.srvPoller=F.srvPoller??new C.SrvPoller({heartbeatFrequencyMS:this.s.heartbeatFrequencyMS,srvHost:F.srvHost,srvMaxHosts:F.srvMaxHosts,srvServiceName:F.srvServiceName}),this.on(T.TOPOLOGY_DESCRIPTION_CHANGED,this.s.detectShardedTopology)),this.connectionLock=void 0}detectShardedTopology(A){var I,N,j;const y=A.previousDescription.type,F=A.newDescription.type,R=y!==s.TopologyType.Sharded&&F===s.TopologyType.Sharded,v=(I=this.s.srvPoller)==null?void 0:I.listeners(C.SrvPoller.SRV_RECORD_DISCOVERY),J=!!(v!=null&&v.includes(this.s.detectSrvRecords));R&&!J&&((N=this.s.srvPoller)==null||N.on(C.SrvPoller.SRV_RECORD_DISCOVERY,this.s.detectSrvRecords),(j=this.s.srvPoller)==null||j.start())}detectSrvRecords(A){const y=this.s.description;this.s.description=this.s.description.updateFromSrvPollingEvent(A,this.s.options.srvMaxHosts),this.s.description!==y&&(b(this),this.emitAndLog(T.TOPOLOGY_DESCRIPTION_CHANGED,new a.TopologyDescriptionChangedEvent(this.s.id,y,this.s.description)))}get description(){return this.s.description}get loadBalanced(){return this.s.options.loadBalanced}get serverApi(){return this.s.options.serverApi}async connect(A){this.connectionLock??(this.connectionLock=this._connect(A));try{return await this.connectionLock,this}finally{this.connectionLock=void 0}}async _connect(A){if(A=A??{},this.s.state===s.STATE_CONNECTED)return this;O(this,s.STATE_CONNECTING),this.emitAndLog(T.TOPOLOGY_OPENING,new a.TopologyOpeningEvent(this.s.id)),this.emitAndLog(T.TOPOLOGY_DESCRIPTION_CHANGED,new a.TopologyDescriptionChangedEvent(this.s.id,new S.TopologyDescription(s.TopologyType.Unknown),this.s.description));const y=Array.from(this.s.description.servers.values());if(this.s.servers=new Map(y.map(I=>[I.address,d(this,I)])),this.s.options.loadBalanced)for(const I of y){const N=new h.ServerDescription(I.hostAddress,void 0,{loadBalanced:this.s.options.loadBalanced});this.serverUpdateHandler(N)}const F=this.client.s.options.serverSelectionTimeoutMS,R=A.readPreference??o.ReadPreference.primary,v=u.TimeoutContext.create({timeoutMS:void 0,serverSelectionTimeoutMS:F,waitQueueTimeoutMS:this.client.s.options.waitQueueTimeoutMS}),J={operationName:"handshake",...A,timeoutContext:v,deprioritizedServers:new g.DeprioritizedServers};try{const I=await this.selectServer((0,g.readPreferenceServerSelector)(R),J);if(!(this.s.options.__skipPingOnConnect===!0)){const j=await I.pool.checkOut({timeoutContext:v});return I.pool.checkIn(j),O(this,s.STATE_CONNECTED),this.emit(T.OPEN,this),this.emit(T.CONNECT,this),this}return O(this,s.STATE_CONNECTED),this.emit(T.OPEN,this),this.emit(T.CONNECT,this),this}catch(I){throw this.close(),I}}closeCheckedOutConnections(){for(const A of this.s.servers.values())return A.closeCheckedOutConnections()}close(){if(!(this.s.state===s.STATE_CLOSED||this.s.state===s.STATE_CLOSING)){for(const A of this.s.servers.values())p(A,this);this.s.servers.clear(),O(this,s.STATE_CLOSING),f(this.waitQueue,new r.MongoTopologyClosedError),this.s.srvPoller&&(this.s.srvPoller.stop(),this.s.srvPoller.removeListener(C.SrvPoller.SRV_RECORD_DISCOVERY,this.s.detectSrvRecords)),this.removeListener(T.TOPOLOGY_DESCRIPTION_CHANGED,this.s.detectShardedTopology),O(this,s.STATE_CLOSED),this.emitAndLog(T.TOPOLOGY_CLOSED,new a.TopologyClosedEvent(this.s.id))}}async selectServer(A,y){var K,ee,ae,ye,ce,le,he,Ee,re,Ce;let F;if(typeof A!="function")if(typeof A=="string")F=(0,g.readPreferenceServerSelector)(o.ReadPreference.fromString(A));else{let _e;A instanceof o.ReadPreference?_e=A:(o.ReadPreference.translate(y),_e=y.readPreference||o.ReadPreference.primary),F=(0,g.readPreferenceServerSelector)(_e)}else F=A;y={serverSelectionTimeoutMS:this.s.serverSelectionTimeoutMS,...y},(K=this.client.mongoLogger)!=null&&K.willLog(n.MongoLoggableComponent.SERVER_SELECTION,n.SeverityLevel.DEBUG)&&((ee=this.client.mongoLogger)==null||ee.debug(n.MongoLoggableComponent.SERVER_SELECTION,new m.ServerSelectionStartedEvent(A,this.description,y.operationName)));let R;y.timeoutContext?R=y.timeoutContext.serverSelectionTimeout:R=u.Timeout.expires(y.serverSelectionTimeoutMS??0);const v=this.description.type===s.TopologyType.Sharded,J=y.session,I=J&&J.transaction;if(v&&I&&I.server)return(ae=this.client.mongoLogger)!=null&&ae.willLog(n.MongoLoggableComponent.SERVER_SELECTION,n.SeverityLevel.DEBUG)&&((ye=this.client.mongoLogger)==null||ye.debug(n.MongoLoggableComponent.SERVER_SELECTION,new m.ServerSelectionSucceededEvent(A,this.description,I.server.pool.address,y.operationName))),(ce=y.timeoutContext)!=null&&ce.clearServerSelectionTimeout&&(R==null||R.clear()),I.server;const{promise:N,resolve:j,reject:x}=(0,c.promiseWithResolvers)(),Y={serverSelector:F,topologyDescription:this.description,mongoLogger:this.client.mongoLogger,transaction:I,resolve:j,reject:x,cancelled:!1,startTime:(0,c.processTimeMS)(),operationName:y.operationName,waitingLogged:!1,deprioritizedServers:y.deprioritizedServers},$=(0,c.addAbortListener)(y.signal,function(){Y.cancelled=!0,x(this.reason)});this.waitQueue.push(Y),l(this);try{R==null||R.throwIfExpired();const _e=await(R?Promise.race([N,R]):N);return(le=y.timeoutContext)!=null&&le.csotEnabled()&&_e.description.minRoundTripTime!==0&&(y.timeoutContext.minRoundTripTime=_e.description.minRoundTripTime),_e}catch(_e){if(u.TimeoutError.is(_e)){Y.cancelled=!0;const He=new r.MongoServerSelectionError(`Server selection timed out after ${R==null?void 0:R.duration} ms`,this.description);throw(he=this.client.mongoLogger)!=null&&he.willLog(n.MongoLoggableComponent.SERVER_SELECTION,n.SeverityLevel.DEBUG)&&((Ee=this.client.mongoLogger)==null||Ee.debug(n.MongoLoggableComponent.SERVER_SELECTION,new m.ServerSelectionFailedEvent(A,this.description,He,y.operationName))),(re=y.timeoutContext)!=null&&re.csotEnabled()?new r.MongoOperationTimeoutError("Timed out during server selection",{cause:He}):He}throw _e}finally{$==null||$[c.kDispose](),(Ce=y.timeoutContext)!=null&&Ce.clearServerSelectionTimeout&&(R==null||R.clear())}}serverUpdateHandler(A){if(!this.s.description.hasServer(A.address)||w(this.s.description,A))return;const y=this.s.description,F=this.s.description.servers.get(A.address);if(!F)return;const R=A.$clusterTime;R&&(0,s._advanceClusterTime)(this,R);const v=F&&F.equals(A);if(this.s.description=this.s.description.update(A),this.s.description.compatibilityError){this.emit(T.ERROR,new r.MongoCompatibilityError(this.s.description.compatibilityError));return}if(!v){const J=this.s.description.servers.get(A.address);J&&this.emit(T.SERVER_DESCRIPTION_CHANGED,new a.ServerDescriptionChangedEvent(this.s.id,A.address,F,J))}b(this,A),this.waitQueue.length>0&&l(this),v||this.emitAndLog(T.TOPOLOGY_DESCRIPTION_CHANGED,new a.TopologyDescriptionChangedEvent(this.s.id,y,this.s.description))}auth(A,y){typeof A=="function"&&(y=A,A=void 0),typeof y=="function"&&y(void 0,!0)}isConnected(){return this.s.state===s.STATE_CONNECTED}isDestroyed(){return this.s.state===s.STATE_CLOSED}lastHello(){const A=Array.from(this.description.servers.values());return A.length===0?{}:A.filter(R=>R.type!==s.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(A){this.s.clusterTime=A}};T.SERVER_OPENING=t.SERVER_OPENING,T.SERVER_CLOSED=t.SERVER_CLOSED,T.SERVER_DESCRIPTION_CHANGED=t.SERVER_DESCRIPTION_CHANGED,T.TOPOLOGY_OPENING=t.TOPOLOGY_OPENING,T.TOPOLOGY_CLOSED=t.TOPOLOGY_CLOSED,T.TOPOLOGY_DESCRIPTION_CHANGED=t.TOPOLOGY_DESCRIPTION_CHANGED,T.ERROR=t.ERROR,T.OPEN=t.OPEN,T.CONNECT=t.CONNECT,T.CLOSE=t.CLOSE,T.TIMEOUT=t.TIMEOUT;let M=T;zn.Topology=M;function p(_,A){for(const y of t.LOCAL_SERVER_EVENTS)_.removeAllListeners(y);_.close(),A.emitAndLog(M.SERVER_CLOSED,new a.ServerClosedEvent(A.s.id,_.description.address));for(const y of t.SERVER_RELAY_EVENTS)_.removeAllListeners(y)}function B(_){return _!=null&&_.directConnection?s.TopologyType.Single:_!=null&&_.replicaSet?s.TopologyType.ReplicaSetNoPrimary:_!=null&&_.loadBalanced?s.TopologyType.LoadBalanced:s.TopologyType.Unknown}function d(_,A){_.emitAndLog(M.SERVER_OPENING,new a.ServerOpeningEvent(_.s.id,A.address));const y=new E.Server(_,A,_.s.options);for(const F of t.SERVER_RELAY_EVENTS)y.on(F,R=>_.emit(F,R));return y.on(E.Server.DESCRIPTION_RECEIVED,F=>_.serverUpdateHandler(F)),y.connect(),y}function b(_,A){if(A&&_.s.servers.has(A.address)){const y=_.s.servers.get(A.address);if(y){if(y.s.description=A,A.error instanceof r.MongoError&&A.error.hasErrorLabel(r.MongoErrorLabel.ResetPool)){const F=A.error.hasErrorLabel(r.MongoErrorLabel.InterruptInUseConnections);y.pool.clear({interruptInUseConnections:F})}else if(A.error==null){const F=_.s.description.type;(A.isDataBearing||A.type!==s.ServerType.Unknown&&F===s.TopologyType.Single)&&y.pool.ready()}}}for(const y of _.description.servers.values())if(!_.s.servers.has(y.address)){const F=d(_,y);_.s.servers.set(y.address,F)}for(const y of _.s.servers){const F=y[0];if(_.description.hasServer(F)||!_.s.servers.has(F))continue;const R=_.s.servers.get(F);_.s.servers.delete(F),R&&p(R,_)}}function f(_,A){var y,F;for(;_.length;){const R=_.shift();R&&(R.cancelled||((y=R.mongoLogger)!=null&&y.willLog(n.MongoLoggableComponent.SERVER_SELECTION,n.SeverityLevel.DEBUG)&&((F=R.mongoLogger)==null||F.debug(n.MongoLoggableComponent.SERVER_SELECTION,new m.ServerSelectionFailedEvent(R.serverSelector,R.topologyDescription,A,R.operationName))),R.reject(A)))}}function l(_){var R,v,J,I,N,j,x,Y;if(_.s.state===s.STATE_CLOSED){f(_.waitQueue,new r.MongoTopologyClosedError);return}const A=_.description.type===s.TopologyType.Sharded,y=Array.from(_.description.servers.values()),F=_.waitQueue.length;for(let $=0;$<F;++$){const K=_.waitQueue.shift();if(!K||K.cancelled)continue;let ee;try{const ce=K.serverSelector,le=K.deprioritizedServers;ee=ce?ce(_.description,y,le):y}catch(ce){(R=_.client.mongoLogger)!=null&&R.willLog(n.MongoLoggableComponent.SERVER_SELECTION,n.SeverityLevel.DEBUG)&&((v=_.client.mongoLogger)==null||v.debug(n.MongoLoggableComponent.SERVER_SELECTION,new m.ServerSelectionFailedEvent(K.serverSelector,_.description,ce,K.operationName))),K.reject(ce);continue}let ae;if(ee.length===0){K.waitingLogged||((J=_.client.mongoLogger)!=null&&J.willLog(n.MongoLoggableComponent.SERVER_SELECTION,n.SeverityLevel.INFORMATIONAL)&&((I=_.client.mongoLogger)==null||I.info(n.MongoLoggableComponent.SERVER_SELECTION,new m.WaitingForSuitableServerEvent(K.serverSelector,_.description,_.s.serverSelectionTimeoutMS!==0?_.s.serverSelectionTimeoutMS-((0,c.processTimeMS)()-K.startTime):-1,K.operationName))),K.waitingLogged=!0),_.waitQueue.push(K);continue}else if(ee.length===1)ae=_.s.servers.get(ee[0].address);else{const ce=(0,c.shuffle)(ee,2),le=_.s.servers.get(ce[0].address),he=_.s.servers.get(ce[1].address);ae=le&&he&&le.s.operationCount<he.s.operationCount?le:he}if(!ae){const ce=new r.MongoServerSelectionError("server selection returned a server description but the server was not found in the topology",_.description);(N=_.client.mongoLogger)!=null&&N.willLog(n.MongoLoggableComponent.SERVER_SELECTION,n.SeverityLevel.DEBUG)&&((j=_.client.mongoLogger)==null||j.debug(n.MongoLoggableComponent.SERVER_SELECTION,new m.ServerSelectionFailedEvent(K.serverSelector,_.description,ce,K.operationName))),K.reject(ce);return}const ye=K.transaction;A&&ye&&ye.isActive&&ae&&ye.pinServer(ae),(x=_.client.mongoLogger)!=null&&x.willLog(n.MongoLoggableComponent.SERVER_SELECTION,n.SeverityLevel.DEBUG)&&((Y=_.client.mongoLogger)==null||Y.debug(n.MongoLoggableComponent.SERVER_SELECTION,new m.ServerSelectionSucceededEvent(K.serverSelector,K.topologyDescription,ae.pool.address,K.operationName))),K.resolve(ae)}if(_.waitQueue.length>0)for(const[,$]of _.s.servers)queueMicrotask(function(){return $.requestCheck()})}function w(_,A){const y=_.servers.get(A.address),F=y==null?void 0:y.topologyVersion;return(0,h.compareTopologyVersion)(F,A.topologyVersion)>0}return zn}var Cc;function mn(){if(Cc)return Or;Cc=1,Object.defineProperty(Or,"__esModule",{value:!0}),Or.MongoClient=Or.ServerApiVersion=void 0;const e=_1,t=es(),r=pe,n=Oi(),i=Mo,o=Ht,u=Cr,c=_l(),s=Ve,a=Z1(),E=Q,h=pi,g=pr,m=Qe,C=E4(),S=Qo,D=qe,O=Ke,M=An,p=b4(),B=at,d=ne();Or.ServerApiVersion=Object.freeze({v1:"1"});class b extends m.TypedEventEmitter{constructor(l,w){super(),this.driverInfoList=[],this.on("error",d.noop),this.options=(0,c.parseOptions)(l,this,w),this.appendMetadata(this.options.driverInfo);const T=Object.values(this.options.mongoLoggerOptions.componentSeverities).some(A=>A!==g.SeverityLevel.OFF);this.mongoLogger=T?new g.MongoLogger(this.options.mongoLoggerOptions):void 0;const _=this;this.s={url:l,bsonOptions:(0,r.resolveBSONOptions)(this.options),namespace:(0,d.ns)("admin"),hasBeenClosed:!1,sessionPool:new B.ServerSessionPool(this),activeSessions:new Set,activeCursors:new Set,authProviders:new h.MongoClientAuthProviders,get options(){return _.options},get readConcern(){return _.options.readConcern},get writeConcern(){return _.options.writeConcern},get readPreference(){return _.options.readPreference},get isMongoClient(){return!0}},this.checkForNonGenuineHosts()}async[Symbol.asyncDispose](){await this.close()}appendMetadata(l){this.driverInfoList.some(T=>(0,u.isDriverInfoEqual)(T,l))||(this.driverInfoList.push(l),this.options.metadata=(0,u.makeClientMetadata)(this.driverInfoList,this.options).then(void 0,d.squashError).then(T=>T??{}))}checkForNonGenuineHosts(){var A,y;const l=this.options.hosts.filter(F=>(0,d.isHostMatch)(d.DOCUMENT_DB_CHECK,F.host)),w=(0,d.isHostMatch)(d.DOCUMENT_DB_CHECK,this.options.srvHost),T=this.options.hosts.filter(F=>(0,d.isHostMatch)(d.COSMOS_DB_CHECK,F.host)),_=(0,d.isHostMatch)(d.COSMOS_DB_CHECK,this.options.srvHost);l.length!==0||w?(A=this.mongoLogger)==null||A.info("client",d.DOCUMENT_DB_MSG):(T.length!==0||_)&&((y=this.mongoLogger)==null||y.info("client",d.COSMOS_DB_MSG))}get serverApi(){return this.options.serverApi&&Object.freeze({...this.options.serverApi})}get monitorCommands(){return this.options.monitorCommands}set monitorCommands(l){this.options.monitorCommands=l}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(l,w){if(this.autoEncrypter)throw new E.MongoInvalidArgumentError("MongoClient bulkWrite does not currently support automatic encryption.");return await new C.ClientBulkWriteExecutor(this,l,(0,d.resolveOptions)(this,w)).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(){var T,_,A,y,F,R;if(this.topology&&this.topology.isConnected())return this;const l=this.options;if(l.tls&&(typeof l.tlsCAFile=="string"&&(l.ca??(l.ca=await e.promises.readFile(l.tlsCAFile))),typeof l.tlsCRLFile=="string"&&(l.crl??(l.crl=await e.promises.readFile(l.tlsCRLFile))),typeof l.tlsCertificateKeyFile=="string"&&(!l.key||!l.cert))){const v=await e.promises.readFile(l.tlsCertificateKeyFile);l.key??(l.key=v),l.cert??(l.cert=v)}if(typeof l.srvHost=="string"){const v=await(0,c.resolveSRVRecord)(l);for(const[J,I]of v.entries())l.hosts[J]=I}if(((T=l.credentials)==null?void 0:T.mechanism)===o.AuthMechanism.MONGODB_OIDC){const v=((A=(_=l.credentials)==null?void 0:_.mechanismProperties)==null?void 0:A.ALLOWED_HOSTS)||i.DEFAULT_ALLOWED_HOSTS;if(!!!((F=(y=l.credentials)==null?void 0:y.mechanismProperties)!=null&&F.ENVIRONMENT)){for(const I of l.hosts)if(!(0,d.hostMatchesWildcards)(I.toHostPort().host,v))throw new E.MongoInvalidArgumentError(`Host '${I}' is not valid for OIDC authentication with ALLOWED_HOSTS of '${v.join(",")}'`)}}this.topology=new p.Topology(this,l.hosts,l),this.topology.once(p.Topology.OPEN,()=>this.emit("open",this));for(const v of s.MONGO_CLIENT_EVENTS)this.topology.on(v,(...J)=>this.emit(v,...J));const w=async()=>{var v,J;try{await((v=this.topology)==null?void 0:v.connect(l))}catch(I){throw(J=this.topology)==null||J.close(),I}};return this.autoEncrypter?(await((R=this.autoEncrypter)==null?void 0:R.init()),await w(),await l.encrypter.connectInternalClient()):await w(),this}async close(l=!1){if(this.closeLock)return await this.closeLock;try{this.closeLock=this._close(),await this.closeLock}finally{this.closeLock=void 0}}async _close(){var F;Object.defineProperty(this.s,"hasBeenClosed",{value:!0,enumerable:!0,configurable:!1,writable:!1}),(F=this.topology)==null||F.closeCheckedOutConnections();const l=Array.from(this.s.activeCursors,R=>R.close());this.s.activeCursors.clear(),await Promise.all(l);const w=Array.from(this.s.activeSessions,R=>R.endSession());if(this.s.activeSessions.clear(),await Promise.all(w),this.topology==null)return;(this.topology.description.type===t.TopologyType.LoadBalanced||this.topology.description.logicalSessionTimeoutMinutes!=null)&&await y(this,this.topology);const _=this.topology;this.topology=void 0,_.close();const{encrypter:A}=this.options;A&&await A.close(this);async function y(R,{description:v}){const J=(0,M.readPreferenceServerSelector)(O.ReadPreference.primaryPreferred),I=Array.from(v.servers.values());if(J(v,I,new M.DeprioritizedServers).length!==0){const j=Array.from(R.s.sessionPool.sessions,({id:x})=>x);if(j.length!==0)try{await(0,D.executeOperation)(R,new S.EndSessionsOperation(j))}catch(x){(0,d.squashError)(x)}}}}db(l,w){w=w??{},l||(l=this.s.options.dbName);const T=Object.assign({},this.options,w);return new a.Db(this,l,T)}static async connect(l,w){return await new this(l,w).connect()}startSession(l){const w=new B.ClientSession(this,this.s.sessionPool,{explicit:!0,...l},this.options);return this.s.activeSessions.add(w),w.once("ended",()=>{this.s.activeSessions.delete(w)}),w}async withSession(l,w){const T={owner:Symbol(),...typeof l=="object"?l:{}},_=typeof l=="function"?l:w;if(_==null)throw new E.MongoInvalidArgumentError("Missing required callback parameter");const A=this.startSession(T);try{return await _(A)}finally{try{await A.endSession()}catch(y){(0,d.squashError)(y)}}}watch(l=[],w={}){return Array.isArray(l)||(w=l,l=[]),new n.ChangeStream(this,l,(0,d.resolveOptions)(this,w))}}return Or.MongoClient=b,Or}var Sc;function Oi(){if(Sc)return Xr;Sc=1,Object.defineProperty(Xr,"__esModule",{value:!0}),Xr.ChangeStream=void 0,Xr.filterOutOptions=D;const e=fi(),t=Ve,r=rt,n=k0(),i=Z1(),o=Q,u=mn(),c=Qe,s=An,a=Te,E=ne(),h={COLLECTION:Symbol("Collection"),DATABASE:Symbol("Database"),CLUSTER:Symbol("Cluster")},g=[t.RESUME_TOKEN_CHANGED,t.END,t.CLOSE],m="A change stream document has been received that lacks a resume token (_id).",C="ChangeStream is closed",S=M();function D(B){return Object.fromEntries(Object.entries(B).filter(([d,b])=>!S.has(d)))}const p=class p extends c.TypedEventEmitter{async[Symbol.asyncDispose](){await this.close()}constructor(d,b=[],f={}){super(),this.pipeline=b,this.options={...f};let l;if(delete this.options.writeConcern,d instanceof e.Collection)this.type=h.COLLECTION,l=d.s.db.client.options.serverSelectionTimeoutMS;else if(d instanceof i.Db)this.type=h.DATABASE,l=d.client.options.serverSelectionTimeoutMS;else if(d instanceof u.MongoClient)this.type=h.CLUSTER,l=d.options.serverSelectionTimeoutMS;else throw new o.MongoChangeStreamError("Parent provided to ChangeStream constructor must be an instance of Collection, Db, or MongoClient");this.contextOwner=Symbol(),this.parent=d,this.namespace=d.s.namespace,!this.options.readPreference&&d.readPreference&&(this.options.readPreference=d.readPreference),this.cursor=this._createChangeStreamCursor(f),this.isClosed=!1,this.mode=!1,this.on("newListener",w=>{w==="change"&&this.cursor&&this.listenerCount("change")===0&&this._streamEvents(this.cursor)}),this.on("removeListener",w=>{var T;w==="change"&&this.listenerCount("change")===0&&this.cursor&&((T=this.cursorStream)==null||T.removeAllListeners("data"))}),this.options.timeoutMS!=null&&(this.timeoutContext=new a.CSOTTimeoutContext({timeoutMS:this.options.timeoutMS,serverSelectionTimeoutMS:l}))}get resumeToken(){var d;return(d=this.cursor)==null?void 0:d.resumeToken}async hasNext(){var d,b;this._setIsIterator(),(d=this.timeoutContext)==null||d.refresh();try{for(;;)try{return await this.cursor.hasNext()}catch(f){try{await this._processErrorIteratorMode(f,this.cursor.id!=null)}catch(l){if(l instanceof o.MongoOperationTimeoutError&&this.cursor.id==null)throw l;try{await this.close()}catch(w){(0,E.squashError)(w)}throw l}}}finally{(b=this.timeoutContext)==null||b.clear()}}async next(){var d,b;this._setIsIterator(),(d=this.timeoutContext)==null||d.refresh();try{for(;;)try{const f=await this.cursor.next();return this._processChange(f??null)}catch(f){try{await this._processErrorIteratorMode(f,this.cursor.id!=null)}catch(l){if(l instanceof o.MongoOperationTimeoutError&&this.cursor.id==null)throw l;try{await this.close()}catch(w){(0,E.squashError)(w)}throw l}}}finally{(b=this.timeoutContext)==null||b.clear()}}async tryNext(){var d,b;this._setIsIterator(),(d=this.timeoutContext)==null||d.refresh();try{for(;;)try{const f=await this.cursor.tryNext();return f?this._processChange(f):null}catch(f){try{await this._processErrorIteratorMode(f,this.cursor.id!=null)}catch(l){if(l instanceof o.MongoOperationTimeoutError&&this.cursor.id==null)throw l;try{await this.close()}catch(w){(0,E.squashError)(w)}throw l}}}finally{(b=this.timeoutContext)==null||b.clear()}}async*[Symbol.asyncIterator](){if(!this.closed)try{for(;;)yield await this.next()}finally{try{await this.close()}catch(d){(0,E.squashError)(d)}}}get closed(){return this.isClosed||this.cursor.closed}async close(){var b;(b=this.timeoutContext)==null||b.clear(),this.timeoutContext=void 0,this.isClosed=!0;const d=this.cursor;try{await d.close()}finally{this._endStream()}}stream(){if(this.closed)throw new o.MongoChangeStreamError(C);return this.cursor.stream()}_setIsEmitter(){if(this.mode==="iterator")throw new o.MongoAPIError("ChangeStream cannot be used as an EventEmitter after being used as an iterator");this.mode="emitter"}_setIsIterator(){if(this.mode==="emitter")throw new o.MongoAPIError("ChangeStream cannot be used as an iterator after being used as an EventEmitter");this.mode="iterator"}_createChangeStreamCursor(d){const b=D(d);this.type===h.CLUSTER&&(b.allChangesForCluster=!0);const f=[{$changeStream:b},...this.pipeline],l=this.type===h.CLUSTER?this.parent:this.type===h.DATABASE?this.parent.client:this.type===h.COLLECTION?this.parent.client:null;if(l==null)throw new o.MongoRuntimeError(`Changestream type should only be one of cluster, database, collection. Found ${this.type.toString()}`);const w=new n.ChangeStreamCursor(l,this.namespace,f,{...d,timeoutContext:this.timeoutContext?new r.CursorTimeoutContext(this.timeoutContext,this.contextOwner):void 0});for(const T of g)w.on(T,_=>this.emit(T,_));return this.listenerCount(p.CHANGE)>0&&this._streamEvents(w),w}_closeEmitterModeWithError(d){this.emit(p.ERROR,d),this.close().then(void 0,E.squashError)}_streamEvents(d){this._setIsEmitter();const b=this.cursorStream??d.stream();this.cursorStream=b,b.on("data",f=>{var l;try{const w=this._processChange(f);this.emit(p.CHANGE,w)}catch(w){this.emit(p.ERROR,w)}(l=this.timeoutContext)==null||l.refresh()}),b.on("error",f=>this._processErrorStreamMode(f,this.cursor.id!=null))}_endStream(){var d,b,f,l;(d=this.cursorStream)==null||d.removeAllListeners("data"),(b=this.cursorStream)==null||b.removeAllListeners("close"),(f=this.cursorStream)==null||f.removeAllListeners("end"),(l=this.cursorStream)==null||l.destroy(),this.cursorStream=void 0}_processChange(d){if(this.isClosed)throw new o.MongoAPIError(C);if(d==null)throw new o.MongoRuntimeError(C);if(d&&!d._id)throw new o.MongoChangeStreamError(m);return this.cursor.cacheResumeToken(d._id),this.options.startAtOperationTime=void 0,d}_processErrorStreamMode(d,b){this.isClosed||(b&&((0,o.isResumableError)(d,this.cursor.maxWireVersion)||d instanceof o.MongoOperationTimeoutError)?(this._endStream(),this.cursor.close().then(()=>this._resume(d),f=>((0,E.squashError)(f),this._resume(d))).then(()=>{d instanceof o.MongoOperationTimeoutError&&this.emit(p.ERROR,d)},()=>this._closeEmitterModeWithError(d))):this._closeEmitterModeWithError(d))}async _processErrorIteratorMode(d,b){if(this.isClosed)throw new o.MongoAPIError(C);if(b&&((0,o.isResumableError)(d,this.cursor.maxWireVersion)||d instanceof o.MongoOperationTimeoutError)){try{await this.cursor.close()}catch(f){(0,E.squashError)(f)}if(await this._resume(d),d instanceof o.MongoOperationTimeoutError)throw d}else{try{await this.close()}catch(f){(0,E.squashError)(f)}throw d}}async _resume(d){var f;(f=this.timeoutContext)==null||f.refresh();const b=(0,E.getTopology)(this.parent);try{await b.selectServer(this.cursor.readPreference,{operationName:"reconnect topology in change stream",timeoutContext:this.timeoutContext,deprioritizedServers:new s.DeprioritizedServers}),this.cursor=this._createChangeStreamCursor(this.cursor.resumeOptions)}catch{throw await this.close(),d}}};p.RESPONSE=t.RESPONSE,p.MORE=t.MORE,p.INIT=t.INIT,p.CLOSE=t.CLOSE,p.CHANGE=t.CHANGE,p.END=t.END,p.ERROR=t.ERROR,p.RESUME_TOKEN_CHANGED=t.RESUME_TOKEN_CHANGED;let O=p;Xr.ChangeStream=O;function M(){const B={allowDiskUse:"",authdb:"",batchSize:"",bsonRegExp:"",bypassDocumentValidation:"",bypassPinningCheck:"",checkKeys:"",collation:"",comment:"",cursor:"",dbName:"",enableUtf8Validation:"",explain:"",fieldsAsRaw:"",hint:"",ignoreUndefined:"",let:"",maxAwaitTimeMS:"",maxTimeMS:"",omitMaxTimeMS:"",out:"",promoteBuffers:"",promoteLongs:"",promoteValues:"",raw:"",rawData:"",readConcern:"",readPreference:"",serializeFunctions:"",session:"",timeoutContext:"",timeoutMS:"",timeoutMode:"",useBigInt64:"",willRetryWrite:"",writeConcern:""};return new Set(Object.keys(B))}return Xr}var $o={},wi={};Object.defineProperty(wi,"__esModule",{value:!0});wi.GridFSBucketReadStream=void 0;const M4=uo,F4=rt,Et=Q,R4=Te,Bu=class Bu extends M4.Readable{constructor(t,r,n,i,o){super({emitClose:!0}),this.s={bytesToTrim:0,bytesToSkip:0,bytesRead:0,chunks:t,expected:0,files:r,filter:i,init:!1,expectedEnd:0,options:{start:0,end:0,...o},readPreference:n,timeoutContext:(o==null?void 0:o.timeoutMS)!=null?new R4.CSOTTimeoutContext({timeoutMS:o.timeoutMS,serverSelectionTimeoutMS:0}):void 0}}_read(){this.destroyed||v4(this,()=>N4(this))}start(t=0){return yc(this),this.s.options.start=t,this}end(t=0){return yc(this),this.s.options.end=t,this}async abort(){var r,n;this.push(null),this.destroy();const t=(r=this.s.timeoutContext)==null?void 0:r.getRemainingTimeMSOrThrow();await((n=this.s.cursor)==null?void 0:n.close({timeoutMS:t}))}};Bu.FILE="file";let no=Bu;wi.GridFSBucketReadStream=no;function yc(e){if(e.s.init)throw new Et.MongoGridFSStreamError("Options cannot be changed after the stream is initialized")}function N4(e){if(e.destroyed||!e.s.cursor||!e.s.file)return;const t=r=>{var h;if(e.destroyed)return;if(!r){e.push(null),(h=e.s.cursor)==null||h.close().then(void 0,g=>e.destroy(g));return}if(!e.s.file)return;const n=e.s.file.length-e.s.bytesRead,i=e.s.expected++,o=Math.min(e.s.file.chunkSize,n);if(r.n>i)return e.destroy(new Et.MongoGridFSChunkError(`ChunkIsMissing: Got unexpected n: ${r.n}, expected: ${i}`));if(r.n<i)return e.destroy(new Et.MongoGridFSChunkError(`ExtraChunk: Got unexpected n: ${r.n}, expected: ${i}`));let u=Buffer.isBuffer(r.data)?r.data:r.data.buffer;if(u.byteLength!==o)return n<=0?e.destroy(new Et.MongoGridFSChunkError(`ExtraChunk: Got unexpected n: ${r.n}, expected file length ${e.s.file.length} bytes but already read ${e.s.bytesRead} bytes`)):e.destroy(new Et.MongoGridFSChunkError(`ChunkIsWrongSize: Got unexpected length: ${u.byteLength}, expected: ${o}`));if(e.s.bytesRead+=u.byteLength,u.byteLength===0)return e.push(null);let c=null,s=null;e.s.bytesToSkip!=null&&(c=e.s.bytesToSkip,e.s.bytesToSkip=0);const a=i===e.s.expectedEnd-1,E=e.s.options.end-e.s.bytesToSkip;a&&e.s.bytesToTrim!=null?s=e.s.file.chunkSize-e.s.bytesToTrim:e.s.options.end&&E<r.data.byteLength&&(s=E),(c!=null||s!=null)&&(u=u.slice(c||0,s||u.byteLength)),e.push(u)};e.s.cursor.next().then(t,r=>{e.destroyed||e.destroy(r)})}function I4(e){var i,o;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);const r=u=>{var a,E;if(e.destroyed)return;if(!u){const g=`FileNotFound: file ${e.s.filter._id?e.s.filter._id.toString():e.s.filter.filename} was not found`,m=new Et.MongoRuntimeError(g);return m.code="ENOENT",e.destroy(m)}if(u.length<=0){e.push(null);return}if(e.destroyed){e.destroy();return}try{e.s.bytesToSkip=P4(e,u,e.s.options)}catch(h){return e.destroy(h)}const c={files_id:u._id};if(e.s.options&&e.s.options.start!=null){const h=Math.floor(e.s.options.start/u.chunkSize);h>0&&(c.n={$gte:h})}let s;try{s=(E=e.s.timeoutContext)==null?void 0:E.getRemainingTimeMSOrThrow(`Download timed out after ${(a=e.s.timeoutContext)==null?void 0:a.timeoutMS}ms`)}catch(h){return e.destroy(h)}e.s.cursor=e.s.chunks.find(c,{timeoutMode:e.s.options.timeoutMS!=null?F4.CursorTimeoutMode.LIFETIME:void 0,timeoutMS:s}).sort({n:1}),e.s.readPreference&&e.s.cursor.withReadPreference(e.s.readPreference),e.s.expectedEnd=Math.ceil(u.length/u.chunkSize),e.s.file=u;try{e.s.bytesToTrim=L4(e,u,e.s.cursor,e.s.options)}catch(h){return e.destroy(h)}e.emit(no.FILE,u)};let n;try{n=(o=e.s.timeoutContext)==null?void 0:o.getRemainingTimeMSOrThrow(`Download timed out after ${(i=e.s.timeoutContext)==null?void 0:i.timeoutMS}ms`)}catch(u){e.destroyed||e.destroy(u);return}t.timeoutMS=n,e.s.files.findOne(e.s.filter,t).then(r,u=>{e.destroyed||e.destroy(u)})}function v4(e,t){if(e.s.file)return t();e.s.init||(I4(e),e.s.init=!0),e.once("file",()=>{t()})}function P4(e,t,r){if(r&&r.start!=null){if(r.start>t.length)throw new Et.MongoInvalidArgumentError(`Stream start (${r.start}) must not be more than the length of the file (${t.length})`);if(r.start<0)throw new Et.MongoInvalidArgumentError(`Stream start (${r.start}) must not be negative`);if(r.end!=null&&r.end<r.start)throw new Et.MongoInvalidArgumentError(`Stream start (${r.start}) must not be greater than stream end (${r.end})`);return e.s.bytesRead=Math.floor(r.start/t.chunkSize)*t.chunkSize,e.s.expected=Math.floor(r.start/t.chunkSize),r.start-e.s.bytesRead}throw new Et.MongoInvalidArgumentError("Start option must be defined")}function L4(e,t,r,n){if(n&&n.end!=null){if(n.end>t.length)throw new Et.MongoInvalidArgumentError(`Stream end (${n.end}) must not be more than the length of the file (${t.length})`);if(n.start==null||n.start<0)throw new Et.MongoInvalidArgumentError(`Stream end (${n.end}) must not be negative`);const i=n.start!=null?Math.floor(n.start/t.chunkSize):0;return r.limit(Math.ceil(n.end/t.chunkSize)-i),e.s.expectedEnd=Math.ceil(n.end/t.chunkSize),Math.ceil(n.end/t.chunkSize)*t.chunkSize-n.end}throw new Et.MongoInvalidArgumentError("End option must be defined")}var _i={};Object.defineProperty(_i,"__esModule",{value:!0});_i.GridFSBucketWriteStream=void 0;const k4=uo,zl=pe,Vl=rt,Lt=Q,U4=Te,Oc=ne(),j4=lt();class x4 extends k4.Writable{constructor(t,r,n){super(),this.gridFSFile=null,n=n??{},this.bucket=t,this.chunks=t.s._chunksCollection,this.filename=r,this.files=t.s._filesCollection,this.options=n,this.writeConcern=j4.WriteConcern.fromOptions(n)||t.s.options.writeConcern,this.done=!1,this.id=n.id?n.id:new zl.ObjectId,this.chunkSizeBytes=n.chunkSizeBytes||this.bucket.s.options.chunkSizeBytes,this.bufToStore=Buffer.alloc(this.chunkSizeBytes),this.length=0,this.n=0,this.pos=0,this.state={streamEnd:!1,outstandingRequests:0,errored:!1,aborted:!1},n.timeoutMS!=null&&(this.timeoutContext=new U4.CSOTTimeoutContext({timeoutMS:n.timeoutMS,serverSelectionTimeoutMS:(0,Oc.resolveTimeoutOptions)(this.bucket.s.db.client,{}).serverSelectionTimeoutMS}))}_construct(t){if(!this.bucket.s.calledOpenUploadStream)this.bucket.s.calledOpenUploadStream=!0,V4(this).then(()=>{this.bucket.s.checkedIndexes=!0,this.bucket.emit("index"),t()},r=>{if(r instanceof Lt.MongoOperationTimeoutError)return Ur(this,r,t);(0,Oc.squashError)(r),t()});else return queueMicrotask(t)}_write(t,r,n){G4(this,t,r,n)}_final(t){if(this.state.streamEnd)return queueMicrotask(t);this.state.streamEnd=!0,q4(this,t)}async abort(){var r,n;if(this.state.streamEnd)throw new Lt.MongoAPIError("Cannot abort a stream that has already completed");if(this.state.aborted)throw new Lt.MongoAPIError("Cannot call abort() on a stream twice");this.state.aborted=!0;const t=(n=this.timeoutContext)==null?void 0:n.getRemainingTimeMSOrThrow(`Upload timed out after ${(r=this.timeoutContext)==null?void 0:r.timeoutMS}ms`);await this.chunks.deleteMany({files_id:this.id},{timeoutMS:t})}}_i.GridFSBucketWriteStream=x4;function Ur(e,t,r){if(e.state.errored){queueMicrotask(r);return}e.state.errored=!0,queueMicrotask(()=>r(t))}function Wl(e,t,r){return{_id:new zl.ObjectId,files_id:e,n:t,data:r}}async function z4(e){var o,u,c,s;const t={files_id:1,n:1};let r;r=(u=e.timeoutContext)==null?void 0:u.getRemainingTimeMSOrThrow(`Upload timed out after ${(o=e.timeoutContext)==null?void 0:o.timeoutMS}ms`);let n;try{n=await e.chunks.listIndexes({timeoutMode:r!=null?Vl.CursorTimeoutMode.LIFETIME:void 0,timeoutMS:r}).toArray()}catch(a){if(a instanceof Lt.MongoError&&a.code===Lt.MONGODB_ERROR_CODES.NamespaceNotFound)n=[];else throw a}!!n.find(a=>Object.keys(a.key).length===2&&a.key.files_id===1&&a.key.n===1)||(r=(s=e.timeoutContext)==null?void 0:s.getRemainingTimeMSOrThrow(`Upload timed out after ${(c=e.timeoutContext)==null?void 0:c.timeoutMS}ms`),await e.chunks.createIndex(t,{...e.writeConcern,background:!0,unique:!0,timeoutMS:r}))}function O1(e,t){var r,n;if(e.done)return queueMicrotask(t);if(e.state.streamEnd&&e.state.outstandingRequests===0&&!e.state.errored){e.done=!0;const i=W4(e.id,e.length,e.chunkSizeBytes,e.filename,e.options.metadata);if(io(e,t))return;const o=(r=e.timeoutContext)==null?void 0:r.remainingTimeMS;if(o!=null&&o<=0)return Ur(e,new Lt.MongoOperationTimeoutError(`Upload timed out after ${(n=e.timeoutContext)==null?void 0:n.timeoutMS}ms`),t);e.files.insertOne(i,{writeConcern:e.writeConcern,timeoutMS:o}).then(()=>{e.gridFSFile=i,t()},u=>Ur(e,u,t));return}queueMicrotask(t)}async function V4(e){var c,s,a,E,h,g;let t=(s=e.timeoutContext)==null?void 0:s.getRemainingTimeMSOrThrow(`Upload timed out after ${(c=e.timeoutContext)==null?void 0:c.timeoutMS}ms`);if(await e.files.findOne({},{projection:{_id:1},timeoutMS:t})!=null)return;const n={filename:1,uploadDate:1};let i;t=(E=e.timeoutContext)==null?void 0:E.getRemainingTimeMSOrThrow(`Upload timed out after ${(a=e.timeoutContext)==null?void 0:a.timeoutMS}ms`);const o={timeoutMode:t!=null?Vl.CursorTimeoutMode.LIFETIME:void 0,timeoutMS:t};try{i=await e.files.listIndexes(o).toArray()}catch(m){if(m instanceof Lt.MongoError&&m.code===Lt.MONGODB_ERROR_CODES.NamespaceNotFound)i=[];else throw m}!!i.find(m=>Object.keys(m.key).length===2&&m.key.filename===1&&m.key.uploadDate===1)||(t=(g=e.timeoutContext)==null?void 0:g.getRemainingTimeMSOrThrow(`Upload timed out after ${(h=e.timeoutContext)==null?void 0:h.timeoutMS}ms`),await e.files.createIndex(n,{background:!1,timeoutMS:t})),await z4(e)}function W4(e,t,r,n,i){const o={_id:e,length:t,chunkSize:r,uploadDate:new Date,filename:n};return i&&(o.metadata=i),o}function G4(e,t,r,n){var a,E;if(io(e,n))return;const i=Buffer.isBuffer(t)?t:Buffer.from(t,r);if(e.length+=i.length,e.pos+i.length<e.chunkSizeBytes){i.copy(e.bufToStore,e.pos),e.pos+=i.length,queueMicrotask(n);return}let o=i.length,u=e.chunkSizeBytes-e.pos,c=Math.min(u,i.length),s=0;for(;o>0;){const h=i.length-o;i.copy(e.bufToStore,e.pos,h,h+c),e.pos+=c,u-=c;let g;if(u===0){g=Wl(e.id,e.n,Buffer.from(e.bufToStore));const m=(a=e.timeoutContext)==null?void 0:a.remainingTimeMS;if(m!=null&&m<=0)return Ur(e,new Lt.MongoOperationTimeoutError(`Upload timed out after ${(E=e.timeoutContext)==null?void 0:E.timeoutMS}ms`),n);if(++e.state.outstandingRequests,++s,io(e,n))return;e.chunks.insertOne(g,{writeConcern:e.writeConcern,timeoutMS:m}).then(()=>{--e.state.outstandingRequests,--s,s||O1(e,n)},C=>Ur(e,C,n)),u=e.chunkSizeBytes,e.pos=0,++e.n}o-=c,c=Math.min(u,o)}}function q4(e,t){var o,u;if(e.pos===0)return O1(e,t);const r=Buffer.alloc(e.pos);e.bufToStore.copy(r,0,0,e.pos);const n=Wl(e.id,e.n,r);if(io(e,t))return;const i=(o=e.timeoutContext)==null?void 0:o.remainingTimeMS;if(i!=null&&i<=0)return Ur(e,new Lt.MongoOperationTimeoutError(`Upload timed out after ${(u=e.timeoutContext)==null?void 0:u.timeoutMS}ms`),t);++e.state.outstandingRequests,e.chunks.insertOne(n,{writeConcern:e.writeConcern,timeoutMS:i}).then(()=>{--e.state.outstandingRequests,O1(e,t)},c=>Ur(e,c,t))}function io(e,t){return e.state.aborted?(queueMicrotask(()=>t(new Lt.MongoAPIError("Stream has been aborted"))),!0):!1}Object.defineProperty($o,"__esModule",{value:!0});$o.GridFSBucket=void 0;const u1=Q,H4=Qe,wc=Te,Ui=ne(),K4=lt(),_c=wi,Dc=_i,Y4={bucketName:"fs",chunkSizeBytes:255*1024},bu=class bu extends H4.TypedEventEmitter{constructor(t,r){super(),this.on("error",Ui.noop),this.setMaxListeners(0);const n=(0,Ui.resolveOptions)(t,{...Y4,...r,writeConcern:K4.WriteConcern.fromOptions(r)});this.s={db:t,options:n,_chunksCollection:t.collection(n.bucketName+".chunks"),_filesCollection:t.collection(n.bucketName+".files"),checkedIndexes:!1,calledOpenUploadStream:!1}}openUploadStream(t,r){return new Dc.GridFSBucketWriteStream(this,t,{timeoutMS:this.s.options.timeoutMS,...r})}openUploadStreamWithId(t,r,n){return new Dc.GridFSBucketWriteStream(this,r,{timeoutMS:this.s.options.timeoutMS,...n,id:t})}openDownloadStream(t,r){return new _c.GridFSBucketReadStream(this.s._chunksCollection,this.s._filesCollection,this.s.options.readPreference,{_id:t},{timeoutMS:this.s.options.timeoutMS,...r})}async delete(t,r){const{timeoutMS:n}=(0,Ui.resolveOptions)(this.s.db,r);let i;n&&(i=new wc.CSOTTimeoutContext({timeoutMS:n,serverSelectionTimeoutMS:this.s.db.client.s.options.serverSelectionTimeoutMS}));const{deletedCount:o}=await this.s._filesCollection.deleteOne({_id:t},{timeoutMS:i==null?void 0:i.remainingTimeMS}),u=i==null?void 0:i.remainingTimeMS;if(u!=null&&u<=0)throw new u1.MongoOperationTimeoutError(`Timed out after ${n}ms`);if(await this.s._chunksCollection.deleteMany({files_id:t},{timeoutMS:u}),o===0)throw new u1.MongoRuntimeError(`File not found for id ${t}`)}find(t={},r={}){return this.s._filesCollection.find(t,r)}openDownloadStreamByName(t,r){let n={uploadDate:-1},i;return r&&r.revision!=null&&(r.revision>=0?(n={uploadDate:1},i=r.revision):i=-r.revision-1),new _c.GridFSBucketReadStream(this.s._chunksCollection,this.s._filesCollection,this.s.options.readPreference,{filename:t},{timeoutMS:this.s.options.timeoutMS,...r,sort:n,skip:i})}async rename(t,r,n){const i={_id:t},o={$set:{filename:r}},{matchedCount:u}=await this.s._filesCollection.updateOne(i,o,n);if(u===0)throw new u1.MongoRuntimeError(`File with id ${t} not found`)}async drop(t){const{timeoutMS:r}=(0,Ui.resolveOptions)(this.s.db,t);let n;if(r&&(n=new wc.CSOTTimeoutContext({timeoutMS:r,serverSelectionTimeoutMS:this.s.db.client.s.options.serverSelectionTimeoutMS})),n){await this.s._filesCollection.drop({timeoutMS:n.remainingTimeMS});const i=n.getRemainingTimeMSOrThrow(`Timed out after ${r}ms`);await this.s._chunksCollection.drop({timeoutMS:i})}else await this.s._filesCollection.drop(),await this.s._chunksCollection.drop()}};bu.INDEX="index";let w1=bu;$o.GridFSBucket=w1;var Tc;function es(){return Tc||(Tc=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.MongoRuntimeError=e.MongoParseError=e.MongoOperationTimeoutError=e.MongoOIDCError=e.MongoNotConnectedError=e.MongoNetworkTimeoutError=e.MongoNetworkError=e.MongoMissingDependencyError=e.MongoMissingCredentialsError=e.MongoKerberosError=e.MongoInvalidArgumentError=e.MongoGridFSStreamError=e.MongoGridFSChunkError=e.MongoGCPError=e.MongoExpiredSessionError=e.MongoError=e.MongoDriverError=e.MongoDecompressionError=e.MongoCursorInUseError=e.MongoCursorExhaustedError=e.MongoCompatibilityError=e.MongoClientClosedError=e.MongoClientBulkWriteExecutionError=e.MongoClientBulkWriteError=e.MongoClientBulkWriteCursorError=e.MongoChangeStreamError=e.MongoBatchReExecutionError=e.MongoAzureError=e.MongoAWSError=e.MongoAPIError=e.ExplainableCursor=e.ChangeStreamCursor=e.ClientEncryption=e.MongoBulkWriteError=e.UUID=e.Timestamp=e.ObjectId=e.MinKey=e.MaxKey=e.Long=e.Int32=e.Double=e.Decimal128=e.DBRef=e.Code=e.BSONType=e.BSONSymbol=e.BSONRegExp=e.Binary=e.BSON=void 0,e.CommandStartedEvent=e.CommandFailedEvent=e.WriteConcern=e.ReadPreference=e.ReadConcern=e.TopologyType=e.ServerType=e.ReadPreferenceMode=e.ReadConcernLevel=e.ProfilingLevel=e.ReturnDocument=e.SeverityLevel=e.MongoLoggableComponent=e.ServerApiVersion=e.ExplainVerbosity=e.MongoErrorLabel=e.CursorTimeoutMode=e.CURSOR_FLAGS=e.Compressor=e.AuthMechanism=e.GSSAPICanonicalizationValue=e.AutoEncryptionLoggerLevel=e.BatchType=e.UnorderedBulkOperation=e.OrderedBulkOperation=e.MongoClient=e.ListIndexesCursor=e.ListCollectionsCursor=e.GridFSBucketWriteStream=e.GridFSBucketReadStream=e.GridFSBucket=e.FindCursor=e.Db=e.Collection=e.ClientSession=e.ChangeStream=e.CancellationToken=e.AggregationCursor=e.Admin=e.AbstractCursor=e.MongoWriteConcernError=e.MongoUnexpectedServerResponseError=e.MongoTransactionError=e.MongoTopologyClosedError=e.MongoTailableCursorError=e.MongoSystemError=e.MongoStalePrimaryError=e.MongoServerSelectionError=e.MongoServerError=e.MongoServerClosedError=void 0,e.MongoClientAuthProviders=e.MongoCryptKMSRequestNetworkTimeoutError=e.MongoCryptInvalidArgumentError=e.MongoCryptError=e.MongoCryptCreateEncryptedCollectionError=e.MongoCryptCreateDataKeyError=e.MongoCryptAzureKMSRequestError=e.SrvPollingEvent=e.WaitingForSuitableServerEvent=e.ServerSelectionSucceededEvent=e.ServerSelectionStartedEvent=e.ServerSelectionFailedEvent=e.ServerSelectionEvent=e.TopologyOpeningEvent=e.TopologyDescriptionChangedEvent=e.TopologyClosedEvent=e.ServerOpeningEvent=e.ServerHeartbeatSucceededEvent=e.ServerHeartbeatStartedEvent=e.ServerHeartbeatFailedEvent=e.ServerDescriptionChangedEvent=e.ServerClosedEvent=e.ConnectionReadyEvent=e.ConnectionPoolReadyEvent=e.ConnectionPoolMonitoringEvent=e.ConnectionPoolCreatedEvent=e.ConnectionPoolClosedEvent=e.ConnectionPoolClearedEvent=e.ConnectionCreatedEvent=e.ConnectionClosedEvent=e.ConnectionCheckOutStartedEvent=e.ConnectionCheckOutFailedEvent=e.ConnectionCheckedOutEvent=e.ConnectionCheckedInEvent=e.CommandSucceededEvent=void 0;const t=$n;Object.defineProperty(e,"Admin",{enumerable:!0,get:function(){return t.Admin}});const r=si;Object.defineProperty(e,"OrderedBulkOperation",{enumerable:!0,get:function(){return r.OrderedBulkOperation}});const n=ai;Object.defineProperty(e,"UnorderedBulkOperation",{enumerable:!0,get:function(){return n.UnorderedBulkOperation}});const i=Oi();Object.defineProperty(e,"ChangeStream",{enumerable:!0,get:function(){return i.ChangeStream}});const o=fi();Object.defineProperty(e,"Collection",{enumerable:!0,get:function(){return o.Collection}});const u=rt;Object.defineProperty(e,"AbstractCursor",{enumerable:!0,get:function(){return u.AbstractCursor}});const c=Gr;Object.defineProperty(e,"AggregationCursor",{enumerable:!0,get:function(){return c.AggregationCursor}});const s=Pr;Object.defineProperty(e,"FindCursor",{enumerable:!0,get:function(){return s.FindCursor}});const a=mi;Object.defineProperty(e,"ListCollectionsCursor",{enumerable:!0,get:function(){return a.ListCollectionsCursor}});const E=di;Object.defineProperty(e,"ListIndexesCursor",{enumerable:!0,get:function(){return E.ListIndexesCursor}});const h=Z1();Object.defineProperty(e,"Db",{enumerable:!0,get:function(){return h.Db}});const g=$o;Object.defineProperty(e,"GridFSBucket",{enumerable:!0,get:function(){return g.GridFSBucket}});const m=wi;Object.defineProperty(e,"GridFSBucketReadStream",{enumerable:!0,get:function(){return m.GridFSBucketReadStream}});const C=_i;Object.defineProperty(e,"GridFSBucketWriteStream",{enumerable:!0,get:function(){return C.GridFSBucketWriteStream}});const S=mn();Object.defineProperty(e,"MongoClient",{enumerable:!0,get:function(){return S.MongoClient}});const D=Qe;Object.defineProperty(e,"CancellationToken",{enumerable:!0,get:function(){return D.CancellationToken}});const O=at;Object.defineProperty(e,"ClientSession",{enumerable:!0,get:function(){return O.ClientSession}});var M=pe;Object.defineProperty(e,"BSON",{enumerable:!0,get:function(){return M.BSON}});var p=pe;Object.defineProperty(e,"Binary",{enumerable:!0,get:function(){return p.Binary}}),Object.defineProperty(e,"BSONRegExp",{enumerable:!0,get:function(){return p.BSONRegExp}}),Object.defineProperty(e,"BSONSymbol",{enumerable:!0,get:function(){return p.BSONSymbol}}),Object.defineProperty(e,"BSONType",{enumerable:!0,get:function(){return p.BSONType}}),Object.defineProperty(e,"Code",{enumerable:!0,get:function(){return p.Code}}),Object.defineProperty(e,"DBRef",{enumerable:!0,get:function(){return p.DBRef}}),Object.defineProperty(e,"Decimal128",{enumerable:!0,get:function(){return p.Decimal128}}),Object.defineProperty(e,"Double",{enumerable:!0,get:function(){return p.Double}}),Object.defineProperty(e,"Int32",{enumerable:!0,get:function(){return p.Int32}}),Object.defineProperty(e,"Long",{enumerable:!0,get:function(){return p.Long}}),Object.defineProperty(e,"MaxKey",{enumerable:!0,get:function(){return p.MaxKey}}),Object.defineProperty(e,"MinKey",{enumerable:!0,get:function(){return p.MinKey}}),Object.defineProperty(e,"ObjectId",{enumerable:!0,get:function(){return p.ObjectId}}),Object.defineProperty(e,"Timestamp",{enumerable:!0,get:function(){return p.Timestamp}}),Object.defineProperty(e,"UUID",{enumerable:!0,get:function(){return p.UUID}});var B=Kn;Object.defineProperty(e,"MongoBulkWriteError",{enumerable:!0,get:function(){return B.MongoBulkWriteError}});var d=Au();Object.defineProperty(e,"ClientEncryption",{enumerable:!0,get:function(){return d.ClientEncryption}});var b=k0();Object.defineProperty(e,"ChangeStreamCursor",{enumerable:!0,get:function(){return b.ChangeStreamCursor}});var f=Cn;Object.defineProperty(e,"ExplainableCursor",{enumerable:!0,get:function(){return f.ExplainableCursor}});var l=Q;Object.defineProperty(e,"MongoAPIError",{enumerable:!0,get:function(){return l.MongoAPIError}}),Object.defineProperty(e,"MongoAWSError",{enumerable:!0,get:function(){return l.MongoAWSError}}),Object.defineProperty(e,"MongoAzureError",{enumerable:!0,get:function(){return l.MongoAzureError}}),Object.defineProperty(e,"MongoBatchReExecutionError",{enumerable:!0,get:function(){return l.MongoBatchReExecutionError}}),Object.defineProperty(e,"MongoChangeStreamError",{enumerable:!0,get:function(){return l.MongoChangeStreamError}}),Object.defineProperty(e,"MongoClientBulkWriteCursorError",{enumerable:!0,get:function(){return l.MongoClientBulkWriteCursorError}}),Object.defineProperty(e,"MongoClientBulkWriteError",{enumerable:!0,get:function(){return l.MongoClientBulkWriteError}}),Object.defineProperty(e,"MongoClientBulkWriteExecutionError",{enumerable:!0,get:function(){return l.MongoClientBulkWriteExecutionError}}),Object.defineProperty(e,"MongoClientClosedError",{enumerable:!0,get:function(){return l.MongoClientClosedError}}),Object.defineProperty(e,"MongoCompatibilityError",{enumerable:!0,get:function(){return l.MongoCompatibilityError}}),Object.defineProperty(e,"MongoCursorExhaustedError",{enumerable:!0,get:function(){return l.MongoCursorExhaustedError}}),Object.defineProperty(e,"MongoCursorInUseError",{enumerable:!0,get:function(){return l.MongoCursorInUseError}}),Object.defineProperty(e,"MongoDecompressionError",{enumerable:!0,get:function(){return l.MongoDecompressionError}}),Object.defineProperty(e,"MongoDriverError",{enumerable:!0,get:function(){return l.MongoDriverError}}),Object.defineProperty(e,"MongoError",{enumerable:!0,get:function(){return l.MongoError}}),Object.defineProperty(e,"MongoExpiredSessionError",{enumerable:!0,get:function(){return l.MongoExpiredSessionError}}),Object.defineProperty(e,"MongoGCPError",{enumerable:!0,get:function(){return l.MongoGCPError}}),Object.defineProperty(e,"MongoGridFSChunkError",{enumerable:!0,get:function(){return l.MongoGridFSChunkError}}),Object.defineProperty(e,"MongoGridFSStreamError",{enumerable:!0,get:function(){return l.MongoGridFSStreamError}}),Object.defineProperty(e,"MongoInvalidArgumentError",{enumerable:!0,get:function(){return l.MongoInvalidArgumentError}}),Object.defineProperty(e,"MongoKerberosError",{enumerable:!0,get:function(){return l.MongoKerberosError}}),Object.defineProperty(e,"MongoMissingCredentialsError",{enumerable:!0,get:function(){return l.MongoMissingCredentialsError}}),Object.defineProperty(e,"MongoMissingDependencyError",{enumerable:!0,get:function(){return l.MongoMissingDependencyError}}),Object.defineProperty(e,"MongoNetworkError",{enumerable:!0,get:function(){return l.MongoNetworkError}}),Object.defineProperty(e,"MongoNetworkTimeoutError",{enumerable:!0,get:function(){return l.MongoNetworkTimeoutError}}),Object.defineProperty(e,"MongoNotConnectedError",{enumerable:!0,get:function(){return l.MongoNotConnectedError}}),Object.defineProperty(e,"MongoOIDCError",{enumerable:!0,get:function(){return l.MongoOIDCError}}),Object.defineProperty(e,"MongoOperationTimeoutError",{enumerable:!0,get:function(){return l.MongoOperationTimeoutError}}),Object.defineProperty(e,"MongoParseError",{enumerable:!0,get:function(){return l.MongoParseError}}),Object.defineProperty(e,"MongoRuntimeError",{enumerable:!0,get:function(){return l.MongoRuntimeError}}),Object.defineProperty(e,"MongoServerClosedError",{enumerable:!0,get:function(){return l.MongoServerClosedError}}),Object.defineProperty(e,"MongoServerError",{enumerable:!0,get:function(){return l.MongoServerError}}),Object.defineProperty(e,"MongoServerSelectionError",{enumerable:!0,get:function(){return l.MongoServerSelectionError}}),Object.defineProperty(e,"MongoStalePrimaryError",{enumerable:!0,get:function(){return l.MongoStalePrimaryError}}),Object.defineProperty(e,"MongoSystemError",{enumerable:!0,get:function(){return l.MongoSystemError}}),Object.defineProperty(e,"MongoTailableCursorError",{enumerable:!0,get:function(){return l.MongoTailableCursorError}}),Object.defineProperty(e,"MongoTopologyClosedError",{enumerable:!0,get:function(){return l.MongoTopologyClosedError}}),Object.defineProperty(e,"MongoTransactionError",{enumerable:!0,get:function(){return l.MongoTransactionError}}),Object.defineProperty(e,"MongoUnexpectedServerResponseError",{enumerable:!0,get:function(){return l.MongoUnexpectedServerResponseError}}),Object.defineProperty(e,"MongoWriteConcernError",{enumerable:!0,get:function(){return l.MongoWriteConcernError}});var w=Kn;Object.defineProperty(e,"BatchType",{enumerable:!0,get:function(){return w.BatchType}});var T=El();Object.defineProperty(e,"AutoEncryptionLoggerLevel",{enumerable:!0,get:function(){return T.AutoEncryptionLoggerLevel}});var _=Fo;Object.defineProperty(e,"GSSAPICanonicalizationValue",{enumerable:!0,get:function(){return _.GSSAPICanonicalizationValue}});var A=Ht;Object.defineProperty(e,"AuthMechanism",{enumerable:!0,get:function(){return A.AuthMechanism}});var y=Po();Object.defineProperty(e,"Compressor",{enumerable:!0,get:function(){return y.Compressor}});var F=rt;Object.defineProperty(e,"CURSOR_FLAGS",{enumerable:!0,get:function(){return F.CURSOR_FLAGS}}),Object.defineProperty(e,"CursorTimeoutMode",{enumerable:!0,get:function(){return F.CursorTimeoutMode}});var R=Q;Object.defineProperty(e,"MongoErrorLabel",{enumerable:!0,get:function(){return R.MongoErrorLabel}});var v=ii;Object.defineProperty(e,"ExplainVerbosity",{enumerable:!0,get:function(){return v.ExplainVerbosity}});var J=mn();Object.defineProperty(e,"ServerApiVersion",{enumerable:!0,get:function(){return J.ServerApiVersion}});var I=pr;Object.defineProperty(e,"MongoLoggableComponent",{enumerable:!0,get:function(){return I.MongoLoggableComponent}}),Object.defineProperty(e,"SeverityLevel",{enumerable:!0,get:function(){return I.SeverityLevel}});var N=X1;Object.defineProperty(e,"ReturnDocument",{enumerable:!0,get:function(){return N.ReturnDocument}});var j=Q1;Object.defineProperty(e,"ProfilingLevel",{enumerable:!0,get:function(){return j.ProfilingLevel}});var x=kt;Object.defineProperty(e,"ReadConcernLevel",{enumerable:!0,get:function(){return x.ReadConcernLevel}});var Y=Ke;Object.defineProperty(e,"ReadPreferenceMode",{enumerable:!0,get:function(){return Y.ReadPreferenceMode}});var $=Ne;Object.defineProperty(e,"ServerType",{enumerable:!0,get:function(){return $.ServerType}}),Object.defineProperty(e,"TopologyType",{enumerable:!0,get:function(){return $.TopologyType}});var K=kt;Object.defineProperty(e,"ReadConcern",{enumerable:!0,get:function(){return K.ReadConcern}});var ee=Ke;Object.defineProperty(e,"ReadPreference",{enumerable:!0,get:function(){return ee.ReadPreference}});var ae=lt();Object.defineProperty(e,"WriteConcern",{enumerable:!0,get:function(){return ae.WriteConcern}});var ye=Cu;Object.defineProperty(e,"CommandFailedEvent",{enumerable:!0,get:function(){return ye.CommandFailedEvent}}),Object.defineProperty(e,"CommandStartedEvent",{enumerable:!0,get:function(){return ye.CommandStartedEvent}}),Object.defineProperty(e,"CommandSucceededEvent",{enumerable:!0,get:function(){return ye.CommandSucceededEvent}});var ce=Fe;Object.defineProperty(e,"ConnectionCheckedInEvent",{enumerable:!0,get:function(){return ce.ConnectionCheckedInEvent}}),Object.defineProperty(e,"ConnectionCheckedOutEvent",{enumerable:!0,get:function(){return ce.ConnectionCheckedOutEvent}}),Object.defineProperty(e,"ConnectionCheckOutFailedEvent",{enumerable:!0,get:function(){return ce.ConnectionCheckOutFailedEvent}}),Object.defineProperty(e,"ConnectionCheckOutStartedEvent",{enumerable:!0,get:function(){return ce.ConnectionCheckOutStartedEvent}}),Object.defineProperty(e,"ConnectionClosedEvent",{enumerable:!0,get:function(){return ce.ConnectionClosedEvent}}),Object.defineProperty(e,"ConnectionCreatedEvent",{enumerable:!0,get:function(){return ce.ConnectionCreatedEvent}}),Object.defineProperty(e,"ConnectionPoolClearedEvent",{enumerable:!0,get:function(){return ce.ConnectionPoolClearedEvent}}),Object.defineProperty(e,"ConnectionPoolClosedEvent",{enumerable:!0,get:function(){return ce.ConnectionPoolClosedEvent}}),Object.defineProperty(e,"ConnectionPoolCreatedEvent",{enumerable:!0,get:function(){return ce.ConnectionPoolCreatedEvent}}),Object.defineProperty(e,"ConnectionPoolMonitoringEvent",{enumerable:!0,get:function(){return ce.ConnectionPoolMonitoringEvent}}),Object.defineProperty(e,"ConnectionPoolReadyEvent",{enumerable:!0,get:function(){return ce.ConnectionPoolReadyEvent}}),Object.defineProperty(e,"ConnectionReadyEvent",{enumerable:!0,get:function(){return ce.ConnectionReadyEvent}});var le=Ue;Object.defineProperty(e,"ServerClosedEvent",{enumerable:!0,get:function(){return le.ServerClosedEvent}}),Object.defineProperty(e,"ServerDescriptionChangedEvent",{enumerable:!0,get:function(){return le.ServerDescriptionChangedEvent}}),Object.defineProperty(e,"ServerHeartbeatFailedEvent",{enumerable:!0,get:function(){return le.ServerHeartbeatFailedEvent}}),Object.defineProperty(e,"ServerHeartbeatStartedEvent",{enumerable:!0,get:function(){return le.ServerHeartbeatStartedEvent}}),Object.defineProperty(e,"ServerHeartbeatSucceededEvent",{enumerable:!0,get:function(){return le.ServerHeartbeatSucceededEvent}}),Object.defineProperty(e,"ServerOpeningEvent",{enumerable:!0,get:function(){return le.ServerOpeningEvent}}),Object.defineProperty(e,"TopologyClosedEvent",{enumerable:!0,get:function(){return le.TopologyClosedEvent}}),Object.defineProperty(e,"TopologyDescriptionChangedEvent",{enumerable:!0,get:function(){return le.TopologyDescriptionChangedEvent}}),Object.defineProperty(e,"TopologyOpeningEvent",{enumerable:!0,get:function(){return le.TopologyOpeningEvent}});var he=mt;Object.defineProperty(e,"ServerSelectionEvent",{enumerable:!0,get:function(){return he.ServerSelectionEvent}}),Object.defineProperty(e,"ServerSelectionFailedEvent",{enumerable:!0,get:function(){return he.ServerSelectionFailedEvent}}),Object.defineProperty(e,"ServerSelectionStartedEvent",{enumerable:!0,get:function(){return he.ServerSelectionStartedEvent}}),Object.defineProperty(e,"ServerSelectionSucceededEvent",{enumerable:!0,get:function(){return he.ServerSelectionSucceededEvent}}),Object.defineProperty(e,"WaitingForSuitableServerEvent",{enumerable:!0,get:function(){return he.WaitingForSuitableServerEvent}});var Ee=kr;Object.defineProperty(e,"SrvPollingEvent",{enumerable:!0,get:function(){return Ee.SrvPollingEvent}});var re=Ge;Object.defineProperty(e,"MongoCryptAzureKMSRequestError",{enumerable:!0,get:function(){return re.MongoCryptAzureKMSRequestError}}),Object.defineProperty(e,"MongoCryptCreateDataKeyError",{enumerable:!0,get:function(){return re.MongoCryptCreateDataKeyError}}),Object.defineProperty(e,"MongoCryptCreateEncryptedCollectionError",{enumerable:!0,get:function(){return re.MongoCryptCreateEncryptedCollectionError}}),Object.defineProperty(e,"MongoCryptError",{enumerable:!0,get:function(){return re.MongoCryptError}}),Object.defineProperty(e,"MongoCryptInvalidArgumentError",{enumerable:!0,get:function(){return re.MongoCryptInvalidArgumentError}}),Object.defineProperty(e,"MongoCryptKMSRequestNetworkTimeoutError",{enumerable:!0,get:function(){return re.MongoCryptKMSRequestNetworkTimeoutError}});var Ce=pi;Object.defineProperty(e,"MongoClientAuthProviders",{enumerable:!0,get:function(){return Ce.MongoClientAuthProviders}})}(ns)),ns}var a1=es();class X4{constructor(t,r,n,i){se(this,"client");se(this,"schemaMeta");se(this,"context");se(this,"fieldMetaMap",{});se(this,"idField","_id");se(this,"dbName","");se(this,"session");this.client=t,this.schemaMeta=r,this.context=n,this.session=i,this.dbName=t.options.dbName,this.fieldMetaMap=Object.entries(r).reduce((o,[u,c])=>(o[u]=c.columns.reduce((s,a)=>(s[a.name]=a,s),{}),o),{})}getObjectId(t){return new a1.ObjectId(t)}getCollection(t){return this.client.db(this.dbName).collection(t)}normalizeId(t){return typeof t=="string"&&a1.ObjectId.isValid(t)?new a1.ObjectId(t):t}buildSort(t){const r={};return t.forEach(n=>{r[n.fieldName]=n.order==="asc"?1:-1}),r}buildFindOptions(t){const r={};if(t!=null&&t.select&&(r.projection=t.select),(t==null?void 0:t.offset)!=null&&(r.skip=t.offset),(t==null?void 0:t.limit)!=null&&(r.limit=t.limit),t!=null&&t.orderBy){const n=pt.QueryBuilder.getOrderByArray(t.orderBy);n.length>0&&(r.sort=this.buildSort(n))}return r}transformResultData(t){return t&&pt.isPlainObject(t)?Object.entries(t).reduce((r,[n,i])=>{var o;return n===this.idField&&typeof i=="object"&&i?r[n]=((o=i==null?void 0:i.toString)==null?void 0:o.call(i))??i:r[n]=i,r},{}):t}async findUnique(t,{where:r,select:n}){const i=this.getCollection(t),o=Object.keys(r??{});if(o.length===1&&o[0]===this.idField){const a={[this.idField]:this.normalizeId(r[this.idField])},E={};n&&(E.projection=n);const h=await i.findOne(a,{...E,session:this.session});return this.transformResultData(h)}const u=pt.QueryBuilder.buildMongodbQuery(r,this.fieldMetaMap[t],this.getObjectId),c={};n&&(c.projection=n);const s=await i.find(u,{...c,limit:1,session:this.session}).toArray();return this.transformResultData(s[0]??null)}async findUniqueOrThrow(t,{where:r,select:n}){const i=await this.findUnique(t,{where:r,select:n});if(!i)throw new Error("Data Not Found");return i}async findFirst(t,r){const n=this.getCollection(t),i=pt.QueryBuilder.buildMongodbQuery((r==null?void 0:r.where)??{},this.fieldMetaMap[t],this.getObjectId),o=this.buildFindOptions({...r,limit:1}),u=await n.findOne(i,{...o,session:this.session});return this.transformResultData(u)}async findFirstOrThrow(t,r){const n=await this.findFirst(t,r);if(!n)throw new Error("Data Not Found");return n}async findManyInner(t,r){const n=this.getCollection(t),i=pt.QueryBuilder.buildMongodbQuery((r==null?void 0:r.where)??{},this.fieldMetaMap[t],this.getObjectId),o=this.buildFindOptions(r);return{data:(await n.find(i,{...o,session:this.session}).toArray()).map(c=>this.transformResultData(c))}}async findMany(t,r){const n=r==null?void 0:r.where,i=r==null?void 0:r.orderBy,o=r==null?void 0:r.select,{data:u}=await this.findManyInner(t,{where:n,orderBy:i,select:o,limit:1e3,offset:0});return u}async findPage(t,r){const i=(r==null?void 0:r.limit)||10;if(i>1e3)throw new Error("limit must be less than or equal to 1000");const o=r==null?void 0:r.where,u=r==null?void 0:r.orderBy,c=(r==null?void 0:r.page)||1,s=r==null?void 0:r.select,a=(c-1)*i,E=this.findManyInner(t,{where:o,orderBy:u,select:s,limit:i,offset:a}),h=this.count(t,{where:o}),{data:g}=await E,m=await h,C=Math.ceil(m/i);return{data:g,total:m,page:c,pageCount:C,limit:i,hasPrev:c>1,hasNext:c<C}}async create(t,{data:r}){const n=this.getCollection(t),i=pt.applyDefaultValues(r,this.schemaMeta[t],this.context);return{_id:(await n.insertOne(i,{session:this.session})).insertedId.toString()}}transformUpdateData(t){const r=["$set","$inc","$mul","$remove","$push","$pop","$unshift","$shift"];return Object.entries(t??[]).reduce((n,[i,o])=>(i==="$set"||(r.includes(i)?n[i]=o:n.$set[i]=o),n),{$set:{...(t==null?void 0:t.$set)??{}}})}async update(t,{where:r,data:n}){const i=this.getCollection(t),o=this.transformUpdateData(pt.applyUpdateValues(n,this.schemaMeta[t])),u=Object.keys(r??{});if(u.length===1&&u[0]===this.idField){const s={[this.idField]:this.normalizeId(r[this.idField])};await i.updateOne(s,o,{session:this.session});return}const c=pt.QueryBuilder.buildMongodbQuery(r,this.fieldMetaMap[t],this.getObjectId);await i.updateMany(c,o,{session:this.session})}async updateAndReturn(t,{where:r,data:n}){const i=this.getCollection(t),o=this.transformUpdateData(pt.applyUpdateValues(n,this.schemaMeta[t])),u=pt.QueryBuilder.buildMongodbQuery(r,this.fieldMetaMap[t],this.getObjectId),c=await i.findOneAndUpdate(u,o,{session:this.session,returnDocument:"after"});return this.transformResultData(c??null)}async delete(t,{where:r}){const n=this.getCollection(t),i=Object.keys(r??{});if(i.length===1&&i[0]===this.idField){const u={[this.idField]:this.normalizeId(r[this.idField])};await n.deleteOne(u,{session:this.session});return}const o=pt.QueryBuilder.buildMongodbQuery(r,this.fieldMetaMap[t],this.getObjectId);await n.deleteMany(o,{session:this.session})}async count(t,r){try{const n=this.getCollection(t),i=pt.QueryBuilder.buildMongodbQuery((r==null?void 0:r.where)??{},this.fieldMetaMap[t],this.getObjectId);return await n.countDocuments(i,{session:this.session})}catch(n){throw console.error("count error:",n),n}}async aggregate(t,r){const i=await this.getCollection(t).aggregate(r,{session:this.session}).toArray();return(i==null?void 0:i.map(o=>this.transformResultData(o)))??[]}}function Gl(e,t,r,n){const i=new X4(e,t,r,n),o={$dbClient:e};return Object.keys(t).forEach(u=>{o[u]={findUnique:c=>i.findUnique(u,c),findUniqueOrThrow:c=>i.findUniqueOrThrow(u,c),findFirst:c=>i.findFirst(u,c),findFirstOrThrow:c=>i.findFirstOrThrow(u,c),findMany:c=>i.findMany(u,c),findPage:c=>i.findPage(u,c),create:c=>i.create(u,c),update:c=>i.update(u,c),updateMany:c=>i.update(u,c),updateAndReturn:c=>i.updateAndReturn(u,c),delete:c=>i.delete(u,c),deleteMany:c=>i.delete(u,c),count:c=>i.count(u,c),aggregate:c=>i.aggregate(u,c)}}),o.$transaction=async u=>{const c=e.startSession();try{c.startTransaction();const s=Gl(e,t,r,c);s.$transaction=void 0;const a=await u(s);return await c.commitTransaction(),await c.endSession(),a}catch(s){throw await c.abortTransaction(),await c.endSession(),s}},o}function J4(e,t,r){return Gl(e,t,r)}exports.createMongoDBClient=J4;
|