@holoscript/core 7.0.0 → 8.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 (345) hide show
  1. package/README.md +2 -2
  2. package/bin/holoscript.cjs +3 -0
  3. package/dist/GLTFPipeline-276GE64O.js +16 -0
  4. package/dist/GLTFPipeline-M7WSSJED.cjs +37 -0
  5. package/dist/HoloScriptPlusParser-7FBIFUFC.js +693 -0
  6. package/dist/HoloScriptPlusParser-A2W7OCN2.cjs +698 -0
  7. package/dist/HoloScriptPlusParser-F2Z56FJR.js +10 -0
  8. package/dist/HoloScriptPlusParser-WKHRIH6T.cjs +27 -0
  9. package/dist/HoloScriptRuntime-3URVTKPJ.js +10 -0
  10. package/dist/HoloScriptRuntime-SXEAEU2N.cjs +19 -0
  11. package/dist/USDZExporter-3FWJ25JI.cjs +1037 -0
  12. package/dist/USDZExporter-D2HQLQYK.js +1035 -0
  13. package/dist/agents/index.cjs +19 -0
  14. package/dist/agents/index.d.ts +100 -0
  15. package/dist/agents/index.js +17 -0
  16. package/dist/chunk-23J755AR.js +1046 -0
  17. package/dist/chunk-253GBQZY.cjs +627 -0
  18. package/dist/chunk-25IQCHTO.cjs +781 -0
  19. package/dist/chunk-2BSMSUCE.js +1941 -0
  20. package/dist/chunk-2M2DPHKB.js +762 -0
  21. package/dist/chunk-2YSNA2F2.cjs +1274 -0
  22. package/dist/chunk-3AO425MZ.cjs +886 -0
  23. package/dist/chunk-3FOKASKO.cjs +348 -0
  24. package/dist/chunk-3HYYMEXI.cjs +56578 -0
  25. package/dist/chunk-3NFFOWGG.js +4287 -0
  26. package/dist/chunk-3WZEJHUQ.cjs +116 -0
  27. package/dist/chunk-4C57PR42.js +468 -0
  28. package/dist/chunk-4N4SXXWF.js +769 -0
  29. package/dist/chunk-4PDEPEQW.cjs +41 -0
  30. package/dist/chunk-4R6SBXDB.js +45 -0
  31. package/dist/chunk-4V2E7U7Q.cjs +2015 -0
  32. package/dist/chunk-5FSKKMR7.cjs +2092 -0
  33. package/dist/chunk-5GLCTO44.js +161 -0
  34. package/dist/chunk-5JEU52DW.js +382 -0
  35. package/dist/chunk-5S7RKFGR.cjs +446 -0
  36. package/dist/chunk-5WUNN6ZN.cjs +428 -0
  37. package/dist/chunk-62FBK3B7.js +70 -0
  38. package/dist/chunk-6CTRH7HT.cjs +1985 -0
  39. package/dist/chunk-6DPSFNJB.cjs +847 -0
  40. package/dist/chunk-6EX3I5P4.cjs +130 -0
  41. package/dist/chunk-73FELZVJ.cjs +611 -0
  42. package/dist/chunk-7CUEMLDZ.cjs +6445 -0
  43. package/dist/chunk-7HIASF7S.cjs +814 -0
  44. package/dist/chunk-A6KINLZJ.js +236 -0
  45. package/dist/chunk-AIA52I7T.cjs +543 -0
  46. package/dist/chunk-ANXZFVY2.js +113 -0
  47. package/dist/chunk-AYBXB26F.js +2176 -0
  48. package/dist/chunk-B4TFTDG4.js +449 -0
  49. package/dist/chunk-BE4UJCQT.js +623 -0
  50. package/dist/chunk-BRQJKJGT.cjs +20 -0
  51. package/dist/chunk-C2A5DUMF.cjs +689 -0
  52. package/dist/chunk-C37BHB7N.cjs +636 -0
  53. package/dist/chunk-CBJY23VL.js +126 -0
  54. package/dist/chunk-CIWWXYHZ.cjs +50 -0
  55. package/dist/chunk-CXFDRBQU.cjs +672 -0
  56. package/dist/chunk-D54CNIAJ.cjs +413 -0
  57. package/dist/chunk-DAJXW4KX.js +725 -0
  58. package/dist/chunk-DTGBOSEM.cjs +319 -0
  59. package/dist/chunk-E7JP3BS3.cjs +61 -0
  60. package/dist/chunk-EKBKLK7P.js +1169 -0
  61. package/dist/chunk-EKYL4PE3.cjs +404 -0
  62. package/dist/chunk-EUDQTK7N.cjs +4310 -0
  63. package/dist/chunk-EXKSFGSX.cjs +274 -0
  64. package/dist/chunk-EXUP2BUM.cjs +1173 -0
  65. package/dist/chunk-F43YAA34.js +623 -0
  66. package/dist/chunk-FDSGHPAK.js +130 -0
  67. package/dist/chunk-FEWUHQNM.cjs +144 -0
  68. package/dist/chunk-FGGJQRLZ.js +270 -0
  69. package/dist/chunk-FHP6LXJS.js +415 -0
  70. package/dist/chunk-FJPADH77.cjs +666 -0
  71. package/dist/chunk-FYSPZT4V.cjs +169 -0
  72. package/dist/chunk-GIOYPNTH.js +5575 -0
  73. package/dist/chunk-GJNCFRJU.cjs +125 -0
  74. package/dist/chunk-GMP623FG.cjs +1508 -0
  75. package/dist/chunk-GQHQOPXZ.cjs +5580 -0
  76. package/dist/chunk-GQT4TYKY.cjs +4381 -0
  77. package/dist/chunk-GTU2Z2WW.cjs +262 -0
  78. package/dist/chunk-GYZE55MO.js +2007 -0
  79. package/dist/chunk-GZG4KA4E.js +529 -0
  80. package/dist/chunk-H652NHX5.js +600 -0
  81. package/dist/chunk-HCCQLAA4.cjs +74 -0
  82. package/dist/chunk-HINXWAOD.cjs +1049 -0
  83. package/dist/chunk-HYNTS5CP.js +422 -0
  84. package/dist/chunk-HZSPDCXV.cjs +457 -0
  85. package/dist/chunk-HZTDET3N.js +1399 -0
  86. package/dist/chunk-I6XZ5DZF.cjs +488 -0
  87. package/dist/chunk-ILRBGFVD.cjs +72 -0
  88. package/dist/chunk-IPWSXCCN.js +1183 -0
  89. package/dist/chunk-IUTY5WQ2.cjs +424 -0
  90. package/dist/chunk-IVSZDECV.js +882 -0
  91. package/dist/chunk-IVY74O6C.js +247 -0
  92. package/dist/chunk-IZM5VQZD.js +714 -0
  93. package/dist/chunk-J32ZJZJH.js +554 -0
  94. package/dist/chunk-J6M4FPK5.js +421 -0
  95. package/dist/chunk-JC5YBPSF.cjs +984 -0
  96. package/dist/chunk-JCLBKPMX.js +3813 -0
  97. package/dist/chunk-JD7CIZ33.js +1949 -0
  98. package/dist/chunk-JIYN45TV.cjs +2525 -0
  99. package/dist/chunk-JJBE3TIH.cjs +1189 -0
  100. package/dist/chunk-JX7YL6ZE.js +2252 -0
  101. package/dist/chunk-K4VVR7CN.cjs +2433 -0
  102. package/dist/chunk-KEFNV2WM.cjs +2257 -0
  103. package/dist/chunk-KH4CNH66.cjs +424 -0
  104. package/dist/chunk-KJLB4OPV.js +5731 -0
  105. package/dist/chunk-KKFZ3B6J.cjs +557 -0
  106. package/dist/chunk-KKP7JKN4.cjs +6002 -0
  107. package/dist/chunk-KPJL34Y7.cjs +186 -0
  108. package/dist/chunk-KQCN6AKJ.cjs +3042 -0
  109. package/dist/chunk-KVRSTFNH.cjs +72 -0
  110. package/dist/chunk-LICPB5HZ.cjs +1409 -0
  111. package/dist/chunk-LM2VU56C.cjs +37 -0
  112. package/dist/chunk-M56JSP4A.js +400 -0
  113. package/dist/chunk-MBOOR7X4.js +18 -0
  114. package/dist/chunk-MGE5Z4GS.js +608 -0
  115. package/dist/chunk-MXFUTKCO.js +56 -0
  116. package/dist/chunk-MYY4PMWX.cjs +264 -0
  117. package/dist/chunk-N75IH2HY.js +258 -0
  118. package/dist/chunk-NBMHU6SW.js +669 -0
  119. package/dist/chunk-NG77ATEW.cjs +778 -0
  120. package/dist/chunk-NGKREZ36.js +6384 -0
  121. package/dist/chunk-NHWSN2SD.cjs +718 -0
  122. package/dist/chunk-NV4VMVXU.js +421 -0
  123. package/dist/chunk-NW5G5FBQ.js +215 -0
  124. package/dist/chunk-NXZFOPVD.cjs +5737 -0
  125. package/dist/chunk-OBIYPYYS.cjs +1993 -0
  126. package/dist/chunk-OIQYIIO3.cjs +473 -0
  127. package/dist/chunk-OL46QLBJ.js +61 -0
  128. package/dist/chunk-OMXII44L.js +5386 -0
  129. package/dist/chunk-OR4Q2BGL.cjs +759 -0
  130. package/dist/chunk-OSYNRVOV.cjs +243 -0
  131. package/dist/chunk-PGANYCAG.cjs +220 -0
  132. package/dist/chunk-PHENW4MQ.js +65 -0
  133. package/dist/chunk-PHVRG4I2.js +844 -0
  134. package/dist/chunk-Q56TT7IL.js +483 -0
  135. package/dist/chunk-QPOQ7VPI.js +1491 -0
  136. package/dist/chunk-QPSKHBJP.js +5963 -0
  137. package/dist/chunk-QXH7QDSZ.js +1989 -0
  138. package/dist/chunk-R75BSDH7.cjs +50 -0
  139. package/dist/chunk-RARB3MBR.js +207 -0
  140. package/dist/chunk-RVBHAXFG.js +56160 -0
  141. package/dist/chunk-S3MDHNKB.cjs +490 -0
  142. package/dist/chunk-S4W6Z2MN.js +2426 -0
  143. package/dist/chunk-S6YWHCKV.cjs +410 -0
  144. package/dist/chunk-SIEXCILW.js +229 -0
  145. package/dist/chunk-SJBGLS25.cjs +2196 -0
  146. package/dist/chunk-SLU6UPJI.cjs +410 -0
  147. package/dist/chunk-SMIWS6DE.cjs +212 -0
  148. package/dist/chunk-T2QCTZMO.js +811 -0
  149. package/dist/chunk-T5J7ZKP3.cjs +4885 -0
  150. package/dist/chunk-TDCNJHWO.js +341 -0
  151. package/dist/chunk-TG7O4WBC.js +406 -0
  152. package/dist/chunk-THCK6ECW.js +2085 -0
  153. package/dist/chunk-TJHVSBP2.js +439 -0
  154. package/dist/chunk-TVHSPJ4N.cjs +606 -0
  155. package/dist/chunk-U44IKGG7.cjs +5390 -0
  156. package/dist/chunk-UJXISJBN.js +487 -0
  157. package/dist/chunk-UM6C3CGK.js +4375 -0
  158. package/dist/chunk-UMABK6SI.js +686 -0
  159. package/dist/chunk-UOIGFQXC.cjs +9750 -0
  160. package/dist/chunk-URG2SJLK.js +2521 -0
  161. package/dist/chunk-V6MKC2FZ.js +979 -0
  162. package/dist/chunk-VECQYRXL.js +474 -0
  163. package/dist/chunk-VJ3L7CHT.cjs +169 -0
  164. package/dist/chunk-VMLKSV26.js +1216 -0
  165. package/dist/chunk-VVKVQZI6.js +55 -0
  166. package/dist/chunk-W6RW64BB.cjs +1219 -0
  167. package/dist/chunk-W7VDOASB.cjs +639 -0
  168. package/dist/chunk-WDT3JTGM.cjs +483 -0
  169. package/dist/chunk-WJIHFLMJ.js +404 -0
  170. package/dist/chunk-WKX5AMOY.js +309 -0
  171. package/dist/chunk-WNNE3PO3.js +34 -0
  172. package/dist/chunk-WRKUDAZJ.js +3038 -0
  173. package/dist/chunk-WRLUBRKS.cjs +1943 -0
  174. package/dist/chunk-WRNEH5MO.js +3169 -0
  175. package/dist/chunk-WRWEX5ZF.js +658 -0
  176. package/dist/chunk-X3GJPRVK.cjs +3246 -0
  177. package/dist/chunk-XHIV6326.cjs +793 -0
  178. package/dist/chunk-XIVIE43A.cjs +729 -0
  179. package/dist/chunk-XJAN7CZG.cjs +432 -0
  180. package/dist/chunk-XKTPFXGA.js +164 -0
  181. package/dist/chunk-XL6INWKT.js +121 -0
  182. package/dist/chunk-XSFNHP2E.js +632 -0
  183. package/dist/chunk-XT6JY5W5.js +9684 -0
  184. package/dist/chunk-XUILI4KB.cjs +430 -0
  185. package/dist/chunk-XUUVDHIF.cjs +3962 -0
  186. package/dist/chunk-YF2I3MV3.js +46 -0
  187. package/dist/chunk-YIMN575O.js +4847 -0
  188. package/dist/chunk-YIVFJNYV.js +176 -0
  189. package/dist/chunk-YKGPCZEE.cjs +237 -0
  190. package/dist/chunk-YN6V7R3L.cjs +327 -0
  191. package/dist/chunk-YQELFNJV.js +39 -0
  192. package/dist/chunk-YYXH45E2.js +426 -0
  193. package/dist/chunk-ZBQXLH2L.js +756 -0
  194. package/dist/chunk-ZDSYWBIE.cjs +69 -0
  195. package/dist/chunk-ZU7NIRT6.js +325 -0
  196. package/dist/chunk-ZZ7RO2UQ.js +1243 -0
  197. package/dist/chunk-ZZEI7MV4.js +778 -0
  198. package/dist/cli/holoscript-runner.cjs +2255 -0
  199. package/dist/cli/holoscript-runner.js +2230 -0
  200. package/dist/codebase/index.cjs +336 -0
  201. package/dist/codebase/index.js +331 -0
  202. package/dist/compiler/agent-inference.cjs +31 -0
  203. package/dist/compiler/agent-inference.js +8 -0
  204. package/dist/compiler/android-xr.cjs +24 -0
  205. package/dist/compiler/android-xr.js +14 -0
  206. package/dist/compiler/android.cjs +24 -0
  207. package/dist/compiler/android.js +14 -0
  208. package/dist/compiler/ar.cjs +23 -0
  209. package/dist/compiler/ar.js +11 -0
  210. package/dist/compiler/babylon.cjs +21 -0
  211. package/dist/compiler/babylon.js +15 -0
  212. package/dist/compiler/business-quest.cjs +43 -0
  213. package/dist/compiler/business-quest.js +4 -0
  214. package/dist/compiler/coco.cjs +27 -0
  215. package/dist/compiler/coco.js +4 -0
  216. package/dist/compiler/context.cjs +25 -0
  217. package/dist/compiler/context.d.ts +28 -0
  218. package/dist/compiler/context.js +8 -0
  219. package/dist/compiler/domain-block-utils.cjs +605 -0
  220. package/dist/compiler/domain-block-utils.js +11 -0
  221. package/dist/compiler/dtdl.cjs +27 -0
  222. package/dist/compiler/dtdl.js +11 -0
  223. package/dist/compiler/gltf-pipeline.cjs +39 -0
  224. package/dist/compiler/gltf-pipeline.js +4 -0
  225. package/dist/compiler/godot.cjs +18 -0
  226. package/dist/compiler/godot.js +12 -0
  227. package/dist/compiler/incremental.cjs +34 -0
  228. package/dist/compiler/incremental.js +9 -0
  229. package/dist/compiler/index.cjs +5860 -0
  230. package/dist/compiler/index.d.ts +322 -21
  231. package/dist/compiler/index.js +5525 -0
  232. package/dist/compiler/ios.cjs +23 -0
  233. package/dist/compiler/ios.js +13 -0
  234. package/dist/compiler/llm-provider-capabilities.cjs +25 -0
  235. package/dist/compiler/llm-provider-capabilities.d.ts +43 -0
  236. package/dist/compiler/llm-provider-capabilities.js +8 -0
  237. package/dist/compiler/multi-layer.cjs +24 -0
  238. package/dist/compiler/multi-layer.js +15 -0
  239. package/dist/compiler/nodetoy.cjs +23 -0
  240. package/dist/compiler/nodetoy.js +4 -0
  241. package/dist/compiler/openxr.cjs +19 -0
  242. package/dist/compiler/openxr.js +13 -0
  243. package/dist/compiler/playcanvas.cjs +19 -0
  244. package/dist/compiler/playcanvas.js +13 -0
  245. package/dist/compiler/r3f.cjs +38 -0
  246. package/dist/compiler/r3f.d.ts +22 -0
  247. package/dist/compiler/r3f.js +16 -0
  248. package/dist/compiler/remotion.cjs +23 -0
  249. package/dist/compiler/remotion.js +4 -0
  250. package/dist/compiler/reproducibility.cjs +39 -0
  251. package/dist/compiler/reproducibility.js +4 -0
  252. package/dist/compiler/sdf.cjs +24 -0
  253. package/dist/compiler/sdf.js +12 -0
  254. package/dist/compiler/semantic-scene.cjs +31 -0
  255. package/dist/compiler/semantic-scene.js +4 -0
  256. package/dist/compiler/state.cjs +21 -0
  257. package/dist/compiler/state.js +11 -0
  258. package/dist/compiler/trait-composition.cjs +30 -0
  259. package/dist/compiler/trait-composition.js +9 -0
  260. package/dist/compiler/unity.cjs +19 -0
  261. package/dist/compiler/unity.js +13 -0
  262. package/dist/compiler/unreal.cjs +23 -0
  263. package/dist/compiler/unreal.js +13 -0
  264. package/dist/compiler/urdf.cjs +52 -0
  265. package/dist/compiler/urdf.js +12 -0
  266. package/dist/compiler/usd-physics.cjs +26 -0
  267. package/dist/compiler/usd-physics.js +9 -0
  268. package/dist/compiler/visionos.cjs +19 -0
  269. package/dist/compiler/visionos.js +13 -0
  270. package/dist/compiler/vrchat.cjs +22 -0
  271. package/dist/compiler/vrchat.js +12 -0
  272. package/dist/compiler/vrr.cjs +24 -0
  273. package/dist/compiler/vrr.js +12 -0
  274. package/dist/compiler/wasm.cjs +36 -0
  275. package/dist/compiler/wasm.js +12 -0
  276. package/dist/compiler/webgpu.cjs +18 -0
  277. package/dist/compiler/webgpu.js +12 -0
  278. package/dist/coordinators/index.cjs +1266 -0
  279. package/dist/coordinators/index.d.ts +72 -1
  280. package/dist/coordinators/index.js +1259 -0
  281. package/dist/debugger.cjs +24 -0
  282. package/dist/debugger.js +11 -0
  283. package/dist/entries/interop.cjs +64 -0
  284. package/dist/entries/interop.js +7 -0
  285. package/dist/entries/scripting.cjs +55 -0
  286. package/dist/entries/scripting.js +10 -0
  287. package/dist/hololand/index.cjs +146 -0
  288. package/dist/hololand/index.d.ts +70 -0
  289. package/dist/hololand/index.js +5 -0
  290. package/dist/index.cjs +43233 -0
  291. package/dist/index.d.ts +976 -21
  292. package/dist/index.js +39995 -0
  293. package/dist/math/tropical-spmv.cjs +45 -0
  294. package/dist/math/tropical-spmv.js +4 -0
  295. package/dist/math/vec3.cjs +57 -0
  296. package/dist/math/vec3.js +4 -0
  297. package/dist/ml-dsa-FSKBTE3W.cjs +1265 -0
  298. package/dist/ml-dsa-Z7JDKW4L.js +1265 -0
  299. package/dist/paper-0c-spike/index.cjs +150 -0
  300. package/dist/paper-0c-spike/index.js +141 -0
  301. package/dist/parser.cjs +61 -0
  302. package/dist/parser.d.ts +11 -0
  303. package/dist/parser.js +12 -0
  304. package/dist/playwright-3AT3AKTV.cjs +98673 -0
  305. package/dist/playwright-VZPDVUEQ.js +98660 -0
  306. package/dist/reconstruction/index.cjs +153 -0
  307. package/dist/reconstruction/index.d.ts +29 -2
  308. package/dist/reconstruction/index.js +8 -0
  309. package/dist/runtime.cjs +316 -0
  310. package/dist/runtime.d.ts +61 -0
  311. package/dist/runtime.js +31 -0
  312. package/dist/self-improvement/index.cjs +563 -0
  313. package/dist/self-improvement/index.js +545 -0
  314. package/dist/storage/index.cjs +38 -0
  315. package/dist/storage/index.js +5 -0
  316. package/dist/testing.cjs +25 -0
  317. package/dist/testing.d.ts +70 -0
  318. package/dist/testing.js +4 -0
  319. package/dist/traitDocs/traitDocs.cjs +33 -0
  320. package/dist/traitDocs/traitDocs.js +7 -0
  321. package/dist/traits/botanical-lotus.cjs +41 -0
  322. package/dist/traits/botanical-lotus.d.ts +172 -0
  323. package/dist/traits/botanical-lotus.js +4 -0
  324. package/dist/traits/engines/index.cjs +520 -0
  325. package/dist/traits/engines/index.js +380 -0
  326. package/dist/traits/index.cjs +24409 -0
  327. package/dist/traits/index.d.ts +171 -35
  328. package/dist/traits/index.js +21634 -0
  329. package/dist/traits/simulation-solver-factory.cjs +13 -0
  330. package/dist/traits/simulation-solver-factory.d.ts +23 -0
  331. package/dist/traits/simulation-solver-factory.js +4 -0
  332. package/dist/traits/webcam-gaze.cjs +35 -0
  333. package/dist/traits/webcam-gaze.d.ts +17 -0
  334. package/dist/traits/webcam-gaze.js +4 -0
  335. package/dist/type-checker.cjs +19 -0
  336. package/dist/type-checker.js +6 -0
  337. package/dist/world/index.cjs +947 -0
  338. package/dist/world/index.d.ts +147 -0
  339. package/dist/world/index.js +939 -0
  340. package/dist/world-model/index.cjs +1446 -0
  341. package/dist/world-model/index.d.ts +119 -0
  342. package/dist/world-model/index.js +1414 -0
  343. package/dist/wot/index.cjs +29 -0
  344. package/dist/wot/index.js +4 -0
  345. package/package.json +93 -49
