var name = "@onyx.dev/onyx-database"; var version = "2.8.2"; /** * Supported operators for building query criteria. * * @example * ```ts * const criteria = { field: 'age', operator: 'GREATER_THAN', value: 21 }; * ``` */ type QueryCriteriaOperator = 'EQUAL' | 'NOT_EQUAL' | 'IN' | 'NOT_IN' | 'GREATER_THAN' | 'GREATER_THAN_EQUAL' | 'LESS_THAN' | 'LESS_THAN_EQUAL' | 'MATCHES' | 'NOT_MATCHES' | 'BETWEEN' | 'NOT_BETWEEN' | 'LIKE' | 'NOT_LIKE' | 'CONTAINS' | 'CONTAINS_IGNORE_CASE' | 'NOT_CONTAINS' | 'NOT_CONTAINS_IGNORE_CASE' | 'STARTS_WITH' | 'NOT_STARTS_WITH' | 'IS_NULL' | 'NOT_NULL' /** High-level lexical, semantic, or hybrid search using server-managed search integration. */ | 'SEARCH' /** Explicitly approximate, bounded admission from an ordinary secondary index. */ | 'CANDIDATES' /** Explicitly approximate, bounded lexical admission from a searchable table. */ | 'SEARCH_CANDIDATES' /** Explicitly approximate, bounded native-HNSW nearest-neighbor admission. */ | 'HNSW_CANDIDATES'; /** Value payload for native vector-managed full-text searches. */ interface FullTextQuery { queryText: string; minScore: number | null; } /** Search strategy used by the high-level {@link SearchOptions} API. */ type SearchMode = 'lexical' | 'semantic' | 'hybrid'; /** Whether the lexical portion of a search may match any term or must match every term. */ type SearchMatch = 'all' | 'any'; /** Options for natural-language lexical, semantic, or hybrid search. */ interface SearchOptions { /** Search strategy. Defaults to `hybrid`. */ mode?: SearchMode; /** Lexical term policy. Defaults to `any`. */ match?: SearchMatch; /** Optional normalized minimum score threshold from 0 through 1. */ minScore?: number | null; /** Maximum candidates considered. Defaults to 1,000; hybrid requires at least 2. */ maxCandidates?: number; } /** Lossless signed 64-bit value accepted by native semantic search helpers. */ type Int64WireInput = string | bigint | number; /** Lossless semantic routing signature used by native vector-managed search. */ interface SemanticVectorSignature { calibrationId: string; bucketId: number; cells: number[]; cellCounts: number[]; fingerprint: string[]; bands: string[]; boundaryConfidence: number; } /** Input accepted by {@link semanticVectorSignature}. */ interface SemanticVectorSignatureInput { calibrationId: Int64WireInput; bucketId: number; cells: readonly number[]; cellCounts: readonly number[]; fingerprint: readonly Int64WireInput[]; bands?: readonly Int64WireInput[]; boundaryConfidence?: number; } /** Native lexical, semantic, or hybrid vector-managed search value. */ interface VectorSearchQuery { text: string | null; semantic: SemanticVectorSignature | null; minScore: number | null; nearbyBucketRadius: number; maxCandidates: number; requireAllTerms: boolean; } /** Input accepted by {@link vectorSearchQuery}. */ interface VectorSearchQueryInput { text?: string | null; semantic?: SemanticVectorSignatureInput | SemanticVectorSignature | null; minScore?: number | null; nearbyBucketRadius?: number; maxCandidates?: number; requireAllTerms?: boolean; } /** Lossless bounded native-HNSW candidate request. */ interface HnswSearchQuery { calibrationId: string; vector: number[]; maxCandidates: number; efSearch: number; minScore: number | null; formatVersion: 1; } /** Input accepted by {@link hnswSearchQuery}. */ interface HnswSearchQueryInput { calibrationId: Int64WireInput; vector: readonly number[]; maxCandidates?: number; efSearch?: number; minScore?: number | null; formatVersion?: number; } /** Bounded ordinary-index candidate route. */ interface ApproximateIndexCandidateQuery { values: unknown[]; maxCandidates: number; } /** Options for the text convenience overload of `approximateSearch`. */ interface ApproximateSearchOptions { minScore?: number | null; maxCandidates?: number; requireAllTerms?: boolean; } /** Logical operator used to join conditions in a query. */ type LogicalOperator = 'AND' | 'OR'; /** * Sorting instruction for query results. * * @property field - Field name to order by. * @property order - Sort direction. * @example * ```ts * const sort: Sort = { field: 'name', order: 'ASC' }; * ``` */ interface Sort { field: string; order: 'ASC' | 'DESC'; } /** Actions emitted by real-time data streams. */ type StreamAction = 'CREATE' | 'UPDATE' | 'DELETE' | 'QUERY_RESPONSE' | 'KEEP_ALIVE'; /** * Basic document representation used by the SDK. * * @example * ```ts * const doc: OnyxDocument = { documentId: '1', content: 'hello' }; * ``` */ interface OnyxDocument { /** Unique document identifier. */ documentId?: string; /** Path within the Onyx database. */ path?: string; /** Creation timestamp. */ created?: Date; /** Last update timestamp. */ updated?: Date; /** MIME type of the content. */ mimeType?: string; /** Raw document content. */ content?: string; } /** Minimal fetch typing to avoid DOM lib dependency */ interface FetchResponse { /** Whether the request succeeded (status in the range 200–299). */ ok: boolean; /** HTTP status code. */ status: number; /** HTTP status text. */ statusText: string; /** Response headers getter. */ headers: { get(name: string): string | null; }; /** Reads the body as text. */ text(): Promise; /** Reads the body as bytes when the response uses a binary wire format. */ arrayBuffer?(): Promise; /** Raw body for streams; left as unknown to avoid DOM typings */ body?: unknown; } /** * Fetch implementation signature used by the SDK. * * @param url - Resource URL. * @param init - Optional init parameters. * @example * ```ts * const res = await fetchImpl('https://api.onyx.dev'); * ``` */ type FetchImpl = (url: string, init?: { method?: string; headers?: Record; body?: string | Uint8Array; }) => Promise; /** * Represents a single field comparison in a query. * * @property field - Field name to evaluate. * @property operator - Comparison operator. * @property value - Value to compare against. * @example * ```ts * const criteria: QueryCriteria = { field: 'age', operator: 'GREATER_THAN', value: 18 }; * ``` */ interface QueryCriteria { field: string; operator: QueryCriteriaOperator; value?: unknown; } /** * Recursive condition structure used to express complex WHERE clauses. * * @example * ```ts * const condition: QueryCondition = { * conditionType: 'CompoundCondition', * operator: 'AND', * conditions: [ * { conditionType: 'SingleCondition', criteria: { field: 'age', operator: 'GREATER_THAN', value: 18 } }, * { conditionType: 'SingleCondition', criteria: { field: 'status', operator: 'EQUAL', value: 'ACTIVE' } } * ] * }; * ``` */ type QueryCondition = { conditionType: 'SingleCondition'; criteria: QueryCriteria; } | { conditionType: 'CompoundCondition'; operator: LogicalOperator; conditions: QueryCondition[]; }; /** * Wire format for select queries sent to the server. * * @example * ```ts * const query: SelectQuery = { * type: 'SelectQuery', * fields: ['id', 'name'], * limit: 10 * }; * ``` */ interface SelectQuery { type: 'SelectQuery'; table?: string | null; fields?: string[] | null; conditions?: QueryCondition | null; sort?: Sort[] | null; limit?: number | null; distinct?: boolean | null; groupBy?: string[] | null; partition?: string | null; resolvers?: string[] | null; } /** * Wire format for update queries sent to the server. * * @example * ```ts * const update: UpdateQuery = { * type: 'UpdateQuery', * updates: { name: 'New Name' } * }; * ``` */ interface UpdateQuery { type: 'UpdateQuery'; conditions?: QueryCondition | null; updates: Record; sort?: Sort[] | null; limit?: number | null; partition?: string | null; } /** * A single page of query results. * * @example * ```ts * const page: QueryPage = { records: users, nextPage: token }; * ``` */ interface QueryPage { /** Records in the current page. */ records: T[]; /** Token for the next page or null if none. */ nextPage?: string | null; } /** * Array-like container for paginated query results. Provides helper methods * to traverse and aggregate records across pages. * * @example * ```ts * const results = new QueryResults(users, nextToken, fetchNext); * const firstUser = results.first(); * ``` */ type QueryResultsPromise = Promise> & { [K in keyof QueryResults as QueryResults[K] extends (...args: any[]) => any ? K : never]: QueryResults[K] extends (...args: infer P) => infer R ? (...args: P) => Promise> : never; }; declare class QueryResults extends Array { /** Token for the next page of results or null. */ nextPage: string | null; private readonly fetcher?; /** * @param records - Records in the current page. * @param nextPage - Token representing the next page. * @param fetcher - Function used to fetch the next page when needed. * @example * ```ts * const results = new QueryResults(users, token, t => fetchMore(t)); * ``` */ constructor(records: Iterable | ArrayLike | T | null | undefined, nextPage: string | null, fetcher?: (token: string) => Promise>); /** * Returns the first record in the result set. * @throws Error if the result set is empty. * @example * ```ts * const user = results.first(); * ``` */ first(): T; /** * Returns the first record or `null` if the result set is empty. * @example * ```ts * const user = results.firstOrNull(); * ``` */ firstOrNull(): T | null; /** * Checks whether the current page has no records. * @example * ```ts * if (results.isEmpty()) console.log('no data'); * ``` */ isEmpty(): boolean; /** * Number of records on the current page. * @example * ```ts * console.log(results.size()); * ``` */ size(): number; /** * Iterates over each record on the current page only. * @param action - Function to invoke for each record. * @param thisArg - Optional `this` binding for the callback. * @example * ```ts * results.forEachOnPage(u => console.log(u.id)); * ``` */ forEachOnPage(action: (item: T, index: number, array: QueryResults) => void, thisArg?: unknown): void; /** * Iterates over every record across all pages sequentially. * @param action - Function executed for each record. Returning `false` * stops iteration early. * @param thisArg - Optional `this` binding for the callback. * @example * ```ts * await results.forEach(u => { * console.log(u.id); * }); * ``` */ forEach(action: (item: T, index: number, array: T[]) => void, thisArg?: unknown): Promise; /** * Iterates over every record across all pages sequentially. * @param action - Function executed for each record. Returning `false` * stops iteration early. * @example * ```ts * await results.forEachAll(u => { * if (u.disabled) return false; * }); * ``` */ forEachAll(action: (item: T) => boolean | void | Promise): Promise; /** * Iterates page by page across the result set. * @param action - Function invoked with each page of records. Returning * `false` stops iteration. * @example * ```ts * await results.forEachPage(page => { * console.log(page.length); * }); * ``` */ forEachPage(action: (records: T[]) => boolean | void | Promise): Promise; /** * Collects all records from every page into a single array. * @returns All records. * @example * ```ts * const allUsers = await results.getAllRecords(); * ``` */ getAllRecords(): Promise; /** * Filters all records using the provided predicate. * @param predicate - Function used to test each record. * @example * ```ts * const enabled = await results.filterAll(u => u.enabled); * ``` */ filterAll(predicate: (record: T) => boolean): Promise; /** * Maps all records using the provided transform. * @param transform - Mapping function. * @example * ```ts * const names = await results.mapAll(u => u.name); * ``` */ mapAll(transform: (record: T) => R): Promise; /** * Extracts values for a field across all records. * @param field - Name of the field to pluck. * @example * ```ts * const ids = await results.values('id'); * ``` */ values(field: K): Promise>; /** * Maximum value produced by the selector across all records. * @param selector - Function extracting a numeric value. * @example * ```ts * const maxAge = await results.maxOfDouble(u => u.age); * ``` */ maxOfDouble(selector: (record: T) => number): Promise; /** * Minimum value produced by the selector across all records. * @param selector - Function extracting a numeric value. * @example * ```ts * const minAge = await results.minOfDouble(u => u.age); * ``` */ minOfDouble(selector: (record: T) => number): Promise; /** * Sum of values produced by the selector across all records. * @param selector - Function extracting a numeric value. * @example * ```ts * const total = await results.sumOfDouble(u => u.score); * ``` */ sumOfDouble(selector: (record: T) => number): Promise; /** * Maximum float value from the selector. * @param selector - Function extracting a numeric value. */ maxOfFloat(selector: (record: T) => number): Promise; /** * Minimum float value from the selector. * @param selector - Function extracting a numeric value. */ minOfFloat(selector: (record: T) => number): Promise; /** * Sum of float values from the selector. * @param selector - Function extracting a numeric value. */ sumOfFloat(selector: (record: T) => number): Promise; /** * Maximum integer value from the selector. * @param selector - Function extracting a numeric value. */ maxOfInt(selector: (record: T) => number): Promise; /** * Minimum integer value from the selector. * @param selector - Function extracting a numeric value. */ minOfInt(selector: (record: T) => number): Promise; /** * Sum of integer values from the selector. * @param selector - Function extracting a numeric value. */ sumOfInt(selector: (record: T) => number): Promise; /** * Maximum long value from the selector. * @param selector - Function extracting a numeric value. */ maxOfLong(selector: (record: T) => number): Promise; /** * Minimum long value from the selector. * @param selector - Function extracting a numeric value. */ minOfLong(selector: (record: T) => number): Promise; /** * Sum of long values from the selector. * @param selector - Function extracting a numeric value. */ sumOfLong(selector: (record: T) => number): Promise; /** * Sum of bigint values from the selector. * @param selector - Function extracting a bigint value. * @example * ```ts * const total = await results.sumOfBigInt(u => u.balance); * ``` */ sumOfBigInt(selector: (record: T) => bigint): Promise; /** * Executes an action for each page in parallel. * @param action - Function executed for each record concurrently. * @example * ```ts * await results.forEachPageParallel(async u => sendEmail(u)); * ``` */ forEachPageParallel(action: (item: T) => void | Promise): Promise; } interface TableFormatOptions { /** * Whether to render a header row. Defaults to `true`. */ headers?: boolean; /** * Maximum width for each rendered column. Defaults to `80`. */ maxColumnWidth?: number; /** * When true, nested objects expand into additional dot-notated columns. * Defaults to `false`. */ flattenNestedObjects?: boolean; /** * Separator used when flattening nested object keys. Defaults to `.`. */ nestedSeparator?: string; /** * Display value used for `null` and `undefined`. Defaults to an empty string. */ nullValue?: string; } interface TreeFormatOptions { /** * Label used for the root node when `includeRoot` is true. Defaults to `results`. */ rootLabel?: string; /** * Field whose value should label each record node. */ keyField?: string; /** * Whether to include a root node. Defaults to `true`. */ includeRoot?: boolean; /** * Maximum nesting depth to expand before rendering remaining values inline. * Defaults to `Infinity`. */ maxDepth?: number; /** * Display value used for `null` and `undefined`. Defaults to an empty string. */ nullValue?: string; } interface CsvFormatOptions { /** * Whether to render a header row. Defaults to `true`. */ headers?: boolean; /** * Field delimiter. Defaults to `,`. */ delimiter?: string; /** * Quote character. Defaults to `"`. */ quote?: string; /** * Escape character used to escape embedded quotes. Defaults to `"`. */ escape?: string; /** * Line ending. Defaults to `\n`. */ newline?: '\n' | '\r\n'; /** * When true, nested objects expand into additional dot-notated columns. * Defaults to `true`. */ flattenNestedObjects?: boolean; /** * Separator used when flattening nested object keys. Defaults to `.`. */ nestedSeparator?: string; /** * Display value used for `null` and `undefined`. Defaults to an empty string. */ nullValue?: string; } interface JsonFormatOptions { /** * Whether to pretty-print the JSON output. Defaults to `true`. */ pretty?: boolean; /** * Indentation size used when `pretty` is true. Defaults to `2`. */ indent?: number; } /** A condition builder, raw criterion, or fully materialized recursive condition. */ type ConditionInput = IConditionBuilder | QueryCriteria | QueryCondition; /** * Builder used to compose query conditions. */ interface IConditionBuilder { /** * Combines the current condition with another using `AND`. * @param condition - Additional condition or builder. * @example * ```ts * cb.and({ field: 'age', operator: 'GREATER_THAN', value: 18 }); * ``` */ and(condition: ConditionInput): IConditionBuilder; /** * Combines the current condition with another using `OR`. * @param condition - Additional condition or builder. * @example * ```ts * cb.or({ field: 'status', operator: 'EQUAL', value: 'ACTIVE' }); * ``` */ or(condition: ConditionInput): IConditionBuilder; /** * Materializes the composed condition into a `QueryCondition` object. * @example * ```ts * const cond = cb.toCondition(); * ``` */ toCondition(): QueryCondition; } /** * Fluent query builder for constructing and executing select/update/delete operations. */ interface IQueryBuilder { /** * Sets the table to query. * @example * ```ts * const users = await db.from('User').list(); * ``` */ from(table: string): IQueryBuilder; /** * Selects a subset of fields to return. * @example * ```ts * const emails = await db.from('User').select('email').list(); * ``` */ select(...fields: Array): IQueryBuilder; /** * Resolves related values by name. * @example * ```ts * const users = await db * .from('User') * .resolve('profile', 'roles') * .list(); * ``` */ resolve(...values: Array): IQueryBuilder; /** * Adds a legacy native vector-managed full-text search predicate. * @example * ```ts * const results = await db.from('User').search('hello world', 4.4).list(); * ``` * @param queryText - Text to match against `__full_text__`. * @param minScore - Optional minimum score; serializes as `null` when omitted. */ search(queryText: string, minScore?: number | null): IQueryBuilder; /** Runs high-level lexical, semantic, or hybrid search; an empty object defaults to hybrid. */ search(queryText: string, options: SearchOptions): IQueryBuilder; /** Adds a typed native lexical, semantic, or hybrid search predicate. */ search(searchQuery: VectorSearchQueryInput): IQueryBuilder; /** * Seeds a bounded lexical candidate request. This must be the sole root * criterion and partitioned tables require one concrete partition. */ approximateSearch(searchQuery: VectorSearchQueryInput): IQueryBuilder; /** Convenience overload for a text-only bounded lexical candidate request. */ approximateSearch(queryText: string, options?: ApproximateSearchOptions): IQueryBuilder; /** Seeds a bounded native-HNSW candidate request as the sole root criterion. */ hnswCandidates(searchQuery: HnswSearchQueryInput): IQueryBuilder; /** * Compatibility shortcut for bounded ordinary-index admission. * @deprecated Prefer `where(approximateCandidates(...))`, matching every * other condition operator. Additional non-negated `AND` predicates filter * the admitted set. */ approximateCandidates(attribute: string, valueOrValues: unknown | readonly unknown[], maxCandidates?: number): IQueryBuilder; /** * Adds a filter condition. * @example * ```ts * const active = await db.from('User').where(eq('status', 'active')).list(); * ``` */ where(condition: ConditionInput): IQueryBuilder; /** * Adds an additional filter with `AND`. * @example * ```ts * qb.where(eq('status', 'active')).and(eq('role', 'admin')); * ``` */ and(condition: ConditionInput): IQueryBuilder; /** * Adds an additional filter with `OR`. * @example * ```ts * qb.where(eq('status', 'active')).or(eq('status', 'invited')); * ``` */ or(condition: ConditionInput): IQueryBuilder; /** * Orders results by the provided fields. * @example * ```ts * const users = await db.from('User').orderBy(asc('createdAt')).list(); * ``` */ orderBy(...sorts: Sort[]): IQueryBuilder; /** * Groups results by the provided fields. * @example * ```ts * const stats = await db.from('User').groupBy('status').list(); * ``` */ groupBy(...fields: string[]): IQueryBuilder; /** * Ensures only distinct records are returned. * @example * ```ts * const roles = await db.from('User').select('role').distinct().list(); * ``` */ distinct(): IQueryBuilder; /** * Limits the number of records returned. * @example * ```ts * const few = await db.from('User').limit(5).list(); * ``` */ limit(n: number): IQueryBuilder; /** * Restricts the query to a specific partition. * @example * ```ts * const tenantUsers = await db.from('User').inPartition('tenantA').list(); * ``` */ inPartition(partition: string): IQueryBuilder; /** Sets the page size for subsequent `list` or `page` calls. */ pageSize(n: number): IQueryBuilder; /** * Continues a paged query using a next-page token. * @example * ```ts * const page2 = await db.from('User').nextPage(token).list(); * ``` */ nextPage(token: string): IQueryBuilder; /** * Counts matching records. * @example * ```ts * const total = await db.from('User').count(); * ``` */ count(): Promise; /** * Lists records with optional pagination. * @example * ```ts * const users = await db.from('User').list({ pageSize: 10 }); * ``` */ list(options?: { pageSize?: number; nextPage?: string; }): QueryResultsPromise; /** * Retrieves the first record or null. * @example * ```ts * const user = await db.from('User').firstOrNull(); * ``` */ firstOrNull(): Promise; /** * Retrieves exactly one record or null. * @example * ```ts * const user = await db * .from('User') * .where(eq('email', 'a@b.com')) * .one(); * ``` */ one(): Promise; /** * Retrieves a single page of records with optional next token. * @example * ```ts * const { records, nextPage } = await db.from('User').page({ pageSize: 25 }); * ``` */ page(options?: { pageSize?: number; nextPage?: string; }): Promise<{ records: T[]; nextPage?: string | null; }>; /** * Executes the query and renders all matching results as a table string. * @example * ```ts * const output = await db.from('User').select('id', 'email').table(); * console.log(output); * ``` */ table(options?: TableFormatOptions): Promise; /** * Executes the query and renders all matching results as a tree string. * @example * ```ts * const output = await db.from('User').select('id', 'email').tree(); * console.log(output); * ``` */ tree(options?: TreeFormatOptions): Promise; /** * Executes the query and renders all matching results as CSV. * @example * ```ts * const output = await db.from('User').select('id', 'email').csv(); * console.log(output); * ``` */ csv(options?: CsvFormatOptions): Promise; /** * Executes the query and renders all matching results as JSON. * @example * ```ts * const output = await db.from('User').select('id', 'email').json(); * console.log(output); * ``` */ json(options?: JsonFormatOptions): Promise; /** * Sets field updates for an update query. * @example * ```ts * await db * .from('User') * .where(eq('id', 'u1')) * .setUpdates({ status: 'active' }) * .update(); * ``` */ setUpdates(updates: Partial): IQueryBuilder; /** * Executes an update operation. * @example * ```ts * await db.from('User').where(eq('id', 'u1')).setUpdates({ status: 'active' }).update(); * ``` */ update(): Promise; /** * Executes a delete operation. * Returns the number of deleted records. * @example * ```ts * await db.from('User').where(eq('status', 'inactive')).delete(); * ``` */ delete(): Promise; /** * Registers a listener for added items on a stream. * @example * ```ts * db.from('User').onItemAdded(u => console.log('added', u)); * ``` */ onItemAdded(listener: (entity: T) => void): IQueryBuilder; /** * Registers a listener for updated items on a stream. * @example * ```ts * db.from('User').onItemUpdated(u => console.log('updated', u)); * ``` */ onItemUpdated(listener: (entity: T) => void): IQueryBuilder; /** * Registers a listener for deleted items on a stream. * @example * ```ts * db.from('User').onItemDeleted(u => console.log('deleted', u)); * ``` */ onItemDeleted(listener: (entity: T) => void): IQueryBuilder; /** * Registers a listener for any stream item with its action. * @example * ```ts * db.from('User').onItem((u, action) => console.log(action, u)); * ``` */ onItem(listener: (entity: T | null, action: StreamAction) => void): IQueryBuilder; /** * Starts a stream including query results. * @example * ```ts * const { cancel } = await db.from('User').stream(); * ``` */ stream(includeQueryResults?: boolean, keepAlive?: boolean): Promise<{ cancel: () => void; }>; /** * Starts a stream emitting only events. * @example * ```ts * const { cancel } = await db.from('User').streamEventsOnly(); * ``` */ streamEventsOnly(keepAlive?: boolean): Promise<{ cancel: () => void; }>; /** * Starts a stream that returns events alongside query results. * @example * ```ts * const { cancel } = await db.from('User').streamWithQueryResults(); * ``` */ streamWithQueryResults(keepAlive?: boolean): Promise<{ cancel: () => void; }>; } /** Builder for save operations. */ interface ISaveBuilder { /** * Cascades specified relationships when saving. * @example * ```ts * await db.save('User').cascade('role').one(user); * ``` */ cascade(...relationships: Array): ISaveBuilder; /** * Persists a single entity. * @example * ```ts * await db.save('User').one({ id: 'u1' }); * ``` */ one(entity: Partial): Promise; /** * Persists multiple entities. * @example * ```ts * await db.save('User').many([{ id: 'u1' }, { id: 'u2' }]); * ``` */ many(entities: Array>): Promise; } /** Builder for cascading save/delete operations across multiple tables. */ interface ICascadeBuilder> { /** * Specifies relationships to cascade through. * @example * ```ts * const builder = db.cascade('permissions'); * ``` */ cascade(...relationships: Array): ICascadeBuilder; /** * Saves one or many entities for a given table. * @example * ```ts * await db.cascade('permissions').save('Role', role); * ``` */ save(table: Table, entityOrEntities: Partial | Array>): Promise; /** * Deletes an entity by primary key. * @example * ```ts * await db.cascade('permissions').delete('Role', 'admin'); * ``` */ delete
(table: Table, primaryKey: string): Promise; } /** Builder for describing cascade relationship metadata. */ interface ICascadeRelationshipBuilder { /** * Names the relationship graph. * @example * ```ts * builder.graph('permissions'); * ``` */ graph(name: string): ICascadeRelationshipBuilder; /** * Sets the graph type. * @example * ```ts * builder.graphType('Permission'); * ``` */ graphType(type: string): ICascadeRelationshipBuilder; /** * Field on the target entity. * @example * ```ts * builder.targetField('roleId'); * ``` */ targetField(field: string): ICascadeRelationshipBuilder; /** * Field on the source entity. * @example * ```ts * const rel = builder.sourceField('id'); * ``` */ sourceField(field: string): string; } /** Result envelope returned by high-level database-wide (`table = "ALL"`) search. */ interface FullTextSearchResult { /** Unique identifier of the matched entity. */ id: unknown; /** Table/entity type containing the match. */ entityType: string; /** Matched entity payload. */ entity: Record; /** Normalized relevance score in `[0, 1]`, or `null` when unavailable. */ score: number | null; } interface RetryOptions { /** * Enable or disable HTTP retries for idempotent GET requests. Defaults to `true`. */ enabled?: boolean; /** * Maximum number of retry attempts after the initial GET request. Defaults to 3. */ maxRetries?: number; /** * Initial backoff delay in milliseconds. Defaults to 300ms and grows with Fibonacci backoff. */ initialDelayMs?: number; } /** Wire format used by entity CRUD and query requests. */ type WireFormat = 'json' | 'msgpack'; interface OnyxConfig { baseUrl?: string; /** * Base URL for AI endpoints. Defaults to https://ai.onyx.dev. */ aiBaseUrl?: string; databaseId?: string; apiKey?: string; apiSecret?: string; fetch?: FetchImpl; /** * Wire format for entity CRUD and query routes. Defaults to `msgpack`. * Documents, schemas, and AI calls remain JSON. Query streams use the * selected format and can accept a JSON-lines fallback. */ wireFormat?: WireFormat; /** * Default AI model when using shorthand chat calls (`db.chat('...')`). Defaults to `onyx`. */ defaultModel?: string; /** * Default partition for queries, `findById`, and deletes when removing by * primary key. Saves rely on the entity's partition field instead. */ partition?: string; /** * When true, log HTTP requests and bodies to the console. */ requestLoggingEnabled?: boolean; /** * When true, log HTTP responses and bodies to the console. */ responseLoggingEnabled?: boolean; /** * Milliseconds to cache resolved credentials; defaults to 5 minutes. */ ttl?: number; /** * Retry configuration for idempotent GET requests. */ retry?: RetryOptions; } interface AiRequestOptions { /** * Optional database scope for AI calls. Defaults to the configured databaseId. */ databaseId?: string; } type AiChatRole = 'system' | 'user' | 'assistant' | 'tool'; interface AiToolCallFunction { name: string; arguments: string; } interface AiToolCall { id?: string | null; type?: string | null; function: AiToolCallFunction; } interface AiChatMessage { role: AiChatRole; content?: string | null; tool_calls?: AiToolCall[] | null; tool_call_id?: string | null; name?: string | null; } interface AiToolFunction { name: string; description?: string | null; parameters?: Record | null; } interface AiTool { type: string; function: AiToolFunction; } type AiToolChoice = 'none' | 'auto' | { type: 'function'; function: { name: string; }; } | null; interface AiChatCompletionRequest { model: string; messages: AiChatMessage[]; stream?: boolean; temperature?: number | null; top_p?: number | null; max_tokens?: number | null; metadata?: Record; tools?: AiTool[]; tool_choice?: AiToolChoice; user?: string | null; } interface AiChatCompletionUsage { prompt_tokens?: number | null; completion_tokens?: number | null; total_tokens?: number | null; } interface AiChatCompletionChoice { index: number; message: AiChatMessage; finish_reason?: string | null; } interface AiChatCompletionResponse { id: string; object: string; created: number; model: string; choices: AiChatCompletionChoice[]; usage?: AiChatCompletionUsage; } interface AiChatCompletionChunkDelta { role?: AiChatRole | null; content?: string | null; tool_calls?: AiToolCall[] | null; tool_call_id?: string | null; name?: string | null; } interface AiChatCompletionChunkChoice { index: number; delta: AiChatCompletionChunkDelta; finish_reason?: string | null; } interface AiChatCompletionChunk { id: string; object: string; created: number; model?: string | null; choices: AiChatCompletionChunkChoice[]; } interface AiChatCompletionStream extends AsyncIterable { cancel(): void; } interface AiChatOptions extends AiRequestOptions { /** * Model to use for the shorthand `db.chat()` call. Defaults to config.defaultModel or `onyx`. */ model?: string; /** * Role for the constructed message. Defaults to `user`. */ role?: AiChatRole; /** * Temperature for the completion. Omit to use the service default. */ temperature?: number | null; /** * Enable SSE streaming. Defaults to `false`. */ stream?: boolean; /** * When true, return the raw completion response instead of the first message content. */ raw?: boolean; } interface AiChatClient { create(request: AiChatCompletionRequest & { stream?: false; }, options?: AiRequestOptions): Promise; create(request: AiChatCompletionRequest & { stream: true; }, options?: AiRequestOptions): Promise; create(request: AiChatCompletionRequest, options?: AiRequestOptions): Promise; } interface AiScriptApprovalRequest { script: string; } interface AiScriptApprovalResponse { normalizedScript: string; expiresAtIso: string; requiresApproval: boolean; findings?: string; } interface AiModelsResponse { object: string; data: AiModel[]; } interface AiModel { id: string; object: string; created: number; owned_by: string; } interface AiErrorResponse { error?: string | { message?: string; [key: string]: unknown; } | null; } type PublishedModelPredictionInput = Record; type PublishedModelPredictionInputs = PublishedModelPredictionInput | PublishedModelPredictionInput[]; interface PublishedModelRawPredictionRequest { inputs: PublishedModelPredictionInputs; } interface PublishedModelScriptPredictionRequest { scriptId: string; scriptParameters?: Record; } interface PublishedModelPredictionResponse { publishedModelId: string; modelId: string; inputCount: number; inputs: PublishedModelPredictionInput[]; predictions: PublishedModelPredictionInput[]; rawPredictions: number[][]; scriptId?: string | null; scriptParameters: Record; } interface AiClient { /** * Run a chat completion. Accepts shorthand strings or full requests. * * @example * ```ts * const quick = await db.ai.chat('Summarize last week.'); // returns first message content * const completion = await db.ai.chat( * { model: 'onyx-chat', messages: [{ role: 'user', content: 'Summarize last week.' }] }, * { databaseId: 'db1', raw: true }, // returns full response * ); * ``` */ chat(content: string, options?: AiChatOptions & { stream?: false; raw?: false | undefined; }): Promise; chat(content: string, options: AiChatOptions & { stream: true; }): Promise; chat(content: string, options: AiChatOptions & { raw: true; }): Promise; chat(request: AiChatCompletionRequest & { stream?: false; }, options?: AiRequestOptions): Promise; chat(request: AiChatCompletionRequest & { stream: true; }, options?: AiRequestOptions): Promise; chat(request: AiChatCompletionRequest, options?: AiRequestOptions): Promise; /** * Access the chat client for more control over streaming and cancellation. */ chatClient(): AiChatClient; /** * List available AI models. * * @example * ```ts * const models = await db.ai.getModels(); * ``` */ getModels(): Promise; /** * Retrieve a single AI model by ID. * * @example * ```ts * const model = await db.ai.getModel('onyx-chat'); * ``` */ getModel(modelId: string): Promise; /** * Request mutation approval for a script. * * @example * ```ts * const approval = await db.ai.requestScriptApproval({ * script: "db.save({ id: 'u1', email: 'a@b.com' })" * }); * ``` */ requestScriptApproval(input: AiScriptApprovalRequest): Promise; } interface IOnyxDatabase> { /** * AI helpers (chat, models, script approvals) grouped under `db.ai`. * * @example * ```ts * const completion = await db.ai.chat({ * model: 'onyx-chat', * messages: [{ role: 'user', content: 'Summarize last week.' }], * }); * ``` */ ai: AiClient; /** * Access OpenAI-compatible chat completions via `db.chat('...')` or `db.chat().create(...)`. * * @example * ```ts * const completion = await db.chat('Summarize last week.'); // returns first message content * ``` * * @example * ```ts * const chat = db.chat(); * const completion = await chat.create({ * model: 'onyx-chat', * messages: [{ role: 'user', content: 'Summarize last week.' }], * }); * ``` * * @example * ```ts * const stream = await db * .chat() * .create({ * model: 'onyx-chat', * stream: true, * messages: [{ role: 'user', content: 'Draft an onboarding checklist.' }], * }); * for await (const chunk of stream) { * process.stdout.write(chunk.choices[0]?.delta?.content ?? ''); * } * ``` */ chat(content: string, options?: AiChatOptions & { stream?: false; raw?: false | undefined; }): Promise; chat(content: string, options: AiChatOptions & { stream: true; }): Promise; chat(content: string, options: AiChatOptions & { raw: true; }): Promise; chat(): AiChatClient; /** * List available AI models. * * @deprecated Prefer `db.ai.getModels()`. * * @example * ```ts * const models = await db.getModels(); * ``` */ getModels(): Promise; /** * Retrieve a single AI model by ID. * * @deprecated Prefer `db.ai.getModel(...)`. * * @example * ```ts * const model = await db.getModel('onyx-chat'); * ``` */ getModel(modelId: string): Promise; /** * Request mutation approval for a script. * * @deprecated Prefer `db.ai.requestScriptApproval(...)`. * * @example * ```ts * const approval = await db.requestScriptApproval({ * script: "db.save({ id: 'u1', email: 'a@b.com' })" * }); * ``` */ requestScriptApproval(input: AiScriptApprovalRequest): Promise; /** * Predict with a published model using raw input data. * * @example * ```ts * const prediction = await db.predict('churn-model', { * age: 42, * country: 'US' * }); * ``` */ predict(publishedModelId: string, inputs: PublishedModelPredictionInputs): Promise; /** * Predict with a published model using rows returned from a saved script. * * @example * ```ts * const prediction = await db.predictFromScript( * 'churn-model', * 'score-active-users', * { segment: 'enterprise' } * ); * ``` */ predictFromScript(publishedModelId: string, scriptId: string, scriptParameters?: Record): Promise; /** * Begin a query against a table. * * @example * ```ts * const maybeUser = await db * .from('User') * .where(eq('email', 'a@b.com')) * .firstOrNull(); // or .one() * ``` * * @example * ```ts * const users = await db * .select('id', 'email') * .from('User') * .list(); * ``` * * @param table Table name to query. */ from
(table: Table): IQueryBuilder; /** * Select specific fields for a query. * * @example * ```ts * const users = await db * .select('id', 'name') * .from('User') * .list(); * ``` * * @param fields Field names to project; omit to select all. */ select(...fields: string[]): IQueryBuilder>; /** * Run legacy native vector-managed full-text search across all searchable tables. * * @example * ```ts * const results = await db.search('hello world', 4.4).list(); * ``` * * @param queryText Text to match against `__full_text__`. * @param minScore Optional minimum score; serialized as `null` when omitted. */ search(queryText: string, minScore?: number | null): IQueryBuilder>; /** Run high-level lexical, semantic, or hybrid search; an empty object defaults to hybrid. */ search(queryText: string, options: SearchOptions): IQueryBuilder; /** * Include related records in the next save or delete. * * @example * ```ts * // Save a role and its permissions * await db * .cascade('permissions:Permission(roleId, id)') * .save('Role', role); * * // Delete a role and all of its permissions via resolver * await db * .cascade('permissions') * .delete('Role', 'admin'); * ``` * * @param relationships Cascade relationship strings using * `graph:Type(targetField, sourceField)` syntax when saving. * When deleting, pass resolver attribute names only. */ cascade(...relationships: Array): ICascadeBuilder; /** * Build cascade relationship strings programmatically. * * @example * ```ts * const rel = db * .cascadeBuilder() * .graph('permissions') * .graphType('Permission') * .targetField('roleId') * .sourceField('id'); * await db.cascade(rel).save('Role', role); * ``` * * @returns Builder that emits strings like * `graphName:TypeName(targetField, sourceField)`. */ cascadeBuilder(): ICascadeRelationshipBuilder; /** * Start a save builder for inserting or updating entities. * * @example * ```ts * await db * .save('User') * .cascade('role:Role(userId, id)') * .one({ * id: 'u1', * email: 'a@b.com', * role: { id: 'admin', userId: 'u1' } * }); * ``` * * @param table Table to save into. */ save
(table: Table): ISaveBuilder; /** * Save one or many entities immediately. * * @example * ```ts * await db.save( * 'Role', * [{ id: 'admin', permissions: [{ id: 'perm1', roleId: 'admin' }] }], * { relationships: ['permissions:Permission(roleId, id)'] } * ); * ``` * * The `relationships` option accepts cascade strings in the form * `graphName:TypeName(targetField, sourceField)` describing how child records relate to the * parent. Use {@link cascadeBuilder} to construct them safely. * * @param table Table to save into. * @param entityOrEntities Object or array of objects to persist. * @param options Optional settings for the save operation. * @param options.relationships Cascade relationships to include. */ save
(table: Table, entityOrEntities: Partial | Array>, options?: { relationships?: string[]; }): Promise; /** * Save many entities in configurable batches. * * @example * ```ts * await db.batchSave('User', users, 500); * ``` * * @param table Table to save into. * @param entities Array of entities to persist. * @param batchSize Number of entities per batch; defaults to 1000. */ batchSave
(table: Table, entities: Array>, batchSize?: number, options?: { relationships?: string[]; }): Promise; /** * Retrieve an entity by its primary key. * * @example * ```ts * const user = await db.findById('User', 'user_1', { * partition: 'tenantA', * resolvers: ['profile'] * }); * ``` * * @param table Table to search. * @param primaryKey Primary key value. * @param options Optional partition and resolver settings. */ findById
(table: Table, primaryKey: string, options?: { partition?: string; resolvers?: string[]; }): Promise; /** * Delete an entity by primary key. * * @example * ```ts * const deleted = await db.delete('Role', 'admin', { * relationships: ['permissions'] * }); * ``` * * @param table Table containing the entity. * @param primaryKey Primary key value. * @param options Optional partition and cascade relationships. * @returns `true` when the delete request succeeds. */ delete
(table: Table, primaryKey: string, options?: { partition?: string; relationships?: string[]; }): Promise; /** * Store a document (file blob) for later retrieval. * * @example * ```ts * const id = await db.saveDocument({ * path: '/docs/note.txt', * mimeType: 'text/plain', * content: 'hello world' * }); * ``` */ saveDocument(doc: OnyxDocument): Promise; /** * Fetch a previously saved document. * * @example * ```ts * const doc = await db.getDocument('doc123', { width: 640, height: 480 }); * ``` * * @param documentId ID of the document to fetch. * @param options Optional image resize settings. */ getDocument(documentId: string, options?: { width?: number; height?: number; }): Promise; /** * Remove a stored document permanently. * * @example * ```ts * await db.deleteDocument('doc123'); * ``` * * @param documentId ID of the document to delete. */ deleteDocument(documentId: string): Promise; /** * Fetch the current schema for the configured database. * * @example * ```ts * const schema = await db.getSchema(); * const userOnly = await db.getSchema({ tables: ['User'] }); * ``` */ getSchema(options?: { tables?: string | string[]; }): Promise; /** * Retrieve the schema revision history for the configured database. */ getSchemaHistory(): Promise; /** * Compare the current API schema with a local schema definition. * * @example * ```ts * const diff = await db.diffSchema(localSchema); * if (!diff.newTables.length && !diff.removedTables.length && !diff.changedTables.length) { * console.log('Schemas match'); * } * ``` */ diffSchema(localSchema: SchemaUpsertRequest): Promise; /** * Update the schema for the configured database. * * @example * ```ts * await db.updateSchema({ * revisionDescription: 'Add profile table', * entities: [ * { * name: 'Profile', * identifier: { name: 'id', generator: 'UUID' }, * attributes: [ * { name: 'displayName', type: 'String', isNullable: false } * ] * } * ] * }, { publish: true }); * ``` */ updateSchema(schema: SchemaUpsertRequest, options?: { publish?: boolean; }): Promise; /** * Validate a schema definition without applying it to the database. */ validateSchema(schema: SchemaUpsertRequest): Promise; /** * List stored secrets for the configured database. */ listSecrets(): Promise; /** * Fetch a decrypted secret value by key. */ getSecret(key: string): Promise; /** * Create or update a secret. */ putSecret(key: string, input: SecretSaveRequest): Promise; /** * Delete a secret by key. */ deleteSecret(key: string): Promise<{ key: string; }>; /** * Cancels active streams; safe to call multiple times. * @example * ```ts * const stream = await db.from('User').stream(); * stream.cancel(); * db.close(); * ``` */ close(): void; } interface OnyxFacade { /** * Initialize a database client. * * @example * ```ts * const db = onyx.init({ * baseUrl: 'https://api.onyx.dev', * databaseId: 'my-db', * apiKey: 'key', * apiSecret: 'secret' * }); * ``` * * @param config Connection settings and optional custom fetch. * @remarks * Each `db` instance resolves configuration once and holds a single internal * HTTP client. Requests leverage Node's built-in `fetch`, which reuses and * pools connections for keep-alive, so additional connection caching or * pooling is rarely necessary. */ init>(config?: OnyxConfig): IOnyxDatabase; /** * Clear cached configuration so the next {@link init} call re-resolves * credentials immediately. */ clearCacheConfig(): void; } interface SecretMetadata { key: string; purpose?: string; updatedAt: Date; } interface SecretRecord extends SecretMetadata { value: string; } interface SecretsListResponse { records: SecretMetadata[]; meta: { totalRecords: number; }; } interface SecretSaveRequest { purpose?: string; value?: string; } type SchemaDataType = 'String' | 'Boolean' | 'Char' | 'Byte' | 'Short' | 'Int' | 'Float' | 'Double' | 'Long' | 'Timestamp' | 'EmbeddedObject' | 'EmbeddedList'; type SchemaIdentifierGenerator = 'None' | 'Sequence' | 'UUID'; interface SchemaIdentifier { name: string; generator?: SchemaIdentifierGenerator; type?: SchemaDataType | string; } interface SchemaAttribute { name: string; type: SchemaDataType | string; isNullable?: boolean; } type SchemaIndexType = 'DEFAULT' | 'VECTOR'; interface SchemaIndex { name: string; type?: SchemaIndexType; /** @deprecated Score thresholds are query-time controls and the server ignores this field. */ minimumScore?: number; [key: string]: unknown; } interface SchemaResolver { name: string; resolver: string; [key: string]: unknown; } type SchemaTriggerEvent = 'PreInsert' | 'PostInsert' | 'PrePersist' | 'PostPersist' | 'PreUpdate' | 'PostUpdate' | 'PreDelete' | 'PostDelete' | string; interface SchemaTrigger { name: string; event: SchemaTriggerEvent; trigger: string; [key: string]: unknown; } type SchemaEntityType = 'DEFAULT' | 'SEARCHABLE'; /** * Search indexes maintained for a SEARCHABLE entity. * * Omitted values are interpreted as BOTH for backward compatibility. */ type SchemaSearchSupport = 'LEXICAL' | 'SEMANTIC' | 'BOTH'; interface SchemaEntity { name: string; type?: SchemaEntityType; searchSupport?: SchemaSearchSupport; identifier?: SchemaIdentifier; partition?: string; attributes?: SchemaAttribute[]; indexes?: SchemaIndex[]; resolvers?: SchemaResolver[]; triggers?: SchemaTrigger[]; [key: string]: unknown; } interface SchemaRevisionMetadata { revisionId?: string; createdAt?: Date; publishedAt?: Date; [key: string]: unknown; } interface SchemaRevision { databaseId: string; revisionDescription?: string; entities: SchemaEntity[]; meta?: SchemaRevisionMetadata; [key: string]: unknown; } type SchemaHistoryEntry = SchemaRevision; type SchemaUpsertRequest = Omit & { databaseId?: string; [key: string]: unknown; }; interface SchemaValidationResult { valid?: boolean; schema?: SchemaRevision; errors?: Array<{ message: string; }>; } interface SchemaAttributeChange { name: string; from: { type?: string; isNullable?: boolean; }; to: { type?: string; isNullable?: boolean; }; } interface SchemaIndexChange { name: string; from: SchemaIndex; to: SchemaIndex; } interface SchemaResolverChange { name: string; from: SchemaResolver; to: SchemaResolver; } interface SchemaTriggerChange { name: string; from: SchemaTrigger; to: SchemaTrigger; } interface SchemaTableDiff { name: string; type?: { from: SchemaEntityType; to: SchemaEntityType; } | null; searchSupport?: { from: SchemaSearchSupport; to: SchemaSearchSupport; } | null; partition?: { from: string | null; to: string | null; } | null; identifier?: { from: SchemaIdentifier | null; to: SchemaIdentifier | null; } | null; attributes?: { added: SchemaAttribute[]; removed: string[]; changed: SchemaAttributeChange[]; }; indexes?: { added: SchemaIndex[]; removed: string[]; changed: SchemaIndexChange[]; }; resolvers?: { added: SchemaResolver[]; removed: string[]; changed: SchemaResolverChange[]; }; triggers?: { added: SchemaTrigger[]; removed: string[]; changed: SchemaTriggerChange[]; }; } interface SchemaDiff { newTables: string[]; removedTables: string[]; changedTables: SchemaTableDiff[]; } declare const asc: (field: string) => Sort; declare const desc: (field: string) => Sort; /** Builder for combining query conditions with logical operators. */ declare class ConditionBuilderImpl implements IConditionBuilder { private condition; /** * Initialize with an optional starting criteria. * * @param criteria Initial query criteria to seed the builder. * @example * ```ts * const builder = new ConditionBuilderImpl({ field: 'id', operator: 'eq', value: '1' }); * ``` */ constructor(criteria?: QueryCriteria | null); /** * Add a criteria combined with AND. * * @param condition Another builder or raw criteria to AND. * @example * ```ts * builder.and({ field: 'name', operator: 'eq', value: 'Ada' }); * ``` */ and(condition: ConditionInput): IConditionBuilder; /** * Add a criteria combined with OR. * * @param condition Another builder or raw criteria to OR. * @example * ```ts * builder.or({ field: 'status', operator: 'eq', value: 'active' }); * ``` */ or(condition: ConditionInput): IConditionBuilder; /** * Produce the composed QueryCondition. * * @example * ```ts * const condition = builder.toCondition(); * ``` */ toCondition(): QueryCondition; /** * Wrap raw criteria into a single condition object. * * @param criteria Criteria to wrap. * @example * ```ts * builder['single']({ field: 'id', operator: 'eq', value: '1' }); * ``` */ private single; /** * Create a compound condition using the provided operator. * * @param operator Logical operator to apply. * @param conditions Child conditions to combine. * @example * ```ts * builder['compound']('AND', [condA, condB]); * ``` */ private compound; /** * Merge the next condition into the existing tree using the operator. * * @param operator Logical operator for the merge. * @param next Condition to merge into the tree. * @example * ```ts * builder['addCompound']('AND', someCondition); * ``` */ private addCompound; /** * Normalize input into a QueryCondition instance. * * @param condition Builder or raw criteria to normalize. * @example * ```ts * const qc = builder['prepare']({ field: 'id', operator: 'eq', value: '1' }); * ``` */ private prepare; } declare const eq: (field: string, value: unknown) => ConditionBuilderImpl; declare const neq: (field: string, value: unknown) => ConditionBuilderImpl; declare function inOp(field: string, values: string): ConditionBuilderImpl; declare function inOp(field: string, values: unknown[] | IQueryBuilder): ConditionBuilderImpl; declare function within(field: string, values: string | unknown[] | IQueryBuilder): ConditionBuilderImpl; declare function notIn(field: string, values: string): ConditionBuilderImpl; declare function notIn(field: string, values: unknown[] | IQueryBuilder): ConditionBuilderImpl; declare function notWithin(field: string, values: string | unknown[] | IQueryBuilder): ConditionBuilderImpl; declare const between: (field: string, lower: unknown, upper: unknown) => ConditionBuilderImpl; declare const notBetween: (field: string, lower: unknown, upper: unknown) => ConditionBuilderImpl; declare const gt: (field: string, value: unknown) => ConditionBuilderImpl; declare const gte: (field: string, value: unknown) => ConditionBuilderImpl; declare const lt: (field: string, value: unknown) => ConditionBuilderImpl; declare const lte: (field: string, value: unknown) => ConditionBuilderImpl; declare const matches: (field: string, regex: string) => ConditionBuilderImpl; declare function search(queryText: string, minScore?: number | null): ConditionBuilderImpl; declare function search(queryText: string, options: SearchOptions): ConditionBuilderImpl; declare function search(searchQuery: VectorSearchQueryInput): ConditionBuilderImpl; /** Sole-root condition for physically bounded lexical candidate admission. */ declare function approximateSearch(queryText: string, options?: ApproximateSearchOptions): ConditionBuilderImpl; declare function approximateSearch(searchQuery: VectorSearchQueryInput): ConditionBuilderImpl; /** Sole-root condition for physically bounded native-HNSW admission. */ declare const hnswCandidates: (query: HnswSearchQueryInput) => ConditionBuilderImpl; /** * Bounded ordinary-index admission condition for * `where(approximateCandidates(...))`, composable through `AND`. */ declare const approximateCandidates: (attribute: string, valueOrValues: unknown | readonly unknown[], maxCandidates?: number) => ConditionBuilderImpl; declare const notMatches: (field: string, regex: string) => ConditionBuilderImpl; declare const like: (field: string, pattern: string) => ConditionBuilderImpl; declare const notLike: (field: string, pattern: string) => ConditionBuilderImpl; declare const contains: (field: string, value: unknown) => ConditionBuilderImpl; declare const containsIgnoreCase: (field: string, value: unknown) => ConditionBuilderImpl; declare const notContains: (field: string, value: unknown) => ConditionBuilderImpl; declare const notContainsIgnoreCase: (field: string, value: unknown) => ConditionBuilderImpl; declare const startsWith: (field: string, prefix: string) => ConditionBuilderImpl; declare const notStartsWith: (field: string, prefix: string) => ConditionBuilderImpl; declare const isNull: (field: string) => ConditionBuilderImpl; declare const notNull: (field: string) => ConditionBuilderImpl; declare const HNSW_QUERY_FORMAT_VERSION: 1; declare const DEFAULT_HNSW_CANDIDATES = 1000; declare const DEFAULT_HNSW_EF_SEARCH = 1000; declare const MAX_HNSW_CANDIDATES = 5000; declare const MAX_HNSW_EF_SEARCH = 20000; declare const MAX_HNSW_VECTOR_DIMENSION = 16384; declare const DEFAULT_APPROXIMATE_INDEX_CANDIDATES = 1000; declare const MAX_APPROXIMATE_INDEX_CANDIDATES = 5000; declare const MAX_APPROXIMATE_INDEX_ROUTE_VALUES = 5000; declare const MAX_VECTOR_SEARCH_CANDIDATES = 5000; /** Validate and canonicalize one lossless semantic routing signature. */ declare function semanticVectorSignature(input: SemanticVectorSignatureInput | SemanticVectorSignature): SemanticVectorSignature; /** Validate and canonicalize a native lexical, semantic, or hybrid search value. */ declare function vectorSearchQuery(input: VectorSearchQueryInput): VectorSearchQuery; /** Validate and canonicalize a bounded native-HNSW candidate request. */ declare function hnswSearchQuery(input: HnswSearchQueryInput): HnswSearchQuery; /** Validate and canonicalize one bounded ordinary-index candidate route. */ declare function approximateIndexCandidateQuery(valueOrValues: unknown | readonly unknown[], maxCandidates?: number): ApproximateIndexCandidateQuery; declare const avg: (attribute: string) => string; declare const sum: (attribute: string) => string; declare const count: (attribute: string) => string; declare const min: (attribute: string) => string; declare const max: (attribute: string) => string; declare const std: (attribute: string) => string; declare const variance: (attribute: string) => string; declare const median: (attribute: string) => string; declare const upper: (attribute: string) => string; declare const lower: (attribute: string) => string; declare const substring: (attribute: string, from: number, length: number) => string; declare const replace: (attribute: string, pattern: string, repl: string) => string; declare const format: (attribute: string, formatter: string) => string; declare const percentile: (attribute: string, p: number) => string; export { MAX_VECTOR_SEARCH_CANDIDATES as $, type AiChatClient as A, DEFAULT_HNSW_CANDIDATES as B, type ConditionInput as C, DEFAULT_APPROXIMATE_INDEX_CANDIDATES as D, DEFAULT_HNSW_EF_SEARCH as E, type FetchImpl as F, type FetchResponse as G, type FullTextQuery as H, type FullTextSearchResult as I, HNSW_QUERY_FORMAT_VERSION as J, type HnswSearchQuery as K, type HnswSearchQueryInput as L, type ICascadeBuilder as M, type ICascadeRelationshipBuilder as N, type OnyxFacade as O, type IConditionBuilder as P, type IOnyxDatabase as Q, type IQueryBuilder as R, type ISaveBuilder as S, type Int64WireInput as T, type JsonFormatOptions as U, type LogicalOperator as V, MAX_APPROXIMATE_INDEX_CANDIDATES as W, MAX_APPROXIMATE_INDEX_ROUTE_VALUES as X, MAX_HNSW_CANDIDATES as Y, MAX_HNSW_EF_SEARCH as Z, MAX_HNSW_VECTOR_DIMENSION as _, type AiChatCompletionChoice as a, count as a$, type OnyxConfig as a0, type OnyxDocument as a1, type PublishedModelPredictionInput as a2, type PublishedModelPredictionInputs as a3, type PublishedModelPredictionResponse as a4, type PublishedModelRawPredictionRequest as a5, type PublishedModelScriptPredictionRequest as a6, type QueryCondition as a7, type QueryCriteria as a8, type QueryCriteriaOperator as a9, type SchemaValidationResult as aA, type SearchMatch as aB, type SearchMode as aC, type SearchOptions as aD, type SecretMetadata as aE, type SecretRecord as aF, type SecretSaveRequest as aG, type SecretsListResponse as aH, type SelectQuery as aI, type SemanticVectorSignature as aJ, type SemanticVectorSignatureInput as aK, type Sort as aL, type StreamAction as aM, type TableFormatOptions as aN, type TreeFormatOptions as aO, type UpdateQuery as aP, type VectorSearchQuery as aQ, type VectorSearchQueryInput as aR, type WireFormat as aS, approximateCandidates as aT, approximateIndexCandidateQuery as aU, approximateSearch as aV, asc as aW, avg as aX, between as aY, contains as aZ, containsIgnoreCase as a_, type QueryPage as aa, QueryResults as ab, type QueryResultsPromise as ac, type RetryOptions as ad, type SchemaAttribute as ae, type SchemaAttributeChange as af, type SchemaDataType as ag, type SchemaDiff as ah, type SchemaEntity as ai, type SchemaEntityType as aj, type SchemaHistoryEntry as ak, type SchemaIdentifier as al, type SchemaIdentifierGenerator as am, type SchemaIndex as an, type SchemaIndexChange as ao, type SchemaIndexType as ap, type SchemaResolver as aq, type SchemaResolverChange as ar, type SchemaRevision as as, type SchemaRevisionMetadata as at, type SchemaSearchSupport as au, type SchemaTableDiff as av, type SchemaTrigger as aw, type SchemaTriggerChange as ax, type SchemaTriggerEvent as ay, type SchemaUpsertRequest as az, type AiChatCompletionChunk as b, desc as b0, eq as b1, format as b2, gt as b3, gte as b4, hnswCandidates as b5, hnswSearchQuery as b6, inOp as b7, isNull as b8, like as b9, sum as bA, upper as bB, variance as bC, vectorSearchQuery as bD, within as bE, lower as ba, lt as bb, lte as bc, matches as bd, max as be, median as bf, min as bg, neq as bh, notBetween as bi, notContains as bj, notContainsIgnoreCase as bk, notIn as bl, notLike as bm, notMatches as bn, notNull as bo, notStartsWith as bp, notWithin as bq, percentile as br, replace as bs, name as bt, version as bu, search as bv, semanticVectorSignature as bw, startsWith as bx, std as by, substring as bz, type AiChatCompletionChunkChoice as c, type AiChatCompletionChunkDelta as d, type AiChatCompletionRequest as e, type AiChatCompletionResponse as f, type AiChatCompletionStream as g, type AiChatCompletionUsage as h, type AiChatMessage as i, type AiChatOptions as j, type AiChatRole as k, type AiClient as l, type AiErrorResponse as m, type AiModel as n, type AiModelsResponse as o, type AiRequestOptions as p, type AiScriptApprovalRequest as q, type AiScriptApprovalResponse as r, type AiTool as s, type AiToolCall as t, type AiToolCallFunction as u, type AiToolChoice as v, type AiToolFunction as w, type ApproximateIndexCandidateQuery as x, type ApproximateSearchOptions as y, type CsvFormatOptions as z };