@dxos/app-graph 0.8.4-main.7ace549 → 0.8.4-main.8360d9e660

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/dist/lib/browser/index.mjs +1345 -602
  2. package/dist/lib/browser/index.mjs.map +4 -4
  3. package/dist/lib/browser/meta.json +1 -1
  4. package/dist/lib/node-esm/index.mjs +1344 -602
  5. package/dist/lib/node-esm/index.mjs.map +4 -4
  6. package/dist/lib/node-esm/meta.json +1 -1
  7. package/dist/types/src/atoms.d.ts +8 -0
  8. package/dist/types/src/atoms.d.ts.map +1 -0
  9. package/dist/types/src/graph-builder.d.ts +111 -65
  10. package/dist/types/src/graph-builder.d.ts.map +1 -1
  11. package/dist/types/src/graph.d.ts +179 -213
  12. package/dist/types/src/graph.d.ts.map +1 -1
  13. package/dist/types/src/index.d.ts +6 -3
  14. package/dist/types/src/index.d.ts.map +1 -1
  15. package/dist/types/src/node-matcher.d.ts +218 -0
  16. package/dist/types/src/node-matcher.d.ts.map +1 -0
  17. package/dist/types/src/node-matcher.test.d.ts +2 -0
  18. package/dist/types/src/node-matcher.test.d.ts.map +1 -0
  19. package/dist/types/src/node.d.ts +44 -5
  20. package/dist/types/src/node.d.ts.map +1 -1
  21. package/dist/types/src/stories/EchoGraph.stories.d.ts.map +1 -1
  22. package/dist/types/src/util.d.ts +34 -0
  23. package/dist/types/src/util.d.ts.map +1 -0
  24. package/dist/types/tsconfig.tsbuildinfo +1 -1
  25. package/package.json +36 -34
  26. package/src/atoms.ts +25 -0
  27. package/src/graph-builder.test.ts +870 -112
  28. package/src/graph-builder.ts +696 -284
  29. package/src/graph.test.ts +448 -120
  30. package/src/graph.ts +1024 -413
  31. package/src/index.ts +9 -3
  32. package/src/node-matcher.test.ts +301 -0
  33. package/src/node-matcher.ts +282 -0
  34. package/src/node.ts +56 -8
  35. package/src/stories/EchoGraph.stories.tsx +148 -108
  36. package/src/stories/Tree.tsx +2 -2
  37. package/src/util.ts +71 -0
  38. package/dist/types/src/signals-integration.test.d.ts +0 -2
  39. package/dist/types/src/signals-integration.test.d.ts.map +0 -1
  40. package/dist/types/src/testing.d.ts +0 -4
  41. package/dist/types/src/testing.d.ts.map +0 -1
  42. package/src/signals-integration.test.ts +0 -223
  43. package/src/testing.ts +0 -21
@@ -1,22 +1,150 @@
1
1
  import { createRequire } from 'node:module';const require = createRequire(import.meta.url);
2
+ var __defProp = Object.defineProperty;
3
+ var __export = (target, all) => {
4
+ for (var name in all)
5
+ __defProp(target, name, { get: all[name], enumerable: true });
6
+ };
7
+
8
+ // src/atoms.ts
9
+ var atoms_exports = {};
10
+ __export(atoms_exports, {
11
+ fromObservable: () => fromObservable
12
+ });
13
+ import { Atom } from "@effect-atom/atom-react";
14
+ var observableFamily = Atom.family((observable) => {
15
+ return Atom.make((get2) => {
16
+ const subscription = observable.subscribe((value) => get2.setSelf(value));
17
+ get2.addFinalizer(() => subscription.unsubscribe());
18
+ return observable.get();
19
+ });
20
+ });
21
+ var fromObservable = (observable) => {
22
+ return observableFamily(observable);
23
+ };
2
24
 
3
25
  // src/graph.ts
4
- import { Atom, Registry } from "@effect-atom/atom-react";
26
+ var graph_exports = {};
27
+ __export(graph_exports, {
28
+ GraphKind: () => GraphKind,
29
+ GraphTypeId: () => GraphTypeId,
30
+ addEdge: () => addEdge,
31
+ addEdges: () => addEdges,
32
+ addNode: () => addNode,
33
+ addNodes: () => addNodes,
34
+ expand: () => expand,
35
+ getActions: () => getActions,
36
+ getConnections: () => getConnections,
37
+ getEdges: () => getEdges,
38
+ getGraph: () => getGraph,
39
+ getNode: () => getNode,
40
+ getNodeOrThrow: () => getNodeOrThrow,
41
+ getPath: () => getPath,
42
+ getRoot: () => getRoot,
43
+ initialize: () => initialize,
44
+ make: () => make,
45
+ relationFromKey: () => relationFromKey,
46
+ relationKey: () => relationKey,
47
+ removeEdge: () => removeEdge,
48
+ removeEdges: () => removeEdges,
49
+ removeNode: () => removeNode,
50
+ removeNodes: () => removeNodes,
51
+ sortEdges: () => sortEdges,
52
+ toJSON: () => toJSON,
53
+ traverse: () => traverse,
54
+ waitForPath: () => waitForPath
55
+ });
56
+ import { Atom as Atom2, Registry } from "@effect-atom/atom-react";
5
57
  import * as Function from "effect/Function";
6
58
  import * as Option from "effect/Option";
59
+ import * as Pipeable from "effect/Pipeable";
7
60
  import * as Record from "effect/Record";
8
61
  import { Event, Trigger } from "@dxos/async";
9
62
  import { todo } from "@dxos/debug";
10
- import { invariant } from "@dxos/invariant";
63
+ import { invariant as invariant2 } from "@dxos/invariant";
11
64
  import { log } from "@dxos/log";
12
65
  import { isNonNullable } from "@dxos/util";
