@korajs/core 1.0.0-beta.12 → 1.0.0-beta.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +21 -13
- package/dist/bindings/index.d.cts +26 -6
- package/dist/bindings/index.d.ts +26 -6
- package/dist/{build-scope-map-Cv5HfCQP.d.ts → build-scope-map-CIFa58oA.d.ts} +1 -1
- package/dist/{build-scope-map-CItP1gsz.d.cts → build-scope-map-ClIq_doj.d.cts} +1 -1
- package/dist/{chunk-5IICSH6H.js → chunk-QUD3DMSD.js} +668 -24
- package/dist/chunk-QUD3DMSD.js.map +1 -0
- package/dist/events-BSU-0z5O.d.cts +1737 -0
- package/dist/events-BSU-0z5O.d.ts +1737 -0
- package/dist/index.cjs +2526 -204
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +810 -220
- package/dist/index.d.ts +810 -220
- package/dist/index.js +2012 -337
- package/dist/index.js.map +1 -1
- package/dist/internal.cjs +857 -85
- package/dist/internal.cjs.map +1 -1
- package/dist/internal.d.cts +251 -21
- package/dist/internal.d.ts +251 -21
- package/dist/internal.js +447 -1
- package/dist/internal.js.map +1 -1
- package/dist/sql-gen-ByOZIQU-.d.ts +622 -0
- package/dist/sql-gen-DdOkMojr.d.cts +622 -0
- package/package.json +2 -1
- package/dist/chunk-5IICSH6H.js.map +0 -1
- package/dist/events-D7JCtQSD.d.cts +0 -1010
- package/dist/events-D7JCtQSD.d.ts +0 -1010
- package/dist/operation-BX4ok7U4.d.ts +0 -164
- package/dist/operation-BXvJ6RiA.d.cts +0 -164
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/types.ts","../src/causal/causal-tracker.ts","../src/identifiers/uuid-v7.ts","../src/blob/blob-ref.ts","../src/secret/secret-crypto.ts","../src/secret/secret-transform.ts","../src/operations/apply-result.ts","../src/operations/atomic-ops.ts","../src/operations/replay-record.ts","../src/operations/op-data-binary.ts","../src/scopes/sync-scope-bindings.ts","../src/state-machine/state-machine.ts","../src/schema/define.ts","../src/schema/quote-ident.ts","../src/schema/sql-gen.ts","../src/schema/types.ts","../src/schema/validation.ts","../src/version-vector/version-vector.ts","../src/scopes/build-scope-map.ts","../src/scopes/extract-scope-from-claims.ts","../src/sequences/sequence-format.ts","../src/migration/apply-operation-transforms.ts","../src/migrations/migration-builder.ts","../src/migrations/migration-rollback.ts","../src/migrations/migration-sql.ts","../src/codegen/proto-generator.ts"],"sourcesContent":["/**\n * Hybrid Logical Clock timestamp.\n * Provides a total order that respects causality without requiring synchronized clocks.\n */\nexport interface HLCTimestamp {\n\t/** Physical wall-clock time in milliseconds */\n\twallTime: number\n\t/** Logical counter. Increments when wallTime hasn't changed since last event. */\n\tlogical: number\n\t/** Node ID for tie-breaking. Ensures total order even with identical wall+logical. */\n\tnodeId: string\n}\n\n/** The three mutation types an operation can represent */\nexport type OperationType = 'insert' | 'update' | 'delete'\n\n/** Supported atomic operation types for intent-preserving field updates */\nexport type AtomicOpType = 'increment' | 'max' | 'min' | 'append' | 'remove'\n\n/**\n * Atomic operation stored in an Operation's atomicOps field.\n * This is the serializable form that persists in the operation log.\n */\nexport interface AtomicOp {\n\treadonly type: AtomicOpType\n\treadonly value: unknown\n}\n\n/**\n * The atomic unit of the entire system. Every mutation produces an Operation.\n * Operations are IMMUTABLE and CONTENT-ADDRESSED.\n */\nexport interface Operation {\n\t/** SHA-256 hash of (type + collection + recordId + data + timestamp + nodeId). Content-addressed. */\n\tid: string\n\t/** UUID v7 of the originating device. Time-sortable. */\n\tnodeId: string\n\t/** What happened */\n\ttype: OperationType\n\t/** Which collection (from schema) */\n\tcollection: string\n\t/** ID of the affected record. UUID v7 for inserts, existing ID for update/delete. */\n\trecordId: string\n\t/** Field values. null for delete. For updates, contains ONLY changed fields. */\n\tdata: Record<string, unknown> | null\n\t/** For updates: previous values of changed fields (enables 3-way merge). null for insert/delete. */\n\tpreviousData: Record<string, unknown> | null\n\t/** Hybrid Logical Clock timestamp. Used for causal ordering. */\n\ttimestamp: HLCTimestamp\n\t/** Monotonically increasing per node. Used in version vectors. */\n\tsequenceNumber: number\n\t/** Operation IDs this operation causally depends on (direct parents in the DAG). */\n\tcausalDeps: string[]\n\t/** Schema version at time of creation. Used for migration transforms. */\n\tschemaVersion: number\n\t/** Atomic operation intents for fields in data (e.g., increment, max). Present only when atomic ops were used. */\n\tatomicOps?: Record<string, AtomicOp>\n\t/** Groups this operation with others in an atomic transaction. Not part of the content hash. */\n\ttransactionId?: string\n\t/** Human-readable name for the mutation group (e.g., 'complete-sale'). For DevTools display. */\n\tmutationName?: string\n}\n\n/**\n * Input for creating an operation (before id and timestamp are assigned).\n */\nexport interface OperationInput {\n\tnodeId: string\n\ttype: OperationType\n\tcollection: string\n\trecordId: string\n\tdata: Record<string, unknown> | null\n\tpreviousData: Record<string, unknown> | null\n\tsequenceNumber: number\n\tcausalDeps: string[]\n\tschemaVersion: number\n\t/** Atomic operation intents for fields in data (e.g., increment, max). */\n\tatomicOps?: Record<string, AtomicOp>\n\t/** Groups this operation with others in an atomic transaction. Not part of the content hash. */\n\ttransactionId?: string\n\t/** Human-readable name for the mutation group (e.g., 'complete-sale'). For DevTools display. */\n\tmutationName?: string\n}\n\n/** Version vector: maps nodeId to the max sequence number seen from that node */\nexport type VersionVector = Map<string, number>\n\n/** Field kinds supported by the schema system */\nexport type FieldKind =\n\t| 'string'\n\t| 'number'\n\t| 'boolean'\n\t| 'timestamp'\n\t| 'richtext'\n\t| 'enum'\n\t| 'array'\n\t| 'object'\n\t| 'json'\n\t| 'blob'\n\t| 'secret'\n\n/**\n * How a `secret` field's value is protected at rest.\n * - `hashed`: one-way (passwords). Stored as a salted hash; never read back.\n * - `encrypted`: reversible (tokens, keys). Stored as ciphertext; decrypted to use.\n */\nexport type SecretMode = 'hashed' | 'encrypted'\n\n/**\n * A content-addressed reference to binary data stored out of band.\n *\n * A `blob` field never carries the bytes in the operation log; it carries this\n * small reference. The bytes live in a content-addressed blob store, keyed by\n * `hash`, so identical content is stored once and never re-synced to a peer that\n * already has that hash.\n */\nexport interface BlobRef {\n\t/** Hex-encoded SHA-256 hash of the bytes. The content address. */\n\thash: string\n\t/** Size of the bytes in bytes. */\n\tsize: number\n\t/** Optional MIME type (for example \"image/png\"). */\n\tmimeType?: string\n\t/** Optional original filename. */\n\tfilename?: string\n\t/**\n\t * Hex-encoded SHA-256 hash of this blob's manifest — the small chunk index a\n\t * peer fetches first to learn how to pull the bytes out of band. Present when\n\t * the blob was stored for transfer; absent for a bare reference created without\n\t * chunking. Because it is a content address like `hash`, the manifest is fetched\n\t * and integrity-verified over the same channel as the chunks.\n\t */\n\tmanifestHash?: string\n}\n\n/**\n * Comprehensive sync diagnostics snapshot.\n * Provides connection, latency, throughput, queue, and error metrics\n * for monitoring and DevTools integration.\n */\nexport interface SyncDiagnosticsSnapshot {\n\t// Connection\n\t/** Current developer-facing sync status */\n\tstatus:\n\t\t| 'connected'\n\t\t| 'reconnecting'\n\t\t| 'syncing'\n\t\t| 'synced'\n\t\t| 'offline'\n\t\t| 'error'\n\t\t| 'schema-mismatch'\n\t\t| 'clock-error'\n\t\t| 'auth-required'\n\t/** Timestamp when the current connection was established, or null if disconnected */\n\tconnectedAt: number | null\n\t/** Timestamp when the last disconnection occurred, or null if never disconnected */\n\tdisconnectedAt: number | null\n\t/** Number of reconnection attempts since last successful connection */\n\treconnectAttempts: number\n\n\t// Latency\n\t/** Current round-trip time in milliseconds */\n\trttMs: number\n\t/** Median (50th percentile) RTT over the sliding window */\n\trttP50Ms: number\n\t/** 95th percentile RTT over the sliding window */\n\trttP95Ms: number\n\t/** 99th percentile RTT over the sliding window */\n\trttP99Ms: number\n\n\t// Throughput\n\t/** Total operations sent during this session */\n\toperationsSent: number\n\t/** Total operations received during this session */\n\toperationsReceived: number\n\t/** Total bytes sent during this session */\n\tbytesSent: number\n\t/** Total bytes received during this session */\n\tbytesReceived: number\n\n\t// Queue\n\t/** Number of operations waiting to be sent */\n\tpendingOperations: number\n\t/** Estimated bytes in the outbound queue */\n\toutboundQueueSize: number\n\n\t// Sync Progress\n\t/** Timestamp of the last successful sync, or null if never synced */\n\tlastSyncedAt: number | null\n\t/** Duration of the last complete sync cycle in ms, or null if no cycle completed */\n\tsyncDuration: number | null\n\t/** Whether the initial sync (full delta exchange) has completed */\n\tinitialSyncComplete: boolean\n\t/** Progress of the initial sync as a 0-1 ratio */\n\tinitialSyncProgress: number\n\n\t// Errors\n\t/** Description of the last error, or null if no error occurred */\n\tlastError: string | null\n\t/** Total number of errors during this session */\n\terrorCount: number\n\n\t// Connection Quality\n\t/** Assessed connection quality level */\n\tquality: 'excellent' | 'good' | 'fair' | 'poor' | 'offline'\n\t/** Estimated effective bandwidth in bytes per second, or null if not yet measured */\n\teffectiveBandwidth: number | null\n}\n\n/** Built-in field merge strategies that can be declared in the schema. */\nexport type FieldMergeStrategy =\n\t| 'lww'\n\t| 'counter'\n\t| 'max'\n\t| 'min'\n\t| 'union'\n\t| 'append-only'\n\t| 'server-authoritative'\n\n/** Map of state to allowed next states for state machine constraints */\nexport type TransitionMap = Record<string, string[]>\n\n/**\n * A state machine constraint extracted from the schema.\n * Used by merge and validation to enforce valid state transitions.\n */\nexport interface StateMachineConstraint {\n\t/** The enum field this constraint controls */\n\tfield: string\n\t/** The collection this constraint applies to */\n\tcollection: string\n\t/** Map of state to allowed next states */\n\ttransitions: TransitionMap\n}\n\n/**\n * Result of validating a state transition.\n */\nexport interface TransitionValidationResult {\n\t/** Whether the transition is allowed */\n\tvalid: boolean\n\t/** The source state */\n\tfrom: string\n\t/** The target state */\n\tto: string\n\t/** The field being transitioned */\n\tfield: string\n\t/** The collection containing the field */\n\tcollection: string\n\t/** All allowed target states from the source state */\n\tallowedTargets: string[]\n}\n\n/**\n * Descriptor produced by the type builder (t.string(), t.number(), etc.).\n * Represents a fully configured field definition.\n */\nexport interface FieldDescriptor {\n\tkind: FieldKind\n\trequired: boolean\n\tdefaultValue: unknown\n\tauto: boolean\n\tenumValues: readonly string[] | null\n\titemKind: FieldKind | null\n\t/** Declared merge strategy. Defaults to kind-appropriate strategy when undefined. */\n\tmergeStrategy: FieldMergeStrategy | null\n\t/** State machine transition map for enum fields. Null if no transitions declared. */\n\ttransitions: TransitionMap | null\n\t/**\n\t * Nested field descriptors for `object` fields (each key merges by its own\n\t * kind). Null for `json` fields (dynamic keys, resolved structurally) and for\n\t * all non-structured kinds.\n\t */\n\tnestedFields?: Record<string, FieldDescriptor> | null\n\t/**\n\t * At-rest protection mode for `secret` fields (`hashed` or `encrypted`).\n\t * Null/absent for every other kind.\n\t */\n\tsecretMode?: SecretMode | null\n}\n\n/**\n * Defines a state machine on an enum field, constraining valid state transitions.\n *\n * When a state machine is defined on a collection, mutations and merges\n * enforce that the controlled field only moves along declared transitions.\n *\n * @example\n * ```typescript\n * stateMachine: {\n * field: 'status',\n * transitions: {\n * draft: ['pending', 'cancelled'],\n * pending: ['confirmed', 'cancelled'],\n * confirmed: ['shipped'],\n * shipped: ['delivered'],\n * delivered: [],\n * cancelled: [],\n * },\n * onInvalidTransition: 'reject',\n * }\n * ```\n */\nexport interface StateMachineDefinition {\n\t/** The enum field this state machine controls */\n\tfield: string\n\t/** Map of state to allowed next states */\n\ttransitions: Record<string, string[]>\n\t/** What to do when an invalid transition is attempted */\n\tonInvalidTransition: 'reject' | 'last-valid-state'\n}\n\n/**\n * Definition of a collection within the schema.\n */\nexport interface CollectionDefinition {\n\tfields: Record<string, FieldDescriptor>\n\tindexes: string[]\n\tconstraints: Constraint[]\n\tresolvers: Record<string, CustomResolver>\n\t/** Scope fields for sync filtering. Only records matching the client's scope values are synced. */\n\tscope: string[]\n\t/** Optional state machine constraining transitions on an enum field */\n\tstateMachine?: StateMachineDefinition\n}\n\n/** Custom resolver function for tier 3 merge resolution */\nexport type CustomResolver = (local: unknown, remote: unknown, base: unknown) => unknown\n\n/**\n * Constraint for tier 2 conflict resolution.\n */\nexport interface Constraint {\n\ttype: 'unique' | 'capacity' | 'referential'\n\tfields: string[]\n\twhere?: Record<string, unknown>\n\tonConflict:\n\t\t| 'first-write-wins'\n\t\t| 'last-write-wins'\n\t\t| 'priority-field'\n\t\t| 'server-decides'\n\t\t| 'custom'\n\tpriorityField?: string\n\tresolve?: (local: unknown, remote: unknown, base: unknown) => unknown\n}\n\n/** Relation type between collections */\nexport type RelationType = 'one-to-one' | 'one-to-many' | 'many-to-one' | 'many-to-many'\n\n/** On-delete behavior for relations */\nexport type OnDeleteAction = 'cascade' | 'set-null' | 'restrict' | 'no-action'\n\n/**\n * Definition of a relation between two collections.\n */\nexport interface RelationDefinition {\n\tfrom: string\n\tto: string\n\ttype: RelationType\n\tfield: string\n\tonDelete: OnDeleteAction\n}\n\n/**\n * Declarative sync filter for a collection.\n *\n * `where` maps record field names to scope value keys. Use `true` to bind a field\n * to a scope value with the same name (e.g. `{ userId: true }`).\n */\nexport interface SyncRuleDefinition {\n\twhere: Record<string, string>\n}\n\n/**\n * The complete schema definition produced by defineSchema().\n */\nexport interface SchemaDefinition {\n\tversion: number\n\tcollections: Record<string, CollectionDefinition>\n\trelations: Record<string, RelationDefinition>\n\t/** Schema migrations keyed by target version. */\n\tmigrations: Record<number, import('./migrations/migration-builder').MigrationDefinition>\n\t/**\n\t * Declarative partial-sync rules per collection.\n\t * When present, only listed collections (plus legacy `scope` collections) sync.\n\t */\n\tsync?: Record<string, SyncRuleDefinition>\n}\n\n/**\n * Merge strategies available for auto-merge and constraints.\n */\nexport const MERGE_STRATEGIES = [\n\t'auto-merge',\n\t'lww',\n\t'first-write-wins',\n\t'server-decides',\n\t'custom',\n] as const\nexport type MergeStrategy = (typeof MERGE_STRATEGIES)[number]\n\n/**\n * Connection quality levels for adaptive sync.\n */\nexport const CONNECTION_QUALITIES = ['excellent', 'good', 'fair', 'poor', 'offline'] as const\nexport type ConnectionQuality = (typeof CONNECTION_QUALITIES)[number]\n\n/**\n * Injectable time source for deterministic testing of clocks.\n */\nexport interface TimeSource {\n\tnow(): number\n}\n\n/**\n * Injectable random source for deterministic testing of UUID generation.\n */\nexport interface RandomSource {\n\tgetRandomValues<T extends ArrayBufferView>(array: T): T\n}\n\n/**\n * Configuration for an offline-safe sequence.\n *\n * Sequences produce monotonically increasing, collision-free identifiers\n * that work across offline devices. Each device maintains its own counter\n * scoped by (name, scope, nodeId).\n *\n * Format tokens available:\n * - `{date}` → YYYYMMDD\n * - `{node4}` → first 4 chars of nodeId\n * - `{node8}` → first 8 chars of nodeId\n * - `{seq}` → zero-padded counter (4 digits)\n * - `{seq:N}` → zero-padded counter with N digits\n *\n * @example\n * ```typescript\n * await app.sequences.next('receipt', {\n * scope: storeId,\n * format: 'S-{date}-{node4}-{seq}',\n * })\n * // → \"S-20260508-a1b2-0042\"\n * ```\n */\nexport interface SequenceConfig {\n\t/** Namespace within the sequence (e.g., a storeId or orgId). Defaults to ''. */\n\tscope?: string\n\t/** Format template. Defaults to `{name}-{seq:4}`. */\n\tformat?: string\n\t/** Starting counter value. Defaults to 1. */\n\tstartAt?: number\n}\n","/**\n * Tracks the latest operation per collection and within an open transaction\n * to populate {@link Operation.causalDeps} for local mutations.\n */\nexport class CausalTracker {\n\tprivate readonly lastOpIdByCollection = new Map<string, string>()\n\tprivate lastTransactionOpId: string | null = null\n\n\t/**\n\t * Start a new transaction boundary. Clears in-transaction op ids.\n\t */\n\tbeginTransaction(): void {\n\t\tthis.lastTransactionOpId = null\n\t}\n\n\t/**\n\t * Clear the transaction boundary without recording ops (after rollback).\n\t */\n\tclearTransaction(): void {\n\t\tthis.lastTransactionOpId = null\n\t}\n\n\t/**\n\t * Compute causal dependencies for the next operation in a collection.\n\t * Uses direct parents only: collection head and the previous op in the open transaction.\n\t */\n\tnextCausalDeps(collection: string, inTransaction: boolean): string[] {\n\t\tconst deps: string[] = []\n\t\tconst lastInCollection = this.lastOpIdByCollection.get(collection)\n\t\tif (lastInCollection !== undefined) {\n\t\t\tdeps.push(lastInCollection)\n\t\t}\n\t\tif (inTransaction && this.lastTransactionOpId !== null) {\n\t\t\tif (!deps.includes(this.lastTransactionOpId)) {\n\t\t\t\tdeps.push(this.lastTransactionOpId)\n\t\t\t}\n\t\t}\n\t\treturn deps\n\t}\n\n\t/**\n\t * Record an operation after it has been created and assigned an id.\n\t */\n\tafterOperation(collection: string, operationId: string, inTransaction: boolean): void {\n\t\tthis.lastOpIdByCollection.set(collection, operationId)\n\t\tif (inTransaction) {\n\t\t\tthis.lastTransactionOpId = operationId\n\t\t}\n\t}\n}\n","import type { RandomSource } from '../types'\n\nconst defaultRandom: RandomSource = globalThis.crypto as RandomSource\n\n/**\n * Generates a UUID v7 per RFC 9562.\n * UUID v7 encodes a Unix timestamp in milliseconds in the most significant 48 bits,\n * making UUIDs time-sortable while remaining globally unique.\n *\n * @param timestamp - Unix timestamp in milliseconds (defaults to Date.now())\n * @param randomSource - Injectable random source for deterministic testing\n * @returns A UUID v7 string in standard 8-4-4-4-12 format\n *\n * @example\n * ```typescript\n * const id = generateUUIDv7()\n * // \"018f3a5c-7e00-7123-abcd-1234567890ab\"\n * ```\n */\nexport function generateUUIDv7(\n\ttimestamp: number = Date.now(),\n\trandomSource: RandomSource = defaultRandom,\n): string {\n\tconst bytes = new Uint8Array(16)\n\trandomSource.getRandomValues(bytes)\n\n\t// Encode 48-bit timestamp in bytes 0-5\n\tconst ms = Math.max(0, Math.floor(timestamp))\n\tbytes[0] = (ms / 2 ** 40) & 0xff\n\tbytes[1] = (ms / 2 ** 32) & 0xff\n\tbytes[2] = (ms / 2 ** 24) & 0xff\n\tbytes[3] = (ms / 2 ** 16) & 0xff\n\tbytes[4] = (ms / 2 ** 8) & 0xff\n\tbytes[5] = ms & 0xff\n\n\t// Set version 7 (0111) in bits 48-51\n\tbytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x70\n\n\t// Set variant 10 in bits 64-65\n\tbytes[8] = ((bytes[8] ?? 0) & 0x3f) | 0x80\n\n\treturn formatUUID(bytes)\n}\n\n/**\n * Extracts the Unix timestamp in milliseconds from a UUID v7.\n *\n * @param uuid - A UUID v7 string\n * @returns The encoded Unix timestamp in milliseconds\n */\nexport function extractTimestamp(uuid: string): number {\n\tconst hex = uuid.replace(/-/g, '')\n\t// First 12 hex chars = 48 bits of timestamp\n\tconst high = Number.parseInt(hex.slice(0, 8), 16)\n\tconst low = Number.parseInt(hex.slice(8, 12), 16)\n\treturn high * 2 ** 16 + low\n}\n\n/**\n * Validates whether a string is a valid UUID v7.\n * Checks format, version (7), and variant (10xx).\n *\n * @param uuid - String to validate\n * @returns true if the string is a valid UUID v7\n */\nexport function isValidUUIDv7(uuid: string): boolean {\n\tif (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(uuid)) {\n\t\treturn false\n\t}\n\tconst hex = uuid.replace(/-/g, '')\n\t// Version must be 7 (nibble at position 12)\n\tif (hex[12] !== '7') return false\n\t// Variant must be 10xx (nibble at position 16 must be 8, 9, a, or b)\n\tconst variantNibble = Number.parseInt(hex[16] ?? '0', 16)\n\treturn variantNibble >= 0x8 && variantNibble <= 0xb\n}\n\nfunction formatUUID(bytes: Uint8Array): string {\n\tconst hex = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('')\n\treturn `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`\n}\n","import type { BlobRef } from '../types'\n\n/**\n * Compute the hex-encoded SHA-256 content hash of a byte buffer.\n *\n * This is the content address of a blob: identical bytes always hash to the same\n * value, which is what lets the blob store deduplicate content and lets a peer\n * skip transferring bytes it already holds.\n *\n * @param bytes - The binary content to hash\n * @returns The hex-encoded SHA-256 hash\n */\nexport async function hashBlob(bytes: Uint8Array): Promise<string> {\n\t// Copy into a fresh, exactly-sized ArrayBuffer so a Uint8Array that is a view\n\t// over a larger buffer (offset/length subrange) hashes its own bytes only.\n\tconst view = new Uint8Array(bytes.byteLength)\n\tview.set(bytes)\n\tconst digest = await globalThis.crypto.subtle.digest('SHA-256', view)\n\tconst out = new Uint8Array(digest)\n\treturn Array.from(out, (b) => b.toString(16).padStart(2, '0')).join('')\n}\n\n/** Optional metadata carried alongside a blob reference. */\nexport interface BlobRefMetadata {\n\tmimeType?: string\n\tfilename?: string\n}\n\n/**\n * Create a content-addressed {@link BlobRef} for a byte buffer.\n *\n * @param bytes - The binary content\n * @param metadata - Optional MIME type and filename\n * @returns A reference carrying the content hash, size, and metadata\n */\nexport async function createBlobRef(\n\tbytes: Uint8Array,\n\tmetadata: BlobRefMetadata = {},\n): Promise<BlobRef> {\n\tconst hash = await hashBlob(bytes)\n\tconst ref: BlobRef = { hash, size: bytes.byteLength }\n\tif (metadata.mimeType !== undefined) {\n\t\tref.mimeType = metadata.mimeType\n\t}\n\tif (metadata.filename !== undefined) {\n\t\tref.filename = metadata.filename\n\t}\n\treturn ref\n}\n\n/**\n * Type guard: whether a value is a structurally valid {@link BlobRef}.\n *\n * Validates the shape only (a non-empty hex hash and a non-negative size); it\n * does not verify that the bytes behind the hash exist or match. Integrity\n * verification against the actual bytes happens in the blob store on read.\n */\nexport function isBlobRef(value: unknown): value is BlobRef {\n\tif (typeof value !== 'object' || value === null) {\n\t\treturn false\n\t}\n\tconst ref = value as Record<string, unknown>\n\tif (typeof ref.hash !== 'string' || !/^[0-9a-f]{64}$/.test(ref.hash)) {\n\t\treturn false\n\t}\n\tif (typeof ref.size !== 'number' || !Number.isInteger(ref.size) || ref.size < 0) {\n\t\treturn false\n\t}\n\tif (ref.mimeType !== undefined && typeof ref.mimeType !== 'string') {\n\t\treturn false\n\t}\n\tif (ref.filename !== undefined && typeof ref.filename !== 'string') {\n\t\treturn false\n\t}\n\tif (\n\t\tref.manifestHash !== undefined &&\n\t\t(typeof ref.manifestHash !== 'string' || !/^[0-9a-f]{64}$/.test(ref.manifestHash))\n\t) {\n\t\treturn false\n\t}\n\treturn true\n}\n","/**\n * Field-level cryptography for `secret` fields.\n *\n * Two protection modes, matching the two ways secrets are used:\n * - `encrypted`: reversible AES-256-GCM (tokens, API keys — decrypt to use).\n * - `hashed`: one-way PBKDF2-SHA-256 with a random salt (passwords — verify only).\n *\n * These primitives use only the standard WebCrypto API so they live in\n * `@korajs/core` with no dependency on `@korajs/auth`; a `secret` field is\n * therefore self-contained. Higher-level key management composes on top.\n */\n\nconst PBKDF2_ITERATIONS = 210_000\nconst SALT_BYTES = 16\nconst IV_BYTES = 12\nconst HASH_BYTES = 32\n\nfunction toHex(bytes: Uint8Array): string {\n\treturn Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('')\n}\n\nfunction fromHex(hex: string): Uint8Array {\n\tif (hex.length % 2 !== 0 || /[^0-9a-f]/i.test(hex)) {\n\t\tthrow new Error('Invalid hex string')\n\t}\n\tconst out = new Uint8Array(hex.length / 2)\n\tfor (let i = 0; i < out.length; i++) {\n\t\tout[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16)\n\t}\n\treturn out\n}\n\nfunction randomBytes(n: number): Uint8Array {\n\tconst out = new Uint8Array(n)\n\tglobalThis.crypto.getRandomValues(out)\n\treturn out\n}\n\n/** Constant-time comparison of two equal-length byte arrays. */\nfunction timingSafeEqual(a: Uint8Array, b: Uint8Array): boolean {\n\tif (a.length !== b.length) {\n\t\treturn false\n\t}\n\tlet diff = 0\n\tfor (let i = 0; i < a.length; i++) {\n\t\tdiff |= (a[i] as number) ^ (b[i] as number)\n\t}\n\treturn diff === 0\n}\n\nasync function deriveAesKey(secretKey: string, salt: Uint8Array): Promise<CryptoKey> {\n\tconst baseKey = await globalThis.crypto.subtle.importKey(\n\t\t'raw',\n\t\tnew TextEncoder().encode(secretKey),\n\t\t'PBKDF2',\n\t\tfalse,\n\t\t['deriveKey'],\n\t)\n\treturn globalThis.crypto.subtle.deriveKey(\n\t\t{ name: 'PBKDF2', salt: salt as BufferSource, iterations: PBKDF2_ITERATIONS, hash: 'SHA-256' },\n\t\tbaseKey,\n\t\t{ name: 'AES-GCM', length: 256 },\n\t\tfalse,\n\t\t['encrypt', 'decrypt'],\n\t)\n}\n\n/**\n * Encrypt a secret's plaintext with AES-256-GCM under a key derived from\n * `secretKey`. The returned string bundles the salt, IV, and ciphertext (all hex,\n * dot-separated) so it is self-describing and safe to store and sync.\n *\n * @param plaintext - The secret value to protect\n * @param secretKey - The key material (from a key provider), never stored\n * @returns An opaque `v1.salt.iv.ciphertext` string\n */\nexport async function encryptSecret(plaintext: string, secretKey: string): Promise<string> {\n\tconst salt = randomBytes(SALT_BYTES)\n\tconst iv = randomBytes(IV_BYTES)\n\tconst key = await deriveAesKey(secretKey, salt)\n\tconst ciphertext = await globalThis.crypto.subtle.encrypt(\n\t\t{ name: 'AES-GCM', iv: iv as BufferSource },\n\t\tkey,\n\t\tnew TextEncoder().encode(plaintext),\n\t)\n\treturn `v1.${toHex(salt)}.${toHex(iv)}.${toHex(new Uint8Array(ciphertext))}`\n}\n\n/**\n * Decrypt a value produced by {@link encryptSecret} with the same key.\n *\n * @param encrypted - The `v1.salt.iv.ciphertext` string\n * @param secretKey - The key material used to encrypt\n * @returns The original plaintext\n * @throws If the format is invalid or the key is wrong (GCM auth failure)\n */\nexport async function decryptSecret(encrypted: string, secretKey: string): Promise<string> {\n\tconst parts = encrypted.split('.')\n\tif (parts.length !== 4 || parts[0] !== 'v1') {\n\t\tthrow new Error('Invalid encrypted secret format')\n\t}\n\tconst salt = fromHex(parts[1] as string)\n\tconst iv = fromHex(parts[2] as string)\n\tconst ciphertext = fromHex(parts[3] as string)\n\tconst key = await deriveAesKey(secretKey, salt)\n\tconst plaintext = await globalThis.crypto.subtle.decrypt(\n\t\t{ name: 'AES-GCM', iv: iv as BufferSource },\n\t\tkey,\n\t\tciphertext as BufferSource,\n\t)\n\treturn new TextDecoder().decode(plaintext)\n}\n\n/**\n * One-way hash a secret (a password) with PBKDF2-SHA-256 and a random salt.\n * The result bundles the salt and hash so {@link verifySecret} needs nothing\n * else. There is no way to recover the plaintext from the result.\n *\n * @param plaintext - The secret value to hash\n * @returns An opaque `v1.salt.hash` string\n */\nexport async function hashSecret(plaintext: string): Promise<string> {\n\tconst salt = randomBytes(SALT_BYTES)\n\tconst hash = await pbkdf2(plaintext, salt)\n\treturn `v1.${toHex(salt)}.${toHex(hash)}`\n}\n\n/**\n * Verify a plaintext against a value produced by {@link hashSecret}, in constant\n * time with respect to the stored hash.\n *\n * @param plaintext - The candidate secret\n * @param stored - The `v1.salt.hash` string\n * @returns Whether the plaintext matches\n */\nexport async function verifySecret(plaintext: string, stored: string): Promise<boolean> {\n\tconst parts = stored.split('.')\n\tif (parts.length !== 3 || parts[0] !== 'v1') {\n\t\treturn false\n\t}\n\tlet salt: Uint8Array\n\tlet expected: Uint8Array\n\ttry {\n\t\tsalt = fromHex(parts[1] as string)\n\t\texpected = fromHex(parts[2] as string)\n\t} catch {\n\t\treturn false\n\t}\n\tconst actual = await pbkdf2(plaintext, salt)\n\treturn timingSafeEqual(actual, expected)\n}\n\nasync function pbkdf2(plaintext: string, salt: Uint8Array): Promise<Uint8Array> {\n\tconst baseKey = await globalThis.crypto.subtle.importKey(\n\t\t'raw',\n\t\tnew TextEncoder().encode(plaintext),\n\t\t'PBKDF2',\n\t\tfalse,\n\t\t['deriveBits'],\n\t)\n\tconst bits = await globalThis.crypto.subtle.deriveBits(\n\t\t{ name: 'PBKDF2', salt: salt as BufferSource, iterations: PBKDF2_ITERATIONS, hash: 'SHA-256' },\n\t\tbaseKey,\n\t\tHASH_BYTES * 8,\n\t)\n\treturn new Uint8Array(bits)\n}\n","import type { CollectionDefinition } from '../types'\nimport { decryptSecret, encryptSecret, hashSecret, verifySecret } from './secret-crypto'\n\n/**\n * Provider of the key material used to encrypt reversible (`encrypted`) secret\n * fields. Called at write and reveal time so the key can be loaded lazily (for\n * example derived from a user passphrase after unlock). Returns undefined when\n * no key is available.\n */\nexport type SecretKeyProvider = () => string | undefined | Promise<string | undefined>\n\n/** Thrown when an `encrypted` secret field is written or read without a key. */\nexport class MissingSecretKeyError extends Error {\n\tconstructor(readonly field: string) {\n\t\tsuper(\n\t\t\t`Secret field \"${field}\" is encrypted but no encryption key is configured. Provide sync.encryption.key (or a key provider) to createApp.`,\n\t\t)\n\t\tthis.name = 'MissingSecretKeyError'\n\t}\n}\n\nasync function resolveKey(provider: SecretKeyProvider | undefined): Promise<string | undefined> {\n\tif (!provider) {\n\t\treturn undefined\n\t}\n\treturn provider()\n}\n\n/**\n * Transform the secret fields of a record's write payload into their at-rest\n * form BEFORE the operation is created, so plaintext never enters the operation\n * log, the store, or the sync stream.\n *\n * - `hashed` fields become a one-way salted hash.\n * - `encrypted` fields become ciphertext (requires a key).\n *\n * Non-secret fields, and secret fields not present in `data`, are passed through\n * untouched. Null/undefined secret values are left as-is (nothing to protect).\n *\n * @param data - The validated write payload (plaintext secret values)\n * @param collectionDef - The collection definition (for field kinds/modes)\n * @param keyProvider - Supplies the encryption key for `encrypted` fields\n * @returns A new payload with secret fields replaced by their at-rest form\n */\nexport async function transformSecretFieldsForWrite(\n\tdata: Record<string, unknown>,\n\tcollectionDef: CollectionDefinition,\n\tkeyProvider?: SecretKeyProvider,\n): Promise<Record<string, unknown>> {\n\t// Fast path: no secret fields in this collection at all.\n\tconst hasSecret = Object.values(collectionDef.fields).some((f) => f.kind === 'secret')\n\tif (!hasSecret) {\n\t\treturn data\n\t}\n\n\tconst result: Record<string, unknown> = { ...data }\n\tlet key: string | undefined\n\tlet keyResolved = false\n\n\tfor (const [field, value] of Object.entries(data)) {\n\t\tconst descriptor = collectionDef.fields[field]\n\t\tif (descriptor?.kind !== 'secret') {\n\t\t\tcontinue\n\t\t}\n\t\tif (typeof value !== 'string') {\n\t\t\t// Null/undefined or non-string: nothing to transform.\n\t\t\tcontinue\n\t\t}\n\t\tconst mode = descriptor.secretMode ?? 'encrypted'\n\t\tif (mode === 'hashed') {\n\t\t\tresult[field] = await hashSecret(value)\n\t\t\tcontinue\n\t\t}\n\t\t// encrypted\n\t\tif (!keyResolved) {\n\t\t\tkey = await resolveKey(keyProvider)\n\t\t\tkeyResolved = true\n\t\t}\n\t\tif (key === undefined) {\n\t\t\tthrow new MissingSecretKeyError(field)\n\t\t}\n\t\tresult[field] = await encryptSecret(value, key)\n\t}\n\n\treturn result\n}\n\n/**\n * Reveal the plaintext of an `encrypted` secret field's stored value. Throws for\n * `hashed` fields, which are one-way and cannot be revealed.\n *\n * @param storedValue - The at-rest value (ciphertext)\n * @param mode - The field's secret mode\n * @param keyProvider - Supplies the decryption key\n * @param field - Field name (for error messages)\n * @returns The decrypted plaintext\n */\nexport async function revealSecret(\n\tstoredValue: string,\n\tmode: 'hashed' | 'encrypted',\n\tkeyProvider: SecretKeyProvider | undefined,\n\tfield = 'secret',\n): Promise<string> {\n\tif (mode === 'hashed') {\n\t\tthrow new Error(\n\t\t\t`Secret field \"${field}\" is hashed (one-way) and cannot be revealed. Use verifySecretValue to check a candidate.`,\n\t\t)\n\t}\n\tconst key = await resolveKey(keyProvider)\n\tif (key === undefined) {\n\t\tthrow new MissingSecretKeyError(field)\n\t}\n\treturn decryptSecret(storedValue, key)\n}\n\n/**\n * Verify a plaintext candidate against a `hashed` secret field's stored value.\n *\n * @param candidate - The plaintext to check (for example a login password)\n * @param storedValue - The stored one-way hash\n * @returns Whether the candidate matches\n */\nexport async function verifySecretValue(candidate: string, storedValue: string): Promise<boolean> {\n\treturn verifySecret(candidate, storedValue)\n}\n","/**\n * Outcome of applying a single operation to materialized storage (local or remote).\n */\nexport const APPLY_RESULTS = ['applied', 'duplicate', 'skipped', 'rejected', 'deferred'] as const\n\nexport type ApplyResult = (typeof APPLY_RESULTS)[number]\n\n/**\n * Structured failure metadata when apply returns `skipped`, `rejected`, or `deferred`.\n */\nexport interface ApplyFailureReason {\n\tcode: string\n\tmessage: string\n\tretriable: boolean\n}\n\n/** Well-known apply failure codes for DevTools and `sync:apply-failed` events. */\nexport const APPLY_FAILURE_CODES = {\n\tAPPLY_FAILED: 'APPLY_FAILED',\n\tAPPLY_SKIPPED: 'APPLY_SKIPPED',\n\tAPPLY_REJECTED: 'APPLY_REJECTED',\n\tAPPLY_DEFERRED: 'APPLY_DEFERRED',\n\tCLOCK_DRIFT: 'CLOCK_DRIFT',\n\tREFERENTIAL_INTEGRITY: 'REFERENTIAL_INTEGRITY',\n\tSCHEMA_MISMATCH: 'SCHEMA_MISMATCH',\n} as const\n\n/**\n * Returns true when the apply outcome should surface as a failure to the developer.\n */\nexport function isApplyFailure(result: ApplyResult): boolean {\n\treturn result === 'skipped' || result === 'rejected' || result === 'deferred'\n}\n\n/**\n * Default failure metadata when the store does not attach a specific reason.\n */\nexport function defaultApplyFailureReason(\n\tresult: Exclude<ApplyResult, 'applied' | 'duplicate'>,\n\toverrides?: Partial<ApplyFailureReason>,\n): ApplyFailureReason {\n\tconst base: ApplyFailureReason =\n\t\tresult === 'deferred'\n\t\t\t? {\n\t\t\t\t\tcode: APPLY_FAILURE_CODES.APPLY_DEFERRED,\n\t\t\t\t\tmessage: 'Operation apply was deferred.',\n\t\t\t\t\tretriable: true,\n\t\t\t\t}\n\t\t\t: result === 'rejected'\n\t\t\t\t? {\n\t\t\t\t\t\tcode: APPLY_FAILURE_CODES.APPLY_REJECTED,\n\t\t\t\t\t\tmessage: 'Operation apply was rejected.',\n\t\t\t\t\t\tretriable: false,\n\t\t\t\t\t}\n\t\t\t\t: {\n\t\t\t\t\t\tcode: APPLY_FAILURE_CODES.APPLY_SKIPPED,\n\t\t\t\t\t\tmessage: 'Operation apply was skipped.',\n\t\t\t\t\t\tretriable: false,\n\t\t\t\t\t}\n\n\treturn { ...base, ...overrides }\n}\n","/**\n * Atomic field operations for intent-preserving updates.\n *\n * Instead of read-modify-write patterns, developers express intent:\n * ```typescript\n * await app.stock.update(id, { quantity: op.increment(-5) })\n * ```\n *\n * The operation intent is preserved in the Operation for merge:\n * concurrent increments compose (sum of deltas) instead of LWW.\n */\n\nimport type { AtomicOp, AtomicOpType } from '../types'\n\n// Re-export for convenience\nexport type { AtomicOp, AtomicOpType }\n\n/**\n * Sentinel marker for detecting atomic op objects in update data.\n * Uses Symbol.for() so the sentinel survives module boundary crossings.\n */\nconst KORA_ATOMIC_OP = Symbol.for('kora.atomic_op')\n\n/** String key used for the sentinel symbol — exported for internal use */\nexport const KORA_ATOMIC_OP_KEY: typeof KORA_ATOMIC_OP = KORA_ATOMIC_OP\n\n/**\n * Sentinel object returned by op.* helpers.\n * Detected by Collection.update() and resolved to concrete values.\n */\nexport interface AtomicOpSentinel {\n\treadonly [KORA_ATOMIC_OP_KEY]: true\n\treadonly type: AtomicOpType\n\treadonly value: unknown\n}\n\n/**\n * Type guard: checks whether a value is an atomic op sentinel.\n *\n * @param value - Any value to check\n * @returns true if the value is an AtomicOpSentinel\n */\nexport function isAtomicOp(value: unknown): value is AtomicOpSentinel {\n\treturn (\n\t\ttypeof value === 'object' &&\n\t\tvalue !== null &&\n\t\tKORA_ATOMIC_OP in value &&\n\t\t(value as Record<symbol, unknown>)[KORA_ATOMIC_OP] === true\n\t)\n}\n\n/**\n * Apply a plain atomic op (`{ type, value }`) to a current value, producing the\n * concrete result. This is the single source of truth for atomic-op semantics:\n * {@link resolveAtomicOp} (sentinel form, used on the write path) delegates here,\n * and the server's materialization replays stored atomic ops through it, so the\n * server's materialized view composes concurrent atomic writes identically to the\n * client. Folding this over a field's writes in HLC order yields, for a same-type\n * atomic chain, exactly the composed intent (sum of increments, max of maxes, ...).\n *\n * @param currentValue - The current value of the field\n * @param atomicOp - The atomic op to apply (type + operand)\n * @returns The resulting concrete value\n */\nexport function applyAtomicOp(currentValue: unknown, atomicOp: AtomicOp): unknown {\n\tswitch (atomicOp.type) {\n\t\tcase 'increment': {\n\t\t\tconst current = typeof currentValue === 'number' ? currentValue : 0\n\t\t\tconst operand = atomicOp.value as number\n\t\t\treturn current + operand\n\t\t}\n\t\tcase 'max': {\n\t\t\tconst current = typeof currentValue === 'number' ? currentValue : Number.NEGATIVE_INFINITY\n\t\t\treturn Math.max(current, atomicOp.value as number)\n\t\t}\n\t\tcase 'min': {\n\t\t\tconst current = typeof currentValue === 'number' ? currentValue : Number.POSITIVE_INFINITY\n\t\t\treturn Math.min(current, atomicOp.value as number)\n\t\t}\n\t\tcase 'append': {\n\t\t\tconst current = Array.isArray(currentValue) ? [...currentValue] : []\n\t\t\tcurrent.push(atomicOp.value)\n\t\t\treturn current\n\t\t}\n\t\tcase 'remove': {\n\t\t\tif (!Array.isArray(currentValue)) return []\n\t\t\t// Compare by value (JSON), matching add-wins-set semantics, so removing an\n\t\t\t// object or array element works instead of silently no-op'ing under the\n\t\t\t// reference inequality that `!==` would give for non-primitives.\n\t\t\tconst target = JSON.stringify(atomicOp.value)\n\t\t\treturn currentValue.filter((item) => JSON.stringify(item) !== target)\n\t\t}\n\t}\n}\n\n/**\n * Resolve an atomic op sentinel against a current value to produce a concrete result.\n *\n * @param currentValue - The current value of the field in the database\n * @param sentinel - The atomic op sentinel from the developer's update call\n * @returns The resolved concrete value\n */\nexport function resolveAtomicOp(currentValue: unknown, sentinel: AtomicOpSentinel): unknown {\n\treturn applyAtomicOp(currentValue, { type: sentinel.type, value: sentinel.value })\n}\n\nfunction createSentinel(type: AtomicOpType, value: unknown): AtomicOpSentinel {\n\treturn Object.freeze({\n\t\t[KORA_ATOMIC_OP]: true as const,\n\t\ttype,\n\t\tvalue,\n\t})\n}\n\n/**\n * Atomic operation helpers. Use these in collection.update() calls\n * to express intent-preserving mutations.\n *\n * @example\n * ```typescript\n * import { op } from 'korajs'\n *\n * // Increment a counter (works correctly with concurrent updates)\n * await app.stock.update(id, { quantity: op.increment(-5) })\n *\n * // Keep the maximum value\n * await app.scores.update(id, { highScore: op.max(newScore) })\n *\n * // Append to an array\n * await app.todos.update(id, { tags: op.append('urgent') })\n * ```\n */\nexport const op = {\n\t/**\n\t * Increment a number field by the given amount.\n\t * Concurrent increments compose: the sum of all deltas is applied to the base.\n\t *\n\t * @param n - The amount to increment (use negative values to decrement)\n\t */\n\tincrement(n: number): AtomicOpSentinel {\n\t\treturn createSentinel('increment', n)\n\t},\n\n\t/**\n\t * Decrement a number field by the given amount.\n\t * Syntactic sugar for `op.increment(-n)`.\n\t *\n\t * @param n - The amount to decrement\n\t */\n\tdecrement(n: number): AtomicOpSentinel {\n\t\treturn createSentinel('increment', -n)\n\t},\n\n\t/**\n\t * Set the field to the maximum of the current value and the given value.\n\t * Concurrent max operations take the maximum of all values.\n\t *\n\t * @param n - The value to compare against the current value\n\t */\n\tmax(n: number): AtomicOpSentinel {\n\t\treturn createSentinel('max', n)\n\t},\n\n\t/**\n\t * Set the field to the minimum of the current value and the given value.\n\t * Concurrent min operations take the minimum of all values.\n\t *\n\t * @param n - The value to compare against the current value\n\t */\n\tmin(n: number): AtomicOpSentinel {\n\t\treturn createSentinel('min', n)\n\t},\n\n\t/**\n\t * Append an item to an array field.\n\t * Concurrent appends include all appended items.\n\t *\n\t * @param item - The item to append to the array\n\t */\n\tappend(item: unknown): AtomicOpSentinel {\n\t\treturn createSentinel('append', item)\n\t},\n\n\t/**\n\t * Remove an item from an array field (by value equality).\n\t * Concurrent removes of the same item are idempotent.\n\t *\n\t * @param item - The item to remove from the array\n\t */\n\tremove(item: unknown): AtomicOpSentinel {\n\t\treturn createSentinel('remove', item)\n\t},\n}\n\n/**\n * Extract the serializable AtomicOp from a sentinel (strips the Symbol marker).\n *\n * @param sentinel - The atomic op sentinel\n * @returns A plain object suitable for JSON serialization\n */\nexport function toAtomicOp(sentinel: AtomicOpSentinel): AtomicOp {\n\treturn { type: sentinel.type, value: sentinel.value }\n}\n","import type { AtomicOp } from '../types'\nimport { applyAtomicOp } from './atomic-ops'\n\n/** One operation's contribution to a record's materialized state. */\nexport interface ReplayOperation {\n\ttype: string\n\tdata: Record<string, unknown> | null\n\t/**\n\t * Atomic-op intents carried by this operation, per field. When present, a field\n\t * is composed (rather than overwritten) if the previous writer on that field was\n\t * an atomic op of the same type. Absent means every field resolves by\n\t * last-write-wins.\n\t */\n\tatomicOps?: Record<string, AtomicOp> | null\n}\n\n/**\n * Replay a list of operations (MUST be pre-sorted in HLC total order —\n * wallTime, then logical, then nodeId) to produce the current state of a single\n * record, composing atomic-op intents.\n *\n * Per field, an atomic op composes onto the running value only when the field's\n * previous writer was an atomic op of the SAME type (a same-type atomic chain:\n * concurrent increments sum, maxes take the max, appends accumulate); any other\n * write, including the first atomic write after a plain set, resolves by\n * last-write-wins on the resolved value. Because operations are folded in HLC order,\n * the current op always wins that last-write-wins comparison, so the result is\n * deterministic and identical on every replica that folds the same operation set.\n *\n * This is the single definition of atomic materialization shared by the client\n * (`@korajs/store` apply pipeline) and the server (`@korajs/server` materialization),\n * so both converge to the same value for any number of concurrent atomic writers.\n *\n * Returns the record field data (without `id`) or null if the record was deleted\n * or never inserted.\n */\nexport function replayOperationsForRecord(ops: ReplayOperation[]): Record<string, unknown> | null {\n\tlet record: Record<string, unknown> | null = null\n\tlet deleted = false\n\t// Per-field provenance of the running value: 'lww' for a plain set, or\n\t// `atomic:<type>` for an atomic write. Drives the compose-vs-overwrite decision.\n\tconst lastWriterKind: Record<string, string> = {}\n\n\tfor (const op of ops) {\n\t\tswitch (op.type) {\n\t\t\tcase 'insert':\n\t\t\t\tif (op.data) {\n\t\t\t\t\trecord = { ...op.data }\n\t\t\t\t\tdeleted = false\n\t\t\t\t\tfor (const field of Object.keys(op.data)) {\n\t\t\t\t\t\tlastWriterKind[field] = 'lww'\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\tcase 'update':\n\t\t\t\tif (op.data) {\n\t\t\t\t\tconst next: Record<string, unknown> = { ...(record ?? {}) }\n\t\t\t\t\tfor (const [field, value] of Object.entries(op.data)) {\n\t\t\t\t\t\tconst atomicOp = op.atomicOps?.[field]\n\t\t\t\t\t\tif (atomicOp && lastWriterKind[field] === `atomic:${atomicOp.type}`) {\n\t\t\t\t\t\t\t// Same-type atomic chain: compose the intent onto the running value.\n\t\t\t\t\t\t\tnext[field] = applyAtomicOp(next[field], atomicOp)\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t// Last-write-wins on the resolved value (later HLC supersedes).\n\t\t\t\t\t\t\tnext[field] = value\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlastWriterKind[field] = atomicOp ? `atomic:${atomicOp.type}` : 'lww'\n\t\t\t\t\t}\n\t\t\t\t\trecord = next\n\t\t\t\t\tdeleted = false\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\tcase 'delete':\n\t\t\t\tdeleted = true\n\t\t\t\tbreak\n\t\t}\n\t}\n\n\treturn deleted ? null : record\n}\n","import { OperationError } from '../errors/errors'\n\n/**\n * Canonical JSON-safe encoding of binary bytes stored inside `op.data` /\n * `op.previousData` (currently richtext field values). A raw Uint8Array\n * JSON-serializes to a numeric-key object and an ArrayBuffer to `{}` (silent\n * data loss), which breaks content-hash stability, persistence round-trips,\n * remote application, and merge. Tagging the bytes as base64 at\n * operation-creation time makes the hashed value, the persisted JSON, the wire\n * payload, and the value the merge engine sees the identical canonical value.\n *\n * This convention lives in `@korajs/core` because `op.data` is a core concept:\n * both `@korajs/store` (persistence, creation) and `@korajs/merge` (CRDT merge)\n * must agree on it, and neither may depend on the other.\n */\nexport interface KoraBytesValue {\n\t$koraBytes: string\n}\n\n/**\n * Type guard for the tagged binary form. Requires exactly the single\n * `$koraBytes` key so arbitrary user objects that happen to contain the key\n * are never silently reinterpreted as bytes.\n */\nexport function isKoraBytesValue(value: unknown): value is KoraBytesValue {\n\tif (typeof value !== 'object' || value === null) {\n\t\treturn false\n\t}\n\tconst record = value as Record<string, unknown>\n\treturn Object.keys(record).length === 1 && typeof record.$koraBytes === 'string'\n}\n\n/**\n * Detects the numeric-key object shape a raw Uint8Array produced when\n * JSON-serialized before the tagged encoding existed ({\"0\":1,\"1\":2,...}).\n */\nexport function isLegacyNumericByteObject(value: unknown): value is Record<string, number> {\n\tif (typeof value !== 'object' || value === null || ArrayBuffer.isView(value)) {\n\t\treturn false\n\t}\n\tconst record = value as Record<string, unknown>\n\tconst keys = Object.keys(record)\n\tif (keys.length === 0) {\n\t\treturn false\n\t}\n\tfor (let i = 0; i < keys.length; i++) {\n\t\tconst byte = record[String(i)]\n\t\tif (typeof byte !== 'number' || !Number.isInteger(byte) || byte < 0 || byte > 255) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nconst BASE64_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\n\nconst BASE64_REVERSE: ReadonlyMap<string, number> = new Map(\n\tArray.from(BASE64_ALPHABET, (char, index) => [char, index]),\n)\n\n/**\n * Dependency-free base64 encoder. btoa is unavailable for bytes in Node and\n * Buffer is unavailable in browsers, so a manual implementation is the only\n * deterministic option that works in every runtime Kora targets.\n */\nexport function bytesToBase64(bytes: Uint8Array): string {\n\tlet out = ''\n\tfor (let i = 0; i < bytes.length; i += 3) {\n\t\tconst b0 = bytes[i] ?? 0\n\t\tconst b1 = bytes[i + 1] ?? 0\n\t\tconst b2 = bytes[i + 2] ?? 0\n\t\tconst triple = (b0 << 16) | (b1 << 8) | b2\n\t\tout += BASE64_ALPHABET[(triple >> 18) & 63] ?? ''\n\t\tout += BASE64_ALPHABET[(triple >> 12) & 63] ?? ''\n\t\tout += i + 1 < bytes.length ? (BASE64_ALPHABET[(triple >> 6) & 63] ?? '') : '='\n\t\tout += i + 2 < bytes.length ? (BASE64_ALPHABET[triple & 63] ?? '') : '='\n\t}\n\treturn out\n}\n\n/**\n * Inverse of {@link bytesToBase64}.\n */\nexport function base64ToBytes(base64: string): Uint8Array {\n\tconst cleaned = base64.replace(/=+$/, '')\n\tconst out = new Uint8Array(Math.floor((cleaned.length * 6) / 8))\n\tlet buffer = 0\n\tlet bits = 0\n\tlet index = 0\n\tfor (const char of cleaned) {\n\t\tconst value = BASE64_REVERSE.get(char)\n\t\tif (value === undefined) {\n\t\t\tthrow new OperationError(`Invalid base64 character \"${char}\" in tagged binary value.`, {\n\t\t\t\tchar,\n\t\t\t})\n\t\t}\n\t\tbuffer = (buffer << 6) | value\n\t\tbits += 6\n\t\tif (bits >= 8) {\n\t\t\tbits -= 8\n\t\t\tout[index] = (buffer >> bits) & 0xff\n\t\t\tindex += 1\n\t\t}\n\t}\n\treturn out\n}\n\n/**\n * Normalize a validated binary-or-string value into the canonical form stored\n * in `op.data`: strings pass through unchanged (backward compatible with every\n * existing operation), binary values become the tagged base64 form.\n */\nexport function encodeBytesForOpData(\n\tvalue: string | Uint8Array | ArrayBuffer,\n): string | KoraBytesValue {\n\tif (typeof value === 'string') {\n\t\treturn value\n\t}\n\tconst bytes = value instanceof Uint8Array ? value : new Uint8Array(value)\n\treturn { $koraBytes: bytesToBase64(bytes) }\n}\n\n/**\n * Reverse of {@link encodeBytesForOpData}, tolerant of every shape a binary\n * op-data value has ever taken: canonical strings and tagged bytes, in-memory\n * Uint8Array/ArrayBuffer (ops that never round-tripped through JSON), and\n * pre-fix numeric-key objects.\n */\nexport function decodeBytesFromOpData(value: unknown): string | Uint8Array {\n\tif (typeof value === 'string') {\n\t\treturn value\n\t}\n\tif (value instanceof Uint8Array) {\n\t\treturn value\n\t}\n\tif (value instanceof ArrayBuffer) {\n\t\treturn new Uint8Array(value)\n\t}\n\tif (isKoraBytesValue(value)) {\n\t\treturn base64ToBytes(value.$koraBytes)\n\t}\n\t// Pre-fix era: a raw Uint8Array in op.data JSON-serialized to a numeric-key\n\t// object. Nothing shipped relies on that shape, but dev databases may still\n\t// contain such operations — reconstructing the bytes here is cheap and\n\t// prevents those databases from crashing on replay/apply/merge. No migration\n\t// is written for this; new operations always use the tagged form.\n\tif (isLegacyNumericByteObject(value)) {\n\t\tconst keys = Object.keys(value)\n\t\tconst bytes = new Uint8Array(keys.length)\n\t\tfor (let i = 0; i < keys.length; i++) {\n\t\t\tbytes[i] = value[String(i)] ?? 0\n\t\t}\n\t\treturn bytes\n\t}\n\tthrow new OperationError(\n\t\t'Binary op-data value must be a string, Uint8Array, ArrayBuffer, tagged { $koraBytes } object, or legacy numeric-key byte object.',\n\t\t{ receivedType: typeof value },\n\t)\n}\n","import type { SchemaDefinition, SyncRuleDefinition } from '../types'\n\n/**\n * Returns true when the schema declares partial sync rules at the root level.\n */\nexport function hasSchemaSyncRules(schema: SchemaDefinition): boolean {\n\treturn schema.sync !== undefined && Object.keys(schema.sync).length > 0\n}\n\n/**\n * Resolve field → scope-value-key bindings for a collection.\n *\n * Sync rules take precedence over legacy `collection.scope` arrays.\n * Returns `null` when the collection has no sync filtering configured.\n */\nexport function getCollectionScopeBindings(\n\tschema: SchemaDefinition,\n\tcollectionName: string,\n): Record<string, string> | null {\n\tconst syncRule = schema.sync?.[collectionName]\n\tif (syncRule && Object.keys(syncRule.where).length > 0) {\n\t\treturn { ...syncRule.where }\n\t}\n\n\tconst scopeFields = schema.collections[collectionName]?.scope ?? []\n\tif (scopeFields.length === 0) {\n\t\treturn null\n\t}\n\n\tconst bindings: Record<string, string> = {}\n\tfor (const field of scopeFields) {\n\t\tbindings[field] = field\n\t}\n\treturn bindings\n}\n\n/**\n * Returns whether a collection participates in sync filtering for this schema.\n */\nexport function isCollectionSyncScoped(schema: SchemaDefinition, collectionName: string): boolean {\n\tif (hasSchemaSyncRules(schema)) {\n\t\tif (schema.sync?.[collectionName]) {\n\t\t\treturn true\n\t\t}\n\t\tconst legacyScope = schema.collections[collectionName]?.scope ?? []\n\t\treturn legacyScope.length > 0\n\t}\n\n\treturn getCollectionScopeBindings(schema, collectionName) !== null\n}\n\n/**\n * Collect unique scope value keys referenced by sync rules and legacy scope fields.\n */\nexport function collectSchemaScopeValueKeys(schema: SchemaDefinition): string[] {\n\tconst keys = new Set<string>()\n\n\tfor (const collection of Object.values(schema.collections)) {\n\t\tfor (const field of collection.scope) {\n\t\t\tkeys.add(field)\n\t\t}\n\t}\n\n\tif (schema.sync) {\n\t\tfor (const rule of Object.values(schema.sync)) {\n\t\t\tfor (const scopeKey of Object.values(rule.where)) {\n\t\t\t\tkeys.add(scopeKey)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn [...keys]\n}\n\n/**\n * Normalize developer sync rule input into internal bindings.\n */\nexport function normalizeSyncRuleWhere(\n\tcollectionName: string,\n\twhere: Record<string, boolean | string>,\n): SyncRuleDefinition['where'] {\n\tconst normalized: Record<string, string> = {}\n\n\tfor (const [field, scopeKey] of Object.entries(where)) {\n\t\tif (scopeKey === true) {\n\t\t\tnormalized[field] = field\n\t\t\tcontinue\n\t\t}\n\n\t\tif (typeof scopeKey === 'string' && scopeKey.length > 0) {\n\t\t\tnormalized[field] = scopeKey\n\t\t\tcontinue\n\t\t}\n\n\t\tthrow new Error(\n\t\t\t`Invalid sync rule for collection \"${collectionName}\": where.${field} must be true or a non-empty scope key string`,\n\t\t)\n\t}\n\n\treturn normalized\n}\n","import { SchemaValidationError } from '../errors/errors'\nimport type {\n\tFieldDescriptor,\n\tSchemaDefinition,\n\tStateMachineConstraint,\n\tTransitionMap,\n\tTransitionValidationResult,\n} from '../types'\n\n/**\n * Validates whether a transition from one state to another is allowed\n * by the given state machine constraint.\n *\n * @param constraint - The state machine constraint defining allowed transitions\n * @param fromValue - The current state value (before the transition)\n * @param toValue - The target state value (after the transition)\n * @returns A TransitionValidationResult describing whether the transition is valid\n *\n * @example\n * ```typescript\n * const constraint: StateMachineConstraint = {\n * field: 'status',\n * collection: 'orders',\n * transitions: {\n * draft: ['submitted', 'cancelled'],\n * submitted: ['approved'],\n * approved: [],\n * },\n * }\n *\n * const result = validateTransition(constraint, 'draft', 'submitted')\n * // { valid: true, from: 'draft', to: 'submitted', field: 'status',\n * // collection: 'orders', allowedTargets: ['submitted', 'cancelled'] }\n * ```\n */\nexport function validateTransition(\n\tconstraint: StateMachineConstraint,\n\tfromValue: unknown,\n\ttoValue: unknown,\n): TransitionValidationResult {\n\tconst from = String(fromValue)\n\tconst to = String(toValue)\n\tconst allowedTargets = constraint.transitions[from] ?? []\n\n\treturn {\n\t\tvalid: allowedTargets.includes(to),\n\t\tfrom,\n\t\tto,\n\t\tfield: constraint.field,\n\t\tcollection: constraint.collection,\n\t\tallowedTargets,\n\t}\n}\n\n/**\n * Extracts all state machine constraints from a schema definition.\n * Scans every collection for enum fields that have transition rules declared\n * via the `.transitions()` builder method.\n *\n * @param schema - The schema definition to extract constraints from\n * @returns An array of StateMachineConstraint objects, one per enum field with transitions\n *\n * @example\n * ```typescript\n * const schema = defineSchema({\n * version: 1,\n * collections: {\n * orders: {\n * fields: {\n * status: t.enum(['draft', 'submitted']).transitions({\n * draft: ['submitted'],\n * submitted: [],\n * }),\n * },\n * },\n * },\n * })\n *\n * const constraints = buildStateMachineConstraints(schema)\n * // [{ field: 'status', collection: 'orders', transitions: { draft: ['submitted'], submitted: [] } }]\n * ```\n */\nexport function buildStateMachineConstraints(schema: SchemaDefinition): StateMachineConstraint[] {\n\tconst constraints: StateMachineConstraint[] = []\n\n\tfor (const [collectionName, collection] of Object.entries(schema.collections)) {\n\t\tfor (const [fieldName, descriptor] of Object.entries(collection.fields)) {\n\t\t\tif (descriptor.kind === 'enum' && descriptor.transitions !== null) {\n\t\t\t\tconstraints.push({\n\t\t\t\t\tfield: fieldName,\n\t\t\t\t\tcollection: collectionName,\n\t\t\t\t\ttransitions: descriptor.transitions,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t}\n\n\treturn constraints\n}\n\n/**\n * Finds the state machine constraint for a specific field in a specific collection,\n * if one exists.\n *\n * @param schema - The schema definition to search\n * @param collection - The collection name\n * @param field - The field name\n * @returns The TransitionMap if the field has transitions declared, or null otherwise\n */\nexport function getTransitionMap(\n\tschema: SchemaDefinition,\n\tcollection: string,\n\tfield: string,\n): TransitionMap | null {\n\tconst collectionDef = schema.collections[collection]\n\tif (!collectionDef) {\n\t\treturn null\n\t}\n\tconst fieldDef = collectionDef.fields[field]\n\tif (!fieldDef || fieldDef.kind !== 'enum') {\n\t\treturn null\n\t}\n\treturn fieldDef.transitions\n}\n\n/**\n * Validates a state machine definition against a collection's fields during schema building.\n * Called by defineSchema() to ensure the state machine is well-formed.\n *\n * @param collectionName - Name of the collection for error messages\n * @param sm - The state machine input definition\n * @param fields - The built field descriptors for the collection\n * @throws {SchemaValidationError} If the state machine definition is invalid\n */\nexport function validateStateMachineDefinition(\n\tcollectionName: string,\n\tsm: { field: string; transitions: Record<string, string[]>; onInvalidTransition: string },\n\tfields: Record<string, FieldDescriptor>,\n): void {\n\tconst fieldDef = fields[sm.field]\n\tif (!fieldDef) {\n\t\tthrow new SchemaValidationError(\n\t\t\t`State machine field \"${sm.field}\" does not exist in collection \"${collectionName}\". Available fields: ${Object.keys(fields).join(', ')}`,\n\t\t\t{ collection: collectionName, field: sm.field },\n\t\t)\n\t}\n\tif (fieldDef.kind !== 'enum') {\n\t\tthrow new SchemaValidationError(\n\t\t\t`State machine field \"${sm.field}\" in collection \"${collectionName}\" must be an enum field, but got \"${fieldDef.kind}\"`,\n\t\t\t{ collection: collectionName, field: sm.field, kind: fieldDef.kind },\n\t\t)\n\t}\n\tconst enumValues = fieldDef.enumValues\n\tif (!enumValues || enumValues.length === 0) {\n\t\tthrow new SchemaValidationError(\n\t\t\t`State machine field \"${sm.field}\" in collection \"${collectionName}\" has no enum values defined`,\n\t\t\t{ collection: collectionName, field: sm.field },\n\t\t)\n\t}\n\tconst validValues = new Set(enumValues)\n\tfor (const [state, targets] of Object.entries(sm.transitions)) {\n\t\tif (!validValues.has(state)) {\n\t\t\tthrow new SchemaValidationError(\n\t\t\t\t`State machine transition source \"${state}\" is not a valid enum value for field \"${sm.field}\" in collection \"${collectionName}\". Valid values: ${[...validValues].join(', ')}`,\n\t\t\t\t{ collection: collectionName, field: sm.field, state },\n\t\t\t)\n\t\t}\n\t\tfor (const target of targets) {\n\t\t\tif (!validValues.has(target)) {\n\t\t\t\tthrow new SchemaValidationError(\n\t\t\t\t\t`State machine transition target \"${target}\" is not a valid enum value for field \"${sm.field}\" in collection \"${collectionName}\". Valid values: ${[...validValues].join(', ')}`,\n\t\t\t\t\t{ collection: collectionName, field: sm.field, state, target },\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t}\n\tif (sm.onInvalidTransition !== 'reject' && sm.onInvalidTransition !== 'last-valid-state') {\n\t\tthrow new SchemaValidationError(\n\t\t\t`State machine onInvalidTransition must be \"reject\" or \"last-valid-state\", got \"${sm.onInvalidTransition}\" in collection \"${collectionName}\"`,\n\t\t\t{ collection: collectionName, onInvalidTransition: sm.onInvalidTransition },\n\t\t)\n\t}\n}\n","import { SchemaValidationError } from '../errors/errors'\nimport type { MigrationDefinition } from '../migrations/migration-builder'\nimport { normalizeSyncRuleWhere } from '../scopes/sync-scope-bindings'\nimport { validateStateMachineDefinition } from '../state-machine/state-machine'\nimport type {\n\tCollectionDefinition,\n\tConstraint,\n\tCustomResolver,\n\tFieldDescriptor,\n\tRelationDefinition,\n\tSchemaDefinition,\n\tStateMachineDefinition,\n\tSyncRuleDefinition,\n} from '../types'\nimport type { FieldBuilder } from './types'\n\n/**\n * Valid collection name pattern: starts with a letter, then letters, numbers,\n * and underscores. Case is preserved, so camelCase (`formResponses`) and\n * PascalCase (`UserProfiles`) are allowed — generated SQL quotes every\n * identifier (see `quoteIdent`), so mixed case and even reserved words like\n * `order` round-trip safely. The leading-letter rule keeps names clear of the\n * framework's own `_`-prefixed tables.\n */\nconst COLLECTION_NAME_RE = /^[A-Za-z][A-Za-z0-9_]*$/\n\n/** Valid field name pattern: camelCase allowed (e.g. createdAt, dueDate) */\nconst FIELD_NAME_RE = /^[a-z][a-zA-Z0-9_]*$/\n\n/** Reserved field names that cannot be used in schemas */\nconst RESERVED_FIELDS = new Set(['id', '_created_at', '_updated_at', '_version', '_deleted'])\n\n/**\n * Input shape for defineSchema() — what the developer writes.\n */\nexport interface SchemaInput {\n\tversion: number\n\tcollections: Record<string, CollectionInput>\n\trelations?: Record<string, RelationInput>\n\t/** Schema migrations keyed by target version number. */\n\tmigrations?: Record<number, MigrationDefinition>\n\t/**\n\t * Declarative partial-sync rules.\n\t *\n\t * @example\n\t * ```typescript\n\t * sync: {\n\t * todos: { where: { userId: true, orgId: true } },\n\t * projects: { where: { orgId: true } },\n\t * }\n\t * ```\n\t */\n\tsync?: Record<string, SyncRuleInput>\n}\n\n/**\n * Developer input for a collection sync rule.\n */\nexport interface SyncRuleInput {\n\t/**\n\t * Field filters bound to scope values.\n\t * Use `true` to bind a field to a scope value with the same name.\n\t * Use a string to bind to a different scope value key.\n\t */\n\twhere: Record<string, boolean | string>\n}\n\nexport interface StateMachineInput {\n\t/** The enum field this state machine controls */\n\tfield: string\n\t/** Map of state to allowed next states */\n\ttransitions: Record<string, string[]>\n\t/** What to do when an invalid transition is attempted */\n\tonInvalidTransition: 'reject' | 'last-valid-state'\n}\n\nexport interface CollectionInput {\n\t// biome-ignore lint/suspicious/noExplicitAny: Required for TypeScript conditional type inference\n\tfields: Record<string, FieldBuilder<any, any, any>>\n\tindexes?: string[]\n\tconstraints?: ConstraintInput[]\n\tresolve?: Record<string, CustomResolver>\n\t/** Scope fields for sync filtering. Only records matching the client's scope values are synced. */\n\tscope?: string[]\n\t/** State machine definition constraining transitions on an enum field */\n\tstateMachine?: StateMachineInput\n}\n\nexport interface ConstraintInput {\n\ttype: 'unique' | 'capacity' | 'referential'\n\tfields: string[]\n\twhere?: Record<string, unknown>\n\tonConflict:\n\t\t| 'first-write-wins'\n\t\t| 'last-write-wins'\n\t\t| 'priority-field'\n\t\t| 'server-decides'\n\t\t| 'custom'\n\tpriorityField?: string\n\tresolve?: (local: unknown, remote: unknown, base: unknown) => unknown\n}\n\nexport interface RelationInput {\n\tfrom: string\n\tto: string\n\ttype: 'one-to-one' | 'one-to-many' | 'many-to-one' | 'many-to-many'\n\tfield: string\n\tonDelete: 'cascade' | 'set-null' | 'restrict' | 'no-action'\n}\n\n/**\n * Validates and builds a SchemaDefinition from developer input.\n * This is the primary developer-facing function for defining a schema.\n *\n * @param input - The schema definition using type builders\n * @returns A validated SchemaDefinition ready for use by the framework\n * @throws {SchemaValidationError} If the schema is invalid\n *\n * @example\n * ```typescript\n * import { defineSchema, t } from '@korajs/core'\n *\n * const schema = defineSchema({\n * version: 1,\n * collections: {\n * todos: {\n * fields: {\n * title: t.string(),\n * completed: t.boolean().default(false),\n * }\n * }\n * }\n * })\n * ```\n */\n/**\n * Schema definition with a phantom type brand preserving the original input shape.\n * The `__input` property exists only at the type level for inference — no runtime cost.\n */\nexport type TypedSchemaDefinition<T extends SchemaInput = SchemaInput> = SchemaDefinition & {\n\treadonly __input: T\n}\n\nexport function defineSchema<const T extends SchemaInput>(input: T): TypedSchemaDefinition<T> {\n\tvalidateVersion(input.version)\n\n\tconst collections: Record<string, CollectionDefinition> = {}\n\n\tfor (const [name, collectionInput] of Object.entries(input.collections)) {\n\t\tvalidateCollectionName(name)\n\t\tcollections[name] = buildCollection(name, collectionInput)\n\t}\n\n\tif (Object.keys(collections).length === 0) {\n\t\tthrow new SchemaValidationError('Schema must define at least one collection')\n\t}\n\n\tconst relations: Record<string, RelationDefinition> = {}\n\tif (input.relations) {\n\t\tfor (const [name, relationInput] of Object.entries(input.relations)) {\n\t\t\tvalidateRelation(name, relationInput, collections)\n\t\t\trelations[name] = { ...relationInput }\n\t\t}\n\t}\n\n\tconst migrations: Record<number, MigrationDefinition> = {}\n\tif (input.migrations) {\n\t\tfor (const [versionStr, migration] of Object.entries(input.migrations)) {\n\t\t\tconst version = Number(versionStr)\n\t\t\tif (!Number.isInteger(version) || version < 2) {\n\t\t\t\tthrow new SchemaValidationError(\n\t\t\t\t\t`Migration key \"${versionStr}\" is invalid. Must be an integer >= 2 (version 1 is the initial schema).`,\n\t\t\t\t\t{ version: versionStr },\n\t\t\t\t)\n\t\t\t}\n\t\t\tif (version > input.version) {\n\t\t\t\tthrow new SchemaValidationError(\n\t\t\t\t\t`Migration version ${version} exceeds schema version ${input.version}. Migrations must target versions <= schema version.`,\n\t\t\t\t\t{ migrationVersion: version, schemaVersion: input.version },\n\t\t\t\t)\n\t\t\t}\n\t\t\tif (!migration.steps || migration.steps.length === 0) {\n\t\t\t\tthrow new SchemaValidationError(\n\t\t\t\t\t`Migration for version ${version} has no steps. Use migrate() to define at least one step.`,\n\t\t\t\t\t{ version },\n\t\t\t\t)\n\t\t\t}\n\t\t\tmigrations[version] = migration\n\t\t}\n\t}\n\n\tconst sync = buildSyncRules(input.sync, collections)\n\tapplySyncRulesToCollectionScope(collections, sync)\n\n\treturn {\n\t\tversion: input.version,\n\t\tcollections,\n\t\trelations,\n\t\tmigrations,\n\t\t...(sync ? { sync } : {}),\n\t} as TypedSchemaDefinition<T>\n}\n\nfunction validateVersion(version: number): void {\n\tif (typeof version !== 'number' || !Number.isInteger(version) || version < 1) {\n\t\tthrow new SchemaValidationError('Schema version must be a positive integer', {\n\t\t\treceived: version,\n\t\t})\n\t}\n}\n\nfunction validateCollectionName(name: string): void {\n\tif (!COLLECTION_NAME_RE.test(name)) {\n\t\tthrow new SchemaValidationError(\n\t\t\t`Collection name \"${name}\" is invalid. Must start with a letter and contain only letters, numbers, and underscores.`,\n\t\t\t{ collection: name },\n\t\t)\n\t}\n}\n\nfunction buildCollection(name: string, input: CollectionInput): CollectionDefinition {\n\tconst fields: Record<string, FieldDescriptor> = {}\n\n\tif (!input.fields || Object.keys(input.fields).length === 0) {\n\t\tthrow new SchemaValidationError(`Collection \"${name}\" must define at least one field`, {\n\t\t\tcollection: name,\n\t\t})\n\t}\n\n\tfor (const [fieldName, builder] of Object.entries(input.fields)) {\n\t\tvalidateFieldName(name, fieldName)\n\t\tfields[fieldName] = builder._build()\n\t}\n\n\tconst indexes = input.indexes ?? []\n\tfor (const indexField of indexes) {\n\t\tif (!(indexField in fields)) {\n\t\t\tthrow new SchemaValidationError(\n\t\t\t\t`Index field \"${indexField}\" does not exist in collection \"${name}\". Available fields: ${Object.keys(fields).join(', ')}`,\n\t\t\t\t{ collection: name, field: indexField },\n\t\t\t)\n\t\t}\n\t}\n\n\tconst constraints: Constraint[] = []\n\tif (input.constraints) {\n\t\tfor (const constraintInput of input.constraints) {\n\t\t\tvalidateConstraint(name, constraintInput, fields)\n\t\t\tconstraints.push({ ...constraintInput })\n\t\t}\n\t}\n\n\tconst resolvers: Record<string, CustomResolver> = {}\n\tif (input.resolve) {\n\t\tfor (const [fieldName, resolver] of Object.entries(input.resolve)) {\n\t\t\tif (!(fieldName in fields)) {\n\t\t\t\tthrow new SchemaValidationError(\n\t\t\t\t\t`Resolver for field \"${fieldName}\" does not exist in collection \"${name}\". Available fields: ${Object.keys(fields).join(', ')}`,\n\t\t\t\t\t{ collection: name, field: fieldName },\n\t\t\t\t)\n\t\t\t}\n\t\t\tif (typeof resolver !== 'function') {\n\t\t\t\tthrow new SchemaValidationError(\n\t\t\t\t\t`Resolver for field \"${fieldName}\" in collection \"${name}\" must be a function`,\n\t\t\t\t\t{ collection: name, field: fieldName },\n\t\t\t\t)\n\t\t\t}\n\t\t\tresolvers[fieldName] = resolver\n\t\t}\n\t}\n\n\tconst scope: string[] = []\n\tif (input.scope) {\n\t\tfor (const scopeField of input.scope) {\n\t\t\tif (!(scopeField in fields)) {\n\t\t\t\tthrow new SchemaValidationError(\n\t\t\t\t\t`Scope field \"${scopeField}\" does not exist in collection \"${name}\". Available fields: ${Object.keys(fields).join(', ')}`,\n\t\t\t\t\t{ collection: name, field: scopeField },\n\t\t\t\t)\n\t\t\t}\n\t\t\tscope.push(scopeField)\n\t\t}\n\t}\n\n\tlet stateMachine: StateMachineDefinition | undefined\n\tif (input.stateMachine) {\n\t\tvalidateStateMachineDefinition(name, input.stateMachine, fields)\n\t\tstateMachine = { ...input.stateMachine }\n\t}\n\n\treturn { fields, indexes, constraints, resolvers, scope, stateMachine }\n}\n\nfunction buildSyncRules(\n\tsyncInput: SchemaInput['sync'],\n\tcollections: Record<string, CollectionDefinition>,\n): Record<string, SyncRuleDefinition> | undefined {\n\tif (!syncInput) {\n\t\treturn undefined\n\t}\n\n\tconst sync: Record<string, SyncRuleDefinition> = {}\n\n\tfor (const [collectionName, ruleInput] of Object.entries(syncInput)) {\n\t\tif (!(collectionName in collections)) {\n\t\t\tthrow new SchemaValidationError(\n\t\t\t\t`Sync rule references collection \"${collectionName}\" which does not exist. Available collections: ${Object.keys(collections).join(', ')}`,\n\t\t\t\t{ collection: collectionName },\n\t\t\t)\n\t\t}\n\n\t\tif (!ruleInput.where || Object.keys(ruleInput.where).length === 0) {\n\t\t\tthrow new SchemaValidationError(\n\t\t\t\t`Sync rule for collection \"${collectionName}\" must declare at least one where binding`,\n\t\t\t\t{ collection: collectionName },\n\t\t\t)\n\t\t}\n\n\t\tconst collection = collections[collectionName]\n\t\tif (!collection) {\n\t\t\tcontinue\n\t\t}\n\n\t\tfor (const fieldName of Object.keys(ruleInput.where)) {\n\t\t\tif (!(fieldName in collection.fields)) {\n\t\t\t\tthrow new SchemaValidationError(\n\t\t\t\t\t`Sync rule where field \"${fieldName}\" does not exist in collection \"${collectionName}\". Available fields: ${Object.keys(collection.fields).join(', ')}`,\n\t\t\t\t\t{ collection: collectionName, field: fieldName },\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\n\t\ttry {\n\t\t\tsync[collectionName] = { where: normalizeSyncRuleWhere(collectionName, ruleInput.where) }\n\t\t} catch (error) {\n\t\t\tthrow new SchemaValidationError(\n\t\t\t\terror instanceof Error ? error.message : 'Invalid sync rule',\n\t\t\t\t{ collection: collectionName },\n\t\t\t)\n\t\t}\n\t}\n\n\treturn sync\n}\n\nfunction applySyncRulesToCollectionScope(\n\tcollections: Record<string, CollectionDefinition>,\n\tsync: Record<string, SyncRuleDefinition> | undefined,\n): void {\n\tif (!sync) {\n\t\treturn\n\t}\n\n\tfor (const [collectionName, rule] of Object.entries(sync)) {\n\t\tconst collection = collections[collectionName]\n\t\tif (!collection) {\n\t\t\tcontinue\n\t\t}\n\n\t\tfor (const fieldName of Object.keys(rule.where)) {\n\t\t\tif (!collection.scope.includes(fieldName)) {\n\t\t\t\tcollection.scope.push(fieldName)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunction validateFieldName(collection: string, fieldName: string): void {\n\tif (RESERVED_FIELDS.has(fieldName)) {\n\t\tthrow new SchemaValidationError(\n\t\t\t`Field name \"${fieldName}\" is reserved in collection \"${collection}\". Reserved fields: ${[...RESERVED_FIELDS].join(', ')}`,\n\t\t\t{ collection, field: fieldName },\n\t\t)\n\t}\n\tif (!FIELD_NAME_RE.test(fieldName)) {\n\t\tthrow new SchemaValidationError(\n\t\t\t`Field name \"${fieldName}\" in collection \"${collection}\" is invalid. Must start with a lowercase letter and contain only letters, numbers, and underscores.`,\n\t\t\t{ collection, field: fieldName },\n\t\t)\n\t}\n}\n\nfunction validateConstraint(\n\tcollection: string,\n\tconstraint: ConstraintInput,\n\tfields: Record<string, FieldDescriptor>,\n): void {\n\tfor (const field of constraint.fields) {\n\t\tif (!(field in fields)) {\n\t\t\tthrow new SchemaValidationError(\n\t\t\t\t`Constraint references field \"${field}\" which does not exist in collection \"${collection}\". Available fields: ${Object.keys(fields).join(', ')}`,\n\t\t\t\t{ collection, field },\n\t\t\t)\n\t\t}\n\t}\n\n\tif (constraint.onConflict === 'priority-field' && !constraint.priorityField) {\n\t\tthrow new SchemaValidationError(\n\t\t\t`Constraint with \"priority-field\" onConflict strategy in collection \"${collection}\" requires a priorityField`,\n\t\t\t{ collection },\n\t\t)\n\t}\n\n\tif (constraint.onConflict === 'priority-field' && constraint.priorityField) {\n\t\tif (!(constraint.priorityField in fields)) {\n\t\t\tthrow new SchemaValidationError(\n\t\t\t\t`Constraint priorityField \"${constraint.priorityField}\" does not exist in collection \"${collection}\"`,\n\t\t\t\t{ collection, field: constraint.priorityField },\n\t\t\t)\n\t\t}\n\t}\n\n\tif (constraint.onConflict === 'custom' && typeof constraint.resolve !== 'function') {\n\t\tthrow new SchemaValidationError(\n\t\t\t`Constraint with \"custom\" onConflict strategy in collection \"${collection}\" requires a resolve function`,\n\t\t\t{ collection },\n\t\t)\n\t}\n}\n\nfunction validateRelation(\n\tname: string,\n\trelation: RelationInput,\n\tcollections: Record<string, CollectionDefinition>,\n): void {\n\tif (!(relation.from in collections)) {\n\t\tthrow new SchemaValidationError(\n\t\t\t`Relation \"${name}\" references source collection \"${relation.from}\" which does not exist. Available collections: ${Object.keys(collections).join(', ')}`,\n\t\t\t{ relation: name, collection: relation.from },\n\t\t)\n\t}\n\n\tif (!(relation.to in collections)) {\n\t\tthrow new SchemaValidationError(\n\t\t\t`Relation \"${name}\" references target collection \"${relation.to}\" which does not exist. Available collections: ${Object.keys(collections).join(', ')}`,\n\t\t\t{ relation: name, collection: relation.to },\n\t\t)\n\t}\n\n\tconst fromCollection = collections[relation.from]\n\tif (fromCollection && !(relation.field in fromCollection.fields)) {\n\t\tthrow new SchemaValidationError(\n\t\t\t`Relation \"${name}\" references field \"${relation.field}\" which does not exist in collection \"${relation.from}\". Available fields: ${Object.keys(fromCollection.fields).join(', ')}`,\n\t\t\t{ relation: name, collection: relation.from, field: relation.field },\n\t\t)\n\t}\n}\n","/**\n * Quote a SQL identifier (table or column name) for safe interpolation into\n * generated SQL.\n *\n * Uses standard double-quote quoting, which both SQLite and PostgreSQL honor,\n * and doubles any embedded double-quote per the SQL standard. Quoting is what\n * lets a valid JavaScript identifier — camelCase (`formResponses`), PascalCase\n * (`UserProfiles`), or a word that happens to be a SQL keyword (`order`,\n * `select`) — round-trip through generated DDL and queries without ever\n * producing invalid or ambiguous SQL.\n *\n * Schema validation (see `validateCollectionName` / `validateFieldName`)\n * already restricts identifiers to `[A-Za-z][A-Za-z0-9_]*`, so the escape here\n * never actually fires in practice; it is defense in depth so this helper is\n * correct for any input rather than only for pre-validated names.\n *\n * Consistency is the contract: every path that emits an identifier for a\n * user-defined collection or field MUST go through this helper, because a\n * quoted `CREATE TABLE \"order\"` paired with an unquoted `SELECT ... FROM order`\n * would reintroduce the exact keyword-collision bug this guards against.\n *\n * @param name - The raw identifier (collection name, field/column name).\n * @returns The identifier wrapped in double quotes, ready to splice into SQL.\n *\n * @example\n * ```typescript\n * quoteIdent('formResponses') // => '\"formResponses\"'\n * quoteIdent('order') // => '\"order\"'\n * ```\n */\nexport function quoteIdent(name: string): string {\n\treturn `\"${name.replace(/\"/g, '\"\"')}\"`\n}\n","import type {\n\tCollectionDefinition,\n\tFieldDescriptor,\n\tRelationDefinition,\n\tSchemaDefinition,\n} from '../types'\nimport { quoteIdent } from './quote-ident'\n\n/**\n * Generate CREATE TABLE and CREATE INDEX SQL for a single collection.\n *\n * @param collectionName - The collection name\n * @param collection - The collection definition\n * @param relations - Optional relations for FK references\n * @returns An array of SQL statements (CREATE TABLE + CREATE INDEX)\n */\nexport function generateSQL(\n\tcollectionName: string,\n\tcollection: CollectionDefinition,\n\trelations?: Record<string, RelationDefinition>,\n): string[] {\n\tconst statements: string[] = []\n\tconst columns: string[] = ['id TEXT PRIMARY KEY NOT NULL']\n\n\t// Track which fields already have indexes\n\tconst indexedFields = new Set(collection.indexes)\n\n\t// Collect FK fields for auto-indexing\n\tconst fkFields: string[] = []\n\n\tfor (const [fieldName, descriptor] of Object.entries(collection.fields)) {\n\t\tlet colDef = columnDefinition(fieldName, descriptor)\n\n\t\t// Add FK reference if a relation exists for this field\n\t\tif (relations) {\n\t\t\tfor (const rel of Object.values(relations)) {\n\t\t\t\tif (rel.from === collectionName && rel.field === fieldName) {\n\t\t\t\t\tcolDef += ` REFERENCES ${quoteIdent(rel.to)}(id)`\n\t\t\t\t\tfkFields.push(fieldName)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tcolumns.push(colDef)\n\t}\n\n\t// Auto metadata columns\n\tcolumns.push('_created_at INTEGER NOT NULL')\n\tcolumns.push('_updated_at INTEGER NOT NULL')\n\tcolumns.push(\"_version TEXT NOT NULL DEFAULT ''\")\n\t// Per-field last-writer HLC versions (JSON: { field -> serialized HLC }).\n\t// Enables deterministic, order-independent field-level LWW so concurrent\n\t// edits to different fields of one record never clobber each other and\n\t// same-field conflicts converge to the max-timestamp writer on every node.\n\tcolumns.push(\"_field_versions TEXT NOT NULL DEFAULT '{}'\")\n\tcolumns.push('_deleted INTEGER NOT NULL DEFAULT 0')\n\n\tstatements.push(\n\t\t`CREATE TABLE IF NOT EXISTS ${quoteIdent(collectionName)} (\\n ${columns.join(',\\n ')}\\n)`,\n\t)\n\n\t// Add ALTER TABLE statements so new columns are added to existing tables.\n\t// These are tagged with --kora:safe-alter so the runtime can ignore \"duplicate column\" errors.\n\tfor (const [fieldName, descriptor] of Object.entries(collection.fields)) {\n\t\tconst colDef = columnDefinition(fieldName, descriptor)\n\t\tstatements.push(\n\t\t\t`--kora:safe-alter\\nALTER TABLE ${quoteIdent(collectionName)} ADD COLUMN ${colDef}`,\n\t\t)\n\t}\n\tstatements.push(\n\t\t`--kora:safe-alter\\nALTER TABLE ${quoteIdent(collectionName)} ADD COLUMN _version TEXT NOT NULL DEFAULT ''`,\n\t)\n\tstatements.push(\n\t\t`--kora:safe-alter\\nALTER TABLE ${quoteIdent(collectionName)} ADD COLUMN _field_versions TEXT NOT NULL DEFAULT '{}'`,\n\t)\n\n\t// Create indexes. The index NAME stays unquoted (it is only ever created and\n\t// dropped by this same construction, never referenced by a query), but the\n\t// table and column in the ON clause are quoted so mixed-case / keyword names\n\t// resolve correctly.\n\tfor (const indexField of collection.indexes) {\n\t\tstatements.push(\n\t\t\t`CREATE INDEX IF NOT EXISTS idx_${collectionName}_${indexField} ON ${quoteIdent(collectionName)} (${quoteIdent(indexField)})`,\n\t\t)\n\t}\n\n\t// Auto-create indexes on FK columns not already indexed\n\tfor (const fkField of fkFields) {\n\t\tif (!indexedFields.has(fkField)) {\n\t\t\tstatements.push(\n\t\t\t\t`CREATE INDEX IF NOT EXISTS idx_${collectionName}_${fkField} ON ${quoteIdent(collectionName)} (${quoteIdent(fkField)})`,\n\t\t\t)\n\t\t}\n\t}\n\n\t// Per-collection operations log table. The table name carries the collection\n\t// name, so it is quoted too (a collection named `order` would otherwise make\n\t// `_kora_ops_order` collide with reserved-word handling on some engines).\n\tstatements.push(\n\t\t`CREATE TABLE IF NOT EXISTS ${quoteIdent(`_kora_ops_${collectionName}`)} (\n id TEXT PRIMARY KEY NOT NULL,\n node_id TEXT NOT NULL,\n type TEXT NOT NULL,\n record_id TEXT NOT NULL,\n data TEXT,\n previous_data TEXT,\n timestamp TEXT NOT NULL,\n sequence_number INTEGER NOT NULL,\n causal_deps TEXT NOT NULL,\n schema_version INTEGER NOT NULL\n)`,\n\t)\n\t// Record-scoped lookups run on every remote apply (latest-op-for-record,\n\t// orphaned-op fold on out-of-order inserts) — index them.\n\tstatements.push(\n\t\t`CREATE INDEX IF NOT EXISTS idx_kora_ops_${collectionName}_record_id ON ${quoteIdent(`_kora_ops_${collectionName}`)} (record_id)`,\n\t)\n\n\treturn statements\n}\n\n/**\n * Generate the full DDL for all collections plus metadata tables.\n *\n * @param schema - The complete schema definition\n * @returns An array of all SQL statements needed to initialize the database\n */\nexport function generateFullDDL(schema: SchemaDefinition): string[] {\n\tconst statements: string[] = []\n\n\t// Metadata table\n\tstatements.push(\n\t\t'CREATE TABLE IF NOT EXISTS _kora_meta (\\n' +\n\t\t\t' key TEXT PRIMARY KEY NOT NULL,\\n' +\n\t\t\t' value TEXT NOT NULL\\n' +\n\t\t\t')',\n\t)\n\n\t// Version vector table\n\tstatements.push(\n\t\t'CREATE TABLE IF NOT EXISTS _kora_version_vector (\\n' +\n\t\t\t' node_id TEXT PRIMARY KEY NOT NULL,\\n' +\n\t\t\t' sequence_number INTEGER NOT NULL\\n' +\n\t\t\t')',\n\t)\n\n\t// Sequence counters table (offline-safe sequences)\n\tstatements.push(\n\t\t'CREATE TABLE IF NOT EXISTS _kora_sequences (\\n' +\n\t\t\t' name TEXT NOT NULL,\\n' +\n\t\t\t\" scope TEXT NOT NULL DEFAULT '',\\n\" +\n\t\t\t' node_id TEXT NOT NULL,\\n' +\n\t\t\t' counter INTEGER NOT NULL DEFAULT 0,\\n' +\n\t\t\t' PRIMARY KEY (name, scope, node_id)\\n' +\n\t\t\t')',\n\t)\n\n\t// Durable outbound sync queue (survives page refresh)\n\tstatements.push(\n\t\t'CREATE TABLE IF NOT EXISTS _kora_sync_queue (\\n' +\n\t\t\t' id TEXT PRIMARY KEY NOT NULL,\\n' +\n\t\t\t' payload TEXT NOT NULL\\n' +\n\t\t\t')',\n\t)\n\n\t// Durable record of operations the server rejected (survives page refresh).\n\t// An op lands here after being diverted out of the outbound queue, so it is\n\t// never retried yet stays explainable to the app until reconciled.\n\tstatements.push(\n\t\t'CREATE TABLE IF NOT EXISTS _kora_sync_rejected (\\n' +\n\t\t\t' operation_id TEXT PRIMARY KEY NOT NULL,\\n' +\n\t\t\t' collection TEXT NOT NULL,\\n' +\n\t\t\t' record_id TEXT NOT NULL,\\n' +\n\t\t\t' code TEXT NOT NULL,\\n' +\n\t\t\t' message TEXT NOT NULL,\\n' +\n\t\t\t' retriable INTEGER NOT NULL,\\n' +\n\t\t\t' rejected_at INTEGER NOT NULL\\n' +\n\t\t\t')',\n\t)\n\n\t// Durable merge / constraint audit trail (enterprise audit export)\n\tstatements.push(\n\t\t'CREATE TABLE IF NOT EXISTS _kora_audit_traces (\\n' +\n\t\t\t' id TEXT PRIMARY KEY NOT NULL,\\n' +\n\t\t\t' recorded_at INTEGER NOT NULL,\\n' +\n\t\t\t' event_type TEXT NOT NULL,\\n' +\n\t\t\t' collection TEXT NOT NULL,\\n' +\n\t\t\t' record_id TEXT NOT NULL,\\n' +\n\t\t\t' field TEXT NOT NULL,\\n' +\n\t\t\t' strategy TEXT NOT NULL,\\n' +\n\t\t\t' tier INTEGER NOT NULL,\\n' +\n\t\t\t' constraint_name TEXT,\\n' +\n\t\t\t' trace_json TEXT NOT NULL\\n' +\n\t\t\t')',\n\t)\n\tstatements.push(\n\t\t'CREATE INDEX IF NOT EXISTS idx_kora_audit_traces_recorded_at ON _kora_audit_traces (recorded_at)',\n\t)\n\tstatements.push(\n\t\t'CREATE INDEX IF NOT EXISTS idx_kora_audit_traces_collection ON _kora_audit_traces (collection)',\n\t)\n\n\tfor (const [name, collection] of Object.entries(schema.collections)) {\n\t\tstatements.push(...generateSQL(name, collection, schema.relations))\n\t}\n\n\treturn statements\n}\n\nfunction columnDefinition(fieldName: string, descriptor: FieldDescriptor): string {\n\tconst sqlType = mapFieldType(descriptor)\n\tconst parts = [quoteIdent(fieldName), sqlType]\n\n\tif (descriptor.required && descriptor.defaultValue === undefined && !descriptor.auto) {\n\t\tparts.push('NOT NULL')\n\t}\n\n\tif (descriptor.defaultValue !== undefined) {\n\t\tparts.push(`DEFAULT ${sqlDefault(descriptor.defaultValue)}`)\n\t}\n\n\t// CHECK constraint for enum fields\n\tif (descriptor.kind === 'enum' && descriptor.enumValues) {\n\t\tconst values = descriptor.enumValues.map((v) => `'${v}'`).join(', ')\n\t\tparts.push(`CHECK (${quoteIdent(fieldName)} IN (${values}))`)\n\t}\n\n\treturn parts.join(' ')\n}\n\nfunction mapFieldType(descriptor: FieldDescriptor): string {\n\tswitch (descriptor.kind) {\n\t\tcase 'string':\n\t\t\treturn 'TEXT'\n\t\tcase 'number':\n\t\t\treturn 'REAL'\n\t\tcase 'boolean':\n\t\t\treturn 'INTEGER'\n\t\tcase 'enum':\n\t\t\treturn 'TEXT'\n\t\tcase 'timestamp':\n\t\t\treturn 'INTEGER'\n\t\tcase 'array':\n\t\t\treturn 'TEXT' // JSON-serialized\n\t\tcase 'object':\n\t\t\treturn 'TEXT' // JSON-serialized structured object\n\t\tcase 'json':\n\t\t\treturn 'TEXT' // JSON-serialized dynamic-key value\n\t\tcase 'blob':\n\t\t\treturn 'TEXT' // JSON-serialized content-addressed BlobRef (bytes stored out of band)\n\t\tcase 'secret':\n\t\t\treturn 'TEXT'\n\t\tcase 'richtext':\n\t\t\treturn 'BLOB' // Yjs state\n\t}\n}\n\nfunction sqlDefault(value: unknown): string {\n\tif (value === null) return 'NULL'\n\tif (typeof value === 'string') return `'${value}'`\n\tif (typeof value === 'number') return String(value)\n\tif (typeof value === 'boolean') return value ? '1' : '0'\n\t// Arrays and objects are stored as JSON strings\n\treturn `'${JSON.stringify(value)}'`\n}\n","import { SchemaValidationError } from '../errors/errors'\nimport type {\n\tFieldDescriptor,\n\tFieldKind,\n\tFieldMergeStrategy,\n\tSecretMode,\n\tTransitionMap,\n} from '../types'\n\n/**\n * Base field builder implementing the builder pattern for schema field definitions.\n * Each builder is immutable — modifier methods return new builder instances.\n *\n * Type parameters track field metadata at the type level for inference:\n * - Kind: the field kind ('string', 'number', etc.)\n * - Req: whether the field is required (true = required on insert)\n * - Auto: whether the field is auto-populated (true = excluded from insert input)\n *\n * @example\n * ```typescript\n * t.string() // required string field\n * t.string().optional() // optional string field\n * t.string().default('hello') // string with default value\n * t.timestamp().auto() // auto-populated timestamp\n * ```\n */\nexport class FieldBuilder<\n\tKind extends FieldKind = FieldKind,\n\tReq extends boolean = true,\n\tAuto extends boolean = false,\n> {\n\tprotected readonly _kind: Kind\n\tprotected readonly _required: boolean\n\tprotected readonly _defaultValue: unknown\n\tprotected readonly _auto: boolean\n\tprotected readonly _mergeStrategy: FieldMergeStrategy | null\n\n\tconstructor(\n\t\tkind: Kind,\n\t\trequired = true as unknown as Req,\n\t\tdefaultValue: unknown = undefined,\n\t\tauto = false as unknown as Auto,\n\t\tmergeStrategy: FieldMergeStrategy | null = null,\n\t) {\n\t\tthis._kind = kind\n\t\tthis._required = required as unknown as boolean\n\t\tthis._defaultValue = defaultValue\n\t\tthis._auto = auto as unknown as boolean\n\t\tthis._mergeStrategy = mergeStrategy\n\t}\n\n\t/** Mark this field as optional (not required on insert) */\n\toptional(): FieldBuilder<Kind, false, Auto> {\n\t\treturn new FieldBuilder(this._kind, false, this._defaultValue, this._auto, this._mergeStrategy)\n\t}\n\n\t/** Set a default value for this field. Implicitly makes the field optional. */\n\tdefault(value: unknown): FieldBuilder<Kind, false, Auto> {\n\t\treturn new FieldBuilder(this._kind, false, value, this._auto, this._mergeStrategy)\n\t}\n\n\t/** Mark this field as auto-populated (e.g., createdAt timestamps). Developers cannot set auto fields. */\n\tauto(): FieldBuilder<Kind, false, true> {\n\t\treturn new FieldBuilder(this._kind, false, undefined, true, this._mergeStrategy)\n\t}\n\n\t/**\n\t * Declare a merge strategy for this field.\n\t * Controls how concurrent modifications are resolved during sync.\n\t *\n\t * @param strategy - The merge strategy to use:\n\t * - `'lww'`: Last-write-wins (default for scalar fields)\n\t * - `'counter'`: Sum of deltas from base (for numbers)\n\t * - `'max'`: Keep the maximum value (for numbers/timestamps)\n\t * - `'min'`: Keep the minimum value (for numbers/timestamps)\n\t * - `'union'`: Set-union merge (default for arrays)\n\t * - `'append-only'`: Concatenate additions (for arrays)\n\t * - `'server-authoritative'`: Always prefer the remote/server value\n\t */\n\tmerge(strategy: FieldMergeStrategy): FieldBuilder<Kind, Req, Auto> {\n\t\treturn new FieldBuilder(\n\t\t\tthis._kind,\n\t\t\tthis._required as unknown as Req,\n\t\t\tthis._defaultValue,\n\t\t\tthis._auto as unknown as Auto,\n\t\t\tstrategy,\n\t\t)\n\t}\n\n\t/** @internal Build the final FieldDescriptor. Used by defineSchema(). */\n\t_build(): FieldDescriptor {\n\t\treturn {\n\t\t\tkind: this._kind,\n\t\t\trequired: this._required as unknown as boolean,\n\t\t\tdefaultValue: this._defaultValue,\n\t\t\tauto: this._auto as unknown as boolean,\n\t\t\tenumValues: null,\n\t\t\titemKind: null,\n\t\t\tmergeStrategy: this._mergeStrategy,\n\t\t\ttransitions: null,\n\t\t}\n\t}\n}\n\n/**\n * Field builder for enum fields with constrained string values.\n * Preserves the literal enum tuple type for inference.\n */\nexport class EnumFieldBuilder<\n\tValues extends readonly string[] = readonly string[],\n\tReq extends boolean = true,\n\tAuto extends boolean = false,\n> extends FieldBuilder<'enum', Req, Auto> {\n\tprivate readonly _enumValues: Values\n\tprivate readonly _transitions: TransitionMap | null\n\n\tconstructor(\n\t\tvalues: Values,\n\t\trequired = true as unknown as Req,\n\t\tdefaultValue: unknown = undefined,\n\t\tauto = false as unknown as Auto,\n\t\tmergeStrategy: FieldMergeStrategy | null = null,\n\t\ttransitions: TransitionMap | null = null,\n\t) {\n\t\tsuper('enum', required, defaultValue, auto, mergeStrategy)\n\t\tthis._enumValues = values\n\t\tthis._transitions = transitions\n\t}\n\n\toverride optional(): EnumFieldBuilder<Values, false, Auto> {\n\t\treturn new EnumFieldBuilder(\n\t\t\tthis._enumValues,\n\t\t\tfalse,\n\t\t\tthis._defaultValue,\n\t\t\tthis._auto,\n\t\t\tthis._mergeStrategy,\n\t\t\tthis._transitions,\n\t\t)\n\t}\n\n\toverride default(value: Values[number]): EnumFieldBuilder<Values, false, Auto> {\n\t\treturn new EnumFieldBuilder(\n\t\t\tthis._enumValues,\n\t\t\tfalse,\n\t\t\tvalue,\n\t\t\tthis._auto,\n\t\t\tthis._mergeStrategy,\n\t\t\tthis._transitions,\n\t\t)\n\t}\n\n\toverride auto(): EnumFieldBuilder<Values, false, true> {\n\t\treturn new EnumFieldBuilder(\n\t\t\tthis._enumValues,\n\t\t\tfalse,\n\t\t\tundefined,\n\t\t\ttrue,\n\t\t\tthis._mergeStrategy,\n\t\t\tthis._transitions,\n\t\t)\n\t}\n\n\toverride merge(strategy: FieldMergeStrategy): EnumFieldBuilder<Values, Req, Auto> {\n\t\treturn new EnumFieldBuilder(\n\t\t\tthis._enumValues,\n\t\t\tthis._required as unknown as Req,\n\t\t\tthis._defaultValue,\n\t\t\tthis._auto as unknown as Auto,\n\t\t\tstrategy,\n\t\t\tthis._transitions,\n\t\t)\n\t}\n\n\t/**\n\t * Declare allowed state transitions for this enum field.\n\t * Enables state machine validation during mutations and merges.\n\t *\n\t * @param map - Map of state to allowed next states\n\t *\n\t * @example\n\t * ```typescript\n\t * t.enum(['draft', 'pending', 'confirmed', 'cancelled']).transitions({\n\t * draft: ['pending', 'cancelled'],\n\t * pending: ['confirmed', 'cancelled'],\n\t * confirmed: [],\n\t * cancelled: [],\n\t * })\n\t * ```\n\t */\n\ttransitions(\n\t\tmap: Partial<Record<Values[number], Values[number][]>>,\n\t): EnumFieldBuilder<Values, Req, Auto> {\n\t\t// Validate that all source and target states are valid enum values\n\t\tconst validValues = new Set(this._enumValues as readonly string[])\n\t\tfor (const [state, targets] of Object.entries(map)) {\n\t\t\tif (!validValues.has(state)) {\n\t\t\t\tthrow new SchemaValidationError(\n\t\t\t\t\t`Invalid source state \"${state}\" in transition map. Valid values: ${[...validValues].join(', ')}`,\n\t\t\t\t\t{ state, validValues: [...validValues] },\n\t\t\t\t)\n\t\t\t}\n\t\t\tfor (const target of targets as string[]) {\n\t\t\t\tif (!validValues.has(target)) {\n\t\t\t\t\tthrow new SchemaValidationError(\n\t\t\t\t\t\t`Invalid target state \"${target}\" in transition from \"${state}\". Valid values: ${[...validValues].join(', ')}`,\n\t\t\t\t\t\t{ state, target, validValues: [...validValues] },\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn new EnumFieldBuilder(\n\t\t\tthis._enumValues,\n\t\t\tthis._required as unknown as Req,\n\t\t\tthis._defaultValue,\n\t\t\tthis._auto as unknown as Auto,\n\t\t\tthis._mergeStrategy,\n\t\t\tmap as TransitionMap,\n\t\t)\n\t}\n\n\toverride _build(): FieldDescriptor {\n\t\treturn {\n\t\t\tkind: 'enum',\n\t\t\trequired: this._required as unknown as boolean,\n\t\t\tdefaultValue: this._defaultValue,\n\t\t\tauto: this._auto as unknown as boolean,\n\t\t\tenumValues: this._enumValues,\n\t\t\titemKind: null,\n\t\t\tmergeStrategy: this._mergeStrategy,\n\t\t\ttransitions: this._transitions,\n\t\t}\n\t}\n}\n\n/**\n * Field builder for array fields with a typed item kind.\n * Preserves the item kind type parameter for inference.\n */\nexport class ArrayFieldBuilder<\n\tItemKind extends FieldKind = FieldKind,\n\tReq extends boolean = true,\n\tAuto extends boolean = false,\n> extends FieldBuilder<'array', Req, Auto> {\n\tprivate readonly _itemKind: ItemKind\n\n\tconstructor(\n\t\titemBuilder: FieldBuilder<ItemKind>,\n\t\trequired = true as unknown as Req,\n\t\tdefaultValue: unknown = undefined,\n\t\tauto = false as unknown as Auto,\n\t\tmergeStrategy: FieldMergeStrategy | null = null,\n\t) {\n\t\tsuper('array', required, defaultValue, auto, mergeStrategy)\n\t\tthis._itemKind = itemBuilder._build().kind as ItemKind\n\t}\n\n\toverride optional(): ArrayFieldBuilder<ItemKind, false, Auto> {\n\t\treturn new ArrayFieldBuilder(\n\t\t\tnew FieldBuilder(this._itemKind),\n\t\t\tfalse,\n\t\t\tthis._defaultValue,\n\t\t\tthis._auto,\n\t\t\tthis._mergeStrategy,\n\t\t)\n\t}\n\n\toverride default(value: unknown[]): ArrayFieldBuilder<ItemKind, false, Auto> {\n\t\treturn new ArrayFieldBuilder(\n\t\t\tnew FieldBuilder(this._itemKind),\n\t\t\tfalse,\n\t\t\tvalue,\n\t\t\tthis._auto,\n\t\t\tthis._mergeStrategy,\n\t\t)\n\t}\n\n\toverride auto(): ArrayFieldBuilder<ItemKind, false, true> {\n\t\treturn new ArrayFieldBuilder(\n\t\t\tnew FieldBuilder(this._itemKind),\n\t\t\tfalse,\n\t\t\tundefined,\n\t\t\ttrue,\n\t\t\tthis._mergeStrategy,\n\t\t)\n\t}\n\n\toverride merge(strategy: FieldMergeStrategy): ArrayFieldBuilder<ItemKind, Req, Auto> {\n\t\treturn new ArrayFieldBuilder(\n\t\t\tnew FieldBuilder(this._itemKind),\n\t\t\tthis._required as unknown as Req,\n\t\t\tthis._defaultValue,\n\t\t\tthis._auto as unknown as Auto,\n\t\t\tstrategy,\n\t\t)\n\t}\n\n\toverride _build(): FieldDescriptor {\n\t\treturn {\n\t\t\tkind: 'array',\n\t\t\trequired: this._required as unknown as boolean,\n\t\t\tdefaultValue: this._defaultValue,\n\t\t\tauto: this._auto as unknown as boolean,\n\t\t\tenumValues: null,\n\t\t\titemKind: this._itemKind,\n\t\t\tmergeStrategy: this._mergeStrategy,\n\t\t\ttransitions: null,\n\t\t}\n\t}\n}\n\n/**\n * Field builder for structured object fields with a nested field schema.\n *\n * Each nested key merges by its own declared kind (scalars via LWW, nested\n * arrays via add-wins, nested objects recursively), so two devices editing\n * different keys of the same object offline both converge on reconnect instead\n * of one clobbering the other.\n */\nexport class ObjectFieldBuilder<\n\tReq extends boolean = true,\n\tAuto extends boolean = false,\n> extends FieldBuilder<'object', Req, Auto> {\n\tprivate readonly _fields: Record<string, FieldBuilder>\n\n\tconstructor(\n\t\tfields: Record<string, FieldBuilder>,\n\t\trequired = true as unknown as Req,\n\t\tdefaultValue: unknown = undefined,\n\t\tauto = false as unknown as Auto,\n\t\tmergeStrategy: FieldMergeStrategy | null = null,\n\t) {\n\t\tsuper('object', required, defaultValue, auto, mergeStrategy)\n\t\tthis._fields = fields\n\t}\n\n\toverride optional(): ObjectFieldBuilder<false, Auto> {\n\t\treturn new ObjectFieldBuilder(\n\t\t\tthis._fields,\n\t\t\tfalse,\n\t\t\tthis._defaultValue,\n\t\t\tthis._auto,\n\t\t\tthis._mergeStrategy,\n\t\t)\n\t}\n\n\toverride default(value: Record<string, unknown>): ObjectFieldBuilder<false, Auto> {\n\t\treturn new ObjectFieldBuilder(this._fields, false, value, this._auto, this._mergeStrategy)\n\t}\n\n\toverride auto(): ObjectFieldBuilder<false, true> {\n\t\treturn new ObjectFieldBuilder(this._fields, false, undefined, true, this._mergeStrategy)\n\t}\n\n\toverride merge(strategy: FieldMergeStrategy): ObjectFieldBuilder<Req, Auto> {\n\t\treturn new ObjectFieldBuilder(\n\t\t\tthis._fields,\n\t\t\tthis._required as unknown as Req,\n\t\t\tthis._defaultValue,\n\t\t\tthis._auto as unknown as Auto,\n\t\t\tstrategy,\n\t\t)\n\t}\n\n\toverride _build(): FieldDescriptor {\n\t\tconst nestedFields: Record<string, FieldDescriptor> = {}\n\t\tfor (const [key, builder] of Object.entries(this._fields)) {\n\t\t\tnestedFields[key] = builder._build()\n\t\t}\n\t\treturn {\n\t\t\tkind: 'object',\n\t\t\trequired: this._required as unknown as boolean,\n\t\t\tdefaultValue: this._defaultValue,\n\t\t\tauto: this._auto as unknown as boolean,\n\t\t\tenumValues: null,\n\t\t\titemKind: null,\n\t\t\tmergeStrategy: this._mergeStrategy,\n\t\t\ttransitions: null,\n\t\t\tnestedFields,\n\t\t}\n\t}\n}\n\n/**\n * Field builder for dynamic-key JSON values. Carries a compile-time shape `T`\n * for inference while merging structurally as a convergent CRDT: a plain-object\n * value recurses as a map, an array merges add-wins, any other value is a scalar\n * leaf under last-write-wins.\n */\nexport class JsonFieldBuilder<\n\tT = unknown,\n\tReq extends boolean = true,\n\tAuto extends boolean = false,\n> extends FieldBuilder<'json', Req, Auto> {\n\toverride optional(): JsonFieldBuilder<T, false, Auto> {\n\t\treturn new JsonFieldBuilder<T, false, Auto>(\n\t\t\t'json',\n\t\t\tfalse,\n\t\t\tthis._defaultValue,\n\t\t\tthis._auto as unknown as Auto,\n\t\t\tthis._mergeStrategy,\n\t\t)\n\t}\n\n\toverride default(value: T): JsonFieldBuilder<T, false, Auto> {\n\t\treturn new JsonFieldBuilder<T, false, Auto>(\n\t\t\t'json',\n\t\t\tfalse,\n\t\t\tvalue,\n\t\t\tthis._auto as unknown as Auto,\n\t\t\tthis._mergeStrategy,\n\t\t)\n\t}\n\n\toverride auto(): JsonFieldBuilder<T, false, true> {\n\t\treturn new JsonFieldBuilder<T, false, true>('json', false, undefined, true, this._mergeStrategy)\n\t}\n\n\toverride merge(strategy: FieldMergeStrategy): JsonFieldBuilder<T, Req, Auto> {\n\t\treturn new JsonFieldBuilder<T, Req, Auto>(\n\t\t\t'json',\n\t\t\tthis._required as unknown as Req,\n\t\t\tthis._defaultValue,\n\t\t\tthis._auto as unknown as Auto,\n\t\t\tstrategy,\n\t\t)\n\t}\n\n\toverride _build(): FieldDescriptor {\n\t\treturn {\n\t\t\tkind: 'json',\n\t\t\trequired: this._required as unknown as boolean,\n\t\t\tdefaultValue: this._defaultValue,\n\t\t\tauto: this._auto as unknown as boolean,\n\t\t\tenumValues: null,\n\t\t\titemKind: null,\n\t\t\tmergeStrategy: this._mergeStrategy,\n\t\t\ttransitions: null,\n\t\t\tnestedFields: null,\n\t\t}\n\t}\n}\n\n/**\n * Field builder for secret fields (passwords, tokens, API keys).\n *\n * A secret field's value is never exposed in merge traces, DevTools, or logs\n * (it is redacted at the point traces are built). Its at-rest protection is\n * chosen with `.hashed()` (one-way, for passwords) or `.encrypted()` (reversible,\n * for tokens); the default is `encrypted`.\n */\nexport class SecretFieldBuilder<\n\tReq extends boolean = true,\n\tAuto extends boolean = false,\n> extends FieldBuilder<'secret', Req, Auto> {\n\tprivate readonly _secretMode: SecretMode\n\n\tconstructor(\n\t\tsecretMode: SecretMode = 'encrypted',\n\t\trequired = true as unknown as Req,\n\t\tdefaultValue: unknown = undefined,\n\t\tauto = false as unknown as Auto,\n\t\tmergeStrategy: FieldMergeStrategy | null = null,\n\t) {\n\t\tsuper('secret', required, defaultValue, auto, mergeStrategy)\n\t\tthis._secretMode = secretMode\n\t}\n\n\t/** Store this secret as a one-way salted hash (passwords: verify, never read back). */\n\thashed(): SecretFieldBuilder<Req, Auto> {\n\t\treturn new SecretFieldBuilder(\n\t\t\t'hashed',\n\t\t\tthis._required as unknown as Req,\n\t\t\tthis._defaultValue,\n\t\t\tthis._auto as unknown as Auto,\n\t\t\tthis._mergeStrategy,\n\t\t)\n\t}\n\n\t/** Store this secret as reversible ciphertext (tokens/keys: decrypt to use). */\n\tencrypted(): SecretFieldBuilder<Req, Auto> {\n\t\treturn new SecretFieldBuilder(\n\t\t\t'encrypted',\n\t\t\tthis._required as unknown as Req,\n\t\t\tthis._defaultValue,\n\t\t\tthis._auto as unknown as Auto,\n\t\t\tthis._mergeStrategy,\n\t\t)\n\t}\n\n\toverride optional(): SecretFieldBuilder<false, Auto> {\n\t\treturn new SecretFieldBuilder(\n\t\t\tthis._secretMode,\n\t\t\tfalse,\n\t\t\tthis._defaultValue,\n\t\t\tthis._auto,\n\t\t\tthis._mergeStrategy,\n\t\t)\n\t}\n\n\toverride auto(): SecretFieldBuilder<false, true> {\n\t\treturn new SecretFieldBuilder(this._secretMode, false, undefined, true, this._mergeStrategy)\n\t}\n\n\toverride merge(strategy: FieldMergeStrategy): SecretFieldBuilder<Req, Auto> {\n\t\treturn new SecretFieldBuilder(\n\t\t\tthis._secretMode,\n\t\t\tthis._required as unknown as Req,\n\t\t\tthis._defaultValue,\n\t\t\tthis._auto as unknown as Auto,\n\t\t\tstrategy,\n\t\t)\n\t}\n\n\toverride _build(): FieldDescriptor {\n\t\treturn {\n\t\t\tkind: 'secret',\n\t\t\trequired: this._required as unknown as boolean,\n\t\t\tdefaultValue: this._defaultValue,\n\t\t\tauto: this._auto as unknown as boolean,\n\t\t\tenumValues: null,\n\t\t\titemKind: null,\n\t\t\tmergeStrategy: this._mergeStrategy,\n\t\t\ttransitions: null,\n\t\t\tsecretMode: this._secretMode,\n\t\t}\n\t}\n}\n\n/**\n * Type builder namespace. The developer's primary interface for defining field types.\n *\n * @example\n * ```typescript\n * import { t } from '@korajs/core'\n *\n * const fields = {\n * title: t.string(),\n * count: t.number(),\n * active: t.boolean().default(true),\n * notes: t.richtext(),\n * tags: t.array(t.string()).default([]),\n * priority: t.enum(['low', 'medium', 'high']).default('medium'),\n * settings: t.object({ theme: t.string(), fontSize: t.number() }),\n * metadata: t.json<{ source: string }>(),\n * createdAt: t.timestamp().auto(),\n * }\n * ```\n */\nexport const t = {\n\tstring(): FieldBuilder<'string', true, false> {\n\t\treturn new FieldBuilder('string', true, undefined, false)\n\t},\n\n\tnumber(): FieldBuilder<'number', true, false> {\n\t\treturn new FieldBuilder('number', true, undefined, false)\n\t},\n\n\tboolean(): FieldBuilder<'boolean', true, false> {\n\t\treturn new FieldBuilder('boolean', true, undefined, false)\n\t},\n\n\ttimestamp(): FieldBuilder<'timestamp', true, false> {\n\t\treturn new FieldBuilder('timestamp', true, undefined, false)\n\t},\n\n\trichtext(): FieldBuilder<'richtext', true, false> {\n\t\treturn new FieldBuilder('richtext', true, undefined, false)\n\t},\n\n\tenum<const V extends readonly string[]>(values: V): EnumFieldBuilder<V, true, false> {\n\t\treturn new EnumFieldBuilder(values, true, undefined, false)\n\t},\n\n\tarray<K extends FieldKind>(itemBuilder: FieldBuilder<K>): ArrayFieldBuilder<K, true, false> {\n\t\treturn new ArrayFieldBuilder(itemBuilder, true, undefined, false)\n\t},\n\n\tobject(fields: Record<string, FieldBuilder>): ObjectFieldBuilder<true, false> {\n\t\treturn new ObjectFieldBuilder(fields, true, undefined, false)\n\t},\n\n\tjson<T = unknown>(): JsonFieldBuilder<T, true, false> {\n\t\treturn new JsonFieldBuilder<T, true, false>('json', true, undefined, false)\n\t},\n\n\tblob(): FieldBuilder<'blob', true, false> {\n\t\treturn new FieldBuilder('blob', true, undefined, false)\n\t},\n\n\tsecret(): SecretFieldBuilder<true, false> {\n\t\treturn new SecretFieldBuilder('encrypted', true, undefined, false)\n\t},\n}\n","import { isBlobRef } from '../blob/blob-ref'\nimport { SchemaValidationError } from '../errors/errors'\nimport { isAtomicOp } from '../operations/atomic-ops'\nimport type { CollectionDefinition, FieldDescriptor, OperationType } from '../types'\n\n/**\n * Validates a record's data against a collection's field definitions.\n * Applies defaults, rejects auto fields, and type-checks each value.\n *\n * @param collection - The collection name (for error messages)\n * @param collectionDef - The collection definition from the schema\n * @param data - The record data to validate\n * @param operationType - The operation type ('insert', 'update', 'delete')\n * @returns The validated and normalized data (with defaults applied)\n * @throws {SchemaValidationError} If validation fails\n */\nexport function validateRecord(\n\tcollection: string,\n\tcollectionDef: CollectionDefinition,\n\tdata: Record<string, unknown>,\n\toperationType: OperationType,\n): Record<string, unknown> {\n\tif (operationType === 'delete') {\n\t\treturn {}\n\t}\n\n\tconst result: Record<string, unknown> = {}\n\tconst fieldNames = Object.keys(collectionDef.fields)\n\n\t// Check for extra fields not in the schema\n\tfor (const key of Object.keys(data)) {\n\t\tif (!(key in collectionDef.fields)) {\n\t\t\tthrow new SchemaValidationError(\n\t\t\t\t`Unknown field \"${key}\" in collection \"${collection}\". Available fields: ${fieldNames.join(', ')}`,\n\t\t\t\t{ collection, field: key },\n\t\t\t)\n\t\t}\n\t}\n\n\tfor (const [fieldName, descriptor] of Object.entries(collectionDef.fields)) {\n\t\tconst value = data[fieldName]\n\t\tconst hasValue = fieldName in data\n\n\t\t// Auto fields cannot be set by the developer\n\t\tif (descriptor.auto && hasValue) {\n\t\t\tthrow new SchemaValidationError(\n\t\t\t\t`Field \"${fieldName}\" in collection \"${collection}\" is auto-populated and cannot be set manually`,\n\t\t\t\t{ collection, field: fieldName },\n\t\t\t)\n\t\t}\n\n\t\t// For updates, only validate fields that are present (partial updates)\n\t\tif (operationType === 'update') {\n\t\t\tif (hasValue) {\n\t\t\t\t// Atomic op sentinels pass through validation — they are resolved\n\t\t\t\t// to concrete values by Collection.update() before the Operation is created.\n\t\t\t\tif (isAtomicOp(value)) {\n\t\t\t\t\tresult[fieldName] = value\n\t\t\t\t} else if (value !== undefined && value !== null) {\n\t\t\t\t\tvalidateFieldValue(collection, fieldName, descriptor, value)\n\t\t\t\t\tresult[fieldName] = value\n\t\t\t\t} else {\n\t\t\t\t\tresult[fieldName] = value\n\t\t\t\t}\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\t// For inserts, apply defaults and check required fields\n\t\tif (descriptor.auto) {\n\t\t\t// Skip auto fields — they are populated by the framework\n\t\t\tcontinue\n\t\t}\n\n\t\tif (!hasValue || value === undefined) {\n\t\t\tif (descriptor.defaultValue !== undefined) {\n\t\t\t\t// Deep-copy default arrays/objects to prevent shared mutations\n\t\t\t\tresult[fieldName] =\n\t\t\t\t\ttypeof descriptor.defaultValue === 'object' && descriptor.defaultValue !== null\n\t\t\t\t\t\t? JSON.parse(JSON.stringify(descriptor.defaultValue))\n\t\t\t\t\t\t: descriptor.defaultValue\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif (descriptor.required) {\n\t\t\t\tthrow new SchemaValidationError(\n\t\t\t\t\t`Required field \"${fieldName}\" is missing in collection \"${collection}\"`,\n\t\t\t\t\t{ collection, field: fieldName },\n\t\t\t\t)\n\t\t\t}\n\n\t\t\t// Optional field with no default — omit from result\n\t\t\tcontinue\n\t\t}\n\n\t\tvalidateFieldValue(collection, fieldName, descriptor, value)\n\t\tresult[fieldName] = value\n\t}\n\n\treturn result\n}\n\nfunction validateFieldValue(\n\tcollection: string,\n\tfieldName: string,\n\tdescriptor: FieldDescriptor,\n\tvalue: unknown,\n): void {\n\tswitch (descriptor.kind) {\n\t\tcase 'string': {\n\t\t\tif (typeof value !== 'string') {\n\t\t\t\tthrow new SchemaValidationError(\n\t\t\t\t\t`Field \"${fieldName}\" in collection \"${collection}\" must be a string, got ${typeof value}`,\n\t\t\t\t\t{ collection, field: fieldName, expectedType: 'string', receivedType: typeof value },\n\t\t\t\t)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t\tcase 'number': {\n\t\t\tif (typeof value !== 'number' || Number.isNaN(value)) {\n\t\t\t\tthrow new SchemaValidationError(\n\t\t\t\t\t`Field \"${fieldName}\" in collection \"${collection}\" must be a number, got ${typeof value}`,\n\t\t\t\t\t{ collection, field: fieldName, expectedType: 'number', receivedType: typeof value },\n\t\t\t\t)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t\tcase 'boolean': {\n\t\t\tif (typeof value !== 'boolean') {\n\t\t\t\tthrow new SchemaValidationError(\n\t\t\t\t\t`Field \"${fieldName}\" in collection \"${collection}\" must be a boolean, got ${typeof value}`,\n\t\t\t\t\t{ collection, field: fieldName, expectedType: 'boolean', receivedType: typeof value },\n\t\t\t\t)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t\tcase 'timestamp': {\n\t\t\tif (typeof value !== 'number' || !Number.isFinite(value)) {\n\t\t\t\tthrow new SchemaValidationError(\n\t\t\t\t\t`Field \"${fieldName}\" in collection \"${collection}\" must be a timestamp (number), got ${typeof value}`,\n\t\t\t\t\t{\n\t\t\t\t\t\tcollection,\n\t\t\t\t\t\tfield: fieldName,\n\t\t\t\t\t\texpectedType: 'timestamp',\n\t\t\t\t\t\treceivedType: typeof value,\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t\tcase 'enum': {\n\t\t\tif (typeof value !== 'string') {\n\t\t\t\tthrow new SchemaValidationError(\n\t\t\t\t\t`Field \"${fieldName}\" in collection \"${collection}\" must be a string (enum), got ${typeof value}`,\n\t\t\t\t\t{ collection, field: fieldName, expectedType: 'enum', receivedType: typeof value },\n\t\t\t\t)\n\t\t\t}\n\t\t\tif (descriptor.enumValues && !descriptor.enumValues.includes(value)) {\n\t\t\t\tthrow new SchemaValidationError(\n\t\t\t\t\t`Field \"${fieldName}\" in collection \"${collection}\" must be one of: ${descriptor.enumValues.join(', ')}. Got \"${value}\"`,\n\t\t\t\t\t{\n\t\t\t\t\t\tcollection,\n\t\t\t\t\t\tfield: fieldName,\n\t\t\t\t\t\tallowedValues: [...descriptor.enumValues],\n\t\t\t\t\t\treceived: value,\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t\tcase 'array': {\n\t\t\tif (!Array.isArray(value)) {\n\t\t\t\tthrow new SchemaValidationError(\n\t\t\t\t\t`Field \"${fieldName}\" in collection \"${collection}\" must be an array, got ${typeof value}`,\n\t\t\t\t\t{ collection, field: fieldName, expectedType: 'array', receivedType: typeof value },\n\t\t\t\t)\n\t\t\t}\n\t\t\tif (descriptor.itemKind) {\n\t\t\t\tconst expectedType = jsTypeForKind(descriptor.itemKind)\n\t\t\t\tfor (let i = 0; i < value.length; i++) {\n\t\t\t\t\tconst item = value[i]\n\t\t\t\t\tif (!matchesJsType(item, expectedType)) {\n\t\t\t\t\t\tthrow new SchemaValidationError(\n\t\t\t\t\t\t\t`Field \"${fieldName}[${i}]\" in collection \"${collection}\" must be a ${descriptor.itemKind}, got ${typeof item}`,\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tcollection,\n\t\t\t\t\t\t\t\tfield: `${fieldName}[${i}]`,\n\t\t\t\t\t\t\t\texpectedType: descriptor.itemKind,\n\t\t\t\t\t\t\t\treceivedType: typeof item,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t\tcase 'richtext': {\n\t\t\t// Richtext fields accept Uint8Array/ArrayBuffer (Yjs state) or string\n\t\t\t// (plain text initial value) — matching what the richtext serializer\n\t\t\t// encodes, so no accepted input can be silently lost downstream.\n\t\t\tif (\n\t\t\t\t!(value instanceof Uint8Array) &&\n\t\t\t\t!(value instanceof ArrayBuffer) &&\n\t\t\t\ttypeof value !== 'string'\n\t\t\t) {\n\t\t\t\tthrow new SchemaValidationError(\n\t\t\t\t\t`Field \"${fieldName}\" in collection \"${collection}\" must be a Uint8Array, ArrayBuffer, or string for richtext, got ${typeof value}`,\n\t\t\t\t\t{\n\t\t\t\t\t\tcollection,\n\t\t\t\t\t\tfield: fieldName,\n\t\t\t\t\t\texpectedType: 'richtext',\n\t\t\t\t\t\treceivedType: typeof value,\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t\tcase 'object': {\n\t\t\tif (!isPlainObject(value)) {\n\t\t\t\tthrow new SchemaValidationError(\n\t\t\t\t\t`Field \"${fieldName}\" in collection \"${collection}\" must be a plain object, got ${describeType(value)}`,\n\t\t\t\t\t{\n\t\t\t\t\t\tcollection,\n\t\t\t\t\t\tfield: fieldName,\n\t\t\t\t\t\texpectedType: 'object',\n\t\t\t\t\t\treceivedType: describeType(value),\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t}\n\t\t\t// Validate declared nested keys by their own kind. Undeclared keys are\n\t\t\t// allowed (forward-compatible), but a present declared key must type-check.\n\t\t\tif (descriptor.nestedFields) {\n\t\t\t\tfor (const [nestedName, nestedDescriptor] of Object.entries(descriptor.nestedFields)) {\n\t\t\t\t\tconst nestedValue = (value as Record<string, unknown>)[nestedName]\n\t\t\t\t\tif (nestedValue !== undefined && nestedValue !== null) {\n\t\t\t\t\t\tvalidateFieldValue(\n\t\t\t\t\t\t\tcollection,\n\t\t\t\t\t\t\t`${fieldName}.${nestedName}`,\n\t\t\t\t\t\t\tnestedDescriptor,\n\t\t\t\t\t\t\tnestedValue,\n\t\t\t\t\t\t)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t\tcase 'json': {\n\t\t\t// Dynamic-key JSON: accept any JSON-serializable value (object, array,\n\t\t\t// scalar, or null). Reject only values that cannot round-trip through\n\t\t\t// JSON, since the store persists them via JSON.stringify.\n\t\t\tconst nonJson = findNonJsonSerializable(value, fieldName)\n\t\t\tif (nonJson) {\n\t\t\t\tthrow new SchemaValidationError(\n\t\t\t\t\t`Field \"${fieldName}\" in collection \"${collection}\" must be JSON-serializable; found ${nonJson.receivedType} at \"${nonJson.path}\"`,\n\t\t\t\t\t{\n\t\t\t\t\t\tcollection,\n\t\t\t\t\t\tfield: fieldName,\n\t\t\t\t\t\texpectedType: 'json',\n\t\t\t\t\t\treceivedType: nonJson.receivedType,\n\t\t\t\t\t\tpath: nonJson.path,\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t\tcase 'blob': {\n\t\t\t// A blob field carries a content-addressed reference, not raw bytes.\n\t\t\t// Developers upload bytes to the blob store (which returns a BlobRef)\n\t\t\t// and assign that reference here.\n\t\t\tif (!isBlobRef(value)) {\n\t\t\t\tthrow new SchemaValidationError(\n\t\t\t\t\t`Field \"${fieldName}\" in collection \"${collection}\" must be a BlobRef (from the blob store), got ${describeType(value)}`,\n\t\t\t\t\t{ collection, field: fieldName, expectedType: 'blob', receivedType: describeType(value) },\n\t\t\t\t)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t\tcase 'secret': {\n\t\t\t// A secret field takes plaintext as a string on input; the framework\n\t\t\t// applies the at-rest transform (hash or encrypt). Its value is never\n\t\t\t// exposed in traces (redacted in the merge engine).\n\t\t\tif (typeof value !== 'string') {\n\t\t\t\tthrow new SchemaValidationError(\n\t\t\t\t\t`Field \"${fieldName}\" in collection \"${collection}\" must be a string, got ${describeType(value)}`,\n\t\t\t\t\t{\n\t\t\t\t\t\tcollection,\n\t\t\t\t\t\tfield: fieldName,\n\t\t\t\t\t\texpectedType: 'secret',\n\t\t\t\t\t\treceivedType: describeType(value),\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t}\n}\n\n/** True for plain data objects only (not arrays, null, or class instances). */\nfunction isPlainObject(value: unknown): boolean {\n\tif (typeof value !== 'object' || value === null || Array.isArray(value)) {\n\t\treturn false\n\t}\n\tconst proto = Object.getPrototypeOf(value)\n\treturn proto === null || proto === Object.prototype\n}\n\ninterface NonJsonSerializableValue {\n\tpath: string\n\treceivedType: string\n}\n\n/** Find the first value that cannot safely round-trip through JSON. */\nfunction findNonJsonSerializable(\n\tvalue: unknown,\n\tpath: string,\n\tseen = new WeakSet<object>(),\n): NonJsonSerializableValue | null {\n\tif (value === null) {\n\t\treturn null\n\t}\n\tconst type = typeof value\n\tif (type === 'string' || type === 'number' || type === 'boolean') {\n\t\tif (type === 'number' && !Number.isFinite(value as number)) {\n\t\t\treturn { path, receivedType: describeType(value) }\n\t\t}\n\t\treturn null\n\t}\n\tif (type === 'undefined' || type === 'function' || type === 'symbol' || type === 'bigint') {\n\t\treturn { path, receivedType: describeType(value) }\n\t}\n\tif (Array.isArray(value)) {\n\t\tfor (let index = 0; index < value.length; index++) {\n\t\t\tconst invalid = findNonJsonSerializable(value[index], `${path}[${index}]`, seen)\n\t\t\tif (invalid) return invalid\n\t\t}\n\t\treturn null\n\t}\n\tif (type === 'object') {\n\t\tconst objectValue = value as Record<string, unknown>\n\t\tif (seen.has(objectValue)) {\n\t\t\treturn { path, receivedType: 'circular object' }\n\t\t}\n\t\tseen.add(objectValue)\n\t\tfor (const [key, nestedValue] of Object.entries(objectValue)) {\n\t\t\tconst invalid = findNonJsonSerializable(nestedValue, `${path}.${key}`, seen)\n\t\t\tif (invalid) return invalid\n\t\t}\n\t\tseen.delete(objectValue)\n\t\treturn null\n\t}\n\treturn { path, receivedType: describeType(value) }\n}\n\n/** A readable type label for error messages (distinguishes array/null from object). */\nfunction describeType(value: unknown): string {\n\tif (value === null) {\n\t\treturn 'null'\n\t}\n\tif (Array.isArray(value)) {\n\t\treturn 'array'\n\t}\n\treturn typeof value\n}\n\nfunction jsTypeForKind(kind: string): string {\n\tswitch (kind) {\n\t\tcase 'string':\n\t\tcase 'enum':\n\t\t\treturn 'string'\n\t\tcase 'number':\n\t\tcase 'timestamp':\n\t\t\treturn 'number'\n\t\tcase 'boolean':\n\t\t\treturn 'boolean'\n\t\tdefault:\n\t\t\treturn 'object'\n\t}\n}\n\nfunction matchesJsType(value: unknown, expected: string): boolean {\n\t// Using explicit comparisons to satisfy Biome's useValidTypeof rule,\n\t// which requires typeof to be compared against string literals.\n\tswitch (expected) {\n\t\tcase 'string':\n\t\t\treturn typeof value === 'string'\n\t\tcase 'number':\n\t\t\treturn typeof value === 'number'\n\t\tcase 'boolean':\n\t\t\treturn typeof value === 'boolean'\n\t\tcase 'object':\n\t\t\treturn typeof value === 'object'\n\t\tdefault:\n\t\t\treturn false\n\t}\n}\n","import type { Operation, VersionVector } from '../types'\nimport { topologicalSort } from './topological-sort'\n\n/**\n * Create an empty version vector.\n */\nexport function createVersionVector(): VersionVector {\n\treturn new Map()\n}\n\n/**\n * Merge two version vectors by taking the max sequence number for each node.\n * This is commutative, associative, and idempotent.\n */\nexport function mergeVectors(a: VersionVector, b: VersionVector): VersionVector {\n\tconst merged = new Map(a)\n\tfor (const [nodeId, seq] of b) {\n\t\tmerged.set(nodeId, Math.max(merged.get(nodeId) ?? 0, seq))\n\t}\n\treturn merged\n}\n\n/**\n * Advance a version vector for a specific node to a new sequence number.\n * Only advances forward — if the current value is higher, no change is made.\n */\nexport function advanceVector(vector: VersionVector, nodeId: string, seq: number): VersionVector {\n\tconst updated = new Map(vector)\n\tupdated.set(nodeId, Math.max(updated.get(nodeId) ?? 0, seq))\n\treturn updated\n}\n\n/**\n * Returns true if vector `a` dominates vector `b` — meaning `a` has seen\n * everything `b` has seen. Formally: for every nodeId in b, a[nodeId] >= b[nodeId].\n */\nexport function dominates(a: VersionVector, b: VersionVector): boolean {\n\tfor (const [nodeId, bSeq] of b) {\n\t\tif ((a.get(nodeId) ?? 0) < bSeq) return false\n\t}\n\treturn true\n}\n\n/**\n * Returns true if two version vectors are exactly equal.\n */\nexport function vectorsEqual(a: VersionVector, b: VersionVector): boolean {\n\tif (a.size !== b.size) return false\n\tfor (const [nodeId, aSeq] of a) {\n\t\tif (b.get(nodeId) !== aSeq) return false\n\t}\n\treturn true\n}\n\n/**\n * Operation log interface for computing deltas.\n * getRange may be async (for DB-backed implementations) or sync (for in-memory).\n */\nexport interface OperationLog {\n\tgetRange(nodeId: string, fromSeq: number, toSeq: number): Operation[] | Promise<Operation[]>\n}\n\n/**\n * Compute the operations that `local` has but `remote` does not.\n * Returns operations in causal (topological) order.\n *\n * @param localVector - The local version vector\n * @param remoteVector - The remote version vector\n * @param operationLog - The operation log to fetch operations from\n * @returns Operations sorted in causal order\n */\nexport async function computeDelta(\n\tlocalVector: VersionVector,\n\tremoteVector: VersionVector,\n\toperationLog: OperationLog,\n): Promise<Operation[]> {\n\tconst missing: Operation[] = []\n\tfor (const [nodeId, localSeq] of localVector) {\n\t\tconst remoteSeq = remoteVector.get(nodeId) ?? 0\n\t\tif (localSeq > remoteSeq) {\n\t\t\tconst ops = await operationLog.getRange(nodeId, remoteSeq + 1, localSeq)\n\t\t\tmissing.push(...ops)\n\t\t}\n\t}\n\treturn topologicalSort(missing)\n}\n\n/**\n * Serialize a version vector to a JSON-compatible string.\n */\nexport function serializeVector(vector: VersionVector): string {\n\tconst entries = [...vector.entries()].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n\treturn JSON.stringify(entries)\n}\n\n/**\n * Deserialize a version vector from its serialized string form.\n */\nexport function deserializeVector(s: string): VersionVector {\n\tconst entries = JSON.parse(s) as [string, number][]\n\treturn new Map(entries)\n}\n","import type { SchemaDefinition } from '../types'\nimport {\n\tcollectSchemaScopeValueKeys,\n\tgetCollectionScopeBindings,\n\thasSchemaSyncRules,\n\tisCollectionSyncScoped,\n} from './sync-scope-bindings'\n\n/**\n * Per-collection scope map: `{ collectionName: { field: value, ... } }`\n *\n * Used to filter which operations a client should receive during sync.\n */\nexport type ScopeMap = Record<string, Record<string, unknown>>\n\n/**\n * Build a per-collection scope map from the schema's scope declarations\n * and the client's flat scope values.\n *\n * Supports both legacy `collection.scope` arrays and declarative `schema.sync`\n * rules (`sync: { todos: { where: { userId: true } } }`).\n *\n * When `schema.sync` is present, only collections with sync rules or legacy\n * scope fields are included in the result. Other collections are omitted so\n * sync engines treat them as out of scope (partial sync).\n *\n * @param schema - The schema definition with scope declarations\n * @param scopeValues - Flat key-value scope values from the client\n * @returns A per-collection scope map\n *\n * @example\n * ```typescript\n * // Schema declares: sales.scope = ['orgId', 'storeId']\n * // Client provides: { orgId: 'org-123', storeId: 'store-456' }\n * // Result: { sales: { orgId: 'org-123', storeId: 'store-456' }, products: {} }\n * ```\n */\nexport function buildScopeMap(\n\tschema: SchemaDefinition,\n\tscopeValues: Record<string, unknown>,\n): ScopeMap {\n\tconst result: ScopeMap = {}\n\tconst partialSync = hasSchemaSyncRules(schema)\n\n\tfor (const collName of Object.keys(schema.collections)) {\n\t\tif (partialSync && !isCollectionSyncScoped(schema, collName)) {\n\t\t\tcontinue\n\t\t}\n\n\t\tconst bindings = getCollectionScopeBindings(schema, collName)\n\t\tif (bindings) {\n\t\t\tconst collScope: Record<string, unknown> = {}\n\t\t\tfor (const [field, scopeKey] of Object.entries(bindings)) {\n\t\t\t\tif (scopeKey in scopeValues) {\n\t\t\t\t\tcollScope[field] = scopeValues[scopeKey]\n\t\t\t\t}\n\t\t\t}\n\t\t\tresult[collName] = collScope\n\t\t} else {\n\t\t\t// Collections without scope declarations are fully visible\n\t\t\tresult[collName] = {}\n\t\t}\n\t}\n\n\treturn result\n}\n\nexport { collectSchemaScopeValueKeys as collectSchemaScopeFields } from './sync-scope-bindings'\n","import type { SchemaDefinition } from '../types'\nimport { collectSchemaScopeValueKeys } from './sync-scope-bindings'\n\n/**\n * Collect every unique scope field name declared across all collections.\n *\n * @deprecated Use {@link collectSchemaScopeValueKeys} instead.\n */\nexport function collectSchemaScopeFields(schema: SchemaDefinition): string[] {\n\treturn collectSchemaScopeValueKeys(schema)\n}\n\n/**\n * Extract flat scope values from JWT (or auth) claims using schema scope field names.\n *\n * Resolution order for each scope field:\n * 1. Top-level claim with the same name\n * 2. Nested `claims.scope[field]` object\n * 3. `userId` falls back to the standard JWT `sub` claim\n *\n * @param schema - Schema with per-collection scope declarations\n * @param claims - Decoded JWT claims (unverified; client-side scope hints only)\n * @returns Flat key-value map suitable for {@link buildScopeMap}\n */\nexport function extractScopeValuesFromClaims(\n\tschema: SchemaDefinition,\n\tclaims: Record<string, unknown>,\n): Record<string, unknown> {\n\tconst scopeFields = collectSchemaScopeValueKeys(schema)\n\tif (scopeFields.length === 0) {\n\t\treturn {}\n\t}\n\n\tconst nestedScope = claims.scope\n\tconst scopeObject =\n\t\ttypeof nestedScope === 'object' && nestedScope !== null && !Array.isArray(nestedScope)\n\t\t\t? (nestedScope as Record<string, unknown>)\n\t\t\t: {}\n\n\tconst result: Record<string, unknown> = {}\n\n\tfor (const field of scopeFields) {\n\t\tif (field in claims) {\n\t\t\tresult[field] = claims[field]\n\t\t\tcontinue\n\t\t}\n\n\t\tif (field in scopeObject) {\n\t\t\tresult[field] = scopeObject[field]\n\t\t\tcontinue\n\t\t}\n\n\t\tif (field === 'userId' && typeof claims.sub === 'string') {\n\t\t\tresult.userId = claims.sub\n\t\t}\n\t}\n\n\treturn result\n}\n","/**\n * Offline-safe sequence formatting.\n *\n * Format tokens:\n * - `{date}` → YYYYMMDD (current date)\n * - `{node4}` → first 4 characters of nodeId\n * - `{node8}` → first 8 characters of nodeId\n * - `{seq}` → zero-padded counter (default 4 digits)\n * - `{seq:N}` → zero-padded counter with N digits\n *\n * @example\n * ```typescript\n * formatSequenceValue('INV-{date}-{node4}-{seq}', 42, 'a1b2c3d4e5f6')\n * // → \"INV-20260508-a1b2-0042\"\n *\n * formatSequenceValue('ORDER-{seq:6}', 7, 'node-id')\n * // → \"ORDER-000007\"\n * ```\n */\nexport function formatSequenceValue(\n\ttemplate: string,\n\tcounter: number,\n\tnodeId: string,\n\tnow?: Date,\n): string {\n\tconst date = now ?? new Date()\n\tconst yyyy = String(date.getUTCFullYear())\n\tconst mm = String(date.getUTCMonth() + 1).padStart(2, '0')\n\tconst dd = String(date.getUTCDate()).padStart(2, '0')\n\tconst dateStr = `${yyyy}${mm}${dd}`\n\n\treturn template.replace(/\\{([^}]+)\\}/g, (_match, token: string) => {\n\t\tif (token === 'date') return dateStr\n\t\tif (token === 'node4') return nodeId.slice(0, 4)\n\t\tif (token === 'node8') return nodeId.slice(0, 8)\n\t\tif (token === 'seq') return String(counter).padStart(4, '0')\n\t\tif (token.startsWith('seq:')) {\n\t\t\tconst width = Number.parseInt(token.slice(4), 10)\n\t\t\tif (Number.isNaN(width) || width < 1) {\n\t\t\t\treturn String(counter).padStart(4, '0')\n\t\t\t}\n\t\t\treturn String(counter).padStart(width, '0')\n\t\t}\n\t\t// Unknown token — leave as-is\n\t\treturn `{${token}}`\n\t})\n}\n\n/**\n * Default format when none is provided: `{name}-{seq:4}`.\n */\nexport function defaultSequenceFormat(name: string): string {\n\treturn `${name}-{seq:4}`\n}\n","import type { Operation } from '../types'\nimport type { OperationTransform } from './operation-transform'\n\nconst MAX_TRANSFORM_STEPS = 32\n\n/**\n * Apply registered transforms until the operation matches `targetSchemaVersion`.\n * Returns null when a transform drops the operation or no path exists.\n */\nexport function applyOperationTransforms(\n\toperation: Operation,\n\ttargetSchemaVersion: number,\n\ttransforms: readonly OperationTransform[],\n): Operation | null {\n\tlet current: Operation = operation\n\n\tfor (let step = 0; step < MAX_TRANSFORM_STEPS; step++) {\n\t\tif (current.schemaVersion === targetSchemaVersion) {\n\t\t\treturn current\n\t\t}\n\n\t\tconst transform = transforms.find(\n\t\t\t(candidate) => candidate.fromVersion === current.schemaVersion,\n\t\t)\n\t\tif (!transform) {\n\t\t\treturn null\n\t\t}\n\n\t\tconst next = transform.transform(current)\n\t\tif (next === null) {\n\t\t\treturn null\n\t\t}\n\t\tcurrent = next\n\t}\n\n\treturn null\n}\n","import type { FieldBuilder } from '../schema/types'\nimport type { FieldDescriptor } from '../types'\n\n/**\n * A single migration step describing a schema change.\n */\nexport type MigrationStep =\n\t| { type: 'addField'; collection: string; field: string; descriptor: FieldDescriptor }\n\t| { type: 'removeField'; collection: string; field: string; descriptor?: FieldDescriptor }\n\t| { type: 'renameField'; collection: string; from: string; to: string }\n\t| { type: 'addIndex'; collection: string; field: string }\n\t| { type: 'removeIndex'; collection: string; field: string }\n\t| {\n\t\t\ttype: 'backfill'\n\t\t\tcollection: string\n\t\t\ttransform: (record: Record<string, unknown>) => Record<string, unknown>\n\t\t\t/** Reverse transform for rollback. If not provided, backfill is not safely reversible. */\n\t\t\treverseTransform?: (record: Record<string, unknown>) => Record<string, unknown>\n\t }\n\n/**\n * A completed migration definition containing ordered steps and optional rollback steps.\n */\nexport interface MigrationDefinition {\n\treadonly steps: readonly MigrationStep[]\n\t/** Explicitly defined rollback steps. If undefined, inverse steps are auto-generated. */\n\treadonly rollbackSteps: readonly MigrationStep[] | undefined\n\t/** Whether this migration can be safely rolled back. */\n\treadonly safelyReversible: boolean\n}\n\n/**\n * Builder for defining rollback steps explicitly.\n * Used with the `.down()` method on MigrationBuilder.\n *\n * @example\n * ```typescript\n * migrate()\n * .addField('todos', 'priority', t.enum(['low', 'medium', 'high']).default('medium'))\n * .addIndex('todos', 'priority')\n * .down((rollback) => {\n * rollback\n * .removeIndex('todos', 'priority')\n * .removeField('todos', 'priority')\n * })\n * ```\n */\nexport class RollbackBuilder {\n\tprivate _steps: MigrationStep[] = []\n\n\t/**\n\t * Add a field during rollback (to reverse a removeField).\n\t */\n\taddField(collection: string, field: string, builder: FieldBuilder): RollbackBuilder {\n\t\tthis._steps.push({ type: 'addField', collection, field, descriptor: builder._build() })\n\t\treturn this\n\t}\n\n\t/**\n\t * Remove a field during rollback (to reverse an addField).\n\t */\n\tremoveField(collection: string, field: string): RollbackBuilder {\n\t\tthis._steps.push({ type: 'removeField', collection, field })\n\t\treturn this\n\t}\n\n\t/**\n\t * Rename a field during rollback (to reverse a renameField).\n\t */\n\trenameField(collection: string, from: string, to: string): RollbackBuilder {\n\t\tthis._steps.push({ type: 'renameField', collection, from, to })\n\t\treturn this\n\t}\n\n\t/**\n\t * Add an index during rollback (to reverse a removeIndex).\n\t */\n\taddIndex(collection: string, field: string): RollbackBuilder {\n\t\tthis._steps.push({ type: 'addIndex', collection, field })\n\t\treturn this\n\t}\n\n\t/**\n\t * Remove an index during rollback (to reverse an addIndex).\n\t */\n\tremoveIndex(collection: string, field: string): RollbackBuilder {\n\t\tthis._steps.push({ type: 'removeIndex', collection, field })\n\t\treturn this\n\t}\n\n\t/**\n\t * Run a backfill during rollback (to reverse a previous backfill).\n\t */\n\tbackfill(\n\t\tcollection: string,\n\t\ttransform: (record: Record<string, unknown>) => Record<string, unknown>,\n\t): RollbackBuilder {\n\t\tthis._steps.push({ type: 'backfill', collection, transform })\n\t\treturn this\n\t}\n\n\t/**\n\t * Get the accumulated rollback steps.\n\t */\n\t_getSteps(): readonly MigrationStep[] {\n\t\treturn [...this._steps]\n\t}\n}\n\n/**\n * Fluent builder for defining schema migrations.\n *\n * Each method returns a new builder instance (immutable).\n *\n * @example\n * ```typescript\n * migrate()\n * .addField('products', 'taxInclusive', t.boolean().default(false))\n * .renameField('products', 'cost', 'costPrice')\n * .backfill('products', (record) => ({\n * taxInclusive: record.taxRate > 0,\n * }))\n * ```\n */\nexport class MigrationBuilder implements MigrationDefinition {\n\treadonly steps: readonly MigrationStep[]\n\treadonly rollbackSteps: readonly MigrationStep[] | undefined\n\treadonly safelyReversible: boolean\n\n\tconstructor(\n\t\tsteps: readonly MigrationStep[] = [],\n\t\trollbackSteps?: readonly MigrationStep[],\n\t\tsafelyReversible?: boolean,\n\t) {\n\t\tthis.steps = steps\n\t\tthis.rollbackSteps = rollbackSteps\n\t\t// Default: safely reversible if no backfill steps without reverseTransform\n\t\tthis.safelyReversible = safelyReversible ?? this._computeSafelyReversible(steps, rollbackSteps)\n\t}\n\n\t/**\n\t * Add a new field to a collection.\n\t * The field builder provides the type and default value.\n\t */\n\taddField(collection: string, field: string, builder: FieldBuilder): MigrationBuilder {\n\t\treturn new MigrationBuilder([\n\t\t\t...this.steps,\n\t\t\t{ type: 'addField', collection, field, descriptor: builder._build() },\n\t\t])\n\t}\n\n\t/**\n\t * Remove a field from a collection.\n\t * Optionally accepts a field builder to preserve the descriptor for rollback.\n\t * Without the descriptor, rollback of this step requires a custom `.down()`.\n\t *\n\t * @param collection - The collection name\n\t * @param field - The field name to remove\n\t * @param builder - Optional field builder preserving the type info for rollback\n\t */\n\tremoveField(collection: string, field: string, builder?: FieldBuilder): MigrationBuilder {\n\t\tconst step: MigrationStep = builder\n\t\t\t? { type: 'removeField', collection, field, descriptor: builder._build() }\n\t\t\t: { type: 'removeField', collection, field }\n\t\treturn new MigrationBuilder([...this.steps, step])\n\t}\n\n\t/**\n\t * Rename a field in a collection.\n\t * Implemented as ALTER TABLE RENAME COLUMN (SQLite 3.25+).\n\t */\n\trenameField(collection: string, from: string, to: string): MigrationBuilder {\n\t\treturn new MigrationBuilder([...this.steps, { type: 'renameField', collection, from, to }])\n\t}\n\n\t/**\n\t * Add an index on a field.\n\t */\n\taddIndex(collection: string, field: string): MigrationBuilder {\n\t\treturn new MigrationBuilder([...this.steps, { type: 'addIndex', collection, field }])\n\t}\n\n\t/**\n\t * Remove an index on a field.\n\t */\n\tremoveIndex(collection: string, field: string): MigrationBuilder {\n\t\treturn new MigrationBuilder([...this.steps, { type: 'removeIndex', collection, field }])\n\t}\n\n\t/**\n\t * Backfill records in a collection using a transform function.\n\t * The transform receives each record and returns the fields to update.\n\t * Runs after structural changes (addField, renameField, etc.).\n\t *\n\t * @param collection - The collection name\n\t * @param transform - Forward transform function\n\t * @param reverseTransform - Optional reverse transform for rollback support\n\t */\n\tbackfill(\n\t\tcollection: string,\n\t\ttransform: (record: Record<string, unknown>) => Record<string, unknown>,\n\t\treverseTransform?: (record: Record<string, unknown>) => Record<string, unknown>,\n\t): MigrationBuilder {\n\t\treturn new MigrationBuilder([\n\t\t\t...this.steps,\n\t\t\t{ type: 'backfill', collection, transform, reverseTransform },\n\t\t])\n\t}\n\n\t/**\n\t * Define explicit rollback steps for this migration.\n\t * If not called, inverse steps are auto-generated from forward steps.\n\t *\n\t * @param fn - Function that receives a RollbackBuilder to define rollback steps\n\t * @returns A new MigrationBuilder with the rollback steps attached\n\t *\n\t * @example\n\t * ```typescript\n\t * migrate()\n\t * .addField('todos', 'priority', t.enum(['low', 'medium', 'high']).default('medium'))\n\t * .addIndex('todos', 'priority')\n\t * .down((rollback) => {\n\t * rollback\n\t * .removeIndex('todos', 'priority')\n\t * .removeField('todos', 'priority')\n\t * })\n\t * ```\n\t */\n\tdown(fn: (rollback: RollbackBuilder) => void): MigrationBuilder {\n\t\tconst rollbackBuilder = new RollbackBuilder()\n\t\tfn(rollbackBuilder)\n\t\tconst rbSteps = rollbackBuilder._getSteps()\n\t\treturn new MigrationBuilder(this.steps, rbSteps, true)\n\t}\n\n\t/**\n\t * Determine if a migration is safely reversible based on its steps.\n\t * A migration is not safely reversible if:\n\t * - It has a backfill step without a reverseTransform and no explicit rollback\n\t * - It has a removeField without a stored descriptor and no explicit rollback\n\t */\n\tprivate _computeSafelyReversible(\n\t\tsteps: readonly MigrationStep[],\n\t\trollbackSteps: readonly MigrationStep[] | undefined,\n\t): boolean {\n\t\t// Explicit rollback steps override auto-detection\n\t\tif (rollbackSteps !== undefined) {\n\t\t\treturn true\n\t\t}\n\n\t\tfor (const step of steps) {\n\t\t\tif (step.type === 'backfill' && !step.reverseTransform) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tif (step.type === 'removeField' && !step.descriptor) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\n\t\treturn true\n\t}\n}\n\n/**\n * Start building a migration.\n *\n * @returns A new MigrationBuilder\n *\n * @example\n * ```typescript\n * import { migrate, t } from '@korajs/core'\n *\n * const migration = migrate()\n * .addField('products', 'taxInclusive', t.boolean().default(false))\n * .renameField('products', 'cost', 'costPrice')\n * ```\n */\nexport function migrate(): MigrationBuilder {\n\treturn new MigrationBuilder()\n}\n","import { KoraError } from '../errors/errors'\nimport type { FieldDescriptor } from '../types'\nimport type { MigrationStep } from './migration-builder'\n\n/**\n * A migration that includes both forward (up) and backward (down) steps.\n * Rollback steps are applied in reverse order of the forward steps.\n */\nexport interface ReversibleMigration {\n\treadonly up: readonly MigrationStep[]\n\treadonly down: readonly MigrationStep[]\n\treadonly fromVersion: number\n\treadonly toVersion: number\n}\n\n/**\n * Error thrown when a migration step cannot be automatically rolled back\n * and no explicit down step has been provided.\n */\nexport class MigrationRollbackError extends KoraError {\n\tconstructor(step: MigrationStep) {\n\t\tsuper(\n\t\t\t`Cannot auto-generate rollback for \"${step.type}\" step on collection \"${step.collection}\". Provide an explicit .down() definition for this migration.`,\n\t\t\t'MIGRATION_ROLLBACK',\n\t\t\t{ stepType: step.type, collection: step.collection },\n\t\t)\n\t\tthis.name = 'MigrationRollbackError'\n\t}\n}\n\n/**\n * Determines whether a migration step can be automatically rolled back\n * without explicit developer-provided down steps.\n *\n * Auto-rollback is possible when the inverse operation is deterministic:\n * - addField -> removeField (drop the added column)\n * - addIndex -> removeIndex (drop the added index)\n * - removeIndex -> addIndex (re-create the index)\n * - renameField -> renameField (swap from/to names)\n *\n * Steps that CANNOT auto-rollback:\n * - removeField: the field descriptor is lost (need it to re-create the column)\n * - backfill: data transforms are not reversible\n *\n * @param step - The forward migration step to check\n * @returns true if the step can be auto-rolled back\n */\nexport function canAutoRollback(step: MigrationStep): boolean {\n\tswitch (step.type) {\n\t\tcase 'addField':\n\t\tcase 'addIndex':\n\t\tcase 'removeIndex':\n\t\tcase 'renameField':\n\t\t\treturn true\n\t\tcase 'removeField':\n\t\tcase 'backfill':\n\t\t\treturn false\n\t}\n}\n\n/**\n * Generates rollback steps for a list of forward migration steps.\n * Steps are reversed in order (last forward step becomes first rollback step).\n *\n * For steps that cannot be auto-rolled back, throws a MigrationRollbackError.\n * Use canAutoRollback() to check before calling, or provide explicit down steps\n * via the MigrationBuilder .down() API.\n *\n * @param forwardSteps - The forward migration steps to generate rollbacks for\n * @returns Array of rollback steps in reverse execution order\n * @throws MigrationRollbackError if any step cannot be auto-rolled back\n */\nexport function generateRollbackSteps(forwardSteps: readonly MigrationStep[]): MigrationStep[] {\n\tconst rollbackSteps: MigrationStep[] = []\n\n\t// Process in reverse order so rollback undoes changes in the opposite sequence\n\tfor (let i = forwardSteps.length - 1; i >= 0; i--) {\n\t\tconst step = forwardSteps[i]\n\t\tif (step === undefined) continue\n\n\t\tconst rollback = generateSingleRollbackStep(step)\n\t\trollbackSteps.push(rollback)\n\t}\n\n\treturn rollbackSteps\n}\n\n/**\n * Generate the inverse of a single migration step.\n * @internal\n */\nfunction generateSingleRollbackStep(step: MigrationStep): MigrationStep {\n\tswitch (step.type) {\n\t\tcase 'addField':\n\t\t\treturn { type: 'removeField', collection: step.collection, field: step.field }\n\n\t\tcase 'removeField':\n\t\t\t// removeField lacks the descriptor needed to re-create the column.\n\t\t\t// The developer must provide an explicit down step.\n\t\t\tif (step.descriptor) {\n\t\t\t\treturn {\n\t\t\t\t\ttype: 'addField',\n\t\t\t\t\tcollection: step.collection,\n\t\t\t\t\tfield: step.field,\n\t\t\t\t\tdescriptor: step.descriptor,\n\t\t\t\t}\n\t\t\t}\n\t\t\tthrow new MigrationRollbackError(step)\n\n\t\tcase 'renameField':\n\t\t\t// Reverse the rename: swap from and to\n\t\t\treturn { type: 'renameField', collection: step.collection, from: step.to, to: step.from }\n\n\t\tcase 'addIndex':\n\t\t\treturn { type: 'removeIndex', collection: step.collection, field: step.field }\n\n\t\tcase 'removeIndex':\n\t\t\treturn { type: 'addIndex', collection: step.collection, field: step.field }\n\n\t\tcase 'backfill':\n\t\t\t// Backfills with a reverseTransform can be auto-reversed\n\t\t\tif (step.reverseTransform) {\n\t\t\t\treturn {\n\t\t\t\t\ttype: 'backfill',\n\t\t\t\t\tcollection: step.collection,\n\t\t\t\t\ttransform: step.reverseTransform,\n\t\t\t\t}\n\t\t\t}\n\t\t\tthrow new MigrationRollbackError(step)\n\t}\n}\n\n/**\n * Create a ReversibleMigration from forward steps, explicit down steps, and version info.\n *\n * If explicit down steps are provided, they are used as-is.\n * If no explicit down steps are provided, auto-generation is attempted.\n *\n * @param upSteps - The forward migration steps\n * @param downSteps - Optional explicit rollback steps (overrides auto-generation)\n * @param fromVersion - The schema version before the migration\n * @param toVersion - The schema version after the migration\n * @returns A complete ReversibleMigration\n * @throws MigrationRollbackError if auto-generation fails and no explicit down steps provided\n */\nexport function createReversibleMigration(\n\tupSteps: readonly MigrationStep[],\n\tdownSteps: readonly MigrationStep[] | null,\n\tfromVersion: number,\n\ttoVersion: number,\n): ReversibleMigration {\n\tconst down = downSteps !== null ? [...downSteps] : generateRollbackSteps(upSteps)\n\n\treturn {\n\t\tup: [...upSteps],\n\t\tdown,\n\t\tfromVersion,\n\t\ttoVersion,\n\t}\n}\n","import { quoteIdent } from '../schema/quote-ident'\nimport type { FieldDescriptor } from '../types'\nimport type { MigrationDefinition, MigrationStep } from './migration-builder'\nimport { generateRollbackSteps } from './migration-rollback'\n\n/**\n * Convert migration steps to SQL statements.\n *\n * Structural steps (addField, removeField, renameField, addIndex, removeIndex)\n * produce SQL. Backfill steps are skipped (handled at the application layer\n * by reading rows and applying the transform function).\n *\n * @param steps - The migration steps from a MigrationBuilder\n * @returns Array of SQL statements for structural changes\n */\nexport function migrationStepsToSQL(steps: readonly MigrationStep[]): string[] {\n\tconst statements: string[] = []\n\n\tfor (const step of steps) {\n\t\tswitch (step.type) {\n\t\t\tcase 'addField':\n\t\t\t\tstatements.push(addFieldSQL(step.collection, step.field, step.descriptor))\n\t\t\t\tbreak\n\t\t\tcase 'removeField':\n\t\t\t\t// SQLite 3.35+ supports DROP COLUMN. For broader compat, we mark\n\t\t\t\t// the column as nullable so it can be ignored in queries.\n\t\t\t\t// Drop is preferred when available.\n\t\t\t\tstatements.push(\n\t\t\t\t\t`ALTER TABLE ${quoteIdent(step.collection)} DROP COLUMN ${quoteIdent(step.field)}`,\n\t\t\t\t)\n\t\t\t\tbreak\n\t\t\tcase 'renameField':\n\t\t\t\t// SQLite 3.25+ supports RENAME COLUMN\n\t\t\t\tstatements.push(\n\t\t\t\t\t`ALTER TABLE ${quoteIdent(step.collection)} RENAME COLUMN ${quoteIdent(step.from)} TO ${quoteIdent(step.to)}`,\n\t\t\t\t)\n\t\t\t\tbreak\n\t\t\tcase 'addIndex':\n\t\t\t\tstatements.push(\n\t\t\t\t\t`CREATE INDEX IF NOT EXISTS idx_${step.collection}_${step.field} ON ${quoteIdent(step.collection)} (${quoteIdent(step.field)})`,\n\t\t\t\t)\n\t\t\t\tbreak\n\t\t\tcase 'removeIndex':\n\t\t\t\tstatements.push(`DROP INDEX IF EXISTS idx_${step.collection}_${step.field}`)\n\t\t\t\tbreak\n\t\t\tcase 'backfill':\n\t\t\t\t// Backfills are handled by the store at runtime, not via SQL.\n\t\t\t\tbreak\n\t\t}\n\t}\n\n\treturn statements\n}\n\n/**\n * Generate SQL statements to roll back a migration.\n *\n * Uses the migration's explicit rollback steps if available,\n * otherwise auto-generates inverse steps from the forward steps.\n *\n * Backfill steps in the rollback are skipped (handled at the application layer).\n *\n * @param migration - The migration definition to generate rollback SQL for\n * @returns Array of SQL statements that undo the migration's structural changes\n *\n * @example\n * ```typescript\n * const migration = migrate()\n * .addField('todos', 'priority', t.enum(['low', 'medium', 'high']).default('medium'))\n * .addIndex('todos', 'priority')\n *\n * const rollbackSQL = rollbackStepsToSQL(migration)\n * // ['DROP INDEX IF EXISTS idx_todos_priority',\n * // 'ALTER TABLE \"todos\" DROP COLUMN \"priority\"']\n * ```\n */\nexport function rollbackStepsToSQL(migration: MigrationDefinition): string[] {\n\t// Use explicit rollback steps if provided, otherwise auto-generate from forward steps\n\tconst rollbackSteps = migration.rollbackSteps ?? generateRollbackSteps(migration.steps)\n\treturn migrationStepsToSQL(rollbackSteps)\n}\n\n/**\n * Produce an ALTER TABLE ADD COLUMN statement for a new field.\n */\nfunction addFieldSQL(collection: string, field: string, descriptor: FieldDescriptor): string {\n\tconst sqlType = mapFieldType(descriptor)\n\tconst parts = [`ALTER TABLE ${quoteIdent(collection)} ADD COLUMN ${quoteIdent(field)}`, sqlType]\n\n\tif (descriptor.defaultValue !== undefined) {\n\t\tparts.push(`DEFAULT ${sqlDefault(descriptor.defaultValue)}`)\n\t}\n\n\tif (descriptor.kind === 'enum' && descriptor.enumValues) {\n\t\tconst values = descriptor.enumValues.map((v) => `'${v}'`).join(', ')\n\t\tparts.push(`CHECK (${quoteIdent(field)} IN (${values}))`)\n\t}\n\n\treturn parts.join(' ')\n}\n\nfunction mapFieldType(descriptor: FieldDescriptor): string {\n\tswitch (descriptor.kind) {\n\t\tcase 'string':\n\t\t\treturn 'TEXT'\n\t\tcase 'number':\n\t\t\treturn 'REAL'\n\t\tcase 'boolean':\n\t\t\treturn 'INTEGER'\n\t\tcase 'enum':\n\t\t\treturn 'TEXT'\n\t\tcase 'timestamp':\n\t\t\treturn 'INTEGER'\n\t\tcase 'array':\n\t\t\treturn 'TEXT'\n\t\tcase 'object':\n\t\t\treturn 'TEXT'\n\t\tcase 'json':\n\t\t\treturn 'TEXT'\n\t\tcase 'blob':\n\t\t\treturn 'TEXT'\n\t\tcase 'secret':\n\t\t\treturn 'TEXT'\n\t\tcase 'richtext':\n\t\t\treturn 'BLOB'\n\t}\n}\n\nfunction sqlDefault(value: unknown): string {\n\tif (value === null) return 'NULL'\n\tif (typeof value === 'string') return `'${value}'`\n\tif (typeof value === 'number') return String(value)\n\tif (typeof value === 'boolean') return value ? '1' : '0'\n\treturn `'${JSON.stringify(value)}'`\n}\n","import type { CollectionDefinition, FieldDescriptor, FieldKind, SchemaDefinition } from '../types'\n\n/**\n * Output of the proto definition generator.\n * Contains the .proto file text, a type mapping, and a JSON descriptor\n * compatible with protobufjs's `Root.fromJSON()`.\n */\nexport interface ProtoOutput {\n\t/** The generated .proto file content as a string */\n\tproto: string\n\t/** TypeScript type map: field name -> protobuf type */\n\ttypeMap: Map<string, string>\n\t/** JSON descriptor for dynamic protobufjs usage (no .proto file needed) */\n\tjsonDescriptor: Record<string, unknown>\n}\n\n/**\n * Maps a Kora FieldKind to its protobuf scalar type string.\n * Array and enum kinds are handled separately because they\n * produce composite types (repeated, generated enum).\n */\nconst SCALAR_TYPE_MAP: Record<Exclude<FieldKind, 'array' | 'enum'>, string> = {\n\tstring: 'string',\n\tnumber: 'double',\n\tboolean: 'bool',\n\ttimestamp: 'int64',\n\trichtext: 'bytes',\n\t// object/json values travel as JSON-serialized strings on the proto wire.\n\tobject: 'string',\n\tjson: 'string',\n\t// A blob field carries a JSON-serialized content-addressed reference, not bytes.\n\tblob: 'string',\n\t// A secret field's stored value is a JSON string (ciphertext or hash).\n\tsecret: 'string',\n}\n\n/**\n * Maps a Kora FieldKind (when used as an array item) to its protobuf scalar type.\n * Only scalar kinds can be array items.\n */\nconst ARRAY_ITEM_TYPE_MAP: Record<string, string> = {\n\tstring: 'string',\n\tnumber: 'double',\n\tboolean: 'bool',\n\ttimestamp: 'int64',\n}\n\n/**\n * Converts a collection name (snake_case) to PascalCase for protobuf message names.\n * E.g., \"todo_items\" becomes \"TodoItems\", \"todos\" becomes \"Todos\".\n */\nfunction toPascalCase(name: string): string {\n\treturn name\n\t\t.split('_')\n\t\t.map((part) => part.charAt(0).toUpperCase() + part.slice(1))\n\t\t.join('')\n}\n\n/**\n * Converts a camelCase field name to snake_case for protobuf field names.\n * E.g., \"dueDate\" becomes \"due_date\", \"createdAt\" becomes \"created_at\".\n */\nfunction toSnakeCase(name: string): string {\n\treturn name.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`)\n}\n\n/**\n * Resolves the protobuf type for a single field descriptor.\n *\n * @param fieldName - The field name (used for enum type naming)\n * @param descriptor - The Kora field descriptor\n * @param messageName - Parent message name (used for scoping enum type names)\n * @returns The protobuf type string\n */\nfunction resolveProtoType(\n\tfieldName: string,\n\tdescriptor: FieldDescriptor,\n\tmessageName: string,\n): string {\n\tif (descriptor.kind === 'enum') {\n\t\treturn `${messageName}${toPascalCase(fieldName)}`\n\t}\n\tif (descriptor.kind === 'array') {\n\t\tconst itemType = descriptor.itemKind\n\t\t\t? (ARRAY_ITEM_TYPE_MAP[descriptor.itemKind] ?? 'string')\n\t\t\t: 'string'\n\t\treturn itemType\n\t}\n\treturn SCALAR_TYPE_MAP[descriptor.kind as Exclude<FieldKind, 'array' | 'enum'>]\n}\n\n/**\n * Generates a protobuf enum definition for a Kora enum field.\n * Protobuf enums require the first value to be 0, so we add\n * an UNSPECIFIED sentinel as field 0.\n */\nfunction generateEnumBlock(\n\tenumTypeName: string,\n\tenumValues: readonly string[],\n\tindent: string,\n): string {\n\tconst lines: string[] = []\n\tlines.push(`${indent}enum ${enumTypeName} {`)\n\t// Proto3 requires field number 0 as a default/unspecified value\n\tlines.push(`${indent}\\t${enumTypeName.toUpperCase()}_UNSPECIFIED = 0;`)\n\tfor (let i = 0; i < enumValues.length; i++) {\n\t\tconst value = enumValues[i]\n\t\tif (value === undefined) continue\n\t\tlines.push(`${indent}\\t${enumTypeName.toUpperCase()}_${value.toUpperCase()} = ${i + 1};`)\n\t}\n\tlines.push(`${indent}}`)\n\treturn lines.join('\\n')\n}\n\n/**\n * Generates a protobuf message definition for a single Kora collection.\n * Includes nested enum types for any enum fields.\n *\n * @param collectionName - The collection name from the schema\n * @param collection - The collection definition\n * @param typeMap - Accumulator map for field->type mappings\n * @returns The proto message block as a string\n */\nfunction generateCollectionMessage(\n\tcollectionName: string,\n\tcollection: CollectionDefinition,\n\ttypeMap: Map<string, string>,\n): string {\n\tconst messageName = `${toPascalCase(collectionName)}Record`\n\tconst lines: string[] = []\n\tconst nestedEnums: string[] = []\n\n\tlines.push(`message ${messageName} {`)\n\n\t// Field 1 is always \"id\"\n\tlines.push('\\tstring id = 1;')\n\ttypeMap.set(`${collectionName}.id`, 'string')\n\n\tlet fieldNumber = 2\n\tconst entries = Object.entries(collection.fields)\n\n\tfor (const [fieldName, descriptor] of entries) {\n\t\tconst protoFieldName = toSnakeCase(fieldName)\n\t\tconst protoType = resolveProtoType(fieldName, descriptor, messageName)\n\t\tconst mapKey = `${collectionName}.${fieldName}`\n\n\t\tif (descriptor.kind === 'enum' && descriptor.enumValues) {\n\t\t\tconst enumTypeName = `${messageName}${toPascalCase(fieldName)}`\n\t\t\tnestedEnums.push(generateEnumBlock(enumTypeName, descriptor.enumValues, '\\t'))\n\t\t\ttypeMap.set(mapKey, enumTypeName)\n\t\t\tlines.push(`\\t${enumTypeName} ${protoFieldName} = ${fieldNumber};`)\n\t\t} else if (descriptor.kind === 'array') {\n\t\t\ttypeMap.set(mapKey, `repeated ${protoType}`)\n\t\t\tlines.push(`\\trepeated ${protoType} ${protoFieldName} = ${fieldNumber};`)\n\t\t} else {\n\t\t\ttypeMap.set(mapKey, protoType)\n\t\t\tlines.push(`\\t${protoType} ${protoFieldName} = ${fieldNumber};`)\n\t\t}\n\n\t\tfieldNumber++\n\t}\n\n\t// Insert nested enums before the closing brace\n\tif (nestedEnums.length > 0) {\n\t\t// Place enum definitions after the last field\n\t\tlines.push('')\n\t\tfor (const enumBlock of nestedEnums) {\n\t\t\tlines.push(enumBlock)\n\t\t}\n\t}\n\n\tlines.push('}')\n\treturn lines.join('\\n')\n}\n\n/**\n * The KoraOperation message — the wire format for individual operations.\n * Field assignments match the sync protocol specification from CLAUDE.md.\n */\nconst KORA_OPERATION_MESSAGE = `message KoraOperation {\n\\tstring id = 1;\n\\tstring node_id = 2;\n\\tstring type = 3;\n\\tstring collection = 4;\n\\tstring record_id = 5;\n\\tbytes data = 6;\n\\tbytes previous_data = 7;\n\\tint64 wall_time = 8;\n\\tint32 logical = 9;\n\\tstring timestamp_node_id = 10;\n\\tint64 sequence_number = 11;\n\\trepeated string causal_deps = 12;\n\\tint32 schema_version = 13;\n}`\n\n/**\n * The OperationBatch message — batches operations for sync transfer.\n */\nconst OPERATION_BATCH_MESSAGE = `message OperationBatch {\n\\trepeated KoraOperation operations = 1;\n\\tbool is_final = 2;\n\\tbytes retractions_json = 3;\n}`\n\n/**\n * The HandshakeMessage — initiates a sync session with version vector exchange.\n */\nconst HANDSHAKE_MESSAGE = `message HandshakeMessage {\n\\tmap<string, int64> version_vector = 1;\n\\tint32 schema_version = 2;\n\\tstring node_id = 3;\n\\tstring scope_exit_policy = 4;\n}`\n\n/**\n * The HandshakeResponse — server acknowledges and returns its version vector.\n */\nconst HANDSHAKE_RESPONSE_MESSAGE = `message HandshakeResponse {\n\\tmap<string, int64> version_vector = 1;\n\\tint32 schema_version = 2;\n\\tbytes accepted_scope_json = 3;\n\\tbytes accepted_downlink_scopes_json = 4;\n\\tbytes accepted_uplink_scopes_json = 5;\n}`\n\n/**\n * The Acknowledgment message — confirms receipt of an operation batch.\n */\nconst ACKNOWLEDGMENT_MESSAGE = `message Acknowledgment {\n\\tint64 sequence_number = 1;\n\\tstring node_id = 2;\n}`\n\n/**\n * Builds a JSON descriptor object compatible with protobufjs Root.fromJSON().\n * This allows runtime usage of the proto definitions without parsing .proto text.\n */\nfunction buildJsonDescriptor(schema: SchemaDefinition): Record<string, unknown> {\n\tconst nested: Record<string, unknown> = {}\n\n\t// Per-collection record messages\n\tfor (const [collectionName, collection] of Object.entries(schema.collections)) {\n\t\tconst messageName = `${toPascalCase(collectionName)}Record`\n\t\tconst fields: Record<string, unknown> = {\n\t\t\tid: { type: 'string', id: 1 },\n\t\t}\n\t\tconst nestedTypes: Record<string, unknown> = {}\n\n\t\tlet fieldNumber = 2\n\t\tfor (const [fieldName, descriptor] of Object.entries(collection.fields)) {\n\t\t\tconst protoFieldName = toSnakeCase(fieldName)\n\t\t\tconst fieldDef: Record<string, unknown> = { id: fieldNumber }\n\n\t\t\tif (descriptor.kind === 'enum' && descriptor.enumValues) {\n\t\t\t\tconst enumTypeName = `${messageName}${toPascalCase(fieldName)}`\n\t\t\t\tfieldDef.type = enumTypeName\n\n\t\t\t\t// Build enum values object for protobufjs\n\t\t\t\tconst enumValuesObj: Record<string, number> = {\n\t\t\t\t\t[`${enumTypeName.toUpperCase()}_UNSPECIFIED`]: 0,\n\t\t\t\t}\n\t\t\t\tfor (let i = 0; i < descriptor.enumValues.length; i++) {\n\t\t\t\t\tconst val = descriptor.enumValues[i]\n\t\t\t\t\tif (val === undefined) continue\n\t\t\t\t\tenumValuesObj[`${enumTypeName.toUpperCase()}_${val.toUpperCase()}`] = i + 1\n\t\t\t\t}\n\t\t\t\tnestedTypes[enumTypeName] = { values: enumValuesObj }\n\t\t\t} else if (descriptor.kind === 'array') {\n\t\t\t\tconst itemType = descriptor.itemKind\n\t\t\t\t\t? (ARRAY_ITEM_TYPE_MAP[descriptor.itemKind] ?? 'string')\n\t\t\t\t\t: 'string'\n\t\t\t\tfieldDef.type = itemType\n\t\t\t\tfieldDef.rule = 'repeated'\n\t\t\t} else {\n\t\t\t\tfieldDef.type = SCALAR_TYPE_MAP[descriptor.kind as Exclude<FieldKind, 'array' | 'enum'>]\n\t\t\t}\n\n\t\t\tfields[protoFieldName] = fieldDef\n\t\t\tfieldNumber++\n\t\t}\n\n\t\tconst messageDescriptor: Record<string, unknown> = { fields }\n\t\tif (Object.keys(nestedTypes).length > 0) {\n\t\t\tmessageDescriptor.nested = nestedTypes\n\t\t}\n\t\tnested[messageName] = messageDescriptor\n\t}\n\n\t// KoraOperation\n\tnested.KoraOperation = {\n\t\tfields: {\n\t\t\tid: { type: 'string', id: 1 },\n\t\t\tnode_id: { type: 'string', id: 2 },\n\t\t\ttype: { type: 'string', id: 3 },\n\t\t\tcollection: { type: 'string', id: 4 },\n\t\t\trecord_id: { type: 'string', id: 5 },\n\t\t\tdata: { type: 'bytes', id: 6 },\n\t\t\tprevious_data: { type: 'bytes', id: 7 },\n\t\t\twall_time: { type: 'int64', id: 8 },\n\t\t\tlogical: { type: 'int32', id: 9 },\n\t\t\ttimestamp_node_id: { type: 'string', id: 10 },\n\t\t\tsequence_number: { type: 'int64', id: 11 },\n\t\t\tcausal_deps: { type: 'string', id: 12, rule: 'repeated' },\n\t\t\tschema_version: { type: 'int32', id: 13 },\n\t\t},\n\t}\n\n\t// OperationBatch\n\tnested.OperationBatch = {\n\t\tfields: {\n\t\t\toperations: { type: 'KoraOperation', id: 1, rule: 'repeated' },\n\t\t\tis_final: { type: 'bool', id: 2 },\n\t\t\tretractions_json: { type: 'bytes', id: 3 },\n\t\t},\n\t}\n\n\t// HandshakeMessage\n\tnested.HandshakeMessage = {\n\t\tfields: {\n\t\t\tversion_vector: { keyType: 'string', type: 'int64', id: 1 },\n\t\t\tschema_version: { type: 'int32', id: 2 },\n\t\t\tnode_id: { type: 'string', id: 3 },\n\t\t\tscope_exit_policy: { type: 'string', id: 4 },\n\t\t},\n\t}\n\n\t// HandshakeResponse\n\tnested.HandshakeResponse = {\n\t\tfields: {\n\t\t\tversion_vector: { keyType: 'string', type: 'int64', id: 1 },\n\t\t\tschema_version: { type: 'int32', id: 2 },\n\t\t\taccepted_scope_json: { type: 'bytes', id: 3 },\n\t\t\taccepted_downlink_scopes_json: { type: 'bytes', id: 4 },\n\t\t\taccepted_uplink_scopes_json: { type: 'bytes', id: 5 },\n\t\t},\n\t}\n\n\t// Acknowledgment\n\tnested.Acknowledgment = {\n\t\tfields: {\n\t\t\tsequence_number: { type: 'int64', id: 1 },\n\t\t\tnode_id: { type: 'string', id: 2 },\n\t\t},\n\t}\n\n\treturn {\n\t\tnested: {\n\t\t\tkora: { nested },\n\t\t},\n\t}\n}\n\n/**\n * Generates Protocol Buffer definitions from a Kora schema.\n *\n * Produces three outputs:\n * 1. A `.proto` file string conforming to proto3 syntax\n * 2. A type map linking Kora field paths to protobuf types\n * 3. A JSON descriptor for runtime protobufjs usage via `Root.fromJSON()`\n *\n * The generated definitions include:\n * - Per-collection record messages with proper type mappings\n * - Nested enum types for enum fields\n * - `KoraOperation` wrapper for the sync wire format\n * - `OperationBatch` for batched sync transfers\n * - `HandshakeMessage` / `HandshakeResponse` for sync session initiation\n * - `Acknowledgment` for delivery confirmation\n *\n * @param schema - A validated SchemaDefinition from defineSchema()\n * @returns ProtoOutput with proto text, type map, and JSON descriptor\n *\n * @example\n * ```typescript\n * import { defineSchema, t, generateProtoDefinitions } from '@korajs/core'\n *\n * const schema = defineSchema({\n * version: 1,\n * collections: {\n * todos: {\n * fields: {\n * title: t.string(),\n * completed: t.boolean().default(false),\n * }\n * }\n * }\n * })\n *\n * const { proto, typeMap, jsonDescriptor } = generateProtoDefinitions(schema)\n * // proto is a valid .proto file string\n * // typeMap maps \"todos.title\" -> \"string\", \"todos.completed\" -> \"bool\"\n * // jsonDescriptor can be loaded with protobuf.Root.fromJSON()\n * ```\n */\nexport function generateProtoDefinitions(schema: SchemaDefinition): ProtoOutput {\n\tconst typeMap = new Map<string, string>()\n\tconst sections: string[] = []\n\n\t// Proto3 header\n\tsections.push('syntax = \"proto3\";')\n\tsections.push('')\n\tsections.push('package kora;')\n\n\t// Per-collection messages\n\tconst collectionEntries = Object.entries(schema.collections)\n\tif (collectionEntries.length > 0) {\n\t\tsections.push('')\n\t\tsections.push('// Collection record messages')\n\t\tfor (const [collectionName, collection] of collectionEntries) {\n\t\t\tsections.push('')\n\t\t\tsections.push(generateCollectionMessage(collectionName, collection, typeMap))\n\t\t}\n\t}\n\n\t// Sync protocol messages\n\tsections.push('')\n\tsections.push('// Sync protocol messages')\n\tsections.push('')\n\tsections.push(KORA_OPERATION_MESSAGE)\n\tsections.push('')\n\tsections.push(OPERATION_BATCH_MESSAGE)\n\tsections.push('')\n\tsections.push(HANDSHAKE_MESSAGE)\n\tsections.push('')\n\tsections.push(HANDSHAKE_RESPONSE_MESSAGE)\n\tsections.push('')\n\tsections.push(ACKNOWLEDGMENT_MESSAGE)\n\n\tconst proto = `${sections.join('\\n')}\\n`\n\tconst jsonDescriptor = buildJsonDescriptor(schema)\n\n\treturn { proto, typeMap, jsonDescriptor }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAwYO,IAAM,mBAAmB;AAAA,EAC/B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACD;AAMO,IAAM,uBAAuB,CAAC,aAAa,QAAQ,QAAQ,QAAQ,SAAS;;;AChZ5E,IAAM,gBAAN,MAAoB;AAAA,EACT,uBAAuB,oBAAI,IAAoB;AAAA,EACxD,sBAAqC;AAAA;AAAA;AAAA;AAAA,EAK7C,mBAAyB;AACxB,SAAK,sBAAsB;AAAA,EAC5B;AAAA;AAAA;AAAA;AAAA,EAKA,mBAAyB;AACxB,SAAK,sBAAsB;AAAA,EAC5B;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,eAAe,YAAoB,eAAkC;AACpE,UAAM,OAAiB,CAAC;AACxB,UAAM,mBAAmB,KAAK,qBAAqB,IAAI,UAAU;AACjE,QAAI,qBAAqB,QAAW;AACnC,WAAK,KAAK,gBAAgB;AAAA,IAC3B;AACA,QAAI,iBAAiB,KAAK,wBAAwB,MAAM;AACvD,UAAI,CAAC,KAAK,SAAS,KAAK,mBAAmB,GAAG;AAC7C,aAAK,KAAK,KAAK,mBAAmB;AAAA,MACnC;AAAA,IACD;AACA,WAAO;AAAA,EACR;AAAA;AAAA;AAAA;AAAA,EAKA,eAAe,YAAoB,aAAqB,eAA8B;AACrF,SAAK,qBAAqB,IAAI,YAAY,WAAW;AACrD,QAAI,eAAe;AAClB,WAAK,sBAAsB;AAAA,IAC5B;AAAA,EACD;AACD;;;AC/CA,IAAM,gBAA8B,WAAW;AAiBxC,SAAS,eACf,YAAoB,KAAK,IAAI,GAC7B,eAA6B,eACpB;AACT,QAAM,QAAQ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gB,YAAY,OAAO,CAAC;AAAA,IAC7E;AAAA,EACD;AAGA,WAAS,KAAK,EAAE;AAChB,WAAS,KAAK,2BAA2B;AACzC,WAAS,KAAK,EAAE;AAChB,WAAS,KAAK,sBAAsB;AACpC,WAAS,KAAK,EAAE;AAChB,WAAS,KAAK,uBAAuB;AACrC,WAAS,KAAK,EAAE;AAChB,WAAS,KAAK,iBAAiB;AAC/B,WAAS,KAAK,EAAE;AAChB,WAAS,KAAK,0BAA0B;AACxC,WAAS,KAAK,EAAE;AAChB,WAAS,KAAK,sBAAsB;AAEpC,QAAM,QAAQ,GAAG,SAAS,KAAK,IAAI,CAAC;AAAA;AACpC,QAAM,iBAAiB,oBAAoB,MAAM;AAEjD,SAAO,EAAE,OAAO,SAAS,eAAe;AACzC;","names":["op","mapFieldType","sqlDefault"]}
|
|
1
|
+
{"version":3,"sources":["../src/types.ts","../src/causal/causal-tracker.ts","../src/identifiers/uuid-v7.ts","../src/blob/blob-ref.ts","../src/secret/secret-crypto.ts","../src/secret/secret-transform.ts","../src/operations/apply-result.ts","../src/operations/atomic-ops.ts","../src/operations/replay-record.ts","../src/migration/apply-operation-transforms.ts","../src/migration/operation-view.ts","../src/fold/authority.ts","../src/fold/errors.ts","../src/fold/values.ts","../src/fold/field-states.ts","../src/fold/types.ts","../src/fold/serialize.ts","../src/fold/fold.ts","../src/fold/plan.ts","../src/fold/snapshot.ts","../src/fold/trace.ts","../src/text/stored-text.ts","../src/fold/side-effect-id.ts","../src/scopes/sync-scope-bindings.ts","../src/state-machine/state-machine.ts","../src/schema/define.ts","../src/schema/types.ts","../src/schema/value-domain.ts","../src/schema/validation.ts","../src/version-vector/version-vector.ts","../src/scopes/build-scope-map.ts","../src/scopes/scope-grant.ts","../src/scopes/extract-scope-from-claims.ts","../src/sequences/sequence-format.ts","../src/migrations/migration-builder.ts","../src/migrations/migration-rollback.ts","../src/migrations/migration-sql.ts","../src/codegen/proto-generator.ts"],"sourcesContent":["/**\n * Hybrid Logical Clock timestamp.\n * Provides a total order that respects causality without requiring synchronized clocks.\n */\nexport interface HLCTimestamp {\n\t/** Physical wall-clock time in milliseconds */\n\twallTime: number\n\t/** Logical counter. Increments when wallTime hasn't changed since last event. */\n\tlogical: number\n\t/** Node ID for tie-breaking. Ensures total order even with identical wall+logical. */\n\tnodeId: string\n}\n\n/** The three mutation types an operation can represent */\nexport type OperationType = 'insert' | 'update' | 'delete'\n\n/** Supported atomic operation types for intent-preserving field updates */\nexport type AtomicOpType = 'increment' | 'max' | 'min' | 'append' | 'remove'\n\n/**\n * Atomic operation stored in an Operation's atomicOps field.\n * This is the serializable form that persists in the operation log.\n */\nexport interface AtomicOp {\n\treadonly type: AtomicOpType\n\treadonly value: unknown\n}\n\n/**\n * The atomic unit of the entire system. Every mutation produces an Operation.\n * Operations are IMMUTABLE and CONTENT-ADDRESSED.\n */\nexport interface Operation {\n\t/**\n\t * Content-addressed SHA-256 hash of the operation's canonical body. Which fields it\n\t * covers depends on `hashVersion` (version 2, the default for new operations, adds\n\t * previousData, sequenceNumber, causalDeps and schemaVersion to version 1's fields).\n\t * Verify with `verifyOperationId`.\n\t */\n\tid: string\n\t/** UUID v7 of the originating device. Time-sortable. */\n\tnodeId: string\n\t/** What happened */\n\ttype: OperationType\n\t/** Which collection (from schema) */\n\tcollection: string\n\t/** ID of the affected record. UUID v7 for inserts, existing ID for update/delete. */\n\trecordId: string\n\t/** Field values. null for delete. For updates, contains ONLY changed fields. */\n\tdata: Record<string, unknown> | null\n\t/** For updates: previous values of changed fields (enables 3-way merge). null for insert/delete. */\n\tpreviousData: Record<string, unknown> | null\n\t/** Hybrid Logical Clock timestamp. Used for causal ordering. */\n\ttimestamp: HLCTimestamp\n\t/** Monotonically increasing per node. Used in version vectors. */\n\tsequenceNumber: number\n\t/** Operation IDs this operation causally depends on (direct parents in the DAG). */\n\tcausalDeps: string[]\n\t/** Schema version at time of creation. Used for migration transforms. */\n\tschemaVersion: number\n\t/** Atomic operation intents for fields in data (e.g., increment, max). Present only when atomic ops were used. */\n\tatomicOps?: Record<string, AtomicOp>\n\t/** Groups this operation with others in an atomic transaction. Not part of the content hash. */\n\ttransactionId?: string\n\t/** Human-readable name for the mutation group (e.g., 'complete-sale'). For DevTools display. */\n\tmutationName?: string\n\t/**\n\t * Per-field HLC versions, present only on server-synthesized scope-entry inserts\n\t * (RT-27). The entry restates a record's current values; each field carries the\n\t * version of the write that produced it, so a receiver resolves every field by\n\t * last-write-wins against its own field version instead of one whole-row stamp.\n\t * `timestamp` is then the record's creation time. Not part of the content hash.\n\t */\n\tfieldVersions?: Record<string, HLCTimestamp>\n\t/**\n\t * Content-hash version of `id` (CORE-1). Absent means 1: the id covers type,\n\t * collection, recordId, data, timestamp, nodeId and atomicOps. 2: it also\n\t * covers previousData, sequenceNumber, causalDeps and schemaVersion. Verify\n\t * with `verifyOperationId`. New operations are version 2 (protocol v2); the\n\t * field is carried on the wire (protobuf operation field 14) and persisted.\n\t */\n\thashVersion?: 1 | 2\n\t/**\n\t * Server-authored serialized fold state (`serializeFoldState`) of the record (W7),\n\t * carried on scope-entry inserts instead of `fieldVersions`, and present only on\n\t * operations from a node the handshake named authoritative\n\t * (`HandshakeResponseMessage.authoritativeNodeIds`). A receiver joins it into its own\n\t * state (`joinStates`), so every field kind (richtext, counters, resolvers, element\n\t * sets) enters with its full merge state. Opaque to the protocol layer. NOT part of\n\t * the content hash; the server strips it from every device upload. Protobuf\n\t * operation field 15.\n\t */\n\tfoldState?: string\n\t/**\n\t * End-to-end encryption envelope (protocol v2, W9). When present the operation's\n\t * `data`, `previousData` and `atomicOps` travel only inside this envelope as\n\t * ciphertext; `data` is null (or holds only the documented cleartext scope fields)\n\t * and `previousData`/`atomicOps` are absent. The id is the version-2 hash of the\n\t * PLAINTEXT operation and is verified after decryption. Not part of the content hash.\n\t * Protobuf operation field 16 (JSON).\n\t */\n\tencrypted?: EncryptedOperationEnvelope\n}\n\n/**\n * One AES-GCM ciphertext inside an {@link EncryptedOperationEnvelope}.\n */\nexport interface EncryptedEnvelopeField {\n\t/** Base64 12-byte IV, unique per field encryption. */\n\tiv: string\n\t/** Base64 AES-GCM ciphertext including the 16-byte tag. */\n\tct: string\n}\n\n/**\n * Versioned end-to-end encryption envelope of an operation (protocol v2, ENC-3,\n * NEW-ENC-1). Each encrypted member is bound by AES-GCM additional authenticated data\n * to canonical(nodeId, collection, recordId, type, timestamp, sequenceNumber, field,\n * keyVersion), so a ciphertext cannot be moved to another operation, record or field.\n */\nexport interface EncryptedOperationEnvelope {\n\t/** Envelope format version. 2 is the only defined value. */\n\tv: 2\n\t/** Cipher. Only AES-256-GCM is defined. */\n\talg: 'aes-256-gcm'\n\t/**\n\t * Identifier of the key material (key-derivation salt fingerprint), so a device\n\t * holding different key material reports a diagnosable mismatch instead of a bare\n\t * authentication failure (ENC-1 key distribution is still to come).\n\t */\n\tkeyId: string\n\t/** Key version used (rotation). */\n\tkeyVersion: number\n\t/** Ciphertext of `data`, or null when the plaintext `data` is null. */\n\tdata: EncryptedEnvelopeField | null\n\t/** Ciphertext of `previousData`, or null when it is null. */\n\tpreviousData: EncryptedEnvelopeField | null\n\t/** Ciphertext of `atomicOps`, present only when the plaintext operation had them. */\n\tatomicOps?: EncryptedEnvelopeField\n}\n\n/**\n * Input for creating an operation (before id and timestamp are assigned).\n */\nexport interface OperationInput {\n\tnodeId: string\n\ttype: OperationType\n\tcollection: string\n\trecordId: string\n\tdata: Record<string, unknown> | null\n\tpreviousData: Record<string, unknown> | null\n\tsequenceNumber: number\n\tcausalDeps: string[]\n\tschemaVersion: number\n\t/** Atomic operation intents for fields in data (e.g., increment, max). */\n\tatomicOps?: Record<string, AtomicOp>\n\t/** Groups this operation with others in an atomic transaction. Not part of the content hash. */\n\ttransactionId?: string\n\t/** Human-readable name for the mutation group (e.g., 'complete-sale'). For DevTools display. */\n\tmutationName?: string\n}\n\n/** Version vector: maps nodeId to the max sequence number seen from that node */\nexport type VersionVector = Map<string, number>\n\n/** Field kinds supported by the schema system */\nexport type FieldKind =\n\t| 'string'\n\t| 'number'\n\t| 'boolean'\n\t| 'timestamp'\n\t| 'richtext'\n\t| 'enum'\n\t| 'array'\n\t| 'object'\n\t| 'json'\n\t| 'blob'\n\t| 'secret'\n\n/**\n * How a `secret` field's value is protected at rest.\n * - `hashed`: one-way (passwords). Stored as a salted hash; never read back.\n * - `encrypted`: reversible (tokens, keys). Stored as ciphertext; decrypted to use.\n */\nexport type SecretMode = 'hashed' | 'encrypted'\n\n/**\n * A content-addressed reference to binary data stored out of band.\n *\n * A `blob` field never carries the bytes in the operation log; it carries this\n * small reference. The bytes live in a content-addressed blob store, keyed by\n * `hash`, so identical content is stored once and never re-synced to a peer that\n * already has that hash.\n */\nexport interface BlobRef {\n\t/** Hex-encoded SHA-256 hash of the bytes. The content address. */\n\thash: string\n\t/** Size of the bytes in bytes. */\n\tsize: number\n\t/** Optional MIME type (for example \"image/png\"). */\n\tmimeType?: string\n\t/** Optional original filename. */\n\tfilename?: string\n\t/**\n\t * Hex-encoded SHA-256 hash of this blob's manifest — the small chunk index a\n\t * peer fetches first to learn how to pull the bytes out of band. Present when\n\t * the blob was stored for transfer; absent for a bare reference created without\n\t * chunking. Because it is a content address like `hash`, the manifest is fetched\n\t * and integrity-verified over the same channel as the chunks.\n\t */\n\tmanifestHash?: string\n}\n\n/**\n * Comprehensive sync diagnostics snapshot.\n * Provides connection, latency, throughput, queue, and error metrics\n * for monitoring and DevTools integration.\n */\nexport interface SyncDiagnosticsSnapshot {\n\t// Connection\n\t/** Current developer-facing sync status */\n\tstatus:\n\t\t| 'connected'\n\t\t| 'reconnecting'\n\t\t| 'syncing'\n\t\t| 'synced'\n\t\t| 'offline'\n\t\t| 'error'\n\t\t| 'schema-mismatch'\n\t\t| 'clock-error'\n\t\t| 'auth-required'\n\t\t| 'encryption-locked'\n\t/** Timestamp when the current connection was established, or null if disconnected */\n\tconnectedAt: number | null\n\t/** Timestamp when the last disconnection occurred, or null if never disconnected */\n\tdisconnectedAt: number | null\n\t/** Number of reconnection attempts since last successful connection */\n\treconnectAttempts: number\n\n\t// Latency\n\t/** Current round-trip time in milliseconds */\n\trttMs: number\n\t/** Median (50th percentile) RTT over the sliding window */\n\trttP50Ms: number\n\t/** 95th percentile RTT over the sliding window */\n\trttP95Ms: number\n\t/** 99th percentile RTT over the sliding window */\n\trttP99Ms: number\n\n\t// Throughput\n\t/** Total operations sent during this session */\n\toperationsSent: number\n\t/** Total operations received during this session */\n\toperationsReceived: number\n\t/** Total bytes sent during this session */\n\tbytesSent: number\n\t/** Total bytes received during this session */\n\tbytesReceived: number\n\n\t// Queue\n\t/** Number of operations waiting to be sent */\n\tpendingOperations: number\n\t/** Estimated bytes in the outbound queue */\n\toutboundQueueSize: number\n\n\t// Sync Progress\n\t/** Timestamp of the last successful sync, or null if never synced */\n\tlastSyncedAt: number | null\n\t/** Duration of the last complete sync cycle in ms, or null if no cycle completed */\n\tsyncDuration: number | null\n\t/** Whether the initial sync (full delta exchange) has completed */\n\tinitialSyncComplete: boolean\n\t/** Progress of the initial sync as a 0-1 ratio */\n\tinitialSyncProgress: number\n\n\t// Errors\n\t/** Description of the last error, or null if no error occurred */\n\tlastError: string | null\n\t/** Total number of errors during this session */\n\terrorCount: number\n\n\t// Connection Quality\n\t/** Assessed connection quality level */\n\tquality: 'excellent' | 'good' | 'fair' | 'poor' | 'offline'\n\t/** Estimated effective bandwidth in bytes per second, or null if not yet measured */\n\teffectiveBandwidth: number | null\n}\n\n/** Built-in field merge strategies that can be declared in the schema. */\nexport type FieldMergeStrategy =\n\t| 'lww'\n\t| 'counter'\n\t| 'max'\n\t| 'min'\n\t| 'union'\n\t| 'append-only'\n\t| 'server-authoritative'\n\n/** Map of state to allowed next states for state machine constraints */\nexport type TransitionMap = Record<string, string[]>\n\n/**\n * A state machine constraint extracted from the schema.\n * Used by merge and validation to enforce valid state transitions.\n */\nexport interface StateMachineConstraint {\n\t/** The enum field this constraint controls */\n\tfield: string\n\t/** The collection this constraint applies to */\n\tcollection: string\n\t/** Map of state to allowed next states */\n\ttransitions: TransitionMap\n}\n\n/**\n * Result of validating a state transition.\n */\nexport interface TransitionValidationResult {\n\t/** Whether the transition is allowed */\n\tvalid: boolean\n\t/** The source state */\n\tfrom: string\n\t/** The target state */\n\tto: string\n\t/** The field being transitioned */\n\tfield: string\n\t/** The collection containing the field */\n\tcollection: string\n\t/** All allowed target states from the source state */\n\tallowedTargets: string[]\n}\n\n/**\n * Descriptor produced by the type builder (t.string(), t.number(), etc.).\n * Represents a fully configured field definition.\n */\nexport interface FieldDescriptor {\n\tkind: FieldKind\n\trequired: boolean\n\tdefaultValue: unknown\n\tauto: boolean\n\tenumValues: readonly string[] | null\n\titemKind: FieldKind | null\n\t/** Declared merge strategy. Defaults to kind-appropriate strategy when undefined. */\n\tmergeStrategy: FieldMergeStrategy | null\n\t/** State machine transition map for enum fields. Null if no transitions declared. */\n\ttransitions: TransitionMap | null\n\t/**\n\t * Nested field descriptors for `object` fields (each key merges by its own\n\t * kind). Null for `json` fields (dynamic keys, resolved structurally) and for\n\t * all non-structured kinds.\n\t */\n\tnestedFields?: Record<string, FieldDescriptor> | null\n\t/**\n\t * At-rest protection mode for `secret` fields (`hashed` or `encrypted`).\n\t * Null/absent for every other kind.\n\t */\n\tsecretMode?: SecretMode | null\n}\n\n/**\n * Defines a state machine on an enum field, constraining valid state transitions.\n *\n * When a state machine is defined on a collection, mutations and merges\n * enforce that the controlled field only moves along declared transitions.\n *\n * @example\n * ```typescript\n * stateMachine: {\n * field: 'status',\n * transitions: {\n * draft: ['pending', 'cancelled'],\n * pending: ['confirmed', 'cancelled'],\n * confirmed: ['shipped'],\n * shipped: ['delivered'],\n * delivered: [],\n * cancelled: [],\n * },\n * onInvalidTransition: 'reject',\n * }\n * ```\n */\nexport interface StateMachineDefinition {\n\t/** The enum field this state machine controls */\n\tfield: string\n\t/** Map of state to allowed next states */\n\ttransitions: Record<string, string[]>\n\t/** What to do when an invalid transition is attempted */\n\tonInvalidTransition: 'reject' | 'last-valid-state'\n}\n\n/**\n * Definition of a collection within the schema.\n */\nexport interface CollectionDefinition {\n\tfields: Record<string, FieldDescriptor>\n\tindexes: string[]\n\tconstraints: Constraint[]\n\tresolvers: Record<string, CustomResolver>\n\t/** Scope fields for sync filtering. Only records matching the client's scope values are synced. */\n\tscope: string[]\n\t/** Optional state machine constraining transitions on an enum field */\n\tstateMachine?: StateMachineDefinition\n}\n\n/** Custom resolver function for tier 3 merge resolution */\nexport type CustomResolver = (local: unknown, remote: unknown, base: unknown) => unknown\n\n/**\n * Constraint for tier 2 conflict resolution.\n */\nexport interface Constraint {\n\ttype: 'unique' | 'capacity' | 'referential'\n\tfields: string[]\n\twhere?: Record<string, unknown>\n\tonConflict:\n\t\t| 'first-write-wins'\n\t\t| 'last-write-wins'\n\t\t| 'priority-field'\n\t\t| 'server-decides'\n\t\t| 'custom'\n\tpriorityField?: string\n\tresolve?: (local: unknown, remote: unknown, base: unknown) => unknown\n}\n\n/** Relation type between collections */\nexport type RelationType = 'one-to-one' | 'one-to-many' | 'many-to-one' | 'many-to-many'\n\n/** On-delete behavior for relations */\nexport type OnDeleteAction = 'cascade' | 'set-null' | 'restrict' | 'no-action'\n\n/**\n * Definition of a relation between two collections.\n */\nexport interface RelationDefinition {\n\tfrom: string\n\tto: string\n\ttype: RelationType\n\tfield: string\n\tonDelete: OnDeleteAction\n}\n\n/**\n * Declarative sync filter for a collection.\n *\n * `where` maps record field names to scope value keys. Use `true` to bind a field\n * to a scope value with the same name (e.g. `{ userId: true }`).\n */\nexport interface SyncRuleDefinition {\n\twhere: Record<string, string>\n}\n\n/**\n * The complete schema definition produced by defineSchema().\n */\nexport interface SchemaDefinition {\n\tversion: number\n\tcollections: Record<string, CollectionDefinition>\n\trelations: Record<string, RelationDefinition>\n\t/** Schema migrations keyed by target version. */\n\tmigrations: Record<number, import('./migrations/migration-builder').MigrationDefinition>\n\t/**\n\t * Declarative partial-sync rules per collection.\n\t * When present, only listed collections (plus legacy `scope` collections) sync.\n\t */\n\tsync?: Record<string, SyncRuleDefinition>\n}\n\n/**\n * Merge strategies available for auto-merge and constraints.\n */\nexport const MERGE_STRATEGIES = [\n\t'auto-merge',\n\t'lww',\n\t'first-write-wins',\n\t'server-decides',\n\t'custom',\n] as const\nexport type MergeStrategy = (typeof MERGE_STRATEGIES)[number]\n\n/**\n * Connection quality levels for adaptive sync.\n */\nexport const CONNECTION_QUALITIES = ['excellent', 'good', 'fair', 'poor', 'offline'] as const\nexport type ConnectionQuality = (typeof CONNECTION_QUALITIES)[number]\n\n/**\n * Injectable time source for deterministic testing of clocks.\n */\nexport interface TimeSource {\n\tnow(): number\n}\n\n/**\n * Injectable random source for deterministic testing of UUID generation.\n */\nexport interface RandomSource {\n\tgetRandomValues<T extends ArrayBufferView>(array: T): T\n}\n\n/**\n * Configuration for an offline-safe sequence.\n *\n * Sequences produce monotonically increasing, collision-free identifiers\n * that work across offline devices. Each device maintains its own counter\n * scoped by (name, scope, nodeId).\n *\n * Format tokens available:\n * - `{date}` → YYYYMMDD\n * - `{node4}` → first 4 chars of nodeId\n * - `{node8}` → first 8 chars of nodeId\n * - `{seq}` → zero-padded counter (4 digits)\n * - `{seq:N}` → zero-padded counter with N digits\n *\n * @example\n * ```typescript\n * await app.sequences.next('receipt', {\n * scope: storeId,\n * format: 'S-{date}-{node4}-{seq}',\n * })\n * // → \"S-20260508-a1b2-0042\"\n * ```\n */\nexport interface SequenceConfig {\n\t/** Namespace within the sequence (e.g., a storeId or orgId). Defaults to ''. */\n\tscope?: string\n\t/** Format template. Defaults to `{name}-{seq:4}`. */\n\tformat?: string\n\t/** Starting counter value. Defaults to 1. */\n\tstartAt?: number\n}\n","/**\n * Tracks the latest operation per collection and within an open transaction\n * to populate {@link Operation.causalDeps} for local mutations.\n */\nexport class CausalTracker {\n\tprivate readonly lastOpIdByCollection = new Map<string, string>()\n\tprivate lastTransactionOpId: string | null = null\n\n\t/**\n\t * Start a new transaction boundary. Clears in-transaction op ids.\n\t */\n\tbeginTransaction(): void {\n\t\tthis.lastTransactionOpId = null\n\t}\n\n\t/**\n\t * Clear the transaction boundary without recording ops (after rollback).\n\t */\n\tclearTransaction(): void {\n\t\tthis.lastTransactionOpId = null\n\t}\n\n\t/**\n\t * Compute causal dependencies for the next operation in a collection.\n\t * Uses direct parents only: collection head and the previous op in the open transaction.\n\t */\n\tnextCausalDeps(collection: string, inTransaction: boolean): string[] {\n\t\tconst deps: string[] = []\n\t\tconst lastInCollection = this.lastOpIdByCollection.get(collection)\n\t\tif (lastInCollection !== undefined) {\n\t\t\tdeps.push(lastInCollection)\n\t\t}\n\t\tif (inTransaction && this.lastTransactionOpId !== null) {\n\t\t\tif (!deps.includes(this.lastTransactionOpId)) {\n\t\t\t\tdeps.push(this.lastTransactionOpId)\n\t\t\t}\n\t\t}\n\t\treturn deps\n\t}\n\n\t/**\n\t * Record an operation after it has been created and assigned an id.\n\t */\n\tafterOperation(collection: string, operationId: string, inTransaction: boolean): void {\n\t\tthis.lastOpIdByCollection.set(collection, operationId)\n\t\tif (inTransaction) {\n\t\t\tthis.lastTransactionOpId = operationId\n\t\t}\n\t}\n}\n","import type { RandomSource } from '../types'\n\nconst defaultRandom: RandomSource = globalThis.crypto as RandomSource\n\n/**\n * Generates a UUID v7 per RFC 9562.\n * UUID v7 encodes a Unix timestamp in milliseconds in the most significant 48 bits,\n * making UUIDs time-sortable while remaining globally unique.\n *\n * @param timestamp - Unix timestamp in milliseconds (defaults to Date.now())\n * @param randomSource - Injectable random source for deterministic testing\n * @returns A UUID v7 string in standard 8-4-4-4-12 format\n *\n * @example\n * ```typescript\n * const id = generateUUIDv7()\n * // \"018f3a5c-7e00-7123-abcd-1234567890ab\"\n * ```\n */\nexport function generateUUIDv7(\n\ttimestamp: number = Date.now(),\n\trandomSource: RandomSource = defaultRandom,\n): string {\n\tconst bytes = new Uint8Array(16)\n\trandomSource.getRandomValues(bytes)\n\n\t// Encode 48-bit timestamp in bytes 0-5\n\tconst ms = Math.max(0, Math.floor(timestamp))\n\tbytes[0] = (ms / 2 ** 40) & 0xff\n\tbytes[1] = (ms / 2 ** 32) & 0xff\n\tbytes[2] = (ms / 2 ** 24) & 0xff\n\tbytes[3] = (ms / 2 ** 16) & 0xff\n\tbytes[4] = (ms / 2 ** 8) & 0xff\n\tbytes[5] = ms & 0xff\n\n\t// Set version 7 (0111) in bits 48-51\n\tbytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x70\n\n\t// Set variant 10 in bits 64-65\n\tbytes[8] = ((bytes[8] ?? 0) & 0x3f) | 0x80\n\n\treturn formatUUID(bytes)\n}\n\n/**\n * Extracts the Unix timestamp in milliseconds from a UUID v7.\n *\n * @param uuid - A UUID v7 string\n * @returns The encoded Unix timestamp in milliseconds\n */\nexport function extractTimestamp(uuid: string): number {\n\tconst hex = uuid.replace(/-/g, '')\n\t// First 12 hex chars = 48 bits of timestamp\n\tconst high = Number.parseInt(hex.slice(0, 8), 16)\n\tconst low = Number.parseInt(hex.slice(8, 12), 16)\n\treturn high * 2 ** 16 + low\n}\n\n/**\n * Validates whether a string is a valid UUID v7.\n * Checks format, version (7), and variant (10xx).\n *\n * @param uuid - String to validate\n * @returns true if the string is a valid UUID v7\n */\nexport function isValidUUIDv7(uuid: string): boolean {\n\tif (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(uuid)) {\n\t\treturn false\n\t}\n\tconst hex = uuid.replace(/-/g, '')\n\t// Version must be 7 (nibble at position 12)\n\tif (hex[12] !== '7') return false\n\t// Variant must be 10xx (nibble at position 16 must be 8, 9, a, or b)\n\tconst variantNibble = Number.parseInt(hex[16] ?? '0', 16)\n\treturn variantNibble >= 0x8 && variantNibble <= 0xb\n}\n\nfunction formatUUID(bytes: Uint8Array): string {\n\tconst hex = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('')\n\treturn `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`\n}\n","import type { BlobRef } from '../types'\n\n/**\n * Compute the hex-encoded SHA-256 content hash of a byte buffer.\n *\n * This is the content address of a blob: identical bytes always hash to the same\n * value, which is what lets the blob store deduplicate content and lets a peer\n * skip transferring bytes it already holds.\n *\n * @param bytes - The binary content to hash\n * @returns The hex-encoded SHA-256 hash\n */\nexport async function hashBlob(bytes: Uint8Array): Promise<string> {\n\t// Copy into a fresh, exactly-sized ArrayBuffer so a Uint8Array that is a view\n\t// over a larger buffer (offset/length subrange) hashes its own bytes only.\n\tconst view = new Uint8Array(bytes.byteLength)\n\tview.set(bytes)\n\tconst digest = await globalThis.crypto.subtle.digest('SHA-256', view)\n\tconst out = new Uint8Array(digest)\n\treturn Array.from(out, (b) => b.toString(16).padStart(2, '0')).join('')\n}\n\n/** Optional metadata carried alongside a blob reference. */\nexport interface BlobRefMetadata {\n\tmimeType?: string\n\tfilename?: string\n}\n\n/**\n * Create a content-addressed {@link BlobRef} for a byte buffer.\n *\n * @param bytes - The binary content\n * @param metadata - Optional MIME type and filename\n * @returns A reference carrying the content hash, size, and metadata\n */\nexport async function createBlobRef(\n\tbytes: Uint8Array,\n\tmetadata: BlobRefMetadata = {},\n): Promise<BlobRef> {\n\tconst hash = await hashBlob(bytes)\n\tconst ref: BlobRef = { hash, size: bytes.byteLength }\n\tif (metadata.mimeType !== undefined) {\n\t\tref.mimeType = metadata.mimeType\n\t}\n\tif (metadata.filename !== undefined) {\n\t\tref.filename = metadata.filename\n\t}\n\treturn ref\n}\n\n/**\n * Type guard: whether a value is a structurally valid {@link BlobRef}.\n *\n * Validates the shape only (a non-empty hex hash and a non-negative size); it\n * does not verify that the bytes behind the hash exist or match. Integrity\n * verification against the actual bytes happens in the blob store on read.\n */\nexport function isBlobRef(value: unknown): value is BlobRef {\n\tif (typeof value !== 'object' || value === null) {\n\t\treturn false\n\t}\n\tconst ref = value as Record<string, unknown>\n\tif (typeof ref.hash !== 'string' || !/^[0-9a-f]{64}$/.test(ref.hash)) {\n\t\treturn false\n\t}\n\tif (typeof ref.size !== 'number' || !Number.isInteger(ref.size) || ref.size < 0) {\n\t\treturn false\n\t}\n\tif (ref.mimeType !== undefined && typeof ref.mimeType !== 'string') {\n\t\treturn false\n\t}\n\tif (ref.filename !== undefined && typeof ref.filename !== 'string') {\n\t\treturn false\n\t}\n\tif (\n\t\tref.manifestHash !== undefined &&\n\t\t(typeof ref.manifestHash !== 'string' || !/^[0-9a-f]{64}$/.test(ref.manifestHash))\n\t) {\n\t\treturn false\n\t}\n\treturn true\n}\n","/**\n * Field-level cryptography for `secret` fields.\n *\n * Two protection modes, matching the two ways secrets are used:\n * - `encrypted`: reversible AES-256-GCM (tokens, API keys — decrypt to use).\n * - `hashed`: one-way PBKDF2-SHA-256 with a random salt (passwords — verify only).\n *\n * These primitives use only the standard WebCrypto API so they live in\n * `@korajs/core` with no dependency on `@korajs/auth`; a `secret` field is\n * therefore self-contained. Higher-level key management composes on top.\n */\n\nconst PBKDF2_ITERATIONS = 210_000\nconst SALT_BYTES = 16\nconst IV_BYTES = 12\nconst HASH_BYTES = 32\n\nfunction toHex(bytes: Uint8Array): string {\n\treturn Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('')\n}\n\nfunction fromHex(hex: string): Uint8Array {\n\tif (hex.length % 2 !== 0 || /[^0-9a-f]/i.test(hex)) {\n\t\tthrow new Error('Invalid hex string')\n\t}\n\tconst out = new Uint8Array(hex.length / 2)\n\tfor (let i = 0; i < out.length; i++) {\n\t\tout[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16)\n\t}\n\treturn out\n}\n\nfunction randomBytes(n: number): Uint8Array {\n\tconst out = new Uint8Array(n)\n\tglobalThis.crypto.getRandomValues(out)\n\treturn out\n}\n\n/** Constant-time comparison of two equal-length byte arrays. */\nfunction timingSafeEqual(a: Uint8Array, b: Uint8Array): boolean {\n\tif (a.length !== b.length) {\n\t\treturn false\n\t}\n\tlet diff = 0\n\tfor (let i = 0; i < a.length; i++) {\n\t\tdiff |= (a[i] as number) ^ (b[i] as number)\n\t}\n\treturn diff === 0\n}\n\nasync function deriveAesKey(secretKey: string, salt: Uint8Array): Promise<CryptoKey> {\n\tconst baseKey = await globalThis.crypto.subtle.importKey(\n\t\t'raw',\n\t\tnew TextEncoder().encode(secretKey),\n\t\t'PBKDF2',\n\t\tfalse,\n\t\t['deriveKey'],\n\t)\n\treturn globalThis.crypto.subtle.deriveKey(\n\t\t{ name: 'PBKDF2', salt: salt as BufferSource, iterations: PBKDF2_ITERATIONS, hash: 'SHA-256' },\n\t\tbaseKey,\n\t\t{ name: 'AES-GCM', length: 256 },\n\t\tfalse,\n\t\t['encrypt', 'decrypt'],\n\t)\n}\n\n/**\n * Encrypt a secret's plaintext with AES-256-GCM under a key derived from\n * `secretKey`. The returned string bundles the salt, IV, and ciphertext (all hex,\n * dot-separated) so it is self-describing and safe to store and sync.\n *\n * @param plaintext - The secret value to protect\n * @param secretKey - The key material (from a key provider), never stored\n * @returns An opaque `v1.salt.iv.ciphertext` string\n */\nexport async function encryptSecret(plaintext: string, secretKey: string): Promise<string> {\n\tconst salt = randomBytes(SALT_BYTES)\n\tconst iv = randomBytes(IV_BYTES)\n\tconst key = await deriveAesKey(secretKey, salt)\n\tconst ciphertext = await globalThis.crypto.subtle.encrypt(\n\t\t{ name: 'AES-GCM', iv: iv as BufferSource },\n\t\tkey,\n\t\tnew TextEncoder().encode(plaintext),\n\t)\n\treturn `v1.${toHex(salt)}.${toHex(iv)}.${toHex(new Uint8Array(ciphertext))}`\n}\n\n/**\n * Decrypt a value produced by {@link encryptSecret} with the same key.\n *\n * @param encrypted - The `v1.salt.iv.ciphertext` string\n * @param secretKey - The key material used to encrypt\n * @returns The original plaintext\n * @throws If the format is invalid or the key is wrong (GCM auth failure)\n */\nexport async function decryptSecret(encrypted: string, secretKey: string): Promise<string> {\n\tconst parts = encrypted.split('.')\n\tif (parts.length !== 4 || parts[0] !== 'v1') {\n\t\tthrow new Error('Invalid encrypted secret format')\n\t}\n\tconst salt = fromHex(parts[1] as string)\n\tconst iv = fromHex(parts[2] as string)\n\tconst ciphertext = fromHex(parts[3] as string)\n\tconst key = await deriveAesKey(secretKey, salt)\n\tconst plaintext = await globalThis.crypto.subtle.decrypt(\n\t\t{ name: 'AES-GCM', iv: iv as BufferSource },\n\t\tkey,\n\t\tciphertext as BufferSource,\n\t)\n\treturn new TextDecoder().decode(plaintext)\n}\n\n/**\n * One-way hash a secret (a password) with PBKDF2-SHA-256 and a random salt.\n * The result bundles the salt and hash so {@link verifySecret} needs nothing\n * else. There is no way to recover the plaintext from the result.\n *\n * @param plaintext - The secret value to hash\n * @returns An opaque `v1.salt.hash` string\n */\nexport async function hashSecret(plaintext: string): Promise<string> {\n\tconst salt = randomBytes(SALT_BYTES)\n\tconst hash = await pbkdf2(plaintext, salt)\n\treturn `v1.${toHex(salt)}.${toHex(hash)}`\n}\n\n/**\n * Verify a plaintext against a value produced by {@link hashSecret}, in constant\n * time with respect to the stored hash.\n *\n * @param plaintext - The candidate secret\n * @param stored - The `v1.salt.hash` string\n * @returns Whether the plaintext matches\n */\nexport async function verifySecret(plaintext: string, stored: string): Promise<boolean> {\n\tconst parts = stored.split('.')\n\tif (parts.length !== 3 || parts[0] !== 'v1') {\n\t\treturn false\n\t}\n\tlet salt: Uint8Array\n\tlet expected: Uint8Array\n\ttry {\n\t\tsalt = fromHex(parts[1] as string)\n\t\texpected = fromHex(parts[2] as string)\n\t} catch {\n\t\treturn false\n\t}\n\tconst actual = await pbkdf2(plaintext, salt)\n\treturn timingSafeEqual(actual, expected)\n}\n\nasync function pbkdf2(plaintext: string, salt: Uint8Array): Promise<Uint8Array> {\n\tconst baseKey = await globalThis.crypto.subtle.importKey(\n\t\t'raw',\n\t\tnew TextEncoder().encode(plaintext),\n\t\t'PBKDF2',\n\t\tfalse,\n\t\t['deriveBits'],\n\t)\n\tconst bits = await globalThis.crypto.subtle.deriveBits(\n\t\t{ name: 'PBKDF2', salt: salt as BufferSource, iterations: PBKDF2_ITERATIONS, hash: 'SHA-256' },\n\t\tbaseKey,\n\t\tHASH_BYTES * 8,\n\t)\n\treturn new Uint8Array(bits)\n}\n","import type { CollectionDefinition } from '../types'\nimport { decryptSecret, encryptSecret, hashSecret, verifySecret } from './secret-crypto'\n\n/**\n * Provider of the key material used to encrypt reversible (`encrypted`) secret\n * fields. Called at write and reveal time so the key can be loaded lazily (for\n * example derived from a user passphrase after unlock). Returns undefined when\n * no key is available.\n */\nexport type SecretKeyProvider = () => string | undefined | Promise<string | undefined>\n\n/** Thrown when an `encrypted` secret field is written or read without a key. */\nexport class MissingSecretKeyError extends Error {\n\tconstructor(readonly field: string) {\n\t\tsuper(\n\t\t\t`Secret field \"${field}\" is encrypted but no encryption key is configured. Provide sync.encryption.key (or a key provider) to createApp.`,\n\t\t)\n\t\tthis.name = 'MissingSecretKeyError'\n\t}\n}\n\nasync function resolveKey(provider: SecretKeyProvider | undefined): Promise<string | undefined> {\n\tif (!provider) {\n\t\treturn undefined\n\t}\n\treturn provider()\n}\n\n/**\n * Transform the secret fields of a record's write payload into their at-rest\n * form BEFORE the operation is created, so plaintext never enters the operation\n * log, the store, or the sync stream.\n *\n * - `hashed` fields become a one-way salted hash.\n * - `encrypted` fields become ciphertext (requires a key).\n *\n * Non-secret fields, and secret fields not present in `data`, are passed through\n * untouched. Null/undefined secret values are left as-is (nothing to protect).\n *\n * @param data - The validated write payload (plaintext secret values)\n * @param collectionDef - The collection definition (for field kinds/modes)\n * @param keyProvider - Supplies the encryption key for `encrypted` fields\n * @returns A new payload with secret fields replaced by their at-rest form\n */\nexport async function transformSecretFieldsForWrite(\n\tdata: Record<string, unknown>,\n\tcollectionDef: CollectionDefinition,\n\tkeyProvider?: SecretKeyProvider,\n): Promise<Record<string, unknown>> {\n\t// Fast path: no secret fields in this collection at all.\n\tconst hasSecret = Object.values(collectionDef.fields).some((f) => f.kind === 'secret')\n\tif (!hasSecret) {\n\t\treturn data\n\t}\n\n\tconst result: Record<string, unknown> = { ...data }\n\tlet key: string | undefined\n\tlet keyResolved = false\n\n\tfor (const [field, value] of Object.entries(data)) {\n\t\tconst descriptor = collectionDef.fields[field]\n\t\tif (descriptor?.kind !== 'secret') {\n\t\t\tcontinue\n\t\t}\n\t\tif (typeof value !== 'string') {\n\t\t\t// Null/undefined or non-string: nothing to transform.\n\t\t\tcontinue\n\t\t}\n\t\tconst mode = descriptor.secretMode ?? 'encrypted'\n\t\tif (mode === 'hashed') {\n\t\t\tresult[field] = await hashSecret(value)\n\t\t\tcontinue\n\t\t}\n\t\t// encrypted\n\t\tif (!keyResolved) {\n\t\t\tkey = await resolveKey(keyProvider)\n\t\t\tkeyResolved = true\n\t\t}\n\t\tif (key === undefined) {\n\t\t\tthrow new MissingSecretKeyError(field)\n\t\t}\n\t\tresult[field] = await encryptSecret(value, key)\n\t}\n\n\treturn result\n}\n\n/**\n * Reveal the plaintext of an `encrypted` secret field's stored value. Throws for\n * `hashed` fields, which are one-way and cannot be revealed.\n *\n * @param storedValue - The at-rest value (ciphertext)\n * @param mode - The field's secret mode\n * @param keyProvider - Supplies the decryption key\n * @param field - Field name (for error messages)\n * @returns The decrypted plaintext\n */\nexport async function revealSecret(\n\tstoredValue: string,\n\tmode: 'hashed' | 'encrypted',\n\tkeyProvider: SecretKeyProvider | undefined,\n\tfield = 'secret',\n): Promise<string> {\n\tif (mode === 'hashed') {\n\t\tthrow new Error(\n\t\t\t`Secret field \"${field}\" is hashed (one-way) and cannot be revealed. Use verifySecretValue to check a candidate.`,\n\t\t)\n\t}\n\tconst key = await resolveKey(keyProvider)\n\tif (key === undefined) {\n\t\tthrow new MissingSecretKeyError(field)\n\t}\n\treturn decryptSecret(storedValue, key)\n}\n\n/**\n * Verify a plaintext candidate against a `hashed` secret field's stored value.\n *\n * @param candidate - The plaintext to check (for example a login password)\n * @param storedValue - The stored one-way hash\n * @returns Whether the candidate matches\n */\nexport async function verifySecretValue(candidate: string, storedValue: string): Promise<boolean> {\n\treturn verifySecret(candidate, storedValue)\n}\n","/**\n * Outcome of applying a single operation to materialized storage (local or remote).\n */\nexport const APPLY_RESULTS = ['applied', 'duplicate', 'skipped', 'rejected', 'deferred'] as const\n\nexport type ApplyResult = (typeof APPLY_RESULTS)[number]\n\n/**\n * Structured failure metadata when apply returns `skipped`, `rejected`, or `deferred`.\n */\nexport interface ApplyFailureReason {\n\tcode: string\n\tmessage: string\n\tretriable: boolean\n}\n\n/** Well-known apply failure codes for DevTools and `sync:apply-failed` events. */\nexport const APPLY_FAILURE_CODES = {\n\tAPPLY_FAILED: 'APPLY_FAILED',\n\tAPPLY_SKIPPED: 'APPLY_SKIPPED',\n\tAPPLY_REJECTED: 'APPLY_REJECTED',\n\tAPPLY_DEFERRED: 'APPLY_DEFERRED',\n\tCLOCK_DRIFT: 'CLOCK_DRIFT',\n\tREFERENTIAL_INTEGRITY: 'REFERENTIAL_INTEGRITY',\n\tSCHEMA_MISMATCH: 'SCHEMA_MISMATCH',\n} as const\n\n/**\n * Returns true when the apply outcome should surface as a failure to the developer.\n */\nexport function isApplyFailure(result: ApplyResult): boolean {\n\treturn result === 'skipped' || result === 'rejected' || result === 'deferred'\n}\n\n/**\n * Default failure metadata when the store does not attach a specific reason.\n */\nexport function defaultApplyFailureReason(\n\tresult: Exclude<ApplyResult, 'applied' | 'duplicate'>,\n\toverrides?: Partial<ApplyFailureReason>,\n): ApplyFailureReason {\n\tconst base: ApplyFailureReason =\n\t\tresult === 'deferred'\n\t\t\t? {\n\t\t\t\t\tcode: APPLY_FAILURE_CODES.APPLY_DEFERRED,\n\t\t\t\t\tmessage: 'Operation apply was deferred.',\n\t\t\t\t\tretriable: true,\n\t\t\t\t}\n\t\t\t: result === 'rejected'\n\t\t\t\t? {\n\t\t\t\t\t\tcode: APPLY_FAILURE_CODES.APPLY_REJECTED,\n\t\t\t\t\t\tmessage: 'Operation apply was rejected.',\n\t\t\t\t\t\tretriable: false,\n\t\t\t\t\t}\n\t\t\t\t: {\n\t\t\t\t\t\tcode: APPLY_FAILURE_CODES.APPLY_SKIPPED,\n\t\t\t\t\t\tmessage: 'Operation apply was skipped.',\n\t\t\t\t\t\tretriable: false,\n\t\t\t\t\t}\n\n\treturn { ...base, ...overrides }\n}\n","/**\n * Atomic field operations for intent-preserving updates.\n *\n * Instead of read-modify-write patterns, developers express intent:\n * ```typescript\n * await app.stock.update(id, { quantity: op.increment(-5) })\n * ```\n *\n * The operation intent is preserved in the Operation for merge:\n * concurrent increments compose (sum of deltas) instead of LWW.\n */\n\nimport type { AtomicOp, AtomicOpType } from '../types'\n\n// Re-export for convenience\nexport type { AtomicOp, AtomicOpType }\n\n/**\n * Sentinel marker for detecting atomic op objects in update data.\n * Uses Symbol.for() so the sentinel survives module boundary crossings.\n */\nconst KORA_ATOMIC_OP = Symbol.for('kora.atomic_op')\n\n/** String key used for the sentinel symbol — exported for internal use */\nexport const KORA_ATOMIC_OP_KEY: typeof KORA_ATOMIC_OP = KORA_ATOMIC_OP\n\n/**\n * Sentinel object returned by op.* helpers.\n * Detected by Collection.update() and resolved to concrete values.\n *\n * The type parameters carry the helper's operation and operand type (RT-113), so an\n * update input accepts numeric helpers only on number and timestamp fields and array\n * helpers, with the element type, only on array fields. The bare `AtomicOpSentinel` is\n * any sentinel.\n */\nexport interface AtomicOpSentinel<Type extends AtomicOpType = AtomicOpType, Value = unknown> {\n\treadonly [KORA_ATOMIC_OP_KEY]: true\n\treadonly type: Type\n\treadonly value: Value\n}\n\n/** The numeric helpers (`op.increment`, `op.decrement`, `op.max`, `op.min`). */\nexport type NumericAtomicOpSentinel = AtomicOpSentinel<'increment' | 'max' | 'min', number>\n\n/** The array helpers (`op.append`, `op.remove`) for an array of `Item`. */\nexport type ArrayAtomicOpSentinel<Item> = AtomicOpSentinel<'append' | 'remove', Item>\n\n/**\n * Constraint of an array helper's item: listing the primitive types keeps a literal\n * argument's literal type (`op.append('high')` is `'high'`, assignable to an enum array),\n * while objects are inferred as written (not readonly).\n */\ntype AtomicItem = string | number | boolean | bigint | symbol | object | null | undefined\n\n/**\n * Type guard: checks whether a value is an atomic op sentinel.\n *\n * @param value - Any value to check\n * @returns true if the value is an AtomicOpSentinel\n */\nexport function isAtomicOp(value: unknown): value is AtomicOpSentinel {\n\treturn (\n\t\ttypeof value === 'object' &&\n\t\tvalue !== null &&\n\t\tKORA_ATOMIC_OP in value &&\n\t\t(value as Record<symbol, unknown>)[KORA_ATOMIC_OP] === true\n\t)\n}\n\n/**\n * Apply a plain atomic op (`{ type, value }`) to a current value, producing the\n * concrete result. This is the single source of truth for atomic-op semantics:\n * {@link resolveAtomicOp} (sentinel form, used on the write path) delegates here,\n * and the server's materialization replays stored atomic ops through it, so the\n * server's materialized view composes concurrent atomic writes identically to the\n * client. Folding this over a field's writes in HLC order yields, for a same-type\n * atomic chain, exactly the composed intent (sum of increments, max of maxes, ...).\n *\n * @param currentValue - The current value of the field\n * @param atomicOp - The atomic op to apply (type + operand)\n * @returns The resulting concrete value\n */\nexport function applyAtomicOp(currentValue: unknown, atomicOp: AtomicOp): unknown {\n\tswitch (atomicOp.type) {\n\t\tcase 'increment': {\n\t\t\tconst current = typeof currentValue === 'number' ? currentValue : 0\n\t\t\tconst operand = atomicOp.value as number\n\t\t\treturn current + operand\n\t\t}\n\t\tcase 'max': {\n\t\t\tconst current = typeof currentValue === 'number' ? currentValue : Number.NEGATIVE_INFINITY\n\t\t\treturn Math.max(current, atomicOp.value as number)\n\t\t}\n\t\tcase 'min': {\n\t\t\tconst current = typeof currentValue === 'number' ? currentValue : Number.POSITIVE_INFINITY\n\t\t\treturn Math.min(current, atomicOp.value as number)\n\t\t}\n\t\tcase 'append': {\n\t\t\tconst current = Array.isArray(currentValue) ? [...currentValue] : []\n\t\t\tcurrent.push(atomicOp.value)\n\t\t\treturn current\n\t\t}\n\t\tcase 'remove': {\n\t\t\tif (!Array.isArray(currentValue)) return []\n\t\t\t// Compare by value (JSON), matching add-wins-set semantics, so removing an\n\t\t\t// object or array element works instead of silently no-op'ing under the\n\t\t\t// reference inequality that `!==` would give for non-primitives.\n\t\t\tconst target = JSON.stringify(atomicOp.value)\n\t\t\treturn currentValue.filter((item) => JSON.stringify(item) !== target)\n\t\t}\n\t}\n}\n\n/**\n * Resolve an atomic op sentinel against a current value to produce a concrete result.\n *\n * @param currentValue - The current value of the field in the database\n * @param sentinel - The atomic op sentinel from the developer's update call\n * @returns The resolved concrete value\n */\nexport function resolveAtomicOp(currentValue: unknown, sentinel: AtomicOpSentinel): unknown {\n\treturn applyAtomicOp(currentValue, { type: sentinel.type, value: sentinel.value })\n}\n\nfunction createSentinel<Type extends AtomicOpType, Value>(\n\ttype: Type,\n\tvalue: Value,\n): AtomicOpSentinel<Type, Value> {\n\treturn Object.freeze({\n\t\t[KORA_ATOMIC_OP]: true as const,\n\t\ttype,\n\t\tvalue,\n\t})\n}\n\n/**\n * Atomic operation helpers. Use these in collection.update() calls\n * to express intent-preserving mutations.\n *\n * @example\n * ```typescript\n * import { op } from 'korajs'\n *\n * // Increment a counter (works correctly with concurrent updates)\n * await app.stock.update(id, { quantity: op.increment(-5) })\n *\n * // Keep the maximum value\n * await app.scores.update(id, { highScore: op.max(newScore) })\n *\n * // Append to an array\n * await app.todos.update(id, { tags: op.append('urgent') })\n * ```\n */\nexport const op = {\n\t/**\n\t * Increment a number field by the given amount.\n\t * Concurrent increments compose: the sum of all deltas is applied to the base.\n\t *\n\t * @param n - The amount to increment (use negative values to decrement)\n\t */\n\tincrement(n: number): AtomicOpSentinel<'increment', number> {\n\t\treturn createSentinel('increment', n)\n\t},\n\n\t/**\n\t * Decrement a number field by the given amount.\n\t * Syntactic sugar for `op.increment(-n)`.\n\t *\n\t * @param n - The amount to decrement\n\t */\n\tdecrement(n: number): AtomicOpSentinel<'increment', number> {\n\t\treturn createSentinel('increment', -n)\n\t},\n\n\t/**\n\t * Set the field to the maximum of the current value and the given value.\n\t * Concurrent max operations take the maximum of all values.\n\t *\n\t * @param n - The value to compare against the current value\n\t */\n\tmax(n: number): AtomicOpSentinel<'max', number> {\n\t\treturn createSentinel('max', n)\n\t},\n\n\t/**\n\t * Set the field to the minimum of the current value and the given value.\n\t * Concurrent min operations take the minimum of all values.\n\t *\n\t * @param n - The value to compare against the current value\n\t */\n\tmin(n: number): AtomicOpSentinel<'min', number> {\n\t\treturn createSentinel('min', n)\n\t},\n\n\t/**\n\t * Append an item to an array field.\n\t * Concurrent appends include all appended items.\n\t *\n\t * @param item - The item to append to the array\n\t */\n\tappend<Item extends AtomicItem>(item: Item): AtomicOpSentinel<'append', Item> {\n\t\treturn createSentinel('append', item)\n\t},\n\n\t/**\n\t * Remove an item from an array field (by value equality).\n\t * Concurrent removes of the same item are idempotent.\n\t *\n\t * @param item - The item to remove from the array\n\t */\n\tremove<Item extends AtomicItem>(item: Item): AtomicOpSentinel<'remove', Item> {\n\t\treturn createSentinel('remove', item)\n\t},\n}\n\n/**\n * Extract the serializable AtomicOp from a sentinel (strips the Symbol marker).\n *\n * @param sentinel - The atomic op sentinel\n * @returns A plain object suitable for JSON serialization\n */\nexport function toAtomicOp(sentinel: AtomicOpSentinel): AtomicOp {\n\treturn { type: sentinel.type, value: sentinel.value }\n}\n","import { HybridLogicalClock } from '../clock/hlc'\nimport type { AtomicOp, HLCTimestamp, Operation } from '../types'\nimport { applyAtomicOp } from './atomic-ops'\nimport { canonicalize } from './content-hash'\n\n/** One operation's contribution to a record's materialized state. */\nexport interface ReplayOperation {\n\ttype: string\n\tdata: Record<string, unknown> | null\n\t/**\n\t * Atomic-op intents carried by this operation, per field. When present, a field\n\t * is composed (rather than overwritten) if the previous writer on that field was\n\t * an atomic op of the same type. Absent means every field resolves by\n\t * last-write-wins.\n\t */\n\tatomicOps?: Record<string, AtomicOp> | null\n\t/**\n\t * For updates: the values the writer saw before its change. Array fields use it\n\t * as the base of a three-way set merge (see {@link mergeArraySet}). Absent means\n\t * array fields resolve by last-write-wins.\n\t */\n\tpreviousData?: Record<string, unknown> | null\n}\n\n/**\n * Three-way set merge for array fields, shared by the client merge engine\n * (`addWinsSet`) and the record fold, so client and server agree.\n *\n * result = (local ∩ remote) ∪ (local − base) ∪ (remote − base)\n *\n * A base element is kept only if BOTH sides kept it (a one-sided removal is never\n * undone by the other side's unchanged copy); a non-base element is kept if EITHER\n * side has it. Elements are compared by `JSON.stringify`.\n *\n * Order is role-independent: kept base elements first, in base order, then every\n * other kept element sorted by its serialized form. Swapping `local` and `remote`\n * yields the identical array.\n *\n * Interim (S1): W7 replaces this pairwise rule with a per-element LWW set.\n *\n * @param local - One side's array after its modifications\n * @param remote - The other side's array after its modifications\n * @param base - The common ancestor both sides edited from\n * @returns The merged array\n */\nexport function mergeArraySet(local: unknown[], remote: unknown[], base: unknown[]): unknown[] {\n\tconst serialize = (v: unknown): string => JSON.stringify(v)\n\n\tconst baseSet = new Set(base.map(serialize))\n\tconst localSet = new Set(local.map(serialize))\n\tconst remoteSet = new Set(remote.map(serialize))\n\n\tconst keep = (s: string): boolean =>\n\t\t(localSet.has(s) && remoteSet.has(s)) ||\n\t\t(!baseSet.has(s) && (localSet.has(s) || remoteSet.has(s)))\n\n\tconst seen = new Set<string>()\n\tconst result: unknown[] = []\n\tconst addIfKept = (serialized: string, value: unknown): void => {\n\t\tif (!seen.has(serialized) && keep(serialized)) {\n\t\t\tseen.add(serialized)\n\t\t\tresult.push(value)\n\t\t}\n\t}\n\n\tfor (const item of base) {\n\t\taddIfKept(serialize(item), item)\n\t}\n\n\tconst others = new Map<string, unknown>()\n\tfor (const item of [...local, ...remote]) {\n\t\tconst s = serialize(item)\n\t\tif (!baseSet.has(s) && !others.has(s)) {\n\t\t\tothers.set(s, item)\n\t\t}\n\t}\n\tfor (const s of [...others.keys()].sort()) {\n\t\taddIfKept(s, others.get(s))\n\t}\n\n\treturn result\n}\n\n/**\n * Resolve a plain (non-atomic) write of an array field onto the running value.\n * When the running value is exactly the writer's base, the write fast-forwards\n * and keeps the writer's element order (what the authoring client materialized).\n * Otherwise a concurrent writer changed the field since that base, so the write's\n * delta is merged with {@link mergeArraySet}, exactly like the client merge.\n */\nfunction resolveArrayWrite(running: unknown, value: unknown, base: unknown): unknown {\n\tif (!Array.isArray(running) || !Array.isArray(value) || !Array.isArray(base)) {\n\t\treturn value\n\t}\n\tif (canonicalize(running) === canonicalize(base)) {\n\t\treturn value\n\t}\n\treturn mergeArraySet(running, value, base)\n}\n\n/**\n * Replay a list of operations (MUST be pre-sorted in HLC total order —\n * wallTime, then logical, then nodeId) to produce the current state of a single\n * record, composing atomic-op intents.\n *\n * Per field, an atomic op composes onto the running value only when the field's\n * previous writer was an atomic op of the SAME type (a same-type atomic chain:\n * concurrent increments sum, maxes take the max, appends accumulate); any other\n * write, including the first atomic write after a plain set, resolves by\n * last-write-wins on the resolved value. Because operations are folded in HLC order,\n * the current op always wins that last-write-wins comparison, so the result is\n * deterministic and identical on every replica that folds the same operation set.\n *\n * Plain array writes that carry `previousData` are merged as a set against that\n * base (see {@link mergeArraySet}) when a concurrent writer changed the field since\n * the base, so the fold and the client merge agree on one-sided removals.\n *\n * This is the single definition of atomic materialization shared by the client\n * (`@korajs/store` apply pipeline) and the server (`@korajs/server` materialization),\n * so both converge to the same value for any number of concurrent atomic writers.\n *\n * Returns the record field data (without `id`) or null if the record was deleted\n * or never inserted.\n */\nexport function replayOperationsForRecord(ops: ReplayOperation[]): Record<string, unknown> | null {\n\tlet record: Record<string, unknown> | null = null\n\tlet deleted = false\n\t// Per-field provenance of the running value: 'lww' for a plain set, or\n\t// `atomic:<type>` for an atomic write. Drives the compose-vs-overwrite decision.\n\tconst lastWriterKind: Record<string, string> = {}\n\n\tfor (const op of ops) {\n\t\tswitch (op.type) {\n\t\t\tcase 'insert':\n\t\t\t\tif (op.data) {\n\t\t\t\t\trecord = { ...op.data }\n\t\t\t\t\tdeleted = false\n\t\t\t\t\tfor (const field of Object.keys(op.data)) {\n\t\t\t\t\t\tlastWriterKind[field] = 'lww'\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\tcase 'update':\n\t\t\t\tif (op.data) {\n\t\t\t\t\tconst next: Record<string, unknown> = { ...(record ?? {}) }\n\t\t\t\t\tfor (const [field, value] of Object.entries(op.data)) {\n\t\t\t\t\t\tconst atomicOp = op.atomicOps?.[field]\n\t\t\t\t\t\tif (atomicOp && lastWriterKind[field] === `atomic:${atomicOp.type}`) {\n\t\t\t\t\t\t\t// Same-type atomic chain: compose the intent onto the running value.\n\t\t\t\t\t\t\tnext[field] = applyAtomicOp(next[field], atomicOp)\n\t\t\t\t\t\t} else if (!atomicOp && op.previousData && field in op.previousData) {\n\t\t\t\t\t\t\t// Plain write with a known base: arrays merge as a set against\n\t\t\t\t\t\t\t// that base; every other kind is last-write-wins.\n\t\t\t\t\t\t\tnext[field] = resolveArrayWrite(next[field], value, op.previousData[field])\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t// Last-write-wins on the resolved value (later HLC supersedes).\n\t\t\t\t\t\t\tnext[field] = value\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlastWriterKind[field] = atomicOp ? `atomic:${atomicOp.type}` : 'lww'\n\t\t\t\t\t}\n\t\t\t\t\trecord = next\n\t\t\t\t\tdeleted = false\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\tcase 'delete':\n\t\t\t\tdeleted = true\n\t\t\t\tbreak\n\t\t}\n\t}\n\n\treturn deleted ? null : record\n}\n\n/** A {@link ReplayOperation} with the HLC timestamp it was written at. */\nexport interface VersionedReplayOperation {\n\ttype: string\n\tdata: Record<string, unknown> | null\n\ttimestamp: HLCTimestamp\n}\n\n/** Per-field versions of a live record, as folded by {@link replayFieldVersionsForRecord}. */\nexport interface RecordFieldVersions {\n\t/** Field name -> HLC of the write that produced the field's current value. */\n\tfields: Record<string, HLCTimestamp>\n\t/** The record's first operation (its creation; the server's `_created_at`). */\n\tcreated: HLCTimestamp\n\t/** The record's newest operation. */\n\tlatest: HLCTimestamp\n}\n\n/**\n * Fold the per-field versions of one record, mirroring {@link replayOperationsForRecord}\n * exactly (RT-27): an insert resets the field set and stamps every field it carries,\n * an update stamps the fields it writes (composed atomic and array writes included:\n * the field's version is its last writer's), a delete hides the record until a later\n * write revives it. Operations MUST be pre-sorted in HLC total order.\n *\n * @param ops - The record's operations in HLC order\n * @returns The live record's field versions, or null when it is deleted or absent\n */\nexport function replayFieldVersionsForRecord(\n\tops: readonly VersionedReplayOperation[],\n): RecordFieldVersions | null {\n\tlet fields: Record<string, HLCTimestamp> | null = null\n\tlet deleted = false\n\tconst first = ops[0]\n\tconst last = ops[ops.length - 1]\n\tif (!first || !last) return null\n\tfor (const op of ops) {\n\t\tswitch (op.type) {\n\t\t\tcase 'insert':\n\t\t\t\tif (op.data) {\n\t\t\t\t\tfields = {}\n\t\t\t\t\tfor (const field of Object.keys(op.data)) fields[field] = { ...op.timestamp }\n\t\t\t\t\tdeleted = false\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\tcase 'update':\n\t\t\t\tif (op.data) {\n\t\t\t\t\tconst next: Record<string, HLCTimestamp> = { ...(fields ?? {}) }\n\t\t\t\t\tfor (const field of Object.keys(op.data)) next[field] = { ...op.timestamp }\n\t\t\t\t\tfields = next\n\t\t\t\t\tdeleted = false\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\tcase 'delete':\n\t\t\t\tdeleted = true\n\t\t\t\tbreak\n\t\t}\n\t}\n\tif (deleted || fields === null) return null\n\treturn { fields, created: { ...first.timestamp }, latest: { ...last.timestamp } }\n}\n\n/**\n * Expand operations for a record fold (RT-27). A scope-entry insert carrying\n * per-field versions restates the record's CURRENT values, each produced at its own\n * version; folding it as one insert at a single timestamp would misplace every field\n * relative to the receiver's own writes. It is expanded into an insert at its\n * `timestamp` (the record's creation) followed by one update per newer field version,\n * so a fold in HLC order puts each field exactly where its writer did. Other\n * operations pass through unchanged. The result is sorted in HLC total order (stable,\n * so an expansion keeps insert-before-update on equal timestamps).\n *\n * @param ops - Operations of one record, in any order\n * @returns The operations to fold, in HLC order\n */\nexport function expandFieldVersionedOperations(ops: readonly Operation[]): Operation[] {\n\tconst expanded: Operation[] = []\n\tfor (const op of ops) {\n\t\tif (op.type !== 'insert' || !op.fieldVersions || !op.data) {\n\t\t\texpanded.push(op)\n\t\t\tcontinue\n\t\t}\n\t\tconst { fieldVersions, ...base } = op\n\t\texpanded.push(base)\n\t\tconst groups = new Map<string, { timestamp: HLCTimestamp; data: Record<string, unknown> }>()\n\t\t// A field without its own version falls back to the entry's newest one.\n\t\tlet newest = op.timestamp\n\t\tfor (const v of Object.values(fieldVersions)) {\n\t\t\tif (HybridLogicalClock.compare(v, newest) > 0) newest = v\n\t\t}\n\t\tfor (const [field, value] of Object.entries(op.data)) {\n\t\t\tconst version = fieldVersions[field] ?? newest\n\t\t\tif (HybridLogicalClock.compare(version, op.timestamp) <= 0) continue\n\t\t\tconst key = `${version.wallTime}:${version.logical}:${version.nodeId}`\n\t\t\tconst group = groups.get(key) ?? { timestamp: version, data: {} }\n\t\t\tgroup.data[field] = value\n\t\t\tgroups.set(key, group)\n\t\t}\n\t\tlet index = 0\n\t\tfor (const group of groups.values()) {\n\t\t\texpanded.push({\n\t\t\t\t...base,\n\t\t\t\tid: `${op.id}#field-version-${index++}`,\n\t\t\t\ttype: 'update',\n\t\t\t\tdata: group.data,\n\t\t\t\tpreviousData: null,\n\t\t\t\ttimestamp: { ...group.timestamp },\n\t\t\t})\n\t\t}\n\t}\n\treturn expanded.sort((a, b) => HybridLogicalClock.compare(a.timestamp, b.timestamp))\n}\n","import type { Operation } from '../types'\nimport type { OperationTransform } from './operation-transform'\n\nconst MAX_TRANSFORM_STEPS = 32\n\n/**\n * Apply registered transforms until the operation matches `targetSchemaVersion`.\n * Returns null when a transform drops the operation or no path exists.\n */\nexport function applyOperationTransforms(\n\toperation: Operation,\n\ttargetSchemaVersion: number,\n\ttransforms: readonly OperationTransform[],\n): Operation | null {\n\tlet current: Operation = operation\n\n\tfor (let step = 0; step < MAX_TRANSFORM_STEPS; step++) {\n\t\tif (current.schemaVersion === targetSchemaVersion) {\n\t\t\treturn current\n\t\t}\n\n\t\tconst transform = transforms.find(\n\t\t\t(candidate) => candidate.fromVersion === current.schemaVersion,\n\t\t)\n\t\tif (!transform) {\n\t\t\treturn null\n\t\t}\n\n\t\tconst next = transform.transform(current)\n\t\tif (next === null) {\n\t\t\treturn null\n\t\t}\n\t\tcurrent = next\n\t}\n\n\treturn null\n}\n","import { KoraError } from '../errors/errors'\nimport { canonicalizeOperationBody } from '../operations/canonical-body'\nimport type { Operation } from '../types'\nimport { applyOperationTransforms } from './apply-operation-transforms'\nimport type { OperationTransform } from './operation-transform'\n\n/**\n * Thrown when a schema transform breaks its contract: it changed an operation's\n * identity (id, node, type, collection, record or timestamp), or produced a body with\n * no canonical JSON form.\n */\nexport class OperationTransformError extends KoraError {\n\tconstructor(message: string, context: Record<string, unknown>) {\n\t\tsuper(message, 'INVALID_OPERATION_TRANSFORM', {\n\t\t\t...context,\n\t\t\tfix: 'An OperationTransform may rewrite data, previousData, atomicOps and schemaVersion only, deterministically, with JSON values.',\n\t\t})\n\t\tthis.name = 'OperationTransformError'\n\t}\n}\n\n/**\n * The operation as a schema reads it: its schema view (transforms at fold time).\n *\n * Operations are immutable and content-addressed, so a schema transform never rewrites\n * a stored operation. Every replica (server stores and devices alike) stores and sends\n * the operation exactly as its author wrote it, and applies the transform chain only\n * when it judges or folds the operation, through this one function:\n * - the server authorizes and validates the view, and its stores fold the view;\n * - a device folds the view; an operation with no view (no transform path, e.g. one\n * authored under a NEWER schema than the device's) is kept aside and replayed after\n * the device upgrades.\n *\n * Contract, enforced here:\n * - transforms are PURE and DETERMINISTIC: the same operation and transforms give the\n * same view on every replica, at every time (no clock, randomness or I/O). Every\n * replica must register the same transforms for the schema versions its log holds;\n * the fold plan fingerprint includes them, so changing a transform re-folds;\n * - a transform rewrites `data`, `previousData`, `atomicOps` and `schemaVersion` only. A\n * view whose id, node, type, collection, record or timestamp differs is refused\n * ({@link OperationTransformError});\n * - the view's body is canonical (core canonical-body), like any written body.\n *\n * Returned unchanged: an operation already at `targetSchemaVersion`, any operation\n * when no transform is registered (it folds as written), and an encryption envelope the\n * caller cannot read (`encrypted` set: the server folds its cleartext header as is;\n * devices transform after decryption).\n *\n * @param op - The operation as stored\n * @param targetSchemaVersion - The schema version of the replica judging or folding it\n * @param transforms - The registered transforms\n * @returns The view, or null when a transform drops the operation or no path exists\n * @throws {OperationTransformError} When a transform breaks the contract above\n */\nexport function operationSchemaView(\n\top: Operation,\n\ttargetSchemaVersion: number,\n\ttransforms: readonly OperationTransform[] | undefined,\n): Operation | null {\n\tif (op.schemaVersion === targetSchemaVersion) return op\n\tif (transforms === undefined || transforms.length === 0) return op\n\tif (op.encrypted !== undefined) return op\n\tlet view: Operation | null\n\ttry {\n\t\tview = applyOperationTransforms(op, targetSchemaVersion, transforms)\n\t} catch (error) {\n\t\tthrow new OperationTransformError(\n\t\t\t`The schema transform of operation ${op.id} (schema v${op.schemaVersion} -> v${targetSchemaVersion}) threw: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t{ operationId: op.id, fromVersion: op.schemaVersion, toVersion: targetSchemaVersion },\n\t\t)\n\t}\n\tif (view === null || view === op) return view\n\tfor (const key of ['id', 'nodeId', 'type', 'collection', 'recordId'] as const) {\n\t\tif (view[key] !== op[key]) {\n\t\t\tthrow new OperationTransformError(\n\t\t\t\t`The schema transform of operation ${op.id} changed its ${key} (\"${String(op[key])}\" -> \"${String(view[key])}\"). A transform may rewrite data, previousData, atomicOps and schemaVersion only.`,\n\t\t\t\t{ operationId: op.id, field: key },\n\t\t\t)\n\t\t}\n\t}\n\tconst a = op.timestamp\n\tconst b = view.timestamp\n\tif (a.wallTime !== b.wallTime || a.logical !== b.logical || a.nodeId !== b.nodeId) {\n\t\tthrow new OperationTransformError(\n\t\t\t`The schema transform of operation ${op.id} changed its timestamp. A transform may rewrite data, previousData, atomicOps and schemaVersion only.`,\n\t\t\t{ operationId: op.id, field: 'timestamp' },\n\t\t)\n\t}\n\ttry {\n\t\treturn canonicalizeOperationBody(view)\n\t} catch (error) {\n\t\tthrow new OperationTransformError(\n\t\t\t`The schema transform of operation ${op.id} produced a value with no JSON form: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t{ operationId: op.id },\n\t\t)\n\t}\n}\n\n/**\n * FNV-1a over UTF-16 code units (same definition as the fold plan fingerprint).\n */\nfunction hashText(text: string): string {\n\tlet hash = 0x811c9dc5\n\tfor (let i = 0; i < text.length; i++) {\n\t\thash ^= text.charCodeAt(i)\n\t\thash = Math.imul(hash, 0x01000193) >>> 0\n\t}\n\treturn hash.toString(16).padStart(8, '0')\n}\n\n/**\n * Fingerprint of a transform chain for a target schema version: '' when no transform\n * is registered (operations fold as written, whatever the target), otherwise the\n * target version and each transform's versions and source text. Part of the fold plan\n * fingerprint, so a replica re-folds when its views change.\n *\n * @param targetSchemaVersion - The replica's schema version\n * @param transforms - The registered transforms\n */\nexport function operationTransformsFingerprint(\n\ttargetSchemaVersion: number,\n\ttransforms: readonly OperationTransform[] | undefined,\n): string {\n\tif (transforms === undefined || transforms.length === 0) return ''\n\tconst parts = transforms\n\t\t.map((t) => `${t.fromVersion}>${t.toVersion}:${hashText(String(t.transform))}`)\n\t\t.sort()\n\treturn `xf@v${targetSchemaVersion}(${parts.join(',')})`\n}\n\n/**\n * Thrown when stored operations have a schema version the registered transforms cannot\n * read (RT-103): starting would fold those operations as absent and silently erase them\n * from every record they belong to.\n */\nexport class OperationTransformCoverageError extends KoraError {\n\tconstructor(\n\t\tmessage: string,\n\t\tpublic readonly versions: readonly number[],\n\t\tpublic readonly targetSchemaVersion: number,\n\t\tcontext: Record<string, unknown> = {},\n\t) {\n\t\tsuper(message, 'OPERATION_TRANSFORM_MISSING', {\n\t\t\t...context,\n\t\t\tversions: [...versions],\n\t\t\ttargetSchemaVersion,\n\t\t\tfix: `Keep a transform path registered from every schema version in the operation log to v${targetSchemaVersion} (a transform must stay registered as long as operations of its source version exist, and the log is append-only), or register no transforms at all (operations then fold as written).`,\n\t\t})\n\t\tthis.name = 'OperationTransformCoverageError'\n\t}\n}\n\n/**\n * The stored schema versions the transforms have no path from (RT-103). Mirrors the\n * path {@link operationSchemaView} follows (`fromVersion` to `toVersion`, at most 32\n * steps). An empty transform list reads everything (operations fold as written).\n *\n * @param storedVersions - Distinct schema versions of the stored operations\n * @param targetSchemaVersion - The replica's schema version\n * @param transforms - The registered transforms\n * @returns Each version with no path and the version whose transform is missing, ascending\n */\nexport function missingTransformPaths(\n\tstoredVersions: Iterable<number>,\n\ttargetSchemaVersion: number,\n\ttransforms: readonly OperationTransform[] | undefined,\n): Array<{ version: number; missingFrom: number }> {\n\tif (transforms === undefined || transforms.length === 0) return []\n\tconst missing: Array<{ version: number; missingFrom: number }> = []\n\tfor (const version of new Set(storedVersions)) {\n\t\tif (version === targetSchemaVersion) continue\n\t\tlet current = version\n\t\tlet reached = false\n\t\tfor (let step = 0; step < 32; step++) {\n\t\t\tif (current === targetSchemaVersion) {\n\t\t\t\treached = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tconst next = transforms.find((candidate) => candidate.fromVersion === current)\n\t\t\tif (!next) break\n\t\t\tcurrent = next.toVersion\n\t\t}\n\t\tif (!reached) missing.push({ version, missingFrom: current })\n\t}\n\treturn missing.sort((a, b) => a.version - b.version)\n}\n\n/**\n * Refuse to start a replica whose transforms cannot read operations it stores (RT-103).\n *\n * @param storedVersions - Distinct schema versions of the stored operations\n * @param targetSchemaVersion - The replica's schema version\n * @param transforms - The registered transforms\n * @param replica - Names the replica in the message (\"server store\", \"local database\")\n * @throws {OperationTransformCoverageError} When a stored version has no path\n */\nexport function assertOperationTransformCoverage(\n\tstoredVersions: Iterable<number>,\n\ttargetSchemaVersion: number,\n\ttransforms: readonly OperationTransform[] | undefined,\n\treplica: string,\n): void {\n\tconst missing = missingTransformPaths(storedVersions, targetSchemaVersion, transforms)\n\tif (missing.length === 0) return\n\tconst versions = missing.map((entry) => entry.version)\n\tconst steps = [...new Set(missing.map((entry) => entry.missingFrom))]\n\tconst plural = versions.length > 1\n\tthrow new OperationTransformCoverageError(\n\t\t`The ${replica} holds operations of schema version${plural ? 's' : ''} ${versions.map((v) => `v${v}`).join(', ')}, but the registered operationTransforms have no path from ${plural ? 'them' : 'it'} to the current schema v${targetSchemaVersion} (no transform from ${steps.map((v) => `v${v}`).join(', ')}). Starting would silently drop those operations from their records, so it is refused. Keep the retired transform(s) registered: a transform may be removed only after every operation of its source version has been folded into snapshots by an explicit compaction.`,\n\t\tversions,\n\t\ttargetSchemaVersion,\n\t\t{ replica, missingFrom: steps },\n\t)\n}\n","/**\n * Node-id namespaces Kora reserves for itself.\n *\n * Every id starting with {@link RESERVED_NODE_ID_PREFIX} belongs to Kora: devices\n * never author under one (a client refuses to adopt such an id, and the server\n * refuses it at the handshake). Inside it, {@link SERVER_NODE_ID_PREFIX} names the\n * server's own nodes (`kora:server:<stableId>`): their writes are authoritative for\n * `merge('server-authoritative')` fields on every replica, whatever list of node\n * ids a given handshake advertised. That keeps authority stable across server\n * restarts and instances without any replica having to learn the ids first.\n */\nexport const RESERVED_NODE_ID_PREFIX = 'kora:'\n\n/** Prefix of every server-authored node id: `kora:server:<stableId>`. */\nexport const SERVER_NODE_ID_PREFIX = 'kora:server:'\n\n/** True when `nodeId` is in Kora's reserved `kora:` namespace. */\nexport function isReservedNodeId(nodeId: string): boolean {\n\treturn nodeId.startsWith(RESERVED_NODE_ID_PREFIX)\n}\n\n/** True when `nodeId` names a server node (`kora:server:<stableId>`). */\nexport function isServerNodeId(nodeId: string): boolean {\n\treturn nodeId.startsWith(SERVER_NODE_ID_PREFIX) && nodeId.length > SERVER_NODE_ID_PREFIX.length\n}\n\n/**\n * Whether a node's writes are authoritative for `merge('server-authoritative')`\n * fields: a server node by prefix, or one of `explicit` (legacy, randomly generated\n * server node ids a server keeps advertising in its handshake).\n *\n * @param nodeId - The writing node\n * @param explicit - Additional authoritative node ids (`FoldOptions.authoritativeNodeIds`)\n */\nexport function isAuthoritativeNodeId(nodeId: string, explicit?: ReadonlySet<string>): boolean {\n\treturn isServerNodeId(nodeId) || (explicit?.has(nodeId) ?? false)\n}\n","import { KoraError } from '../errors/errors'\n\n/**\n * A fold state cannot be used: unknown format version, malformed JSON, a state\n * for a different record, or a field whose stored kind no longer matches the\n * schema. The fix is always the same: re-fold the record from its operation log\n * (`foldRecord`), which is the source of truth.\n */\nexport class FoldStateError extends KoraError {\n\tconstructor(message: string, context?: Record<string, unknown>) {\n\t\tsuper(message, 'FOLD_STATE_INVALID', {\n\t\t\tfix: 'Rebuild the record state from its operation log with foldRecord(ops, schema).',\n\t\t\t...context,\n\t\t})\n\t\tthis.name = 'FoldStateError'\n\t}\n}\n\n/**\n * The fold was asked for something its configuration cannot provide, for example\n * materializing a richtext field with several concurrent Yjs updates without a\n * richtext merger.\n */\nexport class FoldConfigurationError extends KoraError {\n\tconstructor(message: string, context?: Record<string, unknown>) {\n\t\tsuper(message, 'FOLD_CONFIGURATION', context)\n\t\tthis.name = 'FoldConfigurationError'\n\t}\n}\n","import { canonicalize } from '../operations/content-hash'\nimport { bytesToBase64 } from '../operations/op-data-binary'\n\n/** A plain data object (not an array, null, Date, Uint8Array or class instance). */\nexport function isPlainObject(value: unknown): value is Record<string, unknown> {\n\tif (typeof value !== 'object' || value === null || Array.isArray(value)) return false\n\tconst proto = Object.getPrototypeOf(value)\n\treturn proto === null || proto === Object.prototype\n}\n\n/**\n * Normalize a value entering the fold state into its JSON-safe form, exactly as\n * it would be after an op-log round-trip: binary values become the tagged\n * `{ $koraBytes }` form and `undefined` object members are dropped. Every replica\n * therefore holds (and materializes) the same representation whether or not its\n * copy of an operation was ever serialized.\n */\nexport function normalizeValue(value: unknown): unknown {\n\tif (value instanceof Uint8Array) return { $koraBytes: bytesToBase64(value) }\n\tif (value instanceof ArrayBuffer) return { $koraBytes: bytesToBase64(new Uint8Array(value)) }\n\tif (Array.isArray(value)) return value.map(normalizeValue)\n\tif (isPlainObject(value)) {\n\t\tconst out: Record<string, unknown> = {}\n\t\tfor (const [key, member] of Object.entries(value)) {\n\t\t\tif (member !== undefined) out[key] = normalizeValue(member)\n\t\t}\n\t\treturn out\n\t}\n\treturn value\n}\n\n/** Canonical JSON (sorted keys) of a normalized value: the identity used for equality. */\nexport function canonicalKey(value: unknown): string {\n\treturn canonicalize(normalizeValue(value))\n}\n\n/** Structural equality by canonical JSON. */\nexport function sameValue(a: unknown, b: unknown): boolean {\n\treturn a === b || canonicalKey(a) === canonicalKey(b)\n}\n","import { applyAtomicOp } from '../operations/atomic-ops'\nimport { canonicalValue } from '../operations/canonical-body'\nimport { base64ToBytes, bytesToBase64, decodeBytesFromOpData } from '../operations/op-data-binary'\nimport type { AtomicOp } from '../types'\nimport { FoldConfigurationError } from './errors'\nimport type { FieldPlan } from './field-kind'\nimport { compareStamps, isAfter, maxStamp } from './stamp'\nimport type {\n\tCounterFieldState,\n\tElementSetFieldState,\n\tElementState,\n\tExtremumFieldState,\n\tFieldLogEntry,\n\tFieldState,\n\tKeyMapFieldState,\n\tKeyState,\n\tRegisterFieldState,\n\tResolverFieldState,\n\tRichtextFieldState,\n\tRichtextSubsumes,\n\tRichtextUpdateMerger,\n\tStamp,\n} from './types'\nimport { canonicalKey, isPlainObject } from './values'\n\n/**\n * One operation's write to one field, already normalized. Built by the record\n * fold; an update whose value equals its own `previousData` is not a write (the\n * writer restated the field without changing it) and never reaches this layer.\n */\nexport interface FieldWrite {\n\ts: Stamp\n\tinsert: boolean\n\tv: unknown\n\t/** The writer's base (`previousData[field]`), undefined when it has none. */\n\tprev: unknown\n\thasPrev: boolean\n\ta?: AtomicOp\n}\n\n/** A fresh, empty state for a field folded by `plan`. */\nexport function emptyField(plan: FieldPlan): FieldState {\n\tswitch (plan.kind) {\n\t\tcase 'reg':\n\t\t\treturn { k: 'reg', e: [], val: undefined }\n\t\tcase 'res':\n\t\t\treturn { k: 'res', e: [], val: undefined }\n\t\tcase 'set':\n\t\t\treturn { k: 'set', ao: plan.appendOnly, sh: null, clr: null, el: {} }\n\t\tcase 'map':\n\t\t\treturn { k: 'map', sh: null, clr: null, keys: {} }\n\t\tcase 'ctr':\n\t\t\treturn { k: 'ctr', base: null, d: [], val: undefined }\n\t\tcase 'max':\n\t\tcase 'min':\n\t\t\treturn { k: plan.kind, best: null, reg: null }\n\t\tcase 'rt':\n\t\t\treturn { k: 'rt', reset: null, u: {} }\n\t}\n}\n\n/** Result of applying a write: the new state (a copy when changed) and whether it changed. */\nexport interface FieldApplyResult {\n\tstate: FieldState\n\tchanged: boolean\n\t/** Set when a custom resolver threw while producing the new value. */\n\terror?: string\n}\n\n// ---------------------------------------------------------------------------\n// Register (scalars + atomic chain)\n// ---------------------------------------------------------------------------\n\nfunction entryKind(entry: FieldLogEntry): string {\n\treturn entry.a ? entry.a.type : 'set'\n}\n\n/**\n * Fold a chain: a plain write takes its value; an atomic write composes onto the\n * running value only when the previous write was an atomic op of the same type\n * (concurrent increments sum, maxes take the max); otherwise it takes its own\n * resolved value. Same rule as the pre-W7 record replay.\n */\nfunction chainFold(entries: readonly FieldLogEntry[]): unknown {\n\tlet value: unknown\n\tlet last: string | null = null\n\tfor (const entry of entries) {\n\t\tvalue = entry.a && last === entry.a.type ? applyAtomicOp(value, entry.a) : entry.v\n\t\tlast = entryKind(entry)\n\t}\n\treturn value\n}\n\n/** Index at which `stamp` belongs in a stamp-sorted log, or -1 if already present. */\nfunction insertionIndex(entries: readonly FieldLogEntry[], stamp: Stamp): number {\n\tlet lo = 0\n\tlet hi = entries.length\n\twhile (lo < hi) {\n\t\tconst mid = (lo + hi) >>> 1\n\t\tconst entry = entries[mid] as FieldLogEntry\n\t\tconst cmp = compareStamps(entry.s, stamp)\n\t\tif (cmp === 0) return -1\n\t\tif (cmp < 0) lo = mid + 1\n\t\telse hi = mid\n\t}\n\treturn lo\n}\n\n/** Drop every entry older than the newest plain write (a plain write resets the field). */\nfunction pruneChain(entries: FieldLogEntry[]): FieldLogEntry[] {\n\tfor (let i = entries.length - 1; i > 0; i--) {\n\t\tif (!(entries[i] as FieldLogEntry).a) return entries.slice(i)\n\t}\n\treturn entries\n}\n\nfunction toEntry(write: FieldWrite): FieldLogEntry {\n\treturn write.a ? { s: write.s, v: write.v, a: write.a } : { s: write.s, v: write.v }\n}\n\nfunction applyRegister(state: RegisterFieldState, write: FieldWrite): FieldApplyResult {\n\tconst entries = state.e\n\tconst index = insertionIndex(entries, write.s)\n\tif (index === -1) return { state, changed: false }\n\tconst first = entries[0]\n\t// Older than the newest plain write: it cannot affect the value.\n\tif (index === 0 && first !== undefined && !first.a) return { state, changed: false }\n\tconst entry = toEntry(write)\n\tif (index === entries.length) {\n\t\tif (!entry.a) return { state: { k: 'reg', e: [entry], val: entry.v }, changed: true }\n\t\tconst last = entries[entries.length - 1]\n\t\tconst val =\n\t\t\tlast !== undefined && entryKind(last) === entry.a.type\n\t\t\t\t? applyAtomicOp(state.val, entry.a)\n\t\t\t\t: entry.v\n\t\treturn { state: { k: 'reg', e: [...entries, entry], val }, changed: true }\n\t}\n\tconst next = pruneChain([...entries.slice(0, index), entry, ...entries.slice(index)])\n\treturn { state: { k: 'reg', e: next, val: chainFold(next) }, changed: true }\n}\n\nfunction mergeLogs(a: readonly FieldLogEntry[], b: readonly FieldLogEntry[]): FieldLogEntry[] {\n\tconst out: FieldLogEntry[] = []\n\tlet i = 0\n\tlet j = 0\n\twhile (i < a.length || j < b.length) {\n\t\tconst x = a[i]\n\t\tconst y = b[j]\n\t\tif (y === undefined || (x !== undefined && compareStamps(x.s, y.s) < 0)) {\n\t\t\tout.push(x as FieldLogEntry)\n\t\t\ti++\n\t\t} else if (x === undefined || compareStamps(x.s, y.s) > 0) {\n\t\t\tout.push(y)\n\t\t\tj++\n\t\t} else {\n\t\t\tout.push(x)\n\t\t\ti++\n\t\t\tj++\n\t\t}\n\t}\n\treturn out\n}\n\n// ---------------------------------------------------------------------------\n// Resolver log\n// ---------------------------------------------------------------------------\n\nfunction resolveStep(\n\tplan: FieldPlan,\n\tcurrent: unknown,\n\tentry: FieldLogEntry,\n): { value: unknown; error?: string } {\n\ttry {\n\t\t// A resolver's output enters the state in its canonical form (core canonical-body),\n\t\t// the form it has after the persisted state's JSON round trip: undefined is null,\n\t\t// -0 is 0, a Date is its ISO string, bytes are tagged. So the in-memory state and\n\t\t// the persisted one are identical on every replica. An output with no JSON form\n\t\t// (NaN, Infinity, a Map, a cycle) is handled like a throwing resolver.\n\t\treturn { value: canonicalValue(plan.resolver?.(current, entry.v, entry.b), 'resolver') }\n\t} catch (error) {\n\t\t// A throwing resolver must not wedge the record on every replica. The fold\n\t\t// falls back to the incoming (later) value, deterministically, and reports\n\t\t// the exception on the field state and in the merge trace.\n\t\treturn { value: entry.v, error: error instanceof Error ? error.message : String(error) }\n\t}\n}\n\nfunction resolverFold(\n\tplan: FieldPlan,\n\tentries: readonly FieldLogEntry[],\n): { value: unknown; error?: string } {\n\tlet value: unknown\n\tlet error: string | undefined\n\tentries.forEach((entry, index) => {\n\t\tif (index === 0) {\n\t\t\tvalue = entry.v\n\t\t\treturn\n\t\t}\n\t\tconst step = resolveStep(plan, value, entry)\n\t\tvalue = step.value\n\t\tif (step.error !== undefined) error = step.error\n\t})\n\treturn error === undefined ? { value } : { value, error }\n}\n\n/**\n * Drop every entry older than the newest snapshot entry (`z`): a snapshot stands\n * for the whole history before it, so the log always starts at the newest one.\n */\nexport function pruneResolverLog(entries: FieldLogEntry[]): FieldLogEntry[] {\n\tfor (let i = entries.length - 1; i > 0; i--) {\n\t\tif ((entries[i] as FieldLogEntry).z === 1) return entries.slice(i)\n\t}\n\treturn entries\n}\n\nfunction resolverState(\n\tentries: FieldLogEntry[],\n\tresult: { value: unknown; error?: string },\n): ResolverFieldState {\n\treturn result.error === undefined\n\t\t? { k: 'res', e: entries, val: result.value }\n\t\t: { k: 'res', e: entries, val: result.value, err: result.error }\n}\n\nfunction applyResolver(\n\tstate: ResolverFieldState,\n\twrite: FieldWrite,\n\tplan: FieldPlan,\n): FieldApplyResult {\n\tconst index = insertionIndex(state.e, write.s)\n\tif (index === -1) return { state, changed: false }\n\t// Older than a snapshot entry: the snapshot already reflects it.\n\tif (index === 0 && state.e[0]?.z === 1) return { state, changed: false }\n\tconst entry: FieldLogEntry = { s: write.s, v: write.v }\n\tif (write.insert) entry.b = null\n\telse if (write.hasPrev) entry.b = write.prev\n\tif (index === state.e.length) {\n\t\tconst entries = [...state.e, entry]\n\t\tif (state.e.length === 0)\n\t\t\treturn { state: resolverState(entries, { value: entry.v }), changed: true }\n\t\tconst step = resolveStep(plan, state.val, entry)\n\t\tconst next: ResolverFieldState =\n\t\t\tstep.error !== undefined\n\t\t\t\t? { k: 'res', e: entries, val: step.value, err: step.error }\n\t\t\t\t: state.err !== undefined\n\t\t\t\t\t? { k: 'res', e: entries, val: step.value, err: state.err }\n\t\t\t\t\t: { k: 'res', e: entries, val: step.value }\n\t\treturn {\n\t\t\tstate: next,\n\t\t\tchanged: true,\n\t\t\t...(step.error !== undefined ? { error: step.error } : {}),\n\t\t}\n\t}\n\tconst entries = [...state.e.slice(0, index), entry, ...state.e.slice(index)]\n\tconst result = resolverFold(plan, entries)\n\treturn { state: resolverState(entries, result), changed: true }\n}\n\n// ---------------------------------------------------------------------------\n// Element set (arrays)\n// ---------------------------------------------------------------------------\n\nfunction laterShape<T extends { s: Stamp }>(current: T | null, next: T): T | null {\n\treturn current === null || compareStamps(next.s, current.s) > 0 ? next : null\n}\n\nfunction firstAddBefore(a: { s: Stamp; i: number } | null, b: { s: Stamp; i: number }): boolean {\n\tif (a === null) return true\n\tconst cmp = compareStamps(b.s, a.s)\n\treturn cmp < 0 || (cmp === 0 && b.i < a.i)\n}\n\ninterface ElementWriter {\n\t/** Add occurrence `occurrence` of `value`; `index` is its position in the written array. */\n\tadd(value: unknown, occurrence: number, stamp: Stamp, index: number): void\n\tremove(value: unknown, occurrence: number, stamp: Stamp): void\n\t/** The (copy-on-write) element map and whether any element changed. */\n\tresult(): { el: Record<string, ElementState>; changed: boolean }\n}\n\n/**\n * Identity of one occurrence of an array element: the canonical JSON of the value\n * plus its occurrence number (the k-th copy of that value, from 0). Canonical JSON\n * never ends in `#<digits>`, so the key is unambiguous.\n */\nexport function elementKey(canonicalValue: string, occurrence: number): string {\n\treturn `${canonicalValue}#${occurrence}`\n}\n\nfunction elementWriter(base: Record<string, ElementState>): ElementWriter {\n\tlet el = base\n\tlet changed = false\n\tconst read = (value: unknown, occurrence: number): [string, ElementState] => {\n\t\tconst canonical = canonicalKey(value)\n\t\tconst key = elementKey(canonical, occurrence)\n\t\tconst existing = el[key]\n\t\treturn [\n\t\t\tkey,\n\t\t\texisting\n\t\t\t\t? { ...existing }\n\t\t\t\t: { v: JSON.parse(canonical) as unknown, n: occurrence, a: null, f: null, r: null },\n\t\t]\n\t}\n\tconst store = (key: string, element: ElementState): void => {\n\t\tif (el === base) el = { ...base }\n\t\tel[key] = element\n\t\tchanged = true\n\t}\n\treturn {\n\t\tadd(value, occurrence, stamp, index) {\n\t\t\tconst [key, element] = read(value, occurrence)\n\t\t\tlet touched = false\n\t\t\tif (isAfter(stamp, element.a)) {\n\t\t\t\telement.a = stamp\n\t\t\t\ttouched = true\n\t\t\t}\n\t\t\tconst first = { s: stamp, i: index }\n\t\t\tif (firstAddBefore(element.f, first)) {\n\t\t\t\telement.f = first\n\t\t\t\ttouched = true\n\t\t\t}\n\t\t\tif (touched) store(key, element)\n\t\t},\n\t\tremove(value, occurrence, stamp) {\n\t\t\tconst [key, element] = read(value, occurrence)\n\t\t\tif (isAfter(stamp, element.r)) {\n\t\t\t\telement.r = stamp\n\t\t\t\tstore(key, element)\n\t\t\t}\n\t\t},\n\t\tresult: () => ({ el, changed }),\n\t}\n}\n\n/** Canonical value -> number of copies in `items`, and each item's occurrence number. */\nfunction countOccurrences(items: readonly unknown[]): {\n\tcounts: Map<string, number>\n\toccurrences: Array<{ item: unknown; canonical: string; k: number }>\n} {\n\tconst counts = new Map<string, number>()\n\tconst occurrences = items.map((item) => {\n\t\tconst canonical = canonicalKey(item)\n\t\tconst k = counts.get(canonical) ?? 0\n\t\tcounts.set(canonical, k + 1)\n\t\treturn { item, canonical, k }\n\t})\n\treturn { counts, occurrences }\n}\n\nfunction applyElementSet(state: ElementSetFieldState, write: FieldWrite): FieldApplyResult {\n\tconst writer = elementWriter(state.el)\n\tlet sh = state.sh\n\tlet clr = state.clr\n\tlet changed = false\n\tconst setShape = (arr: boolean, value?: unknown): void => {\n\t\tconst next = arr ? { s: write.s, arr } : { s: write.s, arr, v: value }\n\t\tconst later = laterShape(sh, next)\n\t\tif (later) {\n\t\t\tsh = later\n\t\t\tchanged = true\n\t\t}\n\t}\n\tconst atomic = write.a\n\tconst prev = !write.insert && Array.isArray(write.prev) ? (write.prev as unknown[]) : null\n\tconst atomicElement =\n\t\tatomic !== undefined && (atomic.type === 'append' || atomic.type === 'remove')\n\tif (atomicElement && (prev === null || !Array.isArray(write.v))) {\n\t\t// An atomic element op without the writer's array base: append adds (and\n\t\t// remove removes) the value's first occurrence.\n\t\tsetShape(true)\n\t\tif (atomic.type === 'append') writer.add(atomic.value, 0, write.s, 0)\n\t\telse if (!state.ao) writer.remove(atomic.value, 0, write.s)\n\t} else if (!Array.isArray(write.v)) {\n\t\tsetShape(false, write.v)\n\t\tconst nextClr = maxStamp(clr, write.s)\n\t\tif (nextClr !== clr) {\n\t\t\tclr = nextClr\n\t\t\tchanged = true\n\t\t}\n\t} else {\n\t\t// A multiset difference: the k-th copy of a value is added when the written\n\t\t// array holds more than k copies and the writer's base held at most k, and\n\t\t// removed in the opposite case. Duplicates are kept.\n\t\tsetShape(true)\n\t\tconst next = countOccurrences(write.v)\n\t\tconst before = prev ? countOccurrences(prev) : null\n\t\tnext.occurrences.forEach(({ item, canonical, k }, index) => {\n\t\t\tif (k >= (before?.counts.get(canonical) ?? 0)) writer.add(item, k, write.s, index)\n\t\t})\n\t\tif (before && !state.ao) {\n\t\t\tfor (const { item, canonical, k } of before.occurrences) {\n\t\t\t\tif (k >= (next.counts.get(canonical) ?? 0)) writer.remove(item, k, write.s)\n\t\t\t}\n\t\t}\n\t}\n\tconst elements = writer.result()\n\tif (!changed && !elements.changed) return { state, changed: false }\n\treturn { state: { k: 'set', ao: state.ao, sh, clr, el: elements.el }, changed: true }\n}\n\nfunction isElementPresent(element: ElementState, state: ElementSetFieldState): boolean {\n\tif (element.a === null || element.f === null) return false\n\tif (state.ao) return true\n\treturn isAfter(element.a, element.r) && isAfter(element.a, state.clr)\n}\n\nfunction materializeElementSet(state: ElementSetFieldState): unknown {\n\tif (state.sh === null) return undefined\n\tif (!state.sh.arr) return state.sh.v\n\tconst present = Object.entries(state.el).filter(([, element]) => isElementPresent(element, state))\n\tpresent.sort(([ka, a], [kb, b]) => {\n\t\tconst fa = a.f as { s: Stamp; i: number }\n\t\tconst fb = b.f as { s: Stamp; i: number }\n\t\treturn compareStamps(fa.s, fb.s) || fa.i - fb.i || (ka < kb ? -1 : ka > kb ? 1 : 0)\n\t})\n\treturn present.map(([, element]) => element.v)\n}\n\n// ---------------------------------------------------------------------------\n// Key map (objects, json)\n// ---------------------------------------------------------------------------\n\nfunction applyKeyMap(state: KeyMapFieldState, write: FieldWrite): FieldApplyResult {\n\tlet sh = state.sh\n\tlet clr = state.clr\n\tlet keys = state.keys\n\tlet changed = false\n\tconst setKey = (key: string, next: KeyState): void => {\n\t\tconst current = keys[key]\n\t\tif (current === undefined || compareStamps(next.s, current.s) > 0) {\n\t\t\tif (keys === state.keys) keys = { ...state.keys }\n\t\t\tkeys[key] = next\n\t\t\tchanged = true\n\t\t}\n\t}\n\tif (!isPlainObject(write.v)) {\n\t\tconst later = laterShape(sh, { s: write.s, obj: false, v: write.v })\n\t\tif (later) {\n\t\t\tsh = later\n\t\t\tchanged = true\n\t\t}\n\t\tconst nextClr = maxStamp(clr, write.s)\n\t\tif (nextClr !== clr) {\n\t\t\tclr = nextClr\n\t\t\tchanged = true\n\t\t}\n\t} else {\n\t\tconst later = laterShape(sh, { s: write.s, obj: true })\n\t\tif (later) {\n\t\t\tsh = later\n\t\t\tchanged = true\n\t\t}\n\t\tconst prev = !write.insert && isPlainObject(write.prev) ? write.prev : null\n\t\tfor (const [key, value] of Object.entries(write.v)) {\n\t\t\tif (prev && key in prev && canonicalKey(prev[key]) === canonicalKey(value)) continue\n\t\t\tsetKey(key, { s: write.s, del: false, v: value })\n\t\t}\n\t\tif (prev) {\n\t\t\tfor (const key of Object.keys(prev)) {\n\t\t\t\tif (!(key in write.v)) setKey(key, { s: write.s, del: true })\n\t\t\t}\n\t\t}\n\t}\n\tif (!changed) return { state, changed: false }\n\treturn { state: { k: 'map', sh, clr, keys }, changed: true }\n}\n\nfunction materializeKeyMap(state: KeyMapFieldState): unknown {\n\tif (state.sh === null) return undefined\n\tif (!state.sh.obj) return state.sh.v\n\tconst out: Record<string, unknown> = {}\n\tfor (const key of Object.keys(state.keys).sort()) {\n\t\tconst entry = state.keys[key] as KeyState\n\t\tif (entry.del || !isAfter(entry.s, state.clr)) continue\n\t\tout[key] = entry.v\n\t}\n\treturn out\n}\n\n// ---------------------------------------------------------------------------\n// Counter\n// ---------------------------------------------------------------------------\n\nfunction counterDelta(write: FieldWrite): number | null {\n\tif (write.a?.type === 'increment' && typeof write.a.value === 'number') return write.a.value\n\tif (!write.insert && !write.a && typeof write.v === 'number' && typeof write.prev === 'number') {\n\t\treturn write.v - write.prev\n\t}\n\treturn null\n}\n\ninterface Delta {\n\ts: Stamp\n\tn: number\n}\n\n/** Index of `stamp` in a stamp-sorted delta list, or -1 when already present. */\nfunction deltaIndex(deltas: readonly Delta[], stamp: Stamp): number {\n\tlet lo = 0\n\tlet hi = deltas.length\n\twhile (lo < hi) {\n\t\tconst mid = (lo + hi) >>> 1\n\t\tconst cmp = compareStamps((deltas[mid] as Delta).s, stamp)\n\t\tif (cmp === 0) return -1\n\t\tif (cmp < 0) lo = mid + 1\n\t\telse hi = mid\n\t}\n\treturn lo\n}\n\n/**\n * base + deltas, added left to right in stamp order. Floating-point addition is\n * not associative, so every replica must add the same deltas in the same order to\n * get identical bits; the cached `val` is always exactly this sum.\n */\nfunction counterValue(base: { v: unknown } | null, deltas: readonly Delta[]): unknown {\n\tif (deltas.length === 0) return base?.v\n\tlet sum = typeof base?.v === 'number' ? base.v : 0\n\tfor (const delta of deltas) sum += delta.n\n\treturn sum\n}\n\nfunction counterState(base: CounterFieldState['base'], d: Delta[]): CounterFieldState {\n\treturn { k: 'ctr', base, d, val: counterValue(base, d) }\n}\n\n/** Keep only the deltas written after `base` (a base write resets the counter). */\nfunction pruneDeltas(d: readonly Delta[], base: { s: Stamp } | null): Delta[] {\n\tif (base === null) return [...d]\n\treturn d.filter((delta) => compareStamps(delta.s, base.s) > 0)\n}\n\nfunction applyCounter(state: CounterFieldState, write: FieldWrite): FieldApplyResult {\n\tconst n = counterDelta(write)\n\tif (n !== null) {\n\t\tif (state.base !== null && compareStamps(write.s, state.base.s) < 0) {\n\t\t\treturn { state, changed: false }\n\t\t}\n\t\tconst index = deltaIndex(state.d, write.s)\n\t\tif (index === -1) return { state, changed: false }\n\t\tconst delta = { s: write.s, n }\n\t\tif (index === state.d.length) {\n\t\t\tconst val =\n\t\t\t\tstate.d.length === 0 ? counterValue(state.base, [delta]) : (state.val as number) + n\n\t\t\treturn { state: { k: 'ctr', base: state.base, d: [...state.d, delta], val }, changed: true }\n\t\t}\n\t\tconst d = [...state.d.slice(0, index), delta, ...state.d.slice(index)]\n\t\treturn { state: counterState(state.base, d), changed: true }\n\t}\n\tif (state.base !== null && compareStamps(write.s, state.base.s) <= 0) {\n\t\treturn { state, changed: false }\n\t}\n\tconst base = { s: write.s, v: write.v }\n\treturn { state: counterState(base, pruneDeltas(state.d, base)), changed: true }\n}\n\nfunction mergeDeltas(a: readonly Delta[], b: readonly Delta[]): Delta[] {\n\tconst out: Delta[] = []\n\tlet i = 0\n\tlet j = 0\n\twhile (i < a.length || j < b.length) {\n\t\tconst x = a[i]\n\t\tconst y = b[j]\n\t\tif (y === undefined || (x !== undefined && compareStamps(x.s, y.s) < 0)) {\n\t\t\tout.push(x as Delta)\n\t\t\ti++\n\t\t} else if (x === undefined || compareStamps(x.s, y.s) > 0) {\n\t\t\tout.push(y)\n\t\t\tj++\n\t\t} else {\n\t\t\tout.push(x)\n\t\t\ti++\n\t\t\tj++\n\t\t}\n\t}\n\treturn out\n}\n\n// ---------------------------------------------------------------------------\n// Extremum (max / min)\n// ---------------------------------------------------------------------------\n\nfunction betterExtremum(\n\tkind: 'max' | 'min',\n\tcurrent: { s: Stamp; v: number } | null,\n\tnext: { s: Stamp; v: number },\n): boolean {\n\tif (current === null) return true\n\tif (next.v !== current.v) return kind === 'max' ? next.v > current.v : next.v < current.v\n\treturn compareStamps(next.s, current.s) > 0\n}\n\nfunction applyExtremum(state: ExtremumFieldState, write: FieldWrite): FieldApplyResult {\n\tif (typeof write.v === 'number' && !Number.isNaN(write.v)) {\n\t\tconst next = { s: write.s, v: write.v }\n\t\tif (!betterExtremum(state.k, state.best, next)) return { state, changed: false }\n\t\treturn { state: { k: state.k, best: next, reg: state.reg }, changed: true }\n\t}\n\tif (state.reg !== null && compareStamps(write.s, state.reg.s) <= 0) {\n\t\treturn { state, changed: false }\n\t}\n\treturn { state: { k: state.k, best: state.best, reg: { s: write.s, v: write.v } }, changed: true }\n}\n\n// ---------------------------------------------------------------------------\n// Richtext\n// ---------------------------------------------------------------------------\n\nfunction decodeRichtext(value: unknown): { reset: unknown } | { update: string } {\n\tif (value === null || value === undefined) return { reset: null }\n\ttry {\n\t\tconst decoded = decodeBytesFromOpData(value)\n\t\tif (typeof decoded === 'string') return { reset: decoded }\n\t\treturn { update: bytesToBase64(decoded) }\n\t} catch {\n\t\t// Not a richtext value at all: keep it as a whole-value (reset) write so it\n\t\t// is never silently dropped.\n\t\treturn { reset: value }\n\t}\n}\n\nfunction applyRichtext(\n\tstate: RichtextFieldState,\n\twrite: FieldWrite,\n\tsubsumes: RichtextSubsumes | undefined,\n): FieldApplyResult {\n\tconst decoded = decodeRichtext(write.v)\n\tif ('reset' in decoded) {\n\t\tif (state.reset !== null && compareStamps(write.s, state.reset.s) <= 0) {\n\t\t\treturn { state, changed: false }\n\t\t}\n\t\treturn {\n\t\t\tstate: { k: 'rt', reset: { s: write.s, v: decoded.reset }, u: state.u },\n\t\t\tchanged: true,\n\t\t}\n\t}\n\tconst current = state.u[decoded.update]\n\tif (current !== undefined && compareStamps(write.s, current) <= 0) {\n\t\treturn { state, changed: false }\n\t}\n\tif (subsumes === undefined) {\n\t\treturn {\n\t\t\tstate: { k: 'rt', reset: state.reset, u: { ...state.u, [decoded.update]: write.s } },\n\t\t\tchanged: true,\n\t\t}\n\t}\n\t// Keep only maximal updates: one whose content another update contains AND whose\n\t// stamp is not later is redundant (every materialization, before or after any\n\t// reset, is unchanged without it). The maximal elements of this partial order are\n\t// a function of the update set, so pruning commutes with merging.\n\tconst incoming = base64ToBytes(decoded.update)\n\tconst u: Record<string, Stamp> = {}\n\tfor (const [update, stamp] of Object.entries(state.u)) {\n\t\tif (update === decoded.update) continue\n\t\tconst bytes = base64ToBytes(update)\n\t\tif (compareStamps(write.s, stamp) <= 0 && subsumes(incoming, bytes)) {\n\t\t\treturn { state, changed: false }\n\t\t}\n\t\tif (compareStamps(stamp, write.s) <= 0 && subsumes(bytes, incoming)) continue\n\t\tu[update] = stamp\n\t}\n\tu[decoded.update] = write.s\n\treturn { state: { k: 'rt', reset: state.reset, u }, changed: true }\n}\n\nfunction materializeRichtext(\n\tstate: RichtextFieldState,\n\tmerger: RichtextUpdateMerger | undefined,\n\tfield: string,\n): unknown {\n\tconst live = Object.entries(state.u)\n\t\t.filter(([, stamp]) => isAfter(stamp, state.reset?.s ?? null))\n\t\t.map(([update]) => update)\n\t\t.sort()\n\tif (live.length === 0) return state.reset ? state.reset.v : undefined\n\tif (live.length === 1) return { $koraBytes: live[0] }\n\tif (!merger) {\n\t\tthrow new FoldConfigurationError(\n\t\t\t`Richtext field \"${field}\" has ${live.length} concurrent Yjs updates and no richtext merger was given.`,\n\t\t\t{\n\t\t\t\tfield,\n\t\t\t\tupdates: live.length,\n\t\t\t\tfix: 'Pass { richtext: mergeYjsUpdates } (from @korajs/store) in the fold options.',\n\t\t\t},\n\t\t)\n\t}\n\treturn { $koraBytes: bytesToBase64(merger(live.map((update) => base64ToBytes(update)))) }\n}\n\n// ---------------------------------------------------------------------------\n// Dispatch\n// ---------------------------------------------------------------------------\n\n/**\n * Apply one write to a field state. Commutative, associative and idempotent per\n * kind: the resulting state depends only on the set of writes applied.\n *\n * @param subsumes - Richtext only: prunes updates another update contains\n * ({@link FoldOptions.richtextSubsumes})\n */\nexport function applyFieldWrite(\n\tstate: FieldState,\n\twrite: FieldWrite,\n\tplan: FieldPlan,\n\tsubsumes?: RichtextSubsumes,\n): FieldApplyResult {\n\tswitch (state.k) {\n\t\tcase 'reg':\n\t\t\treturn applyRegister(state, write)\n\t\tcase 'res':\n\t\t\treturn applyResolver(state, write, plan)\n\t\tcase 'set':\n\t\t\treturn applyElementSet(state, write)\n\t\tcase 'map':\n\t\t\treturn applyKeyMap(state, write)\n\t\tcase 'ctr':\n\t\t\treturn applyCounter(state, write)\n\t\tcase 'max':\n\t\tcase 'min':\n\t\t\treturn applyExtremum(state, write)\n\t\tcase 'rt':\n\t\t\treturn applyRichtext(state, write, subsumes)\n\t}\n}\n\n/**\n * The field's materialized value, or undefined when it has never been written.\n *\n * @param merger - Required only for a richtext field with several live updates\n */\nexport function materializeField(\n\tstate: FieldState,\n\tfield: string,\n\tmerger?: RichtextUpdateMerger,\n): unknown {\n\tswitch (state.k) {\n\t\tcase 'reg':\n\t\tcase 'res':\n\t\t\treturn state.e.length === 0 ? undefined : state.val\n\t\tcase 'set':\n\t\t\treturn materializeElementSet(state)\n\t\tcase 'map':\n\t\t\treturn materializeKeyMap(state)\n\t\tcase 'ctr':\n\t\t\treturn state.val\n\t\tcase 'max':\n\t\tcase 'min':\n\t\t\treturn state.best !== null ? state.best.v : state.reg?.v\n\t\tcase 'rt':\n\t\t\treturn materializeRichtext(state, merger, field)\n\t}\n}\n\n/** Newest write that affected the field (its `_field_versions` entry), or null. */\nexport function fieldStamp(state: FieldState): Stamp | null {\n\tswitch (state.k) {\n\t\tcase 'reg':\n\t\tcase 'res':\n\t\t\treturn state.e[state.e.length - 1]?.s ?? null\n\t\tcase 'set': {\n\t\t\tlet newest = maxStamp(state.sh?.s ?? null, state.clr)\n\t\t\tfor (const element of Object.values(state.el)) {\n\t\t\t\tnewest = maxStamp(maxStamp(newest, element.a), element.r)\n\t\t\t}\n\t\t\treturn newest\n\t\t}\n\t\tcase 'map': {\n\t\t\tlet newest = maxStamp(state.sh?.s ?? null, state.clr)\n\t\t\tfor (const entry of Object.values(state.keys)) newest = maxStamp(newest, entry.s)\n\t\t\treturn newest\n\t\t}\n\t\tcase 'ctr': {\n\t\t\treturn maxStamp(state.base?.s ?? null, state.d[state.d.length - 1]?.s ?? null)\n\t\t}\n\t\tcase 'max':\n\t\tcase 'min':\n\t\t\treturn maxStamp(state.best?.s ?? null, state.reg?.s ?? null)\n\t\tcase 'rt': {\n\t\t\tlet newest = state.reset?.s ?? null\n\t\t\tfor (const stamp of Object.values(state.u)) newest = maxStamp(newest, stamp)\n\t\t\treturn newest\n\t\t}\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Join (state-based merge of two replicas' states)\n// ---------------------------------------------------------------------------\n\nfunction laterOf<T extends { s: Stamp }>(a: T | null, b: T | null): T | null {\n\tif (a === null) return b\n\tif (b === null) return a\n\treturn compareStamps(a.s, b.s) >= 0 ? a : b\n}\n\nfunction joinElements(\n\ta: Record<string, ElementState>,\n\tb: Record<string, ElementState>,\n): Record<string, ElementState> {\n\tconst out: Record<string, ElementState> = { ...a }\n\tfor (const [key, y] of Object.entries(b)) {\n\t\tconst x = out[key]\n\t\tif (x === undefined) {\n\t\t\tout[key] = y\n\t\t\tcontinue\n\t\t}\n\t\tout[key] = {\n\t\t\tv: x.v,\n\t\t\tn: x.n,\n\t\t\ta: maxStamp(x.a, y.a),\n\t\t\tf: y.f !== null && firstAddBefore(x.f, y.f) ? y.f : x.f,\n\t\t\tr: maxStamp(x.r, y.r),\n\t\t}\n\t}\n\treturn out\n}\n\n/**\n * Join two states of the same field (the least upper bound of the two). For every\n * kind, `join(fold(A), fold(B)) = fold(A ∪ B)`.\n */\nexport function joinFieldStates(a: FieldState, b: FieldState, plan: FieldPlan): FieldState {\n\tif (a.k !== b.k) return a\n\tswitch (a.k) {\n\t\tcase 'reg': {\n\t\t\tconst entries = pruneChain(mergeLogs(a.e, (b as RegisterFieldState).e))\n\t\t\treturn { k: 'reg', e: entries, val: chainFold(entries) }\n\t\t}\n\t\tcase 'res': {\n\t\t\tconst entries = pruneResolverLog(mergeLogs(a.e, (b as ResolverFieldState).e))\n\t\t\treturn resolverState(entries, resolverFold(plan, entries))\n\t\t}\n\t\tcase 'set': {\n\t\t\tconst other = b as ElementSetFieldState\n\t\t\treturn {\n\t\t\t\tk: 'set',\n\t\t\t\tao: a.ao,\n\t\t\t\tsh: laterOf(a.sh, other.sh),\n\t\t\t\tclr: maxStamp(a.clr, other.clr),\n\t\t\t\tel: joinElements(a.el, other.el),\n\t\t\t}\n\t\t}\n\t\tcase 'map': {\n\t\t\tconst other = b as KeyMapFieldState\n\t\t\tconst keys: Record<string, KeyState> = { ...a.keys }\n\t\t\tfor (const [key, entry] of Object.entries(other.keys)) {\n\t\t\t\tconst current = keys[key]\n\t\t\t\tif (current === undefined || compareStamps(entry.s, current.s) > 0) keys[key] = entry\n\t\t\t}\n\t\t\treturn { k: 'map', sh: laterOf(a.sh, other.sh), clr: maxStamp(a.clr, other.clr), keys }\n\t\t}\n\t\tcase 'ctr': {\n\t\t\tconst other = b as CounterFieldState\n\t\t\tconst base = laterOf(a.base, other.base)\n\t\t\treturn counterState(base, pruneDeltas(mergeDeltas(a.d, other.d), base))\n\t\t}\n\t\tcase 'max':\n\t\tcase 'min': {\n\t\t\tconst other = b as ExtremumFieldState\n\t\t\tlet best = a.best\n\t\t\tif (other.best !== null && betterExtremum(a.k, best, other.best)) best = other.best\n\t\t\treturn { k: a.k, best, reg: laterOf(a.reg, other.reg) }\n\t\t}\n\t\tcase 'rt': {\n\t\t\tconst other = b as RichtextFieldState\n\t\t\tconst u: Record<string, Stamp> = { ...a.u }\n\t\t\tfor (const [update, stamp] of Object.entries(other.u)) {\n\t\t\t\tu[update] = maxStamp(u[update] ?? null, stamp) as Stamp\n\t\t\t}\n\t\t\treturn { k: 'rt', reset: laterOf(a.reset, other.reset), u }\n\t\t}\n\t}\n}\n","import type { MergeTrace } from '../events/events'\nimport type { OperationTransform } from '../migration/operation-transform'\nimport type { AtomicOp, HLCTimestamp, Operation } from '../types'\n\n/**\n * Version of the serialized fold-state format ({@link FoldState}). Bumped on any\n * change to the on-disk shape. A reader that sees a different version must refuse\n * the state and re-fold the record from its operation log.\n */\nexport const FOLD_STATE_VERSION = 2\n\n/**\n * A write's position in the record's total order: the operation's HLC timestamp\n * (serialized, so it compares as a plain string exactly like\n * `HybridLogicalClock.compare`), then the operation id as a tie-breaker. Two\n * distinct operations never share a stamp, even when a buggy or forged node reuses\n * an HLC, so every \"latest wins\" comparison in the fold is a strict total order.\n *\n * A write to a `merge('server-authoritative')` field by an authoritative node\n * ({@link FoldOptions.authoritativeNodeIds}) carries class `c: 1`, which orders\n * before the HLC: the order is lexicographic on (class, HLC, op id).\n */\nexport interface Stamp {\n\t/** `HybridLogicalClock.serialize(timestamp)` of the writing operation (or field version). */\n\tt: string\n\t/** Id of the writing operation. */\n\to: string\n\t/** Authority class (1 = authoritative write). Absent means 0. */\n\tc?: 1\n}\n\n/**\n * One write in a field's embedded log ({@link RegisterFieldState},\n * {@link ResolverFieldState}).\n */\nexport interface FieldLogEntry {\n\t/** Position of the write in the total order. */\n\ts: Stamp\n\t/** The written value (for atomic writes, the author's resolved value). */\n\tv: unknown\n\t/** Atomic intent, when the write was `op.increment()`, `op.max()`, ... */\n\ta?: AtomicOp\n\t/** For resolver fields: the writer's base (`previousData[field]`), null for inserts. */\n\tb?: unknown\n\t/**\n\t * Resolver fields only: a snapshot entry ({@link createSnapshotState}). It resets\n\t * the value without calling the resolver, and every older entry is pruned.\n\t */\n\tz?: 1\n}\n\n/**\n * Scalar fields (string, number, boolean, enum, timestamp, blob, secret, and any\n * field declared `merge('lww')` or `merge('server-authoritative')`): a last-write-\n * wins register generalized to the atomic-op chain.\n *\n * `e` holds the writes since (and including) the newest plain write, sorted by\n * stamp. A plain write resets the field unconditionally, so everything older is\n * irrelevant and is pruned. With no atomic writes `e` has exactly one entry: an\n * LWW register. With atomic writes `e` is the chain the value is folded from (a\n * same-type atomic chain composes; any other write takes its resolved value).\n */\nexport interface RegisterFieldState {\n\tk: 'reg'\n\te: FieldLogEntry[]\n\t/** Cached `chainFold(e)`. Always equal to it; stored so materialization is O(1). */\n\tval: unknown\n}\n\n/** One element occurrence of an {@link ElementSetFieldState}. */\nexport interface ElementState {\n\t/** The element value (canonical JSON parsed back, so key order is normalized). */\n\tv: unknown\n\t/** Occurrence number: this is the n-th copy (from 0) of the value in the array. */\n\tn: number\n\t/** Newest add. */\n\ta: Stamp | null\n\t/** Oldest add plus the element's index in that write (its position in the array). */\n\tf: { s: Stamp; i: number } | null\n\t/** Newest removal. */\n\tr: Stamp | null\n}\n\n/**\n * Array fields: an LWW element set. Each element (identified by its canonical JSON)\n * carries its newest add and newest removal; it is present iff its newest add is\n * later than its newest removal and later than the newest write that replaced the\n * whole array with a non-array (`clr`). Order is by first add.\n */\nexport interface ElementSetFieldState {\n\tk: 'set'\n\t/** Append-only (`merge('append-only')`): removals are ignored. */\n\tao: boolean\n\t/** Whole-value shape register: is the field an array, or a non-array value (e.g. null)? */\n\tsh: { s: Stamp; arr: boolean; v?: unknown } | null\n\t/** Newest write that set the field to a non-array value: elements added before it are cleared. */\n\tclr: Stamp | null\n\t/** Elements keyed by canonical JSON. */\n\tel: Record<string, ElementState>\n}\n\n/** One top-level key of a {@link KeyMapFieldState}. */\nexport interface KeyState {\n\ts: Stamp\n\t/** true = removal marker. */\n\tdel: boolean\n\tv?: unknown\n}\n\n/**\n * Object and json fields: per-top-level-key LWW registers with removal markers.\n * Nested values are whole-value LWW per top-level key. A write that replaces the\n * whole value with a non-object (null, a scalar, a json array) is a shape write;\n * keys written before the newest such write are cleared.\n */\nexport interface KeyMapFieldState {\n\tk: 'map'\n\tsh: { s: Stamp; obj: boolean; v?: unknown } | null\n\tclr: Stamp | null\n\tkeys: Record<string, KeyState>\n}\n\n/**\n * `merge('counter')` fields: a base register (inserts and non-numeric writes) plus\n * the deltas written after it. Value = base + sum of deltas in stamp order.\n */\nexport interface CounterFieldState {\n\tk: 'ctr'\n\tbase: { s: Stamp; v: unknown } | null\n\t/** Deltas written after `base`, sorted by stamp (older ones are pruned). */\n\td: Array<{ s: Stamp; n: number }>\n\t/** Cached base + deltas, summed left to right in stamp order. */\n\tval: unknown\n}\n\n/** `merge('max')` / `merge('min')` fields: the extremum of every numeric write. */\nexport interface ExtremumFieldState {\n\tk: 'max' | 'min'\n\tbest: { s: Stamp; v: number } | null\n\t/** LWW register over non-numeric writes, used only while no numeric write exists. */\n\treg: { s: Stamp; v: unknown } | null\n}\n\n/**\n * Fields with a custom resolver (tier 3): the full write log in stamp order and\n * the value folded through the resolver (`local` = the merged value so far).\n */\nexport interface ResolverFieldState {\n\tk: 'res'\n\te: FieldLogEntry[]\n\tval: unknown\n\t/** Message of the newest resolver exception (the fold fell back to LWW there), if any. */\n\terr?: string\n}\n\n/**\n * Richtext fields: a set of opaque Yjs updates (base64) plus a reset register for\n * plain-string (whole-value) writes. Updates written before the newest reset are\n * hidden.\n */\nexport interface RichtextFieldState {\n\tk: 'rt'\n\treset: { s: Stamp; v: unknown } | null\n\t/** base64 Yjs update -> newest stamp that wrote it. */\n\tu: Record<string, Stamp>\n}\n\n/** Per-field merge state. Every variant is a state-based CRDT (join-semilattice). */\nexport type FieldState =\n\t| RegisterFieldState\n\t| ElementSetFieldState\n\t| KeyMapFieldState\n\t| CounterFieldState\n\t| ExtremumFieldState\n\t| ResolverFieldState\n\t| RichtextFieldState\n\n/** The kind tag of a {@link FieldState}. */\nexport type FoldFieldKind = FieldState['k']\n\n/**\n * The merge state of one record: the snapshot every replica (client store, server\n * stores, backup restore, compaction) persists. It is a pure function of the set of\n * operations merged into it, so two replicas holding the same operations hold an\n * identical state, whatever order they arrived in.\n *\n * Serialized with {@link serializeFoldState}; see that function for the on-disk\n * format.\n */\nexport interface FoldState {\n\t/** Format version, {@link FOLD_STATE_VERSION}. */\n\tv: number\n\t/** Collection of the record. */\n\tc: string\n\t/** Record id. */\n\tr: string\n\t/** Oldest insert (the record's creation). null until an insert is merged. */\n\tcr: Stamp | null\n\t/** Newest insert or update (any write keeps the record alive). */\n\tw: Stamp | null\n\t/** Newest delete (the tombstone register). */\n\td: Stamp | null\n\t/** Newest operation of any type. */\n\tu: Stamp | null\n\t/** Per-field states. */\n\tf: Record<string, FieldState>\n}\n\n/** Merges the opaque Yjs updates of a richtext field into one update. */\nexport type RichtextUpdateMerger = (updates: Uint8Array[]) => Uint8Array\n\n/** True when update `a`'s content is contained in update `b`'s (a adds nothing to b). */\nexport type RichtextSubsumes = (a: Uint8Array, b: Uint8Array) => boolean\n\n/** Which merge traces {@link mergeOp} emits. */\nexport type FoldTraceMode = 'conflicts' | 'all' | 'none'\n\n/** Options shared by the fold entry points. */\nexport interface FoldOptions {\n\t/**\n\t * Operations to leave out: the server terminally rejected them (or they are\n\t * otherwise known never to have been stored). Ids, or a predicate.\n\t */\n\texclude?: ReadonlySet<string> | ((op: Operation) => boolean)\n\t/**\n\t * Merges richtext Yjs updates. Required to materialize a richtext field with\n\t * more than one live update (pass `mergeYjsUpdates` from `@korajs/store`).\n\t * Core has no Yjs dependency, so it cannot supply one itself.\n\t */\n\trichtext?: RichtextUpdateMerger\n\t/**\n\t * Optional richtext space bound: when given, an update whose content another\n\t * update of the field contains, and whose stamp is not later, is dropped (it can\n\t * never change a materialization). Devices persist a full Yjs snapshot per edit,\n\t * so without it a field's state keeps every snapshot. Materializations are the\n\t * same with or without it; every replica of one database must use the same setting\n\t * for its serialized states to be byte-identical.\n\t */\n\trichtextSubsumes?: RichtextSubsumes\n\t/** Which traces to emit. Default `'conflicts'`. */\n\ttraces?: FoldTraceMode\n\t/**\n\t * Additional node ids whose writes are authoritative for\n\t * `merge('server-authoritative')` fields: legacy (randomly generated) server node\n\t * ids the server keeps advertising at the handshake. Every node id in the reserved\n\t * `kora:server:` namespace is authoritative without being listed. Authoritative\n\t * writes beat every non-authoritative write of such a field regardless of HLC;\n\t * within a class the later write wins. Every replica must fold with the same set.\n\t */\n\tauthoritativeNodeIds?: ReadonlySet<string>\n\t/**\n\t * Schema transforms applied at fold time (RT-84): an operation authored under another\n\t * schema version is merged as `operationSchemaView(op, schema.version, transforms)`\n\t * reads it. Stored operations are never rewritten. Transforms must be pure and\n\t * deterministic, and every replica of a deployment must fold with the same ones (they\n\t * are part of the fold plan fingerprint). Without transforms an operation folds as\n\t * written.\n\t */\n\ttransforms?: readonly OperationTransform[]\n}\n\n/**\n * A per-field merge decision made by {@link mergeOp}. It carries every\n * {@link MergeTrace} field except `operationA`: the fold state keeps only the id of\n * the operation that produced the prior value (`priorOperationId`), so the caller,\n * which owns the operation log, turns it into a `MergeTrace` with\n * {@link toMergeTrace}.\n */\nexport interface FoldTrace extends Omit<MergeTrace, 'operationA' | 'operationB'> {\n\t/** The operation being merged (`MergeTrace.operationB`). */\n\toperation: Operation\n\t/** Id of the operation that last wrote the field before this merge, or null. */\n\tpriorOperationId: string | null\n\t/**\n\t * True when the incoming write was concurrent with the field's prior value (the\n\t * writer's base differs from it, or the write lost to a newer one).\n\t */\n\tconflict: boolean\n\t/** Set when a custom resolver threw: the fold fell back to last-write-wins. */\n\terror?: string\n}\n\n/** The result of merging one operation. */\nexport interface MergeOpResult {\n\tstate: FoldState\n\ttraces: FoldTrace[]\n\t/** False when the operation changed nothing (a duplicate, an excluded op, a no-op write). */\n\tchanged: boolean\n}\n\n/** The result of folding a set of operations from scratch. */\nexport interface FoldRecordResult {\n\t/** null when no (non-excluded) operation was given. */\n\tstate: FoldState | null\n\ttraces: FoldTrace[]\n}\n\n/** Per-field versions of a live record, the fold's equivalent of `_field_versions`. */\nexport interface FoldFieldVersions {\n\t/** Field name -> HLC of the newest write that affected the field. */\n\tfields: Record<string, HLCTimestamp>\n\t/** HLC of the record's creation (oldest insert). */\n\tcreated: HLCTimestamp\n\t/** HLC of the newest operation of any type. */\n\tlatest: HLCTimestamp\n}\n","import { canonicalize } from '../operations/content-hash'\nimport { FoldStateError } from './errors'\nimport { FOLD_STATE_VERSION, type FieldState, type FoldState } from './types'\n\nconst FIELD_KINDS = new Set(['reg', 'set', 'map', 'ctr', 'max', 'min', 'res', 'rt'])\n\n/**\n * Serialize a record's fold state for storage (the client `_fold_state` column,\n * the server stores' fold-record rows, backups, compaction snapshots).\n *\n * The output is canonical JSON (sorted keys), so two replicas holding the same\n * operations write byte-identical strings. Format, version 2 (version 1, Stage A,\n * keyed array elements by value only and is refused: such a state is re-folded):\n *\n * ```\n * {\n * \"v\": 2, // format version\n * \"c\": \"todos\", \"r\": \"<id>\", // collection, record id\n * \"cr\": Stamp|null, // oldest insert (creation)\n * \"w\": Stamp|null, // newest insert/update\n * \"d\": Stamp|null, // newest delete (tombstone register)\n * \"u\": Stamp|null, // newest operation of any type\n * \"f\": { \"<field>\": FieldState }\n * }\n * Stamp = { \"t\": \"<HLC serialized>\", \"o\": \"<op id>\", \"c\"?: 1 } // c: authority class\n * FieldState =\n * { \"k\":\"reg\", \"e\":[{ \"s\":Stamp, \"v\":value, \"a\"?:AtomicOp }], \"val\":value }\n * { \"k\":\"set\", \"ao\":bool, \"sh\":{ \"s\":Stamp, \"arr\":bool, \"v\"?:value }|null, \"clr\":Stamp|null,\n * \"el\":{ \"<canonical JSON>#<k>\":{ \"v\":value, \"n\":k, \"a\":Stamp|null, \"f\":{ \"s\":Stamp, \"i\":n }|null, \"r\":Stamp|null } } }\n * { \"k\":\"map\", \"sh\":{ \"s\":Stamp, \"obj\":bool, \"v\"?:value }|null, \"clr\":Stamp|null,\n * \"keys\":{ \"<key>\":{ \"s\":Stamp, \"del\":bool, \"v\"?:value } } }\n * { \"k\":\"ctr\", \"base\":{ \"s\":Stamp, \"v\":value }|null, \"d\":[{ \"s\":Stamp, \"n\":number }], \"val\":value }\n * { \"k\":\"max\"|\"min\", \"best\":{ \"s\":Stamp, \"v\":number }|null, \"reg\":{ \"s\":Stamp, \"v\":value }|null }\n * { \"k\":\"res\", \"e\":[{ \"s\":Stamp, \"v\":value, \"b\"?:value, \"z\"?:1 }], \"val\":value, \"err\"?:string }\n * { \"k\":\"rt\", \"reset\":{ \"s\":Stamp, \"v\":value }|null, \"u\":{ \"<base64 Yjs update>\":Stamp } }\n * ```\n *\n * Values are JSON-safe (binary as `{ \"$koraBytes\": base64 }`). The state is\n * self-contained: kinds that need history embed exactly the history they need\n * ('reg' keeps the atomic chain since the newest plain write, 'res' its whole\n * write log, 'ctr' the deltas since its base), so a compactor may treat the state\n * as the record's snapshot and drop operations it covers.\n *\n * @param state - The fold state\n * @returns Canonical JSON\n */\nexport function serializeFoldState(state: FoldState): string {\n\treturn canonicalize(state)\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/**\n * Parse a stored fold state. Throws {@link FoldStateError} for an unknown format\n * version or a malformed state; the caller then re-folds the record from its log.\n *\n * @param json - Output of {@link serializeFoldState}\n */\nexport function deserializeFoldState(json: string): FoldState {\n\tlet parsed: unknown\n\ttry {\n\t\tparsed = JSON.parse(json)\n\t} catch (error) {\n\t\tthrow new FoldStateError('Stored fold state is not valid JSON.', {\n\t\t\treason: error instanceof Error ? error.message : String(error),\n\t\t})\n\t}\n\tif (!isRecord(parsed)) throw new FoldStateError('Stored fold state is not an object.')\n\tif (parsed.v !== FOLD_STATE_VERSION) {\n\t\tthrow new FoldStateError(\n\t\t\t`Stored fold state has format version ${String(parsed.v)}; this build reads version ${FOLD_STATE_VERSION}.`,\n\t\t\t{ found: parsed.v, expected: FOLD_STATE_VERSION },\n\t\t)\n\t}\n\tif (typeof parsed.c !== 'string' || typeof parsed.r !== 'string' || !isRecord(parsed.f)) {\n\t\tthrow new FoldStateError('Stored fold state is missing its collection, record id or fields.')\n\t}\n\tfor (const [field, state] of Object.entries(parsed.f)) {\n\t\tif (!isRecord(state) || typeof state.k !== 'string' || !FIELD_KINDS.has(state.k)) {\n\t\t\tthrow new FoldStateError(`Stored fold state has an unknown kind for field \"${field}\".`, {\n\t\t\t\tfield,\n\t\t\t})\n\t\t}\n\t}\n\tconst state = parsed as unknown as FoldState\n\t// JSON has no undefined: a register's cached value of null round-trips as null,\n\t// which is what the in-memory state holds too (undefined never enters a state).\n\tfor (const fieldState of Object.values(state.f) as FieldState[]) {\n\t\tif ((fieldState.k === 'reg' || fieldState.k === 'res') && fieldState.e.length === 0) {\n\t\t\tfieldState.val = undefined\n\t\t}\n\t\tif (fieldState.k === 'ctr' && fieldState.d.length === 0 && fieldState.base === null) {\n\t\t\tfieldState.val = undefined\n\t\t}\n\t}\n\treturn state\n}\n","/**\n * One deterministic fold (W7, design D3a revised).\n *\n * A record's state is a per-field CRDT. `mergeOp(state, op)` is a join, so the\n * result depends only on the SET of operations merged: not their order, not\n * duplicates, not batching, and not whether the replica is a client, a server\n * store, a restored backup or a compaction snapshot.\n *\n * Total order: every \"later wins\" below compares stamps = (HLC, op id).\n *\n * Writes. An insert writes every field it carries. An update writes a field only\n * when its value differs from its own previousData (or it carries an atomic op);\n * restating a field unchanged is not a write.\n *\n * Per kind (see `planField` for how the schema selects one):\n * - Scalars ('reg'): LWW register. With atomic ops, the chain since the newest\n * plain write is kept: a same-type atomic chain composes (increments sum, max of\n * maxes), any other write takes its resolved value.\n * - Arrays ('set'): occurrence-indexed LWW element multiset. Element identity =\n * (canonical JSON with sorted keys, occurrence k): the k-th copy of a value.\n * adds = data − previousData and removes = previousData − data as multisets\n * (an insert only adds). Present iff newest add > newest remove and > newest\n * non-array write. Order: first add (stamp, then index in that write). Atomic\n * append / remove are the same multiset difference against the writer's base\n * (without an array base: the value's first occurrence). `merge('append-only')`\n * ignores removals.\n * - `merge('server-authoritative')` ('reg'): a register whose writes by server\n * nodes carry class 1 and beat every class-0 write regardless of HLC. Order:\n * (class, HLC, op id). A server node is any node id in the reserved\n * `kora:server:` namespace, plus `FoldOptions.authoritativeNodeIds` (legacy\n * random server node ids the server keeps advertising).\n * - Objects / json ('map'): per-top-level-key LWW with removal markers; nested\n * values are whole-value LWW per key. A non-object write (null, scalar, json\n * array) replaces the whole value and clears keys written before it.\n * - `merge('counter')` ('ctr'): base (insert / non-numeric write) + every delta\n * (data − previousData, or the increment) written after it.\n * - `merge('max' | 'min')`: the extremum of every numeric write.\n * - Custom resolvers ('res', tier 3): the field's whole write log folded in stamp\n * order, `value = resolve(local = merged value so far, remote = write, base =\n * write's previousData)`; the first write initializes. A throwing resolver falls\n * back to the write's value (reported on the trace and the state).\n * - Richtext ('rt'): a set of opaque Yjs updates merged by the caller-supplied\n * merger; a plain-string write is a reset that hides updates written before it.\n * With `richtextSubsumes`, only maximal updates are kept (an update another one\n * contains, with a stamp not later, is dropped): same materializations, bounded state.\n * - Record: exists once an insert is merged; live iff newest insert/update >\n * newest delete. Insert onto an existing row merges per field.\n *\n * Semantic changes versus beta.12/13 (all deliberate; each was non-convergent):\n * 1. Arrays are multisets of elements merged per occurrence (pairwise\n * add-wins-set gone): duplicates are kept; order is first-add order, not the\n * writer's order; a removal beats an unchanged copy; for the same occurrence the\n * later edit wins; two writers that add the same value from the same base add\n * the same occurrence (one copy, not two); objects inside arrays compare by\n * canonical JSON (key order ignored).\n * 2. Objects merge per top-level key only; nested objects / arrays inside a key\n * are whole-value LWW (the pairwise engine recursed and set-merged them).\n * 3. An update that restates a field unchanged no longer wins LWW for it (applies\n * to scalars too, not only arrays: NEW-MERGE-1's rule made uniform).\n * 4. Custom resolvers see `local` = the merged value so far, in HLC order, rather\n * than a device's local row; they are called once per write, not once per\n * concurrent pair. Their output need not be commutative.\n * 5. Insert onto an existing row (or after a delete) merges per field; it no\n * longer resets fields the insert does not carry (server replay used to).\n * 6. `merge('server-authoritative')`: a write by an authoritative node (the\n * server, `authoritativeNodeIds` from the handshake) beats any client write of\n * that field, even a later one; client writes among themselves, and server\n * writes among themselves, are LWW. With no authoritative node known it is LWW.\n * 7. `merge('counter' | 'max' | 'min' | 'append-only')` are folded over every\n * write (they were pairwise formulas against one base).\n * 8. Atomic `append` / `remove` on arrays are multiset differences against the\n * writer's base: appending a value already present adds a copy; `remove`\n * removes every copy the writer saw.\n * 9. An update to a record with no merged insert does not materialize a row (the\n * client already behaved this way; the server replay materialized it).\n * 10. A server scope-entry insert that carries the record's fold state\n * (`op.foldState`) is joined into the local state instead of merged as one\n * insert, so richtext, counters, resolvers and element sets enter with their\n * merge state (RT-29). Without it (older servers) `fieldVersions` still apply.\n * 11. Schema transforms run at fold time (RT-84): an operation of another schema\n * version is merged as its `operationSchemaView` (`FoldOptions.transforms`), and\n * is stored and synced exactly as written. A transform never rewrites a stored\n * operation, so its id stays the hash of its content on every replica.\n * Delete vs update is unchanged: the later of the newest delete and the newest\n * write decides; a revived record shows every field's merged value.\n */\nimport { operationSchemaView } from '../migration/operation-view'\nimport type { CollectionDefinition, HLCTimestamp, Operation, SchemaDefinition } from '../types'\nimport { isAuthoritativeNodeId } from './authority'\nimport { FoldConfigurationError, FoldStateError } from './errors'\nimport { type FieldPlan, planField } from './field-kind'\nimport {\n\ttype FieldWrite,\n\tapplyFieldWrite,\n\temptyField,\n\tfieldStamp,\n\tjoinFieldStates,\n\tmaterializeField,\n} from './field-states'\nimport { deserializeFoldState, serializeFoldState } from './serialize'\nimport { compareStamps, isAfter, maxStamp, minStamp, stampOf, stampTimestamp } from './stamp'\nimport {\n\tFOLD_STATE_VERSION,\n\ttype FieldState,\n\ttype FoldFieldVersions,\n\ttype FoldOptions,\n\ttype FoldRecordResult,\n\ttype FoldState,\n\ttype FoldTrace,\n\ttype MergeOpResult,\n\ttype Stamp,\n} from './types'\nimport { canonicalKey, normalizeValue } from './values'\n\n/** `FoldTrace.field` of a record-level (delete vs write) decision. */\nexport const FOLD_RECORD_TRACE_FIELD = '*'\n\n/** Written into traces in place of a secret field's value. */\nconst SECRET_REDACTED = '[secret]'\n\n/**\n * An empty fold state for one record: no operation merged yet.\n *\n * @param collection - The record's collection\n * @param recordId - The record's id\n */\nexport function createFoldState(collection: string, recordId: string): FoldState {\n\treturn {\n\t\tv: FOLD_STATE_VERSION,\n\t\tc: collection,\n\t\tr: recordId,\n\t\tcr: null,\n\t\tw: null,\n\t\td: null,\n\t\tu: null,\n\t\tf: {},\n\t}\n}\n\nfunction isExcluded(op: Operation, exclude: FoldOptions['exclude']): boolean {\n\tif (exclude === undefined) return false\n\treturn typeof exclude === 'function' ? exclude(op) : exclude.has(op.id)\n}\n\nfunction samePlanKind(state: FieldState, plan: FieldPlan): boolean {\n\tif (state.k !== plan.kind) return false\n\treturn state.k !== 'set' || state.ao === plan.appendOnly\n}\n\nfunction fieldPlanFor(\n\tcollection: CollectionDefinition | undefined,\n\tfield: string,\n\texisting: FieldState | undefined,\n\tstate: FoldState,\n): FieldPlan {\n\tconst plan = planField(collection, field)\n\tif (existing !== undefined && !samePlanKind(existing, plan)) {\n\t\tthrow new FoldStateError(\n\t\t\t`Field \"${field}\" of ${state.c}/${state.r} is stored as fold kind \"${existing.k}\" but the schema now folds it as \"${plan.kind}\".`,\n\t\t\t{ collection: state.c, recordId: state.r, field, stored: existing.k, expected: plan.kind },\n\t\t)\n\t}\n\treturn plan\n}\n\n/**\n * The stamp of one field of an insert. A server-synthesized scope-entry insert\n * (RT-27) restates the record's current values, each produced at its own version\n * (`op.fieldVersions`): the field is stamped at exactly that version (tie-broken by\n * the entry's id), so it lands where its original writer did, never later. Raising\n * it to the entry's own timestamp (which a server of the unreleased Phase 1 build\n * (33bca46) sets to the record's\n * newest write) would let the restated value beat a device's concurrent edit that\n * is newer than the field's real version (RT-67).\n *\n * A field the entry carries without a version (a column no write ever produced,\n * e.g. a later schema default) is as old as the record: it is stamped at the\n * oldest version the entry knows, the earlier of its own timestamp and its oldest\n * field version. An entry with no versions at all (a custom server store that\n * provides neither per-field versions nor a fold state) can only be stamped at its\n * own timestamp; built-in stores always send versions or a fold state.\n */\nfunction fieldWriteStamp(op: Operation, field: string, opStamp: Stamp): Stamp {\n\tif (op.type !== 'insert' || op.fieldVersions === undefined) return opStamp\n\tconst version: HLCTimestamp | undefined = op.fieldVersions[field]\n\tif (version !== undefined) return stampOf(version, op.id)\n\tlet oldest = opStamp\n\tfor (const candidate of Object.values(op.fieldVersions)) {\n\t\tconst stamp = stampOf(candidate, op.id)\n\t\tif (compareStamps(stamp, oldest) < 0) oldest = stamp\n\t}\n\treturn oldest\n}\n\n/**\n * A write to a `merge('server-authoritative')` field by an authoritative node (a\n * `kora:server:` node, or one of `FoldOptions.authoritativeNodeIds`) gets authority\n * class 1, which orders before the HLC (see {@link Stamp}).\n */\nfunction classify(\n\tstamp: Stamp,\n\top: Operation,\n\tfield: string,\n\tplan: FieldPlan,\n\toptions: FoldOptions,\n): Stamp {\n\tif (!plan.authoritative) return stamp\n\t// A scope entry restates the value of the write that produced it: that write's\n\t// node (the version's node id) decides the class, not the entry's system node.\n\tconst author = op.type === 'insert' ? (op.fieldVersions?.[field]?.nodeId ?? op.nodeId) : op.nodeId\n\tif (isAuthoritativeNodeId(author, options.authoritativeNodeIds)) {\n\t\treturn { ...stamp, c: 1 }\n\t}\n\treturn stamp\n}\n\n/**\n * Merge a server scope-entry operation that carries the record's serialized fold\n * state (`op.foldState`): a state-based join. Returns null when the carried state\n * cannot be read (another format version) or holds a field of another fold kind\n * than this replica's schema: the caller then merges the operation's data like any\n * insert (each field at its `fieldVersions` entry), as for an older server.\n */\nfunction mergeCarriedState(\n\tstate: FoldState,\n\top: Operation,\n\tschema: SchemaDefinition,\n\toptions: FoldOptions,\n): MergeOpResult | null {\n\tlet carried: FoldState\n\ttry {\n\t\tcarried = deserializeFoldState(op.foldState as string)\n\t} catch (error) {\n\t\tif (error instanceof FoldStateError) return null\n\t\tthrow error\n\t}\n\tif (carried.c !== state.c || carried.r !== state.r) {\n\t\tthrow new FoldStateError(\n\t\t\t`Operation ${op.id} carries the fold state of ${carried.c}/${carried.r} but targets ${state.c}/${state.r}.`,\n\t\t\t{ operationId: op.id, collection: op.collection, recordId: op.recordId },\n\t\t)\n\t}\n\tlet joined: FoldState\n\ttry {\n\t\tjoined = joinStates(state, carried, schema)\n\t} catch (error) {\n\t\t// The server folded a field under another plan (its schema differs from this\n\t\t// replica's, e.g. mid-rollout of a merge-kind change): its state cannot be\n\t\t// joined field by field, so the entry merges by its data and versions instead,\n\t\t// like one from an older server (RT-63). A function of the op and the schema\n\t\t// only, so every replica decides the same.\n\t\tif (error instanceof FoldStateError) return null\n\t\tthrow error\n\t}\n\tconst changed = serializeFoldState(joined) !== serializeFoldState(state)\n\tconst traces: FoldTrace[] = []\n\tif ((options.traces ?? 'conflicts') !== 'none') {\n\t\t// One trace per field where this replica's value and the server's differed:\n\t\t// the join's per-field decision, for DevTools (RT-29).\n\t\tconst collection = schema.collections[state.c]\n\t\tfor (const [field, incomingState] of Object.entries(carried.f)) {\n\t\t\tconst mine = state.f[field]\n\t\t\tif (mine === undefined) continue\n\t\t\tconst prior = safeMaterializeField(mine, field, options)\n\t\t\tconst incoming = safeMaterializeField(incomingState, field, options)\n\t\t\tif (canonicalKey(prior) === canonicalKey(incoming)) continue\n\t\t\tconst plan = planField(collection, field)\n\t\t\tconst output = safeMaterializeField(joined.f[field], field, options)\n\t\t\tconst redact = (value: unknown): unknown => (plan.secret ? SECRET_REDACTED : value)\n\t\t\ttraces.push({\n\t\t\t\tfield,\n\t\t\t\tstrategy: `scope-entry-${plan.strategy}`,\n\t\t\t\tinputA: redact(prior),\n\t\t\t\tinputB: redact(incoming),\n\t\t\t\tbase: null,\n\t\t\t\toutput: redact(output),\n\t\t\t\ttier: plan.tier,\n\t\t\t\tconstraintViolated: null,\n\t\t\t\tduration: 0,\n\t\t\t\toperation: plan.secret ? redactOperation(op, field) : op,\n\t\t\t\tpriorOperationId: fieldStamp(mine)?.o ?? null,\n\t\t\t\tconflict: true,\n\t\t\t})\n\t\t}\n\t}\n\treturn { state: changed ? joined : state, traces, changed }\n}\n\n/**\n * Build the field write an operation makes, or null when it makes none: the field\n * is absent/undefined, or an update restated it unchanged (its value equals its\n * own `previousData`). An unchanged restatement is not a write: it never overrides\n * a concurrent change, never re-adds a removed element and never resets an atomic\n * chain.\n */\nfunction buildWrite(op: Operation, field: string, raw: unknown, stamp: Stamp): FieldWrite | null {\n\tif (raw === undefined) return null\n\tconst insert = op.type === 'insert'\n\tconst v = normalizeValue(raw)\n\tconst atomic = op.atomicOps?.[field]\n\tconst a = atomic ? { type: atomic.type, value: normalizeValue(atomic.value) } : undefined\n\tconst prevRaw = insert ? undefined : op.previousData?.[field]\n\tconst hasPrev =\n\t\t!insert && op.previousData !== null && field in op.previousData && prevRaw !== undefined\n\tconst prev = hasPrev ? normalizeValue(prevRaw) : undefined\n\tif (!insert && a === undefined && hasPrev && canonicalKey(prev) === canonicalKey(v)) return null\n\treturn a ? { s: stamp, insert, v, prev, hasPrev, a } : { s: stamp, insert, v, prev, hasPrev }\n}\n\nfunction safeMaterializeField(\n\tstate: FieldState | undefined,\n\tfield: string,\n\toptions: FoldOptions,\n): unknown {\n\tif (state === undefined) return undefined\n\ttry {\n\t\treturn materializeField(state, field, options.richtext)\n\t} catch (error) {\n\t\tif (error instanceof FoldConfigurationError) return undefined\n\t\tthrow error\n\t}\n}\n\nfunction redactOperation(op: Operation, field: string): Operation {\n\tconst redact = (data: Record<string, unknown> | null): Record<string, unknown> | null =>\n\t\tdata !== null && field in data ? { ...data, [field]: SECRET_REDACTED } : data\n\treturn { ...op, data: redact(op.data), previousData: redact(op.previousData) }\n}\n\nfunction fieldTrace(\n\top: Operation,\n\tfield: string,\n\tplan: FieldPlan,\n\twrite: FieldWrite,\n\tprior: unknown,\n\tpriorStamp: Stamp | null,\n\toutput: unknown,\n\tnewest: Stamp | null,\n\terror: string | undefined,\n): FoldTrace {\n\tconst lost = newest !== null && compareStamps(newest, write.s) > 0\n\tconst baseMismatch =\n\t\tprior !== undefined && !write.insert && canonicalKey(prior) !== canonicalKey(write.prev)\n\tconst insertOnto = write.insert && prior !== undefined\n\tconst strategy = plan.kind === 'reg' && write.a ? `atomic-${write.a.type}` : plan.strategy\n\tconst trace: FoldTrace = {\n\t\tfield,\n\t\tstrategy,\n\t\tinputA: plan.secret ? SECRET_REDACTED : prior,\n\t\tinputB: plan.secret ? SECRET_REDACTED : write.v,\n\t\tbase: write.hasPrev ? (plan.secret ? SECRET_REDACTED : write.prev) : null,\n\t\toutput: plan.secret ? SECRET_REDACTED : output,\n\t\ttier: plan.tier,\n\t\tconstraintViolated: null,\n\t\t// The fold is pure: callers time the whole mergeOp if they need a duration.\n\t\tduration: 0,\n\t\toperation: plan.secret ? redactOperation(op, field) : op,\n\t\tpriorOperationId: priorStamp?.o ?? null,\n\t\tconflict: lost || baseMismatch || insertOnto,\n\t}\n\tif (error !== undefined) trace.error = error\n\treturn trace\n}\n\nfunction isAlive(state: FoldState): boolean {\n\treturn state.cr !== null && isAfter(state.w, state.d)\n}\n\n/**\n * Merge one operation into a record's fold state.\n *\n * The merge is a join on a per-field CRDT, so it is commutative, associative and\n * idempotent: any replica that has merged the same set of operations, in any\n * order, any number of times, holds an identical state. Cost is O(fields the\n * operation touches) except for the out-of-order cases documented per kind (a late\n * write into an atomic or resolver chain refolds that field's chain).\n *\n * Record-level semantics:\n * - The record exists once an insert has been merged.\n * - Delete vs write is last-write-wins on the record: the record is live iff its\n * newest insert/update is later (HLC, then op id) than its newest delete. A\n * delete keeps the field states; a later write revives the record with every\n * field's merged value (the same visible result as the pre-W7 replay for an\n * update after a delete).\n * - An insert onto an existing row merges per field; it is not a reset.\n *\n * @param state - The record's current state (not mutated)\n * @param op - The operation (must belong to the same collection and record)\n * @param schema - The schema; resolvers and merge strategies come from it\n * @param options - Exclusion, richtext merger (traces only), trace mode, schema\n * transforms (the operation is merged as `operationSchemaView` reads it for\n * `schema.version`)\n * @returns The new state, the merge traces, and whether anything changed\n */\nexport function mergeOp(\n\tstate: FoldState,\n\tinput: Operation,\n\tschema: SchemaDefinition,\n\toptions: FoldOptions = {},\n): MergeOpResult {\n\tif (isExcluded(input, options.exclude)) return { state, traces: [], changed: false }\n\t// Transforms at fold time (RT-84, RT-85): the operation is stored exactly as its\n\t// author wrote it, and folded as the schema reads it. A transform that drops the\n\t// operation leaves it out of the fold, like an excluded one.\n\t// The beta.12 clear rule is NOT applied here: a genuine beta.12 body is made\n\t// canonical once, where its provenance is known (server ingest, a device's own\n\t// log at the upgrade), so a body a transform or anything else rewrote is never\n\t// mistaken for one (RT-85).\n\tconst op = operationSchemaView(input, schema.version, options.transforms)\n\tif (op === null) return { state, traces: [], changed: false }\n\tif (op.collection !== state.c || op.recordId !== state.r) {\n\t\tthrow new FoldStateError(\n\t\t\t`Operation ${op.id} targets ${op.collection}/${op.recordId} but the fold state is for ${state.c}/${state.r}.`,\n\t\t\t{ operationId: op.id, collection: op.collection, recordId: op.recordId },\n\t\t)\n\t}\n\tif (op.foldState !== undefined && op.type === 'insert') {\n\t\tconst carried = mergeCarriedState(state, op, schema, options)\n\t\tif (carried !== null) return carried\n\t}\n\tconst mode = options.traces ?? 'conflicts'\n\tconst traces: FoldTrace[] = []\n\tconst stamp = stampOf(op.timestamp, op.id)\n\tconst next: FoldState = { ...state }\n\tlet changed = false\n\tconst setRecordStamp = (key: 'cr' | 'w' | 'd' | 'u', value: Stamp | null): void => {\n\t\tif (value !== next[key]) {\n\t\t\tnext[key] = value\n\t\t\tchanged = true\n\t\t}\n\t}\n\n\tsetRecordStamp('u', maxStamp(state.u, stamp))\n\tif (op.type === 'delete') {\n\t\tsetRecordStamp('d', maxStamp(state.d, stamp))\n\t\tif (mode !== 'none' && state.cr !== null && isAfter(state.w, stamp)) {\n\t\t\ttraces.push(recordTrace(op, true, true))\n\t\t}\n\t\treturn { state: changed ? next : state, traces, changed }\n\t}\n\tif (op.data === null) {\n\t\t// An envelope operation (protocol v2) whose every field is sealed: the server\n\t\t// cannot read its values, but the write happened. It creates the record (an\n\t\t// insert) and counts as a write against deletes, so the server's record\n\t\t// existence agrees with the devices' (which fold the decrypted operation).\n\t\tif (op.encrypted !== undefined) {\n\t\t\tif (op.type === 'insert') setRecordStamp('cr', minStamp(state.cr, stamp))\n\t\t\tsetRecordStamp('w', maxStamp(state.w, stamp))\n\t\t}\n\t\treturn { state: changed ? next : state, traces, changed }\n\t}\n\n\tif (op.type === 'insert') setRecordStamp('cr', minStamp(state.cr, stamp))\n\tsetRecordStamp('w', maxStamp(state.w, stamp))\n\tif (mode !== 'none' && isAfter(state.d, stamp)) traces.push(recordTrace(op, false, false))\n\n\tconst collection = schema.collections[op.collection]\n\tlet fields = state.f\n\tfor (const [field, raw] of Object.entries(op.data)) {\n\t\tif (raw === undefined) continue\n\t\tconst existing = fields[field]\n\t\tconst plan = fieldPlanFor(collection, field, existing, state)\n\t\tconst write = buildWrite(\n\t\t\top,\n\t\t\tfield,\n\t\t\traw,\n\t\t\tclassify(fieldWriteStamp(op, field, stamp), op, field, plan, options),\n\t\t)\n\t\tif (write === null) continue\n\t\tconst tracing = mode !== 'none'\n\t\tconst prior = tracing ? safeMaterializeField(existing, field, options) : undefined\n\t\tconst priorStamp = existing ? fieldStamp(existing) : null\n\t\tconst result = applyFieldWrite(\n\t\t\texisting ?? emptyField(plan),\n\t\t\twrite,\n\t\t\tplan,\n\t\t\toptions.richtextSubsumes,\n\t\t)\n\t\tif (result.changed) {\n\t\t\tif (fields === state.f) fields = { ...state.f }\n\t\t\tfields[field] = result.state\n\t\t\tchanged = true\n\t\t}\n\t\t// A write that changed nothing can still be a conflict: it lost to a newer one.\n\t\tif (tracing) {\n\t\t\tconst trace = fieldTrace(\n\t\t\t\top,\n\t\t\t\tfield,\n\t\t\t\tplan,\n\t\t\t\twrite,\n\t\t\t\tprior,\n\t\t\t\tpriorStamp,\n\t\t\t\tsafeMaterializeField(result.state, field, options),\n\t\t\t\tfieldStamp(result.state),\n\t\t\t\tresult.error,\n\t\t\t)\n\t\t\tif (mode === 'all' || trace.conflict || trace.error !== undefined) traces.push(trace)\n\t\t}\n\t}\n\tnext.f = fields\n\treturn { state: changed ? next : state, traces, changed }\n}\n\nfunction recordTrace(op: Operation, isDelete: boolean, lost: boolean): FoldTrace {\n\treturn {\n\t\tfield: FOLD_RECORD_TRACE_FIELD,\n\t\tstrategy: 'delete-tombstone-lww',\n\t\tinputA: isDelete ? 'live' : 'deleted',\n\t\tinputB: isDelete ? 'deleted' : 'live',\n\t\tbase: null,\n\t\t// A delete that lost keeps the record live; a write older than the newest\n\t\t// delete stays hidden.\n\t\toutput: isDelete ? (lost ? 'live' : 'deleted') : 'deleted',\n\t\ttier: 1,\n\t\tconstraintViolated: null,\n\t\tduration: 0,\n\t\toperation: op,\n\t\tpriorOperationId: null,\n\t\tconflict: true,\n\t}\n}\n\n/**\n * Fold a record's operations from scratch: the reference definition of the\n * record's state. Equal to merging the operations one by one with\n * {@link mergeOp} in any order.\n *\n * @param ops - The record's operations, in any order, duplicates allowed\n * @param schema - The schema\n * @param options - `exclude` leaves out ops the server terminally rejected; traces\n * default to `'none'` here (pass `traces` to get them)\n * @returns The state (null if no op remains after exclusion) and the traces\n */\nexport function foldRecord(\n\tops: readonly Operation[],\n\tschema: SchemaDefinition,\n\toptions: FoldOptions = {},\n): FoldRecordResult {\n\tconst kept = ops.filter((op) => !isExcluded(op, options.exclude))\n\tconst first = kept[0]\n\tif (first === undefined) return { state: null, traces: [] }\n\t// Merging in stamp order makes every register write an O(1) append.\n\tconst ordered = kept\n\t\t.map((op) => ({ op, stamp: stampOf(op.timestamp, op.id) }))\n\t\t.sort((a, b) => compareStamps(a.stamp, b.stamp))\n\tlet state = createFoldState(first.collection, first.recordId)\n\tconst traces: FoldTrace[] = []\n\t// A from-scratch fold (re-materialization, rejection re-merge) is not a new merge\n\t// decision, so it emits no traces unless asked to.\n\tconst mergeOptions: FoldOptions = {\n\t\t...options,\n\t\texclude: undefined,\n\t\ttraces: options.traces ?? 'none',\n\t}\n\tfor (const { op } of ordered) {\n\t\tconst result = mergeOp(state, op, schema, mergeOptions)\n\t\tstate = result.state\n\t\ttraces.push(...result.traces)\n\t}\n\treturn { state, traces }\n}\n\n/**\n * The record's materialized field values (without `id`), or null when it does not\n * exist (no insert merged) or is deleted. Keys are in sorted order.\n *\n * @param state - The record's fold state\n * @param options - `richtext` is required when a richtext field has concurrent updates\n */\nexport function materialize(\n\tstate: FoldState,\n\toptions: Pick<FoldOptions, 'richtext'> = {},\n): Record<string, unknown> | null {\n\tif (!isAlive(state)) return null\n\tconst record: Record<string, unknown> = {}\n\tfor (const field of Object.keys(state.f).sort()) {\n\t\tconst value = materializeField(state.f[field] as FieldState, field, options.richtext)\n\t\tif (value !== undefined) record[field] = value\n\t}\n\treturn record\n}\n\n/** True when the record exists and its newest write is later than its newest delete. */\nexport function isFoldStateLive(state: FoldState): boolean {\n\treturn isAlive(state)\n}\n\n/**\n * Join two replicas' states of the same record (state-based CRDT merge):\n * `joinStates(foldRecord(A).state, foldRecord(B).state) = foldRecord(A ∪ B).state`.\n * Commutative, associative and idempotent. Used to merge a restored backup or a\n * peer's snapshot without replaying its operations.\n *\n * @param a - One state\n * @param b - The other state (same collection and record)\n * @param schema - The schema (resolver fields refold through their resolver)\n */\nexport function joinStates(a: FoldState, b: FoldState, schema: SchemaDefinition): FoldState {\n\tif (a.c !== b.c || a.r !== b.r) {\n\t\tthrow new FoldStateError(`Cannot join fold states of ${a.c}/${a.r} and ${b.c}/${b.r}.`, {\n\t\t\tleft: `${a.c}/${a.r}`,\n\t\t\tright: `${b.c}/${b.r}`,\n\t\t})\n\t}\n\tconst collection = schema.collections[a.c]\n\tconst fields: Record<string, FieldState> = { ...a.f }\n\tfor (const [field, other] of Object.entries(b.f)) {\n\t\tconst mine = fields[field]\n\t\tif (mine === undefined) {\n\t\t\tfieldPlanFor(collection, field, other, b)\n\t\t\tfields[field] = other\n\t\t\tcontinue\n\t\t}\n\t\tconst plan = fieldPlanFor(collection, field, mine, a)\n\t\tfieldPlanFor(collection, field, other, b)\n\t\tfields[field] = joinFieldStates(mine, other, plan)\n\t}\n\treturn {\n\t\tv: FOLD_STATE_VERSION,\n\t\tc: a.c,\n\t\tr: a.r,\n\t\tcr: minStamp(a.cr, b.cr),\n\t\tw: maxStamp(a.w, b.w),\n\t\td: maxStamp(a.d, b.d),\n\t\tu: maxStamp(a.u, b.u),\n\t\tf: fields,\n\t}\n}\n\n/**\n * Each field's newest affecting write as a serialized HLC (`HybridLogicalClock.\n * serialize`), regardless of liveness: the `_field_versions` column of a stored row,\n * without a deserialize/serialize round trip. Keys in sorted order.\n */\nexport function getFoldFieldVersionStrings(state: FoldState): Record<string, string> {\n\tconst out: Record<string, string> = {}\n\tfor (const field of Object.keys(state.f).sort()) {\n\t\tconst stamp = fieldStamp(state.f[field] as FieldState)\n\t\tif (stamp !== null) out[field] = stamp.t\n\t}\n\treturn out\n}\n\n/**\n * Per-field versions of a live record (the fold's `_field_versions`): each field's\n * newest affecting write, plus the record's creation and newest operation. null\n * when the record is not live.\n */\nexport function getFoldFieldVersions(state: FoldState): FoldFieldVersions | null {\n\tif (!isAlive(state) || state.cr === null || state.u === null) return null\n\tconst fields: Record<string, HLCTimestamp> = {}\n\tfor (const [field, fieldState] of Object.entries(state.f)) {\n\t\tconst stamp = fieldStamp(fieldState)\n\t\tif (stamp !== null) fields[field] = stampTimestamp(stamp)\n\t}\n\treturn { fields, created: stampTimestamp(state.cr), latest: stampTimestamp(state.u) }\n}\n","import type { OperationTransform } from '../migration/operation-transform'\nimport { operationTransformsFingerprint } from '../migration/operation-view'\nimport type { CollectionDefinition, SchemaDefinition } from '../types'\nimport { planField } from './field-kind'\nimport { FOLD_STATE_VERSION, type FieldState, type FoldState } from './types'\n\n/**\n * FNV-1a over UTF-16 code units: a stable, dependency-free text fingerprint. The\n * server stores use this module's definition too (`@korajs/server` `record-fold.ts`\n * re-exports it), so a client and a server agree on whether a plan changed.\n */\nfunction hashText(text: string): string {\n\tlet hash = 0x811c9dc5\n\tfor (let i = 0; i < text.length; i++) {\n\t\thash ^= text.charCodeAt(i)\n\t\thash = Math.imul(hash, 0x01000193) >>> 0\n\t}\n\treturn hash.toString(16).padStart(8, '0')\n}\n\n/**\n * The fold plan of one collection as text: every field's kind, merge strategy and\n * resolver source. Two schemas fold a collection's stored states identically iff\n * these are equal.\n */\nexport function collectionFoldPlanFingerprint(\n\tname: string,\n\tcollection: CollectionDefinition,\n): string {\n\tconst fields = Object.keys(collection.fields)\n\t\t.sort()\n\t\t.map((field) => {\n\t\t\tconst descriptor = collection.fields[field]\n\t\t\tconst resolver = collection.resolvers?.[field]\n\t\t\treturn `${field}:${descriptor?.kind ?? ''}:${descriptor?.mergeStrategy ?? ''}:${\n\t\t\t\tresolver ? hashText(String(resolver)) : ''\n\t\t\t}`\n\t\t})\n\tconst resolverOnly = Object.keys(collection.resolvers ?? {})\n\t\t.filter((field) => !(field in collection.fields))\n\t\t.sort()\n\t\t.map((field) => `${field}:resolver:${hashText(String(collection.resolvers?.[field]))}`)\n\treturn `${name}(${[...fields, ...resolverOnly].join(',')})`\n}\n\n/**\n * Fingerprint of how a schema folds records (W7): the fold-state format version\n * plus every collection's {@link collectionFoldPlanFingerprint}. When it changes\n * (a field becomes `merge('counter')`, an array becomes append-only, a resolver is\n * added or edited), stored fold states may hold fields of another kind and must be\n * re-folded. The same definition as the server stores' `fold_plan_fingerprint`.\n *\n * Schema transforms (RT-84) are part of the plan when any is registered: an operation\n * of another schema version folds as its transformed view, so changing a transform or\n * the target version re-folds. Without transforms the fingerprint is unchanged.\n *\n * @param schema - The schema\n * @param transforms - The schema transforms the replica folds with\n */\nexport function foldPlanFingerprint(\n\tschema: SchemaDefinition,\n\ttransforms?: readonly OperationTransform[],\n): string {\n\tconst parts: string[] = [`fold-v${FOLD_STATE_VERSION}`]\n\tfor (const name of Object.keys(schema.collections).sort()) {\n\t\tconst collection = schema.collections[name]\n\t\tif (!collection) continue\n\t\tparts.push(collectionFoldPlanFingerprint(name, collection))\n\t}\n\tconst xf = operationTransformsFingerprint(schema.version, transforms)\n\tif (xf !== '') parts.push(xf)\n\treturn parts.join('|')\n}\n\n/**\n * Per-collection fold plan fingerprints, to find which collections a schema change\n * re-plans (only their records need re-folding).\n *\n * @param schema - The schema\n * @param transforms - The schema transforms the replica folds with (see {@link foldPlanFingerprint})\n * @returns Collection name -> fingerprint (format version included)\n */\nexport function foldPlanFingerprints(\n\tschema: SchemaDefinition,\n\ttransforms?: readonly OperationTransform[],\n): Record<string, string> {\n\tconst out: Record<string, string> = {}\n\tconst xf = operationTransformsFingerprint(schema.version, transforms)\n\tfor (const name of Object.keys(schema.collections).sort()) {\n\t\tconst collection = schema.collections[name]\n\t\tif (!collection) continue\n\t\tout[name] =\n\t\t\t`fold-v${FOLD_STATE_VERSION}|${collectionFoldPlanFingerprint(name, collection)}${xf !== '' ? `|${xf}` : ''}`\n\t}\n\treturn out\n}\n\n/** Whether a stored field state has the kind the schema folds the field as now. */\nexport function fieldStateMatchesPlan(\n\tcollection: CollectionDefinition | undefined,\n\tfield: string,\n\tstate: FieldState,\n): boolean {\n\tconst plan = planField(collection, field)\n\tif (state.k !== plan.kind) return false\n\treturn state.k !== 'set' || state.ao === plan.appendOnly\n}\n\n/**\n * The fields of a stored fold state whose kind no longer matches the schema (empty\n * when the state can be merged into as-is).\n *\n * @param state - A stored fold state\n * @param schema - The current schema\n */\nexport function mismatchedFoldFields(state: FoldState, schema: SchemaDefinition): string[] {\n\tconst collection = schema.collections[state.c]\n\treturn Object.keys(state.f)\n\t\t.filter((field) => !fieldStateMatchesPlan(collection, field, state.f[field] as FieldState))\n\t\t.sort()\n}\n","import type { HLCTimestamp, SchemaDefinition } from '../types'\nimport { isAuthoritativeNodeId } from './authority'\nimport { FoldConfigurationError } from './errors'\nimport { planField } from './field-kind'\nimport { elementKey, fieldStamp, materializeField } from './field-states'\nimport { createFoldState } from './fold'\nimport { fieldStateMatchesPlan, mismatchedFoldFields } from './plan'\nimport { stampOf } from './stamp'\nimport type { ElementState, FieldState, FoldOptions, FoldState, KeyState, Stamp } from './types'\nimport { canonicalKey, isPlainObject, normalizeValue } from './values'\n\n/**\n * Operation-id sentinels of snapshot stamps. They sort after every real operation\n * id (`` is above any id character), so a snapshot write dominates every\n * operation with the same HLC: the snapshot already reflects that operation.\n */\nconst SNAPSHOT_CLEAR_ID = 'kora-snapshot:0'\nconst SNAPSHOT_WRITE_ID = 'kora-snapshot:1'\n\n/** A materialized row and its versions, the input of {@link createSnapshotState}. */\nexport interface FoldSnapshotInput {\n\tcollection: string\n\trecordId: string\n\t/** Field values of the row (record or op-data form; binary is normalized). */\n\tvalues: Record<string, unknown>\n\t/** Per-field version: the HLC of the newest write of each field. */\n\tfieldVersions: Record<string, HLCTimestamp>\n\t/** HLC of the row's creation. */\n\tcreated: HLCTimestamp\n\t/** HLC of the newest operation the row reflects (its `_version`). */\n\tlatest: HLCTimestamp\n\t/** The row is a domain tombstone. */\n\tdeleted: boolean\n}\n\nfunction snapshotField(\n\tplan: ReturnType<typeof planField>,\n\traw: unknown,\n\tclear: Stamp,\n\twrite: Stamp,\n): FieldState {\n\tconst v = normalizeValue(raw)\n\tswitch (plan.kind) {\n\t\tcase 'reg':\n\t\t\treturn { k: 'reg', e: [{ s: write, v }], val: v }\n\t\tcase 'res':\n\t\t\treturn { k: 'res', e: [{ s: write, v, z: 1 }], val: v }\n\t\tcase 'ctr':\n\t\t\treturn { k: 'ctr', base: { s: write, v }, d: [], val: v }\n\t\tcase 'max':\n\t\tcase 'min':\n\t\t\treturn typeof v === 'number' && !Number.isNaN(v)\n\t\t\t\t? { k: plan.kind, best: { s: write, v }, reg: null }\n\t\t\t\t: { k: plan.kind, best: null, reg: { s: write, v } }\n\t\tcase 'set': {\n\t\t\tif (!Array.isArray(v)) {\n\t\t\t\treturn {\n\t\t\t\t\tk: 'set',\n\t\t\t\t\tao: plan.appendOnly,\n\t\t\t\t\tsh: { s: write, arr: false, v },\n\t\t\t\t\tclr: write,\n\t\t\t\t\tel: {},\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst el: Record<string, ElementState> = {}\n\t\t\tconst counts = new Map<string, number>()\n\t\t\tv.forEach((item, index) => {\n\t\t\t\tconst canonical = canonicalKey(item)\n\t\t\t\tconst n = counts.get(canonical) ?? 0\n\t\t\t\tcounts.set(canonical, n + 1)\n\t\t\t\tel[elementKey(canonical, n)] = {\n\t\t\t\t\tv: JSON.parse(canonical) as unknown,\n\t\t\t\t\tn,\n\t\t\t\t\ta: write,\n\t\t\t\t\tf: { s: write, i: index },\n\t\t\t\t\tr: null,\n\t\t\t\t}\n\t\t\t})\n\t\t\treturn { k: 'set', ao: plan.appendOnly, sh: { s: write, arr: true }, clr: clear, el }\n\t\t}\n\t\tcase 'map': {\n\t\t\tif (!isPlainObject(v)) {\n\t\t\t\treturn { k: 'map', sh: { s: write, obj: false, v }, clr: write, keys: {} }\n\t\t\t}\n\t\t\tconst keys: Record<string, KeyState> = {}\n\t\t\tfor (const [key, member] of Object.entries(v)) keys[key] = { s: write, del: false, v: member }\n\t\t\treturn { k: 'map', sh: { s: write, obj: true }, clr: clear, keys }\n\t\t}\n\t\tcase 'rt': {\n\t\t\tif (v === null || typeof v === 'string' || !isPlainObject(v) || !('$koraBytes' in v)) {\n\t\t\t\treturn { k: 'rt', reset: { s: write, v }, u: {} }\n\t\t\t}\n\t\t\tconst update = String(v.$koraBytes)\n\t\t\treturn { k: 'rt', reset: { s: clear, v: null }, u: { [update]: write } }\n\t\t}\n\t}\n}\n\n/** Options of {@link createSnapshotState}. */\nexport interface FoldSnapshotOptions {\n\t/**\n\t * A fold state this replica still holds for the record (its stored\n\t * `_kora_fold_state`, or the base of a compacted record). Every field whose stored\n\t * kind still matches the schema is taken from it as-is (exact: element, delta and\n\t * update stamps included); only the other fields are rebuilt from the row.\n\t */\n\tseed?: FoldState | null\n\t/**\n\t * Legacy authoritative node ids (`FoldOptions.authoritativeNodeIds`). A\n\t * `merge('server-authoritative')` field whose version was written by an\n\t * authoritative node (a `kora:server:` node or one of these) is stamped with\n\t * authority class 1, so a client write it beat cannot overturn it when merged again.\n\t */\n\tauthoritativeNodeIds?: ReadonlySet<string>\n}\n\n/**\n * Build a record's fold state from a materialized row: the base snapshot used when\n * the operations that produced the row are no longer all in the log (a database\n * compacted before W7, or a record that owns quarantined log rows).\n *\n * Exact where the replica still has the data: fields of `options.seed` (a stored\n * fold state) whose kind is unchanged are used verbatim, and the record stamps come\n * from it. Every other field is written at its own version with a sentinel\n * operation id that sorts after any real id, so the snapshot dominates every\n * operation it reflects: re-merging such an operation changes nothing (the record's\n * remaining log is folded on top of it again on every re-fold), while a later\n * operation merges on top as usual. Arrays and objects also clear elements / keys\n * written before the snapshot (so an older add the row no longer shows is not\n * resurrected), richtext hides older updates, counters drop older deltas and\n * custom-resolver fields start a fresh log at the snapshot value. A\n * `merge('server-authoritative')` field whose version is a server node's write\n * keeps its authority class.\n *\n * Approximate for a row-only field (RT-68 residual): a concurrent write OLDER than\n * the field's version that arrives later folds against the snapshot value, not\n * against the original operations (a late counter delta or array add is dropped).\n * It cannot be otherwise without the original operations: the row alone does not\n * say whether an older write is already in its value. The store marks such records\n * approximate, and the server's fold state replaces the snapshot when the record\n * next enters the device's scope.\n *\n * @param input - The row's values and versions\n * @param schema - The schema (selects each field's fold kind)\n * @param options - Seed state and authoritative node ids\n */\nexport function createSnapshotState(\n\tinput: FoldSnapshotInput,\n\tschema: SchemaDefinition,\n\toptions: FoldSnapshotOptions = {},\n): FoldState {\n\tconst state = createFoldState(input.collection, input.recordId)\n\tconst collection = schema.collections[input.collection]\n\tconst seed =\n\t\toptions.seed && options.seed.c === input.collection && options.seed.r === input.recordId\n\t\t\t? options.seed\n\t\t\t: null\n\tconst fields: Record<string, FieldState> = {}\n\tfor (const [field, raw] of Object.entries(input.values)) {\n\t\tif (raw === undefined) continue\n\t\tconst seeded = seed?.f[field]\n\t\tif (seeded !== undefined && fieldStateMatchesPlan(collection, field, seeded)) {\n\t\t\tfields[field] = seeded\n\t\t\tcontinue\n\t\t}\n\t\tconst version = input.fieldVersions[field] ?? input.latest\n\t\tconst plan = planField(collection, field)\n\t\tconst authoritative =\n\t\t\tplan.authoritative === true &&\n\t\t\tisAuthoritativeNodeId(version.nodeId, options.authoritativeNodeIds)\n\t\tfields[field] = snapshotField(\n\t\t\tplan,\n\t\t\traw,\n\t\t\tclassed(stampOf(version, SNAPSHOT_CLEAR_ID), authoritative),\n\t\t\tclassed(stampOf(version, SNAPSHOT_WRITE_ID), authoritative),\n\t\t)\n\t}\n\tif (seed !== null && seed.cr !== null && seed.u !== null) {\n\t\treturn { ...state, cr: seed.cr, w: seed.w, d: seed.d, u: seed.u, f: fields }\n\t}\n\tconst latestClear = stampOf(input.latest, SNAPSHOT_CLEAR_ID)\n\tconst latestWrite = stampOf(input.latest, SNAPSHOT_WRITE_ID)\n\treturn {\n\t\t...state,\n\t\tcr: stampOf(input.created, SNAPSHOT_WRITE_ID),\n\t\tw: input.deleted ? latestClear : latestWrite,\n\t\td: input.deleted ? latestWrite : null,\n\t\tu: latestWrite,\n\t\tf: fields,\n\t}\n}\n\nfunction classed(stamp: Stamp, authoritative: boolean): Stamp {\n\treturn authoritative ? { ...stamp, c: 1 } : stamp\n}\n\n/** Result of {@link adaptFoldState}. */\nexport interface AdaptedFoldState {\n\tstate: FoldState\n\t/** Fields rebuilt as snapshots (their stored kind no longer matched the schema). */\n\tadapted: string[]\n}\n\n/**\n * Make a stored fold state mergeable under the current schema after a change of a\n * field's fold kind (RT-63): every field whose stored kind no longer matches the\n * plan is replaced by a snapshot of its materialized value at its newest write (as\n * {@link createSnapshotState} builds from a row), keeping its authority class.\n * Fields whose kind is unchanged are kept exactly. Used for compacted base states,\n * whose operations are no longer in the log to re-fold with the new plan.\n *\n * @param state - A stored fold state (base or record state)\n * @param schema - The current schema\n * @param options - `richtext` merger, to materialize a richtext field with several updates\n */\nexport function adaptFoldState(\n\tstate: FoldState,\n\tschema: SchemaDefinition,\n\toptions: Pick<FoldOptions, 'richtext'> = {},\n): AdaptedFoldState {\n\tconst mismatched = mismatchedFoldFields(state, schema)\n\tif (mismatched.length === 0) return { state, adapted: [] }\n\tconst collection = schema.collections[state.c]\n\tconst fields: Record<string, FieldState> = { ...state.f }\n\tfor (const field of mismatched) {\n\t\tconst old = fields[field] as FieldState\n\t\tdelete fields[field]\n\t\tconst stamp = fieldStamp(old)\n\t\tif (stamp === null) continue\n\t\tlet value: unknown\n\t\ttry {\n\t\t\tvalue = materializeField(old, field, options.richtext)\n\t\t} catch (error) {\n\t\t\tif (error instanceof FoldConfigurationError) continue\n\t\t\tthrow error\n\t\t}\n\t\tif (value === undefined) continue\n\t\tconst plan = planField(collection, field)\n\t\tconst authoritative = stamp.c === 1 && plan.authoritative === true\n\t\tfields[field] = snapshotField(\n\t\t\tplan,\n\t\t\tvalue,\n\t\t\tclassed({ t: stamp.t, o: SNAPSHOT_CLEAR_ID }, authoritative),\n\t\t\tclassed({ t: stamp.t, o: SNAPSHOT_WRITE_ID }, authoritative),\n\t\t)\n\t}\n\treturn { state: { ...state, f: fields }, adapted: mismatched }\n}\n","import type { MergeTrace } from '../events/events'\nimport type { Operation } from '../types'\nimport type { FoldTrace } from './types'\n\n/**\n * Turn a {@link FoldTrace} into the {@link MergeTrace} DevTools and `merge:*`\n * events consume. `operationA` is the operation that last wrote the field before\n * the merge; the fold state only keeps its id (`trace.priorOperationId`), so the\n * caller looks it up in its operation log. When it is unavailable (compacted, or\n * the field had no prior value) the incoming operation stands in for it, and\n * `inputA` still carries the prior value.\n *\n * @param trace - A trace from `mergeOp`\n * @param operationA - The operation that produced the field's prior value, if known\n */\nexport function toMergeTrace(trace: FoldTrace, operationA?: Operation | null): MergeTrace {\n\treturn {\n\t\toperationA: operationA ?? trace.operation,\n\t\toperationB: trace.operation,\n\t\tfield: trace.field,\n\t\tstrategy: trace.strategy,\n\t\tinputA: trace.inputA,\n\t\tinputB: trace.inputB,\n\t\tbase: trace.base,\n\t\toutput: trace.output,\n\t\ttier: trace.tier,\n\t\tconstraintViolated: trace.constraintViolated,\n\t\tduration: trace.duration,\n\t}\n}\n","/**\n * Lossless string encoding for SQL text columns (RT-65), shared by every store that\n * binds JavaScript strings into a database: the server's Postgres and SQLite stores\n * and the client's SQLite stores (better-sqlite3, SQLite WASM on OPFS, and the\n * IndexedDB fallback, which runs SQLite WASM in memory).\n *\n * A JavaScript string is a sequence of UTF-16 code units. SQL text is UTF-8, which\n * cannot hold two kinds of code unit sequence a JS string can:\n *\n * - A lone UTF-16 surrogate: better-sqlite3, SQLite WASM (TextEncoder) and the\n * Postgres driver all encode it as U+FFFD: silent corruption.\n * - U+0000: Postgres TEXT refuses it; SQLite WASM reads a TEXT column up to the first\n * NUL.\n *\n * The codec maps those code units to an escape introduced by U+FFFF, a Unicode\n * noncharacter (valid UTF-8, never assigned):\n *\n * | Input | Stored |\n * |---|---|\n * | U+0000 | U+FFFF `0` |\n * | U+FFFF | U+FFFF `F` |\n * | lone surrogate `\\uXXXX` | U+FFFF `s` + 4 lowercase hex digits |\n *\n * Every other string is stored unchanged, so existing rows, equality filters and\n * ordering are unaffected for ordinary text. The map is injective, and\n * `decodeStoredText(encodeStoredText(s)) === s` for every JS string. Equality is\n * preserved: `encode(a) === encode(b)` iff `a === b`, so an equality filter binds the\n * encoded value.\n *\n * Ordering of escaped strings: range filters (`$gt`, `$lt`, ...) and `orderBy` compare\n * the stored (encoded) form, in the database's collation (UTF-8 byte order on SQLite and\n * on Postgres with `C.UTF-8`). A string containing U+0000, U+FFFF or a lone surrogate\n * therefore sorts by its escape, U+FFFF, at the position of the first such code unit:\n * after every other BMP character there, and before supplementary-plane characters.\n * For example `\"a\\u0000\"` sorts after `\"ab\"` (in JavaScript it sorts before), and a\n * lone surrogate sorts after `\"\\uFFFE\"`. Such strings are rare and equality is exact;\n * do not rely on their relative order in range queries.\n *\n * Columns holding `JSON.stringify` output need no codec: well-formed `JSON.stringify`\n * escapes U+0000 and lone surrogates as `\\u` sequences.\n */\n\n/** The escape introducer: U+FFFF, a noncharacter. */\nexport const STORED_TEXT_ESCAPE = ''\n\n// NUL, the escape, or any surrogate (paired ones are filtered in the loop).\n// biome-ignore lint/suspicious/noControlCharactersInRegex: U+0000 is exactly what the codec escapes (RT-65)\nconst NEEDS_ENCODING = /[\\u0000\\ud800-\\udfff]/\n\n/** True when `s` contains a code unit a SQL text column cannot hold as is. */\nexport function needsStoredTextEncoding(s: string): boolean {\n\treturn NEEDS_ENCODING.test(s)\n}\n\n/**\n * Encode a JS string for a SQL TEXT column (or a string inside a JSONB value).\n *\n * @param s - Any JavaScript string\n * @returns `s` itself when it holds no NUL, U+FFFF or lone surrogate; otherwise the escaped form\n */\nexport function encodeStoredText(s: string): string {\n\tif (!NEEDS_ENCODING.test(s)) return s\n\tlet out = ''\n\tfor (let i = 0; i < s.length; i++) {\n\t\tconst code = s.charCodeAt(i)\n\t\tif (code === 0) {\n\t\t\tout += `${STORED_TEXT_ESCAPE}0`\n\t\t} else if (code === 0xffff) {\n\t\t\tout += `${STORED_TEXT_ESCAPE}F`\n\t\t} else if (code >= 0xd800 && code <= 0xdbff) {\n\t\t\tconst next = s.charCodeAt(i + 1)\n\t\t\tif (next >= 0xdc00 && next <= 0xdfff) {\n\t\t\t\tout += s.slice(i, i + 2)\n\t\t\t\ti++\n\t\t\t} else {\n\t\t\t\tout += `${STORED_TEXT_ESCAPE}s${code.toString(16)}`\n\t\t\t}\n\t\t} else if (code >= 0xdc00 && code <= 0xdfff) {\n\t\t\tout += `${STORED_TEXT_ESCAPE}s${code.toString(16)}`\n\t\t} else {\n\t\t\tout += s.charAt(i)\n\t\t}\n\t}\n\treturn out\n}\n\n/**\n * Decode a string written by {@link encodeStoredText}.\n *\n * @param s - A stored string\n * @returns The original JavaScript string. A U+FFFF not followed by a valid tag is kept as is.\n */\nexport function decodeStoredText(s: string): string {\n\tif (!s.includes(STORED_TEXT_ESCAPE)) return s\n\tlet out = ''\n\tfor (let i = 0; i < s.length; i++) {\n\t\tconst char = s[i]\n\t\tif (char !== STORED_TEXT_ESCAPE) {\n\t\t\tout += char\n\t\t\tcontinue\n\t\t}\n\t\tconst tag = s[i + 1]\n\t\tif (tag === '0') {\n\t\t\tout += '\\u0000'\n\t\t\ti += 1\n\t\t} else if (tag === 'F') {\n\t\t\tout += STORED_TEXT_ESCAPE\n\t\t\ti += 1\n\t\t} else if (tag === 's') {\n\t\t\tconst hex = s.slice(i + 2, i + 6)\n\t\t\tconst code = Number.parseInt(hex, 16)\n\t\t\tif (hex.length === 4 && Number.isInteger(code) && code >= 0xd800 && code <= 0xdfff) {\n\t\t\t\tout += String.fromCharCode(code)\n\t\t\t\ti += 5\n\t\t\t} else {\n\t\t\t\t// Not written by the codec (a legacy row a migration did not reach): keep it.\n\t\t\t\tout += char\n\t\t\t}\n\t\t} else {\n\t\t\tout += char\n\t\t}\n\t}\n\treturn out\n}\n\n/**\n * Apply {@link encodeStoredText} to every string (and object key) inside a JSON value.\n *\n * @param value - A JSON-compatible value\n */\nexport function encodeStoredJsonValue(value: unknown): unknown {\n\treturn mapStrings(value, encodeStoredText)\n}\n\n/**\n * Apply {@link decodeStoredText} to every string (and object key) inside a JSON value.\n *\n * @param value - A JSON-compatible value\n */\nexport function decodeStoredJsonValue(value: unknown): unknown {\n\treturn mapStrings(value, decodeStoredText)\n}\n\nfunction mapStrings(value: unknown, map: (s: string) => string): unknown {\n\tif (typeof value === 'string') return map(value)\n\tif (Array.isArray(value)) return value.map((member) => mapStrings(member, map))\n\tif (value !== null && typeof value === 'object' && !ArrayBuffer.isView(value)) {\n\t\tconst out: Record<string, unknown> = {}\n\t\tfor (const [key, member] of Object.entries(value)) out[map(key)] = mapStrings(member, map)\n\t\treturn out\n\t}\n\treturn value\n}\n","import { OperationError } from '../errors/errors'\nimport { canonicalize } from '../operations/content-hash'\n\n/** Domain tag for derived side-effect ids, so they can never collide with a content hash. */\nconst SIDE_EFFECT_DOMAIN = 'kora/side-effect/v1'\n\n/**\n * Deterministic id for a side-effect operation (a referential cascade, a\n * set-null, a constraint correction) generated while applying `parentOpId`.\n *\n * Every replica that applies the same parent operation and generates the same\n * effect on the same record derives the same id, so the effect is stored once and\n * deduplicates everywhere instead of multiplying (one copy per replica) and racing\n * (W7 step 3). Cascades keep working offline: a client derives the same id the\n * server will.\n *\n * Callers must also make the side-effect's CONTENT deterministic (timestamp and\n * data derived from the parent), because dedup by id keeps whichever copy arrives\n * first. Ids are SHA-256 over canonical JSON of\n * `{ domain, parent, rule, target }`, hex encoded.\n *\n * @param parentOpId - Id of the operation whose application produced the effect\n * @param ruleId - Stable id of the rule (for example `relation:<name>:cascade`)\n * @param targetRecordId - Id of the record the effect writes\n * @returns 64-char hex id\n */\nexport async function deriveSideEffectOpId(\n\tparentOpId: string,\n\truleId: string,\n\ttargetRecordId: string,\n): Promise<string> {\n\tfor (const [name, value] of [\n\t\t['parentOpId', parentOpId],\n\t\t['ruleId', ruleId],\n\t\t['targetRecordId', targetRecordId],\n\t] as const) {\n\t\tif (typeof value !== 'string' || value.length === 0) {\n\t\t\tthrow new OperationError(`deriveSideEffectOpId: ${name} must be a non-empty string`, {\n\t\t\t\t[name]: value,\n\t\t\t})\n\t\t}\n\t}\n\tconst canonical = canonicalize({\n\t\tdomain: SIDE_EFFECT_DOMAIN,\n\t\tparent: parentOpId,\n\t\trule: ruleId,\n\t\ttarget: targetRecordId,\n\t})\n\tconst digest = await globalThis.crypto.subtle.digest(\n\t\t'SHA-256',\n\t\tnew TextEncoder().encode(canonical),\n\t)\n\treturn Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, '0')).join('')\n}\n","import type { SchemaDefinition, SyncRuleDefinition } from '../types'\n\n/**\n * Returns true when the schema declares partial sync rules at the root level.\n */\nexport function hasSchemaSyncRules(schema: SchemaDefinition): boolean {\n\treturn schema.sync !== undefined && Object.keys(schema.sync).length > 0\n}\n\n/**\n * Resolve field → scope-value-key bindings for a collection.\n *\n * Sync rules take precedence over legacy `collection.scope` arrays.\n * Returns `null` when the collection has no sync filtering configured.\n */\nexport function getCollectionScopeBindings(\n\tschema: SchemaDefinition,\n\tcollectionName: string,\n): Record<string, string> | null {\n\tconst syncRule = schema.sync?.[collectionName]\n\tif (syncRule && Object.keys(syncRule.where).length > 0) {\n\t\treturn { ...syncRule.where }\n\t}\n\n\tconst scopeFields = schema.collections[collectionName]?.scope ?? []\n\tif (scopeFields.length === 0) {\n\t\treturn null\n\t}\n\n\tconst bindings: Record<string, string> = {}\n\tfor (const field of scopeFields) {\n\t\tbindings[field] = field\n\t}\n\treturn bindings\n}\n\n/**\n * Returns whether a collection participates in sync filtering for this schema.\n */\nexport function isCollectionSyncScoped(schema: SchemaDefinition, collectionName: string): boolean {\n\tif (hasSchemaSyncRules(schema)) {\n\t\tif (schema.sync?.[collectionName]) {\n\t\t\treturn true\n\t\t}\n\t\tconst legacyScope = schema.collections[collectionName]?.scope ?? []\n\t\treturn legacyScope.length > 0\n\t}\n\n\treturn getCollectionScopeBindings(schema, collectionName) !== null\n}\n\n/**\n * Collect unique scope value keys referenced by sync rules and legacy scope fields.\n */\nexport function collectSchemaScopeValueKeys(schema: SchemaDefinition): string[] {\n\tconst keys = new Set<string>()\n\n\tfor (const collection of Object.values(schema.collections)) {\n\t\tfor (const field of collection.scope) {\n\t\t\tkeys.add(field)\n\t\t}\n\t}\n\n\tif (schema.sync) {\n\t\tfor (const rule of Object.values(schema.sync)) {\n\t\t\tfor (const scopeKey of Object.values(rule.where)) {\n\t\t\t\tkeys.add(scopeKey)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn [...keys]\n}\n\n/**\n * Normalize developer sync rule input into internal bindings.\n */\nexport function normalizeSyncRuleWhere(\n\tcollectionName: string,\n\twhere: Record<string, boolean | string>,\n): SyncRuleDefinition['where'] {\n\tconst normalized: Record<string, string> = {}\n\n\tfor (const [field, scopeKey] of Object.entries(where)) {\n\t\tif (scopeKey === true) {\n\t\t\tnormalized[field] = field\n\t\t\tcontinue\n\t\t}\n\n\t\tif (typeof scopeKey === 'string' && scopeKey.length > 0) {\n\t\t\tnormalized[field] = scopeKey\n\t\t\tcontinue\n\t\t}\n\n\t\tthrow new Error(\n\t\t\t`Invalid sync rule for collection \"${collectionName}\": where.${field} must be true or a non-empty scope key string`,\n\t\t)\n\t}\n\n\treturn normalized\n}\n","import { SchemaValidationError } from '../errors/errors'\nimport type {\n\tFieldDescriptor,\n\tSchemaDefinition,\n\tStateMachineConstraint,\n\tTransitionMap,\n\tTransitionValidationResult,\n} from '../types'\n\n/**\n * Validates whether a transition from one state to another is allowed\n * by the given state machine constraint.\n *\n * @param constraint - The state machine constraint defining allowed transitions\n * @param fromValue - The current state value (before the transition)\n * @param toValue - The target state value (after the transition)\n * @returns A TransitionValidationResult describing whether the transition is valid\n *\n * @example\n * ```typescript\n * const constraint: StateMachineConstraint = {\n * field: 'status',\n * collection: 'orders',\n * transitions: {\n * draft: ['submitted', 'cancelled'],\n * submitted: ['approved'],\n * approved: [],\n * },\n * }\n *\n * const result = validateTransition(constraint, 'draft', 'submitted')\n * // { valid: true, from: 'draft', to: 'submitted', field: 'status',\n * // collection: 'orders', allowedTargets: ['submitted', 'cancelled'] }\n * ```\n */\nexport function validateTransition(\n\tconstraint: StateMachineConstraint,\n\tfromValue: unknown,\n\ttoValue: unknown,\n): TransitionValidationResult {\n\tconst from = String(fromValue)\n\tconst to = String(toValue)\n\tconst allowedTargets = constraint.transitions[from] ?? []\n\n\treturn {\n\t\tvalid: allowedTargets.includes(to),\n\t\tfrom,\n\t\tto,\n\t\tfield: constraint.field,\n\t\tcollection: constraint.collection,\n\t\tallowedTargets,\n\t}\n}\n\n/**\n * Extracts all state machine constraints from a schema definition.\n * Scans every collection for enum fields that have transition rules declared\n * via the `.transitions()` builder method.\n *\n * @param schema - The schema definition to extract constraints from\n * @returns An array of StateMachineConstraint objects, one per enum field with transitions\n *\n * @example\n * ```typescript\n * const schema = defineSchema({\n * version: 1,\n * collections: {\n * orders: {\n * fields: {\n * status: t.enum(['draft', 'submitted']).transitions({\n * draft: ['submitted'],\n * submitted: [],\n * }),\n * },\n * },\n * },\n * })\n *\n * const constraints = buildStateMachineConstraints(schema)\n * // [{ field: 'status', collection: 'orders', transitions: { draft: ['submitted'], submitted: [] } }]\n * ```\n */\nexport function buildStateMachineConstraints(schema: SchemaDefinition): StateMachineConstraint[] {\n\tconst constraints: StateMachineConstraint[] = []\n\n\tfor (const [collectionName, collection] of Object.entries(schema.collections)) {\n\t\tfor (const [fieldName, descriptor] of Object.entries(collection.fields)) {\n\t\t\tif (descriptor.kind === 'enum' && descriptor.transitions !== null) {\n\t\t\t\tconstraints.push({\n\t\t\t\t\tfield: fieldName,\n\t\t\t\t\tcollection: collectionName,\n\t\t\t\t\ttransitions: descriptor.transitions,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t}\n\n\treturn constraints\n}\n\n/**\n * Finds the state machine constraint for a specific field in a specific collection,\n * if one exists.\n *\n * @param schema - The schema definition to search\n * @param collection - The collection name\n * @param field - The field name\n * @returns The TransitionMap if the field has transitions declared, or null otherwise\n */\nexport function getTransitionMap(\n\tschema: SchemaDefinition,\n\tcollection: string,\n\tfield: string,\n): TransitionMap | null {\n\tconst collectionDef = schema.collections[collection]\n\tif (!collectionDef) {\n\t\treturn null\n\t}\n\tconst fieldDef = collectionDef.fields[field]\n\tif (!fieldDef || fieldDef.kind !== 'enum') {\n\t\treturn null\n\t}\n\treturn fieldDef.transitions\n}\n\n/**\n * Validates a state machine definition against a collection's fields during schema building.\n * Called by defineSchema() to ensure the state machine is well-formed.\n *\n * @param collectionName - Name of the collection for error messages\n * @param sm - The state machine input definition\n * @param fields - The built field descriptors for the collection\n * @throws {SchemaValidationError} If the state machine definition is invalid\n */\nexport function validateStateMachineDefinition(\n\tcollectionName: string,\n\tsm: { field: string; transitions: Record<string, string[]>; onInvalidTransition: string },\n\tfields: Record<string, FieldDescriptor>,\n): void {\n\tconst fieldDef = fields[sm.field]\n\tif (!fieldDef) {\n\t\tthrow new SchemaValidationError(\n\t\t\t`State machine field \"${sm.field}\" does not exist in collection \"${collectionName}\". Available fields: ${Object.keys(fields).join(', ')}`,\n\t\t\t{ collection: collectionName, field: sm.field },\n\t\t)\n\t}\n\tif (fieldDef.kind !== 'enum') {\n\t\tthrow new SchemaValidationError(\n\t\t\t`State machine field \"${sm.field}\" in collection \"${collectionName}\" must be an enum field, but got \"${fieldDef.kind}\"`,\n\t\t\t{ collection: collectionName, field: sm.field, kind: fieldDef.kind },\n\t\t)\n\t}\n\tconst enumValues = fieldDef.enumValues\n\tif (!enumValues || enumValues.length === 0) {\n\t\tthrow new SchemaValidationError(\n\t\t\t`State machine field \"${sm.field}\" in collection \"${collectionName}\" has no enum values defined`,\n\t\t\t{ collection: collectionName, field: sm.field },\n\t\t)\n\t}\n\tconst validValues = new Set(enumValues)\n\tfor (const [state, targets] of Object.entries(sm.transitions)) {\n\t\tif (!validValues.has(state)) {\n\t\t\tthrow new SchemaValidationError(\n\t\t\t\t`State machine transition source \"${state}\" is not a valid enum value for field \"${sm.field}\" in collection \"${collectionName}\". Valid values: ${[...validValues].join(', ')}`,\n\t\t\t\t{ collection: collectionName, field: sm.field, state },\n\t\t\t)\n\t\t}\n\t\tfor (const target of targets) {\n\t\t\tif (!validValues.has(target)) {\n\t\t\t\tthrow new SchemaValidationError(\n\t\t\t\t\t`State machine transition target \"${target}\" is not a valid enum value for field \"${sm.field}\" in collection \"${collectionName}\". Valid values: ${[...validValues].join(', ')}`,\n\t\t\t\t\t{ collection: collectionName, field: sm.field, state, target },\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t}\n\tif (sm.onInvalidTransition !== 'reject' && sm.onInvalidTransition !== 'last-valid-state') {\n\t\tthrow new SchemaValidationError(\n\t\t\t`State machine onInvalidTransition must be \"reject\" or \"last-valid-state\", got \"${sm.onInvalidTransition}\" in collection \"${collectionName}\"`,\n\t\t\t{ collection: collectionName, onInvalidTransition: sm.onInvalidTransition },\n\t\t)\n\t}\n}\n","import { SchemaValidationError } from '../errors/errors'\nimport type { MigrationDefinition } from '../migrations/migration-builder'\nimport { normalizeSyncRuleWhere } from '../scopes/sync-scope-bindings'\nimport { validateStateMachineDefinition } from '../state-machine/state-machine'\nimport type {\n\tCollectionDefinition,\n\tConstraint,\n\tCustomResolver,\n\tFieldDescriptor,\n\tRelationDefinition,\n\tSchemaDefinition,\n\tStateMachineDefinition,\n\tSyncRuleDefinition,\n} from '../types'\nimport type { FieldBuilder } from './types'\n\n/**\n * Valid collection name pattern: starts with a letter, then letters, numbers,\n * and underscores. Case is preserved, so camelCase (`formResponses`) and\n * PascalCase (`UserProfiles`) are allowed — generated SQL quotes every\n * identifier (see `quoteIdent`), so mixed case and even reserved words like\n * `order` round-trip safely. The leading-letter rule keeps names clear of the\n * framework's own `_`-prefixed tables.\n */\nconst COLLECTION_NAME_RE = /^[A-Za-z][A-Za-z0-9_]*$/\n\n/** Valid field name pattern: camelCase allowed (e.g. createdAt, dueDate) */\nconst FIELD_NAME_RE = /^[a-z][a-zA-Z0-9_]*$/\n\n/** Reserved field names that cannot be used in schemas */\nconst RESERVED_FIELDS = new Set(['id', '_created_at', '_updated_at', '_version', '_deleted'])\n\n/**\n * Input shape for defineSchema() — what the developer writes.\n */\nexport interface SchemaInput {\n\tversion: number\n\tcollections: Record<string, CollectionInput>\n\trelations?: Record<string, RelationInput>\n\t/** Schema migrations keyed by target version number. */\n\tmigrations?: Record<number, MigrationDefinition>\n\t/**\n\t * Declarative partial-sync rules.\n\t *\n\t * @example\n\t * ```typescript\n\t * sync: {\n\t * todos: { where: { userId: true, orgId: true } },\n\t * projects: { where: { orgId: true } },\n\t * }\n\t * ```\n\t */\n\tsync?: Record<string, SyncRuleInput>\n}\n\n/**\n * Developer input for a collection sync rule.\n */\nexport interface SyncRuleInput {\n\t/**\n\t * Field filters bound to scope values.\n\t * Use `true` to bind a field to a scope value with the same name.\n\t * Use a string to bind to a different scope value key.\n\t */\n\twhere: Record<string, boolean | string>\n}\n\nexport interface StateMachineInput {\n\t/** The enum field this state machine controls */\n\tfield: string\n\t/** Map of state to allowed next states */\n\ttransitions: Record<string, string[]>\n\t/** What to do when an invalid transition is attempted */\n\tonInvalidTransition: 'reject' | 'last-valid-state'\n}\n\nexport interface CollectionInput {\n\tfields: Record<string, FieldBuilder>\n\tindexes?: string[]\n\tconstraints?: ConstraintInput[]\n\tresolve?: Record<string, CustomResolver>\n\t/** Scope fields for sync filtering. Only records matching the client's scope values are synced. */\n\tscope?: string[]\n\t/** State machine definition constraining transitions on an enum field */\n\tstateMachine?: StateMachineInput\n}\n\nexport interface ConstraintInput {\n\ttype: 'unique' | 'capacity' | 'referential'\n\tfields: string[]\n\twhere?: Record<string, unknown>\n\tonConflict:\n\t\t| 'first-write-wins'\n\t\t| 'last-write-wins'\n\t\t| 'priority-field'\n\t\t| 'server-decides'\n\t\t| 'custom'\n\tpriorityField?: string\n\tresolve?: (local: unknown, remote: unknown, base: unknown) => unknown\n}\n\nexport interface RelationInput {\n\tfrom: string\n\tto: string\n\ttype: 'one-to-one' | 'one-to-many' | 'many-to-one' | 'many-to-many'\n\tfield: string\n\tonDelete: 'cascade' | 'set-null' | 'restrict' | 'no-action'\n}\n\n/**\n * Validates and builds a SchemaDefinition from developer input.\n * This is the primary developer-facing function for defining a schema.\n *\n * @param input - The schema definition using type builders\n * @returns A validated SchemaDefinition ready for use by the framework\n * @throws {SchemaValidationError} If the schema is invalid\n *\n * @example\n * ```typescript\n * import { defineSchema, t } from '@korajs/core'\n *\n * const schema = defineSchema({\n * version: 1,\n * collections: {\n * todos: {\n * fields: {\n * title: t.string(),\n * completed: t.boolean().default(false),\n * }\n * }\n * }\n * })\n * ```\n */\n/**\n * Schema definition with a phantom type brand preserving the original input shape.\n * The `__input` property exists only at the type level for inference — no runtime cost.\n */\nexport type TypedSchemaDefinition<T extends SchemaInput = SchemaInput> = SchemaDefinition & {\n\treadonly __input: T\n}\n\nexport function defineSchema<const T extends SchemaInput>(input: T): TypedSchemaDefinition<T> {\n\tvalidateVersion(input.version)\n\n\tconst collections: Record<string, CollectionDefinition> = {}\n\n\tfor (const [name, collectionInput] of Object.entries(input.collections)) {\n\t\tvalidateCollectionName(name)\n\t\tcollections[name] = buildCollection(name, collectionInput)\n\t}\n\n\tif (Object.keys(collections).length === 0) {\n\t\tthrow new SchemaValidationError('Schema must define at least one collection')\n\t}\n\n\tconst relations: Record<string, RelationDefinition> = {}\n\tif (input.relations) {\n\t\tfor (const [name, relationInput] of Object.entries(input.relations)) {\n\t\t\tvalidateRelation(name, relationInput, collections)\n\t\t\trelations[name] = { ...relationInput }\n\t\t}\n\t}\n\n\tconst migrations: Record<number, MigrationDefinition> = {}\n\tif (input.migrations) {\n\t\tfor (const [versionStr, migration] of Object.entries(input.migrations)) {\n\t\t\tconst version = Number(versionStr)\n\t\t\tif (!Number.isInteger(version) || version < 2) {\n\t\t\t\tthrow new SchemaValidationError(\n\t\t\t\t\t`Migration key \"${versionStr}\" is invalid. Must be an integer >= 2 (version 1 is the initial schema).`,\n\t\t\t\t\t{ version: versionStr },\n\t\t\t\t)\n\t\t\t}\n\t\t\tif (version > input.version) {\n\t\t\t\tthrow new SchemaValidationError(\n\t\t\t\t\t`Migration version ${version} exceeds schema version ${input.version}. Migrations must target versions <= schema version.`,\n\t\t\t\t\t{ migrationVersion: version, schemaVersion: input.version },\n\t\t\t\t)\n\t\t\t}\n\t\t\tif (!migration.steps || migration.steps.length === 0) {\n\t\t\t\tthrow new SchemaValidationError(\n\t\t\t\t\t`Migration for version ${version} has no steps. Use migrate() to define at least one step.`,\n\t\t\t\t\t{ version },\n\t\t\t\t)\n\t\t\t}\n\t\t\tmigrations[version] = migration\n\t\t}\n\t}\n\n\tconst sync = buildSyncRules(input.sync, collections)\n\tapplySyncRulesToCollectionScope(collections, sync)\n\n\treturn {\n\t\tversion: input.version,\n\t\tcollections,\n\t\trelations,\n\t\tmigrations,\n\t\t...(sync ? { sync } : {}),\n\t} as TypedSchemaDefinition<T>\n}\n\nfunction validateVersion(version: number): void {\n\tif (typeof version !== 'number' || !Number.isInteger(version) || version < 1) {\n\t\tthrow new SchemaValidationError('Schema version must be a positive integer', {\n\t\t\treceived: version,\n\t\t})\n\t}\n}\n\nfunction validateCollectionName(name: string): void {\n\tif (!COLLECTION_NAME_RE.test(name)) {\n\t\tthrow new SchemaValidationError(\n\t\t\t`Collection name \"${name}\" is invalid. Must start with a letter and contain only letters, numbers, and underscores.`,\n\t\t\t{ collection: name },\n\t\t)\n\t}\n}\n\nfunction buildCollection(name: string, input: CollectionInput): CollectionDefinition {\n\tconst fields: Record<string, FieldDescriptor> = {}\n\n\tif (!input.fields || Object.keys(input.fields).length === 0) {\n\t\tthrow new SchemaValidationError(`Collection \"${name}\" must define at least one field`, {\n\t\t\tcollection: name,\n\t\t})\n\t}\n\n\tfor (const [fieldName, builder] of Object.entries(input.fields)) {\n\t\tvalidateFieldName(name, fieldName)\n\t\tfields[fieldName] = builder._build()\n\t}\n\n\tconst indexes = input.indexes ?? []\n\tfor (const indexField of indexes) {\n\t\tif (!(indexField in fields)) {\n\t\t\tthrow new SchemaValidationError(\n\t\t\t\t`Index field \"${indexField}\" does not exist in collection \"${name}\". Available fields: ${Object.keys(fields).join(', ')}`,\n\t\t\t\t{ collection: name, field: indexField },\n\t\t\t)\n\t\t}\n\t}\n\n\tconst constraints: Constraint[] = []\n\tif (input.constraints) {\n\t\tfor (const constraintInput of input.constraints) {\n\t\t\tvalidateConstraint(name, constraintInput, fields)\n\t\t\tconstraints.push({ ...constraintInput })\n\t\t}\n\t}\n\n\tconst resolvers: Record<string, CustomResolver> = {}\n\tif (input.resolve) {\n\t\tfor (const [fieldName, resolver] of Object.entries(input.resolve)) {\n\t\t\tif (!(fieldName in fields)) {\n\t\t\t\tthrow new SchemaValidationError(\n\t\t\t\t\t`Resolver for field \"${fieldName}\" does not exist in collection \"${name}\". Available fields: ${Object.keys(fields).join(', ')}`,\n\t\t\t\t\t{ collection: name, field: fieldName },\n\t\t\t\t)\n\t\t\t}\n\t\t\tif (typeof resolver !== 'function') {\n\t\t\t\tthrow new SchemaValidationError(\n\t\t\t\t\t`Resolver for field \"${fieldName}\" in collection \"${name}\" must be a function`,\n\t\t\t\t\t{ collection: name, field: fieldName },\n\t\t\t\t)\n\t\t\t}\n\t\t\tresolvers[fieldName] = resolver\n\t\t}\n\t}\n\n\tconst scope: string[] = []\n\tif (input.scope) {\n\t\tfor (const scopeField of input.scope) {\n\t\t\tif (!(scopeField in fields)) {\n\t\t\t\tthrow new SchemaValidationError(\n\t\t\t\t\t`Scope field \"${scopeField}\" does not exist in collection \"${name}\". Available fields: ${Object.keys(fields).join(', ')}`,\n\t\t\t\t\t{ collection: name, field: scopeField },\n\t\t\t\t)\n\t\t\t}\n\t\t\tscope.push(scopeField)\n\t\t}\n\t}\n\n\tlet stateMachine: StateMachineDefinition | undefined\n\tif (input.stateMachine) {\n\t\tvalidateStateMachineDefinition(name, input.stateMachine, fields)\n\t\tstateMachine = { ...input.stateMachine }\n\t}\n\n\t// Field-level `t.enum(...).transitions({...})` (NEW-STORE-3) is the documented\n\t// shorthand for a state machine on that field, with the default 'reject' mode.\n\t// With exactly one such field and no collection-level definition, it becomes\n\t// the collection's state machine, so every layer that reads `stateMachine`\n\t// (local writes, transactions, merge) sees it. Local writes also enforce every\n\t// field-level transition map directly, so a collection may declare several.\n\tif (!stateMachine) {\n\t\tconst transitionFields = Object.entries(fields).filter(\n\t\t\t([, descriptor]) => descriptor.kind === 'enum' && descriptor.transitions,\n\t\t)\n\t\tconst only = transitionFields.length === 1 ? transitionFields[0] : undefined\n\t\tif (only?.[1].transitions) {\n\t\t\tconst derived: StateMachineInput = {\n\t\t\t\tfield: only[0],\n\t\t\t\ttransitions: { ...only[1].transitions },\n\t\t\t\tonInvalidTransition: 'reject',\n\t\t\t}\n\t\t\tvalidateStateMachineDefinition(name, derived, fields)\n\t\t\tstateMachine = derived\n\t\t}\n\t}\n\n\treturn { fields, indexes, constraints, resolvers, scope, stateMachine }\n}\n\nfunction buildSyncRules(\n\tsyncInput: SchemaInput['sync'],\n\tcollections: Record<string, CollectionDefinition>,\n): Record<string, SyncRuleDefinition> | undefined {\n\tif (!syncInput) {\n\t\treturn undefined\n\t}\n\n\tconst sync: Record<string, SyncRuleDefinition> = {}\n\n\tfor (const [collectionName, ruleInput] of Object.entries(syncInput)) {\n\t\tif (!(collectionName in collections)) {\n\t\t\tthrow new SchemaValidationError(\n\t\t\t\t`Sync rule references collection \"${collectionName}\" which does not exist. Available collections: ${Object.keys(collections).join(', ')}`,\n\t\t\t\t{ collection: collectionName },\n\t\t\t)\n\t\t}\n\n\t\tif (!ruleInput.where || Object.keys(ruleInput.where).length === 0) {\n\t\t\tthrow new SchemaValidationError(\n\t\t\t\t`Sync rule for collection \"${collectionName}\" must declare at least one where binding`,\n\t\t\t\t{ collection: collectionName },\n\t\t\t)\n\t\t}\n\n\t\tconst collection = collections[collectionName]\n\t\tif (!collection) {\n\t\t\tcontinue\n\t\t}\n\n\t\tfor (const fieldName of Object.keys(ruleInput.where)) {\n\t\t\tif (!(fieldName in collection.fields)) {\n\t\t\t\tthrow new SchemaValidationError(\n\t\t\t\t\t`Sync rule where field \"${fieldName}\" does not exist in collection \"${collectionName}\". Available fields: ${Object.keys(collection.fields).join(', ')}`,\n\t\t\t\t\t{ collection: collectionName, field: fieldName },\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\n\t\ttry {\n\t\t\tsync[collectionName] = { where: normalizeSyncRuleWhere(collectionName, ruleInput.where) }\n\t\t} catch (error) {\n\t\t\tthrow new SchemaValidationError(\n\t\t\t\terror instanceof Error ? error.message : 'Invalid sync rule',\n\t\t\t\t{ collection: collectionName },\n\t\t\t)\n\t\t}\n\t}\n\n\treturn sync\n}\n\nfunction applySyncRulesToCollectionScope(\n\tcollections: Record<string, CollectionDefinition>,\n\tsync: Record<string, SyncRuleDefinition> | undefined,\n): void {\n\tif (!sync) {\n\t\treturn\n\t}\n\n\tfor (const [collectionName, rule] of Object.entries(sync)) {\n\t\tconst collection = collections[collectionName]\n\t\tif (!collection) {\n\t\t\tcontinue\n\t\t}\n\n\t\tfor (const fieldName of Object.keys(rule.where)) {\n\t\t\tif (!collection.scope.includes(fieldName)) {\n\t\t\t\tcollection.scope.push(fieldName)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunction validateFieldName(collection: string, fieldName: string): void {\n\tif (RESERVED_FIELDS.has(fieldName)) {\n\t\tthrow new SchemaValidationError(\n\t\t\t`Field name \"${fieldName}\" is reserved in collection \"${collection}\". Reserved fields: ${[...RESERVED_FIELDS].join(', ')}`,\n\t\t\t{ collection, field: fieldName },\n\t\t)\n\t}\n\tif (!FIELD_NAME_RE.test(fieldName)) {\n\t\tthrow new SchemaValidationError(\n\t\t\t`Field name \"${fieldName}\" in collection \"${collection}\" is invalid. Must start with a lowercase letter and contain only letters, numbers, and underscores.`,\n\t\t\t{ collection, field: fieldName },\n\t\t)\n\t}\n}\n\nfunction validateConstraint(\n\tcollection: string,\n\tconstraint: ConstraintInput,\n\tfields: Record<string, FieldDescriptor>,\n): void {\n\tfor (const field of constraint.fields) {\n\t\tif (!(field in fields)) {\n\t\t\tthrow new SchemaValidationError(\n\t\t\t\t`Constraint references field \"${field}\" which does not exist in collection \"${collection}\". Available fields: ${Object.keys(fields).join(', ')}`,\n\t\t\t\t{ collection, field },\n\t\t\t)\n\t\t}\n\t}\n\n\tif (constraint.onConflict === 'priority-field' && !constraint.priorityField) {\n\t\tthrow new SchemaValidationError(\n\t\t\t`Constraint with \"priority-field\" onConflict strategy in collection \"${collection}\" requires a priorityField`,\n\t\t\t{ collection },\n\t\t)\n\t}\n\n\tif (constraint.onConflict === 'priority-field' && constraint.priorityField) {\n\t\tif (!(constraint.priorityField in fields)) {\n\t\t\tthrow new SchemaValidationError(\n\t\t\t\t`Constraint priorityField \"${constraint.priorityField}\" does not exist in collection \"${collection}\"`,\n\t\t\t\t{ collection, field: constraint.priorityField },\n\t\t\t)\n\t\t}\n\t}\n\n\tif (constraint.onConflict === 'custom' && typeof constraint.resolve !== 'function') {\n\t\tthrow new SchemaValidationError(\n\t\t\t`Constraint with \"custom\" onConflict strategy in collection \"${collection}\" requires a resolve function`,\n\t\t\t{ collection },\n\t\t)\n\t}\n}\n\nfunction validateRelation(\n\tname: string,\n\trelation: RelationInput,\n\tcollections: Record<string, CollectionDefinition>,\n): void {\n\tif (!(relation.from in collections)) {\n\t\tthrow new SchemaValidationError(\n\t\t\t`Relation \"${name}\" references source collection \"${relation.from}\" which does not exist. Available collections: ${Object.keys(collections).join(', ')}`,\n\t\t\t{ relation: name, collection: relation.from },\n\t\t)\n\t}\n\n\tif (!(relation.to in collections)) {\n\t\tthrow new SchemaValidationError(\n\t\t\t`Relation \"${name}\" references target collection \"${relation.to}\" which does not exist. Available collections: ${Object.keys(collections).join(', ')}`,\n\t\t\t{ relation: name, collection: relation.to },\n\t\t)\n\t}\n\n\tconst fromCollection = collections[relation.from]\n\tif (fromCollection && !(relation.field in fromCollection.fields)) {\n\t\tthrow new SchemaValidationError(\n\t\t\t`Relation \"${name}\" references field \"${relation.field}\" which does not exist in collection \"${relation.from}\". Available fields: ${Object.keys(fromCollection.fields).join(', ')}`,\n\t\t\t{ relation: name, collection: relation.from, field: relation.field },\n\t\t)\n\t}\n}\n","import { SchemaValidationError } from '../errors/errors'\nimport { encodeStoredText } from '../text/stored-text'\nimport type {\n\tBlobRef,\n\tFieldDescriptor,\n\tFieldKind,\n\tFieldMergeStrategy,\n\tSecretMode,\n\tTransitionMap,\n} from '../types'\nimport type { FieldKindToType } from './infer'\n\n/**\n * A value a `t.richtext()` field accepts on write: a plain string (stored as a fresh\n * Yjs document holding that text) or Yjs update bytes. Reads always return the Yjs\n * update bytes (`Uint8Array`).\n */\nexport type RichtextInput = string | Uint8Array | ArrayBuffer\n\n/**\n * Compile-time description of a field, carried by every {@link FieldBuilder} under the\n * `'~field'` key. It exists only in the type system (the property is `declare`d, so it is\n * never present at runtime) and is what makes builders structurally distinct:\n * `t.string()` and `t.string().optional()` are different types, so inference can tell a\n * required field from an optional one.\n */\nexport interface FieldTypeInfo<\n\tKind extends FieldKind,\n\tReq extends boolean,\n\tAuto extends boolean,\n\tOutput,\n\tInput,\n> {\n\t/** The field kind. */\n\treadonly kind: Kind\n\t/** Whether the developer must provide the field on insert. */\n\treadonly required: Req\n\t/** Whether the framework fills the field (it cannot be written). */\n\treadonly auto: Auto\n\t/** The type a read returns for the field (before nullability). */\n\treadonly output: Output\n\t/** The type a write accepts for the field (before optionality). */\n\treadonly input: Input\n}\n\n/**\n * The value types of each scalar field kind: what a read returns. `timestamp` is integer\n * milliseconds since the epoch (a `Date` is not accepted; use `date.getTime()`).\n */\nexport interface ScalarKindToType {\n\tstring: string\n\tnumber: number\n\tboolean: boolean\n\ttimestamp: number\n\trichtext: Uint8Array\n\tblob: BlobRef\n\tsecret: string\n}\n\n/** The type a scalar field kind accepts on write. */\nexport interface ScalarKindToInput {\n\tstring: string\n\tnumber: number\n\tboolean: boolean\n\ttimestamp: number\n\trichtext: RichtextInput\n\tblob: BlobRef\n\tsecret: string\n}\n\n/** A scalar field kind: one whose builder is a plain {@link FieldBuilder}. */\nexport type ScalarFieldKind = keyof ScalarKindToType\n\n/** The read type a field kind has when its builder declares nothing more specific. */\nexport type DefaultFieldOutput<Kind extends FieldKind> = FieldKindToType[Kind]\n\n/** The write type a field kind has when its builder declares nothing more specific. */\nexport type DefaultFieldInput<Kind extends FieldKind> = Kind extends 'richtext'\n\t? RichtextInput\n\t: FieldKindToType[Kind]\n\n/**\n * Base field builder implementing the builder pattern for schema field definitions.\n * Each builder is immutable — modifier methods return new builder instances.\n *\n * Type parameters track field metadata at the type level for inference:\n * - Kind: the field kind ('string', 'number', etc.)\n * - Req: whether the field is required (true = required on insert)\n * - Auto: whether the field is auto-populated (true = excluded from insert input)\n * - Output: the type a read returns\n * - Input: the type a write accepts (differs from Output only for richtext)\n *\n * A bare `FieldBuilder` (no type arguments) means \"any field builder\".\n *\n * @example\n * ```typescript\n * t.string() // required string field\n * t.string().optional() // optional string field\n * t.string().default('hello') // string with default value\n * t.timestamp().auto() // auto-populated timestamp\n * ```\n */\nexport class FieldBuilder<\n\tKind extends FieldKind = FieldKind,\n\tReq extends boolean = boolean,\n\tAuto extends boolean = boolean,\n\tOutput = DefaultFieldOutput<Kind>,\n\tInput = Kind extends 'richtext' ? DefaultFieldInput<Kind> : Output,\n> {\n\t/**\n\t * Type-only brand (never present at runtime). It makes the builder's kind,\n\t * requiredness, auto flag and value types part of its structure, which is what\n\t * schema inference reads.\n\t */\n\tdeclare readonly '~field': FieldTypeInfo<Kind, Req, Auto, Output, Input>\n\n\tprotected readonly _kind: Kind\n\tprotected readonly _required: boolean\n\tprotected readonly _defaultValue: unknown\n\tprotected readonly _auto: boolean\n\tprotected readonly _mergeStrategy: FieldMergeStrategy | null\n\n\tconstructor(\n\t\tkind: Kind,\n\t\trequired = true,\n\t\tdefaultValue: unknown = undefined,\n\t\tauto = false,\n\t\tmergeStrategy: FieldMergeStrategy | null = null,\n\t) {\n\t\tthis._kind = kind\n\t\tthis._required = required\n\t\tthis._defaultValue = defaultValue\n\t\tthis._auto = auto\n\t\tthis._mergeStrategy = mergeStrategy\n\t}\n\n\t/** Mark this field as optional (not required on insert; reads may return `null`). */\n\toptional(): FieldBuilder<Kind, false, Auto, Output, Input> {\n\t\treturn new FieldBuilder(this._kind, false, this._defaultValue, this._auto, this._mergeStrategy)\n\t}\n\n\t/**\n\t * Set a default value for this field. Implicitly makes the field optional on insert.\n\t * The value must be of the field's type (`t.number().default('x')` is a type error).\n\t */\n\tdefault(value: Input): FieldBuilder<Kind, false, Auto, Output, Input> {\n\t\treturn new FieldBuilder(this._kind, false, value, this._auto, this._mergeStrategy)\n\t}\n\n\t/**\n\t * Mark this field as auto-populated (e.g., createdAt timestamps). Developers cannot\n\t * set auto fields; the framework fills `t.timestamp().auto()` with the insert time.\n\t */\n\tauto(): FieldBuilder<Kind, false, true, Output, Input> {\n\t\treturn new FieldBuilder(this._kind, false, undefined, true, this._mergeStrategy)\n\t}\n\n\t/**\n\t * Declare a merge strategy for this field.\n\t * Controls how concurrent modifications are resolved during sync.\n\t *\n\t * @param strategy - The merge strategy to use:\n\t * - `'lww'`: Last-write-wins (default for scalar fields)\n\t * - `'counter'`: Sum of deltas from base (for numbers)\n\t * - `'max'`: Keep the maximum value (for numbers/timestamps)\n\t * - `'min'`: Keep the minimum value (for numbers/timestamps)\n\t * - `'union'`: Set-union merge (default for arrays)\n\t * - `'append-only'`: Concatenate additions (for arrays)\n\t * - `'server-authoritative'`: Always prefer the remote/server value\n\t */\n\tmerge(strategy: FieldMergeStrategy): FieldBuilder<Kind, Req, Auto, Output, Input> {\n\t\treturn new FieldBuilder(this._kind, this._required, this._defaultValue, this._auto, strategy)\n\t}\n\n\t/** @internal Build the final FieldDescriptor. Used by defineSchema(). */\n\t_build(): FieldDescriptor {\n\t\treturn {\n\t\t\tkind: this._kind,\n\t\t\trequired: this._required,\n\t\t\tdefaultValue: this._defaultValue,\n\t\t\tauto: this._auto,\n\t\t\tenumValues: null,\n\t\t\titemKind: null,\n\t\t\tmergeStrategy: this._mergeStrategy,\n\t\t\ttransitions: null,\n\t\t}\n\t}\n}\n\n/**\n * Enum values are stored verbatim (an enum column is not raw text with the stored-text\n * codec), so every value must be text SQLite stores and reads back exactly: no U+0000\n * (SQLite WASM reads TEXT up to a NUL), no lone surrogate (UTF-8 cannot hold one) and no\n * U+FFFF (the stored-text codec's escape). The table's `CHECK` used to refuse such values\n * at write time; with the value domain enforced by validation only (RT-101) the schema\n * refuses them up front.\n */\nfunction assertStorableEnumValues(values: readonly string[]): void {\n\tfor (const value of values) {\n\t\tif (typeof value !== 'string' || encodeStoredText(value) !== value) {\n\t\t\tthrow new SchemaValidationError(\n\t\t\t\t`Enum value ${JSON.stringify(value)} cannot be stored: enum values must be well-formed strings without U+0000 or U+FFFF.`,\n\t\t\t\t{ value: String(value) },\n\t\t\t)\n\t\t}\n\t}\n}\n\n/**\n * Field builder for enum fields with constrained string values.\n * Preserves the literal enum tuple type for inference.\n */\nexport class EnumFieldBuilder<\n\tValues extends readonly string[] = readonly string[],\n\tReq extends boolean = boolean,\n\tAuto extends boolean = boolean,\n> extends FieldBuilder<'enum', Req, Auto, Values[number]> {\n\tprivate readonly _enumValues: Values\n\tprivate readonly _transitions: TransitionMap | null\n\n\tconstructor(\n\t\tvalues: Values,\n\t\trequired = true,\n\t\tdefaultValue: unknown = undefined,\n\t\tauto = false,\n\t\tmergeStrategy: FieldMergeStrategy | null = null,\n\t\ttransitions: TransitionMap | null = null,\n\t) {\n\t\tsuper('enum', required, defaultValue, auto, mergeStrategy)\n\t\tthis._enumValues = values\n\t\tthis._transitions = transitions\n\t}\n\n\toverride optional(): EnumFieldBuilder<Values, false, Auto> {\n\t\treturn new EnumFieldBuilder(\n\t\t\tthis._enumValues,\n\t\t\tfalse,\n\t\t\tthis._defaultValue,\n\t\t\tthis._auto,\n\t\t\tthis._mergeStrategy,\n\t\t\tthis._transitions,\n\t\t)\n\t}\n\n\toverride default(value: Values[number]): EnumFieldBuilder<Values, false, Auto> {\n\t\treturn new EnumFieldBuilder(\n\t\t\tthis._enumValues,\n\t\t\tfalse,\n\t\t\tvalue,\n\t\t\tthis._auto,\n\t\t\tthis._mergeStrategy,\n\t\t\tthis._transitions,\n\t\t)\n\t}\n\n\toverride auto(): EnumFieldBuilder<Values, false, true> {\n\t\treturn new EnumFieldBuilder(\n\t\t\tthis._enumValues,\n\t\t\tfalse,\n\t\t\tundefined,\n\t\t\ttrue,\n\t\t\tthis._mergeStrategy,\n\t\t\tthis._transitions,\n\t\t)\n\t}\n\n\toverride merge(strategy: FieldMergeStrategy): EnumFieldBuilder<Values, Req, Auto> {\n\t\treturn new EnumFieldBuilder(\n\t\t\tthis._enumValues,\n\t\t\tthis._required,\n\t\t\tthis._defaultValue,\n\t\t\tthis._auto,\n\t\t\tstrategy,\n\t\t\tthis._transitions,\n\t\t)\n\t}\n\n\t/**\n\t * Declare allowed state transitions for this enum field.\n\t * Enables state machine validation during mutations and merges.\n\t *\n\t * @param map - Map of state to allowed next states\n\t *\n\t * @example\n\t * ```typescript\n\t * t.enum(['draft', 'pending', 'confirmed', 'cancelled']).transitions({\n\t * draft: ['pending', 'cancelled'],\n\t * pending: ['confirmed', 'cancelled'],\n\t * confirmed: [],\n\t * cancelled: [],\n\t * })\n\t * ```\n\t */\n\ttransitions(\n\t\tmap: Partial<Record<Values[number], Values[number][]>>,\n\t): EnumFieldBuilder<Values, Req, Auto> {\n\t\t// Validate that all source and target states are valid enum values\n\t\tconst validValues = new Set(this._enumValues as readonly string[])\n\t\tfor (const [state, targets] of Object.entries(map)) {\n\t\t\tif (!validValues.has(state)) {\n\t\t\t\tthrow new SchemaValidationError(\n\t\t\t\t\t`Invalid source state \"${state}\" in transition map. Valid values: ${[...validValues].join(', ')}`,\n\t\t\t\t\t{ state, validValues: [...validValues] },\n\t\t\t\t)\n\t\t\t}\n\t\t\tfor (const target of targets as string[]) {\n\t\t\t\tif (!validValues.has(target)) {\n\t\t\t\t\tthrow new SchemaValidationError(\n\t\t\t\t\t\t`Invalid target state \"${target}\" in transition from \"${state}\". Valid values: ${[...validValues].join(', ')}`,\n\t\t\t\t\t\t{ state, target, validValues: [...validValues] },\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn new EnumFieldBuilder(\n\t\t\tthis._enumValues,\n\t\t\tthis._required,\n\t\t\tthis._defaultValue,\n\t\t\tthis._auto,\n\t\t\tthis._mergeStrategy,\n\t\t\tmap as TransitionMap,\n\t\t)\n\t}\n\n\toverride _build(): FieldDescriptor {\n\t\treturn {\n\t\t\tkind: 'enum',\n\t\t\trequired: this._required,\n\t\t\tdefaultValue: this._defaultValue,\n\t\t\tauto: this._auto,\n\t\t\tenumValues: this._enumValues,\n\t\t\titemKind: null,\n\t\t\tmergeStrategy: this._mergeStrategy,\n\t\t\ttransitions: this._transitions,\n\t\t}\n\t}\n}\n\n/** The read type of the values a field builder holds (before nullability). */\nexport type FieldOutput<F> = F extends { readonly '~field': { readonly output: infer O } }\n\t? O\n\t: unknown\n\n/** The write type a field builder accepts (before optionality). */\nexport type FieldInput<F> = F extends { readonly '~field': { readonly input: infer I } }\n\t? I\n\t: unknown\n\n/**\n * Field builder for array fields. Carries the item builder's type, so\n * `t.array(t.enum(['a', 'b']))` infers `('a' | 'b')[]`.\n */\nexport class ArrayFieldBuilder<\n\tItem extends FieldBuilder = FieldBuilder,\n\tReq extends boolean = boolean,\n\tAuto extends boolean = boolean,\n> extends FieldBuilder<'array', Req, Auto, FieldOutput<Item>[], FieldInput<Item>[]> {\n\tprivate readonly _item: Item\n\n\tconstructor(\n\t\titemBuilder: Item,\n\t\trequired = true,\n\t\tdefaultValue: unknown = undefined,\n\t\tauto = false,\n\t\tmergeStrategy: FieldMergeStrategy | null = null,\n\t) {\n\t\tsuper('array', required, defaultValue, auto, mergeStrategy)\n\t\tthis._item = itemBuilder\n\t}\n\n\toverride optional(): ArrayFieldBuilder<Item, false, Auto> {\n\t\treturn new ArrayFieldBuilder(\n\t\t\tthis._item,\n\t\t\tfalse,\n\t\t\tthis._defaultValue,\n\t\t\tthis._auto,\n\t\t\tthis._mergeStrategy,\n\t\t)\n\t}\n\n\toverride default(value: FieldInput<Item>[]): ArrayFieldBuilder<Item, false, Auto> {\n\t\treturn new ArrayFieldBuilder(this._item, false, value, this._auto, this._mergeStrategy)\n\t}\n\n\toverride auto(): ArrayFieldBuilder<Item, false, true> {\n\t\treturn new ArrayFieldBuilder(this._item, false, undefined, true, this._mergeStrategy)\n\t}\n\n\toverride merge(strategy: FieldMergeStrategy): ArrayFieldBuilder<Item, Req, Auto> {\n\t\treturn new ArrayFieldBuilder(\n\t\t\tthis._item,\n\t\t\tthis._required,\n\t\t\tthis._defaultValue,\n\t\t\tthis._auto,\n\t\t\tstrategy,\n\t\t)\n\t}\n\n\toverride _build(): FieldDescriptor {\n\t\treturn {\n\t\t\tkind: 'array',\n\t\t\trequired: this._required,\n\t\t\tdefaultValue: this._defaultValue,\n\t\t\tauto: this._auto,\n\t\t\tenumValues: null,\n\t\t\titemKind: this._item._build().kind,\n\t\t\tmergeStrategy: this._mergeStrategy,\n\t\t\ttransitions: null,\n\t\t}\n\t}\n}\n\n/** Flattens an intersection of object types into one object type (for readable hovers). */\nexport type Simplify<T> = { [K in keyof T]: T[K] } & {}\n\ntype RequiredNestedKeys<F> = {\n\t[K in keyof F]: F[K] extends { readonly '~field': { readonly required: true } } ? K : never\n}[keyof F]\n\n/**\n * The value type of a `t.object({...})` field built from its nested builders. A required\n * nested key is required; an optional or defaulted nested key may be absent or `null`.\n */\nexport type ObjectFieldValue<\n\tF extends Record<string, FieldBuilder>,\n\tMode extends 'output' | 'input',\n> = Simplify<\n\t{\n\t\t[K in RequiredNestedKeys<F>]: Mode extends 'output' ? FieldOutput<F[K]> : FieldInput<F[K]>\n\t} & {\n\t\t[K in Exclude<keyof F, RequiredNestedKeys<F>>]?:\n\t\t\t| (Mode extends 'output' ? FieldOutput<F[K]> : FieldInput<F[K]>)\n\t\t\t| null\n\t}\n>\n\n/**\n * Field builder for structured object fields with a nested field schema. Carries the\n * nested builders' types, so `t.object({ theme: t.string() })` infers `{ theme: string }`.\n *\n * Each nested key merges by its own declared kind (scalars via LWW, nested\n * arrays via add-wins, nested objects recursively), so two devices editing\n * different keys of the same object offline both converge on reconnect instead\n * of one clobbering the other.\n */\nexport class ObjectFieldBuilder<\n\tFields extends Record<string, FieldBuilder> = Record<string, FieldBuilder>,\n\tReq extends boolean = boolean,\n\tAuto extends boolean = boolean,\n> extends FieldBuilder<\n\t'object',\n\tReq,\n\tAuto,\n\tObjectFieldValue<Fields, 'output'>,\n\tObjectFieldValue<Fields, 'input'>\n> {\n\tprivate readonly _fields: Fields\n\n\tconstructor(\n\t\tfields: Fields,\n\t\trequired = true,\n\t\tdefaultValue: unknown = undefined,\n\t\tauto = false,\n\t\tmergeStrategy: FieldMergeStrategy | null = null,\n\t) {\n\t\tsuper('object', required, defaultValue, auto, mergeStrategy)\n\t\tthis._fields = fields\n\t}\n\n\toverride optional(): ObjectFieldBuilder<Fields, false, Auto> {\n\t\treturn new ObjectFieldBuilder(\n\t\t\tthis._fields,\n\t\t\tfalse,\n\t\t\tthis._defaultValue,\n\t\t\tthis._auto,\n\t\t\tthis._mergeStrategy,\n\t\t)\n\t}\n\n\toverride default(\n\t\tvalue: ObjectFieldValue<Fields, 'input'>,\n\t): ObjectFieldBuilder<Fields, false, Auto> {\n\t\treturn new ObjectFieldBuilder(this._fields, false, value, this._auto, this._mergeStrategy)\n\t}\n\n\toverride auto(): ObjectFieldBuilder<Fields, false, true> {\n\t\treturn new ObjectFieldBuilder(this._fields, false, undefined, true, this._mergeStrategy)\n\t}\n\n\toverride merge(strategy: FieldMergeStrategy): ObjectFieldBuilder<Fields, Req, Auto> {\n\t\treturn new ObjectFieldBuilder(\n\t\t\tthis._fields,\n\t\t\tthis._required,\n\t\t\tthis._defaultValue,\n\t\t\tthis._auto,\n\t\t\tstrategy,\n\t\t)\n\t}\n\n\toverride _build(): FieldDescriptor {\n\t\tconst nestedFields: Record<string, FieldDescriptor> = {}\n\t\tfor (const [key, builder] of Object.entries(this._fields)) {\n\t\t\tnestedFields[key] = builder._build()\n\t\t}\n\t\treturn {\n\t\t\tkind: 'object',\n\t\t\trequired: this._required,\n\t\t\tdefaultValue: this._defaultValue,\n\t\t\tauto: this._auto,\n\t\t\tenumValues: null,\n\t\t\titemKind: null,\n\t\t\tmergeStrategy: this._mergeStrategy,\n\t\t\ttransitions: null,\n\t\t\tnestedFields,\n\t\t}\n\t}\n}\n\n/**\n * Field builder for dynamic-key JSON values. Carries a compile-time shape `T`\n * for inference while merging structurally as a convergent CRDT: a plain-object\n * value recurses as a map, an array merges add-wins, any other value is a scalar\n * leaf under last-write-wins.\n *\n * A `Date` nested inside a json value is stored as its ISO string (the canonical\n * operation form), so declare such members as `string` in `T`.\n */\nexport class JsonFieldBuilder<\n\tT = unknown,\n\tReq extends boolean = boolean,\n\tAuto extends boolean = boolean,\n> extends FieldBuilder<'json', Req, Auto, T> {\n\toverride optional(): JsonFieldBuilder<T, false, Auto> {\n\t\treturn new JsonFieldBuilder<T, false, Auto>(\n\t\t\t'json',\n\t\t\tfalse,\n\t\t\tthis._defaultValue,\n\t\t\tthis._auto,\n\t\t\tthis._mergeStrategy,\n\t\t)\n\t}\n\n\toverride default(value: T): JsonFieldBuilder<T, false, Auto> {\n\t\treturn new JsonFieldBuilder<T, false, Auto>(\n\t\t\t'json',\n\t\t\tfalse,\n\t\t\tvalue,\n\t\t\tthis._auto,\n\t\t\tthis._mergeStrategy,\n\t\t)\n\t}\n\n\toverride auto(): JsonFieldBuilder<T, false, true> {\n\t\treturn new JsonFieldBuilder<T, false, true>('json', false, undefined, true, this._mergeStrategy)\n\t}\n\n\toverride merge(strategy: FieldMergeStrategy): JsonFieldBuilder<T, Req, Auto> {\n\t\treturn new JsonFieldBuilder<T, Req, Auto>(\n\t\t\t'json',\n\t\t\tthis._required,\n\t\t\tthis._defaultValue,\n\t\t\tthis._auto,\n\t\t\tstrategy,\n\t\t)\n\t}\n\n\toverride _build(): FieldDescriptor {\n\t\treturn {\n\t\t\tkind: 'json',\n\t\t\trequired: this._required,\n\t\t\tdefaultValue: this._defaultValue,\n\t\t\tauto: this._auto,\n\t\t\tenumValues: null,\n\t\t\titemKind: null,\n\t\t\tmergeStrategy: this._mergeStrategy,\n\t\t\ttransitions: null,\n\t\t\tnestedFields: null,\n\t\t}\n\t}\n}\n\n/**\n * Field builder for secret fields (passwords, tokens, API keys).\n *\n * A secret field's value is never exposed in merge traces, DevTools, or logs\n * (it is redacted at the point traces are built). Its at-rest protection is\n * chosen with `.hashed()` (one-way, for passwords) or `.encrypted()` (reversible,\n * for tokens); the default is `encrypted`.\n */\nexport class SecretFieldBuilder<\n\tReq extends boolean = boolean,\n\tAuto extends boolean = boolean,\n> extends FieldBuilder<'secret', Req, Auto, string> {\n\tprivate readonly _secretMode: SecretMode\n\n\tconstructor(\n\t\tsecretMode: SecretMode = 'encrypted',\n\t\trequired = true,\n\t\tdefaultValue: unknown = undefined,\n\t\tauto = false,\n\t\tmergeStrategy: FieldMergeStrategy | null = null,\n\t) {\n\t\tsuper('secret', required, defaultValue, auto, mergeStrategy)\n\t\tthis._secretMode = secretMode\n\t}\n\n\t/** Store this secret as a one-way salted hash (passwords: verify, never read back). */\n\thashed(): SecretFieldBuilder<Req, Auto> {\n\t\treturn new SecretFieldBuilder(\n\t\t\t'hashed',\n\t\t\tthis._required,\n\t\t\tthis._defaultValue,\n\t\t\tthis._auto,\n\t\t\tthis._mergeStrategy,\n\t\t)\n\t}\n\n\t/** Store this secret as reversible ciphertext (tokens/keys: decrypt to use). */\n\tencrypted(): SecretFieldBuilder<Req, Auto> {\n\t\treturn new SecretFieldBuilder(\n\t\t\t'encrypted',\n\t\t\tthis._required,\n\t\t\tthis._defaultValue,\n\t\t\tthis._auto,\n\t\t\tthis._mergeStrategy,\n\t\t)\n\t}\n\n\toverride optional(): SecretFieldBuilder<false, Auto> {\n\t\treturn new SecretFieldBuilder(\n\t\t\tthis._secretMode,\n\t\t\tfalse,\n\t\t\tthis._defaultValue,\n\t\t\tthis._auto,\n\t\t\tthis._mergeStrategy,\n\t\t)\n\t}\n\n\toverride default(value: string): SecretFieldBuilder<false, Auto> {\n\t\treturn new SecretFieldBuilder(this._secretMode, false, value, this._auto, this._mergeStrategy)\n\t}\n\n\toverride auto(): SecretFieldBuilder<false, true> {\n\t\treturn new SecretFieldBuilder(this._secretMode, false, undefined, true, this._mergeStrategy)\n\t}\n\n\toverride merge(strategy: FieldMergeStrategy): SecretFieldBuilder<Req, Auto> {\n\t\treturn new SecretFieldBuilder(\n\t\t\tthis._secretMode,\n\t\t\tthis._required,\n\t\t\tthis._defaultValue,\n\t\t\tthis._auto,\n\t\t\tstrategy,\n\t\t)\n\t}\n\n\toverride _build(): FieldDescriptor {\n\t\treturn {\n\t\t\tkind: 'secret',\n\t\t\trequired: this._required,\n\t\t\tdefaultValue: this._defaultValue,\n\t\t\tauto: this._auto,\n\t\t\tenumValues: null,\n\t\t\titemKind: null,\n\t\t\tmergeStrategy: this._mergeStrategy,\n\t\t\ttransitions: null,\n\t\t\tsecretMode: this._secretMode,\n\t\t}\n\t}\n}\n\n/** The builder `t.<kind>()` returns for a scalar kind: required, not auto. */\nexport type ScalarFieldBuilder<K extends ScalarFieldKind> = FieldBuilder<\n\tK,\n\ttrue,\n\tfalse,\n\tScalarKindToType[K],\n\tScalarKindToInput[K]\n>\n\nfunction scalar<K extends ScalarFieldKind>(kind: K): ScalarFieldBuilder<K> {\n\treturn new FieldBuilder(kind, true, undefined, false)\n}\n\n/**\n * Type builder namespace. The developer's primary interface for defining field types.\n *\n * Value types: `string` and `secret` are strings, `number` is a finite number,\n * `timestamp` is integer milliseconds since the epoch (`Date` is not accepted; pass\n * `date.getTime()`), `richtext` reads as Yjs update bytes and accepts a string or bytes,\n * `blob` is a `BlobRef`.\n *\n * @example\n * ```typescript\n * import { t } from '@korajs/core'\n *\n * const fields = {\n * title: t.string(),\n * count: t.number(),\n * active: t.boolean().default(true),\n * notes: t.richtext(),\n * tags: t.array(t.string()).default([]),\n * priority: t.enum(['low', 'medium', 'high']).default('medium'),\n * settings: t.object({ theme: t.string(), fontSize: t.number() }),\n * metadata: t.json<{ source: string }>(),\n * createdAt: t.timestamp().auto(),\n * }\n * ```\n */\nexport const t = {\n\t/** A string field. */\n\tstring(): ScalarFieldBuilder<'string'> {\n\t\treturn scalar('string')\n\t},\n\n\t/** A finite-number field. */\n\tnumber(): ScalarFieldBuilder<'number'> {\n\t\treturn scalar('number')\n\t},\n\n\t/** A boolean field. */\n\tboolean(): ScalarFieldBuilder<'boolean'> {\n\t\treturn scalar('boolean')\n\t},\n\n\t/** A timestamp field: integer milliseconds since the epoch (not a `Date`). */\n\ttimestamp(): ScalarFieldBuilder<'timestamp'> {\n\t\treturn scalar('timestamp')\n\t},\n\n\t/** A collaborative rich-text field (Yjs). Reads return the Yjs update bytes. */\n\trichtext(): ScalarFieldBuilder<'richtext'> {\n\t\treturn scalar('richtext')\n\t},\n\n\t/** An enum field whose value is one of `values`. */\n\tenum<const V extends readonly string[]>(values: V): EnumFieldBuilder<V, true, false> {\n\t\tassertStorableEnumValues(values)\n\t\treturn new EnumFieldBuilder(values, true, undefined, false)\n\t},\n\n\t/** An array field whose items have the type of `itemBuilder`. */\n\tarray<Item extends FieldBuilder>(itemBuilder: Item): ArrayFieldBuilder<Item, true, false> {\n\t\treturn new ArrayFieldBuilder(itemBuilder, true, undefined, false)\n\t},\n\n\t/** A structured object field whose keys are declared by nested builders. */\n\tobject<const F extends Record<string, FieldBuilder>>(\n\t\tfields: F,\n\t): ObjectFieldBuilder<F, true, false> {\n\t\treturn new ObjectFieldBuilder(fields, true, undefined, false)\n\t},\n\n\t/** A dynamic JSON field typed as `T` (compile-time only; not validated against `T`). */\n\tjson<T = unknown>(): JsonFieldBuilder<T, true, false> {\n\t\treturn new JsonFieldBuilder<T, true, false>('json', true, undefined, false)\n\t},\n\n\t/** A blob reference field (`BlobRef`); the bytes live in the blob store. */\n\tblob(): ScalarFieldBuilder<'blob'> {\n\t\treturn scalar('blob')\n\t},\n\n\t/** A secret field (password, token): redacted from traces, hashed or encrypted at rest. */\n\tsecret(): SecretFieldBuilder<true, false> {\n\t\treturn new SecretFieldBuilder('encrypted', true, undefined, false)\n\t},\n}\n","import { isBlobRef } from '../blob/blob-ref'\nimport { isKoraBytesValue } from '../operations/op-data-binary'\nimport type { FieldDescriptor, Operation } from '../types'\n\n/**\n * One value domain (RT-86, RT-87): every value the local API accepts must be storable and\n * transmissible, unchanged, by every built-in store (client SQLite and IndexedDB; server\n * memory, SQLite and Postgres) and every transport (JSON and protobuf). The domain is\n * defined here once, enforced where values are written (`validateRecord`, after atomic\n * ops resolve) and re-checked by the server on ingest (`operationValueViolation`), so a\n * value outside it is refused with a clear error before anything stores it, never by a\n * database half-way through a sync.\n *\n * | Field type | Domain | Client SQLite / IndexedDB | Server SQLite | Server Postgres | Wire (JSON / protobuf) |\n * |----------------|-----------------------------------------------------------|---------------------------|---------------|--------------------------|------------------------|\n * | `string` | any string (U+0000 and lone surrogates included) | TEXT / string | TEXT | TEXT, lossless text codec (RT-65) | JSON string (escaped) |\n * | `enum` | one of the declared values | TEXT / string | TEXT | TEXT | JSON string |\n * | `secret` | string (stored hashed or encrypted) | TEXT | TEXT | TEXT | JSON string |\n * | `number` | finite double; `-0` is `0` | REAL / number | REAL | DOUBLE PRECISION | JSON number |\n * | `boolean` | `true` / `false` | INTEGER 0/1 / boolean | INTEGER | INTEGER | JSON boolean |\n * | `timestamp` | integer milliseconds in [-8.64e15, 8.64e15] (the `Date` range; a safe integer). Fractions are refused, not rounded | INTEGER / number | INTEGER | BIGINT | JSON number |\n * | `array` | dense array of the item kind's domain, nesting <= {@link MAX_VALUE_DEPTH} | TEXT (JSON) / array | TEXT (JSON) | JSONB (text codec) | JSON array |\n * | `object` | plain object; declared keys in their kind's domain | TEXT (JSON) / object | TEXT (JSON) | JSONB | JSON object |\n * | `json` | any JSON value: finite numbers, no `__proto__` key, nesting <= {@link MAX_VALUE_DEPTH}, not exactly `{ __kora_bytes__ }` (the wire's binary form) | TEXT (JSON) / value | TEXT (JSON) | JSONB | JSON |\n * | `blob` | a `BlobRef` | TEXT (JSON) | TEXT | TEXT | JSON object |\n * | `richtext` | Yjs update bytes (`Uint8Array` / `ArrayBuffer`) or a string | BLOB / bytes | BLOB | BYTEA | `{ $koraBytes }` / bytes |\n * | any operation | serialized size <= `maxOperationBytes` (default {@link DEFAULT_MAX_OPERATION_BYTES}) | | | | |\n *\n * Every value additionally has a canonical JSON form (core canonical-body): no `NaN`,\n * `±Infinity`, `BigInt`, `Map`, `Set`, class instances or cycles.\n */\n\n/** Smallest `t.timestamp()` value: the earliest instant a JavaScript `Date` can hold. */\nexport const TIMESTAMP_MIN_MS = -8_640_000_000_000_000\n\n/** Largest `t.timestamp()` value: the latest instant a JavaScript `Date` can hold. */\nexport const TIMESTAMP_MAX_MS = 8_640_000_000_000_000\n\n/**\n * Deepest nesting of arrays and objects inside one field value. Postgres parses JSONB\n * recursively with a stack limit, and every replica folds values recursively; 64 levels\n * is far beyond any real document.\n */\nexport const MAX_VALUE_DEPTH = 64\n\n/** Default largest serialized operation, shared by the local write path and the server. */\nexport const DEFAULT_MAX_OPERATION_BYTES = 256 * 1024\n\n/**\n * Why `value` is not a valid `t.timestamp()` value, or null when it is.\n *\n * @param value - The value\n */\nexport function timestampDomainViolation(value: unknown): string | null {\n\tif (typeof value !== 'number' || !Number.isFinite(value)) {\n\t\treturn `must be a timestamp (integer milliseconds), got ${describe(value)}`\n\t}\n\tif (!Number.isInteger(value)) {\n\t\treturn `must be a timestamp in whole milliseconds, got ${String(value)}. Round it (Math.round) or use Date.getTime()`\n\t}\n\tif (value < TIMESTAMP_MIN_MS || value > TIMESTAMP_MAX_MS) {\n\t\treturn `must be a timestamp between ${TIMESTAMP_MIN_MS} and ${TIMESTAMP_MAX_MS} (the range of a JavaScript Date), got ${String(value)}`\n\t}\n\treturn null\n}\n\n/**\n * The path of the first container nested deeper than `maxDepth`, or null.\n *\n * @param value - Any value\n * @param maxDepth - The deepest allowed nesting of arrays and objects\n */\nexport function valueDepthViolation(\n\tvalue: unknown,\n\tmaxDepth: number = MAX_VALUE_DEPTH,\n): string | null {\n\tconst walk = (current: unknown, depth: number, path: string): string | null => {\n\t\tif (current === null || typeof current !== 'object') return null\n\t\tif (depth > maxDepth) return path\n\t\tif (current instanceof Uint8Array || current instanceof ArrayBuffer) return null\n\t\tconst entries = Array.isArray(current)\n\t\t\t? current.map((item, index) => [`[${index}]`, item] as const)\n\t\t\t: Object.entries(current as Record<string, unknown>).map(\n\t\t\t\t\t([key, item]) => [`.${key}`, item] as const,\n\t\t\t\t)\n\t\tfor (const [suffix, item] of entries) {\n\t\t\tconst found = walk(item, depth + 1, `${path}${suffix}`)\n\t\t\tif (found !== null) return found\n\t\t}\n\t\treturn null\n\t}\n\treturn walk(value, 1, '')\n}\n\n/**\n * The path of the first own `__proto__` key in a value, or null. JSON can carry such a\n * key, but most JavaScript code (including object spreads into a fresh `{}` with\n * assignment) turns it into a prototype and loses it, so it is refused everywhere.\n *\n * @param value - Any value\n */\nexport function protoKeyViolation(value: unknown): string | null {\n\tconst walk = (current: unknown, path: string): string | null => {\n\t\tif (current === null || typeof current !== 'object') return null\n\t\tif (current instanceof Uint8Array || current instanceof ArrayBuffer) return null\n\t\tif (Array.isArray(current)) {\n\t\t\tfor (let index = 0; index < current.length; index++) {\n\t\t\t\tconst found = walk(current[index], `${path}[${index}]`)\n\t\t\t\tif (found !== null) return found\n\t\t\t}\n\t\t\treturn null\n\t\t}\n\t\tif (Object.prototype.hasOwnProperty.call(current, '__proto__')) return `${path}.__proto__`\n\t\tfor (const [key, item] of Object.entries(current as Record<string, unknown>)) {\n\t\t\tconst found = walk(item, `${path}.${key}`)\n\t\t\tif (found !== null) return found\n\t\t}\n\t\treturn null\n\t}\n\treturn walk(value, '')\n}\n\n/**\n * Why a field value, as an OPERATION carries it (op-data form: richtext as\n * `{ $koraBytes }` or a string, secrets in their at-rest string form), is outside the\n * field's domain, or null when it is inside. The server checks every uploaded and\n * route-written operation's data with it, so every server store and every peer holds\n * the same values (RT-86, RT-87). `null` is always accepted (a cleared field).\n *\n * @param descriptor - The field's descriptor in the schema that reads the operation\n * @param value - The value from `data`\n */\nexport function operationValueViolation(\n\tdescriptor: FieldDescriptor,\n\tvalue: unknown,\n): string | null {\n\tif (value === null || value === undefined) return null\n\tswitch (descriptor.kind) {\n\t\tcase 'string':\n\t\tcase 'secret':\n\t\t\treturn typeof value === 'string' ? null : `must be a string, got ${describe(value)}`\n\t\tcase 'enum':\n\t\t\tif (typeof value !== 'string') return `must be a string (enum), got ${describe(value)}`\n\t\t\tif (descriptor.enumValues && !descriptor.enumValues.includes(value)) {\n\t\t\t\treturn `must be one of: ${descriptor.enumValues.join(', ')}. Got \"${value}\"`\n\t\t\t}\n\t\t\treturn null\n\t\tcase 'number':\n\t\t\treturn typeof value === 'number' && Number.isFinite(value)\n\t\t\t\t? null\n\t\t\t\t: `must be a finite number, got ${describe(value)}`\n\t\tcase 'boolean':\n\t\t\treturn typeof value === 'boolean' ? null : `must be a boolean, got ${describe(value)}`\n\t\tcase 'timestamp':\n\t\t\treturn timestampDomainViolation(value)\n\t\tcase 'richtext':\n\t\t\treturn typeof value === 'string' || isKoraBytesValue(value) || value instanceof Uint8Array\n\t\t\t\t? null\n\t\t\t\t: `must be richtext (Yjs bytes or a string), got ${describe(value)}`\n\t\tcase 'blob':\n\t\t\treturn isBlobRef(value) ? null : `must be a BlobRef, got ${describe(value)}`\n\t\tcase 'array': {\n\t\t\tif (!Array.isArray(value)) return `must be an array, got ${describe(value)}`\n\t\t\tconst item = descriptor.itemKind\n\t\t\tfor (let index = 0; index < value.length; index++) {\n\t\t\t\tconst element = value[index]\n\t\t\t\tif (item === 'timestamp') {\n\t\t\t\t\tconst violation = timestampDomainViolation(element)\n\t\t\t\t\tif (violation) return `[${index}] ${violation}`\n\t\t\t\t} else if (\n\t\t\t\t\titem === 'number' &&\n\t\t\t\t\t(typeof element !== 'number' || !Number.isFinite(element))\n\t\t\t\t) {\n\t\t\t\t\treturn `[${index}] must be a finite number, got ${describe(element)}`\n\t\t\t\t} else if ((item === 'string' || item === 'enum') && typeof element !== 'string') {\n\t\t\t\t\treturn `[${index}] must be a string, got ${describe(element)}`\n\t\t\t\t} else if (item === 'boolean' && typeof element !== 'boolean') {\n\t\t\t\t\treturn `[${index}] must be a boolean, got ${describe(element)}`\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn structureViolation(value)\n\t\t}\n\t\tcase 'object': {\n\t\t\tif (typeof value !== 'object' || Array.isArray(value)) {\n\t\t\t\treturn `must be a plain object, got ${describe(value)}`\n\t\t\t}\n\t\t\tfor (const [name, nested] of Object.entries(descriptor.nestedFields ?? {})) {\n\t\t\t\tconst violation = operationValueViolation(nested, (value as Record<string, unknown>)[name])\n\t\t\t\tif (violation) return `.${name} ${violation}`\n\t\t\t}\n\t\t\treturn structureViolation(value)\n\t\t}\n\t\tcase 'json':\n\t\t\treturn structureViolation(value)\n\t}\n}\n\n/**\n * The sync wire's binary form of a top-level value (`{ __kora_bytes__: <base64> }`, what\n * beta.12 sends a `Uint8Array` as). A json or object field value of exactly that shape\n * would be read back as bytes, so it is refused.\n */\nexport const WIRE_BYTES_KEY = '__kora_bytes__'\n\n/**\n * Why a json or object field value is reserved by the wire, or null: an object whose\n * only member is `__kora_bytes__`.\n *\n * @param value - A field value\n */\nexport function reservedWireShapeViolation(value: unknown): string | null {\n\tif (value === null || typeof value !== 'object' || Array.isArray(value)) return null\n\tconst keys = Object.keys(value)\n\treturn keys.length === 1 && keys[0] === WIRE_BYTES_KEY\n\t\t? `is an object whose only key is \"${WIRE_BYTES_KEY}\", which the sync wire reserves for binary values; add another key or rename it`\n\t\t: null\n}\n\n/** Depth, `__proto__` keys and non-finite numbers inside a structured value. */\nfunction structureViolation(value: unknown): string | null {\n\tconst reserved = reservedWireShapeViolation(value)\n\tif (reserved !== null) return reserved\n\tconst deep = valueDepthViolation(value)\n\tif (deep !== null) return `nests deeper than ${MAX_VALUE_DEPTH} levels at \"${deep}\"`\n\tconst proto = protoKeyViolation(value)\n\tif (proto !== null) return `holds a \"__proto__\" key at \"${proto}\", which is not supported`\n\tconst walk = (current: unknown, path: string): string | null => {\n\t\tif (typeof current === 'number') {\n\t\t\treturn Number.isFinite(current) ? null : `holds ${String(current)} at \"${path}\"`\n\t\t}\n\t\tif (current === null || typeof current !== 'object') return null\n\t\tconst entries = Array.isArray(current)\n\t\t\t? current.map((item, index) => [`${path}[${index}]`, item] as const)\n\t\t\t: Object.entries(current as Record<string, unknown>).map(\n\t\t\t\t\t([key, item]) => [`${path}.${key}`, item] as const,\n\t\t\t\t)\n\t\tfor (const [next, item] of entries) {\n\t\t\tconst found = walk(item, next)\n\t\t\tif (found !== null) return found\n\t\t}\n\t\treturn null\n\t}\n\treturn walk(value, '')\n}\n\n/**\n * Serialized size of an operation in bytes (UTF-8 of its JSON), the measure the server\n * enforces `maxOperationBytes` with and the local write path checks before a write is\n * accepted (RT-86).\n *\n * @param op - The operation\n */\nexport function measureOperationBytes(op: Operation): number {\n\treturn utf8Length(JSON.stringify(op))\n}\n\nfunction utf8Length(text: string): number {\n\tlet bytes = 0\n\tfor (let i = 0; i < text.length; i++) {\n\t\tconst code = text.charCodeAt(i)\n\t\tif (code < 0x80) bytes += 1\n\t\telse if (code < 0x800) bytes += 2\n\t\telse if (code >= 0xd800 && code <= 0xdbff && i + 1 < text.length) {\n\t\t\tconst next = text.charCodeAt(i + 1)\n\t\t\tif (next >= 0xdc00 && next <= 0xdfff) {\n\t\t\t\tbytes += 4\n\t\t\t\ti++\n\t\t\t} else bytes += 3\n\t\t} else bytes += 3\n\t}\n\treturn bytes\n}\n\nfunction describe(value: unknown): string {\n\tif (value === null) return 'null'\n\tif (Array.isArray(value)) return 'array'\n\tif (typeof value === 'number') return Number.isFinite(value) ? 'number' : String(value)\n\tif (value instanceof Date) return 'Date'\n\treturn typeof value\n}\n","import { isBlobRef } from '../blob/blob-ref'\nimport { SchemaValidationError } from '../errors/errors'\nimport { isAtomicOp } from '../operations/atomic-ops'\nimport { NonCanonicalValueError, canonicalValue } from '../operations/canonical-body'\nimport type { CollectionDefinition, FieldDescriptor, OperationType } from '../types'\nimport {\n\tMAX_VALUE_DEPTH,\n\tprotoKeyViolation,\n\treservedWireShapeViolation,\n\ttimestampDomainViolation,\n\tvalueDepthViolation,\n} from './value-domain'\n\n/**\n * Validates a record's data against a collection's field definitions.\n * Applies defaults, rejects auto fields, and type-checks each value.\n *\n * @param collection - The collection name (for error messages)\n * @param collectionDef - The collection definition from the schema\n * @param data - The record data to validate\n * @param operationType - The operation type ('insert', 'update', 'delete')\n * @returns The validated and normalized data (with defaults applied)\n * @throws {SchemaValidationError} If validation fails\n */\nexport function validateRecord(\n\tcollection: string,\n\tcollectionDef: CollectionDefinition,\n\tdata: Record<string, unknown>,\n\toperationType: OperationType,\n): Record<string, unknown> {\n\tif (operationType === 'delete') {\n\t\treturn {}\n\t}\n\n\tconst result: Record<string, unknown> = {}\n\tconst fieldNames = Object.keys(collectionDef.fields)\n\n\t// Check for extra fields not in the schema\n\tfor (const key of Object.keys(data)) {\n\t\tif (!(key in collectionDef.fields)) {\n\t\t\tthrow new SchemaValidationError(\n\t\t\t\t`Unknown field \"${key}\" in collection \"${collection}\". Available fields: ${fieldNames.join(', ')}`,\n\t\t\t\t{ collection, field: key },\n\t\t\t)\n\t\t}\n\t}\n\n\tfor (const [fieldName, descriptor] of Object.entries(collectionDef.fields)) {\n\t\tconst value = data[fieldName]\n\t\tconst hasValue = fieldName in data\n\n\t\t// Auto fields cannot be set by the developer\n\t\tif (descriptor.auto && hasValue) {\n\t\t\tthrow new SchemaValidationError(\n\t\t\t\t`Field \"${fieldName}\" in collection \"${collection}\" is auto-populated and cannot be set manually`,\n\t\t\t\t{ collection, field: fieldName },\n\t\t\t)\n\t\t}\n\n\t\t// For updates, only validate fields that are present (partial updates)\n\t\tif (operationType === 'update') {\n\t\t\tif (hasValue) {\n\t\t\t\t// Atomic op sentinels pass through validation — they are resolved\n\t\t\t\t// to concrete values by Collection.update() before the Operation is created.\n\t\t\t\tif (isAtomicOp(value)) {\n\t\t\t\t\tresult[fieldName] = value\n\t\t\t\t} else if (value !== undefined && value !== null) {\n\t\t\t\t\tvalidateFieldValue(collection, fieldName, descriptor, value)\n\t\t\t\t\tresult[fieldName] = canonicalFieldValue(collection, fieldName, descriptor, value)\n\t\t\t\t} else {\n\t\t\t\t\tresult[fieldName] = value\n\t\t\t\t}\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\t// For inserts, apply defaults and check required fields\n\t\tif (descriptor.auto) {\n\t\t\t// Skip auto fields — they are populated by the framework\n\t\t\tcontinue\n\t\t}\n\n\t\tif (!hasValue || value === undefined) {\n\t\t\tif (descriptor.defaultValue !== undefined) {\n\t\t\t\t// Deep-copy default arrays/objects to prevent shared mutations\n\t\t\t\tresult[fieldName] =\n\t\t\t\t\ttypeof descriptor.defaultValue === 'object' && descriptor.defaultValue !== null\n\t\t\t\t\t\t? JSON.parse(JSON.stringify(descriptor.defaultValue))\n\t\t\t\t\t\t: descriptor.defaultValue\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif (descriptor.required) {\n\t\t\t\tthrow new SchemaValidationError(\n\t\t\t\t\t`Required field \"${fieldName}\" is missing in collection \"${collection}\"`,\n\t\t\t\t\t{ collection, field: fieldName },\n\t\t\t\t)\n\t\t\t}\n\n\t\t\t// Optional field with no default — omit from result\n\t\t\tcontinue\n\t\t}\n\n\t\tvalidateFieldValue(collection, fieldName, descriptor, value)\n\t\tresult[fieldName] = canonicalFieldValue(collection, fieldName, descriptor, value)\n\t}\n\n\treturn result\n}\n\n/**\n * The value in the canonical form an operation carries (core canonical-body.ts): an\n * `undefined` member of an object value is absent, a `Date` inside a json/object value is\n * its ISO string, `-0` is `0`; a value with no JSON form (Map, Set, class instance,\n * BigInt, ...) is refused here, naming the field, instead of being silently changed on\n * the way to the log (RT-72, RT-79). The record therefore holds exactly what peers will\n * see. Richtext values (Yjs bytes) are encoded by the store, not here.\n */\nfunction canonicalFieldValue(\n\tcollection: string,\n\tfieldName: string,\n\tdescriptor: FieldDescriptor,\n\tvalue: unknown,\n): unknown {\n\tif (descriptor.kind === 'richtext') return value\n\ttry {\n\t\treturn canonicalValue(value, `${collection}.${fieldName}`)\n\t} catch (error) {\n\t\tif (error instanceof NonCanonicalValueError) {\n\t\t\tthrow new SchemaValidationError(\n\t\t\t\t`Field \"${fieldName}\" in collection \"${collection}\": ${error.message}`,\n\t\t\t\t{\n\t\t\t\t\tcollection,\n\t\t\t\t\tfield: fieldName,\n\t\t\t\t\tpath: error.path,\n\t\t\t\t\treceivedType: error.receivedType,\n\t\t\t\t},\n\t\t\t)\n\t\t}\n\t\tthrow error\n\t}\n}\n\nfunction validateFieldValue(\n\tcollection: string,\n\tfieldName: string,\n\tdescriptor: FieldDescriptor,\n\tvalue: unknown,\n): void {\n\tswitch (descriptor.kind) {\n\t\tcase 'string': {\n\t\t\tif (typeof value !== 'string') {\n\t\t\t\tthrow new SchemaValidationError(\n\t\t\t\t\t`Field \"${fieldName}\" in collection \"${collection}\" must be a string, got ${typeof value}`,\n\t\t\t\t\t{ collection, field: fieldName, expectedType: 'string', receivedType: typeof value },\n\t\t\t\t)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t\tcase 'number': {\n\t\t\t// The value domain (value-domain.ts): a finite double. Infinity has no JSON form\n\t\t\t// and no store column holds it.\n\t\t\tif (typeof value !== 'number' || !Number.isFinite(value)) {\n\t\t\t\tthrow new SchemaValidationError(\n\t\t\t\t\t`Field \"${fieldName}\" in collection \"${collection}\" must be a finite number, got ${typeof value === 'number' ? String(value) : typeof value}`,\n\t\t\t\t\t{ collection, field: fieldName, expectedType: 'number', receivedType: typeof value },\n\t\t\t\t)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t\tcase 'boolean': {\n\t\t\tif (typeof value !== 'boolean') {\n\t\t\t\tthrow new SchemaValidationError(\n\t\t\t\t\t`Field \"${fieldName}\" in collection \"${collection}\" must be a boolean, got ${typeof value}`,\n\t\t\t\t\t{ collection, field: fieldName, expectedType: 'boolean', receivedType: typeof value },\n\t\t\t\t)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t\tcase 'timestamp': {\n\t\t\t// The value domain (value-domain.ts, RT-87): whole milliseconds within the range\n\t\t\t// of a JavaScript Date, which every store holds (Postgres BIGINT included).\n\t\t\tconst violation = timestampDomainViolation(value)\n\t\t\tif (violation !== null) {\n\t\t\t\tthrow new SchemaValidationError(\n\t\t\t\t\t`Field \"${fieldName}\" in collection \"${collection}\" ${violation}`,\n\t\t\t\t\t{\n\t\t\t\t\t\tcollection,\n\t\t\t\t\t\tfield: fieldName,\n\t\t\t\t\t\texpectedType: 'timestamp',\n\t\t\t\t\t\treceivedType: typeof value,\n\t\t\t\t\t\treceived: value,\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t\tcase 'enum': {\n\t\t\tif (typeof value !== 'string') {\n\t\t\t\tthrow new SchemaValidationError(\n\t\t\t\t\t`Field \"${fieldName}\" in collection \"${collection}\" must be a string (enum), got ${typeof value}`,\n\t\t\t\t\t{ collection, field: fieldName, expectedType: 'enum', receivedType: typeof value },\n\t\t\t\t)\n\t\t\t}\n\t\t\tif (descriptor.enumValues && !descriptor.enumValues.includes(value)) {\n\t\t\t\tthrow new SchemaValidationError(\n\t\t\t\t\t`Field \"${fieldName}\" in collection \"${collection}\" must be one of: ${descriptor.enumValues.join(', ')}. Got \"${value}\"`,\n\t\t\t\t\t{\n\t\t\t\t\t\tcollection,\n\t\t\t\t\t\tfield: fieldName,\n\t\t\t\t\t\tallowedValues: [...descriptor.enumValues],\n\t\t\t\t\t\treceived: value,\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t\tcase 'array': {\n\t\t\tif (!Array.isArray(value)) {\n\t\t\t\tthrow new SchemaValidationError(\n\t\t\t\t\t`Field \"${fieldName}\" in collection \"${collection}\" must be an array, got ${typeof value}`,\n\t\t\t\t\t{ collection, field: fieldName, expectedType: 'array', receivedType: typeof value },\n\t\t\t\t)\n\t\t\t}\n\t\t\tif (descriptor.itemKind) {\n\t\t\t\tconst expectedType = jsTypeForKind(descriptor.itemKind)\n\t\t\t\tfor (let i = 0; i < value.length; i++) {\n\t\t\t\t\tconst item = value[i]\n\t\t\t\t\tif (\n\t\t\t\t\t\t(descriptor.itemKind === 'timestamp' || descriptor.itemKind === 'number') &&\n\t\t\t\t\t\titem !== null &&\n\t\t\t\t\t\titem !== undefined\n\t\t\t\t\t) {\n\t\t\t\t\t\tvalidateFieldValue(\n\t\t\t\t\t\t\tcollection,\n\t\t\t\t\t\t\t`${fieldName}[${i}]`,\n\t\t\t\t\t\t\t{ ...descriptor, kind: descriptor.itemKind, itemKind: null },\n\t\t\t\t\t\t\titem,\n\t\t\t\t\t\t)\n\t\t\t\t\t}\n\t\t\t\t\tif (!matchesJsType(item, expectedType)) {\n\t\t\t\t\t\tthrow new SchemaValidationError(\n\t\t\t\t\t\t\t`Field \"${fieldName}[${i}]\" in collection \"${collection}\" must be a ${descriptor.itemKind}, got ${typeof item}`,\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tcollection,\n\t\t\t\t\t\t\t\tfield: `${fieldName}[${i}]`,\n\t\t\t\t\t\t\t\texpectedType: descriptor.itemKind,\n\t\t\t\t\t\t\t\treceivedType: typeof item,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tassertStructureInDomain(collection, fieldName, value)\n\t\t\tbreak\n\t\t}\n\n\t\tcase 'richtext': {\n\t\t\t// Richtext fields accept Uint8Array/ArrayBuffer (Yjs state) or string\n\t\t\t// (plain text initial value) — matching what the richtext serializer\n\t\t\t// encodes, so no accepted input can be silently lost downstream.\n\t\t\tif (\n\t\t\t\t!(value instanceof Uint8Array) &&\n\t\t\t\t!(value instanceof ArrayBuffer) &&\n\t\t\t\ttypeof value !== 'string'\n\t\t\t) {\n\t\t\t\tthrow new SchemaValidationError(\n\t\t\t\t\t`Field \"${fieldName}\" in collection \"${collection}\" must be a Uint8Array, ArrayBuffer, or string for richtext, got ${typeof value}`,\n\t\t\t\t\t{\n\t\t\t\t\t\tcollection,\n\t\t\t\t\t\tfield: fieldName,\n\t\t\t\t\t\texpectedType: 'richtext',\n\t\t\t\t\t\treceivedType: typeof value,\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t\tcase 'object': {\n\t\t\tif (!isPlainObject(value)) {\n\t\t\t\tthrow new SchemaValidationError(\n\t\t\t\t\t`Field \"${fieldName}\" in collection \"${collection}\" must be a plain object, got ${describeType(value)}`,\n\t\t\t\t\t{\n\t\t\t\t\t\tcollection,\n\t\t\t\t\t\tfield: fieldName,\n\t\t\t\t\t\texpectedType: 'object',\n\t\t\t\t\t\treceivedType: describeType(value),\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t}\n\t\t\t// Validate declared nested keys by their own kind. Undeclared keys are\n\t\t\t// allowed (forward-compatible), but a present declared key must type-check.\n\t\t\tif (descriptor.nestedFields) {\n\t\t\t\tfor (const [nestedName, nestedDescriptor] of Object.entries(descriptor.nestedFields)) {\n\t\t\t\t\tconst nestedValue = (value as Record<string, unknown>)[nestedName]\n\t\t\t\t\tif (nestedValue !== undefined && nestedValue !== null) {\n\t\t\t\t\t\tvalidateFieldValue(\n\t\t\t\t\t\t\tcollection,\n\t\t\t\t\t\t\t`${fieldName}.${nestedName}`,\n\t\t\t\t\t\t\tnestedDescriptor,\n\t\t\t\t\t\t\tnestedValue,\n\t\t\t\t\t\t)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tassertStructureInDomain(collection, fieldName, value)\n\t\t\tbreak\n\t\t}\n\n\t\tcase 'json': {\n\t\t\t// Dynamic-key JSON: accept any JSON-serializable value (object, array,\n\t\t\t// scalar, or null). Reject only values that cannot round-trip through\n\t\t\t// JSON, since the store persists them via JSON.stringify.\n\t\t\tconst nonJson = findNonJsonSerializable(value, fieldName)\n\t\t\tif (nonJson) {\n\t\t\t\tthrow new SchemaValidationError(\n\t\t\t\t\t`Field \"${fieldName}\" in collection \"${collection}\" must be JSON-serializable; found ${nonJson.receivedType} at \"${nonJson.path}\"`,\n\t\t\t\t\t{\n\t\t\t\t\t\tcollection,\n\t\t\t\t\t\tfield: fieldName,\n\t\t\t\t\t\texpectedType: 'json',\n\t\t\t\t\t\treceivedType: nonJson.receivedType,\n\t\t\t\t\t\tpath: nonJson.path,\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t}\n\t\t\tassertStructureInDomain(collection, fieldName, value)\n\t\t\tbreak\n\t\t}\n\n\t\tcase 'blob': {\n\t\t\t// A blob field carries a content-addressed reference, not raw bytes.\n\t\t\t// Developers upload bytes to the blob store (which returns a BlobRef)\n\t\t\t// and assign that reference here.\n\t\t\tif (!isBlobRef(value)) {\n\t\t\t\tthrow new SchemaValidationError(\n\t\t\t\t\t`Field \"${fieldName}\" in collection \"${collection}\" must be a BlobRef (from the blob store), got ${describeType(value)}`,\n\t\t\t\t\t{ collection, field: fieldName, expectedType: 'blob', receivedType: describeType(value) },\n\t\t\t\t)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t\tcase 'secret': {\n\t\t\t// A secret field takes plaintext as a string on input; the framework\n\t\t\t// applies the at-rest transform (hash or encrypt). Its value is never\n\t\t\t// exposed in traces (redacted in the merge engine).\n\t\t\tif (typeof value !== 'string') {\n\t\t\t\tthrow new SchemaValidationError(\n\t\t\t\t\t`Field \"${fieldName}\" in collection \"${collection}\" must be a string, got ${describeType(value)}`,\n\t\t\t\t\t{\n\t\t\t\t\t\tcollection,\n\t\t\t\t\t\tfield: fieldName,\n\t\t\t\t\t\texpectedType: 'secret',\n\t\t\t\t\t\treceivedType: describeType(value),\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t}\n}\n\n/**\n * The value domain of structured values (value-domain.ts): nesting depth and no own\n * `__proto__` key (JSON can carry one, but JavaScript object handling turns it into a\n * prototype and silently drops it, so it is refused everywhere instead).\n */\nfunction assertStructureInDomain(collection: string, fieldName: string, value: unknown): void {\n\tconst reserved = reservedWireShapeViolation(value)\n\tif (reserved !== null) {\n\t\tthrow new SchemaValidationError(\n\t\t\t`Field \"${fieldName}\" in collection \"${collection}\" ${reserved}.`,\n\t\t\t{ collection, field: fieldName },\n\t\t)\n\t}\n\tconst deep = valueDepthViolation(value)\n\tif (deep !== null) {\n\t\tthrow new SchemaValidationError(\n\t\t\t`Field \"${fieldName}\" in collection \"${collection}\" nests deeper than ${MAX_VALUE_DEPTH} levels (at \"${fieldName}${deep}\"). Flatten the value.`,\n\t\t\t{ collection, field: fieldName, path: `${fieldName}${deep}`, maxDepth: MAX_VALUE_DEPTH },\n\t\t)\n\t}\n\tconst proto = protoKeyViolation(value)\n\tif (proto !== null) {\n\t\tthrow new SchemaValidationError(\n\t\t\t`Field \"${fieldName}\" in collection \"${collection}\" holds a \"__proto__\" key (at \"${fieldName}${proto}\"), which cannot be stored and synced unchanged. Rename the key.`,\n\t\t\t{ collection, field: fieldName, path: `${fieldName}${proto}` },\n\t\t)\n\t}\n}\n\n/**\n * The domain check of one resolved field value (value-domain.ts), for values produced\n * after validation: an atomic op's resolved result (`op.increment(0.5)` on a timestamp,\n * an increment past the largest finite number).\n *\n * @param collection - The collection (for the message)\n * @param fieldName - The field\n * @param descriptor - The field's descriptor\n * @param value - The resolved value\n * @throws {SchemaValidationError} When the value is outside the field's domain\n */\nexport function assertResolvedFieldValue(\n\tcollection: string,\n\tfieldName: string,\n\tdescriptor: FieldDescriptor,\n\tvalue: unknown,\n): void {\n\tif (value === null || value === undefined || descriptor.kind === 'richtext') return\n\tvalidateFieldValue(collection, fieldName, descriptor, value)\n}\n\n/** True for plain data objects only (not arrays, null, or class instances). */\nfunction isPlainObject(value: unknown): boolean {\n\tif (typeof value !== 'object' || value === null || Array.isArray(value)) {\n\t\treturn false\n\t}\n\tconst proto = Object.getPrototypeOf(value)\n\treturn proto === null || proto === Object.prototype\n}\n\ninterface NonJsonSerializableValue {\n\tpath: string\n\treceivedType: string\n}\n\n/** Find the first value that cannot safely round-trip through JSON. */\nfunction findNonJsonSerializable(\n\tvalue: unknown,\n\tpath: string,\n\tseen = new WeakSet<object>(),\n): NonJsonSerializableValue | null {\n\tif (value === null) {\n\t\treturn null\n\t}\n\tconst type = typeof value\n\tif (type === 'string' || type === 'number' || type === 'boolean') {\n\t\tif (type === 'number' && !Number.isFinite(value as number)) {\n\t\t\treturn { path, receivedType: describeType(value) }\n\t\t}\n\t\treturn null\n\t}\n\tif (type === 'undefined' || type === 'function' || type === 'symbol' || type === 'bigint') {\n\t\treturn { path, receivedType: describeType(value) }\n\t}\n\tif (Array.isArray(value)) {\n\t\tfor (let index = 0; index < value.length; index++) {\n\t\t\tconst invalid = findNonJsonSerializable(value[index], `${path}[${index}]`, seen)\n\t\t\tif (invalid) return invalid\n\t\t}\n\t\treturn null\n\t}\n\tif (type === 'object') {\n\t\tconst objectValue = value as Record<string, unknown>\n\t\tif (seen.has(objectValue)) {\n\t\t\treturn { path, receivedType: 'circular object' }\n\t\t}\n\t\tseen.add(objectValue)\n\t\tfor (const [key, nestedValue] of Object.entries(objectValue)) {\n\t\t\tconst invalid = findNonJsonSerializable(nestedValue, `${path}.${key}`, seen)\n\t\t\tif (invalid) return invalid\n\t\t}\n\t\tseen.delete(objectValue)\n\t\treturn null\n\t}\n\treturn { path, receivedType: describeType(value) }\n}\n\n/** A readable type label for error messages (distinguishes array/null from object). */\nfunction describeType(value: unknown): string {\n\tif (value === null) {\n\t\treturn 'null'\n\t}\n\tif (Array.isArray(value)) {\n\t\treturn 'array'\n\t}\n\treturn typeof value\n}\n\nfunction jsTypeForKind(kind: string): string {\n\tswitch (kind) {\n\t\tcase 'string':\n\t\tcase 'enum':\n\t\t\treturn 'string'\n\t\tcase 'number':\n\t\tcase 'timestamp':\n\t\t\treturn 'number'\n\t\tcase 'boolean':\n\t\t\treturn 'boolean'\n\t\tdefault:\n\t\t\treturn 'object'\n\t}\n}\n\nfunction matchesJsType(value: unknown, expected: string): boolean {\n\t// Using explicit comparisons to satisfy Biome's useValidTypeof rule,\n\t// which requires typeof to be compared against string literals.\n\tswitch (expected) {\n\t\tcase 'string':\n\t\t\treturn typeof value === 'string'\n\t\tcase 'number':\n\t\t\treturn typeof value === 'number'\n\t\tcase 'boolean':\n\t\t\treturn typeof value === 'boolean'\n\t\tcase 'object':\n\t\t\treturn typeof value === 'object'\n\t\tdefault:\n\t\t\treturn false\n\t}\n}\n","import type { Operation, VersionVector } from '../types'\nimport { topologicalSort } from './topological-sort'\n\n/**\n * Create an empty version vector.\n */\nexport function createVersionVector(): VersionVector {\n\treturn new Map()\n}\n\n/**\n * Merge two version vectors by taking the max sequence number for each node.\n * This is commutative, associative, and idempotent.\n */\nexport function mergeVectors(a: VersionVector, b: VersionVector): VersionVector {\n\tconst merged = new Map(a)\n\tfor (const [nodeId, seq] of b) {\n\t\tmerged.set(nodeId, Math.max(merged.get(nodeId) ?? 0, seq))\n\t}\n\treturn merged\n}\n\n/**\n * Advance a version vector for a specific node to a new sequence number.\n * Only advances forward — if the current value is higher, no change is made.\n */\nexport function advanceVector(vector: VersionVector, nodeId: string, seq: number): VersionVector {\n\tconst updated = new Map(vector)\n\tupdated.set(nodeId, Math.max(updated.get(nodeId) ?? 0, seq))\n\treturn updated\n}\n\n/**\n * Returns true if vector `a` dominates vector `b` — meaning `a` has seen\n * everything `b` has seen. Formally: for every nodeId in b, a[nodeId] >= b[nodeId].\n */\nexport function dominates(a: VersionVector, b: VersionVector): boolean {\n\tfor (const [nodeId, bSeq] of b) {\n\t\tif ((a.get(nodeId) ?? 0) < bSeq) return false\n\t}\n\treturn true\n}\n\n/**\n * Returns true if two version vectors are exactly equal.\n */\nexport function vectorsEqual(a: VersionVector, b: VersionVector): boolean {\n\tif (a.size !== b.size) return false\n\tfor (const [nodeId, aSeq] of a) {\n\t\tif (b.get(nodeId) !== aSeq) return false\n\t}\n\treturn true\n}\n\n/**\n * Operation log interface for computing deltas.\n * getRange may be async (for DB-backed implementations) or sync (for in-memory).\n */\nexport interface OperationLog {\n\tgetRange(nodeId: string, fromSeq: number, toSeq: number): Operation[] | Promise<Operation[]>\n}\n\n/**\n * Compute the operations that `local` has but `remote` does not.\n * Returns operations in causal (topological) order.\n *\n * @param localVector - The local version vector\n * @param remoteVector - The remote version vector\n * @param operationLog - The operation log to fetch operations from\n * @returns Operations sorted in causal order\n */\nexport async function computeDelta(\n\tlocalVector: VersionVector,\n\tremoteVector: VersionVector,\n\toperationLog: OperationLog,\n): Promise<Operation[]> {\n\tconst missing: Operation[] = []\n\tfor (const [nodeId, localSeq] of localVector) {\n\t\tconst remoteSeq = remoteVector.get(nodeId) ?? 0\n\t\tif (localSeq > remoteSeq) {\n\t\t\tconst ops = await operationLog.getRange(nodeId, remoteSeq + 1, localSeq)\n\t\t\tmissing.push(...ops)\n\t\t}\n\t}\n\treturn topologicalSort(missing)\n}\n\n/**\n * Serialize a version vector to a JSON-compatible string.\n */\nexport function serializeVector(vector: VersionVector): string {\n\tconst entries = [...vector.entries()].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n\treturn JSON.stringify(entries)\n}\n\n/**\n * Deserialize a version vector from its serialized string form.\n */\nexport function deserializeVector(s: string): VersionVector {\n\tconst entries = JSON.parse(s) as [string, number][]\n\treturn new Map(entries)\n}\n","import type { SchemaDefinition } from '../types'\nimport {\n\tcollectSchemaScopeValueKeys,\n\tgetCollectionScopeBindings,\n\thasSchemaSyncRules,\n\tisCollectionSyncScoped,\n} from './sync-scope-bindings'\n\n/**\n * Per-collection scope map: `{ collectionName: { field: value, ... } }`\n *\n * Used to filter which operations a client should receive during sync.\n */\nexport type ScopeMap = Record<string, Record<string, unknown>>\n\n/**\n * Build a per-collection scope map from the schema's scope declarations\n * and the client's flat scope values.\n *\n * Supports both legacy `collection.scope` arrays and declarative `schema.sync`\n * rules (`sync: { todos: { where: { userId: true } } }`).\n *\n * When `schema.sync` is present, only collections with sync rules or legacy\n * scope fields are included in the result. Other collections are omitted so\n * sync engines treat them as out of scope (partial sync).\n *\n * @param schema - The schema definition with scope declarations\n * @param scopeValues - Flat key-value scope values from the client\n * @returns A per-collection scope map\n *\n * @example\n * ```typescript\n * // Schema declares: sales.scope = ['orgId', 'storeId']\n * // Client provides: { orgId: 'org-123', storeId: 'store-456' }\n * // Result: { sales: { orgId: 'org-123', storeId: 'store-456' }, products: {} }\n * ```\n */\nexport function buildScopeMap(\n\tschema: SchemaDefinition,\n\tscopeValues: Record<string, unknown>,\n): ScopeMap {\n\tconst result: ScopeMap = {}\n\tconst partialSync = hasSchemaSyncRules(schema)\n\n\tfor (const collName of Object.keys(schema.collections)) {\n\t\tif (partialSync && !isCollectionSyncScoped(schema, collName)) {\n\t\t\tcontinue\n\t\t}\n\n\t\tconst bindings = getCollectionScopeBindings(schema, collName)\n\t\tif (bindings) {\n\t\t\tconst collScope: Record<string, unknown> = {}\n\t\t\tfor (const [field, scopeKey] of Object.entries(bindings)) {\n\t\t\t\tif (scopeKey in scopeValues) {\n\t\t\t\t\tcollScope[field] = scopeValues[scopeKey]\n\t\t\t\t}\n\t\t\t}\n\t\t\tresult[collName] = collScope\n\t\t} else {\n\t\t\t// Collections without scope declarations are fully visible\n\t\t\tresult[collName] = {}\n\t\t}\n\t}\n\n\treturn result\n}\n\nexport { collectSchemaScopeValueKeys as collectSchemaScopeFields } from './sync-scope-bindings'\n","import type { ScopeMap } from './build-scope-map'\n\n/**\n * Reserved key in a server scope grant that carries VERIFIED claim values\n * (for example `{ userId: <jwt sub>, orgId: <from your user store> }`).\n *\n * An auth provider usually cannot know the sync schema, so instead of listing\n * every collection it returns `{ $claims: { userId } }` and the sync server binds\n * each schema-scoped collection from those values when the session starts. A\n * collection whose scope bindings cannot all be resolved from the claims is\n * denied (fail closed), never widened to \"everything\".\n *\n * Collection names must start with a letter, so `$claims` can never collide with\n * a real collection. Any consumer that does not expand it sees a key that matches\n * no collection, which is also fail-closed.\n */\nexport const SCOPE_CLAIMS_KEY = '$claims' as const\n\n/**\n * Build a server scope grant from verified claim values, optionally combined\n * with explicit per-collection grants. Explicit entries win over claim-derived\n * bindings for the same collection.\n *\n * @param claims - Verified scope values, keyed by the scope binding names your\n * schema uses (`scope: ['userId']` binds the `userId` value)\n * @param explicit - Optional explicit per-collection predicates\n * @returns A scope grant suitable for `AuthContext.scopes`\n *\n * @example\n * ```typescript\n * return { userId: payload.sub, scopes: claimScopes({ userId: payload.sub, orgId }) }\n * ```\n */\nexport function claimScopes(claims: Record<string, unknown>, explicit?: ScopeMap): ScopeMap {\n\treturn { ...(explicit ?? {}), [SCOPE_CLAIMS_KEY]: { ...claims } }\n}\n\n/**\n * Read the verified claim values carried by a scope grant, if any.\n *\n * @param grant - A scope grant (possibly containing {@link SCOPE_CLAIMS_KEY})\n * @returns The claim values, or null when the grant has none\n */\nexport function getScopeClaims(grant: ScopeMap | undefined): Record<string, unknown> | null {\n\tif (!grant) return null\n\tconst claims = grant[SCOPE_CLAIMS_KEY]\n\treturn claims && typeof claims === 'object' ? claims : null\n}\n","import type { SchemaDefinition } from '../types'\nimport { collectSchemaScopeValueKeys } from './sync-scope-bindings'\n\n/**\n * Collect every unique scope field name declared across all collections.\n *\n * @deprecated Use {@link collectSchemaScopeValueKeys} instead.\n */\nexport function collectSchemaScopeFields(schema: SchemaDefinition): string[] {\n\treturn collectSchemaScopeValueKeys(schema)\n}\n\n/**\n * Extract flat scope values from JWT (or auth) claims using schema scope field names.\n *\n * Resolution order for each scope field:\n * 1. Top-level claim with the same name\n * 2. Nested `claims.scope[field]` object\n * 3. `userId` falls back to the standard JWT `sub` claim\n *\n * @param schema - Schema with per-collection scope declarations\n * @param claims - Decoded JWT claims (unverified; client-side scope hints only)\n * @returns Flat key-value map suitable for {@link buildScopeMap}\n */\nexport function extractScopeValuesFromClaims(\n\tschema: SchemaDefinition,\n\tclaims: Record<string, unknown>,\n): Record<string, unknown> {\n\tconst scopeFields = collectSchemaScopeValueKeys(schema)\n\tif (scopeFields.length === 0) {\n\t\treturn {}\n\t}\n\n\tconst nestedScope = claims.scope\n\tconst scopeObject =\n\t\ttypeof nestedScope === 'object' && nestedScope !== null && !Array.isArray(nestedScope)\n\t\t\t? (nestedScope as Record<string, unknown>)\n\t\t\t: {}\n\n\tconst result: Record<string, unknown> = {}\n\n\tfor (const field of scopeFields) {\n\t\tif (field in claims) {\n\t\t\tresult[field] = claims[field]\n\t\t\tcontinue\n\t\t}\n\n\t\tif (field in scopeObject) {\n\t\t\tresult[field] = scopeObject[field]\n\t\t\tcontinue\n\t\t}\n\n\t\tif (field === 'userId' && typeof claims.sub === 'string') {\n\t\t\tresult.userId = claims.sub\n\t\t}\n\t}\n\n\treturn result\n}\n","/**\n * Offline-safe sequence formatting.\n *\n * Format tokens:\n * - `{date}` → YYYYMMDD (current date)\n * - `{node4}` → first 4 characters of nodeId\n * - `{node8}` → first 8 characters of nodeId\n * - `{seq}` → zero-padded counter (default 4 digits)\n * - `{seq:N}` → zero-padded counter with N digits\n *\n * @example\n * ```typescript\n * formatSequenceValue('INV-{date}-{node4}-{seq}', 42, 'a1b2c3d4e5f6')\n * // → \"INV-20260508-a1b2-0042\"\n *\n * formatSequenceValue('ORDER-{seq:6}', 7, 'node-id')\n * // → \"ORDER-000007\"\n * ```\n */\nexport function formatSequenceValue(\n\ttemplate: string,\n\tcounter: number,\n\tnodeId: string,\n\tnow?: Date,\n): string {\n\tconst date = now ?? new Date()\n\tconst yyyy = String(date.getUTCFullYear())\n\tconst mm = String(date.getUTCMonth() + 1).padStart(2, '0')\n\tconst dd = String(date.getUTCDate()).padStart(2, '0')\n\tconst dateStr = `${yyyy}${mm}${dd}`\n\n\treturn template.replace(/\\{([^}]+)\\}/g, (_match, token: string) => {\n\t\tif (token === 'date') return dateStr\n\t\tif (token === 'node4') return nodeId.slice(0, 4)\n\t\tif (token === 'node8') return nodeId.slice(0, 8)\n\t\tif (token === 'seq') return String(counter).padStart(4, '0')\n\t\tif (token.startsWith('seq:')) {\n\t\t\tconst width = Number.parseInt(token.slice(4), 10)\n\t\t\tif (Number.isNaN(width) || width < 1) {\n\t\t\t\treturn String(counter).padStart(4, '0')\n\t\t\t}\n\t\t\treturn String(counter).padStart(width, '0')\n\t\t}\n\t\t// Unknown token — leave as-is\n\t\treturn `{${token}}`\n\t})\n}\n\n/**\n * Default format when none is provided: `{name}-{seq:4}`.\n */\nexport function defaultSequenceFormat(name: string): string {\n\treturn `${name}-{seq:4}`\n}\n","import type { FieldBuilder } from '../schema/types'\nimport type { FieldDescriptor } from '../types'\n\n/**\n * A single migration step describing a schema change.\n */\nexport type MigrationStep =\n\t| { type: 'addField'; collection: string; field: string; descriptor: FieldDescriptor }\n\t| { type: 'removeField'; collection: string; field: string; descriptor?: FieldDescriptor }\n\t| { type: 'renameField'; collection: string; from: string; to: string }\n\t| { type: 'addIndex'; collection: string; field: string }\n\t| { type: 'removeIndex'; collection: string; field: string }\n\t| {\n\t\t\ttype: 'backfill'\n\t\t\tcollection: string\n\t\t\ttransform: (record: Record<string, unknown>) => Record<string, unknown>\n\t\t\t/** Reverse transform for rollback. If not provided, backfill is not safely reversible. */\n\t\t\treverseTransform?: (record: Record<string, unknown>) => Record<string, unknown>\n\t\t\t/**\n\t\t\t * Rewrite rows on this device only, without writing operations (so nothing\n\t\t\t * syncs). Default false: every changed record is written through the normal\n\t\t\t * local write path as an update operation (mutation name `migration:v<N>`).\n\t\t\t */\n\t\t\tlocalOnly?: boolean\n\t }\n\n/** Options for {@link MigrationBuilder.backfill}. */\nexport interface BackfillOptions {\n\t/** Reverse transform for rollback support. */\n\treverseTransform?: (record: Record<string, unknown>) => Record<string, unknown>\n\t/**\n\t * Rewrite rows on this device only, without operations, so the change never syncs.\n\t * Use it for device-local derived data. Default false: backfilled values are written\n\t * as update operations and sync like any other write.\n\t */\n\tlocalOnly?: boolean\n}\n\n/**\n * A completed migration definition containing ordered steps and optional rollback steps.\n */\nexport interface MigrationDefinition {\n\treadonly steps: readonly MigrationStep[]\n\t/** Explicitly defined rollback steps. If undefined, inverse steps are auto-generated. */\n\treadonly rollbackSteps: readonly MigrationStep[] | undefined\n\t/** Whether this migration can be safely rolled back. */\n\treadonly safelyReversible: boolean\n}\n\n/**\n * Builder for defining rollback steps explicitly.\n * Used with the `.down()` method on MigrationBuilder.\n *\n * @example\n * ```typescript\n * migrate()\n * .addField('todos', 'priority', t.enum(['low', 'medium', 'high']).default('medium'))\n * .addIndex('todos', 'priority')\n * .down((rollback) => {\n * rollback\n * .removeIndex('todos', 'priority')\n * .removeField('todos', 'priority')\n * })\n * ```\n */\nexport class RollbackBuilder {\n\tprivate _steps: MigrationStep[] = []\n\n\t/**\n\t * Add a field during rollback (to reverse a removeField).\n\t */\n\taddField(collection: string, field: string, builder: FieldBuilder): RollbackBuilder {\n\t\tthis._steps.push({ type: 'addField', collection, field, descriptor: builder._build() })\n\t\treturn this\n\t}\n\n\t/**\n\t * Remove a field during rollback (to reverse an addField).\n\t */\n\tremoveField(collection: string, field: string): RollbackBuilder {\n\t\tthis._steps.push({ type: 'removeField', collection, field })\n\t\treturn this\n\t}\n\n\t/**\n\t * Rename a field during rollback (to reverse a renameField).\n\t */\n\trenameField(collection: string, from: string, to: string): RollbackBuilder {\n\t\tthis._steps.push({ type: 'renameField', collection, from, to })\n\t\treturn this\n\t}\n\n\t/**\n\t * Add an index during rollback (to reverse a removeIndex).\n\t */\n\taddIndex(collection: string, field: string): RollbackBuilder {\n\t\tthis._steps.push({ type: 'addIndex', collection, field })\n\t\treturn this\n\t}\n\n\t/**\n\t * Remove an index during rollback (to reverse an addIndex).\n\t */\n\tremoveIndex(collection: string, field: string): RollbackBuilder {\n\t\tthis._steps.push({ type: 'removeIndex', collection, field })\n\t\treturn this\n\t}\n\n\t/**\n\t * Run a backfill during rollback (to reverse a previous backfill).\n\t */\n\tbackfill(\n\t\tcollection: string,\n\t\ttransform: (record: Record<string, unknown>) => Record<string, unknown>,\n\t): RollbackBuilder {\n\t\tthis._steps.push({ type: 'backfill', collection, transform })\n\t\treturn this\n\t}\n\n\t/**\n\t * Get the accumulated rollback steps.\n\t */\n\t_getSteps(): readonly MigrationStep[] {\n\t\treturn [...this._steps]\n\t}\n}\n\n/**\n * Fluent builder for defining schema migrations.\n *\n * Each method returns a new builder instance (immutable).\n *\n * @example\n * ```typescript\n * migrate()\n * .addField('products', 'taxInclusive', t.boolean().default(false))\n * .renameField('products', 'cost', 'costPrice')\n * .backfill('products', (record) => ({\n * taxInclusive: record.taxRate > 0,\n * }))\n * ```\n */\nexport class MigrationBuilder implements MigrationDefinition {\n\treadonly steps: readonly MigrationStep[]\n\treadonly rollbackSteps: readonly MigrationStep[] | undefined\n\treadonly safelyReversible: boolean\n\n\tconstructor(\n\t\tsteps: readonly MigrationStep[] = [],\n\t\trollbackSteps?: readonly MigrationStep[],\n\t\tsafelyReversible?: boolean,\n\t) {\n\t\tthis.steps = steps\n\t\tthis.rollbackSteps = rollbackSteps\n\t\t// Default: safely reversible if no backfill steps without reverseTransform\n\t\tthis.safelyReversible = safelyReversible ?? this._computeSafelyReversible(steps, rollbackSteps)\n\t}\n\n\t/**\n\t * Add a new field to a collection.\n\t * The field builder provides the type and default value.\n\t */\n\taddField(collection: string, field: string, builder: FieldBuilder): MigrationBuilder {\n\t\treturn new MigrationBuilder([\n\t\t\t...this.steps,\n\t\t\t{ type: 'addField', collection, field, descriptor: builder._build() },\n\t\t])\n\t}\n\n\t/**\n\t * Remove a field from a collection.\n\t * Optionally accepts a field builder to preserve the descriptor for rollback.\n\t * Without the descriptor, rollback of this step requires a custom `.down()`.\n\t *\n\t * @param collection - The collection name\n\t * @param field - The field name to remove\n\t * @param builder - Optional field builder preserving the type info for rollback\n\t */\n\tremoveField(collection: string, field: string, builder?: FieldBuilder): MigrationBuilder {\n\t\tconst step: MigrationStep = builder\n\t\t\t? { type: 'removeField', collection, field, descriptor: builder._build() }\n\t\t\t: { type: 'removeField', collection, field }\n\t\treturn new MigrationBuilder([...this.steps, step])\n\t}\n\n\t/**\n\t * Rename a field in a collection.\n\t * Implemented as ALTER TABLE RENAME COLUMN (SQLite 3.25+).\n\t */\n\trenameField(collection: string, from: string, to: string): MigrationBuilder {\n\t\treturn new MigrationBuilder([...this.steps, { type: 'renameField', collection, from, to }])\n\t}\n\n\t/**\n\t * Add an index on a field.\n\t */\n\taddIndex(collection: string, field: string): MigrationBuilder {\n\t\treturn new MigrationBuilder([...this.steps, { type: 'addIndex', collection, field }])\n\t}\n\n\t/**\n\t * Remove an index on a field.\n\t */\n\tremoveIndex(collection: string, field: string): MigrationBuilder {\n\t\treturn new MigrationBuilder([...this.steps, { type: 'removeIndex', collection, field }])\n\t}\n\n\t/**\n\t * Backfill records in a collection using a transform function.\n\t * The transform receives each live record (typed values, as the app reads them) and\n\t * returns the fields to change. Runs after structural changes (addField, renameField,\n\t * etc.), in the same transaction as them and the schema version write.\n\t *\n\t * Changed records are written as update operations (mutation name `migration:v<N>`)\n\t * through the normal local write path, so backfilled values sync. Pass\n\t * `{ localOnly: true }` for device-local data that must not sync.\n\t *\n\t * @param collection - The collection name\n\t * @param transform - Forward transform function\n\t * @param reverseOrOptions - Reverse transform for rollback support, or options\n\t */\n\tbackfill(\n\t\tcollection: string,\n\t\ttransform: (record: Record<string, unknown>) => Record<string, unknown>,\n\t\treverseOrOptions?:\n\t\t\t| ((record: Record<string, unknown>) => Record<string, unknown>)\n\t\t\t| BackfillOptions,\n\t): MigrationBuilder {\n\t\tconst options: BackfillOptions =\n\t\t\ttypeof reverseOrOptions === 'function'\n\t\t\t\t? { reverseTransform: reverseOrOptions }\n\t\t\t\t: (reverseOrOptions ?? {})\n\t\treturn new MigrationBuilder([\n\t\t\t...this.steps,\n\t\t\t{\n\t\t\t\ttype: 'backfill',\n\t\t\t\tcollection,\n\t\t\t\ttransform,\n\t\t\t\t...(options.reverseTransform ? { reverseTransform: options.reverseTransform } : {}),\n\t\t\t\t...(options.localOnly ? { localOnly: true } : {}),\n\t\t\t},\n\t\t])\n\t}\n\n\t/**\n\t * Define explicit rollback steps for this migration.\n\t * If not called, inverse steps are auto-generated from forward steps.\n\t *\n\t * @param fn - Function that receives a RollbackBuilder to define rollback steps\n\t * @returns A new MigrationBuilder with the rollback steps attached\n\t *\n\t * @example\n\t * ```typescript\n\t * migrate()\n\t * .addField('todos', 'priority', t.enum(['low', 'medium', 'high']).default('medium'))\n\t * .addIndex('todos', 'priority')\n\t * .down((rollback) => {\n\t * rollback\n\t * .removeIndex('todos', 'priority')\n\t * .removeField('todos', 'priority')\n\t * })\n\t * ```\n\t */\n\tdown(fn: (rollback: RollbackBuilder) => void): MigrationBuilder {\n\t\tconst rollbackBuilder = new RollbackBuilder()\n\t\tfn(rollbackBuilder)\n\t\tconst rbSteps = rollbackBuilder._getSteps()\n\t\treturn new MigrationBuilder(this.steps, rbSteps, true)\n\t}\n\n\t/**\n\t * Determine if a migration is safely reversible based on its steps.\n\t * A migration is not safely reversible if:\n\t * - It has a backfill step without a reverseTransform and no explicit rollback\n\t * - It has a removeField without a stored descriptor and no explicit rollback\n\t */\n\tprivate _computeSafelyReversible(\n\t\tsteps: readonly MigrationStep[],\n\t\trollbackSteps: readonly MigrationStep[] | undefined,\n\t): boolean {\n\t\t// Explicit rollback steps override auto-detection\n\t\tif (rollbackSteps !== undefined) {\n\t\t\treturn true\n\t\t}\n\n\t\tfor (const step of steps) {\n\t\t\tif (step.type === 'backfill' && !step.reverseTransform) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tif (step.type === 'removeField' && !step.descriptor) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\n\t\treturn true\n\t}\n}\n\n/**\n * Start building a migration.\n *\n * @returns A new MigrationBuilder\n *\n * @example\n * ```typescript\n * import { migrate, t } from '@korajs/core'\n *\n * const migration = migrate()\n * .addField('products', 'taxInclusive', t.boolean().default(false))\n * .renameField('products', 'cost', 'costPrice')\n * ```\n */\nexport function migrate(): MigrationBuilder {\n\treturn new MigrationBuilder()\n}\n","import { KoraError } from '../errors/errors'\nimport type { FieldDescriptor } from '../types'\nimport type { MigrationStep } from './migration-builder'\n\n/**\n * A migration that includes both forward (up) and backward (down) steps.\n * Rollback steps are applied in reverse order of the forward steps.\n */\nexport interface ReversibleMigration {\n\treadonly up: readonly MigrationStep[]\n\treadonly down: readonly MigrationStep[]\n\treadonly fromVersion: number\n\treadonly toVersion: number\n}\n\n/**\n * Error thrown when a migration step cannot be automatically rolled back\n * and no explicit down step has been provided.\n */\nexport class MigrationRollbackError extends KoraError {\n\tconstructor(step: MigrationStep) {\n\t\tsuper(\n\t\t\t`Cannot auto-generate rollback for \"${step.type}\" step on collection \"${step.collection}\". Provide an explicit .down() definition for this migration.`,\n\t\t\t'MIGRATION_ROLLBACK',\n\t\t\t{ stepType: step.type, collection: step.collection },\n\t\t)\n\t\tthis.name = 'MigrationRollbackError'\n\t}\n}\n\n/**\n * Determines whether a migration step can be automatically rolled back\n * without explicit developer-provided down steps.\n *\n * Auto-rollback is possible when the inverse operation is deterministic:\n * - addField -> removeField (drop the added column)\n * - addIndex -> removeIndex (drop the added index)\n * - removeIndex -> addIndex (re-create the index)\n * - renameField -> renameField (swap from/to names)\n *\n * Steps that CANNOT auto-rollback:\n * - removeField: the field descriptor is lost (need it to re-create the column)\n * - backfill: data transforms are not reversible\n *\n * @param step - The forward migration step to check\n * @returns true if the step can be auto-rolled back\n */\nexport function canAutoRollback(step: MigrationStep): boolean {\n\tswitch (step.type) {\n\t\tcase 'addField':\n\t\tcase 'addIndex':\n\t\tcase 'removeIndex':\n\t\tcase 'renameField':\n\t\t\treturn true\n\t\tcase 'removeField':\n\t\tcase 'backfill':\n\t\t\treturn false\n\t}\n}\n\n/**\n * Generates rollback steps for a list of forward migration steps.\n * Steps are reversed in order (last forward step becomes first rollback step).\n *\n * For steps that cannot be auto-rolled back, throws a MigrationRollbackError.\n * Use canAutoRollback() to check before calling, or provide explicit down steps\n * via the MigrationBuilder .down() API.\n *\n * @param forwardSteps - The forward migration steps to generate rollbacks for\n * @returns Array of rollback steps in reverse execution order\n * @throws MigrationRollbackError if any step cannot be auto-rolled back\n */\nexport function generateRollbackSteps(forwardSteps: readonly MigrationStep[]): MigrationStep[] {\n\tconst rollbackSteps: MigrationStep[] = []\n\n\t// Process in reverse order so rollback undoes changes in the opposite sequence\n\tfor (let i = forwardSteps.length - 1; i >= 0; i--) {\n\t\tconst step = forwardSteps[i]\n\t\tif (step === undefined) continue\n\n\t\tconst rollback = generateSingleRollbackStep(step)\n\t\trollbackSteps.push(rollback)\n\t}\n\n\treturn rollbackSteps\n}\n\n/**\n * Generate the inverse of a single migration step.\n * @internal\n */\nfunction generateSingleRollbackStep(step: MigrationStep): MigrationStep {\n\tswitch (step.type) {\n\t\tcase 'addField':\n\t\t\treturn { type: 'removeField', collection: step.collection, field: step.field }\n\n\t\tcase 'removeField':\n\t\t\t// removeField lacks the descriptor needed to re-create the column.\n\t\t\t// The developer must provide an explicit down step.\n\t\t\tif (step.descriptor) {\n\t\t\t\treturn {\n\t\t\t\t\ttype: 'addField',\n\t\t\t\t\tcollection: step.collection,\n\t\t\t\t\tfield: step.field,\n\t\t\t\t\tdescriptor: step.descriptor,\n\t\t\t\t}\n\t\t\t}\n\t\t\tthrow new MigrationRollbackError(step)\n\n\t\tcase 'renameField':\n\t\t\t// Reverse the rename: swap from and to\n\t\t\treturn { type: 'renameField', collection: step.collection, from: step.to, to: step.from }\n\n\t\tcase 'addIndex':\n\t\t\treturn { type: 'removeIndex', collection: step.collection, field: step.field }\n\n\t\tcase 'removeIndex':\n\t\t\treturn { type: 'addIndex', collection: step.collection, field: step.field }\n\n\t\tcase 'backfill':\n\t\t\t// Backfills with a reverseTransform can be auto-reversed\n\t\t\tif (step.reverseTransform) {\n\t\t\t\treturn {\n\t\t\t\t\ttype: 'backfill',\n\t\t\t\t\tcollection: step.collection,\n\t\t\t\t\ttransform: step.reverseTransform,\n\t\t\t\t}\n\t\t\t}\n\t\t\tthrow new MigrationRollbackError(step)\n\t}\n}\n\n/**\n * Create a ReversibleMigration from forward steps, explicit down steps, and version info.\n *\n * If explicit down steps are provided, they are used as-is.\n * If no explicit down steps are provided, auto-generation is attempted.\n *\n * @param upSteps - The forward migration steps\n * @param downSteps - Optional explicit rollback steps (overrides auto-generation)\n * @param fromVersion - The schema version before the migration\n * @param toVersion - The schema version after the migration\n * @returns A complete ReversibleMigration\n * @throws MigrationRollbackError if auto-generation fails and no explicit down steps provided\n */\nexport function createReversibleMigration(\n\tupSteps: readonly MigrationStep[],\n\tdownSteps: readonly MigrationStep[] | null,\n\tfromVersion: number,\n\ttoVersion: number,\n): ReversibleMigration {\n\tconst down = downSteps !== null ? [...downSteps] : generateRollbackSteps(upSteps)\n\n\treturn {\n\t\tup: [...upSteps],\n\t\tdown,\n\t\tfromVersion,\n\t\ttoVersion,\n\t}\n}\n","import { quoteIdent } from '../schema/quote-ident'\nimport { collectionIndexName, sqlDefaultLiteral } from '../schema/sql-gen'\nimport type { FieldDescriptor } from '../types'\nimport type { MigrationDefinition, MigrationStep } from './migration-builder'\nimport { generateRollbackSteps } from './migration-rollback'\n\n/**\n * Convert migration steps to SQL statements.\n *\n * Structural steps (addField, removeField, renameField, addIndex, removeIndex)\n * produce SQL. Backfill steps are skipped (handled at the application layer\n * by reading rows and applying the transform function).\n *\n * @param steps - The migration steps from a MigrationBuilder\n * @returns Array of SQL statements for structural changes\n */\nexport function migrationStepsToSQL(steps: readonly MigrationStep[]): string[] {\n\tconst statements: string[] = []\n\n\tfor (const step of steps) {\n\t\tswitch (step.type) {\n\t\t\tcase 'addField':\n\t\t\t\tstatements.push(addFieldSQL(step.collection, step.field, step.descriptor))\n\t\t\t\tbreak\n\t\t\tcase 'removeField':\n\t\t\t\t// SQLite 3.35+ supports DROP COLUMN. For broader compat, we mark\n\t\t\t\t// the column as nullable so it can be ignored in queries.\n\t\t\t\t// Drop is preferred when available.\n\t\t\t\tstatements.push(\n\t\t\t\t\t`ALTER TABLE ${quoteIdent(step.collection)} DROP COLUMN ${quoteIdent(step.field)}`,\n\t\t\t\t)\n\t\t\t\tbreak\n\t\t\tcase 'renameField':\n\t\t\t\t// SQLite 3.25+ supports RENAME COLUMN\n\t\t\t\tstatements.push(\n\t\t\t\t\t`ALTER TABLE ${quoteIdent(step.collection)} RENAME COLUMN ${quoteIdent(step.from)} TO ${quoteIdent(step.to)}`,\n\t\t\t\t)\n\t\t\t\tbreak\n\t\t\tcase 'addIndex':\n\t\t\t\tstatements.push(\n\t\t\t\t\t`CREATE INDEX IF NOT EXISTS ${quoteIdent(collectionIndexName(step.collection, step.field))} ON ${quoteIdent(step.collection)} (${quoteIdent(step.field)})`,\n\t\t\t\t)\n\t\t\t\tbreak\n\t\t\tcase 'removeIndex':\n\t\t\t\tstatements.push(\n\t\t\t\t\t`DROP INDEX IF EXISTS ${quoteIdent(collectionIndexName(step.collection, step.field))}`,\n\t\t\t\t)\n\t\t\t\tbreak\n\t\t\tcase 'backfill':\n\t\t\t\t// Backfills are handled by the store at runtime, not via SQL.\n\t\t\t\tbreak\n\t\t}\n\t}\n\n\treturn statements\n}\n\n/**\n * Generate SQL statements to roll back a migration.\n *\n * Uses the migration's explicit rollback steps if available,\n * otherwise auto-generates inverse steps from the forward steps.\n *\n * Backfill steps in the rollback are skipped (handled at the application layer).\n *\n * @param migration - The migration definition to generate rollback SQL for\n * @returns Array of SQL statements that undo the migration's structural changes\n *\n * @example\n * ```typescript\n * const migration = migrate()\n * .addField('todos', 'priority', t.enum(['low', 'medium', 'high']).default('medium'))\n * .addIndex('todos', 'priority')\n *\n * const rollbackSQL = rollbackStepsToSQL(migration)\n * // ['DROP INDEX IF EXISTS \"idx_5_todos_priority\"',\n * // 'ALTER TABLE \"todos\" DROP COLUMN \"priority\"']\n * ```\n */\nexport function rollbackStepsToSQL(migration: MigrationDefinition): string[] {\n\t// Use explicit rollback steps if provided, otherwise auto-generate from forward steps\n\tconst rollbackSteps = migration.rollbackSteps ?? generateRollbackSteps(migration.steps)\n\treturn migrationStepsToSQL(rollbackSteps)\n}\n\n/**\n * Produce an ALTER TABLE ADD COLUMN statement for a new field.\n */\nfunction addFieldSQL(collection: string, field: string, descriptor: FieldDescriptor): string {\n\tconst sqlType = mapFieldType(descriptor)\n\tconst parts = [`ALTER TABLE ${quoteIdent(collection)} ADD COLUMN ${quoteIdent(field)}`, sqlType]\n\n\tif (descriptor.defaultValue !== undefined) {\n\t\tparts.push(`DEFAULT ${sqlDefaultLiteral(descriptor.defaultValue)}`)\n\t}\n\n\t// No CHECK for enums and no NOT NULL: the value domain is enforced by validation only\n\t// (RT-101).\n\treturn parts.join(' ')\n}\n\nfunction mapFieldType(descriptor: FieldDescriptor): string {\n\tswitch (descriptor.kind) {\n\t\tcase 'string':\n\t\t\treturn 'TEXT'\n\t\tcase 'number':\n\t\t\treturn 'REAL'\n\t\tcase 'boolean':\n\t\t\treturn 'INTEGER'\n\t\tcase 'enum':\n\t\t\treturn 'TEXT'\n\t\tcase 'timestamp':\n\t\t\treturn 'INTEGER'\n\t\tcase 'array':\n\t\t\treturn 'TEXT'\n\t\tcase 'object':\n\t\t\treturn 'TEXT'\n\t\tcase 'json':\n\t\t\treturn 'TEXT'\n\t\tcase 'blob':\n\t\t\treturn 'TEXT'\n\t\tcase 'secret':\n\t\t\treturn 'TEXT'\n\t\tcase 'richtext':\n\t\t\treturn 'BLOB'\n\t}\n}\n","import type { CollectionDefinition, FieldDescriptor, FieldKind, SchemaDefinition } from '../types'\n\n/**\n * Output of the proto definition generator.\n * Contains the .proto file text, a type mapping, and a JSON descriptor\n * compatible with protobufjs's `Root.fromJSON()`.\n */\nexport interface ProtoOutput {\n\t/** The generated .proto file content as a string */\n\tproto: string\n\t/** TypeScript type map: field name -> protobuf type */\n\ttypeMap: Map<string, string>\n\t/** JSON descriptor for dynamic protobufjs usage (no .proto file needed) */\n\tjsonDescriptor: Record<string, unknown>\n}\n\n/**\n * Maps a Kora FieldKind to its protobuf scalar type string.\n * Array and enum kinds are handled separately because they\n * produce composite types (repeated, generated enum).\n */\nconst SCALAR_TYPE_MAP: Record<Exclude<FieldKind, 'array' | 'enum'>, string> = {\n\tstring: 'string',\n\tnumber: 'double',\n\tboolean: 'bool',\n\ttimestamp: 'int64',\n\trichtext: 'bytes',\n\t// object/json values travel as JSON-serialized strings on the proto wire.\n\tobject: 'string',\n\tjson: 'string',\n\t// A blob field carries a JSON-serialized content-addressed reference, not bytes.\n\tblob: 'string',\n\t// A secret field's stored value is a JSON string (ciphertext or hash).\n\tsecret: 'string',\n}\n\n/**\n * Maps a Kora FieldKind (when used as an array item) to its protobuf scalar type.\n * Only scalar kinds can be array items.\n */\nconst ARRAY_ITEM_TYPE_MAP: Record<string, string> = {\n\tstring: 'string',\n\tnumber: 'double',\n\tboolean: 'bool',\n\ttimestamp: 'int64',\n}\n\n/**\n * Converts a collection name (snake_case) to PascalCase for protobuf message names.\n * E.g., \"todo_items\" becomes \"TodoItems\", \"todos\" becomes \"Todos\".\n */\nfunction toPascalCase(name: string): string {\n\treturn name\n\t\t.split('_')\n\t\t.map((part) => part.charAt(0).toUpperCase() + part.slice(1))\n\t\t.join('')\n}\n\n/**\n * Converts a camelCase field name to snake_case for protobuf field names.\n * E.g., \"dueDate\" becomes \"due_date\", \"createdAt\" becomes \"created_at\".\n */\nfunction toSnakeCase(name: string): string {\n\treturn name.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`)\n}\n\n/**\n * Resolves the protobuf type for a single field descriptor.\n *\n * @param fieldName - The field name (used for enum type naming)\n * @param descriptor - The Kora field descriptor\n * @param messageName - Parent message name (used for scoping enum type names)\n * @returns The protobuf type string\n */\nfunction resolveProtoType(\n\tfieldName: string,\n\tdescriptor: FieldDescriptor,\n\tmessageName: string,\n): string {\n\tif (descriptor.kind === 'enum') {\n\t\treturn `${messageName}${toPascalCase(fieldName)}`\n\t}\n\tif (descriptor.kind === 'array') {\n\t\tconst itemType = descriptor.itemKind\n\t\t\t? (ARRAY_ITEM_TYPE_MAP[descriptor.itemKind] ?? 'string')\n\t\t\t: 'string'\n\t\treturn itemType\n\t}\n\treturn SCALAR_TYPE_MAP[descriptor.kind as Exclude<FieldKind, 'array' | 'enum'>]\n}\n\n/**\n * Generates a protobuf enum definition for a Kora enum field.\n * Protobuf enums require the first value to be 0, so we add\n * an UNSPECIFIED sentinel as field 0.\n */\nfunction generateEnumBlock(\n\tenumTypeName: string,\n\tenumValues: readonly string[],\n\tindent: string,\n): string {\n\tconst lines: string[] = []\n\tlines.push(`${indent}enum ${enumTypeName} {`)\n\t// Proto3 requires field number 0 as a default/unspecified value\n\tlines.push(`${indent}\\t${enumTypeName.toUpperCase()}_UNSPECIFIED = 0;`)\n\tfor (let i = 0; i < enumValues.length; i++) {\n\t\tconst value = enumValues[i]\n\t\tif (value === undefined) continue\n\t\tlines.push(`${indent}\\t${enumTypeName.toUpperCase()}_${value.toUpperCase()} = ${i + 1};`)\n\t}\n\tlines.push(`${indent}}`)\n\treturn lines.join('\\n')\n}\n\n/**\n * Generates a protobuf message definition for a single Kora collection.\n * Includes nested enum types for any enum fields.\n *\n * @param collectionName - The collection name from the schema\n * @param collection - The collection definition\n * @param typeMap - Accumulator map for field->type mappings\n * @returns The proto message block as a string\n */\nfunction generateCollectionMessage(\n\tcollectionName: string,\n\tcollection: CollectionDefinition,\n\ttypeMap: Map<string, string>,\n): string {\n\tconst messageName = `${toPascalCase(collectionName)}Record`\n\tconst lines: string[] = []\n\tconst nestedEnums: string[] = []\n\n\tlines.push(`message ${messageName} {`)\n\n\t// Field 1 is always \"id\"\n\tlines.push('\\tstring id = 1;')\n\ttypeMap.set(`${collectionName}.id`, 'string')\n\n\tlet fieldNumber = 2\n\tconst entries = Object.entries(collection.fields)\n\n\tfor (const [fieldName, descriptor] of entries) {\n\t\tconst protoFieldName = toSnakeCase(fieldName)\n\t\tconst protoType = resolveProtoType(fieldName, descriptor, messageName)\n\t\tconst mapKey = `${collectionName}.${fieldName}`\n\n\t\tif (descriptor.kind === 'enum' && descriptor.enumValues) {\n\t\t\tconst enumTypeName = `${messageName}${toPascalCase(fieldName)}`\n\t\t\tnestedEnums.push(generateEnumBlock(enumTypeName, descriptor.enumValues, '\\t'))\n\t\t\ttypeMap.set(mapKey, enumTypeName)\n\t\t\tlines.push(`\\t${enumTypeName} ${protoFieldName} = ${fieldNumber};`)\n\t\t} else if (descriptor.kind === 'array') {\n\t\t\ttypeMap.set(mapKey, `repeated ${protoType}`)\n\t\t\tlines.push(`\\trepeated ${protoType} ${protoFieldName} = ${fieldNumber};`)\n\t\t} else {\n\t\t\ttypeMap.set(mapKey, protoType)\n\t\t\tlines.push(`\\t${protoType} ${protoFieldName} = ${fieldNumber};`)\n\t\t}\n\n\t\tfieldNumber++\n\t}\n\n\t// Insert nested enums before the closing brace\n\tif (nestedEnums.length > 0) {\n\t\t// Place enum definitions after the last field\n\t\tlines.push('')\n\t\tfor (const enumBlock of nestedEnums) {\n\t\t\tlines.push(enumBlock)\n\t\t}\n\t}\n\n\tlines.push('}')\n\treturn lines.join('\\n')\n}\n\n/**\n * The KoraOperation message — the wire format for individual operations.\n * Field assignments match the sync protocol specification from CLAUDE.md.\n */\nconst KORA_OPERATION_MESSAGE = `message KoraOperation {\n\\tstring id = 1;\n\\tstring node_id = 2;\n\\tstring type = 3;\n\\tstring collection = 4;\n\\tstring record_id = 5;\n\\tbytes data = 6;\n\\tbytes previous_data = 7;\n\\tint64 wall_time = 8;\n\\tint32 logical = 9;\n\\tstring timestamp_node_id = 10;\n\\tint64 sequence_number = 11;\n\\trepeated string causal_deps = 12;\n\\tint32 schema_version = 13;\n}`\n\n/**\n * The OperationBatch message — batches operations for sync transfer.\n */\nconst OPERATION_BATCH_MESSAGE = `message OperationBatch {\n\\trepeated KoraOperation operations = 1;\n\\tbool is_final = 2;\n\\tbytes retractions_json = 3;\n}`\n\n/**\n * The HandshakeMessage — initiates a sync session with version vector exchange.\n */\nconst HANDSHAKE_MESSAGE = `message HandshakeMessage {\n\\tmap<string, int64> version_vector = 1;\n\\tint32 schema_version = 2;\n\\tstring node_id = 3;\n\\tstring scope_exit_policy = 4;\n}`\n\n/**\n * The HandshakeResponse — server acknowledges and returns its version vector.\n */\nconst HANDSHAKE_RESPONSE_MESSAGE = `message HandshakeResponse {\n\\tmap<string, int64> version_vector = 1;\n\\tint32 schema_version = 2;\n\\tbytes accepted_scope_json = 3;\n\\tbytes accepted_downlink_scopes_json = 4;\n\\tbytes accepted_uplink_scopes_json = 5;\n}`\n\n/**\n * The Acknowledgment message — confirms receipt of an operation batch.\n */\nconst ACKNOWLEDGMENT_MESSAGE = `message Acknowledgment {\n\\tint64 sequence_number = 1;\n\\tstring node_id = 2;\n}`\n\n/**\n * Builds a JSON descriptor object compatible with protobufjs Root.fromJSON().\n * This allows runtime usage of the proto definitions without parsing .proto text.\n */\nfunction buildJsonDescriptor(schema: SchemaDefinition): Record<string, unknown> {\n\tconst nested: Record<string, unknown> = {}\n\n\t// Per-collection record messages\n\tfor (const [collectionName, collection] of Object.entries(schema.collections)) {\n\t\tconst messageName = `${toPascalCase(collectionName)}Record`\n\t\tconst fields: Record<string, unknown> = {\n\t\t\tid: { type: 'string', id: 1 },\n\t\t}\n\t\tconst nestedTypes: Record<string, unknown> = {}\n\n\t\tlet fieldNumber = 2\n\t\tfor (const [fieldName, descriptor] of Object.entries(collection.fields)) {\n\t\t\tconst protoFieldName = toSnakeCase(fieldName)\n\t\t\tconst fieldDef: Record<string, unknown> = { id: fieldNumber }\n\n\t\t\tif (descriptor.kind === 'enum' && descriptor.enumValues) {\n\t\t\t\tconst enumTypeName = `${messageName}${toPascalCase(fieldName)}`\n\t\t\t\tfieldDef.type = enumTypeName\n\n\t\t\t\t// Build enum values object for protobufjs\n\t\t\t\tconst enumValuesObj: Record<string, number> = {\n\t\t\t\t\t[`${enumTypeName.toUpperCase()}_UNSPECIFIED`]: 0,\n\t\t\t\t}\n\t\t\t\tfor (let i = 0; i < descriptor.enumValues.length; i++) {\n\t\t\t\t\tconst val = descriptor.enumValues[i]\n\t\t\t\t\tif (val === undefined) continue\n\t\t\t\t\tenumValuesObj[`${enumTypeName.toUpperCase()}_${val.toUpperCase()}`] = i + 1\n\t\t\t\t}\n\t\t\t\tnestedTypes[enumTypeName] = { values: enumValuesObj }\n\t\t\t} else if (descriptor.kind === 'array') {\n\t\t\t\tconst itemType = descriptor.itemKind\n\t\t\t\t\t? (ARRAY_ITEM_TYPE_MAP[descriptor.itemKind] ?? 'string')\n\t\t\t\t\t: 'string'\n\t\t\t\tfieldDef.type = itemType\n\t\t\t\tfieldDef.rule = 'repeated'\n\t\t\t} else {\n\t\t\t\tfieldDef.type = SCALAR_TYPE_MAP[descriptor.kind as Exclude<FieldKind, 'array' | 'enum'>]\n\t\t\t}\n\n\t\t\tfields[protoFieldName] = fieldDef\n\t\t\tfieldNumber++\n\t\t}\n\n\t\tconst messageDescriptor: Record<string, unknown> = { fields }\n\t\tif (Object.keys(nestedTypes).length > 0) {\n\t\t\tmessageDescriptor.nested = nestedTypes\n\t\t}\n\t\tnested[messageName] = messageDescriptor\n\t}\n\n\t// KoraOperation\n\tnested.KoraOperation = {\n\t\tfields: {\n\t\t\tid: { type: 'string', id: 1 },\n\t\t\tnode_id: { type: 'string', id: 2 },\n\t\t\ttype: { type: 'string', id: 3 },\n\t\t\tcollection: { type: 'string', id: 4 },\n\t\t\trecord_id: { type: 'string', id: 5 },\n\t\t\tdata: { type: 'bytes', id: 6 },\n\t\t\tprevious_data: { type: 'bytes', id: 7 },\n\t\t\twall_time: { type: 'int64', id: 8 },\n\t\t\tlogical: { type: 'int32', id: 9 },\n\t\t\ttimestamp_node_id: { type: 'string', id: 10 },\n\t\t\tsequence_number: { type: 'int64', id: 11 },\n\t\t\tcausal_deps: { type: 'string', id: 12, rule: 'repeated' },\n\t\t\tschema_version: { type: 'int32', id: 13 },\n\t\t},\n\t}\n\n\t// OperationBatch\n\tnested.OperationBatch = {\n\t\tfields: {\n\t\t\toperations: { type: 'KoraOperation', id: 1, rule: 'repeated' },\n\t\t\tis_final: { type: 'bool', id: 2 },\n\t\t\tretractions_json: { type: 'bytes', id: 3 },\n\t\t},\n\t}\n\n\t// HandshakeMessage\n\tnested.HandshakeMessage = {\n\t\tfields: {\n\t\t\tversion_vector: { keyType: 'string', type: 'int64', id: 1 },\n\t\t\tschema_version: { type: 'int32', id: 2 },\n\t\t\tnode_id: { type: 'string', id: 3 },\n\t\t\tscope_exit_policy: { type: 'string', id: 4 },\n\t\t},\n\t}\n\n\t// HandshakeResponse\n\tnested.HandshakeResponse = {\n\t\tfields: {\n\t\t\tversion_vector: { keyType: 'string', type: 'int64', id: 1 },\n\t\t\tschema_version: { type: 'int32', id: 2 },\n\t\t\taccepted_scope_json: { type: 'bytes', id: 3 },\n\t\t\taccepted_downlink_scopes_json: { type: 'bytes', id: 4 },\n\t\t\taccepted_uplink_scopes_json: { type: 'bytes', id: 5 },\n\t\t},\n\t}\n\n\t// Acknowledgment\n\tnested.Acknowledgment = {\n\t\tfields: {\n\t\t\tsequence_number: { type: 'int64', id: 1 },\n\t\t\tnode_id: { type: 'string', id: 2 },\n\t\t},\n\t}\n\n\treturn {\n\t\tnested: {\n\t\t\tkora: { nested },\n\t\t},\n\t}\n}\n\n/**\n * Generates Protocol Buffer definitions from a Kora schema.\n *\n * Produces three outputs:\n * 1. A `.proto` file string conforming to proto3 syntax\n * 2. A type map linking Kora field paths to protobuf types\n * 3. A JSON descriptor for runtime protobufjs usage via `Root.fromJSON()`\n *\n * The generated definitions include:\n * - Per-collection record messages with proper type mappings\n * - Nested enum types for enum fields\n * - `KoraOperation` wrapper for the sync wire format\n * - `OperationBatch` for batched sync transfers\n * - `HandshakeMessage` / `HandshakeResponse` for sync session initiation\n * - `Acknowledgment` for delivery confirmation\n *\n * @param schema - A validated SchemaDefinition from defineSchema()\n * @returns ProtoOutput with proto text, type map, and JSON descriptor\n *\n * @example\n * ```typescript\n * import { defineSchema, t, generateProtoDefinitions } from '@korajs/core'\n *\n * const schema = defineSchema({\n * version: 1,\n * collections: {\n * todos: {\n * fields: {\n * title: t.string(),\n * completed: t.boolean().default(false),\n * }\n * }\n * }\n * })\n *\n * const { proto, typeMap, jsonDescriptor } = generateProtoDefinitions(schema)\n * // proto is a valid .proto file string\n * // typeMap maps \"todos.title\" -> \"string\", \"todos.completed\" -> \"bool\"\n * // jsonDescriptor can be loaded with protobuf.Root.fromJSON()\n * ```\n */\nexport function generateProtoDefinitions(schema: SchemaDefinition): ProtoOutput {\n\tconst typeMap = new Map<string, string>()\n\tconst sections: string[] = []\n\n\t// Proto3 header\n\tsections.push('syntax = \"proto3\";')\n\tsections.push('')\n\tsections.push('package kora;')\n\n\t// Per-collection messages\n\tconst collectionEntries = Object.entries(schema.collections)\n\tif (collectionEntries.length > 0) {\n\t\tsections.push('')\n\t\tsections.push('// Collection record messages')\n\t\tfor (const [collectionName, collection] of collectionEntries) {\n\t\t\tsections.push('')\n\t\t\tsections.push(generateCollectionMessage(collectionName, collection, typeMap))\n\t\t}\n\t}\n\n\t// Sync protocol messages\n\tsections.push('')\n\tsections.push('// Sync protocol messages')\n\tsections.push('')\n\tsections.push(KORA_OPERATION_MESSAGE)\n\tsections.push('')\n\tsections.push(OPERATION_BATCH_MESSAGE)\n\tsections.push('')\n\tsections.push(HANDSHAKE_MESSAGE)\n\tsections.push('')\n\tsections.push(HANDSHAKE_RESPONSE_MESSAGE)\n\tsections.push('')\n\tsections.push(ACKNOWLEDGMENT_MESSAGE)\n\n\tconst proto = `${sections.join('\\n')}\\n`\n\tconst jsonDescriptor = buildJsonDescriptor(schema)\n\n\treturn { proto, typeMap, jsonDescriptor }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAudO,IAAM,mBAAmB;AAAA,EAC/B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACD;AAMO,IAAM,uBAAuB,CAAC,aAAa,QAAQ,QAAQ,QAAQ,SAAS;;;AC/d5E,IAAM,gBAAN,MAAoB;AAAA,EACT,uBAAuB,oBAAI,IAAoB;AAAA,EACxD,sBAAqC;AAAA;AAAA;AAAA;AAAA,EAK7C,mBAAyB;AACxB,SAAK,sBAAsB;AAAA,EAC5B;AAAA;AAAA;AAAA;AAAA,EAKA,mBAAyB;AACxB,SAAK,sBAAsB;AAAA,EAC5B;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,eAAe,YAAoB,eAAkC;AACpE,UAAM,OAAiB,CAAC;AACxB,UAAM,mBAAmB,KAAK,qBAAqB,IAAI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