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

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 (251) hide show
  1. package/ATOM-PIPELINE.md +144 -0
  2. package/README.md +88 -40
  3. package/dist/babel/index.js +113 -6
  4. package/dist/babel/index.mjs +2 -2
  5. package/dist/chunk-3USIFFE4.mjs +2190 -0
  6. package/dist/chunk-45YMGEVT.mjs +186 -0
  7. package/dist/chunk-4FN2AISW.mjs +148 -0
  8. package/dist/chunk-4OPI5L7G.mjs +2593 -0
  9. package/dist/chunk-4RYTKOOJ.mjs +186 -0
  10. package/dist/chunk-5RKTOVR5.mjs +244 -0
  11. package/dist/chunk-5YDMOO4X.mjs +214 -0
  12. package/dist/chunk-64ZWEMLJ.mjs +148 -0
  13. package/dist/chunk-6XP4KSWQ.mjs +2190 -0
  14. package/dist/chunk-72QWL54I.mjs +175 -0
  15. package/dist/chunk-7B4TRI7C.mjs +4835 -0
  16. package/dist/chunk-7ZKGHTNB.mjs +4952 -0
  17. package/dist/chunk-CIESM3BP.mjs +33 -0
  18. package/dist/chunk-DE3ZGQAC.mjs +148 -0
  19. package/dist/chunk-DMCY3BBG.mjs +1933 -0
  20. package/dist/chunk-DPIK3PJS.mjs +244 -0
  21. package/dist/chunk-E5IVH4RE.mjs +186 -0
  22. package/dist/chunk-E6FZNUR5.mjs +4953 -0
  23. package/dist/chunk-EJRBDQDP.mjs +2607 -0
  24. package/dist/chunk-ELO4TXJL.mjs +186 -0
  25. package/dist/chunk-FKRO52XH.mjs +3446 -0
  26. package/dist/chunk-FL4YAKU6.mjs +4941 -0
  27. package/dist/chunk-FYT47UBU.mjs +5076 -0
  28. package/dist/chunk-GCLGPOJZ.mjs +148 -0
  29. package/dist/chunk-GXB4JOP7.mjs +5072 -0
  30. package/dist/chunk-HFXOUMTD.mjs +175 -0
  31. package/dist/chunk-HWIZ47US.mjs +214 -0
  32. package/dist/chunk-IB7MNPQL.mjs +4953 -0
  33. package/dist/chunk-ICSIHQCG.mjs +148 -0
  34. package/dist/chunk-JLA5VNQ3.mjs +186 -0
  35. package/dist/chunk-JQLWFCTM.mjs +214 -0
  36. package/dist/chunk-KFJJCQAL.mjs +148 -0
  37. package/dist/chunk-KJUIIEQE.mjs +186 -0
  38. package/dist/chunk-KNWTHRVQ.mjs +175 -0
  39. package/dist/chunk-KSG4XSZF.mjs +175 -0
  40. package/dist/chunk-LF5N6DOU.mjs +175 -0
  41. package/dist/chunk-LJQCM2IM.mjs +214 -0
  42. package/dist/chunk-NW6555WJ.mjs +186 -0
  43. package/dist/chunk-OMZE6VLQ.mjs +214 -0
  44. package/dist/chunk-P4BR7WVO.mjs +2190 -0
  45. package/dist/chunk-QQHVYH2X.mjs +244 -0
  46. package/dist/chunk-S5QLWLLT.mjs +186 -0
  47. package/dist/chunk-SCWGT2FY.mjs +2190 -0
  48. package/dist/chunk-SMKJUSB3.mjs +2190 -0
  49. package/dist/chunk-VCAY2KGM.mjs +175 -0
  50. package/dist/chunk-WECAV6QB.mjs +148 -0
  51. package/dist/chunk-WMKBXUCE.mjs +3228 -0
  52. package/dist/chunk-XAJ5BKKL.mjs +4947 -0
  53. package/dist/chunk-XG2X7AEA.mjs +175 -0
  54. package/dist/chunk-XG7Z23NQ.mjs +148 -0
  55. package/dist/chunk-XWZAOCQ7.mjs +2607 -0
  56. package/dist/chunk-Y6MA7ULW.mjs +148 -0
  57. package/dist/chunk-YMS7Q7LG.mjs +214 -0
  58. package/dist/chunk-ZA37XTGA.mjs +175 -0
  59. package/dist/cli/index.js +1616 -366
  60. package/dist/cli/index.mjs +8 -8
  61. package/dist/codemod/cli.mjs +1 -1
  62. package/dist/codemod/index.mjs +1 -1
  63. package/dist/dev-server-RmGHIntF.d.mts +113 -0
  64. package/dist/dev-server-RmGHIntF.d.ts +113 -0
  65. package/dist/dev-server.d.mts +1 -1
  66. package/dist/dev-server.d.ts +1 -1
  67. package/dist/dev-server.js +982 -53
  68. package/dist/dev-server.mjs +5 -5
  69. package/dist/envelope.js +113 -6
  70. package/dist/envelope.mjs +3 -3
  71. package/dist/index.d.mts +5 -1
  72. package/dist/index.d.ts +5 -1
  73. package/dist/index.js +992 -63
  74. package/dist/index.mjs +8 -8
  75. package/{src/cli/init.ts → dist/init-7JQMAAXS.mjs} +70 -95
  76. package/dist/init-EHO4VQ22.mjs +369 -0
  77. package/dist/init-UC3FWPIW.mjs +367 -0
  78. package/dist/init-UNSMVKIK.mjs +366 -0
  79. package/dist/init-UNV5XIDE.mjs +367 -0
  80. package/dist/project-compiler-2P4N4DR7.mjs +10 -0
  81. package/dist/project-compiler-D2LCC27O.mjs +10 -0
  82. package/dist/project-compiler-EJ3GANJE.mjs +10 -0
  83. package/dist/project-compiler-LOQKVRZJ.mjs +10 -0
  84. package/dist/project-compiler-RQ6OQKRM.mjs +10 -0
  85. package/dist/project-compiler-VWNNCHGO.mjs +10 -0
  86. package/dist/project-compiler-XVAAU4C5.mjs +10 -0
  87. package/dist/project-compiler-YES5FGMD.mjs +10 -0
  88. package/dist/project-compiler-ZKMQDLGU.mjs +10 -0
  89. package/dist/project-decompiler-FLXCEJHS.mjs +7 -0
  90. package/dist/project-decompiler-VLPR22QF.mjs +7 -0
  91. package/dist/pull-FUS5QYZS.mjs +109 -0
  92. package/dist/pull-LD5ENLGY.mjs +109 -0
  93. package/dist/testing/index.js +113 -6
  94. package/dist/testing/index.mjs +2 -2
  95. package/dist/vite/index.js +113 -6
  96. package/dist/vite/index.mjs +3 -3
  97. package/examples/uber-app/app/admin/fleet.tsx +19 -19
  98. package/package.json +4 -3
  99. package/compile-blueprint-chat.mjs +0 -99
  100. package/compile-blueprint-glass-console.mjs +0 -98
  101. package/compile-chat-defs.mjs +0 -92
  102. package/examples/uber-app/tests/payment.test.tsx +0 -129
  103. package/examples/uber-app/tests/ride-flow.test.tsx +0 -123
  104. package/package.json.backup +0 -86
  105. package/scripts/decompile.ts +0 -226
  106. package/scripts/seed-auth.ts +0 -267
  107. package/scripts/seed-uber.ts +0 -248
  108. package/scripts/validate-uber.ts +0 -119
  109. package/seed-blueprint-chat.mjs +0 -444
  110. package/seed-blueprint-glass-console.mjs +0 -445
  111. package/seed-compiled.mjs +0 -318
  112. package/src/RoundTripValidator.ts +0 -400
  113. package/src/__tests__/atom-rendering-coverage.test.ts +0 -680
  114. package/src/__tests__/auth-module-compilation.test.ts +0 -247
  115. package/src/__tests__/auth-template-compilation.test.ts +0 -589
  116. package/src/__tests__/change-extractor.test.ts +0 -142
  117. package/src/__tests__/cli-pull.test.ts +0 -73
  118. package/src/__tests__/cli-test.test.ts +0 -72
  119. package/src/__tests__/component-extractor.test.ts +0 -331
  120. package/src/__tests__/context-extractor.test.ts +0 -145
  121. package/src/__tests__/decompiler.test.ts +0 -718
  122. package/src/__tests__/define-blueprint.test.ts +0 -133
  123. package/src/__tests__/definition-validator.test.ts +0 -519
  124. package/src/__tests__/during-extractor.test.ts +0 -152
  125. package/src/__tests__/effect-extractor.test.ts +0 -107
  126. package/src/__tests__/event-emission.test.ts +0 -127
  127. package/src/__tests__/examples.test.ts +0 -236
  128. package/src/__tests__/full-blueprint-coverage.test.ts +0 -1221
  129. package/src/__tests__/golden-suite.test.ts +0 -403
  130. package/src/__tests__/grammar-island-extractor.test.ts +0 -289
  131. package/src/__tests__/instance-key.test.ts +0 -82
  132. package/src/__tests__/ir-migration.test.ts +0 -255
  133. package/src/__tests__/lock-file.test.ts +0 -117
  134. package/src/__tests__/model-extractor.test.ts +0 -195
  135. package/src/__tests__/model-field-acl.test.ts +0 -237
  136. package/src/__tests__/model-hooks.test.ts +0 -130
  137. package/src/__tests__/model-ref-resolution.test.ts +0 -268
  138. package/src/__tests__/model-roundtrip.test.ts +0 -502
  139. package/src/__tests__/model-runtime.test.ts +0 -112
  140. package/src/__tests__/model-transitions.test.ts +0 -183
  141. package/src/__tests__/nrt-action-trace.test.ts +0 -391
  142. package/src/__tests__/pipeline-hardening.test.ts +0 -413
  143. package/src/__tests__/project-compiler.test.ts +0 -546
  144. package/src/__tests__/project-decompiler.test.ts +0 -343
  145. package/src/__tests__/query-compilation.test.ts +0 -145
  146. package/src/__tests__/round-trip/PLAN.md +0 -158
  147. package/src/__tests__/round-trip/README.md +0 -52
  148. package/src/__tests__/round-trip/RESULTS.md +0 -86
  149. package/src/__tests__/round-trip/fixtures/data-heavy/main.workflow.tsx +0 -55
  150. package/src/__tests__/round-trip/fixtures/data-heavy/mm.config.ts +0 -11
  151. package/src/__tests__/round-trip/fixtures/data-heavy/models/contact.ts +0 -54
  152. package/src/__tests__/round-trip/fixtures/full-workflow/main.workflow.tsx +0 -79
  153. package/src/__tests__/round-trip/fixtures/full-workflow/mm.config.ts +0 -12
  154. package/src/__tests__/round-trip/fixtures/full-workflow/models/order.ts +0 -50
  155. package/src/__tests__/round-trip/fixtures/simple-crud/main.workflow.tsx +0 -25
  156. package/src/__tests__/round-trip/fixtures/simple-crud/mm.config.ts +0 -11
  157. package/src/__tests__/round-trip/fixtures/simple-crud/models/task.ts +0 -32
  158. package/src/__tests__/round-trip/fixtures/view-heavy/main.workflow.tsx +0 -79
  159. package/src/__tests__/round-trip/fixtures/view-heavy/mm.config.ts +0 -10
  160. package/src/__tests__/round-trip/round-trip.test.ts +0 -2598
  161. package/src/__tests__/round-trip-ir.test.ts +0 -300
  162. package/src/__tests__/round-trip.test.ts +0 -1212
  163. package/src/__tests__/route-merging.test.ts +0 -372
  164. package/src/__tests__/router-composition.test.ts +0 -489
  165. package/src/__tests__/router-extractor.test.ts +0 -176
  166. package/src/__tests__/server-action-extractor.test.ts +0 -128
  167. package/src/__tests__/smart-type-inference.test.ts +0 -365
  168. package/src/__tests__/source-envelope.test.ts +0 -284
  169. package/src/__tests__/source-fidelity.test.ts +0 -516
  170. package/src/__tests__/state-extractor.test.ts +0 -115
  171. package/src/__tests__/strict-mode.test.ts +0 -227
  172. package/src/__tests__/transition-effect-extractor.test.ts +0 -119
  173. package/src/__tests__/transition-extractor.test.ts +0 -68
  174. package/src/__tests__/ts-to-expression.test.ts +0 -462
  175. package/src/__tests__/type-generator.test.ts +0 -201
  176. package/src/__tests__/uber-validation.test.ts +0 -502
  177. package/src/action-compiler.ts +0 -361
  178. package/src/babel/emitters/experience-transform.ts +0 -199
  179. package/src/babel/emitters/ir-to-tsx-emitter.ts +0 -110
  180. package/src/babel/emitters/pure-form-emitter.ts +0 -1023
  181. package/src/babel/emitters/runtime-glue-emitter.ts +0 -39
  182. package/src/babel/extractors/change-extractor.ts +0 -199
  183. package/src/babel/extractors/component-extractor.ts +0 -907
  184. package/src/babel/extractors/computed-extractor.ts +0 -262
  185. package/src/babel/extractors/context-extractor.ts +0 -277
  186. package/src/babel/extractors/during-extractor.ts +0 -295
  187. package/src/babel/extractors/effect-extractor.ts +0 -340
  188. package/src/babel/extractors/event-extractor.ts +0 -235
  189. package/src/babel/extractors/grammar-island-extractor.ts +0 -302
  190. package/src/babel/extractors/model-extractor.ts +0 -1018
  191. package/src/babel/extractors/router-extractor.ts +0 -303
  192. package/src/babel/extractors/server-action-extractor.ts +0 -173
  193. package/src/babel/extractors/server-action-hook-extractor.ts +0 -72
  194. package/src/babel/extractors/server-state-extractor.ts +0 -88
  195. package/src/babel/extractors/state-extractor.ts +0 -214
  196. package/src/babel/extractors/transition-effect-extractor.ts +0 -176
  197. package/src/babel/extractors/transition-extractor.ts +0 -143
  198. package/src/babel/index.ts +0 -24
  199. package/src/babel/transpilers/ts-to-expression.ts +0 -674
  200. package/src/babel/visitor.ts +0 -807
  201. package/src/cli/auth.ts +0 -255
  202. package/src/cli/build.ts +0 -288
  203. package/src/cli/deploy.ts +0 -206
  204. package/src/cli/index.ts +0 -328
  205. package/src/cli/installer.ts +0 -261
  206. package/src/cli/lock-file.ts +0 -94
  207. package/src/cli/mmrc.ts +0 -22
  208. package/src/cli/pull.ts +0 -172
  209. package/src/cli/registry-client.ts +0 -175
  210. package/src/cli/test.ts +0 -397
  211. package/src/cli/type-generator.ts +0 -243
  212. package/src/codemod/__tests__/forward.test.ts +0 -239
  213. package/src/codemod/__tests__/reverse.test.ts +0 -145
  214. package/src/codemod/__tests__/round-trip.test.ts +0 -137
  215. package/src/codemod/annotation.ts +0 -97
  216. package/src/codemod/classify.ts +0 -197
  217. package/src/codemod/cli.ts +0 -207
  218. package/src/codemod/control-flow.ts +0 -409
  219. package/src/codemod/forward.ts +0 -244
  220. package/src/codemod/import-manager.ts +0 -171
  221. package/src/codemod/index.ts +0 -120
  222. package/src/codemod/reverse.ts +0 -197
  223. package/src/codemod/rules.ts +0 -174
  224. package/src/codemod/state-transform.ts +0 -126
  225. package/src/decompiler/ast-builder.ts +0 -538
  226. package/src/decompiler/config-generator.ts +0 -151
  227. package/src/decompiler/index.ts +0 -315
  228. package/src/decompiler/project-decompiler.ts +0 -1776
  229. package/src/decompiler/project.ts +0 -862
  230. package/src/decompiler/split-strategy.ts +0 -140
  231. package/src/decompiler/state-emitter.ts +0 -1053
  232. package/src/decompiler/sx-emitter.ts +0 -318
  233. package/src/decompiler/workspace-hydrator.ts +0 -189
  234. package/src/dev-server.ts +0 -238
  235. package/src/envelope/fs-tree.ts +0 -217
  236. package/src/envelope/source-envelope.ts +0 -264
  237. package/src/envelope.ts +0 -315
  238. package/src/incremental-compiler.ts +0 -401
  239. package/src/index.ts +0 -99
  240. package/src/model-compiler.ts +0 -277
  241. package/src/project-compiler.ts +0 -1629
  242. package/src/route-extractor.ts +0 -333
  243. package/src/testing/index.ts +0 -32
  244. package/src/testing/snapshot.ts +0 -252
  245. package/src/testing/test-utils.ts +0 -226
  246. package/src/types.ts +0 -68
  247. package/src/vite/index.ts +0 -288
  248. package/test-compile.mjs +0 -142
  249. package/tsconfig.json +0 -25
  250. package/tsup.config.ts +0 -23
  251. package/vitest.config.ts +0 -9
@@ -1,1023 +0,0 @@
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
- }