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

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