@arqlet/engine-client 0.7.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@arqlet/engine-client",
3
- "version": "0.7.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.7.0"
87
+ "@arqlet/contracts": "^0.8.0"
81
88
  },
82
89
  "scripts": {
83
90
  "test": "node --test"
package/session.d.ts CHANGED
@@ -1,4 +1,4 @@
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
 
@@ -37,7 +37,95 @@ export interface SessionResult {
37
37
  unchanged?: boolean;
38
38
  }
39
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
+
40
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
+
41
129
  export type ReadAnswer<T> = ({ok: true} & T) | {ok: false; error: string};
42
130
 
43
131
  /** Provisional: one graph, its current snapshot, and changes applied in order with revision checks. */
@@ -54,6 +142,11 @@ export interface Session {
54
142
  */
55
143
  import(graph: Graph, init?: {limit?: number; options?: Record<string, unknown>}): Promise<SessionResult>;
56
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>;
57
150
  reset(): void;
58
151
  /** Whether container `id` is collapsed in the current snapshot. */
59
152
  isCollapsed(id: string): boolean;
@@ -80,6 +173,43 @@ export interface Session {
80
173
  nodeId: string | string[],
81
174
  init?: {hops?: number; direction?: 'out' | 'in' | 'both'; edgeKinds?: string[]},
82
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>>;
83
213
  /**
84
214
  * Provisional: changes the graph without a new import (removals first; a removed node takes what it holds and its
85
215
  * edges along); the view keeps its state and is laid out as a toggle lays it out (abstracting views) or again from
@@ -150,6 +280,15 @@ export function createSession(
150
280
  * Wraps a worker of `createEngineWorker` as an asynchronous run. `onPublication` receives the progressive publications
151
281
  * of a running request.
152
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
+
153
292
  export function workerRun(
154
293
  worker: Worker,
155
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();
@@ -87,14 +115,16 @@ export function httpRun(base = '/api', {fetchImpl = globalThis.fetch} = {}) {
87
115
  */
88
116
  let dragCounter = 0;
89
117
 
90
- export function createSession(run, {onChange, resident: wanted = 'auto'} = {}) {
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;
91
121
  let snapshot = null;
92
122
  let generation = 0;
93
123
  let queue = Promise.resolve();
94
124
  const scenes = new WeakMap();
95
125
  if (wanted === true && !run.openSession) throw Error('This engine has no resident sessions');
96
126
  const resident = wanted === true || (wanted === 'auto' && typeof run.openSession === 'function');
97
- const opened = resident ? Promise.resolve(run.openSession()) : null;
127
+ let opened = resident ? Promise.resolve(run.openSession()) : null;
98
128
  // The engine call: with a resident session, the request goes to it and its answer is turned into the shape of an
99
129
  // answer with a snapshot (the state), its scene remembered for that state.
100
130
  const call = async request => {
@@ -104,7 +134,9 @@ export function createSession(run, {onChange, resident: wanted = 'auto'} = {}) {
104
134
  if (!answer.ok || answer.revision === undefined) return answer;
105
135
  const state = {revision: answer.revision, layoutVersion: answer.layoutVersion, collapsedIds: answer.collapsedIds};
106
136
  if (answer.scene) scenes.set(state, answer.scene);
107
- 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} : {})};
108
140
  };
109
141
 
110
142
  // Runs `step` after every change before it; its answer counts only if no import or reset came in between.
@@ -152,10 +184,25 @@ export function createSession(run, {onChange, resident: wanted = 'auto'} = {}) {
152
184
  * Any change still under way is dropped.
153
185
  */
154
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.
155
188
  generation++;
189
+ queue = Promise.resolve();
156
190
  return enqueue(() => call({op: 'import', graph, limit, ...(options ? {options} : {})}));
157
191
  },
158
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
+
159
206
  /** Drops the snapshot; changes still under way resolve as stale. */
160
207
  reset() {
161
208
  generation++;
@@ -195,6 +242,108 @@ export function createSession(run, {onChange, resident: wanted = 'auto'} = {}) {
195
242
  * `{ok, nodes, edges, hops, visible: {nodes, routes}, distance}` as for `trace`; `nodes` can go to `reveal`.
196
243
  * `direction`: `out`, `in` or `both` (default); `edgeKinds`: follow only edges of these kinds.
197
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
+
198
347
  async neighbourhood(nodeId, {hops, direction, edgeKinds} = {}) {
199
348
  if (!snapshot) return {ok: false, error: 'Nothing imported yet.'};
200
349
  return call({op: 'neighbourhood', snapshot, ...(Array.isArray(nodeId) ? {nodeIds: nodeId} : {nodeId}),
@@ -332,6 +481,39 @@ export function createSession(run, {onChange, resident: wanted = 'auto'} = {}) {
332
481
  /** Whether the snapshot stays in the engine (see `createSession`). */
333
482
  get resident() { return resident; },
334
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
+
335
517
  /** Ends a resident session in the engine (frees its snapshot). The session object is not usable afterwards. */
336
518
  async close() {
337
519
  generation++;
@@ -0,0 +1,160 @@
1
+ import type {DetailsAnswer, FindAnswer, Graph, Hidden, Intent, NeighbourhoodAnswer, Scene, Snapshot, TraceAnswer} from '@arqlet/contracts';
2
+ import type {DetailTarget, PayloadAnswer, PayloadChange, PeekAnswer, ReadAnswer, RefineRun, Session, SessionResult} from './session.js';
3
+ import type {EngineRequest} from './wasm-client.js';
4
+
5
+ /** Provisional: a view as a value (`bookmark`): the engine's intent, the highlight, the selection, the graph's digest. */
6
+ export interface ViewBookmark {
7
+ version: 1;
8
+ digest: string | null;
9
+ intent: Intent;
10
+ highlight?: ViewHighlight extends infer H ? (H extends unknown ? Omit<H, 'answer'> : never) : never;
11
+ selection?: DetailTarget;
12
+ }
13
+
14
+ /** A bookmark as URL-safe text, and back (throws on text that is not one). */
15
+ export function encodeBookmark(bookmark: ViewBookmark): string;
16
+ export function decodeBookmark(text: string): ViewBookmark;
17
+
18
+ /** Provisional: where keyboard navigation goes (see `navigateScene`). */
19
+ export type NavigationDirection = 'left' | 'right' | 'up' | 'down' | 'parent' | 'child' | 'next' | 'previous' | 'out' | 'in';
20
+
21
+ /** The node of `scene` that `direction` leads to from `from` (without `from`, the first top-level node), or null. */
22
+ export function navigateScene(scene: Scene | null, from: string | null, direction: NavigationDirection): string | null;
23
+
24
+ /** What changed between two scenes, by id. */
25
+ export interface SceneDiff {
26
+ nodes: {added: string[]; removed: string[]; changed: string[]};
27
+ routes: {added: string[]; removed: string[]; changed: string[]};
28
+ }
29
+
30
+ /** Provisional: the highlight a view keeps until it is cleared; asked again after every change. */
31
+ export type ViewHighlight =
32
+ | {kind: 'trace'; from: string; to: string; init?: {mode?: 'shortest' | 'all'; edgeKinds?: string[]}; answer: {ok: true} & TraceAnswer}
33
+ | {
34
+ kind: 'neighbourhood';
35
+ nodeId: string | string[];
36
+ init?: {hops?: number; direction?: 'out' | 'in' | 'both'; edgeKinds?: string[]};
37
+ answer: {ok: true} & NeighbourhoodAnswer;
38
+ };
39
+
40
+ /** Provisional: the state of a view controller (frozen; a new object after every change). */
41
+ export interface ViewState {
42
+ /** The session's snapshot (with a resident session only its state). */
43
+ readonly snapshot: Snapshot | null;
44
+ /** The scene to draw. */
45
+ readonly scene: Scene | null;
46
+ /** What the last step changed in the scene, for animation. */
47
+ readonly diff: SceneDiff | null;
48
+ /** Whether a step is running or queued. */
49
+ readonly busy: boolean;
50
+ /** The last error, cleared by the next successful step. */
51
+ readonly error: string | null;
52
+ readonly highlight: ViewHighlight | null;
53
+ /** The selected node or edge (`select`), or null. */
54
+ readonly selection: DetailTarget | null;
55
+ /** What the engine knows about the selection, asked again after every change; null without a selection. */
56
+ readonly details: (DetailsAnswer & {ok: true}) | null;
57
+ /** The last search (`find`) and its answer, or null. */
58
+ readonly search: {query: string; answer: FindAnswer & {ok: true}} | null;
59
+ /** The last `focus`: the node and the bounds of the box that shows it (null when hidden); `serial` counts requests. */
60
+ readonly focus: {nodeId: string; bounds: {x: number; y: number; width: number; height: number} | null; shownAs: string | null; serial: number} | null;
61
+ /** Provisional (ADR 0023, R1): the content's revision after the last `payload`, or undefined. */
62
+ readonly contentRevision?: number;
63
+ /** The look into a collapsed container (`peek`), or null; cleared by the next change. */
64
+ readonly peek: {nodeId: string; answer: PeekAnswer & {ok: true}} | null;
65
+ /** The refinement under way on the second engine (`refine`), or null; `shown` counts intermediate results applied. */
66
+ readonly refining: {op: string; jobId: string; shown: number} | null;
67
+ /** How the last refinement ended: applied, stale (the view had moved on), cancelled, or an error. */
68
+ readonly refined: {op: string; applied: boolean; stale?: true; cancelled?: true; error?: string; optimization?: unknown} | null;
69
+ /** Refinement results discarded because the view had changed. */
70
+ readonly discarded: number;
71
+ /** What the pointer is over (`hover`), or null. */
72
+ readonly hover: DetailTarget | null;
73
+ /** What the view hides (the last `filter`). */
74
+ readonly hide: Hidden;
75
+ readonly canBack: boolean;
76
+ readonly canForward: boolean;
77
+ /** The names of the steps `back` and `forward` would undo and redo (such as `Open group-1`), or null. */
78
+ readonly backLabel: string | null;
79
+ readonly forwardLabel: string | null;
80
+ /** How many steps changed the scene since the import. */
81
+ readonly steps: number;
82
+ }
83
+
84
+ /** A step's answer: the engine's, or `cancelled` when `cancel()` dropped it before it started. */
85
+ export type ViewResult = SessionResult & {cancelled?: boolean};
86
+
87
+ /**
88
+ * Provisional (request 31): a headless view controller over a layout session. `subscribe` and `getState` fit React's
89
+ * `useSyncExternalStore`. Steps run one after the other.
90
+ */
91
+ export interface ViewController {
92
+ getState(): ViewState;
93
+ subscribe(listener: () => void): () => void;
94
+ import(graph: Graph, init?: {limit?: number; options?: Record<string, unknown>}): Promise<ViewResult>;
95
+ open(id: string): Promise<ViewResult>;
96
+ close(id: string): Promise<ViewResult>;
97
+ toggle(id: string): Promise<ViewResult>;
98
+ /** The next `count` (default `page`) children of a `+N more` box; `container` or `rest:<container>`. */
99
+ showRest(container: string, count?: number): Promise<ViewResult>;
100
+ reveal(nodeIds: string[], init?: {partial?: boolean}): Promise<ViewResult>;
101
+ filter(hide?: Hidden): Promise<ViewResult>;
102
+ trace(from: string, to: string, init?: {mode?: 'shortest' | 'all'; edgeKinds?: string[]}): Promise<ReadAnswer<TraceAnswer> & {cancelled?: boolean}>;
103
+ neighbourhood(
104
+ nodeId: string | string[],
105
+ init?: {hops?: number; direction?: 'out' | 'in' | 'both'; edgeKinds?: string[]},
106
+ ): Promise<ReadAnswer<NeighbourhoodAnswer> & {cancelled?: boolean}>;
107
+ /** Opens the groups the highlight passes through. */
108
+ revealHighlight(): Promise<ViewResult>;
109
+ clearHighlight(): void;
110
+ /** Selects a node or an edge (or nothing): `state.details` holds the engine's facts about it, kept up to date. */
111
+ select(target: DetailTarget | null): Promise<ViewResult>;
112
+ /** What the pointer is over (no engine call). */
113
+ hover(target: DetailTarget | null): void;
114
+ /** Finds nodes by label or id, also hidden ones (`state.search` until `clearSearch`). */
115
+ find(query: string, init?: {limit?: number; nodeKinds?: string[]}): Promise<ViewResult>;
116
+ clearSearch(): void;
117
+ /** A look into a collapsed container without opening it (`state.peek`; not a step for `back`). */
118
+ peek(nodeId: string, init?: {limit?: number}): Promise<ViewResult>;
119
+ closePeek(): void;
120
+ /** Provisional (ADR 0023, R1): changes the session's content and refreshes `state.details`; not a step for `back`. */
121
+ payload(change: PayloadChange): Promise<PayloadAnswer | {ok: false; error?: string; cancelled?: boolean}>;
122
+ /** Opens what hides `nodeId` (a step for `back`), selects it, and sets `state.focus` for the host's camera. */
123
+ focus(nodeId: string, options?: {reveal?: boolean; partial?: boolean}): Promise<ViewResult>;
124
+ /**
125
+ * Refines the view on the second engine (`refine`): `{op: 'refine'}` by default, `refineProgressive` or
126
+ * `structuredRefine`; applied only if the view is still the one it started from. Not a step for `back`.
127
+ */
128
+ refine(
129
+ request?: {op?: 'refine' | 'refineProgressive' | 'structuredRefine'; [field: string]: unknown},
130
+ options?: {onApplied?: (snapshot: Snapshot, info: {final: boolean; shown: number}) => void},
131
+ ): Promise<ViewResult>;
132
+ /** Stops the refinement under way; its later results are dropped. */
133
+ cancelRefinement(): void;
134
+ /** Moves the selection the way `direction` says and sets `state.focus` (nothing opened, not a step for `back`). */
135
+ navigate(direction: NavigationDirection): Promise<ViewResult | {ok: false; none: true; collapsed?: boolean}>;
136
+ /** The view as a value to keep or share (`encodeBookmark` for a URL). */
137
+ bookmark(): Promise<{ok: true; bookmark: ViewBookmark} | {ok: false; error?: string; cancelled?: boolean}>;
138
+ /** Opens a bookmark (a step for `back`); another graph's is refused unless `force`. */
139
+ openBookmark(bookmark: ViewBookmark, options?: {force?: boolean}): Promise<ViewResult>;
140
+ back(): Promise<ViewResult>;
141
+ forward(): Promise<ViewResult>;
142
+ /** Any other change of the protocol, remembered for `back` under `label`. */
143
+ apply(
144
+ request: Omit<EngineRequest, 'snapshot' | 'expectedRevision' | 'expectedLayoutVersion'> & {op: string},
145
+ label?: string,
146
+ /** `merge`: a follow-up of the last change, remembered in its entry. */
147
+ options?: {remember?: boolean; merge?: boolean},
148
+ ): Promise<ViewResult>;
149
+ /**
150
+ * Continues from a snapshot the host made; with `forget` the history and the highlight start empty, with `remember` (a
151
+ * label) the change from the previous snapshot is remembered for `back`.
152
+ */
153
+ adopt(snapshot: Snapshot, options?: {forget?: boolean; remember?: string | null}): Promise<ViewResult>;
154
+ /** Drops the steps queued and not started; a step under way finishes. */
155
+ cancel(): void;
156
+ }
157
+
158
+ export function createViewController(session: Session, options?: {page?: number; historyLimit?: number; scenes?: boolean; detailLimit?: number; refine?: RefineRun; publicationInterval?: number}): ViewController;
159
+
160
+ export function sceneDiff(before: Scene | null, after: Scene | null): SceneDiff;