@nicia-ai/typegraph 0.24.1 → 0.25.1

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 (159) hide show
  1. package/dist/backend/postgres/index.cjs +226 -55
  2. package/dist/backend/postgres/index.cjs.map +1 -1
  3. package/dist/backend/postgres/index.d.cts +6 -7
  4. package/dist/backend/postgres/index.d.ts +6 -7
  5. package/dist/backend/postgres/index.js +195 -28
  6. package/dist/backend/postgres/index.js.map +1 -1
  7. package/dist/backend/sqlite/index.cjs +19 -17
  8. package/dist/backend/sqlite/index.d.cts +6 -7
  9. package/dist/backend/sqlite/index.d.ts +6 -7
  10. package/dist/backend/sqlite/index.js +9 -7
  11. package/dist/backend/sqlite/libsql.cjs +12 -10
  12. package/dist/backend/sqlite/libsql.cjs.map +1 -1
  13. package/dist/backend/sqlite/libsql.d.cts +4 -5
  14. package/dist/backend/sqlite/libsql.d.ts +4 -5
  15. package/dist/backend/sqlite/libsql.js +9 -7
  16. package/dist/backend/sqlite/libsql.js.map +1 -1
  17. package/dist/backend/sqlite/local.cjs +14 -12
  18. package/dist/backend/sqlite/local.cjs.map +1 -1
  19. package/dist/backend/sqlite/local.d.cts +4 -5
  20. package/dist/backend/sqlite/local.d.ts +4 -5
  21. package/dist/backend/sqlite/local.js +9 -7
  22. package/dist/backend/sqlite/local.js.map +1 -1
  23. package/dist/chunk-4BOWVUGQ.js +2029 -0
  24. package/dist/chunk-4BOWVUGQ.js.map +1 -0
  25. package/dist/chunk-7V335GHG.cjs +112 -0
  26. package/dist/chunk-7V335GHG.cjs.map +1 -0
  27. package/dist/chunk-AAA2CR3P.js +2628 -0
  28. package/dist/chunk-AAA2CR3P.js.map +1 -0
  29. package/dist/{chunk-QOLTW7OZ.js → chunk-CLEUFN2K.js} +195 -13
  30. package/dist/chunk-CLEUFN2K.js.map +1 -0
  31. package/dist/{chunk-OVJ2BE5Q.cjs → chunk-CLGC7AQ2.cjs} +215 -33
  32. package/dist/chunk-CLGC7AQ2.cjs.map +1 -0
  33. package/dist/{chunk-GUTQTMOV.js → chunk-CPFR3O7L.js} +2 -2
  34. package/dist/chunk-CPFR3O7L.js.map +1 -0
  35. package/dist/{chunk-5HVDOPZU.cjs → chunk-CQVNGKU7.cjs} +452 -104
  36. package/dist/chunk-CQVNGKU7.cjs.map +1 -0
  37. package/dist/chunk-CTHNVU6K.cjs +551 -0
  38. package/dist/chunk-CTHNVU6K.cjs.map +1 -0
  39. package/dist/chunk-D2GO3RBL.cjs +12 -0
  40. package/dist/chunk-D2GO3RBL.cjs.map +1 -0
  41. package/dist/{chunk-WFMTAEEN.js → chunk-DOTEN2FG.js} +81 -7
  42. package/dist/chunk-DOTEN2FG.js.map +1 -0
  43. package/dist/chunk-E5JZSEGJ.cjs +301 -0
  44. package/dist/chunk-E5JZSEGJ.cjs.map +1 -0
  45. package/dist/chunk-EG6TJ3I5.js +286 -0
  46. package/dist/chunk-EG6TJ3I5.js.map +1 -0
  47. package/dist/chunk-EJCDOA37.js +537 -0
  48. package/dist/chunk-EJCDOA37.js.map +1 -0
  49. package/dist/{chunk-UVZHTBZ5.cjs → chunk-EK6RJ373.cjs} +7 -150
  50. package/dist/chunk-EK6RJ373.cjs.map +1 -0
  51. package/dist/{chunk-3JK66E3I.cjs → chunk-JTI5WT4P.cjs} +630 -59
  52. package/dist/chunk-JTI5WT4P.cjs.map +1 -0
  53. package/dist/chunk-NHQWXSTS.js +10 -0
  54. package/dist/chunk-NHQWXSTS.js.map +1 -0
  55. package/dist/chunk-NZ5PMBTG.js +105 -0
  56. package/dist/chunk-NZ5PMBTG.js.map +1 -0
  57. package/dist/{chunk-SUHW2UYL.cjs → chunk-OECDVACY.cjs} +2 -2
  58. package/dist/chunk-OECDVACY.cjs.map +1 -0
  59. package/dist/{chunk-EYELZHKY.js → chunk-OOS2RKRH.js} +5 -140
  60. package/dist/chunk-OOS2RKRH.js.map +1 -0
  61. package/dist/{chunk-EY4LBX3F.js → chunk-PSKUWVCB.js} +373 -38
  62. package/dist/chunk-PSKUWVCB.js.map +1 -0
  63. package/dist/chunk-QMQYK3IF.cjs +2680 -0
  64. package/dist/chunk-QMQYK3IF.cjs.map +1 -0
  65. package/dist/chunk-RCAJZG67.cjs +2069 -0
  66. package/dist/chunk-RCAJZG67.cjs.map +1 -0
  67. package/dist/{chunk-O5PST6TB.cjs → chunk-W5MTHMTE.cjs} +83 -6
  68. package/dist/chunk-W5MTHMTE.cjs.map +1 -0
  69. package/dist/chunk-WVQXAFP3.js +79 -0
  70. package/dist/chunk-WVQXAFP3.js.map +1 -0
  71. package/dist/chunk-X3244EKP.cjs +84 -0
  72. package/dist/chunk-X3244EKP.cjs.map +1 -0
  73. package/dist/{chunk-753F33CV.js → chunk-YZZBDCLV.js} +617 -44
  74. package/dist/chunk-YZZBDCLV.js.map +1 -0
  75. package/dist/{ddl-B_H8JM-E.d.cts → ddl-BqMmpNor.d.ts} +1328 -283
  76. package/dist/{ddl-1tFIvt9V.d.ts → ddl-Bwjh8Hff.d.cts} +1328 -283
  77. package/dist/extension-types-D07e_NTw.d.cts +543 -0
  78. package/dist/extension-types-D07e_NTw.d.ts +543 -0
  79. package/dist/graph-extension/index.cjs +71 -0
  80. package/dist/graph-extension/index.cjs.map +1 -0
  81. package/dist/graph-extension/index.d.cts +278 -0
  82. package/dist/graph-extension/index.d.ts +278 -0
  83. package/dist/graph-extension/index.js +6 -0
  84. package/dist/graph-extension/index.js.map +1 -0
  85. package/dist/{index-DXkEXpNz.d.ts → index-CT6nvtxL.d.cts} +114 -5
  86. package/dist/{index-DXkEXpNz.d.cts → index-DQheiVQV.d.ts} +114 -5
  87. package/dist/index.cjs +2672 -901
  88. package/dist/index.cjs.map +1 -1
  89. package/dist/index.d.cts +29 -10
  90. package/dist/index.d.ts +29 -10
  91. package/dist/index.js +2248 -598
  92. package/dist/index.js.map +1 -1
  93. package/dist/indexes/index.cjs +25 -23
  94. package/dist/indexes/index.d.cts +40 -22
  95. package/dist/indexes/index.d.ts +40 -22
  96. package/dist/indexes/index.js +5 -3
  97. package/dist/interchange/index.cjs +8 -7
  98. package/dist/interchange/index.cjs.map +1 -1
  99. package/dist/interchange/index.d.cts +5 -4
  100. package/dist/interchange/index.d.ts +5 -4
  101. package/dist/interchange/index.js +3 -2
  102. package/dist/interchange/index.js.map +1 -1
  103. package/dist/{manager-Vkz28eAC.d.cts → manager-Cy3dhwYO.d.cts} +194 -6
  104. package/dist/{manager-nIhmttD-.d.ts → manager-sZkU2VPC.d.ts} +194 -6
  105. package/dist/materialize-indexes-BB9N5uQl.d.cts +68 -0
  106. package/dist/materialize-indexes-BYpU2RKh.d.ts +68 -0
  107. package/dist/profiler/index.cjs +10 -8
  108. package/dist/profiler/index.cjs.map +1 -1
  109. package/dist/profiler/index.d.cts +8 -7
  110. package/dist/profiler/index.d.ts +8 -7
  111. package/dist/profiler/index.js +3 -1
  112. package/dist/profiler/index.js.map +1 -1
  113. package/dist/schema/index.cjs +43 -22
  114. package/dist/schema/index.cjs.map +1 -1
  115. package/dist/schema/index.d.cts +17 -8
  116. package/dist/schema/index.d.ts +17 -8
  117. package/dist/schema/index.js +9 -4
  118. package/dist/schema/index.js.map +1 -1
  119. package/dist/{sqlite-D0aceIe0.d.cts → sqlite-BhFswiAR.d.cts} +837 -120
  120. package/dist/{sqlite-SUxbZqfy.d.ts → sqlite-h6dta1IJ.d.ts} +837 -120
  121. package/dist/{store-CpvwTMxV.d.cts → store-BS_hehiz.d.ts} +659 -23
  122. package/dist/{store-U3i2tUch.d.ts → store-CkCvqRUf.d.cts} +659 -23
  123. package/dist/{types-yH4_p0XB.d.cts → types-BpgACExN.d.cts} +3 -2
  124. package/dist/{types-qYFZ9SqD.d.ts → types-Bz-Pi681.d.ts} +3 -2
  125. package/dist/types-DptZHe-l.d.ts +2132 -0
  126. package/dist/types-WF5ItKQu.d.cts +2132 -0
  127. package/dist/where-C40InMIp.d.ts +11 -0
  128. package/dist/where-DZYMiXVq.d.cts +11 -0
  129. package/package.json +33 -73
  130. package/dist/ast-C8S37w1A.d.ts +0 -497
  131. package/dist/ast-dgLhLOg0.d.cts +0 -497
  132. package/dist/chunk-3JK66E3I.cjs.map +0 -1
  133. package/dist/chunk-3PPEHLGK.js +0 -1116
  134. package/dist/chunk-3PPEHLGK.js.map +0 -1
  135. package/dist/chunk-5HVDOPZU.cjs.map +0 -1
  136. package/dist/chunk-753F33CV.js.map +0 -1
  137. package/dist/chunk-EY4LBX3F.js.map +0 -1
  138. package/dist/chunk-EYELZHKY.js.map +0 -1
  139. package/dist/chunk-GFGVREHH.js +0 -1381
  140. package/dist/chunk-GFGVREHH.js.map +0 -1
  141. package/dist/chunk-GUTQTMOV.js.map +0 -1
  142. package/dist/chunk-LBORRUNJ.js +0 -135
  143. package/dist/chunk-LBORRUNJ.js.map +0 -1
  144. package/dist/chunk-O5PST6TB.cjs.map +0 -1
  145. package/dist/chunk-OLROXS2S.cjs +0 -147
  146. package/dist/chunk-OLROXS2S.cjs.map +0 -1
  147. package/dist/chunk-OVJ2BE5Q.cjs.map +0 -1
  148. package/dist/chunk-PAUN562Y.cjs +0 -1417
  149. package/dist/chunk-PAUN562Y.cjs.map +0 -1
  150. package/dist/chunk-PEE4EWXZ.cjs +0 -1131
  151. package/dist/chunk-PEE4EWXZ.cjs.map +0 -1
  152. package/dist/chunk-QOLTW7OZ.js.map +0 -1
  153. package/dist/chunk-SUHW2UYL.cjs.map +0 -1
  154. package/dist/chunk-UVZHTBZ5.cjs.map +0 -1
  155. package/dist/chunk-WFMTAEEN.js.map +0 -1
  156. package/dist/types-C-zfYDJB.d.ts +0 -159
  157. package/dist/types-CQx4iW5Y.d.cts +0 -159
  158. package/dist/types-Qk2l3IkQ.d.cts +0 -1254
  159. package/dist/types-Qk2l3IkQ.d.ts +0 -1254
