topotopo 0.4.0 → 0.5.1

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 (336) hide show
  1. package/NOTICE +10 -10
  2. package/README.md +460 -117
  3. package/dist/cli.js +327 -147
  4. package/dist/config.d.ts +48 -0
  5. package/dist/config.js +170 -0
  6. package/dist/core/bake.d.ts +14 -3
  7. package/dist/core/bake.js +153 -4
  8. package/dist/core/bevel.d.ts +3 -1
  9. package/dist/core/bevel.js +76 -3
  10. package/dist/core/decimate.d.ts +65 -0
  11. package/dist/core/decimate.js +409 -3
  12. package/dist/core/erosion.d.ts +37 -0
  13. package/dist/core/erosion.js +41 -1
  14. package/dist/core/geometry.d.ts +5 -1
  15. package/dist/core/geometry.js +203 -3
  16. package/dist/core/heightfield.d.ts +27 -4
  17. package/dist/core/heightfield.js +54 -16
  18. package/dist/core/intrinsics.d.ts +7 -0
  19. package/dist/core/intrinsics.js +94 -0
  20. package/dist/core/manifold.d.ts +12 -1
  21. package/dist/core/manifold.js +78 -6
  22. package/dist/core/materials.d.ts +7 -0
  23. package/dist/core/materials.js +45 -0
  24. package/dist/core/noise.d.ts +9 -0
  25. package/dist/core/noise.js +10 -1
  26. package/dist/core/polymerge.d.ts +21 -0
  27. package/dist/core/polymerge.js +327 -0
  28. package/dist/core/repair.d.ts +2 -0
  29. package/dist/core/repair.js +2 -0
  30. package/dist/core/report.d.ts +70 -0
  31. package/dist/core/report.js +275 -0
  32. package/dist/core/scene.js +2 -1
  33. package/dist/core/sha256.d.ts +4 -0
  34. package/dist/core/sha256.js +69 -0
  35. package/dist/core/shapes.d.ts +3 -0
  36. package/dist/core/shapes.js +34 -0
  37. package/dist/core/snippet-lib.d.ts +14 -1
  38. package/dist/core/snippet-lib.js +39 -13
  39. package/dist/core/tangents.d.ts +2 -0
  40. package/dist/core/tangents.js +5 -1
  41. package/dist/core/texnoise.d.ts +6 -1
  42. package/dist/core/texnoise.js +6 -2
  43. package/dist/core/texsdf.d.ts +131 -0
  44. package/dist/core/texsdf.js +637 -0
  45. package/dist/core/texture.d.ts +163 -9
  46. package/dist/core/texture.js +844 -20
  47. package/dist/core/topology.d.ts +10 -0
  48. package/dist/core/topology.js +168 -0
  49. package/dist/core/unwrap.d.ts +72 -0
  50. package/dist/core/unwrap.js +800 -0
  51. package/dist/core/usercode.d.ts +27 -0
  52. package/dist/core/usercode.js +87 -0
  53. package/dist/core/uv.d.ts +4 -18
  54. package/dist/core/uv.js +35 -188
  55. package/dist/core/uvislands.d.ts +62 -0
  56. package/dist/core/uvislands.js +574 -0
  57. package/dist/core/uvoverlap.d.ts +58 -0
  58. package/dist/core/uvoverlap.js +220 -0
  59. package/dist/core/uvpack.d.ts +64 -0
  60. package/dist/core/uvpack.js +628 -0
  61. package/dist/core/uvreport.d.ts +61 -0
  62. package/dist/core/uvreport.js +207 -143
  63. package/dist/core/wrangle.d.ts +6 -1
  64. package/dist/core/wrangle.js +27 -16
  65. package/dist/core/xatlas.d.ts +16 -1
  66. package/dist/core/xatlas.js +66 -62
  67. package/dist/engines.d.ts +63 -0
  68. package/dist/engines.js +180 -0
  69. package/dist/explain.d.ts +4 -3
  70. package/dist/explain.js +129 -12
  71. package/dist/graph/engine.d.ts +92 -29
  72. package/dist/graph/engine.js +298 -148
  73. package/dist/graph/expr.d.ts +6 -3
  74. package/dist/graph/expr.js +18 -8
  75. package/dist/graph/outputs.d.ts +23 -0
  76. package/dist/graph/outputs.js +41 -0
  77. package/dist/graph/packages.d.ts +72 -0
  78. package/dist/graph/packages.js +261 -0
  79. package/dist/graph/parallel.d.ts +3 -1
  80. package/dist/graph/parallel.js +4 -1
  81. package/dist/graph/params.d.ts +6 -0
  82. package/dist/graph/params.js +34 -7
  83. package/dist/graph/scope.d.ts +55 -0
  84. package/dist/graph/scope.js +14 -0
  85. package/dist/graph/types.d.ts +75 -12
  86. package/dist/graph/types.js +4 -2
  87. package/dist/graph/vars.d.ts +16 -0
  88. package/dist/graph/vars.js +80 -0
  89. package/dist/host/artifacts.d.ts +10 -1
  90. package/dist/host/artifacts.js +37 -6
  91. package/dist/host/cook.d.ts +241 -0
  92. package/dist/host/cook.js +844 -0
  93. package/dist/host/export-targets.d.ts +42 -5
  94. package/dist/host/export-targets.js +72 -13
  95. package/dist/host/godot-commands.d.ts +4 -0
  96. package/dist/host/godot-commands.js +21 -0
  97. package/dist/host/godot.d.ts +183 -0
  98. package/dist/host/godot.js +916 -0
  99. package/dist/host/node.d.ts +12 -7
  100. package/dist/host/node.js +27 -9
  101. package/dist/host/pool.js +51 -2
  102. package/dist/host/sidecars.d.ts +8 -0
  103. package/dist/host/sidecars.js +50 -0
  104. package/dist/host/types.d.ts +19 -6
  105. package/dist/host/version.d.ts +1 -0
  106. package/dist/host/version.js +3 -0
  107. package/dist/host/worker.js +5 -2
  108. package/dist/index.d.ts +2 -2
  109. package/dist/index.js +1 -1
  110. package/dist/inspect.d.ts +80 -2
  111. package/dist/inspect.js +265 -30
  112. package/dist/io/common.d.ts +25 -5
  113. package/dist/io/export.js +2 -1
  114. package/dist/io/files.d.ts +23 -4
  115. package/dist/io/files.js +60 -8
  116. package/dist/io/gltf.js +134 -47
  117. package/dist/io/heightmap.d.ts +3 -0
  118. package/dist/io/heightmap.js +1 -0
  119. package/dist/io/import.js +10 -0
  120. package/dist/io/inspect-scene.d.ts +55 -0
  121. package/dist/io/inspect-scene.js +155 -0
  122. package/dist/io/kinds.d.ts +81 -0
  123. package/dist/io/kinds.js +163 -0
  124. package/dist/io/points.d.ts +2 -1
  125. package/dist/io/points.js +3 -1
  126. package/dist/io/sidecars.d.ts +24 -0
  127. package/dist/io/sidecars.js +57 -0
  128. package/dist/io/source.d.ts +65 -0
  129. package/dist/io/source.js +112 -0
  130. package/dist/io/targets.d.ts +47 -3
  131. package/dist/io/targets.js +148 -13
  132. package/dist/io/textures.js +21 -1
  133. package/dist/io/unreal.js +5 -1
  134. package/dist/mcp/docs.d.ts +10 -1
  135. package/dist/mcp/docs.js +786 -143
  136. package/dist/mcp/inputs.d.ts +12 -5
  137. package/dist/mcp/inputs.js +50 -13
  138. package/dist/mcp/server.js +56 -27
  139. package/dist/mcp/tools.d.ts +14 -7
  140. package/dist/mcp/tools.js +198 -103
  141. package/dist/mcp/verify.d.ts +2 -2
  142. package/dist/mcp/verify.js +1 -1
  143. package/dist/mcp/workspace.d.ts +15 -0
  144. package/dist/mcp/workspace.js +349 -0
  145. package/dist/nodes/attributes.js +198 -1
  146. package/dist/nodes/bake.js +151 -47
  147. package/dist/nodes/beam.d.ts +1 -0
  148. package/dist/nodes/beam.js +201 -0
  149. package/dist/nodes/bevel.js +51 -3
  150. package/dist/nodes/cloth.js +2 -0
  151. package/dist/nodes/code.js +21 -9
  152. package/dist/nodes/curves.js +433 -93
  153. package/dist/nodes/flow.js +53 -33
  154. package/dist/nodes/generate.js +12 -38
  155. package/dist/nodes/heightfield.js +248 -77
  156. package/dist/nodes/imageops.js +16 -19
  157. package/dist/nodes/index.d.ts +1 -0
  158. package/dist/nodes/index.js +1 -0
  159. package/dist/nodes/material.js +89 -24
  160. package/dist/nodes/measure.js +43 -17
  161. package/dist/nodes/particles.js +2 -0
  162. package/dist/nodes/pcg.js +6 -5
  163. package/dist/nodes/procedural.js +4 -3
  164. package/dist/nodes/remesh.js +71 -15
  165. package/dist/nodes/scene.js +4 -2
  166. package/dist/nodes/sdf.js +10 -5
  167. package/dist/nodes/solid.js +20 -5
  168. package/dist/nodes/splines.d.ts +15 -1
  169. package/dist/nodes/splines.js +112 -105
  170. package/dist/nodes/texture.d.ts +21 -6
  171. package/dist/nodes/texture.js +1318 -185
  172. package/dist/nodes/topology.d.ts +7 -0
  173. package/dist/nodes/topology.js +133 -6
  174. package/dist/nodes/transform.js +6 -2
  175. package/dist/nodes/uv.js +192 -174
  176. package/dist/nodes/wasmcall.js +5 -1
  177. package/dist/open.d.ts +19 -0
  178. package/dist/open.js +12 -0
  179. package/dist/package.d.ts +288 -0
  180. package/dist/package.js +772 -0
  181. package/dist/packages/check.d.ts +32 -0
  182. package/dist/packages/check.js +169 -0
  183. package/dist/packages/commands.d.ts +57 -0
  184. package/dist/packages/commands.js +537 -0
  185. package/dist/packages/registry.d.ts +796 -0
  186. package/dist/packages/registry.js +2998 -0
  187. package/dist/packages/update.d.ts +124 -0
  188. package/dist/packages/update.js +476 -0
  189. package/dist/render/options.d.ts +2 -0
  190. package/dist/render/options.js +57 -5
  191. package/dist/render/preview.d.ts +17 -4
  192. package/dist/render/preview.js +6 -4
  193. package/dist/render/raster.d.ts +74 -5
  194. package/dist/render/raster.js +527 -143
  195. package/dist/render/texview.d.ts +6 -0
  196. package/dist/render/texview.js +27 -0
  197. package/dist/scan.d.ts +61 -0
  198. package/dist/scan.js +228 -0
  199. package/dist/session.d.ts +311 -0
  200. package/dist/session.js +849 -0
  201. package/dist/viewer/app/api.js +48 -6
  202. package/dist/viewer/app/cooking.js +78 -0
  203. package/dist/viewer/app/embed.js +27 -7
  204. package/dist/viewer/app/export-popover.js +118 -16
  205. package/dist/viewer/app/grid.js +5 -1
  206. package/dist/viewer/app/guides.js +122 -0
  207. package/dist/viewer/app/keymap.js +6 -3
  208. package/dist/viewer/app/layers.js +4 -4
  209. package/dist/viewer/app/main.js +185 -52
  210. package/dist/viewer/app/markers.js +60 -0
  211. package/dist/viewer/app/outliner.js +72 -27
  212. package/dist/viewer/app/output-info.js +45 -0
  213. package/dist/viewer/app/outputs.css +147 -8
  214. package/dist/viewer/app/outputs.js +168 -54
  215. package/dist/viewer/app/packages.js +614 -0
  216. package/dist/viewer/app/props.js +176 -52
  217. package/dist/viewer/app/scene.js +30 -5
  218. package/dist/viewer/app/select.js +4 -3
  219. package/dist/viewer/app/status.js +12 -15
  220. package/dist/viewer/app/style.css +65 -7
  221. package/dist/viewer/app/vars.js +47 -0
  222. package/dist/viewer/app/welcome.js +72 -0
  223. package/dist/viewer/graph-file.d.ts +62 -0
  224. package/dist/viewer/graph-file.js +175 -0
  225. package/dist/viewer/index.html +23 -10
  226. package/dist/viewer/json-edit.d.ts +13 -0
  227. package/dist/viewer/json-edit.js +274 -0
  228. package/dist/viewer/outputs.d.ts +49 -5
  229. package/dist/viewer/outputs.js +264 -56
  230. package/dist/viewer/packages.d.ts +121 -0
  231. package/dist/viewer/packages.js +584 -0
  232. package/dist/viewer/server.d.ts +14 -9
  233. package/dist/viewer/server.js +266 -28
  234. package/dist/web/app/web.css +419 -0
  235. package/dist/web/app/web.js +188 -0
  236. package/dist/{gallery → web}/bake.d.ts +4 -4
  237. package/dist/{gallery → web}/bake.js +24 -15
  238. package/dist/web/folder-page.d.ts +101 -0
  239. package/dist/web/folder-page.js +146 -0
  240. package/dist/web/folders.d.ts +280 -0
  241. package/dist/web/folders.js +970 -0
  242. package/dist/web/library.d.ts +91 -0
  243. package/dist/web/library.js +228 -0
  244. package/dist/web/markdown.d.ts +45 -0
  245. package/dist/web/markdown.js +677 -0
  246. package/dist/web/pages.d.ts +258 -0
  247. package/dist/web/pages.js +301 -0
  248. package/dist/web/server.d.ts +24 -0
  249. package/dist/web/server.js +1068 -0
  250. package/dist/workspace.d.ts +88 -118
  251. package/dist/workspace.js +358 -460
  252. package/integrations/godot/addons/topotopo/LICENSE +202 -0
  253. package/integrations/godot/addons/topotopo/README.md +57 -0
  254. package/integrations/godot/addons/topotopo/context_menu.gd +43 -0
  255. package/integrations/godot/addons/topotopo/dock.gd +266 -0
  256. package/integrations/godot/addons/topotopo/dock.tscn +72 -0
  257. package/integrations/godot/addons/topotopo/export_filter.gd +72 -0
  258. package/integrations/godot/addons/topotopo/gltf_instancing.gd +131 -0
  259. package/integrations/godot/addons/topotopo/icons/topotopo.svg +1 -0
  260. package/integrations/godot/addons/topotopo/inspector.gd +38 -0
  261. package/integrations/godot/addons/topotopo/instances_post_import.gd +111 -0
  262. package/integrations/godot/addons/topotopo/package.gd +23 -0
  263. package/integrations/godot/addons/topotopo/package_importer.gd +187 -0
  264. package/integrations/godot/addons/topotopo/plugin.cfg +7 -0
  265. package/integrations/godot/addons/topotopo/plugin.gd +970 -0
  266. package/integrations/godot/addons/topotopo/record.gd +435 -0
  267. package/integrations/godot/addons/topotopo/runner.gd +458 -0
  268. package/integrations/godot/addons/topotopo/tools/check.gd +42 -0
  269. package/integrations/godot/addons/topotopo/watcher.gd +199 -0
  270. package/kernels/pkg/README.md +2 -1
  271. package/kernels/pkg-simd/README.md +2 -1
  272. package/library/architecture/versions/1.0/architecture.topo +12 -0
  273. package/{shelf → library/architecture/versions/1.0/graphs}/arch.json +3 -3
  274. package/{shelf → library/architecture/versions/1.0/graphs}/beam_truss.json +6 -6
  275. package/{shelf → library/architecture/versions/1.0/graphs}/brick_wall.json +8 -8
  276. package/{shelf → library/architecture/versions/1.0/graphs}/door_frame.json +3 -3
  277. package/{shelf → library/architecture/versions/1.0/graphs}/hex_grid_floor.json +3 -2
  278. package/{shelf → library/architecture/versions/1.0/graphs}/house.json +8 -8
  279. package/library/architecture/versions/1.0/graphs/lineup.json +42 -0
  280. package/{shelf → library/architecture/versions/1.0/graphs}/pillar.json +3 -2
  281. package/{shelf → library/architecture/versions/1.0/graphs}/railing.json +5 -5
  282. package/{shelf → library/architecture/versions/1.0/graphs}/roof_gable.json +2 -2
  283. package/{shelf → library/architecture/versions/1.0/graphs}/roof_hip.json +2 -2
  284. package/{shelf → library/architecture/versions/1.0/graphs}/roof_skeleton.json +2 -1
  285. package/{shelf → library/architecture/versions/1.0/graphs}/scaffold.json +4 -4
  286. package/{shelf → library/architecture/versions/1.0/graphs}/spiral_stairs.json +3 -2
  287. package/{shelf → library/architecture/versions/1.0/graphs}/stairs.json +6 -6
  288. package/{shelf → library/architecture/versions/1.0/graphs}/tile_floor.json +3 -2
  289. package/{shelf → library/architecture/versions/1.0/graphs}/wall_segment.json +10 -10
  290. package/{shelf → library/architecture/versions/1.0/graphs}/window_frame.json +2 -2
  291. package/library/architecture/versions/1.0/version.json +1119 -0
  292. package/{shelf → library/nature/versions/1.0/graphs}/bush.json +2 -2
  293. package/{shelf → library/nature/versions/1.0/graphs}/cliff_block.json +4 -3
  294. package/{shelf → library/nature/versions/1.0/graphs}/forest_patch.json +5 -5
  295. package/{shelf → library/nature/versions/1.0/graphs}/grass_clumps.json +2 -2
  296. package/library/nature/versions/1.0/graphs/lineup.json +24 -0
  297. package/{shelf → library/nature/versions/1.0/graphs}/log.json +6 -6
  298. package/{shelf → library/nature/versions/1.0/graphs}/rock.json +5 -4
  299. package/{shelf → library/nature/versions/1.0/graphs}/scatter_rocks.json +5 -5
  300. package/{shelf → library/nature/versions/1.0/graphs}/tree_lowpoly.json +3 -2
  301. package/library/nature/versions/1.0/nature.topo +12 -0
  302. package/library/nature/versions/1.0/version.json +534 -0
  303. package/{shelf → library/props/versions/1.0/graphs}/barrel.json +5 -4
  304. package/{shelf → library/props/versions/1.0/graphs}/crate.json +3 -3
  305. package/library/props/versions/1.0/graphs/lineup.json +18 -0
  306. package/{shelf → library/props/versions/1.0/graphs}/pallet.json +4 -3
  307. package/{shelf → library/props/versions/1.0/graphs}/pipe_run.json +3 -3
  308. package/{shelf → library/props/versions/1.0/graphs}/sandbag_wall.json +5 -5
  309. package/library/props/versions/1.0/props.topo +12 -0
  310. package/library/props/versions/1.0/version.json +336 -0
  311. package/{shelf → library/street/versions/1.0/graphs}/bench.json +5 -5
  312. package/{shelf → library/street/versions/1.0/graphs}/bollard.json +2 -1
  313. package/{shelf → library/street/versions/1.0/graphs}/cable.json +4 -4
  314. package/{shelf → library/street/versions/1.0/graphs}/fence.json +7 -7
  315. package/{shelf → library/street/versions/1.0/graphs}/lamp_post.json +2 -2
  316. package/library/street/versions/1.0/graphs/lineup.json +22 -0
  317. package/{shelf → library/street/versions/1.0/graphs}/road_strip.json +2 -2
  318. package/{shelf → library/street/versions/1.0/graphs}/sign_post.json +1 -1
  319. package/library/street/versions/1.0/street.topo +12 -0
  320. package/library/street/versions/1.0/version.json +421 -0
  321. package/package.json +13 -8
  322. package/dist/gallery/app/gallery.css +0 -100
  323. package/dist/gallery/app/gallery.js +0 -80
  324. package/dist/gallery/cli.d.ts +0 -4
  325. package/dist/gallery/cli.js +0 -157
  326. package/dist/gallery/library.d.ts +0 -124
  327. package/dist/gallery/library.js +0 -366
  328. package/dist/gallery/pages.d.ts +0 -94
  329. package/dist/gallery/pages.js +0 -148
  330. package/dist/gallery/server.d.ts +0 -21
  331. package/dist/gallery/server.js +0 -391
  332. package/dist/graph/migrate.d.ts +0 -23
  333. package/dist/graph/migrate.js +0 -58
  334. package/dist/mcp/library.d.ts +0 -12
  335. package/dist/mcp/library.js +0 -159
  336. package/shelf/index.json +0 -190
