opusdev/vector-similarity-api
1
1import type { DeserializeOptions } from 'bson';2import type { ObjectIdLike } from 'bson';3import type { SerializeOptions } from 'bson';4import { Binary } from 'bson';5import { BSON } from 'bson';6import { BSONRegExp } from 'bson';7import { BSONSymbol } from 'bson';8import { BSONType } from 'bson';9import { Code } from 'bson';10import { DBRef } from 'bson';11import { Decimal128 } from 'bson';12import { deserialize } from 'bson';13import { Document } from 'bson';14import { Double } from 'bson';15import { Int32 } from 'bson';16import { Long } from 'bson';17import { MaxKey } from 'bson';18import { MinKey } from 'bson';19import { ObjectId } from 'bson';20import { serialize } from 'bson';21import { Timestamp } from 'bson';22import { UUID } from 'bson';23import type { SrvRecord } from 'dns';24import { EventEmitter } from 'events';25import type { Socket } from 'net';26import type { TcpNetConnectOpts } from 'net';27import { Readable } from 'stream';28import { Writable } from 'stream';29import type { ConnectionOptions as ConnectionOptions_2 } from 'tls';30import type { TLSSocket } from 'tls';31import type { TLSSocketOptions } from 'tls';32 33/** @public */34export declare type Abortable = {35 /**36 * @experimental37 * When provided, the corresponding `AbortController` can be used to abort an asynchronous action.38 *39 * The `signal.reason` value is used as the error thrown.40 *41 * @remarks42 * **NOTE:** If an abort signal aborts an operation while the driver is writing to the underlying43 * socket or reading the response from the server, the socket will be closed.44 * If signals are aborted at a high rate during socket read/writes this can lead to a high rate of connection reestablishment.45 *46 * We plan to mitigate this in a future release, please follow NODE-6062 (`timeoutMS` expiration suffers the same limitation).47 *48 * AbortSignals are likely a best fit for human interactive interruption (ex. ctrl-C) where the frequency49 * of cancellation is reasonably low. If a signal is programmatically aborted for 100s of operations you can empty50 * the driver's connection pool.51 *52 * @example53 * ```js54 * const controller = new AbortController();55 * const { signal } = controller;56 * process.on('SIGINT', () => controller.abort(new Error('^C pressed')));57 *58 * try {59 * const res = await fetch('...', { signal });60 * await collection.findOne(await res.json(), { signal });61 * catch (error) {62 * if (error === signal.reason) {63 * // signal abort error handling64 * }65 * }66 * ```67 */68 signal?: AbortSignal | undefined;69};70 71/** @public */72export declare abstract class AbstractCursor<TSchema = any, CursorEvents extends AbstractCursorEvents = AbstractCursorEvents> extends TypedEventEmitter<CursorEvents> implements AsyncDisposable_2 {73 /* Excluded from this release type: cursorId */74 /* Excluded from this release type: cursorSession */75 /* Excluded from this release type: selectedServer */76 /* Excluded from this release type: cursorNamespace */77 /* Excluded from this release type: documents */78 /* Excluded from this release type: cursorClient */79 /* Excluded from this release type: transform */80 /* Excluded from this release type: initialized */81 /* Excluded from this release type: isClosed */82 /* Excluded from this release type: isKilled */83 /* Excluded from this release type: cursorOptions */84 /* Excluded from this release type: timeoutContext */85 /** @event */86 static readonly CLOSE: "close";87 /* Excluded from this release type: deserializationOptions */88 protected signal: AbortSignal | undefined;89 private abortListener;90 /* Excluded from this release type: __constructor */91 /**92 * The cursor has no id until it receives a response from the initial cursor creating command.93 *94 * It is non-zero for as long as the database has an open cursor.95 *96 * The initiating command may receive a zero id if the entire result is in the `firstBatch`.97 */98 get id(): Long | undefined;99 /* Excluded from this release type: isDead */100 /* Excluded from this release type: client */101 /* Excluded from this release type: server */102 get namespace(): MongoDBNamespace;103 get readPreference(): ReadPreference;104 get readConcern(): ReadConcern | undefined;105 /* Excluded from this release type: session */106 /* Excluded from this release type: session */107 /**108 * The cursor is closed and all remaining locally buffered documents have been iterated.109 */110 get closed(): boolean;111 /**112 * A `killCursors` command was attempted on this cursor.113 * This is performed if the cursor id is non zero.114 */115 get killed(): boolean;116 get loadBalanced(): boolean;117 /* Excluded from this release type: [Symbol.asyncDispose] */118 /* Excluded from this release type: asyncDispose */119 /** Adds cursor to client's tracking so it will be closed by MongoClient.close() */120 private trackCursor;121 /** Returns current buffered documents length */122 bufferedCount(): number;123 /** Returns current buffered documents */124 readBufferedDocuments(number?: number): NonNullable<TSchema>[];125 [Symbol.asyncIterator](): AsyncGenerator<TSchema, void, void>;126 stream(options?: CursorStreamOptions): Readable & AsyncIterable<TSchema>;127 hasNext(): Promise<boolean>;128 /** Get the next available document from the cursor, returns null if no more documents are available. */129 next(): Promise<TSchema | null>;130 /**131 * Try to get the next available document from the cursor or `null` if an empty batch is returned132 */133 tryNext(): Promise<TSchema | null>;134 /**135 * Iterates over all the documents for this cursor using the iterator, callback pattern.136 *137 * If the iterator returns `false`, iteration will stop.138 *139 * @param iterator - The iteration callback.140 * @deprecated - Will be removed in a future release. Use for await...of instead.141 */142 forEach(iterator: (doc: TSchema) => boolean | void): Promise<void>;143 /**144 * Frees any client-side resources used by the cursor.145 */146 close(options?: {147 timeoutMS?: number;148 }): Promise<void>;149 /**150 * Returns an array of documents. The caller is responsible for making sure that there151 * is enough memory to store the results. Note that the array only contains partial152 * results when this cursor had been previously accessed. In that case,153 * cursor.rewind() can be used to reset the cursor.154 */155 toArray(): Promise<TSchema[]>;156 /**157 * Add a cursor flag to the cursor158 *159 * @param flag - The flag to set, must be one of following ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'partial' -.160 * @param value - The flag boolean value.161 */162 addCursorFlag(flag: CursorFlag, value: boolean): this;163 /**164 * Map all documents using the provided function165 * If there is a transform set on the cursor, that will be called first and the result passed to166 * this function's transform.167 *168 * @remarks169 *170 * **Note** Cursors use `null` internally to indicate that there are no more documents in the cursor. Providing a mapping171 * function that maps values to `null` will result in the cursor closing itself before it has finished iterating172 * all documents. This will **not** result in a memory leak, just surprising behavior. For example:173 *174 * ```typescript175 * const cursor = collection.find({});176 * cursor.map(() => null);177 *178 * const documents = await cursor.toArray();179 * // documents is always [], regardless of how many documents are in the collection.180 * ```181 *182 * Other falsey values are allowed:183 *184 * ```typescript185 * const cursor = collection.find({});186 * cursor.map(() => '');187 *188 * const documents = await cursor.toArray();189 * // documents is now an array of empty strings190 * ```191 *192 * **Note for Typescript Users:** adding a transform changes the return type of the iteration of this cursor,193 * it **does not** return a new instance of a cursor. This means when calling map,194 * you should always assign the result to a new variable in order to get a correctly typed cursor variable.195 * Take note of the following example:196 *197 * @example198 * ```typescript199 * const cursor: FindCursor<Document> = coll.find();200 * const mappedCursor: FindCursor<number> = cursor.map(doc => Object.keys(doc).length);201 * const keyCounts: number[] = await mappedCursor.toArray(); // cursor.toArray() still returns Document[]202 * ```203 * @param transform - The mapping transformation method.204 */205 map<T = any>(transform: (doc: TSchema) => T): AbstractCursor<T>;206 /**207 * Set the ReadPreference for the cursor.208 *209 * @param readPreference - The new read preference for the cursor.210 */211 withReadPreference(readPreference: ReadPreferenceLike): this;212 /**213 * Set the ReadPreference for the cursor.214 *215 * @param readPreference - The new read preference for the cursor.216 */217 withReadConcern(readConcern: ReadConcernLike): this;218 /**219 * Set a maxTimeMS on the cursor query, allowing for hard timeout limits on queries (Only supported on MongoDB 2.6 or higher)220 *221 * @param value - Number of milliseconds to wait before aborting the query.222 */223 maxTimeMS(value: number): this;224 /**225 * Set the batch size for the cursor.226 *227 * @param value - The number of documents to return per batch. See {@link https://www.mongodb.com/docs/manual/reference/command/find/|find command documentation}.228 */229 batchSize(value: number): this;230 /**231 * Rewind this cursor to its uninitialized state. Any options that are present on the cursor will232 * remain in effect. Iterating this cursor will cause new queries to be sent to the server, even233 * if the resultant data has already been retrieved by this cursor.234 */235 rewind(): void;236 /**237 * Returns a new uninitialized copy of this cursor, with options matching those that have been set on the current instance238 */239 abstract clone(): AbstractCursor<TSchema>;240 /* Excluded from this release type: _initialize */241 /* Excluded from this release type: getMore */242 /* Excluded from this release type: cursorInit */243 /* Excluded from this release type: fetchBatch */244 /* Excluded from this release type: cleanup */245 /* Excluded from this release type: hasEmittedClose */246 /* Excluded from this release type: emitClose */247 /* Excluded from this release type: transformDocument */248 /* Excluded from this release type: throwIfInitialized */249}250 251/** @public */252export declare type AbstractCursorEvents = {253 [AbstractCursor.CLOSE](): void;254};255 256/** @public */257export declare interface AbstractCursorOptions extends BSONSerializeOptions {258 session?: ClientSession;259 readPreference?: ReadPreferenceLike;260 readConcern?: ReadConcernLike;261 /**262 * Specifies the number of documents to return in each response from MongoDB263 */264 batchSize?: number;265 /**266 * When applicable `maxTimeMS` controls the amount of time the initial command267 * that constructs a cursor should take. (ex. find, aggregate, listCollections)268 */269 maxTimeMS?: number;270 /**271 * When applicable `maxAwaitTimeMS` controls the amount of time subsequent getMores272 * that a cursor uses to fetch more data should take. (ex. cursor.next())273 */274 maxAwaitTimeMS?: number;275 /**276 * Comment to apply to the operation.277 *278 * In server versions pre-4.4, 'comment' must be string. A server279 * error will be thrown if any other type is provided.280 *281 * In server versions 4.4 and above, 'comment' can be any valid BSON type.282 */283 comment?: unknown;284 /**285 * By default, MongoDB will automatically close a cursor when the286 * client has exhausted all results in the cursor. However, for [capped collections](https://www.mongodb.com/docs/manual/core/capped-collections)287 * you may use a Tailable Cursor that remains open after the client exhausts288 * the results in the initial cursor.289 */290 tailable?: boolean;291 /**292 * If awaitData is set to true, when the cursor reaches the end of the capped collection,293 * MongoDB blocks the query thread for a period of time waiting for new data to arrive.294 * When new data is inserted into the capped collection, the blocked thread is signaled295 * to wake up and return the next batch to the client.296 */297 awaitData?: boolean;298 noCursorTimeout?: boolean;299 /** Specifies the time an operation will run until it throws a timeout error. See {@link AbstractCursorOptions.timeoutMode} for more details on how this option applies to cursors. */300 timeoutMS?: number;301 /**302 * @public303 * @experimental304 * Specifies how `timeoutMS` is applied to the cursor. Can be either `'cursorLifeTime'` or `'iteration'`305 * When set to `'iteration'`, the deadline specified by `timeoutMS` applies to each call of306 * `cursor.next()`.307 * When set to `'cursorLifetime'`, the deadline applies to the life of the entire cursor.308 *309 * Depending on the type of cursor being used, this option has different default values.310 * For non-tailable cursors, this value defaults to `'cursorLifetime'`311 * For tailable cursors, this value defaults to `'iteration'` since tailable cursors, by312 * definition can have an arbitrarily long lifetime.313 *314 * @example315 * ```ts316 * const cursor = collection.find({}, {timeoutMS: 100, timeoutMode: 'iteration'});317 * for await (const doc of cursor) {318 * // process doc319 * // This will throw a timeout error if any of the iterator's `next()` calls takes more than 100ms, but320 * // will continue to iterate successfully otherwise, regardless of the number of batches.321 * }322 * ```323 *324 * @example325 * ```ts326 * const cursor = collection.find({}, { timeoutMS: 1000, timeoutMode: 'cursorLifetime' });327 * const docs = await cursor.toArray(); // This entire line will throw a timeout error if all batches are not fetched and returned within 1000ms.328 * ```329 */330 timeoutMode?: CursorTimeoutMode;331 /* Excluded from this release type: timeoutContext */332}333 334/* Excluded from this release type: AbstractOperation */335 336/** @public */337export declare type AcceptedFields<TSchema, FieldType, AssignableType> = {338 readonly [key in KeysOfAType<TSchema, FieldType>]?: AssignableType;339};340 341/** @public */342export declare type AddToSetOperators<Type> = {343 $each?: Array<Flatten<Type>>;344};345 346/**347 * The **Admin** class is an internal class that allows convenient access to348 * the admin functionality and commands for MongoDB.349 *350 * **ADMIN Cannot directly be instantiated**351 * @public352 *353 * @example354 * ```ts355 * import { MongoClient } from 'mongodb';356 *357 * const client = new MongoClient('mongodb://localhost:27017');358 * const admin = client.db().admin();359 * const dbInfo = await admin.listDatabases();360 * for (const db of dbInfo.databases) {361 * console.log(db.name);362 * }363 * ```364 */365export declare class Admin {366 /* Excluded from this release type: s */367 /* Excluded from this release type: __constructor */368 /**369 * Execute a command370 *371 * The driver will ensure the following fields are attached to the command sent to the server:372 * - `lsid` - sourced from an implicit session or options.session373 * - `$readPreference` - defaults to primary or can be configured by options.readPreference374 * - `$db` - sourced from the name of this database375 *376 * If the client has a serverApi setting:377 * - `apiVersion`378 * - `apiStrict`379 * - `apiDeprecationErrors`380 *381 * When in a transaction:382 * - `readConcern` - sourced from readConcern set on the TransactionOptions383 * - `writeConcern` - sourced from writeConcern set on the TransactionOptions384 *385 * Attaching any of the above fields to the command will have no effect as the driver will overwrite the value.386 *387 * @param command - The command to execute388 * @param options - Optional settings for the command389 */390 command(command: Document, options?: RunCommandOptions): Promise<Document>;391 /**392 * Retrieve the server build information393 *394 * @param options - Optional settings for the command395 */396 buildInfo(options?: CommandOperationOptions): Promise<Document>;397 /**398 * Retrieve the server build information399 *400 * @param options - Optional settings for the command401 */402 serverInfo(options?: CommandOperationOptions): Promise<Document>;403 /**404 * Retrieve this db's server status.405 *406 * @param options - Optional settings for the command407 */408 serverStatus(options?: CommandOperationOptions): Promise<Document>;409 /**410 * Ping the MongoDB server and retrieve results411 *412 * @param options - Optional settings for the command413 */414 ping(options?: CommandOperationOptions): Promise<Document>;415 /**416 * Remove a user from a database417 *418 * @param username - The username to remove419 * @param options - Optional settings for the command420 */421 removeUser(username: string, options?: RemoveUserOptions): Promise<boolean>;422 /**423 * Validate an existing collection424 *425 * @param collectionName - The name of the collection to validate.426 * @param options - Optional settings for the command427 */428 validateCollection(collectionName: string, options?: ValidateCollectionOptions): Promise<Document>;429 /**430 * List the available databases431 *432 * @param options - Optional settings for the command433 */434 listDatabases(options?: ListDatabasesOptions): Promise<ListDatabasesResult>;435 /**436 * Get ReplicaSet status437 *438 * @param options - Optional settings for the command439 */440 replSetGetStatus(options?: CommandOperationOptions): Promise<Document>;441}442 443/* Excluded from this release type: AdminPrivate */444 445/* Excluded from this release type: AggregateOperation */446 447/** @public */448export declare interface AggregateOptions extends Omit<CommandOperationOptions, 'explain'> {449 /** allowDiskUse lets the server know if it can use disk to store temporary results for the aggregation (requires mongodb 2.6 \>). */450 allowDiskUse?: boolean;451 /** The number of documents to return per batch. See [aggregation documentation](https://www.mongodb.com/docs/manual/reference/command/aggregate). */452 batchSize?: number;453 /** Allow driver to bypass schema validation. */454 bypassDocumentValidation?: boolean;455 /** Return the query as cursor, on 2.6 \> it returns as a real cursor on pre 2.6 it returns as an emulated cursor. */456 cursor?: Document;457 /**458 * Specifies a cumulative time limit in milliseconds for processing operations on the cursor. MongoDB interrupts the operation at the earliest following interrupt point.459 */460 maxTimeMS?: number;461 /** The maximum amount of time for the server to wait on new documents to satisfy a tailable cursor query. */462 maxAwaitTimeMS?: number;463 /** Specify collation. */464 collation?: CollationOptions;465 /** Add an index selection hint to an aggregation command */466 hint?: Hint;467 /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */468 let?: Document;469 out?: string;470 /**471 * Specifies the verbosity mode for the explain output.472 * @deprecated This API is deprecated in favor of `collection.aggregate().explain()`473 * or `db.aggregate().explain()`.474 */475 explain?: ExplainOptions['explain'];476 /* Excluded from this release type: timeoutMode */477}478 479/**480 * The **AggregationCursor** class is an internal class that embodies an aggregation cursor on MongoDB481 * allowing for iteration over the results returned from the underlying query. It supports482 * one by one document iteration, conversion to an array or can be iterated as a Node 4.X483 * or higher stream484 * @public485 */486export declare class AggregationCursor<TSchema = any> extends ExplainableCursor<TSchema> {487 readonly pipeline: Document[];488 /* Excluded from this release type: aggregateOptions */489 /* Excluded from this release type: __constructor */490 clone(): AggregationCursor<TSchema>;491 map<T>(transform: (doc: TSchema) => T): AggregationCursor<T>;492 /* Excluded from this release type: _initialize */493 /** Execute the explain for the cursor */494 explain(): Promise<Document>;495 explain(verbosity: ExplainVerbosityLike | ExplainCommandOptions): Promise<Document>;496 explain(options: {497 timeoutMS?: number;498 }): Promise<Document>;499 explain(verbosity: ExplainVerbosityLike | ExplainCommandOptions, options: {500 timeoutMS?: number;501 }): Promise<Document>;502 /** Add a stage to the aggregation pipeline503 * @example504 * ```505 * const documents = await users.aggregate().addStage({ $match: { name: /Mike/ } }).toArray();506 * ```507 * @example508 * ```509 * const documents = await users.aggregate()510 * .addStage<{ name: string }>({ $project: { name: true } })511 * .toArray(); // type of documents is { name: string }[]512 * ```513 */514 addStage(stage: Document): this;515 addStage<T = Document>(stage: Document): AggregationCursor<T>;516 /** Add a group stage to the aggregation pipeline */517 group<T = TSchema>($group: Document): AggregationCursor<T>;518 /** Add a limit stage to the aggregation pipeline */519 limit($limit: number): this;520 /** Add a match stage to the aggregation pipeline */521 match($match: Document): this;522 /** Add an out stage to the aggregation pipeline */523 out($out: {524 db: string;525 coll: string;526 } | string): this;527 /**528 * Add a project stage to the aggregation pipeline529 *530 * @remarks531 * In order to strictly type this function you must provide an interface532 * that represents the effect of your projection on the result documents.533 *534 * By default chaining a projection to your cursor changes the returned type to the generic {@link Document} type.535 * You should specify a parameterized type to have assertions on your final results.536 *537 * @example538 * ```typescript539 * // Best way540 * const docs: AggregationCursor<{ a: number }> = cursor.project<{ a: number }>({ _id: 0, a: true });541 * // Flexible way542 * const docs: AggregationCursor<Document> = cursor.project({ _id: 0, a: true });543 * ```544 *545 * @remarks546 * In order to strictly type this function you must provide an interface547 * that represents the effect of your projection on the result documents.548 *549 * **Note for Typescript Users:** adding a transform changes the return type of the iteration of this cursor,550 * it **does not** return a new instance of a cursor. This means when calling project,551 * you should always assign the result to a new variable in order to get a correctly typed cursor variable.552 * Take note of the following example:553 *554 * @example555 * ```typescript556 * const cursor: AggregationCursor<{ a: number; b: string }> = coll.aggregate([]);557 * const projectCursor = cursor.project<{ a: number }>({ _id: 0, a: true });558 * const aPropOnlyArray: {a: number}[] = await projectCursor.toArray();559 *560 * // or always use chaining and save the final cursor561 *562 * const cursor = coll.aggregate().project<{ a: string }>({563 * _id: 0,564 * a: { $convert: { input: '$a', to: 'string' }565 * }});566 * ```567 */568 project<T extends Document = Document>($project: Document): AggregationCursor<T>;569 /** Add a lookup stage to the aggregation pipeline */570 lookup($lookup: Document): this;571 /** Add a redact stage to the aggregation pipeline */572 redact($redact: Document): this;573 /** Add a skip stage to the aggregation pipeline */574 skip($skip: number): this;575 /** Add a sort stage to the aggregation pipeline */576 sort($sort: Sort): this;577 /** Add a unwind stage to the aggregation pipeline */578 unwind($unwind: Document | string): this;579 /** Add a geoNear stage to the aggregation pipeline */580 geoNear($geoNear: Document): this;581}582 583/** @public */584export declare interface AggregationCursorOptions extends AbstractCursorOptions, AggregateOptions {585}586 587/**588 * It is possible to search using alternative types in mongodb e.g.589 * string types can be searched using a regex in mongo590 * array types can be searched using their element type591 * @public592 */593export declare type AlternativeType<T> = T extends ReadonlyArray<infer U> ? T | RegExpOrString<U> : RegExpOrString<T>;594 595/** @public */596export declare type AnyBulkWriteOperation<TSchema extends Document = Document> = {597 insertOne: InsertOneModel<TSchema>;598} | {599 replaceOne: ReplaceOneModel<TSchema>;600} | {601 updateOne: UpdateOneModel<TSchema>;602} | {603 updateMany: UpdateManyModel<TSchema>;604} | {605 deleteOne: DeleteOneModel<TSchema>;606} | {607 deleteMany: DeleteManyModel<TSchema>;608};609 610/**611 * Used to represent any of the client bulk write models that can be passed as an array612 * to MongoClient#bulkWrite.613 * @public614 */615export declare type AnyClientBulkWriteModel<TSchema extends Document> = ClientInsertOneModel<TSchema> | ClientReplaceOneModel<TSchema> | ClientUpdateOneModel<TSchema> | ClientUpdateManyModel<TSchema> | ClientDeleteOneModel<TSchema> | ClientDeleteManyModel<TSchema>;616 617/** @public */618export declare type AnyError = MongoError | Error;619 620/** @public */621export declare type ArrayElement<Type> = Type extends ReadonlyArray<infer Item> ? Item : never;622 623/** @public */624export declare type ArrayOperator<Type> = {625 $each?: Array<Flatten<Type>>;626 $slice?: number;627 $position?: number;628 $sort?: Sort;629};630 631/**632 * @public633 */634declare interface AsyncDisposable_2 {635 /* Excluded from this release type: [Symbol.asyncDispose] */636 /* Excluded from this release type: asyncDispose */637}638export { AsyncDisposable_2 as AsyncDisposable }639 640/** @public */641export declare interface Auth {642 /** The username for auth */643 username?: string;644 /** The password for auth */645 password?: string;646}647 648/* Excluded from this release type: AuthContext */649 650/** @public */651export declare const AuthMechanism: Readonly<{652 readonly MONGODB_AWS: "MONGODB-AWS";653 readonly MONGODB_CR: "MONGODB-CR";654 readonly MONGODB_DEFAULT: "DEFAULT";655 readonly MONGODB_GSSAPI: "GSSAPI";656 readonly MONGODB_PLAIN: "PLAIN";657 readonly MONGODB_SCRAM_SHA1: "SCRAM-SHA-1";658 readonly MONGODB_SCRAM_SHA256: "SCRAM-SHA-256";659 readonly MONGODB_X509: "MONGODB-X509";660 readonly MONGODB_OIDC: "MONGODB-OIDC";661}>;662 663/** @public */664export declare type AuthMechanism = (typeof AuthMechanism)[keyof typeof AuthMechanism];665 666/** @public */667export declare interface AuthMechanismProperties extends Document {668 SERVICE_HOST?: string;669 SERVICE_NAME?: string;670 SERVICE_REALM?: string;671 CANONICALIZE_HOST_NAME?: GSSAPICanonicalizationValue;672 /** @deprecated Will be removed in the next major version. */673 AWS_SESSION_TOKEN?: string;674 /** A user provided OIDC machine callback function. */675 OIDC_CALLBACK?: OIDCCallbackFunction;676 /** A user provided OIDC human interacted callback function. */677 OIDC_HUMAN_CALLBACK?: OIDCCallbackFunction;678 /** The OIDC environment. Note that 'test' is for internal use only. */679 ENVIRONMENT?: 'test' | 'azure' | 'gcp' | 'k8s';680 /** Allowed hosts that OIDC auth can connect to. */681 ALLOWED_HOSTS?: string[];682 /** The resource token for OIDC auth in Azure and GCP. */683 TOKEN_RESOURCE?: string;684 /**685 * A custom AWS credential provider to use. An example using the AWS SDK default provider chain:686 *687 * ```ts688 * const client = new MongoClient(process.env.MONGODB_URI, {689 * authMechanismProperties: {690 * AWS_CREDENTIAL_PROVIDER: fromNodeProviderChain()691 * }692 * });693 * ```694 *695 * Using a custom function that returns AWS credentials:696 *697 * ```ts698 * const client = new MongoClient(process.env.MONGODB_URI, {699 * authMechanismProperties: {700 * AWS_CREDENTIAL_PROVIDER: async () => {701 * return {702 * accessKeyId: process.env.ACCESS_KEY_ID,703 * secretAccessKey: process.env.SECRET_ACCESS_KEY704 * }705 * }706 * }707 * });708 * ```709 */710 AWS_CREDENTIAL_PROVIDER?: AWSCredentialProvider;711}712 713/* Excluded from this release type: AuthProvider */714 715/* Excluded from this release type: AutoEncrypter */716 717/**718 * @public719 *720 * Extra options related to the mongocryptd process721 * \* _Available in MongoDB 6.0 or higher._722 */723export declare type AutoEncryptionExtraOptions = NonNullable<AutoEncryptionOptions['extraOptions']>;724 725/** @public */726export declare const AutoEncryptionLoggerLevel: Readonly<{727 readonly FatalError: 0;728 readonly Error: 1;729 readonly Warning: 2;730 readonly Info: 3;731 readonly Trace: 4;732}>;733 734/**735 * @public736 * The level of severity of the log message737 *738 * | Value | Level |739 * |-------|-------|740 * | 0 | Fatal Error |741 * | 1 | Error |742 * | 2 | Warning |743 * | 3 | Info |744 * | 4 | Trace |745 */746export declare type AutoEncryptionLoggerLevel = (typeof AutoEncryptionLoggerLevel)[keyof typeof AutoEncryptionLoggerLevel];747 748/** @public */749export declare interface AutoEncryptionOptions {750 /* Excluded from this release type: metadataClient */751 /** A `MongoClient` used to fetch keys from a key vault */752 keyVaultClient?: MongoClient;753 /** The namespace where keys are stored in the key vault */754 keyVaultNamespace?: string;755 /** Configuration options that are used by specific KMS providers during key generation, encryption, and decryption. */756 kmsProviders?: KMSProviders;757 /** Configuration options for custom credential providers. */758 credentialProviders?: CredentialProviders;759 /**760 * A map of namespaces to a local JSON schema for encryption761 *762 * **NOTE**: Supplying options.schemaMap provides more security than relying on JSON Schemas obtained from the server.763 * It protects against a malicious server advertising a false JSON Schema, which could trick the client into sending decrypted data that should be encrypted.764 * Schemas supplied in the schemaMap only apply to configuring automatic encryption for Client-Side Field Level Encryption.765 * Other validation rules in the JSON schema will not be enforced by the driver and will result in an error.766 */767 schemaMap?: Document;768 /** Supply a schema for the encrypted fields in the document */769 encryptedFieldsMap?: Document;770 /** Allows the user to bypass auto encryption, maintaining implicit decryption */771 bypassAutoEncryption?: boolean;772 /** Allows users to bypass query analysis */773 bypassQueryAnalysis?: boolean;774 /**775 * Sets the expiration time for the DEK in the cache in milliseconds. Defaults to 60000. 0 means no timeout.776 */777 keyExpirationMS?: number;778 options?: {779 /** An optional hook to catch logging messages from the underlying encryption engine */780 logger?: (level: AutoEncryptionLoggerLevel, message: string) => void;781 };782 extraOptions?: {783 /**784 * A local process the driver communicates with to determine how to encrypt values in a command.785 * Defaults to "mongodb://%2Fvar%2Fmongocryptd.sock" if domain sockets are available or "mongodb://localhost:27020" otherwise786 */787 mongocryptdURI?: string;788 /** If true, autoEncryption will not attempt to spawn a mongocryptd before connecting */789 mongocryptdBypassSpawn?: boolean;790 /** The path to the mongocryptd executable on the system */791 mongocryptdSpawnPath?: string;792 /** Command line arguments to use when auto-spawning a mongocryptd */793 mongocryptdSpawnArgs?: string[];794 /**795 * Full path to a MongoDB Crypt shared library to be used (instead of mongocryptd).796 *797 * This needs to be the path to the file itself, not a directory.798 * It can be an absolute or relative path. If the path is relative and799 * its first component is `$ORIGIN`, it will be replaced by the directory800 * containing the mongodb-client-encryption native addon file. Otherwise,801 * the path will be interpreted relative to the current working directory.802 *803 * Currently, loading different MongoDB Crypt shared library files from different804 * MongoClients in the same process is not supported.805 *806 * If this option is provided and no MongoDB Crypt shared library could be loaded807 * from the specified location, creating the MongoClient will fail.808 *809 * If this option is not provided and `cryptSharedLibRequired` is not specified,810 * the AutoEncrypter will attempt to spawn and/or use mongocryptd according811 * to the mongocryptd-specific `extraOptions` options.812 *813 * Specifying a path prevents mongocryptd from being used as a fallback.814 *815 * Requires the MongoDB Crypt shared library, available in MongoDB 6.0 or higher.816 */817 cryptSharedLibPath?: string;818 /**819 * If specified, never use mongocryptd and instead fail when the MongoDB Crypt820 * shared library could not be loaded.821 *822 * This is always true when `cryptSharedLibPath` is specified.823 *824 * Requires the MongoDB Crypt shared library, available in MongoDB 6.0 or higher.825 */826 cryptSharedLibRequired?: boolean;827 /* Excluded from this release type: cryptSharedLibSearchPaths */828 };829 proxyOptions?: ProxyOptions;830 /** The TLS options to use connecting to the KMS provider */831 tlsOptions?: CSFLEKMSTlsOptions;832}833 834/** @public **/835export declare type AWSCredentialProvider = () => Promise<AWSCredentials>;836 837/**838 * @public839 * Copy of the AwsCredentialIdentityProvider interface from [`smithy/types`](https://socket.dev/npm/package/\@smithy/types/files/1.1.1/dist-types/identity/awsCredentialIdentity.d.ts),840 * the return type of the aws-sdk's `fromNodeProviderChain().provider()`.841 */842export declare interface AWSCredentials {843 accessKeyId: string;844 secretAccessKey: string;845 sessionToken?: string;846 expiration?: Date;847}848 849/**850 * @public851 * Configuration options for making an AWS encryption key852 */853export declare interface AWSEncryptionKeyOptions {854 /**855 * The AWS region of the KMS856 */857 region: string;858 /**859 * The Amazon Resource Name (ARN) to the AWS customer master key (CMK)860 */861 key: string;862 /**863 * An alternate host to send KMS requests to. May include port number.864 */865 endpoint?: string | undefined;866}867 868/** @public */869export declare interface AWSKMSProviderConfiguration {870 /**871 * The access key used for the AWS KMS provider872 */873 accessKeyId: string;874 /**875 * The secret access key used for the AWS KMS provider876 */877 secretAccessKey: string;878 /**879 * An optional AWS session token that will be used as the880 * X-Amz-Security-Token header for AWS requests.881 */882 sessionToken?: string;883}884 885/**886 * @public887 * Configuration options for making an Azure encryption key888 */889export declare interface AzureEncryptionKeyOptions {890 /**891 * Key name892 */893 keyName: string;894 /**895 * Key vault URL, typically `<name>.vault.azure.net`896 */897 keyVaultEndpoint: string;898 /**899 * Key version900 */901 keyVersion?: string | undefined;902}903 904/** @public */905export declare type AzureKMSProviderConfiguration = {906 /**907 * The tenant ID identifies the organization for the account908 */909 tenantId: string;910 /**911 * The client ID to authenticate a registered application912 */913 clientId: string;914 /**915 * The client secret to authenticate a registered application916 */917 clientSecret: string;918 /**919 * If present, a host with optional port. E.g. "example.com" or "example.com:443".920 * This is optional, and only needed if customer is using a non-commercial Azure instance921 * (e.g. a government or China account, which use different URLs).922 * Defaults to "login.microsoftonline.com"923 */924 identityPlatformEndpoint?: string | undefined;925} | {926 /**927 * If present, an access token to authenticate with Azure.928 */929 accessToken: string;930};931 932/**933 * Keeps the state of a unordered batch so we can rewrite the results934 * correctly after command execution935 *936 * @public937 */938export declare class Batch<T = Document> {939 originalZeroIndex: number;940 currentIndex: number;941 originalIndexes: number[];942 batchType: BatchType;943 operations: T[];944 size: number;945 sizeBytes: number;946 constructor(batchType: BatchType, originalZeroIndex: number);947}948 949/** @public */950export declare const BatchType: Readonly<{951 readonly INSERT: 1;952 readonly UPDATE: 2;953 readonly DELETE: 3;954}>;955 956/** @public */957export declare type BatchType = (typeof BatchType)[keyof typeof BatchType];958 959export { Binary }960 961/** @public */962export declare type BitwiseFilter = number /** numeric bit mask */ | Binary /** BinData bit mask */ | ReadonlyArray<number>;963 964export { BSON }965 966/* Excluded from this release type: BSONElement */967export { BSONRegExp }968 969/**970 * BSON Serialization options.971 * @public972 */973export declare interface BSONSerializeOptions extends Omit<SerializeOptions, 'index'>, Omit<DeserializeOptions, 'evalFunctions' | 'cacheFunctions' | 'cacheFunctionsCrc32' | 'allowObjectSmallerThanBufferSize' | 'index' | 'validation'> {974 /**975 * Enabling the raw option will return a [Node.js Buffer](https://nodejs.org/api/buffer.html)976 * which is allocated using [allocUnsafe API](https://nodejs.org/api/buffer.html#static-method-bufferallocunsafesize).977 * See this section from the [Node.js Docs here](https://nodejs.org/api/buffer.html#what-makes-bufferallocunsafe-and-bufferallocunsafeslow-unsafe)978 * for more detail about what "unsafe" refers to in this context.979 * If you need to maintain your own editable clone of the bytes returned for an extended life time of the process, it is recommended you allocate980 * your own buffer and clone the contents:981 *982 * @example983 * ```ts984 * const raw = await collection.findOne({}, { raw: true });985 * const myBuffer = Buffer.alloc(raw.byteLength);986 * myBuffer.set(raw, 0);987 * // Only save and use `myBuffer` beyond this point988 * ```989 *990 * @remarks991 * Please note there is a known limitation where this option cannot be used at the MongoClient level (see [NODE-3946](https://jira.mongodb.org/browse/NODE-3946)).992 * It does correctly work at `Db`, `Collection`, and per operation the same as other BSON options work.993 */994 raw?: boolean;995 /** Enable utf8 validation when deserializing BSON documents. Defaults to true. */996 enableUtf8Validation?: boolean;997}998 999export { BSONSymbol }1000 1001export { BSONType }1002 1003/** @public */1004export declare type BSONTypeAlias = keyof typeof BSONType;1005 1006/* Excluded from this release type: BufferPool */1007 1008/** @public */1009export declare abstract class BulkOperationBase {1010 isOrdered: boolean;1011 /* Excluded from this release type: s */1012 operationId?: number;1013 private collection;1014 /* Excluded from this release type: __constructor */1015 /**1016 * Add a single insert document to the bulk operation1017 *1018 * @example1019 * ```ts1020 * const bulkOp = collection.initializeOrderedBulkOp();1021 *1022 * // Adds three inserts to the bulkOp.1023 * bulkOp1024 * .insert({ a: 1 })1025 * .insert({ b: 2 })1026 * .insert({ c: 3 });1027 * await bulkOp.execute();1028 * ```1029 */1030 insert(document: Document): BulkOperationBase;1031 /**1032 * Builds a find operation for an update/updateOne/delete/deleteOne/replaceOne.1033 * Returns a builder object used to complete the definition of the operation.1034 *1035 * @example1036 * ```ts1037 * const bulkOp = collection.initializeOrderedBulkOp();1038 *1039 * // Add an updateOne to the bulkOp1040 * bulkOp.find({ a: 1 }).updateOne({ $set: { b: 2 } });1041 *1042 * // Add an updateMany to the bulkOp1043 * bulkOp.find({ c: 3 }).update({ $set: { d: 4 } });1044 *1045 * // Add an upsert1046 * bulkOp.find({ e: 5 }).upsert().updateOne({ $set: { f: 6 } });1047 *1048 * // Add a deletion1049 * bulkOp.find({ g: 7 }).deleteOne();1050 *1051 * // Add a multi deletion1052 * bulkOp.find({ h: 8 }).delete();1053 *1054 * // Add a replaceOne1055 * bulkOp.find({ i: 9 }).replaceOne({writeConcern: { j: 10 }});1056 *1057 * // Update using a pipeline (requires Mongodb 4.2 or higher)1058 * bulk.find({ k: 11, y: { $exists: true }, z: { $exists: true } }).updateOne([1059 * { $set: { total: { $sum: [ '$y', '$z' ] } } }1060 * ]);1061 *1062 * // All of the ops will now be executed1063 * await bulkOp.execute();1064 * ```1065 */1066 find(selector: Document): FindOperators;1067 /** Specifies a raw operation to perform in the bulk write. */1068 raw(op: AnyBulkWriteOperation): this;1069 get length(): number;1070 get bsonOptions(): BSONSerializeOptions;1071 get writeConcern(): WriteConcern | undefined;1072 get batches(): Batch[];1073 execute(options?: BulkWriteOptions): Promise<BulkWriteResult>;1074 /* Excluded from this release type: handleWriteError */1075 abstract addToOperationsList(batchType: BatchType, document: Document | UpdateStatement | DeleteStatement): this;1076 private shouldForceServerObjectId;1077}1078 1079/* Excluded from this release type: BulkOperationPrivate */1080 1081/* Excluded from this release type: BulkResult */1082 1083/** @public */1084export declare interface BulkWriteOperationError {1085 index: number;1086 code: number;1087 errmsg: string;1088 errInfo: Document;1089 op: Document | UpdateStatement | DeleteStatement;1090}1091 1092/** @public */1093export declare interface BulkWriteOptions extends CommandOperationOptions {1094 /**1095 * Allow driver to bypass schema validation.1096 * @defaultValue `false` - documents will be validated by default1097 **/1098 bypassDocumentValidation?: boolean;1099 /**1100 * If true, when an insert fails, don't execute the remaining writes.1101 * If false, continue with remaining inserts when one fails.1102 * @defaultValue `true` - inserts are ordered by default1103 */1104 ordered?: boolean;1105 /**1106 * Force server to assign _id values instead of driver.1107 * @defaultValue `false` - the driver generates `_id` fields by default1108 **/1109 forceServerObjectId?: boolean;1110 /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */1111 let?: Document;1112 /* Excluded from this release type: timeoutContext */1113}1114 1115/**1116 * @public1117 * The result of a bulk write.1118 */1119export declare class BulkWriteResult {1120 private readonly result;1121 /** Number of documents inserted. */1122 readonly insertedCount: number;1123 /** Number of documents matched for update. */1124 readonly matchedCount: number;1125 /** Number of documents modified. */1126 readonly modifiedCount: number;1127 /** Number of documents deleted. */1128 readonly deletedCount: number;1129 /** Number of documents upserted. */1130 readonly upsertedCount: number;1131 /** Upserted document generated Id's, hash key is the index of the originating operation */1132 readonly upsertedIds: {1133 [key: number]: any;1134 };1135 /** Inserted document generated Id's, hash key is the index of the originating operation */1136 readonly insertedIds: {1137 [key: number]: any;1138 };1139 private static generateIdMap;1140 /* Excluded from this release type: __constructor */1141 /** Evaluates to true if the bulk operation correctly executes */1142 get ok(): number;1143 /* Excluded from this release type: getSuccessfullyInsertedIds */1144 /** Returns the upserted id at the given index */1145 getUpsertedIdAt(index: number): Document | undefined;1146 /** Returns raw internal result */1147 getRawResponse(): Document;1148 /** Returns true if the bulk operation contains a write error */1149 hasWriteErrors(): boolean;1150 /** Returns the number of write errors from the bulk operation */1151 getWriteErrorCount(): number;1152 /** Returns a specific write error object */1153 getWriteErrorAt(index: number): WriteError | undefined;1154 /** Retrieve all write errors */1155 getWriteErrors(): WriteError[];1156 /** Retrieve the write concern error if one exists */1157 getWriteConcernError(): WriteConcernError | undefined;1158 toString(): string;1159 isOk(): boolean;1160}1161 1162/**1163 * MongoDB Driver style callback1164 * @public1165 */1166export declare type Callback<T = any> = (error?: AnyError, result?: T) => void;1167 1168/**1169 * @public1170 * @deprecated Will be removed in favor of `AbortSignal` in the next major release.1171 */1172export declare class CancellationToken extends TypedEventEmitter<{1173 cancel(): void;1174}> {1175 constructor(...args: any[]);1176}1177 1178/**1179 * Creates a new Change Stream instance. Normally created using {@link Collection#watch|Collection.watch()}.1180 * @public1181 */1182export declare class ChangeStream<TSchema extends Document = Document, TChange extends Document = ChangeStreamDocument<TSchema>> extends TypedEventEmitter<ChangeStreamEvents<TSchema, TChange>> implements AsyncDisposable_2 {1183 /* Excluded from this release type: [Symbol.asyncDispose] */1184 /* Excluded from this release type: asyncDispose */1185 pipeline: Document[];1186 /**1187 * @remarks WriteConcern can still be present on the options because1188 * we inherit options from the client/db/collection. The1189 * key must be present on the options in order to delete it.1190 * This allows typescript to delete the key but will1191 * not allow a writeConcern to be assigned as a property on options.1192 */1193 options: ChangeStreamOptions & {1194 writeConcern?: never;1195 };1196 parent: MongoClient | Db | Collection;1197 namespace: MongoDBNamespace;1198 type: symbol;1199 /* Excluded from this release type: cursor */1200 streamOptions?: CursorStreamOptions;