create-threenative 0.2.2 → 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 (343) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +10 -2
  3. package/agent-docs/asset-mcp-loop.md +33 -0
  4. package/agent-docs/ctx-surface.md +69 -0
  5. package/agent-docs/engine-capabilities.md +4 -0
  6. package/agent-docs/framework-blocks-you.md +60 -0
  7. package/agent-docs/look-at-it-and-budget-the-look.md +27 -0
  8. package/agent-docs/performance-default.md +42 -0
  9. package/agent-docs/pixel-budget.md +20 -0
  10. package/agent-docs/playtest-fail-closed.md +23 -0
  11. package/agent-docs/references/assertion-reference.md +652 -0
  12. package/agent-docs/references/capability-reference.md +3279 -0
  13. package/agent-docs/references/capture-the-frame.md +53 -0
  14. package/agent-docs/references/ctx-cookbook.md +51 -0
  15. package/agent-docs/references/debug-surface.md +63 -0
  16. package/agent-docs/references/finding-assets.md +147 -0
  17. package/agent-docs/references/gameplay-recipes.md +54 -0
  18. package/agent-docs/references/menu-screens.md +69 -0
  19. package/agent-docs/references/mobile-memory-budget.md +87 -0
  20. package/agent-docs/references/sculpt-from-a-reference.md +39 -0
  21. package/agent-docs/references/visual-baseline.md +133 -0
  22. package/agent-docs/references/webview-ui.md +113 -0
  23. package/agent-docs/sculpt-loop.md +16 -0
  24. package/agent-files/.agents/skills/threenative-builder/SKILL.md +7 -0
  25. package/agent-files/.agents/skills/threenative-verifier/SKILL.md +7 -0
  26. package/agent-files/.claude/agents/threenative-builder.md +7 -0
  27. package/agent-files/.claude/agents/threenative-verifier.md +7 -0
  28. package/agent-files/.threenative/agents/builder.md +32 -0
  29. package/agent-files/.threenative/agents/verifier.md +31 -0
  30. package/agent-files/AGENT-ROLES.md +26 -0
  31. package/capabilities.json +3542 -0
  32. package/dist/index.d.ts +191 -3
  33. package/dist/index.js +1707 -73
  34. package/dist/threenative.d.ts +9 -2
  35. package/dist/threenative.js +1825 -148
  36. package/package.json +30 -6
  37. package/template-assets/loading.ts +315 -0
  38. package/template-assets/patches/three@0.185.1.patch +287 -0
  39. package/templates/action-rpg/.codex/config.toml +15 -0
  40. package/templates/action-rpg/.mcp.json +6 -2
  41. package/templates/action-rpg/AGENTS.md +370 -6
  42. package/templates/action-rpg/CLAUDE.md +370 -6
  43. package/templates/action-rpg/index.html +0 -1
  44. package/templates/action-rpg/package.json +15 -11
  45. package/templates/action-rpg/playtests/combat.playtest.json +23 -9
  46. package/templates/action-rpg/playtests/fail.playtest.json +3 -3
  47. package/templates/action-rpg/playtests/inventory.playtest.json +16 -10
  48. package/templates/action-rpg/playtests/performance.playtest.json +22 -0
  49. package/templates/action-rpg/playtests/progress.playtest.json +18 -13
  50. package/templates/action-rpg/playtests/win.playtest.json +10 -4
  51. package/templates/action-rpg/public/icon.png +0 -0
  52. package/templates/action-rpg/src/entities/Enemy.ts +14 -4
  53. package/templates/action-rpg/src/game.ts +21 -0
  54. package/templates/action-rpg/src/render/lighting.ts +6 -1
  55. package/templates/action-rpg/src/render/loading.ts +267 -42
  56. package/templates/action-rpg/src/render/postprocessing.ts +68 -15
  57. package/templates/action-rpg/src/render/worldEnvironment.ts +583 -0
  58. package/templates/action-rpg/src/scenes/Play.ts +49 -19
  59. package/templates/action-rpg/src/state.ts +4 -0
  60. package/templates/action-rpg/src/style.css +45 -1
  61. package/templates/action-rpg/src/ui/AbilityBar.tsx +9 -7
  62. package/templates/action-rpg/src/ui/App.tsx +9 -8
  63. package/templates/action-rpg/src/ui/CharacterPanel.tsx +10 -8
  64. package/templates/action-rpg/src/ui/GameUi.tsx +24 -0
  65. package/templates/action-rpg/src/ui/Hud.tsx +10 -8
  66. package/templates/action-rpg/src/ui/InventoryPanel.tsx +9 -7
  67. package/templates/action-rpg/src/ui/main.tsx +14 -0
  68. package/templates/action-rpg/threenative.config.ts +21 -8
  69. package/templates/action-rpg/vite.config.ts +32 -2
  70. package/templates/defense/.codex/config.toml +15 -0
  71. package/templates/defense/.mcp.json +6 -2
  72. package/templates/defense/AGENTS.md +371 -8
  73. package/templates/defense/CLAUDE.md +371 -8
  74. package/templates/defense/README.md +2 -1
  75. package/templates/defense/index.html +0 -1
  76. package/templates/defense/package.json +16 -12
  77. package/templates/defense/playtests/leak.playtest.json +9 -4
  78. package/templates/defense/playtests/performance.playtest.json +22 -0
  79. package/templates/defense/playtests/placement.playtest.json +5 -5
  80. package/templates/defense/playtests/pointer-placement.playtest.json +89 -0
  81. package/templates/defense/playtests/scan.playtest.json +3 -3
  82. package/templates/defense/playtests/survive.playtest.json +11 -6
  83. package/templates/defense/public/icon.png +0 -0
  84. package/templates/defense/src/attackers/Attacker.ts +28 -12
  85. package/templates/defense/src/game.ts +24 -2
  86. package/templates/defense/src/render/lighting.ts +6 -1
  87. package/templates/defense/src/render/loading.ts +263 -37
  88. package/templates/defense/src/render/postprocessing.ts +70 -13
  89. package/templates/defense/src/render/shapes.ts +38 -0
  90. package/templates/defense/src/render/worldEnvironment.ts +583 -0
  91. package/templates/defense/src/scenes/Defense.ts +109 -50
  92. package/templates/defense/src/state.ts +6 -0
  93. package/templates/defense/src/style.css +45 -1
  94. package/templates/defense/src/ui/App.tsx +9 -4
  95. package/templates/defense/src/ui/GameUi.tsx +20 -0
  96. package/templates/defense/src/ui/Hud.tsx +6 -5
  97. package/templates/defense/src/ui/main.tsx +14 -0
  98. package/templates/defense/threenative.config.ts +21 -8
  99. package/templates/defense/vite.config.ts +34 -1
  100. package/templates/minimal/.codex/config.toml +15 -0
  101. package/templates/minimal/.mcp.json +6 -2
  102. package/templates/minimal/AGENTS.md +360 -255
  103. package/templates/minimal/CLAUDE.md +360 -255
  104. package/templates/minimal/index.html +0 -1
  105. package/templates/minimal/package.json +14 -11
  106. package/templates/minimal/playtests/atmosphere.playtest.json +32 -0
  107. package/templates/minimal/playtests/play.playtest.json +17 -5
  108. package/templates/minimal/public/icon.png +0 -0
  109. package/templates/minimal/src/game.ts +1 -0
  110. package/templates/minimal/src/render/camera.ts +1 -1
  111. package/templates/minimal/src/render/hud.ts +24 -8
  112. package/templates/minimal/src/render/lighting.ts +23 -2
  113. package/templates/minimal/src/render/loading.ts +23 -103
  114. package/templates/minimal/src/render/postprocessing.ts +92 -14
  115. package/templates/minimal/src/render/sky.ts +37 -32
  116. package/templates/minimal/src/render/worldEnvironment.ts +583 -0
  117. package/templates/minimal/src/scenes/Play.ts +91 -13
  118. package/templates/minimal/src/state.ts +8 -1
  119. package/templates/minimal/threenative.config.ts +15 -10
  120. package/templates/minimal/vite.config.ts +28 -1
  121. package/templates/platformer/.codex/config.toml +15 -0
  122. package/templates/platformer/.mcp.json +6 -2
  123. package/templates/platformer/AGENTS.md +385 -130
  124. package/templates/platformer/CLAUDE.md +385 -130
  125. package/templates/platformer/index.html +0 -1
  126. package/templates/platformer/package.json +17 -14
  127. package/templates/platformer/playtests/avoidance.playtest.json +6 -1
  128. package/templates/platformer/playtests/branding.playtest.json +29 -0
  129. package/templates/platformer/playtests/buffer.playtest.json +1 -1
  130. package/templates/platformer/playtests/collect.playtest.json +1 -1
  131. package/templates/platformer/playtests/collision-layers.playtest.json +2 -2
  132. package/templates/platformer/playtests/coyote.playtest.json +42 -8
  133. package/templates/platformer/playtests/damage.playtest.json +4 -1
  134. package/templates/platformer/playtests/dash.playtest.json +2 -2
  135. package/templates/platformer/playtests/jump.playtest.json +2 -3
  136. package/templates/platformer/playtests/native/touch-controls.playtest.json +33 -0
  137. package/templates/platformer/playtests/oneway.playtest.json +1 -1
  138. package/templates/platformer/playtests/performance.playtest.json +6 -5
  139. package/templates/platformer/playtests/respawn.playtest.json +2 -2
  140. package/templates/platformer/playtests/stomp-rise.playtest.json +17 -3
  141. package/templates/platformer/playtests/stomp.playtest.json +11 -3
  142. package/templates/platformer/playtests/terminal-loop-fail.playtest.json +13 -4
  143. package/templates/platformer/playtests/terminal-loop-win.playtest.json +3 -3
  144. package/templates/platformer/playtests/touch-controls-web.playtest.json +46 -0
  145. package/templates/platformer/public/icon.png +0 -0
  146. package/templates/platformer/src/entities/Character.ts +16 -10
  147. package/templates/platformer/src/entities/Patrol.ts +5 -0
  148. package/templates/platformer/src/game.ts +24 -1
  149. package/templates/platformer/src/render/lighting.ts +6 -1
  150. package/templates/platformer/src/render/loading.ts +270 -61
  151. package/templates/platformer/src/render/postprocessing.ts +68 -15
  152. package/templates/platformer/src/render/touch-controls.ts +54 -36
  153. package/templates/platformer/src/render/worldEnvironment.ts +583 -0
  154. package/templates/platformer/src/scenes/Level.ts +47 -22
  155. package/templates/platformer/src/state.ts +4 -0
  156. package/templates/platformer/src/style.css +45 -1
  157. package/templates/platformer/src/ui/App.tsx +9 -4
  158. package/templates/platformer/src/ui/GameUi.tsx +20 -0
  159. package/templates/platformer/src/ui/Hud.tsx +6 -5
  160. package/templates/platformer/src/ui/main.tsx +14 -0
  161. package/templates/platformer/threenative.config.ts +20 -10
  162. package/templates/platformer/vite.config.ts +34 -1
  163. package/templates/racing/.codex/config.toml +15 -0
  164. package/templates/racing/.mcp.json +6 -2
  165. package/templates/racing/AGENTS.md +370 -6
  166. package/templates/racing/CLAUDE.md +370 -6
  167. package/templates/racing/index.html +0 -1
  168. package/templates/racing/package.json +16 -12
  169. package/templates/racing/playtests/boost.playtest.json +5 -5
  170. package/templates/racing/playtests/outcome.playtest.json +14 -4
  171. package/templates/racing/playtests/performance.playtest.json +22 -0
  172. package/templates/racing/playtests/ranking.playtest.json +2 -2
  173. package/templates/racing/playtests/rescue.playtest.json +12 -6
  174. package/templates/racing/playtests/reverse.playtest.json +3 -3
  175. package/templates/racing/playtests/shortcut.playtest.json +3 -3
  176. package/templates/racing/public/icon.png +0 -0
  177. package/templates/racing/src/game.ts +24 -1
  178. package/templates/racing/src/render/camera.ts +10 -6
  179. package/templates/racing/src/render/lighting.ts +6 -1
  180. package/templates/racing/src/render/loading.ts +291 -34
  181. package/templates/racing/src/render/postprocessing.ts +70 -13
  182. package/templates/racing/src/render/worldEnvironment.ts +583 -0
  183. package/templates/racing/src/scenes/Race.ts +68 -36
  184. package/templates/racing/src/state.ts +4 -0
  185. package/templates/racing/src/style.css +45 -1
  186. package/templates/racing/src/track/Lap.ts +20 -9
  187. package/templates/racing/src/track/Ranking.ts +53 -14
  188. package/templates/racing/src/track/Track.ts +29 -16
  189. package/templates/racing/src/track/TrackSector.ts +14 -4
  190. package/templates/racing/src/ui/App.tsx +9 -4
  191. package/templates/racing/src/ui/GameUi.tsx +20 -0
  192. package/templates/racing/src/ui/Hud.tsx +6 -5
  193. package/templates/racing/src/ui/main.tsx +14 -0
  194. package/templates/racing/threenative.config.ts +21 -8
  195. package/templates/racing/vite.config.ts +34 -1
  196. package/templates/sailing/.codex/config.toml +15 -0
  197. package/templates/sailing/.mcp.json +20 -0
  198. package/templates/sailing/AGENTS.md +388 -0
  199. package/templates/sailing/CLAUDE.md +390 -0
  200. package/templates/sailing/README.md +25 -0
  201. package/templates/sailing/index.html +12 -0
  202. package/templates/sailing/kit.json +7 -0
  203. package/templates/sailing/native-playtests/survives.playtest.json +21 -0
  204. package/templates/sailing/package.json +52 -0
  205. package/templates/sailing/playtests/fail.playtest.json +24 -0
  206. package/templates/sailing/playtests/performance.playtest.json +21 -0
  207. package/templates/sailing/playtests/survives.playtest.json +38 -0
  208. package/templates/sailing/playtests/win.playtest.json +31 -0
  209. package/templates/sailing/public/favicon.svg +5 -0
  210. package/templates/sailing/public/icon.png +0 -0
  211. package/templates/sailing/src/entities/Ship.ts +96 -0
  212. package/templates/sailing/src/game.ts +40 -0
  213. package/templates/sailing/src/main.ts +15 -0
  214. package/templates/sailing/src/render/camera.ts +21 -0
  215. package/templates/sailing/src/render/lighting.ts +36 -0
  216. package/templates/sailing/src/render/loading.ts +315 -0
  217. package/templates/sailing/src/render/materials.ts +28 -0
  218. package/templates/sailing/src/render/palette.ts +24 -0
  219. package/templates/sailing/src/render/postprocessing.ts +33 -0
  220. package/templates/sailing/src/render/props.ts +52 -0
  221. package/templates/sailing/src/render/sky.ts +32 -0
  222. package/templates/sailing/src/render/water-material.ts +14 -0
  223. package/templates/sailing/src/render/water-shaders.ts +12 -0
  224. package/templates/sailing/src/render/wave-nodes.ts +10 -0
  225. package/templates/sailing/src/render/worldEnvironment.ts +590 -0
  226. package/templates/sailing/src/scenes/Boot.ts +12 -0
  227. package/templates/sailing/src/scenes/Sailing.ts +106 -0
  228. package/templates/sailing/src/state.ts +10 -0
  229. package/templates/sailing/src/style.css +61 -0
  230. package/templates/sailing/src/ui/App.tsx +15 -0
  231. package/templates/sailing/src/ui/GameUi.tsx +12 -0
  232. package/templates/sailing/src/ui/Hud.tsx +55 -0
  233. package/templates/sailing/src/ui/Menu.tsx +30 -0
  234. package/templates/sailing/src/ui/main.tsx +7 -0
  235. package/templates/sailing/tailwind.config.ts +2 -0
  236. package/templates/sailing/threenative.config.ts +34 -0
  237. package/templates/sailing/tsconfig.json +17 -0
  238. package/templates/sailing/vite.config.ts +34 -0
  239. package/templates/shooter/.codex/config.toml +15 -0
  240. package/templates/shooter/.mcp.json +6 -2
  241. package/templates/shooter/AGENTS.md +373 -7
  242. package/templates/shooter/CLAUDE.md +373 -7
  243. package/templates/shooter/index.html +0 -1
  244. package/templates/shooter/package.json +16 -11
  245. package/templates/shooter/playtests/fail.playtest.json +5 -4
  246. package/templates/shooter/playtests/input-control.playtest.json +131 -0
  247. package/templates/shooter/playtests/per-item.playtest.json +59 -0
  248. package/templates/shooter/playtests/performance.playtest.json +22 -0
  249. package/templates/shooter/playtests/shooter.playtest.json +22 -18
  250. package/templates/shooter/playtests/survives.playtest.json +1 -1
  251. package/templates/shooter/public/favicon.svg +1 -1
  252. package/templates/shooter/public/icon.png +0 -0
  253. package/templates/shooter/src/game.ts +24 -1
  254. package/templates/shooter/src/main.ts +3 -13
  255. package/templates/shooter/src/render/camera.ts +62 -12
  256. package/templates/shooter/src/render/lighting.ts +6 -1
  257. package/templates/shooter/src/render/loading.ts +262 -33
  258. package/templates/shooter/src/render/palette.ts +1 -1
  259. package/templates/shooter/src/render/postprocessing.ts +68 -16
  260. package/templates/shooter/src/render/shapes.ts +178 -0
  261. package/templates/shooter/src/render/ui.css +34 -1
  262. package/templates/shooter/src/render/worldEnvironment.ts +583 -0
  263. package/templates/shooter/src/scenes/Play.ts +246 -73
  264. package/templates/shooter/src/state.ts +13 -0
  265. package/templates/shooter/src/style.css +26 -0
  266. package/templates/shooter/src/ui/App.tsx +10 -12
  267. package/templates/shooter/src/ui/GameUi.tsx +20 -0
  268. package/templates/shooter/src/ui/Hud.tsx +8 -10
  269. package/templates/shooter/src/ui/Menu.tsx +24 -9
  270. package/templates/shooter/src/ui/main.tsx +15 -0
  271. package/templates/shooter/src/weapons/Projectile.ts +21 -10
  272. package/templates/shooter/threenative.config.ts +21 -8
  273. package/templates/shooter/vite.config.ts +32 -2
  274. package/templates/starter/.codex/config.toml +15 -0
  275. package/templates/starter/.mcp.json +6 -2
  276. package/templates/starter/AGENTS.md +429 -326
  277. package/templates/starter/CLAUDE.md +429 -326
  278. package/templates/starter/assets/pickup.wav +0 -0
  279. package/templates/starter/gitignore +4 -0
  280. package/templates/starter/index.html +0 -1
  281. package/templates/starter/native-playtests/react-hud.playtest.json +20 -0
  282. package/templates/starter/native-playtests/render-chain.playtest.json +12 -0
  283. package/templates/starter/package.json +16 -12
  284. package/templates/starter/playtests/assets.playtest.json +65 -0
  285. package/templates/starter/playtests/buffer.playtest.json +59 -9
  286. package/templates/starter/playtests/cloth.playtest.json +113 -0
  287. package/templates/starter/playtests/coyote.playtest.json +60 -8
  288. package/templates/starter/playtests/forward.playtest.json +29 -4
  289. package/templates/starter/playtests/gameover.playtest.json +66 -0
  290. package/templates/starter/playtests/goal.playtest.json +67 -0
  291. package/templates/starter/playtests/hot-reload.playtest.json +48 -8
  292. package/templates/starter/playtests/look.playtest.json +34 -6
  293. package/templates/starter/playtests/models-baseline.png +0 -0
  294. package/templates/starter/playtests/models.playtest.json +74 -0
  295. package/templates/starter/playtests/monitoring.playtest.json +38 -7
  296. package/templates/starter/playtests/odometer.playtest.json +54 -0
  297. package/templates/starter/playtests/pause.playtest.json +27 -4
  298. package/templates/starter/playtests/play.playtest.json +43 -7
  299. package/templates/starter/playtests/respawn.playtest.json +46 -6
  300. package/templates/starter/playtests/restart.playtest.json +65 -10
  301. package/templates/starter/playtests/seed.playtest.json +44 -8
  302. package/templates/starter/playtests/survives.playtest.json +27 -4
  303. package/templates/starter/playtests/textures-baseline.png +0 -0
  304. package/templates/starter/playtests/textures.playtest.json +74 -0
  305. package/templates/starter/playtests/zoom-pinch.playtest.json +86 -0
  306. package/templates/starter/playtests/zoom-wheel.playtest.json +59 -0
  307. package/templates/starter/public/icon.png +0 -0
  308. package/templates/starter/src/entities/Goal.ts +122 -0
  309. package/templates/starter/src/entities/Player.ts +40 -2
  310. package/templates/starter/src/game.ts +25 -0
  311. package/templates/starter/src/render/camera.ts +31 -5
  312. package/templates/starter/src/render/easing.ts +5 -0
  313. package/templates/starter/src/render/effects/gradualBackground.ts +48 -0
  314. package/templates/starter/src/render/effects/lensDistortion.ts +43 -0
  315. package/templates/starter/src/render/effects/sparkle.ts +49 -0
  316. package/templates/starter/src/render/lighting.ts +6 -1
  317. package/templates/starter/src/render/loading.ts +315 -0
  318. package/templates/starter/src/render/materials.ts +17 -1
  319. package/templates/starter/src/render/pennant.ts +54 -0
  320. package/templates/starter/src/render/postprocessing.ts +46 -15
  321. package/templates/starter/src/render/scenery.ts +83 -0
  322. package/templates/starter/src/render/shapes.ts +9 -21
  323. package/templates/starter/src/render/worldEnvironment.ts +583 -0
  324. package/templates/starter/src/scenes/Play.ts +146 -36
  325. package/templates/starter/src/state.ts +12 -0
  326. package/templates/starter/src/style.css +45 -1
  327. package/templates/starter/src/ui/App.tsx +9 -6
  328. package/templates/starter/src/ui/GameUi.tsx +20 -0
  329. package/templates/starter/src/ui/Hud.tsx +52 -29
  330. package/templates/starter/src/ui/Menu.tsx +25 -23
  331. package/templates/starter/src/ui/main.tsx +14 -0
  332. package/templates/starter/threenative.config.ts +27 -9
  333. package/templates/starter/tools/look.mjs +109 -0
  334. package/templates/starter/vite.config.ts +32 -2
  335. package/templates/minimal/assets/.gitkeep +0 -0
  336. package/templates/minimal/public/.gitkeep +0 -0
  337. package/templates/platformer/assets/.gitkeep +0 -0
  338. package/templates/platformer/public/.gitkeep +0 -0
  339. package/templates/starter/assets/.gitkeep +0 -0
  340. package/templates/starter/public/.gitkeep +0 -0
  341. package/templates/starter/public/pickup.ogg +0 -0
  342. /package/templates/starter/{public → assets}/native-proof.glb +0 -0
  343. /package/templates/starter/{public → assets}/native-proof.png +0 -0
