@arqlet/engine-client 0.6.0 → 0.8.0

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/arqlet.wasm CHANGED
Binary file
package/columns.d.ts CHANGED
@@ -22,6 +22,9 @@ export interface SceneColumns {
22
22
  nodeKind: Uint32Array;
23
23
  /** Values of `SHAPES`. */
24
24
  nodeShape: Uint32Array;
25
+ /** Provisional: each node's `childCount` and `hiddenCount`, `NONE` when absent. */
26
+ nodeChildCount: Uint32Array;
27
+ nodeHiddenCount: Uint32Array;
25
28
 
26
29
  /** Route ids by route index. */
27
30
  routeIds: string[];
package/columns.js CHANGED
@@ -56,12 +56,16 @@ export function columnsOfScene(scene) {
56
56
  const nodeFlags = new Uint32Array(nodes.length);
57
57
  const nodeKind = new Uint32Array(nodes.length);
58
58
  const nodeShape = new Uint32Array(nodes.length);
59
+ const nodeChildCount = new Uint32Array(nodes.length);
60
+ const nodeHiddenCount = new Uint32Array(nodes.length);
59
61
  const nodeKinds = table();
60
62
  nodes.forEach((n, i) => {
61
63
  nodeParent[i] = n.parentId == null ? NONE : at(n.parentId);
62
64
  nodeFlags[i] = (n.container ? 1 : 0) | (n.aggregate ? 2 : 0) | (n.collapsed ? 4 : 0) | (n.invalid ? 8 : 0);
63
65
  nodeKind[i] = nodeKinds.id(n.kind);
64
66
  nodeShape[i] = SHAPES[n.shape] ?? 0;
67
+ nodeChildCount[i] = n.childCount ?? NONE;
68
+ nodeHiddenCount[i] = n.hiddenCount ?? NONE;
65
69
  });
66
70
 
67
71
  const routeSource = new Uint32Array(routes.length);
@@ -137,7 +141,7 @@ export function columnsOfScene(scene) {
137
141
  buses: scene.buses ?? [],
138
142
  bounds: b ? [b.x, b.y, b.width, b.height] : [0, 0, 0, 0],
139
143
  showPorts: Boolean(scene.showPorts),
140
- nodeBounds, nodeParent, nodeFlags, nodeKind, nodeShape,
144
+ nodeBounds, nodeParent, nodeFlags, nodeKind, nodeShape, nodeChildCount, nodeHiddenCount,
141
145
  routeSource, routeTarget, routeWeight, routeFlags, routeOffsets, routePoints,
142
146
  routeKind, routeBackWeight, routeMemberOffsets: Uint32Array.from(routeMemberOffsets), routeMembers: Uint32Array.from(routeMembers),
143
147
  portNode, portEdge, portFlags, portSide, portPosition: points(ports, p => p.position),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@arqlet/engine-client",
3
- "version": "0.6.0",
3
+ "version": "0.8.0",
4
4
  "description": "The Arqlet graph-layout engine as WebAssembly, with a loader, a worker protocol, an ELK-style layout call and preset sequencing. Provisional.",
5
5
  "keywords": [
6
6
  "graph",
@@ -47,6 +47,10 @@
47
47
  "types": "./session.d.ts",
48
48
  "default": "./session.js"
49
49
  },
50
+ "./view-controller.js": {
51
+ "types": "./view-controller.d.ts",
52
+ "default": "./view-controller.js"
53
+ },
50
54
  "./columns.js": {
51
55
  "types": "./columns.d.ts",
52
56
  "default": "./columns.js"
@@ -60,24 +64,27 @@
60
64
  "presets.js",
61
65
  "elk.js",
62
66
  "session.js",
67
+ "view-controller.js",
63
68
  "columns.js",
64
69
  "engine.d.ts",
65
70
  "wasm-client.d.ts",
66
71
  "presets.d.ts",
67
72
  "elk.d.ts",
68
73
  "session.d.ts",
74
+ "view-controller.d.ts",
69
75
  "columns.d.ts",
70
76
  "worker.js",
71
77
  "arqlet.wasm",
72
78
  "README.md",
73
79
  "LICENSE-APACHE",
74
- "LICENSE-MIT"
80
+ "LICENSE-MIT",
81
+ "THIRD_PARTY_NOTICES.md"
75
82
  ],
76
83
  "publishConfig": {
77
84
  "access": "public"
78
85
  },
79
86
  "dependencies": {
80
- "@arqlet/contracts": "^0.6.0"
87
+ "@arqlet/contracts": "^0.8.0"
81
88
  },
82
89
  "scripts": {
83
90
  "test": "node --test"
package/session.d.ts CHANGED
@@ -1,8 +1,33 @@
1
- import type {Graph, GraphNeighbourhood, GraphPatch, GraphTrace, Hidden, NeighbourhoodAnswer, Overview, OverviewRequest, Scene, Snapshot, TraceAnswer} from '@arqlet/contracts';
1
+ import type {DetailsAnswer, FindAnswer, Graph, GraphNeighbourhood, GraphPatch, GraphTrace, Hidden, NeighbourhoodAnswer, Overview, OverviewRequest, Scene, Snapshot, TraceAnswer} from '@arqlet/contracts';
2
2
  import type {SceneColumns} from './columns.js';
3
3
  import type {EngineRequest, EngineResponse, Run} from './wasm-client.js';
4
4
 
5
5
  /** An engine answer as the session reports it. `stale`: an import or reset overtook the change, nothing was applied. */
6
+ /** Provisional (drag API): a move gesture of `Session.drag`. */
7
+ export interface DragHandle {
8
+ /** The node being moved. */
9
+ readonly node: string;
10
+ /** Whether the gesture still takes positions (not dropped, cancelled or refused). */
11
+ readonly active: boolean;
12
+ /** Steps sent, positions replaced by a newer one before they were sent, and steps the engine applied. */
13
+ readonly stats: {sent: number; coalesced: number; applied: number};
14
+ /** The answer to picking the node up (the first step). */
15
+ readonly begun: Promise<SessionResult>;
16
+ /**
17
+ * A newer position (and optionally newer positions of the others). Positions that arrive while one is computed replace
18
+ * each other: only the newest is sent. Resolves with the answer of the step that carried it, or `{ok: true, unchanged}`
19
+ * when a newer position took its place.
20
+ */
21
+ move(position: {x: number; y: number}, others?: Record<string, {x: number; y: number}>): Promise<SessionResult>;
22
+ /**
23
+ * Applies the last position and ends the gesture; the node stays pinned there, or with `release` the layout may move it
24
+ * again. With `settle`, force-directed areas settle afterwards (`op: settle`).
25
+ */
26
+ drop(init?: {release?: boolean; settle?: boolean}): Promise<SessionResult>;
27
+ /** Ends the gesture and puts the node (and the others) back where they were. */
28
+ cancel(): Promise<SessionResult>;
29
+ }
30
+
6
31
  export interface SessionResult {
7
32
  ok: boolean;
8
33
  snapshot?: Snapshot;
@@ -12,7 +37,95 @@ export interface SessionResult {
12
37
  unchanged?: boolean;
13
38
  }
14
39
 
40
+ /** Provisional (ADR 0023, R1): one change of a session's content. Values are JSON; an integer stays an integer. */
41
+ export interface PayloadChange {
42
+ set?: {nodes?: Record<string, Record<string, unknown>>; edges?: Record<string, Record<string, unknown>>};
43
+ unset?: {nodes?: Record<string, string[]>; edges?: Record<string, string[]>};
44
+ clear?: boolean;
45
+ expectedContentRevision?: number;
46
+ }
47
+
48
+ /** Provisional (ADR 0023, R7): what a session holds, in estimated heap bytes per part. */
49
+ export interface SessionMemory {
50
+ ok: true;
51
+ estimated: true;
52
+ parts: Record<string, number>;
53
+ total: number;
54
+ nodes: number;
55
+ perNode: number;
56
+ /** From the WASM engine: the module's live heap, counted. */
57
+ heapBytes?: number;
58
+ /** From the WASM engine: the size of its linear memory, which is never given back. */
59
+ linearMemoryBytes?: number;
60
+ }
61
+
62
+ /** Provisional (ADR 0023, R2): one change group: a patch of the structure, a payload of the content, or both. */
63
+ export interface ChangeGroup {
64
+ patch?: GraphPatch;
65
+ payload?: Omit<PayloadChange, 'expectedContentRevision'>;
66
+ expectedSequence?: number;
67
+ }
68
+
69
+ /** The content's revision and counts after a change; ids the structure does not have are kept and counted. */
70
+ export interface PayloadAnswer {
71
+ ok: true;
72
+ contentRevision: number;
73
+ nodes: number;
74
+ edges: number;
75
+ keys: string[];
76
+ unknownNodes: number;
77
+ unknownEdges: number;
78
+ }
79
+
80
+ /** Provisional: a look into a container (`peek`): its contents as a scene, and the border edges per child shown. */
81
+ export interface PeekAnswer {
82
+ nodeId: string;
83
+ children: number;
84
+ shown: number;
85
+ omitted: number;
86
+ external: Record<string, {incoming: number; outgoing: number}>;
87
+ scene: Scene;
88
+ }
89
+
90
+ /** What `details` asks about: a node, or an edge (a drawn line or an edge of the source graph). */
91
+ export type DetailTarget = {nodeId: string; edgeId?: never} | {edgeId: string; nodeId?: never};
92
+
15
93
  /** The answer of a read-only request (`trace`, `neighbourhood`): its fields beside `ok: true`, or the error. */
94
+ /** Provisional (ADR 0021, M5b): what a query is given besides its text. */
95
+ export interface QueryInit {
96
+ /** The values of the `$name` parameters (JSON values; a map is refused). */
97
+ params?: Record<string, unknown>;
98
+ /** Also map the answer onto the current view (`shown`); costs a few milliseconds on a large view. */
99
+ view?: boolean;
100
+ /** Execution limits (steps of work, rows held, hops of an unbounded `*`). */
101
+ maxSteps?: number;
102
+ maxRows?: number;
103
+ maxHops?: number;
104
+ }
105
+
106
+ /** A value in a row of a query answer: a JSON value, a node as `{node: id}`, an edge as `{edge: id}`, or a list. */
107
+ export type QueryValue = null | boolean | number | string | {node: string} | {edge: string} | QueryValue[];
108
+
109
+ /** Provisional (ADR 0021, M5b): the answer of a query. */
110
+ export interface QueryAnswer {
111
+ columns: string[];
112
+ rows: QueryValue[][];
113
+ rowCount: number;
114
+ /** The ids of the nodes and edges in the rows, once each, in the order they first appear. */
115
+ nodes: string[];
116
+ edges: string[];
117
+ /** What the query could see: the session's source graph (resolved edges only). */
118
+ graph: {nodes: number; edges: number};
119
+ /** The content's revision, when the session has content. */
120
+ contentRevision?: number;
121
+ /** Content for ids the graph does not have (kept, ignored by the query). */
122
+ ignoredContent?: number;
123
+ /** Content values the query layer has no type for (a map), read as null. */
124
+ skippedValues?: number;
125
+ /** With `view: true`: the box that shows each node and the drawn line that carries each edge (null when none). */
126
+ shown?: {nodes: Record<string, string | null>; edges: Record<string, string | null>};
127
+ }
128
+
16
129
  export type ReadAnswer<T> = ({ok: true} & T) | {ok: false; error: string};
17
130
 
18
131
  /** Provisional: one graph, its current snapshot, and changes applied in order with revision checks. */
@@ -29,6 +142,11 @@ export interface Session {
29
142
  */
30
143
  import(graph: Graph, init?: {limit?: number; options?: Record<string, unknown>}): Promise<SessionResult>;
31
144
  /** Drops the snapshot; changes still under way resolve as stale. */
145
+ /**
146
+ * Provisional: continues from `snapshot` (made by the host), after the changes queued before; with `reset` (another
147
+ * view) at once, the changes still under way resolving as stale.
148
+ */
149
+ load(snapshot: Snapshot, options?: {reset?: boolean}): Promise<SessionResult>;
32
150
  reset(): void;
33
151
  /** Whether container `id` is collapsed in the current snapshot. */
34
152
  isCollapsed(id: string): boolean;
@@ -55,12 +173,62 @@ export interface Session {
55
173
  nodeId: string | string[],
56
174
  init?: {hops?: number; direction?: 'out' | 'in' | 'both'; edgeKinds?: string[]},
57
175
  ): Promise<ReadAnswer<NeighbourhoodAnswer>>;
176
+ /**
177
+ * Provisional (read only): what the engine knows about a node or an edge (a drawn line or an edge of the source graph):
178
+ * the containers above a node and the box that shows it, what a collapsed box holds, the edges a line stands for.
179
+ */
180
+ details(target: DetailTarget, init?: {limit?: number}): Promise<ReadAnswer<DetailsAnswer>>;
181
+ /**
182
+ * Provisional (read only): the nodes whose label or id contains `query` (ignoring case), best first, with the box that
183
+ * shows each; at most `limit` (default 20), only `nodeKinds` if given.
184
+ */
185
+ find(query: string, init?: {limit?: number; nodeKinds?: string[]; key?: string}): Promise<ReadAnswer<FindAnswer>>;
186
+ /**
187
+ * Provisional (ADR 0021, M5b; read only): an openCypher query over the session's source graph and its content. Needs an
188
+ * engine built with the cargo feature `query`; otherwise `{ok: false, error}` says so. See {@link QueryAnswer}.
189
+ */
190
+ query(text: string, init?: QueryInit): Promise<ReadAnswer<QueryAnswer>>;
191
+ /**
192
+ * Provisional (ADR 0023, R1): sets, unsets or clears properties in the session's content (beside the snapshot, never in
193
+ * it). Needs a resident session.
194
+ */
195
+ payload(change: PayloadChange): Promise<PayloadAnswer | {ok: false; error?: string; stale?: true}>;
196
+ /** Provisional (ADR 0023, R2): structure and content changed as one group; the answer has its `sequence`. */
197
+ change(group: ChangeGroup): Promise<SessionResult & {sequence?: number; contentRevision?: number}>;
198
+ /** Provisional (ADR 0023, R2): the change groups after `sequence`, or `resync` when the log no longer has them. */
199
+ changesSince(sequence: number): Promise<{ok: true; sequence: number; changes?: Array<ChangeGroup & {sequence: number}>; resync?: true} | {ok: false; error?: string}>;
200
+ /**
201
+ * Provisional (ADR 0023, R7): moves a resident session to another engine (a new worker) so that the old one can be
202
+ * ended and its memory comes back; the view, the content and the change log's number move with it.
203
+ */
204
+ recycle(newEngine: Run): Promise<{ok: true; unchanged: true; sequence: number; contentRevision: number} | {ok: false; error?: string; stale?: true}>;
205
+ /** Provisional (ADR 0023, R7): what the session holds, part by part (estimated), and from WASM the module's heap. */
206
+ memory(): Promise<SessionMemory | {ok: false; error?: string}>;
207
+ /** Provisional (ADR 0023, R7): gives parts back; the snapshot stays. */
208
+ release(parts: Array<'content' | 'changeLog' | 'columns' | 'overview'>, init?: {keys?: string[]}): Promise<(SessionMemory & {released: number}) | {ok: false; error?: string; stale?: true}>;
209
+ /** Provisional (ADR 0023, R2): the whole content and the log's sequence (for a resync). */
210
+ content(): Promise<{ok: true; contentRevision: number; sequence: number; nodes: Record<string, Record<string, unknown>>; edges: Record<string, Record<string, unknown>>} | {ok: false; error?: string}>;
211
+ /** Provisional (read only): a look into a collapsed container without opening it. */
212
+ peek(nodeId: string, init?: {limit?: number}): Promise<ReadAnswer<PeekAnswer>>;
58
213
  /**
59
214
  * Provisional: changes the graph without a new import (removals first; a removed node takes what it holds and its
60
215
  * edges along); the view keeps its state and is laid out as a toggle lays it out (abstracting views) or again from
61
216
  * where it was.
62
217
  */
63
218
  patch(patch: GraphPatch): Promise<SessionResult>;
219
+ /**
220
+ * Provisional (drag API): pins `nodeId` at `position` (in its parent's frame, as `toReactFlow` gives `position`), or
221
+ * where it is now. The layout keeps a pinned node in place.
222
+ */
223
+ pin(nodeId: string, position?: {x: number; y: number}): Promise<SessionResult>;
224
+ /** Provisional (drag API): releases the pin of `nodeId`; the layout may move it again. */
225
+ unpin(nodeId: string): Promise<SessionResult>;
226
+ /**
227
+ * Provisional (drag API): starts moving leaf `nodeId` to `position` (in its parent's frame). `others` maps further
228
+ * nodes moved with it (a selection) to their positions; the set is fixed for the gesture. Each applied step changes the
229
+ * session's snapshot (`onChange`); other changes wait until the gesture ends.
230
+ */
231
+ drag(nodeId: string, position: {x: number; y: number}, init?: {others?: Record<string, {x: number; y: number}>}): DragHandle;
64
232
  /** Provisional: opens the groups that hold `nodeIds`; with `partial` (default true) only as far as needed. */
65
233
  reveal(nodeIds: string[], init?: {partial?: boolean}): Promise<SessionResult>;
66
234
  /** Provisional: hides nodes by kind or id (with what they hold) and edges by kind, keeping the place of the rest, or
@@ -112,6 +280,15 @@ export function createSession(
112
280
  * Wraps a worker of `createEngineWorker` as an asynchronous run. `onPublication` receives the progressive publications
113
281
  * of a running request.
114
282
  */
283
+ /** Provisional: what `createViewController({refine})` runs refinements with. */
284
+ export type RefineRun = (
285
+ request: EngineRequest,
286
+ init?: {onPublication?: (publication: {jobId: string; sequence: number; snapshot: Snapshot}) => void; signal?: AbortSignal},
287
+ ) => Promise<EngineResponse>;
288
+
289
+ /** Provisional: a refinement engine on its own worker, with each progressive request's intermediate results. */
290
+ export function workerRefineRun(worker: Worker): RefineRun;
291
+
115
292
  export function workerRun(
116
293
  worker: Worker,
117
294
  init?: {onPublication?: (requestId: number, message: unknown) => void},
package/session.js CHANGED
@@ -12,6 +12,34 @@ import {columnsOfScene} from './columns.js';
12
12
  * Wraps a worker of `createEngineWorker` as an asynchronous `run`: each request gets an id, and the answer with that id
13
13
  * resolves it. Progressive publications are passed to `onPublication(requestId, message)`.
14
14
  */
15
+ /**
16
+ * Provisional: a refinement engine for `createViewController({refine})` on its own worker (`createEngineWorker`), so that
17
+ * refinement never waits behind the interactive steps: `(request, {onPublication, signal}) => Promise<answer>`, with the
18
+ * intermediate results of a progressive request (`refineProgressive`) handed to that request's `onPublication`. An
19
+ * aborted request resolves at once as cancelled; the worker finishes it in the background and its answer is dropped.
20
+ */
21
+ export function workerRefineRun(worker) {
22
+ let next = 0;
23
+ const waiting = new Map();
24
+ worker.addEventListener('message', ({data}) => {
25
+ const pending = waiting.get(data?.requestId);
26
+ if (!pending) return;
27
+ if (data.publication !== undefined) { pending.onPublication?.(data.publication); return; }
28
+ waiting.delete(data.requestId);
29
+ const {requestId, ...response} = data;
30
+ pending.resolve(response);
31
+ });
32
+ return (request, {onPublication, signal} = {}) => new Promise(resolve => {
33
+ const requestId = ++next;
34
+ if (signal?.aborted) { resolve({ok: false, cancelled: true}); return; }
35
+ waiting.set(requestId, {resolve, onPublication});
36
+ signal?.addEventListener('abort', () => {
37
+ if (waiting.delete(requestId)) resolve({ok: false, cancelled: true});
38
+ }, {once: true});
39
+ worker.postMessage({requestId, request});
40
+ });
41
+ }
42
+
15
43
  export function workerRun(worker, {onPublication} = {}) {
16
44
  let next = 0;
17
45
  const waiting = new Map();
@@ -85,14 +113,18 @@ export function httpRun(base = '/api', {fetchImpl = globalThis.fetch} = {}) {
85
113
  * chooses: `'auto'` (default) where the engine can, `true` always (an error without it), `false` never (every request
86
114
  * sends the snapshot, as before 0.4).
87
115
  */
88
- export function createSession(run, {onChange, resident: wanted = 'auto'} = {}) {
116
+ let dragCounter = 0;
117
+
118
+ export function createSession(engine, {onChange, resident: wanted = 'auto'} = {}) {
119
+ // The engine and, when resident, its session: replaced by `recycle` (a new worker, ADR 0023 R7).
120
+ let run = engine;
89
121
  let snapshot = null;
90
122
  let generation = 0;
91
123
  let queue = Promise.resolve();
92
124
  const scenes = new WeakMap();
93
125
  if (wanted === true && !run.openSession) throw Error('This engine has no resident sessions');
94
126
  const resident = wanted === true || (wanted === 'auto' && typeof run.openSession === 'function');
95
- const opened = resident ? Promise.resolve(run.openSession()) : null;
127
+ let opened = resident ? Promise.resolve(run.openSession()) : null;
96
128
  // The engine call: with a resident session, the request goes to it and its answer is turned into the shape of an
97
129
  // answer with a snapshot (the state), its scene remembered for that state.
98
130
  const call = async request => {
@@ -102,7 +134,9 @@ export function createSession(run, {onChange, resident: wanted = 'auto'} = {}) {
102
134
  if (!answer.ok || answer.revision === undefined) return answer;
103
135
  const state = {revision: answer.revision, layoutVersion: answer.layoutVersion, collapsedIds: answer.collapsedIds};
104
136
  if (answer.scene) scenes.set(state, answer.scene);
105
- return {ok: true, snapshot: state};
137
+ // The change log's number and the content's revision of a source change (ADR 0023, R1 and R2), when the answer has them.
138
+ return {ok: true, snapshot: state, ...(answer.sequence !== undefined ? {sequence: answer.sequence} : {}),
139
+ ...(answer.contentRevision !== undefined ? {contentRevision: answer.contentRevision} : {})};
106
140
  };
107
141
 
108
142
  // Runs `step` after every change before it; its answer counts only if no import or reset came in between.
@@ -150,10 +184,25 @@ export function createSession(run, {onChange, resident: wanted = 'auto'} = {}) {
150
184
  * Any change still under way is dropped.
151
185
  */
152
186
  import(graph, {limit = Math.min(graph.nodes.length, MAX_VIEW_LIMIT), options} = {}) {
187
+ // A new view does not wait for the changes still under way: they resolve as stale.
153
188
  generation++;
189
+ queue = Promise.resolve();
154
190
  return enqueue(() => call({op: 'import', graph, limit, ...(options ? {options} : {})}));
155
191
  },
156
192
 
193
+ /**
194
+ * Provisional: continues from `snapshot` (a host made it: a drag, a refinement, a document it loaded), after the changes
195
+ * queued before; with a resident session the engine takes it over (`load`).
196
+ */
197
+ load(snapshot, {reset = false} = {}) {
198
+ // With `reset` (another view) it does not wait for the changes still under way: they resolve as stale.
199
+ if (reset) {
200
+ generation++;
201
+ queue = Promise.resolve();
202
+ }
203
+ return enqueue(() => (resident ? call({op: 'load', snapshot}) : {ok: true, snapshot}));
204
+ },
205
+
157
206
  /** Drops the snapshot; changes still under way resolve as stale. */
158
207
  reset() {
159
208
  generation++;
@@ -193,6 +242,108 @@ export function createSession(run, {onChange, resident: wanted = 'auto'} = {}) {
193
242
  * `{ok, nodes, edges, hops, visible: {nodes, routes}, distance}` as for `trace`; `nodes` can go to `reveal`.
194
243
  * `direction`: `out`, `in` or `both` (default); `edgeKinds`: follow only edges of these kinds.
195
244
  */
245
+ /**
246
+ * Provisional (search, read only): the nodes of the source graph whose label or id contains `query` (ignoring case),
247
+ * best first, with the containers above each and the box that shows it (also inside collapsed groups); at most
248
+ * `limit` (default 20), only `nodeKinds` if given; `total` counts them all.
249
+ */
250
+ /**
251
+ * Provisional (ADR 0023, R1): sets, unsets or clears properties of nodes and edges in the session's content, as one
252
+ * change: `{set: {nodes: {id: {key: value}}, edges: {…}}, unset: {nodes: {id: [key]}}, clear, expectedContentRevision}`.
253
+ * Kept beside the snapshot (never in it; layout never reads it); `details` answers the properties, `find` with `key`
254
+ * searches one. Needs a resident session; a new import starts the content empty.
255
+ */
256
+ payload(change = {}) {
257
+ if (!resident) return Promise.resolve({ok: false, error: 'payload needs a resident session'});
258
+ return enqueue(() => call({op: 'payload', ...change}));
259
+ },
260
+
261
+ /**
262
+ * Provisional (ADR 0023, R2): a change of structure and content as one group, all of it or nothing:
263
+ * `{patch: {nodes, edges, removeNodes, removeEdges, memberships}, payload: {set, unset, clear}, expectedSequence}`.
264
+ * The answer carries the group's `sequence` in the session's change log. Needs a resident session.
265
+ */
266
+ change(group = {}) {
267
+ if (!resident) return Promise.resolve({ok: false, error: 'change needs a resident session'});
268
+ return enqueue(() => call({op: 'change', ...group}));
269
+ },
270
+
271
+ /**
272
+ * Provisional (ADR 0023, R2, read only): the change groups after `sequence` (`{sequence, changes}`), or `{resync: true}`
273
+ * when some of them are no longer in the log (then take a new snapshot and the `content`).
274
+ */
275
+ async changesSince(sequence) {
276
+ if (!resident) return {ok: false, error: 'changesSince needs a resident session'};
277
+ return call({op: 'changesSince', sequence});
278
+ },
279
+
280
+ /**
281
+ * Provisional (ADR 0023, R7, read only): what the session holds, part by part, in estimated heap bytes (`parts`,
282
+ * `total`, `perNode`); from the WASM engine also the module's live heap (`heapBytes`) and its linear memory
283
+ * (`linearMemoryBytes`), which WebAssembly never gives back (only a new worker does).
284
+ */
285
+ async memory() {
286
+ if (!resident) return {ok: false, error: 'memory needs a resident session'};
287
+ return call({op: 'memory'});
288
+ },
289
+
290
+ /**
291
+ * Provisional (ADR 0023, R7): gives parts back: `content` (all, or only `keys`), `changeLog` (a replica behind it then
292
+ * resyncs), `columns`, `overview`. The snapshot stays; the answer is `memory` after it, with `released`.
293
+ */
294
+ release(parts, {keys} = {}) {
295
+ if (!resident) return Promise.resolve({ok: false, error: 'release needs a resident session'});
296
+ return enqueue(() => call({op: 'release', parts, ...(keys ? {keys} : {})}));
297
+ },
298
+
299
+ /** Provisional (ADR 0023, R2, read only): the whole content and the log's sequence, for a replica that resyncs. */
300
+ async content() {
301
+ if (!resident) return {ok: false, error: 'content needs a resident session'};
302
+ return call({op: 'content'});
303
+ },
304
+
305
+ /**
306
+ * Provisional (read only): a look into the collapsed container `nodeId` without opening it: its contents laid out on
307
+ * their own as a small scene (the containers inside collapsed, at most `limit` direct children, default 50), and per
308
+ * child shown the edges that cross the container's border (`external`).
309
+ */
310
+ async peek(nodeId, {limit} = {}) {
311
+ if (!snapshot) return {ok: false, error: 'Nothing imported yet.'};
312
+ return call({op: 'peek', snapshot, nodeId, ...(limit !== undefined ? {limit} : {})});
313
+ },
314
+
315
+ async find(query, {limit, nodeKinds, key} = {}) {
316
+ if (!snapshot) return {ok: false, error: 'Nothing imported yet.'};
317
+ return call({op: 'find', snapshot, query, ...(limit !== undefined ? {limit} : {}), ...(nodeKinds ? {nodeKinds} : {}),
318
+ ...(key ? {key} : {})});
319
+ },
320
+
321
+ /**
322
+ * Provisional (ADR 0021, M5b; read only, needs an engine built with the cargo feature `query`): an openCypher query over
323
+ * the session's source graph and its content (`payload`): `{ok, columns, rows, rowCount, nodes, edges, graph, ...}`.
324
+ * Nodes and edges in `rows` are `{node: id}` and `{edge: id}`; `nodes` and `edges` list the ids once each. `params`
325
+ * are the `$name` values; `maxSteps`, `maxRows` and `maxHops` lower or raise the execution limits; with `view: true`
326
+ * the answer also has `shown`, the box that shows each node and the line that carries each edge. A failure is
327
+ * `{ok: false, error: 'query <class>: ...'}` with the class `syntax`, `unsupported`, `runtime` or `limit`. A query
328
+ * sees the source graph the engine kept (for a bounded import the selection; `graph` gives its size).
329
+ */
330
+ async query(text, {params, view, maxSteps, maxRows, maxHops} = {}) {
331
+ if (!snapshot) return {ok: false, error: 'Nothing imported yet.'};
332
+ return call({op: 'query', snapshot, query: text, ...(params ? {params} : {}), ...(view ? {view: true} : {}),
333
+ ...(maxSteps !== undefined ? {maxSteps} : {}), ...(maxRows !== undefined ? {maxRows} : {}),
334
+ ...(maxHops !== undefined ? {maxHops} : {})});
335
+ },
336
+
337
+ /**
338
+ * Provisional (view details, read only): what the engine knows about a node (`{nodeId}`) or an edge (`{edgeId}`, a
339
+ * drawn line or an edge of the source graph): the containers above a node and the box that shows it, what a collapsed
340
+ * box holds, the edges a line stands for in either direction (at most `limit` ids each, counts complete).
341
+ */
342
+ async details(target, {limit} = {}) {
343
+ if (!snapshot) return {ok: false, error: 'Nothing imported yet.'};
344
+ return call({op: 'details', snapshot, ...target, ...(limit !== undefined ? {limit} : {})});
345
+ },
346
+
196
347
  async neighbourhood(nodeId, {hops, direction, edgeKinds} = {}) {
197
348
  if (!snapshot) return {ok: false, error: 'Nothing imported yet.'};
198
349
  return call({op: 'neighbourhood', snapshot, ...(Array.isArray(nodeId) ? {nodeIds: nodeId} : {nodeId}),
@@ -206,6 +357,79 @@ export function createSession(run, {onChange, resident: wanted = 'auto'} = {}) {
206
357
  */
207
358
  patch(patch) { return change({op: 'patch', patch}); },
208
359
 
360
+ /**
361
+ * Provisional (drag API): pins `nodeId` at `position` (in its parent's frame, as `toReactFlow` gives `position`), or
362
+ * where it is now; the layout keeps it there.
363
+ */
364
+ pin(nodeId, position) { return change({op: 'pin', nodeId, ...(position ? {position} : {})}); },
365
+
366
+ /** Provisional (drag API): releases the pin of `nodeId`; the layout may move it again. */
367
+ unpin(nodeId) { return change({op: 'pin', nodeId, unpin: true}); },
368
+
369
+ /**
370
+ * Provisional (drag API): starts moving leaf `nodeId` to `position` (in its parent's frame). `others` maps further
371
+ * nodes moved with it (a selection) to their positions; the set is fixed for the gesture. Returns a handle:
372
+ * `move(position, others?)` sends a newer position (positions that arrive while one is computed replace each other, so
373
+ * only the newest is sent); `drop({release, settle})` applies the last position and ends the gesture, keeping the node
374
+ * pinned there (or releasing the pin with `release`), then with `settle` lets force-directed areas settle; `cancel()`
375
+ * puts the node back. Every applied step changes the session's snapshot (`onChange`), so a host redraws from
376
+ * `scene()`. Other changes wait until the gesture ends.
377
+ */
378
+ drag(nodeId, position, {others = {}} = {}) {
379
+ const id = `drag-${++dragCounter}`;
380
+ let seq = 0, pending = null, inFlight = null, ended = false, refused = null;
381
+ const stats = {sent: 0, coalesced: 0, applied: 0};
382
+ const step = (phase, at, release = false) => {
383
+ seq += 1;
384
+ stats.sent += 1;
385
+ return enqueue(() => send({op: 'move', gestureId: id, seq, phase, node: nodeId, position: at, release,
386
+ ...(Object.keys(others).length ? {others} : {})})).then(answer => {
387
+ if (answer.ok) stats.applied += 1; else refused ??= answer;
388
+ return answer;
389
+ });
390
+ };
391
+ // One step at a time; the newest pending position goes next.
392
+ const pump = () => {
393
+ if (inFlight || !pending || refused) return inFlight;
394
+ const at = pending;
395
+ pending = null;
396
+ inFlight = step('update', at).finally(() => { inFlight = null; pump(); });
397
+ return inFlight;
398
+ };
399
+ const begun = step('begin', position);
400
+ const end = async (phase, release, settle) => {
401
+ if (ended) return {ok: false, error: 'The gesture has ended.'};
402
+ ended = true;
403
+ await begun;
404
+ while (inFlight) await inFlight;
405
+ if (phase === 'cancel') pending = null;
406
+ if (pending && !refused) { const at = pending; pending = null; await step('update', at); }
407
+ if (refused) return refused;
408
+ const answer = await step(phase, null, release);
409
+ if (answer.ok && settle) return change({op: 'settle'});
410
+ return answer;
411
+ };
412
+ return {
413
+ /** The node being moved. */
414
+ node: nodeId,
415
+ /** Whether the gesture still takes positions. */
416
+ get active() { return !ended && !refused; },
417
+ /** Steps sent, positions replaced by newer ones before they were sent, and steps applied. */
418
+ get stats() { return {...stats}; },
419
+ /** The answer of the first step (the engine's view after the node was picked up). */
420
+ begun,
421
+ move(at, moved) {
422
+ if (ended || refused) return Promise.resolve(refused ?? {ok: false, error: 'The gesture has ended.'});
423
+ if (pending) stats.coalesced += 1;
424
+ pending = at;
425
+ if (moved) others = moved;
426
+ return begun.then(() => pump() ?? {ok: true, unchanged: true});
427
+ },
428
+ drop({release = false, settle = false} = {}) { return end('finish', release, settle); },
429
+ cancel() { return end('cancel', false, false); },
430
+ };
431
+ },
432
+
209
433
  /** Provisional: opens the groups that hold `nodeIds`; with `partial` (default) only as far as needed. */
210
434
  reveal(nodeIds, {partial = true} = {}) { return change({op: 'reveal', nodeIds, partial}); },
211
435
 
@@ -257,6 +481,39 @@ export function createSession(run, {onChange, resident: wanted = 'auto'} = {}) {
257
481
  /** Whether the snapshot stays in the engine (see `createSession`). */
258
482
  get resident() { return resident; },
259
483
 
484
+ /**
485
+ * Provisional (ADR 0023, R7): moves a resident session to another engine (`newEngine`, typically a new worker), so that
486
+ * the old one can be ended and its memory comes back: WebAssembly never shrinks its linear memory, a new worker starts
487
+ * small. The snapshot, the content (with its revision) and the change log's number move; the log's groups do not, so
488
+ * a replica behind that number resyncs. The engines give identical results, so the view does not change. Runs after
489
+ * the changes queued before it; on a refusal the session stays on the old engine. The host ends the old worker after.
490
+ */
491
+ recycle(newEngine) {
492
+ if (!resident) return Promise.resolve({ok: false, error: 'recycle needs a resident session'});
493
+ if (typeof newEngine?.openSession !== 'function') {
494
+ return Promise.resolve({ok: false, error: 'recycle needs an engine with resident sessions'});
495
+ }
496
+ return enqueue(async () => {
497
+ const old = await opened;
498
+ const exported = await old.run({op: 'export'});
499
+ if (!exported.ok) return exported;
500
+ const content = await old.run({op: 'content'});
501
+ if (!content.ok) return content;
502
+ const fresh = await newEngine.openSession();
503
+ // No scene in the answer: the host has it already, and writing it would grow the new engine's memory.
504
+ const loaded = await fresh.run({op: 'load', scene: false, snapshot: exported.snapshot, sequence: content.sequence,
505
+ content: {contentRevision: content.contentRevision, nodes: content.nodes, edges: content.edges}});
506
+ if (!loaded.ok) {
507
+ await fresh.close?.();
508
+ return loaded;
509
+ }
510
+ await old.close?.();
511
+ run = newEngine;
512
+ opened = Promise.resolve(fresh);
513
+ return {ok: true, unchanged: true, sequence: content.sequence, contentRevision: content.contentRevision};
514
+ });
515
+ },
516
+
260
517
  /** Ends a resident session in the engine (frees its snapshot). The session object is not usable afterwards. */
261
518
  async close() {
262
519
  generation++;