Fields API reference
Current emitted signatures and options for @db3.ai/app/db.
On this page
Source-backed MarkdownImports and examples
Import supported APIs from @db3.ai/app/db. These signatures come from the staged package used by consumers. Relative filenames in declarations describe type dependencies; they are not extra supported deep imports.
Use the guide for setup, executable examples, failure handling and ownership. A signature is not proof that every deployment or provider has been exercised.
Field lifecycle and configuration
ts
import type { Knex } from 'knex';
import type { ValidationRule } from '../validation/index.js';
import type { DatabaseDialect, DatabaseValueOptions } from './dialects/index.js';
/**
* Generic database row shape returned by the SQL driver.
*/
export type DbRow = Record<string, unknown>;
/**
* Partial database row used for inserts and updates.
*
* A field returns an object instead of a scalar because some fields may map to
* multiple database columns. For example, a map/location field could return
* `{ location_lat, location_lng }`.
*/
export type DbWriteData = Record<string, unknown>;
/**
* A structured validation error attached to a specific model field.
*/
export interface FieldError {
/** Logical field name on the model, for example `email` or `password`. */
field: string;
/** Human-readable error message. */
message: string;
/** Stable machine-readable error code, for example `required`. */
code?: string;
/** Offending value, where safe to expose. Avoid storing secrets here. */
value?: unknown;
/** Extra structured data for UI/API consumers. */
details?: unknown;
}
/**
* Error thrown by `ActiveRecord.save()` when one or more fields are invalid.
*/
export declare class RecordValidationError extends Error {
readonly errors: FieldError[];
constructor(errors: FieldError[]);
}
export type FieldDefault = null | string | number | boolean | Record<string, unknown> | unknown[];
export type FieldDefaultFactory = () => unknown;
export type GeneratedValue = boolean | 'db' | 'ulid' | 'uuid-v4' | 'now';
export interface FrontendComponentSpec {
component: string;
props: Record<string, unknown>;
}
export interface DomFormRenderSpec {
component: 'DomForm';
props: Record<string, unknown>;
children: FrontendComponentSpec[];
}
export interface FieldFrontendConfig {
component?: string;
props?: Record<string, unknown>;
searchComponent?: string;
searchProps?: Record<string, unknown>;
}
export interface FieldRenderOptions {
mode?: 'create' | 'edit' | 'search';
}
/**
* Core configuration shared by all fields.
*
* Concrete field types should extend this with their own options.
*/
export interface FieldConfig {
/** Database column name. Defaults to the model field name. */
column?: string;
/** Developer-facing note for generated models and schema tooling. */
comment?: string;
/** Whether the field must have a non-empty value. */
required?: boolean;
/** Whether the field is the model primary key. */
primary?: boolean;
/** Whether the value should be omitted from `toJSON()`. */
hidden?: boolean;
/** Whether normal ActiveRecord fetches should include this field's columns. */
selectedByDefault?: boolean;
/** Whether the generated database schema should include a unique constraint. */
unique?: boolean;
/** Whether the generated database schema should include an index on this field's primary column. */
index?: boolean;
/** Optional name for the generated single-column index. */
indexName?: string;
/** Additional generated database schema indexes for this field. */
indexes?: DbIndexSpec[];
/** Optional human-friendly label for UI/admin/form generation. */
label?: string;
/** Static default value or runtime factory. Use static values for serializable config. */
default?: FieldDefault | FieldDefaultFactory;
/** Named generation strategy. This is serializable and lets the field/framework decide how to generate the value. */
generated?: GeneratedValue;
/** Frontend rendering hints composed by FieldType render helpers. */
frontend?: FieldFrontendConfig;
}
export type FieldClass<TField extends FieldType<any, any, any, any, any> = FieldType<any, any, any, any, any>> = new (config?: any) => TField;
export interface FieldDefinition<TField extends FieldType<any, any, any, any, any> = FieldType<any, any, any, any, any>> {
type: FieldClass<TField>;
config: ConstructorParameters<FieldClass<TField>>[0];
}
export type FieldInput<TField extends FieldType<any, any, any, any, any> = FieldType<any, any, any, any, any>> = FieldClass<TField> | FieldDefinition<TField> | TField;
export type FieldInputMap = Record<string, FieldInput<any>>;
export type FieldMap = Record<string, FieldType<any, any, any, any, any>>;
export type FieldMapFactory = (field: any) => FieldInputMap;
/**
* Context passed into low-level field methods.
*
* Record instances normally use the higher-level field instance API. This
* context remains for schema/query work and for concrete field internals.
*/
export interface FieldContext {
/** The model class metadata. */
model: ModelMetadata;
/** Database dialect used for schema/value conversion when available. */
dialect?: DatabaseDialect;
/** Knex table builder when schema is being applied to the database. */
table?: Knex.TableBuilder;
/** Options used when writing columns through `table`. */
columnWriteOptions?: DbColumnWriteOptions;
/** The active record instance when available. Query code may omit this. */
record?: unknown;
/** Logical field name on the model, for example `email`. */
fieldName: string;
}
/**
* Minimal model metadata required by fields.
*
* This avoids importing `ActiveRecord` into the field base class and keeps the
* dependency direction simple.
*/
export interface ModelMetadata {
/** Database table name. */
table: string;
/** Logical primary-key field name. */
primaryKey: string;
/** Static field definitions on the model class. */
fields: FieldMapFactory;
}
/**
* Options passed when collecting database write data from fields.
*/
export interface DbWriteOptions {
/** True for insert, false for update. */
isInsert: boolean;
/** Whether clean fields should be excluded from the generated row. */
onlyDirty: boolean;
/** Database value conversion context for driver-specific field storage. */
valueOptions?: DatabaseValueOptions;
}
/**
* Basic state used by most one-column value fields.
*/
export interface BasicFieldState<TValue = unknown> {
/** Current app-memory value. */
value: TValue;
/** Value originally loaded from the database or initial default. */
originalValue: TValue;
/** Whether the current value differs from the original value. */
dirty: boolean;
/** Validation errors for this field on this record. */
errors: FieldError[];
}
/**
* Database column description produced by a field's `getDbSchema()`.
*
* The `type` string comes from the active dialect and is applied directly by
* `Database` via Knex `specificType`.
*/
export interface DbColumnSpec {
/** Database column name. */
name: string;
/** Database column type, e.g. `varchar(255)`, `char(26)`, `json`, or `longtext`. */
type: string;
/** Whether null is allowed. */
nullable?: boolean;
/** Whether this column is the primary key. */
primary?: boolean;
/** Whether this column has a unique constraint. */
unique?: boolean;
/** Database default value. */
default?: unknown;
/** Database-native column comment where supported, such as MySQL. */
comment?: string;
}
/**
* Options for writing a column onto a Knex table builder.
*/
export interface DbColumnWriteOptions {
alter?: boolean;
alterNullable?: boolean;
alterType?: boolean;
applyDefault?: boolean;
applyComment?: boolean;
}
/**
* Writes a column spec onto a Knex table builder.
*/
export declare function writeDbColumn(table: Knex.TableBuilder, column: DbColumnSpec, options?: DbColumnWriteOptions): void;
/**
* Neutral database index description.
*/
export interface DbIndexSpec {
/** Columns included in the index. */
columns: DbIndexColumnSpec[];
/** Optional index name. */
name?: string;
/** Whether the index is unique. */
unique?: boolean;
/** Database index kind. Defaults to a normal scalar index. */
type?: 'normal' | 'vector';
}
export type DbIndexColumnSpec = string | {
name: string;
order?: 'asc' | 'desc';
};
export declare function fieldSchemaIndexes(column: string, config: FieldConfig): DbIndexSpec[] | undefined;
/**
* Neutral foreign-key description.
*/
export interface DbForeignKeySpec {
/** Local database column. */
column: string;
/** Referenced database table. */
referencesTable: string;
/** Referenced database column. */
referencesColumn: string;
/** Optional ON DELETE action. */
onDelete?: 'CASCADE' | 'RESTRICT' | 'SET NULL' | 'NO ACTION';
/** Optional ON UPDATE action. */
onUpdate?: 'CASCADE' | 'RESTRICT' | 'SET NULL' | 'NO ACTION';
}
/**
* Database schema contribution produced by a single field.
*/
export interface DbSchemaPart {
/** Columns required by this field. */
columns?: DbColumnSpec[];
/** Indexes required by this field. */
indexes?: DbIndexSpec[];
/** Foreign keys required by this field. */
foreignKeys?: DbForeignKeySpec[];
}
/**
* Base class for reusable field behaviour.
*
* Static model fields are schema definitions. Each ActiveRecord instance creates
* private live field objects that own their value, dirty state, errors, field
* name, and parent record reference.
*
* The low-level lifecycle remains:
*
* - `createState()` creates per-record storage.
* - `setValue()` handles input assignment and stores the hydrated backend value.
* - `getValue()` handles normal property reads.
* - `validate()` stores field errors.
* - `getDataForDb()` returns database write data.
* - `setFromDb()` hydrates state from a database row.
* - `getDisplayValue()` serializes for frontend/form/API-safe output.
*/
export declare abstract class FieldType<TValue = unknown, TDbValue = TValue, TDisplayValue = TValue, TInput = TValue, TState extends {
errors: FieldError[];
} = BasicFieldState<TValue>> {
readonly config: FieldConfig;
private $fieldName?;
private $model?;
private $record?;
private $state?;
private $activeContext?;
constructor(config?: FieldConfig);
/**
* Logical field name on the parent record.
*/
get name(): string;
/**
* Logical field name on the parent record/model.
*/
get fieldName(): string;
/**
* Parent model metadata.
*/
get model(): ModelMetadata;
/**
* Parent ActiveRecord instance.
*/
get record(): unknown;
required(value?: boolean): this;
/**
* Primary database column for this bound field.
*/
get column(): string;
/**
* Current app-memory value for this bound field.
*/
get value(): TValue;
set value(input: TInput);
/**
* Whether this bound field has changed since hydration/default creation.
*/
get dirty(): boolean;
/**
* Current validation errors for this bound field.
*/
get errors(): FieldError[];
/**
* Clears validation errors for this bound field.
*/
clearErrors(): void;
/**
* Hydrates this bound field from a database row.
*/
hydrate(row: DbRow): void;
/**
* Validates this bound field.
*/
validateField(): Promise<FieldError[]>;
/**
* Returns database write data for this bound field.
*/
getBoundDataForDb(options: DbWriteOptions): Promise<DbWriteData>;
/**
* Returns a frontend/form/API-safe value for this bound field.
*/
getBoundDisplayValue(): TDisplayValue | undefined;
/**
* Converts a query value for this bound field.
*/
getBoundQueryValue(input: TInput): unknown;
/**
* Marks this bound field as clean.
*/
markBoundClean(): void;
/**
* Returns the column for this field blueprint on a model.
*/
getColumnFor(model: ModelMetadata, fieldName: string): string;
/**
* Converts a query value for this field blueprint on a model.
*/
getQueryValueFor(model: ModelMetadata, fieldName: string, input: TInput): unknown;
/**
* Returns schema metadata for this field blueprint on a model.
*/
getDbSchemaFor(model: ModelMetadata, fieldName: string): DbSchemaPart;
/**
* Returns the DomStudio component spec for rendering this field in a form.
*/
getFormComponent(options?: FieldRenderOptions, ctx?: FieldContext): FrontendComponentSpec;
/**
* Returns the DomStudio component spec for rendering this field as a search filter.
*/
getSearchFilterComponent(options?: FieldRenderOptions, ctx?: FieldContext): FrontendComponentSpec | null;
/**
* Returns a form component spec for an unbound model field.
*/
getFormComponentFor(model: ModelMetadata, fieldName: string, options?: FieldRenderOptions): FrontendComponentSpec;
/**
* Returns a search component spec for an unbound model field.
*/
getSearchFilterComponentFor(model: ModelMetadata, fieldName: string, options?: FieldRenderOptions): FrontendComponentSpec | null;
/**
* Returns the primary database column for this field.
*
* Compound fields may still return additional columns from `getDataForDb()`.
*/
getColumn(ctx?: FieldContext): string;
/**
* Creates per-record runtime state for this field.
*/
createState(ctx?: FieldContext): TState;
/**
* Handles app-level assignment, e.g. `user.email = '[email protected]'`.
*
* Keep this mostly synchronous. Async work such as hashing should usually
* happen in `getDataForDb()` during save.
*/
setValue(state: TState, input: TInput, ctx?: FieldContext): void;
/**
* Handles app-level property reads, e.g. `user.email`.
*/
getValue(state: TState, ctx?: FieldContext): TValue;
/**
* Hydrates field state from a raw database row.
*/
setFromDb(state: TState, row: DbRow, ctx?: FieldContext): void;
/**
* Validates the field and stores the resulting errors on the field state.
*/
validate(state: TState, ctx?: FieldContext): Promise<FieldError[]>;
/**
* Returns current validation errors for this field state.
*/
getErrors(state: TState): FieldError[];
/**
* Returns true if this field state currently has validation errors.
*/
hasErrors(state: TState): boolean;
/**
* Returns true if the field has changed since hydration/default creation.
*/
isDirty(state: TState): boolean;
/**
* Marks the state as clean after a successful save or hydration.
*/
markClean(state: TState): void;
/**
* Returns database write data for this field.
*
* The default implementation maps one field to one column.
*/
getDataForDb(state: TState, options: DbWriteOptions): Promise<DbWriteData>;
getDataForDb(state: TState, ctx: FieldContext, options: DbWriteOptions): Promise<DbWriteData>;
/**
* Returns a frontend/form/API-safe value for this field.
*/
getDisplayValue(state: TState, ctx?: FieldContext): TDisplayValue | undefined;
/**
* Alias used by JSON transport. Framework docs call this display data.
*/
getJsonValue(state: TState, ctx?: FieldContext): TDisplayValue | undefined;
/**
* Converts an input query value into its database representation.
*
* Query builder methods call this so `where('email', '[email protected]')`
* can compare against the normalized database value.
*/
getQueryValue(input: TInput, ctx?: FieldContext): unknown;
/**
* Returns database schema metadata for dev sync and diff tooling.
*
* When `ctx.table` is present the field also writes its column(s) onto that
* Knex builder using the dialect-owned SQL type string.
*/
getDbSchema(ctx?: FieldContext): DbSchemaPart;
/**
* Returns request/input validation rules for this field.
*/
getValidationRules(ctx?: FieldContext): ValidationRule[];
/**
* Parses app/input assignment into the field's app-memory value.
*/
protected parse(input: TInput): TValue;
/**
* Default form component for this field type.
*/
protected defaultFormComponent(): string;
/**
* Default form props derived from FieldType config.
*/
protected defaultFormComponentProps(_options: FieldRenderOptions): Record<string, unknown>;
/**
* Default search component for this field type.
*/
protected defaultSearchFilterComponent(): string | null;
/**
* Default search props derived from FieldType config.
*/
protected defaultSearchFilterComponentProps(_options: FieldRenderOptions): Record<string, unknown>;
protected fieldLabel(): string;
/**
* Converts a raw database value into app memory.
*/
protected fromDbValue(input: TDbValue): TValue;
/**
* Converts an app-memory value into database storage form.
*/
protected toDbValue(input: TValue, _options?: DatabaseValueOptions): TDbValue;
/**
* Converts a hydrated backend value into frontend/form display data.
*/
protected toDisplayValue(input: TValue): TDisplayValue;
/**
* Collects validation errors for this field state.
*
* Concrete fields should call `super.collectErrors()` then append their own
* errors.
*/
protected collectErrors(state: TState): Promise<FieldError[]>;
/**
* Tests whether a value should count as empty for required validation.
*/
protected isEmpty(value: unknown): boolean;
/**
* Returns the database schema default implied by the runtime field default.
*/
protected getDbDefaultValue(): unknown;
/**
* Context for this bound field.
*/
protected get context(): FieldContext;
/**
* Dialect for schema generation, falling back to the configured connection.
*/
protected schemaDialect(): DatabaseDialect;
/**
* Returns schema metadata and optionally writes columns onto `ctx.table`.
*/
protected completeDbSchema(part: DbSchemaPart, ctx?: FieldContext): DbSchemaPart;
/**
* State for this bound field.
*/
protected get state(): TState;
/**
* Attaches this field instance to a model without creating record state.
*/
bindToModel(model: ModelMetadata, fieldName: string): this;
/**
* Returns an unbound copy of this field definition.
*/
clone(): this;
/**
* Returns a cloned field definition with config overrides applied.
*/
withConfig(config: Partial<FieldConfig>): this;
/**
* Attaches this field instance to a concrete ActiveRecord instance.
*/
bindToRecord(record: unknown, fieldName: string): this;
bindToRecord(model: ModelMetadata, record: unknown, fieldName: string): this;
protected resolveDbWriteArgs(ctxOrOptions: FieldContext | DbWriteOptions, options?: DbWriteOptions): {
ctx?: FieldContext;
options: DbWriteOptions;
};
/**
* We are trying to deprecate this function in favour of using object functions like this.get
* @param ctx @deprecated this.schemaDialect()
* @returns
*/
protected withContext<TResult>(ctx: FieldContext | undefined, callback: () => TResult): TResult;
private modelFromRecord;
private requireModel;
private requireFieldName;
/**
* Resolves the configured default value.
*/
private getDefaultValue;
}
export type FieldValue<TField> = TField extends FieldType<infer TValue, any, any, any, any> ? TValue : never;
export type FieldDbValue<TField> = TField extends FieldType<any, infer TDbValue, any, any, any> ? TDbValue : never;
export type FieldDisplayValue<TField> = TField extends FieldType<any, any, infer TDisplayValue, any, any> ? TDisplayValue : never;
export type FieldInputValue<TField> = TField extends FieldType<any, any, any, infer TInput, any> ? TInput : never;
Model field factory
ts
import type { ActiveRecord, ActiveRecordClass } from '../ActiveRecord.js';
import { EncryptedJsonField, type EncryptedJsonFieldConfig } from './EncryptedJsonField.js';
import { BooleanField, type BooleanFieldConfig, BigIncrementsField, CharUuidField, type CharUuidFieldConfig, ChoiceStringField, type ChoiceStringFieldConfig, DecimalField, type DecimalFieldConfig, EmailField, type EmailFieldConfig, JsonField, type JsonFieldConfig, JsonStringField, type JsonStringFieldConfig, IntegerField, type IntegerFieldConfig, LinkField, type LinkFieldConfig, PasswordField, type PasswordFieldConfig, StringListField, type StringListFieldConfig, StringField, type StringFieldConfig, TextField, type TextFieldConfig, TimestampField, type TimestampFieldConfig, UlidField, type UlidFieldConfig, UrlField, type UrlFieldConfig, VectorField, type VectorFieldConfig } from './index.js';
export { createField } from './createField.js';
export interface FieldBuilder {
bigIncrements(config?: IntegerFieldConfig): BigIncrementsField;
boolean(config?: BooleanFieldConfig): BooleanField;
charUuid(config?: CharUuidFieldConfig): CharUuidField;
choice(config: ChoiceStringFieldConfig): ChoiceStringField;
decimal(config?: DecimalFieldConfig): DecimalField;
email(config?: EmailFieldConfig): EmailField;
/** Creates authenticated encrypted JSON stored in a non-queryable long text column. */
encryptedJson<TValue>(config?: EncryptedJsonFieldConfig): EncryptedJsonField<TValue>;
/** Creates a permissive JSON field for arbitrary JSON-compatible values. */
json<TValue>(config?: JsonFieldConfig): JsonField<TValue | null>;
/** Creates a backwards-compatible JSON field that serializes values for storage. */
jsonString<TValue>(config?: JsonStringFieldConfig): JsonStringField<TValue>;
/** Creates a JSON field serializes into a `text` column. */
jsonText<TValue>(config?: JsonStringFieldConfig): JsonStringField<TValue>;
/** Creates a JSON field serializes into a `longtext` column. */
jsonLongText<TValue>(config?: JsonStringFieldConfig): JsonStringField<TValue>;
integer(config?: IntegerFieldConfig): IntegerField;
link<TRecord extends ActiveRecord>(target: () => ActiveRecordClass<TRecord>, config?: Omit<LinkFieldConfig<TRecord>, 'target'>): LinkField<TRecord>;
/** Creates a JSON-backed list of normalized strings. */
stringList(config?: StringListFieldConfig): StringListField;
password(config: PasswordFieldConfig): PasswordField;
string(config?: StringFieldConfig): StringField;
text(config?: TextFieldConfig): TextField;
longText(config?: TextFieldConfig): TextField;
timestamp(config?: TimestampFieldConfig): TimestampField;
ulid(config?: UlidFieldConfig): UlidField;
url(config?: UrlFieldConfig): UrlField;
/** Creates a native numeric vector field for embeddings. */
vector(config?: VectorFieldConfig): VectorField;
}
export declare const field: FieldBuilder;
String field
ts
import { BasicFieldState, DbSchemaPart, FieldConfig, FieldContext, FieldError, FieldRenderOptions, FieldType } from '../FieldType.js';
import type { ValidationRule } from '../../validation/index.js';
/**
* Configuration for varchar-backed string fields.
*/
export interface StringFieldConfig extends FieldConfig {
/** Maximum app-memory string length. */
maxLength?: number;
/** Whether to trim incoming strings. Defaults to true. */
trim?: boolean;
/** Database varchar length. Defaults to `maxLength` or 255. */
length?: number;
}
/**
* Generic varchar-backed string field.
*
* Responsibilities:
* - coerce input to a string
* - optionally trim whitespace
* - convert empty strings to null
* - validate required/max length
* - describe varchar database column metadata
*/
export declare class StringField extends FieldType<string | null, string | null, string | null, unknown, BasicFieldState<string | null>> {
readonly config: StringFieldConfig;
constructor(config?: StringFieldConfig);
/**
* Parses input into a nullable string.
*/
protected parse(input: unknown): string | null;
protected defaultFormComponent(): string;
protected defaultFormComponentProps(options: FieldRenderOptions): Record<string, unknown>;
getValidationRules(ctx?: FieldContext): ValidationRule[];
/**
* Adds string-specific validation on top of required validation.
*/
protected collectErrors(state: BasicFieldState<string | null>): Promise<FieldError[]>;
/**
* Returns database schema metadata for this string field.
*/
getDbSchema(ctx?: FieldContext): DbSchemaPart;
protected effectiveMaxLength(): number | undefined;
}
Text field
ts
import { DbSchemaPart, FieldConfig, FieldContext, FieldRenderOptions } from '../FieldType.js';
import { StringField } from './StringField.js';
/**
* Configuration for text-backed string fields.
*/
export interface TextFieldConfig extends FieldConfig {
/** Maximum app-memory string length. Text fields have no default max length. */
maxLength?: number;
/** Whether to trim incoming strings. Defaults to true. */
trim?: boolean;
}
/**
* String value stored in a text-like database column.
*/
export declare class TextField extends StringField {
readonly config: TextFieldConfig;
constructor(config?: TextFieldConfig);
protected defaultFormComponent(): string;
protected defaultFormComponentProps(options: FieldRenderOptions): Record<string, unknown>;
/**
* Describes the text-like database column used by this field.
*/
getDbSchema(ctx?: FieldContext): DbSchemaPart;
protected effectiveMaxLength(): number | undefined;
}
Boolean field
ts
import { BasicFieldState, DbSchemaPart, FieldConfig, FieldContext, FieldType } from '../FieldType.js';
import type { ValidationRule } from '../../validation/index.js';
/**
* Configuration for boolean fields.
*/
export interface BooleanFieldConfig extends FieldConfig {
}
/**
* Boolean field with light coercion for common form values.
*/
export declare class BooleanField extends FieldType<boolean | null, boolean | number | string | null, boolean | null, unknown, BasicFieldState<boolean | null>> {
readonly config: BooleanFieldConfig;
constructor(config?: BooleanFieldConfig);
/**
* Parses booleans from booleans, numbers, and common strings.
*/
protected parse(input: unknown): boolean | null;
/**
* Normalises database driver boolean values such as MySQL's 1/0 integers.
*/
protected fromDbValue(input: unknown): boolean | null;
protected defaultFormComponent(): string;
protected defaultSearchFilterComponent(): string | null;
getValidationRules(ctx?: FieldContext): ValidationRule[];
/**
* Describes the boolean database column.
*/
getDbSchema(ctx?: FieldContext): DbSchemaPart;
}
Integer field
ts
import { BasicFieldState, DbSchemaPart, FieldConfig, FieldContext, FieldError, FieldRenderOptions, FieldType } from '../FieldType.js';
import type { ValidationRule } from '../../validation/index.js';
/**
* Configuration for integer fields.
*/
export interface IntegerFieldConfig extends FieldConfig {
/** Minimum allowed integer value. */
min?: number;
/** Maximum allowed integer value. */
max?: number;
/** Whether to generate an unsigned integer column where supported. */
unsigned?: boolean;
/** Whether to generate a big integer column. */
big?: boolean;
}
/**
* Integer field for numeric model attributes.
*/
export declare class IntegerField extends FieldType<number | null, number | null, number | null, unknown, BasicFieldState<number | null>> {
readonly config: IntegerFieldConfig;
constructor(config?: IntegerFieldConfig);
protected parse(input: unknown): number | null;
protected defaultFormComponent(): string;
protected defaultSearchFilterComponent(): string | null;
protected defaultFormComponentProps(options: FieldRenderOptions): Record<string, unknown>;
min(value: number): IntegerField;
max(value: number): IntegerField;
getValidationRules(ctx?: FieldContext): ValidationRule[];
protected collectErrors(state: BasicFieldState<number | null>): Promise<FieldError[]>;
getDbSchema(ctx?: FieldContext): DbSchemaPart;
}
export declare class BigIncrementsField extends IntegerField {
constructor(config?: IntegerFieldConfig);
getDbSchema(ctx?: FieldContext): DbSchemaPart;
}
Decimal field
ts
import { BasicFieldState, DbSchemaPart, FieldConfig, FieldContext, FieldError, FieldRenderOptions, FieldType } from '../FieldType.js';
import type { ValidationRule } from '../../validation/index.js';
export interface DecimalFieldConfig extends FieldConfig {
min?: number;
max?: number;
precision?: number;
scale?: number;
}
export declare class DecimalField extends FieldType<number | null, number | string | null, number | null, unknown, BasicFieldState<number | null>> {
readonly config: DecimalFieldConfig;
constructor(config?: DecimalFieldConfig);
protected parse(input: unknown): number | null;
protected fromDbValue(input: unknown): number | null;
protected defaultFormComponent(): string;
protected defaultSearchFilterComponent(): string | null;
protected defaultFormComponentProps(options: FieldRenderOptions): Record<string, unknown>;
getValidationRules(ctx?: FieldContext): ValidationRule[];
protected collectErrors(state: BasicFieldState<number | null>): Promise<FieldError[]>;
getDbSchema(ctx?: FieldContext): DbSchemaPart;
}
ChoiceString field
ts
import { BasicFieldState, FieldContext, FieldError } from '../FieldType.js';
import type { ValidationRule } from '../../validation/index.js';
import { StringField, type StringFieldConfig } from './StringField.js';
/**
* Configuration for string fields restricted to a known set of values.
*/
export interface ChoiceStringFieldConfig extends StringFieldConfig {
/** Allowed internal values. */
choices: readonly string[];
/** Whether matching should be case-sensitive. Defaults to true. */
caseSensitive?: boolean;
}
/**
* String field that normalises to one of a declared set of choices.
*/
export declare class ChoiceStringField extends StringField {
readonly config: ChoiceStringFieldConfig;
constructor(config: ChoiceStringFieldConfig);
protected parse(input: unknown): string | null;
protected fromDbValue(input: unknown): string | null;
getValidationRules(ctx?: FieldContext): ValidationRule[];
protected collectErrors(state: BasicFieldState<string | null>): Promise<FieldError[]>;
private matchChoice;
private defaultChoice;
}
Email field
ts
import { BasicFieldState, FieldContext, FieldError } from '../FieldType.js';
import type { ValidationRule } from '../../validation/index.js';
import { StringField, StringFieldConfig } from './StringField.js';
/**
* Configuration for email fields.
*/
export interface EmailFieldConfig extends StringFieldConfig {
/** Whether to lowercase incoming email addresses. Defaults to true. */
lowercase?: boolean;
}
/**
* Email field implemented as a specialized string field.
*
* It normalizes values by trimming and lowercasing, then validates basic email
* structure. It intentionally does not send verification emails or check
* uniqueness in application code; that belongs to services/database constraints.
*/
export declare class EmailField extends StringField {
readonly config: EmailFieldConfig;
constructor(config?: EmailFieldConfig);
/**
* Parses and normalises email input.
*/
protected parse(input: unknown): string | null;
protected defaultFormComponent(): string;
getValidationRules(ctx?: FieldContext): ValidationRule[];
/**
* Adds basic email-format validation.
*/
protected collectErrors(state: BasicFieldState<string | null>): Promise<FieldError[]>;
}
Url field
ts
import { BasicFieldState, FieldContext, FieldError } from '../FieldType.js';
import type { ValidationRule } from '../../validation/index.js';
import { TextField, type TextFieldConfig } from './TextField.js';
/**
* Configuration for URL fields.
*/
export interface UrlFieldConfig extends TextFieldConfig {
/** Allowed URL protocols. Defaults to HTTP and HTTPS. */
allowedProtocols?: string[];
/** Whether the hostname must contain a dot. Defaults to true. */
requirePublicHostname?: boolean;
/** Protocol to prepend when users omit one. Defaults to `https://`. */
defaultProtocol?: 'http://' | 'https://';
}
/**
* URL field with request-friendly normalization.
*
* It accepts values with or without a protocol, trims whitespace, normalises via
* the platform URL parser, and returns `null` for values that cannot be saved as
* public URLs.
*/
export declare class UrlField extends TextField {
readonly config: UrlFieldConfig;
constructor(config?: UrlFieldConfig);
protected parse(input: unknown): string | null;
protected defaultFormComponent(): string;
getValidationRules(ctx?: FieldContext): ValidationRule[];
protected collectErrors(state: BasicFieldState<string | null>): Promise<FieldError[]>;
private normalizeUrl;
}
Timestamp field
ts
import { BasicFieldState, DbSchemaPart, DbWriteData, DbWriteOptions, FieldConfig, FieldContext, FieldType } from '../FieldType.js';
/**
* Configuration for timestamp/date-time fields.
*/
export interface TimestampFieldConfig extends FieldConfig {
/** Timestamp precision, e.g. 0 for `timestamp(0)`. */
precision?: number;
/** Automatically set the timestamp on create/update. */
auto?: 'create' | 'update' | 'both';
}
/**
* Timestamp field using `Date | null` in app memory.
*
* The database driver may return dates as Date objects or strings depending on
* dialect/configuration; this field normalises both to `Date`.
*/
export declare class TimestampField extends FieldType<Date | null, Date | string | null, string | null, unknown, BasicFieldState<Date | null>> {
readonly config: TimestampFieldConfig;
constructor(config?: TimestampFieldConfig);
/**
* Parses app input into a Date object.
*/
protected parse(input: unknown): Date | null;
/**
* Converts database value into app-memory Date.
*/
protected fromDbValue(input: unknown): Date | null;
/**
* Converts app-memory Date to database value.
*/
protected toDbValue(input: Date | null): Date | null;
protected defaultFormComponent(): string;
protected defaultSearchFilterComponent(): string | null;
/**
* Returns an ISO string for JSON output.
*/
getDisplayValue(state: BasicFieldState<Date | null>, ctx?: FieldContext): string | null | undefined;
/**
* Automatically sets create/update timestamps when configured.
*/
getDataForDb(state: BasicFieldState<Date | null>, options: DbWriteOptions): Promise<DbWriteData>;
getDataForDb(state: BasicFieldState<Date | null>, ctx: FieldContext, options: DbWriteOptions): Promise<DbWriteData>;
/**
* Describes the timestamp database column.
*/
getDbSchema(ctx?: FieldContext): DbSchemaPart;
}
Ulid field
ts
import { BasicFieldState, DbSchemaPart, DbWriteData, DbWriteOptions, FieldContext, FieldError } from '../FieldType.js';
import type { ValidationRule } from '../../validation/index.js';
import { StringField, StringFieldConfig } from './StringField.js';
/**
* Configuration for ULID fields.
*/
export interface UlidFieldConfig extends StringFieldConfig {
/**
* Character length. ULIDs are canonically 26 characters.
*/
length?: 26;
/**
* Whether the field should generate a ULID automatically.
*
* Kept as serialisable data so this config can be stored in JSON/database.
*/
generated?: boolean | 'ulid' | 'db';
/**
* Whether values should be normalised to uppercase.
*
* ULIDs are case-insensitive, but canonical representation is uppercase.
*/
uppercase?: boolean;
}
/**
* ULID field stored as `char(26)` by default.
*
* ULIDs are useful primary keys because their string representation sorts
* approximately by creation time.
*/
export declare class UlidField extends StringField {
readonly config: UlidFieldConfig;
constructor(config?: UlidFieldConfig);
/**
* Creates per-record state.
*
* If generated is enabled, this creates the ULID immediately so `record.id`
* is available before save.
*/
createState(ctx?: FieldContext): BasicFieldState<string | null>;
/**
* Parses app input into canonical ULID form.
*/
protected parse(input: unknown): string | null;
/**
* Returns request-level validation rules for ULID input.
*/
getValidationRules(ctx?: FieldContext): ValidationRule[];
/**
* Converts this field to database write data.
*
* If `generated: 'db'` and the value is empty, the column is omitted so the
* database can provide the value.
*/
getDataForDb(state: BasicFieldState<string | null>, options: DbWriteOptions): Promise<DbWriteData>;
getDataForDb(state: BasicFieldState<string | null>, ctx: FieldContext, options: DbWriteOptions): Promise<DbWriteData>;
/**
* Adds ULID-format validation when a value is present.
*/
protected collectErrors(state: BasicFieldState<string | null>): Promise<FieldError[]>;
/**
* Describes a `char(26)` database column.
*/
getDbSchema(ctx?: FieldContext): DbSchemaPart;
/**
* Returns true when this field should generate ULIDs in application code.
*/
protected shouldGenerateInApp(): boolean;
}
CharUuid field
ts
import { BasicFieldState, DbSchemaPart, FieldContext, FieldError } from '../FieldType.js';
import type { ValidationRule } from '../../validation/index.js';
import { StringField, StringFieldConfig } from './StringField.js';
/**
* Configuration for textual UUID fields stored as `char(36)` by default.
*/
export interface CharUuidFieldConfig extends StringFieldConfig {
/** Character length. Defaults to 36. */
length?: number;
}
/**
* UUID-like string field stored as `char(36)`.
*
* This fits schemas that store UUIDs as text rather than using the native
* PostgreSQL `uuid` type.
*/
export declare class CharUuidField extends StringField {
readonly config: CharUuidFieldConfig;
constructor(config?: CharUuidFieldConfig);
getValidationRules(ctx?: FieldContext): ValidationRule[];
/**
* Adds simple UUID-format validation when a value is present.
*/
protected collectErrors(state: BasicFieldState<string | null>): Promise<FieldError[]>;
/**
* Describes a `char(36)` database column.
*/
getDbSchema(ctx?: FieldContext): DbSchemaPart;
}
Json field
ts
import { BasicFieldState, DbSchemaPart, FieldConfig, FieldContext, FieldType } from '../FieldType.js';
/**
* Configuration for permissive JSON fields stored in native JSON columns.
*/
export interface JsonFieldConfig extends FieldConfig {
}
/**
* Field that stores JSON-compatible values and persists them as JSON text.
*/
export declare class JsonField<TValue = unknown> extends FieldType<TValue, string | TValue | null, TValue, unknown, BasicFieldState<TValue>> {
readonly config: JsonFieldConfig;
/**
* Creates a permissive JSON field.
*/
constructor(config?: JsonFieldConfig);
/**
* Parses app input. Strings are treated as JSON documents.
*/
protected parse(input: unknown): TValue;
/**
* Converts a database JSON string or decoded JSON value into app memory.
*/
protected fromDbValue(input: string | TValue | null): TValue;
/**
* Converts app memory into database JSON storage.
*/
protected toDbValue(input: TValue): string | null;
/**
* Provides the default form control for editing arbitrary JSON.
*/
protected defaultFormComponent(): string;
/**
* Disables default search filtering for JSON fields.
*/
protected defaultSearchFilterComponent(): string | null;
/**
* Describes the database column used by this JSON field.
*/
getDbSchema(ctx?: FieldContext): DbSchemaPart;
}
JsonString field
ts
import { DbSchemaPart, FieldConfig, FieldContext } from '../FieldType.js';
import { JsonField } from './JsonField.js';
export type JsonStringFieldDbType = 'json' | 'text' | 'longtext';
/**
* Configuration for JSON values serialised into database storage.
*/
export interface JsonStringFieldConfig extends FieldConfig {
/** Database storage type. Defaults to `json`. Prefer `field.jsonText()` or `field.jsonLongText()` over setting this directly. */
dbType?: JsonStringFieldDbType;
}
/**
* Field that stores an object/array in app memory but persists JSON to the DB.
*/
export declare class JsonStringField<TValue> extends JsonField<TValue | null> {
readonly config: JsonStringFieldConfig;
constructor(config?: JsonStringFieldConfig);
/**
* Describes the database column used by this JSON string field.
*/
getDbSchema(ctx?: FieldContext): DbSchemaPart;
}
StringList field
ts
import { BasicFieldState, FieldContext, FieldError } from '../FieldType.js';
import type { ValidationRule } from '../../validation/index.js';
import { JsonField, type JsonFieldConfig } from './JsonField.js';
/**
* Configuration for JSON-backed lists of short strings.
*/
export interface StringListFieldConfig extends JsonFieldConfig {
/** Maximum number of saved items. Leave unset to allow storage-sized lists. */
maxItems?: number;
/** Whether values beyond maxItems are truncated. Defaults to true. */
truncate?: boolean;
}
/**
* Stores a normalised string array in app memory and JSON in the database.
*/
export declare class StringListField extends JsonField<string[]> {
readonly config: StringListFieldConfig;
/**
* Creates a JSON-backed string list field with an empty-array default.
*/
constructor(config?: StringListFieldConfig);
/**
* Normalises supported input into a deduplicated list of trimmed strings.
*/
protected parse(input: unknown): string[];
/**
* Hydrates persisted JSON or already-decoded storage into app values.
*/
protected fromDbValue(input: unknown): string[];
/**
* Serialises the normalised list for database storage.
*/
protected toDbValue(input: string[]): string;
/**
* Provides the default form control for editing JSON string lists.
*/
protected defaultFormComponent(): string;
/**
* Disables default search filtering for list fields.
*/
protected defaultSearchFilterComponent(): string | null;
/**
* Publishes request validation rules for list-shaped input.
*/
getValidationRules(ctx?: FieldContext): ValidationRule[];
/**
* Reports an item-count validation error when maxItems is configured.
*/
protected collectErrors(state: BasicFieldState<string[]>): Promise<FieldError[]>;
/**
* Extracts candidate string values from arrays, JSON, and delimited text.
*/
private rawValues;
}
Password field
ts
import { DbRow, DbSchemaPart, DbWriteData, DbWriteOptions, FieldConfig, FieldContext, FieldError, FieldType } from '../FieldType.js';
import type { ValidationRule } from '../../validation/index.js';
import { type PasswordHash } from '../../auth/passwordHash.js';
/**
* Per-record runtime state for a password field.
*
* The normal app-facing value is always `null`, but the state may hold an
* existing hash or a pending plaintext password waiting to be hashed on save.
*/
export interface PasswordFieldState {
/** Hash currently stored in memory, usually loaded from the database. */
hash: string | null;
/** Plaintext assigned by the app but not yet converted to a hash. */
pendingPlainText: string | null;
/** Hash generated during `getDataForDb()`, committed in `markClean()`. */
preparedHash: string | null;
/** Whether the password should be included in the next update. */
dirty: boolean;
/** Validation errors for this field state. */
errors: FieldError[];
}
/**
* Configuration for password fields.
*/
export interface PasswordFieldConfig extends FieldConfig {
/** Minimum plaintext password length. Defaults to 12. */
minLength?: number;
/** Database varchar length for the hash. Defaults to 255. */
length?: number;
}
/**
* Password field.
*
* App-facing behaviour:
* - `user.password = 'plain text'` stores pending plaintext in field state.
* - `user.password` returns `null`.
* - `user.toJSON()` omits the password.
* - `user.save()` hashes pending plaintext and writes the hash to the database.
*
* The field clears plaintext after successful database conversion.
*/
export declare class PasswordField extends FieldType<null, string | null, undefined, unknown, PasswordFieldState> {
readonly config: PasswordFieldConfig;
constructor(config: PasswordFieldConfig);
/**
* Creates password-specific per-record state.
*/
createState(): PasswordFieldState;
/**
* Stores pending plaintext for hashing later during `getDataForDb()`.
*/
setValue(state: PasswordFieldState, input: unknown, ctx?: FieldContext): void;
/**
* Never exposes a password or hash through normal property access.
*/
getValue(): null;
protected defaultFormComponent(): string;
protected defaultSearchFilterComponent(): string | null;
getValidationRules(ctx?: FieldContext): ValidationRule[];
/**
* Hydrates the existing password hash from a raw database row.
*/
setFromDb(state: PasswordFieldState, row: DbRow, ctx?: FieldContext): void;
/**
* Validates required/minimum length rules.
*/
validate(state: PasswordFieldState, ctx?: FieldContext): Promise<FieldError[]>;
/**
* Produces the database hash column.
*/
getDataForDb(state: PasswordFieldState, options: DbWriteOptions): Promise<DbWriteData>;
getDataForDb(state: PasswordFieldState, ctx: FieldContext, options: DbWriteOptions): Promise<DbWriteData>;
/**
* Commits the prepared hash and clears plaintext after successful save.
*/
markClean(state: PasswordFieldState): void;
/**
* Verifies a plaintext password against this field's hydrated hash.
*/
verifyPassword(plainText: string, passwordHash?: PasswordHash): Promise<boolean>;
/**
* Passwords are omitted from JSON output.
*/
getDisplayValue(): undefined;
/**
* Prevents accidental password querying.
*/
getQueryValue(): never;
/**
* Describes the password hash database column.
*/
getDbSchema(ctx?: FieldContext): DbSchemaPart;
}
Link field
ts
import type { Knex } from 'knex';
import type { ActiveRecord, ActiveRecordClass } from '../ActiveRecord.js';
import { DbRow, DbSchemaPart, DbWriteData, DbWriteOptions, FieldConfig, FieldContext, FieldError, FieldRenderOptions, FieldType } from '../FieldType.js';
/**
* Lightweight reference to another ActiveRecord.
*
* A link field stores this instead of implicitly loading related records. This
* avoids hidden N+1 queries while still giving a convenient `load()` method.
*/
export declare class EntityRef<TRecord extends ActiveRecord> {
/** Target model class. */
readonly target: () => ActiveRecordClass<TRecord>;
/** Primary-key value of the target record. */
readonly id: unknown;
/** Optional already-loaded record. */
private loadedRecord?;
/**
* Returns the primary-key value from a nullable entity reference.
*
* @param ref - Entity reference to read.
* @param message - Error message when the reference or id is missing.
* @returns Primary-key value stored on the reference.
*/
static idOrFail<TRecord extends ActiveRecord>(ref: EntityRef<TRecord> | null | undefined, message?: string): unknown;
/**
* Returns the primary-key value from a nullable entity reference as a string.
*
* @param ref - Entity reference to read.
* @param message - Error message when the reference or id is missing.
* @returns Primary-key value converted to a string.
*/
static stringIdOrFail<TRecord extends ActiveRecord>(ref: EntityRef<TRecord> | null | undefined, message?: string): string;
constructor(
/** Target model class. */
target: () => ActiveRecordClass<TRecord>,
/** Primary-key value of the target record. */
id: unknown,
/** Optional already-loaded record. */
loadedRecord?: (TRecord | null) | undefined);
/**
* Returns the primary-key value stored on this reference.
*
* @param message - Error message when the id is missing.
* @returns Primary-key value stored on the reference.
*/
idOrFail(message?: string): unknown;
/**
* Returns the primary-key value stored on this reference as a string.
*
* @param message - Error message when the id is missing.
* @returns Primary-key value converted to a string.
*/
stringIdOrFail(message?: string): string;
/**
* Returns true if the referenced record has already been loaded.
*
* @returns True when a loaded-record state is present.
*/
isLoaded(): boolean;
/**
* Returns the loaded record if available, otherwise null.
*
* @returns Loaded record or null.
*/
getLoaded(): TRecord | null;
/**
* Explicitly loads the referenced record.
*
* @param db - Optional database connection/session.
* @returns Referenced record or null when it cannot be found.
*/
load(db?: Knex): Promise<TRecord | null>;
/**
* Explicitly loads the referenced record and fails when it cannot be found.
*
* @returns Referenced record.
*/
loadOrFail(): Promise<TRecord>;
}
/**
* Per-record state for a link field.
*/
export interface LinkFieldState<TRecord extends ActiveRecord = ActiveRecord> {
/** Referenced primary-key value. */
id: unknown | null;
/** Optional already-loaded record. */
loadedRecord: TRecord | null;
/** Whether the optional related record was explicitly loaded. */
loaded: boolean;
/** Whether JSON/display output should include the loaded record. */
displayLoaded: boolean;
/** Whether the link changed since hydration. */
dirty: boolean;
/** Validation errors for this field state. */
errors: FieldError[];
}
/**
* Configuration for link/foreign-key fields.
*/
export interface LinkFieldConfig<TRecord extends ActiveRecord> extends FieldConfig {
/** Target model class. Wrapped in a function to allow circular model refs. */
target: () => ActiveRecordClass<TRecord>;
/** Name of the local FK column. Defaults to `${fieldName}_id`. */
column?: string;
/** Optional ON DELETE action for schema generation. */
onDelete?: 'CASCADE' | 'RESTRICT' | 'SET NULL' | 'NO ACTION';
/** Optional ON UPDATE action for schema generation. */
onUpdate?: 'CASCADE' | 'RESTRICT' | 'SET NULL' | 'NO ACTION';
}
/**
* Link/foreign-key field.
*
* App-facing values accepted by `setValue()`:
* - an ID value
* - an ActiveRecord-like object with the target primary-key property
* - an `EntityRef`
*
* Normal reads return an `EntityRef`, not the loaded record. Loading is explicit:
*
* ```ts
* const author = await post.author.load();
* ```
*/
export declare class LinkField<TRecord extends ActiveRecord> extends FieldType<EntityRef<TRecord> | null, unknown | null, unknown | null, unknown, LinkFieldState<TRecord>> {
readonly config: LinkFieldConfig<TRecord>;
constructor(config: LinkFieldConfig<TRecord>);
/**
* Creates link-specific per-record state.
*/
createState(): LinkFieldState<TRecord>;
/**
* Default FK column convention: `author` -> `author_id`.
*/
getColumn(ctx?: FieldContext): string;
protected defaultFormComponent(): string;
protected defaultSearchFilterComponent(): string | null;
protected defaultFormComponentProps(options: FieldRenderOptions): Record<string, unknown>;
protected defaultSearchFilterComponentProps(options: FieldRenderOptions): Record<string, unknown>;
/**
* Stores the referenced primary-key value and optional loaded record.
*/
setValue(state: LinkFieldState<TRecord>, input: unknown, ctx?: FieldContext): void;
/**
* Returns a lightweight reference object for app reads.
*/
getValue(state: LinkFieldState<TRecord>, ctx?: FieldContext): EntityRef<TRecord> | null;
/**
* Hydrates the FK value from the database row.
*/
setFromDb(state: LinkFieldState<TRecord>, row: DbRow, ctx?: FieldContext): void;
/**
* Validates required link fields.
*/
validate(state: LinkFieldState<TRecord>, ctx?: FieldContext): Promise<FieldError[]>;
/**
* Returns FK database data.
*/
getDataForDb(state: LinkFieldState<TRecord>, options: DbWriteOptions): Promise<DbWriteData>;
getDataForDb(state: LinkFieldState<TRecord>, ctx: FieldContext, options: DbWriteOptions): Promise<DbWriteData>;
/**
* Marks the FK as clean after save.
*/
markClean(state: LinkFieldState<TRecord>): void;
/**
* Stores a loaded relation for JSON/display output without dirtying the FK.
*/
setBoundLoadedRecord(record: TRecord | null): void;
/**
* Serialises link fields as IDs unless the relation was explicitly included.
*/
getDisplayValue(state: LinkFieldState<TRecord>): unknown;
/**
* Converts query input to a FK ID.
*/
getQueryValue(input: unknown): unknown;
/**
* Describes the FK column and foreign-key metadata.
*/
getDbSchema(ctx?: FieldContext): DbSchemaPart;
}
Vector field
ts
import type { ValidationRule } from '../../validation/index.js';
import { type BasicFieldState, type DbSchemaPart, type FieldConfig, type FieldContext, type FieldError, type FieldRenderOptions, FieldType } from '../FieldType.js';
import type { DatabaseValueOptions } from '../dialects/index.js';
type VectorDbValue = Uint8Array | string | number[] | null;
/**
* Configuration for native database vectors such as embeddings.
*/
export interface VectorFieldConfig extends FieldConfig {
/** Expected number of vector dimensions. Leave unset to use the database default. */
dimensions?: number;
/** Whether to create a database-native vector index. Defaults to true for required vectors. */
index?: boolean;
}
/**
* Stores an embedding/vector as a native database VECTOR column.
*/
export declare class VectorField extends FieldType<number[] | null, unknown, number[] | null, unknown, BasicFieldState<number[] | null>> {
readonly config: VectorFieldConfig;
/**
* Creates a native vector field and validates schema-level options.
*/
constructor(config?: VectorFieldConfig);
/**
* Parses JSON text, decoded arrays, or binary vector input into app memory.
*/
protected parse(input: unknown): number[] | null;
/**
* Hydrates binary vectors, vector text, or already-decoded arrays.
*/
protected fromDbValue(input: VectorDbValue): number[] | null;
/**
* Converts app-memory vectors into the active dialect's native vector value.
*/
protected toDbValue(input: number[] | null, options?: DatabaseValueOptions): unknown;
/**
* Uses a JSON editor for manual vector editing in generated forms.
*/
protected defaultFormComponent(): string;
/**
* Disables default scalar search filtering for vector fields.
*/
protected defaultSearchFilterComponent(): string | null;
/**
* Adds dimension metadata to generated vector form props.
*/
protected defaultFormComponentProps(options: FieldRenderOptions): Record<string, unknown>;
/**
* Publishes request validation rules for array-shaped vector input.
*/
getValidationRules(ctx?: FieldContext): ValidationRule[];
/**
* Describes the native VECTOR column used by this field.
*/
getDbSchema(ctx?: FieldContext): DbSchemaPart;
/**
* Reports non-array, non-number, and dimension mismatch errors.
*/
protected collectErrors(state: BasicFieldState<number[] | null>): Promise<FieldError[]>;
/**
* Treats an empty vector as empty for required validation.
*/
protected isEmpty(value: unknown): boolean;
}
export {};
Encrypted JSON field
ts
import { Buffer } from 'node:buffer';
import { type BasicFieldState, type DbSchemaPart, type FieldConfig, type FieldContext, FieldType } from '../FieldType.js';
/**
* Configuration for an authenticated encrypted JSON field.
*
* Encrypted fields are always hidden, cannot define database defaults or
* indexes, and use long text storage because randomized ciphertext is not
* queryable JSON.
*/
export interface EncryptedJsonFieldConfig extends Omit<FieldConfig, 'hidden' | 'default' | 'unique' | 'index' | 'indexName' | 'indexes'> {
}
/**
* Error raised when an encrypted JSON field cannot access or use the
* application security service.
*/
export declare class EncryptedJsonFieldError extends Error {
/**
* Creates an encrypted-field error with a user-safe message.
*
* @param message - Error message that must not contain plaintext or ciphertext.
* @param options - Optional underlying security-service error.
*/
constructor(message: string, options?: ErrorOptions);
}
/**
* Field that keeps decoded JSON in application memory and delegates encrypted
* storage to the active app's central security service.
*
* Ciphertext is bound to the model table and field column through additional
* authenticated data, preventing encrypted values from being moved between
* unrelated fields without detection.
*/
export declare class EncryptedJsonField<TValue> extends FieldType<TValue | null, string | Buffer | null, undefined, unknown, BasicFieldState<TValue | null>> {
#private;
readonly config: EncryptedJsonFieldConfig;
/**
* Creates an encrypted JSON field that is always omitted from display data.
*
* @param config - Normal field configuration for the encrypted column.
*/
constructor(config?: EncryptedJsonFieldConfig);
/**
* Prevents encrypted values from being exposed through forms or JSON output.
*
* @returns Undefined for every encrypted value.
*/
getDisplayValue(): undefined;
/**
* Prevents equality queries against randomized ciphertext.
*
* @returns This method never returns.
*/
getQueryValue(): never;
/**
* Describes the long text column used for versioned encrypted payloads.
*
* @param ctx - Model and database dialect context.
* @returns Schema metadata for the encrypted column.
*/
getDbSchema(ctx?: FieldContext): DbSchemaPart;
/**
* Parses decoded input or a JSON document into application memory.
*
* @param input - Decoded JSON value, JSON string, or empty value.
* @returns Parsed value or null.
*/
protected parse(input: unknown): TValue | null;
/**
* Decrypts and parses one database value through the application security service.
*
* @param input - Versioned ciphertext loaded from the database.
* @returns Decoded JSON value or null.
*/
protected fromDbValue(input: string | Buffer | null): TValue | null;
/**
* Serializes and encrypts one application value through the security service.
*
* @param input - Decoded JSON value held by the model.
* @returns Versioned authenticated ciphertext or null.
*/
protected toDbValue(input: TValue | null): string | null;
}