13
- var __dxlog_file = "/__w/dxos/dxos/packages/sdk/app-graph/src/graph.ts";
14
- var graphSymbol = Symbol("graph");
66
+
67
+ // src/node.ts
68
+ var node_exports = {};
69
+ __export(node_exports, {
70
+ ActionGroupType: () => ActionGroupType,
71
+ ActionType: () => ActionType,
72
+ RootId: () => RootId,
73
+ RootType: () => RootType,
74
+ actionGroupSymbol: () => actionGroupSymbol,
75
+ actionRelation: () => actionRelation,
76
+ childRelation: () => childRelation,
77
+ isAction: () => isAction,
78
+ isActionGroup: () => isActionGroup,
79
+ isActionLike: () => isActionLike,
80
+ isGraphNode: () => isGraphNode,
81
+ relation: () => relation
82
+ });
83
+ var RootId = "root";
84
+ var RootType = "org.dxos.type.graph-root";
85
+ var ActionType = "org.dxos.type.graph-action";
86
+ var ActionGroupType = "org.dxos.type.graph-action-group";
87
+ var relation = (kind, direction = "outbound") => ({
88
+ kind,
89
+ direction
90
+ });
91
+ var childRelation = (direction = "outbound") => relation("child", direction);
92
+ var actionRelation = (direction = "outbound") => relation("action", direction);
93
+ var isGraphNode = (data) => data && typeof data === "object" && "id" in data && "properties" in data && data.properties ? typeof data.properties === "object" && "data" in data : false;
94
+ var isAction = (data) => isGraphNode(data) ? typeof data.data === "function" && data.type === ActionType : false;
95
+ var actionGroupSymbol = /* @__PURE__ */ Symbol("ActionGroup");
96
+ var isActionGroup = (data) => isGraphNode(data) ? data.data === actionGroupSymbol && data.type === ActionGroupType : false;
97
+ var isActionLike = (data) => isAction(data) || isActionGroup(data);
98
+
99
+ // src/util.ts
100
+ import { invariant } from "@dxos/invariant";
101
+ var __dxlog_file = "/__w/dxos/dxos/packages/sdk/app-graph/src/util.ts";
102
+ var Separators = {
103
+ primary: "",
104
+ secondary: "",
105
+ path: "/"
106
+ };
107
+ var normalizeRelation = (relation2) => relation2 == null ? childRelation() : typeof relation2 === "string" ? relation(relation2) : relation2;
108
+ var shallowEqual = (a, b) => {
109
+ if (a === b) return true;
110
+ if (a == null || b == null || typeof a !== "object" || typeof b !== "object") return false;
111
+ const keysA = Object.keys(a);
112
+ const keysB = Object.keys(b);
113
+ if (keysA.length !== keysB.length) {
114
+ return false;
115
+ }
116
+ return keysA.every((k) => a[k] === b[k]);
117
+ };
118
+ var nodeArgsUnchanged = (prev, next) => {
119
+ if (prev.length !== next.length) {
120
+ return false;
121
+ }
122
+ return prev.every((prevNode, idx) => {
123
+ const nextNode = next[idx];
124
+ return prevNode.id === nextNode.id && prevNode.type === nextNode.type && shallowEqual(prevNode.data, nextNode.data) && shallowEqual(prevNode.properties, nextNode.properties);
125
+ });
126
+ };
127
+ var qualifyId = (parentId, segmentId) => `${parentId}${Separators.path}${segmentId}`;
128
+ var validateSegmentId = (id) => {
129
+ invariant(!id.includes(Separators.path), `Node segment ID must not contain '${Separators.path}': ${id}`, {
130
+ F: __dxlog_file,
131
+ L: 70,
132
+ S: void 0,
133
+ A: [
134
+ "!id.includes(Separators.path)",
135
+ "`Node segment ID must not contain '${Separators.path}': ${id}`"
136
+ ]
137
+ });
138
+ };
139
+
140
+ // src/graph.ts
141
+ var __dxlog_file2 = "/__w/dxos/dxos/packages/sdk/app-graph/src/graph.ts";
142
+ var graphSymbol = /* @__PURE__ */ Symbol("graph");
15
143
  var getGraph = (node) => {
16
144
  const graph = node[graphSymbol];
17
- invariant(graph, "Node is not associated with a graph.", {
18
- F: __dxlog_file,
19
- L: 29,
145
+ invariant2(graph, "Node is not associated with a graph.", {
146
+ F: __dxlog_file2,
147
+ L: 33,
20
148
  S: void 0,
21
149
  A: [
22
150
  "graph",
@@ -25,41 +153,45 @@ var getGraph = (node) => {
25
153
  });
26
154
  return graph;
27
155
  };
28
- var ROOT_ID = "root";
29
- var ROOT_TYPE = "dxos.org/type/GraphRoot";
30
- var ACTION_TYPE = "dxos.org/type/GraphAction";
31
- var ACTION_GROUP_TYPE = "dxos.org/type/GraphActionGroup";
32
- var Graph = class {
156
+ var GraphTypeId = /* @__PURE__ */ Symbol.for("@dxos/app-graph/Graph");
157
+ var GraphKind = /* @__PURE__ */ Symbol.for("@dxos/app-graph/GraphKind");
158
+ var GraphImpl = class {
159
+ [GraphTypeId] = GraphTypeId;
160
+ [GraphKind] = "writable";
161
+ pipe() {
162
+ return Pipeable.pipeArguments(this, arguments);
163
+ }
33
164
  onNodeChanged = new Event();
34
165
  _onExpand;
35
166
  _onInitialize;
36
167
  _onRemoveNode;
37
168
  _registry;
38
169
  _expanded = Record.empty();
170
+ _pendingExpands = /* @__PURE__ */ new Set();
39
171
  _initialized = Record.empty();
40
172
  _initialEdges = Record.empty();
41
173
  _initialNodes = Record.fromEntries([
42
174
  [
43
- ROOT_ID,
175
+ RootId,
44
176
  this._constructNode({
45
- id: ROOT_ID,
46
- type: ROOT_TYPE,
177
+ id: RootId,
178
+ type: RootType,
47
179
  data: null,
48
180
  properties: {}
49
181
  })
50
182
  ]
51
183
  ]);
52
184
  /** @internal */
53
- _node = Atom.family((id) => {
185
+ _node = Atom2.family((id) => {
54
186
  const initial = Option.flatten(Record.get(this._initialNodes, id));
55
- return Atom.make(initial).pipe(Atom.keepAlive, Atom.withLabel(`graph:node:${id}`));
187
+ return Atom2.make(initial).pipe(Atom2.keepAlive, Atom2.withLabel(`graph:node:${id}`));
56
188
  });
57
- _nodeOrThrow = Atom.family((id) => {
58
- return Atom.make((get2) => {
189
+ _nodeOrThrow = Atom2.family((id) => {
190
+ return Atom2.make((get2) => {
59
191
  const node = get2(this._node(id));
60
- invariant(Option.isSome(node), `Node not available: ${id}`, {
61
- F: __dxlog_file,
62
- L: 267,
192
+ invariant2(Option.isSome(node), `Node not available: ${id}`, {
193
+ F: __dxlog_file2,
194
+ L: 172,
63
195
  S: this,
64
196
  A: [
65
197
  "Option.isSome(node)",
@@ -69,31 +201,34 @@ var Graph = class {
69
201
  return node.value;
70
202
  });
71
203
  });
72
- _edges = Atom.family((id) => {
73
- const initial = Record.get(this._initialEdges, id).pipe(Option.getOrElse(() => ({
74
- inbound: [],
75
- outbound: []
76
- })));
77
- return Atom.make(initial).pipe(Atom.keepAlive, Atom.withLabel(`graph:edges:${id}`));
204
+ _edges = Atom2.family((id) => {
205
+ const initial = Record.get(this._initialEdges, id).pipe(Option.getOrElse(() => ({})));
206
+ return Atom2.make(initial).pipe(Atom2.keepAlive, Atom2.withLabel(`graph:edges:${id}`));
78
207
  });
79
208
  // NOTE: Currently the argument to the family needs to be referentially stable for the atom to be referentially stable.
80
209
  // TODO(wittjosiah): Atom feature request, support for something akin to `ComplexMap` to allow for complex arguments.
81
- _connections = Atom.family((key) => {
82
- return Atom.make((get2) => {
83
- const [id, relation] = key.split("$");
210
+ _connections = Atom2.family((key) => {
211
+ return Atom2.make((get2) => {
212
+ if (!key || key.indexOf(Separators.primary) <= 0) {
213
+ return [];
214
+ }
215
+ const { id, relation: relation2 } = relationFromConnectionKey(key);
84
216
  const edges = get2(this._edges(id));
85
- return edges[relation].map((id2) => get2(this._node(id2))).filter(Option.isSome).map((o) => o.value);
86
- }).pipe(Atom.withLabel(`graph:connections:${key}`));
217
+ return (edges[relationKey(relation2)] ?? []).map((id2) => get2(this._node(id2))).filter(Option.isSome).map((o) => o.value);
218
+ }).pipe(Atom2.withLabel(`graph:connections:${key}`));
87
219
  });
88
- _actions = Atom.family((id) => {
89
- return Atom.make((get2) => {
90
- return get2(this._connections(`${id}$outbound`)).filter((node) => node.type === ACTION_TYPE || node.type === ACTION_GROUP_TYPE);
91
- }).pipe(Atom.withLabel(`graph:actions:${id}`));
220
+ _actions = Atom2.family((id) => {
221
+ return Atom2.make((get2) => {
222
+ if (!id) {
223
+ return [];
224
+ }
225
+ return get2(this._connections(connectionKey(id, actionRelation())));
226
+ }).pipe(Atom2.withLabel(`graph:actions:${id}`));
92
227
  });
93
- _json = Atom.family((id) => {
94
- return Atom.make((get2) => {
95
- const toJSON = (node, seen = []) => {
96
- const nodes = get2(this.connections(node.id));
228
+ _json = Atom2.family((id) => {
229
+ return Atom2.make((get2) => {
230
+ const toJSON2 = (node, seen = []) => {
231
+ const nodes = get2(this._connections(connectionKey(node.id, "child")));
97
232
  const obj = {
98
233
  id: node.id,
99
234
  type: node.type
@@ -107,14 +242,14 @@ var Graph = class {
107
242
  ...seen,
108
243
  node.id
109
244
  ];
110
- return nextSeen.includes(n.id) ? void 0 : toJSON(n, nextSeen);
245
+ return nextSeen.includes(n.id) ? void 0 : toJSON2(n, nextSeen);
111
246
  }).filter(isNonNullable);
112
247
  }
113
248
  return obj;
114
249
  };
115
- const root = get2(this.nodeOrThrow(id));
116
- return toJSON(root);
117
- }).pipe(Atom.withLabel(`graph:json:${id}`));
250
+ const root = get2(this._nodeOrThrow(id));
251
+ return toJSON2(root);
252
+ }).pipe(Atom2.withLabel(`graph:json:${id}`));
118
253
  });
119
254
  constructor({ registry, nodes, edges, onInitialize, onExpand, onRemoveNode } = {}) {
120
255
  this._registry = registry ?? Registry.make();
@@ -132,502 +267,860 @@ var Graph = class {
132
267
  });
133
268
  }
134
269
  }
135
- toJSON(id = ROOT_ID) {
136
- return this._registry.get(this._json(id));
137
- }
138
- json(id = ROOT_ID) {
139
- return this._json(id);
270
+ json(id = RootId) {
271
+ return jsonImpl(this, id);
140
272
  }
141
273
  node(id) {
142
- return this._node(id);
274
+ return nodeImpl(this, id);
143
275
  }
144
276
  nodeOrThrow(id) {
145
- return this._nodeOrThrow(id);
277
+ return nodeOrThrowImpl(this, id);
146
278
  }
147
- connections(id, relation = "outbound") {
148
- return this._connections(`${id}$${relation}`);
279
+ connections(id, relation2) {
280
+ return connectionsImpl(this, id, relation2);
149
281
  }
150
282
  actions(id) {
151
- return this._actions(id);
283
+ return actionsImpl(this, id);
152
284
  }
153
285
  edges(id) {
154
- return this._edges(id);
286
+ return edgesImpl(this, id);
155
287
  }
156
- get root() {
157
- return this.getNodeOrThrow(ROOT_ID);
288
+ /** @internal */
289
+ _constructNode(node) {
290
+ return Option.some({
291
+ [graphSymbol]: this,
292
+ data: null,
293
+ properties: {},
294
+ ...node
295
+ });
158
296
  }
159
- getNode(id) {
160
- return this._registry.get(this.node(id));
297
+ };
298
+ var getInternal = (graph) => {
299
+ return graph;
300
+ };
301
+ var toJSON = (graph, id = RootId) => {
302
+ const internal = getInternal(graph);
303
+ return internal._registry.get(internal._json(id));
304
+ };
305
+ var jsonImpl = (graph, id = RootId) => {
306
+ const internal = getInternal(graph);
307
+ return internal._json(id);
308
+ };
309
+ var nodeImpl = (graph, id) => {
310
+ const internal = getInternal(graph);
311
+ return internal._node(id);
312
+ };
313
+ var nodeOrThrowImpl = (graph, id) => {
314
+ const internal = getInternal(graph);
315
+ return internal._nodeOrThrow(id);
316
+ };
317
+ var connectionsImpl = (graph, id, relation2) => {
318
+ const internal = getInternal(graph);
319
+ return internal._connections(connectionKey(id, relation2));
320
+ };
321
+ var actionsImpl = (graph, id) => {
322
+ const internal = getInternal(graph);
323
+ return internal._actions(id);
324
+ };
325
+ var edgesImpl = (graph, id) => {
326
+ const internal = getInternal(graph);
327
+ return internal._edges(id);
328
+ };
329
+ var getNodeImpl = (graph, id) => {
330
+ const internal = getInternal(graph);
331
+ return internal._registry.get(nodeImpl(graph, id));
332
+ };
333
+ function getNode(graphOrId, id) {
334
+ if (typeof graphOrId === "string") {
335
+ const id2 = graphOrId;
336
+ return (graph) => getNodeImpl(graph, id2);
337
+ } else {
338
+ const graph = graphOrId;
339
+ return getNodeImpl(graph, id);
161
340
  }
162
- getNodeOrThrow(id) {
163
- return this._registry.get(this.nodeOrThrow(id));
341
+ }
342
+ var getNodeOrThrowImpl = (graph, id) => {
343
+ const internal = getInternal(graph);
344
+ return internal._registry.get(nodeOrThrowImpl(graph, id));
345
+ };
346
+ function getNodeOrThrow(graphOrId, id) {
347
+ if (typeof graphOrId === "string") {
348
+ const id2 = graphOrId;
349
+ return (graph) => getNodeOrThrowImpl(graph, id2);
350
+ } else {
351
+ const graph = graphOrId;
352
+ return getNodeOrThrowImpl(graph, id);
164
353
  }
165
- getConnections(id, relation = "outbound") {
166
- return this._registry.get(this.connections(id, relation));
354
+ }
355
+ function getRoot(graph) {
356
+ return getNodeOrThrowImpl(graph, RootId);
357
+ }
358
+ var getConnectionsImpl = (graph, id, relation2) => {
359
+ const internal = getInternal(graph);
360
+ return internal._registry.get(connectionsImpl(graph, id, relation2));
361
+ };
362
+ function getConnections(graphOrId, idOrRelation, relation2) {
363
+ if (typeof graphOrId === "string") {
364
+ const id = graphOrId;
365
+ const rel = idOrRelation;
366
+ return (graph) => getConnectionsImpl(graph, id, rel);
367
+ } else {
368
+ const graph = graphOrId;
369
+ const id = idOrRelation;
370
+ invariant2(relation2 !== void 0, "Relation is required.", {
371
+ F: __dxlog_file2,
372
+ L: 446,
373
+ S: this,
374
+ A: [
375
+ "relation !== undefined",
376
+ "'Relation is required.'"
377
+ ]
378
+ });
379
+ const rel = relation2;
380
+ return getConnectionsImpl(graph, id, rel);
167
381
  }
168
- getActions(id) {
169
- return this._registry.get(this.actions(id));
382
+ }
383
+ var getActionsImpl = (graph, id) => {
384
+ const internal = getInternal(graph);
385
+ return internal._registry.get(actionsImpl(graph, id));
386
+ };
387
+ function getActions(graphOrId, id) {
388
+ if (typeof graphOrId === "string") {
389
+ const id2 = graphOrId;
390
+ return (graph) => getActionsImpl(graph, id2);
391
+ } else {
392
+ const graph = graphOrId;
393
+ return getActionsImpl(graph, id);
170
394
  }
171
- getEdges(id) {
172
- return this._registry.get(this.edges(id));
395
+ }
396
+ var getEdgesImpl = (graph, id) => {
397
+ const internal = getInternal(graph);
398
+ return internal._registry.get(edgesImpl(graph, id));
399
+ };
400
+ function getEdges(graphOrId, id) {
401
+ if (typeof graphOrId === "string") {
402
+ const id2 = graphOrId;
403
+ return (graph) => getEdgesImpl(graph, id2);
404
+ } else {
405
+ const graph = graphOrId;
406
+ return getEdgesImpl(graph, id);
173
407
  }
174
- async initialize(id) {
175
- const initialized = Record.get(this._initialized, id).pipe(Option.getOrElse(() => false));
176
- log("initialize", {
177
- id,
178
- initialized
179
- }, {
180
- F: __dxlog_file,
181
- L: 399,
182
- S: this,
183
- C: (f, a) => f(...a)
408
+ }
409
+ var traverseImpl = (graph, options, path = []) => {
410
+ const { visitor, source = RootId, relation: relation2 } = options;
411
+ if (path.includes(source)) {
412
+ return;
413
+ }
414
+ const node = getNodeOrThrow(graph, source);
415
+ const shouldContinue = visitor(node, [
416
+ ...path,
417
+ source
418
+ ]);
419
+ if (shouldContinue === false) {
420
+ return;
421
+ }
422
+ const relations = Array.isArray(relation2) ? relation2 : [
423
+ relation2
424
+ ];
425
+ const seen = /* @__PURE__ */ new Set();
426
+ for (const rel of relations) {
427
+ for (const connected of getConnections(graph, source, rel)) {
428
+ if (!seen.has(connected.id)) {
429
+ seen.add(connected.id);
430
+ traverseImpl(graph, {
431
+ source: connected.id,
432
+ relation: relation2,
433
+ visitor
434
+ }, [
435
+ ...path,
436
+ source
437
+ ]);
438
+ }
439
+ }
440
+ }
441
+ };
442
+ function traverse(graphOrOptions, optionsOrPath, path) {
443
+ if (typeof graphOrOptions === "object" && "visitor" in graphOrOptions) {
444
+ const options = graphOrOptions;
445
+ const pathArg = Array.isArray(optionsOrPath) ? optionsOrPath : void 0;
446
+ return (graph) => traverseImpl(graph, options, pathArg);
447
+ } else {
448
+ const graph = graphOrOptions;
449
+ const options = optionsOrPath;
450
+ const pathArg = path ?? (Array.isArray(optionsOrPath) ? optionsOrPath : void 0);
451
+ return traverseImpl(graph, options, pathArg);
452
+ }
453
+ }
454
+ var getPathImpl = (graph, params) => {
455
+ return Function.pipe(getNode(graph, params.source ?? "root"), Option.flatMap((node) => {
456
+ let found = Option.none();
457
+ traverseImpl(graph, {
458
+ source: node.id,
459
+ relation: "child",
460
+ visitor: (node2, path) => {
461
+ if (Option.isSome(found)) {
462
+ return false;
463
+ }
464
+ if (node2.id === params.target) {
465
+ found = Option.some(path);
466
+ }
467
+ }
184
468
  });
185
- if (!initialized) {
186
- await this._onInitialize?.(id);
187
- Record.set(this._initialized, id, true);
469
+ return found;
470
+ }));
471
+ };
472
+ function getPath(graphOrParams, params) {
473
+ if (params === void 0 && typeof graphOrParams === "object" && "target" in graphOrParams) {
474
+ const params2 = graphOrParams;
475
+ return (graph) => getPathImpl(graph, params2);
476
+ } else {
477
+ const graph = graphOrParams;
478
+ return getPathImpl(graph, params);
479
+ }
480
+ }
481
+ var waitForPathImpl = (graph, params, options) => {
482
+ const { timeout = 5e3, interval = 500 } = options ?? {};
483
+ const path = getPathImpl(graph, params);
484
+ if (Option.isSome(path)) {
485
+ return Promise.resolve(path.value);
486
+ }
487
+ const trigger = new Trigger();
488
+ const i = setInterval(() => {
489
+ const path2 = getPathImpl(graph, params);
490
+ if (Option.isSome(path2)) {
491
+ trigger.wake(path2.value);
188
492
  }
493
+ }, interval);
494
+ return trigger.wait({
495
+ timeout
496
+ }).finally(() => clearInterval(i));
497
+ };
498
+ function waitForPath(graphOrParams, paramsOrOptions, options) {
499
+ if (typeof graphOrParams === "object" && "target" in graphOrParams) {
500
+ const params = graphOrParams;
501
+ const opts = typeof paramsOrOptions === "object" && !("target" in paramsOrOptions) ? paramsOrOptions : void 0;
502
+ return (graph) => waitForPathImpl(graph, params, opts);
503
+ } else {
504
+ const graph = graphOrParams;
505
+ const params = paramsOrOptions;
506
+ return waitForPathImpl(graph, params, options);
507
+ }
508
+ }
509
+ var initializeImpl = async (graph, id) => {
510
+ const internal = getInternal(graph);
511
+ const initialized = Record.get(internal._initialized, id).pipe(Option.getOrElse(() => false));
512
+ log("initialize", {
513
+ id,
514
+ initialized
515
+ }, {
516
+ F: __dxlog_file2,
517
+ L: 668,
518
+ S: void 0,
519
+ C: (f, a) => f(...a)
520
+ });
521
+ if (!initialized) {
522
+ Record.set(internal._initialized, id, true);
523
+ await internal._onInitialize?.(id);
524
+ }
525
+ return graph;
526
+ };
527
+ function initialize(graphOrId, id) {
528
+ if (typeof graphOrId === "string") {
529
+ const id2 = graphOrId;
530
+ return (graph) => initializeImpl(graph, id2);
531
+ } else {
532
+ const graph = graphOrId;
533
+ return initializeImpl(graph, id);
189
534
  }
190
- expand(id, relation = "outbound") {
191
- const key = `${id}$${relation}`;
192
- const expanded = Record.get(this._expanded, key).pipe(Option.getOrElse(() => false));
535
+ }
536
+ var expandImpl = (graph, id, relation2) => {
537
+ const internal = getInternal(graph);
538
+ const normalizedRelation = normalizeRelation(relation2);
539
+ const key = `${id}${Separators.primary}${relationKey(normalizedRelation)}`;
540
+ const nodeOpt = internal._registry.get(internal._node(id));
541
+ if (Option.isNone(nodeOpt)) {
542
+ internal._pendingExpands.add(key);
193
543
  log("expand", {
194
544
  key,
195
- expanded
545
+ deferred: true
196
546
  }, {
197
- F: __dxlog_file,
198
- L: 409,
199
- S: this,
547
+ F: __dxlog_file2,
548
+ L: 714,
549
+ S: void 0,
200
550
  C: (f, a) => f(...a)
201
551
  });
202
- if (!expanded) {
203
- this._onExpand?.(id, relation);
204
- Record.set(this._expanded, key, true);
205
- }
552
+ return graph;
553
+ }
554
+ const expanded = Record.get(internal._expanded, key).pipe(Option.getOrElse(() => false));
555
+ log("expand", {
556
+ key,
557
+ expanded
558
+ }, {
559
+ F: __dxlog_file2,
560
+ L: 719,
561
+ S: void 0,
562
+ C: (f, a) => f(...a)
563
+ });
564
+ if (!expanded) {
565
+ Record.set(internal._expanded, key, true);
566
+ internal._onExpand?.(id, normalizedRelation);
206
567
  }
207
- addNodes(nodes) {
208
- Atom.batch(() => {
209
- nodes.map((node) => this.addNode(node));
568
+ return graph;
569
+ };
570
+ function expand(graphOrId, idOrRelation, relation2) {
571
+ if (typeof graphOrId === "string") {
572
+ const id = graphOrId;
573
+ const rel = idOrRelation;
574
+ return (graph) => expandImpl(graph, id, rel);
575
+ } else {
576
+ const graph = graphOrId;
577
+ const id = idOrRelation;
578
+ invariant2(relation2 !== void 0, "Relation is required.", {
579
+ F: __dxlog_file2,
580
+ L: 755,
581
+ S: this,
582
+ A: [
583
+ "relation !== undefined",
584
+ "'Relation is required.'"
585
+ ]
210
586
  });
587
+ const rel = relation2;
588
+ return expandImpl(graph, id, rel);
211
589
  }
212
- addNode({ nodes, edges, ...nodeArg }) {
213
- const { id, type, data = null, properties = {} } = nodeArg;
214
- const nodeAtom = this._node(id);
215
- const node = this._registry.get(nodeAtom);
216
- Option.match(node, {
217
- onSome: (node2) => {
218
- const typeChanged = node2.type !== type;
219
- const dataChanged = node2.data !== data;
220
- const propertiesChanged = Object.keys(properties).some((key) => node2.properties[key] !== properties[key]);
221
- log("existing node", {
222
- id,
223
- typeChanged,
224
- dataChanged,
225
- propertiesChanged
226
- }, {
227
- F: __dxlog_file,
228
- L: 431,
229
- S: this,
230
- C: (f, a) => f(...a)
231
- });
232
- if (typeChanged || dataChanged || propertiesChanged) {
233
- log("updating node", {
234
- id,
235
- type,
236
- data,
237
- properties
238
- }, {
239
- F: __dxlog_file,
240
- L: 438,
241
- S: this,
242
- C: (f, a) => f(...a)
243
- });
244
- const newNode = Option.some({
245
- ...node2,
246
- type,
247
- data,
248
- properties: {
249
- ...node2.properties,
250
- ...properties
251
- }
252
- });
253
- this._registry.set(nodeAtom, newNode);
254
- this.onNodeChanged.emit({
255
- id,
256
- node: newNode
257
- });
258
- }
259
- },
260
- onNone: () => {
261
- log("new node", {
590
+ }
591
+ var sortEdgesImpl = (graph, id, relation2, order) => {
592
+ const internal = getInternal(graph);
593
+ const edgesAtom = internal._edges(id);
594
+ const edges = internal._registry.get(edgesAtom);
595
+ const relationId = relationKey(relation2);
596
+ const current = edges[relationId] ?? [];
597
+ const unsorted = current.filter((id2) => !order.includes(id2));
598
+ const sorted = order.filter((id2) => current.includes(id2));
599
+ const newOrder = [
600
+ ...sorted,
601
+ ...unsorted
602
+ ];
603
+ if (newOrder.length === current.length && newOrder.every((id2, i) => id2 === current[i])) {
604
+ return graph;
605
+ }
606
+ internal._registry.set(edgesAtom, {
607
+ ...edges,
608
+ [relationId]: newOrder
609
+ });
610
+ return graph;
611
+ };
612
+ function sortEdges(graphOrId, idOrRelation, relationOrOrder, order) {
613
+ if (typeof graphOrId === "string") {
614
+ const id = graphOrId;
615
+ const relation2 = idOrRelation;
616
+ const order2 = relationOrOrder;
617
+ return (graph) => sortEdgesImpl(graph, id, relation2, order2);
618
+ } else {
619
+ const graph = graphOrId;
620
+ const id = idOrRelation;
621
+ const relation2 = relationOrOrder;
622
+ return sortEdgesImpl(graph, id, relation2, order);
623
+ }
624
+ }
625
+ var addNodesImpl = (graph, nodes) => {
626
+ Atom2.batch(() => {
627
+ nodes.map((node) => addNodeImpl(graph, node));
628
+ });
629
+ return graph;
630
+ };
631
+ function addNodes(graphOrNodes, nodes) {
632
+ if (nodes === void 0) {
633
+ const nodes2 = graphOrNodes;
634
+ return (graph) => addNodesImpl(graph, nodes2);
635
+ } else {
636
+ const graph = graphOrNodes;
637
+ return addNodesImpl(graph, nodes);
638
+ }
639
+ }
640
+ var addNodeImpl = (graph, nodeArg) => {
641
+ const internal = getInternal(graph);
642
+ const { nodes, edges, id, type, data = null, properties = {}, ...rest } = nodeArg;
643
+ const nodeAtom = internal._node(id);
644
+ const existingNode = internal._registry.get(nodeAtom);
645
+ Option.match(existingNode, {
646
+ onSome: (existing) => {
647
+ const typeChanged = existing.type !== type;
648
+ const dataChanged = !shallowEqual(existing.data, data);
649
+ const propertiesChanged = Object.keys(properties).some((key) => existing.properties[key] !== properties[key]);
650
+ log("existing node", {
651
+ id,
652
+ typeChanged,
653
+ dataChanged,
654
+ propertiesChanged
655
+ }, {
656
+ F: __dxlog_file2,
657
+ L: 877,
658
+ S: void 0,
659
+ C: (f, a) => f(...a)
660
+ });
661
+ if (typeChanged || dataChanged || propertiesChanged) {
662
+ log("updating node", {
262
663
  id,
263
664
  type,
264
665
  data,
265
666
  properties
266
667
  }, {
267
- F: __dxlog_file,
268
- L: 450,
269
- S: this,
668
+ F: __dxlog_file2,
669
+ L: 884,
670
+ S: void 0,
270
671
  C: (f, a) => f(...a)
271
672
  });
272
- const newNode = this._constructNode({
273
- id,
673
+ const newNode = Option.some({
674
+ ...existing,
675
+ ...rest,
274
676
  type,
275
677
  data,
276
- properties
678
+ properties: {
679
+ ...existing.properties,
680
+ ...properties
681
+ }
277
682
  });
278
- this._registry.set(nodeAtom, newNode);
279
- this.onNodeChanged.emit({
683
+ internal._registry.set(nodeAtom, newNode);
684
+ graph.onNodeChanged.emit({
280
685
  id,
281
686
  node: newNode
282
687
  });
283
688
  }
284
- });
285
- if (nodes) {
286
- this.addNodes(nodes);
287
- const _edges = nodes.map((node2) => ({
288
- source: id,
289
- target: node2.id
290
- }));
291
- this.addEdges(_edges);
292
- }
293
- if (edges) {
294
- todo();
295
- }
296
- }
297
- removeNodes(ids, edges = false) {
298
- Atom.batch(() => {
299
- ids.map((id) => this.removeNode(id, edges));
300
- });
301
- }
302
- removeNode(id, edges = false) {
303
- const nodeAtom = this._node(id);
304
- this._registry.set(nodeAtom, Option.none());
305
- this.onNodeChanged.emit({
306
- id,
307
- node: Option.none()
308
- });
309
- if (edges) {
310
- const { inbound, outbound } = this._registry.get(this._edges(id));
311
- const edges2 = [
312
- ...inbound.map((source) => ({
313
- source,
314
- target: id
315
- })),
316
- ...outbound.map((target) => ({
317
- source: id,
318
- target
319
- }))
320
- ];
321
- this.removeEdges(edges2);
322
- }
323
- this._onRemoveNode?.(id);
324
- }
325
- addEdges(edges) {
326
- Atom.batch(() => {
327
- edges.map((edge) => this.addEdge(edge));
328
- });
329
- }
330
- addEdge(edgeArg) {
331
- const sourceAtom = this._edges(edgeArg.source);
332
- const source = this._registry.get(sourceAtom);
333
- if (!source.outbound.includes(edgeArg.target)) {
334
- log("add outbound edge", {
335
- source: edgeArg.source,
336
- target: edgeArg.target
689
+ },
690
+ onNone: () => {
691
+ log("new node", {
692
+ id,
693
+ type,
694
+ data,
695
+ properties
337
696
  }, {
338
- F: __dxlog_file,
339
- L: 505,
340
- S: this,
697
+ F: __dxlog_file2,
698
+ L: 897,
699
+ S: void 0,
341
700
  C: (f, a) => f(...a)
342
701
  });
343
- this._registry.set(sourceAtom, {
344
- inbound: source.inbound,
345
- outbound: [
346
- ...source.outbound,
347
- edgeArg.target
348
- ]
349
- });
350
- }
351
- const targetAtom = this._edges(edgeArg.target);
352
- const target = this._registry.get(targetAtom);
353
- if (!target.inbound.includes(edgeArg.source)) {
354
- log("add inbound edge", {
355
- source: edgeArg.source,
356
- target: edgeArg.target
357
- }, {
358
- F: __dxlog_file,
359
- L: 518,
360
- S: this,
361
- C: (f, a) => f(...a)
702
+ const newNode = internal._constructNode({
703
+ id,
704
+ type,
705
+ data,
706
+ properties,
707
+ ...rest
362
708
  });
363
- this._registry.set(targetAtom, {
364
- inbound: [
365
- ...target.inbound,
366
- edgeArg.source
367
- ],
368
- outbound: target.outbound
709
+ internal._registry.set(nodeAtom, newNode);
710
+ graph.onNodeChanged.emit({
711
+ id,
712
+ node: newNode
369
713
  });
714
+ const prefix = `${id}${Separators.primary}`;
715
+ const toApply = [
716
+ ...internal._pendingExpands
717
+ ].filter((k) => k.startsWith(prefix));
718
+ for (const pendingKey of toApply) {
719
+ internal._pendingExpands.delete(pendingKey);
720
+ const relation2 = relationFromKey(pendingKey.slice(prefix.length));
721
+ Record.set(internal._expanded, pendingKey, true);
722
+ internal._onExpand?.(id, relation2);
723
+ }
370
724
  }
725
+ });
726
+ if (nodes) {
727
+ addNodesImpl(graph, nodes);
728
+ const _edges = nodes.map((node) => ({
729
+ source: id,
730
+ target: node.id,
731
+ relation: "child"
732
+ }));
733
+ addEdgesImpl(graph, _edges);
371
734
  }
372
- removeEdges(edges, removeOrphans = false) {
373
- Atom.batch(() => {
374
- edges.map((edge) => this.removeEdge(edge, removeOrphans));
375
- });
735
+ if (edges) {
736
+ todo();
376
737
  }
377
- removeEdge(edgeArg, removeOrphans = false) {
378
- const sourceAtom = this._edges(edgeArg.source);
379
- const source = this._registry.get(sourceAtom);
380
- if (source.outbound.includes(edgeArg.target)) {
381
- this._registry.set(sourceAtom, {
382
- inbound: source.inbound,
383
- outbound: source.outbound.filter((id) => id !== edgeArg.target)
384
- });
385
- }
386
- const targetAtom = this._edges(edgeArg.target);
387
- const target = this._registry.get(targetAtom);
388
- if (target.inbound.includes(edgeArg.source)) {
389
- this._registry.set(targetAtom, {
390
- inbound: target.inbound.filter((id) => id !== edgeArg.source),
391
- outbound: target.outbound
392
- });
393
- }
394
- if (removeOrphans) {
395
- const source2 = this._registry.get(sourceAtom);
396
- const target2 = this._registry.get(targetAtom);
397
- if (source2.outbound.length === 0 && source2.inbound.length === 0 && edgeArg.source !== ROOT_ID) {
398
- this.removeNodes([
399
- edgeArg.source
400
- ]);
401
- }
402
- if (target2.outbound.length === 0 && target2.inbound.length === 0 && edgeArg.target !== ROOT_ID) {
403
- this.removeNodes([
404
- edgeArg.target
405
- ]);
738
+ return graph;
739
+ };
740
+ function addNode(graphOrNodeArg, nodeArg) {
741
+ if (nodeArg === void 0) {
742
+ const nodeArg2 = graphOrNodeArg;
743
+ return (graph) => addNodeImpl(graph, nodeArg2);
744
+ } else {
745
+ const graph = graphOrNodeArg;
746
+ return addNodeImpl(graph, nodeArg);
747
+ }
748
+ }
749
+ var removeNodesImpl = (graph, ids, edges = false) => {
750
+ Atom2.batch(() => {
751
+ ids.map((id) => removeNodeImpl(graph, id, edges));
752
+ });
753
+ return graph;
754
+ };
755
+ function removeNodes(graphOrIds, idsOrEdges, edges) {
756
+ if (Array.isArray(graphOrIds)) {
757
+ const ids = graphOrIds;
758
+ const edgesArg = typeof idsOrEdges === "boolean" ? idsOrEdges : false;
759
+ return (graph) => removeNodesImpl(graph, ids, edgesArg);
760
+ } else {
761
+ const graph = graphOrIds;
762
+ const ids = idsOrEdges;
763
+ const edgesArg = edges ?? false;
764
+ return removeNodesImpl(graph, ids, edgesArg);
765
+ }
766
+ }
767
+ var removeNodeImpl = (graph, id, edges = false) => {
768
+ const internal = getInternal(graph);
769
+ const nodeAtom = internal._node(id);
770
+ internal._registry.set(nodeAtom, Option.none());
771
+ graph.onNodeChanged.emit({
772
+ id,
773
+ node: Option.none()
774
+ });
775
+ if (edges) {
776
+ const nodeEdges = internal._registry.get(internal._edges(id));
777
+ const edgesToRemove = [];
778
+ for (const [relationKeyValue, relatedIds] of Object.entries(nodeEdges)) {
779
+ const relation2 = relationFromKey(relationKeyValue);
780
+ const isInboundRelation = relation2.direction === "inbound";
781
+ for (const relatedId of relatedIds) {
782
+ if (isInboundRelation) {
783
+ edgesToRemove.push({
784
+ source: relatedId,
785
+ target: id,
786
+ relation: inverseRelation(relation2)
787
+ });
788
+ } else {
789
+ edgesToRemove.push({
790
+ source: id,
791
+ target: relatedId,
792
+ relation: relation2
793
+ });
794
+ }
406
795
  }
407
796
  }
797
+ removeEdgesImpl(graph, edgesToRemove);
408
798
  }
409
- sortEdges(id, relation, order) {
410
- const edgesAtom = this._edges(id);
411
- const edges = this._registry.get(edgesAtom);
412
- const unsorted = edges[relation].filter((id2) => !order.includes(id2)) ?? [];
413
- const sorted = order.filter((id2) => edges[relation].includes(id2)) ?? [];
414
- edges[relation].splice(0, edges[relation].length, ...[
415
- ...sorted,
416
- ...unsorted
417
- ]);
418
- this._registry.set(edgesAtom, edges);
799
+ internal._onRemoveNode?.(id);
800
+ return graph;
801
+ };
802
+ function removeNode(graphOrId, idOrEdges, edges) {
803
+ if (typeof graphOrId === "string") {
804
+ const id = graphOrId;
805
+ const edgesArg = typeof idOrEdges === "boolean" ? idOrEdges : false;
806
+ return (graph) => removeNodeImpl(graph, id, edgesArg);
807
+ } else {
808
+ const graph = graphOrId;
809
+ const id = idOrEdges;
810
+ const edgesArg = edges ?? false;
811
+ return removeNodeImpl(graph, id, edgesArg);
419
812
  }
420
- traverse({ visitor, source = ROOT_ID, relation = "outbound" }, path = []) {
421
- if (path.includes(source)) {
422
- return;
423
- }
424
- const node = this.getNodeOrThrow(source);
425
- const shouldContinue = visitor(node, [
426
- ...path,
427
- source
428
- ]);
429
- if (shouldContinue === false) {
430
- return;
431
- }
432
- Object.values(this.getConnections(source, relation)).forEach((child) => this.traverse({
433
- source: child.id,
434
- relation,
435
- visitor
436
- }, [
437
- ...path,
438
- source
439
- ]));
440
- }
441
- getPath({ source = "root", target }) {
442
- return Function.pipe(this.getNode(source), Option.flatMap((node) => {
443
- let found = Option.none();
444
- this.traverse({
445
- source: node.id,
446
- visitor: (node2, path) => {
447
- if (Option.isSome(found)) {
448
- return false;
449
- }
450
- if (node2.id === target) {
451
- found = Option.some(path);
452
- }
453
- }
454
- });
455
- return found;
456
- }));
813
+ }
814
+ var addEdgesImpl = (graph, edges) => {
815
+ Atom2.batch(() => {
816
+ edges.map((edge) => addEdgeImpl(graph, edge));
817
+ });
818
+ return graph;
819
+ };
820
+ function addEdges(graphOrEdges, edges) {
821
+ if (edges === void 0) {
822
+ const edges2 = graphOrEdges;
823
+ return (graph) => addEdgesImpl(graph, edges2);
824
+ } else {
825
+ const graph = graphOrEdges;
826
+ return addEdgesImpl(graph, edges);
457
827
  }
458
- async waitForPath(params, { timeout = 5e3, interval = 500 } = {}) {
459
- const path = this.getPath(params);
460
- if (Option.isSome(path)) {
461
- return path.value;
462
- }
463
- const trigger = new Trigger();
464
- const i = setInterval(() => {
465
- const path2 = this.getPath(params);
466
- if (Option.isSome(path2)) {
467
- trigger.wake(path2.value);
468
- }
469
- }, interval);
470
- return trigger.wait({
471
- timeout
472
- }).finally(() => clearInterval(i));
828
+ }
829
+ var addEdgeImpl = (graph, edgeArg) => {
830
+ const relation2 = normalizeRelation(edgeArg.relation);
831
+ const relationId = relationKey(relation2);
832
+ const inverse = inverseRelation(relation2);
833
+ const inverseId = relationKey(inverse);
834
+ const internal = getInternal(graph);
835
+ const sourceAtom = internal._edges(edgeArg.source);
836
+ const source = internal._registry.get(sourceAtom);
837
+ const sourceList = source[relationId] ?? [];
838
+ if (!sourceList.includes(edgeArg.target)) {
839
+ log("add edge", {
840
+ source: edgeArg.source,
841
+ target: edgeArg.target,
842
+ relation: relationId
843
+ }, {
844
+ F: __dxlog_file2,
845
+ L: 1081,
846
+ S: void 0,
847
+ C: (f, a) => f(...a)
848
+ });
849
+ internal._registry.set(sourceAtom, {
850
+ ...source,
851
+ [relationId]: [
852
+ ...sourceList,
853
+ edgeArg.target
854
+ ]
855
+ });
473
856
  }
474
- /** @internal */
475
- _constructNode(node) {
476
- return Option.some({
477
- [graphSymbol]: this,
478
- data: null,
479
- properties: {},
480
- ...node
857
+ const targetAtom = internal._edges(edgeArg.target);
858
+ const target = internal._registry.get(targetAtom);
859
+ const targetList = target[inverseId] ?? [];
860
+ if (!targetList.includes(edgeArg.source)) {
861
+ log("add inverse edge", {
862
+ source: edgeArg.source,
863
+ target: edgeArg.target,
864
+ relation: inverseId
865
+ }, {
866
+ F: __dxlog_file2,
867
+ L: 1089,
868
+ S: void 0,
869
+ C: (f, a) => f(...a)
870
+ });
871
+ internal._registry.set(targetAtom, {
872
+ ...target,
873
+ [inverseId]: [
874
+ ...targetList,
875
+ edgeArg.source
876
+ ]
481
877
  });
482
878
  }
879
+ return graph;
880
+ };
881
+ function addEdge(graphOrEdgeArg, edgeArg) {
882
+ if (edgeArg === void 0) {
883
+ const edgeArg2 = graphOrEdgeArg;
884
+ return (graph) => addEdgeImpl(graph, edgeArg2);
885
+ } else {
886
+ const graph = graphOrEdgeArg;
887
+ return addEdgeImpl(graph, edgeArg);
888
+ }
889
+ }
890
+ var removeEdgesImpl = (graph, edges, removeOrphans = false) => {
891
+ Atom2.batch(() => {
892
+ edges.map((edge) => removeEdgeImpl(graph, edge, removeOrphans));
893
+ });
894
+ return graph;
895
+ };
896
+ function removeEdges(graphOrEdges, edgesOrRemoveOrphans, removeOrphans) {
897
+ if (Array.isArray(graphOrEdges)) {
898
+ const edges = graphOrEdges;
899
+ const removeOrphansArg = typeof edgesOrRemoveOrphans === "boolean" ? edgesOrRemoveOrphans : false;
900
+ return (graph) => removeEdgesImpl(graph, edges, removeOrphansArg);
901
+ } else {
902
+ const graph = graphOrEdges;
903
+ const edges = edgesOrRemoveOrphans;
904
+ const removeOrphansArg = removeOrphans ?? false;
905
+ return removeEdgesImpl(graph, edges, removeOrphansArg);
906
+ }
907
+ }
908
+ var removeEdgeImpl = (graph, edgeArg, removeOrphans = false) => {
909
+ const relation2 = normalizeRelation(edgeArg.relation);
910
+ const relationId = relationKey(relation2);
911
+ const inverse = inverseRelation(relation2);
912
+ const inverseId = relationKey(inverse);
913
+ const internal = getInternal(graph);
914
+ const sourceAtom = internal._edges(edgeArg.source);
915
+ const source = internal._registry.get(sourceAtom);
916
+ const sourceList = source[relationId] ?? [];
917
+ if (sourceList.includes(edgeArg.target)) {
918
+ internal._registry.set(sourceAtom, {
919
+ ...source,
920
+ [relationId]: sourceList.filter((id) => id !== edgeArg.target)
921
+ });
922
+ }
923
+ const targetAtom = internal._edges(edgeArg.target);
924
+ const target = internal._registry.get(targetAtom);
925
+ const targetList = target[inverseId] ?? [];
926
+ if (targetList.includes(edgeArg.source)) {
927
+ internal._registry.set(targetAtom, {
928
+ ...target,
929
+ [inverseId]: targetList.filter((id) => id !== edgeArg.source)
930
+ });
931
+ }
932
+ if (removeOrphans) {
933
+ const sourceAfter = internal._registry.get(sourceAtom);
934
+ const targetAfter = internal._registry.get(targetAtom);
935
+ const isEmpty = (edges) => Object.values(edges).every((ids) => ids.length === 0);
936
+ if (isEmpty(sourceAfter) && edgeArg.source !== RootId) {
937
+ removeNodesImpl(graph, [
938
+ edgeArg.source
939
+ ]);
940
+ }
941
+ if (isEmpty(targetAfter) && edgeArg.target !== RootId) {
942
+ removeNodesImpl(graph, [
943
+ edgeArg.target
944
+ ]);
945
+ }
946
+ }
947
+ return graph;
948
+ };
949
+ function removeEdge(graphOrEdgeArg, edgeArgOrRemoveOrphans, removeOrphans) {
950
+ if (edgeArgOrRemoveOrphans === void 0 || typeof edgeArgOrRemoveOrphans === "boolean" || "source" in graphOrEdgeArg) {
951
+ const edgeArg = graphOrEdgeArg;
952
+ const removeOrphansArg = typeof edgeArgOrRemoveOrphans === "boolean" ? edgeArgOrRemoveOrphans : false;
953
+ return (graph) => removeEdgeImpl(graph, edgeArg, removeOrphansArg);
954
+ } else {
955
+ const graph = graphOrEdgeArg;
956
+ const edgeArg = edgeArgOrRemoveOrphans;
957
+ const removeOrphansArg = removeOrphans ?? false;
958
+ return removeEdgeImpl(graph, edgeArg, removeOrphansArg);
959
+ }
960
+ }
961
+ var make = (params) => {
962
+ return new GraphImpl(params);
963
+ };
964
+ var relationKey = (relation2) => {
965
+ const normalized = normalizeRelation(relation2);
966
+ return `${normalized.kind}${Separators.secondary}${normalized.direction}`;
967
+ };
968
+ var relationFromKey = (encoded) => {
969
+ const separatorIndex = encoded.lastIndexOf(Separators.secondary);
970
+ invariant2(separatorIndex > 0 && separatorIndex < encoded.length - 1, `Invalid relation key: ${encoded}`, {
971
+ F: __dxlog_file2,
972
+ L: 1234,
973
+ S: void 0,
974
+ A: [
975
+ "separatorIndex > 0 && separatorIndex < encoded.length - 1",
976
+ "`Invalid relation key: ${encoded}`"
977
+ ]
978
+ });
979
+ const kind = encoded.slice(0, separatorIndex);
980
+ const directionRaw = encoded.slice(separatorIndex + 1);
981
+ invariant2(directionRaw === "outbound" || directionRaw === "inbound", `Invalid relation direction: ${directionRaw}`, {
982
+ F: __dxlog_file2,
983
+ L: 1237,
984
+ S: void 0,
985
+ A: [
986
+ "directionRaw === 'outbound' || directionRaw === 'inbound'",
987
+ "`Invalid relation direction: ${directionRaw}`"
988
+ ]
989
+ });
990
+ return relation(kind, directionRaw);
991
+ };
992
+ var connectionKey = (id, relation2) => `${id}${Separators.primary}${relationKey(relation2)}`;
993
+ var relationFromConnectionKey = (key) => {
994
+ const separatorIndex = key.indexOf(Separators.primary);
995
+ invariant2(separatorIndex > 0 && separatorIndex < key.length - 1, `Invalid connection key: ${key}`, {
996
+ F: __dxlog_file2,
997
+ L: 1246,
998
+ S: void 0,
999
+ A: [
1000
+ "separatorIndex > 0 && separatorIndex < key.length - 1",
1001
+ "`Invalid connection key: ${key}`"
1002
+ ]
1003
+ });
1004
+ const id = key.slice(0, separatorIndex);
1005
+ const encodedRelation = key.slice(separatorIndex + 1);
1006
+ return {
1007
+ id,
1008
+ relation: relationFromKey(encodedRelation)
1009
+ };
1010
+ };
1011
+ var inverseRelation = (relation2) => {
1012
+ const normalized = normalizeRelation(relation2);
1013
+ return relation(normalized.kind, normalized.direction === "outbound" ? "inbound" : "outbound");
483
1014
  };
484
1015
 
485
1016
  // src/graph-builder.ts
486
- import { Atom as Atom2, Registry as Registry2 } from "@effect-atom/atom-react";
487
- import { effect } from "@preact/signals-core";
488
- import * as Array from "effect/Array";
1017
+ var graph_builder_exports = {};
1018
+ __export(graph_builder_exports, {
1019
+ GraphBuilderTypeId: () => GraphBuilderTypeId,
1020
+ addExtension: () => addExtension,
1021
+ createConnector: () => createConnector,
1022
+ createExtension: () => createExtension,
1023
+ createExtensionRaw: () => createExtensionRaw,
1024
+ createTypeExtension: () => createTypeExtension,
1025
+ destroy: () => destroy,
1026
+ explore: () => explore,
1027
+ flattenExtensions: () => flattenExtensions,
1028
+ flush: () => flush,
1029
+ from: () => from,
1030
+ make: () => make2,
1031
+ removeExtension: () => removeExtension
1032
+ });
1033
+ import { Atom as Atom3, Registry as Registry2 } from "@effect-atom/atom-react";
1034
+ import * as Array2 from "effect/Array";
1035
+ import * as Effect from "effect/Effect";
489
1036
  import * as Function2 from "effect/Function";
490
- import * as Option2 from "effect/Option";
1037
+ import * as Option3 from "effect/Option";
1038
+ import * as Pipeable2 from "effect/Pipeable";
491
1039
  import * as Record2 from "effect/Record";
1040
+ import { scheduleTask, yieldOrContinue } from "main-thread-scheduling";
492
1041
  import { log as log2 } from "@dxos/log";
493
- import { byPosition, getDebugName, isNode, isNonNullable as isNonNullable2 } from "@dxos/util";
494
-
495
- // src/node.ts
496
- var isGraphNode = (data) => data && typeof data === "object" && "id" in data && "properties" in data && data.properties ? typeof data.properties === "object" && "data" in data : false;
497
- var isAction = (data) => isGraphNode(data) ? typeof data.data === "function" && data.type === ACTION_TYPE : false;
498
- var actionGroupSymbol = Symbol("ActionGroup");
499
- var isActionGroup = (data) => isGraphNode(data) ? data.data === actionGroupSymbol && data.type === ACTION_GROUP_TYPE : false;
500
- var isActionLike = (data) => isAction(data) || isActionGroup(data);
1042
+ import { byPosition, getDebugName, isNonNullable as isNonNullable2 } from "@dxos/util";
501
1043
 
502
- // src/graph-builder.ts
503
- var __dxlog_file2 = "/__w/dxos/dxos/packages/sdk/app-graph/src/graph-builder.ts";
504
- var createExtension = (extension) => {
505
- const { id, position = "static", relation = "outbound", resolver: _resolver, connector: _connector, actions: _actions, actionGroups: _actionGroups } = extension;
506
- const getId = (key) => `${id}/${key}`;
507
- const resolver = _resolver && Atom2.family((id2) => _resolver(id2).pipe(Atom2.withLabel(`graph-builder:_resolver:${id2}`)));
508
- const connector = _connector && Atom2.family((node) => _connector(node).pipe(Atom2.withLabel(`graph-builder:_connector:${id}`)));
509
- const actionGroups = _actionGroups && Atom2.family((node) => _actionGroups(node).pipe(Atom2.withLabel(`graph-builder:_actionGroups:${id}`)));
510
- const actions = _actions && Atom2.family((node) => _actions(node).pipe(Atom2.withLabel(`graph-builder:_actions:${id}`)));
511
- return [
512
- resolver ? {
513
- id: getId("resolver"),
514
- position,
515
- resolver
516
- } : void 0,
517
- connector ? {
518
- id: getId("connector"),
519
- position,
520
- relation,
521
- connector: Atom2.family((node) => Atom2.make((get2) => {
522
- try {
523
- return get2(connector(node));
524
- } catch {
525
- log2.warn("Error in connector", {
526
- id: getId("connector"),
527
- node
528
- }, {
529
- F: __dxlog_file2,
530
- L: 114,
531
- S: void 0,
532
- C: (f, a) => f(...a)
533
- });
534
- return [];
535
- }
536
- }).pipe(Atom2.withLabel(`graph-builder:connector:${id}`)))
537
- } : void 0,
538
- actionGroups ? {
539
- id: getId("actionGroups"),
540
- position,
541
- relation: "outbound",
542
- connector: Atom2.family((node) => Atom2.make((get2) => {
543
- try {
544
- return get2(actionGroups(node)).map((arg) => ({
545
- ...arg,
546
- data: actionGroupSymbol,
547
- type: ACTION_GROUP_TYPE
548
- }));
549
- } catch {
550
- log2.warn("Error in actionGroups", {
551
- id: getId("actionGroups"),
552
- node
553
- }, {
554
- F: __dxlog_file2,
555
- L: 135,
556
- S: void 0,
557
- C: (f, a) => f(...a)
558
- });
559
- return [];
560
- }
561
- }).pipe(Atom2.withLabel(`graph-builder:connector:actionGroups:${id}`)))
562
- } : void 0,
563
- actions ? {
564
- id: getId("actions"),
565
- position,
566
- relation: "outbound",
567
- connector: Atom2.family((node) => Atom2.make((get2) => {
568
- try {
569
- return get2(actions(node)).map((arg) => ({
570
- ...arg,
571
- type: ACTION_TYPE
572
- }));
573
- } catch {
574
- log2.warn("Error in actions", {
575
- id: getId("actions"),
576
- node
577
- }, {
578
- F: __dxlog_file2,
579
- L: 152,
580
- S: void 0,
581
- C: (f, a) => f(...a)
582
- });
583
- return [];
584
- }
585
- }).pipe(Atom2.withLabel(`graph-builder:connector:actions:${id}`)))
586
- } : void 0
587
- ].filter(isNonNullable2);
1044
+ // src/node-matcher.ts
1045
+ var node_matcher_exports = {};
1046
+ __export(node_matcher_exports, {
1047
+ whenAll: () => whenAll,
1048
+ whenAny: () => whenAny,
1049
+ whenEchoObject: () => whenEchoObject,
1050
+ whenEchoObjectMatches: () => whenEchoObjectMatches,
1051
+ whenEchoType: () => whenEchoType,
1052
+ whenEchoTypeMatches: () => whenEchoTypeMatches,
1053
+ whenId: () => whenId,
1054
+ whenNodeType: () => whenNodeType,
1055
+ whenNot: () => whenNot,
1056
+ whenRoot: () => whenRoot
1057
+ });
1058
+ import * as Option2 from "effect/Option";
1059
+ import { Obj } from "@dxos/echo";
1060
+ var whenRoot = (node) => node.id === RootId ? Option2.some(node) : Option2.none();
1061
+ var whenId = (id) => (node) => node.id === id ? Option2.some(node) : Option2.none();
1062
+ var whenNodeType = (type) => (node) => node.type === type ? Option2.some(node) : Option2.none();
1063
+ var whenEchoType = (type) => (node) => Obj.instanceOf(type, node.data) ? Option2.some(node.data) : Option2.none();
1064
+ var whenEchoObject = (node) => Obj.isObject(node.data) ? Option2.some(node.data) : Option2.none();
1065
+ var whenAll = (...matchers) => (node) => {
1066
+ for (const candidate of matchers) {
1067
+ if (Option2.isNone(candidate(node))) {
1068
+ return Option2.none();
1069
+ }
1070
+ }
1071
+ return Option2.some(node);
588
1072
  };
589
- var flattenExtensions = (extension, acc = []) => {
590
- if (Array.isArray(extension)) {
591
- return [
592
- ...acc,
593
- ...extension.flatMap((ext) => flattenExtensions(ext, acc))
594
- ];
595
- } else {
596
- return [
597
- ...acc,
598
- extension
599
- ];
1073
+ var whenAny = (...matchers) => (node) => {
1074
+ for (const candidate of matchers) {
1075
+ if (Option2.isSome(candidate(node))) {
1076
+ return Option2.some(node);
1077
+ }
600
1078
  }
1079
+ return Option2.none();
601
1080
  };
602
- var GraphBuilder = class _GraphBuilder {
1081
+ var whenEchoTypeMatches = (type) => (node) => Obj.instanceOf(type, node.data) ? Option2.some(node) : Option2.none();
1082
+ var whenEchoObjectMatches = (node) => Obj.isObject(node.data) ? Option2.some(node) : Option2.none();
1083
+ var whenNot = (matcher) => (node) => Option2.isNone(matcher(node)) ? Option2.some(node) : Option2.none();
1084
+
1085
+ // src/graph-builder.ts
1086
+ var __dxlog_file3 = "/__w/dxos/dxos/packages/sdk/app-graph/src/graph-builder.ts";
1087
+ var GraphBuilderTypeId = /* @__PURE__ */ Symbol.for("@dxos/app-graph/GraphBuilder");
1088
+ var GraphBuilderImpl = class {
1089
+ [GraphBuilderTypeId] = GraphBuilderTypeId;
1090
+ pipe() {
1091
+ return Pipeable2.pipeArguments(this, arguments);
1092
+ }
603
1093
  // TODO(wittjosiah): Use Context.
1094
+ /** Active subscriptions keyed by composite ID, cleaned up on node removal. */
604
1095
  _subscriptions = /* @__PURE__ */ new Map();
605
- _extensions = Atom2.make(Record2.empty()).pipe(Atom2.keepAlive, Atom2.withLabel("graph-builder:extensions"));
1096
+ /** Connector updates pending flush, keyed by connector key. */
1097
+ _dirtyConnectors = /* @__PURE__ */ new Map();
1098
+ /** Last-flushed node IDs per connector key, used for edge removal on update. */
1099
+ _connectorPrevious = /* @__PURE__ */ new Map();
1100
+ /** Last-flushed node args per connector key, used for change detection. */
1101
+ _connectorPreviousArgs = /* @__PURE__ */ new Map();
1102
+ /** Whether a dirty-flush task is already scheduled. */
1103
+ _flushScheduled = false;
1104
+ /** Resolves when the current flush completes. */
1105
+ _flushPromise = Promise.resolve();
1106
+ /** Registered builder extensions keyed by extension ID. */
1107
+ _extensions = Atom3.make(Record2.empty()).pipe(Atom3.keepAlive, Atom3.withLabel("graph-builder:extensions"));
1108
+ /** Triggers signalling that a node's resolver has fired at least once. */
606
1109
  _initialized = {};
1110
+ /** Shared atom registry for reactive subscriptions. */
607
1111
  _registry;
1112
+ /** Backing graph with internal accessors for node atoms and construction. */
608
1113
  _graph;
609
1114
  constructor({ registry, ...params } = {}) {
610
1115
  this._registry = registry ?? Registry2.make();
611
- this._graph = new Graph({
1116
+ const graph = make({
612
1117
  ...params,
613
1118
  registry: this._registry,
614
- onExpand: (id, relation) => this._onExpand(id, relation),
1119
+ onExpand: (id, relation2) => this._onExpand(id, relation2),
615
1120
  onInitialize: (id) => this._onInitialize(id),
616
1121
  onRemoveNode: (id) => this._onRemoveNode(id)
617
1122
  });
618
- }
619
- static from(pickle, registry) {
620
- if (!pickle) {
621
- return new _GraphBuilder({
622
- registry
623
- });
624
- }
625
- const { nodes, edges } = JSON.parse(pickle);
626
- return new _GraphBuilder({
627
- nodes,
628
- edges,
629
- registry
630
- });
1123
+ this._graph = graph;
631
1124
  }
632
1125
  get graph() {
633
1126
  return this._graph;
@@ -635,155 +1128,151 @@ var GraphBuilder = class _GraphBuilder {
635
1128
  get extensions() {
636
1129
  return this._extensions;
637
1130
  }
638
- addExtension(extensions) {
639
- flattenExtensions(extensions).forEach((extension) => {
640
- const extensions2 = this._registry.get(this._extensions);
641
- this._registry.set(this._extensions, Record2.set(extensions2, extension.id, extension));
642
- });
643
- return this;
644
- }
645
- removeExtension(id) {
646
- const extensions = this._registry.get(this._extensions);
647
- this._registry.set(this._extensions, Record2.remove(extensions, id));
648
- return this;
649
- }
650
- async explore({ registry = Registry2.make(), source = ROOT_ID, relation = "outbound", visitor }, path = []) {
651
- if (path.includes(source)) {
652
- return;
653
- }
654
- if (!isNode()) {
655
- const { yieldOrContinue } = await import("main-thread-scheduling");
656
- await yieldOrContinue("idle");
657
- }
658
- const node = registry.get(this._graph.nodeOrThrow(source));
659
- const shouldContinue = await visitor(node, [
660
- ...path,
661
- node.id
662
- ]);
663
- if (shouldContinue === false) {
664
- return;
665
- }
666
- const nodes = Object.values(this._registry.get(this._extensions)).filter((extension) => relation === (extension.relation ?? "outbound")).map((extension) => extension.connector).filter(isNonNullable2).flatMap((connector) => registry.get(connector(this._graph.node(source))));
667
- await Promise.all(nodes.map((nodeArg) => {
668
- registry.set(this._graph._node(nodeArg.id), this._graph._constructNode(nodeArg));
669
- return this.explore({
670
- registry,
671
- source: nodeArg.id,
672
- relation,
673
- visitor
674
- }, [
675
- ...path,
676
- node.id
677
- ]);
678
- }));
679
- if (registry !== this._registry) {
680
- registry.reset();
681
- registry.dispose();
1131
+ /** Apply a set of node changes for a single connector key. */
1132
+ _applyConnectorUpdate(key, nodes, previous) {
1133
+ const { id, relation: relation2 } = relationFromConnectorKey(key);
1134
+ const ids = nodes.map((node) => node.id);
1135
+ const removed = previous.filter((pid) => !ids.includes(pid));
1136
+ this._connectorPrevious.set(key, ids);
1137
+ this._connectorPreviousArgs.set(key, nodes);
1138
+ removeEdges(this._graph, removed.map((target) => ({
1139
+ source: id,
1140
+ target,
1141
+ relation: relation2
1142
+ })), true);
1143
+ addNodes(this._graph, nodes);
1144
+ addEdges(this._graph, nodes.map((node) => ({
1145
+ source: id,
1146
+ target: node.id,
1147
+ relation: relation2
1148
+ })));
1149
+ if (ids.length > 0) {
1150
+ const sortedIds = [
1151
+ ...nodes
1152
+ ].sort((a, b) => byPosition(a.properties ?? {}, b.properties ?? {})).map((n) => n.id);
1153
+ sortEdges(this._graph, id, relation2, sortedIds);
682
1154
  }
683
1155
  }
684
- destroy() {
685
- this._subscriptions.forEach((unsubscribe) => unsubscribe());
686
- this._subscriptions.clear();
1156
+ _scheduleDirtyFlush() {
1157
+ if (!this._flushScheduled) {
1158
+ this._flushScheduled = true;
1159
+ this._flushPromise = scheduleTask(() => {
1160
+ this._flushScheduled = false;
1161
+ while (this._dirtyConnectors.size > 0) {
1162
+ const entries = [
1163
+ ...this._dirtyConnectors.entries()
1164
+ ];
1165
+ this._dirtyConnectors.clear();
1166
+ Atom3.batch(() => {
1167
+ for (const [key, { nodes, previous }] of entries) {
1168
+ this._applyConnectorUpdate(key, nodes, previous);
1169
+ }
1170
+ });
1171
+ }
1172
+ }, {
1173
+ strategy: "smooth"
1174
+ });
1175
+ }
687
1176
  }
688
- _resolvers = Atom2.family((id) => {
689
- return Atom2.make((get2) => {
690
- return Function2.pipe(get2(this._extensions), Record2.values, Array.sortBy(byPosition), Array.map(({ resolver }) => resolver), Array.filter(isNonNullable2), Array.map((resolver) => get2(resolver(id))), Array.filter(isNonNullable2), Array.head);
1177
+ _resolvers = Atom3.family((id) => {
1178
+ return Atom3.make((get2) => {
1179
+ return Function2.pipe(get2(this._extensions), Record2.values, Array2.sortBy(byPosition), Array2.map(({ resolver }) => resolver), Array2.filter(isNonNullable2), Array2.map((resolver) => get2(resolver(id))), Array2.filter(isNonNullable2), Array2.head);
691
1180
  });
692
1181
  });
693
- _connectors = Atom2.family((key) => {
694
- return Atom2.make((get2) => {
695
- const [id, relation] = key.split("+");
1182
+ _connectors = Atom3.family((key) => {
1183
+ return Atom3.make((get2) => {
1184
+ const { id, relation: relation2 } = relationFromConnectorKey(key);
696
1185
  const node = this._graph.node(id);
697
- return Function2.pipe(
698
- get2(this._extensions),
699
- Record2.values,
700
- // TODO(wittjosiah): Sort on write rather than read.
701
- Array.sortBy(byPosition),
702
- Array.filter(({ relation: _relation = "outbound" }) => _relation === relation),
703
- Array.map(({ connector }) => connector?.(node)),
704
- Array.filter(isNonNullable2),
705
- Array.flatMap((result) => get2(result))
706
- );
707
- }).pipe(Atom2.withLabel(`graph-builder:connectors:${key}`));
1186
+ const sourceNode = Option3.getOrElse(get2(node), () => void 0);
1187
+ if (!sourceNode) {
1188
+ return [];
1189
+ }
1190
+ const extensions = Function2.pipe(get2(this._extensions), Record2.values, Array2.sortBy(byPosition), Array2.filter((ext) => relationKey(ext.relation ?? "child") === relationKey(relation2) && ext.connector != null));
1191
+ const nodes = [];
1192
+ for (const ext of extensions) {
1193
+ const result = get2(ext.connector(node));
1194
+ nodes.push(...result);
1195
+ }
1196
+ return nodes;
1197
+ }).pipe(Atom3.withLabel(`graph-builder:connectors:${key}`));
708
1198
  });
709
- _onExpand(id, relation) {
1199
+ _onExpand(id, relation2) {
710
1200
  log2("onExpand", {
711
1201
  id,
712
- relation,
1202
+ relation: relation2,
713
1203
  registry: getDebugName(this._registry)
714
1204
  }, {
715
- F: __dxlog_file2,
716
- L: 329,
1205
+ F: __dxlog_file3,
1206
+ L: 261,
717
1207
  S: this,
718
1208
  C: (f, a) => f(...a)
719
1209
  });
720
- const connectors = this._connectors(`${id}+${relation}`);
721
- let previous = [];
722
- const cancel = this._registry.subscribe(connectors, (nodes) => {
1210
+ this._expandRelation(id, relation2);
1211
+ if (relation2.kind === "child" && relation2.direction === "outbound") {
1212
+ expand(this._graph, id, "action");
1213
+ }
1214
+ }
1215
+ _expandRelation(id, relation2) {
1216
+ const key = connectorKey(id, relation2);
1217
+ const connectors = this._connectors(key);
1218
+ const cancel = this._registry.subscribe(connectors, (rawNodes) => {
1219
+ const nodes = qualifyNodeArgs(id)(rawNodes);
1220
+ const previous = this._connectorPrevious.get(key) ?? [];
723
1221
  const ids = nodes.map((n) => n.id);
724
- const removed = previous.filter((id2) => !ids.includes(id2));
725
- previous = ids;
1222
+ if (ids.length === previous.length && ids.every((nodeId, idx) => nodeId === previous[idx])) {
1223
+ const prevArgs = this._connectorPreviousArgs.get(key);
1224
+ if (prevArgs && nodeArgsUnchanged(prevArgs, nodes)) {
1225
+ return;
1226
+ }
1227
+ }
726
1228
  log2("update", {
727
1229
  id,
728
- relation,
729
- ids,
730
- removed
1230
+ relation: relation2,
1231
+ ids
731
1232
  }, {
732
- F: __dxlog_file2,
733
- L: 340,
1233
+ F: __dxlog_file3,
1234
+ L: 288,
734
1235
  S: this,
735
1236
  C: (f, a) => f(...a)
736
1237
  });
737
- const update = () => {
738
- Atom2.batch(() => {
739
- this._graph.removeEdges(removed.map((target) => ({
740
- source: id,
741
- target
742
- })), true);
743
- this._graph.addNodes(nodes);
744
- this._graph.addEdges(nodes.map((node) => relation === "outbound" ? {
745
- source: id,
746
- target: node.id
747
- } : {
748
- source: node.id,
749
- target: id
750
- }));
751
- this._graph.sortEdges(id, relation, nodes.map(({ id: id2 }) => id2));
752
- });
753
- };
754
- if (typeof requestAnimationFrame === "function") {
755
- requestAnimationFrame(update);
756
- } else {
757
- update();
758
- }
1238
+ this._dirtyConnectors.set(key, {
1239
+ nodes,
1240
+ previous
1241
+ });
1242
+ this._scheduleDirtyFlush();
759
1243
  }, {
760
1244
  immediate: true
761
1245
  });
762
- this._subscriptions.set(id, cancel);
1246
+ this._subscriptions.set(subscriptionKey(id, "expand", key), cancel);
763
1247
  }
764
1248
  // TODO(wittjosiah): If the same node is added by a connector, the resolver should probably cancel itself?
765
1249
  async _onInitialize(id) {
766
1250
  log2("onInitialize", {
767
1251
  id
768
1252
  }, {
769
- F: __dxlog_file2,
770
- L: 377,
1253
+ F: __dxlog_file3,
1254
+ L: 300,
771
1255
  S: this,
772
1256
  C: (f, a) => f(...a)
773
1257
  });
774
1258
  const resolver = this._resolvers(id);
775
1259
  const cancel = this._registry.subscribe(resolver, (node) => {
776
1260
  const trigger = this._initialized[id];
777
- Option2.match(node, {
1261
+ Option3.match(node, {
778
1262
  onSome: (node2) => {
779
- this._graph.addNodes([
780
- node2
781
- ]);
1263
+ const connectorOwned = [
1264
+ ...this._connectorPrevious.values()
1265
+ ].some((ids) => ids.includes(id));
1266
+ if (!connectorOwned) {
1267
+ addNodes(this._graph, [
1268
+ node2
1269
+ ]);
1270
+ }
782
1271
  trigger?.wake();
783
1272
  },
784
1273
  onNone: () => {
785
1274
  trigger?.wake();
786
- this._graph.removeNodes([
1275
+ removeNodes(this._graph, [
787
1276
  id
788
1277
  ]);
789
1278
  }
@@ -791,48 +1280,301 @@ var GraphBuilder = class _GraphBuilder {
791
1280
  }, {
792
1281
  immediate: true
793
1282
  });
794
- this._subscriptions.set(id, cancel);
1283
+ this._subscriptions.set(subscriptionKey(id, "init"), cancel);
795
1284
  }
796
1285
  _onRemoveNode(id) {
797
- this._subscriptions.get(id)?.();
798
- this._subscriptions.delete(id);
1286
+ const prefix = `${id}${Separators.primary}`;
1287
+ for (const [key, cleanup] of this._subscriptions) {
1288
+ if (key.startsWith(prefix)) {
1289
+ cleanup();
1290
+ this._subscriptions.delete(key);
1291
+ }
1292
+ }
799
1293
  }
800
1294
  };
801
- var atomFromSignal = (cb) => {
802
- return Atom2.make((get2) => {
803
- const dispose = effect(() => {
804
- get2.setSelf(cb());
1295
+ var make2 = (params) => {
1296
+ return new GraphBuilderImpl(params);
1297
+ };
1298
+ var from = (pickle, registry) => {
1299
+ if (!pickle) {
1300
+ return make2({
1301
+ registry
805
1302
  });
806
- get2.addFinalizer(() => dispose());
807
- return cb();
1303
+ }
1304
+ const { nodes, edges } = JSON.parse(pickle);
1305
+ return make2({
1306
+ nodes,
1307
+ edges,
1308
+ registry
808
1309
  });
809
1310
  };
810
- var observableFamily = Atom2.family((observable) => {
811
- return Atom2.make((get2) => {
812
- const subscription = observable.subscribe((value) => get2.setSelf(value));
813
- get2.addFinalizer(() => subscription.unsubscribe());
814
- return observable.get();
1311
+ var addExtensionImpl = (builder, extensions) => {
1312
+ const internal = builder;
1313
+ flattenExtensions(extensions).forEach((extension) => {
1314
+ const extensions2 = internal._registry.get(internal._extensions);
1315
+ internal._registry.set(internal._extensions, Record2.set(extensions2, extension.id, extension));
1316
+ });
1317
+ return builder;
1318
+ };
1319
+ function addExtension(builderOrExtensions, extensions) {
1320
+ if (extensions === void 0) {
1321
+ const extensions2 = builderOrExtensions;
1322
+ return (builder) => addExtensionImpl(builder, extensions2);
1323
+ } else {
1324
+ const builder = builderOrExtensions;
1325
+ return addExtensionImpl(builder, extensions);
1326
+ }
1327
+ }
1328
+ var removeExtensionImpl = (builder, id) => {
1329
+ const internal = builder;
1330
+ const extensions = internal._registry.get(internal._extensions);
1331
+ internal._registry.set(internal._extensions, Record2.remove(extensions, id));
1332
+ return builder;
1333
+ };
1334
+ function removeExtension(builderOrId, id) {
1335
+ if (typeof builderOrId === "string") {
1336
+ const id2 = builderOrId;
1337
+ return (builder) => removeExtensionImpl(builder, id2);
1338
+ } else {
1339
+ const builder = builderOrId;
1340
+ return removeExtensionImpl(builder, id);
1341
+ }
1342
+ }
1343
+ var exploreImpl = async (builder, options, path = []) => {
1344
+ const internal = builder;
1345
+ const { registry = Registry2.make(), source = RootId, relation: relation2, visitor } = options;
1346
+ if (path.includes(source)) {
1347
+ return;
1348
+ }
1349
+ await yieldOrContinue("idle");
1350
+ const node = registry.get(internal._graph.nodeOrThrow(source));
1351
+ const shouldContinue = await visitor(node, [
1352
+ ...path,
1353
+ node.id
1354
+ ]);
1355
+ if (shouldContinue === false) {
1356
+ return;
1357
+ }
1358
+ const nodes = Function2.pipe(internal._registry.get(internal._extensions), Record2.values, Array2.map((extension) => extension.connector), Array2.filter(isNonNullable2), Array2.flatMap((connector) => registry.get(connector(internal._graph.node(source)))), qualifyNodeArgs(source));
1359
+ await Promise.all(nodes.map((nodeArg) => {
1360
+ registry.set(internal._graph._node(nodeArg.id), internal._graph._constructNode(nodeArg));
1361
+ return exploreImpl(builder, {
1362
+ registry,
1363
+ source: nodeArg.id,
1364
+ relation: relation2,
1365
+ visitor
1366
+ }, [
1367
+ ...path,
1368
+ node.id
1369
+ ]);
1370
+ }));
1371
+ if (registry !== internal._registry) {
1372
+ registry.reset();
1373
+ registry.dispose();
1374
+ }
1375
+ };
1376
+ function explore(builderOrOptions, optionsOrPath, path) {
1377
+ if (typeof builderOrOptions === "object" && "visitor" in builderOrOptions) {
1378
+ const options = builderOrOptions;
1379
+ const path2 = Array2.isArray(optionsOrPath) ? optionsOrPath : void 0;
1380
+ return (builder) => exploreImpl(builder, options, path2);
1381
+ } else {
1382
+ const builder = builderOrOptions;
1383
+ const options = optionsOrPath;
1384
+ const pathArg = path ?? (Array2.isArray(optionsOrPath) ? optionsOrPath : void 0);
1385
+ return exploreImpl(builder, options, pathArg);
1386
+ }
1387
+ }
1388
+ var destroyImpl = (builder) => {
1389
+ const internal = builder;
1390
+ internal._subscriptions.forEach((unsubscribe) => unsubscribe());
1391
+ internal._subscriptions.clear();
1392
+ };
1393
+ function destroy(builder) {
1394
+ if (builder === void 0) {
1395
+ return (builder2) => destroyImpl(builder2);
1396
+ } else {
1397
+ return destroyImpl(builder);
1398
+ }
1399
+ }
1400
+ var flush = (builder) => {
1401
+ return builder._flushPromise;
1402
+ };
1403
+ var createExtensionRaw = (extension) => {
1404
+ const { id, position = "static", relation: relation2 = "child", resolver: _resolver, connector: _connector, actions: _actions, actionGroups: _actionGroups } = extension;
1405
+ const normalizedRelation = normalizeRelation(relation2);
1406
+ const getId = (key) => `${id}/${key}`;
1407
+ const resolver = _resolver && Atom3.family((id2) => _resolver(id2).pipe(Atom3.withLabel(`graph-builder:_resolver:${id2}`)));
1408
+ const connector = _connector && Atom3.family((node) => _connector(node).pipe(Atom3.withLabel(`graph-builder:_connector:${id}`)));
1409
+ const actionGroups = _actionGroups && Atom3.family((node) => _actionGroups(node).pipe(Atom3.withLabel(`graph-builder:_actionGroups:${id}`)));
1410
+ const actions = _actions && Atom3.family((node) => _actions(node).pipe(Atom3.withLabel(`graph-builder:_actions:${id}`)));
1411
+ return [
1412
+ resolver ? {
1413
+ id: getId("resolver"),
1414
+ position,
1415
+ resolver
1416
+ } : void 0,
1417
+ connector ? {
1418
+ id: getId("connector"),
1419
+ position,
1420
+ relation: normalizedRelation,
1421
+ connector: Atom3.family((node) => Atom3.make((get2) => {
1422
+ try {
1423
+ return get2(connector(node));
1424
+ } catch (error) {
1425
+ log2.warn("Error in connector", {
1426
+ id: getId("connector"),
1427
+ node,
1428
+ error
1429
+ }, {
1430
+ F: __dxlog_file3,
1431
+ L: 596,
1432
+ S: void 0,
1433
+ C: (f, a) => f(...a)
1434
+ });
1435
+ return [];
1436
+ }
1437
+ }).pipe(Atom3.withLabel(`graph-builder:connector:${id}`)))
1438
+ } : void 0,
1439
+ actionGroups ? {
1440
+ id: getId("actionGroups"),
1441
+ position,
1442
+ relation: actionRelation(),
1443
+ connector: Atom3.family((node) => Atom3.make((get2) => {
1444
+ try {
1445
+ return get2(actionGroups(node)).map((arg) => ({
1446
+ ...arg,
1447
+ data: actionGroupSymbol,
1448
+ type: ActionGroupType
1449
+ }));
1450
+ } catch (error) {
1451
+ log2.warn("Error in actionGroups", {
1452
+ id: getId("actionGroups"),
1453
+ node,
1454
+ error
1455
+ }, {
1456
+ F: __dxlog_file3,
1457
+ L: 617,
1458
+ S: void 0,
1459
+ C: (f, a) => f(...a)
1460
+ });
1461
+ return [];
1462
+ }
1463
+ }).pipe(Atom3.withLabel(`graph-builder:connector:actionGroups:${id}`)))
1464
+ } : void 0,
1465
+ actions ? {
1466
+ id: getId("actions"),
1467
+ position,
1468
+ relation: actionRelation(),
1469
+ connector: Atom3.family((node) => Atom3.make((get2) => {
1470
+ try {
1471
+ return get2(actions(node)).map((arg) => ({
1472
+ ...arg,
1473
+ type: ActionType
1474
+ }));
1475
+ } catch (error) {
1476
+ log2.warn("Error in actions", {
1477
+ id: getId("actions"),
1478
+ node,
1479
+ error
1480
+ }, {
1481
+ F: __dxlog_file3,
1482
+ L: 634,
1483
+ S: void 0,
1484
+ C: (f, a) => f(...a)
1485
+ });
1486
+ return [];
1487
+ }
1488
+ }).pipe(Atom3.withLabel(`graph-builder:connector:actions:${id}`)))
1489
+ } : void 0
1490
+ ].filter(isNonNullable2);
1491
+ };
1492
+ var runEffectSyncWithFallback = (effect, context2, extensionId, fallback) => {
1493
+ return Effect.runSync(effect.pipe(Effect.provide(context2), Effect.catchAll((error) => {
1494
+ log2.warn("Extension failed", {
1495
+ extension: extensionId,
1496
+ error
1497
+ }, {
1498
+ F: __dxlog_file3,
1499
+ L: 677,
1500
+ S: void 0,
1501
+ C: (f, a) => f(...a)
1502
+ });
1503
+ return Effect.succeed(fallback);
1504
+ })));
1505
+ };
1506
+ var createExtension = (options) => Effect.map(Effect.context(), (context2) => {
1507
+ const { id, match: match3, actions, connector, resolver, relation: relation2, position } = options;
1508
+ const connectorExtension = connector ? createConnectorWithRuntime(id, match3, connector, context2) : void 0;
1509
+ const actionsExtension = actions ? (node) => Atom3.make((get2) => Function2.pipe(get2(node), Option3.flatMap(match3), Option3.map((matched) => runEffectSyncWithFallback(actions(matched, get2), context2, id, []).map((action) => ({
1510
+ ...action,
1511
+ // Attach captured context for action execution.
1512
+ _actionContext: context2
1513
+ }))), Option3.getOrElse(() => []))) : void 0;
1514
+ const resolverExtension = resolver ? (nodeId) => Atom3.make((get2) => runEffectSyncWithFallback(resolver(nodeId, get2), context2, id, null) ?? null) : void 0;
1515
+ return createExtensionRaw({
1516
+ id,
1517
+ relation: relation2,
1518
+ position,
1519
+ connector: connectorExtension,
1520
+ actions: actionsExtension,
1521
+ resolver: resolverExtension
815
1522
  });
816
1523
  });
817
- var atomFromObservable = (observable) => {
818
- return observableFamily(observable);
1524
+ var createConnector = (matcher, factory) => {
1525
+ return (node) => Atom3.make((get2) => Function2.pipe(get2(node), Option3.flatMap(matcher), Option3.map((data) => factory(data, get2)), Option3.getOrElse(() => [])));
1526
+ };
1527
+ var createConnectorWithRuntime = (extensionId, matcher, factory, context2) => {
1528
+ return (node) => Atom3.make((get2) => Function2.pipe(get2(node), Option3.flatMap(matcher), Option3.map((data) => runEffectSyncWithFallback(factory(data, get2), context2, extensionId, [])), Option3.getOrElse(() => [])));
1529
+ };
1530
+ var createTypeExtension = (options) => {
1531
+ const { id, type, actions, connector, relation: relation2, position } = options;
1532
+ return createExtension({
1533
+ id,
1534
+ match: whenEchoType(type),
1535
+ actions,
1536
+ connector,
1537
+ relation: relation2,
1538
+ position
1539
+ });
1540
+ };
1541
+ var qualifyNodeArgs = (parentId) => (nodes) => nodes.map((node) => {
1542
+ validateSegmentId(node.id);
1543
+ const qualified = qualifyId(parentId, node.id);
1544
+ return {
1545
+ ...node,
1546
+ id: qualified,
1547
+ nodes: node.nodes ? qualifyNodeArgs(qualified)(node.nodes) : void 0
1548
+ };
1549
+ });
1550
+ var connectorKey = (id, relation2) => `${id}${Separators.primary}${relationKey(relation2)}`;
1551
+ var relationFromConnectorKey = (key) => {
1552
+ const separatorIndex = key.indexOf(Separators.primary);
1553
+ const id = key.slice(0, separatorIndex);
1554
+ return {
1555
+ id,
1556
+ relation: relationFromKey(key.slice(separatorIndex + 1))
1557
+ };
1558
+ };
1559
+ var subscriptionKey = (id, kind, detail) => detail != null ? `${id}${Separators.primary}${kind}${Separators.primary}${detail}` : `${id}${Separators.primary}${kind}`;
1560
+ var flattenExtensions = (extension, acc = []) => {
1561
+ if (Array2.isArray(extension)) {
1562
+ return [
1563
+ ...acc,
1564
+ ...extension.flatMap((ext) => flattenExtensions(ext, acc))
1565
+ ];
1566
+ } else {
1567
+ return [
1568
+ ...acc,
1569
+ extension
1570
+ ];
1571
+ }
819
1572
  };
820
1573
  export {
821
- ACTION_GROUP_TYPE,
822
- ACTION_TYPE,
823
- Graph,
824
- GraphBuilder,
825
- ROOT_ID,
826
- ROOT_TYPE,
827
- actionGroupSymbol,
828
- atomFromObservable,
829
- atomFromSignal,
830
- createExtension,
831
- flattenExtensions,
832
- getGraph,
833
- isAction,
834
- isActionGroup,
835
- isActionLike,
836
- isGraphNode
1574
+ atoms_exports as CreateAtom,
1575
+ graph_exports as Graph,
1576
+ graph_builder_exports as GraphBuilder,
1577
+ node_exports as Node,
1578
+ node_matcher_exports as NodeMatcher
837
1579
  };
838
1580
  //# sourceMappingURL=index.mjs.map