surrealdb
Version:
The official SurrealDB SDK for JavaScript.
1,801 lines (1,799 loc) • 124 kB
TypeScript
// Generated by dts-bundle-generator v9.5.1
import { Replacer } from '@surrealdb/cbor';
import { UUID } from 'uuidv7';
declare class Feature {
#private;
constructor(name: string, since?: string, until?: string);
get name(): string;
get sinceVersion(): string | undefined;
get untilVersion(): string | undefined;
supports(version: string): boolean;
}
type OnFulfilled<T, TResult> = ((value: T) => TResult | PromiseLike<TResult>) | null | undefined;
type OnRejected<TResult> = ((reason: unknown) => TResult | PromiseLike<TResult>) | null | undefined;
declare abstract class DispatchedPromise<T> extends Promise<T> {
#private;
protected abstract dispatch(): Promise<T>;
constructor();
then<TResult1 = T, TResult2 = never>(onfulfilled?: OnFulfilled<T, TResult1>, onrejected?: OnRejected<TResult2>): Promise<TResult1 | TResult2>;
catch<TResult = never>(onrejected?: OnRejected<TResult>): Promise<T | TResult>;
finally(onfinally?: (() => void) | undefined | null): Promise<T>;
static get [Symbol.species](): PromiseConstructor;
get [Symbol.toStringTag](): string;
}
/**
* A bound query represents a query string combined with bindings.
*/
export declare class BoundQuery<R extends unknown[] = unknown[]> {
#private;
/**
* Creates a new empty BoundQuery instance.
*/
constructor();
/**
* Creates a new BoundQuery instance by cloning an existing instance.
*
* @param origin The BoundQuery to clone
*/
constructor(origin: BoundQuery<R>);
/**
* Creates a new BoundQuery instance.
*
* @param query The initial query string
* @param bindings The initial bindings object
*/
constructor(query: string, bindings?: Record<string, unknown>);
/**
* Retrieves the query string.
*/
get query(): string;
/**
* Retrieves a copy of the configured bindings.
*/
get bindings(): Record<string, unknown>;
/**
* Append another BoundQuery to this one, ensuring no duplicate parameters.
*
* @param other The BoundQuery to append
* @returns The current BoundQuery instance
*/
append(other: BoundQuery<R>): this;
/**
* Append a query string and bindings to this one, ensuring no duplicate parameters.
*
* @param query The query string to append
* @param bindings The bindings to append
* @returns The current BoundQuery instance
*/
append(query: string, bindings?: Record<string, unknown>): this;
/**
* Append a query string and bindings through a template literal tags.
* Interpolated values are automatically stored as bindings with unique names.
*
* @param strings The template string segments
* @param values The interpolated values
* @returns The current BoundQuery instance
*/
append(strings: TemplateStringsArray, ...values: unknown[]): this;
}
/**
* The channel iterator is a utility class that allows you to submit values to an async iterator.
*/
export declare class ChannelIterator<T> implements AsyncIterable<T>, AsyncIterator<T> {
#private;
constructor(cleanup?: () => void);
next(): Promise<IteratorResult<T>>;
return(): Promise<IteratorResult<T>>;
throw(error?: unknown): Promise<IteratorResult<T>>;
[Symbol.asyncIterator](): this;
submit(value: T): void;
cancel(): void;
}
/**
* Recursively compare supported SurrealQL values for equality.
*
* @param x The first value to compare
* @param y The second value to compare
* @returns Whether the two values are recursively equal
*/
export declare function equals(x: unknown, y: unknown): boolean;
/**
* A complex SurrealQL value type
*/
export declare abstract class Value {
/**
* Compare equality with another value.
*/
abstract equals(other: unknown): boolean;
/**
* Convert this value to a serializable string
*/
abstract toJSON(): unknown;
/**
* Convert this value to a string representation
*/
abstract toString(): string;
}
type DurationTuple = [
number | bigint,
number | bigint
] | [
number | bigint
] | [
];
/**
* A SurrealQL duration value with support for parsing, formatting, arithmetic, and nanosecond precision.
*/
export declare class Duration extends Value {
#private;
/**
* Constructs a new Duration by cloning an existing duration
*
* @param input Duration input
*/
constructor(input: Duration);
/**
* Constructs a new Duration from a tuple representation
*
* @param input Second and nanosecond tuple
*/
constructor(input: DurationTuple);
/**
* Constructs a new Duration from a human-readable string, e.g. "1h30m"
*
* @param input Duration string
*/
constructor(input: string);
equals(other: unknown): boolean;
toJSON(): string;
/**
* @returns Human readable duration string
*/
toString(): string;
/**
* Converts the duration to a tuple
*/
toCompact(): [
bigint,
bigint
] | [
bigint
] | [
];
/**
* Parses a duration string like "1h30m"
*
* @param input Input string
* @returns [seconds, nanoseconds]
*/
static parseString(input: string): [
bigint,
bigint
];
/**
* Adds two durations together
*
* @param other The duration to add
* @returns The resulting duration
*/
add(other: Duration): Duration;
/**
* Subtracts another duration from this one
*
* @param other The duration to subtract
* @returns The resulting duration
*/
sub(other: Duration): Duration;
/**
* Multiplies the duration by a scalar
*
* @param factor The factor to multiply by
* @returns The resulting duration
*/
mul(factor: number | bigint): Duration;
/**
* Divides the duration
*
* @param divisor The duration or scalar to divide by
* @returns A new Duration or ratio (unitless bigint)
*/
div(divisor: Duration): bigint;
div(divisor: number | bigint): Duration;
/**
* Computes the remainder after division
*
* @param mod The divisor
* @returns The remainder duration
*/
mod(mod: Duration): Duration;
/**
* Total nanoseconds in this duration
*/
get nanoseconds(): bigint;
/**
* Total microseconds
*/
get microseconds(): bigint;
/**
* Total milliseconds
*/
get milliseconds(): bigint;
/**
* Whole seconds in the duration
*/
get seconds(): bigint;
/**
* Total whole minutes in the duration
*/
get minutes(): bigint;
/**
* Total whole hours in the duration
*/
get hours(): bigint;
/**
* Total whole days in the duration
*/
get days(): bigint;
/**
* Total whole weeks in the duration
*/
get weeks(): bigint;
/**
* Total whole years in the duration
*/
get years(): bigint;
/**
* Creates a Duration from nanoseconds
*
* @param ns Nanoseconds value
* @returns The resulting duration
*/
static nanoseconds(ns: number | bigint): Duration;
/**
* Creates a Duration from microseconds
*
* @param µs Microseconds value
* @returns The resulting duration
*/
static microseconds(µs: number | bigint): Duration;
/**
* Creates a Duration from milliseconds
*
* @param ms Milliseconds value
* @returns The resulting duration
*/
static milliseconds(ms: number | bigint): Duration;
/**
* Creates a Duration from seconds
*
* @param s Seconds value
* @returns The resulting duration
*/
static seconds(s: number | bigint): Duration;
/**
* Creates a Duration from minutes
*
* @param m Minutes value
* @returns The resulting duration
*/
static minutes(m: number | bigint): Duration;
/**
* Creates a Duration from hours
*
* @param h Hours value
* @returns The resulting duration
*/
static hours(h: number | bigint): Duration;
/**
* Creates a Duration from days
*
* @param d Days value
* @returns The resulting duration
*/
static days(d: number | bigint): Duration;
/**
* Creates a Duration from weeks
*
* @param w Weeks value
* @returns The resulting duration
*/
static weeks(w: number | bigint): Duration;
/**
* Creates a Duration from years
*
* @param y Years value
* @returns The resulting duration
*/
static years(y: number | bigint): Duration;
/**
* Parses a duration from a float string with a single time unit, e.g. "1.998487792s", "1.5m", "500.0ms"
*
* @param input Float duration string
* @returns The resulting duration
*/
static parseFloat(input: string): Duration;
/**
* Measures the elapsed time since the function was called
* If the Performance API is available, it uses it to measure the elapsed time in nanoseconds
*
* @returns A function that returns the elapsed time as a Duration
*/
static measure(): () => Duration;
}
type DateTimeTuple = [
number | bigint,
number | bigint
];
/**
* A SurrealQL datetime value with support for parsing, formatting, arithmetic, and nanosecond precision.
*/
export declare class DateTime extends Value {
#private;
private static loadHr;
/**
* Constructs a new DateTime with the current time, equivalent to `DateTime.now()`
*/
constructor();
/**
* Constructs a new DateTime by cloning an existing datetime
*
* @param input DateTime input
*/
constructor(input: DateTime);
/**
* Constructs a new DateTime from a JavaScript Date object
*
* @param input Date input
*/
constructor(input: Date);
/**
* Constructs a new DateTime from a tuple representation
*
* @param input Second and nanosecond tuple
*/
constructor(input: DateTimeTuple);
/**
* Constructs a new DateTime from an ISO String
*
* @param input ISO String string
*/
constructor(input: string);
/**
* Constructs a new DateTime from a number or bigint
*
* @param input Number or bigint input
*/
constructor(input: number | bigint);
equals(other: unknown): boolean;
toJSON(): string;
/**
* @returns The ISO 8601 string representation of the datetime
*/
toString(): string;
/**
* Converts the datetime to a tuple
*/
toCompact(): [
bigint,
bigint
];
/**
* Formats the datetime as an ISO 8601 string
*/
toISOString(): string;
/**
* Converts to JavaScript Date object
*/
toDate(): Date;
/**
* Parses a datetime string
*
* @param input Input string (ISO 8601 format)
* @returns [seconds, nanoseconds] tuple
*/
static parseString(input: string): [
bigint,
bigint
];
/**
* Adds a duration to this datetime
*
* @param duration The duration to add
* @returns The new datetime instance
*/
add(duration: Duration): DateTime;
/**
* Subtracts a duration from this datetime
*
* @param duration The duration to subtract
* @returns The new datetime instance
*/
sub(duration: Duration): DateTime;
/**
* Calculates the duration between two datetimes
*
* @param other The other datetime
*/
diff(other: DateTime): Duration;
/**
* Compares this DateTime with another
*
* @param other The DateTime to compare with
* @returns -1 if other is before, 0 if equal, 1 if other is after
*/
compare(other: DateTime): number;
/**
* Total nanoseconds since Unix epoch
*/
get nanoseconds(): bigint;
/**
* Total microseconds since Unix epoch
*/
get microseconds(): bigint;
/**
* Total milliseconds since Unix epoch
*/
get milliseconds(): number;
/**
* Seconds since Unix epoch
*/
get seconds(): number;
/**
* Creates a DateTime from nanoseconds since Unix epoch
*
* @param ns Nanoseconds value
*/
static fromEpochNanoseconds(ns: number | bigint): DateTime;
/**
* Creates a DateTime from microseconds since Unix epoch
*
* @param µs Microseconds value
*/
static fromEpochMicroseconds(µs: number | bigint): DateTime;
/**
* Creates a DateTime from milliseconds since Unix epoch
*
* @param ms Milliseconds value
*/
static fromEpochMilliseconds(ms: number | bigint): DateTime;
/**
* Creates a DateTime from seconds since Unix epoch
*
* @param s Seconds value
*/
static fromEpochSeconds(s: number | bigint): DateTime;
/**
* Returns a new DateTime representing the current time
*/
static now(): DateTime;
/**
* Returns a new DateTime representing the Unix epoch (1970-01-01T00:00:00Z)
*/
static epoch(): DateTime;
}
type DecimalTuple = [
bigint,
bigint,
number
];
/**
* A SurrealQL decimal number value with support for parsing, formatting, arithmetic, and high precision.
*/
export declare class Decimal extends Value {
#private;
/**
* Constructs a new Decimal by cloning an existing Decimal
*
* @param input Decimal input
*/
constructor(input: Decimal);
/**
* Constructs a new Decimal from a scientific notation string
*
* @param input String input
*/
constructor(input: string);
/**
* Constructs a new Decimal from a number or bigint
*
* @param input Number or bigint input
*/
constructor(input: number | bigint);
/**
* Constructs a new Decimal from a tuple [int, frac, scale]
*
* @param input Tuple input
*/
constructor(input: DecimalTuple);
equals(other: unknown): boolean;
toJSON(): string;
/**
* @returns The canonical string representation of the decimal with
* trailing zeros in fractional part trimmed
*/
toString(): string;
/** Returns the integer part of the number */
get int(): bigint;
/** Returns the fractional part of the number */
get frac(): bigint;
/** Returns the scale (number of decimal places) */
get scale(): number;
/**
* Adds another Decimal to this one
*
* @param other The Decimal to add
* @returns A new Decimal representing the sum
*/
add(other: Decimal): Decimal;
/**
* Subtracts another Decimal from this one
*
* @param other The Decimal to subtract
* @returns A new Decimal representing the difference
*/
sub(other: Decimal): Decimal;
/**
* Multiplies this Decimal by another
*
* @param other The Decimal to multiply by
* @returns A new Decimal representing the product
*/
mul(other: Decimal): Decimal;
/**
* Divides this Decimal by another, with fixed precision
*
* @param other The Decimal to divide by
* @returns A new Decimal representing the quotient
*/
div(other: Decimal): Decimal;
/**
* Computes the remainder of this Decimal divided by another
*
* @param other The divisor Decimal
* @returns A new Decimal representing the remainder
*/
mod(other: Decimal): Decimal;
/**
* Returns the absolute value of this Decimal
* @returns A new Decimal with non-negative components
*/
abs(): Decimal;
/**
* Returns the negated value of this Decimal
* @returns A new Decimal with inverted sign
*/
neg(): Decimal;
/**
* Checks if the value is exactly zero
* @returns True if both int and frac parts are zero
*/
isZero(): boolean;
/**
* Checks if the value is negative
* @returns True if negative
*/
isNegative(): boolean;
/**
* Compares this Decimal with another
*
* @param other The Decimal to compare with
* @returns -1 if less, 0 if equal, 1 if greater
*/
compare(other: Decimal): number;
/**
* Rounds the Decimal to a fixed number of decimal places
*
* @param precision Number of digits to keep after the decimal point
* @returns The new decimal instance
*/
round(precision: number): Decimal;
/**
* Converts the number to fixed-point notation string
*
* @param precision Number of digits after the decimal point
*/
toFixed(precision: number): string;
/**
* Converts the Decimal to a native JavaScript number
* @returns A number approximation (may lose precision)
*/
toFloat(): number;
/**
* Converts to bigint by truncating the fractional part
* @returns An bigint approximation (may lose precision)
*/
toBigInt(): bigint;
/**
* Returns the raw parts of the Decimal
* @returns An object with int, frac, and scale
*/
toParts(): {
int: bigint;
frac: bigint;
scale: number;
};
/**
* Converts to scientific notation string (e.g., "1.23e4")
*/
toScientific(): string;
/**
* Parses a number in scientific notation into a Decimal
*
* @param input The scientific notation string
*/
static fromScientificNotation(input: string): Decimal;
private toBigIntWithScale;
}
/**
* A SurrealQL file reference value.
*/
export declare class FileRef extends Value {
#private;
constructor(bucket: string, key: string);
get bucket(): string;
get key(): string;
equals(other: unknown): boolean;
toJSON(): string;
toString(): string;
}
/**
* An uncomputed SurrealQL future value.
*
* @deprecated Futures were removed in SurrealDB 3.0
*/
export declare class Future extends Value {
#private;
constructor(body: string);
equals(other: unknown): boolean;
toJSON(): string;
/**
* @returns The uncomputed future notation
*/
toString(): string;
/**
* The body of the future
*/
get body(): string;
}
/**
* A SurrealQL geometry value.
*/
export declare abstract class Geometry extends Value {
abstract toJSON(): GeoJson;
abstract is(geometry: Geometry): boolean;
abstract clone(): Geometry;
equals(other: unknown): boolean;
toString(): string;
}
/**
* A SurrealQL point geometry value.
*/
export declare class GeometryPoint extends Geometry {
readonly point: [
number,
number
];
constructor(point: [
number | Decimal,
number | Decimal
] | GeometryPoint);
toJSON(): GeoJsonPoint;
get coordinates(): GeoJsonPoint["coordinates"];
is(geometry: Geometry): geometry is GeometryPoint;
clone(): GeometryPoint;
}
/**
* A SurrealQL line geometry value.
*/
export declare class GeometryLine extends Geometry {
readonly line: [
GeometryPoint,
GeometryPoint,
...GeometryPoint[]
];
constructor(line: [
GeometryPoint,
GeometryPoint,
...GeometryPoint[]
] | GeometryLine);
toJSON(): GeoJsonLineString;
get coordinates(): GeoJsonLineString["coordinates"];
close(): void;
is(geometry: Geometry): geometry is GeometryLine;
clone(): GeometryLine;
}
/**
* A SurrealQL polygon geometry value.
*/
export declare class GeometryPolygon extends Geometry {
readonly polygon: [
GeometryLine,
...GeometryLine[]
];
constructor(polygon: [
GeometryLine,
...GeometryLine[]
] | GeometryPolygon);
toJSON(): GeoJsonPolygon;
get coordinates(): GeoJsonPolygon["coordinates"];
is(geometry: Geometry): geometry is GeometryPolygon;
clone(): GeometryPolygon;
}
/**
* A SurrealQL multi-point geometry value.
*/
export declare class GeometryMultiPoint extends Geometry {
readonly points: [
GeometryPoint,
...GeometryPoint[]
];
constructor(points: [
GeometryPoint,
...GeometryPoint[]
] | GeometryMultiPoint);
toJSON(): GeoJsonMultiPoint;
get coordinates(): GeoJsonMultiPoint["coordinates"];
is(geometry: Geometry): geometry is GeometryMultiPoint;
clone(): GeometryMultiPoint;
}
/**
* A SurrealQL multi-line geometry value.
*/
export declare class GeometryMultiLine extends Geometry {
readonly lines: [
GeometryLine,
...GeometryLine[]
];
constructor(lines: [
GeometryLine,
...GeometryLine[]
] | GeometryMultiLine);
toJSON(): GeoJsonMultiLineString;
get coordinates(): GeoJsonMultiLineString["coordinates"];
is(geometry: Geometry): geometry is GeometryMultiLine;
clone(): GeometryMultiLine;
}
/**
* A SurrealQL multi-polygon geometry value.
*/
export declare class GeometryMultiPolygon extends Geometry {
readonly polygons: [
GeometryPolygon,
...GeometryPolygon[]
];
constructor(polygons: [
GeometryPolygon,
...GeometryPolygon[]
] | GeometryMultiPolygon);
toJSON(): GeoJsonMultiPolygon;
get coordinates(): GeoJsonMultiPolygon["coordinates"];
is(geometry: Geometry): geometry is GeometryMultiPolygon;
clone(): GeometryMultiPolygon;
}
/**
* A SurrealQL geometry collection value.
*/
export declare class GeometryCollection extends Geometry {
readonly collection: [
Geometry,
...Geometry[]
];
constructor(collection: [
Geometry,
...Geometry[]
] | GeometryCollection);
toJSON(): GeoJsonCollection;
get geometries(): GeoJsonCollection["geometries"];
is(geometry: Geometry): geometry is GeometryCollection;
clone(): GeometryCollection;
}
type GeoJson = GeoJsonPoint | GeoJsonLineString | GeoJsonPolygon | GeoJsonMultiPoint | GeoJsonMultiLineString | GeoJsonMultiPolygon | GeoJsonCollection;
type GeoJsonPoint = {
type: "Point";
coordinates: [
number,
number
];
};
type GeoJsonLineString = {
type: "LineString";
coordinates: [
GeoJsonPoint["coordinates"],
GeoJsonPoint["coordinates"],
...GeoJsonPoint["coordinates"][]
];
};
type GeoJsonPolygon = {
type: "Polygon";
coordinates: [
GeoJsonLineString["coordinates"],
...GeoJsonLineString["coordinates"][]
];
};
type GeoJsonMultiPoint = {
type: "MultiPoint";
coordinates: [
GeoJsonPoint["coordinates"],
...GeoJsonPoint["coordinates"][]
];
};
type GeoJsonMultiLineString = {
type: "MultiLineString";
coordinates: [
GeoJsonLineString["coordinates"],
...GeoJsonLineString["coordinates"][]
];
};
type GeoJsonMultiPolygon = {
type: "MultiPolygon";
coordinates: [
GeoJsonPolygon["coordinates"],
...GeoJsonPolygon["coordinates"][]
];
};
type GeoJsonCollection = {
type: "GeometryCollection";
geometries: GeoJson[];
};
/**
* Represents a range bound which includes the value within the range
*/
export declare class BoundIncluded<T> {
readonly value: T;
constructor(value: T);
}
/**
* Represents a range bound which excludes the value from the range
*/
export declare class BoundExcluded<T> {
readonly value: T;
constructor(value: T);
}
/**
* Represents a Bound which can represent the start or end of a range
*/
export type Bound<T> = BoundIncluded<T> | BoundExcluded<T> | undefined;
/**
* A SurrealQL range value.
*/
declare class Range$1<Beg, End> extends Value {
#private;
constructor(beg: Bound<Beg>, end: Bound<End>);
equals(other: unknown): boolean;
toJSON(): string;
/**
* @returns The escaped range string
*/
toString(): string;
/**
* The range bound beginning
*/
get begin(): Bound<Beg>;
/**
* The range bound ending
*/
get end(): Bound<End>;
}
type Prettify<T> = {
[K in keyof T]: T[K];
} & {};
type Field<I> = keyof I | (string & {});
type Selection$1 = "value" | "fields" | "diff";
type WidenRecordIdValue<T> = T extends string ? string : T extends number ? number : T extends bigint ? bigint : T;
/**
* A SurrealQL table value.
*/
export declare class Table<Tb extends string = string> extends Value {
#private;
constructor(tb: Tb);
equals(other: unknown): boolean;
toJSON(): string;
/**
* @returns The escaped table name
*/
toString(): string;
/**
* The unescaped table name
*/
get name(): Tb;
}
/**
* A SurrealQL UUID value.
*/
export declare class Uuid extends Value {
#private;
/**
* Constructs a new Uuid by cloning an existing uuid
*
* @param input Uuid input
*/
constructor(uuid: Uuid | UUID);
/**
* Constructs a new Uuid from a string representation
*
* @param uuid String input
*/
constructor(uuid: string);
/**
* Constructs a new Uuid from a binary representation
*
* @param uuid ArrayBuffer or Uint8Array input
*/
constructor(uuid: ArrayBuffer | Uint8Array);
equals(other: unknown): boolean;
toJSON(): string;
/**
* @returns The string representation of the UUID
*/
toString(): string;
/**
* Converts the UUID to a Uint8Array
*/
toUint8Array(): Uint8Array;
/**
* Converts the UUID to a ArrayBuffer
*/
toBuffer(): ArrayBufferLike;
/**
* Generate a new UUID v4
*/
static v4(): Uuid;
/**
* Generate a new UUID v7
*/
static v7(): Uuid;
}
export type RecordIdValue = string | number | Uuid | bigint | unknown[] | Record<string, unknown>;
declare class RecordId<Tb extends string = string, Id extends RecordIdValue = RecordIdValue> extends Value {
#private;
constructor(table: Tb | Table<Tb>, id: Id);
equals(other: unknown): boolean;
toJSON(): string;
/**
* @returns The escaped record ID string including the table name
*/
toString(): string;
/**
* The table part value
*/
get table(): Table<Tb>;
/**
* The ID part value
*/
get id(): Id;
}
interface RecordIdConstructor {
new <T extends string = string, I extends RecordIdValue = RecordIdValue>(table: T | Table<T>, id: I): RecordId<T, WidenRecordIdValue<I>>;
new <R extends RecordId<string, RecordIdValue>>(table: R["table"]["name"], id: R["id"]): RecordId<R["table"]["name"], R["id"]>;
}
/**
* A SurrealQL record ID value.
*/
type _RecordId<Tb extends string = string, Id extends RecordIdValue = RecordIdValue> = RecordId<Tb, Id>;
declare const _RecordId: RecordIdConstructor;
declare class RecordIdRange<Tb extends string = string, Id extends RecordIdValue = RecordIdValue> extends Value {
#private;
constructor(table: Tb | Table<Tb>, beg: Bound<Id>, end: Bound<Id>);
equals(other: unknown): boolean;
toJSON(): string;
/**
* @returns The escaped record ID range string
*/
toString(): string;
/**
* The table part value
*/
get table(): Table<Tb>;
/**
* The range bound beginning
*/
get begin(): Bound<Id>;
/**
* The range bound ending
*/
get end(): Bound<Id>;
}
interface RecordIdRangeConstructor {
new <T extends string = string, I extends RecordIdValue = RecordIdValue>(table: T | Table<T>, beg: Bound<I>, end: Bound<I>): RecordIdRange<T, WidenRecordIdValue<I>>;
new <R extends RecordIdRange<string, RecordIdValue>>(table: R["table"]["name"], beg: R["begin"], end: R["end"]): RecordIdRange<R["table"]["name"], R["begin"] extends Bound<infer I> ? (I extends RecordIdValue ? I : never) : never>;
}
/**
* A SurrealQL record ID range value.
*/
type _RecordIdRange<Tb extends string = string, Id extends RecordIdValue = RecordIdValue> = RecordIdRange<Tb, Id>;
declare const _RecordIdRange: RecordIdRangeConstructor;
/**
* A SurrealQL string-represented record ID value.
*/
export declare class StringRecordId extends Value {
#private;
constructor(rid: string | StringRecordId | _RecordId);
equals(other: unknown): boolean;
toJSON(): string;
/**
* @returns The string representation of the record ID
*/
toString(): string;
}
/**
* Escape a given string to be used as a valid SurrealQL ident
*
* @param str - The string to escape
* @returns Optionally escaped string
*/
export declare function escapeIdent(str: string): string;
/**
* Escape a number to be used as a valid SurrealQL ident
*
* @param num - The number to escape
* @returns Optionally escaped number
*/
export declare function escapeNumber(num: number | bigint): string;
/**
* Escape a record id value part
*
* @param id The record id value part
* @returns The escaped record id value part
*/
export declare function escapeIdPart(id: RecordIdValue): string;
/**
* Escape a range bound value
*
* @param bound The range bound containing a value
* @returns The escaped range bound
*/
export declare function escapeRangeBound<T>(bound: Bound<T>): string;
/**
* Parse a SurrealQL expression to a BoundQuery
*
* @param expr The SurrealQL expression
* @returns A BoundQuery instance
*/
export declare function expr(expr: ExprLike): BoundQuery;
/**
* Represents a raw SurrealQL expression
*
* **IMPORTANT**: This function should only be used when no other operator is applicable.
* Incorrect use of this function will risk exposing queries to SQL injection.
*
* @param s The raw value
*/
export declare const raw: (s: string) => Expr;
/**
* Represents a equality comparison operation (=)
*
* @param field The field name
* @param v The value to compare against
*/
export declare const eq: (field: string, v: unknown) => Expr;
/**
* Represents an exact equality comparison operation (==)
*
* @param field The field name
* @param v The value to compare against
*/
export declare const eeq: (field: string, v: unknown) => Expr;
/**
* Represents a not equal comparison operation (!=)
*
* @param field The field name
* @param v The value to compare against
*/
export declare const ne: (field: string, v: unknown) => Expr;
/**
* Represents a greater than comparison operation (>)
*
* @param field The field name
* @param v The value to compare against
*/
export declare const gt: (field: string, v: unknown) => Expr;
/**
* Represents a greater than or equal to comparison operation (>=)
*
* @param field The field name
* @param v The value to compare against
*/
export declare const gte: (field: string, v: unknown) => Expr;
/**
* Represents a less than comparison operation (<)
*
* @param field The field name
* @param v The value to compare against
*/
export declare const lt: (field: string, v: unknown) => Expr;
/**
* Represents a less than or equal to comparison operation (<=)
*
* @param field The field name
* @param v The value to compare against
*/
export declare const lte: (field: string, v: unknown) => Expr;
/**
* Represents a contains operation (CONTAINS)
*
* @param field The field name
* @param v The value to compare against
*/
export declare const contains: (field: string, v: unknown) => Expr;
/**
* Represents a contains any operation (CONTAINSANY)
*
* @param field The field name
* @param v The value to compare against
*/
export declare const containsAny: (field: string, v: unknown) => Expr;
/**
* Represents a contains all operation (CONTAINSALL)
*
* @param field The field name
* @param v The value to compare against
*/
export declare const containsAll: (field: string, v: unknown) => Expr;
/**
* Represents a contains none operation (CONTAINSNONE)
*
* @param field The field name
* @param v The value to compare against
*/
export declare const containsNone: (field: string, v: unknown) => Expr;
/**
* Represents an inside operation (INSIDE)
*
* @param field The field name
* @param v The value to compare against
*/
export declare const inside: (field: string, v: unknown) => Expr;
/**
* Represents a geometry outside operation (OUTSIDE)
*
* @param field The field name
* @param g The value to compare against
*/
export declare const outside: (field: string, g: unknown) => Expr;
/**
* Represents a geometry intersects operation (INTERSECTS)
*
* @param field The field name
* @param g The value to compare against
*/
export declare const intersects: (field: string, g: unknown) => Expr;
/**
* Represents a full-text search match operation (@@)
*
* @param field The field name
* @param q The value to compare against
* @param ref The optional reference number
*/
export declare const matches: (field: string, q: string, ref?: number) => Expr;
/**
* Represents a KNN nearest neighbor operation
*
* Supported operations include:
* - Brute Force: <|n,metric|>, where n is the number of neighbors and metric is the metric to use
* - MTree: <|n|>, where n is the number of neighbors
* - HNSW: <|n,ef|>, where n is the number of neighbors and ef is the ef
*
* @param field The field name
* @param v The value to compare against
* @param neighbors The number of neighbors
* @param metricOrEf The optional metric or ef
*/
export declare const knn: (field: string, v: unknown, neighbors: number, metricOrEf?: string | number) => Expr;
/**
* Represents a between operation. This is a shortcut for `and(gte(field, a), lte(field, b))`
*
* @param field The field name
* @param a The lower bound
* @param b The upper bound
*/
export declare const between: (field: string, a: unknown, b: unknown) => Expr;
/**
* Represents a logical AND operation
*
* @param exprs The expressions to join
* @returns A new expression
*/
export declare const and: (...exprs: ExprLike[]) => Expr;
/**
* Represents a logical OR operation
*
* @param exprs The expressions to join
* @returns A new expression
*/
export declare const or: (...exprs: ExprLike[]) => Expr;
/**
* Represents a logical NOT operation
*
* @param expr The expression to negate
* @returns A new expression
*/
export declare const not: (expr: ExprLike) => Expr;
/**
* Available features which may be supported by specific
* engines or versions of SurrealDB.
*/
export declare const Features: Readonly<{
LiveQueries: Feature;
Sessions: Feature;
Api: Feature;
RefreshTokens: Feature;
Transactions: Feature;
ExportImportRaw: Feature;
SurrealML: Feature;
}>;
/**
* Represents a single query result frame frame
*/
export declare class Frame<T, J extends boolean> {
readonly query: number;
constructor(query: number);
/**
* Returns true if the frame is associated with the given query index
*/
isOf<V = T>(query: number): this is Frame<V, J>;
/**
* Returns true if the frame is a value frame
*/
isValue<V = T>(): this is ValueFrame<V, J>;
/**
* Returns true if the frame is an error frame
*/
isError<V = T>(): this is ErrorFrame<V, J>;
/**
* Returns true if the frame is a done frame
*/
isDone<V = T>(): this is DoneFrame<V, J>;
/**
* Returns true if the frame is a value frame and associated with the given query index
*/
isValueOf<V = T>(query: number): this is ValueFrame<V, J>;
/**
* Returns true if the frame is an error frame and associated with the given query index
*/
isErrorOf<V = T>(query: number): this is ErrorFrame<V, J>;
/**
* Returns true if the frame is a done frame and associated with the given query index
*/
isDoneOf<V = T>(query: number): this is DoneFrame<V, J>;
}
/**
* Represents a value frame in a query result. If `isSingle` is true, the frame represents a single value
* and no further values will be returned for that specific statement.
*/
export declare class ValueFrame<T, J extends boolean> extends Frame<T, J> {
readonly value: MaybeJsonify<T, J>;
readonly isSingle: boolean;
constructor(query: number, value: MaybeJsonify<T, J>, isSingle: boolean);
isOf<V = T>(query: number): this is ValueFrame<V, J>;
}
/**
* Represents an error frame in a query result
*/
export declare class ErrorFrame<T, J extends boolean> extends Frame<T, J> {
readonly stats: QueryStats | undefined;
readonly error: ServerError;
constructor(query: number, stats: QueryStats | undefined, error: ServerError);
isOf<V = T>(query: number): this is ErrorFrame<V, J>;
/**
* Throw the server error corresponding to this error frame
*/
throw(): never;
}
/**
* Represents a done frame in a query result
*/
export declare class DoneFrame<T, J extends boolean> extends Frame<T, J> {
readonly stats: QueryStats | undefined;
readonly type: QueryType;
constructor(query: number, stats: QueryStats | undefined, type: QueryType);
isOf<V = T>(query: number): this is DoneFrame<V, J>;
}
export declare const MINIMUM_VERSION = "2.1.0";
export declare const MAXIMUM_VERSION = "4.0.0";
/**
* Returns whether a SurrealDB version is supported by the SDK.
*
* @param version The SurrealDB version to check
* @param min The minimum version to check against
* @param until The maximum version to check against
* @returns Whether the version is supported
*/
export declare function isVersionSupported(version: string, min?: string, until?: string): boolean;
export type Jsonify<T> = T extends Date | DateTime | Uuid | Decimal | Duration | Future | FileRef | Range$1<unknown, unknown> | StringRecordId ? string : T extends undefined ? undefined : T extends Record<string | number | symbol, unknown> | Array<unknown> ? {
[K in keyof T]: Jsonify<T[K]>;
} : T extends Map<infer K, infer V> ? Map<K, Jsonify<V>> : T extends Set<infer V> ? Set<Jsonify<V>> : T extends Geometry ? ReturnType<T["toJSON"]> : T extends _RecordId<infer Tb> ? `${Tb}:${string}` : T extends _RecordIdRange<infer Tb> ? `${Tb}:${string}..${string}` : T extends Table<infer Tb> ? `${Tb}` : T;
/**
* Recursively convert any supported SurrealQL value into a serializable JSON representation.
*
* @param input The input value
* @returns JSON-safe representation
*/
export declare function jsonify<T>(input: T): Jsonify<T>;
interface AuthOptions {
transaction: Uuid | undefined;
session: Session;
json: boolean;
}
declare class AuthPromise<T, J extends boolean = false> extends DispatchedPromise<MaybeJsonify<T, J>> {
#private;
constructor(connection: ConnectionController, options: AuthOptions);
/**
* Configure the query to return the result as a
* JSON-compatible structure.
*
* This is useful when query results need to be serialized. Keep in mind
* that your responses will lose SurrealDB type information.
*/
json(): AuthPromise<T, true>;
/**
* Compile this qurery into a BoundQuery
*/
compile(): BoundQuery<[
T
]>;
/**
* Stream the results of the query as they are received.
*
* @returns An async iterable of query frames.
*/
stream(): AsyncIterable<Frame<T, J>>;
protected dispatch(): Promise<MaybeJsonify<T, J>>;
}
interface CreateOptions {
what: AnyRecordId | Table;
mutation?: Mutation;
data?: unknown;
output?: Output;
timeout?: Duration;
version?: DateTime;
transaction: Uuid | undefined;
session: Session;
json: boolean;
}
declare class CreatePromise<T, I, J extends boolean = false> extends DispatchedPromise<MaybeJsonify<T, J>> {
#private;
constructor(connection: ConnectionController, options: CreateOptions);
/**
* Configure the query to return the result as a
* JSON-compatible structure.
*
* This is useful when query results need to be serialized. Keep in mind
* that your responses will lose SurrealDB type information.
*/
json(): CreatePromise<T, I, true>;
/**
* Configure the query to set the record data
*/
content(data: Values<I>): CreatePromise<T, I, J>;
/**
* Configure the query to patch the record data
*/
patch(data: Values<I>): CreatePromise<T, I, J>;
/**
* Configure the output of the query
*/
output(output: Output): CreatePromise<T, I, J>;
/**
* Configure the timeout of the query
*/
timeout(timeout: Duration): CreatePromise<T, I, J>;
/**
* Configure a custom version of the data being created. This is used
* alongside version enabled storage engines such as SurrealKV.
*/
version(version: DateTime): CreatePromise<T, I, J>;
/**
* Compile this qurery into a BoundQuery
*/
compile(): BoundQuery<[
T
]>;
/**
* Stream the results of the query as they are received.
*
* @returns An async iterable of query frames.
*/
stream(): AsyncIterable<Frame<T, J>>;
protected dispatch(): Promise<MaybeJsonify<T, J>>;
}
interface DeleteOptions {
what: AnyRecordId | _RecordIdRange | Table;
output?: Output;
timeout?: Duration;
version?: DateTime;
transaction: Uuid | undefined;
session: Session;
json: boolean;
}
declare class DeletePromise<T, J extends boolean = false> extends DispatchedPromise<MaybeJsonify<T, J>> {
#private;
constructor(connection: ConnectionController, options: DeleteOptions);
/**
* Configure the query to return the result as a
* JSON-compatible structure.
*
* This is useful when query results need to be serialized. Keep in mind
* that your responses will lose SurrealDB type information.
*/
json(): DeletePromise<T, true>;
/**
* Configure the output of the query
*/
output(output: Output): DeletePromise<T, J>;
/**
* Configure the timeout of the query
*/
timeout(timeout: Duration): DeletePromise<T, J>;
/**
* Configure a custom version of the data being created. This is used
* alongside version enabled storage engines such as SurrealKV.
*/
version(version: DateTime): DeletePromise<T, J>;
/**
* Compile this qurery into a BoundQuery
*/
compile(): BoundQuery<[
T
]>;
/**
* Stream the results of the query as they are received.
*
* @returns An async iterable of query frames.
*/
stream(): AsyncIterable<Frame<T, J>>;
protected dispatch(): Promise<MaybeJsonify<T, J>>;
}
interface InsertOptions {
table: Table | undefined;
what: unknown | unknown[];
relation?: boolean;
ignore?: boolean;
output?: Output;
timeout?: Duration;
version?: DateTime;
transaction: Uuid | undefined;
session: Session;
json: boolean;
}
declare class InsertPromise<T, J extends boolean = false> extends DispatchedPromise<MaybeJsonify<T, J>> {
#private;
constructor(connection: ConnectionController, options: InsertOptions);
/**
* Configure the query to return the result as a
* JSON-compatible structure.
*
* This is useful when query results need to be serialized. Keep in mind
* that your responses will lose SurrealDB type information.
*/
json(): InsertPromise<T, true>;
/**
* Configure the query to insert a relation instead of a regular record
*/
relation(): InsertPromise<T, J>;
/**
* Configure the query to ignore records if they already exist
*/
ignore(): InsertPromise<T, J>;
/**
* Configure the output of the query
*/
output(output: Output): InsertPromise<T, J>;
/**
* Configure the timeout of the query
*/
timeout(timeout: Duration): InsertPromise<T, J>;
/**
* Configure a custom version of the data being created. This is used
* alongside version enabled storage engines such as SurrealKV.
*/
version(version: DateTime): InsertPromise<T, J>;
/**
* Compile this qurery into a BoundQuery
*/
compile(): BoundQuery<[
T
]>;
/**
* Stream the results of the query as they are received.
*
* @returns An async iterable of query frames.
*/
stream(): AsyncIterable<Frame<T, J>>;
protected dispatch(): Promise<MaybeJsonify<T, J>>;
}
interface ManagedLiveOptions {
what: LiveResource;
fields?: string[];
selection?: Selection$1;
cond?: Expr;
fetch?: string[];
session: Session;
}
declare class ManagedLivePromise<T> extends DispatchedPromise<LiveSubscription> {
#private;
constructor(connection: ConnectionController, options: ManagedLiveOptions);
/**
* Configure the live subscription to return only patches (diffs)
* instead of the full resource on each update.
*/
diff(): ManagedLivePromise<T>;
/**
* Configure the query to only select the specified field(s)
*/
fields(...fields: Field<T>[]): ManagedLivePromise<T>;
/**
* Configure the query to retrieve the value of the specified field
*/
value(field: Field<T>): ManagedLivePromise<T>;
/**
* Configure the query to fetch the record only if the condition is met.
*
* Expressions can be imported from the `surrealdb` package and combined
* to compose the desired condition.
*
* @see {@link https://github.com/surrealdb/surrealdb.js/blob/main/packages/sdk/src/utils/expr.ts}
*/
where(expr: ExprLike): ManagedLivePromise<T>;
/**
* Configure the query to fetch record link contents for the specified field(s)
*/
fetch(...fields: Field<T>[]): ManagedLivePromise<T>;
/**
* Compile this qurery into a BoundQuery
*/
compile(): BoundQuery<[
T
]>;
protected dispatch(): Promise<LiveSubscription>;
}
interface UnmanagedLiveOptions {
id: Uuid;
session: Session;
}
declare class UnmanagedLivePromise extends DispatchedPromise<LiveSubscription> {
#private;
constructor(connection: ConnectionController, options: UnmanagedLiveOptions);
protected dispatch(): Promise<LiveSubscription>;
}
interface QueryOptions {
query: BoundQuery;
transaction: Uuid | undefined;
session: Session;
json: boolean;
}
type Collect<T extends unknown[], J extends boolean> = T extends [
] ? unknown[] : {
[K in keyof T]: MaybeJsonify<T[K], J>;
};
type Responses<T extends unknown[], J extends boolean> = T extends [
] ? QueryResponse[] : {
[K in keyof T]: QueryResponse<MaybeJsonify<T[K], J>>;
};
declare class Query<R extends unknown[] = unknown[], J extends boolean = false> extends DispatchedPromise<Collect<R, J>> {
#private;
constructor(connection: ConnectionController, options: QueryOptions);
/**
* Retrieve the inner query that will be sent to the database.
*/
get inner(): BoundQuery;
/**
* Configure the query to return the result of each response as a
* JSON-compatible structure.
*
* This is useful when query results need to be serialized. Keep in mind
* that your responses will lose SurrealDB type information.
*/
json(): Query<R, true>;
/**
* Collect and return the results of all queries at once. If any of the queries fail, the promise
* will reject.
*
* You can optionally pass a list of query indexes to collect only the results of specific queries.
*
* This is the same as awaiting the query directly, but allows specifying which queries to collect.
*
* @example
* ```ts
* const [people] = await this.query("SELECT * FROM person").collect<[Person[]]>();
* ```
*
* @param queries The queries to collect. If no queries are provided, all queries will be collected.
* @returns A promise that resolves to the results of all queries at once.
*/
collect<T extends unknown[] = R>(...queries: number[]): Promise<Collect<T, J>>;
/**
* Stream the response frames of the query as they are received as an AsyncIterable.
*
* Each iteration yields a **value**, **error**, or **done** frame. The provided
* `isValue`, `isError`, and `isDone` methods can be used to check the type of frame.
* You can pass a query index to these functions to check if the frame is associated with a
* specific query.
*
* @example
* ```ts
* const stream = this.query("SELECT * FROM person").stream();
*
* for await (const frame of stream) {
* if (frame.isValue<Person>(0)) {
* // use frame.value
* }
* }
* ```
*
* @returns An async iterable of query frames.
*/
stream<T = unknown>(): AsyncIterable<Frame<T, J>>;
/**
* Collect and return the responses of all queries at once. Failed queries will be returned
* with `success: false` and the associated error, while successful queries will have
* `success: true` and their result.
*
* You can optionally pass a list of query indexes to collect only the results of specific responses.
*
* @example
* ```ts
* const [people] = await this.query("SELECT * FROM person").responses<[Person[]]>();
*
* people.success; // true
* people.result; // Person[]
* ```
*
* @param queries The queries to collect. If no queries are provided, all queries will be collected.
* @returns A promise that resolves to the responses of all queries at once.
*/
responses<T extends unknown[] = R>(...queries: number[]): Promise<Responses<T, J>>;
dispatch(): Promise<Collect<R, J>>;
}
interface RelateOptions {
from: AnyRecordId | AnyRecordId[];
what: Table | _RecordId;
to: AnyRecordId | AnyRecordId[];
unique?: boolean;
output?: Output;
timeout?: Duration;
version?: DateTime;
data?: unknown;
transaction: Uuid | undefined;
session: Session;
json: boolean;
}
declare class RelatePromise<T, J extends boolean = false> extends DispatchedPromise<MaybeJsonify<T, J>> {
#private;
constructor(connection: ConnectionController, options: RelateOptions);
/**
* Configure the query to return the result as a
* JSON-compatible structure.
*
* This is useful when query results need to be serialized. Keep in mind
* that your responses will lose SurrealDB type information.
*/
json(): RelatePromise<T, true>;
/**
* Configure the query to enforce a unique relationship
*/
unique(): RelatePromise<T, J>;
/**
* Configure the output of the query
*/
output(output: Output): RelatePromise<T, J>;
/**
* Configure the timeout of the query
*/
timeout(timeout: Duration): RelatePromise<T, J>;
/**
* Configure a custom version of the data being created. This is used
* alongside version enabled storage engines such as SurrealKV.
*/
version(version: DateTime): RelatePromise<T, J>;
/**
* Compile this qurery into a BoundQuery
*/
compile(): BoundQuery<[
T
]>;
/**
* Stream the results of the query as they are received.
*
* @returns An async iterable of query frames.
*/
stream(): AsyncIterable<Frame<T, J>>;
protected dispatch(): Promise<MaybeJsonify<T, J>>;
}
interface RunOptions {
name: string;
version: string | undefined;
args: unknown[];
transaction: Uuid | undefined;
session: Session;
json: boolean;
}
declare class RunPromise<T, J extends boolean = false> extends DispatchedPromise<MaybeJsonify<T, J>> {
#private;
constructor(connection: ConnectionController, options: RunOptions);
/**
* Configure the query to return the result as a
* JSON-compatible structure.
*
* This is useful when query results need to be serialized. Keep in mind
* that your responses will lose SurrealDB type information.
*/
json(): RunPromise<T, true>;
/**
* Compile this qurery into a BoundQuery
*/
compile(): BoundQuery<[
T
]>;
/**
* Stream the results of the query as they are received.
*
* @returns An async iterable of query frames.
*/
stream(): AsyncIterable<Frame<T, J>>;
protected dispatch(): Promise<MaybeJsonify<T, J>>;
}
interface SelectOptions {
what: AnyRecordId | _RecordIdRange | Table;
fields?: string[];
selection?: Selection$1;
start?: number;
limit?: number;
cond?: Expr;
fetch?: string[];
timeout?: Duration;
version?: DateTime;
transaction: Uuid | undefined;
session: Session;
json: boolean;
}
declare class SelectPromise<T, I, J extends boolean = false> extends DispatchedPromise<MaybeJsonify<T, J>> {
#private;
constructor(connection: ConnectionController, options: SelectOptions);
/**
* Configure the query to return the result as a
* JSON-compatible structure.
*
* This is useful when query results need to be serialized. Keep in mind
* that your responses will lose SurrealDB type information.
*/
json(): SelectPromise<T, I, true>;
/**
* Configure the query to only select the specified field(s)
*/
fields(...fields: Field<I>[]): SelectPromise<T, I, J>;
/**
* Configure the query to retrieve the value of the specified field
*/
value(field: Field<I>): SelectPromise<T, I, J>;
/**
* Configure the query to start at the specified index
*/
start(start: number): SelectPromise<T, I, J>;
/**
* Configure the query to limit the number of results
*/
limit(limit: number): SelectPromise<T, I, J>;
/**
* Configure the query to fetch only records that match the condition.
*
* Expressions can be imported from the `surrealdb` package and combined
* to compose the desired condition.
*
* @see {@link https://github.com/surrealdb/surrealdb.js/blob/main/packages/sdk/src/utils/expr.ts}
*/
where(expr: ExprLike): SelectPromise<T, I, J>;
/**
* Configure the query to fetch record link contents for the specified field(s)
*/
fetch(...fields: Field<I>[]): SelectPromise<T, I, J>;
/**
* Configure the timeout of the query
*/
timeout(timeout: Duration): SelectPromise<T, I, J>;
/**
* Configure a custom version of the data being created. This is used
* alongside version enabled storage engines such as SurrealKV.
*/
version(version: DateTime): SelectPromise<T, I, J>;
/**
* Compile this qurery in