logic-mesh 1.0.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.
@@ -1,6 +1,18 @@
1
- import { ZodArray, ZodBoolean, ZodDefault, ZodEnum, ZodNumber, ZodObject, ZodOptional, ZodString, ZodUnknown, } from 'zod';
1
+ import { ZodArray, ZodBoolean, ZodDefault, ZodEnum, ZodLiteral, ZodNull, ZodNullable, ZodNumber, ZodObject, ZodOptional, ZodString, ZodUnion, ZodUnknown, } from 'zod';
2
2
  /**
3
3
  * Defines a new block type with the specified configuration.
4
+ *
5
+ * Execution semantics: the engine passes `null` for an input pin
6
+ * whose value has not been set yet — e.g. on the first cycles after a
7
+ * link is created, before any value has flowed — or is `Null`, and the
8
+ * block reads it as `undefined`. While any input whose schema rejects
9
+ * `undefined` (a plain `z.number()`, say) is still unset, execution is
10
+ * skipped — a no-op, not a fault — and `execute` is not called. Wrap a
11
+ * pin's schema in `.optional()` or `.default(...)` to let the executor
12
+ * run without that pin (a default materializes as the argument value).
13
+ * A pin with a present but mistyped value still faults the block: only
14
+ * absence is tolerated.
15
+ *
4
16
  * @param config - The block configuration, including description, input/output types, and execution logic.
5
17
  * @returns A class that extends TypedBlock, which can be registered with the BlocksEngine.
6
18
  */