@@ -107,18 +107,27 @@ var EdgeNotFoundError = class extends TypeGraphError {
107
107
  }
108
108
  };
109
109
  var KindNotFoundError = class extends TypeGraphError {
110
- constructor(kind, type, options) {
110
+ kindName;
111
+ entity;
112
+ constructor(kindName, entity, options) {
113
+ const where = options?.graphId === void 0 ? "" : ` on graph "${options.graphId}"`;
111
114
  super(
112
- `${type === "node" ? "Node" : "Edge"} kind not found: ${kind}`,
115
+ `${entity === "node" ? "Node" : "Edge"} kind "${kindName}" is not registered${where}.`,
113
116
  "KIND_NOT_FOUND",
114
117
  {
115
- details: { kind, type },
118
+ details: {
119
+ kindName,
120
+ entity,
121
+ ...options?.graphId === void 0 ? {} : { graphId: options.graphId }
122
+ },
116
123
  category: "user",
117
- suggestion: `Verify "${kind}" is defined in your graph schema and spelled correctly.`,
124
+ suggestion: options?.suggestion ?? "Compile-time kinds come from defineGraph; extension kinds appear after store.evolve() returns. Check store.introspect() for the registered set.",
118
125
  cause: options?.cause
119
126
  }
120
127
  );
121
128
  this.name = "KindNotFoundError";
129
+ this.kindName = kindName;
130
+ this.entity = entity;
122
131
  }
123
132
  };
124
133
  var NodeConstraintNotFoundError = class extends TypeGraphError {
@@ -270,6 +279,71 @@ var MigrationError = class extends TypeGraphError {
270
279
  this.name = "MigrationError";
271
280
  }
272
281
  };
282
+ var EagerMaterializationError = class extends TypeGraphError {
283
+ /**
284
+ * The full materialization result, including successful and failed
285
+ * entries. Same shape as `Store.materializeIndexes()` returns.
286
+ */
287
+ materialization;
288
+ constructor(materialization, graphId) {
289
+ const names = collectFailedIndexNames(materialization);
290
+ super(
291
+ `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().`,
292
+ "EAGER_MATERIALIZATION_FAILED",
293
+ {
294
+ details: { graphId, failedIndexNames: names },
295
+ category: "system",
296
+ suggestion: `Inspect error.materialization for per-index errors. Each failure preserves any prior successful materialization timestamp; the schema is committed regardless.`
297
+ }
298
+ );
299
+ this.name = "EagerMaterializationError";
300
+ this.materialization = materialization;
301
+ }
302
+ /**
303
+ * Names of just the indexes that failed — derived from
304
+ * `materialization.results` so the two views can never disagree.
305
+ */
306
+ get failedIndexNames() {
307
+ return collectFailedIndexNames(this.materialization);
308
+ }
309
+ };
310
+ function collectFailedIndexNames(materialization) {
311
+ const names = [];
312
+ for (const entry of materialization.results) {
313
+ if (entry.status === "failed") names.push(entry.indexName);
314
+ }
315
+ return names;
316
+ }
317
+ var StaleVersionError = class extends TypeGraphError {
318
+ constructor(details, options) {
319
+ super(
320
+ `Schema version was advanced by another writer for graph "${details.graphId}": expected active version ${details.expected}, actual is ${details.actual}`,
321
+ "STALE_SCHEMA_VERSION",
322
+ {
323
+ details,
324
+ category: "system",
325
+ suggestion: `Re-read the active schema version, recompute the new version against that baseline, and retry the commit.`,
326
+ cause: options?.cause
327
+ }
328
+ );
329
+ this.name = "StaleVersionError";
330
+ }
331
+ };
332
+ var SchemaContentConflictError = class extends TypeGraphError {
333
+ constructor(details, options) {
334
+ super(
335
+ `Schema content conflict for graph "${details.graphId}" at version ${details.version}: existing hash ${details.existingHash} differs from incoming hash ${details.incomingHash}`,
336
+ "SCHEMA_CONTENT_CONFLICT",
337
+ {
338
+ details,
339
+ category: "system",
340
+ suggestion: `Two writers committed different schemas at the same version. Reconcile the application deployments so they produce the same canonical schema, then retry.`,
341
+ cause: options?.cause
342
+ }
343
+ );
344
+ this.name = "SchemaContentConflictError";
345
+ }
346
+ };
273
347
  var ConfigurationError = class extends TypeGraphError {
274
348
  constructor(message, details = {}, options) {
275
349
  super(message, "CONFIGURATION_ERROR", {
@@ -345,6 +419,6 @@ function getErrorSuggestion(error) {
345
419
  return isTypeGraphError(error) ? error.suggestion : void 0;
346
420
  }
347
421
 
348
- export { BackendDisposedError, CardinalityError, CompilerInvariantError, ConfigurationError, DatabaseOperationError, DisjointError, EdgeNotFoundError, EndpointError, EndpointNotFoundError, KindNotFoundError, MigrationError, NodeConstraintNotFoundError, NodeNotFoundError, RestrictedDeleteError, SchemaMismatchError, TypeGraphError, UniquenessError, UnsupportedPredicateError, ValidationError, VersionConflictError, getErrorSuggestion, isConstraintError, isSystemError, isTypeGraphError, isUserRecoverable };
349
- //# sourceMappingURL=chunk-WFMTAEEN.js.map
350
- //# sourceMappingURL=chunk-WFMTAEEN.js.map
422
+ export { BackendDisposedError, CardinalityError, CompilerInvariantError, ConfigurationError, DatabaseOperationError, DisjointError, EagerMaterializationError, EdgeNotFoundError, EndpointError, EndpointNotFoundError, KindNotFoundError, MigrationError, NodeConstraintNotFoundError, NodeNotFoundError, RestrictedDeleteError, SchemaContentConflictError, SchemaMismatchError, StaleVersionError, TypeGraphError, UniquenessError, UnsupportedPredicateError, ValidationError, VersionConflictError, getErrorSuggestion, isConstraintError, isSystemError, isTypeGraphError, isUserRecoverable };
423
+ //# sourceMappingURL=chunk-DOTEN2FG.js.map
424
+ //# sourceMappingURL=chunk-DOTEN2FG.js.map
@@ -0,0 +1 @@
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,UAAU,KAAK,CAAA;AAAA,EAC7B,SAAS,KAAA,EAAO;AACd,IAAA,OAAO,CAAA,sBAAA,EACL,KAAA,YAAiB,KAA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BAAA,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"]}
@@ -0,0 +1,301 @@
1
+ 'use strict';
2
+
3
+ var chunkX3244EKP_cjs = require('./chunk-X3244EKP.cjs');
4
+ var chunkW5MTHMTE_cjs = require('./chunk-W5MTHMTE.cjs');
5
+
6
+ // src/core/types.ts
7
+ var NODE_TYPE_BRAND = "__nodeType";
8
+ var EDGE_TYPE_BRAND = "__edgeType";
9
+ function isNodeType(value) {
10
+ return typeof value === "object" && value !== null && NODE_TYPE_BRAND in value && value[NODE_TYPE_BRAND] === true;
11
+ }
12
+ function isEdgeType(value) {
13
+ return typeof value === "object" && value !== null && EDGE_TYPE_BRAND in value && value[EDGE_TYPE_BRAND] === true;
14
+ }
15
+ function isEdgeTypeWithEndpoints(value) {
16
+ return isEdgeType(value) && Array.isArray(value.from) && value.from.length > 0 && Array.isArray(value.to) && value.to.length > 0;
17
+ }
18
+
19
+ // src/indexes/auto-derive.ts
20
+ function autoDeriveVectorIndexes(nodes) {
21
+ const out = [];
22
+ for (const registration of Object.values(nodes)) {
23
+ const node = registration.type;
24
+ const shape = readObjectShape(node.schema);
25
+ if (shape === void 0) continue;
26
+ for (const [fieldName, fieldSchema] of Object.entries(shape)) {
27
+ const config = readEmbeddingIndex(fieldSchema);
28
+ if (config === void 0) continue;
29
+ const dimensions = readEmbeddingDimensions(fieldSchema);
30
+ if (dimensions === void 0) continue;
31
+ out.push(buildAutoDerived(node.kind, fieldName, dimensions, config));
32
+ }
33
+ }
34
+ return out;
35
+ }
36
+ function mergeVectorIndexes(explicit, autoDerived) {
37
+ if (autoDerived.length === 0) return explicit;
38
+ const explicitVectorKeys = /* @__PURE__ */ new Set();
39
+ for (const declaration of explicit) {
40
+ if (declaration.entity === "vector") {
41
+ explicitVectorKeys.add(`${declaration.kind}|${declaration.fieldPath}`);
42
+ }
43
+ }
44
+ const filteredAuto = autoDerived.filter(
45
+ (entry) => !explicitVectorKeys.has(`${entry.kind}|${entry.fieldPath}`)
46
+ );
47
+ return [...explicit, ...filteredAuto];
48
+ }
49
+ function buildAutoDerived(kind, fieldName, dimensions, config) {
50
+ const fieldPath = fieldName;
51
+ return Object.freeze({
52
+ entity: "vector",
53
+ name: `tg_vec_${sanitize(kind)}_${sanitize(fieldName)}_${config.metric}`,
54
+ kind,
55
+ fieldPath,
56
+ dimensions,
57
+ metric: config.metric,
58
+ indexType: config.indexType,
59
+ indexParams: Object.freeze({
60
+ m: config.m,
61
+ efConstruction: config.efConstruction,
62
+ lists: config.lists
63
+ })
64
+ });
65
+ }
66
+ function sanitize(value) {
67
+ return value.replaceAll(/[^a-zA-Z0-9]/g, "_").toLowerCase();
68
+ }
69
+ function readObjectShape(schema) {
70
+ if (schema.type !== "object") return void 0;
71
+ const shape = schema.def.shape;
72
+ return shape;
73
+ }
74
+ function readEmbeddingIndex(schema) {
75
+ for (const candidate of unwrapChain(schema)) {
76
+ const config = chunkX3244EKP_cjs.getEmbeddingIndex(candidate);
77
+ if (config !== void 0) return config;
78
+ }
79
+ return void 0;
80
+ }
81
+ function readEmbeddingDimensions(schema) {
82
+ for (const candidate of unwrapChain(schema)) {
83
+ if (chunkX3244EKP_cjs.isEmbeddingSchema(candidate)) {
84
+ return candidate._embeddingDimensions;
85
+ }
86
+ }
87
+ return void 0;
88
+ }
89
+ function* unwrapChain(schema) {
90
+ const seen = /* @__PURE__ */ new Set();
91
+ let current = schema;
92
+ let depth = 0;
93
+ while (current !== void 0 && !seen.has(current) && depth < 8) {
94
+ seen.add(current);
95
+ yield current;
96
+ current = unwrapOnce(current);
97
+ depth++;
98
+ }
99
+ }
100
+ function unwrapOnce(schema) {
101
+ const candidate = schema;
102
+ if (typeof candidate.unwrap === "function") return candidate.unwrap();
103
+ return schema.def?.innerType;
104
+ }
105
+
106
+ // src/core/define-graph.ts
107
+ var GRAPH_DEF_BRAND = "__graphDef";
108
+ function validateConstraintNarrowing(name, edgeType, registration) {
109
+ const builtInFromNames = new Set(edgeType.from.map((node) => node.kind));
110
+ for (const fromNode of registration.from) {
111
+ if (!builtInFromNames.has(fromNode.kind)) {
112
+ throw new chunkW5MTHMTE_cjs.ConfigurationError(
113
+ `Edge "${name}" registration has 'from' kind "${fromNode.kind}" not in edge's built-in domain: [${[...builtInFromNames].join(", ")}]`,
114
+ {
115
+ edgeName: name,
116
+ invalidFrom: fromNode.kind,
117
+ allowedFrom: [...builtInFromNames]
118
+ },
119
+ {
120
+ suggestion: `Edge registration can only narrow, not widen, the edge type's built-in constraints.`
121
+ }
122
+ );
123
+ }
124
+ }
125
+ const builtInToNames = new Set(edgeType.to.map((node) => node.kind));
126
+ for (const toNode of registration.to) {
127
+ if (!builtInToNames.has(toNode.kind)) {
128
+ throw new chunkW5MTHMTE_cjs.ConfigurationError(
129
+ `Edge "${name}" registration has 'to' kind "${toNode.kind}" not in edge's built-in range: [${[...builtInToNames].join(", ")}]`,
130
+ {
131
+ edgeName: name,
132
+ invalidTo: toNode.kind,
133
+ allowedTo: [...builtInToNames]
134
+ },
135
+ {
136
+ suggestion: `Edge registration can only narrow, not widen, the edge type's built-in constraints.`
137
+ }
138
+ );
139
+ }
140
+ }
141
+ }
142
+ function normalizeEdgeEntry(name, entry, allNodeTypes) {
143
+ if (isEdgeType(entry)) {
144
+ if (isEdgeTypeWithEndpoints(entry)) {
145
+ return { type: entry, from: entry.from, to: entry.to };
146
+ }
147
+ return { type: entry, from: allNodeTypes, to: allNodeTypes };
148
+ }
149
+ if (isEdgeTypeWithEndpoints(entry.type)) {
150
+ validateConstraintNarrowing(name, entry.type, entry);
151
+ }
152
+ return entry;
153
+ }
154
+ function normalizeEdges(edges, allNodeTypes) {
155
+ const result = {};
156
+ for (const [name, entry] of Object.entries(edges)) {
157
+ result[name] = normalizeEdgeEntry(name, entry, allNodeTypes);
158
+ }
159
+ return result;
160
+ }
161
+ function defineGraph(config) {
162
+ const defaults = {
163
+ onNodeDelete: config.defaults?.onNodeDelete ?? "restrict",
164
+ temporalMode: config.defaults?.temporalMode ?? "current"
165
+ };
166
+ const allNodeTypes = Object.values(config.nodes).map((reg) => reg.type);
167
+ const normalizedEdges = normalizeEdges(config.edges, allNodeTypes);
168
+ const autoVectorIndexes = autoDeriveVectorIndexes(config.nodes);
169
+ const explicitProvided = config.indexes !== void 0;
170
+ const mergedIndexes = mergeVectorIndexes(
171
+ config.indexes ?? [],
172
+ autoVectorIndexes
173
+ );
174
+ const indexes = !explicitProvided && mergedIndexes.length === 0 ? void 0 : normalizeIndexes(mergedIndexes, config.nodes, normalizedEdges);
175
+ return Object.freeze({
176
+ [GRAPH_DEF_BRAND]: true,
177
+ id: config.id,
178
+ nodes: config.nodes,
179
+ edges: normalizedEdges,
180
+ ontology: config.ontology ?? [],
181
+ defaults,
182
+ indexes,
183
+ extension: void 0,
184
+ deprecatedKinds: EMPTY_DEPRECATED_KINDS
185
+ });
186
+ }
187
+ var EMPTY_DEPRECATED_KINDS = Object.freeze(
188
+ /* @__PURE__ */ new Set()
189
+ );
190
+ function normalizeIndexes(inputs, nodes, edges) {
191
+ if (inputs.length === 0) {
192
+ return [];
193
+ }
194
+ const nodeKinds = collectKinds(nodes);
195
+ const edgeKinds = collectKinds(edges);
196
+ const seenNames = /* @__PURE__ */ new Set();
197
+ for (const declaration of inputs) {
198
+ if (declaration.entity === "node" || declaration.entity === "vector") {
199
+ assertKindRegistered(declaration, nodeKinds, "node");
200
+ } else {
201
+ assertKindRegistered(declaration, edgeKinds, "edge");
202
+ }
203
+ if (seenNames.has(declaration.name)) {
204
+ throw new chunkW5MTHMTE_cjs.ConfigurationError(
205
+ `Duplicate index name "${declaration.name}" in defineGraph({ indexes }). Index names must be unique within a graph.`,
206
+ { indexName: declaration.name },
207
+ {
208
+ suggestion: `Pass an explicit { name: "..." } to disambiguate.`
209
+ }
210
+ );
211
+ }
212
+ seenNames.add(declaration.name);
213
+ }
214
+ return inputs;
215
+ }
216
+ function collectKinds(registrations) {
217
+ const kinds = /* @__PURE__ */ new Set();
218
+ for (const registration of Object.values(registrations)) {
219
+ kinds.add(registration.type.kind);
220
+ }
221
+ return kinds;
222
+ }
223
+ function assertKindRegistered(declaration, registeredKinds, entity) {
224
+ if (registeredKinds.has(declaration.kind)) return;
225
+ const slot = entity === "node" ? "nodes" : "edges";
226
+ const suggestion = entity === "node" ? `Add { ${declaration.kind}: { type: ${declaration.kind} } } to defineGraph({ nodes }) or remove the index from "indexes".` : `Register the edge in defineGraph({ edges }) or remove the index from "indexes".`;
227
+ throw new chunkW5MTHMTE_cjs.ConfigurationError(
228
+ `Index "${declaration.name}" references ${entity} kind "${declaration.kind}" which is not registered in this graph's "${slot}".`,
229
+ {
230
+ indexName: declaration.name,
231
+ referencedKind: declaration.kind,
232
+ availableKinds: [...registeredKinds]
233
+ },
234
+ { suggestion }
235
+ );
236
+ }
237
+ function isGraphDef(value) {
238
+ return typeof value === "object" && value !== null && GRAPH_DEF_BRAND in value && value[GRAPH_DEF_BRAND] === true;
239
+ }
240
+ function getNodeKinds(graph) {
241
+ return Object.keys(graph.nodes);
242
+ }
243
+ function getEdgeKinds(graph) {
244
+ return Object.keys(graph.edges);
245
+ }
246
+ function isKnownKind(graph, name) {
247
+ return Object.hasOwn(graph.nodes, name) || Object.hasOwn(graph.edges, name);
248
+ }
249
+
250
+ // src/utils/date.ts
251
+ var ISO_DATE_PATTERN = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z$/;
252
+ function isValidIsoDate(value) {
253
+ if (!ISO_DATE_PATTERN.test(value)) {
254
+ return false;
255
+ }
256
+ const date = new Date(value);
257
+ return !Number.isNaN(date.getTime());
258
+ }
259
+ function validateIsoDate(value, fieldName) {
260
+ if (!isValidIsoDate(value)) {
261
+ throw new chunkW5MTHMTE_cjs.ValidationError(
262
+ `Invalid ISO 8601 datetime for "${fieldName}": "${value}". Expected format: YYYY-MM-DDTHH:mm:ss.sssZ`,
263
+ {
264
+ issues: [
265
+ {
266
+ path: fieldName,
267
+ message: `Invalid ISO 8601 datetime format. Expected: YYYY-MM-DDTHH:mm:ss.sssZ, got: "${value}"`
268
+ }
269
+ ]
270
+ },
271
+ {
272
+ suggestion: `Use a valid ISO 8601 UTC datetime like "2024-01-15T10:30:00.000Z"`
273
+ }
274
+ );
275
+ }
276
+ return value;
277
+ }
278
+ function validateOptionalIsoDate(value, fieldName) {
279
+ if (value === void 0) return void 0;
280
+ return validateIsoDate(value, fieldName);
281
+ }
282
+ function nowIso() {
283
+ return (/* @__PURE__ */ new Date()).toISOString();
284
+ }
285
+
286
+ exports.EDGE_TYPE_BRAND = EDGE_TYPE_BRAND;
287
+ exports.NODE_TYPE_BRAND = NODE_TYPE_BRAND;
288
+ exports.autoDeriveVectorIndexes = autoDeriveVectorIndexes;
289
+ exports.defineGraph = defineGraph;
290
+ exports.getEdgeKinds = getEdgeKinds;
291
+ exports.getNodeKinds = getNodeKinds;
292
+ exports.isEdgeType = isEdgeType;
293
+ exports.isEdgeTypeWithEndpoints = isEdgeTypeWithEndpoints;
294
+ exports.isGraphDef = isGraphDef;
295
+ exports.isKnownKind = isKnownKind;
296
+ exports.isNodeType = isNodeType;
297
+ exports.mergeVectorIndexes = mergeVectorIndexes;
298
+ exports.nowIso = nowIso;
299
+ exports.validateOptionalIsoDate = validateOptionalIsoDate;
300
+ //# sourceMappingURL=chunk-E5JZSEGJ.cjs.map
301
+ //# sourceMappingURL=chunk-E5JZSEGJ.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/types.ts","../src/indexes/auto-derive.ts","../src/core/define-graph.ts","../src/utils/date.ts"],"names":["getEmbeddingIndex","isEmbeddingSchema","ConfigurationError","ValidationError"],"mappings":";;;;;;AAkCO,IAAM,eAAA,GAAkB;AAGxB,IAAM,eAAA,GAAkB;AAiSxB,SAAS,WAAW,KAAA,EAAmC;AAC5D,EAAA,OACE,OAAO,UAAU,QAAA,IACjB,KAAA,KAAU,QACV,eAAA,IAAmB,KAAA,IAClB,KAAA,CAAkC,eAAe,CAAA,KAAM,IAAA;AAE5D;AAKO,SAAS,WAAW,KAAA,EAAsC;AAC/D,EAAA,OACE,OAAO,UAAU,QAAA,IACjB,KAAA,KAAU,QACV,eAAA,IAAmB,KAAA,IAClB,KAAA,CAAkC,eAAe,CAAA,KAAM,IAAA;AAE5D;AAMO,SAAS,wBACd,KAAA,EACgC;AAChC,EAAA,OACE,WAAW,KAAK,CAAA,IAChB,MAAM,OAAA,CAAQ,KAAA,CAAM,IAAI,CAAA,IACxB,KAAA,CAAM,KAAK,MAAA,GAAS,CAAA,IACpB,MAAM,OAAA,CAAQ,KAAA,CAAM,EAAE,CAAA,IACtB,KAAA,CAAM,GAAG,MAAA,GAAS,CAAA;AAEtB;;;ACtTO,SAAS,wBACd,KAAA,EACmC;AACnC,EAAA,MAAM,MAAgC,EAAC;AACvC,EAAA,KAAA,MAAW,YAAA,IAAgB,MAAA,CAAO,MAAA,CAAO,KAAK,CAAA,EAAG;AAC/C,IAAA,MAAM,OAAO,YAAA,CAAa,IAAA;AAC1B,IAAA,MAAM,KAAA,GAAQ,eAAA,CAAgB,IAAA,CAAK,MAAM,CAAA;AACzC,IAAA,IAAI,UAAU,MAAA,EAAW;AACzB,IAAA,KAAA,MAAW,CAAC,SAAA,EAAW,WAAW,KAAK,MAAA,CAAO,OAAA,CAAQ,KAAK,CAAA,EAAG;AAC5D,MAAA,MAAM,MAAA,GAAS,mBAAmB,WAAW,CAAA;AAC7C,MAAA,IAAI,WAAW,MAAA,EAAW;AAC1B,MAAA,MAA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AI,IAAA,EAAK,EAAE,WAAA,EAAY;AAChC","file":"chunk-E5JZSEGJ.cjs","sourcesContent":["import { type z } from \"zod\";\n\n// ============================================================\n// Cross-cutting Discriminators\n// ============================================================\n\n/**\n * Which side of the bipartite graph a kind lives on. Used everywhere a\n * function takes \"the entity that owns a kind\" — error metadata,\n * extension classifiers, removal queues, schema diffs.\n */\nexport type KindEntity = \"node\" | \"edge\";\n\n/**\n * Which physical surface an index targets. Vector indexes don't own a\n * kind directly (they're partial indexes on `typegraph_node_embeddings`\n * scoped by node-kind), but they participate in the same materialization\n * and diff pipelines, so they share this discriminator.\n */\nexport type IndexEntity = \"node\" | \"edge\" | \"vector\";\n\n/**\n * Field-level null-check operations that round-trip through persisted\n * documents (unique-constraint where clauses, index where clauses,\n * graph-extension where clauses, IsNullPredicate). Consolidated so a\n * single rename or extension touches one site.\n */\nexport type NullCheckOp = \"isNull\" | \"isNotNull\";\n\n// ============================================================\n// Brand Keys for Nominal Typing\n// ============================================================\n\n/** Brand key for NodeType */\nexport const NODE_TYPE_BRAND = \"__nodeType\" as const;\n\n/** Brand key for EdgeType */\nexport const EDGE_TYPE_BRAND = \"__edgeType\" as const;\n\n/** Brand symbol for NodeId */\ndeclare const __nodeId: unique symbol;\n\n/** Brand symbol for EdgeId */\ndeclare const __edgeId: unique symbol;\n\n// ============================================================\n// Node Type\n// ============================================================\n\n/**\n * Any JSON-serializable value.\n *\n * Mirrors the JSON wire format: primitives, arrays, and string-keyed objects.\n * `null` is included because the JSON spec requires it for \"no value here\";\n * this is the one place in the public API that uses `null` over `undefined`.\n */\nexport type JsonValue =\n | null\n | string\n | number\n | boolean\n | readonly JsonValue[]\n | Readonly<{ [key: string]: JsonValue }>;\n\n/**\n * Consumer-owned per-kind annotations.\n *\n * Stable labels attached to a node or edge kind at definition time — UI hints,\n * audit policy, provenance pointers, tooling annotations.\n *\n * **Consumer-owned, fully.** TypeGraph never reads, validates, or interprets\n * values in this field. Consumers own the entire namespace; there are no\n * reserved keys or extension prefixes. Future library-owned per-kind state,\n * if needed, will use a separate sibling field rather than carving out keys\n * here.\n *\n * **Annotations participate in schema hashing.** Any change to an annotation\n * value (or adding/removing an annotation key) bumps the canonical schema\n * hash and is reported as a `safe`-severity diff by `getSchemaChanges`. If\n * you don't want versioning for a piece of state, do not put it here.\n *\n * Values must be JSON-serializable — `bigint`, `function`, `symbol`, `undefined`,\n * `Date`, and other class instances are rejected at definition time so they can\n * never silently break schema hashing or storage round-trips.\n */\nexport type KindAnnotations = Readonly<Record<string, JsonValue>>;\n\n/**\n * A node type definition.\n *\n * Created via `defineNode()`. Represents a type of node in the graph\n * with an associated Zod schema for properties.\n */\nexport type NodeType<\n K extends string = string,\n S extends z.ZodObject<z.ZodRawShape> = z.ZodObject<z.ZodRawShape>,\n> = Readonly<{\n [NODE_TYPE_BRAND]: true;\n kind: K;\n schema: S;\n description: string | undefined;\n annotations: KindAnnotations | undefined;\n}>;\n\n/**\n * Branded node ID type.\n *\n * Prevents mixing IDs from different node types at compile time.\n */\nexport type NodeId<N extends NodeType> = string &\n Readonly<{\n [__nodeId]: N;\n }>;\n\n/**\n * Infer the props type from a NodeType.\n */\nexport type NodeProps<N extends NodeType> = z.infer<N[\"schema\"]>;\n\n// ============================================================\n// Edge Type\n// ============================================================\n\n/**\n * An edge type definition.\n *\n * Created via `defineEdge()`. Represents a type of edge in the graph\n * with an optional Zod schema for properties.\n *\n * Optionally includes `from` and `to` arrays that define the allowed\n * source and target node types (domain and range constraints).\n */\nexport type EdgeType<\n K extends string = string,\n S extends z.ZodObject<z.ZodRawShape> = z.ZodObject<z.ZodRawShape>,\n From extends readonly NodeType[] | undefined = undefined,\n To extends readonly NodeType[] | undefined = undefined,\n> = Readonly<{\n [EDGE_TYPE_BRAND]: true;\n kind: K;\n schema: S;\n description: string | undefined;\n annotations: KindAnnotations | undefined;\n from: From;\n to: To;\n}>;\n\n/**\n * Base edge type for use in constraints - accepts any from/to configuration.\n */\nexport type AnyEdgeType = EdgeType<\n string,\n z.ZodObject<z.ZodRawShape>,\n readonly NodeType[] | undefined,\n readonly NodeType[] | undefined\n>;\n\n/**\n * An edge type that has both from and to constraints defined.\n * Can be used directly in defineGraph without an EdgeRegistration wrapper.\n */\nexport type EdgeTypeWithEndpoints = EdgeType<\n string,\n z.ZodObject<z.ZodRawShape>,\n readonly NodeType[],\n readonly NodeType[]\n>;\n\n/**\n * Branded edge ID type.\n *\n * Prevents mixing IDs from different edge types at compile time.\n */\nexport type EdgeId<E extends AnyEdgeType = AnyEdgeType> = string &\n Readonly<{\n [__edgeId]: E;\n }>;\n\n/**\n * Infer the props type from an EdgeType.\n */\nexport type EdgeProps<E extends AnyEdgeType> = z.infer<E[\"schema\"]>;\n\n// ============================================================\n// Configuration Types\n// ============================================================\n\n/**\n * Delete behaviors for nodes.\n */\nexport type DeleteBehavior = \"restrict\" | \"cascade\" | \"disconnect\";\n\n/**\n * Edge cardinality constraints.\n */\nexport type Cardinality =\n | \"many\" // No constraint (default)\n | \"one\" // At most one edge of this kind from any source node\n | \"unique\" // At most one edge of this kind between any (source, target) pair\n | \"oneActive\"; // At most one edge with valid_to IS NULL from any source\n\n/**\n * Endpoint existence modes for edge validation.\n */\nexport type EndpointExistence =\n | \"notDeleted\" // Endpoint deleted_at IS NULL (default)\n | \"currentlyValid\" // Endpoint not deleted AND temporally valid\n | \"ever\"; // Endpoint exists in any state\n\n/**\n * Temporal query modes.\n */\nexport type TemporalMode =\n | \"current\" // Valid now AND not deleted\n | \"asOf\" // Valid at specific date AND not deleted\n | \"includeEnded\" // All validity periods AND not deleted\n | \"includeTombstones\"; // Everything including soft-deleted\n\n/**\n * Uniqueness constraint scope.\n */\nexport type UniquenessScope =\n | \"kind\" // Unique within this exact kind only\n | \"kindWithSubClasses\"; // Unique across this kind and all subclasses\n\n/**\n * Collation for uniqueness constraints.\n */\nexport type Collation = \"binary\" | \"caseInsensitive\";\n\n// ============================================================\n// Uniqueness Constraint\n// ============================================================\n\n/**\n * Uniqueness constraint definition.\n */\nexport type UniqueConstraint<\n S extends z.ZodObject<z.ZodRawShape> = z.ZodObject<z.ZodRawShape>,\n> = Readonly<{\n name: string;\n fields: readonly (keyof z.infer<S> & string)[];\n where?: (\n props: UniqueConstraintPredicateBuilder<S>,\n ) => UniqueConstraintPredicate;\n scope: UniquenessScope;\n collation: Collation;\n}>;\n\n/**\n * Predicate builder for uniqueness constraint where clause.\n * Uses -? to make all fields required in the builder, even if optional in the schema.\n */\ntype UniqueConstraintPredicateBuilder<S extends z.ZodObject<z.ZodRawShape>> =\n Readonly<{\n [K in keyof z.infer<S>]-?: UniqueConstraintField;\n }>;\n\n/**\n * Field operations for uniqueness constraint predicates.\n */\ntype UniqueConstraintField = Readonly<{\n isNull: () => UniqueConstraintPredicate;\n isNotNull: () => UniqueConstraintPredicate;\n}>;\n\n/**\n * A uniqueness constraint predicate (internal representation).\n */\ntype UniqueConstraintPredicate = Readonly<{\n __type: \"unique_predicate\";\n field: string;\n op: NullCheckOp;\n}>;\n\n// ============================================================\n// Node Registration\n// ============================================================\n\n/**\n * Node registration in a graph definition.\n */\nexport type NodeRegistration<N extends NodeType = NodeType> = Readonly<{\n type: N;\n unique?: readonly UniqueConstraint<N[\"schema\"]>[];\n onDelete?: DeleteBehavior;\n}>;\n\n// ============================================================\n// Edge Registration\n// ============================================================\n\n/**\n * Edge registration in a graph definition.\n */\nexport type EdgeRegistration<\n E extends AnyEdgeType = AnyEdgeType,\n FromTypes extends NodeType = NodeType,\n ToTypes extends NodeType = NodeType,\n> = Readonly<{\n type: E;\n from: readonly FromTypes[];\n to: readonly ToTypes[];\n cardinality?: Cardinality;\n endpointExistence?: EndpointExistence;\n}>;\n\n// ============================================================\n// Graph Defaults\n// ============================================================\n\n/**\n * Default settings for a graph.\n */\nexport type GraphDefaults = Readonly<{\n onNodeDelete?: DeleteBehavior;\n temporalMode?: TemporalMode;\n}>;\n\n// ============================================================\n// Type Helpers\n// ============================================================\n\n/**\n * Checks if a value is a NodeType.\n */\nexport function isNodeType(value: unknown): value is NodeType {\n return (\n typeof value === \"object\" &&\n value !== null &&\n NODE_TYPE_BRAND in value &&\n (value as Record<string, unknown>)[NODE_TYPE_BRAND] === true\n );\n}\n\n/**\n * Checks if a value is an EdgeType.\n */\nexport function isEdgeType(value: unknown): value is AnyEdgeType {\n return (\n typeof value === \"object\" &&\n value !== null &&\n EDGE_TYPE_BRAND in value &&\n (value as Record<string, unknown>)[EDGE_TYPE_BRAND] === true\n );\n}\n\n/**\n * Checks if a value is an EdgeType with both from and to constraints defined.\n * Such edges can be used directly in defineGraph without an EdgeRegistration wrapper.\n */\nexport function isEdgeTypeWithEndpoints(\n value: unknown,\n): value is EdgeTypeWithEndpoints {\n return (\n isEdgeType(value) &&\n Array.isArray(value.from) &&\n value.from.length > 0 &&\n Array.isArray(value.to) &&\n value.to.length > 0\n );\n}\n","/**\n * Auto-derive vector index declarations from `embedding()` brands on\n * node schemas.\n *\n * Walks each node's top-level Zod shape, finds fields wrapped in\n * `embedding(dimensions, opts)` (including `.optional()` /\n * `.nullable()` wrappers), and emits one `VectorIndexDeclaration` per\n * (kind, field) pair. The declaration carries the resolved index\n * configuration from the embedding brand — metric, indexType, HNSW /\n * IVFFlat params — so the materializer doesn't need to reach back into\n * the Zod schema.\n *\n * Auto-derivation is intentionally limited to TOP-LEVEL embedding\n * fields. Embeddings nested inside object properties are out of scope\n * for v1 — pgvector's column-based indexes don't address sub-paths\n * cleanly, and the storage layer's `typegraph_node_embeddings` table\n * uses a flat `field_path` keyed at the kind level.\n *\n * Explicit `defineVectorIndex(node, fieldPath, opts)` declarations\n * passed via `defineGraph({ indexes })` take precedence — when an\n * explicit declaration matches the same (kind, fieldPath) as an\n * auto-derived one, the explicit version wins. This lets consumers\n * override defaults without losing auto-derivation for other fields.\n */\n\nimport { type z } from \"zod\";\n\nimport {\n getEmbeddingIndex,\n isEmbeddingSchema,\n type ResolvedEmbeddingIndex,\n} from \"../core/embedding\";\nimport { type NodeRegistration } from \"../core/types\";\nimport { type IndexDeclaration, type VectorIndexDeclaration } from \"./types\";\n\n/**\n * Auto-derive vector index declarations from embedding brands on a\n * map of node registrations. Returns one declaration per\n * (kind, top-level field) pair. Empty array when no embeddings found.\n *\n * Cross-graph status-table disambiguation does NOT happen here — the\n * declaration name stays clean (`tg_vec_{kind}_{field}_{metric}`) so\n * `pg_indexes` and result-entry inspection are readable. The\n * materializer composes a graph-scoped key (`${graphId}::${name}`)\n * for status-table identity, applied uniformly to both auto-derived\n * and explicit `VectorIndexDeclaration` entries — see\n * `vectorStatusKey` in `store/materialize-indexes.ts`. This keeps\n * the disambiguation rule in one place that BOTH paths go through,\n * rather than depending on the auto-derive caller to produce a\n * graph-scoped name.\n */\nexport function autoDeriveVectorIndexes(\n nodes: Record<string, NodeRegistration>,\n): readonly VectorIndexDeclaration[] {\n const out: VectorIndexDeclaration[] = [];\n for (const registration of Object.values(nodes)) {\n const node = registration.type;\n const shape = readObjectShape(node.schema);\n if (shape === undefined) continue;\n for (const [fieldName, fieldSchema] of Object.entries(shape)) {\n const config = readEmbeddingIndex(fieldSchema);\n if (config === undefined) continue;\n const dimensions = readEmbeddingDimensions(fieldSchema);\n if (dimensions === undefined) continue;\n out.push(buildAutoDerived(node.kind, fieldName, dimensions, config));\n }\n }\n return out;\n}\n\n/**\n * Merge auto-derived declarations with explicit ones, preferring\n * explicit on (kind, fieldPath) collisions. Returns a flat list of all\n * indexes; non-vector entries from `explicit` pass through unchanged.\n */\nexport function mergeVectorIndexes(\n explicit: readonly IndexDeclaration[],\n autoDerived: readonly VectorIndexDeclaration[],\n): readonly IndexDeclaration[] {\n if (autoDerived.length === 0) return explicit;\n const explicitVectorKeys = new Set<string>();\n for (const declaration of explicit) {\n if (declaration.entity === \"vector\") {\n explicitVectorKeys.add(`${declaration.kind}|${declaration.fieldPath}`);\n }\n }\n const filteredAuto = autoDerived.filter(\n (entry) => !explicitVectorKeys.has(`${entry.kind}|${entry.fieldPath}`),\n );\n return [...explicit, ...filteredAuto];\n}\n\n/**\n * Generate the deterministic vector index name. The visible prefix\n * `tg_vec_<kind>_<field>_<metric>` keeps it scannable in result-entry\n * inspection and the `typegraph_index_materializations` table.\n *\n * Cross-graph disambiguation is handled separately at the\n * materialization boundary (see `vectorStatusKey`) so the declaration\n * name doesn't need to carry `graphId` — the same auto-derived name\n * is reusable across graphs and the materializer composes a\n * graph-scoped status key for both auto-derived and explicit entries\n * uniformly.\n */\nfunction buildAutoDerived(\n kind: string,\n fieldName: string,\n dimensions: number,\n config: ResolvedEmbeddingIndex,\n): VectorIndexDeclaration {\n const fieldPath = fieldName;\n return Object.freeze({\n entity: \"vector\" as const,\n name: `tg_vec_${sanitize(kind)}_${sanitize(fieldName)}_${config.metric}`,\n kind,\n fieldPath,\n dimensions,\n metric: config.metric,\n indexType: config.indexType,\n indexParams: Object.freeze({\n m: config.m,\n efConstruction: config.efConstruction,\n lists: config.lists,\n }),\n });\n}\n\nfunction sanitize(value: string): string {\n return value.replaceAll(/[^a-zA-Z0-9]/g, \"_\").toLowerCase();\n}\n\nfunction readObjectShape(\n schema: z.ZodType,\n): Record<string, z.ZodType> | undefined {\n if ((schema as { type?: string }).type !== \"object\") return undefined;\n const shape = (schema.def as { shape?: Record<string, z.ZodType> }).shape;\n return shape;\n}\n\nfunction readEmbeddingIndex(\n schema: z.ZodType,\n): ResolvedEmbeddingIndex | undefined {\n for (const candidate of unwrapChain(schema)) {\n const config = getEmbeddingIndex(candidate);\n if (config !== undefined) return config;\n }\n return undefined;\n}\n\nfunction readEmbeddingDimensions(schema: z.ZodType): number | undefined {\n for (const candidate of unwrapChain(schema)) {\n if (isEmbeddingSchema(candidate)) {\n return (candidate as unknown as Record<string, number>)\n ._embeddingDimensions;\n }\n }\n return undefined;\n}\n\n/**\n * Yield the schema and every reachable inner schema by repeatedly\n * applying `.unwrap()` (Zod 4 optional/nullable/default) and\n * `.def.innerType` (some wrappers). Cycle-guarded by depth and\n * reference identity. Generators stop at the first non-unwrappable\n * schema OR after 8 levels — deeper wrapping is pathological and not\n * worth supporting.\n */\nfunction* unwrapChain(schema: z.ZodType): Generator<z.ZodType, void, void> {\n const seen = new Set<z.ZodType>();\n let current: z.ZodType | undefined = schema;\n let depth = 0;\n while (current !== undefined && !seen.has(current) && depth < 8) {\n seen.add(current);\n yield current;\n current = unwrapOnce(current);\n depth++;\n }\n}\n\nfunction unwrapOnce(schema: z.ZodType): z.ZodType | undefined {\n // Zod 4 wrappers expose `.unwrap()` on optional/nullable/default.\n const candidate = schema as unknown as { unwrap?: () => z.ZodType };\n if (typeof candidate.unwrap === \"function\") return candidate.unwrap();\n // Some wrappers expose the inner schema via `.def.innerType`.\n return (schema as unknown as { def?: { innerType?: z.ZodType } }).def\n ?.innerType;\n}\n","import { ConfigurationError } from \"../errors/index\";\nimport { type GraphExtension } from \"../graph-extension/extension-types\";\nimport {\n autoDeriveVectorIndexes,\n mergeVectorIndexes,\n} from \"../indexes/auto-derive\";\nimport { type IndexDeclaration } from \"../indexes/types\";\nimport { type OntologyRelation } from \"../ontology/types\";\nimport {\n type AnyEdgeType,\n type DeleteBehavior,\n type EdgeRegistration,\n type EdgeTypeWithEndpoints,\n type GraphDefaults,\n isEdgeType,\n isEdgeTypeWithEndpoints,\n type KindEntity,\n type NodeRegistration,\n type NodeType,\n type TemporalMode,\n} from \"./types\";\n\n// ============================================================\n// Graph Definition Brand Symbol\n// ============================================================\n\n/** Brand key for GraphDef */\nconst GRAPH_DEF_BRAND = \"__graphDef\" as const;\n\n// ============================================================\n// Edge Entry Types\n// ============================================================\n\n/**\n * An edge entry in the graph definition.\n * Can be:\n * - EdgeType directly (constrained or unconstrained)\n * - EdgeRegistration object (always works, can override/narrow defaults)\n */\ntype EdgeEntry = EdgeRegistration | AnyEdgeType;\n\n/**\n * Normalized edge map type - all entries become EdgeRegistration.\n * For bare EdgeTypes, constrained endpoints are extracted from the type;\n * unconstrained edges fall back to all node types in the graph.\n */\ntype NormalizedEdges<\n TNodes extends Record<string, NodeRegistration>,\n TEdges extends Record<string, EdgeEntry>,\n> = {\n [K in keyof TEdges]: TEdges[K] extends EdgeRegistration ? TEdges[K]\n : TEdges[K] extends AnyEdgeType ?\n EdgeRegistration<\n TEdges[K],\n TEdges[K][\"from\"] extends readonly (infer N extends NodeType)[] ? N\n : TNodes[keyof TNodes][\"type\"],\n TEdges[K][\"to\"] extends readonly (infer N extends NodeType)[] ? N\n : TNodes[keyof TNodes][\"type\"]\n >\n : never;\n};\n\n// ============================================================\n// Edge Normalization Functions\n// ============================================================\n\n/**\n * Validates that an EdgeRegistration's constraints don't widen beyond\n * the edge type's built-in domain/range constraints.\n */\nfunction validateConstraintNarrowing(\n name: string,\n edgeType: EdgeTypeWithEndpoints,\n registration: EdgeRegistration,\n): void {\n const builtInFromNames = new Set(edgeType.from.map((node) => node.kind));\n for (const fromNode of registration.from) {\n if (!builtInFromNames.has(fromNode.kind)) {\n throw new ConfigurationError(\n `Edge \"${name}\" registration has 'from' kind \"${fromNode.kind}\" ` +\n `not in edge's built-in domain: [${[...builtInFromNames].join(\", \")}]`,\n {\n edgeName: name,\n invalidFrom: fromNode.kind,\n allowedFrom: [...builtInFromNames],\n },\n {\n suggestion: `Edge registration can only narrow, not widen, the edge type's built-in constraints.`,\n },\n );\n }\n }\n\n const builtInToNames = new Set(edgeType.to.map((node) => node.kind));\n for (const toNode of registration.to) {\n if (!builtInToNames.has(toNode.kind)) {\n throw new ConfigurationError(\n `Edge \"${name}\" registration has 'to' kind \"${toNode.kind}\" ` +\n `not in edge's built-in range: [${[...builtInToNames].join(\", \")}]`,\n {\n edgeName: name,\n invalidTo: toNode.kind,\n allowedTo: [...builtInToNames],\n },\n {\n suggestion: `Edge registration can only narrow, not widen, the edge type's built-in constraints.`,\n },\n );\n }\n }\n}\n\n/**\n * Normalizes a single edge entry to EdgeRegistration.\n */\nfunction normalizeEdgeEntry(\n name: string,\n entry: EdgeEntry,\n allNodeTypes: readonly NodeType[],\n): EdgeRegistration {\n if (isEdgeType(entry)) {\n if (isEdgeTypeWithEndpoints(entry)) {\n // EdgeType with from/to — convert to EdgeRegistration\n return { type: entry, from: entry.from, to: entry.to };\n }\n // Unconstrained EdgeType — allow any→any\n return { type: entry, from: allNodeTypes, to: allNodeTypes };\n }\n\n // Already EdgeRegistration — validate narrowing if edge has built-in constraints\n if (isEdgeTypeWithEndpoints(entry.type)) {\n validateConstraintNarrowing(name, entry.type, entry);\n }\n\n return entry;\n}\n\n/**\n * Normalizes all edge entries to EdgeRegistration.\n */\nfunction normalizeEdges(\n edges: Record<string, EdgeEntry>,\n allNodeTypes: readonly NodeType[],\n): Record<string, EdgeRegistration> {\n const result: Record<string, EdgeRegistration> = {};\n for (const [name, entry] of Object.entries(edges)) {\n result[name] = normalizeEdgeEntry(name, entry, allNodeTypes);\n }\n return result;\n}\n\n// ============================================================\n// Graph Definition Configuration\n// ============================================================\n\n/**\n * Configuration for defineGraph.\n */\ntype GraphDefConfig<\n TNodes extends Record<string, NodeRegistration>,\n TEdges extends Record<string, EdgeEntry>,\n TOntology extends readonly OntologyRelation[],\n> = Readonly<{\n /** Unique identifier for this graph */\n id: string;\n /** Node registrations */\n nodes: TNodes;\n /** Edge registrations or EdgeTypes with built-in domain/range */\n edges: TEdges;\n /** Ontology relations */\n ontology?: TOntology;\n /** Graph-wide defaults */\n defaults?: GraphDefaults;\n /**\n * Index declarations attached to this graph.\n *\n * Accepts the outputs of `defineNodeIndex` / `defineEdgeIndex` (which\n * already return `IndexDeclaration` values) or pre-built declarations\n * reconstructed from a stored schema or graph extension.\n *\n * Validated at definition time: every index must reference a `kind`\n * that exists in `nodes` / `edges`, and index `name`s must be unique\n * within the graph.\n *\n * Index DDL is **not** generated by `defineGraph`. Indexes flow into\n * `SerializedSchema.indexes` so they can later be materialized via\n * `store.materializeIndexes()` — lifting the storage concern out of\n * the schema-version commit path.\n */\n indexes?: readonly IndexDeclaration[];\n}>;\n\n// ============================================================\n// Graph Definition Type\n// ============================================================\n\n/**\n * A graph definition.\n *\n * This is a compile-time artifact that describes the structure of a graph.\n * Use `createStore()` to create a runtime store from this definition.\n */\nexport type GraphDef<\n TNodes extends Record<string, NodeRegistration> = Record<\n string,\n NodeRegistration\n >,\n TEdges extends Record<string, EdgeRegistration> = Record<\n string,\n EdgeRegistration\n >,\n TOntology extends readonly OntologyRelation[] = readonly OntologyRelation[],\n> = Readonly<{\n [GRAPH_DEF_BRAND]: true;\n id: string;\n nodes: TNodes;\n edges: TEdges;\n ontology: TOntology;\n defaults: Readonly<{\n onNodeDelete: DeleteBehavior;\n temporalMode: TemporalMode;\n }>;\n /**\n * Index declarations attached to this graph. Preserves whatever the\n * caller passed to `defineGraph` (including an explicit empty array)\n * for introspection purposes.\n *\n * The serialized canonical form is order-canonicalized (sorted by\n * `name`) and treats `undefined` and `[]` as the same \"no slice\" form\n * — an empty array does not bump the schema hash, since indexes are\n * an unordered set keyed by name and `[]` carries no semantic meaning\n * that an absent slice doesn't.\n */\n indexes: readonly IndexDeclaration[] | undefined;\n /**\n * Graph extension this graph was merged with, if any. Set by\n * `mergeGraphExtension`; never set by `defineGraph` directly.\n * Exists solely so re-serialization is stable — the rest of the\n * system reads the merged kinds through `nodes` / `edges` /\n * `ontology` and never inspects this field. Absent on graphs that\n * have never been extended; legacy graphs hash byte-identically.\n */\n extension: GraphExtension | undefined;\n /**\n * Soft-deprecated kind names attached to this graph. Set by the\n * loader from the persisted schema and by `store.deprecateKinds(...)`\n * / `store.undeprecateKinds(...)`. A purely informational signal\n * surfaced for introspection — does not gate reads, writes, or\n * queries. Defaults to the empty set on freshly-defined graphs.\n */\n deprecatedKinds: ReadonlySet<string>;\n}>;\n\n// ============================================================\n// Type Helpers\n// ============================================================\n\n/**\n * Extract node kind names from a GraphDef.\n */\nexport type NodeKinds<G extends GraphDef> = keyof G[\"nodes\"] & string;\n\n/**\n * Extract edge kind names from a GraphDef.\n */\nexport type EdgeKinds<G extends GraphDef> = keyof G[\"edges\"] & string;\n\n/**\n * Get a NodeType from a GraphDef by kind name.\n */\nexport type GetNodeType<\n G extends GraphDef,\n K extends NodeKinds<G>,\n> = G[\"nodes\"][K][\"type\"];\n\n/**\n * Get an EdgeType from a GraphDef by kind name.\n */\nexport type GetEdgeType<\n G extends GraphDef,\n K extends EdgeKinds<G>,\n> = G[\"edges\"][K][\"type\"];\n\n/**\n * Get all NodeTypes from a GraphDef.\n */\nexport type AllNodeTypes<G extends GraphDef> = {\n [K in NodeKinds<G>]: G[\"nodes\"][K][\"type\"];\n}[NodeKinds<G>];\n\n/**\n * Get all EdgeTypes from a GraphDef.\n */\nexport type AllEdgeTypes<G extends GraphDef> = {\n [K in EdgeKinds<G>]: G[\"edges\"][K][\"type\"];\n}[EdgeKinds<G>];\n\n// ============================================================\n// Define Graph Function\n// ============================================================\n\n/**\n * Creates a graph definition.\n *\n * @example\n * ```typescript\n * const graph = defineGraph({\n * id: \"my_graph\",\n * nodes: {\n * Person: { type: Person },\n * Company: { type: Company },\n * },\n * edges: {\n * // Traditional EdgeRegistration syntax\n * worksAt: {\n * type: worksAt,\n * from: [Person],\n * to: [Company],\n * cardinality: \"many\",\n * },\n * // Or use EdgeType directly if it has from/to defined\n * knows, // EdgeType with built-in domain/range\n * },\n * ontology: [\n * subClassOf(Company, Organization),\n * disjointWith(Person, Organization),\n * ],\n * defaults: {\n * onNodeDelete: \"restrict\",\n * temporalMode: \"current\",\n * },\n * });\n * ```\n */\nexport function defineGraph<\n const TNodes extends Record<string, NodeRegistration<NodeType>>,\n const TEdges extends Record<string, EdgeEntry>,\n const TOntology extends readonly OntologyRelation[],\n>(\n config: GraphDefConfig<TNodes, TEdges, TOntology>,\n): GraphDef<TNodes, NormalizedEdges<TNodes, TEdges>, TOntology> {\n const defaults = {\n onNodeDelete: config.defaults?.onNodeDelete ?? \"restrict\",\n temporalMode: config.defaults?.temporalMode ?? \"current\",\n } as const;\n\n const allNodeTypes = Object.values(config.nodes).map((reg) => reg.type);\n const normalizedEdges = normalizeEdges(config.edges, allNodeTypes);\n // Vector indexes are auto-derived from `embedding()` brands on node\n // schemas (see `autoDeriveVectorIndexes`). Explicit declarations\n // passed via `defineGraph({ indexes })` win on (kind, fieldPath)\n // collisions so consumers can override defaults — see\n // `mergeVectorIndexes`. The merged list flows through\n // `normalizeIndexes` for the standard kind-registered + unique-name\n // checks.\n //\n // Preservation rule: if the consumer never passed `indexes` at all\n // AND no embedding brands exist, leave `graph.indexes` undefined to\n // keep the introspection surface stable for legacy graphs. If the\n // consumer passed an explicit `[]`, surface it as `[]` (not\n // `undefined`) to match the contract pinned by the\n // \"preserves an explicit empty indexes array\" test.\n const autoVectorIndexes = autoDeriveVectorIndexes(config.nodes);\n const explicitProvided = config.indexes !== undefined;\n const mergedIndexes = mergeVectorIndexes(\n config.indexes ?? [],\n autoVectorIndexes,\n );\n const indexes =\n !explicitProvided && mergedIndexes.length === 0 ?\n undefined\n : normalizeIndexes(mergedIndexes, config.nodes, normalizedEdges);\n\n return Object.freeze({\n [GRAPH_DEF_BRAND]: true as const,\n id: config.id,\n nodes: config.nodes,\n edges: normalizedEdges,\n ontology: config.ontology ?? ([] as unknown as TOntology),\n defaults,\n indexes,\n extension: undefined,\n deprecatedKinds: EMPTY_DEPRECATED_KINDS,\n }) as GraphDef<TNodes, NormalizedEdges<TNodes, TEdges>, TOntology>;\n}\n\n// Sharing one frozen empty Set keeps the canonical-form hash stable\n// across graphs that never deprecate any kinds.\nconst EMPTY_DEPRECATED_KINDS: ReadonlySet<string> = Object.freeze(\n new Set<string>(),\n);\n\n// ============================================================\n// Index Normalization\n// ============================================================\n\n/**\n * Validates the `indexes` config slice:\n *\n * - Every index references a kind that exists in the graph's `nodes`\n * (for node indexes) or `edges` (for edge indexes).\n * - Index `name`s are unique within the graph.\n */\nfunction normalizeIndexes(\n inputs: readonly IndexDeclaration[],\n nodes: Record<string, NodeRegistration>,\n edges: Record<string, EdgeRegistration>,\n): readonly IndexDeclaration[] {\n if (inputs.length === 0) {\n return [];\n }\n\n const nodeKinds = collectKinds(nodes);\n const edgeKinds = collectKinds(edges);\n const seenNames = new Set<string>();\n\n for (const declaration of inputs) {\n if (declaration.entity === \"node\" || declaration.entity === \"vector\") {\n // Vector indexes attach to node kinds (the embedding lives on a\n // node field). Validation reuses the node-kind check.\n assertKindRegistered(declaration, nodeKinds, \"node\");\n } else {\n assertKindRegistered(declaration, edgeKinds, \"edge\");\n }\n\n if (seenNames.has(declaration.name)) {\n throw new ConfigurationError(\n `Duplicate index name \"${declaration.name}\" in defineGraph({ indexes }). ` +\n `Index names must be unique within a graph.`,\n { indexName: declaration.name },\n {\n suggestion: `Pass an explicit { name: \"...\" } to disambiguate.`,\n },\n );\n }\n seenNames.add(declaration.name);\n }\n\n return inputs;\n}\n\nfunction collectKinds(\n registrations: Record<string, { type: { kind: string } }>,\n): ReadonlySet<string> {\n const kinds = new Set<string>();\n for (const registration of Object.values(registrations)) {\n kinds.add(registration.type.kind);\n }\n return kinds;\n}\n\nfunction assertKindRegistered(\n declaration: IndexDeclaration,\n registeredKinds: ReadonlySet<string>,\n entity: KindEntity,\n): void {\n if (registeredKinds.has(declaration.kind)) return;\n\n const slot = entity === \"node\" ? \"nodes\" : \"edges\";\n const suggestion =\n entity === \"node\" ?\n `Add { ${declaration.kind}: { type: ${declaration.kind} } } to defineGraph({ nodes }) ` +\n `or remove the index from \"indexes\".`\n : `Register the edge in defineGraph({ edges }) or remove the index from \"indexes\".`;\n\n throw new ConfigurationError(\n `Index \"${declaration.name}\" references ${entity} kind \"${declaration.kind}\" ` +\n `which is not registered in this graph's \"${slot}\".`,\n {\n indexName: declaration.name,\n referencedKind: declaration.kind,\n availableKinds: [...registeredKinds],\n },\n { suggestion },\n );\n}\n\n// ============================================================\n// Graph Definition Utilities\n// ============================================================\n\n/**\n * Checks if a value is a GraphDef.\n */\nexport function isGraphDef(value: unknown): value is GraphDef {\n return (\n typeof value === \"object\" &&\n value !== null &&\n GRAPH_DEF_BRAND in value &&\n (value as Record<string, unknown>)[GRAPH_DEF_BRAND] === true\n );\n}\n\n/**\n * Gets all node kind names from a GraphDef.\n */\nexport function getNodeKinds<G extends GraphDef>(\n graph: G,\n): readonly (keyof G[\"nodes\"] & string)[] {\n return Object.keys(graph.nodes);\n}\n\n/**\n * Gets all edge kind names from a GraphDef.\n */\nexport function getEdgeKinds<G extends GraphDef>(\n graph: G,\n): readonly (keyof G[\"edges\"] & string)[] {\n return Object.keys(graph.edges);\n}\n\n/**\n * Returns true when `name` is registered as either a node or edge kind\n * on the given graph.\n */\nexport function isKnownKind(graph: GraphDef, name: string): boolean {\n return Object.hasOwn(graph.nodes, name) || Object.hasOwn(graph.edges, name);\n}\n","/**\n * Date encoding utilities for consistent storage.\n *\n * Contract: All dates are stored as ISO 8601 strings in UTC.\n * - Always includes milliseconds\n * - Always UTC (Z suffix)\n * - Sorts correctly as strings\n */\n\nimport { ValidationError } from \"../errors\";\n\n/**\n * ISO 8601 datetime pattern.\n * Matches formats like:\n * - 2024-01-15T10:30:00.000Z\n * - 2024-01-15T10:30:00Z\n * - 2024-01-15T10:30:00.123Z\n */\nconst ISO_DATE_PATTERN = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d{1,3})?Z$/;\n\n/**\n * Checks if a string is a valid ISO 8601 datetime.\n *\n * @param value - String to validate\n * @returns True if valid ISO 8601 datetime\n */\nexport function isValidIsoDate(value: string): boolean {\n if (!ISO_DATE_PATTERN.test(value)) {\n return false;\n }\n // Also check that Date parsing produces a valid date\n const date = new Date(value);\n return !Number.isNaN(date.getTime());\n}\n\n/**\n * Validates that a string is a valid ISO 8601 datetime.\n * Throws ValidationError if invalid.\n *\n * @param value - String to validate\n * @param fieldName - Name of field for error message\n * @returns The validated string\n * @throws ValidationError if not a valid ISO datetime\n */\nexport function validateIsoDate(value: string, fieldName: string): string {\n if (!isValidIsoDate(value)) {\n throw new ValidationError(\n `Invalid ISO 8601 datetime for \"${fieldName}\": \"${value}\". ` +\n `Expected format: YYYY-MM-DDTHH:mm:ss.sssZ`,\n {\n issues: [\n {\n path: fieldName,\n message: `Invalid ISO 8601 datetime format. Expected: YYYY-MM-DDTHH:mm:ss.sssZ, got: \"${value}\"`,\n },\n ],\n },\n {\n suggestion: `Use a valid ISO 8601 UTC datetime like \"2024-01-15T10:30:00.000Z\"`,\n },\n );\n }\n return value;\n}\n\n/**\n * Validates an optional ISO date string.\n * Returns undefined if value is undefined, otherwise validates.\n */\nexport function validateOptionalIsoDate(\n value: string | undefined,\n fieldName: string,\n): string | undefined {\n if (value === undefined) return undefined;\n return validateIsoDate(value, fieldName);\n}\n\n/**\n * Encodes a Date to an ISO 8601 string for storage.\n */\nexport function encodeDate(date: Date): string {\n return date.toISOString();\n}\n\n/**\n * Decodes an ISO 8601 string to a Date.\n * Validates the string format first.\n *\n * @throws ValidationError if not a valid ISO datetime\n */\nexport function decodeDate(isoString: string): Date {\n validateIsoDate(isoString, \"date\");\n return new Date(isoString);\n}\n\n/**\n * Returns the current timestamp as an ISO string.\n */\nexport function nowIso(): string {\n return new Date().toISOString();\n}\n"]}