/** * RvLite - Lightweight Vector Database SDK * * A unified database combining: * - Vector similarity search * - SQL queries with vector distance operations * - Cypher property graph queries * - SPARQL RDF triple queries * * @example * ```typescript * import { RvLite } from 'rvlite'; * * const db = new RvLite({ dimensions: 384 }); * * // Insert vectors * db.insert([0.1, 0.2, ...], { text: "Hello world" }); * * // Search similar * const results = db.search([0.1, 0.2, ...], 5); * * // SQL with vector distance * db.sql("SELECT * FROM vectors WHERE distance(embedding, ?) < 0.5"); * * // Cypher graph queries * db.cypher("CREATE (p:Person {name: 'Alice'})"); * * // SPARQL RDF queries * db.sparql("SELECT ?s ?p ?o WHERE { ?s ?p ?o }"); * ``` */ export * from '../dist/wasm/rvlite.js'; /** * Check if @ruvector/rvf-wasm is installed for persistent RVF storage. */ export declare function isRvfAvailable(): boolean; /** * Get the active storage backend. */ export declare function getStorageBackend(): 'rvf' | 'indexeddb' | 'memory'; export interface RvLiteConfig { dimensions?: number; distanceMetric?: 'cosine' | 'euclidean' | 'dotproduct'; /** Force a specific storage backend. Auto-detected if omitted. */ backend?: 'rvf' | 'indexeddb' | 'memory' | 'auto'; /** Path to RVF file for persistent storage. */ rvfPath?: string; } export interface SearchResult { id: string; score: number; metadata?: Record; } export interface QueryResult { columns?: string[]; rows?: unknown[][]; [key: string]: unknown; } /** * Main RvLite class - wraps the WASM module with a friendly API */ export declare class RvLite { private wasm; private config; private initialized; constructor(config?: RvLiteConfig); /** * Initialize the WASM module (called automatically on first use) */ init(): Promise; private ensureInit; /** * Insert a vector with optional metadata */ insert(vector: number[], metadata?: Record): Promise; /** * Insert a vector with a specific ID */ insertWithId(id: string, vector: number[], metadata?: Record): Promise; /** * Search for similar vectors */ search(query: number[], k?: number): Promise; /** * Get a vector by ID */ get(id: string): Promise<{ vector: number[]; metadata?: Record; } | null>; /** * Delete a vector by ID */ delete(id: string): Promise; /** * Get the number of vectors */ len(): Promise; /** * Execute a SQL query * * Supports vector distance operations: * - distance(col, vector) - Calculate distance * - vec_search(col, vector, k) - Find k nearest */ sql(query: string): Promise; /** * Execute a Cypher graph query * * Supports: * - CREATE (n:Label {props}) * - MATCH (n:Label) WHERE ... RETURN n * - CREATE (a)-[:REL]->(b) */ cypher(query: string): Promise; /** * Get Cypher graph statistics */ cypherStats(): Promise<{ node_count: number; edge_count: number; }>; /** * Execute a SPARQL query * * Supports SELECT, ASK queries over RDF triples */ sparql(query: string): Promise; /** * Add an RDF triple */ addTriple(subject: string, predicate: string, object: string, graph?: string): Promise; /** * Get the number of triples */ tripleCount(): Promise; /** * Export database state to JSON */ exportJson(): Promise; /** * Import database state from JSON */ importJson(data: unknown): Promise; /** * Save to IndexedDB (browser only) */ save(): Promise; /** * Load from IndexedDB (browser only) */ static load(config?: RvLiteConfig): Promise; /** * Clear IndexedDB storage (browser only) */ static clearStorage(): Promise; /** * Factory method: create an RvLite instance backed by an RVF file. * * Opens or creates an RVF file at the given path, initialises the WASM * module, and (when available) uses `@ruvector/rvf-wasm` for vector storage. * Falls back to standard WASM + JSON-based RVF if the optional package is * not installed. * * @param config - Standard RvLiteConfig plus a required `rvfPath`. * @returns A fully-initialised RvLite instance with data loaded from the * RVF file (if it already exists). */ static createWithRvf(config: RvLiteConfig & { rvfPath: string; }): Promise; /** * Export the current vector state to an RVF file. * * When `@ruvector/rvf-wasm` is available the export uses the native RVF * binary writer. Otherwise the method falls back to a JSON payload * wrapped with RVF header metadata so the file can be identified as RVF. * * @param filePath - Destination path for the RVF file. */ saveToRvf(filePath: string): Promise; /** * Import vector data from an RVF file. * * Parses the RVF format (either native binary via `@ruvector/rvf-wasm` or * the JSON-based fallback envelope) and loads vectors + metadata into the * current instance. * * @param filePath - Source path of the RVF file to import. */ loadFromRvf(filePath: string): Promise; /** @internal handle to optional @ruvector/rvf-wasm module */ private rvfModule; /** @internal path to the RVF backing file (set by createWithRvf) */ private rvfPath; } /** * Create a new RvLite instance (async factory). * * When `@ruvector/rvf-wasm` is installed, persistence uses RVF format. * Override with `config.backend` to force a specific backend. */ export declare function createRvLite(config?: RvLiteConfig): Promise; /** * Generate embeddings using various providers */ export interface EmbeddingProvider { embed(text: string): Promise; embedBatch(texts: string[]): Promise; } /** * Create an embedding provider using Anthropic Claude */ export declare function createAnthropicEmbeddings(apiKey?: string): EmbeddingProvider; /** * Semantic Memory - Higher-level API for AI memory applications * * Combines vector search with knowledge graph storage */ export declare class SemanticMemory { private db; private embedder?; constructor(db: RvLite, embedder?: EmbeddingProvider); /** * Store a memory with semantic embedding */ store(key: string, content: string, embedding?: number[], metadata?: Record): Promise; /** * Query memories by semantic similarity */ query(queryText: string, embedding?: number[], k?: number): Promise; /** * Add a relationship between memories */ addRelation(fromKey: string, relation: string, toKey: string): Promise; /** * Find related memories through graph traversal */ findRelated(key: string, depth?: number): Promise; } /** * JSON-based RVF file structure used when `@ruvector/rvf-wasm` is not * available. The envelope wraps the standard export_json() payload with * header metadata so the file is self-describing. */ export interface RvfFileEnvelope { /** RVF format version (currently 1). */ rvf_version: number; /** Magic identifier — always "RVF1". */ magic: 'RVF1'; /** ISO-8601 timestamp of when the file was created. */ created_at: string; /** Vector dimensions stored in this file. */ dimensions: number; /** Distance metric used. */ distance_metric: string; /** The full database state (as returned by `exportJson()`). */ payload: unknown; } /** * Browser-side writer lease that uses IndexedDB for lock coordination. * * Only one writer may hold the lease for a given `storeId` at a time. * The holder sends heartbeats (timestamp updates) every 10 seconds so * that other tabs / windows can detect stale leases. * * Auto-releases on `beforeunload` to avoid dangling locks. */ export declare class BrowserWriterLease { private heartbeatInterval; private storeId; private static readonly DB_NAME; private static readonly STORE_NAME; private static readonly HEARTBEAT_MS; private static readonly DEFAULT_STALE_MS; private static openDb; private static idbPut; private static idbGet; private static idbDelete; /** * Try to acquire the writer lease for the given store. * * @param storeId - Unique identifier for the rvlite store being locked. * @param timeout - Maximum time in ms to wait for the lease (default 5000). * @returns `true` if the lease was acquired, `false` on timeout. */ acquire(storeId: string, timeout?: number): Promise; /** * Release the currently held lease. */ release(): Promise; /** * Check whether the lease for `storeId` is stale (the holder has stopped * sending heartbeats). * * @param storeId - Store identifier. * @param thresholdMs - Staleness threshold (default 30 000 ms). */ static isStale(storeId: string, thresholdMs?: number): Promise; private _holderId; private holderId; private startHeartbeat; private stopHeartbeat; private registerUnloadHandler; } /** * Describes the synchronisation state between the RVF vector store epoch * and the metadata (SQL / Cypher / SPARQL) epoch. */ export interface EpochState { /** Monotonic epoch counter for the RVF vector store. */ rvfEpoch: number; /** Monotonic epoch counter for metadata stores. */ metadataEpoch: number; /** Human-readable sync status. */ status: 'synchronized' | 'rvf_ahead' | 'metadata_ahead'; } /** * Inspect the current epoch state of an RvLite instance. * * The epochs are stored as metadata keys inside the database itself * (`_rvlite_rvf_epoch` and `_rvlite_metadata_epoch`). * * @param db - An initialised RvLite instance. * @returns The current epoch state. */ export declare function checkEpochSync(db: RvLite): Promise; /** * Reconcile mismatched epochs by advancing the lagging store to match * the leading one. * * - **rvf_ahead**: bumps the metadata epoch to match the RVF epoch. * - **metadata_ahead**: bumps the RVF epoch to match the metadata epoch. * - **synchronized**: no-op. * * @param db - An initialised RvLite instance. * @param state - The epoch state (as returned by `checkEpochSync`). */ export declare function reconcileEpochs(db: RvLite, state: EpochState): Promise; /** * Convenience helper: increment the RVF epoch by 1. * Call this after every successful vector-store mutation. */ export declare function bumpRvfEpoch(db: RvLite): Promise; /** * Convenience helper: increment the metadata epoch by 1. * Call this after every successful metadata mutation (SQL / Cypher / SPARQL). */ export declare function bumpMetadataEpoch(db: RvLite): Promise; export default RvLite; //# sourceMappingURL=index.d.ts.map