@probitas/expect

Type-safe expectation library for Probitas scenario testing with specialized assertions for various client types.

This module provides a unified expect() function that automatically dispatches to the appropriate expectation based on the input type, along with specialized expectations for each client type.

Features

  • Type-safe expectations: Compile-time safety with TypeScript
  • Unified API: Single expect() function that dispatches to specialized expectations
  • Client-specific assertions: Tailored expectations for HTTP, GraphQL, SQL, Redis, MongoDB, and more
  • Method chaining: Fluent API for readable test assertions
  • Consistent naming: All methods follow toBeXxx or toHaveXxx patterns
  • Generic fallback: Chainable wrapper for @std/expect matchers

Usage

Unified expect Function

The expect() function automatically dispatches to the appropriate expectation based on the input type:

Installation

deno add jsr:@probitas/expect

Classes

class

#ConnectRpcError

class ConnectRpcError extends ClientError

Base error class for ConnectRPC/gRPC errors.

NameDescription
name
kind
code
rawMessage
metadata
details
Constructor
new ConnectRpcError(message: string, code: ConnectRpcStatusCode, rawMessage: string, options?: ConnectRpcErrorOptions)
Properties
  • readonlynamestring
  • readonlykind"connectrpc"
  • readonlyrawMessagestring
  • readonlymetadata?Record<string, string>
  • readonlydetailsreadonly ErrorDetail[]
class

#ConnectRpcInternalError

class ConnectRpcInternalError extends ConnectRpcError

Error thrown for internal server errors (code 13).

NameDescription
name
code
Constructor
new ConnectRpcInternalError(rawMessage: string, options?: ConnectRpcErrorOptions)
Properties
  • readonlyname"ConnectRpcInternalError"
  • readonlycode13
class

#ConnectRpcNotFoundError

class ConnectRpcNotFoundError extends ConnectRpcError

Error thrown when the requested resource is not found (code 5).

NameDescription
name
code
Constructor
new ConnectRpcNotFoundError(rawMessage: string, options?: ConnectRpcErrorOptions)
Properties
  • readonlyname"ConnectRpcNotFoundError"
  • readonlycode5
class

#ConnectRpcPermissionDeniedError

class ConnectRpcPermissionDeniedError extends ConnectRpcError

Error thrown when the client lacks permission (code 7).

NameDescription
name
code
Constructor
new ConnectRpcPermissionDeniedError(rawMessage: string, options?: ConnectRpcErrorOptions)
Properties
  • readonlyname"ConnectRpcPermissionDeniedError"
  • readonlycode7
class

#ConnectRpcResourceExhaustedError

class ConnectRpcResourceExhaustedError extends ConnectRpcError

Error thrown when a resource is exhausted (code 8).

NameDescription
name
code
Constructor
new ConnectRpcResourceExhaustedError(rawMessage: string, options?: ConnectRpcErrorOptions)
Properties
  • readonlyname"ConnectRpcResourceExhaustedError"
  • readonlycode8
class

#ConnectRpcResponseImpl

class ConnectRpcResponseImpl implements ConnectRpcResponse

Implementation of ConnectRpcResponse.

NameDescription
type
ok
code
message
headers
trailers
duration
data()
raw()
Constructor
new ConnectRpcResponseImpl(options: ConnectRpcResponseOptions)
Properties
  • readonlytype"connectrpc"
  • readonlyokboolean
  • readonlymessagestring
  • readonlyheadersRecord<string, string>
  • readonlytrailersRecord<string, string>
  • readonlydurationnumber
Methods
data(): unknown
raw(): unknown
class

#ConnectRpcUnauthenticatedError

class ConnectRpcUnauthenticatedError extends ConnectRpcError

Error thrown when the client is not authenticated (code 16).

NameDescription
name
code
Constructor
new ConnectRpcUnauthenticatedError(rawMessage: string, options?: ConnectRpcErrorOptions)
Properties
  • readonlyname"ConnectRpcUnauthenticatedError"
  • readonlycode16
class

#ConnectRpcUnavailableError

class ConnectRpcUnavailableError extends ConnectRpcError

Error thrown when the service is unavailable (code 14).

NameDescription
name
code
Constructor
new ConnectRpcUnavailableError(rawMessage: string, options?: ConnectRpcErrorOptions)
Properties
  • readonlyname"ConnectRpcUnavailableError"
  • readonlycode14
class

#ConstraintError

class ConstraintError extends SqlError
ExtendsSqlError

Error thrown when a constraint violation occurs.

NameDescription
name
kind
constraint
Constructor
new ConstraintError(message: string, constraint: string, options?: SqlErrorOptions)
Properties
  • readonlynamestring
  • readonlykind"constraint"
  • readonlyconstraintstring
class

#DeadlockError

class DeadlockError extends SqlError
ExtendsSqlError

Error thrown when a deadlock is detected.

NameDescription
name
kind
Constructor
new DeadlockError(message: string, options?: SqlErrorOptions)
Properties
  • readonlynamestring
  • readonlykind"deadlock"
class

#DenoKvAtomicBuilderImpl

class DenoKvAtomicBuilderImpl implements DenoKvAtomicBuilder

Implementation of DenoKvAtomicBuilder.

NameDescription
check()
set()
delete()
sum()
min()
max()
commit()
Constructor
new DenoKvAtomicBuilderImpl(kv: Deno.Kv)
Methods
check(): unknown
set(): unknown
delete(): unknown
sum(): unknown
min(): unknown
max(): unknown
commit(): unknown
class

#DenoKvAtomicCheckError

class DenoKvAtomicCheckError extends DenoKvError

Error thrown when an atomic operation fails due to check failures.

NameDescription
name
kind
failedChecksThe keys whose checks failed.
Constructor
new DenoKvAtomicCheckError(message: string, failedChecks: readonly Deno.KvKey[], options?: ErrorOptions)
Properties
  • readonlynamestring
  • readonlykind"atomic_check"
  • readonlyfailedChecksreadonly Deno.KvKey[]

    The keys whose checks failed.

class

#DenoKvError

class DenoKvError extends ClientError

Base error class for Deno KV operations.

NameDescription
name
Constructor
new DenoKvError(message: string, _: unknown, options?: ErrorOptions)
Properties
  • readonlynamestring
class

#DenoKvQuotaError

class DenoKvQuotaError extends DenoKvError

Error thrown when a quota limit is exceeded.

NameDescription
name
kind
Constructor
new DenoKvQuotaError(message: string, options?: ErrorOptions)
Properties
  • readonlynamestring
  • readonlykind"quota"
class

#GraphqlError

class GraphqlError extends ClientError

Base GraphQL error class.

NameDescription
name
kind
errorsGraphQL errors from response
responseAssociated GraphQL response (if available)
Constructor
new GraphqlError(message: string, errors: readonly GraphqlErrorItem[], options?: GraphqlErrorOptions)
Properties
  • readonlynamestring
  • readonlykind"graphql"
  • readonlyerrorsreadonly GraphqlErrorItem[]

    GraphQL errors from response

  • readonlyresponse?GraphqlResponse

    Associated GraphQL response (if available)

class

#GraphqlExecutionError

class GraphqlExecutionError extends GraphqlError

Error thrown for GraphQL execution errors.

NameDescription
name
Constructor
new GraphqlExecutionError(errors: readonly GraphqlErrorItem[], options?: GraphqlErrorOptions)
Properties
  • readonlynamestring
class

#GraphqlNetworkError

class GraphqlNetworkError extends GraphqlError

Error thrown for network/HTTP errors before GraphQL processing.

NameDescription
name
Constructor
new GraphqlNetworkError(message: string, options?: ErrorOptions)
Properties
  • readonlynamestring
class

#GraphqlValidationError

class GraphqlValidationError extends GraphqlError

Error thrown for GraphQL validation errors.

NameDescription
name
Constructor
new GraphqlValidationError(errors: readonly GraphqlErrorItem[], options?: GraphqlErrorOptions)
Properties
  • readonlynamestring
class

#HttpBadRequestError

class HttpBadRequestError extends HttpError
ExtendsHttpError

HTTP 400 Bad Request error.

NameDescription
name
status
statusText
Constructor
new HttpBadRequestError(message: string, options?: HttpErrorOptions)
Properties
  • readonlynamestring
  • readonlystatus400
  • readonlystatusTextstring
class

#HttpConflictError

class HttpConflictError extends HttpError
ExtendsHttpError

HTTP 409 Conflict error.

NameDescription
name
status
statusText
Constructor
new HttpConflictError(message: string, options?: HttpErrorOptions)
Properties
  • readonlynamestring
  • readonlystatus409
  • readonlystatusTextstring
class

#HttpError

class HttpError extends ClientError

Base HTTP error class.

NameDescription
name
kind
statusHTTP status code
statusTextHTTP status text
responseAssociated HTTP response (if available)
Constructor
new HttpError(message: string, status: number, statusText: string, options?: HttpErrorOptions)
Properties
  • readonlynamestring
  • readonlykind"http"
  • readonlystatusnumber

    HTTP status code

  • readonlystatusTextstring

    HTTP status text

  • readonlyresponse?HttpResponse

    Associated HTTP response (if available)

class

#HttpForbiddenError

class HttpForbiddenError extends HttpError
ExtendsHttpError

HTTP 403 Forbidden error.

NameDescription
name
status
statusText
Constructor
new HttpForbiddenError(message: string, options?: HttpErrorOptions)
Properties
  • readonlynamestring
  • readonlystatus403
  • readonlystatusTextstring
class

#HttpInternalServerError

class HttpInternalServerError extends HttpError
ExtendsHttpError

HTTP 500 Internal Server Error.

NameDescription
name
status
statusText
Constructor
new HttpInternalServerError(message: string, options?: HttpErrorOptions)
Properties
  • readonlynamestring
  • readonlystatus500
  • readonlystatusTextstring
class

#HttpNotFoundError

class HttpNotFoundError extends HttpError
ExtendsHttpError

HTTP 404 Not Found error.

NameDescription
name
status
statusText
Constructor
new HttpNotFoundError(message: string, options?: HttpErrorOptions)
Properties
  • readonlynamestring
  • readonlystatus404
  • readonlystatusTextstring
class

#HttpTooManyRequestsError

class HttpTooManyRequestsError extends HttpError
ExtendsHttpError

HTTP 429 Too Many Requests error.

NameDescription
name
status
statusText
Constructor
new HttpTooManyRequestsError(message: string, options?: HttpErrorOptions)
Properties
  • readonlynamestring
  • readonlystatus429
  • readonlystatusTextstring
class

#HttpUnauthorizedError

class HttpUnauthorizedError extends HttpError
ExtendsHttpError

HTTP 401 Unauthorized error.

NameDescription
name
status
statusText
Constructor
new HttpUnauthorizedError(message: string, options?: HttpErrorOptions)
Properties
  • readonlynamestring
  • readonlystatus401
  • readonlystatusTextstring
class

#MongoConnectionError

class MongoConnectionError extends MongoError
ExtendsMongoError

Error thrown when a MongoDB connection cannot be established.

NameDescription
name
kind
Constructor
new MongoConnectionError(message: string, options?: MongoErrorOptions)
Properties
  • readonlynamestring
  • readonlykind"connection"
class

#MongoDuplicateKeyError

class MongoDuplicateKeyError extends MongoError
ExtendsMongoError

Error thrown when a duplicate key constraint is violated.

NameDescription
name
kind
keyPattern
keyValue
Constructor
new MongoDuplicateKeyError(message: string, keyPattern: Record<string, number>, keyValue: Record<string, unknown>, options?: MongoErrorOptions)
Properties
  • readonlynamestring
  • readonlykind"duplicate_key"
  • readonlykeyPatternRecord<string, number>
  • readonlykeyValueRecord<string, unknown>
class

#MongoError

class MongoError extends ClientError

Base error class for MongoDB client errors.

NameDescription
name
code
Constructor
new MongoError(message: string, _: unknown, options?: MongoErrorOptions)
Properties
  • readonlynamestring
  • readonlycode?number
class

#MongoNotFoundError

class MongoNotFoundError extends MongoError
ExtendsMongoError

Error thrown when a document is not found (for firstOrThrow, lastOrThrow).

NameDescription
name
kind
Constructor
new MongoNotFoundError(message: string, options?: MongoErrorOptions)
Properties
  • readonlynamestring
  • readonlykind"not_found"
class

#MongoQueryError

class MongoQueryError extends MongoError
ExtendsMongoError

Error thrown when a MongoDB query fails.

NameDescription
name
kind
collection
Constructor
new MongoQueryError(message: string, collection: string, options?: MongoErrorOptions)
Properties
  • readonlynamestring
  • readonlykind"query"
  • readonlycollectionstring
class

#MongoValidationError

class MongoValidationError extends MongoError
ExtendsMongoError

Error thrown when document validation fails.

NameDescription
name
kind
validationErrors
Constructor
new MongoValidationError(message: string, validationErrors: readonly string[], options?: MongoErrorOptions)
Properties
  • readonlynamestring
  • readonlykind"validation"
  • readonlyvalidationErrorsreadonly string[]
class

#MongoWriteError

class MongoWriteError extends MongoError
ExtendsMongoError

Error thrown when a write operation fails.

NameDescription
name
kind
writeErrors
Constructor
new MongoWriteError(message: string, writeErrors: readonly { index: number; code: number; message: string }[], options?: MongoErrorOptions)
Properties
  • readonlynamestring
  • readonlykind"write"
  • readonlywriteErrorsreadonly { index: number; code: number; message: string }[]
class

#QuerySyntaxError

class QuerySyntaxError extends SqlError
ExtendsSqlError

Error thrown when a SQL query has syntax errors.

NameDescription
name
kind
Constructor
new QuerySyntaxError(message: string, options?: SqlErrorOptions)
Properties
  • readonlynamestring
  • readonlykind"query"
class

#RabbitMqChannelError

class RabbitMqChannelError extends RabbitMqError

Error thrown when a RabbitMQ channel operation fails.

NameDescription
name
kind
channelId
Constructor
new RabbitMqChannelError(message: string, options?: RabbitMqChannelErrorOptions)
Properties
  • readonlynamestring
  • readonlykind"channel"
  • readonlychannelId?number
class

#RabbitMqConnectionError

class RabbitMqConnectionError extends RabbitMqError

Error thrown when a RabbitMQ connection cannot be established.

NameDescription
name
kind
Constructor
new RabbitMqConnectionError(message: string, options?: RabbitMqErrorOptions)
Properties
  • readonlynamestring
  • readonlykind"connection"
class

#RabbitMqError

class RabbitMqError extends ClientError

Base error class for RabbitMQ client errors.

NameDescription
name
code
Constructor
new RabbitMqError(message: string, _: unknown, options?: RabbitMqErrorOptions)
Properties
  • readonlynamestring
  • readonlycode?number
class

#RabbitMqNotFoundError

class RabbitMqNotFoundError extends RabbitMqError

Error thrown when a RabbitMQ resource (queue or exchange) is not found.

NameDescription
name
kind
resource
Constructor
new RabbitMqNotFoundError(message: string, options: RabbitMqNotFoundErrorOptions)
Properties
  • readonlynamestring
  • readonlykind"not_found"
  • readonlyresourcestring
class

#RabbitMqPreconditionFailedError

class RabbitMqPreconditionFailedError extends RabbitMqError

Error thrown when a RabbitMQ precondition check fails.

NameDescription
name
kind
reason
Constructor
new RabbitMqPreconditionFailedError(message: string, options: RabbitMqPreconditionFailedErrorOptions)
Properties
  • readonlynamestring
  • readonlykind"precondition_failed"
  • readonlyreasonstring
class

#RedisCommandError

class RedisCommandError extends RedisError
ExtendsRedisError

Error thrown when a Redis command fails.

NameDescription
name
kind
command
Constructor
new RedisCommandError(message: string, options: RedisCommandErrorOptions)
Properties
  • readonlynamestring
  • readonlykind"command"
  • readonlycommandstring
class

#RedisConnectionError

class RedisConnectionError extends RedisError
ExtendsRedisError

Error thrown when a Redis connection cannot be established.

NameDescription
name
kind
Constructor
new RedisConnectionError(message: string, options?: RedisErrorOptions)
Properties
  • readonlynamestring
  • readonlykind"connection"
class

#RedisError

class RedisError extends ClientError

Base error class for Redis client errors.

NameDescription
name
code
Constructor
new RedisError(message: string, _: unknown, options?: RedisErrorOptions)
Properties
  • readonlynamestring
  • readonlycode?string
class

#RedisScriptError

class RedisScriptError extends RedisError
ExtendsRedisError

Error thrown when a Redis Lua script fails.

