@nicia-ai/typegraph 0.25.0 → 0.26.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 (122) hide show
  1. package/dist/backend/postgres/index.cjs +167 -71
  2. package/dist/backend/postgres/index.cjs.map +1 -1
  3. package/dist/backend/postgres/index.d.cts +6 -8
  4. package/dist/backend/postgres/index.d.ts +6 -8
  5. package/dist/backend/postgres/index.js +119 -27
  6. package/dist/backend/postgres/index.js.map +1 -1
  7. package/dist/backend/sqlite/index.cjs +16 -15
  8. package/dist/backend/sqlite/index.d.cts +11 -26
  9. package/dist/backend/sqlite/index.d.ts +11 -26
  10. package/dist/backend/sqlite/index.js +6 -5
  11. package/dist/backend/sqlite/libsql.cjs +9 -8
  12. package/dist/backend/sqlite/libsql.cjs.map +1 -1
  13. package/dist/backend/sqlite/libsql.d.cts +4 -3
  14. package/dist/backend/sqlite/libsql.d.ts +4 -3
  15. package/dist/backend/sqlite/libsql.js +6 -5
  16. package/dist/backend/sqlite/libsql.js.map +1 -1
  17. package/dist/backend/sqlite/local.cjs +11 -10
  18. package/dist/backend/sqlite/local.cjs.map +1 -1
  19. package/dist/backend/sqlite/local.d.cts +4 -3
  20. package/dist/backend/sqlite/local.d.ts +4 -3
  21. package/dist/backend/sqlite/local.js +6 -5
  22. package/dist/backend/sqlite/local.js.map +1 -1
  23. package/dist/{chunk-LVCSL6A3.js → chunk-3W6AIFT2.js} +11 -34
  24. package/dist/chunk-3W6AIFT2.js.map +1 -0
  25. package/dist/chunk-4FJVSF3K.cjs +12 -0
  26. package/dist/{chunk-D2GO3RBL.cjs.map → chunk-4FJVSF3K.cjs.map} +1 -1
  27. package/dist/{chunk-7W3KAMVQ.cjs → chunk-4TJI44WP.cjs} +94 -119
  28. package/dist/chunk-4TJI44WP.cjs.map +1 -0
  29. package/dist/chunk-5H3BAMTB.js +32 -0
  30. package/dist/chunk-5H3BAMTB.js.map +1 -0
  31. package/dist/{chunk-OJ6IQVZG.js → chunk-DDVA4QBA.js} +177 -37
  32. package/dist/chunk-DDVA4QBA.js.map +1 -0
  33. package/dist/{chunk-7CDXX3QZ.cjs → chunk-DN4RUDF3.cjs} +2 -2
  34. package/dist/chunk-DN4RUDF3.cjs.map +1 -0
  35. package/dist/{chunk-NHQWXSTS.js → chunk-E5ROA3MN.js} +3 -3
  36. package/dist/{chunk-NHQWXSTS.js.map → chunk-E5ROA3MN.js.map} +1 -1
  37. package/dist/{chunk-FPCOUJSL.js → chunk-ENXJLDRK.js} +2 -2
  38. package/dist/chunk-ENXJLDRK.js.map +1 -0
  39. package/dist/chunk-IUIWCFG3.cjs +36 -0
  40. package/dist/chunk-IUIWCFG3.cjs.map +1 -0
  41. package/dist/{chunk-EG6TJ3I5.js → chunk-OYLF3IC7.js} +3 -3
  42. package/dist/{chunk-EG6TJ3I5.js.map → chunk-OYLF3IC7.js.map} +1 -1
  43. package/dist/{chunk-JTI5WT4P.cjs → chunk-PN37HVAV.cjs} +32 -10
  44. package/dist/chunk-PN37HVAV.cjs.map +1 -0
  45. package/dist/{chunk-RCAJZG67.cjs → chunk-PYJOBZR3.cjs} +10 -10
  46. package/dist/{chunk-RCAJZG67.cjs.map → chunk-PYJOBZR3.cjs.map} +1 -1
  47. package/dist/{chunk-WI5VRP3X.js → chunk-RF5EUQWS.js} +371 -47
  48. package/dist/chunk-RF5EUQWS.js.map +1 -0
  49. package/dist/{chunk-ZEMNF3QK.cjs → chunk-RVT2N4RF.cjs} +209 -69
  50. package/dist/chunk-RVT2N4RF.cjs.map +1 -0
  51. package/dist/{chunk-4BOWVUGQ.js → chunk-TSGBRPNE.js} +3 -3
  52. package/dist/{chunk-4BOWVUGQ.js.map → chunk-TSGBRPNE.js.map} +1 -1
  53. package/dist/{chunk-O2P3KAUT.cjs → chunk-TVUARC7S.cjs} +445 -110
  54. package/dist/chunk-TVUARC7S.cjs.map +1 -0
  55. package/dist/{chunk-DOTEN2FG.js → chunk-U5ROKVRF.js} +26 -3
  56. package/dist/chunk-U5ROKVRF.js.map +1 -0
  57. package/dist/{chunk-E5JZSEGJ.cjs → chunk-WFUN6DCM.cjs} +8 -8
  58. package/dist/{chunk-E5JZSEGJ.cjs.map → chunk-WFUN6DCM.cjs.map} +1 -1
  59. package/dist/{chunk-W5MTHMTE.cjs → chunk-YEDQLNVE.cjs} +26 -2
  60. package/dist/chunk-YEDQLNVE.cjs.map +1 -0
  61. package/dist/{chunk-YZZBDCLV.js → chunk-ZTREJOGB.js} +32 -11
  62. package/dist/chunk-ZTREJOGB.js.map +1 -0
  63. package/dist/{ddl-B2jjLjpR.d.cts → ddl-9kw8UADK.d.ts} +697 -29
  64. package/dist/{ddl-DpaeAKPp.d.ts → ddl-Cw82BPM4.d.cts} +697 -29
  65. package/dist/{extension-types-D07e_NTw.d.cts → extension-types-B78CZfA5.d.cts} +1 -1
  66. package/dist/{extension-types-D07e_NTw.d.ts → extension-types-B78CZfA5.d.ts} +1 -1
  67. package/dist/graph-extension/index.cjs +18 -18
  68. package/dist/graph-extension/index.d.cts +4 -4
  69. package/dist/graph-extension/index.d.ts +4 -4
  70. package/dist/graph-extension/index.js +3 -3
  71. package/dist/{index-CT6nvtxL.d.cts → index-Bilw0pYm.d.cts} +34 -3
  72. package/dist/{index-DQheiVQV.d.ts → index-CWdBFWbI.d.ts} +34 -3
  73. package/dist/index.cjs +460 -361
  74. package/dist/index.cjs.map +1 -1
  75. package/dist/index.d.cts +13 -11
  76. package/dist/index.d.ts +13 -11
  77. package/dist/index.js +131 -36
  78. package/dist/index.js.map +1 -1
  79. package/dist/indexes/index.cjs +13 -13
  80. package/dist/indexes/index.d.cts +5 -5
  81. package/dist/indexes/index.d.ts +5 -5
  82. package/dist/indexes/index.js +1 -1
  83. package/dist/interchange/index.cjs +7 -7
  84. package/dist/interchange/index.d.cts +7 -5
  85. package/dist/interchange/index.d.ts +7 -5
  86. package/dist/interchange/index.js +2 -2
  87. package/dist/{manager-BpjBW1JK.d.cts → manager-Aqzmztkb.d.cts} +11 -3
  88. package/dist/{manager-BKaPQbns.d.ts → manager-C3LxzPcX.d.ts} +11 -3
  89. package/dist/{materialize-indexes-BB9N5uQl.d.cts → materialize-indexes-BQfaAZKA.d.cts} +1 -1
  90. package/dist/{materialize-indexes-BYpU2RKh.d.ts → materialize-indexes-DFavFQah.d.ts} +1 -1
  91. package/dist/profiler/index.d.cts +9 -7
  92. package/dist/profiler/index.d.ts +9 -7
  93. package/dist/schema/index.cjs +28 -27
  94. package/dist/schema/index.cjs.map +1 -1
  95. package/dist/schema/index.d.cts +9 -7
  96. package/dist/schema/index.d.ts +9 -7
  97. package/dist/schema/index.js +6 -5
  98. package/dist/schema/index.js.map +1 -1
  99. package/dist/{sqlite-Myo8e3Lr.d.cts → sqlite-BvSEbybu.d.cts} +320 -1
  100. package/dist/{sqlite-CU3j6rc7.d.ts → sqlite-GKvcDPVn.d.ts} +320 -1
  101. package/dist/{store-BAGuOHDh.d.cts → store-CiS_AGNH.d.ts} +112 -4
  102. package/dist/{store-De98Lod4.d.ts → store-DbQLsSor.d.cts} +112 -4
  103. package/dist/{types-CYga3lZp.d.cts → types-CF7nDH3q.d.cts} +2 -2
  104. package/dist/{types-BLmJq4wI.d.ts → types-Cars4JZ1.d.ts} +2 -2
  105. package/dist/{types--0EslBx5.d.cts → types-DZPBXZOK.d.cts} +275 -8
  106. package/dist/{types-BNWYZ-0-.d.ts → types-Dzkr0Eqi.d.ts} +275 -8
  107. package/dist/{where-m1uWsdua.d.cts → where-BmtjfWuS.d.cts} +2 -2
  108. package/dist/{where-CluR73rs.d.ts → where-kk1Zz2En.d.ts} +2 -2
  109. package/package.json +3 -1
  110. package/dist/chunk-7CDXX3QZ.cjs.map +0 -1
  111. package/dist/chunk-7W3KAMVQ.cjs.map +0 -1
  112. package/dist/chunk-D2GO3RBL.cjs +0 -12
  113. package/dist/chunk-DOTEN2FG.js.map +0 -1
  114. package/dist/chunk-FPCOUJSL.js.map +0 -1
  115. package/dist/chunk-JTI5WT4P.cjs.map +0 -1
  116. package/dist/chunk-LVCSL6A3.js.map +0 -1
  117. package/dist/chunk-O2P3KAUT.cjs.map +0 -1
  118. package/dist/chunk-OJ6IQVZG.js.map +0 -1
  119. package/dist/chunk-W5MTHMTE.cjs.map +0 -1
  120. package/dist/chunk-WI5VRP3X.js.map +0 -1
  121. package/dist/chunk-YZZBDCLV.js.map +0 -1
  122. package/dist/chunk-ZEMNF3QK.cjs.map +0 -1
