///
///
///
import type { SrvRecord } from 'dns';
import { Document, ObjectId } from './bson';
import type { Connection } from './cmap/connection';
import type { Collection } from './collection';
import type { AbstractCursor } from './cursor/abstract_cursor';
import type { FindCursor } from './cursor/find_cursor';
import type { Db } from './db';
import { AnyError } from './error';
import type { Explain } from './explain';
import type { MongoClient } from './mongo_client';
import type { CommandOperationOptions, OperationParent } from './operations/command';
import type { IndexSpecification } from './operations/indexes';
import type { Hint, OperationOptions } from './operations/operation';
import { ReadConcern } from './read_concern';
import type { Server } from './sdam/server';
import type { Topology } from './sdam/topology';
import type { ClientSession } from './sessions';
import { W, WriteConcern, WriteConcernOptions } from './write_concern';
/**
* MongoDB Driver style callback
* @public
*/
export declare type Callback = (error?: AnyError, result?: T) => void;
export declare const MAX_JS_INT: number;
export declare type AnyOptions = Document;
/**
* Throws if collectionName is not a valid mongodb collection namespace.
* @internal
*/
export declare function checkCollectionName(collectionName: string): void;
/**
* Ensure Hint field is in a shape we expect:
* - object of index names mapping to 1 or -1
* - just an index name
* @internal
*/
export declare function normalizeHintField(hint?: Hint): Hint | undefined;
interface IndexOptions {
name: string;
keys?: string[];
fieldHash: Document;
}
/**
* Create an index specifier based on
* @internal
*/
export declare function parseIndexOptions(indexSpec: IndexSpecification): IndexOptions;
/**
* Checks if arg is an Object:
* - **NOTE**: the check is based on the `[Symbol.toStringTag]() === 'Object'`
* @internal
*/
export declare function isObject(arg: unknown): arg is object;
/** @internal */
export declare function mergeOptions(target: T, source: S): T & S;
/** @internal */
export declare function filterOptions(options: AnyOptions, names: ReadonlyArray): AnyOptions;
interface HasRetryableWrites {
retryWrites?: boolean;
}
/**
* Applies retryWrites: true to a command if retryWrites is set on the command's database.
* @internal
*
* @param target - The target command to which we will apply retryWrites.
* @param db - The database from which we can inherit a retryWrites value.
*/
export declare function applyRetryableWrites(target: T, db?: Db): T;
interface HasWriteConcern {
writeConcern?: WriteConcernOptions | WriteConcern | W;
}
/**
* Applies a write concern to a command based on well defined inheritance rules, optionally
* detecting support for the write concern in the first place.
* @internal
*
* @param target - the target command we will be applying the write concern to
* @param sources - sources where we can inherit default write concerns from
* @param options - optional settings passed into a command for write concern overrides
*/
export declare function applyWriteConcern(target: T, sources: {
db?: Db;
collection?: Collection;
}, options?: OperationOptions & WriteConcernOptions): T;
/**
* Checks if a given value is a Promise
*
* @typeParam T - The result type of maybePromise
* @param maybePromise - An object that could be a promise
* @returns true if the provided value is a Promise
*/
export declare function isPromiseLike(maybePromise?: PromiseLike | void): maybePromise is Promise;
/**
* Applies collation to a given command.
* @internal
*
* @param command - the command on which to apply collation
* @param target - target of command
* @param options - options containing collation settings
*/
export declare function decorateWithCollation(command: Document, target: MongoClient | Db | Collection, options: AnyOptions): void;
/**
* Applies a read concern to a given command.
* @internal
*
* @param command - the command on which to apply the read concern
* @param coll - the parent collection of the operation calling this method
*/
export declare function decorateWithReadConcern(command: Document, coll: {
s: {
readConcern?: ReadConcern;
};
}, options?: OperationOptions): void;
/**
* Applies an explain to a given command.
* @internal
*
* @param command - the command on which to apply the explain
* @param options - the options containing the explain verbosity
*/
export declare function decorateWithExplain(command: Document, explain: Explain): Document;
/**
* @internal
*/
export declare type TopologyProvider = MongoClient | ClientSession | FindCursor | AbstractCursor | Collection | Db;
/**
* A helper function to get the topology from a given provider. Throws
* if the topology cannot be found.
* @throws MongoNotConnectedError
* @internal
*/
export declare function getTopology(provider: TopologyProvider): Topology;
/**
* Default message handler for generating deprecation warnings.
* @internal
*
* @param name - function name
* @param option - option name
* @returns warning message
*/
export declare function defaultMsgHandler(name: string, option: string): string;
export interface DeprecateOptionsConfig {
/** function name */
name: string;
/** options to deprecate */
deprecatedOptions: string[];
/** index of options object in function arguments array */
optionsIndex: number;
/** optional custom message handler to generate warnings */
msgHandler?(this: void, name: string, option: string): string;
}
/**
* Deprecates a given function's options.
* @internal
*
* @param this - the bound class if this is a method
* @param config - configuration for deprecation
* @param fn - the target function of deprecation
* @returns modified function that warns once per deprecated option, and executes original function
*/
export declare function deprecateOptions(this: unknown, config: DeprecateOptionsConfig, fn: (...args: any[]) => any): any;
/** @internal */
export declare function ns(ns: string): MongoDBNamespace;
/** @public */
export declare class MongoDBNamespace {
db: string;
collection?: string;
/**
* Create a namespace object
*
* @param db - database name
* @param collection - collection name
*/
constructor(db: string, collection?: string);
toString(): string;
withCollection(collection: string): MongoDBNamespace;
static fromString(namespace?: string): MongoDBNamespace;
}
/** @internal */
export declare function makeCounter(seed?: number): Generator;
/**
* Helper function for either accepting a callback, or returning a promise
* @internal
*
* @param callback - The last function argument in exposed method, controls if a Promise is returned
* @param wrapper - A function that wraps the callback
* @returns Returns void if a callback is supplied, else returns a Promise.
*/
export declare function maybePromise(callback: Callback | undefined, wrapper: (fn: Callback) => void): Promise | void;
/** @internal */
export declare function databaseNamespace(ns: string): string;
/**
* Synchronously Generate a UUIDv4
* @internal
*/
export declare function uuidV4(): Buffer;
/**
* A helper function for determining `maxWireVersion` between legacy and new topology instances
* @internal
*/
export declare function maxWireVersion(topologyOrServer?: Connection | Topology | Server): number;
/**
* Checks that collation is supported by server.
* @internal
*
* @param server - to check against
* @param cmd - object where collation may be specified
*/
export declare function collationNotSupported(server: Server, cmd: Document): boolean;
/**
* Applies the function `eachFn` to each item in `arr`, in parallel.
* @internal
*
* @param arr - An array of items to asynchronously iterate over
* @param eachFn - A function to call on each item of the array. The callback signature is `(item, callback)`, where the callback indicates iteration is complete.
* @param callback - The callback called after every item has been iterated
*/
export declare function eachAsync(arr: T[], eachFn: (item: T, callback: (err?: AnyError) => void) => void, callback: Callback): void;
/** @internal */
export declare function eachAsyncSeries(arr: T[], eachFn: (item: T, callback: (err?: AnyError) => void) => void, callback: Callback): void;
/** @internal */
export declare function arrayStrictEqual(arr: unknown[], arr2: unknown[]): boolean;
/** @internal */
export declare function errorStrictEqual(lhs?: AnyError, rhs?: AnyError): boolean;
interface StateTable {
[key: string]: string[];
}
interface ObjectWithState {
s: {
state: string;
};
emit(event: 'stateChanged', state: string, newState: string): void;
}
interface StateTransitionFunction {
(target: ObjectWithState, newState: string): void;
}
/** @public */
export declare type EventEmitterWithState = {
/** @internal */
stateChanged(previous: string, current: string): void;
};
/** @internal */
export declare function makeStateMachine(stateTable: StateTable): StateTransitionFunction;
/** @public */
export interface ClientMetadata {
driver: {
name: string;
version: string;
};
os: {
type: string;
name: NodeJS.Platform;
architecture: string;
version: string;
};
platform: string;
version?: string;
application?: {
name: string;
};
}
/** @public */
export interface ClientMetadataOptions {
driverInfo?: {
name?: string;
version?: string;
platform?: string;
};
appName?: string;
}
export declare function makeClientMetadata(options?: ClientMetadataOptions): ClientMetadata;
/** @internal */
export declare function now(): number;
/** @internal */
export declare function calculateDurationInMs(started: number): number;
export interface InterruptibleAsyncIntervalOptions {
/** The interval to execute a method on */
interval: number;
/** A minimum interval that must elapse before the method is called */
minInterval: number;
/** Whether the method should be called immediately when the interval is started */
immediate: boolean;
/**
* Only used for testing unreliable timer environments
* @internal
*/
clock: () => number;
}
/** @internal */
export interface InterruptibleAsyncInterval {
wake(): void;
stop(): void;
}
/**
* Creates an interval timer which is able to be woken up sooner than
* the interval. The timer will also debounce multiple calls to wake
* ensuring that the function is only ever called once within a minimum
* interval window.
* @internal
*
* @param fn - An async function to run on an interval, must accept a `callback` as its only parameter
*/
export declare function makeInterruptibleAsyncInterval(fn: (callback: Callback) => void, options?: Partial): InterruptibleAsyncInterval;
/** @internal */
export declare function hasAtomicOperators(doc: Document | Document[]): boolean;
/**
* Merge inherited properties from parent into options, prioritizing values from options,
* then values from parent.
* @internal
*/
export declare function resolveOptions(parent: OperationParent | undefined, options?: T): T;
export declare function isSuperset(set: Set | any[], subset: Set | any[]): boolean;
/**
* Checks if the document is a Hello request
* @internal
*/
export declare function isHello(doc: Document): boolean;
/** Returns the items that are uniquely in setA */
export declare function setDifference(setA: Iterable, setB: Iterable): Set;
export declare function isRecord(value: unknown, requiredKeys: T): value is Record;
export declare function isRecord(value: unknown): value is Record;
/**
* Make a deep copy of an object
*
* NOTE: This is not meant to be the perfect implementation of a deep copy,
* but instead something that is good enough for the purposes of
* command monitoring.
*/
export declare function deepCopy(value: T): T;
/** @internal */
declare const kBuffers: unique symbol;
/** @internal */
declare const kLength: unique symbol;
/**
* A pool of Buffers which allow you to read them as if they were one
* @internal
*/
export declare class BufferPool {
[kBuffers]: Buffer[];
[kLength]: number;
constructor();
get length(): number;
/** Adds a buffer to the internal buffer pool list */
append(buffer: Buffer): void;
/** Returns the requested number of bytes without consuming them */
peek(size: number): Buffer;
/** Reads the requested number of bytes, optionally consuming them */
read(size: number, consume?: boolean): Buffer;
}
/** @public */
export declare class HostAddress {
host: string | undefined;
port: number | undefined;
socketPath: string | undefined;
isIPv6: boolean | undefined;
constructor(hostString: string);
inspect(): string;
/**
* @param ipv6Brackets - optionally request ipv6 bracket notation required for connection strings
*/
toString(ipv6Brackets?: boolean): string;
static fromString(this: void, s: string): HostAddress;
static fromHostPort(host: string, port: number): HostAddress;
static fromSrvRecord({ name, port }: SrvRecord): HostAddress;
}
export declare const DEFAULT_PK_FACTORY: {
createPk(): ObjectId;
};
/**
* When the driver used emitWarning the code will be equal to this.
* @public
*
* @example
* ```js
* process.on('warning', (warning) => {
* if (warning.code === MONGODB_WARNING_CODE) console.error('Ah an important warning! :)')
* })
* ```
*/
export declare const MONGODB_WARNING_CODE: "MONGODB DRIVER";
/** @internal */
export declare function emitWarning(message: string): void;
/**
* Will emit a warning once for the duration of the application.
* Uses the message to identify if it has already been emitted
* so using string interpolation can cause multiple emits
* @internal
*/
export declare function emitWarningOnce(message: string): void;
/**
* Takes a JS object and joins the values into a string separated by ', '
*/
export declare function enumToString(en: Record): string;
/**
* Determine if a server supports retryable writes.
*
* @internal
*/
export declare function supportsRetryableWrites(server?: Server): boolean;
export declare function parsePackageVersion({ version }: {
version: string;
}): {
major: number;
minor: number;
patch: number;
};
/**
* Fisher–Yates Shuffle
*
* Reference: https://bost.ocks.org/mike/shuffle/
* @param sequence - items to be shuffled
* @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.
*/
export declare function shuffle(sequence: Iterable, limit?: number): Array;
export declare function commandSupportsReadConcern(command: Document, options?: Document): boolean;
/**
* A utility function to get the instance of mongodb-client-encryption, if it exists.
*
* @throws MongoMissingDependencyError if mongodb-client-encryption isn't installed.
* @returns
*/
export declare function getMongoDBClientEncryption(): any;
export {};
//# sourceMappingURL=utils.d.ts.map