@dxos/app-graph 0.8.2-main.5885341 → 0.8.2-main.600d381

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.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/graph.ts", "../../../src/node.ts", "../../../src/graph-builder.ts"],
4
- "sourcesContent": ["//\n// Copyright 2023 DXOS.org\n//\n\nimport { batch, effect, untracked } from '@preact/signals-core';\n\nimport { asyncTimeout, Trigger } from '@dxos/async';\nimport { invariant } from '@dxos/invariant';\nimport { type Live, live } from '@dxos/live-object';\nimport { log } from '@dxos/log';\nimport { type MakeOptional, isNonNullable, pick } from '@dxos/util';\n\nimport { type Node, type NodeArg, type NodeFilter, type Relation, actionGroupSymbol, isActionLike } from './node';\n\nconst graphSymbol = Symbol('graph');\ntype DeepWriteable<T> = { -readonly [K in keyof T]: T[K] extends object ? DeepWriteable<T[K]> : T[K] };\ntype NodeInternal = DeepWriteable<Node> & { [graphSymbol]: Graph };\n\nexport const getGraph = (node: Node): Graph => {\n const graph = (node as NodeInternal)[graphSymbol];\n invariant(graph, 'Node is not associated with a graph.');\n return graph;\n};\n\nexport const ROOT_ID = 'root';\nexport const ROOT_TYPE = 'dxos.org/type/GraphRoot';\nexport const ACTION_TYPE = 'dxos.org/type/GraphAction';\nexport const ACTION_GROUP_TYPE = 'dxos.org/type/GraphActionGroup';\n\nexport type NodesOptions<TData = any, TProperties extends Record<string, any> = Record<string, any>> = {\n relation?: Relation;\n filter?: NodeFilter<TData, TProperties>;\n expansion?: boolean;\n type?: string;\n};\n\n// TODO(wittjosiah): Consider having default be undefined. This is current default for backwards compatibility.\nconst DEFAULT_FILTER = (node: Node) => untracked(() => !isActionLike(node));\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, path: string[]) => boolean | void;\n\n /**\n * The node to start traversing from.\n *\n * @default root\n */\n node?: Node;\n\n /**\n * The relation to traverse graph edges.\n *\n * @default 'outbound'\n */\n relation?: Relation;\n\n /**\n * Allow traversal to trigger expansion of the graph via `onInitialNodes`.\n */\n expansion?: boolean;\n};\n\nexport type GraphParams = {\n nodes?: MakeOptional<Node, 'data' | 'cacheable'>[];\n edges?: Record<string, string[]>;\n onInitialNode?: Graph['_onInitialNode'];\n onInitialNodes?: Graph['_onInitialNodes'];\n onRemoveNode?: Graph['_onRemoveNode'];\n};\n\n/**\n * The Graph represents the structure of the application constructed via plugins.\n */\nexport class Graph {\n private readonly _onInitialNode?: (id: string) => Promise<void>;\n private readonly _onInitialNodes?: (node: Node, relation: Relation, type?: string) => Promise<void>;\n private readonly _onRemoveNode?: (id: string) => Promise<void>;\n\n private readonly _waitingForNodes: Record<string, Trigger<Node>> = {};\n private readonly _initialized: Record<string, boolean> = {};\n\n /**\n * @internal\n */\n readonly _nodes: Record<string, Live<NodeInternal>> = {};\n\n /**\n * @internal\n */\n readonly _edges: Record<string, Live<{ inbound: string[]; outbound: string[] }>> = {};\n\n constructor({ nodes, edges, onInitialNode, onInitialNodes, onRemoveNode }: GraphParams = {}) {\n this._onInitialNode = onInitialNode;\n this._onInitialNodes = onInitialNodes;\n this._onRemoveNode = onRemoveNode;\n\n this._nodes[ROOT_ID] = this._constructNode({\n id: ROOT_ID,\n type: ROOT_TYPE,\n cacheable: [],\n properties: {},\n data: null,\n });\n if (nodes) {\n nodes.forEach((node) => {\n const cacheable = Object.keys(node.properties ?? {});\n if (node.type === ACTION_TYPE) {\n this._addNode({ cacheable, data: () => log.warn('Pickled action invocation'), ...node });\n } else if (node.type === ACTION_GROUP_TYPE) {\n this._addNode({ cacheable, data: actionGroupSymbol, ...node });\n } else {\n this._addNode({ cacheable, ...node });\n }\n });\n }\n\n this._edges[ROOT_ID] = live({ inbound: [], outbound: [] });\n if (edges) {\n Object.entries(edges).forEach(([source, edges]) => {\n edges.forEach((target) => {\n this._addEdge({ source, target });\n });\n this._sortEdges(source, 'outbound', edges);\n });\n }\n }\n\n static from(pickle: string, options: Omit<GraphParams, 'nodes' | 'edges'> = {}) {\n const { nodes, edges } = JSON.parse(pickle);\n return new Graph({ nodes, edges, ...options });\n }\n\n /**\n * Alias for `findNode('root')`.\n */\n get root() {\n return this.findNode(ROOT_ID)!;\n }\n\n /**\n * Convert the graph to a JSON object.\n */\n toJSON({ id = ROOT_ID, maxLength = 32 }: { id?: string; maxLength?: number } = {}) {\n const toJSON = (node: Node, seen: string[] = []): any => {\n const nodes = this.nodes(node);\n const obj: Record<string, any> = {\n id: node.id.length > maxLength ? `${node.id.slice(0, maxLength - 3)}...` : 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) => {\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 = this.findNode(id);\n invariant(root, `Node not found: ${id}`);\n return toJSON(root);\n }\n\n pickle() {\n const nodes = Object.values(this._nodes)\n .filter((node) => !!node.cacheable)\n .map((node) => {\n return {\n id: node.id,\n type: node.type,\n properties: pick(node.properties, node.cacheable!),\n };\n });\n\n const cacheable = new Set(nodes.map((node) => node.id));\n\n const edges = Object.fromEntries(\n Object.entries(this._edges)\n .filter(([id]) => cacheable.has(id))\n .map(([id, { outbound }]): [string, string[]] => [id, outbound.filter((nodeId) => cacheable.has(nodeId))])\n // TODO(wittjosiah): Why sort?\n .toSorted(([a], [b]) => a.localeCompare(b)),\n );\n\n return JSON.stringify({ nodes, edges });\n }\n\n /**\n * Find the node with the given id in the graph.\n *\n * If a node is not found within the graph and an `onInitialNode` callback is provided,\n * it is called with the id and type of the node, potentially initializing the node.\n */\n findNode(id: string, expansion = true): Node | undefined {\n const existingNode = this._nodes[id];\n if (!existingNode && expansion) {\n void this._onInitialNode?.(id);\n }\n\n return existingNode;\n }\n\n /**\n * Wait for a node to be added to the graph.\n *\n * If the node is already present in the graph, the promise resolves immediately.\n *\n * @param id The id of the node to wait for.\n * @param timeout The time in milliseconds to wait for the node to be added.\n */\n async waitForNode(id: string, timeout?: number): Promise<Node> {\n const trigger = this._waitingForNodes[id] ?? (this._waitingForNodes[id] = new Trigger<Node>());\n const node = this.findNode(id);\n if (node) {\n delete this._waitingForNodes[id];\n return node;\n }\n\n if (timeout === undefined) {\n return trigger.wait();\n } else {\n return asyncTimeout(trigger.wait(), timeout, `Node not found: ${id}`);\n }\n }\n\n /**\n * Nodes that this node is connected to in default order.\n */\n nodes<TData = any, TProperties extends Record<string, any> = Record<string, any>>(\n node: Node,\n options: NodesOptions<TData, TProperties> = {},\n ) {\n const { relation, expansion, filter = DEFAULT_FILTER, type } = options;\n const nodes = this._getNodes({ node, relation, expansion, type });\n return nodes.filter((n) => filter(n, node));\n }\n\n /**\n * Edges that this node is connected to in default order.\n */\n edges(node: Node, { relation = 'outbound' }: { relation?: Relation } = {}) {\n return this._edges[node.id]?.[relation] ?? [];\n }\n\n /**\n * Actions or action groups that this node is connected to in default order.\n */\n actions(node: Node, { expansion }: { expansion?: boolean } = {}) {\n return [\n ...this._getNodes({ node, expansion, type: ACTION_GROUP_TYPE }),\n ...this._getNodes({ node, expansion, type: ACTION_TYPE }),\n ];\n }\n\n async expand(node: Node, relation: Relation = 'outbound', type?: string) {\n const key = this._key(node, relation, type);\n const initialized = this._initialized[key];\n if (!initialized && this._onInitialNodes) {\n await this._onInitialNodes(node, relation, type);\n this._initialized[key] = true;\n }\n }\n\n private _key(node: Node, relation: Relation, type?: string) {\n return `${node.id}-${relation}-${type}`;\n }\n\n /**\n * Recursive depth-first traversal of the graph.\n *\n * @param options.node The node to start traversing from.\n * @param options.relation The relation to traverse graph edges.\n * @param options.visitor A callback which is called for each node visited during traversal.\n */\n traverse(\n { visitor, node = this.root, relation = 'outbound', expansion }: GraphTraversalOptions,\n path: string[] = [],\n ): void {\n // Break cycles.\n if (path.includes(node.id)) {\n return;\n }\n\n const shouldContinue = visitor(node, [...path, node.id]);\n if (shouldContinue === false) {\n return;\n }\n\n Object.values(this._getNodes({ node, relation, expansion })).forEach((child) =>\n this.traverse({ node: child, relation, visitor, expansion }, [...path, node.id]),\n );\n }\n\n /**\n * Recursive depth-first traversal of the graph wrapping each visitor call in an effect.\n *\n * @param options.node The node to start traversing from.\n * @param options.relation The relation to traverse graph edges.\n * @param options.visitor A callback which is called for each node visited during traversal.\n */\n subscribeTraverse(\n { visitor, node = this.root, relation = 'outbound', expansion }: GraphTraversalOptions,\n currentPath: string[] = [],\n ) {\n return effect(() => {\n const path = [...currentPath, node.id];\n const result = visitor(node, path);\n if (result === false) {\n return;\n }\n\n const nodes = this._getNodes({ node, relation, expansion });\n const nodeSubscriptions = nodes.map((n) => this.subscribeTraverse({ node: n, visitor, expansion }, path));\n return () => {\n nodeSubscriptions.forEach((unsubscribe) => unsubscribe());\n };\n });\n }\n\n /**\n * Get the path between two nodes in the graph.\n */\n getPath({ source = 'root', target }: { source?: string; target: string }): string[] | undefined {\n const start = this.findNode(source);\n if (!start) {\n return undefined;\n }\n\n let found: string[] | undefined;\n this.traverse({\n node: start,\n visitor: (node, path) => {\n if (found) {\n return false;\n }\n\n if (node.id === target) {\n found = path;\n }\n },\n });\n\n return found;\n }\n\n /**\n * Wait for the path between two nodes in the graph to be established.\n */\n async waitForPath(\n params: { source?: string; target: string },\n { timeout = 5_000, interval = 500 }: { timeout?: number; interval?: number } = {},\n ) {\n const path = this.getPath(params);\n if (path) {\n return path;\n }\n\n const trigger = new Trigger<string[]>();\n const i = setInterval(() => {\n const path = this.getPath(params);\n if (path) {\n trigger.wake(path);\n }\n }, interval);\n\n return trigger.wait({ timeout }).finally(() => clearInterval(i));\n }\n\n /**\n * Add nodes to the graph.\n *\n * @internal\n */\n _addNodes<TData = null, TProperties extends Record<string, any> = Record<string, any>>(\n nodes: NodeArg<TData, TProperties>[],\n ): Node<TData, TProperties>[] {\n return batch(() => nodes.map((node) => this._addNode(node)));\n }\n\n private _addNode<TData, TProperties extends Record<string, any> = Record<string, any>>({\n nodes,\n edges,\n ..._node\n }: NodeArg<TData, TProperties>): Node<TData, TProperties> {\n return untracked(() => {\n const existingNode = this._nodes[_node.id];\n const node = existingNode ?? this._constructNode({ data: null, properties: {}, ..._node });\n if (existingNode) {\n const { data = null, properties, type } = _node;\n if (data !== node.data) {\n node.data = data;\n }\n\n if (type !== node.type) {\n node.type = type;\n }\n\n for (const key in properties) {\n if (properties[key] !== node.properties[key]) {\n node.properties[key] = properties[key];\n }\n }\n } else {\n this._nodes[node.id] = node;\n this._edges[node.id] = live({ inbound: [], outbound: [] });\n }\n\n const trigger = this._waitingForNodes[node.id];\n if (trigger) {\n trigger.wake(node);\n delete this._waitingForNodes[node.id];\n }\n\n if (nodes) {\n nodes.forEach((subNode) => {\n this._addNode(subNode);\n this._addEdge({ source: node.id, target: subNode.id });\n });\n }\n\n if (edges) {\n edges.forEach(([id, relation]) =>\n relation === 'outbound'\n ? this._addEdge({ source: node.id, target: id })\n : this._addEdge({ source: id, target: node.id }),\n );\n }\n\n return node as unknown as Node<TData, TProperties>;\n });\n }\n\n /**\n * Remove nodes from the graph.\n *\n * @param ids The id of the node to remove.\n * @param edges Whether to remove edges connected to the node from the graph as well.\n * @internal\n */\n _removeNodes(ids: string[], edges = false) {\n batch(() => ids.forEach((id) => this._removeNode(id, edges)));\n }\n\n private _removeNode(id: string, edges = false) {\n untracked(() => {\n const node = this.findNode(id, false);\n if (!node) {\n return;\n }\n\n if (edges) {\n // Remove edges from connected nodes.\n this._getNodes({ node }).forEach((node) => {\n this._removeEdge({ source: id, target: node.id });\n });\n this._getNodes({ node, relation: 'inbound' }).forEach((node) => {\n this._removeEdge({ source: node.id, target: id });\n });\n\n // Remove edges from node.\n delete this._edges[id];\n }\n\n // Remove node.\n delete this._nodes[id];\n Object.keys(this._initialized)\n .filter((key) => key.startsWith(id))\n .forEach((key) => {\n delete this._initialized[key];\n });\n void this._onRemoveNode?.(id);\n });\n }\n\n /**\n * Add edges to the graph.\n *\n * @internal\n */\n _addEdges(edges: { source: string; target: string }[]) {\n batch(() => edges.forEach((edge) => this._addEdge(edge)));\n }\n\n private _addEdge({ source, target }: { source: string; target: string }) {\n untracked(() => {\n if (!this._edges[source]) {\n this._edges[source] = live({ inbound: [], outbound: [] });\n }\n if (!this._edges[target]) {\n this._edges[target] = live({ inbound: [], outbound: [] });\n }\n\n const sourceEdges = this._edges[source];\n if (!sourceEdges.outbound.includes(target)) {\n sourceEdges.outbound.push(target);\n }\n\n const targetEdges = this._edges[target];\n if (!targetEdges.inbound.includes(source)) {\n targetEdges.inbound.push(source);\n }\n });\n }\n\n /**\n * Remove edges from the graph.\n * @internal\n */\n _removeEdges(edges: { source: string; target: string }[], removeOrphans = false) {\n batch(() => edges.forEach((edge) => this._removeEdge(edge, removeOrphans)));\n }\n\n private _removeEdge({ source, target }: { source: string; target: string }, removeOrphans = false) {\n untracked(() => {\n batch(() => {\n const outboundIndex = this._edges[source]?.outbound.findIndex((id) => id === target);\n if (outboundIndex !== undefined && outboundIndex !== -1) {\n this._edges[source].outbound.splice(outboundIndex, 1);\n }\n\n const inboundIndex = this._edges[target]?.inbound.findIndex((id) => id === source);\n if (inboundIndex !== undefined && inboundIndex !== -1) {\n this._edges[target].inbound.splice(inboundIndex, 1);\n }\n\n if (removeOrphans) {\n if (\n this._edges[source]?.outbound.length === 0 &&\n this._edges[source]?.inbound.length === 0 &&\n source !== ROOT_ID\n ) {\n this._removeNode(source, true);\n }\n if (\n this._edges[target]?.outbound.length === 0 &&\n this._edges[target]?.inbound.length === 0 &&\n target !== ROOT_ID\n ) {\n this._removeNode(target, true);\n }\n }\n });\n });\n }\n\n /**\n * Sort edges for a node.\n *\n * Edges not included in the sorted list are appended to the end of the list.\n *\n * @param nodeId The id of the node to sort edges for.\n * @param relation The relation of the edges from the node to sort.\n * @param edges The ordered list of edges.\n * @ignore\n */\n _sortEdges(nodeId: string, relation: Relation, edges: string[]) {\n untracked(() => {\n batch(() => {\n const current = this._edges[nodeId];\n if (current) {\n const unsorted = current[relation].filter((id) => !edges.includes(id)) ?? [];\n const sorted = edges.filter((id) => current[relation].includes(id)) ?? [];\n current[relation].splice(0, current[relation].length, ...[...sorted, ...unsorted]);\n }\n });\n });\n }\n\n private _constructNode = (node: Omit<Node, typeof graphSymbol>) => {\n return live<NodeInternal>({ ...node, [graphSymbol]: this });\n };\n\n private _getNodes({\n node,\n relation = 'outbound',\n type,\n expansion,\n }: {\n node: Node;\n relation?: Relation;\n type?: string;\n expansion?: boolean;\n }): Node[] {\n if (expansion) {\n void this.expand(node, relation, type);\n }\n\n const edges = this._edges[node.id];\n if (!edges) {\n return [];\n } else {\n return edges[relation]\n .map((id) => this._nodes[id])\n .filter(isNonNullable)\n .filter((n) => !type || n.type === type);\n }\n }\n}\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { type MaybePromise, type MakeOptional } from '@dxos/util';\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 Relation = 'outbound' | 'inbound';\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, Relation][];\n};\n\n//\n// Actions\n//\n\nexport type InvokeParams = {\n /** Node the invoked action is connected to. */\n node: Node;\n\n caller?: string;\n};\n\nexport type ActionData = (params: InvokeParams) => MaybePromise<void>;\n\nexport type Action<TProperties extends Record<string, any> = Record<string, any>> = Readonly<\n Omit<Node<ActionData, TProperties>, 'properties'> & {\n properties: Readonly<TProperties>;\n }\n>;\n\nexport const isAction = (data: unknown): data is Action =>\n isGraphNode(data) ? typeof data.data === 'function' : 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 : false;\n\nexport type ActionLike = Action | ActionGroup;\n\nexport const isActionLike = (data: unknown): data is Action | ActionGroup => isAction(data) || isActionGroup(data);\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { effect, type Signal, signal, untracked } from '@preact/signals-core';\n\nimport { Trigger, type CleanupFn } from '@dxos/async';\nimport { invariant } from '@dxos/invariant';\nimport { live } from '@dxos/live-object';\nimport { log } from '@dxos/log';\nimport { byPosition, type Position, isNode, type MaybePromise, isNonNullable } from '@dxos/util';\n\nimport { ACTION_GROUP_TYPE, ACTION_TYPE, Graph, ROOT_ID, type GraphParams } from './graph';\nimport { type ActionData, actionGroupSymbol, type Node, type NodeArg, type Relation } from './node';\n\nconst NODE_RESOLVER_TIMEOUT = 1_000;\n\n/**\n * Graph builder extension for adding nodes to the graph based on just the node id.\n * This is useful for creating the first node in a graph or for hydrating cached nodes with data.\n *\n * @param params.id The id of the node to resolve.\n */\nexport type ResolverExtension = (params: { id: string }) => NodeArg<any> | false | undefined;\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<T = any> = (params: { node: Node<T> }) => NodeArg<any>[] | undefined;\n\n/**\n * Constrained case of the connector extension for more easily adding actions to the graph.\n */\nexport type ActionsExtension<T = any> = (params: {\n node: Node<T>;\n}) => Omit<NodeArg<ActionData>, 'type' | 'nodes' | 'edges'>[] | undefined;\n\n/**\n * Constrained case of the connector extension for more easily adding action groups to the graph.\n */\nexport type ActionGroupsExtension<T = any> = (params: {\n node: Node<T>;\n}) => Omit<NodeArg<typeof actionGroupSymbol>, 'type' | 'data' | 'nodes' | 'edges'>[] | undefined;\n\ntype GuardedNodeType<T> = T extends (value: any) => value is infer N ? (N extends Node<infer D> ? D : unknown) : never;\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.type If provided, all nodes returned are expected to have this type.\n * @param params.disposition Affects the order the extensions are processed in.\n * @param params.filter A filter function to determine if an extension should act on a node.\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 CreateExtensionOptions<T = any> = {\n id: string;\n relation?: Relation;\n type?: string;\n position?: Position;\n filter?: (node: Node) => node is Node<T>;\n resolver?: ResolverExtension;\n connector?: ConnectorExtension<GuardedNodeType<CreateExtensionOptions<T>['filter']>>;\n actions?: ActionsExtension<GuardedNodeType<CreateExtensionOptions<T>['filter']>>;\n actionGroups?: ActionGroupsExtension<GuardedNodeType<CreateExtensionOptions<T>['filter']>>;\n};\n\n/**\n * Create a graph builder extension.\n */\nexport const createExtension = <T = any>(extension: CreateExtensionOptions<T>): BuilderExtension[] => {\n const { id, position = 'static', resolver, connector, actions, actionGroups, ...rest } = extension;\n const getId = (key: string) => `${id}/${key}`;\n return [\n resolver ? { id: getId('resolver'), position, resolver } : undefined,\n connector ? { ...rest, id: getId('connector'), position, connector } : undefined,\n actionGroups\n ? ({\n ...rest,\n id: getId('actionGroups'),\n position,\n type: ACTION_GROUP_TYPE,\n relation: 'outbound',\n connector: ({ node }) =>\n actionGroups({ node })?.map((arg) => ({ ...arg, data: actionGroupSymbol, type: ACTION_GROUP_TYPE })),\n } satisfies BuilderExtension)\n : undefined,\n actions\n ? ({\n ...rest,\n id: getId('actions'),\n position,\n type: ACTION_TYPE,\n relation: 'outbound',\n connector: ({ node }) => actions({ node })?.map((arg) => ({ ...arg, type: ACTION_TYPE })),\n } satisfies BuilderExtension)\n : undefined,\n ].filter(isNonNullable);\n};\n\nexport type GraphBuilderTraverseOptions = {\n visitor: (node: Node, path: string[]) => MaybePromise<boolean | void>;\n node?: Node;\n relation?: Relation;\n};\n\n/**\n * The dispatcher is used to keep track of the current extension and state when memoizing functions.\n */\nclass Dispatcher {\n currentExtension?: string;\n stateIndex = 0;\n state: Record<string, any[]> = {};\n cleanup: (() => void)[] = [];\n}\n\nclass BuilderInternal {\n // This must be static to avoid passing the dispatcher instance to every memoized function.\n // If the dispatcher is not set that means that the memoized function is being called outside of the graph builder.\n static currentDispatcher?: Dispatcher;\n}\n\n/**\n * Allows code to be memoized within the context of a graph builder extension.\n * This is useful for creating instances which should be subscribed to rather than recreated.\n */\nexport const memoize = <T>(fn: () => T, key = 'result'): T => {\n const dispatcher = BuilderInternal.currentDispatcher;\n invariant(dispatcher?.currentExtension, 'memoize must be called within an extension');\n const all = dispatcher.state[dispatcher.currentExtension][dispatcher.stateIndex] ?? {};\n const current = all[key];\n const result = current ? current.result : fn();\n dispatcher.state[dispatcher.currentExtension][dispatcher.stateIndex] = { ...all, [key]: { result } };\n dispatcher.stateIndex++;\n return result;\n};\n\n/**\n * Register a cleanup function to be called when the graph builder is destroyed.\n */\nexport const cleanup = (fn: () => void): void => {\n memoize(() => {\n const dispatcher = BuilderInternal.currentDispatcher;\n invariant(dispatcher, 'cleanup must be called within an extension');\n dispatcher.cleanup.push(fn);\n });\n};\n\n/**\n * Convert a subscribe/get pair into a signal.\n */\nexport const toSignal = <T>(\n subscribe: (onChange: () => void) => () => void,\n get: () => T | undefined,\n key?: string,\n) => {\n const thisSignal = memoize(() => {\n return signal(get());\n }, key);\n const unsubscribe = memoize(() => {\n return subscribe(() => (thisSignal.value = get()));\n }, key);\n cleanup(() => {\n unsubscribe();\n });\n return thisSignal.value;\n};\n\nexport type BuilderExtension = Readonly<{\n id: string;\n position: Position;\n resolver?: ResolverExtension;\n connector?: ConnectorExtension;\n // Only for connector.\n relation?: Relation;\n type?: string;\n filter?: (node: Node) => boolean;\n}>;\n\ntype ExtensionArg = BuilderExtension | BuilderExtension[] | ExtensionArg[];\n\nexport const flattenExtensions = (extension: ExtensionArg, 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\n/**\n * The builder provides an extensible way to compose the construction of the graph.\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.\nexport class GraphBuilder {\n private readonly _dispatcher = new Dispatcher();\n private readonly _extensions = live<Record<string, BuilderExtension>>({});\n private readonly _resolverSubscriptions = new Map<string, CleanupFn>();\n private readonly _connectorSubscriptions = new Map<string, CleanupFn>();\n private readonly _nodeChanged: Record<string, Signal<{}>> = {};\n private readonly _initialized: Record<string, Trigger> = {};\n private _graph: Graph;\n\n constructor(params: Pick<GraphParams, 'nodes' | 'edges'> = {}) {\n this._graph = new Graph({\n ...params,\n onInitialNode: async (id) => this._onInitialNode(id),\n onInitialNodes: async (node, relation, type) => this._onInitialNodes(node, relation, type),\n onRemoveNode: (id) => this._onRemoveNode(id),\n });\n }\n\n static from(pickle?: string) {\n if (!pickle) {\n return new GraphBuilder();\n }\n\n const { nodes, edges } = JSON.parse(pickle);\n return new GraphBuilder({ nodes, edges });\n }\n\n /**\n * If graph is being restored from a pickle, the data will be null.\n * Initialize the data of each node by calling resolvers.\n * Wait until all of the initial nodes have resolved.\n */\n async initialize() {\n Object.keys(this._graph._nodes)\n .filter((id) => id !== ROOT_ID)\n .forEach((id) => (this._initialized[id] = new Trigger()));\n Object.keys(this._graph._nodes).forEach((id) => this._onInitialNode(id));\n await Promise.all(\n Object.entries(this._initialized).map(async ([id, trigger]) => {\n try {\n await trigger.wait({ timeout: NODE_RESOLVER_TIMEOUT });\n } catch {\n log.error('node resolver timeout', { id });\n this.graph._removeNodes([id]);\n }\n }),\n );\n }\n\n get graph() {\n return this._graph;\n }\n\n /**\n * @reactive\n */\n get extensions() {\n return Object.values(this._extensions);\n }\n\n /**\n * Register a node builder which will be called in order to construct the graph.\n */\n addExtension(extension: ExtensionArg): GraphBuilder {\n const extensions = flattenExtensions(extension);\n untracked(() => {\n extensions.forEach((extension) => {\n this._dispatcher.state[extension.id] = [];\n this._extensions[extension.id] = extension;\n });\n });\n return this;\n }\n\n /**\n * Remove a node builder from the graph builder.\n */\n removeExtension(id: string): GraphBuilder {\n untracked(() => {\n delete this._extensions[id];\n });\n return this;\n }\n\n destroy() {\n this._dispatcher.cleanup.forEach((fn) => fn());\n this._resolverSubscriptions.forEach((unsubscribe) => unsubscribe());\n this._connectorSubscriptions.forEach((unsubscribe) => unsubscribe());\n this._resolverSubscriptions.clear();\n this._connectorSubscriptions.clear();\n }\n\n /**\n * A graph traversal using just the connector extensions, without subscribing to any signals or persisting any nodes.\n */\n async explore(\n { node = this._graph.root, relation = 'outbound', visitor }: GraphBuilderTraverseOptions,\n path: string[] = [],\n ) {\n // Break cycles.\n if (path.includes(node.id)) {\n return;\n }\n\n // TODO(wittjosiah): This is a workaround for esm not working in the test runner.\n // Switching to vitest is blocked by having node esm versions of echo-schema & echo-signals.\n if (!isNode()) {\n const { yieldOrContinue } = await import('main-thread-scheduling');\n await yieldOrContinue('idle');\n }\n const shouldContinue = await visitor(node, [...path, node.id]);\n if (shouldContinue === false) {\n return;\n }\n\n const nodes = Object.values(this._extensions)\n .filter((extension) => relation === (extension.relation ?? 'outbound'))\n .filter((extension) => !extension.filter || extension.filter(node))\n .flatMap((extension) => {\n this._dispatcher.currentExtension = extension.id;\n this._dispatcher.stateIndex = 0;\n BuilderInternal.currentDispatcher = this._dispatcher;\n const result = extension.connector?.({ node }) ?? [];\n BuilderInternal.currentDispatcher = undefined;\n return result;\n })\n .map(\n (arg): Node => ({\n id: arg.id,\n type: arg.type,\n cacheable: arg.cacheable,\n data: arg.data ?? null,\n properties: arg.properties ?? {},\n }),\n );\n\n await Promise.all(nodes.map((n) => this.explore({ node: n, relation, visitor }, [...path, node.id])));\n }\n\n private _onInitialNode(nodeId: string) {\n this._nodeChanged[nodeId] = this._nodeChanged[nodeId] ?? signal({});\n this._resolverSubscriptions.set(\n nodeId,\n effect(() => {\n const extensions = Object.values(this._extensions).toSorted(byPosition);\n for (const { id, resolver } of extensions) {\n if (!resolver) {\n continue;\n }\n\n this._dispatcher.currentExtension = id;\n this._dispatcher.stateIndex = 0;\n BuilderInternal.currentDispatcher = this._dispatcher;\n let node: NodeArg<any> | false | undefined;\n try {\n node = resolver({ id: nodeId });\n } catch (err) {\n log.catch(err, { extension: id });\n log.error(`Previous error occurred in extension: ${id}`);\n } finally {\n BuilderInternal.currentDispatcher = undefined;\n }\n\n const trigger = this._initialized[nodeId];\n if (node) {\n this.graph._addNodes([node]);\n trigger?.wake();\n if (this._nodeChanged[node.id]) {\n this._nodeChanged[node.id].value = {};\n }\n break;\n } else if (node === false) {\n this.graph._removeNodes([nodeId]);\n trigger?.wake();\n break;\n }\n }\n }),\n );\n }\n\n private _onInitialNodes(node: Node, nodesRelation: Relation, nodesType?: string) {\n this._nodeChanged[node.id] = this._nodeChanged[node.id] ?? signal({});\n let first = true;\n let previous: string[] = [];\n this._connectorSubscriptions.set(\n node.id,\n effect(() => {\n // TODO(wittjosiah): This is a workaround for a race between the node removal and the effect re-running.\n // To cause this case to happen, remove a collection and then undo the removal.\n if (!first && !this._connectorSubscriptions.has(node.id)) {\n return;\n }\n first = false;\n\n // Subscribe to extensions being added.\n Object.keys(this._extensions);\n // Subscribe to connected node changes.\n this._nodeChanged[node.id].value;\n\n // TODO(wittjosiah): Consider allowing extensions to collaborate on the same node by merging their results.\n const nodes: NodeArg<any>[] = [];\n const extensions = Object.values(this._extensions).toSorted(byPosition);\n for (const { id, connector, filter, type, relation = 'outbound' } of extensions) {\n if (\n !connector ||\n relation !== nodesRelation ||\n (nodesType && type !== nodesType) ||\n (filter && !filter(node))\n ) {\n continue;\n }\n\n this._dispatcher.currentExtension = id;\n this._dispatcher.stateIndex = 0;\n BuilderInternal.currentDispatcher = this._dispatcher;\n try {\n nodes.push(...(connector({ node }) ?? []));\n } catch (err) {\n log.catch(err, { extension: id });\n log.error(`Previous error occurred in extension: ${id}`);\n } finally {\n BuilderInternal.currentDispatcher = undefined;\n }\n }\n\n const ids = nodes.map((n) => n.id);\n const removed = previous.filter((id) => !ids.includes(id));\n previous = ids;\n\n // Remove edges and only remove nodes that are orphaned.\n this.graph._removeEdges(\n removed.map((target) => ({ source: node.id, target })),\n true,\n );\n this.graph._addNodes(nodes);\n this.graph._addEdges(\n nodes.map(({ id }) =>\n nodesRelation === 'outbound' ? { source: node.id, target: id } : { source: id, target: node.id },\n ),\n );\n this.graph._sortEdges(\n node.id,\n nodesRelation,\n nodes.map(({ id }) => id),\n );\n nodes.forEach((n) => {\n if (this._nodeChanged[n.id]) {\n this._nodeChanged[n.id].value = {};\n }\n });\n }),\n );\n }\n\n private async _onRemoveNode(nodeId: string) {\n this._resolverSubscriptions.get(nodeId)?.();\n this._connectorSubscriptions.get(nodeId)?.();\n this._resolverSubscriptions.delete(nodeId);\n this._connectorSubscriptions.delete(nodeId);\n }\n}\n"],
4
+ "sourcesContent": ["//\n// Copyright 2023 DXOS.org\n//\n\nimport { batch, effect, untracked } from '@preact/signals-core';\n\nimport { asyncTimeout, Trigger } from '@dxos/async';\nimport { invariant } from '@dxos/invariant';\nimport { type Live, live } from '@dxos/live-object';\nimport { log } from '@dxos/log';\nimport { type MakeOptional, isNonNullable, pick } from '@dxos/util';\n\nimport { type Node, type NodeArg, type NodeFilter, type Relation, actionGroupSymbol, isActionLike } from './node';\n\nconst graphSymbol = Symbol('graph');\ntype DeepWriteable<T> = { -readonly [K in keyof T]: T[K] extends object ? DeepWriteable<T[K]> : T[K] };\ntype NodeInternal = DeepWriteable<Node> & { [graphSymbol]: Graph };\n\nexport const getGraph = (node: Node): Graph => {\n const graph = (node as NodeInternal)[graphSymbol];\n invariant(graph, 'Node is not associated with a graph.');\n return graph;\n};\n\nexport const ROOT_ID = 'root';\nexport const ROOT_TYPE = 'dxos.org/type/GraphRoot';\nexport const ACTION_TYPE = 'dxos.org/type/GraphAction';\nexport const ACTION_GROUP_TYPE = 'dxos.org/type/GraphActionGroup';\n\nexport type NodesOptions<TData = any, TProperties extends Record<string, any> = Record<string, any>> = {\n relation?: Relation;\n filter?: NodeFilter<TData, TProperties>;\n expansion?: boolean;\n type?: string;\n};\n\n// TODO(wittjosiah): Consider having default be undefined. This is current default for backwards compatibility.\nconst DEFAULT_FILTER = (node: Node) => untracked(() => !isActionLike(node));\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, path: string[]) => boolean | void;\n\n /**\n * The node to start traversing from.\n *\n * @default root\n */\n node?: Node;\n\n /**\n * The relation to traverse graph edges.\n *\n * @default 'outbound'\n */\n relation?: Relation;\n\n /**\n * Allow traversal to trigger expansion of the graph via `onInitialNodes`.\n */\n expansion?: boolean;\n};\n\nexport type GraphParams = {\n nodes?: MakeOptional<Node, 'data' | 'cacheable'>[];\n edges?: Record<string, string[]>;\n onInitialNode?: Graph['_onInitialNode'];\n onInitialNodes?: Graph['_onInitialNodes'];\n onRemoveNode?: Graph['_onRemoveNode'];\n};\n\n/**\n * The Graph represents the structure of the application constructed via plugins.\n */\nexport class Graph {\n private readonly _onInitialNode?: (id: string) => Promise<void>;\n private readonly _onInitialNodes?: (node: Node, relation: Relation, type?: string) => Promise<void>;\n private readonly _onRemoveNode?: (id: string) => Promise<void>;\n\n private readonly _waitingForNodes: Record<string, Trigger<Node>> = {};\n private readonly _initialized: Record<string, boolean> = {};\n\n /**\n * @internal\n */\n readonly _nodes: Record<string, Live<NodeInternal>> = {};\n\n /**\n * @internal\n */\n readonly _edges: Record<string, Live<{ inbound: string[]; outbound: string[] }>> = {};\n\n constructor({ nodes, edges, onInitialNode, onInitialNodes, onRemoveNode }: GraphParams = {}) {\n this._onInitialNode = onInitialNode;\n this._onInitialNodes = onInitialNodes;\n this._onRemoveNode = onRemoveNode;\n\n this._nodes[ROOT_ID] = this._constructNode({\n id: ROOT_ID,\n type: ROOT_TYPE,\n cacheable: [],\n properties: {},\n data: null,\n });\n if (nodes) {\n nodes.forEach((node) => {\n const cacheable = Object.keys(node.properties ?? {});\n if (node.type === ACTION_TYPE) {\n this._addNode({ cacheable, data: () => log.warn('Pickled action invocation'), ...node });\n } else if (node.type === ACTION_GROUP_TYPE) {\n this._addNode({ cacheable, data: actionGroupSymbol, ...node });\n } else {\n this._addNode({ cacheable, ...node });\n }\n });\n }\n\n this._edges[ROOT_ID] = live({ inbound: [], outbound: [] });\n if (edges) {\n Object.entries(edges).forEach(([source, edges]) => {\n edges.forEach((target) => {\n this._addEdge({ source, target });\n });\n this._sortEdges(source, 'outbound', edges);\n });\n }\n }\n\n static from(pickle: string, options: Omit<GraphParams, 'nodes' | 'edges'> = {}) {\n const { nodes, edges } = JSON.parse(pickle);\n return new Graph({ nodes, edges, ...options });\n }\n\n /**\n * Alias for `findNode('root')`.\n */\n get root() {\n return this.findNode(ROOT_ID)!;\n }\n\n /**\n * Convert the graph to a JSON object.\n */\n toJSON({ id = ROOT_ID, maxLength = 32 }: { id?: string; maxLength?: number } = {}) {\n const toJSON = (node: Node, seen: string[] = []): any => {\n const nodes = this.nodes(node);\n const obj: Record<string, any> = {\n id: node.id.length > maxLength ? `${node.id.slice(0, maxLength - 3)}...` : 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) => {\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 = this.findNode(id);\n invariant(root, `Node not found: ${id}`);\n return toJSON(root);\n }\n\n pickle() {\n const nodes = Object.values(this._nodes)\n .filter((node) => !!node.cacheable)\n .map((node) => {\n return {\n id: node.id,\n type: node.type,\n properties: pick(node.properties, node.cacheable!),\n };\n });\n\n const cacheable = new Set(nodes.map((node) => node.id));\n\n const edges = Object.fromEntries(\n Object.entries(this._edges)\n .filter(([id]) => cacheable.has(id))\n .map(([id, { outbound }]): [string, string[]] => [id, outbound.filter((nodeId) => cacheable.has(nodeId))])\n // TODO(wittjosiah): Why sort?\n .toSorted(([a], [b]) => a.localeCompare(b)),\n );\n\n return JSON.stringify({ nodes, edges });\n }\n\n /**\n * Find the node with the given id in the graph.\n *\n * If a node is not found within the graph and an `onInitialNode` callback is provided,\n * it is called with the id and type of the node, potentially initializing the node.\n */\n findNode(id: string, expansion = true): Node | undefined {\n const existingNode = this._nodes[id];\n if (!existingNode && expansion) {\n void this._onInitialNode?.(id);\n }\n\n return existingNode;\n }\n\n /**\n * Wait for a node to be added to the graph.\n *\n * If the node is already present in the graph, the promise resolves immediately.\n *\n * @param id The id of the node to wait for.\n * @param timeout The time in milliseconds to wait for the node to be added.\n */\n async waitForNode(id: string, timeout?: number): Promise<Node> {\n const trigger = this._waitingForNodes[id] ?? (this._waitingForNodes[id] = new Trigger<Node>());\n const node = this.findNode(id);\n if (node) {\n delete this._waitingForNodes[id];\n return node;\n }\n\n if (timeout === undefined) {\n return trigger.wait();\n } else {\n return asyncTimeout(trigger.wait(), timeout, `Node not found: ${id}`);\n }\n }\n\n /**\n * Nodes that this node is connected to in default order.\n */\n nodes<TData = any, TProperties extends Record<string, any> = Record<string, any>>(\n node: Node,\n options: NodesOptions<TData, TProperties> = {},\n ) {\n const { relation, expansion, filter = DEFAULT_FILTER, type } = options;\n const nodes = this._getNodes({ node, relation, expansion, type });\n return nodes.filter((n) => filter(n, node));\n }\n\n /**\n * Edges that this node is connected to in default order.\n */\n edges(node: Node, { relation = 'outbound' }: { relation?: Relation } = {}) {\n return this._edges[node.id]?.[relation] ?? [];\n }\n\n /**\n * Actions or action groups that this node is connected to in default order.\n */\n actions(node: Node, { expansion }: { expansion?: boolean } = {}) {\n return [\n ...this._getNodes({ node, expansion, type: ACTION_GROUP_TYPE }),\n ...this._getNodes({ node, expansion, type: ACTION_TYPE }),\n ];\n }\n\n async expand(node: Node, relation: Relation = 'outbound', type?: string) {\n const key = this._key(node, relation, type);\n const initialized = this._initialized[key];\n if (!initialized && this._onInitialNodes) {\n await this._onInitialNodes(node, relation, type);\n this._initialized[key] = true;\n }\n }\n\n private _key(node: Node, relation: Relation, type?: string) {\n return `${node.id}-${relation}-${type}`;\n }\n\n /**\n * Recursive depth-first traversal of the graph.\n *\n * @param options.node The node to start traversing from.\n * @param options.relation The relation to traverse graph edges.\n * @param options.visitor A callback which is called for each node visited during traversal.\n */\n traverse(\n { visitor, node = this.root, relation = 'outbound', expansion }: GraphTraversalOptions,\n path: string[] = [],\n ): void {\n // Break cycles.\n if (path.includes(node.id)) {\n return;\n }\n\n const shouldContinue = visitor(node, [...path, node.id]);\n if (shouldContinue === false) {\n return;\n }\n\n Object.values(this._getNodes({ node, relation, expansion })).forEach((child) =>\n this.traverse({ node: child, relation, visitor, expansion }, [...path, node.id]),\n );\n }\n\n /**\n * Recursive depth-first traversal of the graph wrapping each visitor call in an effect.\n *\n * @param options.node The node to start traversing from.\n * @param options.relation The relation to traverse graph edges.\n * @param options.visitor A callback which is called for each node visited during traversal.\n */\n subscribeTraverse(\n { visitor, node = this.root, relation = 'outbound', expansion }: GraphTraversalOptions,\n currentPath: string[] = [],\n ) {\n return effect(() => {\n const path = [...currentPath, node.id];\n const result = visitor(node, path);\n if (result === false) {\n return;\n }\n\n const nodes = this._getNodes({ node, relation, expansion });\n const nodeSubscriptions = nodes.map((n) => this.subscribeTraverse({ node: n, visitor, expansion }, path));\n return () => {\n nodeSubscriptions.forEach((unsubscribe) => unsubscribe());\n };\n });\n }\n\n /**\n * Get the path between two nodes in the graph.\n */\n getPath({ source = 'root', target }: { source?: string; target: string }): string[] | undefined {\n const start = this.findNode(source);\n if (!start) {\n return undefined;\n }\n\n let found: string[] | undefined;\n this.traverse({\n node: start,\n visitor: (node, path) => {\n if (found) {\n return false;\n }\n\n if (node.id === target) {\n found = path;\n }\n },\n });\n\n return found;\n }\n\n /**\n * Wait for the path between two nodes in the graph to be established.\n */\n async waitForPath(\n params: { source?: string; target: string },\n { timeout = 5_000, interval = 500 }: { timeout?: number; interval?: number } = {},\n ) {\n const path = this.getPath(params);\n if (path) {\n return path;\n }\n\n const trigger = new Trigger<string[]>();\n const i = setInterval(() => {\n const path = this.getPath(params);\n if (path) {\n trigger.wake(path);\n }\n }, interval);\n\n return trigger.wait({ timeout }).finally(() => clearInterval(i));\n }\n\n /**\n * Add nodes to the graph.\n *\n * @internal\n */\n _addNodes<TData = null, TProperties extends Record<string, any> = Record<string, any>>(\n nodes: NodeArg<TData, TProperties>[],\n ): Node<TData, TProperties>[] {\n return batch(() => nodes.map((node) => this._addNode(node)));\n }\n\n private _addNode<TData, TProperties extends Record<string, any> = Record<string, any>>({\n nodes,\n edges,\n ..._node\n }: NodeArg<TData, TProperties>): Node<TData, TProperties> {\n return untracked(() => {\n const existingNode = this._nodes[_node.id];\n const node = existingNode ?? this._constructNode({ data: null, properties: {}, ..._node });\n if (existingNode) {\n const { data = null, properties, type } = _node;\n if (data !== node.data) {\n node.data = data;\n }\n\n if (type !== node.type) {\n node.type = type;\n }\n\n for (const key in properties) {\n if (properties[key] !== node.properties[key]) {\n node.properties[key] = properties[key];\n }\n }\n } else {\n this._nodes[node.id] = node;\n this._edges[node.id] = live({ inbound: [], outbound: [] });\n }\n\n const trigger = this._waitingForNodes[node.id];\n if (trigger) {\n trigger.wake(node);\n delete this._waitingForNodes[node.id];\n }\n\n if (nodes) {\n nodes.forEach((subNode) => {\n this._addNode(subNode);\n this._addEdge({ source: node.id, target: subNode.id });\n });\n }\n\n if (edges) {\n edges.forEach(([id, relation]) =>\n relation === 'outbound'\n ? this._addEdge({ source: node.id, target: id })\n : this._addEdge({ source: id, target: node.id }),\n );\n }\n\n return node as unknown as Node<TData, TProperties>;\n });\n }\n\n /**\n * Remove nodes from the graph.\n *\n * @param ids The id of the node to remove.\n * @param edges Whether to remove edges connected to the node from the graph as well.\n * @internal\n */\n _removeNodes(ids: string[], edges = false) {\n batch(() => ids.forEach((id) => this._removeNode(id, edges)));\n }\n\n private _removeNode(id: string, edges = false) {\n untracked(() => {\n const node = this.findNode(id, false);\n if (!node) {\n return;\n }\n\n if (edges) {\n // Remove edges from connected nodes.\n this._getNodes({ node }).forEach((node) => {\n this._removeEdge({ source: id, target: node.id });\n });\n this._getNodes({ node, relation: 'inbound' }).forEach((node) => {\n this._removeEdge({ source: node.id, target: id });\n });\n\n // Remove edges from node.\n delete this._edges[id];\n }\n\n // Remove node.\n delete this._nodes[id];\n Object.keys(this._initialized)\n .filter((key) => key.startsWith(id))\n .forEach((key) => {\n delete this._initialized[key];\n });\n void this._onRemoveNode?.(id);\n });\n }\n\n /**\n * Add edges to the graph.\n *\n * @internal\n */\n _addEdges(edges: { source: string; target: string }[]) {\n batch(() => edges.forEach((edge) => this._addEdge(edge)));\n }\n\n private _addEdge({ source, target }: { source: string; target: string }) {\n untracked(() => {\n if (!this._edges[source]) {\n this._edges[source] = live({ inbound: [], outbound: [] });\n }\n if (!this._edges[target]) {\n this._edges[target] = live({ inbound: [], outbound: [] });\n }\n\n const sourceEdges = this._edges[source];\n if (!sourceEdges.outbound.includes(target)) {\n sourceEdges.outbound.push(target);\n }\n\n const targetEdges = this._edges[target];\n if (!targetEdges.inbound.includes(source)) {\n targetEdges.inbound.push(source);\n }\n });\n }\n\n /**\n * Remove edges from the graph.\n * @internal\n */\n _removeEdges(edges: { source: string; target: string }[], removeOrphans = false) {\n batch(() => edges.forEach((edge) => this._removeEdge(edge, removeOrphans)));\n }\n\n private _removeEdge({ source, target }: { source: string; target: string }, removeOrphans = false) {\n untracked(() => {\n batch(() => {\n const outboundIndex = this._edges[source]?.outbound.findIndex((id) => id === target);\n if (outboundIndex !== undefined && outboundIndex !== -1) {\n this._edges[source].outbound.splice(outboundIndex, 1);\n }\n\n const inboundIndex = this._edges[target]?.inbound.findIndex((id) => id === source);\n if (inboundIndex !== undefined && inboundIndex !== -1) {\n this._edges[target].inbound.splice(inboundIndex, 1);\n }\n\n if (removeOrphans) {\n if (\n this._edges[source]?.outbound.length === 0 &&\n this._edges[source]?.inbound.length === 0 &&\n source !== ROOT_ID\n ) {\n this._removeNode(source, true);\n }\n if (\n this._edges[target]?.outbound.length === 0 &&\n this._edges[target]?.inbound.length === 0 &&\n target !== ROOT_ID\n ) {\n this._removeNode(target, true);\n }\n }\n });\n });\n }\n\n /**\n * Sort edges for a node.\n *\n * Edges not included in the sorted list are appended to the end of the list.\n *\n * @param nodeId The id of the node to sort edges for.\n * @param relation The relation of the edges from the node to sort.\n * @param edges The ordered list of edges.\n * @ignore\n */\n _sortEdges(nodeId: string, relation: Relation, edges: string[]) {\n untracked(() => {\n batch(() => {\n const current = this._edges[nodeId];\n if (current) {\n const unsorted = current[relation].filter((id) => !edges.includes(id)) ?? [];\n const sorted = edges.filter((id) => current[relation].includes(id)) ?? [];\n current[relation].splice(0, current[relation].length, ...[...sorted, ...unsorted]);\n }\n });\n });\n }\n\n private _constructNode = (node: Omit<Node, typeof graphSymbol>) => {\n return live<NodeInternal>({ ...node, [graphSymbol]: this });\n };\n\n private _getNodes({\n node,\n relation = 'outbound',\n type,\n expansion,\n }: {\n node: Node;\n relation?: Relation;\n type?: string;\n expansion?: boolean;\n }): Node[] {\n if (expansion) {\n void this.expand(node, relation, type);\n }\n\n const edges = this._edges[node.id];\n if (!edges) {\n return [];\n } else {\n return edges[relation]\n .map((id) => this._nodes[id])\n .filter(isNonNullable)\n .filter((n) => !type || n.type === type);\n }\n }\n}\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { type MaybePromise, type MakeOptional } from '@dxos/util';\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 Relation = 'outbound' | 'inbound';\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, Relation][];\n};\n\n//\n// Actions\n//\n\nexport type InvokeParams = {\n /** Node the invoked action is connected to. */\n parent?: Node;\n\n caller?: string;\n};\n\nexport type ActionData = (params?: InvokeParams) => MaybePromise<void>;\n\nexport type Action<TProperties extends Record<string, any> = Record<string, any>> = Readonly<\n Omit<Node<ActionData, TProperties>, 'properties'> & {\n properties: Readonly<TProperties>;\n }\n>;\n\nexport const isAction = (data: unknown): data is Action =>\n isGraphNode(data) ? typeof data.data === 'function' : 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 : false;\n\nexport type ActionLike = Action | ActionGroup;\n\nexport const isActionLike = (data: unknown): data is Action | ActionGroup => isAction(data) || isActionGroup(data);\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { effect, type Signal, signal, untracked } from '@preact/signals-core';\n\nimport { Trigger, type CleanupFn } from '@dxos/async';\nimport { invariant } from '@dxos/invariant';\nimport { live } from '@dxos/live-object';\nimport { log } from '@dxos/log';\nimport { byPosition, type Position, isNode, type MaybePromise, isNonNullable } from '@dxos/util';\n\nimport { ACTION_GROUP_TYPE, ACTION_TYPE, Graph, ROOT_ID, type GraphParams } from './graph';\nimport { type ActionData, actionGroupSymbol, type Node, type NodeArg, type Relation } from './node';\n\nconst NODE_RESOLVER_TIMEOUT = 1_000;\n\n/**\n * Graph builder extension for adding nodes to the graph based on just the node id.\n * This is useful for creating the first node in a graph or for hydrating cached nodes with data.\n *\n * @param params.id The id of the node to resolve.\n */\nexport type ResolverExtension = (params: { id: string }) => NodeArg<any> | false | undefined;\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<T = any> = (params: { node: Node<T> }) => NodeArg<any>[] | undefined;\n\n/**\n * Constrained case of the connector extension for more easily adding actions to the graph.\n */\nexport type ActionsExtension<T = any> = (params: {\n node: Node<T>;\n}) => Omit<NodeArg<ActionData>, 'type' | 'nodes' | 'edges'>[] | undefined;\n\n/**\n * Constrained case of the connector extension for more easily adding action groups to the graph.\n */\nexport type ActionGroupsExtension<T = any> = (params: {\n node: Node<T>;\n}) => Omit<NodeArg<typeof actionGroupSymbol>, 'type' | 'data' | 'nodes' | 'edges'>[] | undefined;\n\ntype GuardedNodeType<T> = T extends (value: any) => value is infer N ? (N extends Node<infer D> ? D : unknown) : never;\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.type If provided, all nodes returned are expected to have this type.\n * @param params.disposition Affects the order the extensions are processed in.\n * @param params.filter A filter function to determine if an extension should act on a node.\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 CreateExtensionOptions<T = any> = {\n id: string;\n relation?: Relation;\n type?: string;\n position?: Position;\n filter?: (node: Node) => node is Node<T>;\n resolver?: ResolverExtension;\n connector?: ConnectorExtension<GuardedNodeType<CreateExtensionOptions<T>['filter']>>;\n actions?: ActionsExtension<GuardedNodeType<CreateExtensionOptions<T>['filter']>>;\n actionGroups?: ActionGroupsExtension<GuardedNodeType<CreateExtensionOptions<T>['filter']>>;\n};\n\n/**\n * Create a graph builder extension.\n */\nexport const createExtension = <T = any>(extension: CreateExtensionOptions<T>): BuilderExtension[] => {\n const { id, position = 'static', resolver, connector, actions, actionGroups, ...rest } = extension;\n const getId = (key: string) => `${id}/${key}`;\n return [\n resolver ? { id: getId('resolver'), position, resolver } : undefined,\n connector ? { ...rest, id: getId('connector'), position, connector } : undefined,\n actionGroups\n ? ({\n ...rest,\n id: getId('actionGroups'),\n position,\n type: ACTION_GROUP_TYPE,\n relation: 'outbound',\n connector: ({ node }) =>\n actionGroups({ node })?.map((arg) => ({ ...arg, data: actionGroupSymbol, type: ACTION_GROUP_TYPE })),\n } satisfies BuilderExtension)\n : undefined,\n actions\n ? ({\n ...rest,\n id: getId('actions'),\n position,\n type: ACTION_TYPE,\n relation: 'outbound',\n connector: ({ node }) => actions({ node })?.map((arg) => ({ ...arg, type: ACTION_TYPE })),\n } satisfies BuilderExtension)\n : undefined,\n ].filter(isNonNullable);\n};\n\nexport type GraphBuilderTraverseOptions = {\n visitor: (node: Node, path: string[]) => MaybePromise<boolean | void>;\n node?: Node;\n relation?: Relation;\n};\n\n/**\n * The dispatcher is used to keep track of the current extension and state when memoizing functions.\n */\nclass Dispatcher {\n currentExtension?: string;\n stateIndex = 0;\n state: Record<string, any[]> = {};\n cleanup: (() => void)[] = [];\n}\n\nclass BuilderInternal {\n // This must be static to avoid passing the dispatcher instance to every memoized function.\n // If the dispatcher is not set that means that the memoized function is being called outside of the graph builder.\n static currentDispatcher?: Dispatcher;\n}\n\n/**\n * Allows code to be memoized within the context of a graph builder extension.\n * This is useful for creating instances which should be subscribed to rather than recreated.\n */\nexport const memoize = <T>(fn: () => T, key = 'result'): T => {\n const dispatcher = BuilderInternal.currentDispatcher;\n invariant(dispatcher?.currentExtension, 'memoize must be called within an extension');\n const all = dispatcher.state[dispatcher.currentExtension][dispatcher.stateIndex] ?? {};\n const current = all[key];\n const result = current ? current.result : fn();\n dispatcher.state[dispatcher.currentExtension][dispatcher.stateIndex] = { ...all, [key]: { result } };\n dispatcher.stateIndex++;\n return result;\n};\n\n/**\n * Register a cleanup function to be called when the graph builder is destroyed.\n */\nexport const cleanup = (fn: () => void): void => {\n memoize(() => {\n const dispatcher = BuilderInternal.currentDispatcher;\n invariant(dispatcher, 'cleanup must be called within an extension');\n dispatcher.cleanup.push(fn);\n });\n};\n\n/**\n * Convert a subscribe/get pair into a signal.\n */\nexport const toSignal = <T>(\n subscribe: (onChange: () => void) => () => void,\n get: () => T | undefined,\n key?: string,\n) => {\n const thisSignal = memoize(() => {\n return signal(get());\n }, key);\n const unsubscribe = memoize(() => {\n return subscribe(() => (thisSignal.value = get()));\n }, key);\n cleanup(() => {\n unsubscribe();\n });\n return thisSignal.value;\n};\n\nexport type BuilderExtension = Readonly<{\n id: string;\n position: Position;\n resolver?: ResolverExtension;\n connector?: ConnectorExtension;\n // Only for connector.\n relation?: Relation;\n type?: string;\n filter?: (node: Node) => boolean;\n}>;\n\ntype ExtensionArg = BuilderExtension | BuilderExtension[] | ExtensionArg[];\n\nexport const flattenExtensions = (extension: ExtensionArg, 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\n/**\n * The builder provides an extensible way to compose the construction of the graph.\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.\nexport class GraphBuilder {\n private readonly _dispatcher = new Dispatcher();\n private readonly _extensions = live<Record<string, BuilderExtension>>({});\n private readonly _resolverSubscriptions = new Map<string, CleanupFn>();\n private readonly _connectorSubscriptions = new Map<string, CleanupFn>();\n private readonly _nodeChanged: Record<string, Signal<{}>> = {};\n private readonly _initialized: Record<string, Trigger> = {};\n private _graph: Graph;\n\n constructor(params: Pick<GraphParams, 'nodes' | 'edges'> = {}) {\n this._graph = new Graph({\n ...params,\n onInitialNode: async (id) => this._onInitialNode(id),\n onInitialNodes: async (node, relation, type) => this._onInitialNodes(node, relation, type),\n onRemoveNode: (id) => this._onRemoveNode(id),\n });\n }\n\n static from(pickle?: string) {\n if (!pickle) {\n return new GraphBuilder();\n }\n\n const { nodes, edges } = JSON.parse(pickle);\n return new GraphBuilder({ nodes, edges });\n }\n\n /**\n * If graph is being restored from a pickle, the data will be null.\n * Initialize the data of each node by calling resolvers.\n * Wait until all of the initial nodes have resolved.\n */\n async initialize() {\n Object.keys(this._graph._nodes)\n .filter((id) => id !== ROOT_ID)\n .forEach((id) => (this._initialized[id] = new Trigger()));\n Object.keys(this._graph._nodes).forEach((id) => this._onInitialNode(id));\n await Promise.all(\n Object.entries(this._initialized).map(async ([id, trigger]) => {\n try {\n await trigger.wait({ timeout: NODE_RESOLVER_TIMEOUT });\n } catch {\n log.error('node resolver timeout', { id });\n this.graph._removeNodes([id]);\n }\n }),\n );\n }\n\n get graph() {\n return this._graph;\n }\n\n /**\n * @reactive\n */\n get extensions() {\n return Object.values(this._extensions);\n }\n\n /**\n * Register a node builder which will be called in order to construct the graph.\n */\n addExtension(extension: ExtensionArg): GraphBuilder {\n const extensions = flattenExtensions(extension);\n untracked(() => {\n extensions.forEach((extension) => {\n this._dispatcher.state[extension.id] = [];\n this._extensions[extension.id] = extension;\n });\n });\n return this;\n }\n\n /**\n * Remove a node builder from the graph builder.\n */\n removeExtension(id: string): GraphBuilder {\n untracked(() => {\n delete this._extensions[id];\n });\n return this;\n }\n\n destroy() {\n this._dispatcher.cleanup.forEach((fn) => fn());\n this._resolverSubscriptions.forEach((unsubscribe) => unsubscribe());\n this._connectorSubscriptions.forEach((unsubscribe) => unsubscribe());\n this._resolverSubscriptions.clear();\n this._connectorSubscriptions.clear();\n }\n\n /**\n * A graph traversal using just the connector extensions, without subscribing to any signals or persisting any nodes.\n */\n async explore(\n { node = this._graph.root, relation = 'outbound', visitor }: GraphBuilderTraverseOptions,\n path: string[] = [],\n ) {\n // Break cycles.\n if (path.includes(node.id)) {\n return;\n }\n\n // TODO(wittjosiah): This is a workaround for esm not working in the test runner.\n // Switching to vitest is blocked by having node esm versions of echo-schema & echo-signals.\n if (!isNode()) {\n const { yieldOrContinue } = await import('main-thread-scheduling');\n await yieldOrContinue('idle');\n }\n const shouldContinue = await visitor(node, [...path, node.id]);\n if (shouldContinue === false) {\n return;\n }\n\n const nodes = Object.values(this._extensions)\n .filter((extension) => relation === (extension.relation ?? 'outbound'))\n .filter((extension) => !extension.filter || extension.filter(node))\n .flatMap((extension) => {\n this._dispatcher.currentExtension = extension.id;\n this._dispatcher.stateIndex = 0;\n BuilderInternal.currentDispatcher = this._dispatcher;\n const result = extension.connector?.({ node }) ?? [];\n BuilderInternal.currentDispatcher = undefined;\n return result;\n })\n .map(\n (arg): Node => ({\n id: arg.id,\n type: arg.type,\n cacheable: arg.cacheable,\n data: arg.data ?? null,\n properties: arg.properties ?? {},\n }),\n );\n\n await Promise.all(nodes.map((n) => this.explore({ node: n, relation, visitor }, [...path, node.id])));\n }\n\n private _onInitialNode(nodeId: string) {\n this._nodeChanged[nodeId] = this._nodeChanged[nodeId] ?? signal({});\n this._resolverSubscriptions.set(\n nodeId,\n effect(() => {\n const extensions = Object.values(this._extensions).toSorted(byPosition);\n for (const { id, resolver } of extensions) {\n if (!resolver) {\n continue;\n }\n\n this._dispatcher.currentExtension = id;\n this._dispatcher.stateIndex = 0;\n BuilderInternal.currentDispatcher = this._dispatcher;\n let node: NodeArg<any> | false | undefined;\n try {\n node = resolver({ id: nodeId });\n } catch (err) {\n log.catch(err, { extension: id });\n log.error(`Previous error occurred in extension: ${id}`);\n } finally {\n BuilderInternal.currentDispatcher = undefined;\n }\n\n const trigger = this._initialized[nodeId];\n if (node) {\n this.graph._addNodes([node]);\n trigger?.wake();\n if (this._nodeChanged[node.id]) {\n this._nodeChanged[node.id].value = {};\n }\n break;\n } else if (node === false) {\n this.graph._removeNodes([nodeId]);\n trigger?.wake();\n break;\n }\n }\n }),\n );\n }\n\n private _onInitialNodes(node: Node, nodesRelation: Relation, nodesType?: string) {\n this._nodeChanged[node.id] = this._nodeChanged[node.id] ?? signal({});\n let first = true;\n let previous: string[] = [];\n this._connectorSubscriptions.set(\n node.id,\n effect(() => {\n // TODO(wittjosiah): This is a workaround for a race between the node removal and the effect re-running.\n // To cause this case to happen, remove a collection and then undo the removal.\n if (!first && !this._connectorSubscriptions.has(node.id)) {\n return;\n }\n first = false;\n\n // Subscribe to extensions being added.\n Object.keys(this._extensions);\n // Subscribe to connected node changes.\n this._nodeChanged[node.id].value;\n\n // TODO(wittjosiah): Consider allowing extensions to collaborate on the same node by merging their results.\n const nodes: NodeArg<any>[] = [];\n const extensions = Object.values(this._extensions).toSorted(byPosition);\n for (const { id, connector, filter, type, relation = 'outbound' } of extensions) {\n if (\n !connector ||\n relation !== nodesRelation ||\n (nodesType && type !== nodesType) ||\n (filter && !filter(node))\n ) {\n continue;\n }\n\n this._dispatcher.currentExtension = id;\n this._dispatcher.stateIndex = 0;\n BuilderInternal.currentDispatcher = this._dispatcher;\n try {\n nodes.push(...(connector({ node }) ?? []));\n } catch (err) {\n log.catch(err, { extension: id });\n log.error(`Previous error occurred in extension: ${id}`);\n } finally {\n BuilderInternal.currentDispatcher = undefined;\n }\n }\n\n const ids = nodes.map((n) => n.id);\n const removed = previous.filter((id) => !ids.includes(id));\n previous = ids;\n\n // Remove edges and only remove nodes that are orphaned.\n this.graph._removeEdges(\n removed.map((target) => ({ source: node.id, target })),\n true,\n );\n this.graph._addNodes(nodes);\n this.graph._addEdges(\n nodes.map(({ id }) =>\n nodesRelation === 'outbound' ? { source: node.id, target: id } : { source: id, target: node.id },\n ),\n );\n this.graph._sortEdges(\n node.id,\n nodesRelation,\n nodes.map(({ id }) => id),\n );\n nodes.forEach((n) => {\n if (this._nodeChanged[n.id]) {\n this._nodeChanged[n.id].value = {};\n }\n });\n }),\n );\n }\n\n private async _onRemoveNode(nodeId: string) {\n this._resolverSubscriptions.get(nodeId)?.();\n this._connectorSubscriptions.get(nodeId)?.();\n this._resolverSubscriptions.delete(nodeId);\n this._connectorSubscriptions.delete(nodeId);\n }\n}\n"],
5
5
  "mappings": ";AAIA,SAASA,OAAOC,QAAQC,iBAAiB;AAEzC,SAASC,cAAcC,eAAe;AACtC,SAASC,iBAAiB;AAC1B,SAAoBC,YAAY;AAChC,SAASC,WAAW;AACpB,SAA4BC,eAAeC,YAAY;;;ACwChD,IAAMC,cAAc,CAACC,SAC1BA,QAAQ,OAAOA,SAAS,YAAY,QAAQA,QAAQ,gBAAgBA,QAAQA,KAAKC,aAC7E,OAAOD,KAAKC,eAAe,YAAY,UAAUD,OACjD;AAgCC,IAAME,WAAW,CAACF,SACvBD,YAAYC,IAAAA,IAAQ,OAAOA,KAAKA,SAAS,aAAa;AAEjD,IAAMG,oBAAoBC,OAAO,aAAA;AAQjC,IAAMC,gBAAgB,CAACL,SAC5BD,YAAYC,IAAAA,IAAQA,KAAKA,SAASG,oBAAoB;AAIjD,IAAMG,eAAe,CAACN,SAAgDE,SAASF,IAAAA,KAASK,cAAcL,IAAAA;;;;ADvF7G,IAAMO,cAAcC,OAAO,OAAA;AAIpB,IAAMC,WAAW,CAACC,SAAAA;AACvB,QAAMC,QAASD,KAAsBH,WAAAA;AACrCK,YAAUD,OAAO,wCAAA;;;;;;;;;AACjB,SAAOA;AACT;AAEO,IAAME,UAAU;AAChB,IAAMC,YAAY;AAClB,IAAMC,cAAc;AACpB,IAAMC,oBAAoB;AAUjC,IAAMC,iBAAiB,CAACP,SAAeQ,UAAU,MAAM,CAACC,aAAaT,IAAAA,CAAAA;AAyC9D,IAAMU,QAAN,MAAMA,OAAAA;EAkBXC,YAAY,EAAEC,OAAOC,OAAOC,eAAeC,gBAAgBC,aAAY,IAAkB,CAAC,GAAG;AAb5EC,4BAAkD,CAAC;AACnDC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yB,0BAAgBI,oBAAoBpB;QACtC;MACF;AAEA,YAAMiH,MAAMpD,MAAMxD,IAAI,CAAC6F,MAAMA,EAAE3G,EAAE;AACjC,YAAM2H,UAAUH,SAASrG,OAAO,CAACnB,OAAO,CAAC0H,IAAIrB,SAASrG,EAAAA,CAAAA;AACtDwH,iBAAWE;AAGX,WAAKlC,MAAMoC,aACTD,QAAQ7G,IAAI,CAAC+G,YAAY;QAAEC,QAAQjH,KAAKb;QAAI6H;MAAO,EAAA,GACnD,IAAA;AAEF,WAAKrC,MAAM2B,UAAU7C,KAAAA;AACrB,WAAKkB,MAAMuC,UACTzD,MAAMxD,IAAI,CAAC,EAAEd,GAAE,MACbqH,kBAAkB,aAAa;QAAES,QAAQjH,KAAKb;QAAI6H,QAAQ7H;MAAG,IAAI;QAAE8H,QAAQ9H;QAAI6H,QAAQhH,KAAKb;MAAG,CAAA,CAAA;AAGnG,WAAKwF,MAAMwC,WACTnH,KAAKb,IACLqH,eACA/C,MAAMxD,IAAI,CAAC,EAAEd,GAAE,MAAOA,EAAAA,CAAAA;AAExBsE,YAAMS,QAAQ,CAAC4B,MAAAA;AACb,YAAI,KAAKjD,aAAaiD,EAAE3G,EAAE,GAAG;AAC3B,eAAK0D,aAAaiD,EAAE3G,EAAE,EAAE0C,QAAQ,CAAC;QACnC;MACF,CAAA;IACF,CAAA,CAAA;EAEJ;EAEA,MAAcyB,cAAcyC,QAAgB;AAC1C,SAAKrD,uBAAuBjB,IAAIsE,MAAAA,IAAAA;AAChC,SAAKnD,wBAAwBnB,IAAIsE,MAAAA,IAAAA;AACjC,SAAKrD,uBAAuB0E,OAAOrB,MAAAA;AACnC,SAAKnD,wBAAwBwE,OAAOrB,MAAAA;EACtC;AACF;",