NameDescription
name
kind
script
Constructor
new RedisScriptError(message: string, options: RedisScriptErrorOptions)
Properties
  • readonlynamestring
  • readonlykind"script"
  • readonlyscriptstring
class

#SqlError

class SqlError extends ClientError

Base error class for SQL-specific errors. Extends ClientError with SQL-specific properties.

NameDescription
name
kind
sqlState
Constructor
new SqlError(message: string, kind: SqlErrorKind, options?: SqlErrorOptions)
Properties
  • readonlynamestring
  • readonlykindSqlErrorKind
  • readonlysqlState?string
class

#SqlQueryResult

class SqlQueryResult<T = Record<string, any>>

SQL query result with rows, metadata, and transformation methods.

NameDescription
type
ok
rows
rowCount
duration
metadata
map()Map rows to a new type.
as()Create class instances from rows.
Constructor
new SqlQueryResult(init: SqlQueryResultInit<T>)
Properties
Methods
map(): unknown

Map rows to a new type.

as(): unknown

Create class instances from rows.

class

#SqlRows

class SqlRows<T> extends Array<T>
ExtendsArray<T>

Row array with first/last helper methods. Implements ReadonlyArray by extending Array.

NameDescription
first()Get the first row, or undefined if empty.
firstOrThrow()Get the first row, or throw if empty.
last()Get the last row, or undefined if empty.
lastOrThrow()Get the last row, or throw if empty.
Constructor
new SqlRows(items: readonly T[])
Methods
first(): unknown

Get the first row, or undefined if empty.

firstOrThrow(): unknown

Get the first row, or throw if empty.

last(): unknown

Get the last row, or undefined if empty.

lastOrThrow(): unknown

Get the last row, or throw if empty.

class

#SqsBatchError

class SqsBatchError extends SqsError
ExtendsSqsError

Error thrown when a batch operation partially fails.

NameDescription
name
kind
failedCount
Constructor
new SqsBatchError(message: string, failedCount: number, options?: SqsErrorOptions)
Properties
  • readonlynamestring
  • readonlykind"batch"
  • readonlyfailedCountnumber
class

#SqsCommandError

class SqsCommandError extends SqsError
ExtendsSqsError

Error thrown when an SQS command fails.

NameDescription
name
kind
operation
Constructor
new SqsCommandError(message: string, options: SqsCommandErrorOptions)
Properties
  • readonlynamestring
  • readonlykind"command"
  • readonlyoperationstring
class

#SqsConnectionError

class SqsConnectionError extends SqsError
ExtendsSqsError

Error thrown when an SQS connection cannot be established.

NameDescription
name
kind
Constructor
new SqsConnectionError(message: string, options?: SqsErrorOptions)
Properties
  • readonlynamestring
  • readonlykind"connection"
class

#SqsError

class SqsError extends ClientError

Base error class for SQS client errors.

NameDescription
name
code
Constructor
new SqsError(message: string, _: unknown, options?: SqsErrorOptions)
Properties
  • readonlynamestring
  • readonlycode?string
class

#SqsMessageNotFoundError

class SqsMessageNotFoundError extends SqsError
ExtendsSqsError

Error thrown when a message is not found or receipt handle is invalid.

NameDescription
name
kind
Constructor
new SqsMessageNotFoundError(message: string, options?: SqsErrorOptions)
Properties
  • readonlynamestring
  • readonlykind"message_not_found"
class

#SqsMessageTooLargeError

class SqsMessageTooLargeError extends SqsError
ExtendsSqsError

Error thrown when a message exceeds the size limit.

NameDescription
name
kind
size
maxSize
Constructor
new SqsMessageTooLargeError(message: string, size: number, maxSize: number, options?: SqsErrorOptions)
Properties
  • readonlynamestring
  • readonlykind"message_too_large"
  • readonlysizenumber
  • readonlymaxSizenumber
class

#SqsQueueNotFoundError

class SqsQueueNotFoundError extends SqsError
ExtendsSqsError

Error thrown when a queue is not found.

NameDescription
name
kind
queueUrl
Constructor
new SqsQueueNotFoundError(message: string, queueUrl: string, options?: SqsErrorOptions)
Properties
  • readonlynamestring
  • readonlykind"queue_not_found"
  • readonlyqueueUrlstring

Interfaces

interface

#AnythingExpectation

interface AnythingExpectation

Chainable expectation interface for any value using @std/expect matchers.

Unlike @std/expect which returns void from matchers, this interface returns this to enable method chaining.

NameDescription
notNegates the next assertion.
toBe()Asserts that the value is strictly equal (`===`) to the expected value.
toEqual()Asserts that the value is deeply equal to the expected value.
toStrictEqual()Asserts that the value is strictly deeply equal to the expected value.
toMatch()Asserts that the string matches the expected pattern.
toMatchObject()Asserts that the object matches a subset of properties.
toBeDefined()Asserts that the value is not `undefined`.
toBeUndefined()Asserts that the value is `undefined`.
toBeNull()Asserts that the value is `null`.
toBeNaN()Asserts that the value is `NaN`.
toBeTruthy()Asserts that the value is truthy (not `false`, `0`, `""`, `null`, `undefined`, or `NaN`).
toBeFalsy()Asserts that the value is falsy (`false`, `0`, `""`, `null`, `undefined`, or `NaN`).
toContain()Asserts that an array or string contains the expected item or substring.
toContainEqual()Asserts that an array contains an item equal to the expected value.
toHaveLength()Asserts that the array or string has the expected length.
toBeGreaterThan()Asserts that the number is greater than the expected value.
toBeGreaterThanOrEqual()Asserts that the number is greater than or equal to the expected value.
toBeLessThan()Asserts that the number is less than the expected value.
toBeLessThanOrEqual()Asserts that the number is less than or equal to the expected value.
toBeCloseTo()Asserts that the number is close to the expected value within a certain precision.
toBeInstanceOf()Asserts that the value is an instance of the expected class.
toThrow()Asserts that a function throws an error matching the expected pattern.
toHaveProperty()Asserts that the object has a property at the specified path.
toHaveBeenCalled()Asserts that a mock function was called at least once.
toHaveBeenCalledTimes()Asserts that a mock function was called exactly the specified number of times.
toHaveBeenCalledWith()Asserts that a mock function was called with the specified arguments.
toHaveBeenLastCalledWith()Asserts that a mock function was last called with the specified arguments.
toHaveBeenNthCalledWith()Asserts that the nth call of a mock function was with the specified arguments.
toHaveReturned()Asserts that a mock function returned successfully at least once.
toHaveReturnedTimes()Asserts that a mock function returned successfully the specified number of times.
toHaveReturnedWith()Asserts that a mock function returned the specified value at least once.
toHaveLastReturnedWith()Asserts that a mock function last returned the specified value.
toHaveNthReturnedWith()Asserts that the nth call of a mock function returned the specified value.
Properties
  • readonlynotthis

    Negates the next assertion.

Methods
toBe(expected: unknown): this

Asserts that the value is strictly equal (===) to the expected value.

Parameters
  • expectedunknown
    • The expected value
toEqual(expected: unknown): this

Asserts that the value is deeply equal to the expected value.

Parameters
  • expectedunknown
    • The expected value
toStrictEqual(expected: unknown): this

Asserts that the value is strictly deeply equal to the expected value. Unlike toEqual, this checks object types and undefined properties.

Parameters
  • expectedunknown
    • The expected value
toMatch(expected: string | RegExp): this

Asserts that the string matches the expected pattern.

Parameters
  • expectedstring | RegExp
    • A string or RegExp pattern
toMatchObject(expected: Record<string, unknown>): this

Asserts that the object matches a subset of properties.

Parameters
  • expectedRecord<string, unknown>
    • An object containing expected properties
toBeDefined(): this

Asserts that the value is not undefined.

toBeUndefined(): this

Asserts that the value is undefined.

toBeNull(): this

Asserts that the value is null.

toBeNaN(): this

Asserts that the value is NaN.

toBeTruthy(): this

Asserts that the value is truthy (not false, 0, "", null, undefined, or NaN).

toBeFalsy(): this

Asserts that the value is falsy (false, 0, "", null, undefined, or NaN).

toContain(expected: unknown): this

Asserts that an array or string contains the expected item or substring.

Parameters
  • expectedunknown
    • The item or substring to check for
toContainEqual(expected: unknown): this

Asserts that an array contains an item equal to the expected value.

Parameters
  • expectedunknown
    • The item to check for equality
toHaveLength(expected: number): this

Asserts that the array or string has the expected length.

Parameters
  • expectednumber
    • The expected length
toBeGreaterThan(expected: number): this

Asserts that the number is greater than the expected value.

Parameters
  • expectednumber
    • The value to compare against
toBeGreaterThanOrEqual(expected: number): this

Asserts that the number is greater than or equal to the expected value.

Parameters
  • expectednumber
    • The value to compare against
toBeLessThan(expected: number): this

Asserts that the number is less than the expected value.

Parameters
  • expectednumber
    • The value to compare against
toBeLessThanOrEqual(expected: number): this

Asserts that the number is less than or equal to the expected value.

Parameters
  • expectednumber
    • The value to compare against
toBeCloseTo(expected: number, numDigits?: number): this

Asserts that the number is close to the expected value within a certain precision.

Parameters
  • expectednumber
    • The expected value
  • numDigits?number
    • Number of decimal digits to check (default: 2)
toBeInstanceOf(expected: (_: any[]) => unknown): this

Asserts that the value is an instance of the expected class.

Parameters
  • expected(_: any[]) => unknown
    • The expected constructor/class
toThrow(expected?: string | RegExp | Error): this

Asserts that a function throws an error matching the expected pattern.

Parameters
  • expected?string | RegExp | Error
    • Optional string, RegExp, or Error to match
toHaveProperty(keyPath: string | string[], expectedValue?: unknown): this

Asserts that the object has a property at the specified path.

Parameters
  • keyPathstring | string[]
    • The property path (string or array of strings)
  • expectedValue?unknown
    • Optional expected value at the path
toHaveBeenCalled(): this

Asserts that a mock function was called at least once.

toHaveBeenCalledTimes(expected: number): this

Asserts that a mock function was called exactly the specified number of times.

Parameters
  • expectednumber
    • The expected number of calls
toHaveBeenCalledWith(_: unknown[]): this

Asserts that a mock function was called with the specified arguments.

Parameters
  • _unknown[]
toHaveBeenLastCalledWith(_: unknown[]): this

Asserts that a mock function was last called with the specified arguments.

Parameters
  • _unknown[]
toHaveBeenNthCalledWith(n: number, _: unknown[]): this

Asserts that the nth call of a mock function was with the specified arguments.

Parameters
  • nnumber
    • The call index (1-based)
  • _unknown[]
toHaveReturned(): this

Asserts that a mock function returned successfully at least once.

toHaveReturnedTimes(expected: number): this

Asserts that a mock function returned successfully the specified number of times.

Parameters
  • expectednumber
    • The expected number of successful returns
toHaveReturnedWith(expected: unknown): this

Asserts that a mock function returned the specified value at least once.

Parameters
  • expectedunknown
    • The expected return value
toHaveLastReturnedWith(expected: unknown): this

Asserts that a mock function last returned the specified value.

Parameters
  • expectedunknown
    • The expected return value
toHaveNthReturnedWith(n: number, expected: unknown): this

Asserts that the nth call of a mock function returned the specified value.

Parameters
  • nnumber
    • The call index (1-based)
  • expectedunknown
    • The expected return value
interface

#ConnectRpcClient

interface ConnectRpcClient extends AsyncDisposable

ConnectRPC client interface.

NameDescription
configClient configuration
reflectionReflection API (only available when schema: "reflection")
call()Make a unary RPC call.
serverStream()Make a server streaming RPC call.
clientStream()Make a client streaming RPC call.
bidiStream()Make a bidirectional streaming RPC call.
close()Close the client connection.
Properties
Methods
call<TRequest = unknown>(serviceName: string, methodName: string, request: TRequest, options?: ConnectRpcOptions): Promise<ConnectRpcResponse>

Make a unary RPC call.

Parameters
  • serviceNamestring
    • Service name (e.g., "echo.EchoService")
  • methodNamestring
    • Method name (e.g., "echo")
  • requestTRequest
    • Request message
    • Call options
serverStream<TRequest = unknown>(serviceName: string, methodName: string, request: TRequest, options?: ConnectRpcOptions): AsyncIterable<ConnectRpcResponse>

Make a server streaming RPC call.

Parameters
  • serviceNamestring
    • Service name
  • methodNamestring
    • Method name
  • requestTRequest
    • Request message
    • Call options
clientStream<TRequest = unknown>(serviceName: string, methodName: string, requests: AsyncIterable<TRequest>, options?: ConnectRpcOptions): Promise<ConnectRpcResponse>

Make a client streaming RPC call.

Parameters
  • serviceNamestring
    • Service name
  • methodNamestring
    • Method name
  • requestsAsyncIterable<TRequest>
    • Async iterable of request messages
    • Call options
bidiStream<TRequest = unknown>(serviceName: string, methodName: string, requests: AsyncIterable<TRequest>, options?: ConnectRpcOptions): AsyncIterable<ConnectRpcResponse>

Make a bidirectional streaming RPC call.

Parameters
  • serviceNamestring
    • Service name
  • methodNamestring
    • Method name
  • requestsAsyncIterable<TRequest>
    • Async iterable of request messages
    • Call options
close(): Promise<void>

Close the client connection.

interface

#ConnectRpcClientConfig

interface ConnectRpcClientConfig extends CommonOptions

Configuration for creating a ConnectRPC client.

NameDescription
urlServer URL for ConnectRPC connections.
protocolProtocol to use.
httpVersionHTTP version to use.
tlsTLS configuration.
metadataDefault metadata to send with every request.
schemaSchema resolution configuration.
useBinaryFormatWhether to use binary format for messages.
throwOnErrorWhether to throw ConnectRpcError on non-OK responses (code !== 0).
Properties
  • readonlyurlstring | ConnectRpcConnectionConfig

    Server URL for ConnectRPC connections.

    Can be a URL string or a connection configuration object.

  • readonlyprotocol?ConnectProtocol

    Protocol to use.

  • readonlyhttpVersion?HttpVersion

    HTTP version to use.

  • readonlytls?TlsConfig

    TLS configuration. If not provided, uses insecure credentials.

  • readonlymetadata?Record<string, string>

    Default metadata to send with every request.

  • readonlyschema?"reflection" | string | Uint8Array | FileDescriptorSet

    Schema resolution configuration.

    • "reflection": Use Server Reflection to discover services dynamically (default)
    • string: Path to FileDescriptorSet binary file (from buf build --output set.binpb)
    • Uint8Array: FileDescriptorSet binary data
    • FileDescriptorSet: Pre-parsed FileDescriptorSet message object
  • readonlyuseBinaryFormat?boolean

    Whether to use binary format for messages.

  • readonlythrowOnError?boolean

    Whether to throw ConnectRpcError on non-OK responses (code !== 0). Can be overridden per-request via ConnectRpcOptions.throwOnError.

interface

#ConnectRpcConnectionConfig

interface ConnectRpcConnectionConfig extends CommonConnectionConfig

ConnectRPC connection configuration.

Extends CommonConnectionConfig with ConnectRPC-specific options.

NameDescription
protocolProtocol to use.
pathService path prefix.
Properties
  • readonlyprotocol?"http" | "https"

    Protocol to use.

  • readonlypath?string

    Service path prefix.

interface

#ConnectRpcErrorOptions

interface ConnectRpcErrorOptions extends ErrorOptions

Options for ConnectRpcError construction.

NameDescription
metadataHeaders/metadata from the ConnectRPC response.
detailsRich error details from google.rpc.Status.
Properties
  • readonlymetadata?Record<string, string>

    Headers/metadata from the ConnectRPC response.

  • readonlydetails?readonly ErrorDetail[]

    Rich error details from google.rpc.Status.

interface

#ConnectRpcOptions

interface ConnectRpcOptions extends CommonOptions

Options for individual ConnectRPC calls.

NameDescription
metadataMetadata to send with the request.
throwOnErrorWhether to throw ConnectRpcError on non-OK responses (code !== 0).
Properties
  • readonlymetadata?Record<string, string>

    Metadata to send with the request.

  • readonlythrowOnError?boolean

    Whether to throw ConnectRpcError on non-OK responses (code !== 0). Overrides ConnectRpcClientConfig.throwOnError.

interface

#ConnectRpcResponse

interface ConnectRpcResponse

ConnectRPC response interface.

