topotopo 0.3.0 → 0.5.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 (354) hide show
  1. package/NOTICE +40 -10
  2. package/README.md +475 -111
  3. package/dist/cli.js +328 -133
  4. package/dist/config.d.ts +48 -0
  5. package/dist/config.js +170 -0
  6. package/dist/core/analysis.d.ts +5 -1
  7. package/dist/core/analysis.js +8 -3
  8. package/dist/core/bake.d.ts +16 -8
  9. package/dist/core/bake.js +165 -29
  10. package/dist/core/bevel.d.ts +3 -1
  11. package/dist/core/bevel.js +238 -97
  12. package/dist/core/decimate.d.ts +65 -0
  13. package/dist/core/decimate.js +409 -3
  14. package/dist/core/erosion.d.ts +37 -0
  15. package/dist/core/erosion.js +41 -1
  16. package/dist/core/geometry.d.ts +5 -1
  17. package/dist/core/geometry.js +204 -4
  18. package/dist/core/heightfield.d.ts +27 -4
  19. package/dist/core/heightfield.js +54 -16
  20. package/dist/core/imageops.d.ts +6 -0
  21. package/dist/core/imageops.js +51 -0
  22. package/dist/core/intrinsics.d.ts +7 -0
  23. package/dist/core/intrinsics.js +94 -0
  24. package/dist/core/manifold.d.ts +12 -1
  25. package/dist/core/manifold.js +78 -6
  26. package/dist/core/materials.d.ts +11 -0
  27. package/dist/core/materials.js +56 -0
  28. package/dist/core/noise.d.ts +9 -0
  29. package/dist/core/noise.js +10 -1
  30. package/dist/core/packed.js +11 -0
  31. package/dist/core/particles.d.ts +1 -1
  32. package/dist/core/particles.js +1 -1
  33. package/dist/core/polymerge.d.ts +21 -0
  34. package/dist/core/polymerge.js +327 -0
  35. package/dist/core/rbd.js +13 -1
  36. package/dist/core/repair.d.ts +2 -0
  37. package/dist/core/repair.js +2 -0
  38. package/dist/core/report.d.ts +70 -0
  39. package/dist/core/report.js +275 -0
  40. package/dist/core/scatter.d.ts +1 -1
  41. package/dist/core/scatter.js +1 -1
  42. package/dist/core/scene.d.ts +20 -0
  43. package/dist/core/scene.js +72 -0
  44. package/dist/core/sha256.d.ts +4 -0
  45. package/dist/core/sha256.js +69 -0
  46. package/dist/core/shapes.d.ts +3 -0
  47. package/dist/core/shapes.js +34 -0
  48. package/dist/core/snippet-lib.d.ts +15 -2
  49. package/dist/core/snippet-lib.js +40 -14
  50. package/dist/core/solidify.d.ts +38 -0
  51. package/dist/core/solidify.js +356 -0
  52. package/dist/core/tangents.d.ts +54 -0
  53. package/dist/core/tangents.js +218 -0
  54. package/dist/core/texcoord.d.ts +4 -0
  55. package/dist/core/texcoord.js +14 -0
  56. package/dist/core/texnoise.d.ts +6 -1
  57. package/dist/core/texnoise.js +6 -2
  58. package/dist/core/texsdf.d.ts +131 -0
  59. package/dist/core/texsdf.js +637 -0
  60. package/dist/core/texture.d.ts +163 -9
  61. package/dist/core/texture.js +844 -20
  62. package/dist/core/topology.d.ts +32 -0
  63. package/dist/core/topology.js +238 -7
  64. package/dist/core/traceimage.d.ts +7 -0
  65. package/dist/core/traceimage.js +221 -0
  66. package/dist/core/tritri.d.ts +5 -0
  67. package/dist/core/tritri.js +120 -0
  68. package/dist/core/unwrap.d.ts +72 -0
  69. package/dist/core/unwrap.js +800 -0
  70. package/dist/core/usercode.d.ts +27 -0
  71. package/dist/core/usercode.js +87 -0
  72. package/dist/core/uv.d.ts +15 -16
  73. package/dist/core/uv.js +36 -189
  74. package/dist/core/uvislands.d.ts +62 -0
  75. package/dist/core/uvislands.js +574 -0
  76. package/dist/core/uvoverlap.d.ts +58 -0
  77. package/dist/core/uvoverlap.js +220 -0
  78. package/dist/core/uvpack.d.ts +64 -0
  79. package/dist/core/uvpack.js +628 -0
  80. package/dist/core/uvreport.d.ts +127 -0
  81. package/dist/core/uvreport.js +372 -0
  82. package/dist/core/wrangle.d.ts +6 -1
  83. package/dist/core/wrangle.js +27 -16
  84. package/dist/core/xatlas.d.ts +16 -1
  85. package/dist/core/xatlas.js +95 -61
  86. package/dist/engines.d.ts +63 -0
  87. package/dist/engines.js +180 -0
  88. package/dist/explain.d.ts +4 -3
  89. package/dist/explain.js +129 -12
  90. package/dist/graph/engine.d.ts +92 -29
  91. package/dist/graph/engine.js +298 -148
  92. package/dist/graph/expr.d.ts +6 -3
  93. package/dist/graph/expr.js +18 -8
  94. package/dist/graph/outputs.d.ts +23 -0
  95. package/dist/graph/outputs.js +41 -0
  96. package/dist/graph/packages.d.ts +72 -0
  97. package/dist/graph/packages.js +261 -0
  98. package/dist/graph/parallel.d.ts +3 -1
  99. package/dist/graph/parallel.js +4 -1
  100. package/dist/graph/params.d.ts +6 -0
  101. package/dist/graph/params.js +34 -7
  102. package/dist/graph/scope.d.ts +55 -0
  103. package/dist/graph/scope.js +14 -0
  104. package/dist/graph/types.d.ts +75 -12
  105. package/dist/graph/types.js +4 -2
  106. package/dist/graph/vars.d.ts +16 -0
  107. package/dist/graph/vars.js +80 -0
  108. package/dist/host/artifacts.d.ts +10 -1
  109. package/dist/host/artifacts.js +37 -6
  110. package/dist/host/cook.d.ts +241 -0
  111. package/dist/host/cook.js +844 -0
  112. package/dist/host/export-targets.d.ts +42 -5
  113. package/dist/host/export-targets.js +72 -13
  114. package/dist/host/godot-commands.d.ts +4 -0
  115. package/dist/host/godot-commands.js +21 -0
  116. package/dist/host/godot.d.ts +183 -0
  117. package/dist/host/godot.js +916 -0
  118. package/dist/host/node.d.ts +12 -7
  119. package/dist/host/node.js +27 -9
  120. package/dist/host/pool.js +51 -2
  121. package/dist/host/sidecars.d.ts +8 -0
  122. package/dist/host/sidecars.js +50 -0
  123. package/dist/host/types.d.ts +19 -6
  124. package/dist/host/version.d.ts +1 -0
  125. package/dist/host/version.js +3 -0
  126. package/dist/host/worker.js +5 -2
  127. package/dist/index.d.ts +5 -3
  128. package/dist/index.js +3 -2
  129. package/dist/inspect.d.ts +84 -1
  130. package/dist/inspect.js +271 -24
  131. package/dist/io/common.d.ts +33 -5
  132. package/dist/io/export.js +2 -1
  133. package/dist/io/files.d.ts +23 -4
  134. package/dist/io/files.js +60 -8
  135. package/dist/io/gltf.js +355 -51
  136. package/dist/io/heightmap.d.ts +3 -0
  137. package/dist/io/heightmap.js +1 -0
  138. package/dist/io/import.js +10 -0
  139. package/dist/io/inspect-scene.d.ts +55 -0
  140. package/dist/io/inspect-scene.js +155 -0
  141. package/dist/io/kinds.d.ts +81 -0
  142. package/dist/io/kinds.js +163 -0
  143. package/dist/io/points.d.ts +2 -1
  144. package/dist/io/points.js +3 -1
  145. package/dist/io/sidecars.d.ts +24 -0
  146. package/dist/io/sidecars.js +57 -0
  147. package/dist/io/source.d.ts +65 -0
  148. package/dist/io/source.js +112 -0
  149. package/dist/io/targets.d.ts +47 -3
  150. package/dist/io/targets.js +149 -14
  151. package/dist/io/textures.js +21 -1
  152. package/dist/io/unreal.js +5 -1
  153. package/dist/mcp/docs.d.ts +10 -1
  154. package/dist/mcp/docs.js +816 -119
  155. package/dist/mcp/inputs.d.ts +12 -5
  156. package/dist/mcp/inputs.js +50 -13
  157. package/dist/mcp/server.js +70 -24
  158. package/dist/mcp/tools.d.ts +14 -7
  159. package/dist/mcp/tools.js +207 -108
  160. package/dist/mcp/verify.d.ts +2 -2
  161. package/dist/mcp/verify.js +1 -1
  162. package/dist/mcp/workspace.d.ts +15 -0
  163. package/dist/mcp/workspace.js +349 -0
  164. package/dist/nodes/attributes.js +198 -1
  165. package/dist/nodes/bake.js +207 -83
  166. package/dist/nodes/beam.d.ts +1 -0
  167. package/dist/nodes/beam.js +201 -0
  168. package/dist/nodes/bevel.js +54 -5
  169. package/dist/nodes/cloth.js +2 -0
  170. package/dist/nodes/code.js +22 -10
  171. package/dist/nodes/curves.js +440 -93
  172. package/dist/nodes/flow.js +53 -33
  173. package/dist/nodes/generate.js +13 -39
  174. package/dist/nodes/heightfield.js +248 -77
  175. package/dist/nodes/imageops.d.ts +1 -0
  176. package/dist/nodes/imageops.js +203 -0
  177. package/dist/nodes/index.d.ts +4 -0
  178. package/dist/nodes/index.js +4 -0
  179. package/dist/nodes/material.js +91 -23
  180. package/dist/nodes/measure.js +45 -18
  181. package/dist/nodes/particles.js +2 -0
  182. package/dist/nodes/pcg.js +6 -5
  183. package/dist/nodes/procedural.js +4 -3
  184. package/dist/nodes/rbd.js +1 -1
  185. package/dist/nodes/remesh.js +71 -15
  186. package/dist/nodes/scene.d.ts +1 -0
  187. package/dist/nodes/scene.js +55 -0
  188. package/dist/nodes/sdf.js +10 -5
  189. package/dist/nodes/solid.js +20 -5
  190. package/dist/nodes/solidify.d.ts +1 -0
  191. package/dist/nodes/solidify.js +52 -0
  192. package/dist/nodes/splines.d.ts +15 -1
  193. package/dist/nodes/splines.js +112 -105
  194. package/dist/nodes/texture.d.ts +21 -6
  195. package/dist/nodes/texture.js +1318 -185
  196. package/dist/nodes/topology.d.ts +7 -0
  197. package/dist/nodes/topology.js +133 -6
  198. package/dist/nodes/transform.js +11 -3
  199. package/dist/nodes/util.d.ts +1 -1
  200. package/dist/nodes/uv.js +192 -174
  201. package/dist/nodes/wasmcall.js +6 -2
  202. package/dist/open.d.ts +19 -0
  203. package/dist/open.js +12 -0
  204. package/dist/package.d.ts +288 -0
  205. package/dist/package.js +772 -0
  206. package/dist/packages/check.d.ts +32 -0
  207. package/dist/packages/check.js +169 -0
  208. package/dist/packages/commands.d.ts +57 -0
  209. package/dist/packages/commands.js +537 -0
  210. package/dist/packages/registry.d.ts +796 -0
  211. package/dist/packages/registry.js +2998 -0
  212. package/dist/packages/update.d.ts +124 -0
  213. package/dist/packages/update.js +476 -0
  214. package/dist/render/options.d.ts +2 -0
  215. package/dist/render/options.js +44 -5
  216. package/dist/render/pbr.d.ts +28 -0
  217. package/dist/render/pbr.js +378 -0
  218. package/dist/render/preview.d.ts +69 -0
  219. package/dist/render/preview.js +26 -0
  220. package/dist/render/raster.d.ts +78 -7
  221. package/dist/render/raster.js +600 -145
  222. package/dist/render/texview.d.ts +7 -1
  223. package/dist/render/texview.js +34 -2
  224. package/dist/scan.d.ts +61 -0
  225. package/dist/scan.js +228 -0
  226. package/dist/session.d.ts +311 -0
  227. package/dist/session.js +849 -0
  228. package/dist/viewer/app/api.js +48 -6
  229. package/dist/viewer/app/camera.js +1 -1
  230. package/dist/viewer/app/cooking.js +78 -0
  231. package/dist/viewer/app/embed.js +100 -0
  232. package/dist/viewer/app/export-popover.js +118 -16
  233. package/dist/viewer/app/grid.js +6 -2
  234. package/dist/viewer/app/guides.js +123 -1
  235. package/dist/viewer/app/keymap.js +7 -4
  236. package/dist/viewer/app/layers.js +5 -5
  237. package/dist/viewer/app/main.js +186 -53
  238. package/dist/viewer/app/markers.js +61 -1
  239. package/dist/viewer/app/outliner.js +72 -27
  240. package/dist/viewer/app/output-info.js +45 -0
  241. package/dist/viewer/app/outputs.css +147 -8
  242. package/dist/viewer/app/outputs.js +168 -54
  243. package/dist/viewer/app/packages.js +614 -0
  244. package/dist/viewer/app/props.js +177 -53
  245. package/dist/viewer/app/scene.js +35 -6
  246. package/dist/viewer/app/select.js +5 -4
  247. package/dist/viewer/app/selection.js +1 -1
  248. package/dist/viewer/app/status.js +12 -15
  249. package/dist/viewer/app/style.css +66 -8
  250. package/dist/viewer/app/units.js +1 -1
  251. package/dist/viewer/app/vars.js +48 -1
  252. package/dist/viewer/app/welcome.js +72 -0
  253. package/dist/viewer/graph-file.d.ts +62 -0
  254. package/dist/viewer/graph-file.js +175 -0
  255. package/dist/viewer/index.html +24 -11
  256. package/dist/viewer/json-edit.d.ts +13 -0
  257. package/dist/viewer/json-edit.js +274 -0
  258. package/dist/viewer/outputs.d.ts +49 -5
  259. package/dist/viewer/outputs.js +264 -56
  260. package/dist/viewer/packages.d.ts +121 -0
  261. package/dist/viewer/packages.js +584 -0
  262. package/dist/viewer/server.d.ts +24 -7
  263. package/dist/viewer/server.js +289 -31
  264. package/dist/web/app/web.css +419 -0
  265. package/dist/web/app/web.js +188 -0
  266. package/dist/web/bake.d.ts +34 -0
  267. package/dist/web/bake.js +153 -0
  268. package/dist/web/folder-page.d.ts +101 -0
  269. package/dist/web/folder-page.js +146 -0
  270. package/dist/web/folders.d.ts +280 -0
  271. package/dist/web/folders.js +970 -0
  272. package/dist/web/library.d.ts +91 -0
  273. package/dist/web/library.js +228 -0
  274. package/dist/web/markdown.d.ts +45 -0
  275. package/dist/web/markdown.js +677 -0
  276. package/dist/web/pages.d.ts +258 -0
  277. package/dist/web/pages.js +301 -0
  278. package/dist/web/server.d.ts +24 -0
  279. package/dist/web/server.js +1068 -0
  280. package/dist/workspace.d.ts +88 -105
  281. package/dist/workspace.js +359 -375
  282. package/integrations/godot/addons/topotopo/LICENSE +202 -0
  283. package/integrations/godot/addons/topotopo/README.md +57 -0
  284. package/integrations/godot/addons/topotopo/context_menu.gd +43 -0
  285. package/integrations/godot/addons/topotopo/dock.gd +266 -0
  286. package/integrations/godot/addons/topotopo/dock.tscn +72 -0
  287. package/integrations/godot/addons/topotopo/export_filter.gd +72 -0
  288. package/integrations/godot/addons/topotopo/gltf_instancing.gd +131 -0
  289. package/integrations/godot/addons/topotopo/icons/topotopo.svg +1 -0
  290. package/integrations/godot/addons/topotopo/inspector.gd +38 -0
  291. package/integrations/godot/addons/topotopo/instances_post_import.gd +111 -0
  292. package/integrations/godot/addons/topotopo/package.gd +23 -0
  293. package/integrations/godot/addons/topotopo/package_importer.gd +187 -0
  294. package/integrations/godot/addons/topotopo/plugin.cfg +7 -0
  295. package/integrations/godot/addons/topotopo/plugin.gd +970 -0
  296. package/integrations/godot/addons/topotopo/record.gd +435 -0
  297. package/integrations/godot/addons/topotopo/runner.gd +458 -0
  298. package/integrations/godot/addons/topotopo/tools/check.gd +42 -0
  299. package/integrations/godot/addons/topotopo/watcher.gd +199 -0
  300. package/kernels/pkg/README.md +23 -29
  301. package/kernels/pkg-simd/README.md +23 -29
  302. package/library/architecture/versions/1.0/architecture.topo +12 -0
  303. package/{shelf → library/architecture/versions/1.0/graphs}/arch.json +3 -3
  304. package/{shelf → library/architecture/versions/1.0/graphs}/beam_truss.json +6 -6
  305. package/{shelf → library/architecture/versions/1.0/graphs}/brick_wall.json +8 -8
  306. package/{shelf → library/architecture/versions/1.0/graphs}/door_frame.json +3 -3
  307. package/{shelf → library/architecture/versions/1.0/graphs}/hex_grid_floor.json +3 -2
  308. package/{shelf → library/architecture/versions/1.0/graphs}/house.json +8 -8
  309. package/library/architecture/versions/1.0/graphs/lineup.json +42 -0
  310. package/{shelf → library/architecture/versions/1.0/graphs}/pillar.json +3 -2
  311. package/{shelf → library/architecture/versions/1.0/graphs}/railing.json +5 -5
  312. package/{shelf → library/architecture/versions/1.0/graphs}/roof_gable.json +2 -2
  313. package/{shelf → library/architecture/versions/1.0/graphs}/roof_hip.json +2 -2
  314. package/{shelf → library/architecture/versions/1.0/graphs}/roof_skeleton.json +2 -1
  315. package/{shelf → library/architecture/versions/1.0/graphs}/scaffold.json +4 -4
  316. package/{shelf → library/architecture/versions/1.0/graphs}/spiral_stairs.json +3 -2
  317. package/{shelf → library/architecture/versions/1.0/graphs}/stairs.json +6 -6
  318. package/{shelf → library/architecture/versions/1.0/graphs}/tile_floor.json +3 -2
  319. package/{shelf → library/architecture/versions/1.0/graphs}/wall_segment.json +10 -10
  320. package/{shelf → library/architecture/versions/1.0/graphs}/window_frame.json +2 -2
  321. package/library/architecture/versions/1.0/version.json +1119 -0
  322. package/{shelf → library/nature/versions/1.0/graphs}/bush.json +2 -2
  323. package/{shelf → library/nature/versions/1.0/graphs}/cliff_block.json +4 -3
  324. package/{shelf → library/nature/versions/1.0/graphs}/forest_patch.json +5 -5
  325. package/{shelf → library/nature/versions/1.0/graphs}/grass_clumps.json +2 -2
  326. package/library/nature/versions/1.0/graphs/lineup.json +24 -0
  327. package/{shelf → library/nature/versions/1.0/graphs}/log.json +6 -6
  328. package/{shelf → library/nature/versions/1.0/graphs}/rock.json +5 -4
  329. package/{shelf → library/nature/versions/1.0/graphs}/scatter_rocks.json +5 -5
  330. package/{shelf → library/nature/versions/1.0/graphs}/tree_lowpoly.json +3 -2
  331. package/library/nature/versions/1.0/nature.topo +12 -0
  332. package/library/nature/versions/1.0/version.json +534 -0
  333. package/{shelf → library/props/versions/1.0/graphs}/barrel.json +5 -4
  334. package/{shelf → library/props/versions/1.0/graphs}/crate.json +3 -3
  335. package/library/props/versions/1.0/graphs/lineup.json +18 -0
  336. package/{shelf → library/props/versions/1.0/graphs}/pallet.json +4 -3
  337. package/{shelf → library/props/versions/1.0/graphs}/pipe_run.json +3 -3
  338. package/{shelf → library/props/versions/1.0/graphs}/sandbag_wall.json +5 -5
  339. package/library/props/versions/1.0/props.topo +12 -0
  340. package/library/props/versions/1.0/version.json +336 -0
  341. package/{shelf → library/street/versions/1.0/graphs}/bench.json +5 -5
  342. package/{shelf → library/street/versions/1.0/graphs}/bollard.json +2 -1
  343. package/{shelf → library/street/versions/1.0/graphs}/cable.json +4 -4
  344. package/{shelf → library/street/versions/1.0/graphs}/fence.json +7 -7
  345. package/{shelf → library/street/versions/1.0/graphs}/lamp_post.json +2 -2
  346. package/library/street/versions/1.0/graphs/lineup.json +22 -0
  347. package/{shelf → library/street/versions/1.0/graphs}/road_strip.json +2 -2
  348. package/{shelf → library/street/versions/1.0/graphs}/sign_post.json +1 -1
  349. package/library/street/versions/1.0/street.topo +12 -0
  350. package/library/street/versions/1.0/version.json +421 -0
  351. package/package.json +23 -8
  352. package/dist/graph/migrate.d.ts +0 -23
  353. package/dist/graph/migrate.js +0 -58
  354. package/shelf/index.json +0 -190