6
6
  "names": ["batch", "effect", "untracked", "asyncTimeout", "Trigger", "invariant", "live", "log", "isNonNullable", "pick", "isGraphNode", "data", "properties", "isAction", "actionGroupSymbol", "Symbol", "isActionGroup", "isActionLike", "graphSymbol", "Symbol", "getGraph", "node", "graph", "invariant", "ROOT_ID", "ROOT_TYPE", "ACTION_TYPE", "ACTION_GROUP_TYPE", "DEFAULT_FILTER", "untracked", "isActionLike", "Graph", "constructor", "nodes", "edges", "onInitialNode", "onInitialNodes", "onRemoveNode", "_waitingForNodes", "_initialized", "_nodes", "_edges", "_constructNode", "live", "_onInitialNode", "_onInitialNodes", "_onRemoveNode", "id", "type", "cacheable", "properties", "data", "forEach", "Object", "keys", "_addNode", "log", "warn", "actionGroupSymbol", "inbound", "outbound", "entries", "source", "target", "_addEdge", "_sortEdges", "from", "pickle", "options", "JSON", "parse", "root", "findNode", "toJSON", "maxLength", "seen", "obj", "length", "slice", "label", "map", "n", "nextSeen", "includes", "undefined", "filter", "isNonNullable", "values", "pick", "Set", "fromEntries", "has", "nodeId", "toSorted", "a", "b", "localeCompare", "stringify", "expansion", "existingNode", "waitForNode", "timeout", "trigger", "Trigger", "wait", "asyncTimeout", "relation", "_getNodes", "actions", "expand", "key", "_key", "initialized", "traverse", "visitor", "path", "shouldContinue", "child", "subscribeTraverse", "currentPath", "effect", "result", "nodeSubscriptions", "unsubscribe", "getPath", "start", "found", "waitForPath", "params", "interval", "i", "setInterval", "wake", "finally", "clearInterval", "_addNodes", "batch", "_node", "subNode", "_removeNodes", "ids", "_removeNode", "_removeEdge", "startsWith", "_addEdges", "edge", "sourceEdges", "push", "targetEdges", "_removeEdges", "removeOrphans", "outboundIndex", "findIndex", "splice", "inboundIndex", "current", "unsorted", "sorted", "effect", "signal", "untracked", "Trigger", "invariant", "live", "log", "byPosition", "isNode", "isNonNullable", "NODE_RESOLVER_TIMEOUT", "createExtension", "extension", "id", "position", "resolver", "connector", "actions", "actionGroups", "rest", "getId", "key", "undefined", "type", "ACTION_GROUP_TYPE", "relation", "node", "map", "arg", "data", "actionGroupSymbol", "ACTION_TYPE", "filter", "isNonNullable", "Dispatcher", "stateIndex", "state", "cleanup", "BuilderInternal", "memoize", "fn", "dispatcher", "currentDispatcher", "invariant", "currentExtension", "all", "current", "result", "push", "toSignal", "subscribe", "get", "thisSignal", "signal", "unsubscribe", "value", "flattenExtensions", "acc", "Array", "isArray", "flatMap", "ext", "GraphBuilder", "constructor", "params", "_dispatcher", "_extensions", "live", "_resolverSubscriptions", "Map", "_connectorSubscriptions", "_nodeChanged", "_initialized", "_graph", "Graph", "onInitialNode", "_onInitialNode", "onInitialNodes", "_onInitialNodes", "onRemoveNode", "_onRemoveNode", "from", "pickle", "nodes", "edges", "JSON", "parse", "initialize", "Object", "keys", "_nodes", "ROOT_ID", "forEach", "Trigger", "Promise", "entries", "trigger", "wait", "timeout", "log", "error", "graph", "_removeNodes", "extensions", "values", "addExtension", "untracked", "removeExtension", "destroy", "clear", "explore", "root", "visitor", "path", "includes", "isNode", "yieldOrContinue", "shouldContinue", "cacheable", "properties", "n", "nodeId", "set", "effect", "toSorted", "byPosition", "err", "catch", "_addNodes", "wake", "nodesRelation", "nodesType", "first", "previous", "has", "ids", "removed", "_removeEdges", "target", "source", "_addEdges", "_sortEdges", "delete"]
