@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,1053 +0,0 @@
1
- /**
2
- * state-emitter — converts IR field/state/transition declarations back to hook calls.
3
- *
4
- * This is the inverse of state-extractor, effect-extractor, and transition-extractor.
5
- *
6
- * Conversions:
7
- * IRFieldDefinition → const [name, setName] = useState(defaultValue)
8
- * IRStateDefinition → useOnEnter('state', () => { ... })
9
- * useOnExit('state', () => { ... })
10
- * IRTransitionDefinition → const transName = useTransition('name', { from, to, ... })
11
- *
12
- * Handles all known action types including set_field, emit_event, call_workflow,
13
- * spawn_instance, http_request, delay, notify, and log.
14
- */
15
-
16
- import * as t from '@babel/types';
17
- import type {
18
- IRFieldDefinition,
19
- IRStateDefinition,
20
- IRTransitionDefinition,
21
- IRActionDefinition,
22
- IRConditionDefinition,
23
- IRExperienceNode,
24
- } from '@mindmatrix/player-core';
25
- import { valueToExpression } from './sx-emitter';
26
- import type { ImportTracker } from './index';
27
-
28
- // =============================================================================
29
- // Name Helpers
30
- // =============================================================================
31
-
32
- function toCamelCase(str: string): string {
33
- return str.replace(/[-_]([a-z])/g, (_, c: string) => c.toUpperCase());
34
- }
35
-
36
- function toPascalCase(str: string): string {
37
- const camel = toCamelCase(str);
38
- return camel.charAt(0).toUpperCase() + camel.slice(1);
39
- }
40
-
41
- // =============================================================================
42
- // Field → useState()
43
- // =============================================================================
44
-
45
- /**
46
- * IR field type → TypeScript type annotation.
47
- * Returns null for types where inference is sufficient.
48
- * When the field has validation.options, emits a union type.
49
- */
50
- function fieldTypeAnnotation(field: IRFieldDefinition): t.TSType | null {
51
- // Check for options → union type
52
- const f = field as unknown as Record<string, unknown>;
53
- const validation = f.validation as Record<string, unknown> | undefined;
54
- const options = (validation?.options as string[] | undefined)
55
- || ((f.metadata as Record<string, unknown> | undefined)?.options as string[] | undefined)
56
- || (f.options as string[] | undefined);
57
-
58
- if (options && Array.isArray(options) && options.length > 0
59
- && (field.type === 'select' || field.type === 'text')) {
60
- return t.tsUnionType(
61
- options.map(o => t.tsLiteralType(t.stringLiteral(String(o))))
62
- );
63
- }
64
-
65
- switch (field.type) {
66
- case 'text':
67
- case 'rich_text':
68
- case 'email':
69
- case 'url':
70
- case 'phone':
71
- case 'color':
72
- return t.tsStringKeyword();
73
- case 'number':
74
- case 'currency':
75
- case 'percentage':
76
- case 'rating':
77
- case 'duration':
78
- case 'auto_number':
79
- return t.tsNumberKeyword();
80
- case 'boolean':
81
- return t.tsBooleanKeyword();
82
- case 'date':
83
- case 'datetime':
84
- case 'created_at':
85
- case 'updated_at':
86
- return t.tsTypeReference(t.identifier('Date'));
87
- case 'select':
88
- return t.tsStringKeyword();
89
- case 'multi_select':
90
- return t.tsArrayType(t.tsStringKeyword()); // string[]
91
- case 'json':
92
- return null; // Inferred from default
93
- default:
94
- return null;
95
- }
96
- }
97
-
98
- /**
99
- * Emits `const [fieldName, setFieldName] = useState(defaultValue)` statements
100
- * for each field in the IR.
101
- *
102
- * Ephemeral fields get `{ ephemeral: true }` as second argument.
103
- */
104
- export function emitFieldDeclarations(
105
- fields: IRFieldDefinition[],
106
- imports: ImportTracker,
107
- ): t.Statement[] {
108
- if (fields.length === 0) return [];
109
-
110
- addImport(imports, '@mindmatrix/react', 'useState');
111
- const statements: t.Statement[] = [];
112
-
113
- for (const field of fields) {
114
- // Skip computed fields — they're handled separately
115
- if (field.computed) continue;
116
-
117
- const camelName = toCamelCase(field.name);
118
- const setter = `set${toPascalCase(field.name)}`;
119
-
120
- // Default value expression — use explicit default if set, otherwise infer
121
- // from field type. Preserve null as a valid explicit default (useState(null)
122
- // is valid JS/TS) to keep model file and useState in agreement.
123
- const defaultExpr = (field.default_value !== undefined)
124
- ? valueToExpression(field.default_value)
125
- : inferDefaultFromType(field.type);
126
-
127
- // Build useState arguments
128
- const args: t.Expression[] = [defaultExpr];
129
-
130
- // Ephemeral scope → pass options object
131
- if (field.state_home?.scope === 'ephemeral') {
132
- args.push(t.objectExpression([
133
- t.objectProperty(t.identifier('ephemeral'), t.booleanLiteral(true))
134
- ]));
135
- }
136
-
137
- // const [name, setName] = useState(default)
138
- const declaration = t.variableDeclaration('const', [
139
- t.variableDeclarator(
140
- t.arrayPattern([
141
- t.identifier(camelName),
142
- t.identifier(setter),
143
- ]),
144
- t.callExpression(t.identifier('useState'), args),
145
- ),
146
- ]);
147
-
148
- // Add type annotation if non-obvious — skip when default is null since the
149
- // type is ambiguous and adding an annotation would cause source instability
150
- if (field.default_value !== null) {
151
- const tsType = fieldTypeAnnotation(field);
152
- if (tsType) {
153
- const callExpr = (declaration.declarations[0].init as t.CallExpression);
154
- callExpr.typeParameters = t.tsTypeParameterInstantiation([tsType]);
155
- }
156
- }
157
-
158
- statements.push(declaration);
159
- }
160
-
161
- return statements;
162
- }
163
-
164
- /**
165
- * Infers a sensible default value expression from the field type.
166
- */
167
- function inferDefaultFromType(fieldType: string): t.Expression {
168
- switch (fieldType) {
169
- case 'text':
170
- case 'rich_text':
171
- case 'email':
172
- case 'url':
173
- case 'phone':
174
- case 'color':
175
- case 'select':
176
- return t.stringLiteral('');
177
- case 'number':
178
- case 'currency':
179
- case 'percentage':
180
- case 'rating':
181
- case 'duration':
182
- case 'auto_number':
183
- return t.numericLiteral(0);
184
- case 'boolean':
185
- return t.booleanLiteral(false);
186
- case 'multi_select':
187
- return t.arrayExpression([]);
188
- case 'json':
189
- return t.objectExpression([]);
190
- default:
191
- return t.nullLiteral();
192
- }
193
- }
194
-
195
- // =============================================================================
196
- // State Effects → useOnEnter / useOnExit
197
- // =============================================================================
198
-
199
- /**
200
- * Emits useOnEnter/useOnExit calls for states that have entry/exit actions.
201
- */
202
- export function emitStateEffects(
203
- states: IRStateDefinition[],
204
- imports: ImportTracker,
205
- ): t.Statement[] {
206
- const statements: t.Statement[] = [];
207
-
208
- for (const state of states) {
209
- // useOnEnter
210
- if (state.on_enter.length > 0) {
211
- addImport(imports, '@mindmatrix/react', 'useOnEnter');
212
- statements.push(
213
- t.expressionStatement(
214
- t.callExpression(t.identifier('useOnEnter'), [
215
- t.stringLiteral(state.name),
216
- emitActionCallback(state.on_enter),
217
- ])
218
- )
219
- );
220
- }
221
-
222
- // useOnExit
223
- if (state.on_exit.length > 0) {
224
- addImport(imports, '@mindmatrix/react', 'useOnExit');
225
- statements.push(
226
- t.expressionStatement(
227
- t.callExpression(t.identifier('useOnExit'), [
228
- t.stringLiteral(state.name),
229
- emitActionCallback(state.on_exit),
230
- ])
231
- )
232
- );
233
- }
234
-
235
- // During actions → useWhileIn(stateName, intervalMs, callback)
236
- if (state.during.length > 0) {
237
- addImport(imports, '@mindmatrix/react', 'useWhileIn');
238
- for (const during of state.during) {
239
- const args: t.Expression[] = [
240
- t.stringLiteral(state.name),
241
- ];
242
-
243
- // Interval comes BEFORE callback: useWhileIn('state', 30000, () => {...})
244
- if (during.interval_ms) {
245
- args.push(t.numericLiteral(during.interval_ms));
246
- }
247
-
248
- args.push(emitActionCallback(during.actions));
249
-
250
- statements.push(
251
- t.expressionStatement(
252
- t.callExpression(t.identifier('useWhileIn'), args)
253
- )
254
- );
255
- }
256
- }
257
- }
258
-
259
- return statements;
260
- }
261
-
262
- // =============================================================================
263
- // Transitions → useTransition()
264
- // =============================================================================
265
-
266
- /**
267
- * Emits `const transName = useTransition('name', { from, to, ... })` declarations.
268
- *
269
- * Includes a heuristic to fix a known compiler bug: when all transitions share
270
- * the same `from` state (always the first state), the actual source state is
271
- * inferred from the transition name, which by convention equals the source state.
272
- */
273
- export function emitTransitionDeclarations(
274
- transitions: IRTransitionDefinition[],
275
- imports: ImportTracker,
276
- ): t.Statement[] {
277
- if (transitions.length === 0) return [];
278
-
279
- addImport(imports, '@mindmatrix/react', 'useTransition');
280
-
281
- // Detect the "all same from" compiler bug: if every transition has the same
282
- // single `from` value, the compiler stored the first state for all of them.
283
- // In that case, use transition.name as the actual source state.
284
- const correctedTransitions = correctFromFields(transitions);
285
- const statements: t.Statement[] = [];
286
-
287
- for (const transition of correctedTransitions) {
288
- const varName = toCamelCase(transition.name);
289
-
290
- // Build config object
291
- const configProps: t.ObjectProperty[] = [];
292
-
293
- // from: string | string[] — normalize to array first
294
- const fromArr = normalizeFrom(transition.from);
295
-
296
- if (fromArr.length === 1) {
297
- configProps.push(
298
- t.objectProperty(t.identifier('from'), t.stringLiteral(fromArr[0]))
299
- );
300
- } else if (fromArr.length > 1) {
301
- configProps.push(
302
- t.objectProperty(
303
- t.identifier('from'),
304
- t.arrayExpression(fromArr.map(s => t.stringLiteral(s)))
305
- )
306
- );
307
- }
308
-
309
- // to: string
310
- configProps.push(
311
- t.objectProperty(t.identifier('to'), t.stringLiteral(transition.to))
312
- );
313
-
314
- // conditions
315
- if (transition.conditions && transition.conditions.length > 0) {
316
- configProps.push(
317
- t.objectProperty(
318
- t.identifier('when'),
319
- emitConditionExpression(transition.conditions)
320
- )
321
- );
322
- }
323
-
324
- // roles
325
- if (transition.roles && transition.roles.length > 0) {
326
- configProps.push(
327
- t.objectProperty(
328
- t.identifier('roles'),
329
- t.arrayExpression(transition.roles.map(r => t.stringLiteral(r)))
330
- )
331
- );
332
- }
333
-
334
- // auto
335
- if (transition.auto) {
336
- configProps.push(
337
- t.objectProperty(t.identifier('auto'), t.booleanLiteral(true))
338
- );
339
- }
340
-
341
- // required_fields
342
- if (transition.required_fields && transition.required_fields.length > 0) {
343
- configProps.push(
344
- t.objectProperty(
345
- t.identifier('requiredFields'),
346
- t.arrayExpression(transition.required_fields.map(f => t.stringLiteral(f)))
347
- )
348
- );
349
- }
350
-
351
- // const transName = useTransition('name', { from, to, ... })
352
- statements.push(
353
- t.variableDeclaration('const', [
354
- t.variableDeclarator(
355
- t.identifier(varName),
356
- t.callExpression(t.identifier('useTransition'), [
357
- t.stringLiteral(transition.name),
358
- t.objectExpression(configProps),
359
- ])
360
- ),
361
- ])
362
- );
363
- }
364
-
365
- return statements;
366
- }
367
-
368
- // =============================================================================
369
- // Action → Callback Body
370
- // =============================================================================
371
-
372
- /**
373
- * Converts an array of IR action definitions into an arrow function callback.
374
- *
375
- * Handles all known action types with proper JS emission.
376
- * Unknown types fall back to a runtime-safe `void 0` with a comment.
377
- */
378
- function emitActionCallback(actions: IRActionDefinition[]): t.ArrowFunctionExpression {
379
- const body: t.Statement[] = [];
380
-
381
- for (const action of actions) {
382
- const stmt = emitSingleAction(action);
383
- if (stmt) body.push(stmt);
384
- }
385
-
386
- if (body.length === 0) {
387
- body.push(t.emptyStatement());
388
- }
389
-
390
- return t.arrowFunctionExpression([], t.blockStatement(body));
391
- }
392
-
393
- /**
394
- * Emits a single IR action as a JS statement.
395
- */
396
- function emitSingleAction(action: IRActionDefinition): t.Statement | null {
397
- switch (action.type) {
398
- case 'set_field': {
399
- if (!action.config.field) return null;
400
- const setter = `set${toPascalCase(String(action.config.field))}`;
401
- const expr = action.config.expression
402
- ? t.identifier(String(action.config.expression))
403
- : valueToExpression(action.config.value ?? null);
404
- return t.expressionStatement(
405
- t.callExpression(t.identifier(setter), [expr])
406
- );
407
- }
408
-
409
- case 'log_event':
410
- case 'log': {
411
- const msg = action.config.message ?? action.config.event ?? action.type;
412
- return t.expressionStatement(
413
- t.callExpression(
414
- t.memberExpression(t.identifier('console'), t.identifier('log')),
415
- [t.stringLiteral(String(msg))]
416
- )
417
- );
418
- }
419
-
420
- case 'emit_event': {
421
- const eventName = String(action.config.event ?? action.config.name ?? 'unknown');
422
- const args: t.Expression[] = [t.stringLiteral(eventName)];
423
- if (action.config.payload) {
424
- args.push(valueToExpression(action.config.payload));
425
- }
426
- return t.expressionStatement(
427
- t.callExpression(t.identifier('emitEvent'), args)
428
- );
429
- }
430
-
431
- case 'call_workflow': {
432
- const slug = String(action.config.slug ?? action.config.workflow ?? 'unknown');
433
- const args: t.Expression[] = [t.stringLiteral(slug)];
434
- if (action.config.params) {
435
- args.push(valueToExpression(action.config.params));
436
- }
437
- return t.expressionStatement(
438
- t.callExpression(t.identifier('callWorkflow'), args)
439
- );
440
- }
441
-
442
- case 'spawn_instance':
443
- case 'spawn_subworkflow': {
444
- const slug = String(action.config.slug ?? action.config.workflow ?? 'unknown');
445
- const args: t.Expression[] = [t.stringLiteral(slug)];
446
- if (action.config.params || action.config.input) {
447
- args.push(valueToExpression(action.config.params ?? action.config.input));
448
- }
449
- return t.expressionStatement(
450
- t.callExpression(t.identifier('spawnInstance'), args)
451
- );
452
- }
453
-
454
- case 'http_request':
455
- case 'webhook':
456
- case 'call_webhook': {
457
- const url = String(action.config.url ?? '');
458
- const method = String(action.config.method ?? 'POST');
459
- return t.expressionStatement(
460
- t.callExpression(t.identifier('fetch'), [
461
- t.stringLiteral(url),
462
- t.objectExpression([
463
- t.objectProperty(t.identifier('method'), t.stringLiteral(method)),
464
- ]),
465
- ])
466
- );
467
- }
468
-
469
- case 'delay': {
470
- const ms = Number(action.config.duration_ms ?? action.config.delay_ms ?? 1000);
471
- return t.expressionStatement(
472
- t.awaitExpression(
473
- t.callExpression(
474
- t.identifier('delay'),
475
- [t.numericLiteral(ms)]
476
- )
477
- )
478
- );
479
- }
480
-
481
- case 'notify':
482
- case 'send_notification': {
483
- const msg = String(action.config.message ?? action.config.body ?? '');
484
- return t.expressionStatement(
485
- t.callExpression(t.identifier('notify'), [t.stringLiteral(msg)])
486
- );
487
- }
488
-
489
- case 'noop':
490
- return null;
491
-
492
- default: {
493
- // Unknown action type — emit as commented void expression
494
- const comment = ` ${action.type}(${JSON.stringify(action.config)}) `;
495
- const voidExpr = t.unaryExpression('void', t.numericLiteral(0));
496
- t.addComment(voidExpr, 'leading', comment, false);
497
- return t.expressionStatement(voidExpr);
498
- }
499
- }
500
- }
501
-
502
- // =============================================================================
503
- // Condition → Expression
504
- // =============================================================================
505
-
506
- /**
507
- * Converts IR condition definitions to a guard expression string.
508
- *
509
- * Uses the `expression` field directly if present.
510
- * Falls back to field/operator/value comparison. Supports AND/OR compounds.
511
- */
512
- function emitConditionExpression(conditions: IRConditionDefinition[]): t.Expression {
513
- if (conditions.length === 1) {
514
- return emitSingleCondition(conditions[0]);
515
- }
516
-
517
- // Multiple conditions → AND them
518
- let result = emitSingleCondition(conditions[0]);
519
- for (let i = 1; i < conditions.length; i++) {
520
- result = t.logicalExpression('&&', result, emitSingleCondition(conditions[i]));
521
- }
522
- return result;
523
- }
524
-
525
- function emitSingleCondition(cond: IRConditionDefinition): t.Expression {
526
- // Expression-based condition
527
- if (cond.expression) {
528
- return t.identifier(cond.expression);
529
- }
530
-
531
- // Field/operator/value condition
532
- if (cond.field && cond.operator) {
533
- const fieldExpr = t.identifier(toCamelCase(cond.field));
534
- const valueExpr = valueToExpression(cond.value);
535
-
536
- const opMap: Record<string, t.BinaryExpression['operator']> = {
537
- eq: '===',
538
- ne: '!==',
539
- gt: '>',
540
- gte: '>=',
541
- lt: '<',
542
- lte: '<=',
543
- };
544
-
545
- const jsOp = opMap[cond.operator];
546
- if (jsOp) {
547
- return t.binaryExpression(jsOp, fieldExpr, valueExpr);
548
- }
549
-
550
- // Special operators
551
- if (cond.operator === 'is_set') {
552
- return t.binaryExpression('!==', fieldExpr, t.nullLiteral());
553
- }
554
- if (cond.operator === 'is_empty') {
555
- return t.binaryExpression('===', fieldExpr, t.nullLiteral());
556
- }
557
- if (cond.operator === 'contains' && typeof cond.value === 'string') {
558
- return t.callExpression(
559
- t.memberExpression(fieldExpr, t.identifier('includes')),
560
- [t.stringLiteral(cond.value)]
561
- );
562
- }
563
- if (cond.operator === 'in' && Array.isArray(cond.value)) {
564
- return t.callExpression(
565
- t.memberExpression(
566
- t.arrayExpression(cond.value.map(v => valueToExpression(v))),
567
- t.identifier('includes')
568
- ),
569
- [fieldExpr]
570
- );
571
- }
572
- }
573
-
574
- // OR/AND compound
575
- if (cond.OR && cond.OR.length > 0) {
576
- let result = emitSingleCondition(cond.OR[0]);
577
- for (let i = 1; i < cond.OR.length; i++) {
578
- result = t.logicalExpression('||', result, emitSingleCondition(cond.OR[i]));
579
- }
580
- return result;
581
- }
582
- if (cond.AND && cond.AND.length > 0) {
583
- return emitConditionExpression(cond.AND);
584
- }
585
-
586
- // Fallback
587
- return t.booleanLiteral(true);
588
- }
589
-
590
- // =============================================================================
591
- // Roles → useRole()
592
- // =============================================================================
593
-
594
- /**
595
- * Emits `const varName = useRole('roleName')` declarations.
596
- *
597
- * Role dependencies are stored in metadata.roleDependencies (string[]).
598
- * Variable names are generated from role names: 'admin' → 'isAdmin'.
599
- */
600
- export function emitRoleDeclarations(
601
- metadata: Record<string, unknown> | undefined,
602
- imports: ImportTracker,
603
- ): t.Statement[] {
604
- const roleDeps = metadata?.roleDependencies as string[] | undefined;
605
- if (!roleDeps || roleDeps.length === 0) return [];
606
-
607
- addImport(imports, '@mindmatrix/react', 'useRole');
608
- const statements: t.Statement[] = [];
609
-
610
- for (const role of roleDeps) {
611
- const varName = `is${toPascalCase(role)}`;
612
- statements.push(
613
- t.variableDeclaration('const', [
614
- t.variableDeclarator(
615
- t.identifier(varName),
616
- t.callExpression(t.identifier('useRole'), [t.stringLiteral(role)]),
617
- ),
618
- ])
619
- );
620
- }
621
-
622
- return statements;
623
- }
624
-
625
- // =============================================================================
626
- // Data Sources → useQuery() / useMutation()
627
- // =============================================================================
628
-
629
- /**
630
- * Emits `const { data: varName } = useQuery('slug', { ...opts })` declarations.
631
- *
632
- * Data sources come from metadata.dataSources (IRWorkflowDataSource[]).
633
- * Mutation targets come from metadata.mutationTargets (string[]).
634
- */
635
- export function emitQueryDeclarations(
636
- metadata: Record<string, unknown> | undefined,
637
- imports: ImportTracker,
638
- ): t.Statement[] {
639
- const statements: t.Statement[] = [];
640
-
641
- // useQuery declarations
642
- const dataSources = metadata?.dataSources as Array<{
643
- type: string;
644
- name: string;
645
- slug?: string;
646
- query?: string;
647
- filter?: Record<string, unknown>;
648
- sort?: string;
649
- search?: string;
650
- searchFields?: string[];
651
- facets?: string[];
652
- groupBy?: string;
653
- aggregate?: string;
654
- pageSize?: number;
655
- }> | undefined;
656
-
657
- // Model imports map: slug → relative import path (set by project-decompiler)
658
- const modelImports = metadata?.modelImports as Record<string, string> | undefined;
659
- const addedModelImports = new Set<string>();
660
-
661
- if (dataSources && dataSources.length > 0) {
662
- addImport(imports, '@mindmatrix/react', 'useQuery');
663
- const usedVarNames = new Set<string>();
664
-
665
- for (const ds of dataSources) {
666
- if (ds.type !== 'workflow') continue;
667
-
668
- const slug = ds.slug || ds.name;
669
- // Strip dotted prefixes (e.g., "driver.earningsHistory" → "earningsHistory")
670
- const baseName = ds.name.includes('.') ? ds.name.split('.').pop()! : ds.name;
671
- let varName = toCamelCase(baseName.replace(/-/g, '_'));
672
- // Deduplicate variable names (multiple queries for same slug)
673
- if (usedVarNames.has(varName)) {
674
- let suffix = 2;
675
- while (usedVarNames.has(`${varName}${suffix}`)) suffix++;
676
- varName = `${varName}${suffix}`;
677
- }
678
- usedVarNames.add(varName);
679
-
680
- // Add typed model import if available
681
- const modelPath = modelImports?.[slug];
682
- const modelVarName = modelPath ? `${toCamelCase(slug.replace(/-/g, '_'))}Model` : undefined;
683
- if (modelPath && modelVarName && !addedModelImports.has(slug)) {
684
- addImport(imports, modelPath, `default as ${modelVarName}`);
685
- addedModelImports.add(slug);
686
- }
687
-
688
- // Build options object
689
- const optionProps: t.ObjectProperty[] = [];
690
-
691
- if (ds.pageSize) {
692
- optionProps.push(
693
- t.objectProperty(t.identifier('limit'), t.numericLiteral(ds.pageSize))
694
- );
695
- }
696
- if (ds.sort) {
697
- optionProps.push(
698
- t.objectProperty(t.identifier('orderBy'), t.stringLiteral(ds.sort))
699
- );
700
- }
701
- if (ds.filter && Object.keys(ds.filter).length > 0) {
702
- optionProps.push(
703
- t.objectProperty(t.identifier('filter'), valueToExpression(ds.filter))
704
- );
705
- }
706
- if (ds.search) {
707
- optionProps.push(
708
- t.objectProperty(t.identifier('search'), t.stringLiteral(ds.search))
709
- );
710
- }
711
- if (ds.groupBy) {
712
- optionProps.push(
713
- t.objectProperty(t.identifier('groupBy'), t.stringLiteral(ds.groupBy))
714
- );
715
- }
716
-
717
- // Use typed model reference if available, otherwise string literal
718
- const queryTarget: t.Expression = modelVarName
719
- ? t.identifier(modelVarName)
720
- : t.stringLiteral(slug);
721
- const args: t.Expression[] = [queryTarget];
722
- if (optionProps.length > 0) {
723
- args.push(t.objectExpression(optionProps));
724
- }
725
-
726
- // const { data: varName } = useQuery(...)
727
- statements.push(
728
- t.variableDeclaration('const', [
729
- t.variableDeclarator(
730
- t.objectPattern([
731
- t.objectProperty(
732
- t.identifier('data'),
733
- t.identifier(varName),
734
- ),
735
- ]),
736
- t.callExpression(t.identifier('useQuery'), args),
737
- ),
738
- ])
739
- );
740
- }
741
- }
742
-
743
- // useMutation declarations
744
- const mutationTargets = metadata?.mutationTargets as string[] | undefined;
745
- if (mutationTargets && mutationTargets.length > 0) {
746
- addImport(imports, '@mindmatrix/react', 'useMutation');
747
-
748
- for (const slug of mutationTargets) {
749
- // Use typed model reference if available
750
- const modelPath = modelImports?.[slug];
751
- const modelVarName2 = modelPath ? `${toCamelCase(slug.replace(/-/g, '_'))}Model` : undefined;
752
- if (modelPath && modelVarName2 && !addedModelImports?.has(slug)) {
753
- addImport(imports, modelPath, `default as ${modelVarName2}`);
754
- addedModelImports?.add(slug);
755
- }
756
-
757
- const mutTarget: t.Expression = modelVarName2
758
- ? t.identifier(modelVarName2)
759
- : t.stringLiteral(slug);
760
- const varName = `${toCamelCase(slug.replace(/-/g, '_'))}Mutation`;
761
- statements.push(
762
- t.variableDeclaration('const', [
763
- t.variableDeclarator(
764
- t.identifier(varName),
765
- t.callExpression(t.identifier('useMutation'), [mutTarget]),
766
- ),
767
- ])
768
- );
769
- }
770
- }
771
-
772
- return statements;
773
- }
774
-
775
- // =============================================================================
776
- // Field Watchers → useOnChange()
777
- // =============================================================================
778
-
779
- /**
780
- * Emits `useOnChange('fieldName', () => { ...actions })` calls.
781
- *
782
- * Field watchers are stored in metadata.fieldWatchers.
783
- */
784
- export function emitChangeWatchers(
785
- metadata: Record<string, unknown> | undefined,
786
- imports: ImportTracker,
787
- ): t.Statement[] {
788
- const watchers = metadata?.fieldWatchers as Array<{
789
- id: string;
790
- field: string;
791
- actions: IRActionDefinition[];
792
- }> | undefined;
793
-
794
- if (!watchers || watchers.length === 0) return [];
795
-
796
- addImport(imports, '@mindmatrix/react', 'useOnChange');
797
- const statements: t.Statement[] = [];
798
-
799
- for (const watcher of watchers) {
800
- statements.push(
801
- t.expressionStatement(
802
- t.callExpression(t.identifier('useOnChange'), [
803
- t.stringLiteral(watcher.field),
804
- emitActionCallback(watcher.actions),
805
- ])
806
- )
807
- );
808
- }
809
-
810
- return statements;
811
- }
812
-
813
- // =============================================================================
814
- // Event Subscriptions → useOnEvent()
815
- // =============================================================================
816
-
817
- /**
818
- * Emits `useOnEvent('pattern', () => { ...actions })` calls.
819
- *
820
- * Global events come from definition.on_event.
821
- * State-scoped events come from state.on_event (emitted with { while: 'stateName' }).
822
- */
823
- export function emitEventSubscriptions(
824
- onEvent: Array<{ match: string; actions: Array<{ type: string; field?: string; expression?: string; message?: string }> }> | undefined,
825
- imports: ImportTracker,
826
- ): t.Statement[] {
827
- if (!onEvent || onEvent.length === 0) return [];
828
-
829
- addImport(imports, '@mindmatrix/react', 'useOnEvent');
830
- const statements: t.Statement[] = [];
831
-
832
- for (const sub of onEvent) {
833
- // Convert IROnEventAction[] to IRActionDefinition[] for the callback emitter
834
- const actions: IRActionDefinition[] = sub.actions.map((a, i) => ({
835
- id: `event_${i}`,
836
- type: a.type,
837
- mode: 'auto' as const,
838
- config: {
839
- ...(a.field && { field: a.field }),
840
- ...(a.expression && { expression: a.expression }),
841
- ...(a.message && { message: a.message }),
842
- },
843
- }));
844
-
845
- statements.push(
846
- t.expressionStatement(
847
- t.callExpression(t.identifier('useOnEvent'), [
848
- t.stringLiteral(sub.match),
849
- emitActionCallback(actions),
850
- ])
851
- )
852
- );
853
- }
854
-
855
- return statements;
856
- }
857
-
858
- // =============================================================================
859
- // Transition Effects → useOnTransition()
860
- // =============================================================================
861
-
862
- /**
863
- * Emits `useOnTransition('transitionName', () => { ...actions })` calls.
864
- *
865
- * Transition effects are stored in metadata.transitionEffects.
866
- */
867
- export function emitTransitionEffects(
868
- metadata: Record<string, unknown> | undefined,
869
- imports: ImportTracker,
870
- ): t.Statement[] {
871
- const effects = metadata?.transitionEffects as Array<{
872
- id: string;
873
- transition: string;
874
- actions: IRActionDefinition[];
875
- }> | undefined;
876
-
877
- if (!effects || effects.length === 0) return [];
878
-
879
- addImport(imports, '@mindmatrix/react', 'useOnTransition');
880
- const statements: t.Statement[] = [];
881
-
882
- for (const effect of effects) {
883
- statements.push(
884
- t.expressionStatement(
885
- t.callExpression(t.identifier('useOnTransition'), [
886
- t.stringLiteral(effect.transition),
887
- emitActionCallback(effect.actions),
888
- ])
889
- )
890
- );
891
- }
892
-
893
- return statements;
894
- }
895
-
896
- // =============================================================================
897
- // localDefaults → useState() (section-scoped variables from experience tree)
898
- // =============================================================================
899
-
900
- /**
901
- * Walks the experience tree to find localDefaults on Show/Stack nodes.
902
- * Emits additional useState() declarations for variables NOT already
903
- * declared by the definition-level fields.
904
- *
905
- * localDefaults values are either:
906
- * - Actual defaults: { period: "today", is_online: false }
907
- * - Field bindings: { payment: "payment", eta: "etaMinutes" }
908
- *
909
- * Field binding values (strings matching camelCase identifiers) use
910
- * `undefined` as the default since the runtime provides the value.
911
- */
912
- export function emitLocalDefaultDeclarations(
913
- experience: IRExperienceNode,
914
- existingFields: IRFieldDefinition[],
915
- imports: ImportTracker,
916
- ): t.Statement[] {
917
- // Collect all localDefaults from the tree
918
- const allDefaults = new Map<string, unknown>();
919
- collectAllLocalDefaults(experience, allDefaults);
920
-
921
- // Build set of existing variable names (both raw and camelCase) for dedup
922
- const existingNames = new Set<string>();
923
- for (const f of existingFields) {
924
- if (f.computed) continue;
925
- existingNames.add(f.name);
926
- existingNames.add(toCamelCase(f.name));
927
- }
928
-
929
- const emittedCamelNames = new Set<string>();
930
- const statements: t.Statement[] = [];
931
-
932
- for (const [key, value] of allDefaults) {
933
- // Skip dotted keys like "driver.today_earnings" — nested field refs
934
- if (key.includes('.')) continue;
935
- // Skip if already declared as a field (check both raw and camelCase)
936
- if (existingNames.has(key) || existingNames.has(toCamelCase(key))) continue;
937
- // Skip if already emitted from a previous localDefaults
938
- const camelName = toCamelCase(key);
939
- if (emittedCamelNames.has(camelName)) continue;
940
- emittedCamelNames.add(camelName);
941
-
942
- addImport(imports, '@mindmatrix/react', 'useState');
943
-
944
- const setter = `set${toPascalCase(key)}`;
945
-
946
- // Determine default value
947
- let defaultExpr: t.Expression;
948
- if (value === undefined || value === null) {
949
- defaultExpr = t.identifier('undefined');
950
- } else if (typeof value === 'string' && /^[a-zA-Z]\w*$/.test(value) && value !== key) {
951
- // Looks like a field binding name (e.g., "etaMinutes", "processingError")
952
- // Use undefined — the runtime provides the value
953
- defaultExpr = t.identifier('undefined');
954
- } else {
955
- defaultExpr = valueToExpression(value);
956
- }
957
-
958
- statements.push(
959
- t.variableDeclaration('const', [
960
- t.variableDeclarator(
961
- t.arrayPattern([
962
- t.identifier(camelName),
963
- t.identifier(setter),
964
- ]),
965
- t.callExpression(t.identifier('useState'), [defaultExpr]),
966
- ),
967
- ])
968
- );
969
- }
970
-
971
- return statements;
972
- }
973
-
974
- function collectAllLocalDefaults(
975
- node: IRExperienceNode,
976
- out: Map<string, unknown>,
977
- ): void {
978
- if (node.config?.localDefaults && typeof node.config.localDefaults === 'object') {
979
- const ld = node.config.localDefaults as Record<string, unknown>;
980
- for (const [key, value] of Object.entries(ld)) {
981
- if (!out.has(key)) out.set(key, value);
982
- }
983
- }
984
- if (node.children) {
985
- for (const child of node.children) {
986
- collectAllLocalDefaults(child, out);
987
- }
988
- }
989
- }
990
-
991
- // =============================================================================
992
- // Transition From-Field Correction
993
- // =============================================================================
994
-
995
- /**
996
- * Normalizes the `from` field which may be a string or string[] in the DB.
997
- */
998
- function normalizeFrom(from: string | string[]): string[] {
999
- if (Array.isArray(from)) return from;
1000
- if (typeof from === 'string') return [from];
1001
- return [];
1002
- }
1003
-
1004
- /**
1005
- * Detects and corrects the "all same from" compiler bug.
1006
- *
1007
- * When all transitions have the same single `from` value (the first state),
1008
- * but their names correspond to different states, the transition name IS
1009
- * the actual source state (convention: useTransition(from, to)).
1010
- */
1011
- function correctFromFields(
1012
- transitions: IRTransitionDefinition[],
1013
- ): IRTransitionDefinition[] {
1014
- if (transitions.length <= 1) return transitions;
1015
-
1016
- // Collect all unique `from` values
1017
- const fromValues = new Set<string>();
1018
- for (const t of transitions) {
1019
- const arr = normalizeFrom(t.from);
1020
- for (const f of arr) fromValues.add(f);
1021
- }
1022
-
1023
- // If all transitions share exactly one `from` value, it's likely the bug
1024
- if (fromValues.size !== 1) return transitions;
1025
-
1026
- // Build state set from from/to values ONLY (not transition names).
1027
- // Only apply correction if every transition name is already a known state
1028
- // from the from/to values — avoids false positives where transition names
1029
- // like "increment" happen to match because they were self-added.
1030
- const stateNames = new Set<string>([...fromValues]);
1031
- for (const t of transitions) {
1032
- stateNames.add(t.to);
1033
- }
1034
-
1035
- // Only correct if EVERY transition name is a known state
1036
- const allNamesAreStates = transitions.every(t => stateNames.has(t.name));
1037
- if (!allNamesAreStates) return transitions;
1038
-
1039
- // Apply correction: use transition name as the from state
1040
- return transitions.map(t => ({
1041
- ...t,
1042
- from: [t.name],
1043
- }));
1044
- }
1045
-
1046
- // =============================================================================
1047
- // Helpers
1048
- // =============================================================================
1049
-
1050
- function addImport(tracker: ImportTracker, source: string, name: string): void {
1051
- if (!tracker.has(source)) tracker.set(source, new Set());
1052
- tracker.get(source)!.add(name);
1053
- }