@point-hub/papi 0.3.5 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -10822,16 +10822,6 @@ var require_error = __commonJS((exports) => {
10822
10822
  var isNetworkErrorBeforeHandshake = function(err) {
10823
10823
  return err[kBeforeHandshake] === true;
10824
10824
  };
10825
- var makeWriteConcernResultObject = function(input) {
10826
- const output = Object.assign({}, input);
10827
- if (output.ok === 0) {
10828
- output.ok = 1;
10829
- delete output.errmsg;
10830
- delete output.code;
10831
- delete output.codeName;
10832
- }
10833
- return output;
10834
- };
10835
10825
  var needsRetryableWriteLabel = function(error, maxWireVersion) {
10836
10826
  if (error instanceof MongoNetworkError) {
10837
10827
  return true;
@@ -10924,7 +10914,7 @@ var require_error = __commonJS((exports) => {
10924
10914
  return false;
10925
10915
  };
10926
10916
  Object.defineProperty(exports, "__esModule", { value: true });
10927
- exports.isResumableError = exports.isNetworkTimeoutError = exports.isSDAMUnrecoverableError = exports.isNodeShuttingDownError = exports.isRetryableReadError = exports.isRetryableWriteError = exports.needsRetryableWriteLabel = exports.MongoWriteConcernError = exports.MongoServerSelectionError = exports.MongoSystemError = exports.MongoMissingDependencyError = exports.MongoMissingCredentialsError = exports.MongoCompatibilityError = exports.MongoInvalidArgumentError = exports.MongoParseError = exports.MongoNetworkTimeoutError = exports.MongoNetworkError = exports.isNetworkErrorBeforeHandshake = exports.MongoTopologyClosedError = exports.MongoCursorExhaustedError = exports.MongoServerClosedError = exports.MongoCursorInUseError = exports.MongoUnexpectedServerResponseError = exports.MongoGridFSChunkError = exports.MongoGridFSStreamError = exports.MongoTailableCursorError = exports.MongoChangeStreamError = exports.MongoAzureError = exports.MongoAWSError = exports.MongoKerberosError = exports.MongoExpiredSessionError = exports.MongoTransactionError = exports.MongoNotConnectedError = exports.MongoDecompressionError = exports.MongoBatchReExecutionError = exports.MongoRuntimeError = exports.MongoAPIError = exports.MongoDriverError = exports.MongoServerError = exports.MongoError = exports.MongoErrorLabel = exports.GET_MORE_RESUMABLE_CODES = exports.MONGODB_ERROR_CODES = exports.NODE_IS_RECOVERING_ERROR_MESSAGE = exports.LEGACY_NOT_PRIMARY_OR_SECONDARY_ERROR_MESSAGE = exports.LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE = undefined;
10917
+ exports.isResumableError = exports.isNetworkTimeoutError = exports.isSDAMUnrecoverableError = exports.isNodeShuttingDownError = exports.isRetryableReadError = exports.isRetryableWriteError = exports.needsRetryableWriteLabel = exports.MongoWriteConcernError = exports.MongoServerSelectionError = exports.MongoSystemError = exports.MongoMissingDependencyError = exports.MongoMissingCredentialsError = exports.MongoCompatibilityError = exports.MongoInvalidArgumentError = exports.MongoParseError = exports.MongoNetworkTimeoutError = exports.MongoNetworkError = exports.isNetworkErrorBeforeHandshake = exports.MongoTopologyClosedError = exports.MongoCursorExhaustedError = exports.MongoServerClosedError = exports.MongoCursorInUseError = exports.MongoUnexpectedServerResponseError = exports.MongoGridFSChunkError = exports.MongoGridFSStreamError = exports.MongoTailableCursorError = exports.MongoChangeStreamError = exports.MongoGCPError = exports.MongoAzureError = exports.MongoOIDCError = exports.MongoAWSError = exports.MongoKerberosError = exports.MongoExpiredSessionError = exports.MongoTransactionError = exports.MongoNotConnectedError = exports.MongoDecompressionError = exports.MongoBatchReExecutionError = exports.MongoRuntimeError = exports.MongoAPIError = exports.MongoDriverError = exports.MongoServerError = exports.MongoError = exports.MongoErrorLabel = exports.GET_MORE_RESUMABLE_CODES = exports.MONGODB_ERROR_CODES = exports.NODE_IS_RECOVERING_ERROR_MESSAGE = exports.LEGACY_NOT_PRIMARY_OR_SECONDARY_ERROR_MESSAGE = exports.LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE = undefined;
10928
10918
  var kErrorLabels = Symbol("errorLabels");
10929
10919
  exports.LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE = new RegExp("not master", "i");
10930
10920
  exports.LEGACY_NOT_PRIMARY_OR_SECONDARY_ERROR_MESSAGE = new RegExp("not master or secondary", "i");
@@ -10932,6 +10922,7 @@ var require_error = __commonJS((exports) => {
10932
10922
  exports.MONGODB_ERROR_CODES = Object.freeze({
10933
10923
  HostUnreachable: 6,
10934
10924
  HostNotFound: 7,
10925
+ AuthenticationFailed: 18,
10935
10926
  NetworkTimeout: 89,
10936
10927
  ShutdownInProgress: 91,
10937
10928
  PrimarySteppedDown: 189,
@@ -10955,7 +10946,8 @@ var require_error = __commonJS((exports) => {
10955
10946
  MaxTimeMSExpired: 50,
10956
10947
  UnknownReplWriteConcern: 79,
10957
10948
  UnsatisfiableWriteConcern: 100,
10958
- Reauthenticate: 391
10949
+ Reauthenticate: 391,
10950
+ ReadConcernMajorityNotAvailableYet: 134
10959
10951
  });
10960
10952
  exports.GET_MORE_RESUMABLE_CODES = new Set([
10961
10953
  exports.MONGODB_ERROR_CODES.HostUnreachable,
@@ -11140,7 +11132,17 @@ var require_error = __commonJS((exports) => {
11140
11132
  }
11141
11133
  exports.MongoAWSError = MongoAWSError;
11142
11134
 
11143
- class MongoAzureError extends MongoRuntimeError {
11135
+ class MongoOIDCError extends MongoRuntimeError {
11136
+ constructor(message) {
11137
+ super(message);
11138
+ }
11139
+ get name() {
11140
+ return "MongoOIDCError";
11141
+ }
11142
+ }
11143
+ exports.MongoOIDCError = MongoOIDCError;
11144
+
11145
+ class MongoAzureError extends MongoOIDCError {
11144
11146
  constructor(message) {
11145
11147
  super(message);
11146
11148
  }
@@ -11150,6 +11152,16 @@ var require_error = __commonJS((exports) => {
11150
11152
  }
11151
11153
  exports.MongoAzureError = MongoAzureError;
11152
11154
 
11155
+ class MongoGCPError extends MongoOIDCError {
11156
+ constructor(message) {
11157
+ super(message);
11158
+ }
11159
+ get name() {
11160
+ return "MongoGCPError";
11161
+ }
11162
+ }
11163
+ exports.MongoGCPError = MongoGCPError;
11164
+
11153
11165
  class MongoChangeStreamError extends MongoRuntimeError {
11154
11166
  constructor(message) {
11155
11167
  super(message);
@@ -11191,8 +11203,8 @@ var require_error = __commonJS((exports) => {
11191
11203
  exports.MongoGridFSChunkError = MongoGridFSChunkError;
11192
11204
 
11193
11205
  class MongoUnexpectedServerResponseError extends MongoRuntimeError {
11194
- constructor(message) {
11195
- super(message);
11206
+ constructor(message, options) {
11207
+ super(message, options);
11196
11208
  }
11197
11209
  get name() {
11198
11210
  return "MongoUnexpectedServerResponseError";
@@ -11347,15 +11359,10 @@ var require_error = __commonJS((exports) => {
11347
11359
  exports.MongoServerSelectionError = MongoServerSelectionError;
11348
11360
 
11349
11361
  class MongoWriteConcernError extends MongoServerError {
11350
- constructor(message, result) {
11351
- if (result && Array.isArray(result.errorLabels)) {
11352
- message.errorLabels = result.errorLabels;
11353
- }
11354
- super(message);
11355
- this.errInfo = message.errInfo;
11356
- if (result != null) {
11357
- this.result = makeWriteConcernResultObject(result);
11358
- }
11362
+ constructor(result) {
11363
+ super({ ...result, ...result.writeConcernError });
11364
+ this.errInfo = result.writeConcernError.errInfo;
11365
+ this.result = result;
11359
11366
  }
11360
11367
  get name() {
11361
11368
  return "MongoWriteConcernError";
@@ -11374,7 +11381,8 @@ var require_error = __commonJS((exports) => {
11374
11381
  exports.MONGODB_ERROR_CODES.InterruptedDueToReplStateChange,
11375
11382
  exports.MONGODB_ERROR_CODES.NotPrimaryNoSecondaryOk,
11376
11383
  exports.MONGODB_ERROR_CODES.NotPrimaryOrSecondary,
11377
- exports.MONGODB_ERROR_CODES.ExceededTimeLimit
11384
+ exports.MONGODB_ERROR_CODES.ExceededTimeLimit,
11385
+ exports.MONGODB_ERROR_CODES.ReadConcernMajorityNotAvailableYet
11378
11386
  ]);
11379
11387
  var RETRYABLE_WRITE_ERROR_CODES = RETRYABLE_READ_ERROR_CODES;
11380
11388
  exports.needsRetryableWriteLabel = needsRetryableWriteLabel;
@@ -11793,7 +11801,7 @@ var require_constants = __commonJS((exports) => {
11793
11801
  var require_constants2 = __commonJS((exports) => {
11794
11802
  Object.defineProperty(exports, "__esModule", { value: true });
11795
11803
  exports.END = exports.CHANGE = exports.INIT = exports.MORE = exports.RESPONSE = exports.SERVER_HEARTBEAT_FAILED = exports.SERVER_HEARTBEAT_SUCCEEDED = exports.SERVER_HEARTBEAT_STARTED = exports.COMMAND_FAILED = exports.COMMAND_SUCCEEDED = exports.COMMAND_STARTED = exports.CLUSTER_TIME_RECEIVED = exports.CONNECTION_CHECKED_IN = exports.CONNECTION_CHECKED_OUT = exports.CONNECTION_CHECK_OUT_FAILED = exports.CONNECTION_CHECK_OUT_STARTED = exports.CONNECTION_CLOSED = exports.CONNECTION_READY = exports.CONNECTION_CREATED = exports.CONNECTION_POOL_READY = exports.CONNECTION_POOL_CLEARED = exports.CONNECTION_POOL_CLOSED = exports.CONNECTION_POOL_CREATED = exports.WAITING_FOR_SUITABLE_SERVER = exports.SERVER_SELECTION_SUCCEEDED = exports.SERVER_SELECTION_FAILED = exports.SERVER_SELECTION_STARTED = exports.TOPOLOGY_DESCRIPTION_CHANGED = exports.TOPOLOGY_CLOSED = exports.TOPOLOGY_OPENING = exports.SERVER_DESCRIPTION_CHANGED = exports.SERVER_CLOSED = exports.SERVER_OPENING = exports.DESCRIPTION_RECEIVED = exports.UNPINNED = exports.PINNED = exports.MESSAGE = exports.ENDED = exports.CLOSED = exports.CONNECT = exports.OPEN = exports.CLOSE = exports.TIMEOUT = exports.ERROR = exports.SYSTEM_JS_COLLECTION = exports.SYSTEM_COMMAND_COLLECTION = exports.SYSTEM_USER_COLLECTION = exports.SYSTEM_PROFILE_COLLECTION = exports.SYSTEM_INDEX_COLLECTION = exports.SYSTEM_NAMESPACE_COLLECTION = undefined;
11796
- exports.LEGACY_HELLO_COMMAND_CAMEL_CASE = exports.LEGACY_HELLO_COMMAND = exports.MONGO_CLIENT_EVENTS = exports.LOCAL_SERVER_EVENTS = exports.SERVER_RELAY_EVENTS = exports.APM_EVENTS = exports.TOPOLOGY_EVENTS = exports.CMAP_EVENTS = exports.HEARTBEAT_EVENTS = exports.RESUME_TOKEN_CHANGED = undefined;
11804
+ exports.kDecoratedKeys = exports.kDecorateResult = exports.LEGACY_HELLO_COMMAND_CAMEL_CASE = exports.LEGACY_HELLO_COMMAND = exports.MONGO_CLIENT_EVENTS = exports.LOCAL_SERVER_EVENTS = exports.SERVER_RELAY_EVENTS = exports.APM_EVENTS = exports.TOPOLOGY_EVENTS = exports.CMAP_EVENTS = exports.HEARTBEAT_EVENTS = exports.RESUME_TOKEN_CHANGED = undefined;
11797
11805
  exports.SYSTEM_NAMESPACE_COLLECTION = "system.namespaces";
11798
11806
  exports.SYSTEM_INDEX_COLLECTION = "system.indexes";
11799
11807
  exports.SYSTEM_PROFILE_COLLECTION = "system.profile";
@@ -11902,6 +11910,8 @@ var require_constants2 = __commonJS((exports) => {
11902
11910
  ]);
11903
11911
  exports.LEGACY_HELLO_COMMAND = "ismaster";
11904
11912
  exports.LEGACY_HELLO_COMMAND_CAMEL_CASE = "isMaster";
11913
+ exports.kDecorateResult = Symbol.for("@@mdb.decorateDecryptionResult");
11914
+ exports.kDecoratedKeys = Symbol.for("@@mdb.decryptedKeys");
11905
11915
  });
11906
11916
 
11907
11917
  // node_modules/mongodb/lib/read_concern.js
@@ -11958,10 +11968,411 @@ var require_read_concern = __commonJS((exports) => {
11958
11968
  exports.ReadConcern = ReadConcern;
11959
11969
  });
11960
11970
 
11971
+ // node_modules/mongodb/lib/cmap/wire_protocol/on_demand/document.js
11972
+ var require_document = __commonJS((exports) => {
11973
+ Object.defineProperty(exports, "__esModule", { value: true });
11974
+ exports.OnDemandDocument = undefined;
11975
+ var bson_1 = require_bson2();
11976
+
11977
+ class OnDemandDocument {
11978
+ constructor(bson, offset = 0, isArray = false, elements) {
11979
+ this.bson = bson;
11980
+ this.offset = offset;
11981
+ this.isArray = isArray;
11982
+ this.cache = Object.create(null);
11983
+ this.indexFound = Object.create(null);
11984
+ this.elements = elements ?? (0, bson_1.parseToElementsToArray)(this.bson, offset);
11985
+ }
11986
+ isElementName(name, element) {
11987
+ const nameLength = element[2];
11988
+ const nameOffset = element[1];
11989
+ if (name.length !== nameLength)
11990
+ return false;
11991
+ const nameEnd = nameOffset + nameLength;
11992
+ for (let byteIndex = nameOffset, charIndex = 0;charIndex < name.length && byteIndex < nameEnd; charIndex++, byteIndex++) {
11993
+ if (this.bson[byteIndex] !== name.charCodeAt(charIndex))
11994
+ return false;
11995
+ }
11996
+ return true;
11997
+ }
11998
+ getElement(name) {
11999
+ const cachedElement = this.cache[name];
12000
+ if (cachedElement === false)
12001
+ return null;
12002
+ if (cachedElement != null) {
12003
+ return cachedElement;
12004
+ }
12005
+ if (typeof name === "number") {
12006
+ if (this.isArray) {
12007
+ if (name < this.elements.length) {
12008
+ const element = this.elements[name];
12009
+ const cachedElement2 = { element, value: undefined };
12010
+ this.cache[name] = cachedElement2;
12011
+ this.indexFound[name] = true;
12012
+ return cachedElement2;
12013
+ } else {
12014
+ return null;
12015
+ }
12016
+ } else {
12017
+ return null;
12018
+ }
12019
+ }
12020
+ for (let index = 0;index < this.elements.length; index++) {
12021
+ const element = this.elements[index];
12022
+ if (!(index in this.indexFound) && this.isElementName(name, element)) {
12023
+ const cachedElement2 = { element, value: undefined };
12024
+ this.cache[name] = cachedElement2;
12025
+ this.indexFound[index] = true;
12026
+ return cachedElement2;
12027
+ }
12028
+ }
12029
+ this.cache[name] = false;
12030
+ return null;
12031
+ }
12032
+ toJSValue(element, as) {
12033
+ const type = element[0];
12034
+ const offset = element[3];
12035
+ const length = element[4];
12036
+ if (as !== type) {
12037
+ return null;
12038
+ }
12039
+ switch (as) {
12040
+ case bson_1.BSONType.null:
12041
+ case bson_1.BSONType.undefined:
12042
+ return null;
12043
+ case bson_1.BSONType.double:
12044
+ return (0, bson_1.getFloat64LE)(this.bson, offset);
12045
+ case bson_1.BSONType.int:
12046
+ return (0, bson_1.getInt32LE)(this.bson, offset);
12047
+ case bson_1.BSONType.long:
12048
+ return (0, bson_1.getBigInt64LE)(this.bson, offset);
12049
+ case bson_1.BSONType.bool:
12050
+ return Boolean(this.bson[offset]);
12051
+ case bson_1.BSONType.objectId:
12052
+ return new bson_1.ObjectId(this.bson.subarray(offset, offset + 12));
12053
+ case bson_1.BSONType.timestamp:
12054
+ return new bson_1.Timestamp((0, bson_1.getBigInt64LE)(this.bson, offset));
12055
+ case bson_1.BSONType.string:
12056
+ return (0, bson_1.toUTF8)(this.bson, offset + 4, offset + length - 1, false);
12057
+ case bson_1.BSONType.binData: {
12058
+ const totalBinarySize = (0, bson_1.getInt32LE)(this.bson, offset);
12059
+ const subType = this.bson[offset + 4];
12060
+ if (subType === 2) {
12061
+ const subType2BinarySize = (0, bson_1.getInt32LE)(this.bson, offset + 1 + 4);
12062
+ if (subType2BinarySize < 0)
12063
+ throw new bson_1.BSONError("Negative binary type element size found for subtype 0x02");
12064
+ if (subType2BinarySize > totalBinarySize - 4)
12065
+ throw new bson_1.BSONError("Binary type with subtype 0x02 contains too long binary size");
12066
+ if (subType2BinarySize < totalBinarySize - 4)
12067
+ throw new bson_1.BSONError("Binary type with subtype 0x02 contains too short binary size");
12068
+ return new bson_1.Binary(this.bson.subarray(offset + 1 + 4 + 4, offset + 1 + 4 + 4 + subType2BinarySize), 2);
12069
+ }
12070
+ return new bson_1.Binary(this.bson.subarray(offset + 1 + 4, offset + 1 + 4 + totalBinarySize), subType);
12071
+ }
12072
+ case bson_1.BSONType.date:
12073
+ return new Date(Number((0, bson_1.getBigInt64LE)(this.bson, offset)));
12074
+ case bson_1.BSONType.object:
12075
+ return new OnDemandDocument(this.bson, offset);
12076
+ case bson_1.BSONType.array:
12077
+ return new OnDemandDocument(this.bson, offset, true);
12078
+ default:
12079
+ throw new bson_1.BSONError(`Unsupported BSON type: ${as}`);
12080
+ }
12081
+ }
12082
+ size() {
12083
+ return this.elements.length;
12084
+ }
12085
+ has(name) {
12086
+ const cachedElement = this.cache[name];
12087
+ if (cachedElement === false)
12088
+ return false;
12089
+ if (cachedElement != null)
12090
+ return true;
12091
+ return this.getElement(name) != null;
12092
+ }
12093
+ get(name, as, required) {
12094
+ const element = this.getElement(name);
12095
+ if (element == null) {
12096
+ if (required === true) {
12097
+ throw new bson_1.BSONError(`BSON element "${name}" is missing`);
12098
+ } else {
12099
+ return null;
12100
+ }
12101
+ }
12102
+ if (element.value == null) {
12103
+ const value = this.toJSValue(element.element, as);
12104
+ if (value == null) {
12105
+ if (required === true) {
12106
+ throw new bson_1.BSONError(`BSON element "${name}" is missing`);
12107
+ } else {
12108
+ return null;
12109
+ }
12110
+ }
12111
+ element.value = value;
12112
+ }
12113
+ return element.value;
12114
+ }
12115
+ getNumber(name, required) {
12116
+ const maybeBool = this.get(name, bson_1.BSONType.bool);
12117
+ const bool = maybeBool == null ? null : maybeBool ? 1 : 0;
12118
+ const maybeLong = this.get(name, bson_1.BSONType.long);
12119
+ const long = maybeLong == null ? null : Number(maybeLong);
12120
+ const result = bool ?? long ?? this.get(name, bson_1.BSONType.int) ?? this.get(name, bson_1.BSONType.double);
12121
+ if (required === true && result == null) {
12122
+ throw new bson_1.BSONError(`BSON element "${name}" is missing`);
12123
+ }
12124
+ return result;
12125
+ }
12126
+ toObject(options) {
12127
+ return bson_1.BSON.deserialize(this.bson, {
12128
+ ...options,
12129
+ index: this.offset,
12130
+ allowObjectSmallerThanBufferSize: true
12131
+ });
12132
+ }
12133
+ toBytes() {
12134
+ const size = (0, bson_1.getInt32LE)(this.bson, this.offset);
12135
+ return this.bson.subarray(this.offset, this.offset + size);
12136
+ }
12137
+ }
12138
+ exports.OnDemandDocument = OnDemandDocument;
12139
+ });
12140
+
12141
+ // node_modules/mongodb/lib/cmap/wire_protocol/responses.js
12142
+ var require_responses = __commonJS((exports) => {
12143
+ var isErrorResponse = function(bson, elements) {
12144
+ for (let eIdx = 0;eIdx < elements.length; eIdx++) {
12145
+ const element = elements[eIdx];
12146
+ if (element[2] === 2) {
12147
+ const nameOffset = element[1];
12148
+ if (bson[nameOffset] === 111 && bson[nameOffset + 1] === 107) {
12149
+ const valueOffset = element[3];
12150
+ const valueLength = element[4];
12151
+ for (let i = valueOffset;i < valueOffset + valueLength; i++) {
12152
+ if (bson[i] !== 0)
12153
+ return false;
12154
+ }
12155
+ return true;
12156
+ }
12157
+ }
12158
+ }
12159
+ return true;
12160
+ };
12161
+ Object.defineProperty(exports, "__esModule", { value: true });
12162
+ exports.ExplainedCursorResponse = exports.CursorResponse = exports.MongoDBResponse = exports.isErrorResponse = undefined;
12163
+ var bson_1 = require_bson2();
12164
+ var error_1 = require_error();
12165
+ var utils_1 = require_utils2();
12166
+ var document_1 = require_document();
12167
+ exports.isErrorResponse = isErrorResponse;
12168
+
12169
+ class MongoDBResponse extends document_1.OnDemandDocument {
12170
+ get(name, as, required) {
12171
+ try {
12172
+ return super.get(name, as, required);
12173
+ } catch (cause) {
12174
+ throw new error_1.MongoUnexpectedServerResponseError(cause.message, { cause });
12175
+ }
12176
+ }
12177
+ static is(value) {
12178
+ return value instanceof MongoDBResponse;
12179
+ }
12180
+ static make(bson) {
12181
+ const elements = (0, bson_1.parseToElementsToArray)(bson, 0);
12182
+ const isError = isErrorResponse(bson, elements);
12183
+ return isError ? new MongoDBResponse(bson, 0, false, elements) : new this(bson, 0, false, elements);
12184
+ }
12185
+ get recoveryToken() {
12186
+ return this.get("recoveryToken", bson_1.BSONType.object)?.toObject({
12187
+ promoteValues: false,
12188
+ promoteLongs: false,
12189
+ promoteBuffers: false
12190
+ }) ?? null;
12191
+ }
12192
+ get atClusterTime() {
12193
+ return this.get("cursor", bson_1.BSONType.object)?.get("atClusterTime", bson_1.BSONType.timestamp) ?? this.get("atClusterTime", bson_1.BSONType.timestamp);
12194
+ }
12195
+ get operationTime() {
12196
+ return this.get("operationTime", bson_1.BSONType.timestamp);
12197
+ }
12198
+ get ok() {
12199
+ return this.getNumber("ok") ? 1 : 0;
12200
+ }
12201
+ get $err() {
12202
+ return this.get("$err", bson_1.BSONType.string);
12203
+ }
12204
+ get errmsg() {
12205
+ return this.get("errmsg", bson_1.BSONType.string);
12206
+ }
12207
+ get code() {
12208
+ return this.getNumber("code");
12209
+ }
12210
+ get $clusterTime() {
12211
+ if (!("clusterTime" in this)) {
12212
+ const clusterTimeDoc = this.get("$clusterTime", bson_1.BSONType.object);
12213
+ if (clusterTimeDoc == null) {
12214
+ this.clusterTime = null;
12215
+ return null;
12216
+ }
12217
+ const clusterTime = clusterTimeDoc.get("clusterTime", bson_1.BSONType.timestamp, true);
12218
+ const signature = clusterTimeDoc.get("signature", bson_1.BSONType.object)?.toObject();
12219
+ this.clusterTime = { clusterTime, signature };
12220
+ }
12221
+ return this.clusterTime ?? null;
12222
+ }
12223
+ toObject(options) {
12224
+ const exactBSONOptions = {
12225
+ ...(0, bson_1.pluckBSONSerializeOptions)(options ?? {}),
12226
+ validation: this.parseBsonSerializationOptions(options)
12227
+ };
12228
+ return super.toObject(exactBSONOptions);
12229
+ }
12230
+ parseBsonSerializationOptions(options) {
12231
+ const enableUtf8Validation = options?.enableUtf8Validation;
12232
+ if (enableUtf8Validation === false) {
12233
+ return { utf8: false };
12234
+ }
12235
+ return { utf8: { writeErrors: false } };
12236
+ }
12237
+ }
12238
+ MongoDBResponse.empty = new MongoDBResponse(new Uint8Array([13, 0, 0, 0, 16, 111, 107, 0, 1, 0, 0, 0, 0]));
12239
+ exports.MongoDBResponse = MongoDBResponse;
12240
+
12241
+ class CursorResponse extends MongoDBResponse {
12242
+ constructor() {
12243
+ super(...arguments);
12244
+ this._batch = null;
12245
+ this.iterated = 0;
12246
+ this._encryptedBatch = null;
12247
+ }
12248
+ static is(value) {
12249
+ return value instanceof CursorResponse || value === CursorResponse.emptyGetMore;
12250
+ }
12251
+ get cursor() {
12252
+ return this.get("cursor", bson_1.BSONType.object, true);
12253
+ }
12254
+ get id() {
12255
+ try {
12256
+ return bson_1.Long.fromBigInt(this.cursor.get("id", bson_1.BSONType.long, true));
12257
+ } catch (cause) {
12258
+ throw new error_1.MongoUnexpectedServerResponseError(cause.message, { cause });
12259
+ }
12260
+ }
12261
+ get ns() {
12262
+ const namespace = this.cursor.get("ns", bson_1.BSONType.string);
12263
+ if (namespace != null)
12264
+ return (0, utils_1.ns)(namespace);
12265
+ return null;
12266
+ }
12267
+ get length() {
12268
+ return Math.max(this.batchSize - this.iterated, 0);
12269
+ }
12270
+ get encryptedBatch() {
12271
+ if (this.encryptedResponse == null)
12272
+ return null;
12273
+ if (this._encryptedBatch != null)
12274
+ return this._encryptedBatch;
12275
+ const cursor = this.encryptedResponse?.get("cursor", bson_1.BSONType.object);
12276
+ if (cursor?.has("firstBatch"))
12277
+ this._encryptedBatch = cursor.get("firstBatch", bson_1.BSONType.array, true);
12278
+ else if (cursor?.has("nextBatch"))
12279
+ this._encryptedBatch = cursor.get("nextBatch", bson_1.BSONType.array, true);
12280
+ else
12281
+ throw new error_1.MongoUnexpectedServerResponseError("Cursor document did not contain a batch");
12282
+ return this._encryptedBatch;
12283
+ }
12284
+ get batch() {
12285
+ if (this._batch != null)
12286
+ return this._batch;
12287
+ const cursor = this.cursor;
12288
+ if (cursor.has("firstBatch"))
12289
+ this._batch = cursor.get("firstBatch", bson_1.BSONType.array, true);
12290
+ else if (cursor.has("nextBatch"))
12291
+ this._batch = cursor.get("nextBatch", bson_1.BSONType.array, true);
12292
+ else
12293
+ throw new error_1.MongoUnexpectedServerResponseError("Cursor document did not contain a batch");
12294
+ return this._batch;
12295
+ }
12296
+ get batchSize() {
12297
+ return this.batch?.size();
12298
+ }
12299
+ get postBatchResumeToken() {
12300
+ return this.cursor.get("postBatchResumeToken", bson_1.BSONType.object)?.toObject({
12301
+ promoteValues: false,
12302
+ promoteLongs: false,
12303
+ promoteBuffers: false
12304
+ }) ?? null;
12305
+ }
12306
+ shift(options) {
12307
+ if (this.iterated >= this.batchSize) {
12308
+ return null;
12309
+ }
12310
+ const result = this.batch.get(this.iterated, bson_1.BSONType.object, true) ?? null;
12311
+ const encryptedResult = this.encryptedBatch?.get(this.iterated, bson_1.BSONType.object, true) ?? null;
12312
+ this.iterated += 1;
12313
+ if (options?.raw) {
12314
+ return result.toBytes();
12315
+ } else {
12316
+ const object = result.toObject(options);
12317
+ if (encryptedResult) {
12318
+ (0, utils_1.decorateDecryptionResult)(object, encryptedResult.toObject(options), true);
12319
+ }
12320
+ return object;
12321
+ }
12322
+ }
12323
+ clear() {
12324
+ this.iterated = this.batchSize;
12325
+ }
12326
+ }
12327
+ CursorResponse.emptyGetMore = {
12328
+ id: new bson_1.Long(0),
12329
+ length: 0,
12330
+ shift: () => null
12331
+ };
12332
+ exports.CursorResponse = CursorResponse;
12333
+
12334
+ class ExplainedCursorResponse extends CursorResponse {
12335
+ constructor() {
12336
+ super(...arguments);
12337
+ this.isExplain = true;
12338
+ this._length = 1;
12339
+ }
12340
+ get id() {
12341
+ return bson_1.Long.fromBigInt(0n);
12342
+ }
12343
+ get batchSize() {
12344
+ return 0;
12345
+ }
12346
+ get ns() {
12347
+ return null;
12348
+ }
12349
+ get length() {
12350
+ return this._length;
12351
+ }
12352
+ shift(options) {
12353
+ if (this._length === 0)
12354
+ return null;
12355
+ this._length -= 1;
12356
+ return this.toObject(options);
12357
+ }
12358
+ }
12359
+ exports.ExplainedCursorResponse = ExplainedCursorResponse;
12360
+ });
12361
+
11961
12362
  // node_modules/mongodb/lib/write_concern.js
11962
12363
  var require_write_concern = __commonJS((exports) => {
12364
+ var throwIfWriteConcernError = function(response) {
12365
+ if (typeof response === "object" && response != null) {
12366
+ const writeConcernError = responses_1.MongoDBResponse.is(response) && response.has("writeConcernError") ? response.toObject() : !responses_1.MongoDBResponse.is(response) && ("writeConcernError" in response) ? response : null;
12367
+ if (writeConcernError != null) {
12368
+ throw new error_1.MongoWriteConcernError(writeConcernError);
12369
+ }
12370
+ }
12371
+ };
11963
12372
  Object.defineProperty(exports, "__esModule", { value: true });
11964
- exports.WriteConcern = exports.WRITE_CONCERN_KEYS = undefined;
12373
+ exports.throwIfWriteConcernError = exports.WriteConcern = exports.WRITE_CONCERN_KEYS = undefined;
12374
+ var responses_1 = require_responses();
12375
+ var error_1 = require_error();
11965
12376
  exports.WRITE_CONCERN_KEYS = ["w", "wtimeout", "j", "journal", "fsync"];
11966
12377
 
11967
12378
  class WriteConcern {
@@ -12018,6 +12429,7 @@ var require_write_concern = __commonJS((exports) => {
12018
12429
  }
12019
12430
  }
12020
12431
  exports.WriteConcern = WriteConcern;
12432
+ exports.throwIfWriteConcernError = throwIfWriteConcernError;
12021
12433
  });
12022
12434
 
12023
12435
  // node_modules/mongodb/lib/utils.js
@@ -12367,6 +12779,26 @@ var require_utils2 = __commonJS((exports) => {
12367
12779
  const srvHostDomain = `.${normalizedSrvHost.replace(allCharacterBeforeFirstDot, "")}`;
12368
12780
  return addressDomain.endsWith(srvHostDomain);
12369
12781
  };
12782
+ var get = function(url2, options = {}) {
12783
+ return new Promise((resolve, reject) => {
12784
+ let timeoutId;
12785
+ const request2 = http.get(url2, options, (response) => {
12786
+ response.setEncoding("utf8");
12787
+ let body = "";
12788
+ response.on("data", (chunk) => body += chunk);
12789
+ response.on("end", () => {
12790
+ (0, timers_1.clearTimeout)(timeoutId);
12791
+ resolve({ status: response.statusCode, body });
12792
+ });
12793
+ }).on("error", (error) => {
12794
+ (0, timers_1.clearTimeout)(timeoutId);
12795
+ reject(error);
12796
+ }).end();
12797
+ timeoutId = (0, timers_1.setTimeout)(() => {
12798
+ request2.destroy(new error_1.MongoNetworkTimeoutError(`request timed out after 10 seconds`));
12799
+ }, 1e4);
12800
+ });
12801
+ };
12370
12802
  async function request(uri, options = {}) {
12371
12803
  return await new Promise((resolve, reject) => {
12372
12804
  const requestOptions = {
@@ -12453,12 +12885,41 @@ var require_utils2 = __commonJS((exports) => {
12453
12885
  var noop = function() {
12454
12886
  return;
12455
12887
  };
12888
+ var decorateDecryptionResult = function(decrypted, original, isTopLevelDecorateCall = true) {
12889
+ if (isTopLevelDecorateCall) {
12890
+ if (Buffer.isBuffer(original)) {
12891
+ original = (0, bson_1.deserialize)(original);
12892
+ }
12893
+ if (Buffer.isBuffer(decrypted)) {
12894
+ throw new error_1.MongoRuntimeError("Expected result of decryption to be deserialized BSON object");
12895
+ }
12896
+ }
12897
+ if (!decrypted || typeof decrypted !== "object")
12898
+ return;
12899
+ for (const k of Object.keys(decrypted)) {
12900
+ const originalValue = original[k];
12901
+ if (originalValue && originalValue._bsontype === "Binary" && originalValue.sub_type === 6) {
12902
+ if (!decrypted[constants_2.kDecoratedKeys]) {
12903
+ Object.defineProperty(decrypted, constants_2.kDecoratedKeys, {
12904
+ value: [],
12905
+ configurable: true,
12906
+ enumerable: false,
12907
+ writable: false
12908
+ });
12909
+ }
12910
+ decrypted[constants_2.kDecoratedKeys].push(k);
12911
+ continue;
12912
+ }
12913
+ decorateDecryptionResult(decrypted[k], originalValue, false);
12914
+ }
12915
+ };
12456
12916
  Object.defineProperty(exports, "__esModule", { value: true });
12457
- exports.DOCUMENT_DB_MSG = exports.COSMOS_DB_CHECK = exports.DOCUMENT_DB_CHECK = exports.request = exports.matchesParentDomain = exports.parseUnsignedInteger = exports.parseInteger = exports.compareObjectId = exports.commandSupportsReadConcern = exports.shuffle = exports.supportsRetryableWrites = exports.enumToString = exports.emitWarningOnce = exports.emitWarning = exports.MONGODB_WARNING_CODE = exports.DEFAULT_PK_FACTORY = exports.HostAddress = exports.BufferPool = exports.List = exports.deepCopy = exports.isRecord = exports.setDifference = exports.isHello = exports.isSuperset = exports.resolveOptions = exports.hasAtomicOperators = exports.calculateDurationInMs = exports.now = exports.makeStateMachine = exports.errorStrictEqual = exports.arrayStrictEqual = exports.maxWireVersion = exports.uuidV4 = exports.makeCounter = exports.MongoDBCollectionNamespace = exports.MongoDBNamespace = exports.ns = exports.getTopology = exports.decorateWithExplain = exports.decorateWithReadConcern = exports.decorateWithCollation = exports.isPromiseLike = exports.applyRetryableWrites = exports.filterOptions = exports.mergeOptions = exports.isObject = exports.normalizeHintField = exports.hostMatchesWildcards = exports.isUint8Array = exports.ByteUtils = undefined;
12458
- exports.noop = exports.fileIsAccessible = exports.maybeAddIdToDocuments = exports.once = exports.randomBytes = exports.squashError = exports.promiseWithResolvers = exports.isHostMatch = exports.COSMOS_DB_MSG = undefined;
12917
+ exports.COSMOS_DB_CHECK = exports.DOCUMENT_DB_CHECK = exports.request = exports.get = exports.matchesParentDomain = exports.parseUnsignedInteger = exports.parseInteger = exports.compareObjectId = exports.commandSupportsReadConcern = exports.shuffle = exports.supportsRetryableWrites = exports.enumToString = exports.emitWarningOnce = exports.emitWarning = exports.MONGODB_WARNING_CODE = exports.DEFAULT_PK_FACTORY = exports.HostAddress = exports.BufferPool = exports.List = exports.deepCopy = exports.isRecord = exports.setDifference = exports.isHello = exports.isSuperset = exports.resolveOptions = exports.hasAtomicOperators = exports.calculateDurationInMs = exports.now = exports.makeStateMachine = exports.errorStrictEqual = exports.arrayStrictEqual = exports.maxWireVersion = exports.uuidV4 = exports.makeCounter = exports.MongoDBCollectionNamespace = exports.MongoDBNamespace = exports.ns = exports.getTopology = exports.decorateWithExplain = exports.decorateWithReadConcern = exports.decorateWithCollation = exports.isPromiseLike = exports.applyRetryableWrites = exports.filterOptions = exports.mergeOptions = exports.isObject = exports.normalizeHintField = exports.hostMatchesWildcards = exports.isUint8Array = exports.ByteUtils = undefined;
12918
+ exports.decorateDecryptionResult = exports.noop = exports.fileIsAccessible = exports.maybeAddIdToDocuments = exports.once = exports.randomBytes = exports.squashError = exports.promiseWithResolvers = exports.isHostMatch = exports.COSMOS_DB_MSG = exports.DOCUMENT_DB_MSG = undefined;
12459
12919
  var crypto = import.meta.require("crypto");
12460
12920
  var fs_1 = import.meta.require("fs");
12461
12921
  var http = import.meta.require("http");
12922
+ var timers_1 = import.meta.require("timers");
12462
12923
  var url = import.meta.require("url");
12463
12924
  var url_1 = import.meta.require("url");
12464
12925
  var util_1 = import.meta.require("util");
@@ -12796,6 +13257,7 @@ var require_utils2 = __commonJS((exports) => {
12796
13257
  exports.parseInteger = parseInteger;
12797
13258
  exports.parseUnsignedInteger = parseUnsignedInteger;
12798
13259
  exports.matchesParentDomain = matchesParentDomain;
13260
+ exports.get = get;
12799
13261
  exports.request = request;
12800
13262
  exports.DOCUMENT_DB_CHECK = /(\.docdb\.amazonaws\.com$)|(\.docdb-elastic\.amazonaws\.com$)/;
12801
13263
  exports.COSMOS_DB_CHECK = /\.cosmos\.azure\.com$/;
@@ -12809,6 +13271,7 @@ var require_utils2 = __commonJS((exports) => {
12809
13271
  exports.maybeAddIdToDocuments = maybeAddIdToDocuments;
12810
13272
  exports.fileIsAccessible = fileIsAccessible;
12811
13273
  exports.noop = noop;
13274
+ exports.decorateDecryptionResult = decorateDecryptionResult;
12812
13275
  });
12813
13276
 
12814
13277
  // node_modules/mongodb/lib/operations/operation.js
@@ -13092,7 +13555,7 @@ var require_command = __commonJS((exports) => {
13092
13555
  }
13093
13556
  return true;
13094
13557
  }
13095
- async executeCommand(server, session, cmd) {
13558
+ async executeCommand(server, session, cmd, responseType) {
13096
13559
  this.server = server;
13097
13560
  const options = {
13098
13561
  ...this.options,
@@ -13120,7 +13583,7 @@ var require_command = __commonJS((exports) => {
13120
13583
  if (this.hasAspect(operation_1.Aspect.EXPLAINABLE) && this.explain) {
13121
13584
  cmd = (0, utils_1.decorateWithExplain)(cmd, this.explain);
13122
13585
  }
13123
- return await server.command(this.ns, cmd, options);
13586
+ return await server.command(this.ns, cmd, options, responseType);
13124
13587
  }
13125
13588
  }
13126
13589
  exports.CommandOperation = CommandOperation;
@@ -13212,7 +13675,7 @@ var require_run_command = __commonJS((exports) => {
13212
13675
  ...this.options,
13213
13676
  readPreference: this.readPreference,
13214
13677
  session
13215
- });
13678
+ }, this.options.responseType);
13216
13679
  return res;
13217
13680
  }
13218
13681
  }
@@ -13471,8 +13934,7 @@ var require_bulk_write = __commonJS((exports) => {
13471
13934
  for (let i = 0;i < operations.length; i++) {
13472
13935
  bulk.raw(operations[i]);
13473
13936
  }
13474
- const result = await bulk.execute({ ...options, session });
13475
- return result;
13937
+ return await bulk.execute({ ...options, session });
13476
13938
  }
13477
13939
  }
13478
13940
  exports.BulkWriteOperation = BulkWriteOperation;
@@ -13652,7 +14114,8 @@ var require_update = __commonJS((exports) => {
13652
14114
  throw new error_1.MongoCompatibilityError(`hint is not supported with unacknowledged writes`);
13653
14115
  }
13654
14116
  }
13655
- return await super.executeCommand(server, session, command2);
14117
+ const res = await super.executeCommand(server, session, command2);
14118
+ return res;
13656
14119
  }
13657
14120
  }
13658
14121
  exports.UpdateOperation = UpdateOperation;
@@ -14516,6 +14979,7 @@ var require_unordered = __commonJS((exports) => {
14516
14979
  var require_aggregate = __commonJS((exports) => {
14517
14980
  Object.defineProperty(exports, "__esModule", { value: true });
14518
14981
  exports.AggregateOperation = exports.DB_AGGREGATE_COLLECTION = undefined;
14982
+ var responses_1 = require_responses();
14519
14983
  var error_1 = require_error();
14520
14984
  var utils_1 = require_utils2();
14521
14985
  var write_concern_1 = require_write_concern();
@@ -14590,8 +15054,7 @@ var require_aggregate = __commonJS((exports) => {
14590
15054
  if (options.batchSize && !this.hasWriteStage) {
14591
15055
  command2.cursor.batchSize = options.batchSize;
14592
15056
  }
14593
- const res = await super.executeCommand(server, session, command2);
14594
- return res;
15057
+ return await super.executeCommand(server, session, command2, this.explain ? responses_1.ExplainedCursorResponse : responses_1.CursorResponse);
14595
15058
  }
14596
15059
  }
14597
15060
  exports.AggregateOperation = AggregateOperation;
@@ -14603,329 +15066,6 @@ var require_aggregate = __commonJS((exports) => {
14603
15066
  ]);
14604
15067
  });
14605
15068
 
14606
- // node_modules/mongodb/lib/cmap/wire_protocol/on_demand/document.js
14607
- var require_document = __commonJS((exports) => {
14608
- Object.defineProperty(exports, "__esModule", { value: true });
14609
- exports.OnDemandDocument = undefined;
14610
- var bson_1 = require_bson2();
14611
-
14612
- class OnDemandDocument {
14613
- constructor(bson, offset = 0, isArray = false) {
14614
- this.bson = bson;
14615
- this.offset = offset;
14616
- this.isArray = isArray;
14617
- this.cache = Object.create(null);
14618
- this.indexFound = Object.create(null);
14619
- this.elements = (0, bson_1.parseToElementsToArray)(this.bson, offset);
14620
- }
14621
- isElementName(name, element) {
14622
- const nameLength = element[2];
14623
- const nameOffset = element[1];
14624
- if (name.length !== nameLength)
14625
- return false;
14626
- for (let i = 0;i < name.length; i++) {
14627
- if (this.bson[nameOffset + i] !== name.charCodeAt(i))
14628
- return false;
14629
- }
14630
- return true;
14631
- }
14632
- getElement(name) {
14633
- const cachedElement = this.cache[name];
14634
- if (cachedElement === false)
14635
- return null;
14636
- if (cachedElement != null) {
14637
- return cachedElement;
14638
- }
14639
- if (typeof name === "number") {
14640
- if (this.isArray) {
14641
- if (name < this.elements.length) {
14642
- const element = this.elements[name];
14643
- const cachedElement2 = { element, value: undefined };
14644
- this.cache[name] = cachedElement2;
14645
- this.indexFound[name] = true;
14646
- return cachedElement2;
14647
- } else {
14648
- return null;
14649
- }
14650
- } else {
14651
- return null;
14652
- }
14653
- }
14654
- for (let index = 0;index < this.elements.length; index++) {
14655
- const element = this.elements[index];
14656
- if (!this.indexFound[index] && this.isElementName(name, element)) {
14657
- const cachedElement2 = { element, value: undefined };
14658
- this.cache[name] = cachedElement2;
14659
- this.indexFound[index] = true;
14660
- return cachedElement2;
14661
- }
14662
- }
14663
- this.cache[name] = false;
14664
- return null;
14665
- }
14666
- toJSValue(element, as) {
14667
- const type = element[0];
14668
- const offset = element[3];
14669
- const length = element[4];
14670
- if (as !== type) {
14671
- return null;
14672
- }
14673
- switch (as) {
14674
- case bson_1.BSONType.null:
14675
- case bson_1.BSONType.undefined:
14676
- return null;
14677
- case bson_1.BSONType.double:
14678
- return (0, bson_1.getFloat64LE)(this.bson, offset);
14679
- case bson_1.BSONType.int:
14680
- return (0, bson_1.getInt32LE)(this.bson, offset);
14681
- case bson_1.BSONType.long:
14682
- return (0, bson_1.getBigInt64LE)(this.bson, offset);
14683
- case bson_1.BSONType.bool:
14684
- return Boolean(this.bson[offset]);
14685
- case bson_1.BSONType.objectId:
14686
- return new bson_1.ObjectId(this.bson.subarray(offset, offset + 12));
14687
- case bson_1.BSONType.timestamp:
14688
- return new bson_1.Timestamp((0, bson_1.getBigInt64LE)(this.bson, offset));
14689
- case bson_1.BSONType.string:
14690
- return (0, bson_1.toUTF8)(this.bson, offset + 4, offset + length - 1, false);
14691
- case bson_1.BSONType.binData: {
14692
- const totalBinarySize = (0, bson_1.getInt32LE)(this.bson, offset);
14693
- const subType = this.bson[offset + 4];
14694
- if (subType === 2) {
14695
- const subType2BinarySize = (0, bson_1.getInt32LE)(this.bson, offset + 1 + 4);
14696
- if (subType2BinarySize < 0)
14697
- throw new bson_1.BSONError("Negative binary type element size found for subtype 0x02");
14698
- if (subType2BinarySize > totalBinarySize - 4)
14699
- throw new bson_1.BSONError("Binary type with subtype 0x02 contains too long binary size");
14700
- if (subType2BinarySize < totalBinarySize - 4)
14701
- throw new bson_1.BSONError("Binary type with subtype 0x02 contains too short binary size");
14702
- return new bson_1.Binary(this.bson.subarray(offset + 1 + 4 + 4, offset + 1 + 4 + 4 + subType2BinarySize), 2);
14703
- }
14704
- return new bson_1.Binary(this.bson.subarray(offset + 1 + 4, offset + 1 + 4 + totalBinarySize), subType);
14705
- }
14706
- case bson_1.BSONType.date:
14707
- return new Date(Number((0, bson_1.getBigInt64LE)(this.bson, offset)));
14708
- case bson_1.BSONType.object:
14709
- return new OnDemandDocument(this.bson, offset);
14710
- case bson_1.BSONType.array:
14711
- return new OnDemandDocument(this.bson, offset, true);
14712
- default:
14713
- throw new bson_1.BSONError(`Unsupported BSON type: ${as}`);
14714
- }
14715
- }
14716
- size() {
14717
- return this.elements.length;
14718
- }
14719
- has(name) {
14720
- const cachedElement = this.cache[name];
14721
- if (cachedElement === false)
14722
- return false;
14723
- if (cachedElement != null)
14724
- return true;
14725
- return this.getElement(name) != null;
14726
- }
14727
- get(name, as, required) {
14728
- const element = this.getElement(name);
14729
- if (element == null) {
14730
- if (required === true) {
14731
- throw new bson_1.BSONError(`BSON element "${name}" is missing`);
14732
- } else {
14733
- return null;
14734
- }
14735
- }
14736
- if (element.value == null) {
14737
- const value = this.toJSValue(element.element, as);
14738
- if (value == null) {
14739
- if (required === true) {
14740
- throw new bson_1.BSONError(`BSON element "${name}" is missing`);
14741
- } else {
14742
- return null;
14743
- }
14744
- }
14745
- element.value = value;
14746
- }
14747
- return element.value;
14748
- }
14749
- getNumber(name, required) {
14750
- const maybeBool = this.get(name, bson_1.BSONType.bool);
14751
- const bool = maybeBool == null ? null : maybeBool ? 1 : 0;
14752
- const maybeLong = this.get(name, bson_1.BSONType.long);
14753
- const long = maybeLong == null ? null : Number(maybeLong);
14754
- const result = bool ?? long ?? this.get(name, bson_1.BSONType.int) ?? this.get(name, bson_1.BSONType.double);
14755
- if (required === true && result == null) {
14756
- throw new bson_1.BSONError(`BSON element "${name}" is missing`);
14757
- }
14758
- return result;
14759
- }
14760
- toObject(options) {
14761
- return bson_1.BSON.deserialize(this.bson, {
14762
- ...options,
14763
- index: this.offset,
14764
- allowObjectSmallerThanBufferSize: true
14765
- });
14766
- }
14767
- toBytes() {
14768
- const size = (0, bson_1.getInt32LE)(this.bson, this.offset);
14769
- return this.bson.subarray(this.offset, this.offset + size);
14770
- }
14771
- }
14772
- exports.OnDemandDocument = OnDemandDocument;
14773
- });
14774
-
14775
- // node_modules/mongodb/lib/cmap/wire_protocol/responses.js
14776
- var require_responses = __commonJS((exports) => {
14777
- var isErrorResponse = function(bson) {
14778
- const elements = (0, bson_1.parseToElementsToArray)(bson, 0);
14779
- for (let eIdx = 0;eIdx < elements.length; eIdx++) {
14780
- const element = elements[eIdx];
14781
- if (element[2] === 2) {
14782
- const nameOffset = element[1];
14783
- if (bson[nameOffset] === 111 && bson[nameOffset + 1] === 107) {
14784
- const valueOffset = element[3];
14785
- const valueLength = element[4];
14786
- for (let i = valueOffset;i < valueOffset + valueLength; i++) {
14787
- if (bson[i] !== 0)
14788
- return false;
14789
- }
14790
- return true;
14791
- }
14792
- }
14793
- }
14794
- return true;
14795
- };
14796
- Object.defineProperty(exports, "__esModule", { value: true });
14797
- exports.CursorResponse = exports.MongoDBResponse = exports.isErrorResponse = undefined;
14798
- var bson_1 = require_bson2();
14799
- var error_1 = require_error();
14800
- var utils_1 = require_utils2();
14801
- var document_1 = require_document();
14802
- exports.isErrorResponse = isErrorResponse;
14803
-
14804
- class MongoDBResponse extends document_1.OnDemandDocument {
14805
- static is(value) {
14806
- return value instanceof MongoDBResponse;
14807
- }
14808
- get isError() {
14809
- let isError = this.ok === 0;
14810
- isError ||= this.has("errmsg");
14811
- isError ||= this.has("code");
14812
- isError ||= this.has("$err");
14813
- return isError;
14814
- }
14815
- get recoveryToken() {
14816
- return this.get("recoveryToken", bson_1.BSONType.object)?.toObject({
14817
- promoteValues: false,
14818
- promoteLongs: false,
14819
- promoteBuffers: false
14820
- }) ?? null;
14821
- }
14822
- get atClusterTime() {
14823
- return this.get("cursor", bson_1.BSONType.object)?.get("atClusterTime", bson_1.BSONType.timestamp) ?? this.get("atClusterTime", bson_1.BSONType.timestamp);
14824
- }
14825
- get operationTime() {
14826
- return this.get("operationTime", bson_1.BSONType.timestamp);
14827
- }
14828
- get ok() {
14829
- return this.getNumber("ok") ? 1 : 0;
14830
- }
14831
- get $err() {
14832
- return this.get("$err", bson_1.BSONType.string);
14833
- }
14834
- get errmsg() {
14835
- return this.get("errmsg", bson_1.BSONType.string);
14836
- }
14837
- get code() {
14838
- return this.getNumber("code");
14839
- }
14840
- get $clusterTime() {
14841
- if (!("clusterTime" in this)) {
14842
- const clusterTimeDoc = this.get("$clusterTime", bson_1.BSONType.object);
14843
- if (clusterTimeDoc == null) {
14844
- this.clusterTime = null;
14845
- return null;
14846
- }
14847
- const clusterTime = clusterTimeDoc.get("clusterTime", bson_1.BSONType.timestamp, true);
14848
- const signature = clusterTimeDoc.get("signature", bson_1.BSONType.object)?.toObject();
14849
- this.clusterTime = { clusterTime, signature };
14850
- }
14851
- return this.clusterTime ?? null;
14852
- }
14853
- toObject(options) {
14854
- const exactBSONOptions = {
14855
- useBigInt64: options?.useBigInt64,
14856
- promoteLongs: options?.promoteLongs,
14857
- promoteValues: options?.promoteValues,
14858
- promoteBuffers: options?.promoteBuffers,
14859
- bsonRegExp: options?.bsonRegExp,
14860
- raw: options?.raw ?? false,
14861
- fieldsAsRaw: options?.fieldsAsRaw ?? {},
14862
- validation: this.parseBsonSerializationOptions(options)
14863
- };
14864
- return super.toObject(exactBSONOptions);
14865
- }
14866
- parseBsonSerializationOptions(options) {
14867
- const enableUtf8Validation = options?.enableUtf8Validation;
14868
- if (enableUtf8Validation === false) {
14869
- return { utf8: false };
14870
- }
14871
- return { utf8: { writeErrors: false } };
14872
- }
14873
- }
14874
- MongoDBResponse.empty = new MongoDBResponse(new Uint8Array([13, 0, 0, 0, 16, 111, 107, 0, 1, 0, 0, 0, 0]));
14875
- exports.MongoDBResponse = MongoDBResponse;
14876
-
14877
- class CursorResponse extends MongoDBResponse {
14878
- static is(value) {
14879
- return value instanceof CursorResponse || value === CursorResponse.emptyGetMore;
14880
- }
14881
- constructor(bytes, offset, isArray) {
14882
- super(bytes, offset, isArray);
14883
- this.ns = null;
14884
- this.batchSize = 0;
14885
- this.iterated = 0;
14886
- const cursor = this.get("cursor", bson_1.BSONType.object, true);
14887
- const id = cursor.get("id", bson_1.BSONType.long, true);
14888
- this.id = new bson_1.Long(Number(id & 0xffffffffn), Number(id >> 32n & 0xffffffffn));
14889
- const namespace = cursor.get("ns", bson_1.BSONType.string);
14890
- if (namespace != null)
14891
- this.ns = (0, utils_1.ns)(namespace);
14892
- if (cursor.has("firstBatch"))
14893
- this.batch = cursor.get("firstBatch", bson_1.BSONType.array, true);
14894
- else if (cursor.has("nextBatch"))
14895
- this.batch = cursor.get("nextBatch", bson_1.BSONType.array, true);
14896
- else
14897
- throw new error_1.MongoUnexpectedServerResponseError("Cursor document did not contain a batch");
14898
- this.batchSize = this.batch.size();
14899
- }
14900
- get length() {
14901
- return Math.max(this.batchSize - this.iterated, 0);
14902
- }
14903
- shift(options) {
14904
- if (this.iterated >= this.batchSize) {
14905
- return null;
14906
- }
14907
- const result = this.batch.get(this.iterated, bson_1.BSONType.object, true) ?? null;
14908
- this.iterated += 1;
14909
- if (options?.raw) {
14910
- return result.toBytes();
14911
- } else {
14912
- return result.toObject(options);
14913
- }
14914
- }
14915
- clear() {
14916
- this.iterated = this.batchSize;
14917
- }
14918
- pushMany() {
14919
- throw new Error("pushMany Unsupported method");
14920
- }
14921
- push() {
14922
- throw new Error("push Unsupported method");
14923
- }
14924
- }
14925
- CursorResponse.emptyGetMore = { id: new bson_1.Long(0), length: 0, shift: () => null };
14926
- exports.CursorResponse = CursorResponse;
14927
- });
14928
-
14929
15069
  // node_modules/mongodb/lib/mongo_logger.js
14930
15070
  var require_mongo_logger = __commonJS((exports) => {
14931
15071
  var parseSeverityFromString = function(s) {
@@ -15490,7 +15630,7 @@ var require_get_more = __commonJS((exports) => {
15490
15630
  documentsReturnedIn: "nextBatch",
15491
15631
  ...this.options
15492
15632
  };
15493
- return await server.command(this.ns, getMoreCmd, commandOptions, this.options.useCursorResponse ? responses_1.CursorResponse : undefined);
15633
+ return await server.command(this.ns, getMoreCmd, commandOptions, responses_1.CursorResponse);
15494
15634
  }
15495
15635
  }
15496
15636
  exports.GetMoreOperation = GetMoreOperation;
@@ -15624,8 +15764,8 @@ var require_server_description = __commonJS((exports) => {
15624
15764
  if (!currentTv.processId.equals(newTv.processId)) {
15625
15765
  return -1;
15626
15766
  }
15627
- const currentCounter = bson_1.Long.isLong(currentTv.counter) ? currentTv.counter : bson_1.Long.fromNumber(currentTv.counter);
15628
- const newCounter = bson_1.Long.isLong(newTv.counter) ? newTv.counter : bson_1.Long.fromNumber(newTv.counter);
15767
+ const currentCounter = typeof currentTv.counter === "bigint" ? bson_1.Long.fromBigInt(currentTv.counter) : bson_1.Long.isLong(currentTv.counter) ? currentTv.counter : bson_1.Long.fromNumber(currentTv.counter);
15768
+ const newCounter = typeof newTv.counter === "bigint" ? bson_1.Long.fromBigInt(newTv.counter) : bson_1.Long.isLong(newTv.counter) ? newTv.counter : bson_1.Long.fromNumber(newTv.counter);
15629
15769
  return currentCounter.compare(newCounter);
15630
15770
  };
15631
15771
  Object.defineProperty(exports, "__esModule", { value: true });
@@ -16471,7 +16611,7 @@ var require_sessions = __commonJS((exports) => {
16471
16611
  this.sessionPool = sessionPool;
16472
16612
  this.hasEnded = false;
16473
16613
  this.clientOptions = clientOptions;
16474
- this.timeoutMS = options.defaultTimeoutMS ?? client.options?.timeoutMS;
16614
+ this.timeoutMS = options.defaultTimeoutMS ?? client.s.options?.timeoutMS;
16475
16615
  this.explicit = !!options.explicit;
16476
16616
  this[kServerSession] = this.explicit ? this.sessionPool.acquire() : null;
16477
16617
  this[kTxnNumberIncrement] = 0;
@@ -16711,140 +16851,10 @@ var require_sessions = __commonJS((exports) => {
16711
16851
 
16712
16852
  // node_modules/mongodb/lib/cursor/abstract_cursor.js
16713
16853
  var require_abstract_cursor = __commonJS((exports) => {
16714
- async function next(cursor, { blocking, transform, shift }) {
16715
- if (cursor.closed) {
16716
- if (!shift)
16717
- return false;
16718
- return null;
16719
- }
16720
- do {
16721
- if (cursor[kId] == null) {
16722
- await cursor[kInit]();
16723
- }
16724
- if (cursor[kDocuments].length !== 0) {
16725
- if (!shift)
16726
- return true;
16727
- const doc = cursor[kDocuments].shift(cursor[kOptions]);
16728
- if (doc != null && transform && cursor[kTransform]) {
16729
- try {
16730
- return cursor[kTransform](doc);
16731
- } catch (error) {
16732
- try {
16733
- await cleanupCursor(cursor, { error, needsToEmitClosed: true });
16734
- } catch (error2) {
16735
- (0, utils_1.squashError)(error2);
16736
- }
16737
- throw error;
16738
- }
16739
- }
16740
- return doc;
16741
- }
16742
- if (cursor.isDead) {
16743
- await cleanupCursor(cursor, {});
16744
- if (!shift)
16745
- return false;
16746
- return null;
16747
- }
16748
- const batchSize = cursor[kOptions].batchSize || 1000;
16749
- try {
16750
- const response = await cursor.getMore(batchSize);
16751
- if (responses_1.CursorResponse.is(response)) {
16752
- cursor[kId] = response.id;
16753
- cursor[kDocuments] = response;
16754
- } else if (response) {
16755
- const cursorId = typeof response.cursor.id === "number" ? bson_1.Long.fromNumber(response.cursor.id) : typeof response.cursor.id === "bigint" ? bson_1.Long.fromBigInt(response.cursor.id) : response.cursor.id;
16756
- cursor[kDocuments].pushMany(response.cursor.nextBatch);
16757
- cursor[kId] = cursorId;
16758
- }
16759
- } catch (error) {
16760
- try {
16761
- await cleanupCursor(cursor, { error, needsToEmitClosed: true });
16762
- } catch (error2) {
16763
- (0, utils_1.squashError)(error2);
16764
- }
16765
- throw error;
16766
- }
16767
- if (cursor.isDead) {
16768
- await cleanupCursor(cursor, {});
16769
- }
16770
- if (cursor[kDocuments].length === 0 && blocking === false) {
16771
- if (!shift)
16772
- return false;
16773
- return null;
16774
- }
16775
- } while (!cursor.isDead || cursor[kDocuments].length !== 0);
16776
- if (!shift)
16777
- return false;
16778
- return null;
16779
- }
16780
- async function cleanupCursor(cursor, options) {
16781
- const cursorId = cursor[kId];
16782
- const cursorNs = cursor[kNamespace];
16783
- const server = cursor[kServer];
16784
- const session = cursor[kSession];
16785
- const error = options?.error;
16786
- const needsToEmitClosed = options?.needsToEmitClosed ?? cursor[kDocuments].length === 0;
16787
- if (error) {
16788
- if (cursor.loadBalanced && error instanceof error_1.MongoNetworkError) {
16789
- return await completeCleanup();
16790
- }
16791
- }
16792
- if (cursorId == null || server == null || cursorId.isZero() || cursorNs == null) {
16793
- if (needsToEmitClosed) {
16794
- cursor[kClosed] = true;
16795
- cursor[kId] = bson_1.Long.ZERO;
16796
- cursor.emit(AbstractCursor.CLOSE);
16797
- }
16798
- if (session) {
16799
- if (session.owner === cursor) {
16800
- await session.endSession({ error });
16801
- return;
16802
- }
16803
- if (!session.inTransaction()) {
16804
- (0, sessions_1.maybeClearPinnedConnection)(session, { error });
16805
- }
16806
- }
16807
- return;
16808
- }
16809
- async function completeCleanup() {
16810
- if (session) {
16811
- if (session.owner === cursor) {
16812
- try {
16813
- await session.endSession({ error });
16814
- } finally {
16815
- cursor.emit(AbstractCursor.CLOSE);
16816
- }
16817
- return;
16818
- }
16819
- if (!session.inTransaction()) {
16820
- (0, sessions_1.maybeClearPinnedConnection)(session, { error });
16821
- }
16822
- }
16823
- cursor.emit(AbstractCursor.CLOSE);
16824
- return;
16825
- }
16826
- cursor[kKilled] = true;
16827
- if (session.hasEnded) {
16828
- return await completeCleanup();
16829
- }
16830
- try {
16831
- await (0, execute_operation_1.executeOperation)(cursor[kClient], new kill_cursors_1.KillCursorsOperation(cursorId, cursorNs, server, { session }));
16832
- } catch (error2) {
16833
- (0, utils_1.squashError)(error2);
16834
- } finally {
16835
- await completeCleanup();
16836
- }
16837
- }
16838
- var assertUninitialized = function(cursor) {
16839
- if (cursor[kInitialized]) {
16840
- throw new error_1.MongoCursorInUseError;
16841
- }
16842
- };
16843
16854
  Object.defineProperty(exports, "__esModule", { value: true });
16844
- exports.assertUninitialized = exports.AbstractCursor = exports.CURSOR_FLAGS = undefined;
16855
+ exports.AbstractCursor = exports.CURSOR_FLAGS = undefined;
16845
16856
  var stream_1 = import.meta.require("stream");
16846
16857
  var bson_1 = require_bson2();
16847
- var responses_1 = require_responses();
16848
16858
  var error_1 = require_error();
16849
16859
  var mongo_types_1 = require_mongo_types();
16850
16860
  var execute_operation_1 = require_execute_operation();
@@ -16854,18 +16864,6 @@ var require_abstract_cursor = __commonJS((exports) => {
16854
16864
  var read_preference_1 = require_read_preference();
16855
16865
  var sessions_1 = require_sessions();
16856
16866
  var utils_1 = require_utils2();
16857
- var kId = Symbol("id");
16858
- var kDocuments = Symbol("documents");
16859
- var kServer = Symbol("server");
16860
- var kNamespace = Symbol("namespace");
16861
- var kClient = Symbol("client");
16862
- var kSession = Symbol("session");
16863
- var kOptions = Symbol("options");
16864
- var kTransform = Symbol("transform");
16865
- var kInitialized = Symbol("initialized");
16866
- var kClosed = Symbol("closed");
16867
- var kKilled = Symbol("killed");
16868
- var kInit = Symbol("kInit");
16869
16867
  exports.CURSOR_FLAGS = [
16870
16868
  "tailable",
16871
16869
  "oplogReplay",
@@ -16878,90 +16876,88 @@ var require_abstract_cursor = __commonJS((exports) => {
16878
16876
  class AbstractCursor extends mongo_types_1.TypedEventEmitter {
16879
16877
  constructor(client, namespace, options = {}) {
16880
16878
  super();
16879
+ this.documents = null;
16880
+ this.hasEmittedClose = false;
16881
16881
  if (!client.s.isMongoClient) {
16882
16882
  throw new error_1.MongoRuntimeError("Cursor must be constructed with MongoClient");
16883
16883
  }
16884
- this[kClient] = client;
16885
- this[kNamespace] = namespace;
16886
- this[kId] = null;
16887
- this[kDocuments] = new utils_1.List;
16888
- this[kInitialized] = false;
16889
- this[kClosed] = false;
16890
- this[kKilled] = false;
16891
- this[kOptions] = {
16884
+ this.cursorClient = client;
16885
+ this.cursorNamespace = namespace;
16886
+ this.cursorId = null;
16887
+ this.initialized = false;
16888
+ this.isClosed = false;
16889
+ this.isKilled = false;
16890
+ this.cursorOptions = {
16892
16891
  readPreference: options.readPreference && options.readPreference instanceof read_preference_1.ReadPreference ? options.readPreference : read_preference_1.ReadPreference.primary,
16893
16892
  ...(0, bson_1.pluckBSONSerializeOptions)(options)
16894
16893
  };
16895
- this[kOptions].timeoutMS = options.timeoutMS;
16894
+ this.cursorOptions.timeoutMS = options.timeoutMS;
16896
16895
  const readConcern = read_concern_1.ReadConcern.fromOptions(options);
16897
16896
  if (readConcern) {
16898
- this[kOptions].readConcern = readConcern;
16897
+ this.cursorOptions.readConcern = readConcern;
16899
16898
  }
16900
16899
  if (typeof options.batchSize === "number") {
16901
- this[kOptions].batchSize = options.batchSize;
16900
+ this.cursorOptions.batchSize = options.batchSize;
16902
16901
  }
16903
16902
  if (options.comment !== undefined) {
16904
- this[kOptions].comment = options.comment;
16903
+ this.cursorOptions.comment = options.comment;
16905
16904
  }
16906
16905
  if (typeof options.maxTimeMS === "number") {
16907
- this[kOptions].maxTimeMS = options.maxTimeMS;
16906
+ this.cursorOptions.maxTimeMS = options.maxTimeMS;
16908
16907
  }
16909
16908
  if (typeof options.maxAwaitTimeMS === "number") {
16910
- this[kOptions].maxAwaitTimeMS = options.maxAwaitTimeMS;
16909
+ this.cursorOptions.maxAwaitTimeMS = options.maxAwaitTimeMS;
16911
16910
  }
16912
16911
  if (options.session instanceof sessions_1.ClientSession) {
16913
- this[kSession] = options.session;
16912
+ this.cursorSession = options.session;
16914
16913
  } else {
16915
- this[kSession] = this[kClient].startSession({ owner: this, explicit: false });
16914
+ this.cursorSession = this.cursorClient.startSession({ owner: this, explicit: false });
16916
16915
  }
16917
16916
  }
16918
16917
  get id() {
16919
- return this[kId] ?? undefined;
16918
+ return this.cursorId ?? undefined;
16920
16919
  }
16921
16920
  get isDead() {
16922
- return (this[kId]?.isZero() ?? false) || this[kClosed] || this[kKilled];
16921
+ return (this.cursorId?.isZero() ?? false) || this.isClosed || this.isKilled;
16923
16922
  }
16924
16923
  get client() {
16925
- return this[kClient];
16924
+ return this.cursorClient;
16926
16925
  }
16927
16926
  get server() {
16928
- return this[kServer];
16927
+ return this.selectedServer;
16929
16928
  }
16930
16929
  get namespace() {
16931
- return this[kNamespace];
16930
+ return this.cursorNamespace;
16932
16931
  }
16933
16932
  get readPreference() {
16934
- return this[kOptions].readPreference;
16933
+ return this.cursorOptions.readPreference;
16935
16934
  }
16936
16935
  get readConcern() {
16937
- return this[kOptions].readConcern;
16936
+ return this.cursorOptions.readConcern;
16938
16937
  }
16939
16938
  get session() {
16940
- return this[kSession];
16939
+ return this.cursorSession;
16941
16940
  }
16942
16941
  set session(clientSession) {
16943
- this[kSession] = clientSession;
16944
- }
16945
- get cursorOptions() {
16946
- return this[kOptions];
16942
+ this.cursorSession = clientSession;
16947
16943
  }
16948
16944
  get closed() {
16949
- return this[kClosed];
16945
+ return this.isClosed && (this.documents?.length ?? 0) === 0;
16950
16946
  }
16951
16947
  get killed() {
16952
- return this[kKilled];
16948
+ return this.isKilled;
16953
16949
  }
16954
16950
  get loadBalanced() {
16955
- return !!this[kClient].topology?.loadBalanced;
16951
+ return !!this.cursorClient.topology?.loadBalanced;
16956
16952
  }
16957
16953
  bufferedCount() {
16958
- return this[kDocuments].length;
16954
+ return this.documents?.length ?? 0;
16959
16955
  }
16960
16956
  readBufferedDocuments(number) {
16961
16957
  const bufferedDocs = [];
16962
- const documentsToRead = Math.min(number ?? this[kDocuments].length, this[kDocuments].length);
16958
+ const documentsToRead = Math.min(number ?? this.documents?.length ?? 0, this.documents?.length ?? 0);
16963
16959
  for (let count = 0;count < documentsToRead; count++) {
16964
- const document = this[kDocuments].shift(this[kOptions]);
16960
+ const document = this.documents?.shift(this.cursorOptions);
16965
16961
  if (document != null) {
16966
16962
  bufferedDocs.push(document);
16967
16963
  }
@@ -16969,31 +16965,28 @@ var require_abstract_cursor = __commonJS((exports) => {
16969
16965
  return bufferedDocs;
16970
16966
  }
16971
16967
  async* [Symbol.asyncIterator]() {
16972
- if (this.closed) {
16968
+ if (this.isClosed) {
16973
16969
  return;
16974
16970
  }
16975
16971
  try {
16976
16972
  while (true) {
16973
+ if (this.isKilled) {
16974
+ return;
16975
+ }
16976
+ if (this.closed) {
16977
+ return;
16978
+ }
16979
+ if (this.cursorId != null && this.isDead && (this.documents?.length ?? 0) === 0) {
16980
+ return;
16981
+ }
16977
16982
  const document = await this.next();
16978
16983
  if (document === null) {
16979
- if (!this.closed) {
16980
- const message = "Cursor returned a `null` document, but the cursor is not exhausted. Mapping documents to `null` is not supported in the cursor transform.";
16981
- try {
16982
- await cleanupCursor(this, { needsToEmitClosed: true });
16983
- } catch (error) {
16984
- (0, utils_1.squashError)(error);
16985
- }
16986
- throw new error_1.MongoAPIError(message);
16987
- }
16988
- break;
16984
+ return;
16989
16985
  }
16990
16986
  yield document;
16991
- if (this[kId] === bson_1.Long.ZERO) {
16992
- break;
16993
- }
16994
16987
  }
16995
16988
  } finally {
16996
- if (!this.closed) {
16989
+ if (!this.isClosed) {
16997
16990
  try {
16998
16991
  await this.close();
16999
16992
  } catch (error) {
@@ -17024,25 +17017,50 @@ var require_abstract_cursor = __commonJS((exports) => {
17024
17017
  return new ReadableCursorStream(this);
17025
17018
  }
17026
17019
  async hasNext() {
17027
- if (this[kId] === bson_1.Long.ZERO) {
17020
+ if (this.cursorId === bson_1.Long.ZERO) {
17028
17021
  return false;
17029
17022
  }
17030
- if (this[kDocuments].length !== 0) {
17031
- return true;
17032
- }
17033
- return await next(this, { blocking: true, transform: false, shift: false });
17023
+ do {
17024
+ if ((this.documents?.length ?? 0) !== 0) {
17025
+ return true;
17026
+ }
17027
+ await this.fetchBatch();
17028
+ } while (!this.isDead || (this.documents?.length ?? 0) !== 0);
17029
+ return false;
17034
17030
  }
17035
17031
  async next() {
17036
- if (this[kId] === bson_1.Long.ZERO) {
17032
+ if (this.cursorId === bson_1.Long.ZERO) {
17037
17033
  throw new error_1.MongoCursorExhaustedError;
17038
17034
  }
17039
- return await next(this, { blocking: true, transform: true, shift: true });
17035
+ do {
17036
+ const doc = this.documents?.shift(this.cursorOptions);
17037
+ if (doc != null) {
17038
+ if (this.transform != null)
17039
+ return await this.transformDocument(doc);
17040
+ return doc;
17041
+ }
17042
+ await this.fetchBatch();
17043
+ } while (!this.isDead || (this.documents?.length ?? 0) !== 0);
17044
+ return null;
17040
17045
  }
17041
17046
  async tryNext() {
17042
- if (this[kId] === bson_1.Long.ZERO) {
17047
+ if (this.cursorId === bson_1.Long.ZERO) {
17043
17048
  throw new error_1.MongoCursorExhaustedError;
17044
17049
  }
17045
- return await next(this, { blocking: false, transform: true, shift: true });
17050
+ let doc = this.documents?.shift(this.cursorOptions);
17051
+ if (doc != null) {
17052
+ if (this.transform != null)
17053
+ return await this.transformDocument(doc);
17054
+ return doc;
17055
+ }
17056
+ await this.fetchBatch();
17057
+ doc = this.documents?.shift(this.cursorOptions);
17058
+ if (doc != null) {
17059
+ if (this.transform != null)
17060
+ return await this.transformDocument(doc);
17061
+ return doc;
17062
+ }
17063
+ return null;
17046
17064
  }
17047
17065
  async forEach(iterator) {
17048
17066
  if (typeof iterator !== "function") {
@@ -17056,9 +17074,7 @@ var require_abstract_cursor = __commonJS((exports) => {
17056
17074
  }
17057
17075
  }
17058
17076
  async close() {
17059
- const needsToEmitClosed = !this[kClosed];
17060
- this[kClosed] = true;
17061
- await cleanupCursor(this, { needsToEmitClosed });
17077
+ await this.cleanup();
17062
17078
  }
17063
17079
  async toArray() {
17064
17080
  const array = [];
@@ -17068,130 +17084,207 @@ var require_abstract_cursor = __commonJS((exports) => {
17068
17084
  return array;
17069
17085
  }
17070
17086
  addCursorFlag(flag, value) {
17071
- assertUninitialized(this);
17087
+ this.throwIfInitialized();
17072
17088
  if (!exports.CURSOR_FLAGS.includes(flag)) {
17073
17089
  throw new error_1.MongoInvalidArgumentError(`Flag ${flag} is not one of ${exports.CURSOR_FLAGS}`);
17074
17090
  }
17075
17091
  if (typeof value !== "boolean") {
17076
17092
  throw new error_1.MongoInvalidArgumentError(`Flag ${flag} must be a boolean value`);
17077
17093
  }
17078
- this[kOptions][flag] = value;
17094
+ this.cursorOptions[flag] = value;
17079
17095
  return this;
17080
17096
  }
17081
17097
  map(transform) {
17082
- assertUninitialized(this);
17083
- const oldTransform = this[kTransform];
17098
+ this.throwIfInitialized();
17099
+ const oldTransform = this.transform;
17084
17100
  if (oldTransform) {
17085
- this[kTransform] = (doc) => {
17101
+ this.transform = (doc) => {
17086
17102
  return transform(oldTransform(doc));
17087
17103
  };
17088
17104
  } else {
17089
- this[kTransform] = transform;
17105
+ this.transform = transform;
17090
17106
  }
17091
17107
  return this;
17092
17108
  }
17093
17109
  withReadPreference(readPreference) {
17094
- assertUninitialized(this);
17110
+ this.throwIfInitialized();
17095
17111
  if (readPreference instanceof read_preference_1.ReadPreference) {
17096
- this[kOptions].readPreference = readPreference;
17112
+ this.cursorOptions.readPreference = readPreference;
17097
17113
  } else if (typeof readPreference === "string") {
17098
- this[kOptions].readPreference = read_preference_1.ReadPreference.fromString(readPreference);
17114
+ this.cursorOptions.readPreference = read_preference_1.ReadPreference.fromString(readPreference);
17099
17115
  } else {
17100
17116
  throw new error_1.MongoInvalidArgumentError(`Invalid read preference: ${readPreference}`);
17101
17117
  }
17102
17118
  return this;
17103
17119
  }
17104
17120
  withReadConcern(readConcern) {
17105
- assertUninitialized(this);
17121
+ this.throwIfInitialized();
17106
17122
  const resolvedReadConcern = read_concern_1.ReadConcern.fromOptions({ readConcern });
17107
17123
  if (resolvedReadConcern) {
17108
- this[kOptions].readConcern = resolvedReadConcern;
17124
+ this.cursorOptions.readConcern = resolvedReadConcern;
17109
17125
  }
17110
17126
  return this;
17111
17127
  }
17112
17128
  maxTimeMS(value) {
17113
- assertUninitialized(this);
17129
+ this.throwIfInitialized();
17114
17130
  if (typeof value !== "number") {
17115
17131
  throw new error_1.MongoInvalidArgumentError("Argument for maxTimeMS must be a number");
17116
17132
  }
17117
- this[kOptions].maxTimeMS = value;
17133
+ this.cursorOptions.maxTimeMS = value;
17118
17134
  return this;
17119
17135
  }
17120
17136
  batchSize(value) {
17121
- assertUninitialized(this);
17122
- if (this[kOptions].tailable) {
17137
+ this.throwIfInitialized();
17138
+ if (this.cursorOptions.tailable) {
17123
17139
  throw new error_1.MongoTailableCursorError("Tailable cursor does not support batchSize");
17124
17140
  }
17125
17141
  if (typeof value !== "number") {
17126
17142
  throw new error_1.MongoInvalidArgumentError('Operation "batchSize" requires an integer');
17127
17143
  }
17128
- this[kOptions].batchSize = value;
17144
+ this.cursorOptions.batchSize = value;
17129
17145
  return this;
17130
17146
  }
17131
17147
  rewind() {
17132
- if (!this[kInitialized]) {
17148
+ if (!this.initialized) {
17133
17149
  return;
17134
17150
  }
17135
- this[kId] = null;
17136
- this[kDocuments].clear();
17137
- this[kClosed] = false;
17138
- this[kKilled] = false;
17139
- this[kInitialized] = false;
17140
- const session = this[kSession];
17151
+ this.cursorId = null;
17152
+ this.documents?.clear();
17153
+ this.isClosed = false;
17154
+ this.isKilled = false;
17155
+ this.initialized = false;
17156
+ const session = this.cursorSession;
17141
17157
  if (session) {
17142
17158
  if (session.explicit === false) {
17143
17159
  if (!session.hasEnded) {
17144
17160
  session.endSession().then(undefined, utils_1.squashError);
17145
17161
  }
17146
- this[kSession] = this.client.startSession({ owner: this, explicit: false });
17162
+ this.cursorSession = this.cursorClient.startSession({ owner: this, explicit: false });
17147
17163
  }
17148
17164
  }
17149
17165
  }
17150
- async getMore(batchSize, useCursorResponse = false) {
17151
- const getMoreOperation = new get_more_1.GetMoreOperation(this[kNamespace], this[kId], this[kServer], {
17152
- ...this[kOptions],
17153
- session: this[kSession],
17154
- batchSize,
17155
- useCursorResponse
17166
+ async getMore(batchSize) {
17167
+ if (this.cursorId == null) {
17168
+ throw new error_1.MongoRuntimeError("Unexpected null cursor id. A cursor creating command should have set this");
17169
+ }
17170
+ if (this.selectedServer == null) {
17171
+ throw new error_1.MongoRuntimeError("Unexpected null selectedServer. A cursor creating command should have set this");
17172
+ }
17173
+ const getMoreOperation = new get_more_1.GetMoreOperation(this.cursorNamespace, this.cursorId, this.selectedServer, {
17174
+ ...this.cursorOptions,
17175
+ session: this.cursorSession,
17176
+ batchSize
17156
17177
  });
17157
- return await (0, execute_operation_1.executeOperation)(this[kClient], getMoreOperation);
17178
+ return await (0, execute_operation_1.executeOperation)(this.cursorClient, getMoreOperation);
17158
17179
  }
17159
- async[kInit]() {
17180
+ async cursorInit() {
17160
17181
  try {
17161
- const state = await this._initialize(this[kSession]);
17182
+ const state = await this._initialize(this.cursorSession);
17162
17183
  const response = state.response;
17163
- this[kServer] = state.server;
17164
- if (responses_1.CursorResponse.is(response)) {
17165
- this[kId] = response.id;
17166
- if (response.ns)
17167
- this[kNamespace] = response.ns;
17168
- this[kDocuments] = response;
17169
- } else if (response.cursor) {
17170
- this[kId] = typeof response.cursor.id === "number" ? bson_1.Long.fromNumber(response.cursor.id) : typeof response.cursor.id === "bigint" ? bson_1.Long.fromBigInt(response.cursor.id) : response.cursor.id;
17171
- if (response.cursor.ns) {
17172
- this[kNamespace] = (0, utils_1.ns)(response.cursor.ns);
17173
- }
17174
- this[kDocuments].pushMany(response.cursor.firstBatch);
17175
- }
17176
- if (this[kId] == null) {
17177
- this[kId] = bson_1.Long.ZERO;
17178
- this[kDocuments].push(state.response);
17179
- }
17180
- this[kInitialized] = true;
17184
+ this.selectedServer = state.server;
17185
+ this.cursorId = response.id;
17186
+ this.cursorNamespace = response.ns ?? this.namespace;
17187
+ this.documents = response;
17188
+ this.initialized = true;
17181
17189
  } catch (error) {
17182
- this[kInitialized] = true;
17183
- await cleanupCursor(this, { error });
17190
+ this.initialized = true;
17191
+ await this.cleanup(error);
17184
17192
  throw error;
17185
17193
  }
17186
17194
  if (this.isDead) {
17187
- await cleanupCursor(this, undefined);
17195
+ await this.cleanup();
17188
17196
  }
17189
17197
  return;
17190
17198
  }
17199
+ async fetchBatch() {
17200
+ if (this.isClosed) {
17201
+ return;
17202
+ }
17203
+ if (this.isDead) {
17204
+ await this.cleanup();
17205
+ return;
17206
+ }
17207
+ if (this.cursorId == null) {
17208
+ await this.cursorInit();
17209
+ if ((this.documents?.length ?? 0) !== 0 || this.isDead)
17210
+ return;
17211
+ }
17212
+ const batchSize = this.cursorOptions.batchSize || 1000;
17213
+ try {
17214
+ const response = await this.getMore(batchSize);
17215
+ this.cursorId = response.id;
17216
+ this.documents = response;
17217
+ } catch (error) {
17218
+ try {
17219
+ await this.cleanup(error);
17220
+ } catch (error2) {
17221
+ (0, utils_1.squashError)(error2);
17222
+ }
17223
+ throw error;
17224
+ }
17225
+ if (this.isDead) {
17226
+ await this.cleanup();
17227
+ }
17228
+ }
17229
+ async cleanup(error) {
17230
+ this.isClosed = true;
17231
+ const session = this.cursorSession;
17232
+ try {
17233
+ if (!this.isKilled && this.cursorId && !this.cursorId.isZero() && this.cursorNamespace && this.selectedServer && !session.hasEnded) {
17234
+ this.isKilled = true;
17235
+ const cursorId = this.cursorId;
17236
+ this.cursorId = bson_1.Long.ZERO;
17237
+ await (0, execute_operation_1.executeOperation)(this.cursorClient, new kill_cursors_1.KillCursorsOperation(cursorId, this.cursorNamespace, this.selectedServer, {
17238
+ session
17239
+ }));
17240
+ }
17241
+ } catch (error2) {
17242
+ (0, utils_1.squashError)(error2);
17243
+ } finally {
17244
+ if (session?.owner === this) {
17245
+ await session.endSession({ error });
17246
+ }
17247
+ if (!session?.inTransaction()) {
17248
+ (0, sessions_1.maybeClearPinnedConnection)(session, { error });
17249
+ }
17250
+ this.emitClose();
17251
+ }
17252
+ }
17253
+ emitClose() {
17254
+ try {
17255
+ if (!this.hasEmittedClose && ((this.documents?.length ?? 0) === 0 || this.isClosed)) {
17256
+ this.emit("close");
17257
+ }
17258
+ } finally {
17259
+ this.hasEmittedClose = true;
17260
+ }
17261
+ }
17262
+ async transformDocument(document) {
17263
+ if (this.transform == null)
17264
+ return document;
17265
+ try {
17266
+ const transformedDocument = this.transform(document);
17267
+ if (transformedDocument === null) {
17268
+ const TRANSFORM_TO_NULL_ERROR = "Cursor returned a `null` document, but the cursor is not exhausted. Mapping documents to `null` is not supported in the cursor transform.";
17269
+ throw new error_1.MongoAPIError(TRANSFORM_TO_NULL_ERROR);
17270
+ }
17271
+ return transformedDocument;
17272
+ } catch (transformError) {
17273
+ try {
17274
+ await this.close();
17275
+ } catch (closeError) {
17276
+ (0, utils_1.squashError)(closeError);
17277
+ }
17278
+ throw transformError;
17279
+ }
17280
+ }
17281
+ throwIfInitialized() {
17282
+ if (this.initialized)
17283
+ throw new error_1.MongoCursorInUseError;
17284
+ }
17191
17285
  }
17192
17286
  AbstractCursor.CLOSE = "close";
17193
17287
  exports.AbstractCursor = AbstractCursor;
17194
- exports.assertUninitialized = assertUninitialized;
17195
17288
 
17196
17289
  class ReadableCursorStream extends stream_1.Readable {
17197
17290
  constructor(cursor) {
@@ -17213,7 +17306,11 @@ var require_abstract_cursor = __commonJS((exports) => {
17213
17306
  this._cursor.close().then(() => callback(error), (closeError) => callback(closeError));
17214
17307
  }
17215
17308
  _readNext() {
17216
- next(this._cursor, { blocking: true, transform: true, shift: true }).then((result) => {
17309
+ if (this._cursor.id === bson_1.Long.ZERO) {
17310
+ this.push(null);
17311
+ return;
17312
+ }
17313
+ this._cursor.next().then((result) => {
17217
17314
  if (result == null) {
17218
17315
  this.push(null);
17219
17316
  } else if (this.destroyed) {
@@ -17246,22 +17343,17 @@ var require_aggregation_cursor = __commonJS((exports) => {
17246
17343
  var execute_operation_1 = require_execute_operation();
17247
17344
  var utils_1 = require_utils2();
17248
17345
  var abstract_cursor_1 = require_abstract_cursor();
17249
- var kPipeline = Symbol("pipeline");
17250
- var kOptions = Symbol("options");
17251
17346
 
17252
17347
  class AggregationCursor extends abstract_cursor_1.AbstractCursor {
17253
17348
  constructor(client, namespace, pipeline = [], options = {}) {
17254
17349
  super(client, namespace, options);
17255
- this[kPipeline] = pipeline;
17256
- this[kOptions] = options;
17257
- }
17258
- get pipeline() {
17259
- return this[kPipeline];
17350
+ this.pipeline = pipeline;
17351
+ this.aggregateOptions = options;
17260
17352
  }
17261
17353
  clone() {
17262
- const clonedOptions = (0, utils_1.mergeOptions)({}, this[kOptions]);
17354
+ const clonedOptions = (0, utils_1.mergeOptions)({}, this.aggregateOptions);
17263
17355
  delete clonedOptions.session;
17264
- return new AggregationCursor(this.client, this.namespace, this[kPipeline], {
17356
+ return new AggregationCursor(this.client, this.namespace, this.pipeline, {
17265
17357
  ...clonedOptions
17266
17358
  });
17267
17359
  }
@@ -17269,8 +17361,8 @@ var require_aggregation_cursor = __commonJS((exports) => {
17269
17361
  return super.map(transform);
17270
17362
  }
17271
17363
  async _initialize(session) {
17272
- const aggregateOperation = new aggregate_1.AggregateOperation(this.namespace, this[kPipeline], {
17273
- ...this[kOptions],
17364
+ const aggregateOperation = new aggregate_1.AggregateOperation(this.namespace, this.pipeline, {
17365
+ ...this.aggregateOptions,
17274
17366
  ...this.cursorOptions,
17275
17367
  session
17276
17368
  });
@@ -17278,15 +17370,15 @@ var require_aggregation_cursor = __commonJS((exports) => {
17278
17370
  return { server: aggregateOperation.server, session, response };
17279
17371
  }
17280
17372
  async explain(verbosity) {
17281
- return await (0, execute_operation_1.executeOperation)(this.client, new aggregate_1.AggregateOperation(this.namespace, this[kPipeline], {
17282
- ...this[kOptions],
17373
+ return (await (0, execute_operation_1.executeOperation)(this.client, new aggregate_1.AggregateOperation(this.namespace, this.pipeline, {
17374
+ ...this.aggregateOptions,
17283
17375
  ...this.cursorOptions,
17284
17376
  explain: verbosity ?? true
17285
- }));
17377
+ }))).shift(this.aggregateOptions);
17286
17378
  }
17287
17379
  addStage(stage) {
17288
- (0, abstract_cursor_1.assertUninitialized)(this);
17289
- this[kPipeline].push(stage);
17380
+ this.throwIfInitialized();
17381
+ this.pipeline.push(stage);
17290
17382
  return this;
17291
17383
  }
17292
17384
  group($group) {
@@ -17557,6 +17649,7 @@ var require_find = __commonJS((exports) => {
17557
17649
  };
17558
17650
  Object.defineProperty(exports, "__esModule", { value: true });
17559
17651
  exports.FindOperation = undefined;
17652
+ var responses_1 = require_responses();
17560
17653
  var error_1 = require_error();
17561
17654
  var read_concern_1 = require_read_concern();
17562
17655
  var sort_1 = require_sort();
@@ -17590,7 +17683,7 @@ var require_find = __commonJS((exports) => {
17590
17683
  ...this.bsonOptions,
17591
17684
  documentsReturnedIn: "firstBatch",
17592
17685
  session
17593
- }, undefined);
17686
+ }, this.explain ? responses_1.ExplainedCursorResponse : responses_1.CursorResponse);
17594
17687
  }
17595
17688
  }
17596
17689
  exports.FindOperation = FindOperation;
@@ -17604,7 +17697,6 @@ var require_find = __commonJS((exports) => {
17604
17697
 
17605
17698
  // node_modules/mongodb/lib/cursor/find_cursor.js
17606
17699
  var require_find_cursor = __commonJS((exports) => {
17607
- var _a;
17608
17700
  Object.defineProperty(exports, "__esModule", { value: true });
17609
17701
  exports.FindCursor = exports.FLAGS = undefined;
17610
17702
  var responses_1 = require_responses();
@@ -17615,9 +17707,6 @@ var require_find_cursor = __commonJS((exports) => {
17615
17707
  var sort_1 = require_sort();
17616
17708
  var utils_1 = require_utils2();
17617
17709
  var abstract_cursor_1 = require_abstract_cursor();
17618
- var kFilter = Symbol("filter");
17619
- var kNumReturned = Symbol("numReturned");
17620
- var kBuiltOptions = Symbol("builtOptions");
17621
17710
  exports.FLAGS = [
17622
17711
  "tailable",
17623
17712
  "oplogReplay",
@@ -17630,17 +17719,17 @@ var require_find_cursor = __commonJS((exports) => {
17630
17719
  class FindCursor extends abstract_cursor_1.AbstractCursor {
17631
17720
  constructor(client, namespace, filter = {}, options = {}) {
17632
17721
  super(client, namespace, options);
17633
- this[_a] = 0;
17634
- this[kFilter] = filter;
17635
- this[kBuiltOptions] = options;
17722
+ this.numReturned = 0;
17723
+ this.cursorFilter = filter;
17724
+ this.findOptions = options;
17636
17725
  if (options.sort != null) {
17637
- this[kBuiltOptions].sort = (0, sort_1.formatSort)(options.sort);
17726
+ this.findOptions.sort = (0, sort_1.formatSort)(options.sort);
17638
17727
  }
17639
17728
  }
17640
17729
  clone() {
17641
- const clonedOptions = (0, utils_1.mergeOptions)({}, this[kBuiltOptions]);
17730
+ const clonedOptions = (0, utils_1.mergeOptions)({}, this.findOptions);
17642
17731
  delete clonedOptions.session;
17643
- return new FindCursor(this.client, this.namespace, this[kFilter], {
17732
+ return new FindCursor(this.client, this.namespace, this.cursorFilter, {
17644
17733
  ...clonedOptions
17645
17734
  });
17646
17735
  }
@@ -17648,23 +17737,19 @@ var require_find_cursor = __commonJS((exports) => {
17648
17737
  return super.map(transform);
17649
17738
  }
17650
17739
  async _initialize(session) {
17651
- const findOperation = new find_1.FindOperation(this.namespace, this[kFilter], {
17652
- ...this[kBuiltOptions],
17740
+ const findOperation = new find_1.FindOperation(this.namespace, this.cursorFilter, {
17741
+ ...this.findOptions,
17653
17742
  ...this.cursorOptions,
17654
17743
  session
17655
17744
  });
17656
17745
  const response = await (0, execute_operation_1.executeOperation)(this.client, findOperation);
17657
- if (responses_1.CursorResponse.is(response)) {
17658
- this[kNumReturned] = response.batchSize;
17659
- } else {
17660
- this[kNumReturned] = this[kNumReturned] + (response?.cursor?.firstBatch?.length ?? 0);
17661
- }
17746
+ this.numReturned = response.batchSize;
17662
17747
  return { server: findOperation.server, session, response };
17663
17748
  }
17664
17749
  async getMore(batchSize) {
17665
- const numReturned = this[kNumReturned];
17750
+ const numReturned = this.numReturned;
17666
17751
  if (numReturned) {
17667
- const limit = this[kBuiltOptions].limit;
17752
+ const limit = this.findOptions.limit;
17668
17753
  batchSize = limit && limit > 0 && numReturned + batchSize > limit ? limit - numReturned : batchSize;
17669
17754
  if (batchSize <= 0) {
17670
17755
  try {
@@ -17675,12 +17760,8 @@ var require_find_cursor = __commonJS((exports) => {
17675
17760
  return responses_1.CursorResponse.emptyGetMore;
17676
17761
  }
17677
17762
  }
17678
- const response = await super.getMore(batchSize, false);
17679
- if (responses_1.CursorResponse.is(response)) {
17680
- this[kNumReturned] = this[kNumReturned] + response.batchSize;
17681
- } else {
17682
- this[kNumReturned] = this[kNumReturned] + (response?.cursor?.nextBatch?.length ?? 0);
17683
- }
17763
+ const response = await super.getMore(batchSize);
17764
+ this.numReturned = this.numReturned + response.batchSize;
17684
17765
  return response;
17685
17766
  }
17686
17767
  async count(options) {
@@ -17688,85 +17769,85 @@ var require_find_cursor = __commonJS((exports) => {
17688
17769
  if (typeof options === "boolean") {
17689
17770
  throw new error_1.MongoInvalidArgumentError("Invalid first parameter to count");
17690
17771
  }
17691
- return await (0, execute_operation_1.executeOperation)(this.client, new count_1.CountOperation(this.namespace, this[kFilter], {
17692
- ...this[kBuiltOptions],
17772
+ return await (0, execute_operation_1.executeOperation)(this.client, new count_1.CountOperation(this.namespace, this.cursorFilter, {
17773
+ ...this.findOptions,
17693
17774
  ...this.cursorOptions,
17694
17775
  ...options
17695
17776
  }));
17696
17777
  }
17697
17778
  async explain(verbosity) {
17698
- return await (0, execute_operation_1.executeOperation)(this.client, new find_1.FindOperation(this.namespace, this[kFilter], {
17699
- ...this[kBuiltOptions],
17779
+ return (await (0, execute_operation_1.executeOperation)(this.client, new find_1.FindOperation(this.namespace, this.cursorFilter, {
17780
+ ...this.findOptions,
17700
17781
  ...this.cursorOptions,
17701
17782
  explain: verbosity ?? true
17702
- }));
17783
+ }))).shift(this.findOptions);
17703
17784
  }
17704
17785
  filter(filter) {
17705
- (0, abstract_cursor_1.assertUninitialized)(this);
17706
- this[kFilter] = filter;
17786
+ this.throwIfInitialized();
17787
+ this.cursorFilter = filter;
17707
17788
  return this;
17708
17789
  }
17709
17790
  hint(hint) {
17710
- (0, abstract_cursor_1.assertUninitialized)(this);
17711
- this[kBuiltOptions].hint = hint;
17791
+ this.throwIfInitialized();
17792
+ this.findOptions.hint = hint;
17712
17793
  return this;
17713
17794
  }
17714
17795
  min(min) {
17715
- (0, abstract_cursor_1.assertUninitialized)(this);
17716
- this[kBuiltOptions].min = min;
17796
+ this.throwIfInitialized();
17797
+ this.findOptions.min = min;
17717
17798
  return this;
17718
17799
  }
17719
17800
  max(max) {
17720
- (0, abstract_cursor_1.assertUninitialized)(this);
17721
- this[kBuiltOptions].max = max;
17801
+ this.throwIfInitialized();
17802
+ this.findOptions.max = max;
17722
17803
  return this;
17723
17804
  }
17724
17805
  returnKey(value) {
17725
- (0, abstract_cursor_1.assertUninitialized)(this);
17726
- this[kBuiltOptions].returnKey = value;
17806
+ this.throwIfInitialized();
17807
+ this.findOptions.returnKey = value;
17727
17808
  return this;
17728
17809
  }
17729
17810
  showRecordId(value) {
17730
- (0, abstract_cursor_1.assertUninitialized)(this);
17731
- this[kBuiltOptions].showRecordId = value;
17811
+ this.throwIfInitialized();
17812
+ this.findOptions.showRecordId = value;
17732
17813
  return this;
17733
17814
  }
17734
17815
  addQueryModifier(name, value) {
17735
- (0, abstract_cursor_1.assertUninitialized)(this);
17816
+ this.throwIfInitialized();
17736
17817
  if (name[0] !== "$") {
17737
17818
  throw new error_1.MongoInvalidArgumentError(`${name} is not a valid query modifier`);
17738
17819
  }
17739
17820
  const field = name.substr(1);
17740
17821
  switch (field) {
17741
17822
  case "comment":
17742
- this[kBuiltOptions].comment = value;
17823
+ this.findOptions.comment = value;
17743
17824
  break;
17744
17825
  case "explain":
17745
- this[kBuiltOptions].explain = value;
17826
+ this.findOptions.explain = value;
17746
17827
  break;
17747
17828
  case "hint":
17748
- this[kBuiltOptions].hint = value;
17829
+ this.findOptions.hint = value;
17749
17830
  break;
17750
17831
  case "max":
17751
- this[kBuiltOptions].max = value;
17832
+ this.findOptions.max = value;
17752
17833
  break;
17753
17834
  case "maxTimeMS":
17754
- this[kBuiltOptions].maxTimeMS = value;
17835
+ this.findOptions.maxTimeMS = value;
17755
17836
  break;
17756
17837
  case "min":
17757
- this[kBuiltOptions].min = value;
17838
+ this.findOptions.min = value;
17758
17839
  break;
17759
17840
  case "orderby":
17760
- this[kBuiltOptions].sort = (0, sort_1.formatSort)(value);
17841
+ this.findOptions.sort = (0, sort_1.formatSort)(value);
17761
17842
  break;
17762
17843
  case "query":
17763
- this[kFilter] = value;
17844
+ this.cursorFilter = value;
17764
17845
  break;
17765
17846
  case "returnKey":
17766
- this[kBuiltOptions].returnKey = value;
17847
+ this.findOptions.returnKey = value;
17767
17848
  break;
17768
17849
  case "showDiskLoc":
17769
- this[kBuiltOptions].showRecordId = value;
17850
+ this.findOptions.showRecordId = value;
17770
17851
  break;
17771
17852
  default:
17772
17853
  throw new error_1.MongoInvalidArgumentError(`Invalid query modifier: ${name}`);
@@ -17774,81 +17855,80 @@ var require_find_cursor = __commonJS((exports) => {
17774
17855
  return this;
17775
17856
  }
17776
17857
  comment(value) {
17777
- (0, abstract_cursor_1.assertUninitialized)(this);
17778
- this[kBuiltOptions].comment = value;
17858
+ this.throwIfInitialized();
17859
+ this.findOptions.comment = value;
17779
17860
  return this;
17780
17861
  }
17781
17862
  maxAwaitTimeMS(value) {
17782
- (0, abstract_cursor_1.assertUninitialized)(this);
17863
+ this.throwIfInitialized();
17783
17864
  if (typeof value !== "number") {
17784
17865
  throw new error_1.MongoInvalidArgumentError("Argument for maxAwaitTimeMS must be a number");
17785
17866
  }
17786
- this[kBuiltOptions].maxAwaitTimeMS = value;
17867
+ this.findOptions.maxAwaitTimeMS = value;
17787
17868
  return this;
17788
17869
  }
17789
17870
  maxTimeMS(value) {
17790
- (0, abstract_cursor_1.assertUninitialized)(this);
17871
+ this.throwIfInitialized();
17791
17872
  if (typeof value !== "number") {
17792
17873
  throw new error_1.MongoInvalidArgumentError("Argument for maxTimeMS must be a number");
17793
17874
  }
17794
- this[kBuiltOptions].maxTimeMS = value;
17875
+ this.findOptions.maxTimeMS = value;
17795
17876
  return this;
17796
17877
  }
17797
17878
  project(value) {
17798
- (0, abstract_cursor_1.assertUninitialized)(this);
17799
- this[kBuiltOptions].projection = value;
17879
+ this.throwIfInitialized();
17880
+ this.findOptions.projection = value;
17800
17881
  return this;
17801
17882
  }
17802
17883
  sort(sort, direction) {
17803
- (0, abstract_cursor_1.assertUninitialized)(this);
17804
- if (this[kBuiltOptions].tailable) {
17884
+ this.throwIfInitialized();
17885
+ if (this.findOptions.tailable) {
17805
17886
  throw new error_1.MongoTailableCursorError("Tailable cursor does not support sorting");
17806
17887
  }
17807
- this[kBuiltOptions].sort = (0, sort_1.formatSort)(sort, direction);
17888
+ this.findOptions.sort = (0, sort_1.formatSort)(sort, direction);
17808
17889
  return this;
17809
17890
  }
17810
17891
  allowDiskUse(allow = true) {
17811
- (0, abstract_cursor_1.assertUninitialized)(this);
17812
- if (!this[kBuiltOptions].sort) {
17892
+ this.throwIfInitialized();
17893
+ if (!this.findOptions.sort) {
17813
17894
  throw new error_1.MongoInvalidArgumentError('Option "allowDiskUse" requires a sort specification');
17814
17895
  }
17815
17896
  if (!allow) {
17816
- this[kBuiltOptions].allowDiskUse = false;
17897
+ this.findOptions.allowDiskUse = false;
17817
17898
  return this;
17818
17899
  }
17819
- this[kBuiltOptions].allowDiskUse = true;
17900
+ this.findOptions.allowDiskUse = true;
17820
17901
  return this;
17821
17902
  }
17822
17903
  collation(value) {
17823
- (0, abstract_cursor_1.assertUninitialized)(this);
17824
- this[kBuiltOptions].collation = value;
17904
+ this.throwIfInitialized();
17905
+ this.findOptions.collation = value;
17825
17906
  return this;
17826
17907
  }
17827
17908
  limit(value) {
17828
- (0, abstract_cursor_1.assertUninitialized)(this);
17829
- if (this[kBuiltOptions].tailable) {
17909
+ this.throwIfInitialized();
17910
+ if (this.findOptions.tailable) {
17830
17911
  throw new error_1.MongoTailableCursorError("Tailable cursor does not support limit");
17831
17912
  }
17832
17913
  if (typeof value !== "number") {
17833
17914
  throw new error_1.MongoInvalidArgumentError('Operation "limit" requires an integer');
17834
17915
  }
17835
- this[kBuiltOptions].limit = value;
17916
+ this.findOptions.limit = value;
17836
17917
  return this;
17837
17918
  }
17838
17919
  skip(value) {
17839
- (0, abstract_cursor_1.assertUninitialized)(this);
17840
- if (this[kBuiltOptions].tailable) {
17920
+ this.throwIfInitialized();
17921
+ if (this.findOptions.tailable) {
17841
17922
  throw new error_1.MongoTailableCursorError("Tailable cursor does not support skip");
17842
17923
  }
17843
17924
  if (typeof value !== "number") {
17844
17925
  throw new error_1.MongoInvalidArgumentError('Operation "skip" requires an integer');
17845
17926
  }
17846
- this[kBuiltOptions].skip = value;
17927
+ this.findOptions.skip = value;
17847
17928
  return this;
17848
17929
  }
17849
17930
  }
17850
17931
  exports.FindCursor = FindCursor;
17851
- _a = kNumReturned;
17852
17932
  });
17853
17933
 
17854
17934
  // node_modules/mongodb/lib/operations/indexes.js
@@ -17885,6 +17965,7 @@ var require_indexes = __commonJS((exports) => {
17885
17965
  };
17886
17966
  Object.defineProperty(exports, "__esModule", { value: true });
17887
17967
  exports.ListIndexesOperation = exports.DropIndexOperation = exports.CreateIndexesOperation = undefined;
17968
+ var responses_1 = require_responses();
17888
17969
  var error_1 = require_error();
17889
17970
  var utils_1 = require_utils2();
17890
17971
  var command_1 = require_command();
@@ -17992,7 +18073,7 @@ var require_indexes = __commonJS((exports) => {
17992
18073
  if (serverWireVersion >= 9 && this.options.comment !== undefined) {
17993
18074
  command2.comment = this.options.comment;
17994
18075
  }
17995
- return await super.executeCommand(server, session, command2);
18076
+ return await super.executeCommand(server, session, command2, responses_1.CursorResponse);
17996
18077
  }
17997
18078
  }
17998
18079
  exports.ListIndexesOperation = ListIndexesOperation;
@@ -18053,38 +18134,6 @@ var require_list_search_indexes_cursor = __commonJS((exports) => {
18053
18134
  exports.ListSearchIndexesCursor = ListSearchIndexesCursor;
18054
18135
  });
18055
18136
 
18056
- // node_modules/mongodb/lib/operations/count_documents.js
18057
- var require_count_documents = __commonJS((exports) => {
18058
- Object.defineProperty(exports, "__esModule", { value: true });
18059
- exports.CountDocumentsOperation = undefined;
18060
- var aggregate_1 = require_aggregate();
18061
-
18062
- class CountDocumentsOperation extends aggregate_1.AggregateOperation {
18063
- constructor(collection, query, options) {
18064
- const pipeline = [];
18065
- pipeline.push({ $match: query });
18066
- if (typeof options.skip === "number") {
18067
- pipeline.push({ $skip: options.skip });
18068
- }
18069
- if (typeof options.limit === "number") {
18070
- pipeline.push({ $limit: options.limit });
18071
- }
18072
- pipeline.push({ $group: { _id: 1, n: { $sum: 1 } } });
18073
- super(collection.s.namespace, pipeline, options);
18074
- }
18075
- async execute(server, session) {
18076
- const result = await super.execute(server, session);
18077
- const response = result;
18078
- if (response.cursor == null || response.cursor.firstBatch == null) {
18079
- return 0;
18080
- }
18081
- const docs = response.cursor.firstBatch;
18082
- return docs.length ? docs[0].n : 0;
18083
- }
18084
- }
18085
- exports.CountDocumentsOperation = CountDocumentsOperation;
18086
- });
18087
-
18088
18137
  // node_modules/mongodb/lib/operations/distinct.js
18089
18138
  var require_distinct = __commonJS((exports) => {
18090
18139
  Object.defineProperty(exports, "__esModule", { value: true });
@@ -18581,7 +18630,6 @@ var require_collection = __commonJS((exports) => {
18581
18630
  var error_1 = require_error();
18582
18631
  var bulk_write_1 = require_bulk_write();
18583
18632
  var count_1 = require_count();
18584
- var count_documents_1 = require_count_documents();
18585
18633
  var delete_1 = require_delete();
18586
18634
  var distinct_1 = require_distinct();
18587
18635
  var drop_1 = require_drop();
@@ -18745,7 +18793,19 @@ var require_collection = __commonJS((exports) => {
18745
18793
  return await (0, execute_operation_1.executeOperation)(this.client, new estimated_document_count_1.EstimatedDocumentCountOperation(this, (0, utils_1.resolveOptions)(this, options)));
18746
18794
  }
18747
18795
  async countDocuments(filter = {}, options = {}) {
18748
- return await (0, execute_operation_1.executeOperation)(this.client, new count_documents_1.CountDocumentsOperation(this, filter, (0, utils_1.resolveOptions)(this, options)));
18796
+ const pipeline = [];
18797
+ pipeline.push({ $match: filter });
18798
+ if (typeof options.skip === "number") {
18799
+ pipeline.push({ $skip: options.skip });
18800
+ }
18801
+ if (typeof options.limit === "number") {
18802
+ pipeline.push({ $limit: options.limit });
18803
+ }
18804
+ pipeline.push({ $group: { _id: 1, n: { $sum: 1 } } });
18805
+ const cursor = this.aggregate(pipeline, options);
18806
+ const doc = await cursor.next();
18807
+ await cursor.close();
18808
+ return doc?.n ?? 0;
18749
18809
  }
18750
18810
  async distinct(key, filter = {}, options = {}) {
18751
18811
  return await (0, execute_operation_1.executeOperation)(this.client, new distinct_1.DistinctOperation(this, key, filter, (0, utils_1.resolveOptions)(this, options)));
@@ -18827,9 +18887,9 @@ var require_change_stream_cursor = __commonJS((exports) => {
18827
18887
  constructor(client, namespace, pipeline = [], options = {}) {
18828
18888
  super(client, namespace, options);
18829
18889
  this.pipeline = pipeline;
18830
- this.options = options;
18890
+ this.changeStreamCursorOptions = options;
18831
18891
  this._resumeToken = null;
18832
- this.startAtOperationTime = options.startAtOperationTime;
18892
+ this.startAtOperationTime = options.startAtOperationTime ?? null;
18833
18893
  if (options.startAfter) {
18834
18894
  this.resumeToken = options.startAfter;
18835
18895
  } else if (options.resumeAfter) {
@@ -18845,13 +18905,13 @@ var require_change_stream_cursor = __commonJS((exports) => {
18845
18905
  }
18846
18906
  get resumeOptions() {
18847
18907
  const options = {
18848
- ...this.options
18908
+ ...this.changeStreamCursorOptions
18849
18909
  };
18850
18910
  for (const key of ["resumeAfter", "startAfter", "startAtOperationTime"]) {
18851
18911
  delete options[key];
18852
18912
  }
18853
18913
  if (this.resumeToken != null) {
18854
- if (this.options.startAfter && !this.hasReceived) {
18914
+ if (this.changeStreamCursorOptions.startAfter && !this.hasReceived) {
18855
18915
  options.startAfter = this.resumeToken;
18856
18916
  } else {
18857
18917
  options.resumeAfter = this.resumeToken;
@@ -18870,12 +18930,11 @@ var require_change_stream_cursor = __commonJS((exports) => {
18870
18930
  this.hasReceived = true;
18871
18931
  }
18872
18932
  _processBatch(response) {
18873
- const cursor = response.cursor;
18874
- if (cursor.postBatchResumeToken) {
18875
- this.postBatchResumeToken = response.cursor.postBatchResumeToken;
18876
- const batch = "firstBatch" in response.cursor ? response.cursor.firstBatch : response.cursor.nextBatch;
18877
- if (batch.length === 0) {
18878
- this.resumeToken = cursor.postBatchResumeToken;
18933
+ const { postBatchResumeToken } = response;
18934
+ if (postBatchResumeToken) {
18935
+ this.postBatchResumeToken = postBatchResumeToken;
18936
+ if (response.batchSize === 0) {
18937
+ this.resumeToken = postBatchResumeToken;
18879
18938
  }
18880
18939
  }
18881
18940
  }
@@ -18887,13 +18946,13 @@ var require_change_stream_cursor = __commonJS((exports) => {
18887
18946
  async _initialize(session) {
18888
18947
  const aggregateOperation = new aggregate_1.AggregateOperation(this.namespace, this.pipeline, {
18889
18948
  ...this.cursorOptions,
18890
- ...this.options,
18949
+ ...this.changeStreamCursorOptions,
18891
18950
  session
18892
18951
  });
18893
18952
  const response = await (0, execute_operation_1.executeOperation)(session.client, aggregateOperation);
18894
18953
  const server = aggregateOperation.server;
18895
18954
  this.maxWireVersion = (0, utils_1.maxWireVersion)(server);
18896
- if (this.startAtOperationTime == null && this.resumeAfter == null && this.startAfter == null && this.maxWireVersion >= 7) {
18955
+ if (this.startAtOperationTime == null && this.changeStreamCursorOptions.resumeAfter == null && this.changeStreamCursorOptions.startAfter == null && this.maxWireVersion >= 7) {
18897
18956
  this.startAtOperationTime = response.operationTime;
18898
18957
  }
18899
18958
  this._processBatch(response);
@@ -18917,6 +18976,7 @@ var require_change_stream_cursor = __commonJS((exports) => {
18917
18976
  var require_list_collections = __commonJS((exports) => {
18918
18977
  Object.defineProperty(exports, "__esModule", { value: true });
18919
18978
  exports.ListCollectionsOperation = undefined;
18979
+ var responses_1 = require_responses();
18920
18980
  var utils_1 = require_utils2();
18921
18981
  var command_1 = require_command();
18922
18982
  var operation_1 = require_operation();
@@ -18938,7 +18998,7 @@ var require_list_collections = __commonJS((exports) => {
18938
18998
  return "listCollections";
18939
18999
  }
18940
19000
  async execute(server, session) {
18941
- return await super.executeCommand(server, session, this.generateCommand((0, utils_1.maxWireVersion)(server)));
19001
+ return await super.executeCommand(server, session, this.generateCommand((0, utils_1.maxWireVersion)(server)), responses_1.CursorResponse);
18942
19002
  }
18943
19003
  generateCommand(wireVersion) {
18944
19004
  const command2 = {
@@ -19000,6 +19060,7 @@ var require_list_collections_cursor = __commonJS((exports) => {
19000
19060
  var require_run_command_cursor = __commonJS((exports) => {
19001
19061
  Object.defineProperty(exports, "__esModule", { value: true });
19002
19062
  exports.RunCommandCursor = undefined;
19063
+ var responses_1 = require_responses();
19003
19064
  var error_1 = require_error();
19004
19065
  var execute_operation_1 = require_execute_operation();
19005
19066
  var get_more_1 = require_get_more();
@@ -19045,12 +19106,10 @@ var require_run_command_cursor = __commonJS((exports) => {
19045
19106
  const operation = new run_command_1.RunCommandOperation(this.db, this.command, {
19046
19107
  ...this.cursorOptions,
19047
19108
  session,
19048
- readPreference: this.cursorOptions.readPreference
19109
+ readPreference: this.cursorOptions.readPreference,
19110
+ responseType: responses_1.CursorResponse
19049
19111
  });
19050
19112
  const response = await (0, execute_operation_1.executeOperation)(this.client, operation);
19051
- if (response.cursor == null) {
19052
- throw new error_1.MongoUnexpectedServerResponseError("Expected server to respond with cursor");
19053
- }
19054
19113
  return {
19055
19114
  server: operation.server,
19056
19115
  session,
@@ -19061,8 +19120,7 @@ var require_run_command_cursor = __commonJS((exports) => {
19061
19120
  const getMoreOperation = new get_more_1.GetMoreOperation(this.namespace, this.id, this.server, {
19062
19121
  ...this.cursorOptions,
19063
19122
  session: this.session,
19064
- ...this.getMoreOptions,
19065
- useCursorResponse: false
19123
+ ...this.getMoreOptions
19066
19124
  });
19067
19125
  return await (0, execute_operation_1.executeOperation)(this.client, getMoreOperation);
19068
19126
  }
@@ -19787,17 +19845,22 @@ var require_mongo_credentials = __commonJS((exports) => {
19787
19845
  var error_1 = require_error();
19788
19846
  var gssapi_1 = require_gssapi();
19789
19847
  var providers_1 = require_providers();
19790
- var ALLOWED_PROVIDER_NAMES = ["aws", "azure"];
19848
+ var ALLOWED_ENVIRONMENT_NAMES = [
19849
+ "test",
19850
+ "azure",
19851
+ "gcp"
19852
+ ];
19791
19853
  var ALLOWED_HOSTS_ERROR = "Auth mechanism property ALLOWED_HOSTS must be an array of strings.";
19792
19854
  exports.DEFAULT_ALLOWED_HOSTS = [
19793
19855
  "*.mongodb.net",
19856
+ "*.mongodb-qa.net",
19794
19857
  "*.mongodb-dev.net",
19795
19858
  "*.mongodbgov.net",
19796
19859
  "localhost",
19797
19860
  "127.0.0.1",
19798
19861
  "::1"
19799
19862
  ];
19800
- var TOKEN_AUDIENCE_MISSING_ERROR = "TOKEN_AUDIENCE must be set in the auth mechanism properties when PROVIDER_NAME is azure.";
19863
+ var TOKEN_RESOURCE_MISSING_ERROR = "TOKEN_RESOURCE must be set in the auth mechanism properties when ENVIRONMENT is azure or gcp.";
19801
19864
 
19802
19865
  class MongoCredentials {
19803
19866
  constructor(options) {
@@ -19852,20 +19915,20 @@ var require_mongo_credentials = __commonJS((exports) => {
19852
19915
  throw new error_1.MongoMissingCredentialsError(`Username required for mechanism '${this.mechanism}'`);
19853
19916
  }
19854
19917
  if (this.mechanism === providers_1.AuthMechanism.MONGODB_OIDC) {
19855
- if (this.username && this.mechanismProperties.PROVIDER_NAME) {
19856
- throw new error_1.MongoInvalidArgumentError(`username and PROVIDER_NAME may not be used together for mechanism '${this.mechanism}'.`);
19918
+ if (this.username && this.mechanismProperties.ENVIRONMENT && this.mechanismProperties.ENVIRONMENT !== "azure") {
19919
+ throw new error_1.MongoInvalidArgumentError(`username and ENVIRONMENT '${this.mechanismProperties.ENVIRONMENT}' may not be used together for mechanism '${this.mechanism}'.`);
19857
19920
  }
19858
- if (this.mechanismProperties.PROVIDER_NAME === "azure" && !this.mechanismProperties.TOKEN_AUDIENCE) {
19859
- throw new error_1.MongoAzureError(TOKEN_AUDIENCE_MISSING_ERROR);
19921
+ if (this.username && this.password) {
19922
+ throw new error_1.MongoInvalidArgumentError(`No password is allowed in ENVIRONMENT '${this.mechanismProperties.ENVIRONMENT}' for '${this.mechanism}'.`);
19860
19923
  }
19861
- if (this.mechanismProperties.PROVIDER_NAME && !ALLOWED_PROVIDER_NAMES.includes(this.mechanismProperties.PROVIDER_NAME)) {
19862
- throw new error_1.MongoInvalidArgumentError(`Currently only a PROVIDER_NAME in ${ALLOWED_PROVIDER_NAMES.join(",")} is supported for mechanism '${this.mechanism}'.`);
19924
+ if ((this.mechanismProperties.ENVIRONMENT === "azure" || this.mechanismProperties.ENVIRONMENT === "gcp") && !this.mechanismProperties.TOKEN_RESOURCE) {
19925
+ throw new error_1.MongoInvalidArgumentError(TOKEN_RESOURCE_MISSING_ERROR);
19863
19926
  }
19864
- if (this.mechanismProperties.REFRESH_TOKEN_CALLBACK && !this.mechanismProperties.REQUEST_TOKEN_CALLBACK) {
19865
- throw new error_1.MongoInvalidArgumentError(`A REQUEST_TOKEN_CALLBACK must be provided when using a REFRESH_TOKEN_CALLBACK for mechanism '${this.mechanism}'`);
19927
+ if (this.mechanismProperties.ENVIRONMENT && !ALLOWED_ENVIRONMENT_NAMES.includes(this.mechanismProperties.ENVIRONMENT)) {
19928
+ throw new error_1.MongoInvalidArgumentError(`Currently only a ENVIRONMENT in ${ALLOWED_ENVIRONMENT_NAMES.join(",")} is supported for mechanism '${this.mechanism}'.`);
19866
19929
  }
19867
- if (!this.mechanismProperties.PROVIDER_NAME && !this.mechanismProperties.REQUEST_TOKEN_CALLBACK) {
19868
- throw new error_1.MongoInvalidArgumentError(`Either a PROVIDER_NAME or a REQUEST_TOKEN_CALLBACK must be specified for mechanism '${this.mechanism}'.`);
19930
+ if (!this.mechanismProperties.ENVIRONMENT && !this.mechanismProperties.OIDC_CALLBACK && !this.mechanismProperties.OIDC_HUMAN_CALLBACK) {
19931
+ throw new error_1.MongoInvalidArgumentError(`Either a ENVIRONMENT, OIDC_CALLBACK, or OIDC_HUMAN_CALLBACK must be specified for mechanism '${this.mechanism}'.`);
19869
19932
  }
19870
19933
  if (this.mechanismProperties.ALLOWED_HOSTS) {
19871
19934
  const hosts = this.mechanismProperties.ALLOWED_HOSTS;
@@ -23660,7 +23723,7 @@ var require_lib3 = __commonJS((exports) => {
23660
23723
  var require_package = __commonJS((exports, module) => {
23661
23724
  module.exports = {
23662
23725
  name: "mongodb",
23663
- version: "6.6.1",
23726
+ version: "6.8.0",
23664
23727
  description: "The official MongoDB driver for Node.js",
23665
23728
  main: "lib/index.js",
23666
23729
  files: [
@@ -23728,7 +23791,6 @@ var require_package = __commonJS((exports, module) => {
23728
23791
  "@microsoft/api-extractor": "^7.43.1",
23729
23792
  "@microsoft/tsdoc-config": "^0.16.2",
23730
23793
  "@mongodb-js/zstd": "^1.2.0",
23731
- "@octokit/core": "^6.1.2",
23732
23794
  "@types/chai": "^4.3.14",
23733
23795
  "@types/chai-subset": "^1.3.5",
23734
23796
  "@types/express": "^4.17.21",
@@ -23759,7 +23821,7 @@ var require_package = __commonJS((exports, module) => {
23759
23821
  "js-yaml": "^4.1.0",
23760
23822
  mocha: "^10.4.0",
23761
23823
  "mocha-sinon": "^2.1.2",
23762
- "mongodb-client-encryption": "^6.0.0",
23824
+ "mongodb-client-encryption": "^6.0.1",
23763
23825
  "mongodb-legacy": "^6.0.1",
23764
23826
  nyc: "^15.1.0",
23765
23827
  prettier: "^2.8.8",
@@ -23809,8 +23871,10 @@ var require_package = __commonJS((exports, module) => {
23809
23871
  "check:drivers-atlas-testing": "mocha --config test/mocha_mongodb.json test/atlas/drivers_atlas_testing.test.ts",
23810
23872
  "check:adl": "mocha --config test/mocha_mongodb.json test/manual/atlas-data-lake-testing",
23811
23873
  "check:aws": "nyc mocha --config test/mocha_mongodb.json test/integration/auth/mongodb_aws.test.ts",
23812
- "check:oidc": "mocha --config test/mocha_mongodb.json test/manual/mongodb_oidc.prose.test.ts",
23813
- "check:oidc-azure": "mocha --config test/mocha_mongodb.json test/integration/auth/mongodb_oidc_azure.prose.test.ts",
23874
+ "check:oidc-auth": "mocha --config test/mocha_mongodb.json test/integration/auth/auth.spec.test.ts",
23875
+ "check:oidc-test": "mocha --config test/mocha_mongodb.json test/integration/auth/mongodb_oidc.prose.test.ts",
23876
+ "check:oidc-azure": "mocha --config test/mocha_mongodb.json test/integration/auth/mongodb_oidc_azure.prose.05.test.ts",
23877
+ "check:oidc-gcp": "mocha --config test/mocha_mongodb.json test/integration/auth/mongodb_oidc_gcp.prose.06.test.ts",
23814
23878
  "check:ocsp": "mocha --config test/manual/mocharc.json test/manual/ocsp_support.test.js",
23815
23879
  "check:kerberos": "nyc mocha --config test/manual/mocharc.json test/manual/kerberos.test.ts",
23816
23880
  "check:tls": "mocha --config test/manual/mocharc.json test/manual/tls_support.test.ts",
@@ -24817,36 +24881,6 @@ var require_aws = __commonJS((exports) => {
24817
24881
  exports.loadAWSCredentials = loadAWSCredentials;
24818
24882
  });
24819
24883
 
24820
- // node_modules/mongodb/lib/client-side-encryption/providers/utils.js
24821
- var require_utils4 = __commonJS((exports) => {
24822
- var get = function(url, options = {}) {
24823
- return new Promise((resolve, reject) => {
24824
- let timeoutId;
24825
- const request = http.get(url, options, (response) => {
24826
- response.setEncoding("utf8");
24827
- let body = "";
24828
- response.on("data", (chunk) => body += chunk);
24829
- response.on("end", () => {
24830
- (0, timers_1.clearTimeout)(timeoutId);
24831
- resolve({ status: response.statusCode, body });
24832
- });
24833
- }).on("error", (error) => {
24834
- (0, timers_1.clearTimeout)(timeoutId);
24835
- reject(error);
24836
- }).end();
24837
- timeoutId = (0, timers_1.setTimeout)(() => {
24838
- request.destroy(new errors_1.MongoCryptKMSRequestNetworkTimeoutError(`request timed out after 10 seconds`));
24839
- }, 1e4);
24840
- });
24841
- };
24842
- Object.defineProperty(exports, "__esModule", { value: true });
24843
- exports.get = undefined;
24844
- var http = import.meta.require("http");
24845
- var timers_1 = import.meta.require("timers");
24846
- var errors_1 = require_errors();
24847
- exports.get = get;
24848
- });
24849
-
24850
24884
  // node_modules/mongodb/lib/client-side-encryption/providers/azure.js
24851
24885
  var require_azure = __commonJS((exports) => {
24852
24886
  async function parseResponse(response) {
@@ -24876,10 +24910,17 @@ var require_azure = __commonJS((exports) => {
24876
24910
  expiresOnTimestamp: Date.now() + expiresInMS
24877
24911
  };
24878
24912
  }
24879
- var prepareRequest = function(options) {
24880
- const url = new URL(options.url?.toString() ?? "http://169.254.169.254/metadata/identity/oauth2/token");
24913
+ var addAzureParams = function(url, resource, username) {
24881
24914
  url.searchParams.append("api-version", "2018-02-01");
24882
- url.searchParams.append("resource", "https://vault.azure.net");
24915
+ url.searchParams.append("resource", resource);
24916
+ if (username) {
24917
+ url.searchParams.append("client_id", username);
24918
+ }
24919
+ return url;
24920
+ };
24921
+ var prepareRequest = function(options) {
24922
+ const url = new URL(options.url?.toString() ?? exports.AZURE_BASE_URL);
24923
+ addAzureParams(url, "https://vault.azure.net");
24883
24924
  const headers = { ...options.headers, "Content-Type": "application/json", Metadata: true };
24884
24925
  return { headers, url };
24885
24926
  };
@@ -24889,7 +24930,7 @@ var require_azure = __commonJS((exports) => {
24889
24930
  const response = await (0, utils_1.get)(url, { headers });
24890
24931
  return await parseResponse(response);
24891
24932
  } catch (error) {
24892
- if (error instanceof errors_1.MongoCryptKMSRequestNetworkTimeoutError) {
24933
+ if (error instanceof error_1.MongoNetworkTimeoutError) {
24893
24934
  throw new errors_1.MongoCryptAzureKMSRequestError(`[Azure KMS] ${error.message}`);
24894
24935
  }
24895
24936
  throw error;
@@ -24900,10 +24941,12 @@ var require_azure = __commonJS((exports) => {
24900
24941
  return { ...kmsProviders, azure };
24901
24942
  }
24902
24943
  Object.defineProperty(exports, "__esModule", { value: true });
24903
- exports.loadAzureCredentials = exports.fetchAzureKMSToken = exports.prepareRequest = exports.tokenCache = exports.AzureCredentialCache = undefined;
24944
+ exports.loadAzureCredentials = exports.fetchAzureKMSToken = exports.prepareRequest = exports.addAzureParams = exports.tokenCache = exports.AzureCredentialCache = exports.AZURE_BASE_URL = undefined;
24945
+ var error_1 = require_error();
24946
+ var utils_1 = require_utils2();
24904
24947
  var errors_1 = require_errors();
24905
- var utils_1 = require_utils4();
24906
24948
  var MINIMUM_TOKEN_REFRESH_IN_MILLISECONDS = 6000;
24949
+ exports.AZURE_BASE_URL = "http://169.254.169.254/metadata/identity/oauth2/token?";
24907
24950
 
24908
24951
  class AzureCredentialCache {
24909
24952
  constructor() {
@@ -24928,6 +24971,7 @@ var require_azure = __commonJS((exports) => {
24928
24971
  }
24929
24972
  exports.AzureCredentialCache = AzureCredentialCache;
24930
24973
  exports.tokenCache = new AzureCredentialCache;
24974
+ exports.addAzureParams = addAzureParams;
24931
24975
  exports.prepareRequest = prepareRequest;
24932
24976
  exports.fetchAzureKMSToken = fetchAzureKMSToken;
24933
24977
  exports.loadAzureCredentials = loadAzureCredentials;
@@ -25035,6 +25079,7 @@ var require_state_machine = __commonJS((exports) => {
25035
25079
  "tlsDisableOCSPEndpointCheck",
25036
25080
  "tlsDisableCertificateRevocationCheck"
25037
25081
  ];
25082
+ var EMPTY_V;
25038
25083
 
25039
25084
  class StateMachine {
25040
25085
  constructor(options, bsonOptions = (0, bson_1.pluckBSONSerializeOptions)(options)) {
@@ -25077,7 +25122,7 @@ var require_state_machine = __commonJS((exports) => {
25077
25122
  const filter = context.nextMongoOperation();
25078
25123
  const keys = await this.fetchKeys(keyVaultClient, keyVaultNamespace, filter);
25079
25124
  if (keys.length === 0) {
25080
- result = { v: [] };
25125
+ result = EMPTY_V ??= (0, bson_1.serialize)({ v: [] });
25081
25126
  }
25082
25127
  for await (const key of keys) {
25083
25128
  context.addMongoOperationResponse((0, bson_1.serialize)(key));
@@ -25102,7 +25147,7 @@ var require_state_machine = __commonJS((exports) => {
25102
25147
  const message = context.status.message || "Finalization error";
25103
25148
  throw new errors_1.MongoCryptError(message);
25104
25149
  }
25105
- result = (0, bson_1.deserialize)(finalizedContext, this.options);
25150
+ result = finalizedContext;
25106
25151
  break;
25107
25152
  }
25108
25153
  default:
@@ -25260,38 +25305,11 @@ var require_state_machine = __commonJS((exports) => {
25260
25305
 
25261
25306
  // node_modules/mongodb/lib/client-side-encryption/auto_encrypter.js
25262
25307
  var require_auto_encrypter = __commonJS((exports) => {
25263
- var decorateDecryptionResult = function(decrypted, original, isTopLevelDecorateCall = true) {
25264
- if (isTopLevelDecorateCall) {
25265
- if (Buffer.isBuffer(original)) {
25266
- original = (0, bson_1.deserialize)(original);
25267
- }
25268
- if (Buffer.isBuffer(decrypted)) {
25269
- throw new error_1.MongoRuntimeError("Expected result of decryption to be deserialized BSON object");
25270
- }
25271
- }
25272
- if (!decrypted || typeof decrypted !== "object")
25273
- return;
25274
- for (const k of Object.keys(decrypted)) {
25275
- const originalValue = original[k];
25276
- if (originalValue && originalValue._bsontype === "Binary" && originalValue.sub_type === 6) {
25277
- if (!decrypted[kDecoratedKeys]) {
25278
- Object.defineProperty(decrypted, kDecoratedKeys, {
25279
- value: [],
25280
- configurable: true,
25281
- enumerable: false,
25282
- writable: false
25283
- });
25284
- }
25285
- decrypted[kDecoratedKeys].push(k);
25286
- continue;
25287
- }
25288
- decorateDecryptionResult(decrypted[k], originalValue, false);
25289
- }
25290
- };
25291
25308
  var _a;
25292
25309
  Object.defineProperty(exports, "__esModule", { value: true });
25293
25310
  exports.AutoEncrypter = exports.AutoEncryptionLoggerLevel = undefined;
25294
25311
  var bson_1 = require_bson2();
25312
+ var constants_1 = require_constants2();
25295
25313
  var deps_1 = require_deps();
25296
25314
  var error_1 = require_error();
25297
25315
  var mongo_client_1 = require_mongo_client();
@@ -25308,8 +25326,6 @@ var require_auto_encrypter = __commonJS((exports) => {
25308
25326
  Info: 3,
25309
25327
  Trace: 4
25310
25328
  });
25311
- var kDecorateResult = Symbol.for("@@mdb.decorateDecryptionResult");
25312
- var kDecoratedKeys = Symbol.for("@@mdb.decryptedKeys");
25313
25329
 
25314
25330
  class AutoEncrypter {
25315
25331
  static getMongoCrypt() {
@@ -25413,23 +25429,20 @@ var require_auto_encrypter = __commonJS((exports) => {
25413
25429
  proxyOptions: this._proxyOptions,
25414
25430
  tlsOptions: this._tlsOptions
25415
25431
  });
25416
- return await stateMachine.execute(this, context);
25432
+ return (0, bson_1.deserialize)(await stateMachine.execute(this, context), {
25433
+ promoteValues: false,
25434
+ promoteLongs: false
25435
+ });
25417
25436
  }
25418
25437
  async decrypt(response, options = {}) {
25419
- const buffer = Buffer.isBuffer(response) ? response : (0, bson_1.serialize)(response, options);
25420
- const context = this._mongocrypt.makeDecryptionContext(buffer);
25438
+ const context = this._mongocrypt.makeDecryptionContext(response);
25421
25439
  context.id = this._contextCounter++;
25422
25440
  const stateMachine = new state_machine_1.StateMachine({
25423
25441
  ...options,
25424
25442
  proxyOptions: this._proxyOptions,
25425
25443
  tlsOptions: this._tlsOptions
25426
25444
  });
25427
- const decorateResult = this[kDecorateResult];
25428
- const result = await stateMachine.execute(this, context);
25429
- if (decorateResult) {
25430
- decorateDecryptionResult(result, response);
25431
- }
25432
- return result;
25445
+ return await stateMachine.execute(this, context);
25433
25446
  }
25434
25447
  async askForKMSCredentials() {
25435
25448
  return await (0, providers_1.refreshKMSCredentials)(this._kmsProviders);
@@ -25442,7 +25455,7 @@ var require_auto_encrypter = __commonJS((exports) => {
25442
25455
  }
25443
25456
  }
25444
25457
  exports.AutoEncrypter = AutoEncrypter;
25445
- _a = kDecorateResult;
25458
+ _a = constants_1.kDecorateResult;
25446
25459
  });
25447
25460
 
25448
25461
  // node_modules/mongodb/lib/encrypter.js
@@ -25901,6 +25914,7 @@ var require_connection = __commonJS((exports) => {
25901
25914
  exports.CryptoConnection = exports.SizedMessageTransform = exports.Connection = exports.hasSessionSupport = undefined;
25902
25915
  var stream_1 = import.meta.require("stream");
25903
25916
  var timers_1 = import.meta.require("timers");
25917
+ var bson_1 = require_bson2();
25904
25918
  var constants_1 = require_constants2();
25905
25919
  var error_1 = require_error();
25906
25920
  var mongo_logger_1 = require_mongo_logger();
@@ -26072,7 +26086,7 @@ var require_connection = __commonJS((exports) => {
26072
26086
  for await (const response of this.readMany()) {
26073
26087
  this.socket.setTimeout(0);
26074
26088
  const bson = response.parse();
26075
- const document = responseType == null ? new responses_1.MongoDBResponse(bson) : (0, responses_1.isErrorResponse)(bson) ? new responses_1.MongoDBResponse(bson) : new responseType(bson);
26089
+ const document = (responseType ?? responses_1.MongoDBResponse).make(bson);
26076
26090
  yield document;
26077
26091
  this.throwIfAborted();
26078
26092
  if (typeof options.socketTimeoutMS === "number") {
@@ -26110,11 +26124,7 @@ var require_connection = __commonJS((exports) => {
26110
26124
  this.clusterTime = document.$clusterTime;
26111
26125
  this.emit(Connection.CLUSTER_TIME_RECEIVED, document.$clusterTime);
26112
26126
  }
26113
- if (document.has("writeConcernError")) {
26114
- object ??= document.toObject(bsonOptions);
26115
- throw new error_1.MongoWriteConcernError(object.writeConcernError, object);
26116
- }
26117
- if (document.isError) {
26127
+ if (document.ok === 0) {
26118
26128
  throw new error_1.MongoServerError(object ??= document.toObject(bsonOptions));
26119
26129
  }
26120
26130
  if (this.shouldEmitAndLogCommand) {
@@ -26129,11 +26139,7 @@ var require_connection = __commonJS((exports) => {
26129
26139
  }
26130
26140
  } catch (error) {
26131
26141
  if (this.shouldEmitAndLogCommand) {
26132
- if (error.name === "MongoWriteConcernError") {
26133
- this.emitAndLogCommand(this.monitorCommands, Connection.COMMAND_SUCCEEDED, message.databaseName, this.established, new command_monitoring_events_1.CommandSucceededEvent(this, message, options.noResponse ? undefined : object ??= document?.toObject(bsonOptions), started, this.description.serverConnectionId));
26134
- } else {
26135
- this.emitAndLogCommand(this.monitorCommands, Connection.COMMAND_FAILED, message.databaseName, this.established, new command_monitoring_events_1.CommandFailedEvent(this, message, error, started, this.description.serverConnectionId));
26136
- }
26142
+ this.emitAndLogCommand(this.monitorCommands, Connection.COMMAND_FAILED, message.databaseName, this.established, new command_monitoring_events_1.CommandFailedEvent(this, message, error, started, this.description.serverConnectionId));
26137
26143
  }
26138
26144
  throw error;
26139
26145
  }
@@ -26228,7 +26234,7 @@ var require_connection = __commonJS((exports) => {
26228
26234
  super(stream, options);
26229
26235
  this.autoEncrypter = options.autoEncrypter;
26230
26236
  }
26231
- async command(ns, cmd, options, _responseType) {
26237
+ async command(ns, cmd, options, responseType) {
26232
26238
  const { autoEncrypter } = this;
26233
26239
  if (!autoEncrypter) {
26234
26240
  throw new error_1.MongoMissingDependencyError("No AutoEncrypter available for encryption", {
@@ -26237,7 +26243,7 @@ var require_connection = __commonJS((exports) => {
26237
26243
  }
26238
26244
  const serverWireVersion = (0, utils_1.maxWireVersion)(this);
26239
26245
  if (serverWireVersion === 0) {
26240
- return await super.command(ns, cmd, options, undefined);
26246
+ return await super.command(ns, cmd, options, responseType);
26241
26247
  }
26242
26248
  if (serverWireVersion < 8) {
26243
26249
  throw new error_1.MongoCompatibilityError("Auto-encryption requires a minimum MongoDB version of 4.2");
@@ -26253,8 +26259,17 @@ var require_connection = __commonJS((exports) => {
26253
26259
  encrypted.indexes[offset].key = index;
26254
26260
  }
26255
26261
  }
26256
- const response = await super.command(ns, encrypted, options, undefined);
26257
- return await autoEncrypter.decrypt(response, options);
26262
+ const encryptedResponse = await super.command(ns, encrypted, options, responseType ?? responses_1.MongoDBResponse);
26263
+ const result = await autoEncrypter.decrypt(encryptedResponse.toBytes(), options);
26264
+ const decryptedResponse = responseType?.make(result) ?? (0, bson_1.deserialize)(result, options);
26265
+ if (autoEncrypter[constants_1.kDecorateResult]) {
26266
+ if (responseType == null) {
26267
+ (0, utils_1.decorateDecryptionResult)(decryptedResponse, encryptedResponse.toObject(), true);
26268
+ } else if (decryptedResponse instanceof responses_1.CursorResponse) {
26269
+ decryptedResponse.encryptedResponse = encryptedResponse;
26270
+ }
26271
+ }
26272
+ return decryptedResponse;
26258
26273
  }
26259
26274
  }
26260
26275
  exports.CryptoConnection = CryptoConnection;
@@ -26299,7 +26314,7 @@ var require_connect = __commonJS((exports) => {
26299
26314
  async function performInitialHandshake(conn, options) {
26300
26315
  const credentials = options.credentials;
26301
26316
  if (credentials) {
26302
- if (!(credentials.mechanism === providers_1.AuthMechanism.MONGODB_DEFAULT) && !options.authProviders.getOrCreateProvider(credentials.mechanism)) {
26317
+ if (!(credentials.mechanism === providers_1.AuthMechanism.MONGODB_DEFAULT) && !options.authProviders.getOrCreateProvider(credentials.mechanism, credentials.mechanismProperties)) {
26303
26318
  throw new error_1.MongoInvalidArgumentError(`AuthMechanism '${credentials.mechanism}' not supported`);
26304
26319
  }
26305
26320
  }
@@ -26332,7 +26347,7 @@ var require_connect = __commonJS((exports) => {
26332
26347
  if (!response.arbiterOnly && credentials) {
26333
26348
  authContext.response = response;
26334
26349
  const resolvedCredentials = credentials.resolveAuthMechanism(response);
26335
- const provider = options.authProviders.getOrCreateProvider(resolvedCredentials.mechanism);
26350
+ const provider = options.authProviders.getOrCreateProvider(resolvedCredentials.mechanism, resolvedCredentials.mechanismProperties);
26336
26351
  if (!provider) {
26337
26352
  throw new error_1.MongoInvalidArgumentError(`No AuthProvider for ${resolvedCredentials.mechanism} defined.`);
26338
26353
  }
@@ -26368,13 +26383,13 @@ var require_connect = __commonJS((exports) => {
26368
26383
  if (credentials) {
26369
26384
  if (credentials.mechanism === providers_1.AuthMechanism.MONGODB_DEFAULT && credentials.username) {
26370
26385
  handshakeDoc.saslSupportedMechs = `${credentials.source}.${credentials.username}`;
26371
- const provider2 = authContext.options.authProviders.getOrCreateProvider(providers_1.AuthMechanism.MONGODB_SCRAM_SHA256);
26386
+ const provider2 = authContext.options.authProviders.getOrCreateProvider(providers_1.AuthMechanism.MONGODB_SCRAM_SHA256, credentials.mechanismProperties);
26372
26387
  if (!provider2) {
26373
26388
  throw new error_1.MongoInvalidArgumentError(`No AuthProvider for ${providers_1.AuthMechanism.MONGODB_SCRAM_SHA256} defined.`);
26374
26389
  }
26375
26390
  return await provider2.prepare(handshakeDoc, authContext);
26376
26391
  }
26377
- const provider = authContext.options.authProviders.getOrCreateProvider(credentials.mechanism);
26392
+ const provider = authContext.options.authProviders.getOrCreateProvider(credentials.mechanism, credentials.mechanismProperties);
26378
26393
  if (!provider) {
26379
26394
  throw new error_1.MongoInvalidArgumentError(`No AuthProvider for ${credentials.mechanism} defined.`);
26380
26395
  }
@@ -27138,7 +27153,7 @@ var require_connection_pool = __commonJS((exports) => {
27138
27153
  throw new error_1.MongoMissingCredentialsError("Connection is missing credentials when asked to reauthenticate");
27139
27154
  }
27140
27155
  const resolvedCredentials = credentials.resolveAuthMechanism(connection.hello);
27141
- const provider = this[kServer].topology.client.s.authProviders.getOrCreateProvider(resolvedCredentials.mechanism);
27156
+ const provider = this[kServer].topology.client.s.authProviders.getOrCreateProvider(resolvedCredentials.mechanism, resolvedCredentials.mechanismProperties);
27142
27157
  if (!provider) {
27143
27158
  throw new error_1.MongoMissingCredentialsError(`Reauthenticate failed due to no auth provider for ${credentials.mechanism}`);
27144
27159
  }
@@ -27376,6 +27391,7 @@ var require_server = __commonJS((exports) => {
27376
27391
  var mongo_types_1 = require_mongo_types();
27377
27392
  var transactions_1 = require_transactions();
27378
27393
  var utils_1 = require_utils2();
27394
+ var write_concern_1 = require_write_concern();
27379
27395
  var common_1 = require_common();
27380
27396
  var monitor_1 = require_monitor();
27381
27397
  var server_description_1 = require_server_description();
@@ -27507,7 +27523,9 @@ var require_server = __commonJS((exports) => {
27507
27523
  }
27508
27524
  try {
27509
27525
  try {
27510
- return await conn.command(ns, cmd, finalOptions, responseType);
27526
+ const res = await conn.command(ns, cmd, finalOptions, responseType);
27527
+ (0, write_concern_1.throwIfWriteConcernError)(res);
27528
+ return res;
27511
27529
  } catch (commandError) {
27512
27530
  throw this.decorateCommandError(conn, cmd, finalOptions, commandError);
27513
27531
  }
@@ -27515,7 +27533,9 @@ var require_server = __commonJS((exports) => {
27515
27533
  if (operationError instanceof error_1.MongoError && operationError.code === error_1.MONGODB_ERROR_CODES.Reauthenticate) {
27516
27534
  await this.pool.reauthenticate(conn);
27517
27535
  try {
27518
- return await conn.command(ns, cmd, finalOptions, responseType);
27536
+ const res = await conn.command(ns, cmd, finalOptions, responseType);
27537
+ (0, write_concern_1.throwIfWriteConcernError)(res);
27538
+ return res;
27519
27539
  } catch (commandError) {
27520
27540
  throw this.decorateCommandError(conn, cmd, finalOptions, commandError);
27521
27541
  }
@@ -27892,7 +27912,7 @@ var require_monitor = __commonJS((exports) => {
27892
27912
  return this.rttSampler.min();
27893
27913
  }
27894
27914
  get latestRtt() {
27895
- return this.rttSampler.last ?? 0;
27915
+ return this.rttSampler.last;
27896
27916
  }
27897
27917
  addRttSample(rtt) {
27898
27918
  this.rttSampler.addSample(rtt);
@@ -27909,7 +27929,7 @@ var require_monitor = __commonJS((exports) => {
27909
27929
  this[kCancellationToken] = monitor[kCancellationToken];
27910
27930
  this.closed = false;
27911
27931
  this.monitor = monitor;
27912
- this.latestRtt = monitor.latestRtt;
27932
+ this.latestRtt = monitor.latestRtt ?? undefined;
27913
27933
  const heartbeatFrequencyMS = monitor.options.heartbeatFrequencyMS;
27914
27934
  this[kMonitorId] = (0, timers_1.setTimeout)(() => this.measureRoundTripTime(), heartbeatFrequencyMS);
27915
27935
  }
@@ -27926,9 +27946,6 @@ var require_monitor = __commonJS((exports) => {
27926
27946
  this.connection = undefined;
27927
27947
  }
27928
27948
  measureAndReschedule(start, conn) {
27929
- if (start == null) {
27930
- start = (0, utils_1.now)();
27931
- }
27932
27949
  if (this.closed) {
27933
27950
  conn?.destroy();
27934
27951
  return;
@@ -27954,7 +27971,7 @@ var require_monitor = __commonJS((exports) => {
27954
27971
  return;
27955
27972
  }
27956
27973
  const commandName = connection.serverApi?.version || connection.helloOk ? "hello" : constants_1.LEGACY_HELLO_COMMAND;
27957
- connection.command((0, utils_1.ns)("admin.$cmd"), { [commandName]: 1 }, undefined).then(() => this.measureAndReschedule(), () => {
27974
+ connection.command((0, utils_1.ns)("admin.$cmd"), { [commandName]: 1 }, undefined).then(() => this.measureAndReschedule(start), () => {
27958
27975
  this.connection?.destroy();
27959
27976
  this.connection = undefined;
27960
27977
  return;
@@ -29259,307 +29276,336 @@ var require_mongodb_aws = __commonJS((exports) => {
29259
29276
  exports.MongoDBAWS = MongoDBAWS;
29260
29277
  });
29261
29278
 
29262
- // node_modules/mongodb/lib/cmap/auth/mongodb_oidc/service_workflow.js
29263
- var require_service_workflow = __commonJS((exports) => {
29264
- var commandDocument = function(token) {
29279
+ // node_modules/mongodb/lib/cmap/auth/mongodb_oidc/command_builders.js
29280
+ var require_command_builders = __commonJS((exports) => {
29281
+ var finishCommandDocument = function(token, conversationId) {
29282
+ if (conversationId != null) {
29283
+ return {
29284
+ saslContinue: 1,
29285
+ conversationId,
29286
+ payload: new bson_1.Binary(bson_1.BSON.serialize({ jwt: token }))
29287
+ };
29288
+ }
29289
+ return {
29290
+ saslStart: 1,
29291
+ mechanism: providers_1.AuthMechanism.MONGODB_OIDC,
29292
+ payload: new bson_1.Binary(bson_1.BSON.serialize({ jwt: token }))
29293
+ };
29294
+ };
29295
+ var startCommandDocument = function(credentials) {
29296
+ const payload = {};
29297
+ if (credentials.username) {
29298
+ payload.n = credentials.username;
29299
+ }
29265
29300
  return {
29266
29301
  saslStart: 1,
29302
+ autoAuthorize: 1,
29267
29303
  mechanism: providers_1.AuthMechanism.MONGODB_OIDC,
29268
- payload: bson_1.BSON.serialize({ jwt: token })
29304
+ payload: new bson_1.Binary(bson_1.BSON.serialize(payload))
29269
29305
  };
29270
29306
  };
29271
29307
  Object.defineProperty(exports, "__esModule", { value: true });
29272
- exports.commandDocument = exports.ServiceWorkflow = undefined;
29308
+ exports.startCommandDocument = exports.finishCommandDocument = undefined;
29273
29309
  var bson_1 = require_bson();
29274
- var utils_1 = require_utils2();
29275
29310
  var providers_1 = require_providers();
29276
-
29277
- class ServiceWorkflow {
29278
- async execute(connection, credentials) {
29279
- const token = await this.getToken(credentials);
29280
- const command2 = commandDocument(token);
29281
- return await connection.command((0, utils_1.ns)(credentials.source), command2, undefined);
29282
- }
29283
- async speculativeAuth(credentials) {
29284
- const token = await this.getToken(credentials);
29285
- const document = commandDocument(token);
29286
- document.db = credentials.source;
29287
- return { speculativeAuthenticate: document };
29288
- }
29289
- }
29290
- exports.ServiceWorkflow = ServiceWorkflow;
29291
- exports.commandDocument = commandDocument;
29311
+ exports.finishCommandDocument = finishCommandDocument;
29312
+ exports.startCommandDocument = startCommandDocument;
29292
29313
  });
29293
29314
 
29294
- // node_modules/mongodb/lib/cmap/auth/mongodb_oidc/aws_service_workflow.js
29295
- var require_aws_service_workflow = __commonJS((exports) => {
29315
+ // node_modules/mongodb/lib/cmap/auth/mongodb_oidc/machine_workflow.js
29316
+ var require_machine_workflow = __commonJS((exports) => {
29296
29317
  Object.defineProperty(exports, "__esModule", { value: true });
29297
- exports.AwsServiceWorkflow = undefined;
29298
- var fs = import.meta.require("fs");
29299
- var error_1 = require_error();
29300
- var service_workflow_1 = require_service_workflow();
29301
- var TOKEN_MISSING_ERROR = "AWS_WEB_IDENTITY_TOKEN_FILE must be set in the environment.";
29318
+ exports.MachineWorkflow = undefined;
29319
+ var promises_1 = import.meta.require("timers/promises");
29320
+ var utils_1 = require_utils2();
29321
+ var command_builders_1 = require_command_builders();
29322
+ var THROTTLE_MS = 100;
29302
29323
 
29303
- class AwsServiceWorkflow extends service_workflow_1.ServiceWorkflow {
29304
- constructor() {
29305
- super();
29324
+ class MachineWorkflow {
29325
+ constructor(cache) {
29326
+ this.cache = cache;
29327
+ this.callback = this.withLock(this.getToken.bind(this));
29328
+ this.lastExecutionTime = Date.now() - THROTTLE_MS;
29306
29329
  }
29307
- async getToken() {
29308
- const tokenFile = process.env.AWS_WEB_IDENTITY_TOKEN_FILE;
29309
- if (!tokenFile) {
29310
- throw new error_1.MongoAWSError(TOKEN_MISSING_ERROR);
29330
+ async execute(connection, credentials) {
29331
+ const token = await this.getTokenFromCacheOrEnv(connection, credentials);
29332
+ const command2 = (0, command_builders_1.finishCommandDocument)(token);
29333
+ await connection.command((0, utils_1.ns)(credentials.source), command2, undefined);
29334
+ }
29335
+ async reauthenticate(connection, credentials) {
29336
+ if (this.cache.hasAccessToken) {
29337
+ if (connection.accessToken === this.cache.getAccessToken()) {
29338
+ this.cache.removeAccessToken();
29339
+ delete connection.accessToken;
29340
+ } else {
29341
+ connection.accessToken = this.cache.getAccessToken();
29342
+ }
29311
29343
  }
29312
- return await fs.promises.readFile(tokenFile, "utf8");
29344
+ await this.execute(connection, credentials);
29313
29345
  }
29314
- }
29315
- exports.AwsServiceWorkflow = AwsServiceWorkflow;
29316
- });
29317
-
29318
- // node_modules/mongodb/lib/cmap/auth/mongodb_oidc/cache.js
29319
- var require_cache = __commonJS((exports) => {
29320
- Object.defineProperty(exports, "__esModule", { value: true });
29321
- exports.Cache = exports.ExpiringCacheEntry = undefined;
29322
- var EXPIRATION_BUFFER_MS = 300000;
29323
-
29324
- class ExpiringCacheEntry {
29325
- constructor(expiration) {
29326
- this.expiration = this.expirationTime(expiration);
29327
- }
29328
- isValid() {
29329
- return this.expiration - Date.now() > EXPIRATION_BUFFER_MS;
29330
- }
29331
- expirationTime(expiresInSeconds) {
29332
- return Date.now() + expiresInSeconds * 1000;
29333
- }
29334
- }
29335
- exports.ExpiringCacheEntry = ExpiringCacheEntry;
29336
-
29337
- class Cache {
29338
- constructor() {
29339
- this.entries = new Map;
29340
- }
29341
- clear() {
29342
- this.entries.clear();
29343
- }
29344
- hashedCacheKey(address, username, callbackHash) {
29345
- return JSON.stringify([address, username, callbackHash]);
29346
- }
29347
- }
29348
- exports.Cache = Cache;
29349
- });
29350
-
29351
- // node_modules/mongodb/lib/cmap/auth/mongodb_oidc/azure_token_cache.js
29352
- var require_azure_token_cache = __commonJS((exports) => {
29353
- Object.defineProperty(exports, "__esModule", { value: true });
29354
- exports.AzureTokenCache = exports.AzureTokenEntry = undefined;
29355
- var cache_1 = require_cache();
29356
-
29357
- class AzureTokenEntry extends cache_1.ExpiringCacheEntry {
29358
- constructor(token, expiration) {
29359
- super(expiration);
29360
- this.token = token;
29361
- }
29362
- }
29363
- exports.AzureTokenEntry = AzureTokenEntry;
29364
-
29365
- class AzureTokenCache extends cache_1.Cache {
29366
- addEntry(tokenAudience, token) {
29367
- const entry = new AzureTokenEntry(token.access_token, token.expires_in);
29368
- this.entries.set(tokenAudience, entry);
29369
- return entry;
29370
- }
29371
- cacheKey(tokenAudience) {
29372
- return tokenAudience;
29346
+ async speculativeAuth(connection, credentials) {
29347
+ if (!this.cache.hasAccessToken) {
29348
+ return {};
29349
+ }
29350
+ const token = await this.getTokenFromCacheOrEnv(connection, credentials);
29351
+ const document = (0, command_builders_1.finishCommandDocument)(token);
29352
+ document.db = credentials.source;
29353
+ return { speculativeAuthenticate: document };
29373
29354
  }
29374
- deleteEntry(tokenAudience) {
29375
- this.entries.delete(tokenAudience);
29355
+ async getTokenFromCacheOrEnv(connection, credentials) {
29356
+ if (this.cache.hasAccessToken) {
29357
+ return this.cache.getAccessToken();
29358
+ } else {
29359
+ const token = await this.callback(credentials);
29360
+ this.cache.put({ accessToken: token.access_token, expiresInSeconds: token.expires_in });
29361
+ connection.accessToken = token.access_token;
29362
+ return token.access_token;
29363
+ }
29376
29364
  }
29377
- getEntry(tokenAudience) {
29378
- return this.entries.get(tokenAudience);
29365
+ withLock(callback) {
29366
+ let lock = Promise.resolve();
29367
+ return async (credentials) => {
29368
+ await lock;
29369
+ lock = lock.catch(() => null).then(async () => {
29370
+ const difference = Date.now() - this.lastExecutionTime;
29371
+ if (difference <= THROTTLE_MS) {
29372
+ await (0, promises_1.setTimeout)(THROTTLE_MS - difference);
29373
+ }
29374
+ this.lastExecutionTime = Date.now();
29375
+ return await callback(credentials);
29376
+ });
29377
+ return await lock;
29378
+ };
29379
29379
  }
29380
29380
  }
29381
- exports.AzureTokenCache = AzureTokenCache;
29381
+ exports.MachineWorkflow = MachineWorkflow;
29382
29382
  });
29383
29383
 
29384
- // node_modules/mongodb/lib/cmap/auth/mongodb_oidc/azure_service_workflow.js
29385
- var require_azure_service_workflow = __commonJS((exports) => {
29386
- async function getAzureTokenData(tokenAudience) {
29387
- const url = `${AZURE_BASE_URL}&resource=${tokenAudience}`;
29388
- const data = await (0, utils_1.request)(url, {
29389
- json: true,
29384
+ // node_modules/mongodb/lib/cmap/auth/mongodb_oidc/azure_machine_workflow.js
29385
+ var require_azure_machine_workflow = __commonJS((exports) => {
29386
+ async function getAzureTokenData(tokenAudience, username) {
29387
+ const url = new URL(azure_1.AZURE_BASE_URL);
29388
+ (0, azure_1.addAzureParams)(url, tokenAudience, username);
29389
+ const response = await (0, utils_1.get)(url, {
29390
29390
  headers: AZURE_HEADERS
29391
29391
  });
29392
- return data;
29392
+ if (response.status !== 200) {
29393
+ throw new error_1.MongoAzureError(`Status code ${response.status} returned from the Azure endpoint. Response body: ${response.body}`);
29394
+ }
29395
+ const result = JSON.parse(response.body);
29396
+ return {
29397
+ access_token: result.access_token,
29398
+ expires_in: Number(result.expires_in)
29399
+ };
29393
29400
  }
29394
29401
  var isEndpointResultValid = function(token) {
29395
29402
  if (token == null || typeof token !== "object")
29396
29403
  return false;
29397
- return "access_token" in token && "expires_in" in token;
29404
+ return "access_token" in token && typeof token.access_token === "string" && "expires_in" in token && typeof token.expires_in === "number";
29398
29405
  };
29399
29406
  Object.defineProperty(exports, "__esModule", { value: true });
29400
- exports.AzureServiceWorkflow = undefined;
29407
+ exports.AzureMachineWorkflow = undefined;
29408
+ var azure_1 = require_azure();
29401
29409
  var error_1 = require_error();
29402
29410
  var utils_1 = require_utils2();
29403
- var azure_token_cache_1 = require_azure_token_cache();
29404
- var service_workflow_1 = require_service_workflow();
29405
- var AZURE_BASE_URL = "http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01";
29411
+ var machine_workflow_1 = require_machine_workflow();
29406
29412
  var AZURE_HEADERS = Object.freeze({ Metadata: "true", Accept: "application/json" });
29407
29413
  var ENDPOINT_RESULT_ERROR = "Azure endpoint did not return a value with only access_token and expires_in properties";
29408
- var TOKEN_AUDIENCE_MISSING_ERROR = "TOKEN_AUDIENCE must be set in the auth mechanism properties when PROVIDER_NAME is azure.";
29414
+ var TOKEN_RESOURCE_MISSING_ERROR = "TOKEN_RESOURCE must be set in the auth mechanism properties when ENVIRONMENT is azure.";
29409
29415
 
29410
- class AzureServiceWorkflow extends service_workflow_1.ServiceWorkflow {
29411
- constructor() {
29412
- super(...arguments);
29413
- this.cache = new azure_token_cache_1.AzureTokenCache;
29416
+ class AzureMachineWorkflow extends machine_workflow_1.MachineWorkflow {
29417
+ constructor(cache) {
29418
+ super(cache);
29414
29419
  }
29415
29420
  async getToken(credentials) {
29416
- const tokenAudience = credentials?.mechanismProperties.TOKEN_AUDIENCE;
29421
+ const tokenAudience = credentials?.mechanismProperties.TOKEN_RESOURCE;
29422
+ const username = credentials?.username;
29417
29423
  if (!tokenAudience) {
29418
- throw new error_1.MongoAzureError(TOKEN_AUDIENCE_MISSING_ERROR);
29424
+ throw new error_1.MongoAzureError(TOKEN_RESOURCE_MISSING_ERROR);
29419
29425
  }
29420
- let token;
29421
- const entry = this.cache.getEntry(tokenAudience);
29422
- if (entry?.isValid()) {
29423
- token = entry.token;
29424
- } else {
29425
- this.cache.deleteEntry(tokenAudience);
29426
- const response = await getAzureTokenData(tokenAudience);
29427
- if (!isEndpointResultValid(response)) {
29428
- throw new error_1.MongoAzureError(ENDPOINT_RESULT_ERROR);
29429
- }
29430
- this.cache.addEntry(tokenAudience, response);
29431
- token = response.access_token;
29426
+ const response = await getAzureTokenData(tokenAudience, username);
29427
+ if (!isEndpointResultValid(response)) {
29428
+ throw new error_1.MongoAzureError(ENDPOINT_RESULT_ERROR);
29432
29429
  }
29433
- return token;
29430
+ return response;
29434
29431
  }
29435
29432
  }
29436
- exports.AzureServiceWorkflow = AzureServiceWorkflow;
29433
+ exports.AzureMachineWorkflow = AzureMachineWorkflow;
29437
29434
  });
29438
29435
 
29439
- // node_modules/mongodb/lib/cmap/auth/mongodb_oidc/callback_lock_cache.js
29440
- var require_callback_lock_cache = __commonJS((exports) => {
29441
- var withLock = function(callback) {
29442
- let lock = Promise.resolve();
29443
- return async (info, context) => {
29444
- await lock;
29445
- lock = lock.then(() => callback(info, context));
29446
- return await lock;
29447
- };
29448
- };
29449
- var hashFunctions = function(requestFn, refreshFn) {
29450
- let requestHash = FN_HASHES.get(requestFn);
29451
- let refreshHash = FN_HASHES.get(refreshFn ?? NO_FUNCTION);
29452
- if (requestHash == null) {
29453
- FN_HASH_COUNTER++;
29454
- requestHash = FN_HASH_COUNTER;
29455
- FN_HASHES.set(requestFn, FN_HASH_COUNTER);
29436
+ // node_modules/mongodb/lib/cmap/auth/mongodb_oidc/gcp_machine_workflow.js
29437
+ var require_gcp_machine_workflow = __commonJS((exports) => {
29438
+ async function getGcpTokenData(tokenAudience) {
29439
+ const url = new URL(GCP_BASE_URL);
29440
+ url.searchParams.append("audience", tokenAudience);
29441
+ const response = await (0, utils_1.get)(url, {
29442
+ headers: GCP_HEADERS
29443
+ });
29444
+ if (response.status !== 200) {
29445
+ throw new error_1.MongoGCPError(`Status code ${response.status} returned from the GCP endpoint. Response body: ${response.body}`);
29446
+ }
29447
+ return { access_token: response.body };
29448
+ }
29449
+ Object.defineProperty(exports, "__esModule", { value: true });
29450
+ exports.GCPMachineWorkflow = undefined;
29451
+ var error_1 = require_error();
29452
+ var utils_1 = require_utils2();
29453
+ var machine_workflow_1 = require_machine_workflow();
29454
+ var GCP_BASE_URL = "http://metadata/computeMetadata/v1/instance/service-accounts/default/identity";
29455
+ var GCP_HEADERS = Object.freeze({ "Metadata-Flavor": "Google" });
29456
+ var TOKEN_RESOURCE_MISSING_ERROR = "TOKEN_RESOURCE must be set in the auth mechanism properties when ENVIRONMENT is gcp.";
29457
+
29458
+ class GCPMachineWorkflow extends machine_workflow_1.MachineWorkflow {
29459
+ constructor(cache) {
29460
+ super(cache);
29456
29461
  }
29457
- if (refreshHash == null && refreshFn) {
29458
- FN_HASH_COUNTER++;
29459
- refreshHash = FN_HASH_COUNTER;
29460
- FN_HASHES.set(refreshFn, FN_HASH_COUNTER);
29462
+ async getToken(credentials) {
29463
+ const tokenAudience = credentials?.mechanismProperties.TOKEN_RESOURCE;
29464
+ if (!tokenAudience) {
29465
+ throw new error_1.MongoGCPError(TOKEN_RESOURCE_MISSING_ERROR);
29466
+ }
29467
+ return await getGcpTokenData(tokenAudience);
29461
29468
  }
29462
- return `${requestHash}-${refreshHash}`;
29463
- };
29469
+ }
29470
+ exports.GCPMachineWorkflow = GCPMachineWorkflow;
29471
+ });
29472
+
29473
+ // node_modules/mongodb/lib/cmap/auth/mongodb_oidc/token_cache.js
29474
+ var require_token_cache = __commonJS((exports) => {
29464
29475
  Object.defineProperty(exports, "__esModule", { value: true });
29465
- exports.CallbackLockCache = undefined;
29476
+ exports.TokenCache = undefined;
29466
29477
  var error_1 = require_error();
29467
- var cache_1 = require_cache();
29468
- var REQUEST_CALLBACK_REQUIRED_ERROR = "Auth mechanism property REQUEST_TOKEN_CALLBACK is required.";
29469
- var FN_HASH_COUNTER = 0;
29470
- var NO_FUNCTION = async () => ({ accessToken: "test" });
29471
- var FN_HASHES = new WeakMap;
29472
- FN_HASHES.set(NO_FUNCTION, FN_HASH_COUNTER);
29473
-
29474
- class CallbackLockCache extends cache_1.Cache {
29475
- getEntry(connection, credentials) {
29476
- const requestCallback = credentials.mechanismProperties.REQUEST_TOKEN_CALLBACK;
29477
- const refreshCallback = credentials.mechanismProperties.REFRESH_TOKEN_CALLBACK;
29478
- if (!requestCallback) {
29479
- throw new error_1.MongoInvalidArgumentError(REQUEST_CALLBACK_REQUIRED_ERROR);
29480
- }
29481
- const callbackHash = hashFunctions(requestCallback, refreshCallback);
29482
- const key = this.cacheKey(connection.address, credentials.username, callbackHash);
29483
- const entry = this.entries.get(key);
29484
- if (entry) {
29485
- return entry;
29478
+
29479
+ class MongoOIDCError extends error_1.MongoDriverError {
29480
+ }
29481
+
29482
+ class TokenCache {
29483
+ get hasAccessToken() {
29484
+ return !!this.accessToken;
29485
+ }
29486
+ get hasRefreshToken() {
29487
+ return !!this.refreshToken;
29488
+ }
29489
+ get hasIdpInfo() {
29490
+ return !!this.idpInfo;
29491
+ }
29492
+ getAccessToken() {
29493
+ if (!this.accessToken) {
29494
+ throw new MongoOIDCError("Attempted to get an access token when none exists.");
29486
29495
  }
29487
- return this.addEntry(key, callbackHash, requestCallback, refreshCallback);
29496
+ return this.accessToken;
29488
29497
  }
29489
- addEntry(key, callbackHash, requestCallback, refreshCallback) {
29490
- const entry = {
29491
- requestCallback: withLock(requestCallback),
29492
- refreshCallback: refreshCallback ? withLock(refreshCallback) : undefined,
29493
- callbackHash
29494
- };
29495
- this.entries.set(key, entry);
29496
- return entry;
29498
+ getRefreshToken() {
29499
+ if (!this.refreshToken) {
29500
+ throw new MongoOIDCError("Attempted to get a refresh token when none exists.");
29501
+ }
29502
+ return this.refreshToken;
29497
29503
  }
29498
- cacheKey(address, username, callbackHash) {
29499
- return this.hashedCacheKey(address, username, callbackHash);
29504
+ getIdpInfo() {
29505
+ if (!this.idpInfo) {
29506
+ throw new MongoOIDCError("Attempted to get IDP information when none exists.");
29507
+ }
29508
+ return this.idpInfo;
29509
+ }
29510
+ put(response, idpInfo) {
29511
+ this.accessToken = response.accessToken;
29512
+ this.refreshToken = response.refreshToken;
29513
+ this.expiresInSeconds = response.expiresInSeconds;
29514
+ if (idpInfo) {
29515
+ this.idpInfo = idpInfo;
29516
+ }
29517
+ }
29518
+ removeAccessToken() {
29519
+ this.accessToken = undefined;
29520
+ }
29521
+ removeRefreshToken() {
29522
+ this.refreshToken = undefined;
29500
29523
  }
29501
29524
  }
29502
- exports.CallbackLockCache = CallbackLockCache;
29525
+ exports.TokenCache = TokenCache;
29503
29526
  });
29504
29527
 
29505
- // node_modules/mongodb/lib/cmap/auth/mongodb_oidc/token_entry_cache.js
29506
- var require_token_entry_cache = __commonJS((exports) => {
29528
+ // node_modules/mongodb/lib/cmap/auth/mongodb_oidc/token_machine_workflow.js
29529
+ var require_token_machine_workflow = __commonJS((exports) => {
29507
29530
  Object.defineProperty(exports, "__esModule", { value: true });
29508
- exports.TokenEntryCache = exports.TokenEntry = undefined;
29509
- var cache_1 = require_cache();
29510
- var DEFAULT_EXPIRATION_SECS = 0;
29531
+ exports.TokenMachineWorkflow = undefined;
29532
+ var fs = import.meta.require("fs");
29533
+ var error_1 = require_error();
29534
+ var machine_workflow_1 = require_machine_workflow();
29535
+ var TOKEN_MISSING_ERROR = "OIDC_TOKEN_FILE must be set in the environment.";
29511
29536
 
29512
- class TokenEntry extends cache_1.ExpiringCacheEntry {
29513
- constructor(tokenResult, serverInfo, expiration) {
29514
- super(expiration);
29515
- this.tokenResult = tokenResult;
29516
- this.serverInfo = serverInfo;
29537
+ class TokenMachineWorkflow extends machine_workflow_1.MachineWorkflow {
29538
+ constructor(cache) {
29539
+ super(cache);
29540
+ }
29541
+ async getToken() {
29542
+ const tokenFile = process.env.OIDC_TOKEN_FILE;
29543
+ if (!tokenFile) {
29544
+ throw new error_1.MongoAWSError(TOKEN_MISSING_ERROR);
29545
+ }
29546
+ const token = await fs.promises.readFile(tokenFile, "utf8");
29547
+ return { access_token: token };
29517
29548
  }
29518
29549
  }
29519
- exports.TokenEntry = TokenEntry;
29550
+ exports.TokenMachineWorkflow = TokenMachineWorkflow;
29551
+ });
29520
29552
 
29521
- class TokenEntryCache extends cache_1.Cache {
29522
- addEntry(address, username, callbackHash, tokenResult, serverInfo) {
29523
- const entry = new TokenEntry(tokenResult, serverInfo, tokenResult.expiresInSeconds ?? DEFAULT_EXPIRATION_SECS);
29524
- this.entries.set(this.cacheKey(address, username, callbackHash), entry);
29525
- return entry;
29526
- }
29527
- deleteEntry(address, username, callbackHash) {
29528
- this.entries.delete(this.cacheKey(address, username, callbackHash));
29553
+ // node_modules/mongodb/lib/cmap/auth/mongodb_oidc.js
29554
+ var require_mongodb_oidc = __commonJS((exports) => {
29555
+ var getCredentials = function(authContext) {
29556
+ const { credentials } = authContext;
29557
+ if (!credentials) {
29558
+ throw new error_1.MongoMissingCredentialsError(MISSING_CREDENTIALS_ERROR);
29529
29559
  }
29530
- getEntry(address, username, callbackHash) {
29531
- return this.entries.get(this.cacheKey(address, username, callbackHash));
29560
+ return credentials;
29561
+ };
29562
+ Object.defineProperty(exports, "__esModule", { value: true });
29563
+ exports.MongoDBOIDC = exports.OIDC_WORKFLOWS = exports.OIDC_VERSION = undefined;
29564
+ var error_1 = require_error();
29565
+ var auth_provider_1 = require_auth_provider();
29566
+ var azure_machine_workflow_1 = require_azure_machine_workflow();
29567
+ var gcp_machine_workflow_1 = require_gcp_machine_workflow();
29568
+ var token_cache_1 = require_token_cache();
29569
+ var token_machine_workflow_1 = require_token_machine_workflow();
29570
+ var MISSING_CREDENTIALS_ERROR = "AuthContext must provide credentials.";
29571
+ exports.OIDC_VERSION = 1;
29572
+ exports.OIDC_WORKFLOWS = new Map;
29573
+ exports.OIDC_WORKFLOWS.set("test", () => new token_machine_workflow_1.TokenMachineWorkflow(new token_cache_1.TokenCache));
29574
+ exports.OIDC_WORKFLOWS.set("azure", () => new azure_machine_workflow_1.AzureMachineWorkflow(new token_cache_1.TokenCache));
29575
+ exports.OIDC_WORKFLOWS.set("gcp", () => new gcp_machine_workflow_1.GCPMachineWorkflow(new token_cache_1.TokenCache));
29576
+
29577
+ class MongoDBOIDC extends auth_provider_1.AuthProvider {
29578
+ constructor(workflow) {
29579
+ super();
29580
+ if (!workflow) {
29581
+ throw new error_1.MongoInvalidArgumentError("No workflow provided to the OIDC auth provider.");
29582
+ }
29583
+ this.workflow = workflow;
29532
29584
  }
29533
- deleteExpiredEntries() {
29534
- for (const [key, entry] of this.entries) {
29535
- if (!entry.isValid()) {
29536
- this.entries.delete(key);
29537
- }
29585
+ async auth(authContext) {
29586
+ const { connection, reauthenticating, response } = authContext;
29587
+ if (response?.speculativeAuthenticate?.done) {
29588
+ return;
29589
+ }
29590
+ const credentials = getCredentials(authContext);
29591
+ if (reauthenticating) {
29592
+ await this.workflow.reauthenticate(connection, credentials);
29593
+ } else {
29594
+ await this.workflow.execute(connection, credentials, response);
29538
29595
  }
29539
29596
  }
29540
- cacheKey(address, username, callbackHash) {
29541
- return this.hashedCacheKey(address, username, callbackHash);
29597
+ async prepare(handshakeDoc, authContext) {
29598
+ const { connection } = authContext;
29599
+ const credentials = getCredentials(authContext);
29600
+ const result = await this.workflow.speculativeAuth(connection, credentials);
29601
+ return { ...handshakeDoc, ...result };
29542
29602
  }
29543
29603
  }
29544
- exports.TokenEntryCache = TokenEntryCache;
29604
+ exports.MongoDBOIDC = MongoDBOIDC;
29545
29605
  });
29546
29606
 
29547
29607
  // node_modules/mongodb/lib/cmap/auth/mongodb_oidc/callback_workflow.js
29548
29608
  var require_callback_workflow = __commonJS((exports) => {
29549
- var finishCommandDocument = function(token, conversationId) {
29550
- if (conversationId != null && typeof conversationId === "number") {
29551
- return {
29552
- saslContinue: 1,
29553
- conversationId,
29554
- payload: new bson_1.Binary(bson_1.BSON.serialize({ jwt: token }))
29555
- };
29556
- }
29557
- return {
29558
- saslStart: 1,
29559
- mechanism: providers_1.AuthMechanism.MONGODB_OIDC,
29560
- payload: new bson_1.Binary(bson_1.BSON.serialize({ jwt: token }))
29561
- };
29562
- };
29563
29609
  var isCallbackResultInvalid = function(tokenResult) {
29564
29610
  if (tokenResult == null || typeof tokenResult !== "object")
29565
29611
  return true;
@@ -29567,160 +29613,224 @@ var require_callback_workflow = __commonJS((exports) => {
29567
29613
  return true;
29568
29614
  return !Object.getOwnPropertyNames(tokenResult).every((prop) => RESULT_PROPERTIES.includes(prop));
29569
29615
  };
29570
- var startCommandDocument = function(credentials) {
29571
- const payload = {};
29572
- if (credentials.username) {
29573
- payload.n = credentials.username;
29574
- }
29575
- return {
29576
- saslStart: 1,
29577
- autoAuthorize: 1,
29578
- mechanism: providers_1.AuthMechanism.MONGODB_OIDC,
29579
- payload: new bson_1.Binary(bson_1.BSON.serialize(payload))
29580
- };
29581
- };
29582
29616
  Object.defineProperty(exports, "__esModule", { value: true });
29583
- exports.CallbackWorkflow = undefined;
29584
- var bson_1 = require_bson();
29617
+ exports.CallbackWorkflow = exports.AUTOMATED_TIMEOUT_MS = exports.HUMAN_TIMEOUT_MS = undefined;
29618
+ var promises_1 = import.meta.require("timers/promises");
29585
29619
  var error_1 = require_error();
29586
29620
  var utils_1 = require_utils2();
29587
- var providers_1 = require_providers();
29588
- var callback_lock_cache_1 = require_callback_lock_cache();
29589
- var token_entry_cache_1 = require_token_entry_cache();
29590
- var OIDC_VERSION = 0;
29591
- var TIMEOUT_S = 300;
29621
+ var command_builders_1 = require_command_builders();
29622
+ exports.HUMAN_TIMEOUT_MS = 300000;
29623
+ exports.AUTOMATED_TIMEOUT_MS = 60000;
29592
29624
  var RESULT_PROPERTIES = ["accessToken", "expiresInSeconds", "refreshToken"];
29593
29625
  var CALLBACK_RESULT_ERROR = "User provided OIDC callbacks must return a valid object with an accessToken.";
29626
+ var THROTTLE_MS = 100;
29594
29627
 
29595
29628
  class CallbackWorkflow {
29596
- constructor() {
29597
- this.cache = new token_entry_cache_1.TokenEntryCache;
29598
- this.callbackCache = new callback_lock_cache_1.CallbackLockCache;
29599
- }
29600
- async speculativeAuth(credentials) {
29601
- const document = startCommandDocument(credentials);
29602
- document.db = credentials.source;
29603
- return { speculativeAuthenticate: document };
29629
+ constructor(cache, callback) {
29630
+ this.cache = cache;
29631
+ this.callback = this.withLock(callback);
29632
+ this.lastExecutionTime = Date.now() - THROTTLE_MS;
29633
+ }
29634
+ async speculativeAuth(connection, credentials) {
29635
+ if (this.cache.hasAccessToken) {
29636
+ const accessToken = this.cache.getAccessToken();
29637
+ connection.accessToken = accessToken;
29638
+ const document = (0, command_builders_1.finishCommandDocument)(accessToken);
29639
+ document.db = credentials.source;
29640
+ return { speculativeAuthenticate: document };
29641
+ }
29642
+ return {};
29604
29643
  }
29605
- async execute(connection, credentials, reauthenticating, response) {
29606
- const { requestCallback, refreshCallback, callbackHash } = this.callbackCache.getEntry(connection, credentials);
29607
- const entry = this.cache.getEntry(connection.address, credentials.username, callbackHash);
29608
- let result;
29609
- if (entry) {
29610
- if (entry.isValid() && !reauthenticating) {
29611
- result = await this.finishAuthentication(connection, credentials, entry.tokenResult, response?.speculativeAuthenticate?.conversationId);
29644
+ async reauthenticate(connection, credentials) {
29645
+ if (this.cache.hasAccessToken) {
29646
+ if (connection.accessToken === this.cache.getAccessToken()) {
29647
+ this.cache.removeAccessToken();
29648
+ delete connection.accessToken;
29612
29649
  } else {
29613
- const tokenResult = await this.fetchAccessToken(connection, credentials, entry.serverInfo, reauthenticating, callbackHash, requestCallback, refreshCallback);
29614
- try {
29615
- result = await this.finishAuthentication(connection, credentials, tokenResult, reauthenticating ? undefined : response?.speculativeAuthenticate?.conversationId);
29616
- } catch (error) {
29617
- if (reauthenticating && error instanceof error_1.MongoError && error.code === error_1.MONGODB_ERROR_CODES.Reauthenticate) {
29618
- this.cache.deleteEntry(connection.address, credentials.username, callbackHash);
29619
- result = await this.execute(connection, credentials, reauthenticating);
29620
- } else {
29621
- throw error;
29622
- }
29623
- }
29650
+ connection.accessToken = this.cache.getAccessToken();
29624
29651
  }
29625
- } else {
29626
- const startDocument = await this.startAuthentication(connection, credentials, reauthenticating, response);
29627
- const conversationId = startDocument.conversationId;
29628
- const serverResult = bson_1.BSON.deserialize(startDocument.payload.buffer);
29629
- const tokenResult = await this.fetchAccessToken(connection, credentials, serverResult, reauthenticating, callbackHash, requestCallback, refreshCallback);
29630
- result = await this.finishAuthentication(connection, credentials, tokenResult, conversationId);
29631
29652
  }
29632
- return result;
29653
+ await this.execute(connection, credentials);
29633
29654
  }
29634
- async startAuthentication(connection, credentials, reauthenticating, response) {
29655
+ async startAuthentication(connection, credentials, response) {
29635
29656
  let result;
29636
- if (!reauthenticating && response?.speculativeAuthenticate) {
29657
+ if (response?.speculativeAuthenticate) {
29637
29658
  result = response.speculativeAuthenticate;
29638
29659
  } else {
29639
- result = await connection.command((0, utils_1.ns)(credentials.source), startCommandDocument(credentials), undefined);
29660
+ result = await connection.command((0, utils_1.ns)(credentials.source), (0, command_builders_1.startCommandDocument)(credentials), undefined);
29640
29661
  }
29641
29662
  return result;
29642
29663
  }
29643
- async finishAuthentication(connection, credentials, tokenResult, conversationId) {
29644
- const result = await connection.command((0, utils_1.ns)(credentials.source), finishCommandDocument(tokenResult.accessToken, conversationId), undefined);
29645
- return result;
29664
+ async finishAuthentication(connection, credentials, token, conversationId) {
29665
+ await connection.command((0, utils_1.ns)(credentials.source), (0, command_builders_1.finishCommandDocument)(token, conversationId), undefined);
29646
29666
  }
29647
- async fetchAccessToken(connection, credentials, serverInfo, reauthenticating, callbackHash, requestCallback, refreshCallback) {
29648
- const entry = this.cache.getEntry(connection.address, credentials.username, callbackHash);
29649
- let result;
29650
- const context = { timeoutSeconds: TIMEOUT_S, version: OIDC_VERSION };
29651
- if (entry) {
29652
- if (entry.isValid() && !reauthenticating) {
29653
- return entry.tokenResult;
29654
- }
29655
- if (refreshCallback) {
29656
- context.refreshToken = entry.tokenResult.refreshToken;
29657
- result = await refreshCallback(serverInfo, context);
29658
- } else {
29659
- result = await requestCallback(serverInfo, context);
29660
- }
29661
- } else {
29662
- result = await requestCallback(serverInfo, context);
29663
- }
29667
+ async executeAndValidateCallback(params) {
29668
+ const result = await this.callback(params);
29664
29669
  if (isCallbackResultInvalid(result)) {
29665
- this.cache.deleteEntry(connection.address, credentials.username, callbackHash);
29666
29670
  throw new error_1.MongoMissingCredentialsError(CALLBACK_RESULT_ERROR);
29667
29671
  }
29668
- this.cache.deleteExpiredEntries();
29669
- this.cache.addEntry(connection.address, credentials.username || "", callbackHash, result, serverInfo);
29670
29672
  return result;
29671
29673
  }
29674
+ withLock(callback) {
29675
+ let lock = Promise.resolve();
29676
+ return async (params) => {
29677
+ await lock;
29678
+ lock = lock.catch(() => null).then(async () => {
29679
+ const difference = Date.now() - this.lastExecutionTime;
29680
+ if (difference <= THROTTLE_MS) {
29681
+ await (0, promises_1.setTimeout)(THROTTLE_MS - difference, { signal: params.timeoutContext });
29682
+ }
29683
+ this.lastExecutionTime = Date.now();
29684
+ return await callback(params);
29685
+ });
29686
+ return await lock;
29687
+ };
29688
+ }
29672
29689
  }
29673
29690
  exports.CallbackWorkflow = CallbackWorkflow;
29674
29691
  });
29675
29692
 
29676
- // node_modules/mongodb/lib/cmap/auth/mongodb_oidc.js
29677
- var require_mongodb_oidc = __commonJS((exports) => {
29678
- var getCredentials = function(authContext) {
29679
- const { credentials } = authContext;
29680
- if (!credentials) {
29681
- throw new error_1.MongoMissingCredentialsError(MISSING_CREDENTIALS_ERROR);
29693
+ // node_modules/mongodb/lib/cmap/auth/mongodb_oidc/automated_callback_workflow.js
29694
+ var require_automated_callback_workflow = __commonJS((exports) => {
29695
+ Object.defineProperty(exports, "__esModule", { value: true });
29696
+ exports.AutomatedCallbackWorkflow = undefined;
29697
+ var error_1 = require_error();
29698
+ var timeout_1 = require_timeout();
29699
+ var mongodb_oidc_1 = require_mongodb_oidc();
29700
+ var callback_workflow_1 = require_callback_workflow();
29701
+
29702
+ class AutomatedCallbackWorkflow extends callback_workflow_1.CallbackWorkflow {
29703
+ constructor(cache, callback) {
29704
+ super(cache, callback);
29682
29705
  }
29683
- return credentials;
29684
- };
29685
- var getWorkflow = function(credentials) {
29686
- const providerName = credentials.mechanismProperties.PROVIDER_NAME;
29687
- const workflow = exports.OIDC_WORKFLOWS.get(providerName || "callback");
29688
- if (!workflow) {
29689
- throw new error_1.MongoInvalidArgumentError(`Could not load workflow for provider ${credentials.mechanismProperties.PROVIDER_NAME}`);
29706
+ async execute(connection, credentials) {
29707
+ if (this.cache.hasAccessToken) {
29708
+ const token = this.cache.getAccessToken();
29709
+ try {
29710
+ return await this.finishAuthentication(connection, credentials, token);
29711
+ } catch (error) {
29712
+ if (error instanceof error_1.MongoError && error.code === error_1.MONGODB_ERROR_CODES.AuthenticationFailed) {
29713
+ this.cache.removeAccessToken();
29714
+ return await this.execute(connection, credentials);
29715
+ } else {
29716
+ throw error;
29717
+ }
29718
+ }
29719
+ }
29720
+ const response = await this.fetchAccessToken(credentials);
29721
+ this.cache.put(response);
29722
+ connection.accessToken = response.accessToken;
29723
+ await this.finishAuthentication(connection, credentials, response.accessToken);
29690
29724
  }
29691
- return workflow;
29692
- };
29725
+ async fetchAccessToken(credentials) {
29726
+ const controller = new AbortController;
29727
+ const params = {
29728
+ timeoutContext: controller.signal,
29729
+ version: mongodb_oidc_1.OIDC_VERSION
29730
+ };
29731
+ if (credentials.username) {
29732
+ params.username = credentials.username;
29733
+ }
29734
+ const timeout = timeout_1.Timeout.expires(callback_workflow_1.AUTOMATED_TIMEOUT_MS);
29735
+ try {
29736
+ return await Promise.race([this.executeAndValidateCallback(params), timeout]);
29737
+ } catch (error) {
29738
+ if (timeout_1.TimeoutError.is(error)) {
29739
+ controller.abort();
29740
+ throw new error_1.MongoOIDCError(`OIDC callback timed out after ${callback_workflow_1.AUTOMATED_TIMEOUT_MS}ms.`);
29741
+ }
29742
+ throw error;
29743
+ } finally {
29744
+ timeout.clear();
29745
+ }
29746
+ }
29747
+ }
29748
+ exports.AutomatedCallbackWorkflow = AutomatedCallbackWorkflow;
29749
+ });
29750
+
29751
+ // node_modules/mongodb/lib/cmap/auth/mongodb_oidc/human_callback_workflow.js
29752
+ var require_human_callback_workflow = __commonJS((exports) => {
29693
29753
  Object.defineProperty(exports, "__esModule", { value: true });
29694
- exports.MongoDBOIDC = exports.OIDC_WORKFLOWS = undefined;
29754
+ exports.HumanCallbackWorkflow = undefined;
29755
+ var bson_1 = require_bson();
29695
29756
  var error_1 = require_error();
29696
- var auth_provider_1 = require_auth_provider();
29697
- var aws_service_workflow_1 = require_aws_service_workflow();
29698
- var azure_service_workflow_1 = require_azure_service_workflow();
29757
+ var timeout_1 = require_timeout();
29758
+ var mongodb_oidc_1 = require_mongodb_oidc();
29699
29759
  var callback_workflow_1 = require_callback_workflow();
29700
- var MISSING_CREDENTIALS_ERROR = "AuthContext must provide credentials.";
29701
- exports.OIDC_WORKFLOWS = new Map;
29702
- exports.OIDC_WORKFLOWS.set("callback", new callback_workflow_1.CallbackWorkflow);
29703
- exports.OIDC_WORKFLOWS.set("aws", new aws_service_workflow_1.AwsServiceWorkflow);
29704
- exports.OIDC_WORKFLOWS.set("azure", new azure_service_workflow_1.AzureServiceWorkflow);
29705
29760
 
29706
- class MongoDBOIDC extends auth_provider_1.AuthProvider {
29707
- constructor() {
29708
- super();
29761
+ class HumanCallbackWorkflow extends callback_workflow_1.CallbackWorkflow {
29762
+ constructor(cache, callback) {
29763
+ super(cache, callback);
29709
29764
  }
29710
- async auth(authContext) {
29711
- const { connection, reauthenticating, response } = authContext;
29712
- const credentials = getCredentials(authContext);
29713
- const workflow = getWorkflow(credentials);
29714
- await workflow.execute(connection, credentials, reauthenticating, response);
29765
+ async execute(connection, credentials) {
29766
+ if (this.cache.hasAccessToken) {
29767
+ const token = this.cache.getAccessToken();
29768
+ connection.accessToken = token;
29769
+ try {
29770
+ return await this.finishAuthentication(connection, credentials, token);
29771
+ } catch (error) {
29772
+ if (error instanceof error_1.MongoError && error.code === error_1.MONGODB_ERROR_CODES.AuthenticationFailed) {
29773
+ this.cache.removeAccessToken();
29774
+ delete connection.accessToken;
29775
+ return await this.execute(connection, credentials);
29776
+ } else {
29777
+ throw error;
29778
+ }
29779
+ }
29780
+ }
29781
+ if (this.cache.hasRefreshToken) {
29782
+ const refreshToken = this.cache.getRefreshToken();
29783
+ const result = await this.fetchAccessToken(this.cache.getIdpInfo(), credentials, refreshToken);
29784
+ this.cache.put(result);
29785
+ connection.accessToken = result.accessToken;
29786
+ try {
29787
+ return await this.finishAuthentication(connection, credentials, result.accessToken);
29788
+ } catch (error) {
29789
+ if (error instanceof error_1.MongoError && error.code === error_1.MONGODB_ERROR_CODES.AuthenticationFailed) {
29790
+ this.cache.removeRefreshToken();
29791
+ delete connection.accessToken;
29792
+ return await this.execute(connection, credentials);
29793
+ } else {
29794
+ throw error;
29795
+ }
29796
+ }
29797
+ }
29798
+ const startResponse = await this.startAuthentication(connection, credentials);
29799
+ const conversationId = startResponse.conversationId;
29800
+ const idpInfo = bson_1.BSON.deserialize(startResponse.payload.buffer);
29801
+ const callbackResponse = await this.fetchAccessToken(idpInfo, credentials);
29802
+ this.cache.put(callbackResponse, idpInfo);
29803
+ connection.accessToken = callbackResponse.accessToken;
29804
+ return await this.finishAuthentication(connection, credentials, callbackResponse.accessToken, conversationId);
29715
29805
  }
29716
- async prepare(handshakeDoc, authContext) {
29717
- const credentials = getCredentials(authContext);
29718
- const workflow = getWorkflow(credentials);
29719
- const result = await workflow.speculativeAuth(credentials);
29720
- return { ...handshakeDoc, ...result };
29806
+ async fetchAccessToken(idpInfo, credentials, refreshToken) {
29807
+ const controller = new AbortController;
29808
+ const params = {
29809
+ timeoutContext: controller.signal,
29810
+ version: mongodb_oidc_1.OIDC_VERSION,
29811
+ idpInfo
29812
+ };
29813
+ if (credentials.username) {
29814
+ params.username = credentials.username;
29815
+ }
29816
+ if (refreshToken) {
29817
+ params.refreshToken = refreshToken;
29818
+ }
29819
+ const timeout = timeout_1.Timeout.expires(callback_workflow_1.HUMAN_TIMEOUT_MS);
29820
+ try {
29821
+ return await Promise.race([this.executeAndValidateCallback(params), timeout]);
29822
+ } catch (error) {
29823
+ if (timeout_1.TimeoutError.is(error)) {
29824
+ controller.abort();
29825
+ throw new error_1.MongoOIDCError(`OIDC callback timed out after ${callback_workflow_1.HUMAN_TIMEOUT_MS}ms.`);
29826
+ }
29827
+ throw error;
29828
+ } finally {
29829
+ timeout.clear();
29830
+ }
29721
29831
  }
29722
29832
  }
29723
- exports.MongoDBOIDC = MongoDBOIDC;
29833
+ exports.HumanCallbackWorkflow = HumanCallbackWorkflow;
29724
29834
  });
29725
29835
 
29726
29836
  // node_modules/mongodb/lib/cmap/auth/plain.js
@@ -30390,6 +30500,9 @@ var require_mongo_client_auth_providers = __commonJS((exports) => {
30390
30500
  var mongocr_1 = require_mongocr();
30391
30501
  var mongodb_aws_1 = require_mongodb_aws();
30392
30502
  var mongodb_oidc_1 = require_mongodb_oidc();
30503
+ var automated_callback_workflow_1 = require_automated_callback_workflow();
30504
+ var human_callback_workflow_1 = require_human_callback_workflow();
30505
+ var token_cache_1 = require_token_cache();
30393
30506
  var plain_1 = require_plain();
30394
30507
  var providers_1 = require_providers();
30395
30508
  var scram_1 = require_scram();
@@ -30399,7 +30512,7 @@ var require_mongo_client_auth_providers = __commonJS((exports) => {
30399
30512
  [providers_1.AuthMechanism.MONGODB_AWS, () => new mongodb_aws_1.MongoDBAWS],
30400
30513
  [providers_1.AuthMechanism.MONGODB_CR, () => new mongocr_1.MongoCR],
30401
30514
  [providers_1.AuthMechanism.MONGODB_GSSAPI, () => new gssapi_1.GSSAPI],
30402
- [providers_1.AuthMechanism.MONGODB_OIDC, () => new mongodb_oidc_1.MongoDBOIDC],
30515
+ [providers_1.AuthMechanism.MONGODB_OIDC, (workflow) => new mongodb_oidc_1.MongoDBOIDC(workflow)],
30403
30516
  [providers_1.AuthMechanism.MONGODB_PLAIN, () => new plain_1.Plain],
30404
30517
  [providers_1.AuthMechanism.MONGODB_SCRAM_SHA1, () => new scram_1.ScramSHA1],
30405
30518
  [providers_1.AuthMechanism.MONGODB_SCRAM_SHA256, () => new scram_1.ScramSHA256],
@@ -30410,18 +30523,38 @@ var require_mongo_client_auth_providers = __commonJS((exports) => {
30410
30523
  constructor() {
30411
30524
  this.existingProviders = new Map;
30412
30525
  }
30413
- getOrCreateProvider(name) {
30526
+ getOrCreateProvider(name, authMechanismProperties) {
30414
30527
  const authProvider = this.existingProviders.get(name);
30415
30528
  if (authProvider) {
30416
30529
  return authProvider;
30417
30530
  }
30418
- const provider = AUTH_PROVIDERS.get(name)?.();
30419
- if (!provider) {
30531
+ const providerFunction = AUTH_PROVIDERS.get(name);
30532
+ if (!providerFunction) {
30420
30533
  throw new error_1.MongoInvalidArgumentError(`authMechanism ${name} not supported`);
30421
30534
  }
30535
+ let provider;
30536
+ if (name === providers_1.AuthMechanism.MONGODB_OIDC) {
30537
+ provider = providerFunction(this.getWorkflow(authMechanismProperties));
30538
+ } else {
30539
+ provider = providerFunction();
30540
+ }
30422
30541
  this.existingProviders.set(name, provider);
30423
30542
  return provider;
30424
30543
  }
30544
+ getWorkflow(authMechanismProperties) {
30545
+ if (authMechanismProperties.OIDC_HUMAN_CALLBACK) {
30546
+ return new human_callback_workflow_1.HumanCallbackWorkflow(new token_cache_1.TokenCache, authMechanismProperties.OIDC_HUMAN_CALLBACK);
30547
+ } else if (authMechanismProperties.OIDC_CALLBACK) {
30548
+ return new automated_callback_workflow_1.AutomatedCallbackWorkflow(new token_cache_1.TokenCache, authMechanismProperties.OIDC_CALLBACK);
30549
+ } else {
30550
+ const environment = authMechanismProperties.ENVIRONMENT;
30551
+ const workflow = mongodb_oidc_1.OIDC_WORKFLOWS.get(environment)?.();
30552
+ if (!workflow) {
30553
+ throw new error_1.MongoInvalidArgumentError(`Could not load workflow for environment ${authMechanismProperties.ENVIRONMENT}`);
30554
+ }
30555
+ return workflow;
30556
+ }
30557
+ }
30425
30558
  }
30426
30559
  exports.MongoClientAuthProviders = MongoClientAuthProviders;
30427
30560
  });
@@ -31263,7 +31396,7 @@ var require_mongo_client = __commonJS((exports) => {
31263
31396
  }
31264
31397
  if (options.credentials?.mechanism === providers_1.AuthMechanism.MONGODB_OIDC) {
31265
31398
  const allowedHosts = options.credentials?.mechanismProperties?.ALLOWED_HOSTS || mongo_credentials_1.DEFAULT_ALLOWED_HOSTS;
31266
- const isServiceAuth = !!options.credentials?.mechanismProperties?.PROVIDER_NAME;
31399
+ const isServiceAuth = !!options.credentials?.mechanismProperties?.ENVIRONMENT;
31267
31400
  if (!isServiceAuth) {
31268
31401
  for (const host of options.hosts) {
31269
31402
  if (!(0, utils_1.hostMatchesWildcards)(host.toHostPort().host, allowedHosts)) {
@@ -32296,7 +32429,7 @@ var require_client_encryption = __commonJS((exports) => {
32296
32429
  proxyOptions: this._proxyOptions,
32297
32430
  tlsOptions: this._tlsOptions
32298
32431
  });
32299
- const dataKey = await stateMachine.execute(this, context);
32432
+ const dataKey = (0, bson_1.deserialize)(await stateMachine.execute(this, context));
32300
32433
  const { db: dbName, collection: collectionName } = utils_1.MongoDBCollectionNamespace.fromString(this._keyVaultNamespace);
32301
32434
  const { insertedId } = await this._keyVaultClient.db(dbName).collection(collectionName).insertOne(dataKey, { writeConcern: { w: "majority" } });
32302
32435
  return insertedId;
@@ -32313,7 +32446,7 @@ var require_client_encryption = __commonJS((exports) => {
32313
32446
  proxyOptions: this._proxyOptions,
32314
32447
  tlsOptions: this._tlsOptions
32315
32448
  });
32316
- const { v: dataKeys } = await stateMachine.execute(this, context);
32449
+ const { v: dataKeys } = (0, bson_1.deserialize)(await stateMachine.execute(this, context));
32317
32450
  if (dataKeys.length === 0) {
32318
32451
  return {};
32319
32452
  }
@@ -32425,7 +32558,7 @@ var require_client_encryption = __commonJS((exports) => {
32425
32558
  proxyOptions: this._proxyOptions,
32426
32559
  tlsOptions: this._tlsOptions
32427
32560
  });
32428
- const { v } = await stateMachine.execute(this, context);
32561
+ const { v } = (0, bson_1.deserialize)(await stateMachine.execute(this, context));
32429
32562
  return v;
32430
32563
  }
32431
32564
  async askForKMSCredentials() {
@@ -32467,8 +32600,8 @@ var require_client_encryption = __commonJS((exports) => {
32467
32600
  tlsOptions: this._tlsOptions
32468
32601
  });
32469
32602
  const context = this._mongoCrypt.makeExplicitEncryptionContext(valueBuffer, contextOptions);
32470
- const result = await stateMachine.execute(this, context);
32471
- return result.v;
32603
+ const { v } = (0, bson_1.deserialize)(await stateMachine.execute(this, context));
32604
+ return v;
32472
32605
  }
32473
32606
  }
32474
32607
  exports.ClientEncryption = ClientEncryption;
@@ -32477,9 +32610,9 @@ var require_client_encryption = __commonJS((exports) => {
32477
32610
  // node_modules/mongodb/lib/index.js
32478
32611
  var require_lib4 = __commonJS((exports) => {
32479
32612
  Object.defineProperty(exports, "__esModule", { value: true });
32480
- exports.MongoUnexpectedServerResponseError = exports.MongoTransactionError = exports.MongoTopologyClosedError = exports.MongoTailableCursorError = exports.MongoSystemError = exports.MongoServerSelectionError = exports.MongoServerError = exports.MongoServerClosedError = exports.MongoRuntimeError = exports.MongoParseError = exports.MongoNotConnectedError = exports.MongoNetworkTimeoutError = exports.MongoNetworkError = exports.MongoMissingDependencyError = exports.MongoMissingCredentialsError = exports.MongoKerberosError = exports.MongoInvalidArgumentError = exports.MongoGridFSStreamError = exports.MongoGridFSChunkError = exports.MongoExpiredSessionError = exports.MongoError = exports.MongoDriverError = exports.MongoDecompressionError = exports.MongoCursorInUseError = exports.MongoCursorExhaustedError = exports.MongoCompatibilityError = exports.MongoChangeStreamError = exports.MongoBatchReExecutionError = exports.MongoAzureError = exports.MongoAWSError = exports.MongoAPIError = exports.ChangeStreamCursor = exports.ClientEncryption = exports.MongoBulkWriteError = exports.UUID = exports.Timestamp = exports.ObjectId = exports.MinKey = exports.MaxKey = exports.Long = exports.Int32 = exports.Double = exports.Decimal128 = exports.DBRef = exports.Code = exports.BSONType = exports.BSONSymbol = exports.BSONRegExp = exports.Binary = exports.BSON = undefined;
32481
- exports.ConnectionPoolReadyEvent = exports.ConnectionPoolMonitoringEvent = exports.ConnectionPoolCreatedEvent = exports.ConnectionPoolClosedEvent = exports.ConnectionPoolClearedEvent = exports.ConnectionCreatedEvent = exports.ConnectionClosedEvent = exports.ConnectionCheckOutStartedEvent = exports.ConnectionCheckOutFailedEvent = exports.ConnectionCheckedOutEvent = exports.ConnectionCheckedInEvent = exports.CommandSucceededEvent = exports.CommandStartedEvent = exports.CommandFailedEvent = exports.WriteConcern = exports.ReadPreference = exports.ReadConcern = exports.TopologyType = exports.ServerType = exports.ReadPreferenceMode = exports.ReadConcernLevel = exports.ProfilingLevel = exports.ReturnDocument = exports.ServerApiVersion = exports.ExplainVerbosity = exports.MongoErrorLabel = exports.CURSOR_FLAGS = exports.Compressor = exports.AuthMechanism = exports.GSSAPICanonicalizationValue = exports.AutoEncryptionLoggerLevel = exports.BatchType = exports.UnorderedBulkOperation = exports.OrderedBulkOperation = exports.MongoClient = exports.ListIndexesCursor = exports.ListCollectionsCursor = exports.GridFSBucketWriteStream = exports.GridFSBucketReadStream = exports.GridFSBucket = exports.FindCursor = exports.Db = exports.Collection = exports.ClientSession = exports.ChangeStream = exports.CancellationToken = exports.AggregationCursor = exports.Admin = exports.AbstractCursor = exports.MongoWriteConcernError = undefined;
32482
- exports.MongoClientAuthProviders = exports.MongoCryptKMSRequestNetworkTimeoutError = exports.MongoCryptInvalidArgumentError = exports.MongoCryptError = exports.MongoCryptCreateEncryptedCollectionError = exports.MongoCryptCreateDataKeyError = exports.MongoCryptAzureKMSRequestError = exports.SrvPollingEvent = exports.WaitingForSuitableServerEvent = exports.ServerSelectionSucceededEvent = exports.ServerSelectionStartedEvent = exports.ServerSelectionFailedEvent = exports.ServerSelectionEvent = exports.TopologyOpeningEvent = exports.TopologyDescriptionChangedEvent = exports.TopologyClosedEvent = exports.ServerOpeningEvent = exports.ServerHeartbeatSucceededEvent = exports.ServerHeartbeatStartedEvent = exports.ServerHeartbeatFailedEvent = exports.ServerDescriptionChangedEvent = exports.ServerClosedEvent = exports.ConnectionReadyEvent = undefined;
32613
+ exports.MongoTopologyClosedError = exports.MongoTailableCursorError = exports.MongoSystemError = exports.MongoServerSelectionError = exports.MongoServerError = exports.MongoServerClosedError = exports.MongoRuntimeError = exports.MongoParseError = exports.MongoOIDCError = exports.MongoNotConnectedError = exports.MongoNetworkTimeoutError = exports.MongoNetworkError = exports.MongoMissingDependencyError = exports.MongoMissingCredentialsError = exports.MongoKerberosError = exports.MongoInvalidArgumentError = exports.MongoGridFSStreamError = exports.MongoGridFSChunkError = exports.MongoGCPError = exports.MongoExpiredSessionError = exports.MongoError = exports.MongoDriverError = exports.MongoDecompressionError = exports.MongoCursorInUseError = exports.MongoCursorExhaustedError = exports.MongoCompatibilityError = exports.MongoChangeStreamError = exports.MongoBatchReExecutionError = exports.MongoAzureError = exports.MongoAWSError = exports.MongoAPIError = exports.ChangeStreamCursor = exports.ClientEncryption = exports.MongoBulkWriteError = exports.UUID = exports.Timestamp = exports.ObjectId = exports.MinKey = exports.MaxKey = exports.Long = exports.Int32 = exports.Double = exports.Decimal128 = exports.DBRef = exports.Code = exports.BSONType = exports.BSONSymbol = exports.BSONRegExp = exports.Binary = exports.BSON = undefined;
32614
+ exports.ConnectionPoolCreatedEvent = exports.ConnectionPoolClosedEvent = exports.ConnectionPoolClearedEvent = exports.ConnectionCreatedEvent = exports.ConnectionClosedEvent = exports.ConnectionCheckOutStartedEvent = exports.ConnectionCheckOutFailedEvent = exports.ConnectionCheckedOutEvent = exports.ConnectionCheckedInEvent = exports.CommandSucceededEvent = exports.CommandStartedEvent = exports.CommandFailedEvent = exports.WriteConcern = exports.ReadPreference = exports.ReadConcern = exports.TopologyType = exports.ServerType = exports.ReadPreferenceMode = exports.ReadConcernLevel = exports.ProfilingLevel = exports.ReturnDocument = exports.ServerApiVersion = exports.ExplainVerbosity = exports.MongoErrorLabel = exports.CURSOR_FLAGS = exports.Compressor = exports.AuthMechanism = exports.GSSAPICanonicalizationValue = exports.AutoEncryptionLoggerLevel = exports.BatchType = exports.UnorderedBulkOperation = exports.OrderedBulkOperation = exports.MongoClient = exports.ListIndexesCursor = exports.ListCollectionsCursor = exports.GridFSBucketWriteStream = exports.GridFSBucketReadStream = exports.GridFSBucket = exports.FindCursor = exports.Db = exports.Collection = exports.ClientSession = exports.ChangeStream = exports.CancellationToken = exports.AggregationCursor = exports.Admin = exports.AbstractCursor = exports.MongoWriteConcernError = exports.MongoUnexpectedServerResponseError = exports.MongoTransactionError = undefined;
32615
+ exports.MongoClientAuthProviders = exports.MongoCryptKMSRequestNetworkTimeoutError = exports.MongoCryptInvalidArgumentError = exports.MongoCryptError = exports.MongoCryptCreateEncryptedCollectionError = exports.MongoCryptCreateDataKeyError = exports.MongoCryptAzureKMSRequestError = exports.SrvPollingEvent = exports.WaitingForSuitableServerEvent = exports.ServerSelectionSucceededEvent = exports.ServerSelectionStartedEvent = exports.ServerSelectionFailedEvent = exports.ServerSelectionEvent = exports.TopologyOpeningEvent = exports.TopologyDescriptionChangedEvent = exports.TopologyClosedEvent = exports.ServerOpeningEvent = exports.ServerHeartbeatSucceededEvent = exports.ServerHeartbeatStartedEvent = exports.ServerHeartbeatFailedEvent = exports.ServerDescriptionChangedEvent = exports.ServerClosedEvent = exports.ConnectionReadyEvent = exports.ConnectionPoolReadyEvent = exports.ConnectionPoolMonitoringEvent = undefined;
32483
32616
  var admin_1 = require_admin();
32484
32617
  Object.defineProperty(exports, "Admin", { enumerable: true, get: function() {
32485
32618
  return admin_1.Admin;
@@ -32647,6 +32780,9 @@ var require_lib4 = __commonJS((exports) => {
32647
32780
  Object.defineProperty(exports, "MongoExpiredSessionError", { enumerable: true, get: function() {
32648
32781
  return error_1.MongoExpiredSessionError;
32649
32782
  } });
32783
+ Object.defineProperty(exports, "MongoGCPError", { enumerable: true, get: function() {
32784
+ return error_1.MongoGCPError;
32785
+ } });
32650
32786
  Object.defineProperty(exports, "MongoGridFSChunkError", { enumerable: true, get: function() {
32651
32787
  return error_1.MongoGridFSChunkError;
32652
32788
  } });
@@ -32674,6 +32810,9 @@ var require_lib4 = __commonJS((exports) => {
32674
32810
  Object.defineProperty(exports, "MongoNotConnectedError", { enumerable: true, get: function() {
32675
32811
  return error_1.MongoNotConnectedError;
32676
32812
  } });
32813
+ Object.defineProperty(exports, "MongoOIDCError", { enumerable: true, get: function() {
32814
+ return error_1.MongoOIDCError;
32815
+ } });
32677
32816
  Object.defineProperty(exports, "MongoParseError", { enumerable: true, get: function() {
32678
32817
  return error_1.MongoParseError;
32679
32818
  } });
@@ -32899,7 +33038,7 @@ var require_lib4 = __commonJS((exports) => {
32899
33038
  });
32900
33039
 
32901
33040
  // node_modules/handlebars/dist/cjs/handlebars/utils.js
32902
- var require_utils5 = __commonJS((exports) => {
33041
+ var require_utils4 = __commonJS((exports) => {
32903
33042
  var escapeChar = function(chr) {
32904
33043
  return escape[chr];
32905
33044
  };
@@ -33043,7 +33182,7 @@ var require_exception = __commonJS((exports, module) => {
33043
33182
  // node_modules/handlebars/dist/cjs/handlebars/helpers/block-helper-missing.js
33044
33183
  var require_block_helper_missing = __commonJS((exports, module) => {
33045
33184
  exports.__esModule = true;
33046
- var _utils = require_utils5();
33185
+ var _utils = require_utils4();
33047
33186
  exports.default = function(instance) {
33048
33187
  instance.registerHelper("blockHelperMissing", function(context, options) {
33049
33188
  var { inverse: inverse2, fn } = options;
@@ -33079,7 +33218,7 @@ var require_each = __commonJS((exports, module) => {
33079
33218
  return obj && obj.__esModule ? obj : { default: obj };
33080
33219
  };
33081
33220
  exports.__esModule = true;
33082
- var _utils = require_utils5();
33221
+ var _utils = require_utils4();
33083
33222
  var _exception = require_exception();
33084
33223
  var _exception2 = _interopRequireDefault(_exception);
33085
33224
  exports.default = function(instance) {
@@ -33180,7 +33319,7 @@ var require_if = __commonJS((exports, module) => {
33180
33319
  return obj && obj.__esModule ? obj : { default: obj };
33181
33320
  };
33182
33321
  exports.__esModule = true;
33183
- var _utils = require_utils5();
33322
+ var _utils = require_utils4();
33184
33323
  var _exception = require_exception();
33185
33324
  var _exception2 = _interopRequireDefault(_exception);
33186
33325
  exports.default = function(instance) {
@@ -33253,7 +33392,7 @@ var require_with = __commonJS((exports, module) => {
33253
33392
  return obj && obj.__esModule ? obj : { default: obj };
33254
33393
  };
33255
33394
  exports.__esModule = true;
33256
- var _utils = require_utils5();
33395
+ var _utils = require_utils4();
33257
33396
  var _exception = require_exception();
33258
33397
  var _exception2 = _interopRequireDefault(_exception);
33259
33398
  exports.default = function(instance) {
@@ -33327,7 +33466,7 @@ var require_helpers = __commonJS((exports) => {
33327
33466
  // node_modules/handlebars/dist/cjs/handlebars/decorators/inline.js
33328
33467
  var require_inline = __commonJS((exports, module) => {
33329
33468
  exports.__esModule = true;
33330
- var _utils = require_utils5();
33469
+ var _utils = require_utils4();
33331
33470
  exports.default = function(instance) {
33332
33471
  instance.registerDecorator("inline", function(fn, props, container, options) {
33333
33472
  var ret = fn;
@@ -33365,7 +33504,7 @@ var require_decorators = __commonJS((exports) => {
33365
33504
  // node_modules/handlebars/dist/cjs/handlebars/logger.js
33366
33505
  var require_logger = __commonJS((exports, module) => {
33367
33506
  exports.__esModule = true;
33368
- var _utils = require_utils5();
33507
+ var _utils = require_utils4();
33369
33508
  var logger = {
33370
33509
  methodMap: ["debug", "info", "warn", "error"],
33371
33510
  level: "info",
@@ -33408,7 +33547,7 @@ var require_create_new_lookup_object = __commonJS((exports) => {
33408
33547
  };
33409
33548
  exports.__esModule = true;
33410
33549
  exports.createNewLookupObject = createNewLookupObject;
33411
- var _utils = require_utils5();
33550
+ var _utils = require_utils4();
33412
33551
  });
33413
33552
 
33414
33553
  // node_modules/handlebars/dist/cjs/handlebars/internal/proto-access.js
@@ -33487,7 +33626,7 @@ var require_base = __commonJS((exports) => {
33487
33626
  };
33488
33627
  exports.__esModule = true;
33489
33628
  exports.HandlebarsEnvironment = HandlebarsEnvironment;
33490
- var _utils = require_utils5();
33629
+ var _utils = require_utils4();
33491
33630
  var _exception = require_exception();
33492
33631
  var _exception2 = _interopRequireDefault(_exception);
33493
33632
  var _helpers = require_helpers();
@@ -33892,7 +34031,7 @@ var require_runtime = __commonJS((exports) => {
33892
34031
  exports.resolvePartial = resolvePartial;
33893
34032
  exports.invokePartial = invokePartial;
33894
34033
  exports.noop = noop;
33895
- var _utils = require_utils5();
34034
+ var _utils = require_utils4();
33896
34035
  var Utils = _interopRequireWildcard(_utils);
33897
34036
  var _exception = require_exception();
33898
34037
  var _exception2 = _interopRequireDefault(_exception);
@@ -33966,7 +34105,7 @@ var require_handlebars_runtime = __commonJS((exports, module) => {
33966
34105
  var _handlebarsSafeString2 = _interopRequireDefault(_handlebarsSafeString);
33967
34106
  var _handlebarsException = require_exception();
33968
34107
  var _handlebarsException2 = _interopRequireDefault(_handlebarsException);
33969
- var _handlebarsUtils = require_utils5();
34108
+ var _handlebarsUtils = require_utils4();
33970
34109
  var Utils = _interopRequireWildcard(_handlebarsUtils);
33971
34110
  var _handlebarsRuntime = require_runtime();
33972
34111
  var runtime = _interopRequireWildcard(_handlebarsRuntime);
@@ -35210,7 +35349,7 @@ var require_base2 = __commonJS((exports) => {
35210
35349
  var _whitespaceControl2 = _interopRequireDefault(_whitespaceControl);
35211
35350
  var _helpers = require_helpers2();
35212
35351
  var Helpers = _interopRequireWildcard(_helpers);
35213
- var _utils = require_utils5();
35352
+ var _utils = require_utils4();
35214
35353
  exports.parser = _parser2["default"];
35215
35354
  var yy = {};
35216
35355
  _utils.extend(yy, Helpers);
@@ -35307,7 +35446,7 @@ var require_compiler = __commonJS((exports) => {
35307
35446
  exports.compile = compile;
35308
35447
  var _exception = require_exception();
35309
35448
  var _exception2 = _interopRequireDefault(_exception);
35310
- var _utils = require_utils5();
35449
+ var _utils = require_utils4();
35311
35450
  var _ast = require_ast();
35312
35451
  var _ast2 = _interopRequireDefault(_ast);
35313
35452
  var slice = [].slice;
@@ -37329,7 +37468,7 @@ var require_code_gen = __commonJS((exports, module) => {
37329
37468
  this.source = [];
37330
37469
  };
37331
37470
  exports.__esModule = true;
37332
- var _utils = require_utils5();
37471
+ var _utils = require_utils4();
37333
37472
  var SourceNode = undefined;
37334
37473
  try {
37335
37474
  if (typeof define !== "function" || !define.amd) {
@@ -37471,7 +37610,7 @@ var require_javascript_compiler = __commonJS((exports, module) => {
37471
37610
  var _base = require_base();
37472
37611
  var _exception = require_exception();
37473
37612
  var _exception2 = _interopRequireDefault(_exception);
37474
- var _utils = require_utils5();
37613
+ var _utils = require_utils4();
37475
37614
  var _codeGen = require_code_gen();
37476
37615
  var _codeGen2 = _interopRequireDefault(_codeGen);
37477
37616
  JavaScriptCompiler.prototype = {
@@ -39400,7 +39539,7 @@ var require_property = __commonJS((exports, module) => {
39400
39539
  this.additionalPriority = additionalPriority || [];
39401
39540
  };
39402
39541
  module.exports = exports = Property;
39403
- var utils = require_utils6();
39542
+ var utils = require_utils5();
39404
39543
  Property.prototype.compareFunc = function(property) {
39405
39544
  var a = [];
39406
39545
  a.push.apply(a, this.selector.specificity());
@@ -39425,7 +39564,7 @@ var require_property = __commonJS((exports, module) => {
39425
39564
  });
39426
39565
 
39427
39566
  // node_modules/juice/lib/utils.js
39428
- var require_utils6 = __commonJS((exports) => {
39567
+ var require_utils5 = __commonJS((exports) => {
39429
39568
  var mensch = require_mensch();
39430
39569
  var Selector = require_selector();
39431
39570
  var Property = require_property();
@@ -46308,7 +46447,7 @@ var require_static = __commonJS((exports) => {
46308
46447
  });
46309
46448
 
46310
46449
  // node_modules/cheerio/lib/utils.js
46311
- var require_utils7 = __commonJS((exports) => {
46450
+ var require_utils6 = __commonJS((exports) => {
46312
46451
  var isCheerio = function(maybeCheerio) {
46313
46452
  return maybeCheerio.cheerio != null;
46314
46453
  };
@@ -46739,7 +46878,7 @@ var require_attributes = __commonJS((exports) => {
46739
46878
  Object.defineProperty(exports, "__esModule", { value: true });
46740
46879
  exports.toggleClass = exports.removeClass = exports.addClass = exports.hasClass = exports.removeAttr = exports.val = exports.data = exports.prop = exports.attr = undefined;
46741
46880
  var static_js_1 = require_static();
46742
- var utils_js_1 = require_utils7();
46881
+ var utils_js_1 = require_utils6();
46743
46882
  var domutils_1 = require_lib16();
46744
46883
  var hasOwn = Object.prototype.hasOwnProperty;
46745
46884
  var rspace = /\s+/;
@@ -49166,7 +49305,7 @@ var require_traversing = __commonJS((exports) => {
49166
49305
  exports.addBack = exports.add = exports.end = exports.slice = exports.index = exports.toArray = exports.get = exports.eq = exports.last = exports.first = exports.has = exports.not = exports.is = exports.filterArray = exports.filter = exports.map = exports.each = exports.contents = exports.children = exports.siblings = exports.prevUntil = exports.prevAll = exports.prev = exports.nextUntil = exports.nextAll = exports.next = exports.closest = exports.parentsUntil = exports.parents = exports.parent = exports.find = undefined;
49167
49306
  var domhandler_1 = require_lib13();
49168
49307
  var select = __importStar(require_lib19());
49169
- var utils_js_1 = require_utils7();
49308
+ var utils_js_1 = require_utils6();
49170
49309
  var static_js_1 = require_static();
49171
49310
  var domutils_1 = require_lib16();
49172
49311
  var reSiblingSelector = /^\s*[~+]/;
@@ -49641,7 +49780,7 @@ var require_manipulation3 = __commonJS((exports) => {
49641
49780
  var domhandler_1 = require_lib13();
49642
49781
  var parse_js_1 = require_parse3();
49643
49782
  var static_js_1 = require_static();
49644
- var utils_js_1 = require_utils7();
49783
+ var utils_js_1 = require_utils6();
49645
49784
  var domutils_1 = require_lib16();
49646
49785
  exports._makeDomArray = _makeDomArray;
49647
49786
  exports.appendTo = appendTo;
@@ -49759,7 +49898,7 @@ var require_css2 = __commonJS((exports) => {
49759
49898
  };
49760
49899
  Object.defineProperty(exports, "__esModule", { value: true });
49761
49900
  exports.css = undefined;
49762
- var utils_js_1 = require_utils7();
49901
+ var utils_js_1 = require_utils6();
49763
49902
  exports.css = css;
49764
49903
  });
49765
49904
 
@@ -49795,7 +49934,7 @@ var require_forms = __commonJS((exports) => {
49795
49934
  };
49796
49935
  Object.defineProperty(exports, "__esModule", { value: true });
49797
49936
  exports.serializeArray = exports.serialize = undefined;
49798
- var utils_js_1 = require_utils7();
49937
+ var utils_js_1 = require_utils6();
49799
49938
  var submittableSelector = "input,select,textarea,keygen";
49800
49939
  var r20 = /%20/g;
49801
49940
  var rCRLF = /\r?\n/g;
@@ -50005,7 +50144,7 @@ var require_load = __commonJS((exports) => {
50005
50144
  var options_js_1 = __importStar(require_options());
50006
50145
  var staticMethods = __importStar(require_static());
50007
50146
  var cheerio_js_1 = require_cheerio();
50008
- var utils_js_1 = require_utils7();
50147
+ var utils_js_1 = require_utils6();
50009
50148
  exports.getLoad = getLoad;
50010
50149
  });
50011
50150
 
@@ -59169,7 +59308,7 @@ var require_lib21 = __commonJS((exports) => {
59169
59308
  // node_modules/juice/lib/cheerio.js
59170
59309
  var require_cheerio2 = __commonJS((exports, module) => {
59171
59310
  var cheerio = require_lib21();
59172
- var utils = require_utils6();
59311
+ var utils = require_utils5();
59173
59312
  var cheerioLoad = function(html, options, encodeEntities) {
59174
59313
  options = Object.assign({ decodeEntities: false, _useHtmlParser2: true }, options);
59175
59314
  html = encodeEntities(html);
@@ -59321,7 +59460,7 @@ var require_variables = __commonJS((exports, module) => {
59321
59460
 
59322
59461
  // node_modules/juice/lib/inline.js
59323
59462
  var require_inline3 = __commonJS((exports, module) => {
59324
- var utils = require_utils6();
59463
+ var utils = require_utils5();
59325
59464
  var numbers = require_numbers();
59326
59465
  var variables = require_variables();
59327
59466
  module.exports = function makeJuiceClient(juiceClient) {
@@ -59788,7 +59927,7 @@ var require_juice = __commonJS((exports, module) => {
59788
59927
  options.webResources.relativeTo = options.webResources.relativeTo || options.url;
59789
59928
  inlineExternal(html, options.webResources, onInline);
59790
59929
  };
59791
- var utils = require_utils6();
59930
+ var utils = require_utils5();
59792
59931
  var packageJson = require_package2();
59793
59932
  var fs = import.meta.require("fs");
59794
59933
  var path = import.meta.require("path");
@@ -60697,8 +60836,8 @@ class DatabaseConnection {
60697
60836
  async deleteAll(options) {
60698
60837
  return await this.adapter.deleteAll(options);
60699
60838
  }
60700
- async aggregate(pipeline, query, options) {
60701
- return await this.adapter.aggregate(pipeline, query, options);
60839
+ async aggregate(pipeline, options) {
60840
+ return await this.adapter.aggregate(pipeline, options);
60702
60841
  }
60703
60842
  }
60704
60843
 
@@ -61065,37 +61204,14 @@ class MongoDBConnection {
61065
61204
  const result = await this._collection.deleteMany({}, deleteOptions);
61066
61205
  return { deleted_count: result.deletedCount };
61067
61206
  }
61068
- async aggregate(pipeline, query, options) {
61207
+ async aggregate(pipeline, options) {
61069
61208
  if (!this._collection) {
61070
61209
  throw new Error("Collection not found");
61071
61210
  }
61072
61211
  const aggregateOptions = options;
61073
- const cursor = this._collection.aggregate([
61074
- ...pipeline,
61075
- { $skip: (mongodb_querystring_default.page(query.page) - 1) * mongodb_querystring_default.limit(query.page_size) },
61076
- { $limit: mongodb_querystring_default.limit(query.page_size) }
61077
- ], aggregateOptions);
61078
- const sort2 = mongodb_querystring_default.sort(query.sort ?? "");
61079
- if (!isEmpty(sort2)) {
61080
- cursor.sort(sort2);
61081
- }
61082
- const fields2 = mongodb_querystring_default.fields(query.fields ?? "", query.exclude_fields ?? []);
61083
- if (!isEmpty(fields2)) {
61084
- cursor.project(fields2);
61085
- }
61212
+ const cursor = this._collection.aggregate(MongoDBHelper.stringToObjectId(pipeline), aggregateOptions);
61086
61213
  const result = await cursor.toArray();
61087
- const cursorPagination = this._collection.aggregate([...pipeline, { $count: "totalDocument" }], aggregateOptions);
61088
- const resultPagination = await cursorPagination.toArray();
61089
- const totalDocument = resultPagination.length ? resultPagination[0].totalDocument : 0;
61090
- return {
61091
- data: MongoDBHelper.objectIdToString(result),
61092
- pagination: {
61093
- page: mongodb_querystring_default.page(query.page),
61094
- page_count: Math.ceil(totalDocument / mongodb_querystring_default.limit(query.page_size)),
61095
- page_size: mongodb_querystring_default.limit(query.page_size),
61096
- total_document: totalDocument
61097
- }
61098
- };
61214
+ return MongoDBHelper.objectIdToString(result);
61099
61215
  }
61100
61216
  }
61101
61217