7
7
  }
@@ -1 +1 @@
1
- {"inputs":{"packages/sdk/app-graph/src/node.ts":{"bytes":5859,"imports":[],"format":"esm"},"packages/sdk/app-graph/src/graph.ts":{"bytes":63179,"imports":[{"path":"@preact/signals-core","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/live-object","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"packages/sdk/app-graph/src/node.ts","kind":"import-statement","original":"./node"}],"format":"esm"},"packages/sdk/app-graph/src/graph-builder.ts":{"bytes":52318,"imports":[{"path":"@preact/signals-core","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/live-object","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"packages/sdk/app-graph/src/graph.ts","kind":"import-statement","original":"./graph"},{"path":"packages/sdk/app-graph/src/node.ts","kind":"import-statement","original":"./node"},{"path":"main-thread-scheduling","kind":"dynamic-import","external":true}],"format":"esm"},"packages/sdk/app-graph/src/index.ts":{"bytes":672,"imports":[{"path":"packages/sdk/app-graph/src/graph.ts","kind":"import-statement","original":"./graph"},{"path":"packages/sdk/app-graph/src/graph-builder.ts","kind":"import-statement","original":"./graph-builder"},{"path":"packages/sdk/app-graph/src/node.ts","kind":"import-statement","original":"./node"}],"format":"esm"}},"outputs":{"packages/sdk/app-graph/dist/lib/browser/index.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":61201},"packages/sdk/app-graph/dist/lib/browser/index.mjs":{"imports":[{"path":"@preact/signals-core","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/live-object","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"@preact/signals-core","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/live-object","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"main-thread-scheduling","kind":"dynamic-import","external":true}],"exports":["ACTION_GROUP_TYPE","ACTION_TYPE","Graph","GraphBuilder","ROOT_ID","ROOT_TYPE","actionGroupSymbol","cleanup","createExtension","flattenExtensions","getGraph","isAction","isActionGroup","isActionLike","isGraphNode","memoize","toSignal"],"entryPoint":"packages/sdk/app-graph/src/index.ts","inputs":{"packages/sdk/app-graph/src/graph.ts":{"bytesInOutput":15387},"packages/sdk/app-graph/src/node.ts":{"bytesInOutput":477},"packages/sdk/app-graph/src/index.ts":{"bytesInOutput":0},"packages/sdk/app-graph/src/graph-builder.ts":{"bytesInOutput":11341}},"bytes":27669}}}
1
+ {"inputs":{"packages/sdk/app-graph/src/node.ts":{"bytes":5863,"imports":[],"format":"esm"},"packages/sdk/app-graph/src/graph.ts":{"bytes":63179,"imports":[{"path":"@preact/signals-core","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/live-object","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"packages/sdk/app-graph/src/node.ts","kind":"import-statement","original":"./node"}],"format":"esm"},"packages/sdk/app-graph/src/graph-builder.ts":{"bytes":52318,"imports":[{"path":"@preact/signals-core","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/live-object","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"packages/sdk/app-graph/src/graph.ts","kind":"import-statement","original":"./graph"},{"path":"packages/sdk/app-graph/src/node.ts","kind":"import-statement","original":"./node"},{"path":"main-thread-scheduling","kind":"dynamic-import","external":true}],"format":"esm"},"packages/sdk/app-graph/src/index.ts":{"bytes":672,"imports":[{"path":"packages/sdk/app-graph/src/graph.ts","kind":"import-statement","original":"./graph"},{"path":"packages/sdk/app-graph/src/graph-builder.ts","kind":"import-statement","original":"./graph-builder"},{"path":"packages/sdk/app-graph/src/node.ts","kind":"import-statement","original":"./node"}],"format":"esm"}},"outputs":{"packages/sdk/app-graph/dist/lib/browser/index.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":61205},"packages/sdk/app-graph/dist/lib/browser/index.mjs":{"imports":[{"path":"@preact/signals-core","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/live-object","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"@preact/signals-core","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/live-object","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"main-thread-scheduling","kind":"dynamic-import","external":true}],"exports":["ACTION_GROUP_TYPE","ACTION_TYPE","Graph","GraphBuilder","ROOT_ID","ROOT_TYPE","actionGroupSymbol","cleanup","createExtension","flattenExtensions","getGraph","isAction","isActionGroup","isActionLike","isGraphNode","memoize","toSignal"],"entryPoint":"packages/sdk/app-graph/src/index.ts","inputs":{"packages/sdk/app-graph/src/graph.ts":{"bytesInOutput":15387},"packages/sdk/app-graph/src/node.ts":{"bytesInOutput":477},"packages/sdk/app-graph/src/index.ts":{"bytesInOutput":0},"packages/sdk/app-graph/src/graph-builder.ts":{"bytesInOutput":11341}},"bytes":27669}}}
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/graph.ts", "../../../src/node.ts", "../../../src/graph-builder.ts"],
4
- "sourcesContent": ["//\n// Copyright 2023 DXOS.org\n//\n\nimport { batch, effect, untracked } from '@preact/signals-core';\n\nimport { asyncTimeout, Trigger } from '@dxos/async';\nimport { invariant } from '@dxos/invariant';\nimport { type Live, live } from '@dxos/live-object';\nimport { log } from '@dxos/log';\nimport { type MakeOptional, isNonNullable, pick } from '@dxos/util';\n\nimport { type Node, type NodeArg, type NodeFilter, type Relation, actionGroupSymbol, isActionLike } from './node';\n\nconst graphSymbol = Symbol('graph');\ntype DeepWriteable<T> = { -readonly [K in keyof T]: T[K] extends object ? DeepWriteable<T[K]> : T[K] };\ntype NodeInternal = DeepWriteable<Node> & { [graphSymbol]: Graph };\n\nexport const getGraph = (node: Node): Graph => {\n const graph = (node as NodeInternal)[graphSymbol];\n invariant(graph, 'Node is not associated with a graph.');\n return graph;\n};\n\nexport const ROOT_ID = 'root';\nexport const ROOT_TYPE = 'dxos.org/type/GraphRoot';\nexport const ACTION_TYPE = 'dxos.org/type/GraphAction';\nexport const ACTION_GROUP_TYPE = 'dxos.org/type/GraphActionGroup';\n\nexport type NodesOptions<TData = any, TProperties extends Record<string, any> = Record<string, any>> = {\n relation?: Relation;\n filter?: NodeFilter<TData, TProperties>;\n expansion?: boolean;\n type?: string;\n};\n\n// TODO(wittjosiah): Consider having default be undefined. This is current default for backwards compatibility.\nconst DEFAULT_FILTER = (node: Node) => untracked(() => !isActionLike(node));\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, path: string[]) => boolean | void;\n\n /**\n * The node to start traversing from.\n *\n * @default root\n */\n node?: Node;\n\n /**\n * The relation to traverse graph edges.\n *\n * @default 'outbound'\n */\n relation?: Relation;\n\n /**\n * Allow traversal to trigger expansion of the graph via `onInitialNodes`.\n */\n expansion?: boolean;\n};\n\nexport type GraphParams = {\n nodes?: MakeOptional<Node, 'data' | 'cacheable'>[];\n edges?: Record<string, string[]>;\n onInitialNode?: Graph['_onInitialNode'];\n onInitialNodes?: Graph['_onInitialNodes'];\n onRemoveNode?: Graph['_onRemoveNode'];\n};\n\n/**\n * The Graph represents the structure of the application constructed via plugins.\n */\nexport class Graph {\n private readonly _onInitialNode?: (id: string) => Promise<void>;\n private readonly _onInitialNodes?: (node: Node, relation: Relation, type?: string) => Promise<void>;\n private readonly _onRemoveNode?: (id: string) => Promise<void>;\n\n private readonly _waitingForNodes: Record<string, Trigger<Node>> = {};\n private readonly _initialized: Record<string, boolean> = {};\n\n /**\n * @internal\n */\n readonly _nodes: Record<string, Live<NodeInternal>> = {};\n\n /**\n * @internal\n */\n readonly _edges: Record<string, Live<{ inbound: string[]; outbound: string[] }>> = {};\n\n constructor({ nodes, edges, onInitialNode, onInitialNodes, onRemoveNode }: GraphParams = {}) {\n this._onInitialNode = onInitialNode;\n this._onInitialNodes = onInitialNodes;\n this._onRemoveNode = onRemoveNode;\n\n this._nodes[ROOT_ID] = this._constructNode({\n id: ROOT_ID,\n type: ROOT_TYPE,\n cacheable: [],\n properties: {},\n data: null,\n });\n if (nodes) {\n nodes.forEach((node) => {\n const cacheable = Object.keys(node.properties ?? {});\n if (node.type === ACTION_TYPE) {\n this._addNode({ cacheable, data: () => log.warn('Pickled action invocation'), ...node });\n } else if (node.type === ACTION_GROUP_TYPE) {\n this._addNode({ cacheable, data: actionGroupSymbol, ...node });\n } else {\n this._addNode({ cacheable, ...node });\n }\n });\n }\n\n this._edges[ROOT_ID] = live({ inbound: [], outbound: [] });\n if (edges) {\n Object.entries(edges).forEach(([source, edges]) => {\n edges.forEach((target) => {\n this._addEdge({ source, target });\n });\n this._sortEdges(source, 'outbound', edges);\n });\n }\n }\n\n static from(pickle: string, options: Omit<GraphParams, 'nodes' | 'edges'> = {}) {\n const { nodes, edges } = JSON.parse(pickle);\n return new Graph({ nodes, edges, ...options });\n }\n\n /**\n * Alias for `findNode('root')`.\n */\n get root() {\n return this.findNode(ROOT_ID)!;\n }\n\n /**\n * Convert the graph to a JSON object.\n */\n toJSON({ id = ROOT_ID, maxLength = 32 }: { id?: string; maxLength?: number } = {}) {\n const toJSON = (node: Node, seen: string[] = []): any => {\n const nodes = this.nodes(node);\n const obj: Record<string, any> = {\n id: node.id.length > maxLength ? `${node.id.slice(0, maxLength - 3)}...` : 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) => {\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 = this.findNode(id);\n invariant(root, `Node not found: ${id}`);\n return toJSON(root);\n }\n\n pickle() {\n const nodes = Object.values(this._nodes)\n .filter((node) => !!node.cacheable)\n .map((node) => {\n return {\n id: node.id,\n type: node.type,\n properties: pick(node.properties, node.cacheable!),\n };\n });\n\n const cacheable = new Set(nodes.map((node) => node.id));\n\n const edges = Object.fromEntries(\n Object.entries(this._edges)\n .filter(([id]) => cacheable.has(id))\n .map(([id, { outbound }]): [string, string[]] => [id, outbound.filter((nodeId) => cacheable.has(nodeId))])\n // TODO(wittjosiah): Why sort?\n .toSorted(([a], [b]) => a.localeCompare(b)),\n );\n\n return JSON.stringify({ nodes, edges });\n }\n\n /**\n * Find the node with the given id in the graph.\n *\n * If a node is not found within the graph and an `onInitialNode` callback is provided,\n * it is called with the id and type of the node, potentially initializing the node.\n */\n findNode(id: string, expansion = true): Node | undefined {\n const existingNode = this._nodes[id];\n if (!existingNode && expansion) {\n void this._onInitialNode?.(id);\n }\n\n return existingNode;\n }\n\n /**\n * Wait for a node to be added to the graph.\n *\n * If the node is already present in the graph, the promise resolves immediately.\n *\n * @param id The id of the node to wait for.\n * @param timeout The time in milliseconds to wait for the node to be added.\n */\n async waitForNode(id: string, timeout?: number): Promise<Node> {\n const trigger = this._waitingForNodes[id] ?? (this._waitingForNodes[id] = new Trigger<Node>());\n const node = this.findNode(id);\n if (node) {\n delete this._waitingForNodes[id];\n return node;\n }\n\n if (timeout === undefined) {\n return trigger.wait();\n } else {\n return asyncTimeout(trigger.wait(), timeout, `Node not found: ${id}`);\n }\n }\n\n /**\n * Nodes that this node is connected to in default order.\n */\n nodes<TData = any, TProperties extends Record<string, any> = Record<string, any>>(\n node: Node,\n options: NodesOptions<TData, TProperties> = {},\n ) {\n const { relation, expansion, filter = DEFAULT_FILTER, type } = options;\n const nodes = this._getNodes({ node, relation, expansion, type });\n return nodes.filter((n) => filter(n, node));\n }\n\n /**\n * Edges that this node is connected to in default order.\n */\n edges(node: Node, { relation = 'outbound' }: { relation?: Relation } = {}) {\n return this._edges[node.id]?.[relation] ?? [];\n }\n\n /**\n * Actions or action groups that this node is connected to in default order.\n */\n actions(node: Node, { expansion }: { expansion?: boolean } = {}) {\n return [\n ...this._getNodes({ node, expansion, type: ACTION_GROUP_TYPE }),\n ...this._getNodes({ node, expansion, type: ACTION_TYPE }),\n ];\n }\n\n async expand(node: Node, relation: Relation = 'outbound', type?: string) {\n const key = this._key(node, relation, type);\n const initialized = this._initialized[key];\n if (!initialized && this._onInitialNodes) {\n await this._onInitialNodes(node, relation, type);\n this._initialized[key] = true;\n }\n }\n\n private _key(node: Node, relation: Relation, type?: string) {\n return `${node.id}-${relation}-${type}`;\n }\n\n /**\n * Recursive depth-first traversal of the graph.\n *\n * @param options.node The node to start traversing from.\n * @param options.relation The relation to traverse graph edges.\n * @param options.visitor A callback which is called for each node visited during traversal.\n */\n traverse(\n { visitor, node = this.root, relation = 'outbound', expansion }: GraphTraversalOptions,\n path: string[] = [],\n ): void {\n // Break cycles.\n if (path.includes(node.id)) {\n return;\n }\n\n const shouldContinue = visitor(node, [...path, node.id]);\n if (shouldContinue === false) {\n return;\n }\n\n Object.values(this._getNodes({ node, relation, expansion })).forEach((child) =>\n this.traverse({ node: child, relation, visitor, expansion }, [...path, node.id]),\n );\n }\n\n /**\n * Recursive depth-first traversal of the graph wrapping each visitor call in an effect.\n *\n * @param options.node The node to start traversing from.\n * @param options.relation The relation to traverse graph edges.\n * @param options.visitor A callback which is called for each node visited during traversal.\n */\n subscribeTraverse(\n { visitor, node = this.root, relation = 'outbound', expansion }: GraphTraversalOptions,\n currentPath: string[] = [],\n ) {\n return effect(() => {\n const path = [...currentPath, node.id];\n const result = visitor(node, path);\n if (result === false) {\n return;\n }\n\n const nodes = this._getNodes({ node, relation, expansion });\n const nodeSubscriptions = nodes.map((n) => this.subscribeTraverse({ node: n, visitor, expansion }, path));\n return () => {\n nodeSubscriptions.forEach((unsubscribe) => unsubscribe());\n };\n });\n }\n\n /**\n * Get the path between two nodes in the graph.\n */\n getPath({ source = 'root', target }: { source?: string; target: string }): string[] | undefined {\n const start = this.findNode(source);\n if (!start) {\n return undefined;\n }\n\n let found: string[] | undefined;\n this.traverse({\n node: start,\n visitor: (node, path) => {\n if (found) {\n return false;\n }\n\n if (node.id === target) {\n found = path;\n }\n },\n });\n\n return found;\n }\n\n /**\n * Wait for the path between two nodes in the graph to be established.\n */\n async waitForPath(\n params: { source?: string; target: string },\n { timeout = 5_000, interval = 500 }: { timeout?: number; interval?: number } = {},\n ) {\n const path = this.getPath(params);\n if (path) {\n return path;\n }\n\n const trigger = new Trigger<string[]>();\n const i = setInterval(() => {\n const path = this.getPath(params);\n if (path) {\n trigger.wake(path);\n }\n }, interval);\n\n return trigger.wait({ timeout }).finally(() => clearInterval(i));\n }\n\n /**\n * Add nodes to the graph.\n *\n * @internal\n */\n _addNodes<TData = null, TProperties extends Record<string, any> = Record<string, any>>(\n nodes: NodeArg<TData, TProperties>[],\n ): Node<TData, TProperties>[] {\n return batch(() => nodes.map((node) => this._addNode(node)));\n }\n\n private _addNode<TData, TProperties extends Record<string, any> = Record<string, any>>({\n nodes,\n edges,\n ..._node\n }: NodeArg<TData, TProperties>): Node<TData, TProperties> {\n return untracked(() => {\n const existingNode = this._nodes[_node.id];\n const node = existingNode ?? this._constructNode({ data: null, properties: {}, ..._node });\n if (existingNode) {\n const { data = null, properties, type } = _node;\n if (data !== node.data) {\n node.data = data;\n }\n\n if (type !== node.type) {\n node.type = type;\n }\n\n for (const key in properties) {\n if (properties[key] !== node.properties[key]) {\n node.properties[key] = properties[key];\n }\n }\n } else {\n this._nodes[node.id] = node;\n this._edges[node.id] = live({ inbound: [], outbound: [] });\n }\n\n const trigger = this._waitingForNodes[node.id];\n if (trigger) {\n trigger.wake(node);\n delete this._waitingForNodes[node.id];\n }\n\n if (nodes) {\n nodes.forEach((subNode) => {\n this._addNode(subNode);\n this._addEdge({ source: node.id, target: subNode.id });\n });\n }\n\n if (edges) {\n edges.forEach(([id, relation]) =>\n relation === 'outbound'\n ? this._addEdge({ source: node.id, target: id })\n : this._addEdge({ source: id, target: node.id }),\n );\n }\n\n return node as unknown as Node<TData, TProperties>;\n });\n }\n\n /**\n * Remove nodes from the graph.\n *\n * @param ids The id of the node to remove.\n * @param edges Whether to remove edges connected to the node from the graph as well.\n * @internal\n */\n _removeNodes(ids: string[], edges = false) {\n batch(() => ids.forEach((id) => this._removeNode(id, edges)));\n }\n\n private _removeNode(id: string, edges = false) {\n untracked(() => {\n const node = this.findNode(id, false);\n if (!node) {\n return;\n }\n\n if (edges) {\n // Remove edges from connected nodes.\n this._getNodes({ node }).forEach((node) => {\n this._removeEdge({ source: id, target: node.id });\n });\n this._getNodes({ node, relation: 'inbound' }).forEach((node) => {\n this._removeEdge({ source: node.id, target: id });\n });\n\n // Remove edges from node.\n delete this._edges[id];\n }\n\n // Remove node.\n delete this._nodes[id];\n Object.keys(this._initialized)\n .filter((key) => key.startsWith(id))\n .forEach((key) => {\n delete this._initialized[key];\n });\n void this._onRemoveNode?.(id);\n });\n }\n\n /**\n * Add edges to the graph.\n *\n * @internal\n */\n _addEdges(edges: { source: string; target: string }[]) {\n batch(() => edges.forEach((edge) => this._addEdge(edge)));\n }\n\n private _addEdge({ source, target }: { source: string; target: string }) {\n untracked(() => {\n if (!this._edges[source]) {\n this._edges[source] = live({ inbound: [], outbound: [] });\n }\n if (!this._edges[target]) {\n this._edges[target] = live({ inbound: [], outbound: [] });\n }\n\n const sourceEdges = this._edges[source];\n if (!sourceEdges.outbound.includes(target)) {\n sourceEdges.outbound.push(target);\n }\n\n const targetEdges = this._edges[target];\n if (!targetEdges.inbound.includes(source)) {\n targetEdges.inbound.push(source);\n }\n });\n }\n\n /**\n * Remove edges from the graph.\n * @internal\n */\n _removeEdges(edges: { source: string; target: string }[], removeOrphans = false) {\n batch(() => edges.forEach((edge) => this._removeEdge(edge, removeOrphans)));\n }\n\n private _removeEdge({ source, target }: { source: string; target: string }, removeOrphans = false) {\n untracked(() => {\n batch(() => {\n const outboundIndex = this._edges[source]?.outbound.findIndex((id) => id === target);\n if (outboundIndex !== undefined && outboundIndex !== -1) {\n this._edges[source].outbound.splice(outboundIndex, 1);\n }\n\n const inboundIndex = this._edges[target]?.inbound.findIndex((id) => id === source);\n if (inboundIndex !== undefined && inboundIndex !== -1) {\n this._edges[target].inbound.splice(inboundIndex, 1);\n }\n\n if (removeOrphans) {\n if (\n this._edges[source]?.outbound.length === 0 &&\n this._edges[source]?.inbound.length === 0 &&\n source !== ROOT_ID\n ) {\n this._removeNode(source, true);\n }\n if (\n this._edges[target]?.outbound.length === 0 &&\n this._edges[target]?.inbound.length === 0 &&\n target !== ROOT_ID\n ) {\n this._removeNode(target, true);\n }\n }\n });\n });\n }\n\n /**\n * Sort edges for a node.\n *\n * Edges not included in the sorted list are appended to the end of the list.\n *\n * @param nodeId The id of the node to sort edges for.\n * @param relation The relation of the edges from the node to sort.\n * @param edges The ordered list of edges.\n * @ignore\n */\n _sortEdges(nodeId: string, relation: Relation, edges: string[]) {\n untracked(() => {\n batch(() => {\n const current = this._edges[nodeId];\n if (current) {\n const unsorted = current[relation].filter((id) => !edges.includes(id)) ?? [];\n const sorted = edges.filter((id) => current[relation].includes(id)) ?? [];\n current[relation].splice(0, current[relation].length, ...[...sorted, ...unsorted]);\n }\n });\n });\n }\n\n private _constructNode = (node: Omit<Node, typeof graphSymbol>) => {\n return live<NodeInternal>({ ...node, [graphSymbol]: this });\n };\n\n private _getNodes({\n node,\n relation = 'outbound',\n type,\n expansion,\n }: {\n node: Node;\n relation?: Relation;\n type?: string;\n expansion?: boolean;\n }): Node[] {\n if (expansion) {\n void this.expand(node, relation, type);\n }\n\n const edges = this._edges[node.id];\n if (!edges) {\n return [];\n } else {\n return edges[relation]\n .map((id) => this._nodes[id])\n .filter(isNonNullable)\n .filter((n) => !type || n.type === type);\n }\n }\n}\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { type MaybePromise, type MakeOptional } from '@dxos/util';\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 Relation = 'outbound' | 'inbound';\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, Relation][];\n};\n\n//\n// Actions\n//\n\nexport type InvokeParams = {\n /** Node the invoked action is connected to. */\n node: Node;\n\n caller?: string;\n};\n\nexport type ActionData = (params: InvokeParams) => MaybePromise<void>;\n\nexport type Action<TProperties extends Record<string, any> = Record<string, any>> = Readonly<\n Omit<Node<ActionData, TProperties>, 'properties'> & {\n properties: Readonly<TProperties>;\n }\n>;\n\nexport const isAction = (data: unknown): data is Action =>\n isGraphNode(data) ? typeof data.data === 'function' : 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 : false;\n\nexport type ActionLike = Action | ActionGroup;\n\nexport const isActionLike = (data: unknown): data is Action | ActionGroup => isAction(data) || isActionGroup(data);\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { effect, type Signal, signal, untracked } from '@preact/signals-core';\n\nimport { Trigger, type CleanupFn } from '@dxos/async';\nimport { invariant } from '@dxos/invariant';\nimport { live } from '@dxos/live-object';\nimport { log } from '@dxos/log';\nimport { byPosition, type Position, isNode, type MaybePromise, isNonNullable } from '@dxos/util';\n\nimport { ACTION_GROUP_TYPE, ACTION_TYPE, Graph, ROOT_ID, type GraphParams } from './graph';\nimport { type ActionData, actionGroupSymbol, type Node, type NodeArg, type Relation } from './node';\n\nconst NODE_RESOLVER_TIMEOUT = 1_000;\n\n/**\n * Graph builder extension for adding nodes to the graph based on just the node id.\n * This is useful for creating the first node in a graph or for hydrating cached nodes with data.\n *\n * @param params.id The id of the node to resolve.\n */\nexport type ResolverExtension = (params: { id: string }) => NodeArg<any> | false | undefined;\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<T = any> = (params: { node: Node<T> }) => NodeArg<any>[] | undefined;\n\n/**\n * Constrained case of the connector extension for more easily adding actions to the graph.\n */\nexport type ActionsExtension<T = any> = (params: {\n node: Node<T>;\n}) => Omit<NodeArg<ActionData>, 'type' | 'nodes' | 'edges'>[] | undefined;\n\n/**\n * Constrained case of the connector extension for more easily adding action groups to the graph.\n */\nexport type ActionGroupsExtension<T = any> = (params: {\n node: Node<T>;\n}) => Omit<NodeArg<typeof actionGroupSymbol>, 'type' | 'data' | 'nodes' | 'edges'>[] | undefined;\n\ntype GuardedNodeType<T> = T extends (value: any) => value is infer N ? (N extends Node<infer D> ? D : unknown) : never;\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.type If provided, all nodes returned are expected to have this type.\n * @param params.disposition Affects the order the extensions are processed in.\n * @param params.filter A filter function to determine if an extension should act on a node.\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 CreateExtensionOptions<T = any> = {\n id: string;\n relation?: Relation;\n type?: string;\n position?: Position;\n filter?: (node: Node) => node is Node<T>;\n resolver?: ResolverExtension;\n connector?: ConnectorExtension<GuardedNodeType<CreateExtensionOptions<T>['filter']>>;\n actions?: ActionsExtension<GuardedNodeType<CreateExtensionOptions<T>['filter']>>;\n actionGroups?: ActionGroupsExtension<GuardedNodeType<CreateExtensionOptions<T>['filter']>>;\n};\n\n/**\n * Create a graph builder extension.\n */\nexport const createExtension = <T = any>(extension: CreateExtensionOptions<T>): BuilderExtension[] => {\n const { id, position = 'static', resolver, connector, actions, actionGroups, ...rest } = extension;\n const getId = (key: string) => `${id}/${key}`;\n return [\n resolver ? { id: getId('resolver'), position, resolver } : undefined,\n connector ? { ...rest, id: getId('connector'), position, connector } : undefined,\n actionGroups\n ? ({\n ...rest,\n id: getId('actionGroups'),\n position,\n type: ACTION_GROUP_TYPE,\n relation: 'outbound',\n connector: ({ node }) =>\n actionGroups({ node })?.map((arg) => ({ ...arg, data: actionGroupSymbol, type: ACTION_GROUP_TYPE })),\n } satisfies BuilderExtension)\n : undefined,\n actions\n ? ({\n ...rest,\n id: getId('actions'),\n position,\n type: ACTION_TYPE,\n relation: 'outbound',\n connector: ({ node }) => actions({ node })?.map((arg) => ({ ...arg, type: ACTION_TYPE })),\n } satisfies BuilderExtension)\n : undefined,\n ].filter(isNonNullable);\n};\n\nexport type GraphBuilderTraverseOptions = {\n visitor: (node: Node, path: string[]) => MaybePromise<boolean | void>;\n node?: Node;\n relation?: Relation;\n};\n\n/**\n * The dispatcher is used to keep track of the current extension and state when memoizing functions.\n */\nclass Dispatcher {\n currentExtension?: string;\n stateIndex = 0;\n state: Record<string, any[]> = {};\n cleanup: (() => void)[] = [];\n}\n\nclass BuilderInternal {\n // This must be static to avoid passing the dispatcher instance to every memoized function.\n // If the dispatcher is not set that means that the memoized function is being called outside of the graph builder.\n static currentDispatcher?: Dispatcher;\n}\n\n/**\n * Allows code to be memoized within the context of a graph builder extension.\n * This is useful for creating instances which should be subscribed to rather than recreated.\n */\nexport const memoize = <T>(fn: () => T, key = 'result'): T => {\n const dispatcher = BuilderInternal.currentDispatcher;\n invariant(dispatcher?.currentExtension, 'memoize must be called within an extension');\n const all = dispatcher.state[dispatcher.currentExtension][dispatcher.stateIndex] ?? {};\n const current = all[key];\n const result = current ? current.result : fn();\n dispatcher.state[dispatcher.currentExtension][dispatcher.stateIndex] = { ...all, [key]: { result } };\n dispatcher.stateIndex++;\n return result;\n};\n\n/**\n * Register a cleanup function to be called when the graph builder is destroyed.\n */\nexport const cleanup = (fn: () => void): void => {\n memoize(() => {\n const dispatcher = BuilderInternal.currentDispatcher;\n invariant(dispatcher, 'cleanup must be called within an extension');\n dispatcher.cleanup.push(fn);\n });\n};\n\n/**\n * Convert a subscribe/get pair into a signal.\n */\nexport const toSignal = <T>(\n subscribe: (onChange: () => void) => () => void,\n get: () => T | undefined,\n key?: string,\n) => {\n const thisSignal = memoize(() => {\n return signal(get());\n }, key);\n const unsubscribe = memoize(() => {\n return subscribe(() => (thisSignal.value = get()));\n }, key);\n cleanup(() => {\n unsubscribe();\n });\n return thisSignal.value;\n};\n\nexport type BuilderExtension = Readonly<{\n id: string;\n position: Position;\n resolver?: ResolverExtension;\n connector?: ConnectorExtension;\n // Only for connector.\n relation?: Relation;\n type?: string;\n filter?: (node: Node) => boolean;\n}>;\n\ntype ExtensionArg = BuilderExtension | BuilderExtension[] | ExtensionArg[];\n\nexport const flattenExtensions = (extension: ExtensionArg, 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\n/**\n * The builder provides an extensible way to compose the construction of the graph.\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.\nexport class GraphBuilder {\n private readonly _dispatcher = new Dispatcher();\n private readonly _extensions = live<Record<string, BuilderExtension>>({});\n private readonly _resolverSubscriptions = new Map<string, CleanupFn>();\n private readonly _connectorSubscriptions = new Map<string, CleanupFn>();\n private readonly _nodeChanged: Record<string, Signal<{}>> = {};\n private readonly _initialized: Record<string, Trigger> = {};\n private _graph: Graph;\n\n constructor(params: Pick<GraphParams, 'nodes' | 'edges'> = {}) {\n this._graph = new Graph({\n ...params,\n onInitialNode: async (id) => this._onInitialNode(id),\n onInitialNodes: async (node, relation, type) => this._onInitialNodes(node, relation, type),\n onRemoveNode: (id) => this._onRemoveNode(id),\n });\n }\n\n static from(pickle?: string) {\n if (!pickle) {\n return new GraphBuilder();\n }\n\n const { nodes, edges } = JSON.parse(pickle);\n return new GraphBuilder({ nodes, edges });\n }\n\n /**\n * If graph is being restored from a pickle, the data will be null.\n * Initialize the data of each node by calling resolvers.\n * Wait until all of the initial nodes have resolved.\n */\n async initialize() {\n Object.keys(this._graph._nodes)\n .filter((id) => id !== ROOT_ID)\n .forEach((id) => (this._initialized[id] = new Trigger()));\n Object.keys(this._graph._nodes).forEach((id) => this._onInitialNode(id));\n await Promise.all(\n Object.entries(this._initialized).map(async ([id, trigger]) => {\n try {\n await trigger.wait({ timeout: NODE_RESOLVER_TIMEOUT });\n } catch {\n log.error('node resolver timeout', { id });\n this.graph._removeNodes([id]);\n }\n }),\n );\n }\n\n get graph() {\n return this._graph;\n }\n\n /**\n * @reactive\n */\n get extensions() {\n return Object.values(this._extensions);\n }\n\n /**\n * Register a node builder which will be called in order to construct the graph.\n */\n addExtension(extension: ExtensionArg): GraphBuilder {\n const extensions = flattenExtensions(extension);\n untracked(() => {\n extensions.forEach((extension) => {\n this._dispatcher.state[extension.id] = [];\n this._extensions[extension.id] = extension;\n });\n });\n return this;\n }\n\n /**\n * Remove a node builder from the graph builder.\n */\n removeExtension(id: string): GraphBuilder {\n untracked(() => {\n delete this._extensions[id];\n });\n return this;\n }\n\n destroy() {\n this._dispatcher.cleanup.forEach((fn) => fn());\n this._resolverSubscriptions.forEach((unsubscribe) => unsubscribe());\n this._connectorSubscriptions.forEach((unsubscribe) => unsubscribe());\n this._resolverSubscriptions.clear();\n this._connectorSubscriptions.clear();\n }\n\n /**\n * A graph traversal using just the connector extensions, without subscribing to any signals or persisting any nodes.\n */\n async explore(\n { node = this._graph.root, relation = 'outbound', visitor }: GraphBuilderTraverseOptions,\n path: string[] = [],\n ) {\n // Break cycles.\n if (path.includes(node.id)) {\n return;\n }\n\n // TODO(wittjosiah): This is a workaround for esm not working in the test runner.\n // Switching to vitest is blocked by having node esm versions of echo-schema & echo-signals.\n if (!isNode()) {\n const { yieldOrContinue } = await import('main-thread-scheduling');\n await yieldOrContinue('idle');\n }\n const shouldContinue = await visitor(node, [...path, node.id]);\n if (shouldContinue === false) {\n return;\n }\n\n const nodes = Object.values(this._extensions)\n .filter((extension) => relation === (extension.relation ?? 'outbound'))\n .filter((extension) => !extension.filter || extension.filter(node))\n .flatMap((extension) => {\n this._dispatcher.currentExtension = extension.id;\n this._dispatcher.stateIndex = 0;\n BuilderInternal.currentDispatcher = this._dispatcher;\n const result = extension.connector?.({ node }) ?? [];\n BuilderInternal.currentDispatcher = undefined;\n return result;\n })\n .map(\n (arg): Node => ({\n id: arg.id,\n type: arg.type,\n cacheable: arg.cacheable,\n data: arg.data ?? null,\n properties: arg.properties ?? {},\n }),\n );\n\n await Promise.all(nodes.map((n) => this.explore({ node: n, relation, visitor }, [...path, node.id])));\n }\n\n private _onInitialNode(nodeId: string) {\n this._nodeChanged[nodeId] = this._nodeChanged[nodeId] ?? signal({});\n this._resolverSubscriptions.set(\n nodeId,\n effect(() => {\n const extensions = Object.values(this._extensions).toSorted(byPosition);\n for (const { id, resolver } of extensions) {\n if (!resolver) {\n continue;\n }\n\n this._dispatcher.currentExtension = id;\n this._dispatcher.stateIndex = 0;\n BuilderInternal.currentDispatcher = this._dispatcher;\n let node: NodeArg<any> | false | undefined;\n try {\n node = resolver({ id: nodeId });\n } catch (err) {\n log.catch(err, { extension: id });\n log.error(`Previous error occurred in extension: ${id}`);\n } finally {\n BuilderInternal.currentDispatcher = undefined;\n }\n\n const trigger = this._initialized[nodeId];\n if (node) {\n this.graph._addNodes([node]);\n trigger?.wake();\n if (this._nodeChanged[node.id]) {\n this._nodeChanged[node.id].value = {};\n }\n break;\n } else if (node === false) {\n this.graph._removeNodes([nodeId]);\n trigger?.wake();\n break;\n }\n }\n }),\n );\n }\n\n private _onInitialNodes(node: Node, nodesRelation: Relation, nodesType?: string) {\n this._nodeChanged[node.id] = this._nodeChanged[node.id] ?? signal({});\n let first = true;\n let previous: string[] = [];\n this._connectorSubscriptions.set(\n node.id,\n effect(() => {\n // TODO(wittjosiah): This is a workaround for a race between the node removal and the effect re-running.\n // To cause this case to happen, remove a collection and then undo the removal.\n if (!first && !this._connectorSubscriptions.has(node.id)) {\n return;\n }\n first = false;\n\n // Subscribe to extensions being added.\n Object.keys(this._extensions);\n // Subscribe to connected node changes.\n this._nodeChanged[node.id].value;\n\n // TODO(wittjosiah): Consider allowing extensions to collaborate on the same node by merging their results.\n const nodes: NodeArg<any>[] = [];\n const extensions = Object.values(this._extensions).toSorted(byPosition);\n for (const { id, connector, filter, type, relation = 'outbound' } of extensions) {\n if (\n !connector ||\n relation !== nodesRelation ||\n (nodesType && type !== nodesType) ||\n (filter && !filter(node))\n ) {\n continue;\n }\n\n this._dispatcher.currentExtension = id;\n this._dispatcher.stateIndex = 0;\n BuilderInternal.currentDispatcher = this._dispatcher;\n try {\n nodes.push(...(connector({ node }) ?? []));\n } catch (err) {\n log.catch(err, { extension: id });\n log.error(`Previous error occurred in extension: ${id}`);\n } finally {\n BuilderInternal.currentDispatcher = undefined;\n }\n }\n\n const ids = nodes.map((n) => n.id);\n const removed = previous.filter((id) => !ids.includes(id));\n previous = ids;\n\n // Remove edges and only remove nodes that are orphaned.\n this.graph._removeEdges(\n removed.map((target) => ({ source: node.id, target })),\n true,\n );\n this.graph._addNodes(nodes);\n this.graph._addEdges(\n nodes.map(({ id }) =>\n nodesRelation === 'outbound' ? { source: node.id, target: id } : { source: id, target: node.id },\n ),\n );\n this.graph._sortEdges(\n node.id,\n nodesRelation,\n nodes.map(({ id }) => id),\n );\n nodes.forEach((n) => {\n if (this._nodeChanged[n.id]) {\n this._nodeChanged[n.id].value = {};\n }\n });\n }),\n );\n }\n\n private async _onRemoveNode(nodeId: string) {\n this._resolverSubscriptions.get(nodeId)?.();\n this._connectorSubscriptions.get(nodeId)?.();\n this._resolverSubscriptions.delete(nodeId);\n this._connectorSubscriptions.delete(nodeId);\n }\n}\n"],
4
+ "sourcesContent": ["//\n// Copyright 2023 DXOS.org\n//\n\nimport { batch, effect, untracked } from '@preact/signals-core';\n\nimport { asyncTimeout, Trigger } from '@dxos/async';\nimport { invariant } from '@dxos/invariant';\nimport { type Live, live } from '@dxos/live-object';\nimport { log } from '@dxos/log';\nimport { type MakeOptional, isNonNullable, pick } from '@dxos/util';\n\nimport { type Node, type NodeArg, type NodeFilter, type Relation, actionGroupSymbol, isActionLike } from './node';\n\nconst graphSymbol = Symbol('graph');\ntype DeepWriteable<T> = { -readonly [K in keyof T]: T[K] extends object ? DeepWriteable<T[K]> : T[K] };\ntype NodeInternal = DeepWriteable<Node> & { [graphSymbol]: Graph };\n\nexport const getGraph = (node: Node): Graph => {\n const graph = (node as NodeInternal)[graphSymbol];\n invariant(graph, 'Node is not associated with a graph.');\n return graph;\n};\n\nexport const ROOT_ID = 'root';\nexport const ROOT_TYPE = 'dxos.org/type/GraphRoot';\nexport const ACTION_TYPE = 'dxos.org/type/GraphAction';\nexport const ACTION_GROUP_TYPE = 'dxos.org/type/GraphActionGroup';\n\nexport type NodesOptions<TData = any, TProperties extends Record<string, any> = Record<string, any>> = {\n relation?: Relation;\n filter?: NodeFilter<TData, TProperties>;\n expansion?: boolean;\n type?: string;\n};\n\n// TODO(wittjosiah): Consider having default be undefined. This is current default for backwards compatibility.\nconst DEFAULT_FILTER = (node: Node) => untracked(() => !isActionLike(node));\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, path: string[]) => boolean | void;\n\n /**\n * The node to start traversing from.\n *\n * @default root\n */\n node?: Node;\n\n /**\n * The relation to traverse graph edges.\n *\n * @default 'outbound'\n */\n relation?: Relation;\n\n /**\n * Allow traversal to trigger expansion of the graph via `onInitialNodes`.\n */\n expansion?: boolean;\n};\n\nexport type GraphParams = {\n nodes?: MakeOptional<Node, 'data' | 'cacheable'>[];\n edges?: Record<string, string[]>;\n onInitialNode?: Graph['_onInitialNode'];\n onInitialNodes?: Graph['_onInitialNodes'];\n onRemoveNode?: Graph['_onRemoveNode'];\n};\n\n/**\n * The Graph represents the structure of the application constructed via plugins.\n */\nexport class Graph {\n private readonly _onInitialNode?: (id: string) => Promise<void>;\n private readonly _onInitialNodes?: (node: Node, relation: Relation, type?: string) => Promise<void>;\n private readonly _onRemoveNode?: (id: string) => Promise<void>;\n\n private readonly _waitingForNodes: Record<string, Trigger<Node>> = {};\n private readonly _initialized: Record<string, boolean> = {};\n\n /**\n * @internal\n */\n readonly _nodes: Record<string, Live<NodeInternal>> = {};\n\n /**\n * @internal\n */\n readonly _edges: Record<string, Live<{ inbound: string[]; outbound: string[] }>> = {};\n\n constructor({ nodes, edges, onInitialNode, onInitialNodes, onRemoveNode }: GraphParams = {}) {\n this._onInitialNode = onInitialNode;\n this._onInitialNodes = onInitialNodes;\n this._onRemoveNode = onRemoveNode;\n\n this._nodes[ROOT_ID] = this._constructNode({\n id: ROOT_ID,\n type: ROOT_TYPE,\n cacheable: [],\n properties: {},\n data: null,\n });\n if (nodes) {\n nodes.forEach((node) => {\n const cacheable = Object.keys(node.properties ?? {});\n if (node.type === ACTION_TYPE) {\n this._addNode({ cacheable, data: () => log.warn('Pickled action invocation'), ...node });\n } else if (node.type === ACTION_GROUP_TYPE) {\n this._addNode({ cacheable, data: actionGroupSymbol, ...node });\n } else {\n this._addNode({ cacheable, ...node });\n }\n });\n }\n\n this._edges[ROOT_ID] = live({ inbound: [], outbound: [] });\n if (edges) {\n Object.entries(edges).forEach(([source, edges]) => {\n edges.forEach((target) => {\n this._addEdge({ source, target });\n });\n this._sortEdges(source, 'outbound', edges);\n });\n }\n }\n\n static from(pickle: string, options: Omit<GraphParams, 'nodes' | 'edges'> = {}) {\n const { nodes, edges } = JSON.parse(pickle);\n return new Graph({ nodes, edges, ...options });\n }\n\n /**\n * Alias for `findNode('root')`.\n */\n get root() {\n return this.findNode(ROOT_ID)!;\n }\n\n /**\n * Convert the graph to a JSON object.\n */\n toJSON({ id = ROOT_ID, maxLength = 32 }: { id?: string; maxLength?: number } = {}) {\n const toJSON = (node: Node, seen: string[] = []): any => {\n const nodes = this.nodes(node);\n const obj: Record<string, any> = {\n id: node.id.length > maxLength ? `${node.id.slice(0, maxLength - 3)}...` : 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) => {\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 = this.findNode(id);\n invariant(root, `Node not found: ${id}`);\n return toJSON(root);\n }\n\n pickle() {\n const nodes = Object.values(this._nodes)\n .filter((node) => !!node.cacheable)\n .map((node) => {\n return {\n id: node.id,\n type: node.type,\n properties: pick(node.properties, node.cacheable!),\n };\n });\n\n const cacheable = new Set(nodes.map((node) => node.id));\n\n const edges = Object.fromEntries(\n Object.entries(this._edges)\n .filter(([id]) => cacheable.has(id))\n .map(([id, { outbound }]): [string, string[]] => [id, outbound.filter((nodeId) => cacheable.has(nodeId))])\n // TODO(wittjosiah): Why sort?\n .toSorted(([a], [b]) => a.localeCompare(b)),\n );\n\n return JSON.stringify({ nodes, edges });\n }\n\n /**\n * Find the node with the given id in the graph.\n *\n * If a node is not found within the graph and an `onInitialNode` callback is provided,\n * it is called with the id and type of the node, potentially initializing the node.\n */\n findNode(id: string, expansion = true): Node | undefined {\n const existingNode = this._nodes[id];\n if (!existingNode && expansion) {\n void this._onInitialNode?.(id);\n }\n\n return existingNode;\n }\n\n /**\n * Wait for a node to be added to the graph.\n *\n * If the node is already present in the graph, the promise resolves immediately.\n *\n * @param id The id of the node to wait for.\n * @param timeout The time in milliseconds to wait for the node to be added.\n */\n async waitForNode(id: string, timeout?: number): Promise<Node> {\n const trigger = this._waitingForNodes[id] ?? (this._waitingForNodes[id] = new Trigger<Node>());\n const node = this.findNode(id);\n if (node) {\n delete this._waitingForNodes[id];\n return node;\n }\n\n if (timeout === undefined) {\n return trigger.wait();\n } else {\n return asyncTimeout(trigger.wait(), timeout, `Node not found: ${id}`);\n }\n }\n\n /**\n * Nodes that this node is connected to in default order.\n */\n nodes<TData = any, TProperties extends Record<string, any> = Record<string, any>>(\n node: Node,\n options: NodesOptions<TData, TProperties> = {},\n ) {\n const { relation, expansion, filter = DEFAULT_FILTER, type } = options;\n const nodes = this._getNodes({ node, relation, expansion, type });\n return nodes.filter((n) => filter(n, node));\n }\n\n /**\n * Edges that this node is connected to in default order.\n */\n edges(node: Node, { relation = 'outbound' }: { relation?: Relation } = {}) {\n return this._edges[node.id]?.[relation] ?? [];\n }\n\n /**\n * Actions or action groups that this node is connected to in default order.\n */\n actions(node: Node, { expansion }: { expansion?: boolean } = {}) {\n return [\n ...this._getNodes({ node, expansion, type: ACTION_GROUP_TYPE }),\n ...this._getNodes({ node, expansion, type: ACTION_TYPE }),\n ];\n }\n\n async expand(node: Node, relation: Relation = 'outbound', type?: string) {\n const key = this._key(node, relation, type);\n const initialized = this._initialized[key];\n if (!initialized && this._onInitialNodes) {\n await this._onInitialNodes(node, relation, type);\n this._initialized[key] = true;\n }\n }\n\n private _key(node: Node, relation: Relation, type?: string) {\n return `${node.id}-${relation}-${type}`;\n }\n\n /**\n * Recursive depth-first traversal of the graph.\n *\n * @param options.node The node to start traversing from.\n * @param options.relation The relation to traverse graph edges.\n * @param options.visitor A callback which is called for each node visited during traversal.\n */\n traverse(\n { visitor, node = this.root, relation = 'outbound', expansion }: GraphTraversalOptions,\n path: string[] = [],\n ): void {\n // Break cycles.\n if (path.includes(node.id)) {\n return;\n }\n\n const shouldContinue = visitor(node, [...path, node.id]);\n if (shouldContinue === false) {\n return;\n }\n\n Object.values(this._getNodes({ node, relation, expansion })).forEach((child) =>\n this.traverse({ node: child, relation, visitor, expansion }, [...path, node.id]),\n );\n }\n\n /**\n * Recursive depth-first traversal of the graph wrapping each visitor call in an effect.\n *\n * @param options.node The node to start traversing from.\n * @param options.relation The relation to traverse graph edges.\n * @param options.visitor A callback which is called for each node visited during traversal.\n */\n subscribeTraverse(\n { visitor, node = this.root, relation = 'outbound', expansion }: GraphTraversalOptions,\n currentPath: string[] = [],\n ) {\n return effect(() => {\n const path = [...currentPath, node.id];\n const result = visitor(node, path);\n if (result === false) {\n return;\n }\n\n const nodes = this._getNodes({ node, relation, expansion });\n const nodeSubscriptions = nodes.map((n) => this.subscribeTraverse({ node: n, visitor, expansion }, path));\n return () => {\n nodeSubscriptions.forEach((unsubscribe) => unsubscribe());\n };\n });\n }\n\n /**\n * Get the path between two nodes in the graph.\n */\n getPath({ source = 'root', target }: { source?: string; target: string }): string[] | undefined {\n const start = this.findNode(source);\n if (!start) {\n return undefined;\n }\n\n let found: string[] | undefined;\n this.traverse({\n node: start,\n visitor: (node, path) => {\n if (found) {\n return false;\n }\n\n if (node.id === target) {\n found = path;\n }\n },\n });\n\n return found;\n }\n\n /**\n * Wait for the path between two nodes in the graph to be established.\n */\n async waitForPath(\n params: { source?: string; target: string },\n { timeout = 5_000, interval = 500 }: { timeout?: number; interval?: number } = {},\n ) {\n const path = this.getPath(params);\n if (path) {\n return path;\n }\n\n const trigger = new Trigger<string[]>();\n const i = setInterval(() => {\n const path = this.getPath(params);\n if (path) {\n trigger.wake(path);\n }\n }, interval);\n\n return trigger.wait({ timeout }).finally(() => clearInterval(i));\n }\n\n /**\n * Add nodes to the graph.\n *\n * @internal\n */\n _addNodes<TData = null, TProperties extends Record<string, any> = Record<string, any>>(\n nodes: NodeArg<TData, TProperties>[],\n ): Node<TData, TProperties>[] {\n return batch(() => nodes.map((node) => this._addNode(node)));\n }\n\n private _addNode<TData, TProperties extends Record<string, any> = Record<string, any>>({\n nodes,\n edges,\n ..._node\n }: NodeArg<TData, TProperties>): Node<TData, TProperties> {\n return untracked(() => {\n const existingNode = this._nodes[_node.id];\n const node = existingNode ?? this._constructNode({ data: null, properties: {}, ..._node });\n if (existingNode) {\n const { data = null, properties, type } = _node;\n if (data !== node.data) {\n node.data = data;\n }\n\n if (type !== node.type) {\n node.type = type;\n }\n\n for (const key in properties) {\n if (properties[key] !== node.properties[key]) {\n node.properties[key] = properties[key];\n }\n }\n } else {\n this._nodes[node.id] = node;\n this._edges[node.id] = live({ inbound: [], outbound: [] });\n }\n\n const trigger = this._waitingForNodes[node.id];\n if (trigger) {\n trigger.wake(node);\n delete this._waitingForNodes[node.id];\n }\n\n if (nodes) {\n nodes.forEach((subNode) => {\n this._addNode(subNode);\n this._addEdge({ source: node.id, target: subNode.id });\n });\n }\n\n if (edges) {\n edges.forEach(([id, relation]) =>\n relation === 'outbound'\n ? this._addEdge({ source: node.id, target: id })\n : this._addEdge({ source: id, target: node.id }),\n );\n }\n\n return node as unknown as Node<TData, TProperties>;\n });\n }\n\n /**\n * Remove nodes from the graph.\n *\n * @param ids The id of the node to remove.\n * @param edges Whether to remove edges connected to the node from the graph as well.\n * @internal\n */\n _removeNodes(ids: string[], edges = false) {\n batch(() => ids.forEach((id) => this._removeNode(id, edges)));\n }\n\n private _removeNode(id: string, edges = false) {\n untracked(() => {\n const node = this.findNode(id, false);\n if (!node) {\n return;\n }\n\n if (edges) {\n // Remove edges from connected nodes.\n this._getNodes({ node }).forEach((node) => {\n this._removeEdge({ source: id, target: node.id });\n });\n this._getNodes({ node, relation: 'inbound' }).forEach((node) => {\n this._removeEdge({ source: node.id, target: id });\n });\n\n // Remove edges from node.\n delete this._edges[id];\n }\n\n // Remove node.\n delete this._nodes[id];\n Object.keys(this._initialized)\n .filter((key) => key.startsWith(id))\n .forEach((key) => {\n delete this._initialized[key];\n });\n void this._onRemoveNode?.(id);\n });\n }\n\n /**\n * Add edges to the graph.\n *\n * @internal\n */\n _addEdges(edges: { source: string; target: string }[]) {\n batch(() => edges.forEach((edge) => this._addEdge(edge)));\n }\n\n private _addEdge({ source, target }: { source: string; target: string }) {\n untracked(() => {\n if (!this._edges[source]) {\n this._edges[source] = live({ inbound: [], outbound: [] });\n }\n if (!this._edges[target]) {\n this._edges[target] = live({ inbound: [], outbound: [] });\n }\n\n const sourceEdges = this._edges[source];\n if (!sourceEdges.outbound.includes(target)) {\n sourceEdges.outbound.push(target);\n }\n\n const targetEdges = this._edges[target];\n if (!targetEdges.inbound.includes(source)) {\n targetEdges.inbound.push(source);\n }\n });\n }\n\n /**\n * Remove edges from the graph.\n * @internal\n */\n _removeEdges(edges: { source: string; target: string }[], removeOrphans = false) {\n batch(() => edges.forEach((edge) => this._removeEdge(edge, removeOrphans)));\n }\n\n private _removeEdge({ source, target }: { source: string; target: string }, removeOrphans = false) {\n untracked(() => {\n batch(() => {\n const outboundIndex = this._edges[source]?.outbound.findIndex((id) => id === target);\n if (outboundIndex !== undefined && outboundIndex !== -1) {\n this._edges[source].outbound.splice(outboundIndex, 1);\n }\n\n const inboundIndex = this._edges[target]?.inbound.findIndex((id) => id === source);\n if (inboundIndex !== undefined && inboundIndex !== -1) {\n this._edges[target].inbound.splice(inboundIndex, 1);\n }\n\n if (removeOrphans) {\n if (\n this._edges[source]?.outbound.length === 0 &&\n this._edges[source]?.inbound.length === 0 &&\n source !== ROOT_ID\n ) {\n this._removeNode(source, true);\n }\n if (\n this._edges[target]?.outbound.length === 0 &&\n this._edges[target]?.inbound.length === 0 &&\n target !== ROOT_ID\n ) {\n this._removeNode(target, true);\n }\n }\n });\n });\n }\n\n /**\n * Sort edges for a node.\n *\n * Edges not included in the sorted list are appended to the end of the list.\n *\n * @param nodeId The id of the node to sort edges for.\n * @param relation The relation of the edges from the node to sort.\n * @param edges The ordered list of edges.\n * @ignore\n */\n _sortEdges(nodeId: string, relation: Relation, edges: string[]) {\n untracked(() => {\n batch(() => {\n const current = this._edges[nodeId];\n if (current) {\n const unsorted = current[relation].filter((id) => !edges.includes(id)) ?? [];\n const sorted = edges.filter((id) => current[relation].includes(id)) ?? [];\n current[relation].splice(0, current[relation].length, ...[...sorted, ...unsorted]);\n }\n });\n });\n }\n\n private _constructNode = (node: Omit<Node, typeof graphSymbol>) => {\n return live<NodeInternal>({ ...node, [graphSymbol]: this });\n };\n\n private _getNodes({\n node,\n relation = 'outbound',\n type,\n expansion,\n }: {\n node: Node;\n relation?: Relation;\n type?: string;\n expansion?: boolean;\n }): Node[] {\n if (expansion) {\n void this.expand(node, relation, type);\n }\n\n const edges = this._edges[node.id];\n if (!edges) {\n return [];\n } else {\n return edges[relation]\n .map((id) => this._nodes[id])\n .filter(isNonNullable)\n .filter((n) => !type || n.type === type);\n }\n }\n}\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { type MaybePromise, type MakeOptional } from '@dxos/util';\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 Relation = 'outbound' | 'inbound';\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, Relation][];\n};\n\n//\n// Actions\n//\n\nexport type InvokeParams = {\n /** Node the invoked action is connected to. */\n parent?: Node;\n\n caller?: string;\n};\n\nexport type ActionData = (params?: InvokeParams) => MaybePromise<void>;\n\nexport type Action<TProperties extends Record<string, any> = Record<string, any>> = Readonly<\n Omit<Node<ActionData, TProperties>, 'properties'> & {\n properties: Readonly<TProperties>;\n }\n>;\n\nexport const isAction = (data: unknown): data is Action =>\n isGraphNode(data) ? typeof data.data === 'function' : 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 : false;\n\nexport type ActionLike = Action | ActionGroup;\n\nexport const isActionLike = (data: unknown): data is Action | ActionGroup => isAction(data) || isActionGroup(data);\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { effect, type Signal, signal, untracked } from '@preact/signals-core';\n\nimport { Trigger, type CleanupFn } from '@dxos/async';\nimport { invariant } from '@dxos/invariant';\nimport { live } from '@dxos/live-object';\nimport { log } from '@dxos/log';\nimport { byPosition, type Position, isNode, type MaybePromise, isNonNullable } from '@dxos/util';\n\nimport { ACTION_GROUP_TYPE, ACTION_TYPE, Graph, ROOT_ID, type GraphParams } from './graph';\nimport { type ActionData, actionGroupSymbol, type Node, type NodeArg, type Relation } from './node';\n\nconst NODE_RESOLVER_TIMEOUT = 1_000;\n\n/**\n * Graph builder extension for adding nodes to the graph based on just the node id.\n * This is useful for creating the first node in a graph or for hydrating cached nodes with data.\n *\n * @param params.id The id of the node to resolve.\n */\nexport type ResolverExtension = (params: { id: string }) => NodeArg<any> | false | undefined;\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<T = any> = (params: { node: Node<T> }) => NodeArg<any>[] | undefined;\n\n/**\n * Constrained case of the connector extension for more easily adding actions to the graph.\n */\nexport type ActionsExtension<T = any> = (params: {\n node: Node<T>;\n}) => Omit<NodeArg<ActionData>, 'type' | 'nodes' | 'edges'>[] | undefined;\n\n/**\n * Constrained case of the connector extension for more easily adding action groups to the graph.\n */\nexport type ActionGroupsExtension<T = any> = (params: {\n node: Node<T>;\n}) => Omit<NodeArg<typeof actionGroupSymbol>, 'type' | 'data' | 'nodes' | 'edges'>[] | undefined;\n\ntype GuardedNodeType<T> = T extends (value: any) => value is infer N ? (N extends Node<infer D> ? D : unknown) : never;\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.type If provided, all nodes returned are expected to have this type.\n * @param params.disposition Affects the order the extensions are processed in.\n * @param params.filter A filter function to determine if an extension should act on a node.\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 CreateExtensionOptions<T = any> = {\n id: string;\n relation?: Relation;\n type?: string;\n position?: Position;\n filter?: (node: Node) => node is Node<T>;\n resolver?: ResolverExtension;\n connector?: ConnectorExtension<GuardedNodeType<CreateExtensionOptions<T>['filter']>>;\n actions?: ActionsExtension<GuardedNodeType<CreateExtensionOptions<T>['filter']>>;\n actionGroups?: ActionGroupsExtension<GuardedNodeType<CreateExtensionOptions<T>['filter']>>;\n};\n\n/**\n * Create a graph builder extension.\n */\nexport const createExtension = <T = any>(extension: CreateExtensionOptions<T>): BuilderExtension[] => {\n const { id, position = 'static', resolver, connector, actions, actionGroups, ...rest } = extension;\n const getId = (key: string) => `${id}/${key}`;\n return [\n resolver ? { id: getId('resolver'), position, resolver } : undefined,\n connector ? { ...rest, id: getId('connector'), position, connector } : undefined,\n actionGroups\n ? ({\n ...rest,\n id: getId('actionGroups'),\n position,\n type: ACTION_GROUP_TYPE,\n relation: 'outbound',\n connector: ({ node }) =>\n actionGroups({ node })?.map((arg) => ({ ...arg, data: actionGroupSymbol, type: ACTION_GROUP_TYPE })),\n } satisfies BuilderExtension)\n : undefined,\n actions\n ? ({\n ...rest,\n id: getId('actions'),\n position,\n type: ACTION_TYPE,\n relation: 'outbound',\n connector: ({ node }) => actions({ node })?.map((arg) => ({ ...arg, type: ACTION_TYPE })),\n } satisfies BuilderExtension)\n : undefined,\n ].filter(isNonNullable);\n};\n\nexport type GraphBuilderTraverseOptions = {\n visitor: (node: Node, path: string[]) => MaybePromise<boolean | void>;\n node?: Node;\n relation?: Relation;\n};\n\n/**\n * The dispatcher is used to keep track of the current extension and state when memoizing functions.\n */\nclass Dispatcher {\n currentExtension?: string;\n stateIndex = 0;\n state: Record<string, any[]> = {};\n cleanup: (() => void)[] = [];\n}\n\nclass BuilderInternal {\n // This must be static to avoid passing the dispatcher instance to every memoized function.\n // If the dispatcher is not set that means that the memoized function is being called outside of the graph builder.\n static currentDispatcher?: Dispatcher;\n}\n\n/**\n * Allows code to be memoized within the context of a graph builder extension.\n * This is useful for creating instances which should be subscribed to rather than recreated.\n */\nexport const memoize = <T>(fn: () => T, key = 'result'): T => {\n const dispatcher = BuilderInternal.currentDispatcher;\n invariant(dispatcher?.currentExtension, 'memoize must be called within an extension');\n const all = dispatcher.state[dispatcher.currentExtension][dispatcher.stateIndex] ?? {};\n const current = all[key];\n const result = current ? current.result : fn();\n dispatcher.state[dispatcher.currentExtension][dispatcher.stateIndex] = { ...all, [key]: { result } };\n dispatcher.stateIndex++;\n return result;\n};\n\n/**\n * Register a cleanup function to be called when the graph builder is destroyed.\n */\nexport const cleanup = (fn: () => void): void => {\n memoize(() => {\n const dispatcher = BuilderInternal.currentDispatcher;\n invariant(dispatcher, 'cleanup must be called within an extension');\n dispatcher.cleanup.push(fn);\n });\n};\n\n/**\n * Convert a subscribe/get pair into a signal.\n */\nexport const toSignal = <T>(\n subscribe: (onChange: () => void) => () => void,\n get: () => T | undefined,\n key?: string,\n) => {\n const thisSignal = memoize(() => {\n return signal(get());\n }, key);\n const unsubscribe = memoize(() => {\n return subscribe(() => (thisSignal.value = get()));\n }, key);\n cleanup(() => {\n unsubscribe();\n });\n return thisSignal.value;\n};\n\nexport type BuilderExtension = Readonly<{\n id: string;\n position: Position;\n resolver?: ResolverExtension;\n connector?: ConnectorExtension;\n // Only for connector.\n relation?: Relation;\n type?: string;\n filter?: (node: Node) => boolean;\n}>;\n\ntype ExtensionArg = BuilderExtension | BuilderExtension[] | ExtensionArg[];\n\nexport const flattenExtensions = (extension: ExtensionArg, 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\n/**\n * The builder provides an extensible way to compose the construction of the graph.\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.\nexport class GraphBuilder {\n private readonly _dispatcher = new Dispatcher();\n private readonly _extensions = live<Record<string, BuilderExtension>>({});\n private readonly _resolverSubscriptions = new Map<string, CleanupFn>();\n private readonly _connectorSubscriptions = new Map<string, CleanupFn>();\n private readonly _nodeChanged: Record<string, Signal<{}>> = {};\n private readonly _initialized: Record<string, Trigger> = {};\n private _graph: Graph;\n\n constructor(params: Pick<GraphParams, 'nodes' | 'edges'> = {}) {\n this._graph = new Graph({\n ...params,\n onInitialNode: async (id) => this._onInitialNode(id),\n onInitialNodes: async (node, relation, type) => this._onInitialNodes(node, relation, type),\n onRemoveNode: (id) => this._onRemoveNode(id),\n });\n }\n\n static from(pickle?: string) {\n if (!pickle) {\n return new GraphBuilder();\n }\n\n const { nodes, edges } = JSON.parse(pickle);\n return new GraphBuilder({ nodes, edges });\n }\n\n /**\n * If graph is being restored from a pickle, the data will be null.\n * Initialize the data of each node by calling resolvers.\n * Wait until all of the initial nodes have resolved.\n */\n async initialize() {\n Object.keys(this._graph._nodes)\n .filter((id) => id !== ROOT_ID)\n .forEach((id) => (this._initialized[id] = new Trigger()));\n Object.keys(this._graph._nodes).forEach((id) => this._onInitialNode(id));\n await Promise.all(\n Object.entries(this._initialized).map(async ([id, trigger]) => {\n try {\n await trigger.wait({ timeout: NODE_RESOLVER_TIMEOUT });\n } catch {\n log.error('node resolver timeout', { id });\n this.graph._removeNodes([id]);\n }\n }),\n );\n }\n\n get graph() {\n return this._graph;\n }\n\n /**\n * @reactive\n */\n get extensions() {\n return Object.values(this._extensions);\n }\n\n /**\n * Register a node builder which will be called in order to construct the graph.\n */\n addExtension(extension: ExtensionArg): GraphBuilder {\n const extensions = flattenExtensions(extension);\n untracked(() => {\n extensions.forEach((extension) => {\n this._dispatcher.state[extension.id] = [];\n this._extensions[extension.id] = extension;\n });\n });\n return this;\n }\n\n /**\n * Remove a node builder from the graph builder.\n */\n removeExtension(id: string): GraphBuilder {\n untracked(() => {\n delete this._extensions[id];\n });\n return this;\n }\n\n destroy() {\n this._dispatcher.cleanup.forEach((fn) => fn());\n this._resolverSubscriptions.forEach((unsubscribe) => unsubscribe());\n this._connectorSubscriptions.forEach((unsubscribe) => unsubscribe());\n this._resolverSubscriptions.clear();\n this._connectorSubscriptions.clear();\n }\n\n /**\n * A graph traversal using just the connector extensions, without subscribing to any signals or persisting any nodes.\n */\n async explore(\n { node = this._graph.root, relation = 'outbound', visitor }: GraphBuilderTraverseOptions,\n path: string[] = [],\n ) {\n // Break cycles.\n if (path.includes(node.id)) {\n return;\n }\n\n // TODO(wittjosiah): This is a workaround for esm not working in the test runner.\n // Switching to vitest is blocked by having node esm versions of echo-schema & echo-signals.\n if (!isNode()) {\n const { yieldOrContinue } = await import('main-thread-scheduling');\n await yieldOrContinue('idle');\n }\n const shouldContinue = await visitor(node, [...path, node.id]);\n if (shouldContinue === false) {\n return;\n }\n\n const nodes = Object.values(this._extensions)\n .filter((extension) => relation === (extension.relation ?? 'outbound'))\n .filter((extension) => !extension.filter || extension.filter(node))\n .flatMap((extension) => {\n this._dispatcher.currentExtension = extension.id;\n this._dispatcher.stateIndex = 0;\n BuilderInternal.currentDispatcher = this._dispatcher;\n const result = extension.connector?.({ node }) ?? [];\n BuilderInternal.currentDispatcher = undefined;\n return result;\n })\n .map(\n (arg): Node => ({\n id: arg.id,\n type: arg.type,\n cacheable: arg.cacheable,\n data: arg.data ?? null,\n properties: arg.properties ?? {},\n }),\n );\n\n await Promise.all(nodes.map((n) => this.explore({ node: n, relation, visitor }, [...path, node.id])));\n }\n\n private _onInitialNode(nodeId: string) {\n this._nodeChanged[nodeId] = this._nodeChanged[nodeId] ?? signal({});\n this._resolverSubscriptions.set(\n nodeId,\n effect(() => {\n const extensions = Object.values(this._extensions).toSorted(byPosition);\n for (const { id, resolver } of extensions) {\n if (!resolver) {\n continue;\n }\n\n this._dispatcher.currentExtension = id;\n this._dispatcher.stateIndex = 0;\n BuilderInternal.currentDispatcher = this._dispatcher;\n let node: NodeArg<any> | false | undefined;\n try {\n node = resolver({ id: nodeId });\n } catch (err) {\n log.catch(err, { extension: id });\n log.error(`Previous error occurred in extension: ${id}`);\n } finally {\n BuilderInternal.currentDispatcher = undefined;\n }\n\n const trigger = this._initialized[nodeId];\n if (node) {\n this.graph._addNodes([node]);\n trigger?.wake();\n if (this._nodeChanged[node.id]) {\n this._nodeChanged[node.id].value = {};\n }\n break;\n } else if (node === false) {\n this.graph._removeNodes([nodeId]);\n trigger?.wake();\n break;\n }\n }\n }),\n );\n }\n\n private _onInitialNodes(node: Node, nodesRelation: Relation, nodesType?: string) {\n this._nodeChanged[node.id] = this._nodeChanged[node.id] ?? signal({});\n let first = true;\n let previous: string[] = [];\n this._connectorSubscriptions.set(\n node.id,\n effect(() => {\n // TODO(wittjosiah): This is a workaround for a race between the node removal and the effect re-running.\n // To cause this case to happen, remove a collection and then undo the removal.\n if (!first && !this._connectorSubscriptions.has(node.id)) {\n return;\n }\n first = false;\n\n // Subscribe to extensions being added.\n Object.keys(this._extensions);\n // Subscribe to connected node changes.\n this._nodeChanged[node.id].value;\n\n // TODO(wittjosiah): Consider allowing extensions to collaborate on the same node by merging their results.\n const nodes: NodeArg<any>[] = [];\n const extensions = Object.values(this._extensions).toSorted(byPosition);\n for (const { id, connector, filter, type, relation = 'outbound' } of extensions) {\n if (\n !connector ||\n relation !== nodesRelation ||\n (nodesType && type !== nodesType) ||\n (filter && !filter(node))\n ) {\n continue;\n }\n\n this._dispatcher.currentExtension = id;\n this._dispatcher.stateIndex = 0;\n BuilderInternal.currentDispatcher = this._dispatcher;\n try {\n nodes.push(...(connector({ node }) ?? []));\n } catch (err) {\n log.catch(err, { extension: id });\n log.error(`Previous error occurred in extension: ${id}`);\n } finally {\n BuilderInternal.currentDispatcher = undefined;\n }\n }\n\n const ids = nodes.map((n) => n.id);\n const removed = previous.filter((id) => !ids.includes(id));\n previous = ids;\n\n // Remove edges and only remove nodes that are orphaned.\n this.graph._removeEdges(\n removed.map((target) => ({ source: node.id, target })),\n true,\n );\n this.graph._addNodes(nodes);\n this.graph._addEdges(\n nodes.map(({ id }) =>\n nodesRelation === 'outbound' ? { source: node.id, target: id } : { source: id, target: node.id },\n ),\n );\n this.graph._sortEdges(\n node.id,\n nodesRelation,\n nodes.map(({ id }) => id),\n );\n nodes.forEach((n) => {\n if (this._nodeChanged[n.id]) {\n this._nodeChanged[n.id].value = {};\n }\n });\n }),\n );\n }\n\n private async _onRemoveNode(nodeId: string) {\n this._resolverSubscriptions.get(nodeId)?.();\n this._connectorSubscriptions.get(nodeId)?.();\n this._resolverSubscriptions.delete(nodeId);\n this._connectorSubscriptions.delete(nodeId);\n }\n}\n"],
5
5
  "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,0BAAyC;AAEzC,mBAAsC;AACtC,uBAA0B;AAC1B,yBAAgC;AAChC,iBAAoB;AACpB,kBAAuD;AENvD,IAAAA,uBAAuD;AAEvD,IAAAC,gBAAwC;AACxC,IAAAC,oBAA0B;AAC1B,IAAAC,sBAAqB;AACrB,IAAAC,cAAoB;AACpB,IAAAC,eAAoF;ADwC7E,IAAMC,cAAc,CAACC,SAC1BA,QAAQ,OAAOA,SAAS,YAAY,QAAQA,QAAQ,gBAAgBA,QAAQA,KAAKC,aAC7E,OAAOD,KAAKC,eAAe,YAAY,UAAUD,OACjD;AAgCC,IAAME,WAAW,CAACF,SACvBD,YAAYC,IAAAA,IAAQ,OAAOA,KAAKA,SAAS,aAAa;AAEjD,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AG,CAAA,CAAA;AAGnG,WAAKvB,MAAMuC,WACTxC,KAAKwB,IACLqK,eACAlL,MAAM4C,IAAI,CAAC,EAAE/B,GAAE,MAAOA,EAAAA,CAAAA;AAExBb,YAAMgB,QAAQ,CAAC6B,MAAAA;AACb,YAAI,KAAKoH,aAAapH,EAAEhC,EAAE,GAAG;AAC3B,eAAKoJ,aAAapH,EAAEhC,EAAE,EAAEuI,QAAQ,CAAC;QACnC;MACF,CAAA;IACF,CAAA,CAAA;EAEJ;EAEA,MAAczI,cAAc6C,QAAgB;AAC1C,SAAKsG,uBAAuBb,IAAIzF,MAAAA,IAAAA;AAChC,SAAKwG,wBAAwBf,IAAIzF,MAAAA,IAAAA;AACjC,SAAKsG,uBAAuByB,OAAO/H,MAAAA;AACnC,SAAKwG,wBAAwBuB,OAAO/H,MAAAA;EACtC;AACF;",