@@ -1,8 +1,11 @@
1
1
  // Graph evaluation: validation, lazy pull-based cooking, content-addressed caching, time.
2
2
  //
3
3
  // Every node result is keyed by a signature = hash(type, resolved params, input
4
- // signatures[, vars][, expression references]). Editing one parameter therefore re-cooks only the nodes
5
- // downstream of it, and identical sub-results (e.g. loop iterations) are shared.
4
+ // signatures[, the vars its code reads][, expression references][, the node's name, for a node that names its result
5
+ // after itself: NodeDef.usesNodeName]). Editing one parameter therefore re-cooks
6
+ // only the nodes downstream of it, and identical sub-results (e.g. loop iterations) are shared. "=expr" params
7
+ // are keyed by their values; code reads vars by their bare name, so a code node is keyed by the vars its code
8
+ // names (NodeDef.usesVars), and changing another var leaves it cached.
6
9
  //
7
10
  // Time: a cook happens at a frame (frame 1 = time 0). A node is time-dependent when its def says so
8
11
  // (usesTime), when one of its "=expr" params reads frame/time/fps/timeInc, or when its cook reads
@@ -16,6 +19,14 @@
16
19
  // are validated (unknown names, cycles), cooked before the param is resolved, and their signatures
17
20
  // (or, for ch(), the referenced value) are mixed into the dependent node's signature.
