@dxos/app-graph 0.8.4-main.a4bbb77 → 0.8.4-main.abd8ff62ef
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/lib/browser/chunk-3T75MQOS.mjs +1480 -0
- package/dist/lib/browser/chunk-3T75MQOS.mjs.map +7 -0
- package/dist/lib/browser/index.mjs +27 -842
- package/dist/lib/browser/index.mjs.map +4 -4
- package/dist/lib/browser/meta.json +1 -1
- package/dist/lib/browser/testing/index.mjs +39 -0
- package/dist/lib/browser/testing/index.mjs.map +7 -0
- package/dist/lib/node-esm/chunk-UEXRLXMS.mjs +1481 -0
- package/dist/lib/node-esm/chunk-UEXRLXMS.mjs.map +7 -0
- package/dist/lib/node-esm/index.mjs +27 -843
- package/dist/lib/node-esm/index.mjs.map +4 -4
- package/dist/lib/node-esm/meta.json +1 -1
- package/dist/lib/node-esm/testing/index.mjs +40 -0
- package/dist/lib/node-esm/testing/index.mjs.map +7 -0
- package/dist/types/src/atoms.d.ts +8 -0
- package/dist/types/src/atoms.d.ts.map +1 -0
- package/dist/types/src/graph-builder.d.ts +113 -67
- package/dist/types/src/graph-builder.d.ts.map +1 -1
- package/dist/types/src/graph.d.ts +188 -222
- package/dist/types/src/graph.d.ts.map +1 -1
- package/dist/types/src/index.d.ts +7 -3
- package/dist/types/src/index.d.ts.map +1 -1
- package/dist/types/src/node-matcher.d.ts +244 -0
- package/dist/types/src/node-matcher.d.ts.map +1 -0
- package/dist/types/src/node-matcher.test.d.ts +2 -0
- package/dist/types/src/node-matcher.test.d.ts.map +1 -0
- package/dist/types/src/node.d.ts +50 -5
- package/dist/types/src/node.d.ts.map +1 -1
- package/dist/types/src/stories/EchoGraph.stories.d.ts.map +1 -1
- package/dist/types/src/testing/index.d.ts +2 -0
- package/dist/types/src/testing/index.d.ts.map +1 -0
- package/dist/types/src/testing/setup-graph-builder.d.ts +31 -0
- package/dist/types/src/testing/setup-graph-builder.d.ts.map +1 -0
- package/dist/types/src/util.d.ts +40 -0
- package/dist/types/src/util.d.ts.map +1 -0
- package/dist/types/tsconfig.tsbuildinfo +1 -1
- package/package.json +42 -38
- package/src/atoms.ts +25 -0
- package/src/graph-builder.test.ts +1154 -144
- package/src/graph-builder.ts +737 -293
- package/src/graph.test.ts +451 -123
- package/src/graph.ts +1054 -403
- package/src/index.ts +10 -3
- package/src/node-matcher.test.ts +301 -0
- package/src/node-matcher.ts +314 -0
- package/src/node.ts +82 -8
- package/src/stories/EchoGraph.stories.tsx +164 -126
- package/src/stories/Tree.tsx +1 -1
- package/src/testing/index.ts +5 -0
- package/src/testing/setup-graph-builder.ts +41 -0
- package/src/util.ts +101 -0
- package/dist/types/src/experimental/graph-projections.test.d.ts +0 -25
- package/dist/types/src/experimental/graph-projections.test.d.ts.map +0 -1
- package/dist/types/src/signals-integration.test.d.ts +0 -2
- package/dist/types/src/signals-integration.test.d.ts.map +0 -1
- package/dist/types/src/testing.d.ts +0 -5
- package/dist/types/src/testing.d.ts.map +0 -1
- package/src/experimental/graph-projections.test.ts +0 -56
- package/src/signals-integration.test.ts +0 -218
- package/src/testing.ts +0 -20
package/src/graph-builder.ts
CHANGED
|
@@ -2,221 +2,169 @@
|
|
|
2
2
|
// Copyright 2025 DXOS.org
|
|
3
3
|
//
|
|
4
4
|
|
|
5
|
-
import {
|
|
6
|
-
import
|
|
7
|
-
import
|
|
8
|
-
|
|
9
|
-
import
|
|
5
|
+
import { Atom, Registry } from '@effect-atom/atom-react';
|
|
6
|
+
import * as Array from 'effect/Array';
|
|
7
|
+
import type * as Context from 'effect/Context';
|
|
8
|
+
import * as Effect from 'effect/Effect';
|
|
9
|
+
import * as Function from 'effect/Function';
|
|
10
|
+
import * as Option from 'effect/Option';
|
|
11
|
+
import * as Pipeable from 'effect/Pipeable';
|
|
12
|
+
import * as Record from 'effect/Record';
|
|
13
|
+
import type * as Schema from 'effect/Schema';
|
|
14
|
+
import { scheduleTask, yieldOrContinue } from 'main-thread-scheduling';
|
|
15
|
+
|
|
16
|
+
import { type CleanupFn, type Trigger } from '@dxos/async';
|
|
17
|
+
import { type Entity, type Type } from '@dxos/echo';
|
|
10
18
|
import { log } from '@dxos/log';
|
|
11
|
-
import { type MaybePromise, type Position, byPosition, getDebugName,
|
|
19
|
+
import { type MaybePromise, type Position, byPosition, getDebugName, isNonNullable } from '@dxos/util';
|
|
20
|
+
|
|
21
|
+
import * as Graph from './graph';
|
|
22
|
+
import * as Node from './node';
|
|
23
|
+
import * as NodeMatcher from './node-matcher';
|
|
24
|
+
import {
|
|
25
|
+
getParentId,
|
|
26
|
+
nodeArgsUnchanged,
|
|
27
|
+
normalizeRelation,
|
|
28
|
+
primaryKey,
|
|
29
|
+
primaryParts,
|
|
30
|
+
qualifyId,
|
|
31
|
+
validateSegmentId,
|
|
32
|
+
} from './util';
|
|
12
33
|
|
|
13
|
-
|
|
14
|
-
|
|
34
|
+
//
|
|
35
|
+
// Extension Types
|
|
36
|
+
//
|
|
15
37
|
|
|
16
38
|
/**
|
|
17
39
|
* Graph builder extension for adding nodes to the graph based on a node id.
|
|
18
40
|
*/
|
|
19
|
-
export type ResolverExtension = (id: string) =>
|
|
41
|
+
export type ResolverExtension = (id: string) => Atom.Atom<Node.NodeArg<any> | null>;
|
|
20
42
|
|
|
21
43
|
/**
|
|
22
44
|
* Graph builder extension for adding nodes to the graph based on a connection to an existing node.
|
|
23
45
|
*
|
|
24
46
|
* @param params.node The existing node the returned nodes will be connected to.
|
|
25
47
|
*/
|
|
26
|
-
export type ConnectorExtension = (node:
|
|
48
|
+
export type ConnectorExtension = (node: Atom.Atom<Option.Option<Node.Node>>) => Atom.Atom<Node.NodeArg<any>[]>;
|
|
27
49
|
|
|
28
50
|
/**
|
|
29
51
|
* Constrained case of the connector extension for more easily adding actions to the graph.
|
|
30
52
|
*/
|
|
31
53
|
export type ActionsExtension = (
|
|
32
|
-
node:
|
|
33
|
-
) =>
|
|
54
|
+
node: Atom.Atom<Option.Option<Node.Node>>,
|
|
55
|
+
) => Atom.Atom<Omit<Node.NodeArg<Node.ActionData<any>>, 'type' | 'nodes' | 'edges'>[]>;
|
|
34
56
|
|
|
35
57
|
/**
|
|
36
58
|
* Constrained case of the connector extension for more easily adding action groups to the graph.
|
|
37
59
|
*/
|
|
38
60
|
export type ActionGroupsExtension = (
|
|
39
|
-
node:
|
|
40
|
-
) =>
|
|
61
|
+
node: Atom.Atom<Option.Option<Node.Node>>,
|
|
62
|
+
) => Atom.Atom<Omit<Node.NodeArg<typeof Node.actionGroupSymbol>, 'type' | 'data' | 'nodes' | 'edges'>[]>;
|
|
41
63
|
|
|
42
|
-
|
|
43
|
-
* A graph builder extension is used to add nodes to the graph.
|
|
44
|
-
*
|
|
45
|
-
* @param params.id The unique id of the extension.
|
|
46
|
-
* @param params.relation The relation the graph is being expanded from the existing node.
|
|
47
|
-
* @param params.position Affects the order the extensions are processed in.
|
|
48
|
-
* @param params.resolver A function to add nodes to the graph based on just the node id.
|
|
49
|
-
* @param params.connector A function to add nodes to the graph based on a connection to an existing node.
|
|
50
|
-
* @param params.actions A function to add actions to the graph based on a connection to an existing node.
|
|
51
|
-
* @param params.actionGroups A function to add action groups to the graph based on a connection to an existing node.
|
|
52
|
-
*/
|
|
53
|
-
export type CreateExtensionOptions = {
|
|
64
|
+
export type BuilderExtension = Readonly<{
|
|
54
65
|
id: string;
|
|
55
|
-
|
|
56
|
-
|
|
66
|
+
position: Position;
|
|
67
|
+
relation?: Node.RelationInput;
|
|
57
68
|
resolver?: ResolverExtension;
|
|
58
|
-
connector?:
|
|
59
|
-
|
|
60
|
-
actionGroups?: ActionGroupsExtension;
|
|
61
|
-
};
|
|
62
|
-
|
|
63
|
-
/**
|
|
64
|
-
* Create a graph builder extension.
|
|
65
|
-
*/
|
|
66
|
-
export const createExtension = (extension: CreateExtensionOptions): BuilderExtension[] => {
|
|
67
|
-
const {
|
|
68
|
-
id,
|
|
69
|
-
position = 'static',
|
|
70
|
-
relation = 'outbound',
|
|
71
|
-
resolver: _resolver,
|
|
72
|
-
connector: _connector,
|
|
73
|
-
actions: _actions,
|
|
74
|
-
actionGroups: _actionGroups,
|
|
75
|
-
} = extension;
|
|
76
|
-
const getId = (key: string) => `${id}/${key}`;
|
|
77
|
-
|
|
78
|
-
const resolver =
|
|
79
|
-
_resolver && Rx.family((id: string) => _resolver(id).pipe(Rx.withLabel(`graph-builder:_resolver:${id}`)));
|
|
80
|
-
|
|
81
|
-
const connector =
|
|
82
|
-
_connector &&
|
|
83
|
-
Rx.family((node: Rx.Rx<Option.Option<Node>>) =>
|
|
84
|
-
_connector(node).pipe(Rx.withLabel(`graph-builder:_connector:${id}`)),
|
|
85
|
-
);
|
|
86
|
-
|
|
87
|
-
const actionGroups =
|
|
88
|
-
_actionGroups &&
|
|
89
|
-
Rx.family((node: Rx.Rx<Option.Option<Node>>) =>
|
|
90
|
-
_actionGroups(node).pipe(Rx.withLabel(`graph-builder:_actionGroups:${id}`)),
|
|
91
|
-
);
|
|
69
|
+
connector?: (node: Atom.Atom<Option.Option<Node.Node>>) => Atom.Atom<Node.NodeArg<any>[]>;
|
|
70
|
+
}>;
|
|
92
71
|
|
|
93
|
-
|
|
94
|
-
_actions &&
|
|
95
|
-
Rx.family((node: Rx.Rx<Option.Option<Node>>) => _actions(node).pipe(Rx.withLabel(`graph-builder:_actions:${id}`)));
|
|
72
|
+
export type BuilderExtensions = BuilderExtension | BuilderExtension[] | BuilderExtensions[];
|
|
96
73
|
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
? ({
|
|
101
|
-
id: getId('connector'),
|
|
102
|
-
position,
|
|
103
|
-
relation,
|
|
104
|
-
connector: Rx.family((node) =>
|
|
105
|
-
Rx.make((get) => {
|
|
106
|
-
try {
|
|
107
|
-
return get(connector(node));
|
|
108
|
-
} catch {
|
|
109
|
-
log.warn('Error in connector', { id: getId('connector'), node });
|
|
110
|
-
return [];
|
|
111
|
-
}
|
|
112
|
-
}).pipe(Rx.withLabel(`graph-builder:connector:${id}`)),
|
|
113
|
-
),
|
|
114
|
-
} satisfies BuilderExtension)
|
|
115
|
-
: undefined,
|
|
116
|
-
actionGroups
|
|
117
|
-
? ({
|
|
118
|
-
id: getId('actionGroups'),
|
|
119
|
-
position,
|
|
120
|
-
relation: 'outbound',
|
|
121
|
-
connector: Rx.family((node) =>
|
|
122
|
-
Rx.make((get) => {
|
|
123
|
-
try {
|
|
124
|
-
return get(actionGroups(node)).map((arg) => ({
|
|
125
|
-
...arg,
|
|
126
|
-
data: actionGroupSymbol,
|
|
127
|
-
type: ACTION_GROUP_TYPE,
|
|
128
|
-
}));
|
|
129
|
-
} catch {
|
|
130
|
-
log.warn('Error in actionGroups', { id: getId('actionGroups'), node });
|
|
131
|
-
return [];
|
|
132
|
-
}
|
|
133
|
-
}).pipe(Rx.withLabel(`graph-builder:connector:actionGroups:${id}`)),
|
|
134
|
-
),
|
|
135
|
-
} satisfies BuilderExtension)
|
|
136
|
-
: undefined,
|
|
137
|
-
actions
|
|
138
|
-
? ({
|
|
139
|
-
id: getId('actions'),
|
|
140
|
-
position,
|
|
141
|
-
relation: 'outbound',
|
|
142
|
-
connector: Rx.family((node) =>
|
|
143
|
-
Rx.make((get) => {
|
|
144
|
-
try {
|
|
145
|
-
return get(actions(node)).map((arg) => ({ ...arg, type: ACTION_TYPE }));
|
|
146
|
-
} catch {
|
|
147
|
-
log.warn('Error in actions', { id: getId('actions'), node });
|
|
148
|
-
return [];
|
|
149
|
-
}
|
|
150
|
-
}).pipe(Rx.withLabel(`graph-builder:connector:actions:${id}`)),
|
|
151
|
-
),
|
|
152
|
-
} satisfies BuilderExtension)
|
|
153
|
-
: undefined,
|
|
154
|
-
].filter(isNonNullable);
|
|
155
|
-
};
|
|
74
|
+
//
|
|
75
|
+
// GraphBuilder Core
|
|
76
|
+
//
|
|
156
77
|
|
|
157
78
|
export type GraphBuilderTraverseOptions = {
|
|
158
|
-
visitor: (node: Node, path: string[]) => MaybePromise<boolean | void>;
|
|
79
|
+
visitor: (node: Node.Node, path: string[]) => MaybePromise<boolean | void>;
|
|
159
80
|
registry?: Registry.Registry;
|
|
160
81
|
source?: string;
|
|
161
|
-
relation
|
|
82
|
+
relation: Node.RelationInput | Node.RelationInput[];
|
|
162
83
|
};
|
|
163
84
|
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
connector?: (node: Rx.Rx<Option.Option<Node>>) => Rx.Rx<NodeArg<any>[]>;
|
|
170
|
-
}>;
|
|
171
|
-
|
|
172
|
-
export type BuilderExtensions = BuilderExtension | BuilderExtension[] | BuilderExtensions[];
|
|
85
|
+
/**
|
|
86
|
+
* Identifier denoting a GraphBuilder.
|
|
87
|
+
*/
|
|
88
|
+
export const GraphBuilderTypeId: unique symbol = Symbol.for('@dxos/app-graph/GraphBuilder');
|
|
89
|
+
export type GraphBuilderTypeId = typeof GraphBuilderTypeId;
|
|
173
90
|
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
91
|
+
/**
|
|
92
|
+
* GraphBuilder interface.
|
|
93
|
+
*/
|
|
94
|
+
export interface GraphBuilder extends Pipeable.Pipeable {
|
|
95
|
+
readonly [GraphBuilderTypeId]: GraphBuilderTypeId;
|
|
96
|
+
readonly graph: Graph.ExpandableGraph;
|
|
97
|
+
readonly extensions: Atom.Atom<Record<string, BuilderExtension>>;
|
|
98
|
+
}
|
|
181
99
|
|
|
182
100
|
/**
|
|
183
101
|
* The builder provides an extensible way to compose the construction of the graph.
|
|
102
|
+
* @internal
|
|
184
103
|
*/
|
|
185
104
|
// TODO(wittjosiah): Add api for setting subscription set and/or radius.
|
|
186
105
|
// Should unsubscribe from nodes that are not in the set/radius.
|
|
187
106
|
// Should track LRU nodes that are not in the set/radius and remove them beyond a certain threshold.
|
|
188
|
-
|
|
107
|
+
class GraphBuilderImpl implements GraphBuilder {
|
|
108
|
+
readonly [GraphBuilderTypeId]: GraphBuilderTypeId = GraphBuilderTypeId;
|
|
109
|
+
|
|
110
|
+
pipe() {
|
|
111
|
+
// eslint-disable-next-line prefer-rest-params
|
|
112
|
+
return Pipeable.pipeArguments(this, arguments);
|
|
113
|
+
}
|
|
114
|
+
|
|
189
115
|
// TODO(wittjosiah): Use Context.
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
116
|
+
/** Active subscriptions keyed by composite ID, cleaned up on node removal. */
|
|
117
|
+
readonly _subscriptions = new Map<string, CleanupFn>();
|
|
118
|
+
/** Connector updates pending flush, keyed by connector key. */
|
|
119
|
+
readonly _dirtyConnectors = new Map<
|
|
120
|
+
string,
|
|
121
|
+
{
|
|
122
|
+
nodes: Node.NodeArg<any>[];
|
|
123
|
+
previous: string[];
|
|
124
|
+
}
|
|
125
|
+
>();
|
|
126
|
+
/** Last-flushed node IDs per connector key, used for edge removal on update. */
|
|
127
|
+
readonly _connectorPrevious = new Map<string, string[]>();
|
|
128
|
+
/** All inline-descendant IDs per connector key, used to remove stale inline nodes on update. */
|
|
129
|
+
readonly _connectorPreviousInlineIds = new Map<string, string[]>();
|
|
130
|
+
/** Last-flushed node args per connector key, used for change detection. */
|
|
131
|
+
readonly _connectorPreviousArgs = new Map<string, Node.NodeArg<any>[]>();
|
|
132
|
+
/** Whether a dirty-flush task is already scheduled. */
|
|
133
|
+
_flushScheduled = false;
|
|
134
|
+
/** Resolves when the current flush completes. */
|
|
135
|
+
_flushPromise: Promise<void> = Promise.resolve();
|
|
136
|
+
/** Registered builder extensions keyed by extension ID. */
|
|
137
|
+
readonly _extensions = Atom.make(Record.empty<string, BuilderExtension>()).pipe(
|
|
138
|
+
Atom.keepAlive,
|
|
139
|
+
Atom.withLabel('graph-builder:extensions'),
|
|
194
140
|
);
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
141
|
+
/** Triggers signalling that a node's resolver has fired at least once. */
|
|
142
|
+
readonly _initialized: Record<string, Trigger> = {};
|
|
143
|
+
/** Shared atom registry for reactive subscriptions. */
|
|
144
|
+
readonly _registry: Registry.Registry;
|
|
145
|
+
/** Backing graph with internal accessors for node atoms and construction. */
|
|
146
|
+
readonly _graph: Graph.Graph & {
|
|
147
|
+
_node: (id: string) => Atom.Writable<Option.Option<Node.Node>>;
|
|
148
|
+
_constructNode: (node: Node.NodeArg<any>) => Option.Option<Node.Node>;
|
|
149
|
+
};
|
|
150
|
+
|
|
151
|
+
constructor({ registry, ...params }: Pick<Graph.GraphProps, 'registry' | 'nodes' | 'edges'> = {}) {
|
|
200
152
|
this._registry = registry ?? Registry.make();
|
|
201
|
-
|
|
153
|
+
const graph = Graph.make({
|
|
202
154
|
...params,
|
|
203
155
|
registry: this._registry,
|
|
204
156
|
onExpand: (id, relation) => this._onExpand(id, relation),
|
|
205
157
|
onInitialize: (id) => this._onInitialize(id),
|
|
206
158
|
onRemoveNode: (id) => this._onRemoveNode(id),
|
|
207
159
|
});
|
|
160
|
+
// Access internal methods via type assertion since GraphBuilder needs them
|
|
161
|
+
this._graph = graph as Graph.Graph & {
|
|
162
|
+
_node: (id: string) => Atom.Writable<Option.Option<Node.Node>>;
|
|
163
|
+
_constructNode: (node: Node.NodeArg<any>) => Option.Option<Node.Node>;
|
|
164
|
+
};
|
|
208
165
|
}
|
|
209
166
|
|
|
210
|
-
|
|
211
|
-
if (!pickle) {
|
|
212
|
-
return new GraphBuilder({ registry });
|
|
213
|
-
}
|
|
214
|
-
|
|
215
|
-
const { nodes, edges } = JSON.parse(pickle);
|
|
216
|
-
return new GraphBuilder({ nodes, edges, registry });
|
|
217
|
-
}
|
|
218
|
-
|
|
219
|
-
get graph(): ExpandableGraph {
|
|
167
|
+
get graph(): Graph.ExpandableGraph {
|
|
220
168
|
return this._graph;
|
|
221
169
|
}
|
|
222
170
|
|
|
@@ -224,72 +172,65 @@ export class GraphBuilder {
|
|
|
224
172
|
return this._extensions;
|
|
225
173
|
}
|
|
226
174
|
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
const
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
{ registry = Registry.make(), source = ROOT_ID, relation = 'outbound', visitor }: GraphBuilderTraverseOptions,
|
|
246
|
-
path: string[] = [],
|
|
247
|
-
): Promise<void> {
|
|
248
|
-
// Break cycles.
|
|
249
|
-
if (path.includes(source)) {
|
|
250
|
-
return;
|
|
251
|
-
}
|
|
252
|
-
|
|
253
|
-
// TODO(wittjosiah): This is a workaround for esm not working in the test runner.
|
|
254
|
-
// Switching to vitest is blocked by having node esm versions of echo-schema & echo-signals.
|
|
255
|
-
if (!isNode()) {
|
|
256
|
-
const { yieldOrContinue } = await import('main-thread-scheduling');
|
|
257
|
-
await yieldOrContinue('idle');
|
|
258
|
-
}
|
|
259
|
-
|
|
260
|
-
const node = registry.get(this._graph.nodeOrThrow(source));
|
|
261
|
-
const shouldContinue = await visitor(node, [...path, node.id]);
|
|
262
|
-
if (shouldContinue === false) {
|
|
263
|
-
return;
|
|
264
|
-
}
|
|
265
|
-
|
|
266
|
-
const nodes = Object.values(this._registry.get(this._extensions))
|
|
267
|
-
.filter((extension) => relation === (extension.relation ?? 'outbound'))
|
|
268
|
-
.map((extension) => extension.connector)
|
|
269
|
-
.filter(isNonNullable)
|
|
270
|
-
.flatMap((connector) => registry.get(connector(this._graph.node(source))));
|
|
271
|
-
|
|
272
|
-
await Promise.all(
|
|
273
|
-
nodes.map((nodeArg) => {
|
|
274
|
-
registry.set(this._graph._node(nodeArg.id), this._graph._constructNode(nodeArg));
|
|
275
|
-
return this.explore({ registry, source: nodeArg.id, relation, visitor }, [...path, node.id]);
|
|
276
|
-
}),
|
|
175
|
+
/** Apply a set of node changes for a single connector key. */
|
|
176
|
+
private _applyConnectorUpdate(key: string, nodes: Node.NodeArg<any>[], previous: string[]): void {
|
|
177
|
+
const { id, relation } = relationFromConnectorKey(key);
|
|
178
|
+
const ids = nodes.map((node) => node.id);
|
|
179
|
+
const removed = previous.filter((pid) => !ids.includes(pid));
|
|
180
|
+
this._connectorPrevious.set(key, ids);
|
|
181
|
+
this._connectorPreviousArgs.set(key, nodes);
|
|
182
|
+
|
|
183
|
+
const currentInlineIds = collectAllInlineIds(nodes);
|
|
184
|
+
const previousInlineIds = this._connectorPreviousInlineIds.get(key) ?? [];
|
|
185
|
+
const staleInlineIds = previousInlineIds.filter((pid) => !currentInlineIds.includes(pid));
|
|
186
|
+
this._connectorPreviousInlineIds.set(key, currentInlineIds);
|
|
187
|
+
|
|
188
|
+
Graph.removeNodes(this._graph, staleInlineIds, true);
|
|
189
|
+
Graph.removeEdges(
|
|
190
|
+
this._graph,
|
|
191
|
+
removed.map((target) => ({ source: id, target, relation })),
|
|
192
|
+
true,
|
|
277
193
|
);
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
194
|
+
Graph.addNodes(this._graph, nodes);
|
|
195
|
+
Graph.addEdges(
|
|
196
|
+
this._graph,
|
|
197
|
+
nodes.map((node) => ({ source: id, target: node.id, relation })),
|
|
198
|
+
);
|
|
199
|
+
if (ids.length > 0) {
|
|
200
|
+
const sortedIds = [...nodes]
|
|
201
|
+
.sort((a, b) =>
|
|
202
|
+
byPosition(a.properties ?? ({} as { position?: Position }), b.properties ?? ({} as { position?: Position })),
|
|
203
|
+
)
|
|
204
|
+
.map((n) => n.id);
|
|
205
|
+
Graph.sortEdges(this._graph, id, relation, sortedIds);
|
|
282
206
|
}
|
|
283
207
|
}
|
|
284
208
|
|
|
285
|
-
|
|
286
|
-
this.
|
|
287
|
-
|
|
209
|
+
private _scheduleDirtyFlush(): void {
|
|
210
|
+
if (!this._flushScheduled) {
|
|
211
|
+
this._flushScheduled = true;
|
|
212
|
+
this._flushPromise = scheduleTask(
|
|
213
|
+
() => {
|
|
214
|
+
this._flushScheduled = false;
|
|
215
|
+
while (this._dirtyConnectors.size > 0) {
|
|
216
|
+
const entries = [...this._dirtyConnectors.entries()];
|
|
217
|
+
this._dirtyConnectors.clear();
|
|
218
|
+
|
|
219
|
+
Atom.batch(() => {
|
|
220
|
+
for (const [key, { nodes, previous }] of entries) {
|
|
221
|
+
this._applyConnectorUpdate(key, nodes, previous);
|
|
222
|
+
}
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
},
|
|
226
|
+
{ strategy: 'smooth' },
|
|
227
|
+
);
|
|
228
|
+
}
|
|
288
229
|
}
|
|
289
230
|
|
|
290
|
-
private readonly _resolvers =
|
|
291
|
-
return
|
|
292
|
-
return pipe(
|
|
231
|
+
private readonly _resolvers = Atom.family<string, Atom.Atom<Option.Option<Node.NodeArg<any>>>>((id) => {
|
|
232
|
+
return Atom.make((get) => {
|
|
233
|
+
return Function.pipe(
|
|
293
234
|
get(this._extensions),
|
|
294
235
|
Record.values,
|
|
295
236
|
Array.sortBy(byPosition),
|
|
@@ -302,72 +243,74 @@ export class GraphBuilder {
|
|
|
302
243
|
});
|
|
303
244
|
});
|
|
304
245
|
|
|
305
|
-
private readonly _connectors =
|
|
306
|
-
return
|
|
307
|
-
const
|
|
246
|
+
private readonly _connectors = Atom.family<string, Atom.Atom<Node.NodeArg<any>[]>>((key) => {
|
|
247
|
+
return Atom.make((get) => {
|
|
248
|
+
const { id, relation } = relationFromConnectorKey(key);
|
|
308
249
|
const node = this._graph.node(id);
|
|
309
250
|
|
|
310
|
-
|
|
251
|
+
const sourceNode = Option.getOrElse(get(node), () => undefined);
|
|
252
|
+
if (!sourceNode) {
|
|
253
|
+
return [];
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
const extensions = Function.pipe(
|
|
311
257
|
get(this._extensions),
|
|
312
258
|
Record.values,
|
|
313
|
-
// TODO(wittjosiah): Sort on write rather than read.
|
|
314
259
|
Array.sortBy(byPosition),
|
|
315
|
-
Array.filter(
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
260
|
+
Array.filter(
|
|
261
|
+
(ext): ext is BuilderExtension & { connector: NonNullable<BuilderExtension['connector']> } =>
|
|
262
|
+
Graph.relationKey(ext.relation ?? 'child') === Graph.relationKey(relation) && ext.connector != null,
|
|
263
|
+
),
|
|
319
264
|
);
|
|
320
|
-
|
|
265
|
+
|
|
266
|
+
const nodes: Node.NodeArg<any>[] = [];
|
|
267
|
+
for (const ext of extensions) {
|
|
268
|
+
const result = get(ext.connector(node));
|
|
269
|
+
nodes.push(...result);
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
return nodes;
|
|
273
|
+
}).pipe(Atom.withLabel(`graph-builder:connectors:${key}`));
|
|
321
274
|
});
|
|
322
275
|
|
|
323
|
-
private _onExpand(id: string, relation: Relation): void {
|
|
276
|
+
private _onExpand(id: string, relation: Node.Relation): void {
|
|
324
277
|
log('onExpand', { id, relation, registry: getDebugName(this._registry) });
|
|
325
|
-
|
|
278
|
+
this._expandRelation(id, relation);
|
|
279
|
+
|
|
280
|
+
// TODO(wittjosiah): Remove. This is for backwards compatibility.
|
|
281
|
+
if (relation.kind === 'child' && relation.direction === 'outbound') {
|
|
282
|
+
Graph.expand(this._graph, id, 'action');
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
private _expandRelation(id: string, relation: Node.RelationInput): void {
|
|
287
|
+
const key = connectorKey(id, relation);
|
|
288
|
+
const connectors = this._connectors(key);
|
|
326
289
|
|
|
327
|
-
let previous: string[] = [];
|
|
328
290
|
const cancel = this._registry.subscribe(
|
|
329
291
|
connectors,
|
|
330
|
-
(
|
|
292
|
+
(rawNodes) => {
|
|
293
|
+
const nodes = qualifyNodeArgs(id)(rawNodes);
|
|
294
|
+
const previous = this._connectorPrevious.get(key) ?? [];
|
|
331
295
|
const ids = nodes.map((n) => n.id);
|
|
332
|
-
|
|
333
|
-
previous
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
this._graph.removeEdges(
|
|
339
|
-
removed.map((target) => ({ source: id, target })),
|
|
340
|
-
true,
|
|
341
|
-
);
|
|
342
|
-
this._graph.addNodes(nodes);
|
|
343
|
-
this._graph.addEdges(
|
|
344
|
-
nodes.map((node) =>
|
|
345
|
-
relation === 'outbound' ? { source: id, target: node.id } : { source: node.id, target: id },
|
|
346
|
-
),
|
|
347
|
-
);
|
|
348
|
-
this._graph.sortEdges(
|
|
349
|
-
id,
|
|
350
|
-
relation,
|
|
351
|
-
nodes.map(({ id }) => id),
|
|
352
|
-
);
|
|
353
|
-
});
|
|
354
|
-
};
|
|
355
|
-
|
|
356
|
-
// TODO(wittjosiah): Remove `requestAnimationFrame` once we have a better solution.
|
|
357
|
-
// This is a workaround to avoid a race condition where the graph is updated during React render.
|
|
358
|
-
if (typeof requestAnimationFrame === 'function') {
|
|
359
|
-
requestAnimationFrame(update);
|
|
360
|
-
} else {
|
|
361
|
-
update();
|
|
296
|
+
|
|
297
|
+
if (ids.length === previous.length && ids.every((nodeId, idx) => nodeId === previous[idx])) {
|
|
298
|
+
const prevArgs = this._connectorPreviousArgs.get(key);
|
|
299
|
+
if (prevArgs && nodeArgsUnchanged(prevArgs, nodes)) {
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
362
302
|
}
|
|
303
|
+
|
|
304
|
+
log('update', { id, relation, ids });
|
|
305
|
+
this._dirtyConnectors.set(key, { nodes, previous });
|
|
306
|
+
this._scheduleDirtyFlush();
|
|
363
307
|
},
|
|
364
308
|
{ immediate: true },
|
|
365
309
|
);
|
|
366
310
|
|
|
367
|
-
this._subscriptions.set(id, cancel);
|
|
311
|
+
this._subscriptions.set(subscriptionKey(id, 'expand', key), cancel);
|
|
368
312
|
}
|
|
369
313
|
|
|
370
|
-
// TODO(wittjosiah): If the same node is added by a connector, the resolver should probably cancel itself?
|
|
371
314
|
private async _onInitialize(id: string) {
|
|
372
315
|
log('onInitialize', { id });
|
|
373
316
|
const resolver = this._resolvers(id);
|
|
@@ -376,59 +319,560 @@ export class GraphBuilder {
|
|
|
376
319
|
resolver,
|
|
377
320
|
(node) => {
|
|
378
321
|
const trigger = this._initialized[id];
|
|
322
|
+
const connectorOwned = [...this._connectorPrevious.values()].some((ids) => ids.includes(id));
|
|
379
323
|
Option.match(node, {
|
|
380
324
|
onSome: (node) => {
|
|
381
|
-
|
|
325
|
+
if (!connectorOwned) {
|
|
326
|
+
Graph.addNodes(this._graph, [node]);
|
|
327
|
+
// Connect resolved node to its parent via a child edge.
|
|
328
|
+
const parentId = getParentId(id);
|
|
329
|
+
if (parentId) {
|
|
330
|
+
Graph.addEdges(this._graph, [{ source: parentId, target: id, relation: 'child' }]);
|
|
331
|
+
}
|
|
332
|
+
}
|
|
382
333
|
trigger?.wake();
|
|
383
334
|
},
|
|
384
335
|
onNone: () => {
|
|
385
336
|
trigger?.wake();
|
|
386
|
-
|
|
337
|
+
if (!connectorOwned) {
|
|
338
|
+
Graph.removeNodes(this._graph, [id]);
|
|
339
|
+
}
|
|
387
340
|
},
|
|
388
341
|
});
|
|
389
342
|
},
|
|
390
343
|
{ immediate: true },
|
|
391
344
|
);
|
|
392
345
|
|
|
393
|
-
this._subscriptions.set(id, cancel);
|
|
346
|
+
this._subscriptions.set(subscriptionKey(id, 'init'), cancel);
|
|
394
347
|
}
|
|
395
348
|
|
|
396
349
|
private _onRemoveNode(id: string): void {
|
|
397
|
-
this._subscriptions
|
|
398
|
-
|
|
350
|
+
for (const [key, cleanup] of this._subscriptions) {
|
|
351
|
+
if (primaryParts(key)[0] === id) {
|
|
352
|
+
cleanup();
|
|
353
|
+
this._subscriptions.delete(key);
|
|
354
|
+
}
|
|
355
|
+
}
|
|
399
356
|
}
|
|
400
357
|
}
|
|
401
358
|
|
|
402
359
|
/**
|
|
403
|
-
* Creates
|
|
404
|
-
* Will return a new rx instance each time.
|
|
360
|
+
* Creates a new GraphBuilder instance.
|
|
405
361
|
*/
|
|
406
|
-
export const
|
|
407
|
-
return
|
|
408
|
-
|
|
409
|
-
get.setSelf(cb());
|
|
410
|
-
});
|
|
362
|
+
export const make = (params?: Pick<Graph.GraphProps, 'registry' | 'nodes' | 'edges'>): GraphBuilder => {
|
|
363
|
+
return new GraphBuilderImpl(params);
|
|
364
|
+
};
|
|
411
365
|
|
|
412
|
-
|
|
366
|
+
/**
|
|
367
|
+
* Creates a GraphBuilder from a serialized pickle string.
|
|
368
|
+
*/
|
|
369
|
+
export const from = (pickle?: string, registry?: Registry.Registry): GraphBuilder => {
|
|
370
|
+
if (!pickle) {
|
|
371
|
+
return make({ registry });
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
const { nodes, edges } = JSON.parse(pickle);
|
|
375
|
+
return make({ nodes, edges, registry });
|
|
376
|
+
};
|
|
413
377
|
|
|
414
|
-
|
|
378
|
+
/**
|
|
379
|
+
* Implementation helper for addExtension.
|
|
380
|
+
*/
|
|
381
|
+
const addExtensionImpl = (builder: GraphBuilder, extensions: BuilderExtensions): GraphBuilder => {
|
|
382
|
+
const internal = builder as GraphBuilderImpl;
|
|
383
|
+
flattenExtensions(extensions).forEach((extension) => {
|
|
384
|
+
const extensions = internal._registry.get(internal._extensions);
|
|
385
|
+
internal._registry.set(internal._extensions, Record.set(extensions, extension.id, extension));
|
|
415
386
|
});
|
|
387
|
+
return builder;
|
|
416
388
|
};
|
|
417
389
|
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
390
|
+
/**
|
|
391
|
+
* Add extensions to the graph builder.
|
|
392
|
+
*/
|
|
393
|
+
export function addExtension(builder: GraphBuilder, extensions: BuilderExtensions): GraphBuilder;
|
|
394
|
+
export function addExtension(extensions: BuilderExtensions): (builder: GraphBuilder) => GraphBuilder;
|
|
395
|
+
export function addExtension(
|
|
396
|
+
builderOrExtensions: GraphBuilder | BuilderExtensions,
|
|
397
|
+
extensions?: BuilderExtensions,
|
|
398
|
+
): GraphBuilder | ((builder: GraphBuilder) => GraphBuilder) {
|
|
399
|
+
if (extensions === undefined) {
|
|
400
|
+
// Curried: addExtension(extensions)
|
|
401
|
+
const extensions = builderOrExtensions as BuilderExtensions;
|
|
402
|
+
return (builder: GraphBuilder) => addExtensionImpl(builder, extensions);
|
|
403
|
+
} else {
|
|
404
|
+
// Direct: addExtension(builder, extensions)
|
|
405
|
+
const builder = builderOrExtensions as GraphBuilder;
|
|
406
|
+
return addExtensionImpl(builder, extensions);
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
/**
|
|
411
|
+
* Implementation helper for removeExtension.
|
|
412
|
+
*/
|
|
413
|
+
const removeExtensionImpl = (builder: GraphBuilder, id: string): GraphBuilder => {
|
|
414
|
+
const internal = builder as GraphBuilderImpl;
|
|
415
|
+
const extensions = internal._registry.get(internal._extensions);
|
|
416
|
+
internal._registry.set(internal._extensions, Record.remove(extensions, id));
|
|
417
|
+
return builder;
|
|
418
|
+
};
|
|
419
|
+
|
|
420
|
+
/**
|
|
421
|
+
* Remove an extension from the graph builder.
|
|
422
|
+
*/
|
|
423
|
+
export function removeExtension(builder: GraphBuilder, id: string): GraphBuilder;
|
|
424
|
+
export function removeExtension(id: string): (builder: GraphBuilder) => GraphBuilder;
|
|
425
|
+
export function removeExtension(
|
|
426
|
+
builderOrId: GraphBuilder | string,
|
|
427
|
+
id?: string,
|
|
428
|
+
): GraphBuilder | ((builder: GraphBuilder) => GraphBuilder) {
|
|
429
|
+
if (typeof builderOrId === 'string') {
|
|
430
|
+
// Curried: removeExtension(id)
|
|
431
|
+
const id = builderOrId;
|
|
432
|
+
return (builder: GraphBuilder) => removeExtensionImpl(builder, id);
|
|
433
|
+
} else {
|
|
434
|
+
// Direct: removeExtension(builder, id)
|
|
435
|
+
const builder = builderOrId;
|
|
436
|
+
return removeExtensionImpl(builder, id!);
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
/**
|
|
441
|
+
* Implementation helper for explore.
|
|
442
|
+
*/
|
|
443
|
+
const exploreImpl = async (
|
|
444
|
+
builder: GraphBuilder,
|
|
445
|
+
options: GraphBuilderTraverseOptions,
|
|
446
|
+
path: string[] = [],
|
|
447
|
+
): Promise<void> => {
|
|
448
|
+
const internal = builder as GraphBuilderImpl;
|
|
449
|
+
const { registry = Registry.make(), source = Node.RootId, relation, visitor } = options;
|
|
450
|
+
// Break cycles.
|
|
451
|
+
if (path.includes(source)) {
|
|
452
|
+
return;
|
|
453
|
+
}
|
|
421
454
|
|
|
422
|
-
|
|
455
|
+
await yieldOrContinue('idle');
|
|
423
456
|
|
|
424
|
-
|
|
457
|
+
const node = registry.get(internal._graph.nodeOrThrow(source));
|
|
458
|
+
const shouldContinue = await visitor(node, [...path, node.id]);
|
|
459
|
+
if (shouldContinue === false) {
|
|
460
|
+
return;
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
const nodes = Function.pipe(
|
|
464
|
+
internal._registry.get(internal._extensions),
|
|
465
|
+
Record.values,
|
|
466
|
+
Array.map((extension) => extension.connector),
|
|
467
|
+
Array.filter(isNonNullable),
|
|
468
|
+
Array.flatMap((connector) => registry.get(connector(internal._graph.node(source)))),
|
|
469
|
+
qualifyNodeArgs(source),
|
|
470
|
+
);
|
|
471
|
+
|
|
472
|
+
await Promise.all(
|
|
473
|
+
nodes.map((nodeArg) => {
|
|
474
|
+
registry.set(internal._graph._node(nodeArg.id), internal._graph._constructNode(nodeArg));
|
|
475
|
+
return exploreImpl(builder, { registry, source: nodeArg.id, relation, visitor }, [...path, node.id]);
|
|
476
|
+
}),
|
|
477
|
+
);
|
|
478
|
+
|
|
479
|
+
if (registry !== internal._registry) {
|
|
480
|
+
registry.reset();
|
|
481
|
+
registry.dispose();
|
|
482
|
+
}
|
|
483
|
+
};
|
|
484
|
+
|
|
485
|
+
/**
|
|
486
|
+
* Explore the graph by traversing it with the given options.
|
|
487
|
+
*/
|
|
488
|
+
export function explore(builder: GraphBuilder, options: GraphBuilderTraverseOptions, path?: string[]): Promise<void>;
|
|
489
|
+
export function explore(
|
|
490
|
+
options: GraphBuilderTraverseOptions,
|
|
491
|
+
path?: string[],
|
|
492
|
+
): (builder: GraphBuilder) => Promise<void>;
|
|
493
|
+
export function explore(
|
|
494
|
+
builderOrOptions: GraphBuilder | GraphBuilderTraverseOptions,
|
|
495
|
+
optionsOrPath?: GraphBuilderTraverseOptions | string[],
|
|
496
|
+
path?: string[],
|
|
497
|
+
): Promise<void> | ((builder: GraphBuilder) => Promise<void>) {
|
|
498
|
+
if (typeof builderOrOptions === 'object' && 'visitor' in builderOrOptions) {
|
|
499
|
+
// Curried: explore(options, path?)
|
|
500
|
+
const options = builderOrOptions as GraphBuilderTraverseOptions;
|
|
501
|
+
const path = Array.isArray(optionsOrPath) ? optionsOrPath : undefined;
|
|
502
|
+
return (builder: GraphBuilder) => exploreImpl(builder, options, path);
|
|
503
|
+
} else {
|
|
504
|
+
// Direct: explore(builder, options, path?)
|
|
505
|
+
const builder = builderOrOptions as GraphBuilder;
|
|
506
|
+
const options = optionsOrPath as GraphBuilderTraverseOptions;
|
|
507
|
+
const pathArg = path ?? (Array.isArray(optionsOrPath) ? optionsOrPath : undefined);
|
|
508
|
+
return exploreImpl(builder, options, pathArg);
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
/**
|
|
513
|
+
* Implementation helper for destroy.
|
|
514
|
+
*/
|
|
515
|
+
const destroyImpl = (builder: GraphBuilder): void => {
|
|
516
|
+
const internal = builder as GraphBuilderImpl;
|
|
517
|
+
internal._subscriptions.forEach((unsubscribe) => unsubscribe());
|
|
518
|
+
internal._subscriptions.clear();
|
|
519
|
+
};
|
|
520
|
+
|
|
521
|
+
/**
|
|
522
|
+
* Destroy the graph builder and clean up resources.
|
|
523
|
+
*/
|
|
524
|
+
export function destroy(builder: GraphBuilder): void;
|
|
525
|
+
export function destroy(): (builder: GraphBuilder) => void;
|
|
526
|
+
export function destroy(builder?: GraphBuilder): void | ((builder: GraphBuilder) => void) {
|
|
527
|
+
if (builder === undefined) {
|
|
528
|
+
// Curried: destroy()
|
|
529
|
+
return (builder: GraphBuilder) => destroyImpl(builder);
|
|
530
|
+
} else {
|
|
531
|
+
// Direct: destroy(builder)
|
|
532
|
+
return destroyImpl(builder);
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
/**
|
|
537
|
+
* Wait for all pending connector updates to be flushed.
|
|
538
|
+
*/
|
|
539
|
+
export const flush = (builder: GraphBuilder): Promise<void> => {
|
|
540
|
+
return (builder as GraphBuilderImpl)._flushPromise;
|
|
541
|
+
};
|
|
542
|
+
|
|
543
|
+
//
|
|
544
|
+
// Extension Creation
|
|
545
|
+
//
|
|
546
|
+
|
|
547
|
+
/**
|
|
548
|
+
* A graph builder extension is used to add nodes to the graph.
|
|
549
|
+
*
|
|
550
|
+
* @param params.id The unique id of the extension.
|
|
551
|
+
* @param params.relation The relation the graph is being expanded from the existing node.
|
|
552
|
+
* @param params.position Affects the order the extensions are processed in.
|
|
553
|
+
* @param params.resolver A function to add nodes to the graph based on just the node id.
|
|
554
|
+
* @param params.connector A function to add nodes to the graph based on a connection to an existing node.
|
|
555
|
+
* @param params.actions A function to add actions to the graph based on a connection to an existing node.
|
|
556
|
+
* @param params.actionGroups A function to add action groups to the graph based on a connection to an existing node.
|
|
557
|
+
*/
|
|
558
|
+
export type CreateExtensionRawOptions = {
|
|
559
|
+
id: string;
|
|
560
|
+
relation?: Node.RelationInput;
|
|
561
|
+
position?: Position;
|
|
562
|
+
resolver?: ResolverExtension;
|
|
563
|
+
connector?: ConnectorExtension;
|
|
564
|
+
actions?: ActionsExtension;
|
|
565
|
+
actionGroups?: ActionGroupsExtension;
|
|
566
|
+
};
|
|
567
|
+
|
|
568
|
+
/**
|
|
569
|
+
* Create a graph builder extension (low-level API that works directly with Atoms).
|
|
570
|
+
*/
|
|
571
|
+
export const createExtensionRaw = (extension: CreateExtensionRawOptions): BuilderExtension[] => {
|
|
572
|
+
const {
|
|
573
|
+
id,
|
|
574
|
+
position = 'static',
|
|
575
|
+
relation = 'child',
|
|
576
|
+
resolver: _resolver,
|
|
577
|
+
connector: _connector,
|
|
578
|
+
actions: _actions,
|
|
579
|
+
actionGroups: _actionGroups,
|
|
580
|
+
} = extension;
|
|
581
|
+
const normalizedRelation = normalizeRelation(relation);
|
|
582
|
+
const getId = (key: string) => `${id}/${key}`;
|
|
583
|
+
|
|
584
|
+
const resolver =
|
|
585
|
+
_resolver && Atom.family((id: string) => _resolver(id).pipe(Atom.withLabel(`graph-builder:_resolver:${id}`)));
|
|
586
|
+
|
|
587
|
+
const connector =
|
|
588
|
+
_connector &&
|
|
589
|
+
Atom.family((node: Atom.Atom<Option.Option<Node.Node>>) =>
|
|
590
|
+
_connector(node).pipe(Atom.withLabel(`graph-builder:_connector:${id}`)),
|
|
591
|
+
);
|
|
592
|
+
|
|
593
|
+
const actionGroups =
|
|
594
|
+
_actionGroups &&
|
|
595
|
+
Atom.family((node: Atom.Atom<Option.Option<Node.Node>>) =>
|
|
596
|
+
_actionGroups(node).pipe(Atom.withLabel(`graph-builder:_actionGroups:${id}`)),
|
|
597
|
+
);
|
|
598
|
+
|
|
599
|
+
const actions =
|
|
600
|
+
_actions &&
|
|
601
|
+
Atom.family((node: Atom.Atom<Option.Option<Node.Node>>) =>
|
|
602
|
+
_actions(node).pipe(Atom.withLabel(`graph-builder:_actions:${id}`)),
|
|
603
|
+
);
|
|
604
|
+
|
|
605
|
+
return [
|
|
606
|
+
resolver ? { id: getId('resolver'), position, resolver } : undefined,
|
|
607
|
+
connector
|
|
608
|
+
? ({
|
|
609
|
+
id: getId('connector'),
|
|
610
|
+
position,
|
|
611
|
+
relation: normalizedRelation,
|
|
612
|
+
connector: Atom.family((node) =>
|
|
613
|
+
Atom.make((get) => {
|
|
614
|
+
try {
|
|
615
|
+
return get(connector(node));
|
|
616
|
+
} catch (error) {
|
|
617
|
+
log.warn('Error in connector', { id: getId('connector'), node, error });
|
|
618
|
+
return [];
|
|
619
|
+
}
|
|
620
|
+
}).pipe(Atom.withLabel(`graph-builder:connector:${id}`)),
|
|
621
|
+
),
|
|
622
|
+
} satisfies BuilderExtension)
|
|
623
|
+
: undefined,
|
|
624
|
+
actionGroups
|
|
625
|
+
? ({
|
|
626
|
+
id: getId('actionGroups'),
|
|
627
|
+
position,
|
|
628
|
+
relation: Node.actionRelation(),
|
|
629
|
+
connector: Atom.family((node) =>
|
|
630
|
+
Atom.make((get) => {
|
|
631
|
+
try {
|
|
632
|
+
return get(actionGroups(node)).map((arg) => ({
|
|
633
|
+
...arg,
|
|
634
|
+
data: Node.actionGroupSymbol,
|
|
635
|
+
type: Node.ActionGroupType,
|
|
636
|
+
}));
|
|
637
|
+
} catch (error) {
|
|
638
|
+
log.warn('Error in actionGroups', { id: getId('actionGroups'), node, error });
|
|
639
|
+
return [];
|
|
640
|
+
}
|
|
641
|
+
}).pipe(Atom.withLabel(`graph-builder:connector:actionGroups:${id}`)),
|
|
642
|
+
),
|
|
643
|
+
} satisfies BuilderExtension)
|
|
644
|
+
: undefined,
|
|
645
|
+
actions
|
|
646
|
+
? ({
|
|
647
|
+
id: getId('actions'),
|
|
648
|
+
position,
|
|
649
|
+
relation: Node.actionRelation(),
|
|
650
|
+
connector: Atom.family((node) =>
|
|
651
|
+
Atom.make((get) => {
|
|
652
|
+
try {
|
|
653
|
+
return get(actions(node)).map((arg) => ({ ...arg, type: Node.ActionType }));
|
|
654
|
+
} catch (error) {
|
|
655
|
+
log.warn('Error in actions', { id: getId('actions'), node, error });
|
|
656
|
+
return [];
|
|
657
|
+
}
|
|
658
|
+
}).pipe(Atom.withLabel(`graph-builder:connector:actions:${id}`)),
|
|
659
|
+
),
|
|
660
|
+
} satisfies BuilderExtension)
|
|
661
|
+
: undefined,
|
|
662
|
+
].filter(isNonNullable);
|
|
663
|
+
};
|
|
664
|
+
|
|
665
|
+
/**
|
|
666
|
+
* Options for creating a graph builder extension with simplified API.
|
|
667
|
+
* All callbacks must return Effects for dependency injection.
|
|
668
|
+
* Effects may fail - errors are caught, logged, and the extension returns empty results.
|
|
669
|
+
*/
|
|
670
|
+
export type CreateExtensionOptions<TMatched = Node.Node, R = never> = {
|
|
671
|
+
id: string;
|
|
672
|
+
match: (node: Node.Node) => Option.Option<TMatched>;
|
|
673
|
+
actions?: (
|
|
674
|
+
matched: TMatched,
|
|
675
|
+
get: Atom.Context,
|
|
676
|
+
) => Effect.Effect<Omit<Node.NodeArg<Node.ActionData<any>, any>, 'type'>[], Error, R>;
|
|
677
|
+
connector?: (matched: TMatched, get: Atom.Context) => Effect.Effect<Node.NodeArg<any, any>[], Error, R>;
|
|
678
|
+
resolver?: (id: string, get: Atom.Context) => Effect.Effect<Node.NodeArg<any, any> | null, Error, R>;
|
|
679
|
+
relation?: Node.RelationInput;
|
|
680
|
+
position?: Position;
|
|
681
|
+
};
|
|
682
|
+
|
|
683
|
+
/**
|
|
684
|
+
* Run an Effect synchronously with the provided context.
|
|
685
|
+
* If the effect fails, logs the error and returns the fallback value.
|
|
686
|
+
* @internal
|
|
687
|
+
*/
|
|
688
|
+
const runEffectSyncWithFallback = <T, R>(
|
|
689
|
+
effect: Effect.Effect<T, Error, R>,
|
|
690
|
+
context: Context.Context<R>,
|
|
691
|
+
extensionId: string,
|
|
692
|
+
fallback: T,
|
|
693
|
+
): T => {
|
|
694
|
+
return Effect.runSync(
|
|
695
|
+
effect.pipe(
|
|
696
|
+
Effect.provide(context),
|
|
697
|
+
Effect.catchAll((error) => {
|
|
698
|
+
log.warn('Extension failed', { extension: extensionId, error });
|
|
699
|
+
return Effect.succeed(fallback);
|
|
700
|
+
}),
|
|
701
|
+
),
|
|
702
|
+
);
|
|
703
|
+
};
|
|
704
|
+
|
|
705
|
+
/**
|
|
706
|
+
* Create a graph builder extension with simplified API.
|
|
707
|
+
* Returns an Effect to allow callbacks to access services via dependency injection.
|
|
708
|
+
*/
|
|
709
|
+
export const createExtension = <TMatched = Node.Node, R = never>(
|
|
710
|
+
options: CreateExtensionOptions<TMatched, R>,
|
|
711
|
+
): Effect.Effect<BuilderExtension[], never, R> =>
|
|
712
|
+
Effect.map(Effect.context<R>(), (context) => {
|
|
713
|
+
const { id, match, actions, connector, resolver, relation, position } = options;
|
|
714
|
+
|
|
715
|
+
const connectorExtension = connector ? createConnectorWithRuntime(id, match, connector, context) : undefined;
|
|
716
|
+
|
|
717
|
+
const actionsExtension = actions
|
|
718
|
+
? (node: Atom.Atom<Option.Option<Node.Node>>) =>
|
|
719
|
+
Atom.make((get) =>
|
|
720
|
+
Function.pipe(
|
|
721
|
+
get(node),
|
|
722
|
+
Option.flatMap(match),
|
|
723
|
+
Option.map((matched) =>
|
|
724
|
+
runEffectSyncWithFallback(actions(matched, get), context, id, []).map((action) => ({
|
|
725
|
+
...action,
|
|
726
|
+
// Attach captured context for action execution.
|
|
727
|
+
_actionContext: context,
|
|
728
|
+
})),
|
|
729
|
+
),
|
|
730
|
+
Option.getOrElse(() => []),
|
|
731
|
+
),
|
|
732
|
+
)
|
|
733
|
+
: undefined;
|
|
734
|
+
|
|
735
|
+
const resolverExtension = resolver
|
|
736
|
+
? (nodeId: string) =>
|
|
737
|
+
Atom.make((get) => runEffectSyncWithFallback(resolver(nodeId, get), context, id, null) ?? null)
|
|
738
|
+
: undefined;
|
|
739
|
+
|
|
740
|
+
return createExtensionRaw({
|
|
741
|
+
id,
|
|
742
|
+
relation,
|
|
743
|
+
position,
|
|
744
|
+
connector: connectorExtension,
|
|
745
|
+
actions: actionsExtension,
|
|
746
|
+
resolver: resolverExtension,
|
|
747
|
+
});
|
|
425
748
|
});
|
|
426
|
-
});
|
|
427
749
|
|
|
428
750
|
/**
|
|
429
|
-
*
|
|
430
|
-
*
|
|
751
|
+
* Create a connector extension from a matcher and factory function.
|
|
752
|
+
* The factory's data type is inferred from the matcher's return type.
|
|
753
|
+
*/
|
|
754
|
+
export const createConnector = <TData>(
|
|
755
|
+
matcher: (node: Node.Node) => Option.Option<TData>,
|
|
756
|
+
factory: (data: TData, get: Atom.Context) => Node.NodeArg<any>[],
|
|
757
|
+
): ConnectorExtension => {
|
|
758
|
+
return (node: Atom.Atom<Option.Option<Node.Node>>) =>
|
|
759
|
+
Atom.make((get) =>
|
|
760
|
+
Function.pipe(
|
|
761
|
+
get(node),
|
|
762
|
+
Option.flatMap(matcher),
|
|
763
|
+
Option.map((data) => factory(data, get)),
|
|
764
|
+
Option.getOrElse(() => []),
|
|
765
|
+
),
|
|
766
|
+
);
|
|
767
|
+
};
|
|
768
|
+
|
|
769
|
+
/**
|
|
770
|
+
* Create a connector extension from a matcher and factory function with Effect support.
|
|
771
|
+
* The factory must return an Effect. Errors are caught and logged.
|
|
772
|
+
* @internal
|
|
773
|
+
*/
|
|
774
|
+
const createConnectorWithRuntime = <TData, R>(
|
|
775
|
+
extensionId: string,
|
|
776
|
+
matcher: (node: Node.Node) => Option.Option<TData>,
|
|
777
|
+
factory: (data: TData, get: Atom.Context) => Effect.Effect<Node.NodeArg<any>[], Error, R>,
|
|
778
|
+
context: Context.Context<R>,
|
|
779
|
+
): ConnectorExtension => {
|
|
780
|
+
return (node: Atom.Atom<Option.Option<Node.Node>>) =>
|
|
781
|
+
Atom.make((get) =>
|
|
782
|
+
Function.pipe(
|
|
783
|
+
get(node),
|
|
784
|
+
Option.flatMap(matcher),
|
|
785
|
+
Option.map((data) => runEffectSyncWithFallback(factory(data, get), context, extensionId, [])),
|
|
786
|
+
Option.getOrElse(() => []),
|
|
787
|
+
),
|
|
788
|
+
);
|
|
789
|
+
};
|
|
790
|
+
|
|
791
|
+
/**
|
|
792
|
+
* Options for creating a type-based extension.
|
|
793
|
+
* All callbacks must return Effects for dependency injection.
|
|
794
|
+
* Effects may fail - errors are caught, logged, and the extension returns empty results.
|
|
431
795
|
*/
|
|
432
|
-
export
|
|
433
|
-
|
|
796
|
+
export type CreateTypeExtensionOptions<T extends Type.AnyEntity = Type.AnyEntity, R = never> = {
|
|
797
|
+
id: string;
|
|
798
|
+
type: T;
|
|
799
|
+
actions?: (
|
|
800
|
+
object: Entity.Entity<Schema.Schema.Type<T>>,
|
|
801
|
+
get: Atom.Context,
|
|
802
|
+
) => Effect.Effect<Omit<Node.NodeArg<Node.ActionData<any>>, 'type'>[], Error, R>;
|
|
803
|
+
connector?: (
|
|
804
|
+
object: Entity.Entity<Schema.Schema.Type<T>>,
|
|
805
|
+
get: Atom.Context,
|
|
806
|
+
) => Effect.Effect<Node.NodeArg<any>[], Error, R>;
|
|
807
|
+
relation?: Node.RelationInput;
|
|
808
|
+
position?: Position;
|
|
809
|
+
};
|
|
810
|
+
|
|
811
|
+
/**
|
|
812
|
+
* Create an extension that matches nodes by schema type.
|
|
813
|
+
* The entity type is inferred from the schema type and works for both object and relation schemas.
|
|
814
|
+
* Returns an Effect to allow callbacks to access services via dependency injection.
|
|
815
|
+
*/
|
|
816
|
+
export const createTypeExtension = <T extends Type.AnyEntity, R = never>(
|
|
817
|
+
options: CreateTypeExtensionOptions<T, R>,
|
|
818
|
+
): Effect.Effect<BuilderExtension[], never, R> => {
|
|
819
|
+
const { id, type, actions, connector, relation, position } = options;
|
|
820
|
+
return createExtension<Entity.Entity<Schema.Schema.Type<T>>, R>({
|
|
821
|
+
id,
|
|
822
|
+
match: NodeMatcher.whenEchoType(type),
|
|
823
|
+
actions,
|
|
824
|
+
connector,
|
|
825
|
+
relation,
|
|
826
|
+
position,
|
|
827
|
+
});
|
|
828
|
+
};
|
|
829
|
+
|
|
830
|
+
//
|
|
831
|
+
// Extension Utilities
|
|
832
|
+
//
|
|
833
|
+
|
|
834
|
+
/**
|
|
835
|
+
* Qualify node IDs by prefixing with the parent path.
|
|
836
|
+
* Validates that segment IDs do not contain the path separator.
|
|
837
|
+
* Recursively qualifies inline child nodes.
|
|
838
|
+
*/
|
|
839
|
+
const qualifyNodeArgs =
|
|
840
|
+
(parentId: string) =>
|
|
841
|
+
(nodes: Node.NodeArg<any>[]): Node.NodeArg<any>[] =>
|
|
842
|
+
nodes.map((node) => {
|
|
843
|
+
validateSegmentId(node.id);
|
|
844
|
+
const qualified = qualifyId(parentId, node.id);
|
|
845
|
+
return {
|
|
846
|
+
...node,
|
|
847
|
+
id: qualified,
|
|
848
|
+
nodes: node.nodes ? qualifyNodeArgs(qualified)(node.nodes) : undefined,
|
|
849
|
+
};
|
|
850
|
+
});
|
|
851
|
+
|
|
852
|
+
/**
|
|
853
|
+
* Recursively collect all inline-descendant IDs (the `nodes` arrays at every level)
|
|
854
|
+
* from a list of top-level NodeArgs. Top-level IDs are excluded because they are
|
|
855
|
+
* already tracked via `_connectorPrevious`.
|
|
856
|
+
*/
|
|
857
|
+
const collectAllInlineIds = (nodes: Node.NodeArg<any>[]): string[] =>
|
|
858
|
+
nodes.flatMap((node) =>
|
|
859
|
+
node.nodes ? [...node.nodes.map((child) => child.id), ...collectAllInlineIds(node.nodes)] : [],
|
|
860
|
+
);
|
|
861
|
+
|
|
862
|
+
const connectorKey = (id: string, relation: Node.RelationInput): string => primaryKey(id, Graph.relationKey(relation));
|
|
863
|
+
|
|
864
|
+
const relationFromConnectorKey = (key: string): { id: string; relation: Node.Relation } => {
|
|
865
|
+
const [id, encodedRelation] = primaryParts(key);
|
|
866
|
+
return { id, relation: Graph.relationFromKey(encodedRelation) };
|
|
867
|
+
};
|
|
868
|
+
|
|
869
|
+
const subscriptionKey = (id: string, kind: string, detail?: string): string =>
|
|
870
|
+
detail != null ? primaryKey(id, kind, detail) : primaryKey(id, kind);
|
|
871
|
+
|
|
872
|
+
export const flattenExtensions = (extension: BuilderExtensions, acc: BuilderExtension[] = []): BuilderExtension[] => {
|
|
873
|
+
if (Array.isArray(extension)) {
|
|
874
|
+
return [...acc, ...extension.flatMap((ext) => flattenExtensions(ext, acc))];
|
|
875
|
+
} else {
|
|
876
|
+
return [...acc, extension];
|
|
877
|
+
}
|
|
434
878
|
};
|