6
6
  "names": ["import_signals_core", "import_async", "import_invariant", "import_live_object", "import_log", "import_util", "isGraphNode", "data", "properties", "isAction", "actionGroupSymbol", "Symbol", "isActionGroup", "isActionLike", "graphSymbol", "getGraph", "node", "graph", "invariant", "ROOT_ID", "ROOT_TYPE", "ACTION_TYPE", "ACTION_GROUP_TYPE", "DEFAULT_FILTER", "untracked", "Graph", "constructor", "nodes", "edges", "onInitialNode", "onInitialNodes", "onRemoveNode", "_waitingForNodes", "_initialized", "_constructNode", "live", "_onInitialNode", "_onInitialNodes", "_onRemoveNode", "_nodes", "id", "type", "cacheable", "forEach", "Object", "keys", "_addNode", "log", "warn", "_edges", "inbound", "outbound", "entries", "source", "target", "_addEdge", "_sortEdges", "from", "pickle", "options", "JSON", "parse", "root", "findNode", "toJSON", "maxLength", "seen", "obj", "length", "slice", "label", "map", "n", "nextSeen", "includes", "undefined", "filter", "isNonNullable", "values", "pick", "Set", "fromEntries", "has", "nodeId", "toSorted", "a", "b", "localeCompare", "stringify", "expansion", "existingNode", "waitForNode", "timeout", "trigger", "Trigger", "wait", "asyncTimeout", "relation", "_getNodes", "actions", "expand", "key", "_key", "initialized", "traverse", "visitor", "path", "shouldContinue", "child", "subscribeTraverse", "currentPath", "effect", "result", "nodeSubscriptions", "unsubscribe", "getPath", "start", "found", "waitForPath", "params", "interval", "i", "setInterval", "wake", "finally", "clearInterval", "_addNodes", "batch", "_node", "subNode", "_removeNodes", "ids", "_removeNode", "_removeEdge", "startsWith", "_addEdges", "edge", "sourceEdges", "push", "targetEdges", "_removeEdges", "removeOrphans", "outboundIndex", "findIndex", "splice", "inboundIndex", "current", "unsorted", "sorted", "NODE_RESOLVER_TIMEOUT", "createExtension", "extension", "position", "resolver", "connector", "actionGroups", "rest", "getId", "arg", "Dispatcher", "stateIndex", "state", "cleanup", "BuilderInternal", "memoize", "fn", "dispatcher", "currentDispatcher", "currentExtension", "all", "toSignal", "subscribe", "get", "thisSignal", "signal", "value", "flattenExtensions", "acc", "Array", "isArray", "flatMap", "ext", "GraphBuilder", "_dispatcher", "_extensions", "_resolverSubscriptions", "Map", "_connectorSubscriptions", "_nodeChanged", "_graph", "initialize", "Promise", "error", "extensions", "addExtension", "removeExtension", "destroy", "clear", "explore", "isNode", "yieldOrContinue", "set", "byPosition", "err", "catch", "nodesRelation", "nodesType", "first", "previous", "removed", "delete"]
