logic-mesh 0.9.0 → 2.0.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/LICENSE +11 -0
- package/README.md +400 -57
- package/dist/EngineSession.d.ts +206 -0
- package/dist/EngineSession.js +277 -0
- package/dist/JsBlocks.d.ts +150 -0
- package/dist/JsBlocks.js +211 -0
- package/dist/LogicMeshError.d.ts +38 -0
- package/dist/LogicMeshError.js +9 -0
- package/dist/ProgramSchema.d.ts +57 -0
- package/dist/ProgramSchema.js +103 -0
- package/dist/ProgramVersion.d.ts +10 -0
- package/dist/ProgramVersion.js +13 -0
- package/dist/TypedBlock.d.ts +34 -4
- package/dist/TypedBlock.js +121 -37
- package/dist/index.d.ts +241 -52
- package/dist/index.js +7 -2
- package/dist/logic_mesh.d.ts +295 -104
- package/dist/logic_mesh.js +1 -1
- package/dist/logic_mesh_bg.js +904 -452
- package/dist/logic_mesh_bg.wasm +0 -0
- package/dist/logic_mesh_bg.wasm.d.ts +45 -26
- package/package.json +72 -47
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
import type { BlockNotification } from './index.js';
|
|
2
|
+
import type { BlocksEngine, EngineCommand } from './logic_mesh.js';
|
|
3
|
+
/**
|
|
4
|
+
* Options for {@link createEngineSession} and {@link startEngine}.
|
|
5
|
+
*/
|
|
6
|
+
export interface EngineSessionOptions {
|
|
7
|
+
/**
|
|
8
|
+
* An engine to adopt instead of creating one. It must not have been
|
|
9
|
+
* run yet — the session creates its command handles from it, which
|
|
10
|
+
* is impossible once `run()`'s future has been polled.
|
|
11
|
+
*/
|
|
12
|
+
engine?: BlocksEngine;
|
|
13
|
+
/**
|
|
14
|
+
* The engine's scan interval in milliseconds — how long a block that
|
|
15
|
+
* runs on every cycle waits between runs — forwarded to `initEngine`
|
|
16
|
+
* when the session creates the engine itself. Ignored when an
|
|
17
|
+
* `engine` is supplied.
|
|
18
|
+
*/
|
|
19
|
+
scanInterval?: number;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* A watch {@link EngineSession.watch} opened. Close it with
|
|
23
|
+
* {@link close}, or let `await using` close it.
|
|
24
|
+
*/
|
|
25
|
+
export interface WatchSubscription extends AsyncDisposable {
|
|
26
|
+
/** The watch's id, as `EngineCommand.createWatch` resolved with it. */
|
|
27
|
+
readonly id: number;
|
|
28
|
+
/**
|
|
29
|
+
* Closes the watch, resolving with whether the engine still had it
|
|
30
|
+
* open — `false` once the session has stopped. The callback is not
|
|
31
|
+
* called from the moment this is called. Idempotent: later calls
|
|
32
|
+
* share the first call's promise.
|
|
33
|
+
*/
|
|
34
|
+
close(): Promise<boolean>;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Owns the engine start sequence, so the ordering rules cannot be
|
|
38
|
+
* gotten wrong.
|
|
39
|
+
*
|
|
40
|
+
* Two wasm-bindgen facts make the manual sequence a footgun:
|
|
41
|
+
*
|
|
42
|
+
* 1. The future `BlocksEngine.run()` returns holds the engine object's
|
|
43
|
+
* wasm borrow for as long as the engine lives. From the moment that
|
|
44
|
+
* future is first polled — the microtask after `run()` is called —
|
|
45
|
+
* ANY method call on the engine object (`engineCommand()`,
|
|
46
|
+
* `listBlocks()`, `registerBlock()`, …) throws "recursive use of an
|
|
47
|
+
* object detected". Every command handle must therefore be created
|
|
48
|
+
* before `run()`.
|
|
49
|
+
* 2. Commands are serviced only while the engine's message loop runs,
|
|
50
|
+
* and `run()`'s promise resolves only when the engine shuts down.
|
|
51
|
+
* Awaiting `run()` before issuing commands deadlocks, and so does
|
|
52
|
+
* awaiting a command before `run()` has been kicked off.
|
|
53
|
+
*
|
|
54
|
+
* The session bakes the correct order in: its command handles are
|
|
55
|
+
* created up front, {@link start} kicks `run()` off without awaiting
|
|
56
|
+
* it, and {@link stop} / {@link reset} travel through a dedicated
|
|
57
|
+
* control handle so they never touch the engine object.
|
|
58
|
+
*
|
|
59
|
+
* A command handle takes any number of calls at once: each call's
|
|
60
|
+
* promise settles with the engine's answer to that call. Every handle
|
|
61
|
+
* feeds the same engine, which handles requests in the order they
|
|
62
|
+
* arrive. A failed command rejects with a `LogicMeshError` (see
|
|
63
|
+
* `isLogicMeshError`).
|
|
64
|
+
*
|
|
65
|
+
* Create a session with {@link startEngine} (creates, then starts) or
|
|
66
|
+
* {@link createEngineSession} (handles now, {@link start} later — for
|
|
67
|
+
* hosts that create the engine at module load but start it on mount).
|
|
68
|
+
*/
|
|
69
|
+
export declare class EngineSession implements AsyncDisposable {
|
|
70
|
+
/**
|
|
71
|
+
* The engine object. Valid for pre-start setup only —
|
|
72
|
+
* `registerBlock`, `listBlocks`, `run` — and off limits from the
|
|
73
|
+
* first poll of `run()`'s future onwards; use the command handles
|
|
74
|
+
* instead.
|
|
75
|
+
*/
|
|
76
|
+
readonly engine: BlocksEngine;
|
|
77
|
+
/** The general-purpose command handle. */
|
|
78
|
+
readonly command: EngineCommand;
|
|
79
|
+
/**
|
|
80
|
+
* A handle dedicated to connector attachment, kept for callers that
|
|
81
|
+
* want their attach flows on a handle of their own.
|
|
82
|
+
*/
|
|
83
|
+
readonly connectorCommand: EngineCommand;
|
|
84
|
+
/** Stop/reset handle — see the class docs. */
|
|
85
|
+
private readonly control;
|
|
86
|
+
/** Orders control operations: a reset issued before a stop runs
|
|
87
|
+
* first. */
|
|
88
|
+
private controlChain;
|
|
89
|
+
private runDone;
|
|
90
|
+
private stopDone;
|
|
91
|
+
/** Whether `run()`'s future has completed: the engine answers
|
|
92
|
+
* nothing from then on. */
|
|
93
|
+
private ended;
|
|
94
|
+
constructor(options?: EngineSessionOptions);
|
|
95
|
+
/** Whether {@link start} has been called. */
|
|
96
|
+
get started(): boolean;
|
|
97
|
+
/**
|
|
98
|
+
* Kicks off `engine.run()` without awaiting it (its promise resolves
|
|
99
|
+
* only on shutdown; {@link stop} awaits it then). Idempotent. From
|
|
100
|
+
* here on the engine object must not be touched — everything goes
|
|
101
|
+
* through the pre-created command handles.
|
|
102
|
+
*
|
|
103
|
+
* Throws after {@link stop}: a session runs its engine once. Once
|
|
104
|
+
* the engine has stopped, the session answers {@link watch},
|
|
105
|
+
* {@link unwatch}, {@link reset} and {@link stop} without asking the
|
|
106
|
+
* engine, and a restart under it would contradict that.
|
|
107
|
+
*/
|
|
108
|
+
start(): void;
|
|
109
|
+
/**
|
|
110
|
+
* Mints an additional command handle. Only possible before
|
|
111
|
+
* {@link start} — afterwards the engine's wasm borrow is held by
|
|
112
|
+
* `run()`'s future and this throws a descriptive error instead of
|
|
113
|
+
* the raw "recursive use of an object" one. The session's handles
|
|
114
|
+
* take overlapping calls, so most hosts need no more.
|
|
115
|
+
*/
|
|
116
|
+
createCommand(): EngineCommand;
|
|
117
|
+
/**
|
|
118
|
+
* Registers `callback` for block change notifications, resolving with
|
|
119
|
+
* the watch once the engine opened it — before or after
|
|
120
|
+
* {@link start}: before, the watch opens as the engine starts. Close
|
|
121
|
+
* the watch to stop the notifications:
|
|
122
|
+
*
|
|
123
|
+
* ```ts
|
|
124
|
+
* await using watch = await session.watch((n) => console.log(n));
|
|
125
|
+
* // ...
|
|
126
|
+
* // Closed when the scope ends, or earlier with `watch.close()`.
|
|
127
|
+
* ```
|
|
128
|
+
*
|
|
129
|
+
* The watch may outlive the session: once the session has stopped,
|
|
130
|
+
* closing it resolves `false` at once. Rejects if the session stops
|
|
131
|
+
* before the engine opened the watch.
|
|
132
|
+
*/
|
|
133
|
+
watch(callback: (notification: BlockNotification) => void): Promise<WatchSubscription>;
|
|
134
|
+
/**
|
|
135
|
+
* Closes the watch with id `watchId` — one `EngineCommand.createWatch`
|
|
136
|
+
* opened, or a {@link WatchSubscription.id} — resolving with whether
|
|
137
|
+
* it was open. Once the session has stopped, resolves `false`: the
|
|
138
|
+
* engine is gone, and its watches with it.
|
|
139
|
+
*/
|
|
140
|
+
unwatch(watchId: number): Promise<boolean>;
|
|
141
|
+
/**
|
|
142
|
+
* Resets the engine — terminates all blocks and links, and detaches,
|
|
143
|
+
* stops and unregisters the engine-managed connectors. Resolves once
|
|
144
|
+
* the reset is done, so a command issued afterwards sees the engine
|
|
145
|
+
* empty.
|
|
146
|
+
*
|
|
147
|
+
* Rejects once the engine has stopped — through {@link stop}, or a
|
|
148
|
+
* `stopEngine` sent on a command handle — or if it stops before
|
|
149
|
+
* answering: there is nothing left to reset, and the request would
|
|
150
|
+
* otherwise wait on the ended message loop forever. (A reset issued
|
|
151
|
+
* concurrently with stop() is fine: both go through the control
|
|
152
|
+
* chain, reset first.)
|
|
153
|
+
*/
|
|
154
|
+
reset(): Promise<void>;
|
|
155
|
+
/**
|
|
156
|
+
* Shuts the engine down and resolves once `run()`'s future has
|
|
157
|
+
* completed. A no-op before {@link start}. The session is spent
|
|
158
|
+
* afterwards — commands are no longer serviced; create a new session
|
|
159
|
+
* to run again.
|
|
160
|
+
*
|
|
161
|
+
* If the engine has already stopped — through a `stopEngine` sent on
|
|
162
|
+
* a command handle — or stops while this waits, it resolves once
|
|
163
|
+
* `run()`'s future has completed, without waiting for an answer the
|
|
164
|
+
* stopped engine will never send.
|
|
165
|
+
*/
|
|
166
|
+
stop(): Promise<void>;
|
|
167
|
+
/**
|
|
168
|
+
* {@link stop}s the session, so that `await using` stops it when the
|
|
169
|
+
* scope ends:
|
|
170
|
+
*
|
|
171
|
+
* ```ts
|
|
172
|
+
* await using session = startEngine();
|
|
173
|
+
* ```
|
|
174
|
+
*/
|
|
175
|
+
[Symbol.asyncDispose](): Promise<void>;
|
|
176
|
+
/**
|
|
177
|
+
* Sends a request with `send` and settles as it does — or with
|
|
178
|
+
* `stopped()` once the engine has stopped without answering it, or
|
|
179
|
+
* at once, without sending, if it already has. A stopped engine
|
|
180
|
+
* answers nothing, and its channel keeps a request it will never
|
|
181
|
+
* read, so the request would otherwise wait forever.
|
|
182
|
+
*/
|
|
183
|
+
private unlessStopped;
|
|
184
|
+
private enqueueControl;
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* Creates an {@link EngineSession} without starting it: the engine and
|
|
188
|
+
* every command handle exist, `run()` has not been kicked off. For
|
|
189
|
+
* hosts that must separate handle creation (module load) from engine
|
|
190
|
+
* start (mount) — call {@link EngineSession.start} when ready. Most
|
|
191
|
+
* embedders want {@link startEngine} instead.
|
|
192
|
+
*/
|
|
193
|
+
export declare function createEngineSession(options?: EngineSessionOptions): EngineSession;
|
|
194
|
+
/**
|
|
195
|
+
* Creates the engine (or adopts a not-yet-run one), pre-creates the
|
|
196
|
+
* command handles, kicks off `run()` un-awaited, and returns the
|
|
197
|
+
* ready-to-use {@link EngineSession} — the whole ordering-sensitive
|
|
198
|
+
* start sequence in one call. See the {@link EngineSession} docs for
|
|
199
|
+
* why the order matters.
|
|
200
|
+
*
|
|
201
|
+
* ```ts
|
|
202
|
+
* const { command } = startEngine();
|
|
203
|
+
* const id = await command.addBlock('SineWave');
|
|
204
|
+
* ```
|
|
205
|
+
*/
|
|
206
|
+
export declare function startEngine(options?: EngineSessionOptions): EngineSession;
|
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
import { initEngine } from './logic_mesh.js';
|
|
2
|
+
/** The {@link WatchSubscription} {@link EngineSession.watch} returns. */
|
|
3
|
+
class Subscription {
|
|
4
|
+
id;
|
|
5
|
+
closeWatch;
|
|
6
|
+
closing;
|
|
7
|
+
constructor(id, closeWatch) {
|
|
8
|
+
this.id = id;
|
|
9
|
+
this.closeWatch = closeWatch;
|
|
10
|
+
}
|
|
11
|
+
close() {
|
|
12
|
+
this.closing ??= this.closeWatch();
|
|
13
|
+
return this.closing;
|
|
14
|
+
}
|
|
15
|
+
async [Symbol.asyncDispose]() {
|
|
16
|
+
await this.close();
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Owns the engine start sequence, so the ordering rules cannot be
|
|
21
|
+
* gotten wrong.
|
|
22
|
+
*
|
|
23
|
+
* Two wasm-bindgen facts make the manual sequence a footgun:
|
|
24
|
+
*
|
|
25
|
+
* 1. The future `BlocksEngine.run()` returns holds the engine object's
|
|
26
|
+
* wasm borrow for as long as the engine lives. From the moment that
|
|
27
|
+
* future is first polled — the microtask after `run()` is called —
|
|
28
|
+
* ANY method call on the engine object (`engineCommand()`,
|
|
29
|
+
* `listBlocks()`, `registerBlock()`, …) throws "recursive use of an
|
|
30
|
+
* object detected". Every command handle must therefore be created
|
|
31
|
+
* before `run()`.
|
|
32
|
+
* 2. Commands are serviced only while the engine's message loop runs,
|
|
33
|
+
* and `run()`'s promise resolves only when the engine shuts down.
|
|
34
|
+
* Awaiting `run()` before issuing commands deadlocks, and so does
|
|
35
|
+
* awaiting a command before `run()` has been kicked off.
|
|
36
|
+
*
|
|
37
|
+
* The session bakes the correct order in: its command handles are
|
|
38
|
+
* created up front, {@link start} kicks `run()` off without awaiting
|
|
39
|
+
* it, and {@link stop} / {@link reset} travel through a dedicated
|
|
40
|
+
* control handle so they never touch the engine object.
|
|
41
|
+
*
|
|
42
|
+
* A command handle takes any number of calls at once: each call's
|
|
43
|
+
* promise settles with the engine's answer to that call. Every handle
|
|
44
|
+
* feeds the same engine, which handles requests in the order they
|
|
45
|
+
* arrive. A failed command rejects with a `LogicMeshError` (see
|
|
46
|
+
* `isLogicMeshError`).
|
|
47
|
+
*
|
|
48
|
+
* Create a session with {@link startEngine} (creates, then starts) or
|
|
49
|
+
* {@link createEngineSession} (handles now, {@link start} later — for
|
|
50
|
+
* hosts that create the engine at module load but start it on mount).
|
|
51
|
+
*/
|
|
52
|
+
export class EngineSession {
|
|
53
|
+
/**
|
|
54
|
+
* The engine object. Valid for pre-start setup only —
|
|
55
|
+
* `registerBlock`, `listBlocks`, `run` — and off limits from the
|
|
56
|
+
* first poll of `run()`'s future onwards; use the command handles
|
|
57
|
+
* instead.
|
|
58
|
+
*/
|
|
59
|
+
engine;
|
|
60
|
+
/** The general-purpose command handle. */
|
|
61
|
+
command;
|
|
62
|
+
/**
|
|
63
|
+
* A handle dedicated to connector attachment, kept for callers that
|
|
64
|
+
* want their attach flows on a handle of their own.
|
|
65
|
+
*/
|
|
66
|
+
connectorCommand;
|
|
67
|
+
/** Stop/reset handle — see the class docs. */
|
|
68
|
+
control;
|
|
69
|
+
/** Orders control operations: a reset issued before a stop runs
|
|
70
|
+
* first. */
|
|
71
|
+
controlChain = Promise.resolve();
|
|
72
|
+
runDone;
|
|
73
|
+
stopDone;
|
|
74
|
+
/** Whether `run()`'s future has completed: the engine answers
|
|
75
|
+
* nothing from then on. */
|
|
76
|
+
ended = false;
|
|
77
|
+
constructor(options = {}) {
|
|
78
|
+
this.engine = options.engine ?? initEngine(options.scanInterval);
|
|
79
|
+
this.command = this.engine.engineCommand();
|
|
80
|
+
this.connectorCommand = this.engine.engineCommand();
|
|
81
|
+
this.control = this.engine.engineCommand();
|
|
82
|
+
}
|
|
83
|
+
/** Whether {@link start} has been called. */
|
|
84
|
+
get started() {
|
|
85
|
+
return this.runDone !== undefined;
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Kicks off `engine.run()` without awaiting it (its promise resolves
|
|
89
|
+
* only on shutdown; {@link stop} awaits it then). Idempotent. From
|
|
90
|
+
* here on the engine object must not be touched — everything goes
|
|
91
|
+
* through the pre-created command handles.
|
|
92
|
+
*
|
|
93
|
+
* Throws after {@link stop}: a session runs its engine once. Once
|
|
94
|
+
* the engine has stopped, the session answers {@link watch},
|
|
95
|
+
* {@link unwatch}, {@link reset} and {@link stop} without asking the
|
|
96
|
+
* engine, and a restart under it would contradict that.
|
|
97
|
+
*/
|
|
98
|
+
start() {
|
|
99
|
+
if (this.stopDone) {
|
|
100
|
+
throw new Error('EngineSession.start() called after stop(): a session runs its ' +
|
|
101
|
+
'engine once. Create a new session to run again.');
|
|
102
|
+
}
|
|
103
|
+
if (this.runDone)
|
|
104
|
+
return;
|
|
105
|
+
const run = this.engine.run();
|
|
106
|
+
this.runDone = run;
|
|
107
|
+
// Handling a rejection too keeps a shutdown-time one from surfacing
|
|
108
|
+
// as an unhandled rejection when nobody ever calls stop(); stop()
|
|
109
|
+
// still sees it.
|
|
110
|
+
const end = () => {
|
|
111
|
+
this.ended = true;
|
|
112
|
+
};
|
|
113
|
+
run.then(end, end);
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Mints an additional command handle. Only possible before
|
|
117
|
+
* {@link start} — afterwards the engine's wasm borrow is held by
|
|
118
|
+
* `run()`'s future and this throws a descriptive error instead of
|
|
119
|
+
* the raw "recursive use of an object" one. The session's handles
|
|
120
|
+
* take overlapping calls, so most hosts need no more.
|
|
121
|
+
*/
|
|
122
|
+
createCommand() {
|
|
123
|
+
if (this.started) {
|
|
124
|
+
throw new Error('EngineSession.createCommand() called after start(): once the ' +
|
|
125
|
+
"engine runs, run()'s future holds the engine object's wasm " +
|
|
126
|
+
'borrow and no further command handles can be created. Create ' +
|
|
127
|
+
'every handle up front, before start().');
|
|
128
|
+
}
|
|
129
|
+
return this.engine.engineCommand();
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Registers `callback` for block change notifications, resolving with
|
|
133
|
+
* the watch once the engine opened it — before or after
|
|
134
|
+
* {@link start}: before, the watch opens as the engine starts. Close
|
|
135
|
+
* the watch to stop the notifications:
|
|
136
|
+
*
|
|
137
|
+
* ```ts
|
|
138
|
+
* await using watch = await session.watch((n) => console.log(n));
|
|
139
|
+
* // ...
|
|
140
|
+
* // Closed when the scope ends, or earlier with `watch.close()`.
|
|
141
|
+
* ```
|
|
142
|
+
*
|
|
143
|
+
* The watch may outlive the session: once the session has stopped,
|
|
144
|
+
* closing it resolves `false` at once. Rejects if the session stops
|
|
145
|
+
* before the engine opened the watch.
|
|
146
|
+
*/
|
|
147
|
+
async watch(callback) {
|
|
148
|
+
// Closing turns delivery off at once, before the engine answers.
|
|
149
|
+
let open = true;
|
|
150
|
+
const id = await this.unlessStopped(() => this.command.createWatch((notification) => {
|
|
151
|
+
if (open)
|
|
152
|
+
callback(notification);
|
|
153
|
+
}), () => {
|
|
154
|
+
throw new Error('EngineSession.watch() called after stop(): the engine has shut ' +
|
|
155
|
+
'down and opens no watches. Create a new session to run again.');
|
|
156
|
+
});
|
|
157
|
+
return new Subscription(id, () => {
|
|
158
|
+
open = false;
|
|
159
|
+
return this.unwatch(id);
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
/**
|
|
163
|
+
* Closes the watch with id `watchId` — one `EngineCommand.createWatch`
|
|
164
|
+
* opened, or a {@link WatchSubscription.id} — resolving with whether
|
|
165
|
+
* it was open. Once the session has stopped, resolves `false`: the
|
|
166
|
+
* engine is gone, and its watches with it.
|
|
167
|
+
*/
|
|
168
|
+
unwatch(watchId) {
|
|
169
|
+
return this.unlessStopped(() => this.command.removeWatch(watchId), () => false);
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* Resets the engine — terminates all blocks and links, and detaches,
|
|
173
|
+
* stops and unregisters the engine-managed connectors. Resolves once
|
|
174
|
+
* the reset is done, so a command issued afterwards sees the engine
|
|
175
|
+
* empty.
|
|
176
|
+
*
|
|
177
|
+
* Rejects once the engine has stopped — through {@link stop}, or a
|
|
178
|
+
* `stopEngine` sent on a command handle — or if it stops before
|
|
179
|
+
* answering: there is nothing left to reset, and the request would
|
|
180
|
+
* otherwise wait on the ended message loop forever. (A reset issued
|
|
181
|
+
* concurrently with stop() is fine: both go through the control
|
|
182
|
+
* chain, reset first.)
|
|
183
|
+
*/
|
|
184
|
+
reset() {
|
|
185
|
+
const stopped = () => {
|
|
186
|
+
throw new Error('EngineSession.reset() called after stop(): the engine has shut ' +
|
|
187
|
+
'down and no longer services commands. Create a new session to ' +
|
|
188
|
+
'run again.');
|
|
189
|
+
};
|
|
190
|
+
if (this.stopDone)
|
|
191
|
+
return Promise.resolve().then(stopped);
|
|
192
|
+
return this.enqueueControl(() => this.unlessStopped(() => this.control.resetEngine(), stopped));
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* Shuts the engine down and resolves once `run()`'s future has
|
|
196
|
+
* completed. A no-op before {@link start}. The session is spent
|
|
197
|
+
* afterwards — commands are no longer serviced; create a new session
|
|
198
|
+
* to run again.
|
|
199
|
+
*
|
|
200
|
+
* If the engine has already stopped — through a `stopEngine` sent on
|
|
201
|
+
* a command handle — or stops while this waits, it resolves once
|
|
202
|
+
* `run()`'s future has completed, without waiting for an answer the
|
|
203
|
+
* stopped engine will never send.
|
|
204
|
+
*/
|
|
205
|
+
stop() {
|
|
206
|
+
const runDone = this.runDone;
|
|
207
|
+
if (!runDone)
|
|
208
|
+
return Promise.resolve();
|
|
209
|
+
// Idempotent: a second Shutdown would wait on the ended message
|
|
210
|
+
// loop forever, so every caller shares the first stop's promise.
|
|
211
|
+
this.stopDone ??= this.enqueueControl(async () => {
|
|
212
|
+
await this.unlessStopped(() => this.control.stopEngine(), () => undefined);
|
|
213
|
+
await runDone;
|
|
214
|
+
});
|
|
215
|
+
return this.stopDone;
|
|
216
|
+
}
|
|
217
|
+
/**
|
|
218
|
+
* {@link stop}s the session, so that `await using` stops it when the
|
|
219
|
+
* scope ends:
|
|
220
|
+
*
|
|
221
|
+
* ```ts
|
|
222
|
+
* await using session = startEngine();
|
|
223
|
+
* ```
|
|
224
|
+
*/
|
|
225
|
+
async [Symbol.asyncDispose]() {
|
|
226
|
+
await this.stop();
|
|
227
|
+
}
|
|
228
|
+
/**
|
|
229
|
+
* Sends a request with `send` and settles as it does — or with
|
|
230
|
+
* `stopped()` once the engine has stopped without answering it, or
|
|
231
|
+
* at once, without sending, if it already has. A stopped engine
|
|
232
|
+
* answers nothing, and its channel keeps a request it will never
|
|
233
|
+
* read, so the request would otherwise wait forever.
|
|
234
|
+
*/
|
|
235
|
+
unlessStopped(send, stopped) {
|
|
236
|
+
if (this.ended)
|
|
237
|
+
return Promise.resolve().then(stopped);
|
|
238
|
+
const request = send();
|
|
239
|
+
const runDone = this.runDone;
|
|
240
|
+
// Before start(), the request waits for the engine to start.
|
|
241
|
+
if (!runDone)
|
|
242
|
+
return request;
|
|
243
|
+
return Promise.race([request, runDone.then(stopped, stopped)]);
|
|
244
|
+
}
|
|
245
|
+
enqueueControl(op) {
|
|
246
|
+
const next = this.controlChain.catch(() => { }).then(op);
|
|
247
|
+
this.controlChain = next;
|
|
248
|
+
return next;
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
/**
|
|
252
|
+
* Creates an {@link EngineSession} without starting it: the engine and
|
|
253
|
+
* every command handle exist, `run()` has not been kicked off. For
|
|
254
|
+
* hosts that must separate handle creation (module load) from engine
|
|
255
|
+
* start (mount) — call {@link EngineSession.start} when ready. Most
|
|
256
|
+
* embedders want {@link startEngine} instead.
|
|
257
|
+
*/
|
|
258
|
+
export function createEngineSession(options = {}) {
|
|
259
|
+
return new EngineSession(options);
|
|
260
|
+
}
|
|
261
|
+
/**
|
|
262
|
+
* Creates the engine (or adopts a not-yet-run one), pre-creates the
|
|
263
|
+
* command handles, kicks off `run()` un-awaited, and returns the
|
|
264
|
+
* ready-to-use {@link EngineSession} — the whole ordering-sensitive
|
|
265
|
+
* start sequence in one call. See the {@link EngineSession} docs for
|
|
266
|
+
* why the order matters.
|
|
267
|
+
*
|
|
268
|
+
* ```ts
|
|
269
|
+
* const { command } = startEngine();
|
|
270
|
+
* const id = await command.addBlock('SineWave');
|
|
271
|
+
* ```
|
|
272
|
+
*/
|
|
273
|
+
export function startEngine(options = {}) {
|
|
274
|
+
const session = new EngineSession(options);
|
|
275
|
+
session.start();
|
|
276
|
+
return session;
|
|
277
|
+
}
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import type { EngineCommand } from './logic_mesh.js';
|
|
2
|
+
/**
|
|
3
|
+
* A function exposed as a block through {@link defineJsBlocks}.
|
|
4
|
+
*
|
|
5
|
+
* Receives the block's `in` value and returns the block's `out` value,
|
|
6
|
+
* either directly or via a Promise. A thrown exception or a rejected
|
|
7
|
+
* Promise faults the block (with the error message as the fault
|
|
8
|
+
* reason); a hung Promise is bounded by the block's own `timeout` pin,
|
|
9
|
+
* which faults the block with a timeout error — there is no separate
|
|
10
|
+
* timeout to configure here.
|
|
11
|
+
*
|
|
12
|
+
* Values cross the wasm boundary in the Haystack JSON encoding:
|
|
13
|
+
* numbers, strings, booleans, `null`, arrays and plain objects
|
|
14
|
+
* round-trip, with measured exceptions. An `undefined` inside a dict
|
|
15
|
+
* or array keeps its key or slot but arrives as `null`. A `BigInt`
|
|
16
|
+
* becomes a `Number`, as a Haystack Number is a float: outside the safe
|
|
17
|
+
* integer range it rounds to the nearest one, as `Number(value)` does.
|
|
18
|
+
* Non-finite numbers arrive Hayson-encoded, as
|
|
19
|
+
* `{ _kind: 'number', val: 'INF' }` (`'-INF'`, `'NaN'`). Engine-side dicts arrive as plain
|
|
20
|
+
* objects, so a multi-input block is simply a function taking an
|
|
21
|
+
* object: feed the `in` pin a dict value and read named fields off the
|
|
22
|
+
* argument. A returned `undefined` is coerced to `null` rather than
|
|
23
|
+
* faulting the block.
|
|
24
|
+
*/
|
|
25
|
+
export type JsBlockFn = (value: unknown) => unknown | Promise<unknown>;
|
|
26
|
+
/** Options for {@link defineJsBlocks}. */
|
|
27
|
+
export interface JsBlocksOptions {
|
|
28
|
+
/**
|
|
29
|
+
* The name the connector is registered and attached under, and the
|
|
30
|
+
* value of every materialized block's `connector` pin. Must be
|
|
31
|
+
* unique per registry (i.e. per process). Defaults to `'js'`.
|
|
32
|
+
*/
|
|
33
|
+
name?: string;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Block-like ergonomics for JS-implemented logic, without a new engine
|
|
37
|
+
* API: the functions are exposed through one {@link JsConnector} —
|
|
38
|
+
* request/response only — and materialize in the graph as `Request`
|
|
39
|
+
* blocks whose `address` pin selects the function. The engine sees
|
|
40
|
+
* nothing but a connector.
|
|
41
|
+
*
|
|
42
|
+
* Created by {@link defineJsBlocks}. The lifecycle is the connector
|
|
43
|
+
* lifecycle: {@link attach} registers the connector and hands it to
|
|
44
|
+
* the running engine (which starts it and manages it from then on),
|
|
45
|
+
* {@link detach} reverses that, and an engine reset detaches every
|
|
46
|
+
* managed connector — re-{@link attach} afterwards, exactly as with a
|
|
47
|
+
* hand-written connector.
|
|
48
|
+
*
|
|
49
|
+
* Deliberately request-shaped: value *streams* (an `ExternalIn`
|
|
50
|
+
* source) don't fit the one-value-in/one-value-out function signature,
|
|
51
|
+
* so the façade does not bend it — implement a raw {@link JsConnector}
|
|
52
|
+
* with a `subscribe` method for those, and bind an `ExternalIn` block
|
|
53
|
+
* to it by name and address. Fire-and-forget *sinks* do fit: the
|
|
54
|
+
* connector's `publish` dispatches to the same function map (return
|
|
55
|
+
* value discarded), so an `ExternalOut` block bound to this connector
|
|
56
|
+
* name and a function name works without extra API.
|
|
57
|
+
*/
|
|
58
|
+
export declare class JsBlocks<T extends Record<string, JsBlockFn>> {
|
|
59
|
+
/** The connector name — see {@link JsBlocksOptions.name}. */
|
|
60
|
+
readonly name: string;
|
|
61
|
+
private readonly functions;
|
|
62
|
+
private readonly connector;
|
|
63
|
+
/**
|
|
64
|
+
* Serializes {@link attach} and {@link detach} per instance — the
|
|
65
|
+
* same pattern as `EngineSession`'s control chain. Both operations
|
|
66
|
+
* are check-then-act against the live registry; two overlapping
|
|
67
|
+
* calls would race the check and the loser would surface the
|
|
68
|
+
* engine's "already managed" error for what is really an idempotent
|
|
69
|
+
* success.
|
|
70
|
+
*/
|
|
71
|
+
private lifecycleChain;
|
|
72
|
+
/**
|
|
73
|
+
* Whether this instance owns the current registry entry for
|
|
74
|
+
* {@link name}, decided against the LIVE registry: the entry must be
|
|
75
|
+
* this instance's own connector object (`connectorIs` compares JS
|
|
76
|
+
* object identity). A plain "I registered this" boolean cannot carry
|
|
77
|
+
* this — an engine reset unregisters connectors behind the façade's
|
|
78
|
+
* back, after which the same name may be re-registered by someone
|
|
79
|
+
* else, and the stale flag would bless a hijack.
|
|
80
|
+
*/
|
|
81
|
+
private ownsRegistration;
|
|
82
|
+
private enqueue;
|
|
83
|
+
constructor(functions: T, options?: JsBlocksOptions);
|
|
84
|
+
/**
|
|
85
|
+
* Registers the connector and attaches it to the running engine
|
|
86
|
+
* (`addConnector`), which starts it and manages its lifecycle from
|
|
87
|
+
* then on. Idempotent: the initial `listConnectors` reply is a FIFO
|
|
88
|
+
* barrier — it proves the engine has processed everything queued
|
|
89
|
+
* before it, a pending reset included — and an already-attached
|
|
90
|
+
* connector is left alone.
|
|
91
|
+
*
|
|
92
|
+
* `command` must be a handle created before `engine.run()` (any
|
|
93
|
+
* {@link EngineSession} handle qualifies), and — like every engine
|
|
94
|
+
* request — this only resolves while the engine runs (paused or not).
|
|
95
|
+
*
|
|
96
|
+
* Overlapping attach/detach calls on one instance are serialized
|
|
97
|
+
* internally, so two same-tick attaches both succeed (the second
|
|
98
|
+
* observes the first's work and no-ops).
|
|
99
|
+
*
|
|
100
|
+
* Throws if the name is taken by a connector this instance does not
|
|
101
|
+
* own — registered by someone else, attached or not.
|
|
102
|
+
*/
|
|
103
|
+
attach(command: EngineCommand): Promise<void>;
|
|
104
|
+
private attachNow;
|
|
105
|
+
/**
|
|
106
|
+
* Detaches the connector from the engine (`removeConnector` — the
|
|
107
|
+
* engine stops it and unregisters it), or, when it was registered
|
|
108
|
+
* but never attached, just unregisters it. Acts only on a
|
|
109
|
+
* registration this instance owns — decided against the live
|
|
110
|
+
* registry, so a foreign same-name connector is left alone even when
|
|
111
|
+
* it took the name after an engine reset detached ours — and is a
|
|
112
|
+
* no-op when there is nothing left to tear down, so calling it after
|
|
113
|
+
* a reset (which already detached everything) is safe. Serialized
|
|
114
|
+
* with {@link attach} per instance.
|
|
115
|
+
*/
|
|
116
|
+
detach(command: EngineCommand): Promise<void>;
|
|
117
|
+
private detachNow;
|
|
118
|
+
/**
|
|
119
|
+
* Materializes function `fn` as a block: adds a `Request` block
|
|
120
|
+
* (under `blockUuid` when given) and wires its `connector` and
|
|
121
|
+
* `address` pins to this connector and the function name. Returns
|
|
122
|
+
* the block's UUID.
|
|
123
|
+
*
|
|
124
|
+
* Write the argument to the block's `in` pin — or link another
|
|
125
|
+
* block's output to it — and the function's result appears on `out`.
|
|
126
|
+
* The block's `timeout` pin (milliseconds) bounds a hung function.
|
|
127
|
+
*/
|
|
128
|
+
addBlock(command: EngineCommand, fn: Extract<keyof T, string>, blockUuid?: string): Promise<string>;
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Defines a set of JS functions to be exposed as blocks — see
|
|
132
|
+
* {@link JsBlocks} for the mechanics and limits.
|
|
133
|
+
*
|
|
134
|
+
* ```ts
|
|
135
|
+
* const jsBlocks = defineJsBlocks(
|
|
136
|
+
* {
|
|
137
|
+
* scale: (value) => (value as number) * 2,
|
|
138
|
+
* fetchTemp: async (zone) => readSensor(zone as string), // async is fine
|
|
139
|
+
* },
|
|
140
|
+
* { name: 'js' },
|
|
141
|
+
* );
|
|
142
|
+
*
|
|
143
|
+
* const { command } = startEngine();
|
|
144
|
+
* await jsBlocks.attach(command);
|
|
145
|
+
*
|
|
146
|
+
* const id = await jsBlocks.addBlock(command, 'scale');
|
|
147
|
+
* await command.writeBlockInput(id, 'in', 21); // out becomes 42
|
|
148
|
+
* ```
|
|
149
|
+
*/
|
|
150
|
+
export declare function defineJsBlocks<T extends Record<string, JsBlockFn>>(functions: T, options?: JsBlocksOptions): JsBlocks<T>;
|