package/dist/workspace.js CHANGED
@@ -1,397 +1,381 @@
1
- // A workspace: named graphs (persisted as JSON files), saved assets, the human's input files, and the engine
2
- // that cooks them. Shared by the MCP server, the live viewer and the CLI.
3
- // <dir>/graphs/<name>.json graphs <dir>/assets/<name>.json saved assets
4
- // <dir>/inputs/… files people drop in (meshes, guide curves, PNG masks), read with file nodes; or a
5
- // folder given to the constructor (`topotopo view`: inputs/ beside the graph file)
6
- // <dir>/exports/… export output
1
+ // A workspace: a folder tree (a game, an archviz job) whose folders holding a .topo file are its packages, found by
2
+ // scanning it (src/scan.ts). topotopo-workspace.json at its root names it, lists the shared libraries its packages use
3
+ // (registered names, or paths to folders outside the workspace), names the engine project the game is built with,
4
+ // whether its own packages are followed live for looking, and the one version of each package the whole workspace
5
+ // uses: its packages share one copy of it, in topotopo-packages/ beside the file (a package that publishes versions keeps
6
+ // its own copies: its uses are published with it).
7
+ // {"name": "my-game", "libraries": ["props", "../shared/materials"],
8
+ // "engine": {"type": "godot", "project": "../project.godot"}, "follow": false, "uses": {"topotopo/props": "1.1"}}
9
+ // Paths are written from the workspace's folder. Its preferred place is inside the engine's content folder (the Godot
10
+ // project folder or a folder in it, Unreal's Content/ or a folder in it), so Explorer, the engine and the web app show
11
+ // one tree and the engine imports each package's exports/ where they are. package.ts finds the workspace around a
12
+ // package (locate), the places it finds packages in (librariesFor) and where its copies are (copiesFor).
7
13
  import fs from 'node:fs';
