@mmapp/react-compiler 0.1.0-alpha.1

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 (314) hide show
  1. package/README.md +107 -0
  2. package/compile-blueprint-chat.mjs +99 -0
  3. package/compile-blueprint-glass-console.mjs +98 -0
  4. package/compile-chat-defs.mjs +92 -0
  5. package/dist/babel/index.d.mts +3 -0
  6. package/dist/babel/index.d.ts +3 -0
  7. package/dist/babel/index.js +4851 -0
  8. package/dist/babel/index.mjs +7 -0
  9. package/dist/chunk-26U577GB.mjs +3465 -0
  10. package/dist/chunk-2FBDFAX6.mjs +2362 -0
  11. package/dist/chunk-2L4QSMXG.mjs +175 -0
  12. package/dist/chunk-2REDFOER.mjs +931 -0
  13. package/dist/chunk-46YKSHQR.mjs +175 -0
  14. package/dist/chunk-4XHK6FWL.mjs +2058 -0
  15. package/dist/chunk-5M7DKKBC.mjs +215 -0
  16. package/dist/chunk-5VNJ7C6N.mjs +154 -0
  17. package/dist/chunk-6CQOAAMV.mjs +1803 -0
  18. package/dist/chunk-6SEVAAVT.mjs +3516 -0
  19. package/dist/chunk-6YLR5ZDA.mjs +2829 -0
  20. package/dist/chunk-AOGY2GK6.mjs +3292 -0
  21. package/dist/chunk-AXXUXRNA.mjs +1434 -0
  22. package/dist/chunk-CHLVKMQW.mjs +175 -0
  23. package/dist/chunk-CKGOZAB7.mjs +939 -0
  24. package/dist/chunk-D34RAZUX.mjs +2223 -0
  25. package/dist/chunk-EQGA6A6D.mjs +121 -0
  26. package/dist/chunk-EY2CSXYA.mjs +822 -0
  27. package/dist/chunk-FIQ65CDR.mjs +925 -0
  28. package/dist/chunk-FOZXJFAR.mjs +186 -0
  29. package/dist/chunk-FX6URXWN.mjs +186 -0
  30. package/dist/chunk-G7SMOWOL.mjs +828 -0
  31. package/dist/chunk-GGB4G5YY.mjs +175 -0
  32. package/dist/chunk-HLRGCCIL.mjs +4839 -0
  33. package/dist/chunk-HOIUP6IF.mjs +690 -0
  34. package/dist/chunk-I3AU7GRD.mjs +120 -0
  35. package/dist/chunk-ILFGMUVD.mjs +1933 -0
  36. package/dist/chunk-IPTX5MJU.mjs +3223 -0
  37. package/dist/chunk-ITGUSH2Z.mjs +2783 -0
  38. package/dist/chunk-IXHBCAMF.mjs +3306 -0
  39. package/dist/chunk-J7TWJ3TM.mjs +2784 -0
  40. package/dist/chunk-JDPLDGVF.mjs +4810 -0
  41. package/dist/chunk-K53XP2DL.mjs +148 -0
  42. package/dist/chunk-K5HX2SVL.mjs +1902 -0
  43. package/dist/chunk-KFGYOOVS.mjs +214 -0
  44. package/dist/chunk-KFVVOS5N.mjs +925 -0
  45. package/dist/chunk-L2OZ4CDV.mjs +113 -0
  46. package/dist/chunk-MIZV3TAN.mjs +3293 -0
  47. package/dist/chunk-NKKLQE5V.mjs +148 -0
  48. package/dist/chunk-NOW23XFZ.mjs +186 -0
  49. package/dist/chunk-NRXQKQ74.mjs +148 -0
  50. package/dist/chunk-OWI6XWCD.mjs +3375 -0
  51. package/dist/chunk-PRUMNNDI.mjs +3192 -0
  52. package/dist/chunk-QTBD5B3F.mjs +148 -0
  53. package/dist/chunk-SKSDPPNT.mjs +3788 -0
  54. package/dist/chunk-SP2YUS33.mjs +186 -0
  55. package/dist/chunk-SU4E6E7B.mjs +3153 -0
  56. package/dist/chunk-SYUUKW5A.mjs +3379 -0
  57. package/dist/chunk-UL2XZEMA.mjs +3128 -0
  58. package/dist/chunk-XMWUHQVV.mjs +939 -0
  59. package/dist/chunk-XZNEDRGN.mjs +3876 -0
  60. package/dist/chunk-Y6FXYEAI.mjs +10 -0
  61. package/dist/chunk-YFS6JMYO.mjs +3342 -0
  62. package/dist/chunk-Z6AIQ4KL.mjs +113 -0
  63. package/dist/cli/index.d.mts +1 -0
  64. package/dist/cli/index.d.ts +1 -0
  65. package/dist/cli/index.js +11585 -0
  66. package/dist/cli/index.mjs +701 -0
  67. package/dist/codemod/cli.d.mts +1 -0
  68. package/dist/codemod/cli.d.ts +1 -0
  69. package/dist/codemod/cli.js +1104 -0
  70. package/dist/codemod/cli.mjs +157 -0
  71. package/dist/codemod/index.d.mts +148 -0
  72. package/dist/codemod/index.d.ts +148 -0
  73. package/dist/codemod/index.js +981 -0
  74. package/dist/codemod/index.mjs +25 -0
  75. package/dist/dev-server-Bs_sz2DG.d.mts +111 -0
  76. package/dist/dev-server-Bs_sz2DG.d.ts +111 -0
  77. package/dist/dev-server-CjoufJ-u.d.mts +109 -0
  78. package/dist/dev-server-CjoufJ-u.d.ts +109 -0
  79. package/dist/dev-server.d.mts +3 -0
  80. package/dist/dev-server.d.ts +3 -0
  81. package/dist/dev-server.js +7603 -0
  82. package/dist/dev-server.mjs +11 -0
  83. package/dist/envelope-DD7v0v6E.d.mts +265 -0
  84. package/dist/envelope-DD7v0v6E.d.ts +265 -0
  85. package/dist/envelope-vCVjrHlo.d.mts +265 -0
  86. package/dist/envelope-vCVjrHlo.d.ts +265 -0
  87. package/dist/envelope.d.mts +2 -0
  88. package/dist/envelope.d.ts +2 -0
  89. package/dist/envelope.js +5184 -0
  90. package/dist/envelope.mjs +9 -0
  91. package/dist/index-B5gSgvnd.d.mts +44 -0
  92. package/dist/index-B5gSgvnd.d.ts +44 -0
  93. package/dist/index-Bs0MnR54.d.mts +103 -0
  94. package/dist/index-Bs0MnR54.d.ts +103 -0
  95. package/dist/index-DR0nNc_f.d.mts +101 -0
  96. package/dist/index-DR0nNc_f.d.ts +101 -0
  97. package/dist/index-revho_gS.d.mts +104 -0
  98. package/dist/index-revho_gS.d.ts +104 -0
  99. package/dist/index.d.mts +1099 -0
  100. package/dist/index.d.ts +1099 -0
  101. package/dist/index.js +10162 -0
  102. package/dist/index.mjs +372 -0
  103. package/dist/init-IXEE2RCF.mjs +340 -0
  104. package/dist/project-compiler-EGJUTAJU.mjs +10 -0
  105. package/dist/project-compiler-VFR6CSDX.mjs +10 -0
  106. package/dist/project-decompiler-5GY2KSG4.mjs +7 -0
  107. package/dist/pull-A2QUHW4K.mjs +109 -0
  108. package/dist/pull-JBEQWVPE.mjs +109 -0
  109. package/dist/testing/index.d.mts +211 -0
  110. package/dist/testing/index.d.ts +211 -0
  111. package/dist/testing/index.js +5106 -0
  112. package/dist/testing/index.mjs +247 -0
  113. package/dist/vite/index.d.mts +59 -0
  114. package/dist/vite/index.d.ts +59 -0
  115. package/dist/vite/index.js +5023 -0
  116. package/dist/vite/index.mjs +8 -0
  117. package/examples/README.md +72 -0
  118. package/examples/authentication/main.workflow.tsx +139 -0
  119. package/examples/authentication/mm.config.ts +22 -0
  120. package/examples/authentication/models/auth.ts +45 -0
  121. package/examples/authentication/pages/LoginPage.tsx +79 -0
  122. package/examples/authentication/pages/SignupPage.tsx +87 -0
  123. package/examples/counter.workflow.tsx +65 -0
  124. package/examples/dashboard.workflow.tsx +419 -0
  125. package/examples/invoice-approval/actions/invoice.server.ts +72 -0
  126. package/examples/invoice-approval/main.workflow.tsx +168 -0
  127. package/examples/invoice-approval/mm.config.ts +18 -0
  128. package/examples/invoice-approval/models/invoice.ts +46 -0
  129. package/examples/invoice-approval/pages/InvoiceDetailPage.tsx +175 -0
  130. package/examples/invoice-approval/pages/InvoiceFormPage.tsx +198 -0
  131. package/examples/invoice-approval/pages/InvoiceListPage.tsx +141 -0
  132. package/examples/todo-app.workflow.tsx +131 -0
  133. package/examples/uber-app/actions/matching.server.ts +177 -0
  134. package/examples/uber-app/actions/notifications.server.ts +176 -0
  135. package/examples/uber-app/actions/payments.server.ts +184 -0
  136. package/examples/uber-app/actions/pricing.server.ts +176 -0
  137. package/examples/uber-app/app/admin/analytics.tsx +102 -0
  138. package/examples/uber-app/app/admin/fleet.tsx +102 -0
  139. package/examples/uber-app/app/admin/surge-pricing.tsx +95 -0
  140. package/examples/uber-app/app/driver/dashboard.tsx +87 -0
  141. package/examples/uber-app/app/driver/earnings.tsx +101 -0
  142. package/examples/uber-app/app/driver/navigation.tsx +94 -0
  143. package/examples/uber-app/app/driver/ride-acceptance.tsx +103 -0
  144. package/examples/uber-app/app/rider/home.tsx +109 -0
  145. package/examples/uber-app/app/rider/payment-methods.tsx +134 -0
  146. package/examples/uber-app/app/rider/ride-history.tsx +90 -0
  147. package/examples/uber-app/app/rider/ride-tracking.tsx +108 -0
  148. package/examples/uber-app/components/DriverCard.tsx +176 -0
  149. package/examples/uber-app/components/MapView.tsx +216 -0
  150. package/examples/uber-app/components/RatingStars.tsx +227 -0
  151. package/examples/uber-app/components/RideCard.tsx +167 -0
  152. package/examples/uber-app/mm.config.ts +30 -0
  153. package/examples/uber-app/models/location.model.ts +70 -0
  154. package/examples/uber-app/models/payment.model.ts +87 -0
  155. package/examples/uber-app/models/rating.model.ts +54 -0
  156. package/examples/uber-app/models/ride.model.ts +118 -0
  157. package/examples/uber-app/models/user.model.ts +66 -0
  158. package/examples/uber-app/models/vehicle.model.ts +63 -0
  159. package/examples/uber-app/tests/payment.test.tsx +129 -0
  160. package/examples/uber-app/tests/ride-flow.test.tsx +123 -0
  161. package/examples/uber-app/workflows/dispute-resolution.workflow.tsx +205 -0
  162. package/examples/uber-app/workflows/driver-onboarding.workflow.tsx +227 -0
  163. package/examples/uber-app/workflows/payment-processing.workflow.tsx +223 -0
  164. package/examples/uber-app/workflows/ride-request.workflow.tsx +194 -0
  165. package/package.json +77 -0
  166. package/package.json.backup +86 -0
  167. package/scripts/decompile.ts +226 -0
  168. package/scripts/seed-auth.ts +267 -0
  169. package/scripts/seed-uber.ts +248 -0
  170. package/scripts/validate-uber.ts +119 -0
  171. package/seed-blueprint-chat.mjs +444 -0
  172. package/seed-blueprint-glass-console.mjs +445 -0
  173. package/seed-compiled.mjs +318 -0
  174. package/src/RoundTripValidator.ts +400 -0
  175. package/src/__tests__/atom-rendering-coverage.test.ts +680 -0
  176. package/src/__tests__/auth-module-compilation.test.ts +247 -0
  177. package/src/__tests__/auth-template-compilation.test.ts +589 -0
  178. package/src/__tests__/change-extractor.test.ts +142 -0
  179. package/src/__tests__/cli-pull.test.ts +73 -0
  180. package/src/__tests__/cli-test.test.ts +72 -0
  181. package/src/__tests__/component-extractor.test.ts +331 -0
  182. package/src/__tests__/context-extractor.test.ts +145 -0
  183. package/src/__tests__/decompiler.test.ts +718 -0
  184. package/src/__tests__/define-blueprint.test.ts +133 -0
  185. package/src/__tests__/definition-validator.test.ts +519 -0
  186. package/src/__tests__/during-extractor.test.ts +152 -0
  187. package/src/__tests__/effect-extractor.test.ts +107 -0
  188. package/src/__tests__/event-emission.test.ts +127 -0
  189. package/src/__tests__/examples.test.ts +236 -0
  190. package/src/__tests__/full-blueprint-coverage.test.ts +1221 -0
  191. package/src/__tests__/golden-suite.test.ts +403 -0
  192. package/src/__tests__/grammar-island-extractor.test.ts +289 -0
  193. package/src/__tests__/instance-key.test.ts +82 -0
  194. package/src/__tests__/ir-migration.test.ts +255 -0
  195. package/src/__tests__/lock-file.test.ts +117 -0
  196. package/src/__tests__/model-extractor.test.ts +195 -0
  197. package/src/__tests__/model-field-acl.test.ts +237 -0
  198. package/src/__tests__/model-hooks.test.ts +130 -0
  199. package/src/__tests__/model-ref-resolution.test.ts +268 -0
  200. package/src/__tests__/model-roundtrip.test.ts +502 -0
  201. package/src/__tests__/model-runtime.test.ts +112 -0
  202. package/src/__tests__/model-transitions.test.ts +183 -0
  203. package/src/__tests__/nrt-action-trace.test.ts +391 -0
  204. package/src/__tests__/pipeline-hardening.test.ts +413 -0
  205. package/src/__tests__/project-compiler.test.ts +546 -0
  206. package/src/__tests__/project-decompiler.test.ts +343 -0
  207. package/src/__tests__/query-compilation.test.ts +145 -0
  208. package/src/__tests__/round-trip/PLAN.md +158 -0
  209. package/src/__tests__/round-trip/README.md +52 -0
  210. package/src/__tests__/round-trip/RESULTS.md +86 -0
  211. package/src/__tests__/round-trip/fixtures/data-heavy/main.workflow.tsx +55 -0
  212. package/src/__tests__/round-trip/fixtures/data-heavy/mm.config.ts +11 -0
  213. package/src/__tests__/round-trip/fixtures/data-heavy/models/contact.ts +54 -0
  214. package/src/__tests__/round-trip/fixtures/full-workflow/main.workflow.tsx +79 -0
  215. package/src/__tests__/round-trip/fixtures/full-workflow/mm.config.ts +12 -0
  216. package/src/__tests__/round-trip/fixtures/full-workflow/models/order.ts +50 -0
  217. package/src/__tests__/round-trip/fixtures/simple-crud/main.workflow.tsx +25 -0
  218. package/src/__tests__/round-trip/fixtures/simple-crud/mm.config.ts +11 -0
  219. package/src/__tests__/round-trip/fixtures/simple-crud/models/task.ts +32 -0
  220. package/src/__tests__/round-trip/fixtures/view-heavy/main.workflow.tsx +79 -0
  221. package/src/__tests__/round-trip/fixtures/view-heavy/mm.config.ts +10 -0
  222. package/src/__tests__/round-trip/round-trip.test.ts +2598 -0
  223. package/src/__tests__/round-trip-ir.test.ts +300 -0
  224. package/src/__tests__/round-trip.test.ts +1212 -0
  225. package/src/__tests__/route-merging.test.ts +372 -0
  226. package/src/__tests__/router-composition.test.ts +489 -0
  227. package/src/__tests__/router-extractor.test.ts +176 -0
  228. package/src/__tests__/server-action-extractor.test.ts +128 -0
  229. package/src/__tests__/smart-type-inference.test.ts +365 -0
  230. package/src/__tests__/source-envelope.test.ts +284 -0
  231. package/src/__tests__/source-fidelity.test.ts +516 -0
  232. package/src/__tests__/state-extractor.test.ts +115 -0
  233. package/src/__tests__/strict-mode.test.ts +227 -0
  234. package/src/__tests__/transition-effect-extractor.test.ts +119 -0
  235. package/src/__tests__/transition-extractor.test.ts +68 -0
  236. package/src/__tests__/ts-to-expression.test.ts +462 -0
  237. package/src/__tests__/type-generator.test.ts +201 -0
  238. package/src/__tests__/uber-validation.test.ts +502 -0
  239. package/src/action-compiler.ts +361 -0
  240. package/src/babel/emitters/experience-transform.ts +199 -0
  241. package/src/babel/emitters/ir-to-tsx-emitter.ts +110 -0
  242. package/src/babel/emitters/pure-form-emitter.ts +1023 -0
  243. package/src/babel/emitters/runtime-glue-emitter.ts +39 -0
  244. package/src/babel/extractors/change-extractor.ts +199 -0
  245. package/src/babel/extractors/component-extractor.ts +907 -0
  246. package/src/babel/extractors/computed-extractor.ts +262 -0
  247. package/src/babel/extractors/context-extractor.ts +277 -0
  248. package/src/babel/extractors/during-extractor.ts +295 -0
  249. package/src/babel/extractors/effect-extractor.ts +340 -0
  250. package/src/babel/extractors/event-extractor.ts +235 -0
  251. package/src/babel/extractors/grammar-island-extractor.ts +302 -0
  252. package/src/babel/extractors/model-extractor.ts +1018 -0
  253. package/src/babel/extractors/router-extractor.ts +303 -0
  254. package/src/babel/extractors/server-action-extractor.ts +173 -0
  255. package/src/babel/extractors/server-action-hook-extractor.ts +72 -0
  256. package/src/babel/extractors/server-state-extractor.ts +88 -0
  257. package/src/babel/extractors/state-extractor.ts +214 -0
  258. package/src/babel/extractors/transition-effect-extractor.ts +176 -0
  259. package/src/babel/extractors/transition-extractor.ts +143 -0
  260. package/src/babel/index.ts +24 -0
  261. package/src/babel/transpilers/ts-to-expression.ts +674 -0
  262. package/src/babel/visitor.ts +807 -0
  263. package/src/cli/auth.ts +255 -0
  264. package/src/cli/build.ts +288 -0
  265. package/src/cli/deploy.ts +206 -0
  266. package/src/cli/index.ts +328 -0
  267. package/src/cli/init.ts +388 -0
  268. package/src/cli/installer.ts +261 -0
  269. package/src/cli/lock-file.ts +94 -0
  270. package/src/cli/mmrc.ts +22 -0
  271. package/src/cli/pull.ts +172 -0
  272. package/src/cli/registry-client.ts +175 -0
  273. package/src/cli/test.ts +397 -0
  274. package/src/cli/type-generator.ts +243 -0
  275. package/src/codemod/__tests__/forward.test.ts +239 -0
  276. package/src/codemod/__tests__/reverse.test.ts +145 -0
  277. package/src/codemod/__tests__/round-trip.test.ts +137 -0
  278. package/src/codemod/annotation.ts +97 -0
  279. package/src/codemod/classify.ts +197 -0
  280. package/src/codemod/cli.ts +207 -0
  281. package/src/codemod/control-flow.ts +409 -0
  282. package/src/codemod/forward.ts +244 -0
  283. package/src/codemod/import-manager.ts +171 -0
  284. package/src/codemod/index.ts +120 -0
  285. package/src/codemod/reverse.ts +197 -0
  286. package/src/codemod/rules.ts +174 -0
  287. package/src/codemod/state-transform.ts +126 -0
  288. package/src/decompiler/ast-builder.ts +538 -0
  289. package/src/decompiler/config-generator.ts +151 -0
  290. package/src/decompiler/index.ts +315 -0
  291. package/src/decompiler/project-decompiler.ts +1776 -0
  292. package/src/decompiler/project.ts +862 -0
  293. package/src/decompiler/split-strategy.ts +140 -0
  294. package/src/decompiler/state-emitter.ts +1053 -0
  295. package/src/decompiler/sx-emitter.ts +318 -0
  296. package/src/decompiler/workspace-hydrator.ts +189 -0
  297. package/src/dev-server.ts +238 -0
  298. package/src/envelope/fs-tree.ts +217 -0
  299. package/src/envelope/source-envelope.ts +264 -0
  300. package/src/envelope.ts +315 -0
  301. package/src/incremental-compiler.ts +401 -0
  302. package/src/index.ts +99 -0
  303. package/src/model-compiler.ts +277 -0
  304. package/src/project-compiler.ts +1629 -0
  305. package/src/route-extractor.ts +333 -0
  306. package/src/testing/index.ts +32 -0
  307. package/src/testing/snapshot.ts +252 -0
  308. package/src/testing/test-utils.ts +226 -0
  309. package/src/types.ts +68 -0
  310. package/src/vite/index.ts +288 -0
  311. package/test-compile.mjs +142 -0
  312. package/tsconfig.json +25 -0
  313. package/tsup.config.ts +23 -0
  314. package/vitest.config.ts +9 -0
