@holoscript/core 6.0.4 → 7.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (236) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1 -1
  3. package/dist/compiler/index.d.ts +82 -0
  4. package/dist/constants.d.ts +3 -2
  5. package/dist/coordinators/index.d.ts +189 -0
  6. package/dist/index.d.ts +501 -19
  7. package/dist/paper-0c-spike/index.d.ts +29 -0
  8. package/dist/reconstruction/index.d.ts +78 -0
  9. package/dist/tools/index.d.ts +22 -1
  10. package/dist/traitDocs/traitDocs.d.ts +69 -0
  11. package/dist/traits/index.d.ts +61 -0
  12. package/package.json +105 -57
  13. package/dist/GLTFPipeline-DEN36VNK.js +0 -12
  14. package/dist/GLTFPipeline-YPCAK236.cjs +0 -33
  15. package/dist/HoloScriptPlusParser-BN6KVRCM.js +0 -692
  16. package/dist/HoloScriptPlusParser-NC5FE6AL.cjs +0 -697
  17. package/dist/USDZExporter-NTMBNTDB.js +0 -707
  18. package/dist/USDZExporter-UWGWNMMD.cjs +0 -709
  19. package/dist/chunk-27LWW5FU.cjs +0 -410
  20. package/dist/chunk-2CWOLHTE.js +0 -69
  21. package/dist/chunk-33LSUQDD.cjs +0 -835
  22. package/dist/chunk-3FJCK5XA.js +0 -2232
  23. package/dist/chunk-3FXV5S25.cjs +0 -633
  24. package/dist/chunk-3FYZOR7S.cjs +0 -69
  25. package/dist/chunk-3SAK5KFL.cjs +0 -83
  26. package/dist/chunk-4XSNJCLC.cjs +0 -1859
  27. package/dist/chunk-54FHG2MX.js +0 -655
  28. package/dist/chunk-56IF4NTA.js +0 -56
  29. package/dist/chunk-5BGSECRJ.cjs +0 -2237
  30. package/dist/chunk-5GLCTO44.js +0 -161
  31. package/dist/chunk-5O6TQC6M.cjs +0 -1871
  32. package/dist/chunk-5OEOHAAW.cjs +0 -682
  33. package/dist/chunk-5TOFIR6L.js +0 -407
  34. package/dist/chunk-5WUNN6ZN.cjs +0 -428
  35. package/dist/chunk-6TZPZCOJ.cjs +0 -1404
  36. package/dist/chunk-6UEHYZ7V.cjs +0 -773
  37. package/dist/chunk-6XSERL6L.js +0 -5678
  38. package/dist/chunk-72EQECGT.cjs +0 -908
  39. package/dist/chunk-7AGYRWKW.cjs +0 -507
  40. package/dist/chunk-7LCYLPW2.cjs +0 -663
  41. package/dist/chunk-A7PIMZGU.js +0 -263
  42. package/dist/chunk-ATSKSYVE.cjs +0 -51683
  43. package/dist/chunk-B5TCIAPQ.cjs +0 -117
  44. package/dist/chunk-BF2235SI.cjs +0 -5714
  45. package/dist/chunk-BKIGPPVM.js +0 -629
  46. package/dist/chunk-BND3ST2K.cjs +0 -662
  47. package/dist/chunk-BU7VWW2K.js +0 -2522
  48. package/dist/chunk-BWFJEM5A.js +0 -5419
  49. package/dist/chunk-CAUCGUEA.cjs +0 -130
  50. package/dist/chunk-CBJSLA2E.cjs +0 -5423
  51. package/dist/chunk-CDPGV4DN.js +0 -114
  52. package/dist/chunk-CLYEIWA5.cjs +0 -408
  53. package/dist/chunk-CS2EMTGF.js +0 -1966
  54. package/dist/chunk-DMG7C4H2.js +0 -975
  55. package/dist/chunk-DXJQDCFL.js +0 -468
  56. package/dist/chunk-E3FWRT3Z.js +0 -608
  57. package/dist/chunk-E3UALNFA.js +0 -421
  58. package/dist/chunk-EONILVMF.js +0 -762
  59. package/dist/chunk-EQV4R3EV.cjs +0 -769
  60. package/dist/chunk-F3HH56EB.cjs +0 -5538
  61. package/dist/chunk-F4IULT7N.js +0 -1488
  62. package/dist/chunk-FF3Q7ADR.js +0 -380
  63. package/dist/chunk-FFKU7BTK.cjs +0 -1046
  64. package/dist/chunk-FHQVYCH2.js +0 -70
  65. package/dist/chunk-FSF7EQVA.cjs +0 -1974
  66. package/dist/chunk-G4VZTCIB.js +0 -659
  67. package/dist/chunk-G7CT3EMP.cjs +0 -1002
  68. package/dist/chunk-GGHSW2NN.js +0 -51334
  69. package/dist/chunk-GVUR45UF.cjs +0 -777
  70. package/dist/chunk-H5Z7NASB.js +0 -9662
  71. package/dist/chunk-HE7ULERA.cjs +0 -697
  72. package/dist/chunk-HJJLD366.js +0 -1169
  73. package/dist/chunk-HPS76H7Q.js +0 -309
  74. package/dist/chunk-HQUEA5R6.cjs +0 -424
  75. package/dist/chunk-HYNTS5CP.js +0 -422
  76. package/dist/chunk-I6XZ5DZF.cjs +0 -488
  77. package/dist/chunk-IBDG74G2.cjs +0 -1219
  78. package/dist/chunk-IFNQFCTM.js +0 -3098
  79. package/dist/chunk-IHOUYQIA.js +0 -406
  80. package/dist/chunk-ILRBGFVD.cjs +0 -72
  81. package/dist/chunk-IWI6J7FX.js +0 -421
  82. package/dist/chunk-K3JDKWGI.cjs +0 -270
  83. package/dist/chunk-K6EKD26I.js +0 -630
  84. package/dist/chunk-KCQ5NDYC.cjs +0 -3172
  85. package/dist/chunk-KED34ILP.js +0 -832
  86. package/dist/chunk-KSGXLT74.cjs +0 -457
  87. package/dist/chunk-L4G4RLXX.js +0 -767
  88. package/dist/chunk-LDP5OK6G.js +0 -1216
  89. package/dist/chunk-LGGRPKTV.cjs +0 -735
  90. package/dist/chunk-LK5IAVH6.cjs +0 -1173
  91. package/dist/chunk-LSW7P7ML.js +0 -3675
  92. package/dist/chunk-LXJ4667L.cjs +0 -3874
  93. package/dist/chunk-LZ266PCM.cjs +0 -4499
  94. package/dist/chunk-MD6KDHVE.cjs +0 -237
  95. package/dist/chunk-MEASWI2Y.js +0 -126
  96. package/dist/chunk-MPXBVFHQ.js +0 -768
  97. package/dist/chunk-N5FTS757.cjs +0 -415
  98. package/dist/chunk-NCUKG4SK.cjs +0 -3075
  99. package/dist/chunk-NDQNIJEH.js +0 -1715
  100. package/dist/chunk-NOZZ46QU.js +0 -168
  101. package/dist/chunk-OFKWH2IP.js +0 -449
  102. package/dist/chunk-PHENW4MQ.js +0 -65
  103. package/dist/chunk-PMGODDJA.cjs +0 -319
  104. package/dist/chunk-Q4QX3AET.cjs +0 -1505
  105. package/dist/chunk-Q56TT7IL.js +0 -483
  106. package/dist/chunk-Q5JT3YML.cjs +0 -129
  107. package/dist/chunk-Q5SJOGHQ.cjs +0 -4256
  108. package/dist/chunk-QGKNANZ3.js +0 -3071
  109. package/dist/chunk-QLEAOI3Q.cjs +0 -424
  110. package/dist/chunk-R7MA7QWV.js +0 -732
  111. package/dist/chunk-RVYPEYPX.js +0 -678
  112. package/dist/chunk-S2N5TNMA.js +0 -1855
  113. package/dist/chunk-S565K7NK.js +0 -752
  114. package/dist/chunk-SDAMZIRE.js +0 -765
  115. package/dist/chunk-T36DDXSF.js +0 -4250
  116. package/dist/chunk-T4NKMBDL.js +0 -5474
  117. package/dist/chunk-T7LEXZUZ.cjs +0 -2526
  118. package/dist/chunk-TEWCN33Y.js +0 -694
  119. package/dist/chunk-TQSZUOW5.cjs +0 -793
  120. package/dist/chunk-TSH3MSQU.cjs +0 -129
  121. package/dist/chunk-UERJ3YJV.js +0 -504
  122. package/dist/chunk-UPJBDCVF.js +0 -1395
  123. package/dist/chunk-V3NN3HPP.js +0 -4462
  124. package/dist/chunk-VJ3L7CHT.cjs +0 -169
  125. package/dist/chunk-WB4Z63GG.js +0 -229
  126. package/dist/chunk-WDW67DZB.cjs +0 -9728
  127. package/dist/chunk-WGMEAYBG.js +0 -126
  128. package/dist/chunk-X4ZF6CNE.cjs +0 -473
  129. package/dist/chunk-X6SEAXAX.cjs +0 -3681
  130. package/dist/chunk-XCWFGZAA.js +0 -1043
  131. package/dist/chunk-XD6IYDUX.js +0 -903
  132. package/dist/chunk-XG23EUQX.cjs +0 -1717
  133. package/dist/chunk-XRKWN5PL.cjs +0 -173
  134. package/dist/chunk-XUILI4KB.cjs +0 -430
  135. package/dist/chunk-XUTX5CBW.js +0 -126
  136. package/dist/chunk-XWPNTWDN.cjs +0 -755
  137. package/dist/chunk-XXINBTZK.cjs +0 -633
  138. package/dist/chunk-YCXFCXDS.js +0 -1868
  139. package/dist/chunk-YQK5JNFK.js +0 -3725
  140. package/dist/chunk-YYXH45E2.js +0 -426
  141. package/dist/chunk-Z34RLXRA.cjs +0 -612
  142. package/dist/chunk-ZP4D3CSX.cjs +0 -72
  143. package/dist/cli/holoscript-runner.cjs +0 -2259
  144. package/dist/cli/holoscript-runner.js +0 -2234
  145. package/dist/codebase/index.cjs +0 -336
  146. package/dist/codebase/index.js +0 -331
  147. package/dist/compiler/agent-inference.cjs +0 -28
  148. package/dist/compiler/agent-inference.js +0 -5
  149. package/dist/compiler/android-xr.cjs +0 -19
  150. package/dist/compiler/android-xr.js +0 -9
  151. package/dist/compiler/android.cjs +0 -20
  152. package/dist/compiler/android.js +0 -10
  153. package/dist/compiler/ar.cjs +0 -20
  154. package/dist/compiler/ar.js +0 -8
  155. package/dist/compiler/babylon.cjs +0 -17
  156. package/dist/compiler/babylon.js +0 -11
  157. package/dist/compiler/coco.cjs +0 -27
  158. package/dist/compiler/coco.js +0 -4
  159. package/dist/compiler/domain-block-utils.cjs +0 -602
  160. package/dist/compiler/domain-block-utils.js +0 -8
  161. package/dist/compiler/dtdl.cjs +0 -24
  162. package/dist/compiler/dtdl.js +0 -8
  163. package/dist/compiler/gltf-pipeline.cjs +0 -39
  164. package/dist/compiler/gltf-pipeline.js +0 -4
  165. package/dist/compiler/godot.cjs +0 -15
  166. package/dist/compiler/godot.js +0 -9
  167. package/dist/compiler/incremental.cjs +0 -29
  168. package/dist/compiler/incremental.js +0 -4
  169. package/dist/compiler/index.cjs +0 -2578
  170. package/dist/compiler/index.js +0 -2383
  171. package/dist/compiler/ios.cjs +0 -20
  172. package/dist/compiler/ios.js +0 -10
  173. package/dist/compiler/multi-layer.cjs +0 -20
  174. package/dist/compiler/multi-layer.js +0 -11
  175. package/dist/compiler/nodetoy.cjs +0 -23
  176. package/dist/compiler/nodetoy.js +0 -4
  177. package/dist/compiler/openxr.cjs +0 -15
  178. package/dist/compiler/openxr.js +0 -9
  179. package/dist/compiler/playcanvas.cjs +0 -16
  180. package/dist/compiler/playcanvas.js +0 -10
  181. package/dist/compiler/r3f.cjs +0 -34
  182. package/dist/compiler/r3f.js +0 -12
  183. package/dist/compiler/remotion.cjs +0 -23
  184. package/dist/compiler/remotion.js +0 -4
  185. package/dist/compiler/reproducibility.cjs +0 -39
  186. package/dist/compiler/reproducibility.js +0 -4
  187. package/dist/compiler/sdf.cjs +0 -21
  188. package/dist/compiler/sdf.js +0 -9
  189. package/dist/compiler/semantic-scene.cjs +0 -31
  190. package/dist/compiler/semantic-scene.js +0 -4
  191. package/dist/compiler/state.cjs +0 -17
  192. package/dist/compiler/state.js +0 -7
  193. package/dist/compiler/trait-composition.cjs +0 -26
  194. package/dist/compiler/trait-composition.js +0 -5
  195. package/dist/compiler/unity.cjs +0 -15
  196. package/dist/compiler/unity.js +0 -9
  197. package/dist/compiler/unreal.cjs +0 -19
  198. package/dist/compiler/unreal.js +0 -9
  199. package/dist/compiler/urdf.cjs +0 -45
  200. package/dist/compiler/urdf.js +0 -9
  201. package/dist/compiler/usd-physics.cjs +0 -23
  202. package/dist/compiler/usd-physics.js +0 -6
  203. package/dist/compiler/visionos.cjs +0 -15
  204. package/dist/compiler/visionos.js +0 -9
  205. package/dist/compiler/vrchat.cjs +0 -19
  206. package/dist/compiler/vrchat.js +0 -9
  207. package/dist/compiler/vrr.cjs +0 -21
  208. package/dist/compiler/vrr.js +0 -9
  209. package/dist/compiler/wasm.cjs +0 -33
  210. package/dist/compiler/wasm.js +0 -9
  211. package/dist/compiler/webgpu.cjs +0 -15
  212. package/dist/compiler/webgpu.js +0 -9
  213. package/dist/debugger.cjs +0 -21
  214. package/dist/debugger.js +0 -8
  215. package/dist/entries/interop.cjs +0 -62
  216. package/dist/entries/interop.js +0 -5
  217. package/dist/entries/scripting.cjs +0 -68
  218. package/dist/entries/scripting.js +0 -11
  219. package/dist/index.cjs +0 -40921
  220. package/dist/index.js +0 -37763
  221. package/dist/math/vec3.cjs +0 -57
  222. package/dist/math/vec3.js +0 -4
  223. package/dist/ml-dsa-PHCWUBPX.cjs +0 -1178
  224. package/dist/ml-dsa-WYLJHJO6.js +0 -1178
  225. package/dist/parser.cjs +0 -27
  226. package/dist/parser.js +0 -10
  227. package/dist/playwright-5OSAPTNH.js +0 -98660
  228. package/dist/playwright-RL6GY4F7.cjs +0 -98673
  229. package/dist/runtime.cjs +0 -16
  230. package/dist/runtime.js +0 -7
  231. package/dist/storage/index.cjs +0 -37
  232. package/dist/storage/index.js +0 -4
  233. package/dist/traits/index.cjs +0 -14649
  234. package/dist/traits/index.js +0 -12243
  235. package/dist/type-checker.cjs +0 -18
  236. package/dist/type-checker.js +0 -5
