topotopo 0.4.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 (336) hide show
  1. package/NOTICE +10 -10
  2. package/README.md +460 -117
  3. package/dist/cli.js +323 -146
  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 +196 -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 +44 -5
  191. package/dist/render/preview.d.ts +15 -4
  192. package/dist/render/preview.js +6 -4
  193. package/dist/render/raster.d.ts +66 -5
  194. package/dist/render/raster.js +506 -138
  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 +17 -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
@@ -0,0 +1,584 @@
1
+ // The packages a package uses, in the live viewer (the registry is src/packages/registry.ts, Update's before/after
2
+ // src/packages/update.ts): what the page's Packages tab shows, each package it uses with the version in use and
3
+ // its outputs' kinds and tags, the updates its libraries have and their notes, its working folder and whether this
4
+ // session follows it; the before/after of an update, with progress events and a stop of its own (its cooks are not the
5
+ // session's, so the session's stop does not reach them); applying it; and the follow switch. Following lasts as
6
+ // long as the viewer and is never saved. The working folders of the packages it uses are watched: a save in
7
+ // one the session follows cooks the graphs that use it again, a save in another is told to the pages (they offer to
8
+ // follow it), and a version published there is a new update.
9
+ //
10
+ // GET /api/packages the package and the packages it uses (package null: the graphs are in no package)
11
+ // GET /api/packages/search ?q&kind&tag: the outputs of the packages in TopoTopo's built-in library and the places
12
+ // the package looks in, by words, kind and tag, and whether the package can use them (Find packages)
13
+ // GET /api/packages/author in a package that publishes versions: its last version, and whether its files changed since
14
+ // POST /api/packages/check in a package that publishes versions: the publish dry run (every check, nothing written)
15
+ // POST /api/packages/compare {package, to?}: the before/after, answered when it is done or stopped
16
+ // GET /api/packages/compare the last before/after in full, and the one in progress
17
+ // GET /api/packages/compare/geo ?id&place&side=a|b|overlay: a place cooked with one version, or both overlaid
18
+ // POST /api/packages/stop stop the before/after at its next node; what was compared stays
19
+ // POST /api/packages/update {package, from, to}: apply the update; the graphs that use it cook again
20
+ // POST /api/packages/follow {package, on}: use its working folder instead of its copy for this session, or stop
21
+ // POST /api/packages/dismiss {package}: drop the list of what the graphs must change kept after a big update
22
+ // Events: {packages: n} when what the tab shows changed, with saved: "owner/name" after a save in the working folder of
23
+ // a package the session does not follow; {compare: {...}} the progress of a before/after and its end.
24
+ import { isGraph } from '../graph/types.js';
25
+ import fs from 'node:fs';
26
+ import path from 'node:path';
27
+ import { diffOverlay } from '../explain.js';
28
+ import { packagesNamedIn, packagesUsed } from '../graph/packages.js';
29
+ import { copiesFor, placeText, readUses } from '../package.js';
30
+ import { compareVersions, isDefaultOutput, loadPackage, PackageUses, publishedVersions, publishPackage, searchPackages, startsBigVersion, workingHash } from '../packages/registry.js';
31
+ import { BUILTIN_LIBRARY } from '../config.js';
32
+ import { parsePackageName } from '../graph/scope.js';
33
+ import { applyUpdate, beforeAfter, setText } from '../packages/update.js';
34
+ import { previewGLB } from '../render/preview.js';
35
+ import { MANIFEST_EXT } from '../session.js';
36
+ /** What a version holds besides its record and its manifest (<id>.topo): a change there is a save of the working folder (and versions/ a publish). */
37
+ const SAVED = new Set(['graphs', 'assets', 'inputs', 'packages']);
38
+ function err(status, message) { throw Object.assign(new Error(message), { status }); }
39
+ /** The registry's errors say what is wrong and what to do: they are the request's (400). */
40
+ function asked(f) {
41
+ try {
42
+ return f();
43
+ }
44
+ catch (e) {
45
+ if (typeof e?.status === 'number')
46
+ throw e;
47
+ return err(400, String(e?.message ?? e));
48
+ }
49
+ }
50
+ const sameDir = (a, b) => (process.platform === 'win32' ? a.toLowerCase() === b.toLowerCase() : a === b);
51
+ const versionRow = (v) => ({ version: v.version, note: v.note, published: v.published, big: startsBigVersion(v.version), marked: !!v.big });
52
+ /** A version's outputs by the node type a graph names them with, with their kinds and tags (PackageRow.outputs). */
53
+ const outputRows = (pkg, v, used = new Set()) => {
54
+ const isDefault = (o) => isDefaultOutput(v, o);
55
+ // used: a graph names it, or names the package alone and it is the default output
56
+ const row = (type, o, dflt) => ({
57
+ type, ...(o.label ? { label: o.label } : {}), ...(o.kind ? { kind: o.kind } : {}), tags: o.tags ?? [], ...(used.has(type) || (dflt && used.has(pkg)) ? { used: true } : {}),
58
+ });
59
+ const rows = Object.entries(v.outputs).map(([k, o]) => row(`${pkg}/${k}`, o, isDefault(o)));
60
+ return Object.values(v.outputs).some(isDefault) ? rows : [row(pkg, v.default, true), ...rows];
61
+ };
62
+ const byName = (a, b) => (a.package < b.package ? -1 : a.package > b.package ? 1 : 0);
63
+ /**
64
+ * The package output types a node names, as its type and in its nested graphs (foreach and solver bodies), as
65
+ * "owner/name/output" or "owner/name".
66
+ */
67
+ function typesNamedBy(node, depth = 0) {
68
+ if (!node || typeof node !== 'object' || depth > 64)
69
+ return [];
70
+ const out = [], n = node;
71
+ if (typeof n.type === 'string' && n.type.includes('/') && typeof parsePackageName(n.type) !== 'string')
72
+ out.push(n.type);
73
+ if (n.params && typeof n.params === 'object')
74
+ for (const v of Object.values(n.params))
75
+ if (isGraph(v))
76
+ for (const inner of Object.values(v.nodes))
77
+ out.push(...typesNamedBy(inner, depth + 1));
78
+ return out;
79
+ }
80
+ const packageOf = (type) => type.split('/').slice(0, 2).join('/');
81
+ /** The folder of TopoTopo's own repository, whose library/ holds the built-in packages' working folders. */
82
+ const TOPOTOPO_REPO = path.dirname(BUILTIN_LIBRARY.path);
83
+ const inside = (dir, root) => { const r = path.relative(root, dir); return !r.startsWith('..') && !path.isAbsolute(r); };
84
+ export function createPackages(ws, broadcast) {
85
+ const pk = ws.packages instanceof PackageUses ? ws.packages : null;
86
+ let closed = false, n = 0, shown = '', lastStamp = '';
87
+ /** what the graphs must change for a big update applied in this viewer, by package */
88
+ const kept = new Map();
89
+ /** The packages in use, or the reason there are none to work with (400). */
90
+ const need = () => {
91
+ if (!pk)
92
+ err(400, 'this viewer opened no package: its graphs use no packages (topotopo edit <package folder>, or topotopo view <graph.json> on a graph in a package)');
93
+ asked(() => pk.package());
94
+ return pk;
95
+ };
96
+ // ---------------------------------------------------------------- the state
97
+ function state() {
98
+ const base = { running: run?.progress ?? null, compare: last ? { id: last.id, package: last.result.target.package, from: last.result.target.from, to: last.result.target.to } : null };
99
+ if (!pk?.dir)
100
+ return { package: null, packages: [], problems: [], ...base };
101
+ pk.refresh();
102
+ if (!pk.manifest)
103
+ return { package: { id: '', title: '', label: pk.label, dir: pk.dir, places: [], name: null }, packages: [], problems: [pk.error ?? `the manifest of ${pk.dir} cannot be read`], ...base };
104
+ const problems = [];
105
+ let outdated = [];
106
+ try {
107
+ outdated = pk.outdated();
108
+ }
109
+ catch (e) {
110
+ problems.push(e.message);
111
+ }
112
+ const following = new Map(pk.following().map((f) => [f.package, { place: f.place, dir: f.dir }]));
113
+ // where the package's graphs use each package: the nodes, and the output types they name
114
+ const usedBy = new Map(), usedTypes = new Set();
115
+ for (const [graph, g] of ws.graphs)
116
+ for (const [node, spec] of Object.entries(g.nodes)) {
117
+ const types = typesNamedBy(spec);
118
+ for (const type of types)
119
+ usedTypes.add(type);
120
+ for (const pkg of new Set(types.map(packageOf))) {
121
+ const list = usedBy.get(pkg) ?? [];
122
+ list.push({ graph, node, type: types.find((t) => packageOf(t) === pkg) });
123
+ usedBy.set(pkg, list);
124
+ }
125
+ }
126
+ const developing = inside(pk.dir, TOPOTOPO_REPO);
127
+ const row = (o, followed) => {
128
+ const builtin = o.package.startsWith('topotopo/');
129
+ return { builtin, canFollow: !!followed || (o.working.length === 1 && (!builtin || developing)), usedBy: usedBy.get(o.package) ?? [] };
130
+ };
131
+ const packages = outdated.map((o) => {
132
+ const info = pk.copyInfo(o.package, o.version), followed = following.get(o.package) ?? null;
133
+ const outputs = info ? outputRows(o.package, info, usedTypes) : undefined;
134
+ return {
135
+ package: o.package, version: o.version, ...(info ? { note: info.note, published: info.published, outputs } : {}),
136
+ ...(o.small ? { small: o.small } : {}), ...(o.big ? { big: o.big } : {}),
137
+ newer: o.newer.map(versionRow), places: o.places, working: o.working, followed, ...row(o, followed),
138
+ ...(o.error ? { error: o.error } : {}), ...(kept.has(o.package) ? { mustChange: kept.get(o.package) } : {}),
139
+ };
140
+ });
141
+ // a package followed before the package uses it (a working folder without a published version, say)
142
+ for (const [p, f] of following)
143
+ if (!packages.some((r) => r.package === p))
144
+ packages.push({ package: p, version: null, newer: [], places: [f.place], working: [f], followed: f, ...row({ package: p, working: [f] }, f) });
145
+ problems.push(...pk.check());
146
+ const m = pk.manifest;
147
+ let places = [];
148
+ try {
149
+ const l = pk.libraries();
150
+ places = l.libs.map(placeText);
151
+ problems.push(...l.problems);
152
+ }
153
+ catch (e) {
154
+ problems.push(e.message);
155
+ }
156
+ return { package: { id: pk.id ?? '', title: m.title, label: pk.label, dir: pk.dir, places, name: m.name ?? null }, packages: packages.sort(byName), problems: [...new Set(problems)], ...base };
157
+ }
158
+ /** Tell the pages that what the tab shows changed (`force`: after something a page did), and watch its folders. */
159
+ function changed(force = false) {
160
+ if (closed)
161
+ return;
162
+ let s;
163
+ try {
164
+ s = state();
165
+ }
166
+ catch {
167
+ return;
168
+ }
169
+ rewatch(s.packages);
170
+ lastStamp = stamp();
171
+ const key = JSON.stringify({ ...s, running: null, compare: null });
172
+ if (!force && key === shown)
173
+ return;
174
+ shown = key;
175
+ broadcast({ packages: ++n });
176
+ }
177
+ /** What can change the state without the viewer: the manifest, the lock, the versions published in the working folders. */
178
+ const stamp = () => {
179
+ if (!pk?.dir)
180
+ return '';
181
+ const published = [...watchers.keys()].map((d) => { try {
182
+ return fs.readdirSync(path.join(d, 'versions')).sort().join(',');
183
+ }
184
+ catch {
185
+ return '-';
186
+ } });
187
+ return `${pk.revision()}|${published.join(';')}|${pk.following().map((f) => f.package).join(',')}`;
188
+ };
189
+ const check = () => { if (!closed && stamp() !== lastStamp)
190
+ changed(); };
191
+ let soonTimer;
192
+ const soon = () => { clearTimeout(soonTimer); soonTimer = setTimeout(check, 250); soonTimer.unref?.(); };
193
+ // in a package: a build, an edit or the workspace tool may add a package or update one; another process may too (the timer)
194
+ const onGraph = () => soon();
195
+ const timer = pk?.dir ? setInterval(check, 2000) : undefined;
196
+ if (timer) {
197
+ ws.listeners.add(onGraph);
198
+ timer.unref();
199
+ }
200
+ // ---------------------------------------------------------------- the working folders
201
+ const watchers = new Map();
202
+ const saves = new Map();
203
+ function rewatch(rows) {
204
+ const want = new Map();
205
+ for (const r of rows)
206
+ for (const w of [...r.working, ...(r.followed ? [r.followed] : [])])
207
+ want.set(path.resolve(w.dir), r.package);
208
+ for (const [dir, x] of watchers)
209
+ if (want.get(dir) !== x.pkg) {
210
+ x.w.close();
211
+ watchers.delete(dir);
212
+ }
213
+ for (const [dir, p] of want) {
214
+ if (watchers.has(dir))
215
+ continue;
216
+ try {
217
+ const w = fs.watch(dir, { recursive: true }, (_ev, f) => onWorking(p, f ? String(f) : ''));
218
+ w.on('error', () => { w.close(); if (watchers.get(dir)?.w === w)
219
+ watchers.delete(dir); });
220
+ w.unref();
221
+ watchers.set(dir, { w, pkg: p });
222
+ }
223
+ catch { /* not watchable: the timer still sees versions published there */ }
224
+ }
225
+ }
226
+ /** A change in a package's working folder: a publish (versions/), a save, or something a version does not hold. */
227
+ function onWorking(pkg, rel) {
228
+ const parts = rel.split(/[\\/]+/);
229
+ if (!rel || path.isAbsolute(rel) || parts[0] === 'versions') {
230
+ soon();
231
+ return;
232
+ }
233
+ if (!(SAVED.has(parts[0]) || (parts.length === 1 && parts[0].endsWith(MANIFEST_EXT))) || parts.some((x) => x.startsWith('.')))
234
+ return;
235
+ // a folder the session follows cooks the graphs again (pk.watch below); a save in another is offered to the person
236
+ const followed = () => !!pk?.following().some((f) => f.package === pkg);
237
+ if (followed())
238
+ return;
239
+ clearTimeout(saves.get(pkg));
240
+ const t = setTimeout(() => {
241
+ saves.delete(pkg);
242
+ if (!closed && !followed())
243
+ broadcast({ packages: ++n, saved: pkg });
244
+ }, 300);
245
+ t.unref?.();
246
+ saves.set(pkg, t);
247
+ }
248
+ // ---------------------------------------------------------------- cooking the scene again
249
+ /** The graphs that use any of the packages: they name one (in nested graphs too) or use it through assets and graph_ref. */
250
+ const usersOf = (pkgs) => [...ws.graphs].filter(([, g]) => {
251
+ if (packagesNamedIn(g).some((p) => pkgs.includes(p)))
252
+ return true;
253
+ let used = [];
254
+ try {
255
+ used = Object.keys(packagesUsed(ws.engine, g));
256
+ }
257
+ catch { /* it resolves nothing */ }
258
+ return used.some((k) => pkgs.some((p) => k.startsWith(`${p}@`)));
259
+ }).map(([name]) => name);
260
+ const queue = new Set();
261
+ let recooking = null;
262
+ /** Cook the graphs as a whole again, one after the other, and have the pages read them; graphs asked for meanwhile follow. */
263
+ function recook(graphs) {
264
+ for (const g of graphs)
265
+ queue.add(g);
266
+ recooking ??= (async () => {
267
+ try {
268
+ while (queue.size && !closed) {
269
+ const g = queue.values().next().value;
270
+ queue.delete(g);
271
+ if (!ws.graphs.has(g))
272
+ continue;
273
+ // a failure is the graph's report (its nodes show it); the page reads the graph again either way
274
+ try {
275
+ await ws.cook(g);
276
+ }
277
+ catch { /* reported */ }
278
+ ws.bump(g);
279
+ }
280
+ }
281
+ finally {
282
+ recooking = null;
283
+ }
284
+ })();
285
+ return recooking;
286
+ }
287
+ // a save in a working folder this session follows: refresh() has taken it in, the graphs that use it cook again
288
+ if (pk)
289
+ pk.watch(() => { soon(); void recook(usersOf(pk.following().map((f) => f.package))); });
290
+ let run = null, last = null, seq = 0, packageScope = null;
291
+ const send = (r) => { r.progress.elapsed = performance.now() - r.t0; broadcast({ compare: r.progress }); };
292
+ /**
293
+ * Where the package's graphs and assets cook: the engine's root when the session's folder is the package folder (the MCP
294
+ * server, topotopo edit), else (topotopo view keeps its session in a scratch folder) a scope of the package folder
295
+ * with its graphs and assets, read again for each before/after.
296
+ */
297
+ const packageOption = (p) => {
298
+ if (sameDir(path.resolve(ws.dir), p.dir))
299
+ return {};
300
+ packageScope ??= ws.engine.createScope(`package ${p.dir}`, { folder: p.dir, packages: p.resolver });
301
+ loadPackage(ws.engine, p.dir, packageScope);
302
+ return { package: { scope: packageScope, folder: p.dir } };
303
+ };
304
+ /**
305
+ * The before/after of updating `pkg` (to `to`, else the newest version with the same big number), with progress
306
+ * events. One runs at a time: a newer one stops the one before. The person's values tuned without saving play no part:
307
+ * like the CLI's and the agent's, it compares the package as its files hold it, which is what Update changes.
308
+ */
309
+ async function compare(pkg, to) {
310
+ const p = need();
311
+ if (run) {
312
+ const before = run;
313
+ before.progress.superseded = true;
314
+ before.signal.aborted = true;
315
+ await before.done;
316
+ }
317
+ const target = asked(() => p.updateTarget(pkg, to));
318
+ let finish;
319
+ const id = String(++seq), signal = { aborted: false };
320
+ const r = {
321
+ id, signal, t0: performance.now(), done: new Promise((resolve) => { finish = resolve; }),
322
+ progress: { id, package: pkg, from: target.from, to: target.to, big: target.big, done: 0, total: 0, what: 'finding the places the package uses it', elapsed: 0, running: true, stopping: false },
323
+ };
324
+ run = r;
325
+ send(r);
326
+ try {
327
+ const result = await beforeAfter(p, pkg, {
328
+ to: target.to, signal,
329
+ progress: (done, total, what) => { Object.assign(r.progress, { done, total, what }); send(r); },
330
+ ...packageOption(p),
331
+ });
332
+ Object.assign(r.progress, { stopped: result.stopped, done: result.compared.length * 2, total: result.total, what: '' });
333
+ if (r.progress.superseded)
334
+ err(409, 'a newer before/after took the place of this one');
335
+ last = { id, result, glb: new Map() };
336
+ return summary(last);
337
+ }
338
+ catch (e) {
339
+ if (!r.progress.superseded)
340
+ r.progress.error = String(e?.message ?? e);
341
+ throw typeof e?.status === 'number' ? e : Object.assign(e instanceof Error ? e : new Error(String(e)), { status: 400 });
342
+ }
343
+ finally {
344
+ if (run === r)
345
+ run = null;
346
+ r.progress.running = false;
347
+ r.progress.stopping = false;
348
+ send(r);
349
+ finish();
350
+ }
351
+ }
352
+ const sideOf = (s) => ({ ok: s.ok, errors: s.errors, warnings: s.warnings, cooked: s.cooked });
353
+ const useOf = (u) => ({ node: u.node, type: u.type, set: setText(u.spec).trim() });
354
+ /** A before/after for the page: every place and what changed in each, without the geometry (compare/geo serves it). */
355
+ function summary(d) {
356
+ const r = d.result, t = r.target;
357
+ return {
358
+ ok: true, id: d.id, package: r.package, stopped: r.stopped, ms: Math.round(r.ms), comparisons: r.total / 2,
359
+ target: { package: t.package, from: t.from, to: t.to, big: t.big, up: compareVersions(t.to, t.from) > 0, library: t.library, place: t.place, between: t.between.map(versionRow) },
360
+ interfaceBig: r.interfaceBig, interfaceSmall: r.interfaceSmall, mustChange: r.mustChange, problems: r.problems,
361
+ uses: r.uses.map((u) => ({ file: u.file, kind: u.kind, ...useOf(u) })),
362
+ places: r.compared.map((c, index) => ({
363
+ index, file: c.file, kind: c.kind, node: c.node, uses: c.uses.map(useOf), before: sideOf(c.before), after: sideOf(c.after),
364
+ diff: c.diff ? { text: c.diff.text, identical: c.diff.identical, verdict: /^verdict: (.*)$/m.exec(c.diff.text)?.[1] ?? '', hausdorff: Number.isFinite(c.diff.hausdorff) ? c.diff.hausdorff : null } : null,
365
+ notes: c.notes,
366
+ // what the view can show: each side that cooked, and the overlay when both have points to compare
367
+ views: { a: !!c.before.geo, b: !!c.after.geo, overlay: !!(c.geo && c.geo[0].numPoints && c.geo[1].numPoints) },
368
+ })),
369
+ };
370
+ }
371
+ /**
372
+ * The overlay as the view draws it: diffOverlay's colours, without the materials that would tint them. b's polygons
373
+ * and a's (those left where they do not lie on b) are told apart by the material they name, "overlay_b" and
374
+ * "overlay_a": the view draws a's a sliver behind b's, so where the two lie in one plane b's colour shows, without
375
+ * the stripes of two surfaces fighting for each pixel.
376
+ */
377
+ const overlayOf = (a, b) => {
378
+ const g = diffOverlay(a, b);
379
+ g.table('prim').delete('material');
380
+ g.table('detail').delete('materials');
381
+ const m = g.prims.add('material', 'string', 1), nb = b.numPrims;
382
+ for (let p = 0; p < g.numPrims; p++)
383
+ m.set(p, p < nb ? 'overlay_b' : 'overlay_a');
384
+ return g;
385
+ };
386
+ /** A place of the last before/after as a GLB: side a (the version in use), b (the new one), or both overlaid. */
387
+ function placeGLB(d, place, side) {
388
+ const c = d.result.compared[place] ?? err(404, `this before/after has no place ${place}`);
389
+ const t = d.result.target, key = `${place}:${side}`;
390
+ let bytes = d.glb.get(key);
391
+ if (!bytes) {
392
+ const failed = (v, s) => err(422, `with ${t.package} ${v} it does not cook: ${s.errors.join('; ') || 'no geometry'}`);
393
+ let geo;
394
+ if (side === 'a')
395
+ geo = c.before.geo ?? failed(t.from, c.before);
396
+ else if (side === 'b')
397
+ geo = c.after.geo ?? failed(t.to, c.after);
398
+ else if (side === 'overlay') {
399
+ if (!c.geo || !c.geo[0].numPoints || !c.geo[1].numPoints)
400
+ err(422, 'no overlay: it needs points cooked with both versions');
401
+ geo = overlayOf(c.geo[0], c.geo[1]);
402
+ }
403
+ else
404
+ return err(400, 'side is a (the version in use), b (the new version) or overlay');
405
+ bytes = previewGLB(geo);
406
+ d.glb.set(key, bytes);
407
+ bytes.catch(() => d.glb.delete(key));
408
+ }
409
+ return bytes;
410
+ }
411
+ // ---------------------------------------------------------------- Update and follow
412
+ async function update(pkg, from, to) {
413
+ const p = need();
414
+ if (typeof from !== 'string' || typeof to !== 'string')
415
+ err(400, '"from" and "to" are required: the versions of the before/after the person saw');
416
+ if (run?.progress.package === pkg) {
417
+ run.signal.aborted = true;
418
+ await run.done;
419
+ }
420
+ const now = asked(() => readUses(copiesFor(p.dir))[pkg]);
421
+ if (now !== from)
422
+ err(409, now === undefined ? `${p.holder} does not use ${pkg} now: look at its packages again` : `${p.usesFileName} uses ${pkg} ${now} now, not ${from}: look at the before/after again`);
423
+ const r = asked(() => applyUpdate(p, pkg, { from: from, to: to }));
424
+ if (r.mustChange.length)
425
+ kept.set(pkg, { from, to: r.target.to, items: r.mustChange });
426
+ else
427
+ kept.delete(pkg);
428
+ if (last?.result.target.package === pkg)
429
+ last = null;
430
+ changed(true);
431
+ void recook(usersOf([pkg]));
432
+ return { ok: true, text: r.text, package: pkg, from: r.target.from, to: r.target.to, big: r.target.big, mustChange: r.mustChange };
433
+ }
434
+ // ---------------------------------------------------------------- a package that publishes versions
435
+ /** Its last published version, and whether its files changed since (a publish would make a new version). */
436
+ function authorState() {
437
+ const p = need(), m = p.manifest;
438
+ if (!m?.name)
439
+ err(400, `this package has no name to publish under: ${p.usesFileName} names none ("name": "owner/name")`);
440
+ const last = publishedVersions(p.dir, m.name).at(-1);
441
+ let changed = null;
442
+ try {
443
+ changed = last ? workingHash(p.dir) !== last.hash : null;
444
+ }
445
+ catch { /* unreadable files: the check says why */ }
446
+ return { ok: true, package: m.name, last: last?.version ?? null, published: last?.published ?? null, note: last?.note ?? '', changed };
447
+ }
448
+ /** The publish dry run: every check, every output cooked, the number it would get; nothing is written. */
449
+ let checking = null;
450
+ async function checkPublish() {
451
+ const p = need();
452
+ if (!p.manifest?.name)
453
+ err(400, `this package has no name to publish under: ${p.usesFileName} names none ("name": "owner/name")`);
454
+ checking ??= publishPackage(p, { dryRun: true }).finally(() => { checking = null; });
455
+ return { ok: true, check: await checking };
456
+ }
457
+ function follow(pkg, on) {
458
+ const p = need();
459
+ const text = asked(() => p.follow(pkg, on));
460
+ changed(true);
461
+ void recook(usersOf([pkg]));
462
+ return { ok: true, text, followed: p.following().some((f) => f.package === pkg) };
463
+ }
464
+ // the first look, without telling the pages: they ask when they open
465
+ try {
466
+ const s = state();
467
+ rewatch(s.packages);
468
+ shown = JSON.stringify({ ...s, running: null, compare: null });
469
+ lastStamp = stamp();
470
+ }
471
+ catch { /* the next check tries again */ }
472
+ return {
473
+ /** what the Packages tab shows (GET /api/packages) */
474
+ state,
475
+ /**
476
+ * What a change in a package's working folder sets off (`rel`: the file, as the watcher names it), and the check
477
+ * the timer makes, at once: for a test, or a host that knows a folder changed, without waiting for the watchers.
478
+ */
479
+ poke(pkg, rel) {
480
+ if (pkg)
481
+ onWorking(pkg, rel ?? '');
482
+ pk?.poke();
483
+ check();
484
+ },
485
+ close() {
486
+ closed = true;
487
+ if (run)
488
+ run.signal.aborted = true;
489
+ clearInterval(timer);
490
+ clearTimeout(soonTimer);
491
+ for (const t of saves.values())
492
+ clearTimeout(t);
493
+ for (const x of watchers.values())
494
+ x.w.close();
495
+ watchers.clear();
496
+ ws.listeners.delete(onGraph);
497
+ pk?.unwatch();
498
+ last = null;
499
+ },
500
+ async handle(req, res, u, readJSON) {
501
+ if (u.pathname !== '/api/packages' && !u.pathname.startsWith('/api/packages/'))
502
+ return false;
503
+ const json = (status, body) => { res.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store' }); res.end(JSON.stringify(body)); };
504
+ try {
505
+ const gets = ['/api/packages', '/api/packages/search', '/api/packages/author', '/api/packages/compare', '/api/packages/compare/geo'];
506
+ const posts = ['/api/packages/compare', '/api/packages/stop', '/api/packages/update', '/api/packages/follow', '/api/packages/dismiss', '/api/packages/check'];
507
+ if (!gets.includes(u.pathname) && !posts.includes(u.pathname))
508
+ err(404, `no route ${u.pathname}`);
509
+ if (req.method === 'GET' || req.method === 'HEAD') {
510
+ if (u.pathname === '/api/packages') {
511
+ json(200, state());
512
+ return true;
513
+ }
514
+ if (u.pathname === '/api/packages/author') {
515
+ json(200, authorState());
516
+ return true;
517
+ }
518
+ if (u.pathname === '/api/packages/search') {
519
+ // Find packages: the places the package looks in and TopoTopo's built-in packages, and whether this package can use each
520
+ const q = { query: u.searchParams.get('q') ?? '', ...(u.searchParams.get('kind') ? { kind: u.searchParams.get('kind') } : {}), ...(u.searchParams.get('tag') ? { tag: u.searchParams.get('tag') } : {}) };
521
+ const r = asked(() => searchPackages(pk?.start ?? ws.dir, q));
522
+ json(200, { ...r, libraries: r.libraries.map((l) => ({ name: l.name, place: l.place, standing: l.standing, hits: l.hits })) });
523
+ return true;
524
+ }
525
+ if (u.pathname === '/api/packages/compare') {
526
+ json(200, { compare: last ? summary(last) : null, running: run?.progress ?? null });
527
+ return true;
528
+ }
529
+ if (u.pathname === '/api/packages/compare/geo') {
530
+ const id = u.searchParams.get('id'), place = Number(u.searchParams.get('place') || NaN);
531
+ if (!last || last.id !== id)
532
+ err(404, 'this before/after is no longer the last one: run it again');
533
+ if (!Number.isInteger(place) || place < 0)
534
+ err(400, 'place is the index of a place in the before/after');
535
+ const bytes = await placeGLB(last, place, u.searchParams.get('side') ?? '');
536
+ res.writeHead(200, { 'content-type': 'model/gltf-binary', 'cache-control': 'no-store' });
537
+ res.end(bytes);
538
+ return true;
539
+ }
540
+ err(405, 'POST required');
541
+ }
542
+ if (req.method !== 'POST' || !posts.includes(u.pathname))
543
+ err(405, 'GET required');
544
+ const body = await readJSON(req) ?? {};
545
+ if (u.pathname === '/api/packages/check') {
546
+ json(200, await checkPublish());
547
+ return true;
548
+ }
549
+ if (u.pathname === '/api/packages/stop') {
550
+ if (run) {
551
+ run.signal.aborted = true;
552
+ run.progress.stopping = true;
553
+ send(run);
554
+ }
555
+ json(200, { ok: true, stopping: !!run });
556
+ return true;
557
+ }
558
+ const pkg = body.package;
559
+ if (typeof pkg !== 'string' || !pkg)
560
+ err(400, '"package" is required: "owner/name", a package the open package uses (GET /api/packages lists them)');
561
+ if (u.pathname === '/api/packages/compare') {
562
+ if (body.to !== undefined && typeof body.to !== 'string')
563
+ err(400, '"to" is a version, such as "2.0"');
564
+ json(200, await compare(pkg, body.to));
565
+ }
566
+ else if (u.pathname === '/api/packages/update')
567
+ json(200, await update(pkg, body.from, body.to));
568
+ else if (u.pathname === '/api/packages/follow')
569
+ json(200, follow(pkg, body.on !== false));
570
+ else {
571
+ kept.delete(pkg);
572
+ changed(true);
573
+ json(200, { ok: true });
574
+ }
575
+ }
576
+ catch (e) {
577
+ if (res.headersSent || res.destroyed)
578
+ return true;
579
+ json(typeof e?.status === 'number' ? e.status : 500, { ok: false, error: String(e?.message ?? e) });
580
+ }
581
+ return true;
582
+ },
583
+ };
584
+ }
@@ -1,4 +1,5 @@
1
- import type { Workspace } from '../workspace.ts';
1
+ import type { Session } from '../session.ts';
2
+ import type { GraphSource } from './graph-file.ts';
2
3
  import type { Geometry } from '../core/geometry.ts';
3
4
  export declare const appDir: string;
4
5
  export declare const threeDir: string;
@@ -39,25 +40,29 @@ export declare function markersGeometry(list: Marker[]): Geometry;
39
40
  export interface ViewerOptions {
40
41
  /**
41
42
  * Where the inputs folder is, in words that follow "inputs/" on the page: `topotopo view` passes "beside house.json".
42
- * Default: "in the workspace" (or the folder that holds it, when the workspace was given another inputs folder).
43
+ * Default: "in the package" (or the folder that holds it, when the package was given another inputs folder).
43
44
  */
44
45
  inputsWhere?: string;
45
46
  /**
46
- * Called after the page sets an export target in a graph: `topotopo view` writes it back into the graph file, which
47
- * is the only source there (an MCP workspace stores the graph itself).
47
+ * The graph file a graph comes from when it is not the package's own (`topotopo view`: viewGraphFile). The
48
+ * controls then set session values over that graph (Session.sessionVars) instead of editing it: they survive
49
+ * reloads of the file, show where they differ from it, and POST /api/vars/save writes them into its vars. Export
50
+ * targets set on the page go into the file. Both are minimal edits of its text.
48
51
  */
49
- persistGraph?: (graph: string) => void;
52
+ source?: GraphSource;
50
53
  }
51
- /** A running viewer: its URL, the open pages (SSE clients), a workspace swap, and close. */
54
+ /** A running viewer: its URL, the open pages (SSE clients), a session swap, and close. */
52
55
  export interface Viewer {
53
56
  url: string;
54
57
  /** pages open now (event-stream connections) */
55
58
  clients: () => number;
56
59
  /**
57
- * Show another workspace (the MCP library tool's open): the routes serve it from now on and every open page
60
+ * Show another package (the MCP workspace tool's open): the routes serve it from now on and every open page
58
61
  * reconnects and reloads, so the URL stays the same.
59
62
  */
60
- setWorkspace: (ws: Workspace) => void;
63
+ setSession: (ws: Session) => void;
64
+ /** what a change in a package's working folder sets off, without waiting for the file watchers (tests) */
65
+ pokePackages: (pkg?: string, rel?: string) => void;
61
66
  close: () => void;
62
67
  }
63
- export declare function startViewer(ws: Workspace, port?: number, opts?: ViewerOptions): Promise<Viewer>;
68
+ export declare function startViewer(ws: Session, port?: number, opts?: ViewerOptions): Promise<Viewer>;