topotopo 0.4.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (336) hide show
  1. package/NOTICE +10 -10
  2. package/README.md +460 -117
  3. package/dist/cli.js +327 -147
  4. package/dist/config.d.ts +48 -0
  5. package/dist/config.js +170 -0
  6. package/dist/core/bake.d.ts +14 -3
  7. package/dist/core/bake.js +153 -4
  8. package/dist/core/bevel.d.ts +3 -1
  9. package/dist/core/bevel.js +76 -3
  10. package/dist/core/decimate.d.ts +65 -0
  11. package/dist/core/decimate.js +409 -3
  12. package/dist/core/erosion.d.ts +37 -0
  13. package/dist/core/erosion.js +41 -1
  14. package/dist/core/geometry.d.ts +5 -1
  15. package/dist/core/geometry.js +203 -3
  16. package/dist/core/heightfield.d.ts +27 -4
  17. package/dist/core/heightfield.js +54 -16
  18. package/dist/core/intrinsics.d.ts +7 -0
  19. package/dist/core/intrinsics.js +94 -0
  20. package/dist/core/manifold.d.ts +12 -1
  21. package/dist/core/manifold.js +78 -6
  22. package/dist/core/materials.d.ts +7 -0
  23. package/dist/core/materials.js +45 -0
  24. package/dist/core/noise.d.ts +9 -0
  25. package/dist/core/noise.js +10 -1
  26. package/dist/core/polymerge.d.ts +21 -0
  27. package/dist/core/polymerge.js +327 -0
  28. package/dist/core/repair.d.ts +2 -0
  29. package/dist/core/repair.js +2 -0
  30. package/dist/core/report.d.ts +70 -0
  31. package/dist/core/report.js +275 -0
  32. package/dist/core/scene.js +2 -1
  33. package/dist/core/sha256.d.ts +4 -0
  34. package/dist/core/sha256.js +69 -0
  35. package/dist/core/shapes.d.ts +3 -0
  36. package/dist/core/shapes.js +34 -0
  37. package/dist/core/snippet-lib.d.ts +14 -1
  38. package/dist/core/snippet-lib.js +39 -13
  39. package/dist/core/tangents.d.ts +2 -0
  40. package/dist/core/tangents.js +5 -1
  41. package/dist/core/texnoise.d.ts +6 -1
  42. package/dist/core/texnoise.js +6 -2
  43. package/dist/core/texsdf.d.ts +131 -0
  44. package/dist/core/texsdf.js +637 -0
  45. package/dist/core/texture.d.ts +163 -9
  46. package/dist/core/texture.js +844 -20
  47. package/dist/core/topology.d.ts +10 -0
  48. package/dist/core/topology.js +168 -0
  49. package/dist/core/unwrap.d.ts +72 -0
  50. package/dist/core/unwrap.js +800 -0
  51. package/dist/core/usercode.d.ts +27 -0
  52. package/dist/core/usercode.js +87 -0
  53. package/dist/core/uv.d.ts +4 -18
  54. package/dist/core/uv.js +35 -188
  55. package/dist/core/uvislands.d.ts +62 -0
  56. package/dist/core/uvislands.js +574 -0
  57. package/dist/core/uvoverlap.d.ts +58 -0
  58. package/dist/core/uvoverlap.js +220 -0
  59. package/dist/core/uvpack.d.ts +64 -0
  60. package/dist/core/uvpack.js +628 -0
  61. package/dist/core/uvreport.d.ts +61 -0
  62. package/dist/core/uvreport.js +207 -143
  63. package/dist/core/wrangle.d.ts +6 -1
  64. package/dist/core/wrangle.js +27 -16
  65. package/dist/core/xatlas.d.ts +16 -1
  66. package/dist/core/xatlas.js +66 -62
  67. package/dist/engines.d.ts +63 -0
  68. package/dist/engines.js +180 -0
  69. package/dist/explain.d.ts +4 -3
  70. package/dist/explain.js +129 -12
  71. package/dist/graph/engine.d.ts +92 -29
  72. package/dist/graph/engine.js +298 -148
  73. package/dist/graph/expr.d.ts +6 -3
  74. package/dist/graph/expr.js +18 -8
  75. package/dist/graph/outputs.d.ts +23 -0
  76. package/dist/graph/outputs.js +41 -0
  77. package/dist/graph/packages.d.ts +72 -0
  78. package/dist/graph/packages.js +261 -0
  79. package/dist/graph/parallel.d.ts +3 -1
  80. package/dist/graph/parallel.js +4 -1
  81. package/dist/graph/params.d.ts +6 -0
  82. package/dist/graph/params.js +34 -7
  83. package/dist/graph/scope.d.ts +55 -0
  84. package/dist/graph/scope.js +14 -0
  85. package/dist/graph/types.d.ts +75 -12
  86. package/dist/graph/types.js +4 -2
  87. package/dist/graph/vars.d.ts +16 -0
  88. package/dist/graph/vars.js +80 -0
  89. package/dist/host/artifacts.d.ts +10 -1
  90. package/dist/host/artifacts.js +37 -6
  91. package/dist/host/cook.d.ts +241 -0
  92. package/dist/host/cook.js +844 -0
  93. package/dist/host/export-targets.d.ts +42 -5
  94. package/dist/host/export-targets.js +72 -13
  95. package/dist/host/godot-commands.d.ts +4 -0
  96. package/dist/host/godot-commands.js +21 -0
  97. package/dist/host/godot.d.ts +183 -0
  98. package/dist/host/godot.js +916 -0
  99. package/dist/host/node.d.ts +12 -7
  100. package/dist/host/node.js +27 -9
  101. package/dist/host/pool.js +51 -2
  102. package/dist/host/sidecars.d.ts +8 -0
  103. package/dist/host/sidecars.js +50 -0
  104. package/dist/host/types.d.ts +19 -6
  105. package/dist/host/version.d.ts +1 -0
  106. package/dist/host/version.js +3 -0
  107. package/dist/host/worker.js +5 -2
  108. package/dist/index.d.ts +2 -2
  109. package/dist/index.js +1 -1
  110. package/dist/inspect.d.ts +80 -2
  111. package/dist/inspect.js +265 -30
  112. package/dist/io/common.d.ts +25 -5
  113. package/dist/io/export.js +2 -1
  114. package/dist/io/files.d.ts +23 -4
  115. package/dist/io/files.js +60 -8
  116. package/dist/io/gltf.js +134 -47
  117. package/dist/io/heightmap.d.ts +3 -0
  118. package/dist/io/heightmap.js +1 -0
  119. package/dist/io/import.js +10 -0
  120. package/dist/io/inspect-scene.d.ts +55 -0
  121. package/dist/io/inspect-scene.js +155 -0
  122. package/dist/io/kinds.d.ts +81 -0
  123. package/dist/io/kinds.js +163 -0
  124. package/dist/io/points.d.ts +2 -1
  125. package/dist/io/points.js +3 -1
  126. package/dist/io/sidecars.d.ts +24 -0
  127. package/dist/io/sidecars.js +57 -0
  128. package/dist/io/source.d.ts +65 -0
  129. package/dist/io/source.js +112 -0
  130. package/dist/io/targets.d.ts +47 -3
  131. package/dist/io/targets.js +148 -13
  132. package/dist/io/textures.js +21 -1
  133. package/dist/io/unreal.js +5 -1
  134. package/dist/mcp/docs.d.ts +10 -1
  135. package/dist/mcp/docs.js +786 -143
  136. package/dist/mcp/inputs.d.ts +12 -5
  137. package/dist/mcp/inputs.js +50 -13
  138. package/dist/mcp/server.js +56 -27
  139. package/dist/mcp/tools.d.ts +14 -7
  140. package/dist/mcp/tools.js +198 -103
  141. package/dist/mcp/verify.d.ts +2 -2
  142. package/dist/mcp/verify.js +1 -1
  143. package/dist/mcp/workspace.d.ts +15 -0
  144. package/dist/mcp/workspace.js +349 -0
  145. package/dist/nodes/attributes.js +198 -1
  146. package/dist/nodes/bake.js +151 -47
  147. package/dist/nodes/beam.d.ts +1 -0
  148. package/dist/nodes/beam.js +201 -0
  149. package/dist/nodes/bevel.js +51 -3
  150. package/dist/nodes/cloth.js +2 -0
  151. package/dist/nodes/code.js +21 -9
  152. package/dist/nodes/curves.js +433 -93
  153. package/dist/nodes/flow.js +53 -33
  154. package/dist/nodes/generate.js +12 -38
  155. package/dist/nodes/heightfield.js +248 -77
  156. package/dist/nodes/imageops.js +16 -19
  157. package/dist/nodes/index.d.ts +1 -0
  158. package/dist/nodes/index.js +1 -0
  159. package/dist/nodes/material.js +89 -24
  160. package/dist/nodes/measure.js +43 -17
  161. package/dist/nodes/particles.js +2 -0
  162. package/dist/nodes/pcg.js +6 -5
  163. package/dist/nodes/procedural.js +4 -3
  164. package/dist/nodes/remesh.js +71 -15
  165. package/dist/nodes/scene.js +4 -2
  166. package/dist/nodes/sdf.js +10 -5
  167. package/dist/nodes/solid.js +20 -5
  168. package/dist/nodes/splines.d.ts +15 -1
  169. package/dist/nodes/splines.js +112 -105
  170. package/dist/nodes/texture.d.ts +21 -6
  171. package/dist/nodes/texture.js +1318 -185
  172. package/dist/nodes/topology.d.ts +7 -0
  173. package/dist/nodes/topology.js +133 -6
  174. package/dist/nodes/transform.js +6 -2
  175. package/dist/nodes/uv.js +192 -174
  176. package/dist/nodes/wasmcall.js +5 -1
  177. package/dist/open.d.ts +19 -0
  178. package/dist/open.js +12 -0
  179. package/dist/package.d.ts +288 -0
  180. package/dist/package.js +772 -0
  181. package/dist/packages/check.d.ts +32 -0
  182. package/dist/packages/check.js +169 -0
  183. package/dist/packages/commands.d.ts +57 -0
  184. package/dist/packages/commands.js +537 -0
  185. package/dist/packages/registry.d.ts +796 -0
  186. package/dist/packages/registry.js +2998 -0
  187. package/dist/packages/update.d.ts +124 -0
  188. package/dist/packages/update.js +476 -0
  189. package/dist/render/options.d.ts +2 -0
  190. package/dist/render/options.js +57 -5
  191. package/dist/render/preview.d.ts +17 -4
  192. package/dist/render/preview.js +6 -4
  193. package/dist/render/raster.d.ts +74 -5
  194. package/dist/render/raster.js +527 -143
  195. package/dist/render/texview.d.ts +6 -0
  196. package/dist/render/texview.js +27 -0
  197. package/dist/scan.d.ts +61 -0
  198. package/dist/scan.js +228 -0
  199. package/dist/session.d.ts +311 -0
  200. package/dist/session.js +849 -0
  201. package/dist/viewer/app/api.js +48 -6
  202. package/dist/viewer/app/cooking.js +78 -0
  203. package/dist/viewer/app/embed.js +27 -7
  204. package/dist/viewer/app/export-popover.js +118 -16
  205. package/dist/viewer/app/grid.js +5 -1
  206. package/dist/viewer/app/guides.js +122 -0
  207. package/dist/viewer/app/keymap.js +6 -3
  208. package/dist/viewer/app/layers.js +4 -4
  209. package/dist/viewer/app/main.js +185 -52
  210. package/dist/viewer/app/markers.js +60 -0
  211. package/dist/viewer/app/outliner.js +72 -27
  212. package/dist/viewer/app/output-info.js +45 -0
  213. package/dist/viewer/app/outputs.css +147 -8
  214. package/dist/viewer/app/outputs.js +168 -54
  215. package/dist/viewer/app/packages.js +614 -0
  216. package/dist/viewer/app/props.js +176 -52
  217. package/dist/viewer/app/scene.js +30 -5
  218. package/dist/viewer/app/select.js +4 -3
  219. package/dist/viewer/app/status.js +12 -15
  220. package/dist/viewer/app/style.css +65 -7
  221. package/dist/viewer/app/vars.js +47 -0
  222. package/dist/viewer/app/welcome.js +72 -0
  223. package/dist/viewer/graph-file.d.ts +62 -0
  224. package/dist/viewer/graph-file.js +175 -0
  225. package/dist/viewer/index.html +23 -10
  226. package/dist/viewer/json-edit.d.ts +13 -0
  227. package/dist/viewer/json-edit.js +274 -0
  228. package/dist/viewer/outputs.d.ts +49 -5
  229. package/dist/viewer/outputs.js +264 -56
  230. package/dist/viewer/packages.d.ts +121 -0
  231. package/dist/viewer/packages.js +584 -0
  232. package/dist/viewer/server.d.ts +14 -9
  233. package/dist/viewer/server.js +266 -28
  234. package/dist/web/app/web.css +419 -0
  235. package/dist/web/app/web.js +188 -0
  236. package/dist/{gallery → web}/bake.d.ts +4 -4
  237. package/dist/{gallery → web}/bake.js +24 -15
  238. package/dist/web/folder-page.d.ts +101 -0
  239. package/dist/web/folder-page.js +146 -0
  240. package/dist/web/folders.d.ts +280 -0
  241. package/dist/web/folders.js +970 -0
  242. package/dist/web/library.d.ts +91 -0
  243. package/dist/web/library.js +228 -0
  244. package/dist/web/markdown.d.ts +45 -0
  245. package/dist/web/markdown.js +677 -0
  246. package/dist/web/pages.d.ts +258 -0
  247. package/dist/web/pages.js +301 -0
  248. package/dist/web/server.d.ts +24 -0
  249. package/dist/web/server.js +1068 -0
  250. package/dist/workspace.d.ts +88 -118
  251. package/dist/workspace.js +358 -460
  252. package/integrations/godot/addons/topotopo/LICENSE +202 -0
  253. package/integrations/godot/addons/topotopo/README.md +57 -0
  254. package/integrations/godot/addons/topotopo/context_menu.gd +43 -0
  255. package/integrations/godot/addons/topotopo/dock.gd +266 -0
  256. package/integrations/godot/addons/topotopo/dock.tscn +72 -0
  257. package/integrations/godot/addons/topotopo/export_filter.gd +72 -0
  258. package/integrations/godot/addons/topotopo/gltf_instancing.gd +131 -0
  259. package/integrations/godot/addons/topotopo/icons/topotopo.svg +1 -0
  260. package/integrations/godot/addons/topotopo/inspector.gd +38 -0
  261. package/integrations/godot/addons/topotopo/instances_post_import.gd +111 -0
  262. package/integrations/godot/addons/topotopo/package.gd +23 -0
  263. package/integrations/godot/addons/topotopo/package_importer.gd +187 -0
  264. package/integrations/godot/addons/topotopo/plugin.cfg +7 -0
  265. package/integrations/godot/addons/topotopo/plugin.gd +970 -0
  266. package/integrations/godot/addons/topotopo/record.gd +435 -0
  267. package/integrations/godot/addons/topotopo/runner.gd +458 -0
  268. package/integrations/godot/addons/topotopo/tools/check.gd +42 -0
  269. package/integrations/godot/addons/topotopo/watcher.gd +199 -0
  270. package/kernels/pkg/README.md +2 -1
  271. package/kernels/pkg-simd/README.md +2 -1
  272. package/library/architecture/versions/1.0/architecture.topo +12 -0
  273. package/{shelf → library/architecture/versions/1.0/graphs}/arch.json +3 -3
  274. package/{shelf → library/architecture/versions/1.0/graphs}/beam_truss.json +6 -6
  275. package/{shelf → library/architecture/versions/1.0/graphs}/brick_wall.json +8 -8
  276. package/{shelf → library/architecture/versions/1.0/graphs}/door_frame.json +3 -3
  277. package/{shelf → library/architecture/versions/1.0/graphs}/hex_grid_floor.json +3 -2
  278. package/{shelf → library/architecture/versions/1.0/graphs}/house.json +8 -8
  279. package/library/architecture/versions/1.0/graphs/lineup.json +42 -0
  280. package/{shelf → library/architecture/versions/1.0/graphs}/pillar.json +3 -2
  281. package/{shelf → library/architecture/versions/1.0/graphs}/railing.json +5 -5
  282. package/{shelf → library/architecture/versions/1.0/graphs}/roof_gable.json +2 -2
  283. package/{shelf → library/architecture/versions/1.0/graphs}/roof_hip.json +2 -2
  284. package/{shelf → library/architecture/versions/1.0/graphs}/roof_skeleton.json +2 -1
  285. package/{shelf → library/architecture/versions/1.0/graphs}/scaffold.json +4 -4
  286. package/{shelf → library/architecture/versions/1.0/graphs}/spiral_stairs.json +3 -2
  287. package/{shelf → library/architecture/versions/1.0/graphs}/stairs.json +6 -6
  288. package/{shelf → library/architecture/versions/1.0/graphs}/tile_floor.json +3 -2
  289. package/{shelf → library/architecture/versions/1.0/graphs}/wall_segment.json +10 -10
  290. package/{shelf → library/architecture/versions/1.0/graphs}/window_frame.json +2 -2
  291. package/library/architecture/versions/1.0/version.json +1119 -0
  292. package/{shelf → library/nature/versions/1.0/graphs}/bush.json +2 -2
  293. package/{shelf → library/nature/versions/1.0/graphs}/cliff_block.json +4 -3
  294. package/{shelf → library/nature/versions/1.0/graphs}/forest_patch.json +5 -5
  295. package/{shelf → library/nature/versions/1.0/graphs}/grass_clumps.json +2 -2
  296. package/library/nature/versions/1.0/graphs/lineup.json +24 -0
  297. package/{shelf → library/nature/versions/1.0/graphs}/log.json +6 -6
  298. package/{shelf → library/nature/versions/1.0/graphs}/rock.json +5 -4
  299. package/{shelf → library/nature/versions/1.0/graphs}/scatter_rocks.json +5 -5
  300. package/{shelf → library/nature/versions/1.0/graphs}/tree_lowpoly.json +3 -2
  301. package/library/nature/versions/1.0/nature.topo +12 -0
  302. package/library/nature/versions/1.0/version.json +534 -0
  303. package/{shelf → library/props/versions/1.0/graphs}/barrel.json +5 -4
  304. package/{shelf → library/props/versions/1.0/graphs}/crate.json +3 -3
  305. package/library/props/versions/1.0/graphs/lineup.json +18 -0
  306. package/{shelf → library/props/versions/1.0/graphs}/pallet.json +4 -3
  307. package/{shelf → library/props/versions/1.0/graphs}/pipe_run.json +3 -3
  308. package/{shelf → library/props/versions/1.0/graphs}/sandbag_wall.json +5 -5
  309. package/library/props/versions/1.0/props.topo +12 -0
  310. package/library/props/versions/1.0/version.json +336 -0
  311. package/{shelf → library/street/versions/1.0/graphs}/bench.json +5 -5
  312. package/{shelf → library/street/versions/1.0/graphs}/bollard.json +2 -1
  313. package/{shelf → library/street/versions/1.0/graphs}/cable.json +4 -4
  314. package/{shelf → library/street/versions/1.0/graphs}/fence.json +7 -7
  315. package/{shelf → library/street/versions/1.0/graphs}/lamp_post.json +2 -2
  316. package/library/street/versions/1.0/graphs/lineup.json +22 -0
  317. package/{shelf → library/street/versions/1.0/graphs}/road_strip.json +2 -2
  318. package/{shelf → library/street/versions/1.0/graphs}/sign_post.json +1 -1
  319. package/library/street/versions/1.0/street.topo +12 -0
  320. package/library/street/versions/1.0/version.json +421 -0
  321. package/package.json +13 -8
  322. package/dist/gallery/app/gallery.css +0 -100
  323. package/dist/gallery/app/gallery.js +0 -80
  324. package/dist/gallery/cli.d.ts +0 -4
  325. package/dist/gallery/cli.js +0 -157
  326. package/dist/gallery/library.d.ts +0 -124
  327. package/dist/gallery/library.js +0 -366
  328. package/dist/gallery/pages.d.ts +0 -94
  329. package/dist/gallery/pages.js +0 -148
  330. package/dist/gallery/server.d.ts +0 -21
  331. package/dist/gallery/server.js +0 -391
  332. package/dist/graph/migrate.d.ts +0 -23
  333. package/dist/graph/migrate.js +0 -58
  334. package/dist/mcp/library.d.ts +0 -12
  335. package/dist/mcp/library.js +0 -159
  336. package/shelf/index.json +0 -190
