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.
- package/LICENSE +11 -0
- package/README.md +376 -43
- 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 +32 -2
- package/dist/TypedBlock.js +100 -22
- package/dist/index.d.ts +236 -49
- 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 +35 -20
package/dist/JsBlocks.js
ADDED
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
import { connectorIs, connectorRegistered, registerConnector, unregisterConnector, } from './logic_mesh.js';
|
|
2
|
+
/** The attach-time error for a connector name owned by someone else. */
|
|
3
|
+
function nameInUseMessage(name) {
|
|
4
|
+
return (`A different connector is already registered under '${name}' — ` +
|
|
5
|
+
'pick another name, or unregister the existing one first.');
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* Block-like ergonomics for JS-implemented logic, without a new engine
|
|
9
|
+
* API: the functions are exposed through one {@link JsConnector} —
|
|
10
|
+
* request/response only — and materialize in the graph as `Request`
|
|
11
|
+
* blocks whose `address` pin selects the function. The engine sees
|
|
12
|
+
* nothing but a connector.
|
|
13
|
+
*
|
|
14
|
+
* Created by {@link defineJsBlocks}. The lifecycle is the connector
|
|
15
|
+
* lifecycle: {@link attach} registers the connector and hands it to
|
|
16
|
+
* the running engine (which starts it and manages it from then on),
|
|
17
|
+
* {@link detach} reverses that, and an engine reset detaches every
|
|
18
|
+
* managed connector — re-{@link attach} afterwards, exactly as with a
|
|
19
|
+
* hand-written connector.
|
|
20
|
+
*
|
|
21
|
+
* Deliberately request-shaped: value *streams* (an `ExternalIn`
|
|
22
|
+
* source) don't fit the one-value-in/one-value-out function signature,
|
|
23
|
+
* so the façade does not bend it — implement a raw {@link JsConnector}
|
|
24
|
+
* with a `subscribe` method for those, and bind an `ExternalIn` block
|
|
25
|
+
* to it by name and address. Fire-and-forget *sinks* do fit: the
|
|
26
|
+
* connector's `publish` dispatches to the same function map (return
|
|
27
|
+
* value discarded), so an `ExternalOut` block bound to this connector
|
|
28
|
+
* name and a function name works without extra API.
|
|
29
|
+
*/
|
|
30
|
+
export class JsBlocks {
|
|
31
|
+
/** The connector name — see {@link JsBlocksOptions.name}. */
|
|
32
|
+
name;
|
|
33
|
+
functions;
|
|
34
|
+
connector;
|
|
35
|
+
/**
|
|
36
|
+
* Serializes {@link attach} and {@link detach} per instance — the
|
|
37
|
+
* same pattern as `EngineSession`'s control chain. Both operations
|
|
38
|
+
* are check-then-act against the live registry; two overlapping
|
|
39
|
+
* calls would race the check and the loser would surface the
|
|
40
|
+
* engine's "already managed" error for what is really an idempotent
|
|
41
|
+
* success.
|
|
42
|
+
*/
|
|
43
|
+
lifecycleChain = Promise.resolve();
|
|
44
|
+
/**
|
|
45
|
+
* Whether this instance owns the current registry entry for
|
|
46
|
+
* {@link name}, decided against the LIVE registry: the entry must be
|
|
47
|
+
* this instance's own connector object (`connectorIs` compares JS
|
|
48
|
+
* object identity). A plain "I registered this" boolean cannot carry
|
|
49
|
+
* this — an engine reset unregisters connectors behind the façade's
|
|
50
|
+
* back, after which the same name may be re-registered by someone
|
|
51
|
+
* else, and the stale flag would bless a hijack.
|
|
52
|
+
*/
|
|
53
|
+
ownsRegistration() {
|
|
54
|
+
return connectorIs(this.name, this.connector);
|
|
55
|
+
}
|
|
56
|
+
enqueue(op) {
|
|
57
|
+
const next = this.lifecycleChain.catch(() => { }).then(op);
|
|
58
|
+
this.lifecycleChain = next;
|
|
59
|
+
return next;
|
|
60
|
+
}
|
|
61
|
+
constructor(functions, options = {}) {
|
|
62
|
+
this.name = options.name ?? 'js';
|
|
63
|
+
this.functions = functions;
|
|
64
|
+
const lookup = (address) => {
|
|
65
|
+
const fn = this.functions[address];
|
|
66
|
+
if (typeof fn !== 'function') {
|
|
67
|
+
throw new Error(`'${this.name}' has no function named '${address}' ` +
|
|
68
|
+
`(available: ${Object.keys(this.functions).join(', ')})`);
|
|
69
|
+
}
|
|
70
|
+
return fn;
|
|
71
|
+
};
|
|
72
|
+
this.connector = {
|
|
73
|
+
subscribe: (address) => {
|
|
74
|
+
throw new Error(`'${this.name}' exposes plain functions and has no value ` +
|
|
75
|
+
`streams to subscribe to (address '${address}'). For a ` +
|
|
76
|
+
'streaming source, implement a JsConnector with a subscribe ' +
|
|
77
|
+
'method and bind an ExternalIn block to it.');
|
|
78
|
+
},
|
|
79
|
+
// Sink direction: an ExternalOut bound to this connector invokes
|
|
80
|
+
// the addressed function and discards its result. Exceptions and
|
|
81
|
+
// rejections fault the ExternalOut block as publish failures.
|
|
82
|
+
publish: async (address, value) => {
|
|
83
|
+
await lookup(address)(value);
|
|
84
|
+
},
|
|
85
|
+
// Request direction: the addressed function's result becomes the
|
|
86
|
+
// Request block's `out` value.
|
|
87
|
+
request: async (address, value) => {
|
|
88
|
+
const result = await lookup(address)(value);
|
|
89
|
+
// `undefined` has no Haystack encoding and would fault the
|
|
90
|
+
// block on the way back; a function that returns nothing means
|
|
91
|
+
// "no result", which Null carries.
|
|
92
|
+
return result === undefined ? null : result;
|
|
93
|
+
},
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Registers the connector and attaches it to the running engine
|
|
98
|
+
* (`addConnector`), which starts it and manages its lifecycle from
|
|
99
|
+
* then on. Idempotent: the initial `listConnectors` reply is a FIFO
|
|
100
|
+
* barrier — it proves the engine has processed everything queued
|
|
101
|
+
* before it, a pending reset included — and an already-attached
|
|
102
|
+
* connector is left alone.
|
|
103
|
+
*
|
|
104
|
+
* `command` must be a handle created before `engine.run()` (any
|
|
105
|
+
* {@link EngineSession} handle qualifies), and — like every engine
|
|
106
|
+
* request — this only resolves while the engine runs (paused or not).
|
|
107
|
+
*
|
|
108
|
+
* Overlapping attach/detach calls on one instance are serialized
|
|
109
|
+
* internally, so two same-tick attaches both succeed (the second
|
|
110
|
+
* observes the first's work and no-ops).
|
|
111
|
+
*
|
|
112
|
+
* Throws if the name is taken by a connector this instance does not
|
|
113
|
+
* own — registered by someone else, attached or not.
|
|
114
|
+
*/
|
|
115
|
+
attach(command) {
|
|
116
|
+
return this.enqueue(() => this.attachNow(command));
|
|
117
|
+
}
|
|
118
|
+
async attachNow(command) {
|
|
119
|
+
const attached = await command.listConnectors();
|
|
120
|
+
if (attached.includes(this.name)) {
|
|
121
|
+
// Only our own attachment is an idempotent success: a foreign
|
|
122
|
+
// connector on the name would otherwise silently answer this
|
|
123
|
+
// instance's blocks with someone else's functions.
|
|
124
|
+
if (this.ownsRegistration())
|
|
125
|
+
return;
|
|
126
|
+
throw new Error(nameInUseMessage(this.name));
|
|
127
|
+
}
|
|
128
|
+
if (!connectorRegistered(this.name)) {
|
|
129
|
+
registerConnector(this.name, this.connector);
|
|
130
|
+
}
|
|
131
|
+
else if (!this.ownsRegistration()) {
|
|
132
|
+
throw new Error(nameInUseMessage(this.name));
|
|
133
|
+
}
|
|
134
|
+
await command.addConnector(this.name);
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Detaches the connector from the engine (`removeConnector` — the
|
|
138
|
+
* engine stops it and unregisters it), or, when it was registered
|
|
139
|
+
* but never attached, just unregisters it. Acts only on a
|
|
140
|
+
* registration this instance owns — decided against the live
|
|
141
|
+
* registry, so a foreign same-name connector is left alone even when
|
|
142
|
+
* it took the name after an engine reset detached ours — and is a
|
|
143
|
+
* no-op when there is nothing left to tear down, so calling it after
|
|
144
|
+
* a reset (which already detached everything) is safe. Serialized
|
|
145
|
+
* with {@link attach} per instance.
|
|
146
|
+
*/
|
|
147
|
+
detach(command) {
|
|
148
|
+
return this.enqueue(() => this.detachNow(command));
|
|
149
|
+
}
|
|
150
|
+
async detachNow(command) {
|
|
151
|
+
// The live registry entry must be ours: whatever this instance
|
|
152
|
+
// once registered, tearing down someone else's current attachment
|
|
153
|
+
// (or registration) is never its call.
|
|
154
|
+
if (!this.ownsRegistration())
|
|
155
|
+
return;
|
|
156
|
+
const attached = await command.listConnectors();
|
|
157
|
+
if (attached.includes(this.name)) {
|
|
158
|
+
await command.removeConnector(this.name);
|
|
159
|
+
}
|
|
160
|
+
else if (this.ownsRegistration()) {
|
|
161
|
+
// Re-checked after the await: a reset can unregister this
|
|
162
|
+
// connector — and a third party re-register the name — while
|
|
163
|
+
// `listConnectors` was in flight, and a foreign registration is
|
|
164
|
+
// never ours to tear down.
|
|
165
|
+
unregisterConnector(this.name);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* Materializes function `fn` as a block: adds a `Request` block
|
|
170
|
+
* (under `blockUuid` when given) and wires its `connector` and
|
|
171
|
+
* `address` pins to this connector and the function name. Returns
|
|
172
|
+
* the block's UUID.
|
|
173
|
+
*
|
|
174
|
+
* Write the argument to the block's `in` pin — or link another
|
|
175
|
+
* block's output to it — and the function's result appears on `out`.
|
|
176
|
+
* The block's `timeout` pin (milliseconds) bounds a hung function.
|
|
177
|
+
*/
|
|
178
|
+
async addBlock(command, fn, blockUuid) {
|
|
179
|
+
if (typeof this.functions[fn] !== 'function') {
|
|
180
|
+
throw new Error(`'${this.name}' has no function named '${fn}' ` +
|
|
181
|
+
`(available: ${Object.keys(this.functions).join(', ')})`);
|
|
182
|
+
}
|
|
183
|
+
const id = await command.addBlock('Request', blockUuid);
|
|
184
|
+
await command.writeBlockInput(id, 'connector', this.name);
|
|
185
|
+
await command.writeBlockInput(id, 'address', fn);
|
|
186
|
+
return id;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
/**
|
|
190
|
+
* Defines a set of JS functions to be exposed as blocks — see
|
|
191
|
+
* {@link JsBlocks} for the mechanics and limits.
|
|
192
|
+
*
|
|
193
|
+
* ```ts
|
|
194
|
+
* const jsBlocks = defineJsBlocks(
|
|
195
|
+
* {
|
|
196
|
+
* scale: (value) => (value as number) * 2,
|
|
197
|
+
* fetchTemp: async (zone) => readSensor(zone as string), // async is fine
|
|
198
|
+
* },
|
|
199
|
+
* { name: 'js' },
|
|
200
|
+
* );
|
|
201
|
+
*
|
|
202
|
+
* const { command } = startEngine();
|
|
203
|
+
* await jsBlocks.attach(command);
|
|
204
|
+
*
|
|
205
|
+
* const id = await jsBlocks.addBlock(command, 'scale');
|
|
206
|
+
* await command.writeBlockInput(id, 'in', 21); // out becomes 42
|
|
207
|
+
* ```
|
|
208
|
+
*/
|
|
209
|
+
export function defineJsBlocks(functions, options = {}) {
|
|
210
|
+
return new JsBlocks(functions, options);
|
|
211
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The stable, machine-readable code of a failed engine command — the
|
|
3
|
+
* name of the `ErrorCode` the Rust engine reported. A code never
|
|
4
|
+
* changes meaning; new failures get new codes.
|
|
5
|
+
*
|
|
6
|
+
* The union is closed for each package version: the engine that
|
|
7
|
+
* rejects is the wasm module shipped in this package, and its test
|
|
8
|
+
* suite checks this list against its own codes, so it names every code
|
|
9
|
+
* a command can reject with. A later version may add codes, so keep a
|
|
10
|
+
* `default` branch when switching on one.
|
|
11
|
+
*/
|
|
12
|
+
export type LogicMeshErrorCode = 'BlockNotFound' | 'BlockNotRegistered' | 'AmbiguousBlockName' | 'BlockAlreadyRegistered' | 'TooManyInputs' | 'BlockInstanceNotFound' | 'DuplicateBlockId' | 'NoRuntime' | 'InvalidBlockUuid' | 'PinNotFound' | 'InputNotFound' | 'OutputNotFound' | 'LinkBlockNotInProgram' | 'DuplicateLink' | 'DuplicateLinkId' | 'InvalidLinkUuid' | 'UnsupportedProgramVersion' | 'BlockVersionMismatch' | 'BlockTaskGone' | 'BlockDroppedReply' | 'ConnectorAlreadyManaged' | 'ConnectorNotManaged' | 'ConnectorStartFailed' | 'ConnectorStartTimeout' | 'EngineGone' | 'UnexpectedResponse' | 'EvalPanicked' | 'EvalTimeout' | 'AlreadyConnected' | 'SelfLink' | 'NotConnected' | 'KindConversion' | 'UnexpectedValue' | 'ValueConversion' | 'UnitConversion' | 'ZincDecode' | 'ZincEncode' | 'ParseBool' | 'ExternalUnsupported' | 'ExternalUnsupportedMultiThreaded' | 'ExternalLibraryNotFound' | 'ExternalFactoryCallFailed' | 'ExternalFactoryReturnedNonFunction' | 'ConnectorPropertyUnreadable' | 'ConnectorMethodMissing' | 'ConnectorMethodNotFunction' | 'ConnectorNotFound' | 'ConnectorAlreadyRegistered' | 'ConnectorSubscribeFailed' | 'ConnectorPublishFailed' | 'ConnectorRequestFailed' | 'ConnectorTimeout' | 'ConnectorTransport' | 'UnknownImplementation' | 'UnknownRunCondition' | 'UnknownPinKind' | 'BlockNotExternal' | 'InvalidProgram' | 'InvalidArgument' | 'InvalidValue' | 'Serialization';
|
|
13
|
+
/**
|
|
14
|
+
* The `Error` an `EngineCommand` promise rejects with, and the one the
|
|
15
|
+
* synchronous bindings — `initEngine`, the `BlocksEngine` constructor,
|
|
16
|
+
* `registerBlock`, `registerConnector`, `setLogLevel` — throw: `name`
|
|
17
|
+
* is `'LogicMeshError'`, `code` says what failed, and `message`
|
|
18
|
+
* describes it, including the underlying causes.
|
|
19
|
+
*
|
|
20
|
+
* ```ts
|
|
21
|
+
* try {
|
|
22
|
+
* await command.loadProgram(program);
|
|
23
|
+
* } catch (err) {
|
|
24
|
+
* if (isLogicMeshError(err) && err.code === 'UnsupportedProgramVersion') {
|
|
25
|
+
* // Saved by a newer version of the editor.
|
|
26
|
+
* }
|
|
27
|
+
* }
|
|
28
|
+
* ```
|
|
29
|
+
*/
|
|
30
|
+
export interface LogicMeshError extends Error {
|
|
31
|
+
name: 'LogicMeshError';
|
|
32
|
+
code: LogicMeshErrorCode;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Whether `err` is a {@link LogicMeshError}: an engine command's
|
|
36
|
+
* rejection, or an error a synchronous binding threw.
|
|
37
|
+
*/
|
|
38
|
+
export declare function isLogicMeshError(err: unknown): err is LogicMeshError;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Whether `err` is a {@link LogicMeshError}: an engine command's
|
|
3
|
+
* rejection, or an error a synchronous binding threw.
|
|
4
|
+
*/
|
|
5
|
+
export function isLogicMeshError(err) {
|
|
6
|
+
return (err instanceof Error &&
|
|
7
|
+
err.name === 'LogicMeshError' &&
|
|
8
|
+
typeof err.code === 'string');
|
|
9
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import type { EditorMetadata, Program } from './index.js';
|
|
2
|
+
import { type ZodType } from 'zod';
|
|
3
|
+
/**
|
|
4
|
+
* A Zod schema of a saved program: what `getProgram` returns and
|
|
5
|
+
* `loadProgram` takes, checked without the engine. A tool can validate
|
|
6
|
+
* a program file, or a server the programs it stores, before any wasm
|
|
7
|
+
* is loaded, and each problem comes with its path in the program.
|
|
8
|
+
*
|
|
9
|
+
* It reads a program as the engine does:
|
|
10
|
+
*
|
|
11
|
+
* - a program without `version`, a save from logic-mesh 1.x, parses as
|
|
12
|
+
* version 0, and a block's `positions` as its `position`;
|
|
13
|
+
* - a missing `blocks`, `links` or pin `isConnected` reads as empty or
|
|
14
|
+
* `false`, and a `null` optional field as absent;
|
|
15
|
+
* - keys the format does not have are dropped;
|
|
16
|
+
* - a program from a newer format fails on `version`, with the message
|
|
17
|
+
* `loadProgram` rejects it with. That is its first issue; the rest of
|
|
18
|
+
* its shape is checked too.
|
|
19
|
+
*
|
|
20
|
+
* A program that parses can still fail to load: the shape says nothing
|
|
21
|
+
* of whether its block types are registered, its pins exist, its ids
|
|
22
|
+
* are UUIDs or its pin values decode as Haystack values. Those are the
|
|
23
|
+
* engine's checks.
|
|
24
|
+
*
|
|
25
|
+
* Without an argument, editor metadata is any JSON object, as the
|
|
26
|
+
* engine takes it. Pass a schema for your own `Editor` type to check
|
|
27
|
+
* that too, and to type the result as `Program<Editor>`. The engine
|
|
28
|
+
* keeps editor metadata as it is, so to keep keys your schema does not
|
|
29
|
+
* name, build it with `z.looseObject`.
|
|
30
|
+
*
|
|
31
|
+
* Pin values and editor metadata are read as JSON, what `JSON.parse`
|
|
32
|
+
* returns: an `undefined` or a function in them fails to parse.
|
|
33
|
+
*
|
|
34
|
+
* For tools outside JavaScript, `z.toJSONSchema(ProgramSchema, { io:
|
|
35
|
+
* 'input' })` gives the format as a JSON Schema, without the checks
|
|
36
|
+
* JSON Schema cannot express (a duplicate `position`, and the message
|
|
37
|
+
* of a newer `version`).
|
|
38
|
+
*
|
|
39
|
+
* ```ts
|
|
40
|
+
* import { ProgramSchema, programSchema } from 'logic-mesh';
|
|
41
|
+
* import { z } from 'zod';
|
|
42
|
+
*
|
|
43
|
+
* const result = ProgramSchema.safeParse(JSON.parse(text));
|
|
44
|
+
* if (!result.success) console.error(z.prettifyError(result.error));
|
|
45
|
+
*
|
|
46
|
+
* const EditorProgram = programSchema(
|
|
47
|
+
* z.looseObject({ widget: z.object({ kind: z.string() }).optional() }),
|
|
48
|
+
* );
|
|
49
|
+
* const program = EditorProgram.parse(saved); // Program<{ widget?: … }>
|
|
50
|
+
* ```
|
|
51
|
+
*/
|
|
52
|
+
export declare function programSchema(): ZodType<Program>;
|
|
53
|
+
export declare function programSchema<Editor extends EditorMetadata>(editor: ZodType<Editor>): ZodType<Program<Editor>>;
|
|
54
|
+
/**
|
|
55
|
+
* {@link programSchema} with any JSON object as editor metadata.
|
|
56
|
+
*/
|
|
57
|
+
export declare const ProgramSchema: ZodType<Program>;
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { PROGRAM_FORMAT_VERSION } from './ProgramVersion.js';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
/** The version a save from before format versions reads as. */
|
|
4
|
+
const LEGACY_FORMAT_VERSION = 0;
|
|
5
|
+
// The schemas below mirror how the engine reads a program (the serde
|
|
6
|
+
// shape of `base::program` in the Rust crate): the same keys are
|
|
7
|
+
// required, `null` reads as absent where the engine reads an `Option`,
|
|
8
|
+
// and keys the format does not have are dropped. Each transform's
|
|
9
|
+
// result is annotated with the package's own type, so a parsed program
|
|
10
|
+
// is exactly a `Program`.
|
|
11
|
+
const PositionSchema = z.object({ x: z.number(), y: z.number() });
|
|
12
|
+
const PinValueSchema = z.object({
|
|
13
|
+
// A Haystack value in its JSON encoding. The engine also checks that
|
|
14
|
+
// it decodes as one, which no JSON shape can tell.
|
|
15
|
+
value: z.json(),
|
|
16
|
+
isConnected: z.boolean().default(false),
|
|
17
|
+
});
|
|
18
|
+
const LinkDataSchema = z
|
|
19
|
+
.object({
|
|
20
|
+
id: z.string().nullish(),
|
|
21
|
+
sourceBlockPinName: z.string(),
|
|
22
|
+
sourceBlockUuid: z.string(),
|
|
23
|
+
targetBlockPinName: z.string(),
|
|
24
|
+
targetBlockUuid: z.string(),
|
|
25
|
+
})
|
|
26
|
+
.transform(({ id, ...link }) => id == null ? link : { id, ...link });
|
|
27
|
+
const EditorMetadataSchema = z.record(z.string(), z.json());
|
|
28
|
+
function programBlockSchema(editor) {
|
|
29
|
+
return (z
|
|
30
|
+
.object({
|
|
31
|
+
name: z.string(),
|
|
32
|
+
lib: z.string(),
|
|
33
|
+
ver: z.string().nullish(),
|
|
34
|
+
label: z.string().nullish(),
|
|
35
|
+
position: PositionSchema.nullish(),
|
|
36
|
+
// The key a save from before format versions used.
|
|
37
|
+
positions: PositionSchema.nullish(),
|
|
38
|
+
editor: editor.nullish(),
|
|
39
|
+
inputs: z.record(z.string(), PinValueSchema).optional(),
|
|
40
|
+
outputs: z.record(z.string(), PinValueSchema).optional(),
|
|
41
|
+
})
|
|
42
|
+
// As in the engine, which reads `positions` as an alias, naming
|
|
43
|
+
// both keys is an error, even when one of them is `null`.
|
|
44
|
+
.superRefine((block, ctx) => {
|
|
45
|
+
if ('position' in block && 'positions' in block) {
|
|
46
|
+
ctx.addIssue({
|
|
47
|
+
code: 'custom',
|
|
48
|
+
message: 'duplicate field `position`',
|
|
49
|
+
path: ['positions'],
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
})
|
|
53
|
+
.transform((raw) => {
|
|
54
|
+
const block = { name: raw.name, lib: raw.lib };
|
|
55
|
+
const position = raw.position ?? raw.positions;
|
|
56
|
+
if (raw.ver != null)
|
|
57
|
+
block.ver = raw.ver;
|
|
58
|
+
if (raw.label != null)
|
|
59
|
+
block.label = raw.label;
|
|
60
|
+
if (position != null)
|
|
61
|
+
block.position = position;
|
|
62
|
+
if (raw.editor != null)
|
|
63
|
+
block.editor = raw.editor;
|
|
64
|
+
if (raw.inputs)
|
|
65
|
+
block.inputs = raw.inputs;
|
|
66
|
+
if (raw.outputs)
|
|
67
|
+
block.outputs = raw.outputs;
|
|
68
|
+
return block;
|
|
69
|
+
}));
|
|
70
|
+
}
|
|
71
|
+
export function programSchema(editor = EditorMetadataSchema) {
|
|
72
|
+
return z
|
|
73
|
+
.object({
|
|
74
|
+
// First, so that a newer format's version is its first issue.
|
|
75
|
+
version: z
|
|
76
|
+
.int()
|
|
77
|
+
.min(0)
|
|
78
|
+
.max(PROGRAM_FORMAT_VERSION, {
|
|
79
|
+
error: (issue) => `Program format version ${issue.input} is not supported; the newest supported is ${PROGRAM_FORMAT_VERSION}`,
|
|
80
|
+
})
|
|
81
|
+
.optional(),
|
|
82
|
+
name: z.string().nullish(),
|
|
83
|
+
description: z.string().nullish(),
|
|
84
|
+
blocks: z.record(z.string(), programBlockSchema(editor)).optional(),
|
|
85
|
+
links: z.record(z.string(), LinkDataSchema).optional(),
|
|
86
|
+
})
|
|
87
|
+
.transform((raw) => {
|
|
88
|
+
const program = {
|
|
89
|
+
version: raw.version ?? LEGACY_FORMAT_VERSION,
|
|
90
|
+
blocks: raw.blocks ?? {},
|
|
91
|
+
links: raw.links ?? {},
|
|
92
|
+
};
|
|
93
|
+
if (raw.name != null)
|
|
94
|
+
program.name = raw.name;
|
|
95
|
+
if (raw.description != null)
|
|
96
|
+
program.description = raw.description;
|
|
97
|
+
return program;
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* {@link programSchema} with any JSON object as editor metadata.
|
|
102
|
+
*/
|
|
103
|
+
export const ProgramSchema = programSchema();
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The program save format version this package writes, and the newest
|
|
3
|
+
* its engine loads. `getProgram` returns programs in this version;
|
|
4
|
+
* `loadProgram` rejects a program with a higher one.
|
|
5
|
+
*
|
|
6
|
+
* A program with no `version` is a save from before format versions
|
|
7
|
+
* (logic-mesh 1.x): the same shape, except that a block's position is
|
|
8
|
+
* keyed `positions`. `loadProgram` still loads it.
|
|
9
|
+
*/
|
|
10
|
+
export declare const PROGRAM_FORMAT_VERSION = 1;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
// A module of its own, so that importing the version builds no schema
|
|
2
|
+
// and pulls in no zod: ProgramSchema.ts, which needs it at load time,
|
|
3
|
+
// imports it from here rather than from the entry it is re-exported by.
|
|
4
|
+
/**
|
|
5
|
+
* The program save format version this package writes, and the newest
|
|
6
|
+
* its engine loads. `getProgram` returns programs in this version;
|
|
7
|
+
* `loadProgram` rejects a program with a higher one.
|
|
8
|
+
*
|
|
9
|
+
* A program with no `version` is a save from before format versions
|
|
10
|
+
* (logic-mesh 1.x): the same shape, except that a block's position is
|
|
11
|
+
* keyed `positions`. `loadProgram` still loads it.
|
|
12
|
+
*/
|
|
13
|
+
export const PROGRAM_FORMAT_VERSION = 1;
|
package/dist/TypedBlock.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import type { BlockDesc, Kind } from './index';
|
|
2
|
-
import type { BlocksEngine } from './logic_mesh';
|
|
1
|
+
import type { BlockDesc, Kind } from './index.js';
|
|
2
|
+
import type { BlocksEngine } from './logic_mesh.js';
|
|
3
3
|
import { z, type ZodType } from 'zod';
|
|
4
4
|
type InferType<T> = {
|
|
5
5
|
-readonly [K in keyof T]: z.infer<ExtractZodType<T[K]>>;
|
|
@@ -9,6 +9,18 @@ type BlockDetails = Omit<BlockDesc, 'inputs' | 'outputs' | 'implementation'>;
|
|
|
9
9
|
type TupleType = readonly (readonly [string, ZodType])[];
|
|
10
10
|
/**
|
|
11
11
|
* Defines a new block type with the specified configuration.
|
|
12
|
+
*
|
|
13
|
+
* Execution semantics: the engine passes `null` for an input pin
|
|
14
|
+
* whose value has not been set yet — e.g. on the first cycles after a
|
|
15
|
+
* link is created, before any value has flowed — or is `Null`, and the
|
|
16
|
+
* block reads it as `undefined`. While any input whose schema rejects
|
|
17
|
+
* `undefined` (a plain `z.number()`, say) is still unset, execution is
|
|
18
|
+
* skipped — a no-op, not a fault — and `execute` is not called. Wrap a
|
|
19
|
+
* pin's schema in `.optional()` or `.default(...)` to let the executor
|
|
20
|
+
* run without that pin (a default materializes as the argument value).
|
|
21
|
+
* A pin with a present but mistyped value still faults the block: only
|
|
22
|
+
* absence is tolerated.
|
|
23
|
+
*
|
|
12
24
|
* @param config - The block configuration, including description, input/output types, and execution logic.
|
|
13
25
|
* @returns A class that extends TypedBlock, which can be registered with the BlocksEngine.
|
|
14
26
|
*/
|
|
@@ -26,6 +38,15 @@ export declare function defineBlock<I extends TupleType, O extends TupleType>(co
|
|
|
26
38
|
readonly outputs: string[];
|
|
27
39
|
readonly outputTypes: InferType<O>;
|
|
28
40
|
executeImpl(inputs: InferType<I>): Promise<unknown[] | undefined>;
|
|
41
|
+
/**
|
|
42
|
+
* The pin kind of a Zod schema.
|
|
43
|
+
*
|
|
44
|
+
* `.optional()`, `.nullable()` and `.default(...)` take the kind of
|
|
45
|
+
* the schema they wrap. A literal, and a union whose members all
|
|
46
|
+
* have one kind (`z.null()` members aside, as with `.nullable()`),
|
|
47
|
+
* take that kind — so a union of string literals is a `'str'` pin.
|
|
48
|
+
* Any other schema throws.
|
|
49
|
+
*/
|
|
29
50
|
zodToKind(kind: ZodType | undefined): Kind;
|
|
30
51
|
};
|
|
31
52
|
register(engine: BlocksEngine): void;
|
|
@@ -44,6 +65,15 @@ export declare class TypedBlock<I extends TupleType, O extends TupleType> {
|
|
|
44
65
|
execute([..._inputs]: InferType<I>): Promise<unknown[] | undefined>;
|
|
45
66
|
static register(_engine: BlocksEngine): void;
|
|
46
67
|
executeImpl(inputs: InferType<I>): Promise<unknown[] | undefined>;
|
|
68
|
+
/**
|
|
69
|
+
* The pin kind of a Zod schema.
|
|
70
|
+
*
|
|
71
|
+
* `.optional()`, `.nullable()` and `.default(...)` take the kind of
|
|
72
|
+
* the schema they wrap. A literal, and a union whose members all
|
|
73
|
+
* have one kind (`z.null()` members aside, as with `.nullable()`),
|
|
74
|
+
* take that kind — so a union of string literals is a `'str'` pin.
|
|
75
|
+
* Any other schema throws.
|
|
76
|
+
*/
|
|
47
77
|
zodToKind(kind: ZodType | undefined): Kind;
|
|
48
78
|
}
|
|
49
79
|
export {};
|