@arqlet/engine-client 0.5.0 → 0.6.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 ADDED
@@ -0,0 +1,111 @@
1
+ import type {Scene} from '@arqlet/contracts';
2
+
3
+ /**
4
+ * Provisional (ADR 0019, step 4): a session's scene as columns. Index `i` of an id or text table is node, route, port, label,
5
+ * row, conflict or edge `i`, and the typed arrays of the same part are indexed alike. Coordinates are `f32`.
6
+ */
7
+ export interface SceneColumns {
8
+ schemaVersion: number;
9
+ revision: number;
10
+ layoutVersion: number;
11
+
12
+ /** Node ids, labels and kinds (`nodeKind` indexes `nodeKinds`) by node index. */
13
+ nodeIds: string[];
14
+ nodeLabels: string[];
15
+ nodeKinds: string[];
16
+ /** x, y, width, height per node, in scene coordinates. */
17
+ nodeBounds: Float32Array;
18
+ /** Parent node index, `NONE` for a root. */
19
+ nodeParent: Uint32Array;
20
+ /** Bits of `NODE_FLAGS`. */
21
+ nodeFlags: Uint32Array;
22
+ nodeKind: Uint32Array;
23
+ /** Values of `SHAPES`. */
24
+ nodeShape: Uint32Array;
25
+
26
+ /** Route ids by route index. */
27
+ routeIds: string[];
28
+ /** Node index of each route's ends, `NONE` when the end is not a node of the scene. */
29
+ routeSource: Uint32Array;
30
+ routeTarget: Uint32Array;
31
+ routeWeight: Uint32Array;
32
+ /** Bits of `ROUTE_FLAGS`. */
33
+ routeFlags: Uint32Array;
34
+ /** One more than the routes: route `i` is the points `routeOffsets[i]` to `routeOffsets[i + 1]` of `routePoints`. */
35
+ routeOffsets: Uint32Array;
36
+ /** x and y alternating, all routes one after the other. */
37
+ routePoints: Float32Array;
38
+ /** Each route's kind (index into `routeKinds`, '' for none), the edges it stands for in the other direction (`NONE`
39
+ * when it is not a two-way route), and the edges of a bundle (indices into `edgeIds`, behind `routeMemberOffsets`). */
40
+ routeKinds: string[];
41
+ routeKind: Uint32Array;
42
+ routeBackWeight: Uint32Array;
43
+ routeMemberOffsets: Uint32Array;
44
+ routeMembers: Uint32Array;
45
+
46
+ /** Port ids by port index. */
47
+ portIds: string[];
48
+ /** The edges that ports and boundary crossings name, each once. */
49
+ edgeIds: string[];
50
+ /** Node index of each port's node. */
51
+ portNode: Uint32Array;
52
+ /** Index into `edgeIds`. */
53
+ portEdge: Uint32Array;
54
+ /** Bits of `PORT_FLAGS`. */
55
+ portFlags: Uint32Array;
56
+ /** Values of `SIDES`. */
57
+ portSide: Uint32Array;
58
+ /** x and y alternating. */
59
+ portPosition: Float32Array;
60
+
61
+ /** Boundary crossings: edge (index into `edgeIds`), container (node index), ordinal, side, flags (bit 0: derived), position. */
62
+ crossingEdge: Uint32Array;
63
+ crossingContainer: Uint32Array;
64
+ crossingOrdinal: Uint32Array;
65
+ crossingSide: Uint32Array;
66
+ crossingFlags: Uint32Array;
67
+ crossingPosition: Float32Array;
68
+
69
+ /** Placed labels: id and text by label index, `labelKind` indexes `labelKinds`. */
70
+ labelIds: string[];
71
+ labelTexts: string[];
72
+ labelKinds: string[];
73
+ labelKind: Uint32Array;
74
+ /** x, y, width, height per label. */
75
+ labelBounds: Float32Array;
76
+
77
+ /** Rows of the nodes' content, node by node: id and label by row index, the node (index), bounds (four per row). */
78
+ rowIds: string[];
79
+ rowLabels: string[];
80
+ rowNode: Uint32Array;
81
+ rowBounds: Float32Array;
82
+
83
+ /** Conflicts: kind (index into `conflictKinds`) and reason by conflict index; the nodes and routes each names are indices
84
+ * (`NONE` for one outside the scene) in `conflictNodes` and `conflictRoutes`, behind the offsets (conflicts + 1). */
85
+ conflictKinds: string[];
86
+ conflictReasons: string[];
87
+ conflictKind: Uint32Array;
88
+ conflictNodeOffsets: Uint32Array;
89
+ conflictNodes: Uint32Array;
90
+ conflictRouteOffsets: Uint32Array;
91
+ conflictRoutes: Uint32Array;
92
+
93
+ /** Where bus lines branch: x and y alternating. */
94
+ junctions: Float32Array;
95
+ /** x, y, width, height of everything drawn, with its margin (full precision). */
96
+ bounds: [number, number, number, number];
97
+ showPorts: boolean;
98
+ /** The explicit buses, each as its edges' ids. */
99
+ buses: string[][];
100
+ }
101
+
102
+ /** "No node" in an index column. */
103
+ export const NONE: number;
104
+ export const NODE_FLAGS: {readonly container: 1; readonly aggregate: 2; readonly collapsed: 4; readonly invalid: 8};
105
+ export const ROUTE_FLAGS: {readonly invalid: 1; readonly rounded: 2};
106
+ export const PORT_FLAGS: {readonly explicit: 1; readonly target: 2};
107
+ export const SIDES: {readonly left: 0; readonly right: 1; readonly top: 2; readonly bottom: 3};
108
+ export const SHAPES: {readonly rect: 0; readonly square: 1; readonly circle: 2; readonly busLine: 3};
109
+
110
+ /** The columns of a scene object, as the engine builds them (`f32` coordinates). Provisional. */
111
+ export function columnsOfScene(scene: Scene): SceneColumns;
package/columns.js ADDED
@@ -0,0 +1,161 @@
1
+ // Provisional (ADR 0019, step 4): the scene as columns. The engine's own columns (`session.columns()` on a resident
2
+ // session in WASM) and this function give the same arrays; this one serves engines that keep their session elsewhere
3
+ // (the backend answers JSON only) and is the reference the parity tests compare against. Pure: no DOM, no engine.
4
+
5
+ /** "No node" in an index column (`u32::MAX`). */
6
+ export const NONE = 0xffffffff;
7
+ /** Bits of `nodeFlags`. */
8
+ export const NODE_FLAGS = {container: 1, aggregate: 2, collapsed: 4, invalid: 8};
9
+ /** Bits of `routeFlags`. */
10
+ export const ROUTE_FLAGS = {invalid: 1, rounded: 2};
11
+ /** Bits of `portFlags`: authored, and the target end (the source end otherwise). */
12
+ export const PORT_FLAGS = {explicit: 1, target: 2};
13
+ /** Values of `portSide` and `crossingSide`. */
14
+ export const SIDES = {left: 0, right: 1, top: 2, bottom: 3};
15
+ /** Values of `nodeShape` (an unknown shape counts as `rect`). */
16
+ export const SHAPES = {rect: 0, square: 1, circle: 2, busLine: 3};
17
+
18
+ // Strings kept once, numbered in the order they first occur.
19
+ const table = () => {
20
+ const items = [], index = new Map();
21
+ return {items, id: text => { if (!index.has(text)) { index.set(text, items.length); items.push(text); } return index.get(text); }};
22
+ };
23
+ const rects = (list, get) => {
24
+ const out = new Float32Array(list.length * 4);
25
+ list.forEach((item, i) => { const b = get(item); out.set([b.x, b.y, b.width, b.height], i * 4); });
26
+ return out;
27
+ };
28
+ const points = (list, get) => {
29
+ const out = new Float32Array(list.length * 2);
30
+ list.forEach((item, i) => { const p = get(item); out[i * 2] = p.x; out[i * 2 + 1] = p.y; });
31
+ return out;
32
+ };
33
+
34
+ /**
35
+ * The columns of a scene (as `session.scene()` gives it), in the scene's order. Id and text tables (`nodeIds`, `nodeLabels`,
36
+ * `nodeKinds`, `routeIds`, `portIds`, `edgeIds`, `labelIds`, `labelTexts`, `labelKinds`, `rowIds`, `rowLabels`,
37
+ * `conflictKinds`, `conflictReasons`, `buses`), `bounds` (x, y, width, height of everything drawn), `showPorts`, and typed
38
+ * arrays: see `SceneColumns`. Coordinates are narrowed to `f32` as the engine does.
39
+ */
40
+ export function columnsOfScene(scene) {
41
+ const nodes = scene.nodes ?? [];
42
+ const routes = scene.routes ?? [];
43
+ const ports = scene.ports ?? [];
44
+ const crossings = scene.crossings ?? [];
45
+ const labels = scene.labels ?? [];
46
+ const conflicts = scene.conflicts ?? [];
47
+ const index = new Map();
48
+ nodes.forEach((n, i) => index.set(n.id, i));
49
+ const at = id => (index.has(id) ? index.get(id) : NONE);
50
+ const routeIndex = new Map();
51
+ routes.forEach((r, i) => routeIndex.set(r.id, i));
52
+ const atRoute = id => (routeIndex.has(id) ? routeIndex.get(id) : NONE);
53
+
54
+ const nodeBounds = rects(nodes, n => n.bounds);
55
+ const nodeParent = new Uint32Array(nodes.length);
56
+ const nodeFlags = new Uint32Array(nodes.length);
57
+ const nodeKind = new Uint32Array(nodes.length);
58
+ const nodeShape = new Uint32Array(nodes.length);
59
+ const nodeKinds = table();
60
+ nodes.forEach((n, i) => {
61
+ nodeParent[i] = n.parentId == null ? NONE : at(n.parentId);
62
+ nodeFlags[i] = (n.container ? 1 : 0) | (n.aggregate ? 2 : 0) | (n.collapsed ? 4 : 0) | (n.invalid ? 8 : 0);
63
+ nodeKind[i] = nodeKinds.id(n.kind);
64
+ nodeShape[i] = SHAPES[n.shape] ?? 0;
65
+ });
66
+
67
+ const routeSource = new Uint32Array(routes.length);
68
+ const routeTarget = new Uint32Array(routes.length);
69
+ const routeWeight = new Uint32Array(routes.length);
70
+ const routeFlags = new Uint32Array(routes.length);
71
+ const routeKinds = table();
72
+ const routeKind = new Uint32Array(routes.length);
73
+ const routeBackWeight = new Uint32Array(routes.length);
74
+ const routeOffsets = new Uint32Array(routes.length + 1);
75
+ let total = 0;
76
+ for (const r of routes) total += r.points.length;
77
+ const routePoints = new Float32Array(total * 2);
78
+ let cursor = 0;
79
+ routes.forEach((r, i) => {
80
+ routeSource[i] = at(r.source);
81
+ routeTarget[i] = at(r.target);
82
+ routeWeight[i] = Math.min(r.weight ?? 0, NONE);
83
+ routeFlags[i] = (r.invalid ? 1 : 0) | (r.rounded ? 2 : 0);
84
+ routeKind[i] = routeKinds.id(r.kind ?? '');
85
+ routeBackWeight[i] = r.backWeight == null ? NONE : Math.min(r.backWeight, NONE - 1);
86
+ for (const p of r.points) { routePoints[cursor++] = p.x; routePoints[cursor++] = p.y; }
87
+ routeOffsets[i + 1] = cursor / 2;
88
+ });
89
+
90
+ // Ports and boundary crossings name edges; the edges are numbered once, ports first.
91
+ const edges = table();
92
+ const portNode = Uint32Array.from(ports, p => at(p.nodeId));
93
+ const portEdge = Uint32Array.from(ports, p => edges.id(p.edgeId));
94
+ const portFlags = Uint32Array.from(ports, p => (p.explicit ? 1 : 0) | (p.endpoint === 'target' ? 2 : 0));
95
+ const portSide = Uint32Array.from(ports, p => SIDES[p.side]);
96
+ const crossingEdge = Uint32Array.from(crossings, x => edges.id(x.edgeId));
97
+ // The edges of bundles come after those of ports and crossings.
98
+ const routeMemberOffsets = [0], routeMembers = [];
99
+ for (const r of routes) {
100
+ for (const member of r.members ?? []) routeMembers.push(edges.id(member));
101
+ routeMemberOffsets.push(routeMembers.length);
102
+ }
103
+ const labelKinds = table();
104
+
105
+ const conflictKinds = table();
106
+ const conflictNodes = [], conflictRoutes = [], conflictNodeOffsets = [0], conflictRouteOffsets = [0];
107
+ for (const k of conflicts) {
108
+ for (const id of k.nodes) conflictNodes.push(at(id));
109
+ for (const id of k.routes) conflictRoutes.push(atRoute(id));
110
+ conflictNodeOffsets.push(conflictNodes.length);
111
+ conflictRouteOffsets.push(conflictRoutes.length);
112
+ }
113
+ const conflictKind = Uint32Array.from(conflicts, k => conflictKinds.id(k.kind));
114
+
115
+ const rows = [];
116
+ nodes.forEach((n, i) => { for (const row of n.rows ?? []) rows.push({row, node: i}); });
117
+ const b = scene.bounds;
118
+
119
+ return {
120
+ schemaVersion: scene.schemaVersion,
121
+ revision: scene.revision,
122
+ layoutVersion: scene.layoutVersion,
123
+ nodeIds: nodes.map(n => n.id),
124
+ nodeLabels: nodes.map(n => n.label),
125
+ nodeKinds: nodeKinds.items,
126
+ routeIds: routes.map(r => r.id),
127
+ routeKinds: routeKinds.items,
128
+ portIds: ports.map(p => p.id),
129
+ edgeIds: edges.items,
130
+ labelIds: labels.map(l => l.id),
131
+ labelTexts: labels.map(l => l.text),
132
+ labelKinds: labelKinds.items,
133
+ rowIds: rows.map(r => r.row.id),
134
+ rowLabels: rows.map(r => r.row.label),
135
+ conflictKinds: conflictKinds.items,
136
+ conflictReasons: conflicts.map(k => k.reason),
137
+ buses: scene.buses ?? [],
138
+ bounds: b ? [b.x, b.y, b.width, b.height] : [0, 0, 0, 0],
139
+ showPorts: Boolean(scene.showPorts),
140
+ nodeBounds, nodeParent, nodeFlags, nodeKind, nodeShape,
141
+ routeSource, routeTarget, routeWeight, routeFlags, routeOffsets, routePoints,
142
+ routeKind, routeBackWeight, routeMemberOffsets: Uint32Array.from(routeMemberOffsets), routeMembers: Uint32Array.from(routeMembers),
143
+ portNode, portEdge, portFlags, portSide, portPosition: points(ports, p => p.position),
144
+ crossingEdge,
145
+ crossingContainer: Uint32Array.from(crossings, x => at(x.containerId)),
146
+ crossingOrdinal: Uint32Array.from(crossings, x => Math.min(x.ordinal, NONE)),
147
+ crossingSide: Uint32Array.from(crossings, x => SIDES[x.side]),
148
+ crossingFlags: Uint32Array.from(crossings, x => (x.derived ? 1 : 0)),
149
+ crossingPosition: points(crossings, x => x.position),
150
+ labelKind: Uint32Array.from(labels, l => labelKinds.id(l.kind)),
151
+ labelBounds: rects(labels, l => l.bounds),
152
+ rowNode: Uint32Array.from(rows, r => r.node),
153
+ rowBounds: rects(rows, r => r.row.bounds),
154
+ conflictKind,
155
+ conflictNodeOffsets: Uint32Array.from(conflictNodeOffsets),
156
+ conflictNodes: Uint32Array.from(conflictNodes),
157
+ conflictRouteOffsets: Uint32Array.from(conflictRouteOffsets),
158
+ conflictRoutes: Uint32Array.from(conflictRoutes),
159
+ junctions: points(scene.junctions ?? [], p => p),
160
+ };
161
+ }
package/engine.d.ts CHANGED
@@ -18,6 +18,29 @@ export function loadEngine(
18
18
  /** Scene v1 for a snapshot, computed by the engine and cached per snapshot object. Throws the engine's error. */
19
19
  export function sceneOf(run: Run, snapshot: Snapshot): Scene;
20
20
 
21
+ /**
22
+ * Provisional: the groups and communities the view of `graph` adds with `options` (`groups`, `communities`,
23
+ * `communityHubs`), as the `groups` option takes them: node id → path of labels. Given back as `options.groups`, the view
24
+ * gets the same containers (of kind `group`) without computing communities again. Throws the engine's error.
25
+ */
26
+ export function communityGroups(
27
+ run: Run,
28
+ graph: import('@arqlet/contracts').Graph,
29
+ options?: import('@arqlet/contracts').LayoutOptions,
30
+ ): {[nodeId: string]: string[]};
31
+
32
+ /**
33
+ * Provisional: the first view of `graph` (`import`). With `omitSource`, the snapshot leaves the source graph out and
34
+ * carries `sourceDigest`; later requests on it send the graph as `source`. Throws the engine's error.
35
+ */
36
+ export function importGraph(
37
+ run: Run,
38
+ graph: import('@arqlet/contracts').Graph,
39
+ limit: number,
40
+ options?: import('@arqlet/contracts').LayoutOptions,
41
+ delivery?: {omitSource?: boolean},
42
+ ): Snapshot;
43
+
21
44
  /**
22
45
  * Starts a module worker that answers engine requests (browser only). Post `{requestId, request}`; the worker answers
23
46
  * `{requestId, ...response}` and, while a request runs, `{requestId, publication, emittedAt, bytes}` for each
package/engine.js CHANGED
@@ -43,6 +43,28 @@ export function sceneOf(run, snapshot) {
43
43
  return result.scene;
44
44
  }
45
45
 
46
+ /**
47
+ * Provisional: the groups and communities the view of `graph` adds with `options` (`groups`, `communities`,
48
+ * `communityHubs`), as the `groups` option takes them: node id → path of labels. Computed once (in a backend, for a large
49
+ * graph) and given back as `options.groups`, the view gets the same containers without computing communities again.
50
+ * Throws the engine's error.
51
+ */
52
+ export function communityGroups(run, graph, options = {}) {
53
+ const result = run({op: 'communities', graph, options});
54
+ if (!result.ok) throw Error(result.error);
55
+ return result.groups;
56
+ }
57
+
58
+ /**
59
+ * Provisional: the first view of `graph` (`import`). With `omitSource`, the snapshot leaves the source graph out and
60
+ * carries its fingerprint (`sourceDigest`); later requests on it send the graph as `source`. Throws the engine's error.
61
+ */
62
+ export function importGraph(run, graph, limit, options = {}, {omitSource = false} = {}) {
63
+ const result = run({op: 'import', graph, limit, options, ...(omitSource ? {omitSource: true} : {})});
64
+ if (!result.ok) throw Error(result.error);
65
+ return result.snapshot;
66
+ }
67
+
46
68
  /**
47
69
  * Starts a module worker that answers engine requests for the WASM at `wasmUrl`. The worker's own URL is
48
70
  * resolved from this module, so the same package works from any host page or import map.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@arqlet/engine-client",
3
- "version": "0.5.0",
3
+ "version": "0.6.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
+ "./columns.js": {
51
+ "types": "./columns.d.ts",
52
+ "default": "./columns.js"
53
+ },
50
54
  "./worker.js": "./worker.js",
51
55
  "./arqlet.wasm": "./arqlet.wasm"
52
56
  },
@@ -56,11 +60,13 @@
56
60
  "presets.js",
57
61
  "elk.js",
58
62
  "session.js",
63
+ "columns.js",
59
64
  "engine.d.ts",
60
65
  "wasm-client.d.ts",
61
66
  "presets.d.ts",
62
67
  "elk.d.ts",
63
68
  "session.d.ts",
69
+ "columns.d.ts",
64
70
  "worker.js",
65
71
  "arqlet.wasm",
66
72
  "README.md",
@@ -71,7 +77,7 @@
71
77
  "access": "public"
72
78
  },
73
79
  "dependencies": {
74
- "@arqlet/contracts": "^0.5.0"
80
+ "@arqlet/contracts": "^0.6.0"
75
81
  },
76
82
  "scripts": {
77
83
  "test": "node --test"
package/session.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type {Graph, GraphNeighbourhood, GraphPatch, GraphTrace, Hidden, NeighbourhoodAnswer, Overview, OverviewRequest, Scene, Snapshot, TraceAnswer} from '@arqlet/contracts';
2
+ import type {SceneColumns} from './columns.js';
2
3
  import type {EngineRequest, EngineResponse, Run} from './wasm-client.js';
3
4
 
4
5
  /** An engine answer as the session reports it. `stale`: an import or reset overtook the change, nothing was applied. */
@@ -67,6 +68,12 @@ export interface Session {
67
68
  filter(hide?: Hidden): Promise<SessionResult>;
68
69
  /** The scene of the current snapshot, computed once per snapshot. Throws the engine's error. */
69
70
  scene(): Promise<Scene>;
71
+ /**
72
+ * Provisional (ADR 0019, step 4): the scene of the current snapshot as columns. In a resident WASM session called
73
+ * directly, the arrays are views into the engine's memory, valid until the next request to the session (copy what
74
+ * you keep); through a worker they are copies transferred once; otherwise they are built from the scene.
75
+ */
76
+ columns(): Promise<SceneColumns>;
70
77
  /** The whole snapshot: the current one, or with `resident` the one the engine keeps (for saving or hand-over). */
71
78
  exportSnapshot(): Promise<Snapshot | null>;
72
79
  /** Whether the snapshot stays in the engine. */
@@ -79,6 +86,10 @@ export interface Session {
79
86
  export interface ResidentSession {
80
87
  run(request: EngineRequest): EngineResponse | Promise<EngineResponse>;
81
88
  close(): unknown;
89
+ /** Provisional (ADR 0019, step 4): the scene as columns, where the engine keeps them (WASM, a worker). */
90
+ columns?(): SceneColumns | Promise<SceneColumns>;
91
+ /** Provisional (step 4): an `overview` request answered with typed arrays for the numbers, where the engine can. */
92
+ overview?(request: EngineRequest, init?: {copy?: boolean}): EngineResponse | Promise<EngineResponse>;
82
93
  }
83
94
 
84
95
  /** Creates a session on an engine `run`, synchronous (`loadEngine`) or asynchronous (`workerRun`). */
@@ -156,7 +167,17 @@ export function createOverviewSession(
156
167
  run: (Run | ((request: EngineRequest) => Promise<EngineResponse>)) & {
157
168
  openSession?: () => ResidentSession | Promise<ResidentSession>;
158
169
  },
159
- init?: {resident?: boolean | 'auto'},
170
+ init?: {
171
+ resident?: boolean | 'auto';
172
+ /**
173
+ * Provisional (ADR 0019, step 4): the overview's numbers (`parent`, `x`, `y`, `r`, `kind`, `edges`, `links`) as typed
174
+ * arrays instead of JSON arrays, moved without JSON (copied once out of the engine's memory, transferred from a
175
+ * worker). Needs a resident session in an engine that offers `overview` (WASM, a worker); an answer says so
176
+ * otherwise. Default false: the arrays are plain, as before. Typed arrays index like arrays; a `start` built from
177
+ * them is sent as plain arrays.
178
+ */
179
+ columns?: boolean;
180
+ },
160
181
  ): OverviewSession;
161
182
 
162
183
  /** The most nodes an import selects for its view; the default of `Session.import`'s limit. */
package/session.js CHANGED
@@ -6,6 +6,8 @@
6
6
  // layout version to every change, runs changes one after the other on the newest snapshot, and never applies an answer
7
7
  // that was overtaken: after a new `import`, or `reset`, a change still under way resolves to `{ok: false, stale: true}`.
8
8
 
9
+ import {columnsOfScene} from './columns.js';
10
+
9
11
  /**
10
12
  * Wraps a worker of `createEngineWorker` as an asynchronous `run`: each request gets an id, and the answer with that id
11
13
  * resolves it. Progressive publications are passed to `onPublication(requestId, message)`.
@@ -31,7 +33,18 @@ export function workerRun(worker, {onPublication} = {}) {
31
33
  run.openSession = async () => {
32
34
  const opened = await post({session: 'open'});
33
35
  if (!opened.ok) throw Error(opened.error);
34
- return {run: request => post({session: opened.session, request}), close: () => post({session: opened.session, close: true})};
36
+ return {
37
+ run: request => post({session: opened.session, request}),
38
+ close: () => post({session: opened.session, close: true}),
39
+ // Provisional (ADR 0019, step 4): the columns arrive as transferred buffers, copied once in the worker.
40
+ columns: async () => {
41
+ const answer = await post({session: opened.session, columns: true});
42
+ if (!answer.ok) throw Error(answer.error);
43
+ return answer.columns;
44
+ },
45
+ // Provisional: an overview request answered with typed arrays (see `createEngine`'s `overview`).
46
+ overview: request => post({session: opened.session, request, overview: true}),
47
+ };
35
48
  };
36
49
  return run;
37
50
  }
@@ -215,6 +228,23 @@ export function createSession(run, {onChange, resident: wanted = 'auto'} = {}) {
215
228
  return answer.scene;
216
229
  },
217
230
 
231
+ /**
232
+ * Provisional (ADR 0019, step 4): the scene of the current snapshot as columns (`SceneColumns`): id tables and typed
233
+ * arrays for bounds, parents, flags and route points. In a resident WASM session called directly, the arrays are
234
+ * views into the engine's memory (no copy), valid until the next request to the session; through a worker they are
235
+ * copies transferred once; for a backend or a session that sends the snapshot they are built from the scene. The
236
+ * content is the same in every case.
237
+ */
238
+ async columns() {
239
+ if (!snapshot) throw Error('Nothing imported yet.');
240
+ if (resident) {
241
+ await queue;
242
+ const kept = await opened;
243
+ if (typeof kept.columns === 'function') return kept.columns();
244
+ }
245
+ return columnsOfScene(await this.scene());
246
+ },
247
+
218
248
  /** The whole snapshot: the current one, or with `resident` the one the engine keeps (for saving or hand-over). */
219
249
  async exportSnapshot() {
220
250
  if (!snapshot) return null;
@@ -236,6 +266,15 @@ export function createSession(run, {onChange, resident: wanted = 'auto'} = {}) {
236
266
  };
237
267
  }
238
268
 
269
+ // A request whose `start` positions are typed arrays, with plain arrays instead (JSON has no typed arrays).
270
+ const plain = request => {
271
+ const start = request.start;
272
+ if (!start || !['x', 'y', 'r'].some(k => ArrayBuffer.isView(start[k]))) return request;
273
+ const fixed = {...start};
274
+ for (const k of ['x', 'y', 'r']) if (ArrayBuffer.isView(fixed[k])) fixed[k] = Array.from(fixed[k]);
275
+ return {...request, start: fixed};
276
+ };
277
+
239
278
  // The options the overview's clusters depend on; a continuation needs the same ones (as the engine's session checks).
240
279
  // Defaults as the engine's (`communities` 120, `satellites` 0); `groups` and `hubs` compared as given.
241
280
  const clustersOf = options => JSON.stringify([options?.communities ?? 120, options?.satellites ?? 0, options?.groups ?? null, options?.hubs ?? null]);
@@ -247,7 +286,7 @@ const clustersOf = options => JSON.stringify([options?.communities ?? 120, optio
247
286
  * continues from the last overview. Without a resident session the graph and the last positions stay here and are sent
248
287
  * along; the answers are the same. A new `open` overtakes what is still under way (`{ok: false, stale: true}`).
249
288
  */
250
- export function createOverviewSession(run, {resident: wanted = 'auto'} = {}) {
289
+ export function createOverviewSession(run, {resident: wanted = 'auto', columns = false} = {}) {
251
290
  if (wanted === true && !run.openSession) throw Error('This engine has no resident sessions');
252
291
  const resident = wanted === true || (wanted === 'auto' && typeof run.openSession === 'function');
253
292
  const opened = resident ? Promise.resolve(run.openSession()) : null;
@@ -259,7 +298,11 @@ export function createOverviewSession(run, {resident: wanted = 'auto'} = {}) {
259
298
  // On the graph the engine has, only what moves comes back (`positionsOnly`) while the clusters stay; it is put
260
299
  // together with the last overview here, so every answer is a whole overview.
261
300
  const asked = !request.graph && last ? {...request, positionsOnly: true} : request;
262
- const answer = await (await opened).run(asked);
301
+ const kept = await opened;
302
+ // With `columns` the numbers come back as typed arrays (views are copied: `last` outlives the next request); a
303
+ // `start` a host built from them is sent as plain arrays.
304
+ if (columns && typeof kept.overview !== 'function') return {ok: false, error: 'This engine has no columnar overview'};
305
+ const answer = await (columns ? kept.overview(plain(asked), {copy: true}) : kept.run(asked));
263
306
  if (answer.ok && answer.overview?.positionsOnly) {
264
307
  const {positionsOnly: _moved, ...moved} = answer.overview;
265
308
  return {...answer, overview: {...last, ...moved}};
package/wasm-client.d.ts CHANGED
@@ -16,7 +16,14 @@ export type EngineResponse =
16
16
  * snapshot stays in the engine: its requests leave the snapshot out, and its answers bring the scene.
17
17
  */
18
18
  export type Run = ((request: EngineRequest) => EngineResponse) & {
19
- openSession?: () => {run(request: EngineRequest): EngineResponse; close(): void};
19
+ openSession?: () => {
20
+ run(request: EngineRequest): EngineResponse;
21
+ close(): void;
22
+ /** Provisional (step 4): the scene as columns; the numbers are views into the module's memory, valid until the next request. */
23
+ columns?(): import('./columns.js').SceneColumns;
24
+ /** Provisional (step 4): an `overview` request answered with typed arrays; `copy` copies them out of the memory. */
25
+ overview?(request: EngineRequest, init?: {copy?: boolean}): EngineResponse;
26
+ };
20
27
  };
21
28
 
22
29
  export interface CreateEngineOptions {
package/wasm-client.js CHANGED
@@ -31,7 +31,39 @@ export async function createEngine(bytes,{onPublish}={}) {
31
31
  if(api.lw_session_open){
32
32
  run.openSession=()=>{
33
33
  const id=api.lw_session_open();
34
- return {run:input=>exchange(input,(ptr,len)=>api.lw_session_run(id,ptr,len)),close:()=>api.lw_session_close(id)};
34
+ const run=input=>exchange(input,(ptr,len)=>api.lw_session_run(id,ptr,len));
35
+ // Provisional (ADR 0019, step 4): the scene as columns. The numbers are typed-array views into the module's memory,
36
+ // not copies: valid until the next request to this session (a change drops them) or until the memory grows, so a
37
+ // host that keeps them copies them (`slice()`). The id tables are copies.
38
+ const views={f32:Float32Array,u32:Uint32Array,i32:Int32Array,f64:Float64Array};
39
+ // `listed`: name, type and length of each column as the engine described them; `read(index)` its address and bytes.
40
+ const viewsOf=(listed,read,copy)=>{
41
+ const result={};
42
+ listed.forEach((c,index)=>{
43
+ const answer=read(index);
44
+ const ptr=Number(answer & 0xffffffffn),bytes=Number(answer >> 32n);
45
+ const view=new views[c.type](api.memory.buffer,ptr,bytes/views[c.type].BYTES_PER_ELEMENT);
46
+ result[c.name]=copy?view.slice():view;
47
+ });
48
+ return result;
49
+ };
50
+ const columns=()=>{
51
+ const meta=run({op:'columns'});
52
+ if(!meta.ok) throw Error(meta.error);
53
+ const {ok,columns:listed,...result}=meta;
54
+ return {...result,...viewsOf(listed,index=>api.lw_session_column(id,index),false)};
55
+ };
56
+ // Provisional: an `overview` request whose numbers come back as typed arrays instead of JSON arrays (`parent`, `x`,
57
+ // `y`, `r`, `kind`, `edges`, `links`; a continuation with `positionsOnly` only `x`, `y` and `r`), in an answer shaped
58
+ // like the JSON one. `copy` (default false) copies them out of the module's memory, for a host that keeps them past
59
+ // its next request; views are valid only until then.
60
+ const overview=(request,{copy=false}={})=>{
61
+ const answer=run({...request,columns:true});
62
+ if(!answer.ok) return answer;
63
+ const {columns:listed,...rest}=answer.overview;
64
+ return {...answer,overview:{...rest,...viewsOf(listed,index=>api.lw_session_overview_column(id,index),copy)}};
65
+ };
66
+ return {run,close:()=>api.lw_session_close(id),...(api.lw_session_column?{columns}:{}),...(api.lw_session_overview_column?{overview}:{})};
35
67
  };
36
68
  }
37
69
  return run;
package/worker.js CHANGED
@@ -26,6 +26,20 @@ self.onmessage=async({data})=>{
26
26
  const session=sessions.get(data.session);
27
27
  if(!session)throw Error('Unknown session');
28
28
  if(data.close){session.close();sessions.delete(data.session);self.postMessage({requestId:data.requestId,ok:true});return;}
29
+ if(data.columns){
30
+ // The page cannot view this module's memory: copy each column once and hand the copies over (transferred, not cloned).
31
+ if(!session.columns)throw Error('This engine has no columns');
32
+ const result=session.columns();const transfer=[];
33
+ for(const [k,v] of Object.entries(result))if(ArrayBuffer.isView(v)){result[k]=v.slice();transfer.push(result[k].buffer);}
34
+ self.postMessage({requestId:data.requestId,ok:true,columns:result},transfer);return;
35
+ }
36
+ if(data.overview){
37
+ // As for the scene's columns: the numbers of the overview are copied once and transferred.
38
+ if(!session.overview)throw Error('This engine has no columnar overview');
39
+ const result=session.overview(data.request,{copy:true});const transfer=[];
40
+ if(result.ok)for(const v of Object.values(result.overview))if(ArrayBuffer.isView(v))transfer.push(v.buffer);
41
+ self.postMessage({requestId:data.requestId,...result},transfer);return;
42
+ }
29
43
  running=data.requestId;const result=session.run(data.request);running=null;
30
44
  self.postMessage({requestId:data.requestId,...result});return;
31
45
  }