18
21
  //
22
+ // Scopes (src/graph/scope.ts): a cook runs in a scope, which gives it its node types, the graphs graph_ref reads and
23
+ // the files nodes read; nested cooks inherit it. The cache is shared by all scopes: outside the root scope, a node
24
+ // whose result depends on its scope has the scope's id in its signature. It depends on it when it reads it: its
25
+ // signatureExtra reads the scope it is given (a file's stamp), or its cook reads ctx.scope or cooks a nested graph in
26
+ // it (ctx.subcook without a scope of its own). That is found as time dependence is, and remembered per signature
27
+ // (scopeDeps); NodeDef.usesScope says it up front. A node type with a slash is a package output
28
+ // (src/graph/packages.ts), which only the scope's packages resolve.
29
+ //
19
30
  // Concurrency: when the host has a worker pool (Engine.concurrent), the inputs of a node (and the nodes its
20
31
  // expressions reference) are pulled at once, so independent branches overlap wherever a cook awaits (a chunked
21
32
  // kernel on the pool, file I/O). Cooks of one signature that are in flight at the same time share one cook
@@ -24,14 +35,19 @@
24
35
  // on the pool. Without a pool everything is pulled one input at a time, as before.
25
36
  import { Geometry, isGeometry } from '../core/geometry.js';
26
37
  import { DEFAULT_TRANSFER, expandPacked } from '../core/packed.js';
38
+ import { primIntrinsic } from '../core/intrinsics.js';
27
39
  import { splinesToPolylines } from '../core/splines.js';
28
40
  import { hashString } from '../core/random.js';
29
- import { targetError } from '../io/targets.js';
41
+ import { targetError, targetWarning } from '../io/targets.js';
30
42
  import { allAliases, getNodeDef } from './registry.js';
31
43
  import { DeferredExpr, REF_FUNCS, didYouMean, hasRefs, resolveParamName, resolveParams, scanNodeRefs, scanValue, vecOut, } from './params.js';
32
- import { migrateGraphDetailed } from './migrate.js';
44
+ import { outputFieldIssues } from './outputs.js';
33
45
  import { parallelMap as runKernel } from './parallel.js';
