@mmapp/react-compiler 0.1.0-alpha.15 → 0.1.0-alpha.17

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 (185) hide show
  1. package/dist/{chunk-NUPJYPFU.mjs → chunk-6LAII7OP.mjs} +79 -1
  2. package/dist/{chunk-UBDNXVL2.mjs → chunk-FPAMQXKB.mjs} +89 -3
  3. package/dist/cli/index.js +240 -9
  4. package/dist/cli/index.mjs +57 -9
  5. package/dist/dev-server.js +79 -1
  6. package/dist/dev-server.mjs +1 -1
  7. package/dist/index.js +79 -1
  8. package/dist/index.mjs +1 -1
  9. package/dist/{init-2CRSUGV5.mjs → init-CJCDWI33.mjs} +119 -0
  10. package/package.json +2 -2
  11. package/dist/chunk-26U577GB.mjs +0 -3465
  12. package/dist/chunk-2FBDFAX6.mjs +0 -2362
  13. package/dist/chunk-2L4QSMXG.mjs +0 -175
  14. package/dist/chunk-2REDFOER.mjs +0 -931
  15. package/dist/chunk-3USIFFE4.mjs +0 -2190
  16. package/dist/chunk-45YMGEVT.mjs +0 -186
  17. package/dist/chunk-46YKSHQR.mjs +0 -175
  18. package/dist/chunk-4FN2AISW.mjs +0 -148
  19. package/dist/chunk-4OPI5L7G.mjs +0 -2593
  20. package/dist/chunk-4RYTKOOJ.mjs +0 -186
  21. package/dist/chunk-4XHK6FWL.mjs +0 -2058
  22. package/dist/chunk-52XHYD2V.mjs +0 -214
  23. package/dist/chunk-5FTDWKHH.mjs +0 -244
  24. package/dist/chunk-5GUFFFGL.mjs +0 -148
  25. package/dist/chunk-5RKTOVR5.mjs +0 -244
  26. package/dist/chunk-5VNJ7C6N.mjs +0 -154
  27. package/dist/chunk-5YDMOO4X.mjs +0 -214
  28. package/dist/chunk-64ZWEMLJ.mjs +0 -148
  29. package/dist/chunk-6CQOAAMV.mjs +0 -1803
  30. package/dist/chunk-6SEVAAVT.mjs +0 -3516
  31. package/dist/chunk-6XP4KSWQ.mjs +0 -2190
  32. package/dist/chunk-6YLR5ZDA.mjs +0 -2829
  33. package/dist/chunk-72QWL54I.mjs +0 -175
  34. package/dist/chunk-7B4TRI7C.mjs +0 -4835
  35. package/dist/chunk-7JRAEFRB.mjs +0 -7510
  36. package/dist/chunk-7ZKGHTNB.mjs +0 -4952
  37. package/dist/chunk-AOGY2GK6.mjs +0 -3292
  38. package/dist/chunk-AXXUXRNA.mjs +0 -1434
  39. package/dist/chunk-CHLVKMQW.mjs +0 -175
  40. package/dist/chunk-CKGOZAB7.mjs +0 -939
  41. package/dist/chunk-D34RAZUX.mjs +0 -2223
  42. package/dist/chunk-DE3ZGQAC.mjs +0 -148
  43. package/dist/chunk-DMCY3BBG.mjs +0 -1933
  44. package/dist/chunk-DPIK3PJS.mjs +0 -244
  45. package/dist/chunk-E5IVH4RE.mjs +0 -186
  46. package/dist/chunk-E6FZNUR5.mjs +0 -4953
  47. package/dist/chunk-EJRBDQDP.mjs +0 -2607
  48. package/dist/chunk-ELO4TXJL.mjs +0 -186
  49. package/dist/chunk-EO6SYNCG.mjs +0 -175
  50. package/dist/chunk-EQGA6A6D.mjs +0 -121
  51. package/dist/chunk-EY2CSXYA.mjs +0 -822
  52. package/dist/chunk-FIQ65CDR.mjs +0 -925
  53. package/dist/chunk-FKRO52XH.mjs +0 -3446
  54. package/dist/chunk-FL4YAKU6.mjs +0 -4941
  55. package/dist/chunk-FOZXJFAR.mjs +0 -186
  56. package/dist/chunk-FX6URXWN.mjs +0 -186
  57. package/dist/chunk-FYT47UBU.mjs +0 -5076
  58. package/dist/chunk-G7SMOWOL.mjs +0 -828
  59. package/dist/chunk-GCLGPOJZ.mjs +0 -148
  60. package/dist/chunk-GGB4G5YY.mjs +0 -175
  61. package/dist/chunk-GXB4JOP7.mjs +0 -5072
  62. package/dist/chunk-HFXOUMTD.mjs +0 -175
  63. package/dist/chunk-HLRGCCIL.mjs +0 -4839
  64. package/dist/chunk-HOIUP6IF.mjs +0 -690
  65. package/dist/chunk-HRYR54PT.mjs +0 -175
  66. package/dist/chunk-HWIZ47US.mjs +0 -214
  67. package/dist/chunk-I3AU7GRD.mjs +0 -120
  68. package/dist/chunk-IB7MNPQL.mjs +0 -4953
  69. package/dist/chunk-ICSIHQCG.mjs +0 -148
  70. package/dist/chunk-ILFGMUVD.mjs +0 -1933
  71. package/dist/chunk-IPTX5MJU.mjs +0 -3223
  72. package/dist/chunk-ITGUSH2Z.mjs +0 -2783
  73. package/dist/chunk-IXHBCAMF.mjs +0 -3306
  74. package/dist/chunk-J7JUAHS4.mjs +0 -186
  75. package/dist/chunk-J7TWJ3TM.mjs +0 -2784
  76. package/dist/chunk-JDPLDGVF.mjs +0 -4810
  77. package/dist/chunk-JLA5VNQ3.mjs +0 -186
  78. package/dist/chunk-JQLWFCTM.mjs +0 -214
  79. package/dist/chunk-K53XP2DL.mjs +0 -148
  80. package/dist/chunk-K5HX2SVL.mjs +0 -1902
  81. package/dist/chunk-KFGYOOVS.mjs +0 -214
  82. package/dist/chunk-KFJJCQAL.mjs +0 -148
  83. package/dist/chunk-KFVVOS5N.mjs +0 -925
  84. package/dist/chunk-KJUIIEQE.mjs +0 -186
  85. package/dist/chunk-KNWTHRVQ.mjs +0 -175
  86. package/dist/chunk-KSG4XSZF.mjs +0 -175
  87. package/dist/chunk-L2OZ4CDV.mjs +0 -113
  88. package/dist/chunk-LF5N6DOU.mjs +0 -175
  89. package/dist/chunk-LJQCM2IM.mjs +0 -214
  90. package/dist/chunk-MIZV3TAN.mjs +0 -3293
  91. package/dist/chunk-NKKLQE5V.mjs +0 -148
  92. package/dist/chunk-NOW23XFZ.mjs +0 -186
  93. package/dist/chunk-NRXQKQ74.mjs +0 -148
  94. package/dist/chunk-NTB7OEX2.mjs +0 -2918
  95. package/dist/chunk-NW6555WJ.mjs +0 -186
  96. package/dist/chunk-O4AUS7EU.mjs +0 -148
  97. package/dist/chunk-OMZE6VLQ.mjs +0 -214
  98. package/dist/chunk-OPJKP747.mjs +0 -7506
  99. package/dist/chunk-OWI6XWCD.mjs +0 -3375
  100. package/dist/chunk-P4BR7WVO.mjs +0 -2190
  101. package/dist/chunk-PRUMNNDI.mjs +0 -3192
  102. package/dist/chunk-QQHVYH2X.mjs +0 -244
  103. package/dist/chunk-QTBD5B3F.mjs +0 -148
  104. package/dist/chunk-R57T26RR.mjs +0 -734
  105. package/dist/chunk-S5QLWLLT.mjs +0 -186
  106. package/dist/chunk-SCWGT2FY.mjs +0 -2190
  107. package/dist/chunk-SKSDPPNT.mjs +0 -3788
  108. package/dist/chunk-SMKJUSB3.mjs +0 -2190
  109. package/dist/chunk-SP2YUS33.mjs +0 -186
  110. package/dist/chunk-SU4E6E7B.mjs +0 -3153
  111. package/dist/chunk-SYUUKW5A.mjs +0 -3379
  112. package/dist/chunk-THFYE5ZX.mjs +0 -244
  113. package/dist/chunk-UDDTWG5J.mjs +0 -734
  114. package/dist/chunk-UL2XZEMA.mjs +0 -3128
  115. package/dist/chunk-VCAY2KGM.mjs +0 -175
  116. package/dist/chunk-VLTKQDJ3.mjs +0 -244
  117. package/dist/chunk-WBYMW4NQ.mjs +0 -3450
  118. package/dist/chunk-WECAV6QB.mjs +0 -148
  119. package/dist/chunk-WMKBXUCE.mjs +0 -3228
  120. package/dist/chunk-XAJ5BKKL.mjs +0 -4947
  121. package/dist/chunk-XG2X7AEA.mjs +0 -175
  122. package/dist/chunk-XG7Z23NQ.mjs +0 -148
  123. package/dist/chunk-XMWUHQVV.mjs +0 -939
  124. package/dist/chunk-XWZAOCQ7.mjs +0 -2607
  125. package/dist/chunk-XZNEDRGN.mjs +0 -3876
  126. package/dist/chunk-Y6FXYEAI.mjs +0 -10
  127. package/dist/chunk-Y6MA7ULW.mjs +0 -148
  128. package/dist/chunk-YFS6JMYO.mjs +0 -3342
  129. package/dist/chunk-YMS7Q7LG.mjs +0 -214
  130. package/dist/chunk-Z2G5RZ4H.mjs +0 -186
  131. package/dist/chunk-Z6AIQ4KL.mjs +0 -113
  132. package/dist/chunk-ZA37XTGA.mjs +0 -175
  133. package/dist/chunk-ZE3KCHBM.mjs +0 -2918
  134. package/dist/config-PL24KEWL.mjs +0 -219
  135. package/dist/dev-server-Bs_sz2DG.d.mts +0 -111
  136. package/dist/dev-server-Bs_sz2DG.d.ts +0 -111
  137. package/dist/dev-server-CjoufJ-u.d.mts +0 -109
  138. package/dist/dev-server-CjoufJ-u.d.ts +0 -109
  139. package/dist/dev-server-RmGHIntF.d.mts +0 -113
  140. package/dist/dev-server-RmGHIntF.d.ts +0 -113
  141. package/dist/engine-binary-QQUDACBJ.mjs +0 -455
  142. package/dist/envelope-DD7v0v6E.d.mts +0 -265
  143. package/dist/envelope-DD7v0v6E.d.ts +0 -265
  144. package/dist/envelope-vCVjrHlo.d.mts +0 -265
  145. package/dist/envelope-vCVjrHlo.d.ts +0 -265
  146. package/dist/index-B5gSgvnd.d.mts +0 -44
  147. package/dist/index-B5gSgvnd.d.ts +0 -44
  148. package/dist/index-Bs0MnR54.d.mts +0 -103
  149. package/dist/index-Bs0MnR54.d.ts +0 -103
  150. package/dist/index-DR0nNc_f.d.mts +0 -101
  151. package/dist/index-DR0nNc_f.d.ts +0 -101
  152. package/dist/index-revho_gS.d.mts +0 -104
  153. package/dist/index-revho_gS.d.ts +0 -104
  154. package/dist/init-7FJENUDK.mjs +0 -407
  155. package/dist/init-7JQMAAXS.mjs +0 -363
  156. package/dist/init-DQDX3QK6.mjs +0 -369
  157. package/dist/init-EHO4VQ22.mjs +0 -369
  158. package/dist/init-IXEE2RCF.mjs +0 -340
  159. package/dist/init-UC3FWPIW.mjs +0 -367
  160. package/dist/init-UNSMVKIK.mjs +0 -366
  161. package/dist/init-UNV5XIDE.mjs +0 -367
  162. package/dist/project-compiler-2P4N4DR7.mjs +0 -10
  163. package/dist/project-compiler-D2LCC27O.mjs +0 -10
  164. package/dist/project-compiler-EGJUTAJU.mjs +0 -10
  165. package/dist/project-compiler-EJ3GANJE.mjs +0 -10
  166. package/dist/project-compiler-LOQKVRZJ.mjs +0 -10
  167. package/dist/project-compiler-NNK32MPG.mjs +0 -10
  168. package/dist/project-compiler-OP2VVGJQ.mjs +0 -10
  169. package/dist/project-compiler-RQ6OQKRM.mjs +0 -10
  170. package/dist/project-compiler-VFR6CSDX.mjs +0 -10
  171. package/dist/project-compiler-VWNNCHGO.mjs +0 -10
  172. package/dist/project-compiler-XVAAU4C5.mjs +0 -10
  173. package/dist/project-compiler-YES5FGMD.mjs +0 -10
  174. package/dist/project-compiler-ZKMQDLGU.mjs +0 -10
  175. package/dist/project-decompiler-5GY2KSG4.mjs +0 -7
  176. package/dist/project-decompiler-FLXCEJHS.mjs +0 -7
  177. package/dist/project-decompiler-US7GAVIC.mjs +0 -7
  178. package/dist/project-decompiler-VLPR22QF.mjs +0 -7
  179. package/dist/pull-A2QUHW4K.mjs +0 -109
  180. package/dist/pull-FUS5QYZS.mjs +0 -109
  181. package/dist/pull-JBEQWVPE.mjs +0 -109
  182. package/dist/pull-LD5ENLGY.mjs +0 -109
  183. package/dist/pull-P44LDRWB.mjs +0 -109
  184. package/dist/verify-BYHUKARQ.mjs +0 -1833
  185. package/dist/verify-SEIXUGN4.mjs +0 -1833
