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 ADDED
@@ -0,0 +1,11 @@
1
+ Copyright 2022-2024 Radu Racariu
2
+
3
+ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
4
+
5
+ 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
6
+
7
+ 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
8
+
9
+ 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
10
+
11
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package/README.md CHANGED
@@ -1,107 +1,450 @@
1
1
  # Logic Mesh
2
+
2
3
  A logic engine that is fully async, dynamic, and reactive written in Rust.
3
- The engine is compiled to WebAssembly and can be used in the browser, or in a Node.js environment.
4
+ The engine is compiled to WebAssembly and runs in the browser (through a
5
+ bundler) and in Node.js — see [Environment support](#environment-support).
4
6
 
5
7
  ## Applications
8
+
6
9
  - Low code editors
7
10
  - Interactive visualizations
8
11
 
9
12
  ## Features
13
+
10
14
  - Fully async and reactive
11
15
  - Extensible with custom blocks, either in Rust or JavaScript when running in a WASM environment
16
+ - Protocol-agnostic connectors for external data — implement subscribe/publish/request in JavaScript and bind them to blocks with the generic `ExternalIn`, `ExternalOut`, and `Request` blocks
17
+ - Plain JavaScript functions callable as blocks via `defineJsBlocks`
18
+
19
+ ## Installation
20
+
21
+ ```sh
22
+ npm install logic-mesh zod
23
+ ```
24
+
25
+ Upgrading from 1.x? The
26
+ [migration guide](https://github.com/rracariu/logic-mesh/blob/main/docs/migration-2.0.md#9-the-javascript-api)
27
+ lists what changed in the JavaScript API.
28
+
29
+ [Zod](https://zod.dev) 4.6 or newer is a peer dependency: `defineBlock`
30
+ describes pins with your Zod schemas, so the package must use the same `zod`
31
+ your code imports. Upgrade an app on an older Zod first: npm refuses to
32
+ install the package next to it (`ERESOLVE ... peer zod@"^4.6.0"`), even in
33
+ apps that never call `defineBlock`.
34
+
35
+ ## Environment support
36
+
37
+ The package is ESM only. It ships the wasm-pack `bundler` build, whose glue
38
+ module imports the `.wasm` file directly (the WebAssembly ESM integration)
39
+ and instantiates it on first import.
40
+
41
+ ### Node.js
42
+
43
+ Node.js `^22.19.0` or `>=24.5.0` loads the package with a plain `import`,
44
+ without flags or loaders:
45
+
46
+ ```js
47
+ import { startEngine } from 'logic-mesh';
48
+
49
+ const { command } = startEngine();
50
+ console.log(await command.evalBlock('Add', [1, 2])); // [ 3 ]
51
+ ```
52
+
53
+ - Node prints an `ExperimentalWarning` ("Importing WebAssembly module
54
+ instances is an experimental feature"). Run
55
+ `node --disable-warning=ExperimentalWarning` to silence it.
56
+ - From CommonJS use `await import('logic-mesh')`. `require('logic-mesh')`
57
+ fails before Node.js 26 (`WASM is currently unsupported by require(esm)`).
58
+ - Older releases (Node.js 20, 22.12–22.18, 24.0–24.4) load the package only
59
+ with `node --experimental-wasm-modules`, and are outside the supported
60
+ `engines` range.
61
+
62
+ ### Bundlers
63
+
64
+ - **Vite** needs [vite-plugin-wasm](https://github.com/Menci/vite-plugin-wasm).
65
+ Without it, Vite 7 and earlier fail to build the package, and Vite 8's dev
66
+ server serves it broken (only Vite 8's production build copes). The plugin
67
+ instantiates the module with a top-level `await`, which the default build
68
+ target of Vite 6 and earlier rejects, so set `build.target` too. The
69
+ [demo app](https://github.com/rracariu/logic-mesh/blob/main/web/app/vite.config.ts)
70
+ uses this configuration:
71
+
72
+ ```ts
73
+ // vite.config.ts
74
+ import { defineConfig } from 'vite';
75
+ import wasm from 'vite-plugin-wasm';
76
+
77
+ export default defineConfig({
78
+ plugins: [wasm()],
79
+ build: {
80
+ // Needed on Vite 6 and earlier; harmless on Vite 7 and 8.
81
+ target: 'esnext',
82
+ },
83
+ });
84
+ ```
85
+
86
+ - **webpack 5** needs `experiments: { asyncWebAssembly: true }`.
87
+
88
+ ### TypeScript
89
+
90
+ Type declarations ship with the package. The declarations use
91
+ `Symbol.dispose` and `Symbol.asyncDispose`, so compile with
92
+ `skipLibCheck: true` or add `ESNext.Disposable` (or `ESNext`) to `lib`.
12
93
 
13
94
  ## UI Editor
95
+
14
96
  There is a sample low code editor that is built on top of Logic Mesh, which can be found [here](https://rracariu.github.io/logic-mesh/). It serves as an example of how Logic Mesh can be used, and as a simple way to experiment with the Logic Mesh engine.
15
97
 
16
98
  ## Examples
17
99
 
18
- ### List all registered blocks
100
+ ### Start the engine and wire blocks together
101
+
102
+ `startEngine()` creates the engine, prepares the command handles, and
103
+ starts the engine's message loop — in the one order that works.
104
+
19
105
  ```ts
20
- import { initEngine } from 'logic-mesh';
106
+ import { startEngine } from 'logic-mesh';
21
107
 
22
- // Initialize the engine
23
- const engine = initEngine();
108
+ // Engine created and running; `command` is ready to use. The scan
109
+ // interval — how often the blocks that poll check their state — is in
110
+ // milliseconds, 200 by default.
111
+ const session = startEngine({ scanInterval: 100 });
112
+ const { command } = session;
24
113
 
25
- // List all registered blocks
26
- const blocks = engine.listBlocks();
114
+ // Add a SineWave block
115
+ const sineWaveId = await command.addBlock('SineWave');
116
+ // Add a StrLen block
117
+ const strLenId = await command.addBlock('StrLen');
118
+
119
+ // Connect the blocks, sineWave -> strLen (sineWave's out port to strLen's in port).
120
+ // A handle takes overlapping calls too: each promise settles with the
121
+ // engine's answer to its own call.
122
+ await command.createLink(sineWaveId, strLenId, 'out', 'in');
123
+
124
+ // Read a block's state and pin values, as plain objects
125
+ const block = await command.inspectBlock(strLenId);
126
+ console.log(block.state, block.outputs.out.val);
127
+
128
+ // Stop the engine; the promise resolves once it has stopped
129
+ await session.stop();
27
130
  ```
28
131
 
29
- ### Add block and wire them together
132
+ Values reach JavaScript in one JSON-compatible encoding, from every command,
133
+ watch notification and JS block call: a Haystack Dict is a plain object, and
134
+ Null or a missing value is `null`.
135
+
136
+ Under the hood the sequence matters, and getting it wrong fails in
137
+ confusing ways — which is why the wrapper owns it:
138
+
30
139
  ```ts
31
140
  import { initEngine } from 'logic-mesh';
32
141
 
33
- // Initialize the engine
34
142
  const engine = initEngine();
35
143
 
36
- // Get a command instance for the engine
144
+ // Command handles must be created before `run()`: `engineCommand()`
145
+ // borrows the engine mutably, and `run()`'s future holds that borrow
146
+ // from its first poll onward ("recursive use of an object detected").
37
147
  const command = engine.engineCommand();
38
148
 
39
- // Add a SineWave block
40
- const sineWaveId = await command.addBlock('SineWave')
41
- // Add a StrLen block
42
- const strLenId = await command.addBlock('StrLen')
149
+ // Start the engine without awaiting it: commands are only serviced by
150
+ // the running engine's message loop, and `run()`'s promise resolves
151
+ // only on shutdown — awaiting it first deadlocks.
152
+ engine.run();
153
+ ```
154
+
155
+ `startEngine` returns an `EngineSession`, which also carries a second
156
+ handle for connector attachment (`connectorCommand`), `watch()` /
157
+ `unwatch()`, and `reset()`/`stop()` that are safe to call at any point
158
+ after start and resolve once the engine has reset or stopped. Hosts that need to create the
159
+ handles early but start the engine later (say, at component mount) can
160
+ use `createEngineSession()` and call `session.start()` when ready.
161
+
162
+ ### Watch for block changes
163
+
164
+ ```ts
165
+ import { startEngine } from 'logic-mesh';
43
166
 
44
- // Connect the blocks, sineWave -> strLen (sineWave's out port to strLen's in port)
45
- command.createLink(sineWaveId, strLenId, 'out', 'in')
167
+ const session = startEngine();
46
168
 
47
- // Start the engine (this is async)
48
- engine.run()
169
+ // Register a callback that will be called when a block changes. The
170
+ // promise resolves with the watch once the engine opened it.
171
+ const watch = await session.watch((notification) => {
172
+ console.log('Block changed', JSON.stringify(notification));
173
+ });
174
+
175
+ const sineWave = await session.command.addBlock('SineWave');
176
+
177
+ // Stop the notifications. `await using watch = ...` closes it at the
178
+ // end of the scope instead.
179
+ await watch.close();
49
180
  ```
50
181
 
51
- ### Watch for block changes
182
+ ### Handle errors
183
+
184
+ A command that fails rejects with a `LogicMeshError`: an `Error` whose
185
+ `code` names the failure — `'BlockInstanceNotFound'`,
186
+ `'UnsupportedProgramVersion'`, … (the `LogicMeshErrorCode` union) — and
187
+ whose `message` describes it. The codes are stable; the messages are
188
+ for people. The synchronous calls — `initEngine`, `registerBlock`,
189
+ `registerConnector`, `setLogLevel` — throw `LogicMeshError`s too.
190
+
52
191
  ```ts
53
- import { initEngine } from 'logic-mesh';
192
+ import { isLogicMeshError, startEngine } from 'logic-mesh';
54
193
 
55
- // Initialize the engine
56
- const engine = initEngine();
194
+ const { command } = startEngine();
57
195
 
58
- // Get a command instance for the engine
59
- const command = engine.engineCommand();
196
+ try {
197
+ await command.loadProgram(saved);
198
+ } catch (err) {
199
+ if (isLogicMeshError(err) && err.code === 'UnsupportedProgramVersion') {
200
+ console.warn('Saved by a newer version:', err.message);
201
+ } else {
202
+ throw err;
203
+ }
204
+ }
205
+ ```
60
206
 
61
- // Add a SineWave block
62
- const sineWave = await command.addBlock('SineWave')
207
+ ### Logging
208
+
209
+ The engine logs warnings and errors to the console. `setLogLevel` makes
210
+ it more verbose, or silences it:
211
+
212
+ ```ts
213
+ import { setLogLevel } from 'logic-mesh';
214
+
215
+ setLogLevel('debug'); // 'off' | 'error' | 'warn' | 'info' | 'debug' | 'trace'
216
+ ```
63
217
 
64
- // Create a new command instance for the watcher
65
- const watchCommand = engine.engineCommand()
66
- // Register a callback that will be called when the block changes
67
- watchCommand.createWatch((notification) => {
68
- console.log('Block changed', JSON.stringify(notification))
69
- })
218
+ ### Expose JavaScript functions as blocks
70
219
 
71
- engine.run()
220
+ `defineJsBlocks` turns plain JS functions — sync or async — into
221
+ engine blocks. Each function becomes addressable through a `Request`
222
+ block: the block's `in` pin carries the argument, `out` carries the
223
+ returned (and awaited) result, and a rejection surfaces as the block's
224
+ fault. The `Request` block's `timeout` pin bounds functions that never
225
+ settle.
226
+
227
+ ```ts
228
+ import { defineJsBlocks, startEngine } from 'logic-mesh';
229
+
230
+ const session = startEngine();
231
+
232
+ const jsBlocks = defineJsBlocks({
233
+ scale: (value) => (value as number) * 2,
234
+ fetchTemp: async (zone) => {
235
+ const response = await fetch(`/api/temp/${zone as string}`);
236
+ return response.json();
237
+ },
238
+ });
239
+
240
+ // Register the backing connector and attach it to the running engine
241
+ await jsBlocks.attach(session.command);
242
+
243
+ // Add a block that calls `scale` — a `Request` block wired to it
244
+ const id = await jsBlocks.addBlock(session.command, 'scale');
245
+ await session.command.writeBlockInput(id, 'in', 21); // out becomes 42
72
246
  ```
73
247
 
248
+ Functions taking several inputs receive them as one object: write a
249
+ dict value to the `in` pin and the function is handed a plain JS
250
+ object (nested dicts included). `jsBlocks.detach(command)` removes the
251
+ connector again; after an engine `reset()` (which detaches all managed
252
+ connectors) calling `attach` once more restores it.
253
+
74
254
  ### Add a custom JavaScript block
255
+
256
+ For blocks with typed, named pins that show up in the block library
257
+ like the built-ins do, register a full block description instead:
258
+
75
259
  ```ts
76
- import { initEngine, JsBlock } from 'logic-mesh';
260
+ import { createEngineSession, type BlockDesc, type JsBlock } from 'logic-mesh';
77
261
 
78
- // Initialize the engine
79
- const engine = initEngine();
262
+ // Blocks must be registered before the engine starts, so create the
263
+ // session first and start it after registration
264
+ const session = createEngineSession();
80
265
 
81
266
  /**
82
267
  * Defines a block that is implemented in JS
83
268
  */
84
269
  const JsAddBlock = {
85
- // The block description
86
- desc: {
87
- name: 'AddBlock',
88
- dis: 'JS Add block',
89
- lib: 'examples',
90
- ver: '0.0.1',
91
- category: 'Docs',
92
- doc: 'Adds two numbers',
93
- implementation: 'external',
94
- inputs: [{ name: 'in1', kind: 'Number' }, { name: 'in2', kind: 'Number' }],
95
- outputs: [{ name: 'out', kind: 'Number' }],
96
- } satisfies BlockDesc,
97
- // The block implementation
98
- function: async (inputs: unknown[]) => {
99
- return (inputs[0] as number) + (inputs[1] as number)
100
- },
101
- } satisfies JsBlock
102
-
103
- engine.registerBlock(JsAddBlock.desc, JsAddBlock.function)
104
-
105
- engine.run()
270
+ // The block description
271
+ desc: {
272
+ name: 'AddBlock',
273
+ dis: 'JS Add block',
274
+ lib: 'examples',
275
+ ver: '0.0.1',
276
+ category: 'Docs',
277
+ doc: 'Adds two numbers',
278
+ implementation: 'external',
279
+ inputs: [
280
+ { name: 'in1', kind: 'number' },
281
+ { name: 'in2', kind: 'number' },
282
+ ],
283
+ outputs: [{ name: 'out', kind: 'number' }],
284
+ } satisfies BlockDesc,
285
+ // The block factory: called once per block instance, it returns the
286
+ // execute function. Inputs and outputs are arrays in pin order.
287
+ executor: () => async (inputs: unknown[]) => {
288
+ return [Number(inputs[0]) + Number(inputs[1])];
289
+ },
290
+ } satisfies JsBlock;
291
+
292
+ session.engine.registerBlock(JsAddBlock.desc, JsAddBlock.executor);
293
+
294
+ session.start();
295
+ ```
296
+
297
+ The executor may be re-invoked with the same inputs if the engine
298
+ interrupts a call mid-flight (at-least-once), so side-effecting
299
+ executors should be idempotent.
300
+
301
+ A registered block runs when its inputs change: a value delivered over a
302
+ link, or one written with `writeBlockInput`, whether or not the pin is
303
+ linked.
304
+
305
+ ### Which extension point to use
306
+
307
+ The three JS extension points overlap on purpose — each trades ergonomics
308
+ for capability at a different spot. Pick by the shape of what you are adding:
309
+
310
+ | You are adding… | Use | Because |
311
+ | --------------------------------------------------------------------------------------------------- | -------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
312
+ | A function the graph calls with one value (a transform, a lookup, a service call) | `defineJsBlocks` | One `in` → one `out` through a `Request` block: attach/detach on a **running** engine, a `timeout` pin, and a cancelled call is retried automatically (at-least-once — make handlers idempotent). Several inputs travel as one object on the single `in` pin. |
313
+ | A real block: several **independently wired** input pins, typed pins, an entry in the block library | `registerBlock` / `defineBlock` (TypedBlock) | Only registered blocks get named pins that separate upstream blocks can each link to, per-pin kinds (defaults come from `defineBlock`'s schema layer — raw `registerBlock` pins carry name and kind only), and a catalog entry. Register **before** `session.start()` — block registration is not available on a running engine. |
314
+ | A stream of values pushed _into_ the graph, a sink, or a whole protocol (MQTT, WebSocket, …) | a custom connector | `subscribe`/`publish`/`request` with engine-managed lifecycle; `ExternalIn`/`ExternalOut`/`Request` blocks bind to it by name and address, so the binding is data and serializes with the program. `defineJsBlocks` is itself a connector specialized to the request case. |
315
+
316
+ Rule of thumb: start with `defineJsBlocks`; move to `registerBlock` the moment
317
+ you need a second independently-linked input pin or a library entry; drop to a
318
+ custom connector when values flow on their own schedule rather than
319
+ per-request.
320
+
321
+ ### Add a custom JavaScript connector
322
+
323
+ Connectors bridge the engine to external systems (MQTT, WebSockets, HTTP, …).
324
+ A connector implements `subscribe`, `publish`, and `request` (plus optional
325
+ `start`/`stop`); the generic `ExternalIn`/`ExternalOut`/`Request` blocks bind
326
+ to it by connector name and address.
327
+
328
+ ```ts
329
+ import { registerConnector, startEngine, type JsConnector } from 'logic-mesh';
330
+
331
+ const connector = {
332
+ subscribe(address, callback) {
333
+ // Push values with callback(value); report an error with
334
+ // callback(undefined, detail); end the stream with callback().
335
+ const timer = setInterval(() => callback(Math.random() * 100), 1000);
336
+ // Return an unsubscribe function (or a Promise of one)
337
+ return () => clearInterval(timer);
338
+ },
339
+ publish(address, value) {
340
+ console.log(`publish ${value} to ${address}`);
341
+ },
342
+ request(address, value) {
343
+ return Promise.resolve({ echo: value });
344
+ },
345
+ } satisfies JsConnector;
346
+
347
+ // Put the connector in the process-wide registry
348
+ registerConnector('demo', connector);
349
+
350
+ const { command } = startEngine();
351
+
352
+ // ExternalIn streams subscribed values into the graph via its `out` pin
353
+ const inputId = await command.addBlock('ExternalIn');
354
+ await command.writeBlockInput(inputId, 'connector', 'demo');
355
+ await command.writeBlockInput(inputId, 'address', 'sensor/1');
356
+
357
+ // ExternalOut publishes whatever is wired to its `in` pin
358
+ const outputId = await command.addBlock('ExternalOut');
359
+ await command.writeBlockInput(outputId, 'connector', 'demo');
360
+ await command.writeBlockInput(outputId, 'address', 'actuator/1');
361
+
362
+ // Attach the connector to the running engine; the engine manages its
363
+ // lifecycle from here (it is stopped and detached on engine reset)
364
+ await command.addConnector('demo');
365
+ ```
366
+
367
+ ### Save and load programs
368
+
369
+ `getProgram()` resolves with the engine's program in the save format, as
370
+ plain JSON: store it with `JSON.stringify` and hand it back to
371
+ `loadProgram()`. A load is all or nothing, and a program saved by a newer
372
+ release rejects with code `'UnsupportedProgramVersion'`. Programs saved by
373
+ logic-mesh 1.x load as they are.
374
+
375
+ ```ts
376
+ import { startEngine, type Program } from 'logic-mesh';
377
+
378
+ const { command } = startEngine();
379
+
380
+ const program = await command.getProgram();
381
+ localStorage.setItem('program', JSON.stringify(program));
382
+
383
+ // Later, on an engine with no blocks of its own
384
+ await command.resetEngine();
385
+ await command.loadProgram(
386
+ JSON.parse(localStorage.getItem('program')!) as Program,
387
+ );
388
+ ```
389
+
390
+ A block can carry the editor's own state in `editor`, any JSON object
391
+ the engine saves back unchanged. Type it through `Program`'s parameter,
392
+ and declare the type with `type`, not `interface`:
393
+
394
+ ```ts
395
+ import type { Program } from 'logic-mesh';
396
+
397
+ type MyEditor = { widget?: string; collapsed?: boolean };
398
+
399
+ const saved = (await command.getProgram()) as Program<MyEditor>;
400
+ for (const block of Object.values(saved.blocks)) {
401
+ console.log(block.name, block.editor?.widget);
402
+ }
403
+ ```
404
+
405
+ On a running engine, `command.setBlockMetadata(id, label, position)` and
406
+ `command.setBlockEditor(id, editor)` change what a block is saved with.
407
+
408
+ `ProgramSchema` is a Zod schema of the save format. It checks a program
409
+ without the engine, before you store an upload, say, and reports each
410
+ problem at its path. It reads a program as `loadProgram` does: a 1.x save
411
+ parses, and a newer format fails on its `version`. `programSchema(editor)`
412
+ also checks the editor metadata with your own schema, and types the result
413
+ with it:
414
+
415
+ ```ts
416
+ import { ProgramSchema, programSchema, startEngine } from 'logic-mesh';
417
+ import { z } from 'zod';
418
+
419
+ const { command } = startEngine();
420
+
421
+ const result = ProgramSchema.safeParse(
422
+ JSON.parse(localStorage.getItem('program')!),
423
+ );
424
+ if (!result.success) throw new Error(z.prettifyError(result.error));
425
+ await command.loadProgram(result.data);
426
+
427
+ // A loose object keeps editor keys the schema does not name.
428
+ const MyProgram = programSchema(
429
+ z.looseObject({ widget: z.string().optional() }),
430
+ );
431
+ const saved = MyProgram.parse(await command.getProgram());
432
+ console.log(Object.values(saved.blocks)[0]?.editor?.widget);
106
433
  ```
107
434
 
435
+ A program that passes can still fail to load: only the engine knows
436
+ whether its block types are registered and its pins and links exist.
437
+ `z.toJSONSchema(ProgramSchema, { io: 'input' })` gives the format as a
438
+ JSON Schema, for tools outside JavaScript.
439
+
440
+ ### List all registered blocks
441
+
442
+ ```ts
443
+ import { initEngine } from 'logic-mesh';
444
+
445
+ // Initialize the engine
446
+ const engine = initEngine();
447
+
448
+ // List all registered blocks
449
+ const blocks = engine.listBlocks();
450
+ ```