mongodb 6.8.2 → 6.9.0-dev.20240917.sha.20396e1b

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (252) hide show
  1. package/README.md +14 -1
  2. package/lib/beta.d.ts +7940 -0
  3. package/lib/beta.js +21 -0
  4. package/lib/beta.js.map +1 -0
  5. package/lib/bson.js +5 -5
  6. package/lib/bson.js.map +1 -1
  7. package/lib/bulk/common.js +16 -21
  8. package/lib/bulk/common.js.map +1 -1
  9. package/lib/bulk/ordered.js.map +1 -1
  10. package/lib/bulk/unordered.js.map +1 -1
  11. package/lib/change_stream.js +10 -8
  12. package/lib/change_stream.js.map +1 -1
  13. package/lib/client-side-encryption/auto_encrypter.js +14 -3
  14. package/lib/client-side-encryption/auto_encrypter.js.map +1 -1
  15. package/lib/client-side-encryption/client_encryption.js +25 -7
  16. package/lib/client-side-encryption/client_encryption.js.map +1 -1
  17. package/lib/client-side-encryption/crypto_callbacks.js +6 -6
  18. package/lib/client-side-encryption/crypto_callbacks.js.map +1 -1
  19. package/lib/client-side-encryption/mongocryptd_manager.js +9 -5
  20. package/lib/client-side-encryption/mongocryptd_manager.js.map +1 -1
  21. package/lib/client-side-encryption/providers/aws.js +1 -2
  22. package/lib/client-side-encryption/providers/aws.js.map +1 -1
  23. package/lib/client-side-encryption/providers/azure.js +5 -5
  24. package/lib/client-side-encryption/providers/azure.js.map +1 -1
  25. package/lib/client-side-encryption/providers/gcp.js +1 -2
  26. package/lib/client-side-encryption/providers/gcp.js.map +1 -1
  27. package/lib/client-side-encryption/providers/index.js +2 -3
  28. package/lib/client-side-encryption/providers/index.js.map +1 -1
  29. package/lib/client-side-encryption/state_machine.js +9 -4
  30. package/lib/client-side-encryption/state_machine.js.map +1 -1
  31. package/lib/cmap/auth/auth_provider.js.map +1 -1
  32. package/lib/cmap/auth/aws_temporary_credentials.js.map +1 -1
  33. package/lib/cmap/auth/gssapi.js +4 -4
  34. package/lib/cmap/auth/gssapi.js.map +1 -1
  35. package/lib/cmap/auth/mongo_credentials.js +2 -7
  36. package/lib/cmap/auth/mongo_credentials.js.map +1 -1
  37. package/lib/cmap/auth/mongodb_aws.js.map +1 -1
  38. package/lib/cmap/auth/mongodb_oidc/automated_callback_workflow.js.map +1 -1
  39. package/lib/cmap/auth/mongodb_oidc/azure_machine_workflow.js.map +1 -1
  40. package/lib/cmap/auth/mongodb_oidc/callback_workflow.js +0 -2
  41. package/lib/cmap/auth/mongodb_oidc/callback_workflow.js.map +1 -1
  42. package/lib/cmap/auth/mongodb_oidc/command_builders.js +2 -3
  43. package/lib/cmap/auth/mongodb_oidc/command_builders.js.map +1 -1
  44. package/lib/cmap/auth/mongodb_oidc/gcp_machine_workflow.js.map +1 -1
  45. package/lib/cmap/auth/mongodb_oidc/human_callback_workflow.js.map +1 -1
  46. package/lib/cmap/auth/mongodb_oidc/machine_workflow.js +0 -2
  47. package/lib/cmap/auth/mongodb_oidc/machine_workflow.js.map +1 -1
  48. package/lib/cmap/auth/mongodb_oidc/token_cache.js.map +1 -1
  49. package/lib/cmap/auth/mongodb_oidc/token_machine_workflow.js.map +1 -1
  50. package/lib/cmap/auth/mongodb_oidc.js.map +1 -1
  51. package/lib/cmap/auth/plain.js.map +1 -1
  52. package/lib/cmap/auth/scram.js.map +1 -1
  53. package/lib/cmap/auth/x509.js.map +1 -1
  54. package/lib/cmap/command_monitoring_events.js.map +1 -1
  55. package/lib/cmap/commands.js +62 -5
  56. package/lib/cmap/commands.js.map +1 -1
  57. package/lib/cmap/connect.js +10 -7
  58. package/lib/cmap/connect.js.map +1 -1
  59. package/lib/cmap/connection.js +3 -5
  60. package/lib/cmap/connection.js.map +1 -1
  61. package/lib/cmap/connection_pool.js +11 -9
  62. package/lib/cmap/connection_pool.js.map +1 -1
  63. package/lib/cmap/connection_pool_events.js +7 -3
  64. package/lib/cmap/connection_pool_events.js.map +1 -1
  65. package/lib/cmap/handshake/client_metadata.js +5 -5
  66. package/lib/cmap/handshake/client_metadata.js.map +1 -1
  67. package/lib/cmap/metrics.js +1 -1
  68. package/lib/cmap/metrics.js.map +1 -1
  69. package/lib/cmap/stream_description.js.map +1 -1
  70. package/lib/cmap/wire_protocol/compression.js +5 -5
  71. package/lib/cmap/wire_protocol/compression.js.map +1 -1
  72. package/lib/cmap/wire_protocol/constants.js +4 -4
  73. package/lib/cmap/wire_protocol/on_data.js +1 -2
  74. package/lib/cmap/wire_protocol/on_data.js.map +1 -1
  75. package/lib/cmap/wire_protocol/on_demand/document.js.map +1 -1
  76. package/lib/cmap/wire_protocol/responses.js +4 -4
  77. package/lib/cmap/wire_protocol/responses.js.map +1 -1
  78. package/lib/cmap/wire_protocol/shared.js +2 -3
  79. package/lib/cmap/wire_protocol/shared.js.map +1 -1
  80. package/lib/collection.js.map +1 -1
  81. package/lib/connection_string.js +12 -6
  82. package/lib/connection_string.js.map +1 -1
  83. package/lib/constants.js +1 -0
  84. package/lib/constants.js.map +1 -1
  85. package/lib/cursor/abstract_cursor.js +21 -6
  86. package/lib/cursor/abstract_cursor.js.map +1 -1
  87. package/lib/cursor/aggregation_cursor.js +1 -1
  88. package/lib/cursor/aggregation_cursor.js.map +1 -1
  89. package/lib/cursor/change_stream_cursor.js.map +1 -1
  90. package/lib/cursor/find_cursor.js +3 -3
  91. package/lib/cursor/find_cursor.js.map +1 -1
  92. package/lib/db.js +2 -2
  93. package/lib/db.js.map +1 -1
  94. package/lib/deps.js +16 -8
  95. package/lib/deps.js.map +1 -1
  96. package/lib/encrypter.js.map +1 -1
  97. package/lib/error.js +19 -14
  98. package/lib/error.js.map +1 -1
  99. package/lib/explain.js +6 -6
  100. package/lib/explain.js.map +1 -1
  101. package/lib/gridfs/download.js +1 -4
  102. package/lib/gridfs/download.js.map +1 -1
  103. package/lib/gridfs/index.js +1 -1
  104. package/lib/gridfs/index.js.map +1 -1
  105. package/lib/gridfs/upload.js +0 -4
  106. package/lib/gridfs/upload.js.map +1 -1
  107. package/lib/index.js +4 -2
  108. package/lib/index.js.map +1 -1
  109. package/lib/mongo_client.js +15 -1
  110. package/lib/mongo_client.js.map +1 -1
  111. package/lib/mongo_client_auth_providers.js +6 -2
  112. package/lib/mongo_client_auth_providers.js.map +1 -1
  113. package/lib/mongo_logger.js +8 -8
  114. package/lib/mongo_logger.js.map +1 -1
  115. package/lib/mongo_types.js +1 -0
  116. package/lib/mongo_types.js.map +1 -1
  117. package/lib/operations/aggregate.js +1 -0
  118. package/lib/operations/aggregate.js.map +1 -1
  119. package/lib/operations/bulk_write.js.map +1 -1
  120. package/lib/operations/client_bulk_write/command_builder.js +198 -0
  121. package/lib/operations/client_bulk_write/command_builder.js.map +1 -0
  122. package/lib/operations/client_bulk_write/common.js +3 -0
  123. package/lib/operations/client_bulk_write/common.js.map +1 -0
  124. package/lib/operations/collections.js.map +1 -1
  125. package/lib/operations/command.js +1 -1
  126. package/lib/operations/command.js.map +1 -1
  127. package/lib/operations/count.js.map +1 -1
  128. package/lib/operations/create_collection.js.map +1 -1
  129. package/lib/operations/delete.js +2 -2
  130. package/lib/operations/delete.js.map +1 -1
  131. package/lib/operations/distinct.js.map +1 -1
  132. package/lib/operations/drop.js.map +1 -1
  133. package/lib/operations/estimated_document_count.js.map +1 -1
  134. package/lib/operations/execute_operation.js +111 -109
  135. package/lib/operations/execute_operation.js.map +1 -1
  136. package/lib/operations/find.js.map +1 -1
  137. package/lib/operations/find_and_modify.js +2 -8
  138. package/lib/operations/find_and_modify.js.map +1 -1
  139. package/lib/operations/get_more.js.map +1 -1
  140. package/lib/operations/indexes.js.map +1 -1
  141. package/lib/operations/insert.js.map +1 -1
  142. package/lib/operations/is_capped.js.map +1 -1
  143. package/lib/operations/kill_cursors.js.map +1 -1
  144. package/lib/operations/list_collections.js.map +1 -1
  145. package/lib/operations/list_databases.js.map +1 -1
  146. package/lib/operations/operation.js +5 -5
  147. package/lib/operations/operation.js.map +1 -1
  148. package/lib/operations/options_operation.js.map +1 -1
  149. package/lib/operations/profiling_level.js.map +1 -1
  150. package/lib/operations/search_indexes/drop.js.map +1 -1
  151. package/lib/operations/set_profiling_level.js.map +1 -1
  152. package/lib/operations/stats.js.map +1 -1
  153. package/lib/operations/update.js +2 -2
  154. package/lib/operations/update.js.map +1 -1
  155. package/lib/operations/validate_collection.js.map +1 -1
  156. package/lib/read_concern.js.map +1 -1
  157. package/lib/read_preference.js +1 -1
  158. package/lib/read_preference.js.map +1 -1
  159. package/lib/resource_management.js +58 -0
  160. package/lib/resource_management.js.map +1 -0
  161. package/lib/sdam/common.js +3 -3
  162. package/lib/sdam/common.js.map +1 -1
  163. package/lib/sdam/monitor.js +1 -5
  164. package/lib/sdam/monitor.js.map +1 -1
  165. package/lib/sdam/server.js +2 -2
  166. package/lib/sdam/server.js.map +1 -1
  167. package/lib/sdam/server_description.js +3 -3
  168. package/lib/sdam/server_description.js.map +1 -1
  169. package/lib/sdam/server_selection.js +5 -5
  170. package/lib/sdam/server_selection.js.map +1 -1
  171. package/lib/sdam/srv_polling.js +2 -3
  172. package/lib/sdam/srv_polling.js.map +1 -1
  173. package/lib/sdam/topology.js +1 -1
  174. package/lib/sdam/topology.js.map +1 -1
  175. package/lib/sdam/topology_description.js.map +1 -1
  176. package/lib/sessions.js +221 -218
  177. package/lib/sessions.js.map +1 -1
  178. package/lib/sort.js +2 -3
  179. package/lib/sort.js.map +1 -1
  180. package/lib/timeout.js +0 -1
  181. package/lib/timeout.js.map +1 -1
  182. package/lib/transactions.js +2 -2
  183. package/lib/transactions.js.map +1 -1
  184. package/lib/utils.js +54 -54
  185. package/lib/utils.js.map +1 -1
  186. package/lib/write_concern.js +2 -2
  187. package/lib/write_concern.js.map +1 -1
  188. package/mongodb.d.ts +191 -148
  189. package/package.json +27 -28
  190. package/src/beta.ts +22 -0
  191. package/src/bson.ts +1 -2
  192. package/src/bulk/common.ts +18 -18
  193. package/src/change_stream.ts +33 -15
  194. package/src/client-side-encryption/auto_encrypter.ts +18 -82
  195. package/src/client-side-encryption/client_encryption.ts +51 -54
  196. package/src/client-side-encryption/mongocryptd_manager.ts +10 -6
  197. package/src/client-side-encryption/state_machine.ts +28 -6
  198. package/src/cmap/auth/gssapi.ts +1 -1
  199. package/src/cmap/auth/mongo_credentials.ts +2 -8
  200. package/src/cmap/auth/mongodb_aws.ts +2 -2
  201. package/src/cmap/auth/mongodb_oidc/callback_workflow.ts +2 -2
  202. package/src/cmap/auth/mongodb_oidc/machine_workflow.ts +2 -2
  203. package/src/cmap/commands.ts +70 -5
  204. package/src/cmap/connect.ts +4 -1
  205. package/src/cmap/connection.ts +2 -2
  206. package/src/cmap/connection_pool.ts +17 -9
  207. package/src/cmap/connection_pool_events.ts +34 -2
  208. package/src/cmap/handshake/client_metadata.ts +1 -1
  209. package/src/cmap/wire_protocol/constants.ts +4 -4
  210. package/src/cmap/wire_protocol/shared.ts +1 -2
  211. package/src/collection.ts +16 -15
  212. package/src/connection_string.ts +10 -3
  213. package/src/constants.ts +1 -0
  214. package/src/cursor/abstract_cursor.ts +38 -13
  215. package/src/cursor/aggregation_cursor.ts +8 -6
  216. package/src/cursor/find_cursor.ts +2 -2
  217. package/src/db.ts +1 -1
  218. package/src/deps.ts +8 -1
  219. package/src/error.ts +33 -14
  220. package/src/explain.ts +47 -11
  221. package/src/gridfs/download.ts +28 -4
  222. package/src/gridfs/upload.ts +1 -6
  223. package/src/index.ts +11 -2
  224. package/src/mongo_client.ts +29 -5
  225. package/src/mongo_client_auth_providers.ts +8 -2
  226. package/src/mongo_logger.ts +5 -3
  227. package/src/mongo_types.ts +69 -68
  228. package/src/operations/aggregate.ts +2 -1
  229. package/src/operations/bulk_write.ts +2 -2
  230. package/src/operations/client_bulk_write/command_builder.ts +283 -0
  231. package/src/operations/client_bulk_write/common.ts +146 -0
  232. package/src/operations/command.ts +1 -1
  233. package/src/operations/execute_operation.ts +137 -131
  234. package/src/operations/find_and_modify.ts +2 -7
  235. package/src/operations/insert.ts +3 -4
  236. package/src/operations/operation.ts +7 -10
  237. package/src/operations/search_indexes/drop.ts +4 -1
  238. package/src/resource_management.ts +74 -0
  239. package/src/sdam/monitor.ts +3 -5
  240. package/src/sdam/server.ts +1 -1
  241. package/src/sdam/server_description.ts +5 -6
  242. package/src/sdam/srv_polling.ts +1 -2
  243. package/src/sessions.ts +291 -277
  244. package/src/sort.ts +1 -1
  245. package/src/timeout.ts +0 -1
  246. package/src/transactions.ts +1 -2
  247. package/src/utils.ts +25 -9
  248. package/src/write_concern.ts +2 -2
  249. package/tsconfig.json +2 -1
  250. package/lib/cmap/auth/mongocr.js +0 -35
  251. package/lib/cmap/auth/mongocr.js.map +0 -1
  252. package/src/cmap/auth/mongocr.ts +0 -38
