topotopo 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (354) hide show
  1. package/NOTICE +40 -10
  2. package/README.md +475 -111
  3. package/dist/cli.js +328 -133
  4. package/dist/config.d.ts +48 -0
  5. package/dist/config.js +170 -0
  6. package/dist/core/analysis.d.ts +5 -1
  7. package/dist/core/analysis.js +8 -3
  8. package/dist/core/bake.d.ts +16 -8
  9. package/dist/core/bake.js +165 -29
  10. package/dist/core/bevel.d.ts +3 -1
  11. package/dist/core/bevel.js +238 -97
  12. package/dist/core/decimate.d.ts +65 -0
  13. package/dist/core/decimate.js +409 -3
  14. package/dist/core/erosion.d.ts +37 -0
  15. package/dist/core/erosion.js +41 -1
  16. package/dist/core/geometry.d.ts +5 -1
  17. package/dist/core/geometry.js +204 -4
  18. package/dist/core/heightfield.d.ts +27 -4
  19. package/dist/core/heightfield.js +54 -16
  20. package/dist/core/imageops.d.ts +6 -0
  21. package/dist/core/imageops.js +51 -0
  22. package/dist/core/intrinsics.d.ts +7 -0
  23. package/dist/core/intrinsics.js +94 -0
  24. package/dist/core/manifold.d.ts +12 -1
  25. package/dist/core/manifold.js +78 -6
  26. package/dist/core/materials.d.ts +11 -0
  27. package/dist/core/materials.js +56 -0
  28. package/dist/core/noise.d.ts +9 -0
  29. package/dist/core/noise.js +10 -1
  30. package/dist/core/packed.js +11 -0
  31. package/dist/core/particles.d.ts +1 -1
  32. package/dist/core/particles.js +1 -1
  33. package/dist/core/polymerge.d.ts +21 -0
  34. package/dist/core/polymerge.js +327 -0
  35. package/dist/core/rbd.js +13 -1
  36. package/dist/core/repair.d.ts +2 -0
  37. package/dist/core/repair.js +2 -0
  38. package/dist/core/report.d.ts +70 -0
  39. package/dist/core/report.js +275 -0
  40. package/dist/core/scatter.d.ts +1 -1
  41. package/dist/core/scatter.js +1 -1
  42. package/dist/core/scene.d.ts +20 -0
  43. package/dist/core/scene.js +72 -0
  44. package/dist/core/sha256.d.ts +4 -0
  45. package/dist/core/sha256.js +69 -0
  46. package/dist/core/shapes.d.ts +3 -0
  47. package/dist/core/shapes.js +34 -0
  48. package/dist/core/snippet-lib.d.ts +15 -2
  49. package/dist/core/snippet-lib.js +40 -14
  50. package/dist/core/solidify.d.ts +38 -0
  51. package/dist/core/solidify.js +356 -0
  52. package/dist/core/tangents.d.ts +54 -0
  53. package/dist/core/tangents.js +218 -0
  54. package/dist/core/texcoord.d.ts +4 -0
  55. package/dist/core/texcoord.js +14 -0
  56. package/dist/core/texnoise.d.ts +6 -1
  57. package/dist/core/texnoise.js +6 -2
  58. package/dist/core/texsdf.d.ts +131 -0
  59. package/dist/core/texsdf.js +637 -0
  60. package/dist/core/texture.d.ts +163 -9
  61. package/dist/core/texture.js +844 -20
  62. package/dist/core/topology.d.ts +32 -0
  63. package/dist/core/topology.js +238 -7
  64. package/dist/core/traceimage.d.ts +7 -0
  65. package/dist/core/traceimage.js +221 -0
  66. package/dist/core/tritri.d.ts +5 -0
  67. package/dist/core/tritri.js +120 -0
  68. package/dist/core/unwrap.d.ts +72 -0
  69. package/dist/core/unwrap.js +800 -0
  70. package/dist/core/usercode.d.ts +27 -0
  71. package/dist/core/usercode.js +87 -0
  72. package/dist/core/uv.d.ts +15 -16
  73. package/dist/core/uv.js +36 -189
  74. package/dist/core/uvislands.d.ts +62 -0
  75. package/dist/core/uvislands.js +574 -0
  76. package/dist/core/uvoverlap.d.ts +58 -0
  77. package/dist/core/uvoverlap.js +220 -0
  78. package/dist/core/uvpack.d.ts +64 -0
  79. package/dist/core/uvpack.js +628 -0
  80. package/dist/core/uvreport.d.ts +127 -0
  81. package/dist/core/uvreport.js +372 -0
  82. package/dist/core/wrangle.d.ts +6 -1
  83. package/dist/core/wrangle.js +27 -16
  84. package/dist/core/xatlas.d.ts +16 -1
  85. package/dist/core/xatlas.js +95 -61
  86. package/dist/engines.d.ts +63 -0
  87. package/dist/engines.js +180 -0
  88. package/dist/explain.d.ts +4 -3
  89. package/dist/explain.js +129 -12
  90. package/dist/graph/engine.d.ts +92 -29
  91. package/dist/graph/engine.js +298 -148
  92. package/dist/graph/expr.d.ts +6 -3
  93. package/dist/graph/expr.js +18 -8
  94. package/dist/graph/outputs.d.ts +23 -0
  95. package/dist/graph/outputs.js +41 -0
  96. package/dist/graph/packages.d.ts +72 -0
  97. package/dist/graph/packages.js +261 -0
  98. package/dist/graph/parallel.d.ts +3 -1
  99. package/dist/graph/parallel.js +4 -1
  100. package/dist/graph/params.d.ts +6 -0
  101. package/dist/graph/params.js +34 -7
  102. package/dist/graph/scope.d.ts +55 -0
  103. package/dist/graph/scope.js +14 -0
  104. package/dist/graph/types.d.ts +75 -12
  105. package/dist/graph/types.js +4 -2
  106. package/dist/graph/vars.d.ts +16 -0
  107. package/dist/graph/vars.js +80 -0
  108. package/dist/host/artifacts.d.ts +10 -1
  109. package/dist/host/artifacts.js +37 -6
  110. package/dist/host/cook.d.ts +241 -0
  111. package/dist/host/cook.js +844 -0
  112. package/dist/host/export-targets.d.ts +42 -5
  113. package/dist/host/export-targets.js +72 -13
  114. package/dist/host/godot-commands.d.ts +4 -0
  115. package/dist/host/godot-commands.js +21 -0
  116. package/dist/host/godot.d.ts +183 -0
  117. package/dist/host/godot.js +916 -0
  118. package/dist/host/node.d.ts +12 -7
  119. package/dist/host/node.js +27 -9
  120. package/dist/host/pool.js +51 -2
  121. package/dist/host/sidecars.d.ts +8 -0
  122. package/dist/host/sidecars.js +50 -0
  123. package/dist/host/types.d.ts +19 -6
  124. package/dist/host/version.d.ts +1 -0
  125. package/dist/host/version.js +3 -0
  126. package/dist/host/worker.js +5 -2
  127. package/dist/index.d.ts +5 -3
  128. package/dist/index.js +3 -2
  129. package/dist/inspect.d.ts +84 -1
  130. package/dist/inspect.js +271 -24
  131. package/dist/io/common.d.ts +33 -5
  132. package/dist/io/export.js +2 -1
  133. package/dist/io/files.d.ts +23 -4
  134. package/dist/io/files.js +60 -8
  135. package/dist/io/gltf.js +355 -51
  136. package/dist/io/heightmap.d.ts +3 -0
  137. package/dist/io/heightmap.js +1 -0
  138. package/dist/io/import.js +10 -0
  139. package/dist/io/inspect-scene.d.ts +55 -0
  140. package/dist/io/inspect-scene.js +155 -0
  141. package/dist/io/kinds.d.ts +81 -0
  142. package/dist/io/kinds.js +163 -0
  143. package/dist/io/points.d.ts +2 -1
  144. package/dist/io/points.js +3 -1
  145. package/dist/io/sidecars.d.ts +24 -0
  146. package/dist/io/sidecars.js +57 -0
  147. package/dist/io/source.d.ts +65 -0
  148. package/dist/io/source.js +112 -0
  149. package/dist/io/targets.d.ts +47 -3
  150. package/dist/io/targets.js +149 -14
  151. package/dist/io/textures.js +21 -1
  152. package/dist/io/unreal.js +5 -1
  153. package/dist/mcp/docs.d.ts +10 -1
  154. package/dist/mcp/docs.js +816 -119
  155. package/dist/mcp/inputs.d.ts +12 -5
  156. package/dist/mcp/inputs.js +50 -13
  157. package/dist/mcp/server.js +70 -24
  158. package/dist/mcp/tools.d.ts +14 -7
  159. package/dist/mcp/tools.js +207 -108
  160. package/dist/mcp/verify.d.ts +2 -2
  161. package/dist/mcp/verify.js +1 -1
  162. package/dist/mcp/workspace.d.ts +15 -0
  163. package/dist/mcp/workspace.js +349 -0
  164. package/dist/nodes/attributes.js +198 -1
  165. package/dist/nodes/bake.js +207 -83
  166. package/dist/nodes/beam.d.ts +1 -0
  167. package/dist/nodes/beam.js +201 -0
  168. package/dist/nodes/bevel.js +54 -5
  169. package/dist/nodes/cloth.js +2 -0
  170. package/dist/nodes/code.js +22 -10
  171. package/dist/nodes/curves.js +440 -93
  172. package/dist/nodes/flow.js +53 -33
  173. package/dist/nodes/generate.js +13 -39
  174. package/dist/nodes/heightfield.js +248 -77
  175. package/dist/nodes/imageops.d.ts +1 -0
  176. package/dist/nodes/imageops.js +203 -0
  177. package/dist/nodes/index.d.ts +4 -0
  178. package/dist/nodes/index.js +4 -0
  179. package/dist/nodes/material.js +91 -23
  180. package/dist/nodes/measure.js +45 -18
  181. package/dist/nodes/particles.js +2 -0
  182. package/dist/nodes/pcg.js +6 -5
  183. package/dist/nodes/procedural.js +4 -3
  184. package/dist/nodes/rbd.js +1 -1
  185. package/dist/nodes/remesh.js +71 -15
  186. package/dist/nodes/scene.d.ts +1 -0
  187. package/dist/nodes/scene.js +55 -0
  188. package/dist/nodes/sdf.js +10 -5
  189. package/dist/nodes/solid.js +20 -5
  190. package/dist/nodes/solidify.d.ts +1 -0
  191. package/dist/nodes/solidify.js +52 -0
  192. package/dist/nodes/splines.d.ts +15 -1
  193. package/dist/nodes/splines.js +112 -105
  194. package/dist/nodes/texture.d.ts +21 -6
  195. package/dist/nodes/texture.js +1318 -185
  196. package/dist/nodes/topology.d.ts +7 -0
  197. package/dist/nodes/topology.js +133 -6
  198. package/dist/nodes/transform.js +11 -3
  199. package/dist/nodes/util.d.ts +1 -1
  200. package/dist/nodes/uv.js +192 -174
  201. package/dist/nodes/wasmcall.js +6 -2
  202. package/dist/open.d.ts +19 -0
  203. package/dist/open.js +12 -0
  204. package/dist/package.d.ts +288 -0
  205. package/dist/package.js +772 -0
  206. package/dist/packages/check.d.ts +32 -0
  207. package/dist/packages/check.js +169 -0
  208. package/dist/packages/commands.d.ts +57 -0
  209. package/dist/packages/commands.js +537 -0
  210. package/dist/packages/registry.d.ts +796 -0
  211. package/dist/packages/registry.js +2998 -0
  212. package/dist/packages/update.d.ts +124 -0
  213. package/dist/packages/update.js +476 -0
  214. package/dist/render/options.d.ts +2 -0
  215. package/dist/render/options.js +44 -5
  216. package/dist/render/pbr.d.ts +28 -0
  217. package/dist/render/pbr.js +378 -0
  218. package/dist/render/preview.d.ts +69 -0
  219. package/dist/render/preview.js +26 -0
  220. package/dist/render/raster.d.ts +78 -7
  221. package/dist/render/raster.js +600 -145
  222. package/dist/render/texview.d.ts +7 -1
  223. package/dist/render/texview.js +34 -2
  224. package/dist/scan.d.ts +61 -0
  225. package/dist/scan.js +228 -0
  226. package/dist/session.d.ts +311 -0
  227. package/dist/session.js +849 -0
  228. package/dist/viewer/app/api.js +48 -6
  229. package/dist/viewer/app/camera.js +1 -1
  230. package/dist/viewer/app/cooking.js +78 -0
  231. package/dist/viewer/app/embed.js +100 -0
  232. package/dist/viewer/app/export-popover.js +118 -16
  233. package/dist/viewer/app/grid.js +6 -2
  234. package/dist/viewer/app/guides.js +123 -1
  235. package/dist/viewer/app/keymap.js +7 -4
  236. package/dist/viewer/app/layers.js +5 -5
  237. package/dist/viewer/app/main.js +186 -53
  238. package/dist/viewer/app/markers.js +61 -1
  239. package/dist/viewer/app/outliner.js +72 -27
  240. package/dist/viewer/app/output-info.js +45 -0
  241. package/dist/viewer/app/outputs.css +147 -8
  242. package/dist/viewer/app/outputs.js +168 -54
  243. package/dist/viewer/app/packages.js +614 -0
  244. package/dist/viewer/app/props.js +177 -53
  245. package/dist/viewer/app/scene.js +35 -6
  246. package/dist/viewer/app/select.js +5 -4
  247. package/dist/viewer/app/selection.js +1 -1
  248. package/dist/viewer/app/status.js +12 -15
  249. package/dist/viewer/app/style.css +66 -8
  250. package/dist/viewer/app/units.js +1 -1
  251. package/dist/viewer/app/vars.js +48 -1
  252. package/dist/viewer/app/welcome.js +72 -0
  253. package/dist/viewer/graph-file.d.ts +62 -0
  254. package/dist/viewer/graph-file.js +175 -0
  255. package/dist/viewer/index.html +24 -11
  256. package/dist/viewer/json-edit.d.ts +13 -0
  257. package/dist/viewer/json-edit.js +274 -0
  258. package/dist/viewer/outputs.d.ts +49 -5
  259. package/dist/viewer/outputs.js +264 -56
  260. package/dist/viewer/packages.d.ts +121 -0
  261. package/dist/viewer/packages.js +584 -0
  262. package/dist/viewer/server.d.ts +24 -7
  263. package/dist/viewer/server.js +289 -31
  264. package/dist/web/app/web.css +419 -0
  265. package/dist/web/app/web.js +188 -0
  266. package/dist/web/bake.d.ts +34 -0
  267. package/dist/web/bake.js +153 -0
  268. package/dist/web/folder-page.d.ts +101 -0
  269. package/dist/web/folder-page.js +146 -0
  270. package/dist/web/folders.d.ts +280 -0
  271. package/dist/web/folders.js +970 -0
  272. package/dist/web/library.d.ts +91 -0
  273. package/dist/web/library.js +228 -0
  274. package/dist/web/markdown.d.ts +45 -0
  275. package/dist/web/markdown.js +677 -0
  276. package/dist/web/pages.d.ts +258 -0
  277. package/dist/web/pages.js +301 -0
  278. package/dist/web/server.d.ts +24 -0
  279. package/dist/web/server.js +1068 -0
  280. package/dist/workspace.d.ts +88 -105
  281. package/dist/workspace.js +359 -375
  282. package/integrations/godot/addons/topotopo/LICENSE +202 -0
  283. package/integrations/godot/addons/topotopo/README.md +57 -0
  284. package/integrations/godot/addons/topotopo/context_menu.gd +43 -0
  285. package/integrations/godot/addons/topotopo/dock.gd +266 -0
  286. package/integrations/godot/addons/topotopo/dock.tscn +72 -0
  287. package/integrations/godot/addons/topotopo/export_filter.gd +72 -0
  288. package/integrations/godot/addons/topotopo/gltf_instancing.gd +131 -0
  289. package/integrations/godot/addons/topotopo/icons/topotopo.svg +1 -0
  290. package/integrations/godot/addons/topotopo/inspector.gd +38 -0
  291. package/integrations/godot/addons/topotopo/instances_post_import.gd +111 -0
  292. package/integrations/godot/addons/topotopo/package.gd +23 -0
  293. package/integrations/godot/addons/topotopo/package_importer.gd +187 -0
  294. package/integrations/godot/addons/topotopo/plugin.cfg +7 -0
  295. package/integrations/godot/addons/topotopo/plugin.gd +970 -0
  296. package/integrations/godot/addons/topotopo/record.gd +435 -0
  297. package/integrations/godot/addons/topotopo/runner.gd +458 -0
  298. package/integrations/godot/addons/topotopo/tools/check.gd +42 -0
  299. package/integrations/godot/addons/topotopo/watcher.gd +199 -0
  300. package/kernels/pkg/README.md +23 -29
  301. package/kernels/pkg-simd/README.md +23 -29
  302. package/library/architecture/versions/1.0/architecture.topo +12 -0
  303. package/{shelf → library/architecture/versions/1.0/graphs}/arch.json +3 -3
  304. package/{shelf → library/architecture/versions/1.0/graphs}/beam_truss.json +6 -6
  305. package/{shelf → library/architecture/versions/1.0/graphs}/brick_wall.json +8 -8
  306. package/{shelf → library/architecture/versions/1.0/graphs}/door_frame.json +3 -3
  307. package/{shelf → library/architecture/versions/1.0/graphs}/hex_grid_floor.json +3 -2
  308. package/{shelf → library/architecture/versions/1.0/graphs}/house.json +8 -8
  309. package/library/architecture/versions/1.0/graphs/lineup.json +42 -0
  310. package/{shelf → library/architecture/versions/1.0/graphs}/pillar.json +3 -2
  311. package/{shelf → library/architecture/versions/1.0/graphs}/railing.json +5 -5
  312. package/{shelf → library/architecture/versions/1.0/graphs}/roof_gable.json +2 -2
  313. package/{shelf → library/architecture/versions/1.0/graphs}/roof_hip.json +2 -2
  314. package/{shelf → library/architecture/versions/1.0/graphs}/roof_skeleton.json +2 -1
  315. package/{shelf → library/architecture/versions/1.0/graphs}/scaffold.json +4 -4
  316. package/{shelf → library/architecture/versions/1.0/graphs}/spiral_stairs.json +3 -2
  317. package/{shelf → library/architecture/versions/1.0/graphs}/stairs.json +6 -6
  318. package/{shelf → library/architecture/versions/1.0/graphs}/tile_floor.json +3 -2
  319. package/{shelf → library/architecture/versions/1.0/graphs}/wall_segment.json +10 -10
  320. package/{shelf → library/architecture/versions/1.0/graphs}/window_frame.json +2 -2
  321. package/library/architecture/versions/1.0/version.json +1119 -0
  322. package/{shelf → library/nature/versions/1.0/graphs}/bush.json +2 -2
  323. package/{shelf → library/nature/versions/1.0/graphs}/cliff_block.json +4 -3
  324. package/{shelf → library/nature/versions/1.0/graphs}/forest_patch.json +5 -5
  325. package/{shelf → library/nature/versions/1.0/graphs}/grass_clumps.json +2 -2
  326. package/library/nature/versions/1.0/graphs/lineup.json +24 -0
  327. package/{shelf → library/nature/versions/1.0/graphs}/log.json +6 -6
  328. package/{shelf → library/nature/versions/1.0/graphs}/rock.json +5 -4
  329. package/{shelf → library/nature/versions/1.0/graphs}/scatter_rocks.json +5 -5
  330. package/{shelf → library/nature/versions/1.0/graphs}/tree_lowpoly.json +3 -2
  331. package/library/nature/versions/1.0/nature.topo +12 -0
  332. package/library/nature/versions/1.0/version.json +534 -0
  333. package/{shelf → library/props/versions/1.0/graphs}/barrel.json +5 -4
  334. package/{shelf → library/props/versions/1.0/graphs}/crate.json +3 -3
  335. package/library/props/versions/1.0/graphs/lineup.json +18 -0
  336. package/{shelf → library/props/versions/1.0/graphs}/pallet.json +4 -3
  337. package/{shelf → library/props/versions/1.0/graphs}/pipe_run.json +3 -3
  338. package/{shelf → library/props/versions/1.0/graphs}/sandbag_wall.json +5 -5
  339. package/library/props/versions/1.0/props.topo +12 -0
  340. package/library/props/versions/1.0/version.json +336 -0
  341. package/{shelf → library/street/versions/1.0/graphs}/bench.json +5 -5
  342. package/{shelf → library/street/versions/1.0/graphs}/bollard.json +2 -1
  343. package/{shelf → library/street/versions/1.0/graphs}/cable.json +4 -4
  344. package/{shelf → library/street/versions/1.0/graphs}/fence.json +7 -7
  345. package/{shelf → library/street/versions/1.0/graphs}/lamp_post.json +2 -2
  346. package/library/street/versions/1.0/graphs/lineup.json +22 -0
  347. package/{shelf → library/street/versions/1.0/graphs}/road_strip.json +2 -2
  348. package/{shelf → library/street/versions/1.0/graphs}/sign_post.json +1 -1
  349. package/library/street/versions/1.0/street.topo +12 -0
  350. package/library/street/versions/1.0/version.json +421 -0
  351. package/package.json +23 -8
  352. package/dist/graph/migrate.d.ts +0 -23
  353. package/dist/graph/migrate.js +0 -58
  354. package/shelf/index.json +0 -190
