@fractal-solutions/qflow 1.0.83 → 2.0.0-canary.4
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/CHANGELOG.md +107 -0
- package/LICENSE +21 -504
- package/MIGRATION.md +1130 -0
- package/README.md +1432 -823
- package/dist/agent/agent.d.ts +4 -22
- package/dist/agent/agent.js +4 -364
- package/dist/agent/base_agent.d.ts +8 -20
- package/dist/agent/base_agent.js +8 -205
- package/dist/agent/control_nodes.d.ts +61 -0
- package/dist/agent/control_nodes.js +164 -0
- package/dist/agent/engine.d.ts +45 -0
- package/dist/agent/engine.js +415 -0
- package/dist/agent/flow.d.ts +77 -0
- package/dist/agent/flow.js +148 -0
- package/dist/agent/index.d.ts +12 -0
- package/dist/agent/index.js +12 -0
- package/dist/agent/lpavrl_agent.d.ts +1 -2
- package/dist/agent/lpavrl_agent.js +2 -175
- package/dist/agent/ooda_agent.d.ts +1 -2
- package/dist/agent/ooda_agent.js +2 -164
- package/dist/agent/pema_agent.d.ts +1 -2
- package/dist/agent/pema_agent.js +2 -168
- package/dist/agent/raor_agent.d.ts +1 -2
- package/dist/agent/raor_agent.js +2 -161
- package/dist/agent/strategies.d.ts +126 -0
- package/dist/agent/strategies.js +159 -0
- package/dist/agent/tools.d.ts +1 -0
- package/dist/agent/tools.js +42 -24
- package/dist/approval.d.ts +42 -0
- package/dist/approval.js +86 -0
- package/dist/budget.d.ts +103 -0
- package/dist/budget.js +133 -0
- package/dist/bun_nodes.d.ts +119 -0
- package/dist/bun_nodes.js +331 -0
- package/dist/contracts.d.ts +30 -0
- package/dist/contracts.js +103 -0
- package/dist/durable.d.ts +278 -0
- package/dist/durable.js +730 -0
- package/dist/eval.d.ts +165 -0
- package/dist/eval.js +263 -0
- package/dist/graph.d.ts +157 -0
- package/dist/graph.js +330 -0
- package/dist/llm/index.d.ts +359 -0
- package/dist/llm/index.js +924 -0
- package/dist/logger.js +7 -3
- package/dist/mcp/client.d.ts +55 -0
- package/dist/mcp/client.js +145 -0
- package/dist/mcp/index.d.ts +2 -0
- package/dist/mcp/index.js +2 -0
- package/dist/mcp/server.d.ts +106 -0
- package/dist/mcp/server.js +154 -0
- package/dist/mcp/stdio.d.ts +2 -0
- package/dist/mcp/stdio.js +3 -0
- package/dist/memory.d.ts +101 -0
- package/dist/memory.js +217 -0
- package/dist/nodes/browser_control.js +5 -4
- package/dist/nodes/data_extractor.js +2 -1
- package/dist/nodes/data_validation.d.ts +3 -3
- package/dist/nodes/data_validation.js +19 -5
- package/dist/nodes/database.d.ts +2 -1
- package/dist/nodes/database.js +71 -58
- package/dist/nodes/gis.js +1 -1
- package/dist/nodes/git.d.ts +1 -1
- package/dist/nodes/git.js +65 -51
- package/dist/nodes/github.d.ts +1 -0
- package/dist/nodes/hardware_interaction.d.ts +2 -4
- package/dist/nodes/hardware_interaction.js +4 -3
- package/dist/nodes/http.d.ts +1 -7
- package/dist/nodes/http.js +46 -33
- package/dist/nodes/image_gallery.js +45 -45
- package/dist/nodes/index.d.ts +8 -0
- package/dist/nodes/index.js +8 -0
- package/dist/nodes/interactive_webview.d.ts +1 -2
- package/dist/nodes/interactive_webview.js +217 -216
- package/dist/nodes/multimedia_processing.js +1 -1
- package/dist/nodes/navigator.d.ts +7 -0
- package/dist/nodes/navigator.js +48 -8
- package/dist/nodes/pdf_processor.js +2 -1
- package/dist/nodes/remote_execution.js +2 -2
- package/dist/nodes/s3.d.ts +1 -0
- package/dist/nodes/scheduler.js +2 -2
- package/dist/nodes/search.d.ts +1 -1
- package/dist/nodes/search.js +3 -2
- package/dist/nodes/speech_synthesis.js +2 -1
- package/dist/nodes/spreadsheet.d.ts +1 -7
- package/dist/nodes/spreadsheet.js +2 -1
- package/dist/nodes/streaming_llm.d.ts +51 -0
- package/dist/nodes/streaming_llm.js +120 -0
- package/dist/nodes/webhook.d.ts +1 -5
- package/dist/nodes/webhook.js +106 -93
- package/dist/nodes/websockets.js +5 -3
- package/dist/nodes/webview.js +3 -2
- package/dist/optional.d.ts +32 -0
- package/dist/optional.js +61 -0
- package/dist/qflow.d.ts +25 -14
- package/dist/qflow.js +140 -49
- package/dist/schedule.d.ts +41 -0
- package/dist/schedule.js +149 -0
- package/dist/side_effects.d.ts +50 -0
- package/dist/side_effects.js +94 -0
- package/dist/streaming.d.ts +35 -0
- package/dist/streaming.js +199 -0
- package/dist/testing.d.ts +47 -0
- package/dist/testing.js +130 -0
- package/dist/tool_spec.d.ts +76 -0
- package/dist/tool_spec.js +321 -0
- package/dist/trace.d.ts +28 -0
- package/dist/trace.js +190 -0
- package/dist/util.d.ts +57 -0
- package/dist/util.js +122 -0
- package/package.json +153 -67
- package/qflow.config.js +18 -18
- package/scripts/postinstall.js +50 -0
- package/scripts/verify-package.js +114 -0
|
@@ -0,0 +1,331 @@
|
|
|
1
|
+
import { AsyncNode } from './qflow.js';
|
|
2
|
+
import { Database } from 'bun:sqlite';
|
|
3
|
+
async function streamText(stream) {
|
|
4
|
+
if (!stream)
|
|
5
|
+
return '';
|
|
6
|
+
if (typeof stream === 'string')
|
|
7
|
+
return stream;
|
|
8
|
+
const response = new Response(stream);
|
|
9
|
+
return await response.text();
|
|
10
|
+
}
|
|
11
|
+
/** Run a child process with Bun.spawn and capture stdout/stderr. */
|
|
12
|
+
export class BunSpawnNode extends AsyncNode {
|
|
13
|
+
static getToolDefinition() {
|
|
14
|
+
return {
|
|
15
|
+
name: 'bun_spawn',
|
|
16
|
+
description: 'Runs a command with Bun.spawn.',
|
|
17
|
+
parameters: {
|
|
18
|
+
type: 'object',
|
|
19
|
+
properties: {
|
|
20
|
+
command: { type: 'string', description: 'Executable to run.' },
|
|
21
|
+
args: { type: 'array', items: { type: 'string' }, description: 'Arguments for the executable.' },
|
|
22
|
+
cwd: { type: 'string' },
|
|
23
|
+
timeoutMs: { type: 'number' },
|
|
24
|
+
},
|
|
25
|
+
required: ['command'],
|
|
26
|
+
},
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
async prepAsync(shared = {}) {
|
|
30
|
+
const command = this.params.command ?? shared.command;
|
|
31
|
+
if (!command)
|
|
32
|
+
throw new Error('BunSpawnNode requires a command.');
|
|
33
|
+
return { command };
|
|
34
|
+
}
|
|
35
|
+
async execAsync(prepRes, shared = {}, observer = {}) {
|
|
36
|
+
if (!globalThis.Bun?.spawn)
|
|
37
|
+
throw new Error('BunSpawnNode requires the Bun runtime.');
|
|
38
|
+
const { command, args = [], cwd, env, input, timeoutMs } = this.params;
|
|
39
|
+
const proc = globalThis.Bun.spawn({
|
|
40
|
+
cmd: [command, ...(Array.isArray(args) ? args : [])],
|
|
41
|
+
cwd,
|
|
42
|
+
env: env ? { ...process.env, ...env } : undefined,
|
|
43
|
+
stdout: 'pipe',
|
|
44
|
+
stderr: 'pipe',
|
|
45
|
+
stdin: input == null ? 'ignore' : 'pipe',
|
|
46
|
+
});
|
|
47
|
+
if (input != null) {
|
|
48
|
+
proc.stdin.write(typeof input === 'string' ? input : JSON.stringify(input));
|
|
49
|
+
proc.stdin.end();
|
|
50
|
+
}
|
|
51
|
+
let timer = null;
|
|
52
|
+
try {
|
|
53
|
+
const work = (async () => {
|
|
54
|
+
const [stdout, stderr, exitCode] = await Promise.all([
|
|
55
|
+
streamText(proc.stdout),
|
|
56
|
+
streamText(proc.stderr),
|
|
57
|
+
proc.exited,
|
|
58
|
+
]);
|
|
59
|
+
return { exitCode, stdout, stderr };
|
|
60
|
+
})();
|
|
61
|
+
const result = timeoutMs
|
|
62
|
+
? await Promise.race([
|
|
63
|
+
work,
|
|
64
|
+
new Promise((_resolve, reject) => {
|
|
65
|
+
timer = setTimeout(() => {
|
|
66
|
+
proc.kill();
|
|
67
|
+
const error = new Error(`BunSpawnNode timed out after ${timeoutMs}ms.`);
|
|
68
|
+
error.name = 'TimeoutError';
|
|
69
|
+
reject(error);
|
|
70
|
+
}, timeoutMs);
|
|
71
|
+
}),
|
|
72
|
+
])
|
|
73
|
+
: await work;
|
|
74
|
+
observer.emit?.('spawn:exit', { command, args, exitCode: result.exitCode });
|
|
75
|
+
return result;
|
|
76
|
+
}
|
|
77
|
+
finally {
|
|
78
|
+
if (timer)
|
|
79
|
+
clearTimeout(timer);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
async postAsync(shared, prepRes, execRes) {
|
|
83
|
+
shared.spawnResult = execRes;
|
|
84
|
+
shared.spawnStdout = execRes.stdout;
|
|
85
|
+
shared.spawnStderr = execRes.stderr;
|
|
86
|
+
return Object.keys(this.successors).length ? 'default' : execRes;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
/** Query a SQLite database with bun:sqlite, with a cached per-shared handle. */
|
|
90
|
+
export class SQLiteQueryNode extends AsyncNode {
|
|
91
|
+
static getToolDefinition() {
|
|
92
|
+
return {
|
|
93
|
+
name: 'sqlite_query',
|
|
94
|
+
description: 'Runs a SQL statement against a bun:sqlite database.',
|
|
95
|
+
parameters: {
|
|
96
|
+
type: 'object',
|
|
97
|
+
properties: {
|
|
98
|
+
database: { type: 'string', description: 'SQLite filename or :memory:.' },
|
|
99
|
+
sql: { type: 'string', description: 'SQL statement.' },
|
|
100
|
+
params: { type: 'array', items: { type: 'any' } },
|
|
101
|
+
mode: { type: 'string', enum: ['all', 'get', 'run', 'exec'] },
|
|
102
|
+
},
|
|
103
|
+
required: ['database', 'sql'],
|
|
104
|
+
},
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
async prepAsync(shared = {}) {
|
|
108
|
+
const database = this.params.database ?? shared.sqliteDatabase ?? ':memory:';
|
|
109
|
+
const dbKey = this.params.dbKey ?? 'bunDb';
|
|
110
|
+
const db = database instanceof Database
|
|
111
|
+
? database
|
|
112
|
+
: shared[dbKey] instanceof Database
|
|
113
|
+
? shared[dbKey]
|
|
114
|
+
: new Database(database);
|
|
115
|
+
if (!(shared[dbKey] instanceof Database))
|
|
116
|
+
shared[dbKey] = db;
|
|
117
|
+
return { db };
|
|
118
|
+
}
|
|
119
|
+
async execAsync(prepRes) {
|
|
120
|
+
const sql = this.params.sql ?? this.params.query;
|
|
121
|
+
if (!sql)
|
|
122
|
+
throw new Error('SQLiteQueryNode requires `sql`.');
|
|
123
|
+
const values = this.params.params ?? [];
|
|
124
|
+
const mode = this.params.mode ?? 'all';
|
|
125
|
+
if (mode === 'exec') {
|
|
126
|
+
prepRes.db.exec(sql);
|
|
127
|
+
return { changes: 0 };
|
|
128
|
+
}
|
|
129
|
+
const statement = prepRes.db.prepare(sql);
|
|
130
|
+
if (mode === 'get')
|
|
131
|
+
return statement.get(...values);
|
|
132
|
+
if (mode === 'run') {
|
|
133
|
+
const info = statement.run(...values);
|
|
134
|
+
return { changes: info.changes, lastInsertRowid: String(info.lastInsertRowid) };
|
|
135
|
+
}
|
|
136
|
+
return statement.all(...values);
|
|
137
|
+
}
|
|
138
|
+
async postAsync(shared, prepRes, execRes) {
|
|
139
|
+
shared.sqliteResult = execRes;
|
|
140
|
+
return Object.keys(this.successors).length ? 'default' : execRes;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
/** Watch a path and collect file-system events. */
|
|
144
|
+
export class FileWatchNode extends AsyncNode {
|
|
145
|
+
constructor({ eventKey = 'fileEvents', maxEvents = Infinity, waitForEvent = false, timeoutMs = null } = {}) {
|
|
146
|
+
super();
|
|
147
|
+
this.eventKey = eventKey;
|
|
148
|
+
this.maxEvents = maxEvents;
|
|
149
|
+
this.waitForEvent = waitForEvent;
|
|
150
|
+
this.timeoutMs = timeoutMs;
|
|
151
|
+
this.events = [];
|
|
152
|
+
this.watcher = null;
|
|
153
|
+
}
|
|
154
|
+
async execAsync(prepRes, shared = {}, observer = {}) {
|
|
155
|
+
const target = this.params.path ?? shared.watchPath;
|
|
156
|
+
if (!target)
|
|
157
|
+
throw new Error('FileWatchNode requires a path.');
|
|
158
|
+
this.events = [];
|
|
159
|
+
let resolveFirst = null;
|
|
160
|
+
const firstEvent = new Promise(resolve => { resolveFirst = resolve; });
|
|
161
|
+
const record = (event, filename) => {
|
|
162
|
+
const entry = {
|
|
163
|
+
event: String(event),
|
|
164
|
+
filename: filename == null ? '' : String(filename),
|
|
165
|
+
path: target,
|
|
166
|
+
timestamp: Date.now(),
|
|
167
|
+
};
|
|
168
|
+
this.events.push(entry);
|
|
169
|
+
observer.emit?.('file:change', { ...entry, flowId: observer.flowId });
|
|
170
|
+
resolveFirst?.(entry);
|
|
171
|
+
if (this.events.length >= (this.params.maxEvents ?? this.maxEvents))
|
|
172
|
+
this.close();
|
|
173
|
+
};
|
|
174
|
+
const recursive = this.params.recursive ?? true;
|
|
175
|
+
let bunWatcher = null;
|
|
176
|
+
try {
|
|
177
|
+
bunWatcher = globalThis.Bun?.watch?.(target, { recursive }, (event, filename) => record(event, filename));
|
|
178
|
+
}
|
|
179
|
+
catch {
|
|
180
|
+
bunWatcher = null;
|
|
181
|
+
}
|
|
182
|
+
if (bunWatcher?.close) {
|
|
183
|
+
this.watcher = bunWatcher;
|
|
184
|
+
}
|
|
185
|
+
else {
|
|
186
|
+
const { watch } = await import('node:fs');
|
|
187
|
+
this.watcher = watch(target, { recursive }, (event, filename) => record(event, filename));
|
|
188
|
+
}
|
|
189
|
+
if (this.params.waitForEvent ?? this.waitForEvent) {
|
|
190
|
+
const timeoutMs = this.params.timeoutMs ?? this.timeoutMs;
|
|
191
|
+
if (!timeoutMs)
|
|
192
|
+
return await firstEvent;
|
|
193
|
+
let timer = null;
|
|
194
|
+
try {
|
|
195
|
+
return await Promise.race([
|
|
196
|
+
firstEvent,
|
|
197
|
+
new Promise((_resolve, reject) => {
|
|
198
|
+
timer = setTimeout(() => {
|
|
199
|
+
const error = new Error(`FileWatchNode timed out after ${timeoutMs}ms.`);
|
|
200
|
+
error.name = 'TimeoutError';
|
|
201
|
+
reject(error);
|
|
202
|
+
}, timeoutMs);
|
|
203
|
+
}),
|
|
204
|
+
]);
|
|
205
|
+
}
|
|
206
|
+
finally {
|
|
207
|
+
if (timer)
|
|
208
|
+
clearTimeout(timer);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
return { watching: true, path: target };
|
|
212
|
+
}
|
|
213
|
+
close() {
|
|
214
|
+
this.watcher?.close?.();
|
|
215
|
+
this.watcher = null;
|
|
216
|
+
}
|
|
217
|
+
async postAsync(shared, prepRes, execRes) {
|
|
218
|
+
shared[this.params.eventKey ?? this.eventKey] = this.events;
|
|
219
|
+
shared.fileWatchResult = execRes;
|
|
220
|
+
return Object.keys(this.successors).length ? 'default' : execRes;
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
async function readChunks(input) {
|
|
224
|
+
if (input && typeof input.getReader === 'function') {
|
|
225
|
+
const reader = input.getReader();
|
|
226
|
+
const chunks = [];
|
|
227
|
+
while (true) {
|
|
228
|
+
const { done, value } = await reader.read();
|
|
229
|
+
if (done)
|
|
230
|
+
break;
|
|
231
|
+
chunks.push(value);
|
|
232
|
+
}
|
|
233
|
+
reader.releaseLock?.();
|
|
234
|
+
return chunks;
|
|
235
|
+
}
|
|
236
|
+
if (Array.isArray(input))
|
|
237
|
+
return input;
|
|
238
|
+
return input == null ? [] : [input];
|
|
239
|
+
}
|
|
240
|
+
/** Compose Web Streams with map/filter/reduce/transform operations. */
|
|
241
|
+
export class StreamTransformNode extends AsyncNode {
|
|
242
|
+
constructor({ transform = null, mode = 'transform', outputKey = 'streamResult', initialValue = undefined } = {}) {
|
|
243
|
+
super();
|
|
244
|
+
this.transform = transform;
|
|
245
|
+
this.mode = mode;
|
|
246
|
+
this.outputKey = outputKey;
|
|
247
|
+
this.initialValue = initialValue;
|
|
248
|
+
}
|
|
249
|
+
async prepAsync(shared = {}) {
|
|
250
|
+
return this.params.input ?? shared.streamInput ?? shared.items ?? [];
|
|
251
|
+
}
|
|
252
|
+
async execAsync(chunks = [], shared = {}, observer = {}) {
|
|
253
|
+
const mode = this.params.mode ?? this.mode;
|
|
254
|
+
const transform = this.params.transform ?? this.transform;
|
|
255
|
+
const source = new ReadableStream({
|
|
256
|
+
start(controller) {
|
|
257
|
+
for (const chunk of chunks)
|
|
258
|
+
controller.enqueue(chunk);
|
|
259
|
+
controller.close();
|
|
260
|
+
},
|
|
261
|
+
});
|
|
262
|
+
let accumulator = this.params.initialValue ?? this.initialValue;
|
|
263
|
+
const transformer = new TransformStream({
|
|
264
|
+
async transform(chunk, controller) {
|
|
265
|
+
if (mode === 'filter') {
|
|
266
|
+
const keep = typeof transform === 'function' ? await transform(chunk) : Boolean(transform);
|
|
267
|
+
if (keep)
|
|
268
|
+
controller.enqueue(chunk);
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
271
|
+
if (mode === 'reduce') {
|
|
272
|
+
accumulator = typeof transform === 'function'
|
|
273
|
+
? await transform(accumulator, chunk)
|
|
274
|
+
: accumulator;
|
|
275
|
+
return;
|
|
276
|
+
}
|
|
277
|
+
const output = typeof transform === 'function' ? await transform(chunk) : chunk;
|
|
278
|
+
if (output === undefined)
|
|
279
|
+
return;
|
|
280
|
+
if (Array.isArray(output))
|
|
281
|
+
output.forEach(item => controller.enqueue(item));
|
|
282
|
+
else
|
|
283
|
+
controller.enqueue(output);
|
|
284
|
+
},
|
|
285
|
+
flush(controller) {
|
|
286
|
+
if (mode === 'reduce')
|
|
287
|
+
controller.enqueue(accumulator);
|
|
288
|
+
},
|
|
289
|
+
});
|
|
290
|
+
const reader = source.pipeThrough(transformer).getReader();
|
|
291
|
+
const items = [];
|
|
292
|
+
while (true) {
|
|
293
|
+
const { done, value } = await reader.read();
|
|
294
|
+
if (done)
|
|
295
|
+
break;
|
|
296
|
+
items.push(value);
|
|
297
|
+
observer.emit?.('stream:item', { value, index: items.length - 1 });
|
|
298
|
+
}
|
|
299
|
+
reader.releaseLock?.();
|
|
300
|
+
return {
|
|
301
|
+
items,
|
|
302
|
+
stream: new ReadableStream({
|
|
303
|
+
start(controller) {
|
|
304
|
+
for (const item of items)
|
|
305
|
+
controller.enqueue(item);
|
|
306
|
+
controller.close();
|
|
307
|
+
},
|
|
308
|
+
}),
|
|
309
|
+
};
|
|
310
|
+
}
|
|
311
|
+
async postAsync(shared, prepRes, execRes) {
|
|
312
|
+
shared[this.outputKey] = execRes.items;
|
|
313
|
+
shared[this.params.streamKey ?? 'stream'] = execRes.stream;
|
|
314
|
+
return Object.keys(this.successors).length ? 'default' : execRes;
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
export class StreamMapNode extends StreamTransformNode {
|
|
318
|
+
constructor(options = {}) {
|
|
319
|
+
super({ ...options, mode: 'map' });
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
export class StreamFilterNode extends StreamTransformNode {
|
|
323
|
+
constructor(options = {}) {
|
|
324
|
+
super({ ...options, mode: 'filter' });
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
export class StreamReduceNode extends StreamTransformNode {
|
|
328
|
+
constructor(options = {}) {
|
|
329
|
+
super({ ...options, mode: 'reduce' });
|
|
330
|
+
}
|
|
331
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
export function defineState(spec: any): StateContract;
|
|
2
|
+
export function validateState(shared: any, contract: any, options?: {}): {
|
|
3
|
+
valid: boolean;
|
|
4
|
+
errors: any[];
|
|
5
|
+
};
|
|
6
|
+
export function assertState(shared: any, contract: any, options?: {}): any;
|
|
7
|
+
export class StateContract {
|
|
8
|
+
constructor({ name, fields, strict, validator, validate }?: {
|
|
9
|
+
name?: string | undefined;
|
|
10
|
+
fields?: {} | undefined;
|
|
11
|
+
strict?: boolean | undefined;
|
|
12
|
+
validator?: null | undefined;
|
|
13
|
+
validate?: null | undefined;
|
|
14
|
+
});
|
|
15
|
+
name: string;
|
|
16
|
+
fields: {};
|
|
17
|
+
strict: boolean;
|
|
18
|
+
customValidator: any;
|
|
19
|
+
validate(shared?: {}, { phase, throwOnError }?: {
|
|
20
|
+
phase?: string | undefined;
|
|
21
|
+
throwOnError?: boolean | undefined;
|
|
22
|
+
}): {
|
|
23
|
+
valid: boolean;
|
|
24
|
+
errors: any[];
|
|
25
|
+
};
|
|
26
|
+
assert(shared: any, options?: {}): {
|
|
27
|
+
valid: boolean;
|
|
28
|
+
errors: any[];
|
|
29
|
+
};
|
|
30
|
+
}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Lightweight typed shared-state contracts for graph nodes.
|
|
3
|
+
*
|
|
4
|
+
* Contracts are intentionally JSON-compatible so they can be generated from
|
|
5
|
+
* visual tooling. They are validated at node boundaries, not on every write.
|
|
6
|
+
*/
|
|
7
|
+
function typeOf(value) {
|
|
8
|
+
if (value === null)
|
|
9
|
+
return 'null';
|
|
10
|
+
if (Array.isArray(value))
|
|
11
|
+
return 'array';
|
|
12
|
+
return typeof value;
|
|
13
|
+
}
|
|
14
|
+
function matchesType(value, expected) {
|
|
15
|
+
if (!expected || expected === 'any')
|
|
16
|
+
return true;
|
|
17
|
+
const actual = typeOf(value);
|
|
18
|
+
if (Array.isArray(expected))
|
|
19
|
+
return expected.includes(actual);
|
|
20
|
+
return expected === 'object' ? actual === 'object' : actual === expected;
|
|
21
|
+
}
|
|
22
|
+
export class StateContract {
|
|
23
|
+
constructor({ name = 'State', fields = {}, strict = false, validator = null, validate = null } = {}) {
|
|
24
|
+
this.name = name;
|
|
25
|
+
this.fields = { ...fields };
|
|
26
|
+
this.strict = strict;
|
|
27
|
+
// Keep the method named `validate`; a custom validator lives separately so
|
|
28
|
+
// it cannot shadow the public API.
|
|
29
|
+
this.customValidator = validator ?? validate;
|
|
30
|
+
}
|
|
31
|
+
validate(shared = {}, { phase = 'input', throwOnError = false } = {}) {
|
|
32
|
+
const errors = [];
|
|
33
|
+
const value = shared ?? {};
|
|
34
|
+
for (const [key, spec] of Object.entries(this.fields)) {
|
|
35
|
+
const fieldSpec = typeof spec === 'string' ? { type: spec } : spec ?? {};
|
|
36
|
+
const present = Object.prototype.hasOwnProperty.call(value, key);
|
|
37
|
+
const fieldValue = value[key];
|
|
38
|
+
if (!present || fieldValue === undefined) {
|
|
39
|
+
if (fieldSpec.required)
|
|
40
|
+
errors.push(`${this.name}.${key} is required (${phase}).`);
|
|
41
|
+
continue;
|
|
42
|
+
}
|
|
43
|
+
if (!matchesType(fieldValue, fieldSpec.type)) {
|
|
44
|
+
errors.push(`${this.name}.${key} must be ${fieldSpec.type}, received ${typeOf(fieldValue)} (${phase}).`);
|
|
45
|
+
continue;
|
|
46
|
+
}
|
|
47
|
+
if (fieldSpec.enum && !fieldSpec.enum.includes(fieldValue)) {
|
|
48
|
+
errors.push(`${this.name}.${key} must be one of ${fieldSpec.enum.join(', ')} (${phase}).`);
|
|
49
|
+
}
|
|
50
|
+
if (typeof fieldSpec.validate === 'function') {
|
|
51
|
+
const result = fieldSpec.validate(fieldValue, value);
|
|
52
|
+
if (result === false)
|
|
53
|
+
errors.push(`${this.name}.${key} failed validation (${phase}).`);
|
|
54
|
+
if (typeof result === 'string')
|
|
55
|
+
errors.push(`${this.name}.${key}: ${result} (${phase}).`);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
if (this.strict) {
|
|
59
|
+
for (const key of Object.keys(value)) {
|
|
60
|
+
if (!Object.prototype.hasOwnProperty.call(this.fields, key)) {
|
|
61
|
+
errors.push(`${this.name}.${key} is not declared in a strict contract (${phase}).`);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
if (typeof this.customValidator === 'function') {
|
|
66
|
+
const result = this.customValidator(value, { phase });
|
|
67
|
+
if (Array.isArray(result))
|
|
68
|
+
errors.push(...result);
|
|
69
|
+
else if (result === false)
|
|
70
|
+
errors.push(`${this.name} failed validation (${phase}).`);
|
|
71
|
+
else if (typeof result === 'string')
|
|
72
|
+
errors.push(`${this.name}: ${result} (${phase}).`);
|
|
73
|
+
}
|
|
74
|
+
if (throwOnError && errors.length) {
|
|
75
|
+
const error = new Error(errors.join('; '));
|
|
76
|
+
error.name = 'StateContractError';
|
|
77
|
+
error.errors = errors;
|
|
78
|
+
throw error;
|
|
79
|
+
}
|
|
80
|
+
return { valid: errors.length === 0, errors };
|
|
81
|
+
}
|
|
82
|
+
assert(shared, options = {}) {
|
|
83
|
+
return this.validate(shared, { ...options, throwOnError: true });
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
export function defineState(spec) {
|
|
87
|
+
return new StateContract(spec);
|
|
88
|
+
}
|
|
89
|
+
export function validateState(shared, contract, options = {}) {
|
|
90
|
+
if (!contract)
|
|
91
|
+
return { valid: true, errors: [] };
|
|
92
|
+
if (typeof contract.validate === 'function' && contract instanceof StateContract) {
|
|
93
|
+
return contract.validate(shared, options);
|
|
94
|
+
}
|
|
95
|
+
return new StateContract(contract).validate(shared, options);
|
|
96
|
+
}
|
|
97
|
+
export function assertState(shared, contract, options = {}) {
|
|
98
|
+
if (!contract)
|
|
99
|
+
return { valid: true, errors: [] };
|
|
100
|
+
if (typeof contract.assert === 'function')
|
|
101
|
+
return contract.assert(shared, options);
|
|
102
|
+
return new StateContract(contract).assert(shared, options);
|
|
103
|
+
}
|