mesheditor 0.0.0-stage → 1.0.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 (258) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +853 -2
  3. package/dist-lib/esm/AIAgentService.d.ts +106 -0
  4. package/dist-lib/esm/AIAgentService.js +1471 -0
  5. package/dist-lib/esm/MeshEditorApp.d.ts +412 -0
  6. package/dist-lib/esm/MeshEditorApp.js +9092 -0
  7. package/dist-lib/esm/MeshEditorService.d.ts +459 -0
  8. package/dist-lib/esm/MeshEditorService.js +7083 -0
  9. package/dist-lib/esm/Neural3DGeneratorService.d.ts +88 -0
  10. package/dist-lib/esm/Neural3DGeneratorService.js +1397 -0
  11. package/dist-lib/esm/adapters/BrowserPlatformAdapter.d.ts +16 -0
  12. package/dist-lib/esm/adapters/BrowserPlatformAdapter.js +25 -0
  13. package/dist-lib/esm/adapters/ElectronPlatformAdapter.d.ts +32 -0
  14. package/dist-lib/esm/adapters/ElectronPlatformAdapter.js +336 -0
  15. package/dist-lib/esm/adapters/HostAppAdapter.d.ts +54 -0
  16. package/dist-lib/esm/adapters/HostAppAdapter.js +75 -0
  17. package/dist-lib/esm/adapters/PlatformAdapter.d.ts +98 -0
  18. package/dist-lib/esm/adapters/PlatformAdapter.js +1 -0
  19. package/dist-lib/esm/adapters/index.d.ts +13 -0
  20. package/dist-lib/esm/adapters/index.js +15 -0
  21. package/dist-lib/esm/assets/fonts/Droid_Sans_Bold.json +1 -0
  22. package/dist-lib/esm/assets/fonts/Droid_Sans_Regular.json +1 -0
  23. package/dist-lib/esm/assets/fonts/Kenney_Future_Regular.json +1 -0
  24. package/dist-lib/esm/baking/TextureBaker.d.ts +84 -0
  25. package/dist-lib/esm/baking/TextureBaker.js +709 -0
  26. package/dist-lib/esm/builtInSkills.d.ts +19 -0
  27. package/dist-lib/esm/builtInSkills.js +186 -0
  28. package/dist-lib/esm/compression/ModelCompressor.d.ts +87 -0
  29. package/dist-lib/esm/compression/ModelCompressor.js +553 -0
  30. package/dist-lib/esm/decals/DecalController.d.ts +147 -0
  31. package/dist-lib/esm/decals/DecalController.js +1031 -0
  32. package/dist-lib/esm/decals/decalAssetUrls.d.ts +1 -0
  33. package/dist-lib/esm/decals/decalAssetUrls.js +16 -0
  34. package/dist-lib/esm/geometry/architecture.d.ts +114 -0
  35. package/dist-lib/esm/geometry/architecture.js +832 -0
  36. package/dist-lib/esm/geometry/bevelModifier.d.ts +59 -0
  37. package/dist-lib/esm/geometry/bevelModifier.js +345 -0
  38. package/dist-lib/esm/geometry/facetSurfaceUtils.d.ts +127 -0
  39. package/dist-lib/esm/geometry/facetSurfaceUtils.js +676 -0
  40. package/dist-lib/esm/geometry/roundedBox.d.ts +15 -0
  41. package/dist-lib/esm/geometry/roundedBox.js +133 -0
  42. package/dist-lib/esm/index.d.ts +21 -0
  43. package/dist-lib/esm/index.js +50 -0
  44. package/dist-lib/esm/pathExtrusion/PathExtrusionController.d.ts +59 -0
  45. package/dist-lib/esm/pathExtrusion/PathExtrusionController.js +483 -0
  46. package/dist-lib/esm/pathExtrusion/PathExtrusionStudio.d.ts +76 -0
  47. package/dist-lib/esm/pathExtrusion/PathExtrusionStudio.js +1792 -0
  48. package/dist-lib/esm/pathExtrusion/PathFactory.d.ts +95 -0
  49. package/dist-lib/esm/pathExtrusion/PathFactory.js +627 -0
  50. package/dist-lib/esm/pathExtrusion/index.d.ts +4 -0
  51. package/dist-lib/esm/pathExtrusion/index.js +4 -0
  52. package/dist-lib/esm/pathExtrusion/types.d.ts +50 -0
  53. package/dist-lib/esm/pathExtrusion/types.js +1 -0
  54. package/dist-lib/esm/plugin.d.ts +250 -0
  55. package/dist-lib/esm/plugin.js +144 -0
  56. package/dist-lib/esm/rigging/WeightPaintController.d.ts +162 -0
  57. package/dist-lib/esm/rigging/WeightPaintController.js +1421 -0
  58. package/dist-lib/esm/sculpting/SculptController.d.ts +146 -0
  59. package/dist-lib/esm/sculpting/SculptController.js +2038 -0
  60. package/dist-lib/esm/sdf/index.d.ts +2 -0
  61. package/dist-lib/esm/sdf/index.js +2 -0
  62. package/dist-lib/esm/sdf/sdfPrimitives.d.ts +97 -0
  63. package/dist-lib/esm/sdf/sdfPrimitives.js +402 -0
  64. package/dist-lib/esm/sdf/surfaceNets.d.ts +29 -0
  65. package/dist-lib/esm/sdf/surfaceNets.js +399 -0
  66. package/dist-lib/esm/styles.d.ts +11 -0
  67. package/dist-lib/esm/styles.js +32 -0
  68. package/dist-lib/esm/template.d.ts +12 -0
  69. package/dist-lib/esm/template.js +19 -0
  70. package/dist-lib/esm/textMesh/TextMeshController.d.ts +61 -0
  71. package/dist-lib/esm/textMesh/TextMeshController.js +405 -0
  72. package/dist-lib/esm/textures/AITextureGenerator.d.ts +119 -0
  73. package/dist-lib/esm/textures/AITextureGenerator.js +945 -0
  74. package/dist-lib/esm/textures/ExternalImageGeneratorService.d.ts +62 -0
  75. package/dist-lib/esm/textures/ExternalImageGeneratorService.js +879 -0
  76. package/dist-lib/esm/tools/AbstractTool.d.ts +68 -0
  77. package/dist-lib/esm/tools/AbstractTool.js +128 -0
  78. package/dist-lib/esm/tools/ToolExecutionContext.d.ts +40 -0
  79. package/dist-lib/esm/tools/ToolExecutionContext.js +1 -0
  80. package/dist-lib/esm/tools/ToolInterface.d.ts +104 -0
  81. package/dist-lib/esm/tools/ToolInterface.js +1 -0
  82. package/dist-lib/esm/tools/ToolRegistry.d.ts +43 -0
  83. package/dist-lib/esm/tools/ToolRegistry.js +115 -0
  84. package/dist-lib/esm/tools/builtin/ApplyMaterialTool.d.ts +34 -0
  85. package/dist-lib/esm/tools/builtin/ApplyMaterialTool.js +48 -0
  86. package/dist-lib/esm/tools/builtin/AutoUVMappingTool.d.ts +34 -0
  87. package/dist-lib/esm/tools/builtin/AutoUVMappingTool.js +54 -0
  88. package/dist-lib/esm/tools/builtin/BakeTexturesTool.d.ts +42 -0
  89. package/dist-lib/esm/tools/builtin/BakeTexturesTool.js +81 -0
  90. package/dist-lib/esm/tools/builtin/BooleanOperationTool.d.ts +51 -0
  91. package/dist-lib/esm/tools/builtin/BooleanOperationTool.js +86 -0
  92. package/dist-lib/esm/tools/builtin/BuildVoxelMeshTool.d.ts +78 -0
  93. package/dist-lib/esm/tools/builtin/BuildVoxelMeshTool.js +170 -0
  94. package/dist-lib/esm/tools/builtin/CloneArrayTool.d.ts +75 -0
  95. package/dist-lib/esm/tools/builtin/CloneArrayTool.js +115 -0
  96. package/dist-lib/esm/tools/builtin/CreateArchTool.d.ts +118 -0
  97. package/dist-lib/esm/tools/builtin/CreateArchTool.js +89 -0
  98. package/dist-lib/esm/tools/builtin/CreateColumnTool.d.ts +114 -0
  99. package/dist-lib/esm/tools/builtin/CreateColumnTool.js +105 -0
  100. package/dist-lib/esm/tools/builtin/CreateLatheTool.d.ts +87 -0
  101. package/dist-lib/esm/tools/builtin/CreateLatheTool.js +60 -0
  102. package/dist-lib/esm/tools/builtin/CreateMaterialTool.d.ts +114 -0
  103. package/dist-lib/esm/tools/builtin/CreateMaterialTool.js +212 -0
  104. package/dist-lib/esm/tools/builtin/CreateMoldingTool.d.ts +120 -0
  105. package/dist-lib/esm/tools/builtin/CreateMoldingTool.js +95 -0
  106. package/dist-lib/esm/tools/builtin/CreatePrimitiveTool.d.ts +162 -0
  107. package/dist-lib/esm/tools/builtin/CreatePrimitiveTool.js +302 -0
  108. package/dist-lib/esm/tools/builtin/CreateRoofTool.d.ts +120 -0
  109. package/dist-lib/esm/tools/builtin/CreateRoofTool.js +108 -0
  110. package/dist-lib/esm/tools/builtin/CreateRoundedBoxTool.d.ts +101 -0
  111. package/dist-lib/esm/tools/builtin/CreateRoundedBoxTool.js +79 -0
  112. package/dist-lib/esm/tools/builtin/CreateSdfMeshTool.d.ts +224 -0
  113. package/dist-lib/esm/tools/builtin/CreateSdfMeshTool.js +238 -0
  114. package/dist-lib/esm/tools/builtin/CreateStairsTool.d.ts +135 -0
  115. package/dist-lib/esm/tools/builtin/CreateStairsTool.js +119 -0
  116. package/dist-lib/esm/tools/builtin/CreateTextMeshTool.d.ts +94 -0
  117. package/dist-lib/esm/tools/builtin/CreateTextMeshTool.js +131 -0
  118. package/dist-lib/esm/tools/builtin/CreateTubeTool.d.ts +87 -0
  119. package/dist-lib/esm/tools/builtin/CreateTubeTool.js +59 -0
  120. package/dist-lib/esm/tools/builtin/CreateWallTool.d.ts +145 -0
  121. package/dist-lib/esm/tools/builtin/CreateWallTool.js +124 -0
  122. package/dist-lib/esm/tools/builtin/DecalTool.d.ts +76 -0
  123. package/dist-lib/esm/tools/builtin/DecalTool.js +143 -0
  124. package/dist-lib/esm/tools/builtin/DeleteMeshTool.d.ts +20 -0
  125. package/dist-lib/esm/tools/builtin/DeleteMeshTool.js +42 -0
  126. package/dist-lib/esm/tools/builtin/ExecuteBabylonCodeTool.d.ts +21 -0
  127. package/dist-lib/esm/tools/builtin/ExecuteBabylonCodeTool.js +96 -0
  128. package/dist-lib/esm/tools/builtin/ExtrudePolygonTool.d.ts +114 -0
  129. package/dist-lib/esm/tools/builtin/ExtrudePolygonTool.js +77 -0
  130. package/dist-lib/esm/tools/builtin/ExtrudeShapeTool.d.ts +104 -0
  131. package/dist-lib/esm/tools/builtin/ExtrudeShapeTool.js +68 -0
  132. package/dist-lib/esm/tools/builtin/FacetArcTool.d.ts +36 -0
  133. package/dist-lib/esm/tools/builtin/FacetArcTool.js +57 -0
  134. package/dist-lib/esm/tools/builtin/FacetCutThroughTool.d.ts +30 -0
  135. package/dist-lib/esm/tools/builtin/FacetCutThroughTool.js +49 -0
  136. package/dist-lib/esm/tools/builtin/FacetExtrudeTool.d.ts +30 -0
  137. package/dist-lib/esm/tools/builtin/FacetExtrudeTool.js +49 -0
  138. package/dist-lib/esm/tools/builtin/FacetInsetTool.d.ts +34 -0
  139. package/dist-lib/esm/tools/builtin/FacetInsetTool.js +55 -0
  140. package/dist-lib/esm/tools/builtin/GenerateNeuralMeshTool.d.ts +131 -0
  141. package/dist-lib/esm/tools/builtin/GenerateNeuralMeshTool.js +455 -0
  142. package/dist-lib/esm/tools/builtin/GenerateTextureTool.d.ts +87 -0
  143. package/dist-lib/esm/tools/builtin/GenerateTextureTool.js +216 -0
  144. package/dist-lib/esm/tools/builtin/GetSceneInfoTool.d.ts +11 -0
  145. package/dist-lib/esm/tools/builtin/GetSceneInfoTool.js +12 -0
  146. package/dist-lib/esm/tools/builtin/MergeMeshesTool.d.ts +28 -0
  147. package/dist-lib/esm/tools/builtin/MergeMeshesTool.js +56 -0
  148. package/dist-lib/esm/tools/builtin/PlanModelTool.d.ts +87 -0
  149. package/dist-lib/esm/tools/builtin/PlanModelTool.js +155 -0
  150. package/dist-lib/esm/tools/builtin/RetopologizeMeshTool.d.ts +50 -0
  151. package/dist-lib/esm/tools/builtin/RetopologizeMeshTool.js +116 -0
  152. package/dist-lib/esm/tools/builtin/RigWeightTool.d.ts +55 -0
  153. package/dist-lib/esm/tools/builtin/RigWeightTool.js +139 -0
  154. package/dist-lib/esm/tools/builtin/SculptMeshTool.d.ts +138 -0
  155. package/dist-lib/esm/tools/builtin/SculptMeshTool.js +255 -0
  156. package/dist-lib/esm/tools/builtin/SeparateMeshTool.d.ts +21 -0
  157. package/dist-lib/esm/tools/builtin/SeparateMeshTool.js +31 -0
  158. package/dist-lib/esm/tools/builtin/SolidifyMeshTool.d.ts +30 -0
  159. package/dist-lib/esm/tools/builtin/SolidifyMeshTool.js +57 -0
  160. package/dist-lib/esm/tools/builtin/SpawnBaseMeshTool.d.ts +66 -0
  161. package/dist-lib/esm/tools/builtin/SpawnBaseMeshTool.js +105 -0
  162. package/dist-lib/esm/tools/builtin/SubDSmoothTool.d.ts +23 -0
  163. package/dist-lib/esm/tools/builtin/SubDSmoothTool.js +37 -0
  164. package/dist-lib/esm/tools/builtin/SubdivideMeshTool.d.ts +23 -0
  165. package/dist-lib/esm/tools/builtin/SubdivideMeshTool.js +39 -0
  166. package/dist-lib/esm/tools/builtin/TransformMeshTool.d.ts +78 -0
  167. package/dist-lib/esm/tools/builtin/TransformMeshTool.js +69 -0
  168. package/dist-lib/esm/tools/builtin/UVUnwrapTool.d.ts +48 -0
  169. package/dist-lib/esm/tools/builtin/UVUnwrapTool.js +107 -0
  170. package/dist-lib/esm/tools/builtin/VoxelPainterTool.d.ts +60 -0
  171. package/dist-lib/esm/tools/builtin/VoxelPainterTool.js +153 -0
  172. package/dist-lib/esm/tools/builtin/index.d.ts +44 -0
  173. package/dist-lib/esm/tools/builtin/index.js +44 -0
  174. package/dist-lib/esm/tools/editor/AIAgentEditorTool.d.ts +18 -0
  175. package/dist-lib/esm/tools/editor/AIAgentEditorTool.js +43 -0
  176. package/dist-lib/esm/tools/editor/AITextureEditorTool.d.ts +15 -0
  177. package/dist-lib/esm/tools/editor/AITextureEditorTool.js +28 -0
  178. package/dist-lib/esm/tools/editor/AbstractEditorTool.d.ts +29 -0
  179. package/dist-lib/esm/tools/editor/AbstractEditorTool.js +56 -0
  180. package/dist-lib/esm/tools/editor/AnimationPlayerEditorTool.d.ts +17 -0
  181. package/dist-lib/esm/tools/editor/AnimationPlayerEditorTool.js +29 -0
  182. package/dist-lib/esm/tools/editor/BakingEditorTool.d.ts +21 -0
  183. package/dist-lib/esm/tools/editor/BakingEditorTool.js +44 -0
  184. package/dist-lib/esm/tools/editor/CSGEditorTool.d.ts +20 -0
  185. package/dist-lib/esm/tools/editor/CSGEditorTool.js +42 -0
  186. package/dist-lib/esm/tools/editor/CompressModelEditorTool.d.ts +20 -0
  187. package/dist-lib/esm/tools/editor/CompressModelEditorTool.js +48 -0
  188. package/dist-lib/esm/tools/editor/CreatePrimitiveEditorTool.d.ts +17 -0
  189. package/dist-lib/esm/tools/editor/CreatePrimitiveEditorTool.js +36 -0
  190. package/dist-lib/esm/tools/editor/DecalEditorTool.d.ts +17 -0
  191. package/dist-lib/esm/tools/editor/DecalEditorTool.js +36 -0
  192. package/dist-lib/esm/tools/editor/FacetEditorTool.d.ts +23 -0
  193. package/dist-lib/esm/tools/editor/FacetEditorTool.js +80 -0
  194. package/dist-lib/esm/tools/editor/MaterialEditorTool.d.ts +18 -0
  195. package/dist-lib/esm/tools/editor/MaterialEditorTool.js +43 -0
  196. package/dist-lib/esm/tools/editor/MeshPropertiesEditorTool.d.ts +17 -0
  197. package/dist-lib/esm/tools/editor/MeshPropertiesEditorTool.js +37 -0
  198. package/dist-lib/esm/tools/editor/OutlinerEditorTool.d.ts +17 -0
  199. package/dist-lib/esm/tools/editor/OutlinerEditorTool.js +34 -0
  200. package/dist-lib/esm/tools/editor/PathExtrusionEditorTool.d.ts +26 -0
  201. package/dist-lib/esm/tools/editor/PathExtrusionEditorTool.js +72 -0
  202. package/dist-lib/esm/tools/editor/RiggingEditorTool.d.ts +27 -0
  203. package/dist-lib/esm/tools/editor/RiggingEditorTool.js +66 -0
  204. package/dist-lib/esm/tools/editor/SceneEnvironmentEditorTool.d.ts +17 -0
  205. package/dist-lib/esm/tools/editor/SceneEnvironmentEditorTool.js +35 -0
  206. package/dist-lib/esm/tools/editor/SculptEditorTool.d.ts +28 -0
  207. package/dist-lib/esm/tools/editor/SculptEditorTool.js +70 -0
  208. package/dist-lib/esm/tools/editor/TextMeshEditorTool.d.ts +16 -0
  209. package/dist-lib/esm/tools/editor/TextMeshEditorTool.js +30 -0
  210. package/dist-lib/esm/tools/editor/TextureOptimizerEditorTool.d.ts +17 -0
  211. package/dist-lib/esm/tools/editor/TextureOptimizerEditorTool.js +28 -0
  212. package/dist-lib/esm/tools/editor/UVUnwrapEditorTool.d.ts +27 -0
  213. package/dist-lib/esm/tools/editor/UVUnwrapEditorTool.js +70 -0
  214. package/dist-lib/esm/tools/editor/VoxelPainterEditorTool.d.ts +26 -0
  215. package/dist-lib/esm/tools/editor/VoxelPainterEditorTool.js +68 -0
  216. package/dist-lib/esm/tools/editor/aiQuickPrompts.d.ts +30 -0
  217. package/dist-lib/esm/tools/editor/aiQuickPrompts.js +228 -0
  218. package/dist-lib/esm/tools/editor/index.d.ts +32 -0
  219. package/dist-lib/esm/tools/editor/index.js +54 -0
  220. package/dist-lib/esm/tools/editor/toolViews.d.ts +10 -0
  221. package/dist-lib/esm/tools/editor/toolViews.js +53 -0
  222. package/dist-lib/esm/tools/editorTools.d.ts +5 -0
  223. package/dist-lib/esm/tools/editorTools.js +5 -0
  224. package/dist-lib/esm/tools/index.d.ts +8 -0
  225. package/dist-lib/esm/tools/index.js +8 -0
  226. package/dist-lib/esm/tools/textureUtils.d.ts +18 -0
  227. package/dist-lib/esm/tools/textureUtils.js +288 -0
  228. package/dist-lib/esm/types.d.ts +164 -0
  229. package/dist-lib/esm/types.js +1 -0
  230. package/dist-lib/esm/uv/UVUnwrapController.d.ts +108 -0
  231. package/dist-lib/esm/uv/UVUnwrapController.js +1022 -0
  232. package/dist-lib/esm/voxel/CustomVoxelMesher.d.ts +15 -0
  233. package/dist-lib/esm/voxel/CustomVoxelMesher.js +169 -0
  234. package/dist-lib/esm/voxel/TextureAtlasManager.d.ts +54 -0
  235. package/dist-lib/esm/voxel/TextureAtlasManager.js +630 -0
  236. package/dist-lib/esm/voxel/VoxelPainterController.d.ts +100 -0
  237. package/dist-lib/esm/voxel/VoxelPainterController.js +671 -0
  238. package/dist-lib/esm/voxel/index.d.ts +4 -0
  239. package/dist-lib/esm/voxel/index.js +4 -0
  240. package/dist-lib/esm/voxel/types.d.ts +78 -0
  241. package/dist-lib/esm/voxel/types.js +1 -0
  242. package/dist-lib/esm/web-component/MeshEditorElement.d.ts +103 -0
  243. package/dist-lib/esm/web-component/MeshEditorElement.js +246 -0
  244. package/dist-lib/esm/web-component/index.d.ts +1 -0
  245. package/dist-lib/esm/web-component/index.js +1 -0
  246. package/dist-lib/index.umd.js +3 -0
  247. package/dist-lib/mesheditor.css +2 -0
  248. package/dist-lib/mesheditor.css.map +1 -0
  249. package/dist-lib/standalone/mesheditor-element.bundle.js +3 -0
  250. package/package.json +114 -4
  251. package/skills/README.md +48 -0
  252. package/skills/figure-sculptor.md +297 -0
  253. package/skills/image-to-mesh.md +18 -0
  254. package/skills/mesh-updater.md +27 -0
  255. package/skills/neural-3d-generator.md +53 -0
  256. package/skills/procedural-modeler.md +267 -0
  257. package/skills/voxel-painter.md +21 -0
  258. package/src/mesheditor.css +6477 -0