8
14
  import path from 'node:path';
9
- import { Engine, wiringOf } from './graph/engine.js';
10
- import { didYouMean, renameExprRefs } from './graph/params.js';
11
- import { migrateGraph } from './graph/migrate.js';
12
- const NAME_RE = /^[A-Za-z_][\w.-]*$/;
13
- const GEOMETRY_EXTS = new Set(['obj', 'stl', 'ply', 'glb', 'gltf', 'geo', 'bgeo', 'blend', 'csv', 'json', 'points.json']);
14
- const IMAGE_EXTS = new Set(['png', 'jpg', 'jpeg', 'webp']);
15
- /** Lower-case extension of a file name without the dot; ".points.json" is one extension, dot-files have none. */
16
- export function inputExt(file) {
17
- const b = file.toLowerCase().replace(/^.*[\\/]/, '');
18
- if (b.endsWith('.points.json') && b.length > '.points.json'.length)
19
- return 'points.json';
20
- const i = b.lastIndexOf('.');
21
- return i > 0 ? b.slice(i + 1) : '';
15
+ import { ID_RE } from './graph/scope.js';
16
+ import { BUILTIN_LIBRARY, addWorkspace, loadConfig } from './config.js';
17
+ import { WORKSPACE_FILE, WORKSPACE_PACKAGES, workspaceFlag, copiesFor, libraryEntry, locate, manifestAt, parseUses, program, resolveListed, slugify, within, workspaceRepoFiles, writeAtomic } from './package.js';
18
+ import { gatherCopies } from './packages/registry.js';
19
+ import { folderKey, forgetScans, scanTree } from './scan.js';
20
+ import { detectEngine, engineTypeOf, godotIgnore, godotPresetReport, unrealSees } from './engines.js';
21
+ export { WORKSPACE_FILE };
22
+ /** What an "engine.assets" or --assets is told: the "engine:" export folder is gone. */
23
+ export const assetsGone = (what) => `${what} is gone: an export stays in its package's exports/ folder; put the workspace inside the engine project (Godot: the project folder or a folder in it; Unreal: Content/ or a folder in it) and the engine imports the exports from there`;
24
+ /** topotopo-workspace.json checked and normalised; throws naming the problem. */
25
+ export function parseWorkspace(raw, fallbackName) {
26
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
27
+ throw new Error(`${WORKSPACE_FILE} must be an object`);
28
+ const name = raw.name === undefined ? fallbackName : raw.name;
29
+ if (typeof name !== 'string' || !ID_RE.test(name))
30
+ throw new Error(`${WORKSPACE_FILE}: "name" must be lower-case letters, digits, - and _ ("my-game"), got ${JSON.stringify(name)}`);
31
+ const libraries = raw.libraries ?? [];
32
+ if (!Array.isArray(libraries) || libraries.some((l) => typeof l !== 'string'))
33
+ throw new Error(`${WORKSPACE_FILE}: "libraries" must be a list of registered library names and paths from the workspace to folders outside it ("../shared/props")`);
34
+ let engine = null;
35
+ if (raw.engine === 'none')
36
+ engine = 'none';
37
+ else if (raw.engine !== undefined && raw.engine !== null) {
38
+ const e = raw.engine;
39
+ if (e && typeof e === 'object' && e.assets !== undefined)
40
+ throw new Error(`${WORKSPACE_FILE}: ${assetsGone('"engine.assets"')}; remove "assets"`);
41
+ if (!e || typeof e !== 'object' || (e.type !== 'godot' && e.type !== 'unreal') || typeof e.project !== 'string' || !e.project)
42
+ throw new Error(`${WORKSPACE_FILE}: "engine" must be {"type": "godot" | "unreal", "project": "../project.godot"} or "none"`);
43
+ engine = { type: e.type, project: e.project };
44
+ }
45
+ if (raw.follow !== undefined && typeof raw.follow !== 'boolean')
46
+ throw new Error(`${WORKSPACE_FILE}: "follow" must be true or false`);
47
+ const uses = parseUses(raw.uses, WORKSPACE_FILE);
48
+ return { name, libraries: [...new Set(libraries.map((l) => l.trim().replace(/\\/g, '/')))], engine, follow: raw.follow === true, uses };
49
+ }
50
+ /** The workspace file of `dir` (the workspace's folder), checked. */
51
+ export function readWorkspace(dir) {
52
+ const file = path.join(dir, WORKSPACE_FILE);
53
+ let raw;
54
+ try {
55
+ raw = JSON.parse(fs.readFileSync(file, 'utf8'));
56
+ }
57
+ catch (e) {
58
+ throw new Error(`${file}: ${e.message}`);
59
+ }
60
+ try {
61
+ return parseWorkspace(raw, slugify(path.basename(path.resolve(dir))) || 'workspace');
62
+ }
63
+ catch (e) {
64
+ throw new Error(`${file}: ${e.message.replace(`${WORKSPACE_FILE}: `, '')}`);
65
+ }
66
+ }
67
+ export function writeWorkspace(dir, m) {
68
+ const out = { name: m.name, libraries: m.libraries };
69
+ if (m.engine)
70
+ out.engine = m.engine === 'none' ? 'none' : { type: m.engine.type, project: m.engine.project };
71
+ if (m.follow)
72
+ out.follow = true;
73
+ if (Object.keys(m.uses).length)
74
+ out.uses = m.uses;
75
+ writeAtomic(path.join(dir, WORKSPACE_FILE), JSON.stringify(out, null, 2) + '\n');
76
+ forgetScans();
77
+ }
78
+ /** The engine project file a workspace names, absolute; null for none. */
79
+ export const engineFile = (ws, m) => (m.engine && m.engine !== 'none' ? path.resolve(ws, m.engine.project) : null);
80
+ /** The packages of a workspace (src/scan.ts), the folder of its own engine project scanned like any other. */
81
+ export function scanWorkspace(ws, m = readWorkspace(ws)) {
82
+ return scanTree(m.name, ws, { engine: engineFile(ws, m) });
22
83
  }
23
- export function inputKind(ext) {
24
- return GEOMETRY_EXTS.has(ext) ? 'geometry' : IMAGE_EXTS.has(ext) ? 'image' : 'other';
84
+ const rel = (from, to) => path.relative(path.resolve(from), path.resolve(to)).split(path.sep).join('/') || '.';
85
+ /** "godot:game/project.godot" (or a bare path whose file name says the engine) as an engine link; the path may lead upward ("../project.godot"). */
86
+ export function parseEngineArg(arg, dir) {
87
+ const m = /^(godot|unreal):(.+)$/i.exec(arg.trim());
88
+ const file = (m ? m[2] : arg).trim().replace(/\\/g, '/');
89
+ const type = m ? m[1].toLowerCase() : engineTypeOf(file);
90
+ if (!type)
91
+ throw new Error(`--engine "${arg}": write godot:<path to project.godot>, unreal:<path to the .uproject> or none`);
92
+ const abs = path.resolve(dir, file);
93
+ if (!fs.statSync(abs, { throwIfNoEntry: false })?.isFile())
94
+ throw new Error(`--engine "${arg}": no file ${abs}`);
95
+ return { type, project: rel(dir, abs) };
25
96
  }
26
- /** Thrown by Workspace.edit when the edited graph does not validate; the stored graph is unchanged. */
27
- export class EditRejected extends Error {
28
- errors;
29
- constructor(errors) {
30
- super(`✗ edits rejected (graph unchanged) — ${errors.length} error(s):\n` + errors.map((e) => ` [${e.node}] ${e.message}`).join('\n'));
31
- this.name = 'EditRejected';
32
- this.errors = errors;
97
+ /**
98
+ * The name an engine project gives itself, as a workspace name: project.godot's config/name, a .uproject's file name;
99
+ * null when it has none.
100
+ */
101
+ export function engineProjectName(dir, e) {
102
+ const file = path.resolve(dir, e.project);
103
+ if (e.type === 'unreal')
104
+ return slugify(path.basename(file).replace(/\.uproject$/i, '')) || null;
105
+ try {
106
+ const m = /^config\/name\s*=\s*"([^"]*)"/m.exec(fs.readFileSync(file, 'utf8'));
107
+ return m ? slugify(m[1]) || null : null;
108
+ }
109
+ catch {
110
+ return null;
33
111
  }
34
112
  }
35
- export class Workspace {
36
- dir;
37
- engine;
38
- graphs = new Map();
39
- versions = new Map();
40
- lastReport = new Map();
41
- listeners = new Set();
42
- /** the inputs folder given to the constructor (WorkspaceOptions.inputs), if any */
43
- inputsAt;
44
- exportsAt;
45
- constructor(dir, engine, opts = {}) {
46
- this.dir = path.resolve(dir);
47
- this.engine = engine;
48
- this.inputsAt = opts.inputs === undefined ? undefined : path.resolve(opts.inputs);
49
- this.exportsAt = opts.exports === undefined ? undefined : path.resolve(opts.exports);
50
- engine.graphResolver = (n) => this.graphs.get(n);
113
+ /**
114
+ * A name a workspace takes: refused when it is TopoTopo's built-in library's or a registered library's (workspaces and
115
+ * libraries share one set of names, so a web app address /p/<name>/<id> means one thing).
116
+ */
117
+ export function checkWorkspaceName(name, how = '--name <another name>', dir) {
118
+ if (name === BUILTIN_LIBRARY.name)
119
+ throw new Error(`"${name}" is the name of TopoTopo's built-in library: give the workspace another name (${how})`);
120
+ let cfg;
121
+ try {
122
+ cfg = loadConfig();
51
123
  }
52
- get graphDir() { return path.join(this.dir, 'graphs'); }
53
- get assetDir() { return path.join(this.dir, 'assets'); }
54
- get exportDir() { return this.exportsAt ?? path.join(this.dir, 'exports'); }
55
- /**
56
- * files people drop in: meshes, guide curves and points, PNG masks and heightmaps (read as "inputs/<path>");
57
- * <dir>/inputs unless the constructor was given another folder
58
- */
59
- get inputDir() { return this.inputsAt ?? path.join(this.dir, 'inputs'); }
60
- load() {
61
- // the workspace's own inputs/ is made at once (people open it to drop files in); a folder given to the constructor
62
- // is made by the first file written into it
63
- for (const d of [this.dir, this.graphDir, this.assetDir, this.exportDir, ...(this.inputsAt ? [] : [this.inputDir])])
64
- fs.mkdirSync(d, { recursive: true });
65
- const assetErrors = [];
66
- for (const f of fs.readdirSync(this.assetDir).filter((f) => f.endsWith('.json'))) {
67
- try {
68
- const spec = migrateGraph(JSON.parse(fs.readFileSync(path.join(this.assetDir, f), 'utf8')));
69
- this.engine.registerAsset(path.basename(f, '.json'), spec);
70
- }
71
- catch (e) {
72
- assetErrors.push(`${f}: ${e.message}`);
73
- }
74
- }
75
- for (const f of fs.readdirSync(this.graphDir).filter((f) => f.endsWith('.json'))) {
76
- // migrated in memory; the file is rewritten (with its version) on the next save
77
- try {
78
- this.graphs.set(path.basename(f, '.json'), migrateGraph(JSON.parse(fs.readFileSync(path.join(this.graphDir, f), 'utf8'))));
79
- }
80
- catch { /* skip unreadable */ }
81
- }
82
- // workspace assets were registered over shelf assets of the same name (engine.init loads the shelf first)
83
- const defs = [...this.engine.assets.values()].map((a) => a.def);
84
- return {
85
- graphs: this.graphs.size, assets: defs.filter((d) => d.category !== 'shelf').length, shelf: defs.filter((d) => d.category === 'shelf').length,
86
- assetErrors: [...assetErrors, ...this.engine.shelfErrors.map((e) => `shelf ${e}`)],
87
- };
124
+ catch {
125
+ return;
88
126
  }
89
- persist(name) {
90
- const g = this.graphs.get(name);
91
- const file = path.join(this.graphDir, name + '.json');
92
- if (!g) {
93
- if (fs.existsSync(file))
94
- fs.unlinkSync(file);
95
- return;
127
+ const lib = cfg.libraries.find((l) => l.name === name);
128
+ if (lib)
129
+ throw new Error(`"${name}" is the name of a registered library (${lib.path}): workspaces and libraries share one set of names; give the workspace another name (${how})`);
130
+ const other = dir ? cfg.workspaces.find((w) => w.name === name && folderKey(w.path) !== folderKey(dir)) : undefined;
131
+ if (other)
132
+ throw new Error(`"${name}" is the name of another registered workspace (${other.path}): give the workspace another name (${how})`);
133
+ }
134
+ /**
135
+ * The entry a workspace's "libraries" gets for a library a person names (workspace library add, workspace init
136
+ * --library): a folder, as the person sees it (relative to `cwd`), written as its path from the workspace ("../shared");
137
+ * else a registered library's name. Refuses, worded for the workspace file: a folder inside the workspace or holding it
138
+ * (its packages are found by themselves), a package's folder, a folder on another drive, a name not registered.
139
+ */
140
+ export function workspaceLibraryEntry(ws, given, cwd = process.cwd()) {
141
+ const file = path.join(ws, WORKSPACE_FILE);
142
+ const g = given.trim();
143
+ if (g === BUILTIN_LIBRARY.name)
144
+ throw new Error(`TopoTopo's built-in library is looked in by every package without being listed: ${file} "libraries" lists shared libraries only`);
145
+ const abs = path.resolve(cwd, g);
146
+ const isFolder = !!fs.statSync(abs, { throwIfNoEntry: false })?.isDirectory();
147
+ if (isFolder && (!ID_RE.test(g) || !registeredLibrary(g))) {
148
+ let at = null;
149
+ try {
150
+ at = manifestAt(abs);
96
151
  }
97
- fs.writeFileSync(file, JSON.stringify(g, null, 2));
98
- }
99
- bump(name) {
100
- const v = (this.versions.get(name) ?? 0) + 1;
101
- this.versions.set(name, v);
102
- for (const l of this.listeners)
103
- try {
104
- l({ graph: name, version: v });
105
- }
106
- catch { /* ignore */ }
152
+ catch { /* two manifests: a package's folder all the same */ }
153
+ if (at)
154
+ throw new Error(`${abs} is a package's folder (${path.basename(at.file)}), not a library: ${file} "libraries" lists the folders of shared libraries; give the library's folder, or its registered name`);
155
+ if (within(abs, ws))
156
+ throw new Error(`${abs} is inside the workspace (${ws}): its packages are found by themselves; ${file} "libraries" lists shared libraries outside it`);
157
+ if (within(ws, abs))
158
+ throw new Error(`${abs} holds the workspace (${ws}): ${file} "libraries" lists shared libraries outside it, and the workspace's own packages are found by themselves`);
159
+ const r = path.relative(ws, abs).split(path.sep).join('/');
160
+ if (path.isAbsolute(r) || /^[A-Za-z]:/.test(r))
161
+ throw new Error(`${abs} is on another drive than the workspace: register it (${program()} library add <name> ${abs}) and list it by its name`);
162
+ return r.startsWith('.') ? r : `./${r}`;
107
163
  }
108
- getGraph(name) {
109
- const g = this.graphs.get(name);
110
- if (!g) {
111
- const s = didYouMean(name, [...this.graphs.keys()]);
112
- throw new Error(`no graph "${name}"${s.length ? ` — did you mean ${s.join(', ')}?` : ''}. Graphs: ${[...this.graphs.keys()].join(', ') || '(none yet — use build)'}`);
164
+ const k = libraryEntry(g);
165
+ if ('error' in k)
166
+ throw new Error(`${isFolder ? '' : `no folder ${abs}, and `}${k.error}`);
167
+ if ('path' in k)
168
+ throw new Error(`no folder ${abs}: give the library's folder, or its registered name`);
169
+ const lib = registeredLibrary(g);
170
+ if (!lib) {
171
+ let names = 'none are registered';
172
+ try {
173
+ names = loadConfig().libraries.map((l) => l.name).join(', ') || names;
113
174
  }
114
- return g;
175
+ catch { /* said as none */ }
176
+ throw new Error(`"${g}" is no folder here and no registered library (${names}): ${file} "libraries" lists a registered library by its name; register it first (${program()} library add ${g} <folder>), or give the library's folder`);
115
177
  }
116
- setGraph(name, spec) {
117
- if (!NAME_RE.test(name))
118
- throw new Error(`graph name must match ${NAME_RE}`);
119
- this.graphs.set(name, migrateGraph(spec));
120
- this.persist(name);
178
+ if (within(lib.path, ws))
179
+ throw new Error(`library "${g}" (${lib.path}) is inside the workspace: its packages are found by themselves; ${file} "libraries" lists shared libraries outside it`);
180
+ if (within(ws, lib.path))
181
+ throw new Error(`library "${g}" (${lib.path}) holds the workspace: ${file} "libraries" lists shared libraries outside it`);
182
+ return g;
183
+ }
184
+ const registeredLibrary = (name) => { try {
185
+ return loadConfig().libraries.find((l) => l.name === name) ?? null;
186
+ }
187
+ catch {
188
+ return null;
189
+ } };
190
+ /** The workspace around a folder, or an error saying there is none and how one is made. */
191
+ function workspaceOf(start) {
192
+ const at = locate(start);
193
+ if (at.outside)
194
+ throw new Error(`${path.resolve(start)} is in no workspace: the workspace ${at.outside.workspace} does not look in it (${at.outside.why}); outside a workspace every registered library counts`);
195
+ if (!at.workspace)
196
+ throw new Error(`${path.resolve(start)} is in no workspace: ${program()} workspace init <folder> makes one; outside a workspace every registered library counts`);
197
+ return at.workspace;
198
+ }
199
+ /**
200
+ * Add a shared library to the workspace's "libraries", or remove one (`topotopo workspace library add|remove`, MCP
201
+ * workspace {action:"libraries"}): the workspace around `at` (default: the current folder). A library is given as a
202
+ * folder, as the person sees it from `cwd`, or by its registered name. Changes the list only. Says what it lists now.
203
+ */
204
+ export function workspaceLibrary(op, given, o = {}) {
205
+ const cwd = o.cwd ?? process.cwd();
206
+ const ws = workspaceOf(o.at ?? cwd);
207
+ const m = readWorkspace(ws), file = path.join(ws, WORKSPACE_FILE);
208
+ // entries are one library when they name one folder: a registered name and a path to its folder alike
209
+ const folderOf = (e) => {
210
+ const k = libraryEntry(e);
211
+ return 'path' in k ? folderKey(path.resolve(ws, k.path)) : 'name' in k && registeredLibrary(e) ? folderKey(registeredLibrary(e).path) : null;
212
+ };
213
+ if (op === 'add') {
214
+ const entry = workspaceLibraryEntry(ws, given, cwd), at = folderOf(entry);
215
+ const have = m.libraries.find((e) => e === entry || (at !== null && folderOf(e) === at));
216
+ if (have)
217
+ return `${file} lists "${entry}" already${have !== entry ? ` (as "${have}", the same folder)` : ''}\n${librariesLine(ws, m)}`;
218
+ m.libraries.push(entry);
121
219
  }
122
- deleteGraph(name) {
123
- this.getGraph(name);
124
- this.graphs.delete(name);
125
- this.persist(name);
220
+ else {
221
+ const g = given.trim(), reg = ID_RE.test(g) ? registeredLibrary(g) : null;
222
+ const at = folderKey(reg ? reg.path : path.resolve(cwd, g));
223
+ const gone = m.libraries.filter((e) => e === g || e === g.replace(/\\/g, '/') || folderOf(e) === at);
224
+ if (!gone.length)
225
+ throw new Error(`${file} does not list "${given}": it lists ${m.libraries.map((e) => `"${e}"`).join(', ') || 'no libraries'}`);
226
+ m.libraries = m.libraries.filter((e) => !gone.includes(e));
126
227
  }
127
- /** Every file under inputs/, recursively: posix paths relative to it, sorted. Dot-files and dot-folders are skipped. */
128
- listInputs() {
129
- const out = [];
130
- const walk = (dir, rel, depth) => {
131
- let entries;
132
- try {
133
- entries = fs.readdirSync(dir, { withFileTypes: true });
134
- }
135
- catch {
136
- return;
137
- }
138
- for (const e of entries) {
139
- if (e.name.startsWith('.'))
140
- continue;
141
- const abs = path.join(dir, e.name), r = rel ? `${rel}/${e.name}` : e.name;
142
- let st;
143
- try {
144
- st = fs.statSync(abs);
145
- }
146
- catch {
147
- continue;
148
- } // a broken link
149
- if (st.isDirectory()) {
150
- if (depth < 32)
151
- walk(abs, r, depth + 1);
152
- } // the depth cap stops link cycles
153
- else if (st.isFile()) {
154
- const ext = inputExt(e.name);
155
- out.push({ path: r, kind: inputKind(ext), ext, size: st.size, mtime: Math.round(st.mtimeMs) });
156
- }
157
- }
158
- };
159
- walk(this.inputDir, '', 0);
160
- return out.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
228
+ writeWorkspace(ws, m);
229
+ return `the workspace "${m.name}" lists ${m.libraries.length ? m.libraries.map((e) => `"${e}"`).join(', ') : 'no libraries'} in ${file} "libraries" now\n${librariesLine(ws, m)}`;
230
+ }
231
+ /**
232
+ * The shared libraries the workspace around a folder lists and where its packages find packages (MCP workspace
233
+ * {action:"libraries"}); outside a workspace, that every registered library counts.
234
+ */
235
+ export function workspaceLibrariesText(start) {
236
+ const ws = locate(start).workspace;
237
+ if (!ws) {
238
+ let names = 'none is registered';
239
+ try {
240
+ names = loadConfig().libraries.map((l) => `"${l.name}"`).join(', ') || names;
241
+ }
242
+ catch { /* said as none */ }
243
+ return `${path.resolve(start)} is in no workspace: its package finds packages in every registered library (${names}), then in TopoTopo's built-in library; ${program()} workspace init <folder> makes a workspace, whose ${WORKSPACE_FILE} lists the shared libraries its packages use`;
161
244
  }
162
- /** Merge nodes/vars/output of `patch` into an existing graph (upsert). */
163
- mergeGraph(name, patch) {
164
- patch = migrateGraph(patch);
165
- const base = structuredClone(this.graphs.get(name) ?? { nodes: {} });
166
- Object.assign(base.nodes, patch.nodes ?? {});
167
- if (patch.vars)
168
- base.vars = { ...(base.vars ?? {}), ...patch.vars };
169
- if (patch.params)
170
- base.params = { ...(base.params ?? {}), ...patch.params };
171
- if (patch.output)
172
- base.output = patch.output;
173
- if (patch.outputs)
174
- base.outputs = { ...base.outputs, ...patch.outputs };
175
- if (patch.export !== undefined)
176
- base.export = patch.export;
177
- if (patch.description)
178
- base.description = patch.description;
179
- return base;
245
+ const m = readWorkspace(ws);
246
+ return `the workspace "${m.name}" lists ${m.libraries.length ? m.libraries.map((e) => `"${e}"`).join(', ') : 'no libraries'} in ${path.join(ws, WORKSPACE_FILE)} "libraries"
247
+ ${librariesLine(ws, m)}`;
248
+ }
249
+ /** Where a workspace's packages find packages, in a line, and what is wrong with its list. */
250
+ function librariesLine(ws, m) {
251
+ const libs = resolveListed(ws, m.libraries);
252
+ return [
253
+ `its packages find packages in the workspace itself, then in ${libs.libs.length ? libs.libs.map((l) => `library "${l.name}" (${l.root})`).join(', ') : 'no shared library'}, then in TopoTopo's built-in library`,
254
+ ...libs.problems.map((p) => `problem: ${p}`),
255
+ ].join('\n');
256
+ }
257
+ /**
258
+ * Make `dir` a workspace: topotopo-workspace.json with its name (the engine project's, else the folder's), the shared
259
+ * libraries given and the engine project (given, or found: the nearest at or above the folder, else below it; "none"
260
+ * for none, kept). A folder that is a workspace already is changed only where an option says so (its name, engine and
261
+ * follow; --library is for making one). It then says what Unreal will not see, the packages outside the engine
262
+ * project's folder, the Godot export presets that would ship TopoTopo's files; keeps Godot's importer out of the
263
+ * packages' working folders (.gdignore); and moves the copies of the packages inside into the workspace's one copy.
264
+ */
265
+ export function initWorkspace(dir, o = {}) {
266
+ const abs = path.resolve(dir);
267
+ if (o.assets !== undefined)
268
+ throw new Error(assetsGone('--assets'));
269
+ if (!fs.statSync(abs, { throwIfNoEntry: false })?.isDirectory())
270
+ throw new Error(`${abs} is no folder`);
271
+ const had = fs.existsSync(path.join(abs, WORKSPACE_FILE));
272
+ const m = had ? readWorkspace(abs) : { name: slugify(path.basename(abs)) || 'workspace', libraries: [], engine: null, follow: false, uses: {} };
273
+ if (had && o.libraries?.length)
274
+ throw new Error(`--library is for making a workspace, and ${abs} is the workspace "${m.name}" already: ${program()} workspace library add <name or folder>${workspaceFlag(abs, o.cwd)} lists a library for it`);
275
+ if (o.name !== undefined) {
276
+ if (!ID_RE.test(o.name))
277
+ throw new Error(`--name "${o.name}": lower-case letters, digits, - and _ ("my-game")`);
278
+ m.name = o.name;
180
279
  }
181
- /** Apply edit operations; returns the new graph (not yet stored) and notes. */
182
- applyEdits(name, ops) {
183
- const g = structuredClone(this.getGraph(name));
184
- const notes = [];
185
- const need = (n, what) => {
186
- if (!n)
187
- throw new Error(`${what}: "node" is required`);
188
- if (!g.nodes[n]) {
189
- const s = didYouMean(n, Object.keys(g.nodes));
190
- throw new Error(`${what}: no node "${n}"${s.length ? ` — did you mean ${s.join(', ')}?` : ''}`);
191
- }
192
- return n;
193
- };
194
- const refsTo = (target) => {
195
- const out = [];
196
- for (const [k, spec] of Object.entries(g.nodes)) {
197
- if (Array.isArray(spec.in))
198
- spec.in.forEach((r, i) => r === target && out.push({ node: k, idx: i }));
199
- else if (typeof spec.in === 'string') {
200
- if (spec.in === target)
201
- out.push({ node: k, idx: 0 });
202
- }
203
- else if (spec.in && typeof spec.in === 'object')
204
- for (const [ik, r] of Object.entries(spec.in))
205
- if (r === target)
206
- out.push({ node: k, idx: ik });
207
- }
208
- return out;
209
- };
210
- const setRef = (node, idx, value) => {
211
- const spec = g.nodes[node];
212
- if (typeof spec.in === 'string')
213
- spec.in = [value];
214
- else if (Array.isArray(spec.in))
215
- spec.in[idx] = value;
216
- else if (spec.in && typeof spec.in === 'object')
217
- spec.in[idx] = value;
218
- };
219
- for (const [i, op] of ops.entries()) {
220
- const where = `op ${i} (${op.op})`;
221
- switch (op.op) {
222
- case 'set': {
223
- const n = need(op.node, where);
224
- const spec = g.nodes[n];
225
- spec.params = { ...(spec.params ?? {}) };
226
- for (const [k, v] of Object.entries(op.params ?? {})) {
227
- if (v === null)
228
- delete spec.params[k];
229
- else
230
- spec.params[k] = v;
231
- }
232
- break;
233
- }
234
- case 'add': {
235
- if (!op.node || !NAME_RE.test(op.node))
236
- throw new Error(`${where}: "node" must be a valid new node name`);
237
- if (g.nodes[op.node])
238
- throw new Error(`${where}: node "${op.node}" already exists (use set/replace)`);
239
- g.nodes[op.node] = op.spec ?? { type: op.type, ...(op.in !== undefined ? { in: op.in } : {}), ...(op.params ? { params: op.params } : {}) };
240
- if (!g.nodes[op.node].type)
241
- throw new Error(`${where}: "type" is required`);
242
- break;
243
- }
244
- case 'replace': {
245
- const n = need(op.node, where);
246
- g.nodes[n] = op.spec ?? { ...g.nodes[n], ...(op.type ? { type: op.type } : {}), ...(op.params ? { params: op.params } : {}), ...(op.in !== undefined ? { in: op.in } : {}) };
247
- break;
248
- }
249
- case 'remove': {
250
- const n = need(op.node, where);
251
- const refs = refsTo(n);
252
- // reconnect consumers to this node's first input when possible
253
- const def = this.engine.resolveDef(g.nodes[n].type);
254
- const up = def ? wiringOf(g.nodes[n], def).list[0] ?? null : null;
255
- for (const r of refs)
256
- setRef(r.node, r.idx, up);
257
- if (refs.length)
258
- notes.push(`removed "${n}"; rewired ${refs.map((r) => r.node).join(', ')} to ${up ?? '(nothing)'}`);
259
- delete g.nodes[n];
260
- if (g.output === n)
261
- delete g.output;
262
- for (const [id, out] of Object.entries(g.outputs ?? {}))
263
- if (out.node === n)
264
- delete g.outputs[id];
265
- break;
266
- }
267
- case 'connect': {
268
- const n = need(op.node, where);
269
- if (op.in !== undefined)
270
- g.nodes[n].in = op.in;
271
- else if (op.input !== undefined) {
272
- const spec = g.nodes[n];
273
- const def = this.engine.resolveDef(spec.type);
274
- const list = def ? wiringOf(spec, def).list.slice() : [];
275
- while (list.length <= op.input)
276
- list.push(null);
277
- list[op.input] = op.from ?? null;
278
- spec.in = list;
279
- }
280
- else
281
- throw new Error(`${where}: give "in" (full wiring) or "input" + "from"`);
282
- break;
283
- }
284
- case 'rename': {
285
- const n = need(op.node, where);
286
- if (!op.to || !NAME_RE.test(op.to) || g.nodes[op.to])
287
- throw new Error(`${where}: "to" must be a new valid name`);
288
- g.nodes[op.to] = g.nodes[n];
289
- delete g.nodes[n];
290
- for (const r of refsTo(n))
291
- setRef(r.node, r.idx, op.to);
292
- if (g.output === n)
293
- g.output = op.to;
294
- for (const out of Object.values(g.outputs ?? {}))
295
- if (out.node === n)
296
- out.node = op.to;
297
- // expression references: npoints("old"), ch("old/param") …
298
- const touched = [];
299
- for (const [k, spec] of Object.entries(g.nodes)) {
300
- if (!spec.params)
301
- continue;
302
- const before = JSON.stringify(spec.params);
303
- spec.params = Object.fromEntries(Object.entries(spec.params).map(([pk, pv]) => [pk, renameExprRefs(pv, n, op.to)]));
304
- if (JSON.stringify(spec.params) !== before)
305
- touched.push(k);
306
- }
307
- if (touched.length)
308
- notes.push(`updated expression references to "${n}" in ${touched.join(', ')}`);
309
- break;
310
- }
311
- case 'output':
312
- g.output = need(op.node, where);
313
- break;
314
- case 'vars': {
315
- g.vars = { ...(g.vars ?? {}) };
316
- for (const [k, v] of Object.entries(op.vars ?? {})) {
317
- if (v === null)
318
- delete g.vars[k];
319
- else
320
- g.vars[k] = v;
321
- }
322
- break;
323
- }
324
- case 'bypass':
325
- g.nodes[need(op.node, where)].bypass = op.value ?? true;
326
- break;
327
- case 'export': {
328
- // the target of the default output, or of a named one; null removes it (validated with the graph)
329
- if (op.export === undefined)
330
- throw new Error(`${where}: give "export": a format ("glb"), {format, path?, ...options}, or null`);
331
- if (op.output === undefined) {
332
- if (op.export === null)
333
- delete g.export;
334
- else
335
- g.export = op.export;
336
- break;
337
- }
338
- const out = g.outputs?.[op.output];
339
- if (!out) {
340
- const s = didYouMean(op.output, Object.keys(g.outputs ?? {}));
341
- throw new Error(`${where}: no output "${op.output}"${s.length ? ` — did you mean ${s.join(', ')}?` : ''} (publish it in "outputs" first)`);
342
- }
343
- if (op.export === null)
344
- delete out.export;
345
- else
346
- out.export = op.export;
347
- break;
348
- }
349
- case 'insert': {
350
- const after = need(op.after, `${where} after`);
351
- if (!op.node || !NAME_RE.test(op.node) || g.nodes[op.node])
352
- throw new Error(`${where}: "node" must be a new valid name`);
353
- if (!op.type && !op.spec)
354
- throw new Error(`${where}: "type" is required`);
355
- const consumers = refsTo(after);
356
- g.nodes[op.node] = op.spec ?? { type: op.type, in: [after], ...(op.params ? { params: op.params } : {}) };
357
- for (const r of consumers)
358
- setRef(r.node, r.idx, op.node);
359
- if (g.output === after)
360
- g.output = op.node;
361
- notes.push(`inserted "${op.node}" after "${after}"${consumers.length ? `; now feeds ${consumers.map((c) => c.node).join(', ')}` : ''}`);
362
- break;
363
- }
364
- default: throw new Error(`${where}: unknown op. Use set, add, remove, connect, rename, output, vars, bypass, replace, insert, export`);
365
- }
280
+ let found = '';
281
+ if (o.engine === 'none')
282
+ m.engine = 'none';
283
+ else if (o.engine)
284
+ m.engine = parseEngineArg(o.engine, abs);
285
+ else if (!had || m.engine === null) {
286
+ const d = detectEngine(abs);
287
+ if (d) {
288
+ m.engine = d.link;
289
+ found = d.below.length ? (d.below.length > 1 ? ` (found below the workspace, ${d.below.length}: ${d.below.map((e) => e.project).join(', ')}; --engine picks another)` : ' (found below the workspace)') : ' (found at or above the workspace)';
366
290
  }
367
- return { graph: g, notes };
368
291
  }
369
- /**
370
- * The one path for an edit, whoever makes it (the MCP edit tool, the viewer's controls): apply the ops, validate
371
- * (an invalid result throws EditRejected listing the per-node errors and stores nothing), store, cook at `frame`,
372
- * then notify the listeners. They hear after the cook so that what they read (lastReport, cached geometry) is the
373
- * new version's; a cook that throws still notifies, since the graph was stored.
374
- */
375
- async edit(name, ops, opts = {}) {
376
- const { graph, notes } = this.applyEdits(name, ops);
377
- const v = this.engine.validate(graph);
378
- if (v.errors.length)
379
- throw new EditRejected(v.errors);
380
- this.setGraph(name, graph);
381
- let report;
382
- try {
383
- report = await this.cook(name, undefined, opts.frame);
384
- }
385
- finally {
386
- this.bump(name);
292
+ // a new workspace is named after its engine project when that has a name (a checkout's folder may be named otherwise)
293
+ if (!had && o.name === undefined && m.engine && m.engine !== 'none')
294
+ m.name = engineProjectName(abs, m.engine) ?? m.name;
295
+ if (!had || o.name !== undefined)
296
+ checkWorkspaceName(m.name, o.name === undefined ? `--name <another name>: it took "${m.name}" from ${m.engine && m.engine !== 'none' ? 'its engine project' : 'its folder'}` : '--name <another name>', abs);
297
+ for (const l of o.libraries ?? []) {
298
+ const entry = workspaceLibraryEntry(abs, l, o.cwd);
299
+ if (!m.libraries.includes(entry))
300
+ m.libraries.push(entry);
301
+ }
302
+ if (o.follow !== undefined)
303
+ m.follow = o.follow;
304
+ writeWorkspace(abs, m);
305
+ workspaceRepoFiles(abs);
306
+ // a registered workspace renamed is registered again under its new name (the old one would name nothing)
307
+ let registered = '';
308
+ try {
309
+ const was = loadConfig().workspaces.find((w) => folderKey(w.path) === folderKey(abs));
310
+ if (was && was.name !== m.name) {
311
+ addWorkspace(m.name, abs);
312
+ registered = `registered again under its new name "${m.name}" (it was "${was.name}")`;
387
313
  }
388
- return { graph: this.getGraph(name), notes, report };
389
314
  }
390
- async cook(name, target, frame) {
391
- const g = this.getGraph(name);
392
- const r = await this.engine.cook(g, { target, frame });
393
- if (!target)
394
- this.lastReport.set(name, r);
395
- return r;
315
+ catch (e) {
316
+ registered = `still registered under its old name: ${e.message}`;
396
317
  }
318
+ const scan = scanWorkspace(abs, m);
319
+ const engineLines = [];
320
+ const project = engineFile(abs, m);
321
+ if (m.engine && m.engine !== 'none' && project) {
322
+ if (m.engine.type === 'unreal' && !unrealSees(abs, project))
323
+ engineLines.push(` Unreal will not see this workspace: it imports only what lies under the project's Content/ folder (or a plugin's Content/); move the workspace there, so the engine imports each package's exports/`);
324
+ const home = path.dirname(project);
325
+ if (within(home, abs) && path.resolve(home) !== abs) {
326
+ const outside = scan.packages.filter((p) => !within(p.dir, home)).map((p) => p.rel);
327
+ if (outside.length)
328
+ engineLines.push(` packages outside the engine project's folder (${rel(abs, home)}/), whose exports the engine does not import: ${outside.slice(0, 20).join(', ')}${outside.length > 20 ? ` and ${outside.length - 20} more` : ''}`);
329
+ }
330
+ if (m.engine.type === 'godot')
331
+ engineLines.push(...godotPresetReport(home).map((l) => ` ${l}`));
332
+ }
333
+ // Godot imports none of TopoTopo's working folders (versions/, packages/, inputs/)
334
+ const ignored = scan.packages.flatMap((p) => godotIgnore(p.dir));
335
+ // the packages inside that kept their own copies share the workspace's now
336
+ const gathered = gatherCopies(abs);
337
+ const libs = resolveListed(abs, m.libraries);
338
+ const text = [
339
+ `${had ? 'updated' : 'made'} the workspace "${m.name}" (${path.join(abs, WORKSPACE_FILE)})${registered ? `; ${registered}` : ''}`,
340
+ `engine: ${m.engine === 'none' ? 'none (kept: --engine godot:<path> or unreal:<path> names one)' : m.engine ? `${m.engine.type} ${m.engine.project}${found}` : `none found (--engine godot:<path>|unreal:<path>|none)`}`,
341
+ ...engineLines,
342
+ `shared libraries: ${libs.libs.length ? libs.libs.map((l) => l.entry).join(', ') : `none yet (${program()} workspace library add <name or folder>${workspaceFlag(abs, o.cwd)} lists one)`}; its packages find each other by themselves, then look in these, then in TopoTopo's built-in library`,
343
+ ...libs.problems.map((p) => ` problem: ${p}`),
344
+ `packages: ${scan.packages.length}${scan.workspaces.length ? `; other workspaces inside, not scanned: ${scan.workspaces.map((w) => rel(abs, w)).join(', ')}` : ''}`,
345
+ `follow its own packages live: ${m.follow ? 'on (their working folders inside the workspace show in the viewer and renders, for looking; exports use the published versions)' : 'off'}`,
346
+ ...(ignored.length ? [`kept Godot's importer out of the packages' working folders: added ${ignored.length} .gdignore file${ignored.length === 1 ? '' : 's'} (versions/, packages/, inputs/)`] : []),
347
+ ...gathered,
348
+ ].join('\n');
349
+ return { dir: abs, manifest: m, text };
350
+ }
351
+ /**
352
+ * The workspace around a folder in a few lines: its name and file, its engine project, the shared libraries it lists
353
+ * (and what is wrong with an entry), whether it follows its own packages, and the packages inside it (scanned) with
354
+ * what they publish and use. Throws when the folder is in no workspace, saying how one is made.
355
+ */
356
+ export function workspaceText(start) {
357
+ const ws = workspaceOf(start);
358
+ const m = readWorkspace(ws);
359
+ const libs = resolveListed(ws, m.libraries);
360
+ const scan = scanWorkspace(ws, m);
361
+ const lines = [
362
+ `workspace "${m.name}" (${path.join(ws, WORKSPACE_FILE)})`,
363
+ `engine: ${m.engine === 'none' ? 'none' : m.engine ? `${m.engine.type} ${m.engine.project}` : 'none found'}`,
364
+ `shared libraries: ${libs.libs.length ? libs.libs.map((l) => `${l.entry} (${l.root}${l.name !== l.entry ? `, named "${l.name}"` : ''})`).join(', ') : 'none'}; its packages find each other by themselves, then look in these, then in TopoTopo's built-in library`,
365
+ `follow its own packages live: ${m.follow ? 'on (the working folders of its own packages, for looking; exports use the published versions)' : 'off'}`,
366
+ `uses: ${Object.keys(m.uses).length ? Object.entries(m.uses).map(([k, v]) => `${k} ${v}`).join(', ') : 'nothing yet'}; one copy for every package inside (${WORKSPACE_PACKAGES}/), the packages that publish keep their own`,
367
+ `packages: ${scan.packages.length}`,
368
+ ...scan.packages.slice(0, 40).map((p) => {
369
+ const own = copiesFor(p.dir).workspace === null;
370
+ const uses = Object.entries(p.manifest.uses);
371
+ const listed = uses.map(([k, v]) => `${k} ${v}`).join(', ');
372
+ return ` ${p.rel}${p.manifest.name ? ` package ${p.manifest.name}` : ''}${!uses.length ? '' : own ? ` uses ${listed} (its own copies)` : ` its manifest still uses ${listed}: ${program()} workspace init ${ws} moves them into the workspace's`}`;
373
+ }),
374
+ ...(scan.packages.length > 40 ? [` … ${scan.packages.length - 40} more`] : []),
375
+ ...(scan.workspaces.length ? [`other workspaces inside, not scanned: ${scan.workspaces.map((w) => rel(ws, w)).join(', ')}`] : []),
376
+ ];
377
+ const problems = [...libs.problems, ...scan.problems];
378
+ if (problems.length)
379
+ lines.push(`problems: ${problems.length}`, ...problems.map((x) => ` ${x}`));
380
+ return lines.join('\n');
397
381
  }