@wildshard/sdk 0.0.0 → 0.2.3

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 (687) hide show
  1. package/GUIDE.md +790 -0
  2. package/README.md +14 -4
  3. package/bin/wildshard.mjs +38 -0
  4. package/lint/declaration-config.d.mts +2 -0
  5. package/lint/declaration-config.mjs +19 -0
  6. package/lint/engine-plugin.d.mts +2 -0
  7. package/lint/engine-plugin.mjs +40 -0
  8. package/lint/host-callbacks.d.mts +6 -0
  9. package/lint/host-callbacks.mjs +123 -0
  10. package/lint/host-files.d.mts +1 -0
  11. package/lint/host-files.mjs +7 -0
  12. package/lint/layer-exports.d.mts +2 -0
  13. package/lint/layer-exports.mjs +21 -0
  14. package/lint/legacy-line-basis.json +995 -0
  15. package/lint/nine-tiling-baseline.json +35 -0
  16. package/lint/ratchet.json +11 -0
  17. package/lint/runtime-files.d.mts +12 -0
  18. package/lint/runtime-files.json +16 -0
  19. package/lint/runtime-files.mjs +69 -0
  20. package/lint/runtime-performance.d.mts +6 -0
  21. package/lint/runtime-performance.mjs +184 -0
  22. package/lint/sdk-plugin.d.mts +4 -0
  23. package/lint/sdk-plugin.mjs +134 -0
  24. package/lint/shardfile-boundaries.d.mts +10 -0
  25. package/lint/shardfile-boundaries.mjs +122 -0
  26. package/lint/tile-bake-debt.json +556 -0
  27. package/package.json +371 -4
  28. package/scripts/agent-parity.mjs +1524 -0
  29. package/scripts/agent-sync.mjs +518 -0
  30. package/scripts/apfs-clone.mjs +67 -0
  31. package/scripts/assert-store-layout.mjs +23 -0
  32. package/scripts/astc6-phone-cap.d.mts +3 -0
  33. package/scripts/astc6-phone-cap.mjs +137 -0
  34. package/scripts/audit-assets.d.mts +10 -0
  35. package/scripts/audit-assets.mjs +151 -0
  36. package/scripts/bake/coatFiles.d.mts +6 -0
  37. package/scripts/bake/coatFiles.mjs +37 -0
  38. package/scripts/bake/environment.d.mts +2 -0
  39. package/scripts/bake/environment.mjs +58 -0
  40. package/scripts/bake/far-proxies.mjs +45 -0
  41. package/scripts/bake/keyed-sky.d.mts +4 -0
  42. package/scripts/bake/keyed-sky.mjs +34 -0
  43. package/scripts/bake/movers.mjs +56 -0
  44. package/scripts/bake/nativeWorld.d.mts +6 -0
  45. package/scripts/bake/nativeWorld.mjs +43 -0
  46. package/scripts/bake/navmeshGround.ts +22 -0
  47. package/scripts/bake/near-placeholder.mjs +331 -0
  48. package/scripts/bake/placeholderShards.mjs +41 -0
  49. package/scripts/bake/skins.mjs +15 -0
  50. package/scripts/bake/template-skins.mjs +33 -0
  51. package/scripts/bake/viewmodelBytes.ts +26 -0
  52. package/scripts/bake/viewmodelPage.ts +11 -0
  53. package/scripts/bake/worldHost.d.mts +35 -0
  54. package/scripts/bake/worldHost.mjs +110 -0
  55. package/scripts/bake-astc6.cache.json +80 -0
  56. package/scripts/bake-astc6.far-reach.cache.json +23 -0
  57. package/scripts/bake-astc6.list.json +111 -0
  58. package/scripts/bake-astc6.mjs +279 -0
  59. package/scripts/bake-astc6.nalati-grasslands.cache.json +42 -0
  60. package/scripts/bake-catalogue.mjs +44 -0
  61. package/scripts/bake-check.mjs +54 -0
  62. package/scripts/bake-chunk.mjs +124 -0
  63. package/scripts/bake-cloud-field.mjs +24 -0
  64. package/scripts/bake-coats.mjs +110 -0
  65. package/scripts/bake-data-maps.d.mts +24 -0
  66. package/scripts/bake-data-maps.mjs +72 -0
  67. package/scripts/bake-entry-programs.mjs +117 -0
  68. package/scripts/bake-geometry.mjs +106 -0
  69. package/scripts/bake-hybrid-tiles.mjs +28 -0
  70. package/scripts/bake-ktx2.cache.json +276 -0
  71. package/scripts/bake-ktx2.list.json +365 -0
  72. package/scripts/bake-ktx2.mjs +477 -0
  73. package/scripts/bake-map-glb.mjs +127 -0
  74. package/scripts/bake-map-rest.d.mts +7 -0
  75. package/scripts/bake-map-rest.mjs +50 -0
  76. package/scripts/bake-maps.mjs +200 -0
  77. package/scripts/bake-navmesh.mjs +259 -0
  78. package/scripts/bake-packs.mjs +129 -0
  79. package/scripts/bake-pickups.mjs +102 -0
  80. package/scripts/bake-query-terrain.mjs +64 -0
  81. package/scripts/bake-recurve-pool.mjs +16 -0
  82. package/scripts/bake-section-schemas.d.mts +3 -0
  83. package/scripts/bake-template-shardfile.mjs +32 -0
  84. package/scripts/bake-textures.mjs +80 -0
  85. package/scripts/bake-viewmodel-sets.json +45 -0
  86. package/scripts/bake-viewmodel-sets.mjs +137 -0
  87. package/scripts/bake-voxel-ao.mjs +119 -0
  88. package/scripts/bake-water-ripples.mjs +25 -0
  89. package/scripts/blender/README.md +129 -0
  90. package/scripts/blender/build.sh +166 -0
  91. package/scripts/blender/lib/export-scene.mjs +129 -0
  92. package/scripts/blender/lib/glb-digest.mjs +188 -0
  93. package/scripts/blender/lib/glb.py +68 -0
  94. package/scripts/blender/lib/save_blend.py +17 -0
  95. package/scripts/blender/lib/world_fixture.py +55 -0
  96. package/scripts/blender/targets.json +591 -0
  97. package/scripts/build-sdk.mjs +95 -0
  98. package/scripts/build-shardfiles.d.mts +7 -0
  99. package/scripts/build-shardfiles.mjs +206 -0
  100. package/scripts/capture-hero.mjs +137 -0
  101. package/scripts/check-lift-review.mjs +23 -0
  102. package/scripts/chromium-keychain-check.mjs +139 -0
  103. package/scripts/chromium-keychain.d.mts +1 -0
  104. package/scripts/chromium-keychain.mjs +5 -0
  105. package/scripts/compile-script.d.mts +3 -0
  106. package/scripts/compile-script.mjs +8 -0
  107. package/scripts/creature-color.mjs +255 -0
  108. package/scripts/decide/calibrate.py +127 -0
  109. package/scripts/decide/calibration/2026-10-03/labels-s1.tsv +281 -0
  110. package/scripts/decide/calibration/2026-10-03/labels-s2.tsv +97 -0
  111. package/scripts/decide/calibration/2026-10-03/labels-s3.tsv +48 -0
  112. package/scripts/decide/calibration/2026-10-03/labels-s3b.tsv +26 -0
  113. package/scripts/decide/calibration/2026-10-03/res-capture-status-v1.jsonl +376 -0
  114. package/scripts/decide/calibration/2026-10-03/res-text-garbled-strings.jsonl +48 -0
  115. package/scripts/decide/calibration/2026-10-03/res-text-garbled-v1.jsonl +73 -0
  116. package/scripts/decide/decide.py +262 -0
  117. package/scripts/decide/decide.sh +50 -0
  118. package/scripts/decide/layer-purity-pilot.mjs +41 -0
  119. package/scripts/decide/sets/capture-status.json +46 -0
  120. package/scripts/decide/sets/layer-purity.json +28 -0
  121. package/scripts/decide/sets/text-garbled.json +17 -0
  122. package/scripts/decide/test_decide.py +37 -0
  123. package/scripts/docs.mjs +15 -0
  124. package/scripts/entry-reads/crawl.ts +152 -0
  125. package/scripts/entry-reads/tsconfig.json +25 -0
  126. package/scripts/gen-format-schema.d.mts +2 -0
  127. package/scripts/gen-format-schema.mjs +21 -0
  128. package/scripts/gen-host-catalogue.d.mts +14 -0
  129. package/scripts/gen-host-catalogue.mjs +108 -0
  130. package/scripts/gen-shard-layout-doc.d.mts +4 -0
  131. package/scripts/gen-shard-layout-doc.mjs +55 -0
  132. package/scripts/gen-shards.d.mts +17 -0
  133. package/scripts/gen-shards.mjs +311 -0
  134. package/scripts/goldens/capture-inputs.d.mts +4 -0
  135. package/scripts/goldens/capture-inputs.mjs +34 -0
  136. package/scripts/goldens/colour_shift.py +27 -0
  137. package/scripts/goldens/native-residency.d.mts +10 -0
  138. package/scripts/goldens/native-residency.mjs +104 -0
  139. package/scripts/goldens/plot-inputs.d.mts +12 -0
  140. package/scripts/goldens/plot-inputs.mjs +46 -0
  141. package/scripts/gpu-texmem.mjs +98 -0
  142. package/scripts/horizon-matte/config.py +24 -0
  143. package/scripts/horizon-matte/encode.py +91 -0
  144. package/scripts/horizon-matte/key.py +141 -0
  145. package/scripts/horizon-matte/mkjobs.py +33 -0
  146. package/scripts/horizon-matte/mkjobs_day2.py +11 -0
  147. package/scripts/horizon-matte/overlap.py +80 -0
  148. package/scripts/horizon-matte/run_codex.py +57 -0
  149. package/scripts/horizon-matte/stitch.py +133 -0
  150. package/scripts/img2mesh/CC0.md +105 -0
  151. package/scripts/img2mesh/README.md +209 -0
  152. package/scripts/img2mesh/ab_board.py +102 -0
  153. package/scripts/img2mesh/birds/birds.json +255 -0
  154. package/scripts/img2mesh/birds/birds_atlas.py +150 -0
  155. package/scripts/img2mesh/birds/birds_fix_preview.mjs +103 -0
  156. package/scripts/img2mesh/birds/birds_fix_render.py +75 -0
  157. package/scripts/img2mesh/birds/birds_pack.py +110 -0
  158. package/scripts/img2mesh/birds/birds_phone_b.py +112 -0
  159. package/scripts/img2mesh/birds/birds_post.py +550 -0
  160. package/scripts/img2mesh/birds/birds_render.py +125 -0
  161. package/scripts/img2mesh/birds/birds_sheet.py +33 -0
  162. package/scripts/img2mesh/birds/birds_view.py +60 -0
  163. package/scripts/img2mesh/board.py +100 -0
  164. package/scripts/img2mesh/build_cc0.sh +52 -0
  165. package/scripts/img2mesh/build_driftwood.sh +12 -0
  166. package/scripts/img2mesh/build_faces.sh +53 -0
  167. package/scripts/img2mesh/build_props.py +81 -0
  168. package/scripts/img2mesh/cc0_export.py +186 -0
  169. package/scripts/img2mesh/driftwood_post.py +571 -0
  170. package/scripts/img2mesh/e304_faces.sh +67 -0
  171. package/scripts/img2mesh/face_remaster.py +911 -0
  172. package/scripts/img2mesh/face_views.py +95 -0
  173. package/scripts/img2mesh/faces-e304.json +9 -0
  174. package/scripts/img2mesh/faces.json +30 -0
  175. package/scripts/img2mesh/head_cut.py +100 -0
  176. package/scripts/img2mesh/hi3d_paint.py +94 -0
  177. package/scripts/img2mesh/hi3d_refine.py +161 -0
  178. package/scripts/img2mesh/hunyuan_cpu_rasterizer.sh +42 -0
  179. package/scripts/img2mesh/pine_hollow_phone.sh +13 -0
  180. package/scripts/img2mesh/props/coral-arch.json +32 -0
  181. package/scripts/img2mesh/props/ember-furnace.json +30 -0
  182. package/scripts/img2mesh/props/night-market-gate.json +10 -0
  183. package/scripts/img2mesh/render_still.py +86 -0
  184. package/scripts/img2mesh/rig_strip.mjs +46 -0
  185. package/scripts/img2mesh/rig_transfer.mjs +104 -0
  186. package/scripts/img2mesh/split_sheet.py +48 -0
  187. package/scripts/img2mesh/trellis_batch.py +110 -0
  188. package/scripts/img2mesh/versus_board.py +114 -0
  189. package/scripts/import-bundle.d.mts +2 -0
  190. package/scripts/import-bundle.mjs +20 -0
  191. package/scripts/ktx2-ab-board.py +133 -0
  192. package/scripts/ktx2-ab.mjs +111 -0
  193. package/scripts/ktx2-settings.mjs +18 -0
  194. package/scripts/land.d.mts +14 -0
  195. package/scripts/land.mjs +809 -0
  196. package/scripts/lint-dispatch.mjs +14 -0
  197. package/scripts/map-bake-frames.d.mts +4 -0
  198. package/scripts/map-bake-frames.mjs +23 -0
  199. package/scripts/map-geometry.d.mts +9 -0
  200. package/scripts/map-geometry.mjs +29 -0
  201. package/scripts/map-world.mjs +162 -0
  202. package/scripts/mockup-local.sh +46 -0
  203. package/scripts/music/export-midi.mjs +68 -0
  204. package/scripts/music/gen/analyze.py +308 -0
  205. package/scripts/music/gen/audio_jobs.py +46 -0
  206. package/scripts/music/gen/briefs.json +51 -0
  207. package/scripts/music/gen/build_page.py +334 -0
  208. package/scripts/music/gen/folk.json +3187 -0
  209. package/scripts/music/gen/gen_ace_step.py +156 -0
  210. package/scripts/music/gen/gen_heartmula.py +187 -0
  211. package/scripts/music/gen/gen_minimax.py +143 -0
  212. package/scripts/music/gen/gen_sao.py +122 -0
  213. package/scripts/music/gen/gen_sao_small.py +104 -0
  214. package/scripts/music/gen/gen_sfx.py +98 -0
  215. package/scripts/music/gen/gen_sfx_ezaudio.py +112 -0
  216. package/scripts/music/gen/gen_sfx_moss.py +112 -0
  217. package/scripts/music/gen/models.json +61 -0
  218. package/scripts/music/gen/nalati-jobs.json +104 -0
  219. package/scripts/music/gen/nalati-score-build.json +119 -0
  220. package/scripts/music/gen/nalati-score.json +3448 -0
  221. package/scripts/music/gen/ob7-fit-decisions.json +38 -0
  222. package/scripts/music/gen/ob7-score-jobs.json +152 -0
  223. package/scripts/music/gen/ob7-sfx-jobs.json +897 -0
  224. package/scripts/music/gen/ob7_build.py +469 -0
  225. package/scripts/music/gen/ob7_generate.py +67 -0
  226. package/scripts/music/gen/ob7_run.sh +42 -0
  227. package/scripts/music/gen/orchestral.json +3187 -0
  228. package/scripts/music/gen/own_score.py +486 -0
  229. package/scripts/music/gen/ph-jobs.json +27 -0
  230. package/scripts/music/gen/ph_page.py +222 -0
  231. package/scripts/music/gen/piano.json +3175 -0
  232. package/scripts/music/gen/rank_v3.py +248 -0
  233. package/scripts/music/gen/sfx-best.json +2486 -0
  234. package/scripts/music/gen/sfx-ezaudio.json +4082 -0
  235. package/scripts/music/gen/sfx-jobs.json +57 -0
  236. package/scripts/music/gen/sfx-minimax-jobs.json +16 -0
  237. package/scripts/music/gen/sfx-minimax.json +289 -0
  238. package/scripts/music/gen/sfx-moss.json +4082 -0
  239. package/scripts/music/gen/sfx-nalati-b3-jobs.json +17 -0
  240. package/scripts/music/gen/sfx-nalati-jobs.json +338 -0
  241. package/scripts/music/gen/sfx-nalati.json +11202 -0
  242. package/scripts/music/gen/sfx-nd-jobs.json +57 -0
  243. package/scripts/music/gen/sfx-nd-moss.json +2097 -0
  244. package/scripts/music/gen/sfx-nd-sa3-medium.json +2097 -0
  245. package/scripts/music/gen/sfx-nd-summary.json +38 -0
  246. package/scripts/music/gen/sfx-peaks.json +7 -0
  247. package/scripts/music/gen/sfx-ph-jobs.json +169 -0
  248. package/scripts/music/gen/sfx-ph-moss.json +6564 -0
  249. package/scripts/music/gen/sfx-ph-sa3-medium.json +7239 -0
  250. package/scripts/music/gen/sfx-ph-summary.json +63 -0
  251. package/scripts/music/gen/sfx-sa3-medium.json +4082 -0
  252. package/scripts/music/gen/sfx-sa3.json +4082 -0
  253. package/scripts/music/gen/sfx-summary.json +107 -0
  254. package/scripts/music/gen/sfx_build.py +332 -0
  255. package/scripts/music/gen/sfx_merge.py +255 -0
  256. package/scripts/music/gen/sfx_minimax.py +61 -0
  257. package/scripts/music/gen/sfx_nalati.py +331 -0
  258. package/scripts/music/gen/sfx_sprite.py +424 -0
  259. package/scripts/music/gen/stems.py +539 -0
  260. package/scripts/music/gen/test_loop_meter.py +29 -0
  261. package/scripts/music/gen/test_ob7_provenance.py +77 -0
  262. package/scripts/music/gen/v3-folk-build.json +148 -0
  263. package/scripts/music/gen/v3-folk.json +1818 -0
  264. package/scripts/music/gen/v3-jobs.json +145 -0
  265. package/scripts/music/gen/v3-orchestral-build.json +148 -0
  266. package/scripts/music/gen/v3-orchestral.json +1813 -0
  267. package/scripts/music/gen/v3-ph-folk-build.json +94 -0
  268. package/scripts/music/gen/v3-ph-folk.json +1806 -0
  269. package/scripts/music/gen/v3-ph-orchestral-build.json +94 -0
  270. package/scripts/music/gen/v3-ph-orchestral.json +1824 -0
  271. package/scripts/music/gen/v3-ph-piano-build.json +94 -0
  272. package/scripts/music/gen/v3-ph-piano.json +1818 -0
  273. package/scripts/music/gen/v3-piano-build.json +148 -0
  274. package/scripts/music/gen/v3-piano.json +1813 -0
  275. package/scripts/music/wildshard-theme.mid +0 -0
  276. package/scripts/music/wildshard-trailer30.mid +0 -0
  277. package/scripts/named-blob-output.d.mts +8 -0
  278. package/scripts/named-blob-output.mjs +48 -0
  279. package/scripts/pack-all.mjs +15 -0
  280. package/scripts/pid-lock.d.mts +1 -0
  281. package/scripts/pid-lock.mjs +63 -0
  282. package/scripts/practice/bake_dummy.py +53 -0
  283. package/scripts/practice/build_dummies.sh +43 -0
  284. package/scripts/practice/dummy_parts.py +568 -0
  285. package/scripts/practice/dummy_rig_gate.py +139 -0
  286. package/scripts/practice/gate_sheet.py +36 -0
  287. package/scripts/practice/generate_dummy_unimate.py +132 -0
  288. package/scripts/practice/pack_dummy.mjs +59 -0
  289. package/scripts/practice/repair_dummy_weights.mjs +68 -0
  290. package/scripts/practice/rig_dummy.py +828 -0
  291. package/scripts/practice/verify_unimate_skin.mjs +356 -0
  292. package/scripts/preparation-seed.mjs +15 -0
  293. package/scripts/prepare-basis-tool.mjs +6 -0
  294. package/scripts/prepare-product.d.mts +14 -0
  295. package/scripts/prepare-product.mjs +101 -0
  296. package/scripts/product-build-tools.d.mts +3 -0
  297. package/scripts/product-build-tools.json +3 -0
  298. package/scripts/product-build-tools.mjs +31 -0
  299. package/scripts/publish-public.mjs +7 -0
  300. package/scripts/push-tables.d.mts +1 -0
  301. package/scripts/push-tables.mjs +28 -0
  302. package/scripts/record-shard-mounts.mjs +133 -0
  303. package/scripts/sdk-externals.d.mts +2 -0
  304. package/scripts/sdk-externals.mjs +2 -0
  305. package/scripts/section-inventory.ts +209 -0
  306. package/scripts/select-candidate.mjs +15 -0
  307. package/scripts/shard-build-pool.d.mts +4 -0
  308. package/scripts/shard-build-pool.mjs +53 -0
  309. package/scripts/shard-line-baseline.json +17 -0
  310. package/scripts/shard-milestones.d.mts +15 -0
  311. package/scripts/shard-milestones.mjs +105 -0
  312. package/scripts/shard-output-report.d.mts +9 -0
  313. package/scripts/shard-output-report.mjs +85 -0
  314. package/scripts/shard-platform-cli.mjs +93 -0
  315. package/scripts/shard-progress.mjs +212 -0
  316. package/scripts/shard-timelapse.py +102 -0
  317. package/scripts/shardfile-cold-boot.mjs +79 -0
  318. package/scripts/shardfile-vite.d.mts +4 -0
  319. package/scripts/shardfile-vite.mjs +20 -0
  320. package/scripts/simplify-models.mjs +24 -0
  321. package/scripts/site-facts.mjs +88 -0
  322. package/scripts/test-template-gate.mjs +44 -0
  323. package/scripts/test_golden_compare.py +68 -0
  324. package/scripts/tex-tiers.cache.json +181 -0
  325. package/scripts/tex-tiers.mjs +240 -0
  326. package/scripts/texmem-probe.mjs +184 -0
  327. package/scripts/unused-assets.mjs +173 -0
  328. package/scripts/vite-tmp.d.mts +23 -0
  329. package/scripts/vite-tmp.mjs +157 -0
  330. package/scripts/wave-line-baselines.json +32 -0
  331. package/scripts/wildshard.d.mts +4 -0
  332. package/scripts/wildshard.mjs +105 -0
  333. package/scripts/witness-checkpoints.d.mts +10 -0
  334. package/scripts/witness-checkpoints.mjs +84 -0
  335. package/scripts/witness-generation.d.mts +10 -0
  336. package/scripts/witness-generation.mjs +45 -0
  337. package/scripts/witness-manifests.d.mts +8 -0
  338. package/scripts/witness-manifests.mjs +157 -0
  339. package/scripts/worktree-ignore.d.mts +4 -0
  340. package/scripts/worktree-ignore.mjs +36 -0
  341. package/scripts/worktree-reap.mjs +214 -0
  342. package/scripts/worktree.mjs +396 -0
  343. package/scripts/worldclaw/capture-front.sh +28 -0
  344. package/scripts/worldclaw/design-template.md +62 -0
  345. package/scripts/worldclaw/spec-map.py +92 -0
  346. package/scripts/worldclaw/spec.ts +96 -0
  347. package/skills/wildshard/SKILL.md +50 -0
  348. package/skills/wildshard-goldens/SKILL.md +54 -0
  349. package/skills/wildshard-mockup-to-model/SKILL.md +56 -0
  350. package/skills/wildshard-upgrade/SKILL.md +46 -0
  351. package/src/.oxfmtrc.json +50 -0
  352. package/src/.oxlintrc.json +173 -0
  353. package/src/cli/account/account.ts +199 -0
  354. package/src/cli/account/command.ts +193 -0
  355. package/src/cli/account/key.ts +154 -0
  356. package/src/cli/args.ts +97 -0
  357. package/src/cli/audio/audio.ts +24 -0
  358. package/src/cli/bin.mjs +8 -0
  359. package/src/cli/delete/delete.ts +258 -0
  360. package/src/cli/help.ts +196 -0
  361. package/src/cli/hero/adopt.ts +103 -0
  362. package/src/cli/hero/hero.ts +112 -0
  363. package/src/cli/hero/stamp.ts +298 -0
  364. package/src/cli/main.ts +292 -0
  365. package/src/cli/report.ts +16 -0
  366. package/src/cli/shardfile/command.ts +50 -0
  367. package/src/cli/shardfile/shardfile.ts +192 -0
  368. package/src/cli/upload/api.ts +246 -0
  369. package/src/cli/upload/compress.ts +55 -0
  370. package/src/cli/upload/hero.ts +62 -0
  371. package/src/cli/upload/placement.ts +115 -0
  372. package/src/cli/upload/provenance.ts +192 -0
  373. package/src/cli/upload/signature.ts +30 -0
  374. package/src/cli/upload/upload.ts +269 -0
  375. package/src/cli/upload/validate.ts +74 -0
  376. package/src/cli/upload/wire.ts +147 -0
  377. package/src/cli/version.ts +63 -0
  378. package/src/commons/bake/portableMath.ts +187 -0
  379. package/src/commons/catalogue.ts +10 -0
  380. package/src/commons/courseProgram.ts +32 -0
  381. package/src/commons/practiceCourse.ts +16 -0
  382. package/src/commons/scripts/abi.as +14 -0
  383. package/src/commons/scripts/bridge.as +14 -0
  384. package/src/commons/scripts/course.as +63 -0
  385. package/src/scripts/ask-new.sh +29 -0
  386. package/src/scripts/asks.mjs +141 -0
  387. package/src/scripts/herdr-prompt.sh +34 -0
  388. package/src/scripts/herdr-question-open.sh +67 -0
  389. package/src/scripts/md-wrap.mjs +229 -0
  390. package/src/server/app.ts +19 -0
  391. package/src/server/serve.ts +49 -0
  392. package/src/sharddev/admission.ts +7 -0
  393. package/src/sharddev/arenaView.ts +15 -0
  394. package/src/sharddev/as/groupBankV2.ts +36 -0
  395. package/src/sharddev/as/groupStepV2.ts +13 -0
  396. package/src/sharddev/as/ws.ts +30 -0
  397. package/src/sharddev/as/wsV2.ts +180 -0
  398. package/src/sharddev/assemblyscriptCompiler.d.mts +5 -0
  399. package/src/sharddev/assemblyscriptCompiler.mjs +14 -0
  400. package/src/sharddev/assetHandle.ts +84 -0
  401. package/src/sharddev/assetOwner.ts +70 -0
  402. package/src/sharddev/assetScope.ts +30 -0
  403. package/src/sharddev/assets.ts +21 -0
  404. package/src/sharddev/audio.ts +9 -0
  405. package/src/sharddev/audioEncode.ts +211 -0
  406. package/src/sharddev/author.ts +3 -0
  407. package/src/sharddev/authorError.ts +28 -0
  408. package/src/sharddev/authorManifest.ts +39 -0
  409. package/src/sharddev/bake/annulus.ts +19 -0
  410. package/src/sharddev/bake/assemblyscriptMemo.ts +76 -0
  411. package/src/sharddev/bake/assemblyscriptMemoPort.ts +4 -0
  412. package/src/sharddev/bake/authoredWorld.ts +201 -0
  413. package/src/sharddev/bake/basisEncoder.ts +95 -0
  414. package/src/sharddev/bake/basisGlb.ts +85 -0
  415. package/src/sharddev/bake/basisTool.ts +74 -0
  416. package/src/sharddev/bake/basisToolInputs.ts +476 -0
  417. package/src/sharddev/bake/byteCodec.ts +33 -0
  418. package/src/sharddev/bake/canvasAtlas.ts +406 -0
  419. package/src/sharddev/bake/coarseCopy.ts +59 -0
  420. package/src/sharddev/bake/colliders.ts +87 -0
  421. package/src/sharddev/bake/compactGlb.ts +224 -0
  422. package/src/sharddev/bake/compileScript.ts +119 -0
  423. package/src/sharddev/bake/compileScriptV2.ts +75 -0
  424. package/src/sharddev/bake/contactRows.ts +84 -0
  425. package/src/sharddev/bake/creaturePlacement.ts +117 -0
  426. package/src/sharddev/bake/export.ts +67 -0
  427. package/src/sharddev/bake/facetedGeometry.ts +379 -0
  428. package/src/sharddev/bake/farImpostor.ts +120 -0
  429. package/src/sharddev/bake/forest.ts +100 -0
  430. package/src/sharddev/bake/format-hook.mjs +2 -0
  431. package/src/sharddev/bake/generatorGlb.ts +23 -0
  432. package/src/sharddev/bake/geometryBounds.ts +77 -0
  433. package/src/sharddev/bake/geometryError.ts +48 -0
  434. package/src/sharddev/bake/glb.ts +355 -0
  435. package/src/sharddev/bake/glbCompression.ts +143 -0
  436. package/src/sharddev/bake/gltfSource.ts +59 -0
  437. package/src/sharddev/bake/groundMap.ts +142 -0
  438. package/src/sharddev/bake/image.ts +20 -0
  439. package/src/sharddev/bake/isleMap.ts +64 -0
  440. package/src/sharddev/bake/json.mjs +84 -0
  441. package/src/sharddev/bake/keyedSky.ts +47 -0
  442. package/src/sharddev/bake/keyedSkyMemo.ts +39 -0
  443. package/src/sharddev/bake/kinds.ts +137 -0
  444. package/src/sharddev/bake/lightSources.ts +31 -0
  445. package/src/sharddev/bake/mapAssembly.ts +84 -0
  446. package/src/sharddev/bake/mapRaster.ts +173 -0
  447. package/src/sharddev/bake/mapRest.ts +57 -0
  448. package/src/sharddev/bake/mapScenes.ts +234 -0
  449. package/src/sharddev/bake/materialGraph.ts +32 -0
  450. package/src/sharddev/bake/meadow.ts +27 -0
  451. package/src/sharddev/bake/meshoptChoiceMemo.ts +34 -0
  452. package/src/sharddev/bake/nativeInteractionFacts.ts +5 -0
  453. package/src/sharddev/bake/nativeLattice.ts +178 -0
  454. package/src/sharddev/bake/nativeRaster.ts +106 -0
  455. package/src/sharddev/bake/nativeTerrainField.ts +11 -0
  456. package/src/sharddev/bake/navigation-json.mjs +38 -0
  457. package/src/sharddev/bake/navigation.ts +113 -0
  458. package/src/sharddev/bake/navigationAsset.ts +18 -0
  459. package/src/sharddev/bake/nearPlaceholder.ts +206 -0
  460. package/src/sharddev/bake/normalizeRig.ts +80 -0
  461. package/src/sharddev/bake/phoneAstc.ts +93 -0
  462. package/src/sharddev/bake/placeholders.ts +581 -0
  463. package/src/sharddev/bake/placement.ts +80 -0
  464. package/src/sharddev/bake/portableBytes.ts +18 -0
  465. package/src/sharddev/bake/portableBytesMemo.ts +50 -0
  466. package/src/sharddev/bake/practiceCourse.ts +49 -0
  467. package/src/sharddev/bake/primitives.ts +96 -0
  468. package/src/sharddev/bake/props.ts +443 -0
  469. package/src/sharddev/bake/questPlacement.ts +98 -0
  470. package/src/sharddev/bake/rawTexture.ts +26 -0
  471. package/src/sharddev/bake/riderArms.ts +97 -0
  472. package/src/sharddev/bake/rig.ts +95 -0
  473. package/src/sharddev/bake/riggedHullRecipes.ts +40 -0
  474. package/src/sharddev/bake/signPlacements.ts +25 -0
  475. package/src/sharddev/bake/simplifier.ts +52 -0
  476. package/src/sharddev/bake/skinned.ts +312 -0
  477. package/src/sharddev/bake/slabChunks.ts +149 -0
  478. package/src/sharddev/bake/slabs.ts +263 -0
  479. package/src/sharddev/bake/source-loader.mjs +55 -0
  480. package/src/sharddev/bake/sourceMetadata.ts +54 -0
  481. package/src/sharddev/bake/species.ts +368 -0
  482. package/src/sharddev/bake/specimenCatalogue.ts +47 -0
  483. package/src/sharddev/bake/splatGround.ts +141 -0
  484. package/src/sharddev/bake/staticMaterials.ts +171 -0
  485. package/src/sharddev/bake/terrain.ts +195 -0
  486. package/src/sharddev/bake/texture.ts +33 -0
  487. package/src/sharddev/bake/textureWasm.ts +81 -0
  488. package/src/sharddev/bake/tileEncoder.ts +11 -0
  489. package/src/sharddev/bake/tileGrid.ts +62 -0
  490. package/src/sharddev/bake/v2Finite.ts +160 -0
  491. package/src/sharddev/bake/v2Fuel.ts +71 -0
  492. package/src/sharddev/bake/wholePartition.ts +74 -0
  493. package/src/sharddev/bake/wholePieceJoin.ts +147 -0
  494. package/src/sharddev/bake/world.ts +173 -0
  495. package/src/sharddev/bake/worldCollision.ts +128 -0
  496. package/src/sharddev/bake/worldGeometry.ts +237 -0
  497. package/src/sharddev/bake/worldGlb.ts +123 -0
  498. package/src/sharddev/bake/worldImage.ts +12 -0
  499. package/src/sharddev/bake/worldLod.ts +128 -0
  500. package/src/sharddev/bake/worldRows.ts +102 -0
  501. package/src/sharddev/bake/worldTextureMemo.ts +63 -0
  502. package/src/sharddev/bake/zstdBytesMemo.ts +52 -0
  503. package/src/sharddev/bake.ts +193 -0
  504. package/src/sharddev/bakePublication.ts +31 -0
  505. package/src/sharddev/behaviourSource.ts +94 -0
  506. package/src/sharddev/bin/wildshard.mjs +7 -0
  507. package/src/sharddev/blobBytes.ts +65 -0
  508. package/src/sharddev/blobs.ts +138 -0
  509. package/src/sharddev/bootInventory.ts +129 -0
  510. package/src/sharddev/bossProfiles.ts +18 -0
  511. package/src/sharddev/buildBehaviour.ts +77 -0
  512. package/src/sharddev/buildCacheMetrics.ts +17 -0
  513. package/src/sharddev/buildDecisionScripts.ts +122 -0
  514. package/src/sharddev/check.ts +117 -0
  515. package/src/sharddev/checkProject.ts +126 -0
  516. package/src/sharddev/cli.ts +191 -0
  517. package/src/sharddev/clientChannels.ts +169 -0
  518. package/src/sharddev/clientScripts.ts +10 -0
  519. package/src/sharddev/commons.ts +77 -0
  520. package/src/sharddev/commonsCosts.ts +11 -0
  521. package/src/sharddev/compileMovers.ts +11 -0
  522. package/src/sharddev/configBoundary.ts +6 -0
  523. package/src/sharddev/cookInput.ts +40 -0
  524. package/src/sharddev/crowds.ts +6 -0
  525. package/src/sharddev/decisionBindingMap.ts +11 -0
  526. package/src/sharddev/decisionScriptBindings.ts +117 -0
  527. package/src/sharddev/decisionScripts.ts +28 -0
  528. package/src/sharddev/decisionSource.ts +51 -0
  529. package/src/sharddev/dev.ts +113 -0
  530. package/src/sharddev/director.ts +26 -0
  531. package/src/sharddev/directorAbi.ts +77 -0
  532. package/src/sharddev/discoveryDocument.ts +97 -0
  533. package/src/sharddev/draft.ts +11 -0
  534. package/src/sharddev/eliteEntryRows.ts +29 -0
  535. package/src/sharddev/entries.ts +76 -0
  536. package/src/sharddev/entryReads.ts +73 -0
  537. package/src/sharddev/executeBundle.ts +55 -0
  538. package/src/sharddev/finds.ts +5 -0
  539. package/src/sharddev/formatJsonSchema.ts +3 -0
  540. package/src/sharddev/generationCache.ts +257 -0
  541. package/src/sharddev/generationRecipe.ts +94 -0
  542. package/src/sharddev/handwritten.ts +110 -0
  543. package/src/sharddev/immutable.ts +14 -0
  544. package/src/sharddev/interactions.ts +38 -0
  545. package/src/sharddev/kit/bakedGeometry.ts +16 -0
  546. package/src/sharddev/kit/geometryPack.ts +110 -0
  547. package/src/sharddev/ledger.ts +13 -0
  548. package/src/sharddev/looks/tileField.ts +67 -0
  549. package/src/sharddev/materialGraphFiles.ts +57 -0
  550. package/src/sharddev/materials.ts +574 -0
  551. package/src/sharddev/measure.ts +18 -0
  552. package/src/sharddev/modes.ts +115 -0
  553. package/src/sharddev/moverPrograms.ts +213 -0
  554. package/src/sharddev/movers.ts +75 -0
  555. package/src/sharddev/nativePopulationRows.ts +46 -0
  556. package/src/sharddev/newProject.ts +247 -0
  557. package/src/sharddev/noise.ts +54 -0
  558. package/src/sharddev/outputProduct.ts +188 -0
  559. package/src/sharddev/outputRuntime.ts +66 -0
  560. package/src/sharddev/performancePolicy.ts +18 -0
  561. package/src/sharddev/phasedBoss.ts +34 -0
  562. package/src/sharddev/physics.ts +194 -0
  563. package/src/sharddev/platformSections.ts +42 -0
  564. package/src/sharddev/plumbing.ts +8 -0
  565. package/src/sharddev/productOutput.ts +128 -0
  566. package/src/sharddev/project.ts +337 -0
  567. package/src/sharddev/projectCompilerIdentity.ts +94 -0
  568. package/src/sharddev/projectDecisions.ts +66 -0
  569. package/src/sharddev/projectEntryProof.ts +32 -0
  570. package/src/sharddev/projectGeneration.ts +219 -0
  571. package/src/sharddev/projectInputFiles.ts +47 -0
  572. package/src/sharddev/projectManifest.ts +108 -0
  573. package/src/sharddev/projectMap.ts +35 -0
  574. package/src/sharddev/projectOutput.ts +242 -0
  575. package/src/sharddev/projectPolicy.ts +17 -0
  576. package/src/sharddev/projectSections.ts +27 -0
  577. package/src/sharddev/questGraph.ts +25 -0
  578. package/src/sharddev/quests.ts +65 -0
  579. package/src/sharddev/random.ts +61 -0
  580. package/src/sharddev/refusals.ts +234 -0
  581. package/src/sharddev/reportCard.ts +13 -0
  582. package/src/sharddev/returnProjectionV2.ts +81 -0
  583. package/src/sharddev/rows.ts +192 -0
  584. package/src/sharddev/runtimeImports.ts +38 -0
  585. package/src/sharddev/runtimeMirrors.ts +39 -0
  586. package/src/sharddev/runtimePerformance.ts +38 -0
  587. package/src/sharddev/scene.ts +321 -0
  588. package/src/sharddev/sceneAnimation.ts +54 -0
  589. package/src/sharddev/sceneAudio.ts +64 -0
  590. package/src/sharddev/sceneDeclarations.ts +100 -0
  591. package/src/sharddev/sceneGraph.ts +139 -0
  592. package/src/sharddev/sceneTransform.ts +12 -0
  593. package/src/sharddev/schemaValidation.ts +61 -0
  594. package/src/sharddev/sections.ts +47 -0
  595. package/src/sharddev/shardSource.ts +59 -0
  596. package/src/sharddev/sourceReader.ts +26 -0
  597. package/src/sharddev/spawns.ts +38 -0
  598. package/src/sharddev/species/clips.ts +24 -0
  599. package/src/sharddev/species.ts +29 -0
  600. package/src/sharddev/speciesBrains.ts +19 -0
  601. package/src/sharddev/synth.ts +66 -0
  602. package/src/sharddev/test/compileDualScriptV2.ts +71 -0
  603. package/src/sharddev/test/compileSimV2.ts +21 -0
  604. package/src/sharddev/test/diskScriptScenario.ts +86 -0
  605. package/src/sharddev/test/scriptScenario.ts +249 -0
  606. package/src/sharddev/test/scriptSource.ts +12 -0
  607. package/src/sharddev/version.ts +4 -0
  608. package/src/sharddev/weapons/bowProfile.ts +20 -0
  609. package/src/sharddev/weapons/firearmRows.ts +11 -0
  610. package/src/sharddev/weapons/meleeProfile.ts +71 -0
  611. package/src/sharddev/weapons/thrownProfile.ts +10 -0
  612. package/src/sharddev/worldScenes.ts +308 -0
  613. package/src/sharddev/worldSource.ts +82 -0
  614. package/src/shards/_template/README.md +78 -0
  615. package/src/shards/_template/assets/2bf489fdb15f1734ddb4c4f32d500ec6da85c765ec7a4eb28dc6781160e7ec8c +0 -0
  616. package/src/shards/_template/assets/97ec4d8f75f5fa6239ee919444d6dc19fd35896bb305930c1f050ac6e0e0e6a6 +1 -0
  617. package/src/shards/_template/assets/a6a587a31327f936b1b04c05ade818c73fc8964260918662db43539465e27586 +0 -0
  618. package/src/shards/_template/assets/b4fbde0422e125b498c3dc8b9a5cc2516c8598f09e9d0e5f6b639b32f98179e6 +0 -0
  619. package/src/shards/_template/assets/bfa4dfc9c18979f904557ee8deab0058b8a399be10266f5fb1578b403f482fd4 +1 -0
  620. package/src/shards/_template/assets/ef3b7ff4fd22715771cb7d68a3977a903c5e7c3dc293542687d04b3ef3ace2cb +0 -0
  621. package/src/shards/_template/assets/f2db05998615ce1cb79ea96be32c168842eb6a2b34ec01feb86d36404603ee54 +0 -0
  622. package/src/shards/_template/assets/fef98ebb7fce6f66b26e78ac699e5c90f9bdcfaf8cabeb2b58125347eea8b4ab +0 -0
  623. package/src/shards/_template/behaviour/boss.as +39 -0
  624. package/src/shards/_template/behaviour/door.as +32 -0
  625. package/src/shards/_template/behaviour/hooks.json +129 -0
  626. package/src/shards/_template/behaviour/idle.as +75 -0
  627. package/src/shards/_template/behaviour/items.as +22 -0
  628. package/src/shards/_template/card/landscape.jpg +0 -0
  629. package/src/shards/_template/card/portrait.jpg +0 -0
  630. package/src/shards/_template/card/thumb.jpg +0 -0
  631. package/src/shards/_template/data/audio.json +45 -0
  632. package/src/shards/_template/data/bossDecision.json +83 -0
  633. package/src/shards/_template/data/budgets.json +70 -0
  634. package/src/shards/_template/data/card.json +281 -0
  635. package/src/shards/_template/data/clientScripts.json +987 -0
  636. package/src/shards/_template/data/creatures.json +65 -0
  637. package/src/shards/_template/data/director.json +39 -0
  638. package/src/shards/_template/data/encounters.json +96 -0
  639. package/src/shards/_template/data/items.json +172 -0
  640. package/src/shards/_template/data/layout.json +66 -0
  641. package/src/shards/_template/data/ledger.json +32 -0
  642. package/src/shards/_template/data/look.json +521 -0
  643. package/src/shards/_template/data/map.json +64 -0
  644. package/src/shards/_template/data/moves.json +16 -0
  645. package/src/shards/_template/data/placeholder.json +8 -0
  646. package/src/shards/_template/data/plumbing.json +32 -0
  647. package/src/shards/_template/data/quests.json +223 -0
  648. package/src/shards/_template/data/rows.json +423 -0
  649. package/src/shards/_template/data/skins.json +66 -0
  650. package/src/shards/_template/data/spawn.json +6 -0
  651. package/src/shards/_template/data/targets.json +150 -0
  652. package/src/shards/_template/data/text.json +12 -0
  653. package/src/shards/_template/data/ui.json +33 -0
  654. package/src/shards/_template/data/water.json +13 -0
  655. package/src/shards/_template/generators/behaviour.ts +34 -0
  656. package/src/shards/_template/generators/boss.ts +29 -0
  657. package/src/shards/_template/generators/buildOptions.ts +2 -0
  658. package/src/shards/_template/generators/cell.ts +224 -0
  659. package/src/shards/_template/generators/districts.ts +215 -0
  660. package/src/shards/_template/generators/farLook.ts +15 -0
  661. package/src/shards/_template/generators/generate.ts +27 -0
  662. package/src/shards/_template/generators/ground.ts +15 -0
  663. package/src/shards/_template/generators/kit.ts +69 -0
  664. package/src/shards/_template/generators/landscape.ts +59 -0
  665. package/src/shards/_template/generators/landscapeNoise.ts +62 -0
  666. package/src/shards/_template/generators/mapInputs.ts +10 -0
  667. package/src/shards/_template/generators/product.ts +100 -0
  668. package/src/shards/_template/generators/productOutput.ts +18 -0
  669. package/src/shards/_template/generators/props.ts +9 -0
  670. package/src/shards/_template/generators/templatePropsSource.ts +58 -0
  671. package/src/shards/_template/generators/terrain.ts +17 -0
  672. package/src/shards/_template/generators/world.ts +630 -0
  673. package/src/shards/_template/hero.json +10 -0
  674. package/src/shards/_template/look/entry-reads.json +20 -0
  675. package/src/shards/_template/manifest.json +281 -0
  676. package/src/shards/_template/shard.config.ts +10 -0
  677. package/src/shared/health.ts +10 -0
  678. package/src/tools/build-web.ts +59 -0
  679. package/src/tsconfig.json +30 -0
  680. package/src/web/app.tsx +53 -0
  681. package/src/web/index.html +12 -0
  682. package/src/web/main.tsx +10 -0
  683. package/src/web/tsconfig.json +13 -0
  684. package/tsconfig.author.json +23 -0
  685. package/tsconfig.commons.json +21 -0
  686. package/tsconfig.json +47 -0
  687. package/tsconfig.sharddev.json +20 -0