7
7
  }
@@ -1 +1 @@
1
- {"inputs":{"packages/sdk/app-graph/src/node.ts":{"bytes":5859,"imports":[],"format":"esm"},"packages/sdk/app-graph/src/graph.ts":{"bytes":63179,"imports":[{"path":"@preact/signals-core","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/live-object","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"packages/sdk/app-graph/src/node.ts","kind":"import-statement","original":"./node"}],"format":"esm"},"packages/sdk/app-graph/src/graph-builder.ts":{"bytes":52318,"imports":[{"path":"@preact/signals-core","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/live-object","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"packages/sdk/app-graph/src/graph.ts","kind":"import-statement","original":"./graph"},{"path":"packages/sdk/app-graph/src/node.ts","kind":"import-statement","original":"./node"},{"path":"main-thread-scheduling","kind":"dynamic-import","external":true}],"format":"esm"},"packages/sdk/app-graph/src/index.ts":{"bytes":672,"imports":[{"path":"packages/sdk/app-graph/src/graph.ts","kind":"import-statement","original":"./graph"},{"path":"packages/sdk/app-graph/src/graph-builder.ts","kind":"import-statement","original":"./graph-builder"},{"path":"packages/sdk/app-graph/src/node.ts","kind":"import-statement","original":"./node"}],"format":"esm"}},"outputs":{"packages/sdk/app-graph/dist/lib/node/index.cjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":61201},"packages/sdk/app-graph/dist/lib/node/index.cjs":{"imports":[{"path":"@preact/signals-core","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/live-object","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"@preact/signals-core","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/live-object","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"main-thread-scheduling","kind":"dynamic-import","external":true}],"exports":["ACTION_GROUP_TYPE","ACTION_TYPE","Graph","GraphBuilder","ROOT_ID","ROOT_TYPE","actionGroupSymbol","cleanup","createExtension","flattenExtensions","getGraph","isAction","isActionGroup","isActionLike","isGraphNode","memoize","toSignal"],"entryPoint":"packages/sdk/app-graph/src/index.ts","inputs":{"packages/sdk/app-graph/src/graph.ts":{"bytesInOutput":15387},"packages/sdk/app-graph/src/node.ts":{"bytesInOutput":477},"packages/sdk/app-graph/src/index.ts":{"bytesInOutput":0},"packages/sdk/app-graph/src/graph-builder.ts":{"bytesInOutput":11341}},"bytes":27669}}}
1
+ {"inputs":{"packages/sdk/app-graph/src/node.ts":{"bytes":5863,"imports":[],"format":"esm"},"packages/sdk/app-graph/src/graph.ts":{"bytes":63179,"imports":[{"path":"@preact/signals-core","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/live-object","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"packages/sdk/app-graph/src/node.ts","kind":"import-statement","original":"./node"}],"format":"esm"},"packages/sdk/app-graph/src/graph-builder.ts":{"bytes":52318,"imports":[{"path":"@preact/signals-core","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/live-object","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"packages/sdk/app-graph/src/graph.ts","kind":"import-statement","original":"./graph"},{"path":"packages/sdk/app-graph/src/node.ts","kind":"import-statement","original":"./node"},{"path":"main-thread-scheduling","kind":"dynamic-import","external":true}],"format":"esm"},"packages/sdk/app-graph/src/index.ts":{"bytes":672,"imports":[{"path":"packages/sdk/app-graph/src/graph.ts","kind":"import-statement","original":"./graph"},{"path":"packages/sdk/app-graph/src/graph-builder.ts","kind":"import-statement","original":"./graph-builder"},{"path":"packages/sdk/app-graph/src/node.ts","kind":"import-statement","original":"./node"}],"format":"esm"}},"outputs":{"packages/sdk/app-graph/dist/lib/node/index.cjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":61205},"packages/sdk/app-graph/dist/lib/node/index.cjs":{"imports":[{"path":"@preact/signals-core","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/live-object","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"@preact/signals-core","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/live-object","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"main-thread-scheduling","kind":"dynamic-import","external":true}],"exports":["ACTION_GROUP_TYPE","ACTION_TYPE","Graph","GraphBuilder","ROOT_ID","ROOT_TYPE","actionGroupSymbol","cleanup","createExtension","flattenExtensions","getGraph","isAction","isActionGroup","isActionLike","isGraphNode","memoize","toSignal"],"entryPoint":"packages/sdk/app-graph/src/index.ts","inputs":{"packages/sdk/app-graph/src/graph.ts":{"bytesInOutput":15387},"packages/sdk/app-graph/src/node.ts":{"bytesInOutput":477},"packages/sdk/app-graph/src/index.ts":{"bytesInOutput":0},"packages/sdk/app-graph/src/graph-builder.ts":{"bytesInOutput":11341}},"bytes":27669}}}
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/graph.ts", "../../../src/node.ts", "../../../src/graph-builder.ts"],
4
- "sourcesContent": ["//\n// Copyright 2023 DXOS.org\n//\n\nimport { batch, effect, untracked } from '@preact/signals-core';\n\nimport { asyncTimeout, Trigger } from '@dxos/async';\nimport { invariant } from '@dxos/invariant';\nimport { type Live, live } from '@dxos/live-object';\nimport { log } from '@dxos/log';\nimport { type MakeOptional, isNonNullable, pick } from '@dxos/util';\n\nimport { type Node, type NodeArg, type NodeFilter, type Relation, actionGroupSymbol, isActionLike } from './node';\n\nconst graphSymbol = Symbol('graph');\ntype DeepWriteable<T> = { -readonly [K in keyof T]: T[K] extends object ? DeepWriteable<T[K]> : T[K] };\ntype NodeInternal = DeepWriteable<Node> & { [graphSymbol]: Graph };\n\nexport const getGraph = (node: Node): Graph => {\n const graph = (node as NodeInternal)[graphSymbol];\n invariant(graph, 'Node is not associated with a graph.');\n return graph;\n};\n\nexport const ROOT_ID = 'root';\nexport const ROOT_TYPE = 'dxos.org/type/GraphRoot';\nexport const ACTION_TYPE = 'dxos.org/type/GraphAction';\nexport const ACTION_GROUP_TYPE = 'dxos.org/type/GraphActionGroup';\n\nexport type NodesOptions<TData = any, TProperties extends Record<string, any> = Record<string, any>> = {\n relation?: Relation;\n filter?: NodeFilter<TData, TProperties>;\n expansion?: boolean;\n type?: string;\n};\n\n// TODO(wittjosiah): Consider having default be undefined. This is current default for backwards compatibility.\nconst DEFAULT_FILTER = (node: Node) => untracked(() => !isActionLike(node));\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, path: string[]) => boolean | void;\n\n /**\n * The node to start traversing from.\n *\n * @default root\n */\n node?: Node;\n\n /**\n * The relation to traverse graph edges.\n *\n * @default 'outbound'\n */\n relation?: Relation;\n\n /**\n * Allow traversal to trigger expansion of the graph via `onInitialNodes`.\n */\n expansion?: boolean;\n};\n\nexport type GraphParams = {\n nodes?: MakeOptional<Node, 'data' | 'cacheable'>[];\n edges?: Record<string, string[]>;\n onInitialNode?: Graph['_onInitialNode'];\n onInitialNodes?: Graph['_onInitialNodes'];\n onRemoveNode?: Graph['_onRemoveNode'];\n};\n\n/**\n * The Graph represents the structure of the application constructed via plugins.\n */\nexport class Graph {\n private readonly _onInitialNode?: (id: string) => Promise<void>;\n private readonly _onInitialNodes?: (node: Node, relation: Relation, type?: string) => Promise<void>;\n private readonly _onRemoveNode?: (id: string) => Promise<void>;\n\n private readonly _waitingForNodes: Record<string, Trigger<Node>> = {};\n private readonly _initialized: Record<string, boolean> = {};\n\n /**\n * @internal\n */\n readonly _nodes: Record<string, Live<NodeInternal>> = {};\n\n /**\n * @internal\n */\n readonly _edges: Record<string, Live<{ inbound: string[]; outbound: string[] }>> = {};\n\n constructor({ nodes, edges, onInitialNode, onInitialNodes, onRemoveNode }: GraphParams = {}) {\n this._onInitialNode = onInitialNode;\n this._onInitialNodes = onInitialNodes;\n this._onRemoveNode = onRemoveNode;\n\n this._nodes[ROOT_ID] = this._constructNode({\n id: ROOT_ID,\n type: ROOT_TYPE,\n cacheable: [],\n properties: {},\n data: null,\n });\n if (nodes) {\n nodes.forEach((node) => {\n const cacheable = Object.keys(node.properties ?? {});\n if (node.type === ACTION_TYPE) {\n this._addNode({ cacheable, data: () => log.warn('Pickled action invocation'), ...node });\n } else if (node.type === ACTION_GROUP_TYPE) {\n this._addNode({ cacheable, data: actionGroupSymbol, ...node });\n } else {\n this._addNode({ cacheable, ...node });\n }\n });\n }\n\n this._edges[ROOT_ID] = live({ inbound: [], outbound: [] });\n if (edges) {\n Object.entries(edges).forEach(([source, edges]) => {\n edges.forEach((target) => {\n this._addEdge({ source, target });\n });\n this._sortEdges(source, 'outbound', edges);\n });\n }\n }\n\n static from(pickle: string, options: Omit<GraphParams, 'nodes' | 'edges'> = {}) {\n const { nodes, edges } = JSON.parse(pickle);\n return new Graph({ nodes, edges, ...options });\n }\n\n /**\n * Alias for `findNode('root')`.\n */\n get root() {\n return this.findNode(ROOT_ID)!;\n }\n\n /**\n * Convert the graph to a JSON object.\n */\n toJSON({ id = ROOT_ID, maxLength = 32 }: { id?: string; maxLength?: number } = {}) {\n const toJSON = (node: Node, seen: string[] = []): any => {\n const nodes = this.nodes(node);\n const obj: Record<string, any> = {\n id: node.id.length > maxLength ? `${node.id.slice(0, maxLength - 3)}...` : 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) => {\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 = this.findNode(id);\n invariant(root, `Node not found: ${id}`);\n return toJSON(root);\n }\n\n pickle() {\n const nodes = Object.values(this._nodes)\n .filter((node) => !!node.cacheable)\n .map((node) => {\n return {\n id: node.id,\n type: node.type,\n properties: pick(node.properties, node.cacheable!),\n };\n });\n\n const cacheable = new Set(nodes.map((node) => node.id));\n\n const edges = Object.fromEntries(\n Object.entries(this._edges)\n .filter(([id]) => cacheable.has(id))\n .map(([id, { outbound }]): [string, string[]] => [id, outbound.filter((nodeId) => cacheable.has(nodeId))])\n // TODO(wittjosiah): Why sort?\n .toSorted(([a], [b]) => a.localeCompare(b)),\n );\n\n return JSON.stringify({ nodes, edges });\n }\n\n /**\n * Find the node with the given id in the graph.\n *\n * If a node is not found within the graph and an `onInitialNode` callback is provided,\n * it is called with the id and type of the node, potentially initializing the node.\n */\n findNode(id: string, expansion = true): Node | undefined {\n const existingNode = this._nodes[id];\n if (!existingNode && expansion) {\n void this._onInitialNode?.(id);\n }\n\n return existingNode;\n }\n\n /**\n * Wait for a node to be added to the graph.\n *\n * If the node is already present in the graph, the promise resolves immediately.\n *\n * @param id The id of the node to wait for.\n * @param timeout The time in milliseconds to wait for the node to be added.\n */\n async waitForNode(id: string, timeout?: number): Promise<Node> {\n const trigger = this._waitingForNodes[id] ?? (this._waitingForNodes[id] = new Trigger<Node>());\n const node = this.findNode(id);\n if (node) {\n delete this._waitingForNodes[id];\n return node;\n }\n\n if (timeout === undefined) {\n return trigger.wait();\n } else {\n return asyncTimeout(trigger.wait(), timeout, `Node not found: ${id}`);\n }\n }\n\n /**\n * Nodes that this node is connected to in default order.\n */\n nodes<TData = any, TProperties extends Record<string, any> = Record<string, any>>(\n node: Node,\n options: NodesOptions<TData, TProperties> = {},\n ) {\n const { relation, expansion, filter = DEFAULT_FILTER, type } = options;\n const nodes = this._getNodes({ node, relation, expansion, type });\n return nodes.filter((n) => filter(n, node));\n }\n\n /**\n * Edges that this node is connected to in default order.\n */\n edges(node: Node, { relation = 'outbound' }: { relation?: Relation } = {}) {\n return this._edges[node.id]?.[relation] ?? [];\n }\n\n /**\n * Actions or action groups that this node is connected to in default order.\n */\n actions(node: Node, { expansion }: { expansion?: boolean } = {}) {\n return [\n ...this._getNodes({ node, expansion, type: ACTION_GROUP_TYPE }),\n ...this._getNodes({ node, expansion, type: ACTION_TYPE }),\n ];\n }\n\n async expand(node: Node, relation: Relation = 'outbound', type?: string) {\n const key = this._key(node, relation, type);\n const initialized = this._initialized[key];\n if (!initialized && this._onInitialNodes) {\n await this._onInitialNodes(node, relation, type);\n this._initialized[key] = true;\n }\n }\n\n private _key(node: Node, relation: Relation, type?: string) {\n return `${node.id}-${relation}-${type}`;\n }\n\n /**\n * Recursive depth-first traversal of the graph.\n *\n * @param options.node The node to start traversing from.\n * @param options.relation The relation to traverse graph edges.\n * @param options.visitor A callback which is called for each node visited during traversal.\n */\n traverse(\n { visitor, node = this.root, relation = 'outbound', expansion }: GraphTraversalOptions,\n path: string[] = [],\n ): void {\n // Break cycles.\n if (path.includes(node.id)) {\n return;\n }\n\n const shouldContinue = visitor(node, [...path, node.id]);\n if (shouldContinue === false) {\n return;\n }\n\n Object.values(this._getNodes({ node, relation, expansion })).forEach((child) =>\n this.traverse({ node: child, relation, visitor, expansion }, [...path, node.id]),\n );\n }\n\n /**\n * Recursive depth-first traversal of the graph wrapping each visitor call in an effect.\n *\n * @param options.node The node to start traversing from.\n * @param options.relation The relation to traverse graph edges.\n * @param options.visitor A callback which is called for each node visited during traversal.\n */\n subscribeTraverse(\n { visitor, node = this.root, relation = 'outbound', expansion }: GraphTraversalOptions,\n currentPath: string[] = [],\n ) {\n return effect(() => {\n const path = [...currentPath, node.id];\n const result = visitor(node, path);\n if (result === false) {\n return;\n }\n\n const nodes = this._getNodes({ node, relation, expansion });\n const nodeSubscriptions = nodes.map((n) => this.subscribeTraverse({ node: n, visitor, expansion }, path));\n return () => {\n nodeSubscriptions.forEach((unsubscribe) => unsubscribe());\n };\n });\n }\n\n /**\n * Get the path between two nodes in the graph.\n */\n getPath({ source = 'root', target }: { source?: string; target: string }): string[] | undefined {\n const start = this.findNode(source);\n if (!start) {\n return undefined;\n }\n\n let found: string[] | undefined;\n this.traverse({\n node: start,\n visitor: (node, path) => {\n if (found) {\n return false;\n }\n\n if (node.id === target) {\n found = path;\n }\n },\n });\n\n return found;\n }\n\n /**\n * Wait for the path between two nodes in the graph to be established.\n */\n async waitForPath(\n params: { source?: string; target: string },\n { timeout = 5_000, interval = 500 }: { timeout?: number; interval?: number } = {},\n ) {\n const path = this.getPath(params);\n if (path) {\n return path;\n }\n\n const trigger = new Trigger<string[]>();\n const i = setInterval(() => {\n const path = this.getPath(params);\n if (path) {\n trigger.wake(path);\n }\n }, interval);\n\n return trigger.wait({ timeout }).finally(() => clearInterval(i));\n }\n\n /**\n * Add nodes to the graph.\n *\n * @internal\n */\n _addNodes<TData = null, TProperties extends Record<string, any> = Record<string, any>>(\n nodes: NodeArg<TData, TProperties>[],\n ): Node<TData, TProperties>[] {\n return batch(() => nodes.map((node) => this._addNode(node)));\n }\n\n private _addNode<TData, TProperties extends Record<string, any> = Record<string, any>>({\n nodes,\n edges,\n ..._node\n }: NodeArg<TData, TProperties>): Node<TData, TProperties> {\n return untracked(() => {\n const existingNode = this._nodes[_node.id];\n const node = existingNode ?? this._constructNode({ data: null, properties: {}, ..._node });\n if (existingNode) {\n const { data = null, properties, type } = _node;\n if (data !== node.data) {\n node.data = data;\n }\n\n if (type !== node.type) {\n node.type = type;\n }\n\n for (const key in properties) {\n if (properties[key] !== node.properties[key]) {\n node.properties[key] = properties[key];\n }\n }\n } else {\n this._nodes[node.id] = node;\n this._edges[node.id] = live({ inbound: [], outbound: [] });\n }\n\n const trigger = this._waitingForNodes[node.id];\n if (trigger) {\n trigger.wake(node);\n delete this._waitingForNodes[node.id];\n }\n\n if (nodes) {\n nodes.forEach((subNode) => {\n this._addNode(subNode);\n this._addEdge({ source: node.id, target: subNode.id });\n });\n }\n\n if (edges) {\n edges.forEach(([id, relation]) =>\n relation === 'outbound'\n ? this._addEdge({ source: node.id, target: id })\n : this._addEdge({ source: id, target: node.id }),\n );\n }\n\n return node as unknown as Node<TData, TProperties>;\n });\n }\n\n /**\n * Remove nodes from the graph.\n *\n * @param ids The id of the node to remove.\n * @param edges Whether to remove edges connected to the node from the graph as well.\n * @internal\n */\n _removeNodes(ids: string[], edges = false) {\n batch(() => ids.forEach((id) => this._removeNode(id, edges)));\n }\n\n private _removeNode(id: string, edges = false) {\n untracked(() => {\n const node = this.findNode(id, false);\n if (!node) {\n return;\n }\n\n if (edges) {\n // Remove edges from connected nodes.\n this._getNodes({ node }).forEach((node) => {\n this._removeEdge({ source: id, target: node.id });\n });\n this._getNodes({ node, relation: 'inbound' }).forEach((node) => {\n this._removeEdge({ source: node.id, target: id });\n });\n\n // Remove edges from node.\n delete this._edges[id];\n }\n\n // Remove node.\n delete this._nodes[id];\n Object.keys(this._initialized)\n .filter((key) => key.startsWith(id))\n .forEach((key) => {\n delete this._initialized[key];\n });\n void this._onRemoveNode?.(id);\n });\n }\n\n /**\n * Add edges to the graph.\n *\n * @internal\n */\n _addEdges(edges: { source: string; target: string }[]) {\n batch(() => edges.forEach((edge) => this._addEdge(edge)));\n }\n\n private _addEdge({ source, target }: { source: string; target: string }) {\n untracked(() => {\n if (!this._edges[source]) {\n this._edges[source] = live({ inbound: [], outbound: [] });\n }\n if (!this._edges[target]) {\n this._edges[target] = live({ inbound: [], outbound: [] });\n }\n\n const sourceEdges = this._edges[source];\n if (!sourceEdges.outbound.includes(target)) {\n sourceEdges.outbound.push(target);\n }\n\n const targetEdges = this._edges[target];\n if (!targetEdges.inbound.includes(source)) {\n targetEdges.inbound.push(source);\n }\n });\n }\n\n /**\n * Remove edges from the graph.\n * @internal\n */\n _removeEdges(edges: { source: string; target: string }[], removeOrphans = false) {\n batch(() => edges.forEach((edge) => this._removeEdge(edge, removeOrphans)));\n }\n\n private _removeEdge({ source, target }: { source: string; target: string }, removeOrphans = false) {\n untracked(() => {\n batch(() => {\n const outboundIndex = this._edges[source]?.outbound.findIndex((id) => id === target);\n if (outboundIndex !== undefined && outboundIndex !== -1) {\n this._edges[source].outbound.splice(outboundIndex, 1);\n }\n\n const inboundIndex = this._edges[target]?.inbound.findIndex((id) => id === source);\n if (inboundIndex !== undefined && inboundIndex !== -1) {\n this._edges[target].inbound.splice(inboundIndex, 1);\n }\n\n if (removeOrphans) {\n if (\n this._edges[source]?.outbound.length === 0 &&\n this._edges[source]?.inbound.length === 0 &&\n source !== ROOT_ID\n ) {\n this._removeNode(source, true);\n }\n if (\n this._edges[target]?.outbound.length === 0 &&\n this._edges[target]?.inbound.length === 0 &&\n target !== ROOT_ID\n ) {\n this._removeNode(target, true);\n }\n }\n });\n });\n }\n\n /**\n * Sort edges for a node.\n *\n * Edges not included in the sorted list are appended to the end of the list.\n *\n * @param nodeId The id of the node to sort edges for.\n * @param relation The relation of the edges from the node to sort.\n * @param edges The ordered list of edges.\n * @ignore\n */\n _sortEdges(nodeId: string, relation: Relation, edges: string[]) {\n untracked(() => {\n batch(() => {\n const current = this._edges[nodeId];\n if (current) {\n const unsorted = current[relation].filter((id) => !edges.includes(id)) ?? [];\n const sorted = edges.filter((id) => current[relation].includes(id)) ?? [];\n current[relation].splice(0, current[relation].length, ...[...sorted, ...unsorted]);\n }\n });\n });\n }\n\n private _constructNode = (node: Omit<Node, typeof graphSymbol>) => {\n return live<NodeInternal>({ ...node, [graphSymbol]: this });\n };\n\n private _getNodes({\n node,\n relation = 'outbound',\n type,\n expansion,\n }: {\n node: Node;\n relation?: Relation;\n type?: string;\n expansion?: boolean;\n }): Node[] {\n if (expansion) {\n void this.expand(node, relation, type);\n }\n\n const edges = this._edges[node.id];\n if (!edges) {\n return [];\n } else {\n return edges[relation]\n .map((id) => this._nodes[id])\n .filter(isNonNullable)\n .filter((n) => !type || n.type === type);\n }\n }\n}\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { type MaybePromise, type MakeOptional } from '@dxos/util';\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 Relation = 'outbound' | 'inbound';\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, Relation][];\n};\n\n//\n// Actions\n//\n\nexport type InvokeParams = {\n /** Node the invoked action is connected to. */\n node: Node;\n\n caller?: string;\n};\n\nexport type ActionData = (params: InvokeParams) => MaybePromise<void>;\n\nexport type Action<TProperties extends Record<string, any> = Record<string, any>> = Readonly<\n Omit<Node<ActionData, TProperties>, 'properties'> & {\n properties: Readonly<TProperties>;\n }\n>;\n\nexport const isAction = (data: unknown): data is Action =>\n isGraphNode(data) ? typeof data.data === 'function' : 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 : false;\n\nexport type ActionLike = Action | ActionGroup;\n\nexport const isActionLike = (data: unknown): data is Action | ActionGroup => isAction(data) || isActionGroup(data);\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { effect, type Signal, signal, untracked } from '@preact/signals-core';\n\nimport { Trigger, type CleanupFn } from '@dxos/async';\nimport { invariant } from '@dxos/invariant';\nimport { live } from '@dxos/live-object';\nimport { log } from '@dxos/log';\nimport { byPosition, type Position, isNode, type MaybePromise, isNonNullable } from '@dxos/util';\n\nimport { ACTION_GROUP_TYPE, ACTION_TYPE, Graph, ROOT_ID, type GraphParams } from './graph';\nimport { type ActionData, actionGroupSymbol, type Node, type NodeArg, type Relation } from './node';\n\nconst NODE_RESOLVER_TIMEOUT = 1_000;\n\n/**\n * Graph builder extension for adding nodes to the graph based on just the node id.\n * This is useful for creating the first node in a graph or for hydrating cached nodes with data.\n *\n * @param params.id The id of the node to resolve.\n */\nexport type ResolverExtension = (params: { id: string }) => NodeArg<any> | false | undefined;\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<T = any> = (params: { node: Node<T> }) => NodeArg<any>[] | undefined;\n\n/**\n * Constrained case of the connector extension for more easily adding actions to the graph.\n */\nexport type ActionsExtension<T = any> = (params: {\n node: Node<T>;\n}) => Omit<NodeArg<ActionData>, 'type' | 'nodes' | 'edges'>[] | undefined;\n\n/**\n * Constrained case of the connector extension for more easily adding action groups to the graph.\n */\nexport type ActionGroupsExtension<T = any> = (params: {\n node: Node<T>;\n}) => Omit<NodeArg<typeof actionGroupSymbol>, 'type' | 'data' | 'nodes' | 'edges'>[] | undefined;\n\ntype GuardedNodeType<T> = T extends (value: any) => value is infer N ? (N extends Node<infer D> ? D : unknown) : never;\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.type If provided, all nodes returned are expected to have this type.\n * @param params.disposition Affects the order the extensions are processed in.\n * @param params.filter A filter function to determine if an extension should act on a node.\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 CreateExtensionOptions<T = any> = {\n id: string;\n relation?: Relation;\n type?: string;\n position?: Position;\n filter?: (node: Node) => node is Node<T>;\n resolver?: ResolverExtension;\n connector?: ConnectorExtension<GuardedNodeType<CreateExtensionOptions<T>['filter']>>;\n actions?: ActionsExtension<GuardedNodeType<CreateExtensionOptions<T>['filter']>>;\n actionGroups?: ActionGroupsExtension<GuardedNodeType<CreateExtensionOptions<T>['filter']>>;\n};\n\n/**\n * Create a graph builder extension.\n */\nexport const createExtension = <T = any>(extension: CreateExtensionOptions<T>): BuilderExtension[] => {\n const { id, position = 'static', resolver, connector, actions, actionGroups, ...rest } = extension;\n const getId = (key: string) => `${id}/${key}`;\n return [\n resolver ? { id: getId('resolver'), position, resolver } : undefined,\n connector ? { ...rest, id: getId('connector'), position, connector } : undefined,\n actionGroups\n ? ({\n ...rest,\n id: getId('actionGroups'),\n position,\n type: ACTION_GROUP_TYPE,\n relation: 'outbound',\n connector: ({ node }) =>\n actionGroups({ node })?.map((arg) => ({ ...arg, data: actionGroupSymbol, type: ACTION_GROUP_TYPE })),\n } satisfies BuilderExtension)\n : undefined,\n actions\n ? ({\n ...rest,\n id: getId('actions'),\n position,\n type: ACTION_TYPE,\n relation: 'outbound',\n connector: ({ node }) => actions({ node })?.map((arg) => ({ ...arg, type: ACTION_TYPE })),\n } satisfies BuilderExtension)\n : undefined,\n ].filter(isNonNullable);\n};\n\nexport type GraphBuilderTraverseOptions = {\n visitor: (node: Node, path: string[]) => MaybePromise<boolean | void>;\n node?: Node;\n relation?: Relation;\n};\n\n/**\n * The dispatcher is used to keep track of the current extension and state when memoizing functions.\n */\nclass Dispatcher {\n currentExtension?: string;\n stateIndex = 0;\n state: Record<string, any[]> = {};\n cleanup: (() => void)[] = [];\n}\n\nclass BuilderInternal {\n // This must be static to avoid passing the dispatcher instance to every memoized function.\n // If the dispatcher is not set that means that the memoized function is being called outside of the graph builder.\n static currentDispatcher?: Dispatcher;\n}\n\n/**\n * Allows code to be memoized within the context of a graph builder extension.\n * This is useful for creating instances which should be subscribed to rather than recreated.\n */\nexport const memoize = <T>(fn: () => T, key = 'result'): T => {\n const dispatcher = BuilderInternal.currentDispatcher;\n invariant(dispatcher?.currentExtension, 'memoize must be called within an extension');\n const all = dispatcher.state[dispatcher.currentExtension][dispatcher.stateIndex] ?? {};\n const current = all[key];\n const result = current ? current.result : fn();\n dispatcher.state[dispatcher.currentExtension][dispatcher.stateIndex] = { ...all, [key]: { result } };\n dispatcher.stateIndex++;\n return result;\n};\n\n/**\n * Register a cleanup function to be called when the graph builder is destroyed.\n */\nexport const cleanup = (fn: () => void): void => {\n memoize(() => {\n const dispatcher = BuilderInternal.currentDispatcher;\n invariant(dispatcher, 'cleanup must be called within an extension');\n dispatcher.cleanup.push(fn);\n });\n};\n\n/**\n * Convert a subscribe/get pair into a signal.\n */\nexport const toSignal = <T>(\n subscribe: (onChange: () => void) => () => void,\n get: () => T | undefined,\n key?: string,\n) => {\n const thisSignal = memoize(() => {\n return signal(get());\n }, key);\n const unsubscribe = memoize(() => {\n return subscribe(() => (thisSignal.value = get()));\n }, key);\n cleanup(() => {\n unsubscribe();\n });\n return thisSignal.value;\n};\n\nexport type BuilderExtension = Readonly<{\n id: string;\n position: Position;\n resolver?: ResolverExtension;\n connector?: ConnectorExtension;\n // Only for connector.\n relation?: Relation;\n type?: string;\n filter?: (node: Node) => boolean;\n}>;\n\ntype ExtensionArg = BuilderExtension | BuilderExtension[] | ExtensionArg[];\n\nexport const flattenExtensions = (extension: ExtensionArg, 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\n/**\n * The builder provides an extensible way to compose the construction of the graph.\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.\nexport class GraphBuilder {\n private readonly _dispatcher = new Dispatcher();\n private readonly _extensions = live<Record<string, BuilderExtension>>({});\n private readonly _resolverSubscriptions = new Map<string, CleanupFn>();\n private readonly _connectorSubscriptions = new Map<string, CleanupFn>();\n private readonly _nodeChanged: Record<string, Signal<{}>> = {};\n private readonly _initialized: Record<string, Trigger> = {};\n private _graph: Graph;\n\n constructor(params: Pick<GraphParams, 'nodes' | 'edges'> = {}) {\n this._graph = new Graph({\n ...params,\n onInitialNode: async (id) => this._onInitialNode(id),\n onInitialNodes: async (node, relation, type) => this._onInitialNodes(node, relation, type),\n onRemoveNode: (id) => this._onRemoveNode(id),\n });\n }\n\n static from(pickle?: string) {\n if (!pickle) {\n return new GraphBuilder();\n }\n\n const { nodes, edges } = JSON.parse(pickle);\n return new GraphBuilder({ nodes, edges });\n }\n\n /**\n * If graph is being restored from a pickle, the data will be null.\n * Initialize the data of each node by calling resolvers.\n * Wait until all of the initial nodes have resolved.\n */\n async initialize() {\n Object.keys(this._graph._nodes)\n .filter((id) => id !== ROOT_ID)\n .forEach((id) => (this._initialized[id] = new Trigger()));\n Object.keys(this._graph._nodes).forEach((id) => this._onInitialNode(id));\n await Promise.all(\n Object.entries(this._initialized).map(async ([id, trigger]) => {\n try {\n await trigger.wait({ timeout: NODE_RESOLVER_TIMEOUT });\n } catch {\n log.error('node resolver timeout', { id });\n this.graph._removeNodes([id]);\n }\n }),\n );\n }\n\n get graph() {\n return this._graph;\n }\n\n /**\n * @reactive\n */\n get extensions() {\n return Object.values(this._extensions);\n }\n\n /**\n * Register a node builder which will be called in order to construct the graph.\n */\n addExtension(extension: ExtensionArg): GraphBuilder {\n const extensions = flattenExtensions(extension);\n untracked(() => {\n extensions.forEach((extension) => {\n this._dispatcher.state[extension.id] = [];\n this._extensions[extension.id] = extension;\n });\n });\n return this;\n }\n\n /**\n * Remove a node builder from the graph builder.\n */\n removeExtension(id: string): GraphBuilder {\n untracked(() => {\n delete this._extensions[id];\n });\n return this;\n }\n\n destroy() {\n this._dispatcher.cleanup.forEach((fn) => fn());\n this._resolverSubscriptions.forEach((unsubscribe) => unsubscribe());\n this._connectorSubscriptions.forEach((unsubscribe) => unsubscribe());\n this._resolverSubscriptions.clear();\n this._connectorSubscriptions.clear();\n }\n\n /**\n * A graph traversal using just the connector extensions, without subscribing to any signals or persisting any nodes.\n */\n async explore(\n { node = this._graph.root, relation = 'outbound', visitor }: GraphBuilderTraverseOptions,\n path: string[] = [],\n ) {\n // Break cycles.\n if (path.includes(node.id)) {\n return;\n }\n\n // TODO(wittjosiah): This is a workaround for esm not working in the test runner.\n // Switching to vitest is blocked by having node esm versions of echo-schema & echo-signals.\n if (!isNode()) {\n const { yieldOrContinue } = await import('main-thread-scheduling');\n await yieldOrContinue('idle');\n }\n const shouldContinue = await visitor(node, [...path, node.id]);\n if (shouldContinue === false) {\n return;\n }\n\n const nodes = Object.values(this._extensions)\n .filter((extension) => relation === (extension.relation ?? 'outbound'))\n .filter((extension) => !extension.filter || extension.filter(node))\n .flatMap((extension) => {\n this._dispatcher.currentExtension = extension.id;\n this._dispatcher.stateIndex = 0;\n BuilderInternal.currentDispatcher = this._dispatcher;\n const result = extension.connector?.({ node }) ?? [];\n BuilderInternal.currentDispatcher = undefined;\n return result;\n })\n .map(\n (arg): Node => ({\n id: arg.id,\n type: arg.type,\n cacheable: arg.cacheable,\n data: arg.data ?? null,\n properties: arg.properties ?? {},\n }),\n );\n\n await Promise.all(nodes.map((n) => this.explore({ node: n, relation, visitor }, [...path, node.id])));\n }\n\n private _onInitialNode(nodeId: string) {\n this._nodeChanged[nodeId] = this._nodeChanged[nodeId] ?? signal({});\n this._resolverSubscriptions.set(\n nodeId,\n effect(() => {\n const extensions = Object.values(this._extensions).toSorted(byPosition);\n for (const { id, resolver } of extensions) {\n if (!resolver) {\n continue;\n }\n\n this._dispatcher.currentExtension = id;\n this._dispatcher.stateIndex = 0;\n BuilderInternal.currentDispatcher = this._dispatcher;\n let node: NodeArg<any> | false | undefined;\n try {\n node = resolver({ id: nodeId });\n } catch (err) {\n log.catch(err, { extension: id });\n log.error(`Previous error occurred in extension: ${id}`);\n } finally {\n BuilderInternal.currentDispatcher = undefined;\n }\n\n const trigger = this._initialized[nodeId];\n if (node) {\n this.graph._addNodes([node]);\n trigger?.wake();\n if (this._nodeChanged[node.id]) {\n this._nodeChanged[node.id].value = {};\n }\n break;\n } else if (node === false) {\n this.graph._removeNodes([nodeId]);\n trigger?.wake();\n break;\n }\n }\n }),\n );\n }\n\n private _onInitialNodes(node: Node, nodesRelation: Relation, nodesType?: string) {\n this._nodeChanged[node.id] = this._nodeChanged[node.id] ?? signal({});\n let first = true;\n let previous: string[] = [];\n this._connectorSubscriptions.set(\n node.id,\n effect(() => {\n // TODO(wittjosiah): This is a workaround for a race between the node removal and the effect re-running.\n // To cause this case to happen, remove a collection and then undo the removal.\n if (!first && !this._connectorSubscriptions.has(node.id)) {\n return;\n }\n first = false;\n\n // Subscribe to extensions being added.\n Object.keys(this._extensions);\n // Subscribe to connected node changes.\n this._nodeChanged[node.id].value;\n\n // TODO(wittjosiah): Consider allowing extensions to collaborate on the same node by merging their results.\n const nodes: NodeArg<any>[] = [];\n const extensions = Object.values(this._extensions).toSorted(byPosition);\n for (const { id, connector, filter, type, relation = 'outbound' } of extensions) {\n if (\n !connector ||\n relation !== nodesRelation ||\n (nodesType && type !== nodesType) ||\n (filter && !filter(node))\n ) {\n continue;\n }\n\n this._dispatcher.currentExtension = id;\n this._dispatcher.stateIndex = 0;\n BuilderInternal.currentDispatcher = this._dispatcher;\n try {\n nodes.push(...(connector({ node }) ?? []));\n } catch (err) {\n log.catch(err, { extension: id });\n log.error(`Previous error occurred in extension: ${id}`);\n } finally {\n BuilderInternal.currentDispatcher = undefined;\n }\n }\n\n const ids = nodes.map((n) => n.id);\n const removed = previous.filter((id) => !ids.includes(id));\n previous = ids;\n\n // Remove edges and only remove nodes that are orphaned.\n this.graph._removeEdges(\n removed.map((target) => ({ source: node.id, target })),\n true,\n );\n this.graph._addNodes(nodes);\n this.graph._addEdges(\n nodes.map(({ id }) =>\n nodesRelation === 'outbound' ? { source: node.id, target: id } : { source: id, target: node.id },\n ),\n );\n this.graph._sortEdges(\n node.id,\n nodesRelation,\n nodes.map(({ id }) => id),\n );\n nodes.forEach((n) => {\n if (this._nodeChanged[n.id]) {\n this._nodeChanged[n.id].value = {};\n }\n });\n }),\n );\n }\n\n private async _onRemoveNode(nodeId: string) {\n this._resolverSubscriptions.get(nodeId)?.();\n this._connectorSubscriptions.get(nodeId)?.();\n this._resolverSubscriptions.delete(nodeId);\n this._connectorSubscriptions.delete(nodeId);\n }\n}\n"],
4
+ "sourcesContent": ["//\n// Copyright 2023 DXOS.org\n//\n\nimport { batch, effect, untracked } from '@preact/signals-core';\n\nimport { asyncTimeout, Trigger } from '@dxos/async';\nimport { invariant } from '@dxos/invariant';\nimport { type Live, live } from '@dxos/live-object';\nimport { log } from '@dxos/log';\nimport { type MakeOptional, isNonNullable, pick } from '@dxos/util';\n\nimport { type Node, type NodeArg, type NodeFilter, type Relation, actionGroupSymbol, isActionLike } from './node';\n\nconst graphSymbol = Symbol('graph');\ntype DeepWriteable<T> = { -readonly [K in keyof T]: T[K] extends object ? DeepWriteable<T[K]> : T[K] };\ntype NodeInternal = DeepWriteable<Node> & { [graphSymbol]: Graph };\n\nexport const getGraph = (node: Node): Graph => {\n const graph = (node as NodeInternal)[graphSymbol];\n invariant(graph, 'Node is not associated with a graph.');\n return graph;\n};\n\nexport const ROOT_ID = 'root';\nexport const ROOT_TYPE = 'dxos.org/type/GraphRoot';\nexport const ACTION_TYPE = 'dxos.org/type/GraphAction';\nexport const ACTION_GROUP_TYPE = 'dxos.org/type/GraphActionGroup';\n\nexport type NodesOptions<TData = any, TProperties extends Record<string, any> = Record<string, any>> = {\n relation?: Relation;\n filter?: NodeFilter<TData, TProperties>;\n expansion?: boolean;\n type?: string;\n};\n\n// TODO(wittjosiah): Consider having default be undefined. This is current default for backwards compatibility.\nconst DEFAULT_FILTER = (node: Node) => untracked(() => !isActionLike(node));\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, path: string[]) => boolean | void;\n\n /**\n * The node to start traversing from.\n *\n * @default root\n */\n node?: Node;\n\n /**\n * The relation to traverse graph edges.\n *\n * @default 'outbound'\n */\n relation?: Relation;\n\n /**\n * Allow traversal to trigger expansion of the graph via `onInitialNodes`.\n */\n expansion?: boolean;\n};\n\nexport type GraphParams = {\n nodes?: MakeOptional<Node, 'data' | 'cacheable'>[];\n edges?: Record<string, string[]>;\n onInitialNode?: Graph['_onInitialNode'];\n onInitialNodes?: Graph['_onInitialNodes'];\n onRemoveNode?: Graph['_onRemoveNode'];\n};\n\n/**\n * The Graph represents the structure of the application constructed via plugins.\n */\nexport class Graph {\n private readonly _onInitialNode?: (id: string) => Promise<void>;\n private readonly _onInitialNodes?: (node: Node, relation: Relation, type?: string) => Promise<void>;\n private readonly _onRemoveNode?: (id: string) => Promise<void>;\n\n private readonly _waitingForNodes: Record<string, Trigger<Node>> = {};\n private readonly _initialized: Record<string, boolean> = {};\n\n /**\n * @internal\n */\n readonly _nodes: Record<string, Live<NodeInternal>> = {};\n\n /**\n * @internal\n */\n readonly _edges: Record<string, Live<{ inbound: string[]; outbound: string[] }>> = {};\n\n constructor({ nodes, edges, onInitialNode, onInitialNodes, onRemoveNode }: GraphParams = {}) {\n this._onInitialNode = onInitialNode;\n this._onInitialNodes = onInitialNodes;\n this._onRemoveNode = onRemoveNode;\n\n this._nodes[ROOT_ID] = this._constructNode({\n id: ROOT_ID,\n type: ROOT_TYPE,\n cacheable: [],\n properties: {},\n data: null,\n });\n if (nodes) {\n nodes.forEach((node) => {\n const cacheable = Object.keys(node.properties ?? {});\n if (node.type === ACTION_TYPE) {\n this._addNode({ cacheable, data: () => log.warn('Pickled action invocation'), ...node });\n } else if (node.type === ACTION_GROUP_TYPE) {\n this._addNode({ cacheable, data: actionGroupSymbol, ...node });\n } else {\n this._addNode({ cacheable, ...node });\n }\n });\n }\n\n this._edges[ROOT_ID] = live({ inbound: [], outbound: [] });\n if (edges) {\n Object.entries(edges).forEach(([source, edges]) => {\n edges.forEach((target) => {\n this._addEdge({ source, target });\n });\n this._sortEdges(source, 'outbound', edges);\n });\n }\n }\n\n static from(pickle: string, options: Omit<GraphParams, 'nodes' | 'edges'> = {}) {\n const { nodes, edges } = JSON.parse(pickle);\n return new Graph({ nodes, edges, ...options });\n }\n\n /**\n * Alias for `findNode('root')`.\n */\n get root() {\n return this.findNode(ROOT_ID)!;\n }\n\n /**\n * Convert the graph to a JSON object.\n */\n toJSON({ id = ROOT_ID, maxLength = 32 }: { id?: string; maxLength?: number } = {}) {\n const toJSON = (node: Node, seen: string[] = []): any => {\n const nodes = this.nodes(node);\n const obj: Record<string, any> = {\n id: node.id.length > maxLength ? `${node.id.slice(0, maxLength - 3)}...` : 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) => {\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 = this.findNode(id);\n invariant(root, `Node not found: ${id}`);\n return toJSON(root);\n }\n\n pickle() {\n const nodes = Object.values(this._nodes)\n .filter((node) => !!node.cacheable)\n .map((node) => {\n return {\n id: node.id,\n type: node.type,\n properties: pick(node.properties, node.cacheable!),\n };\n });\n\n const cacheable = new Set(nodes.map((node) => node.id));\n\n const edges = Object.fromEntries(\n Object.entries(this._edges)\n .filter(([id]) => cacheable.has(id))\n .map(([id, { outbound }]): [string, string[]] => [id, outbound.filter((nodeId) => cacheable.has(nodeId))])\n // TODO(wittjosiah): Why sort?\n .toSorted(([a], [b]) => a.localeCompare(b)),\n );\n\n return JSON.stringify({ nodes, edges });\n }\n\n /**\n * Find the node with the given id in the graph.\n *\n * If a node is not found within the graph and an `onInitialNode` callback is provided,\n * it is called with the id and type of the node, potentially initializing the node.\n */\n findNode(id: string, expansion = true): Node | undefined {\n const existingNode = this._nodes[id];\n if (!existingNode && expansion) {\n void this._onInitialNode?.(id);\n }\n\n return existingNode;\n }\n\n /**\n * Wait for a node to be added to the graph.\n *\n * If the node is already present in the graph, the promise resolves immediately.\n *\n * @param id The id of the node to wait for.\n * @param timeout The time in milliseconds to wait for the node to be added.\n */\n async waitForNode(id: string, timeout?: number): Promise<Node> {\n const trigger = this._waitingForNodes[id] ?? (this._waitingForNodes[id] = new Trigger<Node>());\n const node = this.findNode(id);\n if (node) {\n delete this._waitingForNodes[id];\n return node;\n }\n\n if (timeout === undefined) {\n return trigger.wait();\n } else {\n return asyncTimeout(trigger.wait(), timeout, `Node not found: ${id}`);\n }\n }\n\n /**\n * Nodes that this node is connected to in default order.\n */\n nodes<TData = any, TProperties extends Record<string, any> = Record<string, any>>(\n node: Node,\n options: NodesOptions<TData, TProperties> = {},\n ) {\n const { relation, expansion, filter = DEFAULT_FILTER, type } = options;\n const nodes = this._getNodes({ node, relation, expansion, type });\n return nodes.filter((n) => filter(n, node));\n }\n\n /**\n * Edges that this node is connected to in default order.\n */\n edges(node: Node, { relation = 'outbound' }: { relation?: Relation } = {}) {\n return this._edges[node.id]?.[relation] ?? [];\n }\n\n /**\n * Actions or action groups that this node is connected to in default order.\n */\n actions(node: Node, { expansion }: { expansion?: boolean } = {}) {\n return [\n ...this._getNodes({ node, expansion, type: ACTION_GROUP_TYPE }),\n ...this._getNodes({ node, expansion, type: ACTION_TYPE }),\n ];\n }\n\n async expand(node: Node, relation: Relation = 'outbound', type?: string) {\n const key = this._key(node, relation, type);\n const initialized = this._initialized[key];\n if (!initialized && this._onInitialNodes) {\n await this._onInitialNodes(node, relation, type);\n this._initialized[key] = true;\n }\n }\n\n private _key(node: Node, relation: Relation, type?: string) {\n return `${node.id}-${relation}-${type}`;\n }\n\n /**\n * Recursive depth-first traversal of the graph.\n *\n * @param options.node The node to start traversing from.\n * @param options.relation The relation to traverse graph edges.\n * @param options.visitor A callback which is called for each node visited during traversal.\n */\n traverse(\n { visitor, node = this.root, relation = 'outbound', expansion }: GraphTraversalOptions,\n path: string[] = [],\n ): void {\n // Break cycles.\n if (path.includes(node.id)) {\n return;\n }\n\n const shouldContinue = visitor(node, [...path, node.id]);\n if (shouldContinue === false) {\n return;\n }\n\n Object.values(this._getNodes({ node, relation, expansion })).forEach((child) =>\n this.traverse({ node: child, relation, visitor, expansion }, [...path, node.id]),\n );\n }\n\n /**\n * Recursive depth-first traversal of the graph wrapping each visitor call in an effect.\n *\n * @param options.node The node to start traversing from.\n * @param options.relation The relation to traverse graph edges.\n * @param options.visitor A callback which is called for each node visited during traversal.\n */\n subscribeTraverse(\n { visitor, node = this.root, relation = 'outbound', expansion }: GraphTraversalOptions,\n currentPath: string[] = [],\n ) {\n return effect(() => {\n const path = [...currentPath, node.id];\n const result = visitor(node, path);\n if (result === false) {\n return;\n }\n\n const nodes = this._getNodes({ node, relation, expansion });\n const nodeSubscriptions = nodes.map((n) => this.subscribeTraverse({ node: n, visitor, expansion }, path));\n return () => {\n nodeSubscriptions.forEach((unsubscribe) => unsubscribe());\n };\n });\n }\n\n /**\n * Get the path between two nodes in the graph.\n */\n getPath({ source = 'root', target }: { source?: string; target: string }): string[] | undefined {\n const start = this.findNode(source);\n if (!start) {\n return undefined;\n }\n\n let found: string[] | undefined;\n this.traverse({\n node: start,\n visitor: (node, path) => {\n if (found) {\n return false;\n }\n\n if (node.id === target) {\n found = path;\n }\n },\n });\n\n return found;\n }\n\n /**\n * Wait for the path between two nodes in the graph to be established.\n */\n async waitForPath(\n params: { source?: string; target: string },\n { timeout = 5_000, interval = 500 }: { timeout?: number; interval?: number } = {},\n ) {\n const path = this.getPath(params);\n if (path) {\n return path;\n }\n\n const trigger = new Trigger<string[]>();\n const i = setInterval(() => {\n const path = this.getPath(params);\n if (path) {\n trigger.wake(path);\n }\n }, interval);\n\n return trigger.wait({ timeout }).finally(() => clearInterval(i));\n }\n\n /**\n * Add nodes to the graph.\n *\n * @internal\n */\n _addNodes<TData = null, TProperties extends Record<string, any> = Record<string, any>>(\n nodes: NodeArg<TData, TProperties>[],\n ): Node<TData, TProperties>[] {\n return batch(() => nodes.map((node) => this._addNode(node)));\n }\n\n private _addNode<TData, TProperties extends Record<string, any> = Record<string, any>>({\n nodes,\n edges,\n ..._node\n }: NodeArg<TData, TProperties>): Node<TData, TProperties> {\n return untracked(() => {\n const existingNode = this._nodes[_node.id];\n const node = existingNode ?? this._constructNode({ data: null, properties: {}, ..._node });\n if (existingNode) {\n const { data = null, properties, type } = _node;\n if (data !== node.data) {\n node.data = data;\n }\n\n if (type !== node.type) {\n node.type = type;\n }\n\n for (const key in properties) {\n if (properties[key] !== node.properties[key]) {\n node.properties[key] = properties[key];\n }\n }\n } else {\n this._nodes[node.id] = node;\n this._edges[node.id] = live({ inbound: [], outbound: [] });\n }\n\n const trigger = this._waitingForNodes[node.id];\n if (trigger) {\n trigger.wake(node);\n delete this._waitingForNodes[node.id];\n }\n\n if (nodes) {\n nodes.forEach((subNode) => {\n this._addNode(subNode);\n this._addEdge({ source: node.id, target: subNode.id });\n });\n }\n\n if (edges) {\n edges.forEach(([id, relation]) =>\n relation === 'outbound'\n ? this._addEdge({ source: node.id, target: id })\n : this._addEdge({ source: id, target: node.id }),\n );\n }\n\n return node as unknown as Node<TData, TProperties>;\n });\n }\n\n /**\n * Remove nodes from the graph.\n *\n * @param ids The id of the node to remove.\n * @param edges Whether to remove edges connected to the node from the graph as well.\n * @internal\n */\n _removeNodes(ids: string[], edges = false) {\n batch(() => ids.forEach((id) => this._removeNode(id, edges)));\n }\n\n private _removeNode(id: string, edges = false) {\n untracked(() => {\n const node = this.findNode(id, false);\n if (!node) {\n return;\n }\n\n if (edges) {\n // Remove edges from connected nodes.\n this._getNodes({ node }).forEach((node) => {\n this._removeEdge({ source: id, target: node.id });\n });\n this._getNodes({ node, relation: 'inbound' }).forEach((node) => {\n this._removeEdge({ source: node.id, target: id });\n });\n\n // Remove edges from node.\n delete this._edges[id];\n }\n\n // Remove node.\n delete this._nodes[id];\n Object.keys(this._initialized)\n .filter((key) => key.startsWith(id))\n .forEach((key) => {\n delete this._initialized[key];\n });\n void this._onRemoveNode?.(id);\n });\n }\n\n /**\n * Add edges to the graph.\n *\n * @internal\n */\n _addEdges(edges: { source: string; target: string }[]) {\n batch(() => edges.forEach((edge) => this._addEdge(edge)));\n }\n\n private _addEdge({ source, target }: { source: string; target: string }) {\n untracked(() => {\n if (!this._edges[source]) {\n this._edges[source] = live({ inbound: [], outbound: [] });\n }\n if (!this._edges[target]) {\n this._edges[target] = live({ inbound: [], outbound: [] });\n }\n\n const sourceEdges = this._edges[source];\n if (!sourceEdges.outbound.includes(target)) {\n sourceEdges.outbound.push(target);\n }\n\n const targetEdges = this._edges[target];\n if (!targetEdges.inbound.includes(source)) {\n targetEdges.inbound.push(source);\n }\n });\n }\n\n /**\n * Remove edges from the graph.\n * @internal\n */\n _removeEdges(edges: { source: string; target: string }[], removeOrphans = false) {\n batch(() => edges.forEach((edge) => this._removeEdge(edge, removeOrphans)));\n }\n\n private _removeEdge({ source, target }: { source: string; target: string }, removeOrphans = false) {\n untracked(() => {\n batch(() => {\n const outboundIndex = this._edges[source]?.outbound.findIndex((id) => id === target);\n if (outboundIndex !== undefined && outboundIndex !== -1) {\n this._edges[source].outbound.splice(outboundIndex, 1);\n }\n\n const inboundIndex = this._edges[target]?.inbound.findIndex((id) => id === source);\n if (inboundIndex !== undefined && inboundIndex !== -1) {\n this._edges[target].inbound.splice(inboundIndex, 1);\n }\n\n if (removeOrphans) {\n if (\n this._edges[source]?.outbound.length === 0 &&\n this._edges[source]?.inbound.length === 0 &&\n source !== ROOT_ID\n ) {\n this._removeNode(source, true);\n }\n if (\n this._edges[target]?.outbound.length === 0 &&\n this._edges[target]?.inbound.length === 0 &&\n target !== ROOT_ID\n ) {\n this._removeNode(target, true);\n }\n }\n });\n });\n }\n\n /**\n * Sort edges for a node.\n *\n * Edges not included in the sorted list are appended to the end of the list.\n *\n * @param nodeId The id of the node to sort edges for.\n * @param relation The relation of the edges from the node to sort.\n * @param edges The ordered list of edges.\n * @ignore\n */\n _sortEdges(nodeId: string, relation: Relation, edges: string[]) {\n untracked(() => {\n batch(() => {\n const current = this._edges[nodeId];\n if (current) {\n const unsorted = current[relation].filter((id) => !edges.includes(id)) ?? [];\n const sorted = edges.filter((id) => current[relation].includes(id)) ?? [];\n current[relation].splice(0, current[relation].length, ...[...sorted, ...unsorted]);\n }\n });\n });\n }\n\n private _constructNode = (node: Omit<Node, typeof graphSymbol>) => {\n return live<NodeInternal>({ ...node, [graphSymbol]: this });\n };\n\n private _getNodes({\n node,\n relation = 'outbound',\n type,\n expansion,\n }: {\n node: Node;\n relation?: Relation;\n type?: string;\n expansion?: boolean;\n }): Node[] {\n if (expansion) {\n void this.expand(node, relation, type);\n }\n\n const edges = this._edges[node.id];\n if (!edges) {\n return [];\n } else {\n return edges[relation]\n .map((id) => this._nodes[id])\n .filter(isNonNullable)\n .filter((n) => !type || n.type === type);\n }\n }\n}\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { type MaybePromise, type MakeOptional } from '@dxos/util';\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 Relation = 'outbound' | 'inbound';\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, Relation][];\n};\n\n//\n// Actions\n//\n\nexport type InvokeParams = {\n /** Node the invoked action is connected to. */\n parent?: Node;\n\n caller?: string;\n};\n\nexport type ActionData = (params?: InvokeParams) => MaybePromise<void>;\n\nexport type Action<TProperties extends Record<string, any> = Record<string, any>> = Readonly<\n Omit<Node<ActionData, TProperties>, 'properties'> & {\n properties: Readonly<TProperties>;\n }\n>;\n\nexport const isAction = (data: unknown): data is Action =>\n isGraphNode(data) ? typeof data.data === 'function' : 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 : false;\n\nexport type ActionLike = Action | ActionGroup;\n\nexport const isActionLike = (data: unknown): data is Action | ActionGroup => isAction(data) || isActionGroup(data);\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { effect, type Signal, signal, untracked } from '@preact/signals-core';\n\nimport { Trigger, type CleanupFn } from '@dxos/async';\nimport { invariant } from '@dxos/invariant';\nimport { live } from '@dxos/live-object';\nimport { log } from '@dxos/log';\nimport { byPosition, type Position, isNode, type MaybePromise, isNonNullable } from '@dxos/util';\n\nimport { ACTION_GROUP_TYPE, ACTION_TYPE, Graph, ROOT_ID, type GraphParams } from './graph';\nimport { type ActionData, actionGroupSymbol, type Node, type NodeArg, type Relation } from './node';\n\nconst NODE_RESOLVER_TIMEOUT = 1_000;\n\n/**\n * Graph builder extension for adding nodes to the graph based on just the node id.\n * This is useful for creating the first node in a graph or for hydrating cached nodes with data.\n *\n * @param params.id The id of the node to resolve.\n */\nexport type ResolverExtension = (params: { id: string }) => NodeArg<any> | false | undefined;\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<T = any> = (params: { node: Node<T> }) => NodeArg<any>[] | undefined;\n\n/**\n * Constrained case of the connector extension for more easily adding actions to the graph.\n */\nexport type ActionsExtension<T = any> = (params: {\n node: Node<T>;\n}) => Omit<NodeArg<ActionData>, 'type' | 'nodes' | 'edges'>[] | undefined;\n\n/**\n * Constrained case of the connector extension for more easily adding action groups to the graph.\n */\nexport type ActionGroupsExtension<T = any> = (params: {\n node: Node<T>;\n}) => Omit<NodeArg<typeof actionGroupSymbol>, 'type' | 'data' | 'nodes' | 'edges'>[] | undefined;\n\ntype GuardedNodeType<T> = T extends (value: any) => value is infer N ? (N extends Node<infer D> ? D : unknown) : never;\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.type If provided, all nodes returned are expected to have this type.\n * @param params.disposition Affects the order the extensions are processed in.\n * @param params.filter A filter function to determine if an extension should act on a node.\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 CreateExtensionOptions<T = any> = {\n id: string;\n relation?: Relation;\n type?: string;\n position?: Position;\n filter?: (node: Node) => node is Node<T>;\n resolver?: ResolverExtension;\n connector?: ConnectorExtension<GuardedNodeType<CreateExtensionOptions<T>['filter']>>;\n actions?: ActionsExtension<GuardedNodeType<CreateExtensionOptions<T>['filter']>>;\n actionGroups?: ActionGroupsExtension<GuardedNodeType<CreateExtensionOptions<T>['filter']>>;\n};\n\n/**\n * Create a graph builder extension.\n */\nexport const createExtension = <T = any>(extension: CreateExtensionOptions<T>): BuilderExtension[] => {\n const { id, position = 'static', resolver, connector, actions, actionGroups, ...rest } = extension;\n const getId = (key: string) => `${id}/${key}`;\n return [\n resolver ? { id: getId('resolver'), position, resolver } : undefined,\n connector ? { ...rest, id: getId('connector'), position, connector } : undefined,\n actionGroups\n ? ({\n ...rest,\n id: getId('actionGroups'),\n position,\n type: ACTION_GROUP_TYPE,\n relation: 'outbound',\n connector: ({ node }) =>\n actionGroups({ node })?.map((arg) => ({ ...arg, data: actionGroupSymbol, type: ACTION_GROUP_TYPE })),\n } satisfies BuilderExtension)\n : undefined,\n actions\n ? ({\n ...rest,\n id: getId('actions'),\n position,\n type: ACTION_TYPE,\n relation: 'outbound',\n connector: ({ node }) => actions({ node })?.map((arg) => ({ ...arg, type: ACTION_TYPE })),\n } satisfies BuilderExtension)\n : undefined,\n ].filter(isNonNullable);\n};\n\nexport type GraphBuilderTraverseOptions = {\n visitor: (node: Node, path: string[]) => MaybePromise<boolean | void>;\n node?: Node;\n relation?: Relation;\n};\n\n/**\n * The dispatcher is used to keep track of the current extension and state when memoizing functions.\n */\nclass Dispatcher {\n currentExtension?: string;\n stateIndex = 0;\n state: Record<string, any[]> = {};\n cleanup: (() => void)[] = [];\n}\n\nclass BuilderInternal {\n // This must be static to avoid passing the dispatcher instance to every memoized function.\n // If the dispatcher is not set that means that the memoized function is being called outside of the graph builder.\n static currentDispatcher?: Dispatcher;\n}\n\n/**\n * Allows code to be memoized within the context of a graph builder extension.\n * This is useful for creating instances which should be subscribed to rather than recreated.\n */\nexport const memoize = <T>(fn: () => T, key = 'result'): T => {\n const dispatcher = BuilderInternal.currentDispatcher;\n invariant(dispatcher?.currentExtension, 'memoize must be called within an extension');\n const all = dispatcher.state[dispatcher.currentExtension][dispatcher.stateIndex] ?? {};\n const current = all[key];\n const result = current ? current.result : fn();\n dispatcher.state[dispatcher.currentExtension][dispatcher.stateIndex] = { ...all, [key]: { result } };\n dispatcher.stateIndex++;\n return result;\n};\n\n/**\n * Register a cleanup function to be called when the graph builder is destroyed.\n */\nexport const cleanup = (fn: () => void): void => {\n memoize(() => {\n const dispatcher = BuilderInternal.currentDispatcher;\n invariant(dispatcher, 'cleanup must be called within an extension');\n dispatcher.cleanup.push(fn);\n });\n};\n\n/**\n * Convert a subscribe/get pair into a signal.\n */\nexport const toSignal = <T>(\n subscribe: (onChange: () => void) => () => void,\n get: () => T | undefined,\n key?: string,\n) => {\n const thisSignal = memoize(() => {\n return signal(get());\n }, key);\n const unsubscribe = memoize(() => {\n return subscribe(() => (thisSignal.value = get()));\n }, key);\n cleanup(() => {\n unsubscribe();\n });\n return thisSignal.value;\n};\n\nexport type BuilderExtension = Readonly<{\n id: string;\n position: Position;\n resolver?: ResolverExtension;\n connector?: ConnectorExtension;\n // Only for connector.\n relation?: Relation;\n type?: string;\n filter?: (node: Node) => boolean;\n}>;\n\ntype ExtensionArg = BuilderExtension | BuilderExtension[] | ExtensionArg[];\n\nexport const flattenExtensions = (extension: ExtensionArg, 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\n/**\n * The builder provides an extensible way to compose the construction of the graph.\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.\nexport class GraphBuilder {\n private readonly _dispatcher = new Dispatcher();\n private readonly _extensions = live<Record<string, BuilderExtension>>({});\n private readonly _resolverSubscriptions = new Map<string, CleanupFn>();\n private readonly _connectorSubscriptions = new Map<string, CleanupFn>();\n private readonly _nodeChanged: Record<string, Signal<{}>> = {};\n private readonly _initialized: Record<string, Trigger> = {};\n private _graph: Graph;\n\n constructor(params: Pick<GraphParams, 'nodes' | 'edges'> = {}) {\n this._graph = new Graph({\n ...params,\n onInitialNode: async (id) => this._onInitialNode(id),\n onInitialNodes: async (node, relation, type) => this._onInitialNodes(node, relation, type),\n onRemoveNode: (id) => this._onRemoveNode(id),\n });\n }\n\n static from(pickle?: string) {\n if (!pickle) {\n return new GraphBuilder();\n }\n\n const { nodes, edges } = JSON.parse(pickle);\n return new GraphBuilder({ nodes, edges });\n }\n\n /**\n * If graph is being restored from a pickle, the data will be null.\n * Initialize the data of each node by calling resolvers.\n * Wait until all of the initial nodes have resolved.\n */\n async initialize() {\n Object.keys(this._graph._nodes)\n .filter((id) => id !== ROOT_ID)\n .forEach((id) => (this._initialized[id] = new Trigger()));\n Object.keys(this._graph._nodes).forEach((id) => this._onInitialNode(id));\n await Promise.all(\n Object.entries(this._initialized).map(async ([id, trigger]) => {\n try {\n await trigger.wait({ timeout: NODE_RESOLVER_TIMEOUT });\n } catch {\n log.error('node resolver timeout', { id });\n this.graph._removeNodes([id]);\n }\n }),\n );\n }\n\n get graph() {\n return this._graph;\n }\n\n /**\n * @reactive\n */\n get extensions() {\n return Object.values(this._extensions);\n }\n\n /**\n * Register a node builder which will be called in order to construct the graph.\n */\n addExtension(extension: ExtensionArg): GraphBuilder {\n const extensions = flattenExtensions(extension);\n untracked(() => {\n extensions.forEach((extension) => {\n this._dispatcher.state[extension.id] = [];\n this._extensions[extension.id] = extension;\n });\n });\n return this;\n }\n\n /**\n * Remove a node builder from the graph builder.\n */\n removeExtension(id: string): GraphBuilder {\n untracked(() => {\n delete this._extensions[id];\n });\n return this;\n }\n\n destroy() {\n this._dispatcher.cleanup.forEach((fn) => fn());\n this._resolverSubscriptions.forEach((unsubscribe) => unsubscribe());\n this._connectorSubscriptions.forEach((unsubscribe) => unsubscribe());\n this._resolverSubscriptions.clear();\n this._connectorSubscriptions.clear();\n }\n\n /**\n * A graph traversal using just the connector extensions, without subscribing to any signals or persisting any nodes.\n */\n async explore(\n { node = this._graph.root, relation = 'outbound', visitor }: GraphBuilderTraverseOptions,\n path: string[] = [],\n ) {\n // Break cycles.\n if (path.includes(node.id)) {\n return;\n }\n\n // TODO(wittjosiah): This is a workaround for esm not working in the test runner.\n // Switching to vitest is blocked by having node esm versions of echo-schema & echo-signals.\n if (!isNode()) {\n const { yieldOrContinue } = await import('main-thread-scheduling');\n await yieldOrContinue('idle');\n }\n const shouldContinue = await visitor(node, [...path, node.id]);\n if (shouldContinue === false) {\n return;\n }\n\n const nodes = Object.values(this._extensions)\n .filter((extension) => relation === (extension.relation ?? 'outbound'))\n .filter((extension) => !extension.filter || extension.filter(node))\n .flatMap((extension) => {\n this._dispatcher.currentExtension = extension.id;\n this._dispatcher.stateIndex = 0;\n BuilderInternal.currentDispatcher = this._dispatcher;\n const result = extension.connector?.({ node }) ?? [];\n BuilderInternal.currentDispatcher = undefined;\n return result;\n })\n .map(\n (arg): Node => ({\n id: arg.id,\n type: arg.type,\n cacheable: arg.cacheable,\n data: arg.data ?? null,\n properties: arg.properties ?? {},\n }),\n );\n\n await Promise.all(nodes.map((n) => this.explore({ node: n, relation, visitor }, [...path, node.id])));\n }\n\n private _onInitialNode(nodeId: string) {\n this._nodeChanged[nodeId] = this._nodeChanged[nodeId] ?? signal({});\n this._resolverSubscriptions.set(\n nodeId,\n effect(() => {\n const extensions = Object.values(this._extensions).toSorted(byPosition);\n for (const { id, resolver } of extensions) {\n if (!resolver) {\n continue;\n }\n\n this._dispatcher.currentExtension = id;\n this._dispatcher.stateIndex = 0;\n BuilderInternal.currentDispatcher = this._dispatcher;\n let node: NodeArg<any> | false | undefined;\n try {\n node = resolver({ id: nodeId });\n } catch (err) {\n log.catch(err, { extension: id });\n log.error(`Previous error occurred in extension: ${id}`);\n } finally {\n BuilderInternal.currentDispatcher = undefined;\n }\n\n const trigger = this._initialized[nodeId];\n if (node) {\n this.graph._addNodes([node]);\n trigger?.wake();\n if (this._nodeChanged[node.id]) {\n this._nodeChanged[node.id].value = {};\n }\n break;\n } else if (node === false) {\n this.graph._removeNodes([nodeId]);\n trigger?.wake();\n break;\n }\n }\n }),\n );\n }\n\n private _onInitialNodes(node: Node, nodesRelation: Relation, nodesType?: string) {\n this._nodeChanged[node.id] = this._nodeChanged[node.id] ?? signal({});\n let first = true;\n let previous: string[] = [];\n this._connectorSubscriptions.set(\n node.id,\n effect(() => {\n // TODO(wittjosiah): This is a workaround for a race between the node removal and the effect re-running.\n // To cause this case to happen, remove a collection and then undo the removal.\n if (!first && !this._connectorSubscriptions.has(node.id)) {\n return;\n }\n first = false;\n\n // Subscribe to extensions being added.\n Object.keys(this._extensions);\n // Subscribe to connected node changes.\n this._nodeChanged[node.id].value;\n\n // TODO(wittjosiah): Consider allowing extensions to collaborate on the same node by merging their results.\n const nodes: NodeArg<any>[] = [];\n const extensions = Object.values(this._extensions).toSorted(byPosition);\n for (const { id, connector, filter, type, relation = 'outbound' } of extensions) {\n if (\n !connector ||\n relation !== nodesRelation ||\n (nodesType && type !== nodesType) ||\n (filter && !filter(node))\n ) {\n continue;\n }\n\n this._dispatcher.currentExtension = id;\n this._dispatcher.stateIndex = 0;\n BuilderInternal.currentDispatcher = this._dispatcher;\n try {\n nodes.push(...(connector({ node }) ?? []));\n } catch (err) {\n log.catch(err, { extension: id });\n log.error(`Previous error occurred in extension: ${id}`);\n } finally {\n BuilderInternal.currentDispatcher = undefined;\n }\n }\n\n const ids = nodes.map((n) => n.id);\n const removed = previous.filter((id) => !ids.includes(id));\n previous = ids;\n\n // Remove edges and only remove nodes that are orphaned.\n this.graph._removeEdges(\n removed.map((target) => ({ source: node.id, target })),\n true,\n );\n this.graph._addNodes(nodes);\n this.graph._addEdges(\n nodes.map(({ id }) =>\n nodesRelation === 'outbound' ? { source: node.id, target: id } : { source: id, target: node.id },\n ),\n );\n this.graph._sortEdges(\n node.id,\n nodesRelation,\n nodes.map(({ id }) => id),\n );\n nodes.forEach((n) => {\n if (this._nodeChanged[n.id]) {\n this._nodeChanged[n.id].value = {};\n }\n });\n }),\n );\n }\n\n private async _onRemoveNode(nodeId: string) {\n this._resolverSubscriptions.get(nodeId)?.();\n this._connectorSubscriptions.get(nodeId)?.();\n this._resolverSubscriptions.delete(nodeId);\n this._connectorSubscriptions.delete(nodeId);\n }\n}\n"],
5
5
  "mappings": ";;;AAIA,SAASA,OAAOC,QAAQC,iBAAiB;AAEzC,SAASC,cAAcC,eAAe;AACtC,SAASC,iBAAiB;AAC1B,SAAoBC,YAAY;AAChC,SAASC,WAAW;AACpB,SAA4BC,eAAeC,YAAY;;;ACwChD,IAAMC,cAAc,CAACC,SAC1BA,QAAQ,OAAOA,SAAS,YAAY,QAAQA,QAAQ,gBAAgBA,QAAQA,KAAKC,aAC7E,OAAOD,KAAKC,eAAe,YAAY,UAAUD,OACjD;AAgCC,IAAME,WAAW,CAACF,SACvBD,YAAYC,IAAAA,IAAQ,OAAOA,KAAKA,SAAS,aAAa;AAEjD,IAAMG,oBA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A/C,MAAMxD,IAAI,CAAC,EAAEd,GAAE,MAAOA,EAAAA,CAAAA;AAExBsE,YAAMS,QAAQ,CAAC4B,MAAAA;AACb,YAAI,KAAKjD,aAAaiD,EAAE3G,EAAE,GAAG;AAC3B,eAAK0D,aAAaiD,EAAE3G,EAAE,EAAE0C,QAAQ,CAAC;QACnC;MACF,CAAA;IACF,CAAA,CAAA;EAEJ;EAEA,MAAcyB,cAAcyC,QAAgB;AAC1C,SAAKrD,uBAAuBjB,IAAIsE,MAAAA,IAAAA;AAChC,SAAKnD,wBAAwBnB,IAAIsE,MAAAA,IAAAA;AACjC,SAAKrD,uBAAuB0E,OAAOrB,MAAAA;AACnC,SAAKnD,wBAAwBwE,OAAOrB,MAAAA;EACtC;AACF;",