NameDescription
typeResult type identifier
okWhether the request was successful (code === 0).
codeConnectRPC/gRPC status code.
messageStatus message (empty string for successful responses).
headersResponse headers
trailersResponse trailers (sent at end of RPC)
durationResponse time in milliseconds.
data()Get deserialized response data.
raw()Get raw response message.
Properties
  • readonlytype"connectrpc"

    Result type identifier

  • readonlyokboolean

    Whether the request was successful (code === 0).

  • ConnectRPC/gRPC status code.

  • readonlymessagestring

    Status message (empty string for successful responses).

  • readonlyheadersRecord<string, string>

    Response headers

  • readonlytrailersRecord<string, string>

    Response trailers (sent at end of RPC)

  • readonlydurationnumber

    Response time in milliseconds.

Methods
data<T = any>(): T | null

Get deserialized response data. Returns the response message as-is (already deserialized by Connect). Returns null if the response is an error or has no data.

raw(): unknown

Get raw response message.

interface

#ConnectRpcResponseOptions

interface ConnectRpcResponseOptions

Options for creating a ConnectRpcResponse.

NameDescription
code
message
headers
trailers
duration
responseMessage
Properties
  • readonlymessagestring
  • readonlyheadersRecord<string, string>
  • readonlytrailersRecord<string, string>
  • readonlydurationnumber
  • readonlyresponseMessageunknown
interface

#CookieConfig

interface CookieConfig

Cookie handling configuration.

NameDescription
disabledDisable automatic cookie handling.
initialInitial cookies to populate the cookie jar.
Properties
  • readonlydisabled?boolean

    Disable automatic cookie handling. When disabled, cookies are not stored or sent automatically.

  • readonlyinitial?Record<string, string>

    Initial cookies to populate the cookie jar.

interface

#DenoKvAtomicBuilder

interface DenoKvAtomicBuilder

Builder for atomic KV operations.

NameDescription
check()Add version checks to the atomic operation.
set()Set a value in the KV store.
delete()Delete a key from the KV store.
sum()Atomically add to a bigint value (Deno.KvU64).
min()Atomically set to minimum of current and provided value.
max()Atomically set to maximum of current and provided value.
commit()Commit the atomic operation.
Methods
check(_: Deno.AtomicCheck[]): this

Add version checks to the atomic operation. If any check fails, the entire operation will fail.

Parameters
  • _Deno.AtomicCheck[]
set<T>(key: Deno.KvKey, value: T, options?: { expireIn?: number }): this

Set a value in the KV store.

Parameters
  • keyDeno.KvKey
  • valueT
  • options?{ expireIn?: number }
delete(key: Deno.KvKey): this

Delete a key from the KV store.

Parameters
  • keyDeno.KvKey
sum(key: Deno.KvKey, n: bigint): this

Atomically add to a bigint value (Deno.KvU64).

Parameters
  • keyDeno.KvKey
  • nbigint
min(key: Deno.KvKey, n: bigint): this

Atomically set to minimum of current and provided value.

Parameters
  • keyDeno.KvKey
  • nbigint
max(key: Deno.KvKey, n: bigint): this

Atomically set to maximum of current and provided value.

Parameters
  • keyDeno.KvKey
  • nbigint
commit(): Promise<DenoKvAtomicResult>

Commit the atomic operation.

interface

#DenoKvAtomicResult

interface DenoKvAtomicResult

Result of an atomic operation.

NameDescription
type
ok
versionstamp
duration
Properties
  • readonlytype"deno-kv:atomic"
  • readonlyokboolean
  • readonlyversionstamp?string
  • readonlydurationnumber
interface

#DenoKvClient

interface DenoKvClient extends AsyncDisposable

Deno KV client for Probitas scenario testing.

NameDescription
configClient configuration.
get()Get a single value by key.
getMany()Get multiple values by keys.
set()Set a value.
delete()Delete a key.
list()List entries by selector.
atomic()Create an atomic operation builder.
close()Close the KV connection.
Properties
Methods
get<T>(key: Deno.KvKey, options?: CommonOptions): Promise<DenoKvGetResult<T>>

Get a single value by key.

Parameters
getMany<T extends readonly unknown[]>(keys: readonly [unknown], options?: CommonOptions): Promise<unknown>

Get multiple values by keys.

Parameters
set<T>(key: Deno.KvKey, value: T, options?: DenoKvSetOptions): Promise<DenoKvSetResult>

Set a value.

Parameters
delete(key: Deno.KvKey, options?: CommonOptions): Promise<DenoKvDeleteResult>

Delete a key.

Parameters
list<T>(selector: Deno.KvListSelector, options?: DenoKvListOptions): Promise<DenoKvListResult<T>>

List entries by selector.

Parameters
atomic(): DenoKvAtomicBuilder

Create an atomic operation builder.

close(): Promise<void>

Close the KV connection.

interface

#DenoKvClientConfig

interface DenoKvClientConfig extends CommonOptions

Configuration for DenoKvClient.

NameDescription
pathPath to the KV database file.
Properties
  • readonlypath?string

    Path to the KV database file. If not specified, uses in-memory storage or Deno Deploy's KV.

interface

#DenoKvDeleteResult

interface DenoKvDeleteResult

Result of a delete operation.

NameDescription
type
ok
duration
Properties
  • readonlytype"deno-kv:delete"
  • readonlyokboolean
  • readonlydurationnumber
interface

#DenoKvEntries

interface DenoKvEntries<T> extends ReadonlyArray<DenoKvEntry<T>>

Collection of KV entries with helper methods.

NameDescription
first()Returns the first entry, or undefined if empty.
firstOrThrow()Returns the first entry, or throws if empty.
last()Returns the last entry, or undefined if empty.
lastOrThrow()Returns the last entry, or throws if empty.
Methods
first(): DenoKvEntry<T> | undefined

Returns the first entry, or undefined if empty.

firstOrThrow(): DenoKvEntry<T>

Returns the first entry, or throws if empty.

last(): DenoKvEntry<T> | undefined

Returns the last entry, or undefined if empty.

lastOrThrow(): DenoKvEntry<T>

Returns the last entry, or throws if empty.

interface

#DenoKvEntry

interface DenoKvEntry<T>

A single entry in the KV store.

NameDescription
key
value
versionstamp
Properties
  • readonlykeyDeno.KvKey
  • readonlyvalueT
  • readonlyversionstampstring
interface

#DenoKvGetResult

interface DenoKvGetResult<T>

Result of a get operation.

NameDescription
type
ok
key
value
versionstamp
duration
Properties
  • readonlytype"deno-kv:get"
  • readonlyokboolean
  • readonlykeyDeno.KvKey
  • readonlyvalueT | null
  • readonlyversionstampstring | null
  • readonlydurationnumber
interface

#DenoKvListOptions

interface DenoKvListOptions extends CommonOptions

Options for list operations.

NameDescription
limitMaximum number of entries to return.
cursorCursor for pagination.
reverseWhether to iterate in reverse order.
Properties
  • readonlylimit?number

    Maximum number of entries to return.

  • readonlycursor?string

    Cursor for pagination.

  • readonlyreverse?boolean

    Whether to iterate in reverse order.

interface

#DenoKvListResult

interface DenoKvListResult<T>

Result of a list operation.

NameDescription
type
ok
entries
duration
Properties
  • readonlytype"deno-kv:list"
  • readonlyokboolean
  • readonlyentriesDenoKvEntries<T>
  • readonlydurationnumber
interface

#DenoKvSetOptions

interface DenoKvSetOptions extends CommonOptions

Options for set operations.

NameDescription
expireInTime-to-live in milliseconds.
Properties
  • readonlyexpireIn?number

    Time-to-live in milliseconds. The entry will automatically expire after this duration.

interface

#DenoKvSetResult

interface DenoKvSetResult

Result of a set operation.

NameDescription
type
ok
versionstamp
duration
Properties
  • readonlytype"deno-kv:set"
  • readonlyokboolean
  • readonlyversionstampstring
  • readonlydurationnumber
interface

#ErrorDetail

interface ErrorDetail

Rich error detail from google.rpc.Status.

ConnectRPC errors can include structured details encoded in error responses. These details follow the google.protobuf.Any format with a type URL and value.

NameDescription
typeUrlType URL identifying the error detail type.
valueDecoded error detail value.
Properties
  • readonlytypeUrlstring

    Type URL identifying the error detail type. Common types include:

    • "type.googleapis.com/google.rpc.BadRequest"
    • "type.googleapis.com/google.rpc.DebugInfo"
    • "type.googleapis.com/google.rpc.RetryInfo"
    • "type.googleapis.com/google.rpc.QuotaFailure"
  • readonlyvalueunknown

    Decoded error detail value. The structure depends on the typeUrl.

interface

#GraphqlClient

interface GraphqlClient extends AsyncDisposable

GraphQL client interface.

NameDescription
configClient configuration
query()Execute a GraphQL query
mutation()Execute a GraphQL mutation
execute()Execute a GraphQL document (query or mutation)
subscribe()Subscribe to a GraphQL subscription via WebSocket
close()Close the client and release resources
Properties
Methods
query<TData = any, TVariables = Record<string, any>>(query: string, variables?: TVariables, options?: GraphqlOptions): Promise<GraphqlResponse<TData>>

Execute a GraphQL query

Parameters
mutation<TData = any, TVariables = Record<string, any>>(mutation: string, variables?: TVariables, options?: GraphqlOptions): Promise<GraphqlResponse<TData>>

Execute a GraphQL mutation

Parameters
execute<TData = any, TVariables = Record<string, any>>(document: string, variables?: TVariables, options?: GraphqlOptions): Promise<GraphqlResponse<TData>>

Execute a GraphQL document (query or mutation)

Parameters
subscribe<TData = any, TVariables = Record<string, any>>(document: string, variables?: TVariables, options?: GraphqlOptions): AsyncIterable<GraphqlResponse<TData>>

Subscribe to a GraphQL subscription via WebSocket

Parameters
close(): Promise<void>

Close the client and release resources

interface

#GraphqlClientConfig

interface GraphqlClientConfig extends CommonOptions

GraphQL client configuration.

NameDescription
urlGraphQL endpoint URL.
headersDefault headers for all requests
wsEndpointWebSocket endpoint URL (for subscriptions)
fetchCustom fetch implementation (for testing/mocking)
throwOnErrorWhether to throw GraphqlError when response contains errors.
Properties
  • readonlyurlstring | GraphqlConnectionConfig

    GraphQL endpoint URL.

    Can be a URL string or a connection configuration object.

  • readonlyheaders?Record<string, string>

    Default headers for all requests

  • readonlywsEndpoint?string

    WebSocket endpoint URL (for subscriptions)

  • readonlyfetch?fetch

    Custom fetch implementation (for testing/mocking)

  • readonlythrowOnError?boolean

    Whether to throw GraphqlError when response contains errors. Can be overridden per-request via GraphqlOptions.

interface

#GraphqlConnectionConfig

interface GraphqlConnectionConfig extends CommonConnectionConfig

GraphQL connection configuration.

Extends CommonConnectionConfig with GraphQL-specific options.

NameDescription
protocolProtocol to use.
pathGraphQL endpoint path.
Properties
  • readonlyprotocol?"http" | "https"

    Protocol to use.

  • readonlypath?string

    GraphQL endpoint path.

interface

#GraphqlErrorItem

interface GraphqlErrorItem

GraphQL error item as per GraphQL specification.

NameDescription
messageError message
locationsLocation(s) in the GraphQL document where the error occurred
pathPath to the field that caused the error
extensionsAdditional error metadata
Properties
  • readonlymessagestring

    Error message

  • readonlylocations?readonly { line: number; column: number }[]

    Location(s) in the GraphQL document where the error occurred

  • readonlypath?readonly unknown[]

    Path to the field that caused the error

  • readonlyextensions?Record<string, unknown>

    Additional error metadata

interface

#GraphqlErrorOptions

interface GraphqlErrorOptions extends ErrorOptions

Options for GraphqlError constructor.

NameDescription
responseAssociated GraphQL response
Properties
interface

#GraphqlOptions

interface GraphqlOptions extends CommonOptions

Options for individual GraphQL requests.

NameDescription
headersAdditional request headers
operationNameOperation name (for documents with multiple operations)
throwOnErrorWhether to throw GraphqlError when response contains errors.
Properties
  • readonlyheaders?Record<string, string>

    Additional request headers

  • readonlyoperationName?string

    Operation name (for documents with multiple operations)

  • readonlythrowOnError?boolean

    Whether to throw GraphqlError when response contains errors.

interface

#GraphqlResponse

interface GraphqlResponse<T = any>

GraphQL response interface with pre-loaded body.

NameDescription
typeResult type identifier
okWhether the request was successful (no errors)
errorsGraphQL errors array (null if no errors)
extensionsResponse extensions
durationResponse time in milliseconds
statusHTTP status code
headersHeaders from the HTTP response
rawRaw Web standard Response (for streaming or special cases)
data()Get response data (null if no data).
Properties
  • readonlytype"graphql"

    Result type identifier

  • readonlyokboolean

    Whether the request was successful (no errors)

  • readonlyerrorsreadonly GraphqlErrorItem[] | null

    GraphQL errors array (null if no errors)

  • readonlyextensions?Record<string, unknown>

    Response extensions

  • readonlydurationnumber

    Response time in milliseconds

  • readonlystatusnumber

    HTTP status code

  • readonlyheadersHeaders

    Headers from the HTTP response

  • readonlyrawglobalThis.Response

    Raw Web standard Response (for streaming or special cases)

Methods
data<U = T>(): U | null

Get response data (null if no data). Does not throw even if errors are present.

interface

#GraphqlResponseOptions

interface GraphqlResponseOptions<T>

Options for creating a GraphqlResponse.

NameDescription
data
errors
extensions
duration
status
raw
Properties
  • readonlydataT | null
  • readonlyerrorsreadonly GraphqlErrorItem[] | null
  • readonlyextensions?Record<string, unknown>
  • readonlydurationnumber
  • readonlystatusnumber
  • readonlyrawglobalThis.Response
interface

#GrpcClientConfig

interface GrpcClientConfig extends Omit<ConnectRpcClientConfig, "protocol">

Configuration for creating a gRPC client.

This is a subset of ConnectRpcClientConfig with protocol fixed to "grpc".

interface

#HttpClient

interface HttpClient extends AsyncDisposable

HTTP client interface.

NameDescription
configClient configuration
get()Send GET request
post()Send POST request
put()Send PUT request
patch()Send PATCH request
delete()Send DELETE request
request()Send request with arbitrary method
getCookies()Get all cookies in the cookie jar.
setCookie()Set a cookie in the cookie jar.
clearCookies()Clear all cookies from the cookie jar.
close()Close the client and release resources
Properties
Methods
get(path: string, options?: HttpOptions): Promise<HttpResponse>

Send GET request

Parameters
post(path: string, body?: BodyInit, options?: HttpOptions): Promise<HttpResponse>

Send POST request

Parameters
put(path: string, body?: BodyInit, options?: HttpOptions): Promise<HttpResponse>

Send PUT request

Parameters
patch(path: string, body?: BodyInit, options?: HttpOptions): Promise<HttpResponse>

Send PATCH request

Parameters
delete(path: string, options?: HttpOptions): Promise<HttpResponse>

Send DELETE request

Parameters
request(method: string, path: string, options?: HttpOptions & { body?: BodyInit }): Promise<HttpResponse>

Send request with arbitrary method

Parameters
getCookies(): Record<string, string>

Get all cookies in the cookie jar. Returns empty object if cookies are disabled.

setCookie(name: string, value: string): void

Set a cookie in the cookie jar.

Parameters
  • namestring
  • valuestring
clearCookies(): void

Clear all cookies from the cookie jar. No-op if cookies are disabled.

close(): Promise<void>

Close the client and release resources

interface

#HttpClientConfig

interface HttpClientConfig extends CommonOptions

HTTP client configuration.

NameDescription
urlBase URL for all requests.
headersDefault headers for all requests
fetchCustom fetch implementation (for testing/mocking)
redirectDefault redirect handling mode.
throwOnErrorWhether to throw HttpError for non-2xx responses.
cookiesCookie handling configuration.
Properties
  • readonlyurlstring | HttpConnectionConfig

    Base URL for all requests.

    Can be a URL string or a connection configuration object.

  • readonlyheaders?Record<string, string>

    Default headers for all requests

  • readonlyfetch?fetch

    Custom fetch implementation (for testing/mocking)

  • readonlyredirect?RedirectMode

    Default redirect handling mode. Can be overridden per-request via HttpOptions.

  • readonlythrowOnError?boolean

    Whether to throw HttpError for non-2xx responses. Can be overridden per-request via HttpOptions.

  • readonlycookies?CookieConfig

    Cookie handling configuration. By default, the client maintains a cookie jar for automatic cookie management across requests. Set cookies: { disabled: true } to disable.

interface

#HttpConnectionConfig

interface HttpConnectionConfig extends CommonConnectionConfig

HTTP connection configuration.

