/** * @db4/core - Core Type Definitions * * Shared TypeScript types used across all @db4 packages. * * @packageDocumentation */ /** * Brand symbol for nominal typing. * This creates a unique brand that cannot be accidentally satisfied. */ declare const __brand: unique symbol; /** * Brand type utility for creating nominal types. * Branded types prevent accidental interchange of structurally identical types. */ export type Brand = T & { readonly [__brand]: B; }; /** * Branded string type for document IDs. * Prevents accidental use of arbitrary strings as document IDs. */ export type DocumentId = Brand; /** * Branded string type for batch IDs. * Prevents accidental use of arbitrary strings as batch IDs. */ export type BatchId = Brand; /** * Branded string type for collection names. * Prevents accidental use of arbitrary strings as collection names. */ export type CollectionName = Brand; /** * Branded string type for shard identifiers. * Prevents accidental use of arbitrary strings as shard IDs. */ export type ShardId = Brand; /** * Branded number type for timestamps (milliseconds since epoch). * Prevents accidental use of arbitrary numbers as timestamps. */ export type Timestamp = Brand; /** * Branded number type for version numbers. * Prevents accidental use of arbitrary numbers as versions. */ export type Version = Brand; /** * Creates a DocumentId from a string. * Use this to safely convert validated strings to DocumentId. * @throws TypeError if the id is empty or whitespace-only */ export declare function createDocumentId(id: string): DocumentId; /** * Creates a BatchId from a string. * Use this to safely convert validated strings to BatchId. * @throws TypeError if the id is empty or whitespace-only */ export declare function createBatchId(id: string): BatchId; /** * Creates a CollectionName from a string. * Use this to safely convert validated strings to CollectionName. * @throws TypeError if the name is empty, whitespace-only, or starts with a number */ export declare function createCollectionName(name: string): CollectionName; /** * Creates a ShardId from a string. * Use this to safely convert validated strings to ShardId. * @throws TypeError if the id is empty or whitespace-only */ export declare function createShardId(id: string): ShardId; /** * Creates a Timestamp from a number. * Use this to safely convert validated numbers to Timestamp. * @throws TypeError if the value is not a finite non-negative number */ export declare function createTimestamp(ms: number): Timestamp; /** * Creates a Version from a number. * Use this to safely convert validated numbers to Version. * @throws TypeError if the value is not a finite non-negative integer */ export declare function createVersion(version: number): Version; /** * Base document interface - all documents must have an id field. * Additional properties are allowed via index signature. */ export interface Document { id: string; [key: string]: unknown; } /** * Document metadata stored alongside each document. */ export interface DocumentMeta { version: number; createdAt: number; updatedAt: number; } /** * Stored document with metadata. * Extends Document and adds the _meta property. */ export interface StoredDocument extends Document { _meta: DocumentMeta; } /** * Metadata for a document batch. */ export interface BatchMetadata { collection: string; shard: string; createdAt: number; } /** * Document batch for efficient storage operations. */ export interface DocumentBatch { batchId: string; documents: StoredDocument[]; metadata: BatchMetadata; } /** * Primitive types supported by the schema system. * Aligned with @icetype/core PrimitiveType for consistent type handling. * * Type categories: * - Strings: string, text * - Integers: int, long, bigint * - Floats: float, double * - Booleans: bool, boolean * - Temporal: timestamp, timestamptz, date, time * - Other: uuid, json, binary */ export type PrimitiveType = 'string' | 'text' | 'int' | 'long' | 'bigint' | 'float' | 'double' | 'bool' | 'boolean' | 'timestamp' | 'timestamptz' | 'date' | 'time' | 'uuid' | 'json' | 'binary'; /** * Canonical primitive type (normalized form). * Used to map alias types to their canonical form. */ export type CanonicalPrimitiveType = 'string' | 'text' | 'int' | 'long' | 'bigint' | 'float' | 'double' | 'boolean' | 'timestamp' | 'timestamptz' | 'date' | 'time' | 'uuid' | 'json' | 'binary'; /** * JavaScript/TypeScript runtime type mapping for primitive types. */ export type RuntimeType = 'string' | 'number' | 'bigint' | 'boolean' | 'object'; /** * SQLite storage type mapping for primitive types. */ export type SQLiteType = 'TEXT' | 'INTEGER' | 'REAL' | 'BLOB'; /** * Maps a PrimitiveType to its canonical form. * Handles aliases like 'bool' -> 'boolean'. * * @param type - The primitive type to normalize * @returns The canonical form of the type */ export declare function normalizeType(type: PrimitiveType): CanonicalPrimitiveType; /** * Maps a PrimitiveType to its JavaScript/TypeScript runtime type. * * @param type - The primitive type to map * @returns The corresponding JS/TS runtime type */ export declare function toRuntimeType(type: PrimitiveType): RuntimeType; /** * Maps a PrimitiveType to its SQLite storage type. * * @param type - The primitive type to map * @returns The corresponding SQLite type */ export declare function toSQLiteType(type: PrimitiveType): SQLiteType; /** * Checks if a type is an alias (e.g., 'bool' is alias for 'boolean'). * * @param type - The primitive type to check * @returns true if the type is an alias */ export declare function isTypeAlias(type: PrimitiveType): boolean; /** * Gets the primary type for an alias. * * @param type - The alias type * @returns The primary type, or the input if not an alias */ export declare function getPrimaryType(type: PrimitiveType): PrimitiveType; /** * Checks if two primitive types are equivalent (considering aliases). * * @param a - First type * @param b - Second type * @returns true if the types are equivalent */ export declare function areTypesEquivalent(a: PrimitiveType, b: PrimitiveType): boolean; /** * Field modifiers for schema definitions. * - '!' marks a field as required * - '?' marks a field as optional * - '#' marks a field as indexed * - '[]' marks a field as an array * - null indicates no modifier */ export type FieldModifier = '!' | '?' | '#' | '[]' | null; /** * Field definition for schema. */ export interface FieldDefinition { name: string; type: PrimitiveType | string; modifier: FieldModifier; isArray: boolean; } /** * Filter operators for query conditions. */ export type FilterOperator = '$eq' | '$ne' | '$gt' | '$gte' | '$lt' | '$lte' | '$in' | '$nin' | '$contains' | '$startsWith' | '$endsWith' | '$exists'; /** * Query filter condition. */ export interface QueryFilter { field: string; operator: FilterOperator; value: unknown; } /** * Sort direction for query results. */ export type SortDirection = 'asc' | 'desc'; /** * Sort specification for query results. */ export interface SortSpec { field: string; direction: SortDirection; } /** * Query result container. * Generic over the document type, defaulting to StoredDocument. */ export interface QueryResult { documents: T[]; total: number; hasMore: boolean; cursor?: string | undefined; } /** * Query options for filtering, sorting, and pagination. */ export interface QueryOptions { filters?: QueryFilter[]; sort?: SortSpec[]; limit?: number; offset?: number; projection?: string[]; } /** * Query execution plan for analyzing query performance. */ export interface QueryPlan { strategy: 'index_lookup' | 'index_scan' | 'batch_scan' | 'full_scan'; indexUsed?: string; estimatedCost: number; estimatedRows: number; /** Memory used by the query result in bytes */ memoryUsed?: number; /** Peak memory used during query execution in bytes */ peakMemory?: number; } /** * Shard metadata for tracking shard state. */ export interface ShardMetadata { shardId: string; shardKey: string; colo?: string; tenant?: string; partition?: string; createdAt: number; lastActivityAt: number; documentCount: number; sizeBytes: number; } /** * Shard routing context for determining target shard. */ export interface ShardRoutingContext { tenant?: string; userId?: string; colo?: string; partitionKey?: string; resourceKey?: string; } /** * Shard routing result with target shard information. */ export interface ShardRoutingResult { shardId: string; shardKey: string; colo?: string; isLocal: boolean; } /** * Isolation level for transactions. */ export type IsolationLevel = 'read_committed' | 'repeatable_read' | 'serializable'; /** * Options for beginning a transaction. */ export interface TransactionOptions { /** Isolation level for the transaction (default: 'repeatable_read') */ isolationLevel?: IsolationLevel; /** Timeout in milliseconds for the transaction (default: 30000) */ timeout?: number; /** Optional transaction ID (auto-generated if not provided) */ transactionId?: string; } /** * Conflict information for a specific document. */ export interface ConflictInfo { /** Document ID that had a conflict */ documentId: string; /** Collection the document belongs to */ collection: string; /** Version when the document was read */ originalVersion: number; /** Current version in the database */ currentVersion: number; } /** * CDC operation type. */ export type CDCOperation = 'INSERT' | 'UPDATE' | 'DELETE' | 'BATCH_INSERT' | 'BATCH_DELETE' | 'SCHEMA_CHANGE'; /** * CDC log entry for change tracking. */ export interface CDCLogEntry { sequenceId: number; operation: CDCOperation; collection: string; documentId: string; timestamp: number; shardId: string; beforeState?: StoredDocument; afterState?: StoredDocument; changedFields?: string[]; transactionId?: string; synced: boolean; } /** * CDC cursor for streaming. */ export interface CDCCursor { shardId: string; lastSequenceId: number; lastTimestamp: number; } /** * CDC batch for streaming. */ export interface CDCBatch { shardId: string; entries: CDCLogEntry[]; fromSequence: number; toSequence: number; timestamp: number; } /** * Options for CDC streaming. */ export interface CDCStreamOptions { fromSequence?: number; fromTimestamp?: number; batchSize?: number; collections?: string[]; operations?: CDCOperation[]; includeBeforeState?: boolean; includeAfterState?: boolean; } /** * Result from CDC streaming. */ export interface CDCStreamResult { entries: CDCLogEntry[]; cursor: CDCCursor; hasMore: boolean; } /** * CDC checkpoint for tracking sync progress. */ export interface CDCCheckpoint { shardId: string; sequenceId: number; timestamp: number; icebergSnapshotId?: string; } /** * Filter options for CDC entries. */ export interface CDCFilter { collections?: string[]; operations?: CDCOperation[]; documentIds?: string[]; fromTimestamp?: number; toTimestamp?: number; } /** * Collection statistics. */ export interface CollectionStats { collection: string; documentCount: number; batchCount: number; totalSizeBytes: number; avgDocumentSize: number; indexCount: number; } /** * Shard statistics. */ export interface ShardStats { shardId: string; collections: CollectionStats[]; totalDocuments: number; totalBatches: number; totalSizeBytes: number; cdcLogSize: number; lastCDCSequence: number; createdAt: number; lastActivityAt: number; } /** * Batch size tier for document packing. */ export type BatchSizeTier = 64 | 128 | 256; /** * Core db4 configuration options. */ export interface DB4Config { /** Shard ID for this instance */ shardId: string; /** Enable schemaless mode (dynamic schema discovery) */ schemaless?: boolean; /** Batch size tier: 64, 128, or 256 documents per batch */ batchSizeTier?: BatchSizeTier; /** Enable CDC logging */ enableCDC?: boolean; /** CDC batch size before flush */ cdcBatchSize?: number; /** Maximum document size in bytes */ maxDocumentSize?: number; /** Maximum batch size in bytes (default: 900KB to stay under 1MB) */ maxBatchSize?: number; /** Maximum result size in bytes for query() to prevent OOM (default: 10MB) */ maxResultSize?: number; /** Threshold for auto-switching to streaming mode (number of documents) */ streamingThreshold?: number; /** Maximum memory budget for query operations in bytes */ maxQueryMemory?: number; /** Enable query logging */ logQueries?: boolean; } /** * Default configuration values. */ export declare const DEFAULT_CONFIG: Required; /** * Storage configuration for IceTypeDO. */ export interface StorageConfig { type: 'durable-object'; sqliteEnabled: boolean; transientAllocLimit?: number; } /** * CDC configuration for IceTypeDO. */ export interface CDCConfig { enabled: boolean; batchSize: number; flushInterval: number; r2Bucket?: string; icebergTable?: string; } /** * Query configuration for IceTypeDO. */ export interface QueryConfig { defaultLimit: number; maxLimit: number; timeout: number; enableCaching?: boolean; } /** * Sharding configuration for IceTypeDO. */ export interface ShardingConfig { enabled: boolean; strategy: 'hash' | 'range'; partitionKey: string; maxShards?: number; } /** * Logging configuration for IceTypeDO. */ export interface LoggingConfig { level: 'debug' | 'info' | 'warn' | 'error'; enableMetrics?: boolean; enableTracing?: boolean; } /** * Performance configuration for IceTypeDO. */ export interface PerformanceConfig { enableBatching?: boolean; batchFlushInterval?: number; enableCompression?: boolean; cacheSize?: number; } /** * Full IceTypeDO configuration extending DB4Config. */ export interface IceTypeDOConfig extends DB4Config { storage: StorageConfig; cdc?: CDCConfig; query?: QueryConfig; sharding?: ShardingConfig; logging?: LoggingConfig; performance?: PerformanceConfig; } /** * Result of config validation. */ export interface ConfigValidationResult { valid: boolean; errors: string[]; warnings?: string[]; } /** * Event types for sync events. */ export type EventType = 'document:created' | 'document:updated' | 'document:deleted' | 'batch:created' | 'batch:updated' | 'schema:updated' | 'cdc:batch'; /** * Sync event for real-time updates. */ export interface SyncEvent { type: EventType; shardId: string; timestamp: number; payload: unknown; } /** * Readonly variant of Document. * All properties are recursively readonly. */ export type ReadonlyDocument = Readonly; /** * Readonly variant of DocumentMeta. */ export type ReadonlyDocumentMeta = Readonly; /** * Readonly variant of StoredDocument. */ export type ReadonlyStoredDocument = Readonly & { readonly _meta: ReadonlyDocumentMeta; }; /** * Readonly variant of BatchMetadata. */ export type ReadonlyBatchMetadata = Readonly; /** * Readonly variant of DocumentBatch. */ export type ReadonlyDocumentBatch = Readonly<{ batchId: string; documents: readonly ReadonlyStoredDocument[]; metadata: ReadonlyBatchMetadata; }>; /** * Readonly variant of QueryFilter. */ export type ReadonlyQueryFilter = Readonly; /** * Readonly variant of SortSpec. */ export type ReadonlySortSpec = Readonly; /** * Readonly variant of QueryOptions. */ export type ReadonlyQueryOptions = Readonly<{ filters?: readonly ReadonlyQueryFilter[]; sort?: readonly ReadonlySortSpec[]; limit?: number; offset?: number; projection?: readonly string[]; }>; /** * Readonly variant of QueryResult. */ export type ReadonlyQueryResult = Readonly<{ documents: readonly T[]; total: number; hasMore: boolean; cursor?: string; }>; /** * Readonly variant of FieldDefinition. */ export type ReadonlyFieldDefinition = Readonly; /** * Partial document for updates (id required, other fields optional). */ export type PartialDocument = Pick & Partial>; /** * Partial document meta for incremental updates. */ export type PartialDocumentMeta = Partial; /** * Input document without metadata (for creation). */ export type DocumentInput = Omit; /** * Update payload with required id and optional fields. */ export type DocumentUpdate = Pick & Partial>; /** * Batch of documents for bulk operations. */ export type DocumentInputBatch = { documents: DocumentInput[]; metadata?: Partial; }; /** * Extracts the document type from a QueryResult. */ export type ExtractDocument = T extends QueryResult ? D : never; /** * Maps a document type to its stored version. */ export type AsStoredDocument = T & { _meta: DocumentMeta; }; /** * Strips metadata from a stored document. */ export type StripMeta = Omit; /** * Picks specific fields from a document type. */ export type ProjectDocument = Pick; /** * Generic result type for operations that can succeed or fail. */ export type Result = { success: true; data: T; } | { success: false; error: E; }; /** * Creates a success result. */ export declare function ok(data: T): Result; /** * Creates a failure result. */ export declare function err(error: E): Result; /** * Check if result is successful. */ export declare function isOk(result: Result): result is { success: true; data: T; }; /** * Check if result is an error. */ export declare function isErr(result: Result): result is { success: false; error: E; }; /** * All valid primitive types as a readonly array. * Useful for validation and iteration. * Aligned with @icetype/core for consistent type handling. */ export declare const PRIMITIVE_TYPES: readonly PrimitiveType[]; /** * All valid filter operators as a readonly array. * Useful for validation and iteration. */ export declare const FILTER_OPERATORS: readonly FilterOperator[]; /** * All valid field modifiers as a readonly array. * Useful for validation and iteration. */ export declare const FIELD_MODIFIERS: readonly FieldModifier[]; /** * All valid sort directions as a readonly array. * Useful for validation and iteration. */ export declare const SORT_DIRECTIONS: readonly SortDirection[]; /** * All valid CDC operations as a readonly array. */ export declare const CDC_OPERATIONS: readonly CDCOperation[]; /** * Valid batch size tiers. */ export declare const BATCH_SIZE_TIERS: readonly BatchSizeTier[]; /** * Creates a CDC cursor with default or specified values. */ export declare function createCDCCursor(shardId: string, lastSequenceId?: number, lastTimestamp?: number): CDCCursor; /** * Encodes a CDC cursor to a base64 string. */ export declare function encodeCDCCursor(cursor: CDCCursor): string; /** * Decodes a base64 string back to a CDC cursor. * @throws Error if the string is invalid */ export declare function decodeCDCCursor(encoded: string): CDCCursor; /** * Creates a CDC batch from entries. */ export declare function createCDCBatch(shardId: string, entries: CDCLogEntry[]): CDCBatch; /** * Merges multiple CDC batches into one. */ export declare function mergeCDCBatches(batches: CDCBatch[]): CDCBatch; /** * Filters CDC entries based on filter criteria. */ export declare function filterCDCEntries(entries: CDCLogEntry[], filter: CDCFilter): CDCLogEntry[]; /** * Type guard for CDC operations. */ export declare function isCDCOperation(value: unknown): value is CDCOperation; /** * Type guard for CDC log entries. */ export declare function isCDCLogEntry(value: unknown): value is CDCLogEntry; /** * Validates a DB4Config object. */ export declare function validateConfig(config: DB4Config): ConfigValidationResult; /** * Deep merges two config objects. */ export declare function mergeConfig(base: T, partial: Partial): T; /** * Creates a config with defaults applied and validates it. * @throws Error if the config is invalid */ export declare function createConfig(overrides: Partial & { shardId: string; }): Required; /** * Type guard for valid batch size tiers. */ export declare function isValidBatchSizeTier(value: unknown): value is BatchSizeTier; /** * Returns a deep copy of the default config. */ export declare function getConfigDefaults(): Required; /** * Normalizes a partial config by filling in defaults. */ export declare function normalizeConfig(partial: Partial): Required; export {}; //# sourceMappingURL=types.d.ts.map