@@ -1,1974 +0,0 @@
1
- 'use strict';
2
-
3
- var crypto = require('crypto');
4
- var platform = require('@holoscript/platform');
5
-
6
- // src/compiler/TraitDependencyGraph.ts
7
- function hashConfig(config) {
8
- const keys = Object.keys(config).sort();
9
- const parts = [];
10
- for (const key of keys) {
11
- const value = config[key];
12
- parts.push(`${key}:${JSON.stringify(value)}`);
13
- }
14
- const str = parts.join("|");
15
- let hash = 5381;
16
- for (let i = 0; i < str.length; i++) {
17
- hash = (hash << 5) + hash ^ str.charCodeAt(i);
18
- }
19
- return (hash >>> 0).toString(36);
20
- }
21
- var TraitDependencyGraph = class _TraitDependencyGraph {
22
- constructor() {
23
- /** Trait → required traits (what this trait depends on) */
24
- this.traitDependencies = /* @__PURE__ */ new Map();
25
- /** Trait → conflicting traits */
26
- this.traitConflicts = /* @__PURE__ */ new Map();
27
- /** Object → trait info (current state) */
28
- this.objectTraits = /* @__PURE__ */ new Map();
29
- /** Trait → objects using this trait */
30
- this.traitToObjects = /* @__PURE__ */ new Map();
31
- /** Source → objects defined in this source */
32
- this.sourceToObjects = /* @__PURE__ */ new Map();
33
- /** Template → objects extending this template */
34
- this.templateToObjects = /* @__PURE__ */ new Map();
35
- /** Previous state for diff comparison */
36
- this.previousObjectTraits = /* @__PURE__ */ new Map();
37
- // ---------------------------------------------------------------------------
38
- // IMPORT GRAPH — cross-file dependency edges
39
- // ---------------------------------------------------------------------------
40
- /**
41
- * File → set of files it directly imports.
42
- * Edge: `importer → importee`
43
- * e.g., 'a.hs' → { 'b.hs', 'c.hs' }
44
- */
45
- this.importEdges = /* @__PURE__ */ new Map();
46
- /**
47
- * Reverse map: file → set of files that import it.
48
- * Edge: `importee → importers`
49
- * e.g., 'b.hs' → { 'a.hs', 'd.hs' }
50
- */
51
- this.reverseImportEdges = /* @__PURE__ */ new Map();
52
- }
53
- // ===========================================================================
54
- // TRAIT REGISTRATION
55
- // ===========================================================================
56
- /**
57
- * Register a trait definition with its dependencies and conflicts
58
- */
59
- registerTrait(definition) {
60
- const { name, requires, conflicts } = definition;
61
- if (!this.traitDependencies.has(name)) {
62
- this.traitDependencies.set(name, /* @__PURE__ */ new Set());
63
- }
64
- for (const req of requires) {
65
- this.traitDependencies.get(name).add(req);
66
- }
67
- if (!this.traitConflicts.has(name)) {
68
- this.traitConflicts.set(name, /* @__PURE__ */ new Set());
69
- }
70
- for (const conflict of conflicts) {
71
- this.traitConflicts.get(name).add(conflict);
72
- }
73
- }
74
- /**
75
- * Register common VR trait dependencies
76
- */
77
- registerBuiltinTraits() {
78
- this.registerTrait({
79
- name: "physics",
80
- requires: [],
81
- conflicts: ["static"]
82
- });
83
- this.registerTrait({
84
- name: "static",
85
- requires: [],
86
- conflicts: ["physics", "kinematic"]
87
- });
88
- this.registerTrait({
89
- name: "kinematic",
90
- requires: [],
91
- conflicts: ["static"]
92
- });
93
- this.registerTrait({
94
- name: "collidable",
95
- requires: [],
96
- conflicts: []
97
- });
98
- this.registerTrait({
99
- name: "grabbable",
100
- requires: ["collidable"],
101
- conflicts: []
102
- });
103
- this.registerTrait({
104
- name: "throwable",
105
- requires: ["grabbable"],
106
- conflicts: []
107
- });
108
- this.registerTrait({
109
- name: "draggable",
110
- requires: ["collidable"],
111
- conflicts: []
112
- });
113
- this.registerTrait({
114
- name: "visible",
115
- requires: [],
116
- conflicts: ["invisible"]
117
- });
118
- this.registerTrait({
119
- name: "invisible",
120
- requires: [],
121
- conflicts: ["visible"]
122
- });
123
- this.registerTrait({
124
- name: "audio",
125
- requires: [],
126
- conflicts: []
127
- });
128
- this.registerTrait({
129
- name: "spatial_audio",
130
- requires: ["audio"],
131
- conflicts: []
132
- });
133
- this.registerTrait({
134
- name: "networked",
135
- requires: [],
136
- conflicts: []
137
- });
138
- this.registerTrait({
139
- name: "lobby",
140
- requires: [],
141
- conflicts: []
142
- });
143
- this.registerTrait({
144
- name: "crdt-room",
145
- requires: [],
146
- conflicts: ["lobby"]
147
- // crdt-room replaces lobby-based room management
148
- });
149
- this.registerTrait({
150
- name: "crdt-room.entity",
151
- requires: ["crdt-room"],
152
- conflicts: []
153
- });
154
- this.registerTrait({
155
- name: "cultural_profile",
156
- requires: [],
157
- conflicts: []
158
- });
159
- this.registerTrait({
160
- name: "norm_compliant",
161
- requires: ["cultural_profile"],
162
- conflicts: []
163
- });
164
- this.registerTrait({
165
- name: "cultural_memory",
166
- requires: ["cultural_profile"],
167
- conflicts: []
168
- });
169
- this.registerTrait({
170
- name: "cultural_trace",
171
- requires: [],
172
- conflicts: []
173
- });
174
- this.registerV6Traits();
175
- }
176
- /**
177
- * Register v6 universal service/data/pipeline/container/resilience traits
178
- */
179
- registerV6Traits() {
180
- this.registerTrait({ name: "service", requires: [], conflicts: [] });
181
- this.registerTrait({ name: "endpoint", requires: ["service"], conflicts: [] });
182
- this.registerTrait({ name: "handler", requires: ["http"], conflicts: [] });
183
- this.registerTrait({ name: "middleware", requires: ["service"], conflicts: [] });
184
- this.registerTrait({ name: "http", requires: [], conflicts: [] });
185
- this.registerTrait({ name: "gateway", requires: [], conflicts: ["proxy"] });
186
- this.registerTrait({ name: "proxy", requires: [], conflicts: ["gateway"] });
187
- this.registerTrait({ name: "db", requires: [], conflicts: [] });
188
- this.registerTrait({ name: "data_model", requires: ["db"], conflicts: [] });
189
- this.registerTrait({ name: "migration", requires: ["db"], conflicts: [] });
190
- this.registerTrait({ name: "query", requires: ["db"], conflicts: [] });
191
- this.registerTrait({ name: "cache", requires: [], conflicts: [] });
192
- this.registerTrait({ name: "pipeline", requires: [], conflicts: [] });
193
- this.registerTrait({ name: "stream", requires: ["pipeline"], conflicts: [] });
194
- this.registerTrait({ name: "queue", requires: [], conflicts: [] });
195
- this.registerTrait({ name: "worker", requires: ["pipeline"], conflicts: ["scheduler"] });
196
- this.registerTrait({ name: "scheduler", requires: [], conflicts: ["worker"] });
197
- this.registerTrait({ name: "container", requires: [], conflicts: ["serverless"] });
198
- this.registerTrait({ name: "serverless", requires: [], conflicts: ["container"] });
199
- this.registerTrait({ name: "deployment", requires: [], conflicts: [] });
200
- this.registerTrait({ name: "metric", requires: [], conflicts: [] });
201
- this.registerTrait({ name: "trace", requires: ["service"], conflicts: [] });
202
- this.registerTrait({ name: "health_check", requires: ["service"], conflicts: [] });
203
- this.registerTrait({ name: "log", requires: [], conflicts: [] });
204
- this.registerTrait({ name: "circuit_breaker", requires: ["service"], conflicts: [] });
205
- this.registerTrait({ name: "retry", requires: ["service"], conflicts: [] });
206
- this.registerTrait({ name: "timeout", requires: ["service"], conflicts: [] });
207
- this.registerTrait({ name: "fallback", requires: [], conflicts: [] });
208
- this.registerTrait({ name: "bulkhead", requires: ["service"], conflicts: [] });
209
- this.registerTrait({ name: "schema", requires: [], conflicts: [] });
210
- this.registerTrait({ name: "validator", requires: ["schema"], conflicts: [] });
211
- this.registerTrait({ name: "serializer", requires: ["schema"], conflicts: [] });
212
- this.registerTrait({ name: "contract", requires: [], conflicts: [] });
213
- }
214
- // ===========================================================================
215
- // IMPORT EDGE TRACKING (@import cross-file dependencies)
216
- // ===========================================================================
217
- /**
218
- * Register a cross-file @import relationship.
219
- *
220
- * Call this once per `@import` directive after parsing.
221
- * Idempotent — registering the same edge twice is safe.
222
- *
223
- * @param importingFile Canonical path of the file that contains `@import`
224
- * @param importedFile Canonical path of the file being imported
225
- */
226
- registerImport(importingFile, importedFile) {
227
- if (!this.importEdges.has(importingFile)) {
228
- this.importEdges.set(importingFile, /* @__PURE__ */ new Set());
229
- }
230
- this.importEdges.get(importingFile).add(importedFile);
231
- if (!this.reverseImportEdges.has(importedFile)) {
232
- this.reverseImportEdges.set(importedFile, /* @__PURE__ */ new Set());
233
- }
234
- this.reverseImportEdges.get(importedFile).add(importingFile);
235
- }
236
- /**
237
- * Remove all import edges for a file (call before re-registering after a parse).
238
- * Cleans both the forward edge and the corresponding reverse entries.
239
- */
240
- clearImportsForFile(importingFile) {
241
- const imported = this.importEdges.get(importingFile);
242
- if (!imported) return;
243
- for (const dep of imported) {
244
- this.reverseImportEdges.get(dep)?.delete(importingFile);
245
- }
246
- this.importEdges.delete(importingFile);
247
- }
248
- /**
249
- * Return the set of files that `sourceFile` directly imports.
250
- */
251
- getImportedFiles(sourceFile) {
252
- return new Set(this.importEdges.get(sourceFile) ?? []);
253
- }
254
- /**
255
- * Return the set of files that directly import `sourceFile`.
256
- */
257
- getFilesThatImport(sourceFile) {
258
- return new Set(this.reverseImportEdges.get(sourceFile) ?? []);
259
- }
260
- /**
261
- * Walk the reverse-import graph (BFS) to compute the full set of files that
262
- * need to be recompiled when `changedFiles` are modified.
263
- *
264
- * Includes the changed files themselves and all direct/transitive importers.
265
- *
266
- * @param changedFiles Canonical paths of the files that changed on disk
267
- * @returns Set of canonical paths that need recompilation
268
- */
269
- getFilesAffectedByChange(changedFiles) {
270
- const affected = new Set(changedFiles);
271
- const queue = [...changedFiles];
272
- while (queue.length > 0) {
273
- const current = queue.shift();
274
- const importers = this.reverseImportEdges.get(current);
275
- if (!importers) continue;
276
- for (const importer of importers) {
277
- if (!affected.has(importer)) {
278
- affected.add(importer);
279
- queue.push(importer);
280
- }
281
- }
282
- }
283
- return affected;
284
- }
285
- // ===========================================================================
286
- // OBJECT TRACKING
287
- // ===========================================================================
288
- /**
289
- * Register an object and its trait usage
290
- */
291
- registerObject(info) {
292
- const { objectName, sourceId, traits, template } = info;
293
- const traitsWithHashes = traits.map((t) => ({
294
- ...t,
295
- configHash: t.configHash || hashConfig(t.config)
296
- }));
297
- const fullInfo = {
298
- ...info,
299
- traits: traitsWithHashes
300
- };
301
- this.objectTraits.set(objectName, fullInfo);
302
- for (const trait of traitsWithHashes) {
303
- if (!this.traitToObjects.has(trait.name)) {
304
- this.traitToObjects.set(trait.name, /* @__PURE__ */ new Set());
305
- }
306
- this.traitToObjects.get(trait.name).add(objectName);
307
- }
308
- if (!this.sourceToObjects.has(sourceId)) {
309
- this.sourceToObjects.set(sourceId, /* @__PURE__ */ new Set());
310
- }
311
- this.sourceToObjects.get(sourceId).add(objectName);
312
- if (template) {
313
- if (!this.templateToObjects.has(template)) {
314
- this.templateToObjects.set(template, /* @__PURE__ */ new Set());
315
- }
316
- this.templateToObjects.get(template).add(objectName);
317
- }
318
- }
319
- /**
320
- * Remove an object from tracking
321
- */
322
- unregisterObject(objectName) {
323
- const info = this.objectTraits.get(objectName);
324
- if (!info) return;
325
- for (const trait of info.traits) {
326
- this.traitToObjects.get(trait.name)?.delete(objectName);
327
- }
328
- this.sourceToObjects.get(info.sourceId)?.delete(objectName);
329
- if (info.template) {
330
- this.templateToObjects.get(info.template)?.delete(objectName);
331
- }
332
- this.objectTraits.delete(objectName);
333
- }
334
- // ===========================================================================
335
- // CHANGE DETECTION
336
- // ===========================================================================
337
- /**
338
- * Save current state for comparison
339
- */
340
- saveSnapshot() {
341
- this.previousObjectTraits = new Map(
342
- Array.from(this.objectTraits.entries()).map(([k, v]) => [
343
- k,
344
- {
345
- ...v,
346
- traits: [...v.traits]
347
- }
348
- ])
349
- );
350
- }
351
- /**
352
- * Detect trait changes for an object
353
- */
354
- detectTraitChanges(objectName, newTraits) {
355
- const changes = [];
356
- const oldInfo = this.previousObjectTraits.get(objectName);
357
- const newTraitsWithHashes = newTraits.map((t) => ({
358
- ...t,
359
- configHash: t.configHash || hashConfig(t.config)
360
- }));
361
- const oldTraitMap = /* @__PURE__ */ new Map();
362
- const newTraitMap = /* @__PURE__ */ new Map();
363
- if (oldInfo) {
364
- for (const t of oldInfo.traits) {
365
- oldTraitMap.set(t.name, t);
366
- }
367
- }
368
- for (const t of newTraitsWithHashes) {
369
- newTraitMap.set(t.name, t);
370
- }
371
- for (const [name, newTrait] of newTraitMap) {
372
- if (!oldTraitMap.has(name)) {
373
- changes.push({
374
- traitName: name,
375
- changeType: "added",
376
- newConfigHash: newTrait.configHash
377
- });
378
- }
379
- }
380
- for (const [name, oldTrait] of oldTraitMap) {
381
- if (!newTraitMap.has(name)) {
382
- changes.push({
383
- traitName: name,
384
- changeType: "removed",
385
- oldConfigHash: oldTrait.configHash
386
- });
387
- }
388
- }
389
- for (const [name, newTrait] of newTraitMap) {
390
- const oldTrait = oldTraitMap.get(name);
391
- if (oldTrait && oldTrait.configHash !== newTrait.configHash) {
392
- changes.push({
393
- traitName: name,
394
- changeType: "config_changed",
395
- oldConfigHash: oldTrait.configHash,
396
- newConfigHash: newTrait.configHash
397
- });
398
- }
399
- }
400
- return changes;
401
- }
402
- // ===========================================================================
403
- // AFFECTED SET CALCULATION
404
- // ===========================================================================
405
- /**
406
- * Get all objects using a specific trait
407
- */
408
- getObjectsUsingTrait(traitName) {
409
- return new Set(this.traitToObjects.get(traitName) || []);
410
- }
411
- /**
412
- * Get all traits that depend on a given trait
413
- */
414
- getDependentTraits(traitName) {
415
- const dependents = /* @__PURE__ */ new Set();
416
- for (const [trait, deps] of this.traitDependencies) {
417
- if (deps.has(traitName)) {
418
- dependents.add(trait);
419
- }
420
- }
421
- return dependents;
422
- }
423
- /**
424
- * Calculate the affected set when traits change
425
- */
426
- calculateAffectedSet(changes) {
427
- const objects = /* @__PURE__ */ new Set();
428
- const sources = /* @__PURE__ */ new Set();
429
- const reasons = /* @__PURE__ */ new Map();
430
- for (const change of changes) {
431
- const { traitName, changeType } = change;
432
- const directUsers = this.getObjectsUsingTrait(traitName);
433
- for (const obj of directUsers) {
434
- objects.add(obj);
435
- reasons.set(obj, `Uses trait @${traitName} (${changeType})`);
436
- const info = this.objectTraits.get(obj);
437
- if (info) {
438
- sources.add(info.sourceId);
439
- }
440
- }
441
- const dependentTraits = this.getDependentTraits(traitName);
442
- for (const depTrait of dependentTraits) {
443
- const depUsers = this.getObjectsUsingTrait(depTrait);
444
- for (const obj of depUsers) {
445
- if (!objects.has(obj)) {
446
- objects.add(obj);
447
- reasons.set(obj, `Uses trait @${depTrait} which depends on @${traitName}`);
448
- const info = this.objectTraits.get(obj);
449
- if (info) {
450
- sources.add(info.sourceId);
451
- }
452
- }
453
- }
454
- }
455
- }
456
- return { objects, sources, reasons };
457
- }
458
- /**
459
- * Calculate minimal recompilation set for changed objects
460
- * Considers trait dependencies and template inheritance
461
- */
462
- calculateRecompilationSet(changedObjects) {
463
- const toRecompile = new Set(changedObjects);
464
- const queue = [...changedObjects];
465
- while (queue.length > 0) {
466
- const current = queue.shift();
467
- const info = this.objectTraits.get(current);
468
- if (!info) continue;
469
- const extending = this.templateToObjects.get(current);
470
- if (extending) {
471
- for (const obj of extending) {
472
- if (!toRecompile.has(obj)) {
473
- toRecompile.add(obj);
474
- queue.push(obj);
475
- }
476
- }
477
- }
478
- }
479
- return toRecompile;
480
- }
481
- // ===========================================================================
482
- // SERIALIZATION (for cache persistence)
483
- // ===========================================================================
484
- /**
485
- * Serialize the graph for persistence
486
- */
487
- serialize() {
488
- const data = {
489
- version: 2,
490
- traitDependencies: Array.from(this.traitDependencies.entries()).map(([k, v]) => [
491
- k,
492
- Array.from(v)
493
- ]),
494
- traitConflicts: Array.from(this.traitConflicts.entries()).map(([k, v]) => [k, Array.from(v)]),
495
- objectTraits: Array.from(this.objectTraits.entries()),
496
- importEdges: Array.from(this.importEdges.entries()).map(([k, v]) => [k, Array.from(v)]),
497
- timestamp: Date.now()
498
- };
499
- return JSON.stringify(data);
500
- }
501
- /**
502
- * Deserialize the graph from persisted data
503
- */
504
- static deserialize(json) {
505
- const graph = new _TraitDependencyGraph();
506
- const data = JSON.parse(json);
507
- if (data.version !== 1 && data.version !== 2) {
508
- throw new Error(`Unsupported trait graph version: ${data.version}`);
509
- }
510
- for (const [trait, deps] of data.traitDependencies) {
511
- graph.traitDependencies.set(trait, new Set(deps));
512
- }
513
- for (const [trait, conflicts] of data.traitConflicts) {
514
- graph.traitConflicts.set(trait, new Set(conflicts));
515
- }
516
- for (const [_name, info] of data.objectTraits) {
517
- graph.registerObject(info);
518
- }
519
- if (data.importEdges) {
520
- for (const [importer, imported] of data.importEdges) {
521
- for (const dep of imported) {
522
- graph.registerImport(importer, dep);
523
- }
524
- }
525
- }
526
- return graph;
527
- }
528
- // ===========================================================================
529
- // STATS & DEBUGGING
530
- // ===========================================================================
531
- /**
532
- * Get graph statistics
533
- */
534
- getStats() {
535
- let dependencyEdges = 0;
536
- for (const deps of this.traitDependencies.values()) {
537
- dependencyEdges += deps.size;
538
- }
539
- let importEdges = 0;
540
- for (const deps of this.importEdges.values()) {
541
- importEdges += deps.size;
542
- }
543
- return {
544
- traitCount: this.traitDependencies.size,
545
- objectCount: this.objectTraits.size,
546
- sourceCount: this.sourceToObjects.size,
547
- dependencyEdges,
548
- importEdges
549
- };
550
- }
551
- /**
552
- * Clear all data
553
- */
554
- clear() {
555
- this.traitDependencies.clear();
556
- this.traitConflicts.clear();
557
- this.objectTraits.clear();
558
- this.traitToObjects.clear();
559
- this.sourceToObjects.clear();
560
- this.templateToObjects.clear();
561
- this.previousObjectTraits.clear();
562
- this.importEdges.clear();
563
- this.reverseImportEdges.clear();
564
- }
565
- };
566
- var globalTraitGraph = new TraitDependencyGraph();
567
- globalTraitGraph.registerBuiltinTraits();
568
-
569
- // src/parser/ImportResolver.ts
570
- function resolveImportPath(importPath, baseDir) {
571
- importPath = importPath.replace(/\\/g, "/");
572
- baseDir = baseDir.replace(/\\/g, "/");
573
- if (importPath.startsWith("/") || /^[A-Za-z]:/.test(importPath)) {
574
- return importPath;
575
- }
576
- const baseResolved = normalizePath(baseDir);
577
- const base = baseResolved.replace(/\/$/, "");
578
- const combined = base + "/" + importPath;
579
- return normalizePath(combined);
580
- }
581
- function normalizePath(p) {
582
- const isAbsolute = p.startsWith("/");
583
- const parts = p.split("/");
584
- const resolved = [];
585
- for (const part of parts) {
586
- if (part === "" || part === ".") {
587
- if (resolved.length === 0 && part === "" && isAbsolute) {
588
- resolved.push("");
589
- }
590
- continue;
591
- }
592
- if (part === "..") {
593
- if (resolved.length > (isAbsolute ? 1 : 0)) {
594
- resolved.pop();
595
- }
596
- } else {
597
- resolved.push(part);
598
- }
599
- }
600
- let result = resolved.join("/");
601
- if (isAbsolute && !result.startsWith("/")) result = "/" + result;
602
- return result || "/";
603
- }
604
- var REGISTRY_IMPORT_RE = /^@[a-zA-Z0-9_-]+\/[a-zA-Z0-9_.-]+$/;
605
- function isRegistryImport(importPath) {
606
- return REGISTRY_IMPORT_RE.test(importPath);
607
- }
608
- function isCrdtImport(importPath) {
609
- return importPath.startsWith("crdt://");
610
- }
611
- function parseRegistryImport(importPath) {
612
- if (!isRegistryImport(importPath)) return null;
613
- const parts = importPath.slice(1).split("/");
614
- return { username: parts[0], name: parts[1] };
615
- }
616
- var ImportResolver = class {
617
- constructor() {
618
- /** Already-resolved modules keyed by canonical path */
619
- this.cache = /* @__PURE__ */ new Map();
620
- /** Paths currently being resolved (DFS cycle detection) */
621
- this.inProgress = /* @__PURE__ */ new Set();
622
- }
623
- /**
624
- * Resolve all @import directives from a parsed result and return a merged scope.
625
- *
626
- * @param result - The top-level parse result (from HoloScriptPlusParser.parse)
627
- * @param sourceFile - Canonical path of the file that produced `result`
628
- * @param options - Resolution options
629
- */
630
- async resolve(result, sourceFile, options) {
631
- if (options.disabled) {
632
- return { scope: /* @__PURE__ */ new Map(), modules: /* @__PURE__ */ new Map(), errors: [] };
633
- }
634
- const scope = /* @__PURE__ */ new Map();
635
- const modules = /* @__PURE__ */ new Map();
636
- const errors = [];
637
- const imports = result.ast?.imports ?? [];
638
- if (imports.length === 0) {
639
- return { scope, modules, errors };
640
- }
641
- const baseDir = options.baseDir.replace(/\\/g, "/");
642
- for (const imp of imports) {
643
- const canonicalPath = isRegistryImport(imp.path) || isCrdtImport(imp.path) ? imp.path : resolveImportPath(imp.path, baseDir);
644
- let mod;
645
- try {
646
- mod = await this._resolveModule(canonicalPath, sourceFile, options, 0, errors);
647
- } catch (err) {
648
- const msg = err instanceof Error ? err.message : String(err);
649
- errors.push({
650
- importPath: imp.path,
651
- message: msg,
652
- code: msg.startsWith("Circular") ? "cycle" : msg.startsWith("Max depth") ? "max_depth" : msg.startsWith("Parse error") ? "parse_error" : msg.startsWith("Registry") ? "registry_unavailable" : "not_found",
653
- ...msg.startsWith("Circular") ? { cycle: [canonicalPath] } : {}
654
- });
655
- continue;
656
- }
657
- modules.set(canonicalPath, mod);
658
- if (imp.namedImports && imp.namedImports.length > 0) {
659
- for (const named of imp.namedImports) {
660
- const node = mod.exports.get(named);
661
- if (!node) {
662
- errors.push({
663
- importPath: imp.path,
664
- message: `'${named}' is not exported from '${imp.path}'`,
665
- code: "named_not_exported"
666
- });
667
- } else {
668
- scope.set(named, node);
669
- }
670
- }
671
- } else if (imp.isWildcard) {
672
- for (const [exportName, node] of mod.exports) {
673
- scope.set(`${imp.alias}.${exportName}`, node);
674
- }
675
- } else {
676
- for (const [exportName, node] of mod.exports) {
677
- scope.set(`${imp.alias}.${exportName}`, node);
678
- }
679
- }
680
- }
681
- return { scope, modules, errors };
682
- }
683
- /**
684
- * Recursively resolve a single module file.
685
- * Cycle detection: if `canonicalPath` is already in `inProgress`, throws.
686
- * Transitive errors (cycles, missing, max depth) are pushed to `errors` array.
687
- */
688
- async _resolveModule(canonicalPath, importedBy, options, depth, errors) {
689
- const maxDepth = options.maxDepth ?? 32;
690
- if (depth > maxDepth) {
691
- throw new Error(`Max depth (${maxDepth}) exceeded resolving '${canonicalPath}'`);
692
- }
693
- if (this.inProgress.has(canonicalPath)) {
694
- const chain = [...this.inProgress, canonicalPath];
695
- throw new Error(`Circular import detected: ${chain.join(" \u2192 ")}`);
696
- }
697
- if (this.cache.has(canonicalPath)) {
698
- return this.cache.get(canonicalPath);
699
- }
700
- this.inProgress.add(canonicalPath);
701
- try {
702
- let source;
703
- if (isRegistryImport(canonicalPath) && options.registryBaseUrl) {
704
- try {
705
- source = await this._fetchRegistrySource(canonicalPath, options.registryBaseUrl);
706
- } catch {
707
- throw new Error(
708
- `Registry unavailable for '${canonicalPath}' (imported from '${importedBy}')`
709
- );
710
- }
711
- } else if (isCrdtImport(canonicalPath)) {
712
- try {
713
- source = await this._fetchCrdtSource(canonicalPath);
714
- } catch (err) {
715
- throw new Error(
716
- `CRDT feed unavailable for '${canonicalPath}' (imported from '${importedBy}'): ${err instanceof Error ? err.message : String(err)}`
717
- );
718
- }
719
- } else {
720
- try {
721
- const reader = options.readFile ?? this._defaultReader();
722
- source = await reader(canonicalPath);
723
- } catch {
724
- throw new Error(`File not found: '${canonicalPath}' (imported from '${importedBy}')`);
725
- }
726
- }
727
- const { HoloScriptPlusParser } = await import('./parser.cjs');
728
- const parser = new HoloScriptPlusParser({ enableTypeScriptImports: true });
729
- const result = parser.parse(source);
730
- if (!result.success && result.errors.length > 0) {
731
- throw new Error(
732
- `Parse error in '${canonicalPath}': ${result.errors[0]?.message ?? "unknown error"}`
733
- );
734
- }
735
- const exports$1 = this._extractExports(result);
736
- const transitiveDeps = [];
737
- const subImports = result.ast?.imports ?? [];
738
- const baseDir = canonicalPath.replace(/\/[^/]+$/, "");
739
- for (const subImp of subImports) {
740
- const subPath = isRegistryImport(subImp.path) || isCrdtImport(subImp.path) ? subImp.path : resolveImportPath(subImp.path, baseDir);
741
- transitiveDeps.push(subPath);
742
- if (!this.cache.has(subPath)) {
743
- try {
744
- const subMod = await this._resolveModule(
745
- subPath,
746
- canonicalPath,
747
- options,
748
- depth + 1,
749
- errors
750
- );
751
- for (const [k, v] of subMod.exports) {
752
- if (!exports$1.has(k)) exports$1.set(k, v);
753
- }
754
- } catch (err) {
755
- const msg = err instanceof Error ? err.message : String(err);
756
- errors.push({
757
- importPath: subImp.path,
758
- message: msg,
759
- code: msg.startsWith("Circular") ? "cycle" : msg.startsWith("Max depth") ? "max_depth" : msg.startsWith("Parse error") ? "parse_error" : msg.startsWith("Registry") ? "registry_unavailable" : "not_found",
760
- ...msg.startsWith("Circular") ? { cycle: [subPath] } : {}
761
- });
762
- }
763
- }
764
- }
765
- const mod = {
766
- canonicalPath,
767
- result,
768
- exports: exports$1,
769
- dependencies: transitiveDeps
770
- };
771
- this.cache.set(canonicalPath, mod);
772
- return mod;
773
- } finally {
774
- this.inProgress.delete(canonicalPath);
775
- }
776
- }
777
- /**
778
- * Fetch native string sources from the local LoroText Holographic CRDT.
779
- * This bridges the compiler directly into the decentralized HoloMesh feed.
780
- */
781
- async _fetchCrdtSource(importPath) {
782
- if (importPath !== "crdt://holomesh/feed") {
783
- throw new Error(`Unknown CRDT namespace. Only crdt://holomesh/feed is supported.`);
784
- }
785
- try {
786
- const fs = await import('fs/promises');
787
- const path = await import('path');
788
- const pkgName = "@loro/loro";
789
- const { LoroDoc } = await import(
790
- /* @vite-ignore */
791
- pkgName
792
- );
793
- const crdtPath = path.resolve(process.cwd(), ".holomesh/worldstate.crdt");
794
- const bytes = await fs.readFile(crdtPath);
795
- const doc = new LoroDoc();
796
- doc.import(bytes);
797
- const feed = doc.getText("feed");
798
- return feed.toString();
799
- } catch (e) {
800
- throw new Error(`CRDT Sync Error: ${e instanceof Error ? e.message : String(e)}`);
801
- }
802
- }
803
- /**
804
- * Fetch source code from the community registry for @username/name imports.
805
- * Calls GET {registryBaseUrl}/api/scene/{name} and returns the scene code.
806
- */
807
- async _fetchRegistrySource(importPath, registryBaseUrl) {
808
- const parsed = parseRegistryImport(importPath);
809
- if (!parsed) {
810
- throw new Error(`Invalid registry import path: '${importPath}'`);
811
- }
812
- const url = `${registryBaseUrl.replace(/\/$/, "")}/api/registry/${encodeURIComponent(parsed.username)}/${encodeURIComponent(parsed.name)}`;
813
- const response = await fetch(url);
814
- if (!response.ok) {
815
- throw new Error(`Registry returned ${response.status} for '${importPath}'`);
816
- }
817
- const data = await response.json();
818
- if (!data.code || typeof data.code !== "string") {
819
- throw new Error(`Registry returned no code for '${importPath}'`);
820
- }
821
- return data.code;
822
- }
823
- /**
824
- * Extract @exported nodes from a parse result.
825
- *
826
- * Handles two AST shapes that HoloScriptPlusParser can produce:
827
- * 1. Single node file: result.ast.root IS the node; its directives contain @export
828
- * 2. Fragment file: result.ast.root.children[] are nodes, each may have @export directives
829
- */
830
- _extractExports(result) {
831
- const exports$1 = /* @__PURE__ */ new Map();
832
- const ast = result.ast;
833
- if (!ast) return exports$1;
834
- const root = ast.root;
835
- if (!root) return exports$1;
836
- const seen = /* @__PURE__ */ new Set();
837
- const nodesToCheck = [];
838
- const addNode = (n) => {
839
- if (!n || typeof n !== "object") return;
840
- const node = n;
841
- if (!seen.has(node)) {
842
- seen.add(node);
843
- nodesToCheck.push(node);
844
- }
845
- };
846
- addNode(root);
847
- if (Array.isArray(root.children)) {
848
- for (const child of root.children) addNode(child);
849
- }
850
- if (Array.isArray(ast.body)) {
851
- for (const n of ast.body) addNode(n);
852
- }
853
- if (Array.isArray(ast.children)) {
854
- for (const n of ast.children) addNode(n);
855
- }
856
- for (const node of nodesToCheck) {
857
- const nodeRec = node;
858
- const directives = nodeRec.directives ?? [];
859
- const exportDir = directives.find((d) => d?.type === "export");
860
- if (exportDir) {
861
- const exportName = exportDir.exportName ?? nodeRec.id ?? nodeRec.name ?? nodeRec.type;
862
- exports$1.set(exportName, node);
863
- }
864
- }
865
- return exports$1;
866
- }
867
- /**
868
- * Default Node.js file reader. Only used on server-side / CLI.
869
- * Throws in environments without the 'fs' module (browser, XR).
870
- */
871
- _defaultReader() {
872
- return async (filePath) => {
873
- try {
874
- const fs = await import('fs/promises');
875
- return await fs.readFile(filePath, "utf-8");
876
- } catch {
877
- throw new Error(
878
- `Cannot read '${filePath}': no readFile option provided and fs is unavailable`
879
- );
880
- }
881
- };
882
- }
883
- /** Clear the module cache (useful between test runs) */
884
- clearCache() {
885
- this.cache.clear();
886
- this.inProgress.clear();
887
- }
888
- /** Return the set of canonical paths currently cached */
889
- getCachedPaths() {
890
- return [...this.cache.keys()];
891
- }
892
- /** Return a resolved module from cache, or undefined */
893
- getCached(canonicalPath) {
894
- return this.cache.get(canonicalPath);
895
- }
896
- };
897
- function hashSourceCode(source) {
898
- return crypto.createHash("sha256").update(source, "utf8").digest("hex");
899
- }
900
- function generateCacheKey(contentHash, type, prefix) {
901
- return `${prefix}:${type}:${contentHash}`;
902
- }
903
- function serializeASTNode(node) {
904
- return JSON.stringify(node, null, 0);
905
- }
906
- function hashASTSubtree(node) {
907
- const serialized = serializeASTNode(node);
908
- return hashSourceCode(serialized);
909
- }
910
- var SemanticCache = class {
911
- constructor(options = {}) {
912
- this.redis = null;
913
- this.memoryCache = /* @__PURE__ */ new Map();
914
- this.stats = {
915
- hits: 0,
916
- misses: 0,
917
- totalLatencyMs: 0,
918
- lookupCount: 0
919
- };
920
- this.redisConnected = false;
921
- this.initialized = false;
922
- this.options = {
923
- redisUrl: options.redisUrl ?? "redis://localhost:6379",
924
- keyPrefix: options.keyPrefix ?? "holoscript:semantic",
925
- ttl: options.ttl ?? 7 * 24 * 60 * 60,
926
- // 7 days in seconds
927
- version: options.version ?? "1.0.0",
928
- debug: options.debug ?? false,
929
- connectionTimeout: options.connectionTimeout ?? 5e3,
930
- maxRetries: options.maxRetries ?? 3
931
- };
932
- }
933
- /**
934
- * Initialize the cache (connect to Redis if available)
935
- */
936
- async initialize() {
937
- if (this.initialized) return;
938
- try {
939
- const Redis = await this.loadRedisClient();
940
- if (Redis) {
941
- this.redis = new Redis(this.options.redisUrl, {
942
- connectTimeout: this.options.connectionTimeout,
943
- maxRetriesPerRequest: this.options.maxRetries,
944
- lazyConnect: true,
945
- enableOfflineQueue: false
946
- });
947
- this.redis.on("connect", () => {
948
- this.redisConnected = true;
949
- this.log("Redis connected");
950
- });
951
- this.redis.on("error", (error) => {
952
- this.log(`Redis error: ${error.message}`);
953
- this.redisConnected = false;
954
- });
955
- this.redis.on("close", () => {
956
- this.redisConnected = false;
957
- this.log("Redis disconnected");
958
- });
959
- await this.redis.ping();
960
- this.redisConnected = true;
961
- this.log("Redis cache initialized");
962
- }
963
- } catch (error) {
964
- this.log(`Redis initialization failed: ${error}. Falling back to in-memory cache.`);
965
- this.redis = null;
966
- this.redisConnected = false;
967
- }
968
- this.initialized = true;
969
- this.log(`Semantic cache initialized (backend: ${this.getBackend()})`);
970
- }
971
- /**
972
- * Load Redis client dynamically (optional dependency)
973
- */
974
- async loadRedisClient() {
975
- try {
976
- const ioredis = await import('ioredis');
977
- return ioredis.default;
978
- } catch (error) {
979
- this.log("ioredis not installed, using in-memory cache");
980
- return null;
981
- }
982
- }
983
- /**
984
- * Get cache entry
985
- */
986
- async get(contentHash, type) {
987
- if (!this.initialized) {
988
- await this.initialize();
989
- }
990
- const startTime = Date.now();
991
- const key = generateCacheKey(contentHash, type, this.options.keyPrefix);
992
- try {
993
- let entry = null;
994
- if (this.redis && this.redisConnected) {
995
- const raw = await this.redis.get(key);
996
- if (raw) {
997
- entry = JSON.parse(raw);
998
- }
999
- } else {
1000
- const memEntry = this.memoryCache.get(key);
1001
- if (memEntry) {
1002
- entry = memEntry;
1003
- }
1004
- }
1005
- const latencyMs = Date.now() - startTime;
1006
- this.stats.totalLatencyMs += latencyMs;
1007
- this.stats.lookupCount++;
1008
- if (!entry) {
1009
- this.stats.misses++;
1010
- return {
1011
- hit: false,
1012
- reason: "not_found",
1013
- latencyMs
1014
- };
1015
- }
1016
- if (entry.version !== this.options.version) {
1017
- this.stats.misses++;
1018
- await this.delete(contentHash, type);
1019
- return {
1020
- hit: false,
1021
- reason: "version_mismatch",
1022
- latencyMs
1023
- };
1024
- }
1025
- if (!this.redis) {
1026
- const age = Date.now() - entry.createdAt;
1027
- const ttlMs = this.options.ttl * 1e3;
1028
- if (age > ttlMs) {
1029
- this.stats.misses++;
1030
- this.memoryCache.delete(key);
1031
- return {
1032
- hit: false,
1033
- reason: "expired",
1034
- latencyMs
1035
- };
1036
- }
1037
- }
1038
- entry.accessedAt = Date.now();
1039
- entry.accessCount++;
1040
- if (this.redis && this.redisConnected) {
1041
- await this.redis.set(key, JSON.stringify(entry), "EX", this.options.ttl);
1042
- } else {
1043
- this.memoryCache.set(key, entry);
1044
- }
1045
- this.stats.hits++;
1046
- this.log(`Cache HIT: ${type} (${contentHash.slice(0, 8)}...) [${latencyMs}ms]`);
1047
- return {
1048
- hit: true,
1049
- entry,
1050
- latencyMs
1051
- };
1052
- } catch (error) {
1053
- this.stats.misses++;
1054
- this.log(`Cache lookup error: ${error}`);
1055
- return {
1056
- hit: false,
1057
- reason: "redis_error",
1058
- latencyMs: Date.now() - startTime
1059
- };
1060
- }
1061
- }
1062
- /**
1063
- * Set cache entry
1064
- */
1065
- async set(contentHash, type, data, options) {
1066
- if (!this.initialized) {
1067
- await this.initialize();
1068
- }
1069
- const key = generateCacheKey(contentHash, type, this.options.keyPrefix);
1070
- const serialized = JSON.stringify(data);
1071
- const entry = {
1072
- contentHash,
1073
- type,
1074
- data,
1075
- sourcePath: options?.sourcePath,
1076
- dependencies: options?.dependencies,
1077
- createdAt: Date.now(),
1078
- accessedAt: Date.now(),
1079
- accessCount: 0,
1080
- size: serialized.length,
1081
- version: this.options.version
1082
- };
1083
- try {
1084
- if (this.redis && this.redisConnected) {
1085
- await this.redis.set(key, JSON.stringify(entry), "EX", this.options.ttl);
1086
- } else {
1087
- this.memoryCache.set(key, entry);
1088
- }
1089
- this.log(`Cache SET: ${type} (${contentHash.slice(0, 8)}...) [${entry.size} bytes]`);
1090
- } catch (error) {
1091
- this.log(`Cache set error: ${error}`);
1092
- }
1093
- }
1094
- /**
1095
- * Delete cache entry
1096
- */
1097
- async delete(contentHash, type) {
1098
- if (!this.initialized) {
1099
- await this.initialize();
1100
- }
1101
- const key = generateCacheKey(contentHash, type, this.options.keyPrefix);
1102
- try {
1103
- if (this.redis && this.redisConnected) {
1104
- await this.redis.del(key);
1105
- } else {
1106
- this.memoryCache.delete(key);
1107
- }
1108
- this.log(`Cache DELETE: ${type} (${contentHash.slice(0, 8)}...)`);
1109
- } catch (error) {
1110
- this.log(`Cache delete error: ${error}`);
1111
- }
1112
- }
1113
- /**
1114
- * Invalidate all cache entries for a type
1115
- */
1116
- async invalidateType(type) {
1117
- if (!this.initialized) {
1118
- await this.initialize();
1119
- }
1120
- let count = 0;
1121
- try {
1122
- if (this.redis && this.redisConnected) {
1123
- const pattern = `${this.options.keyPrefix}:${type}:*`;
1124
- const keys = await this.redis.keys(pattern);
1125
- for (const key of keys) {
1126
- await this.redis.del(key);
1127
- count++;
1128
- }
1129
- } else {
1130
- for (const [key, entry] of this.memoryCache.entries()) {
1131
- if (entry.type === type) {
1132
- this.memoryCache.delete(key);
1133
- count++;
1134
- }
1135
- }
1136
- }
1137
- this.log(`Invalidated ${count} entries of type: ${type}`);
1138
- } catch (error) {
1139
- this.log(`Cache invalidation error: ${error}`);
1140
- }
1141
- return count;
1142
- }
1143
- /**
1144
- * Clear all cache entries
1145
- */
1146
- async clear() {
1147
- if (!this.initialized) {
1148
- await this.initialize();
1149
- }
1150
- try {
1151
- if (this.redis && this.redisConnected) {
1152
- const pattern = `${this.options.keyPrefix}:*`;
1153
- const keys = await this.redis.keys(pattern);
1154
- for (const key of keys) {
1155
- await this.redis.del(key);
1156
- }
1157
- } else {
1158
- this.memoryCache.clear();
1159
- }
1160
- this.stats.hits = 0;
1161
- this.stats.misses = 0;
1162
- this.stats.totalLatencyMs = 0;
1163
- this.stats.lookupCount = 0;
1164
- this.log("Cache cleared");
1165
- } catch (error) {
1166
- this.log(`Cache clear error: ${error}`);
1167
- }
1168
- }
1169
- /**
1170
- * Get cache statistics
1171
- */
1172
- async getStats() {
1173
- const totalRequests = this.stats.hits + this.stats.misses;
1174
- const hitRate = totalRequests > 0 ? this.stats.hits / totalRequests : 0;
1175
- const avgLatencyMs = this.stats.lookupCount > 0 ? this.stats.totalLatencyMs / this.stats.lookupCount : 0;
1176
- let totalEntries = 0;
1177
- const entriesByType = {
1178
- "ast-subtree": 0,
1179
- "compiled-module": 0,
1180
- "compiled-object": 0,
1181
- "trait-composition": 0,
1182
- "import-resolution": 0
1183
- };
1184
- try {
1185
- if (this.redis && this.redisConnected) {
1186
- const pattern = `${this.options.keyPrefix}:*`;
1187
- const keys = await this.redis.keys(pattern);
1188
- totalEntries = keys.length;
1189
- for (const key of keys) {
1190
- const parts = key.split(":");
1191
- const type = parts[2];
1192
- if (type in entriesByType) {
1193
- entriesByType[type]++;
1194
- }
1195
- }
1196
- } else {
1197
- totalEntries = this.memoryCache.size;
1198
- for (const entry of this.memoryCache.values()) {
1199
- entriesByType[entry.type]++;
1200
- }
1201
- }
1202
- } catch (error) {
1203
- this.log(`Stats error: ${error}`);
1204
- }
1205
- return {
1206
- hits: this.stats.hits,
1207
- misses: this.stats.misses,
1208
- hitRate,
1209
- avgLatencyMs,
1210
- totalEntries,
1211
- backend: this.getBackend(),
1212
- redisConnected: this.redisConnected,
1213
- entriesByType
1214
- };
1215
- }
1216
- /**
1217
- * Get cache backend type
1218
- */
1219
- getBackend() {
1220
- return this.redis && this.redisConnected ? "redis" : "memory";
1221
- }
1222
- /**
1223
- * Close Redis connection
1224
- */
1225
- async close() {
1226
- if (this.redis) {
1227
- try {
1228
- await this.redis.quit();
1229
- this.log("Redis connection closed");
1230
- } catch (error) {
1231
- this.log(`Error closing Redis: ${error}`);
1232
- }
1233
- }
1234
- }
1235
- /**
1236
- * Debug logging
1237
- */
1238
- log(message) {
1239
- if (this.options.debug) {
1240
- console.log(`[SemanticCache] ${message}`);
1241
- }
1242
- }
1243
- };
1244
- function createSemanticCache(options) {
1245
- return new SemanticCache(options);
1246
- }
1247
- function hashContent(content) {
1248
- let hash = 0;
1249
- for (let i = 0; i < content.length; i++) {
1250
- const char = content.charCodeAt(i);
1251
- hash = (hash << 5) - hash + char;
1252
- hash = hash & hash;
1253
- }
1254
- return hash.toString(36);
1255
- }
1256
- function hashConfig2(config) {
1257
- const keys = Object.keys(config).sort();
1258
- const parts = [];
1259
- for (const key of keys) {
1260
- const value = config[key];
1261
- parts.push(`${key}:${JSON.stringify(value)}`);
1262
- }
1263
- const str = parts.join("|");
1264
- let hash = 5381;
1265
- for (let i = 0; i < str.length; i++) {
1266
- hash = (hash << 5) + hash ^ str.charCodeAt(i);
1267
- }
1268
- return (hash >>> 0).toString(36);
1269
- }
1270
- function serializeObject(obj) {
1271
- return JSON.stringify({
1272
- name: obj.name,
1273
- properties: obj.properties,
1274
- traits: obj.traits,
1275
- children: obj.children?.map(serializeObject),
1276
- logic: obj.logic
1277
- // logic might not be directly on HoloObjectDecl but used in diff
1278
- });
1279
- }
1280
- function serializeProperty(prop) {
1281
- return JSON.stringify({ key: prop.key, value: prop.value });
1282
- }
1283
- var IncrementalCompiler = class _IncrementalCompiler {
1284
- constructor(traitGraph, options) {
1285
- this.cache = /* @__PURE__ */ new Map();
1286
- this.previousAST = null;
1287
- this.stateSnapshot = null;
1288
- this.dependencyGraph = /* @__PURE__ */ new Map();
1289
- this.semanticCache = null;
1290
- this.traitGraph = traitGraph || globalTraitGraph;
1291
- if (options?.enableSemanticCache) {
1292
- this.semanticCache = createSemanticCache({
1293
- redisUrl: options.redisUrl,
1294
- ttl: options.cacheTTL,
1295
- debug: false
1296
- });
1297
- this.semanticCache.initialize().catch((err) => {
1298
- console.warn(`Semantic cache initialization failed: ${err}`);
1299
- this.semanticCache = null;
1300
- });
1301
- }
1302
- }
1303
- /**
1304
- * Diff two ASTs and return the changes
1305
- */
1306
- diff(oldAST, newAST) {
1307
- const changes = [];
1308
- const addedObjects = [];
1309
- const removedObjects = [];
1310
- const modifiedObjects = [];
1311
- const unchangedObjects = [];
1312
- if (!oldAST) {
1313
- const allObjects = this.collectObjectNames(newAST);
1314
- return {
1315
- hasChanges: true,
1316
- changes: allObjects.map((name) => ({
1317
- type: "added",
1318
- path: [name],
1319
- nodeName: name,
1320
- nodeType: "object",
1321
- newValue: this.findObject(newAST, name)
1322
- })),
1323
- addedObjects: allObjects,
1324
- removedObjects: [],
1325
- modifiedObjects: [],
1326
- unchangedObjects: []
1327
- };
1328
- }
1329
- const oldObjects = /* @__PURE__ */ new Map();
1330
- const newObjects = /* @__PURE__ */ new Map();
1331
- this.collectObjects(oldAST, oldObjects);
1332
- this.collectObjects(newAST, newObjects);
1333
- for (const [name, obj] of newObjects) {
1334
- if (!oldObjects.has(name)) {
1335
- addedObjects.push(name);
1336
- changes.push({
1337
- type: "added",
1338
- path: [name],
1339
- nodeName: name,
1340
- nodeType: "object",
1341
- newValue: obj
1342
- });
1343
- }
1344
- }
1345
- for (const [name, obj] of oldObjects) {
1346
- if (!newObjects.has(name)) {
1347
- removedObjects.push(name);
1348
- changes.push({
1349
- type: "removed",
1350
- path: [name],
1351
- nodeName: name,
1352
- nodeType: "object",
1353
- oldValue: obj
1354
- });
1355
- }
1356
- }
1357
- for (const [name, newObj] of newObjects) {
1358
- if (oldObjects.has(name)) {
1359
- const oldObj = oldObjects.get(name);
1360
- const objectChanges = this.diffObject(oldObj, newObj, [name]);
1361
- if (objectChanges.length > 0) {
1362
- modifiedObjects.push(name);
1363
- changes.push(...objectChanges);
1364
- } else {
1365
- unchangedObjects.push(name);
1366
- }
1367
- }
1368
- }
1369
- return {
1370
- hasChanges: changes.length > 0,
1371
- changes,
1372
- addedObjects,
1373
- removedObjects,
1374
- modifiedObjects,
1375
- unchangedObjects
1376
- };
1377
- }
1378
- /**
1379
- * Diff two objects and return property-level changes
1380
- */
1381
- diffObject(oldObj, newObj, path) {
1382
- const changes = [];
1383
- const oldProps = new Map(oldObj.properties?.map((p) => [p.key, p]) || []);
1384
- const newProps = new Map(newObj.properties?.map((p) => [p.key, p]) || []);
1385
- for (const [key, newProp] of newProps) {
1386
- if (!oldProps.has(key)) {
1387
- changes.push({
1388
- type: "added",
1389
- path: [...path, key],
1390
- nodeName: key,
1391
- nodeType: "property",
1392
- newValue: newProp.value
1393
- });
1394
- } else {
1395
- const oldProp = oldProps.get(key);
1396
- if (serializeProperty(oldProp) !== serializeProperty(newProp)) {
1397
- changes.push({
1398
- type: "modified",
1399
- path: [...path, key],
1400
- nodeName: key,
1401
- nodeType: "property",
1402
- oldValue: oldProp.value,
1403
- newValue: newProp.value
1404
- });
1405
- }
1406
- }
1407
- }
1408
- for (const key of oldProps.keys()) {
1409
- if (!newProps.has(key)) {
1410
- changes.push({
1411
- type: "removed",
1412
- path: [...path, key],
1413
- nodeName: key,
1414
- nodeType: "property",
1415
- oldValue: oldProps.get(key).value
1416
- });
1417
- }
1418
- }
1419
- const oldTraitUsages = this.extractTraitUsages(oldObj.traits || []);
1420
- const newTraitUsages = this.extractTraitUsages(newObj.traits || []);
1421
- const oldTraitMap = new Map(oldTraitUsages.map((t) => [t.name, t]));
1422
- const newTraitMap = new Map(newTraitUsages.map((t) => [t.name, t]));
1423
- for (const [name, newTrait] of newTraitMap) {
1424
- if (!oldTraitMap.has(name)) {
1425
- changes.push({
1426
- type: "added",
1427
- path: [...path, "@" + name],
1428
- nodeName: name,
1429
- nodeType: "trait",
1430
- newValue: newTrait
1431
- });
1432
- }
1433
- }
1434
- for (const [name, oldTrait] of oldTraitMap) {
1435
- if (!newTraitMap.has(name)) {
1436
- changes.push({
1437
- type: "removed",
1438
- path: [...path, "@" + name],
1439
- nodeName: name,
1440
- nodeType: "trait",
1441
- oldValue: oldTrait
1442
- });
1443
- }
1444
- }
1445
- for (const [name, newTrait] of newTraitMap) {
1446
- const oldTrait = oldTraitMap.get(name);
1447
- if (oldTrait && oldTrait.configHash !== newTrait.configHash) {
1448
- changes.push({
1449
- type: "modified",
1450
- path: [...path, "@" + name],
1451
- nodeName: name,
1452
- nodeType: "trait",
1453
- oldValue: oldTrait,
1454
- newValue: newTrait
1455
- });
1456
- }
1457
- }
1458
- if (JSON.stringify(oldObj.logic) !== JSON.stringify(newObj.logic)) {
1459
- changes.push({
1460
- type: "modified",
1461
- path: [...path, "logic"],
1462
- nodeName: "logic",
1463
- nodeType: "logic",
1464
- oldValue: oldObj.logic,
1465
- newValue: newObj.logic
1466
- });
1467
- }
1468
- const oldChildren = new Map((oldObj.children || []).map((c) => [c.name, c]));
1469
- const newChildren = new Map((newObj.children || []).map((c) => [c.name, c]));
1470
- for (const [name, newChild] of newChildren) {
1471
- if (!oldChildren.has(name)) {
1472
- changes.push({
1473
- type: "added",
1474
- path: [...path, name],
1475
- nodeName: name,
1476
- nodeType: "object",
1477
- newValue: newChild
1478
- });
1479
- } else {
1480
- const childChanges = this.diffObject(oldChildren.get(name), newChild, [...path, name]);
1481
- changes.push(...childChanges);
1482
- }
1483
- }
1484
- for (const name of oldChildren.keys()) {
1485
- if (!newChildren.has(name)) {
1486
- changes.push({
1487
- type: "removed",
1488
- path: [...path, name],
1489
- nodeName: name,
1490
- nodeType: "object",
1491
- oldValue: oldChildren.get(name)
1492
- });
1493
- }
1494
- }
1495
- return changes;
1496
- }
1497
- /**
1498
- * Extract trait usages with config hashes from trait array
1499
- * Handles both string traits and trait objects with config
1500
- */
1501
- extractTraitUsages(traits) {
1502
- return traits.map((t) => {
1503
- if (typeof t === "string") {
1504
- return {
1505
- name: t,
1506
- config: {},
1507
- configHash: hashConfig2({})
1508
- };
1509
- }
1510
- if (t && typeof t === "object") {
1511
- const traitObj = t;
1512
- if ("name" in traitObj) {
1513
- const name = String(traitObj.name);
1514
- const config = {};
1515
- for (const [key, value] of Object.entries(traitObj)) {
1516
- if (key !== "name") {
1517
- config[key] = value;
1518
- }
1519
- }
1520
- return {
1521
- name,
1522
- config,
1523
- configHash: hashConfig2(config)
1524
- };
1525
- }
1526
- const keys = Object.keys(traitObj);
1527
- if (keys.length === 1) {
1528
- const name = keys[0];
1529
- const config = traitObj[name] || {};
1530
- return {
1531
- name,
1532
- config: typeof config === "object" ? config : {},
1533
- configHash: hashConfig2(typeof config === "object" ? config : {})
1534
- };
1535
- }
1536
- }
1537
- return {
1538
- name: String(t),
1539
- config: {},
1540
- configHash: hashConfig2({})
1541
- };
1542
- });
1543
- }
1544
- /**
1545
- * Collect all object names from a composition
1546
- */
1547
- collectObjectNames(composition) {
1548
- const names = [];
1549
- const collectFromObject = (obj) => {
1550
- names.push(obj.name);
1551
- obj.children?.forEach(collectFromObject);
1552
- };
1553
- composition.objects?.forEach(collectFromObject);
1554
- composition.spatialGroups?.forEach((group) => {
1555
- names.push(group.name);
1556
- group.objects?.forEach(collectFromObject);
1557
- });
1558
- return names;
1559
- }
1560
- /**
1561
- * Collect all objects into a map
1562
- */
1563
- collectObjects(composition, map) {
1564
- const collectFromObject = (obj) => {
1565
- map.set(obj.name, obj);
1566
- obj.children?.forEach(collectFromObject);
1567
- };
1568
- composition.objects?.forEach(collectFromObject);
1569
- composition.spatialGroups?.forEach((group) => {
1570
- group.objects?.forEach(collectFromObject);
1571
- });
1572
- }
1573
- /**
1574
- * Find an object by name in a composition
1575
- */
1576
- findObject(composition, name) {
1577
- const searchInObject = (obj) => {
1578
- if (obj.name === name) return obj;
1579
- for (const child of obj.children || []) {
1580
- const found = searchInObject(child);
1581
- if (found) return found;
1582
- }
1583
- return void 0;
1584
- };
1585
- for (const obj of composition.objects || []) {
1586
- const found = searchInObject(obj);
1587
- if (found) return found;
1588
- }
1589
- for (const group of composition.spatialGroups || []) {
1590
- for (const obj of group.objects || []) {
1591
- const found = searchInObject(obj);
1592
- if (found) return found;
1593
- }
1594
- }
1595
- return void 0;
1596
- }
1597
- /**
1598
- * Get cached compilation for an object if still valid
1599
- */
1600
- getCached(objectName, currentHash) {
1601
- const entry = this.cache.get(objectName);
1602
- if (entry && entry.hash === currentHash) {
1603
- return entry;
1604
- }
1605
- return null;
1606
- }
1607
- /**
1608
- * Store compilation result in cache
1609
- */
1610
- setCached(objectName, hash, compiledCode, dependencies) {
1611
- this.cache.set(objectName, {
1612
- hash,
1613
- compiledCode,
1614
- dependencies,
1615
- timestamp: Date.now()
1616
- });
1617
- }
1618
- /**
1619
- * Save current state for hot reload
1620
- */
1621
- saveState(states) {
1622
- this.stateSnapshot = {
1623
- objectStates: new Map(states),
1624
- timestamp: Date.now()
1625
- };
1626
- }
1627
- /**
1628
- * Restore state after hot reload
1629
- */
1630
- restoreState() {
1631
- return this.stateSnapshot;
1632
- }
1633
- /**
1634
- * Clear state snapshot
1635
- */
1636
- clearState() {
1637
- this.stateSnapshot = null;
1638
- }
1639
- /**
1640
- * Update dependency graph
1641
- */
1642
- updateDependencies(objectName, dependencies) {
1643
- this.dependencyGraph.set(objectName, new Set(dependencies));
1644
- }
1645
- /**
1646
- * Get objects that depend on a given object
1647
- */
1648
- getDependents(objectName) {
1649
- const dependents = [];
1650
- for (const [name, deps] of this.dependencyGraph) {
1651
- if (deps.has(objectName)) {
1652
- dependents.push(name);
1653
- }
1654
- }
1655
- return dependents;
1656
- }
1657
- /**
1658
- * Get all objects that need recompilation due to a change
1659
- * Enhanced with trait-aware dependency tracking
1660
- */
1661
- getRecompilationSet(changedObjects) {
1662
- const toRecompile = new Set(changedObjects);
1663
- const queue = [...changedObjects];
1664
- while (queue.length > 0) {
1665
- const current = queue.shift();
1666
- const dependents = this.getDependents(current);
1667
- for (const dep of dependents) {
1668
- if (!toRecompile.has(dep)) {
1669
- toRecompile.add(dep);
1670
- queue.push(dep);
1671
- }
1672
- }
1673
- }
1674
- const traitRecompileSet = this.traitGraph.calculateRecompilationSet(changedObjects);
1675
- for (const obj of traitRecompileSet) {
1676
- toRecompile.add(obj);
1677
- }
1678
- return toRecompile;
1679
- }
1680
- /**
1681
- * Get trait changes for specific objects
1682
- * Used for fine-grained trait config change detection
1683
- */
1684
- getTraitChanges(objectName, newTraits) {
1685
- return this.traitGraph.detectTraitChanges(objectName, newTraits);
1686
- }
1687
- /**
1688
- * Get the trait dependency graph for external access
1689
- */
1690
- getTraitGraph() {
1691
- return this.traitGraph;
1692
- }
1693
- // ===========================================================================
1694
- // IMPORT RESOLUTION (Asset Pipeline)
1695
- // ===========================================================================
1696
- /**
1697
- * Resolve all `@import` directives in a `HSPlusCompileResult`, merge the
1698
- * imported exports into a scope, and register cross-file edges in the
1699
- * `TraitDependencyGraph` for incremental recompilation.
1700
- *
1701
- * This method is **async** because it may read files from disk (or any
1702
- * injected async reader).
1703
- *
1704
- * ### Typical usage
1705
- * ```ts
1706
- * const parser = new HoloScriptPlusParser({ enableTypeScriptImports: true });
1707
- * const result = parser.parse(source);
1708
- *
1709
- * const compiler = new IncrementalCompiler();
1710
- * const { importScope, importErrors } = await compiler.resolveImports(
1711
- * result,
1712
- * { baseDir: '/project', sourceFile: '/project/scene.hs' }
1713
- * );
1714
- * ```
1715
- *
1716
- * @param result Parse result that may contain `ast.imports`
1717
- * @param options Must include `baseDir` (and optionally `sourceFile`, `readFile`)
1718
- * @returns `{ scope, modules, errors }` from `ImportResolver.resolve()`
1719
- */
1720
- async resolveImports(result, options) {
1721
- const baseDir = options.baseDir ?? "/";
1722
- const sourceFile = options.sourceFile ?? `${baseDir}/unknown.hs`;
1723
- const resolver = new ImportResolver();
1724
- const resolution = await resolver.resolve(result, sourceFile, {
1725
- baseDir,
1726
- readFile: options.readFile
1727
- });
1728
- const imports = result.ast?.imports ?? [];
1729
- this.traitGraph.clearImportsForFile(sourceFile);
1730
- for (const imp of imports) {
1731
- const canonicalPath = resolveImportPath(imp.path, baseDir);
1732
- this.traitGraph.registerImport(sourceFile, canonicalPath);
1733
- }
1734
- return resolution;
1735
- }
1736
- // ===========================================================================
1737
- // RBAC ENFORCEMENT
1738
- // ===========================================================================
1739
- /**
1740
- * Validate agent has permission for incremental compilation.
1741
- * Skips validation when no token is provided (backwards compatibility / testing).
1742
- */
1743
- validateAccess(agentToken) {
1744
- if (!agentToken) return;
1745
- const rbac = platform.getRBAC();
1746
- const decision = rbac.checkAccess({
1747
- token: agentToken,
1748
- resourceType: platform.ResourceType.AST,
1749
- operation: "read",
1750
- expectedWorkflowStep: platform.WorkflowStep.GENERATE_ASSEMBLY
1751
- });
1752
- if (!decision.allowed) {
1753
- throw new UnauthorizedIncrementalCompilerAccessError(decision, "IncrementalCompiler");
1754
- }
1755
- }
1756
- /**
1757
- * Perform incremental compilation
1758
- */
1759
- async compile(newAST, compileObject, options = {}) {
1760
- const { preserveState = true, forceRecompile = [], skipUnchanged = true, agentToken } = options;
1761
- this.validateAccess(agentToken);
1762
- const diffResult = this.diff(this.previousAST, newAST);
1763
- const changedObjects = [
1764
- ...diffResult.addedObjects,
1765
- ...diffResult.modifiedObjects,
1766
- ...forceRecompile
1767
- ];
1768
- const recompileSet = this.getRecompilationSet(changedObjects);
1769
- for (const removed of diffResult.removedObjects) {
1770
- const dependents = this.getDependents(removed);
1771
- for (const dep of dependents) {
1772
- recompileSet.add(dep);
1773
- }
1774
- }
1775
- const recompiledObjects = [];
1776
- const cachedObjects = [];
1777
- const compiledParts = [];
1778
- const allObjects = /* @__PURE__ */ new Map();
1779
- this.collectObjects(newAST, allObjects);
1780
- for (const [name, obj] of allObjects) {
1781
- const hash = hashContent(serializeObject(obj));
1782
- const traitUsages = this.extractTraitUsages(obj.traits || []);
1783
- this.traitGraph.registerObject({
1784
- objectName: name,
1785
- sourceId: newAST.name || "default",
1786
- traits: traitUsages,
1787
- template: obj.template
1788
- });
1789
- if (skipUnchanged && !recompileSet.has(name)) {
1790
- if (this.semanticCache) {
1791
- const astHash = hashASTSubtree(obj);
1792
- const semanticResult = await this.semanticCache.get(astHash, "compiled-object");
1793
- if (semanticResult.hit) {
1794
- cachedObjects.push(name);
1795
- compiledParts.push(semanticResult.entry.data);
1796
- continue;
1797
- }
1798
- }
1799
- const cached = this.getCached(name, hash);
1800
- if (cached) {
1801
- cachedObjects.push(name);
1802
- compiledParts.push(cached.compiledCode);
1803
- continue;
1804
- }
1805
- }
1806
- const compiled = compileObject(obj);
1807
- recompiledObjects.push(name);
1808
- compiledParts.push(compiled);
1809
- this.setCached(name, hash, compiled, []);
1810
- if (this.semanticCache) {
1811
- const astHash = hashASTSubtree(obj);
1812
- await this.semanticCache.set(astHash, "compiled-object", compiled, {
1813
- sourcePath: newAST.name,
1814
- dependencies: []
1815
- });
1816
- }
1817
- }
1818
- this.previousAST = newAST;
1819
- return {
1820
- fullRecompile: cachedObjects.length === 0,
1821
- recompiledObjects,
1822
- cachedObjects,
1823
- statePreserved: preserveState && this.stateSnapshot !== null,
1824
- compiledCode: compiledParts.join("\n\n"),
1825
- changes: diffResult
1826
- };
1827
- }
1828
- /**
1829
- * Reset compiler state
1830
- */
1831
- reset() {
1832
- this.cache.clear();
1833
- this.previousAST = null;
1834
- this.stateSnapshot = null;
1835
- this.dependencyGraph.clear();
1836
- }
1837
- /**
1838
- * Get cache statistics including trait graph info
1839
- */
1840
- async getStats() {
1841
- let dependencyEdges = 0;
1842
- for (const deps of this.dependencyGraph.values()) {
1843
- dependencyEdges += deps.size;
1844
- }
1845
- const stats = {
1846
- cacheSize: this.cache.size,
1847
- objectsCached: Array.from(this.cache.keys()),
1848
- dependencyEdges,
1849
- traitGraphStats: this.traitGraph.getStats()
1850
- };
1851
- if (this.semanticCache) {
1852
- const semanticStats = await this.semanticCache.getStats();
1853
- return {
1854
- ...stats,
1855
- semanticCache: semanticStats
1856
- };
1857
- }
1858
- return stats;
1859
- }
1860
- /**
1861
- * Get semantic cache statistics
1862
- */
1863
- async getSemanticCacheStats() {
1864
- if (!this.semanticCache) {
1865
- return null;
1866
- }
1867
- return this.semanticCache.getStats();
1868
- }
1869
- /**
1870
- * Clear semantic cache
1871
- */
1872
- async clearSemanticCache() {
1873
- if (this.semanticCache) {
1874
- await this.semanticCache.clear();
1875
- }
1876
- }
1877
- /**
1878
- * Close semantic cache connection
1879
- */
1880
- async closeSemanticCache() {
1881
- if (this.semanticCache) {
1882
- await this.semanticCache.close();
1883
- }
1884
- }
1885
- /**
1886
- * Serialize compiler state for persistence
1887
- * Includes cache, dependency graph, and trait graph
1888
- */
1889
- serialize() {
1890
- const data = {
1891
- version: 1,
1892
- entries: Array.from(this.cache.entries()).map(([name, entry]) => ({
1893
- name,
1894
- entry
1895
- })),
1896
- dependencies: Array.from(this.dependencyGraph.entries()).map(([name, deps]) => ({
1897
- name,
1898
- deps: Array.from(deps)
1899
- })),
1900
- traitGraph: this.traitGraph.serialize(),
1901
- timestamp: Date.now()
1902
- };
1903
- return JSON.stringify(data);
1904
- }
1905
- /**
1906
- * Restore compiler state from serialized data
1907
- */
1908
- static deserialize(json) {
1909
- const data = JSON.parse(json);
1910
- if (data.version !== 1) {
1911
- throw new Error(`Unsupported cache version: ${data.version}`);
1912
- }
1913
- const traitGraph = TraitDependencyGraph.deserialize(data.traitGraph);
1914
- const compiler = new _IncrementalCompiler(traitGraph);
1915
- for (const { name, entry } of data.entries) {
1916
- compiler.cache.set(name, entry);
1917
- }
1918
- for (const { name, deps } of data.dependencies) {
1919
- compiler.dependencyGraph.set(name, new Set(deps));
1920
- }
1921
- return compiler;
1922
- }
1923
- };
1924
- function createIncrementalCompiler() {
1925
- return new IncrementalCompiler();
1926
- }
1927
- function serializeCache(compiler) {
1928
- compiler.getStats();
1929
- const data = {
1930
- version: 1,
1931
- entries: [],
1932
- dependencies: [],
1933
- traitGraph: compiler.getTraitGraph().serialize(),
1934
- timestamp: Date.now()
1935
- };
1936
- return JSON.stringify(data);
1937
- }
1938
- function deserializeCache(json) {
1939
- const data = JSON.parse(json);
1940
- if (data.version !== 1) {
1941
- throw new Error(`Unsupported cache version: ${data.version}`);
1942
- }
1943
- const traitGraph = TraitDependencyGraph.deserialize(data.traitGraph);
1944
- const compiler = new IncrementalCompiler(traitGraph);
1945
- for (const { name, entry } of data.entries) {
1946
- compiler.setCached(name, entry.hash, entry.compiledCode, entry.dependencies);
1947
- }
1948
- for (const { name, deps } of data.dependencies) {
1949
- compiler.updateDependencies(name, deps);
1950
- }
1951
- return compiler;
1952
- }
1953
- var UnauthorizedIncrementalCompilerAccessError = class extends Error {
1954
- constructor(decision, compilerName) {
1955
- super(
1956
- `[${compilerName}] Unauthorized access: ${decision.reason || "Access denied"}
1957
- Agent Role: ${decision.agentRole || "unknown"}
1958
- Required Permission: ${decision.requiredPermission || "unknown"}`
1959
- );
1960
- this.decision = decision;
1961
- this.compilerName = compilerName;
1962
- this.name = "UnauthorizedIncrementalCompilerAccessError";
1963
- }
1964
- };
1965
-
1966
- exports.IncrementalCompiler = IncrementalCompiler;
1967
- exports.TraitDependencyGraph = TraitDependencyGraph;
1968
- exports.UnauthorizedIncrementalCompilerAccessError = UnauthorizedIncrementalCompilerAccessError;
1969
- exports.createIncrementalCompiler = createIncrementalCompiler;
1970
- exports.deserializeCache = deserializeCache;
1971
- exports.globalTraitGraph = globalTraitGraph;
1972
- exports.serializeCache = serializeCache;
1973
- //# sourceMappingURL=chunk-FSF7EQVA.cjs.map
1974
- //# sourceMappingURL=chunk-FSF7EQVA.cjs.map