mongodb 6.8.0-dev.20240802.sha.54efb7d4 → 6.8.0-dev.20240813.sha.b70c8850

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 (172) hide show
  1. package/lib/beta.d.ts +7875 -0
  2. package/lib/beta.js +22 -0
  3. package/lib/beta.js.map +1 -0
  4. package/lib/bson.js +4 -4
  5. package/lib/bson.js.map +1 -1
  6. package/lib/bulk/common.js +2 -2
  7. package/lib/bulk/common.js.map +1 -1
  8. package/lib/bulk/ordered.js.map +1 -1
  9. package/lib/bulk/unordered.js.map +1 -1
  10. package/lib/change_stream.js +10 -2
  11. package/lib/change_stream.js.map +1 -1
  12. package/lib/client-side-encryption/auto_encrypter.js.map +1 -1
  13. package/lib/client-side-encryption/client_encryption.js +2 -2
  14. package/lib/client-side-encryption/client_encryption.js.map +1 -1
  15. package/lib/client-side-encryption/crypto_callbacks.js +6 -6
  16. package/lib/client-side-encryption/crypto_callbacks.js.map +1 -1
  17. package/lib/client-side-encryption/mongocryptd_manager.js +1 -1
  18. package/lib/client-side-encryption/mongocryptd_manager.js.map +1 -1
  19. package/lib/client-side-encryption/providers/aws.js +1 -2
  20. package/lib/client-side-encryption/providers/aws.js.map +1 -1
  21. package/lib/client-side-encryption/providers/azure.js +5 -5
  22. package/lib/client-side-encryption/providers/azure.js.map +1 -1
  23. package/lib/client-side-encryption/providers/gcp.js +1 -2
  24. package/lib/client-side-encryption/providers/gcp.js.map +1 -1
  25. package/lib/client-side-encryption/providers/index.js +2 -3
  26. package/lib/client-side-encryption/providers/index.js.map +1 -1
  27. package/lib/client-side-encryption/state_machine.js.map +1 -1
  28. package/lib/cmap/auth/auth_provider.js.map +1 -1
  29. package/lib/cmap/auth/aws_temporary_credentials.js.map +1 -1
  30. package/lib/cmap/auth/gssapi.js +3 -3
  31. package/lib/cmap/auth/gssapi.js.map +1 -1
  32. package/lib/cmap/auth/mongo_credentials.js.map +1 -1
  33. package/lib/cmap/auth/mongocr.js.map +1 -1
  34. package/lib/cmap/auth/mongodb_aws.js.map +1 -1
  35. package/lib/cmap/auth/mongodb_oidc/automated_callback_workflow.js.map +1 -1
  36. package/lib/cmap/auth/mongodb_oidc/azure_machine_workflow.js.map +1 -1
  37. package/lib/cmap/auth/mongodb_oidc/callback_workflow.js.map +1 -1
  38. package/lib/cmap/auth/mongodb_oidc/command_builders.js +2 -3
  39. package/lib/cmap/auth/mongodb_oidc/command_builders.js.map +1 -1
  40. package/lib/cmap/auth/mongodb_oidc/gcp_machine_workflow.js.map +1 -1
  41. package/lib/cmap/auth/mongodb_oidc/human_callback_workflow.js.map +1 -1
  42. package/lib/cmap/auth/mongodb_oidc/machine_workflow.js.map +1 -1
  43. package/lib/cmap/auth/mongodb_oidc/token_cache.js.map +1 -1
  44. package/lib/cmap/auth/mongodb_oidc/token_machine_workflow.js.map +1 -1
  45. package/lib/cmap/auth/mongodb_oidc.js.map +1 -1
  46. package/lib/cmap/auth/plain.js.map +1 -1
  47. package/lib/cmap/auth/scram.js.map +1 -1
  48. package/lib/cmap/auth/x509.js.map +1 -1
  49. package/lib/cmap/command_monitoring_events.js.map +1 -1
  50. package/lib/cmap/commands.js.map +1 -1
  51. package/lib/cmap/connect.js +6 -6
  52. package/lib/cmap/connect.js.map +1 -1
  53. package/lib/cmap/connection.js +3 -3
  54. package/lib/cmap/connection.js.map +1 -1
  55. package/lib/cmap/connection_pool.js +1 -1
  56. package/lib/cmap/connection_pool.js.map +1 -1
  57. package/lib/cmap/handshake/client_metadata.js +4 -4
  58. package/lib/cmap/handshake/client_metadata.js.map +1 -1
  59. package/lib/cmap/metrics.js +1 -1
  60. package/lib/cmap/metrics.js.map +1 -1
  61. package/lib/cmap/stream_description.js.map +1 -1
  62. package/lib/cmap/wire_protocol/compression.js +5 -5
  63. package/lib/cmap/wire_protocol/compression.js.map +1 -1
  64. package/lib/cmap/wire_protocol/on_data.js +1 -2
  65. package/lib/cmap/wire_protocol/on_data.js.map +1 -1
  66. package/lib/cmap/wire_protocol/on_demand/document.js.map +1 -1
  67. package/lib/cmap/wire_protocol/responses.js +4 -4
  68. package/lib/cmap/wire_protocol/responses.js.map +1 -1
  69. package/lib/cmap/wire_protocol/shared.js +2 -3
  70. package/lib/cmap/wire_protocol/shared.js.map +1 -1
  71. package/lib/collection.js.map +1 -1
  72. package/lib/connection_string.js +3 -3
  73. package/lib/connection_string.js.map +1 -1
  74. package/lib/cursor/abstract_cursor.js +21 -1
  75. package/lib/cursor/abstract_cursor.js.map +1 -1
  76. package/lib/cursor/aggregation_cursor.js +1 -1
  77. package/lib/cursor/aggregation_cursor.js.map +1 -1
  78. package/lib/cursor/change_stream_cursor.js.map +1 -1
  79. package/lib/cursor/find_cursor.js +3 -3
  80. package/lib/cursor/find_cursor.js.map +1 -1
  81. package/lib/db.js +1 -1
  82. package/lib/db.js.map +1 -1
  83. package/lib/deps.js +8 -8
  84. package/lib/deps.js.map +1 -1
  85. package/lib/encrypter.js.map +1 -1
  86. package/lib/error.js +9 -9
  87. package/lib/error.js.map +1 -1
  88. package/lib/explain.js.map +1 -1
  89. package/lib/gridfs/download.js +1 -1
  90. package/lib/gridfs/download.js.map +1 -1
  91. package/lib/gridfs/index.js +1 -1
  92. package/lib/gridfs/index.js.map +1 -1
  93. package/lib/gridfs/upload.js.map +1 -1
  94. package/lib/index.js +4 -2
  95. package/lib/index.js.map +1 -1
  96. package/lib/mongo_client.js +15 -1
  97. package/lib/mongo_client.js.map +1 -1
  98. package/lib/mongo_client_auth_providers.js.map +1 -1
  99. package/lib/mongo_logger.js +5 -5
  100. package/lib/mongo_logger.js.map +1 -1
  101. package/lib/mongo_types.js.map +1 -1
  102. package/lib/operations/aggregate.js.map +1 -1
  103. package/lib/operations/bulk_write.js.map +1 -1
  104. package/lib/operations/collections.js.map +1 -1
  105. package/lib/operations/command.js.map +1 -1
  106. package/lib/operations/count.js.map +1 -1
  107. package/lib/operations/create_collection.js.map +1 -1
  108. package/lib/operations/delete.js +2 -2
  109. package/lib/operations/delete.js.map +1 -1
  110. package/lib/operations/distinct.js.map +1 -1
  111. package/lib/operations/drop.js.map +1 -1
  112. package/lib/operations/estimated_document_count.js.map +1 -1
  113. package/lib/operations/execute_operation.js +1 -2
  114. package/lib/operations/execute_operation.js.map +1 -1
  115. package/lib/operations/find.js.map +1 -1
  116. package/lib/operations/find_and_modify.js.map +1 -1
  117. package/lib/operations/get_more.js.map +1 -1
  118. package/lib/operations/indexes.js.map +1 -1
  119. package/lib/operations/insert.js.map +1 -1
  120. package/lib/operations/is_capped.js.map +1 -1
  121. package/lib/operations/kill_cursors.js.map +1 -1
  122. package/lib/operations/list_collections.js.map +1 -1
  123. package/lib/operations/list_databases.js.map +1 -1
  124. package/lib/operations/operation.js +2 -2
  125. package/lib/operations/operation.js.map +1 -1
  126. package/lib/operations/options_operation.js.map +1 -1
  127. package/lib/operations/profiling_level.js.map +1 -1
  128. package/lib/operations/search_indexes/drop.js.map +1 -1
  129. package/lib/operations/set_profiling_level.js.map +1 -1
  130. package/lib/operations/stats.js.map +1 -1
  131. package/lib/operations/update.js +2 -2
  132. package/lib/operations/update.js.map +1 -1
  133. package/lib/operations/validate_collection.js.map +1 -1
  134. package/lib/read_concern.js.map +1 -1
  135. package/lib/read_preference.js +1 -1
  136. package/lib/read_preference.js.map +1 -1
  137. package/lib/resource_management.js +58 -0
  138. package/lib/resource_management.js.map +1 -0
  139. package/lib/sdam/common.js +3 -3
  140. package/lib/sdam/common.js.map +1 -1
  141. package/lib/sdam/monitor.js.map +1 -1
  142. package/lib/sdam/server.js +1 -1
  143. package/lib/sdam/server.js.map +1 -1
  144. package/lib/sdam/server_description.js +3 -3
  145. package/lib/sdam/server_description.js.map +1 -1
  146. package/lib/sdam/server_selection.js +5 -5
  147. package/lib/sdam/server_selection.js.map +1 -1
  148. package/lib/sdam/srv_polling.js +1 -1
  149. package/lib/sdam/srv_polling.js.map +1 -1
  150. package/lib/sdam/topology.js +1 -1
  151. package/lib/sdam/topology.js.map +1 -1
  152. package/lib/sdam/topology_description.js.map +1 -1
  153. package/lib/sessions.js +14 -5
  154. package/lib/sessions.js.map +1 -1
  155. package/lib/sort.js +1 -2
  156. package/lib/sort.js.map +1 -1
  157. package/lib/timeout.js.map +1 -1
  158. package/lib/transactions.js +2 -2
  159. package/lib/transactions.js.map +1 -1
  160. package/lib/utils.js +49 -50
  161. package/lib/utils.js.map +1 -1
  162. package/lib/write_concern.js +2 -2
  163. package/lib/write_concern.js.map +1 -1
  164. package/mongodb.d.ts +43 -10
  165. package/package.json +5 -4
  166. package/src/beta.ts +22 -0
  167. package/src/change_stream.ts +23 -4
  168. package/src/cursor/abstract_cursor.ts +38 -8
  169. package/src/index.ts +2 -0
  170. package/src/mongo_client.ts +24 -2
  171. package/src/resource_management.ts +74 -0
  172. package/src/sessions.ts +21 -2