6
6
  "names": ["batch", "effect", "untracked", "asyncTimeout", "Trigger", "invariant", "live", "log", "isNonNullable", "pick", "isGraphNode", "data", "properties", "isAction", "actionGroupSymbol", "Symbol", "isActionGroup", "isActionLike", "graphSymbol", "Symbol", "getGraph", "node", "graph", "invariant", "ROOT_ID", "ROOT_TYPE", "ACTION_TYPE", "ACTION_GROUP_TYPE", "DEFAULT_FILTER", "untracked", "isActionLike", "Graph", "constructor", "nodes", "edges", "onInitialNode", "onInitialNodes", "onRemoveNode", "_waitingForNodes", "_initialized", "_nodes", "_edges", "_constructNode", "live", "_onInitialNode", "_onInitialNodes", "_onRemoveNode", "id", "type", "cacheable", "properties", "data", "forEach", "Object", "keys", "_addNode", "log", "warn", "actionGroupSymbol", "inbound", "outbound", "entries", "source", "target", "_addEdge", "_sortEdges", "from", "pickle", "options", "JSON", "parse", "root", "findNode", "toJSON", "maxLength", "seen", "obj", "length", "slice", "label", "map", "n", "nextSeen", "includes", "undefined", "filter", "isNonNullable", "values", "pick", "Set", "fromEntries", "has", "nodeId", "toSorted", "a", "b", "localeCompare", "stringify", "expansion", "existingNode", "waitForNode", "timeout", "trigger", "Trigger", "wait", "asyncTimeout", "relation", "_getNodes", "actions", "expand", "key", "_key", "initialized", "traverse", "visitor", "path", "shouldContinue", "child", "subscribeTraverse", "currentPath", "effect", "result", "nodeSubscriptions", "unsubscribe", "getPath", "start", "found", "waitForPath", "params", "interval", "i", "setInterval", "wake", "finally", "clearInterval", "_addNodes", "batch", "_node", "subNode", "_removeNodes", "ids", "_removeNode", "_removeEdge", "startsWith", "_addEdges", "edge", "sourceEdges", "push", "targetEdges", "_removeEdges", "removeOrphans", "outboundIndex", "findIndex", "splice", "inboundIndex", "current", "unsorted", "sorted", "effect", "signal", "untracked", "Trigger", "invariant", "live", "log", "byPosition", "isNode", "isNonNullable", "NODE_RESOLVER_TIMEOUT", "createExtension", "extension", "id", "position", "resolver", "connector", "actions", "actionGroups", "rest", "getId", "key", "undefined", "type", "ACTION_GROUP_TYPE", "relation", "node", "map", "arg", "data", "actionGroupSymbol", "ACTION_TYPE", "filter", "isNonNullable", "Dispatcher", "stateIndex", "state", "cleanup", "BuilderInternal", "memoize", "fn", "dispatcher", "currentDispatcher", "invariant", "currentExtension", "all", "current", "result", "push", "toSignal", "subscribe", "get", "thisSignal", "signal", "unsubscribe", "value", "flattenExtensions", "acc", "Array", "isArray", "flatMap", "ext", "GraphBuilder", "constructor", "params", "_dispatcher", "_extensions", "live", "_resolverSubscriptions", "Map", "_connectorSubscriptions", "_nodeChanged", "_initialized", "_graph", "Graph", "onInitialNode", "_onInitialNode", "onInitialNodes", "_onInitialNodes", "onRemoveNode", "_onRemoveNode", "from", "pickle", "nodes", "edges", "JSON", "parse", "initialize", "Object", "keys", "_nodes", "ROOT_ID", "forEach", "Trigger", "Promise", "entries", "trigger", "wait", "timeout", "log", "error", "graph", "_removeNodes", "extensions", "values", "addExtension", "untracked", "removeExtension", "destroy", "clear", "explore", "root", "visitor", "path", "includes", "isNode", "yieldOrContinue", "shouldContinue", "cacheable", "properties", "n", "nodeId", "set", "effect", "toSorted", "byPosition", "err", "catch", "_addNodes", "wake", "nodesRelation", "nodesType", "first", "previous", "has", "ids", "removed", "_removeEdges", "target", "source", "_addEdges", "_sortEdges", "delete"]