@@ -1,4839 +0,0 @@
1
- // src/babel/visitor.ts
2
- import * as t17 from "@babel/types";
3
-
4
- // src/babel/extractors/state-extractor.ts
5
- import * as t from "@babel/types";
6
- var KNOWN_TYPE_REFS = {
7
- Date: "date",
8
- URL: "url",
9
- Record: "json",
10
- Map: "json",
11
- Set: "json"
12
- };
13
- function typeNameToSlug(name) {
14
- return name.replace(/([A-Z])/g, "-$1").toLowerCase().replace(/^-/, "");
15
- }
16
- function resolveSingleType(annotation) {
17
- if (t.isTSNumberKeyword(annotation)) return "number";
18
- if (t.isTSStringKeyword(annotation)) return "text";
19
- if (t.isTSBooleanKeyword(annotation)) return "boolean";
20
- if (t.isTSTypeReference(annotation)) {
21
- const typeName = t.isIdentifier(annotation.typeName) ? annotation.typeName.name : "";
22
- if (typeName === "Array") return "multi_select";
23
- if (typeName && KNOWN_TYPE_REFS[typeName]) return KNOWN_TYPE_REFS[typeName];
24
- if (typeName) return typeNameToSlug(typeName);
25
- }
26
- if (t.isTSArrayType(annotation)) return "multi_select";
27
- if (t.isTSTypeLiteral(annotation) || t.isTSTupleType(annotation)) return "json";
28
- return null;
29
- }
30
- function inferFieldType(typeAnnotation, defaultValue) {
31
- if (typeAnnotation) {
32
- if (t.isTSUnionType(typeAnnotation)) {
33
- const allStringLiterals = typeAnnotation.types.every(
34
- (m) => t.isTSLiteralType(m) && t.isStringLiteral(m.literal)
35
- );
36
- if (allStringLiterals) return "select";
37
- const nonNullMembers = typeAnnotation.types.filter(
38
- (m) => !t.isTSNullKeyword(m) && !t.isTSUndefinedKeyword(m)
39
- );
40
- const allLiteralsExceptNull = nonNullMembers.every(
41
- (m) => t.isTSLiteralType(m) && t.isStringLiteral(m.literal)
42
- );
43
- if (allLiteralsExceptNull && nonNullMembers.length > 0) return "select";
44
- if (nonNullMembers.length === 1) {
45
- const resolved2 = resolveSingleType(nonNullMembers[0]);
46
- if (resolved2) return resolved2;
47
- }
48
- if (nonNullMembers.length > 1) return "json";
49
- }
50
- const resolved = resolveSingleType(typeAnnotation);
51
- if (resolved) return resolved;
52
- }
53
- if (defaultValue) {
54
- if (t.isNumericLiteral(defaultValue)) return "number";
55
- if (t.isStringLiteral(defaultValue)) return "text";
56
- if (t.isBooleanLiteral(defaultValue)) return "boolean";
57
- if (t.isArrayExpression(defaultValue)) return "json";
58
- if (t.isObjectExpression(defaultValue)) return "json";
59
- if (t.isNewExpression(defaultValue) && t.isIdentifier(defaultValue.callee)) {
60
- if (defaultValue.callee.name === "Date") return "date";
61
- }
62
- }
63
- return "text";
64
- }
65
- function extractDefaultValue(arg) {
66
- if (t.isNumericLiteral(arg)) return arg.value;
67
- if (t.isStringLiteral(arg)) return arg.value;
68
- if (t.isBooleanLiteral(arg)) return arg.value;
69
- if (t.isNullLiteral(arg)) return null;
70
- if (t.isArrayExpression(arg)) {
71
- return arg.elements.map(
72
- (el) => el && t.isExpression(el) ? extractDefaultValue(el) : null
73
- );
74
- }
75
- if (t.isObjectExpression(arg)) {
76
- const obj = {};
77
- arg.properties.forEach((prop) => {
78
- if (t.isObjectProperty(prop) && t.isIdentifier(prop.key) && t.isExpression(prop.value)) {
79
- obj[prop.key.name] = extractDefaultValue(prop.value);
80
- }
81
- });
82
- return obj;
83
- }
84
- return void 0;
85
- }
86
- function extractStates(path, state) {
87
- const parent = path.parentPath;
88
- if (!parent.isVariableDeclarator()) return;
89
- const id = parent.node.id;
90
- if (!t.isArrayPattern(id) || id.elements.length < 1) return;
91
- const firstElement = id.elements[0];
92
- if (!t.isIdentifier(firstElement)) return;
93
- const fieldName = firstElement.name;
94
- const args = path.node.arguments;
95
- const defaultValue = args.length > 0 && t.isExpression(args[0]) ? args[0] : null;
96
- let typeAnnotation = null;
97
- if (path.node.typeParameters && t.isTSTypeParameterInstantiation(path.node.typeParameters)) {
98
- const params = path.node.typeParameters.params;
99
- if (params.length > 0) {
100
- typeAnnotation = params[0];
101
- }
102
- }
103
- const fieldType = inferFieldType(typeAnnotation, defaultValue);
104
- const fieldDefaultValue = defaultValue ? extractDefaultValue(defaultValue) : void 0;
105
- const field = {
106
- name: fieldName,
107
- type: fieldType,
108
- default_value: fieldDefaultValue
109
- };
110
- if (fieldType === "select" && typeAnnotation && t.isTSUnionType(typeAnnotation)) {
111
- const options = typeAnnotation.types.filter((m) => t.isTSLiteralType(m) && t.isStringLiteral(m.literal)).map((m) => m.literal.value);
112
- if (options.length > 0) {
113
- field.validation = { options };
114
- }
115
- }
116
- const compilerState = state;
117
- if (!compilerState.fields) compilerState.fields = [];
118
- if (!compilerState.fields.some((f) => f.name === fieldName)) {
119
- compilerState.fields.push(field);
120
- }
121
- }
122
-
123
- // src/babel/extractors/effect-extractor.ts
124
- import * as t2 from "@babel/types";
125
- function analyzeCallbackBody(body, actionCounter) {
126
- const actions = [];
127
- for (const statement of body) {
128
- if (t2.isExpressionStatement(statement)) {
129
- const expr = statement.expression;
130
- if (t2.isCallExpression(expr) && t2.isIdentifier(expr.callee)) {
131
- const calleeName = expr.callee.name;
132
- const args = expr.arguments;
133
- if (calleeName === "setField" && args.length >= 2) {
134
- const field = t2.isStringLiteral(args[0]) ? args[0].value : void 0;
135
- const arg1 = args[1];
136
- if (field !== void 0 && !t2.isArgumentPlaceholder(arg1)) {
137
- const value = extractValue(arg1);
138
- actions.push({
139
- id: `auto_${++actionCounter.value}`,
140
- type: "set_field",
141
- mode: "auto",
142
- config: { field, value }
143
- });
144
- }
145
- } else if (calleeName === "setMemory" && args.length >= 2) {
146
- const key = t2.isStringLiteral(args[0]) ? args[0].value : void 0;
147
- const arg1 = args[1];
148
- if (key !== void 0 && !t2.isArgumentPlaceholder(arg1)) {
149
- const value = extractValue(arg1);
150
- actions.push({
151
- id: `auto_${++actionCounter.value}`,
152
- type: "set_memory",
153
- mode: "auto",
154
- config: { key, value }
155
- });
156
- }
157
- } else if (calleeName.startsWith("set") && args.length >= 1) {
158
- const fieldName = calleeName.slice(3).charAt(0).toLowerCase() + calleeName.slice(4);
159
- const arg0 = args[0];
160
- if (!t2.isArgumentPlaceholder(arg0)) {
161
- const value = extractValue(arg0);
162
- actions.push({
163
- id: `auto_${++actionCounter.value}`,
164
- type: "set_field",
165
- mode: "auto",
166
- config: { field: fieldName, value }
167
- });
168
- }
169
- }
170
- } else if (t2.isCallExpression(expr)) {
171
- const callee = expr.callee;
172
- const args = expr.arguments;
173
- if (t2.isMemberExpression(callee) && t2.isIdentifier(callee.object) && callee.object.name === "console" && t2.isIdentifier(callee.property) && callee.property.name === "log" && args.length > 0) {
174
- const arg0 = args[0];
175
- if (!t2.isArgumentPlaceholder(arg0)) {
176
- const message = extractValue(arg0);
177
- actions.push({
178
- id: `auto_${++actionCounter.value}`,
179
- type: "log_event",
180
- mode: "auto",
181
- config: { message }
182
- });
183
- }
184
- } else {
185
- actions.push({
186
- id: `auto_${++actionCounter.value}`,
187
- type: "custom",
188
- mode: "auto",
189
- config: { expression: generateCode(expr) }
190
- });
191
- }
192
- }
193
- }
194
- }
195
- return actions;
196
- }
197
- function extractValue(node) {
198
- if (t2.isNumericLiteral(node)) return node.value;
199
- if (t2.isStringLiteral(node)) return node.value;
200
- if (t2.isBooleanLiteral(node)) return node.value;
201
- if (t2.isNullLiteral(node)) return null;
202
- if (t2.isArrayExpression(node)) {
203
- return node.elements.map((el) => el && t2.isExpression(el) ? extractValue(el) : null);
204
- }
205
- if (t2.isObjectExpression(node)) {
206
- const obj = {};
207
- node.properties.forEach((prop) => {
208
- if (t2.isObjectProperty(prop) && t2.isIdentifier(prop.key) && t2.isExpression(prop.value)) {
209
- obj[prop.key.name] = extractValue(prop.value);
210
- }
211
- });
212
- return obj;
213
- }
214
- return generateCode(node);
215
- }
216
- function generateCode(node) {
217
- if (t2.isIdentifier(node)) return node.name;
218
- if (t2.isNumericLiteral(node)) return String(node.value);
219
- if (t2.isStringLiteral(node)) return `"${node.value}"`;
220
- if (t2.isBooleanLiteral(node)) return String(node.value);
221
- if (t2.isNullLiteral(node)) return "null";
222
- if (t2.isCallExpression(node) && t2.isMemberExpression(node.callee) && t2.isIdentifier(node.callee.object) && node.callee.object.name === "Date" && t2.isIdentifier(node.callee.property) && node.callee.property.name === "now") {
223
- return "now()";
224
- }
225
- if (t2.isCallExpression(node) && t2.isMemberExpression(node.callee) && t2.isNewExpression(node.callee.object) && t2.isIdentifier(node.callee.object.callee) && node.callee.object.callee.name === "Date" && t2.isIdentifier(node.callee.property) && node.callee.property.name === "toISOString") {
226
- return "now()";
227
- }
228
- if (t2.isBinaryExpression(node)) {
229
- return `(${generateCode(node.left)} ${node.operator} ${generateCode(node.right)})`;
230
- }
231
- if (t2.isLogicalExpression(node)) {
232
- return `(${generateCode(node.left)} ${node.operator} ${generateCode(node.right)})`;
233
- }
234
- if (t2.isConditionalExpression(node)) {
235
- return `(${generateCode(node.test)} ? ${generateCode(node.consequent)} : ${generateCode(node.alternate)})`;
236
- }
237
- if (t2.isUnaryExpression(node) && node.prefix) {
238
- return `${node.operator}${generateCode(node.argument)}`;
239
- }
240
- if (t2.isTemplateLiteral(node)) {
241
- return node.quasis.map((q, i) => {
242
- const raw = q.value.raw;
243
- if (i < node.expressions.length) return raw + "${" + generateCode(node.expressions[i]) + "}";
244
- return raw;
245
- }).join("");
246
- }
247
- if (t2.isMemberExpression(node)) {
248
- const obj = generateCode(node.object);
249
- if (node.computed) {
250
- return `${obj}[${generateCode(node.property)}]`;
251
- }
252
- const prop = t2.isIdentifier(node.property) ? node.property.name : "[property]";
253
- return `${obj}.${prop}`;
254
- }
255
- if (t2.isCallExpression(node)) {
256
- if (t2.isIdentifier(node.callee)) {
257
- const args = node.arguments.map((a) => generateCode(a)).join(", ");
258
- return `${node.callee.name}(${args})`;
259
- }
260
- if (t2.isMemberExpression(node.callee)) {
261
- const obj = generateCode(node.callee.object);
262
- const prop = t2.isIdentifier(node.callee.property) ? node.callee.property.name : "[method]";
263
- const args = node.arguments.map((a) => generateCode(a)).join(", ");
264
- return `${obj}.${prop}(${args})`;
265
- }
266
- }
267
- if (t2.isArrowFunctionExpression(node)) {
268
- if (t2.isExpression(node.body)) {
269
- const params = node.params;
270
- if (params.length === 1 && t2.isIdentifier(params[0])) {
271
- const paramName = params[0].name;
272
- const bodyCode = generateCode(node.body);
273
- return bodyCode.replace(new RegExp(`\\b${paramName}\\b`, "g"), "$prev");
274
- }
275
- }
276
- return "[Function]";
277
- }
278
- if (t2.isFunctionExpression(node)) return "[Function]";
279
- if (t2.isArrayExpression(node)) {
280
- const elements = node.elements.map((el) => el ? generateCode(el) : "undefined").join(", ");
281
- return `[${elements}]`;
282
- }
283
- if (t2.isObjectExpression(node)) {
284
- const props = node.properties.map((p) => {
285
- if (t2.isObjectProperty(p)) {
286
- const key = t2.isIdentifier(p.key) ? p.key.name : t2.isStringLiteral(p.key) ? `"${p.key.value}"` : "[key]";
287
- if (p.shorthand && t2.isIdentifier(p.value)) return key;
288
- return `${key}: ${generateCode(p.value)}`;
289
- }
290
- if (t2.isSpreadElement(p)) return `...${generateCode(p.argument)}`;
291
- return "";
292
- }).filter(Boolean).join(", ");
293
- return `{ ${props} }`;
294
- }
295
- if (t2.isTSAsExpression(node)) return generateCode(node.expression);
296
- if (t2.isTSNonNullExpression(node)) return generateCode(node.expression);
297
- return "[Expression]";
298
- }
299
- function ensureState(states, stateName) {
300
- if (!states.has(stateName)) {
301
- states.set(stateName, {
302
- name: stateName,
303
- type: "REGULAR",
304
- on_enter: [],
305
- during: [],
306
- on_exit: []
307
- });
308
- }
309
- return states.get(stateName);
310
- }
311
- function extractEffects(path, state) {
312
- const callee = path.node.callee;
313
- if (!t2.isIdentifier(callee)) return;
314
- const hookName = callee.name;
315
- const args = path.node.arguments;
316
- if ((hookName === "useOnEnter" || hookName === "useOnExit") && args.length >= 2) {
317
- const stateArg = args[0];
318
- const callbackArg = args[1];
319
- if (!t2.isStringLiteral(stateArg)) return;
320
- const stateName = stateArg.value;
321
- let callbackBody = [];
322
- if (t2.isArrowFunctionExpression(callbackArg) || t2.isFunctionExpression(callbackArg)) {
323
- const body = callbackArg.body;
324
- if (t2.isBlockStatement(body)) {
325
- callbackBody = body.body;
326
- } else if (t2.isExpression(body)) {
327
- callbackBody = [t2.expressionStatement(body)];
328
- }
329
- }
330
- const compilerState = state;
331
- if (!compilerState.states) compilerState.states = /* @__PURE__ */ new Map();
332
- if (!compilerState.actionCounter) compilerState.actionCounter = 0;
333
- const stateDefinition = ensureState(compilerState.states, stateName);
334
- const actions = analyzeCallbackBody(callbackBody, { value: compilerState.actionCounter });
335
- compilerState.actionCounter += actions.length;
336
- if (hookName === "useOnEnter") {
337
- stateDefinition.on_enter.push(...actions);
338
- } else if (hookName === "useOnExit") {
339
- stateDefinition.on_exit.push(...actions);
340
- }
341
- }
342
- }
343
-
344
- // src/babel/extractors/transition-extractor.ts
345
- import * as t3 from "@babel/types";
346
- function extractTransitions(path, state) {
347
- const callee = path.node.callee;
348
- if (!t3.isIdentifier(callee) || callee.name !== "useTransition") return;
349
- const args = path.node.arguments;
350
- if (args.length < 1) return;
351
- const nameArg = args[0];
352
- if (!t3.isStringLiteral(nameArg)) return;
353
- const transitionName = nameArg.value;
354
- const compilerState = state;
355
- if (!compilerState.transitions) compilerState.transitions = [];
356
- const existing = compilerState.transitions.find((tr) => tr.name === transitionName);
357
- if (existing) return;
358
- let from = [];
359
- let to = "";
360
- let roles;
361
- let requiredFields;
362
- let auto;
363
- if (args.length >= 2 && t3.isObjectExpression(args[1])) {
364
- const opts = args[1];
365
- for (const prop of opts.properties) {
366
- if (!t3.isObjectProperty(prop) || !t3.isIdentifier(prop.key)) continue;
367
- if (prop.key.name === "from") {
368
- if (t3.isArrayExpression(prop.value)) {
369
- from = prop.value.elements.filter((el) => t3.isStringLiteral(el)).map((el) => el.value);
370
- } else if (t3.isStringLiteral(prop.value)) {
371
- from = [prop.value.value];
372
- }
373
- } else if (prop.key.name === "to") {
374
- if (t3.isStringLiteral(prop.value)) {
375
- to = prop.value.value;
376
- }
377
- } else if (prop.key.name === "roles") {
378
- if (t3.isArrayExpression(prop.value)) {
379
- roles = prop.value.elements.filter((el) => t3.isStringLiteral(el)).map((el) => el.value);
380
- }
381
- } else if (prop.key.name === "requiredFields") {
382
- if (t3.isArrayExpression(prop.value)) {
383
- requiredFields = prop.value.elements.filter((el) => t3.isStringLiteral(el)).map((el) => el.value);
384
- }
385
- } else if (prop.key.name === "auto") {
386
- if (t3.isBooleanLiteral(prop.value)) {
387
- auto = prop.value.value;
388
- }
389
- }
390
- }
391
- }
392
- const transition = {
393
- name: transitionName,
394
- from,
395
- to,
396
- actions: [],
397
- conditions: [],
398
- ...roles && roles.length > 0 && { roles },
399
- ...requiredFields && requiredFields.length > 0 && { required_fields: requiredFields },
400
- ...auto !== void 0 && { auto }
401
- };
402
- compilerState.transitions.push(transition);
403
- }
404
- function inferTransitionStates(transitions, states) {
405
- const stateArray = Array.from(states.values());
406
- const startStates = stateArray.filter((s) => s.type === "START");
407
- const regularStates = stateArray.filter((s) => s.type === "REGULAR");
408
- const needsInference = transitions.filter((t18) => t18.from.length === 0 || !t18.to);
409
- if (needsInference.length === 0) return;
410
- if (startStates.length === 1 && regularStates.length > 0) {
411
- needsInference.forEach((t18, idx) => {
412
- if (t18.from.length === 0) {
413
- t18.from = [startStates[0].name];
414
- }
415
- if (!t18.to) {
416
- t18.to = regularStates[idx % regularStates.length]?.name || startStates[0].name;
417
- }
418
- });
419
- } else {
420
- const allStateNames = stateArray.map((s) => s.name);
421
- needsInference.forEach((t18, idx) => {
422
- if (t18.from.length === 0 && allStateNames.length > 0) {
423
- t18.from = [allStateNames[0]];
424
- }
425
- if (!t18.to && allStateNames.length > 1) {
426
- t18.to = allStateNames[Math.min(idx + 1, allStateNames.length - 1)];
427
- }
428
- });
429
- }
430
- }
431
-
432
- // src/babel/extractors/event-extractor.ts
433
- import * as t4 from "@babel/types";
434
- function analyzeEventCallback(body) {
435
- const actions = [];
436
- for (const statement of body) {
437
- if (t4.isExpressionStatement(statement)) {
438
- const expr = statement.expression;
439
- if (t4.isCallExpression(expr) && t4.isIdentifier(expr.callee)) {
440
- const calleeName = expr.callee.name;
441
- const args = expr.arguments;
442
- if (calleeName === "setField" && args.length >= 2) {
443
- const field = t4.isStringLiteral(args[0]) ? args[0].value : void 0;
444
- const expression = generateExpression(args[1]);
445
- if (field) {
446
- actions.push({
447
- type: "set_field",
448
- field,
449
- expression
450
- });
451
- }
452
- } else if (calleeName === "setMemory" && args.length >= 2) {
453
- const key = t4.isStringLiteral(args[0]) ? args[0].value : void 0;
454
- const expression = generateExpression(args[1]);
455
- if (key) {
456
- actions.push({
457
- type: "set_memory",
458
- key,
459
- expression
460
- });
461
- }
462
- }
463
- } else if (t4.isCallExpression(expr)) {
464
- const callee = expr.callee;
465
- const args = expr.arguments;
466
- if (t4.isMemberExpression(callee) && t4.isIdentifier(callee.object) && callee.object.name === "console" && t4.isIdentifier(callee.property) && callee.property.name === "log") {
467
- const message = args.length > 0 ? generateExpression(args[0]) : "";
468
- actions.push({
469
- type: "log_event",
470
- message
471
- });
472
- }
473
- }
474
- }
475
- }
476
- return actions;
477
- }
478
- function generateExpression(node) {
479
- if (t4.isStringLiteral(node)) return node.value;
480
- if (t4.isNumericLiteral(node)) return String(node.value);
481
- if (t4.isBooleanLiteral(node)) return String(node.value);
482
- if (t4.isNullLiteral(node)) return "null";
483
- if (t4.isIdentifier(node)) return node.name;
484
- if (t4.isBinaryExpression(node)) {
485
- return `(${generateExpression(node.left)} ${node.operator} ${generateExpression(node.right)})`;
486
- }
487
- if (t4.isLogicalExpression(node)) {
488
- return `(${generateExpression(node.left)} ${node.operator} ${generateExpression(node.right)})`;
489
- }
490
- if (t4.isConditionalExpression(node)) {
491
- return `(${generateExpression(node.test)} ? ${generateExpression(node.consequent)} : ${generateExpression(node.alternate)})`;
492
- }
493
- if (t4.isUnaryExpression(node) && node.prefix) {
494
- return `${node.operator}${generateExpression(node.argument)}`;
495
- }
496
- if (t4.isCallExpression(node) && t4.isIdentifier(node.callee)) {
497
- const args = node.arguments.map((arg) => generateExpression(arg)).join(", ");
498
- return `${node.callee.name}(${args})`;
499
- }
500
- if (t4.isCallExpression(node) && t4.isMemberExpression(node.callee)) {
501
- const obj = generateExpression(node.callee.object);
502
- const prop = t4.isIdentifier(node.callee.property) ? node.callee.property.name : "[method]";
503
- const args = node.arguments.map((arg) => generateExpression(arg)).join(", ");
504
- return `${obj}.${prop}(${args})`;
505
- }
506
- if (t4.isMemberExpression(node)) {
507
- const obj = generateExpression(node.object);
508
- if (node.computed) {
509
- const prop2 = generateExpression(node.property);
510
- return `${obj}[${prop2}]`;
511
- }
512
- const prop = t4.isIdentifier(node.property) ? node.property.name : "[property]";
513
- return `${obj}.${prop}`;
514
- }
515
- if (t4.isTemplateLiteral(node)) {
516
- return node.quasis.map((q, i) => {
517
- const raw = q.value.raw;
518
- if (i < node.expressions.length) return raw + "${" + generateExpression(node.expressions[i]) + "}";
519
- return raw;
520
- }).join("");
521
- }
522
- if (t4.isArrayExpression(node)) {
523
- const elements = node.elements.map((el) => el ? generateExpression(el) : "undefined").join(", ");
524
- return `[${elements}]`;
525
- }
526
- if (t4.isObjectExpression(node)) {
527
- const props = node.properties.map((p) => {
528
- if (t4.isObjectProperty(p)) {
529
- const key = t4.isIdentifier(p.key) ? p.key.name : t4.isStringLiteral(p.key) ? `"${p.key.value}"` : "[key]";
530
- if (p.shorthand && t4.isIdentifier(p.value)) return key;
531
- return `${key}: ${generateExpression(p.value)}`;
532
- }
533
- if (t4.isSpreadElement(p)) return `...${generateExpression(p.argument)}`;
534
- return "";
535
- }).filter(Boolean).join(", ");
536
- return `{ ${props} }`;
537
- }
538
- if (t4.isTSAsExpression(node)) return generateExpression(node.expression);
539
- if (t4.isTSNonNullExpression(node)) return generateExpression(node.expression);
540
- return "[Expression]";
541
- }
542
- function ensureState2(states, stateName) {
543
- if (!states.has(stateName)) {
544
- states.set(stateName, {
545
- name: stateName,
546
- type: "REGULAR",
547
- on_enter: [],
548
- during: [],
549
- on_exit: []
550
- });
551
- }
552
- return states.get(stateName);
553
- }
554
- function extractEvents(path, state) {
555
- const callee = path.node.callee;
556
- if (!t4.isIdentifier(callee) || callee.name !== "useOnEvent") return;
557
- const args = path.node.arguments;
558
- if (args.length < 2) return;
559
- const patternArg = args[0];
560
- const callbackArg = args[1];
561
- const optionsArg = args.length > 2 ? args[2] : null;
562
- if (!t4.isStringLiteral(patternArg)) return;
563
- const pattern = patternArg.value;
564
- let callbackBody = [];
565
- if (t4.isArrowFunctionExpression(callbackArg) || t4.isFunctionExpression(callbackArg)) {
566
- const body = callbackArg.body;
567
- if (t4.isBlockStatement(body)) {
568
- callbackBody = body.body;
569
- } else if (t4.isExpression(body)) {
570
- callbackBody = [t4.expressionStatement(body)];
571
- }
572
- }
573
- let stateName = null;
574
- if (optionsArg && t4.isObjectExpression(optionsArg)) {
575
- const whileProp = optionsArg.properties.find(
576
- (prop) => t4.isObjectProperty(prop) && t4.isIdentifier(prop.key) && prop.key.name === "while"
577
- );
578
- if (whileProp && t4.isObjectProperty(whileProp) && t4.isStringLiteral(whileProp.value)) {
579
- stateName = whileProp.value.value;
580
- }
581
- }
582
- const actions = analyzeEventCallback(callbackBody);
583
- const subscription = {
584
- match: pattern,
585
- conditions: [],
586
- actions
587
- };
588
- const compilerState = state;
589
- if (!compilerState.states) compilerState.states = /* @__PURE__ */ new Map();
590
- if (stateName) {
591
- const stateDefinition = ensureState2(compilerState.states, stateName);
592
- if (!stateDefinition.on_event) stateDefinition.on_event = [];
593
- stateDefinition.on_event.push(subscription);
594
- } else {
595
- if (!compilerState.events) compilerState.events = [];
596
- compilerState.events.push(subscription);
597
- }
598
- }
599
-
600
- // src/babel/extractors/component-extractor.ts
601
- import * as t6 from "@babel/types";
602
-
603
- // src/babel/transpilers/ts-to-expression.ts
604
- import * as t5 from "@babel/types";
605
- function transpileExpression(node, options = {}) {
606
- const ctx = new TranspileContext(options);
607
- const expr = ctx.visit(node);
608
- return { expression: expr, pure: ctx.isPure };
609
- }
610
- var TranspileContext = class {
611
- constructor(options) {
612
- this.isPure = true;
613
- this.localFieldMap = options.localFieldMap ?? /* @__PURE__ */ new Map();
614
- this.derivedVarMap = options.derivedVarMap ?? /* @__PURE__ */ new Map();
615
- this.setterToFieldMap = options.setterToFieldMap ?? /* @__PURE__ */ new Map();
616
- }
617
- /**
618
- * Emit an opaque JS fallback, marking the result as impure.
619
- */
620
- opaque(jsCode) {
621
- this.isPure = false;
622
- return `$expr(${jsCode})`;
623
- }
624
- /**
625
- * Visit an AST node and produce an mm-compute expression string.
626
- */
627
- visit(node) {
628
- if (t5.isStringLiteral(node)) return `"${node.value.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
629
- if (t5.isNumericLiteral(node)) return String(node.value);
630
- if (t5.isBooleanLiteral(node)) return String(node.value);
631
- if (t5.isNullLiteral(node)) return "null";
632
- if (t5.isIdentifier(node)) {
633
- const snakeName = this.localFieldMap.get(node.name);
634
- if (snakeName) return `$local.${snakeName}`;
635
- const derivedInit = this.derivedVarMap.get(node.name);
636
- if (derivedInit) return `(${this.visit(derivedInit)})`;
637
- if (node.name === "undefined") return "null";
638
- if (node.name === "NaN") return "null";
639
- if (node.name === "Infinity") return "null";
640
- return node.name;
641
- }
642
- if (t5.isTSAsExpression(node)) return this.visit(node.expression);
643
- if (t5.isTSNonNullExpression(node)) return this.visit(node.expression);
644
- if (t5.isTSTypeAssertion(node)) return this.visit(node.expression);
645
- if (t5.isParenthesizedExpression(node)) return `(${this.visit(node.expression)})`;
646
- if (t5.isUnaryExpression(node) && node.prefix) {
647
- return this.visitUnary(node);
648
- }
649
- if (t5.isBinaryExpression(node)) {
650
- return this.visitBinary(node);
651
- }
652
- if (t5.isLogicalExpression(node)) {
653
- return this.visitLogical(node);
654
- }
655
- if (t5.isConditionalExpression(node)) {
656
- return `if(${this.visit(node.test)}, ${this.visit(node.consequent)}, ${this.visit(node.alternate)})`;
657
- }
658
- if (t5.isMemberExpression(node) || t5.isOptionalMemberExpression(node)) {
659
- return this.visitMember(node);
660
- }
661
- if (t5.isCallExpression(node) || t5.isOptionalCallExpression(node)) {
662
- return this.visitCall(node);
663
- }
664
- if (t5.isTemplateLiteral(node)) {
665
- return this.visitTemplateLiteral(node);
666
- }
667
- if (t5.isArrayExpression(node)) {
668
- const elements = node.elements.map((el) => {
669
- if (el === null) return "null";
670
- if (t5.isSpreadElement(el)) return this.opaque(`...${this.visit(el.argument)}`);
671
- return t5.isExpression(el) ? this.visit(el) : "null";
672
- });
673
- return `[${elements.join(", ")}]`;
674
- }
675
- if (t5.isObjectExpression(node)) {
676
- return this.visitObject(node);
677
- }
678
- if (t5.isArrowFunctionExpression(node)) {
679
- return this.visitArrow(node);
680
- }
681
- if (t5.isNewExpression(node)) {
682
- return this.visitNew(node);
683
- }
684
- return this.opaque(fallbackGenerate(node));
685
- }
686
- // ---------------------------------------------------------------------------
687
- // Unary
688
- // ---------------------------------------------------------------------------
689
- visitUnary(node) {
690
- if (node.operator === "!") {
691
- return `not(${this.visit(node.argument)})`;
692
- }
693
- if (node.operator === "-") {
694
- if (t5.isNumericLiteral(node.argument)) return String(-node.argument.value);
695
- return `(0 - ${this.visit(node.argument)})`;
696
- }
697
- if (node.operator === "typeof") {
698
- return `typeof(${this.visit(node.argument)})`;
699
- }
700
- return this.opaque(`${node.operator}${fallbackGenerate(node.argument)}`);
701
- }
702
- // ---------------------------------------------------------------------------
703
- // Binary
704
- // ---------------------------------------------------------------------------
705
- visitBinary(node) {
706
- const left = this.visit(node.left);
707
- const right = this.visit(node.right);
708
- switch (node.operator) {
709
- case "===":
710
- return `(${left} == ${right})`;
711
- case "!==":
712
- return `(${left} != ${right})`;
713
- case "==":
714
- return `(${left} == ${right})`;
715
- case "!=":
716
- return `(${left} != ${right})`;
717
- case "<":
718
- return `(${left} < ${right})`;
719
- case ">":
720
- return `(${left} > ${right})`;
721
- case "<=":
722
- return `(${left} <= ${right})`;
723
- case ">=":
724
- return `(${left} >= ${right})`;
725
- case "+":
726
- return `(${left} + ${right})`;
727
- case "-":
728
- return `(${left} - ${right})`;
729
- case "*":
730
- return `(${left} * ${right})`;
731
- case "/":
732
- return `(${left} / ${right})`;
733
- case "%":
734
- return `(${left} % ${right})`;
735
- default:
736
- return this.opaque(`(${left} ${node.operator} ${right})`);
737
- }
738
- }
739
- // ---------------------------------------------------------------------------
740
- // Logical
741
- // ---------------------------------------------------------------------------
742
- visitLogical(node) {
743
- const left = this.visit(node.left);
744
- const right = this.visit(node.right);
745
- switch (node.operator) {
746
- case "&&":
747
- return `(${left} && ${right})`;
748
- case "||":
749
- return `(${left} || ${right})`;
750
- case "??":
751
- return `coalesce(${left}, ${right})`;
752
- default:
753
- return this.opaque(`(${left} ${node.operator} ${right})`);
754
- }
755
- }
756
- // ---------------------------------------------------------------------------
757
- // Member expression
758
- // ---------------------------------------------------------------------------
759
- visitMember(node) {
760
- const isOptional = node.optional === true;
761
- if (!node.computed && t5.isIdentifier(node.property) && node.property.name === "length") {
762
- const obj2 = this.visit(node.object);
763
- if (isOptional) {
764
- return `if(${obj2} != null, length(${obj2}), null)`;
765
- }
766
- return `length(${obj2})`;
767
- }
768
- const obj = this.visit(node.object);
769
- if (node.computed) {
770
- const prop2 = t5.isExpression(node.property) ? this.visit(node.property) : "0";
771
- if (isOptional) {
772
- return `if(${obj} != null, get(${obj}, ${prop2}), null)`;
773
- }
774
- return `${obj}[${prop2}]`;
775
- }
776
- const prop = t5.isIdentifier(node.property) ? node.property.name : "[property]";
777
- if (isOptional) {
778
- return `if(${obj} != null, ${obj}.${prop}, null)`;
779
- }
780
- return `${obj}.${prop}`;
781
- }
782
- // ---------------------------------------------------------------------------
783
- // Call expression
784
- // ---------------------------------------------------------------------------
785
- visitCall(node) {
786
- if (t5.isIdentifier(node.callee)) {
787
- const setterField = this.setterToFieldMap.get(node.callee.name);
788
- if (setterField) {
789
- return this.visitSetterCall(node, setterField);
790
- }
791
- const args = this.visitArgs(node.arguments);
792
- return `${node.callee.name}(${args})`;
793
- }
794
- if (t5.isMemberExpression(node.callee) || t5.isOptionalMemberExpression(node.callee)) {
795
- const methodName = t5.isIdentifier(node.callee.property) ? node.callee.property.name : null;
796
- if (!methodName) {
797
- return this.opaque(fallbackGenerate(node));
798
- }
799
- if (t5.isIdentifier(node.callee.object) && node.callee.object.name === "Math") {
800
- return this.visitMathCall(methodName, node.arguments);
801
- }
802
- if (t5.isIdentifier(node.callee.object) && node.callee.object.name === "JSON") {
803
- return this.visitJsonCall(methodName, node.arguments);
804
- }
805
- if (t5.isIdentifier(node.callee.object) && node.callee.object.name === "Date") {
806
- if (methodName === "now") return "now_ms()";
807
- }
808
- const obj = this.visit(node.callee.object);
809
- return this.visitMethodCall(obj, methodName, node.arguments);
810
- }
811
- return this.opaque(fallbackGenerate(node));
812
- }
813
- // ---------------------------------------------------------------------------
814
- // Method call transpilation (obj.method(args))
815
- // ---------------------------------------------------------------------------
816
- visitMethodCall(obj, method, args) {
817
- switch (method) {
818
- // --- String methods ---
819
- case "toLowerCase":
820
- return `lower(${obj})`;
821
- case "toUpperCase":
822
- return `upper(${obj})`;
823
- case "trim":
824
- return `trim(${obj})`;
825
- case "startsWith": {
826
- const [arg] = this.visitArgsList(args);
827
- return `starts_with(${obj}, ${arg})`;
828
- }
829
- case "endsWith": {
830
- const [arg] = this.visitArgsList(args);
831
- return `ends_with(${obj}, ${arg})`;
832
- }
833
- case "includes": {
834
- const [arg] = this.visitArgsList(args);
835
- return `contains(${obj}, ${arg})`;
836
- }
837
- case "split": {
838
- const [sep] = this.visitArgsList(args);
839
- return `split(${obj}, ${sep})`;
840
- }
841
- case "join": {
842
- const [sep] = this.visitArgsList(args);
843
- return `join(${obj}, ${sep})`;
844
- }
845
- case "replace": {
846
- const visited = this.visitArgsList(args);
847
- return `replace(${obj}, ${visited[0]}, ${visited[1]})`;
848
- }
849
- case "substring":
850
- case "slice": {
851
- const visited = this.visitArgsList(args);
852
- if (visited.length === 1) return `substring(${obj}, ${visited[0]})`;
853
- return `substring(${obj}, ${visited[0]}, ${visited[1]})`;
854
- }
855
- case "charAt": {
856
- const [idx] = this.visitArgsList(args);
857
- return `substring(${obj}, ${idx}, (${idx} + 1))`;
858
- }
859
- case "indexOf": {
860
- const [arg] = this.visitArgsList(args);
861
- return `indexof(${obj}, ${arg})`;
862
- }
863
- case "toString":
864
- return `to_string(${obj})`;
865
- case "toISOString":
866
- return "now()";
867
- case "concat": {
868
- const visited = this.visitArgsList(args);
869
- return `concat(${obj}, ${visited.join(", ")})`;
870
- }
871
- // --- Array higher-order methods ---
872
- case "filter":
873
- return this.visitArrayHigherOrder("filter", obj, args);
874
- case "map":
875
- return this.visitArrayHigherOrder("map", obj, args);
876
- case "find":
877
- return this.visitArrayHigherOrder("find", obj, args);
878
- case "reduce":
879
- return this.visitArrayReduce(obj, args);
880
- case "some":
881
- return this.visitArrayHigherOrder("some", obj, args);
882
- case "every":
883
- return this.visitArrayHigherOrder("every", obj, args);
884
- // --- Array mutation-free methods ---
885
- case "reverse":
886
- return `reverse(${obj})`;
887
- case "sort":
888
- return `sort(${obj})`;
889
- case "flat":
890
- return `flat(${obj})`;
891
- // --- JSON methods on values ---
892
- case "stringify":
893
- return `to_string(${obj})`;
894
- default:
895
- return this.opaque(`${obj}.${method}(${this.visitArgs(args)})`);
896
- }
897
- }
898
- // ---------------------------------------------------------------------------
899
- // Array higher-order method transpilation
900
- // ---------------------------------------------------------------------------
901
- visitArrayHigherOrder(fn, obj, args) {
902
- const firstArg = args[0];
903
- if (!firstArg || !t5.isExpression(firstArg)) {
904
- return this.opaque(`${obj}.${fn}()`);
905
- }
906
- if (t5.isArrowFunctionExpression(firstArg) && t5.isExpression(firstArg.body)) {
907
- const paramName = firstArg.params.length > 0 && t5.isIdentifier(firstArg.params[0]) ? firstArg.params[0].name : "_";
908
- const lambdaBody = this.visit(firstArg.body);
909
- return `${fn}(${obj}, ${paramName} => ${lambdaBody})`;
910
- }
911
- const argStr = this.visit(firstArg);
912
- return `${fn}(${obj}, ${argStr})`;
913
- }
914
- visitArrayReduce(obj, args) {
915
- const [callbackArg, initArg] = args;
916
- if (!callbackArg || !t5.isExpression(callbackArg)) {
917
- return this.opaque(`${obj}.reduce()`);
918
- }
919
- if (t5.isArrowFunctionExpression(callbackArg) && t5.isExpression(callbackArg.body)) {
920
- const params = callbackArg.params;
921
- const accName = params.length > 0 && t5.isIdentifier(params[0]) ? params[0].name : "acc";
922
- const itemName = params.length > 1 && t5.isIdentifier(params[1]) ? params[1].name : "x";
923
- const lambdaBody = this.visit(callbackArg.body);
924
- const initStr = initArg && t5.isExpression(initArg) ? this.visit(initArg) : "0";
925
- return `reduce(${obj}, (${accName}, ${itemName}) => ${lambdaBody}, ${initStr})`;
926
- }
927
- return this.opaque(fallbackGenerate({ type: "CallExpression" }));
928
- }
929
- // ---------------------------------------------------------------------------
930
- // Math.* methods
931
- // ---------------------------------------------------------------------------
932
- visitMathCall(method, args) {
933
- const visited = this.visitArgsList(args);
934
- switch (method) {
935
- case "max":
936
- return `max(${visited.join(", ")})`;
937
- case "min":
938
- return `min(${visited.join(", ")})`;
939
- case "round":
940
- return `round(${visited.join(", ")})`;
941
- case "floor":
942
- return `floor(${visited.join(", ")})`;
943
- case "ceil":
944
- return `ceil(${visited.join(", ")})`;
945
- case "abs":
946
- return `abs(${visited.join(", ")})`;
947
- case "pow":
948
- return `power(${visited.join(", ")})`;
949
- case "sqrt":
950
- return `sqrt(${visited.join(", ")})`;
951
- case "log":
952
- return `log(${visited.join(", ")})`;
953
- case "log10":
954
- return `log10(${visited.join(", ")})`;
955
- case "sign":
956
- return `sign(${visited.join(", ")})`;
957
- default:
958
- return this.opaque(`Math.${method}(${visited.join(", ")})`);
959
- }
960
- }
961
- // ---------------------------------------------------------------------------
962
- // JSON.* methods
963
- // ---------------------------------------------------------------------------
964
- visitJsonCall(method, args) {
965
- const visited = this.visitArgsList(args);
966
- switch (method) {
967
- case "stringify":
968
- return `to_string(${visited[0]})`;
969
- case "parse":
970
- return `from_json(${visited[0]})`;
971
- default:
972
- return this.opaque(`JSON.${method}(${visited.join(", ")})`);
973
- }
974
- }
975
- // ---------------------------------------------------------------------------
976
- // Template literals
977
- // ---------------------------------------------------------------------------
978
- visitTemplateLiteral(node) {
979
- const parts = [];
980
- for (let i = 0; i < node.quasis.length; i++) {
981
- const raw = node.quasis[i].value.cooked ?? node.quasis[i].value.raw;
982
- if (raw) {
983
- parts.push(`"${raw.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`);
984
- }
985
- if (i < node.expressions.length) {
986
- const exprStr = this.visit(node.expressions[i]);
987
- parts.push(`to_string(${exprStr})`);
988
- }
989
- }
990
- const nonEmpty = parts.filter((p) => p !== '""');
991
- if (nonEmpty.length === 0) return '""';
992
- if (nonEmpty.length === 1) return nonEmpty[0];
993
- return `concat(${nonEmpty.join(", ")})`;
994
- }
995
- // ---------------------------------------------------------------------------
996
- // Object expression
997
- // ---------------------------------------------------------------------------
998
- visitObject(node) {
999
- const props = node.properties.map((prop) => {
1000
- if (t5.isSpreadElement(prop)) {
1001
- return this.opaque(`...${this.visit(prop.argument)}`);
1002
- }
1003
- if (t5.isObjectProperty(prop)) {
1004
- const key = t5.isIdentifier(prop.key) ? `"${prop.key.name}"` : t5.isStringLiteral(prop.key) ? `"${prop.key.value}"` : t5.isNumericLiteral(prop.key) ? `"${prop.key.value}"` : '"[key]"';
1005
- const value = t5.isExpression(prop.value) ? this.visit(prop.value) : "null";
1006
- return `${key}: ${value}`;
1007
- }
1008
- return this.opaque("[method]");
1009
- });
1010
- return `{${props.join(", ")}}`;
1011
- }
1012
- // ---------------------------------------------------------------------------
1013
- // Arrow function (lambda)
1014
- // ---------------------------------------------------------------------------
1015
- visitArrow(node) {
1016
- if (t5.isExpression(node.body)) {
1017
- const params = node.params.map((p) => {
1018
- if (t5.isIdentifier(p)) return p.name;
1019
- return "_";
1020
- }).join(", ");
1021
- const body = this.visit(node.body);
1022
- if (node.params.length === 1) return `${params} => ${body}`;
1023
- return `(${params}) => ${body}`;
1024
- }
1025
- return this.opaque(fallbackGenerate(node));
1026
- }
1027
- // ---------------------------------------------------------------------------
1028
- // new expressions
1029
- // ---------------------------------------------------------------------------
1030
- visitNew(node) {
1031
- if (t5.isIdentifier(node.callee) && node.callee.name === "Date" && node.arguments.length === 0) {
1032
- return "now()";
1033
- }
1034
- return this.opaque(fallbackGenerate(node));
1035
- }
1036
- // ---------------------------------------------------------------------------
1037
- // setState setter calls
1038
- // ---------------------------------------------------------------------------
1039
- visitSetterCall(node, fieldName) {
1040
- if (node.arguments.length >= 1) {
1041
- const arg = node.arguments[0];
1042
- if ((t5.isArrowFunctionExpression(arg) || t5.isFunctionExpression(arg)) && arg.params.length >= 1 && t5.isIdentifier(arg.params[0])) {
1043
- const paramName = arg.params[0].name;
1044
- const bodyExpr = t5.isExpression(arg.body) ? this.visit(arg.body) : "null";
1045
- const resolved = bodyExpr.replace(
1046
- new RegExp(`(?<![.$\\w])${paramName}(?![\\w])`, "g"),
1047
- `$local.${fieldName}`
1048
- );
1049
- return `$action.setLocal("${fieldName}")(${resolved})`;
1050
- }
1051
- const argStr = t5.isExpression(arg) ? this.visit(arg) : "null";
1052
- return `$action.setLocal("${fieldName}")(${argStr})`;
1053
- }
1054
- return `$action.setLocal("${fieldName}")`;
1055
- }
1056
- // ---------------------------------------------------------------------------
1057
- // Argument helpers
1058
- // ---------------------------------------------------------------------------
1059
- visitArgs(args) {
1060
- return args.map((a) => {
1061
- if (t5.isExpression(a)) return this.visit(a);
1062
- if (t5.isSpreadElement(a)) return this.opaque(`...${this.visit(a.argument)}`);
1063
- return "null";
1064
- }).join(", ");
1065
- }
1066
- visitArgsList(args) {
1067
- return args.map((a) => {
1068
- if (t5.isExpression(a)) return this.visit(a);
1069
- if (t5.isSpreadElement(a)) return this.opaque(`...${this.visit(a.argument)}`);
1070
- return "null";
1071
- });
1072
- }
1073
- };
1074
- function fallbackGenerate(node) {
1075
- if (t5.isIdentifier(node)) return node.name;
1076
- if (t5.isStringLiteral(node)) return `"${node.value.replace(/"/g, '\\"')}"`;
1077
- if (t5.isNumericLiteral(node)) return String(node.value);
1078
- if (t5.isBooleanLiteral(node)) return String(node.value);
1079
- if (t5.isNullLiteral(node)) return "null";
1080
- return `[${node.type}]`;
1081
- }
1082
-
1083
- // src/babel/extractors/component-extractor.ts
1084
- var nodeIdCounter = 0;
1085
- var localFieldMap = /* @__PURE__ */ new Map();
1086
- var setterToFieldMap = /* @__PURE__ */ new Map();
1087
- var derivedVarMap = /* @__PURE__ */ new Map();
1088
- function toSnakeCase(str) {
1089
- return str.replace(/([A-Z])/g, "_$1").toLowerCase().replace(/^_/, "");
1090
- }
1091
- var STATIC_EVAL_FAIL = Symbol("STATIC_EVAL_FAIL");
1092
- function tryStaticEval(node) {
1093
- if (t6.isStringLiteral(node)) return node.value;
1094
- if (t6.isNumericLiteral(node)) return node.value;
1095
- if (t6.isBooleanLiteral(node)) return node.value;
1096
- if (t6.isNullLiteral(node)) return null;
1097
- if (t6.isIdentifier(node) && node.name === "undefined") return void 0;
1098
- if (t6.isUnaryExpression(node) && node.operator === "-" && t6.isNumericLiteral(node.argument)) {
1099
- return -node.argument.value;
1100
- }
1101
- if (t6.isArrayExpression(node)) {
1102
- const result = [];
1103
- for (const el of node.elements) {
1104
- if (el === null) {
1105
- result.push(null);
1106
- continue;
1107
- }
1108
- if (t6.isSpreadElement(el)) return STATIC_EVAL_FAIL;
1109
- const val = tryStaticEval(el);
1110
- if (val === STATIC_EVAL_FAIL) return STATIC_EVAL_FAIL;
1111
- result.push(val);
1112
- }
1113
- return result;
1114
- }
1115
- if (t6.isObjectExpression(node)) {
1116
- const result = {};
1117
- for (const prop of node.properties) {
1118
- if (t6.isSpreadElement(prop) || t6.isObjectMethod(prop)) return STATIC_EVAL_FAIL;
1119
- if (!t6.isObjectProperty(prop)) return STATIC_EVAL_FAIL;
1120
- let key;
1121
- if (t6.isIdentifier(prop.key)) key = prop.key.name;
1122
- else if (t6.isStringLiteral(prop.key)) key = prop.key.value;
1123
- else if (t6.isNumericLiteral(prop.key)) key = String(prop.key.value);
1124
- else return STATIC_EVAL_FAIL;
1125
- if (!t6.isExpression(prop.value)) return STATIC_EVAL_FAIL;
1126
- const val = tryStaticEval(prop.value);
1127
- if (val === STATIC_EVAL_FAIL) return STATIC_EVAL_FAIL;
1128
- result[key] = val;
1129
- }
1130
- return result;
1131
- }
1132
- if (t6.isTemplateLiteral(node) && node.expressions.length === 0) {
1133
- return node.quasis[0].value.cooked ?? node.quasis[0].value.raw;
1134
- }
1135
- return STATIC_EVAL_FAIL;
1136
- }
1137
- function initLocalFieldMaps(fields) {
1138
- localFieldMap.clear();
1139
- setterToFieldMap.clear();
1140
- for (const field of fields) {
1141
- const camelName = field.name;
1142
- const snakeName = toSnakeCase(camelName);
1143
- localFieldMap.set(camelName, snakeName);
1144
- const setterName = "set" + camelName.charAt(0).toUpperCase() + camelName.slice(1);
1145
- setterToFieldMap.set(setterName, snakeName);
1146
- }
1147
- }
1148
- function registerDerivedVar(name, init) {
1149
- derivedVarMap.set(name, init);
1150
- }
1151
- function resetNodeIdCounter() {
1152
- nodeIdCounter = 0;
1153
- derivedVarMap.clear();
1154
- }
1155
- function jsxToExperienceNode(node) {
1156
- if (t6.isJSXFragment(node)) {
1157
- return {
1158
- id: `fragment_${++nodeIdCounter}`,
1159
- children: extractChildren(node.children)
1160
- };
1161
- }
1162
- const element = node.openingElement;
1163
- const componentName = resolveComponentName(element.name);
1164
- const id = generateNodeId(componentName);
1165
- const config = {};
1166
- const bindings = {};
1167
- let visibleWhen;
1168
- let layout;
1169
- let slot;
1170
- let className;
1171
- let displayName;
1172
- const layoutMap = {
1173
- Stack: "stack",
1174
- Row: "row",
1175
- Grid: "grid",
1176
- Tabs: "tabs",
1177
- Column: "column"
1178
- };
1179
- if (layoutMap[componentName]) {
1180
- layout = layoutMap[componentName];
1181
- }
1182
- for (const attr of element.attributes) {
1183
- if (t6.isJSXAttribute(attr) && t6.isJSXIdentifier(attr.name)) {
1184
- const attrName = attr.name.name;
1185
- const attrValue = attr.value;
1186
- if (attrName === "visible_when" && t6.isStringLiteral(attrValue)) {
1187
- visibleWhen = attrValue.value;
1188
- } else if (attrName === "data-slot" && t6.isStringLiteral(attrValue)) {
1189
- slot = attrValue.value;
1190
- } else if (attrName === "className" && t6.isStringLiteral(attrValue)) {
1191
- className = attrValue.value;
1192
- } else if (attrName === "displayName" && t6.isStringLiteral(attrValue)) {
1193
- displayName = attrValue.value;
1194
- } else if (t6.isJSXExpressionContainer(attrValue)) {
1195
- const expr = attrValue.expression;
1196
- if (t6.isJSXEmptyExpression(expr)) continue;
1197
- if (t6.isNumericLiteral(expr)) {
1198
- config[attrName] = expr.value;
1199
- } else if (t6.isBooleanLiteral(expr)) {
1200
- config[attrName] = expr.value;
1201
- } else if (t6.isStringLiteral(expr)) {
1202
- if (expr.value.includes("$instance") || expr.value.includes("$local") || /^[a-zA-Z_]+\(/.test(expr.value)) {
1203
- bindings[attrName] = expr.value;
1204
- } else {
1205
- config[attrName] = expr.value;
1206
- }
1207
- } else if (t6.isIdentifier(expr)) {
1208
- const snakeName = localFieldMap.get(expr.name);
1209
- bindings[attrName] = snakeName ? `$local.${snakeName}` : `$instance.${expr.name}`;
1210
- } else if (isEventHandlerProp(attrName) && (t6.isArrowFunctionExpression(expr) || t6.isFunctionExpression(expr))) {
1211
- const decomposed = decomposeHandlerToSeq(expr);
1212
- if (decomposed) {
1213
- bindings[attrName] = decomposed;
1214
- } else {
1215
- bindings[attrName] = `$expr(${generateExpression2(expr)})`;
1216
- }
1217
- } else if (t6.isExpression(expr)) {
1218
- const staticVal = tryStaticEval(expr);
1219
- if (staticVal !== STATIC_EVAL_FAIL) {
1220
- config[attrName] = staticVal;
1221
- } else {
1222
- bindings[attrName] = generateExpression2(expr);
1223
- }
1224
- }
1225
- } else if (t6.isStringLiteral(attrValue)) {
1226
- config[attrName] = attrValue.value;
1227
- } else if (attrValue === null) {
1228
- config[attrName] = true;
1229
- }
1230
- } else if (t6.isJSXSpreadAttribute(attr)) {
1231
- if (t6.isIdentifier(attr.argument)) {
1232
- bindings["..." + attr.argument.name] = `$instance.${attr.argument.name}`;
1233
- }
1234
- }
1235
- }
1236
- const children = extractChildren(node.children);
1237
- const experienceNode = {
1238
- id,
1239
- ...displayName && { displayName },
1240
- component: componentName,
1241
- ...slot && { slot },
1242
- ...layout && { layout },
1243
- ...className && { className },
1244
- ...Object.keys(bindings).length > 0 && { bindings },
1245
- ...Object.keys(config).length > 0 && { config },
1246
- ...visibleWhen && { visible_when: visibleWhen },
1247
- ...children.length > 0 && { children }
1248
- };
1249
- return experienceNode;
1250
- }
1251
- function resolveComponentName(name) {
1252
- if (t6.isJSXIdentifier(name)) return name.name;
1253
- if (t6.isJSXMemberExpression(name)) {
1254
- const obj = resolveComponentName(name.object);
1255
- return `${obj}.${name.property.name}`;
1256
- }
1257
- if (t6.isJSXNamespacedName(name)) {
1258
- return `${name.namespace.name}:${name.name.name}`;
1259
- }
1260
- return "div";
1261
- }
1262
- function extractChildren(children) {
1263
- const nodes = [];
1264
- for (const child of children) {
1265
- if (t6.isJSXElement(child)) {
1266
- nodes.push(jsxToExperienceNode(child));
1267
- } else if (t6.isJSXFragment(child)) {
1268
- nodes.push(jsxToExperienceNode(child));
1269
- } else if (t6.isJSXText(child)) {
1270
- const text = child.value.trim();
1271
- if (text) {
1272
- nodes.push({
1273
- id: `text_${++nodeIdCounter}`,
1274
- component: "Text",
1275
- config: { value: text }
1276
- });
1277
- }
1278
- } else if (t6.isJSXExpressionContainer(child)) {
1279
- const expr = child.expression;
1280
- if (t6.isJSXEmptyExpression(expr)) continue;
1281
- if (t6.isConditionalExpression(expr)) {
1282
- const condExpr = generateExpression2(expr.test);
1283
- if (t6.isJSXElement(expr.consequent) || t6.isJSXFragment(expr.consequent)) {
1284
- const consequent = jsxToExperienceNode(expr.consequent);
1285
- consequent.visible_when = condExpr;
1286
- nodes.push(consequent);
1287
- }
1288
- if (t6.isJSXElement(expr.alternate) || t6.isJSXFragment(expr.alternate)) {
1289
- const alternate = jsxToExperienceNode(expr.alternate);
1290
- alternate.visible_when = `not(${condExpr})`;
1291
- nodes.push(alternate);
1292
- }
1293
- } else if (t6.isLogicalExpression(expr) && expr.operator === "&&") {
1294
- const condExpr = generateExpression2(expr.left);
1295
- if (t6.isJSXElement(expr.right) || t6.isJSXFragment(expr.right)) {
1296
- const element = jsxToExperienceNode(expr.right);
1297
- element.visible_when = condExpr;
1298
- nodes.push(element);
1299
- }
1300
- } else if (t6.isCallExpression(expr) && t6.isMemberExpression(expr.callee) && t6.isIdentifier(expr.callee.property) && expr.callee.property.name === "map" && expr.arguments.length > 0) {
1301
- const listSource = generateExpression2(expr.callee.object);
1302
- const mapFn = expr.arguments[0];
1303
- let itemTemplate = null;
1304
- let itemAlias = "item";
1305
- if (t6.isArrowFunctionExpression(mapFn) || t6.isFunctionExpression(mapFn)) {
1306
- if (mapFn.params.length > 0 && t6.isIdentifier(mapFn.params[0])) {
1307
- itemAlias = mapFn.params[0].name;
1308
- }
1309
- const body = mapFn.body;
1310
- if (t6.isJSXElement(body) || t6.isJSXFragment(body)) {
1311
- itemTemplate = jsxToExperienceNode(body);
1312
- } else if (t6.isBlockStatement(body)) {
1313
- for (const stmt of body.body) {
1314
- if (t6.isReturnStatement(stmt) && stmt.argument) {
1315
- if (t6.isJSXElement(stmt.argument) || t6.isJSXFragment(stmt.argument)) {
1316
- itemTemplate = jsxToExperienceNode(stmt.argument);
1317
- }
1318
- break;
1319
- }
1320
- }
1321
- }
1322
- }
1323
- nodes.push({
1324
- id: `each_${++nodeIdCounter}`,
1325
- component: "Each",
1326
- bindings: { items: listSource.startsWith("$") ? listSource : `$instance.${listSource}` },
1327
- config: { as: itemAlias },
1328
- ...itemTemplate ? { children: [itemTemplate] } : {}
1329
- });
1330
- } else if ((t6.isArrowFunctionExpression(expr) || t6.isFunctionExpression(expr)) && extractJSXFromCallback(expr)) {
1331
- const jsxNode = extractJSXFromCallback(expr);
1332
- nodes.push(jsxToExperienceNode(jsxNode));
1333
- } else if (t6.isStringLiteral(expr)) {
1334
- nodes.push({
1335
- id: `text_${++nodeIdCounter}`,
1336
- component: "Text",
1337
- config: { value: expr.value }
1338
- });
1339
- } else if (t6.isIdentifier(expr)) {
1340
- const snakeName = localFieldMap.get(expr.name);
1341
- const bindingPath = snakeName ? `$local.${snakeName}` : `$instance.${expr.name}`;
1342
- nodes.push({
1343
- id: `text_${++nodeIdCounter}`,
1344
- component: "Text",
1345
- bindings: { value: bindingPath }
1346
- });
1347
- } else if (t6.isExpression(expr)) {
1348
- const exprStr = generateExpression2(expr);
1349
- if (exprStr !== "[Expression]") {
1350
- nodes.push({
1351
- id: `text_${++nodeIdCounter}`,
1352
- component: "Text",
1353
- bindings: { value: exprStr }
1354
- });
1355
- }
1356
- }
1357
- }
1358
- }
1359
- return nodes;
1360
- }
1361
- function generateNodeId(componentName) {
1362
- const id = componentName.replace(/\./g, "-").replace(/([A-Z])/g, "-$1").toLowerCase().replace(/^-/, "");
1363
- return `${id}_${++nodeIdCounter}`;
1364
- }
1365
- function generateExpression2(node) {
1366
- if (t6.isIdentifier(node)) {
1367
- const snakeName = localFieldMap.get(node.name);
1368
- if (snakeName) return `$local.${snakeName}`;
1369
- const derivedInit = derivedVarMap.get(node.name);
1370
- if (derivedInit) return `(${generateExpression2(derivedInit)})`;
1371
- return node.name;
1372
- }
1373
- if (t6.isStringLiteral(node)) return `"${node.value.replace(/"/g, '\\"')}"`;
1374
- if (t6.isNumericLiteral(node)) return String(node.value);
1375
- if (t6.isBooleanLiteral(node)) return String(node.value);
1376
- if (t6.isNullLiteral(node)) return "null";
1377
- if (t6.isMemberExpression(node) || t6.isOptionalMemberExpression(node)) {
1378
- const obj = t6.isExpression(node.object) ? generateExpression2(node.object) : "[object]";
1379
- const optional = node.optional ? "?." : ".";
1380
- if (node.computed) {
1381
- const prop2 = t6.isExpression(node.property) ? generateExpression2(node.property) : "0";
1382
- return `${obj}[${prop2}]`;
1383
- }
1384
- const prop = t6.isIdentifier(node.property) ? node.property.name : "[property]";
1385
- return `${obj}${optional}${prop}`;
1386
- }
1387
- if (t6.isBinaryExpression(node)) {
1388
- return `(${generateExpression2(node.left)} ${node.operator} ${generateExpression2(node.right)})`;
1389
- }
1390
- if (t6.isLogicalExpression(node)) {
1391
- return `(${generateExpression2(node.left)} ${node.operator} ${generateExpression2(node.right)})`;
1392
- }
1393
- if (t6.isConditionalExpression(node)) {
1394
- return `(${generateExpression2(node.test)} ? ${generateExpression2(node.consequent)} : ${generateExpression2(node.alternate)})`;
1395
- }
1396
- if (t6.isUnaryExpression(node) && node.prefix) {
1397
- const space = node.operator === "typeof" || node.operator === "void" || node.operator === "delete" ? " " : "";
1398
- return `${node.operator}${space}${generateExpression2(node.argument)}`;
1399
- }
1400
- if (t6.isCallExpression(node) || t6.isOptionalCallExpression(node)) {
1401
- if (t6.isIdentifier(node.callee)) {
1402
- const setterFieldName = setterToFieldMap.get(node.callee.name);
1403
- if (setterFieldName) {
1404
- if (node.arguments.length >= 1) {
1405
- const arg = node.arguments[0];
1406
- if ((t6.isArrowFunctionExpression(arg) || t6.isFunctionExpression(arg)) && arg.params.length >= 1 && t6.isIdentifier(arg.params[0])) {
1407
- const paramName = arg.params[0].name;
1408
- const bodyExpr = t6.isExpression(arg.body) ? generateExpression2(arg.body) : "undefined";
1409
- const resolved = bodyExpr.replace(
1410
- new RegExp(`(?<![.$\\w])${paramName}(?![\\w])`, "g"),
1411
- `$local.${setterFieldName}`
1412
- );
1413
- return `$action.setLocal("${setterFieldName}")(${resolved})`;
1414
- }
1415
- const argStr = t6.isExpression(arg) ? generateExpression2(arg) : "undefined";
1416
- return `$action.setLocal("${setterFieldName}")(${argStr})`;
1417
- }
1418
- return `$action.setLocal("${setterFieldName}")`;
1419
- }
1420
- const args = node.arguments.map((a) => t6.isExpression(a) ? generateExpression2(a) : t6.isSpreadElement(a) ? `...${generateExpression2(a.argument)}` : "undefined").join(", ");
1421
- return `${node.callee.name}(${args})`;
1422
- }
1423
- if (t6.isMemberExpression(node.callee) || t6.isOptionalMemberExpression(node.callee)) {
1424
- const mmResult = transpileExpression(node, {
1425
- localFieldMap,
1426
- derivedVarMap,
1427
- setterToFieldMap
1428
- });
1429
- if (mmResult.pure) return mmResult.expression;
1430
- const obj = generateExpression2(node.callee.object);
1431
- const optional = node.callee.optional ? "?." : ".";
1432
- const prop = t6.isIdentifier(node.callee.property) ? node.callee.property.name : "[method]";
1433
- const args = node.arguments.map((a) => t6.isExpression(a) ? generateExpression2(a) : t6.isSpreadElement(a) ? `...${generateExpression2(a.argument)}` : "undefined").join(", ");
1434
- return `${obj}${optional}${prop}(${args})`;
1435
- }
1436
- if (t6.isExpression(node.callee)) {
1437
- const callee = generateExpression2(node.callee);
1438
- const args = node.arguments.map((a) => t6.isExpression(a) ? generateExpression2(a) : "undefined").join(", ");
1439
- return `(${callee})(${args})`;
1440
- }
1441
- }
1442
- if (t6.isTemplateLiteral(node)) {
1443
- const parts = node.quasis.map((q, i) => {
1444
- const raw = q.value.raw;
1445
- if (i < node.expressions.length) {
1446
- return raw + "${" + generateExpression2(node.expressions[i]) + "}";
1447
- }
1448
- return raw;
1449
- }).join("");
1450
- return "`" + parts + "`";
1451
- }
1452
- if (t6.isArrowFunctionExpression(node)) {
1453
- const params = node.params.map((p) => {
1454
- if (t6.isIdentifier(p)) return p.name;
1455
- if (t6.isRestElement(p) && t6.isIdentifier(p.argument)) return `...${p.argument.name}`;
1456
- if (t6.isAssignmentPattern(p) && t6.isIdentifier(p.left)) {
1457
- return `${p.left.name} = ${t6.isExpression(p.right) ? generateExpression2(p.right) : "undefined"}`;
1458
- }
1459
- return "_";
1460
- }).join(", ");
1461
- if (t6.isExpression(node.body)) {
1462
- return `(${params}) => ${generateExpression2(node.body)}`;
1463
- }
1464
- if (t6.isBlockStatement(node.body)) {
1465
- const bodyStr = generateBlockStatement(node.body);
1466
- return `(${params}) => { ${bodyStr} }`;
1467
- }
1468
- }
1469
- if (t6.isArrayExpression(node)) {
1470
- const elements = node.elements.map((el) => {
1471
- if (el === null) return "undefined";
1472
- if (t6.isSpreadElement(el)) return `...${generateExpression2(el.argument)}`;
1473
- return t6.isExpression(el) ? generateExpression2(el) : "undefined";
1474
- }).join(", ");
1475
- return `[${elements}]`;
1476
- }
1477
- if (t6.isObjectExpression(node)) {
1478
- const props = node.properties.map((prop) => {
1479
- if (t6.isSpreadElement(prop)) return `...${generateExpression2(prop.argument)}`;
1480
- if (t6.isObjectProperty(prop)) {
1481
- const key = t6.isIdentifier(prop.key) ? prop.key.name : t6.isStringLiteral(prop.key) ? `"${prop.key.value}"` : t6.isNumericLiteral(prop.key) ? String(prop.key.value) : "[key]";
1482
- if (prop.shorthand && t6.isIdentifier(prop.value)) return key;
1483
- const value = t6.isExpression(prop.value) ? generateExpression2(prop.value) : "undefined";
1484
- return `${key}: ${value}`;
1485
- }
1486
- if (t6.isObjectMethod(prop)) {
1487
- const key = t6.isIdentifier(prop.key) ? prop.key.name : "[method]";
1488
- const params = prop.params.map((p) => t6.isIdentifier(p) ? p.name : "_").join(", ");
1489
- const bodyStr = generateBlockStatement(prop.body);
1490
- return `${key}(${params}) { ${bodyStr} }`;
1491
- }
1492
- return "";
1493
- }).filter(Boolean).join(", ");
1494
- return `{ ${props} }`;
1495
- }
1496
- if (t6.isParenthesizedExpression(node)) {
1497
- return `(${generateExpression2(node.expression)})`;
1498
- }
1499
- if (t6.isTSAsExpression(node)) return generateExpression2(node.expression);
1500
- if (t6.isTSNonNullExpression(node)) return generateExpression2(node.expression);
1501
- if (t6.isTSTypeAssertion(node)) return generateExpression2(node.expression);
1502
- if (t6.isSequenceExpression(node)) {
1503
- return `(${node.expressions.map(generateExpression2).join(", ")})`;
1504
- }
1505
- if (t6.isAssignmentExpression(node)) {
1506
- const left = t6.isExpression(node.left) ? generateExpression2(node.left) : "[target]";
1507
- return `(${left} ${node.operator} ${generateExpression2(node.right)})`;
1508
- }
1509
- if (t6.isUpdateExpression(node)) {
1510
- const arg = generateExpression2(node.argument);
1511
- return node.prefix ? `${node.operator}${arg}` : `${arg}${node.operator}`;
1512
- }
1513
- if (t6.isTaggedTemplateExpression(node)) {
1514
- return generateExpression2(node.quasi);
1515
- }
1516
- if (t6.isSpreadElement(node)) {
1517
- return `...${generateExpression2(node.argument)}`;
1518
- }
1519
- if (t6.isYieldExpression(node)) {
1520
- return node.argument ? `yield ${generateExpression2(node.argument)}` : "yield";
1521
- }
1522
- if (t6.isAwaitExpression(node)) {
1523
- return `await ${generateExpression2(node.argument)}`;
1524
- }
1525
- if (t6.isNewExpression(node)) {
1526
- const callee = t6.isExpression(node.callee) ? generateExpression2(node.callee) : "Object";
1527
- const args = node.arguments.map((a) => t6.isExpression(a) ? generateExpression2(a) : "undefined").join(", ");
1528
- return `new ${callee}(${args})`;
1529
- }
1530
- if (t6.isThisExpression(node)) return "this";
1531
- console.warn(`[component-extractor] Unhandled expression type: ${node.type}`);
1532
- return "[Expression]";
1533
- }
1534
- function generateBlockStatement(block) {
1535
- return block.body.map((stmt) => {
1536
- if (t6.isReturnStatement(stmt)) {
1537
- return stmt.argument ? `return ${generateExpression2(stmt.argument)};` : "return;";
1538
- }
1539
- if (t6.isExpressionStatement(stmt)) {
1540
- return `${generateExpression2(stmt.expression)};`;
1541
- }
1542
- if (t6.isVariableDeclaration(stmt)) {
1543
- const decls = stmt.declarations.map((d) => {
1544
- const id = t6.isIdentifier(d.id) ? d.id.name : "_";
1545
- const init = d.init && t6.isExpression(d.init) ? generateExpression2(d.init) : "undefined";
1546
- return `${id} = ${init}`;
1547
- }).join(", ");
1548
- return `${stmt.kind} ${decls};`;
1549
- }
1550
- if (t6.isIfStatement(stmt)) {
1551
- const test = generateExpression2(stmt.test);
1552
- const consequent = t6.isBlockStatement(stmt.consequent) ? `{ ${generateBlockStatement(stmt.consequent)} }` : t6.isExpressionStatement(stmt.consequent) ? `{ ${generateExpression2(stmt.consequent.expression)}; }` : "{}";
1553
- const alternate = stmt.alternate ? t6.isBlockStatement(stmt.alternate) ? ` else { ${generateBlockStatement(stmt.alternate)} }` : t6.isIfStatement(stmt.alternate) ? ` else ${generateBlockStatement(t6.blockStatement([stmt.alternate]))}` : "" : "";
1554
- return `if (${test}) ${consequent}${alternate}`;
1555
- }
1556
- return "/* [Statement] */";
1557
- }).join(" ");
1558
- }
1559
- function extractJSXFromCallback(node) {
1560
- const body = node.body;
1561
- if (t6.isJSXElement(body) || t6.isJSXFragment(body)) {
1562
- return body;
1563
- }
1564
- if (t6.isParenthesizedExpression(body)) {
1565
- const inner = body.expression;
1566
- if (t6.isJSXElement(inner) || t6.isJSXFragment(inner)) {
1567
- return inner;
1568
- }
1569
- }
1570
- if (t6.isBlockStatement(body)) {
1571
- for (const stmt of body.body) {
1572
- if (t6.isReturnStatement(stmt) && stmt.argument) {
1573
- if (t6.isJSXElement(stmt.argument) || t6.isJSXFragment(stmt.argument)) {
1574
- return stmt.argument;
1575
- }
1576
- if (t6.isParenthesizedExpression(stmt.argument)) {
1577
- const inner = stmt.argument.expression;
1578
- if (t6.isJSXElement(inner) || t6.isJSXFragment(inner)) {
1579
- return inner;
1580
- }
1581
- }
1582
- }
1583
- }
1584
- }
1585
- return null;
1586
- }
1587
- function isEventHandlerProp(name) {
1588
- return /^on[A-Z]/.test(name);
1589
- }
1590
- function expressionToActionAtom(expr) {
1591
- if (t6.isCallExpression(expr) || t6.isOptionalCallExpression(expr)) {
1592
- if (t6.isIdentifier(expr.callee)) {
1593
- const setterFieldName = setterToFieldMap.get(expr.callee.name);
1594
- if (setterFieldName && expr.arguments.length >= 1) {
1595
- const arg = expr.arguments[0];
1596
- if ((t6.isArrowFunctionExpression(arg) || t6.isFunctionExpression(arg)) && arg.params.length >= 1 && t6.isIdentifier(arg.params[0])) {
1597
- const paramName = arg.params[0].name;
1598
- const bodyExpr = t6.isExpression(arg.body) ? generateExpression2(arg.body) : "undefined";
1599
- const resolved = bodyExpr.replace(
1600
- new RegExp(`(?<![.$\\w])${paramName}(?![\\w])`, "g"),
1601
- `$local.${setterFieldName}`
1602
- );
1603
- return `$action.setLocal("${setterFieldName}", ${resolved})`;
1604
- }
1605
- const argStr = t6.isExpression(arg) ? generateExpression2(arg) : "undefined";
1606
- return `$action.setLocal("${setterFieldName}", ${argStr})`;
1607
- }
1608
- return null;
1609
- }
1610
- if (t6.isMemberExpression(expr.callee) || t6.isOptionalMemberExpression(expr.callee)) {
1611
- const generated = generateExpression2(expr);
1612
- if (generated.startsWith("$action.")) return generated;
1613
- }
1614
- return null;
1615
- }
1616
- return null;
1617
- }
1618
- function statementToAction(stmt) {
1619
- if (t6.isExpressionStatement(stmt)) {
1620
- return expressionToActionAtom(stmt.expression);
1621
- }
1622
- if (t6.isIfStatement(stmt)) {
1623
- const condition = generateExpression2(stmt.test);
1624
- let thenAction = null;
1625
- if (t6.isBlockStatement(stmt.consequent)) {
1626
- const actions = stmt.consequent.body.map((s) => statementToAction(s)).filter(Boolean);
1627
- if (actions.length === 0 || actions.length !== stmt.consequent.body.length) return null;
1628
- thenAction = actions.length === 1 ? actions[0] : `$action.seq(${actions.join(", ")})`;
1629
- } else if (t6.isExpressionStatement(stmt.consequent)) {
1630
- thenAction = expressionToActionAtom(stmt.consequent.expression);
1631
- }
1632
- if (!thenAction) return null;
1633
- let elseAction = null;
1634
- if (stmt.alternate) {
1635
- if (t6.isBlockStatement(stmt.alternate)) {
1636
- const actions = stmt.alternate.body.map((s) => statementToAction(s)).filter(Boolean);
1637
- if (actions.length !== stmt.alternate.body.length) return null;
1638
- elseAction = actions.length === 1 ? actions[0] : `$action.seq(${actions.join(", ")})`;
1639
- } else if (t6.isIfStatement(stmt.alternate)) {
1640
- elseAction = statementToAction(stmt.alternate);
1641
- } else if (t6.isExpressionStatement(stmt.alternate)) {
1642
- elseAction = expressionToActionAtom(stmt.alternate.expression);
1643
- }
1644
- if (!elseAction) return null;
1645
- }
1646
- return elseAction ? `$action.when(${condition}, ${thenAction}, ${elseAction})` : `$action.when(${condition}, ${thenAction})`;
1647
- }
1648
- return null;
1649
- }
1650
- function decomposeHandlerToSeq(node) {
1651
- if (t6.isArrowFunctionExpression(node) && t6.isExpression(node.body)) {
1652
- return expressionToActionAtom(node.body);
1653
- }
1654
- const body = node.body;
1655
- if (!t6.isBlockStatement(body)) return null;
1656
- const actions = [];
1657
- for (const stmt of body.body) {
1658
- const action = statementToAction(stmt);
1659
- if (!action) return null;
1660
- actions.push(action);
1661
- }
1662
- if (actions.length === 0) return null;
1663
- if (actions.length === 1) return actions[0];
1664
- return `$action.seq(${actions.join(", ")})`;
1665
- }
1666
- function extractComponents(path, state) {
1667
- const arg = path.node.argument;
1668
- if (!arg) return;
1669
- const compilerState = state;
1670
- if (compilerState.fields && compilerState.fields.length > 0) {
1671
- initLocalFieldMaps(compilerState.fields);
1672
- }
1673
- let experienceNode = null;
1674
- if (t6.isJSXElement(arg)) {
1675
- experienceNode = jsxToExperienceNode(arg);
1676
- } else if (t6.isJSXFragment(arg)) {
1677
- experienceNode = jsxToExperienceNode(arg);
1678
- }
1679
- if (experienceNode) {
1680
- compilerState.experience = experienceNode;
1681
- }
1682
- }
1683
-
1684
- // src/babel/extractors/during-extractor.ts
1685
- import * as t7 from "@babel/types";
1686
- var duringIdCounter = 0;
1687
- function resetDuringIdCounter() {
1688
- duringIdCounter = 0;
1689
- }
1690
- function analyzeCallbackBody2(body, actionCounter) {
1691
- const actions = [];
1692
- for (const statement of body) {
1693
- if (!t7.isExpressionStatement(statement)) continue;
1694
- const expr = statement.expression;
1695
- if (t7.isCallExpression(expr) && t7.isIdentifier(expr.callee)) {
1696
- const calleeName = expr.callee.name;
1697
- const args = expr.arguments;
1698
- if (calleeName === "setField" && args.length >= 2) {
1699
- const field = t7.isStringLiteral(args[0]) ? args[0].value : void 0;
1700
- const arg1 = args[1];
1701
- if (field !== void 0 && !t7.isArgumentPlaceholder(arg1)) {
1702
- actions.push({
1703
- id: `auto_${++actionCounter.value}`,
1704
- type: "set_field",
1705
- mode: "auto",
1706
- config: { field, value: extractValue2(arg1) }
1707
- });
1708
- }
1709
- } else if (calleeName === "setMemory" && args.length >= 2) {
1710
- const key = t7.isStringLiteral(args[0]) ? args[0].value : void 0;
1711
- const arg1 = args[1];
1712
- if (key !== void 0 && !t7.isArgumentPlaceholder(arg1)) {
1713
- actions.push({
1714
- id: `auto_${++actionCounter.value}`,
1715
- type: "set_memory",
1716
- mode: "auto",
1717
- config: { key, value: extractValue2(arg1) }
1718
- });
1719
- }
1720
- } else if (calleeName.startsWith("set") && calleeName.length > 3 && args.length >= 1) {
1721
- const fieldName = calleeName.slice(3, 4).toLowerCase() + calleeName.slice(4);
1722
- const arg0 = args[0];
1723
- if (!t7.isArgumentPlaceholder(arg0)) {
1724
- actions.push({
1725
- id: `auto_${++actionCounter.value}`,
1726
- type: "set_field",
1727
- mode: "auto",
1728
- config: { field: fieldName, value: extractValue2(arg0) }
1729
- });
1730
- }
1731
- }
1732
- } else if (t7.isCallExpression(expr)) {
1733
- const callee = expr.callee;
1734
- if (t7.isMemberExpression(callee) && t7.isIdentifier(callee.object) && callee.object.name === "console" && t7.isIdentifier(callee.property) && callee.property.name === "log" && expr.arguments.length > 0) {
1735
- const arg0 = expr.arguments[0];
1736
- if (!t7.isArgumentPlaceholder(arg0)) {
1737
- actions.push({
1738
- id: `auto_${++actionCounter.value}`,
1739
- type: "log_event",
1740
- mode: "auto",
1741
- config: { message: extractValue2(arg0) }
1742
- });
1743
- }
1744
- } else {
1745
- actions.push({
1746
- id: `auto_${++actionCounter.value}`,
1747
- type: "custom",
1748
- mode: "auto",
1749
- config: { expression: generateCode2(expr) }
1750
- });
1751
- }
1752
- }
1753
- }
1754
- return actions;
1755
- }
1756
- function extractValue2(node) {
1757
- if (t7.isNumericLiteral(node)) return node.value;
1758
- if (t7.isStringLiteral(node)) return node.value;
1759
- if (t7.isBooleanLiteral(node)) return node.value;
1760
- if (t7.isNullLiteral(node)) return null;
1761
- if (t7.isArrayExpression(node)) {
1762
- return node.elements.map((el) => el && t7.isExpression(el) ? extractValue2(el) : null);
1763
- }
1764
- if (t7.isObjectExpression(node)) {
1765
- const obj = {};
1766
- node.properties.forEach((prop) => {
1767
- if (t7.isObjectProperty(prop) && t7.isIdentifier(prop.key) && t7.isExpression(prop.value)) {
1768
- obj[prop.key.name] = extractValue2(prop.value);
1769
- }
1770
- });
1771
- return obj;
1772
- }
1773
- return generateCode2(node);
1774
- }
1775
- function generateCode2(node) {
1776
- if (t7.isIdentifier(node)) return node.name;
1777
- if (t7.isNumericLiteral(node)) return String(node.value);
1778
- if (t7.isStringLiteral(node)) return `"${node.value}"`;
1779
- if (t7.isBooleanLiteral(node)) return String(node.value);
1780
- if (t7.isNullLiteral(node)) return "null";
1781
- if (t7.isBinaryExpression(node)) {
1782
- return `(${generateCode2(node.left)} ${node.operator} ${generateCode2(node.right)})`;
1783
- }
1784
- if (t7.isLogicalExpression(node)) {
1785
- return `(${generateCode2(node.left)} ${node.operator} ${generateCode2(node.right)})`;
1786
- }
1787
- if (t7.isConditionalExpression(node)) {
1788
- return `(${generateCode2(node.test)} ? ${generateCode2(node.consequent)} : ${generateCode2(node.alternate)})`;
1789
- }
1790
- if (t7.isUnaryExpression(node) && node.prefix) {
1791
- return `${node.operator}${generateCode2(node.argument)}`;
1792
- }
1793
- if (t7.isCallExpression(node) && t7.isMemberExpression(node.callee) && t7.isIdentifier(node.callee.object) && node.callee.object.name === "Date" && t7.isIdentifier(node.callee.property) && node.callee.property.name === "now") {
1794
- return "now()";
1795
- }
1796
- if (t7.isMemberExpression(node)) {
1797
- const obj = generateCode2(node.object);
1798
- if (node.computed) {
1799
- return `${obj}[${generateCode2(node.property)}]`;
1800
- }
1801
- const prop = t7.isIdentifier(node.property) ? node.property.name : "[property]";
1802
- return `${obj}.${prop}`;
1803
- }
1804
- if (t7.isCallExpression(node)) {
1805
- if (t7.isIdentifier(node.callee)) {
1806
- const args = node.arguments.map((a) => generateCode2(a)).join(", ");
1807
- return `${node.callee.name}(${args})`;
1808
- }
1809
- if (t7.isMemberExpression(node.callee)) {
1810
- const obj = generateCode2(node.callee.object);
1811
- const prop = t7.isIdentifier(node.callee.property) ? node.callee.property.name : "[method]";
1812
- const args = node.arguments.map((a) => generateCode2(a)).join(", ");
1813
- return `${obj}.${prop}(${args})`;
1814
- }
1815
- }
1816
- if (t7.isArrowFunctionExpression(node) || t7.isFunctionExpression(node)) {
1817
- if (t7.isArrowFunctionExpression(node) && t7.isExpression(node.body)) {
1818
- const params = node.params;
1819
- if (params.length === 1 && t7.isIdentifier(params[0])) {
1820
- const paramName = params[0].name;
1821
- const bodyCode = generateCode2(node.body);
1822
- return bodyCode.replace(new RegExp(`\\b${paramName}\\b`, "g"), "$prev");
1823
- }
1824
- }
1825
- return "[Function]";
1826
- }
1827
- if (t7.isTemplateLiteral(node)) {
1828
- return node.quasis.map((q, i) => {
1829
- const raw = q.value.raw;
1830
- if (i < node.expressions.length) return raw + "${" + generateCode2(node.expressions[i]) + "}";
1831
- return raw;
1832
- }).join("");
1833
- }
1834
- if (t7.isArrayExpression(node)) {
1835
- const elements = node.elements.map((el) => el ? generateCode2(el) : "undefined").join(", ");
1836
- return `[${elements}]`;
1837
- }
1838
- if (t7.isObjectExpression(node)) {
1839
- const props = node.properties.map((p) => {
1840
- if (t7.isObjectProperty(p)) {
1841
- const key = t7.isIdentifier(p.key) ? p.key.name : t7.isStringLiteral(p.key) ? `"${p.key.value}"` : "[key]";
1842
- if (p.shorthand && t7.isIdentifier(p.value)) return key;
1843
- return `${key}: ${generateCode2(p.value)}`;
1844
- }
1845
- if (t7.isSpreadElement(p)) return `...${generateCode2(p.argument)}`;
1846
- return "";
1847
- }).filter(Boolean).join(", ");
1848
- return `{ ${props} }`;
1849
- }
1850
- if (t7.isTSAsExpression(node)) return generateCode2(node.expression);
1851
- if (t7.isTSNonNullExpression(node)) return generateCode2(node.expression);
1852
- return "[Expression]";
1853
- }
1854
- function ensureState3(states, stateName) {
1855
- if (!states.has(stateName)) {
1856
- states.set(stateName, {
1857
- name: stateName,
1858
- type: "REGULAR",
1859
- on_enter: [],
1860
- during: [],
1861
- on_exit: []
1862
- });
1863
- }
1864
- return states.get(stateName);
1865
- }
1866
- function extractDuring(path, state) {
1867
- const callee = path.node.callee;
1868
- if (!t7.isIdentifier(callee) || callee.name !== "useWhileIn") return;
1869
- const args = path.node.arguments;
1870
- if (args.length < 3) return;
1871
- const stateArg = args[0];
1872
- const intervalArg = args[1];
1873
- const callbackArg = args[2];
1874
- if (!t7.isStringLiteral(stateArg)) return;
1875
- const stateName = stateArg.value;
1876
- let intervalMs = 1e3;
1877
- if (t7.isNumericLiteral(intervalArg)) {
1878
- intervalMs = intervalArg.value;
1879
- }
1880
- let callbackBody = [];
1881
- if (t7.isArrowFunctionExpression(callbackArg) || t7.isFunctionExpression(callbackArg)) {
1882
- const body = callbackArg.body;
1883
- if (t7.isBlockStatement(body)) {
1884
- callbackBody = body.body;
1885
- } else if (t7.isExpression(body)) {
1886
- callbackBody = [t7.expressionStatement(body)];
1887
- }
1888
- }
1889
- const compilerState = state;
1890
- if (!compilerState.states) compilerState.states = /* @__PURE__ */ new Map();
1891
- if (!compilerState.actionCounter) compilerState.actionCounter = 0;
1892
- const stateDefinition = ensureState3(compilerState.states, stateName);
1893
- const actions = analyzeCallbackBody2(callbackBody, { value: compilerState.actionCounter });
1894
- compilerState.actionCounter += actions.length;
1895
- const duringAction = {
1896
- id: `during_${++duringIdCounter}`,
1897
- type: "interval",
1898
- interval_ms: intervalMs,
1899
- actions
1900
- };
1901
- stateDefinition.during.push(duringAction);
1902
- }
1903
-
1904
- // src/babel/extractors/change-extractor.ts
1905
- import * as t8 from "@babel/types";
1906
- var watcherIdCounter = 0;
1907
- function resetWatcherIdCounter() {
1908
- watcherIdCounter = 0;
1909
- }
1910
- function analyzeCallbackBody3(body, actionCounter) {
1911
- const actions = [];
1912
- for (const statement of body) {
1913
- if (!t8.isExpressionStatement(statement)) continue;
1914
- const expr = statement.expression;
1915
- if (t8.isCallExpression(expr) && t8.isIdentifier(expr.callee)) {
1916
- const calleeName = expr.callee.name;
1917
- const args = expr.arguments;
1918
- if (calleeName === "setField" && args.length >= 2) {
1919
- const field = t8.isStringLiteral(args[0]) ? args[0].value : void 0;
1920
- if (field !== void 0) {
1921
- actions.push({
1922
- id: `auto_${++actionCounter.value}`,
1923
- type: "set_field",
1924
- mode: "auto",
1925
- config: { field, value: extractValue3(args[1]) }
1926
- });
1927
- }
1928
- } else if (calleeName === "setMemory" && args.length >= 2) {
1929
- const key = t8.isStringLiteral(args[0]) ? args[0].value : void 0;
1930
- if (key !== void 0) {
1931
- actions.push({
1932
- id: `auto_${++actionCounter.value}`,
1933
- type: "set_memory",
1934
- mode: "auto",
1935
- config: { key, value: extractValue3(args[1]) }
1936
- });
1937
- }
1938
- } else if (calleeName.startsWith("set") && calleeName.length > 3 && args.length >= 1) {
1939
- const fieldName = calleeName.slice(3, 4).toLowerCase() + calleeName.slice(4);
1940
- actions.push({
1941
- id: `auto_${++actionCounter.value}`,
1942
- type: "set_field",
1943
- mode: "auto",
1944
- config: { field: fieldName, value: extractValue3(args[0]) }
1945
- });
1946
- }
1947
- } else if (t8.isCallExpression(expr)) {
1948
- const callee = expr.callee;
1949
- if (t8.isMemberExpression(callee) && t8.isIdentifier(callee.object) && callee.object.name === "console" && t8.isIdentifier(callee.property) && callee.property.name === "log" && expr.arguments.length > 0) {
1950
- actions.push({
1951
- id: `auto_${++actionCounter.value}`,
1952
- type: "log_event",
1953
- mode: "auto",
1954
- config: { message: extractValue3(expr.arguments[0]) }
1955
- });
1956
- }
1957
- }
1958
- }
1959
- return actions;
1960
- }
1961
- function extractValue3(node) {
1962
- if (t8.isNumericLiteral(node)) return node.value;
1963
- if (t8.isStringLiteral(node)) return node.value;
1964
- if (t8.isBooleanLiteral(node)) return node.value;
1965
- if (t8.isNullLiteral(node)) return null;
1966
- if (t8.isIdentifier(node)) return node.name;
1967
- if (t8.isTemplateLiteral(node)) {
1968
- return node.quasis.map((q, i) => {
1969
- const raw = q.value.raw;
1970
- if (i < node.expressions.length) {
1971
- const expr = node.expressions[i];
1972
- return raw + "${" + (t8.isIdentifier(expr) ? expr.name : "[expr]") + "}";
1973
- }
1974
- return raw;
1975
- }).join("");
1976
- }
1977
- if (t8.isArrayExpression(node)) {
1978
- return node.elements.map((el) => el && t8.isExpression(el) ? extractValue3(el) : null);
1979
- }
1980
- if (t8.isObjectExpression(node)) {
1981
- const obj = {};
1982
- node.properties.forEach((prop) => {
1983
- if (t8.isObjectProperty(prop) && t8.isIdentifier(prop.key) && t8.isExpression(prop.value)) {
1984
- obj[prop.key.name] = extractValue3(prop.value);
1985
- }
1986
- });
1987
- return obj;
1988
- }
1989
- if (t8.isMemberExpression(node)) {
1990
- const obj = t8.isIdentifier(node.object) ? node.object.name : "[object]";
1991
- const prop = t8.isIdentifier(node.property) ? node.property.name : "[property]";
1992
- return `${obj}.${prop}`;
1993
- }
1994
- if (t8.isConditionalExpression(node)) {
1995
- return `(${extractValue3(node.test)} ? ${extractValue3(node.consequent)} : ${extractValue3(node.alternate)})`;
1996
- }
1997
- if (t8.isBinaryExpression(node)) {
1998
- return `(${extractValue3(node.left)} ${node.operator} ${extractValue3(node.right)})`;
1999
- }
2000
- if (t8.isLogicalExpression(node)) {
2001
- return `(${extractValue3(node.left)} ${node.operator} ${extractValue3(node.right)})`;
2002
- }
2003
- if (t8.isTSAsExpression(node)) return extractValue3(node.expression);
2004
- if (t8.isTSNonNullExpression(node)) return extractValue3(node.expression);
2005
- return "[Expression]";
2006
- }
2007
- function extractChangeWatcher(path, state) {
2008
- const callee = path.node.callee;
2009
- if (!t8.isIdentifier(callee) || callee.name !== "useOnChange") return;
2010
- const args = path.node.arguments;
2011
- if (args.length < 2) return;
2012
- const fieldArg = args[0];
2013
- const callbackArg = args[1];
2014
- if (!t8.isStringLiteral(fieldArg)) return;
2015
- const field = fieldArg.value;
2016
- let callbackBody = [];
2017
- if (t8.isArrowFunctionExpression(callbackArg) || t8.isFunctionExpression(callbackArg)) {
2018
- const body = callbackArg.body;
2019
- if (t8.isBlockStatement(body)) {
2020
- callbackBody = body.body;
2021
- } else if (t8.isExpression(body)) {
2022
- callbackBody = [t8.expressionStatement(body)];
2023
- }
2024
- }
2025
- const compilerState = state;
2026
- if (!compilerState.actionCounter) compilerState.actionCounter = 0;
2027
- const actions = analyzeCallbackBody3(callbackBody, { value: compilerState.actionCounter });
2028
- compilerState.actionCounter += actions.length;
2029
- const watcher = {
2030
- id: `watcher_${++watcherIdCounter}`,
2031
- field,
2032
- actions
2033
- };
2034
- if (!compilerState.metadata) compilerState.metadata = {};
2035
- const meta = compilerState.metadata;
2036
- if (!meta.fieldWatchers) meta.fieldWatchers = [];
2037
- meta.fieldWatchers.push(watcher);
2038
- }
2039
-
2040
- // src/babel/extractors/computed-extractor.ts
2041
- import * as t9 from "@babel/types";
2042
- function expressionToString(node) {
2043
- if (t9.isIdentifier(node)) return node.name;
2044
- if (t9.isNumericLiteral(node)) return String(node.value);
2045
- if (t9.isStringLiteral(node)) return `"${node.value}"`;
2046
- if (t9.isBooleanLiteral(node)) return String(node.value);
2047
- if (t9.isNullLiteral(node)) return "null";
2048
- if (t9.isTemplateLiteral(node)) {
2049
- return node.quasis.map((q, i) => {
2050
- const raw = q.value.raw;
2051
- if (i < node.expressions.length) {
2052
- const expr = node.expressions[i];
2053
- return raw + "${" + expressionToString(expr) + "}";
2054
- }
2055
- return raw;
2056
- }).join("");
2057
- }
2058
- if (t9.isBinaryExpression(node)) {
2059
- return `${expressionToString(node.left)} ${node.operator} ${expressionToString(node.right)}`;
2060
- }
2061
- if (t9.isLogicalExpression(node)) {
2062
- return `${expressionToString(node.left)} ${node.operator} ${expressionToString(node.right)}`;
2063
- }
2064
- if (t9.isConditionalExpression(node)) {
2065
- return `${expressionToString(node.test)} ? ${expressionToString(node.consequent)} : ${expressionToString(node.alternate)}`;
2066
- }
2067
- if (t9.isMemberExpression(node) && !node.computed) {
2068
- return `${expressionToString(node.object)}.${expressionToString(node.property)}`;
2069
- }
2070
- if (t9.isCallExpression(node)) {
2071
- const callee = expressionToString(node.callee);
2072
- const args = node.arguments.map((a) => expressionToString(a)).join(", ");
2073
- return `${callee}(${args})`;
2074
- }
2075
- if (t9.isUnaryExpression(node)) {
2076
- return `${node.operator}${expressionToString(node.argument)}`;
2077
- }
2078
- if (t9.isParenthesizedExpression(node)) {
2079
- return `(${expressionToString(node.expression)})`;
2080
- }
2081
- return "[Expression]";
2082
- }
2083
- function inferComputedType(body) {
2084
- if (t9.isNumericLiteral(body) || t9.isBinaryExpression(body)) return "number";
2085
- if (t9.isStringLiteral(body) || t9.isTemplateLiteral(body)) return "text";
2086
- if (t9.isBooleanLiteral(body) || t9.isLogicalExpression(body)) return "boolean";
2087
- if (t9.isArrayExpression(body)) return "json";
2088
- if (t9.isObjectExpression(body)) return "json";
2089
- return "text";
2090
- }
2091
- function extractStringArray(node) {
2092
- if (!t9.isArrayExpression(node)) return [];
2093
- return node.elements.filter((el) => t9.isStringLiteral(el)).map((el) => el.value);
2094
- }
2095
- function extractComputed(path, state) {
2096
- const callee = path.node.callee;
2097
- if (!t9.isIdentifier(callee) || callee.name !== "useComputed") return;
2098
- const args = path.node.arguments;
2099
- if (args.length < 2) return;
2100
- const nameArg = args[0];
2101
- if (!t9.isStringLiteral(nameArg)) return;
2102
- const fieldName = nameArg.value;
2103
- const computeArg = args[1];
2104
- if (!t9.isArrowFunctionExpression(computeArg) && !t9.isFunctionExpression(computeArg)) return;
2105
- let expression;
2106
- let returnType = "text";
2107
- if (t9.isExpression(computeArg.body) && !t9.isBlockStatement(computeArg.body)) {
2108
- expression = expressionToString(computeArg.body);
2109
- returnType = inferComputedType(computeArg.body);
2110
- } else if (t9.isBlockStatement(computeArg.body)) {
2111
- const returnStmt = computeArg.body.body.find(
2112
- (s) => t9.isReturnStatement(s)
2113
- );
2114
- if (returnStmt?.argument) {
2115
- expression = expressionToString(returnStmt.argument);
2116
- returnType = inferComputedType(returnStmt.argument);
2117
- } else {
2118
- expression = "[Expression]";
2119
- }
2120
- } else {
2121
- expression = "[Expression]";
2122
- }
2123
- let mode = "read-time";
2124
- let deps = [];
2125
- let staleness;
2126
- let rlsStalenessOk;
2127
- let explicitType;
2128
- if (args.length >= 3 && t9.isObjectExpression(args[2])) {
2129
- const optObj = args[2];
2130
- for (const prop of optObj.properties) {
2131
- if (!t9.isObjectProperty(prop) || !t9.isIdentifier(prop.key)) continue;
2132
- switch (prop.key.name) {
2133
- case "mode":
2134
- if (t9.isStringLiteral(prop.value)) {
2135
- const modeVal = prop.value.value;
2136
- if (modeVal === "read-time" || modeVal === "transaction-maintained" || modeVal === "async-materialized") {
2137
- mode = modeVal;
2138
- }
2139
- }
2140
- break;
2141
- case "deps":
2142
- deps = extractStringArray(prop.value);
2143
- break;
2144
- case "staleness":
2145
- if (t9.isStringLiteral(prop.value)) {
2146
- staleness = prop.value.value;
2147
- }
2148
- break;
2149
- case "rlsStalenessOk":
2150
- if (t9.isBooleanLiteral(prop.value)) {
2151
- rlsStalenessOk = prop.value.value;
2152
- }
2153
- break;
2154
- case "type":
2155
- if (t9.isStringLiteral(prop.value)) {
2156
- explicitType = prop.value.value;
2157
- }
2158
- break;
2159
- }
2160
- }
2161
- }
2162
- let varName = fieldName;
2163
- const parent = path.parentPath;
2164
- if (parent?.isVariableDeclarator() && t9.isIdentifier(parent.node.id)) {
2165
- varName = parent.node.id.name;
2166
- }
2167
- const compilerState = state;
2168
- const fieldDef = {
2169
- name: fieldName,
2170
- type: explicitType || returnType,
2171
- computed: expression,
2172
- computed_deps: deps.length > 0 ? deps : void 0
2173
- };
2174
- fieldDef.computed_mode = mode;
2175
- if (staleness !== void 0) {
2176
- fieldDef.computed_staleness = staleness;
2177
- }
2178
- if (rlsStalenessOk !== void 0) {
2179
- fieldDef.rls_staleness_tolerance = rlsStalenessOk;
2180
- }
2181
- compilerState.fields.push(fieldDef);
2182
- if (!compilerState.metadata) compilerState.metadata = {};
2183
- const meta = compilerState.metadata;
2184
- if (!meta.computedFields) meta.computedFields = [];
2185
- meta.computedFields.push({
2186
- name: fieldName,
2187
- varName,
2188
- expression,
2189
- deps,
2190
- mode,
2191
- type: explicitType || returnType,
2192
- staleness,
2193
- rlsStalenessOk
2194
- });
2195
- }
2196
-
2197
- // src/babel/extractors/transition-effect-extractor.ts
2198
- import * as t10 from "@babel/types";
2199
- var transitionEffectIdCounter = 0;
2200
- function resetTransitionEffectIdCounter() {
2201
- transitionEffectIdCounter = 0;
2202
- }
2203
- function analyzeCallbackBody4(body, actionCounter) {
2204
- const actions = [];
2205
- for (const statement of body) {
2206
- if (!t10.isExpressionStatement(statement)) continue;
2207
- const expr = statement.expression;
2208
- if (t10.isCallExpression(expr) && t10.isIdentifier(expr.callee)) {
2209
- const calleeName = expr.callee.name;
2210
- const args = expr.arguments;
2211
- if (calleeName === "setField" && args.length >= 2) {
2212
- const field = t10.isStringLiteral(args[0]) ? args[0].value : void 0;
2213
- if (field !== void 0) {
2214
- actions.push({
2215
- id: `auto_${++actionCounter.value}`,
2216
- type: "set_field",
2217
- mode: "auto",
2218
- config: { field, value: extractValue4(args[1]) }
2219
- });
2220
- }
2221
- } else if (calleeName === "setMemory" && args.length >= 2) {
2222
- const key = t10.isStringLiteral(args[0]) ? args[0].value : void 0;
2223
- if (key !== void 0) {
2224
- actions.push({
2225
- id: `auto_${++actionCounter.value}`,
2226
- type: "set_memory",
2227
- mode: "auto",
2228
- config: { key, value: extractValue4(args[1]) }
2229
- });
2230
- }
2231
- } else if (calleeName.startsWith("set") && calleeName.length > 3 && args.length >= 1) {
2232
- const fieldName = calleeName.slice(3, 4).toLowerCase() + calleeName.slice(4);
2233
- actions.push({
2234
- id: `auto_${++actionCounter.value}`,
2235
- type: "set_field",
2236
- mode: "auto",
2237
- config: { field: fieldName, value: extractValue4(args[0]) }
2238
- });
2239
- }
2240
- } else if (t10.isCallExpression(expr)) {
2241
- const callee = expr.callee;
2242
- if (t10.isMemberExpression(callee) && t10.isIdentifier(callee.object) && callee.object.name === "console" && t10.isIdentifier(callee.property) && callee.property.name === "log" && expr.arguments.length > 0) {
2243
- actions.push({
2244
- id: `auto_${++actionCounter.value}`,
2245
- type: "log_event",
2246
- mode: "auto",
2247
- config: { message: extractValue4(expr.arguments[0]) }
2248
- });
2249
- }
2250
- }
2251
- }
2252
- return actions;
2253
- }
2254
- function extractValue4(node) {
2255
- if (t10.isNumericLiteral(node)) return node.value;
2256
- if (t10.isStringLiteral(node)) return node.value;
2257
- if (t10.isBooleanLiteral(node)) return node.value;
2258
- if (t10.isNullLiteral(node)) return null;
2259
- if (t10.isIdentifier(node)) return node.name;
2260
- if (t10.isArrayExpression(node)) {
2261
- return node.elements.map((el) => el && t10.isExpression(el) ? extractValue4(el) : null);
2262
- }
2263
- if (t10.isObjectExpression(node)) {
2264
- const obj = {};
2265
- node.properties.forEach((prop) => {
2266
- if (t10.isObjectProperty(prop) && t10.isIdentifier(prop.key) && t10.isExpression(prop.value)) {
2267
- obj[prop.key.name] = extractValue4(prop.value);
2268
- }
2269
- });
2270
- return obj;
2271
- }
2272
- if (t10.isMemberExpression(node)) {
2273
- const obj = t10.isIdentifier(node.object) ? node.object.name : "[object]";
2274
- const prop = t10.isIdentifier(node.property) ? node.property.name : "[property]";
2275
- return `${obj}.${prop}`;
2276
- }
2277
- if (t10.isConditionalExpression(node)) {
2278
- return `(${extractValue4(node.test)} ? ${extractValue4(node.consequent)} : ${extractValue4(node.alternate)})`;
2279
- }
2280
- if (t10.isTSAsExpression(node)) return extractValue4(node.expression);
2281
- if (t10.isTSNonNullExpression(node)) return extractValue4(node.expression);
2282
- return "[Expression]";
2283
- }
2284
- function extractTransitionEffect(path, state) {
2285
- const callee = path.node.callee;
2286
- if (!t10.isIdentifier(callee) || callee.name !== "useOnTransition") return;
2287
- const args = path.node.arguments;
2288
- if (args.length < 1) return;
2289
- const callbackArg = args[0];
2290
- let callbackBody = [];
2291
- if (t10.isArrowFunctionExpression(callbackArg) || t10.isFunctionExpression(callbackArg)) {
2292
- const body = callbackArg.body;
2293
- if (t10.isBlockStatement(body)) {
2294
- callbackBody = body.body;
2295
- } else if (t10.isExpression(body)) {
2296
- callbackBody = [t10.expressionStatement(body)];
2297
- }
2298
- }
2299
- const compilerState = state;
2300
- if (!compilerState.actionCounter) compilerState.actionCounter = 0;
2301
- const actions = analyzeCallbackBody4(callbackBody, { value: compilerState.actionCounter });
2302
- compilerState.actionCounter += actions.length;
2303
- const effect = {
2304
- id: `transition_effect_${++transitionEffectIdCounter}`,
2305
- actions
2306
- };
2307
- if (!compilerState.metadata) compilerState.metadata = {};
2308
- const meta = compilerState.metadata;
2309
- if (!meta.transitionEffects) meta.transitionEffects = [];
2310
- meta.transitionEffects.push(effect);
2311
- }
2312
-
2313
- // src/babel/extractors/model-extractor.ts
2314
- import * as t11 from "@babel/types";
2315
- function tsTypeToFieldType(typeAnnotation) {
2316
- if (!typeAnnotation) return "text";
2317
- const annotation = typeAnnotation.typeAnnotation;
2318
- return resolveType(annotation);
2319
- }
2320
- var KNOWN_TYPE_REFS2 = {
2321
- Date: "datetime",
2322
- Record: "json",
2323
- Map: "json",
2324
- Set: "json",
2325
- URL: "url"
2326
- };
2327
- function typeNameToSlug2(name) {
2328
- return name.replace(/([A-Z])/g, "-$1").toLowerCase().replace(/^-/, "");
2329
- }
2330
- function resolveType(annotation) {
2331
- if (t11.isTSStringKeyword(annotation)) return "text";
2332
- if (t11.isTSNumberKeyword(annotation)) return "number";
2333
- if (t11.isTSBooleanKeyword(annotation)) return "boolean";
2334
- if (t11.isTSTypeReference(annotation) && t11.isIdentifier(annotation.typeName)) {
2335
- const typeName = annotation.typeName.name;
2336
- if (KNOWN_TYPE_REFS2[typeName]) return KNOWN_TYPE_REFS2[typeName];
2337
- if (typeName === "Array") return "multi_select";
2338
- return typeNameToSlug2(typeName);
2339
- }
2340
- if (t11.isTSArrayType(annotation)) {
2341
- return "multi_select";
2342
- }
2343
- if (t11.isTSUnionType(annotation)) {
2344
- const allLiterals = annotation.types.every(
2345
- (t22) => t11.isTSLiteralType(t22) && (t11.isStringLiteral(t22.literal) || t11.isNumericLiteral(t22.literal))
2346
- );
2347
- if (allLiterals) return "select";
2348
- return "text";
2349
- }
2350
- if (t11.isTSLiteralType(annotation) && t11.isStringLiteral(annotation.literal)) return "text";
2351
- if (t11.isTSLiteralType(annotation) && t11.isNumericLiteral(annotation.literal)) return "number";
2352
- return "text";
2353
- }
2354
- function extractUnionOptions(annotation) {
2355
- if (!t11.isTSUnionType(annotation)) return void 0;
2356
- const options = [];
2357
- for (const member of annotation.types) {
2358
- if (t11.isTSLiteralType(member) && t11.isStringLiteral(member.literal)) {
2359
- options.push(member.literal.value);
2360
- }
2361
- }
2362
- return options.length > 0 ? options : void 0;
2363
- }
2364
- function extractDefaultValue2(fieldType) {
2365
- switch (fieldType) {
2366
- case "text":
2367
- return "";
2368
- case "rich_text":
2369
- return "";
2370
- case "number":
2371
- return 0;
2372
- case "boolean":
2373
- return false;
2374
- case "date":
2375
- return null;
2376
- case "datetime":
2377
- return null;
2378
- case "select":
2379
- return "";
2380
- case "multi_select":
2381
- return [];
2382
- case "url":
2383
- return "";
2384
- case "json":
2385
- return {};
2386
- // Custom Element-based field types (email, currency, etc.) default to null
2387
- default:
2388
- return null;
2389
- }
2390
- }
2391
- function extractFieldsFromInterface(declaration) {
2392
- const fields = [];
2393
- for (const member of declaration.body.body) {
2394
- if (!t11.isTSPropertySignature(member)) continue;
2395
- if (!t11.isIdentifier(member.key)) continue;
2396
- const name = member.key.name;
2397
- const required = !member.optional;
2398
- const typeAnno = member.typeAnnotation;
2399
- const fieldType = tsTypeToFieldType(typeAnno);
2400
- const field = {
2401
- name,
2402
- type: fieldType,
2403
- label: name.replace(/([A-Z])/g, " $1").replace(/^./, (c) => c.toUpperCase()),
2404
- required,
2405
- default_value: extractDefaultValue2(fieldType)
2406
- };
2407
- if (typeAnno) {
2408
- const options = extractUnionOptions(typeAnno.typeAnnotation);
2409
- if (options) {
2410
- field.validation = { options };
2411
- }
2412
- }
2413
- fields.push(field);
2414
- }
2415
- return fields;
2416
- }
2417
- function extractTransitionsFromObject(init, actionCounter) {
2418
- const transitions = [];
2419
- for (const prop of init.properties) {
2420
- if (!t11.isObjectProperty(prop)) continue;
2421
- if (!t11.isIdentifier(prop.key) && !t11.isStringLiteral(prop.key)) continue;
2422
- if (!t11.isObjectExpression(prop.value)) continue;
2423
- const name = t11.isIdentifier(prop.key) ? prop.key.name : prop.key.value;
2424
- const config = extractObjectLiteral(prop.value);
2425
- let from = [];
2426
- if (typeof config.from === "string") {
2427
- from = [config.from];
2428
- } else if (Array.isArray(config.from)) {
2429
- from = config.from.map(String);
2430
- }
2431
- const to = String(config.to || "");
2432
- const conditions = [];
2433
- if (config.guard) {
2434
- conditions.push(parseGuardExpression(config.guard));
2435
- }
2436
- if (config.conditions && Array.isArray(config.conditions)) {
2437
- for (const cond of config.conditions) {
2438
- conditions.push(cond);
2439
- }
2440
- }
2441
- const actions = [];
2442
- if (config.actions && Array.isArray(config.actions)) {
2443
- for (const action of config.actions) {
2444
- if (typeof action === "object" && action !== null) {
2445
- actions.push({
2446
- id: `auto_${++actionCounter.value}`,
2447
- type: action.type || "custom",
2448
- mode: "auto",
2449
- config: action
2450
- });
2451
- }
2452
- }
2453
- }
2454
- transitions.push({
2455
- name,
2456
- from,
2457
- to,
2458
- description: config.description,
2459
- conditions: conditions.length > 0 ? conditions : void 0,
2460
- actions,
2461
- roles: config.roles,
2462
- auto: config.auto,
2463
- required_fields: config.required_fields
2464
- });
2465
- }
2466
- return transitions;
2467
- }
2468
- function parseGuardExpression(guard) {
2469
- const simpleMatch = guard.match(
2470
- /^(\$?\w+(?:\.\w+)*)\s*(not_in|is_set|is_empty|contains|>=|<=|!=|==|>|<|in)\s*(.+)?$/
2471
- );
2472
- if (simpleMatch) {
2473
- const [, field, op, rawValue] = simpleMatch;
2474
- const operatorMap = {
2475
- "==": "eq",
2476
- "!=": "ne",
2477
- ">": "gt",
2478
- ">=": "gte",
2479
- "<": "lt",
2480
- "<=": "lte",
2481
- "in": "in",
2482
- "not_in": "not_in",
2483
- "contains": "contains",
2484
- "is_set": "is_set",
2485
- "is_empty": "is_empty"
2486
- };
2487
- const operator = operatorMap[op];
2488
- if (operator) {
2489
- let value = rawValue?.trim();
2490
- if (value === void 0 || value === "") {
2491
- return { field, operator };
2492
- }
2493
- if (typeof value === "string") {
2494
- if (value.startsWith('"') && value.endsWith('"')) {
2495
- value = value.slice(1, -1);
2496
- } else if (value.startsWith("'") && value.endsWith("'")) {
2497
- value = value.slice(1, -1);
2498
- } else if (value === "true") {
2499
- value = true;
2500
- } else if (value === "false") {
2501
- value = false;
2502
- } else if (value === "null") {
2503
- value = null;
2504
- } else if (!isNaN(Number(value))) {
2505
- value = Number(value);
2506
- }
2507
- }
2508
- return { field, operator, value };
2509
- }
2510
- }
2511
- return { expression: guard };
2512
- }
2513
- function extractHooksFromObject(init, states, actionCounter) {
2514
- for (const prop of init.properties) {
2515
- if (!t11.isObjectProperty(prop)) continue;
2516
- if (!t11.isIdentifier(prop.key) && !t11.isStringLiteral(prop.key)) continue;
2517
- const hookName = t11.isIdentifier(prop.key) ? prop.key.name : prop.key.value;
2518
- const hookConfig = t11.isObjectExpression(prop.value) ? extractObjectLiteral(prop.value) : {};
2519
- const enterMatch = hookName.match(/^on_enter_(.+)$/);
2520
- const exitMatch = hookName.match(/^on_exit_(.+)$/);
2521
- if (!enterMatch && !exitMatch) continue;
2522
- const stateName = enterMatch ? enterMatch[1] : exitMatch[1];
2523
- const phase = enterMatch ? "on_enter" : "on_exit";
2524
- if (!states.has(stateName)) {
2525
- states.set(stateName, {
2526
- name: stateName,
2527
- type: "REGULAR",
2528
- on_enter: [],
2529
- during: [],
2530
- on_exit: []
2531
- });
2532
- }
2533
- const state = states.get(stateName);
2534
- if (hookConfig.emit && typeof hookConfig.emit === "string") {
2535
- const action = {
2536
- id: `auto_${++actionCounter.value}`,
2537
- type: "emit_event",
2538
- mode: "auto",
2539
- config: { event: hookConfig.emit }
2540
- };
2541
- state[phase].push(action);
2542
- }
2543
- if (hookConfig.actions && Array.isArray(hookConfig.actions)) {
2544
- for (const handler of hookConfig.actions) {
2545
- if (typeof handler === "string") {
2546
- const action = {
2547
- id: `auto_${++actionCounter.value}`,
2548
- type: "server_action",
2549
- mode: "auto",
2550
- config: { handler }
2551
- };
2552
- state[phase].push(action);
2553
- }
2554
- }
2555
- }
2556
- }
2557
- }
2558
- function applyFieldOptions(fields, init) {
2559
- const options = extractObjectLiteral(init);
2560
- for (const [fieldName, opts] of Object.entries(options)) {
2561
- const field = fields.find((f) => f.name === fieldName);
2562
- if (!field) continue;
2563
- if (opts.scope || opts.persistence || opts.sync) {
2564
- field.state_home = {
2565
- scope: opts.scope || "instance",
2566
- persistence: opts.persistence || "durable",
2567
- sync: opts.sync || "none"
2568
- };
2569
- }
2570
- if (opts.computed && typeof opts.computed === "string") {
2571
- field.computed = opts.computed;
2572
- }
2573
- if (opts.computed_deps && Array.isArray(opts.computed_deps)) {
2574
- field.computed_deps = opts.computed_deps.map(String);
2575
- }
2576
- if (opts.visible_in_states && Array.isArray(opts.visible_in_states)) {
2577
- field.visible_in_states = opts.visible_in_states.map(String);
2578
- }
2579
- if (opts.editable_in_states && Array.isArray(opts.editable_in_states)) {
2580
- field.editable_in_states = opts.editable_in_states.map(String);
2581
- }
2582
- if (opts.visible_to_roles && Array.isArray(opts.visible_to_roles)) {
2583
- field.visible_to_roles = opts.visible_to_roles.map(String);
2584
- }
2585
- if (opts.editable_by_roles && Array.isArray(opts.editable_by_roles)) {
2586
- field.editable_by_roles = opts.editable_by_roles.map(String);
2587
- }
2588
- if (opts.visible_when && typeof opts.visible_when === "string") {
2589
- field.visible_when = opts.visible_when;
2590
- }
2591
- if (opts.editable_when && typeof opts.editable_when === "string") {
2592
- field.editable_when = opts.editable_when;
2593
- }
2594
- if (opts.validation && typeof opts.validation === "object") {
2595
- const val = opts.validation;
2596
- const validation = field.validation || {};
2597
- if (val.min !== void 0) validation.min = Number(val.min);
2598
- if (val.max !== void 0) validation.max = Number(val.max);
2599
- if (val.minLength !== void 0) validation.minLength = Number(val.minLength);
2600
- if (val.maxLength !== void 0) validation.maxLength = Number(val.maxLength);
2601
- if (val.options && Array.isArray(val.options)) {
2602
- validation.options = val.options.map(String);
2603
- }
2604
- if (val.rules && Array.isArray(val.rules)) {
2605
- validation.rules = val.rules.map((r) => ({
2606
- expression: String(r.expression || ""),
2607
- message: String(r.message || ""),
2608
- severity: r.severity === "warning" ? "warning" : "error"
2609
- }));
2610
- }
2611
- field.validation = validation;
2612
- }
2613
- }
2614
- }
2615
- function extractObjectLiteral(node) {
2616
- const obj = {};
2617
- for (const prop of node.properties) {
2618
- if (!t11.isObjectProperty(prop)) continue;
2619
- const key = t11.isIdentifier(prop.key) ? prop.key.name : t11.isStringLiteral(prop.key) ? prop.key.value : null;
2620
- if (!key) continue;
2621
- obj[key] = extractNodeValue(prop.value);
2622
- }
2623
- return obj;
2624
- }
2625
- function extractNodeValue(node) {
2626
- if (t11.isStringLiteral(node)) return node.value;
2627
- if (t11.isNumericLiteral(node)) return node.value;
2628
- if (t11.isBooleanLiteral(node)) return node.value;
2629
- if (t11.isNullLiteral(node)) return null;
2630
- if (t11.isArrayExpression(node)) {
2631
- return node.elements.map((el) => {
2632
- if (!el) return null;
2633
- if (t11.isSpreadElement(el)) return "[Spread]";
2634
- return extractNodeValue(el);
2635
- });
2636
- }
2637
- if (t11.isObjectExpression(node)) {
2638
- return extractObjectLiteral(node);
2639
- }
2640
- if (t11.isTemplateLiteral(node)) {
2641
- return node.quasis.map((q) => q.value.raw).join("${}");
2642
- }
2643
- if (t11.isIdentifier(node)) {
2644
- if (node.name === "undefined") return void 0;
2645
- return node.name;
2646
- }
2647
- if (t11.isConditionalExpression(node)) {
2648
- return `(${extractNodeValue(node.test)} ? ${extractNodeValue(node.consequent)} : ${extractNodeValue(node.alternate)})`;
2649
- }
2650
- if (t11.isBinaryExpression(node)) {
2651
- return `(${extractNodeValue(node.left)} ${node.operator} ${extractNodeValue(node.right)})`;
2652
- }
2653
- if (t11.isLogicalExpression(node)) {
2654
- return `(${extractNodeValue(node.left)} ${node.operator} ${extractNodeValue(node.right)})`;
2655
- }
2656
- if (t11.isMemberExpression(node)) {
2657
- const obj = t11.isIdentifier(node.object) ? node.object.name : "[object]";
2658
- const prop = t11.isIdentifier(node.property) ? node.property.name : "[property]";
2659
- return `${obj}.${prop}`;
2660
- }
2661
- if (t11.isTSAsExpression(node)) return extractNodeValue(node.expression);
2662
- if (t11.isTSNonNullExpression(node)) return extractNodeValue(node.expression);
2663
- return "[Expression]";
2664
- }
2665
- function isModelFile(path, filename) {
2666
- if (filename && /\/models\//.test(filename)) return true;
2667
- let hasInterface = false;
2668
- let hasTransitions = false;
2669
- let hasDefineModel = false;
2670
- for (const node of path.node.body) {
2671
- if (t11.isExportDefaultDeclaration(node)) {
2672
- const decl = node.declaration;
2673
- if (t11.isCallExpression(decl) && t11.isIdentifier(decl.callee) && decl.callee.name === "defineModel") {
2674
- hasDefineModel = true;
2675
- }
2676
- }
2677
- if (t11.isExportNamedDeclaration(node)) {
2678
- if (t11.isTSInterfaceDeclaration(node.declaration)) {
2679
- hasInterface = true;
2680
- }
2681
- if (t11.isVariableDeclaration(node.declaration)) {
2682
- for (const decl of node.declaration.declarations) {
2683
- if (t11.isIdentifier(decl.id) && decl.id.name === "transitions") {
2684
- hasTransitions = true;
2685
- }
2686
- }
2687
- }
2688
- }
2689
- }
2690
- return hasDefineModel || hasInterface && hasTransitions;
2691
- }
2692
- function modelTypeToIRType(modelType) {
2693
- switch (modelType) {
2694
- case "string":
2695
- return "text";
2696
- case "number":
2697
- return "number";
2698
- case "boolean":
2699
- return "boolean";
2700
- case "date":
2701
- return "date";
2702
- case "array":
2703
- return "multi_select";
2704
- case "json":
2705
- return "json";
2706
- case "file":
2707
- return "file";
2708
- case "relation":
2709
- return "relation";
2710
- default:
2711
- return modelType;
2712
- }
2713
- }
2714
- function modelStateTypeToIR(type) {
2715
- if (type === "initial") return "START";
2716
- if (type === "final") return "END";
2717
- return "REGULAR";
2718
- }
2719
- function extractDefineModelCall(programPath, compilerState, actionCounter) {
2720
- for (const node of programPath.node.body) {
2721
- if (!t11.isExportDefaultDeclaration(node)) continue;
2722
- const decl = node.declaration;
2723
- if (!t11.isCallExpression(decl)) continue;
2724
- if (!t11.isIdentifier(decl.callee) || decl.callee.name !== "defineModel") continue;
2725
- if (decl.arguments.length === 0 || !t11.isObjectExpression(decl.arguments[0])) continue;
2726
- const config = extractObjectLiteral(decl.arguments[0]);
2727
- if (config.slug) compilerState.metadata.slug = String(config.slug);
2728
- if (config.version) compilerState.metadata.version = String(config.version);
2729
- if (config.category) {
2730
- if (Array.isArray(config.category)) {
2731
- compilerState.metadata.category = String(config.category[0]);
2732
- compilerState.metadata.categoryArray = config.category;
2733
- } else {
2734
- compilerState.metadata.category = String(config.category);
2735
- }
2736
- }
2737
- if (config.description) compilerState.metadata.description = String(config.description);
2738
- if (config.fields && typeof config.fields === "object" && !Array.isArray(config.fields)) {
2739
- const fieldsObj = config.fields;
2740
- for (const [name, fieldConfig] of Object.entries(fieldsObj)) {
2741
- const irType = modelTypeToIRType(String(fieldConfig.type || "text"));
2742
- const field = {
2743
- name,
2744
- type: irType,
2745
- required: fieldConfig.required === true,
2746
- default_value: fieldConfig.default !== void 0 ? fieldConfig.default : extractDefaultValue2(irType)
2747
- };
2748
- if (fieldConfig.enum && Array.isArray(fieldConfig.enum)) {
2749
- field.validation = { options: fieldConfig.enum.map(String) };
2750
- }
2751
- compilerState.fields.push(field);
2752
- }
2753
- }
2754
- if (config.states && typeof config.states === "object" && !Array.isArray(config.states)) {
2755
- const statesObj = config.states;
2756
- for (const [name, stateConfig] of Object.entries(statesObj)) {
2757
- const stateType = modelStateTypeToIR(stateConfig.type);
2758
- if (!compilerState.states.has(name)) {
2759
- compilerState.states.set(name, {
2760
- name,
2761
- type: stateType,
2762
- description: stateConfig.description,
2763
- on_enter: [],
2764
- during: [],
2765
- on_exit: []
2766
- });
2767
- } else {
2768
- compilerState.states.get(name).type = stateType;
2769
- }
2770
- }
2771
- }
2772
- if (config.transitions && typeof config.transitions === "object" && !Array.isArray(config.transitions)) {
2773
- const transObj = config.transitions;
2774
- for (const [name, transConfig] of Object.entries(transObj)) {
2775
- let from = [];
2776
- if (typeof transConfig.from === "string") {
2777
- from = [transConfig.from];
2778
- } else if (Array.isArray(transConfig.from)) {
2779
- from = transConfig.from.map(String);
2780
- }
2781
- const to = String(transConfig.to || "");
2782
- for (const f of from) {
2783
- if (!compilerState.states.has(f)) {
2784
- compilerState.states.set(f, {
2785
- name: f,
2786
- type: "REGULAR",
2787
- on_enter: [],
2788
- during: [],
2789
- on_exit: []
2790
- });
2791
- }
2792
- }
2793
- if (to && !compilerState.states.has(to)) {
2794
- compilerState.states.set(to, {
2795
- name: to,
2796
- type: "REGULAR",
2797
- on_enter: [],
2798
- during: [],
2799
- on_exit: []
2800
- });
2801
- }
2802
- const conditions = [];
2803
- if (transConfig.guard) {
2804
- conditions.push(parseGuardExpression(String(transConfig.guard)));
2805
- }
2806
- compilerState.transitions.push({
2807
- name,
2808
- from,
2809
- to,
2810
- description: transConfig.description,
2811
- conditions: conditions.length > 0 ? conditions : void 0,
2812
- actions: [],
2813
- roles: transConfig.roles,
2814
- auto: transConfig.auto,
2815
- required_fields: transConfig.required_fields
2816
- });
2817
- }
2818
- }
2819
- if (config.roles && typeof config.roles === "object" && !Array.isArray(config.roles)) {
2820
- const rolesObj = config.roles;
2821
- if (!compilerState.metadata.roles) compilerState.metadata.roles = {};
2822
- for (const [roleName, roleConfig] of Object.entries(rolesObj)) {
2823
- compilerState.metadata.roles[roleName] = {
2824
- description: roleConfig.description,
2825
- permissions: roleConfig.permissions
2826
- };
2827
- }
2828
- }
2829
- if (config.metadata && typeof config.metadata === "object") {
2830
- compilerState.metadata.modelMetadata = config.metadata;
2831
- }
2832
- return true;
2833
- }
2834
- return false;
2835
- }
2836
- function extractModelFile(path, state) {
2837
- const compilerState = state;
2838
- if (!compilerState.actionCounter) compilerState.actionCounter = 0;
2839
- const actionCounter = { value: compilerState.actionCounter };
2840
- const foundDefineModel = extractDefineModelCall(path, compilerState, actionCounter);
2841
- if (foundDefineModel) {
2842
- for (const node of path.node.body) {
2843
- if (t11.isExportNamedDeclaration(node) && t11.isTSInterfaceDeclaration(node.declaration)) {
2844
- const interfaceFields = extractFieldsFromInterface(node.declaration);
2845
- for (const iField of interfaceFields) {
2846
- const existing = compilerState.fields.find((f) => f.name === iField.name);
2847
- if (existing) {
2848
- if (iField.required) existing.required = true;
2849
- }
2850
- }
2851
- if (!compilerState.metadata.name) {
2852
- compilerState.metadata.name = node.declaration.id.name;
2853
- }
2854
- }
2855
- }
2856
- compilerState.actionCounter = actionCounter.value;
2857
- return;
2858
- }
2859
- let interfaceName = "";
2860
- for (const node of path.node.body) {
2861
- if (!t11.isExportNamedDeclaration(node)) continue;
2862
- const declaration = node.declaration;
2863
- if (t11.isTSInterfaceDeclaration(declaration)) {
2864
- interfaceName = declaration.id.name;
2865
- const fields = extractFieldsFromInterface(declaration);
2866
- compilerState.fields.push(...fields);
2867
- for (const field of fields) {
2868
- if (field.validation?.options && field.validation.options.length > 0) {
2869
- for (const option of field.validation.options) {
2870
- if (!compilerState.states.has(option)) {
2871
- compilerState.states.set(option, {
2872
- name: option,
2873
- type: "REGULAR",
2874
- on_enter: [],
2875
- during: [],
2876
- on_exit: []
2877
- });
2878
- }
2879
- }
2880
- const firstState = compilerState.states.get(field.validation.options[0]);
2881
- if (firstState) firstState.type = "START";
2882
- break;
2883
- }
2884
- }
2885
- if (!compilerState.metadata.name) {
2886
- compilerState.metadata.name = interfaceName;
2887
- }
2888
- }
2889
- if (t11.isVariableDeclaration(declaration)) {
2890
- for (const decl of declaration.declarations) {
2891
- if (!t11.isIdentifier(decl.id) || !decl.init) continue;
2892
- const varName = decl.id.name;
2893
- if (varName === "transitions" && t11.isObjectExpression(decl.init)) {
2894
- const transitions = extractTransitionsFromObject(decl.init, actionCounter);
2895
- compilerState.transitions.push(...transitions);
2896
- for (const trans of transitions) {
2897
- for (const fromState of trans.from) {
2898
- if (!compilerState.states.has(fromState)) {
2899
- compilerState.states.set(fromState, {
2900
- name: fromState,
2901
- type: "REGULAR",
2902
- on_enter: [],
2903
- during: [],
2904
- on_exit: []
2905
- });
2906
- }
2907
- }
2908
- if (trans.to && !compilerState.states.has(trans.to)) {
2909
- compilerState.states.set(trans.to, {
2910
- name: trans.to,
2911
- type: "REGULAR",
2912
- on_enter: [],
2913
- during: [],
2914
- on_exit: []
2915
- });
2916
- }
2917
- }
2918
- }
2919
- if (varName === "states") {
2920
- const arrExpr = t11.isTSAsExpression(decl.init) ? decl.init.expression : decl.init;
2921
- if (t11.isArrayExpression(arrExpr)) {
2922
- for (const el of arrExpr.elements) {
2923
- if (!t11.isObjectExpression(el)) continue;
2924
- let stateName = "";
2925
- let stateType = "REGULAR";
2926
- let stateDesc = "";
2927
- for (const prop of el.properties) {
2928
- if (!t11.isObjectProperty(prop) || !t11.isIdentifier(prop.key)) continue;
2929
- if (prop.key.name === "name" && t11.isStringLiteral(prop.value)) {
2930
- stateName = prop.value.value;
2931
- } else if (prop.key.name === "type") {
2932
- const val = t11.isTSAsExpression(prop.value) ? prop.value.expression : prop.value;
2933
- if (t11.isStringLiteral(val)) stateType = val.value;
2934
- } else if (prop.key.name === "description" && t11.isStringLiteral(prop.value)) {
2935
- stateDesc = prop.value.value;
2936
- }
2937
- }
2938
- if (stateName && !compilerState.states.has(stateName)) {
2939
- compilerState.states.set(stateName, {
2940
- name: stateName,
2941
- type: stateType,
2942
- description: stateDesc || void 0,
2943
- on_enter: [],
2944
- during: [],
2945
- on_exit: []
2946
- });
2947
- } else if (stateName) {
2948
- compilerState.states.get(stateName).type = stateType;
2949
- }
2950
- }
2951
- }
2952
- }
2953
- if (varName === "endStates" && t11.isArrayExpression(decl.init)) {
2954
- for (const el of decl.init.elements) {
2955
- if (t11.isStringLiteral(el)) {
2956
- if (!compilerState.states.has(el.value)) {
2957
- compilerState.states.set(el.value, {
2958
- name: el.value,
2959
- type: "END",
2960
- on_enter: [],
2961
- during: [],
2962
- on_exit: []
2963
- });
2964
- } else {
2965
- compilerState.states.get(el.value).type = "END";
2966
- }
2967
- }
2968
- }
2969
- }
2970
- if (varName === "cancelledStates" && t11.isArrayExpression(decl.init)) {
2971
- for (const el of decl.init.elements) {
2972
- if (t11.isStringLiteral(el)) {
2973
- if (!compilerState.states.has(el.value)) {
2974
- compilerState.states.set(el.value, {
2975
- name: el.value,
2976
- type: "CANCELLED",
2977
- on_enter: [],
2978
- during: [],
2979
- on_exit: []
2980
- });
2981
- } else {
2982
- compilerState.states.get(el.value).type = "CANCELLED";
2983
- }
2984
- }
2985
- }
2986
- }
2987
- if (varName === "hooks" && t11.isObjectExpression(decl.init)) {
2988
- extractHooksFromObject(decl.init, compilerState.states, actionCounter);
2989
- }
2990
- if (varName === "runtime" && t11.isStringLiteral(decl.init)) {
2991
- compilerState.metadata.runtime = decl.init.value;
2992
- }
2993
- if (varName === "fieldOptions" && t11.isObjectExpression(decl.init)) {
2994
- applyFieldOptions(compilerState.fields, decl.init);
2995
- }
2996
- }
2997
- }
2998
- }
2999
- compilerState.actionCounter = actionCounter.value;
3000
- if (interfaceName && compilerState.metadata.__slugAutoFallback) {
3001
- compilerState.metadata.slug = interfaceName.replace(/([A-Z])/g, "-$1").toLowerCase().replace(/^-/, "");
3002
- delete compilerState.metadata.__slugAutoFallback;
3003
- }
3004
- }
3005
-
3006
- // src/babel/extractors/server-action-extractor.ts
3007
- import * as t12 from "@babel/types";
3008
- function isServerActionFile(filename) {
3009
- if (!filename) return false;
3010
- return /\.server\.(ts|tsx|js|jsx)$/.test(filename);
3011
- }
3012
- function extractServerActions(path, state) {
3013
- const compilerState = state;
3014
- const serverActions = [];
3015
- for (const node of path.node.body) {
3016
- if (t12.isExportNamedDeclaration(node)) {
3017
- const decl = node.declaration;
3018
- if (t12.isFunctionDeclaration(decl) && decl.id) {
3019
- const action = extractFunctionAction(decl);
3020
- if (action) {
3021
- const comments = node.leadingComments || decl.leadingComments || [];
3022
- action.description = extractDescription(comments);
3023
- serverActions.push(action);
3024
- }
3025
- }
3026
- if (t12.isVariableDeclaration(decl)) {
3027
- for (const varDecl of decl.declarations) {
3028
- if (!t12.isIdentifier(varDecl.id)) continue;
3029
- const init = varDecl.init;
3030
- if (t12.isArrowFunctionExpression(init) || t12.isFunctionExpression(init)) {
3031
- const action = {
3032
- name: varDecl.id.name,
3033
- async: init.async || false,
3034
- params: init.params.filter((p) => t12.isIdentifier(p)).map((p) => p.name)
3035
- };
3036
- if (init.params.length > 0) {
3037
- const firstParam = init.params[0];
3038
- if (t12.isIdentifier(firstParam) && firstParam.typeAnnotation) {
3039
- action.contextType = extractTypeName(firstParam.typeAnnotation);
3040
- }
3041
- }
3042
- serverActions.push(action);
3043
- }
3044
- }
3045
- }
3046
- }
3047
- }
3048
- if (serverActions.length > 0) {
3049
- if (!compilerState.metadata) compilerState.metadata = {};
3050
- compilerState.metadata.serverActions = serverActions;
3051
- }
3052
- }
3053
- function extractFunctionAction(decl) {
3054
- if (!decl.id) return null;
3055
- const action = {
3056
- name: decl.id.name,
3057
- async: decl.async || false,
3058
- params: decl.params.filter((p) => t12.isIdentifier(p)).map((p) => p.name)
3059
- };
3060
- if (decl.params.length > 0) {
3061
- const firstParam = decl.params[0];
3062
- if (t12.isIdentifier(firstParam) && firstParam.typeAnnotation) {
3063
- action.contextType = extractTypeName(firstParam.typeAnnotation);
3064
- }
3065
- }
3066
- return action;
3067
- }
3068
- function extractTypeName(annotation) {
3069
- if (t12.isTSTypeAnnotation(annotation)) {
3070
- const typeNode = annotation.typeAnnotation;
3071
- if (t12.isTSTypeReference(typeNode) && t12.isIdentifier(typeNode.typeName)) {
3072
- return typeNode.typeName.name;
3073
- }
3074
- }
3075
- return void 0;
3076
- }
3077
- function extractDescription(comments) {
3078
- for (const comment of comments) {
3079
- if (comment.type !== "CommentBlock") continue;
3080
- const lines = comment.value.split("\n");
3081
- for (const line of lines) {
3082
- const trimmed = line.replace(/^\s*\*\s?/, "").trim();
3083
- if (trimmed && !trimmed.startsWith("@")) {
3084
- return trimmed;
3085
- }
3086
- }
3087
- }
3088
- return void 0;
3089
- }
3090
-
3091
- // src/babel/extractors/server-action-hook-extractor.ts
3092
- import * as t13 from "@babel/types";
3093
- function extractServerActionHook(path, state) {
3094
- const args = path.node.arguments;
3095
- if (args.length < 1) return;
3096
- const nameArg = args[0];
3097
- if (!t13.isStringLiteral(nameArg)) return;
3098
- const compilerState = state;
3099
- const entry = {
3100
- name: nameArg.value
3101
- };
3102
- if (args.length > 1 && t13.isObjectExpression(args[1])) {
3103
- for (const prop of args[1].properties) {
3104
- if (!t13.isObjectProperty(prop) || !t13.isIdentifier(prop.key)) continue;
3105
- if (prop.key.name === "instanceId" && t13.isStringLiteral(prop.value)) {
3106
- entry.staticInstanceId = prop.value.value;
3107
- }
3108
- }
3109
- }
3110
- const parent = path.parentPath;
3111
- if (parent?.isVariableDeclarator() && t13.isIdentifier(parent.node.id)) {
3112
- entry.variableName = parent.node.id.name;
3113
- }
3114
- if (!compilerState.metadata) compilerState.metadata = {};
3115
- const meta = compilerState.metadata;
3116
- if (!meta.serverActionHooks) meta.serverActionHooks = [];
3117
- meta.serverActionHooks.push(entry);
3118
- }
3119
-
3120
- // src/babel/extractors/server-state-extractor.ts
3121
- import * as t14 from "@babel/types";
3122
- function extractServerState(path, state) {
3123
- const args = path.node.arguments;
3124
- if (args.length < 1) return;
3125
- const compilerState = state;
3126
- const entry = {};
3127
- const instanceArg = args[0];
3128
- if (t14.isStringLiteral(instanceArg)) {
3129
- entry.staticInstanceId = instanceArg.value;
3130
- }
3131
- if (args.length > 1 && t14.isObjectExpression(args[1])) {
3132
- for (const prop of args[1].properties) {
3133
- if (!t14.isObjectProperty(prop) || !t14.isIdentifier(prop.key)) continue;
3134
- if (prop.key.name === "enabled" && t14.isBooleanLiteral(prop.value)) {
3135
- if (!prop.value.value) entry.disabled = true;
3136
- }
3137
- }
3138
- }
3139
- const parent = path.parentPath;
3140
- if (parent?.isVariableDeclarator()) {
3141
- if (t14.isIdentifier(parent.node.id)) {
3142
- entry.variableName = parent.node.id.name;
3143
- } else if (t14.isObjectPattern(parent.node.id)) {
3144
- const props = parent.node.id.properties.filter((p) => t14.isObjectProperty(p) && t14.isIdentifier(p.key)).map((p) => p.key.name);
3145
- if (props.length > 0) {
3146
- entry.variableName = props.join(", ");
3147
- }
3148
- }
3149
- }
3150
- if (!compilerState.metadata) compilerState.metadata = {};
3151
- const meta = compilerState.metadata;
3152
- if (!meta.serverStateSubscriptions) meta.serverStateSubscriptions = [];
3153
- meta.serverStateSubscriptions.push(entry);
3154
- meta.requiresSSE = true;
3155
- }
3156
-
3157
- // src/babel/extractors/grammar-island-extractor.ts
3158
- import * as t15 from "@babel/types";
3159
- var GRAMMAR_TAGS = /* @__PURE__ */ new Set(["cedar", "sql", "cron", "dmn", "graphql", "jsonpath"]);
3160
- function parseCedar(source) {
3161
- const policies = [];
3162
- const policyRegex = /(permit|forbid)\s*\(([^)]*)\)(?:\s*when\s*\{([^}]*)\})?/g;
3163
- let match;
3164
- while ((match = policyRegex.exec(source)) !== null) {
3165
- const [, effect, scope, condition] = match;
3166
- const parts = scope.split(",").map((s) => s.trim());
3167
- const policy = {
3168
- effect,
3169
- conditions: []
3170
- };
3171
- for (const part of parts) {
3172
- if (part.startsWith("principal")) {
3173
- policy.principal = part;
3174
- } else if (part.startsWith("action")) {
3175
- policy.action = part;
3176
- } else if (part.startsWith("resource")) {
3177
- policy.resource = part;
3178
- }
3179
- }
3180
- if (condition) {
3181
- policy.conditions.push(condition.trim());
3182
- }
3183
- policies.push(policy);
3184
- }
3185
- return { policies };
3186
- }
3187
- function parseCron(source) {
3188
- const trimmed = source.trim();
3189
- const parts = trimmed.split(/\s+/);
3190
- const valid = parts.length === 5;
3191
- return {
3192
- expression: trimmed,
3193
- fields: {
3194
- minute: parts[0] || "*",
3195
- hour: parts[1] || "*",
3196
- dayOfMonth: parts[2] || "*",
3197
- month: parts[3] || "*",
3198
- dayOfWeek: parts[4] || "*"
3199
- },
3200
- valid
3201
- };
3202
- }
3203
- function parseDmn(source) {
3204
- const lines = source.split("\n").map((l) => l.trim()).filter((l) => l.length > 0);
3205
- const rules = [];
3206
- const headers = [];
3207
- let hitPolicy = "first";
3208
- if (lines.length === 0) return { hitPolicy, rules, headers };
3209
- const headerLine = lines[0];
3210
- const headerCells = headerLine.split("|").map((c) => c.trim()).filter((c) => c.length > 0);
3211
- headers.push(...headerCells);
3212
- const outputStartIndex = headers.length - 1;
3213
- let dataStart = 1;
3214
- if (lines.length > 1 && /^[|\s-]+$/.test(lines[1])) {
3215
- dataStart = 2;
3216
- }
3217
- const hitPolicyMatch = source.match(/@hitPolicy\s*=\s*"?(\w+)"?/);
3218
- if (hitPolicyMatch) {
3219
- hitPolicy = hitPolicyMatch[1];
3220
- }
3221
- for (let i = dataStart; i < lines.length; i++) {
3222
- const cells = lines[i].split("|").map((c) => c.trim()).filter((c) => c.length > 0);
3223
- if (cells.length < headers.length) continue;
3224
- const inputs = {};
3225
- const output = {};
3226
- for (let j = 0; j < headers.length; j++) {
3227
- if (j >= outputStartIndex) {
3228
- output[headers[j]] = cells[j];
3229
- } else {
3230
- inputs[headers[j]] = cells[j];
3231
- }
3232
- }
3233
- rules.push({ inputs, output });
3234
- }
3235
- return { hitPolicy, rules, headers };
3236
- }
3237
- function extractGrammarIsland(path, state, slug) {
3238
- const tag = path.node.tag;
3239
- if (!t15.isIdentifier(tag)) return;
3240
- const tagName = tag.name;
3241
- if (!GRAMMAR_TAGS.has(tagName)) return;
3242
- const compilerState = state;
3243
- const quasi = path.node.quasi;
3244
- let rawSource = "";
3245
- for (let i = 0; i < quasi.quasis.length; i++) {
3246
- rawSource += quasi.quasis[i].value.raw;
3247
- if (i < quasi.expressions.length) {
3248
- const expr = quasi.expressions[i];
3249
- if (t15.isIdentifier(expr)) {
3250
- rawSource += `\${${expr.name}}`;
3251
- } else {
3252
- rawSource += `\${expr_${i}}`;
3253
- }
3254
- }
3255
- }
3256
- rawSource = rawSource.trim();
3257
- let parsed = void 0;
3258
- switch (tagName) {
3259
- case "cedar":
3260
- parsed = parseCedar(rawSource);
3261
- break;
3262
- case "cron":
3263
- parsed = parseCron(rawSource);
3264
- break;
3265
- case "dmn":
3266
- parsed = parseDmn(rawSource);
3267
- break;
3268
- case "sql":
3269
- parsed = { query: rawSource };
3270
- break;
3271
- case "graphql":
3272
- parsed = { query: rawSource };
3273
- break;
3274
- case "jsonpath":
3275
- parsed = { expression: rawSource };
3276
- break;
3277
- }
3278
- const island = {
3279
- slug,
3280
- contextTag: tagName,
3281
- rawSource,
3282
- parsed
3283
- };
3284
- if (!compilerState.metadata) compilerState.metadata = {};
3285
- const meta = compilerState.metadata;
3286
- if (!meta.grammarIslands) meta.grammarIslands = [];
3287
- meta.grammarIslands.push(island);
3288
- }
3289
- function extractGrammarIslands(path, state) {
3290
- path.traverse({
3291
- TaggedTemplateExpression(templatePath) {
3292
- const tag = templatePath.node.tag;
3293
- if (!t15.isIdentifier(tag) || !GRAMMAR_TAGS.has(tag.name)) return;
3294
- let slug = "unnamed";
3295
- const parent = templatePath.parentPath;
3296
- if (parent && parent.isVariableDeclarator() && t15.isIdentifier(parent.node.id)) {
3297
- slug = parent.node.id.name;
3298
- }
3299
- if (parent && parent.isObjectProperty() && t15.isIdentifier(parent.node.key)) {
3300
- slug = parent.node.key.name;
3301
- }
3302
- if (parent && parent.isObjectProperty() && t15.isStringLiteral(parent.node.key)) {
3303
- slug = parent.node.key.value;
3304
- }
3305
- extractGrammarIsland(templatePath, state, slug);
3306
- }
3307
- });
3308
- }
3309
-
3310
- // src/babel/extractors/context-extractor.ts
3311
- import * as t16 from "@babel/types";
3312
- function hasContextCreation(path) {
3313
- let found = false;
3314
- path.traverse({
3315
- CallExpression(callPath) {
3316
- if (t16.isIdentifier(callPath.node.callee, { name: "createContext" })) {
3317
- found = true;
3318
- callPath.stop();
3319
- }
3320
- }
3321
- });
3322
- return found;
3323
- }
3324
- function extractContextWorkflows(path, state) {
3325
- const compilerState = state;
3326
- const contextWorkflows = [];
3327
- const contextNames = /* @__PURE__ */ new Map();
3328
- path.traverse({
3329
- // Detect: const XContext = createContext(...)
3330
- VariableDeclarator(declPath) {
3331
- const init = declPath.node.init;
3332
- if (!init || !t16.isCallExpression(init)) return;
3333
- if (!t16.isIdentifier(init.callee, { name: "createContext" })) return;
3334
- if (!t16.isIdentifier(declPath.node.id)) return;
3335
- const contextName = declPath.node.id.name;
3336
- contextNames.set(contextName, contextName);
3337
- const workflow = {
3338
- name: contextName,
3339
- fields: [],
3340
- reducerActions: []
3341
- };
3342
- const typeParams = init.typeParameters;
3343
- if (typeParams && t16.isTSTypeParameterInstantiation(typeParams)) {
3344
- const typeArg = typeParams.params[0];
3345
- if (t16.isTSTypeReference(typeArg) && t16.isIdentifier(typeArg.typeName)) {
3346
- const interfaceName = typeArg.typeName.name;
3347
- extractFieldsFromInterface2(path, interfaceName, workflow);
3348
- }
3349
- }
3350
- if (init.arguments.length > 0 && t16.isObjectExpression(init.arguments[0])) {
3351
- workflow.initialState = extractObjectLiteral2(init.arguments[0]);
3352
- }
3353
- contextWorkflows.push(workflow);
3354
- },
3355
- // Detect useReducer(reducer, initialState) and extract reducer cases
3356
- CallExpression(callPath) {
3357
- if (!t16.isIdentifier(callPath.node.callee, { name: "useReducer" })) return;
3358
- const args = callPath.node.arguments;
3359
- if (args.length < 1) return;
3360
- const reducerArg = args[0];
3361
- if (!t16.isIdentifier(reducerArg)) return;
3362
- const reducerName = reducerArg.name;
3363
- const actions = extractReducerActions(path, reducerName);
3364
- if (contextWorkflows.length > 0) {
3365
- const lastWorkflow = contextWorkflows[contextWorkflows.length - 1];
3366
- lastWorkflow.reducerActions = actions;
3367
- lastWorkflow.reducerName = reducerName;
3368
- }
3369
- }
3370
- });
3371
- if (contextWorkflows.length > 0) {
3372
- if (!compilerState.metadata) compilerState.metadata = {};
3373
- const meta = compilerState.metadata;
3374
- meta.contextWorkflows = contextWorkflows;
3375
- }
3376
- }
3377
- function extractFieldsFromInterface2(path, interfaceName, workflow) {
3378
- path.traverse({
3379
- TSInterfaceDeclaration(ifacePath) {
3380
- if (!t16.isIdentifier(ifacePath.node.id, { name: interfaceName })) return;
3381
- for (const prop of ifacePath.node.body.body) {
3382
- if (!t16.isTSPropertySignature(prop)) continue;
3383
- if (!t16.isIdentifier(prop.key)) continue;
3384
- const field = {
3385
- name: prop.key.name,
3386
- type: extractTSType(prop.typeAnnotation),
3387
- optional: prop.optional || false
3388
- };
3389
- workflow.fields.push(field);
3390
- }
3391
- }
3392
- });
3393
- }
3394
- function extractTSType(annotation) {
3395
- if (!annotation || !t16.isTSTypeAnnotation(annotation)) return "unknown";
3396
- const typeNode = annotation.typeAnnotation;
3397
- if (t16.isTSStringKeyword(typeNode)) return "string";
3398
- if (t16.isTSNumberKeyword(typeNode)) return "number";
3399
- if (t16.isTSBooleanKeyword(typeNode)) return "boolean";
3400
- if (t16.isTSArrayType(typeNode)) return `${extractTSTypeNode(typeNode.elementType)}[]`;
3401
- if (t16.isTSTypeReference(typeNode) && t16.isIdentifier(typeNode.typeName)) return typeNode.typeName.name;
3402
- return "unknown";
3403
- }
3404
- function extractTSTypeNode(node) {
3405
- if (t16.isTSStringKeyword(node)) return "string";
3406
- if (t16.isTSNumberKeyword(node)) return "number";
3407
- if (t16.isTSBooleanKeyword(node)) return "boolean";
3408
- if (t16.isTSTypeReference(node) && t16.isIdentifier(node.typeName)) return node.typeName.name;
3409
- return "unknown";
3410
- }
3411
- function extractReducerActions(path, reducerName) {
3412
- const actions = [];
3413
- path.traverse({
3414
- FunctionDeclaration(funcPath) {
3415
- if (!funcPath.node.id || funcPath.node.id.name !== reducerName) return;
3416
- funcPath.traverse({
3417
- SwitchStatement(switchPath) {
3418
- for (const switchCase of switchPath.node.cases) {
3419
- if (!switchCase.test) continue;
3420
- if (t16.isStringLiteral(switchCase.test)) {
3421
- actions.push({
3422
- type: switchCase.test.value
3423
- });
3424
- }
3425
- }
3426
- }
3427
- });
3428
- }
3429
- });
3430
- return actions;
3431
- }
3432
- function extractObjectLiteral2(obj) {
3433
- const result = {};
3434
- for (const prop of obj.properties) {
3435
- if (!t16.isObjectProperty(prop) || !t16.isIdentifier(prop.key)) continue;
3436
- if (t16.isStringLiteral(prop.value)) result[prop.key.name] = prop.value.value;
3437
- else if (t16.isNumericLiteral(prop.value)) result[prop.key.name] = prop.value.value;
3438
- else if (t16.isBooleanLiteral(prop.value)) result[prop.key.name] = prop.value.value;
3439
- else if (t16.isNullLiteral(prop.value)) result[prop.key.name] = null;
3440
- else if (t16.isArrayExpression(prop.value)) result[prop.key.name] = [];
3441
- else if (t16.isObjectExpression(prop.value)) result[prop.key.name] = extractObjectLiteral2(prop.value);
3442
- }
3443
- return result;
3444
- }
3445
-
3446
- // ../player-core/dist/index.mjs
3447
- function normalizeCategory(primary, ...tags) {
3448
- const uniqueTags = [...new Set(tags.filter((t18) => t18 !== primary))];
3449
- uniqueTags.sort();
3450
- return [primary, ...uniqueTags];
3451
- }
3452
-
3453
- // src/babel/emitters/experience-transform.ts
3454
- function transformToFrontend(node) {
3455
- const result = {
3456
- id: node.id
3457
- };
3458
- if (node.displayName) {
3459
- result.displayName = node.displayName;
3460
- } else if (node.config?.displayName && typeof node.config.displayName === "string") {
3461
- result.displayName = node.config.displayName;
3462
- }
3463
- if (node.experienceId) result.experienceId = node.experienceId;
3464
- if (node.component) result.component = node.component;
3465
- if (node.slot) {
3466
- result.slot = node.slot;
3467
- } else if (node.config?.slot && typeof node.config.slot === "string") {
3468
- result.slot = node.config.slot;
3469
- }
3470
- if (node.className) {
3471
- result.className = node.className;
3472
- } else if (node.config?.className && typeof node.config.className === "string") {
3473
- result.className = node.config.className;
3474
- }
3475
- if (node.style) result.style = node.style;
3476
- if (node.overrides) result.overrides = node.overrides;
3477
- if (node.layout) result.layout = node.layout;
3478
- if (node.dataScope) result.dataScope = node.dataScope;
3479
- if (node.bindings) result.bindings = node.bindings;
3480
- if (node.visible_when) result.visible_when = node.visible_when;
3481
- if (node.config) {
3482
- const cleaned = { ...node.config };
3483
- delete cleaned.slot;
3484
- delete cleaned.className;
3485
- delete cleaned.displayName;
3486
- if (Object.keys(cleaned).length > 0) {
3487
- result.config = cleaned;
3488
- }
3489
- }
3490
- if (node.dataSources && node.dataSources.length > 0) {
3491
- result.dataSources = node.dataSources.map(transformDataSource);
3492
- }
3493
- if (node.children && node.children.length > 0) {
3494
- result.children = node.children.map(transformToFrontend);
3495
- }
3496
- return result;
3497
- }
3498
- function transformDataSource(ds) {
3499
- const d = ds;
3500
- switch (ds.type) {
3501
- case "workflow":
3502
- return {
3503
- type: "workflow",
3504
- name: ds.name,
3505
- slug: ds.slug,
3506
- query: ds.query,
3507
- ...d.instanceId && { instanceId: d.instanceId },
3508
- ...d.entity !== void 0 && { entity: d.entity },
3509
- ...ds.paginated !== void 0 && { paginated: ds.paginated },
3510
- ...ds.pageSize !== void 0 && { pageSize: ds.pageSize },
3511
- ...d.filter && { filter: d.filter },
3512
- ...d.filters && { filters: d.filters },
3513
- ...ds.sort && { sort: ds.sort },
3514
- ...d.search && { search: d.search },
3515
- ...ds.searchFields && { searchFields: ds.searchFields },
3516
- ...ds.facets && { facets: ds.facets },
3517
- ...d.range && { range: d.range },
3518
- ...d.aggregate && { aggregate: d.aggregate },
3519
- ...ds.groupBy && { groupBy: ds.groupBy },
3520
- ...ds.parentInstanceId && { parentInstanceId: ds.parentInstanceId },
3521
- ...d.autoStart !== void 0 && { autoStart: d.autoStart },
3522
- ...d.initialData && { initialData: d.initialData },
3523
- ...d.includeDefinition !== void 0 && { includeDefinition: d.includeDefinition }
3524
- };
3525
- case "api":
3526
- return {
3527
- type: "api",
3528
- name: ds.name,
3529
- endpoint: ds.endpoint,
3530
- ...d.method && { method: d.method },
3531
- ...d.mapping && { mapping: d.mapping },
3532
- ...d.staleTime !== void 0 && { staleTime: d.staleTime }
3533
- };
3534
- case "ref":
3535
- return {
3536
- type: "ref",
3537
- name: ds.name,
3538
- expression: ds.expression
3539
- };
3540
- case "static":
3541
- return {
3542
- type: "static",
3543
- name: ds.name,
3544
- data: ds.data
3545
- };
3546
- }
3547
- }
3548
-
3549
- // src/babel/emitters/pure-form-emitter.ts
3550
- var PROP_RULES = {
3551
- Text: {
3552
- config: { text: "value" },
3553
- bindings: { text: "value" }
3554
- },
3555
- Heading: {
3556
- config: { text: "value" },
3557
- bindings: { text: "value" }
3558
- },
3559
- Button: {
3560
- config: { text: "label" },
3561
- bindings: { text: "label", onPress: "onClick" }
3562
- }
3563
- };
3564
- var COMPONENT_RENAMES = {
3565
- Heading: "Text"
3566
- };
3567
- var RENAME_EXTRA_CONFIG = {
3568
- Heading: { variant: "h2" }
3569
- };
3570
- function normalizeViewNode(node, fieldNames) {
3571
- if (!node || typeof node !== "object") return node;
3572
- const originalComponent = node.component;
3573
- if (originalComponent && COMPONENT_RENAMES[originalComponent]) {
3574
- node.component = COMPONENT_RENAMES[originalComponent];
3575
- const extra = RENAME_EXTRA_CONFIG[originalComponent];
3576
- if (extra) {
3577
- node.config = { ...extra, ...node.config || {} };
3578
- }
3579
- }
3580
- const rules = PROP_RULES[originalComponent || ""] || PROP_RULES[node.component || ""];
3581
- if (rules) {
3582
- if (node.config && rules.config) {
3583
- for (const [from, to] of Object.entries(rules.config)) {
3584
- if (from in node.config && !(to in node.config)) {
3585
- node.config[to] = node.config[from];
3586
- delete node.config[from];
3587
- }
3588
- }
3589
- }
3590
- if (node.bindings && rules.bindings) {
3591
- for (const [from, to] of Object.entries(rules.bindings)) {
3592
- if (from in node.bindings && !(to in node.bindings)) {
3593
- node.bindings[to] = node.bindings[from];
3594
- delete node.bindings[from];
3595
- }
3596
- }
3597
- }
3598
- }
3599
- if (node.config && fieldNames.size > 0) {
3600
- for (const [prop, val] of Object.entries(node.config)) {
3601
- if (typeof val !== "string") continue;
3602
- const templateRe = /\{\{(\w+)\}\}|\{(\w+)\}/g;
3603
- let match;
3604
- const refs = [];
3605
- while ((match = templateRe.exec(val)) !== null) {
3606
- const field = match[1] || match[2];
3607
- if (fieldNames.has(field)) {
3608
- refs.push({ full: match[0], field, index: match.index });
3609
- }
3610
- }
3611
- if (refs.length > 0) {
3612
- const parts = [];
3613
- let lastEnd = 0;
3614
- for (const ref of refs) {
3615
- const before = val.slice(lastEnd, ref.index);
3616
- if (before) parts.push(`"${before}"`);
3617
- parts.push(`$instance.state_data.${ref.field}`);
3618
- lastEnd = ref.index + ref.full.length;
3619
- }
3620
- const trailing = val.slice(lastEnd);
3621
- if (trailing) parts.push(`"${trailing}"`);
3622
- const expr = `$fn.concat(${parts.join(", ")})`;
3623
- if (!node.bindings) node.bindings = {};
3624
- node.bindings[prop] = expr;
3625
- delete node.config[prop];
3626
- }
3627
- }
3628
- }
3629
- if (node.bindings) {
3630
- for (const [prop, expr] of Object.entries(node.bindings)) {
3631
- if (typeof expr !== "string") continue;
3632
- if (expr.endsWith(".fire")) {
3633
- const transitionName = expr.slice(0, -5);
3634
- node.bindings[prop] = `$action.transition("${transitionName}")`;
3635
- continue;
3636
- }
3637
- if (fieldNames.size > 0 && expr.startsWith("$instance.")) {
3638
- const field = expr.slice("$instance.".length);
3639
- if (fieldNames.has(field)) {
3640
- node.bindings[prop] = `$instance.state_data.${field}`;
3641
- }
3642
- }
3643
- }
3644
- }
3645
- if (node.children && Array.isArray(node.children)) {
3646
- node.children = node.children.map((child) => normalizeViewNode(child, fieldNames));
3647
- if (node.children.length === 1 && node.children[0].component === "Text") {
3648
- const textChild = node.children[0];
3649
- const configKeys = textChild.config ? Object.keys(textChild.config).filter((k) => k !== "value") : [];
3650
- const bindingKeys = textChild.bindings ? Object.keys(textChild.bindings).filter((k) => k !== "value") : [];
3651
- const isSimple = !textChild.style && !textChild.className && !textChild.children && !textChild.visible_when && configKeys.length === 0 && bindingKeys.length === 0;
3652
- if (isSimple) {
3653
- const parentRules = PROP_RULES[node.component || ""];
3654
- const configKey = parentRules?.config?.text || "text";
3655
- const bindingKey = parentRules?.bindings?.text || "text";
3656
- if (textChild.config?.value && !textChild.bindings) {
3657
- if (!node.config) node.config = {};
3658
- node.config[configKey] = textChild.config.value;
3659
- delete node.children;
3660
- } else if (textChild.bindings?.value && !textChild.config?.value) {
3661
- if (!node.bindings) node.bindings = {};
3662
- node.bindings[bindingKey] = textChild.bindings.value;
3663
- delete node.children;
3664
- }
3665
- }
3666
- }
3667
- }
3668
- return node;
3669
- }
3670
- function toSnakeCase2(str) {
3671
- return str.replace(/([A-Z])/g, "_$1").toLowerCase().replace(/^_/, "");
3672
- }
3673
- function convertAction(action) {
3674
- return {
3675
- id: action.id,
3676
- action_type: action.type,
3677
- config: action.config || {},
3678
- ...action.condition && { condition: action.condition }
3679
- };
3680
- }
3681
- function convertDuringAction(during) {
3682
- return {
3683
- id: during.id,
3684
- type: during.type,
3685
- ...during.interval_ms !== void 0 && { interval_ms: during.interval_ms },
3686
- ...during.cron && { cron: during.cron },
3687
- ...during.delay_ms !== void 0 && { delay_ms: during.delay_ms },
3688
- actions: during.actions.map(convertAction),
3689
- ...during.condition && { condition: during.condition }
3690
- };
3691
- }
3692
- function convertOnEvent(sub) {
3693
- return {
3694
- match: sub.match,
3695
- ...sub.description && { description: sub.description },
3696
- conditions: sub.conditions || [],
3697
- actions: sub.actions.map((a) => ({
3698
- type: a.type,
3699
- ...a.field && { field: a.field },
3700
- ...a.expression && { expression: a.expression },
3701
- ...a.key && { key: a.key },
3702
- ...a.message && { message: a.message },
3703
- ...a.config && { config: a.config },
3704
- ...a.conditions && a.conditions.length > 0 && { conditions: a.conditions }
3705
- }))
3706
- };
3707
- }
3708
- function emitIR(extracted) {
3709
- const { slug, name, version, description, category, fields, states, transitions } = extracted;
3710
- const stateArray = Array.from(states.values());
3711
- if (stateArray.length === 0) {
3712
- stateArray.push({
3713
- name: "draft",
3714
- type: "START",
3715
- on_enter: [],
3716
- during: [],
3717
- on_exit: []
3718
- });
3719
- } else {
3720
- const hasStart = stateArray.some((s) => s.type === "START");
3721
- if (!hasStart && stateArray.length > 0) {
3722
- stateArray[0].type = "START";
3723
- }
3724
- }
3725
- inferTransitionStates(transitions, states);
3726
- const stateNames = new Set(stateArray.map((s) => s.name));
3727
- for (const transition of transitions) {
3728
- if (transition.to && !stateNames.has(transition.to)) {
3729
- stateArray.push({
3730
- name: transition.to,
3731
- type: "REGULAR",
3732
- on_enter: [],
3733
- during: [],
3734
- on_exit: []
3735
- });
3736
- stateNames.add(transition.to);
3737
- }
3738
- }
3739
- const fieldNames = new Set(fields.map((f) => f.name));
3740
- let normalizedView;
3741
- if (extracted.experience) {
3742
- normalizedView = normalizeViewNode(
3743
- JSON.parse(JSON.stringify(extracted.experience)),
3744
- fieldNames
3745
- );
3746
- const dataSources = extracted.extraMetadata?.dataSources;
3747
- if (dataSources && dataSources.length > 0) {
3748
- normalizedView.dataSources = dataSources;
3749
- }
3750
- if (fields.length > 0) {
3751
- const localDefaults = {};
3752
- for (const f of fields) {
3753
- localDefaults[toSnakeCase2(f.name)] = f.default_value ?? null;
3754
- }
3755
- if (!normalizedView.config) normalizedView.config = {};
3756
- normalizedView.config.localDefaults = localDefaults;
3757
- }
3758
- }
3759
- const metadata = {
3760
- stable_id: `def-${slug}`,
3761
- provenance: {
3762
- frontend: "react-compiler",
3763
- source: `${slug}.workflow.tsx`,
3764
- compiler_version: "1.0.0"
3765
- }
3766
- };
3767
- if (extracted.fieldWatchers && extracted.fieldWatchers.length > 0) {
3768
- metadata.fieldWatchers = extracted.fieldWatchers;
3769
- }
3770
- if (extracted.transitionEffects && extracted.transitionEffects.length > 0) {
3771
- metadata.transitionEffects = extracted.transitionEffects;
3772
- }
3773
- if (extracted.extraMetadata) {
3774
- for (const [key, value] of Object.entries(extracted.extraMetadata)) {
3775
- metadata[key] = value;
3776
- }
3777
- }
3778
- if (extracted.experience) {
3779
- metadata.experience = extracted.experience;
3780
- }
3781
- const ir = {
3782
- slug,
3783
- name,
3784
- version,
3785
- description,
3786
- category,
3787
- fields,
3788
- states: stateArray,
3789
- transitions,
3790
- roles: [],
3791
- tags: [],
3792
- metadata
3793
- };
3794
- if (normalizedView) {
3795
- ir.views = { default: normalizedView };
3796
- ir.frontendViews = { default: transformToFrontend(normalizedView) };
3797
- }
3798
- if (extracted.events && extracted.events.length > 0) {
3799
- ir.on_event = extracted.events;
3800
- }
3801
- if (extracted.grammarIslands && extracted.grammarIslands.length > 0) {
3802
- const extensions = {};
3803
- for (const island of extracted.grammarIslands) {
3804
- const key = island.contextTag;
3805
- if (!extensions[key]) extensions[key] = [];
3806
- extensions[key].push(island);
3807
- }
3808
- ir.extensions = extensions;
3809
- }
3810
- return ir;
3811
- }
3812
- var emitPureForm = emitIR;
3813
- function liftAction(action) {
3814
- const parts = [];
3815
- if (action.config) {
3816
- for (const [key, value] of Object.entries(action.config)) {
3817
- parts.push({
3818
- slug: key,
3819
- category: ["atom"],
3820
- parts: [{ slug: String(value), category: ["atom"] }]
3821
- });
3822
- }
3823
- }
3824
- if (action.condition) {
3825
- parts.push({
3826
- slug: "condition",
3827
- category: ["expression", "guard"],
3828
- parts: [{ slug: action.condition, category: ["binding"] }]
3829
- });
3830
- }
3831
- return {
3832
- slug: action.id,
3833
- category: normalizeCategory("expression", "mutation", action.type),
3834
- parts: parts.length > 0 ? parts : void 0
3835
- };
3836
- }
3837
- function liftSchedule(during) {
3838
- const parts = [];
3839
- if (during.interval_ms !== void 0) {
3840
- parts.push({
3841
- slug: "every",
3842
- category: ["atom"],
3843
- parts: [{ slug: String(during.interval_ms), category: ["literal"] }]
3844
- });
3845
- }
3846
- if (during.cron) {
3847
- parts.push({
3848
- slug: "cron",
3849
- category: ["atom"],
3850
- parts: [{ slug: during.cron, category: ["literal"] }]
3851
- });
3852
- }
3853
- if (during.delay_ms !== void 0) {
3854
- parts.push({
3855
- slug: "delay",
3856
- category: ["atom"],
3857
- parts: [{ slug: String(during.delay_ms), category: ["literal"] }]
3858
- });
3859
- }
3860
- for (const action of during.actions) {
3861
- parts.push({
3862
- slug: "do",
3863
- category: normalizeCategory("expression", "mutation", action.type),
3864
- parts: Object.entries(action.config || {}).map(([key, value]) => ({
3865
- slug: key,
3866
- category: ["atom"],
3867
- parts: [{ slug: String(value), category: ["atom"] }]
3868
- }))
3869
- });
3870
- }
3871
- return {
3872
- slug: during.id,
3873
- category: normalizeCategory("schedule", during.type),
3874
- parts
3875
- };
3876
- }
3877
- function liftState(state) {
3878
- const parts = [];
3879
- const tags = [];
3880
- if (state.type === "START") tags.push("start");
3881
- if (state.type === "END") tags.push("end");
3882
- if (state.type === "CANCELLED") tags.push("cancelled");
3883
- if (state.on_enter && state.on_enter.length > 0) {
3884
- parts.push({
3885
- slug: "on_enter",
3886
- category: normalizeCategory("expression", "sequence"),
3887
- parts: state.on_enter.map(liftAction)
3888
- });
3889
- }
3890
- if (state.on_exit && state.on_exit.length > 0) {
3891
- parts.push({
3892
- slug: "on_exit",
3893
- category: normalizeCategory("expression", "sequence"),
3894
- parts: state.on_exit.map(liftAction)
3895
- });
3896
- }
3897
- if (state.during && state.during.length > 0) {
3898
- for (const d of state.during) {
3899
- parts.push(liftSchedule(d));
3900
- }
3901
- }
3902
- return {
3903
- slug: state.name,
3904
- category: normalizeCategory("state", ...tags),
3905
- parts: parts.length > 0 ? parts : void 0
3906
- };
3907
- }
3908
- function liftTransition(transition) {
3909
- const parts = [];
3910
- if (transition.from && transition.from.length > 0) {
3911
- parts.push({
3912
- slug: "from",
3913
- category: ["part"],
3914
- parts: transition.from.map((s) => ({ slug: s, category: ["ref"] }))
3915
- });
3916
- }
3917
- if (transition.to) {
3918
- parts.push({
3919
- slug: "to",
3920
- category: ["part"],
3921
- parts: [{ slug: transition.to, category: ["ref"] }]
3922
- });
3923
- }
3924
- if (transition.actions && transition.actions.length > 0) {
3925
- parts.push({
3926
- slug: "actions",
3927
- category: normalizeCategory("expression", "sequence"),
3928
- parts: transition.actions.map(liftAction)
3929
- });
3930
- }
3931
- if (transition.conditions && transition.conditions.length > 0) {
3932
- parts.push({
3933
- slug: "conditions",
3934
- category: normalizeCategory("expression", "guard"),
3935
- parts: transition.conditions.map((c, i) => ({
3936
- slug: `condition_${i}`,
3937
- category: normalizeCategory("expression", c.type || "condition"),
3938
- parts: c.expression ? [{ slug: c.expression, category: ["binding"] }] : void 0
3939
- }))
3940
- });
3941
- }
3942
- return {
3943
- slug: transition.name,
3944
- category: ["transition"],
3945
- parts
3946
- };
3947
- }
3948
- function liftField(field) {
3949
- const parts = [];
3950
- if (field.label) {
3951
- parts.push({
3952
- slug: "label",
3953
- category: ["atom"],
3954
- parts: [{ slug: field.label, category: ["atom"] }]
3955
- });
3956
- }
3957
- if (field.default_value !== void 0) {
3958
- parts.push({
3959
- slug: "default",
3960
- category: ["atom"],
3961
- parts: [{ slug: String(field.default_value), category: ["literal"] }]
3962
- });
3963
- }
3964
- if (field.required) {
3965
- parts.push({ slug: "required", category: ["atom"], parts: [{ slug: "true", category: ["literal"] }] });
3966
- }
3967
- if (field.computed) {
3968
- parts.push({
3969
- slug: "computed",
3970
- category: ["expression"],
3971
- parts: [{ slug: field.computed, category: ["binding"] }]
3972
- });
3973
- }
3974
- return {
3975
- slug: field.name,
3976
- category: normalizeCategory("field", field.type),
3977
- parts: parts.length > 0 ? parts : void 0
3978
- };
3979
- }
3980
- function liftView(node) {
3981
- const componentTag = (node.component || "stack").toLowerCase().replace(/\s+/g, "-");
3982
- const parts = [];
3983
- if (node.config) {
3984
- for (const [key, value] of Object.entries(node.config)) {
3985
- parts.push({
3986
- slug: key,
3987
- category: ["atom"],
3988
- parts: [{ slug: String(value), category: ["atom"] }]
3989
- });
3990
- }
3991
- }
3992
- if (node.bindings) {
3993
- for (const [key, expr] of Object.entries(node.bindings)) {
3994
- if (key === "onClick" || key === "onPress") {
3995
- const match = typeof expr === "string" ? expr.match(/\$action\.transition\("(.+?)"\)/) : null;
3996
- if (match) {
3997
- parts.push({
3998
- slug: key,
3999
- category: normalizeCategory("expression", "effect", "transition"),
4000
- parts: [{ slug: match[1], category: ["ref"] }]
4001
- });
4002
- } else {
4003
- parts.push({
4004
- slug: key,
4005
- category: normalizeCategory("expression", "binding"),
4006
- parts: [{ slug: String(expr), category: ["binding"] }]
4007
- });
4008
- }
4009
- } else {
4010
- parts.push({
4011
- slug: key,
4012
- category: normalizeCategory("expression", "binding"),
4013
- parts: [{ slug: String(expr), category: ["binding"] }]
4014
- });
4015
- }
4016
- }
4017
- }
4018
- if (node.visible_when) {
4019
- const eqMatch = node.visible_when.match(/\$fn\.eq\((.+?),\s*"(.+?)"\)/);
4020
- if (eqMatch) {
4021
- parts.push({
4022
- slug: "visible_when",
4023
- category: normalizeCategory("expression", "guard"),
4024
- parts: [{
4025
- slug: "body",
4026
- category: normalizeCategory("expression", "eq"),
4027
- parts: [
4028
- { slug: "lhs", category: normalizeCategory("expression", "path"), parts: [{ slug: eqMatch[1], category: ["binding"] }] },
4029
- { slug: "rhs", category: normalizeCategory("expression", "literal"), parts: [{ slug: eqMatch[2], category: ["literal"] }] }
4030
- ]
4031
- }]
4032
- });
4033
- } else {
4034
- parts.push({
4035
- slug: "visible_when",
4036
- category: normalizeCategory("expression", "guard"),
4037
- parts: [{ slug: node.visible_when, category: ["binding"] }]
4038
- });
4039
- }
4040
- }
4041
- if (node.children && node.children.length > 0) {
4042
- for (const child of node.children) {
4043
- parts.push(liftView(child));
4044
- }
4045
- }
4046
- return {
4047
- slug: node.id,
4048
- category: normalizeCategory("view", componentTag),
4049
- parts: parts.length > 0 ? parts : void 0
4050
- };
4051
- }
4052
- function emitCanonical(extracted, sourceFilename) {
4053
- const ir = emitIR(extracted);
4054
- const parts = [];
4055
- for (const state of ir.states) {
4056
- parts.push(liftState(state));
4057
- }
4058
- for (const transition of ir.transitions) {
4059
- parts.push(liftTransition(transition));
4060
- }
4061
- for (const field of ir.fields) {
4062
- parts.push(liftField(field));
4063
- }
4064
- if (extracted.experience) {
4065
- parts.push(liftView(extracted.experience));
4066
- }
4067
- parts.push({
4068
- slug: "manifest",
4069
- category: normalizeCategory("meta", "manifest"),
4070
- parts: [
4071
- {
4072
- slug: "workflows",
4073
- category: ["ref-list"],
4074
- parts: [{ slug: ir.slug, category: ["ref"] }]
4075
- },
4076
- {
4077
- slug: "route",
4078
- category: ["route"],
4079
- parts: [
4080
- { slug: "path", category: ["atom"], parts: [{ slug: `/${ir.slug}`, category: ["atom"] }] },
4081
- { slug: "label", category: ["atom"], parts: [{ slug: ir.name, category: ["atom"] }] }
4082
- ]
4083
- }
4084
- ]
4085
- });
4086
- const category = extracted.category;
4087
- let categoryArray;
4088
- if (category.includes("/")) {
4089
- const [primary, ...tags] = category.split("/");
4090
- categoryArray = normalizeCategory(primary, ...tags);
4091
- } else {
4092
- categoryArray = [category];
4093
- }
4094
- return {
4095
- slug: ir.slug,
4096
- category: categoryArray,
4097
- parts,
4098
- metadata: {
4099
- stable_id: `def-${ir.slug}`,
4100
- provenance: {
4101
- frontend: "react-compiler",
4102
- source: sourceFilename || `${ir.slug}.workflow.tsx`,
4103
- compiler_version: "1.0.0",
4104
- compiled_at: (/* @__PURE__ */ new Date()).toISOString()
4105
- }
4106
- }
4107
- };
4108
- }
4109
- function emitCompiledOutput(extracted, sourceFilename) {
4110
- return {
4111
- canonical: emitCanonical(extracted, sourceFilename),
4112
- ir: emitIR(extracted)
4113
- };
4114
- }
4115
- function foldTextContent(node) {
4116
- if (!node || typeof node !== "object") return node;
4117
- if (node.children && Array.isArray(node.children)) {
4118
- node.children = node.children.map((child) => foldTextContent(child));
4119
- if (node.children.length === 1 && node.children[0].component === "Text") {
4120
- const textChild = node.children[0];
4121
- const configKeys = textChild.config ? Object.keys(textChild.config).filter((k) => k !== "value") : [];
4122
- const bindingKeys = textChild.bindings ? Object.keys(textChild.bindings).filter((k) => k !== "value") : [];
4123
- const isSimple = !textChild.style && !textChild.className && !textChild.children && !textChild.visible_when && configKeys.length === 0 && bindingKeys.length === 0;
4124
- if (isSimple) {
4125
- const parentRules = PROP_RULES[node.component || ""];
4126
- const configKey = parentRules?.config?.text || "text";
4127
- const bindingKey = parentRules?.bindings?.text || "text";
4128
- if (textChild.config?.value && !textChild.bindings) {
4129
- if (!node.config) node.config = {};
4130
- node.config[configKey] = textChild.config.value;
4131
- node.children = void 0;
4132
- } else if (textChild.bindings?.value && !textChild.config?.value) {
4133
- if (!node.bindings) node.bindings = {};
4134
- node.bindings[bindingKey] = textChild.bindings.value;
4135
- node.children = void 0;
4136
- }
4137
- }
4138
- }
4139
- if (node.children && node.children.length === 0) {
4140
- node.children = void 0;
4141
- }
4142
- }
4143
- if (!node.children) delete node.children;
4144
- return node;
4145
- }
4146
- function emitWorkflowDefinition(extracted) {
4147
- const ir = emitIR(extracted);
4148
- const states = ir.states.map((s) => ({
4149
- name: s.name,
4150
- state_type: s.type,
4151
- description: s.description || "",
4152
- on_enter: (s.on_enter || []).map(convertAction),
4153
- on_exit: (s.on_exit || []).map(convertAction),
4154
- during: (s.during || []).map(convertDuringAction),
4155
- on_event: (s.on_event || []).map(convertOnEvent)
4156
- }));
4157
- const fields = ir.fields.map((f) => ({
4158
- name: toSnakeCase2(f.name),
4159
- field_type: f.type,
4160
- label: f.label || f.name.replace(/([A-Z])/g, " $1").replace(/^./, (c) => c.toUpperCase()),
4161
- required: f.required || false,
4162
- default_value: f.default_value ?? null,
4163
- ...f.validation && { validation: f.validation },
4164
- ...f.computed && { computed: f.computed },
4165
- ...f.computed_deps && { computed_deps: f.computed_deps },
4166
- ...f.visible_in_states && { visible_in_states: f.visible_in_states },
4167
- ...f.editable_in_states && { editable_in_states: f.editable_in_states },
4168
- ...f.visible_to_roles && { visible_to_roles: f.visible_to_roles },
4169
- ...f.editable_by_roles && { editable_by_roles: f.editable_by_roles },
4170
- ...f.visible_when && { visible_when: f.visible_when },
4171
- ...f.editable_when && { editable_when: f.editable_when },
4172
- ...f.state_home && { state_home: f.state_home }
4173
- }));
4174
- const transitions = ir.transitions.map((t18) => ({
4175
- name: t18.name,
4176
- from: t18.from,
4177
- to: t18.to,
4178
- description: t18.description || "",
4179
- roles: t18.roles || [],
4180
- auto: t18.auto || false,
4181
- conditions: t18.conditions || [],
4182
- actions: (t18.actions || []).map(convertAction),
4183
- required_fields: t18.required_fields || [],
4184
- priority: 0
4185
- }));
4186
- const state_data = {};
4187
- for (const f of fields) {
4188
- state_data[f.name] = f.default_value;
4189
- }
4190
- const on_event = (ir.on_event || []).map(convertOnEvent);
4191
- let views;
4192
- if (extracted.experience) {
4193
- const viewRoot = foldTextContent(JSON.parse(JSON.stringify(extracted.experience)));
4194
- const dataSources = extracted.extraMetadata?.dataSources;
4195
- if (dataSources && dataSources.length > 0) {
4196
- viewRoot.dataSources = dataSources;
4197
- }
4198
- if (extracted.fields.length > 0) {
4199
- const localDefaults = {};
4200
- for (const f of extracted.fields) {
4201
- localDefaults[toSnakeCase2(f.name)] = f.default_value ?? null;
4202
- }
4203
- if (!viewRoot.config) viewRoot.config = {};
4204
- viewRoot.config.localDefaults = localDefaults;
4205
- }
4206
- views = { default: viewRoot };
4207
- }
4208
- return {
4209
- id: `def-${ir.slug}`,
4210
- slug: ir.slug,
4211
- name: ir.name,
4212
- version: ir.version,
4213
- description: ir.description || "",
4214
- category: ir.category,
4215
- states,
4216
- transitions,
4217
- fields,
4218
- state_data,
4219
- roles: [],
4220
- child_definitions: [],
4221
- tags: ir.tags || [],
4222
- metadata: ir.metadata || {},
4223
- ...views && { views },
4224
- ...on_event.length > 0 && { on_event },
4225
- config: {},
4226
- is_immutable: false
4227
- };
4228
- }
4229
- function compilerStateToWorkflow(state, metadata) {
4230
- const fieldWatchers = metadata.fieldWatchers || [];
4231
- const transitionEffects = metadata.transitionEffects || [];
4232
- const grammarIslands = metadata.grammarIslands || [];
4233
- const knownKeys = /* @__PURE__ */ new Set(["slug", "name", "version", "description", "category", "fieldWatchers", "transitionEffects", "grammarIslands", "__modelImports", "__modelImportSlugs", "__slugAutoFallback"]);
4234
- const extraMetadata = {};
4235
- for (const [key, value] of Object.entries(metadata)) {
4236
- if (!knownKeys.has(key) && value !== void 0) {
4237
- extraMetadata[key] = value;
4238
- }
4239
- }
4240
- return {
4241
- slug: metadata.slug || "workflow",
4242
- name: metadata.name || "Workflow",
4243
- version: metadata.version || "0.1.0",
4244
- description: metadata.description,
4245
- category: metadata.category || "workflow",
4246
- fields: state.fields || [],
4247
- states: state.states || /* @__PURE__ */ new Map(),
4248
- transitions: state.transitions || [],
4249
- events: state.events || [],
4250
- experience: state.experience,
4251
- fieldWatchers: fieldWatchers.length > 0 ? fieldWatchers : void 0,
4252
- transitionEffects: transitionEffects.length > 0 ? transitionEffects : void 0,
4253
- grammarIslands: grammarIslands.length > 0 ? grammarIslands : void 0,
4254
- errors: state.errors,
4255
- warnings: state.warnings,
4256
- extraMetadata: Object.keys(extraMetadata).length > 0 ? extraMetadata : void 0
4257
- };
4258
- }
4259
-
4260
- // src/babel/visitor.ts
4261
- function resolveSlugArg(args, state) {
4262
- if (args.length < 1) return null;
4263
- const slugArg = args[0];
4264
- if (t17.isStringLiteral(slugArg)) return slugArg.value;
4265
- if (t17.isIdentifier(slugArg)) {
4266
- const compilerState = state;
4267
- const meta = compilerState.metadata;
4268
- const resolvedSlugs = meta.__modelImportSlugs;
4269
- if (resolvedSlugs?.[slugArg.name]) return resolvedSlugs[slugArg.name];
4270
- const importSources = meta.__modelImports;
4271
- if (importSources?.[slugArg.name]) {
4272
- const importPath = importSources[slugArg.name];
4273
- const filename = importPath.split("/").pop() || "";
4274
- return filename.replace(/\.(ts|tsx|js|jsx)$/, "").replace(/\.model$/, "").replace(/([A-Z])/g, "-$1").toLowerCase().replace(/^-/, "");
4275
- }
4276
- }
4277
- return null;
4278
- }
4279
- function extractQueryDataSource(path, state) {
4280
- const args = path.node.arguments;
4281
- if (args.length < 1) return;
4282
- const slug = resolveSlugArg(args, state);
4283
- if (!slug) return;
4284
- const compilerState = state;
4285
- const dataSource = {
4286
- type: "workflow",
4287
- name: slug,
4288
- slug,
4289
- query: "list"
4290
- };
4291
- if (args.length > 1 && t17.isObjectExpression(args[1])) {
4292
- for (const prop of args[1].properties) {
4293
- if (!t17.isObjectProperty(prop) || !t17.isIdentifier(prop.key)) continue;
4294
- const key = prop.key.name;
4295
- const val = prop.value;
4296
- switch (key) {
4297
- case "limit":
4298
- if (t17.isNumericLiteral(val)) {
4299
- dataSource.pageSize = val.value;
4300
- dataSource.paginated = true;
4301
- }
4302
- break;
4303
- case "orderBy":
4304
- if (t17.isStringLiteral(val)) {
4305
- dataSource.sort = val.value;
4306
- }
4307
- break;
4308
- case "order":
4309
- if (t17.isStringLiteral(val) && dataSource.sort) {
4310
- dataSource.sort = `${dataSource.sort}:${val.value}`;
4311
- }
4312
- break;
4313
- case "search":
4314
- if (t17.isStringLiteral(val)) {
4315
- dataSource.search = val.value;
4316
- }
4317
- break;
4318
- case "searchFields":
4319
- if (t17.isArrayExpression(val)) {
4320
- dataSource.searchFields = val.elements.filter((el) => t17.isStringLiteral(el)).map((el) => el.value);
4321
- }
4322
- break;
4323
- case "filter":
4324
- if (t17.isObjectExpression(val)) {
4325
- const filter = {};
4326
- for (const fp of val.properties) {
4327
- if (t17.isObjectProperty(fp) && t17.isIdentifier(fp.key) && t17.isStringLiteral(fp.value)) {
4328
- filter[fp.key.name] = fp.value.value;
4329
- }
4330
- }
4331
- if (Object.keys(filter).length > 0) {
4332
- dataSource.filter = filter;
4333
- }
4334
- }
4335
- break;
4336
- case "state":
4337
- if (t17.isStringLiteral(val)) {
4338
- if (!dataSource.filter) dataSource.filter = {};
4339
- dataSource.filter.current_state = val.value;
4340
- }
4341
- break;
4342
- case "groupBy":
4343
- if (t17.isStringLiteral(val)) {
4344
- dataSource.groupBy = val.value;
4345
- }
4346
- break;
4347
- case "facets":
4348
- if (t17.isArrayExpression(val)) {
4349
- dataSource.facets = val.elements.filter((el) => t17.isStringLiteral(el)).map((el) => el.value);
4350
- }
4351
- break;
4352
- }
4353
- }
4354
- }
4355
- if (!compilerState.metadata) compilerState.metadata = {};
4356
- const meta = compilerState.metadata;
4357
- if (!meta.dataSources) meta.dataSources = [];
4358
- meta.dataSources.push(dataSource);
4359
- }
4360
- function extractMutationDataSource(path, state) {
4361
- const args = path.node.arguments;
4362
- if (args.length < 1) return;
4363
- const slug = resolveSlugArg(args, state);
4364
- if (!slug) return;
4365
- const compilerState = state;
4366
- if (!compilerState.metadata) compilerState.metadata = {};
4367
- const meta = compilerState.metadata;
4368
- if (!meta.mutationTargets) meta.mutationTargets = [];
4369
- meta.mutationTargets.push(slug);
4370
- }
4371
- function extractDuringAction(path, state) {
4372
- const args = path.node.arguments;
4373
- if (args.length < 1 || !t17.isObjectExpression(args[0])) return;
4374
- const compilerState = state;
4375
- const config = args[0];
4376
- let stateName;
4377
- let intervalMs = 1e3;
4378
- for (const prop of config.properties) {
4379
- if (!t17.isObjectProperty(prop) || !t17.isIdentifier(prop.key)) continue;
4380
- if (prop.key.name === "state" && t17.isStringLiteral(prop.value)) {
4381
- stateName = prop.value.value;
4382
- }
4383
- if (prop.key.name === "intervalMs" && t17.isNumericLiteral(prop.value)) {
4384
- intervalMs = prop.value.value;
4385
- }
4386
- }
4387
- if (!stateName) return;
4388
- if (!compilerState.states.has(stateName)) {
4389
- compilerState.states.set(stateName, {
4390
- name: stateName,
4391
- type: "REGULAR",
4392
- on_enter: [],
4393
- during: [],
4394
- on_exit: []
4395
- });
4396
- }
4397
- const stateEntry = compilerState.states.get(stateName);
4398
- if (!stateEntry.during) stateEntry.during = [];
4399
- compilerState.actionCounter++;
4400
- stateEntry.during.push({
4401
- id: `during_${compilerState.actionCounter}`,
4402
- type: "interval",
4403
- interval_ms: intervalMs,
4404
- actions: []
4405
- });
4406
- }
4407
- function extractRoleDependency(path, state) {
4408
- const args = path.node.arguments;
4409
- if (args.length < 1 || !t17.isStringLiteral(args[0])) return;
4410
- const compilerState = state;
4411
- if (!compilerState.metadata) compilerState.metadata = {};
4412
- const meta = compilerState.metadata;
4413
- if (!meta.roleDependencies) meta.roleDependencies = [];
4414
- const roles = meta.roleDependencies;
4415
- const role = args[0].value;
4416
- if (!roles.includes(role)) roles.push(role);
4417
- }
4418
- function extractViewDependency(path, state) {
4419
- const args = path.node.arguments;
4420
- if (args.length < 1 || !t17.isStringLiteral(args[0])) return;
4421
- const compilerState = state;
4422
- if (!compilerState.metadata) compilerState.metadata = {};
4423
- const meta = compilerState.metadata;
4424
- if (!meta.viewDependencies) meta.viewDependencies = [];
4425
- const views = meta.viewDependencies;
4426
- const slug = args[0].value;
4427
- if (!views.includes(slug)) views.push(slug);
4428
- }
4429
- function extractParamsUsage(_path, state) {
4430
- const compilerState = state;
4431
- if (!compilerState.metadata) compilerState.metadata = {};
4432
- const meta = compilerState.metadata;
4433
- meta.acceptsParams = true;
4434
- }
4435
- function extractLibraryDependency(path, state) {
4436
- const args = path.node.arguments;
4437
- if (args.length < 1 || !t17.isStringLiteral(args[0])) return;
4438
- const compilerState = state;
4439
- if (!compilerState.metadata) compilerState.metadata = {};
4440
- const meta = compilerState.metadata;
4441
- if (!meta.libraryDependencies) meta.libraryDependencies = [];
4442
- const libs = meta.libraryDependencies;
4443
- const slug = args[0].value;
4444
- if (!libs.includes(slug)) libs.push(slug);
4445
- }
4446
- var STRICT_BANNED_HOOKS = {
4447
- useEffect: "STRICT_USE_EFFECT",
4448
- useLayoutEffect: "STRICT_USE_LAYOUT_EFFECT",
4449
- useRef: "STRICT_USE_REF",
4450
- useMemo: "STRICT_USE_MEMO",
4451
- useCallback: "STRICT_USE_CALLBACK"
4452
- };
4453
- function extractMetadataFromComments(comments, metadata) {
4454
- for (const comment of comments) {
4455
- if (comment.type !== "CommentBlock") continue;
4456
- const lines = comment.value.split("\n");
4457
- for (const line of lines) {
4458
- const workflowMatch = line.match(/@workflow\s+(.+)/);
4459
- if (workflowMatch) {
4460
- const rest = workflowMatch[1].trim();
4461
- const kvRegex = /(\w+)="([^"]+)"/g;
4462
- let kvMatch;
4463
- let hasKV = false;
4464
- while ((kvMatch = kvRegex.exec(rest)) !== null) {
4465
- hasKV = true;
4466
- const [, key, val] = kvMatch;
4467
- if (key === "slug") metadata.slug = val;
4468
- else if (key === "version") metadata.version = val;
4469
- else if (key === "category") metadata.category = val;
4470
- else if (key === "description") metadata.description = val;
4471
- }
4472
- if (!hasKV) {
4473
- metadata.slug = rest;
4474
- }
4475
- continue;
4476
- }
4477
- const match = line.match(/@(\w+)\s+(.+)/);
4478
- if (match) {
4479
- const [, tag, value] = match;
4480
- if (tag === "version") metadata.version = value.trim();
4481
- if (tag === "category") metadata.category = value.trim();
4482
- if (tag === "description") metadata.description = value.trim();
4483
- }
4484
- }
4485
- }
4486
- }
4487
- function createVisitor(options = {}) {
4488
- const mode = options.mode;
4489
- return {
4490
- Program: {
4491
- // Initialize compiler state at program entry
4492
- enter(_path, state) {
4493
- resetNodeIdCounter();
4494
- resetDuringIdCounter();
4495
- resetWatcherIdCounter();
4496
- resetTransitionEffectIdCounter();
4497
- const compilerState = {
4498
- fields: [],
4499
- states: /* @__PURE__ */ new Map(),
4500
- transitions: [],
4501
- events: [],
4502
- actionCounter: 0,
4503
- metadata: {},
4504
- errors: [],
4505
- warnings: []
4506
- };
4507
- const program = _path.node;
4508
- const leadingComments = program.leadingComments || [];
4509
- extractMetadataFromComments(leadingComments, compilerState.metadata);
4510
- if (program.body.length > 0) {
4511
- const firstStmt = program.body[0];
4512
- if (firstStmt.leadingComments) {
4513
- extractMetadataFromComments(firstStmt.leadingComments, compilerState.metadata);
4514
- }
4515
- }
4516
- const exportDeclaration = program.body.find(
4517
- (node) => t17.isExportNamedDeclaration(node) || t17.isExportDefaultDeclaration(node)
4518
- );
4519
- if (exportDeclaration) {
4520
- if (exportDeclaration.leadingComments) {
4521
- extractMetadataFromComments(exportDeclaration.leadingComments, compilerState.metadata);
4522
- }
4523
- if (t17.isExportNamedDeclaration(exportDeclaration)) {
4524
- const declaration = exportDeclaration.declaration;
4525
- if (t17.isFunctionDeclaration(declaration)) {
4526
- if (declaration.id) {
4527
- compilerState.metadata.name = declaration.id.name;
4528
- }
4529
- if (declaration.leadingComments) {
4530
- extractMetadataFromComments(declaration.leadingComments, compilerState.metadata);
4531
- }
4532
- }
4533
- } else if (t17.isExportDefaultDeclaration(exportDeclaration)) {
4534
- const declaration = exportDeclaration.declaration;
4535
- if (t17.isFunctionDeclaration(declaration)) {
4536
- if (declaration.id) {
4537
- compilerState.metadata.name = declaration.id.name;
4538
- }
4539
- if (declaration.leadingComments) {
4540
- extractMetadataFromComments(declaration.leadingComments, compilerState.metadata);
4541
- }
4542
- } else if (t17.isIdentifier(declaration)) {
4543
- compilerState.metadata.name = declaration.name;
4544
- }
4545
- }
4546
- }
4547
- if (!compilerState.metadata.slug && state.filename) {
4548
- const fileName = state.filename.split("/").pop() || "";
4549
- compilerState.metadata.slug = fileName.replace(/\.workflow\.(tsx?|jsx?)$/, "").replace(/\.(tsx?|jsx?)$/, "").replace(/([A-Z])/g, "-$1").toLowerCase().replace(/^-/, "");
4550
- compilerState.metadata.__slugAutoFallback = true;
4551
- }
4552
- Object.assign(state, compilerState);
4553
- if (isModelFile(_path, state.filename)) {
4554
- extractModelFile(_path, state);
4555
- state.__isModelFile = true;
4556
- if (!compilerState.metadata.category) {
4557
- compilerState.metadata.category = "data";
4558
- }
4559
- }
4560
- extractGrammarIslands(_path, state);
4561
- if (hasContextCreation(_path)) {
4562
- extractContextWorkflows(_path, state);
4563
- }
4564
- if (isServerActionFile(state.filename)) {
4565
- extractServerActions(_path, state);
4566
- state.__isServerActionFile = true;
4567
- }
4568
- },
4569
- // After all extraction, emit Pure Form JSON
4570
- exit(_path, state) {
4571
- const compilerState = state;
4572
- const extracted = compilerStateToWorkflow(compilerState, compilerState.metadata);
4573
- const ir = emitIR(extracted);
4574
- const definition = emitWorkflowDefinition(extracted);
4575
- const canonical = emitCanonical(extracted, state.filename);
4576
- if (compilerState.errors && compilerState.errors.length > 0) {
4577
- if (!ir.metadata) ir.metadata = {};
4578
- ir.metadata.errors = compilerState.errors;
4579
- }
4580
- if (compilerState.warnings && compilerState.warnings.length > 0) {
4581
- if (!ir.metadata) ir.metadata = {};
4582
- ir.metadata.warnings = compilerState.warnings;
4583
- }
4584
- if (!state.file.metadata) state.file.metadata = {};
4585
- state.file.metadata.mindmatrixIR = ir;
4586
- state.file.metadata.mindmatrixDefinition = definition;
4587
- state.file.metadata.mindmatrixCanonical = canonical;
4588
- }
4589
- },
4590
- // Extract metadata from function declarations with JSDoc
4591
- FunctionDeclaration(path, state) {
4592
- const comments = path.node.leadingComments || [];
4593
- const compilerState = state;
4594
- extractMetadataFromComments(comments, compilerState.metadata);
4595
- },
4596
- // Main hook extraction dispatcher
4597
- CallExpression(path, state) {
4598
- const callee = path.node.callee;
4599
- if (!t17.isIdentifier(callee)) return;
4600
- const compilerState = state;
4601
- const hookName = callee.name;
4602
- if (mode === "strict" && STRICT_BANNED_HOOKS[hookName]) {
4603
- const error = {
4604
- code: STRICT_BANNED_HOOKS[hookName],
4605
- message: `${hookName}() is not allowed in strict mode. Use @mindmatrix/react effect hooks instead.`,
4606
- line: path.node.loc?.start.line,
4607
- column: path.node.loc?.start.column,
4608
- severity: "error"
4609
- };
4610
- if (!compilerState.errors) compilerState.errors = [];
4611
- compilerState.errors.push(error);
4612
- return;
4613
- }
4614
- if (mode === "infer" && hookName === "useEffect") {
4615
- const warning = {
4616
- code: "INFER_RAW_JSX",
4617
- message: `useEffect() found in infer mode \u2014 component will be treated as an opaque [raw jsx] grammar island.`,
4618
- line: path.node.loc?.start.line,
4619
- column: path.node.loc?.start.column,
4620
- severity: "warning"
4621
- };
4622
- if (!compilerState.warnings) compilerState.warnings = [];
4623
- compilerState.warnings.push(warning);
4624
- return;
4625
- }
4626
- switch (hookName) {
4627
- case "useState":
4628
- extractStates(path, state);
4629
- break;
4630
- case "useOnEnter":
4631
- case "useOnExit":
4632
- extractEffects(path, state);
4633
- break;
4634
- case "useTransition":
4635
- extractTransitions(path, state);
4636
- break;
4637
- case "useOnEvent":
4638
- extractEvents(path, state);
4639
- break;
4640
- case "useWhileIn":
4641
- extractDuring(path, state);
4642
- break;
4643
- case "useOnChange":
4644
- extractChangeWatcher(path, state);
4645
- break;
4646
- case "useComputed":
4647
- extractComputed(path, state);
4648
- break;
4649
- case "useOnTransition":
4650
- extractTransitionEffect(path, state);
4651
- break;
4652
- case "useQuery":
4653
- extractQueryDataSource(path, state);
4654
- break;
4655
- case "useMutation":
4656
- extractMutationDataSource(path, state);
4657
- break;
4658
- case "useDuringAction":
4659
- extractDuringAction(path, state);
4660
- break;
4661
- case "useRole":
4662
- extractRoleDependency(path, state);
4663
- break;
4664
- case "useView":
4665
- extractViewDependency(path, state);
4666
- break;
4667
- case "useParams":
4668
- extractParamsUsage(path, state);
4669
- break;
4670
- case "useExpressionLibrary":
4671
- extractLibraryDependency(path, state);
4672
- break;
4673
- case "useServerAction":
4674
- extractServerActionHook(path, state);
4675
- break;
4676
- case "useServerState":
4677
- extractServerState(path, state);
4678
- break;
4679
- }
4680
- },
4681
- // Track imports: model imports for useQuery(modelRef) resolution + strict mode validation
4682
- ImportDeclaration(path, state) {
4683
- const compilerState = state;
4684
- const source = path.node.source.value;
4685
- if (source.match(/\/models\/|\.model(?:\.[tj]sx?)?$/)) {
4686
- if (!compilerState.metadata) compilerState.metadata = {};
4687
- const meta = compilerState.metadata;
4688
- if (!meta.__modelImports) meta.__modelImports = {};
4689
- const imports = meta.__modelImports;
4690
- for (const specifier of path.node.specifiers) {
4691
- if (t17.isImportDefaultSpecifier(specifier) || t17.isImportSpecifier(specifier)) {
4692
- imports[specifier.local.name] = source;
4693
- }
4694
- }
4695
- }
4696
- if (mode !== "strict") return;
4697
- if (source.startsWith("@mindmatrix/") || source === "react" || source.startsWith("react/") || source.startsWith(".") || source.startsWith("/")) {
4698
- return;
4699
- }
4700
- const error = {
4701
- code: "STRICT_FORBIDDEN_IMPORT",
4702
- message: `Import from '${source}' is not allowed in strict mode. Only @mindmatrix/* and relative imports are permitted.`,
4703
- line: path.node.loc?.start.line,
4704
- column: path.node.loc?.start.column,
4705
- severity: "error"
4706
- };
4707
- if (!compilerState.errors) compilerState.errors = [];
4708
- compilerState.errors.push(error);
4709
- },
4710
- // Track derived/computed variable declarations for expression inlining.
4711
- //
4712
- // Three cases:
4713
- // 1. `const hasContent = expr` → registerDerivedVar (inline the expression)
4714
- // 2. `const users = useQuery(...)` → registerDerivedVar as $instance.{slug}
4715
- // (data source results are available on $instance by their slug)
4716
- // 3. `const sendMsg = useMutation(...)` → registerDerivedVar as $action.transition
4717
- // (mutation results are action callbacks)
4718
- // 4. `const memo = useMemo(() => expr, [])` → registerDerivedVar with body expr
4719
- VariableDeclarator(path, state) {
4720
- const compilerState = state;
4721
- if (!compilerState.metadata) return;
4722
- const id = path.node.id;
4723
- const init = path.node.init;
4724
- if (t17.isArrayPattern(id)) return;
4725
- if (!t17.isIdentifier(id) || !init || !t17.isExpression(init)) return;
4726
- const parentFn = path.getFunctionParent();
4727
- if (!parentFn) return;
4728
- const parentNode = parentFn.parentPath;
4729
- const isExportedDirectly = parentNode?.isExportDefaultDeclaration() || parentNode?.isExportNamedDeclaration();
4730
- let isExportedByName = false;
4731
- if (!isExportedDirectly && parentNode?.isVariableDeclarator()) {
4732
- const varId = parentNode.node.id;
4733
- if (t17.isIdentifier(varId)) {
4734
- isExportedByName = varId.name === compilerState.metadata?.name;
4735
- }
4736
- }
4737
- if (!isExportedDirectly && !isExportedByName) return;
4738
- if (t17.isCallExpression(init) && t17.isIdentifier(init.callee)) {
4739
- const callee = init.callee.name;
4740
- if (callee === "useQuery") {
4741
- registerDerivedVar(id.name, t17.optionalMemberExpression(
4742
- t17.identifier("$instance"),
4743
- t17.identifier(id.name),
4744
- false,
4745
- // computed
4746
- true
4747
- // optional
4748
- ));
4749
- return;
4750
- }
4751
- if (callee === "useMutation") {
4752
- registerDerivedVar(id.name, t17.memberExpression(
4753
- t17.identifier("$action"),
4754
- t17.identifier("transition")
4755
- ));
4756
- return;
4757
- }
4758
- if (callee === "useServerAction") {
4759
- registerDerivedVar(id.name, t17.memberExpression(
4760
- t17.identifier("$action"),
4761
- t17.identifier("serverAction")
4762
- ));
4763
- return;
4764
- }
4765
- if (callee === "useServerState") {
4766
- registerDerivedVar(id.name, t17.optionalMemberExpression(
4767
- t17.identifier("$instance"),
4768
- t17.identifier("serverState"),
4769
- false,
4770
- true
4771
- ));
4772
- return;
4773
- }
4774
- if (callee === "useMemo" && init.arguments.length >= 1) {
4775
- const callback = init.arguments[0];
4776
- if (t17.isArrowFunctionExpression(callback)) {
4777
- if (t17.isExpression(callback.body)) {
4778
- registerDerivedVar(id.name, callback.body);
4779
- } else if (t17.isBlockStatement(callback.body)) {
4780
- const retStmt = callback.body.body.find((s) => t17.isReturnStatement(s));
4781
- if (retStmt?.argument && t17.isExpression(retStmt.argument)) {
4782
- registerDerivedVar(id.name, retStmt.argument);
4783
- }
4784
- }
4785
- }
4786
- return;
4787
- }
4788
- if (callee.startsWith("use")) return;
4789
- }
4790
- registerDerivedVar(id.name, init);
4791
- },
4792
- // Extract JSX from function component return.
4793
- // Only extract from the exported component function's direct return,
4794
- // not from nested callbacks (Each render functions, helper components, etc.).
4795
- ReturnStatement(path, state) {
4796
- if (!t17.isJSXElement(path.node.argument) && !t17.isJSXFragment(path.node.argument)) return;
4797
- const parentFn = path.getFunctionParent();
4798
- if (!parentFn) return;
4799
- const parentNode = parentFn.parentPath;
4800
- const isExportedDirectly = parentNode?.isExportDefaultDeclaration() || parentNode?.isExportNamedDeclaration();
4801
- let isExportedByName = false;
4802
- if (!isExportedDirectly && parentNode?.isVariableDeclarator()) {
4803
- const varId = parentNode.node.id;
4804
- if (t17.isIdentifier(varId)) {
4805
- isExportedByName = varId.name === state.metadata?.name;
4806
- }
4807
- }
4808
- if (isExportedDirectly || isExportedByName) {
4809
- extractComponents(path, state);
4810
- }
4811
- }
4812
- };
4813
- }
4814
-
4815
- // src/babel/index.ts
4816
- function babelPlugin(api, options = {}) {
4817
- api.assertVersion(7);
4818
- return {
4819
- name: "mindmatrix-react",
4820
- visitor: createVisitor(options)
4821
- };
4822
- }
4823
-
4824
- export {
4825
- extractStates,
4826
- extractEffects,
4827
- extractTransitions,
4828
- extractEvents,
4829
- extractComponents,
4830
- extractComputed,
4831
- transformToFrontend,
4832
- emitIR,
4833
- emitPureForm,
4834
- emitCanonical,
4835
- emitCompiledOutput,
4836
- compilerStateToWorkflow,
4837
- createVisitor,
4838
- babelPlugin
4839
- };