@depup/mongodb 7.1.0-depup.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 (396) hide show
  1. package/LICENSE.md +201 -0
  2. package/README.md +33 -0
  3. package/etc/prepare.js +12 -0
  4. package/lib/admin.js +136 -0
  5. package/lib/admin.js.map +1 -0
  6. package/lib/bson.js +85 -0
  7. package/lib/bson.js.map +1 -0
  8. package/lib/bulk/common.js +835 -0
  9. package/lib/bulk/common.js.map +1 -0
  10. package/lib/bulk/ordered.js +67 -0
  11. package/lib/bulk/ordered.js.map +1 -0
  12. package/lib/bulk/unordered.js +92 -0
  13. package/lib/bulk/unordered.js.map +1 -0
  14. package/lib/change_stream.js +513 -0
  15. package/lib/change_stream.js.map +1 -0
  16. package/lib/client-side-encryption/auto_encrypter.js +272 -0
  17. package/lib/client-side-encryption/auto_encrypter.js.map +1 -0
  18. package/lib/client-side-encryption/client_encryption.js +609 -0
  19. package/lib/client-side-encryption/client_encryption.js.map +1 -0
  20. package/lib/client-side-encryption/errors.js +138 -0
  21. package/lib/client-side-encryption/errors.js.map +1 -0
  22. package/lib/client-side-encryption/mongocryptd_manager.js +85 -0
  23. package/lib/client-side-encryption/mongocryptd_manager.js.map +1 -0
  24. package/lib/client-side-encryption/providers/aws.js +23 -0
  25. package/lib/client-side-encryption/providers/aws.js.map +1 -0
  26. package/lib/client-side-encryption/providers/azure.js +132 -0
  27. package/lib/client-side-encryption/providers/azure.js.map +1 -0
  28. package/lib/client-side-encryption/providers/gcp.js +16 -0
  29. package/lib/client-side-encryption/providers/gcp.js.map +1 -0
  30. package/lib/client-side-encryption/providers/index.js +43 -0
  31. package/lib/client-side-encryption/providers/index.js.map +1 -0
  32. package/lib/client-side-encryption/state_machine.js +427 -0
  33. package/lib/client-side-encryption/state_machine.js.map +1 -0
  34. package/lib/cmap/auth/auth_provider.js +51 -0
  35. package/lib/cmap/auth/auth_provider.js.map +1 -0
  36. package/lib/cmap/auth/aws4.js +161 -0
  37. package/lib/cmap/auth/aws4.js.map +1 -0
  38. package/lib/cmap/auth/aws_temporary_credentials.js +103 -0
  39. package/lib/cmap/auth/aws_temporary_credentials.js.map +1 -0
  40. package/lib/cmap/auth/gssapi.js +155 -0
  41. package/lib/cmap/auth/gssapi.js.map +1 -0
  42. package/lib/cmap/auth/mongo_credentials.js +169 -0
  43. package/lib/cmap/auth/mongo_credentials.js.map +1 -0
  44. package/lib/cmap/auth/mongodb_aws.js +128 -0
  45. package/lib/cmap/auth/mongodb_aws.js.map +1 -0
  46. package/lib/cmap/auth/mongodb_oidc/automated_callback_workflow.js +84 -0
  47. package/lib/cmap/auth/mongodb_oidc/automated_callback_workflow.js.map +1 -0
  48. package/lib/cmap/auth/mongodb_oidc/azure_machine_workflow.js +62 -0
  49. package/lib/cmap/auth/mongodb_oidc/azure_machine_workflow.js.map +1 -0
  50. package/lib/cmap/auth/mongodb_oidc/callback_workflow.js +141 -0
  51. package/lib/cmap/auth/mongodb_oidc/callback_workflow.js.map +1 -0
  52. package/lib/cmap/auth/mongodb_oidc/command_builders.js +44 -0
  53. package/lib/cmap/auth/mongodb_oidc/command_builders.js.map +1 -0
  54. package/lib/cmap/auth/mongodb_oidc/gcp_machine_workflow.js +39 -0
  55. package/lib/cmap/auth/mongodb_oidc/gcp_machine_workflow.js.map +1 -0
  56. package/lib/cmap/auth/mongodb_oidc/human_callback_workflow.js +122 -0
  57. package/lib/cmap/auth/mongodb_oidc/human_callback_workflow.js.map +1 -0
  58. package/lib/cmap/auth/mongodb_oidc/k8s_machine_workflow.js +32 -0
  59. package/lib/cmap/auth/mongodb_oidc/k8s_machine_workflow.js.map +1 -0
  60. package/lib/cmap/auth/mongodb_oidc/token_cache.js +52 -0
  61. package/lib/cmap/auth/mongodb_oidc/token_cache.js.map +1 -0
  62. package/lib/cmap/auth/mongodb_oidc/token_machine_workflow.js +23 -0
  63. package/lib/cmap/auth/mongodb_oidc/token_machine_workflow.js.map +1 -0
  64. package/lib/cmap/auth/mongodb_oidc.js +73 -0
  65. package/lib/cmap/auth/mongodb_oidc.js.map +1 -0
  66. package/lib/cmap/auth/plain.js +26 -0
  67. package/lib/cmap/auth/plain.js.map +1 -0
  68. package/lib/cmap/auth/providers.js +22 -0
  69. package/lib/cmap/auth/providers.js.map +1 -0
  70. package/lib/cmap/auth/scram.js +254 -0
  71. package/lib/cmap/auth/scram.js.map +1 -0
  72. package/lib/cmap/auth/x509.js +36 -0
  73. package/lib/cmap/auth/x509.js.map +1 -0
  74. package/lib/cmap/command_monitoring_events.js +223 -0
  75. package/lib/cmap/command_monitoring_events.js.map +1 -0
  76. package/lib/cmap/commands.js +535 -0
  77. package/lib/cmap/commands.js.map +1 -0
  78. package/lib/cmap/connect.js +381 -0
  79. package/lib/cmap/connect.js.map +1 -0
  80. package/lib/cmap/connection.js +571 -0
  81. package/lib/cmap/connection.js.map +1 -0
  82. package/lib/cmap/connection_pool.js +558 -0
  83. package/lib/cmap/connection_pool.js.map +1 -0
  84. package/lib/cmap/connection_pool_events.js +190 -0
  85. package/lib/cmap/connection_pool_events.js.map +1 -0
  86. package/lib/cmap/errors.js +108 -0
  87. package/lib/cmap/errors.js.map +1 -0
  88. package/lib/cmap/handshake/client_metadata.js +242 -0
  89. package/lib/cmap/handshake/client_metadata.js.map +1 -0
  90. package/lib/cmap/metrics.js +62 -0
  91. package/lib/cmap/metrics.js.map +1 -0
  92. package/lib/cmap/stream_description.js +70 -0
  93. package/lib/cmap/stream_description.js.map +1 -0
  94. package/lib/cmap/wire_protocol/compression.js +178 -0
  95. package/lib/cmap/wire_protocol/compression.js.map +1 -0
  96. package/lib/cmap/wire_protocol/constants.js +21 -0
  97. package/lib/cmap/wire_protocol/constants.js.map +1 -0
  98. package/lib/cmap/wire_protocol/on_data.js +111 -0
  99. package/lib/cmap/wire_protocol/on_data.js.map +1 -0
  100. package/lib/cmap/wire_protocol/on_demand/document.js +222 -0
  101. package/lib/cmap/wire_protocol/on_demand/document.js.map +1 -0
  102. package/lib/cmap/wire_protocol/responses.js +315 -0
  103. package/lib/cmap/wire_protocol/responses.js.map +1 -0
  104. package/lib/cmap/wire_protocol/shared.js +35 -0
  105. package/lib/cmap/wire_protocol/shared.js.map +1 -0
  106. package/lib/collection.js +751 -0
  107. package/lib/collection.js.map +1 -0
  108. package/lib/connection_string.js +1090 -0
  109. package/lib/connection_string.js.map +1 -0
  110. package/lib/constants.js +170 -0
  111. package/lib/constants.js.map +1 -0
  112. package/lib/cursor/abstract_cursor.js +924 -0
  113. package/lib/cursor/abstract_cursor.js.map +1 -0
  114. package/lib/cursor/aggregation_cursor.js +164 -0
  115. package/lib/cursor/aggregation_cursor.js.map +1 -0
  116. package/lib/cursor/change_stream_cursor.js +104 -0
  117. package/lib/cursor/change_stream_cursor.js.map +1 -0
  118. package/lib/cursor/client_bulk_write_cursor.js +52 -0
  119. package/lib/cursor/client_bulk_write_cursor.js.map +1 -0
  120. package/lib/cursor/explainable_cursor.js +36 -0
  121. package/lib/cursor/explainable_cursor.js.map +1 -0
  122. package/lib/cursor/find_cursor.js +399 -0
  123. package/lib/cursor/find_cursor.js.map +1 -0
  124. package/lib/cursor/list_collections_cursor.js +34 -0
  125. package/lib/cursor/list_collections_cursor.js.map +1 -0
  126. package/lib/cursor/list_indexes_cursor.js +32 -0
  127. package/lib/cursor/list_indexes_cursor.js.map +1 -0
  128. package/lib/cursor/list_search_indexes_cursor.js +14 -0
  129. package/lib/cursor/list_search_indexes_cursor.js.map +1 -0
  130. package/lib/cursor/run_command_cursor.js +94 -0
  131. package/lib/cursor/run_command_cursor.js.map +1 -0
  132. package/lib/db.js +419 -0
  133. package/lib/db.js.map +1 -0
  134. package/lib/deps.js +112 -0
  135. package/lib/deps.js.map +1 -0
  136. package/lib/encrypter.js +106 -0
  137. package/lib/encrypter.js.map +1 -0
  138. package/lib/error.js +1380 -0
  139. package/lib/error.js.map +1 -0
  140. package/lib/explain.js +59 -0
  141. package/lib/explain.js.map +1 -0
  142. package/lib/gridfs/download.js +305 -0
  143. package/lib/gridfs/download.js.map +1 -0
  144. package/lib/gridfs/index.js +164 -0
  145. package/lib/gridfs/index.js.map +1 -0
  146. package/lib/gridfs/upload.js +358 -0
  147. package/lib/gridfs/upload.js.map +1 -0
  148. package/lib/index.js +193 -0
  149. package/lib/index.js.map +1 -0
  150. package/lib/mongo_client.js +557 -0
  151. package/lib/mongo_client.js.map +1 -0
  152. package/lib/mongo_client_auth_providers.js +80 -0
  153. package/lib/mongo_client_auth_providers.js.map +1 -0
  154. package/lib/mongo_logger.js +655 -0
  155. package/lib/mongo_logger.js.map +1 -0
  156. package/lib/mongo_types.js +56 -0
  157. package/lib/mongo_types.js.map +1 -0
  158. package/lib/operations/aggregate.js +90 -0
  159. package/lib/operations/aggregate.js.map +1 -0
  160. package/lib/operations/client_bulk_write/client_bulk_write.js +51 -0
  161. package/lib/operations/client_bulk_write/client_bulk_write.js.map +1 -0
  162. package/lib/operations/client_bulk_write/command_builder.js +340 -0
  163. package/lib/operations/client_bulk_write/command_builder.js.map +1 -0
  164. package/lib/operations/client_bulk_write/common.js +3 -0
  165. package/lib/operations/client_bulk_write/common.js.map +1 -0
  166. package/lib/operations/client_bulk_write/executor.js +120 -0
  167. package/lib/operations/client_bulk_write/executor.js.map +1 -0
  168. package/lib/operations/client_bulk_write/results_merger.js +204 -0
  169. package/lib/operations/client_bulk_write/results_merger.js.map +1 -0
  170. package/lib/operations/command.js +83 -0
  171. package/lib/operations/command.js.map +1 -0
  172. package/lib/operations/count.js +45 -0
  173. package/lib/operations/count.js.map +1 -0
  174. package/lib/operations/create_collection.js +109 -0
  175. package/lib/operations/create_collection.js.map +1 -0
  176. package/lib/operations/delete.js +125 -0
  177. package/lib/operations/delete.js.map +1 -0
  178. package/lib/operations/distinct.js +61 -0
  179. package/lib/operations/distinct.js.map +1 -0
  180. package/lib/operations/drop.js +93 -0
  181. package/lib/operations/drop.js.map +1 -0
  182. package/lib/operations/end_sessions.js +34 -0
  183. package/lib/operations/end_sessions.js.map +1 -0
  184. package/lib/operations/estimated_document_count.js +41 -0
  185. package/lib/operations/estimated_document_count.js.map +1 -0
  186. package/lib/operations/execute_operation.js +239 -0
  187. package/lib/operations/execute_operation.js.map +1 -0
  188. package/lib/operations/find.js +148 -0
  189. package/lib/operations/find.js.map +1 -0
  190. package/lib/operations/find_and_modify.js +158 -0
  191. package/lib/operations/find_and_modify.js.map +1 -0
  192. package/lib/operations/get_more.js +62 -0
  193. package/lib/operations/get_more.js.map +1 -0
  194. package/lib/operations/indexes.js +186 -0
  195. package/lib/operations/indexes.js.map +1 -0
  196. package/lib/operations/insert.js +70 -0
  197. package/lib/operations/insert.js.map +1 -0
  198. package/lib/operations/kill_cursors.js +43 -0
  199. package/lib/operations/kill_cursors.js.map +1 -0
  200. package/lib/operations/list_collections.js +53 -0
  201. package/lib/operations/list_collections.js.map +1 -0
  202. package/lib/operations/list_databases.js +40 -0
  203. package/lib/operations/list_databases.js.map +1 -0
  204. package/lib/operations/operation.js +102 -0
  205. package/lib/operations/operation.js.map +1 -0
  206. package/lib/operations/profiling_level.js +43 -0
  207. package/lib/operations/profiling_level.js.map +1 -0
  208. package/lib/operations/remove_user.js +27 -0
  209. package/lib/operations/remove_user.js.map +1 -0
  210. package/lib/operations/rename.js +38 -0
  211. package/lib/operations/rename.js.map +1 -0
  212. package/lib/operations/run_command.js +47 -0
  213. package/lib/operations/run_command.js.map +1 -0
  214. package/lib/operations/search_indexes/create.js +33 -0
  215. package/lib/operations/search_indexes/create.js.map +1 -0
  216. package/lib/operations/search_indexes/drop.js +43 -0
  217. package/lib/operations/search_indexes/drop.js.map +1 -0
  218. package/lib/operations/search_indexes/update.js +35 -0
  219. package/lib/operations/search_indexes/update.js.map +1 -0
  220. package/lib/operations/set_profiling_level.js +53 -0
  221. package/lib/operations/set_profiling_level.js.map +1 -0
  222. package/lib/operations/stats.js +27 -0
  223. package/lib/operations/stats.js.map +1 -0
  224. package/lib/operations/update.js +188 -0
  225. package/lib/operations/update.js.map +1 -0
  226. package/lib/operations/validate_collection.js +37 -0
  227. package/lib/operations/validate_collection.js.map +1 -0
  228. package/lib/read_concern.js +73 -0
  229. package/lib/read_concern.js.map +1 -0
  230. package/lib/read_preference.js +191 -0
  231. package/lib/read_preference.js.map +1 -0
  232. package/lib/sdam/common.js +49 -0
  233. package/lib/sdam/common.js.map +1 -0
  234. package/lib/sdam/events.js +146 -0
  235. package/lib/sdam/events.js.map +1 -0
  236. package/lib/sdam/monitor.js +544 -0
  237. package/lib/sdam/monitor.js.map +1 -0
  238. package/lib/sdam/server.js +404 -0
  239. package/lib/sdam/server.js.map +1 -0
  240. package/lib/sdam/server_description.js +204 -0
  241. package/lib/sdam/server_description.js.map +1 -0
  242. package/lib/sdam/server_selection.js +294 -0
  243. package/lib/sdam/server_selection.js.map +1 -0
  244. package/lib/sdam/server_selection_events.js +85 -0
  245. package/lib/sdam/server_selection_events.js.map +1 -0
  246. package/lib/sdam/srv_polling.js +108 -0
  247. package/lib/sdam/srv_polling.js.map +1 -0
  248. package/lib/sdam/topology.js +652 -0
  249. package/lib/sdam/topology.js.map +1 -0
  250. package/lib/sdam/topology_description.js +383 -0
  251. package/lib/sdam/topology_description.js.map +1 -0
  252. package/lib/sessions.js +892 -0
  253. package/lib/sessions.js.map +1 -0
  254. package/lib/sort.js +103 -0
  255. package/lib/sort.js.map +1 -0
  256. package/lib/timeout.js +296 -0
  257. package/lib/timeout.js.map +1 -0
  258. package/lib/transactions.js +135 -0
  259. package/lib/transactions.js.map +1 -0
  260. package/lib/utils.js +1163 -0
  261. package/lib/utils.js.map +1 -0
  262. package/lib/write_concern.js +100 -0
  263. package/lib/write_concern.js.map +1 -0
  264. package/mongodb.d.ts +9018 -0
  265. package/package.json +197 -0
  266. package/src/admin.ts +173 -0
  267. package/src/bson.ts +149 -0
  268. package/src/bulk/common.ts +1251 -0
  269. package/src/bulk/ordered.ts +83 -0
  270. package/src/bulk/unordered.ts +115 -0
  271. package/src/change_stream.ts +1160 -0
  272. package/src/client-side-encryption/auto_encrypter.ts +469 -0
  273. package/src/client-side-encryption/client_encryption.ts +1150 -0
  274. package/src/client-side-encryption/errors.ts +144 -0
  275. package/src/client-side-encryption/mongocryptd_manager.ts +100 -0
  276. package/src/client-side-encryption/providers/aws.ts +33 -0
  277. package/src/client-side-encryption/providers/azure.ts +181 -0
  278. package/src/client-side-encryption/providers/gcp.ts +16 -0
  279. package/src/client-side-encryption/providers/index.ts +207 -0
  280. package/src/client-side-encryption/state_machine.ts +651 -0
  281. package/src/cmap/auth/auth_provider.ts +77 -0
  282. package/src/cmap/auth/aws4.ts +207 -0
  283. package/src/cmap/auth/aws_temporary_credentials.ts +129 -0
  284. package/src/cmap/auth/gssapi.ts +203 -0
  285. package/src/cmap/auth/mongo_credentials.ts +292 -0
  286. package/src/cmap/auth/mongodb_aws.ts +179 -0
  287. package/src/cmap/auth/mongodb_oidc/automated_callback_workflow.ts +88 -0
  288. package/src/cmap/auth/mongodb_oidc/azure_machine_workflow.ts +73 -0
  289. package/src/cmap/auth/mongodb_oidc/callback_workflow.ts +188 -0
  290. package/src/cmap/auth/mongodb_oidc/command_builders.ts +53 -0
  291. package/src/cmap/auth/mongodb_oidc/gcp_machine_workflow.ts +46 -0
  292. package/src/cmap/auth/mongodb_oidc/human_callback_workflow.ts +141 -0
  293. package/src/cmap/auth/mongodb_oidc/k8s_machine_workflow.ts +31 -0
  294. package/src/cmap/auth/mongodb_oidc/token_cache.ts +62 -0
  295. package/src/cmap/auth/mongodb_oidc/token_machine_workflow.ts +22 -0
  296. package/src/cmap/auth/mongodb_oidc.ts +185 -0
  297. package/src/cmap/auth/plain.ts +25 -0
  298. package/src/cmap/auth/providers.ts +22 -0
  299. package/src/cmap/auth/scram.ts +344 -0
  300. package/src/cmap/auth/x509.ts +43 -0
  301. package/src/cmap/command_monitoring_events.ts +316 -0
  302. package/src/cmap/commands.ts +788 -0
  303. package/src/cmap/connect.ts +518 -0
  304. package/src/cmap/connection.ts +931 -0
  305. package/src/cmap/connection_pool.ts +831 -0
  306. package/src/cmap/connection_pool_events.ts +300 -0
  307. package/src/cmap/errors.ts +119 -0
  308. package/src/cmap/handshake/client_metadata.ts +353 -0
  309. package/src/cmap/metrics.ts +58 -0
  310. package/src/cmap/stream_description.ts +96 -0
  311. package/src/cmap/wire_protocol/compression.ts +211 -0
  312. package/src/cmap/wire_protocol/constants.ts +17 -0
  313. package/src/cmap/wire_protocol/on_data.ts +139 -0
  314. package/src/cmap/wire_protocol/on_demand/document.ts +358 -0
  315. package/src/cmap/wire_protocol/responses.ts +393 -0
  316. package/src/cmap/wire_protocol/shared.ts +48 -0
  317. package/src/collection.ts +1314 -0
  318. package/src/connection_string.ts +1297 -0
  319. package/src/constants.ts +176 -0
  320. package/src/cursor/abstract_cursor.ts +1247 -0
  321. package/src/cursor/aggregation_cursor.ts +245 -0
  322. package/src/cursor/change_stream_cursor.ts +171 -0
  323. package/src/cursor/client_bulk_write_cursor.ts +83 -0
  324. package/src/cursor/explainable_cursor.ts +51 -0
  325. package/src/cursor/find_cursor.ts +497 -0
  326. package/src/cursor/list_collections_cursor.ts +50 -0
  327. package/src/cursor/list_indexes_cursor.ts +37 -0
  328. package/src/cursor/list_search_indexes_cursor.ts +20 -0
  329. package/src/cursor/run_command_cursor.ts +178 -0
  330. package/src/db.ts +621 -0
  331. package/src/deps.ts +227 -0
  332. package/src/encrypter.ts +127 -0
  333. package/src/error.ts +1567 -0
  334. package/src/explain.ts +124 -0
  335. package/src/gridfs/download.ts +483 -0
  336. package/src/gridfs/index.ts +264 -0
  337. package/src/gridfs/upload.ts +537 -0
  338. package/src/index.ts +633 -0
  339. package/src/mongo_client.ts +1155 -0
  340. package/src/mongo_client_auth_providers.ts +87 -0
  341. package/src/mongo_logger.ts +1081 -0
  342. package/src/mongo_types.ts +678 -0
  343. package/src/operations/aggregate.ts +153 -0
  344. package/src/operations/client_bulk_write/client_bulk_write.ts +72 -0
  345. package/src/operations/client_bulk_write/command_builder.ts +487 -0
  346. package/src/operations/client_bulk_write/common.ts +276 -0
  347. package/src/operations/client_bulk_write/executor.ts +149 -0
  348. package/src/operations/client_bulk_write/results_merger.ts +260 -0
  349. package/src/operations/command.ts +171 -0
  350. package/src/operations/count.ts +74 -0
  351. package/src/operations/create_collection.ts +218 -0
  352. package/src/operations/delete.ts +183 -0
  353. package/src/operations/distinct.ts +92 -0
  354. package/src/operations/drop.ts +130 -0
  355. package/src/operations/end_sessions.ts +44 -0
  356. package/src/operations/estimated_document_count.ts +61 -0
  357. package/src/operations/execute_operation.ts +319 -0
  358. package/src/operations/find.ts +254 -0
  359. package/src/operations/find_and_modify.ts +319 -0
  360. package/src/operations/get_more.ts +108 -0
  361. package/src/operations/indexes.ts +418 -0
  362. package/src/operations/insert.ts +108 -0
  363. package/src/operations/kill_cursors.ts +64 -0
  364. package/src/operations/list_collections.ts +108 -0
  365. package/src/operations/list_databases.ts +68 -0
  366. package/src/operations/operation.ts +181 -0
  367. package/src/operations/profiling_level.ts +46 -0
  368. package/src/operations/remove_user.ts +36 -0
  369. package/src/operations/rename.ts +60 -0
  370. package/src/operations/run_command.ts +79 -0
  371. package/src/operations/search_indexes/create.ts +56 -0
  372. package/src/operations/search_indexes/drop.ts +58 -0
  373. package/src/operations/search_indexes/update.ts +45 -0
  374. package/src/operations/set_profiling_level.ts +74 -0
  375. package/src/operations/stats.ts +37 -0
  376. package/src/operations/update.ts +318 -0
  377. package/src/operations/validate_collection.ts +50 -0
  378. package/src/read_concern.ts +88 -0
  379. package/src/read_preference.ts +256 -0
  380. package/src/sdam/common.ts +74 -0
  381. package/src/sdam/events.ts +219 -0
  382. package/src/sdam/monitor.ts +771 -0
  383. package/src/sdam/server.ts +595 -0
  384. package/src/sdam/server_description.ts +297 -0
  385. package/src/sdam/server_selection.ts +415 -0
  386. package/src/sdam/server_selection_events.ts +142 -0
  387. package/src/sdam/srv_polling.ts +146 -0
  388. package/src/sdam/topology.ts +1100 -0
  389. package/src/sdam/topology_description.ts +548 -0
  390. package/src/sessions.ts +1244 -0
  391. package/src/sort.ts +141 -0
  392. package/src/timeout.ts +405 -0
  393. package/src/transactions.ts +181 -0
  394. package/src/utils.ts +1434 -0
  395. package/src/write_concern.ts +183 -0
  396. package/tsconfig.json +46 -0