7
7
  }
@@ -1 +1 @@
1
- {"inputs":{"packages/sdk/app-graph/src/node.ts":{"bytes":5859,"imports":[],"format":"esm"},"packages/sdk/app-graph/src/graph.ts":{"bytes":63179,"imports":[{"path":"@preact/signals-core","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/live-object","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"packages/sdk/app-graph/src/node.ts","kind":"import-statement","original":"./node"}],"format":"esm"},"packages/sdk/app-graph/src/graph-builder.ts":{"bytes":52318,"imports":[{"path":"@preact/signals-core","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/live-object","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"packages/sdk/app-graph/src/graph.ts","kind":"import-statement","original":"./graph"},{"path":"packages/sdk/app-graph/src/node.ts","kind":"import-statement","original":"./node"},{"path":"main-thread-scheduling","kind":"dynamic-import","external":true}],"format":"esm"},"packages/sdk/app-graph/src/index.ts":{"bytes":672,"imports":[{"path":"packages/sdk/app-graph/src/graph.ts","kind":"import-statement","original":"./graph"},{"path":"packages/sdk/app-graph/src/graph-builder.ts","kind":"import-statement","original":"./graph-builder"},{"path":"packages/sdk/app-graph/src/node.ts","kind":"import-statement","original":"./node"}],"format":"esm"}},"outputs":{"packages/sdk/app-graph/dist/lib/node-esm/index.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":61203},"packages/sdk/app-graph/dist/lib/node-esm/index.mjs":{"imports":[{"path":"@preact/signals-core","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/live-object","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"@preact/signals-core","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/live-object","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"main-thread-scheduling","kind":"dynamic-import","external":true}],"exports":["ACTION_GROUP_TYPE","ACTION_TYPE","Graph","GraphBuilder","ROOT_ID","ROOT_TYPE","actionGroupSymbol","cleanup","createExtension","flattenExtensions","getGraph","isAction","isActionGroup","isActionLike","isGraphNode","memoize","toSignal"],"entryPoint":"packages/sdk/app-graph/src/index.ts","inputs":{"packages/sdk/app-graph/src/graph.ts":{"bytesInOutput":15387},"packages/sdk/app-graph/src/node.ts":{"bytesInOutput":477},"packages/sdk/app-graph/src/index.ts":{"bytesInOutput":0},"packages/sdk/app-graph/src/graph-builder.ts":{"bytesInOutput":11341}},"bytes":27762}}}
1
+ {"inputs":{"packages/sdk/app-graph/src/node.ts":{"bytes":5863,"imports":[],"format":"esm"},"packages/sdk/app-graph/src/graph.ts":{"bytes":63179,"imports":[{"path":"@preact/signals-core","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/live-object","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"packages/sdk/app-graph/src/node.ts","kind":"import-statement","original":"./node"}],"format":"esm"},"packages/sdk/app-graph/src/graph-builder.ts":{"bytes":52318,"imports":[{"path":"@preact/signals-core","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/live-object","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"packages/sdk/app-graph/src/graph.ts","kind":"import-statement","original":"./graph"},{"path":"packages/sdk/app-graph/src/node.ts","kind":"import-statement","original":"./node"},{"path":"main-thread-scheduling","kind":"dynamic-import","external":true}],"format":"esm"},"packages/sdk/app-graph/src/index.ts":{"bytes":672,"imports":[{"path":"packages/sdk/app-graph/src/graph.ts","kind":"import-statement","original":"./graph"},{"path":"packages/sdk/app-graph/src/graph-builder.ts","kind":"import-statement","original":"./graph-builder"},{"path":"packages/sdk/app-graph/src/node.ts","kind":"import-statement","original":"./node"}],"format":"esm"}},"outputs":{"packages/sdk/app-graph/dist/lib/node-esm/index.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":61207},"packages/sdk/app-graph/dist/lib/node-esm/index.mjs":{"imports":[{"path":"@preact/signals-core","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/live-object","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"@preact/signals-core","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/live-object","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"main-thread-scheduling","kind":"dynamic-import","external":true}],"exports":["ACTION_GROUP_TYPE","ACTION_TYPE","Graph","GraphBuilder","ROOT_ID","ROOT_TYPE","actionGroupSymbol","cleanup","createExtension","flattenExtensions","getGraph","isAction","isActionGroup","isActionLike","isGraphNode","memoize","toSignal"],"entryPoint":"packages/sdk/app-graph/src/index.ts","inputs":{"packages/sdk/app-graph/src/graph.ts":{"bytesInOutput":15387},"packages/sdk/app-graph/src/node.ts":{"bytesInOutput":477},"packages/sdk/app-graph/src/index.ts":{"bytesInOutput":0},"packages/sdk/app-graph/src/graph-builder.ts":{"bytesInOutput":11341}},"bytes":27762}}}
@@ -0,0 +1,25 @@
1
+ type Cb = () => void;
2
+ interface Query {
3
+ id?: string[];
4
+ typename?: string[];
5
+ }
6
+ /**
7
+ * Lazy query result that can be executed.
8
+ * Does not run without the run function being called.
9
+ */
10
+ interface QueryResult<T> {
11
+ /**
12
+ * Execute the query and subscribe to the result.
13
+ * @param next Called at least once with the first value (maybe synchronously) and then for every subsequent update.
14
+ * @param error Called on error. `next` is never called after that.
15
+ * @returns Function to dispose the query and unsubscribe.
16
+ */
17
+ run(onData: (value?: T[]) => void, onError: (err: Error) => void): Cb;
18
+ }
19
+ declare const QueryResult: Readonly<{
20
+ fromPromise: <T>(run: (onDispose: (cb: Cb) => void) => Promise<T[]>) => QueryResult<T>;
21
+ }>;
22
+ interface _Resolver<T> {
23
+ query(query: Query): QueryResult<T>;
24
+ }
25
+ //# sourceMappingURL=graph-projections.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"graph-projections.test.d.ts","sourceRoot":"","sources":["../../../../src/experimental/graph-projections.test.ts"],"names":[],"mappings":"AAIA,KAAK,EAAE,GAAG,MAAM,IAAI,CAAC;AAErB,UAAU,KAAK;IACb,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC;IACd,QAAQ,CAAC,EAAE,MAAM,EAAE,CAAC;CACrB;AAED;;;GAGG;AACH,UAAU,WAAW,CAAC,CAAC;IACrB;;;;;OAKG;IACH,GAAG,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,EAAE,CAAC,EAAE,KAAK,IAAI,EAAE,OAAO,EAAE,CAAC,GAAG,EAAE,KAAK,KAAK,IAAI,GAAG,EAAE,CAAC;CACvE;AAED,QAAA,MAAM,WAAW;kBACD,CAAC,OAAO,CAAC,SAAS,EAAE,CAAC,EAAE,EAAE,EAAE,KAAK,IAAI,KAAK,OAAO,CAAC,CAAC,EAAE,CAAC,KAAG,WAAW,CAAC,CAAC,CAAC;EAyBpF,CAAC;AAE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EAAE,EAAE,qBAAqB,EACtF,WAAW,GAAE,MAAM,EAAO;IAiB5B;;OAEG;IACH,OAAO,CAAC,EAAE,MAAe,EAAE,MAAM,EAAE,EAAE;QAAE,MAAM,CAAC,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,GAAG,MAAM,EAAE,GAAG,SAAS;IAuB/F;;OAEG;IACG,WAAW,CACf,MAAM,EAAE;QAAE,MAAM,CAAC,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,EAC3C,EAAE,OAAe,EAAE,QAAc,EAAE,GAAE;QAAE,OAAO,CAAC,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,EAAE,MAAM,CAAA;KAAO;IA6BnF,OAAO,CAAC,QAAQ;IAgEhB,OAAO,CAAC,WAAW;IAwCnB,OAAO,CAAC,QAAQ;IA6BhB,OAAO,CAAC,WAAW;IAiCnB;;;;;;;;;OASG;IACH,UAAU,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,EAAE,KAAK,EAAE,MAAM,EAAE;IAa9D,OAAO,CAAC,cAAc,CAEpB;IAEF,OAAO,CAAC,SAAS;CAyBlB"}
@@ -37,10 +37,10 @@ export type NodeArg<TData, TProperties extends Record<string, any> = Record<stri
37
37
  };