@@ -0,0 +1,844 @@
1
+ // The engine-neutral cook of a package's published outputs into an engine project (`topotopo cook … --for godot`; the
2
+ // Godot flavour is src/host/godot.ts): which outputs, the recording host that learns what each output reads, the
3
+ // per-output incremental cook, the writing rules (write only changed bytes, never a foreign file, a failed output
4
+ // keeps its last good files, orphans), the record, freshness, the shared cook cache, the report and the progress lines.
5
+ //
6
+ // What is cooked: the package's published outputs (packageOutputs, the rule publishing uses) from its working folder
7
+ // at frame 1 with their graphs' var defaults, under --locked rules (nothing of the package is written but its outputs
8
+ // and its record; a graph naming a package it does not use, a missing or edited copy, fail that output). Used packages
9
+ // come from their pinned copies; working folders are never followed.
10
+ //
11
+ // The record, <package>/.topotopo/<for>.json, is committed with the outputs: canonical JSON (sorted keys, 2-space
12
+ // indent, LF, trailing newline), no times and no machine paths: sources relative to the package (posix), output files
13
+ // as the engine names them (res:// in Godot). Same inputs and version give byte-identical outputs and record.
14
+ // {"folders": {<folder>: [<files below it>]}, "for": "godot", "name": <publish name or null>, "notes": [...],
15
+ // "options": {"folder", "instancing", "per_output_folders", "skip"}, "orphans": {<file>: <output>},
16
+ // "outputs": {<id>: {"default", "deps", "errors", "files": {<file>: <sha256>}, "folders", "graph", "instances",
17
+ // "kind", "label", "node", "state": "ok" | "failed", "warnings"}},
18
+ // "package": <id>, "schema": 1, "skipped": {<id>: {"why", ...}}, "sources": {<file>: <contentSha>}, "topotopo": <version>}
19
+ // Source hashes are contentSha (src/packages/registry.ts: text with CRLF read as LF, binary formats raw); output file
20
+ // hashes are raw SHA-256. Freshness (freshness() below; the Godot addon ports it byte for byte, integrations/godot/
21
+ // PROTOCOL.md) checks, in order: no record, schema and flavour, options, sources, folder listings, output files, the
22
+ // installed version, failed outputs.
23
+ import fs from 'node:fs';
24
+ import os from 'node:os';
25
+ import path from 'node:path';
26
+ import { createHash } from 'node:crypto';
27
+ import { fileURLToPath } from 'node:url';
28
+ import { Engine } from '../graph/engine.js';
29
+ import { packagesNamedIn, packagesUsed } from '../graph/packages.js';
30
+ import { kindMismatch, outputKind, publishedKind } from '../io/kinds.js';
31
+ import { packedSourceNames } from '../io/common.js';
32
+ import { PackageUses, contentSha, loadPackage, packageOutputs } from '../packages/registry.js';
33
+ import { WORKSPACE_FILE, copiesFor, locate, readManifest, renameInto, takeLock, writeAtomic } from '../package.js';
34
+ import { isEngineFile } from '../engines.js';
35
+ import { graphFiles } from '../session.js';
36
+ import { folderKey } from '../scan.js';
37
+ import { createNodeHost } from './node.js';
38
+ import { TOPOTOPO_VERSION } from './version.js';
39
+ /** The jobs file's and report's protocol: an engine plugin that speaks another one is told to update. */
40
+ export const COOK_PROTOCOL = 1;
41
+ /** The record's schema. */
42
+ export const RECORD_SCHEMA = 1;
43
+ /** The package's folder of TopoTopo's engine files (a dot folder: engines never import it). */
44
+ export const RECORD_DIR = '.topotopo';
45
+ /** A file being written: <file>.topotopo-part, moved into place. */
46
+ export const PART_SUFFIX = '.topotopo-part';
47
+ /** The folders whose listings every record holds. */
48
+ export const LISTED_FOLDERS = ['assets', 'graphs', 'inputs'];
49
+ /** Why an output listed in the options' skip is not cooked. */
50
+ export const SKIPPED_BY_OPTIONS = "listed in the import options' skip (outputs/skip)";
51
+ // ---------------------------------------------------------------------------------------------------------- files
52
+ const sha256 = (d) => createHash('sha256').update(d).digest('hex');
53
+ const byCode = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
54
+ const posix = (p) => p.split(path.sep).join('/');
55
+ /** An absolute path as reports and progress lines give it: forward slashes ("C:/game/props/props.topo"). */
56
+ export const slash = (p) => path.resolve(p).split(path.sep).join('/');
57
+ const isUrl = (p) => /^[a-z][a-z0-9+.-]*:\/\//i.test(p);
58
+ /** `inner` is `outer` or below it */
59
+ const within = (inner, outer) => { const r = path.relative(path.resolve(outer), path.resolve(inner)); return !r || (!r.startsWith('..') && !path.isAbsolute(r)); };
60
+ /** TopoTopo's own files (fonts, kernels, dependencies): the version rule covers them, a record never names them. */
61
+ const TOPOTOPO_ROOT = path.resolve(fileURLToPath(new URL('../..', import.meta.url)));
62
+ const OWN = ['assets', 'kernels', 'node_modules', 'library'].map((d) => path.join(TOPOTOPO_ROOT, d));
63
+ /**
64
+ * The files below a folder, as a record's "folders" lists them: relative posix paths, recursively, sorted; names
65
+ * starting with "." (files and folders), the files engines write beside ours (*.import, *.uid, *.translation,
66
+ * *.uasset) and *.topotopo-part left out. A folder that is not there lists nothing.
67
+ */
68
+ export function listing(dir) {
69
+ const out = [];
70
+ const walk = (d, rel, depth) => {
71
+ let entries;
72
+ try {
73
+ entries = fs.readdirSync(d, { withFileTypes: true });
74
+ }
75
+ catch {
76
+ return;
77
+ }
78
+ for (const e of entries) {
79
+ if (e.name.startsWith('.'))
80
+ continue;
81
+ const r = rel ? `${rel}/${e.name}` : e.name;
82
+ if (e.isDirectory()) {
83
+ if (depth < 32)
84
+ walk(path.join(d, e.name), r, depth + 1);
85
+ }
86
+ else if (e.isFile() && !isEngineFile(e.name) && !e.name.endsWith(PART_SUFFIX))
87
+ out.push(r);
88
+ }
89
+ };
90
+ walk(dir, '', 0);
91
+ return out.sort(byCode);
92
+ }
93
+ const sameList = (a, b) => !!a && a.length === b.length && [...a].sort(byCode).every((x, i) => x === b[i]);
94
+ /** A record's path for a file: relative to the package (posix) inside the engine project, else absolute (posix). */
95
+ function relOf(dir, project, abs) {
96
+ if (!within(abs, project))
97
+ return posix(path.resolve(abs));
98
+ return posix(path.relative(dir, abs)) || '.';
99
+ }
100
+ /** A record's path back to an absolute one. */
101
+ const absOf = (dir, rel) => (path.isAbsolute(rel) || /^[A-Za-z]:\//.test(rel) ? path.resolve(rel) : path.resolve(dir, ...rel.split('/')));
102
+ /** contentSha of files, each hashed once per cook (null: missing). */
103
+ class Shas {
104
+ memo = new Map();
105
+ of(abs) {
106
+ const k = folderKey(abs);
107
+ if (this.memo.has(k))
108
+ return this.memo.get(k);
109
+ let s = null;
110
+ try {
111
+ s = contentSha(abs, fs.readFileSync(abs));
112
+ }
113
+ catch { /* missing */ }
114
+ this.memo.set(k, s);
115
+ return s;
116
+ }
117
+ /** a file's hash as it was read during a cook (the first one taken stays) */
118
+ seen(abs, sha) { const k = folderKey(abs); if (!this.memo.has(k))
119
+ this.memo.set(k, sha); }
120
+ }
121
+ /** SHA-256 of a file's bytes, or null when it is not there. */
122
+ function rawSha(abs) {
123
+ try {
124
+ return sha256(fs.readFileSync(abs));
125
+ }
126
+ catch {
127
+ return null;
128
+ }
129
+ }
130
+ /** JSON with every object's keys sorted, 2-space indent, LF, one key per line, a trailing newline. */
131
+ export function canonicalText(v) {
132
+ const sort = (x) => {
133
+ if (Array.isArray(x))
134
+ return x.map(sort);
135
+ if (!x || typeof x !== 'object')
136
+ return x;
137
+ const o = {};
138
+ for (const k of Object.keys(x).sort(byCode))
139
+ if (x[k] !== undefined)
140
+ o[k] = sort(x[k]);
141
+ return o;
142
+ };
143
+ return JSON.stringify(sort(v), null, 2) + '\n';
144
+ }
145
+ /** A record file's path for a flavour. */
146
+ export const recordFile = (dir, flavour) => path.join(dir, RECORD_DIR, `${flavour}.json`);
147
+ /** A package's record (null: none; throws when it cannot be read). */
148
+ export function readRecord(dir, flavour) {
149
+ const file = recordFile(dir, flavour);
150
+ let text;
151
+ try {
152
+ text = fs.readFileSync(file, 'utf8');
153
+ }
154
+ catch {
155
+ return null;
156
+ }
157
+ let raw;
158
+ try {
159
+ raw = JSON.parse(text.replace(/^\uFEFF/, ''));
160
+ }
161
+ catch (e) {
162
+ throw new Error(`${file}: ${e.message}`);
163
+ }
164
+ if (!raw || typeof raw !== 'object' || typeof raw.schema !== 'number')
165
+ throw new Error(`${file} is not a cook record (it has no "schema")`);
166
+ return raw;
167
+ }
168
+ /** "0.4.0" against "0.10.1": numeric parts, missing ones 0. */
169
+ export function compareVersions(a, b) {
170
+ const p = (v) => String(v).split('.').map((x) => parseInt(x, 10) || 0);
171
+ const x = p(a), y = p(b);
172
+ for (let i = 0; i < Math.max(x.length, y.length); i++) {
173
+ const d = (x[i] ?? 0) - (y[i] ?? 0);
174
+ if (d)
175
+ return d;
176
+ }
177
+ return 0;
178
+ }
179
+ /** Options as the record compares them: skip sorted, each once. */
180
+ export const normalOptions = (o) => ({ folder: o.folder, instancing: o.instancing, per_output_folders: o.per_output_folders, skip: [...new Set(o.skip)].sort(byCode) });
181
+ const sameOptions = (a, b) => !!a && canonicalText(normalOptions(a)) === canonicalText(normalOptions(b));
182
+ /**
183
+ * The one definition of freshness (the Godot addon ports it: integrations/godot/PROTOCOL.md), checked in this order:
184
+ * 1. no record: never cooked;
185
+ * 2. schema newer than this TopoTopo knows: stale (update); schema or flavour ("for") another: stale;
186
+ * 3. the options differ from the import options: stale;
187
+ * 4. a source missing or its contentSha differs: stale, naming it;
188
+ * 5. a folder's listing differs: stale, naming it;
189
+ * 6. an output file missing or its SHA-256 differs: stale, naming it;
190
+ * 7. the installed TopoTopo (`installed`, when it is known) is newer than the record's: stale; older: a note only;
191
+ * 8. an output failed: failed;
192
+ * 9. ok.
193
+ * `absolutePath`: an output file as the record names it, as a path.
194
+ */
195
+ export function freshness(dir, record, options, o) {
196
+ const shas = o.shas ?? new Shas();
197
+ const f = (state, why, p, text, note = '') => ({ state, why, path: p, note, text });
198
+ if (!record)
199
+ return f('never_cooked', 'record', '', 'never cooked');
200
+ if (record.schema > RECORD_SCHEMA)
201
+ return f('stale', 'newer_schema', '', `the record has schema ${record.schema}, newer than this TopoTopo reads (${RECORD_SCHEMA}): update TopoTopo`);
202
+ if (record.schema !== RECORD_SCHEMA || record.for !== o.for)
203
+ return f('stale', 'schema', '', `the record is of another kind (schema ${record.schema}, for ${record.for})`);
204
+ if (!sameOptions(record.options, options))
205
+ return f('stale', 'options', '', 'the import options changed since the last cook');
206
+ for (const rel of Object.keys(record.sources ?? {}).sort(byCode)) {
207
+ const now = shas.of(absOf(dir, rel));
208
+ if (now === null)
209
+ return f('stale', 'source', rel, `${rel} is missing`);
210
+ if (now !== record.sources[rel])
211
+ return f('stale', 'source', rel, `${rel} changed after the last cook`);
212
+ }
213
+ for (const folder of Object.keys(record.folders ?? {}).sort(byCode)) {
214
+ if (!sameList(record.folders[folder], listing(absOf(dir, folder))))
215
+ return f('stale', 'folder', folder, `${folder}/ holds other files than at the last cook`);
216
+ }
217
+ for (const id of Object.keys(record.outputs ?? {}).sort(byCode)) {
218
+ for (const [file, s] of Object.entries(record.outputs[id].files ?? {}).sort(([a], [b]) => byCode(a, b))) {
219
+ const now = rawSha(o.absolutePath(file));
220
+ if (now === null)
221
+ return f('stale', 'output', file, `${file} is missing`);
222
+ if (now !== s)
223
+ return f('stale', 'output', file, `${file} was changed after the last cook`);
224
+ }
225
+ }
226
+ let note = '';
227
+ if (o.installed) {
228
+ const c = compareVersions(o.installed, record.topotopo);
229
+ if (c > 0)
230
+ return f('stale', 'version', '', `cooked with TopoTopo ${record.topotopo}; ${o.installed} is installed`);
231
+ if (c < 0)
232
+ note = 'update_topotopo';
233
+ }
234
+ const failed = Object.keys(record.outputs ?? {}).sort(byCode).filter((id) => record.outputs[id].state === 'failed');
235
+ if (failed.length)
236
+ return f('failed', 'failed', failed[0], `${failed.length === 1 ? 'output' : 'outputs'} ${failed.join(', ')} did not cook`, note);
237
+ return f('ok', '', '', 'cooked, current', note);
238
+ }
239
+ // ------------------------------------------------------------------------------------------- the recording host
240
+ /** The files and folders the cook of one output read (absolute; files with their contentSha when read whole). */
241
+ class Recorder {
242
+ active = false;
243
+ files = new Map();
244
+ dirs = new Map();
245
+ urls = new Set();
246
+ start() { this.active = true; this.files.clear(); this.dirs.clear(); this.urls.clear(); }
247
+ stop() { this.active = false; }
248
+ file(p, bytes) {
249
+ if (!this.active)
250
+ return;
251
+ if (isUrl(p)) {
252
+ this.urls.add(p);
253
+ return;
254
+ }
255
+ const k = folderKey(p), have = this.files.get(k);
256
+ if (bytes) {
257
+ if (!have?.sha)
258
+ this.files.set(k, { abs: path.resolve(p), sha: contentSha(p, bytes) });
259
+ }
260
+ else if (!have)
261
+ this.files.set(k, { abs: path.resolve(p), sha: null });
262
+ }
263
+ dir(p) { if (this.active && !isUrl(p))
264
+ this.dirs.set(folderKey(p), path.resolve(p)); }
265
+ }
266
+ /**
267
+ * A host whose file operations tell `rec` what they read: readFile, fileStamp, isDirectory (a folder), listDir,
268
+ * convertFile (its source) and the hosts filesAt gives, the only ways the core reads files.
269
+ */
270
+ function recordingHost(host, rec) {
271
+ const w = Object.create(host);
272
+ const { readFile, fileStamp, isDirectory, listDir, convertFile, filesAt } = host;
273
+ w.readFile = async function (p) { const bytes = await readFile.call(this, p); rec.file(this.resolvePath(p), bytes); return bytes; };
274
+ w.fileStamp = function (p) { const s = fileStamp.call(this, p); rec.file(this.resolvePath(p)); return s; };
275
+ if (isDirectory)
276
+ w.isDirectory = function (p) { const d = isDirectory.call(this, p); if (d)
277
+ rec.dir(this.resolvePath(p)); return d; };
278
+ if (listDir)
279
+ w.listDir = function (p) { const l = listDir.call(this, p); rec.dir(this.resolvePath(p)); return l; };
280
+ if (convertFile)
281
+ w.convertFile = async function (p, t) { rec.file(this.resolvePath(p)); return convertFile.call(this, p, t); };
282
+ // the hosts of other folders (a copy's scope) take their methods from `this`: the recording ones
283
+ if (filesAt)
284
+ w.filesAt = function (dir) { return filesAt.call(w, dir); };
285
+ return w;
286
+ }
287
+ // -------------------------------------------------------------------------------------------------------- the cache
288
+ /** Candidates kept per cache entry. */
289
+ const MAX_CANDIDATES = 8;
290
+ /** The cache's size cap: the oldest blobs go first. */
291
+ export const CACHE_MAX_BYTES = 2 * 2 ** 30;
292
+ const CACHE_FORMAT = 1;
293
+ /** The cook cache, shared by every checkout and worktree: $TOPOTOPO_CACHE/cook, else ~/.topotopo/cache/cook. */
294
+ export function cacheRoot() {
295
+ return path.join(process.env.TOPOTOPO_CACHE ? path.resolve(process.env.TOPOTOPO_CACHE) : path.join(os.homedir(), '.topotopo', 'cache'), 'cook');
296
+ }
297
+ const cacheKey = (flavour, instancing, pkg, id) => sha256(JSON.stringify([TOPOTOPO_VERSION, flavour, { instancing }, pkg, id]));
298
+ function readCandidates(key) {
299
+ try {
300
+ const raw = JSON.parse(fs.readFileSync(path.join(cacheRoot(), key, 'manifest.json'), 'utf8'));
301
+ return raw?.format === CACHE_FORMAT && Array.isArray(raw.candidates) ? raw.candidates : [];
302
+ }
303
+ catch {
304
+ return [];
305
+ }
306
+ }
307
+ /** The first candidate whose deps and folders match the package as it is now, with its files' bytes; null for none. */
308
+ function cacheLookup(key, match) {
309
+ for (const c of readCandidates(key)) {
310
+ if (!match(c))
311
+ continue;
312
+ const files = [];
313
+ let complete = true;
314
+ for (const [name, blob] of Object.entries(c.files).sort(([a], [b]) => byCode(a, b))) {
315
+ const at = path.join(cacheRoot(), 'blobs', blob);
316
+ try {
317
+ const bytes = new Uint8Array(fs.readFileSync(at));
318
+ if (sha256(bytes) !== blob) {
319
+ complete = false;
320
+ break;
321
+ }
322
+ files.push({ name, bytes });
323
+ const now = new Date();
324
+ try {
325
+ fs.utimesSync(at, now, now);
326
+ }
327
+ catch { /* still a hit */ }
328
+ }
329
+ catch {
330
+ complete = false;
331
+ break;
332
+ }
333
+ }
334
+ if (complete)
335
+ return { c, files };
336
+ }
337
+ return null;
338
+ }
339
+ /** Keep a result (its blobs, then the entry's candidates, newest first); a cache that cannot be written is no failure. */
340
+ function cacheStore(key, c, files) {
341
+ try {
342
+ const root = cacheRoot();
343
+ fs.mkdirSync(path.join(root, 'blobs'), { recursive: true });
344
+ for (const f of files) {
345
+ const at = path.join(root, 'blobs', c.files[f.name]);
346
+ if (!fs.existsSync(at))
347
+ writeAtomic(at, f.bytes);
348
+ }
349
+ const same = canonicalText(c.deps) + canonicalText(c.folders);
350
+ const rest = readCandidates(key).filter((x) => canonicalText(x.deps) + canonicalText(x.folders) !== same);
351
+ fs.mkdirSync(path.join(root, key), { recursive: true });
352
+ writeAtomic(path.join(root, key, 'manifest.json'), JSON.stringify({ format: CACHE_FORMAT, candidates: [c, ...rest].slice(0, MAX_CANDIDATES) }) + '\n');
353
+ }
354
+ catch { /* a cache */ }
355
+ }
356
+ /** Keep the cache below its cap: the blobs used longest ago go first. */
357
+ export function cachePrune(maxBytes = CACHE_MAX_BYTES) {
358
+ const dir = path.join(cacheRoot(), 'blobs');
359
+ let entries;
360
+ try {
361
+ entries = fs.readdirSync(dir).map((n) => { const at = path.join(dir, n), s = fs.statSync(at); return { at, size: s.size, t: s.mtimeMs }; });
362
+ }
363
+ catch {
364
+ return;
365
+ }
366
+ let total = entries.reduce((s, e) => s + e.size, 0);
367
+ if (total <= maxBytes)
368
+ return;
369
+ for (const e of entries.sort((a, b) => a.t - b.t)) {
370
+ if (total <= maxBytes)
371
+ break;
372
+ try {
373
+ fs.rmSync(e.at, { force: true });
374
+ total -= e.size;
375
+ }
376
+ catch { /* in use */ }
377
+ }
378
+ }
379
+ // ---------------------------------------------------------------------------------------------------------- report
380
+ /** One progress line: JSON in ASCII (every other character escaped as \uXXXX), so any decoding reads it. */
381
+ export function progressLine(ev) {
382
+ return JSON.stringify(ev).replace(/[\u007f-￿]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, '0')}`);
383
+ }
384
+ const issues = (list) => list.map((e) => ({ node: e.node ?? '', message: e.message, hint: e.hint ?? '' }));
385
+ const issue = (message, hint = '', node = '') => ({ node, message, hint });
386
+ // ------------------------------------------------------------------------------------------------------------ cook
387
+ /**
388
+ * Cook one package into its engine folder (see the top of this file): holding <package>/.topotopo/cook.lock, every
389
+ * output that is not current (or all with `force`) from the cache or cooked anew, its files written where their bytes
390
+ * changed, the record last; the report always (to job.report when given).
391
+ */
392
+ export async function cookPackage(job, flavour, flags = {}) {
393
+ const t0 = performance.now();
394
+ const say = (ev) => flags.progress?.(progressLine(ev));
395
+ const rep = {
396
+ protocol: COOK_PROTOCOL, topotopo: TOPOTOPO_VERSION, ok: false, ms: 0, package: { id: job.id, name: null, dir: slash(job.dir), topo: slash(job.topo) },
397
+ outputs: [], orphans: [], exposed: [], errors: [], warnings: [], record: 'none',
398
+ };
399
+ let release = null;
400
+ let engine = null;
401
+ let timer;
402
+ let started = false;
403
+ try {
404
+ rep.exposed = flavour.exposed(job.dir);
405
+ const lockFile = path.join(job.dir, RECORD_DIR, 'cook.lock');
406
+ release = takeLock(lockFile, {
407
+ pidOnly: true, waitMs: (job.timeout ?? 600) * 1000,
408
+ held: (pid) => `${lockFile} is held by another cook of this package (process ${pid}); it was still running after ${job.timeout ?? 600} s`,
409
+ });
410
+ const m = readManifest(job.dir);
411
+ const pkgName = m.name ?? job.id;
412
+ rep.package.name = m.name ?? null;
413
+ const options = normalOptions(job.options);
414
+ let old = null;
415
+ try {
416
+ old = readRecord(job.dir, flavour.for);
417
+ }
418
+ catch (e) {
419
+ rep.warnings.push(`${e.message}; the package is cooked anew`);
420
+ }
421
+ if (old && (old.schema !== RECORD_SCHEMA || old.for !== flavour.for))
422
+ old = null;
423
+ const listed = packageOutputs(job.dir);
424
+ // If the output list cannot be read reliably, preserve the previous record and files. Otherwise a broken
425
+ // graph could look like deliberately removed outputs and turn the package falsely current.
426
+ if (listed.problems.length)
427
+ throw new Error(listed.problems.join('\n'));
428
+ const notes = [...listed.problems];
429
+ say({ event: 'start', package: slash(job.topo), outputs: listed.outputs.length + listed.invalid.length });
430
+ started = true;
431
+ // leftovers of a cook that was stopped: beside the files the record lists, and in each output's own folder
432
+ for (const f of oldFiles(old))
433
+ fs.rmSync(flavour.absolutePath(f) + PART_SUFFIX, { force: true });
434
+ if (job.options.per_output_folders)
435
+ for (const x of listed.outputs) {
436
+ const dir = flavour.outputDir(normalOptions(job.options), x.id);
437
+ try {
438
+ for (const n of fs.readdirSync(dir))
439
+ if (n.endsWith(PART_SUFFIX))
440
+ fs.rmSync(path.join(dir, n), { force: true });
441
+ }
442
+ catch { /* not there yet */ }
443
+ }
444
+ const shas = new Shas();
445
+ const abs = (rel) => absOf(job.dir, rel);
446
+ const rel = (p) => relOf(job.dir, flavour.project, p);
447
+ const store = copiesFor(job.dir);
448
+ const ws = locate(job.dir).workspace;
449
+ const fixed = [manifestRel(job), ...(fs.existsSync(path.join(store.packages, 'lock.json')) ? [rel(path.join(store.packages, 'lock.json'))] : []), ...(ws ? [rel(path.join(ws, WORKSPACE_FILE))] : [])];
450
+ const listings = new Map();
451
+ const listingOf = (folder) => { let l = listings.get(folder); if (!l) {
452
+ l = listing(abs(folder));
453
+ listings.set(folder, l);
454
+ } return l; };
455
+ // what makes every output cook again: --force, no record, other options, a newer TopoTopo, another graphs/ listing
456
+ const installedNewer = !!old && compareVersions(TOPOTOPO_VERSION, old.topotopo) > 0;
457
+ const all = !!flags.force || !old || !sameOptions(old.options, options) || installedNewer || !sameList(old.folders?.graphs, listingOf('graphs'));
458
+ const depsChanged = (deps) => deps.some((d) => old.sources?.[d] === undefined || shas.of(abs(d)) !== old.sources[d]);
459
+ const foldersChanged = (folders) => folders.some((f) => !sameList(old.folders?.[f], listingOf(f)));
460
+ const filesChanged = (files) => Object.entries(files).some(([f, s]) => rawSha(flavour.absolutePath(f)) !== s);
461
+ const outputs = {}, skipped = {};
462
+ // the files of the outputs of this cook (key → output), and those the old record lists (the guard lets them be replaced)
463
+ const claimed = new Map();
464
+ const known = new Set(oldFiles(old).map((f) => folderKey(flavour.absolutePath(f))));
465
+ let cookedAny = false, timedOut = false;
466
+ const signal = { aborted: false };
467
+ if (job.timeout)
468
+ timer = setTimeout(() => { signal.aborted = true; timedOut = true; void engine?.host.pool?.close(); }, job.timeout * 1000);
469
+ // the engine, made when the first output cooks: the package's graphs and assets, its uses from their copies
470
+ const rec = new Recorder();
471
+ let pk = null;
472
+ const getEngine = async () => {
473
+ if (engine && pk)
474
+ return { e: engine, pk };
475
+ const e = new Engine(recordingHost(createNodeHost({ baseDir: job.dir }), rec));
476
+ if (e.host.pool)
477
+ pools.add(e.host.pool);
478
+ await e.init();
479
+ // no working folder is followed: the copies the package pins
480
+ const uses = new PackageUses(e, job.dir, { start: job.dir });
481
+ e.root.packages = uses.resolver;
482
+ for (const p of loadPackage(e, job.dir))
483
+ if (!notes.includes(p))
484
+ notes.push(p);
485
+ if (uses.error && !notes.includes(uses.error))
486
+ notes.push(uses.error);
487
+ const files = graphFiles(job.dir), graphs = e.root.graphs;
488
+ // a graph_ref's graph is a dep of the output that reads it
489
+ e.root.graphs = (n) => { const f = files.get(n); if (f)
490
+ rec.file(f); return graphs?.(n); };
491
+ engine = e;
492
+ pk = uses;
493
+ return { e, pk: uses };
494
+ };
495
+ const report = (o) => {
496
+ o.ms = Math.round(o.ms);
497
+ rep.outputs.push(o);
498
+ say({ event: 'output', package: slash(job.topo), output: o.id, state: o.state, ms: Math.round(o.ms) });
499
+ };
500
+ const base = (x, kind = '') => ({ id: x.id, label: x.label ?? x.id, kind, default: !!x.default, files: [], written: [], instances: {}, cooked: false, ms: 0, errors: [], warnings: [] });
501
+ // outputs that cannot be published as they are: failed, their last good files kept
502
+ for (const inv of listed.invalid) {
503
+ if (options.skip.includes(inv.id)) {
504
+ skipped[inv.id] = { why: SKIPPED_BY_OPTIONS };
505
+ report({ ...base({ id: inv.id }), state: 'skipped' });
506
+ continue;
507
+ }
508
+ const prev = old?.outputs?.[inv.id];
509
+ const deps = [...new Set([...fixed, ...inv.graphs.map((g) => rel(graphFiles(job.dir).get(g) ?? path.join(job.dir, 'graphs', `${g}.json`)))])].sort(byCode);
510
+ outputs[inv.id] = failedEntry(inv, prev, deps);
511
+ report({ ...base({ id: inv.id, label: prev?.label, default: prev?.default }, prev?.kind ?? ''), state: 'failed', files: Object.keys(prev?.files ?? {}), errors: [issue(inv.message)] });
512
+ }
513
+ for (const x of listed.outputs) {
514
+ const t = performance.now();
515
+ const label = x.label ?? x.id;
516
+ if (options.skip.includes(x.id)) {
517
+ skipped[x.id] = { why: SKIPPED_BY_OPTIONS };
518
+ report({ ...base({ id: x.id, label, default: x.default }, x.kind ?? ''), state: 'skipped' });
519
+ continue;
520
+ }
521
+ const prev = old?.outputs?.[x.id];
522
+ const prevSkip = old?.skipped?.[x.id]?.deps ? old.skipped[x.id] : undefined;
523
+ const same = (p) => p.graph === x.graph && p.node === x.node && (p.default === undefined || p.default === x.default);
524
+ const current = !all && (prev
525
+ ? prev.state === 'ok' && same(prev) && !depsChanged(prev.deps) && !foldersChanged(prev.folders ?? []) && !filesChanged(prev.files)
526
+ : !!prevSkip && same(prevSkip) && !depsChanged(prevSkip.deps) && !foldersChanged(prevSkip.folders ?? []));
527
+ if (current && prev) {
528
+ outputs[x.id] = { ...prev, label, default: x.default };
529
+ for (const f of Object.keys(prev.files))
530
+ claimed.set(folderKey(flavour.absolutePath(f)), x.id);
531
+ report({ ...base({ id: x.id, label, default: x.default }, prev.kind), state: 'unchanged', files: Object.keys(prev.files), instances: prev.instances, warnings: prev.warnings });
532
+ continue;
533
+ }
534
+ if (current && prevSkip) {
535
+ skipped[x.id] = { ...prevSkip, label };
536
+ report({ ...base({ id: x.id, label, default: x.default }, prevSkip.kind ?? ''), state: 'skipped', warnings: [prevSkip.why] });
537
+ continue;
538
+ }
539
+ cookedAny = true;
540
+ const dir = flavour.outputDir(options, x.id);
541
+ const fail = (errors, deps, folders, warnings = []) => {
542
+ outputs[x.id] = { ...failedEntry({ id: x.id, graphs: [x.graph], message: '' }, prev, deps), errors, folders, graph: x.graph, node: x.node, label, default: x.default, warnings };
543
+ for (const f of Object.keys(outputs[x.id].files))
544
+ claimed.set(folderKey(flavour.absolutePath(f)), x.id);
545
+ report({ ...base({ id: x.id, label, default: x.default }, prev?.kind ?? x.kind ?? ''), state: 'failed', files: Object.keys(outputs[x.id].files), errors, warnings, cooked: true, ms: performance.now() - t });
546
+ };
547
+ if (signal.aborted) {
548
+ fail([issue(`the cook timed out after ${job.timeout} s before this output`, 'raise the timeout (cook_timeout in the editor settings, --timeout)')], [rel(x.file), ...fixed].sort(byCode), []);
549
+ continue;
550
+ }
551
+ // 1. the cache: a result whose deps and folders match the package as it is now
552
+ const key = cacheKey(flavour.for, options.instancing, pkgName, x.id);
553
+ const hit = flags.force || flags.noCache ? null : cacheLookup(key, (c) => Object.entries(c.deps).every(([d, s]) => shas.of(abs(d)) === s) && Object.entries(c.folders).every(([f, l]) => sameList(l, listingOf(f))));
554
+ let result = null;
555
+ let state = 'written';
556
+ if (hit) {
557
+ result = { deps: Object.keys(hit.c.deps).sort(byCode), folders: Object.keys(hit.c.folders).sort(byCode), kind: hit.c.kind, instances: hit.c.instances, warnings: hit.c.warnings, files: hit.files };
558
+ state = 'cached';
559
+ }
560
+ else {
561
+ // 2. cook it: every read recorded, from a cold engine cache so that a result shared with another output still reads its files
562
+ const { e, pk: uses } = await getEngine();
563
+ const spec = x.spec;
564
+ e.cache.clear();
565
+ rec.start();
566
+ let cooked = null;
567
+ let errors = [];
568
+ let written = null;
569
+ try {
570
+ const unlocked = uses.locked(spec);
571
+ const invalid = unlocked.length ? [] : e.validate(spec, '', { ...e.root, packages: uses.resolver }).errors;
572
+ if (unlocked.length)
573
+ errors = unlocked.map((u) => issue(u.replace(/ \(a cook without --locked adds it\)$/, ''), 'a cook for an engine changes nothing of the package: add the package it names, or restore the copy, then cook again'));
574
+ else if (invalid.length)
575
+ errors = issues(invalid);
576
+ else {
577
+ const r = await e.cook(spec, { target: x.node, frame: 1, signal });
578
+ if (signal.aborted || r.stopped)
579
+ errors = [issue(`the cook timed out after ${job.timeout} s`, 'raise the timeout (cook_timeout in the editor settings, --timeout)', r.stopped ?? '')];
580
+ else if (!r.ok || !r.geo)
581
+ errors = r.errors.length ? issues(r.errors) : [issue('it cooks to no geometry')];
582
+ else {
583
+ const info = outputKind(r.geo), kind = publishedKind(info);
584
+ const warnings = r.warnings.map((w) => `[${w.node}] ${w.message}`);
585
+ const pinned = x.kind ? kindMismatch(x.kind, info) : null;
586
+ if (pinned)
587
+ warnings.push(pinned);
588
+ if (!kind)
589
+ errors = [issue('it cooks to nothing: no polygons, curves, points, instances, heightfields, images, materials or volumes')];
590
+ else {
591
+ cooked = { geo: r.geo, kind, warnings };
592
+ if (!flavour.skipKind(kind)) {
593
+ written = await flavour.write(r.geo, { id: x.id, output: x, kind, options, packageName: pkgName, packages: packagesUsed(e, spec, e.root), host: e.host });
594
+ }
595
+ }
596
+ }
597
+ }
598
+ }
599
+ catch (err) {
600
+ errors = [issue(String(err?.message ?? err))];
601
+ }
602
+ finally {
603
+ rec.stop();
604
+ }
605
+ const deps = depsOf(x, spec, e, uses, shas, rec);
606
+ const folders = [...rec.dirs.values()].map(rel).filter((f) => !isUrl(f)).sort(byCode);
607
+ for (const u of rec.urls)
608
+ if (!notes.includes(`${x.id} reads ${u}: a URL's changes are not tracked (put the file in inputs/)`))
609
+ notes.push(`${x.id} reads ${u}: a URL's changes are not tracked (put the file in inputs/)`);
610
+ for (const d of deps)
611
+ if (path.isAbsolute(d) || /^[A-Za-z]:\//.test(d)) {
612
+ const said = `${x.id} reads ${d}, outside the engine project: a checkout elsewhere does not have it (put the file in inputs/)`;
613
+ if (!notes.includes(said))
614
+ notes.push(said);
615
+ }
616
+ if (errors.length || !cooked) {
617
+ fail(errors, deps, folders);
618
+ continue;
619
+ }
620
+ const why = flavour.skipKind(cooked.kind);
621
+ const instances = instanceCounts(cooked.geo);
622
+ if (why) {
623
+ skipped[x.id] = { why, kind: cooked.kind, graph: x.graph, node: x.node, label, deps, folders };
624
+ cacheStore(key, candidate(deps, folders, cooked.kind, instances, cooked.warnings, [], shas, abs, listingOf), []);
625
+ report({ ...base({ id: x.id, label, default: x.default }, cooked.kind), state: 'skipped', warnings: [why, ...cooked.warnings], cooked: true, ms: performance.now() - t });
626
+ continue;
627
+ }
628
+ result = { deps, folders, kind: cooked.kind, instances, warnings: [...cooked.warnings, ...written.warnings], files: written.files };
629
+ cacheStore(key, candidate(deps, folders, cooked.kind, instances, result.warnings, result.files, shas, abs, listingOf), result.files);
630
+ }
631
+ if (flavour.skipKind(result.kind)) {
632
+ const why = flavour.skipKind(result.kind);
633
+ skipped[x.id] = { why, kind: result.kind, graph: x.graph, node: x.node, label, deps: result.deps, folders: result.folders };
634
+ report({ ...base({ id: x.id, label, default: x.default }, result.kind), state: 'skipped', warnings: [why, ...result.warnings], cooked: true, ms: performance.now() - t });
635
+ continue;
636
+ }
637
+ // 3. the writing rules: no clash with another output, no foreign file, only changed bytes
638
+ const placed = place(result.files, dir, { id: x.id, claimed, known, pkgName, adopt: !!job.adopt, flavour });
639
+ if ('error' in placed) {
640
+ fail([placed.error], result.deps, result.folders, result.warnings);
641
+ continue;
642
+ }
643
+ outputs[x.id] = {
644
+ default: x.default, deps: result.deps, errors: [], files: placed.files, folders: result.folders, graph: x.graph, instances: result.instances,
645
+ kind: result.kind, label, node: x.node, state: 'ok', warnings: result.warnings,
646
+ };
647
+ report({
648
+ ...base({ id: x.id, label, default: x.default }, result.kind), state: state === 'cached' ? 'cached' : placed.written.length ? 'written' : 'unchanged',
649
+ files: Object.keys(placed.files), written: placed.written, instances: result.instances, warnings: result.warnings, cooked: true, ms: performance.now() - t,
650
+ });
651
+ }
652
+ if (timedOut)
653
+ rep.errors.push(`the cook timed out after ${job.timeout} s`);
654
+ // orphans: files an output had and has no more (an output no longer published, another folder), kept until removed
655
+ const orphans = {};
656
+ const now = new Set();
657
+ for (const o of Object.values(outputs))
658
+ for (const f of Object.keys(o.files))
659
+ now.add(folderKey(flavour.absolutePath(f)));
660
+ const was = [...Object.entries(old?.orphans ?? {}), ...Object.entries(old?.outputs ?? {}).flatMap(([id, o]) => Object.keys(o.files ?? {}).map((f) => [f, id]))];
661
+ for (const [f, id] of was)
662
+ if (!now.has(folderKey(flavour.absolutePath(f))) && fs.existsSync(flavour.absolutePath(f)))
663
+ orphans[f] = id;
664
+ rep.orphans = Object.keys(orphans).sort(byCode);
665
+ // the record, last: its sources (the deps of every output), the listings, the notes
666
+ const sources = {};
667
+ const allDeps = [...Object.values(outputs).flatMap((o) => o.deps), ...Object.values(skipped).flatMap((s) => s.deps ?? [])];
668
+ for (const d of allDeps) {
669
+ const s = shas.of(abs(d));
670
+ if (s !== null)
671
+ sources[d] = s;
672
+ }
673
+ const folders = {};
674
+ for (const f of [...LISTED_FOLDERS, ...Object.values(outputs).flatMap((o) => o.folders), ...Object.values(skipped).flatMap((s) => s.folders ?? [])])
675
+ folders[f] = listingOf(f);
676
+ const record = {
677
+ folders, for: flavour.for, name: m.name ?? null, notes: [...new Set(notes)], options, orphans, outputs, package: job.id, schema: RECORD_SCHEMA, skipped, sources,
678
+ topotopo: cookedAny || !old ? TOPOTOPO_VERSION : old.topotopo,
679
+ };
680
+ const text = canonicalText(record), file = recordFile(job.dir, flavour.for);
681
+ let have = '';
682
+ try {
683
+ have = fs.readFileSync(file, 'utf8');
684
+ }
685
+ catch { /* new */ }
686
+ if (have !== text) {
687
+ fs.mkdirSync(path.dirname(file), { recursive: true });
688
+ writeAtomic(file, text);
689
+ rep.record = 'written';
690
+ }
691
+ else
692
+ rep.record = 'unchanged';
693
+ rep.warnings.push(...notes);
694
+ if (old && compareVersions(TOPOTOPO_VERSION, old.topotopo) < 0 && !cookedAny)
695
+ rep.warnings.push(`cooked elsewhere with TopoTopo ${old.topotopo}, newer than this one (${TOPOTOPO_VERSION}): update TopoTopo`);
696
+ }
697
+ catch (e) {
698
+ rep.errors.push(String(e?.message ?? e));
699
+ }
700
+ finally {
701
+ if (timer)
702
+ clearTimeout(timer);
703
+ release?.();
704
+ rep.ok = !rep.errors.length && rep.outputs.every((o) => o.state !== 'failed');
705
+ rep.ms = Math.round(performance.now() - t0);
706
+ if (!started)
707
+ say({ event: 'start', package: slash(job.topo), outputs: 0 });
708
+ if (job.report) {
709
+ try {
710
+ fs.mkdirSync(path.dirname(job.report), { recursive: true });
711
+ writeAtomic(job.report, JSON.stringify(rep, null, 2) + '\n');
712
+ }
713
+ catch (e) {
714
+ rep.errors.push(`the report ${job.report} could not be written: ${e.message}`);
715
+ rep.ok = false;
716
+ }
717
+ }
718
+ say({ event: 'done', package: slash(job.topo), ok: rep.ok, report: job.report ? slash(job.report) : '' });
719
+ }
720
+ return rep;
721
+ /** The files an output read, as the record names them: its reads, its graph, the package's assets, manifest, lock and workspace file, the version records of the copies it uses. */
722
+ function depsOf(x, spec, e, uses, shas, rec) {
723
+ const rel = (p) => relOf(job.dir, flavour.project, p);
724
+ const set = new Set([rel(x.file), manifestRel(job), ...listing(path.join(job.dir, 'assets')).map((f) => `assets/${f}`)]);
725
+ const store = copiesFor(job.dir);
726
+ if (fs.existsSync(path.join(store.packages, 'lock.json')))
727
+ set.add(rel(path.join(store.packages, 'lock.json')));
728
+ const ws = locate(job.dir).workspace;
729
+ if (ws)
730
+ set.add(rel(path.join(ws, WORKSPACE_FILE)));
731
+ for (const { abs, sha } of rec.files.values()) {
732
+ if (OWN.some((d) => within(abs, d)) && !within(abs, job.dir))
733
+ continue;
734
+ if (sha)
735
+ shas.seen(abs, sha);
736
+ set.add(rel(abs));
737
+ }
738
+ let used = {};
739
+ try {
740
+ used = packagesUsed(e, spec, e.root);
741
+ }
742
+ catch { /* said by the cook */ }
743
+ const self = uses.manifest?.name;
744
+ for (const k of Object.keys(used)) {
745
+ const at = k.lastIndexOf('@'), pkg = k.slice(0, at), v = k.slice(at + 1);
746
+ if (v === 'working')
747
+ continue;
748
+ set.add(rel(path.join(store.packages, ...pkg.split('/'), v, 'version.json')));
749
+ }
750
+ // a graph that names the package's own outputs reads its other graphs
751
+ if (self && (packagesNamedIn(spec).includes(self) || Object.keys(used).includes(`${self}@working`)))
752
+ for (const f of graphFiles(job.dir).values())
753
+ set.add(rel(f));
754
+ return [...set].filter((d) => fs.existsSync(absOf(job.dir, d))).sort(byCode);
755
+ }
756
+ }
757
+ /** The manifest's path in the record. */
758
+ const manifestRel = (job) => path.basename(job.topo);
759
+ /** Every output file a record lists (outputs and orphans). */
760
+ function oldFiles(old) {
761
+ if (!old)
762
+ return [];
763
+ return [...Object.keys(old.orphans ?? {}), ...Object.values(old.outputs ?? {}).flatMap((o) => Object.keys(o.files ?? {}))];
764
+ }
765
+ /** A failed output's record: its last good files and what it was, the error. */
766
+ function failedEntry(inv, prev, deps) {
767
+ return {
768
+ default: prev?.default ?? false, deps, errors: inv.message ? [issue(inv.message)] : [], files: prev?.files ?? {}, folders: [], graph: inv.graphs[0] ?? '',
769
+ instances: prev?.instances ?? {}, kind: prev?.kind ?? '', label: prev?.label ?? inv.id, node: prev?.node ?? '', state: 'failed', warnings: [],
770
+ };
771
+ }
772
+ /** A cache candidate of a result: its deps with their hashes now, its folders' listings, its files' blobs. */
773
+ function candidate(deps, folders, kind, instances, warnings, files, shas, abs, listingOf) {
774
+ return {
775
+ deps: Object.fromEntries(deps.map((d) => [d, shas.of(abs(d)) ?? ''])), folders: Object.fromEntries(folders.map((f) => [f, listingOf(f)])),
776
+ files: Object.fromEntries(files.map((f) => [f.name, sha256(f.bytes)])), kind, instances, warnings,
777
+ };
778
+ }
779
+ /** Packed instances per source name (the GLB's node names). */
780
+ function instanceCounts(g) {
781
+ if (!g.hasPacked())
782
+ return {};
783
+ const names = packedSourceNames(g), out = {};
784
+ const kind = g.primKind, src = g.packedSource;
785
+ for (let p = 0; p < kind.length; p++)
786
+ if (kind[p] === 1) {
787
+ const n = names[src[p]] ?? `source_${src[p]}`;
788
+ out[n] = (out[n] ?? 0) + 1;
789
+ }
790
+ return Object.fromEntries(Object.entries(out).sort(([a], [b]) => byCode(a, b)));
791
+ }
792
+ /**
793
+ * The writing rules for one output's files in `dir`: none at a path another output of this cook writes; an existing
794
+ * file is replaced only when the old record lists it, its source block names this package, or with `adopt`; a file
795
+ * is written (through <file>.topotopo-part, moved into place) only when its bytes differ. All or nothing: a refused
796
+ * file writes none of the output's.
797
+ */
798
+ function place(files, dir, o) {
799
+ const targets = files.map((f) => ({ abs: path.join(dir, ...f.name.split('/')), bytes: f.bytes }));
800
+ for (const t of targets) {
801
+ const k = folderKey(t.abs), other = o.claimed.get(k);
802
+ if (other && other !== o.id)
803
+ return { error: issue(`${o.flavour.recordPath(t.abs)} is also an output file of "${other}"`, 'two outputs cannot write one file: per-output folders (outputs/per_output_folders), or rename one output or its images') };
804
+ }
805
+ for (const t of targets) {
806
+ if (!fs.existsSync(t.abs) || o.adopt || o.known.has(folderKey(t.abs)))
807
+ continue;
808
+ if (o.flavour.ownerOf(t.abs) === o.pkgName)
809
+ continue;
810
+ return { error: issue(`${o.flavour.recordPath(t.abs)} is there already and was not cooked from this package`, 'cook into another folder (outputs/folder, --into), or take the file over once with --adopt (its import settings are kept)') };
811
+ }
812
+ const out = {}, written = [];
813
+ for (const t of targets) {
814
+ o.claimed.set(folderKey(t.abs), o.id);
815
+ const r = o.flavour.recordPath(t.abs);
816
+ out[r] = sha256(t.bytes);
817
+ let same = false;
818
+ try {
819
+ same = Buffer.from(fs.readFileSync(t.abs)).equals(Buffer.from(t.bytes.buffer, t.bytes.byteOffset, t.bytes.byteLength));
820
+ }
821
+ catch { /* new */ }
822
+ if (same)
823
+ continue;
824
+ fs.mkdirSync(path.dirname(t.abs), { recursive: true });
825
+ const part = t.abs + PART_SUFFIX;
826
+ try {
827
+ fs.writeFileSync(part, t.bytes);
828
+ renameInto(part, t.abs);
829
+ }
830
+ catch (e) {
831
+ fs.rmSync(part, { force: true });
832
+ return { error: issue(`${r} could not be written: ${e.message}`) };
833
+ }
834
+ written.push(r);
835
+ }
836
+ return { files: Object.fromEntries(Object.entries(out).sort(([a], [b]) => byCode(a, b))), written: written.sort(byCode) };
837
+ }
838
+ /** The worker pools of the engines the cooks made (the process's shared one): closed when a command ends. */
839
+ const pools = new Set();
840
+ export async function closeCookPools() {
841
+ for (const p of pools)
842
+ await p.close();
843
+ pools.clear();
844
+ }