@@ -0,0 +1,1023 @@
1
+ /**
2
+ * Workflow Emitter — assembles extracted pieces into IR, engine-compatible, and canonical outputs.
3
+ *
4
+ * Three output stages:
5
+ * 1. emitIR() → IRWorkflowDefinition (the IR cache)
6
+ * 2. emitWorkflowDefinition() → engine-compatible JSON (state_type, field_type, action_type)
7
+ * 3. emitCanonical() → PureFormWorkflow (canonical tree per 041 protocol)
8
+ * 4. emitCompiledOutput() → { canonical, ir } (combined output)
9
+ *
10
+ * Data flow:
11
+ * CompilerState → compilerStateToWorkflow() → ExtractedWorkflow → emitIR() → IRWorkflowDefinition
12
+ * → emitWorkflowDefinition() → engine-compatible JSON
13
+ * → emitCanonical() → PureFormWorkflow
14
+ *
15
+ * Critical contract: NOTHING extracted may be silently dropped.
16
+ * Every piece of data extracted by the visitor must appear in the output.
17
+ */
18
+
19
+ import type {
20
+ IRWorkflowDefinition,
21
+ IRStateDefinition,
22
+ IRTransitionDefinition,
23
+ IRFieldDefinition,
24
+ IRConditionDefinition,
25
+ IRDuringAction,
26
+ IROnEventSubscription,
27
+ IRGrammarIsland,
28
+ IRActionDefinition,
29
+ IRExperienceNode,
30
+ IRDataSource,
31
+ PureFormWorkflow,
32
+ } from '@mindmatrix/player-core';
33
+ import { normalizeCategory } from '@mindmatrix/player-core';
34
+ import type { ExtractedWorkflow, CompilerState } from '../../types';
35
+ import type { FieldWatcher } from '../extractors/change-extractor';
36
+ import type { TransitionEffect } from '../extractors/transition-effect-extractor';
37
+ import { inferTransitionStates } from '../extractors/transition-extractor';
38
+ import { transformToFrontend } from './experience-transform';
39
+
40
+ // =============================================================================
41
+ // View normalization (moved from seed-compiled.mjs into compiler)
42
+ // =============================================================================
43
+
44
+ const PROP_RULES: Record<string, { config?: Record<string, string>; bindings?: Record<string, string> }> = {
45
+ Text: {
46
+ config: { text: 'value' },
47
+ bindings: { text: 'value' },
48
+ },
49
+ Heading: {
50
+ config: { text: 'value' },
51
+ bindings: { text: 'value' },
52
+ },
53
+ Button: {
54
+ config: { text: 'label' },
55
+ bindings: { text: 'label', onPress: 'onClick' },
56
+ },
57
+ };
58
+
59
+ const COMPONENT_RENAMES: Record<string, string> = {
60
+ Heading: 'Text',
61
+ };
62
+
63
+ const RENAME_EXTRA_CONFIG: Record<string, Record<string, unknown>> = {
64
+ Heading: { variant: 'h2' },
65
+ };
66
+
67
+ /**
68
+ * Normalizes an ExperienceNode tree:
69
+ * - Renames components (Heading → Text + variant)
70
+ * - Remaps prop names (text→value, onPress→onClick)
71
+ * - Converts template strings ({field}) → $fn.concat() bindings
72
+ * - Rewrites .fire bindings → $action.transition()
73
+ * - Rewrites $instance.field → $instance.state_data.field
74
+ */
75
+ function normalizeViewNode(node: IRExperienceNode, fieldNames: Set<string>): IRExperienceNode {
76
+ if (!node || typeof node !== 'object') return node;
77
+
78
+ // Rename component if needed
79
+ const originalComponent = node.component;
80
+ if (originalComponent && COMPONENT_RENAMES[originalComponent]) {
81
+ node.component = COMPONENT_RENAMES[originalComponent];
82
+ const extra = RENAME_EXTRA_CONFIG[originalComponent];
83
+ if (extra) {
84
+ node.config = { ...extra, ...(node.config || {}) };
85
+ }
86
+ }
87
+
88
+ // Apply prop rename rules
89
+ const rules = PROP_RULES[originalComponent || ''] || PROP_RULES[node.component || ''];
90
+ if (rules) {
91
+ if (node.config && rules.config) {
92
+ for (const [from, to] of Object.entries(rules.config)) {
93
+ if (from in node.config && !(to in node.config)) {
94
+ node.config[to] = node.config[from];
95
+ delete node.config[from];
96
+ }
97
+ }
98
+ }
99
+ if (node.bindings && rules.bindings) {
100
+ for (const [from, to] of Object.entries(rules.bindings)) {
101
+ if (from in node.bindings && !(to in node.bindings)) {
102
+ node.bindings[to] = node.bindings[from];
103
+ delete node.bindings[from];
104
+ }
105
+ }
106
+ }
107
+ }
108
+
109
+ // Convert template strings in config to bindings
110
+ if (node.config && fieldNames.size > 0) {
111
+ for (const [prop, val] of Object.entries(node.config)) {
112
+ if (typeof val !== 'string') continue;
113
+ const templateRe = /\{\{(\w+)\}\}|\{(\w+)\}/g;
114
+ let match;
115
+ const refs: Array<{ full: string; field: string; index: number }> = [];
116
+ while ((match = templateRe.exec(val)) !== null) {
117
+ const field = match[1] || match[2];
118
+ if (fieldNames.has(field)) {
119
+ refs.push({ full: match[0], field, index: match.index });
120
+ }
121
+ }
122
+ if (refs.length > 0) {
123
+ const parts: string[] = [];
124
+ let lastEnd = 0;
125
+ for (const ref of refs) {
126
+ const before = val.slice(lastEnd, ref.index);
127
+ if (before) parts.push(`"${before}"`);
128
+ parts.push(`$instance.state_data.${ref.field}`);
129
+ lastEnd = ref.index + ref.full.length;
130
+ }
131
+ const trailing = val.slice(lastEnd);
132
+ if (trailing) parts.push(`"${trailing}"`);
133
+ const expr = `$fn.concat(${parts.join(', ')})`;
134
+ if (!node.bindings) node.bindings = {};
135
+ node.bindings[prop] = expr;
136
+ delete node.config[prop];
137
+ }
138
+ }
139
+ }
140
+
141
+ // Rewrite bindings
142
+ if (node.bindings) {
143
+ for (const [prop, expr] of Object.entries(node.bindings)) {
144
+ if (typeof expr !== 'string') continue;
145
+
146
+ // .fire bindings → $action.transition("name")
147
+ if (expr.endsWith('.fire')) {
148
+ const transitionName = expr.slice(0, -5);
149
+ node.bindings[prop] = `$action.transition("${transitionName}")`;
150
+ continue;
151
+ }
152
+
153
+ // $instance.fieldName → $instance.state_data.fieldName
154
+ if (fieldNames.size > 0 && expr.startsWith('$instance.')) {
155
+ const field = expr.slice('$instance.'.length);
156
+ if (fieldNames.has(field)) {
157
+ node.bindings[prop] = `$instance.state_data.${field}`;
158
+ }
159
+ }
160
+ }
161
+ }
162
+
163
+ if (node.children && Array.isArray(node.children)) {
164
+ node.children = node.children.map(child => normalizeViewNode(child, fieldNames));
165
+
166
+ // Fold single Text children into parent config/bindings — only when the
167
+ // child Text is "simple" (no style, className, children, or extra config).
168
+ // Use PROP_RULES-mapped key so the result is already canonical.
169
+ if (node.children.length === 1 && node.children[0].component === 'Text') {
170
+ const textChild = node.children[0];
171
+ // Only fold when the child Text is truly simple — no style, className,
172
+ // children, visible_when, or extra config/binding keys beyond value.
173
+ const configKeys = textChild.config ? Object.keys(textChild.config).filter(k => k !== 'value') : [];
174
+ const bindingKeys = textChild.bindings ? Object.keys(textChild.bindings).filter(k => k !== 'value') : [];
175
+ const isSimple = !textChild.style && !textChild.className && !textChild.children
176
+ && !textChild.visible_when && configKeys.length === 0 && bindingKeys.length === 0;
177
+ if (isSimple) {
178
+ const parentRules = PROP_RULES[node.component || ''];
179
+ const configKey = parentRules?.config?.text || 'text';
180
+ const bindingKey = parentRules?.bindings?.text || 'text';
181
+ if (textChild.config?.value && !textChild.bindings) {
182
+ // Static text child: fold into config
183
+ if (!node.config) node.config = {};
184
+ node.config[configKey] = textChild.config.value;
185
+ delete node.children;
186
+ } else if (textChild.bindings?.value && !textChild.config?.value) {
187
+ // Dynamic text child: fold into bindings
188
+ if (!node.bindings) node.bindings = {};
189
+ node.bindings[bindingKey] = textChild.bindings.value;
190
+ delete node.children;
191
+ }
192
+ }
193
+ }
194
+ }
195
+
196
+ return node;
197
+ }
198
+
199
+ // =============================================================================
200
+ // Utility functions
201
+ // =============================================================================
202
+
203
+ /**
204
+ * Converts camelCase to snake_case.
205
+ */
206
+ function toSnakeCase(str: string): string {
207
+ return str.replace(/([A-Z])/g, '_$1').toLowerCase().replace(/^_/, '');
208
+ }
209
+
210
+ /**
211
+ * Converts action from IR format (type) to engine format (action_type).
212
+ */
213
+ function convertAction(action: any): any {
214
+ return {
215
+ id: action.id,
216
+ action_type: action.type,
217
+ config: action.config || {},
218
+ ...(action.condition && { condition: action.condition }),
219
+ };
220
+ }
221
+
222
+ /**
223
+ * Converts an IRDuringAction to engine format.
224
+ */
225
+ function convertDuringAction(during: IRDuringAction): Record<string, unknown> {
226
+ return {
227
+ id: during.id,
228
+ type: during.type,
229
+ ...(during.interval_ms !== undefined && { interval_ms: during.interval_ms }),
230
+ ...(during.cron && { cron: during.cron }),
231
+ ...(during.delay_ms !== undefined && { delay_ms: during.delay_ms }),
232
+ actions: during.actions.map(convertAction),
233
+ ...(during.condition && { condition: during.condition }),
234
+ };
235
+ }
236
+
237
+ /**
238
+ * Converts an IROnEventSubscription to engine format.
239
+ */
240
+ function convertOnEvent(sub: IROnEventSubscription): Record<string, unknown> {
241
+ return {
242
+ match: sub.match,
243
+ ...(sub.description && { description: sub.description }),
244
+ conditions: sub.conditions || [],
245
+ actions: sub.actions.map((a) => ({
246
+ type: a.type,
247
+ ...(a.field && { field: a.field }),
248
+ ...(a.expression && { expression: a.expression }),
249
+ ...(a.key && { key: a.key }),
250
+ ...(a.message && { message: a.message }),
251
+ ...(a.config && { config: a.config }),
252
+ ...(a.conditions && a.conditions.length > 0 && { conditions: a.conditions }),
253
+ })),
254
+ };
255
+ }
256
+
257
+ // =============================================================================
258
+ // IR Emission (renamed from emitPureForm)
259
+ // =============================================================================
260
+
261
+ /**
262
+ * Emits IR from extracted workflow data.
263
+ *
264
+ * This is the lowered IR output — everything extracted ends up here.
265
+ * View tree is normalized and emitted as a top-level `view` field
266
+ * (not inside metadata.experience).
267
+ */
268
+ export function emitIR(extracted: ExtractedWorkflow): IRWorkflowDefinition {
269
+ const { slug, name, version, description, category, fields, states, transitions } = extracted;
270
+
271
+ // Convert state map to array
272
+ const stateArray: IRStateDefinition[] = Array.from(states.values());
273
+
274
+ // Ensure at least one START state exists
275
+ if (stateArray.length === 0) {
276
+ stateArray.push({
277
+ name: 'draft',
278
+ type: 'START',
279
+ on_enter: [],
280
+ during: [],
281
+ on_exit: [],
282
+ });
283
+ } else {
284
+ const hasStart = stateArray.some((s) => s.type === 'START');
285
+ if (!hasStart && stateArray.length > 0) {
286
+ stateArray[0].type = 'START';
287
+ }
288
+ }
289
+
290
+ // Only infer from/to for transitions that don't already have explicit values
291
+ inferTransitionStates(transitions, states);
292
+
293
+ // Validate: every transition references existing states
294
+ const stateNames = new Set(stateArray.map((s) => s.name));
295
+ for (const transition of transitions) {
296
+ if (transition.to && !stateNames.has(transition.to)) {
297
+ stateArray.push({
298
+ name: transition.to,
299
+ type: 'REGULAR',
300
+ on_enter: [],
301
+ during: [],
302
+ on_exit: [],
303
+ });
304
+ stateNames.add(transition.to);
305
+ }
306
+ }
307
+
308
+ // Normalize view tree (prop renames, binding rewrites, template conversion)
309
+ const fieldNames = new Set(fields.map(f => f.name));
310
+ let normalizedView: IRExperienceNode | undefined;
311
+ if (extracted.experience) {
312
+ normalizedView = normalizeViewNode(
313
+ JSON.parse(JSON.stringify(extracted.experience)),
314
+ fieldNames,
315
+ );
316
+
317
+ // Attach dataSources from useQuery() extractions to the root view node
318
+ const dataSources = extracted.extraMetadata?.dataSources as IRDataSource[] | undefined;
319
+ if (dataSources && dataSources.length > 0) {
320
+ normalizedView.dataSources = dataSources;
321
+ }
322
+
323
+ // Attach localDefaults config for $local initialization from useState fields
324
+ if (fields.length > 0) {
325
+ const localDefaults: Record<string, unknown> = {};
326
+ for (const f of fields) {
327
+ localDefaults[toSnakeCase(f.name)] = f.default_value ?? null;
328
+ }
329
+ if (!normalizedView.config) normalizedView.config = {};
330
+ normalizedView.config.localDefaults = localDefaults;
331
+ }
332
+ }
333
+
334
+ // Build metadata — include everything extracted EXCEPT experience (now top-level view)
335
+ const metadata: Record<string, unknown> = {
336
+ stable_id: `def-${slug}`,
337
+ provenance: {
338
+ frontend: 'react-compiler',
339
+ source: `${slug}.workflow.tsx`,
340
+ compiler_version: '1.0.0',
341
+ },
342
+ };
343
+ if (extracted.fieldWatchers && extracted.fieldWatchers.length > 0) {
344
+ metadata.fieldWatchers = extracted.fieldWatchers;
345
+ }
346
+ if (extracted.transitionEffects && extracted.transitionEffects.length > 0) {
347
+ metadata.transitionEffects = extracted.transitionEffects;
348
+ }
349
+ // Forward extra metadata from model files (runtime, etc.)
350
+ if (extracted.extraMetadata) {
351
+ for (const [key, value] of Object.entries(extracted.extraMetadata)) {
352
+ metadata[key] = value;
353
+ }
354
+ }
355
+
356
+ // Keep experience in metadata for backward compatibility during migration
357
+ if (extracted.experience) {
358
+ metadata.experience = extracted.experience;
359
+ }
360
+
361
+ const ir: IRWorkflowDefinition = {
362
+ slug,
363
+ name,
364
+ version,
365
+ description,
366
+ category,
367
+ fields,
368
+ states: stateArray,
369
+ transitions,
370
+ roles: [],
371
+ tags: [],
372
+ metadata,
373
+ };
374
+
375
+ // Attach normalized view as views.default (IR format)
376
+ // Also attach frontend-compatible view via transform pass
377
+ if (normalizedView) {
378
+ (ir as any).views = { default: normalizedView };
379
+ (ir as any).frontendViews = { default: transformToFrontend(normalizedView) };
380
+ }
381
+
382
+ // Emit workflow-level on_event
383
+ if (extracted.events && extracted.events.length > 0) {
384
+ ir.on_event = extracted.events;
385
+ }
386
+
387
+ // Emit grammar islands as extensions
388
+ if (extracted.grammarIslands && extracted.grammarIslands.length > 0) {
389
+ const extensions: Record<string, typeof extracted.grammarIslands> = {};
390
+ for (const island of extracted.grammarIslands) {
391
+ const key = island.contextTag;
392
+ if (!extensions[key]) extensions[key] = [];
393
+ extensions[key].push(island);
394
+ }
395
+ ir.extensions = extensions;
396
+ }
397
+
398
+ return ir;
399
+ }
400
+
401
+ /** @deprecated Use emitIR() instead. Kept for backward compatibility. */
402
+ export const emitPureForm = emitIR;
403
+
404
+ // =============================================================================
405
+ // Canonical Tree Emission (per 041 protocol)
406
+ // =============================================================================
407
+
408
+ /**
409
+ * Lifts an IR action into canonical form.
410
+ */
411
+ function liftAction(action: IRActionDefinition): PureFormWorkflow {
412
+ const parts: PureFormWorkflow[] = [];
413
+
414
+ if (action.config) {
415
+ for (const [key, value] of Object.entries(action.config)) {
416
+ parts.push({
417
+ slug: key,
418
+ category: ['atom'],
419
+ parts: [{ slug: String(value), category: ['atom'] }],
420
+ });
421
+ }
422
+ }
423
+
424
+ if (action.condition) {
425
+ parts.push({
426
+ slug: 'condition',
427
+ category: ['expression', 'guard'],
428
+ parts: [{ slug: action.condition, category: ['binding'] }],
429
+ });
430
+ }
431
+
432
+ return {
433
+ slug: action.id,
434
+ category: normalizeCategory('expression', 'mutation', action.type),
435
+ parts: parts.length > 0 ? parts : undefined,
436
+ };
437
+ }
438
+
439
+ /**
440
+ * Lifts an IR during action (schedule) into canonical form.
441
+ */
442
+ function liftSchedule(during: IRDuringAction): PureFormWorkflow {
443
+ const parts: PureFormWorkflow[] = [];
444
+
445
+ if (during.interval_ms !== undefined) {
446
+ parts.push({
447
+ slug: 'every',
448
+ category: ['atom'],
449
+ parts: [{ slug: String(during.interval_ms), category: ['literal'] }],
450
+ });
451
+ }
452
+
453
+ if (during.cron) {
454
+ parts.push({
455
+ slug: 'cron',
456
+ category: ['atom'],
457
+ parts: [{ slug: during.cron, category: ['literal'] }],
458
+ });
459
+ }
460
+
461
+ if (during.delay_ms !== undefined) {
462
+ parts.push({
463
+ slug: 'delay',
464
+ category: ['atom'],
465
+ parts: [{ slug: String(during.delay_ms), category: ['literal'] }],
466
+ });
467
+ }
468
+
469
+ // Lift inner actions
470
+ for (const action of during.actions) {
471
+ parts.push({
472
+ slug: 'do',
473
+ category: normalizeCategory('expression', 'mutation', action.type),
474
+ parts: Object.entries(action.config || {}).map(([key, value]) => ({
475
+ slug: key,
476
+ category: ['atom'],
477
+ parts: [{ slug: String(value), category: ['atom'] }],
478
+ })),
479
+ });
480
+ }
481
+
482
+ return {
483
+ slug: during.id,
484
+ category: normalizeCategory('schedule', during.type),
485
+ parts,
486
+ };
487
+ }
488
+
489
+ /**
490
+ * Lifts an IR state into canonical form.
491
+ */
492
+ function liftState(state: IRStateDefinition): PureFormWorkflow {
493
+ const parts: PureFormWorkflow[] = [];
494
+ const tags: string[] = [];
495
+
496
+ if (state.type === 'START') tags.push('start');
497
+ if (state.type === 'END') tags.push('end');
498
+ if (state.type === 'CANCELLED') tags.push('cancelled');
499
+
500
+ // on_enter actions
501
+ if (state.on_enter && state.on_enter.length > 0) {
502
+ parts.push({
503
+ slug: 'on_enter',
504
+ category: normalizeCategory('expression', 'sequence'),
505
+ parts: state.on_enter.map(liftAction),
506
+ });
507
+ }
508
+
509
+ // on_exit actions
510
+ if (state.on_exit && state.on_exit.length > 0) {
511
+ parts.push({
512
+ slug: 'on_exit',
513
+ category: normalizeCategory('expression', 'sequence'),
514
+ parts: state.on_exit.map(liftAction),
515
+ });
516
+ }
517
+
518
+ // during actions (schedules)
519
+ if (state.during && state.during.length > 0) {
520
+ for (const d of state.during) {
521
+ parts.push(liftSchedule(d));
522
+ }
523
+ }
524
+
525
+ return {
526
+ slug: state.name,
527
+ category: normalizeCategory('state', ...tags),
528
+ parts: parts.length > 0 ? parts : undefined,
529
+ };
530
+ }
531
+
532
+ /**
533
+ * Lifts an IR transition into canonical form.
534
+ */
535
+ function liftTransition(transition: IRTransitionDefinition): PureFormWorkflow {
536
+ const parts: PureFormWorkflow[] = [];
537
+
538
+ // from refs
539
+ if (transition.from && transition.from.length > 0) {
540
+ parts.push({
541
+ slug: 'from',
542
+ category: ['part'],
543
+ parts: transition.from.map((s: string) => ({ slug: s, category: ['ref'] as string[] })),
544
+ });
545
+ }
546
+
547
+ // to ref
548
+ if (transition.to) {
549
+ parts.push({
550
+ slug: 'to',
551
+ category: ['part'],
552
+ parts: [{ slug: transition.to, category: ['ref'] }],
553
+ });
554
+ }
555
+
556
+ // actions
557
+ if (transition.actions && transition.actions.length > 0) {
558
+ parts.push({
559
+ slug: 'actions',
560
+ category: normalizeCategory('expression', 'sequence'),
561
+ parts: transition.actions.map(liftAction),
562
+ });
563
+ }
564
+
565
+ // conditions
566
+ if (transition.conditions && transition.conditions.length > 0) {
567
+ parts.push({
568
+ slug: 'conditions',
569
+ category: normalizeCategory('expression', 'guard'),
570
+ parts: transition.conditions.map((c: IRConditionDefinition, i: number) => ({
571
+ slug: `condition_${i}`,
572
+ category: normalizeCategory('expression', c.type || 'condition'),
573
+ parts: c.expression ? [{ slug: c.expression, category: ['binding'] as string[] }] : undefined,
574
+ })),
575
+ });
576
+ }
577
+
578
+ return {
579
+ slug: transition.name,
580
+ category: ['transition'],
581
+ parts,
582
+ };
583
+ }
584
+
585
+ /**
586
+ * Lifts an IR field into canonical form.
587
+ */
588
+ function liftField(field: IRFieldDefinition): PureFormWorkflow {
589
+ const parts: PureFormWorkflow[] = [];
590
+
591
+ if (field.label) {
592
+ parts.push({
593
+ slug: 'label',
594
+ category: ['atom'],
595
+ parts: [{ slug: field.label, category: ['atom'] }],
596
+ });
597
+ }
598
+
599
+ if (field.default_value !== undefined) {
600
+ parts.push({
601
+ slug: 'default',
602
+ category: ['atom'],
603
+ parts: [{ slug: String(field.default_value), category: ['literal'] }],
604
+ });
605
+ }
606
+
607
+ if (field.required) {
608
+ parts.push({ slug: 'required', category: ['atom'], parts: [{ slug: 'true', category: ['literal'] }] });
609
+ }
610
+
611
+ if (field.computed) {
612
+ parts.push({
613
+ slug: 'computed',
614
+ category: ['expression'],
615
+ parts: [{ slug: field.computed, category: ['binding'] }],
616
+ });
617
+ }
618
+
619
+ return {
620
+ slug: field.name,
621
+ category: normalizeCategory('field', field.type),
622
+ parts: parts.length > 0 ? parts : undefined,
623
+ };
624
+ }
625
+
626
+ /**
627
+ * Lifts an ExperienceNode tree into canonical view form.
628
+ */
629
+ function liftView(node: IRExperienceNode): PureFormWorkflow {
630
+ const componentTag = (node.component || 'stack').toLowerCase().replace(/\s+/g, '-');
631
+ const parts: PureFormWorkflow[] = [];
632
+
633
+ // Config as atom parts
634
+ if (node.config) {
635
+ for (const [key, value] of Object.entries(node.config)) {
636
+ parts.push({
637
+ slug: key,
638
+ category: ['atom'],
639
+ parts: [{ slug: String(value), category: ['atom'] }],
640
+ });
641
+ }
642
+ }
643
+
644
+ // Bindings as expression parts
645
+ if (node.bindings) {
646
+ for (const [key, expr] of Object.entries(node.bindings)) {
647
+ if (key === 'onClick' || key === 'onPress') {
648
+ // Transition binding
649
+ const match = typeof expr === 'string' ? expr.match(/\$action\.transition\("(.+?)"\)/) : null;
650
+ if (match) {
651
+ parts.push({
652
+ slug: key,
653
+ category: normalizeCategory('expression', 'effect', 'transition'),
654
+ parts: [{ slug: match[1], category: ['ref'] }],
655
+ });
656
+ } else {
657
+ parts.push({
658
+ slug: key,
659
+ category: normalizeCategory('expression', 'binding'),
660
+ parts: [{ slug: String(expr), category: ['binding'] }],
661
+ });
662
+ }
663
+ } else {
664
+ parts.push({
665
+ slug: key,
666
+ category: normalizeCategory('expression', 'binding'),
667
+ parts: [{ slug: String(expr), category: ['binding'] }],
668
+ });
669
+ }
670
+ }
671
+ }
672
+
673
+ // visible_when as guard expression
674
+ if (node.visible_when) {
675
+ const eqMatch = node.visible_when.match(/\$fn\.eq\((.+?),\s*"(.+?)"\)/);
676
+ if (eqMatch) {
677
+ parts.push({
678
+ slug: 'visible_when',
679
+ category: normalizeCategory('expression', 'guard'),
680
+ parts: [{
681
+ slug: 'body',
682
+ category: normalizeCategory('expression', 'eq'),
683
+ parts: [
684
+ { slug: 'lhs', category: normalizeCategory('expression', 'path'), parts: [{ slug: eqMatch[1], category: ['binding'] }] },
685
+ { slug: 'rhs', category: normalizeCategory('expression', 'literal'), parts: [{ slug: eqMatch[2], category: ['literal'] }] },
686
+ ],
687
+ }],
688
+ });
689
+ } else {
690
+ parts.push({
691
+ slug: 'visible_when',
692
+ category: normalizeCategory('expression', 'guard'),
693
+ parts: [{ slug: node.visible_when, category: ['binding'] }],
694
+ });
695
+ }
696
+ }
697
+
698
+ // Recurse children
699
+ if (node.children && node.children.length > 0) {
700
+ for (const child of node.children) {
701
+ parts.push(liftView(child));
702
+ }
703
+ }
704
+
705
+ return {
706
+ slug: node.id,
707
+ category: normalizeCategory('view', componentTag),
708
+ parts: parts.length > 0 ? parts : undefined,
709
+ };
710
+ }
711
+
712
+ /**
713
+ * Emits canonical tree from extracted workflow data.
714
+ *
715
+ * Produces `{ slug, category, parts, metadata }` per 041 protocol.
716
+ * This is the TRUTH. The IR is a derivable cache.
717
+ */
718
+ export function emitCanonical(extracted: ExtractedWorkflow, sourceFilename?: string): PureFormWorkflow {
719
+ // First get the IR to reuse its processing (START state inference, transition validation, etc.)
720
+ const ir = emitIR(extracted);
721
+
722
+ const parts: PureFormWorkflow[] = [];
723
+
724
+ // Lift states
725
+ for (const state of ir.states) {
726
+ parts.push(liftState(state));
727
+ }
728
+
729
+ // Lift transitions
730
+ for (const transition of ir.transitions) {
731
+ parts.push(liftTransition(transition));
732
+ }
733
+
734
+ // Lift fields
735
+ for (const field of ir.fields) {
736
+ parts.push(liftField(field));
737
+ }
738
+
739
+ // Lift view tree (from original experience, not normalized IR view)
740
+ if (extracted.experience) {
741
+ parts.push(liftView(extracted.experience));
742
+ }
743
+
744
+ // Manifest as meta part
745
+ parts.push({
746
+ slug: 'manifest',
747
+ category: normalizeCategory('meta', 'manifest'),
748
+ parts: [
749
+ {
750
+ slug: 'workflows',
751
+ category: ['ref-list'],
752
+ parts: [{ slug: ir.slug, category: ['ref'] }],
753
+ },
754
+ {
755
+ slug: 'route',
756
+ category: ['route'],
757
+ parts: [
758
+ { slug: 'path', category: ['atom'], parts: [{ slug: `/${ir.slug}`, category: ['atom'] }] },
759
+ { slug: 'label', category: ['atom'], parts: [{ slug: ir.name, category: ['atom'] }] },
760
+ ],
761
+ },
762
+ ],
763
+ });
764
+
765
+ // Parse category: the user-specified category is the primary.
766
+ // Open category set — any string is valid (workflow, data, blueprint, module,
767
+ // data-type, view, expression-library, or user-defined categories).
768
+ // If the category contains a slash (e.g., "workflow/demo"), split into primary + tag.
769
+ const category = extracted.category;
770
+ let categoryArray: string[];
771
+ if (category.includes('/')) {
772
+ const [primary, ...tags] = category.split('/');
773
+ categoryArray = normalizeCategory(primary, ...tags);
774
+ } else {
775
+ categoryArray = [category];
776
+ }
777
+
778
+ return {
779
+ slug: ir.slug,
780
+ category: categoryArray,
781
+ parts,
782
+ metadata: {
783
+ stable_id: `def-${ir.slug}`,
784
+ provenance: {
785
+ frontend: 'react-compiler',
786
+ source: sourceFilename || `${ir.slug}.workflow.tsx`,
787
+ compiler_version: '1.0.0',
788
+ compiled_at: new Date().toISOString(),
789
+ },
790
+ },
791
+ };
792
+ }
793
+
794
+ /**
795
+ * Emits the combined compiled output: canonical tree + lowered IR.
796
+ */
797
+ export function emitCompiledOutput(extracted: ExtractedWorkflow, sourceFilename?: string): { canonical: PureFormWorkflow; ir: IRWorkflowDefinition } {
798
+ return {
799
+ canonical: emitCanonical(extracted, sourceFilename),
800
+ ir: emitIR(extracted),
801
+ };
802
+ }
803
+
804
+ // =============================================================================
805
+ // Text-content folding (lightweight, no renames/rewrites)
806
+ // =============================================================================
807
+
808
+ /**
809
+ * Folds single Text children into parent config/bindings.
810
+ * e.g. <Heading>Counter</Heading> → Heading with config.text = "Counter"
811
+ * e.g. <Text>{count}</Text> → Text with bindings.text = "$instance.count"
812
+ * Does NOT rename components or rewrite bindings — that's normalizeViewNode's job.
813
+ */
814
+ function foldTextContent(node: IRExperienceNode): IRExperienceNode {
815
+ if (!node || typeof node !== 'object') return node;
816
+
817
+ if (node.children && Array.isArray(node.children)) {
818
+ node.children = node.children.map(child => foldTextContent(child));
819
+
820
+ // Fold single Text children into parent — only when truly simple
821
+ if (node.children.length === 1 && node.children[0].component === 'Text') {
822
+ const textChild = node.children[0];
823
+ const configKeys = textChild.config ? Object.keys(textChild.config).filter((k: string) => k !== 'value') : [];
824
+ const bindingKeys = textChild.bindings ? Object.keys(textChild.bindings).filter((k: string) => k !== 'value') : [];
825
+ const isSimple = !textChild.style && !textChild.className && !textChild.children
826
+ && !textChild.visible_when && configKeys.length === 0 && bindingKeys.length === 0;
827
+ if (isSimple) {
828
+ const parentRules = PROP_RULES[node.component || ''];
829
+ const configKey = parentRules?.config?.text || 'text';
830
+ const bindingKey = parentRules?.bindings?.text || 'text';
831
+ if (textChild.config?.value && !textChild.bindings) {
832
+ if (!node.config) node.config = {};
833
+ node.config[configKey] = textChild.config.value;
834
+ node.children = undefined as any;
835
+ } else if (textChild.bindings?.value && !textChild.config?.value) {
836
+ if (!node.bindings) node.bindings = {};
837
+ node.bindings[bindingKey] = textChild.bindings.value;
838
+ node.children = undefined as any;
839
+ }
840
+ }
841
+ }
842
+
843
+ // Clean up empty children arrays
844
+ if (node.children && node.children.length === 0) {
845
+ node.children = undefined as any;
846
+ }
847
+ }
848
+
849
+ // Remove undefined children from serialization
850
+ if (!node.children) delete (node as any).children;
851
+
852
+ return node;
853
+ }
854
+
855
+ // =============================================================================
856
+ // Engine-compatible Definition Emission
857
+ // =============================================================================
858
+
859
+ /**
860
+ * Emits a LocalWorkflowEngine-compatible WorkflowDefinition.
861
+ *
862
+ * This converts from the IR format to the engine format:
863
+ * - state.type → state.state_type
864
+ * - field.type → field.field_type
865
+ * - action.type → action.action_type
866
+ * - during actions → engine format with action_type
867
+ * - on_event → preserved per-state and at workflow level
868
+ * - camelCase field names → snake_case
869
+ */
870
+ export function emitWorkflowDefinition(extracted: ExtractedWorkflow): Record<string, unknown> {
871
+ const ir = emitIR(extracted);
872
+
873
+ // Convert states: type → state_type, actions type → action_type
874
+ const states = ir.states.map((s) => ({
875
+ name: s.name,
876
+ state_type: s.type,
877
+ description: s.description || '',
878
+ on_enter: (s.on_enter || []).map(convertAction),
879
+ on_exit: (s.on_exit || []).map(convertAction),
880
+ during: (s.during || []).map(convertDuringAction),
881
+ on_event: (s.on_event || []).map(convertOnEvent),
882
+ }));
883
+
884
+ // Convert fields: type → field_type, name to snake_case, preserve ACL
885
+ const fields = ir.fields.map((f) => ({
886
+ name: toSnakeCase(f.name),
887
+ field_type: f.type,
888
+ label: f.label || f.name.replace(/([A-Z])/g, ' $1').replace(/^./, (c) => c.toUpperCase()),
889
+ required: f.required || false,
890
+ default_value: f.default_value ?? null,
891
+ ...(f.validation && { validation: f.validation }),
892
+ ...(f.computed && { computed: f.computed }),
893
+ ...(f.computed_deps && { computed_deps: f.computed_deps }),
894
+ ...(f.visible_in_states && { visible_in_states: f.visible_in_states }),
895
+ ...(f.editable_in_states && { editable_in_states: f.editable_in_states }),
896
+ ...(f.visible_to_roles && { visible_to_roles: f.visible_to_roles }),
897
+ ...(f.editable_by_roles && { editable_by_roles: f.editable_by_roles }),
898
+ ...(f.visible_when && { visible_when: f.visible_when }),
899
+ ...(f.editable_when && { editable_when: f.editable_when }),
900
+ ...(f.state_home && { state_home: f.state_home }),
901
+ }));
902
+
903
+ // Convert transitions: add engine-expected extra fields
904
+ const transitions = ir.transitions.map((t) => ({
905
+ name: t.name,
906
+ from: t.from,
907
+ to: t.to,
908
+ description: t.description || '',
909
+ roles: t.roles || [],
910
+ auto: t.auto || false,
911
+ conditions: t.conditions || [],
912
+ actions: (t.actions || []).map(convertAction),
913
+ required_fields: t.required_fields || [],
914
+ priority: 0,
915
+ }));
916
+
917
+ // Build state_data from fields
918
+ const state_data: Record<string, unknown> = {};
919
+ for (const f of fields) {
920
+ state_data[f.name] = f.default_value;
921
+ }
922
+
923
+ // Build workflow-level on_event
924
+ const on_event = (ir.on_event || []).map(convertOnEvent);
925
+
926
+ // Build views from raw experience (with text-content folding only, no normalization)
927
+ let views: Record<string, unknown> | undefined;
928
+ if (extracted.experience) {
929
+ const viewRoot = foldTextContent(JSON.parse(JSON.stringify(extracted.experience)));
930
+
931
+ // Attach dataSources to the engine-compatible view root
932
+ const dataSources = extracted.extraMetadata?.dataSources as IRDataSource[] | undefined;
933
+ if (dataSources && dataSources.length > 0) {
934
+ viewRoot.dataSources = dataSources;
935
+ }
936
+
937
+ // Attach localDefaults for $local initialization
938
+ if (extracted.fields.length > 0) {
939
+ const localDefaults: Record<string, unknown> = {};
940
+ for (const f of extracted.fields) {
941
+ localDefaults[toSnakeCase(f.name)] = f.default_value ?? null;
942
+ }
943
+ if (!viewRoot.config) viewRoot.config = {};
944
+ viewRoot.config.localDefaults = localDefaults;
945
+ }
946
+
947
+ views = { default: viewRoot };
948
+ }
949
+
950
+ return {
951
+ id: `def-${ir.slug}`,
952
+ slug: ir.slug,
953
+ name: ir.name,
954
+ version: ir.version,
955
+ description: ir.description || '',
956
+ category: ir.category,
957
+ states,
958
+ transitions,
959
+ fields,
960
+ state_data,
961
+ roles: [],
962
+ child_definitions: [],
963
+ tags: ir.tags || [],
964
+ metadata: ir.metadata || {},
965
+ ...(views && { views }),
966
+ ...(on_event.length > 0 && { on_event }),
967
+ config: {},
968
+ is_immutable: false,
969
+ };
970
+ }
971
+
972
+ // =============================================================================
973
+ // Compiler State Conversion
974
+ // =============================================================================
975
+
976
+ /**
977
+ * Converts compiler state to ExtractedWorkflow.
978
+ *
979
+ * Critical: must transfer ALL extracted data — nothing may be lost.
980
+ */
981
+ export function compilerStateToWorkflow(state: CompilerState, metadata: {
982
+ slug?: string;
983
+ name?: string;
984
+ version?: string;
985
+ description?: string;
986
+ category?: string;
987
+ [key: string]: unknown;
988
+ }): ExtractedWorkflow {
989
+ // Extract field watchers and transition effects from metadata
990
+ const fieldWatchers = (metadata.fieldWatchers as FieldWatcher[] | undefined) || [];
991
+ const transitionEffects = (metadata.transitionEffects as TransitionEffect[] | undefined) || [];
992
+
993
+ // Extract grammar islands from metadata
994
+ const grammarIslands = (metadata.grammarIslands as IRGrammarIsland[] | undefined) || [];
995
+
996
+ // Collect extra metadata — everything that isn't a known key
997
+ const knownKeys = new Set(['slug', 'name', 'version', 'description', 'category', 'fieldWatchers', 'transitionEffects', 'grammarIslands', '__modelImports', '__modelImportSlugs', '__slugAutoFallback']);
998
+ const extraMetadata: Record<string, unknown> = {};
999
+ for (const [key, value] of Object.entries(metadata)) {
1000
+ if (!knownKeys.has(key) && value !== undefined) {
1001
+ extraMetadata[key] = value;
1002
+ }
1003
+ }
1004
+
1005
+ return {
1006
+ slug: metadata.slug || 'workflow',
1007
+ name: metadata.name || 'Workflow',
1008
+ version: metadata.version || '0.1.0',
1009
+ description: metadata.description,
1010
+ category: metadata.category || 'workflow',
1011
+ fields: state.fields || [],
1012
+ states: state.states || new Map(),
1013
+ transitions: state.transitions || [],
1014
+ events: state.events || [],
1015
+ experience: state.experience,
1016
+ fieldWatchers: fieldWatchers.length > 0 ? fieldWatchers : undefined,
1017
+ transitionEffects: transitionEffects.length > 0 ? transitionEffects : undefined,
1018
+ grammarIslands: grammarIslands.length > 0 ? grammarIslands : undefined,
1019
+ errors: state.errors,
1020
+ warnings: state.warnings,
1021
+ extraMetadata: Object.keys(extraMetadata).length > 0 ? extraMetadata : undefined,
1022
+ };
1023
+ }