@holoscript/core 6.0.4 → 7.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (236) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1 -1
  3. package/dist/compiler/index.d.ts +82 -0
  4. package/dist/constants.d.ts +3 -2
  5. package/dist/coordinators/index.d.ts +189 -0
  6. package/dist/index.d.ts +501 -19
  7. package/dist/paper-0c-spike/index.d.ts +29 -0
  8. package/dist/reconstruction/index.d.ts +78 -0
  9. package/dist/tools/index.d.ts +22 -1
  10. package/dist/traitDocs/traitDocs.d.ts +69 -0
  11. package/dist/traits/index.d.ts +61 -0
  12. package/package.json +105 -57
  13. package/dist/GLTFPipeline-DEN36VNK.js +0 -12
  14. package/dist/GLTFPipeline-YPCAK236.cjs +0 -33
  15. package/dist/HoloScriptPlusParser-BN6KVRCM.js +0 -692
  16. package/dist/HoloScriptPlusParser-NC5FE6AL.cjs +0 -697
  17. package/dist/USDZExporter-NTMBNTDB.js +0 -707
  18. package/dist/USDZExporter-UWGWNMMD.cjs +0 -709
  19. package/dist/chunk-27LWW5FU.cjs +0 -410
  20. package/dist/chunk-2CWOLHTE.js +0 -69
  21. package/dist/chunk-33LSUQDD.cjs +0 -835
  22. package/dist/chunk-3FJCK5XA.js +0 -2232
  23. package/dist/chunk-3FXV5S25.cjs +0 -633
  24. package/dist/chunk-3FYZOR7S.cjs +0 -69
  25. package/dist/chunk-3SAK5KFL.cjs +0 -83
  26. package/dist/chunk-4XSNJCLC.cjs +0 -1859
  27. package/dist/chunk-54FHG2MX.js +0 -655
  28. package/dist/chunk-56IF4NTA.js +0 -56
  29. package/dist/chunk-5BGSECRJ.cjs +0 -2237
  30. package/dist/chunk-5GLCTO44.js +0 -161
  31. package/dist/chunk-5O6TQC6M.cjs +0 -1871
  32. package/dist/chunk-5OEOHAAW.cjs +0 -682
  33. package/dist/chunk-5TOFIR6L.js +0 -407
  34. package/dist/chunk-5WUNN6ZN.cjs +0 -428
  35. package/dist/chunk-6TZPZCOJ.cjs +0 -1404
  36. package/dist/chunk-6UEHYZ7V.cjs +0 -773
  37. package/dist/chunk-6XSERL6L.js +0 -5678
  38. package/dist/chunk-72EQECGT.cjs +0 -908
  39. package/dist/chunk-7AGYRWKW.cjs +0 -507
  40. package/dist/chunk-7LCYLPW2.cjs +0 -663
  41. package/dist/chunk-A7PIMZGU.js +0 -263
  42. package/dist/chunk-ATSKSYVE.cjs +0 -51683
  43. package/dist/chunk-B5TCIAPQ.cjs +0 -117
  44. package/dist/chunk-BF2235SI.cjs +0 -5714
  45. package/dist/chunk-BKIGPPVM.js +0 -629
  46. package/dist/chunk-BND3ST2K.cjs +0 -662
  47. package/dist/chunk-BU7VWW2K.js +0 -2522
  48. package/dist/chunk-BWFJEM5A.js +0 -5419
  49. package/dist/chunk-CAUCGUEA.cjs +0 -130
  50. package/dist/chunk-CBJSLA2E.cjs +0 -5423
  51. package/dist/chunk-CDPGV4DN.js +0 -114
  52. package/dist/chunk-CLYEIWA5.cjs +0 -408
  53. package/dist/chunk-CS2EMTGF.js +0 -1966
  54. package/dist/chunk-DMG7C4H2.js +0 -975
  55. package/dist/chunk-DXJQDCFL.js +0 -468
  56. package/dist/chunk-E3FWRT3Z.js +0 -608
  57. package/dist/chunk-E3UALNFA.js +0 -421
  58. package/dist/chunk-EONILVMF.js +0 -762
  59. package/dist/chunk-EQV4R3EV.cjs +0 -769
  60. package/dist/chunk-F3HH56EB.cjs +0 -5538
  61. package/dist/chunk-F4IULT7N.js +0 -1488
  62. package/dist/chunk-FF3Q7ADR.js +0 -380
  63. package/dist/chunk-FFKU7BTK.cjs +0 -1046
  64. package/dist/chunk-FHQVYCH2.js +0 -70
  65. package/dist/chunk-FSF7EQVA.cjs +0 -1974
  66. package/dist/chunk-G4VZTCIB.js +0 -659
  67. package/dist/chunk-G7CT3EMP.cjs +0 -1002
  68. package/dist/chunk-GGHSW2NN.js +0 -51334
  69. package/dist/chunk-GVUR45UF.cjs +0 -777
  70. package/dist/chunk-H5Z7NASB.js +0 -9662
  71. package/dist/chunk-HE7ULERA.cjs +0 -697
  72. package/dist/chunk-HJJLD366.js +0 -1169
  73. package/dist/chunk-HPS76H7Q.js +0 -309
  74. package/dist/chunk-HQUEA5R6.cjs +0 -424
  75. package/dist/chunk-HYNTS5CP.js +0 -422
  76. package/dist/chunk-I6XZ5DZF.cjs +0 -488
  77. package/dist/chunk-IBDG74G2.cjs +0 -1219
  78. package/dist/chunk-IFNQFCTM.js +0 -3098
  79. package/dist/chunk-IHOUYQIA.js +0 -406
  80. package/dist/chunk-ILRBGFVD.cjs +0 -72
  81. package/dist/chunk-IWI6J7FX.js +0 -421
  82. package/dist/chunk-K3JDKWGI.cjs +0 -270
  83. package/dist/chunk-K6EKD26I.js +0 -630
  84. package/dist/chunk-KCQ5NDYC.cjs +0 -3172
  85. package/dist/chunk-KED34ILP.js +0 -832
  86. package/dist/chunk-KSGXLT74.cjs +0 -457
  87. package/dist/chunk-L4G4RLXX.js +0 -767
  88. package/dist/chunk-LDP5OK6G.js +0 -1216
  89. package/dist/chunk-LGGRPKTV.cjs +0 -735
  90. package/dist/chunk-LK5IAVH6.cjs +0 -1173
  91. package/dist/chunk-LSW7P7ML.js +0 -3675
  92. package/dist/chunk-LXJ4667L.cjs +0 -3874
  93. package/dist/chunk-LZ266PCM.cjs +0 -4499
  94. package/dist/chunk-MD6KDHVE.cjs +0 -237
  95. package/dist/chunk-MEASWI2Y.js +0 -126
  96. package/dist/chunk-MPXBVFHQ.js +0 -768
  97. package/dist/chunk-N5FTS757.cjs +0 -415
  98. package/dist/chunk-NCUKG4SK.cjs +0 -3075
  99. package/dist/chunk-NDQNIJEH.js +0 -1715
  100. package/dist/chunk-NOZZ46QU.js +0 -168
  101. package/dist/chunk-OFKWH2IP.js +0 -449
  102. package/dist/chunk-PHENW4MQ.js +0 -65
  103. package/dist/chunk-PMGODDJA.cjs +0 -319
  104. package/dist/chunk-Q4QX3AET.cjs +0 -1505
  105. package/dist/chunk-Q56TT7IL.js +0 -483
  106. package/dist/chunk-Q5JT3YML.cjs +0 -129
  107. package/dist/chunk-Q5SJOGHQ.cjs +0 -4256
  108. package/dist/chunk-QGKNANZ3.js +0 -3071
  109. package/dist/chunk-QLEAOI3Q.cjs +0 -424
  110. package/dist/chunk-R7MA7QWV.js +0 -732
  111. package/dist/chunk-RVYPEYPX.js +0 -678
  112. package/dist/chunk-S2N5TNMA.js +0 -1855
  113. package/dist/chunk-S565K7NK.js +0 -752
  114. package/dist/chunk-SDAMZIRE.js +0 -765
  115. package/dist/chunk-T36DDXSF.js +0 -4250
  116. package/dist/chunk-T4NKMBDL.js +0 -5474
  117. package/dist/chunk-T7LEXZUZ.cjs +0 -2526
  118. package/dist/chunk-TEWCN33Y.js +0 -694
  119. package/dist/chunk-TQSZUOW5.cjs +0 -793
  120. package/dist/chunk-TSH3MSQU.cjs +0 -129
  121. package/dist/chunk-UERJ3YJV.js +0 -504
  122. package/dist/chunk-UPJBDCVF.js +0 -1395
  123. package/dist/chunk-V3NN3HPP.js +0 -4462
  124. package/dist/chunk-VJ3L7CHT.cjs +0 -169
  125. package/dist/chunk-WB4Z63GG.js +0 -229
  126. package/dist/chunk-WDW67DZB.cjs +0 -9728
  127. package/dist/chunk-WGMEAYBG.js +0 -126
  128. package/dist/chunk-X4ZF6CNE.cjs +0 -473
  129. package/dist/chunk-X6SEAXAX.cjs +0 -3681
  130. package/dist/chunk-XCWFGZAA.js +0 -1043
  131. package/dist/chunk-XD6IYDUX.js +0 -903
  132. package/dist/chunk-XG23EUQX.cjs +0 -1717
  133. package/dist/chunk-XRKWN5PL.cjs +0 -173
  134. package/dist/chunk-XUILI4KB.cjs +0 -430
  135. package/dist/chunk-XUTX5CBW.js +0 -126
  136. package/dist/chunk-XWPNTWDN.cjs +0 -755
  137. package/dist/chunk-XXINBTZK.cjs +0 -633
  138. package/dist/chunk-YCXFCXDS.js +0 -1868
  139. package/dist/chunk-YQK5JNFK.js +0 -3725
  140. package/dist/chunk-YYXH45E2.js +0 -426
  141. package/dist/chunk-Z34RLXRA.cjs +0 -612
  142. package/dist/chunk-ZP4D3CSX.cjs +0 -72
  143. package/dist/cli/holoscript-runner.cjs +0 -2259
  144. package/dist/cli/holoscript-runner.js +0 -2234
  145. package/dist/codebase/index.cjs +0 -336
  146. package/dist/codebase/index.js +0 -331
  147. package/dist/compiler/agent-inference.cjs +0 -28
  148. package/dist/compiler/agent-inference.js +0 -5
  149. package/dist/compiler/android-xr.cjs +0 -19
  150. package/dist/compiler/android-xr.js +0 -9
  151. package/dist/compiler/android.cjs +0 -20
  152. package/dist/compiler/android.js +0 -10
  153. package/dist/compiler/ar.cjs +0 -20
  154. package/dist/compiler/ar.js +0 -8
  155. package/dist/compiler/babylon.cjs +0 -17
  156. package/dist/compiler/babylon.js +0 -11
  157. package/dist/compiler/coco.cjs +0 -27
  158. package/dist/compiler/coco.js +0 -4
  159. package/dist/compiler/domain-block-utils.cjs +0 -602
  160. package/dist/compiler/domain-block-utils.js +0 -8
  161. package/dist/compiler/dtdl.cjs +0 -24
  162. package/dist/compiler/dtdl.js +0 -8
  163. package/dist/compiler/gltf-pipeline.cjs +0 -39
  164. package/dist/compiler/gltf-pipeline.js +0 -4
  165. package/dist/compiler/godot.cjs +0 -15
  166. package/dist/compiler/godot.js +0 -9
  167. package/dist/compiler/incremental.cjs +0 -29
  168. package/dist/compiler/incremental.js +0 -4
  169. package/dist/compiler/index.cjs +0 -2578
  170. package/dist/compiler/index.js +0 -2383
  171. package/dist/compiler/ios.cjs +0 -20
  172. package/dist/compiler/ios.js +0 -10
  173. package/dist/compiler/multi-layer.cjs +0 -20
  174. package/dist/compiler/multi-layer.js +0 -11
  175. package/dist/compiler/nodetoy.cjs +0 -23
  176. package/dist/compiler/nodetoy.js +0 -4
  177. package/dist/compiler/openxr.cjs +0 -15
  178. package/dist/compiler/openxr.js +0 -9
  179. package/dist/compiler/playcanvas.cjs +0 -16
  180. package/dist/compiler/playcanvas.js +0 -10
  181. package/dist/compiler/r3f.cjs +0 -34
  182. package/dist/compiler/r3f.js +0 -12
  183. package/dist/compiler/remotion.cjs +0 -23
  184. package/dist/compiler/remotion.js +0 -4
  185. package/dist/compiler/reproducibility.cjs +0 -39
  186. package/dist/compiler/reproducibility.js +0 -4
  187. package/dist/compiler/sdf.cjs +0 -21
  188. package/dist/compiler/sdf.js +0 -9
  189. package/dist/compiler/semantic-scene.cjs +0 -31
  190. package/dist/compiler/semantic-scene.js +0 -4
  191. package/dist/compiler/state.cjs +0 -17
  192. package/dist/compiler/state.js +0 -7
  193. package/dist/compiler/trait-composition.cjs +0 -26
  194. package/dist/compiler/trait-composition.js +0 -5
  195. package/dist/compiler/unity.cjs +0 -15
  196. package/dist/compiler/unity.js +0 -9
  197. package/dist/compiler/unreal.cjs +0 -19
  198. package/dist/compiler/unreal.js +0 -9
  199. package/dist/compiler/urdf.cjs +0 -45
  200. package/dist/compiler/urdf.js +0 -9
  201. package/dist/compiler/usd-physics.cjs +0 -23
  202. package/dist/compiler/usd-physics.js +0 -6
  203. package/dist/compiler/visionos.cjs +0 -15
  204. package/dist/compiler/visionos.js +0 -9
  205. package/dist/compiler/vrchat.cjs +0 -19
  206. package/dist/compiler/vrchat.js +0 -9
  207. package/dist/compiler/vrr.cjs +0 -21
  208. package/dist/compiler/vrr.js +0 -9
  209. package/dist/compiler/wasm.cjs +0 -33
  210. package/dist/compiler/wasm.js +0 -9
  211. package/dist/compiler/webgpu.cjs +0 -15
  212. package/dist/compiler/webgpu.js +0 -9
  213. package/dist/debugger.cjs +0 -21
  214. package/dist/debugger.js +0 -8
  215. package/dist/entries/interop.cjs +0 -62
  216. package/dist/entries/interop.js +0 -5
  217. package/dist/entries/scripting.cjs +0 -68
  218. package/dist/entries/scripting.js +0 -11
  219. package/dist/index.cjs +0 -40921
  220. package/dist/index.js +0 -37763
  221. package/dist/math/vec3.cjs +0 -57
  222. package/dist/math/vec3.js +0 -4
  223. package/dist/ml-dsa-PHCWUBPX.cjs +0 -1178
  224. package/dist/ml-dsa-WYLJHJO6.js +0 -1178
  225. package/dist/parser.cjs +0 -27
  226. package/dist/parser.js +0 -10
  227. package/dist/playwright-5OSAPTNH.js +0 -98660
  228. package/dist/playwright-RL6GY4F7.cjs +0 -98673
  229. package/dist/runtime.cjs +0 -16
  230. package/dist/runtime.js +0 -7
  231. package/dist/storage/index.cjs +0 -37
  232. package/dist/storage/index.js +0 -4
  233. package/dist/traits/index.cjs +0 -14649
  234. package/dist/traits/index.js +0 -12243
  235. package/dist/type-checker.cjs +0 -18
  236. package/dist/type-checker.js +0 -5
