mongodb 6.8.2 → 6.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (242) hide show
  1. package/README.md +14 -1
  2. package/lib/beta.d.ts +7905 -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.map +1 -1
  36. package/lib/cmap/auth/mongocr.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 +2 -2
  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 +1 -1
  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.map +1 -1
  100. package/lib/gridfs/download.js +1 -4
  101. package/lib/gridfs/download.js.map +1 -1
  102. package/lib/gridfs/index.js +1 -1
  103. package/lib/gridfs/index.js.map +1 -1
  104. package/lib/gridfs/upload.js +0 -4
  105. package/lib/gridfs/upload.js.map +1 -1
  106. package/lib/index.js +4 -2
  107. package/lib/index.js.map +1 -1
  108. package/lib/mongo_client.js +15 -1
  109. package/lib/mongo_client.js.map +1 -1
  110. package/lib/mongo_client_auth_providers.js.map +1 -1
  111. package/lib/mongo_logger.js +8 -8
  112. package/lib/mongo_logger.js.map +1 -1
  113. package/lib/mongo_types.js +1 -0
  114. package/lib/mongo_types.js.map +1 -1
  115. package/lib/operations/aggregate.js +1 -0
  116. package/lib/operations/aggregate.js.map +1 -1
  117. package/lib/operations/bulk_write.js.map +1 -1
  118. package/lib/operations/client_bulk_write/command_builder.js +198 -0
  119. package/lib/operations/client_bulk_write/command_builder.js.map +1 -0
  120. package/lib/operations/client_bulk_write/common.js +3 -0
  121. package/lib/operations/client_bulk_write/common.js.map +1 -0
  122. package/lib/operations/collections.js.map +1 -1
  123. package/lib/operations/command.js +1 -1
  124. package/lib/operations/command.js.map +1 -1
  125. package/lib/operations/count.js.map +1 -1
  126. package/lib/operations/create_collection.js.map +1 -1
  127. package/lib/operations/delete.js +2 -2
  128. package/lib/operations/delete.js.map +1 -1
  129. package/lib/operations/distinct.js.map +1 -1
  130. package/lib/operations/drop.js.map +1 -1
  131. package/lib/operations/estimated_document_count.js.map +1 -1
  132. package/lib/operations/execute_operation.js +111 -109
  133. package/lib/operations/execute_operation.js.map +1 -1
  134. package/lib/operations/find.js.map +1 -1
  135. package/lib/operations/find_and_modify.js +2 -8
  136. package/lib/operations/find_and_modify.js.map +1 -1
  137. package/lib/operations/get_more.js.map +1 -1
  138. package/lib/operations/indexes.js.map +1 -1
  139. package/lib/operations/insert.js.map +1 -1
  140. package/lib/operations/is_capped.js.map +1 -1
  141. package/lib/operations/kill_cursors.js.map +1 -1
  142. package/lib/operations/list_collections.js.map +1 -1
  143. package/lib/operations/list_databases.js.map +1 -1
  144. package/lib/operations/operation.js +5 -5
  145. package/lib/operations/operation.js.map +1 -1
  146. package/lib/operations/options_operation.js.map +1 -1
  147. package/lib/operations/profiling_level.js.map +1 -1
  148. package/lib/operations/search_indexes/drop.js.map +1 -1
  149. package/lib/operations/set_profiling_level.js.map +1 -1
  150. package/lib/operations/stats.js.map +1 -1
  151. package/lib/operations/update.js +2 -2
  152. package/lib/operations/update.js.map +1 -1
  153. package/lib/operations/validate_collection.js.map +1 -1
  154. package/lib/read_concern.js.map +1 -1
  155. package/lib/read_preference.js +1 -1
  156. package/lib/read_preference.js.map +1 -1
  157. package/lib/resource_management.js +58 -0
  158. package/lib/resource_management.js.map +1 -0
  159. package/lib/sdam/common.js +3 -3
  160. package/lib/sdam/common.js.map +1 -1
  161. package/lib/sdam/monitor.js +1 -5
  162. package/lib/sdam/monitor.js.map +1 -1
  163. package/lib/sdam/server.js +2 -2
  164. package/lib/sdam/server.js.map +1 -1
  165. package/lib/sdam/server_description.js +3 -3
  166. package/lib/sdam/server_description.js.map +1 -1
  167. package/lib/sdam/server_selection.js +5 -5
  168. package/lib/sdam/server_selection.js.map +1 -1
  169. package/lib/sdam/srv_polling.js +2 -3
  170. package/lib/sdam/srv_polling.js.map +1 -1
  171. package/lib/sdam/topology.js +1 -1
  172. package/lib/sdam/topology.js.map +1 -1
  173. package/lib/sdam/topology_description.js.map +1 -1
  174. package/lib/sessions.js +221 -218
  175. package/lib/sessions.js.map +1 -1
  176. package/lib/sort.js +2 -3
  177. package/lib/sort.js.map +1 -1
  178. package/lib/timeout.js +0 -1
  179. package/lib/timeout.js.map +1 -1
  180. package/lib/transactions.js +2 -2
  181. package/lib/transactions.js.map +1 -1
  182. package/lib/utils.js +49 -51
  183. package/lib/utils.js.map +1 -1
  184. package/lib/write_concern.js +2 -2
  185. package/lib/write_concern.js.map +1 -1
  186. package/mongodb.d.ts +150 -142
  187. package/package.json +26 -27
  188. package/src/beta.ts +22 -0
  189. package/src/bson.ts +1 -2
  190. package/src/bulk/common.ts +18 -18
  191. package/src/change_stream.ts +33 -15
  192. package/src/client-side-encryption/auto_encrypter.ts +18 -82
  193. package/src/client-side-encryption/client_encryption.ts +51 -54
  194. package/src/client-side-encryption/mongocryptd_manager.ts +10 -6
  195. package/src/client-side-encryption/state_machine.ts +28 -6
  196. package/src/cmap/auth/gssapi.ts +1 -1
  197. package/src/cmap/auth/mongodb_aws.ts +2 -2
  198. package/src/cmap/auth/mongodb_oidc/callback_workflow.ts +2 -2
  199. package/src/cmap/auth/mongodb_oidc/machine_workflow.ts +2 -2
  200. package/src/cmap/commands.ts +70 -5
  201. package/src/cmap/connect.ts +4 -1
  202. package/src/cmap/connection.ts +2 -2
  203. package/src/cmap/connection_pool.ts +17 -9
  204. package/src/cmap/connection_pool_events.ts +34 -2
  205. package/src/cmap/handshake/client_metadata.ts +1 -1
  206. package/src/cmap/wire_protocol/constants.ts +2 -2
  207. package/src/cmap/wire_protocol/shared.ts +1 -2
  208. package/src/collection.ts +16 -15
  209. package/src/connection_string.ts +10 -3
  210. package/src/constants.ts +1 -0
  211. package/src/cursor/abstract_cursor.ts +38 -13
  212. package/src/cursor/aggregation_cursor.ts +6 -4
  213. package/src/deps.ts +8 -1
  214. package/src/error.ts +33 -14
  215. package/src/gridfs/download.ts +28 -4
  216. package/src/gridfs/upload.ts +1 -6
  217. package/src/index.ts +5 -1
  218. package/src/mongo_client.ts +29 -5
  219. package/src/mongo_logger.ts +5 -3
  220. package/src/mongo_types.ts +69 -68
  221. package/src/operations/aggregate.ts +2 -1
  222. package/src/operations/bulk_write.ts +2 -2
  223. package/src/operations/client_bulk_write/command_builder.ts +283 -0
  224. package/src/operations/client_bulk_write/common.ts +146 -0
  225. package/src/operations/command.ts +1 -1
  226. package/src/operations/execute_operation.ts +137 -131
  227. package/src/operations/find_and_modify.ts +2 -7
  228. package/src/operations/insert.ts +3 -4
  229. package/src/operations/operation.ts +7 -10
  230. package/src/operations/search_indexes/drop.ts +4 -1
  231. package/src/resource_management.ts +74 -0
  232. package/src/sdam/monitor.ts +3 -5
  233. package/src/sdam/server.ts +1 -1
  234. package/src/sdam/server_description.ts +5 -6
  235. package/src/sdam/srv_polling.ts +1 -2
  236. package/src/sessions.ts +291 -277
  237. package/src/sort.ts +1 -1
  238. package/src/timeout.ts +0 -1
  239. package/src/transactions.ts +1 -2
  240. package/src/utils.ts +9 -4
  241. package/src/write_concern.ts +2 -2
  242. package/tsconfig.json +2 -1
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);
@@ -56,15 +56,41 @@ export interface GridFSFile {
56
56
 
57
57
  /** @internal */
58
58
  export interface GridFSBucketReadStreamPrivate {
59
+ /**
60
+ * The running total number of bytes read from the chunks collection.
61
+ */
59
62
  bytesRead: number;
63
+ /**
64
+ * The number of bytes to remove from the last chunk read in the file. This is non-zero
65
+ * if `end` is not equal to the length of the document and `end` is not a multiple
66
+ * of the chunkSize.
67
+ */
60
68
  bytesToTrim: number;
69
+
70
+ /**
71
+ * The number of bytes to remove from the first chunk read in the file. This is non-zero
72
+ * if `start` is not equal to the 0 and `start` is not a multiple
73
+ * of the chunkSize.
74
+ */
61
75
  bytesToSkip: number;
76
+
77
+ files: Collection<GridFSFile>;
62
78
  chunks: Collection<GridFSChunk>;
63
79
  cursor?: FindCursor<GridFSChunk>;
80
+
81
+ /** The running total number of chunks read from the chunks collection. */
64
82
  expected: number;
65
- files: Collection<GridFSFile>;
83
+
84
+ /**
85
+ * The filter used to search in the _files_ collection (i.e., `{ _id: <> }`)
86
+ * This is not the same filter used when reading chunks from the chunks collection.
87
+ */
66
88
  filter: Document;
89
+
90
+ /** Indicates whether or not download has started. */
67
91
  init: boolean;
92
+
93
+ /** The expected number of chunks to read, calculated from start, end, chunkSize and file length. */
68
94
  expectedEnd: number;
69
95
  file?: GridFSFile;
70
96
  options: {
@@ -190,7 +216,7 @@ function doRead(stream: GridFSBucketReadStream): void {
190
216
 
191
217
  if (!doc) {
192
218
  stream.push(null);
193
- // eslint-disable-next-line github/no-then
219
+
194
220
  stream.s.cursor?.close().then(undefined, error => stream.destroy(error));
195
221
  return;
196
222
  }
@@ -262,7 +288,6 @@ function doRead(stream: GridFSBucketReadStream): void {
262
288
  return;
263
289
  };
264
290
 
265
- // eslint-disable-next-line github/no-then
266
291
  stream.s.cursor.next().then(handleReadResult, error => {
267
292
  if (stream.destroyed) return;
268
293
  stream.destroy(error);
@@ -346,7 +371,6 @@ function init(stream: GridFSBucketReadStream): void {
346
371
  return;
347
372
  };
348
373
 
349
- // eslint-disable-next-line github/no-then
350
374
  stream.s.files.findOne(stream.s.filter, findOneOptions).then(handleReadResult, error => {
351
375
  if (stream.destroyed) return;
352
376
  stream.destroy(error);
@@ -1,7 +1,6 @@
1
1
  import { Writable } from 'stream';
2
2
 
3
- import type { Document } from '../bson';
4
- import { ObjectId } from '../bson';
3
+ import { type Document, ObjectId } from '../bson';
5
4
  import type { Collection } from '../collection';
6
5
  import { MongoAPIError, MONGODB_ERROR_CODES, MongoError } from '../error';
7
6
  import { type Callback, squashError } from '../utils';
@@ -135,7 +134,6 @@ export class GridFSBucketWriteStream extends Writable {
135
134
  if (!this.bucket.s.calledOpenUploadStream) {
136
135
  this.bucket.s.calledOpenUploadStream = true;
137
136
 
138
- // eslint-disable-next-line github/no-then
139
137
  checkIndexes(this).then(() => {
140
138
  this.bucket.s.checkedIndexes = true;
141
139
  this.bucket.emit('index');
@@ -272,7 +270,6 @@ function checkDone(stream: GridFSBucketWriteStream, callback: Callback): void {
272
270
  return;
273
271
  }
274
272
 
275
- // eslint-disable-next-line github/no-then
276
273
  stream.files.insertOne(gridFSFile, { writeConcern: stream.writeConcern }).then(
277
274
  () => {
278
275
  stream.gridFSFile = gridFSFile;
@@ -396,7 +393,6 @@ function doWrite(
396
393
  return;
397
394
  }
398
395
 
399
- // eslint-disable-next-line github/no-then
400
396
  stream.chunks.insertOne(doc, { writeConcern: stream.writeConcern }).then(
401
397
  () => {
402
398
  --stream.state.outstandingRequests;
@@ -437,7 +433,6 @@ function writeRemnant(stream: GridFSBucketWriteStream, callback: Callback): void
437
433
  return;
438
434
  }
439
435
 
440
- // eslint-disable-next-line github/no-then
441
436
  stream.chunks.insertOne(doc, { writeConcern: stream.writeConcern }).then(
442
437
  () => {
443
438
  --stream.state.outstandingRequests;
package/src/index.ts CHANGED
@@ -73,8 +73,10 @@ export {
73
73
  MongoTopologyClosedError,
74
74
  MongoTransactionError,
75
75
  MongoUnexpectedServerResponseError,
76
- MongoWriteConcernError
76
+ MongoWriteConcernError,
77
+ WriteConcernErrorResult
77
78
  } from './error';
79
+ export { configureExplicitResourceManagement } from './resource_management';
78
80
  export {
79
81
  AbstractCursor,
80
82
  // Actual driver classes exported
@@ -247,6 +249,7 @@ export type {
247
249
  LocalKMSProviderConfiguration
248
250
  } from './client-side-encryption/providers/index';
249
251
  export type {
252
+ ClientEncryptionSocketOptions,
250
253
  ClientEncryptionTlsOptions,
251
254
  CSFLEKMSTlsOptions,
252
255
  StateMachineExecutable
@@ -524,6 +527,7 @@ export type {
524
527
  ReadPreferenceLikeOptions,
525
528
  ReadPreferenceOptions
526
529
  } from './read_preference';
530
+ export type { AsyncDisposable } from './resource_management';
527
531
  export type { ClusterTime, TimerQueue } from './sdam/common';
528
532
  export type {
529
533
  Monitor,
@@ -34,6 +34,7 @@ import { executeOperation } from './operations/execute_operation';
34
34
  import { RunAdminCommandOperation } from './operations/run_command';
35
35
  import type { ReadConcern, ReadConcernLevel, ReadConcernLike } from './read_concern';
36
36
  import { ReadPreference, type ReadPreferenceMode } from './read_preference';
37
+ import { type AsyncDisposable, configureResourceManagement } from './resource_management';
37
38
  import type { ServerMonitoringMode } from './sdam/monitor';
38
39
  import type { TagSet } from './sdam/server_description';
39
40
  import { readPreferenceServerSelector } from './sdam/server_selection';
@@ -92,8 +93,10 @@ export interface PkFactory {
92
93
 
93
94
  /** @public */
94
95
  export type SupportedTLSConnectionOptions = Pick<
95
- TLSConnectionOptions,
96
- Extract<keyof TLSConnectionOptions, (typeof LEGAL_TLS_SOCKET_OPTIONS)[number]>
96
+ TLSConnectionOptions & {
97
+ allowPartialTrustChain?: boolean;
98
+ },
99
+ (typeof LEGAL_TLS_SOCKET_OPTIONS)[number]
97
100
  >;
98
101
 
99
102
  /** @public */
@@ -104,7 +107,7 @@ export type SupportedTLSSocketOptions = Pick<
104
107
 
105
108
  /** @public */
106
109
  export type SupportedSocketOptions = Pick<
107
- TcpNetConnectOpts,
110
+ TcpNetConnectOpts & { autoSelectFamily?: boolean; autoSelectFamilyAttemptTimeout?: number },
108
111
  (typeof LEGAL_TCP_SOCKET_OPTIONS)[number]
109
112
  >;
110
113
 
@@ -344,7 +347,7 @@ const kOptions = Symbol('options');
344
347
  * await client.insertOne({ name: 'spot', kind: 'dog' });
345
348
  * ```
346
349
  */
347
- export class MongoClient extends TypedEventEmitter<MongoClientEvents> {
350
+ export class MongoClient extends TypedEventEmitter<MongoClientEvents> implements AsyncDisposable {
348
351
  /** @internal */
349
352
  s: MongoClientPrivate;
350
353
  /** @internal */
@@ -404,6 +407,17 @@ export class MongoClient extends TypedEventEmitter<MongoClientEvents> {
404
407
  this.checkForNonGenuineHosts();
405
408
  }
406
409
 
410
+ /**
411
+ * @beta
412
+ * @experimental
413
+ * An alias for {@link MongoClient.close|MongoClient.close()}.
414
+ */
415
+ declare [Symbol.asyncDispose]: () => Promise<void>;
416
+ /** @internal */
417
+ async asyncDispose() {
418
+ await this.close();
419
+ }
420
+
407
421
  /** @internal */
408
422
  private checkForNonGenuineHosts() {
409
423
  const documentDBHostnames = this[kOptions].hosts.filter((hostAddress: HostAddress) =>
@@ -570,7 +584,15 @@ export class MongoClient extends TypedEventEmitter<MongoClientEvents> {
570
584
  }
571
585
 
572
586
  /**
573
- * Close the client and its underlying connections
587
+ * Cleans up client-side resources used by the MongoCLient and . This includes:
588
+ *
589
+ * - Closes all open, unused connections (see note).
590
+ * - Ends all in-use sessions with {@link ClientSession#endSession|ClientSession.endSession()}.
591
+ * - Ends all unused sessions server-side.
592
+ * - Cleans up any resources being used for auto encryption if auto encryption is enabled.
593
+ *
594
+ * @remarks Any in-progress operations are not killed and any connections used by in progress operations
595
+ * will be cleaned up lazily as operations finish.
574
596
  *
575
597
  * @param force - Force close, emitting no events
576
598
  */
@@ -758,6 +780,8 @@ export class MongoClient extends TypedEventEmitter<MongoClientEvents> {
758
780
  }
759
781
  }
760
782
 
783
+ configureResourceManagement(MongoClient.prototype);
784
+
761
785
  /**
762
786
  * Parsed Mongo Client Options.
763
787
  *
@@ -604,6 +604,7 @@ export function defaultLogTransform(
604
604
  log = attachConnectionFields(log, logObject);
605
605
  log.message = 'Connection ready';
606
606
  log.driverConnectionId = logObject.connectionId;
607
+ log.durationMS = logObject.durationMS;
607
608
  return log;
608
609
  case CONNECTION_CLOSED:
609
610
  log = attachConnectionFields(log, logObject);
@@ -653,11 +654,13 @@ export function defaultLogTransform(
653
654
  default:
654
655
  log.reason = `Unknown close reason: ${logObject.reason}`;
655
656
  }
657
+ log.durationMS = logObject.durationMS;
656
658
  return log;
657
659
  case CONNECTION_CHECKED_OUT:
658
660
  log = attachConnectionFields(log, logObject);
659
661
  log.message = 'Connection checked out';
660
662
  log.driverConnectionId = logObject.connectionId;
663
+ log.durationMS = logObject.durationMS;
661
664
  return log;
662
665
  case CONNECTION_CHECKED_IN:
663
666
  log = attachConnectionFields(log, logObject);
@@ -836,9 +839,9 @@ export class MongoLogger {
836
839
 
837
840
  if (isPromiseLike(this.pendingLog)) {
838
841
  this.pendingLog = this.pendingLog
839
- // eslint-disable-next-line github/no-then
842
+
840
843
  .then(() => this.logDestination.write(logMessage))
841
- // eslint-disable-next-line github/no-then
844
+
842
845
  .then(this.clearPendingLog.bind(this), this.logWriteFailureHandler.bind(this));
843
846
  return;
844
847
  }
@@ -846,7 +849,6 @@ export class MongoLogger {
846
849
  try {
847
850
  const logResult = this.logDestination.write(logMessage);
848
851
  if (isPromiseLike(logResult)) {
849
- // eslint-disable-next-line github/no-then
850
852
  this.pendingLog = logResult.then(
851
853
  this.clearPendingLog.bind(this),
852
854
  this.logWriteFailureHandler.bind(this)
@@ -34,11 +34,11 @@ export type InferIdType<TSchema> = TSchema extends { _id: infer IdType }
34
34
  ? never // explicitly forbid empty objects as the type of _id
35
35
  : IdType
36
36
  : TSchema extends { _id?: infer IdType }
37
- ? // optional _id defined - return ObjectId | IdType
38
- unknown extends IdType
39
- ? ObjectId // infer the _id type as ObjectId if the type of _id is unknown
40
- : IdType
41
- : ObjectId; // user has not defined _id on schema
37
+ ? // optional _id defined - return ObjectId | IdType
38
+ unknown extends IdType
39
+ ? ObjectId // infer the _id type as ObjectId if the type of _id is unknown
40
+ : IdType
41
+ : ObjectId; // user has not defined _id on schema
42
42
 
43
43
  /** Add an _id field to an object shaped type @public */
44
44
  export type WithId<TSchema> = EnhancedOmit<TSchema, '_id'> & { _id: InferIdType<TSchema> };
@@ -68,8 +68,8 @@ export type OptionalUnlessRequiredId<TSchema> = TSchema extends { _id: any }
68
68
  export type EnhancedOmit<TRecordOrUnion, KeyUnion> = string extends keyof TRecordOrUnion
69
69
  ? TRecordOrUnion // TRecordOrUnion has indexed type e.g. { _id: string; [k: string]: any; } or it is "any"
70
70
  : TRecordOrUnion extends any
71
- ? Pick<TRecordOrUnion, Exclude<keyof TRecordOrUnion, KeyUnion>> // discriminated unions
72
- : never;
71
+ ? Pick<TRecordOrUnion, Exclude<keyof TRecordOrUnion, KeyUnion>> // discriminated unions
72
+ : never;
73
73
 
74
74
  /** Remove the _id field from an object shaped type @public */
75
75
  export type WithoutId<TSchema> = Omit<TSchema, '_id'>;
@@ -88,9 +88,8 @@ export type Condition<T> = AlternativeType<T> | FilterOperators<AlternativeType<
88
88
  * array types can be searched using their element type
89
89
  * @public
90
90
  */
91
- export type AlternativeType<T> = T extends ReadonlyArray<infer U>
92
- ? T | RegExpOrString<U>
93
- : RegExpOrString<T>;
91
+ export type AlternativeType<T> =
92
+ T extends ReadonlyArray<infer U> ? T | RegExpOrString<U> : RegExpOrString<T>;
94
93
 
95
94
  /** @public */
96
95
  export type RegExpOrString<T> = T extends string ? BSONRegExp | RegExp | T : T;
@@ -192,9 +191,10 @@ export type IntegerType = number | Int32 | Long | bigint;
192
191
  export type NumericType = IntegerType | Decimal128 | Double;
193
192
 
194
193
  /** @public */
195
- export type FilterOperations<T> = T extends Record<string, any>
196
- ? { [key in keyof T]?: FilterOperators<T[key]> }
197
- : FilterOperators<T>;
194
+ export type FilterOperations<T> =
195
+ T extends Record<string, any>
196
+ ? { [key in keyof T]?: FilterOperators<T[key]> }
197
+ : FilterOperators<T>;
198
198
 
199
199
  /** @public */
200
200
  export type KeysOfAType<TSchema, Type> = {
@@ -412,6 +412,7 @@ export declare interface TypedEventEmitter<Events extends EventsDescription> ext
412
412
  * @public
413
413
  */
414
414
 
415
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
415
416
  export class TypedEventEmitter<Events extends EventsDescription> extends EventEmitter {
416
417
  /** @internal */
417
418
  protected mongoLogger?: MongoLogger;
@@ -480,31 +481,31 @@ export class CancellationToken extends TypedEventEmitter<{ cancel(): void }> {}
480
481
  export type Join<T extends unknown[], D extends string> = T extends []
481
482
  ? ''
482
483
  : T extends [string | number]
483
- ? `${T[0]}`
484
- : T extends [string | number, ...infer R]
485
- ? `${T[0]}${D}${Join<R, D>}`
486
- : string;
484
+ ? `${T[0]}`
485
+ : T extends [string | number, ...infer R]
486
+ ? `${T[0]}${D}${Join<R, D>}`
487
+ : string;
487
488
 
488
489
  /** @public */
489
490
  export type PropertyType<Type, Property extends string> = string extends Property
490
491
  ? unknown
491
492
  : Property extends keyof Type
492
- ? Type[Property]
493
- : Property extends `${number}`
494
- ? Type extends ReadonlyArray<infer ArrayType>
495
- ? ArrayType
496
- : unknown
497
- : Property extends `${infer Key}.${infer Rest}`
498
- ? Key extends `${number}`
499
- ? Type extends ReadonlyArray<infer ArrayType>
500
- ? PropertyType<ArrayType, Rest>
501
- : unknown
502
- : Key extends keyof Type
503
- ? Type[Key] extends Map<string, infer MapType>
504
- ? MapType
505
- : PropertyType<Type[Key], Rest>
506
- : unknown
507
- : unknown;
493
+ ? Type[Property]
494
+ : Property extends `${number}`
495
+ ? Type extends ReadonlyArray<infer ArrayType>
496
+ ? ArrayType
497
+ : unknown
498
+ : Property extends `${infer Key}.${infer Rest}`
499
+ ? Key extends `${number}`
500
+ ? Type extends ReadonlyArray<infer ArrayType>
501
+ ? PropertyType<ArrayType, Rest>
502
+ : unknown
503
+ : Key extends keyof Type
504
+ ? Type[Key] extends Map<string, infer MapType>
505
+ ? MapType
506
+ : PropertyType<Type[Key], Rest>
507
+ : unknown
508
+ : unknown;
508
509
 
509
510
  /**
510
511
  * @public
@@ -521,41 +522,41 @@ export type PropertyType<Type, Property extends string> = string extends Propert
521
522
  export type NestedPaths<Type, Depth extends number[]> = Depth['length'] extends 8
522
523
  ? []
523
524
  : Type extends
524
- | string
525
- | number
526
- | bigint
527
- | boolean
528
- | Date
529
- | RegExp
530
- | Buffer
531
- | Uint8Array
532
- | ((...args: any[]) => any)
533
- | { _bsontype: string }
534
- ? []
535
- : Type extends ReadonlyArray<infer ArrayType>
536
- ? [] | [number, ...NestedPaths<ArrayType, [...Depth, 1]>]
537
- : Type extends Map<string, any>
538
- ? [string]
539
- : Type extends object
540
- ? {
541
- [Key in Extract<keyof Type, string>]: Type[Key] extends Type // type of value extends the parent
542
- ? [Key]
543
- : // for a recursive union type, the child will never extend the parent type.
544
- // but the parent will still extend the child
545
- Type extends Type[Key]
546
- ? [Key]
547
- : Type[Key] extends ReadonlyArray<infer ArrayType> // handling recursive types with arrays
548
- ? Type extends ArrayType // is the type of the parent the same as the type of the array?
549
- ? [Key] // yes, it's a recursive array type
550
- : // for unions, the child type extends the parent
551
- ArrayType extends Type
552
- ? [Key] // we have a recursive array union
553
- : // child is an array, but it's not a recursive array
554
- [Key, ...NestedPaths<Type[Key], [...Depth, 1]>]
555
- : // child is not structured the same as the parent
556
- [Key, ...NestedPaths<Type[Key], [...Depth, 1]>] | [Key];
557
- }[Extract<keyof Type, string>]
558
- : [];
525
+ | string
526
+ | number
527
+ | bigint
528
+ | boolean
529
+ | Date
530
+ | RegExp
531
+ | Buffer
532
+ | Uint8Array
533
+ | ((...args: any[]) => any)
534
+ | { _bsontype: string }
535
+ ? []
536
+ : Type extends ReadonlyArray<infer ArrayType>
537
+ ? [] | [number, ...NestedPaths<ArrayType, [...Depth, 1]>]
538
+ : Type extends Map<string, any>
539
+ ? [string]
540
+ : Type extends object
541
+ ? {
542
+ [Key in Extract<keyof Type, string>]: Type[Key] extends Type // type of value extends the parent
543
+ ? [Key]
544
+ : // for a recursive union type, the child will never extend the parent type.
545
+ // but the parent will still extend the child
546
+ Type extends Type[Key]
547
+ ? [Key]
548
+ : Type[Key] extends ReadonlyArray<infer ArrayType> // handling recursive types with arrays
549
+ ? Type extends ArrayType // is the type of the parent the same as the type of the array?
550
+ ? [Key] // yes, it's a recursive array type
551
+ : // for unions, the child type extends the parent
552
+ ArrayType extends Type
553
+ ? [Key] // we have a recursive array union
554
+ : // child is an array, but it's not a recursive array
555
+ [Key, ...NestedPaths<Type[Key], [...Depth, 1]>]
556
+ : // child is not structured the same as the parent
557
+ [Key, ...NestedPaths<Type[Key], [...Depth, 1]>] | [Key];
558
+ }[Extract<keyof Type, string>]
559
+ : [];
559
560
 
560
561
  /**
561
562
  * @public
@@ -9,8 +9,9 @@ import { type CollationOptions, CommandOperation, type CommandOperationOptions }
9
9
  import { Aspect, defineAspects, type Hint } from './operation';
10
10
 
11
11
  /** @internal */
12
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
12
13
  export const DB_AGGREGATE_COLLECTION = 1 as const;
13
- const MIN_WIRE_VERSION_$OUT_READ_CONCERN_SUPPORT = 8 as const;
14
+ const MIN_WIRE_VERSION_$OUT_READ_CONCERN_SUPPORT = 8;
14
15
 
15
16
  /** @public */
16
17
  export interface AggregateOptions extends CommandOperationOptions {
@@ -13,11 +13,11 @@ import { AbstractOperation, Aspect, defineAspects } from './operation';
13
13
  export class BulkWriteOperation extends AbstractOperation<BulkWriteResult> {
14
14
  override options: BulkWriteOptions;
15
15
  collection: Collection;
16
- operations: AnyBulkWriteOperation[];
16
+ operations: ReadonlyArray<AnyBulkWriteOperation>;
17
17
 
18
18
  constructor(
19
19
  collection: Collection,
20
- operations: AnyBulkWriteOperation[],
20
+ operations: ReadonlyArray<AnyBulkWriteOperation>,
21
21
  options: BulkWriteOptions
22
22
  ) {
23
23
  super(options);