@arqlet/engine-client 0.2.0 → 0.4.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/README.md CHANGED
@@ -5,6 +5,9 @@ The Arqlet engine as WebAssembly (`arqlet.wasm`, included) and its JavaScript ac
5
5
  - `engine.js`: `loadEngine(url?)` (browser via `fetch`, Node from disk), `sceneOf(run, snapshot)`, `createEngineWorker(url?)`;
6
6
  - `wasm-client.js`: `createEngine(bytes, {onPublish})`, the raw binding;
7
7
  - `elk.js`: `createElkLayout(run)`, an `elk.layout(graph)`-style call;
8
+ - `session.js`: `createSession(run)`, a layout session that keeps positions across changes (collapse, expand, …)
9
+ with revision checks, `createOverviewSession(run)`, a cluster overview whose graph stays in the engine (later layouts
10
+ send only what changed), and `workerRun(worker)` / `httpRun(base)`, a worker or a backend as an asynchronous `run`;
8
11
  - `presets.js`: `presetState` and `applyPreset`.
9
12
 
10
13
  Most users want the [`arqlet`](https://www.npmjs.com/package/arqlet) package, which re-exports these.
package/arqlet.wasm CHANGED
Binary file
package/elk.d.ts CHANGED
@@ -46,7 +46,8 @@ export interface ElkNode extends ElkShape {
46
46
  export interface ElkLayoutOptions {
47
47
  /** Arqlet layout options; they win over the ones translated from `layoutOptions`. */
48
48
  options?: Record<string, unknown>;
49
- /** Runs the refinement after the layout. Default `false`. */
49
+ /** Runs the refinement after the layout. Default `false`. It removes conflicts (routes through nodes, shared lines);
50
+ * a drawing without them comes back the same, a little later. */
50
51
  refine?: boolean;
51
52
  }
52
53
 
package/engine.js CHANGED
@@ -16,7 +16,8 @@ async function readWasm(url) {
16
16
  const {readFile} = await import(fs);
17
17
  return readFile(href);
18
18
  }
19
- const response = await fetch(href, {cache: 'no-store'});
19
+ // The browser's HTTP cache applies, as for any asset.
20
+ const response = await fetch(href);
20
21
  if (!response.ok) throw Error(`Engine not available: ${href}`);
21
22
  return response.arrayBuffer();
22
23
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@arqlet/engine-client",
3
- "version": "0.2.0",
3
+ "version": "0.4.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",
@@ -43,6 +43,10 @@
43
43
  "types": "./elk.d.ts",
44
44
  "default": "./elk.js"
45
45
  },
46
+ "./session.js": {
47
+ "types": "./session.d.ts",
48
+ "default": "./session.js"
49
+ },
46
50
  "./worker.js": "./worker.js",
47
51
  "./arqlet.wasm": "./arqlet.wasm"
48
52
  },
@@ -51,10 +55,12 @@
51
55
  "wasm-client.js",
52
56
  "presets.js",
53
57
  "elk.js",
58
+ "session.js",
54
59
  "engine.d.ts",
55
60
  "wasm-client.d.ts",
56
61
  "presets.d.ts",
57
62
  "elk.d.ts",
63
+ "session.d.ts",
58
64
  "worker.js",
59
65
  "arqlet.wasm",
60
66
  "README.md",
@@ -65,7 +71,7 @@
65
71
  "access": "public"
66
72
  },
67
73
  "dependencies": {
68
- "@arqlet/contracts": "^0.2.0"
74
+ "@arqlet/contracts": "^0.4.0"
69
75
  },
