@n3rdw1z4rd/core 0.20.0 → 0.22.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.
Files changed (44) hide show
  1. package/dist/graph/doc.d.ts +141 -0
  2. package/dist/graph/doc.js +173 -0
  3. package/dist/graph/evaluate.d.ts +114 -0
  4. package/dist/graph/evaluate.js +319 -0
  5. package/dist/graph/index.d.ts +9 -0
  6. package/dist/graph/index.js +9 -0
  7. package/dist/graph/node.d.ts +153 -0
  8. package/dist/graph/node.js +94 -0
  9. package/dist/graph/nodes.d.ts +11 -0
  10. package/dist/graph/nodes.js +399 -0
  11. package/dist/graph/script.d.ts +64 -0
  12. package/dist/graph/script.js +111 -0
  13. package/dist/graph/sources.d.ts +11 -0
  14. package/dist/graph/sources.js +263 -0
  15. package/dist/graph/subgraph.d.ts +36 -0
  16. package/dist/graph/subgraph.js +280 -0
  17. package/dist/graph/types.d.ts +56 -0
  18. package/dist/graph/types.js +67 -0
  19. package/dist/graph.cjs +1723 -0
  20. package/dist/graph.d.cts +576 -0
  21. package/dist/index.cjs +53 -52
  22. package/dist/rng-Dhqq7owV.cjs +642 -0
  23. package/dist/{spatial-partition-3d-Ba-VBveM.cjs → spatial-partition-3d-CmSCL87Z.cjs} +19 -660
  24. package/dist/three/adaptive-grid.d.ts +43 -0
  25. package/dist/three/adaptive-grid.js +127 -0
  26. package/dist/three/ecs.d.ts +5 -3
  27. package/dist/three/ecs.js +5 -3
  28. package/dist/three/editor-camera.d.ts +93 -0
  29. package/dist/three/editor-camera.js +174 -0
  30. package/dist/three/index.d.ts +6 -1
  31. package/dist/three/index.js +6 -1
  32. package/dist/three/picking.d.ts +34 -0
  33. package/dist/three/picking.js +59 -0
  34. package/dist/three/schema.d.ts +139 -0
  35. package/dist/three/schema.js +214 -0
  36. package/dist/three/world.d.ts +192 -0
  37. package/dist/three/world.js +363 -0
  38. package/dist/three.cjs +970 -23
  39. package/dist/three.d.cts +497 -5
  40. package/dist/vite.cjs +40 -0
  41. package/dist/vite.d.cts +35 -0
  42. package/dist/vite.d.ts +35 -0
  43. package/dist/vite.js +39 -0
  44. package/package.json +21 -1