@@ -0,0 +1,4885 @@
1
+ 'use strict';
2
+
3
+ var chunkNG77ATEW_cjs = require('./chunk-NG77ATEW.cjs');
4
+ var chunkWRLUBRKS_cjs = require('./chunk-WRLUBRKS.cjs');
5
+ var crypto = require('crypto');
6
+
7
+ function _interopNamespace(e) {
8
+ if (e && e.__esModule) return e;
9
+ var n = Object.create(null);
10
+ if (e) {
11
+ Object.keys(e).forEach(function (k) {
12
+ if (k !== 'default') {
13
+ var d = Object.getOwnPropertyDescriptor(e, k);
14
+ Object.defineProperty(n, k, d.get ? d : {
15
+ enumerable: true,
16
+ get: function () { return e[k]; }
17
+ });
18
+ }
19
+ });
20
+ }
21
+ n.default = e;
22
+ return Object.freeze(n);
23
+ }
24
+
25
+ var crypto__namespace = /*#__PURE__*/_interopNamespace(crypto);
26
+
27
+ // src/parser/HybridChunker.ts
28
+ function countTokens(text) {
29
+ return Math.ceil(text.length / 4);
30
+ }
31
+ function detectFileType(filePath) {
32
+ const ext = filePath.split(".").pop()?.toLowerCase() || "";
33
+ if (["ts", "js", "jsx", "tsx", "hs", "hsplus"].includes(ext)) {
34
+ return "code";
35
+ }
36
+ if (["log", "txt", "csv"].includes(ext)) {
37
+ return "log";
38
+ }
39
+ if (["md", "mdx", "markdown"].includes(ext)) {
40
+ return "markdown";
41
+ }
42
+ return "unknown";
43
+ }
44
+ var StructureBasedChunker = class {
45
+ constructor(options) {
46
+ this.options = {
47
+ maxTokens: options.maxTokens || 1024,
48
+ overlapTokens: options.overlapTokens || 100,
49
+ semanticThreshold: options.semanticThreshold || 0.85,
50
+ debug: options.debug || false
51
+ };
52
+ }
53
+ /**
54
+ * Chunk code files by detecting structural boundaries
55
+ */
56
+ chunk(content, filePath) {
57
+ const lines = content.split("\n");
58
+ const boundaries = this.detectStructuralBoundaries(lines);
59
+ if (boundaries.length === 0) {
60
+ return [
61
+ {
62
+ id: `structure:${filePath}:0`,
63
+ type: "code-block",
64
+ startLine: 1,
65
+ endLine: lines.length,
66
+ content,
67
+ tokens: countTokens(content),
68
+ strategy: "structure"
69
+ }
70
+ ];
71
+ }
72
+ const chunks = [];
73
+ let currentChunk = [];
74
+ let currentStart = 1;
75
+ let chunkIndex = 0;
76
+ for (let i = 0; i < boundaries.length; i++) {
77
+ const boundary = boundaries[i];
78
+ const segmentContent = lines.slice(boundary.startLine - 1, boundary.endLine).join("\n");
79
+ const segmentTokens = countTokens(segmentContent);
80
+ if (currentChunk.length > 0 && countTokens(currentChunk.join("\n") + "\n" + segmentContent) > this.options.maxTokens) {
81
+ const chunkContent = currentChunk.join("\n");
82
+ chunks.push({
83
+ id: `structure:${filePath}:${chunkIndex++}`,
84
+ type: "code-block",
85
+ startLine: currentStart,
86
+ endLine: currentStart + currentChunk.length - 1,
87
+ content: chunkContent,
88
+ tokens: countTokens(chunkContent),
89
+ strategy: "structure"
90
+ });
91
+ currentChunk = [];
92
+ currentStart = boundary.startLine;
93
+ }
94
+ if (segmentTokens > this.options.maxTokens) {
95
+ const subChunks = this.recursiveSplit(
96
+ segmentContent,
97
+ boundary.startLine,
98
+ filePath,
99
+ chunkIndex
100
+ );
101
+ chunks.push(...subChunks);
102
+ chunkIndex += subChunks.length;
103
+ } else {
104
+ currentChunk.push(segmentContent);
105
+ }
106
+ }
107
+ if (currentChunk.length > 0) {
108
+ const chunkContent = currentChunk.join("\n");
109
+ chunks.push({
110
+ id: `structure:${filePath}:${chunkIndex}`,
111
+ type: "code-block",
112
+ startLine: currentStart,
113
+ endLine: currentStart + currentChunk.length - 1,
114
+ content: chunkContent,
115
+ tokens: countTokens(chunkContent),
116
+ strategy: "structure"
117
+ });
118
+ }
119
+ return chunks;
120
+ }
121
+ /**
122
+ * Detect structural boundaries (functions, classes, interfaces)
123
+ */
124
+ detectStructuralBoundaries(lines) {
125
+ const boundaries = [];
126
+ let braceDepth = 0;
127
+ let currentBlock = null;
128
+ for (let i = 0; i < lines.length; i++) {
129
+ const line = lines[i];
130
+ const trimmed = line.trim();
131
+ if (!currentBlock) {
132
+ const functionMatch = trimmed.match(
133
+ /^(export\s+)?(async\s+)?function\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/
134
+ );
135
+ const classMatch = trimmed.match(
136
+ /^(export\s+)?(abstract\s+)?class\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/
137
+ );
138
+ const interfaceMatch = trimmed.match(/^(export\s+)?interface\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/);
139
+ const methodMatch = trimmed.match(
140
+ /^(public|private|protected|static)?\s*([a-zA-Z_$][a-zA-Z0-9_$]*)\s*\([^)]*\)\s*[:{]/
141
+ );
142
+ if (functionMatch) {
143
+ currentBlock = {
144
+ type: "function",
145
+ name: functionMatch[3],
146
+ startLine: i + 1
147
+ };
148
+ } else if (classMatch) {
149
+ currentBlock = {
150
+ type: "class",
151
+ name: classMatch[3],
152
+ startLine: i + 1
153
+ };
154
+ } else if (interfaceMatch) {
155
+ currentBlock = {
156
+ type: "interface",
157
+ name: interfaceMatch[2],
158
+ startLine: i + 1
159
+ };
160
+ } else if (methodMatch) {
161
+ currentBlock = {
162
+ type: "method",
163
+ name: methodMatch[2],
164
+ startLine: i + 1
165
+ };
166
+ }
167
+ }
168
+ if (currentBlock) {
169
+ for (const char of line) {
170
+ if (char === "{") braceDepth++;
171
+ if (char === "}") braceDepth--;
172
+ }
173
+ if (braceDepth === 0 && trimmed.includes("}")) {
174
+ boundaries.push({
175
+ type: currentBlock.type,
176
+ name: currentBlock.name,
177
+ startLine: currentBlock.startLine,
178
+ endLine: i + 1
179
+ });
180
+ currentBlock = null;
181
+ }
182
+ }
183
+ }
184
+ if (currentBlock) {
185
+ boundaries.push({
186
+ type: currentBlock.type,
187
+ name: currentBlock.name,
188
+ startLine: currentBlock.startLine,
189
+ endLine: lines.length
190
+ });
191
+ }
192
+ return boundaries;
193
+ }
194
+ /**
195
+ * Recursively split large segments
196
+ */
197
+ recursiveSplit(content, startLine, filePath, baseIndex) {
198
+ const lines = content.split("\n");
199
+ const chunks = [];
200
+ let currentChunk = [];
201
+ let currentStart = startLine;
202
+ for (let i = 0; i < lines.length; i++) {
203
+ currentChunk.push(lines[i]);
204
+ if (countTokens(currentChunk.join("\n")) >= this.options.maxTokens) {
205
+ const chunkContent = currentChunk.join("\n");
206
+ chunks.push({
207
+ id: `structure:${filePath}:${baseIndex + chunks.length}`,
208
+ type: "code-fragment",
209
+ startLine: currentStart,
210
+ endLine: currentStart + currentChunk.length - 1,
211
+ content: chunkContent,
212
+ tokens: countTokens(chunkContent),
213
+ strategy: "structure",
214
+ metadata: { splitReason: "recursive-oversized" }
215
+ });
216
+ currentChunk = [];
217
+ currentStart = startLine + i + 1;
218
+ }
219
+ }
220
+ if (currentChunk.length > 0) {
221
+ const chunkContent = currentChunk.join("\n");
222
+ chunks.push({
223
+ id: `structure:${filePath}:${baseIndex + chunks.length}`,
224
+ type: "code-fragment",
225
+ startLine: currentStart,
226
+ endLine: currentStart + currentChunk.length - 1,
227
+ content: chunkContent,
228
+ tokens: countTokens(chunkContent),
229
+ strategy: "structure"
230
+ });
231
+ }
232
+ return chunks;
233
+ }
234
+ };
235
+ var FixedSizeChunker = class {
236
+ constructor(options) {
237
+ this.options = {
238
+ maxTokens: options.maxTokens || 1024,
239
+ overlapTokens: options.overlapTokens || 100,
240
+ semanticThreshold: options.semanticThreshold || 0.85,
241
+ debug: options.debug || false
242
+ };
243
+ }
244
+ /**
245
+ * Chunk text files into fixed-size segments with overlap
246
+ */
247
+ chunk(content, filePath) {
248
+ const lines = content.split("\n");
249
+ const chunks = [];
250
+ let currentChunk = [];
251
+ let currentStart = 1;
252
+ let chunkIndex = 0;
253
+ for (let i = 0; i < lines.length; i++) {
254
+ currentChunk.push(lines[i]);
255
+ const currentTokens = countTokens(currentChunk.join("\n"));
256
+ if (currentTokens >= this.options.maxTokens) {
257
+ const chunkContent = currentChunk.join("\n");
258
+ chunks.push({
259
+ id: `fixed:${filePath}:${chunkIndex++}`,
260
+ type: "text-block",
261
+ startLine: currentStart,
262
+ endLine: currentStart + currentChunk.length - 1,
263
+ content: chunkContent,
264
+ tokens: currentTokens,
265
+ strategy: "fixed"
266
+ });
267
+ const overlapLines = this.calculateOverlapLines(currentChunk);
268
+ currentChunk = overlapLines;
269
+ currentStart = currentStart + currentChunk.length - overlapLines.length;
270
+ }
271
+ }
272
+ if (currentChunk.length > 0) {
273
+ const chunkContent = currentChunk.join("\n");
274
+ chunks.push({
275
+ id: `fixed:${filePath}:${chunkIndex}`,
276
+ type: "text-block",
277
+ startLine: currentStart,
278
+ endLine: currentStart + currentChunk.length - 1,
279
+ content: chunkContent,
280
+ tokens: countTokens(chunkContent),
281
+ strategy: "fixed"
282
+ });
283
+ }
284
+ return chunks;
285
+ }
286
+ /**
287
+ * Calculate overlap lines based on token count
288
+ */
289
+ calculateOverlapLines(lines) {
290
+ const overlapLines = [];
291
+ let overlapTokens = 0;
292
+ for (let i = lines.length - 1; i >= 0; i--) {
293
+ const lineTokens = countTokens(lines[i]);
294
+ if (overlapTokens + lineTokens > this.options.overlapTokens) {
295
+ break;
296
+ }
297
+ overlapLines.unshift(lines[i]);
298
+ overlapTokens += lineTokens;
299
+ }
300
+ return overlapLines;
301
+ }
302
+ };
303
+ var SemanticChunker = class {
304
+ constructor(options) {
305
+ this.options = {
306
+ maxTokens: options.maxTokens || 1024,
307
+ overlapTokens: options.overlapTokens || 100,
308
+ semanticThreshold: options.semanticThreshold || 0.85,
309
+ debug: options.debug || false
310
+ };
311
+ }
312
+ /**
313
+ * Chunk markdown/docs by semantic similarity
314
+ */
315
+ chunk(content, filePath) {
316
+ const paragraphs = this.detectParagraphs(content);
317
+ if (paragraphs.length === 0) {
318
+ return [
319
+ {
320
+ id: `semantic:${filePath}:0`,
321
+ type: "document",
322
+ startLine: 1,
323
+ endLine: content.split("\n").length,
324
+ content,
325
+ tokens: countTokens(content),
326
+ strategy: "semantic"
327
+ }
328
+ ];
329
+ }
330
+ const chunks = [];
331
+ let currentGroup = [];
332
+ let chunkIndex = 0;
333
+ for (let i = 0; i < paragraphs.length; i++) {
334
+ const para = paragraphs[i];
335
+ if (currentGroup.length === 0) {
336
+ currentGroup.push(para);
337
+ continue;
338
+ }
339
+ const lastPara = currentGroup[currentGroup.length - 1];
340
+ const similarity2 = this.computeSimilarity(lastPara.content, para.content);
341
+ const groupContent = currentGroup.map((p) => p.content).join("\n\n");
342
+ const groupTokens = countTokens(groupContent + "\n\n" + para.content);
343
+ if (similarity2 >= this.options.semanticThreshold && groupTokens <= this.options.maxTokens) {
344
+ currentGroup.push(para);
345
+ } else {
346
+ const chunkContent = currentGroup.map((p) => p.content).join("\n\n");
347
+ chunks.push({
348
+ id: `semantic:${filePath}:${chunkIndex++}`,
349
+ type: "semantic-group",
350
+ startLine: currentGroup[0].startLine,
351
+ endLine: currentGroup[currentGroup.length - 1].endLine,
352
+ content: chunkContent,
353
+ tokens: countTokens(chunkContent),
354
+ strategy: "semantic",
355
+ metadata: {
356
+ paragraphCount: currentGroup.length
357
+ }
358
+ });
359
+ currentGroup = [para];
360
+ }
361
+ }
362
+ if (currentGroup.length > 0) {
363
+ const chunkContent = currentGroup.map((p) => p.content).join("\n\n");
364
+ chunks.push({
365
+ id: `semantic:${filePath}:${chunkIndex}`,
366
+ type: "semantic-group",
367
+ startLine: currentGroup[0].startLine,
368
+ endLine: currentGroup[currentGroup.length - 1].endLine,
369
+ content: chunkContent,
370
+ tokens: countTokens(chunkContent),
371
+ strategy: "semantic",
372
+ metadata: {
373
+ paragraphCount: currentGroup.length
374
+ }
375
+ });
376
+ }
377
+ return chunks;
378
+ }
379
+ /**
380
+ * Detect paragraph boundaries in markdown
381
+ */
382
+ detectParagraphs(content) {
383
+ const lines = content.split("\n");
384
+ const paragraphs = [];
385
+ let currentPara = [];
386
+ let currentStart = 1;
387
+ for (let i = 0; i < lines.length; i++) {
388
+ const line = lines[i];
389
+ const trimmed = line.trim();
390
+ if (trimmed === "" || trimmed.startsWith("#") || /^[-*+]\s/.test(trimmed) || /^\d+\.\s/.test(trimmed)) {
391
+ if (currentPara.length > 0) {
392
+ paragraphs.push({
393
+ content: currentPara.join("\n"),
394
+ startLine: currentStart,
395
+ endLine: i
396
+ });
397
+ currentPara = [];
398
+ }
399
+ if (trimmed !== "") {
400
+ currentPara.push(line);
401
+ currentStart = i + 1;
402
+ } else {
403
+ currentStart = i + 2;
404
+ }
405
+ } else {
406
+ currentPara.push(line);
407
+ }
408
+ }
409
+ if (currentPara.length > 0) {
410
+ paragraphs.push({
411
+ content: currentPara.join("\n"),
412
+ startLine: currentStart,
413
+ endLine: lines.length
414
+ });
415
+ }
416
+ return paragraphs;
417
+ }
418
+ /**
419
+ * Compute similarity between two text segments
420
+ *
421
+ * Simple heuristic: Jaccard similarity of word sets
422
+ * For production: Use sentence-transformers embeddings + cosine similarity
423
+ */
424
+ computeSimilarity(text1, text2) {
425
+ const words1 = new Set(
426
+ text1.toLowerCase().split(/\s+/).filter((w) => w.length > 3)
427
+ );
428
+ const words2 = new Set(
429
+ text2.toLowerCase().split(/\s+/).filter((w) => w.length > 3)
430
+ );
431
+ const intersection = new Set([...words1].filter((w) => words2.has(w)));
432
+ const union = /* @__PURE__ */ new Set([...words1, ...words2]);
433
+ return union.size > 0 ? intersection.size / union.size : 0;
434
+ }
435
+ };
436
+ var HybridChunker = class {
437
+ constructor(options = {}) {
438
+ this.options = {
439
+ maxTokens: options.maxTokens || 1024,
440
+ overlapTokens: options.overlapTokens || 100,
441
+ semanticThreshold: options.semanticThreshold || 0.85,
442
+ debug: options.debug || false
443
+ };
444
+ this.structureChunker = new StructureBasedChunker(this.options);
445
+ this.fixedChunker = new FixedSizeChunker(this.options);
446
+ this.semanticChunker = new SemanticChunker(this.options);
447
+ }
448
+ /**
449
+ * Chunk a file using the optimal strategy
450
+ */
451
+ chunk(content, filePath) {
452
+ const fileType = detectFileType(filePath);
453
+ this.log(`Chunking ${filePath} (type: ${fileType})`);
454
+ let chunks;
455
+ switch (fileType) {
456
+ case "code":
457
+ chunks = this.structureChunker.chunk(content, filePath);
458
+ break;
459
+ case "log":
460
+ chunks = this.fixedChunker.chunk(content, filePath);
461
+ break;
462
+ case "markdown":
463
+ chunks = this.semanticChunker.chunk(content, filePath);
464
+ break;
465
+ default:
466
+ this.log(`Unknown file type for ${filePath}, using fixed-size chunking`);
467
+ chunks = this.fixedChunker.chunk(content, filePath);
468
+ }
469
+ this.log(
470
+ `Generated ${chunks.length} chunks (${chunks.reduce((sum, c) => sum + c.tokens, 0)} total tokens)`
471
+ );
472
+ return chunks;
473
+ }
474
+ /**
475
+ * Get chunking statistics
476
+ */
477
+ getStats(chunks) {
478
+ const totalTokens = chunks.reduce((sum, c) => sum + c.tokens, 0);
479
+ const strategyDistribution = {};
480
+ for (const chunk of chunks) {
481
+ strategyDistribution[chunk.strategy] = (strategyDistribution[chunk.strategy] || 0) + 1;
482
+ }
483
+ return {
484
+ totalChunks: chunks.length,
485
+ totalTokens,
486
+ avgTokensPerChunk: chunks.length > 0 ? totalTokens / chunks.length : 0,
487
+ strategyDistribution
488
+ };
489
+ }
490
+ /**
491
+ * Debug logging
492
+ */
493
+ log(message) {
494
+ if (this.options.debug) {
495
+ console.log(`[HybridChunker] ${message}`);
496
+ }
497
+ }
498
+ };
499
+ function createHybridChunker(options) {
500
+ return new HybridChunker(options);
501
+ }
502
+
503
+ // src/parser/ChunkDetector.ts
504
+ var ChunkDetector = class {
505
+ /**
506
+ * Detects chunks in the source code based on top-level keywords
507
+ *
508
+ * @deprecated Use detectHybrid() for better performance with multi-strategy chunking
509
+ */
510
+ static detect(source) {
511
+ const lines = source.split(/\r?\n/);
512
+ const chunks = [];
513
+ let currentChunk = null;
514
+ let braceDepth = 0;
515
+ for (let i = 0; i < lines.length; i++) {
516
+ const line = lines[i];
517
+ const trimmed = line.trim();
518
+ if (!currentChunk && (!trimmed || trimmed.startsWith("//"))) {
519
+ continue;
520
+ }
521
+ if (!currentChunk) {
522
+ const orbMatch = trimmed.match(/^orb\s+([a-zA-Z0-9_#"]+)/);
523
+ const templateMatch = trimmed.match(/^template\s+"([^"]+)"/);
524
+ const envMatch = trimmed.startsWith("environment");
525
+ const logicMatch = trimmed.startsWith("logic");
526
+ const directiveMatch = trimmed.startsWith("@");
527
+ if (orbMatch || templateMatch || envMatch || logicMatch || directiveMatch) {
528
+ currentChunk = {
529
+ startLine: i + 1,
530
+ content: line
531
+ };
532
+ if (orbMatch) {
533
+ currentChunk.type = "orb";
534
+ currentChunk.name = orbMatch[1].replace(/[#"]/g, "");
535
+ currentChunk.id = `orb:${currentChunk.name}`;
536
+ } else if (templateMatch) {
537
+ currentChunk.type = "template";
538
+ currentChunk.name = templateMatch[1];
539
+ currentChunk.id = `template:${currentChunk.name}`;
540
+ } else if (envMatch) {
541
+ currentChunk.type = "environment";
542
+ currentChunk.id = `environment:${i + 1}`;
543
+ } else if (logicMatch) {
544
+ currentChunk.type = "logic";
545
+ currentChunk.id = `logic:${i + 1}`;
546
+ } else if (directiveMatch) {
547
+ currentChunk.type = "directive";
548
+ if (!trimmed.includes("{")) {
549
+ currentChunk.endLine = i + 1;
550
+ currentChunk.id = `directive:${i + 1}`;
551
+ chunks.push(currentChunk);
552
+ currentChunk = null;
553
+ continue;
554
+ }
555
+ currentChunk.id = `directive:${i + 1}`;
556
+ }
557
+ }
558
+ } else {
559
+ currentChunk.content += "\n" + line;
560
+ }
561
+ if (currentChunk) {
562
+ for (const char of line) {
563
+ if (char === "{") braceDepth++;
564
+ if (char === "}") braceDepth--;
565
+ }
566
+ if (braceDepth === 0) {
567
+ currentChunk.endLine = i + 1;
568
+ chunks.push(currentChunk);
569
+ currentChunk = null;
570
+ }
571
+ }
572
+ }
573
+ if (currentChunk) {
574
+ currentChunk.endLine = lines.length;
575
+ chunks.push(currentChunk);
576
+ }
577
+ return chunks;
578
+ }
579
+ /**
580
+ * Detect chunks using HybridChunker (structure-based + semantic + fixed-size)
581
+ *
582
+ * Routes .hs/.hsplus files to structure-based chunking for better performance.
583
+ * This method provides 20-30% better parsing speed by using AST-aware boundaries.
584
+ *
585
+ * @param source - Source code content
586
+ * @param filePath - File path for type detection (defaults to .hsplus)
587
+ * @param options - Chunking options
588
+ */
589
+ static detectHybrid(source, filePath = "file.hsplus", options) {
590
+ const hybridChunker = createHybridChunker(options);
591
+ const chunks = hybridChunker.chunk(source, filePath);
592
+ return chunks.map((chunk) => ({
593
+ id: chunk.id,
594
+ type: this.mapChunkType(chunk.type),
595
+ name: chunk.name,
596
+ startLine: chunk.startLine,
597
+ endLine: chunk.endLine,
598
+ content: chunk.content,
599
+ tokens: chunk.tokens,
600
+ strategy: chunk.strategy,
601
+ metadata: chunk.metadata
602
+ }));
603
+ }
604
+ /**
605
+ * Map HybridChunker types to ChunkDetector types
606
+ */
607
+ static mapChunkType(hybridType) {
608
+ if (hybridType.includes("class")) return "template";
609
+ if (hybridType.includes("function")) return "logic";
610
+ return "unknown";
611
+ }
612
+ };
613
+ var ParseCache = class {
614
+ constructor(maxEntries = 500) {
615
+ this.cache = /* @__PURE__ */ new Map();
616
+ this.evictionCount = 0;
617
+ /** Monotonically increasing counter for reliable LRU ordering */
618
+ this.clock = 0;
619
+ this.maxEntries = maxEntries;
620
+ }
621
+ /**
622
+ * Generates a hash for the chunk content
623
+ */
624
+ static hash(content) {
625
+ return crypto__namespace.createHash("sha256").update(content).digest("hex");
626
+ }
627
+ /**
628
+ * Retrieves a cached node if the hash matches
629
+ */
630
+ get(id, currentHash) {
631
+ const cached = this.cache.get(id);
632
+ if (cached && cached.hash === currentHash) {
633
+ cached.lastUsed = ++this.clock;
634
+ return cached.node;
635
+ }
636
+ return null;
637
+ }
638
+ /**
639
+ * Stores a node in the cache
640
+ */
641
+ set(id, hash, node) {
642
+ if (this.cache.size >= this.maxEntries) {
643
+ this.evictOldest();
644
+ }
645
+ this.cache.set(id, {
646
+ id,
647
+ hash,
648
+ node,
649
+ lastUsed: ++this.clock
650
+ });
651
+ }
652
+ /**
653
+ * Clears the entire cache
654
+ */
655
+ clear() {
656
+ this.cache.clear();
657
+ }
658
+ /**
659
+ * Returns cache statistics: current size, total evictions, and capacity.
660
+ */
661
+ getStats() {
662
+ return {
663
+ size: this.cache.size,
664
+ evictions: this.evictionCount,
665
+ maxEntries: this.maxEntries
666
+ };
667
+ }
668
+ evictOldest() {
669
+ let oldestId = null;
670
+ let oldestTime = Infinity;
671
+ for (const [id, entry] of this.cache.entries()) {
672
+ if (entry.lastUsed < oldestTime) {
673
+ oldestTime = entry.lastUsed;
674
+ oldestId = id;
675
+ }
676
+ }
677
+ if (oldestId) {
678
+ this.cache.delete(oldestId);
679
+ this.evictionCount++;
680
+ }
681
+ }
682
+ };
683
+ var globalParseCache = new ParseCache();
684
+
685
+ // src/parser/IncrementalParser.ts
686
+ var ChunkBasedIncrementalParser = class {
687
+ constructor(cache = globalParseCache) {
688
+ this.lastSource = "";
689
+ this.lastChunks = /* @__PURE__ */ new Map();
690
+ this.cache = cache;
691
+ this.parser = new HoloScriptPlusParser({
692
+ enableVRTraits: true,
693
+ enableTypeScriptImports: true,
694
+ strict: false
695
+ });
696
+ }
697
+ /**
698
+ * Parse source with incremental caching
699
+ */
700
+ parse(source) {
701
+ const startTime = Date.now();
702
+ let cached = 0;
703
+ let parsed = 0;
704
+ const changedChunks = [];
705
+ const currentChunks = this.detectChunks(source);
706
+ const chunkMap = new Map(currentChunks.map((c) => [c.id, c]));
707
+ const changedIds = this.identifyChangedChunks(currentChunks);
708
+ changedChunks.push(...changedIds);
709
+ const dependentIds = this.findDependents(changedIds, currentChunks);
710
+ const toParseIds = /* @__PURE__ */ new Set([...changedIds, ...dependentIds]);
711
+ const chunkNodes = /* @__PURE__ */ new Map();
712
+ for (const chunk of currentChunks) {
713
+ const hash = ParseCache.hash(chunk.content);
714
+ if (toParseIds.has(chunk.id)) {
715
+ const chunkNode = this.parseChunk(chunk);
716
+ if (chunkNode) {
717
+ chunkNodes.set(chunk.id, chunkNode);
718
+ this.cache.set(chunk.id, hash, chunkNode);
719
+ parsed++;
720
+ }
721
+ } else {
722
+ const cached_node = this.cache.get(chunk.id, hash);
723
+ if (cached_node) {
724
+ chunkNodes.set(chunk.id, cached_node);
725
+ cached++;
726
+ } else {
727
+ const chunkNode = this.parseChunk(chunk);
728
+ if (chunkNode) {
729
+ chunkNodes.set(chunk.id, chunkNode);
730
+ this.cache.set(chunk.id, hash, chunkNode);
731
+ parsed++;
732
+ }
733
+ }
734
+ }
735
+ }
736
+ const ast = this.assembleAST(chunkNodes, currentChunks);
737
+ this.lastSource = source;
738
+ this.lastChunks = chunkMap;
739
+ const duration = Date.now() - startTime;
740
+ return {
741
+ ast,
742
+ cached,
743
+ parsed,
744
+ duration,
745
+ changedChunks
746
+ };
747
+ }
748
+ /**
749
+ * Detects top-level chunks in the source
750
+ */
751
+ detectChunks(source) {
752
+ return ChunkDetector.detect(source);
753
+ }
754
+ /**
755
+ * Identifies which chunks have changed by comparing hashes
756
+ */
757
+ identifyChangedChunks(currentChunks) {
758
+ const changed = [];
759
+ for (const chunk of currentChunks) {
760
+ const hash = ParseCache.hash(chunk.content);
761
+ const lastChunk = this.lastChunks.get(chunk.id);
762
+ if (!lastChunk) {
763
+ changed.push(chunk.id);
764
+ } else {
765
+ const lastHash = ParseCache.hash(lastChunk.content);
766
+ if (hash !== lastHash) {
767
+ changed.push(chunk.id);
768
+ }
769
+ }
770
+ }
771
+ for (const [id, _lastChunk] of this.lastChunks.entries()) {
772
+ const currentChunk = this.detectChunks(this.lastSource).find((c) => c.id === id);
773
+ if (!currentChunk) {
774
+ changed.push(id);
775
+ }
776
+ }
777
+ return changed;
778
+ }
779
+ /**
780
+ * Finds chunks that depend on the changed ones
781
+ */
782
+ findDependents(changedIds, chunks) {
783
+ const dependents = /* @__PURE__ */ new Set();
784
+ const changeSet = new Set(changedIds);
785
+ const references = /* @__PURE__ */ new Map();
786
+ for (const chunk of chunks) {
787
+ const refs = this.extractReferences(chunk.content);
788
+ if (refs.size > 0) {
789
+ references.set(chunk.id, refs);
790
+ }
791
+ }
792
+ for (const [chunkId, refs] of references.entries()) {
793
+ if (!changeSet.has(chunkId)) {
794
+ for (const ref of refs) {
795
+ if (changeSet.has(ref) || dependents.has(ref)) {
796
+ dependents.add(chunkId);
797
+ break;
798
+ }
799
+ }
800
+ }
801
+ }
802
+ return Array.from(dependents);
803
+ }
804
+ /**
805
+ * Extracts referenced identifiers from a chunk (templates, orbs, logic)
806
+ */
807
+ extractReferences(content) {
808
+ const refs = /* @__PURE__ */ new Set();
809
+ const templateRefs = content.match(/using\s+"([^"]+)"/g);
810
+ if (templateRefs) {
811
+ templateRefs.forEach((ref) => {
812
+ const name = ref.match(/"([^"]+)"/)[1];
813
+ refs.add(`template:${name}`);
814
+ });
815
+ }
816
+ const spreadRefs = content.match(/\.\.\.\s*([a-zA-Z0-9_]+)/g);
817
+ if (spreadRefs) {
818
+ spreadRefs.forEach((ref) => {
819
+ const name = ref.replace(/\.\.\./, "").trim();
820
+ refs.add(`identifier:${name}`);
821
+ });
822
+ }
823
+ const compRefs = content.match(/@composition\s+"([^"]+)"/g);
824
+ if (compRefs) {
825
+ compRefs.forEach((ref) => {
826
+ const name = ref.match(/"([^"]+)"/)[1];
827
+ refs.add(`composition:${name}`);
828
+ });
829
+ }
830
+ return refs;
831
+ }
832
+ /**
833
+ * Parses a single chunk
834
+ */
835
+ parseChunk(chunk) {
836
+ try {
837
+ const content = this.wrapChunkForParsing(chunk);
838
+ const result = this.parser.parse(content);
839
+ if (result.success && result.ast) {
840
+ return result.ast;
841
+ }
842
+ return null;
843
+ } catch (error) {
844
+ console.warn(`Failed to parse chunk ${chunk.id}:`, error);
845
+ return null;
846
+ }
847
+ }
848
+ /**
849
+ * Wraps chunk content to make it parseable in isolation
850
+ */
851
+ wrapChunkForParsing(chunk) {
852
+ return chunk.content;
853
+ }
854
+ /**
855
+ * Assembles final AST from parsed chunks
856
+ */
857
+ assembleAST(chunkNodes, chunks) {
858
+ const children = [];
859
+ for (const chunk of chunks) {
860
+ const node = chunkNodes.get(chunk.id);
861
+ if (node) {
862
+ children.push(node);
863
+ }
864
+ }
865
+ if (children.length === 1) {
866
+ return children[0];
867
+ }
868
+ return {
869
+ type: "fragment",
870
+ children,
871
+ properties: {},
872
+ directives: [],
873
+ traits: /* @__PURE__ */ new Map(),
874
+ loc: { start: { line: 1, column: 0 }, end: { line: 1, column: 0 } }
875
+ };
876
+ }
877
+ /**
878
+ * Clears the internal cache
879
+ */
880
+ clearCache() {
881
+ this.cache.clear();
882
+ this.lastChunks.clear();
883
+ }
884
+ /**
885
+ * Gets cache statistics
886
+ */
887
+ getCacheStats() {
888
+ return {
889
+ size: this.lastChunks.size,
890
+ maxSize: 500
891
+ };
892
+ }
893
+ };
894
+ function parseIncrementalChunks(source, cache = globalParseCache) {
895
+ const parser = new ChunkBasedIncrementalParser(cache);
896
+ return parser.parse(source);
897
+ }
898
+
899
+ // src/parser/RichErrors.ts
900
+ var HSPLUS_ERROR_CODES = {
901
+ // Syntax Errors (HSP001-HSP099)
902
+ HSP001: "Unexpected token",
903
+ HSP002: "Expected identifier",
904
+ HSP003: "Expected keyword",
905
+ HSP004: "Unclosed brace - missing }",
906
+ HSP005: "Unclosed bracket - missing ]",
907
+ HSP006: "Unclosed parenthesis - missing )",
908
+ HSP007: "Unclosed string literal",
909
+ HSP008: "Invalid number format",
910
+ HSP009: "Missing colon after property name",
911
+ HSP010: "Missing value after colon",
912
+ // Structure Errors (HSP100-HSP199)
913
+ HSP100: "Invalid composition structure",
914
+ HSP101: "Invalid object definition",
915
+ HSP102: "Invalid template definition",
916
+ HSP103: "Invalid spatial_group definition",
917
+ HSP104: "Invalid environment block",
918
+ HSP105: "Invalid state block",
919
+ HSP106: "Invalid logic block",
920
+ HSP107: "Duplicate identifier",
921
+ HSP108: "Missing required property",
922
+ // Trait Errors (HSP200-HSP299)
923
+ HSP200: "Unknown trait",
924
+ HSP201: "Invalid trait syntax",
925
+ HSP202: "Missing trait argument",
926
+ HSP203: "Invalid trait argument type",
927
+ HSP204: "Trait not allowed in this context",
928
+ HSP205: "Duplicate trait",
929
+ // Expression Errors (HSP300-HSP399)
930
+ HSP300: "Invalid expression",
931
+ HSP301: "Undefined variable",
932
+ HSP302: "Invalid operator",
933
+ HSP303: "Type mismatch",
934
+ HSP304: "Invalid function call",
935
+ HSP305: "Missing function argument",
936
+ // Import/Module Errors (HSP400-HSP499)
937
+ HSP400: "Invalid import statement",
938
+ HSP401: "Module not found",
939
+ HSP402: "Circular import detected",
940
+ // Limit Errors (HSP900-HSP999)
941
+ HSP900: "Maximum nesting depth exceeded",
942
+ HSP901: "Maximum array length exceeded",
943
+ HSP902: "Maximum string length exceeded"
944
+ };
945
+ function levenshteinDistance(a, b) {
946
+ const matrix = [];
947
+ for (let i = 0; i <= b.length; i++) {
948
+ matrix[i] = [i];
949
+ }
950
+ for (let j = 0; j <= a.length; j++) {
951
+ matrix[0][j] = j;
952
+ }
953
+ for (let i = 1; i <= b.length; i++) {
954
+ for (let j = 1; j <= a.length; j++) {
955
+ if (b.charAt(i - 1) === a.charAt(j - 1)) {
956
+ matrix[i][j] = matrix[i - 1][j - 1];
957
+ } else {
958
+ matrix[i][j] = Math.min(
959
+ matrix[i - 1][j - 1] + 1,
960
+ // substitution
961
+ matrix[i][j - 1] + 1,
962
+ // insertion
963
+ matrix[i - 1][j] + 1
964
+ // deletion
965
+ );
966
+ }
967
+ }
968
+ }
969
+ return matrix[b.length][a.length];
970
+ }
971
+ function similarity(a, b) {
972
+ const aLower = a.toLowerCase();
973
+ const bLower = b.toLowerCase();
974
+ if (aLower === bLower) return 1;
975
+ if (bLower.startsWith(aLower) || aLower.startsWith(bLower)) {
976
+ return 0.9;
977
+ }
978
+ const maxLen = Math.max(a.length, b.length);
979
+ if (maxLen === 0) return 1;
980
+ const distance = levenshteinDistance(aLower, bLower);
981
+ return 1 - distance / maxLen;
982
+ }
983
+ function findSimilarTrait(input, threshold = 0.5) {
984
+ let bestMatch;
985
+ let bestScore = threshold;
986
+ for (const trait of chunkWRLUBRKS_cjs.VR_TRAITS) {
987
+ const score = similarity(input, trait);
988
+ if (score > bestScore) {
989
+ bestScore = score;
990
+ bestMatch = trait;
991
+ }
992
+ }
993
+ return bestMatch;
994
+ }
995
+ function findSimilarKeyword(input, threshold = 0.5) {
996
+ const keywords = [
997
+ "composition",
998
+ "object",
999
+ "template",
1000
+ "spatial_group",
1001
+ "environment",
1002
+ "state",
1003
+ "logic",
1004
+ "on_click",
1005
+ "on_hover",
1006
+ "on_enter",
1007
+ "on_exit",
1008
+ "position",
1009
+ "rotation",
1010
+ "scale",
1011
+ "color",
1012
+ "model",
1013
+ "geometry",
1014
+ "visible",
1015
+ "opacity",
1016
+ "material",
1017
+ "physics",
1018
+ "audio",
1019
+ "animation",
1020
+ "true",
1021
+ "false",
1022
+ "null",
1023
+ "if",
1024
+ "else",
1025
+ "for",
1026
+ "while",
1027
+ "function",
1028
+ "let",
1029
+ "const",
1030
+ "return",
1031
+ "import",
1032
+ "from",
1033
+ "using",
1034
+ "spawn",
1035
+ "emit"
1036
+ ];
1037
+ let bestMatch;
1038
+ let bestScore = threshold;
1039
+ for (const keyword of keywords) {
1040
+ const score = similarity(input, keyword);
1041
+ if (score > bestScore) {
1042
+ bestScore = score;
1043
+ bestMatch = keyword;
1044
+ }
1045
+ }
1046
+ return bestMatch;
1047
+ }
1048
+ function getSourceContext(source, line, column, contextLines = 2) {
1049
+ const lines = source.split("\n");
1050
+ const result = [];
1051
+ const startLine = Math.max(1, line - contextLines);
1052
+ const endLine = Math.min(lines.length, line + contextLines);
1053
+ const maxLineNum = endLine;
1054
+ const padding = String(maxLineNum).length;
1055
+ for (let i = startLine; i <= endLine; i++) {
1056
+ const lineContent = lines[i - 1] || "";
1057
+ const lineNum = String(i).padStart(padding, " ");
1058
+ const prefix = i === line ? ">" : " ";
1059
+ result.push(`${prefix} ${lineNum} | ${lineContent}`);
1060
+ if (i === line) {
1061
+ const indicator = " ".repeat(padding + 4 + Math.max(0, column - 1)) + "^";
1062
+ result.push(indicator);
1063
+ }
1064
+ }
1065
+ return result.join("\n");
1066
+ }
1067
+ function createRichError(code, message, line, column, options = {}) {
1068
+ const { source, suggestion, severity = "error", endLine, endColumn } = options;
1069
+ return {
1070
+ code,
1071
+ message: `${code}: ${message}`,
1072
+ line,
1073
+ column,
1074
+ endLine,
1075
+ endColumn,
1076
+ context: source ? getSourceContext(source, line, column) : void 0,
1077
+ suggestion,
1078
+ severity
1079
+ };
1080
+ }
1081
+ function createTraitError(traitName, line, column, source) {
1082
+ const similar = findSimilarTrait(traitName);
1083
+ const suggestion = similar ? `Did you mean '@${similar}'?` : void 0;
1084
+ return createRichError("HSP200", `Unknown trait '@${traitName}'`, line, column, {
1085
+ source,
1086
+ suggestion
1087
+ });
1088
+ }
1089
+ function createKeywordError(found, expected, line, column, source) {
1090
+ const similar = findSimilarKeyword(found);
1091
+ const suggestion = similar ? `Did you mean '${similar}'?` : `Expected '${expected}'`;
1092
+ return createRichError("HSP003", `Expected '${expected}' but found '${found}'`, line, column, {
1093
+ source,
1094
+ suggestion
1095
+ });
1096
+ }
1097
+ function formatRichError(error) {
1098
+ const lines = [];
1099
+ const icon = error.severity === "error" ? "\u274C" : error.severity === "warning" ? "\u26A0\uFE0F" : "\u2139\uFE0F";
1100
+ lines.push(`${icon} ${error.message}`);
1101
+ lines.push(` at line ${error.line}, column ${error.column}`);
1102
+ if (error.context) {
1103
+ lines.push("");
1104
+ lines.push(error.context);
1105
+ }
1106
+ if (error.suggestion) {
1107
+ lines.push("");
1108
+ lines.push(`\u{1F4A1} ${error.suggestion}`);
1109
+ }
1110
+ lines.push("");
1111
+ lines.push(`\u{1F4D6} See: https://holoscript.net/errors/${error.code}`);
1112
+ return lines.join("\n");
1113
+ }
1114
+ function formatRichErrors(errors) {
1115
+ if (errors.length === 0) {
1116
+ return "\u2705 No errors found";
1117
+ }
1118
+ const lines = [];
1119
+ const errorCount = errors.filter((e) => e.severity === "error").length;
1120
+ const warningCount = errors.filter((e) => e.severity === "warning").length;
1121
+ lines.push(`Found ${errorCount} error(s) and ${warningCount} warning(s):`);
1122
+ lines.push("");
1123
+ const displayErrors = errors.slice(0, 10);
1124
+ for (let i = 0; i < displayErrors.length; i++) {
1125
+ lines.push(`[${i + 1}/${errors.length}] \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500`);
1126
+ lines.push(formatRichError(displayErrors[i]));
1127
+ lines.push("");
1128
+ }
1129
+ if (errors.length > 10) {
1130
+ lines.push(`... and ${errors.length - 10} more errors`);
1131
+ }
1132
+ return lines.join("\n");
1133
+ }
1134
+ function getErrorCodeDocumentation() {
1135
+ const docs = [];
1136
+ for (const [code, description] of Object.entries(HSPLUS_ERROR_CODES)) {
1137
+ let category = "General";
1138
+ const num = parseInt(code.replace("HSP", ""), 10);
1139
+ if (num < 100) category = "Syntax";
1140
+ else if (num < 200) category = "Structure";
1141
+ else if (num < 300) category = "Traits";
1142
+ else if (num < 400) category = "Expressions";
1143
+ else if (num < 500) category = "Imports";
1144
+ else if (num >= 900) category = "Limits";
1145
+ docs.push({ code, description, category });
1146
+ }
1147
+ return docs;
1148
+ }
1149
+
1150
+ // src/parser/HoloScriptPlusParser.ts
1151
+ var Lexer = class {
1152
+ constructor(source) {
1153
+ this.pos = 0;
1154
+ this.line = 1;
1155
+ this.column = 1;
1156
+ this.indentStack = [0];
1157
+ this.tokens = [];
1158
+ this.pendingDedents = 0;
1159
+ this.source = source;
1160
+ }
1161
+ tokenize() {
1162
+ while (this.pos < this.source.length) {
1163
+ while (this.pendingDedents > 0) {
1164
+ this.tokens.push(this.createToken("DEDENT", ""));
1165
+ this.pendingDedents--;
1166
+ }
1167
+ const char = this.source[this.pos];
1168
+ if (char === " " || char === " ") {
1169
+ if (this.column === 1) {
1170
+ this.handleIndentation();
1171
+ } else {
1172
+ this.advance();
1173
+ }
1174
+ continue;
1175
+ }
1176
+ if (char === "/" && this.peek(1) === "/") {
1177
+ this.skipLineComment();
1178
+ continue;
1179
+ }
1180
+ if (char === "\n") {
1181
+ this.advance();
1182
+ this.tokens.push(this.createToken("NEWLINE", "\n"));
1183
+ this.line++;
1184
+ this.column = 1;
1185
+ continue;
1186
+ }
1187
+ if (char === "\r") {
1188
+ const startOff = this.pos;
1189
+ this.advance();
1190
+ if (this.peek() === "\n") {
1191
+ this.advance();
1192
+ }
1193
+ const token = this.createToken("NEWLINE", "\n");
1194
+ token.offset = startOff;
1195
+ this.tokens.push(token);
1196
+ this.line++;
1197
+ this.column = 1;
1198
+ continue;
1199
+ }
1200
+ if (char === "{") {
1201
+ this.advance();
1202
+ this.tokens.push(this.createToken("LBRACE", "{"));
1203
+ continue;
1204
+ }
1205
+ if (char === "}") {
1206
+ this.advance();
1207
+ this.tokens.push(this.createToken("RBRACE", "}"));
1208
+ continue;
1209
+ }
1210
+ if (char === "[") {
1211
+ this.advance();
1212
+ this.tokens.push(this.createToken("LBRACKET", "["));
1213
+ continue;
1214
+ }
1215
+ if (char === "]") {
1216
+ this.advance();
1217
+ this.tokens.push(this.createToken("RBRACKET", "]"));
1218
+ continue;
1219
+ }
1220
+ if (char === "(") {
1221
+ this.advance();
1222
+ this.tokens.push(this.createToken("LPAREN", "("));
1223
+ continue;
1224
+ }
1225
+ if (char === ")") {
1226
+ this.advance();
1227
+ this.tokens.push(this.createToken("RPAREN", ")"));
1228
+ continue;
1229
+ }
1230
+ if (char === ":") {
1231
+ this.advance();
1232
+ this.tokens.push(this.createToken("COLON", ":"));
1233
+ continue;
1234
+ }
1235
+ if (char === ",") {
1236
+ this.advance();
1237
+ this.tokens.push(this.createToken("COMMA", ","));
1238
+ continue;
1239
+ }
1240
+ if (char === "@") {
1241
+ this.advance();
1242
+ this.tokens.push(this.createToken("AT", "@"));
1243
+ continue;
1244
+ }
1245
+ if (char === "#") {
1246
+ this.advance();
1247
+ this.tokens.push(this.createToken("HASH", "#"));
1248
+ continue;
1249
+ }
1250
+ if (char === ".") {
1251
+ if (this.peek(1) === "." && this.peek(2) === ".") {
1252
+ const startCol = this.column;
1253
+ this.advance();
1254
+ this.advance();
1255
+ this.advance();
1256
+ this.tokens.push(this.createToken("SPREAD", "..."));
1257
+ this.tokens[this.tokens.length - 1].column = startCol;
1258
+ continue;
1259
+ }
1260
+ this.advance();
1261
+ this.tokens.push(this.createToken("DOT", "."));
1262
+ continue;
1263
+ }
1264
+ if (char === "+") {
1265
+ this.advance();
1266
+ this.tokens.push(this.createToken("PLUS", "+"));
1267
+ continue;
1268
+ }
1269
+ if (char === "-") {
1270
+ if (this.peek(1) === ">") {
1271
+ const startCol = this.column;
1272
+ this.advance();
1273
+ this.advance();
1274
+ this.tokens.push(this.createToken("ARROW", "->"));
1275
+ this.tokens[this.tokens.length - 1].column = startCol;
1276
+ continue;
1277
+ }
1278
+ this.advance();
1279
+ this.tokens.push(this.createToken("MINUS", "-"));
1280
+ continue;
1281
+ }
1282
+ if (char === "*") {
1283
+ this.advance();
1284
+ this.tokens.push(this.createToken("ASTERISK", "*"));
1285
+ continue;
1286
+ }
1287
+ if (char === "/") {
1288
+ if (this.peek(1) === "*") {
1289
+ this.skipBlockComment();
1290
+ continue;
1291
+ }
1292
+ if (this.peek(1) === "/") {
1293
+ this.skipLineComment();
1294
+ continue;
1295
+ }
1296
+ this.advance();
1297
+ this.tokens.push(this.createToken("SLASH", "/"));
1298
+ continue;
1299
+ }
1300
+ if (char === "%") {
1301
+ this.advance();
1302
+ this.tokens.push(this.createToken("PERCENT", "%"));
1303
+ continue;
1304
+ }
1305
+ if (char === "!") {
1306
+ if (this.peek(1) === "=") {
1307
+ const startCol = this.column;
1308
+ const startOff = this.pos;
1309
+ this.advance();
1310
+ this.advance();
1311
+ this.tokens.push(this.createToken("NOT_EQUALS", "!="));
1312
+ this.tokens[this.tokens.length - 1].column = startCol;
1313
+ this.tokens[this.tokens.length - 1].offset = startOff;
1314
+ continue;
1315
+ }
1316
+ this.advance();
1317
+ this.tokens.push(this.createToken("EXCLAMATION", "!"));
1318
+ continue;
1319
+ }
1320
+ if (char === "=") {
1321
+ if (this.peek(1) === ">") {
1322
+ const startCol = this.column;
1323
+ const startOff = this.pos;
1324
+ this.advance();
1325
+ this.advance();
1326
+ this.tokens.push(this.createToken("ARROW", "=>"));
1327
+ this.tokens[this.tokens.length - 1].column = startCol;
1328
+ this.tokens[this.tokens.length - 1].offset = startOff;
1329
+ continue;
1330
+ }
1331
+ if (this.peek(1) === "=") {
1332
+ const startCol = this.column;
1333
+ const startOff = this.pos;
1334
+ this.advance();
1335
+ this.advance();
1336
+ this.tokens.push(this.createToken("DOUBLE_EQUALS", "=="));
1337
+ this.tokens[this.tokens.length - 1].column = startCol;
1338
+ this.tokens[this.tokens.length - 1].offset = startOff;
1339
+ continue;
1340
+ }
1341
+ this.advance();
1342
+ this.tokens.push(this.createToken("EQUALS", "="));
1343
+ continue;
1344
+ }
1345
+ if (char === "<") {
1346
+ if (this.peek(1) === "=") {
1347
+ const startCol = this.column;
1348
+ const startOff = this.pos;
1349
+ this.advance();
1350
+ this.advance();
1351
+ this.tokens.push(this.createToken("LESS_EQUAL", "<="));
1352
+ this.tokens[this.tokens.length - 1].column = startCol;
1353
+ this.tokens[this.tokens.length - 1].offset = startOff;
1354
+ continue;
1355
+ }
1356
+ this.advance();
1357
+ this.tokens.push(this.createToken("LESS_THAN", "<"));
1358
+ continue;
1359
+ }
1360
+ if (char === ">") {
1361
+ if (this.peek(1) === "=") {
1362
+ const startCol = this.column;
1363
+ const startOff = this.pos;
1364
+ this.advance();
1365
+ this.advance();
1366
+ this.tokens.push(this.createToken("GREATER_EQUAL", ">="));
1367
+ this.tokens[this.tokens.length - 1].column = startCol;
1368
+ this.tokens[this.tokens.length - 1].offset = startOff;
1369
+ continue;
1370
+ }
1371
+ this.advance();
1372
+ this.tokens.push(this.createToken("GREATER_THAN", ">"));
1373
+ continue;
1374
+ }
1375
+ if (char === "-") {
1376
+ if (this.peek(1) === ">") {
1377
+ const startCol = this.column;
1378
+ this.advance();
1379
+ this.advance();
1380
+ this.tokens.push(this.createToken("ARROW", "->"));
1381
+ this.tokens[this.tokens.length - 1].column = startCol;
1382
+ continue;
1383
+ }
1384
+ }
1385
+ if (char === "&") {
1386
+ if (this.peek(1) === "&") {
1387
+ const startCol = this.column;
1388
+ const startOff = this.pos;
1389
+ this.advance();
1390
+ this.advance();
1391
+ this.tokens.push(this.createToken("AND", "&&"));
1392
+ this.tokens[this.tokens.length - 1].column = startCol;
1393
+ this.tokens[this.tokens.length - 1].offset = startOff;
1394
+ continue;
1395
+ }
1396
+ this.advance();
1397
+ continue;
1398
+ }
1399
+ if (char === "|") {
1400
+ if (this.peek(1) === "|") {
1401
+ const startCol = this.column;
1402
+ const startOff = this.pos;
1403
+ this.advance();
1404
+ this.advance();
1405
+ this.tokens.push(this.createToken("OR", "||"));
1406
+ this.tokens[this.tokens.length - 1].column = startCol;
1407
+ this.tokens[this.tokens.length - 1].offset = startOff;
1408
+ continue;
1409
+ }
1410
+ this.advance();
1411
+ this.tokens.push(this.createToken("PIPE", "|"));
1412
+ continue;
1413
+ }
1414
+ if (char === '"' || char === "'") {
1415
+ this.tokens.push(this.readString(char));
1416
+ continue;
1417
+ }
1418
+ if (this.isDigit(char) || char === "-" && this.isDigit(this.peek(1))) {
1419
+ this.tokens.push(this.readNumber());
1420
+ continue;
1421
+ }
1422
+ if (char === "?") {
1423
+ if (this.peek(1) === "?") {
1424
+ if (this.peek(2) === "=") {
1425
+ const startCol2 = this.column;
1426
+ const startOff2 = this.pos;
1427
+ this.advance();
1428
+ this.advance();
1429
+ this.advance();
1430
+ this.tokens.push(this.createToken("NULL_COALESCE_ASSIGN", "??="));
1431
+ this.tokens[this.tokens.length - 1].column = startCol2;
1432
+ this.tokens[this.tokens.length - 1].offset = startOff2;
1433
+ continue;
1434
+ }
1435
+ const startCol = this.column;
1436
+ const startOff = this.pos;
1437
+ this.advance();
1438
+ this.advance();
1439
+ this.tokens.push(this.createToken("NULL_COALESCE", "??"));
1440
+ this.tokens[this.tokens.length - 1].column = startCol;
1441
+ this.tokens[this.tokens.length - 1].offset = startOff;
1442
+ continue;
1443
+ }
1444
+ if (this.peek(1) === ".") {
1445
+ const startCol = this.column;
1446
+ const startOff = this.pos;
1447
+ this.advance();
1448
+ this.advance();
1449
+ this.tokens.push(this.createToken("OPTIONAL_DOT", "?."));
1450
+ this.tokens[this.tokens.length - 1].column = startCol;
1451
+ this.tokens[this.tokens.length - 1].offset = startOff;
1452
+ continue;
1453
+ }
1454
+ this.advance();
1455
+ this.tokens.push(this.createToken("QUESTION", "?"));
1456
+ continue;
1457
+ }
1458
+ if (char === "`") {
1459
+ this.tokens.push(this.readTemplateString());
1460
+ continue;
1461
+ }
1462
+ if (this.isIdentifierStart(char)) {
1463
+ this.tokens.push(this.readIdentifier());
1464
+ continue;
1465
+ }
1466
+ this.advance();
1467
+ }
1468
+ while (this.indentStack.length > 1) {
1469
+ this.tokens.push(this.createToken("DEDENT", ""));
1470
+ this.indentStack.pop();
1471
+ }
1472
+ this.tokens.push(this.createToken("EOF", ""));
1473
+ return this.tokens;
1474
+ }
1475
+ advance() {
1476
+ const char = this.source[this.pos];
1477
+ this.pos++;
1478
+ this.column++;
1479
+ return char;
1480
+ }
1481
+ peek(offset = 0) {
1482
+ const pos = this.pos + offset;
1483
+ return pos < this.source.length ? this.source[pos] : "";
1484
+ }
1485
+ createToken(type, value) {
1486
+ const token = {
1487
+ type,
1488
+ value,
1489
+ line: this.line,
1490
+ column: this.column - (value.length || 0),
1491
+ offset: this.pos - (value.length || 0)
1492
+ };
1493
+ return token;
1494
+ }
1495
+ handleIndentation() {
1496
+ let indent = 0;
1497
+ while (this.peek() === " " || this.peek() === " ") {
1498
+ indent += this.peek() === " " ? 4 : 1;
1499
+ this.advance();
1500
+ }
1501
+ if (this.peek() === "\n" || this.peek() === "\r") {
1502
+ return;
1503
+ }
1504
+ const currentIndent = this.indentStack[this.indentStack.length - 1];
1505
+ if (indent > currentIndent) {
1506
+ this.indentStack.push(indent);
1507
+ this.tokens.push(this.createToken("INDENT", ""));
1508
+ } else if (indent < currentIndent) {
1509
+ while (this.indentStack.length > 1 && indent < this.indentStack[this.indentStack.length - 1]) {
1510
+ this.indentStack.pop();
1511
+ this.pendingDedents++;
1512
+ }
1513
+ }
1514
+ }
1515
+ skipLineComment() {
1516
+ while (this.peek() !== "\n" && this.pos < this.source.length) {
1517
+ this.advance();
1518
+ }
1519
+ }
1520
+ skipBlockComment() {
1521
+ this.advance();
1522
+ this.advance();
1523
+ while (this.pos < this.source.length) {
1524
+ if (this.peek() === "*" && this.peek(1) === "/") {
1525
+ this.advance();
1526
+ this.advance();
1527
+ break;
1528
+ }
1529
+ if (this.peek() === "\n") {
1530
+ this.line++;
1531
+ this.column = 0;
1532
+ }
1533
+ this.advance();
1534
+ }
1535
+ }
1536
+ readString(quote) {
1537
+ const startLine = this.line;
1538
+ const startColumn = this.column;
1539
+ this.advance();
1540
+ let value = "";
1541
+ while (this.peek() !== quote && this.pos < this.source.length) {
1542
+ if (this.peek() === "\\") {
1543
+ this.advance();
1544
+ const escaped = this.advance();
1545
+ switch (escaped) {
1546
+ case "n":
1547
+ value += "\n";
1548
+ break;
1549
+ case "t":
1550
+ value += " ";
1551
+ break;
1552
+ case "r":
1553
+ value += "\r";
1554
+ break;
1555
+ case "\\":
1556
+ value += "\\";
1557
+ break;
1558
+ case '"':
1559
+ value += '"';
1560
+ break;
1561
+ case "'":
1562
+ value += "'";
1563
+ break;
1564
+ default:
1565
+ value += escaped;
1566
+ }
1567
+ } else if (this.peek() === "\n") {
1568
+ this.line++;
1569
+ this.column = 0;
1570
+ value += this.advance();
1571
+ } else {
1572
+ value += this.advance();
1573
+ }
1574
+ }
1575
+ this.advance();
1576
+ const token = {
1577
+ type: "STRING",
1578
+ value,
1579
+ line: startLine,
1580
+ column: startColumn,
1581
+ offset: this.pos - (value.length + 2)
1582
+ // approximation for start of string
1583
+ };
1584
+ return token;
1585
+ }
1586
+ readTemplateString() {
1587
+ const startLine = this.line;
1588
+ const startColumn = this.column;
1589
+ const startOff = this.pos;
1590
+ this.advance();
1591
+ let value = "";
1592
+ let braceDepth = 0;
1593
+ while (this.pos < this.source.length) {
1594
+ const c = this.source[this.pos];
1595
+ if (c === "`" && braceDepth === 0) {
1596
+ this.advance();
1597
+ break;
1598
+ }
1599
+ if (c === "$" && this.peek(1) === "{") {
1600
+ braceDepth++;
1601
+ value += "${";
1602
+ this.advance();
1603
+ this.advance();
1604
+ continue;
1605
+ }
1606
+ if (c === "{" && braceDepth > 0) {
1607
+ braceDepth++;
1608
+ value += c;
1609
+ this.advance();
1610
+ continue;
1611
+ }
1612
+ if (c === "}" && braceDepth > 0) {
1613
+ braceDepth--;
1614
+ value += c;
1615
+ this.advance();
1616
+ continue;
1617
+ }
1618
+ if (c === "\n") {
1619
+ this.line++;
1620
+ this.column = 0;
1621
+ }
1622
+ value += c;
1623
+ this.advance();
1624
+ }
1625
+ return {
1626
+ type: "TEMPLATE_STRING",
1627
+ value,
1628
+ line: startLine,
1629
+ column: startColumn,
1630
+ offset: startOff
1631
+ };
1632
+ }
1633
+ readNumber() {
1634
+ const startColumn = this.column;
1635
+ let value = "";
1636
+ if (this.peek() === "-") {
1637
+ value += this.advance();
1638
+ }
1639
+ while (this.isDigit(this.peek())) {
1640
+ value += this.advance();
1641
+ }
1642
+ if (this.peek() === "." && this.isDigit(this.peek(1))) {
1643
+ value += this.advance();
1644
+ while (this.isDigit(this.peek())) {
1645
+ value += this.advance();
1646
+ }
1647
+ }
1648
+ if (this.peek() === "e" || this.peek() === "E") {
1649
+ value += this.advance();
1650
+ if (this.peek() === "+" || this.peek() === "-") {
1651
+ value += this.advance();
1652
+ }
1653
+ while (this.isDigit(this.peek())) {
1654
+ value += this.advance();
1655
+ }
1656
+ }
1657
+ while (this.isAlpha(this.peek()) || this.peek() === "%") {
1658
+ value += this.advance();
1659
+ }
1660
+ const token = {
1661
+ type: "NUMBER",
1662
+ value,
1663
+ line: this.line,
1664
+ column: startColumn,
1665
+ offset: this.pos - value.length
1666
+ };
1667
+ return token;
1668
+ }
1669
+ readExpression() {
1670
+ const startLine = this.line;
1671
+ const startColumn = this.column;
1672
+ this.advance();
1673
+ this.advance();
1674
+ let value = "";
1675
+ let braceDepth = 1;
1676
+ while (braceDepth > 0 && this.pos < this.source.length) {
1677
+ if (this.peek() === "{") {
1678
+ braceDepth++;
1679
+ } else if (this.peek() === "}") {
1680
+ braceDepth--;
1681
+ if (braceDepth === 0) {
1682
+ break;
1683
+ }
1684
+ }
1685
+ if (this.peek() === "\n") {
1686
+ this.line++;
1687
+ this.column = 0;
1688
+ }
1689
+ value += this.advance();
1690
+ }
1691
+ this.advance();
1692
+ return {
1693
+ type: "EXPRESSION",
1694
+ value: value.trim(),
1695
+ line: startLine,
1696
+ column: startColumn,
1697
+ offset: this.pos - (value.length + 3)
1698
+ // ${...}
1699
+ };
1700
+ }
1701
+ readIdentifier() {
1702
+ const startColumn = this.column;
1703
+ let value = "";
1704
+ while (this.isIdentifierPart(this.peek())) {
1705
+ value += this.advance();
1706
+ }
1707
+ if (value === "true" || value === "false") {
1708
+ return {
1709
+ type: "BOOLEAN",
1710
+ value,
1711
+ line: this.line,
1712
+ column: startColumn,
1713
+ offset: this.pos - value.length
1714
+ };
1715
+ }
1716
+ if (value === "null" || value === "none") {
1717
+ return {
1718
+ type: "NULL",
1719
+ value,
1720
+ line: this.line,
1721
+ column: startColumn,
1722
+ offset: this.pos - value.length
1723
+ };
1724
+ }
1725
+ const token = {
1726
+ type: "IDENTIFIER",
1727
+ value,
1728
+ line: this.line,
1729
+ column: startColumn,
1730
+ offset: this.pos - value.length
1731
+ };
1732
+ switch (value) {
1733
+ case "state_machine":
1734
+ token.type = "STATE_MACHINE";
1735
+ break;
1736
+ case "initial":
1737
+ token.type = "INITIAL";
1738
+ break;
1739
+ case "state":
1740
+ token.type = "STATE";
1741
+ break;
1742
+ case "on_entry":
1743
+ token.type = "ON_ENTRY";
1744
+ break;
1745
+ case "on_exit":
1746
+ token.type = "ON_EXIT";
1747
+ break;
1748
+ case "transition":
1749
+ token.type = "TRANSITION";
1750
+ break;
1751
+ case "match":
1752
+ token.type = "MATCH";
1753
+ break;
1754
+ case "on_error":
1755
+ token.type = "ON_ERROR";
1756
+ break;
1757
+ case "assert":
1758
+ token.type = "ASSERT";
1759
+ break;
1760
+ case "_":
1761
+ token.type = "UNDERSCORE";
1762
+ break;
1763
+ }
1764
+ return token;
1765
+ }
1766
+ isDigit(char) {
1767
+ return char >= "0" && char <= "9";
1768
+ }
1769
+ isAlpha(char) {
1770
+ return char >= "a" && char <= "z" || char >= "A" && char <= "Z";
1771
+ }
1772
+ isIdentifierStart(char) {
1773
+ return this.isAlpha(char) || char === "_" || char === "$";
1774
+ }
1775
+ isIdentifierPart(char) {
1776
+ return this.isIdentifierStart(char) || this.isDigit(char) || char === "-";
1777
+ }
1778
+ };
1779
+ var HoloScriptPlusParser = class {
1780
+ constructor(options = {}) {
1781
+ this.tokens = [];
1782
+ this.pos = 0;
1783
+ this.source = "";
1784
+ this.errors = [];
1785
+ this.warnings = [];
1786
+ this.imports = [];
1787
+ this.hasState = false;
1788
+ this.hasVRTraits = false;
1789
+ this.hasControlFlow = false;
1790
+ this.compiledExpressions = /* @__PURE__ */ new Map();
1791
+ this.errorRecovery = new chunkNG77ATEW_cjs.ErrorRecovery();
1792
+ /**
1793
+ * Internal incremental parser for parseIncremental.
1794
+ * Uses ChunkBasedIncrementalParser with AST-aware chunking and
1795
+ * dependency tracking — no fallback to full re-parse for unchanged chunks.
1796
+ */
1797
+ this._incrementalParser = null;
1798
+ /**
1799
+ * Per-cache incremental parser map so callers can supply their own cache
1800
+ * and still get a dedicated ChunkBasedIncrementalParser instance.
1801
+ */
1802
+ this._incrementalParserCache = /* @__PURE__ */ new Map();
1803
+ this.options = {
1804
+ enableVRTraits: true,
1805
+ enableTypeScriptImports: true,
1806
+ strict: false,
1807
+ ...options
1808
+ };
1809
+ }
1810
+ /**
1811
+ * Get quick fixes for all errors in the last parse
1812
+ * Useful for IDE integrations and LSP
1813
+ */
1814
+ getQuickFixes() {
1815
+ const fixes = /* @__PURE__ */ new Map();
1816
+ for (const error of this.errors) {
1817
+ const errorFixes = chunkNG77ATEW_cjs.generateQuickFixes(
1818
+ {
1819
+ code: error.code,
1820
+ message: error.message,
1821
+ line: error.line,
1822
+ column: error.column,
1823
+ source: this.source
1824
+ },
1825
+ this.source
1826
+ );
1827
+ if (errorFixes.length > 0) {
1828
+ fixes.set(error.line, errorFixes);
1829
+ }
1830
+ }
1831
+ return fixes;
1832
+ }
1833
+ /**
1834
+ * Get enriched errors with additional suggestions from ErrorRecovery
1835
+ */
1836
+ getEnrichedErrors() {
1837
+ return this.errors.map(
1838
+ (error) => chunkNG77ATEW_cjs.enrichErrorWithSuggestions(
1839
+ {
1840
+ code: error.code,
1841
+ message: error.message,
1842
+ line: error.line,
1843
+ column: error.column,
1844
+ source: this.source
1845
+ },
1846
+ this.source
1847
+ )
1848
+ );
1849
+ }
1850
+ parse(source) {
1851
+ this.source = source;
1852
+ this.errors = [];
1853
+ this.warnings = [];
1854
+ this.imports = [];
1855
+ this.hasState = false;
1856
+ this.hasVRTraits = false;
1857
+ this.hasControlFlow = false;
1858
+ this.compiledExpressions = /* @__PURE__ */ new Map();
1859
+ this.pos = 0;
1860
+ this.errorRecovery.clear();
1861
+ const lexer = new Lexer(source);
1862
+ this.tokens = lexer.tokenize();
1863
+ const root = this.parseDocument();
1864
+ return this.buildResult(root);
1865
+ }
1866
+ /**
1867
+ * Performs an incremental parse using ChunkBasedIncrementalParser with
1868
+ * AST-aware chunking, hash-based caching, and dependency tracking.
1869
+ *
1870
+ * Unchanged chunks are served from cache (zero re-parse cost). Only chunks
1871
+ * whose content hash changed — plus chunks that reference changed ones via
1872
+ * `using`, spread, or `@composition` — are re-parsed.
1873
+ *
1874
+ * Previous implementation fell back to a full re-parse per chunk because it
1875
+ * used `ChunkDetector.detect()` inline without the stateful comparison that
1876
+ * `ChunkBasedIncrementalParser` provides. This is now wired through the
1877
+ * superior engine (APL WIT audit gap #3, 2026-05-21).
1878
+ */
1879
+ parseIncremental(source, cache = globalParseCache) {
1880
+ let incrementalParser = this._incrementalParserCache.get(cache);
1881
+ if (!incrementalParser) {
1882
+ incrementalParser = new ChunkBasedIncrementalParser(cache);
1883
+ this._incrementalParserCache.set(cache, incrementalParser);
1884
+ }
1885
+ const incrementalResult = incrementalParser.parse(source);
1886
+ const chunks = ChunkDetector.detect(source);
1887
+ const children = incrementalResult.ast.type === "fragment" ? incrementalResult.ast.children || [] : [incrementalResult.ast];
1888
+ for (let i = 0; i < children.length; i++) {
1889
+ const chunk = chunks[i];
1890
+ if (chunk && chunk.startLine > 1) {
1891
+ this.offsetNodeLoc(children[i], chunk.startLine - 1);
1892
+ }
1893
+ }
1894
+ this.source = source;
1895
+ this.errors = [];
1896
+ this.warnings = [];
1897
+ this.imports = [];
1898
+ this.hasState = false;
1899
+ this.hasVRTraits = false;
1900
+ this.hasControlFlow = false;
1901
+ this.compiledExpressions = /* @__PURE__ */ new Map();
1902
+ for (const node of children) {
1903
+ if (node && typeof node === "object") {
1904
+ const nodeAny = node;
1905
+ if (nodeAny.traits instanceof Map) {
1906
+ for (const [traitName] of nodeAny.traits) {
1907
+ const name = String(traitName);
1908
+ if (name === "state") this.hasState = true;
1909
+ if (name === "grabbable" || name === "throwable" || name === "hoverable" || name === "clickable" || name === "collidable") {
1910
+ this.hasVRTraits = true;
1911
+ }
1912
+ }
1913
+ }
1914
+ }
1915
+ }
1916
+ const root = incrementalResult.ast.type === "fragment" ? incrementalResult.ast : {
1917
+ type: "fragment",
1918
+ id: "root",
1919
+ properties: {},
1920
+ directives: [],
1921
+ children: [incrementalResult.ast],
1922
+ traits: /* @__PURE__ */ new Map(),
1923
+ loc: incrementalResult.ast.loc || { start: { line: 1, column: 1 }, end: { line: 1, column: 1 } },
1924
+ body: [incrementalResult.ast]
1925
+ };
1926
+ if (root.type === "fragment" && root.loc) {
1927
+ root.loc.start = { line: 1, column: 1 };
1928
+ if (chunks.length > 0) {
1929
+ root.loc.end = { line: chunks[chunks.length - 1].endLine, column: 1 };
1930
+ }
1931
+ }
1932
+ const result = this.buildResult(root);
1933
+ result.incrementalMetrics = {
1934
+ cached: incrementalResult.cached,
1935
+ parsed: incrementalResult.parsed,
1936
+ duration: incrementalResult.duration,
1937
+ changedChunks: incrementalResult.changedChunks
1938
+ };
1939
+ return result;
1940
+ }
1941
+ buildResult(root) {
1942
+ const isFragment = root.type === "fragment";
1943
+ const directives = root.directives || [];
1944
+ let version;
1945
+ const migrations = [];
1946
+ for (const d of directives) {
1947
+ if (d.type === "version") {
1948
+ version = d.version;
1949
+ } else if (d.type === "migrate") {
1950
+ migrations.push({
1951
+ type: "Migration",
1952
+ fromVersion: d.fromVersion,
1953
+ body: d.body
1954
+ });
1955
+ }
1956
+ }
1957
+ if (version === void 0) version = "1.0";
1958
+ const children = isFragment ? root.children || [] : [root];
1959
+ const worlds = children.filter((c) => c.type === "world");
1960
+ const compositions = children.filter((c) => c.type === "composition");
1961
+ const templates = children.filter((c) => c.type === "template");
1962
+ const npcs = children.filter((c) => c.type === "npc");
1963
+ const ast = {
1964
+ type: "Program",
1965
+ id: "root",
1966
+ properties: isFragment ? root.properties || {} : {},
1967
+ directives,
1968
+ children,
1969
+ worlds,
1970
+ compositions,
1971
+ templates,
1972
+ npcs,
1973
+ traits: isFragment ? root.traits || /* @__PURE__ */ new Map() : /* @__PURE__ */ new Map(),
1974
+ loc: root.loc,
1975
+ body: children,
1976
+ version,
1977
+ migrations: migrations.length > 0 ? migrations : void 0,
1978
+ root,
1979
+ imports: this.imports,
1980
+ hasState: this.hasState,
1981
+ hasVRTraits: this.hasVRTraits,
1982
+ hasControlFlow: this.hasControlFlow
1983
+ };
1984
+ return {
1985
+ success: this.errors.length === 0,
1986
+ ast,
1987
+ compiledExpressions: this.compiledExpressions,
1988
+ requiredCompanions: this.imports.map((i) => i.path),
1989
+ features: {
1990
+ state: this.hasState,
1991
+ vrTraits: this.hasVRTraits,
1992
+ loops: this.hasControlFlow,
1993
+ conditionals: this.hasControlFlow,
1994
+ lifecycleHooks: (root.directives || []).some((d) => d.type === "lifecycle")
1995
+ },
1996
+ warnings: this.warnings,
1997
+ errors: this.errors
1998
+ };
1999
+ }
2000
+ offsetNodeLoc(node, lineOffset) {
2001
+ if (node.loc) {
2002
+ if (node.loc.start) node.loc.start.line += lineOffset;
2003
+ if (node.loc.end) node.loc.end.line += lineOffset;
2004
+ }
2005
+ if (node.children) {
2006
+ node.children.forEach((child) => this.offsetNodeLoc(child, lineOffset));
2007
+ }
2008
+ if (node.body && Array.isArray(node.body)) {
2009
+ node.body.forEach((child) => this.offsetNodeLoc(child, lineOffset));
2010
+ }
2011
+ }
2012
+ parseDocument() {
2013
+ this.skipNewlines();
2014
+ const topLevelNodes = [];
2015
+ const globalDirectives = [];
2016
+ while (!this.check("EOF")) {
2017
+ const currentDirectives = [];
2018
+ try {
2019
+ while (this.check("AT")) {
2020
+ const directive = this.parseDirective();
2021
+ if (directive) {
2022
+ const { type } = directive;
2023
+ if (type === "version" || type === "migrate" || type === "import" || type === "export") {
2024
+ globalDirectives.push(directive);
2025
+ if (type === "export") {
2026
+ currentDirectives.push(directive);
2027
+ }
2028
+ } else {
2029
+ currentDirectives.push(directive);
2030
+ }
2031
+ }
2032
+ this.skipNewlines();
2033
+ }
2034
+ const isNodeStart = this.check("IDENTIFIER") || this.check("STATE_MACHINE") || this.check("STATE") || this.check("TRANSITION") || this.check("INITIAL");
2035
+ if (isNodeStart) {
2036
+ const node = this.parseNode();
2037
+ const existingDirectives = node.directives || [];
2038
+ node.directives = [...currentDirectives, ...existingDirectives];
2039
+ if (node.type === "template") {
2040
+ for (const d of currentDirectives) {
2041
+ if (d.type === "version") {
2042
+ node.version = d.version;
2043
+ } else if (d.type === "migrate") {
2044
+ if (!node.migrations) node.migrations = [];
2045
+ node.migrations.push({
2046
+ type: "Migration",
2047
+ fromVersion: d.fromVersion,
2048
+ body: d.body
2049
+ });
2050
+ }
2051
+ }
2052
+ }
2053
+ topLevelNodes.push(node);
2054
+ } else {
2055
+ if (currentDirectives.length > 0) {
2056
+ if (this.check("EOF")) {
2057
+ globalDirectives.push(...currentDirectives);
2058
+ } else {
2059
+ this.error(
2060
+ `Expected node after directives, got ${this.current().type}. Valid nodes: orb, template, logic, object, world, composition, scene, group`,
2061
+ "HSP003"
2062
+ );
2063
+ globalDirectives.push(...currentDirectives);
2064
+ }
2065
+ } else if (!this.check("EOF")) {
2066
+ this.error(
2067
+ `Unexpected token ${this.current().type} "${this.current().value}" at top level. Expected: composition, object, world, template, logic, or @directive`,
2068
+ "HSP001"
2069
+ );
2070
+ throw new Error("ParseError");
2071
+ }
2072
+ }
2073
+ if (this.check("IDENTIFIER") && this.current().value === "connect") {
2074
+ const connection = this.parseConnectionStatement();
2075
+ const node = {
2076
+ type: "connection",
2077
+ properties: connection,
2078
+ directives: [],
2079
+ children: [],
2080
+ traits: /* @__PURE__ */ new Map(),
2081
+ loc: {
2082
+ start: { line: this.current().line, column: 0 },
2083
+ end: { line: this.current().line, column: 0 }
2084
+ }
2085
+ };
2086
+ topLevelNodes.push(node);
2087
+ }
2088
+ } catch (e) {
2089
+ const errorMessage = e instanceof Error ? e.message : String(e);
2090
+ if (errorMessage !== "ParseError" && errorMessage !== "Unexpected token") {
2091
+ console.error(e);
2092
+ }
2093
+ this.synchronize();
2094
+ }
2095
+ this.skipNewlines();
2096
+ }
2097
+ if (topLevelNodes.length === 1 && globalDirectives.length === 0) {
2098
+ return topLevelNodes[0];
2099
+ }
2100
+ return {
2101
+ type: "fragment",
2102
+ id: "root",
2103
+ properties: {},
2104
+ directives: globalDirectives,
2105
+ children: topLevelNodes,
2106
+ traits: /* @__PURE__ */ new Map(),
2107
+ loc: {
2108
+ start: { line: 1, column: 1 },
2109
+ end: { line: this.current().line, column: this.current().column }
2110
+ },
2111
+ body: topLevelNodes
2112
+ };
2113
+ }
2114
+ parseNode() {
2115
+ const startToken = this.current();
2116
+ const typeToken = this.match([
2117
+ "IDENTIFIER",
2118
+ "STATE_MACHINE",
2119
+ "STATE",
2120
+ "TRANSITION",
2121
+ "INITIAL",
2122
+ "ON_ENTRY",
2123
+ "ON_EXIT"
2124
+ ]) || this.expect("IDENTIFIER", "Expected element type");
2125
+ const type = typeToken.value;
2126
+ if (type === "template") {
2127
+ const templateName = this.expect("STRING", "Expected template name").value;
2128
+ const templateBody = this.parseBlockContent();
2129
+ let version;
2130
+ const migrations = [];
2131
+ const directives2 = [];
2132
+ const children2 = [];
2133
+ for (const [key, value] of Object.entries(templateBody)) {
2134
+ if (key === "@version") {
2135
+ const v = value;
2136
+ if (v.type === "version") version = v.version;
2137
+ delete templateBody[key];
2138
+ } else if (key === "@migrate") {
2139
+ const m = value;
2140
+ if (m.type === "migrate") {
2141
+ migrations.push({
2142
+ type: "Migration",
2143
+ fromVersion: m.fromVersion,
2144
+ body: m.body
2145
+ });
2146
+ }
2147
+ delete templateBody[key];
2148
+ } else if (key.startsWith("@")) {
2149
+ directives2.push(value);
2150
+ delete templateBody[key];
2151
+ } else if (typeof value === "object" && value && "type" in value) {
2152
+ children2.push(value);
2153
+ delete templateBody[key];
2154
+ }
2155
+ }
2156
+ return {
2157
+ type: "template",
2158
+ name: templateName,
2159
+ properties: templateBody,
2160
+ // Now contains only true properties
2161
+ version,
2162
+ migrations,
2163
+ directives: directives2,
2164
+ children: children2,
2165
+ traits: /* @__PURE__ */ new Map(),
2166
+ loc: {
2167
+ start: { line: startToken.line, column: startToken.column },
2168
+ end: { line: this.current().line, column: this.current().column }
2169
+ }
2170
+ };
2171
+ }
2172
+ if (type === "logic") {
2173
+ const logicBody = this.parseLogicBlock();
2174
+ return {
2175
+ type: "logic",
2176
+ name: "logic",
2177
+ id: "logic",
2178
+ properties: {},
2179
+ directives: [],
2180
+ children: [],
2181
+ traits: /* @__PURE__ */ new Map(),
2182
+ body: logicBody,
2183
+ loc: {
2184
+ start: { line: startToken.line, column: startToken.column },
2185
+ end: { line: this.current().line, column: this.current().column }
2186
+ }
2187
+ };
2188
+ }
2189
+ if ([
2190
+ "module",
2191
+ "script",
2192
+ "struct",
2193
+ "enum",
2194
+ "class",
2195
+ "interface",
2196
+ "action",
2197
+ "function",
2198
+ "async",
2199
+ "on"
2200
+ ].includes(type)) {
2201
+ let name = "anonymous";
2202
+ if (this.check("IDENTIFIER")) {
2203
+ name = this.advance().value;
2204
+ } else if (this.check("STRING")) {
2205
+ name = this.advance().value;
2206
+ }
2207
+ while (this.check("DOT")) {
2208
+ this.advance();
2209
+ if (this.check("IDENTIFIER")) this.advance();
2210
+ }
2211
+ if (this.check("LPAREN")) {
2212
+ this.skipParens();
2213
+ }
2214
+ let bodyContent = "";
2215
+ if (this.check("LBRACE")) {
2216
+ bodyContent = this.parseRawBlock();
2217
+ }
2218
+ return {
2219
+ type,
2220
+ name,
2221
+ id: name,
2222
+ properties: {},
2223
+ directives: [],
2224
+ children: [],
2225
+ traits: /* @__PURE__ */ new Map(),
2226
+ body: bodyContent,
2227
+ loc: {
2228
+ start: { line: startToken.line, column: startToken.column },
2229
+ end: { line: this.current().line, column: this.current().column }
2230
+ }
2231
+ };
2232
+ }
2233
+ if (startToken.type === "STATE_MACHINE" || type === "state_machine") {
2234
+ return this.parseStateMachine();
2235
+ }
2236
+ if (type === "on_error" || startToken.type === "ON_ERROR") {
2237
+ return this.parseOnErrorNode();
2238
+ }
2239
+ if (type === "assert" || startToken.type === "ASSERT") {
2240
+ return this.parseAssertNode();
2241
+ }
2242
+ if (type === "environment") {
2243
+ const envBody = this.parseEnvironmentBlock();
2244
+ return {
2245
+ type: "environment",
2246
+ properties: envBody.properties,
2247
+ directives: envBody.directives,
2248
+ children: [],
2249
+ traits: /* @__PURE__ */ new Map(),
2250
+ loc: {
2251
+ start: { line: startToken.line, column: startToken.column },
2252
+ end: { line: this.current().line, column: this.current().column }
2253
+ }
2254
+ };
2255
+ }
2256
+ if (type === "composition" || type === "world") {
2257
+ let id2;
2258
+ if (this.check("HASH")) {
2259
+ this.advance();
2260
+ id2 = this.expect("IDENTIFIER", "Expected ID after #").value;
2261
+ }
2262
+ if (this.check("STRING")) {
2263
+ id2 = this.advance().value;
2264
+ }
2265
+ if (this.check("IDENTIFIER")) {
2266
+ id2 = this.advance().value;
2267
+ }
2268
+ const compBody = this.parseCompositionBlock();
2269
+ const traits2 = /* @__PURE__ */ new Map();
2270
+ for (const child of compBody.children) {
2271
+ if (child.type === "fragment" && Array.isArray(child.directives)) {
2272
+ for (const d of child.directives) {
2273
+ if (d.type === "trait") {
2274
+ traits2.set(d.name, d.config);
2275
+ this.hasVRTraits = true;
2276
+ }
2277
+ }
2278
+ }
2279
+ }
2280
+ return {
2281
+ type: type === "composition" ? "composition" : "world",
2282
+ name: id2,
2283
+ id: id2,
2284
+ properties: compBody.properties || {},
2285
+ directives: [],
2286
+ children: compBody.children,
2287
+ traits: traits2,
2288
+ body: compBody,
2289
+ loc: {
2290
+ start: { line: startToken.line, column: startToken.column },
2291
+ end: { line: this.current().line, column: this.current().column }
2292
+ }
2293
+ };
2294
+ }
2295
+ let id;
2296
+ let templateRef;
2297
+ if (this.check("HASH")) {
2298
+ this.advance();
2299
+ id = this.expect("IDENTIFIER", "Expected ID after #").value;
2300
+ }
2301
+ if (this.check("STRING")) {
2302
+ id = this.advance().value;
2303
+ }
2304
+ if (this.check("IDENTIFIER") && this.current().value !== "using") {
2305
+ id = this.advance().value;
2306
+ }
2307
+ if (this.check("LPAREN")) {
2308
+ this.skipParens();
2309
+ }
2310
+ if (this.check("IDENTIFIER") && this.current().value === "using") {
2311
+ this.advance();
2312
+ templateRef = this.expect("STRING", "Expected template name after using").value;
2313
+ }
2314
+ if (this.check("COLON")) {
2315
+ this.advance();
2316
+ if (this.check("IDENTIFIER")) this.advance();
2317
+ if (this.check("LBRACKET")) {
2318
+ this.advance();
2319
+ if (this.check("RBRACKET")) this.advance();
2320
+ }
2321
+ }
2322
+ const properties = {};
2323
+ const children = [];
2324
+ const directives = [];
2325
+ const traits = /* @__PURE__ */ new Map();
2326
+ if (templateRef) {
2327
+ properties.__templateRef = templateRef;
2328
+ }
2329
+ while (!this.check("LBRACE") && !this.check("EOF")) {
2330
+ try {
2331
+ if (this.check("NEWLINE")) {
2332
+ this.skipNewlines();
2333
+ if (this.check("LBRACE")) break;
2334
+ if (!this.check("AT")) {
2335
+ if (this.check("EOF")) break;
2336
+ }
2337
+ }
2338
+ if (this.check("AT")) {
2339
+ const directive = this.parseDirective();
2340
+ if (directive) {
2341
+ if (directive.type === "trait") {
2342
+ traits.set(directive.name, directive.config);
2343
+ this.hasVRTraits = true;
2344
+ directives.push(directive);
2345
+ } else {
2346
+ directives.push(directive);
2347
+ }
2348
+ }
2349
+ } else if (this.check("SPREAD")) {
2350
+ const startToken2 = this.advance();
2351
+ const targetExpr = this.parseUnary();
2352
+ let target;
2353
+ if (typeof targetExpr === "object" && targetExpr && "__ref" in targetExpr) {
2354
+ target = targetExpr.__ref;
2355
+ } else if (typeof targetExpr === "string") {
2356
+ target = targetExpr;
2357
+ } else {
2358
+ this.error(
2359
+ "Expected identifier or member expression after spread operator (...)",
2360
+ "HSP002"
2361
+ );
2362
+ target = "unknown";
2363
+ }
2364
+ children.push({
2365
+ type: "spread",
2366
+ target,
2367
+ loc: {
2368
+ start: { line: startToken2.line, column: startToken2.column },
2369
+ end: { line: this.current().line, column: this.current().column }
2370
+ }
2371
+ });
2372
+ } else if (this.check("IDENTIFIER")) {
2373
+ const key = this.advance().value;
2374
+ let value = true;
2375
+ if (this.check("COLON")) {
2376
+ this.advance();
2377
+ value = this.parseValue();
2378
+ }
2379
+ properties[key] = value;
2380
+ } else {
2381
+ if (!this.check("LBRACE")) {
2382
+ this.error(
2383
+ `Unexpected token in properties: ${this.current().type}. Expected property name, @directive, or spread (...)`,
2384
+ "HSP101"
2385
+ );
2386
+ this.synchronizeProperty();
2387
+ }
2388
+ }
2389
+ } catch (e) {
2390
+ const errorMessage = e instanceof Error ? e.message : String(e);
2391
+ if (errorMessage !== "ParseError") console.error(e);
2392
+ this.synchronizeProperty();
2393
+ }
2394
+ }
2395
+ if (this.check("LBRACE")) {
2396
+ this.advance();
2397
+ this.skipNewlines();
2398
+ while (!this.check("RBRACE") && !this.check("EOF")) {
2399
+ try {
2400
+ this.skipNewlines();
2401
+ if (this.check("RBRACE") || this.check("EOF")) break;
2402
+ if (this.check("AT")) {
2403
+ const directive = this.parseDirective();
2404
+ if (directive) {
2405
+ if (directive.type === "trait") {
2406
+ traits.set(directive.name, directive.config);
2407
+ this.hasVRTraits = true;
2408
+ }
2409
+ directives.push(directive);
2410
+ }
2411
+ } else if (this.check("SPREAD")) {
2412
+ const startToken2 = this.advance();
2413
+ const targetExpr = this.parseUnary();
2414
+ let target;
2415
+ if (typeof targetExpr === "object" && targetExpr && "__ref" in targetExpr) {
2416
+ target = targetExpr.__ref;
2417
+ } else if (typeof targetExpr === "string") {
2418
+ target = targetExpr;
2419
+ } else {
2420
+ this.error(
2421
+ "Expected identifier or member expression after spread operator (...)",
2422
+ "HSP002"
2423
+ );
2424
+ target = "unknown";
2425
+ }
2426
+ const spreadNode = {
2427
+ type: "spread",
2428
+ target,
2429
+ loc: {
2430
+ start: { line: startToken2.line, column: startToken2.column },
2431
+ end: { line: this.current().line, column: this.current().column }
2432
+ }
2433
+ };
2434
+ children.push(spreadNode);
2435
+ const key = "__spread_" + target;
2436
+ properties[key] = spreadNode;
2437
+ } else {
2438
+ const token = this.current();
2439
+ const isKeyToken = token.type === "IDENTIFIER" || token.type === "STRING" || token.type === "HASH" || token.type === "STATE" || token.type === "STATE_MACHINE" || token.type === "INITIAL" || token.type === "ON_ENTRY" || token.type === "ON_EXIT" || token.type === "TRANSITION";
2440
+ if (isKeyToken) {
2441
+ const saved = this.pos;
2442
+ const name = this.advance().value;
2443
+ const childNodeKeywords = [
2444
+ "logic",
2445
+ "template",
2446
+ "environment",
2447
+ "state",
2448
+ "object",
2449
+ "composition",
2450
+ "system",
2451
+ "core_config",
2452
+ "narrative",
2453
+ "quest",
2454
+ "objective",
2455
+ "dialogue",
2456
+ "choice",
2457
+ "visual_metadata",
2458
+ "spatial_group",
2459
+ "scene",
2460
+ "group",
2461
+ "world",
2462
+ "module",
2463
+ "struct",
2464
+ "orb",
2465
+ "on_error",
2466
+ "assert",
2467
+ "transition",
2468
+ "on_entry",
2469
+ "on_exit",
2470
+ "page",
2471
+ "include"
2472
+ ];
2473
+ if (name === "transition" && this.check("STRING")) {
2474
+ const event = this.advance().value;
2475
+ if (this.check("ARROW")) {
2476
+ this.advance();
2477
+ const targetState = this.expect("STRING", "Expected target state string").value;
2478
+ let block = {};
2479
+ if (this.check("LBRACE")) {
2480
+ block = this.parseBlockContent();
2481
+ }
2482
+ children.push({
2483
+ type: "transition",
2484
+ name: `${event}_to_${targetState}`,
2485
+ event,
2486
+ target: targetState,
2487
+ guard: block.guard || "",
2488
+ action: block.action || "",
2489
+ block
2490
+ });
2491
+ continue;
2492
+ } else {
2493
+ this.pos = saved;
2494
+ }
2495
+ }
2496
+ if (name === "on_entry" || name === "on_exit") {
2497
+ let block = "";
2498
+ if (this.check("LBRACE")) {
2499
+ block = this.parseCodeBlock();
2500
+ } else {
2501
+ while (!this.check("RBRACE") && !this.check("EOF")) this.advance();
2502
+ }
2503
+ children.push({
2504
+ type: "method",
2505
+ name,
2506
+ params: [],
2507
+ returnType: "unknown",
2508
+ body: block
2509
+ });
2510
+ continue;
2511
+ }
2512
+ if (this.check("LPAREN")) {
2513
+ const possibleMethod = saved;
2514
+ this.pos = saved;
2515
+ const methodName = this.advance().value;
2516
+ const params = [];
2517
+ this.advance();
2518
+ while (!this.check("RPAREN") && !this.check("EOF") && !this.check("LBRACE")) {
2519
+ if (this.check("IDENTIFIER")) {
2520
+ params.push(this.advance().value);
2521
+ } else {
2522
+ this.advance();
2523
+ }
2524
+ }
2525
+ if (this.check("RPAREN")) this.advance();
2526
+ let returnType = "unknown";
2527
+ if (this.check("COLON")) {
2528
+ this.advance();
2529
+ if (this.check("IDENTIFIER")) {
2530
+ returnType = this.advance().value;
2531
+ }
2532
+ }
2533
+ if (this.check("LBRACE")) {
2534
+ const body = this.parseCodeBlock();
2535
+ children.push({
2536
+ type: "method",
2537
+ name: methodName,
2538
+ params,
2539
+ returnType,
2540
+ body
2541
+ });
2542
+ continue;
2543
+ } else {
2544
+ this.pos = possibleMethod;
2545
+ this.advance();
2546
+ }
2547
+ }
2548
+ if (this.check("COLON") || this.check("EQUALS")) {
2549
+ this.advance();
2550
+ properties[name] = this.parseValue();
2551
+ } else if (childNodeKeywords.includes(name) && (this.check("LBRACE") || this.check("STRING"))) {
2552
+ this.pos = saved;
2553
+ children.push(this.parseNode());
2554
+ } else if (this.current().type === "IDENTIFIER") {
2555
+ this.pos = saved;
2556
+ children.push(this.parseNode());
2557
+ } else {
2558
+ properties[name] = true;
2559
+ while (this.check("LPAREN") || this.check("DOT") || this.check("LBRACE")) {
2560
+ if (this.check("LPAREN")) this.skipParens();
2561
+ else if (this.check("LBRACE")) this.skipBraces();
2562
+ else {
2563
+ this.advance();
2564
+ if (this.check("IDENTIFIER")) this.advance();
2565
+ }
2566
+ }
2567
+ }
2568
+ } else if (this.check("COMMA")) {
2569
+ this.advance();
2570
+ } else {
2571
+ this.error(
2572
+ `Unexpected token ${this.current().type} "${this.current().value}" in node body`
2573
+ );
2574
+ this.synchronizeProperty();
2575
+ }
2576
+ }
2577
+ this.skipNewlines();
2578
+ } catch (e) {
2579
+ const errorMessage = e instanceof Error ? e.message : String(e);
2580
+ if (errorMessage !== "ParseError") console.error(e);
2581
+ this.synchronizeProperty();
2582
+ }
2583
+ }
2584
+ this.expect("RBRACE", "Expected }");
2585
+ }
2586
+ return {
2587
+ type,
2588
+ name: id,
2589
+ // Mapping id to name for runtime compatibility
2590
+ id,
2591
+ properties,
2592
+ directives,
2593
+ children,
2594
+ traits,
2595
+ loc: {
2596
+ start: { line: startToken.line, column: startToken.column },
2597
+ end: { line: this.current().line, column: this.current().column }
2598
+ }
2599
+ };
2600
+ }
2601
+ parseDirective() {
2602
+ this.expect("AT", "Expected @");
2603
+ const nameToken = this.current();
2604
+ const isKeyword = ["STATE_MACHINE", "STATE", "ON_ENTRY", "ON_EXIT", "TRANSITION"].includes(
2605
+ nameToken.type
2606
+ );
2607
+ if (nameToken.type !== "IDENTIFIER" && !isKeyword) {
2608
+ this.error(
2609
+ `Expected directive name, got ${nameToken.type}. Directives start with @ followed by name (e.g., @grabbable)`,
2610
+ "HSP201"
2611
+ );
2612
+ return null;
2613
+ }
2614
+ this.advance();
2615
+ const name = nameToken.value;
2616
+ if (name === "version") {
2617
+ this.expect("LPAREN", "Expected ( after @version");
2618
+ const versionToken = this.expect("NUMBER", "Expected version number");
2619
+ const version = Number(versionToken.value);
2620
+ this.expect("RPAREN", "Expected ) after version number");
2621
+ return { type: "version", version };
2622
+ }
2623
+ if (name === "migrate") {
2624
+ const fromToken = this.expect("IDENTIFIER", 'Expected "from" after @migrate');
2625
+ if (fromToken.value !== "from") {
2626
+ this.error('Expected "from" after @migrate');
2627
+ }
2628
+ this.expect("LPAREN", "Expected ( after from");
2629
+ const fromVersionToken = this.expect("NUMBER", "Expected version number");
2630
+ const fromVersion = Number(fromVersionToken.value);
2631
+ this.expect("RPAREN", "Expected ) after version number");
2632
+ const body = this.check("LBRACE") ? this.parseCodeBlock() : "";
2633
+ return { type: "migrate", fromVersion, body };
2634
+ }
2635
+ if (chunkWRLUBRKS_cjs.VR_TRAITS.includes(name)) {
2636
+ if (!this.options.enableVRTraits) {
2637
+ this.warn(`VR trait @${name} is disabled`);
2638
+ return null;
2639
+ }
2640
+ let config2 = {};
2641
+ if (this.check("LPAREN")) {
2642
+ config2 = this.parseTraitConfig();
2643
+ } else if (this.check("LBRACE")) {
2644
+ config2 = this.parseBlockContent();
2645
+ }
2646
+ return this.parseTraitSumTail({ type: "trait", name, config: config2 });
2647
+ }
2648
+ if (chunkNG77ATEW_cjs.LIFECYCLE_HOOKS.includes(name)) {
2649
+ const params = [];
2650
+ if (this.check("LPAREN")) {
2651
+ this.advance();
2652
+ while (!this.check("RPAREN") && !this.check("EOF")) {
2653
+ params.push(this.expect("IDENTIFIER", "Expected parameter name").value);
2654
+ if (this.check("COLON")) {
2655
+ this.advance();
2656
+ this.expect("IDENTIFIER", "Expected type");
2657
+ }
2658
+ if (this.check("COMMA")) this.advance();
2659
+ }
2660
+ this.expect("RPAREN", "Expected )");
2661
+ }
2662
+ if (this.check("COLON")) {
2663
+ this.advance();
2664
+ if (this.check("LPAREN")) this.skipParens();
2665
+ if (this.check("ARROW")) this.advance();
2666
+ }
2667
+ let body = "";
2668
+ if (this.check("ARROW")) {
2669
+ this.advance();
2670
+ body = this.parseInlineExpression();
2671
+ } else if (this.check("LBRACE")) {
2672
+ body = this.parseCodeBlock();
2673
+ }
2674
+ return {
2675
+ type: "lifecycle",
2676
+ hook: name,
2677
+ params,
2678
+ body
2679
+ };
2680
+ }
2681
+ if (name === "state") {
2682
+ this.hasState = true;
2683
+ const body = this.parseStateBlock();
2684
+ return { type: "state", body };
2685
+ }
2686
+ if (name === "bindings") {
2687
+ const bindings = this.parseBindingsBlock();
2688
+ return { type: "bindings", bindings };
2689
+ }
2690
+ if (name === "for") {
2691
+ this.hasControlFlow = true;
2692
+ const variable = this.expect("IDENTIFIER", "Expected variable name").value;
2693
+ this.expect("IDENTIFIER", 'Expected "in"');
2694
+ const iterable = this.parseInlineExpression();
2695
+ const body = this.parseControlFlowBody();
2696
+ return { type: "for", variable, iterable, body };
2697
+ }
2698
+ if (name === "forEach") {
2699
+ this.hasControlFlow = true;
2700
+ const variable = this.expect("IDENTIFIER", "Expected variable name").value;
2701
+ this.expect("IDENTIFIER", 'Expected "in"');
2702
+ const collection = this.parseInlineExpression();
2703
+ const body = this.parseControlFlowBody();
2704
+ return { type: "forEach", variable, collection, body };
2705
+ }
2706
+ if (name === "while") {
2707
+ this.hasControlFlow = true;
2708
+ const condition = this.parseInlineExpression();
2709
+ const body = this.parseControlFlowBody();
2710
+ return { type: "while", condition, body };
2711
+ }
2712
+ if (name === "if") {
2713
+ this.hasControlFlow = true;
2714
+ const condition = this.parseInlineExpression();
2715
+ const body = this.parseControlFlowBody();
2716
+ let elseBody;
2717
+ this.skipNewlines();
2718
+ if (this.check("AT")) {
2719
+ const saved = this.pos;
2720
+ this.advance();
2721
+ if (this.check("IDENTIFIER") && this.current().value === "else") {
2722
+ this.advance();
2723
+ elseBody = this.parseControlFlowBody();
2724
+ } else {
2725
+ this.pos = saved;
2726
+ }
2727
+ }
2728
+ return { type: "if", condition, body, else: elseBody };
2729
+ }
2730
+ if (name === "import") {
2731
+ if (!this.options.enableTypeScriptImports) {
2732
+ this.warn("@import is disabled");
2733
+ return null;
2734
+ }
2735
+ let namedImports;
2736
+ let isWildcard = false;
2737
+ if (this.check("LBRACE")) {
2738
+ this.advance();
2739
+ namedImports = [];
2740
+ while (!this.check("RBRACE") && !this.check("EOF")) {
2741
+ if (this.check("IDENTIFIER")) {
2742
+ namedImports.push(this.advance().value);
2743
+ }
2744
+ if (this.check("COMMA")) this.advance();
2745
+ }
2746
+ this.expect("RBRACE", "Expected } in named import list");
2747
+ if (this.check("IDENTIFIER") && this.current().value === "from") {
2748
+ this.advance();
2749
+ } else {
2750
+ this.warn("Expected 'from' after named import specifiers");
2751
+ }
2752
+ }
2753
+ if (this.check("ASTERISK") || this.check("IDENTIFIER") && this.current().value === "*") {
2754
+ this.advance();
2755
+ isWildcard = true;
2756
+ if (this.check("IDENTIFIER") && this.current().value === "as") {
2757
+ this.advance();
2758
+ }
2759
+ }
2760
+ const path = this.expect("STRING", "Expected import path string").value;
2761
+ let alias = path.split("/").pop()?.replace(/\.[^.]+$/, "") || "import";
2762
+ if (!namedImports && this.check("IDENTIFIER") && this.current().value === "as") {
2763
+ this.advance();
2764
+ alias = this.expect("IDENTIFIER", "Expected alias after as").value;
2765
+ }
2766
+ if (isWildcard && this.check("IDENTIFIER") && this.current().value !== "from") {
2767
+ alias = this.advance().value;
2768
+ if (this.check("IDENTIFIER") && this.current().value === "from") {
2769
+ this.advance();
2770
+ }
2771
+ }
2772
+ this.imports.push({ path, alias, namedImports, isWildcard });
2773
+ return {
2774
+ type: "import",
2775
+ path,
2776
+ alias,
2777
+ namedImports,
2778
+ isWildcard
2779
+ };
2780
+ }
2781
+ if (name === "export") {
2782
+ let exportKind = "any";
2783
+ if (this.check("IDENTIFIER")) {
2784
+ const kindToken = this.current();
2785
+ const knownKinds = ["template", "object", "composition", "trait", "group", "scene"];
2786
+ if (knownKinds.includes(kindToken.value)) {
2787
+ exportKind = this.advance().value;
2788
+ }
2789
+ }
2790
+ let exportName;
2791
+ if (this.check("STRING")) {
2792
+ exportName = this.advance().value;
2793
+ } else if (this.check("IDENTIFIER")) {
2794
+ exportName = this.advance().value;
2795
+ }
2796
+ return {
2797
+ type: "export",
2798
+ exportKind,
2799
+ exportName
2800
+ };
2801
+ }
2802
+ if (name === "manifest") {
2803
+ let config2 = {};
2804
+ let manifestName = "default";
2805
+ if (this.check("LPAREN")) {
2806
+ this.advance();
2807
+ if (this.check("STRING")) {
2808
+ manifestName = this.advance().value;
2809
+ }
2810
+ while (!this.check("RPAREN") && !this.check("EOF")) this.advance();
2811
+ this.expect("RPAREN", "Expected )");
2812
+ } else if (this.check("STRING")) {
2813
+ manifestName = this.advance().value;
2814
+ }
2815
+ if (this.check("LBRACE")) {
2816
+ const block = this.parseBlockContent();
2817
+ config2 = { ...config2, ...block };
2818
+ }
2819
+ return { type: "manifest", name: manifestName, ...config2 };
2820
+ }
2821
+ if (name === "asset") {
2822
+ if (this.check("LPAREN")) {
2823
+ const config2 = this.parseTraitConfig();
2824
+ return { ...config2, type: "asset" };
2825
+ }
2826
+ const assetId = this.expect("STRING", "Expected asset ID").value;
2827
+ return { type: "asset", id: assetId };
2828
+ }
2829
+ if (name === "semantic") {
2830
+ const semanticName = this.check("LPAREN") ? this.parseParenString() : this.expect("STRING", "Expected semantic name").value;
2831
+ const config2 = this.parseBlockContent();
2832
+ return { ...config2, type: "semantic", name: semanticName };
2833
+ }
2834
+ if (name === "annotate") {
2835
+ const annotateName = this.check("LPAREN") ? this.parseParenString() : this.expect("STRING", "Expected annotation type").value;
2836
+ let config2 = {};
2837
+ if (this.check("COMMA")) {
2838
+ this.advance();
2839
+ config2 = this.parseValue();
2840
+ if (this.check("RPAREN")) this.advance();
2841
+ } else if (this.check("RPAREN")) {
2842
+ this.advance();
2843
+ }
2844
+ return { type: "annotate", annotationType: annotateName, config: config2 };
2845
+ }
2846
+ if (name === "semantic_ref") {
2847
+ const refName = this.check("LPAREN") ? this.parseParenString() : this.expect("STRING", "Expected semantic reference").value;
2848
+ return { type: "semantic_ref", ref: refName };
2849
+ }
2850
+ if (name === "bindings") {
2851
+ const bindings = this.parseBindingsBlock();
2852
+ return { type: "bindings", bindings };
2853
+ }
2854
+ if (name === "world_metadata") {
2855
+ const config2 = this.parseBlockContent();
2856
+ return { ...config2, type: "world_metadata" };
2857
+ }
2858
+ if (name === "world_config") {
2859
+ const config2 = this.parseBlockContent();
2860
+ return { ...config2, type: "world_config" };
2861
+ }
2862
+ if (name === "zones") {
2863
+ const zones = this.parseNamedBlockList("zone");
2864
+ return { type: "zones", zones };
2865
+ }
2866
+ if (name === "spawn_points") {
2867
+ const spawns = this.parseNamedBlockList("spawn");
2868
+ return { type: "spawn_points", spawns };
2869
+ }
2870
+ if (name === "skybox") {
2871
+ const config2 = this.parseBlockContent();
2872
+ return { ...config2, type: "skybox" };
2873
+ }
2874
+ if (name === "ambient_light") {
2875
+ const config2 = this.parseBlockContent();
2876
+ return { ...config2, type: "ambient_light" };
2877
+ }
2878
+ if (name === "directional_light") {
2879
+ let lightName = "default";
2880
+ if (this.check("LPAREN")) {
2881
+ lightName = this.parseParenString();
2882
+ }
2883
+ const config2 = this.parseBlockContent();
2884
+ return { ...config2, type: "directional_light", name: lightName };
2885
+ }
2886
+ if (name === "fog") {
2887
+ const config2 = this.parseBlockContent();
2888
+ return { ...config2, type: "fog" };
2889
+ }
2890
+ if (name === "artwork_metadata") {
2891
+ const config2 = this.parseBlockContent();
2892
+ return { ...config2, type: "artwork_metadata" };
2893
+ }
2894
+ if (name === "npc_behavior") {
2895
+ const config2 = this.parseBlockContent();
2896
+ return { ...config2, type: "npc_behavior" };
2897
+ }
2898
+ if (name === "interactive") {
2899
+ const config2 = this.parseBlockContent();
2900
+ return { ...config2, type: "interactive" };
2901
+ }
2902
+ if (name === "lod") {
2903
+ const config2 = this.parseBlockContent();
2904
+ return { ...config2, type: "lod" };
2905
+ }
2906
+ if (name === "external_api") {
2907
+ let externalApiName = "default";
2908
+ if (this.check("STRING")) {
2909
+ externalApiName = this.advance().value;
2910
+ } else if (this.check("IDENTIFIER")) {
2911
+ externalApiName = this.advance().value;
2912
+ }
2913
+ const config2 = this.check("LBRACE") ? this.parseBlockContent() : this.parseTraitConfig();
2914
+ return {
2915
+ type: "external_api",
2916
+ name: externalApiName,
2917
+ ...config2
2918
+ };
2919
+ }
2920
+ if (name === "generate") {
2921
+ const config2 = this.parseTraitConfig();
2922
+ const prompt = config2.prompt || "";
2923
+ const context = config2.context || "";
2924
+ const target = config2.target || "children";
2925
+ return { type: "generate", prompt, context, target };
2926
+ }
2927
+ if (name === "npc") {
2928
+ const npcName = this.expect("STRING", "Expected NPC name").value;
2929
+ const props = this.parsePropsBlock();
2930
+ return { type: "npc", name: npcName, props };
2931
+ }
2932
+ if (name === "dialog") {
2933
+ const dialogName = this.expect("STRING", "Expected dialog name").value;
2934
+ const { props, options } = this.parseDialogBlock();
2935
+ return { type: "dialog", name: dialogName, props, options };
2936
+ }
2937
+ if (name === "hololand") {
2938
+ if (this.check("DOT")) {
2939
+ this.advance();
2940
+ const eventName = this.expect("IDENTIFIER", "Expected event name").value;
2941
+ const params = [];
2942
+ if (this.check("LPAREN")) {
2943
+ this.advance();
2944
+ while (!this.check("RPAREN") && !this.check("EOF")) {
2945
+ params.push(this.expect("IDENTIFIER", "Expected parameter").value);
2946
+ if (this.check("COLON")) {
2947
+ this.advance();
2948
+ this.expect("IDENTIFIER", "Expected type");
2949
+ }
2950
+ if (this.check("COMMA")) this.advance();
2951
+ }
2952
+ this.expect("RPAREN", "Expected )");
2953
+ }
2954
+ return { type: "hololand_event", event: eventName, params };
2955
+ }
2956
+ }
2957
+ if (chunkNG77ATEW_cjs.STRUCTURAL_DIRECTIVES.includes(name)) {
2958
+ let nodeName;
2959
+ if (this.check("STRING")) {
2960
+ nodeName = this.advance().value;
2961
+ }
2962
+ const config2 = this.check("LBRACE") ? this.parseBlockContent() : this.parseTraitConfig();
2963
+ return { ...config2, type: name, name: nodeName };
2964
+ }
2965
+ if (this.options.strict) {
2966
+ this.traitError(name);
2967
+ } else {
2968
+ this.warn(`Unknown directive @${name}`);
2969
+ }
2970
+ let config = {};
2971
+ if (this.check("LPAREN")) {
2972
+ config = this.parseTraitConfig();
2973
+ } else if (this.check("LBRACE")) {
2974
+ config = this.parseBlockContent();
2975
+ }
2976
+ if (this.check("COLON")) {
2977
+ this.advance();
2978
+ if (this.check("LPAREN")) this.skipParens();
2979
+ if (this.check("ARROW")) this.advance();
2980
+ if (this.check("LBRACE")) {
2981
+ config.body = this.parseCodeBlock();
2982
+ }
2983
+ }
2984
+ return this.parseTraitSumTail({ type: "trait", name, config });
2985
+ }
2986
+ parseTraitSumTail(first) {
2987
+ if (!this.check("PLUS")) {
2988
+ return first;
2989
+ }
2990
+ const alternatives = [
2991
+ { type: "trait_atom", name: first.name, config: first.config ?? {} }
2992
+ ];
2993
+ while (this.check("PLUS")) {
2994
+ this.advance();
2995
+ alternatives.push(this.parseTraitAtom());
2996
+ }
2997
+ return {
2998
+ type: "trait_sum",
2999
+ operation: "additive",
3000
+ alternatives
3001
+ };
3002
+ }
3003
+ parseTraitAtom() {
3004
+ this.expect("AT", "Expected @ in trait sum alternative");
3005
+ const name = this.expect("IDENTIFIER", "Expected trait name in trait sum alternative").value;
3006
+ let config = {};
3007
+ if (this.check("LPAREN")) {
3008
+ config = this.parseTraitConfig();
3009
+ } else if (this.check("LBRACE")) {
3010
+ config = this.parseBlockContent();
3011
+ }
3012
+ return { type: "trait_atom", name, config };
3013
+ }
3014
+ /**
3015
+ * Parse a string inside parentheses: ("name")
3016
+ */
3017
+ parseParenString() {
3018
+ this.expect("LPAREN", "Expected (");
3019
+ const value = this.expect("STRING", "Expected string").value;
3020
+ this.expect("RPAREN", "Expected )");
3021
+ return value;
3022
+ }
3023
+ parseConnectionStatement() {
3024
+ this.expect("IDENTIFIER", "Expected connect");
3025
+ const from = this.expect("IDENTIFIER", "Expected from name").value;
3026
+ this.expect("IDENTIFIER", "Expected to");
3027
+ const to = this.expect("IDENTIFIER", "Expected to name").value;
3028
+ return { from, to };
3029
+ }
3030
+ /**
3031
+ * Parse block content: { key: value, ... }
3032
+ */
3033
+ parseBlockContent() {
3034
+ const content = {};
3035
+ if (!this.check("LBRACE")) {
3036
+ return content;
3037
+ }
3038
+ this.advance();
3039
+ this.skipNewlines();
3040
+ while (!this.check("RBRACE") && !this.check("EOF")) {
3041
+ this.skipNewlines();
3042
+ if (this.check("RBRACE") || this.check("EOF")) break;
3043
+ this.skipNewlines();
3044
+ if (this.check("RBRACE") || this.check("EOF")) break;
3045
+ const token = this.current();
3046
+ const isKeyToken = token.type === "IDENTIFIER" || token.type === "STRING" || token.type === "STATE" || token.type === "STATE_MACHINE" || token.type === "INITIAL" || token.type === "ON_ENTRY" || token.type === "ON_EXIT" || token.type === "TRANSITION";
3047
+ if (isKeyToken) {
3048
+ const next = this.peek(1);
3049
+ if (next.type === "COLON" || next.type === "EQUALS") {
3050
+ const key = this.advance().value;
3051
+ this.advance();
3052
+ content[key] = this.parseValue();
3053
+ } else if (next.type === "STRING" || next.type === "LBRACE" || next.type === "IDENTIFIER") {
3054
+ const node = this.parseNode();
3055
+ const type = node.type;
3056
+ const name = node.name || `unnamed_${type}_${Object.keys(content).length}`;
3057
+ content[name] = node;
3058
+ } else {
3059
+ const key = this.advance().value;
3060
+ content[key] = true;
3061
+ }
3062
+ } else if (this.check("SPREAD")) {
3063
+ this.advance();
3064
+ const val = this.parseValue();
3065
+ const spreadKey = `__spread_${Object.keys(content).length}`;
3066
+ content[spreadKey] = { type: "spread", argument: val };
3067
+ } else if (this.check("AT")) {
3068
+ const directive = this.parseDirective();
3069
+ if (directive) {
3070
+ const dirKey = ("name" in directive ? directive.name : void 0) || directive.type;
3071
+ content[`@${dirKey}`] = directive;
3072
+ }
3073
+ } else if (this.check("LBRACE")) {
3074
+ let depth = 1;
3075
+ this.advance();
3076
+ while (depth > 0 && !this.check("EOF")) {
3077
+ if (this.check("LBRACE")) depth++;
3078
+ if (this.check("RBRACE")) depth--;
3079
+ this.advance();
3080
+ }
3081
+ } else if (this.check("LPAREN")) {
3082
+ this.skipParens();
3083
+ } else {
3084
+ this.advance();
3085
+ }
3086
+ if (this.check("COMMA")) this.advance();
3087
+ this.skipNewlines();
3088
+ }
3089
+ this.expect("RBRACE", "Expected }");
3090
+ return content;
3091
+ }
3092
+ /**
3093
+ * Parse bindings block: { bind(expr) -> target, ... }
3094
+ */
3095
+ parseBindingsBlock() {
3096
+ const bindings = [];
3097
+ if (!this.check("LBRACE")) {
3098
+ return bindings;
3099
+ }
3100
+ this.advance();
3101
+ this.skipNewlines();
3102
+ while (!this.check("RBRACE") && !this.check("EOF")) {
3103
+ this.skipNewlines();
3104
+ if (this.check("RBRACE") || this.check("EOF")) break;
3105
+ if (this.check("IDENTIFIER") && this.current().value === "bind") {
3106
+ this.advance();
3107
+ if (this.check("LPAREN")) {
3108
+ this.advance();
3109
+ let source = "";
3110
+ let parenDepth = 1;
3111
+ while (parenDepth > 0 && !this.check("EOF")) {
3112
+ if (this.check("LPAREN")) parenDepth++;
3113
+ if (this.check("RPAREN")) {
3114
+ parenDepth--;
3115
+ if (parenDepth === 0) break;
3116
+ }
3117
+ source += this.advance().value + " ";
3118
+ }
3119
+ this.expect("RPAREN", "Expected )");
3120
+ source = source.trim();
3121
+ if (this.check("ARROW")) {
3122
+ this.advance();
3123
+ }
3124
+ let target = "";
3125
+ while (!this.check("NEWLINE") && !this.check("RBRACE") && !this.check("EOF")) {
3126
+ target += this.advance().value;
3127
+ }
3128
+ target = target.trim();
3129
+ bindings.push({ source, target });
3130
+ }
3131
+ } else {
3132
+ while (!this.check("NEWLINE") && !this.check("RBRACE") && !this.check("EOF")) {
3133
+ this.advance();
3134
+ }
3135
+ }
3136
+ this.skipNewlines();
3137
+ }
3138
+ this.expect("RBRACE", "Expected }");
3139
+ return bindings;
3140
+ }
3141
+ /**
3142
+ * Parse named block list: zone "name" { ... } or spawn "name" { ... }
3143
+ */
3144
+ parseNamedBlockList(blockType) {
3145
+ const blocks = [];
3146
+ if (!this.check("LBRACE")) {
3147
+ return blocks;
3148
+ }
3149
+ this.advance();
3150
+ this.skipNewlines();
3151
+ while (!this.check("RBRACE") && !this.check("EOF")) {
3152
+ this.skipNewlines();
3153
+ if (this.check("RBRACE") || this.check("EOF")) break;
3154
+ if (this.check("IDENTIFIER") && this.current().value === blockType) {
3155
+ this.advance();
3156
+ const blockName = this.expect("STRING", `Expected ${blockType} name`).value;
3157
+ const config = this.parseBlockContent();
3158
+ blocks.push({ name: blockName, config });
3159
+ } else {
3160
+ this.advance();
3161
+ }
3162
+ this.skipNewlines();
3163
+ }
3164
+ this.expect("RBRACE", "Expected }");
3165
+ return blocks;
3166
+ }
3167
+ /**
3168
+ * Parse composition block: composition "Name" { ... }
3169
+ */
3170
+ parseCompositionBlock() {
3171
+ const result = {
3172
+ systems: [],
3173
+ configs: [],
3174
+ children: [],
3175
+ properties: {}
3176
+ };
3177
+ if (!this.check("LBRACE")) {
3178
+ return result;
3179
+ }
3180
+ this.advance();
3181
+ this.skipNewlines();
3182
+ const childNodeKeywords = [
3183
+ "logic",
3184
+ "template",
3185
+ "environment",
3186
+ "state",
3187
+ "object",
3188
+ "composition",
3189
+ "system",
3190
+ "core_config",
3191
+ "narrative",
3192
+ "quest",
3193
+ "objective",
3194
+ "dialogue",
3195
+ "choice",
3196
+ "visual_metadata",
3197
+ "spatial_group",
3198
+ "scene",
3199
+ "group",
3200
+ "world",
3201
+ "module",
3202
+ "struct",
3203
+ "orb",
3204
+ "on_error",
3205
+ "assert",
3206
+ "topic",
3207
+ "channel",
3208
+ "config",
3209
+ "zone",
3210
+ "audio",
3211
+ "light",
3212
+ "npc",
3213
+ "camera",
3214
+ "timeline",
3215
+ "page",
3216
+ "include"
3217
+ ];
3218
+ while (!this.check("RBRACE") && !this.check("EOF")) {
3219
+ const currentDirectives = [];
3220
+ this.skipNewlines();
3221
+ if (this.check("RBRACE") || this.check("EOF")) break;
3222
+ while (this.check("AT")) {
3223
+ const directive = this.parseDirective();
3224
+ if (directive) {
3225
+ currentDirectives.push(directive);
3226
+ }
3227
+ this.skipNewlines();
3228
+ }
3229
+ const isNodeStart = this.check("IDENTIFIER") || this.check("STATE_MACHINE") || this.check("STATE") || this.check("TRANSITION") || this.check("INITIAL");
3230
+ if (isNodeStart) {
3231
+ const token = this.current();
3232
+ const next = this.peek(1);
3233
+ if (token.type === "IDENTIFIER" && token.value === "system" && (next.type === "IDENTIFIER" || next.type === "STRING") && this.peek(2).type !== "LBRACE") {
3234
+ const startToken = this.advance();
3235
+ const name = this.advance().value;
3236
+ result.systems.push({
3237
+ type: "system",
3238
+ name,
3239
+ id: name,
3240
+ properties: {},
3241
+ directives: currentDirectives,
3242
+ children: [],
3243
+ traits: /* @__PURE__ */ new Map(),
3244
+ loc: {
3245
+ start: { line: startToken.line, column: startToken.column },
3246
+ end: { line: this.current().line, column: this.current().column }
3247
+ }
3248
+ });
3249
+ } else if (token.type === "IDENTIFIER" && token.value === "page" && next.type === "STRING") {
3250
+ const startToken = this.advance();
3251
+ const name = this.advance().value;
3252
+ const properties = {};
3253
+ if (this.check("LBRACE")) {
3254
+ this.advance();
3255
+ this.skipNewlines();
3256
+ while (!this.check("RBRACE") && !this.check("EOF")) {
3257
+ this.skipNewlines();
3258
+ if (this.check("RBRACE") || this.check("EOF")) break;
3259
+ if (this.check("IDENTIFIER")) {
3260
+ const key = this.advance().value;
3261
+ if (this.check("COLON") || this.check("EQUALS")) {
3262
+ this.advance();
3263
+ properties[key] = this.parseValue();
3264
+ } else if (this.check("STRING")) {
3265
+ properties[key] = this.advance().value;
3266
+ } else {
3267
+ properties[key] = true;
3268
+ }
3269
+ } else if (this.check("COMMA")) {
3270
+ this.advance();
3271
+ } else {
3272
+ this.advance();
3273
+ }
3274
+ this.skipNewlines();
3275
+ }
3276
+ this.expect("RBRACE", "Expected }");
3277
+ }
3278
+ result.children.push({
3279
+ type: "page",
3280
+ name,
3281
+ id: name,
3282
+ properties,
3283
+ directives: currentDirectives,
3284
+ children: [],
3285
+ traits: /* @__PURE__ */ new Map(),
3286
+ loc: {
3287
+ start: { line: startToken.line, column: startToken.column },
3288
+ end: { line: this.current().line, column: this.current().column }
3289
+ }
3290
+ });
3291
+ } else if (next.type === "COLON" || next.type === "EQUALS") {
3292
+ const key = this.advance().value;
3293
+ this.advance();
3294
+ result.properties[key] = this.parseValue();
3295
+ } else if (childNodeKeywords.includes(token.value) && (next.type === "LBRACE" || next.type === "STRING" || next.type === "IDENTIFIER" || next.type === "HASH")) {
3296
+ const keyword = this.current().value;
3297
+ const node = this.parseNode();
3298
+ node.directives = [...currentDirectives, ...node.directives || []];
3299
+ if (keyword === "system" || node.type === "system") {
3300
+ result.systems.push(node);
3301
+ } else if (keyword === "core_config" || node.type === "core_config") {
3302
+ result.configs.push(node);
3303
+ } else {
3304
+ result.children.push(node);
3305
+ }
3306
+ } else if (!childNodeKeywords.includes(token.value) && (next.type === "STRING" || next.type === "NUMBER" || next.type === "BOOLEAN" || next.type === "NULL")) {
3307
+ const key = this.advance().value;
3308
+ result.properties[key] = this.parseValue();
3309
+ } else if (next.type === "LBRACE" || next.type === "IDENTIFIER" || next.type === "STRING" || next.type === "HASH") {
3310
+ const keyword = this.current().value;
3311
+ const node = this.parseNode();
3312
+ node.directives = [...currentDirectives, ...node.directives || []];
3313
+ if (keyword === "system" || node.type === "system") {
3314
+ result.systems.push(node);
3315
+ } else if (keyword === "core_config" || node.type === "core_config") {
3316
+ result.configs.push(node);
3317
+ } else {
3318
+ result.children.push(node);
3319
+ }
3320
+ } else if (next.type === "LPAREN") {
3321
+ const possibleMethod = this.pos;
3322
+ const methodName = this.advance().value;
3323
+ const params = [];
3324
+ this.advance();
3325
+ while (!this.check("RPAREN") && !this.check("EOF") && !this.check("LBRACE")) {
3326
+ if (this.check("IDENTIFIER")) {
3327
+ params.push(this.advance().value);
3328
+ } else {
3329
+ this.advance();
3330
+ }
3331
+ }
3332
+ if (this.check("RPAREN")) this.advance();
3333
+ let returnType = "unknown";
3334
+ if (this.check("COLON")) {
3335
+ this.advance();
3336
+ if (this.check("IDENTIFIER")) {
3337
+ returnType = this.advance().value;
3338
+ }
3339
+ }
3340
+ if (this.check("LBRACE")) {
3341
+ const body = this.parseCodeBlock();
3342
+ result.children.push({
3343
+ type: "method",
3344
+ name: methodName,
3345
+ params,
3346
+ returnType,
3347
+ body
3348
+ });
3349
+ } else {
3350
+ this.pos = possibleMethod;
3351
+ const key = this.advance().value;
3352
+ result.properties[key] = true;
3353
+ }
3354
+ } else {
3355
+ const key = this.advance().value;
3356
+ result.properties[key] = true;
3357
+ }
3358
+ } else if (currentDirectives.length > 0) {
3359
+ const fragment = {
3360
+ type: "fragment",
3361
+ directives: currentDirectives,
3362
+ children: [],
3363
+ traits: /* @__PURE__ */ new Map(),
3364
+ properties: {}
3365
+ };
3366
+ result.children.push(fragment);
3367
+ } else if (this.check("COMMA")) {
3368
+ this.advance();
3369
+ } else if (this.check("LBRACKET")) {
3370
+ let depth = 1;
3371
+ this.advance();
3372
+ while (depth > 0 && !this.check("EOF")) {
3373
+ if (this.check("LBRACKET")) depth++;
3374
+ else if (this.check("RBRACKET")) depth--;
3375
+ this.advance();
3376
+ }
3377
+ } else if (this.check("LBRACE")) {
3378
+ let depth = 1;
3379
+ this.advance();
3380
+ while (depth > 0 && !this.check("EOF")) {
3381
+ if (this.check("LBRACE")) depth++;
3382
+ else if (this.check("RBRACE")) depth--;
3383
+ this.advance();
3384
+ }
3385
+ } else {
3386
+ if (!this.check("RBRACE") && !this.check("EOF")) {
3387
+ this.error(
3388
+ `Unexpected token ${this.current().type} "${this.current().value}" in composition body. Expected property name, @directive, or child node`,
3389
+ "HSP101"
3390
+ );
3391
+ this.advance();
3392
+ }
3393
+ }
3394
+ this.skipNewlines();
3395
+ }
3396
+ this.expect("RBRACE", "Expected }");
3397
+ return result;
3398
+ }
3399
+ /**
3400
+ * Parse logic block: logic { function..., on_tick..., on_scene_load... }
3401
+ */
3402
+ parseLogicBlock() {
3403
+ const result = {
3404
+ functions: [],
3405
+ actions: [],
3406
+ eventHandlers: [],
3407
+ tickHandlers: []
3408
+ };
3409
+ if (!this.check("LBRACE")) {
3410
+ return result;
3411
+ }
3412
+ this.advance();
3413
+ this.skipNewlines();
3414
+ while (!this.check("RBRACE") && !this.check("EOF")) {
3415
+ this.skipNewlines();
3416
+ if (this.check("RBRACE") || this.check("EOF")) break;
3417
+ if (this.check("IDENTIFIER")) {
3418
+ const keyword = this.current().value;
3419
+ if (keyword === "function") {
3420
+ this.advance();
3421
+ const funcName = this.expect("IDENTIFIER", "Expected function name").value;
3422
+ const params = [];
3423
+ if (this.check("LPAREN")) {
3424
+ this.advance();
3425
+ while (!this.check("RPAREN") && !this.check("EOF")) {
3426
+ params.push(this.expect("IDENTIFIER", "Expected parameter").value);
3427
+ if (this.check("COLON")) {
3428
+ this.advance();
3429
+ this.expect("IDENTIFIER", "Expected type");
3430
+ }
3431
+ if (this.check("COMMA")) this.advance();
3432
+ }
3433
+ this.expect("RPAREN", "Expected )");
3434
+ }
3435
+ if (this.check("COLON")) {
3436
+ this.advance();
3437
+ this.expect("IDENTIFIER", "Expected return type");
3438
+ }
3439
+ const body = this.parseCodeBlock();
3440
+ result.functions.push({ name: funcName, params, body });
3441
+ } else if (keyword === "action") {
3442
+ this.advance();
3443
+ const actionName = this.check("IDENTIFIER") || this.check("STRING") ? this.advance().value : "anonymous";
3444
+ const params = [];
3445
+ if (this.check("LPAREN")) {
3446
+ this.advance();
3447
+ while (!this.check("RPAREN") && !this.check("EOF")) {
3448
+ if (this.check("IDENTIFIER")) {
3449
+ params.push(this.advance().value);
3450
+ if (this.check("COLON")) {
3451
+ this.advance();
3452
+ while (!this.check("COMMA") && !this.check("RPAREN") && !this.check("EOF")) {
3453
+ this.advance();
3454
+ }
3455
+ }
3456
+ if (this.check("COMMA")) {
3457
+ this.advance();
3458
+ }
3459
+ } else {
3460
+ this.advance();
3461
+ }
3462
+ }
3463
+ this.expect("RPAREN", "Expected )");
3464
+ }
3465
+ const body = this.check("LBRACE") ? this.parseCodeBlock() : "";
3466
+ result.actions.push({ name: actionName, params, body });
3467
+ } else if (keyword === "on_tick") {
3468
+ this.advance();
3469
+ let interval = 1;
3470
+ if (this.check("LPAREN")) {
3471
+ this.advance();
3472
+ const intervalToken = this.expect("NUMBER", "Expected interval");
3473
+ interval = parseFloat(intervalToken.value);
3474
+ this.expect("RPAREN", "Expected )");
3475
+ }
3476
+ const body = this.parseCodeBlock();
3477
+ result.tickHandlers.push({ interval, body });
3478
+ } else if (keyword === "on_scene_load") {
3479
+ this.advance();
3480
+ const body = this.parseCodeBlock();
3481
+ result.eventHandlers.push({ event: "scene_load", params: [], body });
3482
+ } else if (keyword === "on") {
3483
+ this.advance();
3484
+ let eventName = "";
3485
+ if (this.check("AT")) {
3486
+ this.advance();
3487
+ eventName = this.expect("IDENTIFIER", "Expected event namespace").value;
3488
+ if (this.check("DOT")) {
3489
+ this.advance();
3490
+ eventName += "." + this.expect("IDENTIFIER", "Expected event name").value;
3491
+ }
3492
+ } else {
3493
+ eventName = this.expect("IDENTIFIER", "Expected event name").value;
3494
+ }
3495
+ const params = [];
3496
+ if (this.check("LPAREN")) {
3497
+ this.advance();
3498
+ while (!this.check("RPAREN") && !this.check("EOF")) {
3499
+ params.push(this.expect("IDENTIFIER", "Expected parameter").value);
3500
+ if (this.check("COLON")) {
3501
+ this.advance();
3502
+ this.expect("IDENTIFIER", "Expected type");
3503
+ }
3504
+ if (this.check("COMMA")) this.advance();
3505
+ }
3506
+ this.expect("RPAREN", "Expected )");
3507
+ }
3508
+ const body = this.parseCodeBlock();
3509
+ result.eventHandlers.push({ event: eventName, params, body });
3510
+ } else if (keyword === "on_start") {
3511
+ this.advance();
3512
+ const params = [];
3513
+ if (this.check("LPAREN")) {
3514
+ this.advance();
3515
+ while (!this.check("RPAREN") && !this.check("EOF")) {
3516
+ params.push(this.expect("IDENTIFIER", "Expected parameter").value);
3517
+ if (this.check("COMMA")) this.advance();
3518
+ }
3519
+ this.expect("RPAREN", "Expected )");
3520
+ }
3521
+ const body = this.parseCodeBlock();
3522
+ result.eventHandlers.push({ event: "start", params, body });
3523
+ } else if (keyword === "on_event") {
3524
+ this.advance();
3525
+ let eventName = "";
3526
+ const params = [];
3527
+ if (this.check("LPAREN")) {
3528
+ this.advance();
3529
+ if (this.check("STRING")) {
3530
+ eventName = this.advance().value;
3531
+ } else {
3532
+ eventName = this.expect("IDENTIFIER", "Expected event name").value;
3533
+ }
3534
+ if (this.check("COMMA")) {
3535
+ this.advance();
3536
+ while (!this.check("RPAREN") && !this.check("EOF")) {
3537
+ params.push(this.expect("IDENTIFIER", "Expected parameter").value);
3538
+ if (this.check("COMMA")) this.advance();
3539
+ }
3540
+ }
3541
+ this.expect("RPAREN", "Expected )");
3542
+ }
3543
+ const body = this.parseCodeBlock();
3544
+ result.eventHandlers.push({ event: eventName, params, body });
3545
+ } else {
3546
+ this.advance();
3547
+ if (this.check("LPAREN")) this.skipParens();
3548
+ if (this.check("LBRACE")) this.skipBraces();
3549
+ while (!this.check("RBRACE") && !this.check("EOF") && !this.check("NEWLINE")) {
3550
+ this.advance();
3551
+ }
3552
+ }
3553
+ } else {
3554
+ this.advance();
3555
+ }
3556
+ this.skipNewlines();
3557
+ }
3558
+ this.expect("RBRACE", "Expected }");
3559
+ return result;
3560
+ }
3561
+ /**
3562
+ * Parse environment block with lighting directives
3563
+ */
3564
+ parseEnvironmentBlock() {
3565
+ const properties = {};
3566
+ const directives = [];
3567
+ if (!this.check("LBRACE")) {
3568
+ return { properties, directives };
3569
+ }
3570
+ this.advance();
3571
+ this.skipNewlines();
3572
+ while (!this.check("RBRACE") && !this.check("EOF")) {
3573
+ this.skipNewlines();
3574
+ if (this.check("RBRACE") || this.check("EOF")) break;
3575
+ if (this.check("AT")) {
3576
+ const directive = this.parseDirective();
3577
+ if (directive) {
3578
+ directives.push(directive);
3579
+ }
3580
+ } else if (this.check("IDENTIFIER")) {
3581
+ const key = this.advance().value;
3582
+ if (this.check("COLON") || this.check("EQUALS")) {
3583
+ this.advance();
3584
+ properties[key] = this.parseValue();
3585
+ } else {
3586
+ properties[key] = true;
3587
+ }
3588
+ } else {
3589
+ this.advance();
3590
+ }
3591
+ this.skipNewlines();
3592
+ }
3593
+ this.expect("RBRACE", "Expected }");
3594
+ return { properties, directives };
3595
+ }
3596
+ parsePropsBlock() {
3597
+ this.skipNewlines();
3598
+ const props = {};
3599
+ if (this.check("LBRACE")) {
3600
+ this.advance();
3601
+ this.skipNewlines();
3602
+ while (!this.check("RBRACE") && !this.check("EOF")) {
3603
+ if (this.check("SPREAD")) {
3604
+ this.advance();
3605
+ const val = this.parseValue();
3606
+ const spreadKey = `__spread_${Object.keys(props).length}`;
3607
+ props[spreadKey] = { type: "spread", argument: val };
3608
+ this.skipNewlines();
3609
+ if (this.check("COMMA")) this.advance();
3610
+ this.skipNewlines();
3611
+ continue;
3612
+ }
3613
+ const key = this.expect("IDENTIFIER", "Expected property name").value;
3614
+ if (this.check("COLON") || this.check("EQUALS")) {
3615
+ this.advance();
3616
+ props[key] = this.parseValue();
3617
+ } else {
3618
+ props[key] = true;
3619
+ }
3620
+ this.skipNewlines();
3621
+ if (this.check("COMMA")) this.advance();
3622
+ this.skipNewlines();
3623
+ }
3624
+ this.expect("RBRACE", "Expected }");
3625
+ }
3626
+ return props;
3627
+ }
3628
+ parseDialogBlock() {
3629
+ this.skipNewlines();
3630
+ const props = {};
3631
+ const options = [];
3632
+ if (this.check("LBRACE")) {
3633
+ this.advance();
3634
+ this.skipNewlines();
3635
+ while (!this.check("RBRACE") && !this.check("EOF")) {
3636
+ if (this.check("IDENTIFIER") && this.current().value === "option") {
3637
+ this.advance();
3638
+ const text = this.expect("STRING", "Expected option text").value;
3639
+ this.expect("ARROW", "Expected ->");
3640
+ let target;
3641
+ if (this.check("AT")) {
3642
+ const d = this.parseDirective();
3643
+ target = { type: "directive", value: d };
3644
+ } else {
3645
+ target = this.expect("STRING", "Expected target ID").value;
3646
+ }
3647
+ options.push({ text, target });
3648
+ } else {
3649
+ const key = this.expect("IDENTIFIER", "Expected property name").value;
3650
+ if (this.check("COLON") || this.check("EQUALS")) {
3651
+ this.advance();
3652
+ props[key] = this.parseValue();
3653
+ } else {
3654
+ props[key] = true;
3655
+ }
3656
+ }
3657
+ this.skipNewlines();
3658
+ }
3659
+ this.expect("RBRACE", "Expected }");
3660
+ }
3661
+ return { props, options };
3662
+ }
3663
+ parseTraitConfig() {
3664
+ const config = {};
3665
+ if (this.check("LPAREN")) {
3666
+ this.advance();
3667
+ this.skipNewlines();
3668
+ if (this.check("STRING") && (this.peek(1).type === "RPAREN" || this.peek(1).type === "COMMA")) {
3669
+ config["default"] = this.advance().value;
3670
+ if (this.check("COMMA")) this.advance();
3671
+ this.skipNewlines();
3672
+ }
3673
+ while (!this.check("RPAREN") && !this.check("EOF")) {
3674
+ this.skipNewlines();
3675
+ if (this.check("RPAREN") || this.check("EOF")) break;
3676
+ if (!this.check("IDENTIFIER")) {
3677
+ this.advance();
3678
+ continue;
3679
+ }
3680
+ const key = this.expect("IDENTIFIER", "Expected property name").value;
3681
+ if (this.check("COLON") || this.check("EQUALS")) {
3682
+ this.advance();
3683
+ config[key] = this.parseValue();
3684
+ } else {
3685
+ config[key] = true;
3686
+ }
3687
+ if (this.check("COMMA")) this.advance();
3688
+ this.skipNewlines();
3689
+ }
3690
+ this.expect("RPAREN", "Expected )");
3691
+ }
3692
+ return config;
3693
+ }
3694
+ parseStateBlock() {
3695
+ const state = {};
3696
+ if (this.check("LBRACE")) {
3697
+ this.advance();
3698
+ this.skipNewlines();
3699
+ while (!this.check("RBRACE") && !this.check("EOF")) {
3700
+ this.skipNewlines();
3701
+ if (this.check("RBRACE") || this.check("EOF")) break;
3702
+ if (this.check("SPREAD")) {
3703
+ this.advance();
3704
+ const spreadArg = this.parseValue();
3705
+ if (spreadArg === null) {
3706
+ this.error("Expected expression after spread operator (...) in state block", "HSP300");
3707
+ } else {
3708
+ const spreadKey = `__spread_${Object.keys(state).length}`;
3709
+ state[spreadKey] = { type: "spread", argument: spreadArg };
3710
+ }
3711
+ this.skipNewlines();
3712
+ continue;
3713
+ }
3714
+ const key = this.expect("IDENTIFIER", "Expected state variable name").value;
3715
+ if (this.check("COLON") || this.check("EQUALS")) {
3716
+ this.advance();
3717
+ state[key] = this.parseValue();
3718
+ } else {
3719
+ state[key] = true;
3720
+ }
3721
+ this.skipNewlines();
3722
+ }
3723
+ this.expect("RBRACE", "Expected }");
3724
+ }
3725
+ return state;
3726
+ }
3727
+ /**
3728
+ * Parse spatial state machine (Phase 13)
3729
+ */
3730
+ parseStateMachine() {
3731
+ const startToken = this.current();
3732
+ if (startToken.type === "STATE_MACHINE") {
3733
+ this.advance();
3734
+ }
3735
+ const name = this.expect("IDENTIFIER", "Expected state machine name").value;
3736
+ const states = [];
3737
+ const transitions = [];
3738
+ let initialState = "";
3739
+ this.expect("LBRACE", "Expected { after state machine name");
3740
+ this.skipNewlines();
3741
+ while (!this.check("RBRACE") && !this.check("EOF")) {
3742
+ this.skipNewlines();
3743
+ if (this.check("RBRACE") || this.check("EOF")) break;
3744
+ const current = this.current();
3745
+ if (current.type === "INITIAL" || current.value === "initial") {
3746
+ this.advance();
3747
+ this.expect("COLON", "Expected : after initial");
3748
+ initialState = this.expect("STRING", "Expected initial state name").value;
3749
+ } else if (current.type === "STATE" || current.value === "state") {
3750
+ states.push(this.parseStateNode());
3751
+ } else if (current.type === "TRANSITION" || current.value === "transitions") {
3752
+ transitions.push(...this.parseTransitionsBlock());
3753
+ } else {
3754
+ this.advance();
3755
+ }
3756
+ this.skipNewlines();
3757
+ }
3758
+ this.expect("RBRACE", "Expected } at end of state machine");
3759
+ return {
3760
+ type: "state-machine",
3761
+ name,
3762
+ initialState,
3763
+ states,
3764
+ transitions,
3765
+ loc: {
3766
+ start: { line: startToken.line, column: startToken.column },
3767
+ end: { line: this.current().line, column: this.current().column }
3768
+ }
3769
+ };
3770
+ }
3771
+ parseStateNode() {
3772
+ this.advance();
3773
+ const name = this.expect("IDENTIFIER", "Expected state name").value;
3774
+ let onEntry;
3775
+ let onExit;
3776
+ this.expect("LBRACE", "Expected { after state name");
3777
+ this.skipNewlines();
3778
+ while (!this.check("RBRACE") && !this.check("EOF")) {
3779
+ this.skipNewlines();
3780
+ if (this.check("RBRACE") || this.check("EOF")) break;
3781
+ const current = this.current();
3782
+ if (current.type === "ON_ENTRY" || current.value === "on_entry") {
3783
+ this.advance();
3784
+ onEntry = this.parseCodeBlock();
3785
+ } else if (current.type === "ON_EXIT" || current.value === "on_exit") {
3786
+ this.advance();
3787
+ onExit = this.parseCodeBlock();
3788
+ } else {
3789
+ this.advance();
3790
+ }
3791
+ this.skipNewlines();
3792
+ }
3793
+ this.expect("RBRACE", "Expected }");
3794
+ return { name, onEntry, onExit };
3795
+ }
3796
+ parseOnErrorNode() {
3797
+ const startToken = this.previous();
3798
+ const body = this.parseControlFlowBody();
3799
+ return {
3800
+ type: "on_error",
3801
+ body,
3802
+ loc: {
3803
+ start: { line: startToken.line, column: startToken.column },
3804
+ end: { line: this.current().line, column: this.current().column }
3805
+ }
3806
+ };
3807
+ }
3808
+ parseAssertNode() {
3809
+ const startToken = this.previous();
3810
+ this.expect("LPAREN", "Expected (");
3811
+ const condition = this.parseExpression();
3812
+ let message = "";
3813
+ if (this.match(["COMMA"])) {
3814
+ message = String(this.parseValue());
3815
+ }
3816
+ this.expect("RPAREN", "Expected )");
3817
+ return {
3818
+ type: "assert",
3819
+ condition,
3820
+ message,
3821
+ loc: {
3822
+ start: { line: startToken.line, column: startToken.column },
3823
+ end: { line: this.current().line, column: this.current().column }
3824
+ }
3825
+ };
3826
+ }
3827
+ parseTransitionsBlock() {
3828
+ const transitions = [];
3829
+ this.advance();
3830
+ this.expect("LBRACE", "Expected {");
3831
+ this.skipNewlines();
3832
+ while (!this.check("RBRACE") && !this.check("EOF")) {
3833
+ this.skipNewlines();
3834
+ if (this.check("RBRACE") || this.check("EOF")) break;
3835
+ const from = this.expect("IDENTIFIER", "Expected source state").value;
3836
+ this.expect("ARROW", "Expected ->");
3837
+ const to = this.expect("IDENTIFIER", "Expected target state").value;
3838
+ this.expect("COLON", "Expected :");
3839
+ const event = this.expect("IDENTIFIER", "Expected event name").value;
3840
+ transitions.push({ from, to, event });
3841
+ this.skipNewlines();
3842
+ }
3843
+ this.expect("RBRACE", "Expected }");
3844
+ return transitions;
3845
+ }
3846
+ parseControlFlowBody() {
3847
+ const nodes = [];
3848
+ if (this.check("LBRACE")) {
3849
+ this.advance();
3850
+ this.skipNewlines();
3851
+ while (!this.check("RBRACE") && !this.check("EOF")) {
3852
+ this.skipNewlines();
3853
+ if (this.check("RBRACE") || this.check("EOF")) break;
3854
+ if (this.check("AT")) {
3855
+ const directive = this.parseDirective();
3856
+ if (directive) {
3857
+ if (directive.type === "for" || directive.type === "while" || directive.type === "if" || directive.type === "forEach") {
3858
+ nodes.push({
3859
+ type: "fragment",
3860
+ directives: [directive],
3861
+ children: [],
3862
+ traits: /* @__PURE__ */ new Map(),
3863
+ properties: {}
3864
+ });
3865
+ } else if (directive.type === "trait") {
3866
+ this.warn(`Standalone trait @${directive.name} in block`);
3867
+ } else {
3868
+ nodes.push({
3869
+ type: "fragment",
3870
+ directives: [directive],
3871
+ children: [],
3872
+ traits: /* @__PURE__ */ new Map(),
3873
+ properties: {}
3874
+ });
3875
+ }
3876
+ }
3877
+ } else if (this.check("IDENTIFIER")) {
3878
+ nodes.push(this.parseNode());
3879
+ } else {
3880
+ this.advance();
3881
+ }
3882
+ this.skipNewlines();
3883
+ }
3884
+ this.expect("RBRACE", "Expected }");
3885
+ }
3886
+ return nodes;
3887
+ }
3888
+ parseCodeBlock() {
3889
+ let code = "";
3890
+ let braceDepth = 0;
3891
+ if (this.check("LBRACE")) {
3892
+ this.advance();
3893
+ braceDepth = 1;
3894
+ try {
3895
+ while (braceDepth > 0 && !this.check("EOF")) {
3896
+ const token = this.advance();
3897
+ if (token.type === "LBRACE") {
3898
+ braceDepth++;
3899
+ code += "{";
3900
+ } else if (token.type === "RBRACE") {
3901
+ braceDepth--;
3902
+ if (braceDepth > 0) {
3903
+ code += "}";
3904
+ }
3905
+ } else if (token.type === "STRING") {
3906
+ code += `"${token.value}"`;
3907
+ code += " ";
3908
+ } else {
3909
+ code += token.value;
3910
+ if (token.type === "NEWLINE") {
3911
+ code += "\n";
3912
+ } else {
3913
+ code += " ";
3914
+ }
3915
+ }
3916
+ }
3917
+ } catch (e) {
3918
+ const errorMessage = e instanceof Error ? e.message : String(e);
3919
+ if (errorMessage !== "ParseError") console.error(e);
3920
+ this.synchronize();
3921
+ }
3922
+ }
3923
+ return code.trim();
3924
+ }
3925
+ parseInlineExpression() {
3926
+ let expr = "";
3927
+ while (!this.check("NEWLINE") && !this.check("LBRACE") && !this.check("EOF")) {
3928
+ const token = this.advance();
3929
+ expr += token.value + " ";
3930
+ }
3931
+ return expr.trim();
3932
+ }
3933
+ /**
3934
+ * Parse any value or expression (Entry Point)
3935
+ * Handles operators like ?? and unary operators like ...
3936
+ */
3937
+ parseValue() {
3938
+ return this.parseAssignment();
3939
+ }
3940
+ /**
3941
+ * Parse assignment expressions (??=)
3942
+ * Much lower precedence than ternary/null-coalesce
3943
+ * Example: x ??= value → x = x ?? value
3944
+ */
3945
+ parseAssignment() {
3946
+ const expr = this.parseExpression();
3947
+ if (this.check("NULL_COALESCE_ASSIGN")) {
3948
+ const isAssignable = typeof expr === "string" || typeof expr === "object" && expr && "__ref" in expr || // identifier or member expression
3949
+ typeof expr === "object" && expr && "type" in expr && expr.type === "member";
3950
+ if (isAssignable) {
3951
+ this.advance();
3952
+ const value = this.parseExpression();
3953
+ return {
3954
+ type: "nullCoalescingAssignment",
3955
+ target: expr,
3956
+ value
3957
+ };
3958
+ } else {
3959
+ throw new Error(
3960
+ `Cannot use ??= on non-assignable expression at line ${this.current().line}`
3961
+ );
3962
+ }
3963
+ }
3964
+ return expr;
3965
+ }
3966
+ /**
3967
+ * Parse expression (Entry Point for operators)
3968
+ * Handles Ternary Operators: cond ? true : false
3969
+ */
3970
+ parseExpression() {
3971
+ const condition = this.parseNullCoalesce();
3972
+ if (this.check("QUESTION")) {
3973
+ this.advance();
3974
+ const trueValue = this.parseExpression();
3975
+ this.expect("COLON", "Expected : in ternary operator");
3976
+ const falseValue = this.parseExpression();
3977
+ return { type: "ternary", condition, trueValue, falseValue };
3978
+ }
3979
+ return condition;
3980
+ }
3981
+ /**
3982
+ * Parse binary expressions: ?? (null coalesce) — lower precedence than logical OR
3983
+ */
3984
+ parseNullCoalesce() {
3985
+ let left = this.parseLogicalOr();
3986
+ while (this.check("NULL_COALESCE")) {
3987
+ this.advance();
3988
+ const right = this.parseLogicalOr();
3989
+ left = { type: "binary", operator: "??", left, right };
3990
+ }
3991
+ return left;
3992
+ }
3993
+ /** Parse logical OR: a || b */
3994
+ parseLogicalOr() {
3995
+ let left = this.parseLogicalAnd();
3996
+ while (this.check("OR")) {
3997
+ this.advance();
3998
+ const right = this.parseLogicalAnd();
3999
+ left = { type: "binary", operator: "||", left, right };
4000
+ }
4001
+ return left;
4002
+ }
4003
+ /** Parse logical AND: a && b */
4004
+ parseLogicalAnd() {
4005
+ let left = this.parseEquality();
4006
+ while (this.check("AND")) {
4007
+ this.advance();
4008
+ const right = this.parseEquality();
4009
+ left = { type: "binary", operator: "&&", left, right };
4010
+ }
4011
+ return left;
4012
+ }
4013
+ /** Parse equality: a == b, a != b */
4014
+ parseEquality() {
4015
+ let left = this.parseComparison();
4016
+ while (this.check("DOUBLE_EQUALS") || this.check("NOT_EQUALS")) {
4017
+ const operator = this.current().value;
4018
+ this.advance();
4019
+ const right = this.parseComparison();
4020
+ left = { type: "binary", operator, left, right };
4021
+ }
4022
+ return left;
4023
+ }
4024
+ /** Parse comparison: a < b, a > b, a <= b, a >= b */
4025
+ parseComparison() {
4026
+ let left = this.parseAdditive();
4027
+ while (this.check("LESS_THAN") || this.check("GREATER_THAN") || this.check("LESS_EQUAL") || this.check("GREATER_EQUAL")) {
4028
+ const operator = this.current().value;
4029
+ this.advance();
4030
+ const right = this.parseAdditive();
4031
+ left = { type: "binary", operator, left, right };
4032
+ }
4033
+ return left;
4034
+ }
4035
+ /** Parse additive: a + b, a - b */
4036
+ parseAdditive() {
4037
+ let left = this.parseMultiplicative();
4038
+ while (this.check("PLUS") || this.check("MINUS")) {
4039
+ const operator = this.current().value;
4040
+ this.advance();
4041
+ const right = this.parseMultiplicative();
4042
+ left = { type: "binary", operator, left, right };
4043
+ }
4044
+ return left;
4045
+ }
4046
+ /** Parse multiplicative: a * b, a / b, a % b */
4047
+ parseMultiplicative() {
4048
+ let left = this.parseUnary();
4049
+ while (this.check("ASTERISK") || this.check("SLASH") || this.check("PERCENT")) {
4050
+ const operator = this.current().value;
4051
+ this.advance();
4052
+ const right = this.parseUnary();
4053
+ left = { type: "binary", operator, left, right };
4054
+ }
4055
+ return left;
4056
+ }
4057
+ /**
4058
+ * Parse unary prefix expressions (!, spread, unary minus, unary plus)
4059
+ */
4060
+ parseUnary() {
4061
+ if (this.check("SPREAD")) {
4062
+ this.advance();
4063
+ const arg = this.parseUnary();
4064
+ return { type: "spread", argument: arg };
4065
+ }
4066
+ if (this.check("EXCLAMATION")) {
4067
+ this.advance();
4068
+ const arg = this.parseUnary();
4069
+ return { type: "unary", operator: "!", argument: arg };
4070
+ }
4071
+ if (this.check("MINUS") || this.check("PLUS")) {
4072
+ const operator = this.current().type === "MINUS" ? "-" : "+";
4073
+ this.advance();
4074
+ const arg = this.parseUnary();
4075
+ if (typeof arg === "number") {
4076
+ return operator === "-" ? -arg : arg;
4077
+ }
4078
+ return { type: "unary", operator, argument: arg };
4079
+ }
4080
+ return this.parsePrimary();
4081
+ }
4082
+ /**
4083
+ * Parse a primary value (literal, identifier, parenthesis, etc.)
4084
+ */
4085
+ parsePrimary() {
4086
+ const token = this.current();
4087
+ if (token.type === "STRING") {
4088
+ this.advance();
4089
+ return token.value;
4090
+ }
4091
+ if (token.type === "NUMBER") {
4092
+ this.advance();
4093
+ const match = token.value.match(/^(-?\d+(?:\.\d+)?(?:e[+-]?\d+)?)(.*)?$/i);
4094
+ if (match) {
4095
+ const num = parseFloat(match[1]);
4096
+ const unit = match[2];
4097
+ if (unit) {
4098
+ return `${num}${unit}`;
4099
+ }
4100
+ return num;
4101
+ }
4102
+ return parseFloat(token.value);
4103
+ }
4104
+ if (token.type === "BOOLEAN") {
4105
+ this.advance();
4106
+ return token.value === "true";
4107
+ }
4108
+ if (token.type === "NULL") {
4109
+ this.advance();
4110
+ return null;
4111
+ }
4112
+ if (token.type === "EXPRESSION") {
4113
+ this.advance();
4114
+ const exprId = `expr_${this.compiledExpressions.size}`;
4115
+ this.compiledExpressions.set(exprId, token.value);
4116
+ return { __expr: exprId, __raw: token.value };
4117
+ }
4118
+ if (token.type === "TEMPLATE_STRING") {
4119
+ this.advance();
4120
+ return { type: "templateLiteral", value: token.value };
4121
+ }
4122
+ if (token.type === "LBRACKET") {
4123
+ return this.parseArray();
4124
+ }
4125
+ if (token.type === "LBRACE") {
4126
+ return this.parseBlockContent();
4127
+ }
4128
+ if (token.type === "HASH") {
4129
+ this.advance();
4130
+ const nextToken = this.current();
4131
+ if (nextToken.type === "IDENTIFIER" || nextToken.type === "NUMBER") {
4132
+ const hexValue = this.advance().value;
4133
+ return `#${hexValue}`;
4134
+ }
4135
+ return `#`;
4136
+ }
4137
+ if (token.type === "THIS") {
4138
+ this.advance();
4139
+ let ref = "this";
4140
+ while (this.check("DOT")) {
4141
+ this.advance();
4142
+ const part = this.expect("IDENTIFIER", "Expected property name").value;
4143
+ ref += "." + part;
4144
+ }
4145
+ return { __ref: ref };
4146
+ }
4147
+ if (token.type === "LPAREN") {
4148
+ let isArrow = false;
4149
+ let i = 1;
4150
+ let parenDepth = 1;
4151
+ while (this.peek(i).type !== "EOF") {
4152
+ const t = this.peek(i);
4153
+ if (t.type === "LPAREN") parenDepth++;
4154
+ if (t.type === "RPAREN") {
4155
+ parenDepth--;
4156
+ if (parenDepth === 0) {
4157
+ const next = this.peek(i + 1);
4158
+ if (next.type === "ARROW") isArrow = true;
4159
+ if (next.type === "COLON") {
4160
+ let j = i + 2;
4161
+ while (this.peek(j).type === "IDENTIFIER" || this.peek(j).type === "LBRACKET" || this.peek(j).type === "RBRACKET")
4162
+ j++;
4163
+ if (this.peek(j).type === "ARROW") isArrow = true;
4164
+ }
4165
+ break;
4166
+ }
4167
+ }
4168
+ i++;
4169
+ }
4170
+ if (isArrow) {
4171
+ return this.parseArrowFunction();
4172
+ }
4173
+ return this.parseParenExpression();
4174
+ }
4175
+ if (token.type === "MATCH") {
4176
+ return this.parseMatchExpression();
4177
+ }
4178
+ const isIdentifierLike = token.type === "IDENTIFIER" || token.type === "STATE" || token.type === "INITIAL" || token.type === "STATE_MACHINE" || token.type === "TRANSITION" || token.type === "ON_ENTRY" || token.type === "ON_EXIT";
4179
+ if (isIdentifierLike) {
4180
+ if (this.peek(1).type === "ARROW") {
4181
+ return this.parseArrowFunction();
4182
+ }
4183
+ this.advance();
4184
+ let ref = token.value;
4185
+ while (this.check("DOT") || this.check("OPTIONAL_DOT") || this.check("LBRACKET")) {
4186
+ if (this.check("OPTIONAL_DOT")) {
4187
+ this.advance();
4188
+ const nextToken = this.current();
4189
+ const isPropertyName = nextToken.type === "IDENTIFIER" || nextToken.type === "STATE" || nextToken.type === "INITIAL" || nextToken.type === "STATE_MACHINE" || nextToken.type === "TRANSITION" || nextToken.type === "ON_ENTRY" || nextToken.type === "ON_EXIT";
4190
+ if (isPropertyName) {
4191
+ ref += "?." + this.advance().value;
4192
+ } else {
4193
+ this.error("Expected property name after optional chaining (?.)", "HSP002");
4194
+ }
4195
+ } else if (this.check("LBRACKET")) {
4196
+ this.advance();
4197
+ const indexExpr = this.parseValue();
4198
+ this.expect("RBRACKET", "Expected ]");
4199
+ const base = ref;
4200
+ return { type: "computedMember", object: { __ref: base }, property: indexExpr };
4201
+ } else {
4202
+ this.advance();
4203
+ const nextToken = this.current();
4204
+ const isPropertyName = nextToken.type === "IDENTIFIER" || nextToken.type === "STATE" || nextToken.type === "INITIAL" || nextToken.type === "STATE_MACHINE" || nextToken.type === "TRANSITION" || nextToken.type === "ON_ENTRY" || nextToken.type === "ON_EXIT";
4205
+ if (isPropertyName) {
4206
+ ref += "." + this.advance().value;
4207
+ } else {
4208
+ this.error("Expected property name after dot (.)", "HSP002");
4209
+ }
4210
+ }
4211
+ }
4212
+ if (this.check("LPAREN")) {
4213
+ const args = this.parseParenExpression();
4214
+ return { type: "call", callee: ref, args };
4215
+ }
4216
+ return { __ref: ref };
4217
+ }
4218
+ if (this.check("AT")) {
4219
+ const dir = this.parseDirective();
4220
+ return dir;
4221
+ }
4222
+ this.error(
4223
+ `Unexpected token in expression: ${token.type} "${token.value}". Expected value, identifier, or expression`,
4224
+ "HSP300"
4225
+ );
4226
+ const err = new Error("ParseError");
4227
+ err.message = "ParseError";
4228
+ throw err;
4229
+ }
4230
+ parseParenExpression() {
4231
+ this.expect("LPAREN", "Expected (");
4232
+ const items = [];
4233
+ while (!this.check("RPAREN") && !this.check("EOF")) {
4234
+ items.push(this.parseValue());
4235
+ if (this.check("COMMA")) this.advance();
4236
+ }
4237
+ this.expect("RPAREN", "Expected )");
4238
+ return items.length === 1 ? items[0] : items;
4239
+ }
4240
+ parseArrowFunction() {
4241
+ const params = [];
4242
+ if (this.check("LPAREN")) {
4243
+ this.advance();
4244
+ while (!this.check("RPAREN") && !this.check("EOF")) {
4245
+ if (this.check("SPREAD")) {
4246
+ this.advance();
4247
+ const name2 = this.expect("IDENTIFIER", "Expected parameter name after ...").value;
4248
+ let type2 = null;
4249
+ if (this.check("COLON")) {
4250
+ this.advance();
4251
+ type2 = this.expect("IDENTIFIER", "Expected type").value;
4252
+ }
4253
+ params.push({ name: name2, type: type2, rest: true });
4254
+ if (this.check("COMMA")) this.advance();
4255
+ break;
4256
+ }
4257
+ const name = this.expect("IDENTIFIER", "Expected parameter name").value;
4258
+ let type = null;
4259
+ if (this.check("COLON")) {
4260
+ this.advance();
4261
+ type = this.expect("IDENTIFIER", "Expected type").value;
4262
+ }
4263
+ params.push({ name, type });
4264
+ if (this.check("COMMA")) this.advance();
4265
+ }
4266
+ this.expect("RPAREN", "Expected )");
4267
+ } else {
4268
+ if (this.check("SPREAD")) {
4269
+ this.advance();
4270
+ const name = this.expect("IDENTIFIER", "Expected parameter name after ...").value;
4271
+ params.push({ name, type: null, rest: true });
4272
+ } else {
4273
+ const name = this.expect("IDENTIFIER", "Expected parameter name").value;
4274
+ params.push({ name, type: null });
4275
+ }
4276
+ }
4277
+ let returnType = null;
4278
+ if (this.check("COLON")) {
4279
+ this.advance();
4280
+ returnType = this.expect("IDENTIFIER", "Expected return type").value;
4281
+ }
4282
+ this.expect("ARROW", "Expected =>");
4283
+ let body;
4284
+ if (this.check("LBRACE")) {
4285
+ body = this.parseCodeBlock();
4286
+ } else {
4287
+ body = this.parseInlineExpression();
4288
+ }
4289
+ return { type: "arrow_function", params, returnType, body };
4290
+ }
4291
+ parseArray() {
4292
+ const arr = [];
4293
+ this.expect("LBRACKET", "Expected [");
4294
+ this.skipNewlines();
4295
+ while (!this.check("RBRACKET") && !this.check("EOF")) {
4296
+ const beforePos = this.pos;
4297
+ this.skipNewlines();
4298
+ if (this.check("RBRACKET") || this.check("EOF")) break;
4299
+ if (this.check("SPREAD")) {
4300
+ this.advance();
4301
+ const spreadArg = this.parseValue();
4302
+ if (spreadArg === null) {
4303
+ this.error(
4304
+ "Expected expression after spread operator (...) in array. Example: [...items]",
4305
+ "HSP300"
4306
+ );
4307
+ } else {
4308
+ arr.push({ type: "spread", argument: spreadArg });
4309
+ }
4310
+ } else {
4311
+ const value = this.parseValue();
4312
+ if (value !== null) {
4313
+ arr.push(value);
4314
+ } else if (this.pos === beforePos) {
4315
+ this.advance();
4316
+ }
4317
+ }
4318
+ if (this.check("COMMA")) this.advance();
4319
+ this.skipNewlines();
4320
+ }
4321
+ this.expect("RBRACKET", "Expected ]");
4322
+ return arr;
4323
+ }
4324
+ parseObject() {
4325
+ const obj = {};
4326
+ this.expect("LBRACE", "Expected {");
4327
+ this.skipNewlines();
4328
+ while (!this.check("RBRACE") && !this.check("EOF")) {
4329
+ this.skipNewlines();
4330
+ if (this.check("RBRACE") || this.check("EOF")) break;
4331
+ if (this.check("SPREAD")) {
4332
+ this.advance();
4333
+ const spreadArg = this.parseValue();
4334
+ if (spreadArg === null) {
4335
+ this.error(
4336
+ "Expected expression after spread operator (...) in object. Example: {...template}",
4337
+ "HSP300"
4338
+ );
4339
+ } else {
4340
+ const spreadKey = `__spread_${Object.keys(obj).length}`;
4341
+ obj[spreadKey] = { type: "spread", argument: spreadArg };
4342
+ }
4343
+ } else if (this.check("IDENTIFIER")) {
4344
+ const key = this.advance().value;
4345
+ if (this.check("COLON") || this.check("EQUALS")) {
4346
+ this.advance();
4347
+ obj[key] = this.parseValue();
4348
+ } else {
4349
+ obj[key] = true;
4350
+ }
4351
+ } else {
4352
+ this.advance();
4353
+ continue;
4354
+ }
4355
+ if (this.check("COMMA")) this.advance();
4356
+ this.skipNewlines();
4357
+ }
4358
+ this.expect("RBRACE", "Expected }");
4359
+ return obj;
4360
+ }
4361
+ /**
4362
+ * Parse a match expression: match subject { pattern => body, ... }
4363
+ * Supports:
4364
+ * - Literal patterns: "idle", 42, true
4365
+ * - Wildcard pattern: _
4366
+ * - Binding patterns: x (captures value)
4367
+ * - Guard clauses: pattern if condition => body
4368
+ */
4369
+ parseMatchExpression() {
4370
+ const startToken = this.current();
4371
+ this.expect("MATCH", "Expected match keyword");
4372
+ const subject = this.parseValue();
4373
+ if (subject === null) {
4374
+ this.error("Expected expression after match keyword", "HSP300");
4375
+ return null;
4376
+ }
4377
+ this.expect("LBRACE", "Expected { after match subject");
4378
+ this.skipNewlines();
4379
+ const cases = [];
4380
+ let hasWildcard = false;
4381
+ while (!this.check("RBRACE") && !this.check("EOF")) {
4382
+ this.skipNewlines();
4383
+ if (this.check("RBRACE")) break;
4384
+ const caseNode = this.parseMatchCase();
4385
+ if (caseNode) {
4386
+ cases.push(caseNode);
4387
+ if (caseNode.pattern && caseNode.pattern.type === "wildcard-pattern") {
4388
+ hasWildcard = true;
4389
+ }
4390
+ }
4391
+ if (this.check("COMMA")) this.advance();
4392
+ this.skipNewlines();
4393
+ }
4394
+ this.expect("RBRACE", "Expected } to close match expression");
4395
+ return {
4396
+ type: "match",
4397
+ subject,
4398
+ cases,
4399
+ hasWildcard,
4400
+ sourceLocation: {
4401
+ line: startToken.line,
4402
+ column: startToken.column
4403
+ }
4404
+ };
4405
+ }
4406
+ /**
4407
+ * Parse a single match case: pattern [if guard] => body
4408
+ */
4409
+ parseMatchCase() {
4410
+ const pattern = this.parseMatchPattern();
4411
+ if (!pattern) {
4412
+ return null;
4413
+ }
4414
+ let guard;
4415
+ if (this.check("IDENTIFIER") && this.current().value === "if") {
4416
+ this.advance();
4417
+ let guardExpr = "";
4418
+ while (!this.check("ARROW") && !this.check("EOF") && !this.check("RBRACE")) {
4419
+ guardExpr += this.current().value + " ";
4420
+ this.advance();
4421
+ }
4422
+ guard = guardExpr.trim();
4423
+ }
4424
+ this.expect("ARROW", "Expected => after match pattern");
4425
+ let body;
4426
+ if (this.check("LBRACE")) {
4427
+ body = this.parseBlockContent();
4428
+ } else {
4429
+ body = this.parseValue();
4430
+ }
4431
+ return {
4432
+ type: "match-case",
4433
+ pattern,
4434
+ body,
4435
+ guard
4436
+ };
4437
+ }
4438
+ /**
4439
+ * Parse a match pattern:
4440
+ * - Literal: "string", 42, true
4441
+ * - Wildcard: _
4442
+ * - Binding: identifier
4443
+ */
4444
+ parseMatchPattern() {
4445
+ const token = this.current();
4446
+ if (token.type === "UNDERSCORE" || token.type === "IDENTIFIER" && token.value === "_") {
4447
+ this.advance();
4448
+ return {
4449
+ type: "wildcard-pattern",
4450
+ symbol: "_"
4451
+ };
4452
+ }
4453
+ if (token.type === "STRING") {
4454
+ this.advance();
4455
+ return {
4456
+ type: "literal-pattern",
4457
+ value: token.value
4458
+ };
4459
+ }
4460
+ if (token.type === "NUMBER") {
4461
+ this.advance();
4462
+ return {
4463
+ type: "literal-pattern",
4464
+ value: parseFloat(token.value)
4465
+ };
4466
+ }
4467
+ if (token.type === "BOOLEAN") {
4468
+ this.advance();
4469
+ return {
4470
+ type: "literal-pattern",
4471
+ value: token.value === "true"
4472
+ };
4473
+ }
4474
+ if (token.type === "IDENTIFIER") {
4475
+ this.advance();
4476
+ return {
4477
+ type: "binding-pattern",
4478
+ name: token.value
4479
+ };
4480
+ }
4481
+ if (token.type === "NULL") {
4482
+ this.advance();
4483
+ return {
4484
+ type: "literal-pattern",
4485
+ value: null
4486
+ };
4487
+ }
4488
+ this.error(`Expected match pattern (literal, identifier, or _), got ${token.type}`, "HSP300");
4489
+ return null;
4490
+ }
4491
+ current() {
4492
+ return this.tokens[this.pos] || { type: "EOF", value: "", line: 0, column: 0 };
4493
+ }
4494
+ peek(offset = 0) {
4495
+ return this.tokens[this.pos + offset] || { type: "EOF", value: "", line: 0, column: 0 };
4496
+ }
4497
+ check(type) {
4498
+ return this.current().type === type;
4499
+ }
4500
+ advance() {
4501
+ const token = this.current();
4502
+ if (this.pos < this.tokens.length) {
4503
+ this.pos++;
4504
+ }
4505
+ return token;
4506
+ }
4507
+ previous() {
4508
+ return this.tokens[this.pos - 1] || this.current();
4509
+ }
4510
+ match(types) {
4511
+ for (const type of types) {
4512
+ if (this.check(type)) {
4513
+ return this.advance();
4514
+ }
4515
+ }
4516
+ return null;
4517
+ }
4518
+ expect(type, message) {
4519
+ if (!this.check(type)) {
4520
+ const current = this.current();
4521
+ const fullMessage = `${message}. Got ${current.type} "${current.value}"`;
4522
+ let errorCode = "HSP001";
4523
+ let suggestion;
4524
+ switch (type) {
4525
+ case "RBRACE":
4526
+ errorCode = "HSP004";
4527
+ suggestion = "Check for matching opening brace { and ensure all blocks are properly closed";
4528
+ break;
4529
+ case "RBRACKET":
4530
+ errorCode = "HSP005";
4531
+ suggestion = "Check for matching opening bracket [ and ensure all arrays are properly closed";
4532
+ break;
4533
+ case "RPAREN":
4534
+ errorCode = "HSP006";
4535
+ suggestion = "Check for matching opening parenthesis ( and ensure all expressions are properly closed";
4536
+ break;
4537
+ case "COLON":
4538
+ errorCode = "HSP009";
4539
+ suggestion = "Properties use colon syntax: propertyName: value";
4540
+ break;
4541
+ case "IDENTIFIER":
4542
+ errorCode = "HSP002";
4543
+ if (current.type === "IDENTIFIER") {
4544
+ const similar = findSimilarKeyword(current.value);
4545
+ if (similar) {
4546
+ suggestion = `Did you mean '${similar}'?`;
4547
+ }
4548
+ }
4549
+ break;
4550
+ case "LBRACE":
4551
+ errorCode = "HSP100";
4552
+ suggestion = "Expected opening brace { to start block";
4553
+ break;
4554
+ default:
4555
+ errorCode = "HSP001";
4556
+ }
4557
+ if (suggestion) {
4558
+ this.errorWithSuggestion(fullMessage, suggestion, errorCode);
4559
+ } else {
4560
+ this.error(fullMessage, errorCode);
4561
+ }
4562
+ if (type === "RBRACE" || type === "LBRACE" || type === "IDENTIFIER") {
4563
+ this.synchronize();
4564
+ }
4565
+ return current;
4566
+ }
4567
+ return this.advance();
4568
+ }
4569
+ skipNewlines() {
4570
+ while (this.check("NEWLINE") || this.check("INDENT") || this.check("DEDENT")) {
4571
+ this.advance();
4572
+ }
4573
+ }
4574
+ /** Skip a balanced parenthesised list ( ... ) including nested parens */
4575
+ skipParens() {
4576
+ if (!this.check("LPAREN")) return;
4577
+ this.advance();
4578
+ let depth = 1;
4579
+ while (depth > 0 && !this.check("EOF")) {
4580
+ if (this.check("LPAREN")) depth++;
4581
+ if (this.check("RPAREN")) depth--;
4582
+ this.advance();
4583
+ }
4584
+ }
4585
+ skipBraces() {
4586
+ if (!this.check("LBRACE")) return;
4587
+ this.advance();
4588
+ let depth = 1;
4589
+ while (depth > 0 && !this.check("EOF")) {
4590
+ if (this.check("LBRACE")) depth++;
4591
+ if (this.check("RBRACE")) depth--;
4592
+ this.advance();
4593
+ }
4594
+ }
4595
+ error(message, code = "HSP001") {
4596
+ const token = this.current();
4597
+ const line = token.line;
4598
+ const column = token.column;
4599
+ let suggestion;
4600
+ if (token.type === "IDENTIFIER") {
4601
+ const similar = findSimilarKeyword(token.value);
4602
+ if (similar) {
4603
+ suggestion = `Did you mean '${similar}'?`;
4604
+ }
4605
+ }
4606
+ this.errors.push(
4607
+ createRichError(code, message, line, column, {
4608
+ source: this.source,
4609
+ suggestion,
4610
+ severity: "error"
4611
+ })
4612
+ );
4613
+ }
4614
+ errorWithSuggestion(message, suggestion, code = "HSP001") {
4615
+ const token = this.current();
4616
+ this.errors.push(
4617
+ createRichError(code, message, token.line, token.column, {
4618
+ source: this.source,
4619
+ suggestion,
4620
+ severity: "error"
4621
+ })
4622
+ );
4623
+ }
4624
+ traitError(traitName) {
4625
+ const token = this.current();
4626
+ this.errors.push(createTraitError(traitName, token.line, token.column, this.source));
4627
+ }
4628
+ warn(message, code = "HSP001") {
4629
+ const token = this.current();
4630
+ this.warnings.push(
4631
+ createRichError(code, message, token.line, token.column, {
4632
+ source: this.source,
4633
+ severity: "warning"
4634
+ })
4635
+ );
4636
+ }
4637
+ /**
4638
+ * Detect common mistakes and provide context-aware error messages
4639
+ */
4640
+ detectCommonMistake() {
4641
+ const current = this.current();
4642
+ const prev = this.pos > 0 ? this.tokens[this.pos - 1] : null;
4643
+ const next = this.pos + 1 < this.tokens.length ? this.tokens[this.pos + 1] : null;
4644
+ if (current.type === "EQUALS" && prev?.type === "IDENTIFIER") {
4645
+ return {
4646
+ message: `Unexpected '=' after property name '${prev.value}'`,
4647
+ suggestion: "Use ':' instead of '=' for property assignment. Example: propertyName: value",
4648
+ code: "HSP009"
4649
+ };
4650
+ }
4651
+ if (current.value === ";") {
4652
+ return {
4653
+ message: "Unexpected semicolon",
4654
+ suggestion: "HoloScript does not require semicolons. Remove the semicolon to continue.",
4655
+ code: "HSP001"
4656
+ };
4657
+ }
4658
+ if (current.type === "IDENTIFIER" && chunkWRLUBRKS_cjs.VR_TRAITS.includes(current.value)) {
4659
+ if (prev?.type !== "AT") {
4660
+ return {
4661
+ message: `'${current.value}' is a trait and requires '@' prefix`,
4662
+ suggestion: `Use '@${current.value}' to apply this trait`,
4663
+ code: "HSP200"
4664
+ };
4665
+ }
4666
+ }
4667
+ if (current.type === "STRING" && next?.type === "COLON") {
4668
+ return {
4669
+ message: "Property names should not be quoted in HoloScript",
4670
+ suggestion: `Remove quotes: use ${current.value.replace(/['"]/g, "")}: instead of "${current.value}":`,
4671
+ code: "HSP101"
4672
+ };
4673
+ }
4674
+ if (current.value === "function" && prev?.type === "COLON") {
4675
+ return {
4676
+ message: "Unexpected 'function' keyword",
4677
+ suggestion: "Use arrow function syntax: handler: (args) => { ... }",
4678
+ code: "HSP300"
4679
+ };
4680
+ }
4681
+ if (current.type === "SPREAD" && next && (next.type === "RBRACE" || next.type === "RBRACKET" || next.type === "COMMA" || next.type === "NEWLINE")) {
4682
+ return {
4683
+ message: "Spread operator (...) requires a target expression",
4684
+ suggestion: "Provide an expression to spread: ...targetObject or ...targetArray",
4685
+ code: "HSP002"
4686
+ };
4687
+ }
4688
+ return null;
4689
+ }
4690
+ /**
4691
+ * Enhanced error reporting with common mistake detection
4692
+ */
4693
+ errorWithContext(message, code = "HSP001") {
4694
+ const commonMistake = this.detectCommonMistake();
4695
+ if (commonMistake) {
4696
+ this.errorWithSuggestion(commonMistake.message, commonMistake.suggestion, commonMistake.code);
4697
+ return;
4698
+ }
4699
+ this.error(message, code);
4700
+ }
4701
+ /**
4702
+ * Synchronize parser state after an error
4703
+ * Skips tokens until a potential recovery point (newline followed by keyword/directive)
4704
+ */
4705
+ synchronize() {
4706
+ this.advance();
4707
+ while (!this.check("EOF")) {
4708
+ if (this.check("RBRACE")) {
4709
+ return;
4710
+ }
4711
+ if (this.check("IDENTIFIER") && ["orb", "template", "logic", "object", "composition", "scene", "group"].includes(
4712
+ this.current().value
4713
+ )) {
4714
+ return;
4715
+ }
4716
+ if (this.check("AT")) {
4717
+ return;
4718
+ }
4719
+ this.advance();
4720
+ }
4721
+ }
4722
+ /**
4723
+ * Mini-sync for property lists: skips until next line or comma
4724
+ */
4725
+ synchronizeProperty() {
4726
+ this.advance();
4727
+ while (!this.check("EOF")) {
4728
+ if (this.check("RBRACE") || this.check("LBRACE")) {
4729
+ return;
4730
+ }
4731
+ if (this.check("IDENTIFIER") || this.check("STRING") || this.check("SPREAD") || this.check("AT")) {
4732
+ return;
4733
+ }
4734
+ if (this.check("NEWLINE")) {
4735
+ this.advance();
4736
+ this.skipNewlines();
4737
+ if (this.check("IDENTIFIER") || this.check("STRING") || this.check("SPREAD") || this.check("AT")) {
4738
+ return;
4739
+ }
4740
+ }
4741
+ if (this.check("COMMA")) {
4742
+ this.advance();
4743
+ return;
4744
+ }
4745
+ this.advance();
4746
+ }
4747
+ }
4748
+ /**
4749
+ * Synchronize for array context: skip to next valid array element or closing bracket
4750
+ */
4751
+ synchronizeArray() {
4752
+ while (!this.check("EOF")) {
4753
+ if (this.check("RBRACKET")) {
4754
+ return;
4755
+ }
4756
+ if (this.check("COMMA")) {
4757
+ this.advance();
4758
+ this.skipNewlines();
4759
+ return;
4760
+ }
4761
+ if (this.check("NEWLINE")) {
4762
+ this.advance();
4763
+ this.skipNewlines();
4764
+ if (this.check("RBRACKET") || this.isLikelyValue(this.current()) || this.check("SPREAD")) {
4765
+ return;
4766
+ }
4767
+ }
4768
+ this.advance();
4769
+ }
4770
+ }
4771
+ /**
4772
+ * Synchronize for expression context: skip to end of expression
4773
+ */
4774
+ synchronizeExpression() {
4775
+ let parenDepth = 0;
4776
+ let braceDepth = 0;
4777
+ let bracketDepth = 0;
4778
+ while (!this.check("EOF")) {
4779
+ const token = this.current();
4780
+ if (token.type === "LPAREN") parenDepth++;
4781
+ else if (token.type === "RPAREN") {
4782
+ if (parenDepth === 0) return;
4783
+ parenDepth--;
4784
+ } else if (token.type === "LBRACE") braceDepth++;
4785
+ else if (token.type === "RBRACE") {
4786
+ if (braceDepth === 0) return;
4787
+ braceDepth--;
4788
+ } else if (token.type === "LBRACKET") bracketDepth++;
4789
+ else if (token.type === "RBRACKET") {
4790
+ if (bracketDepth === 0) return;
4791
+ bracketDepth--;
4792
+ }
4793
+ if (parenDepth === 0 && braceDepth === 0 && bracketDepth === 0) {
4794
+ if (this.check("NEWLINE") || this.check("COMMA")) {
4795
+ return;
4796
+ }
4797
+ }
4798
+ this.advance();
4799
+ }
4800
+ }
4801
+ /**
4802
+ * Attempt to recover from missing colon by looking ahead
4803
+ * Returns true if recovery was successful
4804
+ */
4805
+ tryRecoverMissingColon() {
4806
+ if (this.check("IDENTIFIER")) {
4807
+ const nextPos = this.pos + 1;
4808
+ if (nextPos < this.tokens.length) {
4809
+ const nextToken = this.tokens[nextPos];
4810
+ if (this.isLikelyValue(nextToken) || nextToken.type === "IDENTIFIER") {
4811
+ this.warn(
4812
+ `Missing colon after property "${this.current().value}". Consider adding ':' between property name and value`,
4813
+ "HSP009"
4814
+ );
4815
+ return true;
4816
+ }
4817
+ }
4818
+ }
4819
+ return false;
4820
+ }
4821
+ /**
4822
+ * Helper to check if current token is a natural boundary after a value
4823
+ */
4824
+ isValueBoundary() {
4825
+ return this.check("NEWLINE") || this.check("RBRACE") || this.check("COMMA") || this.check("IDENTIFIER") || this.check("SPREAD") || this.check("AT") || this.check("EOF");
4826
+ }
4827
+ /**
4828
+ * Helper to check if a token is likely the start of a value
4829
+ */
4830
+ isLikelyValue(token) {
4831
+ return token.type === "STRING" || token.type === "NUMBER" || token.type === "LBRACKET" || token.type === "LBRACE" || token.type === "BOOLEAN" || token.type === "NULL" || token.type === "TEMPLATE_STRING";
4832
+ }
4833
+ /**
4834
+ * Parse a block of raw code (balanced braces)
4835
+ */
4836
+ parseRawBlock() {
4837
+ const startToken = this.expect("LBRACE", "Expected {");
4838
+ const startOffset = startToken.offset + 1;
4839
+ let braceDepth = 1;
4840
+ let endOffset = startOffset;
4841
+ while (braceDepth > 0 && this.pos < this.tokens.length) {
4842
+ const token = this.current();
4843
+ if (token.type === "EOF") break;
4844
+ if (token.type === "LBRACE") {
4845
+ braceDepth++;
4846
+ } else if (token.type === "RBRACE") {
4847
+ braceDepth--;
4848
+ if (braceDepth === 0) {
4849
+ endOffset = token.offset;
4850
+ break;
4851
+ }
4852
+ }
4853
+ this.advance();
4854
+ }
4855
+ this.expect("RBRACE", "Expected }");
4856
+ return this.source.substring(startOffset, endOffset).trim();
4857
+ }
4858
+ };
4859
+ function createParser(options) {
4860
+ return new HoloScriptPlusParser(options);
4861
+ }
4862
+ function parse(source, options) {
4863
+ const parser = createParser(options);
4864
+ return parser.parse(source);
4865
+ }
4866
+
4867
+ exports.ChunkBasedIncrementalParser = ChunkBasedIncrementalParser;
4868
+ exports.HSPLUS_ERROR_CODES = HSPLUS_ERROR_CODES;
4869
+ exports.HoloScriptPlusParser = HoloScriptPlusParser;
4870
+ exports.ParseCache = ParseCache;
4871
+ exports.createKeywordError = createKeywordError;
4872
+ exports.createParser = createParser;
4873
+ exports.createRichError = createRichError;
4874
+ exports.createTraitError = createTraitError;
4875
+ exports.findSimilarKeyword = findSimilarKeyword;
4876
+ exports.findSimilarTrait = findSimilarTrait;
4877
+ exports.formatRichError = formatRichError;
4878
+ exports.formatRichErrors = formatRichErrors;
4879
+ exports.getErrorCodeDocumentation = getErrorCodeDocumentation;
4880
+ exports.getSourceContext = getSourceContext;
4881
+ exports.globalParseCache = globalParseCache;
4882
+ exports.parse = parse;
4883
+ exports.parseIncrementalChunks = parseIncrementalChunks;
4884
+ //# sourceMappingURL=chunk-T5J7ZKP3.cjs.map
4885
+ //# sourceMappingURL=chunk-T5J7ZKP3.cjs.map