@nicia-ai/typegraph 0.22.0 → 0.24.0

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.
Files changed (73) hide show
  1. package/dist/{ast-CSLbPIOC.d.ts → ast-C8S37w1A.d.ts} +1 -1
  2. package/dist/{ast-DogwbBqA.d.cts → ast-dgLhLOg0.d.cts} +1 -1
  3. package/dist/backend/postgres/index.cjs +165 -48
  4. package/dist/backend/postgres/index.cjs.map +1 -1
  5. package/dist/backend/postgres/index.d.cts +43 -6
  6. package/dist/backend/postgres/index.d.ts +43 -6
  7. package/dist/backend/postgres/index.js +138 -21
  8. package/dist/backend/postgres/index.js.map +1 -1
  9. package/dist/backend/sqlite/index.cjs +13 -12
  10. package/dist/backend/sqlite/index.d.cts +6 -6
  11. package/dist/backend/sqlite/index.d.ts +6 -6
  12. package/dist/backend/sqlite/index.js +3 -2
  13. package/dist/backend/sqlite/libsql.cjs +6 -5
  14. package/dist/backend/sqlite/libsql.cjs.map +1 -1
  15. package/dist/backend/sqlite/libsql.d.cts +4 -4
  16. package/dist/backend/sqlite/libsql.d.ts +4 -4
  17. package/dist/backend/sqlite/libsql.js +3 -2
  18. package/dist/backend/sqlite/libsql.js.map +1 -1
  19. package/dist/backend/sqlite/local.cjs +7 -6
  20. package/dist/backend/sqlite/local.cjs.map +1 -1
  21. package/dist/backend/sqlite/local.d.cts +4 -4
  22. package/dist/backend/sqlite/local.d.ts +4 -4
  23. package/dist/backend/sqlite/local.js +3 -2
  24. package/dist/backend/sqlite/local.js.map +1 -1
  25. package/dist/chunk-3EUKJEQ3.js +77 -0
  26. package/dist/chunk-3EUKJEQ3.js.map +1 -0
  27. package/dist/{chunk-GUYI6VAS.cjs → chunk-3MDBMCFF.cjs} +67 -42
  28. package/dist/chunk-3MDBMCFF.cjs.map +1 -0
  29. package/dist/{chunk-SCXOGKLD.cjs → chunk-5HVDOPZU.cjs} +88 -45
  30. package/dist/chunk-5HVDOPZU.cjs.map +1 -0
  31. package/dist/chunk-7TU5EWQ7.js +47 -0
  32. package/dist/chunk-7TU5EWQ7.js.map +1 -0
  33. package/dist/{chunk-5ZMMHUWR.js → chunk-EY4LBX3F.js} +88 -43
  34. package/dist/chunk-EY4LBX3F.js.map +1 -0
  35. package/dist/{chunk-NSLTDXVH.js → chunk-GTG5J4UP.js} +52 -27
  36. package/dist/chunk-GTG5J4UP.js.map +1 -0
  37. package/dist/chunk-HTGDWIDE.cjs +89 -0
  38. package/dist/chunk-HTGDWIDE.cjs.map +1 -0
  39. package/dist/chunk-RNUNP5JD.cjs +52 -0
  40. package/dist/chunk-RNUNP5JD.cjs.map +1 -0
  41. package/dist/{ddl-BqkTShcR.d.ts → ddl-1tFIvt9V.d.ts} +3 -3
  42. package/dist/{ddl-Dk1NDN3M.d.cts → ddl-B_H8JM-E.d.cts} +3 -3
  43. package/dist/index.cjs +133 -145
  44. package/dist/index.cjs.map +1 -1
  45. package/dist/index.d.cts +8 -8
  46. package/dist/index.d.ts +8 -8
  47. package/dist/index.js +94 -106
  48. package/dist/index.js.map +1 -1
  49. package/dist/indexes/index.d.cts +5 -5
  50. package/dist/indexes/index.d.ts +5 -5
  51. package/dist/interchange/index.d.cts +4 -4
  52. package/dist/interchange/index.d.ts +4 -4
  53. package/dist/{manager-BPK-2PUI.d.cts → manager-Vkz28eAC.d.cts} +1 -1
  54. package/dist/{manager-0jVZtiE8.d.ts → manager-nIhmttD-.d.ts} +1 -1
  55. package/dist/profiler/index.d.cts +6 -6
  56. package/dist/profiler/index.d.ts +6 -6
  57. package/dist/schema/index.d.cts +4 -4
  58. package/dist/schema/index.d.ts +4 -4
  59. package/dist/{sqlite-D1rrwcir.d.cts → sqlite-D0aceIe0.d.cts} +1 -1
  60. package/dist/{sqlite-W3rmJMlc.d.ts → sqlite-SUxbZqfy.d.ts} +1 -1
  61. package/dist/{store-C0q13mtJ.d.ts → store-CpvwTMxV.d.cts} +58 -8
  62. package/dist/{store-2QW2SIRk.d.cts → store-U3i2tUch.d.ts} +58 -8
  63. package/dist/{types-IMQCuser.d.ts → types-C-zfYDJB.d.ts} +2 -2
  64. package/dist/{types-vgjar7Ch.d.cts → types-CQx4iW5Y.d.cts} +2 -2
  65. package/dist/{types-CQF88McG.d.ts → types-Qk2l3IkQ.d.cts} +20 -1
  66. package/dist/{types-CQF88McG.d.cts → types-Qk2l3IkQ.d.ts} +20 -1
  67. package/dist/{types-CglvhPKz.d.ts → types-qYFZ9SqD.d.ts} +1 -1
  68. package/dist/{types-D23slCOA.d.cts → types-yH4_p0XB.d.cts} +1 -1
  69. package/package.json +15 -1
  70. package/dist/chunk-5ZMMHUWR.js.map +0 -1
  71. package/dist/chunk-GUYI6VAS.cjs.map +0 -1
  72. package/dist/chunk-NSLTDXVH.js.map +0 -1
  73. package/dist/chunk-SCXOGKLD.cjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/backend/types.ts"],"names":[],"mappings":";AAqsBO,SAAS,oBAAA,CACd,SACA,QAAA,EACc;AACd,EAAA,IAAI,QAAA,GAAW,KAAA;AACf,EAAA,OAAO;AAAA,IACL,GAAG,OAAA;AAAA,IACH,MAAM,KAAA,GAAuB;AAC3B,MAAA,IAAI,QAAA,EAAU;AACd,MAAA,QAAA,GAAW,IAAA;AACX,MAAA,MAAM,QAAQ,KAAA,EAAM;AACpB,MAAA,MAAM,QAAA,EAAS;AAAA,IACjB;AAAA,GACF;AACF;AAeA,eAAsB,0BAAA,CACpB,OAAA,EACA,EAAA,EACA,QAAA,EACY;AACZ,EAAA,IAAI,CAAC,OAAA,CAAQ,YAAA,CAAa,YAAA,EAAc;AACtC,IAAA,OAAO,EAAA,CAAG,YAAY,OAAO,CAAA;AAAA,EAC/B;AACA,EAAA,OAAO,QAAQ,WAAA,CAAY,CAAC,EAAA,KAAO,EAAA,CAAG,EAAE,CAAC,CAAA;AAC3C;AAyLO,IAAM,mBAAA,GAA2C;AAAA,EACtD,KAAA,EAAO,KAAA;AAAA;AAAA,EACP,cAAA,EAAgB,IAAA;AAAA;AAAA,EAChB,UAAA,EAAY,KAAA;AAAA;AAAA,EACZ,GAAA,EAAK,IAAA;AAAA;AAAA,EACL,SAAA,EAAW,IAAA;AAAA;AAAA,EACX,YAAA,EAAc;AAAA;AAChB;AAKO,IAAM,qBAAA,GAA6C;AAAA,EACxD,KAAA,EAAO,IAAA;AAAA;AAAA,EACP,cAAA,EAAgB,IAAA;AAAA,EAChB,UAAA,EAAY,IAAA;AAAA,EACZ,GAAA,EAAK,IAAA;AAAA,EACL,SAAA,EAAW,IAAA;AAAA,EACX,YAAA,EAAc;AAAA;AAChB","file":"chunk-7TU5EWQ7.js","sourcesContent":["/**\n * Backend interface types for TypeGraph storage.\n *\n * The backend abstracts database operations, allowing different\n * SQL implementations (SQLite, PostgreSQL) behind a common interface.\n */\nimport { type SQL } from \"drizzle-orm\";\n\nimport { type TemporalMode } from \"../core/types\";\nimport { type SqlTableNames } from \"../query/compiler/schema\";\nimport { type FulltextStrategy } from \"../query/dialect/fulltext-strategy\";\nimport { type SerializedSchema } from \"../schema/types\";\n\n// ============================================================\n// Vector Search Types\n// ============================================================\n\n/**\n * Supported vector similarity metrics.\n */\nexport type VectorMetric = \"cosine\" | \"l2\" | \"inner_product\";\n\n/**\n * Supported vector index types.\n */\nexport type VectorIndexType = \"hnsw\" | \"ivfflat\" | \"none\";\n\n/**\n * Vector search capabilities.\n */\nexport type VectorCapabilities = Readonly<{\n /** Whether the backend supports vector operations */\n supported: boolean;\n /** Supported similarity metrics */\n metrics: readonly VectorMetric[];\n /** Supported index types */\n indexTypes: readonly VectorIndexType[];\n /** Maximum dimensions supported */\n maxDimensions: number;\n}>;\n\n// ============================================================\n// Fulltext Search Types\n// ============================================================\n\n/**\n * Query modes for fulltext search.\n *\n * - \"websearch\": Google-style syntax (quoted phrases, +required, -excluded).\n * Postgres: `websearch_to_tsquery`. SQLite: translated to FTS5 MATCH.\n * - \"phrase\": treats the whole query as a phrase.\n * Postgres: `phraseto_tsquery`. SQLite: FTS5 `\"...\"` phrase.\n * - \"plain\": splits on whitespace and ANDs terms.\n * Postgres: `plainto_tsquery`. SQLite: default FTS5 AND.\n * - \"raw\": dialect-native syntax passed through unchanged.\n */\nexport type FulltextQueryMode = \"websearch\" | \"phrase\" | \"plain\" | \"raw\";\n\n/**\n * Fulltext search capabilities declared by a backend.\n */\nexport type FulltextCapabilities = Readonly<{\n /** Whether the backend supports fulltext operations */\n supported: boolean;\n /**\n * Language / tokenizer names understood by this backend.\n * Postgres: installed regconfigs (english, simple, ...).\n * SQLite FTS5: tokenizer names (unicode61, porter, trigram).\n */\n languages: readonly string[];\n /** Whether phrase queries are supported. */\n phraseQueries: boolean;\n /** Whether prefix (`foo*`) queries are supported. */\n prefixQueries: boolean;\n /** Whether highlighting / snippets are supported. */\n highlighting: boolean;\n}>;\n\n// ============================================================\n// SQL Dialect & Capabilities\n// ============================================================\n\nimport { type SqlDialect } from \"../query/dialect/types\";\n\nexport type { SqlDialect } from \"../query/dialect/types\";\n\n/**\n * Backend capabilities that vary by dialect.\n */\nexport type BackendCapabilities = Readonly<{\n /** Whether the backend supports JSONB type (vs TEXT for JSON) */\n jsonb: boolean;\n /** Whether the backend supports partial indexes */\n partialIndexes: boolean;\n /** Whether the backend supports GIN indexes for JSON */\n ginIndexes: boolean;\n /** Whether the backend supports CTE (WITH) queries */\n cte: boolean;\n /** Whether the backend supports RETURNING clause */\n returning: boolean;\n /** Whether the backend supports atomic transactions (D1 does not) */\n transactions: boolean;\n /** Vector search capabilities (undefined if not configured) */\n vector?: VectorCapabilities | undefined;\n /** Fulltext search capabilities (undefined if not configured) */\n fulltext?: FulltextCapabilities | undefined;\n}>;\n\n// ============================================================\n// Row Types (Database Records)\n// ============================================================\n\n/**\n * A row from the typegraph_nodes table.\n */\nexport type NodeRow = Readonly<{\n graph_id: string;\n kind: string;\n id: string;\n props: string; // JSON string\n version: number;\n valid_from: string | undefined;\n valid_to: string | undefined;\n created_at: string;\n updated_at: string;\n deleted_at: string | undefined;\n}>;\n\n/**\n * A row from the typegraph_edges table.\n */\nexport type EdgeRow = Readonly<{\n graph_id: string;\n id: string;\n kind: string;\n from_kind: string;\n from_id: string;\n to_kind: string;\n to_id: string;\n props: string; // JSON string\n valid_from: string | undefined;\n valid_to: string | undefined;\n created_at: string;\n updated_at: string;\n deleted_at: string | undefined;\n}>;\n\n/**\n * A row from the typegraph_node_uniques table.\n */\nexport type UniqueRow = Readonly<{\n graph_id: string;\n node_kind: string;\n constraint_name: string;\n key: string;\n node_id: string;\n concrete_kind: string;\n deleted_at: string | undefined;\n}>;\n\n/**\n * A row from the typegraph_schema_versions table.\n */\nexport type SchemaVersionRow = Readonly<{\n graph_id: string;\n version: number;\n schema_hash: string;\n schema_doc: string; // JSON string\n created_at: string;\n is_active: boolean;\n}>;\n\n/**\n * A row from the typegraph_node_embeddings table.\n */\nexport type EmbeddingRow = Readonly<{\n graph_id: string;\n node_kind: string;\n node_id: string;\n field_path: string;\n embedding: readonly number[];\n dimensions: number;\n created_at: string;\n updated_at: string;\n}>;\n\n// ============================================================\n// Insert Parameters\n// ============================================================\n\n/**\n * Parameters for inserting a node.\n */\nexport type InsertNodeParams = Readonly<{\n graphId: string;\n kind: string;\n id: string;\n props: Readonly<Record<string, unknown>>;\n validFrom?: string;\n validTo?: string;\n}>;\n\n/**\n * Parameters for updating a node.\n */\nexport type UpdateNodeParams = Readonly<{\n graphId: string;\n kind: string;\n id: string;\n props: Readonly<Record<string, unknown>>;\n validTo?: string;\n incrementVersion?: boolean;\n /** If true, clears deleted_at (un-deletes the node). Used by upsert. */\n clearDeleted?: boolean;\n}>;\n\n/**\n * Parameters for deleting a node (soft delete).\n */\nexport type DeleteNodeParams = Readonly<{\n graphId: string;\n kind: string;\n id: string;\n}>;\n\n/**\n * Parameters for inserting an edge.\n */\nexport type InsertEdgeParams = Readonly<{\n graphId: string;\n id: string;\n kind: string;\n fromKind: string;\n fromId: string;\n toKind: string;\n toId: string;\n props: Readonly<Record<string, unknown>>;\n validFrom?: string;\n validTo?: string;\n}>;\n\n/**\n * Parameters for updating an edge.\n */\nexport type UpdateEdgeParams = Readonly<{\n graphId: string;\n id: string;\n props: Readonly<Record<string, unknown>>;\n validTo?: string;\n clearDeleted?: boolean;\n}>;\n\n/**\n * Parameters for deleting an edge (soft delete).\n */\nexport type DeleteEdgeParams = Readonly<{\n graphId: string;\n id: string;\n}>;\n\n/**\n * Parameters for hard deleting a node (permanent removal).\n */\nexport type HardDeleteNodeParams = Readonly<{\n graphId: string;\n kind: string;\n id: string;\n}>;\n\n/**\n * Parameters for hard deleting an edge (permanent removal).\n */\nexport type HardDeleteEdgeParams = Readonly<{\n graphId: string;\n id: string;\n}>;\n\n// ============================================================\n// Embedding Parameters\n// ============================================================\n\n/**\n * Parameters for inserting or updating an embedding.\n */\nexport type UpsertEmbeddingParams = Readonly<{\n graphId: string;\n nodeKind: string;\n nodeId: string;\n fieldPath: string;\n embedding: readonly number[];\n dimensions: number;\n}>;\n\n/**\n * Parameters for deleting an embedding.\n */\nexport type DeleteEmbeddingParams = Readonly<{\n graphId: string;\n nodeKind: string;\n nodeId: string;\n fieldPath: string;\n}>;\n\n/**\n * Parameters for vector similarity search.\n */\nexport type VectorSearchParams = Readonly<{\n graphId: string;\n nodeKind: string;\n fieldPath: string;\n queryEmbedding: readonly number[];\n metric: VectorMetric;\n limit: number;\n minScore?: number;\n}>;\n\n/**\n * Result from a vector similarity search.\n */\nexport type VectorSearchResult = Readonly<{\n nodeId: string;\n /**\n * Cosine metric returns similarity score (higher is better).\n * L2 and inner_product return raw distance (lower is better).\n */\n score: number;\n}>;\n\n/**\n * Parameters for creating a vector index.\n */\nexport type CreateVectorIndexParams = Readonly<{\n graphId: string;\n nodeKind: string;\n fieldPath: string;\n dimensions: number;\n metric: VectorMetric;\n indexType: VectorIndexType;\n /** Index-specific parameters */\n indexParams?: Readonly<{\n /** HNSW: max connections per layer */\n m?: number;\n /** HNSW: construction search depth */\n efConstruction?: number;\n /** IVFFlat: number of lists */\n lists?: number;\n }>;\n}>;\n\n/**\n * Parameters for dropping a vector index.\n */\nexport type DropVectorIndexParams = Readonly<{\n graphId: string;\n nodeKind: string;\n fieldPath: string;\n}>;\n\n// ============================================================\n// Fulltext Parameters\n// ============================================================\n\n/**\n * Parameters for inserting or updating a fulltext entry.\n *\n * One row per node. Callers concatenate the searchable fields into\n * `content` so a single MATCH query can find terms spread across fields.\n */\nexport type UpsertFulltextParams = Readonly<{\n graphId: string;\n nodeKind: string;\n nodeId: string;\n content: string;\n language: string;\n}>;\n\n/**\n * Parameters for deleting a single fulltext entry.\n */\nexport type DeleteFulltextParams = Readonly<{\n graphId: string;\n nodeKind: string;\n nodeId: string;\n}>;\n\n/**\n * A single row in a fulltext batch upsert.\n */\nexport type FulltextBatchRow = Readonly<{\n nodeId: string;\n content: string;\n language: string;\n}>;\n\n/**\n * Parameters for a batched fulltext upsert.\n *\n * Homogeneous: one graph, one node kind, many nodes. Duplicate `nodeId`\n * values within a single batch are deduplicated last-write-wins by the\n * builders before SQL generation — Postgres `ON CONFLICT` errors on\n * repeated conflict keys in one statement, and SQLite `DELETE + INSERT`\n * would create duplicate virtual-table rows otherwise.\n */\nexport type UpsertFulltextBatchParams = Readonly<{\n graphId: string;\n nodeKind: string;\n rows: readonly FulltextBatchRow[];\n}>;\n\n/**\n * Parameters for a batched fulltext delete.\n */\nexport type DeleteFulltextBatchParams = Readonly<{\n graphId: string;\n nodeKind: string;\n nodeIds: readonly string[];\n}>;\n\n/**\n * Parameters for fulltext search.\n */\nexport type FulltextSearchParams = Readonly<{\n graphId: string;\n nodeKind: string;\n /** The user-supplied query string. */\n query: string;\n /** How to parse `query`. Default: \"websearch\". */\n mode?: FulltextQueryMode;\n /**\n * Language override. Default: per-row language (as stored at insert time).\n * Postgres: passed as the regconfig to `to_tsquery` / `websearch_to_tsquery`.\n * SQLite: informational only (FTS5 tokenizer is fixed at table-create time).\n */\n language?: string;\n /** Max rows to return. */\n limit: number;\n /** Minimum rank to include (backend-dependent units). */\n minScore?: number;\n /** Whether to return a highlighted snippet per match. */\n includeSnippets?: boolean;\n}>;\n\n/**\n * Result from a fulltext search.\n *\n * Score semantics differ by backend; prefer `rank` (1-based) when fusing\n * with another source via RRF.\n */\nexport type FulltextSearchResult = Readonly<{\n nodeId: string;\n /**\n * Backend-native relevance score.\n * Postgres: `ts_rank_cd` (higher is better).\n * SQLite FTS5: negated `bm25()` (higher is better; FTS5 returns lower-is-better).\n */\n score: number;\n /** 1-based rank within the result set, suitable for RRF. */\n rank: number;\n /** Highlighted snippet of the content (if `includeSnippets` was set). */\n snippet?: string;\n}>;\n\n/**\n * Parameters for creating a fulltext index.\n *\n * The canonical index (Postgres GIN on `tsv`, SQLite FTS5 virtual table)\n * is created when the fulltext table itself is created. This is reserved\n * for advanced per-kind specializations.\n */\nexport type CreateFulltextIndexParams = Readonly<{\n graphId: string;\n nodeKind: string;\n language: string;\n}>;\n\n/**\n * Parameters for dropping a fulltext index created via createFulltextIndex.\n */\nexport type DropFulltextIndexParams = Readonly<{\n graphId: string;\n nodeKind: string;\n}>;\n\n// ============================================================\n// Query Types\n// ============================================================\n\n/**\n * Transaction options.\n */\nexport type TransactionOptions = Readonly<{\n /** Transaction isolation level (if supported) */\n isolationLevel?:\n | \"read_uncommitted\"\n | \"read_committed\"\n | \"repeatable_read\"\n | \"serializable\";\n}>;\n\n// ============================================================\n// Backend Interface\n// ============================================================\n\n/**\n * Transaction backend - a backend scoped to a transaction.\n */\nexport type TransactionBackend = Omit<\n GraphBackend,\n \"transaction\" | \"close\" | \"refreshStatistics\"\n>;\n\n/**\n * The GraphBackend interface abstracts database operations.\n *\n * Implementations should provide:\n * - SQLite backend via better-sqlite3 or libsql\n * - PostgreSQL backend via pg or postgres\n */\nexport type GraphBackend = Readonly<{\n /** The SQL dialect */\n dialect: SqlDialect;\n /** Backend capabilities */\n capabilities: BackendCapabilities;\n /** Table names used by this backend (for query schema auto-derivation) */\n tableNames?: SqlTableNames | undefined;\n /**\n * Optional fulltext strategy override. When present, both the compiler\n * (for `$fulltext.matches()` in query builder) and backend-direct\n * search paths use this instead of the dialect's default strategy —\n * allowing a Postgres backend to ship pg_trgm, ParadeDB, pgroonga etc.\n * When absent, the dialect's default strategy is used.\n */\n fulltextStrategy?: FulltextStrategy | undefined;\n\n // === Node Operations ===\n insertNode: (params: InsertNodeParams) => Promise<NodeRow>;\n insertNodeNoReturn?: (params: InsertNodeParams) => Promise<void>;\n insertNodesBatch?: (params: readonly InsertNodeParams[]) => Promise<void>;\n insertNodesBatchReturning?: (\n params: readonly InsertNodeParams[],\n ) => Promise<readonly NodeRow[]>;\n updateNode: (params: UpdateNodeParams) => Promise<NodeRow>;\n deleteNode: (params: DeleteNodeParams) => Promise<void>;\n hardDeleteNode: (params: HardDeleteNodeParams) => Promise<void>;\n getNode: (\n graphId: string,\n kind: string,\n id: string,\n ) => Promise<NodeRow | undefined>;\n getNodes?: (\n graphId: string,\n kind: string,\n ids: readonly string[],\n ) => Promise<readonly NodeRow[]>;\n\n // === Edge Operations ===\n insertEdge: (params: InsertEdgeParams) => Promise<EdgeRow>;\n insertEdgeNoReturn?: (params: InsertEdgeParams) => Promise<void>;\n insertEdgesBatch?: (params: readonly InsertEdgeParams[]) => Promise<void>;\n insertEdgesBatchReturning?: (\n params: readonly InsertEdgeParams[],\n ) => Promise<readonly EdgeRow[]>;\n updateEdge: (params: UpdateEdgeParams) => Promise<EdgeRow>;\n deleteEdge: (params: DeleteEdgeParams) => Promise<void>;\n hardDeleteEdge: (params: HardDeleteEdgeParams) => Promise<void>;\n getEdge: (graphId: string, id: string) => Promise<EdgeRow | undefined>;\n getEdges?: (\n graphId: string,\n ids: readonly string[],\n ) => Promise<readonly EdgeRow[]>;\n\n // === Edge Cardinality Operations ===\n countEdgesFrom: (params: CountEdgesFromParams) => Promise<number>;\n edgeExistsBetween: (params: EdgeExistsBetweenParams) => Promise<boolean>;\n\n // === Edge Query Operations ===\n findEdgesConnectedTo: (\n params: FindEdgesConnectedToParams,\n ) => Promise<readonly EdgeRow[]>;\n\n // === Collection Query Operations ===\n findNodesByKind: (\n params: FindNodesByKindParams,\n ) => Promise<readonly NodeRow[]>;\n countNodesByKind: (params: CountNodesByKindParams) => Promise<number>;\n findEdgesByKind: (\n params: FindEdgesByKindParams,\n ) => Promise<readonly EdgeRow[]>;\n countEdgesByKind: (params: CountEdgesByKindParams) => Promise<number>;\n\n // === Unique Constraint Operations ===\n insertUnique: (params: InsertUniqueParams) => Promise<void>;\n deleteUnique: (params: DeleteUniqueParams) => Promise<void>;\n checkUnique: (params: CheckUniqueParams) => Promise<UniqueRow | undefined>;\n checkUniqueBatch?: (\n params: CheckUniqueBatchParams,\n ) => Promise<readonly UniqueRow[]>;\n\n // === Schema Operations ===\n getActiveSchema: (graphId: string) => Promise<SchemaVersionRow | undefined>;\n getSchemaVersion: (\n graphId: string,\n version: number,\n ) => Promise<SchemaVersionRow | undefined>;\n insertSchema: (params: InsertSchemaParams) => Promise<SchemaVersionRow>;\n setActiveSchema: (graphId: string, version: number) => Promise<void>;\n\n // === Embedding Operations (optional - depends on vector capabilities) ===\n upsertEmbedding?: (params: UpsertEmbeddingParams) => Promise<void>;\n deleteEmbedding?: (params: DeleteEmbeddingParams) => Promise<void>;\n getEmbedding?: (\n graphId: string,\n nodeKind: string,\n nodeId: string,\n fieldPath: string,\n ) => Promise<EmbeddingRow | undefined>;\n vectorSearch?: (\n params: VectorSearchParams,\n ) => Promise<readonly VectorSearchResult[]>;\n createVectorIndex?: (params: CreateVectorIndexParams) => Promise<void>;\n dropVectorIndex?: (params: DropVectorIndexParams) => Promise<void>;\n\n // === Fulltext Operations (optional - depends on fulltext capabilities) ===\n upsertFulltext?: (params: UpsertFulltextParams) => Promise<void>;\n deleteFulltext?: (params: DeleteFulltextParams) => Promise<void>;\n /**\n * Batched variant of `upsertFulltext`. Optional — callers fall back to\n * per-row `upsertFulltext` when unset.\n */\n upsertFulltextBatch?: (params: UpsertFulltextBatchParams) => Promise<void>;\n /**\n * Batched variant of `deleteFulltext`. Optional — callers fall back to\n * per-row `deleteFulltext` when unset.\n */\n deleteFulltextBatch?: (params: DeleteFulltextBatchParams) => Promise<void>;\n fulltextSearch?: (\n params: FulltextSearchParams,\n ) => Promise<readonly FulltextSearchResult[]>;\n createFulltextIndex?: (params: CreateFulltextIndexParams) => Promise<void>;\n dropFulltextIndex?: (params: DropFulltextIndexParams) => Promise<void>;\n\n // === Graph Lifecycle ===\n /**\n * Hard-deletes all data for a graph (nodes, edges, uniques, embeddings, schema versions).\n * Intended for import-replacement workflows. No hooks, no per-row logic.\n */\n clearGraph: (graphId: string) => Promise<void>;\n\n /**\n * Creates the base TypeGraph tables if they don't already exist.\n *\n * Called automatically by `createStoreWithSchema()` when a fresh database\n * is detected. Users who manage DDL themselves via `createStore()` never\n * hit this path.\n */\n bootstrapTables?: () => Promise<void>;\n\n /**\n * Refreshes the backend's query-planner statistics.\n *\n * Call this once after a large initial import or bulk backfill. Without\n * up-to-date statistics, the planner can pick suboptimal execution plans\n * — on PostgreSQL this is the difference between a 0.5ms and a 5ms\n * forward traversal; on SQLite it's the difference between 0.9ms and\n * 23ms fulltext search. Autovacuum / background statistics collection\n * will catch up eventually, but calling this explicitly after a bulk\n * load gives you correct latencies immediately.\n *\n * Implementations:\n * - SQLite runs `ANALYZE`, which populates `sqlite_stat1`\n * - PostgreSQL runs `ANALYZE` on the TypeGraph-managed tables\n *\n * Safe to call at any time; costs a few tens of milliseconds on the\n * sizes this library is designed for.\n */\n refreshStatistics: () => Promise<void>;\n\n // === Query Execution ===\n execute: <T>(query: SQL) => Promise<readonly T[]>;\n\n /** Execute pre-compiled SQL text with bound parameters. Available on sync SQLite and pg backends. */\n executeRaw?: <T>(\n sqlText: string,\n params: readonly unknown[],\n ) => Promise<readonly T[]>;\n\n /** Compile a Drizzle SQL object to { sql, params } without executing. */\n compileSql?: (\n query: SQL,\n ) => Readonly<{ sql: string; params: readonly unknown[] }>;\n\n // === Transaction ===\n transaction: <T>(\n fn: (tx: TransactionBackend) => Promise<T>,\n options?: TransactionOptions,\n ) => Promise<T>;\n\n // === Lifecycle ===\n close: () => Promise<void>;\n}>;\n\n// ============================================================\n// Managed Backend Helper\n// ============================================================\n\n/**\n * Wraps a GraphBackend with idempotent close that also runs a teardown\n * callback (e.g. closing the underlying database connection).\n */\nexport function wrapWithManagedClose(\n backend: GraphBackend,\n teardown: () => void | Promise<void>,\n): GraphBackend {\n let isClosed = false;\n return {\n ...backend,\n async close(): Promise<void> {\n if (isClosed) return;\n isClosed = true;\n await backend.close();\n await teardown();\n },\n };\n}\n\n/**\n * Runs `fn` inside a transaction when the backend supports one, falling\n * through to a direct invocation otherwise. Lets call sites benefit from\n * atomicity on backends that have transactions while staying functional\n * on backends that don't (Cloudflare D1, `drizzle-orm/neon-http` over\n * HTTP). The single-statement race window is already implicit on any\n * backend that reports `transactions: false`; callers that cannot\n * tolerate it must branch on the capability themselves.\n *\n * Pass `fallback` only when the toplevel backend method would recurse\n * — for example, when implementing `backend.setActiveSchema` itself,\n * pass the operation-level backend so the no-tx path doesn't loop.\n */\nexport async function runOptionallyInTransaction<T>(\n backend: GraphBackend,\n fn: (target: GraphBackend | TransactionBackend) => Promise<T>,\n fallback?: GraphBackend | TransactionBackend,\n): Promise<T> {\n if (!backend.capabilities.transactions) {\n return fn(fallback ?? backend);\n }\n return backend.transaction((tx) => fn(tx));\n}\n\n// ============================================================\n// Additional Parameter Types\n// ============================================================\n\n/**\n * Parameters for inserting a unique constraint entry.\n */\nexport type InsertUniqueParams = Readonly<{\n graphId: string;\n nodeKind: string;\n constraintName: string;\n key: string;\n nodeId: string;\n concreteKind: string;\n}>;\n\n/**\n * Parameters for deleting a unique constraint entry.\n */\nexport type DeleteUniqueParams = Readonly<{\n graphId: string;\n nodeKind: string;\n constraintName: string;\n key: string;\n}>;\n\n/**\n * Parameters for checking a unique constraint.\n */\nexport type CheckUniqueParams = Readonly<{\n graphId: string;\n nodeKind: string;\n constraintName: string;\n key: string;\n /** If true, also returns soft-deleted entries. Used by get-or-create operations. */\n includeDeleted?: boolean;\n}>;\n\n/**\n * Parameters for batch-checking unique constraints.\n */\nexport type CheckUniqueBatchParams = Readonly<{\n graphId: string;\n nodeKind: string;\n constraintName: string;\n keys: readonly string[];\n /** If true, also returns soft-deleted entries. Used by get-or-create operations. */\n includeDeleted?: boolean;\n}>;\n\n/**\n * Parameters for inserting a schema version.\n */\nexport type InsertSchemaParams = Readonly<{\n graphId: string;\n version: number;\n schemaHash: string;\n schemaDoc: SerializedSchema;\n isActive: boolean;\n}>;\n\n/**\n * Parameters for counting edges from a source node.\n */\nexport type CountEdgesFromParams = Readonly<{\n graphId: string;\n edgeKind: string;\n fromKind: string;\n fromId: string;\n /** If true, only count edges where valid_to IS NULL */\n activeOnly?: boolean;\n}>;\n\n/**\n * Parameters for checking if an edge exists between two nodes.\n */\nexport type EdgeExistsBetweenParams = Readonly<{\n graphId: string;\n edgeKind: string;\n fromKind: string;\n fromId: string;\n toKind: string;\n toId: string;\n}>;\n\n/**\n * Parameters for finding edges connected to a node.\n */\nexport type FindEdgesConnectedToParams = Readonly<{\n graphId: string;\n nodeKind: string;\n nodeId: string;\n}>;\n\n/**\n * Parameters for finding nodes by kind.\n */\nexport type FindNodesByKindParams = Readonly<{\n graphId: string;\n kind: string;\n /** Max rows to return. */\n limit?: number;\n /** Offset. Present for backward compat; rebuild uses `after` instead. */\n offset?: number;\n /** If true, exclude deleted nodes. Default true. */\n excludeDeleted?: boolean;\n /** Temporal mode for filtering by validity period. */\n temporalMode?: TemporalMode;\n /** Timestamp for \"current\" and \"asOf\" temporal modes. */\n asOf?: string;\n /**\n * Stable ordering for keyset pagination. Default: \"created_at\" (existing\n * behavior). Rebuild should use \"id\" for iteration that is stable under\n * concurrent writes and shared timestamps.\n */\n orderBy?: \"id\" | \"created_at\";\n /**\n * Keyset cursor. Returns rows strictly greater (by `orderBy`) than this\n * value. When `orderBy: \"id\"`, compared lexicographically. Mutually\n * exclusive with `offset` — callers pick one.\n */\n after?: string;\n}>;\n\n/**\n * Parameters for counting nodes by kind.\n */\nexport type CountNodesByKindParams = Readonly<{\n graphId: string;\n kind: string;\n /** If true, exclude deleted nodes. Default true. */\n excludeDeleted?: boolean;\n /** Temporal mode for filtering by validity period. */\n temporalMode?: TemporalMode;\n /** Timestamp for \"current\" and \"asOf\" temporal modes. */\n asOf?: string;\n}>;\n\n/**\n * Parameters for finding edges by kind.\n */\nexport type FindEdgesByKindParams = Readonly<{\n graphId: string;\n kind: string;\n fromKind?: string;\n fromId?: string;\n toKind?: string;\n toId?: string;\n limit?: number;\n offset?: number;\n /** If true, exclude deleted edges. Default true. */\n excludeDeleted?: boolean;\n /** Temporal mode for filtering by validity period. */\n temporalMode?: TemporalMode;\n /** Timestamp for \"current\" and \"asOf\" temporal modes. */\n asOf?: string;\n}>;\n\n/**\n * Parameters for counting edges by kind.\n */\nexport type CountEdgesByKindParams = Readonly<{\n graphId: string;\n kind: string;\n fromKind?: string;\n fromId?: string;\n toKind?: string;\n toId?: string;\n /** If true, exclude deleted edges. Default true. */\n excludeDeleted?: boolean;\n /** Temporal mode for filtering by validity period. */\n temporalMode?: TemporalMode;\n /** Timestamp for \"current\" and \"asOf\" temporal modes. */\n asOf?: string;\n}>;\n\n// ============================================================\n// Default Capabilities\n// ============================================================\n\n/**\n * Default capabilities for SQLite.\n */\nexport const SQLITE_CAPABILITIES: BackendCapabilities = {\n jsonb: false, // SQLite uses TEXT with json functions\n partialIndexes: true, // SQLite supports WHERE in CREATE INDEX\n ginIndexes: false, // SQLite doesn't have GIN\n cte: true, // SQLite supports WITH\n returning: true, // SQLite 3.35+ supports RETURNING\n transactions: true, // SQLite supports transactions\n};\n\n/**\n * Default capabilities for PostgreSQL.\n */\nexport const POSTGRES_CAPABILITIES: BackendCapabilities = {\n jsonb: true, // PostgreSQL has native JSONB\n partialIndexes: true,\n ginIndexes: true,\n cte: true,\n returning: true,\n transactions: true, // PostgreSQL supports transactions\n};\n"]}