package/mongodb.d.ts CHANGED
@@ -1,5 +1,3 @@
1
- /// <reference types="node" />
2
-
3
1
  import type { DeserializeOptions , ObjectIdLike , SerializeOptions } from 'bson';
4
2
  import { Binary , BSON , BSONRegExp , BSONSymbol , BSONType , Code , DBRef , Decimal128 , deserialize , Document , Double , Int32 , Long , MaxKey , MinKey , ObjectId , serialize , Timestamp , UUID } from 'bson';
5
3
  import type { SrvRecord } from 'dns';
@@ -9,7 +7,7 @@ import { Readable , Writable } from 'stream';
9
7
  import type { ConnectionOptions as ConnectionOptions_2 , TLSSocket , TLSSocketOptions } from 'tls';
10
8
 
11
9
  /** @public */
12
- export declare abstract class AbstractCursor<TSchema = any, CursorEvents extends AbstractCursorEvents = AbstractCursorEvents> extends TypedEventEmitter<CursorEvents> {
10
+ export declare abstract class AbstractCursor<TSchema = any, CursorEvents extends AbstractCursorEvents = AbstractCursorEvents> extends TypedEventEmitter<CursorEvents> implements AsyncDisposable_2 {
13
11
  /* Excluded from this release type: cursorId */
14
12
  /* Excluded from this release type: cursorSession */
15
13
  /* Excluded from this release type: selectedServer */
@@ -50,10 +48,12 @@ export declare abstract class AbstractCursor<TSchema = any, CursorEvents extends
50
48
  */
51
49
  get killed(): boolean;
52
50
  get loadBalanced(): boolean;
51
+ /* Excluded from this release type: [Symbol.asyncDispose] */
52
+ /* Excluded from this release type: asyncDispose */
53
53
  /** Returns current buffered documents length */
54
54
  bufferedCount(): number;
55
55
  /** Returns current buffered documents */
56
- readBufferedDocuments(number?: number): TSchema[];
56
+ readBufferedDocuments(number?: number): NonNullable<TSchema>[];
57
57
  [Symbol.asyncIterator](): AsyncGenerator<TSchema, void, void>;
58
58
  stream(options?: CursorStreamOptions): Readable & AsyncIterable<TSchema>;
59
59
  hasNext(): Promise<boolean>;
@@ -72,6 +72,9 @@ export declare abstract class AbstractCursor<TSchema = any, CursorEvents extends
72
72
  * @deprecated - Will be removed in a future release. Use for await...of instead.
73
73
  */
74
74
  forEach(iterator: (doc: TSchema) => boolean | void): Promise<void>;
75
+ /**
76
+ * Frees any client-side resources used by the cursor.
77
+ */
75
78
  close(): Promise<void>;
76
79
  /**
77
80
  * Returns an array of documents. The caller is responsible for making sure that there
@@ -500,6 +503,15 @@ export declare type ArrayOperator<Type> = {
500
503
  $sort?: Sort;
501
504
  };
502
505
 
506
+ /**
507
+ * @public
508
+ */
509
+ declare interface AsyncDisposable_2 {
510
+ /* Excluded from this release type: [Symbol.asyncDispose] */
511
+ /* Excluded from this release type: asyncDispose */
512
+ }
513
+ export { AsyncDisposable_2 as AsyncDisposable }
514
+
503
515
  /** @public */
504
516
  export declare interface Auth {
505
517
  /** The username for auth */
@@ -988,7 +1000,9 @@ export declare class CancellationToken extends TypedEventEmitter<{
988
1000
  * Creates a new Change Stream instance. Normally created using {@link Collection#watch|Collection.watch()}.
989
1001
  * @public
990
1002
  */
991
- export declare class ChangeStream<TSchema extends Document = Document, TChange extends Document = ChangeStreamDocument<TSchema>> extends TypedEventEmitter<ChangeStreamEvents<TSchema, TChange>> {
1003
+ export declare class ChangeStream<TSchema extends Document = Document, TChange extends Document = ChangeStreamDocument<TSchema>> extends TypedEventEmitter<ChangeStreamEvents<TSchema, TChange>> implements AsyncDisposable_2 {
1004
+ /* Excluded from this release type: [Symbol.asyncDispose] */
1005
+ /* Excluded from this release type: asyncDispose */
992
1006
  pipeline: Document[];
993
1007
  /**
994
1008
  * @remarks WriteConcern can still be present on the options because
@@ -1047,7 +1061,9 @@ export declare class ChangeStream<TSchema extends Document = Document, TChange e
1047
1061
  [Symbol.asyncIterator](): AsyncGenerator<TChange, void, void>;
1048
1062
  /** Is the cursor closed */
1049
1063
  get closed(): boolean;
1050
- /** Close the Change Stream */
1064
+ /**
1065
+ * Frees the internal resources used by the change stream.
1066
+ */
1051
1067
  close(): Promise<void>;
1052
1068
  /**
1053
1069
  * Return a modified Readable stream including a possible transform method.
@@ -1909,7 +1925,7 @@ export declare interface ClientMetadataOptions {
1909
1925
  * NOTE: not meant to be instantiated directly.
1910
1926
  * @public
1911
1927
  */
1912
- export declare class ClientSession extends TypedEventEmitter<ClientSessionEvents> {
1928
+ export declare class ClientSession extends TypedEventEmitter<ClientSessionEvents> implements AsyncDisposable_2 {
1913
1929
  /* Excluded from this release type: client */
1914
1930
  /* Excluded from this release type: sessionPool */
1915
1931
  hasEnded: boolean;
@@ -1941,11 +1957,16 @@ export declare class ClientSession extends TypedEventEmitter<ClientSessionEvents
1941
1957
  /* Excluded from this release type: unpin */
1942
1958
  get isPinned(): boolean;
1943
1959
  /**
1944
- * Ends this session on the server
1960
+ * Frees any client-side resources held by the current session. If a session is in a transaction,
1961
+ * the transaction is aborted.
1962
+ *
1963
+ * Does not end the session on the server.
1945
1964
  *
1946
1965
  * @param options - Optional settings. Currently reserved for future use
1947
1966
  */
1948
1967
  endSession(options?: EndSessionOptions): Promise<void>;
1968
+ /* Excluded from this release type: [Symbol.asyncDispose] */
1969
+ /* Excluded from this release type: asyncDispose */
1949
1970
  /**
1950
1971
  * Advances the operationTime for a ClientSession.
1951
1972
  *
@@ -2787,6 +2808,8 @@ export declare type CompressorName = keyof typeof Compressor;
2787
2808
  /** @public */
2788
2809
  export declare type Condition<T> = AlternativeType<T> | FilterOperators<AlternativeType<T>>;
2789
2810
 
2811
+ /* Excluded from this release type: configureExplicitResourceManagement */
2812
+
2790
2813
  /* Excluded from this release type: Connection */
2791
2814
 
2792
2815
  /* Excluded from this release type: CONNECTION_CHECK_OUT_FAILED */
@@ -4902,13 +4925,15 @@ export declare class MongoChangeStreamError extends MongoRuntimeError {
4902
4925
  * await client.insertOne({ name: 'spot', kind: 'dog' });
4903
4926
  * ```
4904
4927
  */
4905
- export declare class MongoClient extends TypedEventEmitter<MongoClientEvents> {
4928
+ export declare class MongoClient extends TypedEventEmitter<MongoClientEvents> implements AsyncDisposable_2 {
4906
4929
  /* Excluded from this release type: s */
4907
4930
  /* Excluded from this release type: topology */
4908
4931
  /* Excluded from this release type: mongoLogger */
4909
4932
  /* Excluded from this release type: connectionLock */
4910
4933
  /* Excluded from this release type: [kOptions] */
4911
4934
  constructor(url: string, options?: MongoClientOptions);
4935
+ /* Excluded from this release type: [Symbol.asyncDispose] */
4936
+ /* Excluded from this release type: asyncDispose */
4912
4937
  /* Excluded from this release type: checkForNonGenuineHosts */
4913
4938
  /** @see MongoOptions */
4914
4939
  get options(): Readonly<MongoOptions>;
@@ -4928,7 +4953,15 @@ export declare class MongoClient extends TypedEventEmitter<MongoClientEvents> {
4928
4953
  connect(): Promise<this>;
4929
4954
  /* Excluded from this release type: _connect */
4930
4955
  /**
4931
- * Close the client and its underlying connections
4956
+ * Cleans up client-side resources used by the MongoCLient and . This includes:
4957
+ *
4958
+ * - Closes all open, unused connections (see note).
4959
+ * - Ends all in-use sessions with {@link ClientSession#endSession|ClientSession.endSession()}.
4960
+ * - Ends all unused sessions server-side.
4961
+ * - Cleans up any resources being used for auto encryption if auto encryption is enabled.
4962
+ *
4963
+ * @remarks Any in-progress operations are not killed and any connections used by in progress operations
4964
+ * will be cleaned up lazily as operations finish.
4932
4965
  *
4933
4966
  * @param force - Force close, emitting no events
4934
4967
  */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mongodb",
3
- "version": "6.8.0-dev.20240802.sha.54efb7d4",
3
+ "version": "6.8.0-dev.20240813.sha.b70c8850",
4
4
  "description": "The official MongoDB driver for Node.js",
5
5
  "main": "lib/index.js",
6
6
  "files": [
@@ -73,7 +73,7 @@
73
73
  "@types/express": "^4.17.21",
74
74
  "@types/kerberos": "^1.1.5",
75
75
  "@types/mocha": "^10.0.6",
76
- "@types/node": "^20.12.7",
76
+ "@types/node": "^20.14.10",
77
77
  "@types/saslprep": "^1.0.3",
78
78
  "@types/semver": "^7.5.8",
79
79
  "@types/sinon": "^17.0.3",
@@ -110,7 +110,7 @@
110
110
  "source-map-support": "^0.5.21",
111
111
  "ts-node": "^10.9.2",
112
112
  "tsd": "^0.31.0",
113
- "typescript": "5.0",
113
+ "typescript": "5.5",
114
114
  "typescript-cached-transpile": "^0.0.6",
115
115
  "v8-heapsnapshot": "^1.3.1",
116
116
  "yargs": "^17.7.2"
@@ -126,7 +126,7 @@
126
126
  "scripts": {
127
127
  "build:evergreen": "node .evergreen/generate_evergreen_tasks.js",
128
128
  "build:ts": "node ./node_modules/typescript/bin/tsc",
129
- "build:dts": "npm run build:ts && api-extractor run && node etc/clean_definition_files.cjs && eslint mongodb.d.ts --fix",
129
+ "build:dts": "npm run build:ts && api-extractor run && node etc/clean_definition_files.cjs && eslint --no-ignore --fix mongodb.d.ts lib/beta.d.ts",
130
130
  "build:docs": "./etc/docs/build.ts",
131
131
  "build:typedoc": "typedoc",
132
132
  "build:nightly": "node ./.github/scripts/nightly.mjs",
@@ -145,6 +145,7 @@
145
145
  "check:unit": "mocha test/unit",
146
146
  "check:ts": "node ./node_modules/typescript/bin/tsc -v && node ./node_modules/typescript/bin/tsc --noEmit",
147
147
  "check:atlas": "mocha --config test/manual/mocharc.json test/manual/atlas_connectivity.test.ts",
148
+ "check:resource-management": "mocha --config test/manual/mocharc.json test/manual/resource_management.test.ts",
148
149
  "check:drivers-atlas-testing": "mocha --config test/mocha_mongodb.json test/atlas/drivers_atlas_testing.test.ts",
149
150
  "check:adl": "mocha --config test/mocha_mongodb.json test/manual/atlas-data-lake-testing",
150
151
  "check:aws": "nyc mocha --config test/mocha_mongodb.json test/integration/auth/mongodb_aws.test.ts",
package/src/beta.ts ADDED
@@ -0,0 +1,22 @@
1
+ import { type Document } from 'bson';
2
+
3
+ export * from './index';
4
+
5
+ /**
6
+ * @internal
7
+ *
8
+ * Since we don't bundle tslib helpers, we need to polyfill this method.
9
+ *
10
+ * This is used in the generated JS. Adapted from https://github.com/microsoft/TypeScript/blob/aafdfe5b3f76f5c41abeec412ce73c86da94c75f/src/compiler/factory/emitHelpers.ts#L1202.
11
+ */
12
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
13
+ function __exportStar(mod: Document) {
14
+ for (const key of Object.keys(mod)) {
15
+ Object.defineProperty(exports, key, {
16
+ enumerable: true,
17
+ get: function () {
18
+ return mod[key];
19
+ }
20
+ });
21
+ }
22
+ }
@@ -18,6 +18,7 @@ import { type InferIdType, TypedEventEmitter } from './mongo_types';
18
18
  import type { AggregateOptions } from './operations/aggregate';
19
19
  import type { CollationOptions, OperationParent } from './operations/command';
20
20
  import type { ReadPreference } from './read_preference';
21
+ import { type AsyncDisposable, configureResourceManagement } from './resource_management';
21
22
  import type { ServerSessionId } from './sessions';
22
23
  import { filterOptions, getTopology, type MongoDBNamespace, squashError } from './utils';
23
24
 
@@ -544,9 +545,23 @@ export type ChangeStreamEvents<
544
545
  * @public
545
546
  */
546
547
  export class ChangeStream<
547
- TSchema extends Document = Document,
548
- TChange extends Document = ChangeStreamDocument<TSchema>
549
- > extends TypedEventEmitter<ChangeStreamEvents<TSchema, TChange>> {
548
+ TSchema extends Document = Document,
549
+ TChange extends Document = ChangeStreamDocument<TSchema>
550
+ >
551
+ extends TypedEventEmitter<ChangeStreamEvents<TSchema, TChange>>
552
+ implements AsyncDisposable
553
+ {
554
+ /**
555
+ * @beta
556
+ * @experimental
557
+ * An alias for {@link ChangeStream.close|ChangeStream.close()}.
558
+ */
559
+ declare [Symbol.asyncDispose]: () => Promise<void>;
560
+ /** @internal */
561
+ async asyncDispose() {
562
+ await this.close();
563
+ }
564
+
550
565
  pipeline: Document[];
551
566
  /**
552
567
  * @remarks WriteConcern can still be present on the options because
@@ -765,7 +780,9 @@ export class ChangeStream<
765
780
  return this[kClosed] || this.cursor.closed;
766
781
  }
767
782
 
768
- /** Close the Change Stream */
783
+ /**
784
+ * Frees the internal resources used by the change stream.
785
+ */
769
786
  async close(): Promise<void> {
770
787
  this[kClosed] = true;
771
788
 
@@ -986,3 +1003,5 @@ export class ChangeStream<
986
1003
  }
987
1004
  }
988
1005
  }
1006
+
1007
+ configureResourceManagement(ChangeStream.prototype);
@@ -17,6 +17,7 @@ import { GetMoreOperation } from '../operations/get_more';
17
17
  import { KillCursorsOperation } from '../operations/kill_cursors';
18
18
  import { ReadConcern, type ReadConcernLike } from '../read_concern';
19
19
  import { ReadPreference, type ReadPreferenceLike } from '../read_preference';
20
+ import { type AsyncDisposable, configureResourceManagement } from '../resource_management';
20
21
  import type { Server } from '../sdam/server';
21
22
  import { ClientSession, maybeClearPinnedConnection } from '../sessions';
22
23
  import { type MongoDBNamespace, squashError } from '../utils';
@@ -124,9 +125,12 @@ export type AbstractCursorEvents = {
124
125
 
125
126
  /** @public */
126
127
  export abstract class AbstractCursor<
127
- TSchema = any,
128
- CursorEvents extends AbstractCursorEvents = AbstractCursorEvents
129
- > extends TypedEventEmitter<CursorEvents> {
128
+ TSchema = any,
129
+ CursorEvents extends AbstractCursorEvents = AbstractCursorEvents
130
+ >
131
+ extends TypedEventEmitter<CursorEvents>
132
+ implements AsyncDisposable
133
+ {
130
134
  /** @internal */
131
135
  private cursorId: Long | null;
132
136
  /** @internal */
@@ -275,14 +279,25 @@ export abstract class AbstractCursor<
275
279
  return !!this.cursorClient.topology?.loadBalanced;
276
280
  }
277
281
 
282
+ /**
283
+ * @beta
284
+ * @experimental
285
+ * An alias for {@link AbstractCursor.close|AbstractCursor.close()}.
286
+ */
287
+ declare [Symbol.asyncDispose]: () => Promise<void>;
288
+ /** @internal */
289
+ async asyncDispose() {
290
+ await this.close();
291
+ }
292
+
278
293
  /** Returns current buffered documents length */
279
294
  bufferedCount(): number {
280
295
  return this.documents?.length ?? 0;
281
296
  }
282
297
 
283
298
  /** Returns current buffered documents */
284
- readBufferedDocuments(number?: number): TSchema[] {
285
- const bufferedDocs: TSchema[] = [];
299
+ readBufferedDocuments(number?: number): NonNullable<TSchema>[] {
300
+ const bufferedDocs: NonNullable<TSchema>[] = [];
286
301
  const documentsToRead = Math.min(
287
302
  number ?? this.documents?.length ?? 0,
288
303
  this.documents?.length ?? 0
@@ -297,6 +312,7 @@ export abstract class AbstractCursor<
297
312
 
298
313
  return bufferedDocs;
299
314
  }
315
+
300
316
  async *[Symbol.asyncIterator](): AsyncGenerator<TSchema, void, void> {
301
317
  if (this.isClosed) {
302
318
  return;
@@ -446,6 +462,9 @@ export abstract class AbstractCursor<
446
462
  }
447
463
  }
448
464
 
465
+ /**
466
+ * Frees any client-side resources used by the cursor.
467
+ */
449
468
  async close(): Promise<void> {
450
469
  await this.cleanup();
451
470
  }
@@ -457,13 +476,22 @@ export abstract class AbstractCursor<
457
476
  * cursor.rewind() can be used to reset the cursor.
458
477
  */
459
478
  async toArray(): Promise<TSchema[]> {
460
- const array = [];
479
+ const array: TSchema[] = [];
480
+ // at the end of the loop (since readBufferedDocuments is called) the buffer will be empty
481
+ // then, the 'await of' syntax will run a getMore call
461
482
  for await (const document of this) {
462
483
  array.push(document);
484
+ const docs = this.readBufferedDocuments();
485
+ if (this.transform != null) {
486
+ for (const doc of docs) {
487
+ array.push(await this.transformDocument(doc));
488
+ }
489
+ } else {
490
+ array.push(...docs);
491
+ }
463
492
  }
464
493
  return array;
465
494
  }
466
-
467
495
  /**
468
496
  * Add a cursor flag to the cursor
469
497
  *
@@ -804,7 +832,7 @@ export abstract class AbstractCursor<
804
832
  }
805
833
 
806
834
  /** @internal */
807
- private async transformDocument(document: NonNullable<TSchema>): Promise<TSchema> {
835
+ private async transformDocument(document: NonNullable<TSchema>): Promise<NonNullable<TSchema>> {
808
836
  if (this.transform == null) return document;
809
837
 
810
838
  try {
@@ -916,3 +944,5 @@ class ReadableCursorStream extends Readable {
916
944
  );
917
945
  }
918
946
  }
947
+
948
+ configureResourceManagement(AbstractCursor.prototype);
package/src/index.ts CHANGED
@@ -76,6 +76,7 @@ export {
76
76
  MongoWriteConcernError,
77
77
  WriteConcernErrorResult
78
78
  } from './error';
79
+ export { configureExplicitResourceManagement } from './resource_management';
79
80
  export {
80
81
  AbstractCursor,
81
82
  // Actual driver classes exported
@@ -522,6 +523,7 @@ export type {
522
523
  ReadPreferenceLikeOptions,
523
524
  ReadPreferenceOptions
524
525
  } from './read_preference';
526
+ export type { AsyncDisposable } from './resource_management';
525
527
  export type { ClusterTime, TimerQueue } from './sdam/common';
526
528
  export type {
527
529
  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';
@@ -344,7 +345,7 @@ const kOptions = Symbol('options');
344
345
  * await client.insertOne({ name: 'spot', kind: 'dog' });
345
346
  * ```
346
347
  */
347
- export class MongoClient extends TypedEventEmitter<MongoClientEvents> {
348
+ export class MongoClient extends TypedEventEmitter<MongoClientEvents> implements AsyncDisposable {
348
349
  /** @internal */
349
350
  s: MongoClientPrivate;
350
351
  /** @internal */
@@ -404,6 +405,17 @@ export class MongoClient extends TypedEventEmitter<MongoClientEvents> {
404
405
  this.checkForNonGenuineHosts();
405
406
  }
406
407
 
408
+ /**
409
+ * @beta
410
+ * @experimental
411
+ * An alias for {@link MongoClient.close|MongoClient.close()}.
412
+ */
413
+ declare [Symbol.asyncDispose]: () => Promise<void>;
414
+ /** @internal */
415
+ async asyncDispose() {
416
+ await this.close();
417
+ }
418
+
407
419
  /** @internal */
408
420
  private checkForNonGenuineHosts() {
409
421
  const documentDBHostnames = this[kOptions].hosts.filter((hostAddress: HostAddress) =>
@@ -570,7 +582,15 @@ export class MongoClient extends TypedEventEmitter<MongoClientEvents> {
570
582
  }
571
583
 
572
584
  /**
573
- * Close the client and its underlying connections
585
+ * Cleans up client-side resources used by the MongoCLient and . This includes:
586
+ *
587
+ * - Closes all open, unused connections (see note).
588
+ * - Ends all in-use sessions with {@link ClientSession#endSession|ClientSession.endSession()}.
589
+ * - Ends all unused sessions server-side.
590
+ * - Cleans up any resources being used for auto encryption if auto encryption is enabled.
591
+ *
592
+ * @remarks Any in-progress operations are not killed and any connections used by in progress operations
593
+ * will be cleaned up lazily as operations finish.
574
594
  *
575
595
  * @param force - Force close, emitting no events
576
596
  */
@@ -758,6 +778,8 @@ export class MongoClient extends TypedEventEmitter<MongoClientEvents> {
758
778
  }
759
779
  }
760
780
 
781
+ configureResourceManagement(MongoClient.prototype);
782
+
761
783
  /**
762
784
  * Parsed Mongo Client Options.
763
785
  *
@@ -0,0 +1,74 @@
1
+ /**
2
+ * @public
3
+ */
4
+ export interface AsyncDisposable {
5
+ /**
6
+ * @beta
7
+ * @experimental
8
+ */
9
+ [Symbol.asyncDispose](): Promise<void>;
10
+
11
+ /**
12
+ * @internal
13
+ *
14
+ * A method that wraps disposal semantics for a given resource in the class.
15
+ */
16
+ asyncDispose(): Promise<void>;
17
+ }
18
+
19
+ /** @internal */
20
+ export function configureResourceManagement(target: AsyncDisposable) {
21
+ Symbol.asyncDispose &&
22
+ Object.defineProperty(target, Symbol.asyncDispose, {
23
+ value: async function asyncDispose(this: AsyncDisposable) {
24
+ await this.asyncDispose();
25
+ },
26
+ enumerable: false,
27
+ configurable: true,
28
+ writable: true
29
+ });
30
+ }
31
+
32
+ /**
33
+ * @beta
34
+ * @experimental
35
+ *
36
+ * Attaches `Symbol.asyncDispose` methods to the MongoClient, Cursors, sessions and change streams
37
+ * if Symbol.asyncDispose is defined.
38
+ *
39
+ * It's usually not necessary to call this method - the driver attempts to attach these methods
40
+ * itself when its loaded. However, sometimes the driver may be loaded before `Symbol.asyncDispose`
41
+ * is defined, in which case it is necessary to call this method directly. This can happen if the
42
+ * application is polyfilling `Symbol.asyncDispose`.
43
+ *
44
+ * Example:
45
+ *
46
+ * ```typescript
47
+ * import { configureExplicitResourceManagement, MongoClient } from 'mongodb/lib/beta';
48
+ *
49
+ * Symbol.asyncDispose ??= Symbol('dispose');
50
+ * load();
51
+ *
52
+ * await using client = new MongoClient(...);
53
+ * ```
54
+ */
55
+ export function configureExplicitResourceManagement() {
56
+ // We must import lazily here, because there's a circular dependency between the resource management
57
+ // file and each resources' file. We could move `configureResourceManagement` to a separate
58
+ // function, but keeping all resource-management related code together seemed preferable and I chose
59
+ // lazy requiring of resources instead.
60
+
61
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
62
+ const { MongoClient } = require('./mongo_client');
63
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
64
+ const { ClientSession } = require('./sessions');
65
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
66
+ const { AbstractCursor } = require('./cursor/abstract_cursor');
67
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
68
+ const { ChangeStream } = require('./change_stream');
69
+
70
+ configureResourceManagement(MongoClient.prototype);
71
+ configureResourceManagement(ClientSession.prototype);
72
+ configureResourceManagement(AbstractCursor.prototype);
73
+ configureResourceManagement(ChangeStream.prototype);
74
+ }
package/src/sessions.ts CHANGED
@@ -27,6 +27,7 @@ import { executeOperation } from './operations/execute_operation';
27
27
  import { RunAdminCommandOperation } from './operations/run_command';
28
28
  import { ReadConcernLevel } from './read_concern';
29
29
  import { ReadPreference } from './read_preference';
30
+ import { type AsyncDisposable, configureResourceManagement } from './resource_management';
30
31
  import { _advanceClusterTime, type ClusterTime, TopologyType } from './sdam/common';
31
32
  import {
32
33
  isTransactionCommand,
@@ -105,7 +106,10 @@ export interface EndSessionOptions {
105
106
  * NOTE: not meant to be instantiated directly.
106
107
  * @public
107
108
  */
108
- export class ClientSession extends TypedEventEmitter<ClientSessionEvents> {
109
+ export class ClientSession
110
+ extends TypedEventEmitter<ClientSessionEvents>
111
+ implements AsyncDisposable
112
+ {
109
113
  /** @internal */
110
114
  client: MongoClient;
111
115
  /** @internal */
@@ -255,7 +259,10 @@ export class ClientSession extends TypedEventEmitter<ClientSessionEvents> {
255
259
  }
256
260
 
257
261
  /**
258
- * Ends this session on the server
262
+ * Frees any client-side resources held by the current session. If a session is in a transaction,
263
+ * the transaction is aborted.
264
+ *
265
+ * Does not end the session on the server.
259
266
  *
260
267
  * @param options - Optional settings. Currently reserved for future use
261
268
  */
@@ -286,6 +293,16 @@ export class ClientSession extends TypedEventEmitter<ClientSessionEvents> {
286
293
  maybeClearPinnedConnection(this, { force: true, ...options });
287
294
  }
288
295
  }
296
+ /**
297
+ * @beta
298
+ * @experimental
299
+ * An alias for {@link ClientSession.endSession|ClientSession.endSession()}.
300
+ */
301
+ declare [Symbol.asyncDispose]: () => Promise<void>;
302
+ /** @internal */
303
+ async asyncDispose() {
304
+ await this.endSession({ force: true });
305
+ }
289
306
 
290
307
  /**
291
308
  * Advances the operationTime for a ClientSession.
@@ -484,6 +501,8 @@ export class ClientSession extends TypedEventEmitter<ClientSessionEvents> {
484
501
  }
485
502
  }
486
503
 
504
+ configureResourceManagement(ClientSession.prototype);
505
+
487
506
  const MAX_WITH_TRANSACTION_TIMEOUT = 120000;
488
507
  const NON_DETERMINISTIC_WRITE_CONCERN_ERRORS = new Set([
489
508
  'CannotSatisfyWriteConcern',