38
38
  export type InvokeParams = {
39
39
  /** Node the invoked action is connected to. */
40
- node: Node;
40
+ parent?: Node;
41
41
  caller?: string;
42
42
  };
43
- export type ActionData = (params: InvokeParams) => MaybePromise<void>;
43
+ export type ActionData = (params?: InvokeParams) => MaybePromise<void>;
44
44
  export type Action<TProperties extends Record<string, any> = Record<string, any>> = Readonly<Omit<Node<ActionData, TProperties>, 'properties'> & {
45
45
  properties: Readonly<TProperties>;
46
46
  }>;
@@ -1 +1 @@
1
- {"version":3,"file":"node.d.ts","sourceRoot":"","sources":["../../../src/node.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,KAAK,YAAY,EAAE,KAAK,YAAY,EAA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AI,IAAI,MAAM,GAAG,WAAoD,CAAC"}
@@ -1 +1 @@
1
- {"version":"5.7.3"}
1
+ {"version":"5.8.3"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dxos/app-graph",
3
- "version": "0.8.2-main.5885341",
3
+ "version": "0.8.2-main.600d381",
4
4
  "description": "Constructs knowledge graphs for the purpose of building applications on top of",
5
5
  "homepage": "https://dxos.org",
6
6
  "bugs": "https://github.com/dxos/dxos/issues",
@@ -26,14 +26,14 @@
26
26
  "dependencies": {
27
27
  "@preact/signals-core": "^1.6.0",
28
28
  "main-thread-scheduling": "^14.1.1",
29
- "@dxos/async": "0.8.2-main.5885341",
30
- "@dxos/debug": "0.8.2-main.5885341",
31
- "@dxos/echo-schema": "0.8.2-main.5885341",
32
- "@dxos/echo-signals": "0.8.2-main.5885341",
33
- "@dxos/invariant": "0.8.2-main.5885341",
34
- "@dxos/live-object": "0.8.2-main.5885341",
35
- "@dxos/log": "0.8.2-main.5885341",
36
- "@dxos/util": "0.8.2-main.5885341"
29
+ "@dxos/async": "0.8.2-main.600d381",
30
+ "@dxos/debug": "0.8.2-main.600d381",
31
+ "@dxos/echo-schema": "0.8.2-main.600d381",
32
+ "@dxos/invariant": "0.8.2-main.600d381",
33
+ "@dxos/echo-signals": "0.8.2-main.600d381",
34
+ "@dxos/live-object": "0.8.2-main.600d381",
35
+ "@dxos/util": "0.8.2-main.600d381",
36
+ "@dxos/log": "0.8.2-main.600d381"
37
37
  },
38
38
  "devDependencies": {
39
39
  "@phosphor-icons/react": "^2.1.5",
@@ -42,18 +42,18 @@
42
42
  "react": "~18.2.0",
43
43
  "react-dom": "~18.2.0",
44
44
  "vite": "5.4.7",
45
- "@dxos/random": "0.8.2-main.5885341",
46
- "@dxos/react-ui-theme": "0.8.2-main.5885341",
47
- "@dxos/react-ui": "0.8.2-main.5885341",
48
- "@dxos/react-client": "0.8.2-main.5885341",
49
- "@dxos/storybook-utils": "0.8.2-main.5885341"
45
+ "@dxos/random": "0.8.2-main.600d381",
46
+ "@dxos/react-client": "0.8.2-main.600d381",
47
+ "@dxos/react-ui": "0.8.2-main.600d381",
48
+ "@dxos/react-ui-theme": "0.8.2-main.600d381",
49
+ "@dxos/storybook-utils": "0.8.2-main.600d381"
50
50
  },
51
51
  "peerDependencies": {
52
52
  "@phosphor-icons/react": "^2.1.5",
53
53
  "react": "~18.2.0",
54
54
  "react-dom": "~18.2.0",
55
- "@dxos/react-ui": "0.8.2-main.5885341",
56
- "@dxos/react-ui-theme": "0.8.2-main.5885341"
55
+ "@dxos/react-ui": "0.8.2-main.600d381",
56
+ "@dxos/react-ui-theme": "0.8.2-main.600d381"
57
57
  },
58
58
  "publishConfig": {
59
59
  "access": "public"
@@ -0,0 +1,56 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ type Cb = () => void;
6
+
7
+ interface Query {
8
+ id?: string[];
9
+ typename?: string[];
10
+ }
11
+
12
+ /**
13
+ * Lazy query result that can be executed.
14
+ * Does not run without the run function being called.
15
+ */
16
+ interface QueryResult<T> {
17
+ /**
18
+ * Execute the query and subscribe to the result.
19
+ * @param next Called at least once with the first value (maybe synchronously) and then for every subsequent update.
20
+ * @param error Called on error. `next` is never called after that.
21
+ * @returns Function to dispose the query and unsubscribe.
22
+ */
23
+ run(onData: (value?: T[]) => void, onError: (err: Error) => void): Cb;
24
+ }
25
+
26
+ const QueryResult = Object.freeze({
27
+ fromPromise: <T>(run: (onDispose: (cb: Cb) => void) => Promise<T[]>): QueryResult<T> => {
28
+ return {
29
+ run: (onData, onError) => {
30
+ const cbs: Cb[] = [];
31
+ let disposed = false;
32
+ const dispose = () => {
33
+ cbs.forEach((cb) => cb());
34
+ disposed = true;
35
+ };
36
+ run((cb) => (disposed ? cb() : cbs.push(cb))).then(
37
+ (data) => {
38
+ if (disposed) {
39
+ return;
40
+ }
41
+ onData(data);
42
+ },
43
+ (err) => {
44
+ dispose();
45
+ onError(err);
46
+ },
47
+ );
48
+ return dispose;
49
+ },
50
+ };
51
+ },
52
+ });
53
+
54
+ interface _Resolver<T> {
55
+ query(query: Query): QueryResult<T>;
56
+ }
package/src/node.ts CHANGED
@@ -70,12 +70,12 @@ export type NodeArg<TData, TProperties extends Record<string, any> = Record<stri
70
70
 
71
71
  export type InvokeParams = {
72
72
  /** Node the invoked action is connected to. */
73
- node: Node;
73
+ parent?: Node;
74
74
 
75
75
  caller?: string;
76
76
  };
77
77
 
78
- export type ActionData = (params: InvokeParams) => MaybePromise<void>;
78
+ export type ActionData = (params?: InvokeParams) => MaybePromise<void>;
79
79
 
80
80
  export type Action<TProperties extends Record<string, any> = Record<string, any>> = Readonly<
81
81
  Omit<Node<ActionData, TProperties>, 'properties'> & {