@nicia-ai/typegraph 0.9.1 → 0.10.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.
package/dist/index.d.cts CHANGED
@@ -3,8 +3,8 @@ import { N as NodeType, E as EdgeType } from './types-DMzKq0d5.cjs';
3
3
  export { A as AnyEdgeType, C as Cardinality, a as Collation, D as DeleteBehavior, b as EdgeId, c as EdgeProps, d as EdgeRegistration, e as EdgeTypeWithEndpoints, f as EndpointExistence, G as GraphDefaults, g as NodeId, h as NodeProps, i as NodeRegistration, S as SqlDialect, T as TemporalMode, U as UniqueConstraint, j as UniquenessScope, k as isEdgeType, l as isEdgeTypeWithEndpoints, m as isNodeType } from './types-DMzKq0d5.cjs';
4
4
  import { I as InferenceType, M as MetaEdge, O as OntologyRelation } from './types-GLkwvQvS.cjs';
5
5
  export { D as DEFAULT_SQL_SCHEMA, G as GraphBackend, a as MetaEdgeProperties, S as SqlSchema, b as SqlTableNames, T as TransactionBackend, c as createSqlSchema, i as isMetaEdge } from './types-GLkwvQvS.cjs';
6
- import { A as AliasMap, E as EdgeAliasMap, Q as QueryBuilder, T as TraversalBuilder, C as CreateQueryBuilderOptions } from './store-DgzIgrmn.cjs';
7
- export { a as AggregateResult, b as ConstraintNames, c as CreateEdgeInput, d as CreateNodeInput, e as Edge, f as EdgeAccessor, g as EdgeCollection, h as EdgeFindByEndpointsOptions, i as EdgeGetOrCreateByEndpointsOptions, j as EdgeGetOrCreateByEndpointsResult, k as EmbeddingSchema, l as EmbeddingValue, m as ExecutableAggregateQuery, n as ExecutableQuery, F as FieldAccessor, G as GetOrCreateAction, H as HookContext, I as IfExistsMode, N as Node, o as NodeAccessor, p as NodeAlias, q as NodeCollection, r as NodeGetOrCreateByConstraintOptions, s as NodeGetOrCreateByConstraintResult, t as NodeRef, O as OperationHookContext, P as PaginateOptions, u as PaginatedResult, v as Predicate, w as PreparedQuery, x as PropsAccessor, y as QueryHookContext, z as QueryOptions, R as RecursiveTraversalOptions, S as SelectContext, B as SelectableEdge, D as SelectableNode, J as Store, K as StoreHooks, L as StoreOptions, M as StreamOptions, U as TransactionContext, V as TypedEdgeCollection, W as UnionableQuery, X as UpdateEdgeInput, Y as UpdateNodeInput, Z as createStore, _ as createStoreWithSchema, $ as embedding, a0 as exists, a1 as fieldRef, a2 as getEmbeddingDimensions, a3 as inSubquery, a4 as isEmbeddingSchema, a5 as isParameterRef, a6 as notExists, a7 as notInSubquery, a8 as param } from './store-DgzIgrmn.cjs';
6
+ import { A as AliasMap, E as EdgeAliasMap, Q as QueryBuilder, T as TraversalBuilder, C as CreateQueryBuilderOptions } from './store-NE18RGqV.cjs';
7
+ export { a as AggregateResult, b as AnyEdge, c as AnyNode, d as ConstraintNames, e as CreateEdgeInput, f as CreateNodeInput, g as Edge, h as EdgeAccessor, i as EdgeCollection, j as EdgeFindByEndpointsOptions, k as EdgeGetOrCreateByEndpointsOptions, l as EdgeGetOrCreateByEndpointsResult, m as EmbeddingSchema, n as EmbeddingValue, o as ExecutableAggregateQuery, p as ExecutableQuery, F as FieldAccessor, G as GetOrCreateAction, H as HookContext, I as IfExistsMode, N as Node, q as NodeAccessor, r as NodeAlias, s as NodeCollection, t as NodeGetOrCreateByConstraintOptions, u as NodeGetOrCreateByConstraintResult, v as NodeRef, O as OperationHookContext, P as PaginateOptions, w as PaginatedResult, x as Predicate, y as PreparedQuery, z as PropsAccessor, B as QueryHookContext, D as QueryOptions, R as RecursiveTraversalOptions, S as SelectContext, J as SelectableEdge, K as SelectableNode, L as Store, M as StoreHooks, U as StoreOptions, V as StreamOptions, W as SubgraphOptions, X as SubgraphResult, Y as SubsetEdge, Z as SubsetNode, _ as TransactionContext, $ as TypedEdgeCollection, a0 as UnionableQuery, a1 as UpdateEdgeInput, a2 as UpdateNodeInput, a3 as createStore, a4 as createStoreWithSchema, a5 as embedding, a6 as exists, a7 as fieldRef, a8 as getEmbeddingDimensions, a9 as inSubquery, aa as isEmbeddingSchema, ab as isParameterRef, ac as notExists, ad as notInSubquery, ae as param } from './store-NE18RGqV.cjs';
8
8
  import { G as GraphDef, K as KindRegistry } from './manager-DGSnJa1v.cjs';