70
76
  "scripts": {
71
77
  "test": "node --test"
package/session.d.ts ADDED
@@ -0,0 +1,139 @@
1
+ import type {Graph, Hidden, Overview, OverviewRequest, Scene, Snapshot} from '@arqlet/contracts';
2
+ import type {EngineRequest, EngineResponse, Run} from './wasm-client.js';
3
+
4
+ /** An engine answer as the session reports it. `stale`: an import or reset overtook the change, nothing was applied. */
5
+ export interface SessionResult {
6
+ ok: boolean;
7
+ snapshot?: Snapshot;
8
+ error?: string;
9
+ stale?: boolean;
10
+ /** `expand`/`collapse`: the container was in that state already; no engine call was made. */
11
+ unchanged?: boolean;
12
+ }
13
+
14
+ /** Provisional: one graph, its current snapshot, and changes applied in order with revision checks. */
15
+ export interface Session {
16
+ /**
17
+ * The current snapshot, or null before the first import. With a resident session only its state (`revision`,
18
+ * `layoutVersion`, `collapsedIds`); `exportSnapshot()` gives the whole snapshot.
19
+ */
20
+ readonly snapshot: Snapshot | null;
21
+ /**
22
+ * Lays out `graph` (nodes with `parentId` are containers) and starts the session on it; changes still under way are
23
+ * dropped. `limit`: the most nodes the first view selects (default: all, at most `MAX_VIEW_LIMIT`). `options`: layout
24
+ * options.
25
+ */
26
+ import(graph: Graph, init?: {limit?: number; options?: Record<string, unknown>}): Promise<SessionResult>;
27
+ /** Drops the snapshot; changes still under way resolve as stale. */
28
+ reset(): void;
29
+ /** Whether container `id` is collapsed in the current snapshot. */
30
+ isCollapsed(id: string): boolean;
31
+ /** Collapses or expands container `id`. */
32
+ toggle(id: string): Promise<SessionResult>;
33
+ /** Expands container `id` unless it is open. */
34
+ expand(id: string): Promise<SessionResult>;
35
+ /** Collapses container `id` unless it is collapsed. */
36
+ collapse(id: string): Promise<SessionResult>;
37
+ /** Any other change of the protocol (`direction`, `configure`, `add`, …); snapshot and expected versions are added. */
38
+ apply(request: Omit<EngineRequest, 'snapshot' | 'expectedRevision' | 'expectedLayoutVersion'> & {op: string}): Promise<SessionResult>;
39
+ /**
40
+ * Provisional (path cut-out): the paths between two nodes of the current snapshot, read only. `visible` names the boxes
41
+ * and routes of the current view that carry them; `distance` the hops of every visible node from the path.
42
+ * `edgeKinds`: the paths follow only edges of these kinds (default: every edge).
43
+ */
44
+ trace(from: string, to: string, init?: {mode?: 'shortest' | 'all'; edgeKinds?: string[]}): Promise<EngineResponse>;
45
+ /** Provisional: opens the groups that hold `nodeIds`; with `partial` (default true) only as far as needed. */
46
+ reveal(nodeIds: string[], init?: {partial?: boolean}): Promise<SessionResult>;
47
+ /** Provisional: hides nodes by kind or id (with what they hold) and edges by kind, keeping the place of the rest;
48
+ * `hide` replaces what was hidden before, `{}` shows everything. */
49
+ filter(hide?: Hidden): Promise<SessionResult>;
50
+ /** The scene of the current snapshot, computed once per snapshot. Throws the engine's error. */
51
+ scene(): Promise<Scene>;
52
+ /** The whole snapshot: the current one, or with `resident` the one the engine keeps (for saving or hand-over). */
53
+ exportSnapshot(): Promise<Snapshot | null>;
54
+ /** Whether the snapshot stays in the engine. */
55
+ readonly resident: boolean;
56
+ /** Ends a resident session in the engine (frees its snapshot); the session is not usable afterwards. */
57
+ close(): Promise<void>;
58
+ }
59
+
60
+ /** A session whose snapshot stays in the engine (`openSession`); requests leave the snapshot out. Provisional. */
61
+ export interface ResidentSession {
62
+ run(request: EngineRequest): EngineResponse | Promise<EngineResponse>;
63
+ close(): unknown;
64
+ }
65
+
66
+ /** Creates a session on an engine `run`, synchronous (`loadEngine`) or asynchronous (`workerRun`). */
67
+ export function createSession(
68
+ run: (Run | ((request: EngineRequest) => Promise<EngineResponse>)) & {
69
+ openSession?: () => ResidentSession | Promise<ResidentSession>;
70
+ },
71
+ init?: {
72
+ onChange?: (snapshot: Snapshot) => void;
73
+ /**
74
+ * Provisional (ADR 0019): keep the snapshot in the engine. Requests carry only the change and answers bring the
75
+ * scene; `snapshot` is then the session's state (revision, layout version, collapsed containers). `'auto'` (default):
76
+ * where the engine can (`openSession`); `true`: always; `false`: never.
77
+ */
78
+ resident?: boolean | 'auto';
79
+ },
80
+ ): Session;
81
+
82
+ /**
83
+ * Wraps a worker of `createEngineWorker` as an asynchronous run. `onPublication` receives the progressive publications
84
+ * of a running request.
85
+ */
86
+ export function workerRun(
87
+ worker: Worker,
88
+ init?: {onPublication?: (requestId: number, message: unknown) => void},
89
+ ): ((request: EngineRequest) => Promise<EngineResponse>) & {openSession(): Promise<ResidentSession>};
90
+
91
+ /**
92
+ * Provisional: a backend as an asynchronous run (`${base}/op`), with sessions kept in the backend
93
+ * (`${base}/session`). `fetchImpl` replaces `fetch`.
94
+ */
95
+ export function httpRun(
96
+ base?: string,
97
+ init?: {fetchImpl?: typeof fetch},
98
+ ): ((request: EngineRequest) => Promise<EngineResponse>) & {openSession(): Promise<ResidentSession>};
99
+
100
+ /**
101
+ * An overview request without `op` and `graph` (`OverviewRequest` in `@arqlet/contracts`): `start` without positions
102
+ * continues from the last overview.
103
+ */
104
+ export type OverviewSessionRequest = Omit<OverviewRequest, 'graph'>;
105
+
106
+ /** The answer to an overview request: `overview` (ids, parent, x, y, r, labels, kinds, …) when `ok`. */
107
+ export interface OverviewAnswer {
108
+ ok: boolean;
109
+ overview?: Overview;
110
+ error?: string;
111
+ /** A new `open` overtook it; nothing was applied. */
112
+ stale?: boolean;
113
+ }
114
+
115
+ /** Provisional: an overview of one graph, laid out again as the host asks; the graph stays in the engine where it can. */
116
+ export interface OverviewSession {
117
+ /** Lays out `graph`; replaces the graph the session had. */
118
+ open(graph: Graph, request?: OverviewSessionRequest): Promise<OverviewAnswer>;
119
+ /** Lays out the graph again; `start` without positions continues from the last overview (same cluster options). */
120
+ layOut(request?: OverviewSessionRequest): Promise<OverviewAnswer>;
121
+ /** The last overview, or null. */
122
+ readonly overview: OverviewAnswer['overview'] | null;
123
+ /** Whether the graph stays in the engine. */
124
+ readonly resident: boolean;
125
+ /** Ends the session and frees the graph in the engine. */
126
+ close(): Promise<void>;
127
+ }
128
+
129
+ /** Creates an overview session on an engine `run`; `resident` as for `createSession`. */
130
+ export function createOverviewSession(
131
+ run: (Run | ((request: EngineRequest) => Promise<EngineResponse>)) & {
132
+ openSession?: () => ResidentSession | Promise<ResidentSession>;
133
+ },
134
+ init?: {resident?: boolean | 'auto'},
135
+ ): OverviewSession;
136
+
137
+ /** The most nodes an import selects for its view; the default of `Session.import`'s limit. */
138
+ export const MAX_VIEW_LIMIT: number;
139
+
package/session.js ADDED
@@ -0,0 +1,291 @@
1
+ // A layout session (provisional): one graph, its current snapshot, and the changes sent to the engine as operations on
2
+ // it, so that unchanged parts keep their place. Pure: no DOM, no fetch; `run` is the engine (`loadEngine`) or a worker
3
+ // (`workerRun`).
4
+ //
5
+ // The engine refuses a change to an older snapshot ("Stale view request"); the session adds the snapshot's revision and
6
+ // layout version to every change, runs changes one after the other on the newest snapshot, and never applies an answer
7
+ // that was overtaken: after a new `import`, or `reset`, a change still under way resolves to `{ok: false, stale: true}`.
8
+
9
+ /**
10
+ * Wraps a worker of `createEngineWorker` as an asynchronous `run`: each request gets an id, and the answer with that id
11
+ * resolves it. Progressive publications are passed to `onPublication(requestId, message)`.
12
+ */
13
+ export function workerRun(worker, {onPublication} = {}) {
14
+ let next = 0;
15
+ const waiting = new Map();
16
+ worker.addEventListener('message', ({data}) => {
17
+ const pending = waiting.get(data?.requestId);
18
+ if (!pending) return;
19
+ if (data.publication !== undefined) { onPublication?.(data.requestId, data); return; }
20
+ waiting.delete(data.requestId);
21
+ const {requestId, ...response} = data;
22
+ pending(response);
23
+ });
24
+ const post = message => new Promise(resolve => {
25
+ const requestId = ++next;
26
+ waiting.set(requestId, resolve);
27
+ worker.postMessage({requestId, ...message});
28
+ });
29
+ const run = request => post({request});
30
+ // Provisional (ADR 0019, step 3): a session kept in the worker; its requests leave the snapshot out.
31
+ run.openSession = async () => {
32
+ const opened = await post({session: 'open'});
33
+ if (!opened.ok) throw Error(opened.error);
34
+ return {run: request => post({session: opened.session, request}), close: () => post({session: opened.session, close: true})};
35
+ };
36
+ return run;
37
+ }
38
+
39
+ /** The most nodes an import selects for its view (the engine's `MAX_VIEW_LIMIT`); the default of `import`'s limit. */
40
+ export const MAX_VIEW_LIMIT = 10000;
41
+
42
+ /**
43
+ * Provisional (ADR 0019): a backend as an asynchronous `run`. Requests go to `${base}/op` (one native computation each);
44
+ * `openSession()` keeps a session in the backend (`${base}/session`), whose requests leave the snapshot out. `fetchImpl`
45
+ * replaces `fetch` (tests, other transports). The playground's backend (`apps/playground/server.py`) answers both.
46
+ */
47
+ export function httpRun(base = '/api', {fetchImpl = globalThis.fetch} = {}) {
48
+ const post = async (path, body) => {
49
+ const response = await fetchImpl(`${base}/${path}`, {
50
+ method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(body),
51
+ });
52
+ try { return await response.json(); } catch { return {ok: false, error: `HTTP ${response.status}`}; }
53
+ };
54
+ const run = request => post('op', request);
55
+ run.openSession = async () => {
56
+ const opened = await post('session', {session: 'open'});
57
+ if (!opened.ok) throw Error(opened.error);
58
+ return {
59
+ run: request => post('session', {session: opened.session, request}),
60
+ close: () => post('session', {session: opened.session, close: true}),
61
+ };
62
+ };
63
+ return run;
64
+ }
65
+
66
+ /**
67
+ * Creates a session on `run` (synchronous or asynchronous). `onChange(snapshot)` is called after every applied change.
68
+ *
69
+ * Where the engine can keep a session (`run.openSession`, which `loadEngine` and `workerRun` provide), the snapshot
70
+ * stays in the engine (ADR 0019): requests carry only the change, answers bring the scene, and `snapshot` is the
71
+ * session's state (`revision`, `layoutVersion`, `collapsedIds`); `exportSnapshot()` gives the whole snapshot. `resident`
72
+ * chooses: `'auto'` (default) where the engine can, `true` always (an error without it), `false` never (every request
73
+ * sends the snapshot, as before 0.4).
74
+ */
75
+ export function createSession(run, {onChange, resident: wanted = 'auto'} = {}) {
76
+ let snapshot = null;
77
+ let generation = 0;
78
+ let queue = Promise.resolve();
79
+ const scenes = new WeakMap();
80
+ if (wanted === true && !run.openSession) throw Error('This engine has no resident sessions');
81
+ const resident = wanted === true || (wanted === 'auto' && typeof run.openSession === 'function');
82
+ const opened = resident ? Promise.resolve(run.openSession()) : null;
83
+ // The engine call: with a resident session, the request goes to it and its answer is turned into the shape of an
84
+ // answer with a snapshot (the state), its scene remembered for that state.
85
+ const call = async request => {
86
+ if (!resident) return run(request);
87
+ const {snapshot: _sent, ...rest} = request;
88
+ const answer = await (await opened).run(rest);
89
+ if (!answer.ok || answer.revision === undefined) return answer;
90
+ const state = {revision: answer.revision, layoutVersion: answer.layoutVersion, collapsedIds: answer.collapsedIds};
91
+ if (answer.scene) scenes.set(state, answer.scene);
92
+ return {ok: true, snapshot: state};
93
+ };
94
+
95
+ // Runs `step` after every change before it; its answer counts only if no import or reset came in between.
96
+ const enqueue = step => {
97
+ const mine = generation;
98
+ const result = queue.then(async () => {
99
+ if (mine !== generation) return {ok: false, stale: true, error: 'The session was reset.'};
100
+ const answer = await step();
101
+ if (mine !== generation) return {ok: false, stale: true, error: 'The session was reset.'};
102
+ if (answer?.ok && answer.snapshot && !answer.unchanged) {
103
+ snapshot = answer.snapshot;
104
+ onChange?.(snapshot);
105
+ }
106
+ return answer;
107
+ });
108
+ queue = result.catch(() => {});
109
+ return result;
110
+ };
111
+
112
+ // A change to the current snapshot; called inside a queued step.
113
+ const send = request => {
114
+ if (!snapshot) return {ok: false, error: 'Nothing imported yet.'};
115
+ return call({
116
+ ...request,
117
+ snapshot,
118
+ expectedRevision: snapshot.revision,
119
+ expectedLayoutVersion: snapshot.layoutVersion,
120
+ });
121
+ };
122
+ const change = request => enqueue(() => send(request));
123
+
124
+ const collapsed = id => (snapshot?.collapsedIds ?? []).includes(id);
125
+ // Toggles `id` only when it is not yet in the wanted state, decided and sent in one step.
126
+ const ensure = (id, wantCollapsed) => enqueue(() => (collapsed(id) === wantCollapsed
127
+ ? {ok: true, snapshot, unchanged: true}
128
+ : send({op: 'toggle', nodeId: id})));
129
+
130
+ return {
131
+ /** The current snapshot, or null before the first import. */
132
+ get snapshot() { return snapshot; },
133
+
134
+ /**
135
+ * Lays out `graph` (nodes with `parentId` are containers) and starts the session on it. `limit` is the most nodes
136
+ * the first view selects (default: all, at most `MAX_VIEW_LIMIT`; containers beyond it start collapsed); `options` are layout options (`docs/configuration.md`).
137
+ * Any change still under way is dropped.
138
+ */
139
+ import(graph, {limit = Math.min(graph.nodes.length, MAX_VIEW_LIMIT), options} = {}) {
140
+ generation++;
141
+ return enqueue(() => call({op: 'import', graph, limit, ...(options ? {options} : {})}));
142
+ },
143
+
144
+ /** Drops the snapshot; changes still under way resolve as stale. */
145
+ reset() {
146
+ generation++;
147
+ snapshot = null;
148
+ },
149
+
150
+ /** Whether container `id` is collapsed in the current snapshot. */
151
+ isCollapsed: collapsed,
152
+
153
+ /** Collapses or expands container `id`. */
154
+ toggle(id) { return change({op: 'toggle', nodeId: id}); },
155
+
156
+ /** Expands container `id`; `{ok: true, unchanged: true}` when it is open already. */
157
+ expand(id) { return ensure(id, false); },
158
+
159
+ /** Collapses container `id`; `{ok: true, unchanged: true}` when it is collapsed already. */
160
+ collapse(id) { return ensure(id, true); },
161
+
162
+ /**
163
+ * Any other change of the engine's protocol, for example `{op: 'direction', nodeId, direction: 'tb'}`,
164
+ * `{op: 'configure', options}` or `{op: 'add', sourceId, label}`. The snapshot and the expected versions are added.
165
+ */
166
+ apply(request) { return change(request); },
167
+
168
+ /**
169
+ * Provisional (path cut-out): the paths from `from` to `to` in the current snapshot (read only, nothing changes):
170
+ * `{ok, found, reversed, length, nodes, edges, visible: {nodes, routes}, distance}`. `mode`: `shortest` (default) or
171
+ * `all`. `edgeKinds`: follow only edges of these kinds (default: every edge).
172
+ */
173
+ async trace(from, to, {mode = 'shortest', edgeKinds} = {}) {
174
+ if (!snapshot) return {ok: false, error: 'Nothing imported yet.'};
175
+ return call({op: 'trace', snapshot, from, to, mode, ...(edgeKinds ? {edgeKinds} : {})});
176
+ },
177
+
178
+ /** Provisional: opens the groups that hold `nodeIds`; with `partial` (default) only as far as needed. */
179
+ reveal(nodeIds, {partial = true} = {}) { return change({op: 'reveal', nodeIds, partial}); },
180
+
181
+ /**
182
+ * Provisional: hides nodes by kind or id (each with what it holds) and edges by kind, keeping the place of the rest.
183
+ * `hide` replaces what was hidden before; `{}` shows everything again.
184
+ */
185
+ filter(hide = {}) { return change({op: 'filter', hide}); },
186
+
187
+ /** The scene (drawing) of the current snapshot, computed once per snapshot. */
188
+ async scene() {
189
+ const current = snapshot;
190
+ if (!current) throw Error('Nothing imported yet.');
191
+ const known = scenes.get(current);
192
+ if (known) return known;
193
+ const answer = await call({op: 'scene', snapshot: current});
194
+ if (!answer.ok) throw Error(answer.error);
195
+ scenes.set(current, answer.scene);
196
+ return answer.scene;
197
+ },
198
+
199
+ /** The whole snapshot: the current one, or with `resident` the one the engine keeps (for saving or hand-over). */
200
+ async exportSnapshot() {
201
+ if (!snapshot) return null;
202
+ if (!resident) return snapshot;
203
+ const answer = await (await opened).run({op: 'export'});
204
+ if (!answer.ok) throw Error(answer.error);
205
+ return answer.snapshot;
206
+ },
207
+
208
+ /** Whether the snapshot stays in the engine (see `createSession`). */
209
+ get resident() { return resident; },
210
+
211
+ /** Ends a resident session in the engine (frees its snapshot). The session object is not usable afterwards. */
212
+ async close() {
213
+ generation++;
214
+ snapshot = null;
215
+ if (resident) await (await opened).close();
216
+ },
217
+ };
218
+ }
219
+
220
+ // The options the overview's clusters depend on; a continuation needs the same ones (as the engine's session checks).
221
+ // Defaults as the engine's (`communities` 120, `satellites` 0); `groups` compared as given.
222
+ const clustersOf = options => JSON.stringify([options?.communities ?? 120, options?.satellites ?? 0, options?.groups ?? null]);
223
+
224
+ /**
225
+ * Provisional (ADR 0019 for the overview): an overview of one graph, laid out again as the host asks, with the graph kept
226
+ * in the engine where it can keep a session (`run.openSession`). `open(graph, request)` lays out a graph; `layOut(request)`
227
+ * lays it out again (other options, `radii`, `intent`, `configSet`); a `start` without positions (`{settle}` or `{}`)
228
+ * continues from the last overview. Without a resident session the graph and the last positions stay here and are sent
229
+ * along; the answers are the same. A new `open` overtakes what is still under way (`{ok: false, stale: true}`).
230
+ */
231
+ export function createOverviewSession(run, {resident: wanted = 'auto'} = {}) {
232
+ if (wanted === true && !run.openSession) throw Error('This engine has no resident sessions');
233
+ const resident = wanted === true || (wanted === 'auto' && typeof run.openSession === 'function');
234
+ const opened = resident ? Promise.resolve(run.openSession()) : null;
235
+ // `graph` is kept here only without a resident session; `started`: an `open` was asked for (it may still run).
236
+ let graph = null, started = false, last = null, clusters = null, generation = 0, queue = Promise.resolve();
237
+
238
+ const send = async request => {
239
+ if (resident) return (await opened).run(request);
240
+ const sent = {...request, graph: request.graph ?? graph};
241
+ const start = request.start;
242
+ if (start && start.x === undefined) {
243
+ if (!last || request.graph) return {ok: false, error: 'No overview to continue from: lay out without start first.'};
244
+ if (clustersOf(request.options) !== clusters) return {ok: false, error: 'The clusters changed since the last overview; lay out without start.'};
245
+ sent.start = {...start, x: last.x, y: last.y, r: last.r};
246
+ }
247
+ return run(sent);
248
+ };
249
+ const enqueue = (request, fresh) => {
250
+ if (fresh) generation++;
251
+ const mine = generation;
252
+ const result = queue.then(async () => {
253
+ if (mine !== generation) return {ok: false, stale: true, error: 'A new graph overtook this overview.'};
254
+ const answer = await send(request);
255
+ if (mine !== generation) return {ok: false, stale: true, error: 'A new graph overtook this overview.'};
256
+ if (answer.ok) {
257
+ last = answer.overview;
258
+ clusters = clustersOf(request.options);
259
+ if (fresh && !resident) graph = request.graph;
260
+ }
261
+ return answer;
262
+ });
263
+ queue = result.catch(() => {});
264
+ return result;
265
+ };
266
+
267
+ return {
268
+ /** Lays out `graph` with `request` (`options`, `intent`, `configSet`, `radii`, `threads`). */
269
+ open(newGraph, request = {}) {
270
+ started = true;
271
+ return enqueue({...request, op: 'overview', graph: newGraph}, true);
272
+ },
273
+ /** Lays out the graph again; `start` without positions continues from the last overview. */
274
+ layOut(request = {}) {
275
+ if (!started) return Promise.resolve({ok: false, error: 'No graph yet: open one first.'});
276
+ const {graph: _ignored, ...rest} = request;
277
+ return enqueue({...rest, op: 'overview'}, false);
278
+ },
279
+ /** The last overview (`{ids, parent, x, y, r, …}`), or null. */
280
+ get overview() { return last; },
281
+ /** Whether the graph stays in the engine. */
282
+ get resident() { return resident; },
283
+ /** Ends the session (frees the graph in the engine). */
284
+ async close() {
285
+ generation++;
286
+ graph = last = null;
287
+ started = false;
288
+ if (resident) await (await opened).close();
289
+ },
290
+ };
291
+ }
package/wasm-client.d.ts CHANGED
@@ -11,13 +11,18 @@ export type EngineResponse =
11
11
  | ({ok: true} & {[field: string]: any})
12
12
  | {ok: false; error: string; [field: string]: unknown};
13
13
 
14
- /** Runs one request synchronously on the engine. */
15
- export type Run = (request: EngineRequest) => EngineResponse;
14
+ /**
15
+ * Runs one request synchronously on the engine. `openSession` (provisional, ADR 0019 step 3) opens a session whose
16
+ * snapshot stays in the engine: its requests leave the snapshot out, and its answers bring the scene.
17
+ */
18
+ export type Run = ((request: EngineRequest) => EngineResponse) & {
19
+ openSession?: () => {run(request: EngineRequest): EngineResponse; close(): void};
20
+ };
16
21
 
17
22
  export interface CreateEngineOptions {
18
23
  /** Receives each progressive publication (JSON text) while the call that produced it is still running. */
19
24
  onPublish?: (message: string) => void;
20
25
  }
21
26
 
22
- /** Instantiates the WASM engine from its bytes. */
23
- export function createEngine(bytes: BufferSource, options?: CreateEngineOptions): Promise<Run>;
27
+ /** Instantiates the WASM engine from its bytes, or from a module the host compiled already. */
28
+ export function createEngine(bytes: BufferSource | WebAssembly.Module, options?: CreateEngineOptions): Promise<Run>;
package/wasm-client.js CHANGED
@@ -10,17 +10,29 @@ export async function createEngine(bytes,{onPublish}={}) {
10
10
  onPublish(decoder.decode(new Uint8Array(api.memory.buffer,ptr,len)));
11
11
  },
12
12
  }};
