@dxos/app-graph 0.8.4-main.a4bbb77 → 0.8.4-main.abd8ff62ef

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 (60) hide show
  1. package/dist/lib/browser/chunk-3T75MQOS.mjs +1480 -0
  2. package/dist/lib/browser/chunk-3T75MQOS.mjs.map +7 -0
  3. package/dist/lib/browser/index.mjs +27 -842
  4. package/dist/lib/browser/index.mjs.map +4 -4
  5. package/dist/lib/browser/meta.json +1 -1
  6. package/dist/lib/browser/testing/index.mjs +39 -0
  7. package/dist/lib/browser/testing/index.mjs.map +7 -0
  8. package/dist/lib/node-esm/chunk-UEXRLXMS.mjs +1481 -0
  9. package/dist/lib/node-esm/chunk-UEXRLXMS.mjs.map +7 -0
  10. package/dist/lib/node-esm/index.mjs +27 -843
  11. package/dist/lib/node-esm/index.mjs.map +4 -4
  12. package/dist/lib/node-esm/meta.json +1 -1
  13. package/dist/lib/node-esm/testing/index.mjs +40 -0
  14. package/dist/lib/node-esm/testing/index.mjs.map +7 -0
  15. package/dist/types/src/atoms.d.ts +8 -0
  16. package/dist/types/src/atoms.d.ts.map +1 -0
  17. package/dist/types/src/graph-builder.d.ts +113 -67
  18. package/dist/types/src/graph-builder.d.ts.map +1 -1
  19. package/dist/types/src/graph.d.ts +188 -222
  20. package/dist/types/src/graph.d.ts.map +1 -1
  21. package/dist/types/src/index.d.ts +7 -3
  22. package/dist/types/src/index.d.ts.map +1 -1
  23. package/dist/types/src/node-matcher.d.ts +244 -0
  24. package/dist/types/src/node-matcher.d.ts.map +1 -0
  25. package/dist/types/src/node-matcher.test.d.ts +2 -0
  26. package/dist/types/src/node-matcher.test.d.ts.map +1 -0
  27. package/dist/types/src/node.d.ts +50 -5
  28. package/dist/types/src/node.d.ts.map +1 -1
  29. package/dist/types/src/stories/EchoGraph.stories.d.ts.map +1 -1
  30. package/dist/types/src/testing/index.d.ts +2 -0
  31. package/dist/types/src/testing/index.d.ts.map +1 -0
  32. package/dist/types/src/testing/setup-graph-builder.d.ts +31 -0
  33. package/dist/types/src/testing/setup-graph-builder.d.ts.map +1 -0
  34. package/dist/types/src/util.d.ts +40 -0
  35. package/dist/types/src/util.d.ts.map +1 -0
  36. package/dist/types/tsconfig.tsbuildinfo +1 -1
  37. package/package.json +42 -38
  38. package/src/atoms.ts +25 -0
  39. package/src/graph-builder.test.ts +1154 -144
  40. package/src/graph-builder.ts +737 -293
  41. package/src/graph.test.ts +451 -123
  42. package/src/graph.ts +1054 -403
  43. package/src/index.ts +10 -3
  44. package/src/node-matcher.test.ts +301 -0
  45. package/src/node-matcher.ts +314 -0
  46. package/src/node.ts +82 -8
  47. package/src/stories/EchoGraph.stories.tsx +164 -126
  48. package/src/stories/Tree.tsx +1 -1
  49. package/src/testing/index.ts +5 -0
  50. package/src/testing/setup-graph-builder.ts +41 -0
  51. package/src/util.ts +101 -0
  52. package/dist/types/src/experimental/graph-projections.test.d.ts +0 -25
  53. package/dist/types/src/experimental/graph-projections.test.d.ts.map +0 -1
  54. package/dist/types/src/signals-integration.test.d.ts +0 -2
  55. package/dist/types/src/signals-integration.test.d.ts.map +0 -1
  56. package/dist/types/src/testing.d.ts +0 -5
  57. package/dist/types/src/testing.d.ts.map +0 -1
  58. package/src/experimental/graph-projections.test.ts +0 -56
  59. package/src/signals-integration.test.ts +0 -218
  60. package/src/testing.ts +0 -20
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/node.ts", "../../../src/util.ts", "../../../src/graph.ts", "../../../src/node-matcher.ts", "../../../src/graph-builder.ts"],
4
+ "sourcesContent": ["//\n// Copyright 2023 DXOS.org\n//\n\nimport type * as Context from 'effect/Context';\nimport type * as Effect from 'effect/Effect';\n\nimport { type MakeOptional } from '@dxos/util';\n\n/**\n * Root node ID.\n */\nexport const RootId = 'root';\n\n/**\n * Root node type.\n */\nexport const RootType = 'org.dxos.type.graphRoot';\n\n/**\n * Action node type.\n */\nexport const ActionType = 'org.dxos.type.graphAction';\n\n/**\n * Action group node type.\n */\nexport const ActionGroupType = 'org.dxos.type.graphActionGroup';\n\n/**\n * Represents a node in the graph.\n */\n// TODO(wittjosiah): Use Effect Schema.\n// TODO(burdon): Rename GraphNode. Node is already in the global namespace.\nexport type Node<TData = any, TProperties extends Record<string, any> = Record<string, any>> = Readonly<{\n /**\n * Globally unique ID.\n */\n // TODO(burdon): Allow string array, which is concatenated.\n id: string;\n\n /**\n * Typename of the data the node represents.\n */\n type: string;\n\n /**\n * Keys in of the properties which should be cached.\n * If defined, the node will be included in the cache.\n * If undefined, the node will not be included in the cache.\n */\n cacheable?: string[];\n\n /**\n * Properties of the node relevant to displaying the node.\n */\n properties: Readonly<TProperties>;\n\n /**\n * Data the node represents.\n */\n // TODO(burdon): Type system (e.g., minimally provide identifier string vs. TypedObject vs. Graph mixin type system)?\n // type field would prevent convoluted sniffing of object properties. And allow direct pass-through for ECHO TypedObjects.\n data: TData;\n}>;\n\nexport type NodeFilter<TData = any, TProperties extends Record<string, any> = Record<string, any>> = (\n node: Node<unknown, Record<string, any>>,\n connectedNode: Node,\n) => node is Node<TData, TProperties>;\n\nexport type RelationDirection = 'outbound' | 'inbound';\n\nexport type Relation = Readonly<{\n kind: string;\n direction: RelationDirection;\n}>;\n\nexport type RelationInput = Relation | string;\n\nexport const relation = (kind: string, direction: RelationDirection = 'outbound'): Relation => ({ kind, direction });\n// TODO(wittjosiah): Consider moving these helpers out of the core API.\nexport const childRelation = (direction: RelationDirection = 'outbound'): Relation => relation('child', direction);\nexport const actionRelation = (direction: RelationDirection = 'outbound'): Relation => relation('action', direction);\n\nexport const isGraphNode = (data: unknown): data is Node =>\n data && typeof data === 'object' && 'id' in data && 'properties' in data && data.properties\n ? typeof data.properties === 'object' && 'data' in data\n : false;\n\nexport type NodeArg<TData, TProperties extends Record<string, any> = Record<string, any>> = MakeOptional<\n Node<TData, TProperties>,\n 'data' | 'properties' | 'cacheable'\n> & {\n /** Will automatically add nodes with an edge from this node to each. */\n nodes?: NodeArg<unknown>[];\n\n /** Will automatically add specified edges. */\n edges?: [string, RelationInput][];\n};\n\n//\n// Actions\n//\n\nexport type InvokeProps = {\n /** Node the invoked action is connected to. */\n parent?: Node;\n\n /** Path from root to the node in the current tree context. */\n path?: string[];\n\n caller?: string;\n};\n\n/**\n * Action data is an Effect-returning function.\n * The Effect is provided with captured context at execution time.\n */\nexport type ActionData<R = never> = (params?: InvokeProps) => Effect.Effect<any, Error, R>;\n\n/**\n * Context captured at extension creation time.\n * Automatically provided to action Effects at execution.\n */\nexport type ActionContext = Context.Context<any>;\n\nexport type Action<TProperties extends Record<string, any> = Record<string, any>> = Readonly<\n Omit<Node<ActionData, TProperties>, 'properties'> & {\n properties: Readonly<TProperties>;\n /** Captured context from extension creation. Provided automatically at action execution. */\n _actionContext?: ActionContext;\n }\n>;\n\nexport const isAction = (data: unknown): data is Action =>\n isGraphNode(data) ? typeof data.data === 'function' && data.type === ActionType : false;\n\nexport const actionGroupSymbol = Symbol('ActionGroup');\n\nexport type ActionGroup<TProperties extends Record<string, any> = Record<string, any>> = Readonly<\n Omit<Node<typeof actionGroupSymbol, TProperties>, 'properties'> & {\n properties: Readonly<TProperties>;\n }\n>;\n\nexport const isActionGroup = (data: unknown): data is ActionGroup =>\n isGraphNode(data) ? data.data === actionGroupSymbol && data.type === ActionGroupType : false;\n\nexport type ActionLike = Action | ActionGroup;\n\nexport const isActionLike = (data: unknown): data is Action | ActionGroup => isAction(data) || isActionGroup(data);\n\n//\n// Node Factories\n//\n\n/** Typed factory for constructing a NodeArg. Provides auto-complete and type validation. */\nexport const make = <TData = any, TProperties extends Record<string, any> = Record<string, any>>(\n arg: NodeArg<TData, TProperties>,\n): NodeArg<TData, TProperties> => arg;\n\n/** Create an action node. Automatically sets `type: ActionType`. */\nexport const makeAction = <R = never>(\n arg: Omit<NodeArg<ActionData<R>>, 'type' | 'nodes' | 'edges'>,\n): NodeArg<ActionData<R>> => ({\n ...arg,\n type: ActionType,\n});\n\n/** Create an action group node. Automatically sets `type` and `data`. */\nexport const makeActionGroup = (\n arg: Omit<NodeArg<typeof actionGroupSymbol>, 'type' | 'data' | 'nodes' | 'edges'>,\n): NodeArg<typeof actionGroupSymbol> => ({\n ...arg,\n type: ActionGroupType,\n data: actionGroupSymbol,\n});\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { invariant } from '@dxos/invariant';\n\nimport * as Node from './node';\n\n// PRIMARY separates top-level components (e.g., node ID from relation) in compound string keys used within the app-graph package.\nconst PRIMARY = '\\u0001';\n\n// SECONDARY separates sub-components within an encoded value (e.g., relation kind from direction) in the same context.\nconst SECONDARY = '\\u0002';\n\n// PATH separates segments in qualified node IDs (e.g., parent path from local segment).\nconst PATH = '/';\n\n/** Join parts with the primary separator. */\nexport const primaryKey = (...parts: string[]): string => parts.join(PRIMARY);\n\n/** Split a key on the primary separator. */\nexport const primaryParts = (key: string): string[] => key.split(PRIMARY);\n\n/** Join parts with the secondary separator. */\nexport const secondaryKey = (...parts: string[]): string => parts.join(SECONDARY);\n\n/** Split a key on the secondary separator. */\nexport const secondaryParts = (key: string): string[] => key.split(SECONDARY);\n\n/**\n * Normalize a relation input to a full Relation object.\n */\nexport const normalizeRelation = (relation?: Node.RelationInput): Node.Relation =>\n relation == null ? Node.childRelation() : typeof relation === 'string' ? Node.relation(relation) : relation;\n\n/**\n * Shallow-compare two values: same reference, or same own-keys with === values.\n */\nexport const shallowEqual = (a: unknown, b: unknown): boolean => {\n if (a === b) {\n return true;\n }\n if (a == null || b == null || typeof a !== 'object' || typeof b !== 'object') {\n return false;\n }\n const keysA = Object.keys(a as Record<string, unknown>);\n const keysB = Object.keys(b as Record<string, unknown>);\n if (keysA.length !== keysB.length) {\n return false;\n }\n return keysA.every((k) => (a as Record<string, unknown>)[k] === (b as Record<string, unknown>)[k]);\n};\n\n/**\n * Returns true if two NodeArg arrays are semantically identical (same id, type, data, properties per index).\n * Inline child nodes (the `nodes` field) are compared recursively.\n */\nexport const nodeArgsUnchanged = (prev: Node.NodeArg<any>[], next: Node.NodeArg<any>[]): boolean => {\n if (prev.length !== next.length) {\n return false;\n }\n\n return prev.every((prevNode, idx) => {\n const nextNode = next[idx];\n return (\n prevNode.id === nextNode.id &&\n prevNode.type === nextNode.type &&\n shallowEqual(prevNode.data, nextNode.data) &&\n shallowEqual(prevNode.properties, nextNode.properties) &&\n nodeArgsUnchanged(prevNode.nodes ?? [], nextNode.nodes ?? [])\n );\n });\n};\n\n/**\n * Build a qualified node ID by joining path segments.\n */\nexport const qualifyId = (parentId: string, ...segmentIds: string[]): string => [parentId, ...segmentIds].join(PATH);\n\n/**\n * Validate that a segment ID does not contain the path separator.\n */\nexport const validateSegmentId = (id: string): void => {\n invariant(!id.includes(PATH), `Node segment ID must not contain '${PATH}': ${id}`);\n};\n\n/**\n * Extract the parent qualified ID (everything before the last path separator).\n * Returns undefined for IDs with no parent (single segment).\n */\nexport const getParentId = (qualifiedId: string): string | undefined => {\n const lastSlash = qualifiedId.lastIndexOf(PATH);\n return lastSlash > 0 ? qualifiedId.slice(0, lastSlash) : undefined;\n};\n\n/**\n * Extract the last segment of a qualified ID.\n */\nexport const getSegmentId = (qualifiedId: string): string => {\n return qualifiedId.split(PATH).pop() ?? qualifiedId;\n};\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { Atom, Registry } from '@effect-atom/atom-react';\nimport * as Function from 'effect/Function';\nimport * as Option from 'effect/Option';\nimport * as Pipeable from 'effect/Pipeable';\nimport * as Record from 'effect/Record';\n\nimport { Event, Trigger } from '@dxos/async';\nimport { todo } from '@dxos/debug';\nimport { invariant } from '@dxos/invariant';\nimport { log } from '@dxos/log';\nimport { type MakeOptional, isNonNullable } from '@dxos/util';\n\nimport * as Node from './node';\nimport { normalizeRelation, primaryKey, primaryParts, secondaryKey, secondaryParts, shallowEqual } from './util';\n\nconst graphSymbol = Symbol('graph');\n\ntype DeepWriteable<T> = {\n -readonly [K in keyof T]: T[K] extends object ? DeepWriteable<T[K]> : T[K];\n};\n\ntype NodeInternal = DeepWriteable<Node.Node> & { [graphSymbol]: GraphImpl };\n\n/**\n * Get the Graph a Node is currently associated with.\n */\nexport const getGraph = (node: Node.Node): Graph => {\n const graph = (node as NodeInternal)[graphSymbol];\n invariant(graph, 'Node is not associated with a graph.');\n return graph as Graph;\n};\n\nexport type GraphTraversalOptions = {\n /**\n * A callback which is called for each node visited during traversal.\n *\n * If the callback returns `false`, traversal is stops recursing.\n */\n visitor: (node: Node.Node, path: string[]) => boolean | void;\n\n /**\n * The node to start traversing from.\n *\n * @default ROOT_ID\n */\n source?: string;\n\n /** The relation(s) to traverse graph edges. */\n relation: Node.RelationInput | Node.RelationInput[];\n};\n\nexport type GraphProps = {\n registry?: Registry.Registry;\n nodes?: MakeOptional<Node.Node, 'data' | 'cacheable'>[];\n edges?: Record<string, Edges>;\n onExpand?: (id: string, relation: Node.Relation) => void;\n onInitialize?: (id: string) => Promise<void>;\n onRemoveNode?: (id: string) => void;\n};\n\nexport type Edge = { source: string; target: string; relation: Node.RelationInput };\nexport type Edges = Record<string, string[]>;\n\n/**\n * Identifier denoting a Graph.\n */\nexport const GraphTypeId: unique symbol = Symbol.for('@dxos/app-graph/Graph');\nexport type GraphTypeId = typeof GraphTypeId;\n\n/**\n * Identifier for the graph kind discriminator.\n */\nexport const GraphKind: unique symbol = Symbol.for('@dxos/app-graph/GraphKind');\nexport type GraphKind = typeof GraphKind;\n\nexport type GraphKindType = 'readable' | 'expandable' | 'writable';\n\nexport interface BaseGraph extends Pipeable.Pipeable {\n readonly [GraphTypeId]: GraphTypeId;\n readonly [GraphKind]: GraphKindType;\n /**\n * Event emitted when a node is changed.\n */\n readonly onNodeChanged: Event<{ id: string; node: Option.Option<Node.Node> }>;\n /**\n * Get the atom key for the JSON representation of the graph.\n */\n json(id?: string): Atom.Atom<any>;\n /**\n * Get the atom key for the node with the given id.\n */\n node(id: string): Atom.Atom<Option.Option<Node.Node>>;\n /**\n * Get the atom key for the node with the given id.\n */\n nodeOrThrow(id: string): Atom.Atom<Node.Node>;\n /**\n * Get the atom key for the connections of the node with the given id.\n */\n connections(id: string, relation: Node.RelationInput): Atom.Atom<Node.Node[]>;\n /**\n * Get the atom key for the actions of the node with the given id.\n */\n actions(id: string): Atom.Atom<(Node.Action | Node.ActionGroup)[]>;\n /**\n * Get the atom key for the edges of the node with the given id.\n */\n edges(id: string): Atom.Atom<Edges>;\n}\n\nexport type ReadableGraph = BaseGraph & { readonly [GraphKind]: 'readable' | 'expandable' | 'writable' };\nexport type ExpandableGraph = BaseGraph & { readonly [GraphKind]: 'expandable' | 'writable' };\nexport type WritableGraph = BaseGraph & { readonly [GraphKind]: 'writable' };\n\n/**\n * Graph interface.\n */\nexport type Graph = WritableGraph;\n\n/**\n * The Graph represents the user interface information architecture of the application constructed via plugins.\n * @internal\n */\nclass GraphImpl implements WritableGraph {\n readonly [GraphTypeId]: GraphTypeId = GraphTypeId;\n readonly [GraphKind] = 'writable' as const;\n\n pipe() {\n // eslint-disable-next-line prefer-rest-params\n return Pipeable.pipeArguments(this, arguments);\n }\n\n readonly onNodeChanged = new Event<{\n id: string;\n node: Option.Option<Node.Node>;\n }>();\n\n readonly _onExpand?: GraphProps['onExpand'];\n readonly _onInitialize?: GraphProps['onInitialize'];\n readonly _onRemoveNode?: GraphProps['onRemoveNode'];\n\n readonly _registry: Registry.Registry;\n readonly _expanded = Record.empty<string, boolean>();\n readonly _pendingExpands = new Set<string>();\n readonly _initialized = Record.empty<string, boolean>();\n readonly _initialEdges = Record.empty<string, Edges>();\n readonly _initialNodes = Record.fromEntries([\n [\n Node.RootId,\n this._constructNode({\n id: Node.RootId,\n type: Node.RootType,\n data: null,\n properties: {},\n }),\n ],\n ]);\n\n /** @internal */\n readonly _node = Atom.family<string, Atom.Writable<Option.Option<Node.Node>>>((id) => {\n const initial = Option.flatten(Record.get(this._initialNodes, id));\n return Atom.make<Option.Option<Node.Node>>(initial).pipe(Atom.keepAlive, Atom.withLabel(`graph:node:${id}`));\n });\n\n readonly _nodeOrThrow = Atom.family<string, Atom.Atom<Node.Node>>((id) => {\n return Atom.make((get) => {\n const node = get(this._node(id));\n invariant(Option.isSome(node), `Node not available: ${id}`);\n return node.value;\n });\n });\n\n readonly _edges = Atom.family<string, Atom.Writable<Edges>>((id) => {\n const initial = Record.get(this._initialEdges, id).pipe(Option.getOrElse(() => ({}) as Edges));\n return Atom.make<Edges>(initial).pipe(Atom.keepAlive, Atom.withLabel(`graph:edges:${id}`));\n });\n\n // NOTE: Currently the argument to the family needs to be referentially stable for the atom to be referentially stable.\n // TODO(wittjosiah): Atom feature request, support for something akin to `ComplexMap` to allow for complex arguments.\n readonly _connections = Atom.family<string, Atom.Atom<Node.Node[]>>((key) => {\n return Atom.make((get) => {\n const parts = key ? primaryParts(key) : [];\n // Empty id (e.g. from `useConnections(graph, undefined, ...)`) yields a key like `\\u0001child\\u0002outbound`,\n // which has 2 parts but an empty id — treat as no connections rather than throwing.\n if (parts.length < 2 || !parts[0]) {\n return [];\n }\n const { id, relation } = relationFromConnectionKey(key);\n const edges = get(this._edges(id));\n return (edges[relationKey(relation)] ?? [])\n .map((id) => get(this._node(id)))\n .filter(Option.isSome)\n .map((o) => o.value);\n }).pipe(Atom.withLabel(`graph:connections:${key}`));\n });\n\n readonly _actions = Atom.family<string, Atom.Atom<(Node.Action | Node.ActionGroup)[]>>((id) => {\n return Atom.make((get) => {\n if (!id) {\n return [];\n }\n return get(this._connections(connectionKey(id, Node.actionRelation()))) as (Node.Action | Node.ActionGroup)[];\n }).pipe(Atom.withLabel(`graph:actions:${id}`));\n });\n\n readonly _json = Atom.family<string, Atom.Atom<any>>((id) => {\n return Atom.make((get) => {\n const toJSON = (node: Node.Node, seen: string[] = []): any => {\n const nodes = get(this._connections(connectionKey(node.id, 'child')));\n const obj: Record<string, any> = {\n id: node.id,\n type: node.type,\n };\n if (node.properties.label) {\n obj.label = node.properties.label;\n }\n if (nodes.length) {\n obj.nodes = nodes\n .map((n: Node.Node) => {\n // Break cycles.\n const nextSeen = [...seen, node.id];\n return nextSeen.includes(n.id) ? undefined : toJSON(n, nextSeen);\n })\n .filter(isNonNullable);\n }\n return obj;\n };\n\n const root = get(this._nodeOrThrow(id));\n return toJSON(root);\n }).pipe(Atom.withLabel(`graph:json:${id}`));\n });\n\n constructor({ registry, nodes, edges, onInitialize, onExpand, onRemoveNode }: GraphProps = {}) {\n this._registry = registry ?? Registry.make();\n this._onInitialize = onInitialize;\n this._onExpand = onExpand;\n this._onRemoveNode = onRemoveNode;\n\n if (nodes) {\n nodes.forEach((node) => {\n Record.set(this._initialNodes, node.id, this._constructNode(node));\n });\n }\n\n if (edges) {\n Object.entries(edges).forEach(([source, edges]) => {\n Record.set(this._initialEdges, source, edges);\n });\n }\n }\n\n json(id = Node.RootId): Atom.Atom<any> {\n return jsonImpl(this, id);\n }\n\n node(id: string): Atom.Atom<Option.Option<Node.Node>> {\n return nodeImpl(this, id);\n }\n\n nodeOrThrow(id: string): Atom.Atom<Node.Node> {\n return nodeOrThrowImpl(this, id);\n }\n\n connections(id: string, relation: Node.RelationInput): Atom.Atom<Node.Node[]> {\n return connectionsImpl(this, id, relation);\n }\n\n actions(id: string): Atom.Atom<(Node.Action | Node.ActionGroup)[]> {\n return actionsImpl(this, id);\n }\n\n edges(id: string): Atom.Atom<Edges> {\n return edgesImpl(this, id);\n }\n\n /** @internal */\n _constructNode(node: Node.NodeArg<any>): Option.Option<Node.Node> {\n return Option.some({\n [graphSymbol]: this,\n data: null,\n properties: {},\n ...node,\n });\n }\n}\n\n/**\n * Internal helper to access GraphImpl internals.\n * @internal\n */\nconst getInternal = (graph: BaseGraph): GraphImpl => {\n return graph as unknown as GraphImpl;\n};\n\n/**\n * Convert the graph to a JSON object.\n */\nexport const toJSON = (graph: BaseGraph, id = Node.RootId): object => {\n const internal = getInternal(graph);\n return internal._registry.get(internal._json(id));\n};\n\n/**\n * Implementation helper for json.\n */\nconst jsonImpl = (graph: BaseGraph, id = Node.RootId): Atom.Atom<any> => {\n const internal = getInternal(graph);\n return internal._json(id);\n};\n\n/**\n * Implementation helper for node.\n */\nconst nodeImpl = (graph: BaseGraph, id: string): Atom.Atom<Option.Option<Node.Node>> => {\n const internal = getInternal(graph);\n return internal._node(id);\n};\n\n/**\n * Implementation helper for nodeOrThrow.\n */\nconst nodeOrThrowImpl = (graph: BaseGraph, id: string): Atom.Atom<Node.Node> => {\n const internal = getInternal(graph);\n return internal._nodeOrThrow(id);\n};\n\n/**\n * Implementation helper for connections.\n */\nconst connectionsImpl = (graph: BaseGraph, id: string, relation: Node.RelationInput): Atom.Atom<Node.Node[]> => {\n const internal = getInternal(graph);\n return internal._connections(connectionKey(id, relation));\n};\n\n/**\n * Implementation helper for actions.\n */\nconst actionsImpl = (graph: BaseGraph, id: string): Atom.Atom<(Node.Action | Node.ActionGroup)[]> => {\n const internal = getInternal(graph);\n return internal._actions(id);\n};\n\n/**\n * Implementation helper for edges.\n */\nconst edgesImpl = (graph: BaseGraph, id: string): Atom.Atom<Edges> => {\n const internal = getInternal(graph);\n return internal._edges(id);\n};\n\n/**\n * Implementation helper for getNode.\n */\nconst getNodeImpl = (graph: BaseGraph, id: string): Option.Option<Node.Node> => {\n const internal = getInternal(graph);\n return internal._registry.get(nodeImpl(graph, id));\n};\n\n/**\n * Get the node with the given id from the graph's registry.\n */\nexport function getNode(graph: BaseGraph, id: string): Option.Option<Node.Node>;\nexport function getNode(id: string): (graph: BaseGraph) => Option.Option<Node.Node>;\nexport function getNode(\n graphOrId: BaseGraph | string,\n id?: string,\n): Option.Option<Node.Node> | ((graph: BaseGraph) => Option.Option<Node.Node>) {\n if (typeof graphOrId === 'string') {\n // Curried: getNode(id)\n const id = graphOrId;\n return (graph: BaseGraph) => getNodeImpl(graph, id);\n } else {\n // Direct: getNode(graph, id)\n const graph = graphOrId;\n return getNodeImpl(graph, id!);\n }\n}\n\n/**\n * Implementation helper for getNodeOrThrow.\n */\nconst getNodeOrThrowImpl = (graph: BaseGraph, id: string): Node.Node => {\n const internal = getInternal(graph);\n return internal._registry.get(nodeOrThrowImpl(graph, id));\n};\n\n/**\n * Get the node with the given id from the graph's registry.\n *\n * @throws If the node is Option.none().\n */\nexport function getNodeOrThrow(graph: BaseGraph, id: string): Node.Node;\nexport function getNodeOrThrow(id: string): (graph: BaseGraph) => Node.Node;\nexport function getNodeOrThrow(\n graphOrId: BaseGraph | string,\n id?: string,\n): Node.Node | ((graph: BaseGraph) => Node.Node) {\n if (typeof graphOrId === 'string') {\n // Curried: getNodeOrThrow(id)\n const id = graphOrId;\n return (graph: BaseGraph) => getNodeOrThrowImpl(graph, id);\n } else {\n // Direct: getNodeOrThrow(graph, id)\n const graph = graphOrId;\n return getNodeOrThrowImpl(graph, id!);\n }\n}\n\n/**\n * Get the root node of the graph.\n * This is an alias for `getNodeOrThrow(graph, ROOT_ID)`.\n */\nexport function getRoot(graph: BaseGraph): Node.Node {\n return getNodeOrThrowImpl(graph, Node.RootId);\n}\n\n/**\n * Implementation helper for getConnections.\n */\nconst getConnectionsImpl = (graph: BaseGraph, id: string, relation: Node.RelationInput): Node.Node[] => {\n const internal = getInternal(graph);\n return internal._registry.get(connectionsImpl(graph, id, relation));\n};\n\n/**\n * Get all nodes connected to the node with the given id by the given relation from the graph's registry.\n */\nexport function getConnections(graph: BaseGraph, id: string, relation: Node.RelationInput): Node.Node[];\nexport function getConnections(id: string, relation: Node.RelationInput): (graph: BaseGraph) => Node.Node[];\nexport function getConnections(\n graphOrId: BaseGraph | string,\n idOrRelation: string | Node.RelationInput,\n relation?: Node.RelationInput,\n): Node.Node[] | ((graph: BaseGraph) => Node.Node[]) {\n if (typeof graphOrId === 'string') {\n // Curried: getConnections(id, relation)\n const id = graphOrId;\n const rel = idOrRelation as Node.RelationInput;\n return (graph: BaseGraph) => getConnectionsImpl(graph, id, rel);\n } else {\n // Direct: getConnections(graph, id, relation)\n const graph = graphOrId;\n const id = idOrRelation as string;\n invariant(relation !== undefined, 'Relation is required.');\n const rel = relation;\n return getConnectionsImpl(graph, id, rel);\n }\n}\n\n/**\n * Implementation helper for getActions.\n */\nconst getActionsImpl = (graph: BaseGraph, id: string): Node.Node[] => {\n const internal = getInternal(graph);\n return internal._registry.get(actionsImpl(graph, id));\n};\n\n/**\n * Get all actions connected to the node with the given id from the graph's registry.\n */\nexport function getActions(graph: BaseGraph, id: string): Node.Node[];\nexport function getActions(id: string): (graph: BaseGraph) => Node.Node[];\nexport function getActions(\n graphOrId: BaseGraph | string,\n id?: string,\n): Node.Node[] | ((graph: BaseGraph) => Node.Node[]) {\n if (typeof graphOrId === 'string') {\n // Curried: getActions(id)\n const id = graphOrId;\n return (graph: BaseGraph) => getActionsImpl(graph, id);\n } else {\n // Direct: getActions(graph, id)\n const graph = graphOrId;\n return getActionsImpl(graph, id!);\n }\n}\n\n/**\n * Implementation helper for getEdges.\n */\nconst getEdgesImpl = (graph: BaseGraph, id: string): Edges => {\n const internal = getInternal(graph);\n return internal._registry.get(edgesImpl(graph, id));\n};\n\n/**\n * Get the edges from the node with the given id from the graph's registry.\n */\nexport function getEdges(graph: BaseGraph, id: string): Edges;\nexport function getEdges(id: string): (graph: BaseGraph) => Edges;\nexport function getEdges(graphOrId: BaseGraph | string, id?: string): Edges | ((graph: BaseGraph) => Edges) {\n if (typeof graphOrId === 'string') {\n // Curried: getEdges(id)\n const id = graphOrId;\n return (graph: BaseGraph) => getEdgesImpl(graph, id);\n } else {\n // Direct: getEdges(graph, id)\n const graph = graphOrId;\n return getEdgesImpl(graph, id!);\n }\n}\n\n/**\n * Recursive depth-first traversal of the graph.\n */\n/**\n * Implementation helper for traverse.\n */\nconst traverseImpl = (graph: BaseGraph, options: GraphTraversalOptions, path: string[] = []): void => {\n const { visitor, source = Node.RootId, relation } = options;\n // Break cycles.\n if (path.includes(source)) {\n return;\n }\n\n const node = getNodeOrThrow(graph, source);\n const shouldContinue = visitor(node, [...path, source]);\n if (shouldContinue === false) {\n return;\n }\n\n const relations = Array.isArray(relation) ? relation : [relation];\n const seen = new Set<string>();\n for (const rel of relations) {\n for (const connected of getConnections(graph, source, rel)) {\n if (!seen.has(connected.id)) {\n seen.add(connected.id);\n traverseImpl(graph, { source: connected.id, relation, visitor }, [...path, source]);\n }\n }\n }\n};\n\n/**\n * Traverse the graph with the given options.\n */\nexport function traverse(graph: BaseGraph, options: GraphTraversalOptions, path?: string[]): void;\nexport function traverse(options: GraphTraversalOptions, path?: string[]): (graph: BaseGraph) => void;\nexport function traverse(\n graphOrOptions: BaseGraph | GraphTraversalOptions,\n optionsOrPath?: GraphTraversalOptions | string[],\n path?: string[],\n): void | ((graph: BaseGraph) => void) {\n if (typeof graphOrOptions === 'object' && 'visitor' in graphOrOptions) {\n // Curried: traverse(options, path?)\n const options = graphOrOptions as GraphTraversalOptions;\n const pathArg = Array.isArray(optionsOrPath) ? optionsOrPath : undefined;\n return (graph: BaseGraph) => traverseImpl(graph, options, pathArg);\n } else {\n // Direct: traverse(graph, options, path?)\n const graph = graphOrOptions as BaseGraph;\n const options = optionsOrPath as GraphTraversalOptions;\n const pathArg = path ?? (Array.isArray(optionsOrPath) ? optionsOrPath : undefined);\n return traverseImpl(graph, options, pathArg);\n }\n}\n\n/**\n * Implementation helper for getPath.\n */\nconst getPathImpl = (graph: BaseGraph, params: { source?: string; target: string }): Option.Option<string[]> => {\n return Function.pipe(\n getNode(graph, params.source ?? 'root'),\n Option.flatMap((node) => {\n let found: Option.Option<string[]> = Option.none();\n traverseImpl(graph, {\n source: node.id,\n relation: 'child',\n visitor: (node, path) => {\n if (Option.isSome(found)) {\n return false;\n }\n\n if (node.id === params.target) {\n found = Option.some(path);\n }\n },\n });\n\n return found;\n }),\n );\n};\n\n/**\n * Get the path between two nodes in the graph.\n */\nexport function getPath(graph: BaseGraph, params: { source?: string; target: string }): Option.Option<string[]>;\nexport function getPath(params: { source?: string; target: string }): (graph: BaseGraph) => Option.Option<string[]>;\nexport function getPath(\n graphOrParams: BaseGraph | { source?: string; target: string },\n params?: { source?: string; target: string },\n): Option.Option<string[]> | ((graph: BaseGraph) => Option.Option<string[]>) {\n if (params === undefined && typeof graphOrParams === 'object' && 'target' in graphOrParams) {\n // Curried: getPath(params)\n const params = graphOrParams as { source?: string; target: string };\n return (graph: BaseGraph) => getPathImpl(graph, params);\n } else {\n // Direct: getPath(graph, params)\n const graph = graphOrParams as BaseGraph;\n return getPathImpl(graph, params!);\n }\n}\n\n/**\n * Implementation helper for waitForPath.\n */\nconst waitForPathImpl = (\n graph: BaseGraph,\n params: { source?: string; target: string },\n options?: { timeout?: number; interval?: number },\n): Promise<string[]> => {\n const { timeout = 5_000, interval = 500 } = options ?? {};\n const path = getPathImpl(graph, params);\n if (Option.isSome(path)) {\n return Promise.resolve(path.value);\n }\n\n const trigger = new Trigger<string[]>();\n const i = setInterval(() => {\n const path = getPathImpl(graph, params);\n if (Option.isSome(path)) {\n trigger.wake(path.value);\n }\n }, interval);\n\n return trigger.wait({ timeout }).finally(() => clearInterval(i));\n};\n\n/**\n * Wait for the path between two nodes in the graph to be established.\n */\nexport function waitForPath(\n graph: BaseGraph,\n params: { source?: string; target: string },\n options?: { timeout?: number; interval?: number },\n): Promise<string[]>;\nexport function waitForPath(\n params: { source?: string; target: string },\n options?: { timeout?: number; interval?: number },\n): (graph: BaseGraph) => Promise<string[]>;\nexport function waitForPath(\n graphOrParams: BaseGraph | { source?: string; target: string },\n paramsOrOptions?: { source?: string; target: string } | { timeout?: number; interval?: number },\n options?: { timeout?: number; interval?: number },\n): Promise<string[]> | ((graph: BaseGraph) => Promise<string[]>) {\n if (typeof graphOrParams === 'object' && 'target' in graphOrParams) {\n // Curried: waitForPath(params, options?)\n const params = graphOrParams as { source?: string; target: string };\n const opts = typeof paramsOrOptions === 'object' && !('target' in paramsOrOptions) ? paramsOrOptions : undefined;\n return (graph: BaseGraph) => waitForPathImpl(graph, params, opts);\n } else {\n // Direct: waitForPath(graph, params, options?)\n const graph = graphOrParams as BaseGraph;\n const params = paramsOrOptions as { source?: string; target: string };\n return waitForPathImpl(graph, params, options);\n }\n}\n\n/**\n * Implementation helper for initialize.\n */\nconst initializeImpl = async <T extends ExpandableGraph | WritableGraph>(graph: T, id: string): Promise<T> => {\n const internal = getInternal(graph);\n const initialized = Record.get(internal._initialized, id).pipe(Option.getOrElse(() => false));\n log('initialize', { id, initialized });\n if (!initialized) {\n Record.set(internal._initialized, id, true);\n await internal._onInitialize?.(id);\n }\n return graph;\n};\n\n/**\n * Initialize a node in the graph.\n *\n * Fires the `onInitialize` callback to provide initial data for a node.\n */\nexport function initialize<T extends ExpandableGraph | WritableGraph>(graph: T, id: string): Promise<T>;\nexport function initialize(id: string): <T extends ExpandableGraph | WritableGraph>(graph: T) => Promise<T>;\nexport function initialize<T extends ExpandableGraph | WritableGraph>(\n graphOrId: T | string,\n id?: string,\n): Promise<T> | (<T extends ExpandableGraph | WritableGraph>(graph: T) => Promise<T>) {\n if (typeof graphOrId === 'string') {\n // Curried: initialize(id)\n const id = graphOrId;\n return <T extends ExpandableGraph | WritableGraph>(graph: T) => initializeImpl(graph, id);\n } else {\n // Direct: initialize(graph, id)\n const graph = graphOrId;\n return initializeImpl(graph, id!);\n }\n}\n\n/**\n * Implementation helper for expand.\n * If the node does not exist yet, the expand is recorded as pending and applied when the node is added.\n */\nconst expandImpl = <T extends ExpandableGraph | WritableGraph>(\n graph: T,\n id: string,\n relation: Node.RelationInput,\n): T => {\n const internal = getInternal(graph);\n const normalizedRelation = normalizeRelation(relation);\n const key = primaryKey(id, relationKey(normalizedRelation));\n const nodeOpt = internal._registry.get(internal._node(id));\n if (Option.isNone(nodeOpt)) {\n // Node not yet in graph: record expand to run when the node is added.\n internal._pendingExpands.add(key);\n log('expand', { key, deferred: true });\n return graph;\n }\n\n const expanded = Record.get(internal._expanded, key).pipe(Option.getOrElse(() => false));\n log('expand', { key, expanded });\n if (!expanded) {\n Record.set(internal._expanded, key, true);\n internal._onExpand?.(id, normalizedRelation);\n }\n return graph;\n};\n\n/**\n * Expand a node in the graph.\n *\n * Fires the `onExpand` callback to add connections to the node.\n */\nexport function expand<T extends ExpandableGraph | WritableGraph>(\n graph: T,\n id: string,\n relation: Node.RelationInput,\n): T;\nexport function expand(\n id: string,\n relation: Node.RelationInput,\n): <T extends ExpandableGraph | WritableGraph>(graph: T) => T;\nexport function expand<T extends ExpandableGraph | WritableGraph>(\n graphOrId: T | string,\n idOrRelation: string | Node.RelationInput,\n relation?: Node.RelationInput,\n): T | (<T extends ExpandableGraph | WritableGraph>(graph: T) => T) {\n if (typeof graphOrId === 'string') {\n // Curried: expand(id, relation)\n const id = graphOrId;\n const rel = idOrRelation as Node.RelationInput;\n return <T extends ExpandableGraph | WritableGraph>(graph: T) => expandImpl(graph, id, rel);\n } else {\n // Direct: expand(graph, id, relation)\n const graph = graphOrId;\n const id = idOrRelation as string;\n invariant(relation !== undefined, 'Relation is required.');\n const rel = relation;\n return expandImpl(graph, id, rel);\n }\n}\n\n/**\n * Implementation helper for sortEdges.\n */\nconst sortEdgesImpl = <T extends ExpandableGraph | WritableGraph>(\n graph: T,\n id: string,\n relation: Node.RelationInput,\n order: string[],\n): T => {\n const internal = getInternal(graph);\n const edgesAtom = internal._edges(id);\n const edges = internal._registry.get(edgesAtom);\n const relationId = relationKey(relation);\n const current = edges[relationId] ?? [];\n const unsorted = current.filter((id) => !order.includes(id));\n const sorted = order.filter((id) => current.includes(id));\n const newOrder = [...sorted, ...unsorted];\n if (newOrder.length === current.length && newOrder.every((id, i) => id === current[i])) {\n return graph;\n }\n internal._registry.set(edgesAtom, {\n ...edges,\n [relationId]: newOrder,\n });\n return graph;\n};\n\n/**\n * Sort the edges of the node with the given id.\n */\nexport function sortEdges<T extends ExpandableGraph | WritableGraph>(\n graph: T,\n id: string,\n relation: Node.RelationInput,\n order: string[],\n): T;\nexport function sortEdges(\n id: string,\n relation: Node.RelationInput,\n order: string[],\n): <T extends ExpandableGraph | WritableGraph>(graph: T) => T;\nexport function sortEdges<T extends ExpandableGraph | WritableGraph>(\n graphOrId: T | string,\n idOrRelation?: string | Node.RelationInput,\n relationOrOrder?: Node.RelationInput | string[],\n order?: string[],\n): T | (<T extends ExpandableGraph | WritableGraph>(graph: T) => T) {\n if (typeof graphOrId === 'string') {\n // Curried: sortEdges(id, relation, order)\n const id = graphOrId;\n const relation = idOrRelation as Node.RelationInput;\n const order = relationOrOrder as string[];\n return <T extends ExpandableGraph | WritableGraph>(graph: T) => sortEdgesImpl(graph, id, relation, order);\n } else {\n // Direct: sortEdges(graph, id, relation, order)\n const graph = graphOrId;\n const id = idOrRelation as string;\n const relation = relationOrOrder as Node.RelationInput;\n return sortEdgesImpl(graph, id, relation, order!);\n }\n}\n\n/**\n * Implementation helper for addNodes.\n */\nconst addNodesImpl = <T extends WritableGraph>(graph: T, nodes: Node.NodeArg<any, Record<string, any>>[]): T => {\n Atom.batch(() => {\n nodes.map((node) => addNodeImpl(graph, node));\n });\n return graph;\n};\n\n/**\n * Add nodes to the graph.\n */\nexport function addNodes<T extends WritableGraph>(graph: T, nodes: Node.NodeArg<any, Record<string, any>>[]): T;\nexport function addNodes(nodes: Node.NodeArg<any, Record<string, any>>[]): <T extends WritableGraph>(graph: T) => T;\nexport function addNodes<T extends WritableGraph>(\n graphOrNodes: T | Node.NodeArg<any, Record<string, any>>[],\n nodes?: Node.NodeArg<any, Record<string, any>>[],\n): T | (<T extends WritableGraph>(graph: T) => T) {\n if (nodes === undefined) {\n // Curried: addNodes(nodes)\n const nodes = graphOrNodes as Node.NodeArg<any, Record<string, any>>[];\n return <T extends WritableGraph>(graph: T) => addNodesImpl(graph, nodes);\n } else {\n // Direct: addNodes(graph, nodes)\n const graph = graphOrNodes as T;\n return addNodesImpl(graph, nodes);\n }\n}\n\n/**\n * Implementation helper for addNode.\n */\nconst addNodeImpl = <T extends WritableGraph>(graph: T, nodeArg: Node.NodeArg<any, Record<string, any>>): T => {\n const internal = getInternal(graph);\n // Extract known NodeArg fields, preserve any extra fields (like _actionContext) in rest.\n const {\n nodes,\n edges,\n id,\n type,\n data = null,\n properties = {},\n ...rest\n } = nodeArg as Node.NodeArg<any> & {\n _actionContext?: Node.ActionContext;\n };\n const nodeAtom = internal._node(id);\n const existingNode = internal._registry.get(nodeAtom);\n Option.match(existingNode, {\n onSome: (existing) => {\n const typeChanged = existing.type !== type;\n const dataChanged = !shallowEqual(existing.data, data);\n const propertiesChanged = Object.keys(properties).some((key) => existing.properties[key] !== properties[key]);\n log('existing node', {\n id,\n typeChanged,\n dataChanged,\n propertiesChanged,\n });\n if (typeChanged || dataChanged || propertiesChanged) {\n log('updating node', { id, type, data, properties });\n const newNode = Option.some({\n ...existing,\n ...rest,\n type,\n data,\n properties: { ...existing.properties, ...properties },\n });\n internal._registry.set(nodeAtom, newNode);\n graph.onNodeChanged.emit({ id, node: newNode });\n }\n },\n onNone: () => {\n log('new node', { id, type, data, properties });\n const newNode = internal._constructNode({ id, type, data, properties, ...rest });\n internal._registry.set(nodeAtom, newNode);\n graph.onNodeChanged.emit({ id, node: newNode });\n\n // Apply any expands that were deferred because this node did not exist yet.\n const toApply = [...internal._pendingExpands].filter((k) => primaryParts(k)[0] === id);\n for (const pendingKey of toApply) {\n internal._pendingExpands.delete(pendingKey);\n const relation = relationFromKey(primaryParts(pendingKey)[1]);\n Record.set(internal._expanded, pendingKey, true);\n internal._onExpand?.(id, relation);\n }\n },\n });\n\n if (nodes) {\n addNodesImpl(graph, nodes);\n const _edges = nodes.map((node) => ({ source: id, target: node.id, relation: 'child' as const }));\n addEdgesImpl(graph, _edges);\n }\n\n if (edges) {\n todo();\n }\n return graph;\n};\n\n/**\n * Add a node to the graph.\n */\nexport function addNode<T extends WritableGraph>(graph: T, nodeArg: Node.NodeArg<any, Record<string, any>>): T;\nexport function addNode(nodeArg: Node.NodeArg<any, Record<string, any>>): <T extends WritableGraph>(graph: T) => T;\nexport function addNode<T extends WritableGraph>(\n graphOrNodeArg: T | Node.NodeArg<any, Record<string, any>>,\n nodeArg?: Node.NodeArg<any, Record<string, any>>,\n): T | (<T extends WritableGraph>(graph: T) => T) {\n if (nodeArg === undefined) {\n // Curried: addNode(nodeArg)\n const nodeArg = graphOrNodeArg as Node.NodeArg<any, Record<string, any>>;\n return <T extends WritableGraph>(graph: T) => addNodeImpl(graph, nodeArg);\n } else {\n // Direct: addNode(graph, nodeArg)\n const graph = graphOrNodeArg as T;\n return addNodeImpl(graph, nodeArg);\n }\n}\n\n/**\n * Implementation helper for removeNodes.\n */\nconst removeNodesImpl = <T extends WritableGraph>(graph: T, ids: string[], edges = false): T => {\n Atom.batch(() => {\n ids.map((id) => removeNodeImpl(graph, id, edges));\n });\n return graph;\n};\n\n/**\n * Remove nodes from the graph.\n */\nexport function removeNodes<T extends WritableGraph>(graph: T, ids: string[], edges?: boolean): T;\nexport function removeNodes(ids: string[], edges?: boolean): <T extends WritableGraph>(graph: T) => T;\nexport function removeNodes<T extends WritableGraph>(\n graphOrIds: T | string[],\n idsOrEdges?: string[] | boolean,\n edges?: boolean,\n): T | (<T extends WritableGraph>(graph: T) => T) {\n if (Array.isArray(graphOrIds)) {\n // Curried: removeNodes(ids, edges?)\n const ids = graphOrIds;\n const edgesArg = typeof idsOrEdges === 'boolean' ? idsOrEdges : false;\n return <T extends WritableGraph>(graph: T) => removeNodesImpl(graph, ids, edgesArg);\n } else {\n // Direct: removeNodes(graph, ids, edges?)\n const graph = graphOrIds;\n const ids = idsOrEdges as string[];\n const edgesArg = edges ?? false;\n return removeNodesImpl(graph, ids, edgesArg);\n }\n}\n\n/**\n * Implementation helper for removeNode.\n */\nconst removeNodeImpl = <T extends WritableGraph>(graph: T, id: string, edges = false): T => {\n const internal = getInternal(graph);\n const nodeAtom = internal._node(id);\n // TODO(wittjosiah): Is there a way to mark these atom values for garbage collection?\n internal._registry.set(nodeAtom, Option.none());\n graph.onNodeChanged.emit({ id, node: Option.none() });\n // TODO(wittjosiah): Reset expanded and initialized flags?\n\n if (edges) {\n const nodeEdges = internal._registry.get(internal._edges(id));\n const edgesToRemove: Edge[] = [];\n for (const [relationKeyValue, relatedIds] of Object.entries(nodeEdges)) {\n const relation = relationFromKey(relationKeyValue);\n const isInboundRelation = relation.direction === 'inbound';\n for (const relatedId of relatedIds) {\n if (isInboundRelation) {\n // Inbound edge lists store source node IDs; reconstruct the canonical outbound edge.\n edgesToRemove.push({ source: relatedId, target: id, relation: inverseRelation(relation) });\n } else {\n edgesToRemove.push({ source: id, target: relatedId, relation });\n }\n }\n }\n removeEdgesImpl(graph, edgesToRemove);\n }\n\n internal._onRemoveNode?.(id);\n return graph;\n};\n\n/**\n * Remove a node from the graph.\n */\nexport function removeNode<T extends WritableGraph>(graph: T, id: string, edges?: boolean): T;\nexport function removeNode(id: string, edges?: boolean): <T extends WritableGraph>(graph: T) => T;\nexport function removeNode<T extends WritableGraph>(\n graphOrId: T | string,\n idOrEdges?: string | boolean,\n edges?: boolean,\n): T | (<T extends WritableGraph>(graph: T) => T) {\n if (typeof graphOrId === 'string') {\n // Curried: removeNode(id, edges?)\n const id = graphOrId;\n const edgesArg = typeof idOrEdges === 'boolean' ? idOrEdges : false;\n return <T extends WritableGraph>(graph: T) => removeNodeImpl(graph, id, edgesArg);\n } else {\n // Direct: removeNode(graph, id, edges?)\n const graph = graphOrId;\n const id = idOrEdges as string;\n const edgesArg = edges ?? false;\n return removeNodeImpl(graph, id, edgesArg);\n }\n}\n\n/**\n * Implementation helper for addEdges.\n */\nconst addEdgesImpl = <T extends WritableGraph>(graph: T, edges: Edge[]): T => {\n Atom.batch(() => {\n edges.map((edge) => addEdgeImpl(graph, edge));\n });\n return graph;\n};\n\n/**\n * Add edges to the graph.\n */\nexport function addEdges<T extends WritableGraph>(graph: T, edges: Edge[]): T;\nexport function addEdges(edges: Edge[]): <T extends WritableGraph>(graph: T) => T;\nexport function addEdges<T extends WritableGraph>(\n graphOrEdges: T | Edge[],\n edges?: Edge[],\n): T | (<T extends WritableGraph>(graph: T) => T) {\n if (edges === undefined) {\n // Curried: addEdges(edges)\n const edges = graphOrEdges as Edge[];\n return <T extends WritableGraph>(graph: T) => addEdgesImpl(graph, edges);\n } else {\n // Direct: addEdges(graph, edges)\n const graph = graphOrEdges as T;\n return addEdgesImpl(graph, edges);\n }\n}\n\n/**\n * Implementation helper for addEdge.\n */\nconst addEdgeImpl = <T extends WritableGraph>(graph: T, edgeArg: Edge): T => {\n const relation = normalizeRelation(edgeArg.relation);\n const relationId = relationKey(relation);\n const inverse = inverseRelation(relation);\n const inverseId = relationKey(inverse);\n const internal = getInternal(graph);\n\n const sourceAtom = internal._edges(edgeArg.source);\n const source = internal._registry.get(sourceAtom);\n const sourceList = source[relationId] ?? [];\n if (!sourceList.includes(edgeArg.target)) {\n log('add edge', { source: edgeArg.source, target: edgeArg.target, relation: relationId });\n internal._registry.set(sourceAtom, { ...source, [relationId]: [...sourceList, edgeArg.target] });\n }\n\n const targetAtom = internal._edges(edgeArg.target);\n const target = internal._registry.get(targetAtom);\n const targetList = target[inverseId] ?? [];\n if (!targetList.includes(edgeArg.source)) {\n log('add inverse edge', { source: edgeArg.source, target: edgeArg.target, relation: inverseId });\n internal._registry.set(targetAtom, { ...target, [inverseId]: [...targetList, edgeArg.source] });\n }\n\n return graph;\n};\n\n/**\n * Add an edge to the graph.\n */\nexport function addEdge<T extends WritableGraph>(graph: T, edgeArg: Edge): T;\nexport function addEdge(edgeArg: Edge): <T extends WritableGraph>(graph: T) => T;\nexport function addEdge<T extends WritableGraph>(\n graphOrEdgeArg: T | Edge,\n edgeArg?: Edge,\n): T | (<T extends WritableGraph>(graph: T) => T) {\n if (edgeArg === undefined) {\n // Curried: addEdge(edgeArg)\n const edgeArg = graphOrEdgeArg as Edge;\n return <T extends WritableGraph>(graph: T) => addEdgeImpl(graph, edgeArg);\n } else {\n // Direct: addEdge(graph, edgeArg)\n const graph = graphOrEdgeArg as T;\n return addEdgeImpl(graph, edgeArg);\n }\n}\n\n/**\n * Implementation helper for removeEdges.\n */\nconst removeEdgesImpl = <T extends WritableGraph>(graph: T, edges: Edge[], removeOrphans = false): T => {\n Atom.batch(() => {\n edges.map((edge) => removeEdgeImpl(graph, edge, removeOrphans));\n });\n return graph;\n};\n\n/**\n * Remove edges from the graph.\n */\nexport function removeEdges<T extends WritableGraph>(graph: T, edges: Edge[], removeOrphans?: boolean): T;\nexport function removeEdges(edges: Edge[], removeOrphans?: boolean): <T extends WritableGraph>(graph: T) => T;\nexport function removeEdges<T extends WritableGraph>(\n graphOrEdges: T | Edge[],\n edgesOrRemoveOrphans?: Edge[] | boolean,\n removeOrphans?: boolean,\n): T | (<T extends WritableGraph>(graph: T) => T) {\n if (Array.isArray(graphOrEdges)) {\n // Curried: removeEdges(edges, removeOrphans?)\n const edges = graphOrEdges;\n const removeOrphansArg = typeof edgesOrRemoveOrphans === 'boolean' ? edgesOrRemoveOrphans : false;\n return <T extends WritableGraph>(graph: T) => removeEdgesImpl(graph, edges, removeOrphansArg);\n } else {\n // Direct: removeEdges(graph, edges, removeOrphans?)\n const graph = graphOrEdges;\n const edges = edgesOrRemoveOrphans as Edge[];\n const removeOrphansArg = removeOrphans ?? false;\n return removeEdgesImpl(graph, edges, removeOrphansArg);\n }\n}\n\n/**\n * Implementation helper for removeEdge.\n */\nconst removeEdgeImpl = <T extends WritableGraph>(graph: T, edgeArg: Edge, removeOrphans = false): T => {\n const relation = normalizeRelation(edgeArg.relation);\n const relationId = relationKey(relation);\n const inverse = inverseRelation(relation);\n const inverseId = relationKey(inverse);\n const internal = getInternal(graph);\n\n const sourceAtom = internal._edges(edgeArg.source);\n const source = internal._registry.get(sourceAtom);\n const sourceList = source[relationId] ?? [];\n if (sourceList.includes(edgeArg.target)) {\n internal._registry.set(sourceAtom, { ...source, [relationId]: sourceList.filter((id) => id !== edgeArg.target) });\n }\n\n const targetAtom = internal._edges(edgeArg.target);\n const target = internal._registry.get(targetAtom);\n const targetList = target[inverseId] ?? [];\n if (targetList.includes(edgeArg.source)) {\n internal._registry.set(targetAtom, { ...target, [inverseId]: targetList.filter((id) => id !== edgeArg.source) });\n }\n\n if (removeOrphans) {\n const sourceAfter = internal._registry.get(sourceAtom);\n const targetAfter = internal._registry.get(targetAtom);\n const isEmpty = (edges: Edges) => Object.values(edges).every((ids) => ids.length === 0);\n if (isEmpty(sourceAfter) && edgeArg.source !== Node.RootId) {\n removeNodesImpl(graph, [edgeArg.source]);\n }\n if (isEmpty(targetAfter) && edgeArg.target !== Node.RootId) {\n removeNodesImpl(graph, [edgeArg.target]);\n }\n }\n return graph;\n};\n\n/**\n * Remove an edge from the graph.\n */\nexport function removeEdge<T extends WritableGraph>(graph: T, edgeArg: Edge, removeOrphans?: boolean): T;\nexport function removeEdge(edgeArg: Edge, removeOrphans?: boolean): <T extends WritableGraph>(graph: T) => T;\nexport function removeEdge<T extends WritableGraph>(\n graphOrEdgeArg: T | Edge,\n edgeArgOrRemoveOrphans?: Edge | boolean,\n removeOrphans?: boolean,\n): T | (<T extends WritableGraph>(graph: T) => T) {\n if (\n edgeArgOrRemoveOrphans === undefined ||\n typeof edgeArgOrRemoveOrphans === 'boolean' ||\n 'source' in graphOrEdgeArg\n ) {\n // Curried: removeEdge(edgeArg, removeOrphans?)\n const edgeArg = graphOrEdgeArg as Edge;\n const removeOrphansArg = typeof edgeArgOrRemoveOrphans === 'boolean' ? edgeArgOrRemoveOrphans : false;\n return <T extends WritableGraph>(graph: T) => removeEdgeImpl(graph, edgeArg, removeOrphansArg);\n } else {\n // Direct: removeEdge(graph, edgeArg, removeOrphans?)\n const graph = graphOrEdgeArg as T;\n const edgeArg = edgeArgOrRemoveOrphans as Edge;\n const removeOrphansArg = removeOrphans ?? false;\n return removeEdgeImpl(graph, edgeArg, removeOrphansArg);\n }\n}\n\n/**\n * Creates a new Graph instance.\n */\nexport const make = (params?: GraphProps): Graph => {\n return new GraphImpl(params);\n};\n\n//\n// Utilities\n//\n\nexport const relationKey = (relation: Node.RelationInput): string => {\n const normalized = normalizeRelation(relation);\n return secondaryKey(normalized.kind, normalized.direction);\n};\n\nexport const relationFromKey = (encoded: string): Node.Relation => {\n const parts = secondaryParts(encoded);\n invariant(parts.length === 2 && parts[0].length > 0 && parts[1].length > 0, `Invalid relation key: ${encoded}`);\n const [kind, directionRaw] = parts;\n invariant(directionRaw === 'outbound' || directionRaw === 'inbound', `Invalid relation direction: ${directionRaw}`);\n return Node.relation(kind, directionRaw);\n};\n\nconst connectionKey = (id: string, relation: Node.RelationInput): string => primaryKey(id, relationKey(relation));\n\nconst relationFromConnectionKey = (key: string): { id: string; relation: Node.Relation } => {\n const [id, encodedRelation] = primaryParts(key);\n invariant(id && encodedRelation, `Invalid connection key: ${key}`);\n return { id, relation: relationFromKey(encodedRelation) };\n};\n\nconst inverseRelation = (relation: Node.RelationInput): Node.Relation => {\n const normalized = normalizeRelation(relation);\n return Node.relation(normalized.kind, normalized.direction === 'outbound' ? 'inbound' : 'outbound');\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Option from 'effect/Option';\nimport type * as Schema from 'effect/Schema';\n\nimport { type Entity, Obj, type Type } from '@dxos/echo';\n\nimport * as Node from './node';\n\n/**\n * Type for a node matcher function that returns an Option of the matched data.\n * Matchers are used to filter and transform nodes in the app graph.\n *\n * @template TData - The type of data returned when the matcher succeeds.\n * Defaults to Node.Node, but can be a more specific type (e.g., an ECHO entity).\n */\nexport type NodeMatcher<TData = Node.Node> = (node: Node.Node) => Option.Option<TData>;\n\n//\n// Basic Node Matchers\n//\n\n/**\n * Matches the root node of the graph.\n *\n * @returns Option.some(node) if the node is the root, Option.none() otherwise.\n *\n * @example\n * ```ts\n * GraphBuilder.createExtension({\n * id: 'my-extension',\n * match: NodeMatcher.whenRoot,\n * connector: (node) => Effect.succeed([...]),\n * });\n * ```\n */\nexport const whenRoot = (node: Node.Node): Option.Option<Node.Node> =>\n node.id === Node.RootId ? Option.some(node) : Option.none();\n\n/**\n * Matches a node by its exact ID.\n *\n * @param id - The node ID to match against.\n * @returns A matcher that returns Option.some(node) if IDs match, Option.none() otherwise.\n *\n * @example\n * ```ts\n * GraphBuilder.createExtension({\n * id: 'spaces-extension',\n * match: NodeMatcher.whenId('spaces'),\n * connector: (node) => Effect.succeed([...]),\n * });\n * ```\n */\nexport const whenId =\n (id: string) =>\n (node: Node.Node): Option.Option<Node.Node> =>\n node.id === id ? Option.some(node) : Option.none();\n\n/**\n * Matches a node by its type string (the `node.type` property).\n *\n * @param type - The node type string to match against.\n * @returns A matcher that returns Option.some(node) if types match, Option.none() otherwise.\n *\n * @example\n * ```ts\n * GraphBuilder.createExtension({\n * id: 'space-settings-extension',\n * match: NodeMatcher.whenNodeType('org.dxos.plugin.space.settings'),\n * connector: (node) => Effect.succeed([...]),\n * });\n * ```\n */\nexport const whenNodeType =\n (type: string) =>\n (node: Node.Node): Option.Option<Node.Node> =>\n node.type === type ? Option.some(node) : Option.none();\n\n//\n// ECHO Data Matchers\n//\n\n/**\n * Matches a node whose data is an instance of the given ECHO schema type.\n * Returns the **typed entity data** (not the node) for direct use in callbacks.\n *\n * Use this when you need to work directly with the typed ECHO entity in your\n * connector or actions callback.\n *\n * @template T - The ECHO schema type to match against.\n * @param type - The ECHO schema (e.g., `Collection.Collection`, `Document.Document`).\n * @returns A matcher that returns Option.some(entity) if the data matches, Option.none() otherwise.\n *\n * @example\n * ```ts\n * GraphBuilder.createExtension({\n * id: 'collection-extension',\n * match: NodeMatcher.whenEchoType(Collection.Collection),\n * connector: (collection) => {\n * // `collection` is typed as Collection.Collection\n * return Effect.succeed(collection.objects.map(...));\n * },\n * });\n * ```\n *\n * Can be composed directly with {@link whenAll}/{@link whenAny}/{@link whenNot} while\n * preserving the typed entity data in the result.\n *\n * @see {@link whenEchoTypeMatches} - Returns the node instead of data for legacy composition.\n */\nexport const whenEchoType =\n <T extends Type.AnyEntity>(type: T): NodeMatcher<Entity.Entity<Schema.Schema.Type<T>>> =>\n (node: Node.Node): Option.Option<Entity.Entity<Schema.Schema.Type<T>>> =>\n Obj.instanceOf(type, node.data) ? Option.some(node.data) : Option.none();\n\n/**\n * Matches a node whose data is any ECHO object.\n * Returns the **object data** (not the node) for direct use in callbacks.\n *\n * Use this when you need to work with any ECHO object regardless of its specific type.\n *\n * @returns Option.some(object) if the node's data is an ECHO object, Option.none() otherwise.\n *\n * @example\n * ```ts\n * GraphBuilder.createExtension({\n * id: 'object-properties',\n * match: NodeMatcher.whenEchoObject,\n * connector: (object) => {\n * // `object` is typed as Obj.Unknown\n * const id = Obj.getDXN(object).toString();\n * return Effect.succeed([{ id: `${id}.settings`, ... }]);\n * },\n * });\n * ```\n *\n * Can be composed directly with {@link whenAll}/{@link whenAny}/{@link whenNot} while\n * preserving the `Obj.Unknown` data type in the result.\n *\n * @see {@link whenEchoObjectMatches} - Returns the node instead of data for legacy composition.\n */\nexport const whenEchoObject = (node: Node.Node): Option.Option<Obj.Unknown> =>\n Obj.isObject(node.data) ? Option.some(node.data) : Option.none();\n\n//\n// Composition Matchers\n//\n\n/**\n * Composes multiple matchers with AND logic - all matchers must match for success.\n * The result data type is the intersection of all matchers' data types.\n * Filter matchers like {@link whenNot} return `unknown`, making them transparent\n * in the intersection (since `T & unknown = T`).\n *\n * @param matchers - The matchers to combine. All must return Option.some for success.\n * @returns A matcher whose data type is the intersection of all input matchers' data types.\n * Returns the first matcher's value when all match, Option.none() otherwise.\n *\n * @example\n * ```ts\n * // Match ECHO objects that are NOT Channels — result is NodeMatcher<Obj.Unknown>.\n * const whenCommentable = NodeMatcher.whenAll(\n * NodeMatcher.whenEchoObject,\n * NodeMatcher.whenNot(NodeMatcher.whenEchoTypeMatches(Channel.Channel)),\n * );\n * ```\n */\nexport const whenAll: {\n <A>(a: NodeMatcher<A>, b: NodeMatcher<unknown>): NodeMatcher<A>;\n <A>(a: NodeMatcher<unknown>, b: NodeMatcher<A>): NodeMatcher<A>;\n <A, B>(a: NodeMatcher<A>, b: NodeMatcher<B>): NodeMatcher<A & B>;\n <A, B, C>(a: NodeMatcher<A>, b: NodeMatcher<B>, c: NodeMatcher<C>): NodeMatcher<A & B & C>;\n <A, B, C, D>(a: NodeMatcher<A>, b: NodeMatcher<B>, c: NodeMatcher<C>, d: NodeMatcher<D>): NodeMatcher<A & B & C & D>;\n (...matchers: NodeMatcher<any>[]): NodeMatcher<any>;\n} =\n (...matchers: NodeMatcher<any>[]): NodeMatcher<any> =>\n (node: Node.Node) => {\n let first: Option.Option<any> = Option.none();\n for (const candidate of matchers) {\n const result = candidate(node);\n if (Option.isNone(result)) {\n return Option.none();\n }\n if (Option.isNone(first)) {\n first = result;\n }\n }\n return first;\n };\n\n/**\n * Composes multiple matchers with OR logic - at least one matcher must match.\n * The result data type is the union of all matchers' data types.\n *\n * @param matchers - The matchers to combine. At least one must return Option.some.\n * @returns A matcher whose data type is the union of all input matchers' data types.\n * Returns the first matching matcher's value, or Option.none() if none match.\n *\n * @example\n * ```ts\n * // Match nodes that are either Sequences or Routines\n * const whenInvocable = NodeMatcher.whenAny(\n * NodeMatcher.whenEchoTypeMatches(Sequence),\n * NodeMatcher.whenEchoTypeMatches(Routine.Routine),\n * );\n * ```\n */\nexport const whenAny: {\n <A, B>(a: NodeMatcher<A>, b: NodeMatcher<B>): NodeMatcher<A | B>;\n <A, B, C>(a: NodeMatcher<A>, b: NodeMatcher<B>, c: NodeMatcher<C>): NodeMatcher<A | B | C>;\n <A, B, C, D>(a: NodeMatcher<A>, b: NodeMatcher<B>, c: NodeMatcher<C>, d: NodeMatcher<D>): NodeMatcher<A | B | C | D>;\n (...matchers: NodeMatcher<any>[]): NodeMatcher<any>;\n} =\n (...matchers: NodeMatcher<any>[]): NodeMatcher<any> =>\n (node: Node.Node) => {\n for (const candidate of matchers) {\n const result = candidate(node);\n if (Option.isSome(result)) {\n return result;\n }\n }\n return Option.none();\n };\n\n/**\n * Matches a node whose data is an instance of the given ECHO schema type.\n * Returns the **node** (not the data) to enable composition with whenAll/whenAny/whenNot.\n *\n * Use this instead of {@link whenEchoType} when you need to combine matchers.\n * The difference is what's returned:\n * - `whenEchoType` returns the typed entity (for direct use)\n * - `whenEchoTypeMatches` returns the node (for composition)\n *\n * @template T - The ECHO schema type to match against.\n * @param type - The ECHO schema (e.g., `Channel.Channel`, `Document.Document`).\n * @returns A matcher that returns Option.some(node) if the data matches, Option.none() otherwise.\n *\n * @example\n * ```ts\n * // Use with whenAny for OR logic\n * const whenPresentable = NodeMatcher.whenAny(\n * NodeMatcher.whenEchoTypeMatches(Collection.Collection),\n * NodeMatcher.whenEchoTypeMatches(Markdown.Document),\n * );\n *\n * // Use with whenNot for exclusion\n * const whenNotChannel = NodeMatcher.whenNot(\n * NodeMatcher.whenEchoTypeMatches(Channel.Channel),\n * );\n * ```\n *\n * @see {@link whenEchoType} - Use instead when you need the typed entity directly.\n */\nexport const whenEchoTypeMatches =\n <T extends Type.AnyEntity>(type: T): NodeMatcher =>\n (node: Node.Node): Option.Option<Node.Node> =>\n Obj.instanceOf(type, node.data) ? Option.some(node) : Option.none();\n\n/**\n * Matches a node whose data is any ECHO object.\n * Returns the **node** (not the data) to enable composition with whenAll/whenAny/whenNot.\n *\n * Use this instead of {@link whenEchoObject} when you need to combine matchers.\n * The difference is what's returned:\n * - `whenEchoObject` returns the object data (for direct use)\n * - `whenEchoObjectMatches` returns the node (for composition)\n *\n * @returns Option.some(node) if the node's data is an ECHO object, Option.none() otherwise.\n *\n * @example\n * ```ts\n * // Match ECHO objects that are not system types\n * const whenUserObject = NodeMatcher.whenAll(\n * NodeMatcher.whenEchoObjectMatches,\n * NodeMatcher.whenNot(NodeMatcher.whenEchoTypeMatches(SystemType)),\n * );\n * ```\n *\n * @see {@link whenEchoObject} - Use instead when you need the object data directly.\n */\nexport const whenEchoObjectMatches = (node: Node.Node): Option.Option<Node.Node> =>\n Obj.isObject(node.data) ? Option.some(node) : Option.none();\n\n/**\n * Negates a matcher - matches when the given matcher does NOT match.\n * Useful for exclusion patterns like \"any object EXCEPT type X\".\n *\n * Returns `NodeMatcher<unknown>` because negation is a filter — it doesn't provide\n * typed data. This makes it transparent in {@link whenAll} intersections\n * (since `T & unknown = T`).\n *\n * @param matcher - The matcher to negate.\n * @returns A matcher that returns Option.some(node) if the input matcher returns none,\n * and Option.none() if the input matcher returns some.\n *\n * @example\n * ```ts\n * // Match any ECHO object that is NOT a Channel — result is NodeMatcher<Obj.Unknown>.\n * const whenCommentable = NodeMatcher.whenAll(\n * NodeMatcher.whenEchoObject,\n * NodeMatcher.whenNot(NodeMatcher.whenEchoTypeMatches(Channel.Channel)),\n * );\n *\n * // Match any node that is NOT the root\n * const whenNotRoot = NodeMatcher.whenNot(NodeMatcher.whenRoot);\n * ```\n */\nexport const whenNot =\n (matcher: NodeMatcher<any>): NodeMatcher<unknown> =>\n (node: Node.Node): Option.Option<unknown> =>\n Option.isNone(matcher(node)) ? Option.some(node) : Option.none();\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { Atom, Registry } from '@effect-atom/atom-react';\nimport * as Array from 'effect/Array';\nimport type * as Context from 'effect/Context';\nimport * as Effect from 'effect/Effect';\nimport * as Function from 'effect/Function';\nimport * as Option from 'effect/Option';\nimport * as Pipeable from 'effect/Pipeable';\nimport * as Record from 'effect/Record';\nimport type * as Schema from 'effect/Schema';\nimport { scheduleTask, yieldOrContinue } from 'main-thread-scheduling';\n\nimport { type CleanupFn, type Trigger } from '@dxos/async';\nimport { type Entity, type Type } from '@dxos/echo';\nimport { log } from '@dxos/log';\nimport { type MaybePromise, type Position, byPosition, getDebugName, isNonNullable } from '@dxos/util';\n\nimport * as Graph from './graph';\nimport * as Node from './node';\nimport * as NodeMatcher from './node-matcher';\nimport {\n getParentId,\n nodeArgsUnchanged,\n normalizeRelation,\n primaryKey,\n primaryParts,\n qualifyId,\n validateSegmentId,\n} from './util';\n\n//\n// Extension Types\n//\n\n/**\n * Graph builder extension for adding nodes to the graph based on a node id.\n */\nexport type ResolverExtension = (id: string) => Atom.Atom<Node.NodeArg<any> | null>;\n\n/**\n * Graph builder extension for adding nodes to the graph based on a connection to an existing node.\n *\n * @param params.node The existing node the returned nodes will be connected to.\n */\nexport type ConnectorExtension = (node: Atom.Atom<Option.Option<Node.Node>>) => Atom.Atom<Node.NodeArg<any>[]>;\n\n/**\n * Constrained case of the connector extension for more easily adding actions to the graph.\n */\nexport type ActionsExtension = (\n node: Atom.Atom<Option.Option<Node.Node>>,\n) => Atom.Atom<Omit<Node.NodeArg<Node.ActionData<any>>, 'type' | 'nodes' | 'edges'>[]>;\n\n/**\n * Constrained case of the connector extension for more easily adding action groups to the graph.\n */\nexport type ActionGroupsExtension = (\n node: Atom.Atom<Option.Option<Node.Node>>,\n) => Atom.Atom<Omit<Node.NodeArg<typeof Node.actionGroupSymbol>, 'type' | 'data' | 'nodes' | 'edges'>[]>;\n\nexport type BuilderExtension = Readonly<{\n id: string;\n position: Position;\n relation?: Node.RelationInput;\n resolver?: ResolverExtension;\n connector?: (node: Atom.Atom<Option.Option<Node.Node>>) => Atom.Atom<Node.NodeArg<any>[]>;\n}>;\n\nexport type BuilderExtensions = BuilderExtension | BuilderExtension[] | BuilderExtensions[];\n\n//\n// GraphBuilder Core\n//\n\nexport type GraphBuilderTraverseOptions = {\n visitor: (node: Node.Node, path: string[]) => MaybePromise<boolean | void>;\n registry?: Registry.Registry;\n source?: string;\n relation: Node.RelationInput | Node.RelationInput[];\n};\n\n/**\n * Identifier denoting a GraphBuilder.\n */\nexport const GraphBuilderTypeId: unique symbol = Symbol.for('@dxos/app-graph/GraphBuilder');\nexport type GraphBuilderTypeId = typeof GraphBuilderTypeId;\n\n/**\n * GraphBuilder interface.\n */\nexport interface GraphBuilder extends Pipeable.Pipeable {\n readonly [GraphBuilderTypeId]: GraphBuilderTypeId;\n readonly graph: Graph.ExpandableGraph;\n readonly extensions: Atom.Atom<Record<string, BuilderExtension>>;\n}\n\n/**\n * The builder provides an extensible way to compose the construction of the graph.\n * @internal\n */\n// TODO(wittjosiah): Add api for setting subscription set and/or radius.\n// Should unsubscribe from nodes that are not in the set/radius.\n// Should track LRU nodes that are not in the set/radius and remove them beyond a certain threshold.\nclass GraphBuilderImpl implements GraphBuilder {\n readonly [GraphBuilderTypeId]: GraphBuilderTypeId = GraphBuilderTypeId;\n\n pipe() {\n // eslint-disable-next-line prefer-rest-params\n return Pipeable.pipeArguments(this, arguments);\n }\n\n // TODO(wittjosiah): Use Context.\n /** Active subscriptions keyed by composite ID, cleaned up on node removal. */\n readonly _subscriptions = new Map<string, CleanupFn>();\n /** Connector updates pending flush, keyed by connector key. */\n readonly _dirtyConnectors = new Map<\n string,\n {\n nodes: Node.NodeArg<any>[];\n previous: string[];\n }\n >();\n /** Last-flushed node IDs per connector key, used for edge removal on update. */\n readonly _connectorPrevious = new Map<string, string[]>();\n /** All inline-descendant IDs per connector key, used to remove stale inline nodes on update. */\n readonly _connectorPreviousInlineIds = new Map<string, string[]>();\n /** Last-flushed node args per connector key, used for change detection. */\n readonly _connectorPreviousArgs = new Map<string, Node.NodeArg<any>[]>();\n /** Whether a dirty-flush task is already scheduled. */\n _flushScheduled = false;\n /** Resolves when the current flush completes. */\n _flushPromise: Promise<void> = Promise.resolve();\n /** Registered builder extensions keyed by extension ID. */\n readonly _extensions = Atom.make(Record.empty<string, BuilderExtension>()).pipe(\n Atom.keepAlive,\n Atom.withLabel('graph-builder:extensions'),\n );\n /** Triggers signalling that a node's resolver has fired at least once. */\n readonly _initialized: Record<string, Trigger> = {};\n /** Shared atom registry for reactive subscriptions. */\n readonly _registry: Registry.Registry;\n /** Backing graph with internal accessors for node atoms and construction. */\n readonly _graph: Graph.Graph & {\n _node: (id: string) => Atom.Writable<Option.Option<Node.Node>>;\n _constructNode: (node: Node.NodeArg<any>) => Option.Option<Node.Node>;\n };\n\n constructor({ registry, ...params }: Pick<Graph.GraphProps, 'registry' | 'nodes' | 'edges'> = {}) {\n this._registry = registry ?? Registry.make();\n const graph = Graph.make({\n ...params,\n registry: this._registry,\n onExpand: (id, relation) => this._onExpand(id, relation),\n onInitialize: (id) => this._onInitialize(id),\n onRemoveNode: (id) => this._onRemoveNode(id),\n });\n // Access internal methods via type assertion since GraphBuilder needs them\n this._graph = graph as Graph.Graph & {\n _node: (id: string) => Atom.Writable<Option.Option<Node.Node>>;\n _constructNode: (node: Node.NodeArg<any>) => Option.Option<Node.Node>;\n };\n }\n\n get graph(): Graph.ExpandableGraph {\n return this._graph;\n }\n\n get extensions() {\n return this._extensions;\n }\n\n /** Apply a set of node changes for a single connector key. */\n private _applyConnectorUpdate(key: string, nodes: Node.NodeArg<any>[], previous: string[]): void {\n const { id, relation } = relationFromConnectorKey(key);\n const ids = nodes.map((node) => node.id);\n const removed = previous.filter((pid) => !ids.includes(pid));\n this._connectorPrevious.set(key, ids);\n this._connectorPreviousArgs.set(key, nodes);\n\n const currentInlineIds = collectAllInlineIds(nodes);\n const previousInlineIds = this._connectorPreviousInlineIds.get(key) ?? [];\n const staleInlineIds = previousInlineIds.filter((pid) => !currentInlineIds.includes(pid));\n this._connectorPreviousInlineIds.set(key, currentInlineIds);\n\n Graph.removeNodes(this._graph, staleInlineIds, true);\n Graph.removeEdges(\n this._graph,\n removed.map((target) => ({ source: id, target, relation })),\n true,\n );\n Graph.addNodes(this._graph, nodes);\n Graph.addEdges(\n this._graph,\n nodes.map((node) => ({ source: id, target: node.id, relation })),\n );\n if (ids.length > 0) {\n const sortedIds = [...nodes]\n .sort((a, b) =>\n byPosition(a.properties ?? ({} as { position?: Position }), b.properties ?? ({} as { position?: Position })),\n )\n .map((n) => n.id);\n Graph.sortEdges(this._graph, id, relation, sortedIds);\n }\n }\n\n private _scheduleDirtyFlush(): void {\n if (!this._flushScheduled) {\n this._flushScheduled = true;\n this._flushPromise = scheduleTask(\n () => {\n this._flushScheduled = false;\n while (this._dirtyConnectors.size > 0) {\n const entries = [...this._dirtyConnectors.entries()];\n this._dirtyConnectors.clear();\n\n Atom.batch(() => {\n for (const [key, { nodes, previous }] of entries) {\n this._applyConnectorUpdate(key, nodes, previous);\n }\n });\n }\n },\n { strategy: 'smooth' },\n );\n }\n }\n\n private readonly _resolvers = Atom.family<string, Atom.Atom<Option.Option<Node.NodeArg<any>>>>((id) => {\n return Atom.make((get) => {\n return Function.pipe(\n get(this._extensions),\n Record.values,\n Array.sortBy(byPosition),\n Array.map(({ resolver }) => resolver),\n Array.filter(isNonNullable),\n Array.map((resolver) => get(resolver(id))),\n Array.filter(isNonNullable),\n Array.head,\n );\n });\n });\n\n private readonly _connectors = Atom.family<string, Atom.Atom<Node.NodeArg<any>[]>>((key) => {\n return Atom.make((get) => {\n const { id, relation } = relationFromConnectorKey(key);\n const node = this._graph.node(id);\n\n const sourceNode = Option.getOrElse(get(node), () => undefined);\n if (!sourceNode) {\n return [];\n }\n\n const extensions = Function.pipe(\n get(this._extensions),\n Record.values,\n Array.sortBy(byPosition),\n Array.filter(\n (ext): ext is BuilderExtension & { connector: NonNullable<BuilderExtension['connector']> } =>\n Graph.relationKey(ext.relation ?? 'child') === Graph.relationKey(relation) && ext.connector != null,\n ),\n );\n\n const nodes: Node.NodeArg<any>[] = [];\n for (const ext of extensions) {\n const result = get(ext.connector(node));\n nodes.push(...result);\n }\n\n return nodes;\n }).pipe(Atom.withLabel(`graph-builder:connectors:${key}`));\n });\n\n private _onExpand(id: string, relation: Node.Relation): void {\n log('onExpand', { id, relation, registry: getDebugName(this._registry) });\n this._expandRelation(id, relation);\n\n // TODO(wittjosiah): Remove. This is for backwards compatibility.\n if (relation.kind === 'child' && relation.direction === 'outbound') {\n Graph.expand(this._graph, id, 'action');\n }\n }\n\n private _expandRelation(id: string, relation: Node.RelationInput): void {\n const key = connectorKey(id, relation);\n const connectors = this._connectors(key);\n\n const cancel = this._registry.subscribe(\n connectors,\n (rawNodes) => {\n const nodes = qualifyNodeArgs(id)(rawNodes);\n const previous = this._connectorPrevious.get(key) ?? [];\n const ids = nodes.map((n) => n.id);\n\n if (ids.length === previous.length && ids.every((nodeId, idx) => nodeId === previous[idx])) {\n const prevArgs = this._connectorPreviousArgs.get(key);\n if (prevArgs && nodeArgsUnchanged(prevArgs, nodes)) {\n return;\n }\n }\n\n log('update', { id, relation, ids });\n this._dirtyConnectors.set(key, { nodes, previous });\n this._scheduleDirtyFlush();\n },\n { immediate: true },\n );\n\n this._subscriptions.set(subscriptionKey(id, 'expand', key), cancel);\n }\n\n private async _onInitialize(id: string) {\n log('onInitialize', { id });\n const resolver = this._resolvers(id);\n\n const cancel = this._registry.subscribe(\n resolver,\n (node) => {\n const trigger = this._initialized[id];\n const connectorOwned = [...this._connectorPrevious.values()].some((ids) => ids.includes(id));\n Option.match(node, {\n onSome: (node) => {\n if (!connectorOwned) {\n Graph.addNodes(this._graph, [node]);\n // Connect resolved node to its parent via a child edge.\n const parentId = getParentId(id);\n if (parentId) {\n Graph.addEdges(this._graph, [{ source: parentId, target: id, relation: 'child' }]);\n }\n }\n trigger?.wake();\n },\n onNone: () => {\n trigger?.wake();\n if (!connectorOwned) {\n Graph.removeNodes(this._graph, [id]);\n }\n },\n });\n },\n { immediate: true },\n );\n\n this._subscriptions.set(subscriptionKey(id, 'init'), cancel);\n }\n\n private _onRemoveNode(id: string): void {\n for (const [key, cleanup] of this._subscriptions) {\n if (primaryParts(key)[0] === id) {\n cleanup();\n this._subscriptions.delete(key);\n }\n }\n }\n}\n\n/**\n * Creates a new GraphBuilder instance.\n */\nexport const make = (params?: Pick<Graph.GraphProps, 'registry' | 'nodes' | 'edges'>): GraphBuilder => {\n return new GraphBuilderImpl(params);\n};\n\n/**\n * Creates a GraphBuilder from a serialized pickle string.\n */\nexport const from = (pickle?: string, registry?: Registry.Registry): GraphBuilder => {\n if (!pickle) {\n return make({ registry });\n }\n\n const { nodes, edges } = JSON.parse(pickle);\n return make({ nodes, edges, registry });\n};\n\n/**\n * Implementation helper for addExtension.\n */\nconst addExtensionImpl = (builder: GraphBuilder, extensions: BuilderExtensions): GraphBuilder => {\n const internal = builder as GraphBuilderImpl;\n flattenExtensions(extensions).forEach((extension) => {\n const extensions = internal._registry.get(internal._extensions);\n internal._registry.set(internal._extensions, Record.set(extensions, extension.id, extension));\n });\n return builder;\n};\n\n/**\n * Add extensions to the graph builder.\n */\nexport function addExtension(builder: GraphBuilder, extensions: BuilderExtensions): GraphBuilder;\nexport function addExtension(extensions: BuilderExtensions): (builder: GraphBuilder) => GraphBuilder;\nexport function addExtension(\n builderOrExtensions: GraphBuilder | BuilderExtensions,\n extensions?: BuilderExtensions,\n): GraphBuilder | ((builder: GraphBuilder) => GraphBuilder) {\n if (extensions === undefined) {\n // Curried: addExtension(extensions)\n const extensions = builderOrExtensions as BuilderExtensions;\n return (builder: GraphBuilder) => addExtensionImpl(builder, extensions);\n } else {\n // Direct: addExtension(builder, extensions)\n const builder = builderOrExtensions as GraphBuilder;\n return addExtensionImpl(builder, extensions);\n }\n}\n\n/**\n * Implementation helper for removeExtension.\n */\nconst removeExtensionImpl = (builder: GraphBuilder, id: string): GraphBuilder => {\n const internal = builder as GraphBuilderImpl;\n const extensions = internal._registry.get(internal._extensions);\n internal._registry.set(internal._extensions, Record.remove(extensions, id));\n return builder;\n};\n\n/**\n * Remove an extension from the graph builder.\n */\nexport function removeExtension(builder: GraphBuilder, id: string): GraphBuilder;\nexport function removeExtension(id: string): (builder: GraphBuilder) => GraphBuilder;\nexport function removeExtension(\n builderOrId: GraphBuilder | string,\n id?: string,\n): GraphBuilder | ((builder: GraphBuilder) => GraphBuilder) {\n if (typeof builderOrId === 'string') {\n // Curried: removeExtension(id)\n const id = builderOrId;\n return (builder: GraphBuilder) => removeExtensionImpl(builder, id);\n } else {\n // Direct: removeExtension(builder, id)\n const builder = builderOrId;\n return removeExtensionImpl(builder, id!);\n }\n}\n\n/**\n * Implementation helper for explore.\n */\nconst exploreImpl = async (\n builder: GraphBuilder,\n options: GraphBuilderTraverseOptions,\n path: string[] = [],\n): Promise<void> => {\n const internal = builder as GraphBuilderImpl;\n const { registry = Registry.make(), source = Node.RootId, relation, visitor } = options;\n // Break cycles.\n if (path.includes(source)) {\n return;\n }\n\n await yieldOrContinue('idle');\n\n const node = registry.get(internal._graph.nodeOrThrow(source));\n const shouldContinue = await visitor(node, [...path, node.id]);\n if (shouldContinue === false) {\n return;\n }\n\n const nodes = Function.pipe(\n internal._registry.get(internal._extensions),\n Record.values,\n Array.map((extension) => extension.connector),\n Array.filter(isNonNullable),\n Array.flatMap((connector) => registry.get(connector(internal._graph.node(source)))),\n qualifyNodeArgs(source),\n );\n\n await Promise.all(\n nodes.map((nodeArg) => {\n registry.set(internal._graph._node(nodeArg.id), internal._graph._constructNode(nodeArg));\n return exploreImpl(builder, { registry, source: nodeArg.id, relation, visitor }, [...path, node.id]);\n }),\n );\n\n if (registry !== internal._registry) {\n registry.reset();\n registry.dispose();\n }\n};\n\n/**\n * Explore the graph by traversing it with the given options.\n */\nexport function explore(builder: GraphBuilder, options: GraphBuilderTraverseOptions, path?: string[]): Promise<void>;\nexport function explore(\n options: GraphBuilderTraverseOptions,\n path?: string[],\n): (builder: GraphBuilder) => Promise<void>;\nexport function explore(\n builderOrOptions: GraphBuilder | GraphBuilderTraverseOptions,\n optionsOrPath?: GraphBuilderTraverseOptions | string[],\n path?: string[],\n): Promise<void> | ((builder: GraphBuilder) => Promise<void>) {\n if (typeof builderOrOptions === 'object' && 'visitor' in builderOrOptions) {\n // Curried: explore(options, path?)\n const options = builderOrOptions as GraphBuilderTraverseOptions;\n const path = Array.isArray(optionsOrPath) ? optionsOrPath : undefined;\n return (builder: GraphBuilder) => exploreImpl(builder, options, path);\n } else {\n // Direct: explore(builder, options, path?)\n const builder = builderOrOptions as GraphBuilder;\n const options = optionsOrPath as GraphBuilderTraverseOptions;\n const pathArg = path ?? (Array.isArray(optionsOrPath) ? optionsOrPath : undefined);\n return exploreImpl(builder, options, pathArg);\n }\n}\n\n/**\n * Implementation helper for destroy.\n */\nconst destroyImpl = (builder: GraphBuilder): void => {\n const internal = builder as GraphBuilderImpl;\n internal._subscriptions.forEach((unsubscribe) => unsubscribe());\n internal._subscriptions.clear();\n};\n\n/**\n * Destroy the graph builder and clean up resources.\n */\nexport function destroy(builder: GraphBuilder): void;\nexport function destroy(): (builder: GraphBuilder) => void;\nexport function destroy(builder?: GraphBuilder): void | ((builder: GraphBuilder) => void) {\n if (builder === undefined) {\n // Curried: destroy()\n return (builder: GraphBuilder) => destroyImpl(builder);\n } else {\n // Direct: destroy(builder)\n return destroyImpl(builder);\n }\n}\n\n/**\n * Wait for all pending connector updates to be flushed.\n */\nexport const flush = (builder: GraphBuilder): Promise<void> => {\n return (builder as GraphBuilderImpl)._flushPromise;\n};\n\n//\n// Extension Creation\n//\n\n/**\n * A graph builder extension is used to add nodes to the graph.\n *\n * @param params.id The unique id of the extension.\n * @param params.relation The relation the graph is being expanded from the existing node.\n * @param params.position Affects the order the extensions are processed in.\n * @param params.resolver A function to add nodes to the graph based on just the node id.\n * @param params.connector A function to add nodes to the graph based on a connection to an existing node.\n * @param params.actions A function to add actions to the graph based on a connection to an existing node.\n * @param params.actionGroups A function to add action groups to the graph based on a connection to an existing node.\n */\nexport type CreateExtensionRawOptions = {\n id: string;\n relation?: Node.RelationInput;\n position?: Position;\n resolver?: ResolverExtension;\n connector?: ConnectorExtension;\n actions?: ActionsExtension;\n actionGroups?: ActionGroupsExtension;\n};\n\n/**\n * Create a graph builder extension (low-level API that works directly with Atoms).\n */\nexport const createExtensionRaw = (extension: CreateExtensionRawOptions): BuilderExtension[] => {\n const {\n id,\n position = 'static',\n relation = 'child',\n resolver: _resolver,\n connector: _connector,\n actions: _actions,\n actionGroups: _actionGroups,\n } = extension;\n const normalizedRelation = normalizeRelation(relation);\n const getId = (key: string) => `${id}/${key}`;\n\n const resolver =\n _resolver && Atom.family((id: string) => _resolver(id).pipe(Atom.withLabel(`graph-builder:_resolver:${id}`)));\n\n const connector =\n _connector &&\n Atom.family((node: Atom.Atom<Option.Option<Node.Node>>) =>\n _connector(node).pipe(Atom.withLabel(`graph-builder:_connector:${id}`)),\n );\n\n const actionGroups =\n _actionGroups &&\n Atom.family((node: Atom.Atom<Option.Option<Node.Node>>) =>\n _actionGroups(node).pipe(Atom.withLabel(`graph-builder:_actionGroups:${id}`)),\n );\n\n const actions =\n _actions &&\n Atom.family((node: Atom.Atom<Option.Option<Node.Node>>) =>\n _actions(node).pipe(Atom.withLabel(`graph-builder:_actions:${id}`)),\n );\n\n return [\n resolver ? { id: getId('resolver'), position, resolver } : undefined,\n connector\n ? ({\n id: getId('connector'),\n position,\n relation: normalizedRelation,\n connector: Atom.family((node) =>\n Atom.make((get) => {\n try {\n return get(connector(node));\n } catch (error) {\n log.warn('Error in connector', { id: getId('connector'), node, error });\n return [];\n }\n }).pipe(Atom.withLabel(`graph-builder:connector:${id}`)),\n ),\n } satisfies BuilderExtension)\n : undefined,\n actionGroups\n ? ({\n id: getId('actionGroups'),\n position,\n relation: Node.actionRelation(),\n connector: Atom.family((node) =>\n Atom.make((get) => {\n try {\n return get(actionGroups(node)).map((arg) => ({\n ...arg,\n data: Node.actionGroupSymbol,\n type: Node.ActionGroupType,\n }));\n } catch (error) {\n log.warn('Error in actionGroups', { id: getId('actionGroups'), node, error });\n return [];\n }\n }).pipe(Atom.withLabel(`graph-builder:connector:actionGroups:${id}`)),\n ),\n } satisfies BuilderExtension)\n : undefined,\n actions\n ? ({\n id: getId('actions'),\n position,\n relation: Node.actionRelation(),\n connector: Atom.family((node) =>\n Atom.make((get) => {\n try {\n return get(actions(node)).map((arg) => ({ ...arg, type: Node.ActionType }));\n } catch (error) {\n log.warn('Error in actions', { id: getId('actions'), node, error });\n return [];\n }\n }).pipe(Atom.withLabel(`graph-builder:connector:actions:${id}`)),\n ),\n } satisfies BuilderExtension)\n : undefined,\n ].filter(isNonNullable);\n};\n\n/**\n * Options for creating a graph builder extension with simplified API.\n * All callbacks must return Effects for dependency injection.\n * Effects may fail - errors are caught, logged, and the extension returns empty results.\n */\nexport type CreateExtensionOptions<TMatched = Node.Node, R = never> = {\n id: string;\n match: (node: Node.Node) => Option.Option<TMatched>;\n actions?: (\n matched: TMatched,\n get: Atom.Context,\n ) => Effect.Effect<Omit<Node.NodeArg<Node.ActionData<any>, any>, 'type'>[], Error, R>;\n connector?: (matched: TMatched, get: Atom.Context) => Effect.Effect<Node.NodeArg<any, any>[], Error, R>;\n resolver?: (id: string, get: Atom.Context) => Effect.Effect<Node.NodeArg<any, any> | null, Error, R>;\n relation?: Node.RelationInput;\n position?: Position;\n};\n\n/**\n * Run an Effect synchronously with the provided context.\n * If the effect fails, logs the error and returns the fallback value.\n * @internal\n */\nconst runEffectSyncWithFallback = <T, R>(\n effect: Effect.Effect<T, Error, R>,\n context: Context.Context<R>,\n extensionId: string,\n fallback: T,\n): T => {\n return Effect.runSync(\n effect.pipe(\n Effect.provide(context),\n Effect.catchAll((error) => {\n log.warn('Extension failed', { extension: extensionId, error });\n return Effect.succeed(fallback);\n }),\n ),\n );\n};\n\n/**\n * Create a graph builder extension with simplified API.\n * Returns an Effect to allow callbacks to access services via dependency injection.\n */\nexport const createExtension = <TMatched = Node.Node, R = never>(\n options: CreateExtensionOptions<TMatched, R>,\n): Effect.Effect<BuilderExtension[], never, R> =>\n Effect.map(Effect.context<R>(), (context) => {\n const { id, match, actions, connector, resolver, relation, position } = options;\n\n const connectorExtension = connector ? createConnectorWithRuntime(id, match, connector, context) : undefined;\n\n const actionsExtension = actions\n ? (node: Atom.Atom<Option.Option<Node.Node>>) =>\n Atom.make((get) =>\n Function.pipe(\n get(node),\n Option.flatMap(match),\n Option.map((matched) =>\n runEffectSyncWithFallback(actions(matched, get), context, id, []).map((action) => ({\n ...action,\n // Attach captured context for action execution.\n _actionContext: context,\n })),\n ),\n Option.getOrElse(() => []),\n ),\n )\n : undefined;\n\n const resolverExtension = resolver\n ? (nodeId: string) =>\n Atom.make((get) => runEffectSyncWithFallback(resolver(nodeId, get), context, id, null) ?? null)\n : undefined;\n\n return createExtensionRaw({\n id,\n relation,\n position,\n connector: connectorExtension,\n actions: actionsExtension,\n resolver: resolverExtension,\n });\n });\n\n/**\n * Create a connector extension from a matcher and factory function.\n * The factory's data type is inferred from the matcher's return type.\n */\nexport const createConnector = <TData>(\n matcher: (node: Node.Node) => Option.Option<TData>,\n factory: (data: TData, get: Atom.Context) => Node.NodeArg<any>[],\n): ConnectorExtension => {\n return (node: Atom.Atom<Option.Option<Node.Node>>) =>\n Atom.make((get) =>\n Function.pipe(\n get(node),\n Option.flatMap(matcher),\n Option.map((data) => factory(data, get)),\n Option.getOrElse(() => []),\n ),\n );\n};\n\n/**\n * Create a connector extension from a matcher and factory function with Effect support.\n * The factory must return an Effect. Errors are caught and logged.\n * @internal\n */\nconst createConnectorWithRuntime = <TData, R>(\n extensionId: string,\n matcher: (node: Node.Node) => Option.Option<TData>,\n factory: (data: TData, get: Atom.Context) => Effect.Effect<Node.NodeArg<any>[], Error, R>,\n context: Context.Context<R>,\n): ConnectorExtension => {\n return (node: Atom.Atom<Option.Option<Node.Node>>) =>\n Atom.make((get) =>\n Function.pipe(\n get(node),\n Option.flatMap(matcher),\n Option.map((data) => runEffectSyncWithFallback(factory(data, get), context, extensionId, [])),\n Option.getOrElse(() => []),\n ),\n );\n};\n\n/**\n * Options for creating a type-based extension.\n * All callbacks must return Effects for dependency injection.\n * Effects may fail - errors are caught, logged, and the extension returns empty results.\n */\nexport type CreateTypeExtensionOptions<T extends Type.AnyEntity = Type.AnyEntity, R = never> = {\n id: string;\n type: T;\n actions?: (\n object: Entity.Entity<Schema.Schema.Type<T>>,\n get: Atom.Context,\n ) => Effect.Effect<Omit<Node.NodeArg<Node.ActionData<any>>, 'type'>[], Error, R>;\n connector?: (\n object: Entity.Entity<Schema.Schema.Type<T>>,\n get: Atom.Context,\n ) => Effect.Effect<Node.NodeArg<any>[], Error, R>;\n relation?: Node.RelationInput;\n position?: Position;\n};\n\n/**\n * Create an extension that matches nodes by schema type.\n * The entity type is inferred from the schema type and works for both object and relation schemas.\n * Returns an Effect to allow callbacks to access services via dependency injection.\n */\nexport const createTypeExtension = <T extends Type.AnyEntity, R = never>(\n options: CreateTypeExtensionOptions<T, R>,\n): Effect.Effect<BuilderExtension[], never, R> => {\n const { id, type, actions, connector, relation, position } = options;\n return createExtension<Entity.Entity<Schema.Schema.Type<T>>, R>({\n id,\n match: NodeMatcher.whenEchoType(type),\n actions,\n connector,\n relation,\n position,\n });\n};\n\n//\n// Extension Utilities\n//\n\n/**\n * Qualify node IDs by prefixing with the parent path.\n * Validates that segment IDs do not contain the path separator.\n * Recursively qualifies inline child nodes.\n */\nconst qualifyNodeArgs =\n (parentId: string) =>\n (nodes: Node.NodeArg<any>[]): Node.NodeArg<any>[] =>\n nodes.map((node) => {\n validateSegmentId(node.id);\n const qualified = qualifyId(parentId, node.id);\n return {\n ...node,\n id: qualified,\n nodes: node.nodes ? qualifyNodeArgs(qualified)(node.nodes) : undefined,\n };\n });\n\n/**\n * Recursively collect all inline-descendant IDs (the `nodes` arrays at every level)\n * from a list of top-level NodeArgs. Top-level IDs are excluded because they are\n * already tracked via `_connectorPrevious`.\n */\nconst collectAllInlineIds = (nodes: Node.NodeArg<any>[]): string[] =>\n nodes.flatMap((node) =>\n node.nodes ? [...node.nodes.map((child) => child.id), ...collectAllInlineIds(node.nodes)] : [],\n );\n\nconst connectorKey = (id: string, relation: Node.RelationInput): string => primaryKey(id, Graph.relationKey(relation));\n\nconst relationFromConnectorKey = (key: string): { id: string; relation: Node.Relation } => {\n const [id, encodedRelation] = primaryParts(key);\n return { id, relation: Graph.relationFromKey(encodedRelation) };\n};\n\nconst subscriptionKey = (id: string, kind: string, detail?: string): string =>\n detail != null ? primaryKey(id, kind, detail) : primaryKey(id, kind);\n\nexport const flattenExtensions = (extension: BuilderExtensions, acc: BuilderExtension[] = []): BuilderExtension[] => {\n if (Array.isArray(extension)) {\n return [...acc, ...extension.flatMap((ext) => flattenExtensions(ext, acc))];\n } else {\n return [...acc, extension];\n }\n};\n"],
5
+ "mappings": ";;;;;;;AAAA;;;;;;;;;;;;;;;;;;AAYO,IAAMA,SAAS;AAKf,IAAMC,WAAW;AAKjB,IAAMC,aAAa;AAKnB,IAAMC,kBAAkB;AAqDxB,IAAMC,WAAW,CAACC,MAAcC,YAA+B,gBAA0B;EAAED;EAAMC;AAAU;AAE3G,IAAMC,gBAAgB,CAACD,YAA+B,eA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E,UAAA,gBAAA,eAAA;EAEA;AAGA;IACE,kBAAkByD,CAAAA,IAAAA,MAAY,WAAA,UAAA,OAAA,WAAA,IAAA,MAAA,MAAA,IAAA,WAAA,IAAA,IAAA;IAC5B,oBAAO,CAAA,WAAA,MAAA,CAAA,MAAA;qBAAIyD,SAAAA,GAAAA;WAAQzD;MAAwD,GAAA;MACtE,GAAA,UAAA,QAAA,CAAA,QAAA,kBAAA,KAAA,GAAA,CAAA;IACL;;WAAgBA;MAAU,GAAA;MAC5B;IACA;;;",
6
+ "names": ["RootId", "RootType", "ActionType", "ActionGroupType", "relation", "kind", "direction", "childRelation", "actionRelation", "isGraphNode", "data", "properties", "isAction", "type", "actionGroupSymbol", "Symbol", "isActionGroup", "isActionLike", "make", "arg", "makeAction", "makeActionGroup", "invariant", "SECONDARY", "PATH", "secondaryKey", "parts", "join", "secondaryParts", "key", "split", "a", "keysA", "length", "keysB", "prev", "prevNode", "nextNode", "segmentIds", "lastSlash", "qualifiedId", "make", "Atom", "Registry", "Function", "Option", "Pipeable", "Record", "Event", "Trigger", "todo", "invariant", "log", "isNonNullable", "__dxlog_file", "graphSymbol", "invariant", "graph", "GraphKind", "pipe", "onNodeChanged", "Event", "_onExpand", "_onInitialize", "_onRemoveNode", "_registry", "_expanded", "_pendingExpands", "_initialized", "Record", "empty", "_initialEdges", "_initialNodes", "fromEntries", "id", "type", "RootType", "data", "properties", "make", "initial", "Atom", "keepAlive", "_nodeOrThrow", "family", "node", "_node", "Option", "isSome", "value", "_edges", "parts", "key", "primaryParts", "get", "relation", "edges", "relationKey", "withLabel", "_actions", "_json", "toJSON", "nodes", "obj", "nextSeen", "filter", "root", "registry", "onInitialize", "onExpand", "onRemoveNode", "json", "nodeOrThrow", "connections", "actions", "_constructNode", "internal", "_connections", "connectionKey", "nodeImpl", "getNode", "graphOrId", "nodeOrThrowImpl", "getNodeOrThrow", "connectionsImpl", "getConnections", "idOrRelation", "rel", "getConnectionsImpl", "actionsImpl", "getActions", "edgesImpl", "getEdges", "path", "source", "shouldContinue", "connected", "has", "seen", "traverseImpl", "visitor", "options", "graphOrOptions", "pathArg", "params", "graphOrParams", "getPathImpl", "Promise", "resolve", "trigger", "Trigger", "wake", "interval", "timeout", "finally", "clearInterval", "waitForPath", "waitForPathImpl", "initialized", "log", "normalizedRelation", "normalizeRelation", "primaryKey", "nodeOpt", "isNone", "deferred", "expanded", "expandImpl", "edgesAtom", "relationId", "current", "unsorted", "order", "sorted", "newOrder", "sortEdgesImpl", "addNodeImpl", "graphOrNodes", "existingNode", "nodeAtom", "onSome", "existing", "typeChanged", "dataChanged", "propertiesChanged", "Object", "newNode", "onNone", "pendingKey", "delete", "relationFromKey", "set", "target", "addEdgesImpl", "nodeArg", "graphOrNodeArg", "ids", "removeNodeImpl", "graphOrIds", "edgesArg", "removeNodesImpl", "none", "edgesToRemove", "relationKeyValue", "relatedIds", "entries", "nodeEdges", "isInboundRelation", "direction", "relatedId", "removeEdgesImpl", "edge", "addEdgeImpl", "graphOrEdges", "inverse", "inverseRelation", "inverseId", "sourceAtom", "edgeArg", "sourceList", "targetList", "graphOrEdgeArg", "removeEdgeImpl", "removeOrphans", "removeOrphansArg", "includes", "targetAtom", "targetAfter", "isEmpty", "sourceAfter", "RootId", "secondaryKey", "normalized", "encoded", "directionRaw", "Node", "kind", "encodedRelation", "Option", "Obj", "whenRoot", "node", "id", "RootId", "some", "none", "whenId", "whenNodeType", "type", "whenEchoType", "Obj", "instanceOf", "data", "whenEchoObject", "isObject", "whenAll", "matchers", "first", "candidate", "result", "isNone", "whenAny", "isSome", "whenEchoTypeMatches", "whenEchoObjectMatches", "whenNot", "matcher", "make", "Atom", "Registry", "Array", "Effect", "Function", "Option", "Pipeable", "Record", "scheduleTask", "yieldOrContinue", "log", "byPosition", "getDebugName", "isNonNullable", "__dxlog_file", "pipe", "_connectorPrevious", "_connectorPreviousArgs", "Map", "resolve", "Atom", "_initialized", "_registry", "graph", "make", "Registry", "registry", "onExpand", "onInitialize", "id", "onRemoveNode", "_onRemoveNode", "extensions", "removed", "previous", "filter", "includes", "pid", "key", "ids", "nodes", "currentInlineIds", "collectAllInlineIds", "_connectorPreviousInlineIds", "staleInlineIds", "previousInlineIds", "Graph", "removeNodes", "_graph", "target", "relation", "addNodes", "addEdges", "source", "node", "length", "byPosition", "sortEdges", "_scheduleDirtyFlush", "_flushScheduled", "_flushPromise", "scheduleTask", "_dirtyConnectors", "size", "entries", "_applyConnectorUpdate", "strategy", "_resolvers", "Function", "get", "isNonNullable", "_connectors", "relationFromConnectorKey", "sourceNode", "Option", "undefined", "result", "push", "_onExpand", "_expandRelation", "connectors", "cancel", "subscribe", "qualifyNodeArgs", "rawNodes", "every", "nodeId", "prevArgs", "nodeArgsUnchanged", "immediate", "_subscriptions", "_onInitialize", "log", "resolver", "trigger", "connectorOwned", "values", "match", "onSome", "parentId", "onNone", "primaryParts", "cleanup", "delete", "edges", "flattenExtensions", "forEach", "extension", "internal", "_extensions", "Record", "builder", "builderOrExtensions", "builderOrId", "Node", "RootId", "path", "shouldContinue", "_node", "_constructNode", "nodeArg", "exploreImpl", "visitor", "dispose", "options", "builderOrOptions", "pathArg", "destroyImpl", "normalizedRelation", "normalizeRelation", "getId", "_resolver", "connector", "_connector", "actionGroups", "_actionGroups", "family", "actions", "_actions", "withLabel", "position", "warn", "error", "actionRelation", "arg", "data", "actionGroupSymbol", "type", "ActionType", "context", "extensionId", "connectorExtension", "createConnectorWithRuntime", "actionsExtension", "action", "_actionContext", "resolverExtension", "createExtensionRaw", "createExtension", "whenEchoType", "qualified", "connectorKey", "primaryKey", "encodedRelation", "acc"]
7
+ }