9
9
  export { A as AllEdgeTypes, a as AllNodeTypes, E as EdgeKinds, b as GetEdgeType, c as GetNodeType, N as NodeKinds, d as defineGraph, g as getEdgeKinds, e as getNodeKinds, i as isGraphDef } from './manager-DGSnJa1v.cjs';
10
10
  export { C as CardinalityError, a as CompilerInvariantError, b as ConfigurationError, D as DatabaseOperationError, c as DisjointError, E as EdgeNotFoundError, d as EndpointError, e as EndpointNotFoundError, f as ErrorCategory, K as KindNotFoundError, M as MigrationError, N as NodeConstraintNotFoundError, g as NodeNotFoundError, R as RestrictedDeleteError, S as SchemaMismatchError, T as TypeGraphError, h as TypeGraphErrorOptions, U as UniquenessError, i as UnsupportedPredicateError, V as ValidationError, j as ValidationErrorDetails, k as ValidationIssue, l as VersionConflictError, m as getErrorSuggestion, n as isConstraintError, o as isSystemError, p as isTypeGraphError, q as isUserRecoverable } from './index-QTnQwakS.cjs';
package/dist/index.d.ts CHANGED
@@ -3,8 +3,8 @@ import { N as NodeType, E as EdgeType } from './types-DMzKq0d5.js';
3
3
  export { A as AnyEdgeType, C as Cardinality, a as Collation, D as DeleteBehavior, b as EdgeId, c as EdgeProps, d as EdgeRegistration, e as EdgeTypeWithEndpoints, f as EndpointExistence, G as GraphDefaults, g as NodeId, h as NodeProps, i as NodeRegistration, S as SqlDialect, T as TemporalMode, U as UniqueConstraint, j as UniquenessScope, k as isEdgeType, l as isEdgeTypeWithEndpoints, m as isNodeType } from './types-DMzKq0d5.js';
4
4
  import { I as InferenceType, M as MetaEdge, O as OntologyRelation } from './types-1YJKodRv.js';
5
5
  export { D as DEFAULT_SQL_SCHEMA, G as GraphBackend, a as MetaEdgeProperties, S as SqlSchema, b as SqlTableNames, T as TransactionBackend, c as createSqlSchema, i as isMetaEdge } from './types-1YJKodRv.js';