@@ -1,10 +1,16 @@
1
1
  #!/usr/bin/env node
2
- import { spawn } from 'child_process';
3
- import { stat, mkdir, writeFile, readFile, access, unlink } from 'fs/promises';
4
- import { createRequire } from 'module';
5
- import path from 'path';
2
+ import { createRequire } from 'node:module';
3
+ import { spawnSync, execFileSync, spawn } from 'child_process';
4
+ import { randomUUID, createHash } from 'crypto';
5
+ import { readFile, readdir, stat, mkdir, writeFile, rm, rename, access, unlink } from 'fs/promises';
6
+ import { createRequire as createRequire$1 } from 'module';
7
+ import path2 from 'path';
8
+ import { compileAssets, parsePng } from '@threenative/assets';
6
9
  import { pathToFileURL, fileURLToPath } from 'url';
10
+ import { existsSync, realpathSync, readFileSync, statSync, openSync, readSync, closeSync, accessSync, constants } from 'fs';
11
+ import { homedir } from 'os';
7
12
 
13
+ createRequire(import.meta.url);
8
14
  var ORIENTATIONS = ["landscape", "portrait", "sensor"];
9
15
  var CONFIG_FILE = "threenative.config.ts";
10
16
  var ConfigFailure = class extends Error {
@@ -55,6 +61,16 @@ function positiveInteger(value, fallback, code, label) {
55
61
  }
56
62
  return value;
57
63
  }
