@holoscript/core 6.0.3 → 7.0.0

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