@@ -0,0 +1,1397 @@
1
+ export const NEURAL_3D_PROTOCOL_DEFAULTS = {
2
+ trellis: {
3
+ omlx: {
4
+ endpointUrl: 'http://localhost:8000/v1/3d/generations',
5
+ modelId: 'mlx-community/TRELLIS.2-4B',
6
+ requiresKey: false,
7
+ },
8
+ local_rest: {
9
+ endpointUrl: 'http://localhost:8080/generate',
10
+ modelId: 'microsoft/TRELLIS.2-4B',
11
+ requiresKey: false,
12
+ },
13
+ gradio: {
14
+ endpointUrl: 'http://localhost:7860',
15
+ modelId: 'microsoft/TRELLIS-image-large',
16
+ requiresKey: false,
17
+ },
18
+ fal: {
19
+ endpointUrl: 'https://fal.run/fal-ai/trellis',
20
+ modelId: 'fal-ai/trellis',
21
+ requiresKey: true,
22
+ },
23
+ replicate: {
24
+ endpointUrl: 'https://api.replicate.com/v1/predictions',
25
+ modelId: 'firtoz/trellis',
26
+ requiresKey: true,
27
+ },
28
+ },
29
+ hunyuan3d: {
30
+ omlx: {
31
+ endpointUrl: 'http://localhost:8000/v1/3d/generations',
32
+ modelId: 'mlx-community/Hunyuan3D-2.1',
33
+ requiresKey: false,
34
+ },
35
+ local_rest: {
36
+ endpointUrl: 'http://localhost:8081/generate',
37
+ modelId: 'tencent/Hunyuan3D-2.1',
38
+ requiresKey: false,
39
+ },
40
+ gradio: {
41
+ endpointUrl: 'http://localhost:7861',
42
+ modelId: 'tencent/Hunyuan3D-2',
43
+ requiresKey: false,
44
+ },
45
+ fal: {
46
+ endpointUrl: 'https://fal.run/fal-ai/hunyuan3d-v2',
47
+ modelId: 'fal-ai/hunyuan3d-v2',
48
+ requiresKey: true,
49
+ },
50
+ replicate: {
51
+ endpointUrl: 'https://api.replicate.com/v1/predictions',
52
+ modelId: 'tencent/hunyuan3d-2',
53
+ requiresKey: true,
54
+ },
55
+ },
56
+ hi3d: {
57
+ omlx: {
58
+ endpointUrl: 'http://localhost:8000/v1/3d/generations',
59
+ modelId: 'mlx-community/Hi3D-V3.0',
60
+ requiresKey: false,
61
+ },
62
+ local_rest: {
63
+ endpointUrl: 'http://localhost:8082/generate',
64
+ modelId: 'Hi3D-V3.0',
65
+ requiresKey: false,
66
+ },
67
+ gradio: {
68
+ endpointUrl: 'http://localhost:7862',
69
+ modelId: 'Hi3D-V3.0',
70
+ requiresKey: false,
71
+ },
72
+ fal: {
73
+ endpointUrl: 'https://fal.run/fal-ai/hi3d',
74
+ modelId: 'fal-ai/hi3d',
75
+ requiresKey: true,
76
+ },
77
+ replicate: {
78
+ endpointUrl: 'https://api.replicate.com/v1/predictions',
79
+ modelId: 'hi3d/hi3d-v3',
80
+ requiresKey: true,
81
+ },
82
+ },
83
+ };
84
+ export function createDefaultNeural3DProviders() {
85
+ return {
86
+ trellis: {
87
+ id: 'trellis',
88
+ name: 'TRELLIS 2 / TRELLIS',
89
+ enabled: false,
90
+ protocol: 'omlx',
91
+ endpointUrl: NEURAL_3D_PROTOCOL_DEFAULTS.trellis.omlx.endpointUrl,
92
+ apiKey: '',
93
+ modelId: NEURAL_3D_PROTOCOL_DEFAULTS.trellis.omlx.modelId,
94
+ },
95
+ hunyuan3d: {
96
+ id: 'hunyuan3d',
97
+ name: 'Hunyuan3D',
98
+ enabled: false,
99
+ protocol: 'omlx',
100
+ endpointUrl: NEURAL_3D_PROTOCOL_DEFAULTS.hunyuan3d.omlx.endpointUrl,
101
+ apiKey: '',
102
+ modelId: NEURAL_3D_PROTOCOL_DEFAULTS.hunyuan3d.omlx.modelId,
103
+ },
104
+ hi3d: {
105
+ id: 'hi3d',
106
+ name: 'Hi3D (V1.0–V3.0)',
107
+ enabled: false,
108
+ protocol: 'omlx',
109
+ endpointUrl: NEURAL_3D_PROTOCOL_DEFAULTS.hi3d.omlx.endpointUrl,
110
+ apiKey: '',
111
+ modelId: NEURAL_3D_PROTOCOL_DEFAULTS.hi3d.omlx.modelId,
112
+ },
113
+ };
114
+ }
115
+ export function normalizeNeural3DProviders(raw) {
116
+ const defaults = createDefaultNeural3DProviders();
117
+ if (!raw || typeof raw !== 'object') {
118
+ return defaults;
119
+ }
120
+ const ids = ['trellis', 'hunyuan3d', 'hi3d'];
121
+ for (const id of ids) {
122
+ const item = raw[id];
123
+ if (item && typeof item === 'object') {
124
+ const protocol = item.protocol && ['omlx', 'local_rest', 'gradio', 'fal', 'replicate'].includes(item.protocol)
125
+ ? item.protocol
126
+ : defaults[id].protocol;
127
+ const preset = NEURAL_3D_PROTOCOL_DEFAULTS[id][protocol];
128
+ defaults[id] = {
129
+ id,
130
+ name: defaults[id].name,
131
+ enabled: typeof item.enabled === 'boolean' ? item.enabled : false,
132
+ protocol,
133
+ endpointUrl: typeof item.endpointUrl === 'string' && item.endpointUrl.trim()
134
+ ? item.endpointUrl.trim()
135
+ : preset.endpointUrl,
136
+ apiKey: typeof item.apiKey === 'string' ? item.apiKey : '',
137
+ modelId: typeof item.modelId === 'string' && item.modelId.trim()
138
+ ? item.modelId.trim()
139
+ : preset.modelId,
140
+ };
141
+ }
142
+ }
143
+ return defaults;
144
+ }
145
+ /**
146
+ * Service handling communication with local (oMLX, FastAPI, Gradio) and cloud BYO-key
147
+ * (Fal.ai, Replicate) Neural 3D Generators: TRELLIS 2, Hunyuan3D, and Hi3D.
148
+ */
149
+ export class Neural3DGeneratorService {
150
+ /**
151
+ * Selects the best enabled provider for a given 3D generation request.
152
+ */
153
+ static selectBestProvider(providers, request) {
154
+ const enabledList = ['trellis', 'hunyuan3d', 'hi3d']
155
+ .map((id) => providers[id])
156
+ .filter((p) => !!p && p.enabled);
157
+ if (enabledList.length === 0) {
158
+ throw new Error('No Neural 3D Generator (TRELLIS 2, Hunyuan3D, or Hi3D) is currently enabled. Enable at least one generator in AI Agent Settings.');
159
+ }
160
+ // 1. Explicit backend request if enabled
161
+ if (request.backend && request.backend !== 'auto') {
162
+ const explicit = providers[request.backend];
163
+ if (explicit && explicit.enabled) {
164
+ return explicit;
165
+ }
166
+ }
167
+ // 2. Heuristic auto-selection among enabled providers:
168
+ // - If 3D printing / high-res 2K untextured geometry is requested -> prefer Hi3D
169
+ if (request.highResPrint || request.generateTextures === false) {
170
+ if (providers.hi3d?.enabled)
171
+ return providers.hi3d;
172
+ }
173
+ // - If an input reference image is provided -> prefer TRELLIS 2 (best image-to-3D & topology), then Hunyuan3D
174
+ if (request.imageUrl) {
175
+ if (providers.trellis?.enabled)
176
+ return providers.trellis;
177
+ if (providers.hunyuan3d?.enabled)
178
+ return providers.hunyuan3d;
179
+ }
180
+ // - If textured object generation from text -> prefer Hunyuan3D or TRELLIS 2
181
+ if (request.generateTextures !== false) {
182
+ if (providers.trellis?.enabled)
183
+ return providers.trellis;
184
+ if (providers.hunyuan3d?.enabled)
185
+ return providers.hunyuan3d;
186
+ }
187
+ return enabledList[0];
188
+ }
189
+ /**
190
+ * Generates a 3D mesh from the selected Neural 3D Generator provider.
191
+ */
192
+ static async generateMesh(providers, request, customFetch) {
193
+ const provider = this.selectBestProvider(providers, request);
194
+ const fetchFn = customFetch || globalThis.fetch.bind(globalThis);
195
+ request.onStatus?.(`Delegating 3D generation to ${provider.name} (${provider.protocol})...`);
196
+ switch (provider.protocol) {
197
+ case 'gradio':
198
+ return await this.executeGradioRequest(provider, request, fetchFn);
199
+ case 'fal':
200
+ return await this.executeFalRequest(provider, request, fetchFn);
201
+ case 'replicate':
202
+ return await this.executeReplicateRequest(provider, request, fetchFn);
203
+ case 'omlx':
204
+ case 'local_rest':
205
+ default:
206
+ return await this.executeRestOrOmlxRequest(provider, request, fetchFn);
207
+ }
208
+ }
209
+ /**
210
+ * Resolves the generation endpoint URL for oMLX or local REST servers.
211
+ */
212
+ static resolveRestUrl(endpointUrl, protocol) {
213
+ const clean = (endpointUrl || '').trim().replace(/\/+$/, '');
214
+ if (!clean) {
215
+ return protocol === 'omlx'
216
+ ? 'http://localhost:8000/v1/3d/generations'
217
+ : 'http://localhost:8080/generate';
218
+ }
219
+ if (protocol === 'omlx') {
220
+ if (clean.endsWith('/v1')) {
221
+ return `${clean}/3d/generations`;
222
+ }
223
+ if (/^https?:\/\/[^/]+$/i.test(clean)) {
224
+ return `${clean}/v1/3d/generations`;
225
+ }
226
+ }
227
+ return clean;
228
+ }
229
+ static async executeRestOrOmlxRequest(provider, request, fetchFn) {
230
+ const primaryUrl = this.resolveRestUrl(provider.endpointUrl, provider.protocol);
231
+ const headers = {
232
+ 'Content-Type': 'application/json',
233
+ Accept: 'application/json, model/gltf-binary, application/octet-stream',
234
+ };
235
+ if (provider.apiKey && provider.apiKey.trim()) {
236
+ headers['Authorization'] = `Bearer ${provider.apiKey.trim()}`;
237
+ }
238
+ const generateTextures = request.generateTextures !== undefined
239
+ ? request.generateTextures
240
+ : provider.id !== 'hi3d';
241
+ const octreeRes = request.octreeResolution || (provider.id === 'hi3d' || request.highResPrint ? 512 : 256);
242
+ const payload = {
243
+ model: provider.modelId || provider.id,
244
+ backend: provider.id,
245
+ prompt: request.prompt,
246
+ text: request.prompt,
247
+ texture: generateTextures,
248
+ generate_textures: generateTextures,
249
+ high_res_print: !!request.highResPrint || provider.id === 'hi3d',
250
+ octree_resolution: octreeRes,
251
+ format: 'glb',
252
+ response_format: 'glb',
253
+ };
254
+ if (request.imageUrl) {
255
+ payload.image = request.imageUrl;
256
+ payload.image_url = request.imageUrl;
257
+ const base64Clean = request.imageUrl.replace(/^data:image\/[a-zA-Z0-9+.-]+;base64,/, '');
258
+ payload.image_base64 = base64Clean;
259
+ }
260
+ if (typeof request.seed === 'number') {
261
+ payload.seed = request.seed;
262
+ }
263
+ let res = await fetchFn(primaryUrl, {
264
+ method: 'POST',
265
+ headers,
266
+ body: JSON.stringify(payload),
267
+ signal: request.signal,
268
+ });
269
+ // If oMLX /v1/3d/generations returns 404, try /generate on the same host
270
+ if (res.status === 404 && primaryUrl.endsWith('/v1/3d/generations')) {
271
+ const fallbackUrl = primaryUrl.replace(/\/v1\/3d\/generations$/, '/generate');
272
+ res = await fetchFn(fallbackUrl, {
273
+ method: 'POST',
274
+ headers,
275
+ body: JSON.stringify(payload),
276
+ signal: request.signal,
277
+ });
278
+ }
279
+ if (!res.ok) {
280
+ const errText = await res.text().catch(() => '');
281
+ throw new Error(`${provider.name} endpoint error (${res.status}): ${errText || res.statusText}`);
282
+ }
283
+ return await this.parseHttpResponseToMeshResult(res, provider, primaryUrl, fetchFn, request.signal);
284
+ }
285
+ static async executeGradioRequest(provider, request, fetchFn) {
286
+ const baseUrl = provider.endpointUrl.trim().replace(/\/+$/, '');
287
+ const headers = {
288
+ 'Content-Type': 'application/json',
289
+ Accept: 'application/json',
290
+ };
291
+ if (provider.apiKey && provider.apiKey.trim()) {
292
+ headers['Authorization'] = `Bearer ${provider.apiKey.trim()}`;
293
+ }
294
+ const explicitPredictSuffix = /\/(gradio_api\/)?(api|run)\/predict$/i.test(baseUrl);
295
+ const rootUrl = baseUrl
296
+ .replace(/\/(gradio_api\/)?(api|run|call)\/.*$/i, '')
297
+ .replace(/\/(gradio_api\/)?(info|config)$/i, '')
298
+ .replace(/\/+$/, '');
299
+ // 1. Try inspecting Gradio /config first (supported across Gradio 3, 4, and 5 even when show_api=False)
300
+ if (!explicitPredictSuffix) {
301
+ try {
302
+ const cfgRes = await fetchFn(`${rootUrl}/config`, {
303
+ method: 'GET',
304
+ headers: { Accept: 'application/json', ...(headers.Authorization ? { Authorization: headers.Authorization } : {}) },
305
+ signal: request.signal,
306
+ });
307
+ if (cfgRes && cfgRes.ok) {
308
+ const cfgText = await this.readResponseText(cfgRes);
309
+ const cfgJson = JSON.parse(cfgText);
310
+ if (cfgJson && Array.isArray(cfgJson.dependencies)) {
311
+ return await this.executeGradioWithConfig(provider, request, rootUrl, cfgJson, headers, fetchFn);
312
+ }
313
+ }
314
+ }
315
+ catch (err) {
316
+ // Re-throw if it's a deliberate user-facing error from executeGradioWithConfig or abort
317
+ if (err?.name === 'AbortError' ||
318
+ (err instanceof Error && err.message.startsWith(`${provider.name} Gradio`))) {
319
+ throw err;
320
+ }
321
+ // Otherwise fall back to legacy /api/predict -> /run/predict calls
322
+ }
323
+ }
324
+ // 2. Fallback: Direct /api/predict, /run/predict, or /gradio_api/run/predict
325
+ const body = {
326
+ data: [
327
+ request.imageUrl || request.prompt,
328
+ request.prompt,
329
+ request.seed ?? 42,
330
+ request.generateTextures !== false,
331
+ ],
332
+ fn_index: 0,
333
+ };
334
+ const candidateUrls = explicitPredictSuffix
335
+ ? [baseUrl]
336
+ : [
337
+ `${rootUrl}/api/predict`,
338
+ `${rootUrl}/run/predict`,
339
+ `${rootUrl}/gradio_api/run/predict`,
340
+ `${rootUrl}/gradio_api/api/predict`,
341
+ ];
342
+ let lastRes = null;
343
+ for (const predictUrl of candidateUrls) {
344
+ lastRes = await fetchFn(predictUrl, {
345
+ method: 'POST',
346
+ headers,
347
+ body: JSON.stringify(body),
348
+ signal: request.signal,
349
+ });
350
+ if (lastRes.status !== 404) {
351
+ break;
352
+ }
353
+ }
354
+ if (!lastRes || !lastRes.ok) {
355
+ const errText = lastRes ? await lastRes.text().catch(() => '') : '';
356
+ throw new Error(`${provider.name} Gradio error (${lastRes?.status || 'Network'}): ${errText || lastRes?.statusText || 'Failed'}`);
357
+ }
358
+ return await this.parseHttpResponseToMeshResult(lastRes, provider, rootUrl, fetchFn, request.signal, request.generateTextures !== false);
359
+ }
360
+ /**
361
+ * Executes a single-stage or multi-stage 3D generation workflow (such as TRELLIS
362
+ * preprocess_image -> image_to_3d -> extract_glb or Hunyuan3D generation_all)
363
+ * using the live Gradio /config schema across Gradio 3, 4, and 5.
364
+ */
365
+ static async executeGradioWithConfig(provider, request, rootUrl, config, headers, fetchFn) {
366
+ const apiPrefix = typeof config.api_prefix === 'string' && config.api_prefix.trim()
367
+ ? '/' + config.api_prefix.trim().replace(/^\/+|\/+$/g, '')
368
+ : '';
369
+ const isGradio3 = String(config.version || '').trim().startsWith('3.');
370
+ const sessionHash = Math.random().toString(36).substring(2, 13);
371
+ const componentsMap = new Map();
372
+ if (Array.isArray(config.components)) {
373
+ for (const comp of config.components) {
374
+ if (comp && typeof comp.id === 'number') {
375
+ componentsMap.set(comp.id, comp);
376
+ }
377
+ }
378
+ }
379
+ const rawDeps = Array.isArray(config.dependencies) ? config.dependencies : [];
380
+ const deps = rawDeps.map((d, idx) => ({
381
+ raw: d,
382
+ fnIndex: typeof d?.id === 'number' ? d.id : idx,
383
+ apiName: typeof d?.api_name === 'string' && d.api_name.trim()
384
+ ? d.api_name.trim().replace(/^\/+/, '')
385
+ : null,
386
+ inputs: Array.isArray(d?.inputs) ? d.inputs : [],
387
+ outputs: Array.isArray(d?.outputs) ? d.outputs : [],
388
+ backendFn: d?.backend_fn !== false,
389
+ queue: d?.queue,
390
+ }));
391
+ const backendDeps = deps.filter((d) => d.backendFn);
392
+ // 1. Find primary generation dependency (and optional 2-stage extract_glb dependency)
393
+ let mainDep = (!request.imageUrl
394
+ ? backendDeps.find((d) => ['text_to_3d', 'text2mesh', 'txt2mesh'].includes((d.apiName || '').toLowerCase()))
395
+ : undefined) ||
396
+ (request.generateTextures !== false
397
+ ? backendDeps.find((d) => (d.apiName || '').toLowerCase() === 'generation_all')
398
+ : undefined) ||
399
+ backendDeps.find((d) => [
400
+ 'image_to_3d',
401
+ 'img_to_3d',
402
+ 'shape_generation',
403
+ 'generation_all',
404
+ 'text_to_3d',
405
+ 'generate_3d',
406
+ 'generate_mesh',
407
+ 'generate',
408
+ 'predict',
409
+ 'run',
410
+ ].includes((d.apiName || '').toLowerCase()));
411
+ let extractDep = backendDeps.find((d) => ['extract_glb', 'extract_mesh', 'export_glb', 'export_mesh'].includes((d.apiName || '').toLowerCase()));
412
+ const isMeshOutputComp = (id) => {
413
+ const t = (componentsMap.get(id)?.type || '').toLowerCase();
414
+ return t === 'model3d' || t === 'file' || t === 'downloadbutton';
415
+ };
416
+ const isInputPromptComp = (id) => {
417
+ const t = (componentsMap.get(id)?.type || '').toLowerCase();
418
+ return t === 'image' || t === 'textbox' || t === 'text';
419
+ };
420
+ // Component-graph discovery if api_name is unnamed/custom
421
+ if (!mainDep) {
422
+ // Look for 1-stage: (image/textbox) -> (model3d/file/downloadbutton)
423
+ mainDep = backendDeps.find((d) => d.inputs.some(isInputPromptComp) && d.outputs.some(isMeshOutputComp));
424
+ }
425
+ if (!mainDep) {
426
+ // Look for 2-stage (like TRELLIS when api_name is unnamed):
427
+ // Stage 1: (image/textbox) -> state(S), Stage 2: state(S) -> (model3d/file/downloadbutton)
428
+ for (const candidate of backendDeps) {
429
+ if (!candidate.inputs.some(isInputPromptComp))
430
+ continue;
431
+ const stateOutIds = candidate.outputs.filter((id) => (componentsMap.get(id)?.type || '').toLowerCase() === 'state');
432
+ if (stateOutIds.length > 0) {
433
+ const matchingExtract = backendDeps.find((d2) => d2 !== candidate &&
434
+ stateOutIds.some((sid) => d2.inputs.includes(sid)) &&
435
+ d2.outputs.some(isMeshOutputComp));
436
+ if (matchingExtract) {
437
+ mainDep = candidate;
438
+ if (!extractDep)
439
+ extractDep = matchingExtract;
440
+ break;
441
+ }
442
+ }
443
+ }
444
+ }
445
+ if (!mainDep) {
446
+ mainDep = backendDeps[0] || deps[0];
447
+ }
448
+ if (!mainDep) {
449
+ throw new Error(`${provider.name} Gradio error: No callable dependencies found in /config.`);
450
+ }
451
+ // If mainDep outputs a state component and doesn't directly output a model3d, locate matching extractor
452
+ if (!extractDep && !mainDep.outputs.some(isMeshOutputComp)) {
453
+ const stateOutIds = mainDep.outputs.filter((id) => (componentsMap.get(id)?.type || '').toLowerCase() === 'state');
454
+ if (stateOutIds.length > 0) {
455
+ extractDep = backendDeps.find((d2) => d2 !== mainDep &&
456
+ stateOutIds.some((sid) => d2.inputs.includes(sid)) &&
457
+ d2.outputs.some(isMeshOutputComp));
458
+ }
459
+ }
460
+ // Verify if mainDep strictly requires an input image (Image-to-3D only) when no image was provided
461
+ const hasImageInput = mainDep.inputs.some((id) => (componentsMap.get(id)?.type || '').toLowerCase() === 'image');
462
+ const hasTextInput = mainDep.inputs.some((id) => ['textbox', 'text'].includes((componentsMap.get(id)?.type || '').toLowerCase()));
463
+ if (hasImageInput && !hasTextInput && !request.imageUrl) {
464
+ throw new Error(`${provider.name} Gradio server at ${rootUrl} is running an Image-to-3D pipeline (${mainDep.apiName || 'image_to_3d'}) and requires an input image. Please attach a reference image (Image button) or enable '+ 3D View' in the AI Mesh Agent.`);
465
+ }
466
+ const stateByComponentId = new Map();
467
+ // 2. Upload input image if provided
468
+ let uploadedImageInput = null;
469
+ if (request.imageUrl) {
470
+ request.onStatus?.(`Uploading reference image to ${provider.name} (Gradio)...`);
471
+ uploadedImageInput = await this.uploadGradioImage(rootUrl, apiPrefix, request.imageUrl, isGradio3, sessionHash, headers, fetchFn, request.signal);
472
+ }
473
+ // 3. Optional start_session step (used by TRELLIS to create session tmp dir)
474
+ const startSessionDep = backendDeps.find((d) => (d.apiName || '').toLowerCase() === 'start_session' && d.inputs.length === 0);
475
+ if (startSessionDep) {
476
+ try {
477
+ await this.callGradioDependency(rootUrl, apiPrefix, startSessionDep, [], sessionHash, isGradio3, provider.name, headers, fetchFn, request.signal);
478
+ }
479
+ catch {
480
+ // Ignore non-fatal start_session errors
481
+ }
482
+ }
483
+ // 4. Optional preprocess_image step (used by TRELLIS to remove background before image_to_3d)
484
+ const primaryImageCompId = mainDep.inputs.find((id) => (componentsMap.get(id)?.type || '').toLowerCase() === 'image');
485
+ if (uploadedImageInput && primaryImageCompId !== undefined) {
486
+ stateByComponentId.set(primaryImageCompId, uploadedImageInput);
487
+ const preprocessDep = backendDeps.find((d) => d !== mainDep &&
488
+ ((d.apiName || '').toLowerCase() === 'preprocess_image' ||
489
+ (d.inputs.length === 1 &&
490
+ d.outputs.length === 1 &&
491
+ d.inputs[0] === primaryImageCompId &&
492
+ d.outputs[0] === primaryImageCompId)));
493
+ if (preprocessDep) {
494
+ try {
495
+ request.onStatus?.(`${provider.name}: preprocessing reference image...`);
496
+ const prepOut = await this.callGradioDependency(rootUrl, apiPrefix, preprocessDep, [uploadedImageInput], sessionHash, isGradio3, provider.name, headers, fetchFn, request.signal, request.onStatus);
497
+ if (prepOut?.data?.[0]) {
498
+ stateByComponentId.set(primaryImageCompId, prepOut.data[0]);
499
+ }
500
+ }
501
+ catch {
502
+ // Keep original uploaded image if preprocess_image is optional or fails
503
+ }
504
+ }
505
+ }
506
+ // 5. Build inputs for mainDep and execute 3D generation
507
+ const mainInputs = this.buildGradioInputsForDependency(mainDep.inputs, componentsMap, stateByComponentId, request, uploadedImageInput);
508
+ request.onStatus?.(`${provider.name}: running ${mainDep.apiName || '3D generation'} on Gradio...`);
509
+ const mainOut = await this.callGradioDependency(rootUrl, apiPrefix, mainDep, mainInputs, sessionHash, isGradio3, provider.name, headers, fetchFn, request.signal, request.onStatus);
510
+ if (Array.isArray(mainOut?.data)) {
511
+ mainDep.outputs.forEach((outCompId, idx) => {
512
+ if (idx < mainOut.data.length && mainOut.data[idx] !== undefined) {
513
+ stateByComponentId.set(outCompId, mainOut.data[idx]);
514
+ }
515
+ });
516
+ }
517
+ // Check if mainOut already returned a 3D mesh URL/file (e.g. Hunyuan3D or 1-stage TRELLIS)
518
+ const directUrl = this.extractModelUrlFromJson(mainOut, rootUrl, apiPrefix, request.generateTextures !== false);
519
+ let finalJsonPayload = mainOut;
520
+ // 6. If no 3D mesh file yet and extractDep exists (e.g. TRELLIS extract_glb), execute Stage 2!
521
+ if (!directUrl && extractDep) {
522
+ request.onStatus?.(`${provider.name}: extracting GLB mesh (${extractDep.apiName || 'extract_glb'})...`);
523
+ const extractInputs = this.buildGradioInputsForDependency(extractDep.inputs, componentsMap, stateByComponentId, request, uploadedImageInput);
524
+ finalJsonPayload = await this.callGradioDependency(rootUrl, apiPrefix, extractDep, extractInputs, sessionHash, isGradio3, provider.name, headers, fetchFn, request.signal, request.onStatus);
525
+ }
526
+ const syntheticRes = new Response(JSON.stringify(finalJsonPayload), {
527
+ status: 200,
528
+ headers: { 'content-type': 'application/json' },
529
+ });
530
+ return await this.parseHttpResponseToMeshResult(syntheticRes, provider, rootUrl, fetchFn, request.signal, request.generateTextures !== false, apiPrefix);
531
+ }
532
+ static buildGradioInputsForDependency(inputIds, componentsMap, stateByComponentId, request, uploadedImageInput) {
533
+ let primaryImageAssigned = false;
534
+ let primaryTextAssigned = false;
535
+ return inputIds.map((compId) => {
536
+ if (stateByComponentId.has(compId)) {
537
+ return stateByComponentId.get(compId);
538
+ }
539
+ const comp = componentsMap.get(compId);
540
+ if (!comp)
541
+ return null;
542
+ const type = String(comp.type || '').toLowerCase();
543
+ const props = comp.props || {};
544
+ const label = String(props.label || props.name || '').toLowerCase();
545
+ if (type === 'state') {
546
+ return props.value ?? null;
547
+ }
548
+ if (type === 'image') {
549
+ const isSecondaryMultiView = /\b(back|left|right|bottom|top)\b/i.test(label);
550
+ if (!primaryImageAssigned && !isSecondaryMultiView && uploadedImageInput) {
551
+ primaryImageAssigned = true;
552
+ return uploadedImageInput;
553
+ }
554
+ return null;
555
+ }
556
+ if (type === 'gallery') {
557
+ return Array.isArray(props.value) ? props.value : [];
558
+ }
559
+ if (type === 'textbox' || type === 'text') {
560
+ if (!primaryTextAssigned || /prompt|caption|description|text/i.test(label)) {
561
+ primaryTextAssigned = true;
562
+ return request.prompt || props.value || '';
563
+ }
564
+ return props.value ?? '';
565
+ }
566
+ if (type === 'number' || type === 'slider') {
567
+ if (label.includes('seed')) {
568
+ return typeof request.seed === 'number' ? request.seed : (props.value ?? 42);
569
+ }
570
+ if (label.includes('octree')) {
571
+ return request.octreeResolution || props.value || 256;
572
+ }
573
+ return props.value !== undefined && props.value !== null
574
+ ? props.value
575
+ : (props.minimum ?? 1);
576
+ }
577
+ if (type === 'checkbox') {
578
+ if (label.includes('random') && label.includes('seed')) {
579
+ return typeof request.seed === 'number' ? false : (props.value ?? true);
580
+ }
581
+ if (label.includes('texture')) {
582
+ return request.generateTextures !== false;
583
+ }
584
+ return props.value !== undefined ? Boolean(props.value) : true;
585
+ }
586
+ if (type === 'radio' || type === 'dropdown') {
587
+ if (props.value !== undefined && props.value !== null) {
588
+ return props.value;
589
+ }
590
+ if (Array.isArray(props.choices) && props.choices.length > 0) {
591
+ const first = props.choices[0];
592
+ return Array.isArray(first) ? first[1] : first;
593
+ }
594
+ return null;
595
+ }
596
+ return props.value ?? null;
597
+ });
598
+ }
599
+ static async uploadGradioImage(rootUrl, apiPrefix, imageUrl, isGradio3, uploadId, headers, fetchFn, signal) {
600
+ if (isGradio3 && imageUrl.startsWith('data:')) {
601
+ return imageUrl;
602
+ }
603
+ try {
604
+ let bytes;
605
+ let mimeType = 'image/png';
606
+ if (imageUrl.startsWith('data:')) {
607
+ const match = imageUrl.match(/^data:([^;]+);base64,(.*)$/);
608
+ if (match) {
609
+ mimeType = match[1] || 'image/png';
610
+ bytes = this.decodeBase64(match[2]);
611
+ }
612
+ else {
613
+ return imageUrl;
614
+ }
615
+ }
616
+ else {
617
+ const imgRes = await fetchFn(imageUrl, { method: 'GET', signal });
618
+ if (!imgRes.ok)
619
+ return imageUrl;
620
+ mimeType = imgRes.headers?.get?.('content-type') || 'image/png';
621
+ bytes = new Uint8Array(await imgRes.arrayBuffer());
622
+ }
623
+ if (typeof FormData === 'undefined' || typeof Blob === 'undefined') {
624
+ return imageUrl;
625
+ }
626
+ const ext = mimeType.includes('jpeg') || mimeType.includes('jpg') ? 'jpg' : 'png';
627
+ const fileName = `input.${ext}`;
628
+ const formData = new FormData();
629
+ formData.append('files', new Blob([bytes], { type: mimeType }), fileName);
630
+ const uploadHeaders = {};
631
+ if (headers.Authorization) {
632
+ uploadHeaders.Authorization = headers.Authorization;
633
+ }
634
+ const uploadCandidates = apiPrefix
635
+ ? [`${rootUrl}${apiPrefix}/upload?upload_id=${uploadId}`, `${rootUrl}/upload?upload_id=${uploadId}`]
636
+ : [`${rootUrl}/upload?upload_id=${uploadId}`, `${rootUrl}/gradio_api/upload?upload_id=${uploadId}`];
637
+ for (const uploadUrl of uploadCandidates) {
638
+ const upRes = await fetchFn(uploadUrl, {
639
+ method: 'POST',
640
+ headers: uploadHeaders,
641
+ body: formData,
642
+ signal,
643
+ });
644
+ if (upRes && upRes.ok) {
645
+ const upText = await this.readResponseText(upRes);
646
+ const upJson = JSON.parse(upText);
647
+ const uploadedItem = Array.isArray(upJson) ? upJson[0] : upJson;
648
+ const uploadedPath = typeof uploadedItem === 'string' ? uploadedItem : uploadedItem?.path || uploadedItem?.name;
649
+ if (typeof uploadedPath === 'string' && uploadedPath.trim()) {
650
+ return {
651
+ path: uploadedPath,
652
+ url: `${rootUrl}${apiPrefix}/file=${uploadedPath}`,
653
+ orig_name: fileName,
654
+ size: bytes.byteLength,
655
+ mime_type: mimeType,
656
+ is_stream: false,
657
+ meta: { _type: 'gradio.FileData' },
658
+ };
659
+ }
660
+ }
661
+ if (upRes && upRes.status !== 404) {
662
+ break;
663
+ }
664
+ }
665
+ }
666
+ catch {
667
+ // Fall back to passing imageUrl directly
668
+ }
669
+ return imageUrl;
670
+ }
671
+ static async callGradioDependency(rootUrl, apiPrefix, dep, data, sessionHash, isGradio3, providerName, headers, fetchFn, signal, onStatus) {
672
+ const payload = {
673
+ data,
674
+ event_data: null,
675
+ fn_index: dep.fnIndex,
676
+ session_hash: sessionHash,
677
+ };
678
+ // 1. Gradio 4 / 5 /call/<apiName> SSE endpoint (preferred when apiName is known and queue !== false)
679
+ if (!isGradio3 && dep.apiName && dep.queue !== false) {
680
+ const callUrl = `${rootUrl}${apiPrefix}/call/${dep.apiName}`;
681
+ const callRes = await fetchFn(callUrl, {
682
+ method: 'POST',
683
+ headers,
684
+ body: JSON.stringify(payload),
685
+ signal,
686
+ });
687
+ if (callRes && callRes.ok) {
688
+ const callText = await this.readResponseText(callRes);
689
+ const callJson = JSON.parse(callText);
690
+ if (callJson?.event_id) {
691
+ const streamUrl = `${rootUrl}${apiPrefix}/call/${dep.apiName}/${callJson.event_id}`;
692
+ const streamRes = await fetchFn(streamUrl, {
693
+ method: 'GET',
694
+ headers: {
695
+ Accept: 'text/event-stream',
696
+ ...(headers.Authorization ? { Authorization: headers.Authorization } : {}),
697
+ },
698
+ signal,
699
+ });
700
+ if (!streamRes.ok) {
701
+ const errText = await this.readResponseText(streamRes).catch(() => '');
702
+ throw new Error(`${providerName} Gradio stream error (${streamRes.status}): ${errText || streamRes.statusText}`);
703
+ }
704
+ return await this.readGradioSseStream(streamRes, providerName, onStatus);
705
+ }
706
+ if (Array.isArray(callJson?.data)) {
707
+ return callJson;
708
+ }
709
+ }
710
+ }
711
+ // 2. Gradio 3 / 4 / 5 /queue/join + /queue/data SSE endpoint (works even when apiName is null/false or show_api=False)
712
+ if (dep.queue !== false) {
713
+ const joinUrl = `${rootUrl}${apiPrefix}/queue/join`;
714
+ const joinRes = await fetchFn(joinUrl, {
715
+ method: 'POST',
716
+ headers,
717
+ body: JSON.stringify(payload),
718
+ signal,
719
+ });
720
+ if (joinRes && joinRes.ok) {
721
+ const streamUrl = `${rootUrl}${apiPrefix}/queue/data?session_hash=${encodeURIComponent(sessionHash)}`;
722
+ const streamRes = await fetchFn(streamUrl, {
723
+ method: 'GET',
724
+ headers: {
725
+ Accept: 'text/event-stream',
726
+ ...(headers.Authorization ? { Authorization: headers.Authorization } : {}),
727
+ },
728
+ signal,
729
+ });
730
+ if (streamRes && streamRes.ok) {
731
+ return await this.readGradioSseStream(streamRes, providerName, onStatus);
732
+ }
733
+ }
734
+ }
735
+ // 3. Synchronous /run/<apiName>, /run/predict, /api/predict fallback
736
+ const syncUrls = [];
737
+ if (dep.apiName) {
738
+ syncUrls.push(`${rootUrl}${apiPrefix}/run/${dep.apiName}`);
739
+ }
740
+ syncUrls.push(`${rootUrl}${apiPrefix}/run/predict`);
741
+ syncUrls.push(`${rootUrl}${apiPrefix}/api/predict`);
742
+ if (apiPrefix) {
743
+ syncUrls.push(`${rootUrl}/run/predict`);
744
+ syncUrls.push(`${rootUrl}/api/predict`);
745
+ }
746
+ let lastRes = null;
747
+ for (const url of syncUrls) {
748
+ lastRes = await fetchFn(url, {
749
+ method: 'POST',
750
+ headers,
751
+ body: JSON.stringify(payload),
752
+ signal,
753
+ });
754
+ if (lastRes && lastRes.status !== 404) {
755
+ break;
756
+ }
757
+ }
758
+ if (!lastRes || !lastRes.ok) {
759
+ const errText = lastRes ? await this.readResponseText(lastRes).catch(() => '') : '';
760
+ throw new Error(`${providerName} Gradio error (${lastRes?.status || 'Network'}): ${errText || lastRes?.statusText || 'Failed'}`);
761
+ }
762
+ const syncText = await this.readResponseText(lastRes);
763
+ const syncJson = JSON.parse(syncText);
764
+ return Array.isArray(syncJson?.data) ? syncJson : { data: Array.isArray(syncJson) ? syncJson : [syncJson] };
765
+ }
766
+ static async readGradioSseStream(res, providerName, onStatus) {
767
+ const parseEvents = (rawSse) => {
768
+ const lines = rawSse.split(/\r?\n/);
769
+ let currentEvent = '';
770
+ for (const rawLine of lines) {
771
+ const line = rawLine.trim();
772
+ if (!line) {
773
+ currentEvent = '';
774
+ continue;
775
+ }
776
+ if (line.startsWith('event:')) {
777
+ currentEvent = line.slice(6).trim();
778
+ continue;
779
+ }
780
+ if (line.startsWith('data:')) {
781
+ const dataStr = line.slice(5).trim();
782
+ if (!dataStr || dataStr === '[DONE]')
783
+ continue;
784
+ if (currentEvent === 'error') {
785
+ let errMsg = dataStr;
786
+ try {
787
+ const parsedErr = JSON.parse(dataStr);
788
+ errMsg =
789
+ typeof parsedErr === 'string'
790
+ ? parsedErr
791
+ : parsedErr?.error || parsedErr?.message || JSON.stringify(parsedErr);
792
+ }
793
+ catch {
794
+ // keep raw string
795
+ }
796
+ return { done: true, error: `${providerName} Gradio error: ${errMsg}` };
797
+ }
798
+ if (currentEvent === 'complete') {
799
+ try {
800
+ const parsed = JSON.parse(dataStr);
801
+ return {
802
+ done: true,
803
+ result: { data: Array.isArray(parsed) ? parsed : [parsed] },
804
+ };
805
+ }
806
+ catch {
807
+ // wait for full JSON line
808
+ }
809
+ }
810
+ try {
811
+ const parsed = JSON.parse(dataStr);
812
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
813
+ if (parsed.msg === 'process_starts') {
814
+ onStatus?.(`${providerName}: processing in Gradio...`);
815
+ }
816
+ else if (parsed.msg === 'progress' &&
817
+ Array.isArray(parsed.progress_data) &&
818
+ parsed.progress_data[0]) {
819
+ const p = parsed.progress_data[0];
820
+ if (typeof p.index === 'number' && typeof p.length === 'number') {
821
+ onStatus?.(`${providerName}: step ${p.index}/${p.length} ${p.unit || ''}...`.trim());
822
+ }
823
+ }
824
+ else if (parsed.msg === 'process_completed') {
825
+ if (parsed.success === false || parsed.output?.error) {
826
+ return {
827
+ done: true,
828
+ error: `${providerName} Gradio error: ${parsed.output?.error || 'Process failed'}`,
829
+ };
830
+ }
831
+ if (Array.isArray(parsed.output?.data)) {
832
+ return { done: true, result: { data: parsed.output.data } };
833
+ }
834
+ }
835
+ else if (Array.isArray(parsed.data)) {
836
+ return { done: true, result: { data: parsed.data } };
837
+ }
838
+ }
839
+ }
840
+ catch {
841
+ // Ignore partial chunk lines
842
+ }
843
+ }
844
+ }
845
+ return { done: false };
846
+ };
847
+ if (res.body && typeof res.body.getReader === 'function') {
848
+ const reader = res.body.getReader();
849
+ const decoder = new TextDecoder();
850
+ let accumulated = '';
851
+ try {
852
+ while (true) {
853
+ const { done, value } = await reader.read();
854
+ if (done)
855
+ break;
856
+ accumulated += decoder.decode(value, { stream: true });
857
+ const check = parseEvents(accumulated);
858
+ if (check.done) {
859
+ await reader.cancel().catch(() => { });
860
+ if (check.error)
861
+ throw new Error(check.error);
862
+ if (check.result)
863
+ return check.result;
864
+ }
865
+ }
866
+ accumulated += decoder.decode();
867
+ }
868
+ finally {
869
+ reader.releaseLock?.();
870
+ }
871
+ const finalCheck = parseEvents(accumulated);
872
+ if (finalCheck.error)
873
+ throw new Error(finalCheck.error);
874
+ if (finalCheck.result)
875
+ return finalCheck.result;
876
+ throw new Error(`${providerName} Gradio stream ended without returning completion data.`);
877
+ }
878
+ const fullText = await this.readResponseText(res);
879
+ const check = parseEvents(fullText);
880
+ if (check.error)
881
+ throw new Error(check.error);
882
+ if (check.result)
883
+ return check.result;
884
+ throw new Error(`${providerName} Gradio stream ended without returning completion data.`);
885
+ }
886
+ static async readResponseText(res) {
887
+ if (typeof res.text === 'function') {
888
+ return await res.text();
889
+ }
890
+ if (typeof res.arrayBuffer === 'function') {
891
+ const ab = await res.arrayBuffer();
892
+ return new TextDecoder().decode(new Uint8Array(ab));
893
+ }
894
+ return '';
895
+ }
896
+ static async executeFalRequest(provider, request, fetchFn) {
897
+ const url = provider.endpointUrl.trim();
898
+ const headers = {
899
+ 'Content-Type': 'application/json',
900
+ Accept: 'application/json',
901
+ };
902
+ if (provider.apiKey && provider.apiKey.trim()) {
903
+ const key = provider.apiKey.trim();
904
+ headers['Authorization'] = key.startsWith('Key ') || key.startsWith('Bearer ') ? key : `Key ${key}`;
905
+ }
906
+ const payload = {
907
+ prompt: request.prompt,
908
+ texture: request.generateTextures !== false,
909
+ };
910
+ if (request.imageUrl) {
911
+ payload.image_url = request.imageUrl;
912
+ }
913
+ if (typeof request.seed === 'number') {
914
+ payload.seed = request.seed;
915
+ }
916
+ const res = await fetchFn(url, {
917
+ method: 'POST',
918
+ headers,
919
+ body: JSON.stringify(payload),
920
+ signal: request.signal,
921
+ });
922
+ if (!res.ok) {
923
+ const errText = await res.text().catch(() => '');
924
+ throw new Error(`${provider.name} (Fal.ai) error (${res.status}): ${errText || res.statusText}`);
925
+ }
926
+ return await this.parseHttpResponseToMeshResult(res, provider, url, fetchFn, request.signal);
927
+ }
928
+ static async executeReplicateRequest(provider, request, fetchFn) {
929
+ const url = provider.endpointUrl.trim();
930
+ const headers = {
931
+ 'Content-Type': 'application/json',
932
+ Accept: 'application/json',
933
+ Prefer: 'wait',
934
+ };
935
+ if (provider.apiKey && provider.apiKey.trim()) {
936
+ const key = provider.apiKey.trim();
937
+ headers['Authorization'] = key.startsWith('Bearer ') || key.startsWith('Token ') ? key : `Bearer ${key}`;
938
+ }
939
+ const payload = {
940
+ version: provider.modelId || provider.id,
941
+ model: provider.modelId || provider.id,
942
+ input: {
943
+ prompt: request.prompt,
944
+ image: request.imageUrl,
945
+ generate_model: true,
946
+ texture: request.generateTextures !== false,
947
+ },
948
+ };
949
+ const res = await fetchFn(url, {
950
+ method: 'POST',
951
+ headers,
952
+ body: JSON.stringify(payload),
953
+ signal: request.signal,
954
+ });
955
+ if (!res.ok) {
956
+ const errText = await res.text().catch(() => '');
957
+ throw new Error(`${provider.name} (Replicate) error (${res.status}): ${errText || res.statusText}`);
958
+ }
959
+ return await this.parseHttpResponseToMeshResult(res, provider, url, fetchFn, request.signal);
960
+ }
961
+ /**
962
+ * Inspects an HTTP response (binary GLB/OBJ/STL or JSON with base64 / file URL / raw mesh data)
963
+ * and normalizes it into a Neural3DGenerationResult.
964
+ */
965
+ static async parseHttpResponseToMeshResult(res, provider, baseEndpointUrl, fetchFn, signal, preferTextured = true, gradioApiPrefix = '') {
966
+ const contentType = (res.headers?.get?.('content-type') || '').toLowerCase();
967
+ // 1. Direct binary response (model/gltf-binary, application/octet-stream, model/stl, model/obj)
968
+ if (contentType.includes('model/gltf-binary') ||
969
+ contentType.includes('application/octet-stream') ||
970
+ contentType.includes('model/stl') ||
971
+ contentType.includes('model/obj')) {
972
+ const ab = await res.arrayBuffer();
973
+ const bytes = new Uint8Array(ab);
974
+ const format = this.detectBinaryFormat(bytes, contentType);
975
+ return {
976
+ providerId: provider.id,
977
+ providerName: provider.name,
978
+ modelId: provider.modelId || provider.id,
979
+ format,
980
+ data: bytes,
981
+ };
982
+ }
983
+ // Read arrayBuffer first so we can handle both binary responses missing Content-Type and JSON/text
984
+ const rawBuffer = await res.arrayBuffer();
985
+ const rawBytes = new Uint8Array(rawBuffer);
986
+ // Check for glTF binary magic header "glTF" (0x67, 0x6C, 0x54, 0x46)
987
+ if (rawBytes.length >= 4 &&
988
+ rawBytes[0] === 0x67 &&
989
+ rawBytes[1] === 0x6c &&
990
+ rawBytes[2] === 0x54 &&
991
+ rawBytes[3] === 0x46) {
992
+ return {
993
+ providerId: provider.id,
994
+ providerName: provider.name,
995
+ modelId: provider.modelId || provider.id,
996
+ format: 'glb',
997
+ data: rawBytes,
998
+ };
999
+ }
1000
+ const text = new TextDecoder().decode(rawBytes).trim();
1001
+ // Check if response is raw Wavefront OBJ text
1002
+ if ((text.startsWith('#') || text.startsWith('v ') || text.startsWith('o ')) &&
1003
+ /\nv\s+[-0-9.]+\s+[-0-9.]+\s+[-0-9.]+/.test('\n' + text)) {
1004
+ return {
1005
+ providerId: provider.id,
1006
+ providerName: provider.name,
1007
+ modelId: provider.modelId || provider.id,
1008
+ format: 'obj',
1009
+ data: rawBytes,
1010
+ textData: text,
1011
+ };
1012
+ }
1013
+ let json;
1014
+ try {
1015
+ json = JSON.parse(text);
1016
+ }
1017
+ catch {
1018
+ throw new Error(`Unexpected non-JSON, non-binary response from ${provider.name}: ${text.slice(0, 180)}`);
1019
+ }
1020
+ // 2. Direct JSON mesh vertices/indices representation
1021
+ const meshDataObj = json?.mesh_data || json?.geometry || (Array.isArray(json?.positions) || Array.isArray(json?.vertices) ? json : null);
1022
+ if (meshDataObj &&
1023
+ (Array.isArray(meshDataObj.positions) || Array.isArray(meshDataObj.vertices)) &&
1024
+ (Array.isArray(meshDataObj.indices) || Array.isArray(meshDataObj.faces))) {
1025
+ const rawPositions = meshDataObj.positions || meshDataObj.vertices;
1026
+ const positions = Array.isArray(rawPositions[0])
1027
+ ? rawPositions.flat().map(Number)
1028
+ : rawPositions.map(Number);
1029
+ const rawIndices = meshDataObj.indices || meshDataObj.faces;
1030
+ const indices = Array.isArray(rawIndices[0])
1031
+ ? rawIndices.flat().map(Number)
1032
+ : rawIndices.map(Number);
1033
+ return {
1034
+ providerId: provider.id,
1035
+ providerName: provider.name,
1036
+ modelId: provider.modelId || provider.id,
1037
+ format: 'json_mesh',
1038
+ data: rawBytes,
1039
+ textData: text,
1040
+ jsonMesh: {
1041
+ positions,
1042
+ indices,
1043
+ normals: Array.isArray(meshDataObj.normals) ? meshDataObj.normals.flat().map(Number) : undefined,
1044
+ uvs: Array.isArray(meshDataObj.uvs) ? meshDataObj.uvs.flat().map(Number) : undefined,
1045
+ colors: Array.isArray(meshDataObj.colors) ? meshDataObj.colors.flat().map(Number) : undefined,
1046
+ },
1047
+ };
1048
+ }
1049
+ // 3. Wavefront OBJ text inside JSON
1050
+ const objText = json?.obj || json?.obj_text || json?.data?.[0]?.obj;
1051
+ if (typeof objText === 'string' && objText.includes('v ')) {
1052
+ const encoded = new TextEncoder().encode(objText);
1053
+ return {
1054
+ providerId: provider.id,
1055
+ providerName: provider.name,
1056
+ modelId: provider.modelId || provider.id,
1057
+ format: 'obj',
1058
+ data: encoded,
1059
+ textData: objText,
1060
+ };
1061
+ }
1062
+ // 4. Base64-encoded GLB/OBJ/STL inside JSON
1063
+ const b64Candidate = json?.glb_base64 ||
1064
+ json?.b64_glb ||
1065
+ json?.mesh_base64 ||
1066
+ json?.model_base64 ||
1067
+ json?.file_base64 ||
1068
+ json?.b64_json ||
1069
+ json?.data?.[0]?.b64_glb ||
1070
+ json?.data?.[0]?.b64_json ||
1071
+ json?.data?.[0]?.glb_base64;
1072
+ if (typeof b64Candidate === 'string' && b64Candidate.trim().length > 0) {
1073
+ const cleanB64 = b64Candidate
1074
+ .trim()
1075
+ .replace(/^data:[^;]+;base64,/, '');
1076
+ const decodedBytes = this.decodeBase64(cleanB64);
1077
+ const format = this.detectBinaryFormat(decodedBytes, json?.format || 'glb');
1078
+ return {
1079
+ providerId: provider.id,
1080
+ providerName: provider.name,
1081
+ modelId: provider.modelId || provider.id,
1082
+ format,
1083
+ data: decodedBytes,
1084
+ textData: format === 'obj' ? new TextDecoder().decode(decodedBytes) : undefined,
1085
+ };
1086
+ }
1087
+ // 5. URL reference inside JSON (Fal.ai, Replicate, Gradio, oMLX file URL)
1088
+ const extractedUrl = this.extractModelUrlFromJson(json, baseEndpointUrl, gradioApiPrefix, preferTextured);
1089
+ if (extractedUrl) {
1090
+ let fileRes = await fetchFn(extractedUrl, {
1091
+ method: 'GET',
1092
+ signal,
1093
+ });
1094
+ // Fallback for Gradio 5 /gradio_api/file= vs Gradio 3/4 /file=
1095
+ if (fileRes.status === 404 && extractedUrl.includes('/file=')) {
1096
+ const altUrl = extractedUrl.includes('/gradio_api/file=')
1097
+ ? extractedUrl.replace('/gradio_api/file=', '/file=')
1098
+ : extractedUrl.replace('/file=', '/gradio_api/file=');
1099
+ const altRes = await fetchFn(altUrl, {
1100
+ method: 'GET',
1101
+ signal,
1102
+ });
1103
+ if (altRes.ok) {
1104
+ fileRes = altRes;
1105
+ }
1106
+ }
1107
+ if (!fileRes.ok) {
1108
+ throw new Error(`Failed to download generated 3D model from ${extractedUrl} (HTTP ${fileRes.status})`);
1109
+ }
1110
+ const fileBuf = await fileRes.arrayBuffer();
1111
+ const fileBytes = new Uint8Array(fileBuf);
1112
+ const format = this.detectBinaryFormat(fileBytes, extractedUrl);
1113
+ return {
1114
+ providerId: provider.id,
1115
+ providerName: provider.name,
1116
+ modelId: provider.modelId || provider.id,
1117
+ format,
1118
+ data: fileBytes,
1119
+ textData: format === 'obj' ? new TextDecoder().decode(fileBytes) : undefined,
1120
+ sourceUrl: extractedUrl,
1121
+ };
1122
+ }
1123
+ throw new Error(`Could not extract 3D mesh (GLB/OBJ/STL) from ${provider.name} response.`);
1124
+ }
1125
+ static extractModelUrlFromJson(json, baseEndpointUrl, gradioApiPrefix = '', preferTextured = true) {
1126
+ if (!json || typeof json !== 'object')
1127
+ return null;
1128
+ const isNonMeshMediaUrl = (s) => /\.(mp4|webm|mov|avi|png|jpg|jpeg|webp|gif|svg|html|json)(\?.*)?$/i.test(s.trim());
1129
+ const isMeshExtension = (s) => /\.(glb|gltf|obj|stl|ply)(\?.*)?$/i.test(s.trim());
1130
+ const rawCandidates = [];
1131
+ const pushCandidate = (val, isGradioFilePath = false) => {
1132
+ if (typeof val !== 'string' || !val.trim())
1133
+ return;
1134
+ const trimmed = val.trim();
1135
+ if (trimmed.startsWith('<') || isNonMeshMediaUrl(trimmed))
1136
+ return;
1137
+ if (isGradioFilePath) {
1138
+ rawCandidates.push(this.resolveGradioFileUrl(baseEndpointUrl, trimmed, gradioApiPrefix));
1139
+ }
1140
+ else {
1141
+ rawCandidates.push(trimmed);
1142
+ }
1143
+ };
1144
+ pushCandidate(json.url);
1145
+ pushCandidate(json.glb_url);
1146
+ pushCandidate(json.mesh_url);
1147
+ pushCandidate(json.model_url);
1148
+ pushCandidate(json.model_mesh?.url);
1149
+ pushCandidate(json.mesh?.url);
1150
+ pushCandidate(json.glb?.url);
1151
+ pushCandidate(json.output?.model);
1152
+ pushCandidate(json.output?.glb);
1153
+ pushCandidate(json.output?.mesh);
1154
+ if (typeof json.output === 'string') {
1155
+ pushCandidate(json.output);
1156
+ }
1157
+ else if (Array.isArray(json.output)) {
1158
+ const meshOut = json.output.find((item) => typeof item === 'string' && isMeshExtension(item)) ||
1159
+ json.output[0];
1160
+ pushCandidate(meshOut);
1161
+ }
1162
+ // Inspect all elements of json.data (Gradio outputs array)
1163
+ if (Array.isArray(json.data)) {
1164
+ const gradioUrls = [];
1165
+ const extractFromGradioItem = (item) => {
1166
+ if (!item)
1167
+ return;
1168
+ if (typeof item === 'string') {
1169
+ const s = item.trim();
1170
+ if (!s || s.startsWith('<') || isNonMeshMediaUrl(s))
1171
+ return;
1172
+ if (s.startsWith('http://') ||
1173
+ s.startsWith('https://') ||
1174
+ s.startsWith('data:') ||
1175
+ s.startsWith('/file=') ||
1176
+ s.startsWith('/gradio_api/file=')) {
1177
+ gradioUrls.push(s);
1178
+ }
1179
+ else if (isMeshExtension(s) ||
1180
+ /^(\/|[a-zA-Z]:\\)/.test(s)) {
1181
+ gradioUrls.push(this.resolveGradioFileUrl(baseEndpointUrl, s, gradioApiPrefix));
1182
+ }
1183
+ return;
1184
+ }
1185
+ if (typeof item === 'object') {
1186
+ // Handle gr.update(value=...) wrapper
1187
+ if (item.value !== undefined && item.value !== null && item.value !== item) {
1188
+ extractFromGradioItem(item.value);
1189
+ }
1190
+ if (typeof item.url === 'string' && item.url.trim() && !isNonMeshMediaUrl(item.url)) {
1191
+ gradioUrls.push(item.url.trim());
1192
+ }
1193
+ else if (typeof item.path === 'string' &&
1194
+ item.path.trim() &&
1195
+ !isNonMeshMediaUrl(item.path)) {
1196
+ gradioUrls.push(this.resolveGradioFileUrl(baseEndpointUrl, item.path.trim(), gradioApiPrefix));
1197
+ }
1198
+ else if (typeof item.name === 'string' &&
1199
+ item.name.trim() &&
1200
+ !isNonMeshMediaUrl(item.name)) {
1201
+ gradioUrls.push(this.resolveGradioFileUrl(baseEndpointUrl, item.name.trim(), gradioApiPrefix));
1202
+ }
1203
+ }
1204
+ };
1205
+ for (const item of json.data) {
1206
+ extractFromGradioItem(item);
1207
+ }
1208
+ if (gradioUrls.length > 0) {
1209
+ // Prefer explicitly textured mesh URL when preferTextured is true (e.g. Hunyuan3D [white_mesh.glb, textured_mesh.glb])
1210
+ if (preferTextured && gradioUrls.length > 1) {
1211
+ const texturedMatch = gradioUrls.find((u) => /textured|paint|color/i.test(u));
1212
+ if (texturedMatch) {
1213
+ rawCandidates.push(texturedMatch);
1214
+ }
1215
+ }
1216
+ for (const u of gradioUrls) {
1217
+ rawCandidates.push(u);
1218
+ }
1219
+ }
1220
+ }
1221
+ for (const c of rawCandidates) {
1222
+ if (typeof c === 'string' && c.trim()) {
1223
+ const val = c.trim();
1224
+ if (val.startsWith('http://') ||
1225
+ val.startsWith('https://') ||
1226
+ val.startsWith('data:') ||
1227
+ val.startsWith('/')) {
1228
+ if (val.startsWith('/') && /^https?:\/\//i.test(baseEndpointUrl)) {
1229
+ try {
1230
+ const u = new URL(baseEndpointUrl);
1231
+ return `${u.origin}${val}`;
1232
+ }
1233
+ catch {
1234
+ return val;
1235
+ }
1236
+ }
1237
+ return val;
1238
+ }
1239
+ }
1240
+ }
1241
+ return null;
1242
+ }
1243
+ static resolveGradioFileUrl(baseEndpointUrl, filePath, gradioApiPrefix = '') {
1244
+ const cleanBase = baseEndpointUrl
1245
+ .replace(/\/(gradio_api\/)?(api|run|call)\/.*$/i, '')
1246
+ .replace(/\/+$/, '');
1247
+ const prefix = gradioApiPrefix
1248
+ ? '/' + gradioApiPrefix.replace(/^\/+|\/+$/g, '')
1249
+ : '';
1250
+ // Preserve leading slash for absolute Unix paths (/tmp/..., /var/..., /Users/...) required by Gradio /file=
1251
+ const normalizedPath = filePath.trim();
1252
+ return `${cleanBase}${prefix}/file=${normalizedPath}`;
1253
+ }
1254
+ static detectBinaryFormat(bytes, hint = '') {
1255
+ if (bytes.length >= 4 &&
1256
+ bytes[0] === 0x67 &&
1257
+ bytes[1] === 0x6c &&
1258
+ bytes[2] === 0x54 &&
1259
+ bytes[3] === 0x46) {
1260
+ return 'glb';
1261
+ }
1262
+ const lowerHint = (hint || '').toLowerCase();
1263
+ if (lowerHint.includes('.obj') || lowerHint.includes('model/obj') || lowerHint === 'obj') {
1264
+ return 'obj';
1265
+ }
1266
+ if (lowerHint.includes('.stl') || lowerHint.includes('model/stl') || lowerHint === 'stl') {
1267
+ return 'stl';
1268
+ }
1269
+ // Check if ASCII text looks like Wavefront OBJ
1270
+ if (bytes.length > 4 && bytes.length < 50_000_000) {
1271
+ const head = new TextDecoder().decode(bytes.subarray(0, Math.min(256, bytes.length)));
1272
+ if ((head.startsWith('#') || head.startsWith('v ') || head.startsWith('o ')) && head.includes('v ')) {
1273
+ return 'obj';
1274
+ }
1275
+ }
1276
+ return 'glb';
1277
+ }
1278
+ static decodeBase64(b64) {
1279
+ const nodeBuffer = globalThis.Buffer;
1280
+ if (typeof nodeBuffer !== 'undefined') {
1281
+ return new Uint8Array(nodeBuffer.from(b64, 'base64'));
1282
+ }
1283
+ const binStr = atob(b64);
1284
+ const bytes = new Uint8Array(binStr.length);
1285
+ for (let i = 0; i < binStr.length; i++) {
1286
+ bytes[i] = binStr.charCodeAt(i);
1287
+ }
1288
+ return bytes;
1289
+ }
1290
+ /**
1291
+ * Tests connectivity to a configured Neural 3D Generator endpoint.
1292
+ */
1293
+ static async testProviderConnection(provider, customFetch) {
1294
+ const fetchFn = customFetch || globalThis.fetch.bind(globalThis);
1295
+ const rawUrl = (provider.endpointUrl || '').trim();
1296
+ if (!rawUrl) {
1297
+ return { ok: false, message: 'Endpoint URL is empty.' };
1298
+ }
1299
+ const headers = {
1300
+ Accept: 'application/json',
1301
+ };
1302
+ if (provider.apiKey && provider.apiKey.trim()) {
1303
+ const key = provider.apiKey.trim();
1304
+ headers['Authorization'] =
1305
+ provider.protocol === 'fal' && !key.startsWith('Key ')
1306
+ ? `Key ${key}`
1307
+ : key.startsWith('Bearer ') || key.startsWith('Key ')
1308
+ ? key
1309
+ : `Bearer ${key}`;
1310
+ }
1311
+ // Build ordered candidate probe URLs based on protocol
1312
+ const probeUrls = [];
1313
+ try {
1314
+ const parsed = new URL(rawUrl);
1315
+ if (provider.protocol === 'omlx') {
1316
+ probeUrls.push(`${parsed.origin}/v1/models`, `${parsed.origin}/health`, rawUrl);
1317
+ }
1318
+ else if (provider.protocol === 'gradio') {
1319
+ const cleanGradioBase = rawUrl
1320
+ .replace(/\/(gradio_api\/)?(api|run|call)\/.*$/i, '')
1321
+ .replace(/\/(gradio_api\/)?(info|config)$/i, '')
1322
+ .replace(/\/+$/, '');
1323
+ // /config is always available across Gradio 3, 4, and 5 (even when show_api=False)
1324
+ probeUrls.push(`${cleanGradioBase}/config`, `${cleanGradioBase}/gradio_api/info`, `${cleanGradioBase}/info`, `${cleanGradioBase}/`);
1325
+ }
1326
+ else if (provider.protocol === 'local_rest') {
1327
+ probeUrls.push(`${parsed.origin}/health`, `${parsed.origin}/docs`, rawUrl);
1328
+ }
1329
+ else {
1330
+ probeUrls.push(rawUrl);
1331
+ }
1332
+ }
1333
+ catch {
1334
+ probeUrls.push(rawUrl);
1335
+ }
1336
+ let lastStatus = 0;
1337
+ let lastStatusText = '';
1338
+ for (const probeUrl of probeUrls) {
1339
+ try {
1340
+ const res = await fetchFn(probeUrl, {
1341
+ method: 'GET',
1342
+ headers,
1343
+ });
1344
+ lastStatus = res.status;
1345
+ lastStatusText = res.statusText || '';
1346
+ if (res.status === 401 || res.status === 403) {
1347
+ return {
1348
+ ok: false,
1349
+ message: `${provider.name} reachable, but authentication failed (HTTP ${res.status}). Check API Key.`,
1350
+ };
1351
+ }
1352
+ // For POST-only endpoints (like /generate or fal.run), 405 Method Not Allowed or 422 means the server is alive and reachable
1353
+ if (res.ok || res.status === 405 || res.status === 422) {
1354
+ if (provider.protocol === 'gradio' && probeUrl.endsWith('/config') && res.ok) {
1355
+ try {
1356
+ const cfgText = await this.readResponseText(res);
1357
+ const cfgJson = JSON.parse(cfgText);
1358
+ if (cfgJson && (cfgJson.version || Array.isArray(cfgJson.dependencies))) {
1359
+ const ver = cfgJson.version ? ` v${cfgJson.version}` : '';
1360
+ const epCount = Array.isArray(cfgJson.dependencies)
1361
+ ? `, ${cfgJson.dependencies.length} endpoints`
1362
+ : '';
1363
+ return {
1364
+ ok: true,
1365
+ message: `${provider.name} reachable (Gradio${ver}${epCount}).`,
1366
+ };
1367
+ }
1368
+ }
1369
+ catch {
1370
+ // Fall through to standard success message
1371
+ }
1372
+ }
1373
+ return {
1374
+ ok: true,
1375
+ message: `${provider.name} reachable (${provider.protocol}, HTTP ${res.status}).`,
1376
+ };
1377
+ }
1378
+ // If 404, try the next candidate probe URL
1379
+ if (res.status === 404) {
1380
+ continue;
1381
+ }
1382
+ }
1383
+ catch (err) {
1384
+ if (probeUrl === probeUrls[probeUrls.length - 1]) {
1385
+ return {
1386
+ ok: false,
1387
+ message: `Could not reach ${provider.name} at ${rawUrl}: ${err?.message || String(err)}`,
1388
+ };
1389
+ }
1390
+ }
1391
+ }
1392
+ return {
1393
+ ok: false,
1394
+ message: `${provider.name} returned HTTP ${lastStatus || 404} (${lastStatusText || 'Not Found'}).`,
1395
+ };
1396
+ }
1397
+ }