@@ -1,2383 +0,0 @@
1
- export { createReproducibilityContext, parseReproducibilityFlags } from '../chunk-5GLCTO44.js';
2
- export { GLTF_PIPELINE_TOOLS, registerGLTFTools } from '../chunk-OFKWH2IP.js';
3
- export { NodeToyMapper, mapNodeToyToShader } from '../chunk-IHOUYQIA.js';
4
- import { init_A2AAgentCardCompiler, A2AAgentCardCompiler_exports, init_NIRCompiler, NIRCompiler_exports } from '../chunk-T4NKMBDL.js';
5
- export { CompilerBridge, USDZPipeline, bestCategoryForTraits, compilePipelineSource, compilePipelineSourceToNode, compilePipelineSourceToPython, compilePipelineToNode, compilePipelineToPython, quickSafetyCheck, runSafetyPass, selectModality, selectModalityForAll } from '../chunk-T4NKMBDL.js';
6
- export { generateHullGeometry, generateMembraneGeometry, generateSplineGeometry } from '../chunk-HJJLD366.js';
7
- export { RemotionBridgeImpl as RemotionBridge } from '../chunk-YYXH45E2.js';
8
- export { SemanticSceneGraph } from '../chunk-HYNTS5CP.js';
9
- import '../chunk-XD6IYDUX.js';
10
- export { COCOExporterImpl as COCOExporter } from '../chunk-Q56TT7IL.js';
11
- import { init_DTDLCompiler, DTDLCompiler_exports } from '../chunk-IWI6J7FX.js';
12
- export { DTDLCompiler } from '../chunk-IWI6J7FX.js';
13
- import { init_URDFCompiler, URDFCompiler_exports } from '../chunk-UPJBDCVF.js';
14
- export { URDFCompiler } from '../chunk-UPJBDCVF.js';
15
- export { USDPhysicsCompiler } from '../chunk-SDAMZIRE.js';
16
- import { init_SDFCompiler, SDFCompiler_exports } from '../chunk-UERJ3YJV.js';
17
- export { SDFCompiler } from '../chunk-UERJ3YJV.js';
18
- import { init_StateCompiler, StateCompiler_exports } from '../chunk-CDPGV4DN.js';
19
- export { StateCompiler } from '../chunk-CDPGV4DN.js';
20
- export { TraitCompositionCompiler } from '../chunk-NOZZ46QU.js';
21
- export { IncrementalCompiler } from '../chunk-CS2EMTGF.js';
22
- import { init_R3FCompiler, R3FCompiler_exports } from '../chunk-T36DDXSF.js';
23
- export { ENVIRONMENT_PRESETS, R3FCompiler } from '../chunk-T36DDXSF.js';
24
- import '../chunk-H5Z7NASB.js';
25
- import { init_PlayCanvasCompiler, PlayCanvasCompiler_exports } from '../chunk-S565K7NK.js';
26
- export { PlayCanvasCompiler } from '../chunk-S565K7NK.js';
27
- import { init_AndroidCompiler, AndroidCompiler_exports } from '../chunk-QGKNANZ3.js';
28
- export { AndroidCompiler } from '../chunk-QGKNANZ3.js';
29
- import { init_AndroidXRCompiler, AndroidXRCompiler_exports } from '../chunk-S2N5TNMA.js';
30
- export { AndroidXRCompiler } from '../chunk-S2N5TNMA.js';
31
- import { init_IOSCompiler, IOSCompiler_exports } from '../chunk-BWFJEM5A.js';
32
- export { IOSCompiler } from '../chunk-BWFJEM5A.js';
33
- import { init_VisionOSCompiler, VisionOSCompiler_exports } from '../chunk-YCXFCXDS.js';
34
- export { VisionOSCompiler } from '../chunk-YCXFCXDS.js';
35
- import { init_WASMCompiler, WASMCompiler_exports } from '../chunk-L4G4RLXX.js';
36
- export { WASMCompiler } from '../chunk-L4G4RLXX.js';
37
- import { init_WebGPUCompiler, WebGPUCompiler_exports } from '../chunk-G4VZTCIB.js';
38
- export { WebGPUCompiler } from '../chunk-G4VZTCIB.js';
39
- export { MultiLayerCompiler } from '../chunk-FHQVYCH2.js';
40
- import { init_ARCompiler, ARCompiler_exports } from '../chunk-MEASWI2Y.js';
41
- export { ARCompiler } from '../chunk-MEASWI2Y.js';
42
- import { init_OpenXRCompiler, OpenXRCompiler_exports } from '../chunk-XCWFGZAA.js';
43
- export { OpenXRCompiler } from '../chunk-XCWFGZAA.js';
44
- import { init_VRChatCompiler, VRChatCompiler_exports } from '../chunk-E3FWRT3Z.js';
45
- export { VRChatCompiler } from '../chunk-E3FWRT3Z.js';
46
- import { init_BabylonCompiler, BabylonCompiler_exports } from '../chunk-KED34ILP.js';
47
- export { BabylonCompiler } from '../chunk-KED34ILP.js';
48
- import '../chunk-A7PIMZGU.js';
49
- import '../chunk-DXJQDCFL.js';
50
- import { init_UnityCompiler, UnityCompiler_exports } from '../chunk-TEWCN33Y.js';
51
- export { UnityCompiler } from '../chunk-TEWCN33Y.js';
52
- import { init_UnrealCompiler, UnrealCompiler_exports } from '../chunk-RVYPEYPX.js';
53
- import { init_GodotCompiler, GodotCompiler_exports } from '../chunk-K6EKD26I.js';
54
- export { GodotCompiler } from '../chunk-K6EKD26I.js';
55
- import '../chunk-56IF4NTA.js';
56
- import { init_constants, CONNECTOR_PACKAGES, CONNECTOR_ENV_REQUIREMENTS, KNOWN_CONNECTORS } from '../chunk-NDQNIJEH.js';
57
- import '../chunk-IFNQFCTM.js';
58
- import '../chunk-HPS76H7Q.js';
59
- import '../chunk-WB4Z63GG.js';
60
- import '../chunk-XUTX5CBW.js';
61
- import { init_VRRCompiler, VRRCompiler_exports } from '../chunk-R7MA7QWV.js';
62
- import '../chunk-YQK5JNFK.js';
63
- import { init_CompilerBase, CompilerBase, init_identity, ANSCapabilityPath, init_CompilerDocumentationGenerator } from '../chunk-6XSERL6L.js';
64
- export { CompilerBase, CompilerDocumentationGenerator, UnauthorizedCompilerAccessError, createTestCompilerToken, isCapabilityTokenCredential } from '../chunk-6XSERL6L.js';
65
- import { __export, __esm, __toCommonJS } from '../chunk-2CWOLHTE.js';
66
-
67
- // src/compiler/Native2DCompiler.ts
68
- var Native2DCompiler_exports = {};
69
- __export(Native2DCompiler_exports, {
70
- Native2DCompiler: () => Native2DCompiler
71
- });
72
- var Native2DCompiler;
73
- var init_Native2DCompiler = __esm({
74
- "src/compiler/Native2DCompiler.ts"() {
75
- init_CompilerBase();
76
- Native2DCompiler = class extends CompilerBase {
77
- constructor() {
78
- super(...arguments);
79
- this.compilerName = "Native2DCompiler";
80
- // ============================================================================
81
- // REACT GENERATION
82
- // ============================================================================
83
- /** Collected during node traversal — used to generate imports and hooks */
84
- this._slotImports = /* @__PURE__ */ new Map();
85
- this._uiImports = /* @__PURE__ */ new Set();
86
- this._stateFields = /* @__PURE__ */ new Map();
87
- this._fetchCalls = [];
88
- this._options = {};
89
- }
90
- // @ts-expect-error During migration
91
- compile(composition, agentToken, outputPath, options) {
92
- this.validateCompilerAccess(agentToken, outputPath);
93
- const isReact = options?.format === "react";
94
- const elements = composition.ui?.elements || composition.objects || [];
95
- if (isReact) {
96
- const code = this.generateReactComponent(composition.name, elements, composition, options);
97
- if (options?.generateDocs) {
98
- return {
99
- output: code,
100
- documentation: this.generateDocumentation(composition, code, options.docsOptions)
101
- };
102
- }
103
- return code;
104
- } else {
105
- const code = this.generateHTMLPage(composition.name, elements, composition);
106
- if (options?.generateDocs) {
107
- return {
108
- output: code,
109
- documentation: this.generateDocumentation(composition, code, options.docsOptions)
110
- };
111
- }
112
- return code;
113
- }
114
- }
115
- generateReactComponent(name, objects, composition, options) {
116
- this._slotImports.clear();
117
- this._uiImports.clear();
118
- this._stateFields.clear();
119
- this._fetchCalls = [];
120
- this._options = options || {};
121
- const safeName = name.replace(/[^a-zA-Z0-9]/g, "");
122
- if (composition?.state?.properties) {
123
- for (const prop of composition.state.properties) {
124
- this._stateFields.set(prop.key, prop.value ?? null);
125
- }
126
- }
127
- const jsx = objects.map((obj) => this.generateReactNode(obj)).join("\n ");
128
- const imports = [];
129
- const reactImports = /* @__PURE__ */ new Set();
130
- if (this._stateFields.size > 0) reactImports.add("useState");
131
- if (this._fetchCalls.length > 0) reactImports.add("useEffect");
132
- imports.push(
133
- reactImports.size > 0 ? `import React, { ${[...reactImports].join(", ")} } from 'react';` : `import React from 'react';`
134
- );
135
- if (this._uiImports.size > 0) {
136
- imports.push(`import { ${[...this._uiImports].join(", ")} } from '@holoscript/ui';`);
137
- }
138
- for (const [, slot] of this._slotImports) {
139
- imports.push(`import { ${slot.component} } from '${slot.importPath}';`);
140
- }
141
- const stateHooks = [];
142
- for (const [key, value] of this._stateFields) {
143
- const capitalKey = key.charAt(0).toUpperCase() + key.slice(1);
144
- const initValue = JSON.stringify(value);
145
- stateHooks.push(
146
- ` const [${key}, set${capitalKey}] = useState(${initValue === void 0 ? "null" : initValue});`
147
- );
148
- }
149
- const fetchEffects = [];
150
- for (const f of this._fetchCalls) {
151
- fetchEffects.push(` useEffect(() => {
152
- fetch(\`${f.endpoint}\`${f.method !== "GET" ? `, { method: '${f.method}' }` : ""})
153
- .then(r => r.json())
154
- .then(set${f.name.charAt(0).toUpperCase() + f.name.slice(1)})
155
- .catch(console.error);
156
- }, []);`);
157
- }
158
- return `${imports.join("\n")}
159
-
160
- // @generated by HoloScript Native2DCompiler \u2014 DO NOT EDIT
161
- export function ${safeName}Component() {
162
- ${stateHooks.join("\n")}
163
- ${fetchEffects.join("\n")}
164
-
165
- return (
166
- <div className="holoscript-2d-root w-full h-full">
167
- ${jsx}
168
- </div>
169
- );
170
- }
171
-
172
- export default ${safeName}Component;
173
- `;
174
- }
175
- generateReactNode(obj) {
176
- const traits = this.extractTraits(obj);
177
- if (traits.slot) {
178
- const slotName = traits.slot.name || obj.name || "Slot";
179
- const configuredSlot = this._options.slots?.[String(slotName)];
180
- const component = traits.slot.component || configuredSlot?.component || slotName;
181
- const importPath = traits.slot.import || configuredSlot?.importPath || `@/components/${component}`;
182
- this._slotImports.set(slotName, { component, importPath });
183
- const propsStr = traits.slot.props ? ` {...${JSON.stringify(traits.slot.props)}}` : "";
184
- return `<div data-holo-slot="${slotName}">
185
- <${component}${propsStr} />
186
- </div>`;
187
- }
188
- if (traits.fetch) {
189
- const name = traits.fetch.into || "data";
190
- const endpoint = traits.fetch.endpoint || "/api/data";
191
- const method = traits.fetch.method || "GET";
192
- this._fetchCalls.push({ name, endpoint, method });
193
- if (!this._stateFields.has(name)) {
194
- this._stateFields.set(name, null);
195
- }
196
- }
197
- let tag = traits.theme?.tag || traits.panel?.tag || (typeof obj.type === "string" ? obj.type.toLowerCase() : void 0) || "div";
198
- if ([
199
- "nav",
200
- "section",
201
- "main",
202
- "footer",
203
- "form",
204
- "style",
205
- "a",
206
- "header",
207
- "h1",
208
- "h2",
209
- "h3"
210
- ].includes(tag)) ; else if (tag === "container") {
211
- tag = "div";
212
- } else if (traits.link || tag === "link") {
213
- tag = "a";
214
- } else if (traits.button || tag === "button") {
215
- tag = "button";
216
- } else if (traits.image || tag === "image") {
217
- tag = "img";
218
- } else if (traits.input || tag === "input") {
219
- tag = "input";
220
- } else if (traits.text || tag === "text") {
221
- tag = this.mapTextVariantToTag(traits.text?.variant || "body");
222
- } else {
223
- tag = "div";
224
- }
225
- const styles = this.buildStyles(traits);
226
- const classes = this.buildClasses(traits);
227
- let props = ``;
228
- if (traits.theme?.className) {
229
- classes.push(traits.theme.className);
230
- }
231
- if (traits.theme?.id) {
232
- props += ` id="${traits.theme.id}"`;
233
- }
234
- const combinedStyles = { ...styles };
235
- if (traits.theme?.style) {
236
- traits.theme.style.split(";").forEach((rule) => {
237
- const [key, ...valueParts] = rule.split(":");
238
- const value = valueParts.join(":");
239
- if (key && value) {
240
- const camelKey = key.trim().replace(/-([a-z])/g, (g) => g[1].toUpperCase());
241
- combinedStyles[camelKey] = value.trim();
242
- }
243
- });
244
- }
245
- if (Object.keys(combinedStyles).length > 0) {
246
- props += ` style={${JSON.stringify(combinedStyles)}}`;
247
- }
248
- if (classes.length > 0) {
249
- props += ` className="${classes.join(" ")}"`;
250
- }
251
- if (traits.theme?.attributes) {
252
- try {
253
- const parsedAttrs = JSON.parse(traits.theme.attributes);
254
- for (const [key, value] of Object.entries(parsedAttrs)) {
255
- props += ` ${key}="${value}"`;
256
- }
257
- } catch (e) {
258
- }
259
- }
260
- if (traits.button?.onClick || traits.form?.onSubmit) {
261
- const action = traits.button?.onClick || traits.form?.onSubmit;
262
- if (action) {
263
- const cleanAction = action.replace(/["']/g, "'");
264
- if (cleanAction.includes("navigate")) {
265
- props += ` onClick={() => ${cleanAction}}`;
266
- } else if (cleanAction.includes("submit")) {
267
- props += ` onSubmit={${cleanAction}}`;
268
- } else if (cleanAction.includes("window.open")) {
269
- props += ` onClick={() => ${cleanAction}}`;
270
- } else {
271
- props += ` onClick={() => console.log('${cleanAction}')}`;
272
- }
273
- }
274
- }
275
- if (traits.image?.src) props += ` src="${traits.image.src}"`;
276
- if (traits.image?.alt) props += ` alt="${traits.image.alt}"`;
277
- if (traits.link?.href) props += ` href="${traits.link.href}"`;
278
- if (traits.input?.placeholder) props += ` placeholder="${traits.input.placeholder}"`;
279
- if (traits.input?.type) props += ` type="${traits.input.type}"`;
280
- if (traits.input?.required) props += ` required`;
281
- if (traits.button?.type) props += ` type="${traits.button.type}"`;
282
- const childrenMarkup = (obj.children || obj.objects || []).map((child) => this.generateReactNode(child)).join("\n");
283
- const content = traits.text?.content || traits.button?.content || traits.link?.content || traits.icon?.name;
284
- let safeContent = "";
285
- if (content) {
286
- safeContent = `{\`${content.replace(/`/g, "\\`").replace(/\$/g, "\\$")}\`}`;
287
- }
288
- if (tag === "style") {
289
- const escapedStyle = (content || "").replace(/`/g, "\\`").replace(/\$/g, "\\$");
290
- return `<style dangerouslySetInnerHTML={{ __html: \`${escapedStyle}\` }} />`;
291
- }
292
- if (tag === "img" || tag === "input") {
293
- return `<${tag}${props} />`;
294
- }
295
- return `<${tag}${props}>
296
- ${safeContent}
297
- ${childrenMarkup}
298
- </${tag}>`;
299
- }
300
- // ============================================================================
301
- // HTML GENERATION
302
- // ============================================================================
303
- generateHTMLPage(name, objects, composition) {
304
- const content = objects.map((obj) => this.generateHTMLNode(obj)).join("\n ");
305
- let bgColor = "#ffffff";
306
- let color = "#000000";
307
- if (composition.environment?.properties) {
308
- const themeProp = composition.environment.properties.find((p) => p.key === "theme");
309
- const bgProp = composition.environment.properties.find((p) => p.key === "backgroundColor");
310
- if (themeProp?.value === "dark" || composition.traits?.some((t) => t.name === "theme" && t.config?.dark)) {
311
- bgColor = bgProp?.value || "#050510";
312
- color = "#ffffff";
313
- }
314
- }
315
- return `<!DOCTYPE html>
316
- <html lang="en">
317
- <head>
318
- <meta charset="UTF-8">
319
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
320
- <title>${name}</title>
321
- <script src="https://cdn.tailwindcss.com"></script>
322
- <style>
323
- body { margin: 0; padding: 0; background-color: ${bgColor}; color: ${color}; font-family: system-ui, -apple-system, sans-serif; }
324
- /* Basic resets and custom trait animations to mirror React Framer variants */
325
- .glow-btn:hover { box-shadow: 0 0 15px rgba(255,255,255,0.5); }
326
- .lift-card { transition: transform 0.2s ease, box-shadow 0.2s ease; }
327
- .lift-card:hover { transform: translateY(-4px); box-shadow: 0 10px 20px rgba(0,0,0,0.2); }
328
- </style>
329
- </head>
330
- <body>
331
- <div id="holoscript-native-root">
332
- ${content}
333
- </div>
334
- <script>
335
- function navigate(path) { window.location.href = path; }
336
- function submitNewsletter(e) { e.preventDefault(); alert('Subscribed!'); }
337
- </script>
338
- </body>
339
- </html>`;
340
- }
341
- generateHTMLNode(obj) {
342
- const node = obj;
343
- const traits = this.extractTraits(obj);
344
- const nodeType = typeof node.type === "string" ? node.type.toLowerCase() : void 0;
345
- let tag = traits.theme?.tag || traits.panel?.tag || nodeType || "div";
346
- if ([
347
- "nav",
348
- "section",
349
- "main",
350
- "footer",
351
- "form",
352
- "style",
353
- "a",
354
- "header",
355
- "h1",
356
- "h2",
357
- "h3"
358
- ].includes(tag)) ; else if (tag === "container") {
359
- tag = "div";
360
- } else if (traits.link || tag === "link") {
361
- tag = "a";
362
- } else if (traits.button || tag === "button") {
363
- tag = "button";
364
- } else if (traits.image || tag === "image") {
365
- tag = "img";
366
- } else if (traits.input || tag === "input") {
367
- tag = "input";
368
- } else if (traits.text || tag === "text") {
369
- tag = this.mapTextVariantToTag(traits.text?.variant || "body");
370
- } else {
371
- tag = "div";
372
- }
373
- const styles = this.buildStyles(traits);
374
- const classes = this.buildClasses(traits);
375
- let props = ``;
376
- if (traits.theme?.className) {
377
- classes.push(traits.theme.className);
378
- }
379
- if (traits.theme?.id) {
380
- props += ` id="${traits.theme.id}"`;
381
- }
382
- if (Object.keys(styles).length > 0 || traits.theme?.style) {
383
- let styleStr = Object.entries(styles).map(([k, v]) => `${this.camelToKebab(k)}: ${v}`).join("; ");
384
- if (traits.theme?.style) {
385
- styleStr += (styleStr ? "; " : "") + traits.theme.style;
386
- }
387
- props += ` style="${styleStr}"`;
388
- }
389
- if (classes.length > 0) {
390
- props += ` class="${classes.join(" ")}"`;
391
- }
392
- if (traits.theme?.attributes) {
393
- try {
394
- const parsedAttrs = JSON.parse(traits.theme.attributes);
395
- for (const [key, value] of Object.entries(parsedAttrs)) {
396
- props += ` ${key}="${value}"`;
397
- }
398
- } catch (e) {
399
- }
400
- }
401
- if (traits.button?.onClick) props += ` onclick="${traits.button.onClick}"`;
402
- if (traits.form?.onSubmit) props += ` onsubmit="${traits.form.onSubmit}"`;
403
- if (traits.image?.src) props += ` src="${traits.image.src}"`;
404
- if (traits.image?.alt) props += ` alt="${traits.image.alt}"`;
405
- if (traits.link?.href) props += ` href="${traits.link.href}"`;
406
- if (traits.input?.placeholder) props += ` placeholder="${traits.input.placeholder}"`;
407
- if (traits.input?.type) props += ` type="${traits.input.type}"`;
408
- if (traits.input?.required) props += ` required`;
409
- const children = node.children || node.objects || [];
410
- const childrenMarkup = children.map((child) => this.generateHTMLNode(child)).join("\n");
411
- const content = traits.text?.content || traits.button?.content || traits.link?.content || traits.icon?.name;
412
- if (tag === "img" || tag === "input") {
413
- return `<${tag}${props}>`;
414
- }
415
- return `<${tag}${props}>
416
- ${content ? content : ""}
417
- ${childrenMarkup}
418
- </${tag}>`;
419
- }
420
- // ============================================================================
421
- // UTILITIES
422
- // ============================================================================
423
- extractTraits(obj) {
424
- const map = {};
425
- const node = obj;
426
- if (!node.traits) return map;
427
- for (const t of node.traits) {
428
- map[t.name] = t.config || {};
429
- if (t.name === "tailwind" && typeof t.config === "string") {
430
- map[t.name] = { classes: t.config };
431
- }
432
- }
433
- return map;
434
- }
435
- mapTextVariantToTag(variant) {
436
- switch (variant) {
437
- case "h1":
438
- return "h1";
439
- case "h2":
440
- return "h2";
441
- case "h3":
442
- return "h3";
443
- case "subtitle":
444
- return "h4";
445
- case "caption":
446
- return "span";
447
- case "emoji":
448
- return "span";
449
- default:
450
- return "p";
451
- }
452
- }
453
- buildStyles(traits) {
454
- const styles = {};
455
- const layout = traits.layout;
456
- const theme = traits.theme;
457
- if (layout) {
458
- if (layout.flex) {
459
- styles.display = "flex";
460
- styles.flexDirection = layout.flex === "row" ? "row" : "column";
461
- }
462
- if (layout.grid) {
463
- styles.display = "grid";
464
- styles.gridTemplateColumns = `repeat(${layout.columns || 1}, minmax(0, 1fr))`;
465
- }
466
- if (layout.justify) styles.justifyContent = layout.justify;
467
- if (layout.align) styles.alignItems = layout.align;
468
- if (layout.gap) styles.gap = typeof layout.gap === "number" ? `${layout.gap}px` : layout.gap;
469
- if (layout.padding)
470
- styles.padding = typeof layout.padding === "number" ? `${layout.padding}px` : layout.padding;
471
- }
472
- if (theme) {
473
- if (theme.backgroundColor) styles.backgroundColor = theme.backgroundColor;
474
- if (theme.color) styles.color = theme.color;
475
- if (theme.padding)
476
- styles.padding = typeof theme.padding === "number" ? `${theme.padding}px` : theme.padding;
477
- if (theme.borderRadius)
478
- styles.borderRadius = typeof theme.borderRadius === "number" ? `${theme.borderRadius}px` : theme.borderRadius;
479
- if (theme.border) styles.border = theme.border;
480
- if (theme.borderTop) styles.borderTop = theme.borderTop;
481
- }
482
- if (traits.text) {
483
- if (traits.text.align) styles.textAlign = traits.text.align;
484
- if (traits.text.maxWidth)
485
- styles.maxWidth = typeof traits.text.maxWidth === "number" ? `${traits.text.maxWidth}px` : traits.text.maxWidth;
486
- if (traits.text.weight) styles.fontWeight = traits.text.weight;
487
- }
488
- return styles;
489
- }
490
- buildClasses(traits) {
491
- const classes = [];
492
- if (traits.text) {
493
- if (traits.text.variant === "h1") classes.push("text-5xl font-bold tracking-tight");
494
- if (traits.text.variant === "h2") classes.push("text-3xl font-bold");
495
- if (traits.text.variant === "h3") classes.push("text-xl font-semibold");
496
- if (traits.text.variant === "subtitle") classes.push("text-xl text-gray-400");
497
- if (traits.text.variant === "caption") classes.push("text-sm text-gray-500");
498
- if (traits.text.variant === "emoji") classes.push("text-2xl");
499
- }
500
- if (traits.button) {
501
- classes.push("px-4 py-2 rounded-lg font-medium transition-all");
502
- if (traits.button.variant === "primary")
503
- classes.push("bg-blue-600 hover:bg-blue-700 text-white");
504
- if (traits.button.variant === "outline")
505
- classes.push("border border-gray-600 hover:bg-gray-800 text-white");
506
- if (traits.button.variant === "ghost")
507
- classes.push("hover:bg-gray-800 text-gray-300 hover:text-white");
508
- if (traits.button.variant === "glow")
509
- classes.push("bg-indigo-600 text-white glow-btn hover:bg-indigo-500");
510
- if (traits.button.size === "lg") classes.push("px-6 py-3 text-lg");
511
- if (traits.button.size === "sm") classes.push("px-3 py-1 text-sm");
512
- }
513
- if (traits.card) {
514
- if (traits.card.shadow === "md") classes.push("shadow-md");
515
- if (traits.card.shadow === "lg") classes.push("shadow-lg");
516
- if (traits.card.hover === "glow") classes.push("lift-card");
517
- }
518
- if (traits.input) {
519
- classes.push(
520
- "px-4 py-2 rounded-lg border border-gray-700 bg-gray-900 text-white focus:ring-2 focus:ring-indigo-500 outline-none"
521
- );
522
- }
523
- if (traits.tailwind?.classes) {
524
- classes.push(traits.tailwind.classes);
525
- }
526
- return classes;
527
- }
528
- camelToKebab(str) {
529
- return str.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase();
530
- }
531
- };
532
- }
533
- });
534
-
535
- // src/compiler/NextJSAPICompiler.ts
536
- var NextJSAPICompiler_exports = {};
537
- __export(NextJSAPICompiler_exports, {
538
- NextJSAPICompiler: () => NextJSAPICompiler,
539
- compileAllToNextJSAPI: () => compileAllToNextJSAPI,
540
- compileToNextJSAPI: () => compileToNextJSAPI
541
- });
542
- function toScalar(val) {
543
- if (val === null || val === void 0) return void 0;
544
- if (typeof val === "string" || typeof val === "number") return val;
545
- if (typeof val === "object" && !Array.isArray(val) && "value" in val) {
546
- return toScalar(val.value);
547
- }
548
- return void 0;
549
- }
550
- function findRootTrait(composition, traitName) {
551
- if (!composition.traits) return null;
552
- const found = composition.traits.find((t) => t.name === traitName);
553
- return found ? found.config : null;
554
- }
555
- function buildPropMap(obj) {
556
- const map = /* @__PURE__ */ new Map();
557
- for (const prop of obj.properties) {
558
- const scalar = toScalar(prop.value);
559
- if (scalar !== void 0) map.set(prop.key, scalar);
560
- }
561
- return map;
562
- }
563
- function toApiRouteSegment(name, override) {
564
- if (override) {
565
- return override.replace(/^\/+api\/+/, "").replace(/^\/+/, "").replace(/\/+$/, "");
566
- }
567
- return name.replace(/API$/, "").replace(/Api$/, "").replace(/([a-z0-9])([A-Z])/g, "$1-$2").replace(/([A-Z]{2,})([A-Z][a-z])/g, "$1-$2").toLowerCase().replace(/\s+/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "") || "api";
568
- }
569
- function parseMethod(raw) {
570
- if (raw === void 0) return void 0;
571
- const upper = String(raw).trim().toUpperCase();
572
- return VALID_METHODS.has(upper) ? upper : void 0;
573
- }
574
- function extractHandlers(composition) {
575
- const byMethod = /* @__PURE__ */ new Map();
576
- const rootHttp = findRootTrait(composition, "http");
577
- if (rootHttp) {
578
- const method = parseMethod(toScalar(rootHttp["method"]));
579
- if (method) {
580
- byMethod.set(method, {
581
- method,
582
- statusCode: Number(toScalar(rootHttp["statusCode"]) ?? toScalar(rootHttp["status"]) ?? 200),
583
- description: String(toScalar(rootHttp["description"]) ?? "")
584
- });
585
- }
586
- }
587
- for (const obj of composition.objects) {
588
- const hasHttpTrait = obj.traits.some((t) => t.name === "http");
589
- if (!hasHttpTrait) continue;
590
- const traitConfig = obj.traits.find((t) => t.name === "http")?.config ?? {};
591
- const props = buildPropMap(obj);
592
- const rawMethod = toScalar(traitConfig["method"]) ?? props.get("method");
593
- const method = parseMethod(rawMethod);
594
- if (!method) continue;
595
- const traitStatus = toScalar(traitConfig["statusCode"] ?? traitConfig["status"]);
596
- const propStatus = props.get("statusCode") ?? props.get("status");
597
- byMethod.set(method, {
598
- method,
599
- statusCode: Number(traitStatus ?? propStatus ?? 200),
600
- description: String(
601
- props.get("description") ?? toScalar(traitConfig["description"]) ?? obj.name ?? ""
602
- )
603
- });
604
- }
605
- return [...byMethod.values()];
606
- }
607
- function emitHandler(handler) {
608
- const { method, statusCode, description } = handler;
609
- const lines = [];
610
- const hasBody = BODY_METHODS.has(method);
611
- const isPassthrough = PASSTHROUGH_METHODS.has(method);
612
- if (description) {
613
- lines.push(`/** ${description} */`);
614
- }
615
- const param = isPassthrough ? "_request: Request" : "_request: NextRequest";
616
- lines.push(`export async function ${method}(${param}): Promise<NextResponse> {`);
617
- if (method === "HEAD") {
618
- lines.push(` return new NextResponse(null, { status: 200 });`);
619
- } else if (method === "DELETE") {
620
- const code = statusCode === 200 ? 204 : statusCode;
621
- lines.push(` return new NextResponse(null, { status: ${code} });`);
622
- } else if (hasBody) {
623
- lines.push(` let body: unknown;`);
624
- lines.push(` try {`);
625
- lines.push(` body = await _request.json();`);
626
- lines.push(` } catch {`);
627
- lines.push(` return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 });`);
628
- lines.push(` }`);
629
- lines.push(``);
630
- lines.push(` void body; // TODO: validate and process body`);
631
- lines.push(``);
632
- lines.push(` return NextResponse.json(`);
633
- lines.push(` { /* TODO: return response data */ },`);
634
- lines.push(` { status: ${statusCode} }`);
635
- lines.push(` );`);
636
- } else {
637
- lines.push(` return NextResponse.json(`);
638
- lines.push(` { /* TODO: return response data */ },`);
639
- lines.push(` { status: ${statusCode} }`);
640
- lines.push(` );`);
641
- }
642
- lines.push(`}`);
643
- return lines;
644
- }
645
- function compileToNextJSAPI(composition, options = {}) {
646
- let handlers = extractHandlers(composition);
647
- if (handlers.length === 0) {
648
- handlers = [
649
- {
650
- method: "GET",
651
- statusCode: 200,
652
- description: `${composition.name} API endpoint`
653
- }
654
- ];
655
- }
656
- const routeSegment = toApiRouteSegment(composition.name, options.apiRoute);
657
- const outputBase = options.outputDir ? options.outputDir.replace(/\/$/, "") : "api";
658
- const filePath = `${outputBase}/${routeSegment}/route.ts`;
659
- const lines = [];
660
- if (options.includeJsDoc !== false) {
661
- lines.push(`// @generated by HoloScript NextJSAPICompiler \u2014 DO NOT EDIT`);
662
- lines.push(`// Source composition: "${composition.name}"`);
663
- lines.push(`// Route: /${outputBase}/${routeSegment}`);
664
- lines.push(``);
665
- }
666
- const needsNextRequest = handlers.some((h) => !PASSTHROUGH_METHODS.has(h.method));
667
- if (needsNextRequest) {
668
- lines.push(`import { NextRequest, NextResponse } from 'next/server';`);
669
- } else {
670
- lines.push(`import { NextResponse } from 'next/server';`);
671
- }
672
- lines.push(``);
673
- for (let i = 0; i < handlers.length; i++) {
674
- lines.push(...emitHandler(handlers[i]));
675
- if (i < handlers.length - 1) {
676
- lines.push(``);
677
- }
678
- }
679
- return {
680
- path: filePath,
681
- code: lines.join("\n").trimEnd() + "\n"
682
- };
683
- }
684
- function compileAllToNextJSAPI(compositions, options = {}) {
685
- return compositions.map(({ composition }) => compileToNextJSAPI(composition, options));
686
- }
687
- var VALID_METHODS, BODY_METHODS, PASSTHROUGH_METHODS, NextJSAPICompiler;
688
- var init_NextJSAPICompiler = __esm({
689
- "src/compiler/NextJSAPICompiler.ts"() {
690
- init_CompilerBase();
691
- VALID_METHODS = /* @__PURE__ */ new Set([
692
- "GET",
693
- "POST",
694
- "PUT",
695
- "PATCH",
696
- "DELETE",
697
- "HEAD",
698
- "OPTIONS"
699
- ]);
700
- BODY_METHODS = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH"]);
701
- PASSTHROUGH_METHODS = /* @__PURE__ */ new Set(["HEAD", "DELETE"]);
702
- NextJSAPICompiler = class extends CompilerBase {
703
- constructor(options = {}) {
704
- super();
705
- this.options = options;
706
- }
707
- get name() {
708
- return "nextjs-api";
709
- }
710
- compile(composition, agentToken) {
711
- const comp = composition;
712
- const result = compileAllToNextJSAPI(comp);
713
- return {
714
- code: result.map((r) => r.code).join("\n\n"),
715
- files: result.map((r) => ({ path: r.routePath, content: r.code }))
716
- };
717
- }
718
- compileSingle(composition, agentToken) {
719
- const comp = composition;
720
- return compileToNextJSAPI(comp);
721
- }
722
- };
723
- }
724
- });
725
-
726
- // src/compiler/NodeServiceCompiler.ts
727
- var NodeServiceCompiler_exports = {};
728
- __export(NodeServiceCompiler_exports, {
729
- NodeServiceCompiler: () => NodeServiceCompiler
730
- });
731
- var NodeServiceCompiler;
732
- var init_NodeServiceCompiler = __esm({
733
- "src/compiler/NodeServiceCompiler.ts"() {
734
- init_CompilerBase();
735
- init_identity();
736
- init_DialectRegistry();
737
- init_constants();
738
- NodeServiceCompiler = class extends CompilerBase {
739
- constructor(options = {}) {
740
- super();
741
- this.compilerName = "NodeServiceCompiler";
742
- this.services = [];
743
- this.options = {
744
- framework: options.framework ?? "express",
745
- port: options.port ?? 3e3,
746
- apiPrefix: options.apiPrefix ?? "/api",
747
- typescript: options.typescript ?? true,
748
- nodeVersion: options.nodeVersion ?? "20",
749
- includeDocker: options.includeDocker ?? false
750
- };
751
- }
752
- getRequiredCapability() {
753
- return ANSCapabilityPath.NODE_SERVICE;
754
- }
755
- compile(composition, agentToken, outputPath) {
756
- console.log("DEBUG: Composition:", JSON.stringify(composition, null, 2));
757
- this.validateCompilerAccess(agentToken, outputPath);
758
- this.services = [];
759
- this.extractServices(composition);
760
- const output = {};
761
- output[this.ext("index")] = this.emitEntryPoint();
762
- for (const service of this.services) {
763
- output[this.ext(`routes/${this.toFileName(service.name)}`)] = this.emitRouteModule(service);
764
- }
765
- const allMiddleware = this.collectMiddleware();
766
- if (allMiddleware.length > 0) {
767
- output[this.ext("middleware/index")] = this.emitMiddlewareIndex(allMiddleware);
768
- }
769
- const allEnvVars = this.collectEnvVars();
770
- if (allEnvVars.length > 0) {
771
- output[this.ext("config/env")] = this.emitEnvConfig(allEnvVars);
772
- }
773
- const allConnectors = this.collectConnectors();
774
- if (allConnectors.length > 0) {
775
- output[this.ext("connectors/index")] = this.emitConnectorsIndex(allConnectors);
776
- }
777
- const railwayService = this.services.find((s) => s.deploy?.platform === "railway");
778
- if (railwayService?.deploy) {
779
- output["railway.json"] = this.emitRailwayConfig(railwayService.deploy);
780
- }
781
- output["package.json"] = this.emitPackageJson(composition.name);
782
- if (this.options.typescript) {
783
- output["tsconfig.json"] = this.emitTsConfig();
784
- }
785
- if (this.options.includeDocker) {
786
- output["Dockerfile"] = this.emitDockerfile();
787
- }
788
- this.validateConnectorIntegration();
789
- return output;
790
- }
791
- // ── Extraction ─────────────────────────────────────────────────────────
792
- extractServices(composition) {
793
- if (composition.domainBlocks) {
794
- for (const block of composition.domainBlocks) {
795
- if (this.isServiceBlock(block)) {
796
- this.services.push(this.parseServiceBlock(block));
797
- }
798
- }
799
- }
800
- if (composition.objects) {
801
- for (const obj of composition.objects) {
802
- if (this.hasServiceTraits(obj)) {
803
- this.services.push(this.parseServiceObject(obj));
804
- }
805
- }
806
- }
807
- if (this.services.length === 0) {
808
- this.services.push({
809
- name: composition.name || "App",
810
- routes: [],
811
- middleware: [],
812
- connectors: [],
813
- envVars: [],
814
- port: this.options.port
815
- });
816
- }
817
- }
818
- isServiceBlock(block) {
819
- return block.keyword === "service" || block.keyword === "endpoint" || block.keyword === "gateway" || block.keyword === "handler";
820
- }
821
- hasServiceTraits(obj) {
822
- if (!obj.traits) return false;
823
- const serviceTraits = ["service", "endpoint", "http", "handler", "route", "connector", "env", "deploy"];
824
- return obj.traits.some((t) => serviceTraits.includes(t.name));
825
- }
826
- parseServiceBlock(block) {
827
- const service = {
828
- name: block.name,
829
- routes: [],
830
- middleware: [],
831
- port: this.resolveNumber(block.properties["port"]) ?? this.options.port,
832
- connectors: [],
833
- envVars: []
834
- };
835
- if (block.traits) {
836
- service.middleware = this.extractMiddlewareFromTraits(block.traits);
837
- service.connectors = this.extractConnectors(block.traits, block.properties);
838
- service.envVars = this.extractEnvVars(block.traits, block.properties);
839
- service.deploy = this.extractDeploy(block.traits, block.properties);
840
- }
841
- if (block.children) {
842
- for (const child of block.children) {
843
- const route = this.extractRoute(child, block.name);
844
- if (route) service.routes.push(route);
845
- }
846
- }
847
- const inlineRoute = this.extractInlineRoute(block);
848
- if (inlineRoute) service.routes.push(inlineRoute);
849
- return service;
850
- }
851
- parseServiceObject(obj) {
852
- const service = {
853
- name: obj.name,
854
- routes: [],
855
- middleware: [],
856
- port: this.options.port,
857
- connectors: [],
858
- envVars: []
859
- };
860
- if (obj.traits) {
861
- const traitNames = obj.traits.map((t) => t.name);
862
- service.middleware = this.extractMiddlewareFromTraits(traitNames);
863
- service.connectors = this.extractConnectors(traitNames, this.objectPropsToMap(obj.properties));
864
- service.envVars = this.extractEnvVars(traitNames, this.objectPropsToMap(obj.properties));
865
- service.deploy = this.extractDeploy(traitNames, this.objectPropsToMap(obj.properties));
866
- }
867
- const route = this.extractRoute(obj, obj.name);
868
- if (route) service.routes.push(route);
869
- return service;
870
- }
871
- extractRoute(obj, serviceName) {
872
- const propMap = this.objectPropsToMap(obj.properties);
873
- const traits = (obj.traits || []).map((t) => t.name);
874
- const method = this.resolveString(propMap.get("method"))?.toUpperCase() || "GET";
875
- const path = this.resolveString(propMap.get("path")) || `/${this.toKebab(obj.name)}`;
876
- const handlerName = this.resolveString(propMap.get("handler")) || this.toCamelCase(obj.name);
877
- const hasHttpInfo = propMap.has("method") || propMap.has("path") || traits.includes("http") || traits.includes("route");
878
- if (!hasHttpInfo) return null;
879
- return {
880
- method,
881
- path,
882
- handlerName,
883
- middleware: this.extractMiddlewareFromTraits(traits),
884
- serviceName
885
- };
886
- }
887
- extractInlineRoute(block) {
888
- const props = block.properties;
889
- if (!props["method"] && !props["path"]) return null;
890
- return {
891
- method: this.resolveString(props["method"])?.toUpperCase() || "GET",
892
- path: this.resolveString(props["path"]) || `/${this.toKebab(block.name)}`,
893
- handlerName: this.resolveString(props["handler"]) || this.toCamelCase(block.name),
894
- middleware: [],
895
- serviceName: block.name
896
- };
897
- }
898
- extractMiddlewareFromTraits(traits) {
899
- const mw = [];
900
- for (const t of traits) {
901
- if (t === "middleware" || t === "auth" || t === "rate_limit" || t === "cors" || t === "validation") {
902
- mw.push(t);
903
- }
904
- }
905
- return mw;
906
- }
907
- collectMiddleware() {
908
- const set = /* @__PURE__ */ new Set();
909
- for (const service of this.services) {
910
- for (const mw of service.middleware) set.add(mw);
911
- for (const route of service.routes) {
912
- for (const mw of route.middleware) set.add(mw);
913
- }
914
- }
915
- return [...set];
916
- }
917
- // ── Connector Extraction ──────────────────────────────────────────────
918
- extractConnectors(traits, props) {
919
- const connectors = [];
920
- const propMap = props instanceof Map ? props : this.objectPropsToMapFromRecord(props);
921
- for (const t of traits) {
922
- if (t === "connector" || t === "@connector") {
923
- const name = this.resolveString(propMap.get("connector_name")) || "unknown";
924
- connectors.push({ name, config: {} });
925
- }
926
- }
927
- return connectors;
928
- }
929
- extractEnvVars(traits, props) {
930
- const envVars = [];
931
- const propMap = props instanceof Map ? props : this.objectPropsToMapFromRecord(props);
932
- for (const t of traits) {
933
- if (t === "env" || t === "@env") {
934
- const name = this.resolveString(propMap.get("env_name")) || "UNKNOWN_VAR";
935
- envVars.push({
936
- name,
937
- required: this.resolveBoolean(propMap.get("env_required")) ?? true,
938
- defaultValue: this.resolveString(propMap.get("env_default"))
939
- });
940
- }
941
- }
942
- return envVars;
943
- }
944
- extractDeploy(traits, props) {
945
- if (!traits.some((t) => t === "deploy" || t === "@deploy")) return void 0;
946
- const propMap = props instanceof Map ? props : this.objectPropsToMapFromRecord(props);
947
- return {
948
- platform: this.resolveString(propMap.get("platform")) || "railway",
949
- service: this.resolveString(propMap.get("service")),
950
- environment: this.resolveString(propMap.get("environment")),
951
- healthPath: this.resolveString(propMap.get("healthPath")) || "/health"
952
- };
953
- }
954
- objectPropsToMapFromRecord(props) {
955
- const map = /* @__PURE__ */ new Map();
956
- for (const [k, v] of Object.entries(props)) {
957
- map.set(k, v);
958
- }
959
- return map;
960
- }
961
- resolveBoolean(val) {
962
- if (val === void 0 || val === null) return void 0;
963
- if (typeof val === "boolean") return val;
964
- if (typeof val === "string") return val === "true";
965
- return void 0;
966
- }
967
- // ── Code Emission ──────────────────────────────────────────────────────
968
- emitEntryPoint() {
969
- const isExpress = this.options.framework === "express";
970
- const lines = [];
971
- lines.push(`/**`);
972
- lines.push(` * Auto-generated by HoloScript NodeServiceCompiler v0.1.0`);
973
- lines.push(` * Framework: ${this.options.framework}`);
974
- lines.push(` */`);
975
- lines.push("");
976
- if (isExpress) {
977
- lines.push(`import express from 'express';`);
978
- lines.push(`import './config/env';`);
979
- const hasConnectors = this.collectConnectors().length > 0;
980
- if (hasConnectors) {
981
- lines.push(`import { initConnectors } from './connectors';`);
982
- }
983
- for (const service of this.services) {
984
- const importName = `${this.toCamelCase(service.name)}Routes`;
985
- lines.push(`import { ${importName} } from './routes/${this.toFileName(service.name)}';`);
986
- }
987
- lines.push("");
988
- lines.push(`const app = express();`);
989
- lines.push(`app.use(express.json());`);
990
- lines.push(`app.use(express.urlencoded({ extended: true }));`);
991
- lines.push("");
992
- for (const service of this.services) {
993
- const importName = `${this.toCamelCase(service.name)}Routes`;
994
- lines.push(
995
- `app.use('${this.escapeStringValue(this.options.apiPrefix, "TypeScript")}', ${importName});`
996
- );
997
- }
998
- lines.push("");
999
- lines.push(`const PORT = process.env['PORT'] || ${this.options.port};`);
1000
- if (hasConnectors) {
1001
- lines.push(`initConnectors().then(() => {`);
1002
- lines.push(` app.listen(PORT, () => {`);
1003
- lines.push(` console.log(\`Server running on port \${PORT}\`);`);
1004
- lines.push(` });`);
1005
- lines.push(`});`);
1006
- } else {
1007
- lines.push(`app.listen(PORT, () => {`);
1008
- lines.push(` console.log(\`Server running on port \${PORT}\`);`);
1009
- lines.push(`});`);
1010
- }
1011
- lines.push("");
1012
- lines.push(`export { app };`);
1013
- } else {
1014
- lines.push(`import Fastify from 'fastify';`);
1015
- for (const service of this.services) {
1016
- const importName = `${this.toCamelCase(service.name)}Routes`;
1017
- lines.push(`import { ${importName} } from './routes/${this.toFileName(service.name)}';`);
1018
- }
1019
- lines.push("");
1020
- lines.push(`const app = Fastify({ logger: true });`);
1021
- lines.push("");
1022
- for (const service of this.services) {
1023
- const importName = `${this.toCamelCase(service.name)}Routes`;
1024
- lines.push(
1025
- `app.register(${importName}, { prefix: '${this.escapeStringValue(this.options.apiPrefix, "TypeScript")}' });`
1026
- );
1027
- }
1028
- lines.push("");
1029
- lines.push(`const PORT = Number(process.env['PORT']) || ${this.options.port};`);
1030
- lines.push(`app.listen({ port: PORT, host: '0.0.0.0' }).then((address) => {`);
1031
- lines.push(` console.log(\`Server running at \${address}\`);`);
1032
- lines.push(`});`);
1033
- lines.push("");
1034
- lines.push(`export { app };`);
1035
- }
1036
- return lines.join("\n");
1037
- }
1038
- emitRouteModule(service) {
1039
- const isExpress = this.options.framework === "express";
1040
- const lines = [];
1041
- const routerName = `${this.toCamelCase(service.name)}Routes`;
1042
- lines.push(`/**`);
1043
- lines.push(` * Routes for ${service.name}`);
1044
- lines.push(` * Auto-generated by HoloScript NodeServiceCompiler`);
1045
- lines.push(` */`);
1046
- lines.push("");
1047
- if (isExpress) {
1048
- lines.push(`import { Router } from 'express';`);
1049
- if (this.options.typescript) {
1050
- lines.push(`import type { Request, Response } from 'express';`);
1051
- }
1052
- lines.push("");
1053
- lines.push(`const router = Router();`);
1054
- lines.push("");
1055
- for (const route of service.routes) {
1056
- const methodLower = route.method.toLowerCase();
1057
- const mwArgs = route.middleware.length > 0 ? route.middleware.map((mw) => `/* ${mw} */`).join(", ") + ", " : "";
1058
- lines.push(`// ${route.method} ${route.path}`);
1059
- if (this.options.typescript) {
1060
- lines.push(
1061
- `router.${methodLower}('${this.escapeStringValue(route.path, "TypeScript")}', ${mwArgs}(req: Request, res: Response) => {`
1062
- );
1063
- } else {
1064
- lines.push(
1065
- `router.${methodLower}('${this.escapeStringValue(route.path, "TypeScript")}', ${mwArgs}(req, res) => {`
1066
- );
1067
- }
1068
- lines.push(` // TODO: Implement ${route.handlerName}`);
1069
- lines.push(
1070
- ` res.json({ message: '${this.escapeStringValue(route.handlerName, "TypeScript")} not implemented' });`
1071
- );
1072
- lines.push(`});`);
1073
- lines.push("");
1074
- }
1075
- if (service.routes.length === 0) {
1076
- lines.push(`// Default health check`);
1077
- if (this.options.typescript) {
1078
- lines.push(`router.get('/health', (_req: Request, res: Response) => {`);
1079
- } else {
1080
- lines.push(`router.get('/health', (_req, res) => {`);
1081
- }
1082
- lines.push(
1083
- ` res.json({ status: 'ok', service: '${this.escapeStringValue(service.name, "TypeScript")}' });`
1084
- );
1085
- lines.push(`});`);
1086
- lines.push("");
1087
- }
1088
- lines.push(`export { router as ${routerName} };`);
1089
- } else {
1090
- lines.push(`import type { FastifyInstance } from 'fastify';`);
1091
- lines.push("");
1092
- lines.push(`export async function ${routerName}(app: FastifyInstance) {`);
1093
- for (const route of service.routes) {
1094
- const methodLower = route.method.toLowerCase();
1095
- lines.push(` // ${route.method} ${route.path}`);
1096
- lines.push(
1097
- ` app.${methodLower}('${this.escapeStringValue(route.path, "TypeScript")}', async (request, reply) => {`
1098
- );
1099
- lines.push(` // TODO: Implement ${route.handlerName}`);
1100
- lines.push(
1101
- ` return { message: '${this.escapeStringValue(route.handlerName, "TypeScript")} not implemented' };`
1102
- );
1103
- lines.push(` });`);
1104
- lines.push("");
1105
- }
1106
- if (service.routes.length === 0) {
1107
- lines.push(` // Default health check`);
1108
- lines.push(` app.get('/health', async () => {`);
1109
- lines.push(
1110
- ` return { status: 'ok', service: '${this.escapeStringValue(service.name, "TypeScript")}' };`
1111
- );
1112
- lines.push(` });`);
1113
- lines.push("");
1114
- }
1115
- lines.push(`}`);
1116
- }
1117
- return lines.join("\n");
1118
- }
1119
- emitMiddlewareIndex(middleware) {
1120
- const lines = [];
1121
- lines.push(`/**`);
1122
- lines.push(` * Middleware stubs`);
1123
- lines.push(` * Auto-generated by HoloScript NodeServiceCompiler`);
1124
- lines.push(` */`);
1125
- lines.push("");
1126
- if (this.options.framework === "express") {
1127
- lines.push(`import type { Request, Response, NextFunction } from 'express';`);
1128
- lines.push("");
1129
- for (const mw of middleware) {
1130
- const fnName = this.toCamelCase(mw) + "Middleware";
1131
- lines.push(`export function ${fnName}(req: Request, _res: Response, next: NextFunction) {`);
1132
- lines.push(` // TODO: Implement ${mw} middleware`);
1133
- lines.push(` next();`);
1134
- lines.push(`}`);
1135
- lines.push("");
1136
- }
1137
- } else {
1138
- lines.push(
1139
- `import type { FastifyRequest, FastifyReply, HookHandlerDoneFunction } from 'fastify';`
1140
- );
1141
- lines.push("");
1142
- for (const mw of middleware) {
1143
- const fnName = this.toCamelCase(mw) + "Middleware";
1144
- lines.push(
1145
- `export function ${fnName}(request: FastifyRequest, _reply: FastifyReply, done: HookHandlerDoneFunction) {`
1146
- );
1147
- lines.push(` // TODO: Implement ${mw} middleware`);
1148
- lines.push(` done();`);
1149
- lines.push(`}`);
1150
- lines.push("");
1151
- }
1152
- }
1153
- return lines.join("\n");
1154
- }
1155
- emitPackageJson(projectName) {
1156
- const name = this.toKebab(projectName || "holoscript-service");
1157
- const isExpress = this.options.framework === "express";
1158
- const dependencies = isExpress ? { express: "^4.21.0", dotenv: "^16.4.0" } : { fastify: "^5.0.0", dotenv: "^16.4.0" };
1159
- const connectors = this.collectConnectors();
1160
- for (const conn of connectors) {
1161
- const pkg2 = CONNECTOR_PACKAGES[conn.name];
1162
- if (pkg2) {
1163
- dependencies[pkg2] = "latest";
1164
- }
1165
- }
1166
- const pkg = {
1167
- name,
1168
- version: "0.1.0",
1169
- description: `Generated by HoloScript NodeServiceCompiler`,
1170
- main: this.options.typescript ? "dist/index.js" : "index.js",
1171
- scripts: {
1172
- ...this.options.typescript ? {
1173
- build: "tsc",
1174
- start: "node dist/index.js",
1175
- dev: "tsx watch index.ts"
1176
- } : {
1177
- start: "node index.js",
1178
- dev: "node --watch index.js"
1179
- }
1180
- },
1181
- dependencies,
1182
- ...this.options.typescript && {
1183
- devDependencies: {
1184
- typescript: "^5.5.0",
1185
- tsx: "^4.0.0",
1186
- ...isExpress ? { "@types/express": "^4.17.21", "@types/node": "^20.0.0" } : { "@types/node": "^20.0.0" }
1187
- }
1188
- }
1189
- };
1190
- return JSON.stringify(pkg, null, 2);
1191
- }
1192
- emitTsConfig() {
1193
- const config = {
1194
- compilerOptions: {
1195
- target: "ES2022",
1196
- module: "NodeNext",
1197
- moduleResolution: "NodeNext",
1198
- outDir: "./dist",
1199
- rootDir: "./",
1200
- strict: true,
1201
- esModuleInterop: true,
1202
- skipLibCheck: true,
1203
- declaration: true
1204
- },
1205
- include: ["./**/*.ts"],
1206
- exclude: ["node_modules", "dist"]
1207
- };
1208
- return JSON.stringify(config, null, 2);
1209
- }
1210
- emitDockerfile() {
1211
- const nodeVer = this.options.nodeVersion;
1212
- return [
1213
- `FROM node:${nodeVer}-alpine AS builder`,
1214
- `WORKDIR /app`,
1215
- `COPY package*.json ./`,
1216
- `RUN npm ci`,
1217
- `COPY . .`,
1218
- ...this.options.typescript ? [`RUN npm run build`] : [],
1219
- ``,
1220
- `FROM node:${nodeVer}-alpine`,
1221
- `WORKDIR /app`,
1222
- `COPY --from=builder /app/package*.json ./`,
1223
- `RUN npm ci --omit=dev`,
1224
- ...this.options.typescript ? [`COPY --from=builder /app/dist ./dist`] : [`COPY --from=builder /app/*.js ./`],
1225
- `EXPOSE ${this.options.port}`,
1226
- `CMD ["npm", "start"]`,
1227
- ``
1228
- ].join("\n");
1229
- }
1230
- // ── Utilities ──────────────────────────────────────────────────────────
1231
- collectEnvVars() {
1232
- const map = /* @__PURE__ */ new Map();
1233
- for (const service of this.services) {
1234
- for (const env of service.envVars) {
1235
- map.set(env.name, env);
1236
- }
1237
- for (const conn of service.connectors) {
1238
- const requirements = CONNECTOR_ENV_REQUIREMENTS[conn.name] || [];
1239
- for (const req of requirements) {
1240
- if (!map.has(req)) {
1241
- map.set(req, { name: req, required: true });
1242
- }
1243
- }
1244
- }
1245
- }
1246
- return Array.from(map.values());
1247
- }
1248
- collectConnectors() {
1249
- const map = /* @__PURE__ */ new Map();
1250
- for (const service of this.services) {
1251
- for (const conn of service.connectors) {
1252
- map.set(conn.name, conn);
1253
- }
1254
- }
1255
- return Array.from(map.values());
1256
- }
1257
- // ── Emitters ──────────────────────────────────────────────────────────
1258
- emitEnvConfig(envVars) {
1259
- const lines = [];
1260
- lines.push(`/**`);
1261
- lines.push(` * Environment Configuration`);
1262
- lines.push(` * Auto-generated by HoloScript NodeServiceCompiler`);
1263
- lines.push(` */`);
1264
- lines.push(``);
1265
- lines.push(`import dotenv from 'dotenv';`);
1266
- lines.push(`dotenv.config();`);
1267
- lines.push(``);
1268
- lines.push(`export const env = {`);
1269
- for (const ev of envVars) {
1270
- const fallback = ev.defaultValue ? ` || '${ev.defaultValue}'` : "";
1271
- lines.push(` ${ev.name}: process.env['${ev.name}']${fallback},`);
1272
- }
1273
- lines.push(`};`);
1274
- lines.push(``);
1275
- lines.push(`// Validation`);
1276
- lines.push(`const missing: string[] = [];`);
1277
- for (const ev of envVars) {
1278
- if (ev.required) {
1279
- lines.push(`if (!env.${ev.name}) missing.push('${ev.name}');`);
1280
- }
1281
- }
1282
- lines.push(``);
1283
- lines.push(`if (missing.length > 0) {`);
1284
- lines.push(` console.error('Missing required environment variables:', missing.join(', '));`);
1285
- lines.push(` process.exit(1);`);
1286
- lines.push(`}`);
1287
- return lines.join("\n");
1288
- }
1289
- emitConnectorsIndex(connectors) {
1290
- const lines = [];
1291
- lines.push(`/**`);
1292
- lines.push(` * Connector Registry`);
1293
- lines.push(` * Auto-generated by HoloScript NodeServiceCompiler`);
1294
- lines.push(` */`);
1295
- lines.push(``);
1296
- for (const conn of connectors) {
1297
- const pkg = CONNECTOR_PACKAGES[conn.name];
1298
- if (pkg) {
1299
- lines.push(`import { ${this.toClassName(conn.name)}Connector } from '${pkg}';`);
1300
- }
1301
- }
1302
- lines.push(``);
1303
- for (const conn of connectors) {
1304
- const className = this.toClassName(conn.name);
1305
- lines.push(`export const ${conn.name} = new ${className}Connector();`);
1306
- }
1307
- lines.push(``);
1308
- lines.push(`export async function initConnectors(): Promise<void> {`);
1309
- lines.push(` await Promise.all([`);
1310
- for (const conn of connectors) {
1311
- lines.push(` ${conn.name}.connect(),`);
1312
- }
1313
- lines.push(` ]);`);
1314
- for (const conn of connectors) {
1315
- lines.push(` console.log('[connectors] ${conn.name}: connected');`);
1316
- }
1317
- lines.push(`}`);
1318
- lines.push(``);
1319
- lines.push(`export async function shutdownConnectors(): Promise<void> {`);
1320
- lines.push(` await Promise.all([`);
1321
- for (const conn of connectors) {
1322
- lines.push(` ${conn.name}.disconnect(),`);
1323
- }
1324
- lines.push(` ]);`);
1325
- lines.push(`}`);
1326
- return lines.join("\n");
1327
- }
1328
- emitRailwayConfig(deploy) {
1329
- const config = {
1330
- $schema: "https://railway.app/railway.schema.json",
1331
- build: {
1332
- builder: "DOCKERFILE",
1333
- dockerfilePath: "Dockerfile"
1334
- },
1335
- deploy: {
1336
- numReplicas: 1,
1337
- sleepApplication: false,
1338
- restartPolicyType: "ON_FAILURE",
1339
- healthcheckPath: deploy.healthPath || "/health"
1340
- }
1341
- };
1342
- return JSON.stringify(config, null, 2);
1343
- }
1344
- toClassName(name) {
1345
- return name.charAt(0).toUpperCase() + this.toCamelCase(name).slice(1);
1346
- }
1347
- /** Convert HoloObjectProperty[] to a Map for key-based lookup */
1348
- objectPropsToMap(props) {
1349
- const map = /* @__PURE__ */ new Map();
1350
- if (!props) return map;
1351
- for (const prop of props) {
1352
- map.set(prop.key, prop.value);
1353
- }
1354
- return map;
1355
- }
1356
- ext(name) {
1357
- return this.options.typescript ? `${name}.ts` : `${name}.js`;
1358
- }
1359
- toFileName(name) {
1360
- return name.replace(/[^a-zA-Z0-9]/g, "-").replace(/-+/g, "-");
1361
- }
1362
- toKebab(name) {
1363
- return name.replace(/([a-z])([A-Z])/g, "$1-$2").replace(/[^a-zA-Z0-9]/g, "-").replace(/-+/g, "-").toLowerCase();
1364
- }
1365
- toCamelCase(name) {
1366
- const parts = name.replace(/[^a-zA-Z0-9]/g, " ").split(/\s+/).filter(Boolean);
1367
- if (parts.length === 0) return "unnamed";
1368
- return parts[0].toLowerCase() + parts.slice(1).map((p) => p.charAt(0).toUpperCase() + p.slice(1).toLowerCase()).join("");
1369
- }
1370
- resolveString(val) {
1371
- if (val === void 0 || val === null) return void 0;
1372
- if (typeof val === "string") return val;
1373
- if (typeof val === "object" && "value" in val) return String(val.value);
1374
- return String(val);
1375
- }
1376
- resolveNumber(val) {
1377
- if (val === void 0 || val === null) return void 0;
1378
- if (typeof val === "number") return val;
1379
- if (typeof val === "string") {
1380
- const n = Number(val);
1381
- return isNaN(n) ? void 0 : n;
1382
- }
1383
- if (typeof val === "object" && "value" in val) {
1384
- const n = Number(val.value);
1385
- return isNaN(n) ? void 0 : n;
1386
- }
1387
- return void 0;
1388
- }
1389
- validateConnectorIntegration() {
1390
- const connectors = this.collectConnectors();
1391
- const envVars = this.collectEnvVars();
1392
- const envMap = new Map(envVars.map((ev) => [ev.name, ev]));
1393
- for (const conn of connectors) {
1394
- if (!KNOWN_CONNECTORS.includes(conn.name)) {
1395
- console.warn(`[NodeServiceCompiler] Warning: Unknown connector '${conn.name}'. Package dependency will not be added.`);
1396
- } else {
1397
- const requirements = CONNECTOR_ENV_REQUIREMENTS[conn.name] || [];
1398
- for (const req of requirements) {
1399
- if (!envMap.has(req)) {
1400
- throw new Error(`Connector '${conn.name}' requires environment variable '${req}'`);
1401
- }
1402
- }
1403
- }
1404
- }
1405
- const deployable = this.services.find((s) => s.deploy);
1406
- if (deployable?.deploy) {
1407
- if (deployable.deploy.platform !== "railway") {
1408
- console.warn(
1409
- `[NodeServiceCompiler] Warning: Platform '${deployable.deploy.platform}' is not explicitly supported for config generation yet.`
1410
- );
1411
- }
1412
- }
1413
- }
1414
- };
1415
- DialectRegistry.register({
1416
- name: "node-service",
1417
- domain: "service",
1418
- description: "Compiles @service traits to Express/Fastify Node.js applications",
1419
- supportedTraits: [
1420
- "service",
1421
- "endpoint",
1422
- "route",
1423
- "handler",
1424
- "middleware",
1425
- "http",
1426
- "gateway",
1427
- "proxy",
1428
- "load_balancer",
1429
- "auth",
1430
- "cors",
1431
- "rate_limit",
1432
- "validation",
1433
- "connector",
1434
- "env",
1435
- "deploy",
1436
- "on_connector_event"
1437
- ],
1438
- riskTier: "standard",
1439
- factory: (options) => new NodeServiceCompiler(options),
1440
- outputExtensions: [".ts", ".js", ".json"],
1441
- experimental: true
1442
- });
1443
- }
1444
- });
1445
-
1446
- // src/compiler/registerBuiltinDialects.ts
1447
- var registerBuiltinDialects_exports = {};
1448
- __export(registerBuiltinDialects_exports, {
1449
- registerBuiltinDialects: () => registerBuiltinDialects
1450
- });
1451
- function registerBuiltinDialects() {
1452
- if (_registered) return;
1453
- _registered = true;
1454
- const descriptors = [
1455
- // ── Game Engines ──────────────────────────────────────────────────────
1456
- {
1457
- name: "unity",
1458
- domain: "gamedev",
1459
- description: "Compiles to Unity C# MonoBehaviours",
1460
- supportedTraits: [
1461
- "physics",
1462
- "collidable",
1463
- "grabbable",
1464
- "throwable",
1465
- "audio",
1466
- "spatial_audio",
1467
- "animation",
1468
- "particles",
1469
- "material",
1470
- "ui",
1471
- "networked",
1472
- "behavior_tree",
1473
- "navmesh",
1474
- "lod"
1475
- ],
1476
- riskTier: "standard",
1477
- factory: (opts) => {
1478
- const { UnityCompiler: UnityCompiler2 } = (init_UnityCompiler(), __toCommonJS(UnityCompiler_exports));
1479
- return new UnityCompiler2(opts);
1480
- },
1481
- outputExtensions: [".cs"]
1482
- },
1483
- {
1484
- name: "unreal",
1485
- domain: "gamedev",
1486
- description: "Compiles to Unreal Engine C++ actors",
1487
- supportedTraits: [
1488
- "physics",
1489
- "collidable",
1490
- "grabbable",
1491
- "audio",
1492
- "animation",
1493
- "particles",
1494
- "material",
1495
- "niagara",
1496
- "landscape",
1497
- "behavior_tree",
1498
- "navmesh",
1499
- "lod"
1500
- ],
1501
- riskTier: "standard",
1502
- factory: (opts) => {
1503
- const { UnrealCompiler } = (init_UnrealCompiler(), __toCommonJS(UnrealCompiler_exports));
1504
- return new UnrealCompiler(opts);
1505
- },
1506
- outputExtensions: [".cpp", ".h"]
1507
- },
1508
- {
1509
- name: "godot",
1510
- domain: "gamedev",
1511
- description: "Compiles to Godot GDScript nodes",
1512
- supportedTraits: [
1513
- "physics",
1514
- "collidable",
1515
- "grabbable",
1516
- "audio",
1517
- "animation",
1518
- "particles",
1519
- "material",
1520
- "behavior_tree",
1521
- "navmesh"
1522
- ],
1523
- riskTier: "standard",
1524
- factory: (opts) => {
1525
- const { GodotCompiler: GodotCompiler2 } = (init_GodotCompiler(), __toCommonJS(GodotCompiler_exports));
1526
- return new GodotCompiler2(opts);
1527
- },
1528
- outputExtensions: [".gd", ".tscn"]
1529
- },
1530
- // ── Web 3D ────────────────────────────────────────────────────────────
1531
- {
1532
- name: "r3f",
1533
- domain: "web3d",
1534
- description: "Compiles to React Three Fiber JSX components",
1535
- supportedTraits: [
1536
- "physics",
1537
- "collidable",
1538
- "grabbable",
1539
- "audio",
1540
- "spatial_audio",
1541
- "animation",
1542
- "particles",
1543
- "material",
1544
- "ui",
1545
- "behavior_tree",
1546
- "lod",
1547
- "vr_only",
1548
- "ar_only"
1549
- ],
1550
- riskTier: "standard",
1551
- factory: (opts) => {
1552
- const { R3FCompiler: R3FCompiler2 } = (init_R3FCompiler(), __toCommonJS(R3FCompiler_exports));
1553
- return new R3FCompiler2(opts);
1554
- },
1555
- outputExtensions: [".tsx", ".jsx"]
1556
- },
1557
- {
1558
- name: "babylon",
1559
- domain: "web3d",
1560
- description: "Compiles to Babylon.js scene code",
1561
- supportedTraits: [
1562
- "physics",
1563
- "collidable",
1564
- "audio",
1565
- "animation",
1566
- "particles",
1567
- "material",
1568
- "behavior_tree"
1569
- ],
1570
- riskTier: "standard",
1571
- factory: (opts) => {
1572
- const { BabylonCompiler: BabylonCompiler2 } = (init_BabylonCompiler(), __toCommonJS(BabylonCompiler_exports));
1573
- return new BabylonCompiler2(opts);
1574
- },
1575
- outputExtensions: [".ts", ".js"]
1576
- },
1577
- {
1578
- name: "playcanvas",
1579
- domain: "web3d",
1580
- description: "Compiles to PlayCanvas engine scripts",
1581
- supportedTraits: ["physics", "collidable", "audio", "animation", "material"],
1582
- riskTier: "standard",
1583
- factory: (opts) => {
1584
- const { PlayCanvasCompiler: PlayCanvasCompiler2 } = (init_PlayCanvasCompiler(), __toCommonJS(PlayCanvasCompiler_exports));
1585
- return new PlayCanvasCompiler2(opts);
1586
- },
1587
- outputExtensions: [".js"]
1588
- },
1589
- // ── VR/XR ─────────────────────────────────────────────────────────────
1590
- {
1591
- name: "openxr",
1592
- domain: "xr",
1593
- description: "Compiles to OpenXR C++ application layer",
1594
- supportedTraits: [
1595
- "physics",
1596
- "hand_tracking",
1597
- "spatial_anchor",
1598
- "input",
1599
- "collidable",
1600
- "grabbable"
1601
- ],
1602
- riskTier: "standard",
1603
- factory: (opts) => {
1604
- const { OpenXRCompiler: OpenXRCompiler2 } = (init_OpenXRCompiler(), __toCommonJS(OpenXRCompiler_exports));
1605
- return new OpenXRCompiler2(opts);
1606
- },
1607
- outputExtensions: [".cpp", ".h"]
1608
- },
1609
- {
1610
- name: "vrchat",
1611
- domain: "social-vr",
1612
- description: "Compiles to VRChat UdonSharp scripts",
1613
- supportedTraits: [
1614
- "physics",
1615
- "collidable",
1616
- "grabbable",
1617
- "audio",
1618
- "animation",
1619
- "networked",
1620
- "ui",
1621
- "interaction"
1622
- ],
1623
- riskTier: "standard",
1624
- factory: (opts) => {
1625
- const { VRChatCompiler: VRChatCompiler2 } = (init_VRChatCompiler(), __toCommonJS(VRChatCompiler_exports));
1626
- return new VRChatCompiler2(opts);
1627
- },
1628
- outputExtensions: [".cs"]
1629
- },
1630
- {
1631
- name: "visionos",
1632
- domain: "xr",
1633
- description: "Compiles to visionOS RealityKit Swift",
1634
- supportedTraits: [
1635
- "physics",
1636
- "hand_tracking",
1637
- "spatial_anchor",
1638
- "animation",
1639
- "material",
1640
- "collidable"
1641
- ],
1642
- riskTier: "standard",
1643
- factory: (opts) => {
1644
- const { VisionOSCompiler: VisionOSCompiler2 } = (init_VisionOSCompiler(), __toCommonJS(VisionOSCompiler_exports));
1645
- return new VisionOSCompiler2(opts);
1646
- },
1647
- outputExtensions: [".swift"]
1648
- },
1649
- {
1650
- name: "android-xr",
1651
- domain: "xr",
1652
- description: "Compiles to Android XR OpenXR Kotlin",
1653
- supportedTraits: ["physics", "hand_tracking", "spatial_anchor", "input", "collidable"],
1654
- riskTier: "standard",
1655
- factory: (opts) => {
1656
- const { AndroidXRCompiler: AndroidXRCompiler2 } = (init_AndroidXRCompiler(), __toCommonJS(AndroidXRCompiler_exports));
1657
- return new AndroidXRCompiler2(opts);
1658
- },
1659
- outputExtensions: [".kt"]
1660
- },
1661
- // ── Mobile ────────────────────────────────────────────────────────────
1662
- {
1663
- name: "ios",
1664
- domain: "mobile",
1665
- description: "Compiles to iOS ARKit Swift",
1666
- supportedTraits: ["physics", "ar_anchor", "animation", "material", "collidable"],
1667
- riskTier: "standard",
1668
- factory: (opts) => {
1669
- const { IOSCompiler: IOSCompiler2 } = (init_IOSCompiler(), __toCommonJS(IOSCompiler_exports));
1670
- return new IOSCompiler2(opts);
1671
- },
1672
- outputExtensions: [".swift"]
1673
- },
1674
- {
1675
- name: "android",
1676
- domain: "mobile",
1677
- description: "Compiles to Android ARCore Kotlin",
1678
- supportedTraits: ["physics", "ar_anchor", "animation", "material", "collidable"],
1679
- riskTier: "standard",
1680
- factory: (opts) => {
1681
- const { AndroidCompiler: AndroidCompiler2 } = (init_AndroidCompiler(), __toCommonJS(AndroidCompiler_exports));
1682
- return new AndroidCompiler2(opts);
1683
- },
1684
- outputExtensions: [".kt"]
1685
- },
1686
- {
1687
- name: "ar",
1688
- domain: "mobile",
1689
- description: "Compiles to generic AR platform code",
1690
- supportedTraits: ["physics", "ar_anchor", "spatial_anchor", "collidable", "material"],
1691
- riskTier: "standard",
1692
- factory: (opts) => {
1693
- const { ARCompiler: ARCompiler2 } = (init_ARCompiler(), __toCommonJS(ARCompiler_exports));
1694
- return new ARCompiler2(opts);
1695
- },
1696
- outputExtensions: [".ts"]
1697
- },
1698
- // ── Low-level ─────────────────────────────────────────────────────────
1699
- {
1700
- name: "wasm",
1701
- domain: "runtime",
1702
- description: "Compiles to WebAssembly modules",
1703
- supportedTraits: ["physics", "animation", "audio"],
1704
- riskTier: "high",
1705
- factory: (opts) => {
1706
- const { WASMCompiler: WASMCompiler2 } = (init_WASMCompiler(), __toCommonJS(WASMCompiler_exports));
1707
- return new WASMCompiler2(opts);
1708
- },
1709
- outputExtensions: [".wasm", ".js"]
1710
- },
1711
- {
1712
- name: "webgpu",
1713
- domain: "shader",
1714
- description: "Compiles to WebGPU compute shaders (WGSL)",
1715
- supportedTraits: ["physics", "particles", "fluid", "material", "compute"],
1716
- riskTier: "standard",
1717
- factory: (opts) => {
1718
- const { WebGPUCompiler: WebGPUCompiler2 } = (init_WebGPUCompiler(), __toCommonJS(WebGPUCompiler_exports));
1719
- return new WebGPUCompiler2(opts);
1720
- },
1721
- outputExtensions: [".wgsl", ".ts"]
1722
- },
1723
- // ── Robotics & IoT ───────────────────────────────────────────────────
1724
- {
1725
- name: "urdf",
1726
- domain: "robotics",
1727
- description: "Compiles to URDF robot descriptions",
1728
- supportedTraits: ["joint", "actuator", "sensor", "collider", "end_effector"],
1729
- riskTier: "standard",
1730
- factory: (opts) => {
1731
- const { URDFCompiler: URDFCompiler2 } = (init_URDFCompiler(), __toCommonJS(URDFCompiler_exports));
1732
- return new URDFCompiler2(opts);
1733
- },
1734
- outputExtensions: [".urdf"]
1735
- },
1736
- {
1737
- name: "sdf",
1738
- domain: "robotics",
1739
- description: "Compiles to SDF simulation descriptions (Gazebo)",
1740
- supportedTraits: ["joint", "actuator", "sensor", "collider", "physics", "environment"],
1741
- riskTier: "standard",
1742
- factory: (opts) => {
1743
- const { SDFCompiler: SDFCompiler2 } = (init_SDFCompiler(), __toCommonJS(SDFCompiler_exports));
1744
- return new SDFCompiler2(opts);
1745
- },
1746
- outputExtensions: [".sdf"]
1747
- },
1748
- {
1749
- name: "dtdl",
1750
- domain: "iot",
1751
- description: "Compiles to DTDL digital twin definitions",
1752
- supportedTraits: ["sensor", "telemetry", "property", "command", "relationship"],
1753
- riskTier: "standard",
1754
- factory: (opts) => {
1755
- const { DTDLCompiler: DTDLCompiler2 } = (init_DTDLCompiler(), __toCommonJS(DTDLCompiler_exports));
1756
- return new DTDLCompiler2(opts);
1757
- },
1758
- outputExtensions: [".json"]
1759
- },
1760
- // ── Specialized ───────────────────────────────────────────────────────
1761
- {
1762
- name: "state",
1763
- domain: "meta",
1764
- description: "Extracts reactive state descriptors from compositions",
1765
- supportedTraits: ["state", "bind", "reactive"],
1766
- riskTier: "standard",
1767
- factory: (opts) => {
1768
- const { StateCompiler: StateCompiler2 } = (init_StateCompiler(), __toCommonJS(StateCompiler_exports));
1769
- return new StateCompiler2(opts);
1770
- },
1771
- outputExtensions: [".json"]
1772
- },
1773
- {
1774
- name: "a2a-agent-card",
1775
- domain: "ai",
1776
- description: "Generates A2A Agent Card from composition metadata",
1777
- supportedTraits: ["agent", "skill", "capability"],
1778
- riskTier: "standard",
1779
- factory: (opts) => {
1780
- const { A2AAgentCardCompiler } = (init_A2AAgentCardCompiler(), __toCommonJS(A2AAgentCardCompiler_exports));
1781
- return new A2AAgentCardCompiler(opts);
1782
- },
1783
- outputExtensions: [".json"]
1784
- },
1785
- {
1786
- name: "nir",
1787
- domain: "neuromorphic",
1788
- description: "Compiles to Neuromorphic Intermediate Representation",
1789
- supportedTraits: ["snn", "neuron", "synapse", "spike_train"],
1790
- riskTier: "high",
1791
- factory: (opts) => {
1792
- const { NIRCompiler } = (init_NIRCompiler(), __toCommonJS(NIRCompiler_exports));
1793
- return new NIRCompiler(opts);
1794
- },
1795
- outputExtensions: [".json"]
1796
- },
1797
- {
1798
- name: "vrr",
1799
- domain: "xr",
1800
- description: "Compiles with Variable Rate Rendering optimizations",
1801
- supportedTraits: ["physics", "material", "lod", "rendering"],
1802
- riskTier: "standard",
1803
- factory: (opts) => {
1804
- const { VRRCompiler } = (init_VRRCompiler(), __toCommonJS(VRRCompiler_exports));
1805
- return new VRRCompiler(opts);
1806
- },
1807
- outputExtensions: [".ts"]
1808
- },
1809
- {
1810
- name: "native-2d",
1811
- domain: "web3d",
1812
- description: "Compiles to native 2D HTML/CSS/Canvas applications",
1813
- supportedTraits: ["layout", "style", "animation", "interaction"],
1814
- riskTier: "standard",
1815
- factory: (opts) => {
1816
- const { Native2DCompiler: Native2DCompiler2 } = (init_Native2DCompiler(), __toCommonJS(Native2DCompiler_exports));
1817
- return new Native2DCompiler2(opts);
1818
- },
1819
- outputExtensions: [".tsx", ".html"]
1820
- },
1821
- // ── Next.js API Routes ────────────────────────────────────────────────
1822
- {
1823
- name: "nextjs-api",
1824
- domain: "web",
1825
- description: "Compiles @http traits to Next.js App Router API route handlers (route.ts)",
1826
- supportedTraits: ["http", "handler", "middleware", "auth", "rate_limit", "cors"],
1827
- riskTier: "standard",
1828
- factory: () => {
1829
- const { compileToNextJSAPI: compileToNextJSAPI2 } = (init_NextJSAPICompiler(), __toCommonJS(NextJSAPICompiler_exports));
1830
- return {
1831
- compile: (composition, _token) => compileToNextJSAPI2(composition)
1832
- };
1833
- },
1834
- outputExtensions: [".ts"],
1835
- experimental: true
1836
- },
1837
- // ── v6 Universal Service ──────────────────────────────────────────────
1838
- {
1839
- name: "node-service",
1840
- domain: "service",
1841
- description: "Compiles @service traits to Express/Fastify applications",
1842
- supportedTraits: [
1843
- "service",
1844
- "endpoint",
1845
- "route",
1846
- "handler",
1847
- "middleware",
1848
- "cors_policy",
1849
- "rate_limiter",
1850
- "health_endpoint"
1851
- ],
1852
- riskTier: "standard",
1853
- factory: (opts) => {
1854
- const { NodeServiceCompiler: NodeServiceCompiler2 } = (init_NodeServiceCompiler(), __toCommonJS(NodeServiceCompiler_exports));
1855
- return new NodeServiceCompiler2(opts);
1856
- },
1857
- outputExtensions: [".ts", ".js"],
1858
- experimental: true
1859
- }
1860
- ];
1861
- for (const desc of descriptors) {
1862
- if (!DialectRegistry.has(desc.name)) {
1863
- DialectRegistry.register(desc);
1864
- }
1865
- }
1866
- }
1867
- var _registered;
1868
- var init_registerBuiltinDialects = __esm({
1869
- "src/compiler/registerBuiltinDialects.ts"() {
1870
- init_DialectRegistry();
1871
- _registered = false;
1872
- }
1873
- });
1874
-
1875
- // src/compiler/DialectRegistry.ts
1876
- function ensureDialectsBooted() {
1877
- if (_autoBooted) return;
1878
- _autoBooted = true;
1879
- try {
1880
- const { registerBuiltinDialects: registerBuiltinDialects2 } = (init_registerBuiltinDialects(), __toCommonJS(registerBuiltinDialects_exports));
1881
- registerBuiltinDialects2();
1882
- } catch {
1883
- }
1884
- }
1885
- var DialectRegistryImpl, DialectRegistry, _autoBooted;
1886
- var init_DialectRegistry = __esm({
1887
- "src/compiler/DialectRegistry.ts"() {
1888
- DialectRegistryImpl = class {
1889
- constructor() {
1890
- this.dialects = /* @__PURE__ */ new Map();
1891
- }
1892
- /**
1893
- * Register a new compiler dialect.
1894
- * @throws Error if a dialect with the same name already exists
1895
- */
1896
- register(descriptor) {
1897
- if (this.dialects.has(descriptor.name)) {
1898
- throw new Error(
1899
- `Dialect "${descriptor.name}" is already registered. Use DialectRegistry.override() to replace an existing dialect.`
1900
- );
1901
- }
1902
- if (!descriptor.ansPath) {
1903
- descriptor.ansPath = `/compile/${descriptor.domain}/${descriptor.name}`;
1904
- }
1905
- this.dialects.set(descriptor.name, descriptor);
1906
- }
1907
- /**
1908
- * Override an existing dialect registration.
1909
- */
1910
- override(descriptor) {
1911
- if (!descriptor.ansPath) {
1912
- descriptor.ansPath = `/compile/${descriptor.domain}/${descriptor.name}`;
1913
- }
1914
- this.dialects.set(descriptor.name, descriptor);
1915
- }
1916
- /**
1917
- * Unregister a dialect.
1918
- */
1919
- unregister(name) {
1920
- return this.dialects.delete(name);
1921
- }
1922
- /**
1923
- * Check if a dialect is registered.
1924
- */
1925
- has(name) {
1926
- return this.dialects.has(name);
1927
- }
1928
- /**
1929
- * Get dialect info (without factory, safe for discovery).
1930
- */
1931
- get(name) {
1932
- const desc = this.dialects.get(name);
1933
- if (!desc) return void 0;
1934
- return {
1935
- name: desc.name,
1936
- domain: desc.domain,
1937
- description: desc.description,
1938
- supportedTraits: desc.supportedTraits,
1939
- riskTier: desc.riskTier,
1940
- ansPath: desc.ansPath || `/compile/${desc.domain}/${desc.name}`,
1941
- outputExtensions: desc.outputExtensions || [],
1942
- experimental: desc.experimental ?? false
1943
- };
1944
- }
1945
- /**
1946
- * Create a compiler instance from a registered dialect.
1947
- * @throws Error if dialect not found
1948
- */
1949
- create(name, options) {
1950
- const desc = this.dialects.get(name);
1951
- if (!desc) {
1952
- const available = [...this.dialects.keys()].join(", ");
1953
- throw new Error(`Unknown dialect "${name}". Available: ${available}`);
1954
- }
1955
- return desc.factory(options);
1956
- }
1957
- /**
1958
- * List all registered dialects.
1959
- */
1960
- list() {
1961
- return [...this.dialects.values()].map((desc) => ({
1962
- name: desc.name,
1963
- domain: desc.domain,
1964
- description: desc.description,
1965
- supportedTraits: desc.supportedTraits,
1966
- riskTier: desc.riskTier,
1967
- ansPath: desc.ansPath || `/compile/${desc.domain}/${desc.name}`,
1968
- outputExtensions: desc.outputExtensions || [],
1969
- experimental: desc.experimental ?? false
1970
- }));
1971
- }
1972
- /**
1973
- * List dialects filtered by domain.
1974
- */
1975
- listByDomain(domain) {
1976
- return this.list().filter((d) => d.domain === domain);
1977
- }
1978
- /**
1979
- * Find dialects that support a specific trait.
1980
- */
1981
- findByTrait(traitName) {
1982
- return this.list().filter((d) => d.supportedTraits.includes(traitName));
1983
- }
1984
- /**
1985
- * Get all registered dialect names.
1986
- */
1987
- names() {
1988
- return [...this.dialects.keys()];
1989
- }
1990
- /**
1991
- * Get count of registered dialects.
1992
- */
1993
- get size() {
1994
- return this.dialects.size;
1995
- }
1996
- /**
1997
- * Execute a progressive lowering pipeline for a dialect.
1998
- * Runs all registered lowering passes in priority order.
1999
- */
2000
- executeLoweringPipeline(dialectName, composition, options = {}) {
2001
- const desc = this.dialects.get(dialectName);
2002
- if (!desc) {
2003
- throw new Error(`Unknown dialect "${dialectName}"`);
2004
- }
2005
- const passes = [...desc.loweringPasses || []].sort((a, b) => a.priority - b.priority);
2006
- if (passes.length === 0) {
2007
- throw new Error(
2008
- `Dialect "${dialectName}" has no lowering passes. Use create() for direct compilation.`
2009
- );
2010
- }
2011
- const context = {
2012
- target: dialectName,
2013
- options,
2014
- previousPasses: /* @__PURE__ */ new Map(),
2015
- diagnostics: []
2016
- };
2017
- let lastResult = { output: "" };
2018
- for (const pass of passes) {
2019
- lastResult = pass.lower(composition, context);
2020
- context.previousPasses.set(pass.name, lastResult);
2021
- if (lastResult.diagnostics) {
2022
- context.diagnostics.push(...lastResult.diagnostics);
2023
- }
2024
- const hasError = lastResult.diagnostics?.some((d) => d.level === "error");
2025
- if (hasError) break;
2026
- }
2027
- lastResult.diagnostics = context.diagnostics;
2028
- return lastResult;
2029
- }
2030
- };
2031
- DialectRegistry = new DialectRegistryImpl();
2032
- _autoBooted = false;
2033
- }
2034
- });
2035
-
2036
- // src/compiler/index.ts
2037
- init_CompilerBase();
2038
- init_CompilerDocumentationGenerator();
2039
- init_R3FCompiler();
2040
- init_UnityCompiler();
2041
- init_GodotCompiler();
2042
- init_BabylonCompiler();
2043
- init_PlayCanvasCompiler();
2044
- init_ARCompiler();
2045
- init_OpenXRCompiler();
2046
- init_VRChatCompiler();
2047
- init_VisionOSCompiler();
2048
- init_AndroidCompiler();
2049
- init_AndroidXRCompiler();
2050
- init_IOSCompiler();
2051
- init_WASMCompiler();
2052
- init_WebGPUCompiler();
2053
- init_SDFCompiler();
2054
- init_DTDLCompiler();
2055
- init_URDFCompiler();
2056
- init_StateCompiler();
2057
-
2058
- // src/compiler/NextJSCompiler.ts
2059
- init_CompilerBase();
2060
- init_Native2DCompiler();
2061
- function findTrait(composition, traitName) {
2062
- const traits = composition.traits;
2063
- if (!traits) return null;
2064
- const found = traits.find((t) => t.name === traitName);
2065
- return found?.config || null;
2066
- }
2067
- var NextJSCompiler = class extends CompilerBase {
2068
- constructor(options = {}) {
2069
- super();
2070
- this.options = options;
2071
- this.compilerName = "NextJSCompiler";
2072
- }
2073
- /**
2074
- * Compile HoloComposition AST to Next.js App Router Code
2075
- *
2076
- * @param composition - HoloScript AST
2077
- * @param agentToken - JWT or UCAN token proving agent identity
2078
- * @param outputPath - Optional output file path for scope validation
2079
- * @param sceneGraph - Optional pre-computed SSG
2080
- */
2081
- async compile(composition, agentToken, outputPath, _sceneGraph) {
2082
- this.validateCompilerAccess(agentToken, outputPath);
2083
- return this.buildNextRoute(composition);
2084
- }
2085
- validateCompilerAccess(agentToken, outputPath) {
2086
- if (typeof agentToken === "object" && agentToken !== null) {
2087
- this.validateCapabilityAccess(agentToken, outputPath);
2088
- } else {
2089
- this.validateASTAccess(agentToken);
2090
- this.validateCodeGeneration(agentToken);
2091
- if (outputPath) {
2092
- this.validateOutputPath(agentToken, outputPath);
2093
- }
2094
- this.validateSpatialZoneAccess(agentToken);
2095
- }
2096
- }
2097
- buildNextRoute(composition) {
2098
- const compiler = new Native2DCompiler();
2099
- const pageTrait = findTrait(composition, "page");
2100
- const metaTrait = findTrait(composition, "metadata");
2101
- const route = pageTrait?.route || `/${composition.name.toLowerCase().replace(/\s+/g, "-")}`;
2102
- const isClient = pageTrait?.client !== false;
2103
- const slotMap = this.options.slots || {};
2104
- if (pageTrait?.redirect) {
2105
- const redirectUrl = pageTrait.redirect;
2106
- const lines2 = [
2107
- `// @generated by HoloScript NextJSCompiler \u2014 DO NOT EDIT`,
2108
- `import { redirect } from 'next/navigation';`,
2109
- ``,
2110
- `export default function RedirectPage() {`,
2111
- ` redirect(${JSON.stringify(redirectUrl)});`,
2112
- `}`
2113
- ];
2114
- if (metaTrait) {
2115
- const metaEntries = [];
2116
- if (metaTrait.title) metaEntries.push(` title: ${JSON.stringify(metaTrait.title)},`);
2117
- if (metaTrait.description)
2118
- metaEntries.push(` description: ${JSON.stringify(metaTrait.description)},`);
2119
- lines2.push("");
2120
- lines2.push(`export const metadata = {`);
2121
- lines2.push(metaEntries.join("\n"));
2122
- lines2.push(`};`);
2123
- }
2124
- const routePath2 = route.replace(/^\//, "") || "index";
2125
- return {
2126
- path: `${routePath2}/page.tsx`,
2127
- code: lines2.join("\n")
2128
- };
2129
- }
2130
- const compilerOptions = {
2131
- format: "react",
2132
- useUIComponents: true,
2133
- slots: slotMap
2134
- };
2135
- const elements = composition.ui?.elements || composition.objects || [];
2136
- const componentCode = compiler.generateReactComponent(
2137
- composition.name,
2138
- elements,
2139
- composition,
2140
- compilerOptions
2141
- );
2142
- const pageSafeComponentCode = componentCode.replace(
2143
- /export\s+function\s+([A-Za-z0-9_]+)\s*\(/,
2144
- "function $1("
2145
- );
2146
- const lines = [];
2147
- if (isClient) {
2148
- lines.push("'use client';");
2149
- lines.push("");
2150
- }
2151
- lines.push(pageSafeComponentCode);
2152
- if (metaTrait && !isClient) {
2153
- const metaEntries = [];
2154
- if (metaTrait.title) metaEntries.push(` title: ${JSON.stringify(metaTrait.title)},`);
2155
- if (metaTrait.description)
2156
- metaEntries.push(` description: ${JSON.stringify(metaTrait.description)},`);
2157
- lines.push("");
2158
- lines.push(`export const metadata = {`);
2159
- lines.push(metaEntries.join("\n"));
2160
- lines.push(`};`);
2161
- }
2162
- const routePath = route.replace(/^\//, "") || "index";
2163
- return {
2164
- path: `${routePath}/page.tsx`,
2165
- code: lines.join("\n")
2166
- };
2167
- }
2168
- };
2169
-
2170
- // src/compiler/index.ts
2171
- init_NextJSAPICompiler();
2172
-
2173
- // src/compiler/MCPConfigCompiler.ts
2174
- init_CompilerBase();
2175
- init_DialectRegistry();
2176
- var MCPConfigCompiler = class extends CompilerBase {
2177
- constructor(options = {}) {
2178
- super();
2179
- this.compilerName = "MCPConfigCompiler";
2180
- this.servers = [];
2181
- this.options = {
2182
- target: options.target ?? "generic",
2183
- envFile: options.envFile ?? "",
2184
- envValues: options.envValues ?? {},
2185
- cwd: options.cwd ?? ""
2186
- };
2187
- }
2188
- compile(composition, agentToken, outputPath) {
2189
- this.validateCompilerAccess(agentToken, outputPath);
2190
- this.servers = [];
2191
- if (composition.domainBlocks) {
2192
- for (const block of composition.domainBlocks) {
2193
- if (block.domain === "mcp_servers" || block.name === "mcp_servers") {
2194
- this.extractServersFromBlock(block);
2195
- }
2196
- }
2197
- }
2198
- if (composition.objects) {
2199
- for (const obj of composition.objects) {
2200
- if (this.hasConnectorTrait(obj)) {
2201
- this.servers.push(this.extractServerFromObject(obj));
2202
- }
2203
- }
2204
- }
2205
- const config = this.generateConfig();
2206
- return JSON.stringify(config, null, 2);
2207
- }
2208
- // ── Extraction ────────────────────────────────────────────────────────────
2209
- extractServersFromBlock(block) {
2210
- if (!block.children) return;
2211
- for (const child of block.children) {
2212
- if ("type" in child && child.type === "ObjectDecl") {
2213
- const obj = child;
2214
- this.servers.push(this.extractServerFromObject(obj));
2215
- }
2216
- }
2217
- }
2218
- extractServerFromObject(obj) {
2219
- const props = this.objectPropsToMap(obj.properties);
2220
- const traits = obj.traits || [];
2221
- let transport = "http";
2222
- const connectorTrait = traits.find((t) => t.name === "connector");
2223
- if (connectorTrait?.config) {
2224
- const t = this.resolveString(connectorTrait.config["transport"] || connectorTrait.config["_arg1"]);
2225
- if (t === "stdio" || t === "sse" || t === "http") transport = t;
2226
- }
2227
- const envVars = [];
2228
- for (const trait of traits) {
2229
- if (trait.name === "env") {
2230
- const varName = this.resolveString(trait.config["_arg0"] || trait.config["name"] || "");
2231
- const header = this.resolveString(trait.config["header"] || "");
2232
- if (varName) {
2233
- envVars.push({ name: varName, header: header || void 0 });
2234
- }
2235
- }
2236
- }
2237
- return {
2238
- name: obj.name,
2239
- transport,
2240
- url: this.resolveString(props.get("url")),
2241
- command: this.resolveString(props.get("command")),
2242
- args: this.resolveArray(props.get("args")),
2243
- cwd: this.resolveString(props.get("cwd")),
2244
- description: this.resolveString(props.get("description")),
2245
- envVars
2246
- };
2247
- }
2248
- hasConnectorTrait(obj) {
2249
- return (obj.traits || []).some((t) => t.name === "connector");
2250
- }
2251
- // ── Config Generation ─────────────────────────────────────────────────────
2252
- generateConfig() {
2253
- const mcpServers = {};
2254
- for (const server of this.servers) {
2255
- mcpServers[server.name] = this.generateServerEntry(server);
2256
- }
2257
- const config = {
2258
- _generated: "HoloScript MCPConfigCompiler",
2259
- _target: this.options.target,
2260
- _updated: (/* @__PURE__ */ new Date()).toISOString().split("T")[0],
2261
- mcpServers
2262
- };
2263
- if (this.options.target === "claude") {
2264
- config["$schema"] = "https://modelcontextprotocol.io/schemas/mcp-config.json";
2265
- }
2266
- return config;
2267
- }
2268
- generateServerEntry(server) {
2269
- const entry = {};
2270
- if (server.transport === "stdio") {
2271
- entry.command = server.command || "node";
2272
- if (server.args) entry.args = server.args;
2273
- if (server.cwd || this.options.target === "antigravity") {
2274
- entry.cwd = server.cwd || this.options.cwd || void 0;
2275
- }
2276
- const envBlock = {};
2277
- for (const ev of server.envVars) {
2278
- if (!ev.header) {
2279
- envBlock[ev.name] = this.resolveEnvValue(ev.name);
2280
- }
2281
- }
2282
- if (Object.keys(envBlock).length > 0) {
2283
- entry.env = envBlock;
2284
- }
2285
- } else {
2286
- if (this.options.target === "antigravity") {
2287
- entry.serverURL = server.url;
2288
- } else {
2289
- entry.url = server.url;
2290
- }
2291
- if (this.options.target !== "antigravity" && server.transport === "sse") {
2292
- entry.transport = "sse";
2293
- }
2294
- const headers = {};
2295
- for (const ev of server.envVars) {
2296
- if (ev.header) {
2297
- const [headerName, ...prefix] = ev.header.split(":");
2298
- const prefixStr = prefix.join(":").trim();
2299
- const value = this.resolveEnvValue(ev.name);
2300
- headers[headerName.trim()] = prefixStr ? `${prefixStr} ${value}` : value;
2301
- } else {
2302
- headers[ev.name] = this.resolveEnvValue(ev.name);
2303
- }
2304
- }
2305
- if (Object.keys(headers).length > 0) {
2306
- entry.headers = headers;
2307
- }
2308
- }
2309
- if (server.description) {
2310
- entry.description = server.description;
2311
- }
2312
- return entry;
2313
- }
2314
- // ── Env Value Resolution ──────────────────────────────────────────────────
2315
- resolveEnvValue(varName) {
2316
- switch (this.options.target) {
2317
- case "antigravity":
2318
- return this.options.envValues[varName] || this.readEnvFile(varName) || `MISSING_${varName}`;
2319
- case "vscode":
2320
- return `\${env:${varName}}`;
2321
- case "claude":
2322
- case "cursor":
2323
- case "generic":
2324
- default:
2325
- return `\${${varName}}`;
2326
- }
2327
- }
2328
- readEnvFile(varName) {
2329
- if (!this.options.envFile) return void 0;
2330
- try {
2331
- return this.options.envValues[varName];
2332
- } catch {
2333
- return void 0;
2334
- }
2335
- }
2336
- // ── Helpers ───────────────────────────────────────────────────────────────
2337
- objectPropsToMap(props) {
2338
- const map = /* @__PURE__ */ new Map();
2339
- if (!props) return map;
2340
- for (const prop of props) {
2341
- map.set(prop.key, prop.value);
2342
- }
2343
- return map;
2344
- }
2345
- resolveString(value) {
2346
- if (!value) return void 0;
2347
- if (typeof value === "string") return value;
2348
- if (typeof value === "object" && "value" in value) {
2349
- return String(value.value);
2350
- }
2351
- return String(value);
2352
- }
2353
- resolveArray(value) {
2354
- if (!value) return void 0;
2355
- if (Array.isArray(value)) {
2356
- return value.map((v) => {
2357
- if (typeof v === "string") return v;
2358
- if (typeof v === "object" && v && "value" in v) return String(v.value);
2359
- return String(v);
2360
- });
2361
- }
2362
- return void 0;
2363
- }
2364
- };
2365
- DialectRegistry.register({
2366
- name: "mcp-config",
2367
- domain: "configuration",
2368
- description: "Compiles .holo server definitions to IDE-specific MCP config JSON",
2369
- supportedTraits: ["connector", "env"],
2370
- factory: (options) => new MCPConfigCompiler(options),
2371
- inputFormats: [".holo"],
2372
- outputFormat: ".json"
2373
- });
2374
-
2375
- // src/compiler/index.ts
2376
- init_Native2DCompiler();
2377
- init_NodeServiceCompiler();
2378
- init_DialectRegistry();
2379
- init_registerBuiltinDialects();
2380
-
2381
- export { DialectRegistry, MCPConfigCompiler, Native2DCompiler, NextJSCompiler, NodeServiceCompiler, compileAllToNextJSAPI, compileToNextJSAPI, ensureDialectsBooted, registerBuiltinDialects };
2382
- //# sourceMappingURL=index.js.map
2383
- //# sourceMappingURL=index.js.map