@@ -5,43 +5,6 @@ import { customType, pgTable, timestamp, integer, jsonb, text, primaryKey, index
5
5
  import { sqliteTable, text as text$1, integer as integer$1, primaryKey as primaryKey$1, index as index$1, blob, getTableConfig } from 'drizzle-orm/sqlite-core';
6
6
  import { sql, getTableName } from 'drizzle-orm';
7
7
 
8
- // src/backend/types.ts
9
- function wrapWithManagedClose(backend, teardown) {
10
- let isClosed = false;
11
- return {
12
- ...backend,
13
- async close() {
14
- if (isClosed) return;
15
- isClosed = true;
16
- await backend.close();
17
- await teardown();
18
- }
19
- };
20
- }
21
- var SQLITE_CAPABILITIES = {
22
- jsonb: false,
23
- // SQLite uses TEXT with json functions
24
- partialIndexes: true,
25
- // SQLite supports WHERE in CREATE INDEX
26
- ginIndexes: false,
27
- // SQLite doesn't have GIN
28
- cte: true,
29
- // SQLite supports WITH
30
- returning: true,
31
- // SQLite 3.35+ supports RETURNING
32
- transactions: true
33
- // SQLite supports transactions
34
- };
35
- var POSTGRES_CAPABILITIES = {
36
- jsonb: true,
37
- // PostgreSQL has native JSONB
38
- partialIndexes: true,
39
- ginIndexes: true,
40
- cte: true,
41
- returning: true,
42
- transactions: true
43
- // PostgreSQL supports transactions
44
- };
45
8
  var vector = customType({
46
9
  dataType(config) {
47
10
  return config?.dimensions ? `vector(${config.dimensions})` : "vector";
@@ -1940,9 +1903,7 @@ function buildVectorSearchMinScoreCondition(distanceExpression, metric, minScore
1940
1903
  }
1941
1904
  }
1942
1905
  }
1943
- function buildVectorSearchPostgres(tables3, params) {
1944
- const { embeddings: embeddings3 } = tables3;
1945
- const queryLiteral = formatEmbeddingLiteral(params.queryEmbedding);
1906
+ function assertVectorSearchBounds(params) {
1946
1907
  if (params.minScore !== void 0 && !Number.isFinite(params.minScore)) {
1947
1908
  throw new TypeError(
1948
1909
  `minScore must be a finite number, got: ${params.minScore}`
@@ -1951,6 +1912,11 @@ function buildVectorSearchPostgres(tables3, params) {
1951
1912
  if (!Number.isInteger(params.limit) || params.limit <= 0) {
1952
1913
  throw new Error(`limit must be a positive integer, got: ${params.limit}`);
1953
1914
  }
1915
+ }
1916
+ function buildVectorSearchPostgres(tables3, params) {
1917
+ const { embeddings: embeddings3 } = tables3;
1918
+ const queryLiteral = formatEmbeddingLiteral(params.queryEmbedding);
1919
+ assertVectorSearchBounds(params);
1954
1920
  const embeddingColumn = sql`${embeddings3.embedding}`;
1955
1921
  const distanceExpression = buildDistanceExpression(
1956
1922
  embeddingColumn,
@@ -1986,6 +1952,65 @@ function buildVectorSearchPostgres(tables3, params) {
1986
1952
  LIMIT ${params.limit}
1987
1953
  `;
1988
1954
  }
1955
+ function buildSqliteDistanceExpression(embeddingColumn, embeddingJson, metric) {
1956
+ switch (metric) {
1957
+ case "cosine": {
1958
+ return sql`vec_distance_cosine(${embeddingColumn}, vec_f32(${embeddingJson}))`;
1959
+ }
1960
+ case "l2": {
1961
+ return sql`vec_distance_l2(${embeddingColumn}, vec_f32(${embeddingJson}))`;
1962
+ }
1963
+ case "inner_product": {
1964
+ throw new Error(
1965
+ "Inner product distance is not supported by sqlite-vec. Use 'cosine' or 'l2' metrics instead."
1966
+ );
1967
+ }
1968
+ default: {
1969
+ const _exhaustive = metric;
1970
+ throw new Error(`Unsupported vector metric: ${String(_exhaustive)}`);
1971
+ }
1972
+ }
1973
+ }
1974
+ function buildVectorSearchSqlite(tables3, params) {
1975
+ const { embeddings: embeddings3 } = tables3;
1976
+ assertFiniteNumberArray(params.queryEmbedding, "queryEmbedding");
1977
+ const embeddingJson = JSON.stringify(params.queryEmbedding);
1978
+ assertVectorSearchBounds(params);
1979
+ const embeddingColumn = sql`${embeddings3.embedding}`;
1980
+ const distanceExpression = buildSqliteDistanceExpression(
1981
+ embeddingColumn,
1982
+ embeddingJson,
1983
+ params.metric
1984
+ );
1985
+ const conditions = [
1986
+ sql`${embeddings3.graphId} = ${params.graphId}`,
1987
+ sql`${embeddings3.nodeKind} = ${params.nodeKind}`,
1988
+ sql`${embeddings3.fieldPath} = ${params.fieldPath}`
1989
+ ];
1990
+ if (params.minScore !== void 0) {
1991
+ conditions.push(
1992
+ buildVectorSearchMinScoreCondition(
1993
+ distanceExpression,
1994
+ params.metric,
1995
+ params.minScore
1996
+ )
1997
+ );
1998
+ }
1999
+ const whereClause = sql.join(conditions, sql` AND `);
2000
+ const scoreExpression = buildVectorSearchScoreExpression(
2001
+ distanceExpression,
2002
+ params.metric
2003
+ );
2004
+ return sql`
2005
+ SELECT
2006
+ ${embeddings3.nodeId} as node_id,
2007
+ ${scoreExpression} as score
2008
+ FROM ${embeddings3}
2009
+ WHERE ${whereClause}
2010
+ ORDER BY ${distanceExpression} ASC
2011
+ LIMIT ${params.limit}
2012
+ `;
2013
+ }
1989
2014
 
1990
2015
  // src/backend/drizzle/operations/strategy.ts
1991
2016
  function bindTableOperationBuilders(tables3, builders) {
@@ -2082,6 +2107,9 @@ function createSqliteOperationStrategy(tables3, fulltextStrategy) {
2082
2107
  },
2083
2108
  buildDeleteEmbedding(params) {
2084
2109
  return buildDeleteEmbedding(tables3, params);
2110
+ },
2111
+ buildVectorSearch(params) {
2112
+ return buildVectorSearchSqlite(tables3, params);
2085
2113
  }
2086
2114
  };
2087
2115
  }
@@ -2283,6 +2311,23 @@ function dropSqliteVectorIndex(graphId, nodeKind, fieldPath, metric = "cosine")
2283
2311
  };
2284
2312
  }
2285
2313
 
2314
+ // src/backend/drizzle/execution/lru.ts
2315
+ function getOrCreateLru(cache, key, cacheMax, create) {
2316
+ const cached = cache.get(key);
2317
+ if (cached !== void 0) {
2318
+ cache.delete(key);
2319
+ cache.set(key, cached);
2320
+ return cached;
2321
+ }
2322
+ const value = create();
2323
+ cache.set(key, value);
2324
+ if (cache.size > cacheMax) {
2325
+ const oldest = cache.keys().next().value;
2326
+ if (oldest !== void 0) cache.delete(oldest);
2327
+ }
2328
+ return value;
2329
+ }
2330
+
2286
2331
  // src/backend/drizzle/execution/types.ts
2287
2332
  function compileQueryWithDialect(db, query, backendName) {
2288
2333
  const databaseWithCompiler = db;
@@ -2293,6 +2338,6 @@ function compileQueryWithDialect(db, query, backendName) {
2293
2338
  return compiler.sqlToQuery(query);
2294
2339
  }
2295
2340
 
2296
- export { POSTGRES_CAPABILITIES, POSTGRES_ROW_MAPPER_CONFIG, SQLITE_CAPABILITIES, SQLITE_ROW_MAPPER_CONFIG, compileQueryWithDialect, createCommonOperationBackend, createEdgeRowMapper, createNodeRowMapper, createPostgresOperationStrategy, createPostgresTables, createPostgresVectorIndex, createSchemaVersionRowMapper, createSqliteOperationStrategy, createSqliteTables, createSqliteVectorIndex, createUniqueRowMapper, dropPostgresVectorIndex, dropSqliteVectorIndex, edges, edges2, embeddings, embeddings2, formatPostgresTimestamp, generatePostgresDDL, generatePostgresMigrationSQL, generateSqliteDDL, generateSqliteMigrationSQL, generateVectorIndexName, nodes, nodes2, nowIso, schemaVersions, schemaVersions2, tables, tables2, uniques, uniques2, wrapWithManagedClose };
2297
- //# sourceMappingURL=chunk-5ZMMHUWR.js.map
2298
- //# sourceMappingURL=chunk-5ZMMHUWR.js.map
2341
+ export { POSTGRES_ROW_MAPPER_CONFIG, SQLITE_ROW_MAPPER_CONFIG, compileQueryWithDialect, createCommonOperationBackend, createEdgeRowMapper, createNodeRowMapper, createPostgresOperationStrategy, createPostgresTables, createPostgresVectorIndex, createSchemaVersionRowMapper, createSqliteOperationStrategy, createSqliteTables, createSqliteVectorIndex, createUniqueRowMapper, dropPostgresVectorIndex, dropSqliteVectorIndex, edges, edges2, embeddings, embeddings2, formatPostgresTimestamp, generatePostgresDDL, generatePostgresMigrationSQL, generateSqliteDDL, generateSqliteMigrationSQL, generateVectorIndexName, getOrCreateLru, nodes, nodes2, nowIso, schemaVersions, schemaVersions2, tables, tables2, uniques, uniques2 };
2342
+ //# sourceMappingURL=chunk-EY4LBX3F.js.map
2343
+ //# sourceMappingURL=chunk-EY4LBX3F.js.map