package/dist/graph.cjs ADDED
@@ -0,0 +1,1723 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_rng = require("./rng-Dhqq7owV.cjs");
3
+ //#region src/graph/types.ts
4
+ /** @category Graph */
5
+ function parseType(type) {
6
+ const t = type.trim();
7
+ return t.endsWith("[]") ? {
8
+ base: t.slice(0, -2).trim(),
9
+ list: true
10
+ } : {
11
+ base: t,
12
+ list: false
13
+ };
14
+ }
15
+ /**
16
+ * Known pin types and which connect to which.
17
+ *
18
+ * @category Graph
19
+ */
20
+ var TypeRegistry = class {
21
+ types = /* @__PURE__ */ new Map();
22
+ constructor() {
23
+ this.define("any", "#9a9a9a");
24
+ }
25
+ define(name, color, options = {}) {
26
+ const def = {
27
+ name,
28
+ color,
29
+ accepts: options.accepts ?? []
30
+ };
31
+ this.types.set(name, def);
32
+ return def;
33
+ }
34
+ get(name) {
35
+ return this.types.get(parseType(name).base);
36
+ }
37
+ /** The color for a type (unknown types get `any`'s). */
38
+ color(name) {
39
+ return (this.get(name) ?? this.types.get("any")).color;
40
+ }
41
+ /**
42
+ * Whether an output of type `from` may connect to an input of type `to`. List-ness never
43
+ * blocks a connection: one value into a list port becomes a one-item list, and a list
44
+ * into a single-value port broadcasts.
45
+ */
46
+ canConnect(from, to) {
47
+ const a = parseType(from).base;
48
+ const b = parseType(to).base;
49
+ if (a === b || a === "any" || b === "any") return true;
50
+ return this.types.get(b)?.accepts.includes(a) ?? false;
51
+ }
52
+ all() {
53
+ return [...this.types.values()];
54
+ }
55
+ };
56
+ /**
57
+ * The default pin types (colors match the apparatus palette).
58
+ *
59
+ * @category Graph
60
+ */
61
+ const portTypes = new TypeRegistry();
62
+ portTypes.define("number", "#3fd1a4");
63
+ portTypes.define("boolean", "#e8554e");
64
+ portTypes.define("string", "#e86fb0");
65
+ portTypes.define("color", "#f2a541");
66
+ portTypes.define("vec2", "#4ea8de");
67
+ portTypes.define("vec3", "#9b6dde");
68
+ //#endregion
69
+ //#region src/graph/doc.ts
70
+ /**
71
+ * The graph document: plain JSON, saved and shared as-is.
72
+ *
73
+ * ```json
74
+ * {
75
+ * "format": "n3rdw1z4rd.graph", "version": 1,
76
+ * "nodes": [{ "id": "a1", "type": "list/grid2d", "pos": [0, 0], "values": { "cols": 14 } }],
77
+ * "links": [{ "id": "l1", "from": { "node": "a1", "port": "points" }, "to": { "node": "b2", "port": "at" } }],
78
+ * "scripts": { "my/ball": "export const inputs = …" }
79
+ * }
80
+ * ```
81
+ *
82
+ * `values` holds the node's params and the values of its unconnected inputs; `scripts` holds
83
+ * the source of the script node types the graph uses, so a graph file is self-contained.
84
+ *
85
+ * @module
86
+ */
87
+ const GRAPH_FORMAT = "n3rdw1z4rd.graph";
88
+ const GRAPH_VERSION = 1;
89
+ /** @category Graph */
90
+ function createGraph() {
91
+ return {
92
+ format: GRAPH_FORMAT,
93
+ version: 1,
94
+ nodes: [],
95
+ links: []
96
+ };
97
+ }
98
+ let idCounter = 0;
99
+ /** A short id, unique within a graph (random part + counter). @category Graph */
100
+ function graphId(prefix = "n") {
101
+ return `${prefix}${Math.random().toString(36).slice(2, 7)}${(idCounter++).toString(36)}`;
102
+ }
103
+ /** Checks a parsed JSON value is a graph document and fills in missing optional parts. @category Graph */
104
+ function normalizeGraph(raw) {
105
+ const g = raw;
106
+ if (!g || g.format !== "n3rdw1z4rd.graph") throw new Error("not a graph document");
107
+ if (typeof g.version !== "number" || g.version > 1) throw new Error(`unsupported graph version ${g.version}`);
108
+ const nodes = (Array.isArray(g.nodes) ? g.nodes : []).filter((n) => !!n && typeof n.id === "string" && typeof n.type === "string").map((n) => ({
109
+ ...n,
110
+ pos: Array.isArray(n.pos) ? [Number(n.pos[0]) || 0, Number(n.pos[1]) || 0] : [0, 0],
111
+ values: n.values && typeof n.values === "object" ? n.values : {}
112
+ }));
113
+ const ids = new Set(nodes.map((n) => n.id));
114
+ const links = (Array.isArray(g.links) ? g.links : []).filter((l) => !!l && typeof l.id === "string" && ids.has(l.from?.node) && ids.has(l.to?.node) && typeof l.from.port === "string" && typeof l.to.port === "string");
115
+ const groups = (Array.isArray(g.groups) ? g.groups : []).filter((gr) => !!gr && typeof gr.id === "string" && Array.isArray(gr.rect) && gr.rect.length === 4 && gr.rect.every((v) => Number.isFinite(v))).map((gr) => ({
116
+ id: gr.id,
117
+ title: String(gr.title ?? "group"),
118
+ color: String(gr.color ?? "#3a3a3a"),
119
+ rect: [...gr.rect]
120
+ }));
121
+ return {
122
+ ...g,
123
+ format: GRAPH_FORMAT,
124
+ version: 1,
125
+ nodes,
126
+ links,
127
+ ...groups.length ? { groups } : { groups: void 0 }
128
+ };
129
+ }
130
+ /** @category Graph */
131
+ function getNode(doc, id) {
132
+ return doc.nodes.find((n) => n.id === id);
133
+ }
134
+ /** The link into an input, if any (the first, for a multi input). @category Graph */
135
+ function linkInto(doc, node, port) {
136
+ return doc.links.find((l) => l.to.node === node && l.to.port === port);
137
+ }
138
+ /** Every link into an input, in the order they were made. @category Graph */
139
+ function linksInto(doc, node, port) {
140
+ return doc.links.filter((l) => l.to.node === node && l.to.port === port);
141
+ }
142
+ /** Adds a node of `def`'s type with its default values. @category Graph */
143
+ function addNode(doc, def, pos = [0, 0], values = {}) {
144
+ const node = {
145
+ id: graphId(),
146
+ type: def.type,
147
+ pos: [pos[0], pos[1]],
148
+ values: {}
149
+ };
150
+ for (const p of def.params) if (p.default !== void 0) node.values[p.name] = clone(p.default);
151
+ for (const p of def.inputs) if (p.default !== void 0) node.values[p.name] = clone(p.default);
152
+ Object.assign(node.values, clone(values));
153
+ doc.nodes.push(node);
154
+ return node;
155
+ }
156
+ /** Removes a node and every link to or from it. @category Graph */
157
+ function removeNode(doc, id) {
158
+ doc.nodes = doc.nodes.filter((n) => n.id !== id);
159
+ doc.links = doc.links.filter((l) => l.from.node !== id && l.to.node !== id);
160
+ }
161
+ /**
162
+ * Whether `from` (an output) may connect to `to` (an input): both exist, the types fit,
163
+ * and it wouldn't make a cycle. An input's existing link doesn't block (it gets replaced).
164
+ *
165
+ * @category Graph
166
+ */
167
+ function canConnect(doc, registry, from, to, types = portTypes) {
168
+ const a = getNode(doc, from.node);
169
+ const b = getNode(doc, to.node);
170
+ if (!a || !b) return {
171
+ ok: false,
172
+ reason: "no such node"
173
+ };
174
+ if (a.id === b.id) return {
175
+ ok: false,
176
+ reason: "a node can’t connect to itself"
177
+ };
178
+ const out = registry.get(a.type)?.outputs.find((p) => p.name === from.port);
179
+ const inp = registry.get(b.type)?.inputs.find((p) => p.name === to.port);
180
+ if (!out) return {
181
+ ok: false,
182
+ reason: `no output "${from.port}"`
183
+ };
184
+ if (!inp) return {
185
+ ok: false,
186
+ reason: `no input "${to.port}"`
187
+ };
188
+ if (!types.canConnect(out.type, inp.type)) return {
189
+ ok: false,
190
+ reason: `${out.type} doesn’t fit ${inp.type}`
191
+ };
192
+ if (reaches(doc, b.id, a.id)) return {
193
+ ok: false,
194
+ reason: "that would make a loop"
195
+ };
196
+ return { ok: true };
197
+ }
198
+ /**
199
+ * Connects an output to an input; throws if it can't. A plain input's existing link is
200
+ * replaced; a multi input keeps its links and adds this one (an identical link isn't doubled).
201
+ *
202
+ * @category Graph
203
+ */
204
+ function connect(doc, registry, from, to, types = portTypes) {
205
+ const check = canConnect(doc, registry, from, to, types);
206
+ if (!check.ok) throw new Error(check.reason);
207
+ const multi = registry.get(getNode(doc, to.node).type)?.inputs.find((p) => p.name === to.port)?.multi;
208
+ const same = doc.links.find((l) => l.to.node === to.node && l.to.port === to.port && l.from.node === from.node && l.from.port === from.port);
209
+ if (multi && same) return same;
210
+ if (!multi) doc.links = doc.links.filter((l) => !(l.to.node === to.node && l.to.port === to.port));
211
+ const link = {
212
+ id: graphId("l"),
213
+ from: { ...from },
214
+ to: { ...to }
215
+ };
216
+ doc.links.push(link);
217
+ return link;
218
+ }
219
+ /** @category Graph */
220
+ function disconnect(doc, linkId) {
221
+ doc.links = doc.links.filter((l) => l.id !== linkId);
222
+ }
223
+ /** Whether following links downstream from `start` reaches `target`. */
224
+ function reaches(doc, start, target) {
225
+ const seen = /* @__PURE__ */ new Set();
226
+ const stack = [start];
227
+ while (stack.length) {
228
+ const id = stack.pop();
229
+ if (id === target) return true;
230
+ if (seen.has(id)) continue;
231
+ seen.add(id);
232
+ for (const l of doc.links) if (l.from.node === id) stack.push(l.to.node);
233
+ }
234
+ return false;
235
+ }
236
+ function clone(v) {
237
+ return v !== null && typeof v === "object" ? structuredClone(v) : v;
238
+ }
239
+ //#endregion
240
+ //#region src/graph/evaluate.ts
241
+ /**
242
+ * Evaluates a graph: runs the nodes the outputs depend on, in dependency order, passing
243
+ * values along the links.
244
+ *
245
+ * - **Lazy:** only output nodes (`output: true`) and what they depend on run, unless you
246
+ * name other targets.
247
+ * - **Memoized:** a node re-runs only when its params / input values, an upstream result or
248
+ * its type changed since the last evaluation; otherwise its previous outputs are reused.
249
+ * - **List broadcasting:** a list wired into a single-value input runs the node once per
250
+ * item (several lists: longest wins, shorter ones repeat their last item) and every
251
+ * output becomes a list. A list port (`vec2[]`) takes the whole list instead; one value
252
+ * wired into it arrives as a one-item list. A list output of a broadcast node is
253
+ * flattened into the result list.
254
+ * - **Animation (optional):** a node with `animate` on (per node, or its type's default)
255
+ * re-runs on every evaluation that passes a new `frame`, and so does everything downstream
256
+ * of it; the rest stays cached. {@link GraphEvaluator.animated} tells the host whether any
257
+ * output depends on an animated node — if not, there's nothing to re-evaluate per frame.
258
+ * - **Disabled nodes** (`GraphNode.disabled`) don't run; downstream they count as failed
259
+ * (blocked, or left out of a multi input).
260
+ * - **Errors stay local:** a throwing node gets an `error`; nodes downstream of it are
261
+ * `blocked` (skipped) and don't run; the rest of the graph still evaluates. A **multi**
262
+ * input leaves failed sources out instead (listed in `skipped`), so one broken branch
263
+ * doesn't take down everything it feeds into.
264
+ *
265
+ * Nodes must treat their inputs as read-only: values are shared with upstream caches.
266
+ *
267
+ * @category Graph
268
+ */
269
+ var GraphEvaluator = class {
270
+ registry;
271
+ cache = /* @__PURE__ */ new Map();
272
+ stamp = 0;
273
+ constructor(registry) {
274
+ this.registry = registry;
275
+ }
276
+ /** The last result of a node. */
277
+ result(nodeId) {
278
+ return this.cache.get(nodeId);
279
+ }
280
+ /** Forgets cached results (all, or one node's), so they re-run next time. */
281
+ invalidate(nodeId) {
282
+ if (nodeId === void 0) this.cache.clear();
283
+ else this.cache.delete(nodeId);
284
+ }
285
+ /** The animated nodes the outputs (or `targets`) depend on; empty: no need to evaluate per frame. */
286
+ animated(doc, targets) {
287
+ const { order } = this.order(doc, targets ?? this.defaultTargets(doc));
288
+ return order.filter((id) => {
289
+ const node = getNode(doc, id);
290
+ return !node.disabled && (node.animate ?? this.registry.get(node.type)?.animate ?? false);
291
+ });
292
+ }
293
+ async evaluate(doc, options = {}) {
294
+ const env = options.env ?? {};
295
+ const frame = options.frame ?? {
296
+ time: 0,
297
+ dt: 0,
298
+ frame: 0
299
+ };
300
+ const scope = options.scope ? `${options.scope}/` : "";
301
+ const targets = options.targets ?? this.defaultTargets(doc);
302
+ const { order, cyclic } = this.order(doc, targets);
303
+ const ran = [];
304
+ const results = /* @__PURE__ */ new Map();
305
+ for (const id of order) {
306
+ const node = getNode(doc, id);
307
+ const def = this.registry.get(node.type);
308
+ if (!def) {
309
+ results.set(id, this.store(id, "", fail(`unknown node type "${node.type}"`)));
310
+ continue;
311
+ }
312
+ if (cyclic.has(id)) {
313
+ results.set(id, this.store(id, "", fail("part of a loop")));
314
+ continue;
315
+ }
316
+ if (node.disabled) {
317
+ results.set(id, this.store(id, "", {
318
+ outputs: {},
319
+ lists: {},
320
+ disabled: true,
321
+ ms: 0
322
+ }));
323
+ continue;
324
+ }
325
+ const values = {};
326
+ const isList = {};
327
+ const keyParts = [def.type, def.revision];
328
+ if (node.animate ?? def.animate) keyParts.push([
329
+ "frame",
330
+ frame.frame,
331
+ frame.time
332
+ ]);
333
+ let blocked;
334
+ let missing;
335
+ const skipped = [];
336
+ for (const p of def.inputs) {
337
+ const links = linksInto(doc, id, p.name);
338
+ const external = options.externals?.get(`${id}:${p.name}`);
339
+ if (!links.length && external?.length) {
340
+ keyParts.push([
341
+ p.name,
342
+ "external",
343
+ options.externalsStamp ?? 0
344
+ ]);
345
+ if (p.multi) {
346
+ values[p.name] = external.flatMap((x) => x.list ? x.value : x.value === void 0 ? [] : [x.value]);
347
+ isList[p.name] = true;
348
+ } else {
349
+ values[p.name] = external[0].value;
350
+ isList[p.name] = external[0].list;
351
+ }
352
+ } else if (links.length) {
353
+ const gathered = [];
354
+ for (const link of p.multi ? links : links.slice(0, 1)) {
355
+ const src = results.get(link.from.node);
356
+ if (!src || src.error || src.blocked || src.disabled) {
357
+ if (p.multi) skipped.push(link.from.node);
358
+ else blocked ??= link.from.node;
359
+ keyParts.push([
360
+ p.name,
361
+ link.from.node,
362
+ "failed"
363
+ ]);
364
+ continue;
365
+ }
366
+ const v = src.outputs[link.from.port];
367
+ const list = !!src.lists[link.from.port];
368
+ keyParts.push([
369
+ p.name,
370
+ link.from.node,
371
+ src.stamp,
372
+ link.from.port
373
+ ]);
374
+ if (!p.multi) {
375
+ values[p.name] = v;
376
+ isList[p.name] = list;
377
+ } else if (list) gathered.push(...v);
378
+ else if (v !== void 0) gathered.push(v);
379
+ }
380
+ if (p.multi) {
381
+ values[p.name] = gathered;
382
+ isList[p.name] = true;
383
+ }
384
+ } else {
385
+ const v = node.values[p.name] ?? p.default;
386
+ values[p.name] = v;
387
+ isList[p.name] = p.list && Array.isArray(v);
388
+ keyParts.push([p.name, v]);
389
+ if (v === void 0 && !p.optional) missing ??= p.name;
390
+ }
391
+ }
392
+ if (blocked) {
393
+ results.set(id, this.store(id, "", {
394
+ ...fail(""),
395
+ error: void 0,
396
+ blocked
397
+ }));
398
+ continue;
399
+ }
400
+ if (missing) {
401
+ results.set(id, this.store(id, "", fail(`input "${missing}" needs a value or a link`)));
402
+ continue;
403
+ }
404
+ const params = {};
405
+ for (const p of def.params) params[p.name] = node.values[p.name] ?? p.default;
406
+ keyParts.push(params);
407
+ const key = safeKey(keyParts);
408
+ const prev = this.cache.get(id);
409
+ if (prev && key && prev.key === key && !prev.error) {
410
+ results.set(id, prev);
411
+ continue;
412
+ }
413
+ const res = await this.run(def, scope + id, values, isList, params, env, frame);
414
+ if (skipped.length) res.skipped = skipped;
415
+ ran.push(id);
416
+ results.set(id, this.store(id, key, res));
417
+ }
418
+ for (const id of [...this.cache.keys()]) if (!getNode(doc, id)) this.cache.delete(id);
419
+ return {
420
+ order,
421
+ ran,
422
+ results
423
+ };
424
+ }
425
+ defaultTargets(doc) {
426
+ const outputs = doc.nodes.filter((n) => this.registry.get(n.type)?.output).map((n) => n.id);
427
+ return outputs.length ? outputs : doc.nodes.map((n) => n.id);
428
+ }
429
+ /** Dependency order (upstream first) of the targets and everything they depend on. */
430
+ order(doc, targets) {
431
+ const order = [];
432
+ const done = /* @__PURE__ */ new Set();
433
+ const active = /* @__PURE__ */ new Set();
434
+ const cyclic = /* @__PURE__ */ new Set();
435
+ const visit = (id) => {
436
+ if (done.has(id)) return;
437
+ if (active.has(id)) {
438
+ for (const a of active) cyclic.add(a);
439
+ return;
440
+ }
441
+ if (!getNode(doc, id)) return;
442
+ active.add(id);
443
+ for (const l of doc.links) if (l.to.node === id) visit(l.from.node);
444
+ active.delete(id);
445
+ done.add(id);
446
+ order.push(id);
447
+ };
448
+ for (const t of targets) visit(t);
449
+ return {
450
+ order,
451
+ cyclic
452
+ };
453
+ }
454
+ async run(def, nodeId, values, isList, params, env, frame) {
455
+ const t0 = now();
456
+ const broadcast = [];
457
+ for (const p of def.inputs) if (p.list) {
458
+ if (!isList[p.name]) values[p.name] = values[p.name] === void 0 ? [] : [values[p.name]];
459
+ } else if (isList[p.name]) broadcast.push(p);
460
+ const outputs = {};
461
+ const lists = {};
462
+ try {
463
+ if (broadcast.length === 0) {
464
+ const r = await def.run(values, params, {
465
+ nodeId,
466
+ type: def.type,
467
+ source: def.source,
468
+ index: 0,
469
+ count: 1,
470
+ env,
471
+ ...frame
472
+ }) ?? {};
473
+ const said = r[OUTPUT_LISTS];
474
+ for (const o of def.outputs) {
475
+ outputs[o.name] = r[o.name];
476
+ lists[o.name] = said?.[o.name] ?? o.list;
477
+ }
478
+ } else {
479
+ const lens = broadcast.map((p) => values[p.name].length);
480
+ const count = lens.some((n) => n === 0) ? 0 : Math.max(...lens);
481
+ for (const o of def.outputs) {
482
+ outputs[o.name] = [];
483
+ lists[o.name] = true;
484
+ }
485
+ for (let i = 0; i < count; i++) {
486
+ const args = { ...values };
487
+ broadcast.forEach((p, k) => {
488
+ const list = values[p.name];
489
+ args[p.name] = list[Math.min(i, lens[k] - 1)];
490
+ });
491
+ const r = await def.run(args, params, {
492
+ nodeId,
493
+ type: def.type,
494
+ source: def.source,
495
+ index: i,
496
+ count,
497
+ env,
498
+ ...frame
499
+ }) ?? {};
500
+ for (const o of def.outputs) {
501
+ const v = r[o.name];
502
+ if (o.list && Array.isArray(v)) outputs[o.name].push(...v);
503
+ else outputs[o.name].push(v);
504
+ }
505
+ }
506
+ }
507
+ } catch (err) {
508
+ return {
509
+ ...fail(describe(err)),
510
+ ms: now() - t0
511
+ };
512
+ }
513
+ return {
514
+ outputs,
515
+ lists,
516
+ ms: now() - t0
517
+ };
518
+ }
519
+ store(id, key, res) {
520
+ const r = {
521
+ ...res,
522
+ stamp: ++this.stamp,
523
+ key
524
+ };
525
+ this.cache.set(id, r);
526
+ return r;
527
+ }
528
+ };
529
+ /**
530
+ * A key a node's `run` may add to its result: `{ [OUTPUT_LISTS]: { out: true } }` marks outputs
531
+ * as lists regardless of their declared type.
532
+ *
533
+ * @category Graph
534
+ */
535
+ const OUTPUT_LISTS = "__lists";
536
+ function fail(error) {
537
+ return {
538
+ outputs: {},
539
+ lists: {},
540
+ error,
541
+ ms: 0
542
+ };
543
+ }
544
+ function describe(err) {
545
+ return err instanceof Error ? `${err.name}: ${err.message}` : String(err);
546
+ }
547
+ /** A cache key; '' (never matches) if something in it can't be serialized. */
548
+ function safeKey(parts) {
549
+ try {
550
+ return JSON.stringify(parts);
551
+ } catch {
552
+ return "";
553
+ }
554
+ }
555
+ const now = () => typeof performance !== "undefined" ? performance.now() : Date.now();
556
+ //#endregion
557
+ //#region src/graph/node.ts
558
+ let revisionCounter = 0;
559
+ function port(name, spec) {
560
+ const s = typeof spec === "string" ? { type: spec } : spec;
561
+ if (typeof s.type !== "string" || !s.type.trim()) throw new Error(`port "${name}": missing type`);
562
+ const parsed = parseType(s.type);
563
+ const multi = !!s.multi;
564
+ if (multi && !parsed.list) throw new Error(`port "${name}": only list ports (type[]) can be multi`);
565
+ return {
566
+ ...s,
567
+ name,
568
+ ...parsed,
569
+ type: s.type.trim(),
570
+ optional: !!s.optional,
571
+ multi
572
+ };
573
+ }
574
+ /**
575
+ * Checks and normalizes a node spec.
576
+ *
577
+ * @category Graph
578
+ */
579
+ function defineNode(spec) {
580
+ if (!spec || typeof spec.type !== "string" || !spec.type.trim()) throw new Error("defineNode: `type` is required");
581
+ if (typeof spec.run !== "function") throw new Error(`node "${spec.type}": \`run\` must be a function`);
582
+ const names = /* @__PURE__ */ new Set();
583
+ const unique = (n, what) => {
584
+ if (names.has(`${what}:${n}`)) throw new Error(`node "${spec.type}": duplicate ${what} "${n}"`);
585
+ names.add(`${what}:${n}`);
586
+ };
587
+ const inputs = Object.entries(spec.inputs ?? {}).map(([n, s]) => (unique(n, "input"), port(n, s)));
588
+ const outputs = Object.entries(spec.outputs ?? {}).map(([n, s]) => (unique(n, "output"), port(n, s)));
589
+ const params = Object.entries(spec.params ?? {}).map(([n, s]) => {
590
+ unique(n, "input");
591
+ if (!s || typeof s.type !== "string") throw new Error(`node "${spec.type}": param "${n}" needs a type`);
592
+ return {
593
+ ...s,
594
+ name: n
595
+ };
596
+ });
597
+ const type = spec.type.trim();
598
+ return {
599
+ type,
600
+ title: spec.title ?? type.split("/").pop(),
601
+ category: spec.category ?? (type.includes("/") ? type.slice(0, type.lastIndexOf("/")) : "misc"),
602
+ description: spec.description ?? "",
603
+ inputs,
604
+ params,
605
+ outputs,
606
+ run: spec.run,
607
+ output: !!spec.output,
608
+ animate: !!spec.animate,
609
+ source: spec.source,
610
+ revision: ++revisionCounter
611
+ };
612
+ }
613
+ /**
614
+ * Node types by name.
615
+ *
616
+ * @category Graph
617
+ */
618
+ var NodeRegistry = class {
619
+ defs = /* @__PURE__ */ new Map();
620
+ listeners = /* @__PURE__ */ new Set();
621
+ register(spec) {
622
+ const def = "revision" in spec ? spec : defineNode(spec);
623
+ this.defs.set(def.type, def);
624
+ for (const l of this.listeners) l(def, false);
625
+ return def;
626
+ }
627
+ unregister(type) {
628
+ const def = this.defs.get(type);
629
+ if (!def) return;
630
+ this.defs.delete(type);
631
+ for (const l of this.listeners) l(def, true);
632
+ }
633
+ get(type) {
634
+ return this.defs.get(type);
635
+ }
636
+ has(type) {
637
+ return this.defs.has(type);
638
+ }
639
+ all() {
640
+ return [...this.defs.values()];
641
+ }
642
+ /** Called when a type is registered (or replaced) or removed; returns an unsubscribe. */
643
+ onChange(listener) {
644
+ this.listeners.add(listener);
645
+ return () => this.listeners.delete(listener);
646
+ }
647
+ };
648
+ //#endregion
649
+ //#region src/graph/sources.ts
650
+ /**
651
+ * The built-in nodes as script modules: the same interface and behaviour as the TypeScript
652
+ * definitions in `nodes.ts`, written self-contained so the editor can show a built-in's code
653
+ * and fork it into a custom node. A test compiles each one and checks it matches.
654
+ *
655
+ * @module
656
+ */
657
+ const num$1 = `const num = (v, d = 0) => (typeof v === 'number' && Number.isFinite(v) ? v : d);`;
658
+ /** @category Graph */
659
+ const BUILTIN_SOURCES = {
660
+ "value/number": `export const title = 'Number';
661
+ export const params = { value: { type: 'number', default: 0 } };
662
+ export const outputs = { value: 'number' };
663
+
664
+ ${num$1}
665
+
666
+ export function run(inputs, { value }) {
667
+ return { value: num(value) };
668
+ }
669
+ `,
670
+ "value/vec2": `export const title = 'Vec2';
671
+ export const inputs = {
672
+ x: { type: 'number', default: 0 },
673
+ y: { type: 'number', default: 0 },
674
+ };
675
+ export const outputs = { vec: 'vec2' };
676
+
677
+ ${num$1}
678
+
679
+ export function run({ x, y }) {
680
+ return { vec: { x: num(x), y: num(y) } };
681
+ }
682
+ `,
683
+ "value/color": `export const title = 'Color';
684
+ export const params = { color: { type: 'color', default: '#3fd1a4' } };
685
+ export const outputs = { color: 'color' };
686
+
687
+ export function run(inputs, { color }) {
688
+ return { color };
689
+ }
690
+ `,
691
+ "value/text": `export const title = 'Text';
692
+ export const params = { text: { type: 'string', default: '' } };
693
+ export const outputs = { text: 'string' };
694
+
695
+ export function run(inputs, { text }) {
696
+ return { text: String(text ?? '') };
697
+ }
698
+ `,
699
+ "value/time": `export const title = 'Time';
700
+ export const description = 'the animation clock (animates by default)';
701
+ export const animate = true;
702
+ export const params = { speed: { type: 'number', default: 1, step: 0.1 } };
703
+ export const outputs = { time: 'number', dt: 'number', frame: 'number' };
704
+
705
+ ${num$1}
706
+
707
+ export function run(inputs, { speed }, ctx) {
708
+ return { time: ctx.time * num(speed, 1), dt: ctx.dt * num(speed, 1), frame: ctx.frame };
709
+ }
710
+ `,
711
+ "math/wave": `export const title = 'Wave';
712
+ export const description = 'sin / triangle / square / saw of t';
713
+ export const inputs = {
714
+ t: { type: 'number', default: 0 },
715
+ period: { type: 'number', default: 1 },
716
+ amplitude: { type: 'number', default: 1 },
717
+ };
718
+ export const params = { shape: { type: 'enum', options: ['sine', 'triangle', 'square', 'saw'], default: 'sine' } };
719
+ export const outputs = { value: 'number' };
720
+
721
+ ${num$1}
722
+
723
+ export function run({ t, period, amplitude }, { shape }) {
724
+ const p = num(t) / (num(period, 1) || 1);
725
+ const f = p - Math.floor(p);
726
+ const waves = {
727
+ sine: Math.sin(p * Math.PI * 2),
728
+ triangle: 1 - 4 * Math.abs(f - 0.5),
729
+ square: f < 0.5 ? 1 : -1,
730
+ saw: f * 2 - 1,
731
+ };
732
+ return { value: (waves[shape] ?? waves.sine) * num(amplitude, 1) };
733
+ }
734
+ `,
735
+ "math/math": `export const title = 'Math';
736
+ export const description = 'a ⊕ b for the chosen operation';
737
+ export const inputs = {
738
+ a: { type: 'number', default: 0 },
739
+ b: { type: 'number', default: 0 },
740
+ };
741
+ export const params = { op: { type: 'enum', options: ['+', '−', '×', '÷', 'min', 'max', 'pow', 'mod'], default: '+' } };
742
+ export const outputs = { result: 'number' };
743
+
744
+ ${num$1}
745
+
746
+ export function run({ a, b }, { op }) {
747
+ const x = num(a);
748
+ const y = num(b);
749
+ const results = {
750
+ '+': x + y, '−': x - y, '×': x * y, '÷': y === 0 ? 0 : x / y,
751
+ min: Math.min(x, y), max: Math.max(x, y), pow: x ** y, mod: y === 0 ? 0 : ((x % y) + y) % y,
752
+ };
753
+ return { result: results[op] ?? x + y };
754
+ }
755
+ `,
756
+ "math/remap": `export const title = 'Remap';
757
+ export const inputs = {
758
+ value: { type: 'number', default: 0.5 },
759
+ inMin: { type: 'number', default: 0 },
760
+ inMax: { type: 'number', default: 1 },
761
+ outMin: { type: 'number', default: 0 },
762
+ outMax: { type: 'number', default: 100 },
763
+ };
764
+ export const params = { clamp: { type: 'boolean', default: false } };
765
+ export const outputs = { result: 'number' };
766
+
767
+ export function run({ value, inMin, inMax, outMin, outMax }, { clamp }) {
768
+ let t = inMax === inMin ? 0 : (value - inMin) / (inMax - inMin);
769
+ if (clamp) t = Math.min(1, Math.max(0, t));
770
+ return { result: outMin + (outMax - outMin) * t };
771
+ }
772
+ `,
773
+ "vec2/split": `export const title = 'Split Vec2';
774
+ export const inputs = { vec: 'vec2' };
775
+ export const outputs = { x: 'number', y: 'number' };
776
+
777
+ ${num$1}
778
+
779
+ export function run({ vec }) {
780
+ return { x: num(vec?.x), y: num(vec?.y) };
781
+ }
782
+ `,
783
+ "vec2/offset": `export const title = 'Offset';
784
+ export const description = 'vec + by';
785
+ export const inputs = {
786
+ vec: 'vec2',
787
+ by: { type: 'vec2', default: { x: 0, y: 0 } },
788
+ };
789
+ export const outputs = { vec: 'vec2' };
790
+
791
+ ${num$1}
792
+
793
+ export function run({ vec, by }) {
794
+ return { vec: { x: num(vec?.x) + num(by?.x), y: num(vec?.y) + num(by?.y) } };
795
+ }
796
+ `,
797
+ "list/range": `export const title = 'Range';
798
+ export const description = 'numbers from start (inclusive) to end (exclusive)';
799
+ export const inputs = {
800
+ start: { type: 'number', default: 0 },
801
+ end: { type: 'number', default: 10 },
802
+ step: { type: 'number', default: 1 },
803
+ };
804
+ export const outputs = { numbers: 'number[]' };
805
+
806
+ ${num$1}
807
+
808
+ export function run({ start, end, step }) {
809
+ const s = num(step, 1) || 1;
810
+ const numbers = [];
811
+ for (let v = num(start); s > 0 ? v < end : v > end; v += s) {
812
+ numbers.push(v);
813
+ if (numbers.length >= 100000) break;
814
+ }
815
+ return { numbers };
816
+ }
817
+ `,
818
+ "list/grid2d": `export const title = 'Grid';
819
+ export const description = 'points on a grid, centered on \`center\`; stagger shifts every other row by half a cell';
820
+ export const inputs = {
821
+ cols: { type: 'number', default: 5, min: 1, step: 1 },
822
+ rows: { type: 'number', default: 5, min: 1, step: 1 },
823
+ spacing: { type: 'vec2', default: { x: 32, y: 32 } },
824
+ center: { type: 'vec2', default: { x: 0, y: 0 } },
825
+ };
826
+ export const params = { stagger: { type: 'boolean', default: false } };
827
+ export const outputs = { points: 'vec2[]' };
828
+
829
+ ${num$1}
830
+
831
+ export function run({ cols, rows, spacing, center }, { stagger }) {
832
+ const c = Math.max(0, Math.min(1000, Math.floor(num(cols))));
833
+ const r = Math.max(0, Math.min(1000, Math.floor(num(rows))));
834
+ const sx = num(spacing?.x, 32);
835
+ const sy = num(spacing?.y, 32);
836
+ const points = [];
837
+ for (let j = 0; j < r; j++) {
838
+ const shift = stagger && j % 2 === 1 ? sx / 2 : 0;
839
+ for (let i = 0; i < c; i++) {
840
+ points.push({ x: num(center?.x) + (i - (c - 1) / 2) * sx + shift, y: num(center?.y) + ((r - 1) / 2 - j) * sy });
841
+ }
842
+ }
843
+ return { points };
844
+ }
845
+ `,
846
+ "list/random": `export const title = 'Random';
847
+ export const description = 'seeded random numbers in [min, max)';
848
+ export const inputs = {
849
+ count: { type: 'number', default: 10, min: 0, step: 1 },
850
+ min: { type: 'number', default: 0 },
851
+ max: { type: 'number', default: 1 },
852
+ seed: { type: 'number', default: 1, step: 1 },
853
+ };
854
+ export const outputs = { numbers: 'number[]' };
855
+
856
+ ${num$1}
857
+
858
+ // the same generator as @n3rdw1z4rd/core's Rng: a 32-bit hash of an incrementing seed
859
+ const hash32 = (n) => {
860
+ n |= 0;
861
+ n ^= n >>> 16;
862
+ n = Math.imul(n, 0x85ebca6b);
863
+ n ^= n >>> 13;
864
+ n = Math.imul(n, 0xc2b2ae35);
865
+ n ^= n >>> 16;
866
+ return n >>> 0;
867
+ };
868
+
869
+ export function run({ count, min, max, seed }) {
870
+ let s = num(seed, 1) | 0;
871
+ const next = () => hash32((s++) | 0) / 0x100000000;
872
+ const n = Math.max(0, Math.min(100000, Math.floor(num(count))));
873
+ return { numbers: Array.from({ length: n }, () => num(min) + next() * (num(max, 1) - num(min))) };
874
+ }
875
+ `,
876
+ "list/count": `export const title = 'Count';
877
+ export const inputs = { list: 'any[]' };
878
+ export const outputs = { count: 'number' };
879
+
880
+ export function run({ list }) {
881
+ return { count: list.length };
882
+ }
883
+ `,
884
+ "list/merge": `export const title = 'Merge';
885
+ export const description = 'joins every list wired in, in order';
886
+ export const inputs = { lists: { type: 'any[]', multi: true, optional: true } };
887
+ export const outputs = { list: 'any[]' };
888
+
889
+ export function run({ lists }) {
890
+ return { list: [...(lists ?? [])] };
891
+ }
892
+ `,
893
+ "list/pick": `export const title = 'Pick';
894
+ export const description = 'every nth item from a list';
895
+ export const inputs = {
896
+ list: 'any[]',
897
+ every: { type: 'number', default: 2, min: 1, step: 1 },
898
+ offset: { type: 'number', default: 0, step: 1 },
899
+ };
900
+ export const outputs = { list: 'any[]' };
901
+
902
+ ${num$1}
903
+
904
+ export function run({ list, every, offset }) {
905
+ const n = Math.max(1, Math.floor(num(every, 1)));
906
+ return { list: list.filter((_, i) => (i - Math.floor(num(offset))) % n === 0 && i >= num(offset)) };
907
+ }
908
+ `
909
+ };
910
+ //#endregion
911
+ //#region src/graph/nodes.ts
912
+ const v2 = (x = 0, y = 0) => ({
913
+ x,
914
+ y
915
+ });
916
+ const num = (v, d = 0) => typeof v === "number" && Number.isFinite(v) ? v : d;
917
+ /** @category Graph */
918
+ const BUILTIN_NODES = [
919
+ {
920
+ type: "value/number",
921
+ title: "Number",
922
+ params: { value: {
923
+ type: "number",
924
+ default: 0
925
+ } },
926
+ outputs: { value: "number" },
927
+ run: (_, { value }) => ({ value: num(value) })
928
+ },
929
+ {
930
+ type: "value/vec2",
931
+ title: "Vec2",
932
+ inputs: {
933
+ x: {
934
+ type: "number",
935
+ default: 0
936
+ },
937
+ y: {
938
+ type: "number",
939
+ default: 0
940
+ }
941
+ },
942
+ outputs: { vec: "vec2" },
943
+ run: ({ x, y }) => ({ vec: v2(num(x), num(y)) })
944
+ },
945
+ {
946
+ type: "value/color",
947
+ title: "Color",
948
+ params: { color: {
949
+ type: "color",
950
+ default: "#3fd1a4"
951
+ } },
952
+ outputs: { color: "color" },
953
+ run: (_, { color }) => ({ color })
954
+ },
955
+ {
956
+ type: "value/text",
957
+ title: "Text",
958
+ params: { text: {
959
+ type: "string",
960
+ default: ""
961
+ } },
962
+ outputs: { text: "string" },
963
+ run: (_, { text }) => ({ text: String(text ?? "") })
964
+ },
965
+ {
966
+ type: "value/time",
967
+ title: "Time",
968
+ description: "the animation clock (animates by default)",
969
+ animate: true,
970
+ params: { speed: {
971
+ type: "number",
972
+ default: 1,
973
+ step: .1
974
+ } },
975
+ outputs: {
976
+ time: "number",
977
+ dt: "number",
978
+ frame: "number"
979
+ },
980
+ run: (_, { speed }, ctx) => ({
981
+ time: ctx.time * num(speed, 1),
982
+ dt: ctx.dt * num(speed, 1),
983
+ frame: ctx.frame
984
+ })
985
+ },
986
+ {
987
+ type: "math/wave",
988
+ title: "Wave",
989
+ description: "sin / triangle / square / saw of t",
990
+ inputs: {
991
+ t: {
992
+ type: "number",
993
+ default: 0
994
+ },
995
+ period: {
996
+ type: "number",
997
+ default: 1
998
+ },
999
+ amplitude: {
1000
+ type: "number",
1001
+ default: 1
1002
+ }
1003
+ },
1004
+ params: { shape: {
1005
+ type: "enum",
1006
+ options: [
1007
+ "sine",
1008
+ "triangle",
1009
+ "square",
1010
+ "saw"
1011
+ ],
1012
+ default: "sine"
1013
+ } },
1014
+ outputs: { value: "number" },
1015
+ run: ({ t, period, amplitude }, { shape }) => {
1016
+ const p = num(t) / (num(period, 1) || 1);
1017
+ const f = p - Math.floor(p);
1018
+ const w = {
1019
+ sine: Math.sin(p * Math.PI * 2),
1020
+ triangle: 1 - 4 * Math.abs(f - .5),
1021
+ square: f < .5 ? 1 : -1,
1022
+ saw: f * 2 - 1
1023
+ };
1024
+ return { value: (w[shape] ?? w.sine) * num(amplitude, 1) };
1025
+ }
1026
+ },
1027
+ {
1028
+ type: "math/math",
1029
+ title: "Math",
1030
+ description: "a ⊕ b for the chosen operation",
1031
+ inputs: {
1032
+ a: {
1033
+ type: "number",
1034
+ default: 0
1035
+ },
1036
+ b: {
1037
+ type: "number",
1038
+ default: 0
1039
+ }
1040
+ },
1041
+ params: { op: {
1042
+ type: "enum",
1043
+ options: [
1044
+ "+",
1045
+ "−",
1046
+ "×",
1047
+ "÷",
1048
+ "min",
1049
+ "max",
1050
+ "pow",
1051
+ "mod"
1052
+ ],
1053
+ default: "+"
1054
+ } },
1055
+ outputs: { result: "number" },
1056
+ run: ({ a, b }, { op }) => {
1057
+ const x = num(a);
1058
+ const y = num(b);
1059
+ return { result: {
1060
+ "+": x + y,
1061
+ "−": x - y,
1062
+ "×": x * y,
1063
+ "÷": y === 0 ? 0 : x / y,
1064
+ min: Math.min(x, y),
1065
+ max: Math.max(x, y),
1066
+ pow: x ** y,
1067
+ mod: y === 0 ? 0 : (x % y + y) % y
1068
+ }[op] ?? x + y };
1069
+ }
1070
+ },
1071
+ {
1072
+ type: "math/remap",
1073
+ title: "Remap",
1074
+ inputs: {
1075
+ value: {
1076
+ type: "number",
1077
+ default: .5
1078
+ },
1079
+ inMin: {
1080
+ type: "number",
1081
+ default: 0
1082
+ },
1083
+ inMax: {
1084
+ type: "number",
1085
+ default: 1
1086
+ },
1087
+ outMin: {
1088
+ type: "number",
1089
+ default: 0
1090
+ },
1091
+ outMax: {
1092
+ type: "number",
1093
+ default: 100
1094
+ }
1095
+ },
1096
+ params: { clamp: {
1097
+ type: "boolean",
1098
+ default: false
1099
+ } },
1100
+ outputs: { result: "number" },
1101
+ run: ({ value, inMin, inMax, outMin, outMax }, { clamp }) => {
1102
+ let t = inMax === inMin ? 0 : (value - inMin) / (inMax - inMin);
1103
+ if (clamp) t = Math.min(1, Math.max(0, t));
1104
+ return { result: outMin + (outMax - outMin) * t };
1105
+ }
1106
+ },
1107
+ {
1108
+ type: "vec2/split",
1109
+ title: "Split Vec2",
1110
+ inputs: { vec: "vec2" },
1111
+ outputs: {
1112
+ x: "number",
1113
+ y: "number"
1114
+ },
1115
+ run: ({ vec }) => ({
1116
+ x: num(vec?.x),
1117
+ y: num(vec?.y)
1118
+ })
1119
+ },
1120
+ {
1121
+ type: "vec2/offset",
1122
+ title: "Offset",
1123
+ description: "vec + by",
1124
+ inputs: {
1125
+ vec: "vec2",
1126
+ by: {
1127
+ type: "vec2",
1128
+ default: {
1129
+ x: 0,
1130
+ y: 0
1131
+ }
1132
+ }
1133
+ },
1134
+ outputs: { vec: "vec2" },
1135
+ run: ({ vec, by }) => ({ vec: v2(num(vec?.x) + num(by?.x), num(vec?.y) + num(by?.y)) })
1136
+ },
1137
+ {
1138
+ type: "list/range",
1139
+ title: "Range",
1140
+ description: "numbers from start (inclusive) to end (exclusive)",
1141
+ inputs: {
1142
+ start: {
1143
+ type: "number",
1144
+ default: 0
1145
+ },
1146
+ end: {
1147
+ type: "number",
1148
+ default: 10
1149
+ },
1150
+ step: {
1151
+ type: "number",
1152
+ default: 1
1153
+ }
1154
+ },
1155
+ outputs: { numbers: "number[]" },
1156
+ run: ({ start, end, step }) => {
1157
+ const s = num(step, 1) || 1;
1158
+ const out = [];
1159
+ for (let v = num(start); s > 0 ? v < end : v > end; v += s) {
1160
+ out.push(v);
1161
+ if (out.length >= 1e5) break;
1162
+ }
1163
+ return { numbers: out };
1164
+ }
1165
+ },
1166
+ {
1167
+ type: "list/grid2d",
1168
+ title: "Grid",
1169
+ description: "points on a grid, centered on `center`; stagger shifts every other row by half a cell",
1170
+ inputs: {
1171
+ cols: {
1172
+ type: "number",
1173
+ default: 5,
1174
+ min: 1,
1175
+ step: 1
1176
+ },
1177
+ rows: {
1178
+ type: "number",
1179
+ default: 5,
1180
+ min: 1,
1181
+ step: 1
1182
+ },
1183
+ spacing: {
1184
+ type: "vec2",
1185
+ default: {
1186
+ x: 32,
1187
+ y: 32
1188
+ }
1189
+ },
1190
+ center: {
1191
+ type: "vec2",
1192
+ default: {
1193
+ x: 0,
1194
+ y: 0
1195
+ }
1196
+ }
1197
+ },
1198
+ params: { stagger: {
1199
+ type: "boolean",
1200
+ default: false
1201
+ } },
1202
+ outputs: { points: "vec2[]" },
1203
+ run: ({ cols, rows, spacing, center }, { stagger }) => {
1204
+ const c = Math.max(0, Math.min(1e3, Math.floor(num(cols))));
1205
+ const r = Math.max(0, Math.min(1e3, Math.floor(num(rows))));
1206
+ const sx = num(spacing?.x, 32);
1207
+ const sy = num(spacing?.y, 32);
1208
+ const points = [];
1209
+ for (let j = 0; j < r; j++) {
1210
+ const shift = stagger && j % 2 === 1 ? sx / 2 : 0;
1211
+ for (let i = 0; i < c; i++) points.push(v2(num(center?.x) + (i - (c - 1) / 2) * sx + shift, num(center?.y) + ((r - 1) / 2 - j) * sy));
1212
+ }
1213
+ return { points };
1214
+ }
1215
+ },
1216
+ {
1217
+ type: "list/random",
1218
+ title: "Random",
1219
+ description: "seeded random numbers in [min, max)",
1220
+ inputs: {
1221
+ count: {
1222
+ type: "number",
1223
+ default: 10,
1224
+ min: 0,
1225
+ step: 1
1226
+ },
1227
+ min: {
1228
+ type: "number",
1229
+ default: 0
1230
+ },
1231
+ max: {
1232
+ type: "number",
1233
+ default: 1
1234
+ },
1235
+ seed: {
1236
+ type: "number",
1237
+ default: 1,
1238
+ step: 1
1239
+ }
1240
+ },
1241
+ outputs: { numbers: "number[]" },
1242
+ run: ({ count, min, max, seed }) => {
1243
+ const rng = new require_rng.Rng(num(seed, 1));
1244
+ const n = Math.max(0, Math.min(1e5, Math.floor(num(count))));
1245
+ return { numbers: Array.from({ length: n }, () => num(min) + rng.nextFloat() * (num(max, 1) - num(min))) };
1246
+ }
1247
+ },
1248
+ {
1249
+ type: "list/count",
1250
+ title: "Count",
1251
+ inputs: { list: "any[]" },
1252
+ outputs: { count: "number" },
1253
+ run: ({ list }) => ({ count: list.length })
1254
+ },
1255
+ {
1256
+ type: "list/merge",
1257
+ title: "Merge",
1258
+ description: "joins every list wired in, in order",
1259
+ inputs: { lists: {
1260
+ type: "any[]",
1261
+ multi: true,
1262
+ optional: true
1263
+ } },
1264
+ outputs: { list: "any[]" },
1265
+ run: ({ lists }) => ({ list: [...lists ?? []] })
1266
+ },
1267
+ {
1268
+ type: "list/pick",
1269
+ title: "Pick",
1270
+ description: "every nth item from a list",
1271
+ inputs: {
1272
+ list: "any[]",
1273
+ every: {
1274
+ type: "number",
1275
+ default: 2,
1276
+ min: 1,
1277
+ step: 1
1278
+ },
1279
+ offset: {
1280
+ type: "number",
1281
+ default: 0,
1282
+ step: 1
1283
+ }
1284
+ },
1285
+ outputs: { list: "any[]" },
1286
+ run: ({ list, every, offset }) => {
1287
+ const n = Math.max(1, Math.floor(num(every, 1)));
1288
+ return { list: list.filter((_, i) => (i - Math.floor(num(offset))) % n === 0 && i >= num(offset)) };
1289
+ }
1290
+ }
1291
+ ];
1292
+ /**
1293
+ * A registry with the built-in nodes.
1294
+ *
1295
+ * @category Graph
1296
+ */
1297
+ function createNodeRegistry() {
1298
+ const registry = new NodeRegistry();
1299
+ for (const spec of BUILTIN_NODES) registry.register({
1300
+ ...spec,
1301
+ source: spec.source ?? BUILTIN_SOURCES[spec.type]
1302
+ });
1303
+ return registry;
1304
+ }
1305
+ //#endregion
1306
+ //#region src/graph/script.ts
1307
+ /**
1308
+ * Script nodes: a node type written as a plain ES module, compiled at runtime.
1309
+ *
1310
+ * ```js
1311
+ * export const title = 'Ball'; // optional: title, category, description, output, animate
1312
+ * export const inputs = { at: 'vec2', radius: { type: 'number', default: 8 } };
1313
+ * export const params = { color: { type: 'color', default: '#e8554e' } };
1314
+ * export const outputs = { entity: 'entity' };
1315
+ * export function run({ at, radius }, { color }, ctx) {
1316
+ * return { entity: { shape: 'ball', x: at.x, y: at.y, r: radius, color } };
1317
+ * }
1318
+ * ```
1319
+ *
1320
+ * The module is imported from a `data:` URL, which works in browsers, workers and Node.
1321
+ * It runs with the page's (or worker's) privileges — treat shared scripts as untrusted and
1322
+ * evaluate them in a worker.
1323
+ *
1324
+ * @module
1325
+ */
1326
+ /**
1327
+ * The functions a behaviour module can export (any of them, and no `run`): what they mean is up to
1328
+ * the host. apparatus runs `setup` once, `step` every physics step, and `enter` / `exit` when a body
1329
+ * starts / stops touching (or overlapping) the one the behaviour is on.
1330
+ *
1331
+ * @category Graph
1332
+ */
1333
+ const BEHAVIOR_HOOKS = [
1334
+ "setup",
1335
+ "step",
1336
+ "enter",
1337
+ "exit"
1338
+ ];
1339
+ /**
1340
+ * Compiles a script node's source into a node type named `type`.
1341
+ *
1342
+ * @category Graph
1343
+ */
1344
+ async function compileNodeScript(type, source) {
1345
+ const mod = await import(
1346
+ /* @vite-ignore */
1347
+ `data:text/javascript;charset=utf-8,${encodeURIComponent(source)}`
1348
+ );
1349
+ const m = { ...mod.default && typeof mod.default === "object" && !mod.run ? mod.default : mod };
1350
+ if (typeof m.run !== "function" && BEHAVIOR_HOOKS.some((h) => typeof m[h] === "function")) {
1351
+ m.run = behaviorRun;
1352
+ m.outputs ??= { behavior: "behavior" };
1353
+ m.category ??= "behavior";
1354
+ }
1355
+ if (typeof m.run !== "function") throw new Error(`script node "${type}": export a run(inputs, params, ctx) function (or setup / step / enter / exit for a behaviour)`);
1356
+ return defineNode({
1357
+ type,
1358
+ title: m.title,
1359
+ category: m.category ?? "scripts",
1360
+ description: m.description,
1361
+ inputs: m.inputs,
1362
+ params: m.params,
1363
+ outputs: m.outputs,
1364
+ output: m.output,
1365
+ animate: m.animate,
1366
+ run: m.run,
1367
+ source
1368
+ });
1369
+ }
1370
+ /**
1371
+ * The `run` of a behaviour node: packs its inputs, params and source into a {@link BehaviorValue}
1372
+ * on the `behavior` output. Behaviour modules (exporting a hook, no `run`) get it automatically.
1373
+ *
1374
+ * @category Graph
1375
+ */
1376
+ function behaviorRun(inputs, params, ctx) {
1377
+ if (!ctx.source) throw new Error(`behaviour node ${ctx.type} has no source module`);
1378
+ return { behavior: {
1379
+ kind: "behavior",
1380
+ type: ctx.type,
1381
+ node: ctx.nodeId,
1382
+ params: {
1383
+ ...inputs,
1384
+ ...params
1385
+ },
1386
+ source: ctx.source
1387
+ } };
1388
+ }
1389
+ /** A starting point for a new script node. @category Graph */
1390
+ const SCRIPT_NODE_TEMPLATE = `// A node is a function with a typed interface.
1391
+ // inputs: pins wired from other nodes (an unconnected one uses its widget value / default)
1392
+ // params: widgets on the node
1393
+ // outputs: what run() returns
1394
+ // A "type[]" pin takes (or gives) a whole list; a list wired into a plain pin runs
1395
+ // run() once per item and collects the results into lists.
1396
+
1397
+ export const inputs = {
1398
+ a: { type: 'number', default: 1 },
1399
+ b: { type: 'number', default: 2 },
1400
+ };
1401
+
1402
+ export const params = {
1403
+ scale: { type: 'number', default: 1, min: 0, max: 10, step: 0.1 },
1404
+ };
1405
+
1406
+ export const outputs = {
1407
+ result: 'number',
1408
+ };
1409
+
1410
+ export function run({ a, b }, { scale }, ctx) {
1411
+ return { result: (a + b) * scale };
1412
+ }
1413
+ `;
1414
+ //#endregion
1415
+ //#region src/graph/subgraph.ts
1416
+ /**
1417
+ * Subgraphs: a selection of nodes collapsed into one node type. The inner graph is stored in
1418
+ * `doc.subgraphs[type]` with its interface — every wire that crossed the selection's edge
1419
+ * became an input or output. A subgraph node evaluates its inner graph (with its own cache per
1420
+ * instance), feeding the inner ports from its inputs.
1421
+ *
1422
+ * @module
1423
+ */
1424
+ /** The node spec for a subgraph type: runs the inner graph. */
1425
+ function subgraphSpec(type, def, registry) {
1426
+ const inner = {
1427
+ format: "n3rdw1z4rd.graph",
1428
+ version: 1,
1429
+ nodes: def.nodes,
1430
+ links: def.links
1431
+ };
1432
+ const evaluators = /* @__PURE__ */ new Map();
1433
+ let stamp = 0;
1434
+ const probe = new GraphEvaluator(registry);
1435
+ const targets = [...new Set(def.outputs.map((o) => o.from.node))];
1436
+ return {
1437
+ type,
1438
+ title: def.title,
1439
+ category: "subgraph",
1440
+ description: `a subgraph of ${def.nodes.length} node${def.nodes.length === 1 ? "" : "s"} (double-click to go inside)`,
1441
+ inputs: Object.fromEntries(def.inputs.map((p) => [p.name, {
1442
+ type: p.type,
1443
+ multi: !!p.multi,
1444
+ optional: true
1445
+ }])),
1446
+ outputs: Object.fromEntries(def.outputs.map((p) => [p.name, p.type])),
1447
+ animate: probe.animated(inner, targets).length > 0,
1448
+ async run(inputs, _params, ctx) {
1449
+ const key = `${ctx.nodeId}#${ctx.index}`;
1450
+ let ev = evaluators.get(key);
1451
+ if (!ev) evaluators.set(key, ev = new GraphEvaluator(registry));
1452
+ const externals = /* @__PURE__ */ new Map();
1453
+ for (const p of def.inputs) {
1454
+ const v = inputs[p.name];
1455
+ if (v === void 0) continue;
1456
+ const list = p.type.trim().endsWith("[]");
1457
+ for (const to of p.to) {
1458
+ const k = `${to.node}:${to.port}`;
1459
+ externals.set(k, [...externals.get(k) ?? [], {
1460
+ value: v,
1461
+ list
1462
+ }]);
1463
+ }
1464
+ }
1465
+ const r = await ev.evaluate(inner, {
1466
+ targets,
1467
+ externals,
1468
+ externalsStamp: ++stamp,
1469
+ scope: key,
1470
+ env: ctx.env,
1471
+ frame: {
1472
+ time: ctx.time,
1473
+ dt: ctx.dt,
1474
+ frame: ctx.frame
1475
+ }
1476
+ });
1477
+ const out = {};
1478
+ const lists = {};
1479
+ for (const o of def.outputs) {
1480
+ const res = r.results.get(o.from.node);
1481
+ if (!res) throw new Error(`inside: node ${o.from.node} is missing`);
1482
+ const node = getNode(inner, o.from.node);
1483
+ const name = node?.title ?? registry.get(node?.type ?? "")?.title ?? o.from.node;
1484
+ if (res.error) throw new Error(`inside, ${name}: ${res.error}`);
1485
+ if (res.disabled) throw new Error(`inside, ${name} is disabled`);
1486
+ if (res.blocked) {
1487
+ const up = getNode(inner, res.blocked);
1488
+ throw new Error(`inside, ${name} is waiting on ${up?.title ?? registry.get(up?.type ?? "")?.title ?? res.blocked}`);
1489
+ }
1490
+ out[o.name] = res.outputs[o.from.port];
1491
+ lists[o.name] = !!res.lists[o.from.port];
1492
+ }
1493
+ return {
1494
+ ...out,
1495
+ [OUTPUT_LISTS]: lists
1496
+ };
1497
+ }
1498
+ };
1499
+ }
1500
+ const registered = /* @__PURE__ */ new Map();
1501
+ /**
1502
+ * Registers (or updates) every subgraph type a document defines. Unchanged definitions are
1503
+ * left alone (so their nodes keep their caches). Definitions may use each other.
1504
+ */
1505
+ function registerSubgraphs(doc, registry) {
1506
+ for (const [type, def] of Object.entries(doc.subgraphs ?? {})) {
1507
+ const json = JSON.stringify(def);
1508
+ if (registered.get(type) === json && registry.get(type)) continue;
1509
+ registered.set(type, json);
1510
+ registry.register(subgraphSpec(type, def, registry));
1511
+ }
1512
+ }
1513
+ /** A free type name for a subgraph (`subgraph/name`, `subgraph/name-2`, …). */
1514
+ function freeSubgraphType(doc, registry, name) {
1515
+ const base = `subgraph/${name.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || "subgraph"}`;
1516
+ let type = base;
1517
+ for (let k = 2; registry.get(type) || doc.subgraphs?.[type]; k++) type = `${base}-${k}`;
1518
+ return type;
1519
+ }
1520
+ /**
1521
+ * Collapses nodes into a new subgraph type and puts one node of it in their place, wired to
1522
+ * everything they were wired to. Output nodes (like a viewport) can't go into a subgraph.
1523
+ */
1524
+ function collapseToSubgraph(doc, registry, nodeIds, title = "Subgraph") {
1525
+ const ids = new Set(nodeIds.filter((id) => {
1526
+ const n = getNode(doc, id);
1527
+ return n && !registry.get(n.type)?.output;
1528
+ }));
1529
+ if (!ids.size) throw new Error("select some nodes (output nodes stay outside)");
1530
+ const type = freeSubgraphType(doc, registry, title);
1531
+ const inside = doc.nodes.filter((n) => ids.has(n.id));
1532
+ const internal = doc.links.filter((l) => ids.has(l.from.node) && ids.has(l.to.node));
1533
+ const incoming = doc.links.filter((l) => !ids.has(l.from.node) && ids.has(l.to.node));
1534
+ const outgoing = doc.links.filter((l) => ids.has(l.from.node) && !ids.has(l.to.node));
1535
+ const used = /* @__PURE__ */ new Set();
1536
+ const unique = (name) => {
1537
+ let n = name;
1538
+ for (let k = 2; used.has(n); k++) n = `${name}${k}`;
1539
+ used.add(n);
1540
+ return n;
1541
+ };
1542
+ const portOf = (ref, dir) => {
1543
+ const def = registry.get(getNode(doc, ref.node).type);
1544
+ return (dir === "in" ? def?.inputs : def?.outputs)?.find((p) => p.name === ref.port);
1545
+ };
1546
+ const inputs = [];
1547
+ const inputBySource = /* @__PURE__ */ new Map();
1548
+ const outerIn = [];
1549
+ for (const l of incoming) {
1550
+ const k = `${l.from.node}:${l.from.port}`;
1551
+ let input = inputBySource.get(k);
1552
+ if (!input) {
1553
+ const p = portOf(l.to, "in");
1554
+ input = {
1555
+ name: unique(l.to.port),
1556
+ type: p?.type ?? "any",
1557
+ ...p?.multi ? { multi: true } : {},
1558
+ to: []
1559
+ };
1560
+ inputBySource.set(k, input);
1561
+ inputs.push(input);
1562
+ outerIn.push({
1563
+ source: l.from,
1564
+ input: input.name
1565
+ });
1566
+ }
1567
+ input.to.push({ ...l.to });
1568
+ }
1569
+ used.clear();
1570
+ const outputs = [];
1571
+ const outputBySource = /* @__PURE__ */ new Map();
1572
+ for (const l of outgoing) {
1573
+ const k = `${l.from.node}:${l.from.port}`;
1574
+ if (outputBySource.has(k)) continue;
1575
+ const name = unique(l.from.port);
1576
+ outputBySource.set(k, name);
1577
+ outputs.push({
1578
+ name,
1579
+ type: portOf(l.from, "out")?.type ?? "any",
1580
+ from: { ...l.from }
1581
+ });
1582
+ }
1583
+ let minX = Infinity, minY = Infinity, sumX = 0, sumY = 0;
1584
+ for (const n of inside) {
1585
+ minX = Math.min(minX, n.pos[0]);
1586
+ minY = Math.min(minY, n.pos[1]);
1587
+ sumX += n.pos[0];
1588
+ sumY += n.pos[1];
1589
+ }
1590
+ const def = {
1591
+ title,
1592
+ nodes: inside.map((n) => ({
1593
+ ...structuredClone(n),
1594
+ pos: [n.pos[0] - minX, n.pos[1] - minY]
1595
+ })),
1596
+ links: internal.map((l) => structuredClone(l)),
1597
+ inputs,
1598
+ outputs
1599
+ };
1600
+ doc.subgraphs = {
1601
+ ...doc.subgraphs ?? {},
1602
+ [type]: def
1603
+ };
1604
+ registry.register(subgraphSpec(type, def, registry));
1605
+ const node = {
1606
+ id: graphId(),
1607
+ type,
1608
+ pos: [Math.round(sumX / inside.length), Math.round(sumY / inside.length)],
1609
+ values: {}
1610
+ };
1611
+ doc.nodes = doc.nodes.filter((n) => !ids.has(n.id));
1612
+ doc.nodes.push(node);
1613
+ doc.links = doc.links.filter((l) => !ids.has(l.from.node) && !ids.has(l.to.node));
1614
+ for (const { source, input } of outerIn) doc.links.push({
1615
+ id: graphId("l"),
1616
+ from: { ...source },
1617
+ to: {
1618
+ node: node.id,
1619
+ port: input
1620
+ }
1621
+ });
1622
+ for (const l of outgoing) doc.links.push({
1623
+ id: graphId("l"),
1624
+ from: {
1625
+ node: node.id,
1626
+ port: outputBySource.get(`${l.from.node}:${l.from.port}`)
1627
+ },
1628
+ to: { ...l.to }
1629
+ });
1630
+ return {
1631
+ type,
1632
+ node
1633
+ };
1634
+ }
1635
+ /**
1636
+ * Replaces a subgraph node with a copy of its inner nodes (fresh ids), wired as the
1637
+ * subgraph's inputs and outputs were. Returns the new node ids. The type stays defined.
1638
+ * `defs`: where the definitions are (default: `doc.subgraphs`; pass the top-level document's
1639
+ * when `doc` is itself a subgraph's inner graph).
1640
+ */
1641
+ function expandSubgraph(doc, nodeId, defs = doc.subgraphs) {
1642
+ const node = getNode(doc, nodeId);
1643
+ const def = node && defs?.[node.type];
1644
+ if (!node || !def) throw new Error("not a subgraph node");
1645
+ const ids = /* @__PURE__ */ new Map();
1646
+ for (const n of def.nodes) {
1647
+ const id = graphId();
1648
+ ids.set(n.id, id);
1649
+ doc.nodes.push({
1650
+ ...structuredClone(n),
1651
+ id,
1652
+ pos: [n.pos[0] + node.pos[0], n.pos[1] + node.pos[1]]
1653
+ });
1654
+ }
1655
+ const links = def.links.map((l) => ({
1656
+ id: graphId("l"),
1657
+ from: {
1658
+ node: ids.get(l.from.node),
1659
+ port: l.from.port
1660
+ },
1661
+ to: {
1662
+ node: ids.get(l.to.node),
1663
+ port: l.to.port
1664
+ }
1665
+ }));
1666
+ for (const l of doc.links) if (l.to.node === nodeId) {
1667
+ const input = def.inputs.find((p) => p.name === l.to.port);
1668
+ for (const to of input?.to ?? []) links.push({
1669
+ id: graphId("l"),
1670
+ from: { ...l.from },
1671
+ to: {
1672
+ node: ids.get(to.node),
1673
+ port: to.port
1674
+ }
1675
+ });
1676
+ } else if (l.from.node === nodeId) {
1677
+ const output = def.outputs.find((p) => p.name === l.from.port);
1678
+ if (output) links.push({
1679
+ id: graphId("l"),
1680
+ from: {
1681
+ node: ids.get(output.from.node),
1682
+ port: output.from.port
1683
+ },
1684
+ to: { ...l.to }
1685
+ });
1686
+ } else links.push(l);
1687
+ doc.links = links;
1688
+ doc.nodes = doc.nodes.filter((n) => n.id !== nodeId);
1689
+ return [...ids.values()];
1690
+ }
1691
+ //#endregion
1692
+ exports.BEHAVIOR_HOOKS = BEHAVIOR_HOOKS;
1693
+ exports.BUILTIN_NODES = BUILTIN_NODES;
1694
+ exports.BUILTIN_SOURCES = BUILTIN_SOURCES;
1695
+ exports.GRAPH_FORMAT = GRAPH_FORMAT;
1696
+ exports.GRAPH_VERSION = GRAPH_VERSION;
1697
+ exports.GraphEvaluator = GraphEvaluator;
1698
+ exports.NodeRegistry = NodeRegistry;
1699
+ exports.OUTPUT_LISTS = OUTPUT_LISTS;
1700
+ exports.SCRIPT_NODE_TEMPLATE = SCRIPT_NODE_TEMPLATE;
1701
+ exports.TypeRegistry = TypeRegistry;
1702
+ exports.addNode = addNode;
1703
+ exports.behaviorRun = behaviorRun;
1704
+ exports.canConnect = canConnect;
1705
+ exports.collapseToSubgraph = collapseToSubgraph;
1706
+ exports.compileNodeScript = compileNodeScript;
1707
+ exports.connect = connect;
1708
+ exports.createGraph = createGraph;
1709
+ exports.createNodeRegistry = createNodeRegistry;
1710
+ exports.defineNode = defineNode;
1711
+ exports.disconnect = disconnect;
1712
+ exports.expandSubgraph = expandSubgraph;
1713
+ exports.freeSubgraphType = freeSubgraphType;
1714
+ exports.getNode = getNode;
1715
+ exports.graphId = graphId;
1716
+ exports.linkInto = linkInto;
1717
+ exports.linksInto = linksInto;
1718
+ exports.normalizeGraph = normalizeGraph;
1719
+ exports.parseType = parseType;
1720
+ exports.portTypes = portTypes;
1721
+ exports.registerSubgraphs = registerSubgraphs;
1722
+ exports.removeNode = removeNode;
1723
+ exports.subgraphSpec = subgraphSpec;