@@ -0,0 +1,1068 @@
1
+ // The web app server: a file explorer of the registered workspaces and libraries. The front page shows each as a
2
+ // card (a few pictures from inside, its packages, folders, files and flags; TopoTopo's built-in library last) and
3
+ // searches every package and output. Every folder below a workspace or library is a page (/w/<workspace>/<path…>/,
4
+ // /l/<library>/<path…>/, src/web/folder-page.ts): its flags, its package when it is one (preview, versions, outputs,
5
+ // who uses it, graphs, Open in editor, Re-bake), its notes, its subfolders as cards and its files by type, which the
6
+ // same addresses serve (read only, inside the folder, with ranges). A package keeps a stable address for boards,
7
+ // /p/<workspace or library>/<id>, which leads to its folder page, with its thumbnail and an iframe embed.
8
+ // It reads files and serves baked previews; it never cooks: bakes run in child processes (BakeQueue) and "Open in
9
+ // editor" starts a `topotopo edit` child. Bound to 127.0.0.1 on a fixed port (stable links); requests must name this
10
+ // server as their Host, and writes must come from its own pages.
11
+ import http from 'node:http';
12
+ import fs from 'node:fs';
13
+ import path from 'node:path';
14
+ import zlib from 'node:zlib';
15
+ import crypto from 'node:crypto';
16
+ import { spawn } from 'node:child_process';
17
+ import { fileURLToPath } from 'node:url';
18
+ import { encodePNG } from '../render/png.js';
19
+ import { MIME, appDir, threeDir } from '../viewer/server.js';
20
+ import { webDir, isStale, listFiles, placeNamed, readBakeState, scanAll } from './library.js';
21
+ import { BUILTIN_LIBRARY, loadConfig } from '../config.js';
22
+ import { readWorkspace, engineFile } from '../workspace.js';
23
+ import { WORKSPACE_PACKAGES } from '../package.js';
24
+ import { folderKey, forgetScans, forgetScansOf, scanTree, unscanned } from '../scan.js';
25
+ import { engineTypeOf } from '../engines.js';
26
+ import { graphFiles } from '../session.js';
27
+ import { builtinLibrary, compareVersions, copyRecord, isDefaultOutput, publishedVersions, startsBigVersion, workingHash } from '../packages/registry.js';
28
+ import { BakeQueue } from './bake.js';
29
+ import { embedPage, esc, frontPage, importMap, modelPage, shell, count } from './pages.js';
30
+ import { folderPage } from './folder-page.js';
31
+ import { PathError, byName, engineTitle, exportSources, exportStale, graphTypes, headingPrefix, kindOf, listFolder, noteHtml, noteId, plumbing, realBelow, resolveIn, rootKey, sendFile, walkTree } from './folders.js';
32
+ const here = path.dirname(fileURLToPath(import.meta.url));
33
+ const assetDir = path.join(here, 'app');
34
+ const cli = path.resolve(here, '..', import.meta.url.endsWith('.ts') ? 'cli.ts' : 'cli.js');
35
+ const RESCAN_MS = 5 * 60_000;
36
+ const EDITOR_START_MS = 60_000;
37
+ /** a folder page shows this many notes as boxes (a README first, documents before text files); the rest are listed with its other files */
38
+ const MAX_NOTE_BOXES = 24;
39
+ /** TopoTopo's built-in library is read again for its page at most this often */
40
+ const BUILTIN_AUDIT_MS = 60_000;
41
+ /**
42
+ * What the pages may load: their own files, and in notes the privacy players of YouTube and Vimeo, the only outside
43
+ * content the web app shows (a note's link to an outside image stays a link).
44
+ */
45
+ const PAGE_CSP = "default-src 'self'; img-src 'self' data:; media-src 'self'; frame-src 'self' https://www.youtube-nocookie.com https://player.vimeo.com; script-src 'self'; style-src 'self' 'unsafe-inline'; connect-src 'self'; object-src 'none'; base-uri 'none'; form-action 'self'; frame-ancestors 'self'";
46
+ /**
47
+ * What a 3D view may load (a model's page, a package's embed): its own files and what a model holds (data: and blob:
48
+ * buffers and textures), three.js through the inline import map (allowed by its hash) and the meshopt decoder's
49
+ * WebAssembly; a glTF's buffers or textures on another site are not fetched.
50
+ */
51
+ const viewCsp = (map, framed) => `default-src 'self'; script-src 'self' 'wasm-unsafe-eval' 'sha256-${crypto.createHash('sha256').update(map).digest('base64')}'; img-src 'self' data: blob:; connect-src 'self' data: blob:; style-src 'unsafe-inline'; object-src 'none'; base-uri 'none'; form-action 'none'${framed ? '' : "; frame-ancestors 'self'"}`;
52
+ /** A note named so is shown first among the boxes of its folder. */
53
+ const README = /^(readme|index)\.(md|txt)$/i;
54
+ class HttpError extends Error {
55
+ status;
56
+ constructor(status, msg) { super(msg); this.status = status; }
57
+ }
58
+ /** A web app answers here already: its URL, or null. */
59
+ export async function runningWeb(port) {
60
+ try {
61
+ const res = await fetch(`http://127.0.0.1:${port}/api/health`, { signal: AbortSignal.timeout(1500) });
62
+ const j = await res.json();
63
+ return j?.web ? `http://127.0.0.1:${port}/` : null;
64
+ }
65
+ catch {
66
+ return null;
67
+ }
68
+ }
69
+ /** The engine project a workspace file names, read as written even when the file is otherwise refused. */
70
+ function engineWritten(ws) {
71
+ try {
72
+ const e = JSON.parse(fs.readFileSync(path.join(ws, 'topotopo-workspace.json'), 'utf8'))?.engine;
73
+ return e && (e.type === 'godot' || e.type === 'unreal') && typeof e.project === 'string' && e.project ? { type: e.type, file: path.resolve(ws, e.project) } : null;
74
+ }
75
+ catch {
76
+ return null;
77
+ }
78
+ }
79
+ const firstLine = (s) => { const l = (s ?? '').trim().split('\n')[0] ?? ''; return l.length > 240 ? `${l.slice(0, 240)}…` : l; };
80
+ export async function startWeb(o = {}) {
81
+ const cfg = o.config ?? loadConfig();
82
+ const log = o.log ?? (() => { });
83
+ const bakeOn = o.bake ?? true;
84
+ let base = '';
85
+ // ---------------------------------------------------------------- workspaces and libraries
86
+ let scans = [];
87
+ const packages = new Map();
88
+ /** the packages by folder (folderKey) */
89
+ const byDir = new Map();
90
+ const keyOf = (p) => `${p.lib}/${p.id}`;
91
+ /** one of TopoTopo's own packages: never baked or edited here */
92
+ const isBuiltin = (p) => p.lib === BUILTIN_LIBRARY.name;
93
+ /**
94
+ * The built-in library's packages, by folder: where their graphs are read (the working folder in TopoTopo's
95
+ * repository, else the newest version) and the output whose thumbnail stands for each.
96
+ */
97
+ const builtinAt = new Map();
98
+ /** TopoTopo's built-in library as a library: its packages' manifests from their working folders or newest versions */
99
+ const scanBuiltin = () => {
100
+ builtinAt.clear();
101
+ const list = builtinLibrary();
102
+ for (const b of list) {
103
+ const newest = b.versions.at(-1);
104
+ const thumb = newest ? Object.keys(newest.outputs).find((x) => fs.existsSync(path.join(b.dir, 'thumbs', `${x}.png`))) ?? null : null;
105
+ builtinAt.set(b.dir, { from: b.from, thumb });
106
+ }
107
+ return {
108
+ name: BUILTIN_LIBRARY.name, root: BUILTIN_LIBRARY.path, problems: [], workspaces: [],
109
+ packages: list.map((b) => ({ lib: BUILTIN_LIBRARY.name, id: b.id, dir: b.dir, rel: b.id, collection: '', manifest: b.manifest, updated: Date.parse(b.versions.at(-1)?.published ?? '') || 0 })),
110
+ };
111
+ };
112
+ /** the registered workspaces: their file (or what is wrong with it), engine project and scan */
113
+ let games = [];
114
+ /** every registered workspace and library as a tree of pages, TopoTopo's built-in library last */
115
+ let roots = [];
116
+ const indexPackages = () => {
117
+ packages.clear();
118
+ byDir.clear();
119
+ // a package's address is its library's or workspace's name and its id: the first folder of an id keeps it (the scan says so)
120
+ for (const s of scans)
121
+ for (const p of s.packages) {
122
+ if (!packages.has(keyOf(p)))
123
+ packages.set(keyOf(p), p);
124
+ if (!byDir.has(folderKey(p.dir)))
125
+ byDir.set(folderKey(p.dir), p);
126
+ }
127
+ };
128
+ /**
129
+ * Read the packages of the workspaces and libraries again: those of `roots` (their folders), else all of them. The
130
+ * audits stay: what changed decides which go (forget()).
131
+ */
132
+ const rescanPackages = (changed) => {
133
+ if (changed)
134
+ for (const d of changed)
135
+ forgetScansOf(d);
136
+ else
137
+ forgetScans();
138
+ // the libraries (but those inside a registered workspace) and the workspaces; TopoTopo's built-in library last,
139
+ // read again each time: a built-in package published while the web app runs shows
140
+ const all = scanAll(cfg);
141
+ games = [];
142
+ for (const [i, s] of all.entries()) {
143
+ if (!s.workspace)
144
+ continue;
145
+ try {
146
+ const m = readWorkspace(s.root), e = engineFile(s.root, m);
147
+ games.push({ name: m.name, dir: s.root, m, engine: e && m.engine && m.engine !== 'none' ? { type: m.engine.type, file: e } : null, scan: s });
148
+ }
149
+ catch (err) {
150
+ // the workspace file cannot be read: its folder pages still show its folders and packages (scanned with the
151
+ // engine project the file names), and the problem as a flag on it
152
+ const engine = engineWritten(s.root);
153
+ const t = scanTree(s.name, s.root, { engine: engine?.file ?? null });
154
+ all[i] = { ...t, problems: t.problems, workspace: true };
155
+ games.push({ name: s.name, dir: s.root, m: null, problem: err.message, engine, scan: all[i] });
156
+ }
157
+ }
158
+ scans = [...all, scanBuiltin()];
159
+ indexPackages();
160
+ roots = [
161
+ ...games.map((g) => ({ kind: 'w', name: g.name, dir: g.dir, engine: g.engine })),
162
+ ...scans.filter((s) => !s.workspace && s.name !== BUILTIN_LIBRARY.name).map((s) => ({ kind: 'l', name: s.name, dir: s.root, engine: null })),
163
+ { kind: 'l', name: BUILTIN_LIBRARY.name, dir: BUILTIN_LIBRARY.path, engine: null, builtin: true },
164
+ ];
165
+ };
166
+ /** The libraries' scans: a workspace's packages are its own. */
167
+ const libraryScans = () => scans.filter((s) => !s.workspace);
168
+ /** Read TopoTopo's built-in library again (a few small files), the other libraries as they were scanned. */
169
+ const refreshBuiltin = () => {
170
+ const b = scanBuiltin();
171
+ scans = [...scans.filter((s) => s.name !== BUILTIN_LIBRARY.name), b];
172
+ indexPackages();
173
+ };
174
+ /** when the packages were last read again for an address none has (a board may keep asking for a removed one) */
175
+ let missRescan = 0;
176
+ const find = (lib, id) => {
177
+ let p = packages.get(`${lib}/${id}`);
178
+ // made a moment ago, before the watch noticed: read the packages again, at most every few seconds
179
+ if (!p && Date.now() - missRescan > 3000) {
180
+ missRescan = Date.now();
181
+ rescanPackages();
182
+ p = packages.get(`${lib}/${id}`);
183
+ }
184
+ if (!p)
185
+ throw new HttpError(404, `no package "${id}" in library "${lib}"`);
186
+ return p;
187
+ };
188
+ /** The workspace or library a package's folder page is in (workspaces and libraries share one set of names). */
189
+ const rootOf = (p) => roots.find((r) => (isBuiltin(p) ? r.builtin : !r.builtin && r.name === p.lib)) ?? roots[roots.length - 1];
190
+ /** A workspace's uses: the version of each package its packages share (its copy's record), the package's page, a newer version. */
191
+ const workspaceUses = (r) => {
192
+ const g = r.kind === 'w' ? games.find((x) => x.name === r.name) : undefined;
193
+ if (!g?.m)
194
+ return [];
195
+ const homes = packageHomes();
196
+ return Object.entries(g.m.uses).map(([name, v]) => {
197
+ let rec = null;
198
+ try {
199
+ rec = JSON.parse(fs.readFileSync(path.join(g.dir, WORKSPACE_PACKAGES, ...name.split('/'), v, 'version.json'), 'utf8'));
200
+ }
201
+ catch { /* no copy yet */ }
202
+ const home = homes.get(name), newest = newestOf(name, homes);
203
+ return { name, version: v, ...(rec ? { note: String(rec.note ?? ''), published: String(rec.published ?? '') } : {}), ...(home ? { url: pageOf(home) } : {}), ...(newest && compareVersions(newest, v) > 0 ? { newest } : {}) };
204
+ });
205
+ };
206
+ const within = (inner, outer) => { const x = path.relative(path.resolve(outer), path.resolve(inner)); return !x.startsWith('..') && !path.isAbsolute(x); };
207
+ // ---------------------------------------------------------------- events (SSE) and bakes
208
+ const clients = new Set();
209
+ const broadcast = (ev) => { const m = `data: ${JSON.stringify(ev)}\n\n`; for (const c of clients)
210
+ c.write(m); };
211
+ const queue = new BakeQueue({
212
+ log,
213
+ onDone: (dir, state) => {
214
+ const p = byDir.get(folderKey(dir));
215
+ if (p) {
216
+ forget(rootKey(rootOf(p)));
217
+ rewarm();
218
+ }
219
+ if (p)
220
+ broadcast({ package: keyOf(p), ok: state?.ok ?? false, version: state?.at ?? 0 });
221
+ },
222
+ });
223
+ /**
224
+ * A package's graphs (graphs/, and graph files beside its manifest; a built-in package's where it is read from), and
225
+ * whether it has the one its manifest shows.
226
+ */
227
+ const graphsOf = (p) => graphFiles(builtinAt.get(p.dir)?.from ?? p.dir);
228
+ const hasDefault = (p) => graphsOf(p).has(p.manifest.bake.graph ?? p.manifest.graph);
229
+ const bakeIfStale = (p) => {
230
+ // nothing to bake before the package has its default graph: its card says so ("no default graph yet"); TopoTopo's
231
+ // own packages are never baked here
232
+ if (!bakeOn || isBuiltin(p) || queue.pending(p.dir) || !hasDefault(p))
233
+ return;
234
+ try {
235
+ if (isStale(p) && queue.add(p.dir))
236
+ broadcast({ package: keyOf(p), baking: true });
237
+ }
238
+ catch { /* removed meanwhile */ }
239
+ };
240
+ const audits = new Map();
241
+ /** the audits under way, and each tree's count of changes (an audit begun before a change is not kept) */
242
+ const auditing = new Map();
243
+ const changes = new Map();
244
+ /** the links of the notes the walks read, by file: a walk again reads only the notes that changed */
245
+ const noteLinks = new Map();
246
+ const forget = (key) => { audits.delete(key); changes.set(key, (changes.get(key) ?? 0) + 1); };
247
+ const forgetAll = () => { for (const r of roots)
248
+ forget(rootKey(r)); };
249
+ let warm, closed = false;
250
+ const rewarm = () => {
251
+ clearTimeout(warm);
252
+ warm = setTimeout(async () => { for (const r of roots) {
253
+ if (closed)
254
+ return;
255
+ try {
256
+ await auditOf(r);
257
+ }
258
+ catch { /* its page says it */ }
259
+ } }, 200);
260
+ warm.unref();
261
+ };
262
+ const rescan = () => { rescanPackages(); forgetAll(); };
263
+ rescan();
264
+ for (const p of packages.values())
265
+ bakeIfStale(p);
266
+ // A change below a library: a manifest, graphs/, assets/ and inputs/ may need a bake; anything else may be a
267
+ // package made, moved or removed, or attachments: read that tree's packages again, forget its audit unless the change
268
+ // is one no audit sees (plumbing, an engine project's own files outside packages), and tell the pages.
269
+ const touched = new Set();
270
+ const changedFolders = new Set();
271
+ const changedRoots = new Set();
272
+ const staleAudits = new Set();
273
+ let changeTimer;
274
+ const onChange = () => {
275
+ clearTimeout(changeTimer);
276
+ changeTimer = setTimeout(() => {
277
+ const before = [...packages.keys()].join('\n');
278
+ rescanPackages([...changedRoots]);
279
+ for (const k of staleAudits)
280
+ forget(k);
281
+ for (const k of touched) {
282
+ const p = packages.get(k);
283
+ if (p)
284
+ bakeIfStale(p);
285
+ }
286
+ for (const p of packages.values())
287
+ if (!readBakeState(p.dir))
288
+ bakeIfStale(p);
289
+ broadcast({ changed: [...touched], list: before !== [...packages.keys()].join('\n'), folders: [...changedFolders] });
290
+ rewarm();
291
+ touched.clear();
292
+ changedFolders.clear();
293
+ changedRoots.clear();
294
+ staleAudits.clear();
295
+ }, 500);
296
+ };
297
+ const watchers = [];
298
+ for (const s of scans) {
299
+ if (s.name === BUILTIN_LIBRARY.name)
300
+ continue; // nothing of it is baked here: read again at each rescan
301
+ try {
302
+ const w = fs.watch(s.root, { recursive: true }, (_ev, f) => {
303
+ const rel = f ? String(f).split(path.sep).join('/') : '';
304
+ if (path.isAbsolute(rel))
305
+ return; // the root itself went away: the periodic rescan notices
306
+ const parts = rel.split('/');
307
+ if (parts.some((x) => x.startsWith('.') || x === 'node_modules'))
308
+ return; // .web/, .cache/, .part files
309
+ const p = scans.find((x) => x.root === s.root)?.packages.find((x) => rel === x.rel || rel.startsWith(x.rel + '/'));
310
+ if (p)
311
+ touched.add(keyOf(p));
312
+ changedRoots.add(s.root);
313
+ for (const r of roots) {
314
+ if (r.dir !== s.root)
315
+ continue;
316
+ changedFolders.add(`${rootKey(r)}/${parts.slice(0, -1).join('/')}`.replace(/\/$/, ''));
317
+ // plumbing, and an engine project's own files (outside packages), are in no audit
318
+ const engine = audits.get(rootKey(r))?.walk.engines.some((e) => rel === e || rel.startsWith(e + '/'));
319
+ if (p || !(engine || parts.slice(0, -1).some((x) => plumbing(x, []))))
320
+ staleAudits.add(rootKey(r));
321
+ }
322
+ onChange();
323
+ });
324
+ w.on('error', () => w.close());
325
+ w.unref();
326
+ watchers.push(w);
327
+ }
328
+ catch { /* no folder (a problem on the page) or no recursive watch: the periodic rescan covers it */ }
329
+ }
330
+ const periodic = setInterval(() => { rescan(); for (const p of packages.values())
331
+ bakeIfStale(p); rewarm(); }, RESCAN_MS);
332
+ periodic.unref();
333
+ // ---------------------------------------------------------------- editors
334
+ const editors = new Map();
335
+ const editorFor = (p) => {
336
+ const have = editors.get(p.dir);
337
+ if (have && have.child.exitCode === null)
338
+ return have.url;
339
+ const child = spawn(process.execPath, [cli, 'edit', p.dir, '--json'], { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });
340
+ const url = new Promise((resolve, reject) => {
341
+ let out = '', err = '';
342
+ const t = setTimeout(() => { child.kill(); reject(new Error('the editor did not start within a minute')); }, EDITOR_START_MS);
343
+ child.stdout.on('data', (d) => {
344
+ out += d;
345
+ const line = out.split('\n').find((l) => l.startsWith('{'));
346
+ if (line) {
347
+ clearTimeout(t);
348
+ try {
349
+ resolve(JSON.parse(line).url);
350
+ }
351
+ catch (e) {
352
+ reject(e);
353
+ }
354
+ }
355
+ });
356
+ child.stderr.on('data', (d) => { if (err.length < 4000)
357
+ err += d; });
358
+ child.on('exit', (code) => { clearTimeout(t); editors.delete(p.dir); reject(new Error(`the editor stopped (exit ${code}): ${err.trim().split('\n').slice(-3).join(' ')}`)); });
359
+ });
360
+ url.catch(() => { });
361
+ editors.set(p.dir, { child, url });
362
+ return url;
363
+ };
364
+ const reveal = (dir) => {
365
+ const [cmd, args] = process.platform === 'win32' ? ['explorer.exe', [dir]] : process.platform === 'darwin' ? ['open', [dir]] : ['xdg-open', [dir]];
366
+ const c = spawn(cmd, args, { detached: true, stdio: 'ignore', windowsHide: false });
367
+ c.on('error', () => { });
368
+ c.unref();
369
+ };
370
+ // ---------------------------------------------------------------- URLs
371
+ const enc = encodeURIComponent;
372
+ const relPath = (rel) => rel.split('/').filter(Boolean).map(enc).join('/');
373
+ const urls = {
374
+ home: '/',
375
+ package: (lib, id) => `/p/${enc(lib)}/${enc(id)}`,
376
+ thumb: (lib, id, v) => `/p/${enc(lib)}/${enc(id)}/thumb.png${v ? `?v=${enc(String(v))}` : ''}`,
377
+ glb: (lib, id, v) => `/p/${enc(lib)}/${enc(id)}/preview.glb${v ? `?v=${enc(String(v))}` : ''}`,
378
+ embed: (lib, id) => `/embed/${enc(lib)}/${enc(id)}`,
379
+ file: (lib, id, rel) => `/p/${enc(lib)}/${enc(id)}/files/${relPath(rel)}`,
380
+ // TopoTopo's own packages are edited in TopoTopo's repository, not from here
381
+ edit: (lib, id) => (lib === BUILTIN_LIBRARY.name ? null : `/p/${enc(lib)}/${enc(id)}/edit`),
382
+ folder: (kind, name, rel) => `/${kind}/${enc(name)}/${rel ? `${relPath(rel)}/` : ''}`,
383
+ raw: (kind, name, rel) => `/${kind}/${enc(name)}/${relPath(rel)}`,
384
+ model: (kind, name, rel) => `/model/${kind}/${enc(name)}/${relPath(rel)}`,
385
+ asset: (name) => `/static/${name}`,
386
+ app: (name) => `/app/${name}`,
387
+ three: '/vendor/three/',
388
+ };
389
+ /** A package's folder page. */
390
+ const pageOf = (p) => { const r = rootOf(p); return urls.folder(r.kind, r.name, p.rel); };
391
+ // ---------------------------------------------------------------- page data
392
+ /** A package's thumbnail of one of its outputs (thumbs/<output>.png, which TopoTopo's built-in packages keep). */
393
+ const outputThumb = (p, output) => (fs.existsSync(path.join(p.dir, 'thumbs', `${output}.png`)) ? `/p/${enc(p.lib)}/${enc(p.id)}/thumbs/${enc(output)}.png` : undefined);
394
+ /** A package's preview as a picture, when it has one: its baked thumbnail, a built-in package's first output's. */
395
+ const previewOf = (p) => {
396
+ if (isBuiltin(p)) {
397
+ const v = publishedVersions(p.dir, p.manifest.name ?? '').at(-1)?.version;
398
+ return builtinAt.get(p.dir)?.thumb ? urls.thumb(p.lib, p.id, v) : undefined;
399
+ }
400
+ const s = readBakeState(p.dir);
401
+ return fs.existsSync(path.join(webDir(p.dir), 'thumb.png')) ? urls.thumb(p.lib, p.id, s?.at ?? 0) : undefined;
402
+ };
403
+ /** The newest version of a package the web app knows of: its home's, in a library or TopoTopo's built-in one. */
404
+ const newestOf = (name, homes = packageHomes()) => {
405
+ const home = homes.get(name);
406
+ return home ? publishedVersions(home.dir, name).at(-1)?.version : undefined;
407
+ };
408
+ /** The packages of the libraries and the workspaces that use a package, with the version each uses. */
409
+ const usersOf = (name) => [
410
+ ...[...packages.values()].filter((p) => p.manifest.uses[name])
411
+ .map((p) => ({ lib: p.lib, id: p.id, title: p.manifest.title, version: p.manifest.uses[name], url: pageOf(p) })),
412
+ ...games.filter((g) => g.m?.uses[name]).map((g) => ({ lib: 'workspace', id: g.name, title: `workspace ${g.name}`, version: g.m.uses[name], url: urls.folder('w', g.name, '') })),
413
+ ].sort((a, b) => (a.title < b.title ? -1 : a.title > b.title ? 1 : 0));
414
+ const status = (p, s) => (isBuiltin(p) ? 'ok' : !hasDefault(p) ? 'empty' : queue.pending(p.dir) ? 'baking' : !s ? 'new' : s.ok ? 'ok' : 'failed');
415
+ const cardOf = (p) => {
416
+ const s = readBakeState(p.dir);
417
+ const m = p.manifest;
418
+ // a package: its full name, its newest version and its outputs (its published versions' records)
419
+ const newest = m.name ? publishedVersions(p.dir, m.name).at(-1) : undefined;
420
+ const pkg = m.name ? { name: m.name, version: newest?.version ?? null } : undefined;
421
+ const outputs = m.name && newest ? outputsOf(m.name, newest).map((x) => ({ type: x.type, ...(x.alias ? { alias: x.alias } : {}), label: x.label, ...(x.kind ? { kind: x.kind } : {}), tags: x.tags })) : undefined;
422
+ // the packages it uses, and those of them with a newer version: the card says so
423
+ const uses = Object.keys(m.uses);
424
+ const updates = uses.flatMap((name) => { const n = newestOf(name); return n && compareVersions(n, m.uses[name]) > 0 ? [{ name, version: m.uses[name], newest: n }] : []; });
425
+ // a built-in package's thumbnail changes with its versions, a package's with its bakes
426
+ const version = isBuiltin(p) ? newest?.version ?? '0' : String(s?.at ?? 0);
427
+ return {
428
+ lib: p.lib, id: p.id, title: m.title, collection: p.collection, tags: m.tags, description: m.description, updated: p.updated, status: status(p, s), version, url: pageOf(p),
429
+ ...(pkg ? { pkg } : {}), ...(outputs ? { outputs } : {}), ...(uses.length ? { usesPackages: uses } : {}), ...(updates.length ? { updates } : {}),
430
+ };
431
+ };
432
+ /** The packages that publish versions, by full name: the first library's when two hold one, TopoTopo's own among them. */
433
+ const packageHomes = () => {
434
+ const homes = new Map();
435
+ for (const p of packages.values())
436
+ if (p.manifest.name && !homes.has(p.manifest.name))
437
+ homes.set(p.manifest.name, p);
438
+ return homes;
439
+ };
440
+ /**
441
+ * A version's published outputs, each by the node type a graph names it with ("owner/name" alone is the default),
442
+ * with the thumbnail the package `p` keeps of it, if any.
443
+ */
444
+ const outputsOf = (name, v, p) => {
445
+ const isDefault = (x) => isDefaultOutput(v, x);
446
+ const row = (type, x, dflt, output) => {
447
+ const thumb = p && output ? outputThumb(p, output) : undefined;
448
+ return {
449
+ type, ...(dflt ? { alias: name } : {}), label: x.label ?? '', ...(x.kind ? { kind: x.kind } : {}), tags: x.tags ?? [],
450
+ graph: x.graph, node: x.node, params: Object.keys(x.sliders), inputs: x.inputs.map((i) => i.label || `input ${i.index}`), ...(thumb ? { thumb } : {}),
451
+ };
452
+ };
453
+ const rows = Object.entries(v.outputs).map(([k, x]) => row(`${name}/${k}`, x, isDefault(x), k));
454
+ // a default output that is no named output is listed by the package's name alone
455
+ if (!Object.values(v.outputs).some(isDefault))
456
+ rows.unshift(row(name, v.default, false));
457
+ return rows;
458
+ };
459
+ /** The exports of a package older than the graph they were made from, by path below exports/. */
460
+ const staleExports = (p) => {
461
+ const graphs = graphsOf(p), out = new Set();
462
+ for (const e of exportSources(p.dir)) {
463
+ const f = graphs.get(e.made.graph);
464
+ if (f && exportStale(f, e.made))
465
+ out.add(e.rel);
466
+ }
467
+ return out;
468
+ };
469
+ const packageData = (p) => {
470
+ const builtin = isBuiltin(p), s = builtin ? null : readBakeState(p.dir);
471
+ const graphs = [...graphsOf(p)].map(([name, file]) => {
472
+ let g = {};
473
+ try {
474
+ g = JSON.parse(fs.readFileSync(file, 'utf8')) ?? {};
475
+ }
476
+ catch { /* unreadable: listed without nodes */ }
477
+ const meta = g.params ?? {};
478
+ return {
479
+ name, nodes: Object.keys(g.nodes ?? {}).length,
480
+ vars: Object.entries(g.vars ?? {}).map(([k, v]) => ({ name: k, value: v, desc: meta[k]?.desc ?? meta[k]?.label, min: meta[k]?.min, max: meta[k]?.max })),
481
+ };
482
+ });
483
+ const abs = (u) => base + u;
484
+ const m = p.manifest, homes = packageHomes(), r = rootOf(p);
485
+ const versions = m.name ? publishedVersions(p.dir, m.name) : [];
486
+ // the packages it uses: the version in use (its copy's record), its home's page and the newest version there
487
+ const uses = Object.entries(m.uses).map(([name, v]) => {
488
+ const rec = copyRecord(p.dir, name, v), home = homes.get(name), newest = newestOf(name, homes);
489
+ return { name, version: v, ...(rec ? { note: rec.note, published: rec.published } : {}), ...(home ? { url: pageOf(home) } : {}), ...(newest && compareVersions(newest, v) > 0 ? { newest } : {}) };
490
+ });
491
+ const at = (sub, f) => urls.raw(r.kind, r.name, `${p.rel}/${sub}/${f}`);
492
+ const model = (sub, f) => (/\.(glb|gltf)$/i.test(f) ? { model: urls.model(r.kind, r.name, `${p.rel}/${sub}/${f}`) } : {});
493
+ const stale = builtin ? new Set() : staleExports(p);
494
+ return {
495
+ ...cardOf(p), builtin, rel: p.rel, place: games.some((g) => g.scan.packages.includes(p)) ? `in the workspace "${p.lib}"` : builtin ? 'in TopoTopo\'s built-in library' : `in library "${p.lib}"`, links: m.links, graph: m.bake.graph ?? m.graph, graphs, created: m.created,
496
+ attachments: builtin ? [] : listFiles(path.join(p.dir, 'attachments')).map((f) => ({ ...f, url: at('attachments', f.path), ...model('attachments', f.path) })),
497
+ exports: builtin ? [] : listFiles(path.join(p.dir, 'exports')).filter((f) => !/\.json$/i.test(f.path) || !/(^|\/)(source|landscape)\.json$|\.(source|meshes)\.json$/i.test(f.path)).map((f) => ({ ...f, url: at('exports', f.path), ...model('exports', f.path), ...(stale.has(f.path) ? { stale: true } : {}) })),
498
+ glb: !builtin && fs.existsSync(path.join(webDir(p.dir), 'preview.glb')), thumb: !!previewOf(p), bake: s,
499
+ share: { link: abs(urls.package(p.lib, p.id)), thumb: abs(urls.thumb(p.lib, p.id)), embed: abs(urls.embed(p.lib, p.id)) },
500
+ package: m.name ? {
501
+ name: m.name,
502
+ versions: [...versions].reverse().map((v) => ({ version: v.version, note: v.note, published: v.published, big: startsBigVersion(v.version), marked: v.big, outputs: outputsOf(m.name, v) })),
503
+ outputs: versions.length ? outputsOf(m.name, versions.at(-1), p) : [],
504
+ usedBy: usersOf(m.name),
505
+ } : null,
506
+ uses,
507
+ };
508
+ };
509
+ const listJSON = () => [...packages.values()].map((p) => {
510
+ const c = cardOf(p);
511
+ return {
512
+ lib: p.lib, id: p.id, title: c.title, description: c.description, tags: c.tags, collection: c.collection, updated: p.updated, status: c.status,
513
+ url: base + urls.package(p.lib, p.id), thumb: base + urls.thumb(p.lib, p.id, c.version), embed: base + urls.embed(p.lib, p.id),
514
+ ...(c.pkg ? { package: c.pkg } : {}),
515
+ };
516
+ });
517
+ // ---------------------------------------------------------------- flags
518
+ /** The packages of a workspace or library: those its scan found (TopoTopo's built-in ones are not audited). */
519
+ const packagesOf = (r) => (r.builtin ? [] : scans.find((s) => s.root === r.dir && s.name === r.name)?.packages ?? []);
520
+ /**
521
+ * What is wrong with a package that TopoTopo can tell from its files: its preview did not cook; it publishes versions
522
+ * and has none, or changes no version holds; an export older than its graph; published outputs that no other package
523
+ * of the workspace uses (`used`: node type → the folders of the packages whose graphs use it; null outside a workspace).
524
+ */
525
+ const packageFlags = (p, used) => {
526
+ const out = [], at = p.rel, m = p.manifest;
527
+ const s = readBakeState(p.dir);
528
+ if (s && !s.ok && hasDefault(p) && !queue.pending(p.dir))
529
+ out.push({ kind: 'bake', at, what: `The preview of ${m.title} did not cook: ${firstLine(s.error) || 'no reason given'}`, todo: 'Open it in the editor to see why; it bakes again when the graph is saved, or press Re-bake' });
530
+ if (m.name) {
531
+ const versions = publishedVersions(p.dir, m.name), last = versions.at(-1);
532
+ if (!last)
533
+ out.push({ kind: 'publish', at, what: `${m.name} publishes versions and has none yet`, todo: 'Publish the first: topotopo publish --note "…" in its folder, or ask your agent' });
534
+ else {
535
+ let changed = false;
536
+ try {
537
+ changed = workingHash(p.dir) !== last.hash;
538
+ }
539
+ catch { /* unreadable files: topotopo check says why */ }
540
+ if (changed)
541
+ out.push({ kind: 'publish', at, what: `${m.name} has changes that no version holds (the newest is ${last.version})`, todo: 'Publish them as a new version: topotopo publish --note "…" in its folder, or ask your agent' });
542
+ if (used) {
543
+ const rows = outputsOf(m.name, last);
544
+ const usedHere = (t) => [...(used.get(t) ?? [])].some((d) => d !== folderKey(p.dir));
545
+ const unused = rows.filter((x) => !usedHere(x.type) && !(x.alias && usedHere(x.alias))).map((x) => x.type.slice(m.name.length + 1) || x.type);
546
+ if (unused.length) {
547
+ const all = unused.length === rows.length;
548
+ out.push({
549
+ kind: 'unused', at,
550
+ what: `No package in this workspace uses ${all ? (rows.length === 1 ? 'the output' : `any of the ${rows.length} outputs`) : `${unused.length} of the ${rows.length} outputs`} ${m.name} ${last.version} publishes: ${unused.slice(0, 12).join(', ')}${unused.length > 12 ? ` and ${unused.length - 12} more` : ''}`,
551
+ todo: 'If the game does not use their exports either, drop them from the graph\'s outputs before the next version',
552
+ });
553
+ }
554
+ }
555
+ }
556
+ }
557
+ for (const e of staleExports(p))
558
+ out.push({ kind: 'export', at, what: `exports/${e} was made from an older version of its graph`, todo: 'Export it again: the Export button in the editor, or ask your agent' });
559
+ return out;
560
+ };
561
+ /**
562
+ * A tree's audit: its walk (counts, images, broken links in notes) and its packages' flags, kept until it changes;
563
+ * one at a time per tree (pages that ask meanwhile wait for the same one).
564
+ */
565
+ const auditOf = (r) => {
566
+ const key = rootKey(r), have = audits.get(key);
567
+ if (have && (!r.builtin || Date.now() - have.at < BUILTIN_AUDIT_MS))
568
+ return Promise.resolve(have);
569
+ // one under way since the last change serves; one begun before it does not (its walk may have missed the change)
570
+ const gen = changes.get(key) ?? 0, going = auditing.get(key);
571
+ if (going && going.gen === gen)
572
+ return going.made;
573
+ const made = auditNow(r).then((a) => { if ((changes.get(key) ?? 0) === gen)
574
+ audits.set(key, a); return a; })
575
+ .finally(() => { if (auditing.get(key)?.made === made)
576
+ auditing.delete(key); });
577
+ auditing.set(key, { gen, made });
578
+ return made;
579
+ };
580
+ const auditNow = async (r) => {
581
+ if (noteLinks.size > 100_000)
582
+ noteLinks.clear();
583
+ const walk = await walkTree(r, { links: noteLinks, slice: 8, limits: o.walkLimits });
584
+ const flags = [];
585
+ const g = r.kind === 'w' ? games.find((x) => x.name === r.name) : undefined;
586
+ if (g?.problem)
587
+ flags.push({ kind: 'workspace', at: '', what: `topotopo-workspace.json cannot be read: ${g.problem.replace(/^.*?topotopo-workspace\.json: /, '')}`, todo: 'Fix the file as this says: until then TopoTopo cannot use the workspace (its folders still show here)' });
588
+ for (const prob of scans.find((s) => s.root === r.dir && s.name === r.name)?.problems ?? [])
589
+ if (!g?.problem || !prob.includes(g.problem))
590
+ flags.push({ kind: 'workspace', at: '', what: prob, todo: 'Fix it in the folder it names: until then that package is not found' });
591
+ const pk = packagesOf(r);
592
+ let used = null;
593
+ if (r.kind === 'w') {
594
+ used = new Map();
595
+ for (const q of pk)
596
+ for (const f of graphsOf(q).values())
597
+ for (const t of graphTypes(f)) {
598
+ if (!used.has(t))
599
+ used.set(t, new Set());
600
+ used.get(t).add(folderKey(q.dir));
601
+ }
602
+ }
603
+ for (const p of pk) {
604
+ flags.push(...packageFlags(p, used));
605
+ await new Promise((res) => setImmediate(res));
606
+ }
607
+ walk.flags.forEach((f) => flags.push(f));
608
+ // an engine project below the root is browsable, never audited
609
+ const inEngine = (at) => walk.engines.some((e) => at === e || at.startsWith(e + '/'));
610
+ return { walk, flags: flags.filter((f) => !inEngine(f.at)), at: Date.now() };
611
+ };
612
+ const under = (rel, at) => !rel || at === rel || at.startsWith(rel + '/');
613
+ /** A tree's flags as they are now: a preview that did not cook is no flag while it bakes again. */
614
+ const flagsNow = (r, a) => a.flags.filter((x) => x.kind !== 'bake' || !queue.pending(byDir.get(folderKey(path.join(r.dir, ...x.at.split('/'))))?.dir ?? ''));
615
+ // ---------------------------------------------------------------- folder pages
616
+ const rootLabel = (r) => (r.builtin ? 'TopoTopo\'s built-in library' : r.kind === 'w' ? 'Workspace' : 'Library');
617
+ const engineLabel = (r) => (r.engine ? `${r.engine.type === 'godot' ? 'Godot' : 'Unreal'} · ${engineTitle(r.engine.file)}` : undefined);
618
+ /**
619
+ * A folder's picture: its package's preview, else its first image, else a picture from a package or a shown folder
620
+ * in it (never from plumbing, which is not served).
621
+ */
622
+ const pictureOf = (r, rel, abs, first) => {
623
+ const p = byDir.get(folderKey(abs));
624
+ const own = p ? previewOf(p) : undefined;
625
+ if (own)
626
+ return own;
627
+ if (first)
628
+ return urls.raw(r.kind, r.name, first);
629
+ for (const q of packagesOf(r))
630
+ if (q.rel.startsWith(rel + '/')) {
631
+ const t = previewOf(q);
632
+ if (t)
633
+ return t;
634
+ }
635
+ // an image one folder down
636
+ let entries = [];
637
+ try {
638
+ entries = fs.readdirSync(abs, { withFileTypes: true });
639
+ }
640
+ catch { /* none */ }
641
+ const files = entries.filter((e) => e.isFile()).map((e) => e.name);
642
+ const subs = entries.filter((e) => e.isDirectory() && !plumbing(e.name, files)).sort((a, b) => byName(a.name, b.name)).slice(0, 12);
643
+ for (const s of subs) {
644
+ let names = [];
645
+ try {
646
+ names = fs.readdirSync(path.join(abs, s.name)).sort(byName);
647
+ }
648
+ catch {
649
+ continue;
650
+ }
651
+ const img = names.find((n) => /\.(png|jpe?g|webp|gif|avif)$/i.test(n) && !n.startsWith('.'));
652
+ if (img)
653
+ return urls.raw(r.kind, r.name, rel ? `${rel}/${s.name}/${img}` : `${s.name}/${img}`);
654
+ }
655
+ return undefined;
656
+ };
657
+ /** Where a note's box is: on this page (`here`: the folder shown and the notes boxed on it), else on its folder's page, which then shows it. */
658
+ const noteUrlOf = (r, here) => (rel, anchor) => {
659
+ const at = rel.includes('/') ? rel.slice(0, rel.lastIndexOf('/')) : '', name = rel.slice(rel.lastIndexOf('/') + 1);
660
+ if (here && here.rel === at && here.boxed.has(name))
661
+ return `#${anchor}`;
662
+ return `${urls.folder(r.kind, r.name, at)}?note=${enc(name)}#${anchor}`;
663
+ };
664
+ const noteEnv = (r, here = null) => ({
665
+ root: r,
666
+ folderUrl: (rel) => urls.folder(r.kind, r.name, rel),
667
+ fileUrl: (rel) => urls.raw(r.kind, r.name, rel),
668
+ modelUrl: (rel) => urls.model(r.kind, r.name, rel),
669
+ noteUrl: noteUrlOf(r, here),
670
+ card: (rel, abs) => {
671
+ const p = byDir.get(folderKey(abs));
672
+ if (p)
673
+ return { title: p.manifest.title, sub: p.manifest.name ? `package ${p.manifest.name}` : 'package', thumb: pictureOf(r, rel, abs) };
674
+ const l = listFolder(abs, rel, r.dir);
675
+ const image = l.files.find((f) => f.kind === 'image')?.rel;
676
+ let project;
677
+ try {
678
+ project = fs.readdirSync(abs).find((f) => engineTypeOf(f));
679
+ }
680
+ catch { /* unreadable */ }
681
+ // an engine project: its own picture only (what lies below it is the engine's)
682
+ if (project)
683
+ return { title: engineTitle(path.join(abs, project)), sub: `${engineTypeOf(project) === 'godot' ? 'Godot' : 'Unreal'} project`, ...(image ? { thumb: urls.raw(r.kind, r.name, image) } : {}) };
684
+ return { title: rel ? rel.split('/').pop() : r.name, sub: [count(l.folders.length, 'folder'), count(l.files.length + l.notes.length, 'file')].join(' · '), thumb: pictureOf(r, rel, abs, image) };
685
+ },
686
+ });
687
+ /** A folder's notes in the order of their boxes: a README (or index) first, then documents (.md), then text files, each by name. */
688
+ const noteOrder = (a, b) => {
689
+ const rank = (n) => (README.test(n) ? 0 : /\.md$/i.test(n) ? 1 : 2);
690
+ return rank(a.name) - rank(b.name) || byName(a.name, b.name);
691
+ };
692
+ const folderData = async (r, rel, abs, askedNote = null) => {
693
+ const listing = listFolder(abs, rel, r.dir);
694
+ const audit = await auditOf(r);
695
+ const engines = audit.walk.engines;
696
+ const engineAt = engines.find((e) => rel === e || rel.startsWith(e + '/'));
697
+ const p = listing.topo.length ? byDir.get(folderKey(abs)) ?? null : null;
698
+ const name = rel ? rel.split('/').pop() : r.name;
699
+ const crumbs = [{ name: r.name, url: urls.folder(r.kind, r.name, '') }, ...rel.split('/').filter(Boolean).map((s, i, a) => ({ name: s, url: urls.folder(r.kind, r.name, a.slice(0, i + 1).join('/')) }))];
700
+ // a .topo here that is none of the tree's packages: why the scan leaves it out
701
+ let notice;
702
+ if (engineAt !== undefined) {
703
+ const e = engineTypeOf(fs.readdirSync(path.join(r.dir, ...engineAt.split('/'))).find((f) => engineTypeOf(f)) ?? '');
704
+ notice = `${engineAt === rel ? 'This is' : 'This is inside'} the ${e === 'unreal' ? 'Unreal' : 'Godot'} project: shown as it is, not audited for flags.`;
705
+ }
706
+ else if (listing.topo.length && !p) {
707
+ const why = listing.topo.length > 1 ? `it holds ${listing.topo.join(' and ')}, and a package has one .topo file` : unscanned(r.dir, abs, { engine: r.engine?.file ?? null }) ?? 'its manifest cannot be read, or its id is taken by another folder';
708
+ notice = `This folder holds ${listing.topo.join(', ')} but is none of the packages of ${r.kind === 'w' ? 'the workspace' : 'the library'}: ${why}.`;
709
+ }
710
+ const flagsHere = engineAt !== undefined ? [] : flagsNow(r, audit);
711
+ // a folder of hundreds of text files shows the first as boxes and lists the rest with the other files: its README
712
+ // and documents before its text files, and always the notes with flags here and the note a link asked for
713
+ const ranked = [...listing.notes].sort(noteOrder);
714
+ const flagged = new Set(flagsHere.filter((x) => x.at === rel && x.note).map((x) => x.note));
715
+ const boxed = new Set(ranked.slice(0, MAX_NOTE_BOXES).map((n) => n.name));
716
+ for (const n of ranked)
717
+ if (flagged.has(n.name) || n.name === askedNote)
718
+ boxed.add(n.name);
719
+ const env = noteEnv(r, { rel, boxed });
720
+ const notes = ranked.filter((n) => boxed.has(n.name)).map((n) => {
721
+ const h = noteHtml(env, abs, path.join(abs, n.name), headingPrefix(n.name));
722
+ return { name: n.name, id: noteId(n.name), url: urls.raw(r.kind, r.name, n.rel), html: h.html, long: h.long, ...(n.name === askedNote ? { asked: true } : {}) };
723
+ });
724
+ const unboxed = ranked.filter((n) => !boxed.has(n.name));
725
+ const folders = listing.folders.map((f) => {
726
+ const fabs = path.join(abs, f.name);
727
+ const url = urls.folder(r.kind, r.name, f.rel);
728
+ if (f.engine)
729
+ return { name: f.name, url, kind: 'engine', title: f.engine.title, sub: `${f.engine.type === 'godot' ? 'Godot' : 'Unreal'} project`, ...(f.image ? { thumb: urls.raw(r.kind, r.name, f.image) } : {}), flags: 0, packages: 0 };
730
+ if (f.workspace) {
731
+ let wsName = f.name;
732
+ try {
733
+ wsName = JSON.parse(fs.readFileSync(path.join(fabs, 'topotopo-workspace.json'), 'utf8'))?.name ?? f.name;
734
+ }
735
+ catch { /* its folder's name */ }
736
+ const reg = games.find((g) => folderKey(g.dir) === folderKey(fabs));
737
+ return { name: f.name, url: reg ? urls.folder('w', reg.name, '') : url, kind: 'workspace', title: String(wsName), sub: reg ? 'another workspace' : 'another workspace, not registered', flags: 0, packages: 0 };
738
+ }
739
+ const q = byDir.get(folderKey(fabs));
740
+ const flags = flagsHere.filter((x) => under(f.rel, x.at)).length;
741
+ const what = [count(f.folders, 'folder'), count(f.files, 'file'), ...(f.unreal ? [count(f.unreal, 'Unreal asset')] : [])].join(' · ');
742
+ if (q) {
743
+ const c = cardOf(q);
744
+ return { name: f.name, url, kind: 'package', title: q.manifest.title, sub: what, thumb: pictureOf(r, f.rel, fabs, f.image), flags, packages: 1, ...(c.pkg ? { pkg: c.pkg } : {}), status: c.status };
745
+ }
746
+ const inside = packagesOf(r).filter((x) => x.rel.startsWith(f.rel + '/')).length;
747
+ const empty = !f.folders && !f.files && !f.unreal;
748
+ return { name: f.name, url, kind: 'folder', title: f.name, sub: empty ? 'empty' : what, thumb: pictureOf(r, f.rel, fabs, f.image), flags, packages: inside, ...(empty ? { empty } : {}) };
749
+ });
750
+ // exports TopoTopo made: the package above them says whether their graph changed since
751
+ let above = null;
752
+ for (let d = abs; within(d, r.dir); d = path.dirname(d)) {
753
+ const q = byDir.get(folderKey(d));
754
+ if (q) {
755
+ above = q;
756
+ break;
757
+ }
758
+ if (folderKey(d) === folderKey(r.dir))
759
+ break;
760
+ }
761
+ const graphs = above ? graphsOf(above) : null;
762
+ const files = [...listing.files, ...unboxed.map((n) => ({ ...n, kind: 'other' }))].map((f) => {
763
+ const made = f.made ? { graph: f.made.graph, output: f.made.output, stale: graphs?.get(f.made.graph) ? exportStale(graphs.get(f.made.graph), f.made) : null } : undefined;
764
+ return { name: f.name, url: urls.raw(r.kind, r.name, f.rel), size: f.size, mtime: f.mtime, kind: f.kind, ...(f.kind === 'model' ? { model: urls.model(r.kind, r.name, f.rel) } : {}), ...(made ? { made } : {}) };
765
+ });
766
+ const own = flagsHere.filter((x) => x.at === rel);
767
+ const below = new Map();
768
+ for (const x of flagsHere)
769
+ if (x.at !== rel && under(rel, x.at)) {
770
+ if (!below.has(x.at))
771
+ below.set(x.at, []);
772
+ below.get(x.at).push(x);
773
+ }
774
+ const kicker = !rel ? [rootLabel(r), ...(r.kind === 'w' && engineLabel(r) ? [engineLabel(r)] : [])].join(' · ')
775
+ : p ? `Package${p.manifest.name ? ` · ${p.manifest.name}` : ''}` : engineAt === rel ? `${notice?.includes('Unreal') ? 'Unreal' : 'Godot'} project` : 'Folder';
776
+ const stats = [count(listing.folders.length, 'folder'), count(listing.files.length + listing.notes.length, 'file'), ...(listing.notes.length ? [count(listing.notes.length, 'note')] : []), ...(!rel && r.kind === 'w' ? [count(packagesOf(r).length, 'package')] : [])].join(' · ');
777
+ return {
778
+ root: { kind: r.kind, name: r.name, label: rootLabel(r) }, rel, crumbs, kicker, title: p ? p.manifest.title : name, stats, dir: abs,
779
+ flags: own, below: [...below].sort(([a], [b]) => byName(a, b)).map(([at, fl]) => ({ at, url: urls.folder(r.kind, r.name, at), flags: fl })),
780
+ ...(!rel ? { uses: workspaceUses(r) } : {}), ...(!rel && audit.walk.cut.length ? { cut: audit.walk.cut } : {}),
781
+ ...(notice ? { notice } : {}), notes, moreNotes: unboxed.length, folders, files, engineAssets: listing.engineAssets, package: p ? packageData(p) : null,
782
+ live: { root: rootKey(r), rel, ...(p ? { package: keyOf(p) } : {}), reveal: `${urls.folder(r.kind, r.name, rel)}?reveal` },
783
+ };
784
+ };
785
+ // ---------------------------------------------------------------- front page data
786
+ const rootCard = async (r) => {
787
+ const a = await auditOf(r), pk = r.builtin ? (scans.find((s) => s.name === BUILTIN_LIBRARY.name)?.packages ?? []) : packagesOf(r);
788
+ const thumbs = [];
789
+ for (const p of pk) {
790
+ if (thumbs.length >= 4)
791
+ break;
792
+ const t = previewOf(p);
793
+ if (t)
794
+ thumbs.push(t);
795
+ }
796
+ for (const i of a.walk.images) {
797
+ if (thumbs.length >= 4)
798
+ break;
799
+ thumbs.push(urls.raw(r.kind, r.name, i));
800
+ }
801
+ const g = r.kind === 'w' ? games.find((x) => x.name === r.name) : undefined;
802
+ const problem = g?.problem ? 'Its workspace file cannot be read: see its page' : !fs.existsSync(r.dir) ? 'Its folder is not there' : undefined;
803
+ return {
804
+ kind: r.kind, name: r.name, dir: r.dir, url: urls.folder(r.kind, r.name, ''), ...(engineLabel(r) ? { engine: engineLabel(r) } : {}), ...(r.builtin ? { builtin: true } : {}),
805
+ thumbs, packages: pk.length, folders: a.walk.folders, files: a.walk.files, flags: flagsNow(r, a).length, ...(problem ? { problem } : {}), ...(a.walk.cut.length ? { cut: true } : {}),
806
+ };
807
+ };
808
+ let placeholder = null;
809
+ const placeholderPNG = () => {
810
+ if (!placeholder) {
811
+ const n = 64, rgba = new Uint8Array(n * n * 4);
812
+ for (let i = 0; i < n * n; i++)
813
+ rgba.set([0x2b, 0x2d, 0x31, 0xff], i * 4);
814
+ placeholder = encodePNG(rgba, n, n, (d) => zlib.deflateSync(d));
815
+ }
816
+ return placeholder;
817
+ };
818
+ /** `files/<rest>` of a package: below attachments/ or exports/, never outside them (links included). */
819
+ const packageFile = (p, rest) => {
820
+ const parts = rest.split('/').map((x) => decodeURIComponent(x));
821
+ // decoded segments: "%2F" and "%5C" must not smuggle separators (and so "..") past the split
822
+ if (!['attachments', 'exports'].includes(parts[0]) || parts.length < 2 || parts.some((x) => !x || x.startsWith('.') || /[\\/\0]/.test(x)))
823
+ throw new HttpError(400, 'files/ serves attachments/<path> and exports/<path> (no dot names)');
824
+ const root = path.join(p.dir, parts[0]);
825
+ const abs = path.join(root, ...parts.slice(1));
826
+ if (!abs.startsWith(root + path.sep))
827
+ throw new HttpError(400, 'the path leaves the package');
828
+ if (!fs.statSync(abs, { throwIfNoEntry: false })?.isFile())
829
+ throw new HttpError(404, `no file ${parts.join('/')}`);
830
+ // where it really is (links and short names resolved): inside, and through no dot folder by another name
831
+ const real = realBelow(root, abs, true);
832
+ if ('why' in real)
833
+ throw new HttpError(400, `not served: ${real.why}`);
834
+ return abs;
835
+ };
836
+ const readStatic = (dir, rel) => {
837
+ const p = path.resolve(dir, decodeURIComponent(rel));
838
+ if (!p.startsWith(dir + path.sep) || !fs.statSync(p, { throwIfNoEntry: false })?.isFile())
839
+ return null;
840
+ return p;
841
+ };
842
+ /** A page that says there is nothing at an address, with the way back. */
843
+ const missingPage = (msg, back) => shell('Not found · TopoTopo', urls, `<header class="bar"><a class="brand" href="/"><b>TopoTopo</b></a></header>
844
+ <main class="wrap folder"><div class="head"><p class="kicker">Not found</p><h1>Nothing here</h1><p class="hstats">${esc(msg)}</p></div><p><a class="btn" href="${esc(back)}">Back</a></p></main>`, { page: 'missing' });
845
+ // ---------------------------------------------------------------- routes
846
+ const server = http.createServer(async (req, res) => {
847
+ const head = (code, type, extra = {}) => res.writeHead(code, { 'content-type': type, 'cache-control': 'no-store', 'x-content-type-options': 'nosniff', ...extra });
848
+ const send = (code, body, type = 'text/plain; charset=utf-8', extra = {}) => { head(code, type, extra); res.end(req.method === 'HEAD' ? undefined : body); };
849
+ // pages may only be framed by the web app itself; the embed page is made to be framed by a board; the 3D views
850
+ // load three.js through an inline import map (allowed by its hash) and nothing from other sites
851
+ const map = importMap(urls);
852
+ const html = (body, framable = false, code = 200) => send(code, body, MIME['.html'], { 'content-security-policy': framable === true ? viewCsp(map, true) : framable === 'view' ? viewCsp(map, false) : PAGE_CSP });
853
+ const json = (code, body, extra = {}) => send(code, JSON.stringify(body), MIME['.json'], extra);
854
+ const redirect = (code, location) => { res.writeHead(code, { location, 'cache-control': 'no-store' }); res.end(); };
855
+ try {
856
+ const host = String(req.headers.host ?? '');
857
+ if (!/^(127\.0\.0\.1|localhost|\[::1\])(:\d+)?$/i.test(host))
858
+ return json(403, { error: `unexpected Host "${host}"` });
859
+ const origin = req.headers.origin;
860
+ const write = req.method !== 'GET' && req.method !== 'HEAD';
861
+ if (write && origin !== undefined && origin !== `http://${host}`)
862
+ return json(403, { error: `cross-origin ${req.method} refused (${origin})` });
863
+ const u = new URL(req.url ?? '/', 'http://localhost');
864
+ const seg = u.pathname.split('/').slice(1);
865
+ if (u.pathname === '/' || u.pathname === '/index.html') {
866
+ // TopoTopo's built-in library as it is now: a built-in package published while the web app runs shows
867
+ refreshBuiltin();
868
+ const all = [...packages.values()].filter((p) => packages.get(keyOf(p)) === p).map(cardOf).sort((a, b) => byName(a.title, b.title));
869
+ return html(frontPage({
870
+ workspaces: await Promise.all(roots.filter((r) => r.kind === 'w').map(rootCard)),
871
+ libraries: await Promise.all(roots.filter((r) => r.kind === 'l').map(rootCard)),
872
+ packages: all,
873
+ problems: libraryScans().filter((s) => s.name !== BUILTIN_LIBRARY.name && !fs.existsSync(s.root)).map((s) => `library "${s.name}": no folder ${s.root}`),
874
+ }, urls));
875
+ }
876
+ if (seg[0] === 'static') {
877
+ const p = readStatic(assetDir, seg.slice(1).join('/'));
878
+ return p ? send(200, fs.readFileSync(p), MIME[path.extname(p)] ?? 'application/octet-stream') : send(404, 'not found');
879
+ }
880
+ if (seg[0] === 'app') {
881
+ const p = readStatic(appDir, seg.slice(1).join('/'));
882
+ return p ? send(200, fs.readFileSync(p), MIME[path.extname(p)] ?? 'application/octet-stream') : send(404, 'not found');
883
+ }
884
+ if (seg[0] === 'vendor' && seg[1] === 'three') {
885
+ const p = readStatic(threeDir, seg.slice(2).join('/'));
886
+ return p ? send(200, fs.readFileSync(p), MIME[path.extname(p)] ?? 'application/octet-stream', { 'cache-control': 'max-age=3600' }) : send(404, 'not found');
887
+ }
888
+ if (u.pathname === '/api/health')
889
+ return json(200, { web: true, libraries: scans.length, packages: packages.size, baking: queue.size });
890
+ if (u.pathname === '/api/events') {
891
+ res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-store', connection: 'keep-alive' });
892
+ res.write(': hello\n\n');
893
+ clients.add(res);
894
+ req.on('close', () => clients.delete(res));
895
+ return;
896
+ }
897
+ if (u.pathname === '/api/packages') {
898
+ // a board on another origin may read the list when the config allows it (web.cors)
899
+ const cors = origin && cfg.web.cors.includes(origin) ? { 'access-control-allow-origin': origin, vary: 'Origin' } : { vary: 'Origin' };
900
+ if (req.method === 'OPTIONS')
901
+ return send(204, '', 'text/plain', { ...cors, 'access-control-allow-methods': 'GET' });
902
+ return json(200, { libraries: scans.map((s) => ({ name: s.name, packages: s.packages.length, problems: s.problems })), packages: listJSON() }, cors);
903
+ }
904
+ // a workspace's or library's folder pages and files: /w/<name>/<path…>/ and /l/<name>/<path…>; a model's 3D view
905
+ const model = seg[0] === 'model';
906
+ const at = model ? seg.slice(1) : seg;
907
+ if ((at[0] === 'w' || at[0] === 'l') && at.length >= 2) {
908
+ const kind = at[0], name = decodeURIComponent(at[1]);
909
+ const r = roots.find((x) => x.kind === kind && x.name === name);
910
+ if (!r) {
911
+ // a registered library inside a registered workspace is the workspace's: its folders are there (and a
912
+ // workspace's name under /l/ is the workspace)
913
+ const placed = kind === 'l' ? placeNamed(cfg, name) : null;
914
+ if (placed?.place.workspace)
915
+ return redirect(302, `${urls.folder('w', placed.place.name, placed.prefix)}${at.slice(2).map((x) => x).join('/')}${u.search}`);
916
+ return html(missingPage(`No ${kind === 'w' ? 'workspace' : 'library'} "${name}" is registered.`, '/'), false, 404);
917
+ }
918
+ const segs = at.slice(2);
919
+ const slash = u.pathname.endsWith('/');
920
+ const parts = slash ? segs.slice(0, -1) : segs;
921
+ if (parts.some((x) => x === ''))
922
+ throw new PathError(400, 'an empty folder name in the path');
923
+ let found;
924
+ try {
925
+ found = resolveIn(r.dir, parts);
926
+ }
927
+ catch (e) {
928
+ if (e instanceof PathError && e.status === 404)
929
+ return html(missingPage(e.message, urls.folder(r.kind, r.name, '')), false, 404);
930
+ throw e;
931
+ }
932
+ const st = fs.statSync(found.abs, { throwIfNoEntry: false });
933
+ const up = urls.folder(r.kind, r.name, found.rel.split('/').slice(0, -1).join('/'));
934
+ if (!st)
935
+ return html(missingPage(`There is no ${found.rel || r.name} in ${r.kind === 'w' ? 'the workspace' : 'the library'} "${r.name}".`, up), false, 404);
936
+ if (model) {
937
+ if (!st.isFile() || !/\.(glb|gltf)$/i.test(found.abs))
938
+ throw new HttpError(404, 'a 3D view is of a .glb or .gltf file');
939
+ return html(modelPage({ title: path.basename(found.abs), src: urls.raw(r.kind, r.name, found.rel), link: urls.raw(r.kind, r.name, found.rel) }, urls), 'view');
940
+ }
941
+ if (st.isDirectory()) {
942
+ if (req.method === 'POST' && u.searchParams.has('reveal')) {
943
+ reveal(found.abs);
944
+ return json(200, { ok: true });
945
+ }
946
+ // a folder's address ends with a slash, in the letter case on disk
947
+ if (!slash || found.rel !== found.parts.join('/'))
948
+ return redirect(301, `${urls.folder(r.kind, r.name, found.rel)}${u.search}`);
949
+ if (r.builtin)
950
+ refreshBuiltin();
951
+ const asked = u.searchParams.get('note');
952
+ return html(folderPage(await folderData(r, found.rel, found.abs, asked && kindOf(asked) === 'note' && !/[\\/]/.test(asked) ? asked : null), urls));
953
+ }
954
+ if (slash)
955
+ return redirect(301, urls.raw(r.kind, r.name, found.rel));
956
+ if (write)
957
+ throw new HttpError(405, 'files are read only here');
958
+ return sendFile(req, res, found.abs, { download: u.searchParams.has('download') });
959
+ }
960
+ if (seg[0] === 'embed' && seg.length === 3) {
961
+ const p = find(decodeURIComponent(seg[1]), decodeURIComponent(seg[2]));
962
+ const c = cardOf(p);
963
+ const glb = !isBuiltin(p) && fs.existsSync(path.join(webDir(p.dir), 'preview.glb'));
964
+ return html(embedPage({ lib: p.lib, id: p.id, title: p.manifest.title, glb, version: c.version, packageUrl: urls.package(p.lib, p.id) }, urls), true);
965
+ }
966
+ if (seg[0] === 'p' && seg.length >= 3) {
967
+ const p = find(decodeURIComponent(seg[1]), decodeURIComponent(seg[2]));
968
+ const rest = seg.slice(3);
969
+ // a package's stable address leads to its folder page
970
+ if (!rest.length || (rest.length === 1 && !rest[0]))
971
+ return redirect(302, pageOf(p));
972
+ // a package's thumbnail of one of its outputs (thumbs/<output>.png), nothing else of that folder
973
+ if (rest[0] === 'thumbs' && rest.length === 2) {
974
+ const file = decodeURIComponent(rest[1]);
975
+ const abs = /^[a-z0-9][a-z0-9_-]*\.png$/.test(file) ? path.join(p.dir, 'thumbs', file) : '';
976
+ if (!abs || !fs.statSync(abs, { throwIfNoEntry: false })?.isFile())
977
+ throw new HttpError(404, `no thumbnail ${file}`);
978
+ return send(200, fs.readFileSync(abs), 'image/png', { 'cache-control': 'max-age=3600' });
979
+ }
980
+ // a built-in package: the thumbnail of its first output that has one; no 3D preview
981
+ if (isBuiltin(p) && (rest[0] === 'thumb.png' || rest[0] === 'preview.glb')) {
982
+ const thumb = builtinAt.get(p.dir)?.thumb;
983
+ if (rest[0] === 'preview.glb' || !thumb)
984
+ return rest[0] === 'thumb.png' ? send(200, placeholderPNG(), 'image/png') : json(404, { error: 'TopoTopo\'s built-in packages have no 3D preview here' });
985
+ return send(200, fs.readFileSync(path.join(p.dir, 'thumbs', `${thumb}.png`)), 'image/png', { 'cache-control': 'max-age=3600' });
986
+ }
987
+ if (rest[0] === 'thumb.png' || rest[0] === 'preview.glb') {
988
+ const s = readBakeState(p.dir);
989
+ const file = path.join(webDir(p.dir), rest[0]);
990
+ if (!fs.existsSync(file)) {
991
+ bakeIfStale(p);
992
+ if (rest[0] === 'thumb.png')
993
+ return send(200, placeholderPNG(), 'image/png');
994
+ return json(404, { error: s?.ok === false ? `the bake failed: ${s.error}` : 'not baked yet' });
995
+ }
996
+ const etag = `"${s?.key ?? 'x'}-${s?.at ?? 0}"`;
997
+ if (req.headers['if-none-match'] === etag) {
998
+ res.writeHead(304, { etag });
999
+ return res.end();
1000
+ }
1001
+ return send(200, fs.readFileSync(file), rest[0] === 'thumb.png' ? 'image/png' : MIME['.glb'], { etag, 'cache-control': 'no-cache' });
1002
+ }
1003
+ if (rest[0] === 'files' && rest.length > 1)
1004
+ return sendFile(req, res, packageFile(p, rest.slice(1).join('/')));
1005
+ if ((rest[0] === 'edit' || rest[0] === 'bake') && isBuiltin(p))
1006
+ throw new HttpError(400, 'TopoTopo\'s built-in packages are not edited or baked here: TopoTopo\'s repository publishes them');
1007
+ if (rest[0] === 'edit') {
1008
+ const url = await editorFor(p);
1009
+ return redirect(302, url);
1010
+ }
1011
+ if (rest[0] === 'bake') {
1012
+ if (req.method !== 'POST')
1013
+ throw new HttpError(405, 'POST to bake again');
1014
+ if (!hasDefault(p))
1015
+ throw new HttpError(400, `no default graph yet: ${p.manifest.title} has no graph "${p.manifest.bake.graph ?? p.manifest.graph}" to bake`);
1016
+ const queued = queue.add(p.dir);
1017
+ if (queued)
1018
+ broadcast({ package: keyOf(p), baking: true });
1019
+ return json(200, { ok: true, queued });
1020
+ }
1021
+ if (rest[0] === 'reveal') {
1022
+ if (req.method !== 'POST')
1023
+ throw new HttpError(405, 'POST to show the folder');
1024
+ reveal(p.dir);
1025
+ return json(200, { ok: true });
1026
+ }
1027
+ }
1028
+ send(404, 'not found');
1029
+ }
1030
+ catch (e) {
1031
+ if (res.headersSent || res.destroyed)
1032
+ return;
1033
+ const code = e instanceof HttpError || e instanceof PathError ? e.status : 500;
1034
+ json(code, { ok: false, error: String(e?.message ?? e) });
1035
+ }
1036
+ });
1037
+ const port = o.port ?? cfg.web.port;
1038
+ await new Promise((resolve, reject) => {
1039
+ server.once('error', reject);
1040
+ server.listen(port, '127.0.0.1', () => resolve());
1041
+ });
1042
+ const actual = server.address().port;
1043
+ base = `http://127.0.0.1:${actual}`;
1044
+ const keepAlive = setInterval(() => { for (const c of clients)
1045
+ c.write(': ping\n\n'); }, 20000);
1046
+ keepAlive.unref();
1047
+ // the audits of the trees, made now so that the first page does not wait for them
1048
+ rewarm();
1049
+ return {
1050
+ url: base + '/', port: actual, rescan, queue,
1051
+ close: () => {
1052
+ clearInterval(periodic);
1053
+ clearInterval(keepAlive);
1054
+ clearTimeout(changeTimer);
1055
+ clearTimeout(warm);
1056
+ closed = true;
1057
+ for (const w of watchers)
1058
+ w.close();
1059
+ queue.close();
1060
+ for (const e of editors.values())
1061
+ e.child.kill();
1062
+ for (const c of clients)
1063
+ c.end();
1064
+ server.close();
1065
+ server.closeAllConnections?.();
1066
+ },
1067
+ };
1068
+ }