@nicia-ai/typegraph 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +47 -0
  3. package/dist/ast-BVyihVbP.d.cts +564 -0
  4. package/dist/ast-BVyihVbP.d.ts +564 -0
  5. package/dist/backend/drizzle/index.cjs +41 -0
  6. package/dist/backend/drizzle/index.cjs.map +1 -0
  7. package/dist/backend/drizzle/index.d.cts +12 -0
  8. package/dist/backend/drizzle/index.d.ts +12 -0
  9. package/dist/backend/drizzle/index.js +12 -0
  10. package/dist/backend/drizzle/index.js.map +1 -0
  11. package/dist/backend/drizzle/postgres.cjs +27 -0
  12. package/dist/backend/drizzle/postgres.cjs.map +1 -0
  13. package/dist/backend/drizzle/postgres.d.cts +37 -0
  14. package/dist/backend/drizzle/postgres.d.ts +37 -0
  15. package/dist/backend/drizzle/postgres.js +10 -0
  16. package/dist/backend/drizzle/postgres.js.map +1 -0
  17. package/dist/backend/drizzle/schema/postgres.cjs +40 -0
  18. package/dist/backend/drizzle/schema/postgres.cjs.map +1 -0
  19. package/dist/backend/drizzle/schema/postgres.d.cts +2419 -0
  20. package/dist/backend/drizzle/schema/postgres.d.ts +2419 -0
  21. package/dist/backend/drizzle/schema/postgres.js +7 -0
  22. package/dist/backend/drizzle/schema/postgres.js.map +1 -0
  23. package/dist/backend/drizzle/schema/sqlite.cjs +40 -0
  24. package/dist/backend/drizzle/schema/sqlite.cjs.map +1 -0
  25. package/dist/backend/drizzle/schema/sqlite.d.cts +2647 -0
  26. package/dist/backend/drizzle/schema/sqlite.d.ts +2647 -0
  27. package/dist/backend/drizzle/schema/sqlite.js +7 -0
  28. package/dist/backend/drizzle/schema/sqlite.js.map +1 -0
  29. package/dist/backend/drizzle/sqlite.cjs +27 -0
  30. package/dist/backend/drizzle/sqlite.cjs.map +1 -0
  31. package/dist/backend/drizzle/sqlite.d.cts +36 -0
  32. package/dist/backend/drizzle/sqlite.d.ts +36 -0
  33. package/dist/backend/drizzle/sqlite.js +10 -0
  34. package/dist/backend/drizzle/sqlite.js.map +1 -0
  35. package/dist/backend/postgres/index.cjs +53 -0
  36. package/dist/backend/postgres/index.cjs.map +1 -0
  37. package/dist/backend/postgres/index.d.cts +12 -0
  38. package/dist/backend/postgres/index.d.ts +12 -0
  39. package/dist/backend/postgres/index.js +12 -0
  40. package/dist/backend/postgres/index.js.map +1 -0
  41. package/dist/backend/sqlite/index.cjs +117 -0
  42. package/dist/backend/sqlite/index.cjs.map +1 -0
  43. package/dist/backend/sqlite/index.d.cts +71 -0
  44. package/dist/backend/sqlite/index.d.ts +71 -0
  45. package/dist/backend/sqlite/index.js +78 -0
  46. package/dist/backend/sqlite/index.js.map +1 -0
  47. package/dist/chunk-2QHQ2C4P.js +146 -0
  48. package/dist/chunk-2QHQ2C4P.js.map +1 -0
  49. package/dist/chunk-3A5TKOEJ.js +306 -0
  50. package/dist/chunk-3A5TKOEJ.js.map +1 -0
  51. package/dist/chunk-4PIEL2VO.js +162 -0
  52. package/dist/chunk-4PIEL2VO.js.map +1 -0
  53. package/dist/chunk-536PH5FT.js +342 -0
  54. package/dist/chunk-536PH5FT.js.map +1 -0
  55. package/dist/chunk-DBFCKELK.cjs +156 -0
  56. package/dist/chunk-DBFCKELK.cjs.map +1 -0
  57. package/dist/chunk-DDM2FZRJ.cjs +1143 -0
  58. package/dist/chunk-DDM2FZRJ.cjs.map +1 -0
  59. package/dist/chunk-DGUM43GV.js +10 -0
  60. package/dist/chunk-DGUM43GV.js.map +1 -0
  61. package/dist/chunk-F32HCHYA.cjs +680 -0
  62. package/dist/chunk-F32HCHYA.cjs.map +1 -0
  63. package/dist/chunk-IIAT36MI.js +353 -0
  64. package/dist/chunk-IIAT36MI.js.map +1 -0
  65. package/dist/chunk-JDAET5LO.js +236 -0
  66. package/dist/chunk-JDAET5LO.js.map +1 -0
  67. package/dist/chunk-JEQ2X3Z6.cjs +12 -0
  68. package/dist/chunk-JEQ2X3Z6.cjs.map +1 -0
  69. package/dist/chunk-JKTO7TW3.js +299 -0
  70. package/dist/chunk-JKTO7TW3.js.map +1 -0
  71. package/dist/chunk-K7SQ3SWP.js +497 -0
  72. package/dist/chunk-K7SQ3SWP.js.map +1 -0
  73. package/dist/chunk-L642L24T.js +142 -0
  74. package/dist/chunk-L642L24T.js.map +1 -0
  75. package/dist/chunk-MFVCSNIY.cjs +308 -0
  76. package/dist/chunk-MFVCSNIY.cjs.map +1 -0
  77. package/dist/chunk-MNO33ASC.cjs +240 -0
  78. package/dist/chunk-MNO33ASC.cjs.map +1 -0
  79. package/dist/chunk-N4AOJ3VF.cjs +154 -0
  80. package/dist/chunk-N4AOJ3VF.cjs.map +1 -0
  81. package/dist/chunk-P5CNM325.cjs +508 -0
  82. package/dist/chunk-P5CNM325.cjs.map +1 -0
  83. package/dist/chunk-RYT4H46I.js +646 -0
  84. package/dist/chunk-RYT4H46I.js.map +1 -0
  85. package/dist/chunk-SV5H3XM5.cjs +321 -0
  86. package/dist/chunk-SV5H3XM5.cjs.map +1 -0
  87. package/dist/chunk-TXHKFLWX.cjs +344 -0
  88. package/dist/chunk-TXHKFLWX.cjs.map +1 -0
  89. package/dist/chunk-UJAGXJDG.cjs +170 -0
  90. package/dist/chunk-UJAGXJDG.cjs.map +1 -0
  91. package/dist/chunk-VXRVGFCI.js +1128 -0
  92. package/dist/chunk-VXRVGFCI.js.map +1 -0
  93. package/dist/chunk-YM5AL65Y.cjs +357 -0
  94. package/dist/chunk-YM5AL65Y.cjs.map +1 -0
  95. package/dist/index.cjs +8334 -0
  96. package/dist/index.cjs.map +1 -0
  97. package/dist/index.d.cts +1365 -0
  98. package/dist/index.d.ts +1365 -0
  99. package/dist/index.js +8105 -0
  100. package/dist/index.js.map +1 -0
  101. package/dist/indexes/index.cjs +67 -0
  102. package/dist/indexes/index.cjs.map +1 -0
  103. package/dist/indexes/index.d.cts +62 -0
  104. package/dist/indexes/index.d.ts +62 -0
  105. package/dist/indexes/index.js +6 -0
  106. package/dist/indexes/index.js.map +1 -0
  107. package/dist/interchange/index.cjs +612 -0
  108. package/dist/interchange/index.cjs.map +1 -0
  109. package/dist/interchange/index.d.cts +288 -0
  110. package/dist/interchange/index.d.ts +288 -0
  111. package/dist/interchange/index.js +598 -0
  112. package/dist/interchange/index.js.map +1 -0
  113. package/dist/profiler/index.cjs +793 -0
  114. package/dist/profiler/index.cjs.map +1 -0
  115. package/dist/profiler/index.d.cts +283 -0
  116. package/dist/profiler/index.d.ts +283 -0
  117. package/dist/profiler/index.js +785 -0
  118. package/dist/profiler/index.js.map +1 -0
  119. package/dist/store-60Lcfi0w.d.ts +2263 -0
  120. package/dist/store-Bifii8MZ.d.cts +2263 -0
  121. package/dist/test-helpers-BjyRYJZX.d.ts +22 -0
  122. package/dist/test-helpers-NoQXhleQ.d.cts +22 -0
  123. package/dist/types-BRzHlhKC.d.cts +14 -0
  124. package/dist/types-BRzHlhKC.d.ts +14 -0
  125. package/dist/types-BrSfFSpW.d.cts +158 -0
  126. package/dist/types-CX4cLd7M.d.ts +152 -0
  127. package/dist/types-CjZ7g_7v.d.ts +442 -0
  128. package/dist/types-DDOSfrih.d.cts +442 -0
  129. package/dist/types-D_3mEv2y.d.ts +158 -0
  130. package/dist/types-a5rAxC92.d.cts +152 -0
  131. package/package.json +201 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Nicia AI, Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,47 @@