13
- const {instance}=await WebAssembly.instantiate(bytes,imports);
13
+ // The bytes of the module, or a module the host compiled already (then it is not compiled again).
14
+ const result=await WebAssembly.instantiate(bytes,imports);
15
+ const instance=result instanceof WebAssembly.Instance?result:result.instance;
14
16
  api=instance.exports;
15
- return input=>{
17
+ // Copies a request into the module, runs `call` on it, and reads the answer (both buffers freed afterwards).
18
+ const exchange=(input,call)=>{
16
19
  const encoded=new TextEncoder().encode(JSON.stringify(input));
17
20
  const ptr=api.lw_alloc(encoded.length);
18
21
  let out=0,len=0;
19
22
  try {
20
23
  new Uint8Array(api.memory.buffer,ptr,encoded.length).set(encoded);
21
- const result=api.lw_run(ptr,encoded.length);
24
+ const result=call(ptr,encoded.length);
22
25
  out=Number(result & 0xffffffffn);len=Number(result >> 32n);
23
26
  return JSON.parse(decoder.decode(new Uint8Array(api.memory.buffer,out,len)));
24
27
  } finally {api.lw_free(ptr,encoded.length);if(out)api.lw_free(out,len);}
25
28
  };
29
+ const run=input=>exchange(input,(ptr,len)=>api.lw_run(ptr,len));
30
+ // Provisional (ADR 0019, step 3): a session whose snapshot stays in the module; requests leave the snapshot out.
31
+ if(api.lw_session_open){
32
+ run.openSession=()=>{
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)};
35
+ };
36
+ }
37
+ return run;
26
38
  }