Extends CommonConnectionConfig with HTTP-specific options.

NameDescription
protocolProtocol to use.
pathBase path prefix for all requests.
Properties
  • readonlyprotocol?"http" | "https"

    Protocol to use.

  • readonlypath?string

    Base path prefix for all requests.

interface

#HttpErrorOptions

interface HttpErrorOptions extends ErrorOptions

Options for HttpError constructor.

NameDescription
responseAssociated HTTP response
Properties
interface

#HttpOptions

interface HttpOptions extends CommonOptions

Options for individual HTTP requests.

NameDescription
queryQuery parameters (arrays for multi-value params)
headersAdditional request headers
redirectRedirect handling mode.
throwOnErrorWhether to throw HttpError for non-2xx responses.
Properties
  • readonlyquery?Record<string, QueryValue | QueryValue[]>

    Query parameters (arrays for multi-value params)

  • readonlyheaders?Record<string, string>

    Additional request headers

  • readonlyredirect?RedirectMode

    Redirect handling mode.

  • readonlythrowOnError?boolean

    Whether to throw HttpError for non-2xx responses. When false, non-2xx responses are returned as HttpResponse.

interface

#HttpResponse

interface HttpResponse

HTTP response with pre-loaded body for synchronous access.

Wraps Web standard Response, allowing body to be read synchronously and multiple times (unlike the streaming-based standard Response).

NameDescription
typeResult type identifier
okWhether the response was successful (status 200-299)
statusHTTP status code
statusTextHTTP status text
headersResponse headers
urlRequest URL
bodyResponse body as raw bytes (null if no body)
durationResponse time in milliseconds
rawRaw Web standard Response (for streaming or special cases)
arrayBuffer()Get body as ArrayBuffer (null if no body)
blob()Get body as Blob (null if no body)
text()Get body as text (null if no body)
data()Get body as parsed JSON (null if no body)
Properties
  • readonlytype"http"

    Result type identifier

  • readonlyokboolean

    Whether the response was successful (status 200-299)

  • readonlystatusnumber

    HTTP status code

  • readonlystatusTextstring

    HTTP status text

  • readonlyheadersHeaders

    Response headers

  • readonlyurlstring

    Request URL

  • readonlybodyUint8Array | null

    Response body as raw bytes (null if no body)

  • readonlydurationnumber

    Response time in milliseconds

  • readonlyrawglobalThis.Response

    Raw Web standard Response (for streaming or special cases)

Methods
arrayBuffer(): ArrayBuffer | null

Get body as ArrayBuffer (null if no body)

blob(): Blob | null

Get body as Blob (null if no body)

text(): string | null

Get body as text (null if no body)

data<T = any>(): T | null

Get body as parsed JSON (null if no body)

interface

#MethodInfo

interface MethodInfo

Method information from reflection.

NameDescription
nameMethod name (e.g., "Echo")
localNameLocal name (camelCase)
kindMethod kind
inputTypeInput message type name
outputTypeOutput message type name
idempotentWhether the method is idempotent
Properties
  • readonlynamestring

    Method name (e.g., "Echo")

  • readonlylocalNamestring

    Local name (camelCase)

  • readonlykind"unary" | "server_streaming" | "client_streaming" | "bidi_streaming"

    Method kind

  • readonlyinputTypestring

    Input message type name

  • readonlyoutputTypestring

    Output message type name

  • readonlyidempotentboolean

    Whether the method is idempotent

interface

#MongoClient

interface MongoClient extends AsyncDisposable

MongoDB client interface

NameDescription
config
collection()
db()
transaction()
close()
Properties
Methods
collection<T extends Document = Document>(name: string): MongoCollection<T>
Parameters
  • namestring
db(name: string): MongoClient
Parameters
  • namestring
transaction<T>(fn: (session: MongoSession) => unknown): Promise<T>
Parameters
close(): Promise<void>
interface

#MongoClientConfig

interface MongoClientConfig extends CommonOptions

MongoDB client configuration.

Examples

Using a connection string

const config: MongoClientConfig = {
  url: "mongodb://localhost:27017",
  database: "testdb",
};

Using a configuration object

const config: MongoClientConfig = {
  url: {
    host: "localhost",
    port: 27017,
    username: "admin",
    password: "secret",
    authSource: "admin",
  },
  database: "testdb",
};
NameDescription
urlMongoDB connection URL or configuration object.
databaseDatabase name to connect to.
Properties
  • readonlyurlstring | MongoConnectionConfig

    MongoDB connection URL or configuration object.

  • readonlydatabasestring

    Database name to connect to.

interface

#MongoCollection

interface MongoCollection<T extends Document>

MongoDB collection interface

Methods
find(filter?: Filter, options?: MongoFindOptions): Promise<MongoFindResult<T>>
Parameters
findOne(filter: Filter, options?: CommonOptions): Promise<MongoFindOneResult<T>>
Parameters
insertOne(doc: Omit<T, "_id">, options?: CommonOptions): Promise<MongoInsertOneResult>
Parameters
insertMany(docs: Omit<T, "_id">[], options?: CommonOptions): Promise<MongoInsertManyResult>
Parameters
updateOne(filter: Filter, update: UpdateFilter, options?: MongoUpdateOptions): Promise<MongoUpdateResult>
Parameters
updateMany(filter: Filter, update: UpdateFilter, options?: MongoUpdateOptions): Promise<MongoUpdateResult>
Parameters
deleteOne(filter: Filter, options?: CommonOptions): Promise<MongoDeleteResult>
Parameters
deleteMany(filter: Filter, options?: CommonOptions): Promise<MongoDeleteResult>
Parameters
aggregate<R = T>(pipeline: Document[], options?: CommonOptions): Promise<MongoFindResult<R>>
Parameters
countDocuments(filter?: Filter, options?: CommonOptions): Promise<MongoCountResult>
Parameters
interface

#MongoConnectionConfig

interface MongoConnectionConfig extends CommonConnectionConfig

MongoDB connection configuration.

Extends CommonConnectionConfig with MongoDB-specific options.

NameDescription
databaseDatabase name to connect to.
authSourceAuthentication database.
replicaSetReplica set name.
Properties
  • readonlydatabase?string

    Database name to connect to.

  • readonlyauthSource?string

    Authentication database.

  • readonlyreplicaSet?string

    Replica set name.

interface

#MongoCountResult

interface MongoCountResult

Count result

NameDescription
type
ok
count
duration
Properties
  • readonlytype"mongo:count"
  • readonlyokboolean
  • readonlycountnumber
  • readonlydurationnumber
interface

#MongoDeleteResult

interface MongoDeleteResult

Delete result

NameDescription
type
ok
deletedCount
duration
Properties
  • readonlytype"mongo:delete"
  • readonlyokboolean
  • readonlydeletedCountnumber
  • readonlydurationnumber
interface

#MongoDocs

interface MongoDocs<T> extends ReadonlyArray<T>

Document array with first/last methods

NameDescription
first()
firstOrThrow()
last()
lastOrThrow()
Methods
first(): T | undefined
firstOrThrow(): T
last(): T | undefined
lastOrThrow(): T
interface

#MongoErrorOptions

interface MongoErrorOptions extends ErrorOptions

Options for MongoDB errors.

NameDescription
code
Properties
  • readonlycode?number
interface

#MongoFindOneResult

interface MongoFindOneResult<T = Document>

FindOne result

NameDescription
type
ok
doc
duration
Properties
  • readonlytype"mongo:find-one"
  • readonlyokboolean
  • readonlydocT | undefined
  • readonlydurationnumber
interface

#MongoFindOptions

interface MongoFindOptions extends CommonOptions

MongoDB find options

NameDescription
sort
limit
skip
projection
Properties
  • readonlysort?Record<string, 1 | -1>
  • readonlylimit?number
  • readonlyskip?number
  • readonlyprojection?Record<string, 0 | 1>
interface

#MongoFindResult

interface MongoFindResult<T = Document>

Query result (find, aggregate)

NameDescription
type
ok
docs
duration
Properties
  • readonlytype"mongo:find"
  • readonlyokboolean
  • readonlydocsMongoDocs<T>
  • readonlydurationnumber
interface

#MongoInsertManyResult

interface MongoInsertManyResult

Insert many result

NameDescription
type
ok
insertedIds
insertedCount
duration
Properties
  • readonlytype"mongo:insert"
  • readonlyokboolean
  • readonlyinsertedIdsreadonly string[]
  • readonlyinsertedCountnumber
  • readonlydurationnumber
interface

#MongoInsertOneResult

interface MongoInsertOneResult

Insert one result

NameDescription
type
ok
insertedId
duration
Properties
  • readonlytype"mongo:insert"
  • readonlyokboolean
  • readonlyinsertedIdstring
  • readonlydurationnumber
interface

#MongoSession

interface MongoSession

MongoDB session interface (for transactions)

NameDescription
collection()
Methods
collection<T extends Document = Document>(name: string): MongoCollection<T>
Parameters
  • namestring
interface

#MongoUpdateOptions

interface MongoUpdateOptions extends CommonOptions

MongoDB update options

NameDescription
upsert
Properties
  • readonlyupsert?boolean
interface

#MongoUpdateResult

interface MongoUpdateResult

Update result

NameDescription
type
ok
matchedCount
modifiedCount
upsertedId
duration
Properties
  • readonlytype"mongo:update"
  • readonlyokboolean
  • readonlymatchedCountnumber
  • readonlymodifiedCountnumber
  • readonlyupsertedId?string
  • readonlydurationnumber
interface

#RabbitMqAckResult

interface RabbitMqAckResult

Ack/Nack result.

NameDescription
type
ok
duration
Properties
  • readonlytype"rabbitmq:ack"
  • readonlyokboolean
  • readonlydurationnumber
interface

#RabbitMqChannel

interface RabbitMqChannel extends AsyncDisposable

RabbitMQ channel interface.

Methods
assertExchange(name: string, type: RabbitMqExchangeType, options?: RabbitMqExchangeOptions): Promise<RabbitMqExchangeResult>
Parameters
deleteExchange(name: string, options?: CommonOptions): Promise<RabbitMqExchangeResult>
Parameters
assertQueue(name: string, options?: RabbitMqQueueOptions): Promise<RabbitMqQueueResult>
Parameters
deleteQueue(name: string, options?: CommonOptions): Promise<RabbitMqQueueResult>
Parameters
purgeQueue(name: string, options?: CommonOptions): Promise<RabbitMqQueueResult>
Parameters
bindQueue(queue: string, exchange: string, routingKey: string, options?: CommonOptions): Promise<RabbitMqExchangeResult>
Parameters
unbindQueue(queue: string, exchange: string, routingKey: string, options?: CommonOptions): Promise<RabbitMqExchangeResult>
Parameters
publish(exchange: string, routingKey: string, content: Uint8Array, options?: RabbitMqPublishOptions): Promise<RabbitMqPublishResult>
Parameters
sendToQueue(queue: string, content: Uint8Array, options?: RabbitMqPublishOptions): Promise<RabbitMqPublishResult>
Parameters
get(queue: string, options?: CommonOptions): Promise<RabbitMqConsumeResult>
Parameters
consume(queue: string, options?: RabbitMqConsumeOptions): AsyncIterable<RabbitMqMessage>
Parameters
ack(message: RabbitMqMessage, options?: CommonOptions): Promise<RabbitMqAckResult>
Parameters
nack(message: RabbitMqMessage, options?: RabbitMqNackOptions): Promise<RabbitMqAckResult>
Parameters
reject(message: RabbitMqMessage, requeue?: boolean): Promise<RabbitMqAckResult>
Parameters
prefetch(count: number): Promise<void>
Parameters
  • countnumber
close(): Promise<void>
interface

#RabbitMqChannelErrorOptions

interface RabbitMqChannelErrorOptions extends RabbitMqErrorOptions

Options for RabbitMQ channel errors.

NameDescription
channelId
Properties
  • readonlychannelId?number
interface

#RabbitMqClient

interface RabbitMqClient extends AsyncDisposable

RabbitMQ client interface.

NameDescription
config
channel()
close()
Properties
Methods
channel(): Promise<RabbitMqChannel>
close(): Promise<void>
interface

#RabbitMqClientConfig

interface RabbitMqClientConfig extends CommonOptions

RabbitMQ client configuration.

NameDescription
urlRabbitMQ connection URL or configuration object.
heartbeatHeartbeat interval in seconds
prefetchDefault prefetch count for channels
Properties
  • readonlyurlstring | RabbitMqConnectionConfig

    RabbitMQ connection URL or configuration object.

  • readonlyheartbeat?number

    Heartbeat interval in seconds

  • readonlyprefetch?number

    Default prefetch count for channels

interface

#RabbitMqConnectionConfig

interface RabbitMqConnectionConfig extends CommonConnectionConfig

RabbitMQ connection configuration.

Extends CommonConnectionConfig with RabbitMQ-specific options.

NameDescription
vhostVirtual host.
Properties
  • readonlyvhost?string

    Virtual host.

interface

#RabbitMqConsumeOptions

interface RabbitMqConsumeOptions extends CommonOptions

Consume options.

NameDescription
noAck
exclusive
priority
Properties
  • readonlynoAck?boolean
  • readonlyexclusive?boolean
  • readonlypriority?number
interface

#RabbitMqConsumeResult

interface RabbitMqConsumeResult

Consume result (single message retrieval).

NameDescription
type
ok
message
duration
Properties
  • readonlytype"rabbitmq:consume"
  • readonlyokboolean
  • readonlymessageRabbitMqMessage | null
  • readonlydurationnumber
interface

#RabbitMqErrorOptions

interface RabbitMqErrorOptions extends ErrorOptions

Options for RabbitMQ errors.

NameDescription
code
Properties
  • readonlycode?number
interface

#RabbitMqExchangeOptions

interface RabbitMqExchangeOptions extends CommonOptions

Exchange options.

NameDescription
durable
autoDelete
internal
arguments
Properties
  • readonlydurable?boolean
  • readonlyautoDelete?boolean
  • readonlyinternal?boolean
  • readonlyarguments?Record<string, unknown>
interface

#RabbitMqExchangeResult

interface RabbitMqExchangeResult

Exchange declaration result.

NameDescription
type
ok
duration
Properties
  • readonlytype"rabbitmq:exchange"
  • readonlyokboolean
  • readonlydurationnumber
interface

#RabbitMqMessage

interface RabbitMqMessage

RabbitMQ message.

NameDescription
content
properties
fields
Properties
interface

#RabbitMqMessageFields

interface RabbitMqMessageFields

RabbitMQ message fields.

NameDescription
deliveryTag
redelivered
exchange
routingKey
Properties
  • readonlydeliveryTagbigint
  • readonlyredeliveredboolean
  • readonlyexchangestring
  • readonlyroutingKeystring
interface

#RabbitMqMessageProperties

interface RabbitMqMessageProperties

RabbitMQ message properties.

NameDescription
contentType
contentEncoding
headers
deliveryMode1: non-persistent, 2: persistent
priority
correlationId
replyTo
expiration
messageId
timestamp
type
userId
appId
Properties
  • readonlycontentType?string
  • readonlycontentEncoding?string
  • readonlyheaders?Record<string, unknown>
  • readonlydeliveryMode?1 | 2

    1: non-persistent, 2: persistent

  • readonlypriority?number
  • readonlycorrelationId?string
  • readonlyreplyTo?string
  • readonlyexpiration?string
  • readonlymessageId?string
  • readonlytimestamp?number
  • readonlytype?string
  • readonlyuserId?string
  • readonlyappId?string
interface

#RabbitMqNackOptions

interface RabbitMqNackOptions extends CommonOptions

Nack options.

NameDescription
requeue
allUpTo
Properties
  • readonlyrequeue?boolean
  • readonlyallUpTo?boolean
interface

#RabbitMqNotFoundErrorOptions

interface RabbitMqNotFoundErrorOptions extends RabbitMqErrorOptions

Options for RabbitMQ not found errors.

NameDescription
resource
Properties
  • readonlyresourcestring
interface

#RabbitMqPreconditionFailedErrorOptions

interface RabbitMqPreconditionFailedErrorOptions extends RabbitMqErrorOptions

Options for RabbitMQ precondition failed errors.

NameDescription
reason
Properties
  • readonlyreasonstring
interface

#RabbitMqPublishOptions

interface RabbitMqPublishOptions extends CommonOptions

Publish options.

Properties
  • readonlypersistent?boolean
  • readonlycontentType?string
  • readonlycontentEncoding?string
  • readonlyheaders?Record<string, unknown>
  • readonlycorrelationId?string
  • readonlyreplyTo?string
  • readonlyexpiration?string
  • readonlymessageId?string
  • readonlypriority?number
interface

#RabbitMqPublishResult

interface RabbitMqPublishResult