1
+ # @nicia-ai/typegraph
2
+
3
+ Type-driven embedded knowledge graph for TypeScript.
4
+
5
+ - Docs: [typegraph.dev](https://typegraph.dev)
6
+ - Repo: [github.com/nicia-ai/typegraph](https://github.com/nicia-ai/typegraph)
7
+
8
+ ## Installation
9
+
10
+ ```bash
11
+ npm install @nicia-ai/typegraph zod drizzle-orm better-sqlite3
12
+ ```
13
+
14
+ ## Quick Start
15
+
16
+ ```ts
17
+ import { z } from "zod";
18
+ import Database from "better-sqlite3";
19
+ import { drizzle } from "drizzle-orm/better-sqlite3";
20
+
21
+ import { createStore, defineEdge, defineGraph, defineNode } from "@nicia-ai/typegraph";
22
+ import { createSqliteBackend, getSqliteMigrationSQL } from "@nicia-ai/typegraph/sqlite";
23
+
24
+ const Person = defineNode("Person", { schema: z.object({ name: z.string() }) });
25
+ const knows = defineEdge("knows");
26
+
27
+ const graph = defineGraph({
28
+ id: "social",
29
+ nodes: { Person: { type: Person } },
30
+ edges: { knows: { type: knows, from: [Person], to: [Person] } },
31
+ });
32
+
33
+ const sqlite = new Database(":memory:");
34
+ const db = drizzle(sqlite);
35
+ sqlite.exec(getSqliteMigrationSQL());
36
+
37
+ const backend = createSqliteBackend(db);
38
+ const store = createStore(graph, backend);
39
+
40
+ const alice = await store.nodes.Person.create({ name: "Alice" });
41
+ const bob = await store.nodes.Person.create({ name: "Bob" });
42
+ await store.edges.knows.create(alice, bob);
43
+ ```
44
+
45
+ See the repo README for more.
46
+
47
+ Examples: [github.com/nicia-ai/typegraph/tree/main/packages/typegraph/examples](https://github.com/nicia-ai/typegraph/tree/main/packages/typegraph/examples)
@@ -0,0 +1,564 @@
1
+ import { z } from 'zod';
2
+
3
+ /** Brand key for NodeType */
4
+ declare const NODE_TYPE_BRAND: "__nodeType";
5
+ /** Brand key for EdgeType */
6
+ declare const EDGE_TYPE_BRAND: "__edgeType";
7
+ /** Brand symbol for NodeId */
8
+ declare const __nodeId: unique symbol;
9
+ /**
10
+ * A node type definition.
11
+ *
12
+ * Created via `defineNode()`. Represents a type of node in the graph
13
+ * with an associated Zod schema for properties.
14
+ */
15
+ type NodeType<K extends string = string, S extends z.ZodObject<z.ZodRawShape> = z.ZodObject<z.ZodRawShape>> = Readonly<{
16
+ [NODE_TYPE_BRAND]: true;
17
+ name: K;
18
+ schema: S;
19
+ description: string | undefined;
20
+ }>;
21
+ /**
22
+ * Branded node ID type.
23
+ *
24
+ * Prevents mixing IDs from different node types at compile time.
25
+ */
26
+ type NodeId<N extends NodeType> = string & Readonly<{
27
+ [__nodeId]: N;
28
+ }>;
29
+ /**
30
+ * Infer the props type from a NodeType.
31
+ */
32
+ type NodeProps<N extends NodeType> = z.infer<N["schema"]>;
33
+ /**
34
+ * An edge type definition.
35
+ *
36
+ * Created via `defineEdge()`. Represents a type of edge in the graph
37
+ * with an optional Zod schema for properties.
38
+ *
39
+ * Optionally includes `from` and `to` arrays that define the allowed
40
+ * source and target node types (domain and range constraints).
41
+ */
42
+ type EdgeType<K extends string = string, S extends z.ZodObject<z.ZodRawShape> = z.ZodObject<z.ZodRawShape>, From extends readonly NodeType[] | undefined = undefined, To extends readonly NodeType[] | undefined = undefined> = Readonly<{
43
+ [EDGE_TYPE_BRAND]: true;
44
+ name: K;
45
+ schema: S;
46
+ description: string | undefined;
47
+ from: From;
48
+ to: To;
49
+ }>;
50
+ /**
51
+ * Base edge type for use in constraints - accepts any from/to configuration.
52
+ */
53
+ type AnyEdgeType = EdgeType<string, z.ZodObject<z.ZodRawShape>, readonly NodeType[] | undefined, readonly NodeType[] | undefined>;
54
+ /**
55
+ * An edge type that has both from and to constraints defined.
56
+ * Can be used directly in defineGraph without an EdgeRegistration wrapper.
57
+ */
58
+ type EdgeTypeWithEndpoints = EdgeType<string, z.ZodObject<z.ZodRawShape>, readonly NodeType[], readonly NodeType[]>;
59
+ /**
60
+ * Infer the props type from an EdgeType.
61
+ */
62
+ type EdgeProps<E extends AnyEdgeType> = z.infer<E["schema"]>;
63
+ /**
64
+ * Delete behaviors for nodes.
65
+ */
66
+ type DeleteBehavior = "restrict" | "cascade" | "disconnect";
67
+ /**
68
+ * Edge cardinality constraints.
69
+ */
70
+ type Cardinality = "many" | "one" | "unique" | "oneActive";
71
+ /**
72
+ * Endpoint existence modes for edge validation.
73
+ */
74
+ type EndpointExistence = "notDeleted" | "currentlyValid" | "ever";
75
+ /**
76
+ * Temporal query modes.
77
+ */
78
+ type TemporalMode = "current" | "asOf" | "includeEnded" | "includeTombstones";
79
+ /**
80
+ * Uniqueness constraint scope.
81
+ */
82
+ type UniquenessScope = "kind" | "kindWithSubClasses";
83
+ /**
84
+ * Collation for uniqueness constraints.
85
+ */
86
+ type Collation = "binary" | "caseInsensitive";
87
+ /**
88
+ * Uniqueness constraint definition.
89
+ */
90
+ type UniqueConstraint<S extends z.ZodObject<z.ZodRawShape> = z.ZodObject<z.ZodRawShape>> = Readonly<{
91
+ name: string;
92
+ fields: readonly (keyof z.infer<S> & string)[];
93
+ where?: (props: UniqueConstraintPredicateBuilder<S>) => UniqueConstraintPredicate;
94
+ scope: UniquenessScope;
95
+ collation: Collation;
96
+ }>;
97
+ /**
98
+ * Predicate builder for uniqueness constraint where clause.
99
+ * Uses -? to make all fields required in the builder, even if optional in the schema.
100
+ */
101
+ type UniqueConstraintPredicateBuilder<S extends z.ZodObject<z.ZodRawShape>> = Readonly<{
102
+ [K in keyof z.infer<S>]-?: UniqueConstraintField;
103
+ }>;
104
+ /**
105
+ * Field operations for uniqueness constraint predicates.
106
+ */
107
+ type UniqueConstraintField = Readonly<{
108
+ isNull: () => UniqueConstraintPredicate;
109
+ isNotNull: () => UniqueConstraintPredicate;
110
+ }>;
111
+ /**
112
+ * A uniqueness constraint predicate (internal representation).
113
+ */
114
+ type UniqueConstraintPredicate = Readonly<{
115
+ __type: "unique_predicate";
116
+ field: string;
117
+ op: "isNull" | "isNotNull";
118
+ }>;
119
+ /**
120
+ * Node registration in a graph definition.
121
+ */
122
+ type NodeRegistration<N extends NodeType = NodeType> = Readonly<{
123
+ type: N;
124
+ unique?: readonly UniqueConstraint<N["schema"]>[];
125
+ onDelete?: DeleteBehavior;
126
+ }>;
127
+ /**
128
+ * Edge registration in a graph definition.
129
+ */
130
+ type EdgeRegistration<E extends AnyEdgeType = AnyEdgeType, FromTypes extends NodeType = NodeType, ToTypes extends NodeType = NodeType> = Readonly<{
131
+ type: E;
132
+ from: readonly FromTypes[];
133
+ to: readonly ToTypes[];
134
+ cardinality?: Cardinality;
135
+ endpointExistence?: EndpointExistence;
136
+ }>;
137
+ /**
138
+ * Default settings for a graph.
139
+ */
140
+ type GraphDefaults = Readonly<{
141
+ onNodeDelete?: DeleteBehavior;
142
+ temporalMode?: TemporalMode;
143
+ }>;
144
+ /**
145
+ * Checks if a value is a NodeType.
146
+ */
147
+ declare function isNodeType(value: unknown): value is NodeType;
148
+ /**
149
+ * Checks if a value is an EdgeType.
150
+ */
151
+ declare function isEdgeType(value: unknown): value is AnyEdgeType;
152
+ /**
153
+ * Checks if a value is an EdgeType with both from and to constraints defined.
154
+ * Such edges can be used directly in defineGraph without an EdgeRegistration wrapper.
155
+ */
156
+ declare function isEdgeTypeWithEndpoints(value: unknown): value is EdgeTypeWithEndpoints;
157
+
158
+ declare const MAX_JSON_POINTER_DEPTH: 5;
159
+ type JsonPointer = string & {
160
+ readonly __jsonPointer: unique symbol;
161
+ };
162
+ type JsonPointerSegment = string | number;
163
+ type JsonPointerSegments = readonly JsonPointerSegment[];
164
+ type Depth = 0 | 1 | 2 | 3 | 4 | 5;
165
+ interface DepthDecrementMap {
166
+ 0: 0;
167
+ 1: 0;
168
+ 2: 1;
169
+ 3: 2;
170
+ 4: 3;
171
+ 5: 4;
172
+ }
173
+ type Decrement<Current extends Depth> = DepthDecrementMap[Current];
174
+ type NonNegativeIntegerString = Exclude<`${bigint}`, `-${string}`>;
175
+ type ObjectPointerKey<T> = Exclude<Extract<keyof T, string>, NonNegativeIntegerString>;
176
+ type EncodeTilde<S extends string> = S extends `${infer Head}~${infer Tail}` ? `${EncodeTilde<Head>}~0${EncodeTilde<Tail>}` : S;
177
+ type EncodeSlash<S extends string> = S extends `${infer Head}/${infer Tail}` ? `${EncodeSlash<Head>}~1${EncodeSlash<Tail>}` : S;
178
+ type EncodePointerSegment<S extends string> = EncodeSlash<EncodeTilde<S>>;
179
+ type DecodePointerSegment<S extends string> = S extends `${infer Head}~1${infer Tail}` ? `${DecodePointerSegment<Head>}/${DecodePointerSegment<Tail>}` : S extends `${infer Head}~0${infer Tail}` ? `${DecodePointerSegment<Head>}~${DecodePointerSegment<Tail>}` : S;
180
+ type PointerForArray<T, Current extends Depth> = `/${NonNegativeIntegerString}` | (Current extends 1 ? never : `/${NonNegativeIntegerString}${JsonPointerFor<T, Decrement<Current>>}`);
181
+ type PointerForObject<T, Current extends Depth> = {
182
+ [K in ObjectPointerKey<T>]: `/${EncodePointerSegment<K>}` | (Current extends 1 ? never : `/${EncodePointerSegment<K>}${JsonPointerFor<T[K], Decrement<Current>>}`);
183
+ }[ObjectPointerKey<T>];
184
+ type JsonPointerFor<T, Current extends Depth = 5> = "" | (Current extends 0 ? "" : T extends readonly (infer U)[] ? PointerForArray<U, Current> : never) | (Current extends 0 ? "" : T extends Record<string, unknown> ? PointerForObject<T, Current> : never);
185
+ type PointerSegmentsForArray<T, Current extends Depth> = readonly [number] | (Current extends 1 ? readonly [number] : readonly [number, ...JsonPointerSegmentsFor<T, Decrement<Current>>]);
186
+ type PointerSegmentsForObject<T, Current extends Depth> = {
187
+ [K in ObjectPointerKey<T>]: readonly [K] | (Current extends 1 ? readonly [K] : readonly [K, ...JsonPointerSegmentsFor<T[K], Decrement<Current>>]);
188
+ }[ObjectPointerKey<T>];
189
+ type JsonPointerSegmentsFor<T, Current extends Depth = 5> = readonly [] | (Current extends 0 ? readonly [] : T extends readonly (infer U)[] ? PointerSegmentsForArray<U, Current> : never) | (Current extends 0 ? readonly [] : T extends Record<string, unknown> ? PointerSegmentsForObject<T, Current> : never);
190
+ type JsonPointerInput<T> = JsonPointerFor<T> | JsonPointerSegmentsFor<T> | JsonPointer;
191
+ type ResolveJsonPointer<T, Pointer extends string> = Pointer extends "" ? T : Pointer extends `/${infer Head}/${infer Tail}` ? ResolveJsonPointer<ResolvePointerSegment<T, DecodePointerSegment<Head>>, `/${Tail}`> : Pointer extends `/${infer Head}` ? ResolvePointerSegment<T, DecodePointerSegment<Head>> : unknown;
192
+ type ResolvePointerSegment<T, Segment extends string> = T extends readonly (infer U)[] ? Segment extends NonNegativeIntegerString ? U : unknown : T extends Record<string, unknown> ? Segment extends keyof T ? Segment extends NonNegativeIntegerString ? unknown : T[Segment] : unknown : unknown;
193
+ type ResolveJsonPointerSegments<T, Segments extends readonly JsonPointerSegment[]> = Segments extends readonly [] ? T : Segments extends readonly [infer Head, ...infer Tail] ? ResolveJsonPointerSegments<ResolvePointerSegment<T, SegmentToString<Head>>, Extract<Tail, readonly JsonPointerSegment[]>> : unknown;
194
+ type SegmentToString<Segment> = Segment extends number ? `${Segment}` : Segment extends string ? Segment : string;
195
+ declare function jsonPointer(segments: JsonPointerSegments): JsonPointer;
196
+ declare function normalizeJsonPointer<T>(input: JsonPointerInput<T>): JsonPointer;
197
+ declare function parseJsonPointer(pointer: JsonPointer): readonly string[];
198
+ declare function joinJsonPointers(base: JsonPointer | undefined, relative: JsonPointer): JsonPointer;
199
+
200
+ /**
201
+ * Query AST types.
202
+ *
203
+ * Defines the abstract syntax tree for TypeGraph queries.
204
+ * This portable representation can be compiled to SQL (today)
205
+ * or other query languages (Cypher, SPARQL) in the future.
206
+ */
207
+
208
+ /**
209
+ * A field reference in a predicate.
210
+ */
211
+ type FieldRef = Readonly<{
212
+ __type: "field_ref";
213
+ alias: string;
214
+ path: readonly string[];
215
+ jsonPointer?: JsonPointer | undefined;
216
+ valueType?: ValueType | undefined;
217
+ elementType?: ValueType | undefined;
218
+ }>;
219
+ /**
220
+ * A literal value in a predicate.
221
+ */
222
+ type LiteralValue = Readonly<{
223
+ __type: "literal";
224
+ value: string | number | boolean;
225
+ valueType?: ValueType | undefined;
226
+ }>;
227
+ /**
228
+ * Supported value types for predicates.
229
+ */
230
+ type ValueType = "string" | "number" | "boolean" | "date" | "array" | "object" | "embedding" | "unknown";
231
+ /**
232
+ * Comparison operators.
233
+ */
234
+ type ComparisonOp = "eq" | "neq" | "gt" | "gte" | "lt" | "lte" | "in" | "notIn";
235
+ /**
236
+ * String operators.
237
+ */
238
+ type StringOp = "contains" | "startsWith" | "endsWith" | "like" | "ilike";
239
+ /**
240
+ * A comparison predicate.
241
+ */
242
+ type ComparisonPredicate = Readonly<{
243
+ __type: "comparison";
244
+ op: ComparisonOp;
245
+ left: FieldRef;
246
+ right: LiteralValue | LiteralValue[];
247
+ }>;
248
+ /**
249
+ * A string predicate.
250
+ */
251
+ type StringPredicate = Readonly<{
252
+ __type: "string_op";
253
+ op: StringOp;
254
+ field: FieldRef;
255
+ pattern: string;
256
+ }>;
257
+ /**
258
+ * A null check predicate.
259
+ */
260
+ type NullPredicate = Readonly<{
261
+ __type: "null_check";
262
+ op: "isNull" | "isNotNull";
263
+ field: FieldRef;
264
+ }>;
265
+ /**
266
+ * A between predicate.
267
+ */
268
+ type BetweenPredicate = Readonly<{
269
+ __type: "between";
270
+ field: FieldRef;
271
+ lower: LiteralValue;
272
+ upper: LiteralValue;
273
+ }>;
274
+ /**
275
+ * Array operators.
276
+ */
277
+ type ArrayOp = "contains" | "containsAll" | "containsAny" | "isEmpty" | "isNotEmpty" | "lengthEq" | "lengthGt" | "lengthGte" | "lengthLt" | "lengthLte";
278
+ /**
279
+ * An array predicate.
280
+ */
281
+ type ArrayPredicate = Readonly<{
282
+ __type: "array_op";
283
+ op: ArrayOp;
284
+ field: FieldRef;
285
+ values?: readonly LiteralValue[];
286
+ length?: number;
287
+ }>;
288
+ /**
289
+ * Object operators.
290
+ */
291
+ type ObjectOp = "hasKey" | "hasPath" | "pathEquals" | "pathContains" | "pathIsNull" | "pathIsNotNull";
292
+ /**
293
+ * An object/JSON predicate.
294
+ */
295
+ type ObjectPredicate = Readonly<{
296
+ __type: "object_op";
297
+ op: ObjectOp;
298
+ field: FieldRef;
299
+ pointer: JsonPointer;
300
+ value?: LiteralValue;
301
+ valueType?: ValueType;
302
+ elementType?: ValueType;
303
+ }>;
304
+ /**
305
+ * Logical AND predicate.
306
+ */
307
+ type AndPredicate = Readonly<{
308
+ __type: "and";
309
+ predicates: readonly PredicateExpression[];
310
+ }>;
311
+ /**
312
+ * Logical OR predicate.
313
+ */
314
+ type OrPredicate = Readonly<{
315
+ __type: "or";
316
+ predicates: readonly PredicateExpression[];
317
+ }>;
318
+ /**
319
+ * Logical NOT predicate.
320
+ */
321
+ type NotPredicate = Readonly<{
322
+ __type: "not";
323
+ predicate: PredicateExpression;
324
+ }>;
325
+ /**
326
+ * An aggregate comparison predicate (for HAVING clauses).
327
+ */
328
+ type AggregateComparisonPredicate = Readonly<{
329
+ __type: "aggregate_comparison";
330
+ op: ComparisonOp;
331
+ aggregate: AggregateExpr;
332
+ value: LiteralValue;
333
+ }>;
334
+ /**
335
+ * An EXISTS subquery predicate.
336
+ * Tests whether the subquery returns any rows.
337
+ */
338
+ type ExistsSubquery = Readonly<{
339
+ __type: "exists";
340
+ subquery: QueryAst;
341
+ negated: boolean;
342
+ }>;
343
+ /**
344
+ * An IN subquery predicate.
345
+ * Tests whether a field value is in the subquery results.
346
+ */
347
+ type InSubquery = Readonly<{
348
+ __type: "in_subquery";
349
+ field: FieldRef;
350
+ subquery: QueryAst;
351
+ negated: boolean;
352
+ }>;
353
+ /**
354
+ * Vector similarity metric types.
355
+ */
356
+ type VectorMetricType = "cosine" | "l2" | "inner_product";
357
+ /**
358
+ * A vector similarity predicate.
359
+ * Finds nodes with embeddings similar to the query embedding.
360
+ *
361
+ * This predicate affects query execution by:
362
+ * - Joining with the embeddings table
363
+ * - Adding ORDER BY distance (ascending)
364
+ * - Applying LIMIT (top k results)
365
+ * - Optionally filtering by minimum score
366
+ */
367
+ type VectorSimilarityPredicate = Readonly<{
368
+ __type: "vector_similarity";
369
+ /** The embedding field reference */
370
+ field: FieldRef;
371
+ /** The query embedding to compare against */
372
+ queryEmbedding: readonly number[];
373
+ /** Similarity metric to use */
374
+ metric: VectorMetricType;
375
+ /** Maximum number of results to return */
376
+ limit: number;
377
+ /** Optional minimum similarity score (0-1 for cosine) */
378
+ minScore?: number;
379
+ }>;
380
+ /**
381
+ * All predicate expression types.
382
+ */
383
+ type PredicateExpression = ComparisonPredicate | StringPredicate | NullPredicate | BetweenPredicate | ArrayPredicate | ObjectPredicate | AndPredicate | OrPredicate | NotPredicate | AggregateComparisonPredicate | ExistsSubquery | InSubquery | VectorSimilarityPredicate;
384
+ /**
385
+ * The starting point of a query (the FROM clause).
386
+ */
387
+ type QueryStart = Readonly<{
388
+ alias: string;
389
+ kinds: readonly string[];
390
+ includeSubClasses: boolean;
391
+ }>;
392
+ /**
393
+ * Direction of edge traversal.
394
+ */
395
+ type TraversalDirection = "out" | "in";
396
+ /**
397
+ * Variable-length traversal specification for recursive graph traversals.
398
+ */
399
+ type VariableLengthSpec = Readonly<{
400
+ /** Minimum number of hops before including results (default: 1) */
401
+ minDepth: number;
402
+ /** Maximum number of hops (-1 = unlimited, default: -1) */
403
+ maxDepth: number;
404
+ /** Include the traversal path as an array in results */
405
+ collectPath: boolean;
406
+ /** Column alias for path array (default: "{nodeAlias}_path") */
407
+ pathAlias?: string;
408
+ /** Column alias for depth (default: "{nodeAlias}_depth") */
409
+ depthAlias?: string;
410
+ }>;
411
+ /**
412
+ * A traversal step in the query.
413
+ */
414
+ type Traversal = Readonly<{
415
+ edgeAlias: string;
416
+ edgeKinds: readonly string[];
417
+ direction: TraversalDirection;
418
+ nodeAlias: string;
419
+ nodeKinds: readonly string[];
420
+ joinFromAlias: string;
421
+ joinEdgeField: "from_id" | "to_id";
422
+ /** If true, use LEFT JOIN instead of INNER JOIN (optional match) */
423
+ optional: boolean;
424
+ /** Variable-length traversal configuration (for recursive CTEs) */
425
+ variableLength?: VariableLengthSpec;
426
+ }>;
427
+ /**
428
+ * Supported aggregate functions.
429
+ */
430
+ type AggregateFunction = "count" | "countDistinct" | "sum" | "avg" | "min" | "max";
431
+ /**
432
+ * An aggregate expression.
433
+ */
434
+ type AggregateExpr = Readonly<{
435
+ __type: "aggregate";
436
+ function: AggregateFunction;
437
+ field: FieldRef;
438
+ }>;
439
+ /**
440
+ * A GROUP BY specification.
441
+ */
442
+ type GroupBySpec = Readonly<{
443
+ fields: readonly FieldRef[];
444
+ }>;
445
+ /**
446
+ * A projected field in the SELECT clause.
447
+ * Can be either a direct field reference or an aggregate expression.
448
+ */
449
+ type ProjectedField = Readonly<{
450
+ outputName: string;
451
+ source: FieldRef | AggregateExpr;
452
+ /** Override the CTE alias for this field (used for edge fields in node CTEs) */
453
+ cteAlias?: string;
454
+ }>;
455
+ /**
456
+ * The projection (SELECT) clause.
457
+ */
458
+ type Projection = Readonly<{
459
+ fields: readonly ProjectedField[];
460
+ }>;
461
+ /**
462
+ * A selectively projected field for optimized queries.
463
+ *
464
+ * Used when the select callback only accesses specific fields,
465
+ * allowing the compiler to generate optimized SQL that fetches
466
+ * only those fields instead of the full props blob.
467
+ */
468
+ type SelectiveField = Readonly<{
469
+ /** The alias (node or edge) this field belongs to */
470
+ alias: string;
471
+ /** The field name (e.g., "email", "name", "id") */
472
+ field: string;
473
+ /** The output column name in the result (e.g., "p_email") */
474
+ outputName: string;
475
+ /** True if this is a system field (id, kind, etc.), false for props */
476
+ isSystemField: boolean;
477
+ /**
478
+ * Optional value type for props fields.
479
+ *
480
+ * When present, the compiler can use type-aware JSON extraction
481
+ * (e.g. numeric/date casts) to better match predicate compilation
482
+ * and enable expression index coverage.
483
+ */
484
+ valueType?: ValueType | undefined;
485
+ }>;
486
+ /**
487
+ * Null ordering preference.
488
+ */
489
+ type NullOrdering = "first" | "last";
490
+ /**
491
+ * Sort direction.
492
+ */
493
+ type SortDirection = "asc" | "desc";
494
+ /**
495
+ * An ordering specification.
496
+ */
497
+ type OrderSpec = Readonly<{
498
+ field: FieldRef;
499
+ direction: SortDirection;
500
+ nulls?: NullOrdering;
501
+ }>;
502
+ /**
503
+ * A predicate applied to a specific node or edge alias.
504
+ */
505
+ type NodePredicate = Readonly<{
506
+ targetAlias: string;
507
+ /** Whether this predicate targets a node or edge. Defaults to "node". */
508
+ targetType?: "node" | "edge";
509
+ expression: PredicateExpression;
510
+ }>;
511
+ /**
512
+ * Temporal query options.
513
+ */
514
+ type TemporalOptions = Readonly<{
515
+ mode: TemporalMode;
516
+ asOf?: string;
517
+ }>;
518
+ /**
519
+ * The complete query AST.
520
+ */
521
+ type QueryAst = Readonly<{
522
+ /** The graph ID this query is for (used for subqueries) */
523
+ graphId?: string;
524
+ start: QueryStart;
525
+ traversals: readonly Traversal[];
526
+ predicates: readonly NodePredicate[];
527
+ projection: Projection;
528
+ temporalMode: TemporalOptions;
529
+ orderBy?: readonly OrderSpec[];
530
+ limit?: number;
531
+ offset?: number;
532
+ /** GROUP BY specification for aggregate queries */
533
+ groupBy?: GroupBySpec;
534
+ /** HAVING clause - predicates applied after GROUP BY */
535
+ having?: PredicateExpression;
536
+ /**
537
+ * Selective fields for optimized queries.
538
+ * When present, the compiler generates SQL that only fetches these specific
539
+ * fields instead of the full props blob, enabling covered index usage.
540
+ */
541
+ selectiveFields?: readonly SelectiveField[];
542
+ }>;
543
+ /**
544
+ * Set operation types for combining queries.
545
+ */
546
+ type SetOperationType = "union" | "unionAll" | "intersect" | "except";
547
+ /**
548
+ * A set operation combining two queries.
549
+ */
550
+ type SetOperation = Readonly<{
551
+ __type: "set_operation";
552
+ operator: SetOperationType;
553
+ left: ComposableQuery;
554
+ right: ComposableQuery;
555
+ orderBy?: readonly OrderSpec[];
556
+ limit?: number;
557
+ offset?: number;
558
+ }>;
559
+ /**
560
+ * A composable query - either a base query or a set operation.
561
+ */
562
+ type ComposableQuery = QueryAst | SetOperation;
563
+
564
+ export { type AnyEdgeType as A, type Traversal as B, type ComparisonOp as C, type DeleteBehavior as D, type EdgeType as E, type FieldRef as F, type GraphDefaults as G, type NodePredicate as H, type ProjectedField as I, type JsonPointer as J, type GroupBySpec as K, type TraversalDirection as L, MAX_JSON_POINTER_DEPTH as M, type NodeType as N, type OrderSpec as O, type PredicateExpression as P, type QueryAst as Q, type ResolveJsonPointer as R, type SortDirection as S, type TemporalMode as T, type UniqueConstraint as U, type ValueType as V, type ComposableQuery as W, type SetOperationType as X, type SetOperation as Y, type JsonPointerFor as a, type JsonPointerSegmentsFor as b, type AggregateExpr as c, type AggregateComparisonPredicate as d, type Cardinality as e, type Collation as f, type EdgeProps as g, type EdgeRegistration as h, type EdgeTypeWithEndpoints as i, type EndpointExistence as j, type JsonPointerInput as k, type JsonPointerSegment as l, type JsonPointerSegments as m, type NodeId as n, type NodeProps as o, type NodeRegistration as p, type ResolveJsonPointerSegments as q, type UniquenessScope as r, isEdgeType as s, isEdgeTypeWithEndpoints as t, isNodeType as u, joinJsonPointers as v, jsonPointer as w, normalizeJsonPointer as x, parseJsonPointer as y, type VectorMetricType as z };