@@ -1,12 +0,0 @@
1
- 'use strict';
2
-
3
- var chunkRCAJZG67_cjs = require('./chunk-RCAJZG67.cjs');
4
-
5
- // src/graph-extension/define-graph-extension.ts
6
- function defineGraphExtension(input) {
7
- return chunkRCAJZG67_cjs.unwrap(chunkRCAJZG67_cjs.validateGraphExtension(input, { strict: true }));
8
- }
9
-
10
- exports.defineGraphExtension = defineGraphExtension;
11
- //# sourceMappingURL=chunk-D2GO3RBL.cjs.map
12
- //# sourceMappingURL=chunk-D2GO3RBL.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/errors/index.ts"],"names":[],"mappings":";AAyDA,SAAS,YAAY,KAAA,EAAwB;AAC3C,EAAA,IAAI,iBAAiB,KAAA,EAAO;AAC1B,IAAA,OAAO,KAAA,CAAM,SAAS,KAAA,CAAM,OAAA;AAAA,EAC9B;AACA,EAAA,IAAI,OAAO,UAAU,QAAA,EAAU;AAC7B,IAAA,OAAO,KAAA;AAAA,EACT;AACA,EAAA,IACE,OAAO,UAAU,QAAA,IACjB,OAAO,UAAU,SAAA,IACjB,OAAO,UAAU,QAAA,EACjB;AACA,IAAA,OAAO,OAAO,KAAK,CAAA;AAAA,EACrB;AACA,EAAA,IAAI,OAAO,UAAU,QAAA,EAAU;AAC7B,IAAA,OAAO,MAAM,WAAA,IAAe,QAAA;AAAA,EAC9B;AACA,EAAA,IAAI,UAAU,MAAA,EAAW;AACvB,IAAA,OAAO,eAAA;AAAA,EACT;AAEA,EAAA,IAAI;AACF,IAAA,OAAO,IAAA,CAAK,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CAAA,IAAK,KAAA,CAAM,QAAA,KAAa,QAAA;AACvD;AAKO,SAAS,kBAAkB,KAAA,EAAyB;AACzD,EAAA,OAAO,gBAAA,CAAiB,KAAK,CAAA,IAAK,KAAA,CAAM,QAAA,KAAa,YAAA;AACvD;AAKO,SAAS,mBAAmB,KAAA,EAAoC;AACrE,EAAA,OAAO,gBAAA,CAAiB,KAAK,CAAA,GAAI,KAAA,CAAM,UAAA,GAAa,MAAA;AACtD","file":"chunk-DOTEN2FG.js","sourcesContent":["/**\n * TypeGraph Error Hierarchy\n *\n * All errors extend TypeGraphError with:\n * - `code`: Machine-readable error code for programmatic handling\n * - `category`: Classification for error handling strategies\n * - `suggestion`: Optional recovery guidance for users\n * - `details`: Structured context about the error\n *\n * @example\n * ```typescript\n * try {\n * await store.nodes.Person.create({ name: \"\" });\n * } catch (error) {\n * if (isTypeGraphError(error)) {\n * console.error(error.toUserMessage());\n * if (isUserRecoverable(error)) {\n * // Show to user for correction\n * }\n * }\n * }\n * ```\n */\n\nimport type { KindEntity } from \"../core/types\";\n// Type-only import: `materialize-indexes.ts` value-imports\n// `ConfigurationError` from this file, but type-only imports are erased\n// at runtime so this back-edge does not create a value cycle.\nimport type { MaterializeIndexesResult } from \"../store/materialize-indexes\";\n\n// ============================================================\n// Types\n// ============================================================\n\n/**\n * Error category for programmatic handling.\n *\n * - `user`: Caused by invalid input or incorrect usage. Recoverable by fixing input.\n * - `constraint`: Business rule or schema constraint violation. Recoverable by changing data.\n * - `system`: Internal error or infrastructure issue. May require investigation or retry.\n */\nexport type ErrorCategory = \"user\" | \"constraint\" | \"system\";\n\n/**\n * Options for TypeGraphError constructor.\n */\nexport type TypeGraphErrorOptions = Readonly<{\n /** Structured context about the error */\n details?: Record<string, unknown>;\n /** Error category for handling strategies */\n category: ErrorCategory;\n /** Recovery guidance for users */\n suggestion?: string;\n /** Underlying cause of the error */\n cause?: unknown;\n}>;\n\nfunction formatCause(cause: unknown): string {\n if (cause instanceof Error) {\n return cause.stack ?? cause.message;\n }\n if (typeof cause === \"string\") {\n return cause;\n }\n if (\n typeof cause === \"number\" ||\n typeof cause === \"boolean\" ||\n typeof cause === \"bigint\"\n ) {\n return String(cause);\n }\n if (typeof cause === \"symbol\") {\n return cause.description ?? \"Symbol\";\n }\n if (cause === undefined) {\n return \"Unknown cause\";\n }\n\n try {\n return JSON.stringify(cause);\n } catch (error) {\n return `Unserializable cause: ${\n error instanceof Error ? error.message : \"Unknown error\"\n }`;\n }\n}\n\n// ============================================================\n// Base Error\n// ============================================================\n\n/**\n * Base error class for all TypeGraph errors.\n *\n * Provides structured error information for both programmatic handling\n * and user-friendly messages.\n */\nexport class TypeGraphError extends Error {\n /** Machine-readable error code (e.g., \"VALIDATION_ERROR\") */\n readonly code: string;\n\n /** Error category for handling strategies */\n readonly category: ErrorCategory;\n\n /** Structured context about the error */\n readonly details: Readonly<Record<string, unknown>>;\n\n /** Recovery guidance for users */\n readonly suggestion?: string;\n\n constructor(message: string, code: string, options: TypeGraphErrorOptions) {\n super(message, options.cause ? { cause: options.cause } : undefined);\n this.name = \"TypeGraphError\";\n this.code = code;\n this.category = options.category;\n this.details = Object.freeze(options.details ?? {});\n if (options.suggestion !== undefined) {\n this.suggestion = options.suggestion;\n }\n }\n\n /**\n * Returns a user-friendly error message with suggestion if available.\n */\n toUserMessage(): string {\n if (this.suggestion) {\n return `${this.message}\\n\\nSuggestion: ${this.suggestion}`;\n }\n return this.message;\n }\n\n /**\n * Returns a detailed string representation for logging.\n */\n toLogString(): string {\n const lines = [\n `[${this.code}] ${this.message}`,\n ` Category: ${this.category}`,\n ];\n\n if (this.suggestion) {\n lines.push(` Suggestion: ${this.suggestion}`);\n }\n\n const detailKeys = Object.keys(this.details);\n if (detailKeys.length > 0) {\n lines.push(` Details: ${JSON.stringify(this.details)}`);\n }\n\n if (this.cause) {\n lines.push(` Cause: ${formatCause(this.cause)}`);\n }\n\n return lines.join(\"\\n\");\n }\n}\n\n// ============================================================\n// Validation Errors (category: \"user\")\n// ============================================================\n\n/**\n * Validation issue from Zod or custom validation.\n */\nexport type ValidationIssue = Readonly<{\n /** Path to the invalid field (e.g., \"address.city\") */\n path: string;\n /** Human-readable error message */\n message: string;\n /** Zod error code if from Zod validation */\n code?: string;\n}>;\n\n/**\n * Details for ValidationError.\n */\nexport type ValidationErrorDetails = Readonly<{\n /** Type of entity being validated */\n entityType?: KindEntity;\n /** Kind/type name of the entity */\n kind?: string;\n /** Operation being performed */\n operation?: \"create\" | \"update\";\n /** Entity ID if updating */\n id?: string;\n /** Individual validation issues */\n issues: readonly ValidationIssue[];\n}>;\n\n/**\n * Thrown when schema validation fails during node or edge operations.\n *\n * @example\n * ```typescript\n * try {\n * await store.nodes.Person.create({ email: \"invalid\" });\n * } catch (error) {\n * if (error instanceof ValidationError) {\n * console.log(error.details.issues);\n * // [{ path: \"email\", message: \"Invalid email\" }]\n * }\n * }\n * ```\n */\nexport class ValidationError extends TypeGraphError {\n declare readonly details: ValidationErrorDetails;\n\n constructor(\n message: string,\n details: ValidationErrorDetails,\n options?: { cause?: unknown; suggestion?: string },\n ) {\n const fieldList =\n details.issues.length > 0 ?\n details.issues.map((index) => index.path || \"(root)\").join(\", \")\n : \"unknown\";\n\n super(message, \"VALIDATION_ERROR\", {\n details,\n category: \"user\",\n suggestion:\n options?.suggestion ??\n `Check the following fields: ${fieldList}. See error.details.issues for specific validation failures.`,\n cause: options?.cause,\n });\n this.name = \"ValidationError\";\n }\n}\n\n// ============================================================\n// Not Found Errors (category: \"user\")\n// ============================================================\n\n/**\n * Thrown when a node is not found.\n *\n * @example\n * ```typescript\n * try {\n * await store.nodes.Person.get(\"nonexistent-id\");\n * } catch (error) {\n * if (error instanceof NodeNotFoundError) {\n * console.log(error.details.kind, error.details.id);\n * }\n * }\n * ```\n */\nexport class NodeNotFoundError extends TypeGraphError {\n constructor(kind: string, id: string, options?: { cause?: unknown }) {\n super(`Node not found: ${kind}/${id}`, \"NODE_NOT_FOUND\", {\n details: { kind, id },\n category: \"user\",\n suggestion: `Verify the node ID \"${id}\" exists and has not been deleted.`,\n cause: options?.cause,\n });\n this.name = \"NodeNotFoundError\";\n }\n}\n\n/**\n * Thrown when an edge is not found.\n */\nexport class EdgeNotFoundError extends TypeGraphError {\n constructor(kind: string, id: string, options?: { cause?: unknown }) {\n super(`Edge not found: ${kind}/${id}`, \"EDGE_NOT_FOUND\", {\n details: { kind, id },\n category: \"user\",\n suggestion: `Verify the edge ID \"${id}\" exists and has not been deleted.`,\n cause: options?.cause,\n });\n this.name = \"EdgeNotFoundError\";\n }\n}\n\n/**\n * Thrown when an operation references a kind that isn't registered on\n * the graph — `getNodeCollectionOrThrow` against an unknown kind, a\n * `materializeIndexes({ kinds })` filter naming a missing kind, an\n * extension referencing an unresolved endpoint, search facade typos,\n * etc. Carries the offending `kindName` and `entity` plus the host\n * `graphId` so logs are unambiguous when multiple stores share a\n * process.\n */\nexport class KindNotFoundError extends TypeGraphError {\n readonly kindName: string;\n readonly entity: KindEntity;\n\n constructor(\n kindName: string,\n entity: KindEntity,\n options?: Readonly<{\n graphId?: string;\n suggestion?: string;\n cause?: unknown;\n }>,\n ) {\n const where =\n options?.graphId === undefined ? \"\" : ` on graph \"${options.graphId}\"`;\n super(\n `${entity === \"node\" ? \"Node\" : \"Edge\"} kind \"${kindName}\" is not registered${where}.`,\n \"KIND_NOT_FOUND\",\n {\n details: {\n kindName,\n entity,\n ...(options?.graphId === undefined ?\n {}\n : { graphId: options.graphId }),\n },\n category: \"user\",\n suggestion:\n options?.suggestion ??\n \"Compile-time kinds come from defineGraph; extension kinds appear after store.evolve() returns. Check store.introspect() for the registered set.\",\n cause: options?.cause,\n },\n );\n this.name = \"KindNotFoundError\";\n this.kindName = kindName;\n this.entity = entity;\n }\n}\n\n/**\n * Thrown when a uniqueness constraint name is not found on a node kind.\n */\nexport class NodeConstraintNotFoundError extends TypeGraphError {\n constructor(\n constraintName: string,\n kind: string,\n options?: { cause?: unknown },\n ) {\n super(\n `Constraint not found: \"${constraintName}\" on node kind \"${kind}\"`,\n \"CONSTRAINT_NOT_FOUND\",\n {\n details: { constraintName, kind },\n category: \"user\",\n suggestion: `Verify the constraint name \"${constraintName}\" is defined in the unique constraints for \"${kind}\".`,\n cause: options?.cause,\n },\n );\n this.name = \"NodeConstraintNotFoundError\";\n }\n}\n\n// ============================================================\n// Constraint Errors (category: \"constraint\")\n// ============================================================\n\n/**\n * Thrown when edge endpoint node does not exist or is deleted.\n */\nexport class EndpointNotFoundError extends TypeGraphError {\n constructor(\n details: Readonly<{\n edgeKind: string;\n endpoint: \"from\" | \"to\";\n nodeKind: string;\n nodeId: string;\n }>,\n options?: { cause?: unknown },\n ) {\n super(\n `Endpoint node not found for edge \"${details.edgeKind}\": ${details.nodeKind}/${details.nodeId} (${details.endpoint})`,\n \"ENDPOINT_NOT_FOUND\",\n {\n details,\n category: \"constraint\",\n suggestion: `Ensure the ${details.endpoint} node exists before creating the edge.`,\n cause: options?.cause,\n },\n );\n this.name = \"EndpointNotFoundError\";\n }\n}\n\n/**\n * Thrown when edge endpoint has wrong node type.\n */\nexport class EndpointError extends TypeGraphError {\n constructor(\n details: Readonly<{\n edgeKind: string;\n endpoint: \"from\" | \"to\";\n actualKind: string;\n expectedKinds: readonly string[];\n }>,\n options?: { cause?: unknown },\n ) {\n const expected = details.expectedKinds.join(\" | \");\n super(\n `Invalid ${details.endpoint} endpoint for edge \"${details.edgeKind}\": got \"${details.actualKind}\", expected ${expected}`,\n \"ENDPOINT_ERROR\",\n {\n details,\n category: \"constraint\",\n suggestion: `Use a node of type ${expected} as the ${details.endpoint} endpoint.`,\n cause: options?.cause,\n },\n );\n this.name = \"EndpointError\";\n }\n}\n\n/**\n * Thrown when uniqueness constraint is violated.\n */\nexport class UniquenessError extends TypeGraphError {\n constructor(\n details: Readonly<{\n constraintName: string;\n kind: string;\n existingId: string;\n newId: string;\n fields: readonly string[];\n }>,\n options?: { cause?: unknown },\n ) {\n const fieldList = details.fields.join(\", \");\n super(\n `Uniqueness violation on \"${details.kind}\": constraint \"${details.constraintName}\" (fields: ${fieldList}) conflicts with existing node ${details.existingId}`,\n \"UNIQUENESS_VIOLATION\",\n {\n details,\n category: \"constraint\",\n suggestion: `Change the values for fields [${fieldList}] to be unique, or update the existing node ${details.existingId} instead.`,\n cause: options?.cause,\n },\n );\n this.name = \"UniquenessError\";\n }\n}\n\n/**\n * Thrown when cardinality constraint is violated.\n */\nexport class CardinalityError extends TypeGraphError {\n constructor(\n details: Readonly<{\n edgeKind: string;\n fromKind: string;\n fromId: string;\n cardinality: string;\n existingCount: number;\n }>,\n options?: { cause?: unknown },\n ) {\n super(\n `Cardinality violation: \"${details.edgeKind}\" from ${details.fromKind}/${details.fromId} allows \"${details.cardinality}\" but ${details.existingCount} edge(s) already exist`,\n \"CARDINALITY_ERROR\",\n {\n details,\n category: \"constraint\",\n suggestion:\n details.cardinality === \"one\" || details.cardinality === \"unique\" ?\n `Delete the existing edge before creating a new one, or use cardinality \"many\".`\n : `Check if the cardinality constraint \"${details.cardinality}\" is correct for your use case.`,\n cause: options?.cause,\n },\n );\n this.name = \"CardinalityError\";\n }\n}\n\n/**\n * Thrown when disjointness constraint is violated.\n *\n * Disjoint types cannot share the same ID - a node cannot be both\n * a Person and an Organization if they are declared disjoint.\n */\nexport class DisjointError extends TypeGraphError {\n constructor(\n details: Readonly<{\n nodeId: string;\n attemptedKind: string;\n conflictingKind: string;\n }>,\n options?: { cause?: unknown },\n ) {\n super(\n `Disjoint constraint violation: cannot create ${details.attemptedKind} with ID \"${details.nodeId}\" - conflicts with existing ${details.conflictingKind}`,\n \"DISJOINT_ERROR\",\n {\n details,\n category: \"constraint\",\n suggestion: `Use a different ID for the new ${details.attemptedKind} node, or delete the existing ${details.conflictingKind}/${details.nodeId} first.`,\n cause: options?.cause,\n },\n );\n this.name = \"DisjointError\";\n }\n}\n\n/**\n * Thrown when deletion is blocked due to existing edges (restrict behavior).\n */\nexport class RestrictedDeleteError extends TypeGraphError {\n constructor(\n details: Readonly<{\n nodeKind: string;\n nodeId: string;\n edgeCount: number;\n edgeKinds: readonly string[];\n }>,\n options?: { cause?: unknown },\n ) {\n const edgeList = details.edgeKinds.join(\", \");\n super(\n `Cannot delete ${details.nodeKind}/${details.nodeId}: ${details.edgeCount} connected edge(s) exist (${edgeList})`,\n \"RESTRICTED_DELETE\",\n {\n details,\n category: \"constraint\",\n suggestion: `Delete the connected edges first, or change onDelete behavior to \"cascade\" (auto-delete edges) or \"disconnect\" (soft-delete edges).`,\n cause: options?.cause,\n },\n );\n this.name = \"RestrictedDeleteError\";\n }\n}\n\n// ============================================================\n// Concurrency Errors (category: \"system\")\n// ============================================================\n\n/**\n * Thrown when optimistic locking detects a concurrent modification.\n *\n * This occurs when two operations try to update the same entity simultaneously.\n * The operation with the stale version fails.\n */\nexport class VersionConflictError extends TypeGraphError {\n constructor(\n details: Readonly<{\n kind: string;\n id: string;\n expectedVersion: number;\n actualVersion: number;\n }>,\n options?: { cause?: unknown },\n ) {\n super(\n `Version conflict on ${details.kind}/${details.id}: expected version ${details.expectedVersion}, found ${details.actualVersion}`,\n \"VERSION_CONFLICT\",\n {\n details,\n category: \"system\",\n suggestion: `Fetch the latest version of the entity and retry the operation. This error indicates concurrent modification.`,\n cause: options?.cause,\n },\n );\n this.name = \"VersionConflictError\";\n }\n}\n\n// ============================================================\n// Schema Errors (category: \"system\")\n// ============================================================\n\n/**\n * Thrown when the schema in code doesn't match the schema in the database.\n */\nexport class SchemaMismatchError extends TypeGraphError {\n constructor(\n details: Readonly<{\n graphId: string;\n expectedHash: string;\n actualHash: string;\n }>,\n options?: { cause?: unknown },\n ) {\n super(\n `Schema mismatch for graph \"${details.graphId}\": code schema differs from database schema`,\n \"SCHEMA_MISMATCH\",\n {\n details,\n category: \"system\",\n suggestion: `Run schema migration to update the database, or use createStoreWithSchema() for automatic migration.`,\n cause: options?.cause,\n },\n );\n this.name = \"SchemaMismatchError\";\n }\n}\n\n/**\n * Thrown when schema migration fails.\n */\nexport class MigrationError extends TypeGraphError {\n constructor(\n message: string,\n details: Readonly<{\n graphId: string;\n fromVersion: number;\n toVersion: number;\n reason?: string;\n }>,\n options?: { cause?: unknown },\n ) {\n super(message, \"MIGRATION_ERROR\", {\n details,\n category: \"system\",\n suggestion: `Review the schema changes and ensure they are backwards compatible, or implement a data migration.`,\n cause: options?.cause,\n });\n this.name = \"MigrationError\";\n }\n}\n\n/**\n * Thrown by `Store.evolve(extension, { eager })` when the schema\n * commit succeeded but the follow-on `materializeIndexes()` produced\n * one or more failed entries.\n *\n * Recovery: the schema commit is NOT rolled back. The new `Store` is\n * fully constructed and (when `options.ref` was supplied) `ref.current`\n * already points to it — the caller can read the new store via the ref\n * and decide how to handle the failed indexes (retry, skip, alert).\n * The full `MaterializeIndexesResult` is attached as `.materialization`.\n *\n * @example\n * ```ts\n * const ref = { current: store };\n * try {\n * await store.evolve(extension, { ref, eager: {} });\n * } catch (error) {\n * if (error instanceof EagerMaterializationError) {\n * // schema is committed; ref.current is the new store\n * log.warn(\n * { failed: error.failedIndexNames },\n * \"indexes did not materialize; will retry\",\n * );\n * await ref.current.materializeIndexes();\n * } else {\n * throw error;\n * }\n * }\n * ```\n */\nexport class EagerMaterializationError extends TypeGraphError {\n /**\n * The full materialization result, including successful and failed\n * entries. Same shape as `Store.materializeIndexes()` returns.\n */\n readonly materialization: MaterializeIndexesResult;\n\n constructor(materialization: MaterializeIndexesResult, graphId: string) {\n const names = collectFailedIndexNames(materialization);\n super(\n `Eager materialization failed for ${names.length} index(es) on graph \"${graphId}\": ${names.join(\", \")}. The schema commit succeeded; the new Store is available via the ref handle (when supplied) and the failed indexes can be retried via store.materializeIndexes().`,\n \"EAGER_MATERIALIZATION_FAILED\",\n {\n details: { graphId, failedIndexNames: names },\n category: \"system\",\n suggestion: `Inspect error.materialization for per-index errors. Each failure preserves any prior successful materialization timestamp; the schema is committed regardless.`,\n },\n );\n this.name = \"EagerMaterializationError\";\n this.materialization = materialization;\n }\n\n /**\n * Names of just the indexes that failed — derived from\n * `materialization.results` so the two views can never disagree.\n */\n get failedIndexNames(): readonly string[] {\n return collectFailedIndexNames(this.materialization);\n }\n}\n\nfunction collectFailedIndexNames(\n materialization: MaterializeIndexesResult,\n): readonly string[] {\n const names: string[] = [];\n for (const entry of materialization.results) {\n if (entry.status === \"failed\") names.push(entry.indexName);\n }\n return names;\n}\n\n/**\n * Thrown by `commitSchemaVersion` and `setActiveVersion` when the\n * caller's view of the active schema version is out of date — another\n * writer has already advanced it.\n *\n * Recovery: re-read the active version with `getActiveSchema(graphId)`,\n * recompute against the new baseline, and retry. This is a routine\n * concurrency signal, not a bug.\n *\n * `actual` is `0` when no active version exists yet (initial-commit race\n * where another writer initialized first).\n */\nexport class StaleVersionError extends TypeGraphError {\n declare readonly details: Readonly<{\n graphId: string;\n expected: number;\n actual: number;\n }>;\n\n constructor(\n details: Readonly<{\n graphId: string;\n expected: number;\n actual: number;\n }>,\n options?: { cause?: unknown },\n ) {\n super(\n `Schema version was advanced by another writer for graph \"${details.graphId}\": expected active version ${details.expected}, actual is ${details.actual}`,\n \"STALE_SCHEMA_VERSION\",\n {\n details,\n category: \"system\",\n suggestion: `Re-read the active schema version, recompute the new version against that baseline, and retry the commit.`,\n cause: options?.cause,\n },\n );\n this.name = \"StaleVersionError\";\n }\n}\n\n/**\n * Thrown by `commitSchemaVersion` when a row already exists at the\n * target version with a *different* schema hash — i.e. two writers\n * committed materially different schemas at the same version number.\n *\n * Distinct from `StaleVersionError`: this is not a refetch-and-retry\n * situation, it's a content disagreement that needs operator\n * intervention. Typically caused by inconsistent application\n * deployments writing schemas that hash differently.\n */\nexport class SchemaContentConflictError extends TypeGraphError {\n declare readonly details: Readonly<{\n graphId: string;\n version: number;\n existingHash: string;\n incomingHash: string;\n }>;\n\n constructor(\n details: Readonly<{\n graphId: string;\n version: number;\n existingHash: string;\n incomingHash: string;\n }>,\n options?: { cause?: unknown },\n ) {\n super(\n `Schema content conflict for graph \"${details.graphId}\" at version ${details.version}: existing hash ${details.existingHash} differs from incoming hash ${details.incomingHash}`,\n \"SCHEMA_CONTENT_CONFLICT\",\n {\n details,\n category: \"system\",\n suggestion: `Two writers committed different schemas at the same version. Reconcile the application deployments so they produce the same canonical schema, then retry.`,\n cause: options?.cause,\n },\n );\n this.name = \"SchemaContentConflictError\";\n }\n}\n\n// ============================================================\n// Configuration Errors (category: \"user\")\n// ============================================================\n\n/**\n * Thrown when graph configuration is invalid.\n *\n * This includes invalid schema definitions, ontology conflicts,\n * and other configuration issues detected at graph creation time.\n */\nexport class ConfigurationError extends TypeGraphError {\n constructor(\n message: string,\n details: Record<string, unknown> = {},\n options?: { cause?: unknown; suggestion?: string },\n ) {\n super(message, \"CONFIGURATION_ERROR\", {\n details,\n category: \"user\",\n suggestion:\n options?.suggestion ?? `Review your graph definition for errors.`,\n cause: options?.cause,\n });\n this.name = \"ConfigurationError\";\n }\n}\n\n// ============================================================\n// Database Errors (category: \"system\")\n// ============================================================\n\n/**\n * Thrown when a database operation fails unexpectedly.\n *\n * This indicates a system-level failure in the database backend,\n * not a user-recoverable error.\n */\nexport class DatabaseOperationError extends TypeGraphError {\n constructor(\n message: string,\n details: Readonly<{ operation: string; entity: string }>,\n options?: { cause?: unknown },\n ) {\n super(message, \"DATABASE_OPERATION_ERROR\", {\n details,\n category: \"system\",\n suggestion: `This is a system-level database error. Check the database connection and retry the operation. If the problem persists, investigate the underlying cause.`,\n cause: options?.cause,\n });\n this.name = \"DatabaseOperationError\";\n }\n}\n\n// ============================================================\n// Query Errors (category: \"system\")\n// ============================================================\n\n/**\n * Thrown when a query predicate cannot be compiled for the target database.\n */\nexport class UnsupportedPredicateError extends TypeGraphError {\n constructor(\n message: string,\n details: Readonly<Record<string, unknown>> = {},\n options?: { cause?: unknown; suggestion?: string },\n ) {\n super(message, \"UNSUPPORTED_PREDICATE\", {\n details,\n category: \"system\",\n suggestion:\n options?.suggestion ??\n `This predicate may not be supported by your database backend. Check the documentation for supported predicates.`,\n cause: options?.cause,\n });\n this.name = \"UnsupportedPredicateError\";\n }\n}\n\n// ============================================================\n// Compiler Errors (category: \"system\")\n// ============================================================\n\n/**\n * Thrown when a compiler invariant is violated.\n *\n * This indicates a bug in the query compiler — the compiler reached\n * a state that should be unreachable. These errors are not user-recoverable.\n */\nexport class CompilerInvariantError extends TypeGraphError {\n constructor(\n message: string,\n details?: Readonly<Record<string, unknown>>,\n options?: { cause?: unknown },\n ) {\n super(message, \"COMPILER_INVARIANT_ERROR\", {\n details: details ?? {},\n category: \"system\",\n suggestion: `This is an internal compiler error. Please report it as a bug with the query that triggered it.`,\n cause: options?.cause,\n });\n this.name = \"CompilerInvariantError\";\n }\n}\n\n// ============================================================\n// Lifecycle Errors (category: \"system\")\n// ============================================================\n\n/**\n * Thrown when an operation is attempted on a backend that has been disposed.\n *\n * This typically occurs during runtime teardown — for example, when a\n * Cloudflare Workers test runner resets Durable Object storage while\n * the TypeGraph backend still has queued operations.\n */\nexport class BackendDisposedError extends TypeGraphError {\n constructor(options?: { cause?: unknown }) {\n super(\n \"Backend has been disposed — the underlying database connection is no longer available\",\n \"BACKEND_DISPOSED\",\n {\n category: \"system\",\n suggestion:\n \"Ensure all store operations complete before calling backend.close(). \" +\n \"In test environments, await store teardown before resetting the database.\",\n cause: options?.cause,\n },\n );\n this.name = \"BackendDisposedError\";\n }\n}\n\n// ============================================================\n// Utility Functions\n// ============================================================\n\n/**\n * Type guard for TypeGraphError.\n *\n * @example\n * ```typescript\n * try {\n * await store.nodes.Person.create({});\n * } catch (error) {\n * if (isTypeGraphError(error)) {\n * console.log(error.code, error.category);\n * }\n * }\n * ```\n */\nexport function isTypeGraphError(error: unknown): error is TypeGraphError {\n return error instanceof TypeGraphError;\n}\n\n/**\n * Check if error is recoverable by user action (user or constraint error).\n *\n * User-recoverable errors can typically be resolved by:\n * - Fixing invalid input data\n * - Using different IDs or values\n * - Deleting conflicting data first\n *\n * @example\n * ```typescript\n * if (isUserRecoverable(error)) {\n * showErrorToUser(error.toUserMessage());\n * } else {\n * logAndAlertOps(error);\n * }\n * ```\n */\nexport function isUserRecoverable(error: unknown): boolean {\n if (!isTypeGraphError(error)) return false;\n return error.category === \"user\" || error.category === \"constraint\";\n}\n\n/**\n * Check if error indicates a system/infrastructure issue.\n *\n * System errors typically require:\n * - Retry logic (for transient failures)\n * - Investigation (for persistent failures)\n * - Ops team notification\n */\nexport function isSystemError(error: unknown): boolean {\n return isTypeGraphError(error) && error.category === \"system\";\n}\n\n/**\n * Check if error is a constraint violation.\n */\nexport function isConstraintError(error: unknown): boolean {\n return isTypeGraphError(error) && error.category === \"constraint\";\n}\n\n/**\n * Extract suggestion from error if available.\n */\nexport function getErrorSuggestion(error: unknown): string | undefined {\n return isTypeGraphError(error) ? error.suggestion : undefined;\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/backend/types.ts"],"names":[],"mappings":";AA48BO,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;AA4OO,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-FPCOUJSL.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 {\n type IndexEntity,\n type KindEntity,\n type TemporalMode,\n} 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 * Build the index without taking an `AccessExclusiveLock` on live\n * tables (Postgres `CREATE INDEX CONCURRENTLY`). Mirrors the\n * `concurrent` flag the relational DDL path uses inside\n * `materializeIndexes()`. Cannot be set inside a transaction —\n * callers (`materializeIndexes()`) run at top level. Backends that\n * don't have a CONCURRENTLY equivalent (SQLite) ignore this flag.\n */\n concurrent?: boolean;\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 *\n * Note: `createFulltextIndex` / `dropFulltextIndex` were removed as\n * dead code in #PR_E. The fulltext table's canonical index (Postgres\n * GIN on `tsv`, SQLite FTS5 virtual table) is created with the table\n * itself by `bootstrapTables` per the active `FulltextStrategy`;\n * per-kind fulltext indexes are an \"advanced strategy\" surface that\n * doesn't fit the relational-style declaration model and is reserved\n * for future work.\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 */\n\n// ============================================================\n// Index Materialization Status\n// ============================================================\n\n/**\n * Per-deployment record for a single declared index.\n *\n * Identified by `indexName` because SQL index names are physical,\n * database-global identifiers — `graphId` is provenance, not identity.\n * `materializedAt` is null until the first successful CREATE INDEX\n * completes; `lastAttemptedAt` is always set, even on failure.\n */\nexport type IndexMaterializationRow = Readonly<{\n indexName: string;\n graphId: string;\n entity: IndexEntity;\n kind: string;\n signature: string;\n schemaVersion: number;\n materializedAt: string | undefined;\n lastAttemptedAt: string;\n lastError: string | undefined;\n}>;\n\n/**\n * Parameters for upserting a materialization attempt.\n *\n * On success: pass `materializedAt` (ISO timestamp) and undefined `error`.\n * On failure: pass undefined `materializedAt` (preserve any existing\n * timestamp from a prior success) and the error message.\n */\nexport type RecordIndexMaterializationParams = Readonly<{\n indexName: string;\n graphId: string;\n entity: IndexEntity;\n kind: string;\n signature: string;\n schemaVersion: number;\n attemptedAt: string;\n /** ISO timestamp on success; undefined on failure (preserves existing). */\n materializedAt: string | undefined;\n /** Error message on failure; undefined on success (clears existing). */\n error: string | undefined;\n}>;\n\n// ============================================================\n// Kind Removals (data-cleanup status)\n// ============================================================\n\n/**\n * One row of the per-deployment `typegraph_kind_removals` table:\n * a graph-extension kind that has been removed from the schema and whose\n * data may or may not have been cleaned up yet.\n */\nexport type KindRemovalRow = Readonly<{\n graphId: string;\n kindName: string;\n entity: KindEntity;\n schemaVersion: number;\n /** ISO timestamp when the data-cleanup pass succeeded; undefined while pending. */\n removedAt: string | undefined;\n lastAttemptedAt: string;\n lastError: string | undefined;\n}>;\n\n/**\n * Upsert payload for a kind-removal status row. On removal-commit:\n * pass `removedAt: undefined` (the pending state). On successful\n * data-cleanup: pass `removedAt` set and `error: undefined`. On\n * cleanup failure: pass `removedAt: undefined` (preserves any prior\n * timestamp from a partial success on a different replica) and the\n * error message.\n */\nexport type RecordKindRemovalParams = Readonly<{\n graphId: string;\n kindName: string;\n entity: KindEntity;\n schemaVersion: number;\n attemptedAt: string;\n /** ISO timestamp on success; undefined while pending or on failure. */\n removedAt: string | undefined;\n /** Error message on failure; undefined on success or while pending. */\n error: string | undefined;\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 *\n * `commitSchemaVersion` and `setActiveVersion` are intentionally omitted:\n * the atomicity / CAS guarantees of those primitives depend on\n * dialect-specific write-locking (BEGIN IMMEDIATE on SQLite,\n * `pg_advisory_xact_lock` on Postgres) acquired by the top-level\n * backend wrappers, not the transaction itself. Calling them from a\n * user-supplied `backend.transaction(...)` callback would bypass that\n * locking and silently weaken the orphan-row crash window the primitive\n * exists to eliminate. Schema commits go through the top-level backend\n * methods only.\n */\nexport type TransactionBackend = Omit<\n GraphBackend,\n | \"transaction\"\n | \"close\"\n | \"refreshStatistics\"\n | \"commitSchemaVersion\"\n | \"setActiveVersion\"\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 /**\n * Atomically inserts a new schema version and activates it as a single\n * transactional unit, with optimistic compare-and-swap on the currently\n * active version.\n *\n * - If `expected.kind === \"active\"` and the actual active version\n * differs, throws `StaleVersionError` (caller should refetch and\n * retry).\n * - If a row already exists at `params.version` with the same\n * `schemaHash`, returns it idempotently — reactivating it if it was\n * left inactive by an earlier crashed commit.\n * - If a row already exists at `params.version` with a different\n * `schemaHash`, throws `SchemaContentConflictError`.\n *\n * Requires `capabilities.transactions === true`. On non-transactional\n * backends (e.g. Cloudflare D1, drizzle-orm/neon-http) this method\n * throws `ConfigurationError` rather than running with degraded\n * atomicity that would silently re-introduce the orphan-row crash\n * window the primitive exists to eliminate.\n */\n commitSchemaVersion: (\n params: CommitSchemaVersionParams,\n ) => Promise<SchemaVersionRow>;\n /**\n * Atomically flips the active schema pointer to an existing version,\n * with optimistic compare-and-swap on the currently active version.\n * Used by `rollbackSchema` and any other \"promote/demote existing\n * version\" workflow. Throws `StaleVersionError` on CAS mismatch and\n * `MigrationError` if the target version row does not exist.\n *\n * Same transactional requirements as `commitSchemaVersion`.\n */\n setActiveVersion: (params: SetActiveVersionParams) => 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\n // === Index Materialization (used by store.materializeIndexes) ===\n /**\n * Idempotently ensure ONLY the `typegraph_index_materializations`\n * table exists — separate from `bootstrapTables` so that\n * `materializeIndexes` doesn't pull in the full base-table DDL set\n * just to access the status table.\n *\n * Why focused: `bootstrapTables` issues 20+ `CREATE TABLE / CREATE\n * INDEX IF NOT EXISTS` statements covering every base table. Two\n * concurrent calls (e.g. two replicas of the same `schema_doc` both\n * starting up and calling `materializeIndexes`) race on\n * Postgres SHARE locks and DEADLOCK. Restricting the ensure-step to\n * the single status table eliminates the cross-table race entirely\n * — concurrent `CREATE TABLE IF NOT EXISTS` for one specific table\n * is well-behaved on Postgres.\n */\n ensureIndexMaterializationsTable?: () => Promise<void>;\n\n /**\n * Look up a recorded materialization for a declared index by its\n * physical SQL index name. Returns `undefined` if no row exists.\n */\n getIndexMaterialization?: (\n indexName: string,\n ) => Promise<IndexMaterializationRow | undefined>;\n /**\n * Bulk variant of `getIndexMaterialization`: load every recorded\n * materialization whose `indexName` (status key) is in `statusKeys`,\n * in a single round-trip. Returned rows are unordered — callers index\n * by `indexName`. Optional; consumers fall back to per-key\n * `getIndexMaterialization` when unset.\n */\n getIndexMaterializations?: (\n statusKeys: readonly string[],\n ) => Promise<readonly IndexMaterializationRow[]>;\n /**\n * Upsert a materialization attempt — success or failure. Failure rows\n * preserve any prior `materializedAt` so the historical successful\n * timestamp survives across error windows.\n */\n recordIndexMaterialization?: (\n params: RecordIndexMaterializationParams,\n ) => Promise<void>;\n\n // === Kind Removal Status ===\n\n /**\n * Bootstraps the per-deployment `typegraph_kind_removals` table so\n * `store.removeKinds()` and `store.materializeRemovals()` can persist\n * removal status. Mirrors the focused-bootstrap rationale documented\n * on `ensureIndexMaterializationsTable` — the full `bootstrapTables`\n * touches every base table and risks Postgres SHARE-lock deadlock\n * under concurrent replica startup.\n */\n ensureKindRemovalsTable?: () => Promise<void>;\n\n /**\n * List graph-extension kind removals whose data-cleanup pass has not yet\n * succeeded for this `graphId`. Returns rows with\n * `removedAt: undefined`. Order is unspecified; callers materialize\n * one-at-a-time and don't depend on it.\n */\n getPendingKindRemovals?: (\n graphId: string,\n ) => Promise<readonly KindRemovalRow[]>;\n\n /**\n * List ALL kind-removal rows for a `graphId` — pending and completed.\n * Used by `materializeRemovals()` reconciliation to detect rows that\n * are missing entirely (the `removeKinds()` crash window) versus\n * already completed. Without this distinction the reconciler would\n * have to upsert every expected historical removal on every call,\n * churning `last_attempted_at` on rows that long since succeeded.\n * Order is unspecified.\n */\n getAllKindRemovals?: (graphId: string) => Promise<readonly KindRemovalRow[]>;\n\n /**\n * Upsert a kind-removal status row. `removedAt: undefined` records\n * the pending state at schema-commit time; `removedAt: <iso>`\n * marks the data cleanup successful. The COALESCE rule on `removedAt`\n * mirrors `recordIndexMaterialization` so a later failure doesn't\n * clobber the historical successful timestamp from another replica.\n */\n recordKindRemoval?: (params: RecordKindRemovalParams) => Promise<void>;\n\n // === Reconciliation Watermark ===\n\n /**\n * Bootstraps the per-deployment `typegraph_reconciliation_markers`\n * table so `materializeRemovals()` can persist reconciliation\n * progress. Same focused-bootstrap rationale as the other status\n * tables — full `bootstrapTables` risks Postgres SHARE-lock\n * deadlock under concurrent replica startup.\n */\n ensureReconciliationMarkersTable?: () => Promise<void>;\n\n /**\n * Read the high-water mark schema version for which\n * `materializeRemovals` reconciliation has already verified history\n * for `graphId`. Returns `undefined` when no marker has been\n * recorded yet. Used to skip already-checked transitions in the\n * recovery walk.\n */\n getReconciliationMarker?: (graphId: string) => Promise<number | undefined>;\n\n /**\n * Persist the reconciliation high-water mark for `graphId`. Called\n * after `materializeRemovals` completes a clean walk; subsequent\n * calls walk only versions newer than this marker. Idempotent\n * upsert by `graphId`.\n */\n setReconciliationMarker?: (graphId: string, version: number) => 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 /**\n * Execute a DDL statement that returns no rows (CREATE INDEX,\n * CREATE TABLE, ALTER TABLE, etc.). Separate from `executeRaw`\n * because some drivers (better-sqlite3) require `.run()` for DDL\n * and `.all()` for queries — the ambiguity can't be resolved by\n * inspecting the SQL string portably.\n *\n * Postgres path can use this for `CREATE INDEX CONCURRENTLY`, which\n * cannot run inside a transaction. Implementations must execute the\n * statement outside `transaction(...)`.\n */\n executeDdl?: (ddl: string) => Promise<void>;\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 * — pass the operation-level backend so the no-tx path doesn't loop\n * back through the same toplevel method.\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 *\n * Used internally by backend implementations. Public callers go through\n * `commitSchemaVersion`, which handles the insert + activate atomically\n * with CAS guarantees.\n */\nexport type InsertSchemaParams = Readonly<{\n graphId: string;\n version: number;\n schemaHash: string;\n schemaDoc: SerializedSchema;\n isActive: boolean;\n}>;\n\n/**\n * The caller's claim about the currently-active schema version, used as\n * the optimistic compare-and-swap guard for `commitSchemaVersion`.\n *\n * - `{ kind: \"initial\" }` — caller is committing the first-ever version\n * for this graph and asserts no active version exists yet.\n * - `{ kind: \"active\", version: N }` — caller observed version N as\n * active and is committing version N+1 against that baseline. The\n * commit fails with `StaleVersionError` if some other writer has\n * advanced or rolled back the pointer in the meantime.\n *\n * Tagged-union form (rather than a magic `version: 0` sentinel) because\n * the two cases have materially different semantics: the initial path\n * skips the \"deactivate prior\" UPDATE, and the no-active-row state is\n * a *valid* expected state, not an out-of-band signal.\n */\nexport type CommitSchemaVersionExpected =\n | Readonly<{ kind: \"initial\" }>\n | Readonly<{ kind: \"active\"; version: number }>;\n\n/**\n * Parameters for `commitSchemaVersion`.\n */\nexport type CommitSchemaVersionParams = Readonly<{\n graphId: string;\n /** CAS guard — see `CommitSchemaVersionExpected`. */\n expected: CommitSchemaVersionExpected;\n /** The new version to insert and activate. */\n version: number;\n schemaHash: string;\n schemaDoc: SerializedSchema;\n}>;\n\n/**\n * Parameters for `setActiveVersion`.\n *\n * Flips the active pointer from `expected` to `version` for an existing\n * row. CAS prevents overwriting a concurrent rollback or commit.\n */\nexport type SetActiveVersionParams = Readonly<{\n graphId: string;\n /** CAS guard. Same semantics as `commitSchemaVersion.expected`. */\n expected: CommitSchemaVersionExpected;\n /** The version to mark active. Must already exist. */\n version: number;\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"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/backend/drizzle/operations/shared.ts","../src/query/dialect/fulltext-strategy.ts","../src/query/dialect/postgres.ts","../src/query/dialect/sqlite.ts","../src/query/dialect/index.ts","../src/indexes/compiler.ts","../src/indexes/ddl.ts","../src/indexes/drizzle.ts","../src/indexes/prof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AA,CAAM;AAAA,GACd;AACF;AASO,SAAS,kBACd,OAAA,EAC0B;AAC1B,EAAA,OAAO,OAAA,CACJ,MAAA;AAAA,IACC,CAAC,KAAA,KACC,KAAA,CAAM,MAAA,KAAW,MAAA,IAAU,MAAM,MAAA,KAAW;AAAA,IAE/C,GAAA,CAAI,CAAC,KAAA,KAAU,eAAA,CAAgB,KAAK,CAAC,CAAA;AAC1C;;;AChCO,SAAS,YACX,UAAA,EACmB;AACtB,EAAA,IAAI,UAAA,CAAW,WAAW,CAAA,EAAG;AAC3B,IAAA,OAAO,WAAW,CAAC,CAAA;AAAA,EACrB;AAEA,EAAA,OAAO;AAAA,IACL,MAAA,EAAQ,iBAAA;AAAA,IACR;AAAA,GACF;AACF;AAEO,SAAS,WACX,UAAA,EACmB;AACtB,EAAA,IAAI,UAAA,CAAW,WAAW,CAAA,EAAG;AAC3B,IAAA,OAAO,WAAW,CAAC,CAAA;AAAA,EACrB;AAEA,EAAA,OAAO;AAAA,IACL,MAAA,EAAQ,gBAAA;AAAA,IACR;AAAA,GACF;AACF;AAEO,SAAS,SACd,SAAA,EACsB;AACtB,EAAA,OAAO;AAAA,IACL,MAAA,EAAQ,iBAAA;AAAA,IACR;AAAA,GACF;AACF","file":"chunk-JTI5WT4P.cjs","sourcesContent":["import { type SQL, sql } from \"drizzle-orm\";\n\nimport type { PostgresTables } from \"../schema/postgres\";\nimport type { SqliteTables } from \"../schema/sqlite\";\n\nexport type Tables = SqliteTables | PostgresTables;\n\n/**\n * Converts undefined to SQL NULL for use in template literals.\n * Drizzle doesn't handle undefined in sql`` templates correctly.\n */\nexport function sqlNull(value: string | undefined): SQL | string {\n return value ?? sql.raw(\"NULL\");\n}\n\nexport function quotedColumn(column: { name: string }): SQL {\n return sql.raw(`\"${column.name.replaceAll('\"', '\"\"')}\"`);\n}\n\n/**\n * Returns a quoted SQL identifier for a bare table name string.\n * Use when the operation targets a table that isn't represented as a\n * Drizzle table object (e.g. the FTS5 virtual table).\n */\nexport function quotedTableName(tableName: string): SQL {\n return sql.raw(`\"${tableName.replaceAll('\"', '\"\"')}\"`);\n}\n\nexport function nodeColumnList(nodes: Tables[\"nodes\"]): SQL {\n return sql.raw(`\"${nodes.graphId.name}\", \"${nodes.kind.name}\", \"${nodes.id.name}\", \"${nodes.props.name}\", \"${nodes.version.name}\", \"${nodes.validFrom.name}\", \"${nodes.validTo.name}\", \"${nodes.createdAt.name}\", \"${nodes.updatedAt.name}\"`);\n}\n\nexport function edgeColumnList(edges: Tables[\"edges\"]): SQL {\n return sql.raw(`\"${edges.graphId.name}\", \"${edges.id.name}\", \"${edges.kind.name}\", \"${edges.fromKind.name}\", \"${edges.fromId.name}\", \"${edges.toKind.name}\", \"${edges.toId.name}\", \"${edges.props.name}\", \"${edges.validFrom.name}\", \"${edges.validTo.name}\", \"${edges.createdAt.name}\", \"${edges.updatedAt.name}\"`);\n}\n","/**\n * Fulltext Strategy — pluggable DDL + SQL generation for a dialect's\n * fulltext stack. A strategy owns every SQL statement that touches its\n * backing table: DDL, upsert (single + batch), delete (single + batch),\n * MATCH condition, rank expression, and snippet expression.\n *\n * A dialect picks one as its default; `createPostgresBackend` /\n * `createSqliteBackend` accept an override for alternate Postgres stacks\n * (pg_trgm, ParadeDB/pg_search, pgroonga) to swap the entire fulltext\n * pipeline without forking TypeGraph.\n */\nimport { type SQL, sql } from \"drizzle-orm\";\n\nimport { quotedTableName } from \"../../backend/drizzle/operations/shared\";\nimport {\n type DeleteFulltextBatchParams,\n type DeleteFulltextParams,\n type FulltextBatchRow,\n type FulltextCapabilities,\n type FulltextQueryMode,\n type UpsertFulltextBatchParams,\n type UpsertFulltextParams,\n} from \"../../backend/types\";\n\n/**\n * Every `FulltextQueryMode` both shipped strategies accept.\n */\nexport const ALL_FULLTEXT_MODES: readonly FulltextQueryMode[] = [\n \"websearch\",\n \"phrase\",\n \"plain\",\n \"raw\",\n] as const;\n\n/**\n * Derives the `FulltextCapabilities` backends advertise from the active\n * strategy, so the two never drift.\n */\nexport function buildFulltextCapabilities(\n strategy: FulltextStrategy,\n): FulltextCapabilities {\n return {\n supported: true,\n languages: strategy.languages,\n phraseQueries: strategy.supportedModes.includes(\"phrase\"),\n prefixQueries: strategy.supportsPrefix,\n highlighting: strategy.supportsSnippets,\n };\n}\n\n/**\n * A pluggable fulltext implementation. Each strategy is expected to be\n * self-contained: given a table name, a query string, and a parse mode,\n * it emits every SQL statement the compiler and backend need — DDL,\n * reads, and writes. No out-of-band conventions across layers.\n */\nexport interface FulltextStrategy {\n /** Human-readable identifier used in error messages and telemetry. */\n readonly name: string;\n\n /**\n * Parse modes this strategy can translate. Callers validate against\n * this list before emitting SQL; a mode outside the set means the\n * strategy rejects the query at compile time.\n */\n readonly supportedModes: readonly FulltextQueryMode[];\n\n /**\n * Whether the strategy can emit a per-row highlighted snippet. When\n * false, `snippetExpression` returns a literal `NULL` so callers can\n * leave the `snippet` column in place without a branch.\n */\n readonly supportsSnippets: boolean;\n\n /**\n * Whether the strategy supports prefix queries (`foo*`). Used to\n * populate `BackendCapabilities.fulltext.prefixQueries`. A strategy\n * may support prefix queries via dedicated syntax without advertising\n * \"raw\" mode (and vice-versa).\n */\n readonly supportsPrefix: boolean;\n\n /**\n * Whether a per-query `language` override is honored. Postgres' tsvector\n * accepts any installed regconfig at query time; SQLite FTS5's tokenizer\n * is fixed at table-create time, so the override is silently ignored.\n * Callers may surface a warning when the user passes `language` to a\n * strategy that doesn't honor it.\n */\n readonly supportsLanguageOverride: boolean;\n\n /**\n * Languages / tokenizer names understood by the strategy. Advisory — a\n * runtime backend like Postgres may accept other installed regconfigs.\n * Used to populate `BackendCapabilities.fulltext.languages`.\n */\n readonly languages: readonly string[];\n\n /**\n * Emits the WHERE-side MATCH expression.\n *\n * @example\n * tsvector: `\"typegraph_node_fulltext\".\"tsv\" @@ websearch_to_tsquery('english', 'cats')`\n * fts5: `\"typegraph_node_fulltext\" MATCH '\"cats\"'`\n */\n matchCondition(\n tableName: string,\n query: string,\n mode: FulltextQueryMode,\n language?: string,\n ): SQL;\n\n /**\n * Emits the relevance expression. Higher values = more relevant. The\n * compiler orders by this expression DESC, and both builder and\n * backend-direct paths use the same form so their top-k results agree.\n */\n rankExpression(\n tableName: string,\n query: string,\n mode: FulltextQueryMode,\n language?: string,\n ): SQL;\n\n /**\n * Emits a per-row highlighted snippet expression, or `NULL` when\n * `supportsSnippets` is false. Snippet markup is `<mark>…</mark>` in\n * both shipped strategies so consumers can apply one stylesheet.\n */\n snippetExpression(\n tableName: string,\n query: string,\n mode: FulltextQueryMode,\n language?: string,\n ): SQL;\n\n /**\n * DDL statements to create the backing table and any supporting\n * indexes. Idempotent (`CREATE ... IF NOT EXISTS`). Called once from\n * `bootstrapTables()` on a fresh database.\n */\n generateDdl(tableName: string): readonly string[];\n\n /**\n * Emits the statements that upsert a single fulltext row. Returns one\n * or more statements — some backends (SQLite FTS5) cannot emulate\n * upsert in a single statement and need DELETE + INSERT.\n */\n buildUpsert(\n tableName: string,\n params: UpsertFulltextParams,\n timestamp: string,\n ): readonly SQL[];\n\n /**\n * Emits the statements that upsert many fulltext rows at once. Input\n * rows are expected to be de-duplicated last-write-wins by the\n * strategy if the underlying SQL statement cannot tolerate duplicate\n * conflict keys. Returns `[]` when `params.rows` is empty.\n */\n buildBatchUpsert(\n tableName: string,\n params: UpsertFulltextBatchParams,\n timestamp: string,\n ): readonly SQL[];\n\n /**\n * Emits the statements that delete a single fulltext row. Normally a\n * single PK-scoped DELETE, but strategies that maintain auxiliary\n * indexes (delete-triggered external stores, ParadeDB-style secondary\n * structures) may need more.\n */\n buildDelete(tableName: string, params: DeleteFulltextParams): readonly SQL[];\n\n /**\n * Emits the statements that delete many fulltext rows at once. Returns\n * `[]` when `params.nodeIds` is empty.\n */\n buildBatchDelete(\n tableName: string,\n params: DeleteFulltextBatchParams,\n ): readonly SQL[];\n}\n\n// ============================================================\n// Internal helpers\n// ============================================================\n\nfunction quoteIdentifier(name: string): string {\n return `\"${name.replaceAll('\"', '\"\"')}\"`;\n}\n\nfunction tsvectorColumn(tableName: string): SQL {\n return sql`${quotedTableName(tableName)}.\"tsv\"`;\n}\n\n/**\n * Dedupes batch rows last-write-wins by nodeId. Returns a plain array\n * in insertion order of the last occurrence of each id. Shared by both\n * shipped strategies.\n */\nfunction dedupeFulltextBatchRows(\n rows: readonly FulltextBatchRow[],\n): FulltextBatchRow[] {\n const seen = new Map<string, FulltextBatchRow>();\n for (const row of rows) seen.set(row.nodeId, row);\n return [...seen.values()];\n}\n\nfunction buildPkScopedDelete(\n tableName: string,\n params: DeleteFulltextParams,\n): SQL {\n const table = quotedTableName(tableName);\n return sql`\n DELETE FROM ${table}\n WHERE \"graph_id\" = ${params.graphId}\n AND \"node_kind\" = ${params.nodeKind}\n AND \"node_id\" = ${params.nodeId}\n `;\n}\n\nfunction buildPkScopedBatchDelete(\n tableName: string,\n params: DeleteFulltextBatchParams,\n): SQL | undefined {\n if (params.nodeIds.length === 0) return undefined;\n const unique = [...new Set(params.nodeIds)];\n const table = quotedTableName(tableName);\n return sql`\n DELETE FROM ${table}\n WHERE \"graph_id\" = ${params.graphId}\n AND \"node_kind\" = ${params.nodeKind}\n AND \"node_id\" IN (${sql.join(\n unique.map((id) => sql`${id}`),\n sql`, `,\n )})\n `;\n}\n\n// ============================================================\n// tsvector strategy (PostgreSQL built-in)\n// ============================================================\n\nfunction postgresTsquery(\n mode: FulltextQueryMode,\n query: string,\n language: string | undefined,\n): SQL {\n // The `language` column is already `regconfig`, so the non-override\n // path references the column directly. The per-query override path\n // still arrives as a bound text parameter and needs the cast.\n const langExpr: SQL =\n language === undefined ? sql`\"language\"` : sql`${language}::regconfig`;\n switch (mode) {\n case \"websearch\": {\n return sql`websearch_to_tsquery(${langExpr}, ${query})`;\n }\n case \"phrase\": {\n return sql`phraseto_tsquery(${langExpr}, ${query})`;\n }\n case \"plain\": {\n return sql`plainto_tsquery(${langExpr}, ${query})`;\n }\n case \"raw\": {\n return sql`to_tsquery(${langExpr}, ${query})`;\n }\n default: {\n const _exhaustive: never = mode;\n throw new Error(`Unsupported fulltext mode: ${String(_exhaustive)}`);\n }\n }\n}\n\nexport const tsvectorStrategy: FulltextStrategy = {\n name: \"tsvector\",\n supportedModes: ALL_FULLTEXT_MODES,\n supportsSnippets: true,\n // `raw` mode exposes `foo:*` prefix-match syntax to callers.\n supportsPrefix: true,\n supportsLanguageOverride: true,\n // Canonical Postgres stemmers; every stock install ships these plus a\n // few others. Runtime `to_tsvector` accepts any installed regconfig\n // name — this list is advisory for capability discovery.\n languages: [\n \"simple\",\n \"english\",\n \"french\",\n \"german\",\n \"italian\",\n \"portuguese\",\n \"russian\",\n \"spanish\",\n \"swedish\",\n ] as const,\n\n matchCondition(tableName, query, mode, language) {\n const q = postgresTsquery(mode, query, language);\n return sql`${tsvectorColumn(tableName)} @@ ${q}`;\n },\n\n rankExpression(tableName, query, mode, language) {\n const q = postgresTsquery(mode, query, language);\n return sql`ts_rank_cd(${tsvectorColumn(tableName)}, ${q})`;\n },\n\n snippetExpression(_tableName, query, mode, language) {\n const langExpr: SQL =\n language === undefined ? sql`\"language\"` : sql`${language}::regconfig`;\n const q = postgresTsquery(mode, query, language);\n return sql`ts_headline(${langExpr}, \"content\", ${q}, 'StartSel=<mark>,StopSel=</mark>,MaxFragments=1,MinWords=5,MaxWords=30,ShortWord=3')`;\n },\n\n generateDdl(tableName) {\n const name = quoteIdentifier(tableName);\n const gin = quoteIdentifier(`${tableName}_tsv_idx`);\n const kind = quoteIdentifier(`${tableName}_kind_idx`);\n // `language` is `regconfig` so `to_tsvector(\"language\", \"content\")`\n // is an immutable expression — Postgres can then compute `tsv` as a\n // GENERATED STORED column and own the `content → tsv` invariant.\n // (The text→regconfig cast happens once at INSERT time against the\n // bound parameter, which is fine because it's not inside the\n // generated expression.)\n return [\n `CREATE TABLE IF NOT EXISTS ${name} (\n \"graph_id\" TEXT NOT NULL,\n \"node_kind\" TEXT NOT NULL,\n \"node_id\" TEXT NOT NULL,\n \"content\" TEXT NOT NULL,\n \"language\" regconfig NOT NULL,\n \"tsv\" tsvector NOT NULL\n GENERATED ALWAYS AS (to_tsvector(\"language\", \"content\")) STORED,\n \"updated_at\" TIMESTAMPTZ NOT NULL,\n PRIMARY KEY (\"graph_id\", \"node_kind\", \"node_id\")\n);`,\n `CREATE INDEX IF NOT EXISTS ${gin} ON ${name} USING GIN (\"tsv\");`,\n `CREATE INDEX IF NOT EXISTS ${kind} ON ${name} (\"graph_id\", \"node_kind\");`,\n ];\n },\n\n buildUpsert(tableName, params, timestamp) {\n const table = quotedTableName(tableName);\n // `tsv` is a GENERATED STORED column — Postgres computes it from\n // `content` + `language`, so it must not appear in the column list\n // or the ON CONFLICT update set.\n return [\n sql`\n INSERT INTO ${table} (\"graph_id\", \"node_kind\", \"node_id\", \"content\", \"language\", \"updated_at\")\n VALUES (\n ${params.graphId}, ${params.nodeKind}, ${params.nodeId},\n ${params.content}, ${params.language}::regconfig,\n ${timestamp}\n )\n ON CONFLICT (\"graph_id\", \"node_kind\", \"node_id\")\n DO UPDATE SET\n \"content\" = EXCLUDED.\"content\",\n \"language\" = EXCLUDED.\"language\",\n \"updated_at\" = EXCLUDED.\"updated_at\"\n `,\n ];\n },\n\n buildBatchUpsert(tableName, params, timestamp) {\n const rows = dedupeFulltextBatchRows(params.rows);\n if (rows.length === 0) return [];\n\n const table = quotedTableName(tableName);\n const valueTuples = rows.map(\n (row) => sql`\n (\n ${params.graphId}, ${params.nodeKind}, ${row.nodeId},\n ${row.content}, ${row.language}::regconfig,\n ${timestamp}\n )\n `,\n );\n\n return [\n sql`\n INSERT INTO ${table} (\"graph_id\", \"node_kind\", \"node_id\", \"content\", \"language\", \"updated_at\")\n VALUES ${sql.join(valueTuples, sql`, `)}\n ON CONFLICT (\"graph_id\", \"node_kind\", \"node_id\")\n DO UPDATE SET\n \"content\" = EXCLUDED.\"content\",\n \"language\" = EXCLUDED.\"language\",\n \"updated_at\" = EXCLUDED.\"updated_at\"\n `,\n ];\n },\n\n buildDelete(tableName, params) {\n return [buildPkScopedDelete(tableName, params)];\n },\n\n buildBatchDelete(tableName, params) {\n const stmt = buildPkScopedBatchDelete(tableName, params);\n return stmt === undefined ? [] : [stmt];\n },\n};\n\n// ============================================================\n// FTS5 strategy (SQLite)\n// ============================================================\n\nfunction translateToFts5Query(query: string, mode: FulltextQueryMode): string {\n switch (mode) {\n case \"phrase\": {\n return `\"${query.replaceAll('\"', '\"\"')}\"`;\n }\n case \"plain\": {\n return query\n .trim()\n .split(/\\s+/u)\n .filter((token) => token.length > 0)\n .map((token) => `\"${token.replaceAll('\"', '\"\"')}\"`)\n .join(\" \");\n }\n case \"websearch\": {\n return translateWebsearchToFts5(query);\n }\n case \"raw\": {\n return query;\n }\n default: {\n const _exhaustive: never = mode;\n throw new Error(`Unsupported fulltext mode: ${String(_exhaustive)}`);\n }\n }\n}\n\nfunction translateWebsearchToFts5(query: string): string {\n const tokens: string[] = [];\n let index = 0;\n\n function skipWhitespace(): void {\n while (index < query.length && /\\s/u.test(query[index] ?? \"\")) {\n index += 1;\n }\n }\n\n function readPhrase(): string {\n index += 1;\n let content = \"\";\n while (index < query.length && query[index] !== '\"') {\n content += query[index] ?? \"\";\n index += 1;\n }\n if (query[index] === '\"') index += 1;\n return `\"${content.replaceAll('\"', '\"\"')}\"`;\n }\n\n function readBareTerm(): string {\n let term = \"\";\n while (index < query.length && !/\\s/u.test(query[index] ?? \"\")) {\n term += query[index] ?? \"\";\n index += 1;\n }\n return term;\n }\n\n while (index < query.length) {\n skipWhitespace();\n if (index >= query.length) break;\n const ch = query[index];\n if (ch === '\"') {\n tokens.push(readPhrase());\n continue;\n }\n if (ch === \"-\") {\n index += 1;\n const term =\n query[index] === '\"' ?\n readPhrase()\n : `\"${readBareTerm().replaceAll('\"', '\"\"')}\"`;\n tokens.push(`NOT ${term}`);\n continue;\n }\n if (ch === \"+\") {\n index += 1;\n continue;\n }\n const bare = readBareTerm();\n if (bare.length === 0) continue;\n if (bare.toUpperCase() === \"OR\") {\n tokens.push(\"OR\");\n continue;\n }\n tokens.push(`\"${bare.replaceAll('\"', '\"\"')}\"`);\n }\n\n if (tokens.length > 0 && tokens[0]?.startsWith(\"NOT \")) {\n tokens.shift();\n }\n\n return tokens.join(\" \");\n}\n\nexport const fts5Strategy: FulltextStrategy = {\n name: \"fts5\",\n supportedModes: ALL_FULLTEXT_MODES,\n supportsSnippets: true,\n // FTS5 supports `foo*` prefix matching natively.\n supportsPrefix: true,\n // FTS5 tokenizer is fixed at table-create time; per-row / per-query\n // language metadata is stored but not consulted.\n supportsLanguageOverride: false,\n // The built-in tokenizer is `porter unicode61 remove_diacritics 2`; the\n // `language` field on searchable() is recorded for future use but not\n // applied at query time.\n languages: [\"porter\", \"unicode61\", \"trigram\"] as const,\n\n matchCondition(tableName, query, mode, _language) {\n const matchExpression = translateToFts5Query(query, mode);\n return sql`${quotedTableName(tableName)} MATCH ${matchExpression}`;\n },\n\n rankExpression(tableName, _query, _mode, _language) {\n // FTS5 bm25() returns a negative score where lower = more relevant.\n // Negate so callers see higher = better (uniform with tsvector).\n return sql`-bm25(${quotedTableName(tableName)})`;\n },\n\n snippetExpression(tableName, _query, _mode, _language) {\n return sql`snippet(${quotedTableName(tableName)}, -1, '<mark>', '</mark>', '…', 20)`;\n },\n\n generateDdl(tableName) {\n const name = quoteIdentifier(tableName);\n return [\n `CREATE VIRTUAL TABLE IF NOT EXISTS ${name} USING fts5(\n graph_id UNINDEXED,\n node_kind UNINDEXED,\n node_id UNINDEXED,\n language UNINDEXED,\n updated_at UNINDEXED,\n content,\n tokenize='porter unicode61 remove_diacritics 2'\n);`,\n ];\n },\n\n buildUpsert(tableName, params, timestamp) {\n const table = quotedTableName(tableName);\n // FTS5 virtual tables don't support ON CONFLICT — emulate with\n // DELETE + INSERT, atomic under the caller's outer transaction.\n return [\n sql`\n DELETE FROM ${table}\n WHERE \"graph_id\" = ${params.graphId}\n AND \"node_kind\" = ${params.nodeKind}\n AND \"node_id\" = ${params.nodeId}\n `,\n sql`\n INSERT INTO ${table} (graph_id, node_kind, node_id, content, language, updated_at)\n VALUES (${params.graphId}, ${params.nodeKind}, ${params.nodeId}, ${params.content}, ${params.language}, ${timestamp})\n `,\n ];\n },\n\n buildBatchUpsert(tableName, params, timestamp) {\n const rows = dedupeFulltextBatchRows(params.rows);\n if (rows.length === 0) return [];\n\n const table = quotedTableName(tableName);\n const nodeIds = rows.map((row) => row.nodeId);\n\n const deleteStmt = sql`\n DELETE FROM ${table}\n WHERE \"graph_id\" = ${params.graphId}\n AND \"node_kind\" = ${params.nodeKind}\n AND \"node_id\" IN (${sql.join(\n nodeIds.map((id) => sql`${id}`),\n sql`, `,\n )})\n `;\n\n const valueTuples = rows.map(\n (row) => sql`\n (\n ${params.graphId}, ${params.nodeKind}, ${row.nodeId},\n ${row.content}, ${row.language}, ${timestamp}\n )\n `,\n );\n\n const insertStmt = sql`\n INSERT INTO ${table} (graph_id, node_kind, node_id, content, language, updated_at)\n VALUES ${sql.join(valueTuples, sql`, `)}\n `;\n\n return [deleteStmt, insertStmt];\n },\n\n buildDelete(tableName, params) {\n return [buildPkScopedDelete(tableName, params)];\n },\n\n buildBatchDelete(tableName, params) {\n const stmt = buildPkScopedBatchDelete(tableName, params);\n return stmt === undefined ? [] : [stmt];\n },\n};\n","/**\n * PostgreSQL Dialect Adapter\n *\n * Implements dialect-specific SQL generation for PostgreSQL databases.\n * Uses PostgreSQL's native JSONB operators for JSON operations.\n */\nimport { type SQL, sql } from \"drizzle-orm\";\n\nimport { type JsonPointer, parseJsonPointer } from \"../json-pointer\";\nimport { tsvectorStrategy } from \"./fulltext-strategy\";\nimport { type DialectAdapter } from \"./types\";\n\n/**\n * Escapes a string for use in a PostgreSQL string literal.\n * Uses single quotes and escapes embedded single quotes.\n */\nfunction escapePostgresLiteral(value: string): string {\n // PostgreSQL uses '' to escape single quotes inside string literals\n return `'${value.replaceAll(\"'\", \"''\")}'`;\n}\n\n/**\n * Converts a JSON pointer to PostgreSQL's text array path.\n *\n * Uses raw SQL (non-parameterized) to ensure the same expression text\n * is generated when the same field is used in multiple clauses (SELECT, GROUP BY).\n * This is safe because JSON pointers come from schema definitions, not user input.\n *\n * @example\n * \"/name\" → ARRAY['name']\n * \"/items/0\" → ARRAY['items', '0']\n * \"/a/b/c\" → ARRAY['a', 'b', 'c']\n */\nfunction toPostgresPath(pointer: JsonPointer): SQL {\n if (!pointer || pointer === \"\" || pointer === \"/\") {\n return sql.raw(\"ARRAY[]::text[]\");\n }\n\n const segments = parseJsonPointer(pointer);\n if (segments.length === 0) {\n return sql.raw(\"ARRAY[]::text[]\");\n }\n\n // Use raw SQL for path segments to ensure identical SQL text\n // when the same field is used in multiple clauses (e.g., SELECT and GROUP BY)\n const escapedSegments = segments\n .map((segment) => escapePostgresLiteral(segment))\n .join(\", \");\n return sql.raw(`ARRAY[${escapedSegments}]`);\n}\n\n/**\n * PostgreSQL dialect adapter implementation.\n */\nexport const postgresDialect: DialectAdapter = {\n name: \"postgres\",\n capabilities: {\n standardQueryStrategy: \"cte_project\",\n recursiveQueryStrategy: \"recursive_cte\",\n setOperationStrategy: \"standard_parenthesized\",\n materializeIntermediateTraversalCtes: false,\n emitNotMaterializedHint: true,\n forceRecursiveWorktableOuterJoinOrder: false,\n vectorPredicateStrategy: \"native\",\n vectorMetrics: [\"cosine\", \"l2\", \"inner_product\"] as const,\n supportsFulltext: true,\n },\n\n // ============================================================\n // JSON Path Operations\n // ============================================================\n\n compilePath(pointer) {\n return toPostgresPath(pointer);\n },\n\n jsonExtract(column, pointer) {\n // #> returns JSONB value at path\n const path = toPostgresPath(pointer);\n return sql`${column} #> ${path}`;\n },\n\n jsonExtractText(column, pointer) {\n // #>> returns text value at path\n const path = toPostgresPath(pointer);\n return sql`${column} #>> ${path}`;\n },\n\n jsonExtractNumber(column, pointer) {\n // Extract as text then cast to numeric\n const path = toPostgresPath(pointer);\n return sql`(${column} #>> ${path})::numeric`;\n },\n\n jsonExtractBoolean(column, pointer) {\n // Extract as text then cast to boolean\n const path = toPostgresPath(pointer);\n return sql`(${column} #>> ${path})::boolean`;\n },\n\n jsonExtractDate(column, pointer) {\n // Extract as text then cast to timestamptz\n const path = toPostgresPath(pointer);\n return sql`(${column} #>> ${path})::timestamptz`;\n },\n\n // ============================================================\n // JSON Array Operations\n // ============================================================\n\n jsonArrayLength(column) {\n return sql`jsonb_array_length(${column})`;\n },\n\n jsonArrayContains(column, value) {\n // @> checks if left contains right\n const jsonValue = JSON.stringify([value]);\n return sql`${column} @> ${jsonValue}::jsonb`;\n },\n\n jsonArrayContainsAll(column, values) {\n if (values.length === 0) {\n return sql.raw(\"1=1\");\n }\n\n // @> with full array checks all values\n const jsonValue = JSON.stringify(values);\n return sql`${column} @> ${jsonValue}::jsonb`;\n },\n\n jsonArrayContainsAny(column, values) {\n if (values.length === 0) {\n return sql.raw(\"1=0\");\n }\n\n // Check each value with @> and OR them together\n // PostgreSQL doesn't have a native \"overlaps\" for jsonb arrays\n const conditions = values.map((value) => {\n const jsonValue = JSON.stringify([value]);\n return sql`${column} @> ${jsonValue}::jsonb`;\n });\n return sql`(${sql.join(conditions, sql` OR `)})`;\n },\n\n // ============================================================\n // JSON Object Operations\n // ============================================================\n\n jsonHasPath(column, pointer) {\n const path = toPostgresPath(pointer);\n return sql`${column} #> ${path} IS NOT NULL`;\n },\n\n jsonPathIsNull(column, pointer) {\n const path = toPostgresPath(pointer);\n // Check both SQL NULL and JSON null literal\n return sql`(${column} #> ${path} IS NULL OR ${column} #>> ${path} = 'null')`;\n },\n\n jsonPathIsNotNull(column, pointer) {\n const path = toPostgresPath(pointer);\n return sql`(${column} #> ${path} IS NOT NULL AND ${column} #>> ${path} != 'null')`;\n },\n\n // ============================================================\n // String Operations\n // ============================================================\n\n ilike(column, pattern) {\n // PostgreSQL has native ILIKE operator\n return sql`${column} ILIKE ${pattern}`;\n },\n\n // ============================================================\n // Recursive CTE Path Operations\n // ============================================================\n\n initializePath(nodeId) {\n // PostgreSQL uses text arrays: ARRAY[id]\n return sql`ARRAY[${nodeId}]`;\n },\n\n extendPath(currentPath, nodeId) {\n // Array concatenation: path || id\n return sql`${currentPath} || ${nodeId}`;\n },\n\n cycleCheck(nodeId, path) {\n // Check that id is NOT in array path\n // Returns TRUE if no cycle (id not in array)\n return sql`${nodeId} != ALL(${path})`;\n },\n\n // ============================================================\n // Type Utilities\n // ============================================================\n\n currentTimestamp() {\n return sql`NOW()`;\n },\n\n // ============================================================\n // Value Binding & Literals\n // ============================================================\n\n bindValue(value) {\n // PostgreSQL supports native booleans, no conversion needed\n return value;\n },\n\n booleanLiteral(value) {\n return sql.raw(this.booleanLiteralString(value));\n },\n\n booleanLiteralString(value) {\n return value ? \"TRUE\" : \"FALSE\";\n },\n\n quoteIdentifier(name) {\n // PostgreSQL uses double quotes, escape embedded quotes by doubling\n return `\"${name.replaceAll('\"', '\"\"')}\"`;\n },\n\n // ============================================================\n // Vector Operations\n // ============================================================\n\n supportsVectors: true,\n\n vectorDistance(column, embedding, metric) {\n const formatted = this.formatEmbedding(embedding);\n // Column is native VECTOR type, no cast needed\n switch (metric) {\n case \"cosine\": {\n // Cosine distance: 1 - cosine_similarity\n // Lower is more similar (0 = identical)\n return sql`(${column} <=> ${formatted})`;\n }\n case \"l2\": {\n // Euclidean (L2) distance\n // Lower is more similar (0 = identical)\n return sql`(${column} <-> ${formatted})`;\n }\n case \"inner_product\": {\n // Inner product distance (negative inner product)\n // Note: pgvector uses <#> which returns NEGATIVE inner product\n // More negative = more similar for normalized vectors\n return sql`(${column} <#> ${formatted})`;\n }\n default: {\n const _exhaustive: never = metric;\n throw new Error(\"Unsupported vector metric: \" + String(_exhaustive));\n }\n }\n },\n\n formatEmbedding(embedding) {\n // Validate all values are finite numbers to prevent injection\n for (const [index, value] of embedding.entries()) {\n if (typeof value !== \"number\" || !Number.isFinite(value)) {\n throw new TypeError(\n `embedding[${index}] must be a finite number, got: ${value}`,\n );\n }\n }\n // Format as PostgreSQL vector literal: '[1.0,2.0,3.0]'::vector\n // Query embedding still needs cast since it's a literal string\n const asString = `[${embedding.join(\",\")}]`;\n return sql`${asString}::vector`;\n },\n\n // ============================================================\n // Fulltext Operations\n // ============================================================\n\n fulltext: tsvectorStrategy,\n};\n","/**\n * SQLite Dialect Adapter\n *\n * Implements dialect-specific SQL generation for SQLite databases.\n * Uses SQLite's JSON1 extension for JSON operations.\n */\nimport { sql } from \"drizzle-orm\";\n\nimport { type JsonPointer, parseJsonPointer } from \"../json-pointer\";\nimport { fts5Strategy } from \"./fulltext-strategy\";\nimport { type DialectAdapter } from \"./types\";\n\n/**\n * Escapes a string for use in a SQLite string literal.\n * SQLite uses single quotes and escapes embedded single quotes by doubling them.\n */\nfunction escapeSqliteLiteral(value: string): string {\n return `'${value.replaceAll(\"'\", \"''\")}'`;\n}\n\n/**\n * Converts a JSON pointer to SQLite's JSON path syntax.\n *\n * @example\n * \"/name\" → \"$.\\\"name\\\"\"\n * \"/items/0\" → \"$.\\\"items\\\"[0]\"\n * \"/a/b/c\" → \"$.\\\"a\\\".\\\"b\\\".\\\"c\\\"\"\n */\nfunction toSqlitePath(pointer: JsonPointer): string {\n if (!pointer || pointer === \"\" || pointer === \"/\") {\n return \"$\";\n }\n\n const segments = parseJsonPointer(pointer);\n const parts: string[] = [\"$\"];\n\n for (const segment of segments) {\n if (isArrayIndex(segment)) {\n parts.push(`[${segment}]`);\n } else {\n // Quote the key to handle special characters\n parts.push(`.${JSON.stringify(segment)}`);\n }\n }\n\n return parts.join(\"\");\n}\n\n/**\n * Checks if a JSON pointer segment is an array index.\n */\nfunction isArrayIndex(segment: string): boolean {\n return /^\\d+$/.test(segment);\n}\n\n/**\n * SQLite dialect adapter implementation.\n */\nexport const sqliteDialect: DialectAdapter = {\n name: \"sqlite\",\n capabilities: {\n standardQueryStrategy: \"cte_project\",\n recursiveQueryStrategy: \"recursive_cte\",\n setOperationStrategy: \"sqlite_compound\",\n materializeIntermediateTraversalCtes: true,\n emitNotMaterializedHint: false,\n forceRecursiveWorktableOuterJoinOrder: true,\n vectorPredicateStrategy: \"native\",\n vectorMetrics: [\"cosine\", \"l2\"] as const,\n supportsFulltext: true,\n },\n\n // ============================================================\n // JSON Path Operations\n // ============================================================\n\n compilePath(pointer) {\n // Use raw SQL to ensure the path is a literal, which allows expression\n // indexes on json_extract(...) to be used by the query planner.\n return sql.raw(escapeSqliteLiteral(toSqlitePath(pointer)));\n },\n\n jsonExtract(column, pointer) {\n const path = toSqlitePath(pointer);\n return sql`json_extract(${column}, ${sql.raw(escapeSqliteLiteral(path))})`;\n },\n\n jsonExtractText(column, pointer) {\n // SQLite's json_extract returns the native JSON type, which works\n // for text comparisons. For explicit text, we use the same function.\n const path = toSqlitePath(pointer);\n return sql`json_extract(${column}, ${sql.raw(escapeSqliteLiteral(path))})`;\n },\n\n jsonExtractNumber(column, pointer) {\n // SQLite json_extract returns numbers natively when the value is numeric\n const path = toSqlitePath(pointer);\n return sql`json_extract(${column}, ${sql.raw(escapeSqliteLiteral(path))})`;\n },\n\n jsonExtractBoolean(column, pointer) {\n // SQLite json_extract returns 0/1 for boolean values\n const path = toSqlitePath(pointer);\n return sql`json_extract(${column}, ${sql.raw(escapeSqliteLiteral(path))})`;\n },\n\n jsonExtractDate(column, pointer) {\n // SQLite stores dates as ISO strings, json_extract returns them as text\n const path = toSqlitePath(pointer);\n return sql`json_extract(${column}, ${sql.raw(escapeSqliteLiteral(path))})`;\n },\n\n // ============================================================\n // JSON Array Operations\n // ============================================================\n\n jsonArrayLength(column) {\n return sql`json_array_length(${column})`;\n },\n\n jsonArrayContains(column, value) {\n return sql`EXISTS (SELECT 1 FROM json_each(${column}) WHERE json_each.value = ${value})`;\n },\n\n jsonArrayContainsAll(column, values) {\n if (values.length === 0) {\n return sql.raw(\"1=1\");\n }\n\n const conditions = values.map(\n (value) =>\n sql`EXISTS (SELECT 1 FROM json_each(${column}) WHERE json_each.value = ${value})`,\n );\n return sql`(${sql.join(conditions, sql` AND `)})`;\n },\n\n jsonArrayContainsAny(column, values) {\n if (values.length === 0) {\n return sql.raw(\"1=0\");\n }\n\n const conditions = values.map(\n (value) =>\n sql`EXISTS (SELECT 1 FROM json_each(${column}) WHERE json_each.value = ${value})`,\n );\n return sql`(${sql.join(conditions, sql` OR `)})`;\n },\n\n // ============================================================\n // JSON Object Operations\n // ============================================================\n\n jsonHasPath(column, pointer) {\n const path = toSqlitePath(pointer);\n return sql`json_type(${column}, ${sql.raw(escapeSqliteLiteral(path))}) IS NOT NULL`;\n },\n\n jsonPathIsNull(column, pointer) {\n const path = toSqlitePath(pointer);\n const pathSql = sql.raw(escapeSqliteLiteral(path));\n return sql`(json_extract(${column}, ${pathSql}) IS NULL OR json_type(${column}, ${pathSql}) = 'null')`;\n },\n\n jsonPathIsNotNull(column, pointer) {\n const path = toSqlitePath(pointer);\n const pathSql = sql.raw(escapeSqliteLiteral(path));\n return sql`(json_extract(${column}, ${pathSql}) IS NOT NULL AND json_type(${column}, ${pathSql}) != 'null')`;\n },\n\n // ============================================================\n // String Operations\n // ============================================================\n\n ilike(column, pattern) {\n // SQLite LIKE is case-insensitive for ASCII by default, but we use\n // LOWER() for consistency with non-ASCII characters\n return sql`LOWER(${column}) LIKE LOWER(${pattern})`;\n },\n\n // ============================================================\n // Recursive CTE Path Operations\n // ============================================================\n\n initializePath(nodeId) {\n // SQLite uses string-based paths with delimiters: '|id|'\n return sql`'|' || ${nodeId} || '|'`;\n },\n\n extendPath(currentPath, nodeId) {\n // Append: path || id || '|'\n return sql`${currentPath} || ${nodeId} || '|'`;\n },\n\n cycleCheck(nodeId, path) {\n // Check that id is NOT in path using INSTR\n // Returns TRUE if no cycle (id not found in path)\n return sql`INSTR(${path}, '|' || ${nodeId} || '|') = 0`;\n },\n\n // ============================================================\n // Type Utilities\n // ============================================================\n\n currentTimestamp() {\n // Keep ISO-8601 format aligned with stored timestamps from Date.toISOString()\n // so string-based temporal comparisons remain correct in SQLite TEXT columns.\n return sql`strftime('%Y-%m-%dT%H:%M:%fZ', 'now')`;\n },\n\n // ============================================================\n // Value Binding & Literals\n // ============================================================\n\n bindValue(value) {\n // SQLite doesn't support native booleans, convert to 0/1\n if (typeof value === \"boolean\") {\n return value ? 1 : 0;\n }\n return value;\n },\n\n booleanLiteral(value) {\n return sql.raw(this.booleanLiteralString(value));\n },\n\n booleanLiteralString(value) {\n return value ? \"1\" : \"0\";\n },\n\n quoteIdentifier(name) {\n // SQLite uses double quotes (or backticks), escape embedded quotes by doubling\n return `\"${name.replaceAll('\"', '\"\"')}\"`;\n },\n\n // ============================================================\n // Vector Operations\n // ============================================================\n\n supportsVectors: true,\n\n vectorDistance(column, embedding, metric) {\n // sqlite-vec functions expect vec_f32 format for the query embedding\n const formatted = this.formatEmbedding(embedding);\n switch (metric) {\n case \"cosine\": {\n // Cosine distance: 1 - cosine_similarity\n // Lower is more similar (0 = identical)\n return sql`vec_distance_cosine(${column}, ${formatted})`;\n }\n case \"l2\": {\n // Euclidean (L2) distance\n // Lower is more similar (0 = identical)\n return sql`vec_distance_l2(${column}, ${formatted})`;\n }\n case \"inner_product\": {\n // sqlite-vec does not support inner product distance\n // See: https://alexgarcia.xyz/sqlite-vec/api-reference.html\n throw new Error(\n \"Inner product distance is not supported by sqlite-vec. Use 'cosine' or 'l2' metrics instead.\",\n );\n }\n default: {\n const _exhaustive: never = metric;\n throw new Error(\"Unsupported vector metric: \" + String(_exhaustive));\n }\n }\n },\n\n formatEmbedding(embedding) {\n // Validate all values are finite numbers\n for (const [index, value] of embedding.entries()) {\n if (typeof value !== \"number\" || !Number.isFinite(value)) {\n throw new TypeError(\n `embedding[${index}] must be a finite number, got: ${value}`,\n );\n }\n }\n // sqlite-vec uses vec_f32() to convert JSON array to binary format\n const asJson = JSON.stringify(embedding);\n return sql`vec_f32(${asJson})`;\n },\n\n // ============================================================\n // Fulltext Operations\n // ============================================================\n\n fulltext: fts5Strategy,\n};\n","/**\n * SQL Dialect Module\n *\n * Provides dialect adapters for different SQL databases.\n * Use `getDialect()` to get the appropriate adapter for a dialect name.\n */\n\nexport type { FulltextStrategy } from \"./fulltext-strategy\";\nexport {\n ALL_FULLTEXT_MODES,\n buildFulltextCapabilities,\n fts5Strategy,\n tsvectorStrategy,\n} from \"./fulltext-strategy\";\nexport { postgresDialect } from \"./postgres\";\nexport { sqliteDialect } from \"./sqlite\";\nexport type {\n DialectAdapter,\n DialectCapabilities,\n DialectRecursiveQueryStrategy,\n DialectSetOperationStrategy,\n DialectStandardQueryStrategy,\n DialectVectorPredicateStrategy,\n SqlDialect,\n} from \"./types\";\n\nimport { postgresDialect } from \"./postgres\";\nimport { sqliteDialect } from \"./sqlite\";\nimport { type DialectAdapter, type SqlDialect } from \"./types\";\n\n/**\n * Map of dialect names to their adapters.\n */\nconst DIALECT_ADAPTERS: Record<SqlDialect, DialectAdapter> = {\n sqlite: sqliteDialect,\n postgres: postgresDialect,\n};\n\n/**\n * Gets the dialect adapter for a given dialect name.\n *\n * @param dialect - The dialect name (\"sqlite\" or \"postgres\")\n * @returns The dialect adapter\n *\n * @example\n * ```typescript\n * const adapter = getDialect(\"postgres\");\n * const sql = adapter.jsonExtract(column, \"/name\");\n * ```\n */\nexport function getDialect(dialect: SqlDialect): DialectAdapter {\n return DIALECT_ADAPTERS[dialect];\n}\n\n/**\n * Default dialect used when none is specified.\n */\nexport const DEFAULT_DIALECT: SqlDialect = \"sqlite\";\n","import { type SQL, sql } from \"drizzle-orm\";\n\nimport { type ValueType } from \"../query/ast\";\nimport { getDialect, type SqlDialect } from \"../query/dialect\";\nimport { type JsonPointer, jsonPointer } from \"../query/json-pointer\";\nimport {\n type EdgeIndexDeclaration,\n type IndexWhereExpression,\n type IndexWhereLiteral,\n type IndexWhereOp,\n type IndexWhereOperand,\n type NodeIndexDeclaration,\n type SystemColumnName,\n} from \"./types\";\n\n// ============================================================\n// Public Types\n// ============================================================\n\nexport type IndexCompilationContext = Readonly<{\n dialect: SqlDialect;\n propsColumn: SQL;\n systemColumn: (column: SystemColumnName) => SQL;\n}>;\n\ntype CompiledIndexKeys = Readonly<{\n /** SQL expressions in index key order */\n keys: readonly SQL[];\n}>;\n\n// ============================================================\n// Index Key Compilation\n// ============================================================\n\nexport function compileNodeIndexKeys(\n index: NodeIndexDeclaration,\n dialect: SqlDialect,\n propsColumn: SQL,\n systemColumn: (column: SystemColumnName) => SQL,\n): CompiledIndexKeys {\n const adapter = getDialect(dialect);\n const keys: SQL[] = [];\n\n for (const column of getNodeScopeColumns(index.scope)) {\n keys.push(systemColumn(column));\n }\n\n const allPointers = [...index.fields, ...index.coveringFields];\n const allValueTypes = [\n ...index.fieldValueTypes,\n ...index.coveringFieldValueTypes,\n ];\n\n for (const [pointerIndex, pointer] of allPointers.entries()) {\n const valueType = allValueTypes[pointerIndex];\n const extracted = compileIndexKeyValue(\n adapter,\n propsColumn,\n pointer,\n valueType,\n );\n keys.push(sql`(${extracted})`);\n }\n\n return { keys };\n}\n\nexport function compileEdgeIndexKeys(\n index: EdgeIndexDeclaration,\n dialect: SqlDialect,\n propsColumn: SQL,\n systemColumn: (column: SystemColumnName) => SQL,\n): CompiledIndexKeys {\n const adapter = getDialect(dialect);\n const keys: SQL[] = [];\n\n for (const column of getEdgeScopeColumns(index.scope, index.direction)) {\n keys.push(systemColumn(column));\n }\n\n const allPointers = [...index.fields, ...index.coveringFields];\n const allValueTypes = [\n ...index.fieldValueTypes,\n ...index.coveringFieldValueTypes,\n ];\n\n for (const [pointerIndex, pointer] of allPointers.entries()) {\n const valueType = allValueTypes[pointerIndex];\n const extracted = compileIndexKeyValue(\n adapter,\n propsColumn,\n pointer,\n valueType,\n );\n keys.push(sql`(${extracted})`);\n }\n\n return { keys };\n}\n\nfunction compileIndexKeyValue(\n dialect: ReturnType<typeof getDialect>,\n propsColumn: SQL,\n pointer: JsonPointer,\n valueType: ValueType | undefined,\n): SQL {\n switch (valueType) {\n case \"number\": {\n return dialect.jsonExtractNumber(propsColumn, pointer);\n }\n case \"boolean\": {\n return dialect.jsonExtractBoolean(propsColumn, pointer);\n }\n case \"date\": {\n return dialect.jsonExtractDate(propsColumn, pointer);\n }\n case \"string\":\n case \"unknown\":\n case undefined: {\n return dialect.jsonExtractText(propsColumn, pointer);\n }\n case \"array\":\n case \"object\":\n case \"embedding\": {\n // For advanced index types (GIN/json), callers should use dialect.jsonExtract\n // or index the props column directly. We keep this as a conservative fallback.\n return dialect.jsonExtract(propsColumn, pointer);\n }\n }\n}\n\nfunction getNodeScopeColumns(\n scope: NodeIndexDeclaration[\"scope\"],\n): readonly SystemColumnName[] {\n switch (scope) {\n case \"graphAndKind\": {\n return [\"graph_id\", \"kind\"];\n }\n case \"graph\": {\n return [\"graph_id\"];\n }\n case \"none\": {\n return [];\n }\n }\n}\n\nfunction getEdgeScopeColumns(\n scope: EdgeIndexDeclaration[\"scope\"],\n direction: EdgeIndexDeclaration[\"direction\"],\n): readonly SystemColumnName[] {\n const base =\n scope === \"graphAndKind\" ? ([\"graph_id\", \"kind\"] as const)\n : scope === \"graph\" ? ([\"graph_id\"] as const)\n : ([] as const);\n\n if (direction === \"out\") {\n return [...base, \"from_id\"];\n }\n if (direction === \"in\") {\n return [...base, \"to_id\"];\n }\n return [...base];\n}\n\n// ============================================================\n// WHERE Clause Compilation\n// ============================================================\n\nfunction isIndexWhereLiteralList(\n value: IndexWhereLiteral | readonly IndexWhereLiteral[],\n): value is readonly IndexWhereLiteral[] {\n return Array.isArray(value);\n}\n\nexport function compileIndexWhere(\n ctx: IndexCompilationContext,\n expression: IndexWhereExpression,\n): SQL {\n switch (expression.__type) {\n case \"index_where_and\": {\n return sql`(${sql.join(\n expression.predicates.map((p) => compileIndexWhere(ctx, p)),\n sql` AND `,\n )})`;\n }\n case \"index_where_or\": {\n return sql`(${sql.join(\n expression.predicates.map((p) => compileIndexWhere(ctx, p)),\n sql` OR `,\n )})`;\n }\n case \"index_where_not\": {\n return sql`(NOT ${compileIndexWhere(ctx, expression.predicate)})`;\n }\n case \"index_where_null_check\": {\n const operand = compileIndexWhereOperand(ctx, expression.operand);\n return expression.op === \"isNull\" ?\n sql`${operand} IS NULL`\n : sql`${operand} IS NOT NULL`;\n }\n case \"index_where_comparison\": {\n const left = compileIndexWhereOperand(ctx, expression.left);\n\n const right = expression.right;\n if (isIndexWhereLiteralList(right)) {\n if (expression.op !== \"in\" && expression.op !== \"notIn\") {\n throw new Error(\n `Operator \"${expression.op}\" does not support list comparison in index WHERE clause`,\n );\n }\n const values = right.map((literal) =>\n compileIndexWhereLiteral(ctx.dialect, literal),\n );\n const operator = expression.op === \"in\" ? sql`IN` : sql`NOT IN`;\n return sql`${left} ${operator} (${sql.join(values, sql`, `)})`;\n }\n\n if (expression.op === \"in\" || expression.op === \"notIn\") {\n throw new Error(\n `Operator \"${expression.op}\" requires a list of values in index WHERE clause`,\n );\n }\n\n const rightLiteral = compileIndexWhereLiteral(ctx.dialect, right);\n const opSql = compileComparisonOperator(expression.op);\n return sql`${left} ${opSql} ${rightLiteral}`;\n }\n }\n}\n\nfunction compileIndexWhereOperand(\n ctx: IndexCompilationContext,\n operand: IndexWhereOperand,\n): SQL {\n if (operand.__type === \"index_operand_system\") {\n return ctx.systemColumn(operand.column);\n }\n\n const adapter = getDialect(ctx.dialect);\n const pointer = jsonPointer([operand.field]);\n\n switch (operand.valueType) {\n case \"number\": {\n return adapter.jsonExtractNumber(ctx.propsColumn, pointer);\n }\n case \"boolean\": {\n return adapter.jsonExtractBoolean(ctx.propsColumn, pointer);\n }\n case \"date\": {\n return adapter.jsonExtractDate(ctx.propsColumn, pointer);\n }\n case \"array\":\n case \"object\":\n case \"embedding\": {\n return adapter.jsonExtract(ctx.propsColumn, pointer);\n }\n case \"string\":\n case \"unknown\":\n case undefined: {\n return adapter.jsonExtractText(ctx.propsColumn, pointer);\n }\n }\n}\n\nfunction compileIndexWhereLiteral(\n dialect: SqlDialect,\n literal: IndexWhereLiteral,\n): SQL {\n switch (literal.valueType) {\n case \"string\":\n case \"date\": {\n return sql.raw(escapeStringLiteral(literal.value.toString()));\n }\n case \"number\": {\n return sql.raw(literal.value.toString());\n }\n case \"boolean\": {\n return getDialect(dialect).booleanLiteral(literal.value as boolean);\n }\n case \"array\":\n case \"object\":\n case \"embedding\":\n case \"unknown\": {\n return sql.raw(escapeStringLiteral(literal.value.toString()));\n }\n }\n}\n\ntype ComparisonIndexWhereOp = Exclude<IndexWhereOp, \"in\" | \"notIn\">;\n\nfunction compileComparisonOperator(op: ComparisonIndexWhereOp): SQL {\n switch (op) {\n case \"eq\": {\n return sql`=`;\n }\n case \"neq\": {\n return sql`<>`;\n }\n case \"gt\": {\n return sql`>`;\n }\n case \"gte\": {\n return sql`>=`;\n }\n case \"lt\": {\n return sql`<`;\n }\n case \"lte\": {\n return sql`<=`;\n }\n }\n}\n\nfunction escapeStringLiteral(value: string): string {\n return `'${value.replaceAll(\"'\", \"''\")}'`;\n}\n","import { type SQL, sql } from \"drizzle-orm\";\nimport { CasingCache } from \"drizzle-orm/casing\";\n\nimport { getDialect, type SqlDialect } from \"../query/dialect\";\nimport {\n compileEdgeIndexKeys,\n compileIndexWhere,\n compileNodeIndexKeys,\n type IndexCompilationContext,\n} from \"./compiler\";\nimport {\n type EdgeIndexDeclaration,\n type NodeIndexDeclaration,\n type RelationalIndexDeclaration,\n type SystemColumnName,\n} from \"./types\";\n\nexport type GenerateIndexDdlOptions = Readonly<{\n nodesTableName?: string | undefined;\n edgesTableName?: string | undefined;\n ifNotExists?: boolean | undefined;\n /**\n * Emit `CREATE INDEX CONCURRENTLY` (Postgres only). Required for\n * `store.materializeIndexes()` so live tables don't take an\n * `AccessExclusiveLock`. Ignored on SQLite (no equivalent; SQLite is\n * single-writer regardless). When true on Postgres, the resulting\n * statement cannot be executed inside a transaction.\n */\n concurrent?: boolean | undefined;\n}>;\n\n/**\n * Generate `CREATE INDEX` DDL for a single relational index declaration.\n *\n * Vector index declarations (`entity: \"vector\"`) are NOT handled here —\n * they go through `backend.createVectorIndex` instead because the DDL\n * is dialect-specific (`USING hnsw (...) WITH (m=..., ef_construction=...)`\n * on Postgres) and operates on the embeddings table, not\n * `typegraph_nodes` / `typegraph_edges`. Callers narrow to the\n * relational subset before calling this function.\n */\nexport function generateIndexDDL(\n index: RelationalIndexDeclaration,\n dialect: SqlDialect,\n options: GenerateIndexDdlOptions = {},\n): string {\n if (index.entity === \"node\") {\n return generateNodeIndexDDL(index, dialect, options);\n }\n return generateEdgeIndexDDL(index, dialect, options);\n}\n\nexport function generateNodeIndexDDL(\n index: NodeIndexDeclaration,\n dialect: SqlDialect,\n options: GenerateIndexDdlOptions = {},\n): string {\n const tableName = options.nodesTableName ?? \"typegraph_nodes\";\n return generateTableIndexDDL(index, dialect, tableName, options);\n}\n\nexport function generateEdgeIndexDDL(\n index: EdgeIndexDeclaration,\n dialect: SqlDialect,\n options: GenerateIndexDdlOptions = {},\n): string {\n const tableName = options.edgesTableName ?? \"typegraph_edges\";\n return generateTableIndexDDL(index, dialect, tableName, options);\n}\n\nfunction generateTableIndexDDL(\n index: RelationalIndexDeclaration,\n dialect: SqlDialect,\n tableName: string,\n options: GenerateIndexDdlOptions,\n): string {\n const ifNotExists = options.ifNotExists ?? true;\n const propsColumn = sql.raw('\"props\"');\n const systemColumn = (column: SystemColumnName): SQL =>\n sql.raw(quoteIdentifier(column));\n\n const keys =\n index.entity === \"node\" ?\n compileNodeIndexKeys(index, dialect, propsColumn, systemColumn).keys\n : compileEdgeIndexKeys(index, dialect, propsColumn, systemColumn).keys;\n\n const whereSql =\n index.where ?\n sqlToInlineString(\n compileIndexWhere(\n {\n dialect,\n propsColumn,\n systemColumn,\n } satisfies IndexCompilationContext,\n index.where,\n ),\n dialect,\n )\n : undefined;\n\n const keySql = keys.map((k) => sqlToInlineString(k, dialect)).join(\", \");\n const unique = index.unique ? \"UNIQUE \" : \"\";\n const concurrent =\n options.concurrent === true && dialect === \"postgres\" ?\n \"CONCURRENTLY \"\n : \"\";\n const ifNotExistsSql = ifNotExists ? \"IF NOT EXISTS \" : \"\";\n\n const whereClause = whereSql ? ` WHERE ${whereSql}` : \"\";\n\n return `CREATE ${unique}INDEX ${concurrent}${ifNotExistsSql}${quoteIdentifier(index.name)} ON ${quoteIdentifier(tableName)} (${keySql})${whereClause};`;\n}\n\nfunction quoteIdentifier(identifier: string): string {\n return `\"${identifier.replaceAll('\"', '\"\"')}\"`;\n}\n\nfunction sqlToInlineString(object: SQL, dialect: SqlDialect): string {\n const query = object.toQuery({\n casing: new CasingCache(),\n escapeName: (name) => name,\n escapeParam: (_number, value) => inlineParam(value, dialect),\n escapeString: (value) => escapeStringLiteral(value),\n inlineParams: true,\n invokeSource: \"indexes\",\n });\n\n if (query.params.length > 0) {\n throw new Error(\n \"Index DDL generation produced parameters; expected fully inlined SQL\",\n );\n }\n\n return query.sql;\n}\n\nfunction inlineParam(value: unknown, dialect: SqlDialect): string {\n if (value === null || value === undefined) {\n return \"NULL\";\n }\n if (value instanceof Date) {\n return escapeStringLiteral(value.toISOString());\n }\n\n if (typeof value === \"string\") {\n return escapeStringLiteral(value);\n }\n if (typeof value === \"number\") {\n return value.toString();\n }\n if (typeof value === \"boolean\") {\n return getDialect(dialect).booleanLiteralString(value);\n }\n if (typeof value === \"bigint\") {\n return value.toString();\n }\n\n throw new TypeError(\n \"Index DDL generation received an unsupported SQL parameter value\",\n );\n}\n\nfunction escapeStringLiteral(value: string): string {\n return `'${value.replaceAll(\"'\", \"''\")}'`;\n}\n","import { type SQL, sql, type SQLWrapper } from \"drizzle-orm\";\nimport {\n index as pgIndex,\n type IndexBuilder as PgIndexBuilder,\n uniqueIndex as pgUniqueIndex,\n} from \"drizzle-orm/pg-core\";\nimport {\n index as sqliteIndex,\n type IndexBuilder as SqliteIndexBuilder,\n uniqueIndex as sqliteUniqueIndex,\n} from \"drizzle-orm/sqlite-core\";\n\nimport {\n compileEdgeIndexKeys,\n compileIndexWhere,\n compileNodeIndexKeys,\n type IndexCompilationContext,\n} from \"./compiler\";\nimport {\n type EdgeIndexDeclaration,\n type IndexDeclaration,\n type NodeIndexDeclaration,\n type SystemColumnName,\n} from \"./types\";\n\n// ============================================================\n// PostgreSQL (Drizzle Schema)\n// ============================================================\n\nexport function buildPostgresNodeIndexBuilders(\n table: NodeIndexTable,\n indexes: readonly IndexDeclaration[],\n): readonly PgIndexBuilder[] {\n const nodeIndexes = indexes.filter(\n (index): index is NodeIndexDeclaration => index.entity === \"node\",\n );\n\n return nodeIndexes.map((index) => {\n const propsColumn = sql`${table.props}`;\n const systemColumn = (column: SystemColumnName): SQL =>\n sql`${getPostgresNodeSystemColumn(table, column)}`;\n\n const { keys } = compileNodeIndexKeys(\n index,\n \"postgres\",\n propsColumn,\n systemColumn,\n );\n assertNonEmpty(keys, `node index \"${index.name}\"`);\n\n const base = index.unique ? pgUniqueIndex(index.name) : pgIndex(index.name);\n\n const builder = base.on(...keys);\n\n if (index.where) {\n const ctx: IndexCompilationContext = {\n dialect: \"postgres\",\n propsColumn,\n systemColumn,\n };\n builder.where(compileIndexWhere(ctx, index.where));\n }\n\n return builder;\n });\n}\n\nexport function buildPostgresEdgeIndexBuilders(\n table: EdgeIndexTable,\n indexes: readonly IndexDeclaration[],\n): readonly PgIndexBuilder[] {\n const edgeIndexes = indexes.filter(\n (index): index is EdgeIndexDeclaration => index.entity === \"edge\",\n );\n\n return edgeIndexes.map((index) => {\n const propsColumn = sql`${table.props}`;\n const systemColumn = (column: SystemColumnName): SQL =>\n sql`${getPostgresEdgeSystemColumn(table, column)}`;\n\n const { keys } = compileEdgeIndexKeys(\n index,\n \"postgres\",\n propsColumn,\n systemColumn,\n );\n assertNonEmpty(keys, `edge index \"${index.name}\"`);\n\n const base = index.unique ? pgUniqueIndex(index.name) : pgIndex(index.name);\n\n const builder = base.on(...keys);\n\n if (index.where) {\n const ctx: IndexCompilationContext = {\n dialect: \"postgres\",\n propsColumn,\n systemColumn,\n };\n builder.where(compileIndexWhere(ctx, index.where));\n }\n\n return builder;\n });\n}\n\nfunction getPostgresNodeSystemColumn(\n table: NodeIndexTable,\n column: SystemColumnName,\n): SQLWrapper {\n switch (column) {\n case \"graph_id\": {\n return table.graphId;\n }\n case \"kind\": {\n return table.kind;\n }\n case \"id\": {\n return table.id;\n }\n case \"from_kind\":\n case \"from_id\":\n case \"to_kind\":\n case \"to_id\": {\n throw new Error(`Unsupported node system column for indexes: ${column}`);\n }\n case \"deleted_at\": {\n return table.deletedAt;\n }\n case \"valid_from\": {\n return table.validFrom;\n }\n case \"valid_to\": {\n return table.validTo;\n }\n case \"created_at\": {\n return table.createdAt;\n }\n case \"updated_at\": {\n return table.updatedAt;\n }\n case \"version\": {\n return table.version;\n }\n }\n}\n\nfunction getPostgresEdgeSystemColumn(\n table: EdgeIndexTable,\n column: SystemColumnName,\n): SQLWrapper {\n switch (column) {\n case \"graph_id\": {\n return table.graphId;\n }\n case \"kind\": {\n return table.kind;\n }\n case \"id\": {\n return table.id;\n }\n case \"from_kind\": {\n return table.fromKind;\n }\n case \"from_id\": {\n return table.fromId;\n }\n case \"to_kind\": {\n return table.toKind;\n }\n case \"to_id\": {\n return table.toId;\n }\n case \"deleted_at\": {\n return table.deletedAt;\n }\n case \"valid_from\": {\n return table.validFrom;\n }\n case \"valid_to\": {\n return table.validTo;\n }\n case \"created_at\": {\n return table.createdAt;\n }\n case \"updated_at\": {\n return table.updatedAt;\n }\n case \"version\": {\n throw new Error(`Unsupported edge system column for indexes: ${column}`);\n }\n }\n}\n\n// ============================================================\n// SQLite (Drizzle Schema)\n// ============================================================\n\nexport function buildSqliteNodeIndexBuilders(\n table: NodeIndexTable,\n indexes: readonly IndexDeclaration[],\n): readonly SqliteIndexBuilder[] {\n const nodeIndexes = indexes.filter(\n (index): index is NodeIndexDeclaration => index.entity === \"node\",\n );\n\n return nodeIndexes.map((index) => {\n const propsColumn = sql`${table.props}`;\n const systemColumn = (column: SystemColumnName): SQL =>\n sql`${getSqliteNodeSystemColumn(table, column)}`;\n\n const { keys } = compileNodeIndexKeys(\n index,\n \"sqlite\",\n propsColumn,\n systemColumn,\n );\n assertNonEmpty(keys, `node index \"${index.name}\"`);\n\n const base =\n index.unique ? sqliteUniqueIndex(index.name) : sqliteIndex(index.name);\n\n const builder = base.on(...keys);\n\n if (index.where) {\n const ctx: IndexCompilationContext = {\n dialect: \"sqlite\",\n propsColumn,\n systemColumn,\n };\n builder.where(compileIndexWhere(ctx, index.where));\n }\n\n return builder;\n });\n}\n\nexport function buildSqliteEdgeIndexBuilders(\n table: EdgeIndexTable,\n indexes: readonly IndexDeclaration[],\n): readonly SqliteIndexBuilder[] {\n const edgeIndexes = indexes.filter(\n (index): index is EdgeIndexDeclaration => index.entity === \"edge\",\n );\n\n return edgeIndexes.map((index) => {\n const propsColumn = sql`${table.props}`;\n const systemColumn = (column: SystemColumnName): SQL =>\n sql`${getSqliteEdgeSystemColumn(table, column)}`;\n\n const { keys } = compileEdgeIndexKeys(\n index,\n \"sqlite\",\n propsColumn,\n systemColumn,\n );\n assertNonEmpty(keys, `edge index \"${index.name}\"`);\n\n const base =\n index.unique ? sqliteUniqueIndex(index.name) : sqliteIndex(index.name);\n\n const builder = base.on(...keys);\n\n if (index.where) {\n const ctx: IndexCompilationContext = {\n dialect: \"sqlite\",\n propsColumn,\n systemColumn,\n };\n builder.where(compileIndexWhere(ctx, index.where));\n }\n\n return builder;\n });\n}\n\nfunction getSqliteNodeSystemColumn(\n table: NodeIndexTable,\n column: SystemColumnName,\n): SQLWrapper {\n switch (column) {\n case \"graph_id\": {\n return table.graphId;\n }\n case \"kind\": {\n return table.kind;\n }\n case \"id\": {\n return table.id;\n }\n case \"from_kind\":\n case \"from_id\":\n case \"to_kind\":\n case \"to_id\": {\n throw new Error(`Unsupported node system column for indexes: ${column}`);\n }\n case \"deleted_at\": {\n return table.deletedAt;\n }\n case \"valid_from\": {\n return table.validFrom;\n }\n case \"valid_to\": {\n return table.validTo;\n }\n case \"created_at\": {\n return table.createdAt;\n }\n case \"updated_at\": {\n return table.updatedAt;\n }\n case \"version\": {\n return table.version;\n }\n }\n}\n\nfunction getSqliteEdgeSystemColumn(\n table: EdgeIndexTable,\n column: SystemColumnName,\n): SQLWrapper {\n switch (column) {\n case \"graph_id\": {\n return table.graphId;\n }\n case \"kind\": {\n return table.kind;\n }\n case \"id\": {\n return table.id;\n }\n case \"from_kind\": {\n return table.fromKind;\n }\n case \"from_id\": {\n return table.fromId;\n }\n case \"to_kind\": {\n return table.toKind;\n }\n case \"to_id\": {\n return table.toId;\n }\n case \"deleted_at\": {\n return table.deletedAt;\n }\n case \"valid_from\": {\n return table.validFrom;\n }\n case \"valid_to\": {\n return table.validTo;\n }\n case \"created_at\": {\n return table.createdAt;\n }\n case \"updated_at\": {\n return table.updatedAt;\n }\n case \"version\": {\n throw new Error(`Unsupported edge system column for indexes: ${column}`);\n }\n }\n}\n\n// ============================================================\n// Minimal table shapes (shared between dialect schemas)\n// ============================================================\n\ntype NodeIndexTable = Readonly<{\n graphId: SQLWrapper;\n kind: SQLWrapper;\n id: SQLWrapper;\n props: SQLWrapper;\n version: SQLWrapper;\n validFrom: SQLWrapper;\n validTo: SQLWrapper;\n createdAt: SQLWrapper;\n updatedAt: SQLWrapper;\n deletedAt: SQLWrapper;\n}>;\n\ntype EdgeIndexTable = Readonly<{\n graphId: SQLWrapper;\n id: SQLWrapper;\n kind: SQLWrapper;\n fromKind: SQLWrapper;\n fromId: SQLWrapper;\n toKind: SQLWrapper;\n toId: SQLWrapper;\n props: SQLWrapper;\n validFrom: SQLWrapper;\n validTo: SQLWrapper;\n createdAt: SQLWrapper;\n updatedAt: SQLWrapper;\n deletedAt: SQLWrapper;\n}>;\n\nfunction assertNonEmpty(\n values: readonly SQL[],\n label: string,\n): asserts values is readonly [SQL, ...SQL[]] {\n if (values.length === 0) {\n throw new Error(`Index must have at least one key (${label})`);\n }\n}\n","import { type DeclaredIndex } from \"../profiler/types\";\nimport {\n type IndexDeclaration,\n type RelationalIndexDeclaration,\n} from \"./types\";\n\nexport function toDeclaredIndex(\n index: RelationalIndexDeclaration,\n): DeclaredIndex {\n return {\n entityType: index.entity,\n kind: index.kind,\n fields: [...index.fields],\n unique: index.unique,\n name: index.name,\n };\n}\n\n/**\n * Vector indexes are excluded from the profiler-format conversion —\n * the profiler operates on relational tables (`typegraph_nodes` /\n * `typegraph_edges`) where index hits / misses can be measured against\n * SQL plans. Vector indexes live on the embeddings table with a\n * different access pattern.\n */\nexport function toDeclaredIndexes(\n indexes: readonly IndexDeclaration[],\n): readonly DeclaredIndex[] {\n return indexes\n .filter(\n (index): index is RelationalIndexDeclaration =>\n index.entity === \"node\" || index.entity === \"edge\",\n )\n .map((index) => toDeclaredIndex(index));\n}\n","import { type IndexWhereExpression } from \"./types\";\n\nexport function andWhere(\n ...predicates: [IndexWhereExpression, ...IndexWhereExpression[]]\n): IndexWhereExpression {\n if (predicates.length === 1) {\n return predicates[0];\n }\n\n return {\n __type: \"index_where_and\",\n predicates,\n };\n}\n\nexport function orWhere(\n ...predicates: [IndexWhereExpression, ...IndexWhereExpression[]]\n): IndexWhereExpression {\n if (predicates.length === 1) {\n return predicates[0];\n }\n\n return {\n __type: \"index_where_or\",\n predicates,\n };\n}\n\nexport function notWhere(\n predicate: IndexWhereExpression,\n): IndexWhereExpression {\n return {\n __type: \"index_where_not\",\n predicate,\n };\n}\n"]}