@@ -24,7 +36,9 @@ export function defineBlock(config) {
24
36
  const Ctor = this;
25
37
  const executor = new Ctor();
26
38
  if (executeFn) {
27
- engine.registerBlock(executor.desc, () => executor.executeImpl.bind(executor));
39
+ // The engine hands the inputs over as they are; `executeImpl`
40
+ // validates them against the input schemas.
41
+ engine.registerBlock(executor.desc, () => (inputs) => executor.executeImpl(inputs));
28
42
  }
29
43
  else {
30
44
  engine.registerBlock(executor.desc);
@@ -43,17 +57,19 @@ export class TypedBlock {
43
57
  this.inputTypes = inputs.map(([, type]) => type);
44
58
  this.outputs = outputs.map(([name, _]) => name);
45
59
  this.outputTypes = outputs.map(([, type]) => type);
46
- const blockDescription = desc;
47
- blockDescription.implementation = 'external';
48
- blockDescription.inputs = this.inputs.map((name, i) => ({
49
- name,
50
- kind: this.zodToKind(this.inputTypes.at(i)),
51
- }));
52
- blockDescription.outputs = this.outputs.map((name, i) => ({
53
- name,
54
- kind: this.zodToKind(this.outputTypes.at(i)),
55
- }));
56
- this.desc = blockDescription;
60
+ // A copy: the caller's `desc` may describe more than one block.
61
+ this.desc = {
62
+ ...desc,
63
+ implementation: 'external',
64
+ inputs: this.inputs.map((name, i) => ({
65
+ name,
66
+ kind: this.zodToKind(this.inputTypes.at(i)),
67
+ })),
68
+ outputs: this.outputs.map((name, i) => ({
69
+ name,
70
+ kind: this.zodToKind(this.outputTypes.at(i)),
71
+ })),
72
+ };
57
73
  }
58
74
  execute([..._inputs]) {
59
75
  throw new Error('Not implemented');
@@ -66,11 +82,32 @@ export class TypedBlock {
66
82
  if (inputs.length !== this.inputs.length) {
67
83
  throw new Error('Invalid number of inputs');
68
84
  }
69
- this.inputs.map((_, i) => {
85
+ // The engine passes `null` for a pin whose value is not yet set —
86
+ // e.g. on the first cycles after a link is created, before a value
87
+ // flows — or is Null, and a direct caller may pass `undefined`.
88
+ // That must not fault the block permanently: an unset pin, either
89
+ // way, is probed with `safeParse`, and when its schema rejects
90
+ // `undefined` (a required pin like plain `z.number()`) the whole
91
+ // execution is skipped by returning a non-array — on the Rust side
92
+ // that is a silent no-op: outputs untouched, no fault. A schema
93
+ // that accepts `undefined` (`.optional()`, `.default(...)`,
94
+ // `z.unknown()`) contributes its parsed value instead — a default
95
+ // materializes here. A pin with a DEFINED value keeps the strict
96
+ // `parse`: a present-but-mistyped value is a real error and still
97
+ // faults, deliberately.
98
+ for (let i = 0; i < this.inputs.length; i++) {
70
99
  const val = inputs.at(i);
71
100
  const kind = this.inputTypes[i];
72
- inputs[i] = kind.parse(val);
73
- });
101
+ if (val === undefined || val === null) {
102
+ const probe = kind.safeParse(undefined);
103
+ if (!probe.success)
104
+ return undefined; // not ready yet — skip
105
+ inputs[i] = probe.data;
106
+ }
107
+ else {
108
+ inputs[i] = kind.parse(val);
109
+ }
110
+ }
74
111
  const res = await this.execute(inputs);
75
112
  if (res === undefined) {
76
113
  return undefined;
@@ -86,12 +123,30 @@ export class TypedBlock {
86
123
  });
87
124
  return res;
88
125
  }
126
+ /**
127
+ * The pin kind of a Zod schema.
128
+ *
129
+ * `.optional()`, `.nullable()` and `.default(...)` take the kind of
130
+ * the schema they wrap. A literal, and a union whose members all
131
+ * have one kind (`z.null()` members aside, as with `.nullable()`),
132
+ * take that kind — so a union of string literals is a `'str'` pin.
133
+ * Any other schema throws.
134
+ */
89
135
  zodToKind(kind) {
90
136
  if (kind === undefined) {
91
137
  throw new Error('Unspecified kind');
92
138
  }
93
- if (kind instanceof ZodOptional) {
94
- kind = kind.def.innerType;
139
+ if (kind instanceof ZodOptional ||
140
+ kind instanceof ZodNullable ||
141
+ kind instanceof ZodDefault) {
142
+ return this.zodToKind(kind.def.innerType);
143
+ }
144
+ if (kind instanceof ZodLiteral) {
145
+ return sameKind([...kind.values].map((value) => literalKind(value)), 'literal');
146
+ }
147
+ if (kind instanceof ZodUnion) {
148
+ const members = kind.options.filter((member) => !(member instanceof ZodNull));
149
+ return sameKind(members.map((member) => this.zodToKind(member)), 'union');
95
150
  }
96
151
  if (kind instanceof ZodBoolean) {
97
152
  return 'bool';
@@ -114,11 +169,34 @@ export class TypedBlock {
114
169
  else if (kind instanceof ZodUnknown) {
115
170
  return 'null';
116
171
  }
117
- else if (kind instanceof ZodDefault) {
118
- return this.zodToKind(kind.def.innerType);
119
- }
120
172
  else {
121
- throw new Error(`Invalid kind: ${kind?.constructor.name}`);
173
+ throw new Error(`Invalid kind: ${kind.constructor.name} has no pin kind. Use a ` +
174
+ 'boolean, number, string, enum, literal, array, object or ' +
175
+ 'unknown schema, a union of schemas of one kind, or one of ' +
176
+ 'these made optional, nullable or defaulted.');
122
177
  }
123
178
  }
124
179
  }
180
+ /** The pin kind of a literal value. */
181
+ function literalKind(value) {
182
+ switch (typeof value) {
183
+ case 'string':
184
+ return 'str';
185
+ case 'number':
186
+ return 'number';
187
+ case 'boolean':
188
+ return 'bool';
189
+ default:
190
+ throw new Error(`Invalid kind: the literal ${String(value)} has no pin kind. ` +
191
+ 'Use string, number or boolean literals.');
192
+ }
193
+ }
194
+ /** The one kind of `kinds`, which describe the members of a `what`. */
195
+ function sameKind(kinds, what) {
196
+ const unique = [...new Set(kinds)];
197
+ if (unique.length !== 1) {
198
+ throw new Error(`Invalid kind: a ${what} with ${unique.length === 0 ? 'no kind' : `the kinds ${unique.join(', ')}`} has no ` +
199
+ 'single pin kind. Use members of one kind.');
200
+ }
201
+ return unique[0];
202
+ }
package/dist/index.d.ts CHANGED
@@ -1,9 +1,98 @@
1
- export { BlocksEngine, initEngine, EngineCommand } from './logic_mesh.js';
2
- export { defineBlock, TypedBlock } from './TypedBlock';
1
+ export { BlocksEngine, initEngine, EngineCommand, registerConnector, unregisterConnector, connectorRegistered, connectorIs, setLogLevel, } from './logic_mesh.js';
2
+ export { defineBlock, TypedBlock } from './TypedBlock.js';
3
+ export { createEngineSession, startEngine, EngineSession, type EngineSessionOptions, type WatchSubscription, } from './EngineSession.js';
4
+ export { isLogicMeshError, type LogicMeshError, type LogicMeshErrorCode, } from './LogicMeshError.js';
5
+ export { defineJsBlocks, type JsBlocks, type JsBlockFn, type JsBlocksOptions, } from './JsBlocks.js';
6
+ export { PROGRAM_FORMAT_VERSION } from './ProgramVersion.js';
7
+ export { ProgramSchema, programSchema } from './ProgramSchema.js';
8
+ /**
9
+ * The callback a connector subscription pushes values through.
10
+ *
11
+ * - `callback(value)` pushes `value` into the subscription stream.
12
+ * - `callback(undefined, detail)` pushes an error carrying `detail`;
13
+ * the subscription stays live.
14
+ * - `callback()` — no arguments — ends the stream.
15
+ *
16
+ * Beware: an accidentally-`undefined` value is indistinguishable from
17
+ * `callback()` and silently ends the subscription. Once the engine
18
+ * drops the subscription the callback is destroyed and calling it
19
+ * throws, so stop calling it after the unsubscribe function runs.
20
+ */
21
+ export type ConnectorCallback = (value?: unknown, detail?: unknown) => void;
22
+ /**
23
+ * A connector that is implemented in JS.
24
+ *
25
+ * Register it under a name with `registerConnector` (or the
26
+ * `BlocksEngine.registerConnector` convenience method), then attach it
27
+ * to the running engine with the `addConnector` engine command; the
28
+ * `ExternalIn`/`ExternalOut`/`Request` blocks resolve it by name.
29
+ *
30
+ * Every method may return a Promise — the engine awaits it — or a
31
+ * plain value, and is invoked with `this` bound to the connector
32
+ * object, so class instances work. Values cross the boundary as
33
+ * Haystack-encoded JSON: plain JS numbers, strings, booleans and
34
+ * `null` map directly.
35
+ */
36
+ export interface JsConnector {
37
+ /**
38
+ * Called once per subscription. Push values through `callback` and
39
+ * return an unsubscribe function — directly or via a Promise — to be
40
+ * told when the engine drops the subscription (return nothing if
41
+ * there is no cleanup to do). The unsubscribe function may run after
42
+ * the stream already ended, so it must be idempotent.
43
+ */
44
+ subscribe(address: string, callback: ConnectorCallback): (() => void) | void | Promise<(() => void) | void>;
45
+ /**
46
+ * Publishes `value` to `address`. A thrown exception or a rejected
47
+ * Promise marks the publish as failed.
48
+ */
49
+ publish(address: string, value: unknown): void | Promise<void>;
50
+ /**
51
+ * Round-trips `value` through `address`, resolving with the
52
+ * response value.
53
+ */
54
+ request(address: string, value: unknown): unknown;
55
+ /**
56
+ * Optional. Called when the engine starts running, before any block
57
+ * executes.
58
+ */
59
+ start?(): void | Promise<void>;
60
+ /**
61
+ * Optional. Called on engine shutdown and reset. Must end every
62
+ * outstanding subscription by invoking its callback with no
63
+ * arguments.
64
+ */
65
+ stop?(): void | Promise<void>;
66
+ }
3
67
  /**
4
68
  * The kind of the block pin.
5
69
  */
6
70
  export type Kind = 'null' | 'remove' | 'marker' | 'na' | 'bool' | 'number' | 'str' | 'uri' | 'ref' | 'symbol' | 'date' | 'time' | 'dateTime' | 'coord' | 'xstr' | 'list' | 'dict' | 'grid';
71
+ /**
72
+ * The level `setLogLevel` takes: the most verbose level the engine
73
+ * logs to the console at. The module starts at `'warn'`.
74
+ */
75
+ export type LogLevel = 'off' | 'error' | 'warn' | 'info' | 'debug' | 'trace';
76
+ /**
77
+ * The function that executes a JS block.
78
+ *
79
+ * It is called with the block's input values, in the order of the
80
+ * inputs in the block description, and returns the output values in
81
+ * the order of the outputs — directly or through a Promise. The values
82
+ * are Haystack values in their JSON encoding, as every binding hands
83
+ * them out: a Dict is a plain object, and an input with no value, or a
84
+ * `Null` one, is `null`. Returning
85
+ * anything but an array leaves the outputs as they are. A throw or a
86
+ * rejection faults the block, with the error's message as the fault
87
+ * reason.
88
+ */
89
+ export type JsBlockExecutor = (inputs: unknown[]) => unknown[] | undefined | Promise<unknown[] | undefined>;
90
+ /**
91
+ * What `BlocksEngine.registerBlock` takes to run a JS block: a factory
92
+ * called once per block instance, returning the instance's
93
+ * {@link JsBlockExecutor}.
94
+ */
95
+ export type JsBlockFactory = () => JsBlockExecutor;
7
96
  /**
8
97
  * A block that is implemented in JS
9
98
  */
@@ -14,14 +103,9 @@ export type JsBlock = {
14
103
  desc: BlockDesc;
15
104
  /**
16
105
  * An optional block factory function that returns a function that is called when the block is executed.
17
- *
18
- * The execute function is called with the block inputs and should return the block outputs.
19
- * The order of the inputs and outputs is the same as the order of the pins in the block description.
20
- * Returning `undefined` will not change the output value.
21
- *
22
- * @returns The execute function that is called when the block is executed.
106
+ * See {@link JsBlockExecutor}.
23
107
  */
24
- executor?: () => (inputs: unknown[]) => Promise<unknown[] | undefined>;
108
+ executor?: JsBlockFactory;
25
109
  };
26
110
  /**
27
111
  * A block pin.
@@ -108,7 +192,7 @@ export interface BlockNotification {
108
192
  */
109
193
  id: string;
110
194
  /**
111
- * The changes
195
+ * The pins that changed, outputs first, each in the block's pin order
112
196
  */
113
197
  changes: {
114
198
  /**
@@ -121,8 +205,10 @@ export interface BlockNotification {
121
205
  source: string;
122
206
  /**
123
207
  * The value that was changed on this pin. The shape is
124
- * Haystack-encoded JSON; consumers narrow as needed (e.g.
125
- * `typeof value === 'number'` for a numeric pin).
208
+ * Haystack-encoded JSON, as `inspectBlock` and `getProgram` give
209
+ * it: a Dict is a plain object, and `Null` is `null`. Consumers
210
+ * narrow as needed (e.g. `typeof value === 'number'` for a numeric
211
+ * pin).
126
212
  */
127
213
  value: unknown;
128
214
  }[];
@@ -130,13 +216,59 @@ export interface BlockNotification {
130
216
  * The block's operational state at the time of the notification.
131
217
  * Drives fault visualization on the UI.
132
218
  */
133
- state: 'running' | 'fault' | 'disabled' | 'terminated';
219
+ state: BlockState;
134
220
  /**
135
221
  * Optional reason associated with `state === "fault"`.
136
222
  */
137
223
  faultReason?: string;
138
224
  }
139
- export interface LinkData {
225
+ /**
226
+ * A block's operational state.
227
+ */
228
+ export type BlockState = 'running' | 'fault' | 'disabled' | 'terminated';
229
+ /**
230
+ * A block's state and pin values, as `EngineCommand.inspectBlock`
231
+ * resolves with them: plain objects, with pin values in the Haystack
232
+ * JSON encoding `getProgram` uses.
233
+ */
234
+ export interface BlockInspection {
235
+ /** The block id. */
236
+ id: string;
237
+ /** The block type name. */
238
+ name: string;
239
+ /** The library of the block type. */
240
+ lib: string;
241
+ /** The input pins by name. */
242
+ inputs: Record<string, {
243
+ /** The pin kind. */
244
+ kind: Kind;
245
+ /** The pin value; `null` when it has none. */
246
+ val: unknown;
247
+ /** True if the pin is linked to another pin. */
248
+ isConnected: boolean;
249
+ }>;
250
+ /** The output pins by name. */
251
+ outputs: Record<string, {
252
+ /** The pin kind. */
253
+ kind: Kind;
254
+ /** The pin value; `null` when it has none. */
255
+ val: unknown;
256
+ }>;
257
+ /** The block's operational state. */
258
+ state: BlockState;
259
+ /** The reason when `state` is `'fault'`. */
260
+ faultReason?: string;
261
+ }
262
+ /**
263
+ * A link between two block pins, as `createLink` resolves with it and a
264
+ * program saves it.
265
+ *
266
+ * Declared with `type`, so that it is a plain JSON object to
267
+ * TypeScript too: a `LinkData` can be stored where a
268
+ * `Record<string, unknown>` is expected, such as a graph library's edge
269
+ * data.
270
+ */
271
+ export type LinkData = {
140
272
  /**
141
273
  * The link id
142
274
  */
@@ -157,6 +289,76 @@ export interface LinkData {
157
289
  * The link target block uuid
158
290
  */
159
291
  targetBlockUuid: string;
292
+ };
293
+ /**
294
+ * A block's UI position in a saved program.
295
+ */
296
+ export interface Position {
297
+ x: number;
298
+ y: number;
299
+ }
300
+ /**
301
+ * A pin value in a saved program.
302
+ */
303
+ export interface PinValue {
304
+ /**
305
+ * The pin value, a Haystack value encoded as JSON. `null` when the
306
+ * pin has none; a load does not write a `null`.
307
+ */
308
+ value: unknown;
309
+ /**
310
+ * True if the pin is linked to another pin. `loadProgram` reads a
311
+ * missing flag as `false`.
312
+ */
313
+ isConnected: boolean;
314
+ }
315
+ /**
316
+ * Opaque editor state saved with a block: any JSON object. The engine
317
+ * keeps it without reading it, and `getProgram` returns it as
318
+ * `loadProgram` received it. Values JSON cannot encode, such as
319
+ * `undefined`, come back as `null`.
320
+ */
321
+ export type EditorMetadata = Record<string, unknown>;
322
+ /**
323
+ * One block of a saved program.
324
+ *
325
+ * `Editor` types the block's editor metadata for an application that
326
+ * knows what it stores there. Like the engine, it takes a plain JSON
327
+ * object only — not an array, a function or a class instance such as a
328
+ * `Date` — so declare it as an object type with `type`: an `interface`
329
+ * has no index signature, and does not satisfy {@link EditorMetadata}.
330
+ *
331
+ * ```ts
332
+ * type BlockEditor = { widget?: { kind: string } };
333
+ * const block: ProgramBlock<BlockEditor> = {
334
+ * name: 'Add',
335
+ * lib: 'core',
336
+ * editor: { widget: { kind: 'Slider' } },
337
+ * };
338
+ * ```
339
+ */
340
+ export interface ProgramBlock<Editor extends EditorMetadata = EditorMetadata> {
341
+ /** The block type name. */
342
+ name: string;
343
+ /** The library of the block type. */
344
+ lib: string;
345
+ /**
346
+ * The version of the block type the program was saved with (the
347
+ * block's `BlockDesc.ver`). A load rejects a block saved at an
348
+ * incompatible version of its type — another major version, or below
349
+ * 1.0 another minor version. Left out, the block is not checked.
350
+ */
351
+ ver?: string;
352
+ /** User-supplied display label shown alongside the block-type name. */
353
+ label?: string;
354
+ /** The block's position in the editor. */
355
+ position?: Position;
356
+ /** Opaque editor metadata, see {@link EditorMetadata}. */
357
+ editor?: Editor;
358
+ /** Input pin values by pin name. */
359
+ inputs?: Record<string, PinValue>;
360
+ /** Output pin values by pin name. */
361
+ outputs?: Record<string, PinValue>;
160
362
  }
161
363
  /**
162
364
  * Describes a program that would be loaded in the engine.
@@ -164,47 +366,32 @@ export interface LinkData {
164
366
  * The program is a set of blocks and links between them.
165
367
  * The program and the blocks have meta data that would be used in the editor
166
368
  * for example to position the blocks.
369
+ *
370
+ * This is the shape `getProgram` returns and `loadProgram` takes. Beyond
371
+ * it, `loadProgram` accepts a program without `version` (a pre-2.0
372
+ * save), and reads missing `blocks` or `links` as empty.
373
+ *
374
+ * `Editor` types the blocks' editor metadata, see {@link ProgramBlock}.
167
375
  */
168
- export interface Program {
376
+ export interface Program<Editor extends EditorMetadata = EditorMetadata> {
169
377
  /**
170
- * The program name
378
+ * The save format version, see {@link PROGRAM_FORMAT_VERSION}.
171
379
  */
172
- name: string;
380
+ version: number;
381
+ /**
382
+ * Optional program name
383
+ */
384
+ name?: string;
173
385
  /**
174
386
  * Optional program description
175
387
  */
176
388
  description?: string;
177
389
  /**
178
- * Blocks used in the program
179
- */
180
- blocks: {
181
- [blockUuid: string]: {
182
- name: string;
183
- lib: string;
184
- /** User-supplied display label shown alongside the block-type name. */
185
- label?: string;
186
- positions: {
187
- x: number;
188
- y: number;
189
- };
190
- inputs?: {
191
- [pinName: string]: {
192
- value?: unknown;
193
- isConnected?: boolean;
194
- };
195
- };
196
- outputs?: {
197
- [pinName: string]: {
198
- value?: unknown;
199
- isConnected?: boolean;
200
- };
201
- };
202
- };
203
- };
204
- /**
205
- * Links between blocks
206
- */
207
- links: {
208
- [linkUuid: string]: LinkData;
209
- };
390
+ * Blocks used in the program, by block uuid
391
+ */
392
+ blocks: Record<string, ProgramBlock<Editor>>;
393
+ /**
394
+ * Links between blocks, by link uuid
395
+ */
396
+ links: Record<string, LinkData>;
210
397
  }
package/dist/index.js CHANGED
@@ -1,2 +1,7 @@
1
- export { BlocksEngine, initEngine, EngineCommand } from './logic_mesh.js';
2
- export { defineBlock, TypedBlock } from './TypedBlock';
1
+ export { BlocksEngine, initEngine, EngineCommand, registerConnector, unregisterConnector, connectorRegistered, connectorIs, setLogLevel, } from './logic_mesh.js';
2
+ export { defineBlock, TypedBlock } from './TypedBlock.js';
3
+ export { createEngineSession, startEngine, EngineSession, } from './EngineSession.js';
4
+ export { isLogicMeshError, } from './LogicMeshError.js';
5
+ export { defineJsBlocks, } from './JsBlocks.js';
6
+ export { PROGRAM_FORMAT_VERSION } from './ProgramVersion.js';
7
+ export { ProgramSchema, programSchema } from './ProgramSchema.js';