64
+ function maxFpsValue(value) {
65
+ if (value === void 0) return 60;
66
+ if (!Number.isSafeInteger(value) || value < 0 || value > 1e3) {
67
+ fail(
68
+ "TN_CONFIG_MAX_FPS_INVALID",
69
+ "display.maxFps must be a whole number between 0 (uncapped) and 1000."
70
+ );
71
+ }
72
+ return value;
73
+ }
58
74
  function packageDisplayName(manifest) {
59
75
  if (typeof manifest.name !== "string" || manifest.name.trim().length === 0) {
60
76
  fail("TN_CONFIG_PACKAGE_NAME_MISSING", "package.json must declare a non-empty name.");
@@ -68,54 +84,14 @@ function defaultAppId(name) {
68
84
  if (!/^[a-z]/u.test(segment)) segment = `game${segment}`;
69
85
  return `com.threenative.${segment}`;
70
86
  }
71
- var PNG_SIGNATURE = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
72
- function crc32(value) {
73
- let crc = 4294967295;
74
- for (const byte of value) {
75
- crc ^= byte;
76
- for (let bit = 0; bit < 8; bit += 1) {
77
- crc = crc >>> 1 ^ (crc & 1 ? 3988292384 : 0);
78
- }
79
- }
80
- return (crc ^ 4294967295) >>> 0;
81
- }
82
- function isPng(value) {
83
- if (value.length < PNG_SIGNATURE.length || !value.subarray(0, 8).equals(PNG_SIGNATURE)) {
84
- return false;
85
- }
86
- let offset = PNG_SIGNATURE.length;
87
- let hasHeader = false;
88
- let hasData = false;
89
- while (offset + 12 <= value.length) {
90
- const length = value.readUInt32BE(offset);
91
- const chunkEnd = offset + 12 + length;
92
- if (chunkEnd > value.length) return false;
93
- const type = value.toString("ascii", offset + 4, offset + 8);
94
- const chunk = value.subarray(offset + 4, offset + 8 + length);
95
- if (crc32(chunk) !== value.readUInt32BE(offset + 8 + length)) return false;
96
- if (type === "IHDR") {
97
- if (hasHeader || length !== 13) return false;
98
- if (value.readUInt32BE(offset + 8) === 0 || value.readUInt32BE(offset + 12) === 0) {
99
- return false;
100
- }
101
- hasHeader = true;
102
- } else if (type === "IDAT") {
103
- hasData = true;
104
- } else if (type === "IEND") {
105
- return length === 0 && hasHeader && hasData && chunkEnd === value.length;
106
- }
107
- offset = chunkEnd;
108
- }
109
- return false;
110
- }
111
87
  function projectRequire(cwd) {
112
- return createRequire(path.join(cwd, "package.json"));
88
+ return createRequire$1(path2.join(cwd, "package.json"));
113
89
  }
114
90
  function configLoaderSearch(cwd) {
115
91
  return [
116
- path.join(cwd, "node_modules", "vite"),
117
- path.join(cwd, "node_modules", "esbuild"),
118
- path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "node_modules", "esbuild")
92
+ path2.join(cwd, "node_modules", "vite"),
93
+ path2.join(cwd, "node_modules", "esbuild"),
94
+ path2.resolve(path2.dirname(fileURLToPath(import.meta.url)), "..", "node_modules", "esbuild")
119
95
  ];
120
96
  }
121
97
  var CONFIG_BUILD_COMMAND = "pnpm exec threenative build --target web";
@@ -123,7 +99,7 @@ function configContext(cwd, layer, sources, searched, fix) {
123
99
  return { cwd, fix, layer, searched, sources };
124
100
  }
125
101
  function packageContext(cwd) {
126
- const packagePath = path.join(cwd, "package.json");
102
+ const packagePath = path2.join(cwd, "package.json");
127
103
  return configContext(
128
104
  cwd,
129
105
  "package manifest",
@@ -146,8 +122,8 @@ function validationContext(cwd, sources) {
146
122
  cwd,
147
123
  "config validation",
148
124
  sources,
149
- [path.join(cwd, "package.json"), path.join(cwd, CONFIG_FILE)],
150
- `fix '${path.join(cwd, CONFIG_FILE)}' and rerun ${CONFIG_BUILD_COMMAND}`
125
+ [path2.join(cwd, "package.json"), path2.join(cwd, CONFIG_FILE)],
126
+ `fix '${path2.join(cwd, CONFIG_FILE)}' and rerun ${CONFIG_BUILD_COMMAND}`
151
127
  );
152
128
  }
153
129
  function configFailure(code, context, detail) {
@@ -176,10 +152,10 @@ function resolveEsbuild(cwd) {
176
152
  } catch {
177
153
  try {
178
154
  const vite = require2.resolve("vite");
179
- return createRequire(vite).resolve("esbuild");
155
+ return createRequire$1(vite).resolve("esbuild");
180
156
  } catch {
181
157
  try {
182
- return createRequire(import.meta.url).resolve("esbuild");
158
+ return createRequire$1(import.meta.url).resolve("esbuild");
183
159
  } catch {
184
160
  return void 0;
185
161
  }
@@ -187,7 +163,7 @@ function resolveEsbuild(cwd) {
187
163
  }
188
164
  }
189
165
  async function importConfig(cwd) {
190
- const sourcePath = path.join(cwd, CONFIG_FILE);
166
+ const sourcePath = path2.join(cwd, CONFIG_FILE);
191
167
  try {
192
168
  await access(sourcePath);
193
169
  } catch {
@@ -200,9 +176,12 @@ async function importConfig(cwd) {
200
176
  loadingContext(
201
177
  cwd,
202
178
  sourcePath,
203
- `run pnpm add -D vite in '${cwd}' and rerun ${CONFIG_BUILD_COMMAND}`
179
+ `run pnpm add -D esbuild in '${cwd}' and rerun ${CONFIG_BUILD_COMMAND}`
204
180
  ),
205
- "threenative.config.ts needs project-resolved esbuild; install Vite or esbuild."
181
+ // Not "install Vite": Vite 8 dropped esbuild for rolldown, so a project on it satisfies the
182
+ // old advice and still lands here. The templates ship esbuild explicitly for this reason;
183
+ // projects scaffolded before that do not.
184
+ "threenative.config.ts needs project-resolved esbuild; install esbuild."
206
185
  );
207
186
  }
208
187
  let esbuild;
@@ -245,7 +224,7 @@ async function importConfig(cwd) {
245
224
  error instanceof Error ? error.message : String(error)
246
225
  );
247
226
  }
248
- const compiledPath = path.join(cwd, `.threenative.config.${process.pid}.${Date.now()}.mjs`);
227
+ const compiledPath = path2.join(cwd, `.threenative.config.${process.pid}.${Date.now()}.mjs`);
249
228
  try {
250
229
  await writeFile(compiledPath, code, "utf8");
251
230
  } catch (error) {
@@ -281,7 +260,7 @@ async function importConfig(cwd) {
281
260
  async function readManifest(cwd) {
282
261
  let parsed;
283
262
  try {
284
- parsed = JSON.parse(await readFile(path.join(cwd, "package.json"), "utf8"));
263
+ parsed = JSON.parse(await readFile(path2.join(cwd, "package.json"), "utf8"));
285
264
  } catch (error) {
286
265
  fail("TN_CONFIG_PACKAGE_INVALID", error instanceof Error ? error.message : String(error));
287
266
  }
@@ -300,19 +279,19 @@ function packageNativeEntry(manifest) {
300
279
  }
301
280
  function validateNativeEntry(value, cwd) {
302
281
  const entry = nonEmptyString(value, "TN_NATIVE_ENTRY_MISSING", "nativeEntry");
303
- if (path.isAbsolute(entry)) {
282
+ if (path2.isAbsolute(entry)) {
304
283
  fail("TN_CONFIG_NATIVE_ENTRY_INVALID", "nativeEntry must be project-relative.");
305
284
  }
306
- const resolved = path.resolve(cwd, entry);
307
- const relative = path.relative(cwd, resolved);
308
- if (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
285
+ const resolved = path2.resolve(cwd, entry);
286
+ const relative = path2.relative(cwd, resolved);
287
+ if (relative === ".." || relative.startsWith(`..${path2.sep}`) || path2.isAbsolute(relative)) {
309
288
  fail("TN_CONFIG_NATIVE_ENTRY_INVALID", "nativeEntry must stay inside the project.");
310
289
  }
311
290
  return entry;
312
291
  }
313
292
  async function validateApp(raw, name, cwd) {
314
293
  const app = assertRecord(raw, "app");
315
- assertKeys(app, "app", ["id", "name", "version", "build", "icon"]);
294
+ assertKeys(app, "app", ["id", "name", "version", "build", "icon", "icons"]);
316
295
  const id = app.id === void 0 ? defaultAppId(name) : nonEmptyString(app.id, "TN_CONFIG_APP_ID_INVALID", "app.id");
317
296
  if (!/^[a-z][a-z0-9]*(?:\.[a-z][a-z0-9]*)+$/u.test(id)) {
318
297
  fail("TN_CONFIG_APP_ID_INVALID", "app.id must be a lower-case reverse-DNS identifier.");
@@ -326,33 +305,201 @@ async function validateApp(raw, name, cwd) {
326
305
  );
327
306
  }
328
307
  const build2 = positiveInteger(app.build, 1, "TN_CONFIG_APP_BUILD_INVALID", "app.build");
329
- if (app.icon === void 0) return { id, name: appName, version, build: build2 };
330
- const icon = nonEmptyString(app.icon, "TN_CONFIG_ICON_INVALID", "app.icon");
331
- if (path.extname(icon).toLowerCase() !== ".png") {
332
- fail("TN_CONFIG_ICON_INVALID", "app.icon must point to a PNG file.");
308
+ const icon = app.icon === void 0 ? void 0 : await validateProjectAsset(app.icon, cwd, "app.icon", {
309
+ codePrefix: "TN_CONFIG_ICON",
310
+ formats: ["png"],
311
+ square: true
312
+ });
313
+ const icons = await validateIconVariants(app.icons, cwd);
314
+ if (icons?.android !== void 0 && icon === void 0 && icons.android.foreground === void 0) {
315
+ fail(
316
+ "TN_CONFIG_BRAND_ANDROID_FOREGROUND_MISSING",
317
+ "app.icons.android.foreground is required when app.icon is not declared."
318
+ );
333
319
  }
334
- const iconPath = path.resolve(cwd, icon);
320
+ return {
321
+ id,
322
+ name: appName,
323
+ version,
324
+ build: build2,
325
+ ...icon === void 0 ? {} : { icon },
326
+ ...icons === void 0 ? {} : { icons }
327
+ };
328
+ }
329
+ async function validateProjectAsset(raw, cwd, label, options) {
330
+ const relative = nonEmptyString(raw, `${options.codePrefix}_INVALID`, label);
331
+ if (path2.isAbsolute(relative)) {
332
+ fail(`${options.codePrefix}_PATH_INVALID`, `${label} must be project-relative: ${relative}`);
333
+ }
334
+ const resolved = path2.resolve(cwd, relative);
335
+ const withinProject = path2.relative(cwd, resolved);
336
+ if (withinProject === ".." || withinProject.startsWith(`..${path2.sep}`) || path2.isAbsolute(withinProject)) {
337
+ fail(
338
+ `${options.codePrefix}_PATH_INVALID`,
339
+ `${label} must stay inside the project: ${relative}`
340
+ );
341
+ }
342
+ const extension = path2.extname(relative).slice(1).toLowerCase();
343
+ if (!options.formats.includes(extension)) {
344
+ fail(
345
+ options.codePrefix === "TN_CONFIG_ICON" ? `${options.codePrefix}_INVALID` : `${options.codePrefix}_FORMAT_INVALID`,
346
+ `${label} must use ${options.formats.map((format) => `.${format}`).join(" or ")}: ${relative}`
347
+ );
348
+ }
349
+ let info;
335
350
  try {
336
- const info = await stat(iconPath);
337
- if (!info.isFile()) fail("TN_CONFIG_ICON_MISSING", `app.icon does not name a file: ${icon}`);
338
- } catch (error) {
339
- if (error instanceof ConfigFailure) throw error;
340
- fail("TN_CONFIG_ICON_MISSING", `app.icon does not exist: ${icon}`);
351
+ info = await stat(resolved);
352
+ } catch {
353
+ fail(`${options.codePrefix}_MISSING`, `${label} does not exist: ${relative}`);
341
354
  }
355
+ if (!info.isFile()) fail(`${options.codePrefix}_MISSING`, `${label} is not a file: ${relative}`);
342
356
  let contents;
343
357
  try {
344
- contents = await readFile(iconPath);
358
+ contents = await readFile(resolved);
345
359
  } catch (error) {
346
- fail("TN_CONFIG_ICON_INVALID", error instanceof Error ? error.message : String(error));
360
+ fail(
361
+ `${options.codePrefix}_INVALID`,
362
+ `${label} could not be read at ${relative}: ${error instanceof Error ? error.message : String(error)}`
363
+ );
364
+ }
365
+ if (extension === "svg") {
366
+ if (!/<svg(?:\s|>)/iu.test(contents.toString("utf8"))) {
367
+ fail(`${options.codePrefix}_INVALID`, `${label} is not a valid SVG file: ${relative}`);
368
+ }
369
+ return relative;
347
370
  }
348
- if (!isPng(contents)) {
349
- fail("TN_CONFIG_ICON_INVALID", `app.icon is not a valid PNG file: ${icon}`);
371
+ const png = parsePng(contents);
372
+ if (png === void 0) {
373
+ fail(`${options.codePrefix}_INVALID`, `${label} is not a valid PNG file: ${relative}`);
374
+ }
375
+ if (options.square === true && png.width !== png.height) {
376
+ fail(
377
+ `${options.codePrefix}_DIMENSIONS_INVALID`,
378
+ `${label} must be square (${png.width}x${png.height}): ${relative}`
379
+ );
380
+ }
381
+ if (options.requiresAlpha === true && !png.hasAlpha) {
382
+ fail(
383
+ `${options.codePrefix}_ALPHA_INVALID`,
384
+ `${label} must include an alpha channel: ${relative}`
385
+ );
350
386
  }
351
- return { id, name: appName, version, build: build2, icon };
387
+ return relative;
388
+ }
389
+ function validateBrandColor(raw, label) {
390
+ if (typeof raw !== "string" || !/^#[0-9a-f]{6}$/iu.test(raw)) {
391
+ fail("TN_CONFIG_BRAND_COLOR_INVALID", `${label} must be a #rrggbb colour.`);
392
+ }
393
+ return raw;
394
+ }
395
+ async function validateIconVariants(raw, cwd) {
396
+ if (raw === void 0) return void 0;
397
+ const icons = assertRecord(raw, "app.icons");
398
+ assertKeys(icons, "app.icons", ["android", "ios", "web"]);
399
+ const android = icons.android === void 0 ? void 0 : assertRecord(icons.android, "app.icons.android");
400
+ const ios = icons.ios === void 0 ? void 0 : assertRecord(icons.ios, "app.icons.ios");
401
+ const web = icons.web === void 0 ? void 0 : assertRecord(icons.web, "app.icons.web");
402
+ if (android !== void 0)
403
+ assertKeys(android, "app.icons.android", ["foreground", "background", "monochrome"]);
404
+ if (ios !== void 0) assertKeys(ios, "app.icons.ios", ["dark", "tinted"]);
405
+ if (web !== void 0)
406
+ assertKeys(web, "app.icons.web", ["favicon", "maskable", "monochrome", "appleTouch"]);
407
+ const androidResult = android === void 0 ? void 0 : {
408
+ ...android.foreground === void 0 ? {} : {
409
+ foreground: await validateProjectAsset(
410
+ android.foreground,
411
+ cwd,
412
+ "app.icons.android.foreground",
413
+ {
414
+ codePrefix: "TN_CONFIG_BRAND_ANDROID_FOREGROUND",
415
+ formats: ["png"],
416
+ requiresAlpha: true,
417
+ square: true
418
+ }
419
+ )
420
+ },
421
+ ...android.background === void 0 ? {} : {
422
+ background: validateBrandColor(android.background, "app.icons.android.background")
423
+ },
424
+ ...android.monochrome === void 0 ? {} : {
425
+ monochrome: await validateProjectAsset(
426
+ android.monochrome,
427
+ cwd,
428
+ "app.icons.android.monochrome",
429
+ {
430
+ codePrefix: "TN_CONFIG_BRAND_ANDROID_MONOCHROME",
431
+ formats: ["png"],
432
+ requiresAlpha: true,
433
+ square: true
434
+ }
435
+ )
436
+ }
437
+ };
438
+ const iosResult = ios === void 0 ? void 0 : {
439
+ ...ios.dark === void 0 ? {} : {
440
+ dark: await validateProjectAsset(ios.dark, cwd, "app.icons.ios.dark", {
441
+ codePrefix: "TN_CONFIG_BRAND_IOS_DARK",
442
+ formats: ["png"],
443
+ square: true
444
+ })
445
+ },
446
+ ...ios.tinted === void 0 ? {} : {
447
+ tinted: await validateProjectAsset(ios.tinted, cwd, "app.icons.ios.tinted", {
448
+ codePrefix: "TN_CONFIG_BRAND_IOS_TINTED",
449
+ formats: ["png"],
450
+ square: true
451
+ })
452
+ }
453
+ };
454
+ const webResult = web === void 0 ? void 0 : {
455
+ ...web.favicon === void 0 ? {} : {
456
+ favicon: await validateProjectAsset(web.favicon, cwd, "app.icons.web.favicon", {
457
+ codePrefix: "TN_CONFIG_BRAND_WEB_FAVICON",
458
+ formats: ["png", "svg"],
459
+ square: true
460
+ })
461
+ },
462
+ ...web.maskable === void 0 ? {} : {
463
+ maskable: await validateProjectAsset(web.maskable, cwd, "app.icons.web.maskable", {
464
+ codePrefix: "TN_CONFIG_BRAND_WEB_MASKABLE",
465
+ formats: ["png"],
466
+ square: true
467
+ })
468
+ },
469
+ ...web.monochrome === void 0 ? {} : {
470
+ monochrome: await validateProjectAsset(
471
+ web.monochrome,
472
+ cwd,
473
+ "app.icons.web.monochrome",
474
+ {
475
+ codePrefix: "TN_CONFIG_BRAND_WEB_MONOCHROME",
476
+ formats: ["png"],
477
+ square: true
478
+ }
479
+ )
480
+ },
481
+ ...web.appleTouch === void 0 ? {} : {
482
+ appleTouch: await validateProjectAsset(
483
+ web.appleTouch,
484
+ cwd,
485
+ "app.icons.web.appleTouch",
486
+ {
487
+ codePrefix: "TN_CONFIG_BRAND_WEB_APPLE_TOUCH",
488
+ formats: ["png"],
489
+ square: true
490
+ }
491
+ )
492
+ }
493
+ };
494
+ return {
495
+ ...androidResult === void 0 ? {} : { android: androidResult },
496
+ ...iosResult === void 0 ? {} : { ios: iosResult },
497
+ ...webResult === void 0 ? {} : { web: webResult }
498
+ };
352
499
  }
353
500
  function validateDisplay(raw) {
354
501
  const display = assertRecord(raw, "display");
355
- assertKeys(display, "display", ["orientation", "fullscreen", "keepScreenOn"]);
502
+ assertKeys(display, "display", ["orientation", "fullscreen", "keepScreenOn", "maxFps"]);
356
503
  const orientation = display.orientation === void 0 ? "landscape" : display.orientation;
357
504
  if (typeof orientation !== "string" || !ORIENTATIONS.includes(orientation)) {
358
505
  fail(
@@ -373,7 +520,8 @@ function validateDisplay(raw) {
373
520
  false,
374
521
  "TN_CONFIG_KEEP_SCREEN_ON_INVALID",
375
522
  "display.keepScreenOn"
376
- )
523
+ ),
524
+ maxFps: maxFpsValue(display.maxFps)
377
525
  };
378
526
  }
379
527
  function validateWindow(raw, appName) {
@@ -391,54 +539,291 @@ function validateWindow(raw, appName) {
391
539
  )
392
540
  };
393
541
  }
394
- function validateLoading(raw) {
395
- const loading = assertRecord(raw, "loading");
396
- assertKeys(loading, "loading", [
397
- "image",
398
- "backdropColor",
399
- "trackColor",
400
- "progressColor",
401
- "showProgressBar"
402
- ]);
403
- const color = (value, fallback, label) => {
404
- if (value === void 0) return fallback;
405
- if (typeof value !== "string" || !/^#[0-9a-f]{6}$/iu.test(value)) {
406
- fail("TN_CONFIG_LOADING_COLOR_INVALID", `${label} must be a #rrggbb colour.`);
407
- }
408
- return value;
409
- };
410
- const image = loading.image === void 0 ? void 0 : nonEmptyString(loading.image, "TN_CONFIG_LOADING_IMAGE_INVALID", "loading.image");
411
- if (image !== void 0 && path.isAbsolute(image)) {
412
- fail("TN_CONFIG_LOADING_IMAGE_INVALID", "loading.image must be project-relative.");
413
- }
542
+ async function validateBootSplash(raw, cwd) {
543
+ if (raw === void 0) return void 0;
544
+ const bootSplash = assertRecord(raw, "bootSplash");
545
+ assertKeys(bootSplash, "bootSplash", ["backgroundColor", "image"]);
546
+ const backgroundColor = bootSplash.backgroundColor === void 0 ? void 0 : validateBrandColor(bootSplash.backgroundColor, "bootSplash.backgroundColor");
547
+ const image = bootSplash.image === void 0 ? void 0 : await validateProjectAsset(bootSplash.image, cwd, "bootSplash.image", {
548
+ codePrefix: "TN_CONFIG_BRAND_SPLASH",
549
+ formats: ["png"]
550
+ });
414
551
  return {
415
- ...image === void 0 ? {} : { image },
416
- backdropColor: color(loading.backdropColor, "#0d1b2a", "loading.backdropColor"),
417
- trackColor: color(loading.trackColor, "#274060", "loading.trackColor"),
418
- progressColor: color(loading.progressColor, "#8fd694", "loading.progressColor"),
419
- showProgressBar: booleanValue(
420
- loading.showProgressBar,
421
- true,
422
- "TN_CONFIG_LOADING_BAR_INVALID",
423
- "loading.showProgressBar"
424
- )
552
+ ...backgroundColor === void 0 ? {} : { backgroundColor },
553
+ ...image === void 0 ? {} : { image }
425
554
  };
426
555
  }
556
+ var UI_RENDERERS = ["native", "web"];
557
+ function validateUi(raw) {
558
+ const ui = assertRecord(raw, "ui");
559
+ assertKeys(ui, "ui", ["renderer"]);
560
+ const renderer = ui.renderer === void 0 ? "native" : ui.renderer;
561
+ if (typeof renderer !== "string" || !UI_RENDERERS.includes(renderer)) {
562
+ fail("TN_CONFIG_UI_RENDERER_INVALID", "ui.renderer must be web or native.");
563
+ }
564
+ return { renderer };
565
+ }
427
566
  function validateRenderer(raw) {
428
567
  const renderer = assertRecord(raw, "renderer");
429
- assertKeys(renderer, "renderer", ["preferWebGPU"]);
568
+ assertKeys(renderer, "renderer", ["preferWebGPU", "resolutionScale", "antialias", "android"]);
569
+ const android = assertRecord(renderer.android, "renderer.android");
570
+ assertKeys(android, "renderer.android", ["resolutionScale", "antialias"]);
571
+ const resolutionScale = renderer.resolutionScale;
572
+ const androidResolutionScale = android.resolutionScale;
573
+ for (const [name, value] of [
574
+ ["renderer.resolutionScale", resolutionScale],
575
+ ["renderer.android.resolutionScale", androidResolutionScale]
576
+ ]) {
577
+ if (value === void 0 || value === "auto") continue;
578
+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0 || value > 1) {
579
+ fail(
580
+ "TN_CONFIG_RENDERER_RESOLUTION_SCALE_INVALID",
581
+ `${name} must be "auto" or a number within (0, 1].`
582
+ );
583
+ }
584
+ }
585
+ const antialias = booleanOrUndefined(renderer.antialias, "renderer.antialias");
586
+ const androidAntialias = booleanOrUndefined(android.antialias, "renderer.android.antialias");
587
+ const androidOverrides = {
588
+ ...androidResolutionScale === void 0 ? {} : { resolutionScale: androidResolutionScale },
589
+ ...androidAntialias === void 0 ? {} : { antialias: androidAntialias }
590
+ };
430
591
  return {
431
592
  preferWebGPU: booleanValue(
432
593
  renderer.preferWebGPU,
433
594
  true,
434
595
  "TN_CONFIG_RENDERER_INVALID",
435
596
  "renderer.preferWebGPU"
436
- )
597
+ ),
598
+ ...antialias === void 0 ? {} : { antialias },
599
+ ...resolutionScale === void 0 ? {} : { resolutionScale },
600
+ ...Object.keys(androidOverrides).length === 0 ? {} : { android: androidOverrides }
601
+ };
602
+ }
603
+ function booleanOrUndefined(value, name) {
604
+ if (value === void 0) return void 0;
605
+ if (typeof value !== "boolean") fail("TN_CONFIG_RENDERER_INVALID", `${name} must be a boolean.`);
606
+ return value;
607
+ }
608
+ var ASSET_TARGET_KEYS = [
609
+ "maxMaterials",
610
+ "maxTriangles",
611
+ "maxTextureDimension"
612
+ ];
613
+ function validateAssetTargets(raw) {
614
+ const targets = assertRecord(raw, "assets.targets");
615
+ assertKeys(targets, "assets.targets", ASSET_TARGET_KEYS);
616
+ return {
617
+ ...targets.maxMaterials === void 0 ? {} : {
618
+ maxMaterials: positiveInteger(
619
+ targets.maxMaterials,
620
+ 1,
621
+ "TN_CONFIG_ASSETS_INVALID",
622
+ "assets.targets.maxMaterials"
623
+ )
624
+ },
625
+ ...targets.maxTriangles === void 0 ? {} : {
626
+ maxTriangles: positiveInteger(
627
+ targets.maxTriangles,
628
+ 1,
629
+ "TN_CONFIG_ASSETS_INVALID",
630
+ "assets.targets.maxTriangles"
631
+ )
632
+ },
633
+ ...targets.maxTextureDimension === void 0 ? {} : {
634
+ maxTextureDimension: positiveInteger(
635
+ targets.maxTextureDimension,
636
+ 1,
637
+ "TN_CONFIG_ASSETS_INVALID",
638
+ "assets.targets.maxTextureDimension"
639
+ )
640
+ }
641
+ };
642
+ }
643
+ var ASSET_TEXTURE_KEYS = ["overrides", "quality"];
644
+ var TEXTURE_OVERRIDE_KEYS = ["codec", "glob", "quality"];
645
+ var TEXTURE_CODECS = ["etc1s", "none", "uastc"];
646
+ function textureQuality(value, label) {
647
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 1 || value > 255) {
648
+ fail("TN_CONFIG_ASSETS_INVALID", `${label} must be an integer between 1 and 255.`);
649
+ }
650
+ return value;
651
+ }
652
+ function validateTextureOverrides(raw) {
653
+ if (!Array.isArray(raw)) {
654
+ fail("TN_CONFIG_ASSETS_INVALID", "assets.textures.overrides must be an array.");
655
+ }
656
+ return raw.map((item, index) => {
657
+ if (!isRecord(item)) {
658
+ fail(
659
+ "TN_CONFIG_ASSETS_INVALID",
660
+ `assets.textures.overrides[${String(index)}] must be an object.`
661
+ );
662
+ }
663
+ assertKeys(item, `assets.textures.overrides[${String(index)}]`, TEXTURE_OVERRIDE_KEYS);
664
+ const glob = nonEmptyString(
665
+ item.glob,
666
+ "TN_CONFIG_ASSETS_INVALID",
667
+ `assets.textures.overrides[${String(index)}].glob`
668
+ );
669
+ if (typeof item.codec !== "string" || !TEXTURE_CODECS.includes(item.codec)) {
670
+ fail(
671
+ "TN_CONFIG_ASSETS_INVALID",
672
+ `assets.textures.overrides[${String(index)}].codec must be one of ${TEXTURE_CODECS.join(", ")}; received '${String(item.codec)}'.`
673
+ );
674
+ }
675
+ return {
676
+ codec: item.codec,
677
+ glob,
678
+ ...item.quality === void 0 ? {} : {
679
+ quality: textureQuality(
680
+ item.quality,
681
+ `assets.textures.overrides[${String(index)}].quality`
682
+ )
683
+ }
684
+ };
685
+ });
686
+ }
687
+ function validateTextures(raw) {
688
+ if (raw === "none") return "none";
689
+ const textures = assertRecord(raw, "assets.textures");
690
+ assertKeys(textures, "assets.textures", ASSET_TEXTURE_KEYS);
691
+ return {
692
+ ...textures.quality === void 0 ? {} : { quality: textureQuality(textures.quality, "assets.textures.quality") },
693
+ ...textures.overrides === void 0 ? {} : { overrides: validateTextureOverrides(textures.overrides) }
694
+ };
695
+ }
696
+ var MODEL_PASS_KEYS = ["dedup", "meshopt", "prune", "quantize", "reorder"];
697
+ var MODEL_QUANTIZE_KEYS = ["normalBits", "positionBits", "uvBits"];
698
+ var MODEL_VIRTUAL_KEYS = [
699
+ "groupSize",
700
+ "maxTriangles",
701
+ "minSourceTriangles",
702
+ "minTriangles",
703
+ "simplifyRatio"
704
+ ];
705
+ function bitDepth(value, label) {
706
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 1 || value > 16) {
707
+ fail("TN_CONFIG_ASSETS_INVALID", `${label} must be an integer between 1 and 16 bits.`);
708
+ }
709
+ return value;
710
+ }
711
+ function validateModels(raw) {
712
+ if (raw === "none") return "none";
713
+ const models = assertRecord(raw, "assets.models");
714
+ assertKeys(models, "assets.models", [
715
+ "lightmap",
716
+ "passes",
717
+ "quantize",
718
+ "simplify",
719
+ "textures",
720
+ "virtual"
721
+ ]);
722
+ let lightmap;
723
+ if (models.lightmap !== void 0) {
724
+ const rawLightmap = assertRecord(models.lightmap, "assets.models.lightmap");
725
+ assertKeys(rawLightmap, "assets.models.lightmap", ["atlasSize", "padding"]);
726
+ if (rawLightmap.atlasSize === void 0 || rawLightmap.padding === void 0) {
727
+ fail("TN_CONFIG_ASSETS_INVALID", "assets.models.lightmap requires atlasSize and padding.");
728
+ }
729
+ lightmap = {
730
+ atlasSize: positiveInteger(
731
+ rawLightmap.atlasSize,
732
+ 1,
733
+ "TN_CONFIG_ASSETS_INVALID",
734
+ "assets.models.lightmap.atlasSize"
735
+ ),
736
+ padding: positiveInteger(
737
+ rawLightmap.padding,
738
+ 1,
739
+ "TN_CONFIG_ASSETS_INVALID",
740
+ "assets.models.lightmap.padding"
741
+ )
742
+ };
743
+ }
744
+ let passes;
745
+ if (models.passes !== void 0) {
746
+ const rawPasses = assertRecord(models.passes, "assets.models.passes");
747
+ assertKeys(rawPasses, "assets.models.passes", MODEL_PASS_KEYS);
748
+ passes = {};
749
+ for (const key of MODEL_PASS_KEYS) {
750
+ const value = rawPasses[key];
751
+ if (value === void 0) continue;
752
+ if (typeof value !== "boolean")
753
+ fail("TN_CONFIG_ASSETS_INVALID", `assets.models.passes.${key} must be true or false.`);
754
+ passes = { ...passes, [key]: value };
755
+ }
756
+ }
757
+ let quantize;
758
+ if (models.quantize !== void 0) {
759
+ const rawQuantize = assertRecord(models.quantize, "assets.models.quantize");
760
+ assertKeys(rawQuantize, "assets.models.quantize", MODEL_QUANTIZE_KEYS);
761
+ quantize = {};
762
+ for (const key of MODEL_QUANTIZE_KEYS) {
763
+ const value = rawQuantize[key];
764
+ if (value === void 0) continue;
765
+ quantize = {
766
+ ...quantize,
767
+ [key]: bitDepth(value, `assets.models.quantize.${key}`)
768
+ };
769
+ }
770
+ }
771
+ const simplify = models.simplify;
772
+ const textures = models.textures;
773
+ let virtual;
774
+ if (models.virtual === "none") {
775
+ virtual = "none";
776
+ } else if (models.virtual !== void 0) {
777
+ const rawVirtual = assertRecord(models.virtual, "assets.models.virtual");
778
+ assertKeys(rawVirtual, "assets.models.virtual", MODEL_VIRTUAL_KEYS);
779
+ const bake = {};
780
+ for (const key of MODEL_VIRTUAL_KEYS) {
781
+ const value = rawVirtual[key];
782
+ if (value === void 0) continue;
783
+ if (key === "simplifyRatio") {
784
+ if (typeof value !== "number" || !(value > 0) || !(value < 1))
785
+ fail(
786
+ "TN_CONFIG_ASSETS_INVALID",
787
+ "assets.models.virtual.simplifyRatio must be a number between 0 and 1, exclusive."
788
+ );
789
+ bake.simplifyRatio = value;
790
+ continue;
791
+ }
792
+ bake[key] = positiveInteger(
793
+ value,
794
+ 1,
795
+ "TN_CONFIG_ASSETS_INVALID",
796
+ `assets.models.virtual.${key}`
797
+ );
798
+ }
799
+ virtual = bake;
800
+ }
801
+ return {
802
+ ...lightmap === void 0 ? {} : { lightmap },
803
+ ...passes === void 0 || Object.keys(passes).length === 0 ? {} : { passes },
804
+ ...quantize === void 0 || Object.keys(quantize).length === 0 ? {} : { quantize },
805
+ ...simplify === void 0 ? {} : { simplify },
806
+ ...textures === void 0 ? {} : { textures },
807
+ ...virtual === void 0 ? {} : { virtual }
808
+ };
809
+ }
810
+ function validateAssets(raw) {
811
+ const assets = assertRecord(raw, "assets");
812
+ assertKeys(assets, "assets", ["models", "source", "output", "targets", "textures"]);
813
+ const targets = assets.targets === void 0 ? void 0 : validateAssetTargets(assets.targets);
814
+ const models = assets.models === void 0 ? void 0 : validateModels(assets.models);
815
+ const textures = assets.textures === void 0 ? void 0 : validateTextures(assets.textures);
816
+ return {
817
+ ...assets.source === void 0 ? {} : { source: nonEmptyString(assets.source, "TN_CONFIG_ASSETS_INVALID", "assets.source") },
818
+ ...assets.output === void 0 ? {} : { output: nonEmptyString(assets.output, "TN_CONFIG_ASSETS_INVALID", "assets.output") },
819
+ ...targets === void 0 ? {} : { targets },
820
+ ...models === void 0 ? {} : { models },
821
+ ...textures === void 0 ? {} : { textures }
437
822
  };
438
823
  }
439
824
  async function loadConfigInternal(root) {
440
- const packagePath = path.join(root, "package.json");
441
- const sourcePath = path.join(root, CONFIG_FILE);
825
+ const packagePath = path2.join(root, "package.json");
826
+ const sourcePath = path2.join(root, CONFIG_FILE);
442
827
  const manifest = await withConfigContext(
443
828
  packageContext(root),
444
829
  "TN_CONFIG_PACKAGE_INVALID",
@@ -464,10 +849,12 @@ async function loadConfigInternal(root) {
464
849
  assertKeys(raw, "config", [
465
850
  "app",
466
851
  "display",
467
- "loading",
852
+ "bootSplash",
468
853
  "window",
469
854
  "nativeEntry",
470
- "renderer"
855
+ "renderer",
856
+ "ui",
857
+ "assets"
471
858
  ]);
472
859
  }
473
860
  const configuredEntry = raw?.nativeEntry;
@@ -478,21 +865,25 @@ async function loadConfigInternal(root) {
478
865
  );
479
866
  }
480
867
  const app = await validateApp(raw?.app, name, root);
868
+ const bootSplash = await validateBootSplash(raw?.bootSplash, root);
869
+ const assets = raw?.assets === void 0 ? void 0 : validateAssets(raw.assets);
481
870
  return {
482
871
  app,
483
872
  display: validateDisplay(raw?.display),
484
- loading: validateLoading(raw?.loading),
485
873
  window: validateWindow(raw?.window, app.name),
486
874
  nativeEntry: validateNativeEntry(configuredEntry ?? packageEntry ?? "src/game.ts", root),
487
- renderer: validateRenderer(raw?.renderer)
875
+ renderer: validateRenderer(raw?.renderer),
876
+ ui: validateUi(raw?.ui),
877
+ ...bootSplash === void 0 ? {} : { bootSplash },
878
+ ...assets === void 0 ? {} : { assets }
488
879
  };
489
880
  }
490
881
  );
491
882
  }
492
883
  async function loadConfig(cwd) {
493
- const root = path.resolve(cwd);
884
+ const root = path2.resolve(cwd);
494
885
  return withConfigContext(
495
- validationContext(root, [path.join(root, CONFIG_FILE), path.join(root, "package.json")]),
886
+ validationContext(root, [path2.join(root, CONFIG_FILE), path2.join(root, "package.json")]),
496
887
  "TN_CONFIG_VALIDATION_FAILED",
497
888
  () => loadConfigInternal(root)
498
889
  );
@@ -501,11 +892,11 @@ async function loadConfig(cwd) {
501
892
  // src/build.ts
502
893
  var TARGETS = ["web", "desktop", "android", "ios"];
503
894
  function projectRequire2(cwd) {
504
- return createRequire(path.join(cwd, "package.json"));
895
+ return createRequire$1(path2.join(cwd, "package.json"));
505
896
  }
506
897
  function packageRoot(cwd, packageName) {
507
898
  try {
508
- return path.dirname(projectRequire2(cwd).resolve(`${packageName}/package.json`));
899
+ return path2.dirname(projectRequire2(cwd).resolve(`${packageName}/package.json`));
509
900
  } catch {
510
901
  throw new Error(
511
902
  `Cannot build a native target because '${packageName}' is not installed in ${cwd}.`
@@ -514,7 +905,7 @@ function packageRoot(cwd, packageName) {
514
905
  }
515
906
  function executable(cwd, name) {
516
907
  const suffix = process.platform === "win32" ? ".cmd" : "";
517
- return path.join(cwd, "node_modules", ".bin", `${name}${suffix}`);
908
+ return path2.join(cwd, "node_modules", ".bin", `${name}${suffix}`);
518
909
  }
519
910
  async function run(command, args, cwd) {
520
911
  await new Promise((resolve, reject) => {
@@ -522,12 +913,12 @@ async function run(command, args, cwd) {
522
913
  child.once("error", reject);
523
914
  child.once("exit", (code) => {
524
915
  if (code === 0) resolve();
525
- else reject(new Error(`${path.basename(command)} exited with code ${code ?? "unknown"}.`));
916
+ else reject(new Error(`${path2.basename(command)} exited with code ${code ?? "unknown"}.`));
526
917
  });
527
918
  });
528
919
  }
529
920
  async function projectName(cwd) {
530
- const manifest = JSON.parse(await readFile(path.join(cwd, "package.json"), "utf8"));
921
+ const manifest = JSON.parse(await readFile(path2.join(cwd, "package.json"), "utf8"));
531
922
  const name = manifest.name?.replace(/^@[^/]+\//u, "").replace(/[^a-zA-Z0-9._-]/gu, "-");
532
923
  if (name === void 0 || name.length === 0) throw new Error("package.json must name the game.");
533
924
  return name;
@@ -554,13 +945,146 @@ async function assertNativeBundleCompatible(bundle, target) {
554
945
  `TN_NATIVE_WASM_ON_MOBILE: ${target} bundle contains ${wasm.map(([label]) => label).join(", ")}. Move web-only WASM imports out of src/game.ts or provide a threenative-native conditional backend; mobile navigation is owned by PRD-052.`
555
946
  );
556
947
  }
948
+ function assertNativeUiRendererCompatible(target, renderer, platform = process.platform) {
949
+ if (renderer === "native" || target === "android" || target === "ios") return;
950
+ if (target === "desktop" && platform === "linux") return;
951
+ const platformName = platform === "darwin" ? "macOS" : platform === "win32" ? "Windows" : platform;
952
+ throw new Error(
953
+ `TN_UI_RENDERER_UNSUPPORTED: ui.renderer is "web", but ${target} has no WebView host on ${platformName}. Set ui.renderer to "native" for ${target}.`
954
+ );
955
+ }
956
+ var COMPRESSED_MODEL_EXTENSIONS = [
957
+ "EXT_meshopt_compression",
958
+ "KHR_draco_mesh_compression",
959
+ "KHR_meshopt_compression"
960
+ ];
961
+ function namedAssets(logicalPaths) {
962
+ const shown = logicalPaths.slice(0, 3).join(", ");
963
+ const rest = logicalPaths.length - 3;
964
+ return rest > 0 ? `${shown} and ${rest} more` : shown;
965
+ }
966
+ async function assertNativeAssetsCompatible(cwd, target, config) {
967
+ if (target === "desktop" || target === "web") return;
968
+ const outputRoot = path2.resolve(cwd, config.assets?.output ?? "public");
969
+ const manifestPath = path2.join(outputRoot, "assets.manifest.json");
970
+ let raw;
971
+ try {
972
+ raw = await readFile(manifestPath, "utf8");
973
+ } catch {
974
+ return;
975
+ }
976
+ let parsed;
977
+ try {
978
+ parsed = JSON.parse(raw);
979
+ } catch (error) {
980
+ throw new Error(
981
+ `TN_NATIVE_ASSET_MANIFEST_INVALID: '${manifestPath}' is not valid JSON: ${error instanceof Error ? error.message : String(error)}`
982
+ );
983
+ }
984
+ const entries = parsed.entries;
985
+ if (typeof entries !== "object" || entries === null) {
986
+ throw new Error(`TN_NATIVE_ASSET_MANIFEST_INVALID: '${manifestPath}' has no 'entries' object.`);
987
+ }
988
+ const rows = Object.entries(entries).map(
989
+ ([logical, entry]) => [logical, entry ?? {}]
990
+ );
991
+ const ktx2 = rows.filter(([, entry]) => typeof entry.output === "string" && /\.ktx2$/iu.test(entry.output)).map(([logical]) => logical);
992
+ if (ktx2.length > 0) {
993
+ throw new Error(
994
+ `TN_NATIVE_KTX2_UNSUPPORTED: ${target} cannot ship compiled KTX2 textures (${namedAssets(ktx2)}). The mobile native runtime has no WebAssembly and therefore no Basis transcoder, so nothing in the bundle can decode them. Set assets.textures to "none" so native builds ship the source textures, or keep the compressed textures on the web target.`
995
+ );
996
+ }
997
+ const compressedModels = rows.filter(
998
+ ([, entry]) => (Array.isArray(entry.extensions) ? entry.extensions : []).some(
999
+ (extension) => typeof extension === "string" && COMPRESSED_MODEL_EXTENSIONS.includes(extension)
1000
+ )
1001
+ ).map(([logical]) => logical);
1002
+ if (compressedModels.length > 0) {
1003
+ throw new Error(
1004
+ `TN_NATIVE_MESH_COMPRESSION_UNSUPPORTED: ${target} cannot ship compressed model geometry (${namedAssets(compressedModels)}). The mobile native runtime has no WebAssembly and therefore no Meshopt or Draco decoder. Set assets.models to "none" so native builds ship uncompressed geometry, or keep the compressed models on the web target.`
1005
+ );
1006
+ }
1007
+ }
1008
+ var UI_ENTRY = path2.join("src", "ui", "main.tsx");
1009
+ var UI_PAGE_PREFIX = ".threenative-ui-";
1010
+ async function buildUi(cwd, config) {
1011
+ const output = path2.join(cwd, ".threenative", "build", "ui");
1012
+ const entry = path2.join(cwd, UI_ENTRY);
1013
+ try {
1014
+ if (!(await stat(entry)).isFile()) throw new Error("not a file");
1015
+ } catch {
1016
+ throw new Error(
1017
+ `TN_UI_ENTRY_MISSING: ui.renderer is "${config.ui.renderer}" but ${UI_ENTRY} does not exist. It is the entry every platform's web view loads; create it, or set ui.renderer to "native".`
1018
+ );
1019
+ }
1020
+ const buildRoot = path2.join(cwd, ".threenative", "build");
1021
+ await mkdir(buildRoot, { recursive: true });
1022
+ const page = path2.join(cwd, `${UI_PAGE_PREFIX}${randomUUID()}.html`);
1023
+ await writeFile(
1024
+ page,
1025
+ [
1026
+ "<!doctype html>",
1027
+ '<html lang="en">',
1028
+ " <head>",
1029
+ ' <meta charset="utf-8" />',
1030
+ ' <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />',
1031
+ " <style>html,body,#tn-ui{margin:0;height:100%;background:transparent}</style>",
1032
+ " </head>",
1033
+ " <body>",
1034
+ ' <div id="tn-ui"></div>',
1035
+ ` <script type="module" src="/${UI_ENTRY.split(path2.sep).join("/")}"></script>`,
1036
+ " </body>",
1037
+ "</html>"
1038
+ ].join("\n")
1039
+ );
1040
+ const driver = path2.join(buildRoot, "build-ui.mjs");
1041
+ await writeFile(driver, uiBuildDriver(cwd, page, output));
1042
+ try {
1043
+ await run(process.execPath, [driver], cwd);
1044
+ } finally {
1045
+ await rm(page, { force: true });
1046
+ }
1047
+ const generatedPage = path2.join(output, path2.basename(page));
1048
+ const index = path2.join(output, "index.html");
1049
+ await rename(generatedPage, index);
1050
+ return output;
1051
+ }
1052
+ function uiBuildDriver(cwd, page, output) {
1053
+ const literal = (value) => JSON.stringify(value);
1054
+ return `${[
1055
+ 'import { build, loadConfigFromFile, mergeConfig } from "vite";',
1056
+ "",
1057
+ `const root = ${literal(cwd)};`,
1058
+ `const loaded = await loadConfigFromFile({ command: "build", mode: "production" }, undefined, root);`,
1059
+ "await build(",
1060
+ " mergeConfig(loaded?.config ?? {}, {",
1061
+ " root,",
1062
+ ' base: "./",',
1063
+ // The UI is a HUD page, not the game: it must not carry the game's `public/`. Vite copies
1064
+ // `publicDir` into every build it runs, and this output is packaged *beside* the game's own
1065
+ // assets — so every model, texture and sound shipped twice. One game's APK came to 361 MB, of
1066
+ // which 97.6 MB was a second copy of its own 97.3 MB asset directory, six copies of one 11 MB
1067
+ // weapon among them. Nothing in `src/ui/` reads those files; it reaches the game through
1068
+ // published state and intents.
1069
+ " publicDir: false,",
1070
+ " build: {",
1071
+ ` outDir: ${literal(output)},`,
1072
+ " emptyOutDir: true,",
1073
+ ` rollupOptions: { input: { index: ${literal(page)} } },`,
1074
+ " },",
1075
+ " }),",
1076
+ ");"
1077
+ ].join("\n")}
1078
+ `;
1079
+ }
557
1080
  async function buildWeb(cwd, viteArgs = []) {
558
- await loadConfig(cwd);
1081
+ const config = await loadConfig(cwd);
1082
+ await compileAssets({ config: config.assets, cwd });
559
1083
  await run(executable(cwd, "vite"), ["build", ...viteArgs], cwd);
560
1084
  }
561
1085
  async function nativeEntry(cwd, config) {
562
1086
  const relative = (config ?? await loadConfig(cwd)).nativeEntry;
563
- const entry = path.resolve(cwd, relative);
1087
+ const entry = path2.resolve(cwd, relative);
564
1088
  try {
565
1089
  if (!(await stat(entry)).isFile()) throw new Error("not a file");
566
1090
  } catch {
@@ -568,27 +1092,63 @@ async function nativeEntry(cwd, config) {
568
1092
  }
569
1093
  return entry;
570
1094
  }
571
- async function writePackagingConfig(cwd, config) {
572
- const directory = path.join(cwd, ".threenative", "build");
573
- await mkdir(directory, { recursive: true });
1095
+ function resolvePackagingConfig(cwd, config) {
1096
+ const resolve = (value) => value === void 0 ? void 0 : path2.resolve(cwd, value);
574
1097
  const artifact = {
575
1098
  ...config,
576
1099
  app: {
577
1100
  ...config.app,
578
- ...config.app.icon === void 0 ? {} : { icon: path.resolve(cwd, config.app.icon) }
1101
+ ...config.app.icon === void 0 ? {} : { icon: path2.resolve(cwd, config.app.icon) },
1102
+ ...config.app.icons === void 0 ? {} : {
1103
+ icons: {
1104
+ ...config.app.icons.android === void 0 ? {} : {
1105
+ android: {
1106
+ ...config.app.icons.android.foreground === void 0 ? {} : { foreground: path2.resolve(cwd, config.app.icons.android.foreground) },
1107
+ ...config.app.icons.android.background === void 0 ? {} : { background: config.app.icons.android.background },
1108
+ ...config.app.icons.android.monochrome === void 0 ? {} : { monochrome: path2.resolve(cwd, config.app.icons.android.monochrome) }
1109
+ }
1110
+ },
1111
+ ...config.app.icons.ios === void 0 ? {} : {
1112
+ ios: {
1113
+ ...config.app.icons.ios.dark === void 0 ? {} : { dark: path2.resolve(cwd, config.app.icons.ios.dark) },
1114
+ ...config.app.icons.ios.tinted === void 0 ? {} : { tinted: path2.resolve(cwd, config.app.icons.ios.tinted) }
1115
+ }
1116
+ },
1117
+ ...config.app.icons.web === void 0 ? {} : {
1118
+ web: {
1119
+ ...config.app.icons.web.favicon === void 0 ? {} : { favicon: resolve(config.app.icons.web.favicon) },
1120
+ ...config.app.icons.web.maskable === void 0 ? {} : { maskable: resolve(config.app.icons.web.maskable) },
1121
+ ...config.app.icons.web.monochrome === void 0 ? {} : { monochrome: resolve(config.app.icons.web.monochrome) },
1122
+ ...config.app.icons.web.appleTouch === void 0 ? {} : { appleTouch: resolve(config.app.icons.web.appleTouch) }
1123
+ }
1124
+ }
1125
+ }
1126
+ }
1127
+ },
1128
+ ...config.bootSplash === void 0 ? {} : {
1129
+ bootSplash: {
1130
+ ...config.bootSplash,
1131
+ ...config.bootSplash.image === void 0 ? {} : { image: path2.resolve(cwd, config.bootSplash.image) }
1132
+ }
579
1133
  }
580
1134
  };
581
- const output = path.join(directory, "config.json");
1135
+ return artifact;
1136
+ }
1137
+ async function writePackagingConfig(cwd, config) {
1138
+ const directory = path2.join(cwd, ".threenative", "build");
1139
+ await mkdir(directory, { recursive: true });
1140
+ const artifact = resolvePackagingConfig(cwd, config);
1141
+ const output = path2.join(directory, "config.json");
582
1142
  await writeFile(output, `${JSON.stringify(artifact, null, 2)}
583
1143
  `);
584
1144
  return output;
585
1145
  }
586
1146
  async function bundleNative(cwd, runtimeRoot, entry, target) {
587
- const output = path.join(cwd, ".threenative", "build", "game.js");
1147
+ const output = path2.join(cwd, ".threenative", "build", "game.js");
588
1148
  await run(
589
1149
  process.execPath,
590
1150
  [
591
- path.join(runtimeRoot, "scripts", "bundle.mjs"),
1151
+ path2.join(runtimeRoot, "scripts", "bundle.mjs"),
592
1152
  "--project",
593
1153
  cwd,
594
1154
  "--entry",
@@ -604,30 +1164,35 @@ async function bundleNative(cwd, runtimeRoot, entry, target) {
604
1164
  }
605
1165
  function installedRuntime(runtimeRoot) {
606
1166
  if (process.env.THREENATIVE_RUNTIME_BINARY)
607
- return path.resolve(process.env.THREENATIVE_RUNTIME_BINARY);
1167
+ return path2.resolve(process.env.THREENATIVE_RUNTIME_BINARY);
608
1168
  const key = `${process.platform}-${process.arch}`;
609
1169
  const filename = process.platform === "win32" ? "threenative-runtime.exe" : "threenative-runtime";
610
- return path.join(runtimeRoot, "prebuilt", key, filename);
1170
+ return path2.join(runtimeRoot, "prebuilt", key, filename);
611
1171
  }
612
1172
  async function buildNative(target, cwd) {
613
1173
  const config = await loadConfig(cwd);
1174
+ assertNativeUiRendererCompatible(target, config.ui.renderer);
1175
+ await compileAssets({ config: config.assets, cwd });
1176
+ await assertNativeAssetsCompatible(cwd, target, config);
614
1177
  const entry = await nativeEntry(cwd, config);
615
1178
  const orientation = config.display.orientation;
616
1179
  const configPath = await writePackagingConfig(cwd, config);
617
1180
  const runtimeRoot = packageRoot(cwd, "@threenative/runtime-native");
618
1181
  const bundle = await bundleNative(cwd, runtimeRoot, entry, target);
619
1182
  await assertNativeBundleCompatible(bundle, target);
620
- const assets = path.join(cwd, "public");
1183
+ const assets = path2.join(cwd, "public");
1184
+ const ui = config.ui.renderer === "web" ? await buildUi(cwd, config) : void 0;
621
1185
  if (target === "ios") {
622
- const output2 = path.join(cwd, "dist-native", `${await projectName(cwd)}.app`);
1186
+ const output2 = path2.join(cwd, "dist-native", `${await projectName(cwd)}.app`);
623
1187
  await run(
624
1188
  process.execPath,
625
1189
  [
626
- path.join(runtimeRoot, "scripts", "package-ios.mjs"),
1190
+ path2.join(runtimeRoot, "scripts", "package-ios.mjs"),
627
1191
  "--bundle",
628
1192
  bundle,
629
1193
  "--assets",
630
1194
  assets,
1195
+ ...ui === void 0 ? [] : ["--ui", ui],
631
1196
  "--orientation",
632
1197
  orientation,
633
1198
  "--config",
@@ -640,15 +1205,16 @@ async function buildNative(target, cwd) {
640
1205
  return;
641
1206
  }
642
1207
  if (target === "android") {
643
- const output2 = path.join(cwd, "dist-native", `${await projectName(cwd)}.apk`);
1208
+ const output2 = path2.join(cwd, "dist-native", `${await projectName(cwd)}.apk`);
644
1209
  await run(
645
1210
  process.execPath,
646
1211
  [
647
- path.join(runtimeRoot, "scripts", "package-android.mjs"),
1212
+ path2.join(runtimeRoot, "scripts", "package-android.mjs"),
648
1213
  "--bundle",
649
1214
  bundle,
650
1215
  "--assets",
651
1216
  assets,
1217
+ ...ui === void 0 ? [] : ["--ui", ui],
652
1218
  "--orientation",
653
1219
  orientation,
654
1220
  "--config",
@@ -660,15 +1226,16 @@ async function buildNative(target, cwd) {
660
1226
  );
661
1227
  return;
662
1228
  }
663
- const output = path.join(cwd, "dist-native", await projectName(cwd));
1229
+ const output = path2.join(cwd, "dist-native", await projectName(cwd));
664
1230
  await run(
665
1231
  process.execPath,
666
1232
  [
667
- path.join(runtimeRoot, "scripts", "package-desktop.mjs"),
1233
+ path2.join(runtimeRoot, "scripts", "package-desktop.mjs"),
668
1234
  "--bundle",
669
1235
  bundle,
670
1236
  "--assets",
671
1237
  assets,
1238
+ ...ui === void 0 ? [] : ["--ui", ui],
672
1239
  "--config",
673
1240
  configPath,
674
1241
  "--runtime",
@@ -680,7 +1247,7 @@ async function buildNative(target, cwd) {
680
1247
  );
681
1248
  }
682
1249
  async function build(options) {
683
- const cwd = path.resolve(options.cwd ?? process.cwd());
1250
+ const cwd = path2.resolve(options.cwd ?? process.cwd());
684
1251
  if (options.target === "web") await buildWeb(cwd, options.viteArgs);
685
1252
  else {
686
1253
  if ((options.viteArgs?.length ?? 0) > 0) {
@@ -721,16 +1288,1113 @@ function parseBuildArgs(argv) {
721
1288
  };
722
1289
  }
723
1290
 
1291
+ // src/commands.ts
1292
+ var threenativeCommands = ["build", "doctor"];
1293
+ var commandSummaries = {
1294
+ build: "Build web or native output.",
1295
+ doctor: "Check this project and report what would break a build."
1296
+ };
1297
+ var DEFAULT_NATIVE_ENTRY = "src/game.ts";
1298
+ var RUNTIME_PACKAGE = "@threenative/runtime-native";
1299
+ var PLAYTEST_BINARY = "threenative-playtest";
1300
+ var ANDROID_JDK_MAJOR = 17;
1301
+ var ANDROID_COMPILE_SDK = 35;
1302
+ var MCP_SERVER_SPECS = [
1303
+ {
1304
+ configName: "threenative-assets",
1305
+ expectedArgs: "./node_modules/@threenative/core/mcp/assets.mjs",
1306
+ packageName: "threenative-asset-mcp",
1307
+ // Kept equal to what `@threenative/core` actually installs — its package.json dependency and
1308
+ // `mcp/servers.mjs` both say 0.6.0, and doctor.spec asserts all three agree. A doctor that
1309
+ // reports a version the install does not use tells a game author their MCP surface is
1310
+ // something it is not.
1311
+ version: "0.6.0"
1312
+ },
1313
+ {
1314
+ configName: "threenative-sculpt",
1315
+ expectedArgs: "./node_modules/@threenative/core/mcp/sculpt.mjs",
1316
+ packageName: "threenative-sculpt-mcp",
1317
+ version: "0.1.1"
1318
+ },
1319
+ {
1320
+ configName: "threenative-engine",
1321
+ expectedArgs: "./node_modules/@threenative/core/mcp/engine.mjs",
1322
+ packageName: "@threenative/core",
1323
+ version: "0.3.0"
1324
+ }
1325
+ ];
1326
+ var ASSET_DOWNLOAD_DIRECTORIES = ["public/assets", "public/audio"];
1327
+ function detectX11Compositor(environment = process.env) {
1328
+ if (environment.DISPLAY === void 0) return void 0;
1329
+ try {
1330
+ const output = execFileSync("xprop", ["-root", "_NET_WM_CM_S0"], {
1331
+ encoding: "utf8",
1332
+ env: { ...environment },
1333
+ stdio: ["ignore", "pipe", "pipe"]
1334
+ });
1335
+ return /window id\s*#/u.test(output);
1336
+ } catch (error) {
1337
+ return error.code === "ENOENT" ? void 0 : false;
1338
+ }
1339
+ }
1340
+ function probeDesktopOverlay(environment = process.env, compositor = detectX11Compositor) {
1341
+ const wayland = environment.WAYLAND_DISPLAY !== void 0 || environment.XDG_SESSION_TYPE === "wayland";
1342
+ if (wayland) {
1343
+ return {
1344
+ detail: "the transparent container could not be created on this Wayland/Xwayland session",
1345
+ fix: "Run the desktop target under an X11 session (for example SDL_VIDEODRIVER=x11) or use the web UI target.",
1346
+ status: "fail"
1347
+ };
1348
+ }
1349
+ if (environment.DISPLAY === void 0) {
1350
+ return {
1351
+ detail: "no display is available, so the desktop overlay could not be probed",
1352
+ fix: "Run doctor in the display session that will host the desktop target.",
1353
+ status: "warn"
1354
+ };
1355
+ }
1356
+ const present = compositor(environment);
1357
+ if (present === true) {
1358
+ return {
1359
+ detail: "an X11 compositing manager owns _NET_WM_CM_S0; transparent overlay alpha can blend",
1360
+ fix: "",
1361
+ status: "ok"
1362
+ };
1363
+ }
1364
+ if (present === false) {
1365
+ return {
1366
+ detail: "no compositing manager is running, so nothing would blend the overlay",
1367
+ fix: "Start a compositing manager or run the desktop target under a composited X11 session.",
1368
+ status: "fail"
1369
+ };
1370
+ }
1371
+ return {
1372
+ detail: "the X11 compositor probe could not run, so overlay transparency is unknown",
1373
+ fix: "Install xprop and rerun doctor in the desktop display session.",
1374
+ status: "warn"
1375
+ };
1376
+ }
1377
+ function record(value) {
1378
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
1379
+ }
1380
+ function declaredDependencies(packageJson) {
1381
+ const manifest = record(packageJson);
1382
+ if (manifest === void 0) return [];
1383
+ const names = /* @__PURE__ */ new Set();
1384
+ for (const field of ["dependencies", "devDependencies", "optionalDependencies"]) {
1385
+ for (const name of Object.keys(record(manifest[field]) ?? {})) {
1386
+ if (name.startsWith("@threenative/")) names.add(name);
1387
+ }
1388
+ }
1389
+ return [...names].sort();
1390
+ }
1391
+ function nativeEntryFrom(config) {
1392
+ const configured = record(config)?.nativeEntry;
1393
+ return typeof configured === "string" && configured.length > 0 ? configured : DEFAULT_NATIVE_ENTRY;
1394
+ }
1395
+ function usesDesktopOverlay(config) {
1396
+ return record(record(config)?.ui)?.renderer === "web";
1397
+ }
1398
+ function nativeEntryCompat(value) {
1399
+ const entry = record(value)?.nativeEntry;
1400
+ return typeof entry === "string" && entry.length > 0 ? { nativeEntry: entry } : void 0;
1401
+ }
1402
+ function resolvePackageDirectoryFrom(start, name) {
1403
+ let directory = path2.resolve(start);
1404
+ while (true) {
1405
+ const candidate = path2.join(directory, "node_modules", name);
1406
+ if (existsSync(path2.join(candidate, "package.json"))) return candidate;
1407
+ const parent = path2.dirname(directory);
1408
+ if (parent === directory) return void 0;
1409
+ directory = parent;
1410
+ }
1411
+ }
1412
+ function resolvePackageDirectory(snapshot, name) {
1413
+ if (snapshot.resolvePackageDirectory !== void 0) {
1414
+ return snapshot.resolvePackageDirectory(name);
1415
+ }
1416
+ if (snapshot.projectRoot === void 0) return void 0;
1417
+ const direct = resolvePackageDirectoryFrom(snapshot.projectRoot, name);
1418
+ if (direct !== void 0) return direct;
1419
+ const core = resolvePackageDirectoryFrom(snapshot.projectRoot, "@threenative/core");
1420
+ if (core === void 0) return void 0;
1421
+ try {
1422
+ return resolvePackageDirectoryFrom(realpathSync(core), name);
1423
+ } catch {
1424
+ return void 0;
1425
+ }
1426
+ }
1427
+ function resolveBinaryFrom(start, name) {
1428
+ let directory = path2.resolve(start);
1429
+ while (true) {
1430
+ const binDirectory = path2.join(directory, "node_modules", ".bin");
1431
+ const candidates = process.platform === "win32" ? [path2.join(binDirectory, `${name}.cmd`), path2.join(binDirectory, name)] : [path2.join(binDirectory, name)];
1432
+ const found = candidates.find((candidate) => existsSync(candidate));
1433
+ if (found !== void 0) return found;
1434
+ const parent = path2.dirname(directory);
1435
+ if (parent === directory) return void 0;
1436
+ directory = parent;
1437
+ }
1438
+ }
1439
+ function expectedMcpServer(spec) {
1440
+ return {
1441
+ command: "node",
1442
+ args: [spec.expectedArgs],
1443
+ ...spec.configName === "threenative-assets" ? {
1444
+ env: Object.fromEntries([
1445
+ ["ASSET_DOWNLOAD_DIR", "./public/assets"],
1446
+ ["AUDIO_DOWNLOAD_DIR", "./public/audio"]
1447
+ ])
1448
+ } : {}
1449
+ };
1450
+ }
1451
+ function mcpServerMatches(spec, value) {
1452
+ const server = record(value);
1453
+ if (server === void 0 || server.command !== "node") return false;
1454
+ if (!Array.isArray(server.args) || server.args.length !== 1 || server.args[0] !== spec.expectedArgs)
1455
+ return false;
1456
+ if (spec.configName !== "threenative-assets") return true;
1457
+ const env = record(server.env);
1458
+ return env?.ASSET_DOWNLOAD_DIR === "./public/assets" && env.AUDIO_DOWNLOAD_DIR === "./public/audio";
1459
+ }
1460
+ function mcpConfig(snapshot) {
1461
+ if (!snapshot.files.has(".mcp.json")) return { kind: "missing" };
1462
+ const source = snapshot.readText(".mcp.json");
1463
+ if (source === void 0) return { detail: ".mcp.json could not be read", kind: "malformed" };
1464
+ let parsed;
1465
+ try {
1466
+ parsed = JSON.parse(source);
1467
+ } catch (error) {
1468
+ return {
1469
+ detail: `invalid JSON: ${error instanceof Error ? error.message : String(error)}`,
1470
+ kind: "malformed"
1471
+ };
1472
+ }
1473
+ const root = record(parsed);
1474
+ const servers = record(root?.mcpServers);
1475
+ return servers === void 0 ? { detail: "missing an object-valued mcpServers property", kind: "malformed" } : { kind: "ready", servers };
1476
+ }
1477
+ function mcpServerCheck(snapshot, spec, value) {
1478
+ const name = `capability search: ${spec.packageName}`;
1479
+ if (value === void 0) {
1480
+ return {
1481
+ detail: `${spec.configName} is missing from .mcp.json; expected ${spec.packageName}@${spec.version}`,
1482
+ fix: "Restore the server entry from the generated .mcp.json.",
1483
+ name,
1484
+ status: "fail"
1485
+ };
1486
+ }
1487
+ if (!mcpServerMatches(spec, value)) {
1488
+ return {
1489
+ detail: `${spec.configName} is hand-edited or malformed; expected ${JSON.stringify(expectedMcpServer(spec))}`,
1490
+ fix: "Restore the generated .mcp.json entry so the ThreeNative shim and asset directories remain wired.",
1491
+ name,
1492
+ status: "fail"
1493
+ };
1494
+ }
1495
+ if (snapshot.projectRoot !== void 0 && !existsSync(path2.resolve(snapshot.projectRoot, spec.expectedArgs))) {
1496
+ return {
1497
+ detail: `${spec.configName} points at missing ${spec.expectedArgs}; @threenative/core is not providing the configured server shim`,
1498
+ fix: "Install @threenative/core again so the generated MCP server entry exists.",
1499
+ name,
1500
+ status: "fail"
1501
+ };
1502
+ }
1503
+ const health = snapshot.mcpServerHealth?.get(spec.configName);
1504
+ if (health?.status === "fail") {
1505
+ return {
1506
+ detail: `${spec.configName} is configured, but ${health.detail}`,
1507
+ fix: `Reinstall @threenative/core and ${spec.packageName}, then rerun doctor.`,
1508
+ name,
1509
+ status: "fail"
1510
+ };
1511
+ }
1512
+ const packageDirectory = resolvePackageDirectory(snapshot, spec.packageName);
1513
+ if (packageDirectory === void 0) {
1514
+ return {
1515
+ detail: `${spec.configName} is reachable by npx only: ${spec.packageName}@${spec.version} is not installed (npx --yes ${spec.packageName}@${spec.version})`,
1516
+ fix: `Install ${spec.packageName}@${spec.version} when this server is needed, or use the npx fallback named above.`,
1517
+ name,
1518
+ status: "warn"
1519
+ };
1520
+ }
1521
+ const manifest = readJsonSync(path2.join(packageDirectory, "package.json"));
1522
+ const installedVersion = record(manifest)?.version;
1523
+ if (typeof installedVersion !== "string") {
1524
+ return {
1525
+ detail: `${spec.configName} resolves ${spec.packageName}, but its package.json has no version`,
1526
+ fix: `Reinstall ${spec.packageName}@${spec.version}.`,
1527
+ name,
1528
+ status: "fail"
1529
+ };
1530
+ }
1531
+ if (installedVersion !== spec.version) {
1532
+ return {
1533
+ detail: `${spec.configName} resolves ${spec.packageName}@${installedVersion}; the .mcp.json fallback is ${spec.packageName}@${spec.version}`,
1534
+ fix: `Install ${spec.packageName}@${spec.version} so the capability contract is version-matched.`,
1535
+ name,
1536
+ status: "warn"
1537
+ };
1538
+ }
1539
+ return {
1540
+ detail: `${spec.configName} resolves ${spec.packageName}@${installedVersion}${health === void 0 ? "" : `; ${health.detail}`}`,
1541
+ name,
1542
+ status: "ok"
1543
+ };
1544
+ }
1545
+ function probeMcpServer(projectRoot, spec) {
1546
+ const initialize = JSON.stringify({
1547
+ id: 1,
1548
+ jsonrpc: "2.0",
1549
+ method: "initialize",
1550
+ params: {
1551
+ capabilities: {},
1552
+ clientInfo: { name: "threenative-doctor", version: "0.3.0" },
1553
+ protocolVersion: "2025-06-18"
1554
+ }
1555
+ });
1556
+ const initialized = JSON.stringify({
1557
+ jsonrpc: "2.0",
1558
+ method: "notifications/initialized"
1559
+ });
1560
+ const list = JSON.stringify({ id: 2, jsonrpc: "2.0", method: "tools/list", params: {} });
1561
+ const result = spawnSync("node", [spec.expectedArgs], {
1562
+ cwd: projectRoot,
1563
+ encoding: "utf8",
1564
+ env: {
1565
+ ...process.env,
1566
+ ...spec.configName === "threenative-assets" ? Object.fromEntries([
1567
+ ["ASSET_DOWNLOAD_DIR", "./public/assets"],
1568
+ ["AUDIO_DOWNLOAD_DIR", "./public/audio"]
1569
+ ]) : {}
1570
+ },
1571
+ input: `${initialize}
1572
+ ${initialized}
1573
+ ${list}
1574
+ `,
1575
+ maxBuffer: 4 * 1024 * 1024,
1576
+ timeout: 5e3
1577
+ });
1578
+ if (result.error !== void 0 || result.status !== 0) {
1579
+ const stderr = result.stderr.trim();
1580
+ const reason = result.error?.message ?? (stderr.length > 0 ? stderr : `exited ${result.status}`);
1581
+ return { detail: `its MCP transport failed to start: ${reason}`, status: "fail" };
1582
+ }
1583
+ const responses = result.stdout.split(/\r?\n/u).flatMap((line) => {
1584
+ try {
1585
+ return [JSON.parse(line)];
1586
+ } catch {
1587
+ return [];
1588
+ }
1589
+ }).map(record).filter((value) => value !== void 0);
1590
+ const initializeResponse = responses.find(({ id }) => id === 1);
1591
+ const listResponse = responses.find(({ id }) => id === 2);
1592
+ const tools = record(listResponse?.result)?.tools;
1593
+ if (record(initializeResponse?.result) === void 0 || !Array.isArray(tools) || tools.length === 0) {
1594
+ return {
1595
+ detail: "its MCP transport did not complete initialize and advertise tools",
1596
+ status: "fail"
1597
+ };
1598
+ }
1599
+ return { detail: `transport initialized and advertised ${tools.length} tool(s)`, status: "ok" };
1600
+ }
1601
+ function mcpSummary(serverChecks) {
1602
+ const failed = serverChecks.filter(({ status: status2 }) => status2 === "fail").length;
1603
+ const warned = serverChecks.filter(({ status: status2 }) => status2 === "warn").length;
1604
+ const status = failed > 0 ? "fail" : warned > 0 ? "warn" : "ok";
1605
+ return {
1606
+ detail: status === "ok" ? "all three configured MCP servers resolve" : `${serverChecks.length - failed - warned} server(s) resolve; ${warned} reachable by npx only; ${failed} malformed or missing`,
1607
+ fix: status === "ok" ? void 0 : "Inspect the per-server capability search checks below.",
1608
+ name: "capability search",
1609
+ status
1610
+ };
1611
+ }
1612
+ function capabilitySearchChecks(snapshot) {
1613
+ const config = mcpConfig(snapshot);
1614
+ if (config.kind === "missing") {
1615
+ return [
1616
+ {
1617
+ detail: "no .mcp.json, so an agent here cannot search engine capabilities and will hand-write what exists",
1618
+ fix: "Restore the .mcp.json a scaffolded project ships, which wires the ThreeNative MCP servers.",
1619
+ name: "capability search",
1620
+ status: "fail"
1621
+ }
1622
+ ];
1623
+ }
1624
+ if (config.kind === "malformed") {
1625
+ return [
1626
+ {
1627
+ detail: `.mcp.json is malformed: ${config.detail}`,
1628
+ fix: "Restore a valid generated .mcp.json, preserving any unrelated servers.",
1629
+ name: "capability search",
1630
+ status: "fail"
1631
+ }
1632
+ ];
1633
+ }
1634
+ const serverChecks = MCP_SERVER_SPECS.map(
1635
+ (spec) => mcpServerCheck(snapshot, spec, config.servers[spec.configName])
1636
+ );
1637
+ return [mcpSummary(serverChecks), ...serverChecks];
1638
+ }
1639
+ function readJsonSync(file) {
1640
+ try {
1641
+ return JSON.parse(readFileSync(file, "utf8"));
1642
+ } catch {
1643
+ return void 0;
1644
+ }
1645
+ }
1646
+ function addCommandTargets(targets, value) {
1647
+ if (typeof value !== "string") return;
1648
+ for (const match of value.matchAll(/--target(?:=|\s+)(web|desktop|android|ios)\b/gu)) {
1649
+ const target = match[1];
1650
+ if (target !== void 0) targets.add(target);
1651
+ }
1652
+ }
1653
+ function addConfiguredTargets(targets, value) {
1654
+ if (Array.isArray(value)) {
1655
+ for (const target of value) if (typeof target === "string") targets.add(target);
1656
+ } else if (typeof value === "string") {
1657
+ targets.add(value);
1658
+ }
1659
+ }
1660
+ function configuredTargets(snapshot) {
1661
+ const targets = /* @__PURE__ */ new Set();
1662
+ const packageScripts = record(record(snapshot.packageJson)?.scripts);
1663
+ for (const value of Object.values(packageScripts ?? {})) addCommandTargets(targets, value);
1664
+ const configRecord = record(snapshot.config);
1665
+ for (const key of ["targets", "nativeTargets"])
1666
+ addConfiguredTargets(targets, configRecord?.[key]);
1667
+ return [...targets];
1668
+ }
1669
+ function directoryCanBeWritten(snapshot, relative) {
1670
+ if (snapshot.directoryWritable !== void 0) return snapshot.directoryWritable(relative);
1671
+ if (snapshot.projectRoot === void 0) return void 0;
1672
+ const root = path2.resolve(snapshot.projectRoot);
1673
+ let candidate = path2.resolve(root, relative);
1674
+ if (candidate !== root && !candidate.startsWith(`${root}${path2.sep}`)) return false;
1675
+ while (candidate !== root && !existsSync(candidate)) candidate = path2.dirname(candidate);
1676
+ if (!existsSync(candidate)) return false;
1677
+ try {
1678
+ if (!statSync(candidate).isDirectory()) return false;
1679
+ accessSync(candidate, constants.W_OK);
1680
+ return true;
1681
+ } catch {
1682
+ return false;
1683
+ }
1684
+ }
1685
+ function assetPipelineCheck(snapshot) {
1686
+ const details = [];
1687
+ let status = "ok";
1688
+ for (const directory of ASSET_DOWNLOAD_DIRECTORIES) {
1689
+ const writable = directoryCanBeWritten(snapshot, directory);
1690
+ if (writable === false) {
1691
+ details.push(`${directory} is not writable and cannot receive MCP downloads`);
1692
+ status = "warn";
1693
+ } else if (writable === true) {
1694
+ details.push(`${directory} exists or can be created`);
1695
+ } else {
1696
+ details.push(`${directory} was not probed in this in-memory snapshot`);
1697
+ }
1698
+ }
1699
+ const assets = record(record(snapshot.config)?.assets) ?? {};
1700
+ const mobileTargets = configuredTargets(snapshot).filter(
1701
+ (target) => target === "android" || target === "ios"
1702
+ );
1703
+ if (mobileTargets.length > 0) {
1704
+ const textures = assets.textures;
1705
+ if (textures !== "none") {
1706
+ details.push(
1707
+ `TN_NATIVE_KTX2_UNSUPPORTED: assets.textures compiles textures for ${mobileTargets.join("/")}; mobile native targets require assets.textures to be "none"`
1708
+ );
1709
+ status = "warn";
1710
+ }
1711
+ const models = assets.models;
1712
+ if (models !== "none") {
1713
+ details.push(
1714
+ `TN_NATIVE_MESH_COMPRESSION_UNSUPPORTED: assets.models compiles model geometry for ${mobileTargets.join("/")}; mobile native targets require assets.models to be "none"`
1715
+ );
1716
+ status = "warn";
1717
+ }
1718
+ }
1719
+ return {
1720
+ detail: details.join("; "),
1721
+ ...status === "ok" ? {} : {
1722
+ fix: "Make public/assets and public/audio writable, and disable compiled assets for Android/iOS native builds."
1723
+ },
1724
+ name: "asset pipeline",
1725
+ status
1726
+ };
1727
+ }
1728
+ function androidToolchainStatus(probe) {
1729
+ const details = [];
1730
+ let status = probe.status ?? "ok";
1731
+ if (probe.jdkVersion === void 0 || probe.jdkMajor === void 0) {
1732
+ details.push(`JDK not found; Android builds require JDK ${ANDROID_JDK_MAJOR}`);
1733
+ status = "warn";
1734
+ } else if (probe.jdkMajor !== ANDROID_JDK_MAJOR) {
1735
+ details.push(
1736
+ `JDK ${probe.jdkVersion} found; Android builds support JDK ${ANDROID_JDK_MAJOR} only`
1737
+ );
1738
+ status = "warn";
1739
+ } else {
1740
+ details.push(`JDK ${probe.jdkVersion} found (supported JDK ${ANDROID_JDK_MAJOR})`);
1741
+ }
1742
+ if (probe.sdkVersion === void 0) {
1743
+ details.push(`Android SDK platform android-${ANDROID_COMPILE_SDK} not found`);
1744
+ status = "warn";
1745
+ } else {
1746
+ details.push(`Android SDK platform android-${ANDROID_COMPILE_SDK} ${probe.sdkVersion} found`);
1747
+ }
1748
+ return {
1749
+ detail: details.join("; "),
1750
+ fix: status === "ok" ? void 0 : `Install Android SDK platform android-${ANDROID_COMPILE_SDK} and JDK ${ANDROID_JDK_MAJOR}, or set ANDROID_HOME or ANDROID_SDK_ROOT and JAVA_HOME (or put JDK ${ANDROID_JDK_MAJOR} on PATH).`,
1751
+ name: "android toolchain",
1752
+ status
1753
+ };
1754
+ }
1755
+ function playtestRunner(snapshot) {
1756
+ if (snapshot.playtestRunnerPath !== void 0) return snapshot.playtestRunnerPath;
1757
+ return snapshot.projectRoot === void 0 ? void 0 : resolveBinaryFrom(snapshot.projectRoot, PLAYTEST_BINARY);
1758
+ }
1759
+ function missingPlaytestCheck(snapshot) {
1760
+ return {
1761
+ detail: snapshot.projectRoot === void 0 ? "runner was not probed in this in-memory snapshot" : "threenative-playtest is missing from node_modules/.bin",
1762
+ fix: "Install the test runner: npm install -D @threenative/playtest, then rerun doctor.",
1763
+ name: "playtest",
1764
+ status: snapshot.projectRoot === void 0 ? "warn" : "fail"
1765
+ };
1766
+ }
1767
+ function childOutput(value) {
1768
+ const text = typeof value === "string" ? value : Buffer.isBuffer(value) ? value.toString("utf8") : void 0;
1769
+ const trimmed = text?.trim();
1770
+ return trimmed === void 0 || trimmed.length === 0 ? void 0 : trimmed;
1771
+ }
1772
+ function playtestFailureDetail(error) {
1773
+ const fields = record(error);
1774
+ const output = [childOutput(fields?.stderr), childOutput(fields?.stdout)].filter((value) => value !== void 0).join("\n");
1775
+ return output.length > 0 ? output : error instanceof Error ? error.message : String(error);
1776
+ }
1777
+ function playtestInvocation(runner) {
1778
+ if (process.platform !== "win32" || !/\.cmd$/iu.test(runner)) {
1779
+ return { args: ["doctor", "--text"], command: runner };
1780
+ }
1781
+ const command = process.env.ComSpec ?? process.env.COMSPEC ?? "cmd.exe";
1782
+ return {
1783
+ args: ["/d", "/s", "/c", `"${runner}" doctor --text`],
1784
+ command
1785
+ };
1786
+ }
1787
+ function executePlaytestDoctor(runner, projectRoot) {
1788
+ const invocation = playtestInvocation(runner);
1789
+ return execFileSync(invocation.command, invocation.args, {
1790
+ cwd: projectRoot,
1791
+ encoding: "utf8",
1792
+ stdio: ["ignore", "pipe", "pipe"],
1793
+ timeout: 3e4
1794
+ });
1795
+ }
1796
+ function playtestCheck(snapshot) {
1797
+ const runner = playtestRunner(snapshot);
1798
+ if (runner === void 0) return missingPlaytestCheck(snapshot);
1799
+ try {
1800
+ const output = snapshot.runPlaytestDoctor?.() ?? executePlaytestDoctor(runner, snapshot.projectRoot);
1801
+ const detail = output.trim();
1802
+ return {
1803
+ detail: detail.length === 0 ? "threenative-playtest doctor completed" : `threenative-playtest doctor completed:
1804
+ ${detail}`,
1805
+ name: "playtest",
1806
+ status: "ok"
1807
+ };
1808
+ } catch (error) {
1809
+ return {
1810
+ detail: `threenative-playtest doctor failed: ${playtestFailureDetail(error)}`,
1811
+ fix: "Run npx @threenative/playtest doctor --text directly and fix the first reported machine or browser blocker.",
1812
+ name: "playtest",
1813
+ status: "fail"
1814
+ };
1815
+ }
1816
+ }
1817
+ var APK_SIZE_RECORD = /^docs\/verification\/apk-size-(\d{4}-\d{2}-\d{2})\.md$/u;
1818
+ function parseApkSizeRecord(source) {
1819
+ const bytesMatch = source.match(/^\s*-\s*Rebuilt APK bytes:\s*\*\*(\d[\d,]*)\*\*\s*$/mu);
1820
+ const artifactMatch = source.match(/^\s*-\s*APK artifact:\s*`([^`]+)`\s*$/mu);
1821
+ const buildDirectoryMatch = source.match(/^\s*-\s*Build directory:\s*`([^`]+)`\s*$/mu);
1822
+ const sha256Match = source.match(/^\s*-\s*APK SHA-256:\s*`([0-9a-f]{64})`\s*$/imu);
1823
+ if (bytesMatch === null || artifactMatch === null || buildDirectoryMatch === null || sha256Match === null)
1824
+ return void 0;
1825
+ const bytesText = bytesMatch[1];
1826
+ const artifact = artifactMatch[1];
1827
+ const buildDirectory = buildDirectoryMatch[1];
1828
+ const sha256 = sha256Match[1];
1829
+ if (bytesText === void 0 || artifact === void 0 || buildDirectory === void 0 || sha256 === void 0)
1830
+ return void 0;
1831
+ const bytes = Number(bytesText.replaceAll(",", ""));
1832
+ if (!Number.isSafeInteger(bytes) || bytes <= 0) return void 0;
1833
+ if (artifact.length === 0 || buildDirectory.length === 0) return void 0;
1834
+ return { artifact, buildDirectory, bytes, sha256: sha256.toLowerCase() };
1835
+ }
1836
+ function sha256File(file) {
1837
+ const hash = createHash("sha256");
1838
+ const descriptor = openSync(file, "r");
1839
+ const buffer = Buffer.allocUnsafe(1024 * 1024);
1840
+ try {
1841
+ let bytesRead = 0;
1842
+ do {
1843
+ bytesRead = readSync(descriptor, buffer, 0, buffer.length, null);
1844
+ if (bytesRead > 0) hash.update(buffer.subarray(0, bytesRead));
1845
+ } while (bytesRead > 0);
1846
+ return hash.digest("hex");
1847
+ } finally {
1848
+ closeSync(descriptor);
1849
+ }
1850
+ }
1851
+ function evidencePath(snapshot, relative) {
1852
+ if (snapshot.projectRoot === void 0 || path2.isAbsolute(relative)) return void 0;
1853
+ const root = path2.resolve(snapshot.projectRoot);
1854
+ const resolved = path2.resolve(root, relative);
1855
+ return resolved === root || resolved.startsWith(`${root}${path2.sep}`) ? resolved : void 0;
1856
+ }
1857
+ function evidenceExists(snapshot, relative, directory) {
1858
+ const absolute = evidencePath(snapshot, relative);
1859
+ if (absolute !== void 0) {
1860
+ try {
1861
+ const stats = statSync(absolute);
1862
+ return directory ? stats.isDirectory() : stats.isFile();
1863
+ } catch {
1864
+ return false;
1865
+ }
1866
+ }
1867
+ return snapshot.files.has(relative);
1868
+ }
1869
+ function apkSizeCheck(snapshot) {
1870
+ const recordPath = [...snapshot.files].filter((file) => APK_SIZE_RECORD.test(file)).sort().at(-1);
1871
+ if (recordPath === void 0) return void 0;
1872
+ const source = snapshot.readText(recordPath);
1873
+ const record2 = source === void 0 ? void 0 : parseApkSizeRecord(source);
1874
+ if (record2 === void 0) {
1875
+ return {
1876
+ detail: `attribution record ${recordPath} is malformed; no APK total was trusted`,
1877
+ fix: "Regenerate the record with the APK artifact, SHA-256, build directory, and rebuilt byte total.",
1878
+ name: "APK size",
1879
+ status: "warn"
1880
+ };
1881
+ }
1882
+ if (!evidenceExists(snapshot, record2.buildDirectory, true)) {
1883
+ return {
1884
+ detail: `missing evidence \u2014 attribution record ${recordPath} names build directory ${record2.buildDirectory}, which is missing`,
1885
+ fix: "Rebuild the recorded Android variant before using its attribution total.",
1886
+ name: "APK size",
1887
+ status: "warn"
1888
+ };
1889
+ }
1890
+ const artifact = evidencePath(snapshot, record2.artifact);
1891
+ if (!evidenceExists(snapshot, record2.artifact, false) || artifact === void 0) {
1892
+ return {
1893
+ detail: `missing evidence \u2014 attribution record ${recordPath} names APK artifact ${record2.artifact}, which is missing`,
1894
+ fix: "Rebuild the recorded Android variant before using its attribution total.",
1895
+ name: "APK size",
1896
+ status: "warn"
1897
+ };
1898
+ }
1899
+ let actualBytes;
1900
+ let actualSha256;
1901
+ try {
1902
+ actualBytes = statSync(artifact).size;
1903
+ actualSha256 = sha256File(artifact);
1904
+ } catch {
1905
+ return {
1906
+ detail: `missing evidence \u2014 APK artifact ${record2.artifact} could not be read`,
1907
+ fix: "Rebuild the recorded Android variant before using its attribution total.",
1908
+ name: "APK size",
1909
+ status: "warn"
1910
+ };
1911
+ }
1912
+ if (actualBytes !== record2.bytes) {
1913
+ return {
1914
+ detail: `evidence differs \u2014 ${record2.artifact} is ${actualBytes.toLocaleString("en-US")} bytes, but ${recordPath} records a different total`,
1915
+ fix: "Regenerate the attribution record from this APK before trusting its rows.",
1916
+ name: "APK size",
1917
+ status: "warn"
1918
+ };
1919
+ }
1920
+ if (actualSha256 !== record2.sha256) {
1921
+ return {
1922
+ detail: `evidence differs \u2014 ${record2.artifact} has SHA-256 ${actualSha256}, but ${recordPath} records ${record2.sha256}`,
1923
+ fix: "Regenerate the attribution record from this APK before trusting its rows.",
1924
+ name: "APK size",
1925
+ status: "warn"
1926
+ };
1927
+ }
1928
+ return {
1929
+ detail: `last attributed APK: ${record2.bytes.toLocaleString("en-US")} bytes (${recordPath})`,
1930
+ name: "APK size",
1931
+ status: "ok"
1932
+ };
1933
+ }
1934
+ function dependencyChecks(snapshot) {
1935
+ const declared = declaredDependencies(snapshot.packageJson);
1936
+ const missing = declared.filter((name) => !snapshot.installedVersions.has(name));
1937
+ const installed = [...snapshot.installedVersions].sort(([a], [b]) => a.localeCompare(b));
1938
+ const versions = new Set(installed.map(([, version]) => version));
1939
+ return [
1940
+ missing.length > 0 ? {
1941
+ detail: `declared but not installed: ${missing.join(", ")}`,
1942
+ fix: "Install dependencies: 'npm install' (or the package manager this project uses).",
1943
+ name: "dependencies",
1944
+ status: "fail"
1945
+ } : {
1946
+ detail: declared.length === 0 ? "no @threenative packages declared" : `${declared.length} installed`,
1947
+ name: "dependencies",
1948
+ status: "ok"
1949
+ },
1950
+ versions.size > 1 ? {
1951
+ detail: `@threenative packages disagree on version: ${installed.map(([name, version]) => `${name}@${version}`).join(", ")}`,
1952
+ fix: "Install one version across all @threenative packages; mixed versions break at the package boundary.",
1953
+ name: "versions",
1954
+ status: "fail"
1955
+ } : {
1956
+ detail: versions.size === 0 ? "nothing installed to compare" : `all at ${[...versions][0]}`,
1957
+ name: "versions",
1958
+ status: "ok"
1959
+ }
1960
+ ];
1961
+ }
1962
+ function nativeEntryCheck(snapshot) {
1963
+ const entry = nativeEntryFrom(snapshot.config);
1964
+ if (!snapshot.files.has(entry)) {
1965
+ return {
1966
+ detail: `the portable entry ${entry} does not exist, so a native build has nothing to start`,
1967
+ fix: `Create ${entry} with a default game export, or point threenative.nativeEntry at the file that has one.`,
1968
+ name: "native entry",
1969
+ status: "fail"
1970
+ };
1971
+ }
1972
+ const source = snapshot.readText(entry) ?? "";
1973
+ if (!/export\s+default\b/u.test(source)) {
1974
+ return {
1975
+ detail: `${entry} has no default export; the native host rejects it with TN_NATIVE_ENTRY_NO_DEFAULT`,
1976
+ fix: `Add 'export default' to the game defined in ${entry}.`,
1977
+ name: "native entry",
1978
+ status: "fail"
1979
+ };
1980
+ }
1981
+ return { detail: `${entry} default-exports a game`, name: "native entry", status: "ok" };
1982
+ }
1983
+ function nativeRuntimeKey() {
1984
+ return `${process.platform}-${process.arch}`;
1985
+ }
1986
+ function nativeRuntimeFilename() {
1987
+ return process.platform === "win32" ? "threenative-runtime.exe" : "threenative-runtime";
1988
+ }
1989
+ function nativeRuntimeCheck(snapshot) {
1990
+ const key = nativeRuntimeKey();
1991
+ if (snapshot.runtimeRoot === void 0 || snapshot.readRuntimeText === void 0) {
1992
+ return snapshot.installedVersions.has(RUNTIME_PACKAGE) ? {
1993
+ detail: `unavailable \u2014 ${RUNTIME_PACKAGE} is installed but its package root could not be resolved`,
1994
+ fix: "Reinstall dependencies so the native runtime package resolves from node_modules.",
1995
+ name: "native runtime",
1996
+ status: "fail"
1997
+ } : {
1998
+ detail: "unknown \u2014 no install status recorded",
1999
+ fix: "Install @threenative/runtime-native before building a native target.",
2000
+ name: "native runtime",
2001
+ status: "warn"
2002
+ };
2003
+ }
2004
+ const statusText = snapshot.readRuntimeText("prebuilt/install-status.json");
2005
+ if (statusText === void 0) {
2006
+ return {
2007
+ detail: "unknown \u2014 no install status recorded",
2008
+ fix: "Run npm install so the runtime install hook can record its result.",
2009
+ name: "native runtime",
2010
+ status: "warn"
2011
+ };
2012
+ }
2013
+ let status;
2014
+ try {
2015
+ const parsed = JSON.parse(statusText);
2016
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))
2017
+ throw new Error("status is not an object");
2018
+ status = parsed;
2019
+ } catch (error) {
2020
+ return {
2021
+ detail: `unavailable \u2014 install status is malformed: ${error instanceof Error ? error.message : String(error)}`,
2022
+ fix: "Remove node_modules/@threenative/runtime-native and run npm install again.",
2023
+ name: "native runtime",
2024
+ status: "fail"
2025
+ };
2026
+ }
2027
+ if (status.ok !== true) {
2028
+ const reason = typeof status.reason === "string" ? status.reason : "the install hook recorded no reason";
2029
+ return {
2030
+ detail: `unavailable \u2014 ${key}: ${reason}`,
2031
+ fix: "Fix the recorded prebuilt download failure, then run npm install again.",
2032
+ name: "native runtime",
2033
+ status: "fail"
2034
+ };
2035
+ }
2036
+ if (status.key !== key) {
2037
+ return {
2038
+ detail: `unavailable \u2014 install status is for ${String(status.key ?? "an unknown target")}, not ${key}`,
2039
+ fix: "Remove the runtime package and run npm install on this platform.",
2040
+ name: "native runtime",
2041
+ status: "fail"
2042
+ };
2043
+ }
2044
+ const installedVersion = snapshot.installedVersions.get(RUNTIME_PACKAGE);
2045
+ if (status.version !== installedVersion) {
2046
+ return {
2047
+ detail: `unavailable \u2014 install status version ${String(status.version ?? "is missing")} does not match installed runtime ${String(installedVersion ?? "with no version")}`,
2048
+ fix: "Remove the runtime package and run npm install to refresh its prebuilt status.",
2049
+ name: "native runtime",
2050
+ status: "fail"
2051
+ };
2052
+ }
2053
+ if (snapshot.runtimeManifestUrl === void 0) {
2054
+ return {
2055
+ detail: "unavailable \u2014 the installed runtime release URL contract could not be loaded",
2056
+ fix: "Reinstall @threenative/runtime-native so scripts/install-prebuilt.mjs is present.",
2057
+ name: "native runtime",
2058
+ status: "fail"
2059
+ };
2060
+ }
2061
+ if (status.url !== snapshot.runtimeManifestUrl) {
2062
+ return {
2063
+ detail: `unavailable \u2014 install status release URL ${String(status.url ?? "is missing")} does not match ${snapshot.runtimeManifestUrl}`,
2064
+ fix: "Remove the runtime package and run npm install to fetch the current release manifest.",
2065
+ name: "native runtime",
2066
+ status: "fail"
2067
+ };
2068
+ }
2069
+ const binary = `prebuilt/${key}/${nativeRuntimeFilename()}`;
2070
+ const exists = snapshot.runtimeFileExists?.(binary) ?? existsSync(path2.join(snapshot.runtimeRoot, binary));
2071
+ if (!exists) {
2072
+ return {
2073
+ detail: `unavailable \u2014 ${key} prebuilt binary is missing`,
2074
+ fix: "Run npm install again to restore the native runtime prebuilt.",
2075
+ name: "native runtime",
2076
+ status: "fail"
2077
+ };
2078
+ }
2079
+ return { detail: `available (${key})`, name: "native runtime", status: "ok" };
2080
+ }
2081
+ function javaVersion(output) {
2082
+ const match = output.match(/version\s+["']([^"']+)["']/iu);
2083
+ const version = match?.[1];
2084
+ if (version === void 0) return void 0;
2085
+ const majorMatch = version.startsWith("1.") ? version.match(/^1\.(\d+)/u) : version.match(/^(\d+)/u);
2086
+ const majorText = majorMatch?.[1];
2087
+ const major = majorText === void 0 ? Number.NaN : Number(majorText);
2088
+ return Number.isSafeInteger(major) ? { major, version } : void 0;
2089
+ }
2090
+ function androidSdkVersion(root) {
2091
+ const sourceProperties = path2.join(
2092
+ root,
2093
+ "platforms",
2094
+ `android-${ANDROID_COMPILE_SDK}`,
2095
+ "source.properties"
2096
+ );
2097
+ try {
2098
+ const source = readFileSync(sourceProperties, "utf8");
2099
+ const match = source.match(/^Pkg\.Revision\s*=\s*(\S+)/mu);
2100
+ return match?.[1];
2101
+ } catch {
2102
+ return void 0;
2103
+ }
2104
+ }
2105
+ function probeAndroidToolchain(environment = process.env) {
2106
+ const javaHome = environment.JAVA_HOME?.trim() || void 0;
2107
+ const java = javaHome === void 0 ? "java" : path2.join(javaHome, "bin", process.platform === "win32" ? "java.exe" : "java");
2108
+ let jdkMajor;
2109
+ let jdkVersion;
2110
+ try {
2111
+ const result = spawnSync(java, ["-version"], {
2112
+ encoding: "utf8",
2113
+ env: { ...environment },
2114
+ stdio: ["ignore", "pipe", "pipe"],
2115
+ timeout: 5e3
2116
+ });
2117
+ const parsed = javaVersion(`${result.stdout ?? ""}${result.stderr ?? ""}`);
2118
+ jdkMajor = parsed?.major;
2119
+ jdkVersion = parsed?.version;
2120
+ } catch {
2121
+ }
2122
+ const sdkCandidates = [
2123
+ environment.ANDROID_HOME,
2124
+ environment.ANDROID_SDK_ROOT,
2125
+ path2.join(homedir(), "Android", "Sdk")
2126
+ ].map((candidate) => candidate?.trim()).filter((candidate) => candidate !== void 0 && candidate.length > 0);
2127
+ const sdkRoot = sdkCandidates.find((candidate) => existsSync(candidate));
2128
+ return {
2129
+ ...jdkMajor === void 0 ? {} : { jdkMajor },
2130
+ ...jdkVersion === void 0 ? {} : { jdkVersion },
2131
+ ...sdkRoot === void 0 ? {} : { sdkVersion: androidSdkVersion(sdkRoot) }
2132
+ };
2133
+ }
2134
+ function runtimeFileAvailable(snapshot, relative) {
2135
+ if (snapshot.runtimeRoot === void 0) return false;
2136
+ return snapshot.runtimeFileExists?.(relative) ?? existsSync(path2.join(snapshot.runtimeRoot, relative));
2137
+ }
2138
+ function androidTargetCheck(snapshot) {
2139
+ if (!runtimeFileAvailable(snapshot, "scripts/package-android.mjs")) {
2140
+ return {
2141
+ detail: "unavailable \u2014 @threenative/runtime-native has no Android packager",
2142
+ name: "target android",
2143
+ status: snapshot.runtimeRoot === void 0 ? "warn" : "fail"
2144
+ };
2145
+ }
2146
+ const androidToolchain = snapshot.androidToolchain ?? (snapshot.projectRoot === void 0 ? void 0 : probeAndroidToolchain());
2147
+ const toolchain = androidToolchain === void 0 ? void 0 : androidToolchainStatus(androidToolchain);
2148
+ return {
2149
+ detail: toolchain === void 0 ? "available \u2014 runtime packager installed; Android toolchain was not probed in this in-memory snapshot" : `available \u2014 runtime packager installed; ${toolchain.detail}`,
2150
+ ...toolchain?.fix === void 0 ? {} : { fix: toolchain.fix },
2151
+ name: "target android",
2152
+ status: toolchain?.status ?? "ok"
2153
+ };
2154
+ }
2155
+ function iosTargetCheck(snapshot) {
2156
+ const iosPackager = runtimeFileAvailable(snapshot, "scripts/package-ios.mjs");
2157
+ const iosHost = process.platform === "darwin" && process.arch === "arm64";
2158
+ if (iosHost && iosPackager) {
2159
+ return {
2160
+ detail: "available \u2014 darwin-arm64 simulator packager installed",
2161
+ name: "target ios",
2162
+ status: "ok"
2163
+ };
2164
+ }
2165
+ return {
2166
+ detail: iosHost ? "unavailable \u2014 @threenative/runtime-native has no iOS packager" : `unavailable \u2014 iOS simulator packaging requires darwin-arm64; received ${process.platform}-${process.arch}`,
2167
+ name: "target ios",
2168
+ status: iosHost ? "fail" : "warn"
2169
+ };
2170
+ }
2171
+ function targetChecks(snapshot, nativeRuntime) {
2172
+ const webAvailable = snapshot.files.has("src/main.ts");
2173
+ const desktopDetail = nativeRuntime.status === "ok" ? nativeRuntime.detail : `unavailable \u2014 ${nativeRuntime.detail.replace(/^(?:unavailable|unknown) — /u, "")}`;
2174
+ return [
2175
+ webAvailable ? { detail: "available \u2014 src/main.ts", name: "target web", status: "ok" } : {
2176
+ detail: "unavailable \u2014 src/main.ts is missing",
2177
+ name: "target web",
2178
+ status: "warn"
2179
+ },
2180
+ {
2181
+ detail: desktopDetail,
2182
+ name: "target desktop",
2183
+ status: nativeRuntime.status
2184
+ },
2185
+ androidTargetCheck(snapshot),
2186
+ iosTargetCheck(snapshot)
2187
+ ];
2188
+ }
2189
+ function desktopOverlayCheck(probe) {
2190
+ return {
2191
+ detail: probe.detail,
2192
+ fix: probe.fix,
2193
+ name: "desktop overlay",
2194
+ status: probe.status
2195
+ };
2196
+ }
2197
+ function diagnoseProject(snapshot) {
2198
+ if (record(snapshot.packageJson) === void 0) {
2199
+ return {
2200
+ checks: [
2201
+ {
2202
+ detail: "no readable package.json in this directory",
2203
+ fix: "Run this inside a generated project, or scaffold one with 'npm create threenative@latest'.",
2204
+ name: "package.json",
2205
+ status: "fail"
2206
+ }
2207
+ ],
2208
+ pass: false
2209
+ };
2210
+ }
2211
+ const hasPlaytests = [...snapshot.files].some((file) => file.endsWith(".playtest.json"));
2212
+ const nativeRuntime = nativeRuntimeCheck(snapshot);
2213
+ const apkSize = apkSizeCheck(snapshot);
2214
+ const playtest = playtestCheck(snapshot);
2215
+ const checks = [
2216
+ { detail: "readable", name: "package.json", status: "ok" },
2217
+ ...dependencyChecks(snapshot),
2218
+ nativeEntryCheck(snapshot),
2219
+ nativeRuntime,
2220
+ assetPipelineCheck(snapshot),
2221
+ ...apkSize === void 0 ? [] : [apkSize],
2222
+ ...!usesDesktopOverlay(snapshot.config) || snapshot.desktopOverlay === void 0 ? [] : [desktopOverlayCheck(snapshot.desktopOverlay)],
2223
+ ...targetChecks(snapshot, nativeRuntime),
2224
+ snapshot.files.has("src/main.ts") ? { detail: "src/main.ts is the web entry", name: "web entry", status: "ok" } : {
2225
+ detail: "no src/main.ts, so 'threenative build' has no web entry to bundle",
2226
+ fix: "Add src/main.ts, which mounts the game and any browser-only UI.",
2227
+ name: "web entry",
2228
+ status: "warn"
2229
+ },
2230
+ playtest,
2231
+ hasPlaytests ? { detail: "at least one scenario can prove this game", name: "playtests", status: "ok" } : {
2232
+ detail: "no *.playtest.json scenario, so nothing here proves the game runs",
2233
+ fix: "Create one: 'npx @threenative/playtest init'.",
2234
+ name: "playtests",
2235
+ status: "warn"
2236
+ },
2237
+ ...capabilitySearchChecks(snapshot)
2238
+ ];
2239
+ return { checks, pass: checks.every(({ status }) => status !== "fail") };
2240
+ }
2241
+ async function collectFiles(root, relative = "", depth = 0) {
2242
+ if (depth > 3) return [];
2243
+ const absolute = path2.join(root, relative);
2244
+ if (!existsSync(absolute)) return [];
2245
+ const entries = await readdir(absolute, { withFileTypes: true });
2246
+ const files = [];
2247
+ for (const entry of entries) {
2248
+ if (entry.name === "node_modules" || entry.name.startsWith(".git")) continue;
2249
+ const next = relative === "" ? entry.name : `${relative}/${entry.name}`;
2250
+ if (entry.isDirectory()) files.push(...await collectFiles(root, next, depth + 1));
2251
+ else files.push(next);
2252
+ }
2253
+ return files;
2254
+ }
2255
+ async function readJson(file) {
2256
+ try {
2257
+ return JSON.parse(await readFile(file, "utf8"));
2258
+ } catch {
2259
+ return void 0;
2260
+ }
2261
+ }
2262
+ async function runtimeReleaseManifestUrl(runtimeRoot, version) {
2263
+ try {
2264
+ const module = await import(pathToFileURL(path2.join(runtimeRoot, "scripts", "install-prebuilt.mjs")).href);
2265
+ const releaseUrl = record(module)?.releaseManifestUrl;
2266
+ if (typeof releaseUrl !== "function") return void 0;
2267
+ const result = releaseUrl(version);
2268
+ return typeof result === "string" ? result : void 0;
2269
+ } catch {
2270
+ return void 0;
2271
+ }
2272
+ }
2273
+ async function readProject(root) {
2274
+ const projectRoot = path2.resolve(root);
2275
+ const packageJson = await readJson(path2.join(projectRoot, "package.json"));
2276
+ const typeScriptConfig = path2.join(projectRoot, "threenative.config.ts");
2277
+ const config = existsSync(typeScriptConfig) ? await readTypeScriptConfig(projectRoot) : nativeEntryCompat(record(packageJson)?.threenative);
2278
+ const files = new Set(await collectFiles(projectRoot));
2279
+ const installedVersions = /* @__PURE__ */ new Map();
2280
+ for (const name of declaredDependencies(packageJson)) {
2281
+ const manifest = await readJson(path2.join(projectRoot, "node_modules", name, "package.json"));
2282
+ const version = record(manifest)?.version;
2283
+ if (typeof version === "string") installedVersions.set(name, version);
2284
+ }
2285
+ const runtimeRoot = installedVersions.has(RUNTIME_PACKAGE) ? (() => {
2286
+ const candidate = path2.join(projectRoot, "node_modules", RUNTIME_PACKAGE);
2287
+ try {
2288
+ return realpathSync(candidate);
2289
+ } catch {
2290
+ return void 0;
2291
+ }
2292
+ })() : void 0;
2293
+ const runtimeVersion = installedVersions.get(RUNTIME_PACKAGE);
2294
+ const runtimeManifestUrl = runtimeRoot === void 0 || runtimeVersion === void 0 ? void 0 : await runtimeReleaseManifestUrl(runtimeRoot, runtimeVersion);
2295
+ const playtestRunnerPath = resolveBinaryFrom(projectRoot, PLAYTEST_BINARY);
2296
+ const mcpServerHealth = /* @__PURE__ */ new Map();
2297
+ if (files.has(".mcp.json")) {
2298
+ for (const spec of MCP_SERVER_SPECS) {
2299
+ if (existsSync(path2.resolve(projectRoot, spec.expectedArgs))) {
2300
+ mcpServerHealth.set(spec.configName, probeMcpServer(projectRoot, spec));
2301
+ }
2302
+ }
2303
+ }
2304
+ return {
2305
+ config,
2306
+ files,
2307
+ installedVersions,
2308
+ mcpServerHealth,
2309
+ packageJson,
2310
+ projectRoot,
2311
+ readText: (relative) => {
2312
+ const file = path2.join(projectRoot, relative);
2313
+ try {
2314
+ return existsSync(file) ? readFileSync(file, "utf8") : void 0;
2315
+ } catch {
2316
+ return void 0;
2317
+ }
2318
+ },
2319
+ androidToolchain: probeAndroidToolchain(),
2320
+ ...usesDesktopOverlay(config) ? { desktopOverlay: probeDesktopOverlay() } : {},
2321
+ ...playtestRunnerPath === void 0 ? {} : {
2322
+ playtestRunnerPath,
2323
+ runPlaytestDoctor: () => executePlaytestDoctor(playtestRunnerPath, projectRoot)
2324
+ },
2325
+ ...runtimeRoot === void 0 ? {} : {
2326
+ readRuntimeText: (relative) => {
2327
+ try {
2328
+ return readFileSync(path2.join(runtimeRoot, relative), "utf8");
2329
+ } catch {
2330
+ return void 0;
2331
+ }
2332
+ },
2333
+ runtimeFileExists: (relative) => existsSync(path2.join(runtimeRoot, relative)),
2334
+ ...runtimeManifestUrl === void 0 ? {} : { runtimeManifestUrl },
2335
+ runtimeRoot
2336
+ }
2337
+ };
2338
+ }
2339
+ async function readTypeScriptConfig(root) {
2340
+ try {
2341
+ return await loadConfig(root);
2342
+ } catch {
2343
+ return void 0;
2344
+ }
2345
+ }
2346
+ function formatDoctorReport(report) {
2347
+ const symbols = { fail: "\u2717", ok: "\u2713", warn: "!" };
2348
+ const isBaseline = (name) => ["package.json", "dependencies", "versions"].includes(name);
2349
+ const isCraft = (name) => name.startsWith("capability search");
2350
+ const isTest = (name) => name === "playtest" || name === "playtests";
2351
+ const groups = [
2352
+ ["Baseline", isBaseline],
2353
+ ["Craft", isCraft],
2354
+ ["Test", isTest],
2355
+ ["Ship", (name) => !isBaseline(name) && !isCraft(name) && !isTest(name)]
2356
+ ];
2357
+ const lines = [];
2358
+ for (const [group, belongs] of groups) {
2359
+ const checks = report.checks.filter(({ name }) => belongs(name));
2360
+ if (checks.length === 0) continue;
2361
+ lines.push(`${group}:`);
2362
+ lines.push(
2363
+ ...checks.map(
2364
+ ({ detail, fix, name, status }) => `${symbols[status]} ${name}: ${detail}${fix === void 0 || status === "ok" ? "" : `
2365
+ fix: ${fix}`}`
2366
+ )
2367
+ );
2368
+ }
2369
+ if (!report.pass) lines.push("\nAt least one check failed; fix it before trusting a build here.");
2370
+ return `${lines.join("\n")}
2371
+ `;
2372
+ }
2373
+
724
2374
  // src/threenative.ts
725
2375
  function cliHelp(command) {
726
2376
  if (command === "build") return buildHelp();
2377
+ if (command === "doctor") {
2378
+ return `${[
2379
+ "Usage: threenative doctor [--text]",
2380
+ "",
2381
+ "Checks this project against what the build and the native host assume about it:",
2382
+ "installed and version-matched @threenative packages, a portable entry that",
2383
+ "default-exports a game, a web entry, a scenario that can prove it, and the",
2384
+ "capability search an authoring agent needs.",
2385
+ "",
2386
+ "Prints JSON by default; --text prints the same report for a person.",
2387
+ "Exits 0 when nothing failed, 1 when a check failed."
2388
+ ].join("\n")}
2389
+ `;
2390
+ }
727
2391
  return `${[
728
- "Usage: threenative build [options]",
2392
+ "Usage: threenative <command> [options]",
729
2393
  "",
730
2394
  "Commands:",
731
- " build Build web or native output.",
2395
+ ...threenativeCommands.map((command2) => ` ${command2.padEnd(6)} ${commandSummaries[command2]}`),
732
2396
  "",
733
- "Run 'threenative build --help' for command-specific help."
2397
+ "Run 'threenative <command> --help' for command-specific help."
734
2398
  ].join("\n")}
735
2399
  `;
736
2400
  }
@@ -738,14 +2402,27 @@ function helpFor(argv) {
738
2402
  const command = argv[0];
739
2403
  if (command === void 0 || command.startsWith("-")) return cliHelp();
740
2404
  if (command === "build") return cliHelp("build");
2405
+ if (command === "doctor") return cliHelp("doctor");
741
2406
  throw new Error(`Unknown threenative command '${command}'.
742
2407
  ${cliHelp()}`);
743
2408
  }
2409
+ async function runDoctorCommand(argv, cwd = process.cwd()) {
2410
+ const report = diagnoseProject(await readProject(cwd));
2411
+ process.stdout.write(
2412
+ argv.includes("--text") ? formatDoctorReport(report) : `${JSON.stringify(report, null, 2)}
2413
+ `
2414
+ );
2415
+ return report.pass ? 0 : 1;
2416
+ }
744
2417
  async function main(argv = process.argv.slice(2)) {
745
2418
  if (argv.includes("--help") || argv.includes("-h")) {
746
2419
  process.stdout.write(helpFor(argv));
747
2420
  return;
748
2421
  }
2422
+ if (argv[0] === "doctor") {
2423
+ process.exitCode = await runDoctorCommand(argv.slice(1));
2424
+ return;
2425
+ }
749
2426
  await build(parseBuildArgs(argv));
750
2427
  }
751
2428
  main().catch((error) => {
@@ -754,4 +2431,4 @@ main().catch((error) => {
754
2431
  process.exitCode = 1;
755
2432
  });
756
2433
 
757
- export { cliHelp, main };
2434
+ export { cliHelp, main, runDoctorCommand };