34
- import { NodeError } from './types.js';
46
+ import { parsePackageName, scopeSig } from './scope.js';
47
+ import { NodeError, STOPPED } from './types.js';
48
+ import { VAR_NAME_HINT, varNameError } from './vars.js';
49
+ import { codeVarNames, pickVars } from '../core/usercode.js';
50
+ export { STOPPED };
35
51
  // ---------------------------------------------------------------- cache
36
52
  function geoBytes(g) {
37
53
  let b = g.primStart.byteLength + g.vertexPoint.byteLength + g.primClosed.byteLength + 256;
@@ -111,6 +127,18 @@ export function resolveTime(o = {}) {
111
127
  return { frame, time, fps, timeInc: inc !== undefined && inc > 0 ? inc : 1 / fps };
112
128
  }
113
129
  const timeKey = (t) => `T:${t.frame}:${t.time}:${t.fps}:${t.timeInc}`;
130
+ /**
131
+ * A scope that calls `read` when what it holds is read: its assets, graphs, files or packages (what a node is given, in
132
+ * signatureExtra and as CookContext.scope: Engine.scopeDeps). Its id alone does not count: a node that reads it keys
133
+ * its result by it itself.
134
+ */
135
+ const watchScope = (s, read) => ({
136
+ get id() { return s.id; },
137
+ get assets() { read(); return s.assets; },
138
+ get graphs() { read(); return s.graphs; },
139
+ get files() { read(); return s.files; },
140
+ get packages() { read(); return s.packages; },
141
+ });
114
142
  /** Normalise `in` wiring into an ordered list of node names (null = unconnected). */
115
143
  export function wiringOf(spec, def) {
116
144
  const errors = [];
@@ -141,6 +169,8 @@ export function wiringOf(spec, def) {
141
169
  function inferParamType(meta, v) {
142
170
  if (meta?.type)
143
171
  return meta.type;
172
+ if (Array.isArray(meta?.options) && meta.options.length)
173
+ return 'enum';
144
174
  if (typeof v === 'boolean')
145
175
  return 'bool';
146
176
  if (typeof v === 'number')
@@ -157,6 +187,30 @@ function inferParamType(meta, v) {
157
187
  }
158
188
  return 'json';
159
189
  }
190
+ /**
191
+ * A graph as a node type (an asset, a package output): its vars are the params, with their "params" declarations, and
192
+ * its input nodes the inputs, by their index.
193
+ */
194
+ export function graphInterface(graph) {
195
+ const params = {};
196
+ for (const [k, v] of Object.entries(graph.vars ?? {})) {
197
+ const meta = graph.params?.[k] ?? {};
198
+ params[k] = {
199
+ type: inferParamType(meta, v), default: v, desc: meta.desc ?? '',
200
+ min: meta.min, max: meta.max, options: meta.options,
201
+ };
202
+ }
203
+ let nIn = 0;
204
+ const inputDescs = [];
205
+ for (const n of Object.values(graph.nodes)) {
206
+ if (typeof n?.type === 'string' && getNodeDef(n.type)?.type === 'input') {
207
+ const idx = Number(n.params?.index ?? 0);
208
+ nIn = Math.max(nIn, idx + 1);
209
+ inputDescs[idx] = n.params?.label ?? n.note ?? '';
210
+ }
211
+ }
212
+ return { params, inputs: Array.from({ length: nIn }, (_, i) => ({ name: `input${i}`, desc: inputDescs[i] || `subgraph input ${i}`, optional: true })) };
213
+ }
160
214
  /** Implementations of the expression reference functions, bound to the referenced results of one node. */
161
215
  function refFunctions(geo, chp) {
162
216
  const G = (fn, n) => {
@@ -226,6 +280,20 @@ function refFunctions(geo, chp) {
226
280
  },
227
281
  point: (n, i, attr, c) => elem('point', 'point', n, i, attr, c),
228
282
  prim: (n, i, attr, c) => elem('prim', 'prim', n, i, attr, c),
283
+ primintrinsic: (n, i, name, c) => {
284
+ const g = G('primintrinsic', n);
285
+ const call = `primintrinsic("${n}", ${i}, ${JSON.stringify(name)})`;
286
+ if (typeof name !== 'string')
287
+ throw new Error(`${call}: the intrinsic name must be a string`);
288
+ let v;
289
+ try {
290
+ v = primIntrinsic(g, i, name);
291
+ }
292
+ catch (e) {
293
+ throw new Error(`${call}: ${e.message}`);
294
+ }
295
+ return comp(v, c, call);
296
+ },
229
297
  ch: (a, b) => {
230
298
  let node = a, param = b;
231
299
  if (b === undefined && typeof a === 'string') {
@@ -251,9 +319,12 @@ const PSUF = '\u0000params';
251
319
  export class Engine {
252
320
  host;
253
321
  cache = new GeoCache();
254
- assets = new Map();
322
+ /** the package's scope: the assets, graphs and files of every cook that is not given another (CookOptions.scope) */
323
+ root;
255
324
  /** base signatures of nodes found to depend on time while cooking */
256
325
  timeDeps = new Set();
326
+ /** signatures (without the scope) of nodes found to read their scope: their results are keyed by the scope's id */
327
+ scopeDeps = new Set();
257
328
  /** manifold-3d wasm module, loaded by init() */
258
329
  manifold = null;
259
330
  maxDepth = 24;
@@ -270,13 +341,9 @@ export class Engine {
270
341
  poolStats = { parallel: 0, serial: 0, chunks: 0 };
271
342
  /** cooks in progress by signature: a second cook of the same signature waits for the first */
272
343
  inflight = new Map();
273
- /** shelf assets as shipped (name → graph), kept so that deleting a workspace override restores them */
274
- shelf = new Map();
275
- /** problems found while loading the shelf (unreadable index or files, invalid graphs) */
276
- shelfErrors = [];
277
- shelfLoaded = false;
278
344
  constructor(host) {
279
345
  this.host = host;
346
+ this.root = { id: '', assets: new Map(), files: host };
280
347
  this.concurrent = !!host.pool && host.pool.size > 0;
281
348
  }
282
349
  async init() {
@@ -286,116 +353,91 @@ export class Engine {
286
353
  const { MeshoptSimplifier } = await import('meshoptimizer');
287
354
  await MeshoptSimplifier.ready;
288
355
  }
289
- if (!this.shelfLoaded && this.host.shelfPath)
290
- await this.loadShelf(this.host.shelfPath);
291
356
  }
292
357
  /**
293
- * Register the shipped asset shelf as node types of category "shelf". `<base>/index.json` lists the asset files
294
- * ({"assets": [{"name", "file"}]}, dependencies first); everything is read through the Host, so a browser host
295
- * serves the same directory over HTTP. Workspace assets with the same name take precedence: they replace the shelf
296
- * entry when registered, and a (re)load of the shelf never replaces them.
358
+ * A node type in a scope: its own assets, then the built-in nodes. A name with a slash is a package output, which
359
+ * only the scope's packages resolve (packageIssue says why one does not).
297
360
  */
298
- async loadShelf(base) {
299
- this.shelfLoaded = true;
300
- const dec = new TextDecoder();
301
- const at = (f) => base.replace(/[\\/]+$/, '') + '/' + f;
302
- const errors = [];
303
- let entries = [];
304
- try {
305
- const index = JSON.parse(dec.decode(await this.host.readFile(at('index.json'))));
306
- entries = (Array.isArray(index) ? index : index.assets ?? []).map((e) => typeof e === 'string' ? { name: e.replace(/\.json$/, ''), file: e } : { name: e.name ?? String(e.file).replace(/\.json$/, ''), file: e.file ?? `${e.name}.json` });
307
- }
308
- catch (e) {
309
- errors.push(`shelf index ${at('index.json')}: ${e.message}`);
310
- }
311
- let pending = [];
312
- for (const { name, file } of entries) {
313
- try {
314
- pending.push({ name, graph: JSON.parse(dec.decode(await this.host.readFile(at(file)))) });
315
- }
316
- catch (e) {
317
- errors.push(`${file}: ${e.message}`);
318
- }
319
- }
320
- // register in index order; an asset that uses a shelf asset listed after it is retried until nothing changes
321
- let loaded = 0;
322
- for (let pass = 0; pending.length; pass++) {
323
- const failed = [];
324
- for (const { name, graph } of pending) {
325
- this.shelf.set(name, graph);
326
- const cur = this.assets.get(name);
327
- if (cur && cur.def.category !== 'shelf')
328
- continue; // a workspace asset overrides it
329
- try {
330
- this.registerAsset(name, graph, { category: 'shelf' });
331
- loaded++;
332
- }
333
- catch (e) {
334
- failed.push({ name, graph, error: e.message });
335
- }
336
- }
337
- if (failed.length === pending.length || pass > 8) {
338
- for (const f of failed) {
339
- this.shelf.delete(f.name);
340
- errors.push(`${f.name}: ${f.error}`);
341
- }
342
- break;
343
- }
344
- pending = failed;
345
- }
346
- this.shelfErrors = errors;
347
- return { loaded, errors };
348
- }
349
- resolveDef(type) {
361
+ resolveDef(type, scope = this.root) {
350
362
  if (typeof type !== 'string')
351
363
  return undefined;
352
- const a = this.assets.get(type) ?? this.assets.get(type.replace(/^asset:/, ''));
364
+ if (type.includes('/')) {
365
+ const r = scope.packages?.resolve(type);
366
+ return r && !('error' in r) ? r : undefined;
367
+ }
368
+ const a = this.asset(type, scope);
353
369
  if (a)
354
370
  return a.def;
355
371
  return getNodeDef(type);
356
372
  }
357
- allTypeNames() {
358
- return [...allAliases(), ...this.assets.keys()];
373
+ /** Why a name with a slash names no node type in a scope: a package the scope does not use, an unknown output … */
374
+ packageIssue(type, scope = this.root) {
375
+ const r = scope.packages?.resolve(type);
376
+ if (r && 'error' in r)
377
+ return r;
378
+ const n = parsePackageName(type);
379
+ if (typeof n === 'string')
380
+ return { error: n };
381
+ return { error: `"${type}" is an output of package ${n.package}, and this cook has no packages`, hint: 'a package uses packages (its manifest\'s "uses"); they are cooked by the TopoTopo CLI, viewer or MCP server' };
382
+ }
383
+ /**
384
+ * The names a did-you-mean offers in a scope: node types and their aliases, its assets, the package outputs it uses,
385
+ * and those its packages offer (PackageResolver.offered), which a graph's first use adds.
386
+ */
387
+ allTypeNames(scope = this.root) {
388
+ return [...allAliases(), ...this.assetsIn(scope).map((a) => a.name), ...(scope.packages?.names() ?? []), ...(scope.packages?.offered?.() ?? []).map((d) => d.type)];
389
+ }
390
+ /**
391
+ * The node types of package outputs for the catalog and help: those a scope uses, then those its packages offer that
392
+ * it does not use yet (PackageResolver.offered: TopoTopo's own, which a graph's first use adds).
393
+ */
394
+ packageDefs(scope = this.root) {
395
+ const used = (scope.packages?.names() ?? []).map((n) => this.resolveDef(n, scope)).filter((d) => !!d);
396
+ const have = new Set(used.map((d) => d.type));
397
+ return [...used, ...(scope.packages?.offered?.() ?? []).filter((d) => !have.has(d.type))];
398
+ }
399
+ /**
400
+ * A scope for cooks of its own (CookOptions.scope): its id (not "", which is the root's), the folder its relative
401
+ * paths read (absolute, or relative to the host's own; default: the host's files), the graphs graph_ref reads in it
402
+ * and the package outputs its graphs name. Register its assets with registerAsset(name, graph, {scope}), or give it
403
+ * another scope's (`assets`: a scope like that one with other packages).
404
+ */
405
+ createScope(id, opts = {}) {
406
+ if (!id)
407
+ throw new Error('a scope needs an id ("" is the root scope\'s)');
408
+ if (opts.folder !== undefined && !this.host.filesAt)
409
+ throw new Error(`scope "${id}": the ${this.host.name} host has no file access for other folders (Host.filesAt)`);
410
+ return { id, assets: opts.assets ?? new Map(), graphs: opts.graphs, files: opts.folder === undefined ? this.host : this.host.filesAt(opts.folder), packages: opts.packages };
359
411
  }
360
412
  // ------------------------------------------------------------ assets
361
- /** Register a graph as a node type. category "shelf" marks shipped assets (see loadShelf); default "asset". */
413
+ /** The asset a name refers to in a scope: one of the scope's own. */
414
+ asset(name, scope = this.root) {
415
+ return scope.assets.get(name);
416
+ }
417
+ /** The assets a scope has, in the order they were registered. */
418
+ assetsIn(scope = this.root) {
419
+ return [...scope.assets.values()];
420
+ }
421
+ /** Register a graph as a node type, an asset of a scope (default: the root). The graph is validated in that scope. */
362
422
  registerAsset(name, graph, opts = {}) {
363
423
  if (!/^[A-Za-z_][\w]*$/.test(name))
364
424
  throw new Error(`asset name must be an identifier, got "${name}"`);
365
- if (getNodeDef(name) && !this.assets.has(name))
425
+ const scope = opts.scope ?? this.root;
426
+ if (getNodeDef(name) && !this.asset(name, scope))
366
427
  throw new Error(`"${name}" clashes with a built-in node type`);
367
- const category = opts.category ?? 'asset';
368
- graph = migrateGraphDetailed(graph).graph;
369
- const issues = this.validate(graph);
428
+ const issues = this.validate(graph, '', scope);
370
429
  if (issues.errors.length)
371
430
  throw new Error(`asset graph invalid: ${issues.errors.map((e) => `${e.node}: ${e.message}`).join('; ')}`);
372
431
  const hash = String(hashString(stableStringify(graph)));
373
- const params = {};
374
- for (const [k, v] of Object.entries(graph.vars ?? {})) {
375
- const meta = graph.params?.[k] ?? {};
376
- params[k] = {
377
- type: inferParamType(meta, v), default: v, desc: meta.desc ?? '',
378
- min: meta.min, max: meta.max, options: meta.options,
379
- };
380
- }
381
- let nIn = 0;
382
- const inputDescs = [];
383
- for (const n of Object.values(graph.nodes)) {
384
- if (getNodeDef(n.type)?.type === 'input') {
385
- const idx = Number(n.params?.index ?? 0);
386
- nIn = Math.max(nIn, idx + 1);
387
- inputDescs[idx] = n.params?.label ?? n.note ?? '';
388
- }
389
- }
390
- // shelf assets: the first sentence of the description is the catalog summary, the rest the long description
391
- const shelfDoc = category === 'shelf' && graph.description ? /^(.+?[.!?])\s+(.+)$/s.exec(graph.description) : null;
432
+ const { params, inputs } = graphInterface(graph);
392
433
  const def = {
393
434
  type: name,
394
- category,
395
- summary: shelfDoc?.[1] ?? graph.description ?? `${category === 'shelf' ? 'shelf' : 'user'} asset "${name}"`,
396
- ...(shelfDoc ? { description: shelfDoc[2] } : {}),
397
- inputs: Array.from({ length: nIn }, (_, i) => ({ name: `input${i}`, desc: inputDescs[i] || `subgraph input ${i}`, optional: true })),
435
+ category: 'asset',
436
+ summary: graph.description ?? `user asset "${name}"`,
437
+ inputs,
398
438
  params,
439
+ // the graph's node types resolve in the scope the asset cooks in
440
+ usesScope: true,
399
441
  signatureExtra: () => hash,
400
442
  // the asset's own nodes unpack what they need
401
443
  packed: 'keep',
@@ -412,13 +454,14 @@ export class Engine {
412
454
  },
413
455
  };
414
456
  // results of other graphs (and assets) that used the previous definition are cached under unchanged keys
415
- if (this.assets.has(name) && this.assets.get(name).hash !== hash)
457
+ const prev = this.asset(name, scope);
458
+ if (prev && prev.hash !== hash)
416
459
  this.cache.clear();
417
- this.assets.set(name, { name, graph, def, hash });
460
+ scope.assets.set(name, { name, graph, def, hash });
418
461
  return def;
419
462
  }
420
463
  // ------------------------------------------------------------ validation
421
- findOutput(graph) {
464
+ findOutput(graph, scope = this.root) {
422
465
  const names = Object.keys(graph.nodes ?? {});
423
466
  if (graph.output && graph.nodes[graph.output])
424
467
  return { name: graph.output };
@@ -427,7 +470,7 @@ export class Engine {
427
470
  return { name: named };
428
471
  const referenced = new Set();
429
472
  for (const n of names) {
430
- const def = this.resolveDef(graph.nodes[n].type);
473
+ const def = this.resolveDef(graph.nodes[n].type, scope);
431
474
  if (!def)
432
475
  continue;
433
476
  for (const r of wiringOf(graph.nodes[n], def).list)
@@ -447,7 +490,7 @@ export class Engine {
447
490
  note: leaves.length > 1 ? `several end nodes (${leaves.join(', ')}); displaying "${pick}". Set "output" or merge them.` : undefined,
448
491
  };
449
492
  }
450
- validate(graph, path = '') {
493
+ validate(graph, path = '', scope = this.root) {
451
494
  const errors = [], warnings = [];
452
495
  if (!graph || typeof graph !== 'object' || !graph.nodes || typeof graph.nodes !== 'object' || Array.isArray(graph.nodes)) {
453
496
  errors.push({ node: path || '(graph)', message: 'graph must be {"nodes": {"name": {"type": ..., "in": [...], "params": {...}}}, "output": "name"}' });
@@ -463,10 +506,20 @@ export class Engine {
463
506
  errors.push({ node: path || '(graph)', message: `named output "${id}" must reference an existing node and have an optional string label` });
464
507
  else if (out.export !== undefined && targetError(out.export))
465
508
  errors.push({ node: path || '(graph)', message: `named output "${id}": ${targetError(out.export)}` });
509
+ else if (out.publish !== undefined && typeof out.publish !== 'boolean')
510
+ errors.push({ node: path || '(graph)', message: `named output "${id}": "publish" must be true or false (false keeps it out of the published version), got ${JSON.stringify(out.publish)}` });
511
+ else
512
+ for (const i of outputFieldIssues(out))
513
+ errors.push({ node: path || '(graph)', message: `named output "${id}": ${i.message}`, hint: i.hint });
514
+ const w = out && typeof out === 'object' && out.export !== undefined && !targetError(out.export) ? targetWarning(out.export) : null;
515
+ if (w)
516
+ warnings.push({ node: path || '(graph)', message: `named output "${id}": ${w}` });
466
517
  }
467
518
  }
468
519
  if (graph.export !== undefined && targetError(graph.export))
469
520
  errors.push({ node: path || '(graph)', message: targetError(graph.export) });
521
+ else if (graph.export !== undefined && targetWarning(graph.export))
522
+ warnings.push({ node: path || '(graph)', message: targetWarning(graph.export) });
470
523
  if (!names.length)
471
524
  errors.push({ node: path || '(graph)', message: 'graph has no nodes' });
472
525
  if (graph.output && !graph.nodes[graph.output])
@@ -484,7 +537,26 @@ export class Engine {
484
537
  });
485
538
  }
486
539
  }
487
- const typeNames = this.allTypeNames();
540
+ // var names: expressions and code read vars by their bare name
541
+ const declared = new Set();
542
+ for (const o of [graph.vars, graph.params])
543
+ if (o && typeof o === 'object' && !Array.isArray(o))
544
+ for (const k of Object.keys(o))
545
+ declared.add(k);
546
+ for (const k of declared) {
547
+ const bad = varNameError(k);
548
+ if (bad)
549
+ errors.push({ node: path + '(vars)', message: bad, hint: VAR_NAME_HINT });
550
+ }
551
+ if (graph.params && typeof graph.params === 'object') {
552
+ for (const [k, vd] of Object.entries(graph.params)) {
553
+ const o = vd && typeof vd === 'object' ? vd.options : undefined;
554
+ if (o !== undefined && !(Array.isArray(o) && o.length && o.every((x) => typeof x === 'string' || (typeof x === 'number' && Number.isFinite(x)))))
555
+ errors.push({ node: path + '(params)', message: `params "${k}": options must be a list of strings or numbers, got ${JSON.stringify(o)?.slice(0, 80)}` });
556
+ }
557
+ }
558
+ // for did-you-mean, listed once a type is unknown (the package names load the scope's packages)
559
+ let typeNames = null;
488
560
  const refsOf = new Map();
489
561
  for (const name of names) {
490
562
  const spec = graph.nodes[name];
@@ -493,9 +565,14 @@ export class Engine {
493
565
  errors.push({ node: nm, message: 'node spec must be an object with a "type" string' });
494
566
  continue;
495
567
  }
496
- const def = this.resolveDef(spec.type);
568
+ const def = this.resolveDef(spec.type, scope);
497
569
  if (!def) {
498
- const s = didYouMean(spec.type, typeNames);
570
+ if (spec.type.includes('/')) {
571
+ const p = this.packageIssue(spec.type, scope);
572
+ errors.push({ node: nm, message: p.error, ...(p.hint ? { hint: p.hint } : {}) });
573
+ continue;
574
+ }
575
+ const s = didYouMean(spec.type, typeNames ??= this.allTypeNames(scope));
499
576
  errors.push({ node: nm, message: `unknown node type "${spec.type}"${s.length ? ` — did you mean ${s.join(', ')}?` : ''}`, hint: 'use the catalog tool to list node types' });
500
577
  continue;
501
578
  }
@@ -523,10 +600,12 @@ export class Engine {
523
600
  }
524
601
  for (const k of Object.keys(spec.params ?? {})) {
525
602
  if (!resolveParamName(def, k)) {
526
- const s = didYouMean(k, Object.keys(def.params));
603
+ // a renamed or removed param says what to write now (NodeDef.renamed)
604
+ const now = def.renamed?.[k];
605
+ const s = now ? [] : didYouMean(k, Object.keys(def.params));
527
606
  errors.push({
528
607
  node: nm,
529
- message: `unknown param "${k}" for ${def.type}${s.length ? ` — did you mean ${s.map((x) => `"${x}"`).join(' or ')}?` : ''}`,
608
+ message: `unknown param "${k}" for ${def.type}${now ? `: ${now}` : s.length ? ` — did you mean ${s.map((x) => `"${x}"`).join(' or ')}?` : ''}`,
530
609
  hint: `valid params: ${Object.keys(def.params).join(', ') || '(none)'}`,
531
610
  });
532
611
  }
@@ -549,7 +628,7 @@ export class Engine {
549
628
  errors.push({ node: nm, message: `ch("${c.node}/${c.param}") references unknown node "${c.node}"${s.length ? ` — did you mean ${s.join(', ')}?` : ''}`, hint: `nodes in this graph: ${names.join(', ')}` });
550
629
  continue;
551
630
  }
552
- const tdef = typeof target === 'object' && target ? this.resolveDef(target.type) : undefined;
631
+ const tdef = typeof target === 'object' && target ? this.resolveDef(target.type, scope) : undefined;
553
632
  if (tdef && !resolveParamName(tdef, c.param)) {
554
633
  const s = didYouMean(c.param, Object.keys(tdef.params));
555
634
  errors.push({
@@ -566,7 +645,7 @@ export class Engine {
566
645
  const key = Object.keys(spec.params ?? {}).find((k) => resolveParamName(def, k) === pk);
567
646
  const sub = key ? spec.params[key] : undefined;
568
647
  if (sub) {
569
- const r = this.validate(sub, `${nm}/`);
648
+ const r = this.validate(sub, `${nm}/`, scope);
570
649
  errors.push(...r.errors);
571
650
  warnings.push(...r.warnings);
572
651
  }
@@ -583,7 +662,7 @@ export class Engine {
583
662
  }
584
663
  const out = [];
585
664
  const spec = graph.nodes[v];
586
- const def = spec && this.resolveDef(spec.type);
665
+ const def = spec && this.resolveDef(spec.type, scope);
587
666
  if (def)
588
667
  for (const r of wiringOf(spec, def).list)
589
668
  if (r && graph.nodes[r])
@@ -619,17 +698,15 @@ export class Engine {
619
698
  return { errors, warnings };
620
699
  }
621
700
  /** Validate and resolve all params without cooking. */
622
- dryRun(graph, vars) {
623
- const mig = migrateGraphDetailed(graph);
624
- graph = mig.graph;
625
- const v = this.validate(graph);
626
- const notes = [...mig.notes];
701
+ dryRun(graph, vars, scope = this.root) {
702
+ const v = this.validate(graph, '', scope);
703
+ const notes = [];
627
704
  const allVars = { ...(graph.vars ?? {}), ...(vars ?? {}) };
628
705
  if (!v.errors.length) {
629
706
  // reference functions need cooked nodes: their params are reported as deferred
630
707
  const deferred = Object.fromEntries(REF_FUNCS.map((f) => [f, () => { throw new DeferredExpr(f); }]));
631
708
  for (const [name, spec] of Object.entries(graph.nodes)) {
632
- const def = this.resolveDef(spec.type);
709
+ const def = this.resolveDef(spec.type, scope);
633
710
  const r = resolveParams(def, spec.params, allVars, { fns: deferred, host: this.host, timeoutMs: this.scriptTimeoutMs });
634
711
  for (const e of r.errors)
635
712
  if (!e.startsWith('unknown param'))
@@ -644,7 +721,7 @@ export class Engine {
644
721
  notes.push(`${name}: "${def.type}" is deprecated — ${def.deprecated}`);
645
722
  }
646
723
  }
647
- const out = v.errors.length ? { name: graph.output ?? '' } : this.findOutput(graph);
724
+ const out = v.errors.length ? { name: graph.output ?? '' } : this.findOutput(graph, scope);
648
725
  if (out.note)
649
726
  notes.push(out.note);
650
727
  return { ...v, notes, output: out.name };
@@ -672,27 +749,19 @@ export class Engine {
672
749
  report.frame = time.frame;
673
750
  report.time = time.time;
674
751
  report.fps = time.fps;
675
- if (depth === 0) {
676
- // documents are migrated once; nested graphs belong to their parent document
677
- try {
678
- const m = migrateGraphDetailed(graph);
679
- graph = m.graph;
680
- report.notes.push(...m.notes);
681
- }
682
- catch (e) {
683
- report.errors.push({ node: '(graph)', message: e.message });
684
- return report;
685
- }
686
- }
687
- const v = this.validate(graph);
752
+ const scope = opts.scope ?? this.root;
753
+ const v = this.validate(graph, '', scope);
688
754
  if (v.errors.length) {
689
755
  report.errors = v.errors;
690
756
  report.ms = now() - t0;
691
757
  return report;
692
758
  }
759
+ // what validating warns of (an export target written with a prefix that is gone) is said with the cook
760
+ if (!depth)
761
+ report.warnings.push(...v.warnings);
693
762
  let target = opts.target;
694
763
  if (target === undefined) {
695
- const o = this.findOutput(graph);
764
+ const o = this.findOutput(graph, scope);
696
765
  target = o.name;
697
766
  if (o.note)
698
767
  report.notes.push(o.note);
@@ -706,7 +775,7 @@ export class Engine {
706
775
  const memo = new Map();
707
776
  const pmemo = new Map();
708
777
  const s = {
709
- graph, opts, time, depth, report, memo, pmemo, pdone: new Map(), shared: [],
778
+ graph, opts, scope, time, depth, report, memo, pmemo, pdone: new Map(), shared: [],
710
779
  vars: { ...(graph.vars ?? {}), ...(opts.vars ?? {}) },
711
780
  pull: (name) => {
712
781
  let pr = memo.get(name);
@@ -746,6 +815,9 @@ export class Engine {
746
815
  report.ok = !res.error;
747
816
  report.geo = res.geo;
748
817
  report.timeDependent = res.timeDependent;
818
+ // a failure after a stop is the stop's doing: the first node that did not cook (a nested stop fails its parent)
819
+ if (!report.ok && opts.signal?.aborted)
820
+ report.stopped = (report.errors.find((e) => e.message === STOPPED) ?? report.errors[0])?.node ?? target;
749
821
  report.ms = now() - t0;
750
822
  return report;
751
823
  }
@@ -757,7 +829,6 @@ export class Engine {
757
829
  if (!(range.end >= range.start))
758
830
  throw new Error(`frame range end (${range.end}) is before start (${range.start})`);
759
831
  const n = Math.floor((range.end - range.start) / step + 1e-9) + 1;
760
- graph = migrateGraphDetailed(graph).graph;
761
832
  const failed = [];
762
833
  for (let i = 0; i < n; i++) {
763
834
  const frame = r9(range.start + i * step);
@@ -771,7 +842,7 @@ export class Engine {
771
842
  /** Resolve a node's params, cooking the nodes its expressions reference first. */
772
843
  async nodeParams(s, name) {
773
844
  const spec = s.graph.nodes[name];
774
- const def = this.resolveDef(spec.type);
845
+ const def = this.resolveDef(spec.type, s.scope);
775
846
  const refs = scanNodeRefs(def, spec.params);
776
847
  if (!hasRefs(refs)) {
777
848
  const rp = resolveParams(def, spec.params, s.vars, { time: s.time, host: this.host, timeoutMs: this.scriptTimeoutMs });
@@ -798,7 +869,7 @@ export class Engine {
798
869
  const msg = np.error ?? np.rp.errors.join('; ');
799
870
  if (msg)
800
871
  return fail(`ch("${c.node}/${c.param}"): node "${c.node}" has param errors: ${msg}`);
801
- chp.set(c.node, { def: this.resolveDef(s.graph.nodes[c.node].type), values: np.rp.values });
872
+ chp.set(c.node, { def: this.resolveDef(s.graph.nodes[c.node].type, s.scope), values: np.rp.values });
802
873
  usesTime ||= np.usesTime;
803
874
  depTime ||= np.depsTimeDependent;
804
875
  }
@@ -811,9 +882,9 @@ export class Engine {
811
882
  }
812
883
  /** Cook a single node of a graph (pulling inputs and referenced nodes through the session). */
813
884
  async cookOne(s, name) {
814
- const { graph, vars, opts, time, depth, report } = s;
885
+ const { graph, vars, opts, scope, time, depth, report } = s;
815
886
  const spec = graph.nodes[name];
816
- const def = this.resolveDef(spec.type);
887
+ const def = this.resolveDef(spec.type, scope);
817
888
  const result = { node: name, geo: null, sig: '', ms: 0, cached: false, warnings: [], timeDependent: false };
818
889
  report.results.set(name, result);
819
890
  if (def.deprecated)
@@ -884,16 +955,28 @@ export class Engine {
884
955
  result.warnings.push('bypassed');
885
956
  return result;
886
957
  }
958
+ // the scope a node reads, through signatureExtra (a file's stamp) or while it cooks (ctx.scope, a nested cook in
959
+ // it), keys its result outside the root scope (scopeSig); found once, remembered for its signature (scopeDeps)
960
+ let readScope = !!def.usesScope, readScopeCooking = false;
887
961
  let extra = '';
888
962
  try {
889
- extra = def.signatureExtra?.(rp.values, this) ?? '';
963
+ extra = def.signatureExtra?.(rp.values, watchScope(scope, () => { readScope = true; })) ?? '';
890
964
  }
891
965
  catch (e) {
892
966
  result.error = { node: name, message: e.message };
893
967
  return result;
894
968
  }
895
- const baseSig = String(hashString(def.type + '|' + stableStringify(rp.values) + '|' + inputSigs.join(',') + '|' +
896
- (def.usesVars ? stableStringify(vars) : '') + '|' + extra + (np.refSig ? '|R:' + np.refSig : '')));
969
+ // vars read by the node's code: all of them (loop bodies, scripts), or those its code names
970
+ const varsSig = def.usesVars === true ? stableStringify(vars)
971
+ : typeof def.usesVars === 'function' ? stableStringify(pickVars(vars, codeVarNames(def.usesVars(rp.values), vars))) : '';
972
+ // a result named after its node (an image's default name) is not shared with an identical node of another name
973
+ const nameSig = def.usesNodeName && (def.usesNodeName === true || def.usesNodeName(rp.values)) ? '|N:' + name : '';
974
+ const material = def.type + '|' + stableStringify(rp.values) + '|' + inputSigs.join(',') + '|' + varsSig + '|' + extra + (np.refSig ? '|R:' + np.refSig : '') + nameSig;
975
+ const plainSig = String(hashString(material));
976
+ if (this.scopeDeps.has(plainSig))
977
+ readScope = true;
978
+ const scopedSig = () => (scopeSig(scope) ? String(hashString(material + scopeSig(scope))) : plainSig);
979
+ let baseSig = readScope ? scopedSig() : plainSig;
897
980
  const timeSig = () => String(hashString(baseSig + '|' + timeKey(time)));
898
981
  let timeDep = !!def.usesTime || np.usesTime || this.timeDeps.has(baseSig);
899
982
  let sig = timeDep ? timeSig() : baseSig;
@@ -905,6 +988,36 @@ export class Engine {
905
988
  result.cached = true;
906
989
  return result;
907
990
  }
991
+ // about to cook: report it (the host may yield there), and stop here when the cook was asked to stop
992
+ const progress = opts.onNode ? { phase: 'start', node: name, type: def.type, depth, within: opts.within ?? [] } : null;
993
+ // a progress hook that throws must not break the cook
994
+ const ended = (ms, error) => {
995
+ if (progress)
996
+ try {
997
+ void opts.onNode({ ...progress, phase: 'end', ms, ...(error ? { error } : {}) });
998
+ }
999
+ catch { /* ignore */ }
1000
+ };
1001
+ if (progress)
1002
+ try {
1003
+ await opts.onNode(progress);
1004
+ }
1005
+ catch { /* ignore */ }
1006
+ if (opts.signal?.aborted) {
1007
+ result.error = { node: name, message: STOPPED };
1008
+ ended(0, STOPPED);
1009
+ return result;
1010
+ }
1011
+ if (progress) {
1012
+ // while the host had the thread, another cook may have made this result
1013
+ const made = this.cache.get(sig);
1014
+ if (made) {
1015
+ result.geo = made;
1016
+ result.cached = true;
1017
+ ended(0);
1018
+ return result;
1019
+ }
1020
+ }
908
1021
  // the same signature is cooking elsewhere (another branch, an identical node, another iteration): share that cook
909
1022
  const key = sig;
910
1023
  const flight = this.inflight.get(key);
@@ -916,9 +1029,15 @@ export class Engine {
916
1029
  result.timeDependent = d.timeDep || depTime;
917
1030
  result.cached = true;
918
1031
  s.shared.push({ leader: flight.result, waiter: result });
1032
+ ended(0);
1033
+ return result;
1034
+ }
1035
+ // it failed: cook here again, as a cook that came after it would (unless this cook was stopped meanwhile)
1036
+ if (opts.signal?.aborted) {
1037
+ result.error = { node: name, message: STOPPED };
1038
+ ended(0, STOPPED);
919
1039
  return result;
920
1040
  }
921
- // it failed: cook here again, as a cook that came after it would
922
1041
  }
923
1042
  let land;
924
1043
  const mine = { done: new Promise((r) => { land = r; }), result };
@@ -939,6 +1058,7 @@ export class Engine {
939
1058
  warn: (m) => result.warnings.push(m),
940
1059
  vars,
941
1060
  engine: this,
1061
+ scope: watchScope(scope, () => { readScopeCooking = true; }),
942
1062
  inputSigs,
943
1063
  depth,
944
1064
  get frame() { mark(); return time.frame; },
@@ -946,9 +1066,17 @@ export class Engine {
946
1066
  get fps() { mark(); return time.fps; },
947
1067
  get timeInc() { mark(); return time.timeInc; },
948
1068
  markTimeDependent: mark,
1069
+ signal: opts.signal,
949
1070
  async subcook(g, o = {}) {
950
1071
  const inherit = o.frame === undefined && o.time === undefined ? { frame: time.frame, time: time.time, timeInc: time.timeInc } : {};
951
- const r = await engine.cook(g, { fps: time.fps, ...inherit, ...o, depth: depth + 1, ancestors: chain() });
1072
+ // a nested cook in this cook's scope resolves its node types there
1073
+ if (!o.scope)
1074
+ readScopeCooking = true;
1075
+ // nested cooks report their nodes (inside this one), stop with this cook and run in its scope unless given one
1076
+ const r = await engine.cook(g, {
1077
+ fps: time.fps, ...inherit, ...o, depth: depth + 1, ancestors: chain(),
1078
+ onNode: opts.onNode, signal: opts.signal, within: [...(opts.within ?? []), name], scope: o.scope ?? scope,
1079
+ });
952
1080
  if (r.timeDependent)
953
1081
  mark();
954
1082
  return r;
@@ -967,7 +1095,17 @@ export class Engine {
967
1095
  return { geo: r.geo, sig: rr.sig, timeDependent: true };
968
1096
  },
969
1097
  stat: (k, v) => { (result.stats ??= {})[k] = v; },
970
- parallelMap: (kernel, job, o) => runKernel(engine.host.pool, kernel, job, o, engine.poolStats),
1098
+ // the node's pool tasks stop with the cook
1099
+ parallelMap: (kernel, job, o) => runKernel(engine.host.pool, kernel, job, opts.signal ? { ...o, signal: opts.signal } : o, engine.poolStats),
1100
+ async checkpoint() {
1101
+ if (progress)
1102
+ try {
1103
+ await opts.onNode({ ...progress, phase: 'step' });
1104
+ }
1105
+ catch { /* ignore */ }
1106
+ if (opts.signal?.aborted)
1107
+ throw new NodeError(STOPPED);
1108
+ },
971
1109
  };
972
1110
  try {
973
1111
  this.unpackInputs(def, rp.values, inputs, inputSigs, name, result);
@@ -975,6 +1113,17 @@ export class Engine {
975
1113
  if (!isGeometry(out))
976
1114
  throw new Error(`node returned ${out === null ? 'null' : typeof out} instead of geometry`);
977
1115
  checkFinite(out, result);
1116
+ if (readScopeCooking && !readScope) {
1117
+ // found to read its scope: remember it, and key this result by the scope (the root's key stays the same)
1118
+ if (this.scopeDeps.size > 100000) {
1119
+ this.scopeDeps.clear();
1120
+ this.cache.clear();
1121
+ }
1122
+ this.scopeDeps.add(plainSig);
1123
+ baseSig = scopedSig();
1124
+ sig = timeDep ? timeSig() : baseSig;
1125
+ result.sig = sig;
1126
+ }
978
1127
  if (readTime && !timeDep) {
979
1128
  // discovered while cooking: remember it so later cooks look up the time-mixed key directly
980
1129
  timeDep = true;
@@ -996,6 +1145,7 @@ export class Engine {
996
1145
  if (this.inflight.get(key) === mine)
997
1146
  this.inflight.delete(key);
998
1147
  land({ geo: result.geo, sig: result.sig, timeDep, failed: !!result.error });
1148
+ ended(result.ms, result.error?.message);
999
1149
  return result;
1000
1150
  }
1001
1151
  /**
@@ -1015,7 +1165,7 @@ export class Engine {
1015
1165
  if (!pseen.has(n)) {
1016
1166
  pseen.add(n);
1017
1167
  const spec = s.graph.nodes[n];
1018
- const def = this.resolveDef(spec.type);
1168
+ const def = this.resolveDef(spec.type, s.scope);
1019
1169
  const refs = scanNodeRefs(def, spec.params);
1020
1170
  if (hasRefs(refs)) {
1021
1171
  let ok = true;
@@ -1047,7 +1197,7 @@ export class Engine {
1047
1197
  seen.add(n);
1048
1198
  order.push(n);
1049
1199
  const spec = s.graph.nodes[n];
1050
- const def = this.resolveDef(spec.type);
1200
+ const def = this.resolveDef(spec.type, s.scope);
1051
1201
  const wiring = wiringOf(spec, def).list;
1052
1202
  const lazy = !!def.inputsUsed && !spec.bypass && def.type !== 'input';
1053
1203
  let used = null;