package/worker.js CHANGED
@@ -3,13 +3,33 @@ import {createEngine} from './wasm-client.js';
3
3
  const wasmUrl=new URL(self.location.href).searchParams.get('wasm');
4
4
  // The request being run. Publications are forwarded while its call is still executing; the final reply follows it.
5
5
  let running=null;
6
- const engine=fetch(wasmUrl,{cache:'no-store'}).then(r=>{if(!r.ok)throw Error(`Engine not available: ${wasmUrl}`);return r.arrayBuffer();})
6
+ // The browser's HTTP cache applies: an unchanged engine is not downloaded again for every worker.
7
+ const engine=fetch(wasmUrl).then(r=>{if(!r.ok)throw Error(`Engine not available: ${wasmUrl}`);return r.arrayBuffer();})
7
8
  .then(bytes=>createEngine(bytes,{onPublish:text=>{
8
9
  if(running===null) return;
9
10
  // emittedAt and bytes let the page split the latency into computation, transfer and display.
10
11
  self.postMessage({requestId:running,publication:JSON.parse(text).publication,emittedAt:Date.now(),bytes:text.length});
11
12
  }}));
13
+ // Provisional (ADR 0019, step 3): sessions kept in this worker, by handle. `{requestId, session: 'open'}` answers
14
+ // `{session: id}`; `{requestId, session: id, request}` runs a request in it; `{requestId, session: id, close: true}` ends it.
15
+ const sessions=new Map();
16
+ let nextSession=0;
12
17
  self.onmessage=async({data})=>{
13
- try{const run=await engine;running=data.requestId;const result=run(data.request);running=null;self.postMessage({requestId:data.requestId,...result});}
18
+ try{
19
+ const run=await engine;
20
+ if(data.session==='open'){
21
+ if(!run.openSession)throw Error('This engine has no sessions');
22
+ const id=++nextSession;sessions.set(id,run.openSession());
23
+ self.postMessage({requestId:data.requestId,ok:true,session:id});return;
24
+ }
25
+ if(data.session!==undefined){
26
+ const session=sessions.get(data.session);
27
+ if(!session)throw Error('Unknown session');
28
+ if(data.close){session.close();sessions.delete(data.session);self.postMessage({requestId:data.requestId,ok:true});return;}
29
+ running=data.requestId;const result=session.run(data.request);running=null;
30
+ self.postMessage({requestId:data.requestId,...result});return;
31
+ }
32
+ running=data.requestId;const result=run(data.request);running=null;self.postMessage({requestId:data.requestId,...result});
33
+ }
14
34
  catch(e){running=null;self.postMessage({requestId:data.requestId,ok:false,error:e.message});}
15
35
  };