6
- import { A as AliasMap, E as EdgeAliasMap, Q as QueryBuilder, T as TraversalBuilder, C as CreateQueryBuilderOptions } from './store-wqOO3GSy.js';
7
- export { a as AggregateResult, b as ConstraintNames, c as CreateEdgeInput, d as CreateNodeInput, e as Edge, f as EdgeAccessor, g as EdgeCollection, h as EdgeFindByEndpointsOptions, i as EdgeGetOrCreateByEndpointsOptions, j as EdgeGetOrCreateByEndpointsResult, k as EmbeddingSchema, l as EmbeddingValue, m as ExecutableAggregateQuery, n as ExecutableQuery, F as FieldAccessor, G as GetOrCreateAction, H as HookContext, I as IfExistsMode, N as Node, o as NodeAccessor, p as NodeAlias, q as NodeCollection, r as NodeGetOrCreateByConstraintOptions, s as NodeGetOrCreateByConstraintResult, t as NodeRef, O as OperationHookContext, P as PaginateOptions, u as PaginatedResult, v as Predicate, w as PreparedQuery, x as PropsAccessor, y as QueryHookContext, z as QueryOptions, R as RecursiveTraversalOptions, S as SelectContext, B as SelectableEdge, D as SelectableNode, J as Store, K as StoreHooks, L as StoreOptions, M as StreamOptions, U as TransactionContext, V as TypedEdgeCollection, W as UnionableQuery, X as UpdateEdgeInput, Y as UpdateNodeInput, Z as createStore, _ as createStoreWithSchema, $ as embedding, a0 as exists, a1 as fieldRef, a2 as getEmbeddingDimensions, a3 as inSubquery, a4 as isEmbeddingSchema, a5 as isParameterRef, a6 as notExists, a7 as notInSubquery, a8 as param } from './store-wqOO3GSy.js';
6
+ import { A as AliasMap, E as EdgeAliasMap, Q as QueryBuilder, T as TraversalBuilder, C as CreateQueryBuilderOptions } from './store-BcFe9jJe.js';
7
+ export { a as AggregateResult, b as AnyEdge, c as AnyNode, d as ConstraintNames, e as CreateEdgeInput, f as CreateNodeInput, g as Edge, h as EdgeAccessor, i as EdgeCollection, j as EdgeFindByEndpointsOptions, k as EdgeGetOrCreateByEndpointsOptions, l as EdgeGetOrCreateByEndpointsResult, m as EmbeddingSchema, n as EmbeddingValue, o as ExecutableAggregateQuery, p as ExecutableQuery, F as FieldAccessor, G as GetOrCreateAction, H as HookContext, I as IfExistsMode, N as Node, q as NodeAccessor, r as NodeAlias, s as NodeCollection, t as NodeGetOrCreateByConstraintOptions, u as NodeGetOrCreateByConstraintResult, v as NodeRef, O as OperationHookContext, P as PaginateOptions, w as PaginatedResult, x as Predicate, y as PreparedQuery, z as PropsAccessor, B as QueryHookContext, D as QueryOptions, R as RecursiveTraversalOptions, S as SelectContext, J as SelectableEdge, K as SelectableNode, L as Store, M as StoreHooks, U as StoreOptions, V as StreamOptions, W as SubgraphOptions, X as SubgraphResult, Y as SubsetEdge, Z as SubsetNode, _ as TransactionContext, $ as TypedEdgeCollection, a0 as UnionableQuery, a1 as UpdateEdgeInput, a2 as UpdateNodeInput, a3 as createStore, a4 as createStoreWithSchema, a5 as embedding, a6 as exists, a7 as fieldRef, a8 as getEmbeddingDimensions, a9 as inSubquery, aa as isEmbeddingSchema, ab as isParameterRef, ac as notExists, ad as notInSubquery, ae as param } from './store-BcFe9jJe.js';
8
8
  import { G as GraphDef, K as KindRegistry } from './manager-BCLhWysp.js';
9
9
  export { A as AllEdgeTypes, a as AllNodeTypes, E as EdgeKinds, b as GetEdgeType, c as GetNodeType, N as NodeKinds, d as defineGraph, g as getEdgeKinds, e as getNodeKinds, i as isGraphDef } from './manager-BCLhWysp.js';
10
10
  export { C as CardinalityError, a as CompilerInvariantError, b as ConfigurationError, D as DatabaseOperationError, c as DisjointError, E as EdgeNotFoundError, d as EndpointError, e as EndpointNotFoundError, f as ErrorCategory, K as KindNotFoundError, M as MigrationError, N as NodeConstraintNotFoundError, g as NodeNotFoundError, R as RestrictedDeleteError, S as SchemaMismatchError, T as TypeGraphError, h as TypeGraphErrorOptions, U as UniquenessError, i as UnsupportedPredicateError, V as ValidationError, j as ValidationErrorDetails, k as ValidationIssue, l as VersionConflictError, m as getErrorSuggestion, n as isConstraintError, o as isSystemError, p as isTypeGraphError, q as isUserRecoverable } from './index-QTnQwakS.js';