@@ -0,0 +1,193 @@
1
+ import { Group, InstancedMesh, Matrix4, Mesh, type Object3D } from 'three';
2
+ import { readScene, type SceneDescription } from './scene';
3
+ import { confinedScenePath, publishSceneDescription } from './bakePublication';
4
+ import { Collider } from './physics';
5
+ import { declareNavigation } from './bake/navigationAsset';
6
+ import { bakeTerrain, type BakedTerrain, type TerrainBakeSource } from './bake/terrain';
7
+ import { bakeProps, type BakedProps, type PropScatter, type PropsBakeSource, type PropWhole } from './bake/props';
8
+ import { bakeKinds, type KindBakeOptions, type KindCollider, type PieceBake } from './bake/kinds';
9
+ import { completeL0Tiles } from './bake/tileGrid';
10
+
11
+ /**
12
+ * SHARD-PLATFORM SF80 (design-system.md §3, "the design's central call"): `bake(scene, identity)`. A generator builds an
13
+ * ordinary three.js `Scene`; `bake` walks it once, writes its inspectable `scene.json` (`synth`), and emits the shardfile
14
+ * content the scene declares:
15
+ *
16
+ * - **terrain**: the ground's height / colour recipe (`inputs.terrain`) baked into the 64 L0 + 16 L1 tiles and the critical
17
+ * collider (`bake/terrain`);
18
+ * - **static props**: every plain `Mesh` outside a `BakedPiece` / `Scatter`, merged per tile onto those tiles (`bake/props`);
19
+ * - **scatter**: every `InstancedMesh` (one model) and every `Scatter` (a multi-mesh model) as per-tile instance lists;
20
+ * - **pieces**: every `BakedPiece`, its named `InstancedMesh` kinds folded into one instanced GLB (`bake/kinds`; one draw
21
+ * per kind, never multi-draw) with the collider rows it declares;
22
+ * - **colliders**: the SDK `Collider` nodes (`@wildshard/sdk/physics`), the props' collider rows and each piece's rows.
23
+ *
24
+ * The full-world tile inventory includes every L0 square. Vacant squares have
25
+ * zero costs and no files; the sparse render/terrain payload sections stay sparse.
26
+ *
27
+ * It runs only at build time and never installs a service. Generic: it knows no shard, only the scene it is handed.
28
+ */
29
+
30
+ /** An inspected author graph and the exact digest/path of its canonical JSON; neither is a finished shardfile. */
31
+ export interface SynthResult {
32
+ scene: SceneDescription;
33
+ hash: string;
34
+ path: string;
35
+ }
36
+
37
+ /** A path under the author project, refused when it resolves outside it. */
38
+ export function confined(root: string, path: string): string { return confinedScenePath(root, path); }
39
+
40
+ /** Publish the canonical description through the existing confined Node writer. */
41
+ export function publishScene(description: SceneDescription, project: string, slug: string): SynthResult {
42
+ return publishSceneDescription(description, project, slug);
43
+ }
44
+
45
+ /** The shard a scene bakes into (`shard.config.ts`'s identity). */
46
+ export interface BakeIdentity { slug: string; name?: string }
47
+
48
+ /** A code-built world piece baked as instanced kinds: its children are the named kinds, its rows the colliders it declares. */
49
+ export class BakedPiece<C extends KindCollider = KindCollider> extends Group {
50
+ readonly colliders: readonly C[];
51
+ readonly options: KindBakeOptions;
52
+ /** Extra plain JSON rows the piece's client reads beside its kinds (anchors, per-piece placements). */
53
+ readonly rows: Readonly<Record<string, unknown>>;
54
+ constructor(name: string, kinds: readonly (readonly [string, Mesh])[], colliders: readonly C[], options: KindBakeOptions = {}, rows: Readonly<Record<string, unknown>> = {}) {
55
+ super();
56
+ this.name = name; this.colliders = colliders; this.options = options; this.rows = rows;
57
+ for (const [kind, mesh] of kinds) { mesh.name = kind; this.add(mesh); }
58
+ }
59
+ /** The piece's kinds, in authored order. */
60
+ kinds(): (readonly [string, Mesh])[] {
61
+ return this.children.filter((child): child is Mesh => child instanceof Mesh).map((mesh) => [mesh.name, mesh] as const);
62
+ }
63
+ }
64
+
65
+ /** One (possibly multi-mesh) model scattered at world transforms; the model is its only child, at the scatter's origin. */
66
+ export class Scatter extends Group {
67
+ readonly model: Object3D;
68
+ readonly transforms: readonly Matrix4[];
69
+ constructor(name: string, model: Object3D, transforms: readonly Matrix4[]) {
70
+ super();
71
+ this.name = name; this.model = model; this.transforms = transforms.map((m) => m.clone());
72
+ this.add(model);
73
+ }
74
+ }
75
+
76
+ /** A named static mesh kept whole in its own frame, owned by its origin's L0 tile.
77
+ * Its ordinary scene transforms become the existing PropWhole transform; its child is never also merged. */
78
+ export class WholeShape extends Group {
79
+ readonly mesh: Mesh;
80
+ readonly options: Pick<PropWhole, 'customAttributes' | 'nativeAttributes' | 'partition' | 'overhang' | 'compact' | 'compactGlow' | 'materialName'>;
81
+ constructor(name: string, mesh: Mesh, options: Pick<PropWhole, 'customAttributes' | 'nativeAttributes' | 'partition' | 'overhang' | 'compact' | 'compactGlow' | 'materialName'> = {}) {
82
+ super();
83
+ this.name = name; this.mesh = mesh; this.options = options; this.add(mesh);
84
+ }
85
+ }
86
+
87
+ /** Build-time inputs a scene graph cannot hold: closures, library panels and hand-made proxies. */
88
+ export interface BakeInputs {
89
+ /** Repository / author-project root: `scene.json` goes to `<project>/.wildshard/cache/<slug>/`. Omitted: nothing is written. */
90
+ project?: string;
91
+ /** Original WSNM bytes, declared and charged without resampling or changing queries. */
92
+ navigation?: Uint8Array;
93
+ /** The ground's recipe (closures run here only). Omitted: the shardfile has no terrain. */
94
+ terrain?: TerrainBakeSource;
95
+ /** Props options the graph does not express yet: panels, library models, coarse / far proxies, family, colour texture. */
96
+ props?: Omit<PropsBakeSource, 'static' | 'scatter'>;
97
+ }
98
+
99
+ /** A baked piece: its GLB, kind rows, collider rows and extra rows. */
100
+ export interface BakedSceneParts extends PieceBake { name: string; rows: Readonly<Record<string, unknown>> }
101
+
102
+ /** Everything `bake` emits: the shardfile rows, the immutable files by hash and the pieces' GLBs. */
103
+ export interface BakedScene {
104
+ identity: BakeIdentity;
105
+ /** The synthesized description, its content hash and where it was written (null without `inputs.project`). */
106
+ scene: SceneDescription; sceneHash: string | null; scenePath: string | null;
107
+ terrain: BakedTerrain | null;
108
+ props: BakedProps | null;
109
+ pieces: BakedSceneParts[];
110
+ /** Shardfile rows in the product's canonical order (tiles by lod, x, z; files by hash). */
111
+ shardfile: Pick<BakedTerrain, 'tiles' | 'files' | 'critical'> & Partial<Pick<BakedTerrain, 'edge' | 'terrain'> & Pick<BakedProps, 'far' | 'library'>> & { navigation?: ReturnType<typeof declareNavigation>['navigation'] };
112
+ colliders: { scene: SceneDescription['colliders']; props: BakedProps['props']['colliders']; pieces: { piece: string; colliders: PieceBake['colliders'] }[] };
113
+ assets: Map<string, Uint8Array>;
114
+ }
115
+
116
+ const SLUG = /^[a-z][a-z0-9-]{0,127}$/u;
117
+
118
+ const isPiece = (object: Object3D): object is BakedPiece => object instanceof BakedPiece;
119
+ const isMesh = (object: Object3D): object is Mesh => object instanceof Mesh;
120
+
121
+ /** Inside a piece or a scatter (their own bakers own those meshes). */
122
+ function owned(object: Object3D): boolean {
123
+ for (let node: Object3D | null = object.parent; node !== null; node = node.parent) if (node instanceof BakedPiece || node instanceof Scatter || node instanceof WholeShape) return true;
124
+ return false;
125
+ }
126
+
127
+ /** World-placed stand-in for a mesh, so the props merge reads exactly its world triangles. */
128
+ function placed(mesh: Mesh): Mesh {
129
+ const proxy = new Mesh(mesh.geometry, mesh.material);
130
+ proxy.matrixAutoUpdate = false; proxy.matrix.copy(mesh.matrixWorld);
131
+ return proxy;
132
+ }
133
+
134
+ /** Bake the existing scene content, optionally publishing its canonical diagnostic description. */
135
+ export function bake(scene: Object3D, identity: BakeIdentity, inputs: BakeInputs = {}): BakedScene {
136
+ const result = bakeOwned(scene, identity, inputs);
137
+ if (inputs.project !== undefined) {
138
+ const published = publishScene(result.scene, inputs.project, identity.slug);
139
+ result.sceneHash = published.hash; result.scenePath = published.path;
140
+ }
141
+ return result;
142
+ }
143
+
144
+ /** Build-only scene compilation into owned rows and bytes, without publishing
145
+ * files or installing services. Shares the complete algorithm with `bake`;
146
+ * source programs cache the returned values through their injected context. */
147
+ export function bakeOwned(scene: Object3D, identity: BakeIdentity, inputs: Omit<BakeInputs, 'project'> = {}): BakedScene {
148
+ if (!SLUG.test(identity.slug)) throw new Error('bake: identity needs a bounded shard slug');
149
+ scene.updateMatrixWorld(true);
150
+ const statics = new Group(), scatter: PropScatter[] = [], pieces: BakedPiece[] = [], whole: PropWhole[] = [...inputs.props?.whole ?? []];
151
+ scene.traverse((object) => {
152
+ if (owned(object)) return;
153
+ if (isPiece(object)) { pieces.push(object); return; }
154
+ if (object instanceof WholeShape) {
155
+ whole.push({ ...object.options, id: object.name, mesh: object.mesh, transform: object.mesh.matrixWorld.clone() }); return;
156
+ }
157
+ if (object instanceof Scatter) {
158
+ if (!object.matrixWorld.equals(new Matrix4())) throw new Error(`bake: scatter ${object.name} must sit at the world origin (its transforms are world space)`);
159
+ scatter.push({ model: object.model, transforms: object.transforms }); return;
160
+ }
161
+ if (object instanceof InstancedMesh) {
162
+ const transforms = Array.from({ length: object.count }, (_, i) => { const m = new Matrix4(); object.getMatrixAt(i, m); return object.matrixWorld.clone().multiply(m); });
163
+ scatter.push({ model: new Mesh(object.geometry, object.material), transforms }); return;
164
+ }
165
+ if (isMesh(object) && !(object instanceof Collider)) statics.add(placed(object));
166
+ });
167
+ if (new Set(pieces.map((p) => p.name)).size !== pieces.length || pieces.some((p) => p.name === '')) throw new Error('bake: every piece needs a unique name');
168
+
169
+ // synth: the inspectable middle step, with each scatter's instances and each piece's declared rows on its node
170
+ const description = readScene(scene), byId = new Map(description.nodes.map((n) => [n.id, n]));
171
+ scene.traverse((object) => {
172
+ if (!(object instanceof Scatter)) return;
173
+ const node = byId.get(object.name);
174
+ if (node === undefined) throw new Error(`bake: scatter ${object.name} needs a unique name`);
175
+ node.instances = object.transforms.map((m) => [...m.elements]);
176
+ });
177
+
178
+ const navigation = inputs.navigation === undefined ? null : declareNavigation(inputs.navigation);
179
+ const terrain = inputs.terrain === undefined ? null : bakeTerrain(inputs.terrain);
180
+ if (terrain !== null) { terrain.tiles.sort((a, b) => a.lod - b.lod || a.x - b.x || a.z - b.z); terrain.files.sort((a, b) => a.hash.localeCompare(b.hash)); }
181
+ const hasProps = statics.children.length > 0 || scatter.length > 0 || whole.length > 0 || (inputs.props?.panels?.length ?? 0) > 0;
182
+ const props = hasProps ? bakeProps({ ...inputs.props, static: statics, scatter, whole }, terrain?.tiles ?? []) : null;
183
+ const baked = pieces.map((piece): BakedSceneParts => Object.assign(bakeKinds(piece.name, piece.kinds(), piece.colliders, piece.options), { name: piece.name, rows: piece.rows }));
184
+
185
+ const assets = new Map([...terrain?.assets ?? [], ...props?.assets ?? [], ...navigation?.assets ?? []]);
186
+ const tiles = completeL0Tiles((props?.tiles ?? terrain?.tiles ?? []).slice().sort((a, b) => a.lod - b.lod || a.x - b.x || a.z - b.z));
187
+ const files = [...terrain?.files ?? [], ...props?.files ?? [], ...navigation?.files ?? []].sort((a, b) => a.hash.localeCompare(b.hash));
188
+ const shardfile: BakedScene['shardfile'] = { tiles, files, critical: [...terrain?.critical ?? [], ...navigation?.critical ?? []],
189
+ ...(navigation === null ? {} : { navigation: navigation.navigation }),
190
+ ...(terrain === null ? {} : { terrain: terrain.terrain, edge: terrain.edge }), ...(props === null ? {} : { far: props.far, library: props.library }) };
191
+ return { identity, scene: description, sceneHash: null, scenePath: null, terrain, props, pieces: baked, shardfile,
192
+ colliders: { scene: description.colliders, props: props?.props.colliders ?? inputs.props?.colliders ?? [], pieces: baked.map((p) => ({ piece: p.name, colliders: p.colliders })) }, assets };
193
+ }
@@ -0,0 +1,31 @@
1
+ // oxlint-disable-next-line import/no-nodejs-modules -- Explicit Node publication retains the existing confined file writes.
2
+ import { existsSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from 'node:fs';
3
+ // oxlint-disable-next-line import/no-nodejs-modules -- Published paths stay under the author project.
4
+ import { dirname, resolve, sep } from 'node:path';
5
+ import { encodeCanonicalJson, hashImmutableBytes } from './immutable';
6
+ import type { SceneDescription } from './scene';
7
+ import type { SynthResult } from './bake';
8
+
9
+ /** A path under the author project, refused when it (or its nearest existing parent) resolves outside it. */
10
+ export function confinedScenePath(root: string, path: string): string {
11
+ const destination = resolve(root, path);
12
+ let existing = destination;
13
+ while (!existsSync(existing)) existing = dirname(existing);
14
+ const actual = realpathSync(existing);
15
+ if (actual !== root && !actual.startsWith(root + sep)) throw new Error('Scene synth path resolves outside project');
16
+ return destination;
17
+ }
18
+
19
+ /** Publish an already-read description as canonical scene.json (and its content-hash copy); `synth` and `bake` both write through it. */
20
+ export function publishSceneDescription(description: SceneDescription, project: string, slug: string): SynthResult {
21
+ if (!/^[a-z][a-z0-9-]{0,127}$/u.test(slug)) throw new Error('Scene synth requires a bounded shard slug');
22
+ const root = realpathSync(project);
23
+ const bytes = new TextEncoder().encode(encodeCanonicalJson(description)), hash = hashImmutableBytes(bytes);
24
+ const cache = `.wildshard/cache/${slug}`, immutable = confinedScenePath(root, `${cache}/${hash}/scene.json`);
25
+ const path = confinedScenePath(root, `${cache}/scene.json`);
26
+ if (existsSync(immutable)) {
27
+ if (hashImmutableBytes(readFileSync(immutable)) !== hash) throw new Error('Scene synth cached bytes disagree with their content hash');
28
+ } else { mkdirSync(dirname(immutable), { recursive: true }); writeFileSync(immutable, bytes, { flag: 'wx' }); }
29
+ writeFileSync(path, bytes);
30
+ return { scene: description, hash, path };
31
+ }
@@ -0,0 +1,94 @@
1
+ import * as v from 'valibot';
2
+ import { isJsonData } from '@wildshard/format/json';
3
+ import { compileScript } from './bake/compileScript';
4
+ import { hashImmutableBytes } from './immutable';
5
+
6
+ const path = v.pipe(v.string(), v.maxLength(512), v.check(value => value.split('/').every(part => /^[A-Za-z0-9_-][A-Za-z0-9_.-]*$/u.test(part)), 'project-relative source path'));
7
+ /** Build-only source declarations. References use `script:<id>` and become immutable admitted Wasm hashes. */
8
+ export const BehaviourSourceSchema: v.SchemaWithPipe<readonly [
9
+ v.ArraySchema<v.StrictObjectSchema<{
10
+ readonly id: v.SchemaWithPipe<readonly [
11
+ v.StringSchema<undefined>,
12
+ v.RegexAction<string, undefined>,
13
+ v.MaxLengthAction<string, 128, undefined>
14
+ ]>;
15
+ readonly source: v.SchemaWithPipe<readonly [
16
+ v.SchemaWithPipe<readonly [
17
+ v.StringSchema<undefined>,
18
+ v.MaxLengthAction<string, 512, undefined>,
19
+ v.CheckAction<string, "project-relative source path">
20
+ ]>,
21
+ v.CheckAction<string, "AssemblyScript .as source">
22
+ ]>;
23
+ readonly maximumPages: v.OptionalSchema<v.SchemaWithPipe<readonly [
24
+ v.NumberSchema<undefined>,
25
+ v.IntegerAction<number, undefined>,
26
+ v.MinValueAction<number, 1, undefined>,
27
+ v.MaxValueAction<number, 64, undefined>
28
+ ]>, 2>;
29
+ readonly sources: v.OptionalSchema<v.RecordSchema<v.SchemaWithPipe<readonly [
30
+ v.StringSchema<undefined>,
31
+ v.RegexAction<string, undefined>
32
+ ]>, v.SchemaWithPipe<readonly [
33
+ v.StringSchema<undefined>,
34
+ v.MaxLengthAction<string, 512, undefined>,
35
+ v.CheckAction<string, "project-relative source path">
36
+ ]>, undefined>, NonNullable<unknown>>;
37
+ }, undefined>, undefined>,
38
+ v.MaxLengthAction<{
39
+ id: string;
40
+ source: string;
41
+ maximumPages: number;
42
+ sources: Record<string, string>;
43
+ }[], 64, undefined>,
44
+ v.CheckAction<{
45
+ id: string;
46
+ source: string;
47
+ maximumPages: number;
48
+ sources: Record<string, string>;
49
+ }[], "unique behaviour source ids">
50
+ ]> = v.pipe(v.array(v.strictObject({
51
+ id: v.pipe(v.string(), v.regex(/^[a-z][a-z0-9.-]*$/u), v.maxLength(128)),
52
+ source: v.pipe(path, v.check(value => value.endsWith('.as'), 'AssemblyScript .as source')),
53
+ maximumPages: v.optional(v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(64)), 2),
54
+ sources: v.optional(v.record(v.pipe(v.string(), v.regex(/^(?:[A-Za-z0-9_-]+\/)*[A-Za-z0-9_-]+\.ts$/u)), path), {}),
55
+ })), v.maxLength(64), v.check(rows => new Set(rows.map(row => row.id)).size === rows.length, 'unique behaviour source ids'));
56
+
57
+ /** Compile explicitly listed source files in memory with pinned portable tools. No project compiler script executes.
58
+ * The trusted loader bounds and confines every read. Symbolic references are replaced only in module/script fields.
59
+ * Server scripts are critical and their three admitted memory copies are charged before geometry admission. */
60
+ export async function compileBehaviourSource(input: unknown, declaration: unknown, read: (path: string) => string): Promise<{ declaration: unknown; assets: Map<string, Uint8Array> }> {
61
+ if (!isJsonData(input) || !isJsonData(declaration) || typeof declaration !== 'object' || declaration === null || Array.isArray(declaration)) throw new Error('Behaviour source needs plain JSON declarations');
62
+ const rows = v.parse(BehaviourSourceSchema, input), assets = new Map<string, Uint8Array>(), refs = new Map<string, string>();
63
+ const files: object[] = []; let wire = 0, resident = 0;
64
+ for (const row of rows) {
65
+ const sources = Object.fromEntries(Object.entries(row.sources).map(([name, sourcePath]) => [name, read(sourcePath)]));
66
+ let bytes: Uint8Array;
67
+ try { bytes = await compileScript(read(row.source), { maximumPages: row.maximumPages, sources }); }
68
+ catch (error) { throw new Error(`AssemblyScript ${row.id} (${row.source}): ${error instanceof Error ? error.message : String(error)}`, { cause: error }); }
69
+ const hash = hashImmutableBytes(bytes); refs.set(`script:${row.id}`, hash);
70
+ if (assets.has(hash)) continue;
71
+ assets.set(hash, bytes); wire += bytes.length; resident += bytes.length + row.maximumPages * 65536 * 3;
72
+ files.push({ hash, kind: 'wasm', compressed: bytes.length, decoded: bytes.length, gpu: 0, triangles: 0, draws: 0, dependencies: [], critical: true });
73
+ }
74
+ const resolveRef = (value: string): string => {
75
+ if (!value.startsWith('script:')) return value;
76
+ const hash = refs.get(value); if (hash === undefined) throw new Error(`Unknown authored ${value}`); return hash;
77
+ };
78
+ const replace = (value: unknown, key = ''): unknown => {
79
+ if (typeof value === 'string' && (key === 'module' || key === 'scripts')) return resolveRef(value);
80
+ if (Array.isArray(value)) return value.map(row => replace(row, key));
81
+ if (typeof value === 'object' && value !== null) return Object.fromEntries(Object.entries(value).map(([name, row]) => [name, replace(row, name)]));
82
+ return value;
83
+ };
84
+ const data = replace(declaration);
85
+ if (typeof data !== 'object' || data === null || Array.isArray(data)) throw new Error('Behaviour config needs object data');
86
+ const record = (value: unknown): Record<string, unknown> => {
87
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) throw new Error('Behaviour config needs declared budgets'); return value as Record<string, unknown>;
88
+ };
89
+ const base = record(data), budgets = record(base['budgets']), sim = record(budgets['sim']), server = record(base['serverBudget']);
90
+ const oldFiles = v.parse(v.array(v.unknown()), base['files']), critical = v.parse(v.array(v.string()), base['critical']);
91
+ return { declaration: { ...base, files: [...oldFiles, ...files], critical: [...new Set([...critical, ...assets.keys()])],
92
+ budgets: { ...budgets, sim: { resident: v.parse(v.number(), sim['resident']) + resident, compressed: v.parse(v.number(), sim['compressed']) + wire } },
93
+ serverBudget: { ...server, memory: v.parse(v.number(), server['memory']) + resident } }, assets };
94
+ }
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env node
2
+ import { runCli } from '../dist/cli.js';
3
+ // oxlint-disable-next-line import/no-nodejs-modules -- This executable is the Node author CLI.
4
+ import process from 'node:process';
5
+
6
+ try { await runCli(process.argv.slice(2)); }
7
+ catch (error) { console.error(error instanceof Error ? error.message : String(error)); process.exitCode = 1; }
@@ -0,0 +1,65 @@
1
+ import { assetCost, prepareAssetDecoders } from '@wildshard/format/product';
2
+ import { parseImageAsset } from '@wildshard/format/stillImage';
3
+ import { decodeTerrainTile } from '@wildshard/format/terrainTileBytes';
4
+ import { outputBlobPath } from '@wildshard/format/outputAddress';
5
+ import { encodeCanonicalJson } from './immutable';
6
+ import { ownAssetBytes } from './assetOwner';
7
+ import type { BlobOptions, NamedBlob, NamedBlobKind } from './blobs';
8
+
9
+ // Author-only facade; browser admission prepares this codec at its async boundary.
10
+ await prepareAssetDecoders();
11
+
12
+ const MAX_BYTES = 25_000_000;
13
+ const logicalName = /^(?:[A-Za-z0-9_-][A-Za-z0-9_.-]*\/)*[A-Za-z0-9_-][A-Za-z0-9_.-]*$/u;
14
+ const reference = /^(?:commons:)?[a-f0-9]{64}$/u;
15
+ const kinds = new Set<NamedBlobKind>(['glb', 'ktx2', 'image', 'audio', 'wasm', 'bin', 'tile', 'json']);
16
+
17
+ function assertName(name: string): void {
18
+ if (name.length > 240 || !logicalName.test(name) || name.split('/').some(part => part === '.' || part === '..')) throw new Error('Blob logical name must be a bounded relative path');
19
+ }
20
+
21
+ function isTextGltf(bytes: Uint8Array): boolean {
22
+ let json: unknown;
23
+ try { json = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)); }
24
+ catch { return false; }
25
+ return typeof json === 'object' && json !== null && 'asset' in json && typeof json.asset === 'object'
26
+ && json.asset !== null && 'version' in json.asset && json.asset.version === '2.0';
27
+ }
28
+
29
+ function extension(kind: NamedBlobKind, bytes: Uint8Array): string {
30
+ if (kind === 'image') return ({ 'image/png': 'png', 'image/jpeg': 'jpg', 'image/webp': 'webp' })[parseImageAsset(bytes).mime];
31
+ if (kind === 'audio') return new TextDecoder().decode(bytes.subarray(0, 4)) === 'RIFF' ? 'wav' : 'm4a';
32
+ if (kind === 'tile') { decodeTerrainTile(bytes); return 'wtt'; }
33
+ return kind === 'bin' ? 'bin' : kind;
34
+ }
35
+
36
+ /** Shared exact-byte admission without a schema-compiler dependency. A declared
37
+ * JSON schema requires its validator; omitting it never skips admission. */
38
+ export function nameBlobBytes(name: string, kind: NamedBlobKind, input: Uint8Array, options: BlobOptions = {}, validateJson?: (schemaBytes: Uint8Array, bytes: Uint8Array) => unknown): NamedBlob {
39
+ assertName(name);
40
+ if (name.startsWith('custom/')) throw new Error('Custom output names are retired');
41
+ if (!kinds.has(kind)) throw new Error('Unsupported named blob kind');
42
+ if (input.length === 0 || input.length > MAX_BYTES) throw new Error('Blob exceeds its wire byte cap');
43
+ const owned = ownAssetBytes(input), bytes = owned.bytes, suffix = extension(kind, bytes);
44
+ if ((kind === 'bin' || kind === 'json') && isTextGltf(bytes)) throw new Error('Text glTF must compile to GLB, never a JSON or binary blob');
45
+ if (kind !== 'wasm' && options.script !== undefined) throw new Error('Script contract requires a Wasm blob');
46
+ if (options.jsonSchema !== undefined) {
47
+ if (kind !== 'json') throw new Error('JSON schema requires a named JSON blob');
48
+ if (validateJson === undefined) throw new Error('Named JSON schema requires its validator');
49
+ validateJson(new TextEncoder().encode(encodeCanonicalJson(options.jsonSchema)), bytes);
50
+ }
51
+ const actual = assetCost(kind === 'bin' || kind === 'tile' ? 'binary' : kind, bytes, options.script);
52
+ const costs = { decoded: options.decoded ?? actual.decoded, gpu: options.gpu ?? actual.gpu, triangles: options.triangles ?? actual.triangles, draws: options.draws ?? actual.draws };
53
+ for (const key of ['decoded', 'gpu', 'triangles', 'draws'] as const) if (!Number.isSafeInteger(costs[key]) || costs[key] < actual[key]) throw new Error('Blob costs cannot understate actual bytes or geometry');
54
+ const dependencies = [...options.dependencies ?? []];
55
+ if (dependencies.some(hash => !reference.test(hash)) || new Set(dependencies).size !== dependencies.length || (options.critical !== undefined && typeof options.critical !== 'boolean')) throw new Error('Invalid blob dependencies or admission policy');
56
+ if (options.tier !== undefined && (options.critical === true || (options.tier !== 'phone' && options.tier !== 'desktop'))) throw new Error('A tiered named blob is a non-critical phone or desktop file');
57
+ if (options.variantOf !== undefined && (options.critical === true || options.variantOf.length === 0 || options.variantOf.length > 240)) throw new Error('A variant is a non-critical file of a named payload');
58
+ const verified = ownAssetBytes(bytes), hash = verified.hash;
59
+ const file = { name, path: `blobs/${kind}/${hash}.${suffix}`, kind, hash, compressed: bytes.length, ...costs, critical: options.critical ?? false, dependencies,
60
+ ...(options.tier === undefined ? {} : { tier: options.tier }),
61
+ ...(options.variantOf === undefined ? {} : { variantOf: options.variantOf }),
62
+ ...(options.jsonSchema === undefined ? {} : { jsonSchema: structuredClone(Object.fromEntries(Object.entries(options.jsonSchema))) }) };
63
+ outputBlobPath(file);
64
+ return { file, bytes: verified.bytes, ...(options.script === undefined ? {} : { script: { ...options.script } }) };
65
+ }
@@ -0,0 +1,138 @@
1
+ import { registeredJsonContract } from '@wildshard/format/registeredJson';
2
+ import type { ScriptContract } from '@wildshard/format/scriptContract';
3
+ import type { JsonSchema } from '@valibot/to-json-schema';
4
+ import type { AssetCost } from '@wildshard/format/product';
5
+ import type { OutputFile } from '@wildshard/format/outputIndex';
6
+ import { AdmissionServerSchema, serverFilePath, type ServerFile } from '@wildshard/format/admissionServer';
7
+ import { NATIVE_ASSEMBLY_DATA_SCHEMA, NATIVE_ASSEMBLY_FILE, NATIVE_ASSEMBLY_SCHEMA, type NativeAssemblyPlan as AssemblyPlan } from '@wildshard/format/nativeAssembly';
8
+ import { validatePlatformFile } from '@wildshard/format/platformFileFamilies';
9
+ import { outputBlobKind } from '@wildshard/format/productValidation';
10
+ import { parse } from 'valibot';
11
+ import { encodeCanonicalJson, hashImmutableBytes } from './immutable';
12
+ import { nameBlobBytes } from './blobBytes';
13
+ import { validateDefinedJson } from './sections';
14
+ import { compileGltfSource } from './bake/gltfSource';
15
+ import { compressGlb } from './bake/glbCompression';
16
+
17
+ /** Named assets, including lazily read JSON bakes, occupy kind-specific content-addressed paths. */
18
+ export type NamedBlobKind = OutputFile['kind'];
19
+ /** Conservative owner costs may exceed measured minima; undersized claims refuse before emission. */
20
+ export interface BlobOptions extends Partial<AssetCost> { readonly script?: ScriptContract; readonly critical?: boolean; readonly dependencies?: readonly string[]; readonly jsonSchema?: JsonSchema | Readonly<Record<string, unknown>>;
21
+ /** The one device tier that fetches this file (absent: both). The other tier's selection drops it, as it drops a
22
+ * tiered tile or texture entry; a critical file serves both tiers and takes no tier. */
23
+ readonly tier?: 'phone' | 'desktop';
24
+ /** The payload this file is one variant of (its texture modes' alternatives: image, KTX2, ASTC, ...); a device
25
+ * fetches one variant, so each tier's selection keeps only its largest variant (the worst case it can fetch). */
26
+ readonly variantOf?: string }
27
+ /** Build-only meshopt candidate, kept only if gzip-9 does not grow; compressed input needs no option. */
28
+ export interface BlobSourceOptions extends BlobOptions { readonly meshopt?: boolean }
29
+ /** One owned byte array and the exact index entry that names it. */
30
+ export interface NamedBlob { readonly file: OutputFile; readonly bytes: Uint8Array; readonly script?: ScriptContract }
31
+ /** The writer merges declarations into admission before emitting these immutable assets. */
32
+ export interface EmittedBlobs { readonly files: readonly OutputFile[]; readonly assets: ReadonlyMap<string, Uint8Array> }
33
+
34
+ /** Admit actual bytes, hash their owned copy and attach a stable logical name. No author-provided hash or path is used.
35
+ * Binary channel-specific and cross-reference admission still belongs to the section's defining reader/product build. */
36
+ export function nameBlob(name: string, kind: NamedBlobKind, input: Uint8Array, options: BlobOptions = {}): NamedBlob {
37
+ if (registeredJsonContract(name) !== undefined) {
38
+ if (kind !== 'json' || options.jsonSchema === undefined) throw new Error('Registered JSON requires its defining schema');
39
+ return nameBlobBytes(name, kind, input, options, (schema, bytes) => validateDefinedJson(schema, bytes, name));
40
+ }
41
+ return nameBlobBytes(name, kind, input, options, validateDefinedJson);
42
+ }
43
+
44
+ const MAX_BYTES = 25_000_000;
45
+
46
+ /** Whether a meshopt-packed GLB gzips (level 9) no larger than its source: the download encoding decides, as source intake
47
+ * does. */
48
+ export async function meshoptNoLarger(packed: Uint8Array, input: Uint8Array): Promise<boolean> {
49
+ // oxlint-disable-next-line import/no-nodejs-modules -- Compare actual download encoding, as source intake does.
50
+ const compression = await import('node:zlib');
51
+ return compression.gzipSync(packed, { level: 9 }).length <= compression.gzipSync(input, { level: 9 }).length;
52
+ }
53
+ // CI6: one answer per packed / source pair and comparison a process (Pine names some GLBs more than once); identical bytes
54
+ // need no gzip
55
+ const choices = new WeakMap<typeof meshoptNoLarger, Map<string, boolean>>();
56
+
57
+ /** Name a GLB the way a `meshopt: true` blob source is named: losslessly meshopt-packed when that gzips (level 9) no
58
+ * larger, otherwise as given. For a program that builds its GLB in memory (GR8) rather than reading a source file.
59
+ * `noLarger` is the comparison (a build context's memoised `meshoptNoLarger`, when it has one). */
60
+ export async function nameMeshoptBlob(name: string, input: Uint8Array, options: BlobOptions = {}, noLarger: typeof meshoptNoLarger = meshoptNoLarger): Promise<NamedBlob> {
61
+ const packed = compressGlb(input), key = `${hashImmutableBytes(packed)}:${hashImmutableBytes(input)}`;
62
+ const known = choices.get(noLarger) ?? new Map<string, boolean>();
63
+ choices.set(noLarger, known);
64
+ let pick = known.get(key);
65
+ if (pick === undefined) {
66
+ pick = packed.length === input.length && packed.every((byte, i) => byte === input[i]) ? true : await noLarger(packed, input);
67
+ known.set(key, pick);
68
+ }
69
+ return nameBlob(name, 'glb', pick ? packed : input, options);
70
+ }
71
+
72
+ /** Read only project-contained files. Textual .gltf sources compile with bounded local/embedded resources into GLB;
73
+ * an escape (including through a symlink), remote URI or unsupported extension refuses before publication. */
74
+ export async function readNamedBlob(project: string, name: string, source: string, kind: NamedBlobKind, options: BlobSourceOptions = {}): Promise<NamedBlob> {
75
+ const [fileSystem, pathTools, { readBoundedFile }] = await Promise.all([
76
+ // oxlint-disable-next-line import/no-nodejs-modules -- Only explicit CLI file intake loads filesystem access.
77
+ import('node:fs'),
78
+ // oxlint-disable-next-line import/no-nodejs-modules -- Keep config-only nameBlob imports free of file services.
79
+ import('node:path'),
80
+ import('./sourceReader'),
81
+ ]);
82
+ const root = fileSystem.realpathSync(project);
83
+ const contained = (base: string, path: string): string => {
84
+ const relative = decodeURIComponent(path);
85
+ if (pathTools.isAbsolute(relative) || relative.includes('\\') || (/[:?#]/u.test(relative) || relative.includes(String.fromCodePoint(0)))) throw new Error('Blob source must be a local relative path');
86
+ const file = fileSystem.realpathSync(pathTools.resolve(base, relative));
87
+ if (!file.startsWith(`${root}${pathTools.sep}`)) throw new Error('Blob source escapes its project');
88
+ return file;
89
+ };
90
+ const file = contained(root, source), bytes = readBoundedFile(file, MAX_BYTES);
91
+ if (options.meshopt !== undefined && typeof options.meshopt !== 'boolean') throw new Error('Invalid meshopt compression option');
92
+ if (options.meshopt === true && kind !== 'glb') throw new Error('Meshopt compression requires a GLB blob');
93
+ const admit = (value: Uint8Array): Promise<NamedBlob> | NamedBlob =>
94
+ options.meshopt === true ? nameMeshoptBlob(name, value, options) : nameBlob(name, kind, value, options);
95
+ if (source.toLowerCase().endsWith('.gltf')) {
96
+ if (kind !== 'glb') throw new Error('Text glTF must compile to a GLB blob');
97
+ return admit(await compileGltfSource(bytes, uri => readBoundedFile(contained(pathTools.dirname(file), uri), MAX_BYTES)));
98
+ }
99
+ return admit(bytes);
100
+ }
101
+
102
+ /** Revalidate every owned entry before returning sorted declarations/assets. One hash has one logical name;
103
+ * duplicate names, aliases and post-admission mutation refuse rather than producing ambiguous index entries. */
104
+ export function emitNamedBlobs(blobs: readonly NamedBlob[]): EmittedBlobs {
105
+ const files: OutputFile[] = [], assets = new Map<string, Uint8Array>(), names = new Set<string>();
106
+ for (const row of blobs) {
107
+ if (row.file.name === undefined) throw new Error('Named blob needs its logical name');
108
+ const checked = nameBlob(row.file.name, row.file.kind, row.bytes, { ...row.file, ...(row.script === undefined ? {} : { script: row.script }) });
109
+ if (encodeCanonicalJson(checked.file) !== encodeCanonicalJson(row.file)) throw new Error('Named blob changed after admission');
110
+ if (names.has(row.file.name) || assets.has(row.file.hash)) throw new Error('Duplicate blob name or content reference');
111
+ names.add(row.file.name); files.push(checked.file); assets.set(row.file.hash, checked.bytes);
112
+ }
113
+ files.sort((a, b) => (a.name ?? '') < (b.name ?? '') ? -1 : (a.name ?? '') > (b.name ?? '') ? 1 : 0);
114
+ return { files, assets: new Map([...assets].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) };
115
+ }
116
+
117
+ /** J91: one server-class file and its bytes, ready for `ProjectOutput.server`. */
118
+ export interface ServerBlob { readonly file: ServerFile; readonly bytes: Uint8Array }
119
+ /** Name a server-class file: registered platform JSON by its defining schema, or binary bytes. The client never sees it. */
120
+ export function serverBlob(name: string, input: { readonly bytes: Uint8Array } | { readonly schema: string; readonly value: unknown }): ServerBlob {
121
+ if ('bytes' in input) {
122
+ const bytes = Uint8Array.from(input.bytes), kind = outputBlobKind('binary', bytes);
123
+ if (kind !== 'bin' && kind !== 'tile') throw new Error('Server binary must be a bin or tile');
124
+ const hash = hashImmutableBytes(bytes);
125
+ return { bytes, file: parse(AdmissionServerSchema, [{ name, path: serverFilePath(kind, hash), hash, bytes: bytes.length, kind }])[0] ?? missingServerRow() };
126
+ }
127
+ if (validatePlatformFile(name, input.schema, input.value) === undefined) throw new Error(`Unregistered named JSON: ${name}`);
128
+ const bytes = new TextEncoder().encode(encodeCanonicalJson(input.value)), hash = hashImmutableBytes(bytes);
129
+ return { bytes, file: parse(AdmissionServerSchema, [{ name, path: serverFilePath('json', hash), hash, bytes: bytes.length, kind: 'json', schema: input.schema }])[0] ?? missingServerRow() };
130
+ }
131
+ function missingServerRow(): never { throw new Error('Missing server file row'); }
132
+ /** J90: a native world's plan, as a generator writes it. */
133
+ export type NativeAssemblyPlan = AssemblyPlan;
134
+ /** A native world's server class: its plan, then the JSON rows and binary files it names. */
135
+ export function nativeAssemblyFiles(plan: NativeAssemblyPlan, rows: ReadonlyMap<string, unknown>, binary: ReadonlyMap<string, Uint8Array> = new Map()): ServerBlob[] {
136
+ return [serverBlob(NATIVE_ASSEMBLY_FILE, { schema: NATIVE_ASSEMBLY_SCHEMA, value: plan }),
137
+ ...[...rows].map(([name, value]) => serverBlob(name, { schema: NATIVE_ASSEMBLY_DATA_SCHEMA, value })), ...[...binary].map(([name, bytes]) => serverBlob(name, { bytes }))];
138
+ }