Publish result.

NameDescription
type
ok
duration
Properties
  • readonlytype"rabbitmq:publish"
  • readonlyokboolean
  • readonlydurationnumber
interface

#RabbitMqQueueOptions

interface RabbitMqQueueOptions extends CommonOptions

Queue options.

Properties
  • readonlydurable?boolean
  • readonlyexclusive?boolean
  • readonlyautoDelete?boolean
  • readonlyarguments?Record<string, unknown>
  • readonlymessageTtl?number
  • readonlymaxLength?number
  • readonlydeadLetterExchange?string
  • readonlydeadLetterRoutingKey?string
interface

#RabbitMqQueueResult

interface RabbitMqQueueResult

Queue declaration result.

NameDescription
type
ok
queue
messageCount
consumerCount
duration
Properties
  • readonlytype"rabbitmq:queue"
  • readonlyokboolean
  • readonlyqueuestring
  • readonlymessageCountnumber
  • readonlyconsumerCountnumber
  • readonlydurationnumber
interface

#RedisArrayResult

interface RedisArrayResult<T = string> extends RedisResultBase<readonly T[]>

Redis array result (LRANGE, SMEMBERS, etc.)

NameDescription
type
Properties
  • readonlytype"redis:array"
interface

#RedisClient

interface RedisClient extends AsyncDisposable

Redis client interface

Properties
Methods
get(key: string, options?: CommonOptions): Promise<RedisGetResult>
Parameters
set(key: string, value: string, options?: RedisSetOptions): Promise<RedisSetResult>
Parameters
del(_: string[]): Promise<RedisCountResult>
Parameters
  • _string[]
incr(key: string): Promise<RedisCountResult>
Parameters
  • keystring
decr(key: string): Promise<RedisCountResult>
Parameters
  • keystring
hget(key: string, field: string, options?: CommonOptions): Promise<RedisGetResult>
Parameters
hset(key: string, field: string, value: string, options?: CommonOptions): Promise<RedisCountResult>
Parameters
hgetall(key: string, options?: CommonOptions): Promise<RedisHashResult>
Parameters
hdel(key: string, _: string[]): Promise<RedisCountResult>
Parameters
  • keystring
  • _string[]
lpush(key: string, _: string[]): Promise<RedisCountResult>
Parameters
  • keystring
  • _string[]
rpush(key: string, _: string[]): Promise<RedisCountResult>
Parameters
  • keystring
  • _string[]
lpop(key: string): Promise<RedisGetResult>
Parameters
  • keystring
rpop(key: string): Promise<RedisGetResult>
Parameters
  • keystring
lrange(key: string, start: number, stop: number, options?: CommonOptions): Promise<RedisArrayResult>
Parameters
llen(key: string): Promise<RedisCountResult>
Parameters
  • keystring
sadd(key: string, _: string[]): Promise<RedisCountResult>
Parameters
  • keystring
  • _string[]
srem(key: string, _: string[]): Promise<RedisCountResult>
Parameters
  • keystring
  • _string[]
smembers(key: string, options?: CommonOptions): Promise<RedisArrayResult>
Parameters
sismember(key: string, member: string): Promise<RedisCommonResult<boolean>>
Parameters
  • keystring
  • memberstring
zadd(key: string, _: { score: number; member: string }[]): Promise<RedisCountResult>
Parameters
  • keystring
  • _{ score: number; member: string }[]
zrange(key: string, start: number, stop: number, options?: CommonOptions): Promise<RedisArrayResult>
Parameters
zscore(key: string, member: string): Promise<RedisCommonResult<number | null>>
Parameters
  • keystring
  • memberstring
publish(channel: string, message: string): Promise<RedisCountResult>
Parameters
  • channelstring
  • messagestring
subscribe(channel: string): AsyncIterable<RedisMessage>
Parameters
  • channelstring
multi(): RedisTransaction
command<T = unknown>(cmd: string, _: unknown[]): Promise<RedisCommonResult<T>>
Parameters
  • cmdstring
  • _unknown[]
close(): Promise<void>
interface

#RedisClientConfig

interface RedisClientConfig extends CommonOptions

Redis client configuration.

NameDescription
urlRedis connection URL or configuration object.
Properties
interface

#RedisCommandErrorOptions

interface RedisCommandErrorOptions extends RedisErrorOptions

Options for Redis command errors.

NameDescription
command
Properties
  • readonlycommandstring
interface

#RedisCommonResult

interface RedisCommonResult<T = unknown> extends RedisResultBase<T>

Redis operation result (common/generic)

NameDescription
type
Properties
  • readonlytype"redis:common"
interface

#RedisConnectionConfig

interface RedisConnectionConfig extends CommonConnectionConfig

Redis connection configuration.

Extends CommonConnectionConfig with Redis-specific options.

NameDescription
dbDatabase index.
Properties
  • readonlydb?number

    Database index.

interface

#RedisCountResult

interface RedisCountResult extends RedisResultBase<number>

Redis numeric result (DEL, LPUSH, SADD, etc.)

NameDescription
type
Properties
  • readonlytype"redis:count"
interface

#RedisErrorOptions

interface RedisErrorOptions extends ErrorOptions

Options for Redis errors.

NameDescription
code
Properties
  • readonlycode?string
interface

#RedisGetResult

interface RedisGetResult extends RedisResultBase<string | null>

Redis GET result

NameDescription
type
Properties
  • readonlytype"redis:get"
interface

#RedisHashResult

interface RedisHashResult extends RedisResultBase<Record<string, string>>

Redis hash result (HGETALL)

NameDescription
type
Properties
  • readonlytype"redis:hash"
interface

#RedisMessage

interface RedisMessage

Redis Pub/Sub message

NameDescription
channel
message
Properties
  • readonlychannelstring
  • readonlymessagestring
interface

#RedisResultBase

interface RedisResultBase<T = unknown>

Base interface for Redis operation results. All Redis result types extend this interface.

NameDescription
type
ok
value
duration
Properties
  • readonlytypestring
  • readonlyokboolean
  • readonlyvalueT
  • readonlydurationnumber
interface

#RedisScriptErrorOptions

interface RedisScriptErrorOptions extends RedisErrorOptions

Options for Redis script errors.

NameDescription
script
Properties
  • readonlyscriptstring
interface

#RedisSetOptions

interface RedisSetOptions extends CommonOptions

Redis SET options

NameDescription
exExpiration in seconds
pxExpiration in milliseconds
nxOnly set if key does not exist
xxOnly set if key exists
Properties
  • readonlyex?number

    Expiration in seconds

  • readonlypx?number

    Expiration in milliseconds

  • readonlynx?boolean

    Only set if key does not exist

  • readonlyxx?boolean

    Only set if key exists

interface

#RedisSetResult

interface RedisSetResult extends RedisResultBase<"OK">

Redis SET result

NameDescription
type
Properties
  • readonlytype"redis:set"
interface

#RedisTransaction

interface RedisTransaction

Redis transaction interface

Methods
get(key: string): this
Parameters
  • keystring
set(key: string, value: string, options?: RedisSetOptions): this
Parameters
del(_: string[]): this
Parameters
  • _string[]
incr(key: string): this
Parameters
  • keystring
decr(key: string): this
Parameters
  • keystring
hget(key: string, field: string): this
Parameters
  • keystring
  • fieldstring
hset(key: string, field: string, value: string): this
Parameters
  • keystring
  • fieldstring
  • valuestring
hgetall(key: string): this
Parameters
  • keystring
hdel(key: string, _: string[]): this
Parameters
  • keystring
  • _string[]
lpush(key: string, _: string[]): this
Parameters
  • keystring
  • _string[]
rpush(key: string, _: string[]): this
Parameters
  • keystring
  • _string[]
lpop(key: string): this
Parameters
  • keystring
rpop(key: string): this
Parameters
  • keystring
lrange(key: string, start: number, stop: number): this
Parameters
  • keystring
  • startnumber
  • stopnumber
llen(key: string): this
Parameters
  • keystring
sadd(key: string, _: string[]): this
Parameters
  • keystring
  • _string[]
srem(key: string, _: string[]): this
Parameters
  • keystring
  • _string[]
smembers(key: string): this
Parameters
  • keystring
sismember(key: string, member: string): this
Parameters
  • keystring
  • memberstring
zadd(key: string, _: { score: number; member: string }[]): this
Parameters
  • keystring
  • _{ score: number; member: string }[]
zrange(key: string, start: number, stop: number): this
Parameters
  • keystring
  • startnumber
  • stopnumber
zscore(key: string, member: string): this
Parameters
  • keystring
  • memberstring
exec(): Promise<RedisArrayResult<unknown>>
discard(): void
interface

#ReflectionApi

interface ReflectionApi

Reflection API for ConnectRPC client. Only available when client is created with schema: "reflection".

NameDescription
enabledCheck if reflection is enabled.
listServices()List all available services on the server.
getServiceInfo()Get detailed information about a specific service.
listMethods()Get methods for a specific service.
hasService()Check if a service exists.
Properties
  • readonlyenabledboolean

    Check if reflection is enabled.

Methods
listServices(): Promise<ServiceInfo[]>

List all available services on the server.

getServiceInfo(serviceName: string): Promise<ServiceDetail>

Get detailed information about a specific service.

Parameters
  • serviceNamestring
    • Fully qualified service name (e.g., "echo.EchoService")
listMethods(serviceName: string): Promise<MethodInfo[]>

Get methods for a specific service.

Parameters
  • serviceNamestring
    • Fully qualified service name
hasService(serviceName: string): Promise<boolean>

Check if a service exists.

Parameters
  • serviceNamestring
    • Fully qualified service name
interface

#ServiceDetail

interface ServiceDetail

Detailed service information.

NameDescription
nameService name
fullNameFully qualified service name
packageNamePackage name
protoFileProto file name
methodsAll methods
Properties
  • readonlynamestring

    Service name

  • readonlyfullNamestring

    Fully qualified service name

  • readonlypackageNamestring

    Package name

  • readonlyprotoFilestring

    Proto file name

  • readonlymethodsreadonly MethodInfo[]

    All methods

interface

#ServiceInfo

interface ServiceInfo

Service information from reflection.

NameDescription
nameFully qualified service name (e.g., "echo.EchoService")
fileProto file name
Properties
  • readonlynamestring

    Fully qualified service name (e.g., "echo.EchoService")

  • readonlyfilestring

    Proto file name

interface

#SqlErrorOptions

interface SqlErrorOptions extends ErrorOptions

Options for SqlError constructor.

NameDescription
sqlStateSQL State code (e.g., "23505" for unique violation)
Properties
  • readonlysqlState?string

    SQL State code (e.g., "23505" for unique violation)

interface

#SqlQueryResultExpectation

interface SqlQueryResultExpectation<T>

Expectation interface for SQL query results. All methods return this for chaining.

NameDescription
notNegates the next assertion.
toBeSuccessful()Asserts that the query succeeded.
toHaveContent()Asserts that the result has at least one row.
toHaveLength()Asserts that the row count matches the expected value.
toHaveLengthGreaterThanOrEqual()Asserts that the row count is at least the expected value.
toHaveLengthLessThanOrEqual()Asserts that the row count is at most the expected value.
toHaveRowCount()Asserts that the affected row count matches the expected value.
toHaveRowCountGreaterThanOrEqual()Asserts that the affected row count is at least the expected value.
toHaveRowCountLessThanOrEqual()Asserts that the affected row count is at most the expected value.
toMatchObject()Asserts that at least one row contains the given subset of properties.
toSatisfy()Validates the rows using a custom matcher function.
toHaveMapContaining()Asserts that at least one mapped row contains the given subset.
toHaveMapMatching()Validates the mapped rows using a custom matcher function.
toHaveInstanceContaining()Asserts that at least one instance created from rows contains the given subset.
toHaveInstanceMatching()Validates instances created from rows using a custom matcher function.
toHaveLastInsertId()Asserts that the lastInsertId matches the expected value.
toHaveLastInsertId()Asserts that the lastInsertId is present.
toHaveDurationLessThan()Asserts that the query duration is less than the threshold.
toHaveDurationLessThanOrEqual()Asserts that the query duration is at most the threshold.
toHaveDurationGreaterThan()Asserts that the query duration is greater than the threshold.
toHaveDurationGreaterThanOrEqual()Asserts that the query duration is at least the threshold.
Properties
  • readonlynotthis

    Negates the next assertion.

Methods
toBeSuccessful(): this

Asserts that the query succeeded.

toHaveContent(): this

Asserts that the result has at least one row.

toHaveLength(expected: number): this

Asserts that the row count matches the expected value.

Parameters
  • expectednumber
    • The expected number of rows
toHaveLengthGreaterThanOrEqual(expected: number): this

Asserts that the row count is at least the expected value.

Parameters
  • expectednumber
    • The minimum expected number of rows
toHaveLengthLessThanOrEqual(expected: number): this

Asserts that the row count is at most the expected value.

Parameters
  • expectednumber
    • The maximum expected number of rows
toHaveRowCount(count: number): this

Asserts that the affected row count matches the expected value.

Parameters
  • countnumber
    • The expected affected row count
toHaveRowCountGreaterThanOrEqual(count: number): this

Asserts that the affected row count is at least the expected value.

Parameters
  • countnumber
    • The minimum expected affected row count
toHaveRowCountLessThanOrEqual(count: number): this

Asserts that the affected row count is at most the expected value.

Parameters
  • countnumber
    • The maximum expected affected row count
toMatchObject(subset: Partial<T>): this

Asserts that at least one row contains the given subset of properties.

Parameters
  • subsetPartial<T>
    • The partial object to match against rows
toSatisfy(matcher: (rows: SqlRows<T>) => unknown): this

Validates the rows using a custom matcher function.

Parameters
  • matcher(rows: SqlRows<T>) => unknown
    • A function that receives the rows and performs assertions
toHaveMapContaining<U>(mapper: (row: T) => unknown, subset: Partial<U>): this

Asserts that at least one mapped row contains the given subset.

Parameters
  • mapper(row: T) => unknown
    • A function to transform each row
  • subsetPartial<U>
    • The partial object to match against mapped rows
toHaveMapMatching<U>(mapper: (row: T) => unknown, matcher: (mapped: U[]) => unknown): this

Validates the mapped rows using a custom matcher function.

Parameters
  • mapper(row: T) => unknown
    • A function to transform each row
  • matcher(mapped: U[]) => unknown
    • A function that receives the mapped rows and performs assertions
toHaveInstanceContaining<U>(ctor: (row: T) => unknown, subset: Partial<U>): this

Asserts that at least one instance created from rows contains the given subset.

Parameters
  • ctor(row: T) => unknown
    • The constructor to instantiate with each row
  • subsetPartial<U>
    • The partial object to match against instances
toHaveInstanceMatching<U>(ctor: (row: T) => unknown, matcher: (instances: U[]) => unknown): this

Validates instances created from rows using a custom matcher function.

Parameters
  • ctor(row: T) => unknown
    • The constructor to instantiate with each row
  • matcher(instances: U[]) => unknown
    • A function that receives the instances and performs assertions
toHaveLastInsertId(expected: bigint | string): this

Asserts that the lastInsertId matches the expected value.

Parameters
  • expectedbigint | string
    • The expected lastInsertId value
toHaveLastInsertId(): this

Asserts that the lastInsertId is present.

toHaveDurationLessThan(ms: number): this

Asserts that the query duration is less than the threshold.

Parameters
  • msnumber
    • The maximum duration in milliseconds (exclusive)
toHaveDurationLessThanOrEqual(ms: number): this

Asserts that the query duration is at most the threshold.

Parameters
  • msnumber
    • The maximum duration in milliseconds (inclusive)
toHaveDurationGreaterThan(ms: number): this

Asserts that the query duration is greater than the threshold.

Parameters
  • msnumber
    • The minimum duration in milliseconds (exclusive)
toHaveDurationGreaterThanOrEqual(ms: number): this

Asserts that the query duration is at least the threshold.

Parameters
  • msnumber
    • The minimum duration in milliseconds (inclusive)
interface

#SqlQueryResultInit

interface SqlQueryResultInit<T>

Options for creating a SqlQueryResult.

NameDescription
okWhether the query succeeded
rowsThe result rows
rowCountNumber of affected rows (for INSERT/UPDATE/DELETE)
durationQuery execution duration in milliseconds
metadataAdditional metadata
Properties
  • readonlyokboolean

    Whether the query succeeded

  • readonlyrowsreadonly T[]

    The result rows

  • readonlyrowCountnumber

    Number of affected rows (for INSERT/UPDATE/DELETE)

  • readonlydurationnumber

    Query execution duration in milliseconds

  • readonlymetadataSqlQueryResultMetadata

    Additional metadata

interface

#SqlQueryResultMetadata