package/lib/utils.js ADDED
@@ -0,0 +1,1163 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.kDispose = exports.randomBytes = exports.COSMOS_DB_MSG = exports.DOCUMENT_DB_MSG = exports.COSMOS_DB_CHECK = exports.DOCUMENT_DB_CHECK = exports.MONGODB_WARNING_CODE = exports.DEFAULT_PK_FACTORY = exports.HostAddress = exports.BufferPool = exports.List = exports.MongoDBCollectionNamespace = exports.MongoDBNamespace = exports.ByteUtils = void 0;
4
+ exports.isUint8Array = isUint8Array;
5
+ exports.hostMatchesWildcards = hostMatchesWildcards;
6
+ exports.normalizeHintField = normalizeHintField;
7
+ exports.isObject = isObject;
8
+ exports.mergeOptions = mergeOptions;
9
+ exports.filterOptions = filterOptions;
10
+ exports.isPromiseLike = isPromiseLike;
11
+ exports.decorateWithCollation = decorateWithCollation;
12
+ exports.decorateWithReadConcern = decorateWithReadConcern;
13
+ exports.getTopology = getTopology;
14
+ exports.ns = ns;
15
+ exports.makeCounter = makeCounter;
16
+ exports.uuidV4 = uuidV4;
17
+ exports.maxWireVersion = maxWireVersion;
18
+ exports.arrayStrictEqual = arrayStrictEqual;
19
+ exports.errorStrictEqual = errorStrictEqual;
20
+ exports.makeStateMachine = makeStateMachine;
21
+ exports.processTimeMS = processTimeMS;
22
+ exports.calculateDurationInMs = calculateDurationInMs;
23
+ exports.hasAtomicOperators = hasAtomicOperators;
24
+ exports.resolveTimeoutOptions = resolveTimeoutOptions;
25
+ exports.resolveOptions = resolveOptions;
26
+ exports.isSuperset = isSuperset;
27
+ exports.isHello = isHello;
28
+ exports.setDifference = setDifference;
29
+ exports.isRecord = isRecord;
30
+ exports.emitWarning = emitWarning;
31
+ exports.emitWarningOnce = emitWarningOnce;
32
+ exports.enumToString = enumToString;
33
+ exports.supportsRetryableWrites = supportsRetryableWrites;
34
+ exports.shuffle = shuffle;
35
+ exports.commandSupportsReadConcern = commandSupportsReadConcern;
36
+ exports.compareObjectId = compareObjectId;
37
+ exports.parseInteger = parseInteger;
38
+ exports.parseUnsignedInteger = parseUnsignedInteger;
39
+ exports.checkParentDomainMatch = checkParentDomainMatch;
40
+ exports.get = get;
41
+ exports.isHostMatch = isHostMatch;
42
+ exports.promiseWithResolvers = promiseWithResolvers;
43
+ exports.squashError = squashError;
44
+ exports.once = once;
45
+ exports.maybeAddIdToDocuments = maybeAddIdToDocuments;
46
+ exports.fileIsAccessible = fileIsAccessible;
47
+ exports.csotMin = csotMin;
48
+ exports.noop = noop;
49
+ exports.decorateDecryptionResult = decorateDecryptionResult;
50
+ exports.addAbortListener = addAbortListener;
51
+ exports.abortable = abortable;
52
+ const crypto = require("crypto");
53
+ const fs_1 = require("fs");
54
+ const http = require("http");
55
+ const process = require("process");
56
+ const timers_1 = require("timers");
57
+ const bson_1 = require("./bson");
58
+ const constants_1 = require("./cmap/wire_protocol/constants");
59
+ const constants_2 = require("./constants");
60
+ const error_1 = require("./error");
61
+ const read_concern_1 = require("./read_concern");
62
+ const read_preference_1 = require("./read_preference");
63
+ const common_1 = require("./sdam/common");
64
+ const write_concern_1 = require("./write_concern");
65
+ exports.ByteUtils = {
66
+ toLocalBufferType(buffer) {
67
+ return Buffer.isBuffer(buffer)
68
+ ? buffer
69
+ : Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength);
70
+ },
71
+ equals(seqA, seqB) {
72
+ return exports.ByteUtils.toLocalBufferType(seqA).equals(seqB);
73
+ },
74
+ compare(seqA, seqB) {
75
+ return exports.ByteUtils.toLocalBufferType(seqA).compare(seqB);
76
+ },
77
+ toBase64(uint8array) {
78
+ return exports.ByteUtils.toLocalBufferType(uint8array).toString('base64');
79
+ }
80
+ };
81
+ /**
82
+ * Returns true if value is a Uint8Array or a Buffer
83
+ * @param value - any value that may be a Uint8Array
84
+ */
85
+ function isUint8Array(value) {
86
+ return (value != null &&
87
+ typeof value === 'object' &&
88
+ Symbol.toStringTag in value &&
89
+ value[Symbol.toStringTag] === 'Uint8Array');
90
+ }
91
+ /**
92
+ * Determines if a connection's address matches a user provided list
93
+ * of domain wildcards.
94
+ */
95
+ function hostMatchesWildcards(host, wildcards) {
96
+ for (const wildcard of wildcards) {
97
+ if (host === wildcard ||
98
+ (wildcard.startsWith('*.') && host?.endsWith(wildcard.substring(2, wildcard.length))) ||
99
+ (wildcard.startsWith('*/') && host?.endsWith(wildcard.substring(2, wildcard.length)))) {
100
+ return true;
101
+ }
102
+ }
103
+ return false;
104
+ }
105
+ /**
106
+ * Ensure Hint field is in a shape we expect:
107
+ * - object of index names mapping to 1 or -1
108
+ * - just an index name
109
+ * @internal
110
+ */
111
+ function normalizeHintField(hint) {
112
+ let finalHint = undefined;
113
+ if (typeof hint === 'string') {
114
+ finalHint = hint;
115
+ }
116
+ else if (Array.isArray(hint)) {
117
+ finalHint = {};
118
+ hint.forEach(param => {
119
+ finalHint[param] = 1;
120
+ });
121
+ }
122
+ else if (hint != null && typeof hint === 'object') {
123
+ finalHint = {};
124
+ for (const name in hint) {
125
+ finalHint[name] = hint[name];
126
+ }
127
+ }
128
+ return finalHint;
129
+ }
130
+ const TO_STRING = (object) => Object.prototype.toString.call(object);
131
+ /**
132
+ * Checks if arg is an Object:
133
+ * - **NOTE**: the check is based on the `[Symbol.toStringTag]() === 'Object'`
134
+ * @internal
135
+ */
136
+ function isObject(arg) {
137
+ return '[object Object]' === TO_STRING(arg);
138
+ }
139
+ /** @internal */
140
+ function mergeOptions(target, source) {
141
+ return { ...target, ...source };
142
+ }
143
+ /** @internal */
144
+ function filterOptions(options, names) {
145
+ const filterOptions = {};
146
+ for (const name in options) {
147
+ if (names.includes(name)) {
148
+ filterOptions[name] = options[name];
149
+ }
150
+ }
151
+ // Filtered options
152
+ return filterOptions;
153
+ }
154
+ /**
155
+ * Applies a write concern to a command based on well defined inheritance rules, optionally
156
+ * detecting support for the write concern in the first place.
157
+ * @internal
158
+ *
159
+ * @param target - the target command we will be applying the write concern to
160
+ * @param sources - sources where we can inherit default write concerns from
161
+ * @param options - optional settings passed into a command for write concern overrides
162
+ */
163
+ /**
164
+ * Checks if a given value is a Promise
165
+ *
166
+ * @typeParam T - The resolution type of the possible promise
167
+ * @param value - An object that could be a promise
168
+ * @returns true if the provided value is a Promise
169
+ */
170
+ function isPromiseLike(value) {
171
+ return (value != null &&
172
+ typeof value === 'object' &&
173
+ 'then' in value &&
174
+ typeof value.then === 'function');
175
+ }
176
+ /**
177
+ * Applies collation to a given command.
178
+ * @internal
179
+ *
180
+ * @param command - the command on which to apply collation
181
+ * @param target - target of command
182
+ * @param options - options containing collation settings
183
+ */
184
+ function decorateWithCollation(command, options) {
185
+ if (options.collation && typeof options.collation === 'object') {
186
+ command.collation = options.collation;
187
+ }
188
+ }
189
+ /**
190
+ * Applies a read concern to a given command.
191
+ * @internal
192
+ *
193
+ * @param command - the command on which to apply the read concern
194
+ * @param coll - the parent collection of the operation calling this method
195
+ */
196
+ function decorateWithReadConcern(command, coll, options) {
197
+ if (options && options.session && options.session.inTransaction()) {
198
+ return;
199
+ }
200
+ const readConcern = Object.assign({}, command.readConcern || {});
201
+ if (coll.s.readConcern) {
202
+ Object.assign(readConcern, coll.s.readConcern);
203
+ }
204
+ if (Object.keys(readConcern).length > 0) {
205
+ Object.assign(command, { readConcern: readConcern });
206
+ }
207
+ }
208
+ /**
209
+ * A helper function to get the topology from a given provider. Throws
210
+ * if the topology cannot be found.
211
+ * @throws MongoNotConnectedError
212
+ * @internal
213
+ */
214
+ function getTopology(provider) {
215
+ // MongoClient or ClientSession or AbstractCursor
216
+ if ('topology' in provider && provider.topology) {
217
+ return provider.topology;
218
+ }
219
+ else if ('client' in provider && provider.client.topology) {
220
+ return provider.client.topology;
221
+ }
222
+ throw new error_1.MongoNotConnectedError('MongoClient must be connected to perform this operation');
223
+ }
224
+ /** @internal */
225
+ function ns(ns) {
226
+ return MongoDBNamespace.fromString(ns);
227
+ }
228
+ /** @public */
229
+ class MongoDBNamespace {
230
+ /**
231
+ * Create a namespace object
232
+ *
233
+ * @param db - database name
234
+ * @param collection - collection name
235
+ */
236
+ constructor(db, collection) {
237
+ this.db = db;
238
+ this.collection = collection === '' ? undefined : collection;
239
+ }
240
+ toString() {
241
+ return this.collection ? `${this.db}.${this.collection}` : this.db;
242
+ }
243
+ withCollection(collection) {
244
+ return new MongoDBCollectionNamespace(this.db, collection);
245
+ }
246
+ static fromString(namespace) {
247
+ if (typeof namespace !== 'string' || namespace === '') {
248
+ // TODO(NODE-3483): Replace with MongoNamespaceError
249
+ throw new error_1.MongoRuntimeError(`Cannot parse namespace from "${namespace}"`);
250
+ }
251
+ const [db, ...collectionParts] = namespace.split('.');
252
+ const collection = collectionParts.join('.');
253
+ return new MongoDBNamespace(db, collection === '' ? undefined : collection);
254
+ }
255
+ }
256
+ exports.MongoDBNamespace = MongoDBNamespace;
257
+ /**
258
+ * @public
259
+ *
260
+ * A class representing a collection's namespace. This class enforces (through Typescript) that
261
+ * the `collection` portion of the namespace is defined and should only be
262
+ * used in scenarios where this can be guaranteed.
263
+ */
264
+ class MongoDBCollectionNamespace extends MongoDBNamespace {
265
+ constructor(db, collection) {
266
+ super(db, collection);
267
+ this.collection = collection;
268
+ }
269
+ static fromString(namespace) {
270
+ return super.fromString(namespace);
271
+ }
272
+ }
273
+ exports.MongoDBCollectionNamespace = MongoDBCollectionNamespace;
274
+ /** @internal */
275
+ function* makeCounter(seed = 0) {
276
+ let count = seed;
277
+ while (true) {
278
+ const newCount = count;
279
+ count += 1;
280
+ yield newCount;
281
+ }
282
+ }
283
+ /**
284
+ * Synchronously Generate a UUIDv4
285
+ * @internal
286
+ */
287
+ function uuidV4() {
288
+ const result = crypto.randomBytes(16);
289
+ result[6] = (result[6] & 0x0f) | 0x40;
290
+ result[8] = (result[8] & 0x3f) | 0x80;
291
+ return result;
292
+ }
293
+ /**
294
+ * A helper function for determining `maxWireVersion` between legacy and new topology instances
295
+ * @internal
296
+ */
297
+ function maxWireVersion(handshakeAware) {
298
+ if (handshakeAware) {
299
+ if (handshakeAware.hello) {
300
+ return handshakeAware.hello.maxWireVersion;
301
+ }
302
+ if (handshakeAware.serverApi?.version) {
303
+ // We return the max supported wire version for serverAPI.
304
+ return constants_1.MAX_SUPPORTED_WIRE_VERSION;
305
+ }
306
+ // This is the fallback case for load balanced mode. If we are building commands the
307
+ // object being checked will be a connection, and we will have a hello response on
308
+ // it. For other cases, such as retryable writes, the object will be a server or
309
+ // topology, and there will be no hello response on those objects, so we return
310
+ // the max wire version so we support retryability. Once we have a min supported
311
+ // wire version of 9, then the needsRetryableWriteLabel() check can remove the
312
+ // usage of passing the wire version into it.
313
+ if (handshakeAware.loadBalanced) {
314
+ return constants_1.MAX_SUPPORTED_WIRE_VERSION;
315
+ }
316
+ if ('lastHello' in handshakeAware && typeof handshakeAware.lastHello === 'function') {
317
+ const lastHello = handshakeAware.lastHello();
318
+ if (lastHello) {
319
+ return lastHello.maxWireVersion;
320
+ }
321
+ }
322
+ if (handshakeAware.description &&
323
+ 'maxWireVersion' in handshakeAware.description &&
324
+ handshakeAware.description.maxWireVersion != null) {
325
+ return handshakeAware.description.maxWireVersion;
326
+ }
327
+ }
328
+ return 0;
329
+ }
330
+ /** @internal */
331
+ function arrayStrictEqual(arr, arr2) {
332
+ if (!Array.isArray(arr) || !Array.isArray(arr2)) {
333
+ return false;
334
+ }
335
+ return arr.length === arr2.length && arr.every((elt, idx) => elt === arr2[idx]);
336
+ }
337
+ /** @internal */
338
+ function errorStrictEqual(lhs, rhs) {
339
+ if (lhs === rhs) {
340
+ return true;
341
+ }
342
+ if (!lhs || !rhs) {
343
+ return lhs === rhs;
344
+ }
345
+ if ((lhs == null && rhs != null) || (lhs != null && rhs == null)) {
346
+ return false;
347
+ }
348
+ if (lhs.constructor.name !== rhs.constructor.name) {
349
+ return false;
350
+ }
351
+ if (lhs.message !== rhs.message) {
352
+ return false;
353
+ }
354
+ return true;
355
+ }
356
+ /** @internal */
357
+ function makeStateMachine(stateTable) {
358
+ return function stateTransition(target, newState) {
359
+ const legalStates = stateTable[target.s.state];
360
+ if (legalStates && legalStates.indexOf(newState) < 0) {
361
+ throw new error_1.MongoRuntimeError(`illegal state transition from [${target.s.state}] => [${newState}], allowed: [${legalStates}]`);
362
+ }
363
+ target.emit('stateChanged', target.s.state, newState);
364
+ target.s.state = newState;
365
+ };
366
+ }
367
+ /**
368
+ * This function returns the number of milliseconds since an arbitrary point in time.
369
+ * This function should only be used to measure time intervals.
370
+ * @internal
371
+ * */
372
+ function processTimeMS() {
373
+ return Math.floor(performance.now());
374
+ }
375
+ /** @internal */
376
+ function calculateDurationInMs(started) {
377
+ if (typeof started !== 'number') {
378
+ return -1;
379
+ }
380
+ const elapsed = processTimeMS() - started;
381
+ return elapsed < 0 ? 0 : elapsed;
382
+ }
383
+ /** @internal */
384
+ function hasAtomicOperators(doc, options) {
385
+ if (Array.isArray(doc)) {
386
+ for (const document of doc) {
387
+ if (hasAtomicOperators(document)) {
388
+ return true;
389
+ }
390
+ }
391
+ return false;
392
+ }
393
+ const keys = Object.keys(doc);
394
+ // In this case we need to throw if all the atomic operators are undefined.
395
+ if (options?.ignoreUndefined) {
396
+ let allUndefined = true;
397
+ for (const key of keys) {
398
+ // eslint-disable-next-line no-restricted-syntax
399
+ if (doc[key] !== undefined) {
400
+ allUndefined = false;
401
+ break;
402
+ }
403
+ }
404
+ if (allUndefined) {
405
+ throw new error_1.MongoInvalidArgumentError('Update operations require that all atomic operators have defined values, but none were provided.');
406
+ }
407
+ }
408
+ return keys.length > 0 && keys[0][0] === '$';
409
+ }
410
+ function resolveTimeoutOptions(client, options) {
411
+ const { socketTimeoutMS, serverSelectionTimeoutMS, waitQueueTimeoutMS, timeoutMS } = client.s.options;
412
+ return { socketTimeoutMS, serverSelectionTimeoutMS, waitQueueTimeoutMS, timeoutMS, ...options };
413
+ }
414
+ /**
415
+ * Merge inherited properties from parent into options, prioritizing values from options,
416
+ * then values from parent.
417
+ *
418
+ * @param parent - An optional owning class of the operation being run. ex. Db/Collection/MongoClient.
419
+ * @param options - The options passed to the operation method.
420
+ *
421
+ * @internal
422
+ */
423
+ function resolveOptions(parent, options) {
424
+ const result = Object.assign({}, options, (0, bson_1.resolveBSONOptions)(options, parent));
425
+ const timeoutMS = options?.timeoutMS ?? parent?.timeoutMS;
426
+ // Users cannot pass a readConcern/writeConcern to operations in a transaction
427
+ const session = options?.session;
428
+ if (!session?.inTransaction()) {
429
+ const readConcern = read_concern_1.ReadConcern.fromOptions(options) ?? parent?.readConcern;
430
+ if (readConcern) {
431
+ result.readConcern = readConcern;
432
+ }
433
+ let writeConcern = write_concern_1.WriteConcern.fromOptions(options) ?? parent?.writeConcern;
434
+ if (writeConcern) {
435
+ if (timeoutMS != null) {
436
+ writeConcern = write_concern_1.WriteConcern.fromOptions({
437
+ writeConcern: {
438
+ ...writeConcern,
439
+ wtimeout: undefined,
440
+ wtimeoutMS: undefined
441
+ }
442
+ });
443
+ }
444
+ result.writeConcern = writeConcern;
445
+ }
446
+ }
447
+ result.timeoutMS = timeoutMS;
448
+ const readPreference = read_preference_1.ReadPreference.fromOptions(options) ?? parent?.readPreference;
449
+ if (readPreference) {
450
+ result.readPreference = readPreference;
451
+ }
452
+ const isConvenientTransaction = session?.explicit && session?.timeoutContext != null;
453
+ if (isConvenientTransaction && options?.timeoutMS != null) {
454
+ throw new error_1.MongoInvalidArgumentError('An operation cannot be given a timeoutMS setting when inside a withTransaction call that has a timeoutMS setting');
455
+ }
456
+ return result;
457
+ }
458
+ function isSuperset(set, subset) {
459
+ set = Array.isArray(set) ? new Set(set) : set;
460
+ subset = Array.isArray(subset) ? new Set(subset) : subset;
461
+ for (const elem of subset) {
462
+ if (!set.has(elem)) {
463
+ return false;
464
+ }
465
+ }
466
+ return true;
467
+ }
468
+ /**
469
+ * Checks if the document is a Hello request
470
+ * @internal
471
+ */
472
+ function isHello(doc) {
473
+ return doc[constants_2.LEGACY_HELLO_COMMAND] || doc.hello ? true : false;
474
+ }
475
+ /** Returns the items that are uniquely in setA */
476
+ function setDifference(setA, setB) {
477
+ const difference = new Set(setA);
478
+ for (const elem of setB) {
479
+ difference.delete(elem);
480
+ }
481
+ return difference;
482
+ }
483
+ const HAS_OWN = (object, prop) => Object.prototype.hasOwnProperty.call(object, prop);
484
+ function isRecord(value, requiredKeys = undefined) {
485
+ if (!isObject(value)) {
486
+ return false;
487
+ }
488
+ const ctor = value.constructor;
489
+ if (ctor && ctor.prototype) {
490
+ if (!isObject(ctor.prototype)) {
491
+ return false;
492
+ }
493
+ // Check to see if some method exists from the Object exists
494
+ if (!HAS_OWN(ctor.prototype, 'isPrototypeOf')) {
495
+ return false;
496
+ }
497
+ }
498
+ if (requiredKeys) {
499
+ const keys = Object.keys(value);
500
+ return isSuperset(keys, requiredKeys);
501
+ }
502
+ return true;
503
+ }
504
+ /**
505
+ * A sequential list of items in a circularly linked list
506
+ * @remarks
507
+ * The head node is special, it is always defined and has a value of null.
508
+ * It is never "included" in the list, in that, it is not returned by pop/shift or yielded by the iterator.
509
+ * The circular linkage and always defined head node are to reduce checks for null next/prev references to zero.
510
+ * New nodes are declared as object literals with keys always in the same order: next, prev, value.
511
+ * @internal
512
+ */
513
+ class List {
514
+ get length() {
515
+ return this.count;
516
+ }
517
+ get [Symbol.toStringTag]() {
518
+ return 'List';
519
+ }
520
+ constructor() {
521
+ this.count = 0;
522
+ // this is carefully crafted:
523
+ // declaring a complete and consistently key ordered
524
+ // object is beneficial to the runtime optimizations
525
+ this.head = {
526
+ next: null,
527
+ prev: null,
528
+ value: null
529
+ };
530
+ this.head.next = this.head;
531
+ this.head.prev = this.head;
532
+ }
533
+ toArray() {
534
+ return Array.from(this);
535
+ }
536
+ toString() {
537
+ return `head <=> ${this.toArray().join(' <=> ')} <=> head`;
538
+ }
539
+ *[Symbol.iterator]() {
540
+ for (const node of this.nodes()) {
541
+ yield node.value;
542
+ }
543
+ }
544
+ *nodes() {
545
+ let ptr = this.head.next;
546
+ while (ptr !== this.head) {
547
+ // Save next before yielding so that we make removing within iteration safe
548
+ const { next } = ptr;
549
+ yield ptr;
550
+ ptr = next;
551
+ }
552
+ }
553
+ /** Insert at end of list */
554
+ push(value) {
555
+ this.count += 1;
556
+ const newNode = {
557
+ next: this.head,
558
+ prev: this.head.prev,
559
+ value
560
+ };
561
+ this.head.prev.next = newNode;
562
+ this.head.prev = newNode;
563
+ }
564
+ /** Inserts every item inside an iterable instead of the iterable itself */
565
+ pushMany(iterable) {
566
+ for (const value of iterable) {
567
+ this.push(value);
568
+ }
569
+ }
570
+ /** Insert at front of list */
571
+ unshift(value) {
572
+ this.count += 1;
573
+ const newNode = {
574
+ next: this.head.next,
575
+ prev: this.head,
576
+ value
577
+ };
578
+ this.head.next.prev = newNode;
579
+ this.head.next = newNode;
580
+ }
581
+ remove(node) {
582
+ if (node === this.head || this.length === 0) {
583
+ return null;
584
+ }
585
+ this.count -= 1;
586
+ const prevNode = node.prev;
587
+ const nextNode = node.next;
588
+ prevNode.next = nextNode;
589
+ nextNode.prev = prevNode;
590
+ return node.value;
591
+ }
592
+ /** Removes the first node at the front of the list */
593
+ shift() {
594
+ return this.remove(this.head.next);
595
+ }
596
+ /** Removes the last node at the end of the list */
597
+ pop() {
598
+ return this.remove(this.head.prev);
599
+ }
600
+ /** Iterates through the list and removes nodes where filter returns true */
601
+ prune(filter) {
602
+ for (const node of this.nodes()) {
603
+ if (filter(node.value)) {
604
+ this.remove(node);
605
+ }
606
+ }
607
+ }
608
+ clear() {
609
+ this.count = 0;
610
+ this.head.next = this.head;
611
+ this.head.prev = this.head;
612
+ }
613
+ /** Returns the first item in the list, does not remove */
614
+ first() {
615
+ // If the list is empty, value will be the head's null
616
+ return this.head.next.value;
617
+ }
618
+ /** Returns the last item in the list, does not remove */
619
+ last() {
620
+ // If the list is empty, value will be the head's null
621
+ return this.head.prev.value;
622
+ }
623
+ }
624
+ exports.List = List;
625
+ /**
626
+ * A pool of Buffers which allow you to read them as if they were one
627
+ * @internal
628
+ */
629
+ class BufferPool {
630
+ constructor() {
631
+ this.buffers = new List();
632
+ this.totalByteLength = 0;
633
+ }
634
+ get length() {
635
+ return this.totalByteLength;
636
+ }
637
+ /** Adds a buffer to the internal buffer pool list */
638
+ append(buffer) {
639
+ this.buffers.push(buffer);
640
+ this.totalByteLength += buffer.length;
641
+ }
642
+ /**
643
+ * If BufferPool contains 4 bytes or more construct an int32 from the leading bytes,
644
+ * otherwise return null. Size can be negative, caller should error check.
645
+ */
646
+ getInt32() {
647
+ if (this.totalByteLength < 4) {
648
+ return null;
649
+ }
650
+ const firstBuffer = this.buffers.first();
651
+ if (firstBuffer != null && firstBuffer.byteLength >= 4) {
652
+ return firstBuffer.readInt32LE(0);
653
+ }
654
+ // Unlikely case: an int32 is split across buffers.
655
+ // Use read and put the returned buffer back on top
656
+ const top4Bytes = this.read(4);
657
+ const value = top4Bytes.readInt32LE(0);
658
+ // Put it back.
659
+ this.totalByteLength += 4;
660
+ this.buffers.unshift(top4Bytes);
661
+ return value;
662
+ }
663
+ /** Reads the requested number of bytes, optionally consuming them */
664
+ read(size) {
665
+ if (typeof size !== 'number' || size < 0) {
666
+ throw new error_1.MongoInvalidArgumentError('Argument "size" must be a non-negative number');
667
+ }
668
+ // oversized request returns empty buffer
669
+ if (size > this.totalByteLength) {
670
+ return Buffer.alloc(0);
671
+ }
672
+ // We know we have enough, we just don't know how it is spread across chunks
673
+ // TODO(NODE-4732): alloc API should change based on raw option
674
+ const result = Buffer.allocUnsafe(size);
675
+ for (let bytesRead = 0; bytesRead < size;) {
676
+ const buffer = this.buffers.shift();
677
+ if (buffer == null) {
678
+ break;
679
+ }
680
+ const bytesRemaining = size - bytesRead;
681
+ const bytesReadable = Math.min(bytesRemaining, buffer.byteLength);
682
+ const bytes = buffer.subarray(0, bytesReadable);
683
+ result.set(bytes, bytesRead);
684
+ bytesRead += bytesReadable;
685
+ this.totalByteLength -= bytesReadable;
686
+ if (bytesReadable < buffer.byteLength) {
687
+ this.buffers.unshift(buffer.subarray(bytesReadable));
688
+ }
689
+ }
690
+ return result;
691
+ }
692
+ }
693
+ exports.BufferPool = BufferPool;
694
+ /** @public */
695
+ class HostAddress {
696
+ constructor(hostString) {
697
+ this.host = undefined;
698
+ this.port = undefined;
699
+ this.socketPath = undefined;
700
+ this.isIPv6 = false;
701
+ const escapedHost = hostString.split(' ').join('%20'); // escape spaces, for socket path hosts
702
+ if (escapedHost.endsWith('.sock')) {
703
+ // heuristically determine if we're working with a domain socket
704
+ this.socketPath = decodeURIComponent(escapedHost);
705
+ return;
706
+ }
707
+ const urlString = `iLoveJS://${escapedHost}`;
708
+ let url;
709
+ try {
710
+ url = new URL(urlString);
711
+ }
712
+ catch (urlError) {
713
+ const runtimeError = new error_1.MongoRuntimeError(`Unable to parse ${escapedHost} with URL`);
714
+ runtimeError.cause = urlError;
715
+ throw runtimeError;
716
+ }
717
+ const hostname = url.hostname;
718
+ const port = url.port;
719
+ let normalized = decodeURIComponent(hostname).toLowerCase();
720
+ if (normalized.startsWith('[') && normalized.endsWith(']')) {
721
+ this.isIPv6 = true;
722
+ normalized = normalized.substring(1, hostname.length - 1);
723
+ }
724
+ this.host = normalized.toLowerCase();
725
+ if (typeof port === 'number') {
726
+ this.port = port;
727
+ }
728
+ else if (typeof port === 'string' && port !== '') {
729
+ this.port = Number.parseInt(port, 10);
730
+ }
731
+ else {
732
+ this.port = 27017;
733
+ }
734
+ if (this.port === 0) {
735
+ throw new error_1.MongoParseError('Invalid port (zero) with hostname');
736
+ }
737
+ Object.freeze(this);
738
+ }
739
+ [Symbol.for('nodejs.util.inspect.custom')]() {
740
+ return this.inspect();
741
+ }
742
+ inspect() {
743
+ return `new HostAddress('${this.toString()}')`;
744
+ }
745
+ toString() {
746
+ if (typeof this.host === 'string') {
747
+ if (this.isIPv6) {
748
+ return `[${this.host}]:${this.port}`;
749
+ }
750
+ return `${this.host}:${this.port}`;
751
+ }
752
+ return `${this.socketPath}`;
753
+ }
754
+ static fromString(s) {
755
+ return new HostAddress(s);
756
+ }
757
+ static fromHostPort(host, port) {
758
+ if (host.includes(':')) {
759
+ host = `[${host}]`; // IPv6 address
760
+ }
761
+ return HostAddress.fromString(`${host}:${port}`);
762
+ }
763
+ static fromSrvRecord({ name, port }) {
764
+ return HostAddress.fromHostPort(name, port);
765
+ }
766
+ toHostPort() {
767
+ if (this.socketPath) {
768
+ return { host: this.socketPath, port: 0 };
769
+ }
770
+ const host = this.host ?? '';
771
+ const port = this.port ?? 0;
772
+ return { host, port };
773
+ }
774
+ }
775
+ exports.HostAddress = HostAddress;
776
+ exports.DEFAULT_PK_FACTORY = {
777
+ // We prefer not to rely on ObjectId having a createPk method
778
+ createPk() {
779
+ return new bson_1.ObjectId();
780
+ }
781
+ };
782
+ /**
783
+ * When the driver used emitWarning the code will be equal to this.
784
+ * @public
785
+ *
786
+ * @example
787
+ * ```ts
788
+ * process.on('warning', (warning) => {
789
+ * if (warning.code === MONGODB_WARNING_CODE) console.error('Ah an important warning! :)')
790
+ * })
791
+ * ```
792
+ */
793
+ exports.MONGODB_WARNING_CODE = 'MONGODB DRIVER';
794
+ /** @internal */
795
+ function emitWarning(message) {
796
+ return process.emitWarning(message, { code: exports.MONGODB_WARNING_CODE });
797
+ }
798
+ const emittedWarnings = new Set();
799
+ /**
800
+ * Will emit a warning once for the duration of the application.
801
+ * Uses the message to identify if it has already been emitted
802
+ * so using string interpolation can cause multiple emits
803
+ * @internal
804
+ */
805
+ function emitWarningOnce(message) {
806
+ if (!emittedWarnings.has(message)) {
807
+ emittedWarnings.add(message);
808
+ return emitWarning(message);
809
+ }
810
+ }
811
+ /**
812
+ * Takes a JS object and joins the values into a string separated by ', '
813
+ */
814
+ function enumToString(en) {
815
+ return Object.values(en).join(', ');
816
+ }
817
+ /**
818
+ * Determine if a server supports retryable writes.
819
+ *
820
+ * @internal
821
+ */
822
+ function supportsRetryableWrites(server) {
823
+ if (!server) {
824
+ return false;
825
+ }
826
+ if (server.loadBalanced) {
827
+ // Loadbalanced topologies will always support retry writes
828
+ return true;
829
+ }
830
+ if (server.description.logicalSessionTimeoutMinutes != null) {
831
+ // that supports sessions
832
+ if (server.description.type !== common_1.ServerType.Standalone) {
833
+ // and that is not a standalone
834
+ return true;
835
+ }
836
+ }
837
+ return false;
838
+ }
839
+ /**
840
+ * Fisher–Yates Shuffle
841
+ *
842
+ * Reference: https://bost.ocks.org/mike/shuffle/
843
+ * @param sequence - items to be shuffled
844
+ * @param limit - Defaults to `0`. If nonzero shuffle will slice the randomized array e.g, `.slice(0, limit)` otherwise will return the entire randomized array.
845
+ */
846
+ function shuffle(sequence, limit = 0) {
847
+ const items = Array.from(sequence); // shallow copy in order to never shuffle the input
848
+ if (limit > items.length) {
849
+ throw new error_1.MongoRuntimeError('Limit must be less than the number of items');
850
+ }
851
+ let remainingItemsToShuffle = items.length;
852
+ const lowerBound = limit % items.length === 0 ? 1 : items.length - limit;
853
+ while (remainingItemsToShuffle > lowerBound) {
854
+ // Pick a remaining element
855
+ const randomIndex = Math.floor(Math.random() * remainingItemsToShuffle);
856
+ remainingItemsToShuffle -= 1;
857
+ // And swap it with the current element
858
+ const swapHold = items[remainingItemsToShuffle];
859
+ items[remainingItemsToShuffle] = items[randomIndex];
860
+ items[randomIndex] = swapHold;
861
+ }
862
+ return limit % items.length === 0 ? items : items.slice(lowerBound);
863
+ }
864
+ /**
865
+ * TODO(NODE-4936): read concern eligibility for commands should be codified in command construction
866
+ * @internal
867
+ * @see https://github.com/mongodb/specifications/blob/master/source/read-write-concern/read-write-concern.md#read-concern
868
+ */
869
+ function commandSupportsReadConcern(command) {
870
+ if (command.aggregate || command.count || command.distinct || command.find || command.geoNear) {
871
+ return true;
872
+ }
873
+ return false;
874
+ }
875
+ /**
876
+ * Compare objectIds. `null` is always less
877
+ * - `+1 = oid1 is greater than oid2`
878
+ * - `-1 = oid1 is less than oid2`
879
+ * - `+0 = oid1 is equal oid2`
880
+ */
881
+ function compareObjectId(oid1, oid2) {
882
+ if (oid1 == null && oid2 == null) {
883
+ return 0;
884
+ }
885
+ if (oid1 == null) {
886
+ return -1;
887
+ }
888
+ if (oid2 == null) {
889
+ return 1;
890
+ }
891
+ return exports.ByteUtils.compare(oid1.id, oid2.id);
892
+ }
893
+ function parseInteger(value) {
894
+ if (typeof value === 'number')
895
+ return Math.trunc(value);
896
+ const parsedValue = Number.parseInt(String(value), 10);
897
+ return Number.isNaN(parsedValue) ? null : parsedValue;
898
+ }
899
+ function parseUnsignedInteger(value) {
900
+ const parsedInt = parseInteger(value);
901
+ return parsedInt != null && parsedInt >= 0 ? parsedInt : null;
902
+ }
903
+ /**
904
+ * This function throws a MongoAPIError in the event that either of the following is true:
905
+ * * If the provided address domain does not match the provided parent domain
906
+ * * If the parent domain contains less than three `.` separated parts and the provided address does not contain at least one more domain level than its parent
907
+ *
908
+ * If a DNS server were to become compromised SRV records would still need to
909
+ * advertise addresses that are under the same domain as the srvHost.
910
+ *
911
+ * @param address - The address to check against a domain
912
+ * @param srvHost - The domain to check the provided address against
913
+ * @returns void
914
+ */
915
+ function checkParentDomainMatch(address, srvHost) {
916
+ // Remove trailing dot if exists on either the resolved address or the srv hostname
917
+ const normalizedAddress = address.endsWith('.') ? address.slice(0, address.length - 1) : address;
918
+ const normalizedSrvHost = srvHost.endsWith('.') ? srvHost.slice(0, srvHost.length - 1) : srvHost;
919
+ const allCharacterBeforeFirstDot = /^.*?\./;
920
+ const srvIsLessThanThreeParts = normalizedSrvHost.split('.').length < 3;
921
+ // Remove all characters before first dot
922
+ // Add leading dot back to string so
923
+ // an srvHostDomain = '.trusted.site'
924
+ // will not satisfy an addressDomain that endsWith '.fake-trusted.site'
925
+ const addressDomain = `.${normalizedAddress.replace(allCharacterBeforeFirstDot, '')}`;
926
+ let srvHostDomain = srvIsLessThanThreeParts
927
+ ? normalizedSrvHost
928
+ : `.${normalizedSrvHost.replace(allCharacterBeforeFirstDot, '')}`;
929
+ if (!srvHostDomain.startsWith('.')) {
930
+ srvHostDomain = '.' + srvHostDomain;
931
+ }
932
+ if (srvIsLessThanThreeParts &&
933
+ normalizedAddress.split('.').length <= normalizedSrvHost.split('.').length) {
934
+ throw new error_1.MongoAPIError('Server record does not have at least one more domain level than parent URI');
935
+ }
936
+ if (!addressDomain.endsWith(srvHostDomain)) {
937
+ throw new error_1.MongoAPIError('Server record does not share hostname with parent URI');
938
+ }
939
+ }
940
+ /**
941
+ * Perform a get request that returns status and body.
942
+ * @internal
943
+ */
944
+ function get(url, options = {}) {
945
+ return new Promise((resolve, reject) => {
946
+ /* eslint-disable prefer-const */
947
+ let timeoutId;
948
+ const request = http
949
+ .get(url, options, response => {
950
+ response.setEncoding('utf8');
951
+ let body = '';
952
+ response.on('data', chunk => (body += chunk));
953
+ response.on('end', () => {
954
+ (0, timers_1.clearTimeout)(timeoutId);
955
+ resolve({ status: response.statusCode, body });
956
+ });
957
+ })
958
+ .on('error', error => {
959
+ (0, timers_1.clearTimeout)(timeoutId);
960
+ reject(error);
961
+ })
962
+ .end();
963
+ timeoutId = (0, timers_1.setTimeout)(() => {
964
+ request.destroy(new error_1.MongoNetworkTimeoutError(`request timed out after 10 seconds`));
965
+ }, 10000);
966
+ });
967
+ }
968
+ /** @internal */
969
+ exports.DOCUMENT_DB_CHECK = /(\.docdb\.amazonaws\.com$)|(\.docdb-elastic\.amazonaws\.com$)/;
970
+ /** @internal */
971
+ exports.COSMOS_DB_CHECK = /\.cosmos\.azure\.com$/;
972
+ /** @internal */
973
+ exports.DOCUMENT_DB_MSG = 'You appear to be connected to a DocumentDB cluster. For more information regarding feature compatibility and support please visit https://www.mongodb.com/supportability/documentdb';
974
+ /** @internal */
975
+ exports.COSMOS_DB_MSG = 'You appear to be connected to a CosmosDB cluster. For more information regarding feature compatibility and support please visit https://www.mongodb.com/supportability/cosmosdb';
976
+ /** @internal */
977
+ function isHostMatch(match, host) {
978
+ return host && match.test(host.toLowerCase()) ? true : false;
979
+ }
980
+ function promiseWithResolvers() {
981
+ let resolve;
982
+ let reject;
983
+ const promise = new Promise(function withResolversExecutor(promiseResolve, promiseReject) {
984
+ resolve = promiseResolve;
985
+ reject = promiseReject;
986
+ });
987
+ return { promise, resolve, reject };
988
+ }
989
+ /**
990
+ * A noop function intended for use in preventing unhandled rejections.
991
+ *
992
+ * @example
993
+ * ```js
994
+ * const promise = myAsyncTask();
995
+ * // eslint-disable-next-line github/no-then
996
+ * promise.then(undefined, squashError);
997
+ * ```
998
+ */
999
+ function squashError(_error) {
1000
+ return;
1001
+ }
1002
+ const randomBytes = (size) => {
1003
+ return new Promise((resolve, reject) => {
1004
+ crypto.randomBytes(size, (error, buf) => {
1005
+ if (error)
1006
+ return reject(error);
1007
+ resolve(buf);
1008
+ });
1009
+ });
1010
+ };
1011
+ exports.randomBytes = randomBytes;
1012
+ /**
1013
+ * Replicates the events.once helper.
1014
+ *
1015
+ * Removes unused signal logic and It **only** supports 0 or 1 argument events.
1016
+ *
1017
+ * @param ee - An event emitter that may emit `ev`
1018
+ * @param name - An event name to wait for
1019
+ */
1020
+ async function once(ee, name, options) {
1021
+ options?.signal?.throwIfAborted();
1022
+ const { promise, resolve, reject } = promiseWithResolvers();
1023
+ const onEvent = (data) => resolve(data);
1024
+ const onError = (error) => reject(error);
1025
+ const abortListener = addAbortListener(options?.signal, function () {
1026
+ reject(this.reason);
1027
+ });
1028
+ ee.once(name, onEvent).once('error', onError);
1029
+ try {
1030
+ return await promise;
1031
+ }
1032
+ finally {
1033
+ ee.off(name, onEvent);
1034
+ ee.off('error', onError);
1035
+ abortListener?.[exports.kDispose]();
1036
+ }
1037
+ }
1038
+ function maybeAddIdToDocuments(collection, document, options) {
1039
+ const forceServerObjectId = options.forceServerObjectId ?? collection.db.options?.forceServerObjectId ?? false;
1040
+ // no need to modify the docs if server sets the ObjectId
1041
+ if (forceServerObjectId) {
1042
+ return document;
1043
+ }
1044
+ if (document._id == null) {
1045
+ document._id = collection.s.pkFactory.createPk();
1046
+ }
1047
+ return document;
1048
+ }
1049
+ async function fileIsAccessible(fileName, mode) {
1050
+ try {
1051
+ await fs_1.promises.access(fileName, mode);
1052
+ return true;
1053
+ }
1054
+ catch {
1055
+ return false;
1056
+ }
1057
+ }
1058
+ function csotMin(duration1, duration2) {
1059
+ if (duration1 === 0)
1060
+ return duration2;
1061
+ if (duration2 === 0)
1062
+ return duration1;
1063
+ return Math.min(duration1, duration2);
1064
+ }
1065
+ function noop() {
1066
+ return;
1067
+ }
1068
+ /**
1069
+ * Recurse through the (identically-shaped) `decrypted` and `original`
1070
+ * objects and attach a `decryptedKeys` property on each sub-object that
1071
+ * contained encrypted fields. Because we only call this on BSON responses,
1072
+ * we do not need to worry about circular references.
1073
+ *
1074
+ * @internal
1075
+ */
1076
+ function decorateDecryptionResult(decrypted, original, isTopLevelDecorateCall = true) {
1077
+ if (isTopLevelDecorateCall) {
1078
+ // The original value could have been either a JS object or a BSON buffer
1079
+ if (Buffer.isBuffer(original)) {
1080
+ original = (0, bson_1.deserialize)(original);
1081
+ }
1082
+ if (Buffer.isBuffer(decrypted)) {
1083
+ throw new error_1.MongoRuntimeError('Expected result of decryption to be deserialized BSON object');
1084
+ }
1085
+ }
1086
+ if (!decrypted || typeof decrypted !== 'object')
1087
+ return;
1088
+ for (const k of Object.keys(decrypted)) {
1089
+ const originalValue = original[k];
1090
+ // An object was decrypted by libmongocrypt if and only if it was
1091
+ // a BSON Binary object with subtype 6.
1092
+ if (originalValue && originalValue._bsontype === 'Binary' && originalValue.sub_type === 6) {
1093
+ if (!decrypted[constants_2.kDecoratedKeys]) {
1094
+ Object.defineProperty(decrypted, constants_2.kDecoratedKeys, {
1095
+ value: [],
1096
+ configurable: true,
1097
+ enumerable: false,
1098
+ writable: false
1099
+ });
1100
+ }
1101
+ // this is defined in the preceding if-statement
1102
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1103
+ decrypted[constants_2.kDecoratedKeys].push(k);
1104
+ // Do not recurse into this decrypted value. It could be a sub-document/array,
1105
+ // in which case there is no original value associated with its subfields.
1106
+ continue;
1107
+ }
1108
+ decorateDecryptionResult(decrypted[k], originalValue, false);
1109
+ }
1110
+ }
1111
+ /** @internal */
1112
+ exports.kDispose = Symbol.dispose ?? Symbol('dispose');
1113
+ /**
1114
+ * A utility that helps with writing listener code idiomatically
1115
+ *
1116
+ * @example
1117
+ * ```js
1118
+ * using listener = addAbortListener(signal, function () {
1119
+ * console.log('aborted', this.reason);
1120
+ * });
1121
+ * ```
1122
+ *
1123
+ * @param signal - if exists adds an abort listener
1124
+ * @param listener - the listener to be added to signal
1125
+ * @returns A disposable that will remove the abort listener
1126
+ */
1127
+ function addAbortListener(signal, listener) {
1128
+ if (signal == null)
1129
+ return;
1130
+ signal.addEventListener('abort', listener, { once: true });
1131
+ return { [exports.kDispose]: () => signal.removeEventListener('abort', listener) };
1132
+ }
1133
+ /**
1134
+ * Takes a promise and races it with a promise wrapping the abort event of the optionally provided signal.
1135
+ * The given promise is _always_ ordered before the signal's abort promise.
1136
+ * When given an already rejected promise and an already aborted signal, the promise's rejection takes precedence.
1137
+ *
1138
+ * Any asynchronous processing in `promise` will continue even after the abort signal has fired,
1139
+ * but control will be returned to the caller
1140
+ *
1141
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/race
1142
+ *
1143
+ * @param promise - A promise to discard if the signal aborts
1144
+ * @param options - An options object carrying an optional signal
1145
+ */
1146
+ async function abortable(promise, { signal }) {
1147
+ if (signal == null) {
1148
+ return await promise;
1149
+ }
1150
+ const { promise: aborted, reject } = promiseWithResolvers();
1151
+ const abortListener = signal.aborted
1152
+ ? reject(signal.reason)
1153
+ : addAbortListener(signal, function () {
1154
+ reject(this.reason);
1155
+ });
1156
+ try {
1157
+ return await Promise.race([promise, aborted]);
1158
+ }
1159
+ finally {
1160
+ abortListener?.[exports.kDispose]();
1161
+ }
1162
+ }
1163
+ //# sourceMappingURL=utils.js.map