@azure/cosmos
Version:
Microsoft Azure Cosmos DB Service Node.js SDK for NOSQL API
1,258 lines (1,211 loc) • 252 kB
TypeScript
import { AbortError } from '@azure/abort-controller';
import type { HttpClient } from '@azure/core-rest-pipeline';
import type { Pipeline } from '@azure/core-rest-pipeline';
import { RestError } from '@azure/core-rest-pipeline';
import type { TokenCredential } from '@azure/core-auth';
export { AbortError }
declare class AeadAes256CbcHmacSha256Algorithm {
private algoVersion;
private blockSizeInBytes;
private encryptionType;
private dataEncryptionKey;
private version;
private versionSize;
private keySizeInBytes;
private minimumCipherTextLength;
constructor(dataEncryptionKey: DataEncryptionKey, encryptionType: EncryptionType);
encrypt(plainTextBuffer: Buffer): Buffer;
decrypt(cipherTextBuffer: Buffer): Buffer;
private generateAuthenticationTag;
private validateAuthenticationTag;
}
export declare interface Agent {
maxFreeSockets: number;
maxSockets: number;
sockets: any;
requests: any;
destroy(): void;
}
export declare type AggregateType = "Average" | "Count" | "Max" | "Min" | "Sum" | "MakeSet" | "MakeList";
/**
* Implementation of EncryptionKeyResolver that uses Azure Key Vault for customer managed keys.
*/
export declare class AzureKeyVaultEncryptionKeyResolver implements EncryptionKeyResolver {
private credentials;
constructor(credentials: TokenCredential);
/**
* Name of the resolver to use for client side encryption.
* Currently only AzureKeyVault implementation is supported.
*/
encryptionKeyResolverName: EncryptionKeyResolverName;
/**
* wraps the given key using the specified key encryption key path and algorithm.
* @param encryptionKeyId - path to the customer managed key to be used for wrapping. For Azure Key Vault, this is url of the key in the vault.
* @param algorithm - algorithm to be used for wrapping.
* @param unwrappedKey - dek to be wrapped.
* @returns wrapped DEK.
*/
wrapKey(encryptionKeyId: string, algorithm: string, unwrappedKey: Uint8Array): Promise<Uint8Array>;
/**
* Unwraps the given wrapped key using the specified key encryption key path and algorithm.
* @param encryptionKeyId - path to the customer managed key to be used for unwrapping. For Azure Key Vault, this is url of the key in the vault.
* @param algorithm - algorithm to be used for unwrapping.
* @param wrappedKey - wrapped DEK.
* @returns unwrapped DEK.
*/
unwrapKey(encryptionKeyId: string, algorithm: string, wrappedKey: Uint8Array): Promise<Uint8Array>;
private getKeyDetails;
private getOrigin;
}
export declare type BulkOperationResponse = OperationResponse[] & {
diagnostics: CosmosDiagnostics;
};
export declare const BulkOperationType: {
readonly Create: "Create";
readonly Upsert: "Upsert";
readonly Read: "Read";
readonly Delete: "Delete";
readonly Replace: "Replace";
readonly Patch: "Patch";
};
/**
* Options object used to modify bulk execution.
* continueOnError (Default value: false) - Continues bulk execution when an operation fails ** NOTE THIS WILL DEFAULT TO TRUE IN the 4.0 RELEASE
*/
export declare interface BulkOptions {
continueOnError?: boolean;
}
export declare type BulkPatchOperation = OperationBase & {
operationType: typeof BulkOperationType.Patch;
id: string;
};
/**
* Provides iterator for change feed.
*
* Use `Items.changeFeed()` to get an instance of the iterator.
*/
export declare class ChangeFeedIterator<T> {
private clientContext;
private resourceId;
private resourceLink;
private partitionKey;
private changeFeedOptions;
private static readonly IfNoneMatchAllHeaderValue;
private nextIfNoneMatch;
private ifModifiedSince;
private lastStatusCode;
private isPartitionSpecified;
/**
* Gets a value indicating whether there are potentially additional results that can be retrieved.
*
* Initially returns true. This value is set based on whether the last execution returned a continuation token.
*
* @returns Boolean value representing if whether there are potentially additional results that can be retrieved.
*/
get hasMoreResults(): boolean;
/**
* Gets an async iterator which will yield pages of results from Azure Cosmos DB.
*/
getAsyncIterator(): AsyncIterable<ChangeFeedResponse<Array<T & Resource>>>;
/**
* Read feed and retrieves the next page of results in Azure Cosmos DB.
*/
fetchNext(): Promise<ChangeFeedResponse<Array<T & Resource>>>;
private getFeedResponse;
}
/**
* Specifies options for the change feed
*
* If none of those options are set, it will start reading changes from now for the entire container.
*/
export declare interface ChangeFeedIteratorOptions {
/**
* Max amount of items to return per page
*/
maxItemCount?: number;
/**
* The session token to use. If not specified, will use the most recent captured session token to start with.
*/
sessionToken?: string;
/**
* Signals where to start from in the change feed.
*/
changeFeedStartFrom?: ChangeFeedStartFrom;
/**
* Signals the mode in which the change feed needs to start.
*/
changeFeedMode?: ChangeFeedMode;
}
/**
* A single response page from the Azure Cosmos DB Change Feed
*/
export declare class ChangeFeedIteratorResponse<T> {
/**
* Gets the items returned in the response from Azure Cosmos DB
*/
readonly result: T;
/**
* Gets the number of items returned in the response from Azure Cosmos DB
*/
readonly count: number;
/**
* Gets the status code of the response from Azure Cosmos DB
*/
readonly statusCode: number;
/**
* Cosmos Diagnostic Object.
*/
readonly diagnostics: CosmosDiagnostics;
/**
* Gets the subStatusCodes of the response from Azure Cosmos DB. Useful in partition split or partition gone.
*/
readonly subStatusCode?: number;
/**
* Gets the request charge for this request from the Azure Cosmos DB service.
*/
get requestCharge(): number;
/**
* Gets the activity ID for the request from the Azure Cosmos DB service.
*/
get activityId(): string;
/**
* Gets the continuation token to be used for continuing enumeration of the Azure Cosmos DB service.
*/
get continuationToken(): string;
/**
* Gets the session token for use in session consistency reads from the Azure Cosmos DB service.
*/
get sessionToken(): string;
/**
* Response headers of the response from Azure Cosmos DB
*/
headers: CosmosHeaders;
}
export declare enum ChangeFeedMode {
LatestVersion = "Incremental Feed",
AllVersionsAndDeletes = "Full-Fidelity Feed"
}
/**
* Specifies options for the change feed
*
* Some of these options control where and when to start reading from the change feed. The order of precedence is:
* - continuation
* - startTime
* - startFromBeginning
*
* If none of those options are set, it will start reading changes from the first `ChangeFeedIterator.fetchNext()` call.
*/
export declare interface ChangeFeedOptions {
/**
* Max amount of items to return per page
*/
maxItemCount?: number;
/**
* The continuation token to start from.
*
* This is equivalent to the etag and continuation value from the `ChangeFeedResponse`
*/
continuation?: string;
/**
* The session token to use. If not specified, will use the most recent captured session token to start with.
*/
sessionToken?: string;
/**
* Signals whether to start from the beginning or not.
*/
startFromBeginning?: boolean;
/**
* Specified the start time to start reading changes from.
*/
startTime?: Date;
}
/**
* Represents the change feed policy configuration for a container in the Azure Cosmos DB service.
*/
export declare class ChangeFeedPolicy {
retentionDuration: number;
constructor(retentionDuration: ChangeFeedRetentionTimeSpan);
}
/**
* Use `Items.getChangeFeedIterator()` to return an iterator that can iterate over all the changes for a partition key, feed range or an entire container.
*/
export declare interface ChangeFeedPullModelIterator<T> {
/**
* Always returns true, changefeed is an infinite stream.
*/
readonly hasMoreResults: boolean;
/**
* Returns next set of results for the change feed.
*/
readNext(): Promise<ChangeFeedIteratorResponse<Array<T & Resource>>>;
/**
* Gets an async iterator which will yield change feed results.
* @example Get changefeed for an entire container from now
* ```typescript
* const options = { changeFeedStartFrom: ChangeFeedStartFrom.Now() };
* for await(const res of container.items.getChangeFeedIterator(options).getAsyncIterator()) {
* //process res
* }
* ```
*/
getAsyncIterator(): AsyncIterable<ChangeFeedIteratorResponse<Array<T & Resource>>>;
}
/**
* A single response page from the Azure Cosmos DB Change Feed
*/
export declare class ChangeFeedResponse<T> {
/**
* Gets the items returned in the response from Azure Cosmos DB
*/
readonly result: T;
/**
* Gets the number of items returned in the response from Azure Cosmos DB
*/
readonly count: number;
/**
* Gets the status code of the response from Azure Cosmos DB
*/
readonly statusCode: number;
readonly diagnostics: CosmosDiagnostics;
/**
* Gets the request charge for this request from the Azure Cosmos DB service.
*/
get requestCharge(): number;
/**
* Gets the activity ID for the request from the Azure Cosmos DB service.
*/
get activityId(): string;
/**
* Gets the continuation token to be used for continuing enumeration of the Azure Cosmos DB service.
*
* This is equivalent to the `etag` property.
*/
get continuation(): string;
/**
* Gets the session token for use in session consistency reads from the Azure Cosmos DB service.
*/
get sessionToken(): string;
/**
* Gets the entity tag associated with last transaction in the Azure Cosmos DB service,
* which can be used as If-Non-Match Access condition for ReadFeed REST request or
* `continuation` property of `ChangeFeedOptions` parameter for
* `Items.changeFeed()`
* to get feed changes since the transaction specified by this entity tag.
*
* This is equivalent to the `continuation` property.
*/
get etag(): string;
/**
* Response headers of the response from Azure Cosmos DB
*/
headers: CosmosHeaders;
}
export declare class ChangeFeedRetentionTimeSpan {
private retentionInMinutes;
/**
* Specifies the retention window in minutes for which processing the change feed with allVersionsAndDeletes mode will be available.
*/
static fromMinutes(minutes: number): ChangeFeedRetentionTimeSpan;
}
/**
* Base class for where to start a ChangeFeedIterator.
*/
export declare abstract class ChangeFeedStartFrom {
/**
* Returns an object that tells the ChangeFeedIterator to start from the beginning of time.
* @param cfResource - PartitionKey or FeedRange for which changes are to be fetched. Leave blank for fetching changes for entire container.
*/
static Beginning(cfResource?: PartitionKey | FeedRange): ChangeFeedStartFromBeginning;
/**
* Returns an object that tells the ChangeFeedIterator to start reading changes from this moment onward.
* @param cfResource - PartitionKey or FeedRange for which changes are to be fetched. Leave blank for fetching changes for entire container.
**/
static Now(cfResource?: PartitionKey | FeedRange): ChangeFeedStartFromNow;
/**
* Returns an object that tells the ChangeFeedIterator to start reading changes from some point in time onward.
* @param startTime - Date object specfiying the time to start reading changes from.
* @param cfResource - PartitionKey or FeedRange for which changes are to be fetched. Leave blank for fetching changes for entire container.
*/
static Time(startTime: Date, cfResource?: PartitionKey | FeedRange): ChangeFeedStartFromTime;
/**
* Returns an object that tells the ChangeFeedIterator to start reading changes from a save point.
* @param continuation - The continuation to resume from.
*/
static Continuation(continuationToken: string): ChangeFeedStartFromContinuation;
}
/**
* @hidden
* Class which specifies the ChangeFeedIterator to start reading changes from beginning of time.
*/
declare class ChangeFeedStartFromBeginning {
private cfResource?;
constructor(cfResource?: PartitionKey | FeedRange);
getCfResource(): PartitionKey | FeedRange | undefined;
}
/**
* @hidden
* Class which specifies the ChangeFeedIterator to start reading changes from a saved point.
*/
declare class ChangeFeedStartFromContinuation {
private continuationToken;
constructor(continuation: string);
getCfResource(): string;
getCfResourceJson(): any;
getResourceType(): any;
}
/**
* @hidden
* Class which specifies the ChangeFeedIterator to start reading changes from this moment in time.
*/
declare class ChangeFeedStartFromNow {
cfResource?: PartitionKey | FeedRange;
constructor(cfResource?: PartitionKey | FeedRange);
getCfResource(): PartitionKey | FeedRange | undefined;
}
/**
* @hidden
* Class which specifies the ChangeFeedIterator to start reading changes from a particular point of time.
*/
declare class ChangeFeedStartFromTime {
private cfResource?;
private startTime;
constructor(startTime: Date, cfResource?: PartitionKey | FeedRange);
getCfResource(): PartitionKey | FeedRange | undefined;
getStartTime(): Date;
}
/**
* This type holds information related to initialization of `CosmosClient`
*/
export declare type ClientConfigDiagnostic = {
/**
* End point configured during client initialization.
*/
endpoint: string;
/**
* True if `resourceTokens` was supplied during client initialization.
*/
resourceTokensConfigured: boolean;
/**
* True if `tokenProvider` was supplied during client initialization.
*/
tokenProviderConfigured: boolean;
/**
* True if `aadCredentials` was supplied during client initialization.
*/
aadCredentialsConfigured: boolean;
/**
* True if `connectionPolicy` was supplied during client initialization.
*/
connectionPolicyConfigured: boolean;
/**
* `consistencyLevel` supplied during client initialization.
*/
consistencyLevel?: keyof typeof ConsistencyLevel;
/**
* `defaultHeaders` supplied during client initialization.
*/
defaultHeaders?: {
[key: string]: any;
};
/**
* True if `connectionPolicy` were supplied during client initialization.
*/
agentConfigured: boolean;
/**
* `userAgentSuffix` supplied during client initialization.
*/
userAgentSuffix: string;
/**
* `diagnosticLevel` supplied during client initialization.
*/
diagnosticLevel?: CosmosDbDiagnosticLevel;
/**
* True if `plugins` were supplied during client initialization.
*/
pluginsConfigured: boolean;
/**
* SDK version
*/
sDKVersion: string;
};
/**
* @hidden
* @hidden
*/
export declare class ClientContext {
private cosmosClientOptions;
private globalEndpointManager;
private clientConfig;
diagnosticLevel: CosmosDbDiagnosticLevel;
private readonly sessionContainer;
private connectionPolicy;
private pipeline;
private diagnosticWriter;
private diagnosticFormatter;
partitionKeyDefinitionCache: {
[containerUrl: string]: any;
};
/** boolean flag to support operations with client-side encryption */
enableEncryption: boolean;
constructor(cosmosClientOptions: CosmosClientOptions, globalEndpointManager: GlobalEndpointManager, clientConfig: ClientConfigDiagnostic, diagnosticLevel: CosmosDbDiagnosticLevel);
/** @hidden */
read<T>({ path, resourceType, resourceId, options, partitionKey, diagnosticNode, }: {
path: string;
resourceType: ResourceType;
resourceId: string;
options?: RequestOptions;
partitionKey?: PartitionKey;
diagnosticNode: DiagnosticNodeInternal;
}): Promise<Response_2<T & Resource>>;
queryFeed<T>({ path, resourceType, resourceId, resultFn, query, options, diagnosticNode, partitionKeyRangeId, partitionKey, startEpk, endEpk, correlatedActivityId, }: {
path: string;
resourceType: ResourceType;
resourceId: string;
resultFn: (result: {
[key: string]: any;
}) => any[];
query: SqlQuerySpec | string;
options: FeedOptions;
diagnosticNode: DiagnosticNodeInternal;
partitionKeyRangeId?: string;
partitionKey?: PartitionKey;
startEpk?: string | undefined;
endEpk?: string | undefined;
correlatedActivityId?: string;
}): Promise<Response_2<T & Resource>>;
getQueryPlan(path: string, resourceType: ResourceType, resourceId: string, query: SqlQuerySpec | string, options: FeedOptions, diagnosticNode: DiagnosticNodeInternal, correlatedActivityId?: string): Promise<Response_2<PartitionedQueryExecutionInfo>>;
queryPartitionKeyRanges(collectionLink: string, query?: string | SqlQuerySpec, options?: FeedOptions): QueryIterator<PartitionKeyRange>;
delete<T>({ path, resourceType, resourceId, options, partitionKey, method, diagnosticNode, }: {
path: string;
resourceType: ResourceType;
resourceId: string;
options?: RequestOptions;
partitionKey?: PartitionKey;
method?: HTTPMethod;
diagnosticNode: DiagnosticNodeInternal;
}): Promise<Response_2<T & Resource>>;
patch<T>({ body, path, resourceType, resourceId, options, partitionKey, diagnosticNode, }: {
body: any;
path: string;
resourceType: ResourceType;
resourceId: string;
options?: RequestOptions;
partitionKey?: PartitionKey;
diagnosticNode: DiagnosticNodeInternal;
}): Promise<Response_2<T & Resource>>;
create<T, U = T>({ body, path, resourceType, resourceId, diagnosticNode, options, partitionKey, }: {
body: T;
path: string;
resourceType: ResourceType;
resourceId: string;
diagnosticNode: DiagnosticNodeInternal;
options?: RequestOptions;
partitionKey?: PartitionKey;
}): Promise<Response_2<T & U & Resource>>;
private processQueryFeedResponse;
private applySessionToken;
replace<T>({ body, path, resourceType, resourceId, options, partitionKey, diagnosticNode, }: {
body: any;
path: string;
resourceType: ResourceType;
resourceId: string;
options?: RequestOptions;
partitionKey?: PartitionKey;
diagnosticNode: DiagnosticNodeInternal;
}): Promise<Response_2<T & Resource>>;
upsert<T, U = T>({ body, path, resourceType, resourceId, options, partitionKey, diagnosticNode, }: {
body: T;
path: string;
resourceType: ResourceType;
resourceId: string;
options?: RequestOptions;
partitionKey?: PartitionKey;
diagnosticNode: DiagnosticNodeInternal;
}): Promise<Response_2<T & U & Resource>>;
execute<T>({ sprocLink, params, options, partitionKey, diagnosticNode, }: {
sprocLink: string;
params?: any[];
options?: RequestOptions;
partitionKey?: PartitionKey;
diagnosticNode: DiagnosticNodeInternal;
}): Promise<Response_2<T>>;
/**
* Gets the Database account information.
* @param options - `urlConnection` in the options is the endpoint url whose database account needs to be retrieved.
* If not present, current client's url will be used.
*/
getDatabaseAccount(diagnosticNode: DiagnosticNodeInternal, options?: RequestOptions): Promise<Response_2<DatabaseAccount>>;
getWriteEndpoint(diagnosticNode: DiagnosticNodeInternal): Promise<string>;
getReadEndpoint(diagnosticNode: DiagnosticNodeInternal): Promise<string>;
getWriteEndpoints(): Promise<readonly string[]>;
getReadEndpoints(): Promise<readonly string[]>;
batch<T>({ body, path, partitionKey, resourceId, options, diagnosticNode, }: {
body: T;
path: string;
partitionKey: PartitionKey;
resourceId: string;
options?: RequestOptions;
diagnosticNode: DiagnosticNodeInternal;
}): Promise<Response_2<any>>;
bulk<T>({ body, path, partitionKeyRangeId, resourceId, bulkOptions, options, diagnosticNode, }: {
body: T;
path: string;
partitionKeyRangeId: string;
resourceId: string;
bulkOptions?: BulkOptions;
options?: RequestOptions;
diagnosticNode: DiagnosticNodeInternal;
}): Promise<Response_2<any>>;
private captureSessionToken;
clearSessionToken(path: string): void;
recordDiagnostics(diagnostic: CosmosDiagnostics): void;
initializeDiagnosticSettings(diagnosticLevel: CosmosDbDiagnosticLevel): void;
private getSessionParams;
private isMasterResource;
private buildHeaders;
/**
* Returns collection of properties which are derived from the context for Request Creation.
* These properties have client wide scope, as opposed to request specific scope.
* @returns
*/
private getContextDerivedPropsForRequestCreation;
getClientConfig(): ClientConfigDiagnostic;
}
/**
* Represents a path for encryption and its associated settings.
*/
export declare interface ClientEncryptionIncludedPath {
/**
* name of the path to be encrypted
*/
path: string;
/**
* identifier of the client encryption key to use to encrypt the path
*/
clientEncryptionKeyId: string;
/**
* type of encryption to be performed (Deterministic or Randomized)
*/
encryptionType: EncryptionType;
/**
* encryption algorithm to be used
* currently only AEAD_AES_256_CBC_HMAC_SHA256 algo is supported
*/
encryptionAlgorithm: EncryptionAlgorithm;
}
/**
* Details of a client encryption key for use with the Azure Cosmos DB service.
*/
export declare interface ClientEncryptionKeyProperties {
/**
* unique identifier for the client encryption key
*/
id: string;
/**
* Encryption algorithm that will be used along with this client encryption key to encrypt/decrypt data
*/
encryptionAlgorithm: string;
/**
* Wrapped (encrypted) form of the client encryption key.
*/
wrappedDataEncryptionKey: Uint8Array;
/**
* Metadata used to wrap/unwrap client encryption key using customer managed key.
*/
encryptionKeyWrapMetadata: EncryptionKeyWrapMetadata;
}
/**
* The cache used to store the properties of the client encryption key
* see {@link ClientEncryptionKeyProperties}
* @hidden
*/
declare class ClientEncryptionKeyPropertiesCache {
private clientEncryptionKeyPropertiesCache;
constructor();
get(key: string): ClientEncryptionKeyProperties | undefined;
set(key: string, clientEncryptionKeyProperties: ClientEncryptionKeyProperties): void;
}
/**
* Interface representing a request for client encryption key in Cosmos DB.
*/
export declare interface ClientEncryptionKeyRequest {
/** id of the client encryption key */
id: string;
/**
* The algorithm used to encrypt/decrypt data.
*/
encryptionAlgorithm: string;
/**
* Metadata containing information necessary to wrap/unwrap the encryption key.
*/
keyWrapMetadata: EncryptionKeyWrapMetadata;
/**
* The wrapped (encrypted) data encryption key.
*/
wrappedDataEncryptionKey: string;
}
/** Response object for ClientEncryptionKey operations */
export declare class ClientEncryptionKeyResponse extends ResourceResponse<Resource> {
constructor(resource: Resource, headers: CosmosHeaders, statusCode: number, clientEncryptionKeyProperties: ClientEncryptionKeyProperties, diagnostics: CosmosDiagnostics);
/** Properties of the client encryption key */
readonly clientEncryptionKeyProperties: ClientEncryptionKeyProperties;
}
/**
* Represents the encryption options associated with a CosmosClient.
*/
export declare interface ClientEncryptionOptions {
/** resolver that allows interaction with key encryption keys. */
keyEncryptionKeyResolver: EncryptionKeyResolver;
/** time for which encryption keys and settings will be cached. Default is 7200 seconds */
encryptionKeyTimeToLiveInSeconds?: number;
}
/**
* Represents the client encryption policy associated with a container.
*/
export declare interface ClientEncryptionPolicy {
/** list of paths that needs to be encrypted along with their encryption settings. */
includedPaths: ClientEncryptionIncludedPath[];
/**
* Version of the client encryption policy definition.
* The supported versions are 1 and 2. Default is 1.
* Id and partition key paths encryption are only supported in version 2.
*/
policyFormatVersion?: number;
}
export declare class ClientSideMetrics {
readonly requestCharge: number;
constructor(requestCharge: number);
/**
* Adds one or more ClientSideMetrics to a copy of this instance and returns the result.
*/
add(...clientSideMetricsArray: ClientSideMetrics[]): ClientSideMetrics;
static readonly zero: ClientSideMetrics;
static createFromArray(...clientSideMetricsArray: ClientSideMetrics[]): ClientSideMetrics;
}
/**
* This is a collection type for all client side diagnostic information.
*/
export declare type ClientSideRequestStatistics = {
/**
* This is the UTC timestamp for start of client operation.
*/
requestStartTimeUTCInMs: number;
/**
* This is the duration in milli seconds taken by client operation.
*/
requestDurationInMs: number;
/**
* This is the list of Location Endpoints contacted during the client operation.
*/
locationEndpointsContacted: string[];
/**
* This field captures diagnostic information for retries happened during client operation.
*/
retryDiagnostics: RetryDiagnostics;
/**
* This field captures diagnostic information for meta data lookups happened during client operation.
*/
metadataDiagnostics: MetadataLookUpDiagnostics;
/**
* These are the statistics for main point look operation.
*/
gatewayStatistics: GatewayStatistics[];
/**
* This is the cumulated Request Payload Length n bytes, this includes metadata calls along with the main operation.
*/
totalRequestPayloadLengthInBytes: number;
/**
* This is the cumulated Response Payload Length n bytes, this includes metadata calls along with the main operation.
*/
totalResponsePayloadLengthInBytes: number;
/**
* This field captures diagnostic information for encryption/decryption happened during CRUD operation if encryption is enabled.
*/
encryptionDiagnostics?: EncryptionDiagnostics;
};
/**
* Represents a composite path in the indexing policy.
*/
export declare interface CompositePath {
/** The path in the JSON document to include in the composite index. */
path: string;
/** The order of the composite index, either "ascending" or "descending". */
order: "ascending" | "descending";
}
export declare interface ComputedProperty {
/**
* The name of the computed property. Name of the computed property
* should be chosen such that it does not collide with any existing
* or future document properties.
*/
name: string;
query: string;
[key: string]: any;
}
/**
* Use to read or delete a given {@link Conflict} by id.
*
* @see {@link Conflicts} to query or read all conflicts.
*/
export declare class Conflict {
readonly container: Container;
readonly id: string;
private readonly clientContext;
private partitionKey?;
/**
* Returns a reference URL to the resource. Used for linking in Permissions.
*/
get url(): string;
/**
* @hidden
* @param container - The parent {@link Container}.
* @param id - The id of the given {@link Conflict}.
*/
constructor(container: Container, id: string, clientContext: ClientContext, partitionKey?: PartitionKey);
/**
* Read the {@link ConflictDefinition} for the given {@link Conflict}.
*/
read(options?: RequestOptions): Promise<ConflictResponse>;
/**
* Delete the given {@link ConflictDefinition}.
*/
delete(options?: RequestOptions): Promise<ConflictResponse>;
}
export declare interface ConflictDefinition {
/** The id of the conflict */
id?: string;
/** Source resource id */
resourceId?: string;
resourceType?: ResourceType;
operationType?: OperationType;
content?: string;
}
export declare enum ConflictResolutionMode {
Custom = "Custom",
LastWriterWins = "LastWriterWins"
}
/**
* Represents the conflict resolution policy configuration for specifying how to resolve conflicts
* in case writes from different regions result in conflicts on documents in the collection in the Azure Cosmos DB service.
*/
export declare interface ConflictResolutionPolicy {
/**
* Gets or sets the <see cref="ConflictResolutionMode"/> in the Azure Cosmos DB service. By default it is {@link ConflictResolutionMode.LastWriterWins}.
*/
mode?: keyof typeof ConflictResolutionMode;
/**
* Gets or sets the path which is present in each document in the Azure Cosmos DB service for last writer wins conflict-resolution.
* This path must be present in each document and must be an integer value.
* In case of a conflict occurring on a document, the document with the higher integer value in the specified path will be picked.
* If the path is unspecified, by default the timestamp path will be used.
*
* This value should only be set when using {@link ConflictResolutionMode.LastWriterWins}.
*
* ```typescript
* conflictResolutionPolicy.ConflictResolutionPath = "/name/first";
* ```
*
*/
conflictResolutionPath?: string;
/**
* Gets or sets the {@link StoredProcedure} which is used for conflict resolution in the Azure Cosmos DB service.
* This stored procedure may be created after the {@link Container} is created and can be changed as required.
*
* 1. This value should only be set when using {@link ConflictResolutionMode.Custom}.
* 2. In case the stored procedure fails or throws an exception, the conflict resolution will default to registering conflicts in the conflicts feed.
*
* ```typescript
* conflictResolutionPolicy.ConflictResolutionProcedure = "resolveConflict"
* ```
*/
conflictResolutionProcedure?: string;
}
export declare class ConflictResponse extends ResourceResponse<ConflictDefinition & Resource> {
constructor(resource: ConflictDefinition & Resource, headers: CosmosHeaders, statusCode: number, conflict: Conflict, diagnostics: CosmosDiagnostics);
/** A reference to the {@link Conflict} corresponding to the returned {@link ConflictDefinition}. */
readonly conflict: Conflict;
}
/**
* Use to query or read all conflicts.
*
* @see {@link Conflict} to read or delete a given {@link Conflict} by id.
*/
export declare class Conflicts {
readonly container: Container;
private readonly clientContext;
constructor(container: Container, clientContext: ClientContext);
/**
* Queries all conflicts.
* @param query - Query configuration for the operation. See {@link SqlQuerySpec} for more info on how to configure a query.
* @param options - Use to set options like response page size, continuation tokens, etc.
* @returns {@link QueryIterator} Allows you to return results in an array or iterate over them one at a time.
*/
query(query: string | SqlQuerySpec, options?: FeedOptions): QueryIterator<any>;
/**
* Queries all conflicts.
* @param query - Query configuration for the operation. See {@link SqlQuerySpec} for more info on how to configure a query.
* @param options - Use to set options like response page size, continuation tokens, etc.
* @returns {@link QueryIterator} Allows you to return results in an array or iterate over them one at a time.
*/
query<T>(query: string | SqlQuerySpec, options?: FeedOptions): QueryIterator<T>;
/**
* Reads all conflicts
* @param options - Use to set options like response page size, continuation tokens, etc.
*/
readAll(options?: FeedOptions): QueryIterator<ConflictDefinition & Resource>;
}
/** Determines the connection behavior of the CosmosClient. Note, we currently only support Gateway Mode. */
export declare enum ConnectionMode {
/** Gateway mode talks to an intermediate gateway which handles the direct communication with your individual partitions. */
Gateway = 0
}
/**
* Represents the Connection policy associated with a CosmosClient in the Azure Cosmos DB database service.
*/
export declare interface ConnectionPolicy {
/** Determines which mode to connect to Cosmos with. (Currently only supports Gateway option) */
connectionMode?: ConnectionMode;
/** Request timeout (time to wait for response from network peer). Represented in milliseconds. */
requestTimeout?: number;
/**
* Flag to enable/disable automatic redirecting of requests based on read/write operations. Default true.
* Required to call client.dispose() when this is set to true after destroying the CosmosClient inside another process or in the browser.
*/
enableEndpointDiscovery?: boolean;
/** List of azure regions to be used as preferred locations for read requests. */
preferredLocations?: string[];
/** RetryOptions object which defines several configurable properties used during retry. */
retryOptions?: RetryOptions;
/**
* The flag that enables writes on any locations (regions) for geo-replicated database accounts in the Azure Cosmos DB service.
* Default is `false`.
*/
useMultipleWriteLocations?: boolean;
/** Rate in milliseconds at which the client will refresh the endpoints list in the background */
endpointRefreshRateInMs?: number;
/** Flag to enable/disable background refreshing of endpoints. Defaults to false.
* Endpoint discovery using `enableEndpointsDiscovery` will still work for failed requests. */
enableBackgroundEndpointRefreshing?: boolean;
}
/**
* Represents the consistency levels supported for Azure Cosmos DB client operations.<br>
* The requested ConsistencyLevel must match or be weaker than that provisioned for the database account.
* Consistency levels.
*
* Consistency levels by order of strength are Strong, BoundedStaleness, Session, Consistent Prefix, and Eventual.
*
* See https://aka.ms/cosmos-consistency for more detailed documentation on Consistency Levels.
*/
export declare enum ConsistencyLevel {
/**
* Strong Consistency guarantees that read operations always return the value that was last written.
*/
Strong = "Strong",
/**
* Bounded Staleness guarantees that reads are not too out-of-date.
* This can be configured based on number of operations (MaxStalenessPrefix) or time (MaxStalenessIntervalInSeconds).
*/
BoundedStaleness = "BoundedStaleness",
/**
* Session Consistency guarantees monotonic reads (you never read old data, then new, then old again),
* monotonic writes (writes are ordered) and read your writes (your writes are immediately visible to your reads)
* within any single session.
*/
Session = "Session",
/**
* Eventual Consistency guarantees that reads will return a subset of writes.
* All writes will be eventually be available for reads.
*/
Eventual = "Eventual",
/**
* ConsistentPrefix Consistency guarantees that reads will return some prefix of all writes with no gaps.
* All writes will be eventually be available for reads.
*/
ConsistentPrefix = "ConsistentPrefix"
}
/**
* @hidden
*/
export declare const Constants: {
HttpHeaders: {
Authorization: string;
ETag: string;
MethodOverride: string;
Slug: string;
ContentType: string;
LastModified: string;
ContentEncoding: string;
CharacterSet: string;
UserAgent: string;
CustomUserAgent: string;
IfModifiedSince: string;
IfMatch: string;
IfNoneMatch: string;
ContentLength: string;
AcceptEncoding: string;
KeepAlive: string;
CacheControl: string;
TransferEncoding: string;
ContentLanguage: string;
ContentLocation: string;
ContentMd5: string;
ContentRange: string;
Accept: string;
AcceptCharset: string;
AcceptLanguage: string;
IfRange: string;
IfUnmodifiedSince: string;
MaxForwards: string;
ProxyAuthorization: string;
AcceptRanges: string;
ProxyAuthenticate: string;
RetryAfter: string;
SetCookie: string;
WwwAuthenticate: string;
Origin: string;
Host: string;
AccessControlAllowOrigin: string;
AccessControlAllowHeaders: string;
KeyValueEncodingFormat: string;
WrapAssertionFormat: string;
WrapAssertion: string;
WrapScope: string;
SimpleToken: string;
HttpDate: string;
Prefer: string;
Location: string;
Referer: string;
A_IM: string;
Query: string;
IsQuery: string;
IsQueryPlan: string;
SupportedQueryFeatures: string;
QueryVersion: string;
Continuation: string;
ContinuationToken: string;
PageSize: string;
ItemCount: string;
ChangeFeedWireFormatVersion: string;
ActivityId: string;
CorrelatedActivityId: string;
PreTriggerInclude: string;
PreTriggerExclude: string;
PostTriggerInclude: string;
PostTriggerExclude: string;
IndexingDirective: string;
SessionToken: string;
ConsistencyLevel: string;
XDate: string;
CollectionPartitionInfo: string;
CollectionServiceInfo: string;
RetryAfterInMilliseconds: string;
RetryAfterInMs: string;
IsFeedUnfiltered: string;
ResourceTokenExpiry: string;
EnableScanInQuery: string;
EmitVerboseTracesInQuery: string;
EnableCrossPartitionQuery: string;
ParallelizeCrossPartitionQuery: string;
ResponseContinuationTokenLimitInKB: string;
SDKSupportedCapabilities: string;
PopulateQueryMetrics: string;
QueryMetrics: string;
PopulateIndexMetrics: string;
IndexUtilization: string;
Version: string;
OwnerFullName: string;
OwnerId: string;
PartitionKey: string;
PartitionKeyRangeID: string;
StartEpk: string;
EndEpk: string;
ReadFeedKeyType: string;
MaxEntityCount: string;
CurrentEntityCount: string;
CollectionQuotaInMb: string;
CollectionCurrentUsageInMb: string;
MaxMediaStorageUsageInMB: string;
CurrentMediaStorageUsageInMB: string;
RequestCharge: string;
PopulateQuotaInfo: string;
MaxResourceQuota: string;
OfferType: string;
OfferThroughput: string;
AutoscaleSettings: string;
DisableRUPerMinuteUsage: string;
IsRUPerMinuteUsed: string;
OfferIsRUPerMinuteThroughputEnabled: string;
IndexTransformationProgress: string;
LazyIndexingProgress: string;
IsUpsert: string;
SubStatus: string;
EnableScriptLogging: string;
ScriptLogResults: string;
ALLOW_MULTIPLE_WRITES: string;
IsBatchRequest: string;
IsBatchAtomic: string;
BatchContinueOnError: string;
DedicatedGatewayPerRequestCacheStaleness: string;
DedicatedGatewayPerRequestBypassCache: string;
ForceRefresh: string;
PriorityLevel: string;
ThroughputBucket: string;
IsClientEncryptedHeader: string;
IntendedCollectionHeader: string;
DatabaseRidHeader: string;
AllowCachedReadsHeader: string;
};
ThrottledRequestMaxRetryAttemptCount: number;
ThrottledRequestMaxWaitTimeInSeconds: number;
ThrottledRequestFixedRetryIntervalInMs: number;
WritableLocations: string;
ReadableLocations: string;
LocationUnavailableExpirationTimeInMs: number;
ENABLE_MULTIPLE_WRITABLE_LOCATIONS: string;
DefaultUnavailableLocationExpirationTimeMS: number;
ThrottleRetryCount: string;
ThrottleRetryWaitTimeInMs: string;
CurrentVersion: string;
AzureNamespace: string;
AzurePackageName: string;
SDKName: string;
SDKVersion: string;
CosmosDbDiagnosticLevelEnvVarName: string;
DefaultMaxBulkRequestBodySizeInBytes: number;
Encryption: {
DiagnosticsDecryptOperation: string;
DiagnosticsDuration: string;
DiagnosticsEncryptionDiagnostics: string;
DiagnosticsEncryptOperation: string;
DiagnosticsPropertiesEncryptedCount: string;
DiagnosticsPropertiesDecryptedCount: string;
DiagnosticsStartTime: string;
};
Quota: {
CollectionSize: string;
};
Path: {
Root: string;
DatabasesPathSegment: string;
CollectionsPathSegment: string;
UsersPathSegment: string;
DocumentsPathSegment: string;
PermissionsPathSegment: string;
StoredProceduresPathSegment: string;
TriggersPathSegment: string;
UserDefinedFunctionsPathSegment: string;
ConflictsPathSegment: string;
AttachmentsPathSegment: string;
PartitionKeyRangesPathSegment: string;
SchemasPathSegment: string;
OffersPathSegment: string;
TopologyPathSegment: string;
DatabaseAccountPathSegment: string;
};
PartitionKeyRange: PartitionKeyRangePropertiesNames;
QueryRangeConstants: {
MinInclusive: string;
MaxExclusive: string;
min: string;
};
/**
* @deprecated Use EffectivePartitionKeyConstants instead
*/
EffectiveParitionKeyConstants: {
MinimumInclusiveEffectivePartitionKey: string;
MaximumExclusiveEffectivePartitionKey: string;
};
EffectivePartitionKeyConstants: {
MinimumInclusiveEffectivePartitionKey: string;
MaximumExclusiveEffectivePartitionKey: string;
};
AllVersionsAndDeletesChangeFeedWireFormatVersion: string;
ChangeFeedIfNoneMatchStartFromNowHeader: string;
DefaultEncryptionCacheTimeToLiveInSeconds: number;
EncryptionCacheRefreshIntervalInMs: number;
};
/**
* Operations for reading, replacing, or deleting a specific, existing container by id.
*
* @see {@link Containers} for creating new containers, and reading/querying all containers; use `.containers`.
*
* Note: all these operations make calls against a fixed budget.
* You should design your system such that these calls scale sublinearly with your application.
* For instance, do not call `container(id).read()` before every single `item.read()` call, to ensure the container exists;
* do this once on application start up.
*/
export declare class Container {
readonly database: Database;
readonly id: string;
private readonly clientContext;
private encryptionManager?;
private $items;
/**
* Operations for creating new items, and reading/querying all items
*
* For reading, replacing, or deleting an existing item, use `.item(id)`.
*
* @example Create a new item
* ```typescript
* const {body: createdItem} = await container.items.create({id: "<item id>", properties: {}});
* ```
*/
get items(): Items;
private $scripts;
/**
* All operations for Stored Procedures, Triggers, and User Defined Functions
*/
get scripts(): Scripts;
private $conflicts;
/**
* Operations for reading and querying conflicts for the given container.
*
* For reading or deleting a specific conflict, use `.conflict(id)`.
*/
get conflicts(): Conflicts;
/**
* Returns a reference URL to the resource. Used for linking in Permissions.
*/
get url(): string;
private isEncryptionInitialized;
private encryptionInitializationPromise;
/**
* Returns a container instance. Note: You should get this from `database.container(id)`, rather than creating your own object.
* @param database - The parent {@link Database}.
* @param id - The id of the given container.
* @hidden
*/
constructor(database: Database, id: string, clientContext: ClientContext, encryptionManager?: EncryptionManager, _rid?: string);
/**
* Used to read, replace, or delete a specific, existing {@link Item} by id.
*
* Use `.items` for creating new items, or querying/reading all items.
*
* @param id - The id of the {@link Item}.
* @param partitionKeyValue - The value of the {@link Item} partition key
* @example Replace an item
* `const {body: replacedItem} = await container.item("<item id>", "<partition key value>").replace({id: "<item id>", title: "Updated post", authorID: 5});`
*/
item(id: string, partitionKeyValue?: PartitionKey): Item;
/**
* Used to read, replace, or delete a specific, existing {@link Conflict} by id.
*
* Use `.conflicts` for creating new conflicts, or querying/reading all conflicts.
* @param id - The id of the {@link Conflict}.
*/
conflict(id: string, partitionKey?: PartitionKey): Conflict;
/** Read the container's definition */
read(options?: RequestOptions): Promise<ContainerResponse>;
/**
* @hidden
*/
readInternal(diagnosticNode: DiagnosticNodeInternal, options?: RequestOptions): Promise<ContainerResponse>;
/** Replace the container's definition */
replace(body: ContainerDefinition, options?: RequestOptions): Promise<ContainerResponse>;
/** Delete the container */
delete(options?: RequestOptions): Promise<ContainerResponse>;
/**
* Gets the partition key definition first by looking into the cache otherwise by reading the collection.
* @deprecated This method has been renamed to readPartitionKeyDefinition.
*/
getPartitionKeyDefinit