package/dist/index.js CHANGED
@@ -2524,14 +2524,8 @@ function compileAggregateExprFromSource(expr, dialect) {
2524
2524
  const { field: field2 } = expr;
2525
2525
  const fn = expr.function;
2526
2526
  switch (fn) {
2527
- case "count": {
2528
- const cteAlias = `cte_${field2.alias}`;
2529
- return sql`COUNT(${sql.raw(cteAlias)}.${sql.raw(field2.alias)}_id)`;
2530
- }
2531
- case "countDistinct": {
2532
- const cteAlias = `cte_${field2.alias}`;
2533
- return sql`COUNT(DISTINCT ${sql.raw(cteAlias)}.${sql.raw(field2.alias)}_id)`;
2534
- }
2527
+ case "count":
2528
+ case "countDistinct":
2535
2529
  case "sum":
2536
2530
  case "avg":
2537
2531
  case "min":
@@ -2543,6 +2537,9 @@ function compileAggregateExprFromSource(expr, dialect) {
2543
2537
  field2.valueType,
2544
2538
  cteAlias
2545
2539
  );
2540
+ if (fn === "countDistinct") {
2541
+ return sql`COUNT(DISTINCT ${column})`;
2542
+ }
2546
2543
  return sql`${sql.raw(fn.toUpperCase())}(${column})`;
2547
2544
  }
2548
2545
  default: {
@@ -3038,7 +3035,7 @@ function compileRecursiveCte(ast, traversal, graphId, ctx, requiredColumnsByAlia
3038
3035
  recursiveBaseWhereClauses.push(cycleCheck);
3039
3036
  }
3040
3037
  recursiveBaseWhereClauses.push(...edgePredicates, ...targetNodePredicates);
3041
- function compileRecursiveBranch(branch) {
3038
+ function compileRecursiveBranch2(branch) {
3042
3039
  const recursiveFilterClauses = [
3043
3040
  ...recursiveBaseWhereClauses,
3044
3041
  compileKindFilter2(branch.edgeKinds, "e.kind"),
@@ -3093,7 +3090,7 @@ function compileRecursiveCte(ast, traversal, graphId, ctx, requiredColumnsByAlia
3093
3090
  const directTargetField = direction === "out" ? "to_id" : "from_id";
3094
3091
  const directJoinKindField = direction === "out" ? "from_kind" : "to_kind";
3095
3092
  const directTargetKindField = direction === "out" ? "to_kind" : "from_kind";
3096
- const directBranch = compileRecursiveBranch({
3093
+ const directBranch = compileRecursiveBranch2({
3097
3094
  joinField: directJoinField,
3098
3095
  targetField: directTargetField,
3099
3096
  joinKindField: directJoinKindField,
@@ -3109,7 +3106,7 @@ function compileRecursiveCte(ast, traversal, graphId, ctx, requiredColumnsByAlia
3109
3106
  (kind) => directEdgeKinds.includes(kind)
3110
3107
  );
3111
3108
  const duplicateGuard = overlappingKinds.length > 0 ? sql`NOT (e.from_id = e.to_id AND ${compileKindFilter2(overlappingKinds, "e.kind")})` : void 0;
3112
- const inverseBranch = compileRecursiveBranch({
3109
+ const inverseBranch = compileRecursiveBranch2({
3113
3110
  joinField: inverseJoinField,
3114
3111
  targetField: inverseTargetField,
3115
3112
  joinKindField: inverseJoinKindField,
@@ -3652,19 +3649,17 @@ function compilePrefixedSelect(ast, prefix, dialect) {
3652
3649
  function compileFieldValueForSetOp(source, prefix, alias, dialect) {
3653
3650
  if ("__type" in source && source.__type === "aggregate") {
3654
3651
  const { field: field2, function: fn } = source;
3655
- const cteName = `cte_${prefix}_${field2.alias}`;
3656
3652
  switch (fn) {
3657
- case "count": {
3658
- return sql`COUNT(${sql.raw(cteName)}.${sql.raw(field2.alias)}_id)`;
3659
- }
3660
- case "countDistinct": {
3661
- return sql`COUNT(DISTINCT ${sql.raw(cteName)}.${sql.raw(field2.alias)}_id)`;
3662
- }
3653
+ case "count":
3654
+ case "countDistinct":
3663
3655
  case "sum":
3664
3656
  case "avg":
3665
3657
  case "min":
3666
3658
  case "max": {
3667
3659
  const column = compileFieldColumnForSetOp(field2, prefix, dialect);
3660
+ if (fn === "countDistinct") {
3661
+ return sql`COUNT(DISTINCT ${column})`;
3662
+ }
3668
3663
  return sql`${sql.raw(fn.toUpperCase())}(${column})`;
3669
3664
  }
3670
3665
  default: {
@@ -3878,9 +3873,7 @@ function collectRequiredColumnsByAlias2(ast) {
3878
3873
  markFieldRefAsRequired(requiredColumnsByAlias, source);
3879
3874
  } else {
3880
3875
  addRequiredColumn(requiredColumnsByAlias, source.field.alias, "id");
3881
- if (source.function !== "count" && source.function !== "countDistinct") {
3882
- markFieldRefAsRequired(requiredColumnsByAlias, source.field);
3883
- }
3876
+ markFieldRefAsRequired(requiredColumnsByAlias, source.field);
3884
3877
  }
3885
3878
  }
3886
3879
  }
@@ -11197,6 +11190,142 @@ async function executeNodeBulkGetOrCreateByConstraint(ctx, kind, constraintName,
11197
11190
  }
11198
11191
  return results;
11199
11192
  }
11193
+ var DEFAULT_SUBGRAPH_MAX_DEPTH = 10;
11194
+ function normalizeProps(value) {
11195
+ return typeof value === "string" ? value : JSON.stringify(value ?? {});
11196
+ }
11197
+ async function executeSubgraph(params) {
11198
+ const { options } = params;
11199
+ if (options.edges.length === 0) {
11200
+ return { nodes: [], edges: [] };
11201
+ }
11202
+ const maxDepth = Math.min(
11203
+ options.maxDepth ?? DEFAULT_SUBGRAPH_MAX_DEPTH,
11204
+ MAX_RECURSIVE_DEPTH
11205
+ );
11206
+ const ctx = {
11207
+ graphId: params.graphId,
11208
+ rootId: params.rootId,
11209
+ edgeKinds: options.edges,
11210
+ maxDepth,
11211
+ includeKinds: options.includeKinds,
11212
+ excludeRoot: options.excludeRoot ?? false,
11213
+ direction: options.direction ?? "out",
11214
+ cyclePolicy: options.cyclePolicy ?? "prevent",
11215
+ dialect: params.dialect,
11216
+ schema: params.schema ?? DEFAULT_SQL_SCHEMA,
11217
+ backend: params.backend
11218
+ };
11219
+ const reachableCte = buildReachableCte(ctx);
11220
+ const includedIdsCte = buildIncludedIdsCte(ctx);
11221
+ const [nodeRows, edgeRows] = await Promise.all([
11222
+ fetchSubgraphNodes(ctx, reachableCte, includedIdsCte),
11223
+ fetchSubgraphEdges(ctx, reachableCte, includedIdsCte)
11224
+ ]);
11225
+ const nodes = nodeRows.map(
11226
+ (row) => rowToNode({ ...row, props: normalizeProps(row.props) })
11227
+ );
11228
+ const edges = edgeRows.map(
11229
+ (row) => rowToEdge({ ...row, props: normalizeProps(row.props) })
11230
+ );
11231
+ return {
11232
+ nodes,
11233
+ edges
11234
+ };
11235
+ }
11236
+ function buildReachableCte(ctx) {
11237
+ const shouldTrackPath = ctx.cyclePolicy === "prevent";
11238
+ const edgeKindFilter = compileKindFilter(sql.raw("e.kind"), ctx.edgeKinds);
11239
+ const initialPath = shouldTrackPath ? ctx.dialect.initializePath(sql.raw("n.id")) : void 0;
11240
+ const pathExtension = shouldTrackPath ? ctx.dialect.extendPath(sql.raw("r.path"), sql.raw("n.id")) : void 0;
11241
+ const cycleCheck = shouldTrackPath ? ctx.dialect.cycleCheck(sql.raw("n.id"), sql.raw("r.path")) : void 0;
11242
+ const baseColumns = [sql`n.id`, sql`n.kind`, sql`0 AS depth`];
11243
+ if (initialPath !== void 0) {
11244
+ baseColumns.push(sql`${initialPath} AS path`);
11245
+ }
11246
+ const baseCase = sql`SELECT ${sql.join(baseColumns, sql`, `)} FROM ${ctx.schema.nodesTable} n WHERE n.graph_id = ${ctx.graphId} AND n.id = ${ctx.rootId} AND n.deleted_at IS NULL`;
11247
+ const recursiveColumns = [
11248
+ sql`n.id`,
11249
+ sql`n.kind`,
11250
+ sql`r.depth + 1 AS depth`
11251
+ ];
11252
+ if (pathExtension !== void 0) {
11253
+ recursiveColumns.push(sql`${pathExtension} AS path`);
11254
+ }
11255
+ const recursiveWhereClauses = [
11256
+ sql`e.graph_id = ${ctx.graphId}`,
11257
+ edgeKindFilter,
11258
+ sql`e.deleted_at IS NULL`,
11259
+ sql`n.deleted_at IS NULL`,
11260
+ sql`r.depth < ${ctx.maxDepth}`
11261
+ ];
11262
+ if (cycleCheck !== void 0) {
11263
+ recursiveWhereClauses.push(cycleCheck);
11264
+ }
11265
+ const forceWorktableOuterJoinOrder = ctx.dialect.capabilities.forceRecursiveWorktableOuterJoinOrder;
11266
+ const recursiveCase = ctx.direction === "both" ? compileBidirectionalBranch({
11267
+ recursiveColumns,
11268
+ whereClauses: recursiveWhereClauses,
11269
+ forceWorktableOuterJoinOrder,
11270
+ schema: ctx.schema
11271
+ }) : compileRecursiveBranch({
11272
+ recursiveColumns,
11273
+ whereClauses: recursiveWhereClauses,
11274
+ joinField: "from_id",
11275
+ targetField: "to_id",
11276
+ targetKindField: "to_kind",
11277
+ forceWorktableOuterJoinOrder,
11278
+ schema: ctx.schema
11279
+ });
11280
+ return sql`WITH RECURSIVE reachable AS (${baseCase} UNION ALL ${recursiveCase})`;
11281
+ }
11282
+ function compileRecursiveBranch(params) {
11283
+ const columns = [...params.recursiveColumns];
11284
+ const selectClause = sql`SELECT ${sql.join(columns, sql`, `)}`;
11285
+ const nodeJoin = sql`JOIN ${params.schema.nodesTable} n ON n.graph_id = e.graph_id AND n.id = e.${sql.raw(params.targetField)} AND n.kind = e.${sql.raw(params.targetKindField)}`;
11286
+ if (params.forceWorktableOuterJoinOrder) {
11287
+ const allWhere = [
11288
+ ...params.whereClauses,
11289
+ sql`e.${sql.raw(params.joinField)} = r.id`
11290
+ ];
11291
+ return sql`${selectClause} FROM reachable r CROSS JOIN ${params.schema.edgesTable} e ${nodeJoin} WHERE ${sql.join(allWhere, sql` AND `)}`;
11292
+ }
11293
+ const where = [...params.whereClauses];
11294
+ return sql`${selectClause} FROM reachable r JOIN ${params.schema.edgesTable} e ON e.${sql.raw(params.joinField)} = r.id ${nodeJoin} WHERE ${sql.join(where, sql` AND `)}`;
11295
+ }
11296
+ function compileBidirectionalBranch(params) {
11297
+ const columns = [...params.recursiveColumns];
11298
+ const selectClause = sql`SELECT ${sql.join(columns, sql`, `)}`;
11299
+ const nodeJoin = sql`JOIN ${params.schema.nodesTable} n ON n.graph_id = e.graph_id AND ((e.to_id = r.id AND n.id = e.from_id AND n.kind = e.from_kind) OR (e.from_id = r.id AND n.id = e.to_id AND n.kind = e.to_kind))`;
11300
+ if (params.forceWorktableOuterJoinOrder) {
11301
+ const allWhere = [
11302
+ ...params.whereClauses,
11303
+ sql`(e.from_id = r.id OR e.to_id = r.id)`
11304
+ ];
11305
+ return sql`${selectClause} FROM reachable r CROSS JOIN ${params.schema.edgesTable} e ${nodeJoin} WHERE ${sql.join(allWhere, sql` AND `)}`;
11306
+ }
11307
+ return sql`${selectClause} FROM reachable r JOIN ${params.schema.edgesTable} e ON (e.from_id = r.id OR e.to_id = r.id) ${nodeJoin} WHERE ${sql.join([...params.whereClauses], sql` AND `)}`;
11308
+ }
11309
+ function buildIncludedIdsCte(ctx) {
11310
+ const filters = [];
11311
+ if (ctx.includeKinds !== void 0 && ctx.includeKinds.length > 0) {
11312
+ filters.push(compileKindFilter(sql.raw("kind"), ctx.includeKinds));
11313
+ }
11314
+ if (ctx.excludeRoot) {
11315
+ filters.push(sql`id != ${ctx.rootId}`);
11316
+ }
11317
+ const whereClause = filters.length > 0 ? sql` WHERE ${sql.join(filters, sql` AND `)}` : sql``;
11318
+ return sql`, included_ids AS (SELECT DISTINCT id FROM reachable${whereClause})`;
11319
+ }
11320
+ async function fetchSubgraphNodes(ctx, reachableCte, includedIdsCte) {
11321
+ const query = sql`${reachableCte}${includedIdsCte} SELECT n.kind, n.id, n.props, n.version, n.valid_from, n.valid_to, n.created_at, n.updated_at, n.deleted_at FROM ${ctx.schema.nodesTable} n WHERE n.graph_id = ${ctx.graphId} AND n.id IN (SELECT id FROM included_ids)`;
11322
+ return ctx.backend.execute(query);
11323
+ }
11324
+ async function fetchSubgraphEdges(ctx, reachableCte, includedIdsCte) {
11325
+ const edgeKindFilter = compileKindFilter(sql.raw("e.kind"), ctx.edgeKinds);
11326
+ const query = sql`${reachableCte}${includedIdsCte} SELECT e.id, e.kind, e.from_kind, e.from_id, e.to_kind, e.to_id, e.props, e.valid_from, e.valid_to, e.created_at, e.updated_at, e.deleted_at FROM ${ctx.schema.edgesTable} e WHERE e.graph_id = ${ctx.graphId} AND ${edgeKindFilter} AND e.deleted_at IS NULL AND e.from_id IN (SELECT id FROM included_ids) AND e.to_id IN (SELECT id FROM included_ids)`;
11327
+ return ctx.backend.execute(query);
11328
+ }
11200
11329
 
11201
11330
  // src/store/store.ts
11202
11331
  var Store = class {
@@ -11400,6 +11529,39 @@ var Store = class {
11400
11529
  query() {
11401
11530
  return this.#createQueryForBackend(this.#backend);
11402
11531
  }
11532
+ // === Subgraph Extraction ===
11533
+ /**
11534
+ * Extracts a typed subgraph by traversing from a root node.
11535
+ *
11536
+ * Performs a BFS traversal from `rootId` following the specified edge kinds,
11537
+ * then returns all reachable nodes and the edges connecting them.
11538
+ *
11539
+ * @example
11540
+ * ```typescript
11541
+ * const result = await store.subgraph(run.id, {
11542
+ * edges: ["has_task", "runs_agent", "uses_skill"],
11543
+ * maxDepth: 4,
11544
+ * includeKinds: ["Run", "Task", "Agent", "Skill"],
11545
+ * });
11546
+ *
11547
+ * for (const node of result.nodes) {
11548
+ * switch (node.kind) {
11549
+ * case "Task": console.log(node.name); break;
11550
+ * case "Agent": console.log(node.model); break;
11551
+ * }
11552
+ * }
11553
+ * ```
11554
+ */
11555
+ async subgraph(rootId, options) {
11556
+ return executeSubgraph({
11557
+ graphId: this.graphId,
11558
+ rootId,
11559
+ backend: this.#backend,
11560
+ dialect: getDialect(this.#backend.dialect),
11561
+ schema: this.#schema,
11562
+ options
11563
+ });
11564
+ }
11403
11565
  // === Transactions ===
11404
11566
  /**
11405
11567
  * Executes a function within a transaction.