@mmapp/react-compiler 0.1.0-alpha.1 → 0.1.0-alpha.4

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 (346) hide show
  1. package/ATOM-PIPELINE.md +144 -0
  2. package/README.md +88 -40
  3. package/dist/auth-3UK75242.mjs +17 -0
  4. package/dist/babel/index.d.mts +2 -2
  5. package/dist/babel/index.d.ts +2 -2
  6. package/dist/babel/index.js +2816 -279
  7. package/dist/babel/index.mjs +2 -2
  8. package/dist/chunk-3USIFFE4.mjs +2190 -0
  9. package/dist/chunk-45YMGEVT.mjs +186 -0
  10. package/dist/chunk-4FN2AISW.mjs +148 -0
  11. package/dist/chunk-4OPI5L7G.mjs +2593 -0
  12. package/dist/chunk-4RYTKOOJ.mjs +186 -0
  13. package/dist/chunk-52XHYD2V.mjs +214 -0
  14. package/dist/chunk-5FTDWKHH.mjs +244 -0
  15. package/dist/chunk-5GUFFFGL.mjs +148 -0
  16. package/dist/chunk-5RKTOVR5.mjs +244 -0
  17. package/dist/chunk-5YDMOO4X.mjs +214 -0
  18. package/dist/chunk-64ZWEMLJ.mjs +148 -0
  19. package/dist/chunk-6XP4KSWQ.mjs +2190 -0
  20. package/dist/chunk-72QWL54I.mjs +175 -0
  21. package/dist/chunk-7B4TRI7C.mjs +4835 -0
  22. package/dist/chunk-7JRAEFRB.mjs +7510 -0
  23. package/dist/chunk-7T6Q5KAA.mjs +7506 -0
  24. package/dist/chunk-7ZKGHTNB.mjs +4952 -0
  25. package/dist/chunk-ABYPKRSB.mjs +215 -0
  26. package/dist/chunk-BZEXUPDH.mjs +175 -0
  27. package/dist/chunk-CIESM3BP.mjs +33 -0
  28. package/dist/chunk-DE3ZGQAC.mjs +148 -0
  29. package/dist/chunk-DMCY3BBG.mjs +1933 -0
  30. package/dist/chunk-DPIK3PJS.mjs +244 -0
  31. package/dist/chunk-E5IVH4RE.mjs +186 -0
  32. package/dist/chunk-E6FZNUR5.mjs +4953 -0
  33. package/dist/chunk-EJRBDQDP.mjs +2607 -0
  34. package/dist/chunk-ELO4TXJL.mjs +186 -0
  35. package/dist/chunk-EO6SYNCG.mjs +175 -0
  36. package/dist/chunk-FKRO52XH.mjs +3446 -0
  37. package/dist/chunk-FL4YAKU6.mjs +4941 -0
  38. package/dist/chunk-FYT47UBU.mjs +5076 -0
  39. package/dist/chunk-GCLGPOJZ.mjs +148 -0
  40. package/dist/chunk-GXB4JOP7.mjs +5072 -0
  41. package/dist/chunk-HFXOUMTD.mjs +175 -0
  42. package/dist/chunk-HRYR54PT.mjs +175 -0
  43. package/dist/chunk-HWIZ47US.mjs +214 -0
  44. package/dist/chunk-IB7MNPQL.mjs +4953 -0
  45. package/dist/chunk-ICSIHQCG.mjs +148 -0
  46. package/dist/chunk-J3M4GUS7.mjs +161 -0
  47. package/dist/chunk-J7JUAHS4.mjs +186 -0
  48. package/dist/chunk-JLA5VNQ3.mjs +186 -0
  49. package/dist/chunk-JQLWFCTM.mjs +214 -0
  50. package/dist/chunk-JRGFBWTN.mjs +2918 -0
  51. package/dist/chunk-KFJJCQAL.mjs +148 -0
  52. package/dist/chunk-KJUIIEQE.mjs +186 -0
  53. package/dist/chunk-KNWTHRVQ.mjs +175 -0
  54. package/dist/chunk-KSG4XSZF.mjs +175 -0
  55. package/dist/chunk-LF5N6DOU.mjs +175 -0
  56. package/dist/chunk-LJQCM2IM.mjs +214 -0
  57. package/dist/chunk-NTB7OEX2.mjs +2918 -0
  58. package/dist/chunk-NW6555WJ.mjs +186 -0
  59. package/dist/chunk-O4AUS7EU.mjs +148 -0
  60. package/dist/chunk-OMZE6VLQ.mjs +214 -0
  61. package/dist/chunk-OPJKP747.mjs +7506 -0
  62. package/dist/chunk-P4BR7WVO.mjs +2190 -0
  63. package/dist/chunk-QQHVYH2X.mjs +244 -0
  64. package/dist/chunk-R2DD5GTY.mjs +186 -0
  65. package/dist/chunk-S5QLWLLT.mjs +186 -0
  66. package/dist/chunk-SCWGT2FY.mjs +2190 -0
  67. package/dist/chunk-SMKJUSB3.mjs +2190 -0
  68. package/dist/chunk-THFYE5ZX.mjs +244 -0
  69. package/dist/chunk-UDDTWG5J.mjs +734 -0
  70. package/dist/chunk-VCAY2KGM.mjs +175 -0
  71. package/dist/chunk-VLTKQDJ3.mjs +244 -0
  72. package/dist/chunk-WBYMW4NQ.mjs +3450 -0
  73. package/dist/chunk-WECAV6QB.mjs +148 -0
  74. package/dist/chunk-WMKBXUCE.mjs +3228 -0
  75. package/dist/chunk-WVYY32LD.mjs +939 -0
  76. package/dist/chunk-XAJ5BKKL.mjs +4947 -0
  77. package/dist/chunk-XDVM4YHX.mjs +3450 -0
  78. package/dist/chunk-XG2X7AEA.mjs +175 -0
  79. package/dist/chunk-XG7Z23NQ.mjs +148 -0
  80. package/dist/chunk-XWZAOCQ7.mjs +2607 -0
  81. package/dist/chunk-Y6MA7ULW.mjs +148 -0
  82. package/dist/chunk-YMS7Q7LG.mjs +214 -0
  83. package/dist/chunk-Z2G5RZ4H.mjs +186 -0
  84. package/dist/chunk-ZA37XTGA.mjs +175 -0
  85. package/dist/chunk-ZE3KCHBM.mjs +2918 -0
  86. package/dist/cli/index.js +14720 -7199
  87. package/dist/cli/index.mjs +224 -183
  88. package/dist/codemod/cli.js +1 -1
  89. package/dist/codemod/cli.mjs +2 -2
  90. package/dist/codemod/index.d.mts +3 -3
  91. package/dist/codemod/index.d.ts +3 -3
  92. package/dist/codemod/index.js +1 -1
  93. package/dist/codemod/index.mjs +2 -2
  94. package/dist/config-PL24KEWL.mjs +219 -0
  95. package/dist/deploy-YAJGW6II.mjs +9 -0
  96. package/dist/dev-server-CrQ041KP.d.mts +79 -0
  97. package/dist/dev-server-CrQ041KP.d.ts +79 -0
  98. package/dist/dev-server-RmGHIntF.d.mts +113 -0
  99. package/dist/dev-server-RmGHIntF.d.ts +113 -0
  100. package/dist/dev-server.d.mts +2 -2
  101. package/dist/dev-server.d.ts +2 -2
  102. package/dist/dev-server.js +6424 -1597
  103. package/dist/dev-server.mjs +5 -5
  104. package/dist/envelope-ChEkuHij.d.mts +265 -0
  105. package/dist/envelope-ChEkuHij.d.ts +265 -0
  106. package/dist/envelope.d.mts +2 -2
  107. package/dist/envelope.d.ts +2 -2
  108. package/dist/envelope.js +2814 -277
  109. package/dist/envelope.mjs +3 -3
  110. package/dist/index-CEKyyazf.d.mts +104 -0
  111. package/dist/index-CEKyyazf.d.ts +104 -0
  112. package/dist/index.d.mts +168 -9
  113. package/dist/index.d.ts +168 -9
  114. package/dist/index.js +5606 -681
  115. package/dist/index.mjs +217 -9
  116. package/dist/init-7FJENUDK.mjs +407 -0
  117. package/{src/cli/init.ts → dist/init-7JQMAAXS.mjs} +70 -95
  118. package/dist/init-DQDX3QK6.mjs +369 -0
  119. package/dist/init-EHO4VQ22.mjs +369 -0
  120. package/dist/init-UC3FWPIW.mjs +367 -0
  121. package/dist/init-UNSMVKIK.mjs +366 -0
  122. package/dist/init-UNV5XIDE.mjs +367 -0
  123. package/dist/project-compiler-2P4N4DR7.mjs +10 -0
  124. package/dist/project-compiler-D2LCC27O.mjs +10 -0
  125. package/dist/project-compiler-EJ3GANJE.mjs +10 -0
  126. package/dist/project-compiler-LOQKVRZJ.mjs +10 -0
  127. package/dist/project-compiler-NNK32MPG.mjs +10 -0
  128. package/dist/project-compiler-OP2VVGJQ.mjs +10 -0
  129. package/dist/project-compiler-RQ6OQKRM.mjs +10 -0
  130. package/dist/project-compiler-VWNNCHGO.mjs +10 -0
  131. package/dist/project-compiler-XVAAU4C5.mjs +10 -0
  132. package/dist/project-compiler-YES5FGMD.mjs +10 -0
  133. package/dist/project-compiler-ZB4RUYVL.mjs +10 -0
  134. package/dist/project-compiler-ZKMQDLGU.mjs +10 -0
  135. package/dist/project-decompiler-FLXCEJHS.mjs +7 -0
  136. package/dist/project-decompiler-U55HQUHW.mjs +7 -0
  137. package/dist/project-decompiler-US7GAVIC.mjs +7 -0
  138. package/dist/project-decompiler-VLPR22QF.mjs +7 -0
  139. package/dist/pull-FUS5QYZS.mjs +109 -0
  140. package/dist/pull-KOL2QAYQ.mjs +109 -0
  141. package/dist/pull-LD5ENLGY.mjs +109 -0
  142. package/dist/pull-P44LDRWB.mjs +109 -0
  143. package/dist/seed-KOGEPGOJ.mjs +154 -0
  144. package/dist/server-VW6UPCHO.mjs +277 -0
  145. package/dist/testing/index.d.mts +8 -8
  146. package/dist/testing/index.d.ts +8 -8
  147. package/dist/testing/index.js +2824 -287
  148. package/dist/testing/index.mjs +2 -2
  149. package/dist/verify-BYHUKARQ.mjs +1833 -0
  150. package/dist/verify-OQDEQYMS.mjs +1833 -0
  151. package/dist/verify-SEIXUGN4.mjs +1833 -0
  152. package/dist/vite/index.d.mts +1 -1
  153. package/dist/vite/index.d.ts +1 -1
  154. package/dist/vite/index.js +2817 -280
  155. package/dist/vite/index.mjs +3 -3
  156. package/examples/authentication/main.workflow.tsx +1 -1
  157. package/examples/authentication/mm.config.ts +1 -1
  158. package/examples/authentication/pages/LoginPage.tsx +2 -2
  159. package/examples/authentication/pages/SignupPage.tsx +2 -2
  160. package/examples/counter.workflow.tsx +1 -1
  161. package/examples/dashboard.workflow.tsx +1 -1
  162. package/examples/invoice-approval/actions/invoice.server.ts +1 -1
  163. package/examples/invoice-approval/main.workflow.tsx +1 -1
  164. package/examples/invoice-approval/mm.config.ts +1 -1
  165. package/examples/invoice-approval/pages/InvoiceDetailPage.tsx +1 -1
  166. package/examples/invoice-approval/pages/InvoiceFormPage.tsx +1 -1
  167. package/examples/invoice-approval/pages/InvoiceListPage.tsx +1 -1
  168. package/examples/todo-app.workflow.tsx +1 -1
  169. package/examples/uber-app/actions/matching.server.ts +1 -1
  170. package/examples/uber-app/actions/notifications.server.ts +1 -1
  171. package/examples/uber-app/actions/payments.server.ts +1 -1
  172. package/examples/uber-app/actions/pricing.server.ts +1 -1
  173. package/examples/uber-app/app/admin/analytics.tsx +2 -2
  174. package/examples/uber-app/app/admin/fleet.tsx +21 -21
  175. package/examples/uber-app/app/admin/surge-pricing.tsx +2 -2
  176. package/examples/uber-app/app/driver/dashboard.tsx +2 -2
  177. package/examples/uber-app/app/driver/earnings.tsx +2 -2
  178. package/examples/uber-app/app/driver/navigation.tsx +2 -2
  179. package/examples/uber-app/app/driver/ride-acceptance.tsx +2 -2
  180. package/examples/uber-app/app/rider/home.tsx +2 -2
  181. package/examples/uber-app/app/rider/payment-methods.tsx +2 -2
  182. package/examples/uber-app/app/rider/ride-history.tsx +2 -2
  183. package/examples/uber-app/app/rider/ride-tracking.tsx +2 -2
  184. package/examples/uber-app/components/DriverCard.tsx +1 -1
  185. package/examples/uber-app/components/MapView.tsx +3 -3
  186. package/examples/uber-app/components/RatingStars.tsx +2 -2
  187. package/examples/uber-app/components/RideCard.tsx +1 -1
  188. package/examples/uber-app/mm.config.ts +1 -1
  189. package/examples/uber-app/workflows/dispute-resolution.workflow.tsx +2 -2
  190. package/examples/uber-app/workflows/driver-onboarding.workflow.tsx +2 -2
  191. package/examples/uber-app/workflows/payment-processing.workflow.tsx +2 -2
  192. package/examples/uber-app/workflows/ride-request.workflow.tsx +2 -2
  193. package/package.json +10 -4
  194. package/compile-blueprint-chat.mjs +0 -99
  195. package/compile-blueprint-glass-console.mjs +0 -98
  196. package/compile-chat-defs.mjs +0 -92
  197. package/examples/uber-app/tests/payment.test.tsx +0 -129
  198. package/examples/uber-app/tests/ride-flow.test.tsx +0 -123
  199. package/package.json.backup +0 -86
  200. package/scripts/decompile.ts +0 -226
  201. package/scripts/seed-auth.ts +0 -267
  202. package/scripts/seed-uber.ts +0 -248
  203. package/scripts/validate-uber.ts +0 -119
  204. package/seed-blueprint-chat.mjs +0 -444
  205. package/seed-blueprint-glass-console.mjs +0 -445
  206. package/seed-compiled.mjs +0 -318
  207. package/src/RoundTripValidator.ts +0 -400
  208. package/src/__tests__/atom-rendering-coverage.test.ts +0 -680
  209. package/src/__tests__/auth-module-compilation.test.ts +0 -247
  210. package/src/__tests__/auth-template-compilation.test.ts +0 -589
  211. package/src/__tests__/change-extractor.test.ts +0 -142
  212. package/src/__tests__/cli-pull.test.ts +0 -73
  213. package/src/__tests__/cli-test.test.ts +0 -72
  214. package/src/__tests__/component-extractor.test.ts +0 -331
  215. package/src/__tests__/context-extractor.test.ts +0 -145
  216. package/src/__tests__/decompiler.test.ts +0 -718
  217. package/src/__tests__/define-blueprint.test.ts +0 -133
  218. package/src/__tests__/definition-validator.test.ts +0 -519
  219. package/src/__tests__/during-extractor.test.ts +0 -152
  220. package/src/__tests__/effect-extractor.test.ts +0 -107
  221. package/src/__tests__/event-emission.test.ts +0 -127
  222. package/src/__tests__/examples.test.ts +0 -236
  223. package/src/__tests__/full-blueprint-coverage.test.ts +0 -1221
  224. package/src/__tests__/golden-suite.test.ts +0 -403
  225. package/src/__tests__/grammar-island-extractor.test.ts +0 -289
  226. package/src/__tests__/instance-key.test.ts +0 -82
  227. package/src/__tests__/ir-migration.test.ts +0 -255
  228. package/src/__tests__/lock-file.test.ts +0 -117
  229. package/src/__tests__/model-extractor.test.ts +0 -195
  230. package/src/__tests__/model-field-acl.test.ts +0 -237
  231. package/src/__tests__/model-hooks.test.ts +0 -130
  232. package/src/__tests__/model-ref-resolution.test.ts +0 -268
  233. package/src/__tests__/model-roundtrip.test.ts +0 -502
  234. package/src/__tests__/model-runtime.test.ts +0 -112
  235. package/src/__tests__/model-transitions.test.ts +0 -183
  236. package/src/__tests__/nrt-action-trace.test.ts +0 -391
  237. package/src/__tests__/pipeline-hardening.test.ts +0 -413
  238. package/src/__tests__/project-compiler.test.ts +0 -546
  239. package/src/__tests__/project-decompiler.test.ts +0 -343
  240. package/src/__tests__/query-compilation.test.ts +0 -145
  241. package/src/__tests__/round-trip/PLAN.md +0 -158
  242. package/src/__tests__/round-trip/README.md +0 -52
  243. package/src/__tests__/round-trip/RESULTS.md +0 -86
  244. package/src/__tests__/round-trip/fixtures/data-heavy/main.workflow.tsx +0 -55
  245. package/src/__tests__/round-trip/fixtures/data-heavy/mm.config.ts +0 -11
  246. package/src/__tests__/round-trip/fixtures/data-heavy/models/contact.ts +0 -54
  247. package/src/__tests__/round-trip/fixtures/full-workflow/main.workflow.tsx +0 -79
  248. package/src/__tests__/round-trip/fixtures/full-workflow/mm.config.ts +0 -12
  249. package/src/__tests__/round-trip/fixtures/full-workflow/models/order.ts +0 -50
  250. package/src/__tests__/round-trip/fixtures/simple-crud/main.workflow.tsx +0 -25
  251. package/src/__tests__/round-trip/fixtures/simple-crud/mm.config.ts +0 -11
  252. package/src/__tests__/round-trip/fixtures/simple-crud/models/task.ts +0 -32
  253. package/src/__tests__/round-trip/fixtures/view-heavy/main.workflow.tsx +0 -79
  254. package/src/__tests__/round-trip/fixtures/view-heavy/mm.config.ts +0 -10
  255. package/src/__tests__/round-trip/round-trip.test.ts +0 -2598
  256. package/src/__tests__/round-trip-ir.test.ts +0 -300
  257. package/src/__tests__/round-trip.test.ts +0 -1212
  258. package/src/__tests__/route-merging.test.ts +0 -372
  259. package/src/__tests__/router-composition.test.ts +0 -489
  260. package/src/__tests__/router-extractor.test.ts +0 -176
  261. package/src/__tests__/server-action-extractor.test.ts +0 -128
  262. package/src/__tests__/smart-type-inference.test.ts +0 -365
  263. package/src/__tests__/source-envelope.test.ts +0 -284
  264. package/src/__tests__/source-fidelity.test.ts +0 -516
  265. package/src/__tests__/state-extractor.test.ts +0 -115
  266. package/src/__tests__/strict-mode.test.ts +0 -227
  267. package/src/__tests__/transition-effect-extractor.test.ts +0 -119
  268. package/src/__tests__/transition-extractor.test.ts +0 -68
  269. package/src/__tests__/ts-to-expression.test.ts +0 -462
  270. package/src/__tests__/type-generator.test.ts +0 -201
  271. package/src/__tests__/uber-validation.test.ts +0 -502
  272. package/src/action-compiler.ts +0 -361
  273. package/src/babel/emitters/experience-transform.ts +0 -199
  274. package/src/babel/emitters/ir-to-tsx-emitter.ts +0 -110
  275. package/src/babel/emitters/pure-form-emitter.ts +0 -1023
  276. package/src/babel/emitters/runtime-glue-emitter.ts +0 -39
  277. package/src/babel/extractors/change-extractor.ts +0 -199
  278. package/src/babel/extractors/component-extractor.ts +0 -907
  279. package/src/babel/extractors/computed-extractor.ts +0 -262
  280. package/src/babel/extractors/context-extractor.ts +0 -277
  281. package/src/babel/extractors/during-extractor.ts +0 -295
  282. package/src/babel/extractors/effect-extractor.ts +0 -340
  283. package/src/babel/extractors/event-extractor.ts +0 -235
  284. package/src/babel/extractors/grammar-island-extractor.ts +0 -302
  285. package/src/babel/extractors/model-extractor.ts +0 -1018
  286. package/src/babel/extractors/router-extractor.ts +0 -303
  287. package/src/babel/extractors/server-action-extractor.ts +0 -173
  288. package/src/babel/extractors/server-action-hook-extractor.ts +0 -72
  289. package/src/babel/extractors/server-state-extractor.ts +0 -88
  290. package/src/babel/extractors/state-extractor.ts +0 -214
  291. package/src/babel/extractors/transition-effect-extractor.ts +0 -176
  292. package/src/babel/extractors/transition-extractor.ts +0 -143
  293. package/src/babel/index.ts +0 -24
  294. package/src/babel/transpilers/ts-to-expression.ts +0 -674
  295. package/src/babel/visitor.ts +0 -807
  296. package/src/cli/auth.ts +0 -255
  297. package/src/cli/build.ts +0 -288
  298. package/src/cli/deploy.ts +0 -206
  299. package/src/cli/index.ts +0 -328
  300. package/src/cli/installer.ts +0 -261
  301. package/src/cli/lock-file.ts +0 -94
  302. package/src/cli/mmrc.ts +0 -22
  303. package/src/cli/pull.ts +0 -172
  304. package/src/cli/registry-client.ts +0 -175
  305. package/src/cli/test.ts +0 -397
  306. package/src/cli/type-generator.ts +0 -243
  307. package/src/codemod/__tests__/forward.test.ts +0 -239
  308. package/src/codemod/__tests__/reverse.test.ts +0 -145
  309. package/src/codemod/__tests__/round-trip.test.ts +0 -137
  310. package/src/codemod/annotation.ts +0 -97
  311. package/src/codemod/classify.ts +0 -197
  312. package/src/codemod/cli.ts +0 -207
  313. package/src/codemod/control-flow.ts +0 -409
  314. package/src/codemod/forward.ts +0 -244
  315. package/src/codemod/import-manager.ts +0 -171
  316. package/src/codemod/index.ts +0 -120
  317. package/src/codemod/reverse.ts +0 -197
  318. package/src/codemod/rules.ts +0 -174
  319. package/src/codemod/state-transform.ts +0 -126
  320. package/src/decompiler/ast-builder.ts +0 -538
  321. package/src/decompiler/config-generator.ts +0 -151
  322. package/src/decompiler/index.ts +0 -315
  323. package/src/decompiler/project-decompiler.ts +0 -1776
  324. package/src/decompiler/project.ts +0 -862
  325. package/src/decompiler/split-strategy.ts +0 -140
  326. package/src/decompiler/state-emitter.ts +0 -1053
  327. package/src/decompiler/sx-emitter.ts +0 -318
  328. package/src/decompiler/workspace-hydrator.ts +0 -189
  329. package/src/dev-server.ts +0 -238
  330. package/src/envelope/fs-tree.ts +0 -217
  331. package/src/envelope/source-envelope.ts +0 -264
  332. package/src/envelope.ts +0 -315
  333. package/src/incremental-compiler.ts +0 -401
  334. package/src/index.ts +0 -99
  335. package/src/model-compiler.ts +0 -277
  336. package/src/project-compiler.ts +0 -1629
  337. package/src/route-extractor.ts +0 -333
  338. package/src/testing/index.ts +0 -32
  339. package/src/testing/snapshot.ts +0 -252
  340. package/src/testing/test-utils.ts +0 -226
  341. package/src/types.ts +0 -68
  342. package/src/vite/index.ts +0 -288
  343. package/test-compile.mjs +0 -142
  344. package/tsconfig.json +0 -25
  345. package/tsup.config.ts +0 -23
  346. package/vitest.config.ts +0 -9