interface SqlQueryResultMetadata

Metadata for SQL query results.

NameDescription
lastInsertIdLast inserted ID (for INSERT statements)
warningsWarning messages from the database
Properties
  • readonlylastInsertId?bigint | string

    Last inserted ID (for INSERT statements)

  • readonlywarnings?readonly string[]

    Warning messages from the database

interface

#SqlTransaction

interface SqlTransaction

SQL transaction interface. Implementations should provide actual database-specific transaction handling.

NameDescription
query()Execute a query within the transaction.
queryOne()Execute a query and return the first row or undefined.
commit()Commit the transaction.
rollback()Rollback the transaction.
Methods
query<T = Record<string, any>>(sql: string, params?: unknown[]): Promise<SqlQueryResult<T>>

Execute a query within the transaction.

Parameters
  • sqlstring
    • SQL query string
  • params?unknown[]
    • Optional query parameters
queryOne<T = Record<string, any>>(sql: string, params?: unknown[]): Promise<T | undefined>

Execute a query and return the first row or undefined.

Parameters
  • sqlstring
    • SQL query string
  • params?unknown[]
    • Optional query parameters
commit(): Promise<void>

Commit the transaction.

rollback(): Promise<void>

Rollback the transaction.

interface

#SqlTransactionOptions

interface SqlTransactionOptions

Options for starting a transaction.

NameDescription
isolationLevelIsolation level for the transaction
Properties
interface

#SqsBatchFailedEntry

interface SqsBatchFailedEntry

Failed batch entry.

NameDescription
id
code
message
Properties
  • readonlyidstring
  • readonlycodestring
  • readonlymessagestring
interface

#SqsBatchMessage

interface SqsBatchMessage

Batch message for sendBatch.

NameDescription
id
body
delaySeconds
messageAttributes
Properties
  • readonlyidstring
  • readonlybodystring
  • readonlydelaySeconds?number
  • readonlymessageAttributes?Record<string, SqsMessageAttribute>
interface

#SqsBatchSuccessEntry

interface SqsBatchSuccessEntry

Successful batch send entry.

NameDescription
messageId
id
Properties
  • readonlymessageIdstring
  • readonlyidstring
interface

#SqsClient

interface SqsClient extends AsyncDisposable

SQS client interface.

NameDescription
config
queueUrlThe current queue URL.
setQueueUrl()Set the queue URL for subsequent operations.
ensureQueue()Ensure a queue exists.
deleteQueue()Delete a queue by URL.
send()Send a message to the queue.
sendBatch()Send multiple messages to the queue in a single request.
receive()Receive messages from the queue.
delete()Delete a message from the queue.
deleteBatch()Delete multiple messages from the queue in a single request.
purge()Purge all messages from the queue.
close()Close the client and release resources.
Properties
  • readonlyconfigSqsClientConfig
  • readonlyqueueUrlstring | undefined

    The current queue URL. Can be set via config, ensureQueue(), or setQueueUrl().

Methods
setQueueUrl(queueUrl: string): void

Set the queue URL for subsequent operations.

Parameters
  • queueUrlstring
ensureQueue(queueName: string, options?: SqsEnsureQueueOptions): Promise<SqsEnsureQueueResult>

Ensure a queue exists. Creates the queue if it doesn't exist. If the queue already exists with the same attributes, returns the existing queue URL. Also sets the queue URL for subsequent operations.

Parameters
deleteQueue(queueUrl: string, options?: CommonOptions): Promise<SqsDeleteQueueResult>

Delete a queue by URL.

Parameters
send(body: string, options?: SqsSendOptions): Promise<SqsSendResult>

Send a message to the queue.

Parameters
sendBatch(messages: SqsBatchMessage[]): Promise<SqsSendBatchResult>

Send multiple messages to the queue in a single request.

Parameters
receive(options?: SqsReceiveOptions): Promise<SqsReceiveResult>

Receive messages from the queue.

Parameters
delete(receiptHandle: string, options?: CommonOptions): Promise<SqsDeleteResult>

Delete a message from the queue.

Parameters
deleteBatch(receiptHandles: string[], options?: CommonOptions): Promise<SqsDeleteBatchResult>

Delete multiple messages from the queue in a single request.

Parameters
purge(options?: CommonOptions): Promise<SqsDeleteResult>

Purge all messages from the queue.

Parameters
close(): Promise<void>

Close the client and release resources.

interface

#SqsClientConfig

interface SqsClientConfig extends CommonOptions

SQS client configuration.

NameDescription
regionAWS region
credentialsAWS credentials
queueUrlSQS queue URL (optional - can be set later or used with ensureQueue)
urlSQS endpoint URL (e.g., "http://localhost:4566" for LocalStack).
Properties
  • readonlyregionstring

    AWS region

  • readonlycredentials?{ accessKeyId: string; secretAccessKey: string }

    AWS credentials

  • readonlyqueueUrl?string

    SQS queue URL (optional - can be set later or used with ensureQueue)

  • readonlyurl?string | SqsConnectionConfig

    SQS endpoint URL (e.g., "http://localhost:4566" for LocalStack). Can be a string URL or a connection config object. Optional for real AWS (uses default endpoint), required for LocalStack.

interface

#SqsCommandErrorOptions

interface SqsCommandErrorOptions extends SqsErrorOptions

Options for SQS command errors.

NameDescription
operation
Properties
  • readonlyoperationstring
interface

#SqsConnectionConfig

interface SqsConnectionConfig extends CommonConnectionConfig

SQS connection configuration.

Extends CommonConnectionConfig with SQS-specific options.

NameDescription
protocolProtocol to use.
pathCustom path (for LocalStack or custom endpoints).
regionAWS region (required for AWS, optional for LocalStack).
Properties
  • readonlyprotocol?"http" | "https"

    Protocol to use.

  • readonlypath?string

    Custom path (for LocalStack or custom endpoints).

  • readonlyregion?string

    AWS region (required for AWS, optional for LocalStack).

interface

#SqsDeleteBatchResult

interface SqsDeleteBatchResult

Result of batch deleting messages.

NameDescription
type
ok
successful
failed
duration
Properties
  • readonlytype"sqs:delete-batch"
  • readonlyokboolean
  • readonlysuccessfulreadonly string[]
  • readonlyfailedreadonly SqsBatchFailedEntry[]
  • readonlydurationnumber
interface

#SqsDeleteQueueResult

interface SqsDeleteQueueResult

Result of deleting a queue.

NameDescription
type
ok
duration
Properties
  • readonlytype"sqs:delete-queue"
  • readonlyokboolean
  • readonlydurationnumber
interface

#SqsDeleteResult

interface SqsDeleteResult

Result of deleting a message.

NameDescription
type
ok
duration
Properties
  • readonlytype"sqs:delete"
  • readonlyokboolean
  • readonlydurationnumber
interface

#SqsEnsureQueueOptions

interface SqsEnsureQueueOptions extends CommonOptions

Options for ensuring a queue exists.

NameDescription
attributesQueue attributes (e.g., DelaySeconds, MessageRetentionPeriod)
tagsQueue tags
Properties
  • readonlyattributes?Record<string, string>

    Queue attributes (e.g., DelaySeconds, MessageRetentionPeriod)

  • readonlytags?Record<string, string>

    Queue tags

interface

#SqsEnsureQueueResult

interface SqsEnsureQueueResult

Result of ensuring a queue exists.

NameDescription
type
ok
queueUrl
duration
Properties
  • readonlytype"sqs:ensure-queue"
  • readonlyokboolean
  • readonlyqueueUrlstring
  • readonlydurationnumber
interface

#SqsErrorOptions

interface SqsErrorOptions extends ErrorOptions

Options for SQS errors.

NameDescription
code
Properties
  • readonlycode?string
interface

#SqsMessage

interface SqsMessage

SQS message received from a queue.

Properties
  • readonlymessageIdstring
  • readonlybodystring
  • readonlyreceiptHandlestring
  • readonlyattributesRecord<string, string>
  • readonlymessageAttributes?Record<string, SqsMessageAttribute>
  • readonlymd5OfBodystring
interface

#SqsMessageAttribute

interface SqsMessageAttribute

SQS message attributes.

NameDescription
dataType
stringValue
binaryValue
Properties
  • readonlydataType"String" | "Number" | "Binary"
  • readonlystringValue?string
  • readonlybinaryValue?Uint8Array
interface

#SqsMessages

interface SqsMessages extends ReadonlyArray<SqsMessage>

Message array with helper methods.

NameDescription
first()Get the first message or undefined if empty
firstOrThrow()Get the first message or throw if empty
last()Get the last message or undefined if empty
lastOrThrow()Get the last message or throw if empty
Methods
first(): SqsMessage | undefined

Get the first message or undefined if empty

firstOrThrow(): SqsMessage

Get the first message or throw if empty

last(): SqsMessage | undefined

Get the last message or undefined if empty

lastOrThrow(): SqsMessage

Get the last message or throw if empty

interface

#SqsReceiveOptions

interface SqsReceiveOptions extends CommonOptions

Options for receiving messages.

NameDescription
maxMessagesMaximum number of messages to receive (1-10, default: 1)
waitTimeSecondsWait time in seconds for long polling (0-20)
visibilityTimeoutVisibility timeout in seconds (0-43200)
attributeNamesSystem attribute names to retrieve
messageAttributeNamesMessage attribute names to retrieve
Properties
  • readonlymaxMessages?number

    Maximum number of messages to receive (1-10, default: 1)

  • readonlywaitTimeSeconds?number

    Wait time in seconds for long polling (0-20)

  • readonlyvisibilityTimeout?number

    Visibility timeout in seconds (0-43200)

  • readonlyattributeNames?readonly string[]

    System attribute names to retrieve

  • readonlymessageAttributeNames?readonly string[]

    Message attribute names to retrieve

interface

#SqsReceiveResult

interface SqsReceiveResult

Result of receiving messages.

NameDescription
type
ok
messages
duration
Properties
  • readonlytype"sqs:receive"
  • readonlyokboolean
  • readonlymessagesSqsMessages
  • readonlydurationnumber
interface

#SqsSendBatchResult

interface SqsSendBatchResult

Result of batch sending messages.

NameDescription
type
ok
successful
failed
duration
Properties
interface

#SqsSendOptions

interface SqsSendOptions extends CommonOptions

Options for sending a message.

NameDescription
delaySecondsDelay in seconds before the message becomes visible (0-900)
messageAttributesMessage attributes
messageGroupIdMessage group ID (required for FIFO queues)
messageDeduplicationIdMessage deduplication ID (required for FIFO queues without content-based deduplication)
Properties
  • readonlydelaySeconds?number

    Delay in seconds before the message becomes visible (0-900)

  • readonlymessageAttributes?Record<string, SqsMessageAttribute>

    Message attributes

  • readonlymessageGroupId?string

    Message group ID (required for FIFO queues)

  • readonlymessageDeduplicationId?string

    Message deduplication ID (required for FIFO queues without content-based deduplication)

interface

#SqsSendResult

interface SqsSendResult

Result of sending a message.

NameDescription
type
ok
messageId
md5OfBody
sequenceNumber
duration
Properties
  • readonlytype"sqs:send"
  • readonlyokboolean
  • readonlymessageIdstring
  • readonlymd5OfBodystring
  • readonlysequenceNumber?string
  • readonlydurationnumber
interface

#TlsConfig

interface TlsConfig

TLS configuration for ConnectRPC connections.

NameDescription
rootCertsRoot CA certificate (PEM format).
clientCertClient certificate (PEM format).
clientKeyClient private key (PEM format).
insecureSkip server certificate verification (use only for testing).
Properties
  • readonlyrootCerts?Uint8Array

    Root CA certificate (PEM format).

  • readonlyclientCert?Uint8Array

    Client certificate (PEM format).

  • readonlyclientKey?Uint8Array

    Client private key (PEM format).

  • readonlyinsecure?boolean

    Skip server certificate verification (use only for testing).

Functions

function

#buildErrorMessage

function buildErrorMessage(header: string, diffs: string[], expected: unknown, actual: unknown): string

Builds a structured error message with diffs.

Parameters
  • headerstring
    • The error header message
  • diffsstring[]
    • Array of diff lines from formatDifferences (includes [Diff] header and colors)
  • expectedunknown
    • The expected value
  • actualunknown
    • The actual value
Returns

string — Formatted error message

function

#containsSubarray

function containsSubarray(arr: Uint8Array, sub: Uint8Array): boolean

Check if an array contains a contiguous subarray.

Parameters
  • arrUint8Array
    • The array to search
  • subUint8Array
    • The subarray to find
Returns

boolean — True if arr contains sub as a contiguous sequence

function

#containsSubset

function containsSubset(obj: unknown, subset: unknown): boolean

Check if an object contains all properties from subset (deep partial match).

Parameters
  • objunknown
    • The object to check
  • subsetunknown
    • The subset of properties to match
Returns

boolean — True if obj contains all properties from subset

function

#createConnectRpcClient

function createConnectRpcClient(config: ConnectRpcClientConfig): ConnectRpcClient

Create a new ConnectRPC client instance.

The client supports multiple protocols (Connect, gRPC, gRPC-Web) and provides Server Reflection for runtime service discovery without compile-time code generation.

Parameters
Returns

ConnectRpcClient — A new ConnectRPC client instance

Examples

Basic usage with reflection

const client = createConnectRpcClient({
  url: "http://localhost:50051",
});

// Call a method
const response = await client.call(
  "echo.EchoService",
  "echo",
  { message: "Hello!" }
);
console.log(response.data());

await client.close();

Service discovery with reflection

const client = createConnectRpcClient({
  url: "http://localhost:50051",
});

// Discover available services
const services = await client.reflection.listServices();
console.log("Services:", services);

// Get method information
const info = await client.reflection.getServiceInfo("echo.EchoService");
console.log("Methods:", info.methods);

await client.close();

Using different protocols

// Connect protocol (HTTP/1.1 or HTTP/2)
const connectClient = createConnectRpcClient({
  url: "http://localhost:8080",
  protocol: "connect",
});

// gRPC protocol (HTTP/2 with binary protobuf)
const grpcClient = createConnectRpcClient({
  url: "http://localhost:50051",
  protocol: "grpc",
});

// gRPC-Web protocol (for browser compatibility)
const grpcWebClient = createConnectRpcClient({
  url: "http://localhost:8080",
  protocol: "grpc-web",
});

Using connection config object

const client = createConnectRpcClient({
  url: {
    host: "grpc.example.com",
    port: 443,
    protocol: "https",
  },
});

Using await using for automatic cleanup

await using client = createConnectRpcClient({
  url: "http://localhost:50051",
});

const res = await client.call("echo.EchoService", "echo", { message: "test" });
// Client automatically closed when scope exits
function

#createDenoKvClient

async function createDenoKvClient(config?: DenoKvClientConfig): Promise<DenoKvClient>

Create a new Deno KV client instance.

The client provides key-value operations with support for atomic transactions, time-to-live (TTL), and prefix-based listing.

Parameters
Returns

Promise<DenoKvClient> — A promise resolving to a new Deno KV client instance

Examples

Basic usage with in-memory database

const kv = await createDenoKvClient();

await kv.set(["users", "123"], { name: "Alice", email: "alice@example.com" });

const result = await kv.get<User>(["users", "123"]);
console.log(result.value);  // { name: "Alice", email: "alice@example.com" }

await kv.close();

Using persistent storage

const kv = await createDenoKvClient({
  path: "./data.kv",
});

Set with expiration (TTL)

await kv.set(["sessions", sessionId], sessionData, {
  expireIn: 3600_000,  // Expire in 1 hour
});

List entries by prefix

const result = await kv.list<User>({ prefix: ["users"] });
for (const entry of result.entries) {
  console.log(entry.key, entry.value);
}

Atomic transactions

const atomicResult = await kv.atomic()
  .check({ key: ["counter"], versionstamp: null })
  .set(["counter"], 1)
  .commit();

Using await using for automatic cleanup

await using kv = await createDenoKvClient();

await kv.set(["test"], "value");
// Client automatically closed when scope exits
function

#createDenoKvEntries

function createDenoKvEntries<T>(entries: DenoKvEntry<T>[]): DenoKvEntries<T>

Creates a DenoKvEntries instance from an array of entries.

Parameters
function

#createGraphqlClient

function createGraphqlClient(config: GraphqlClientConfig): GraphqlClient

Create a new GraphQL client instance.

The client provides methods for executing GraphQL queries, mutations, and subscriptions with automatic error handling and response parsing.

Parameters
Returns

GraphqlClient — A new GraphQL client instance

Examples

Basic query

const client = createGraphqlClient({
  url: "http://localhost:4000/graphql",
});

const response = await client.query(`
  query GetUser($id: ID!) {
    user(id: $id) { id name email }
  }
`, { id: "123" });

