@dxos/app-graph 0.7.1 → 0.7.2-staging.6d26b2a
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/lib/browser/index.mjs +34 -20
- package/dist/lib/browser/index.mjs.map +3 -3
- package/dist/lib/browser/meta.json +1 -1
- package/dist/lib/node/index.cjs +33 -19
- package/dist/lib/node/index.cjs.map +3 -3
- package/dist/lib/node/meta.json +1 -1
- package/dist/lib/node-esm/index.mjs +34 -20
- package/dist/lib/node-esm/index.mjs.map +3 -3
- package/dist/lib/node-esm/meta.json +1 -1
- package/dist/types/src/graph-builder.d.ts +1 -1
- package/dist/types/src/graph-builder.d.ts.map +1 -1
- package/dist/types/src/graph.d.ts +5 -1
- package/dist/types/src/graph.d.ts.map +1 -1
- package/dist/types/src/node.d.ts +7 -1
- package/dist/types/src/node.d.ts.map +1 -1
- package/package.json +15 -15
- package/src/graph-builder.ts +6 -2
- package/src/graph.ts +32 -20
- package/src/node.ts +8 -1
- package/src/stories/EchoGraph.stories.tsx +2 -2
|
@@ -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 { type ReactiveObject, create } from '@dxos/echo-schema';\nimport { invariant } from '@dxos/invariant';\nimport { log } from '@dxos/log';\nimport { nonNullable } from '@dxos/util';\n\nimport { type Relation, type Node, type NodeArg, type NodeFilter, isActionLike, actionGroupSymbol } from './node';\n\nconst graphSymbol = Symbol('graph');\ntype DeepWriteable<T> = { -readonly [K in keyof T]: DeepWriteable<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<T = any, U extends Record<string, any> = Record<string, any>> = {\n relation?: Relation;\n filter?: NodeFilter<T, U>;\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 // TODO(wittjosiah): Make data optional instead of omitting.\n nodes?: Omit<Node, 'data'>[];\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, ReactiveObject<NodeInternal>> = {};\n\n /**\n * @internal\n */\n readonly _edges: Record<string, ReactiveObject<{ inbound: string[]; outbound: string[] }>> = {};\n\n constructor({ nodes, edges, onInitialNode, onInitialNodes, onRemoveNode }: GraphParams = {}) {\n this._nodes[ROOT_ID] = this._constructNode({ id: ROOT_ID, type: ROOT_TYPE, properties: {}, data: null });\n if (nodes) {\n nodes.forEach((node) => {\n if (node.type === ACTION_TYPE) {\n this._addNode({ ...node, data: () => log.warn('Pickled action invocation') });\n } else if (node.type === ACTION_GROUP_TYPE) {\n this._addNode({ ...node, data: actionGroupSymbol });\n } else {\n this._addNode(node);\n }\n });\n }\n\n this._edges[ROOT_ID] = create({ 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 this._onInitialNode = onInitialNode;\n this._onInitialNodes = onInitialNodes;\n this._onRemoveNode = onRemoveNode;\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(nonNullable);\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).map((node) => {\n return {\n id: node.id,\n type: node.type,\n properties: node.properties,\n };\n });\n\n const edges = Object.fromEntries(\n Object.entries(this._edges)\n .map(([id, { outbound }]): [string, string[]] => [id, outbound])\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<T = any, U extends Record<string, any> = Record<string, any>>(node: Node, options: NodesOptions<T, U> = {}) {\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\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, properties, type } = _node;\n if (data && 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] = create({ 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);\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] = create({ inbound: [], outbound: [] });\n }\n if (!this._edges[target]) {\n this._edges[target] = create({ 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 create<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(nonNullable)\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 id: string;\n\n /**\n * Typename of the data the node represents.\n */\n type: 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<T = any, U extends Record<string, any> = Record<string, any>> = (\n node: Node<unknown, Record<string, any>>,\n connectedNode: Node,\n) => node is Node<T, U>;\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'\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 = Readonly<\n Omit<Node<typeof actionGroupSymbol, Record<string, any>>, 'properties'> & {\n properties: Readonly<Record<string, any>>;\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 { type Signal, effect, signal } from '@preact/signals-core';\n\nimport { type UnsubscribeCallback } from '@dxos/async';\nimport { create } from '@dxos/echo-schema';\nimport { invariant } from '@dxos/invariant';\nimport { log } from '@dxos/log';\nimport { isNode, type MaybePromise, nonNullable } from '@dxos/util';\n\nimport { ACTION_GROUP_TYPE, ACTION_TYPE, Graph, type GraphParams } from './graph';\nimport { type Relation, type NodeArg, type Node, type ActionData, actionGroupSymbol } from './node';\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> | 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.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 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, resolver, connector, actions, actionGroups, ...rest } = extension;\n const getId = (key: string) => `${id}/${key}`;\n return [\n resolver ? { id: getId('resolver'), resolver } : undefined,\n connector ? { ...rest, id: getId('connector'), connector } : undefined,\n actionGroups\n ? ({\n ...rest,\n id: getId('actionGroups'),\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 type: ACTION_TYPE,\n relation: 'outbound',\n connector: ({ node }) => actions({ node })?.map((arg) => ({ ...arg, type: ACTION_TYPE })),\n } satisfies BuilderExtension)\n : undefined,\n ].filter(nonNullable);\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 = {\n id: string;\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\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 = create<Record<string, BuilderExtension>>({});\n private readonly _resolverSubscriptions = new Map<string, UnsubscribeCallback>();\n private readonly _connectorSubscriptions = new Map<string, UnsubscribeCallback>();\n private readonly _nodeChanged: Record<string, Signal<{}>> = {};\n private _graph: Graph;\n\n constructor(params: Pick<GraphParams, 'nodes' | 'edges'> = {}) {\n this._graph = new Graph({\n ...params,\n onInitialNode: (id) => this._onInitialNode(id),\n onInitialNodes: (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 */\n async initialize() {\n return Promise.all(Object.keys(this._graph._nodes).map((id) => this._onInitialNode(id)));\n }\n\n get graph() {\n return this._graph;\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 if (Array.isArray(extension)) {\n extension.forEach((ext) => this.addExtension(ext));\n return this;\n }\n\n this._dispatcher.state[extension.id] = [];\n this._extensions[extension.id] = extension;\n return this;\n }\n\n /**\n * Remove a node builder from the graph builder.\n */\n removeExtension(id: string): GraphBuilder {\n delete this._extensions[id];\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 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 async _onInitialNode(nodeId: string) {\n this._nodeChanged[nodeId] = this._nodeChanged[nodeId] ?? signal({});\n this._resolverSubscriptions.set(\n nodeId,\n effect(() => {\n for (const { id, resolver } of Object.values(this._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> | 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 if (node) {\n this.graph._addNodes([node]);\n if (this._nodeChanged[node.id]) {\n this._nodeChanged[node.id].value = {};\n }\n break;\n }\n }\n }),\n );\n }\n\n private async _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 for (const { id, connector, filter, type, relation = 'outbound' } of Object.values(this._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
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,0BAAyC;AAEzC,mBAAsC;AACtC,yBAA4C;AAC5C,uBAA0B;AAC1B,iBAAoB;AACpB,kBAA4B;AEN5B,IAAAA,uBAA4C;AAG5C,IAAAC,sBAAuB;AACvB,IAAAC,oBAA0B;AAC1B,IAAAC,cAAoB;AACpB,IAAAC,eAAuD;ADgChD,IAAMC,cAAc,CAACC,SAC1BA,QAAQ,OAAOA,SAAS,YAAY,QAAQA,QAAQ,gBAAgBA,QAAQA,KAAKC,aAC7E,OAAOD,K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A;EAEJ;EAEA,MAAcnH,cAAcuF,QAAgB;AAC1C,SAAKgC,uBAAuBP,IAAIzB,MAAAA,IAAAA;AAChC,SAAKkC,wBAAwBT,IAAIzB,MAAAA,IAAAA;AACjC,SAAKgC,uBAAuB4B,OAAO5D,MAAAA;AACnC,SAAKkC,wBAAwB0B,OAAO5D,MAAAA;EACtC;AACF;",
|
|
6
|
-
"names": ["import_signals_core", "import_echo_schema", "import_invariant", "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", "create", "
|
|
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 { type ReactiveObject, create } from '@dxos/echo-schema';\nimport { invariant } from '@dxos/invariant';\nimport { log } from '@dxos/log';\nimport { type MakeOptional, nonNullable, pick } from '@dxos/util';\n\nimport { type Relation, type Node, type NodeArg, type NodeFilter, isActionLike, actionGroupSymbol } from './node';\n\nconst graphSymbol = Symbol('graph');\ntype DeepWriteable<T> = { -readonly [K in keyof T]: DeepWriteable<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<T = any, U extends Record<string, any> = Record<string, any>> = {\n relation?: Relation;\n filter?: NodeFilter<T, U>;\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, ReactiveObject<NodeInternal>> = {};\n\n /**\n * @internal\n */\n readonly _edges: Record<string, ReactiveObject<{ 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] = create({ 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(nonNullable);\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<T = any, U extends Record<string, any> = Record<string, any>>(node: Node, options: NodesOptions<T, U> = {}) {\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\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, properties, type } = _node;\n if (data && 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] = create({ 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] = create({ inbound: [], outbound: [] });\n }\n if (!this._edges[target]) {\n this._edges[target] = create({ 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 create<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(nonNullable)\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 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<T = any, U extends Record<string, any> = Record<string, any>> = (\n node: Node<unknown, Record<string, any>>,\n connectedNode: Node,\n) => node is Node<T, U>;\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 = Readonly<\n Omit<Node<typeof actionGroupSymbol, Record<string, any>>, 'properties'> & {\n properties: Readonly<Record<string, any>>;\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 { type Signal, effect, signal } from '@preact/signals-core';\n\nimport { type UnsubscribeCallback } from '@dxos/async';\nimport { create } from '@dxos/echo-schema';\nimport { invariant } from '@dxos/invariant';\nimport { log } from '@dxos/log';\nimport { isNode, type MaybePromise, nonNullable } from '@dxos/util';\n\nimport { ACTION_GROUP_TYPE, ACTION_TYPE, Graph, type GraphParams } from './graph';\nimport { type Relation, type NodeArg, type Node, type ActionData, actionGroupSymbol } from './node';\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.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 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, resolver, connector, actions, actionGroups, ...rest } = extension;\n const getId = (key: string) => `${id}/${key}`;\n return [\n resolver ? { id: getId('resolver'), resolver } : undefined,\n connector ? { ...rest, id: getId('connector'), connector } : undefined,\n actionGroups\n ? ({\n ...rest,\n id: getId('actionGroups'),\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 type: ACTION_TYPE,\n relation: 'outbound',\n connector: ({ node }) => actions({ node })?.map((arg) => ({ ...arg, type: ACTION_TYPE })),\n } satisfies BuilderExtension)\n : undefined,\n ].filter(nonNullable);\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 = {\n id: string;\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\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 = create<Record<string, BuilderExtension>>({});\n private readonly _resolverSubscriptions = new Map<string, UnsubscribeCallback>();\n private readonly _connectorSubscriptions = new Map<string, UnsubscribeCallback>();\n private readonly _nodeChanged: Record<string, Signal<{}>> = {};\n private _graph: Graph;\n\n constructor(params: Pick<GraphParams, 'nodes' | 'edges'> = {}) {\n this._graph = new Graph({\n ...params,\n onInitialNode: (id) => this._onInitialNode(id),\n onInitialNodes: (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 */\n async initialize() {\n return Promise.all(Object.keys(this._graph._nodes).map((id) => this._onInitialNode(id)));\n }\n\n get graph() {\n return this._graph;\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 if (Array.isArray(extension)) {\n extension.forEach((ext) => this.addExtension(ext));\n return this;\n }\n\n this._dispatcher.state[extension.id] = [];\n this._extensions[extension.id] = extension;\n return this;\n }\n\n /**\n * Remove a node builder from the graph builder.\n */\n removeExtension(id: string): GraphBuilder {\n delete this._extensions[id];\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 async _onInitialNode(nodeId: string) {\n this._nodeChanged[nodeId] = this._nodeChanged[nodeId] ?? signal({});\n this._resolverSubscriptions.set(\n nodeId,\n effect(() => {\n for (const { id, resolver } of Object.values(this._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 if (node) {\n this.graph._addNodes([node]);\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 break;\n }\n }\n }),\n );\n }\n\n private async _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 for (const { id, connector, filter, type, relation = 'outbound' } of Object.values(this._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
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,0BAAyC;AAEzC,mBAAsC;AACtC,yBAA4C;AAC5C,uBAA0B;AAC1B,iBAAoB;AACpB,kBAAqD;AENrD,IAAAA,uBAA4C;AAG5C,IAAAC,sBAAuB;AACvB,IAAAC,oBAA0B;AAC1B,IAAAC,cAAoB;AACpB,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,SAASlC,EAAAA,CAAAA;AACtDkK,iBAAWvE;AAGX,WAAKlH,MAAM2H,aACT+D,QAAQpI,IAAI,CAACjB,YAAY;QAAED,QAAQrC,KAAKwB;QAAIc;MAAO,EAAA,GACnD,IAAA;AAEF,WAAKrC,MAAM6G,UAAUnG,KAAAA;AACrB,WAAKV,MAAMsH,UACT5G,MAAM4C,IAAI,CAAC,EAAE/B,GAAE,MACb+J,kBAAkB,aAAa;QAAElJ,QAAQrC,KAAKwB;QAAIc,QAAQd;MAAG,IAAI;QAAEa,QAAQb;QAAIc,QAAQtC,KAAKwB;MAAG,CAAA,CAAA;AAGnG,WAAKvB,MAAMuC,WACTxC,KAAKwB,IACL+J,eACA5K,MAAM4C,IAAI,CAAC,EAAE/B,GAAE,MAAOA,EAAAA,CAAAA;AAExBb,YAAMgB,QAAQ,CAAC6B,MAAAA;AACb,YAAI,KAAK4G,aAAa5G,EAAEhC,EAAE,GAAG;AAC3B,eAAK4I,aAAa5G,EAAEhC,EAAE,EAAEqI,QAAQ,CAAC;QACnC;MACF,CAAA;IACF,CAAA,CAAA;EAEJ;EAEA,MAAcvI,cAAc6C,QAAgB;AAC1C,SAAK8F,uBAAuBP,IAAIvF,MAAAA,IAAAA;AAChC,SAAKgG,wBAAwBT,IAAIvF,MAAAA,IAAAA;AACjC,SAAK8F,uBAAuB2B,OAAOzH,MAAAA;AACnC,SAAKgG,wBAAwByB,OAAOzH,MAAAA;EACtC;AACF;",
|
|
6
|
+
"names": ["import_signals_core", "import_echo_schema", "import_invariant", "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", "create", "_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", "nonNullable", "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", "createExtension", "extension", "resolver", "connector", "actionGroups", "rest", "getId", "arg", "Dispatcher", "stateIndex", "state", "cleanup", "BuilderInternal", "memoize", "fn", "dispatcher", "currentDispatcher", "currentExtension", "all", "toSignal", "subscribe", "get", "thisSignal", "signal", "value", "GraphBuilder", "_dispatcher", "_extensions", "_resolverSubscriptions", "Map", "_connectorSubscriptions", "_nodeChanged", "_graph", "initialize", "Promise", "addExtension", "Array", "isArray", "ext", "removeExtension", "destroy", "clear", "explore", "isNode", "yieldOrContinue", "flatMap", "set", "err", "catch", "error", "nodesRelation", "nodesType", "first", "previous", "removed", "delete"]
|
|
7
7
|
}
|
package/dist/lib/node/meta.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"inputs":{"packages/sdk/app-graph/src/node.ts":{"bytes":
|
|
1
|
+
{"inputs":{"packages/sdk/app-graph/src/node.ts":{"bytes":5675,"imports":[],"format":"esm"},"packages/sdk/app-graph/src/graph.ts":{"bytes":63106,"imports":[{"path":"@preact/signals-core","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/echo-schema","kind":"import-statement","external":true},{"path":"@dxos/invariant","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":46847,"imports":[{"path":"@preact/signals-core","kind":"import-statement","external":true},{"path":"@dxos/echo-schema","kind":"import-statement","external":true},{"path":"@dxos/invariant","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":58246},"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/echo-schema","kind":"import-statement","external":true},{"path":"@dxos/invariant","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/echo-schema","kind":"import-statement","external":true},{"path":"@dxos/invariant","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","getGraph","isAction","isActionGroup","isActionLike","isGraphNode","memoize","toSignal"],"entryPoint":"packages/sdk/app-graph/src/index.ts","inputs":{"packages/sdk/app-graph/src/graph.ts":{"bytesInOutput":15394},"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":9862}},"bytes":26176}}}
|
|
@@ -6,7 +6,7 @@ import { asyncTimeout, Trigger } from "@dxos/async";
|
|
|
6
6
|
import { create } from "@dxos/echo-schema";
|
|
7
7
|
import { invariant } from "@dxos/invariant";
|
|
8
8
|
import { log } from "@dxos/log";
|
|
9
|
-
import { nonNullable } from "@dxos/util";
|
|
9
|
+
import { nonNullable, pick } from "@dxos/util";
|
|
10
10
|
|
|
11
11
|
// packages/sdk/app-graph/src/node.ts
|
|
12
12
|
var isGraphNode = (data) => data && typeof data === "object" && "id" in data && "properties" in data && data.properties ? typeof data.properties === "object" && "data" in data : false;
|
|
@@ -54,31 +54,41 @@ var Graph = class _Graph {
|
|
|
54
54
|
[graphSymbol]: this
|
|
55
55
|
});
|
|
56
56
|
};
|
|
57
|
+
this._onInitialNode = onInitialNode;
|
|
58
|
+
this._onInitialNodes = onInitialNodes;
|
|
59
|
+
this._onRemoveNode = onRemoveNode;
|
|
57
60
|
this._nodes[ROOT_ID] = this._constructNode({
|
|
58
61
|
id: ROOT_ID,
|
|
59
62
|
type: ROOT_TYPE,
|
|
63
|
+
cacheable: [],
|
|
60
64
|
properties: {},
|
|
61
65
|
data: null
|
|
62
66
|
});
|
|
63
67
|
if (nodes) {
|
|
64
68
|
nodes.forEach((node) => {
|
|
69
|
+
const cacheable = Object.keys(node.properties ?? {});
|
|
65
70
|
if (node.type === ACTION_TYPE) {
|
|
66
71
|
this._addNode({
|
|
67
|
-
|
|
72
|
+
cacheable,
|
|
68
73
|
data: () => log.warn("Pickled action invocation", void 0, {
|
|
69
74
|
F: __dxlog_file,
|
|
70
|
-
L:
|
|
75
|
+
L: 113,
|
|
71
76
|
S: this,
|
|
72
77
|
C: (f, a) => f(...a)
|
|
73
|
-
})
|
|
78
|
+
}),
|
|
79
|
+
...node
|
|
74
80
|
});
|
|
75
81
|
} else if (node.type === ACTION_GROUP_TYPE) {
|
|
76
82
|
this._addNode({
|
|
77
|
-
|
|
78
|
-
data: actionGroupSymbol
|
|
83
|
+
cacheable,
|
|
84
|
+
data: actionGroupSymbol,
|
|
85
|
+
...node
|
|
79
86
|
});
|
|
80
87
|
} else {
|
|
81
|
-
this._addNode(
|
|
88
|
+
this._addNode({
|
|
89
|
+
cacheable,
|
|
90
|
+
...node
|
|
91
|
+
});
|
|
82
92
|
}
|
|
83
93
|
});
|
|
84
94
|
}
|
|
@@ -97,9 +107,6 @@ var Graph = class _Graph {
|
|
|
97
107
|
this._sortEdges(source, "outbound", edges2);
|
|
98
108
|
});
|
|
99
109
|
}
|
|
100
|
-
this._onInitialNode = onInitialNode;
|
|
101
|
-
this._onInitialNodes = onInitialNodes;
|
|
102
|
-
this._onRemoveNode = onRemoveNode;
|
|
103
110
|
}
|
|
104
111
|
static from(pickle, options = {}) {
|
|
105
112
|
const { nodes, edges } = JSON.parse(pickle);
|
|
@@ -142,7 +149,7 @@ var Graph = class _Graph {
|
|
|
142
149
|
const root = this.findNode(id);
|
|
143
150
|
invariant(root, `Node not found: ${id}`, {
|
|
144
151
|
F: __dxlog_file,
|
|
145
|
-
L:
|
|
152
|
+
L: 171,
|
|
146
153
|
S: this,
|
|
147
154
|
A: [
|
|
148
155
|
"root",
|
|
@@ -152,16 +159,17 @@ var Graph = class _Graph {
|
|
|
152
159
|
return toJSON(root);
|
|
153
160
|
}
|
|
154
161
|
pickle() {
|
|
155
|
-
const nodes = Object.values(this._nodes).map((node) => {
|
|
162
|
+
const nodes = Object.values(this._nodes).filter((node) => !!node.cacheable).map((node) => {
|
|
156
163
|
return {
|
|
157
164
|
id: node.id,
|
|
158
165
|
type: node.type,
|
|
159
|
-
properties: node.properties
|
|
166
|
+
properties: pick(node.properties, node.cacheable)
|
|
160
167
|
};
|
|
161
168
|
});
|
|
162
|
-
const
|
|
169
|
+
const cacheable = new Set(nodes.map((node) => node.id));
|
|
170
|
+
const edges = Object.fromEntries(Object.entries(this._edges).filter(([id]) => cacheable.has(id)).map(([id, { outbound }]) => [
|
|
163
171
|
id,
|
|
164
|
-
outbound
|
|
172
|
+
outbound.filter((nodeId) => cacheable.has(nodeId))
|
|
165
173
|
]).toSorted(([a], [b]) => a.localeCompare(b)));
|
|
166
174
|
return JSON.stringify({
|
|
167
175
|
nodes,
|
|
@@ -428,7 +436,7 @@ var Graph = class _Graph {
|
|
|
428
436
|
}
|
|
429
437
|
_removeNode(id, edges = false) {
|
|
430
438
|
untracked(() => {
|
|
431
|
-
const node = this.findNode(id);
|
|
439
|
+
const node = this.findNode(id, false);
|
|
432
440
|
if (!node) {
|
|
433
441
|
return;
|
|
434
442
|
}
|
|
@@ -754,6 +762,7 @@ var GraphBuilder = class _GraphBuilder {
|
|
|
754
762
|
}).map((arg) => ({
|
|
755
763
|
id: arg.id,
|
|
756
764
|
type: arg.type,
|
|
765
|
+
cacheable: arg.cacheable,
|
|
757
766
|
data: arg.data ?? null,
|
|
758
767
|
properties: arg.properties ?? {}
|
|
759
768
|
}));
|
|
@@ -786,13 +795,13 @@ var GraphBuilder = class _GraphBuilder {
|
|
|
786
795
|
extension: id
|
|
787
796
|
}, {
|
|
788
797
|
F: __dxlog_file2,
|
|
789
|
-
L:
|
|
798
|
+
L: 319,
|
|
790
799
|
S: this,
|
|
791
800
|
C: (f, a) => f(...a)
|
|
792
801
|
});
|
|
793
802
|
log2.error(`Previous error occurred in extension: ${id}`, void 0, {
|
|
794
803
|
F: __dxlog_file2,
|
|
795
|
-
L:
|
|
804
|
+
L: 320,
|
|
796
805
|
S: this,
|
|
797
806
|
C: (f, a) => f(...a)
|
|
798
807
|
});
|
|
@@ -807,6 +816,11 @@ var GraphBuilder = class _GraphBuilder {
|
|
|
807
816
|
this._nodeChanged[node.id].value = {};
|
|
808
817
|
}
|
|
809
818
|
break;
|
|
819
|
+
} else if (node === false) {
|
|
820
|
+
this.graph._removeNodes([
|
|
821
|
+
nodeId
|
|
822
|
+
]);
|
|
823
|
+
break;
|
|
810
824
|
}
|
|
811
825
|
}
|
|
812
826
|
}));
|
|
@@ -839,13 +853,13 @@ var GraphBuilder = class _GraphBuilder {
|
|
|
839
853
|
extension: id
|
|
840
854
|
}, {
|
|
841
855
|
F: __dxlog_file2,
|
|
842
|
-
L:
|
|
856
|
+
L: 377,
|
|
843
857
|
S: this,
|
|
844
858
|
C: (f, a) => f(...a)
|
|
845
859
|
});
|
|
846
860
|
log2.error(`Previous error occurred in extension: ${id}`, void 0, {
|
|
847
861
|
F: __dxlog_file2,
|
|
848
|
-
L:
|
|
862
|
+
L: 378,
|
|
849
863
|
S: this,
|
|
850
864
|
C: (f, a) => f(...a)
|
|
851
865
|
});
|