@@ -0,0 +1,2593 @@
1
+ import {
2
+ babelPlugin,
3
+ init_ts_to_expression,
4
+ transpileBlock,
5
+ ts_to_expression_exports
6
+ } from "./chunk-FYT47UBU.mjs";
7
+ import {
8
+ __toCommonJS
9
+ } from "./chunk-CIESM3BP.mjs";
10
+
11
+ // src/project-compiler.ts
12
+ import { transformSync as transformSync3 } from "@babel/core";
13
+
14
+ // src/babel/extractors/router-extractor.ts
15
+ function pathToStateName(routePath) {
16
+ if (!routePath || routePath === "" || routePath === "/") return "HOME";
17
+ return routePath.split("/").filter(Boolean).map((segment) => {
18
+ if (segment.startsWith("[") && segment.endsWith("]")) {
19
+ return segment.slice(1, -1);
20
+ }
21
+ return segment;
22
+ }).join("_").replace(/([a-z])([A-Z])/g, "$1_$2").toUpperCase().replace(/-/g, "_");
23
+ }
24
+ function pathToUrlPattern(relativePath, pageFileName = "page.tsx") {
25
+ let routePath = relativePath.replace(new RegExp(`/?${pageFileName.replace(".", "\\.")}$`), "");
26
+ routePath = routePath.replace(/\[([^\]]+)\]/g, ":$1");
27
+ return "/" + routePath;
28
+ }
29
+ function extractParams(relativePath) {
30
+ const params = [];
31
+ const paramRegex = /\[([^\]]+)\]/g;
32
+ let match;
33
+ while ((match = paramRegex.exec(relativePath)) !== null) {
34
+ params.push(match[1]);
35
+ }
36
+ return params;
37
+ }
38
+ function extractRouterWorkflow(pages, options = {}) {
39
+ const {
40
+ slug = "app-router",
41
+ pageFileName = "page.tsx",
42
+ layoutFileName = "layout.tsx"
43
+ } = options;
44
+ const pageFiles = pages.filter((p) => !p.isLayout && p.relativePath.endsWith(pageFileName));
45
+ const layoutFiles = pages.filter((p) => p.isLayout || p.relativePath.endsWith(layoutFileName));
46
+ const routeStates = [];
47
+ const stateMap = /* @__PURE__ */ new Map();
48
+ for (const page of pageFiles) {
49
+ const routePath = page.relativePath.replace(new RegExp(`/?${pageFileName.replace(".", "\\.")}$`), "");
50
+ const stateName = pathToStateName(routePath);
51
+ const urlPattern = pathToUrlPattern(page.relativePath, pageFileName);
52
+ const params = extractParams(page.relativePath);
53
+ const layoutBoundary = findLayoutBoundary(page.relativePath, layoutFiles);
54
+ const routeState = {
55
+ name: stateName,
56
+ path: urlPattern,
57
+ params,
58
+ layoutBoundary,
59
+ sourceFile: page.relativePath,
60
+ type: stateName === "HOME" ? "START" : "REGULAR"
61
+ };
62
+ routeStates.push(routeState);
63
+ stateMap.set(stateName, routeState);
64
+ }
65
+ if (!stateMap.has("HOME") && routeStates.length > 0) {
66
+ routeStates[0].type = "START";
67
+ }
68
+ const states = routeStates.map((rs) => ({
69
+ name: rs.name,
70
+ type: rs.type,
71
+ description: `Route: ${rs.path}`,
72
+ on_enter: [],
73
+ during: [],
74
+ on_exit: []
75
+ }));
76
+ const transitions = [];
77
+ let transitionId = 0;
78
+ for (const page of pageFiles) {
79
+ if (!page.navigationTargets) continue;
80
+ const fromPath = page.relativePath.replace(new RegExp(`/?${pageFileName.replace(".", "\\.")}$`), "");
81
+ const fromState = pathToStateName(fromPath);
82
+ for (const target of page.navigationTargets) {
83
+ const targetPath = target.replace(/^\//, "").replace(/\/page\.(tsx|ts|jsx|js)$/, "");
84
+ const toState = pathToStateName(targetPath);
85
+ if (stateMap.has(toState) || toState === fromState) continue;
86
+ const transitionName = `navigate_to_${toState.toLowerCase()}`;
87
+ transitions.push({
88
+ name: transitionName,
89
+ from: [fromState],
90
+ to: toState,
91
+ actions: [],
92
+ conditions: []
93
+ });
94
+ transitionId++;
95
+ }
96
+ }
97
+ if (routeStates.length > 1) {
98
+ for (const rs of routeStates) {
99
+ if (rs.type !== "START") {
100
+ transitions.push({
101
+ name: `navigate_home_from_${rs.name.toLowerCase()}`,
102
+ from: [rs.name],
103
+ to: "HOME",
104
+ actions: [],
105
+ conditions: []
106
+ });
107
+ }
108
+ }
109
+ }
110
+ const fields = [];
111
+ const seenParams = /* @__PURE__ */ new Set();
112
+ for (const rs of routeStates) {
113
+ for (const param of rs.params) {
114
+ if (seenParams.has(param)) continue;
115
+ seenParams.add(param);
116
+ fields.push({
117
+ name: param,
118
+ type: "text",
119
+ required: false,
120
+ default_value: ""
121
+ });
122
+ }
123
+ }
124
+ const routeMetadata = routeStates.map((rs) => ({
125
+ state: rs.name,
126
+ path: rs.path,
127
+ params: rs.params,
128
+ layoutBoundary: rs.layoutBoundary,
129
+ sourceFile: rs.sourceFile
130
+ }));
131
+ return {
132
+ slug,
133
+ name: "Router",
134
+ version: "1.0.0",
135
+ description: "Auto-derived router workflow from file-based routing",
136
+ category: "router",
137
+ fields,
138
+ states,
139
+ transitions,
140
+ roles: [],
141
+ tags: [{ tag_name: "auto-derived" }, { tag_name: "router" }],
142
+ metadata: {
143
+ runtime: "local",
144
+ routes: routeMetadata,
145
+ layoutBoundaries: layoutFiles.map((l) => l.relativePath)
146
+ }
147
+ };
148
+ }
149
+ function findLayoutBoundary(pageRelativePath, layoutFiles) {
150
+ const layoutPaths = layoutFiles.map((l) => l.relativePath);
151
+ const parts = pageRelativePath.split("/");
152
+ for (let i = parts.length - 1; i >= 0; i--) {
153
+ const dir = parts.slice(0, i).join("/");
154
+ const layoutPath = dir ? `${dir}/layout.tsx` : "layout.tsx";
155
+ if (layoutPaths.includes(layoutPath)) {
156
+ return layoutPath;
157
+ }
158
+ }
159
+ return void 0;
160
+ }
161
+
162
+ // src/model-compiler.ts
163
+ import { transformSync } from "@babel/core";
164
+ function extractInterfaceName(source) {
165
+ const match = source.match(/export\s+interface\s+(\w+)/);
166
+ return match ? match[1] : "Unknown";
167
+ }
168
+ function extractWorkflowAnnotation(source) {
169
+ const result = {};
170
+ const workflowMatch = source.match(/@workflow\s+(.+)/);
171
+ if (workflowMatch) {
172
+ const attrs = workflowMatch[1];
173
+ const slugM = attrs.match(/slug="([^"]+)"/);
174
+ if (slugM) result.slug = slugM[1];
175
+ const versionM = attrs.match(/version="([^"]+)"/);
176
+ if (versionM) result.version = versionM[1];
177
+ const categoryM = attrs.match(/category="([^"]+)"/);
178
+ if (categoryM) result.category = categoryM[1];
179
+ }
180
+ const descMatch = source.match(/@description\s+(.+)/);
181
+ if (descMatch) result.description = descMatch[1].trim();
182
+ return result;
183
+ }
184
+ function extractFieldOptionsRaw(source) {
185
+ const result = {};
186
+ const match = source.match(/export\s+const\s+fieldOptions\s*=\s*\{([\s\S]*?)\};/);
187
+ if (!match) return result;
188
+ const body = match[1];
189
+ const fieldRegex = /(\w+)\s*:\s*\{([^}]*)\}/g;
190
+ let fieldMatch;
191
+ while ((fieldMatch = fieldRegex.exec(body)) !== null) {
192
+ const fieldName = fieldMatch[1];
193
+ const optionsBody = fieldMatch[2];
194
+ const opts = {};
195
+ const kvRegex = /(\w+)\s*:\s*(?:'([^']*)'|"([^"]*)"|\[([^\]]*)\]|(\d+(?:\.\d+)?)|(\w+))/g;
196
+ let kvMatch;
197
+ while ((kvMatch = kvRegex.exec(optionsBody)) !== null) {
198
+ const key = kvMatch[1];
199
+ const strVal = kvMatch[2] ?? kvMatch[3];
200
+ const arrVal = kvMatch[4];
201
+ const numVal = kvMatch[5];
202
+ const identVal = kvMatch[6];
203
+ if (strVal !== void 0) {
204
+ opts[key] = strVal;
205
+ } else if (arrVal !== void 0) {
206
+ opts[key] = arrVal.split(",").map((s) => s.trim().replace(/['"]/g, "")).filter(Boolean);
207
+ } else if (numVal !== void 0) {
208
+ opts[key] = Number(numVal);
209
+ } else if (identVal !== void 0) {
210
+ if (identVal === "true") opts[key] = true;
211
+ else if (identVal === "false") opts[key] = false;
212
+ else opts[key] = identVal;
213
+ }
214
+ }
215
+ result[fieldName] = opts;
216
+ }
217
+ return result;
218
+ }
219
+ function compileModel(filename, source, options = {}) {
220
+ const mode = options.mode || "infer";
221
+ const interfaceName = extractInterfaceName(source);
222
+ const annotation = extractWorkflowAnnotation(source);
223
+ const rawFieldOptions = extractFieldOptionsRaw(source);
224
+ const parserPlugins = filename.endsWith(".tsx") ? ["typescript", "jsx"] : ["typescript"];
225
+ const babelResult = transformSync(source, {
226
+ filename,
227
+ plugins: [[babelPlugin, { mode }]],
228
+ parserOpts: { plugins: parserPlugins, attachComment: true }
229
+ });
230
+ const ir = babelResult?.metadata?.mindmatrixIR ?? createEmptyModelIR(interfaceName);
231
+ ir.category = options.categoryOverride || annotation.category || "data";
232
+ if (options.slugOverride) {
233
+ ir.slug = options.slugOverride;
234
+ }
235
+ if (ir.states.length === 0) {
236
+ ir.states.push({
237
+ name: "draft",
238
+ type: "START",
239
+ on_enter: [],
240
+ during: [],
241
+ on_exit: []
242
+ });
243
+ }
244
+ const hasStart = ir.states.some((s) => s.type === "START");
245
+ if (!hasStart && ir.states.length > 0) {
246
+ ir.states[0].type = "START";
247
+ }
248
+ if (!ir.metadata) ir.metadata = {};
249
+ const meta = ir.metadata;
250
+ meta.sourceInterface = interfaceName;
251
+ meta.fieldOptions = rawFieldOptions;
252
+ meta.provenance = {
253
+ frontend: "react-compiler",
254
+ source: "model",
255
+ compiler_version: "2.0.0"
256
+ };
257
+ return {
258
+ ir,
259
+ interfaceName,
260
+ fieldNames: ir.fields.map((f) => f.name),
261
+ transitionNames: ir.transitions.map((t2) => t2.name),
262
+ stateNames: ir.states.map((s) => s.name),
263
+ hasFieldOptions: Object.keys(rawFieldOptions).length > 0,
264
+ fieldOptions: rawFieldOptions
265
+ };
266
+ }
267
+ function compileModels(files, options = {}) {
268
+ const results = /* @__PURE__ */ new Map();
269
+ for (const [filename, source] of Object.entries(files)) {
270
+ try {
271
+ const compiled = compileModel(filename, source, options);
272
+ results.set(filename, compiled);
273
+ } catch (_err) {
274
+ const iface = extractInterfaceName(source);
275
+ results.set(filename, {
276
+ ir: createEmptyModelIR(iface),
277
+ interfaceName: iface,
278
+ fieldNames: [],
279
+ transitionNames: [],
280
+ stateNames: ["draft"],
281
+ hasFieldOptions: false,
282
+ fieldOptions: {}
283
+ });
284
+ }
285
+ }
286
+ return results;
287
+ }
288
+ function createEmptyModelIR(interfaceName) {
289
+ const slug = interfaceName.replace(/([A-Z])/g, "-$1").toLowerCase().replace(/^-/, "");
290
+ return {
291
+ slug,
292
+ name: interfaceName,
293
+ version: "1.0.0",
294
+ description: "Data model: " + interfaceName,
295
+ category: "data",
296
+ fields: [],
297
+ states: [{
298
+ name: "draft",
299
+ type: "START",
300
+ on_enter: [],
301
+ during: [],
302
+ on_exit: []
303
+ }],
304
+ transitions: [],
305
+ roles: [],
306
+ tags: [{ tag_name: "data" }, { tag_name: "model" }],
307
+ metadata: {
308
+ sourceInterface: interfaceName,
309
+ provenance: {
310
+ frontend: "react-compiler",
311
+ source: "model",
312
+ compiler_version: "2.0.0"
313
+ }
314
+ }
315
+ };
316
+ }
317
+
318
+ // src/route-extractor.ts
319
+ function filePathToUrlPattern(filePath, rootDir) {
320
+ let route = filePath;
321
+ const rootPrefix = rootDir + "/";
322
+ if (route.startsWith(rootPrefix)) {
323
+ route = route.slice(rootPrefix.length);
324
+ }
325
+ route = route.replace(/\.(tsx?|jsx?)$/, "");
326
+ route = route.replace(/\/(page|index)$/, "");
327
+ if (route === "page" || route === "index" || route === "") {
328
+ return "/";
329
+ }
330
+ route = route.replace(/\[([^\]]+)\]/g, ":$1");
331
+ return "/" + route;
332
+ }
333
+ function urlToStateName(urlPath) {
334
+ if (urlPath === "/") return "HOME";
335
+ return urlPath.split("/").filter(Boolean).map((segment) => segment.replace(/^:/, "")).join("_").replace(/([a-z])([A-Z])/g, "$1_$2").replace(/-/g, "_").toUpperCase();
336
+ }
337
+ function extractRouteParams(filePath) {
338
+ const params = [];
339
+ const regex = /\[([^\]]+)\]/g;
340
+ let match;
341
+ while ((match = regex.exec(filePath)) !== null) {
342
+ params.push(match[1]);
343
+ }
344
+ return params;
345
+ }
346
+ function routeDepth(urlPath) {
347
+ if (urlPath === "/") return 0;
348
+ return urlPath.split("/").filter(Boolean).length;
349
+ }
350
+ function isPageFile(filename, pageFileName) {
351
+ if (filename.endsWith("/" + pageFileName)) return true;
352
+ return /\.(tsx|ts|jsx|js)$/.test(filename) && !filename.endsWith(".test.ts") && !filename.endsWith(".test.tsx") && !filename.includes("layout");
353
+ }
354
+ function isLayoutFile(filename, layoutFileName) {
355
+ return filename.endsWith("/" + layoutFileName) || filename.endsWith(layoutFileName);
356
+ }
357
+ function extractRoutes(files, options = {}) {
358
+ const rootDir = options.rootDir || "app";
359
+ const pageFileName = options.pageFileName || "page.tsx";
360
+ const layoutFileName = options.layoutFileName || "layout.tsx";
361
+ const slugPrefix = options.slugPrefix || "app";
362
+ const layouts = [];
363
+ for (const filename of Object.keys(files)) {
364
+ if (isLayoutFile(filename, layoutFileName)) {
365
+ const dir = filename.replace(/\/[^/]+$/, "");
366
+ layouts.push({
367
+ sourceFile: filename,
368
+ directory: dir,
369
+ depth: dir.split("/").filter(Boolean).length
370
+ });
371
+ }
372
+ }
373
+ layouts.sort((a, b) => a.depth - b.depth);
374
+ const routes = [];
375
+ const allParams = /* @__PURE__ */ new Set();
376
+ for (const filename of Object.keys(files)) {
377
+ if (isLayoutFile(filename, layoutFileName)) continue;
378
+ if (!filename.startsWith(rootDir + "/") && !filename.startsWith(rootDir)) continue;
379
+ if (!isPageFile(filename, pageFileName)) continue;
380
+ const urlPath = filePathToUrlPattern(filename, rootDir);
381
+ const stateName = urlToStateName(urlPath);
382
+ const params = extractRouteParams(filename);
383
+ const depth = routeDepth(urlPath);
384
+ const fileDir = filename.replace(/\/[^/]+$/, "");
385
+ let layoutBoundary;
386
+ for (let i = layouts.length - 1; i >= 0; i--) {
387
+ if (fileDir.startsWith(layouts[i].directory)) {
388
+ layoutBoundary = layouts[i].sourceFile;
389
+ break;
390
+ }
391
+ }
392
+ for (const p of params) allParams.add(p);
393
+ routes.push({
394
+ path: urlPath,
395
+ stateName,
396
+ sourceFile: filename,
397
+ params,
398
+ layoutBoundary,
399
+ depth
400
+ });
401
+ }
402
+ routes.sort((a, b) => a.path.localeCompare(b.path));
403
+ const routerIR = buildRouterIR(routes, layouts, Array.from(allParams), slugPrefix);
404
+ return {
405
+ routes,
406
+ layouts,
407
+ routerIR,
408
+ allParams: Array.from(allParams)
409
+ };
410
+ }
411
+ function buildRouterIR(routes, layouts, allParams, slugPrefix) {
412
+ const states = routes.map((route) => ({
413
+ name: route.stateName,
414
+ type: route.path === "/" ? "START" : "REGULAR",
415
+ description: "Route: " + route.path,
416
+ on_enter: [],
417
+ during: [],
418
+ on_exit: []
419
+ }));
420
+ if (states.length > 0 && !states.some((s) => s.type === "START")) {
421
+ states[0].type = "START";
422
+ }
423
+ const transitions = [];
424
+ for (const from of routes) {
425
+ for (const to of routes) {
426
+ if (from.stateName === to.stateName) continue;
427
+ transitions.push({
428
+ name: "nav_" + from.stateName.toLowerCase() + "_to_" + to.stateName.toLowerCase(),
429
+ from: [from.stateName],
430
+ to: to.stateName,
431
+ actions: [],
432
+ conditions: []
433
+ });
434
+ }
435
+ }
436
+ const fields = allParams.map((param) => ({
437
+ name: param,
438
+ type: "text",
439
+ label: param.replace(/([A-Z])/g, " $1").replace(/^./, (c) => c.toUpperCase()),
440
+ required: false,
441
+ default_value: ""
442
+ }));
443
+ fields.push({
444
+ name: "current_route",
445
+ type: "text",
446
+ label: "Current Route",
447
+ required: false,
448
+ default_value: "/"
449
+ });
450
+ return {
451
+ slug: slugPrefix + "-router",
452
+ name: "Router",
453
+ version: "1.0.0",
454
+ description: "Auto-generated router from app/ directory structure",
455
+ category: "router",
456
+ fields,
457
+ states,
458
+ transitions,
459
+ roles: [],
460
+ tags: [{ tag_name: "auto-derived" }, { tag_name: "router" }],
461
+ metadata: {
462
+ runtime: "local",
463
+ routes: routes.map((r) => ({
464
+ state: r.stateName,
465
+ path: r.path,
466
+ params: r.params,
467
+ layoutBoundary: r.layoutBoundary,
468
+ sourceFile: r.sourceFile
469
+ })),
470
+ layoutBoundaries: layouts.map((l) => l.sourceFile),
471
+ provenance: {
472
+ frontend: "react-compiler",
473
+ source: "route-extractor",
474
+ compiler_version: "2.0.0"
475
+ }
476
+ }
477
+ };
478
+ }
479
+
480
+ // src/action-compiler.ts
481
+ import { transformSync as transformSync2 } from "@babel/core";
482
+ function extractActionGroup(filename) {
483
+ const base = filename.split("/").pop() || filename;
484
+ return base.replace(/\.server\.(ts|tsx|js|jsx)$/, "");
485
+ }
486
+ function generateEndpoint(blueprintSlug, group, actionName, apiBasePath) {
487
+ return apiBasePath + "/" + blueprintSlug + "/" + group + "/" + actionName;
488
+ }
489
+ function generateActionId(group, actionName) {
490
+ return group + ":" + actionName;
491
+ }
492
+ function extractFunctionBodies(source) {
493
+ const result = /* @__PURE__ */ new Map();
494
+ const funcHeaderRegex = /export\s+(async\s+)?function\s+(\w+)\s*\(/g;
495
+ let headerMatch;
496
+ while ((headerMatch = funcHeaderRegex.exec(source)) !== null) {
497
+ const funcName = headerMatch[2];
498
+ const startIdx = headerMatch.index;
499
+ let braceStart = source.indexOf("{", headerMatch.index + headerMatch[0].length);
500
+ if (braceStart === -1) continue;
501
+ const signatureSlice = source.slice(headerMatch.index + headerMatch[0].length, braceStart);
502
+ const returnTypeMatch = signatureSlice.match(/\)\s*:\s*([^{]+)/);
503
+ const returnType = returnTypeMatch ? returnTypeMatch[1].trim() : void 0;
504
+ let depth = 0;
505
+ let endIdx = braceStart;
506
+ for (let i = braceStart; i < source.length; i++) {
507
+ if (source[i] === "{") depth++;
508
+ else if (source[i] === "}") {
509
+ depth--;
510
+ if (depth === 0) {
511
+ endIdx = i + 1;
512
+ break;
513
+ }
514
+ }
515
+ }
516
+ const fullText = source.slice(startIdx, endIdx);
517
+ result.set(funcName, { body: fullText, returnType });
518
+ }
519
+ return result;
520
+ }
521
+ function extractActionsViaRegex(source) {
522
+ const actions = [];
523
+ const funcRegex = /(?:\/\*\*([\s\S]*?)\*\/\s*)?export\s+(async\s+)?function\s+(\w+)\s*\(([^)]*)\)/g;
524
+ let match;
525
+ while ((match = funcRegex.exec(source)) !== null) {
526
+ const jsdoc = match[1];
527
+ const isAsync = !!match[2];
528
+ const name = match[3];
529
+ const paramsStr = match[4];
530
+ const params = paramsStr.split(",").map((p) => p.trim().split(":")[0].trim().split("?")[0].trim()).filter(Boolean);
531
+ let description;
532
+ if (jsdoc) {
533
+ const lines = jsdoc.split("\n");
534
+ for (const line of lines) {
535
+ const trimmed = line.replace(/^\s*\*\s?/, "").trim();
536
+ if (trimmed && !trimmed.startsWith("@")) {
537
+ description = trimmed;
538
+ break;
539
+ }
540
+ }
541
+ }
542
+ actions.push({ name, async: isAsync, params, description });
543
+ }
544
+ const arrowRegex = /export\s+const\s+(\w+)\s*=\s*(async\s+)?\([^)]*\)/g;
545
+ while ((match = arrowRegex.exec(source)) !== null) {
546
+ const name = match[1];
547
+ const isAsync = !!match[2];
548
+ const arrowParamMatch = source.slice(match.index).match(/\(([^)]*)\)/);
549
+ const params = arrowParamMatch ? arrowParamMatch[1].split(",").map((p) => p.trim().split(":")[0].trim()).filter(Boolean) : [];
550
+ actions.push({ name, async: isAsync, params });
551
+ }
552
+ return actions;
553
+ }
554
+ function compileActions(files, options = {}) {
555
+ const mode = options.mode || "infer";
556
+ const blueprintSlug = options.blueprintSlug || "app";
557
+ const apiBasePath = options.apiBasePath || "/api/v1/actions";
558
+ const allActions = [];
559
+ const byFile = /* @__PURE__ */ new Map();
560
+ const byGroup = /* @__PURE__ */ new Map();
561
+ const errors = [];
562
+ for (const [filename, source] of Object.entries(files)) {
563
+ const group = extractActionGroup(filename);
564
+ const fileActions = [];
565
+ const bodies = extractFunctionBodies(source);
566
+ try {
567
+ const parserPlugins = filename.endsWith(".tsx") ? ["typescript", "jsx"] : ["typescript"];
568
+ const babelResult = transformSync2(source, {
569
+ filename,
570
+ plugins: [[babelPlugin, { mode }]],
571
+ parserOpts: { plugins: parserPlugins, attachComment: true }
572
+ });
573
+ const ir = babelResult?.metadata?.mindmatrixIR ?? null;
574
+ const meta = ir?.metadata;
575
+ const babelActions = meta?.serverActions;
576
+ if (babelActions && babelActions.length > 0) {
577
+ for (const action of babelActions) {
578
+ const bodyInfo = bodies.get(action.name);
579
+ const reg = {
580
+ name: action.name,
581
+ sourceFile: filename,
582
+ async: action.async,
583
+ params: action.params,
584
+ contextType: action.contextType,
585
+ description: action.description,
586
+ body: bodyInfo?.body,
587
+ returnType: bodyInfo?.returnType,
588
+ endpoint: generateEndpoint(blueprintSlug, group, action.name, apiBasePath),
589
+ group,
590
+ actionId: generateActionId(group, action.name)
591
+ };
592
+ fileActions.push(reg);
593
+ }
594
+ } else {
595
+ const regexActions = extractActionsViaRegex(source);
596
+ for (const action of regexActions) {
597
+ const bodyInfo = bodies.get(action.name);
598
+ const reg = {
599
+ name: action.name,
600
+ sourceFile: filename,
601
+ async: action.async,
602
+ params: action.params,
603
+ description: action.description,
604
+ body: bodyInfo?.body,
605
+ returnType: bodyInfo?.returnType,
606
+ endpoint: generateEndpoint(blueprintSlug, group, action.name, apiBasePath),
607
+ group,
608
+ actionId: generateActionId(group, action.name)
609
+ };
610
+ fileActions.push(reg);
611
+ }
612
+ }
613
+ } catch (err) {
614
+ errors.push({ file: filename, message: err.message });
615
+ const regexActions = extractActionsViaRegex(source);
616
+ for (const action of regexActions) {
617
+ const bodyInfo = bodies.get(action.name);
618
+ const reg = {
619
+ name: action.name,
620
+ sourceFile: filename,
621
+ async: action.async,
622
+ params: action.params,
623
+ description: action.description,
624
+ body: bodyInfo?.body,
625
+ returnType: bodyInfo?.returnType,
626
+ endpoint: generateEndpoint(blueprintSlug, group, action.name, apiBasePath),
627
+ group,
628
+ actionId: generateActionId(group, action.name)
629
+ };
630
+ fileActions.push(reg);
631
+ }
632
+ }
633
+ byFile.set(filename, fileActions);
634
+ if (!byGroup.has(group)) byGroup.set(group, []);
635
+ byGroup.get(group).push(...fileActions);
636
+ allActions.push(...fileActions);
637
+ }
638
+ return { actions: allActions, byFile, byGroup, errors };
639
+ }
640
+ function resolveActionReferences(actionNames, registrations) {
641
+ const result = /* @__PURE__ */ new Map();
642
+ const byName = new Map(registrations.map((r) => [r.name, r]));
643
+ for (const name of actionNames) {
644
+ if (byName.has(name)) {
645
+ result.set(name, byName.get(name));
646
+ continue;
647
+ }
648
+ const colonIdx = name.indexOf(":");
649
+ if (colonIdx > 0) {
650
+ const actionName = name.slice(colonIdx + 1);
651
+ if (byName.has(actionName)) {
652
+ result.set(name, byName.get(actionName));
653
+ continue;
654
+ }
655
+ }
656
+ result.set(name, null);
657
+ }
658
+ return result;
659
+ }
660
+
661
+ // src/babel/extractors/action-extractor.ts
662
+ init_ts_to_expression();
663
+ import { parse } from "@babel/parser";
664
+ import * as t from "@babel/types";
665
+ function extractAction(source, filename) {
666
+ let ast;
667
+ try {
668
+ ast = parse(source, {
669
+ sourceType: "module",
670
+ plugins: ["typescript"],
671
+ strictMode: false
672
+ });
673
+ } catch {
674
+ return null;
675
+ }
676
+ const result = findDefaultExportedFunction(ast);
677
+ if (!result) return null;
678
+ const { name, params, body, returnTypeAnnotation, isAsync } = result;
679
+ const slug = toKebabCase(name);
680
+ const warnings = [];
681
+ const fields = params.map((p) => paramToField(p));
682
+ const parameterMap = /* @__PURE__ */ new Map();
683
+ for (const p of params) {
684
+ const snakeName = toSnakeCase(p.name);
685
+ if (snakeName !== p.name) {
686
+ parameterMap.set(p.name, snakeName);
687
+ }
688
+ }
689
+ const humanName = name.replace(/([A-Z])/g, " $1").replace(/^./, (s) => s.toUpperCase()).trim();
690
+ const metadata = {
691
+ source_file: filename,
692
+ source_function: name,
693
+ provenance: {
694
+ frontend: "react-compiler",
695
+ source: "action-extractor",
696
+ compiler_version: "2.0.0"
697
+ }
698
+ };
699
+ if (returnTypeAnnotation) {
700
+ metadata.return_type = returnTypeAnnotation;
701
+ }
702
+ if (isAsync) {
703
+ const segments = splitAtAwaits(body.body);
704
+ const hasAwaits = segments.some((s) => s.kind === "await");
705
+ if (hasAwaits) {
706
+ const rewritten = rewriteAwaitReferences(segments);
707
+ const { states: states2, transitions: transitions2, bodyIsPure } = generateMultiStateIR(rewritten, warnings, parameterMap);
708
+ if (!bodyIsPure) {
709
+ warnings.push(`Async action '${name}' body contains untranslatable JS \u2014 wrapped in $expr() markers`);
710
+ }
711
+ const ir2 = {
712
+ slug,
713
+ name: humanName,
714
+ version: "0.1.0",
715
+ category: "action",
716
+ fields,
717
+ states: states2,
718
+ transitions: transitions2,
719
+ roles: [],
720
+ metadata: { ...metadata, async: true }
721
+ };
722
+ return { ir: ir2, bodyIsPure, warnings };
723
+ }
724
+ }
725
+ const transpileResult = transpileBlock(body, { allMutable: true, parameterMap });
726
+ const bodyExpr = transpileResult.expression;
727
+ if (!transpileResult.pure) {
728
+ warnings.push(`Action '${name}' body contains untranslatable JS \u2014 wrapped in $expr() markers`);
729
+ }
730
+ const states = [
731
+ {
732
+ name: "ready",
733
+ type: "START",
734
+ on_enter: [],
735
+ during: [],
736
+ on_exit: []
737
+ },
738
+ {
739
+ name: "done",
740
+ type: "END",
741
+ on_enter: [],
742
+ during: [],
743
+ on_exit: []
744
+ }
745
+ ];
746
+ const transitions = [
747
+ {
748
+ name: "execute",
749
+ from: ["ready"],
750
+ to: "done",
751
+ actions: [
752
+ {
753
+ id: "body",
754
+ type: "eval",
755
+ mode: "auto",
756
+ config: {
757
+ expression: bodyExpr
758
+ }
759
+ }
760
+ ]
761
+ }
762
+ ];
763
+ const ir = {
764
+ slug,
765
+ name: humanName,
766
+ version: "0.1.0",
767
+ category: "action",
768
+ fields,
769
+ states,
770
+ transitions,
771
+ roles: [],
772
+ metadata
773
+ };
774
+ return { ir, bodyIsPure: transpileResult.pure, warnings };
775
+ }
776
+ function findDefaultExportedFunction(ast) {
777
+ const topLevelVars = /* @__PURE__ */ new Map();
778
+ for (const node of ast.program.body) {
779
+ if (t.isVariableDeclaration(node)) {
780
+ for (const decl of node.declarations) {
781
+ if (t.isIdentifier(decl.id) && decl.init) {
782
+ if (t.isArrowFunctionExpression(decl.init) || t.isFunctionExpression(decl.init)) {
783
+ topLevelVars.set(decl.id.name, decl.init);
784
+ }
785
+ }
786
+ }
787
+ }
788
+ }
789
+ for (const node of ast.program.body) {
790
+ if (t.isExportDefaultDeclaration(node)) {
791
+ const decl = node.declaration;
792
+ if (t.isFunctionDeclaration(decl) && decl.body) {
793
+ const name = decl.id?.name ?? inferNameFromFile(decl) ?? "action";
794
+ return extractFromFunction(name, decl.params, decl.body, decl.returnType, decl.async);
795
+ }
796
+ if (t.isArrowFunctionExpression(decl) || t.isFunctionExpression(decl)) {
797
+ const name = t.isFunctionExpression(decl) && decl.id ? decl.id.name : "action";
798
+ const body = ensureBlock(decl.body);
799
+ if (!body) return null;
800
+ return extractFromFunction(name, decl.params, body, decl.returnType, decl.async);
801
+ }
802
+ if (t.isIdentifier(decl)) {
803
+ const fn = topLevelVars.get(decl.name);
804
+ if (fn) {
805
+ const body = ensureBlock(fn.body);
806
+ if (!body) return null;
807
+ return extractFromFunction(decl.name, fn.params, body, fn.returnType, fn.async);
808
+ }
809
+ }
810
+ }
811
+ }
812
+ return null;
813
+ }
814
+ function extractFromFunction(name, params, body, returnType, isAsync = false) {
815
+ const extracted = params.map((p) => extractParam(p));
816
+ const returnTypeAnnotation = returnType && t.isTSTypeAnnotation(returnType) ? serializeTSType(returnType.typeAnnotation) : void 0;
817
+ return { name, params: extracted, body, returnTypeAnnotation, isAsync };
818
+ }
819
+ function ensureBlock(body) {
820
+ if (t.isBlockStatement(body)) return body;
821
+ const ret = t.returnStatement(body);
822
+ return t.blockStatement([ret]);
823
+ }
824
+ function inferNameFromFile(_node) {
825
+ return null;
826
+ }
827
+ function extractParam(param) {
828
+ if (t.isIdentifier(param)) {
829
+ return {
830
+ name: param.name,
831
+ typeAnnotation: param.typeAnnotation ? param.typeAnnotation.typeAnnotation : null,
832
+ optional: param.optional ?? false
833
+ };
834
+ }
835
+ if (t.isAssignmentPattern(param)) {
836
+ const inner = param.left;
837
+ if (t.isIdentifier(inner)) {
838
+ return {
839
+ name: inner.name,
840
+ typeAnnotation: inner.typeAnnotation ? inner.typeAnnotation.typeAnnotation : null,
841
+ optional: true,
842
+ defaultValue: param.right
843
+ };
844
+ }
845
+ }
846
+ if (t.isRestElement(param)) {
847
+ const arg = param.argument;
848
+ return {
849
+ name: t.isIdentifier(arg) ? arg.name : "rest",
850
+ typeAnnotation: null,
851
+ optional: true
852
+ };
853
+ }
854
+ return { name: "params", typeAnnotation: null, optional: false };
855
+ }
856
+ function paramToField(param) {
857
+ const fieldType = param.typeAnnotation ? tsTypeToFieldType(param.typeAnnotation) : "text";
858
+ const field = {
859
+ name: toSnakeCase(param.name),
860
+ type: fieldType,
861
+ required: !param.optional
862
+ };
863
+ if (param.defaultValue !== void 0) {
864
+ field.default_value = extractLiteralDefault(param.defaultValue);
865
+ }
866
+ return field;
867
+ }
868
+ function extractLiteralDefault(expr) {
869
+ if (!expr) return void 0;
870
+ if (t.isStringLiteral(expr)) return expr.value;
871
+ if (t.isNumericLiteral(expr)) return expr.value;
872
+ if (t.isBooleanLiteral(expr)) return expr.value;
873
+ if (t.isNullLiteral(expr)) return null;
874
+ if (t.isArrayExpression(expr) && expr.elements.length === 0) return [];
875
+ if (t.isObjectExpression(expr) && expr.properties.length === 0) return {};
876
+ return void 0;
877
+ }
878
+ function tsTypeToFieldType(tsType) {
879
+ if (t.isTSStringKeyword(tsType)) return "text";
880
+ if (t.isTSNumberKeyword(tsType)) return "number";
881
+ if (t.isTSBooleanKeyword(tsType)) return "boolean";
882
+ if (t.isTSObjectKeyword(tsType)) return "json";
883
+ if (t.isTSAnyKeyword(tsType) || t.isTSUnknownKeyword(tsType)) return "json";
884
+ if (t.isTSArrayType(tsType)) return "json";
885
+ if (t.isTSUnionType(tsType)) {
886
+ const nonNullable = tsType.types.filter(
887
+ (t2) => !t.isTSNullKeyword(t2) && !t.isTSUndefinedKeyword(t2)
888
+ );
889
+ if (nonNullable.length === 1) {
890
+ return tsTypeToFieldType(nonNullable[0]);
891
+ }
892
+ if (nonNullable.every((t2) => t.isTSLiteralType(t2) && t.isStringLiteral(t2.literal))) {
893
+ return "select";
894
+ }
895
+ return "text";
896
+ }
897
+ if (t.isTSTypeReference(tsType) && t.isIdentifier(tsType.typeName)) {
898
+ const name = tsType.typeName.name;
899
+ if (name === "Date") return "datetime";
900
+ if (name === "string") return "text";
901
+ if (name === "number") return "number";
902
+ if (name === "boolean") return "boolean";
903
+ }
904
+ return "text";
905
+ }
906
+ function serializeTSType(tsType) {
907
+ if (t.isTSStringKeyword(tsType)) return "string";
908
+ if (t.isTSNumberKeyword(tsType)) return "number";
909
+ if (t.isTSBooleanKeyword(tsType)) return "boolean";
910
+ if (t.isTSVoidKeyword(tsType)) return "void";
911
+ if (t.isTSAnyKeyword(tsType)) return "any";
912
+ if (t.isTSTypeReference(tsType) && t.isIdentifier(tsType.typeName)) {
913
+ return tsType.typeName.name;
914
+ }
915
+ if (t.isTSArrayType(tsType)) return `${serializeTSType(tsType.elementType)}[]`;
916
+ if (t.isTSPromiseType(tsType)) {
917
+ return `Promise<${tsType.typeParameter ? serializeTSType(tsType.typeParameter.params[0]) : "unknown"}>`;
918
+ }
919
+ return "unknown";
920
+ }
921
+ function splitAtAwaits(body) {
922
+ const segments = [];
923
+ let current = [];
924
+ let index = 0;
925
+ for (const stmt of body) {
926
+ const awaitInfo = extractAwait(stmt);
927
+ if (!awaitInfo) {
928
+ current.push(stmt);
929
+ continue;
930
+ }
931
+ if (current.length > 0) {
932
+ segments.push({ index: index++, kind: "sync", statements: current });
933
+ current = [];
934
+ }
935
+ segments.push({
936
+ index: index++,
937
+ kind: "await",
938
+ statements: [stmt],
939
+ awaitTarget: awaitInfo.callee,
940
+ awaitArgs: awaitInfo.args,
941
+ resultBinding: awaitInfo.binding
942
+ });
943
+ }
944
+ if (current.length > 0) {
945
+ segments.push({ index: index++, kind: "sync", statements: current });
946
+ }
947
+ return segments;
948
+ }
949
+ function extractAwait(stmt) {
950
+ if (t.isVariableDeclaration(stmt)) {
951
+ const decl = stmt.declarations[0];
952
+ if (decl?.init && t.isAwaitExpression(decl.init)) {
953
+ const arg = decl.init.argument;
954
+ if (t.isCallExpression(arg)) {
955
+ return {
956
+ callee: getCalleeName(arg.callee),
957
+ args: arg.arguments,
958
+ binding: t.isIdentifier(decl.id) ? decl.id.name : void 0
959
+ };
960
+ }
961
+ }
962
+ }
963
+ if (t.isExpressionStatement(stmt) && t.isAwaitExpression(stmt.expression)) {
964
+ const arg = stmt.expression.argument;
965
+ if (t.isCallExpression(arg)) {
966
+ return {
967
+ callee: getCalleeName(arg.callee),
968
+ args: arg.arguments,
969
+ binding: void 0
970
+ };
971
+ }
972
+ }
973
+ if (t.isReturnStatement(stmt) && stmt.argument && t.isAwaitExpression(stmt.argument)) {
974
+ const arg = stmt.argument.argument;
975
+ if (t.isCallExpression(arg)) {
976
+ return {
977
+ callee: getCalleeName(arg.callee),
978
+ args: arg.arguments,
979
+ binding: void 0
980
+ };
981
+ }
982
+ }
983
+ return null;
984
+ }
985
+ function getCalleeName(callee) {
986
+ if (t.isIdentifier(callee)) return callee.name;
987
+ if (t.isMemberExpression(callee) && t.isIdentifier(callee.object) && t.isIdentifier(callee.property)) {
988
+ return `${callee.object.name}_${callee.property.name}`;
989
+ }
990
+ return "unknown_action";
991
+ }
992
+ function rewriteAwaitReferences(segments) {
993
+ const bindings = /* @__PURE__ */ new Map();
994
+ const slugCounts = /* @__PURE__ */ new Map();
995
+ return segments.map((seg) => {
996
+ if (seg.kind === "await" && seg.resultBinding) {
997
+ const slug = toSnakeCase(seg.awaitTarget ?? "unknown");
998
+ const count = (slugCounts.get(slug) ?? 0) + 1;
999
+ slugCounts.set(slug, count);
1000
+ const key = count > 1 ? `${slug}_${count}` : slug;
1001
+ bindings.set(seg.resultBinding, `action_results.${key}`);
1002
+ }
1003
+ if (seg.kind === "sync" && bindings.size > 0) {
1004
+ return {
1005
+ ...seg,
1006
+ statements: seg.statements.map(
1007
+ (stmt) => rewriteIdentifiersInStatement(stmt, bindings)
1008
+ )
1009
+ };
1010
+ }
1011
+ return seg;
1012
+ });
1013
+ }
1014
+ function rewriteIdentifiersInStatement(stmt, _bindings) {
1015
+ return stmt;
1016
+ }
1017
+ function generateMultiStateIR(segments, _warnings, parameterMap) {
1018
+ const states = [];
1019
+ const transitions = [];
1020
+ let bodyIsPure = true;
1021
+ const awaitBindings = /* @__PURE__ */ new Map();
1022
+ const slugCounts = /* @__PURE__ */ new Map();
1023
+ for (const seg of segments) {
1024
+ if (seg.kind === "await" && seg.resultBinding) {
1025
+ const slug = toSnakeCase(seg.awaitTarget ?? "unknown");
1026
+ const count = (slugCounts.get(slug) ?? 0) + 1;
1027
+ slugCounts.set(slug, count);
1028
+ const key = count > 1 ? `${slug}_${count}` : slug;
1029
+ awaitBindings.set(seg.resultBinding, `action_results.${key}`);
1030
+ }
1031
+ }
1032
+ states.push({ name: "ready", type: "START", on_enter: [], during: [], on_exit: [] });
1033
+ const usedStateNames = /* @__PURE__ */ new Set();
1034
+ let prevState = "ready";
1035
+ let transitionCount = 0;
1036
+ let pendingSyncStmts = [];
1037
+ for (const seg of segments) {
1038
+ if (seg.kind === "sync") {
1039
+ pendingSyncStmts.push(...seg.statements);
1040
+ continue;
1041
+ }
1042
+ const targetSlug = toSnakeCase(seg.awaitTarget ?? "unknown");
1043
+ let stateName = `awaiting_${targetSlug}`;
1044
+ if (usedStateNames.has(stateName)) {
1045
+ let suffix = 2;
1046
+ while (usedStateNames.has(`${stateName}_${suffix}`)) suffix++;
1047
+ stateName = `${stateName}_${suffix}`;
1048
+ }
1049
+ usedStateNames.add(stateName);
1050
+ states.push({ name: stateName, type: "REGULAR", on_enter: [], during: [], on_exit: [] });
1051
+ const actions = [];
1052
+ if (pendingSyncStmts.length > 0) {
1053
+ const block = t.blockStatement(pendingSyncStmts);
1054
+ const transpiled = transpileBlock(block, {
1055
+ allMutable: true,
1056
+ derivedVarMap: buildDerivedVarMap(awaitBindings),
1057
+ parameterMap
1058
+ });
1059
+ if (!transpiled.pure) bodyIsPure = false;
1060
+ actions.push({
1061
+ id: `pre_${transitionCount}`,
1062
+ type: "eval",
1063
+ mode: "auto",
1064
+ config: { expression: transpiled.expression }
1065
+ });
1066
+ pendingSyncStmts = [];
1067
+ }
1068
+ const callConfig = {
1069
+ definition_slug: seg.awaitTarget,
1070
+ result_key: targetSlug
1071
+ };
1072
+ if (seg.awaitArgs && seg.awaitArgs.length > 0) {
1073
+ const params = {};
1074
+ for (let i = 0; i < seg.awaitArgs.length; i++) {
1075
+ const arg = seg.awaitArgs[i];
1076
+ if (t.isObjectExpression(arg)) {
1077
+ for (const prop of arg.properties) {
1078
+ if (t.isObjectProperty(prop) && t.isIdentifier(prop.key)) {
1079
+ const { expression: valExpr } = transpileArgExpression(prop.value, awaitBindings);
1080
+ params[prop.key.name] = valExpr;
1081
+ }
1082
+ }
1083
+ } else {
1084
+ const { expression: valExpr } = transpileArgExpression(arg, awaitBindings);
1085
+ params[`arg${i}`] = valExpr;
1086
+ }
1087
+ }
1088
+ if (Object.keys(params).length > 0) {
1089
+ callConfig.params = params;
1090
+ }
1091
+ }
1092
+ actions.push({
1093
+ id: `call_${targetSlug}`,
1094
+ type: "call_workflow",
1095
+ mode: "auto",
1096
+ config: callConfig
1097
+ });
1098
+ const transName = transitionCount === 0 ? "execute" : `on_${getStateSuffix(prevState)}_complete`;
1099
+ transitions.push({
1100
+ name: transName,
1101
+ from: [prevState],
1102
+ to: stateName,
1103
+ actions
1104
+ });
1105
+ prevState = stateName;
1106
+ transitionCount++;
1107
+ }
1108
+ states.push({ name: "done", type: "END", on_enter: [], during: [], on_exit: [] });
1109
+ const finalActions = [];
1110
+ if (pendingSyncStmts.length > 0) {
1111
+ const block = t.blockStatement(pendingSyncStmts);
1112
+ const transpiled = transpileBlock(block, {
1113
+ allMutable: true,
1114
+ derivedVarMap: buildDerivedVarMap(awaitBindings),
1115
+ parameterMap
1116
+ });
1117
+ if (!transpiled.pure) bodyIsPure = false;
1118
+ finalActions.push({
1119
+ id: "post_final",
1120
+ type: "eval",
1121
+ mode: "auto",
1122
+ config: { expression: transpiled.expression }
1123
+ });
1124
+ }
1125
+ const finalTransName = transitionCount === 0 ? "execute" : `on_${getStateSuffix(prevState)}_complete`;
1126
+ transitions.push({
1127
+ name: finalTransName,
1128
+ from: [prevState],
1129
+ to: "done",
1130
+ actions: finalActions
1131
+ });
1132
+ return { states, transitions, bodyIsPure };
1133
+ }
1134
+ function getStateSuffix(stateName) {
1135
+ return stateName.replace(/^awaiting_/, "");
1136
+ }
1137
+ function transpileArgExpression(expr, bindings) {
1138
+ if (t.isIdentifier(expr)) {
1139
+ const replacement = bindings.get(expr.name);
1140
+ if (replacement) return { expression: replacement };
1141
+ return { expression: `state_data.${toSnakeCase(expr.name)}` };
1142
+ }
1143
+ if (t.isMemberExpression(expr) && t.isIdentifier(expr.object)) {
1144
+ const replacement = bindings.get(expr.object.name);
1145
+ if (replacement && t.isIdentifier(expr.property)) {
1146
+ return { expression: `${replacement}.${expr.property.name}` };
1147
+ }
1148
+ }
1149
+ if (t.isStringLiteral(expr)) return { expression: `'${expr.value}'` };
1150
+ if (t.isNumericLiteral(expr)) return { expression: String(expr.value) };
1151
+ if (t.isBooleanLiteral(expr)) return { expression: String(expr.value) };
1152
+ const { transpile } = (init_ts_to_expression(), __toCommonJS(ts_to_expression_exports));
1153
+ return { expression: transpile(expr, { derivedVarMap: buildDerivedVarMap(bindings) }) };
1154
+ }
1155
+ function buildDerivedVarMap(bindings) {
1156
+ const map = /* @__PURE__ */ new Map();
1157
+ for (const [varName, path] of bindings) {
1158
+ map.set(varName, t.identifier(path));
1159
+ }
1160
+ return map;
1161
+ }
1162
+ function toKebabCase(name) {
1163
+ return name.replace(/([A-Z])/g, "-$1").toLowerCase().replace(/^-/, "");
1164
+ }
1165
+ function toSnakeCase(name) {
1166
+ return name.replace(/([A-Z])/g, "_$1").toLowerCase().replace(/^_/, "");
1167
+ }
1168
+
1169
+ // src/incremental-compiler.ts
1170
+ function hashContent(content) {
1171
+ let hash = 5381;
1172
+ for (let i = 0; i < content.length; i++) {
1173
+ hash = (hash << 5) + hash + content.charCodeAt(i);
1174
+ hash |= 0;
1175
+ }
1176
+ return (hash >>> 0).toString(36);
1177
+ }
1178
+ function extractImports(source) {
1179
+ const imports = [];
1180
+ const regex = /import\s+.*?from\s+['"](\.[^'"]+)['"]/g;
1181
+ let match;
1182
+ while ((match = regex.exec(source)) !== null) {
1183
+ imports.push(match[1]);
1184
+ }
1185
+ return imports;
1186
+ }
1187
+ function resolveImport(fromFile, importPath, availableFiles) {
1188
+ const parts = fromFile.split("/");
1189
+ parts.pop();
1190
+ const dir = parts.join("/");
1191
+ const segments = (dir ? dir + "/" + importPath : importPath).split("/");
1192
+ const resolved = [];
1193
+ for (const seg of segments) {
1194
+ if (seg === ".") continue;
1195
+ if (seg === "..") {
1196
+ resolved.pop();
1197
+ continue;
1198
+ }
1199
+ resolved.push(seg);
1200
+ }
1201
+ const basePath = resolved.join("/");
1202
+ const extensions = ["", ".ts", ".tsx", ".js", ".jsx"];
1203
+ for (const ext of extensions) {
1204
+ const candidate = basePath + ext;
1205
+ if (availableFiles.includes(candidate)) {
1206
+ return candidate;
1207
+ }
1208
+ }
1209
+ for (const ext of [".ts", ".tsx", ".js", ".jsx"]) {
1210
+ const candidate = basePath + "/index" + ext;
1211
+ if (availableFiles.includes(candidate)) {
1212
+ return candidate;
1213
+ }
1214
+ }
1215
+ return null;
1216
+ }
1217
+ function buildDependencyGraph(files) {
1218
+ const availableFiles = Object.keys(files);
1219
+ const edges = [];
1220
+ const dependents = /* @__PURE__ */ new Map();
1221
+ const dependencies = /* @__PURE__ */ new Map();
1222
+ for (const filename of availableFiles) {
1223
+ dependents.set(filename, /* @__PURE__ */ new Set());
1224
+ dependencies.set(filename, /* @__PURE__ */ new Set());
1225
+ }
1226
+ for (const [filename, source] of Object.entries(files)) {
1227
+ const imports = extractImports(source);
1228
+ for (const imp of imports) {
1229
+ const resolved = resolveImport(filename, imp, availableFiles);
1230
+ if (resolved && resolved !== filename) {
1231
+ edges.push({ from: filename, to: resolved });
1232
+ dependencies.get(filename).add(resolved);
1233
+ if (!dependents.has(resolved)) dependents.set(resolved, /* @__PURE__ */ new Set());
1234
+ dependents.get(resolved).add(filename);
1235
+ }
1236
+ }
1237
+ }
1238
+ return { edges, dependents, dependencies };
1239
+ }
1240
+ function computeTransitiveDirtySet(directlyChanged, dependents) {
1241
+ const dirty = new Set(directlyChanged);
1242
+ const queue = [...directlyChanged];
1243
+ while (queue.length > 0) {
1244
+ const file = queue.shift();
1245
+ const deps = dependents.get(file);
1246
+ if (!deps) continue;
1247
+ for (const dep of deps) {
1248
+ if (!dirty.has(dep)) {
1249
+ dirty.add(dep);
1250
+ queue.push(dep);
1251
+ }
1252
+ }
1253
+ }
1254
+ return dirty;
1255
+ }
1256
+ function topologicalSort(files, dependencies) {
1257
+ const inDegree = /* @__PURE__ */ new Map();
1258
+ const dependentMap = /* @__PURE__ */ new Map();
1259
+ for (const f of files) {
1260
+ inDegree.set(f, 0);
1261
+ dependentMap.set(f, /* @__PURE__ */ new Set());
1262
+ }
1263
+ for (const f of files) {
1264
+ const deps = dependencies.get(f);
1265
+ if (!deps) continue;
1266
+ for (const dep of deps) {
1267
+ if (files.includes(dep)) {
1268
+ inDegree.set(f, (inDegree.get(f) || 0) + 1);
1269
+ if (!dependentMap.has(dep)) dependentMap.set(dep, /* @__PURE__ */ new Set());
1270
+ dependentMap.get(dep).add(f);
1271
+ }
1272
+ }
1273
+ }
1274
+ const queue = [];
1275
+ for (const [f, degree] of inDegree) {
1276
+ if (degree === 0) queue.push(f);
1277
+ }
1278
+ const order = [];
1279
+ while (queue.length > 0) {
1280
+ const f = queue.shift();
1281
+ order.push(f);
1282
+ for (const dependent of dependentMap.get(f) || []) {
1283
+ const newDegree = (inDegree.get(dependent) || 1) - 1;
1284
+ inDegree.set(dependent, newDegree);
1285
+ if (newDegree === 0) queue.push(dependent);
1286
+ }
1287
+ }
1288
+ for (const f of files) {
1289
+ if (!order.includes(f)) {
1290
+ order.push(f);
1291
+ }
1292
+ }
1293
+ return order;
1294
+ }
1295
+ var IncrementalCache = class {
1296
+ constructor() {
1297
+ this.hashes = /* @__PURE__ */ new Map();
1298
+ this.results = /* @__PURE__ */ new Map();
1299
+ this.lastStats = {
1300
+ totalCached: 0,
1301
+ lastRecompiled: 0,
1302
+ lastCacheHits: 0,
1303
+ lastCompileMs: 0,
1304
+ avgPerFileMs: 0,
1305
+ cacheHitRate: 0
1306
+ };
1307
+ }
1308
+ /**
1309
+ * Determines which files are dirty given current file contents.
1310
+ */
1311
+ detectDirtyFiles(files, dependents) {
1312
+ const currentFiles = new Set(Object.keys(files));
1313
+ const contentChanged = [];
1314
+ const removed = [];
1315
+ const added = [];
1316
+ for (const [filename, source] of Object.entries(files)) {
1317
+ const hash = hashContent(source);
1318
+ const cached = this.hashes.get(filename);
1319
+ if (!cached) {
1320
+ added.push(filename);
1321
+ } else if (cached.hash !== hash) {
1322
+ contentChanged.push(filename);
1323
+ }
1324
+ }
1325
+ for (const cached of this.hashes.keys()) {
1326
+ if (!currentFiles.has(cached)) {
1327
+ removed.push(cached);
1328
+ }
1329
+ }
1330
+ const directlyDirty = /* @__PURE__ */ new Set([...contentChanged, ...added]);
1331
+ let dependencyDirty = [];
1332
+ if (dependents && directlyDirty.size > 0) {
1333
+ const allDirty = computeTransitiveDirtySet(directlyDirty, dependents);
1334
+ dependencyDirty = [...allDirty].filter((f) => !directlyDirty.has(f));
1335
+ }
1336
+ return { contentChanged, dependencyDirty, removed, added };
1337
+ }
1338
+ /**
1339
+ * Updates the cache with a compilation result.
1340
+ */
1341
+ set(filename, source, result) {
1342
+ this.hashes.set(filename, {
1343
+ hash: hashContent(source),
1344
+ compiledAt: Date.now(),
1345
+ size: source.length
1346
+ });
1347
+ this.results.set(filename, result);
1348
+ }
1349
+ /**
1350
+ * Gets a cached result.
1351
+ */
1352
+ get(filename) {
1353
+ return this.results.get(filename);
1354
+ }
1355
+ /**
1356
+ * Checks if a file is in cache and not dirty.
1357
+ */
1358
+ has(filename) {
1359
+ return this.results.has(filename);
1360
+ }
1361
+ /**
1362
+ * Removes a file from cache.
1363
+ */
1364
+ delete(filename) {
1365
+ this.hashes.delete(filename);
1366
+ this.results.delete(filename);
1367
+ }
1368
+ /**
1369
+ * Clears all cached data.
1370
+ */
1371
+ clear() {
1372
+ this.hashes.clear();
1373
+ this.results.clear();
1374
+ }
1375
+ /**
1376
+ * Updates stats after a compilation run.
1377
+ */
1378
+ updateStats(recompiled, cacheHits, compileMs) {
1379
+ const total = recompiled + cacheHits;
1380
+ this.lastStats = {
1381
+ totalCached: this.results.size,
1382
+ lastRecompiled: recompiled,
1383
+ lastCacheHits: cacheHits,
1384
+ lastCompileMs: compileMs,
1385
+ avgPerFileMs: recompiled > 0 ? compileMs / recompiled : 0,
1386
+ cacheHitRate: total > 0 ? cacheHits / total : 0
1387
+ };
1388
+ }
1389
+ /**
1390
+ * Gets compilation statistics.
1391
+ */
1392
+ getStats() {
1393
+ return { ...this.lastStats };
1394
+ }
1395
+ /**
1396
+ * Gets all cached filenames.
1397
+ */
1398
+ getCachedFiles() {
1399
+ return [...this.results.keys()];
1400
+ }
1401
+ /**
1402
+ * Gets all cached results.
1403
+ */
1404
+ getAllResults() {
1405
+ return new Map(this.results);
1406
+ }
1407
+ };
1408
+
1409
+ // src/project-compiler.ts
1410
+ function parseConfig(source) {
1411
+ const config = {};
1412
+ const slugMatch = source.match(/slug:\s*['"]([^'"]+)['"]/);
1413
+ if (slugMatch) config.slug = slugMatch[1];
1414
+ const nameMatch = source.match(/name:\s*['"]([^'"]+)['"]/);
1415
+ if (nameMatch) config.name = nameMatch[1];
1416
+ const versionMatch = source.match(/version:\s*['"]([^'"]+)['"]/);
1417
+ if (versionMatch) config.version = versionMatch[1];
1418
+ const descMatch = source.match(/description:\s*['"]([^'"]+)['"]/);
1419
+ if (descMatch) config.description = descMatch[1];
1420
+ const categoryArrayMatch = source.match(/category:\s*\[([^\]]+)\]/);
1421
+ if (categoryArrayMatch) {
1422
+ const items = categoryArrayMatch[1].match(/['"]([^'"]+)['"]/g);
1423
+ if (items) {
1424
+ config.category = items.map((s) => s.replace(/['"]/g, ""));
1425
+ }
1426
+ } else {
1427
+ const categoryMatch = source.match(/category:\s*['"]([^'"]+)['"]/);
1428
+ if (categoryMatch) config.category = categoryMatch[1];
1429
+ }
1430
+ const modeMatch = source.match(/mode:\s*['"]([^'"]+)['"]/);
1431
+ if (modeMatch && (modeMatch[1] === "strict" || modeMatch[1] === "infer")) {
1432
+ config.mode = modeMatch[1];
1433
+ }
1434
+ return config;
1435
+ }
1436
+ function parseModuleManifest(source) {
1437
+ if (!source.includes("defineBlueprint") && !source.includes("defineModule")) return null;
1438
+ const manifest = {};
1439
+ const stringFields = ["slug", "name", "version", "description", "author", "license", "icon"];
1440
+ for (const field of stringFields) {
1441
+ const match = source.match(new RegExp(`${field}:\\s*['"]([^'"]+)['"]`));
1442
+ if (match) manifest[field] = match[1];
1443
+ }
1444
+ const catArrayMatch = source.match(/category:\s*\[([^\]]+)\]/);
1445
+ if (catArrayMatch) {
1446
+ const items = catArrayMatch[1].match(/['"]([^'"]+)['"]/g);
1447
+ if (items) {
1448
+ manifest.category = items.map((s) => s.replace(/['"]/g, ""));
1449
+ }
1450
+ } else {
1451
+ const catMatch = source.match(/category:\s*['"]([^'"]+)['"]/);
1452
+ if (catMatch) manifest.category = catMatch[1];
1453
+ }
1454
+ const tagsMatch = source.match(/tags:\s*\[([^\]]*)\]/);
1455
+ if (tagsMatch) {
1456
+ manifest.tags = tagsMatch[1].split(",").map((s) => s.trim().replace(/^['"]|['"]$/g, "")).filter(Boolean);
1457
+ }
1458
+ const modelsMatch = source.match(/models:\s*\[([^\]]*)\]/);
1459
+ if (modelsMatch) {
1460
+ manifest.models = modelsMatch[1].split(",").map((s) => s.trim().replace(/^['"]|['"]$/g, "")).filter(Boolean);
1461
+ }
1462
+ const capsMatch = source.match(/capabilities:\s*\[([^\]]*)\]/);
1463
+ if (capsMatch) {
1464
+ manifest.capabilities = capsMatch[1].split(",").map((s) => s.trim().replace(/^['"]|['"]$/g, "")).filter(Boolean);
1465
+ }
1466
+ const routesBlock = extractArrayBlock(source, "routes");
1467
+ if (routesBlock) {
1468
+ const routes = [];
1469
+ const routeRegex = /\{\s*path:\s*['"]([^'"]+)['"][^}]*\}/g;
1470
+ let rm;
1471
+ while ((rm = routeRegex.exec(routesBlock)) !== null) {
1472
+ const entry = { path: rm[1] };
1473
+ const labelMatch = rm[0].match(/label:\s*['"]([^'"]+)['"]/);
1474
+ if (labelMatch) entry.label = labelMatch[1];
1475
+ const groupMatch = rm[0].match(/group:\s*['"]([^'"]+)['"]/);
1476
+ if (groupMatch) entry.group = groupMatch[1];
1477
+ const iconMatch = rm[0].match(/icon:\s*['"]([^'"]+)['"]/);
1478
+ if (iconMatch) entry.icon = iconMatch[1];
1479
+ routes.push(entry);
1480
+ }
1481
+ if (routes.length > 0) manifest.routes = routes;
1482
+ }
1483
+ const actionsBlock = extractArrayBlock(source, "actions");
1484
+ if (actionsBlock) {
1485
+ const actions = [];
1486
+ const actionRegex = /\{\s*id:\s*['"]([^'"]+)['"][^}]*\}/g;
1487
+ let am;
1488
+ while ((am = actionRegex.exec(actionsBlock)) !== null) {
1489
+ const entry = { id: am[1] };
1490
+ const descMatch = am[0].match(/description:\s*['"]([^'"]+)['"]/);
1491
+ if (descMatch) entry.description = descMatch[1];
1492
+ actions.push(entry);
1493
+ }
1494
+ if (actions.length > 0) manifest.actions = actions;
1495
+ }
1496
+ const contribsBlock = extractArrayBlock(source, "contributions");
1497
+ if (contribsBlock) {
1498
+ const contributions = [];
1499
+ const contribRegex = /\{\s*slot:\s*['"]([^'"]+)['"][^}]*\}/g;
1500
+ let cm;
1501
+ while ((cm = contribRegex.exec(contribsBlock)) !== null) {
1502
+ const entry = { slot: cm[1], view: "" };
1503
+ const viewMatch = cm[0].match(/view:\s*['"]([^'"]+)['"]/);
1504
+ if (viewMatch) entry.view = viewMatch[1];
1505
+ const prioMatch = cm[0].match(/priority:\s*(\d+)/);
1506
+ if (prioMatch) entry.priority = parseInt(prioMatch[1], 10);
1507
+ contributions.push(entry);
1508
+ }
1509
+ if (contributions.length > 0) manifest.contributions = contributions;
1510
+ }
1511
+ const configSchemaMatch = source.match(/configSchema:\s*\{([^}]*(?:\{[^}]*\}[^}]*)*)\}/);
1512
+ if (configSchemaMatch) {
1513
+ const configSchema = {};
1514
+ const modelSlugMatch = configSchemaMatch[1].match(/modelSlug:\s*['"]([^'"]+)['"]/);
1515
+ if (modelSlugMatch) configSchema.modelSlug = modelSlugMatch[1];
1516
+ const defaultsMatch = configSchemaMatch[1].match(/defaults:\s*\{([^}]*)\}/);
1517
+ if (defaultsMatch) {
1518
+ const defaults = {};
1519
+ const kvRegex = /(\w+):\s*(?:'([^']*)'|"([^"]*)"|(\d+(?:\.\d+)?)|(\btrue\b|\bfalse\b))/g;
1520
+ let kv;
1521
+ while ((kv = kvRegex.exec(defaultsMatch[1])) !== null) {
1522
+ const key = kv[1];
1523
+ const val = kv[2] ?? kv[3] ?? (kv[4] !== void 0 ? Number(kv[4]) : kv[5] === "true");
1524
+ defaults[key] = val;
1525
+ }
1526
+ configSchema.defaults = defaults;
1527
+ }
1528
+ manifest.configSchema = configSchema;
1529
+ }
1530
+ const depsBlock = extractArrayBlock(source, "dependencies");
1531
+ if (depsBlock) {
1532
+ const dependencies = [];
1533
+ const depRegex = /\{\s*slug:\s*['"]([^'"]+)['"][^}]*\}/g;
1534
+ let dm;
1535
+ while ((dm = depRegex.exec(depsBlock)) !== null) {
1536
+ const entry = { slug: dm[1] };
1537
+ const verMatch = dm[0].match(/version:\s*['"]([^'"]+)['"]/);
1538
+ if (verMatch) entry.version = verMatch[1];
1539
+ const reqMatch = dm[0].match(/required:\s*(true|false)/);
1540
+ if (reqMatch) entry.required = reqMatch[1] === "true";
1541
+ const prefixMatch = dm[0].match(/prefix:\s*['"]([^'"]+)['"]/);
1542
+ if (prefixMatch) entry.routeConfig = { prefix: prefixMatch[1] };
1543
+ dependencies.push(entry);
1544
+ }
1545
+ if (dependencies.length > 0) manifest.dependencies = dependencies;
1546
+ }
1547
+ const hasRichFields = manifest.routes || manifest.actions || manifest.contributions || manifest.capabilities || manifest.dependencies;
1548
+ return hasRichFields ? manifest : null;
1549
+ }
1550
+ function parseDependencyRouteConfigs(files) {
1551
+ const result = /* @__PURE__ */ new Map();
1552
+ let configSource;
1553
+ for (const [filename, source] of Object.entries(files)) {
1554
+ if (isConfigFile(filename)) {
1555
+ configSource = source;
1556
+ break;
1557
+ }
1558
+ }
1559
+ if (!configSource) return result;
1560
+ const depsBlock = extractArrayBlock(configSource, "dependencies");
1561
+ if (!depsBlock) return result;
1562
+ const depObjects = extractNestedObjects(depsBlock);
1563
+ for (const depSrc of depObjects) {
1564
+ const slugMatch = depSrc.match(/slug:\s*['"]([^'"]+)['"]/);
1565
+ if (!slugMatch) continue;
1566
+ const slug = slugMatch[1];
1567
+ const rcBlock = extractObjectBlock(depSrc, "routeConfig");
1568
+ if (!rcBlock) continue;
1569
+ const entry = {};
1570
+ const prefixMatch = rcBlock.match(/prefix:\s*['"]([^'"]+)['"]/);
1571
+ if (prefixMatch) entry.prefix = prefixMatch[1];
1572
+ const routesBlock = extractObjectBlock(rcBlock, "routes");
1573
+ if (routesBlock) {
1574
+ const overrides = {};
1575
+ const overrideRegex = /['"]([^'"]+)['"]\s*:\s*(?:['"]([^'"]+)['"]|(false))/g;
1576
+ let om;
1577
+ while ((om = overrideRegex.exec(routesBlock)) !== null) {
1578
+ overrides[om[1]] = om[3] === "false" ? false : om[2];
1579
+ }
1580
+ if (Object.keys(overrides).length > 0) entry.routes = overrides;
1581
+ }
1582
+ result.set(slug, entry);
1583
+ }
1584
+ return result;
1585
+ }
1586
+ function extractNestedObjects(source) {
1587
+ const objects = [];
1588
+ let depth = 0;
1589
+ let start = -1;
1590
+ for (let i = 0; i < source.length; i++) {
1591
+ if (source[i] === "{") {
1592
+ if (depth === 0) start = i;
1593
+ depth++;
1594
+ } else if (source[i] === "}") {
1595
+ depth--;
1596
+ if (depth === 0 && start >= 0) {
1597
+ objects.push(source.slice(start, i + 1));
1598
+ start = -1;
1599
+ }
1600
+ }
1601
+ }
1602
+ return objects;
1603
+ }
1604
+ function extractObjectBlock(source, fieldName) {
1605
+ const pattern = new RegExp(`${fieldName}:\\s*\\{`);
1606
+ const match = pattern.exec(source);
1607
+ if (!match) return null;
1608
+ let depth = 1;
1609
+ const startIdx = match.index + match[0].length;
1610
+ for (let i = startIdx; i < source.length; i++) {
1611
+ if (source[i] === "{") depth++;
1612
+ else if (source[i] === "}") {
1613
+ depth--;
1614
+ if (depth === 0) return source.slice(startIdx, i);
1615
+ }
1616
+ }
1617
+ return null;
1618
+ }
1619
+ function extractArrayBlock(source, fieldName) {
1620
+ const startPattern = new RegExp(`${fieldName}:\\s*\\[`);
1621
+ const match = startPattern.exec(source);
1622
+ if (!match) return null;
1623
+ let depth = 1;
1624
+ const startIdx = match.index + match[0].length;
1625
+ for (let i = startIdx; i < source.length; i++) {
1626
+ if (source[i] === "[") depth++;
1627
+ else if (source[i] === "]") {
1628
+ depth--;
1629
+ if (depth === 0) return source.slice(startIdx, i);
1630
+ }
1631
+ }
1632
+ return null;
1633
+ }
1634
+ function isWorkflowFile(filename) {
1635
+ return /\.workflow\.(tsx?|jsx?)$/.test(filename);
1636
+ }
1637
+ function isModelFile(filename) {
1638
+ return /models\/.*\.(ts|tsx)$/.test(filename) && !filename.endsWith(".test.ts");
1639
+ }
1640
+ function isServerActionFile(filename) {
1641
+ return /\.server\.(ts|tsx)$/.test(filename);
1642
+ }
1643
+ function isActionFile(filename) {
1644
+ return /^actions\/.*\.(ts|tsx)$/.test(filename) && !filename.endsWith(".server.ts") && !filename.endsWith(".test.ts") && !filename.endsWith(".test.tsx");
1645
+ }
1646
+ function isComponentFile(filename) {
1647
+ return /components\/.*\.(tsx?|jsx?)$/.test(filename) && !filename.endsWith(".test.ts") && !filename.endsWith(".test.tsx");
1648
+ }
1649
+ function isPageFile2(filename) {
1650
+ return (/pages\/.*\.(tsx?|jsx?)$/.test(filename) || /app\/.*\.(tsx?|jsx?)$/.test(filename)) && !filename.endsWith(".test.ts") && !filename.endsWith(".test.tsx") && !filename.includes("layout");
1651
+ }
1652
+ function isAppDirFile(filename) {
1653
+ return /^app\//.test(filename);
1654
+ }
1655
+ function isConfigFile(filename) {
1656
+ return /mm\.config\.(ts|tsx|js)$/.test(filename);
1657
+ }
1658
+ function isModuleManifestFile(filename) {
1659
+ return /mm\.module\.(ts|tsx|js)$/.test(filename);
1660
+ }
1661
+ function isCompilableFile(filename) {
1662
+ return isWorkflowFile(filename) || isModelFile(filename) || isServerActionFile(filename) || isActionFile(filename) || isPageFile2(filename) || isComponentFile(filename);
1663
+ }
1664
+ function compileFile(filename, source, mode) {
1665
+ const errors = [];
1666
+ try {
1667
+ const parserPlugins = filename.endsWith(".tsx") || filename.endsWith(".jsx") ? ["typescript", "jsx"] : ["typescript"];
1668
+ const result = transformSync3(source, {
1669
+ filename,
1670
+ plugins: [[babelPlugin, { mode }]],
1671
+ parserOpts: { plugins: parserPlugins, attachComment: true }
1672
+ });
1673
+ const ir = result?.metadata?.mindmatrixIR ?? null;
1674
+ if (ir?.metadata) {
1675
+ const meta = ir.metadata;
1676
+ const fileErrors = meta.errors;
1677
+ const fileWarnings = meta.warnings;
1678
+ if (fileErrors) {
1679
+ for (const e of fileErrors) {
1680
+ errors.push({
1681
+ file: filename,
1682
+ message: e.message,
1683
+ line: e.line,
1684
+ column: e.column,
1685
+ endLine: e.line,
1686
+ endColumn: e.column !== void 0 ? e.column + 10 : void 0,
1687
+ severity: "error"
1688
+ });
1689
+ }
1690
+ }
1691
+ if (fileWarnings) {
1692
+ for (const w of fileWarnings) {
1693
+ errors.push({
1694
+ file: filename,
1695
+ message: w.message,
1696
+ line: w.line,
1697
+ column: w.column,
1698
+ endLine: w.line,
1699
+ endColumn: w.column !== void 0 ? w.column + 10 : void 0,
1700
+ severity: "warning"
1701
+ });
1702
+ }
1703
+ }
1704
+ }
1705
+ return { ir, errors };
1706
+ } catch (err) {
1707
+ const errMsg = err.message;
1708
+ const locMatch = errMsg.match(/\((\d+):(\d+)\)/);
1709
+ const line = locMatch ? parseInt(locMatch[1], 10) : void 0;
1710
+ const column = locMatch ? parseInt(locMatch[2], 10) : void 0;
1711
+ errors.push({
1712
+ file: filename,
1713
+ message: "Compilation failed: " + errMsg,
1714
+ line,
1715
+ column,
1716
+ endLine: line,
1717
+ endColumn: column !== void 0 ? column + 1 : void 0,
1718
+ severity: "error"
1719
+ });
1720
+ return { ir: null, errors };
1721
+ }
1722
+ }
1723
+ function deduplicateActions(actions) {
1724
+ const seen = /* @__PURE__ */ new Set();
1725
+ const result = [];
1726
+ for (const action of actions) {
1727
+ const key = JSON.stringify(action);
1728
+ if (!seen.has(key)) {
1729
+ seen.add(key);
1730
+ result.push(action);
1731
+ }
1732
+ }
1733
+ return result;
1734
+ }
1735
+ function mergeIRs(irs, config) {
1736
+ if (irs.length === 0) {
1737
+ return createEmptyIR(config);
1738
+ }
1739
+ if (irs.length === 1) {
1740
+ return applyConfig(irs[0], config);
1741
+ }
1742
+ const fieldMap = /* @__PURE__ */ new Map();
1743
+ for (const ir of irs) {
1744
+ for (const field of ir.fields) {
1745
+ if (!fieldMap.has(field.name)) {
1746
+ fieldMap.set(field.name, field);
1747
+ } else {
1748
+ const existing = fieldMap.get(field.name);
1749
+ if (field.required && !existing.required) {
1750
+ existing.required = true;
1751
+ }
1752
+ if (field.default_value != null && field.default_value !== "" && field.default_value !== 0 && field.default_value !== false) {
1753
+ if (existing.default_value == null || existing.default_value === "" || existing.default_value === 0 || existing.default_value === false) {
1754
+ existing.default_value = field.default_value;
1755
+ }
1756
+ }
1757
+ }
1758
+ }
1759
+ }
1760
+ const stateMap = /* @__PURE__ */ new Map();
1761
+ for (const ir of irs) {
1762
+ for (const state of ir.states) {
1763
+ if (stateMap.has(state.name)) {
1764
+ const existing = stateMap.get(state.name);
1765
+ existing.on_enter = deduplicateActions([...existing.on_enter, ...state.on_enter]);
1766
+ existing.on_exit = deduplicateActions([...existing.on_exit, ...state.on_exit]);
1767
+ existing.during = deduplicateActions([...existing.during, ...state.during]);
1768
+ if (state.on_event) {
1769
+ existing.on_event = [...existing.on_event || [], ...state.on_event];
1770
+ }
1771
+ } else {
1772
+ stateMap.set(state.name, { ...state });
1773
+ }
1774
+ }
1775
+ }
1776
+ const transitionMap = /* @__PURE__ */ new Map();
1777
+ for (const ir of irs) {
1778
+ for (const transition of ir.transitions) {
1779
+ if (!transitionMap.has(transition.name)) {
1780
+ transitionMap.set(transition.name, transition);
1781
+ }
1782
+ }
1783
+ }
1784
+ const events = [];
1785
+ for (const ir of irs) {
1786
+ if (ir.on_event) {
1787
+ events.push(...ir.on_event);
1788
+ }
1789
+ }
1790
+ const viewTrees = [];
1791
+ for (const ir of irs) {
1792
+ const views = ir.views;
1793
+ if (views?.default) {
1794
+ viewTrees.push(views.default);
1795
+ }
1796
+ }
1797
+ const extensions = {};
1798
+ for (const ir of irs) {
1799
+ if (ir.extensions) {
1800
+ for (const [key, islands] of Object.entries(ir.extensions)) {
1801
+ if (!extensions[key]) extensions[key] = [];
1802
+ extensions[key].push(...islands);
1803
+ }
1804
+ }
1805
+ }
1806
+ const metadata = {};
1807
+ for (const ir of irs) {
1808
+ if (ir.metadata) {
1809
+ for (const [key, value] of Object.entries(ir.metadata)) {
1810
+ if (key === "errors" || key === "warnings") continue;
1811
+ metadata[key] = value;
1812
+ }
1813
+ }
1814
+ }
1815
+ const roleMap = /* @__PURE__ */ new Map();
1816
+ for (const ir of irs) {
1817
+ for (const role of ir.roles) {
1818
+ if (!roleMap.has(role.name)) {
1819
+ roleMap.set(role.name, role);
1820
+ }
1821
+ }
1822
+ }
1823
+ const base = irs[0];
1824
+ const merged = {
1825
+ slug: base.slug,
1826
+ name: base.name,
1827
+ version: base.version,
1828
+ description: base.description,
1829
+ category: base.category,
1830
+ fields: Array.from(fieldMap.values()),
1831
+ states: Array.from(stateMap.values()),
1832
+ transitions: Array.from(transitionMap.values()),
1833
+ roles: Array.from(roleMap.values()),
1834
+ tags: base.tags,
1835
+ metadata
1836
+ };
1837
+ if (events.length > 0) {
1838
+ merged.on_event = events;
1839
+ }
1840
+ if (Object.keys(extensions).length > 0) {
1841
+ merged.extensions = extensions;
1842
+ }
1843
+ if (viewTrees.length === 1) {
1844
+ merged.views = { default: viewTrees[0] };
1845
+ } else if (viewTrees.length > 1) {
1846
+ const rootView = {
1847
+ id: "project-root",
1848
+ component: "Stack",
1849
+ children: viewTrees
1850
+ };
1851
+ merged.views = { default: rootView };
1852
+ }
1853
+ return applyConfig(merged, config);
1854
+ }
1855
+ function applyConfig(ir, config) {
1856
+ if (config.slug) ir.slug = config.slug;
1857
+ if (config.name) ir.name = config.name;
1858
+ if (config.version) ir.version = config.version;
1859
+ if (config.description !== void 0) ir.description = config.description;
1860
+ if (config.category) ir.category = config.category;
1861
+ if (!ir.metadata) ir.metadata = {};
1862
+ ir.metadata.stable_id = "def-" + ir.slug;
1863
+ ir.metadata.provenance = {
1864
+ frontend: "react-compiler",
1865
+ source: "project",
1866
+ compiler_version: "2.0.0"
1867
+ };
1868
+ return ir;
1869
+ }
1870
+ function createEmptyIR(config) {
1871
+ return {
1872
+ slug: config.slug || "project",
1873
+ name: config.name || "Project",
1874
+ version: config.version || "0.1.0",
1875
+ description: config.description,
1876
+ category: config.category || "workflow",
1877
+ fields: [],
1878
+ states: [{
1879
+ name: "draft",
1880
+ type: "START",
1881
+ on_enter: [],
1882
+ during: [],
1883
+ on_exit: []
1884
+ }],
1885
+ transitions: [],
1886
+ roles: [],
1887
+ tags: [],
1888
+ metadata: {
1889
+ stable_id: "def-" + (config.slug || "project"),
1890
+ provenance: {
1891
+ frontend: "react-compiler",
1892
+ source: "project",
1893
+ compiler_version: "2.0.0"
1894
+ }
1895
+ }
1896
+ };
1897
+ }
1898
+ function resolveImportLinks(files, compilableFiles) {
1899
+ const links = [];
1900
+ for (const filename of compilableFiles) {
1901
+ const source = files[filename];
1902
+ const importRegex = /import\s+(?:type\s+)?(?:\{([^}]+)\}|(\w+))\s+from\s+['"](\.[^'"]+)['"]/g;
1903
+ let match;
1904
+ while ((match = importRegex.exec(source)) !== null) {
1905
+ const namedImports = match[1];
1906
+ const defaultImport = match[2];
1907
+ const importPath = match[3];
1908
+ const resolved = resolveImport(filename, importPath, Object.keys(files));
1909
+ if (!resolved || resolved === filename) continue;
1910
+ let linkType = "unknown";
1911
+ if (isModelFile(resolved)) {
1912
+ linkType = "data-source";
1913
+ } else if (isServerActionFile(resolved)) {
1914
+ linkType = "action";
1915
+ } else if (/components\//.test(resolved)) {
1916
+ linkType = "component";
1917
+ }
1918
+ const symbols = [];
1919
+ if (namedImports) {
1920
+ symbols.push(...namedImports.split(",").map((s) => s.trim().split(" as ")[0].trim()).filter(Boolean));
1921
+ }
1922
+ if (defaultImport) {
1923
+ symbols.push(defaultImport);
1924
+ }
1925
+ links.push({
1926
+ fromFile: filename,
1927
+ toFile: resolved,
1928
+ linkType,
1929
+ symbols
1930
+ });
1931
+ }
1932
+ }
1933
+ return links;
1934
+ }
1935
+ function resolveCompilationOrder(files, compilableFiles) {
1936
+ const { dependencies } = buildDependencyGraph(files);
1937
+ return topologicalSort(compilableFiles, dependencies);
1938
+ }
1939
+ function extractComponentProps(source) {
1940
+ const match = source.match(/function\s+\w+\s*\(\s*\{([^}]+)\}/);
1941
+ if (!match) return [];
1942
+ return match[1].split(",").map((p) => p.trim().split(/[\s=:]/)[0].replace(/^\.{3}/, "").trim()).filter(Boolean);
1943
+ }
1944
+ function generateModuleTypeStubs(childDefinitions, modelResults) {
1945
+ const stubs = {};
1946
+ for (const child of childDefinitions) {
1947
+ if (!child.slug) continue;
1948
+ const category = child.category;
1949
+ const isModel = category === "data" || Array.isArray(category) && category.includes("model") || Array.isArray(category) && category.includes("data");
1950
+ if (!isModel || !child.fields || child.fields.length === 0) continue;
1951
+ const interfaceName = slugToInterfaceName(child.slug) + "Fields";
1952
+ const lines = [
1953
+ `// Auto-generated type stub for model: ${child.slug}`,
1954
+ `// Do not edit \u2014 regenerated on each build.`,
1955
+ ``,
1956
+ `export interface ${interfaceName} {`
1957
+ ];
1958
+ for (const field of child.fields) {
1959
+ const tsType = irFieldTypeToTs(field.type || "string");
1960
+ const optional = field.required ? "" : "?";
1961
+ if (field.description) {
1962
+ lines.push(` /** ${field.description} */`);
1963
+ }
1964
+ lines.push(` ${field.name}${optional}: ${tsType};`);
1965
+ }
1966
+ lines.push(`}`);
1967
+ lines.push(``);
1968
+ lines.push(`export declare const ${slugToCamelCase(child.slug)}Slug: '${child.slug}';`);
1969
+ lines.push(``);
1970
+ stubs[`types/modules/${child.slug}.d.ts`] = lines.join("\n");
1971
+ }
1972
+ return stubs;
1973
+ }
1974
+ function slugToInterfaceName(slug) {
1975
+ return slug.split("-").map((s) => s.charAt(0).toUpperCase() + s.slice(1)).join("");
1976
+ }
1977
+ function slugToCamelCase(slug) {
1978
+ const parts = slug.split("-");
1979
+ return parts[0] + parts.slice(1).map((s) => s.charAt(0).toUpperCase() + s.slice(1)).join("");
1980
+ }
1981
+ function irFieldTypeToTs(type) {
1982
+ switch (type) {
1983
+ case "string":
1984
+ case "text":
1985
+ case "email":
1986
+ case "url":
1987
+ case "phone":
1988
+ case "slug":
1989
+ case "color":
1990
+ case "password":
1991
+ return "string";
1992
+ case "number":
1993
+ case "integer":
1994
+ case "float":
1995
+ case "currency":
1996
+ case "percent":
1997
+ return "number";
1998
+ case "boolean":
1999
+ case "toggle":
2000
+ return "boolean";
2001
+ case "date":
2002
+ case "datetime":
2003
+ case "timestamp":
2004
+ return "string";
2005
+ case "json":
2006
+ case "object":
2007
+ return "Record<string, unknown>";
2008
+ case "array":
2009
+ return "unknown[]";
2010
+ case "enum":
2011
+ return "string";
2012
+ case "file":
2013
+ case "image":
2014
+ return "string";
2015
+ default:
2016
+ return "unknown";
2017
+ }
2018
+ }
2019
+ function buildComposedResult(files, fileIRs, config, errors, warnings, options = {}) {
2020
+ const usePhase2 = options.usePhase2Modules !== false;
2021
+ const workflowIRs = [];
2022
+ const modelIRs = [];
2023
+ const actionDefinitionIRs = [];
2024
+ const serverActionEntries = [];
2025
+ let modelResults;
2026
+ let actionResult;
2027
+ let routeResult;
2028
+ const componentDefinitions = {};
2029
+ for (const [filename, ir] of Object.entries(fileIRs)) {
2030
+ if (isWorkflowFile(filename)) {
2031
+ workflowIRs.push(ir);
2032
+ } else if (isModelFile(filename)) {
2033
+ if (!ir.category || ir.category === "workflow") {
2034
+ ir.category = "data";
2035
+ }
2036
+ modelIRs.push(ir);
2037
+ } else if (isServerActionFile(filename)) {
2038
+ const meta = ir.metadata;
2039
+ const actions = meta?.serverActions;
2040
+ if (actions) {
2041
+ for (const action of actions) {
2042
+ serverActionEntries.push({
2043
+ name: action.name,
2044
+ sourceFile: filename,
2045
+ async: action.async,
2046
+ params: action.params,
2047
+ description: action.description
2048
+ });
2049
+ }
2050
+ }
2051
+ } else if (isComponentFile(filename)) {
2052
+ const views = ir.views;
2053
+ const experience = views?.default ?? ir.experience;
2054
+ if (experience) {
2055
+ const baseName = filename.split("/").pop()?.replace(/\.(tsx?|jsx?)$/, "") || "Component";
2056
+ const source = files[filename];
2057
+ const props = source ? extractComponentProps(source) : [];
2058
+ componentDefinitions[baseName] = { experience, props };
2059
+ }
2060
+ }
2061
+ }
2062
+ for (const [filename, source] of Object.entries(files)) {
2063
+ if (isActionFile(filename)) {
2064
+ const result = extractAction(source, filename);
2065
+ if (result) {
2066
+ actionDefinitionIRs.push(result.ir);
2067
+ for (const w of result.warnings) {
2068
+ warnings.push({ file: filename, message: w, severity: "warning" });
2069
+ }
2070
+ }
2071
+ }
2072
+ }
2073
+ if (usePhase2) {
2074
+ const modelFiles = {};
2075
+ for (const [filename, source] of Object.entries(files)) {
2076
+ if (isModelFile(filename)) {
2077
+ modelFiles[filename] = source;
2078
+ }
2079
+ }
2080
+ if (Object.keys(modelFiles).length > 0) {
2081
+ modelResults = compileModels(modelFiles, { mode: options.mode || "infer" });
2082
+ modelIRs.length = 0;
2083
+ for (const [, result] of modelResults) {
2084
+ modelIRs.push(result.ir);
2085
+ }
2086
+ }
2087
+ const actionFiles = {};
2088
+ for (const [filename, source] of Object.entries(files)) {
2089
+ if (isServerActionFile(filename)) {
2090
+ actionFiles[filename] = source;
2091
+ }
2092
+ }
2093
+ if (Object.keys(actionFiles).length > 0) {
2094
+ actionResult = compileActions(actionFiles, {
2095
+ mode: options.mode || "infer",
2096
+ blueprintSlug: config.slug || "app"
2097
+ });
2098
+ serverActionEntries.length = 0;
2099
+ for (const reg of actionResult.actions) {
2100
+ serverActionEntries.push({
2101
+ name: reg.name,
2102
+ sourceFile: reg.sourceFile,
2103
+ async: reg.async,
2104
+ params: reg.params,
2105
+ description: reg.description,
2106
+ body: reg.body,
2107
+ returnType: reg.returnType
2108
+ });
2109
+ }
2110
+ }
2111
+ const appFiles = {};
2112
+ for (const [filename, source] of Object.entries(files)) {
2113
+ if (isAppDirFile(filename) || isPageFile2(filename)) {
2114
+ appFiles[filename] = source;
2115
+ }
2116
+ }
2117
+ if (Object.keys(appFiles).length > 0) {
2118
+ routeResult = extractRoutes(appFiles, {
2119
+ slugPrefix: config.slug || "app"
2120
+ });
2121
+ }
2122
+ }
2123
+ const childDefinitions = [
2124
+ ...workflowIRs,
2125
+ ...modelIRs,
2126
+ ...actionDefinitionIRs
2127
+ ];
2128
+ let routeTable = [];
2129
+ if (routeResult) {
2130
+ routeTable = routeResult.routes.map((r) => ({
2131
+ path: r.path,
2132
+ stateName: r.stateName,
2133
+ sourceFile: r.sourceFile,
2134
+ params: r.params
2135
+ }));
2136
+ childDefinitions.push(routeResult.routerIR);
2137
+ } else {
2138
+ const pageFiles = [];
2139
+ for (const filename of Object.keys(files)) {
2140
+ if (isPageFile2(filename)) {
2141
+ pageFiles.push({
2142
+ relativePath: filename,
2143
+ absolutePath: filename
2144
+ });
2145
+ const routePath = filename.replace(/^pages\//, "").replace(/^app\//, "").replace(/\.(tsx?|jsx?)$/, "").replace(/\/index$/, "").replace(/\/page$/, "");
2146
+ const stateName = pathToStateName(routePath);
2147
+ const urlPattern = pathToUrlPattern(filename, filename.split("/").pop() || "page.tsx");
2148
+ const params = extractParams(filename);
2149
+ routeTable.push({
2150
+ path: urlPattern,
2151
+ stateName,
2152
+ sourceFile: filename,
2153
+ params
2154
+ });
2155
+ }
2156
+ }
2157
+ if (pageFiles.length > 0) {
2158
+ const routerWorkflow = extractRouterWorkflow(pageFiles, {
2159
+ slug: config.slug ? config.slug + "-router" : "app-router",
2160
+ pageFileName: pageFiles[0]?.relativePath.split("/").pop() || "page.tsx"
2161
+ });
2162
+ childDefinitions.push(routerWorkflow);
2163
+ }
2164
+ }
2165
+ if (options.resolvedModules && options.resolvedModules.length > 0) {
2166
+ const depConfigs = parseDependencyRouteConfigs(files);
2167
+ for (const mod of options.resolvedModules) {
2168
+ const depConfig = depConfigs.get(mod.slug);
2169
+ const prefix = depConfig?.prefix ?? `/${mod.slug.replace(/^mod-/, "")}`;
2170
+ const routeOverrides = depConfig?.routes;
2171
+ for (const modRoute of mod.routeTable) {
2172
+ if (routeOverrides) {
2173
+ const override = routeOverrides[modRoute.path];
2174
+ if (override === false) continue;
2175
+ if (typeof override === "string") {
2176
+ const existingPaths2 = new Set(routeTable.map((r) => r.path));
2177
+ if (!existingPaths2.has(override)) {
2178
+ routeTable.push({
2179
+ path: override,
2180
+ stateName: `MOD_${mod.slug.replace(/-/g, "_").toUpperCase()}_${modRoute.stateName}`,
2181
+ sourceFile: modRoute.sourceFile,
2182
+ params: modRoute.params,
2183
+ moduleSlug: mod.slug
2184
+ });
2185
+ }
2186
+ continue;
2187
+ }
2188
+ }
2189
+ const prefixedPath = prefix + (modRoute.path === "/" ? "" : modRoute.path);
2190
+ const existingPaths = new Set(routeTable.map((r) => r.path));
2191
+ if (!existingPaths.has(prefixedPath)) {
2192
+ routeTable.push({
2193
+ path: prefixedPath,
2194
+ stateName: `MOD_${mod.slug.replace(/-/g, "_").toUpperCase()}_${modRoute.stateName}`,
2195
+ sourceFile: modRoute.sourceFile,
2196
+ params: modRoute.params,
2197
+ moduleSlug: mod.slug
2198
+ });
2199
+ }
2200
+ }
2201
+ }
2202
+ }
2203
+ if (options.resolvedModules && options.resolvedModules.length > 0) {
2204
+ for (const mod of options.resolvedModules) {
2205
+ if (mod.serverActions && mod.serverActions.length > 0) {
2206
+ for (const action of mod.serverActions) {
2207
+ const namespacedName = `${mod.slug}:${action.name}`;
2208
+ if (!serverActionEntries.some((a) => a.name === namespacedName)) {
2209
+ serverActionEntries.push({
2210
+ ...action,
2211
+ name: namespacedName,
2212
+ sourceFile: `${mod.slug}/${action.sourceFile}`
2213
+ });
2214
+ }
2215
+ }
2216
+ }
2217
+ }
2218
+ }
2219
+ const allIRs = Object.values(fileIRs);
2220
+ const parentIR = mergeIRs(allIRs, config);
2221
+ if (!parentIR.metadata) parentIR.metadata = {};
2222
+ const parentMeta = parentIR.metadata;
2223
+ parentMeta.childSlugs = childDefinitions.map((c) => c.slug);
2224
+ parentMeta.serverActions = serverActionEntries;
2225
+ if (routeTable.length > 0) {
2226
+ parentMeta.routeTable = routeTable;
2227
+ }
2228
+ parentMeta.composition = {
2229
+ workflowCount: workflowIRs.length,
2230
+ modelCount: modelIRs.length,
2231
+ actionCount: actionDefinitionIRs.length,
2232
+ serverActionCount: serverActionEntries.length,
2233
+ routeCount: routeTable.length,
2234
+ componentCount: Object.keys(componentDefinitions).length,
2235
+ totalFiles: Object.keys(files).length
2236
+ };
2237
+ if (Object.keys(componentDefinitions).length > 0) {
2238
+ parentMeta.componentDefinitions = componentDefinitions;
2239
+ }
2240
+ if (actionResult) {
2241
+ parentMeta.actionEndpoints = actionResult.actions.map((a) => ({
2242
+ actionId: a.actionId,
2243
+ endpoint: a.endpoint,
2244
+ group: a.group
2245
+ }));
2246
+ }
2247
+ for (const [filename, source] of Object.entries(files)) {
2248
+ if (isConfigFile(filename) || isModuleManifestFile(filename)) {
2249
+ const manifest2 = parseModuleManifest(source);
2250
+ if (manifest2) {
2251
+ parentMeta.module_manifest = manifest2;
2252
+ }
2253
+ break;
2254
+ }
2255
+ }
2256
+ const manifest = parentMeta.module_manifest;
2257
+ if (manifest?.dependencies) {
2258
+ parentMeta.module_dependencies = manifest.dependencies;
2259
+ }
2260
+ if (manifest?.contributions) {
2261
+ parentMeta.slot_contributions = manifest.contributions;
2262
+ }
2263
+ if (manifest?.configSchema) {
2264
+ parentMeta.configSchema = manifest.configSchema;
2265
+ }
2266
+ if (manifest?.dependencies) {
2267
+ const depConfigs = {};
2268
+ for (const dep of manifest.dependencies) {
2269
+ if (dep.config) {
2270
+ depConfigs[dep.slug] = dep.config;
2271
+ }
2272
+ }
2273
+ if (Object.keys(depConfigs).length > 0) {
2274
+ parentMeta.module_configs = depConfigs;
2275
+ }
2276
+ }
2277
+ const compilableFiles = Object.keys(files).filter(isCompilableFile);
2278
+ const importLinks = resolveImportLinks(files, compilableFiles);
2279
+ const pageExperiences = {};
2280
+ for (const [filename, ir] of Object.entries(fileIRs)) {
2281
+ if (isPageFile2(filename)) {
2282
+ const views = ir.views;
2283
+ if (views?.default) {
2284
+ pageExperiences[filename] = views.default;
2285
+ }
2286
+ }
2287
+ }
2288
+ const parentViews = parentIR.views;
2289
+ if (Object.keys(pageExperiences).length > 0) {
2290
+ const pageEntries = Object.entries(pageExperiences);
2291
+ const routeNodes = pageEntries.map(([pagePath, pageTree], i) => {
2292
+ const routePath = "/" + pagePath.replace(/^app\//, "").replace(/\.(tsx?|jsx?)$/, "").replace(/\/index$/, "").replace(/\/page$/, "");
2293
+ return {
2294
+ id: `route-${i}`,
2295
+ component: "Route",
2296
+ config: { path: routePath },
2297
+ children: [pageTree]
2298
+ };
2299
+ });
2300
+ const navLinks = pageEntries.map(([pagePath], i) => {
2301
+ const routePath = "/" + pagePath.replace(/^app\//, "").replace(/\.(tsx?|jsx?)$/, "").replace(/\/index$/, "").replace(/\/page$/, "");
2302
+ const segments = routePath.split("/").filter(Boolean);
2303
+ const label = segments[segments.length - 1]?.replace(/-/g, " ").replace(/\b\w/g, (c) => c.toUpperCase()) || "Home";
2304
+ return {
2305
+ id: `nav-link-${i}`,
2306
+ component: "NavLink",
2307
+ config: { to: routePath, label }
2308
+ };
2309
+ });
2310
+ routeNodes.unshift({
2311
+ id: "route-index",
2312
+ component: "Route",
2313
+ config: { path: "/", exact: true },
2314
+ children: [pageEntries[0][1]]
2315
+ });
2316
+ const moduleRoutes = routeTable.filter((r) => r.moduleSlug);
2317
+ for (let mi = 0; mi < moduleRoutes.length; mi++) {
2318
+ const mr = moduleRoutes[mi];
2319
+ routeNodes.push({
2320
+ id: `mod-route-${mi}`,
2321
+ component: "Route",
2322
+ config: { path: mr.path },
2323
+ children: [{
2324
+ id: `mod-route-${mi}-placeholder`,
2325
+ component: "ModuleView",
2326
+ config: { moduleSlug: mr.moduleSlug, sourceFile: mr.sourceFile, path: mr.path }
2327
+ }]
2328
+ });
2329
+ const segments = mr.path.split("/").filter(Boolean);
2330
+ const label = segments[segments.length - 1]?.replace(/-/g, " ").replace(/\b\w/g, (c) => c.toUpperCase()) || mr.moduleSlug;
2331
+ navLinks.push({
2332
+ id: `mod-nav-${mi}`,
2333
+ component: "NavLink",
2334
+ config: { to: mr.path, label, moduleSlug: mr.moduleSlug }
2335
+ });
2336
+ }
2337
+ const composedExperience = {
2338
+ id: "blueprint-root",
2339
+ component: "Stack",
2340
+ className: "h-full flex flex-col",
2341
+ children: [
2342
+ // Nav bar (always visible, not inside Router so it always renders)
2343
+ {
2344
+ id: "nav-bar",
2345
+ component: "Row",
2346
+ config: { gap: 1 },
2347
+ className: "px-4 py-2 border-b border-border bg-background/95 backdrop-blur-sm sticky top-0 z-10 flex-wrap",
2348
+ children: navLinks
2349
+ },
2350
+ // Router with page routes
2351
+ {
2352
+ id: "page-router",
2353
+ component: "Router",
2354
+ className: "flex-1 min-h-0 overflow-y-auto",
2355
+ children: routeNodes.map((r) => ({
2356
+ ...r,
2357
+ children: r.children?.map((child) => ({
2358
+ ...child,
2359
+ id: child.id || r.id + "-content",
2360
+ component: child.component || "Stack",
2361
+ config: { ...child.config, gap: 4, padding: 4 }
2362
+ }))
2363
+ }))
2364
+ }
2365
+ ]
2366
+ };
2367
+ parentIR.experience = composedExperience;
2368
+ const slug = config.slug || parentIR.slug || "blueprint";
2369
+ parentMeta.blueprint_manifest = {
2370
+ routes: [
2371
+ { path: `${slug}/*`, node: slug, label: config.name || parentIR.name || slug }
2372
+ ],
2373
+ config: {
2374
+ full_bleed: true
2375
+ }
2376
+ };
2377
+ } else if (parentViews?.default) {
2378
+ parentIR.experience = parentViews.default;
2379
+ }
2380
+ for (const childDef of childDefinitions) {
2381
+ for (const [filename, ir] of Object.entries(fileIRs)) {
2382
+ if (ir.slug === childDef.slug || isWorkflowFile(filename) && ir.slug === childDef.slug) {
2383
+ const views = ir.views;
2384
+ if (views?.default) {
2385
+ childDef.experience = views.default;
2386
+ }
2387
+ break;
2388
+ }
2389
+ }
2390
+ }
2391
+ const typeStubs = generateModuleTypeStubs(childDefinitions, modelResults);
2392
+ return {
2393
+ ir: parentIR,
2394
+ childDefinitions,
2395
+ fileIRs,
2396
+ routeTable,
2397
+ serverActions: serverActionEntries,
2398
+ errors,
2399
+ warnings,
2400
+ pageExperiences,
2401
+ componentDefinitions,
2402
+ importLinks,
2403
+ modelResults,
2404
+ actionResult,
2405
+ routeResult,
2406
+ typeStubs
2407
+ };
2408
+ }
2409
+ function compileProject(files, options = {}) {
2410
+ const allErrors = [];
2411
+ const allWarnings = [];
2412
+ const fileIRs = {};
2413
+ let config = {};
2414
+ for (const [filename, source] of Object.entries(files)) {
2415
+ if (isConfigFile(filename)) {
2416
+ config = parseConfig(source);
2417
+ break;
2418
+ }
2419
+ }
2420
+ const mode = config.mode || options.mode || "infer";
2421
+ const compilableFiles = Object.keys(files).filter(isCompilableFile);
2422
+ const orderedFiles = resolveCompilationOrder(files, compilableFiles);
2423
+ for (const filename of orderedFiles) {
2424
+ const source = files[filename];
2425
+ const { ir, errors } = compileFile(filename, source, mode);
2426
+ for (const e of errors) {
2427
+ if (e.severity === "error") allErrors.push(e);
2428
+ else allWarnings.push(e);
2429
+ }
2430
+ if (ir) {
2431
+ fileIRs[filename] = ir;
2432
+ }
2433
+ }
2434
+ return buildComposedResult(files, fileIRs, config, allErrors, allWarnings, {
2435
+ usePhase2Modules: options.usePhase2Modules,
2436
+ mode,
2437
+ resolvedModules: options.resolvedModules
2438
+ });
2439
+ }
2440
+ var IncrementalProjectCompiler = class {
2441
+ constructor() {
2442
+ this.lastConfig = {};
2443
+ this.cache = new IncrementalCache();
2444
+ }
2445
+ /**
2446
+ * Compile a project incrementally — only recompiles changed files.
2447
+ */
2448
+ compile(files, options = {}) {
2449
+ const startTime = Date.now();
2450
+ const { dependents } = buildDependencyGraph(files);
2451
+ const dirtySet = this.cache.detectDirtyFiles(files, dependents);
2452
+ const allDirty = /* @__PURE__ */ new Set([
2453
+ ...dirtySet.contentChanged,
2454
+ ...dirtySet.dependencyDirty,
2455
+ ...dirtySet.added
2456
+ ]);
2457
+ for (const removed of dirtySet.removed) {
2458
+ this.cache.delete(removed);
2459
+ }
2460
+ if (allDirty.size === 0 && this.cache.getCachedFiles().length > 0) {
2461
+ this.cache.updateStats(0, this.cache.getCachedFiles().length, Date.now() - startTime);
2462
+ return this.rebuildFromCache(files, options);
2463
+ }
2464
+ for (const [filename, source] of Object.entries(files)) {
2465
+ if (isConfigFile(filename)) {
2466
+ if (allDirty.has(filename)) {
2467
+ this.lastConfig = parseConfig(source);
2468
+ }
2469
+ break;
2470
+ }
2471
+ }
2472
+ const mode = this.lastConfig.mode || options.mode || "infer";
2473
+ const compilableFiles = Object.keys(files).filter(isCompilableFile);
2474
+ let recompiled = 0;
2475
+ let cacheHits = 0;
2476
+ for (const filename of compilableFiles) {
2477
+ if (allDirty.has(filename) || !this.cache.has(filename)) {
2478
+ const { ir, errors } = compileFile(filename, files[filename], mode);
2479
+ if (ir) {
2480
+ this.cache.set(filename, files[filename], { ir, errors });
2481
+ } else {
2482
+ this.cache.delete(filename);
2483
+ }
2484
+ recompiled++;
2485
+ } else {
2486
+ cacheHits++;
2487
+ }
2488
+ }
2489
+ for (const cached of this.cache.getCachedFiles()) {
2490
+ if (!compilableFiles.includes(cached)) {
2491
+ this.cache.delete(cached);
2492
+ }
2493
+ }
2494
+ const fileIRs = {};
2495
+ const allErrors = [];
2496
+ const allWarnings = [];
2497
+ for (const cached of this.cache.getCachedFiles()) {
2498
+ const entry = this.cache.get(cached);
2499
+ if (entry) {
2500
+ fileIRs[cached] = entry.ir;
2501
+ for (const e of entry.errors) {
2502
+ if (e.severity === "error") allErrors.push(e);
2503
+ else allWarnings.push(e);
2504
+ }
2505
+ }
2506
+ }
2507
+ this.cache.updateStats(recompiled, cacheHits, Date.now() - startTime);
2508
+ return buildComposedResult(files, fileIRs, this.lastConfig, allErrors, allWarnings, {
2509
+ usePhase2Modules: options.usePhase2Modules,
2510
+ mode,
2511
+ resolvedModules: options.resolvedModules
2512
+ });
2513
+ }
2514
+ /**
2515
+ * Rebuild result from cache without recompiling anything.
2516
+ */
2517
+ rebuildFromCache(files, options) {
2518
+ let config = this.lastConfig;
2519
+ if (!config.slug) {
2520
+ for (const [filename, source] of Object.entries(files)) {
2521
+ if (isConfigFile(filename)) {
2522
+ config = parseConfig(source);
2523
+ this.lastConfig = config;
2524
+ break;
2525
+ }
2526
+ }
2527
+ }
2528
+ const fileIRs = {};
2529
+ const allErrors = [];
2530
+ const allWarnings = [];
2531
+ for (const cached of this.cache.getCachedFiles()) {
2532
+ const entry = this.cache.get(cached);
2533
+ if (entry) {
2534
+ fileIRs[cached] = entry.ir;
2535
+ for (const e of entry.errors) {
2536
+ if (e.severity === "error") allErrors.push(e);
2537
+ else allWarnings.push(e);
2538
+ }
2539
+ }
2540
+ }
2541
+ const mode = this.lastConfig.mode || options.mode || "infer";
2542
+ return buildComposedResult(files, fileIRs, config, allErrors, allWarnings, {
2543
+ usePhase2Modules: options.usePhase2Modules,
2544
+ mode,
2545
+ resolvedModules: options.resolvedModules
2546
+ });
2547
+ }
2548
+ /** Invalidate a specific file's cache. */
2549
+ invalidate(filename) {
2550
+ this.cache.delete(filename);
2551
+ }
2552
+ /** Invalidate all caches. */
2553
+ invalidateAll() {
2554
+ this.cache.clear();
2555
+ this.lastConfig = {};
2556
+ }
2557
+ /** Check if a file would need recompilation given its current source. */
2558
+ isDirty(filename, source) {
2559
+ hashContent(source);
2560
+ const cached = this.cache.get(filename);
2561
+ return !cached;
2562
+ }
2563
+ /** Get list of files currently in cache. */
2564
+ getCachedFiles() {
2565
+ return this.cache.getCachedFiles();
2566
+ }
2567
+ /** Get compilation statistics. */
2568
+ getStats() {
2569
+ const stats = this.cache.getStats();
2570
+ return {
2571
+ cachedFiles: stats.totalCached,
2572
+ totalHashes: stats.totalCached,
2573
+ ...stats
2574
+ };
2575
+ }
2576
+ };
2577
+
2578
+ export {
2579
+ compileModel,
2580
+ compileModels,
2581
+ extractRoutes,
2582
+ compileActions,
2583
+ resolveActionReferences,
2584
+ hashContent,
2585
+ extractImports,
2586
+ resolveImport,
2587
+ buildDependencyGraph,
2588
+ computeTransitiveDirtySet,
2589
+ topologicalSort,
2590
+ IncrementalCache,
2591
+ compileProject,
2592
+ IncrementalProjectCompiler
2593
+ };