console.log(response.data());
await client.close();

Using connection config object

const client = createGraphqlClient({
  url: { host: "api.example.com", port: 443, protocol: "https" },
});

Mutation with error handling

const response = await client.mutation(`
  mutation CreateUser($input: CreateUserInput!) {
    createUser(input: $input) { id }
  }
`, { input: { name: "Alice", email: "alice@example.com" } });

if (response.ok) {
  console.log("Created user:", response.data().createUser.id);
}

Using await using for automatic cleanup

await using client = createGraphqlClient({
  url: "http://localhost:4000/graphql",
});
const response = await client.query(`{ __typename }`);
// Client automatically closed when scope exits
function

#createGraphqlResponse

function createGraphqlResponse<T>(options: GraphqlResponseOptions<T>): GraphqlResponse<T>

Create a GraphqlResponse from parsed response data.

Parameters
function

#createGrpcClient

function createGrpcClient(config: GrpcClientConfig): ConnectRpcClient

Create a new gRPC client instance.

This is a thin wrapper around createConnectRpcClient with protocol: "grpc" fixed. The client provides Server Reflection support for runtime service discovery.

Parameters
Returns

ConnectRpcClient — A new gRPC client instance

Examples

Basic usage with reflection

const client = createGrpcClient({
  url: "http://localhost:50051",
});

// Call a method
const response = await client.call(
  "echo.EchoService",
  "echo",
  { message: "Hello!" }
);
console.log(response.data());

await client.close();

Service discovery with reflection

const client = createGrpcClient({
  url: "http://localhost:50051",
});

// Discover available services
const services = await client.reflection.listServices();
console.log("Available services:", services);

// Get method information
const info = await client.reflection.getServiceInfo("echo.EchoService");
console.log("Methods:", info.methods);

await client.close();

Testing error responses

const response = await client.call(
  "user.UserService",
  "getUser",
  { id: "non-existent" },
  { throwOnError: false }
);

if (!response.ok) {
  console.log("Error code:", response.code);  // NOT_FOUND = 5
}

Using await using for automatic cleanup

await using client = createGrpcClient({
  url: "http://localhost:50051",
});

const res = await client.call("echo.EchoService", "echo", { message: "test" });
console.log(res.data());
// Client automatically closed when scope exits
function

#createHttpClient

function createHttpClient(config: HttpClientConfig): HttpClient

Create a new HTTP client instance.

The client provides methods for making HTTP requests with automatic cookie handling, response body pre-loading, and error handling.

Parameters
Returns

HttpClient — A new HTTP client instance

Examples

Basic usage with string URL

const http = createHttpClient({ url: "http://localhost:3000" });

const response = await http.get("/users/123");
console.log(response.data());

await http.close();

With connection config object

const http = createHttpClient({
  url: { host: "api.example.com", port: 443, protocol: "https" },
});

With default headers

const http = createHttpClient({
  url: "http://localhost:3000",
  headers: {
    "Authorization": "Bearer token123",
    "Accept": "application/json",
  },
});

Using await using for automatic cleanup

await using http = createHttpClient({ url: "http://localhost:3000" });
const response = await http.get("/health");
// Client automatically closed when scope exits
function

#createHttpResponse

async function createHttpResponse(raw: globalThis.Response, duration: number): Promise<HttpResponse>

Create HttpResponse from raw Response.

Consumes the response body and creates a reusable HttpResponse.

Parameters
  • rawglobalThis.Response
  • durationnumber
function

#createMongoClient

async function createMongoClient(config: MongoClientConfig): Promise<MongoClient>

Create a new MongoDB client instance.

The client provides typed collection access, aggregation pipelines, transaction support, and comprehensive CRUD operations.

Parameters
Returns

Promise<MongoClient> — A promise resolving to a new MongoDB client instance

Examples

Basic usage with connection string

const mongo = await createMongoClient({
  url: "mongodb://localhost:27017",
  database: "testdb",
});

const users = mongo.collection<{ name: string; age: number }>("users");
const result = await users.find({ age: { $gte: 18 } });
console.log(result.docs.first());

await mongo.close();

Using connection config object

const mongo = await createMongoClient({
  url: {
    host: "localhost",
    port: 27017,
    username: "admin",
    password: "secret",
    authSource: "admin",
  },
  database: "testdb",
});

Insert and query documents

const users = mongo.collection<User>("users");

// Insert a document
const insertResult = await users.insertOne({ name: "Alice", age: 30 });
console.log("Inserted ID:", insertResult.insertedId);

// Find documents with projection and sorting
const findResult = await users.find(
  { age: { $gte: 25 } },
  { sort: { name: 1 }, limit: 10 }
);
console.log("Found:", findResult.documents.length);

Transaction with auto-commit/rollback

await mongo.transaction(async (session) => {
  const users = session.collection<User>("users");
  await users.insertOne({ name: "Bob", age: 25 });
  await users.updateOne({ name: "Alice" }, { $inc: { age: 1 } });
});

Aggregation pipeline

const result = await users.aggregate<{ _id: string; avgAge: number }>([
  { $group: { _id: "$department", avgAge: { $avg: "$age" } } },
  { $sort: { avgAge: -1 } },
]);

Using await using for automatic cleanup

await using mongo = await createMongoClient({
  url: "mongodb://localhost:27017",
  database: "testdb",
});

const result = await mongo.collection("users").find({});
// Client automatically closed when scope exits
function

#createMongoDocs

function createMongoDocs<T>(items: T[]): MongoDocs<T>

Create a MongoDocs array from a regular array.

Parameters
  • itemsT[]
function

#createRabbitMqClient

async function createRabbitMqClient(config: RabbitMqClientConfig): Promise<RabbitMqClient>

Create a new RabbitMQ client instance.

The client provides queue and exchange management, message publishing and consumption, and acknowledgment handling via AMQP protocol.

Parameters
Returns

Promise<RabbitMqClient> — A promise resolving to a new RabbitMQ client instance

Examples

Basic usage with string URL

const rabbit = await createRabbitMqClient({
  url: "amqp://guest:guest@localhost:5672",
});

const channel = await rabbit.channel();
await channel.assertQueue("my-queue", { durable: true });

const content = new TextEncoder().encode(JSON.stringify({ type: "ORDER" }));
await channel.sendToQueue("my-queue", content, { persistent: true });

await channel.close();
await rabbit.close();

With connection config object

const rabbit = await createRabbitMqClient({
  url: {
    host: "localhost",
    port: 5672,
    username: "guest",
    password: "guest",
    vhost: "/",
  },
});

Exchange and binding

// Create exchange and queue
await channel.assertExchange("events", "topic", { durable: true });
await channel.assertQueue("user-events");
await channel.bindQueue("user-events", "events", "user.*");

// Publish to exchange
await channel.publish("events", "user.created", content);

Consuming messages

for await (const message of channel.consume("my-queue")) {
  console.log("Received:", new TextDecoder().decode(message.content));
  await channel.ack(message);
}

Get single message (polling)

const result = await channel.get("my-queue");
if (result.message) {
  await channel.ack(result.message);
}

Using await using for automatic cleanup

await using rabbit = await createRabbitMqClient({
  url: "amqp://localhost:5672",
});

const channel = await rabbit.channel();
// Client automatically closed when scope exits
function

#createRedisClient

async function createRedisClient(config: RedisClientConfig): Promise<RedisClient>

Create a new Redis client instance.

The client provides comprehensive Redis data structure support including strings, hashes, lists, sets, sorted sets, pub/sub, and transactions.

Parameters
Returns

Promise<RedisClient> — A promise resolving to a new Redis client instance

Examples

Using URL string

const client = await createRedisClient({
  url: "redis://localhost:6379/0",
});

await client.set("key", "value");
const result = await client.get("key");
console.log(result.value);  // "value"

await client.close();

Using connection config object

const client = await createRedisClient({
  url: {
    host: "localhost",
    port: 6379,
    password: "secret",
    db: 0,
  },
});

Set with expiration

// Set key with 1 hour TTL
await client.set("session", sessionData, { ex: 3600 });

// Set key with 5 second TTL in milliseconds
await client.set("temp", data, { px: 5000 });

Hash operations

await client.hset("user:123", "name", "Alice");
await client.hset("user:123", "email", "alice@example.com");

const user = await client.hgetall("user:123");
console.log(user.value);  // { name: "Alice", email: "alice@example.com" }

Pub/Sub

// Subscribe to channel
for await (const message of client.subscribe("events")) {
  console.log("Received:", message.message);
}

// In another session
await client.publish("events", JSON.stringify({ type: "user.created" }));

Using await using for automatic cleanup

await using client = await createRedisClient({
  url: "redis://localhost:6379",
});

await client.set("test", "value");
// Client automatically closed when scope exits
function

#createSqsClient

function createSqsClient(config: SqsClientConfig): Promise<SqsClient>

Create a new Amazon SQS client instance.

The client provides queue management, message publishing and consumption, batch operations, and supports both standard and FIFO queues via AWS SDK.

Parameters
Returns

Promise<SqsClient> — A promise resolving to a new SQS client instance

Examples

Basic usage with existing queue

const sqs = await createSqsClient({
  region: "ap-northeast-1",
  queueUrl: "https://sqs.ap-northeast-1.amazonaws.com/123456789/my-queue",
});

// Send a message
const sendResult = await sqs.send(JSON.stringify({
  type: "ORDER",
  orderId: "123",
}));
console.log("Message ID:", sendResult.messageId);

await sqs.close();

Using LocalStack for local development

const sqs = await createSqsClient({
  region: "us-east-1",
  url: "http://localhost:4566",
  credentials: {
    accessKeyId: "test",
    secretAccessKey: "test",
  },
});

// Create queue dynamically (also sets queueUrl)
const result = await sqs.ensureQueue("test-queue");
console.log(result.queueUrl);  // http://localhost:4566/000000000000/test-queue

Receiving messages with long polling

// Long polling waits up to 20 seconds for messages
const receiveResult = await sqs.receive({
  maxMessages: 10,
  waitTimeSeconds: 20,
  visibilityTimeout: 30,
});

console.log("Received:", receiveResult.messages.length);

// Process and acknowledge messages
for (const msg of receiveResult.messages) {
  const data = JSON.parse(msg.body);
  console.log("Processing:", data);

  // Delete after successful processing
  await sqs.delete(msg.receiptHandle);
}

Batch operations for high throughput

// Send multiple messages in a single API call
const batchResult = await sqs.sendBatch([
  { id: "1", body: JSON.stringify({ event: "user.created", userId: "a1" }) },
  { id: "2", body: JSON.stringify({ event: "user.created", userId: "a2" }) },
  { id: "3", body: JSON.stringify({ event: "user.updated", userId: "a3" }) },
]);

console.log(`Sent: ${batchResult.successful.length}`);
console.log(`Failed: ${batchResult.failed.length}`);

// Batch delete processed messages
const handles = receiveResult.messages.map(m => m.receiptHandle);
await sqs.deleteBatch(handles);

FIFO queue with deduplication

const sqs = await createSqsClient({
  region: "ap-northeast-1",
  queueUrl: "https://sqs.ap-northeast-1.amazonaws.com/123456789/orders.fifo",
});

// FIFO queues require MessageGroupId and optionally MessageDeduplicationId
await sqs.send(JSON.stringify({ orderId: "order-123" }), {
  messageGroupId: "orders",
  messageDeduplicationId: "order-123-v1",
});

Using await using for automatic cleanup

await using sqs = await createSqsClient({
  region: "us-east-1",
  url: "http://localhost:4566",
});

await sqs.ensureQueue("test-queue");
await sqs.send("Hello, SQS!");
// Client automatically closed when scope exits
function

#createSqsMessages

function createSqsMessages(messages: SqsMessage[]): SqsMessages

Create an SqsMessages array with helper methods.

Parameters
function

#expect(11 overloads)

function expect<T extends HttpResponse>(value: T): ReturnType<expectHttpResponse>

Unified expect function that dispatches to the appropriate expectation function based on the type of the input object.

Parameters
  • valueT
Examples
// HTTP response
const httpRes = await http.get("/users");
expect(httpRes).toBeSuccessful().toHaveContentContaining({ users: [] });

// GraphQL response
const gqlRes = await graphql.query("{ users { id name } }");
expect(gqlRes).toBeSuccessful().toHaveContent();

// SQL query result
const sqlRes = await db.query("SELECT * FROM users");
expect(sqlRes).toBeSuccessful().toHaveCount(10);

// MongoDB result
const mongoRes = await mongo.find({ status: "active" });
expect(mongoRes).toBeSuccessful().toHaveLength(10);

// Falls back to expectAnything (chainable @std/expect) for other values
expect(42).toBe(42).toBeGreaterThan(40);
Show all 11 overloads
#1
function expect<T extends HttpResponse>(value: T): ReturnType<expectHttpResponse>

Unified expect function that dispatches to the appropriate expectation function based on the type of the input object.

Parameters
  • valueT
#2
function expect<T extends ConnectRpcResponse>(value: T): ReturnType<expectConnectRpcResponse>
Parameters
  • valueT
#3
function expect<T extends GraphqlResponse>(value: T): ReturnType<expectGraphqlResponse>
Parameters
  • valueT
#4
function expect<T extends SqlQueryResult>(value: T): SqlQueryResultExpectation<ExtractSqlRowType<T>>
Parameters
  • valueT
#5
function expect<T extends DenoKvResult>(value: T): ReturnType<expectDenoKvResult>
Parameters
  • valueT
#6
function expect<T extends RedisResult>(value: T): ReturnType<expectRedisResult>
Parameters
  • valueT
#7
function expect<T extends MongoResult>(value: T): ReturnType<expectMongoResult>
Parameters
  • valueT
#8
function expect<T extends RabbitMqResult>(value: T): ReturnType<expectRabbitMqResult>
Parameters
  • valueT
#9
function expect<T extends SqsResult>(value: T): ReturnType<expectSqsResult>
Parameters
  • valueT
#10
function expect(value: unknown): AnythingExpectation
Parameters
  • valueunknown
#11
function expect(value: unknown): unknown
Parameters
  • valueunknown
function

#expectAnything

function expectAnything<T>(value: T, _: unknown): AnythingExpectation

Creates a chainable expectation for any value using @std/expect matchers.

This wrapper allows method chaining, unlike @std/expect which returns void.

Parameters
  • valueT
    • Value to test
  • _unknown
Returns

AnythingExpectation — Chainable expectation interface

Examples
import { expectAnything } from "@probitas/expect/anything";

// Method chaining
expectAnything(42)
  .toBeDefined()
  .toBeGreaterThan(40)
  .toBeLessThan(50);

// Negation with continued chaining
expectAnything("hello")
  .not.toBe("world")
  .not.toBeNull()
  .toContain("hello");
function

#expectConnectRpcResponse

function expectConnectRpcResponse(response: ConnectRpcResponse, _: unknown): ConnectRpcResponseExpectation

Create a fluent assertion chain for ConnectRPC response validation.

Returns an expectation object with chainable assertion methods. Each assertion throws an Error if it fails, making it ideal for testing.

Parameters
Returns

ConnectRpcResponseExpectation — A fluent expectation chain

Examples

Basic assertions

const response = await client.call(
  "echo.EchoService",
  "echo",
  { message: "Hello!" }
);

expectConnectRpcResponse(response)
  .toBeSuccessful()
  .toHaveContent()
  .toMatchObject({ message: "Hello!" });

Error status assertions

const response = await client.call(
  "user.UserService",
  "getUser",
  { id: "non-existent" },
  { throwOnError: false }
);

expectConnectRpcResponse(response)
  .not.toBeSuccessful()
  .toHaveCode(5)  // NOT_FOUND
  .toHaveErrorContaining("not found");

Header and trailer assertions

expectConnectRpcResponse(response)
  .toBeSuccessful()
  .toHaveHeader("x-request-id")
  .toHaveTrailer("grpc-status");

Performance assertions

expectConnectRpcResponse(response)
  .toBeSuccessful()
  .toHaveDurationLessThan(500);  // Must respond within 500ms
function

#expectDenoKvResult

function expectDenoKvResult<R extends DenoKvResult<any>>(result: R): DenoKvExpectation<R>

Create a fluent expectation chain for any Deno KV result validation.

This unified function accepts any Deno KV result type and returns the appropriate expectation interface based on the result's type discriminator.

Parameters
  • resultR
Examples
// For GET result - returns DenoKvGetResultExpectation<T>
const getResult = await kv.get(["users", "1"]);
expectDenoKvResult(getResult).toBeSuccessful().toHaveContent().toMatchObject({ name: "Alice" });

