@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
@@ -1,1018 +0,0 @@
1
- /**
2
- * Model Extractor — extracts TypeScript model files into workflow definitions.
3
- *
4
- * Model files (e.g., models/channel.ts) define workflows declaratively:
5
- *
6
- * export interface Channel {
7
- * name: string;
8
- * status: 'active' | 'archived';
9
- * memberCount: number;
10
- * isPublic: boolean;
11
- * createdAt: Date;
12
- * tags: string[];
13
- * metadata?: Record<string, unknown>;
14
- * }
15
- *
16
- * export const transitions = {
17
- * archive: { from: 'active', to: 'archived', guard: '$user.role == "admin"', roles: ['admin'] },
18
- * activate: { from: ['archived', 'draft'], to: 'active', required_fields: ['name'] },
19
- * };
20
- *
21
- * export const endStates = ['deleted'];
22
- * export const cancelledStates = ['cancelled'];
23
- *
24
- * export const hooks = {
25
- * on_enter_active: { emit: 'channel:activated', actions: ['notifyMembers'] },
26
- * on_exit_active: { actions: ['logDeactivation'] },
27
- * };
28
- *
29
- * export const runtime: RuntimeProfile = 'backend';
30
- *
31
- * export const fieldOptions = {
32
- * name: { scope: 'instance', persistence: 'durable' },
33
- * memberCount: {
34
- * computed: 'count(refs("member", { channel_id: $instance.id }))',
35
- * computed_deps: [],
36
- * visible_in_states: ['active'],
37
- * editable_by_roles: ['admin'],
38
- * },
39
- * };
40
- */
41
-
42
- import type { NodePath } from '@babel/traverse';
43
- import * as t from '@babel/types';
44
- import type {
45
- IRFieldDefinition,
46
- IRTransitionDefinition,
47
- IRConditionDefinition,
48
- IRActionDefinition,
49
- IRStateDefinition,
50
- IRWorkflowFieldType,
51
- IRStateType as _IRStateType,
52
- IRFieldValidation,
53
- IRStateHome,
54
- RuntimeProfile,
55
- } from '@mindmatrix/player-core';
56
- import type { CompilerState } from '../../types';
57
-
58
- // =============================================================================
59
- // Type Mapping
60
- // =============================================================================
61
-
62
- /**
63
- * Maps TypeScript type annotation strings to IR field types.
64
- */
65
- function tsTypeToFieldType(typeAnnotation: t.TSTypeAnnotation | t.TypeAnnotation | null | undefined): IRWorkflowFieldType {
66
- if (!typeAnnotation) return 'text';
67
- const annotation = typeAnnotation.typeAnnotation;
68
- return resolveType(annotation);
69
- }
70
-
71
- /** Well-known TypeScript type names that map to built-in IR field types */
72
- const KNOWN_TYPE_REFS: Record<string, IRWorkflowFieldType> = {
73
- Date: 'datetime',
74
- Record: 'json',
75
- Map: 'json',
76
- Set: 'json',
77
- URL: 'url',
78
- };
79
-
80
- /**
81
- * Converts a PascalCase TypeScript name to a kebab-case slug.
82
- */
83
- function typeNameToSlug(name: string): string {
84
- return name
85
- .replace(/([A-Z])/g, '-$1')
86
- .toLowerCase()
87
- .replace(/^-/, '');
88
- }
89
-
90
- function resolveType(annotation: t.Node): IRWorkflowFieldType {
91
- // string
92
- if (t.isTSStringKeyword(annotation)) return 'text';
93
- // number
94
- if (t.isTSNumberKeyword(annotation)) return 'number';
95
- // boolean
96
- if (t.isTSBooleanKeyword(annotation)) return 'boolean';
97
-
98
- // Named type references
99
- if (t.isTSTypeReference(annotation) && t.isIdentifier(annotation.typeName)) {
100
- const typeName = annotation.typeName.name;
101
- // Check known types first
102
- if (KNOWN_TYPE_REFS[typeName]) return KNOWN_TYPE_REFS[typeName];
103
- // Array<T> → multi_select
104
- if (typeName === 'Array') return 'multi_select';
105
- // Unknown type reference → emit as slug (Element-based custom field type)
106
- return typeNameToSlug(typeName);
107
- }
108
-
109
- // Array types: string[] or Array<string>
110
- if (t.isTSArrayType(annotation)) {
111
- return 'multi_select';
112
- }
113
-
114
- // Union of string literals → select
115
- if (t.isTSUnionType(annotation)) {
116
- const allLiterals = annotation.types.every(
117
- (t2) => t.isTSLiteralType(t2) && (t.isStringLiteral(t2.literal) || t.isNumericLiteral(t2.literal))
118
- );
119
- if (allLiterals) return 'select';
120
- // Union containing null/undefined means optional
121
- return 'text';
122
- }
123
-
124
- // Literal types (single literal)
125
- if (t.isTSLiteralType(annotation) && t.isStringLiteral(annotation.literal)) return 'text';
126
- if (t.isTSLiteralType(annotation) && t.isNumericLiteral(annotation.literal)) return 'number';
127
-
128
- return 'text';
129
- }
130
-
131
- /**
132
- * Extracts validation options from union string literal types.
133
- */
134
- function extractUnionOptions(annotation: t.Node): string[] | undefined {
135
- if (!t.isTSUnionType(annotation)) return undefined;
136
- const options: string[] = [];
137
- for (const member of annotation.types) {
138
- if (t.isTSLiteralType(member) && t.isStringLiteral(member.literal)) {
139
- options.push(member.literal.value);
140
- }
141
- }
142
- return options.length > 0 ? options : undefined;
143
- }
144
-
145
- /**
146
- * Extracts default value from an interface property's type.
147
- */
148
- function extractDefaultValue(fieldType: IRWorkflowFieldType): unknown {
149
- switch (fieldType) {
150
- case 'text': return '';
151
- case 'rich_text': return '';
152
- case 'number': return 0;
153
- case 'boolean': return false;
154
- case 'date': return null;
155
- case 'datetime': return null;
156
- case 'select': return '';
157
- case 'multi_select': return [];
158
- case 'url': return '';
159
- case 'json': return {};
160
- // Custom Element-based field types (email, currency, etc.) default to null
161
- default: return null;
162
- }
163
- }
164
-
165
- // =============================================================================
166
- // Interface Extraction → Fields
167
- // =============================================================================
168
-
169
- /**
170
- * Extracts fields from an exported TypeScript interface.
171
- */
172
- function extractFieldsFromInterface(
173
- declaration: t.TSInterfaceDeclaration
174
- ): IRFieldDefinition[] {
175
- const fields: IRFieldDefinition[] = [];
176
-
177
- for (const member of declaration.body.body) {
178
- if (!t.isTSPropertySignature(member)) continue;
179
- if (!t.isIdentifier(member.key)) continue;
180
-
181
- const name = member.key.name;
182
- const required = !member.optional;
183
- const typeAnno = member.typeAnnotation as t.TSTypeAnnotation | undefined;
184
- const fieldType = tsTypeToFieldType(typeAnno);
185
-
186
- const field: IRFieldDefinition = {
187
- name,
188
- type: fieldType,
189
- label: name.replace(/([A-Z])/g, ' $1').replace(/^./, (c) => c.toUpperCase()),
190
- required,
191
- default_value: extractDefaultValue(fieldType),
192
- };
193
-
194
- // Extract select options from union types
195
- if (typeAnno) {
196
- const options = extractUnionOptions(typeAnno.typeAnnotation);
197
- if (options) {
198
- field.validation = { options };
199
- }
200
- }
201
-
202
- fields.push(field);
203
- }
204
-
205
- return fields;
206
- }
207
-
208
- // =============================================================================
209
- // Transitions Extraction
210
- // =============================================================================
211
-
212
- interface TransitionConfig {
213
- from: string | string[];
214
- to: string;
215
- guard?: string;
216
- roles?: string[];
217
- auto?: boolean;
218
- required_fields?: string[];
219
- description?: string;
220
- actions?: Array<Record<string, unknown>>;
221
- conditions?: Array<Record<string, unknown>>;
222
- }
223
-
224
- /**
225
- * Extracts transitions from `export const transitions = { ... }`.
226
- */
227
- function extractTransitionsFromObject(
228
- init: t.ObjectExpression,
229
- actionCounter: { value: number }
230
- ): IRTransitionDefinition[] {
231
- const transitions: IRTransitionDefinition[] = [];
232
-
233
- for (const prop of init.properties) {
234
- if (!t.isObjectProperty(prop)) continue;
235
- if (!t.isIdentifier(prop.key) && !t.isStringLiteral(prop.key)) continue;
236
- if (!t.isObjectExpression(prop.value)) continue;
237
-
238
- const name = t.isIdentifier(prop.key) ? prop.key.name : prop.key.value;
239
- const config = extractObjectLiteral(prop.value) as unknown as TransitionConfig;
240
-
241
- // Parse from: can be string or array of strings
242
- let from: string[] = [];
243
- if (typeof config.from === 'string') {
244
- from = [config.from];
245
- } else if (Array.isArray(config.from)) {
246
- from = config.from.map(String);
247
- }
248
-
249
- const to = String(config.to || '');
250
-
251
- // Build conditions from guard expression
252
- const conditions: IRConditionDefinition[] = [];
253
- if (config.guard) {
254
- conditions.push(parseGuardExpression(config.guard));
255
- }
256
- // Also merge any explicit conditions
257
- if (config.conditions && Array.isArray(config.conditions)) {
258
- for (const cond of config.conditions) {
259
- conditions.push(cond as IRConditionDefinition);
260
- }
261
- }
262
-
263
- // Build actions from inline actions
264
- const actions: IRActionDefinition[] = [];
265
- if (config.actions && Array.isArray(config.actions)) {
266
- for (const action of config.actions) {
267
- if (typeof action === 'object' && action !== null) {
268
- actions.push({
269
- id: `auto_${++actionCounter.value}`,
270
- type: (action as any).type || 'custom',
271
- mode: 'auto',
272
- config: action as Record<string, unknown>,
273
- });
274
- }
275
- }
276
- }
277
-
278
- transitions.push({
279
- name,
280
- from,
281
- to,
282
- description: config.description,
283
- conditions: conditions.length > 0 ? conditions : undefined,
284
- actions,
285
- roles: config.roles,
286
- auto: config.auto,
287
- required_fields: config.required_fields,
288
- });
289
- }
290
-
291
- return transitions;
292
- }
293
-
294
- // =============================================================================
295
- // Guard Expression Parsing
296
- // =============================================================================
297
-
298
- /**
299
- * Parses a guard expression string into IRConditionDefinition.
300
- *
301
- * Supports:
302
- * - Simple field comparison: "$user.role == \"admin\""
303
- * - Expression form: any string → expression condition
304
- */
305
- function parseGuardExpression(guard: string): IRConditionDefinition {
306
- // Try to parse simple field operator value patterns
307
- // The \$? prefix is included in the capture group so $user.role stays as $user.role
308
- // Operators are ordered longest-first to prevent partial matches (>= before >)
309
- const simpleMatch = guard.match(
310
- /^(\$?\w+(?:\.\w+)*)\s*(not_in|is_set|is_empty|contains|>=|<=|!=|==|>|<|in)\s*(.+)?$/
311
- );
312
- if (simpleMatch) {
313
- const [, field, op, rawValue] = simpleMatch;
314
- const operatorMap: Record<string, IRConditionDefinition['operator']> = {
315
- '==': 'eq', '!=': 'ne', '>': 'gt', '>=': 'gte', '<': 'lt', '<=': 'lte',
316
- 'in': 'in', 'not_in': 'not_in', 'contains': 'contains',
317
- 'is_set': 'is_set', 'is_empty': 'is_empty',
318
- };
319
- const operator = operatorMap[op];
320
- if (operator) {
321
- let value: unknown = rawValue?.trim();
322
- if (value === undefined || value === '') {
323
- // Unary operators like is_set/is_empty
324
- return { field, operator };
325
- }
326
- // Parse value
327
- if (typeof value === 'string') {
328
- // Remove quotes
329
- if (value.startsWith('"') && value.endsWith('"')) {
330
- value = value.slice(1, -1);
331
- } else if (value.startsWith("'") && value.endsWith("'")) {
332
- value = value.slice(1, -1);
333
- } else if (value === 'true') {
334
- value = true;
335
- } else if (value === 'false') {
336
- value = false;
337
- } else if (value === 'null') {
338
- value = null;
339
- } else if (!isNaN(Number(value))) {
340
- value = Number(value);
341
- }
342
- }
343
- return { field, operator, value };
344
- }
345
- }
346
-
347
- // Fall back to expression form
348
- return { expression: guard };
349
- }
350
-
351
- // =============================================================================
352
- // Hooks Extraction
353
- // =============================================================================
354
-
355
- /**
356
- * Extracts hooks from `export const hooks = { ... }`.
357
- *
358
- * Format:
359
- * on_enter_stateName: { emit: 'event:name', actions: ['handler1', 'handler2'] }
360
- * on_exit_stateName: { actions: ['cleanup'] }
361
- */
362
- function extractHooksFromObject(
363
- init: t.ObjectExpression,
364
- states: Map<string, IRStateDefinition>,
365
- actionCounter: { value: number }
366
- ): void {
367
- for (const prop of init.properties) {
368
- if (!t.isObjectProperty(prop)) continue;
369
- if (!t.isIdentifier(prop.key) && !t.isStringLiteral(prop.key)) continue;
370
-
371
- const hookName = t.isIdentifier(prop.key) ? prop.key.name : prop.key.value;
372
- const hookConfig = t.isObjectExpression(prop.value)
373
- ? extractObjectLiteral(prop.value)
374
- : {};
375
-
376
- // Parse hook name: on_enter_active, on_exit_draft, etc.
377
- const enterMatch = hookName.match(/^on_enter_(.+)$/);
378
- const exitMatch = hookName.match(/^on_exit_(.+)$/);
379
-
380
- if (!enterMatch && !exitMatch) continue;
381
-
382
- const stateName = enterMatch ? enterMatch[1] : exitMatch![1];
383
- const phase = enterMatch ? 'on_enter' : 'on_exit';
384
-
385
- // Ensure state exists
386
- if (!states.has(stateName)) {
387
- states.set(stateName, {
388
- name: stateName,
389
- type: 'REGULAR',
390
- on_enter: [],
391
- during: [],
392
- on_exit: [],
393
- });
394
- }
395
- const state = states.get(stateName)!;
396
-
397
- // Process emit → emit_event action
398
- if (hookConfig.emit && typeof hookConfig.emit === 'string') {
399
- const action: IRActionDefinition = {
400
- id: `auto_${++actionCounter.value}`,
401
- type: 'emit_event',
402
- mode: 'auto',
403
- config: { event: hookConfig.emit },
404
- };
405
- state[phase].push(action);
406
- }
407
-
408
- // Process actions[] → server_action references
409
- if (hookConfig.actions && Array.isArray(hookConfig.actions)) {
410
- for (const handler of hookConfig.actions) {
411
- if (typeof handler === 'string') {
412
- const action: IRActionDefinition = {
413
- id: `auto_${++actionCounter.value}`,
414
- type: 'server_action',
415
- mode: 'auto',
416
- config: { handler },
417
- };
418
- state[phase].push(action);
419
- }
420
- }
421
- }
422
- }
423
- }
424
-
425
- // =============================================================================
426
- // Field Options Extraction
427
- // =============================================================================
428
-
429
- /**
430
- * Extracts field options from `export const fieldOptions = { ... }`.
431
- * Enriches existing fields with ACL, computed, validation, state home.
432
- */
433
- function applyFieldOptions(
434
- fields: IRFieldDefinition[],
435
- init: t.ObjectExpression
436
- ): void {
437
- const options = extractObjectLiteral(init) as Record<string, Record<string, unknown>>;
438
-
439
- for (const [fieldName, opts] of Object.entries(options)) {
440
- const field = fields.find((f) => f.name === fieldName);
441
- if (!field) continue;
442
-
443
- // State home
444
- if (opts.scope || opts.persistence || opts.sync) {
445
- field.state_home = {
446
- scope: (opts.scope as IRStateHome['scope']) || 'instance',
447
- persistence: (opts.persistence as IRStateHome['persistence']) || 'durable',
448
- sync: (opts.sync as IRStateHome['sync']) || 'none',
449
- };
450
- }
451
-
452
- // Computed fields
453
- if (opts.computed && typeof opts.computed === 'string') {
454
- field.computed = opts.computed;
455
- }
456
- if (opts.computed_deps && Array.isArray(opts.computed_deps)) {
457
- field.computed_deps = opts.computed_deps.map(String);
458
- }
459
-
460
- // Field-level ACL
461
- if (opts.visible_in_states && Array.isArray(opts.visible_in_states)) {
462
- field.visible_in_states = opts.visible_in_states.map(String);
463
- }
464
- if (opts.editable_in_states && Array.isArray(opts.editable_in_states)) {
465
- field.editable_in_states = opts.editable_in_states.map(String);
466
- }
467
- if (opts.visible_to_roles && Array.isArray(opts.visible_to_roles)) {
468
- field.visible_to_roles = opts.visible_to_roles.map(String);
469
- }
470
- if (opts.editable_by_roles && Array.isArray(opts.editable_by_roles)) {
471
- field.editable_by_roles = opts.editable_by_roles.map(String);
472
- }
473
- if (opts.visible_when && typeof opts.visible_when === 'string') {
474
- field.visible_when = opts.visible_when;
475
- }
476
- if (opts.editable_when && typeof opts.editable_when === 'string') {
477
- field.editable_when = opts.editable_when;
478
- }
479
-
480
- // Validation enrichment
481
- if (opts.validation && typeof opts.validation === 'object') {
482
- const val = opts.validation as Record<string, unknown>;
483
- const validation: IRFieldValidation = field.validation || {};
484
- if (val.min !== undefined) validation.min = Number(val.min);
485
- if (val.max !== undefined) validation.max = Number(val.max);
486
- if (val.minLength !== undefined) validation.minLength = Number(val.minLength);
487
- if (val.maxLength !== undefined) validation.maxLength = Number(val.maxLength);
488
- if (val.options && Array.isArray(val.options)) {
489
- validation.options = val.options.map(String);
490
- }
491
- if (val.rules && Array.isArray(val.rules)) {
492
- validation.rules = val.rules.map((r: any) => ({
493
- expression: String(r.expression || ''),
494
- message: String(r.message || ''),
495
- severity: r.severity === 'warning' ? 'warning' : 'error',
496
- }));
497
- }
498
- field.validation = validation;
499
- }
500
- }
501
- }
502
-
503
- // =============================================================================
504
- // Utility: Extract JS object literal to plain object
505
- // =============================================================================
506
-
507
- /**
508
- * Converts an AST ObjectExpression to a plain JavaScript object.
509
- * Handles string, number, boolean, null, arrays, and nested objects.
510
- */
511
- function extractObjectLiteral(node: t.ObjectExpression): Record<string, unknown> {
512
- const obj: Record<string, unknown> = {};
513
-
514
- for (const prop of node.properties) {
515
- if (!t.isObjectProperty(prop)) continue;
516
-
517
- const key = t.isIdentifier(prop.key)
518
- ? prop.key.name
519
- : t.isStringLiteral(prop.key)
520
- ? prop.key.value
521
- : null;
522
- if (!key) continue;
523
-
524
- obj[key] = extractNodeValue(prop.value);
525
- }
526
-
527
- return obj;
528
- }
529
-
530
- /**
531
- * Extracts a value from an AST node into a plain JS value.
532
- */
533
- function extractNodeValue(node: t.Node): unknown {
534
- if (t.isStringLiteral(node)) return node.value;
535
- if (t.isNumericLiteral(node)) return node.value;
536
- if (t.isBooleanLiteral(node)) return node.value;
537
- if (t.isNullLiteral(node)) return null;
538
-
539
- if (t.isArrayExpression(node)) {
540
- return node.elements.map((el) => {
541
- if (!el) return null;
542
- if (t.isSpreadElement(el)) return '[Spread]';
543
- return extractNodeValue(el);
544
- });
545
- }
546
-
547
- if (t.isObjectExpression(node)) {
548
- return extractObjectLiteral(node);
549
- }
550
-
551
- if (t.isTemplateLiteral(node)) {
552
- return node.quasis.map((q) => q.value.raw).join('${}');
553
- }
554
-
555
- if (t.isIdentifier(node)) {
556
- // For bare identifiers like `true` treated as identifier in some contexts
557
- if (node.name === 'undefined') return undefined;
558
- return node.name;
559
- }
560
-
561
- if (t.isConditionalExpression(node)) {
562
- return `(${extractNodeValue(node.test)} ? ${extractNodeValue(node.consequent)} : ${extractNodeValue(node.alternate)})`;
563
- }
564
- if (t.isBinaryExpression(node)) {
565
- return `(${extractNodeValue(node.left)} ${node.operator} ${extractNodeValue(node.right)})`;
566
- }
567
- if (t.isLogicalExpression(node)) {
568
- return `(${extractNodeValue(node.left)} ${node.operator} ${extractNodeValue(node.right)})`;
569
- }
570
- if (t.isMemberExpression(node)) {
571
- const obj = t.isIdentifier(node.object) ? node.object.name : '[object]';
572
- const prop = t.isIdentifier(node.property) ? node.property.name : '[property]';
573
- return `${obj}.${prop}`;
574
- }
575
- if (t.isTSAsExpression(node)) return extractNodeValue(node.expression);
576
- if (t.isTSNonNullExpression(node)) return extractNodeValue(node.expression);
577
-
578
- return '[Expression]';
579
- }
580
-
581
- // =============================================================================
582
- // Main Extraction Entry Point
583
- // =============================================================================
584
-
585
- /**
586
- * Detects whether a file is a model file.
587
- * Criteria: file path includes /models/ OR exports an interface + transitions
588
- * OR has an `export default defineModel(...)` call.
589
- */
590
- export function isModelFile(path: NodePath<t.Program>, filename: string | undefined): boolean {
591
- // Path-based detection
592
- if (filename && /\/models\//.test(filename)) return true;
593
-
594
- let hasInterface = false;
595
- let hasTransitions = false;
596
- let hasDefineModel = false;
597
-
598
- for (const node of path.node.body) {
599
- // Check for defineModel() in export default
600
- if (t.isExportDefaultDeclaration(node)) {
601
- const decl = node.declaration;
602
- if (t.isCallExpression(decl) && t.isIdentifier(decl.callee) && decl.callee.name === 'defineModel') {
603
- hasDefineModel = true;
604
- }
605
- }
606
- // Duck-typing: check for exported interface + exported transitions
607
- if (t.isExportNamedDeclaration(node)) {
608
- if (t.isTSInterfaceDeclaration(node.declaration)) {
609
- hasInterface = true;
610
- }
611
- if (t.isVariableDeclaration(node.declaration)) {
612
- for (const decl of node.declaration.declarations) {
613
- if (t.isIdentifier(decl.id) && decl.id.name === 'transitions') {
614
- hasTransitions = true;
615
- }
616
- }
617
- }
618
- }
619
- }
620
-
621
- return hasDefineModel || (hasInterface && hasTransitions);
622
- }
623
-
624
- // =============================================================================
625
- // defineModel() extraction
626
- // =============================================================================
627
-
628
- /**
629
- * Maps a defineModel field type string back to an IR field type.
630
- */
631
- function modelTypeToIRType(modelType: string): IRWorkflowFieldType {
632
- switch (modelType) {
633
- case 'string': return 'text';
634
- case 'number': return 'number';
635
- case 'boolean': return 'boolean';
636
- case 'date': return 'date';
637
- case 'array': return 'multi_select';
638
- case 'json': return 'json';
639
- case 'file': return 'file';
640
- case 'relation': return 'relation';
641
- default: return modelType as IRWorkflowFieldType;
642
- }
643
- }
644
-
645
- /**
646
- * Maps a defineModel state type ('initial'/'final') to IR state type.
647
- */
648
- function modelStateTypeToIR(type: string | undefined): 'START' | 'END' | 'REGULAR' {
649
- if (type === 'initial') return 'START';
650
- if (type === 'final') return 'END';
651
- return 'REGULAR';
652
- }
653
-
654
- /**
655
- * Extracts a defineModel({ ... }) call and populates compiler state.
656
- * Returns true if a defineModel call was found and extracted.
657
- */
658
- function extractDefineModelCall(
659
- programPath: NodePath<t.Program>,
660
- compilerState: CompilerState,
661
- actionCounter: { value: number },
662
- ): boolean {
663
- for (const node of programPath.node.body) {
664
- if (!t.isExportDefaultDeclaration(node)) continue;
665
- const decl = node.declaration;
666
- if (!t.isCallExpression(decl)) continue;
667
- if (!t.isIdentifier(decl.callee) || decl.callee.name !== 'defineModel') continue;
668
- if (decl.arguments.length === 0 || !t.isObjectExpression(decl.arguments[0])) continue;
669
-
670
- const config = extractObjectLiteral(decl.arguments[0]);
671
-
672
- // Metadata from top-level properties
673
- if (config.slug) compilerState.metadata.slug = String(config.slug);
674
- if (config.version) compilerState.metadata.version = String(config.version);
675
- if (config.category) {
676
- if (Array.isArray(config.category)) {
677
- compilerState.metadata.category = String(config.category[0]);
678
- compilerState.metadata.categoryArray = config.category;
679
- } else {
680
- compilerState.metadata.category = String(config.category);
681
- }
682
- }
683
- if (config.description) compilerState.metadata.description = String(config.description);
684
-
685
- // Fields
686
- if (config.fields && typeof config.fields === 'object' && !Array.isArray(config.fields)) {
687
- const fieldsObj = config.fields as Record<string, Record<string, unknown>>;
688
- for (const [name, fieldConfig] of Object.entries(fieldsObj)) {
689
- const irType = modelTypeToIRType(String(fieldConfig.type || 'text'));
690
- const field: IRFieldDefinition = {
691
- name,
692
- type: irType,
693
- required: fieldConfig.required === true,
694
- default_value: fieldConfig.default !== undefined ? fieldConfig.default : extractDefaultValue(irType),
695
- };
696
- // Enum → validation.options
697
- if (fieldConfig.enum && Array.isArray(fieldConfig.enum)) {
698
- (field as any).validation = { options: fieldConfig.enum.map(String) };
699
- }
700
- compilerState.fields.push(field);
701
- }
702
- }
703
-
704
- // States
705
- if (config.states && typeof config.states === 'object' && !Array.isArray(config.states)) {
706
- const statesObj = config.states as Record<string, Record<string, unknown>>;
707
- for (const [name, stateConfig] of Object.entries(statesObj)) {
708
- const stateType = modelStateTypeToIR(stateConfig.type as string | undefined);
709
- if (!compilerState.states.has(name)) {
710
- compilerState.states.set(name, {
711
- name,
712
- type: stateType,
713
- description: stateConfig.description as string | undefined,
714
- on_enter: [],
715
- during: [],
716
- on_exit: [],
717
- });
718
- } else {
719
- // Explicit states are authoritative
720
- compilerState.states.get(name)!.type = stateType;
721
- }
722
- }
723
- }
724
-
725
- // Transitions
726
- if (config.transitions && typeof config.transitions === 'object' && !Array.isArray(config.transitions)) {
727
- const transObj = config.transitions as Record<string, Record<string, unknown>>;
728
- for (const [name, transConfig] of Object.entries(transObj)) {
729
- let from: string[] = [];
730
- if (typeof transConfig.from === 'string') {
731
- from = [transConfig.from];
732
- } else if (Array.isArray(transConfig.from)) {
733
- from = transConfig.from.map(String);
734
- }
735
- const to = String(transConfig.to || '');
736
-
737
- // Ensure referenced states exist
738
- for (const f of from) {
739
- if (!compilerState.states.has(f)) {
740
- compilerState.states.set(f, {
741
- name: f, type: 'REGULAR', on_enter: [], during: [], on_exit: [],
742
- });
743
- }
744
- }
745
- if (to && !compilerState.states.has(to)) {
746
- compilerState.states.set(to, {
747
- name: to, type: 'REGULAR', on_enter: [], during: [], on_exit: [],
748
- });
749
- }
750
-
751
- const conditions: IRConditionDefinition[] = [];
752
- if (transConfig.guard) {
753
- conditions.push(parseGuardExpression(String(transConfig.guard)));
754
- }
755
-
756
- compilerState.transitions.push({
757
- name,
758
- from,
759
- to,
760
- description: transConfig.description as string | undefined,
761
- conditions: conditions.length > 0 ? conditions : undefined,
762
- actions: [],
763
- roles: transConfig.roles as string[] | undefined,
764
- auto: transConfig.auto as boolean | undefined,
765
- required_fields: transConfig.required_fields as string[] | undefined,
766
- });
767
- }
768
- }
769
-
770
- // Roles (with descriptions and permissions)
771
- if (config.roles && typeof config.roles === 'object' && !Array.isArray(config.roles)) {
772
- const rolesObj = config.roles as Record<string, Record<string, unknown>>;
773
- if (!compilerState.metadata.roles) compilerState.metadata.roles = {};
774
- for (const [roleName, roleConfig] of Object.entries(rolesObj)) {
775
- (compilerState.metadata.roles as Record<string, unknown>)[roleName] = {
776
- description: roleConfig.description,
777
- permissions: roleConfig.permissions,
778
- };
779
- }
780
- }
781
-
782
- // Metadata
783
- if (config.metadata && typeof config.metadata === 'object') {
784
- compilerState.metadata.modelMetadata = config.metadata;
785
- }
786
-
787
- return true;
788
- }
789
-
790
- return false;
791
- }
792
-
793
- /**
794
- * Extracts a complete workflow from a model file.
795
- * Called from visitor.ts when a model file is detected.
796
- *
797
- * Supports two formats:
798
- * 1. defineModel({ slug, fields, states, transitions }) — preferred
799
- * 2. Legacy: export interface + export const states/transitions
800
- */
801
- export function extractModelFile(path: NodePath<t.Program>, state: any): void {
802
- const compilerState = state as CompilerState;
803
- if (!compilerState.actionCounter) compilerState.actionCounter = 0;
804
- const actionCounter = { value: compilerState.actionCounter };
805
-
806
- // Try defineModel() format first — if found, also extract companion interface
807
- // for field metadata (required, types) but defineModel is authoritative for
808
- // slug/version/category/states/transitions.
809
- const foundDefineModel = extractDefineModelCall(path, compilerState, actionCounter);
810
-
811
- if (foundDefineModel) {
812
- // Also extract companion interface fields for richer type metadata
813
- // (e.g. required status from TS syntax: `name: string` vs `name?: string`)
814
- for (const node of path.node.body) {
815
- if (t.isExportNamedDeclaration(node) && t.isTSInterfaceDeclaration(node.declaration)) {
816
- const interfaceFields = extractFieldsFromInterface(node.declaration);
817
- // Merge required + type from interface into existing defineModel fields
818
- for (const iField of interfaceFields) {
819
- const existing = compilerState.fields.find(f => f.name === iField.name);
820
- if (existing) {
821
- if (iField.required) existing.required = true;
822
- }
823
- }
824
- // Set metadata name from interface name
825
- if (!compilerState.metadata.name) {
826
- compilerState.metadata.name = node.declaration.id.name;
827
- }
828
- }
829
- }
830
- compilerState.actionCounter = actionCounter.value;
831
- return;
832
- }
833
-
834
- // Legacy format: export interface + export const states/transitions
835
- let interfaceName = '';
836
-
837
- for (const node of path.node.body) {
838
- if (!t.isExportNamedDeclaration(node)) continue;
839
- const declaration = node.declaration;
840
-
841
- // Interface → fields
842
- if (t.isTSInterfaceDeclaration(declaration)) {
843
- interfaceName = declaration.id.name;
844
- const fields = extractFieldsFromInterface(declaration);
845
- compilerState.fields.push(...fields);
846
-
847
- // Infer states from union-typed fields (first union field found)
848
- for (const field of fields) {
849
- if (field.validation?.options && field.validation.options.length > 0) {
850
- // Create states for each option
851
- for (const option of field.validation.options) {
852
- if (!compilerState.states.has(option)) {
853
- compilerState.states.set(option, {
854
- name: option,
855
- type: 'REGULAR',
856
- on_enter: [],
857
- during: [],
858
- on_exit: [],
859
- });
860
- }
861
- }
862
- // First option is the START state
863
- const firstState = compilerState.states.get(field.validation.options[0]);
864
- if (firstState) firstState.type = 'START';
865
- break; // Only use first union field for state inference
866
- }
867
- }
868
-
869
- // Set metadata name from interface name
870
- if (!compilerState.metadata.name) {
871
- compilerState.metadata.name = interfaceName;
872
- }
873
- }
874
-
875
- // Variable declarations
876
- if (t.isVariableDeclaration(declaration)) {
877
- for (const decl of declaration.declarations) {
878
- if (!t.isIdentifier(decl.id) || !decl.init) continue;
879
- const varName = decl.id.name;
880
-
881
- // transitions = { ... }
882
- if (varName === 'transitions' && t.isObjectExpression(decl.init)) {
883
- const transitions = extractTransitionsFromObject(decl.init, actionCounter);
884
- compilerState.transitions.push(...transitions);
885
-
886
- // Ensure all referenced states exist
887
- for (const trans of transitions) {
888
- for (const fromState of trans.from) {
889
- if (!compilerState.states.has(fromState)) {
890
- compilerState.states.set(fromState, {
891
- name: fromState,
892
- type: 'REGULAR',
893
- on_enter: [],
894
- during: [],
895
- on_exit: [],
896
- });
897
- }
898
- }
899
- if (trans.to && !compilerState.states.has(trans.to)) {
900
- compilerState.states.set(trans.to, {
901
- name: trans.to,
902
- type: 'REGULAR',
903
- on_enter: [],
904
- during: [],
905
- on_exit: [],
906
- });
907
- }
908
- }
909
- }
910
-
911
- // states = [{ name: 'draft', type: 'START' as const }, ...] as const
912
- // Parse the explicit states array used in decompiler-generated model files
913
- if (varName === 'states') {
914
- const arrExpr = t.isTSAsExpression(decl.init) ? decl.init.expression : decl.init;
915
- if (t.isArrayExpression(arrExpr)) {
916
- for (const el of arrExpr.elements) {
917
- if (!t.isObjectExpression(el)) continue;
918
- let stateName = '';
919
- let stateType = 'REGULAR';
920
- let stateDesc = '';
921
- for (const prop of el.properties) {
922
- if (!t.isObjectProperty(prop) || !t.isIdentifier(prop.key)) continue;
923
- if (prop.key.name === 'name' && t.isStringLiteral(prop.value)) {
924
- stateName = prop.value.value;
925
- } else if (prop.key.name === 'type') {
926
- // type: 'START' as const → unwrap TSAsExpression
927
- const val = t.isTSAsExpression(prop.value) ? prop.value.expression : prop.value;
928
- if (t.isStringLiteral(val)) stateType = val.value;
929
- } else if (prop.key.name === 'description' && t.isStringLiteral(prop.value)) {
930
- stateDesc = prop.value.value;
931
- }
932
- }
933
- if (stateName && !compilerState.states.has(stateName)) {
934
- compilerState.states.set(stateName, {
935
- name: stateName,
936
- type: stateType as 'START' | 'END' | 'REGULAR',
937
- description: stateDesc || undefined,
938
- on_enter: [],
939
- during: [],
940
- on_exit: [],
941
- });
942
- } else if (stateName) {
943
- // Explicit states array is authoritative — always override type
944
- // (even downgrading from inferred START to declared REGULAR).
945
- compilerState.states.get(stateName)!.type = stateType as 'START' | 'END' | 'REGULAR';
946
- }
947
- }
948
- }
949
- }
950
-
951
- // endStates = ['deleted']
952
- if (varName === 'endStates' && t.isArrayExpression(decl.init)) {
953
- for (const el of decl.init.elements) {
954
- if (t.isStringLiteral(el)) {
955
- if (!compilerState.states.has(el.value)) {
956
- compilerState.states.set(el.value, {
957
- name: el.value,
958
- type: 'END',
959
- on_enter: [],
960
- during: [],
961
- on_exit: [],
962
- });
963
- } else {
964
- compilerState.states.get(el.value)!.type = 'END';
965
- }
966
- }
967
- }
968
- }
969
-
970
- // cancelledStates = ['cancelled']
971
- if (varName === 'cancelledStates' && t.isArrayExpression(decl.init)) {
972
- for (const el of decl.init.elements) {
973
- if (t.isStringLiteral(el)) {
974
- if (!compilerState.states.has(el.value)) {
975
- compilerState.states.set(el.value, {
976
- name: el.value,
977
- type: 'CANCELLED',
978
- on_enter: [],
979
- during: [],
980
- on_exit: [],
981
- });
982
- } else {
983
- compilerState.states.get(el.value)!.type = 'CANCELLED';
984
- }
985
- }
986
- }
987
- }
988
-
989
- // hooks = { ... }
990
- if (varName === 'hooks' && t.isObjectExpression(decl.init)) {
991
- extractHooksFromObject(decl.init, compilerState.states, actionCounter);
992
- }
993
-
994
- // runtime = 'backend'
995
- if (varName === 'runtime' && t.isStringLiteral(decl.init)) {
996
- compilerState.metadata.runtime = decl.init.value as RuntimeProfile;
997
- }
998
-
999
- // fieldOptions = { ... }
1000
- if (varName === 'fieldOptions' && t.isObjectExpression(decl.init)) {
1001
- applyFieldOptions(compilerState.fields, decl.init);
1002
- }
1003
- }
1004
- }
1005
- }
1006
-
1007
- compilerState.actionCounter = actionCounter.value;
1008
-
1009
- // For model files, derive slug from interface name if slug was auto-derived from filename
1010
- // (JSDoc @workflow slug takes precedence and should never be overridden)
1011
- if (interfaceName && (compilerState.metadata as any).__slugAutoFallback) {
1012
- compilerState.metadata.slug = interfaceName
1013
- .replace(/([A-Z])/g, '-$1')
1014
- .toLowerCase()
1015
- .replace(/^-/, '');
1016
- delete (compilerState.metadata as any).__slugAutoFallback;
1017
- }
1018
- }