@@ -13,6 +13,7 @@ import {
13
13
  CONNECTION_READY
14
14
  } from '../constants';
15
15
  import type { MongoError } from '../error';
16
+ import { now } from '../utils';
16
17
  import type { Connection } from './connection';
17
18
  import type { ConnectionPool, ConnectionPoolOptions } from './connection_pool';
18
19
 
@@ -126,12 +127,25 @@ export class ConnectionCreatedEvent extends ConnectionPoolMonitoringEvent {
126
127
  export class ConnectionReadyEvent extends ConnectionPoolMonitoringEvent {
127
128
  /** The id of the connection */
128
129
  connectionId: number | '<monitor>';
130
+ /**
131
+ * The time it took to establish the connection.
132
+ * In accordance with the definition of establishment of a connection
133
+ * specified by `ConnectionPoolOptions.maxConnecting`,
134
+ * it is the time elapsed between emitting a `ConnectionCreatedEvent`
135
+ * and emitting this event as part of the same checking out.
136
+ *
137
+ * Naturally, when establishing a connection is part of checking out,
138
+ * this duration is not greater than
139
+ * `ConnectionCheckedOutEvent.duration`.
140
+ */
141
+ durationMS: number;
129
142
  /** @internal */
130
143
  name = CONNECTION_READY;
131
144
 
132
145
  /** @internal */
133
- constructor(pool: ConnectionPool, connection: Connection) {
146
+ constructor(pool: ConnectionPool, connection: Connection, connectionCreatedEventTime: number) {
134
147
  super(pool);
148
+ this.durationMS = now() - connectionCreatedEventTime;
135
149
  this.connectionId = connection.id;
136
150
  }
137
151
  }
@@ -194,14 +208,23 @@ export class ConnectionCheckOutFailedEvent extends ConnectionPoolMonitoringEvent
194
208
  error?: MongoError;
195
209
  /** @internal */
196
210
  name = CONNECTION_CHECK_OUT_FAILED;
211
+ /**
212
+ * The time it took to check out the connection.
213
+ * More specifically, the time elapsed between
214
+ * emitting a `ConnectionCheckOutStartedEvent`
215
+ * and emitting this event as part of the same check out.
216
+ */
217
+ durationMS: number;
197
218
 
198
219
  /** @internal */
199
220
  constructor(
200
221
  pool: ConnectionPool,
201
222
  reason: 'poolClosed' | 'timeout' | 'connectionError',
223
+ checkoutTime: number,
202
224
  error?: MongoError
203
225
  ) {
204
226
  super(pool);
227
+ this.durationMS = now() - checkoutTime;
205
228
  this.reason = reason;
206
229
  this.error = error;
207
230
  }
@@ -217,10 +240,19 @@ export class ConnectionCheckedOutEvent extends ConnectionPoolMonitoringEvent {
217
240
  connectionId: number | '<monitor>';
218
241
  /** @internal */
219
242
  name = CONNECTION_CHECKED_OUT;
243
+ /**
244
+ * The time it took to check out the connection.
245
+ * More specifically, the time elapsed between
246
+ * emitting a `ConnectionCheckOutStartedEvent`
247
+ * and emitting this event as part of the same checking out.
248
+ *
249
+ */
250
+ durationMS: number;
220
251
 
221
252
  /** @internal */
222
- constructor(pool: ConnectionPool, connection: Connection) {
253
+ constructor(pool: ConnectionPool, connection: Connection, checkoutTime: number) {
223
254
  super(pool);
255
+ this.durationMS = now() - checkoutTime;
224
256
  this.connectionId = connection.id;
225
257
  }
226
258
  }
@@ -6,7 +6,7 @@ import { MongoInvalidArgumentError } from '../../error';
6
6
  import type { MongoOptions } from '../../mongo_client';
7
7
  import { fileIsAccessible } from '../../utils';
8
8
 
9
- // eslint-disable-next-line @typescript-eslint/no-var-requires
9
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
10
10
  const NODE_DRIVER_VERSION = require('../../../package.json').version;
11
11
 
12
12
  /**
@@ -1,7 +1,7 @@
1
- export const MIN_SUPPORTED_SERVER_VERSION = '3.6';
2
- export const MAX_SUPPORTED_SERVER_VERSION = '7.0';
3
- export const MIN_SUPPORTED_WIRE_VERSION = 6;
4
- export const MAX_SUPPORTED_WIRE_VERSION = 21;
1
+ export const MIN_SUPPORTED_SERVER_VERSION = '4.0';
2
+ export const MAX_SUPPORTED_SERVER_VERSION = '8.0';
3
+ export const MIN_SUPPORTED_WIRE_VERSION = 7;
4
+ export const MAX_SUPPORTED_WIRE_VERSION = 25;
5
5
  export const MIN_SUPPORTED_QE_WIRE_VERSION = 21;
6
6
  export const MIN_SUPPORTED_QE_SERVER_VERSION = '7.0';
7
7
  export const OP_REPLY = 1;
@@ -1,6 +1,5 @@
1
1
  import { MongoInvalidArgumentError } from '../../error';
2
- import type { ReadPreferenceLike } from '../../read_preference';
3
- import { ReadPreference } from '../../read_preference';
2
+ import { ReadPreference, type ReadPreferenceLike } from '../../read_preference';
4
3
  import { ServerType } from '../../sdam/common';
5
4
  import type { Server } from '../../sdam/server';
6
5
  import type { ServerDescription } from '../../sdam/server_description';
package/src/collection.ts CHANGED
@@ -47,17 +47,18 @@ import {
47
47
  FindOneAndUpdateOperation,
48
48
  type FindOneAndUpdateOptions
49
49
  } from './operations/find_and_modify';
50
- import type {
51
- CreateIndexesOptions,
52
- DropIndexesOptions,
53
- IndexDescription,
54
- IndexDescriptionCompact,
55
- IndexDescriptionInfo,
56
- IndexInformationOptions,
57
- IndexSpecification,
58
- ListIndexesOptions
50
+ import {
51
+ CreateIndexesOperation,
52
+ type CreateIndexesOptions,
53
+ type DropIndexesOptions,
54
+ DropIndexOperation,
55
+ type IndexDescription,
56
+ type IndexDescriptionCompact,
57
+ type IndexDescriptionInfo,
58
+ type IndexInformationOptions,
59
+ type IndexSpecification,
60
+ type ListIndexesOptions
59
61
  } from './operations/indexes';
60
- import { CreateIndexesOperation, DropIndexOperation } from './operations/indexes';
61
62
  import {
62
63
  InsertManyOperation,
63
64
  type InsertManyResult,
@@ -292,7 +293,7 @@ export class Collection<TSchema extends Document = Document> {
292
293
  * @param options - Optional settings for the command
293
294
  */
294
295
  async insertMany(
295
- docs: OptionalUnlessRequiredId<TSchema>[],
296
+ docs: ReadonlyArray<OptionalUnlessRequiredId<TSchema>>,
296
297
  options?: BulkWriteOptions
297
298
  ): Promise<InsertManyResult<TSchema>> {
298
299
  return await executeOperation(
@@ -325,7 +326,7 @@ export class Collection<TSchema extends Document = Document> {
325
326
  * @throws MongoDriverError if operations is not an array
326
327
  */
327
328
  async bulkWrite(
328
- operations: AnyBulkWriteOperation<TSchema>[],
329
+ operations: ReadonlyArray<AnyBulkWriteOperation<TSchema>>,
329
330
  options?: BulkWriteOptions
330
331
  ): Promise<BulkWriteResult> {
331
332
  if (!Array.isArray(operations)) {
@@ -336,7 +337,7 @@ export class Collection<TSchema extends Document = Document> {
336
337
  this.client,
337
338
  new BulkWriteOperation(
338
339
  this as TODO_NODE_3286,
339
- operations as TODO_NODE_3286,
340
+ operations,
340
341
  resolveOptions(this, options ?? { ordered: true })
341
342
  )
342
343
  );
@@ -1121,8 +1122,8 @@ export class Collection<TSchema extends Document = Document> {
1121
1122
  indexNameOrOptions == null
1122
1123
  ? null
1123
1124
  : typeof indexNameOrOptions === 'object'
1124
- ? null
1125
- : indexNameOrOptions;
1125
+ ? null
1126
+ : indexNameOrOptions;
1126
1127
 
1127
1128
  return new ListSearchIndexesCursor(this as TODO_NODE_3286, indexName, options);
1128
1129
  }
@@ -73,7 +73,7 @@ export async function resolveSRVRecord(options: MongoOptions): Promise<HostAddre
73
73
  // the SRV record is resolved before starting a second DNS query.
74
74
  const lookupAddress = options.srvHost;
75
75
  const txtResolutionPromise = dns.promises.resolveTxt(lookupAddress);
76
- // eslint-disable-next-line github/no-then
76
+
77
77
  txtResolutionPromise.then(undefined, squashError); // rejections will be handled later
78
78
 
79
79
  // Resolve the SRV record and use the result as the list of hosts to connect to.
@@ -552,7 +552,6 @@ export function parseOptions(
552
552
 
553
553
  mongoOptions.metadata = makeClientMetadata(mongoOptions);
554
554
 
555
- // eslint-disable-next-line github/no-then
556
555
  mongoOptions.extendedMetadata = addContainerMetadata(mongoOptions.metadata).then(
557
556
  undefined,
558
557
  squashError
@@ -740,6 +739,13 @@ export const OPTIONS = {
740
739
  autoEncryption: {
741
740
  type: 'record'
742
741
  },
742
+ autoSelectFamily: {
743
+ type: 'boolean',
744
+ default: true
745
+ },
746
+ autoSelectFamilyAttemptTimeout: {
747
+ type: 'uint'
748
+ },
743
749
  bsonRegExp: {
744
750
  type: 'boolean'
745
751
  },
@@ -1222,7 +1228,8 @@ export const OPTIONS = {
1222
1228
  // Custom types for modifying core behavior
1223
1229
  connectionType: { type: 'any' },
1224
1230
  srvPoller: { type: 'any' },
1225
- // Accepted NodeJS Options
1231
+ // Accepted Node.js Options
1232
+ allowPartialTrustChain: { type: 'any' },
1226
1233
  minDHSize: { type: 'any' },
1227
1234
  pskCallback: { type: 'any' },
1228
1235
  secureContext: { type: 'any' },
package/src/constants.ts CHANGED
@@ -1,3 +1,4 @@
1
+ /* eslint-disable @typescript-eslint/no-unnecessary-type-assertion */
1
2
  export const SYSTEM_NAMESPACE_COLLECTION = 'system.namespaces';
2
3
  export const SYSTEM_INDEX_COLLECTION = 'system.indexes';
3
4
  export const SYSTEM_PROFILE_COLLECTION = 'system.profile';
@@ -18,6 +18,7 @@ import { GetMoreOperation } from '../operations/get_more';
18
18
  import { KillCursorsOperation } from '../operations/kill_cursors';
19
19
  import { ReadConcern, type ReadConcernLike } from '../read_concern';
20
20
  import { ReadPreference, type ReadPreferenceLike } from '../read_preference';
21
+ import { type AsyncDisposable, configureResourceManagement } from '../resource_management';
21
22
  import type { Server } from '../sdam/server';
22
23
  import { ClientSession, maybeClearPinnedConnection } from '../sessions';
23
24
  import { type MongoDBNamespace, squashError } from '../utils';
@@ -125,9 +126,12 @@ export type AbstractCursorEvents = {
125
126
 
126
127
  /** @public */
127
128
  export abstract class AbstractCursor<
128
- TSchema = any,
129
- CursorEvents extends AbstractCursorEvents = AbstractCursorEvents
130
- > extends TypedEventEmitter<CursorEvents> {
129
+ TSchema = any,
130
+ CursorEvents extends AbstractCursorEvents = AbstractCursorEvents
131
+ >
132
+ extends TypedEventEmitter<CursorEvents>
133
+ implements AsyncDisposable
134
+ {
131
135
  /** @internal */
132
136
  private cursorId: Long | null;
133
137
  /** @internal */
@@ -286,14 +290,25 @@ export abstract class AbstractCursor<
286
290
  return !!this.cursorClient.topology?.loadBalanced;
287
291
  }
288
292
 
293
+ /**
294
+ * @beta
295
+ * @experimental
296
+ * An alias for {@link AbstractCursor.close|AbstractCursor.close()}.
297
+ */
298
+ declare [Symbol.asyncDispose]: () => Promise<void>;
299
+ /** @internal */
300
+ async asyncDispose() {
301
+ await this.close();
302
+ }
303
+
289
304
  /** Returns current buffered documents length */
290
305
  bufferedCount(): number {
291
306
  return this.documents?.length ?? 0;
292
307
  }
293
308
 
294
309
  /** Returns current buffered documents */
295
- readBufferedDocuments(number?: number): TSchema[] {
296
- const bufferedDocs: TSchema[] = [];
310
+ readBufferedDocuments(number?: number): NonNullable<TSchema>[] {
311
+ const bufferedDocs: NonNullable<TSchema>[] = [];
297
312
  const documentsToRead = Math.min(
298
313
  number ?? this.documents?.length ?? 0,
299
314
  this.documents?.length ?? 0
@@ -308,6 +323,7 @@ export abstract class AbstractCursor<
308
323
 
309
324
  return bufferedDocs;
310
325
  }
326
+
311
327
  async *[Symbol.asyncIterator](): AsyncGenerator<TSchema, void, void> {
312
328
  if (this.closed) {
313
329
  return;
@@ -457,6 +473,9 @@ export abstract class AbstractCursor<
457
473
  }
458
474
  }
459
475
 
476
+ /**
477
+ * Frees any client-side resources used by the cursor.
478
+ */
460
479
  async close(): Promise<void> {
461
480
  await this.cleanup();
462
481
  }
@@ -468,13 +487,22 @@ export abstract class AbstractCursor<
468
487
  * cursor.rewind() can be used to reset the cursor.
469
488
  */
470
489
  async toArray(): Promise<TSchema[]> {
471
- const array = [];
490
+ const array: TSchema[] = [];
491
+ // at the end of the loop (since readBufferedDocuments is called) the buffer will be empty
492
+ // then, the 'await of' syntax will run a getMore call
472
493
  for await (const document of this) {
473
494
  array.push(document);
495
+ const docs = this.readBufferedDocuments();
496
+ if (this.transform != null) {
497
+ for (const doc of docs) {
498
+ array.push(await this.transformDocument(doc));
499
+ }
500
+ } else {
501
+ array.push(...docs);
502
+ }
474
503
  }
475
504
  return array;
476
505
  }
477
-
478
506
  /**
479
507
  * Add a cursor flag to the cursor
480
508
  *
@@ -639,7 +667,6 @@ export abstract class AbstractCursor<
639
667
  // We only want to end this session if we created it, and it hasn't ended yet
640
668
  if (session.explicit === false) {
641
669
  if (!session.hasEnded) {
642
- // eslint-disable-next-line github/no-then
643
670
  session.endSession().then(undefined, squashError);
644
671
  }
645
672
  this.cursorSession = this.cursorClient.startSession({ owner: this, explicit: false });
@@ -815,7 +842,7 @@ export abstract class AbstractCursor<
815
842
  }
816
843
 
817
844
  /** @internal */
818
- private async transformDocument(document: NonNullable<TSchema>): Promise<TSchema> {
845
+ private async transformDocument(document: NonNullable<TSchema>): Promise<NonNullable<TSchema>> {
819
846
  if (this.transform == null) return document;
820
847
 
821
848
  try {
@@ -865,7 +892,6 @@ class ReadableCursorStream extends Readable {
865
892
  }
866
893
 
867
894
  override _destroy(error: Error | null, callback: (error?: Error | null) => void): void {
868
- // eslint-disable-next-line github/no-then
869
895
  this._cursor.close().then(
870
896
  () => callback(error),
871
897
  closeError => callback(closeError)
@@ -878,13 +904,11 @@ class ReadableCursorStream extends Readable {
878
904
  return;
879
905
  }
880
906
 
881
- // eslint-disable-next-line github/no-then
882
907
  this._cursor.next().then(
883
908
  result => {
884
909
  if (result == null) {
885
910
  this.push(null);
886
911
  } else if (this.destroyed) {
887
- // eslint-disable-next-line github/no-then
888
912
  this._cursor.close().then(undefined, squashError);
889
913
  } else {
890
914
  if (this.push(result)) {
@@ -900,7 +924,6 @@ class ReadableCursorStream extends Readable {
900
924
  // a client during iteration. Alternatively, we could do the "right" thing and
901
925
  // propagate the error message by removing this special case.
902
926
  if (err.message.match(/server is closed/)) {
903
- // eslint-disable-next-line github/no-then
904
927
  this._cursor.close().then(undefined, squashError);
905
928
  return this.push(null);
906
929
  }
@@ -927,3 +950,5 @@ class ReadableCursorStream extends Readable {
927
950
  );
928
951
  }
929
952
  }
953
+
954
+ configureResourceManagement(AbstractCursor.prototype);
@@ -1,14 +1,16 @@
1
1
  import type { Document } from '../bson';
2
- import type { ExplainVerbosityLike } from '../explain';
2
+ import type { ExplainCommandOptions, ExplainVerbosityLike } from '../explain';
3
3
  import type { MongoClient } from '../mongo_client';
4
4
  import { AggregateOperation, type AggregateOptions } from '../operations/aggregate';
5
5
  import { executeOperation } from '../operations/execute_operation';
6
6
  import type { ClientSession } from '../sessions';
7
7
  import type { Sort } from '../sort';
8
- import type { MongoDBNamespace } from '../utils';
9
- import { mergeOptions } from '../utils';
10
- import type { AbstractCursorOptions, InitialCursorResponse } from './abstract_cursor';
11
- import { AbstractCursor } from './abstract_cursor';
8
+ import { mergeOptions, type MongoDBNamespace } from '../utils';
9
+ import {
10
+ AbstractCursor,
11
+ type AbstractCursorOptions,
12
+ type InitialCursorResponse
13
+ } from './abstract_cursor';
12
14
 
13
15
  /** @public */
14
16
  export interface AggregationCursorOptions extends AbstractCursorOptions, AggregateOptions {}
@@ -64,7 +66,7 @@ export class AggregationCursor<TSchema = any> extends AbstractCursor<TSchema> {
64
66
  }
65
67
 
66
68
  /** Execute the explain for the cursor */
67
- async explain(verbosity?: ExplainVerbosityLike): Promise<Document> {
69
+ async explain(verbosity?: ExplainVerbosityLike | ExplainCommandOptions): Promise<Document> {
68
70
  return (
69
71
  await executeOperation(
70
72
  this.client,
@@ -1,7 +1,7 @@
1
1
  import { type Document } from '../bson';
2
2
  import { CursorResponse } from '../cmap/wire_protocol/responses';
3
3
  import { MongoInvalidArgumentError, MongoTailableCursorError } from '../error';
4
- import { type ExplainVerbosityLike } from '../explain';
4
+ import { type ExplainCommandOptions, type ExplainVerbosityLike } from '../explain';
5
5
  import type { MongoClient } from '../mongo_client';
6
6
  import type { CollationOptions } from '../operations/command';
7
7
  import { CountOperation, type CountOptions } from '../operations/count';
@@ -133,7 +133,7 @@ export class FindCursor<TSchema = any> extends AbstractCursor<TSchema> {
133
133
  }
134
134
 
135
135
  /** Execute the explain for the cursor */
136
- async explain(verbosity?: ExplainVerbosityLike): Promise<Document> {
136
+ async explain(verbosity?: ExplainVerbosityLike | ExplainCommandOptions): Promise<Document> {
137
137
  return (
138
138
  await executeOperation(
139
139
  this.client,
package/src/db.ts CHANGED
@@ -279,7 +279,7 @@ export class Db {
279
279
  }
280
280
 
281
281
  /**
282
- * Execute an aggregation framework pipeline against the database, needs MongoDB \>= 3.6
282
+ * Execute an aggregation framework pipeline against the database.
283
283
  *
284
284
  * @param pipeline - An array of aggregation stages to be executed
285
285
  * @param options - Optional settings for the command
package/src/deps.ts CHANGED
@@ -1,4 +1,3 @@
1
- /* eslint-disable @typescript-eslint/no-var-requires */
2
1
  import { type Stream } from './cmap/connect';
3
2
  import { MongoMissingDependencyError } from './error';
4
3
  import type { Callback } from './utils';
@@ -24,6 +23,7 @@ export function getKerberos(): Kerberos {
24
23
  let kerberos: Kerberos;
25
24
  try {
26
25
  // Ensure you always wrap an optional require in the try block NODE-3199
26
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
27
27
  kerberos = require('kerberos');
28
28
  } catch (error) {
29
29
  kerberos = makeErrorModule(
@@ -63,6 +63,7 @@ export type ZStandard = ZStandardLib | { kModuleError: MongoMissingDependencyErr
63
63
  export function getZstdLibrary(): ZStandardLib | { kModuleError: MongoMissingDependencyError } {
64
64
  let ZStandard: ZStandardLib | { kModuleError: MongoMissingDependencyError };
65
65
  try {
66
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
66
67
  ZStandard = require('@mongodb-js/zstd');
67
68
  } catch (error) {
68
69
  ZStandard = makeErrorModule(
@@ -101,6 +102,7 @@ export function getAwsCredentialProvider():
101
102
  | { kModuleError: MongoMissingDependencyError } {
102
103
  try {
103
104
  // Ensure you always wrap an optional require in the try block NODE-3199
105
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
104
106
  const credentialProvider = require('@aws-sdk/credential-providers');
105
107
  return credentialProvider;
106
108
  } catch (error) {
@@ -122,6 +124,7 @@ export type GcpMetadata =
122
124
  export function getGcpMetadata(): GcpMetadata {
123
125
  try {
124
126
  // Ensure you always wrap an optional require in the try block NODE-3199
127
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
125
128
  const credentialProvider = require('gcp-metadata');
126
129
  return credentialProvider;
127
130
  } catch (error) {
@@ -153,6 +156,7 @@ export type SnappyLib = {
153
156
  export function getSnappy(): SnappyLib | { kModuleError: MongoMissingDependencyError } {
154
157
  try {
155
158
  // Ensure you always wrap an optional require in the try block NODE-3199
159
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
156
160
  const value = require('snappy');
157
161
  return value;
158
162
  } catch (error) {
@@ -187,6 +191,7 @@ export type SocksLib = {
187
191
  export function getSocks(): SocksLib | { kModuleError: MongoMissingDependencyError } {
188
192
  try {
189
193
  // Ensure you always wrap an optional require in the try block NODE-3199
194
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
190
195
  const value = require('socks');
191
196
  return value;
192
197
  } catch (error) {
@@ -244,6 +249,7 @@ export const aws4: AWS4 | { kModuleError: MongoMissingDependencyError } = loadAw
244
249
  function loadAws4() {
245
250
  let aws4: AWS4 | { kModuleError: MongoMissingDependencyError };
246
251
  try {
252
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
247
253
  aws4 = require('aws4');
248
254
  } catch (error) {
249
255
  aws4 = makeErrorModule(
@@ -267,6 +273,7 @@ export function getMongoDBClientEncryption():
267
273
  // NOTE(NODE-3199): Ensure you always wrap an optional require literally in the try block
268
274
  // Cannot be moved to helper utility function, bundlers search and replace the actual require call
269
275
  // in a way that makes this line throw at bundle time, not runtime, catching here will make bundling succeed
276
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
270
277
  mongodbClientEncryption = require('mongodb-client-encryption');
271
278
  } catch (error) {
272
279
  const kModuleError = new MongoMissingDependencyError(
package/src/error.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { Document } from './bson';
2
+ import type { ServerType } from './sdam/common';
2
3
  import type { TopologyVersion } from './sdam/server_description';
3
4
  import type { TopologyDescription } from './sdam/topology_description';
4
5
 
@@ -1158,6 +1159,23 @@ export class MongoServerSelectionError extends MongoSystemError {
1158
1159
  }
1159
1160
  }
1160
1161
 
1162
+ /**
1163
+ * The type of the result property of MongoWriteConcernError
1164
+ * @public
1165
+ */
1166
+ export interface WriteConcernErrorResult {
1167
+ writeConcernError: {
1168
+ code: number;
1169
+ errmsg: string;
1170
+ codeName?: string;
1171
+ errInfo?: Document;
1172
+ };
1173
+ ok: number;
1174
+ code?: number;
1175
+ errorLabels?: string[];
1176
+ [x: string | number]: unknown;
1177
+ }
1178
+
1161
1179
  /**
1162
1180
  * An error thrown when the server reports a writeConcernError
1163
1181
  * @public
@@ -1178,16 +1196,8 @@ export class MongoWriteConcernError extends MongoServerError {
1178
1196
  *
1179
1197
  * @public
1180
1198
  **/
1181
- constructor(result: {
1182
- writeConcernError: {
1183
- code: number;
1184
- errmsg: string;
1185
- codeName?: string;
1186
- errInfo?: Document;
1187
- };
1188
- errorLabels?: string[];
1189
- }) {
1190
- super({ ...result, ...result.writeConcernError });
1199
+ constructor(result: WriteConcernErrorResult) {
1200
+ super({ ...result.writeConcernError, ...result });
1191
1201
  this.errInfo = result.writeConcernError.errInfo;
1192
1202
  this.result = result;
1193
1203
  }
@@ -1217,7 +1227,11 @@ const RETRYABLE_READ_ERROR_CODES = new Set<number>([
1217
1227
  // see: https://github.com/mongodb/specifications/blob/master/source/retryable-writes/retryable-writes.rst#terms
1218
1228
  const RETRYABLE_WRITE_ERROR_CODES = RETRYABLE_READ_ERROR_CODES;
1219
1229
 
1220
- export function needsRetryableWriteLabel(error: Error, maxWireVersion: number): boolean {
1230
+ export function needsRetryableWriteLabel(
1231
+ error: Error,
1232
+ maxWireVersion: number,
1233
+ serverType: ServerType
1234
+ ): boolean {
1221
1235
  // pre-4.4 server, then the driver adds an error label for every valid case
1222
1236
  // execute operation will only inspect the label, code/message logic is handled here
1223
1237
  if (error instanceof MongoNetworkError) {
@@ -1237,11 +1251,16 @@ export function needsRetryableWriteLabel(error: Error, maxWireVersion: number):
1237
1251
  }
1238
1252
 
1239
1253
  if (error instanceof MongoWriteConcernError) {
1240
- return RETRYABLE_WRITE_ERROR_CODES.has(error.result?.code ?? error.code ?? 0);
1254
+ if (serverType === 'Mongos' && maxWireVersion < 9) {
1255
+ // use original top-level code from server response
1256
+ return RETRYABLE_WRITE_ERROR_CODES.has(error.result.code ?? 0);
1257
+ }
1258
+ const code = error.result.writeConcernError.code ?? Number(error.code);
1259
+ return RETRYABLE_WRITE_ERROR_CODES.has(Number.isNaN(code) ? 0 : code);
1241
1260
  }
1242
1261
 
1243
- if (error instanceof MongoError && typeof error.code === 'number') {
1244
- return RETRYABLE_WRITE_ERROR_CODES.has(error.code);
1262
+ if (error instanceof MongoError) {
1263
+ return RETRYABLE_WRITE_ERROR_CODES.has(Number(error.code));
1245
1264
  }
1246
1265
 
1247
1266
  const isNotWritablePrimaryError = LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE.test(error.message);
package/src/explain.ts CHANGED
@@ -1,5 +1,3 @@
1
- import { MongoInvalidArgumentError } from './error';
2
-
3
1
  /** @public */
4
2
  export const ExplainVerbosity = Object.freeze({
5
3
  queryPlanner: 'queryPlanner',
@@ -13,23 +11,59 @@ export type ExplainVerbosity = string;
13
11
 
14
12
  /**
15
13
  * For backwards compatibility, true is interpreted as "allPlansExecution"
16
- * and false as "queryPlanner". Prior to server version 3.6, aggregate()
17
- * ignores the verbosity parameter and executes in "queryPlanner".
14
+ * and false as "queryPlanner".
18
15
  * @public
19
16
  */
20
17
  export type ExplainVerbosityLike = ExplainVerbosity | boolean;
21
18
 
22
19
  /** @public */
20
+ export interface ExplainCommandOptions {
21
+ /** The explain verbosity for the command. */
22
+ verbosity: ExplainVerbosity;
23
+ /** The maxTimeMS setting for the command. */
24
+ maxTimeMS?: number;
25
+ }
26
+
27
+ /**
28
+ * @public
29
+ *
30
+ * When set, this configures an explain command. Valid values are boolean (for legacy compatibility,
31
+ * see {@link ExplainVerbosityLike}), a string containing the explain verbosity, or an object containing the verbosity and
32
+ * an optional maxTimeMS.
33
+ *
34
+ * Examples of valid usage:
35
+ *
36
+ * ```typescript
37
+ * collection.find({ name: 'john doe' }, { explain: true });
38
+ * collection.find({ name: 'john doe' }, { explain: false });
39
+ * collection.find({ name: 'john doe' }, { explain: 'queryPlanner' });
40
+ * collection.find({ name: 'john doe' }, { explain: { verbosity: 'queryPlanner' } });
41
+ * ```
42
+ *
43
+ * maxTimeMS can be configured to limit the amount of time the server
44
+ * spends executing an explain by providing an object:
45
+ *
46
+ * ```typescript
47
+ * // limits the `explain` command to no more than 2 seconds
48
+ * collection.find({ name: 'john doe' }, {
49
+ * explain: {
50
+ * verbosity: 'queryPlanner',
51
+ * maxTimeMS: 2000
52
+ * }
53
+ * });
54
+ * ```
55
+ */
23
56
  export interface ExplainOptions {
24
57
  /** Specifies the verbosity mode for the explain output. */
25
- explain?: ExplainVerbosityLike;
58
+ explain?: ExplainVerbosityLike | ExplainCommandOptions;
26
59
  }
27
60
 
28
61
  /** @internal */
29
62
  export class Explain {
30
- verbosity: ExplainVerbosity;
63
+ readonly verbosity: ExplainVerbosity;
64
+ readonly maxTimeMS?: number;
31
65
 
32
- constructor(verbosity: ExplainVerbosityLike) {
66
+ private constructor(verbosity: ExplainVerbosityLike, maxTimeMS?: number) {
33
67
  if (typeof verbosity === 'boolean') {
34
68
  this.verbosity = verbosity
35
69
  ? ExplainVerbosity.allPlansExecution
@@ -37,16 +71,18 @@ export class Explain {
37
71
  } else {
38
72
  this.verbosity = verbosity;
39
73
  }
74
+
75
+ this.maxTimeMS = maxTimeMS;
40
76
  }
41
77
 
42
- static fromOptions(options?: ExplainOptions): Explain | undefined {
43
- if (options?.explain == null) return;
78
+ static fromOptions({ explain }: ExplainOptions = {}): Explain | undefined {
79
+ if (explain == null) return;
44
80
 
45
- const explain = options.explain;
46
81
  if (typeof explain === 'boolean' || typeof explain === 'string') {
47
82
  return new Explain(explain);
48
83
  }
49
84
 
50
- throw new MongoInvalidArgumentError('Field "explain" must be a string or a boolean');
85
+ const { verbosity, maxTimeMS } = explain;
86
+ return new Explain(verbosity, maxTimeMS);
51
87
  }
52
88
  }