// For SET result - returns DenoKvSetResultExpectation
const setResult = await kv.set(["users", "1"], { name: "Alice" });
expectDenoKvResult(setResult).toBeSuccessful().toHaveVersionstamp();

// For LIST result - returns DenoKvListResultExpectation<T>
const listResult = await kv.list({ prefix: ["users"] });
expectDenoKvResult(listResult).toBeSuccessful().toHaveLength(3);

// For DELETE result - returns DenoKvDeleteResultExpectation
const deleteResult = await kv.delete(["users", "1"]);
expectDenoKvResult(deleteResult).toBeSuccessful();

// For ATOMIC result - returns DenoKvAtomicResultExpectation
const atomicResult = await kv.atomic().set(["counter"], 1).commit();
expectDenoKvResult(atomicResult).toBeSuccessful().toHaveVersionstamp();
function

#expectGraphqlResponse

function expectGraphqlResponse(response: GraphqlResponse, _: unknown): GraphqlResponseExpectation

Create a fluent expectation chain for GraphQL response validation.

Returns an expectation object with chainable assertion methods. Each assertion throws an Error if it fails, making it ideal for testing.

Parameters
Returns

GraphqlResponseExpectation — A fluent expectation chain

Examples

Basic assertions

const response = await client.query(`
  query GetUser($id: ID!) {
    user(id: $id) { id name }
  }
`, { id: "123" });

expectGraphqlResponse(response)
  .toBeSuccessful()
  .toHaveContent()
  .toMatchObject({ user: { name: "Alice" } });

Error assertions

const response = await client.query(`
  query { invalidField }
`, undefined, { throwOnError: false });

expectGraphqlResponse(response)
  .not.toBeSuccessful()
  .toHaveErrorContaining("Cannot query field");

Mutation with custom matcher

const response = await client.mutation(`
  mutation CreateUser($input: CreateUserInput!) {
    createUser(input: $input) { id name }
  }
`, { input: { name: "Bob" } });

expectGraphqlResponse(response)
  .toBeSuccessful()
  .toSatisfy((data) => {
    assertEquals(data.createUser.name, "Bob");
  });

Performance assertions

expectGraphqlResponse(response)
  .toBeSuccessful()
  .toHaveDurationLessThan(500);  // Must respond within 500ms
function

#expectGrpcResponse

function expectGrpcResponse(response: GrpcResponse, _: unknown): GrpcResponseExpectation

Creates an expectation for a gRPC response.

Parameters
Returns

GrpcResponseExpectation — Fluent expectation interface

Examples
import { expectGrpcResponse } from "@probitas/expect/grpc";

const response = await client.call("GetUser", { id: "1" });
expectGrpcResponse(response)
  .toBeSuccessful()
  .toHaveCode(0)
  .toHaveContent()
  .toHaveDataContaining({ id: "1", name: "Alice" });
function

#expectHttpResponse

function expectHttpResponse(response: HttpResponse, _: unknown): HttpResponseExpectation

Create a fluent expectation chain for HTTP response validation.

Returns an expectation object with chainable assertion methods. Each assertion throws an Error if it fails, making it ideal for testing.

Parameters
Returns

HttpResponseExpectation — A fluent expectation chain

Examples

Basic assertions

const response = await http.get("/users/123");

expectHttpResponse(response)
  .toBeSuccessful()
  .toHaveContentType("application/json")
  .toMatchObject({ id: 123, name: "Alice" });

Error response assertions

const response = await http.get("/not-found", { throwOnError: false });

expectHttpResponse(response)
  .not.toBeSuccessful()
  .toHaveStatus(404);

Performance assertions

expectHttpResponse(response)
  .toBeSuccessful()
  .toHaveDurationLessThan(1000);  // Must respond within 1 second
function

#expectMongoResult

function expectMongoResult<R extends MongoResult<any>>(result: R): MongoExpectation<R>

Create a fluent expectation chain for any MongoDB result validation.

This unified function accepts any MongoDB result type and returns the appropriate expectation interface based on the result's type discriminator.

Parameters
  • resultR
Examples
// For find result - returns MongoFindResultExpectation
const findResult = await users.find({ age: { $gte: 30 } });
expectMongoResult(findResult).toBeSuccessful().toHaveContent().toHaveLength(2);

// For insert result - returns MongoInsertResultExpectation
const insertResult = await users.insertOne({ name: "Alice", age: 30 });
expectMongoResult(insertResult).toBeSuccessful().toHaveInsertedId();

// For update result - returns MongoUpdateResultExpectation
const updateResult = await users.updateOne({ name: "Alice" }, { $set: { age: 31 } });
expectMongoResult(updateResult).toBeSuccessful().toHaveMatchedCount(1).toHaveModifiedCount(1);

// For delete result - returns MongoDeleteResultExpectation
const deleteResult = await users.deleteOne({ name: "Alice" });
expectMongoResult(deleteResult).toBeSuccessful().toHaveDeletedCount(1);

// For findOne result - returns MongoFindOneResultExpectation
const findOneResult = await users.findOne({ name: "Alice" });
expectMongoResult(findOneResult).toBeSuccessful().toHaveContent().toMatchObject({ name: "Alice" });

// For count result - returns MongoCountResultExpectation
const countResult = await users.countDocuments();
expectMongoResult(countResult).toBeSuccessful().toHaveLength(10);
function

#expectRabbitMqResult

function expectRabbitMqResult<R extends RabbitMqResult>(result: R): RabbitMqExpectation<R>

Create a fluent expectation chain for any RabbitMQ result validation.

This unified function accepts any RabbitMQ result type and returns the appropriate expectation interface based on the result's type discriminator.

Parameters
  • resultR
Examples
// For publish result - returns RabbitMqPublishResultExpectation
const publishResult = await channel.sendToQueue(queue, content);
expectRabbitMqResult(publishResult).toBeSuccessful();

// For consume result - returns RabbitMqConsumeResultExpectation
const consumeResult = await channel.get(queue);
expectRabbitMqResult(consumeResult).toBeSuccessful().toHaveContent().routingKey("key");

// For queue result - returns RabbitMqQueueResultExpectation
const queueResult = await channel.assertQueue("my-queue");
expectRabbitMqResult(queueResult).toBeSuccessful().messageCount(0);

// For exchange result - returns RabbitMqExchangeResultExpectation
const exchangeResult = await channel.assertExchange("my-exchange", "direct");
expectRabbitMqResult(exchangeResult).toBeSuccessful();

// For ack result - returns RabbitMqAckResultExpectation
const ackResult = await channel.ack(message);
expectRabbitMqResult(ackResult).toBeSuccessful();
function

#expectRedisResult

function expectRedisResult<R extends RedisResult<any>>(result: R): RedisExpectation<R>

Create a fluent expectation chain for any Redis result validation.

This unified function accepts any Redis result type and returns the appropriate expectation interface based on the result's type discriminator.

Parameters
  • resultR
Examples
// For GET result - returns RedisResultExpectation<string | null>
const getResult = await client.get("key");
expectRedisResult(getResult).toBeSuccessful().toHaveValue("expected");

// For COUNT result - returns RedisCountResultExpectation
const countResult = await client.del("key");
expectRedisResult(countResult).toBeSuccessful().toHaveCount(1);

// For ARRAY result - returns RedisArrayResultExpectation
const arrayResult = await client.lrange("list", 0, -1);
expectRedisResult(arrayResult).toBeSuccessful().toHaveLength(3).toContain("item");
function

#expectSqlQueryResult

function expectSqlQueryResult<T = Record<string, any>>(result: SqlQueryResult<T>, _: unknown): SqlQueryResultExpectation<T>

Create a fluent expectation chain for SQL query result validation.

Returns an expectation object with chainable assertion methods. Each assertion throws an Error if it fails, making it ideal for testing.

Parameters
Returns

SqlQueryResultExpectation<T> — A fluent expectation chain

Examples

Basic assertions

const result = await client.query("SELECT * FROM users WHERE active = true");

expectSqlQueryResult(result)
  .toBeSuccessful()
  .toHaveLengthGreaterThanOrEqual(1)
  .toMatchObject({ name: "Alice" });

Insert/Update assertions

const result = await client.query(
  "INSERT INTO users (name, email) VALUES ($1, $2)",
  ["Bob", "bob@example.com"]
);

expectSqlQueryResult(result)
  .toBeSuccessful()
  .toHaveRowCount(1)
  .toHaveLastInsertId();

Custom matcher with mapped data

expectSqlQueryResult(result)
  .toBeSuccessful()
  .toHaveMapMatching(
    (row) => row.name.toUpperCase(),
    (names) => assertEquals(names, ["ALICE", "BOB"])
  );

Performance assertions

expectSqlQueryResult(result)
  .toBeSuccessful()
  .toHaveDurationLessThan(100);  // Must complete within 100ms
function

#expectSqsMessage

function expectSqsMessage(message: SqsMessage): SqsMessageExpectation

Create a fluent expectation chain for SQS message validation.

Parameters
function

#expectSqsResult

function expectSqsResult<R extends SqsResult>(result: R): SqsExpectation<R>

Create a fluent expectation chain for any SQS result validation.

This unified function accepts any SQS result type and returns the appropriate expectation interface based on the result's type discriminator. Supports send, sendBatch, receive, delete, deleteBatch, ensureQueue, and deleteQueue results.

Parameters
  • resultR
    • The SQS result to create expectations for
Returns

SqsExpectation<R> — A typed expectation object matching the result type

Examples

Send result validation

const sendResult = await sqs.send(JSON.stringify({ orderId: "123" }));
expectSqsResult(sendResult)
  .toBeSuccessful()
  .hasMessageId()
  .toHaveDurationLessThan(1000);

Receive result validation

const receiveResult = await sqs.receive({ maxMessages: 10 });
expectSqsResult(receiveResult)
  .toBeSuccessful()
  .toHaveContent()
  .countAtLeast(1)
  .toMatchObject({ body: "orderId" });

Batch operations

// Send batch
const batchResult = await sqs.sendBatch([
  { id: "1", body: "msg1" },
  { id: "2", body: "msg2" },
]);
expectSqsResult(batchResult)
  .toBeSuccessful()
  .allSuccessful()
  .noFailures();

// Delete batch
const deleteResult = await sqs.deleteBatch(receiptHandles);
expectSqsResult(deleteResult)
  .toBeSuccessful()
  .successfulCount(2);

Queue management

// Ensure queue exists
const ensureResult = await sqs.ensureQueue("test-queue");
expectSqsResult(ensureResult)
  .toBeSuccessful()
  .hasQueueUrl()
  .queueUrlContains("test-queue");

// Delete queue
const deleteResult = await sqs.deleteQueue(queueUrl);
expectSqsResult(deleteResult).toBeSuccessful();

Individual message validation

const receiveResult = await sqs.receive();
for (const msg of receiveResult.messages) {
  expectSqsMessage(msg)
    .bodyJsonContains({ type: "ORDER" })
    .hasAttribute("correlationId");
}
function

#formatDifferences

function formatDifferences(actual: unknown, expected: unknown): string[]

Generates a diff between actual and expected values using LCS algorithm.

This uses @std/internal/diff which implements a Longest Common Subsequence algorithm for intelligent diff generation. This produces much more readable output than simple line-by-line comparison, especially for arrays and nested objects.

Parameters
  • actualunknown
    • The actual value
  • expectedunknown
    • The expected value
Returns

string[] — Array of formatted diff lines (includes [Diff] header)

function

#formatValue

function formatValue(value: unknown): string

Formats a value for display in error messages.

Uses @std/internal/format for consistent formatting that matches Deno's built-in assertion library.

Parameters
  • valueunknown
    • The value to format
Returns

string — Formatted string representation

function

#fromConnectError

function fromConnectError(error: ConnectError, metadata?: Record<string, string>): ConnectRpcError

Convert ConnectRPC's ConnectError to ConnectRpcError.

Parameters
  • errorConnectError
    • The ConnectError from @connectrpc/connect
  • metadata?Record<string, string>
    • Optional metadata from the response
Returns

ConnectRpcError — Appropriate ConnectRpcError subclass based on error code

function

#getStatusName

function getStatusName(code: ConnectRpcStatusCode): string

Get the name of a ConnectRPC/gRPC status code.

Parameters
Examples
getStatusName(0);  // "OK"
getStatusName(5);  // "NOT_FOUND"
getStatusName(16); // "UNAUTHENTICATED"
function

#isConnectRpcStatusCode

function isConnectRpcStatusCode(code: number): code is ConnectRpcStatusCode

Check if a number is a valid ConnectRPC/gRPC status code.

Parameters
  • codenumber
Examples
isConnectRpcStatusCode(0);   // true
isConnectRpcStatusCode(16);  // true
isConnectRpcStatusCode(99);  // false
function

#stripAnsi

function stripAnsi(text: string): string

Strips ANSI escape sequences from a string. Useful for testing error messages.

Parameters
  • textstring
    • Text with ANSI codes
Returns

string — Text without ANSI codes

Type Aliases

type

#BodyInit

type BodyInit = string | Uint8Array | Record<string, unknown> | FormData | URLSearchParams

Request body type.

type

#ConnectProtocol

type ConnectProtocol = "connect" | "grpc" | "grpc-web"

Protocol to use for ConnectRPC transport.

type

#ConnectRpcStatusCode

type ConnectRpcStatusCode = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16

ConnectRPC/gRPC status codes. These codes are used by both gRPC and ConnectRPC protocols.

type

#DenoKvResult

type DenoKvResult<T = unknown> = DenoKvGetResult<T> | DenoKvSetResult | DenoKvDeleteResult | DenoKvListResult<T> | DenoKvAtomicResult

Union of all Deno KV result types.

type

#Document

type Document<T = any> = Record<string, T>

MongoDB document type

type

#FileDescriptorSet

type FileDescriptorSet = MessageShape<FileDescriptorSetSchema>

FileDescriptorSet message type from @bufbuild/protobuf. This is the decoded protobuf message containing file descriptors.

type

#Filter

type Filter = Record<string, any>

MongoDB filter type (simplified for compatibility with mongodb driver) Allows query operators like $gte, $lt, $in, etc.

type

#HttpVersion

type HttpVersion = "1.1" | "2"

HTTP version for transport.

type

#MongoResult

type MongoResult<T = any> = MongoFindResult<T> | MongoInsertOneResult | MongoInsertManyResult | MongoUpdateResult | MongoDeleteResult | MongoFindOneResult<T> | MongoCountResult

Union of all MongoDB result types.

type

#QueryValue

type QueryValue = string | number | boolean

Query parameter value type.

type

#RabbitMqExchangeType

type RabbitMqExchangeType = "direct" | "topic" | "fanout" | "headers"

Exchange type.

type

#RabbitMqResult

type RabbitMqResult = RabbitMqPublishResult | RabbitMqConsumeResult | RabbitMqAckResult | RabbitMqQueueResult | RabbitMqExchangeResult

Union of all RabbitMQ result types.

type

#RedirectMode

type RedirectMode = "follow" | "manual" | "error"

Redirect handling mode.

  • "follow": Automatically follow redirects (default)
  • "manual": Return redirect response without following
  • "error": Throw error on redirect
type

#RedisResult

type RedisResult<T = unknown> = RedisCommonResult<T> | RedisGetResult | RedisSetResult | RedisCountResult | RedisArrayResult<T> | RedisHashResult

Union of all Redis result types.

type

#SqlErrorKind

type SqlErrorKind = "query" | "constraint" | "deadlock" | "unknown"

SQL-specific error kinds.

type

#SqlIsolationLevel

type SqlIsolationLevel = "read_uncommitted" | "read_committed" | "repeatable_read" | "serializable"

Transaction isolation level.

type

#SqsResult

type SqsResult = SqsSendResult | SqsSendBatchResult | SqsReceiveResult | SqsDeleteResult | SqsDeleteBatchResult | SqsEnsureQueueResult | SqsDeleteQueueResult

Union type of all SQS result types.

type

#UpdateFilter

type UpdateFilter = Record<string, any>

MongoDB update filter type (simplified for compatibility with mongodb driver) Allows update operators like $set, $inc, $unset, etc.

Variables

const

#ConnectRpcStatus

const ConnectRpcStatus: { OK: number; CANCELLED: number; UNKNOWN: number; INVALID_ARGUMENT: number; DEADLINE_EXCEEDED: number; NOT_FOUND: number; ALREADY_EXISTS: number; PERMISSION_DENIED: number; RESOURCE_EXHAUSTED: number; FAILED_PRECONDITION: number; ABORTED: number; OUT_OF_RANGE: number; UNIMPLEMENTED: number; INTERNAL: number; UNAVAILABLE: number; DATA_LOSS: number; UNAUTHENTICATED: number }

Human-readable names for ConnectRPC/gRPC status codes.

const

#outdent

const outdent: Outdent
Search Documentation