@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
@@ -0,0 +1,2607 @@
1
+ import {
2
+ babelPlugin,
3
+ init_ts_to_expression,
4
+ transpileBlock,
5
+ ts_to_expression_exports
6
+ } from "./chunk-FYT47UBU.mjs";
7
+ import {
8
+ __toCommonJS
9
+ } from "./chunk-CIESM3BP.mjs";
10
+
11
+ // src/project-compiler.ts
12
+ import { transformSync as transformSync3 } from "@babel/core";
13
+
14
+ // src/babel/extractors/router-extractor.ts
15
+ function pathToStateName(routePath) {
16
+ if (!routePath || routePath === "" || routePath === "/") return "HOME";
17
+ return routePath.split("/").filter(Boolean).map((segment) => {
18
+ if (segment.startsWith("[") && segment.endsWith("]")) {
19
+ return segment.slice(1, -1);
20
+ }
21
+ return segment;
22
+ }).join("_").replace(/([a-z])([A-Z])/g, "$1_$2").toUpperCase().replace(/-/g, "_");
23
+ }
24
+ function pathToUrlPattern(relativePath, pageFileName = "page.tsx") {
25
+ let routePath = relativePath.replace(new RegExp(`/?${pageFileName.replace(".", "\\.")}$`), "");
26
+ routePath = routePath.replace(/\[([^\]]+)\]/g, ":$1");
27
+ return "/" + routePath;
28
+ }
29
+ function extractParams(relativePath) {
30
+ const params = [];
31
+ const paramRegex = /\[([^\]]+)\]/g;
32
+ let match;
33
+ while ((match = paramRegex.exec(relativePath)) !== null) {
34
+ params.push(match[1]);
35
+ }
36
+ return params;
37
+ }
38
+ function extractRouterWorkflow(pages, options = {}) {
39
+ const {
40
+ slug = "app-router",
41
+ pageFileName = "page.tsx",
42
+ layoutFileName = "layout.tsx"
43
+ } = options;
44
+ const pageFiles = pages.filter((p) => !p.isLayout && p.relativePath.endsWith(pageFileName));
45
+ const layoutFiles = pages.filter((p) => p.isLayout || p.relativePath.endsWith(layoutFileName));
46
+ const routeStates = [];
47
+ const stateMap = /* @__PURE__ */ new Map();
48
+ for (const page of pageFiles) {
49
+ const routePath = page.relativePath.replace(new RegExp(`/?${pageFileName.replace(".", "\\.")}$`), "");
50
+ const stateName = pathToStateName(routePath);
51
+ const urlPattern = pathToUrlPattern(page.relativePath, pageFileName);
52
+ const params = extractParams(page.relativePath);
53
+ const layoutBoundary = findLayoutBoundary(page.relativePath, layoutFiles);
54
+ const routeState = {
55
+ name: stateName,
56
+ path: urlPattern,
57
+ params,
58
+ layoutBoundary,
59
+ sourceFile: page.relativePath,
60
+ type: stateName === "HOME" ? "START" : "REGULAR"
61
+ };
62
+ routeStates.push(routeState);
63
+ stateMap.set(stateName, routeState);
64
+ }
65
+ if (!stateMap.has("HOME") && routeStates.length > 0) {
66
+ routeStates[0].type = "START";
67
+ }
68
+ const states = routeStates.map((rs) => ({
69
+ name: rs.name,
70
+ type: rs.type,
71
+ description: `Route: ${rs.path}`,
72
+ on_enter: [],
73
+ during: [],
74
+ on_exit: []
75
+ }));
76
+ const transitions = [];
77
+ let transitionId = 0;
78
+ for (const page of pageFiles) {
79
+ if (!page.navigationTargets) continue;
80
+ const fromPath = page.relativePath.replace(new RegExp(`/?${pageFileName.replace(".", "\\.")}$`), "");
81
+ const fromState = pathToStateName(fromPath);
82
+ for (const target of page.navigationTargets) {
83
+ const targetPath = target.replace(/^\//, "").replace(/\/page\.(tsx|ts|jsx|js)$/, "");
84
+ const toState = pathToStateName(targetPath);
85
+ if (stateMap.has(toState) || toState === fromState) continue;
86
+ const transitionName = `navigate_to_${toState.toLowerCase()}`;
87
+ transitions.push({
88
+ name: transitionName,
89
+ from: [fromState],
90
+ to: toState,
91
+ actions: [],
92
+ conditions: []
93
+ });
94
+ transitionId++;
95
+ }
96
+ }
97
+ if (routeStates.length > 1) {
98
+ for (const rs of routeStates) {
99
+ if (rs.type !== "START") {
100
+ transitions.push({
101
+ name: `navigate_home_from_${rs.name.toLowerCase()}`,
102
+ from: [rs.name],
103
+ to: "HOME",
104
+ actions: [],
105
+ conditions: []
106
+ });
107
+ }
108
+ }
109
+ }
110
+ const fields = [];
111
+ const seenParams = /* @__PURE__ */ new Set();
112
+ for (const rs of routeStates) {
113
+ for (const param of rs.params) {
114
+ if (seenParams.has(param)) continue;
115
+ seenParams.add(param);
116
+ fields.push({
117
+ name: param,
118
+ type: "text",
119
+ required: false,
120
+ default_value: ""
121
+ });
122
+ }
123
+ }
124
+ const routeMetadata = routeStates.map((rs) => ({
125
+ state: rs.name,
126
+ path: rs.path,
127
+ params: rs.params,
128
+ layoutBoundary: rs.layoutBoundary,
129
+ sourceFile: rs.sourceFile
130
+ }));
131
+ return {
132
+ slug,
133
+ name: "Router",
134
+ version: "1.0.0",
135
+ description: "Auto-derived router workflow from file-based routing",
136
+ category: "router",
137
+ fields,
138
+ states,
139
+ transitions,
140
+ roles: [],
141
+ tags: [{ tag_name: "auto-derived" }, { tag_name: "router" }],
142
+ metadata: {
143
+ runtime: "local",
144
+ routes: routeMetadata,
145
+ layoutBoundaries: layoutFiles.map((l) => l.relativePath)
146
+ }
147
+ };
148
+ }
149
+ function findLayoutBoundary(pageRelativePath, layoutFiles) {
150
+ const layoutPaths = layoutFiles.map((l) => l.relativePath);
151
+ const parts = pageRelativePath.split("/");
152
+ for (let i = parts.length - 1; i >= 0; i--) {
153
+ const dir = parts.slice(0, i).join("/");
154
+ const layoutPath = dir ? `${dir}/layout.tsx` : "layout.tsx";
155
+ if (layoutPaths.includes(layoutPath)) {
156
+ return layoutPath;
157
+ }
158
+ }
159
+ return void 0;
160
+ }
161
+
162
+ // src/model-compiler.ts
163
+ import { transformSync } from "@babel/core";
164
+ function extractInterfaceName(source) {
165
+ const match = source.match(/export\s+interface\s+(\w+)/);
166
+ return match ? match[1] : "Unknown";
167
+ }
168
+ function extractWorkflowAnnotation(source) {
169
+ const result = {};
170
+ const workflowMatch = source.match(/@workflow\s+(.+)/);
171
+ if (workflowMatch) {
172
+ const attrs = workflowMatch[1];
173
+ const slugM = attrs.match(/slug="([^"]+)"/);
174
+ if (slugM) result.slug = slugM[1];
175
+ const versionM = attrs.match(/version="([^"]+)"/);
176
+ if (versionM) result.version = versionM[1];
177
+ const categoryM = attrs.match(/category="([^"]+)"/);
178
+ if (categoryM) result.category = categoryM[1];
179
+ }
180
+ const descMatch = source.match(/@description\s+(.+)/);
181
+ if (descMatch) result.description = descMatch[1].trim();
182
+ return result;
183
+ }
184
+ function extractFieldOptionsRaw(source) {
185
+ const result = {};
186
+ const match = source.match(/export\s+const\s+fieldOptions\s*=\s*\{([\s\S]*?)\};/);
187
+ if (!match) return result;
188
+ const body = match[1];
189
+ const fieldRegex = /(\w+)\s*:\s*\{([^}]*)\}/g;
190
+ let fieldMatch;
191
+ while ((fieldMatch = fieldRegex.exec(body)) !== null) {
192
+ const fieldName = fieldMatch[1];
193
+ const optionsBody = fieldMatch[2];
194
+ const opts = {};
195
+ const kvRegex = /(\w+)\s*:\s*(?:'([^']*)'|"([^"]*)"|\[([^\]]*)\]|(\d+(?:\.\d+)?)|(\w+))/g;
196
+ let kvMatch;
197
+ while ((kvMatch = kvRegex.exec(optionsBody)) !== null) {
198
+ const key = kvMatch[1];
199
+ const strVal = kvMatch[2] ?? kvMatch[3];
200
+ const arrVal = kvMatch[4];
201
+ const numVal = kvMatch[5];
202
+ const identVal = kvMatch[6];
203
+ if (strVal !== void 0) {
204
+ opts[key] = strVal;
205
+ } else if (arrVal !== void 0) {
206
+ opts[key] = arrVal.split(",").map((s) => s.trim().replace(/['"]/g, "")).filter(Boolean);
207
+ } else if (numVal !== void 0) {
208
+ opts[key] = Number(numVal);
209
+ } else if (identVal !== void 0) {
210
+ if (identVal === "true") opts[key] = true;
211
+ else if (identVal === "false") opts[key] = false;
212
+ else opts[key] = identVal;
213
+ }
214
+ }
215
+ result[fieldName] = opts;
216
+ }
217
+ return result;
218
+ }
219
+ function compileModel(filename, source, options = {}) {
220
+ const mode = options.mode || "infer";
221
+ const interfaceName = extractInterfaceName(source);
222
+ const annotation = extractWorkflowAnnotation(source);
223
+ const rawFieldOptions = extractFieldOptionsRaw(source);
224
+ const parserPlugins = filename.endsWith(".tsx") ? ["typescript", "jsx"] : ["typescript"];
225
+ const babelResult = transformSync(source, {
226
+ filename,
227
+ plugins: [[babelPlugin, { mode }]],
228
+ parserOpts: { plugins: parserPlugins, attachComment: true }
229
+ });
230
+ const ir = babelResult?.metadata?.mindmatrixIR ?? createEmptyModelIR(interfaceName);
231
+ ir.category = options.categoryOverride || annotation.category || "data";
232
+ if (options.slugOverride) {
233
+ ir.slug = options.slugOverride;
234
+ }
235
+ if (ir.states.length === 0) {
236
+ ir.states.push({
237
+ name: "draft",
238
+ type: "START",
239
+ on_enter: [],
240
+ during: [],
241
+ on_exit: []
242
+ });
243
+ }
244
+ const hasStart = ir.states.some((s) => s.type === "START");
245
+ if (!hasStart && ir.states.length > 0) {
246
+ ir.states[0].type = "START";
247
+ }
248
+ if (!ir.metadata) ir.metadata = {};
249
+ const meta = ir.metadata;
250
+ meta.sourceInterface = interfaceName;
251
+ meta.fieldOptions = rawFieldOptions;
252
+ meta.provenance = {
253
+ frontend: "react-compiler",
254
+ source: "model",
255
+ compiler_version: "2.0.0"
256
+ };
257
+ return {
258
+ ir,
259
+ interfaceName,
260
+ fieldNames: ir.fields.map((f) => f.name),
261
+ transitionNames: ir.transitions.map((t2) => t2.name),
262
+ stateNames: ir.states.map((s) => s.name),
263
+ hasFieldOptions: Object.keys(rawFieldOptions).length > 0,
264
+ fieldOptions: rawFieldOptions
265
+ };
266
+ }
267
+ function compileModels(files, options = {}) {
268
+ const results = /* @__PURE__ */ new Map();
269
+ for (const [filename, source] of Object.entries(files)) {
270
+ try {
271
+ const compiled = compileModel(filename, source, options);
272
+ results.set(filename, compiled);
273
+ } catch (_err) {
274
+ const iface = extractInterfaceName(source);
275
+ results.set(filename, {
276
+ ir: createEmptyModelIR(iface),
277
+ interfaceName: iface,
278
+ fieldNames: [],
279
+ transitionNames: [],
280
+ stateNames: ["draft"],
281
+ hasFieldOptions: false,
282
+ fieldOptions: {}
283
+ });
284
+ }
285
+ }
286
+ return results;
287
+ }
288
+ function createEmptyModelIR(interfaceName) {
289
+ const slug = interfaceName.replace(/([A-Z])/g, "-$1").toLowerCase().replace(/^-/, "");
290
+ return {
291
+ slug,
292
+ name: interfaceName,
293
+ version: "1.0.0",
294
+ description: "Data model: " + interfaceName,
295
+ category: "data",
296
+ fields: [],
297
+ states: [{
298
+ name: "draft",
299
+ type: "START",
300
+ on_enter: [],
301
+ during: [],
302
+ on_exit: []
303
+ }],
304
+ transitions: [],
305
+ roles: [],
306
+ tags: [{ tag_name: "data" }, { tag_name: "model" }],
307
+ metadata: {
308
+ sourceInterface: interfaceName,
309
+ provenance: {
310
+ frontend: "react-compiler",
311
+ source: "model",
312
+ compiler_version: "2.0.0"
313
+ }
314
+ }
315
+ };
316
+ }
317
+
318
+ // src/route-extractor.ts
319
+ function filePathToUrlPattern(filePath, rootDir) {
320
+ let route = filePath;
321
+ const rootPrefix = rootDir + "/";
322
+ if (route.startsWith(rootPrefix)) {
323
+ route = route.slice(rootPrefix.length);
324
+ }
325
+ route = route.replace(/\.(tsx?|jsx?)$/, "");
326
+ route = route.replace(/\/(page|index)$/, "");
327
+ if (route === "page" || route === "index" || route === "") {
328
+ return "/";
329
+ }
330
+ route = route.replace(/\[([^\]]+)\]/g, ":$1");
331
+ return "/" + route;
332
+ }
333
+ function urlToStateName(urlPath) {
334
+ if (urlPath === "/") return "HOME";
335
+ return urlPath.split("/").filter(Boolean).map((segment) => segment.replace(/^:/, "")).join("_").replace(/([a-z])([A-Z])/g, "$1_$2").replace(/-/g, "_").toUpperCase();
336
+ }
337
+ function extractRouteParams(filePath) {
338
+ const params = [];
339
+ const regex = /\[([^\]]+)\]/g;
340
+ let match;
341
+ while ((match = regex.exec(filePath)) !== null) {
342
+ params.push(match[1]);
343
+ }
344
+ return params;
345
+ }
346
+ function routeDepth(urlPath) {
347
+ if (urlPath === "/") return 0;
348
+ return urlPath.split("/").filter(Boolean).length;
349
+ }
350
+ function isPageFile(filename, pageFileName) {
351
+ if (filename.endsWith("/" + pageFileName)) return true;
352
+ return /\.(tsx|ts|jsx|js)$/.test(filename) && !filename.endsWith(".test.ts") && !filename.endsWith(".test.tsx") && !filename.includes("layout");
353
+ }
354
+ function isLayoutFile(filename, layoutFileName) {
355
+ return filename.endsWith("/" + layoutFileName) || filename.endsWith(layoutFileName);
356
+ }
357
+ function extractRoutes(files, options = {}) {
358
+ const rootDir = options.rootDir || "app";
359
+ const pageFileName = options.pageFileName || "page.tsx";
360
+ const layoutFileName = options.layoutFileName || "layout.tsx";
361
+ const slugPrefix = options.slugPrefix || "app";
362
+ const layouts = [];
363
+ for (const filename of Object.keys(files)) {
364
+ if (isLayoutFile(filename, layoutFileName)) {
365
+ const dir = filename.replace(/\/[^/]+$/, "");
366
+ layouts.push({
367
+ sourceFile: filename,
368
+ directory: dir,
369
+ depth: dir.split("/").filter(Boolean).length
370
+ });
371
+ }
372
+ }
373
+ layouts.sort((a, b) => a.depth - b.depth);
374
+ const routes = [];
375
+ const allParams = /* @__PURE__ */ new Set();
376
+ for (const filename of Object.keys(files)) {
377
+ if (isLayoutFile(filename, layoutFileName)) continue;
378
+ if (!filename.startsWith(rootDir + "/") && !filename.startsWith(rootDir)) continue;
379
+ if (!isPageFile(filename, pageFileName)) continue;
380
+ const urlPath = filePathToUrlPattern(filename, rootDir);
381
+ const stateName = urlToStateName(urlPath);
382
+ const params = extractRouteParams(filename);
383
+ const depth = routeDepth(urlPath);
384
+ const fileDir = filename.replace(/\/[^/]+$/, "");
385
+ let layoutBoundary;
386
+ for (let i = layouts.length - 1; i >= 0; i--) {
387
+ if (fileDir.startsWith(layouts[i].directory)) {
388
+ layoutBoundary = layouts[i].sourceFile;
389
+ break;
390
+ }
391
+ }
392
+ for (const p of params) allParams.add(p);
393
+ routes.push({
394
+ path: urlPath,
395
+ stateName,
396
+ sourceFile: filename,
397
+ params,
398
+ layoutBoundary,
399
+ depth
400
+ });
401
+ }
402
+ routes.sort((a, b) => a.path.localeCompare(b.path));
403
+ const routerIR = buildRouterIR(routes, layouts, Array.from(allParams), slugPrefix);
404
+ return {
405
+ routes,
406
+ layouts,
407
+ routerIR,
408
+ allParams: Array.from(allParams)
409
+ };
410
+ }
411
+ function buildRouterIR(routes, layouts, allParams, slugPrefix) {
412
+ const states = routes.map((route) => ({
413
+ name: route.stateName,
414
+ type: route.path === "/" ? "START" : "REGULAR",
415
+ description: "Route: " + route.path,
416
+ on_enter: [],
417
+ during: [],
418
+ on_exit: []
419
+ }));
420
+ if (states.length > 0 && !states.some((s) => s.type === "START")) {
421
+ states[0].type = "START";
422
+ }
423
+ const transitions = [];
424
+ for (const from of routes) {
425
+ for (const to of routes) {
426
+ if (from.stateName === to.stateName) continue;
427
+ transitions.push({
428
+ name: "nav_" + from.stateName.toLowerCase() + "_to_" + to.stateName.toLowerCase(),
429
+ from: [from.stateName],
430
+ to: to.stateName,
431
+ actions: [],
432
+ conditions: []
433
+ });
434
+ }
435
+ }
436
+ const fields = allParams.map((param) => ({
437
+ name: param,
438
+ type: "text",
439
+ label: param.replace(/([A-Z])/g, " $1").replace(/^./, (c) => c.toUpperCase()),
440
+ required: false,
441
+ default_value: ""
442
+ }));
443
+ fields.push({
444
+ name: "current_route",
445
+ type: "text",
446
+ label: "Current Route",
447
+ required: false,
448
+ default_value: "/"
449
+ });
450
+ return {
451
+ slug: slugPrefix + "-router",
452
+ name: "Router",
453
+ version: "1.0.0",
454
+ description: "Auto-generated router from app/ directory structure",
455
+ category: "router",
456
+ fields,
457
+ states,
458
+ transitions,
459
+ roles: [],
460
+ tags: [{ tag_name: "auto-derived" }, { tag_name: "router" }],
461
+ metadata: {
462
+ runtime: "local",
463
+ routes: routes.map((r) => ({
464
+ state: r.stateName,
465
+ path: r.path,
466
+ params: r.params,
467
+ layoutBoundary: r.layoutBoundary,
468
+ sourceFile: r.sourceFile
469
+ })),
470
+ layoutBoundaries: layouts.map((l) => l.sourceFile),
471
+ provenance: {
472
+ frontend: "react-compiler",
473
+ source: "route-extractor",
474
+ compiler_version: "2.0.0"
475
+ }
476
+ }
477
+ };
478
+ }
479
+
480
+ // src/action-compiler.ts
481
+ import { transformSync as transformSync2 } from "@babel/core";
482
+ function extractActionGroup(filename) {
483
+ const base = filename.split("/").pop() || filename;
484
+ return base.replace(/\.server\.(ts|tsx|js|jsx)$/, "");
485
+ }
486
+ function generateEndpoint(blueprintSlug, group, actionName, apiBasePath) {
487
+ return apiBasePath + "/" + blueprintSlug + "/" + group + "/" + actionName;
488
+ }
489
+ function generateActionId(group, actionName) {
490
+ return group + ":" + actionName;
491
+ }
492
+ function extractFunctionBodies(source) {
493
+ const result = /* @__PURE__ */ new Map();
494
+ const funcHeaderRegex = /export\s+(async\s+)?function\s+(\w+)\s*\(/g;
495
+ let headerMatch;
496
+ while ((headerMatch = funcHeaderRegex.exec(source)) !== null) {
497
+ const funcName = headerMatch[2];
498
+ const startIdx = headerMatch.index;
499
+ let braceStart = source.indexOf("{", headerMatch.index + headerMatch[0].length);
500
+ if (braceStart === -1) continue;
501
+ const signatureSlice = source.slice(headerMatch.index + headerMatch[0].length, braceStart);
502
+ const returnTypeMatch = signatureSlice.match(/\)\s*:\s*([^{]+)/);
503
+ const returnType = returnTypeMatch ? returnTypeMatch[1].trim() : void 0;
504
+ let depth = 0;
505
+ let endIdx = braceStart;
506
+ for (let i = braceStart; i < source.length; i++) {
507
+ if (source[i] === "{") depth++;
508
+ else if (source[i] === "}") {
509
+ depth--;
510
+ if (depth === 0) {
511
+ endIdx = i + 1;
512
+ break;
513
+ }
514
+ }
515
+ }
516
+ const fullText = source.slice(startIdx, endIdx);
517
+ result.set(funcName, { body: fullText, returnType });
518
+ }
519
+ return result;
520
+ }
521
+ function extractActionsViaRegex(source) {
522
+ const actions = [];
523
+ const funcRegex = /(?:\/\*\*([\s\S]*?)\*\/\s*)?export\s+(async\s+)?function\s+(\w+)\s*\(([^)]*)\)/g;
524
+ let match;
525
+ while ((match = funcRegex.exec(source)) !== null) {
526
+ const jsdoc = match[1];
527
+ const isAsync = !!match[2];
528
+ const name = match[3];
529
+ const paramsStr = match[4];
530
+ const params = paramsStr.split(",").map((p) => p.trim().split(":")[0].trim().split("?")[0].trim()).filter(Boolean);
531
+ let description;
532
+ if (jsdoc) {
533
+ const lines = jsdoc.split("\n");
534
+ for (const line of lines) {
535
+ const trimmed = line.replace(/^\s*\*\s?/, "").trim();
536
+ if (trimmed && !trimmed.startsWith("@")) {
537
+ description = trimmed;
538
+ break;
539
+ }
540
+ }
541
+ }
542
+ actions.push({ name, async: isAsync, params, description });
543
+ }
544
+ const arrowRegex = /export\s+const\s+(\w+)\s*=\s*(async\s+)?\([^)]*\)/g;
545
+ while ((match = arrowRegex.exec(source)) !== null) {
546
+ const name = match[1];
547
+ const isAsync = !!match[2];
548
+ const arrowParamMatch = source.slice(match.index).match(/\(([^)]*)\)/);
549
+ const params = arrowParamMatch ? arrowParamMatch[1].split(",").map((p) => p.trim().split(":")[0].trim()).filter(Boolean) : [];
550
+ actions.push({ name, async: isAsync, params });
551
+ }
552
+ return actions;
553
+ }
554
+ function compileActions(files, options = {}) {
555
+ const mode = options.mode || "infer";
556
+ const blueprintSlug = options.blueprintSlug || "app";
557
+ const apiBasePath = options.apiBasePath || "/api/v1/actions";
558
+ const allActions = [];
559
+ const byFile = /* @__PURE__ */ new Map();
560
+ const byGroup = /* @__PURE__ */ new Map();
561
+ const errors = [];
562
+ for (const [filename, source] of Object.entries(files)) {
563
+ const group = extractActionGroup(filename);
564
+ const fileActions = [];
565
+ const bodies = extractFunctionBodies(source);
566
+ try {
567
+ const parserPlugins = filename.endsWith(".tsx") ? ["typescript", "jsx"] : ["typescript"];
568
+ const babelResult = transformSync2(source, {
569
+ filename,
570
+ plugins: [[babelPlugin, { mode }]],
571
+ parserOpts: { plugins: parserPlugins, attachComment: true }
572
+ });
573
+ const ir = babelResult?.metadata?.mindmatrixIR ?? null;
574
+ const meta = ir?.metadata;
575
+ const babelActions = meta?.serverActions;
576
+ if (babelActions && babelActions.length > 0) {
577
+ for (const action of babelActions) {
578
+ const bodyInfo = bodies.get(action.name);
579
+ const reg = {
580
+ name: action.name,
581
+ sourceFile: filename,
582
+ async: action.async,
583
+ params: action.params,
584
+ contextType: action.contextType,
585
+ description: action.description,
586
+ body: bodyInfo?.body,
587
+ returnType: bodyInfo?.returnType,
588
+ endpoint: generateEndpoint(blueprintSlug, group, action.name, apiBasePath),
589
+ group,
590
+ actionId: generateActionId(group, action.name)
591
+ };
592
+ fileActions.push(reg);
593
+ }
594
+ } else {
595
+ const regexActions = extractActionsViaRegex(source);
596
+ for (const action of regexActions) {
597
+ const bodyInfo = bodies.get(action.name);
598
+ const reg = {
599
+ name: action.name,
600
+ sourceFile: filename,
601
+ async: action.async,
602
+ params: action.params,
603
+ description: action.description,
604
+ body: bodyInfo?.body,
605
+ returnType: bodyInfo?.returnType,
606
+ endpoint: generateEndpoint(blueprintSlug, group, action.name, apiBasePath),
607
+ group,
608
+ actionId: generateActionId(group, action.name)
609
+ };
610
+ fileActions.push(reg);
611
+ }
612
+ }
613
+ } catch (err) {
614
+ errors.push({ file: filename, message: err.message });
615
+ const regexActions = extractActionsViaRegex(source);
616
+ for (const action of regexActions) {
617
+ const bodyInfo = bodies.get(action.name);
618
+ const reg = {
619
+ name: action.name,
620
+ sourceFile: filename,
621
+ async: action.async,
622
+ params: action.params,
623
+ description: action.description,
624
+ body: bodyInfo?.body,
625
+ returnType: bodyInfo?.returnType,
626
+ endpoint: generateEndpoint(blueprintSlug, group, action.name, apiBasePath),
627
+ group,
628
+ actionId: generateActionId(group, action.name)
629
+ };
630
+ fileActions.push(reg);
631
+ }
632
+ }
633
+ byFile.set(filename, fileActions);
634
+ if (!byGroup.has(group)) byGroup.set(group, []);
635
+ byGroup.get(group).push(...fileActions);
636
+ allActions.push(...fileActions);
637
+ }
638
+ return { actions: allActions, byFile, byGroup, errors };
639
+ }
640
+ function resolveActionReferences(actionNames, registrations) {
641
+ const result = /* @__PURE__ */ new Map();
642
+ const byName = new Map(registrations.map((r) => [r.name, r]));
643
+ for (const name of actionNames) {
644
+ if (byName.has(name)) {
645
+ result.set(name, byName.get(name));
646
+ continue;
647
+ }
648
+ const colonIdx = name.indexOf(":");
649
+ if (colonIdx > 0) {
650
+ const actionName = name.slice(colonIdx + 1);
651
+ if (byName.has(actionName)) {
652
+ result.set(name, byName.get(actionName));
653
+ continue;
654
+ }
655
+ }
656
+ result.set(name, null);
657
+ }
658
+ return result;
659
+ }
660
+
661
+ // src/babel/extractors/action-extractor.ts
662
+ init_ts_to_expression();
663
+ import { parse } from "@babel/parser";
664
+ import * as t from "@babel/types";
665
+ function extractAction(source, filename) {
666
+ let ast;
667
+ try {
668
+ ast = parse(source, {
669
+ sourceType: "module",
670
+ plugins: ["typescript"],
671
+ strictMode: false
672
+ });
673
+ } catch {
674
+ return null;
675
+ }
676
+ const result = findDefaultExportedFunction(ast);
677
+ if (!result) return null;
678
+ const { name, params, body, returnTypeAnnotation, isAsync } = result;
679
+ const slug = toKebabCase(name);
680
+ const warnings = [];
681
+ const fields = params.map((p) => paramToField(p));
682
+ const parameterMap = /* @__PURE__ */ new Map();
683
+ for (const p of params) {
684
+ const snakeName = toSnakeCase(p.name);
685
+ if (snakeName !== p.name) {
686
+ parameterMap.set(p.name, snakeName);
687
+ }
688
+ }
689
+ const humanName = name.replace(/([A-Z])/g, " $1").replace(/^./, (s) => s.toUpperCase()).trim();
690
+ const metadata = {
691
+ source_file: filename,
692
+ source_function: name,
693
+ provenance: {
694
+ frontend: "react-compiler",
695
+ source: "action-extractor",
696
+ compiler_version: "2.0.0"
697
+ }
698
+ };
699
+ if (returnTypeAnnotation) {
700
+ metadata.return_type = returnTypeAnnotation;
701
+ }
702
+ if (isAsync) {
703
+ const segments = splitAtAwaits(body.body);
704
+ const hasAwaits = segments.some((s) => s.kind === "await");
705
+ if (hasAwaits) {
706
+ const rewritten = rewriteAwaitReferences(segments);
707
+ const { states: states2, transitions: transitions2, bodyIsPure } = generateMultiStateIR(rewritten, warnings, parameterMap);
708
+ if (!bodyIsPure) {
709
+ warnings.push(`Async action '${name}' body contains untranslatable JS \u2014 wrapped in $expr() markers`);
710
+ }
711
+ const ir2 = {
712
+ slug,
713
+ name: humanName,
714
+ version: "0.1.0",
715
+ category: "action",
716
+ fields,
717
+ states: states2,
718
+ transitions: transitions2,
719
+ roles: [],
720
+ metadata: { ...metadata, async: true }
721
+ };
722
+ return { ir: ir2, bodyIsPure, warnings };
723
+ }
724
+ }
725
+ const transpileResult = transpileBlock(body, { allMutable: true, parameterMap });
726
+ const bodyExpr = transpileResult.expression;
727
+ if (!transpileResult.pure) {
728
+ warnings.push(`Action '${name}' body contains untranslatable JS \u2014 wrapped in $expr() markers`);
729
+ }
730
+ const states = [
731
+ {
732
+ name: "ready",
733
+ type: "START",
734
+ on_enter: [],
735
+ during: [],
736
+ on_exit: []
737
+ },
738
+ {
739
+ name: "done",
740
+ type: "END",
741
+ on_enter: [],
742
+ during: [],
743
+ on_exit: []
744
+ }
745
+ ];
746
+ const transitions = [
747
+ {
748
+ name: "execute",
749
+ from: ["ready"],
750
+ to: "done",
751
+ actions: [
752
+ {
753
+ id: "body",
754
+ type: "eval",
755
+ mode: "auto",
756
+ config: {
757
+ expression: bodyExpr
758
+ }
759
+ }
760
+ ]
761
+ }
762
+ ];
763
+ const ir = {
764
+ slug,
765
+ name: humanName,
766
+ version: "0.1.0",
767
+ category: "action",
768
+ fields,
769
+ states,
770
+ transitions,
771
+ roles: [],
772
+ metadata
773
+ };
774
+ return { ir, bodyIsPure: transpileResult.pure, warnings };
775
+ }
776
+ function findDefaultExportedFunction(ast) {
777
+ const topLevelVars = /* @__PURE__ */ new Map();
778
+ for (const node of ast.program.body) {
779
+ if (t.isVariableDeclaration(node)) {
780
+ for (const decl of node.declarations) {
781
+ if (t.isIdentifier(decl.id) && decl.init) {
782
+ if (t.isArrowFunctionExpression(decl.init) || t.isFunctionExpression(decl.init)) {
783
+ topLevelVars.set(decl.id.name, decl.init);
784
+ }
785
+ }
786
+ }
787
+ }
788
+ }
789
+ for (const node of ast.program.body) {
790
+ if (t.isExportDefaultDeclaration(node)) {
791
+ const decl = node.declaration;
792
+ if (t.isFunctionDeclaration(decl) && decl.body) {
793
+ const name = decl.id?.name ?? inferNameFromFile(decl) ?? "action";
794
+ return extractFromFunction(name, decl.params, decl.body, decl.returnType, decl.async);
795
+ }
796
+ if (t.isArrowFunctionExpression(decl) || t.isFunctionExpression(decl)) {
797
+ const name = t.isFunctionExpression(decl) && decl.id ? decl.id.name : "action";
798
+ const body = ensureBlock(decl.body);
799
+ if (!body) return null;
800
+ return extractFromFunction(name, decl.params, body, decl.returnType, decl.async);
801
+ }
802
+ if (t.isIdentifier(decl)) {
803
+ const fn = topLevelVars.get(decl.name);
804
+ if (fn) {
805
+ const body = ensureBlock(fn.body);
806
+ if (!body) return null;
807
+ return extractFromFunction(decl.name, fn.params, body, fn.returnType, fn.async);
808
+ }
809
+ }
810
+ }
811
+ }
812
+ return null;
813
+ }
814
+ function extractFromFunction(name, params, body, returnType, isAsync = false) {
815
+ const extracted = params.map((p) => extractParam(p));
816
+ const returnTypeAnnotation = returnType && t.isTSTypeAnnotation(returnType) ? serializeTSType(returnType.typeAnnotation) : void 0;
817
+ return { name, params: extracted, body, returnTypeAnnotation, isAsync };
818
+ }
819
+ function ensureBlock(body) {
820
+ if (t.isBlockStatement(body)) return body;
821
+ const ret = t.returnStatement(body);
822
+ return t.blockStatement([ret]);
823
+ }
824
+ function inferNameFromFile(_node) {
825
+ return null;
826
+ }
827
+ function extractParam(param) {
828
+ if (t.isIdentifier(param)) {
829
+ return {
830
+ name: param.name,
831
+ typeAnnotation: param.typeAnnotation ? param.typeAnnotation.typeAnnotation : null,
832
+ optional: param.optional ?? false
833
+ };
834
+ }
835
+ if (t.isAssignmentPattern(param)) {
836
+ const inner = param.left;
837
+ if (t.isIdentifier(inner)) {
838
+ return {
839
+ name: inner.name,
840
+ typeAnnotation: inner.typeAnnotation ? inner.typeAnnotation.typeAnnotation : null,
841
+ optional: true,
842
+ defaultValue: param.right
843
+ };
844
+ }
845
+ }
846
+ if (t.isRestElement(param)) {
847
+ const arg = param.argument;
848
+ return {
849
+ name: t.isIdentifier(arg) ? arg.name : "rest",
850
+ typeAnnotation: null,
851
+ optional: true
852
+ };
853
+ }
854
+ return { name: "params", typeAnnotation: null, optional: false };
855
+ }
856
+ function paramToField(param) {
857
+ const fieldType = param.typeAnnotation ? tsTypeToFieldType(param.typeAnnotation) : "text";
858
+ const field = {
859
+ name: toSnakeCase(param.name),
860
+ type: fieldType,
861
+ required: !param.optional
862
+ };
863
+ if (param.defaultValue !== void 0) {
864
+ field.default_value = extractLiteralDefault(param.defaultValue);
865
+ }
866
+ return field;
867
+ }
868
+ function extractLiteralDefault(expr) {
869
+ if (!expr) return void 0;
870
+ if (t.isStringLiteral(expr)) return expr.value;
871
+ if (t.isNumericLiteral(expr)) return expr.value;
872
+ if (t.isBooleanLiteral(expr)) return expr.value;
873
+ if (t.isNullLiteral(expr)) return null;
874
+ if (t.isArrayExpression(expr) && expr.elements.length === 0) return [];
875
+ if (t.isObjectExpression(expr) && expr.properties.length === 0) return {};
876
+ return void 0;
877
+ }
878
+ function tsTypeToFieldType(tsType) {
879
+ if (t.isTSStringKeyword(tsType)) return "text";
880
+ if (t.isTSNumberKeyword(tsType)) return "number";
881
+ if (t.isTSBooleanKeyword(tsType)) return "boolean";
882
+ if (t.isTSObjectKeyword(tsType)) return "json";
883
+ if (t.isTSAnyKeyword(tsType) || t.isTSUnknownKeyword(tsType)) return "json";
884
+ if (t.isTSArrayType(tsType)) return "json";
885
+ if (t.isTSUnionType(tsType)) {
886
+ const nonNullable = tsType.types.filter(
887
+ (t2) => !t.isTSNullKeyword(t2) && !t.isTSUndefinedKeyword(t2)
888
+ );
889
+ if (nonNullable.length === 1) {
890
+ return tsTypeToFieldType(nonNullable[0]);
891
+ }
892
+ if (nonNullable.every((t2) => t.isTSLiteralType(t2) && t.isStringLiteral(t2.literal))) {
893
+ return "select";
894
+ }
895
+ return "text";
896
+ }
897
+ if (t.isTSTypeReference(tsType) && t.isIdentifier(tsType.typeName)) {
898
+ const name = tsType.typeName.name;
899
+ if (name === "Date") return "datetime";
900
+ if (name === "string") return "text";
901
+ if (name === "number") return "number";
902
+ if (name === "boolean") return "boolean";
903
+ }
904
+ return "text";
905
+ }
906
+ function serializeTSType(tsType) {
907
+ if (t.isTSStringKeyword(tsType)) return "string";
908
+ if (t.isTSNumberKeyword(tsType)) return "number";
909
+ if (t.isTSBooleanKeyword(tsType)) return "boolean";
910
+ if (t.isTSVoidKeyword(tsType)) return "void";
911
+ if (t.isTSAnyKeyword(tsType)) return "any";
912
+ if (t.isTSTypeReference(tsType) && t.isIdentifier(tsType.typeName)) {
913
+ return tsType.typeName.name;
914
+ }
915
+ if (t.isTSArrayType(tsType)) return `${serializeTSType(tsType.elementType)}[]`;
916
+ if (t.isTSPromiseType(tsType)) {
917
+ return `Promise<${tsType.typeParameter ? serializeTSType(tsType.typeParameter.params[0]) : "unknown"}>`;
918
+ }
919
+ return "unknown";
920
+ }
921
+ function splitAtAwaits(body) {
922
+ const segments = [];
923
+ let current = [];
924
+ let index = 0;
925
+ for (const stmt of body) {
926
+ const awaitInfo = extractAwait(stmt);
927
+ if (!awaitInfo) {
928
+ current.push(stmt);
929
+ continue;
930
+ }
931
+ if (current.length > 0) {
932
+ segments.push({ index: index++, kind: "sync", statements: current });
933
+ current = [];
934
+ }
935
+ segments.push({
936
+ index: index++,
937
+ kind: "await",
938
+ statements: [stmt],
939
+ awaitTarget: awaitInfo.callee,
940
+ awaitArgs: awaitInfo.args,
941
+ resultBinding: awaitInfo.binding
942
+ });
943
+ }
944
+ if (current.length > 0) {
945
+ segments.push({ index: index++, kind: "sync", statements: current });
946
+ }
947
+ return segments;
948
+ }
949
+ function extractAwait(stmt) {
950
+ if (t.isVariableDeclaration(stmt)) {
951
+ const decl = stmt.declarations[0];
952
+ if (decl?.init && t.isAwaitExpression(decl.init)) {
953
+ const arg = decl.init.argument;
954
+ if (t.isCallExpression(arg)) {
955
+ return {
956
+ callee: getCalleeName(arg.callee),
957
+ args: arg.arguments,
958
+ binding: t.isIdentifier(decl.id) ? decl.id.name : void 0
959
+ };
960
+ }
961
+ }
962
+ }
963
+ if (t.isExpressionStatement(stmt) && t.isAwaitExpression(stmt.expression)) {
964
+ const arg = stmt.expression.argument;
965
+ if (t.isCallExpression(arg)) {
966
+ return {
967
+ callee: getCalleeName(arg.callee),
968
+ args: arg.arguments,
969
+ binding: void 0
970
+ };
971
+ }
972
+ }
973
+ if (t.isReturnStatement(stmt) && stmt.argument && t.isAwaitExpression(stmt.argument)) {
974
+ const arg = stmt.argument.argument;
975
+ if (t.isCallExpression(arg)) {
976
+ return {
977
+ callee: getCalleeName(arg.callee),
978
+ args: arg.arguments,
979
+ binding: void 0
980
+ };
981
+ }
982
+ }
983
+ return null;
984
+ }
985
+ function getCalleeName(callee) {
986
+ if (t.isIdentifier(callee)) return callee.name;
987
+ if (t.isMemberExpression(callee) && t.isIdentifier(callee.object) && t.isIdentifier(callee.property)) {
988
+ return `${callee.object.name}_${callee.property.name}`;
989
+ }
990
+ return "unknown_action";
991
+ }
992
+ function rewriteAwaitReferences(segments) {
993
+ const bindings = /* @__PURE__ */ new Map();
994
+ const slugCounts = /* @__PURE__ */ new Map();
995
+ return segments.map((seg) => {
996
+ if (seg.kind === "await" && seg.resultBinding) {
997
+ const slug = toSnakeCase(seg.awaitTarget ?? "unknown");
998
+ const count = (slugCounts.get(slug) ?? 0) + 1;
999
+ slugCounts.set(slug, count);
1000
+ const key = count > 1 ? `${slug}_${count}` : slug;
1001
+ bindings.set(seg.resultBinding, `action_results.${key}`);
1002
+ }
1003
+ if (seg.kind === "sync" && bindings.size > 0) {
1004
+ return {
1005
+ ...seg,
1006
+ statements: seg.statements.map(
1007
+ (stmt) => rewriteIdentifiersInStatement(stmt, bindings)
1008
+ )
1009
+ };
1010
+ }
1011
+ return seg;
1012
+ });
1013
+ }
1014
+ function rewriteIdentifiersInStatement(stmt, _bindings) {
1015
+ return stmt;
1016
+ }
1017
+ function generateMultiStateIR(segments, _warnings, parameterMap) {
1018
+ const states = [];
1019
+ const transitions = [];
1020
+ let bodyIsPure = true;
1021
+ const awaitBindings = /* @__PURE__ */ new Map();
1022
+ const slugCounts = /* @__PURE__ */ new Map();
1023
+ for (const seg of segments) {
1024
+ if (seg.kind === "await" && seg.resultBinding) {
1025
+ const slug = toSnakeCase(seg.awaitTarget ?? "unknown");
1026
+ const count = (slugCounts.get(slug) ?? 0) + 1;
1027
+ slugCounts.set(slug, count);
1028
+ const key = count > 1 ? `${slug}_${count}` : slug;
1029
+ awaitBindings.set(seg.resultBinding, `action_results.${key}`);
1030
+ }
1031
+ }
1032
+ states.push({ name: "ready", type: "START", on_enter: [], during: [], on_exit: [] });
1033
+ const usedStateNames = /* @__PURE__ */ new Set();
1034
+ let prevState = "ready";
1035
+ let transitionCount = 0;
1036
+ let pendingSyncStmts = [];
1037
+ for (const seg of segments) {
1038
+ if (seg.kind === "sync") {
1039
+ pendingSyncStmts.push(...seg.statements);
1040
+ continue;
1041
+ }
1042
+ const targetSlug = toSnakeCase(seg.awaitTarget ?? "unknown");
1043
+ let stateName = `awaiting_${targetSlug}`;
1044
+ if (usedStateNames.has(stateName)) {
1045
+ let suffix = 2;
1046
+ while (usedStateNames.has(`${stateName}_${suffix}`)) suffix++;
1047
+ stateName = `${stateName}_${suffix}`;
1048
+ }
1049
+ usedStateNames.add(stateName);
1050
+ states.push({ name: stateName, type: "REGULAR", on_enter: [], during: [], on_exit: [] });
1051
+ const actions = [];
1052
+ if (pendingSyncStmts.length > 0) {
1053
+ const block = t.blockStatement(pendingSyncStmts);
1054
+ const transpiled = transpileBlock(block, {
1055
+ allMutable: true,
1056
+ derivedVarMap: buildDerivedVarMap(awaitBindings),
1057
+ parameterMap
1058
+ });
1059
+ if (!transpiled.pure) bodyIsPure = false;
1060
+ actions.push({
1061
+ id: `pre_${transitionCount}`,
1062
+ type: "eval",
1063
+ mode: "auto",
1064
+ config: { expression: transpiled.expression }
1065
+ });
1066
+ pendingSyncStmts = [];
1067
+ }
1068
+ const callConfig = {
1069
+ definition_slug: seg.awaitTarget,
1070
+ result_key: targetSlug
1071
+ };
1072
+ if (seg.awaitArgs && seg.awaitArgs.length > 0) {
1073
+ const params = {};
1074
+ for (let i = 0; i < seg.awaitArgs.length; i++) {
1075
+ const arg = seg.awaitArgs[i];
1076
+ if (t.isObjectExpression(arg)) {
1077
+ for (const prop of arg.properties) {
1078
+ if (t.isObjectProperty(prop) && t.isIdentifier(prop.key)) {
1079
+ const { expression: valExpr } = transpileArgExpression(prop.value, awaitBindings);
1080
+ params[prop.key.name] = valExpr;
1081
+ }
1082
+ }
1083
+ } else {
1084
+ const { expression: valExpr } = transpileArgExpression(arg, awaitBindings);
1085
+ params[`arg${i}`] = valExpr;
1086
+ }
1087
+ }
1088
+ if (Object.keys(params).length > 0) {
1089
+ callConfig.params = params;
1090
+ }
1091
+ }
1092
+ actions.push({
1093
+ id: `call_${targetSlug}`,
1094
+ type: "call_workflow",
1095
+ mode: "auto",
1096
+ config: callConfig
1097
+ });
1098
+ const transName = transitionCount === 0 ? "execute" : `on_${getStateSuffix(prevState)}_complete`;
1099
+ transitions.push({
1100
+ name: transName,
1101
+ from: [prevState],
1102
+ to: stateName,
1103
+ actions
1104
+ });
1105
+ prevState = stateName;
1106
+ transitionCount++;
1107
+ }
1108
+ states.push({ name: "done", type: "END", on_enter: [], during: [], on_exit: [] });
1109
+ const finalActions = [];
1110
+ if (pendingSyncStmts.length > 0) {
1111
+ const block = t.blockStatement(pendingSyncStmts);
1112
+ const transpiled = transpileBlock(block, {
1113
+ allMutable: true,
1114
+ derivedVarMap: buildDerivedVarMap(awaitBindings),
1115
+ parameterMap
1116
+ });
1117
+ if (!transpiled.pure) bodyIsPure = false;
1118
+ finalActions.push({
1119
+ id: "post_final",
1120
+ type: "eval",
1121
+ mode: "auto",
1122
+ config: { expression: transpiled.expression }
1123
+ });
1124
+ }
1125
+ const finalTransName = transitionCount === 0 ? "execute" : `on_${getStateSuffix(prevState)}_complete`;
1126
+ transitions.push({
1127
+ name: finalTransName,
1128
+ from: [prevState],
1129
+ to: "done",
1130
+ actions: finalActions
1131
+ });
1132
+ return { states, transitions, bodyIsPure };
1133
+ }
1134
+ function getStateSuffix(stateName) {
1135
+ return stateName.replace(/^awaiting_/, "");
1136
+ }
1137
+ function transpileArgExpression(expr, bindings) {
1138
+ if (t.isIdentifier(expr)) {
1139
+ const replacement = bindings.get(expr.name);
1140
+ if (replacement) return { expression: replacement };
1141
+ return { expression: `state_data.${toSnakeCase(expr.name)}` };
1142
+ }
1143
+ if (t.isMemberExpression(expr) && t.isIdentifier(expr.object)) {
1144
+ const replacement = bindings.get(expr.object.name);
1145
+ if (replacement && t.isIdentifier(expr.property)) {
1146
+ return { expression: `${replacement}.${expr.property.name}` };
1147
+ }
1148
+ }
1149
+ if (t.isStringLiteral(expr)) return { expression: `'${expr.value}'` };
1150
+ if (t.isNumericLiteral(expr)) return { expression: String(expr.value) };
1151
+ if (t.isBooleanLiteral(expr)) return { expression: String(expr.value) };
1152
+ const { transpile } = (init_ts_to_expression(), __toCommonJS(ts_to_expression_exports));
1153
+ return { expression: transpile(expr, { derivedVarMap: buildDerivedVarMap(bindings) }) };
1154
+ }
1155
+ function buildDerivedVarMap(bindings) {
1156
+ const map = /* @__PURE__ */ new Map();
1157
+ for (const [varName, path] of bindings) {
1158
+ map.set(varName, t.identifier(path));
1159
+ }
1160
+ return map;
1161
+ }
1162
+ function toKebabCase(name) {
1163
+ return name.replace(/([A-Z])/g, "-$1").toLowerCase().replace(/^-/, "");
1164
+ }
1165
+ function toSnakeCase(name) {
1166
+ return name.replace(/([A-Z])/g, "_$1").toLowerCase().replace(/^_/, "");
1167
+ }
1168
+
1169
+ // src/incremental-compiler.ts
1170
+ function hashContent(content) {
1171
+ let hash = 5381;
1172
+ for (let i = 0; i < content.length; i++) {
1173
+ hash = (hash << 5) + hash + content.charCodeAt(i);
1174
+ hash |= 0;
1175
+ }
1176
+ return (hash >>> 0).toString(36);
1177
+ }
1178
+ function extractImports(source) {
1179
+ const imports = [];
1180
+ const regex = /import\s+.*?from\s+['"](\.[^'"]+)['"]/g;
1181
+ let match;
1182
+ while ((match = regex.exec(source)) !== null) {
1183
+ imports.push(match[1]);
1184
+ }
1185
+ return imports;
1186
+ }
1187
+ function resolveImport(fromFile, importPath, availableFiles) {
1188
+ const parts = fromFile.split("/");
1189
+ parts.pop();
1190
+ const dir = parts.join("/");
1191
+ const segments = (dir ? dir + "/" + importPath : importPath).split("/");
1192
+ const resolved = [];
1193
+ for (const seg of segments) {
1194
+ if (seg === ".") continue;
1195
+ if (seg === "..") {
1196
+ resolved.pop();
1197
+ continue;
1198
+ }
1199
+ resolved.push(seg);
1200
+ }
1201
+ const basePath = resolved.join("/");
1202
+ const extensions = ["", ".ts", ".tsx", ".js", ".jsx"];
1203
+ for (const ext of extensions) {
1204
+ const candidate = basePath + ext;
1205
+ if (availableFiles.includes(candidate)) {
1206
+ return candidate;
1207
+ }
1208
+ }
1209
+ for (const ext of [".ts", ".tsx", ".js", ".jsx"]) {
1210
+ const candidate = basePath + "/index" + ext;
1211
+ if (availableFiles.includes(candidate)) {
1212
+ return candidate;
1213
+ }
1214
+ }
1215
+ return null;
1216
+ }
1217
+ function buildDependencyGraph(files) {
1218
+ const availableFiles = Object.keys(files);
1219
+ const edges = [];
1220
+ const dependents = /* @__PURE__ */ new Map();
1221
+ const dependencies = /* @__PURE__ */ new Map();
1222
+ for (const filename of availableFiles) {
1223
+ dependents.set(filename, /* @__PURE__ */ new Set());
1224
+ dependencies.set(filename, /* @__PURE__ */ new Set());
1225
+ }
1226
+ for (const [filename, source] of Object.entries(files)) {
1227
+ const imports = extractImports(source);
1228
+ for (const imp of imports) {
1229
+ const resolved = resolveImport(filename, imp, availableFiles);
1230
+ if (resolved && resolved !== filename) {
1231
+ edges.push({ from: filename, to: resolved });
1232
+ dependencies.get(filename).add(resolved);
1233
+ if (!dependents.has(resolved)) dependents.set(resolved, /* @__PURE__ */ new Set());
1234
+ dependents.get(resolved).add(filename);
1235
+ }
1236
+ }
1237
+ }
1238
+ return { edges, dependents, dependencies };
1239
+ }
1240
+ function computeTransitiveDirtySet(directlyChanged, dependents) {
1241
+ const dirty = new Set(directlyChanged);
1242
+ const queue = [...directlyChanged];
1243
+ while (queue.length > 0) {
1244
+ const file = queue.shift();
1245
+ const deps = dependents.get(file);
1246
+ if (!deps) continue;
1247
+ for (const dep of deps) {
1248
+ if (!dirty.has(dep)) {
1249
+ dirty.add(dep);
1250
+ queue.push(dep);
1251
+ }
1252
+ }
1253
+ }
1254
+ return dirty;
1255
+ }
1256
+ function topologicalSort(files, dependencies) {
1257
+ const inDegree = /* @__PURE__ */ new Map();
1258
+ const dependentMap = /* @__PURE__ */ new Map();
1259
+ for (const f of files) {
1260
+ inDegree.set(f, 0);
1261
+ dependentMap.set(f, /* @__PURE__ */ new Set());
1262
+ }
1263
+ for (const f of files) {
1264
+ const deps = dependencies.get(f);
1265
+ if (!deps) continue;
1266
+ for (const dep of deps) {
1267
+ if (files.includes(dep)) {
1268
+ inDegree.set(f, (inDegree.get(f) || 0) + 1);
1269
+ if (!dependentMap.has(dep)) dependentMap.set(dep, /* @__PURE__ */ new Set());
1270
+ dependentMap.get(dep).add(f);
1271
+ }
1272
+ }
1273
+ }
1274
+ const queue = [];
1275
+ for (const [f, degree] of inDegree) {
1276
+ if (degree === 0) queue.push(f);
1277
+ }
1278
+ const order = [];
1279
+ while (queue.length > 0) {
1280
+ const f = queue.shift();
1281
+ order.push(f);
1282
+ for (const dependent of dependentMap.get(f) || []) {
1283
+ const newDegree = (inDegree.get(dependent) || 1) - 1;
1284
+ inDegree.set(dependent, newDegree);
1285
+ if (newDegree === 0) queue.push(dependent);
1286
+ }
1287
+ }
1288
+ for (const f of files) {
1289
+ if (!order.includes(f)) {
1290
+ order.push(f);
1291
+ }
1292
+ }
1293
+ return order;
1294
+ }
1295
+ var IncrementalCache = class {
1296
+ constructor() {
1297
+ this.hashes = /* @__PURE__ */ new Map();
1298
+ this.results = /* @__PURE__ */ new Map();
1299
+ this.lastStats = {
1300
+ totalCached: 0,
1301
+ lastRecompiled: 0,
1302
+ lastCacheHits: 0,
1303
+ lastCompileMs: 0,
1304
+ avgPerFileMs: 0,
1305
+ cacheHitRate: 0
1306
+ };
1307
+ }
1308
+ /**
1309
+ * Determines which files are dirty given current file contents.
1310
+ */
1311
+ detectDirtyFiles(files, dependents) {
1312
+ const currentFiles = new Set(Object.keys(files));
1313
+ const contentChanged = [];
1314
+ const removed = [];
1315
+ const added = [];
1316
+ for (const [filename, source] of Object.entries(files)) {
1317
+ const hash = hashContent(source);
1318
+ const cached = this.hashes.get(filename);
1319
+ if (!cached) {
1320
+ added.push(filename);
1321
+ } else if (cached.hash !== hash) {
1322
+ contentChanged.push(filename);
1323
+ }
1324
+ }
1325
+ for (const cached of this.hashes.keys()) {
1326
+ if (!currentFiles.has(cached)) {
1327
+ removed.push(cached);
1328
+ }
1329
+ }
1330
+ const directlyDirty = /* @__PURE__ */ new Set([...contentChanged, ...added]);
1331
+ let dependencyDirty = [];
1332
+ if (dependents && directlyDirty.size > 0) {
1333
+ const allDirty = computeTransitiveDirtySet(directlyDirty, dependents);
1334
+ dependencyDirty = [...allDirty].filter((f) => !directlyDirty.has(f));
1335
+ }
1336
+ return { contentChanged, dependencyDirty, removed, added };
1337
+ }
1338
+ /**
1339
+ * Updates the cache with a compilation result.
1340
+ */
1341
+ set(filename, source, result) {
1342
+ this.hashes.set(filename, {
1343
+ hash: hashContent(source),
1344
+ compiledAt: Date.now(),
1345
+ size: source.length
1346
+ });
1347
+ this.results.set(filename, result);
1348
+ }
1349
+ /**
1350
+ * Gets a cached result.
1351
+ */
1352
+ get(filename) {
1353
+ return this.results.get(filename);
1354
+ }
1355
+ /**
1356
+ * Checks if a file is in cache and not dirty.
1357
+ */
1358
+ has(filename) {
1359
+ return this.results.has(filename);
1360
+ }
1361
+ /**
1362
+ * Removes a file from cache.
1363
+ */
1364
+ delete(filename) {
1365
+ this.hashes.delete(filename);
1366
+ this.results.delete(filename);
1367
+ }
1368
+ /**
1369
+ * Clears all cached data.
1370
+ */
1371
+ clear() {
1372
+ this.hashes.clear();
1373
+ this.results.clear();
1374
+ }
1375
+ /**
1376
+ * Updates stats after a compilation run.
1377
+ */
1378
+ updateStats(recompiled, cacheHits, compileMs) {
1379
+ const total = recompiled + cacheHits;
1380
+ this.lastStats = {
1381
+ totalCached: this.results.size,
1382
+ lastRecompiled: recompiled,
1383
+ lastCacheHits: cacheHits,
1384
+ lastCompileMs: compileMs,
1385
+ avgPerFileMs: recompiled > 0 ? compileMs / recompiled : 0,
1386
+ cacheHitRate: total > 0 ? cacheHits / total : 0
1387
+ };
1388
+ }
1389
+ /**
1390
+ * Gets compilation statistics.
1391
+ */
1392
+ getStats() {
1393
+ return { ...this.lastStats };
1394
+ }
1395
+ /**
1396
+ * Gets all cached filenames.
1397
+ */
1398
+ getCachedFiles() {
1399
+ return [...this.results.keys()];
1400
+ }
1401
+ /**
1402
+ * Gets all cached results.
1403
+ */
1404
+ getAllResults() {
1405
+ return new Map(this.results);
1406
+ }
1407
+ };
1408
+
1409
+ // src/project-compiler.ts
1410
+ function parseConfig(source) {
1411
+ const config = {};
1412
+ const slugMatch = source.match(/slug:\s*['"]([^'"]+)['"]/);
1413
+ if (slugMatch) config.slug = slugMatch[1];
1414
+ const nameMatch = source.match(/name:\s*['"]([^'"]+)['"]/);
1415
+ if (nameMatch) config.name = nameMatch[1];
1416
+ const versionMatch = source.match(/version:\s*['"]([^'"]+)['"]/);
1417
+ if (versionMatch) config.version = versionMatch[1];
1418
+ const descMatch = source.match(/description:\s*['"]([^'"]+)['"]/);
1419
+ if (descMatch) config.description = descMatch[1];
1420
+ const categoryArrayMatch = source.match(/category:\s*\[([^\]]+)\]/);
1421
+ if (categoryArrayMatch) {
1422
+ const items = categoryArrayMatch[1].match(/['"]([^'"]+)['"]/g);
1423
+ if (items) {
1424
+ config.category = items.map((s) => s.replace(/['"]/g, ""));
1425
+ }
1426
+ } else {
1427
+ const categoryMatch = source.match(/category:\s*['"]([^'"]+)['"]/);
1428
+ if (categoryMatch) config.category = categoryMatch[1];
1429
+ }
1430
+ const modeMatch = source.match(/mode:\s*['"]([^'"]+)['"]/);
1431
+ if (modeMatch && (modeMatch[1] === "strict" || modeMatch[1] === "infer")) {
1432
+ config.mode = modeMatch[1];
1433
+ }
1434
+ return config;
1435
+ }
1436
+ function parseModuleManifest(source) {
1437
+ if (!source.includes("defineBlueprint") && !source.includes("defineModule")) return null;
1438
+ const manifest = {};
1439
+ const stringFields = ["slug", "name", "version", "description", "author", "license", "icon"];
1440
+ for (const field of stringFields) {
1441
+ const match = source.match(new RegExp(`${field}:\\s*['"]([^'"]+)['"]`));
1442
+ if (match) manifest[field] = match[1];
1443
+ }
1444
+ const catArrayMatch = source.match(/category:\s*\[([^\]]+)\]/);
1445
+ if (catArrayMatch) {
1446
+ const items = catArrayMatch[1].match(/['"]([^'"]+)['"]/g);
1447
+ if (items) {
1448
+ manifest.category = items.map((s) => s.replace(/['"]/g, ""));
1449
+ }
1450
+ } else {
1451
+ const catMatch = source.match(/category:\s*['"]([^'"]+)['"]/);
1452
+ if (catMatch) manifest.category = catMatch[1];
1453
+ }
1454
+ const tagsMatch = source.match(/tags:\s*\[([^\]]*)\]/);
1455
+ if (tagsMatch) {
1456
+ manifest.tags = tagsMatch[1].split(",").map((s) => s.trim().replace(/^['"]|['"]$/g, "")).filter(Boolean);
1457
+ }
1458
+ const modelsMatch = source.match(/models:\s*\[([^\]]*)\]/);
1459
+ if (modelsMatch) {
1460
+ manifest.models = modelsMatch[1].split(",").map((s) => s.trim().replace(/^['"]|['"]$/g, "")).filter(Boolean);
1461
+ }
1462
+ const capsMatch = source.match(/capabilities:\s*\[([^\]]*)\]/);
1463
+ if (capsMatch) {
1464
+ manifest.capabilities = capsMatch[1].split(",").map((s) => s.trim().replace(/^['"]|['"]$/g, "")).filter(Boolean);
1465
+ }
1466
+ const routesBlock = extractArrayBlock(source, "routes");
1467
+ if (routesBlock) {
1468
+ const routes = [];
1469
+ const routeRegex = /\{\s*path:\s*['"]([^'"]+)['"][^}]*\}/g;
1470
+ let rm;
1471
+ while ((rm = routeRegex.exec(routesBlock)) !== null) {
1472
+ const entry = { path: rm[1] };
1473
+ const labelMatch = rm[0].match(/label:\s*['"]([^'"]+)['"]/);
1474
+ if (labelMatch) entry.label = labelMatch[1];
1475
+ const groupMatch = rm[0].match(/group:\s*['"]([^'"]+)['"]/);
1476
+ if (groupMatch) entry.group = groupMatch[1];
1477
+ const iconMatch = rm[0].match(/icon:\s*['"]([^'"]+)['"]/);
1478
+ if (iconMatch) entry.icon = iconMatch[1];
1479
+ routes.push(entry);
1480
+ }
1481
+ if (routes.length > 0) manifest.routes = routes;
1482
+ }
1483
+ const actionsBlock = extractArrayBlock(source, "actions");
1484
+ if (actionsBlock) {
1485
+ const actions = [];
1486
+ const actionRegex = /\{\s*id:\s*['"]([^'"]+)['"][^}]*\}/g;
1487
+ let am;
1488
+ while ((am = actionRegex.exec(actionsBlock)) !== null) {
1489
+ const entry = { id: am[1] };
1490
+ const descMatch = am[0].match(/description:\s*['"]([^'"]+)['"]/);
1491
+ if (descMatch) entry.description = descMatch[1];
1492
+ actions.push(entry);
1493
+ }
1494
+ if (actions.length > 0) manifest.actions = actions;
1495
+ }
1496
+ const contribsBlock = extractArrayBlock(source, "contributions");
1497
+ if (contribsBlock) {
1498
+ const contributions = [];
1499
+ const contribRegex = /\{\s*slot:\s*['"]([^'"]+)['"][^}]*\}/g;
1500
+ let cm;
1501
+ while ((cm = contribRegex.exec(contribsBlock)) !== null) {
1502
+ const entry = { slot: cm[1], view: "" };
1503
+ const viewMatch = cm[0].match(/view:\s*['"]([^'"]+)['"]/);
1504
+ if (viewMatch) entry.view = viewMatch[1];
1505
+ const prioMatch = cm[0].match(/priority:\s*(\d+)/);
1506
+ if (prioMatch) entry.priority = parseInt(prioMatch[1], 10);
1507
+ contributions.push(entry);
1508
+ }
1509
+ if (contributions.length > 0) manifest.contributions = contributions;
1510
+ }
1511
+ const configSchemaBlock = extractObjectBlock(source, "configSchema");
1512
+ if (configSchemaBlock) {
1513
+ const configSchema = {};
1514
+ const modelSlugMatch = configSchemaBlock.match(/modelSlug:\s*['"]([^'"]+)['"]/);
1515
+ if (modelSlugMatch) configSchema.modelSlug = modelSlugMatch[1];
1516
+ const defaultsBlock = extractObjectBlock(configSchemaBlock, "defaults");
1517
+ if (defaultsBlock) {
1518
+ const defaults = {};
1519
+ const kvRegex = /(\w+):\s*(?:'([^']*)'|"([^"]*)"|(\d+(?:\.\d+)?)|(\btrue\b|\bfalse\b))/g;
1520
+ let kv;
1521
+ while ((kv = kvRegex.exec(defaultsBlock)) !== null) {
1522
+ const key = kv[1];
1523
+ const val = kv[2] ?? kv[3] ?? (kv[4] !== void 0 ? Number(kv[4]) : kv[5] === "true");
1524
+ defaults[key] = val;
1525
+ }
1526
+ configSchema.defaults = defaults;
1527
+ }
1528
+ manifest.configSchema = configSchema;
1529
+ }
1530
+ const depsBlock = extractArrayBlock(source, "dependencies");
1531
+ if (depsBlock) {
1532
+ const dependencies = [];
1533
+ const depBlocks = extractNestedObjects(depsBlock);
1534
+ for (const block of depBlocks) {
1535
+ const slugMatch = block.match(/slug:\s*['"]([^'"]+)['"]/);
1536
+ if (!slugMatch) continue;
1537
+ const entry = { slug: slugMatch[1] };
1538
+ const verMatch = block.match(/version:\s*['"]([^'"]+)['"]/);
1539
+ if (verMatch) entry.version = verMatch[1];
1540
+ const reqMatch = block.match(/required:\s*(true|false)/);
1541
+ if (reqMatch) entry.required = reqMatch[1] === "true";
1542
+ const prefixMatch = block.match(/prefix:\s*['"]([^'"]+)['"]/);
1543
+ if (prefixMatch) entry.routeConfig = { prefix: prefixMatch[1] };
1544
+ const configBlock = extractObjectBlock(block, "config");
1545
+ if (configBlock) {
1546
+ const config = {};
1547
+ const kvRegex = /(\w+):\s*(?:'([^']*)'|"([^"]*)"|(\d+(?:\.\d+)?)|(\btrue\b|\bfalse\b))/g;
1548
+ let kv;
1549
+ while ((kv = kvRegex.exec(configBlock)) !== null) {
1550
+ const key = kv[1];
1551
+ const val = kv[2] ?? kv[3] ?? (kv[4] !== void 0 ? Number(kv[4]) : kv[5] === "true");
1552
+ config[key] = val;
1553
+ }
1554
+ if (Object.keys(config).length > 0) entry.config = config;
1555
+ }
1556
+ dependencies.push(entry);
1557
+ }
1558
+ if (dependencies.length > 0) manifest.dependencies = dependencies;
1559
+ }
1560
+ const hasRichFields = manifest.routes || manifest.actions || manifest.contributions || manifest.capabilities || manifest.dependencies || manifest.configSchema;
1561
+ return hasRichFields ? manifest : null;
1562
+ }
1563
+ function parseDependencyRouteConfigs(files) {
1564
+ const result = /* @__PURE__ */ new Map();
1565
+ let configSource;
1566
+ for (const [filename, source] of Object.entries(files)) {
1567
+ if (isConfigFile(filename)) {
1568
+ configSource = source;
1569
+ break;
1570
+ }
1571
+ }
1572
+ if (!configSource) return result;
1573
+ const depsBlock = extractArrayBlock(configSource, "dependencies");
1574
+ if (!depsBlock) return result;
1575
+ const depObjects = extractNestedObjects(depsBlock);
1576
+ for (const depSrc of depObjects) {
1577
+ const slugMatch = depSrc.match(/slug:\s*['"]([^'"]+)['"]/);
1578
+ if (!slugMatch) continue;
1579
+ const slug = slugMatch[1];
1580
+ const rcBlock = extractObjectBlock(depSrc, "routeConfig");
1581
+ if (!rcBlock) continue;
1582
+ const entry = {};
1583
+ const prefixMatch = rcBlock.match(/prefix:\s*['"]([^'"]+)['"]/);
1584
+ if (prefixMatch) entry.prefix = prefixMatch[1];
1585
+ const routesBlock = extractObjectBlock(rcBlock, "routes");
1586
+ if (routesBlock) {
1587
+ const overrides = {};
1588
+ const overrideRegex = /['"]([^'"]+)['"]\s*:\s*(?:['"]([^'"]+)['"]|(false))/g;
1589
+ let om;
1590
+ while ((om = overrideRegex.exec(routesBlock)) !== null) {
1591
+ overrides[om[1]] = om[3] === "false" ? false : om[2];
1592
+ }
1593
+ if (Object.keys(overrides).length > 0) entry.routes = overrides;
1594
+ }
1595
+ result.set(slug, entry);
1596
+ }
1597
+ return result;
1598
+ }
1599
+ function extractNestedObjects(source) {
1600
+ const objects = [];
1601
+ let depth = 0;
1602
+ let start = -1;
1603
+ for (let i = 0; i < source.length; i++) {
1604
+ if (source[i] === "{") {
1605
+ if (depth === 0) start = i;
1606
+ depth++;
1607
+ } else if (source[i] === "}") {
1608
+ depth--;
1609
+ if (depth === 0 && start >= 0) {
1610
+ objects.push(source.slice(start, i + 1));
1611
+ start = -1;
1612
+ }
1613
+ }
1614
+ }
1615
+ return objects;
1616
+ }
1617
+ function extractObjectBlock(source, fieldName) {
1618
+ const pattern = new RegExp(`${fieldName}:\\s*\\{`);
1619
+ const match = pattern.exec(source);
1620
+ if (!match) return null;
1621
+ let depth = 1;
1622
+ const startIdx = match.index + match[0].length;
1623
+ for (let i = startIdx; i < source.length; i++) {
1624
+ if (source[i] === "{") depth++;
1625
+ else if (source[i] === "}") {
1626
+ depth--;
1627
+ if (depth === 0) return source.slice(startIdx, i);
1628
+ }
1629
+ }
1630
+ return null;
1631
+ }
1632
+ function extractArrayBlock(source, fieldName) {
1633
+ const startPattern = new RegExp(`${fieldName}:\\s*\\[`);
1634
+ const match = startPattern.exec(source);
1635
+ if (!match) return null;
1636
+ let depth = 1;
1637
+ const startIdx = match.index + match[0].length;
1638
+ for (let i = startIdx; i < source.length; i++) {
1639
+ if (source[i] === "[") depth++;
1640
+ else if (source[i] === "]") {
1641
+ depth--;
1642
+ if (depth === 0) return source.slice(startIdx, i);
1643
+ }
1644
+ }
1645
+ return null;
1646
+ }
1647
+ function isWorkflowFile(filename) {
1648
+ return /\.workflow\.(tsx?|jsx?)$/.test(filename);
1649
+ }
1650
+ function isModelFile(filename) {
1651
+ return /models\/.*\.(ts|tsx)$/.test(filename) && !filename.endsWith(".test.ts");
1652
+ }
1653
+ function isServerActionFile(filename) {
1654
+ return /\.server\.(ts|tsx)$/.test(filename);
1655
+ }
1656
+ function isActionFile(filename) {
1657
+ return /^actions\/.*\.(ts|tsx)$/.test(filename) && !filename.endsWith(".server.ts") && !filename.endsWith(".test.ts") && !filename.endsWith(".test.tsx");
1658
+ }
1659
+ function isComponentFile(filename) {
1660
+ return /components\/.*\.(tsx?|jsx?)$/.test(filename) && !filename.endsWith(".test.ts") && !filename.endsWith(".test.tsx");
1661
+ }
1662
+ function isPageFile2(filename) {
1663
+ return (/pages\/.*\.(tsx?|jsx?)$/.test(filename) || /app\/.*\.(tsx?|jsx?)$/.test(filename)) && !filename.endsWith(".test.ts") && !filename.endsWith(".test.tsx") && !filename.includes("layout");
1664
+ }
1665
+ function isAppDirFile(filename) {
1666
+ return /^app\//.test(filename);
1667
+ }
1668
+ function isConfigFile(filename) {
1669
+ return /mm\.config\.(ts|tsx|js)$/.test(filename);
1670
+ }
1671
+ function isModuleManifestFile(filename) {
1672
+ return /mm\.module\.(ts|tsx|js)$/.test(filename);
1673
+ }
1674
+ function isCompilableFile(filename) {
1675
+ return isWorkflowFile(filename) || isModelFile(filename) || isServerActionFile(filename) || isActionFile(filename) || isPageFile2(filename) || isComponentFile(filename);
1676
+ }
1677
+ function compileFile(filename, source, mode) {
1678
+ const errors = [];
1679
+ try {
1680
+ const parserPlugins = filename.endsWith(".tsx") || filename.endsWith(".jsx") ? ["typescript", "jsx"] : ["typescript"];
1681
+ const result = transformSync3(source, {
1682
+ filename,
1683
+ plugins: [[babelPlugin, { mode }]],
1684
+ parserOpts: { plugins: parserPlugins, attachComment: true }
1685
+ });
1686
+ const ir = result?.metadata?.mindmatrixIR ?? null;
1687
+ if (ir?.metadata) {
1688
+ const meta = ir.metadata;
1689
+ const fileErrors = meta.errors;
1690
+ const fileWarnings = meta.warnings;
1691
+ if (fileErrors) {
1692
+ for (const e of fileErrors) {
1693
+ errors.push({
1694
+ file: filename,
1695
+ message: e.message,
1696
+ line: e.line,
1697
+ column: e.column,
1698
+ endLine: e.line,
1699
+ endColumn: e.column !== void 0 ? e.column + 10 : void 0,
1700
+ severity: "error"
1701
+ });
1702
+ }
1703
+ }
1704
+ if (fileWarnings) {
1705
+ for (const w of fileWarnings) {
1706
+ errors.push({
1707
+ file: filename,
1708
+ message: w.message,
1709
+ line: w.line,
1710
+ column: w.column,
1711
+ endLine: w.line,
1712
+ endColumn: w.column !== void 0 ? w.column + 10 : void 0,
1713
+ severity: "warning"
1714
+ });
1715
+ }
1716
+ }
1717
+ }
1718
+ return { ir, errors };
1719
+ } catch (err) {
1720
+ const errMsg = err.message;
1721
+ const locMatch = errMsg.match(/\((\d+):(\d+)\)/);
1722
+ const line = locMatch ? parseInt(locMatch[1], 10) : void 0;
1723
+ const column = locMatch ? parseInt(locMatch[2], 10) : void 0;
1724
+ errors.push({
1725
+ file: filename,
1726
+ message: "Compilation failed: " + errMsg,
1727
+ line,
1728
+ column,
1729
+ endLine: line,
1730
+ endColumn: column !== void 0 ? column + 1 : void 0,
1731
+ severity: "error"
1732
+ });
1733
+ return { ir: null, errors };
1734
+ }
1735
+ }
1736
+ function deduplicateActions(actions) {
1737
+ const seen = /* @__PURE__ */ new Set();
1738
+ const result = [];
1739
+ for (const action of actions) {
1740
+ const key = JSON.stringify(action);
1741
+ if (!seen.has(key)) {
1742
+ seen.add(key);
1743
+ result.push(action);
1744
+ }
1745
+ }
1746
+ return result;
1747
+ }
1748
+ function mergeIRs(irs, config) {
1749
+ if (irs.length === 0) {
1750
+ return createEmptyIR(config);
1751
+ }
1752
+ if (irs.length === 1) {
1753
+ return applyConfig(irs[0], config);
1754
+ }
1755
+ const fieldMap = /* @__PURE__ */ new Map();
1756
+ for (const ir of irs) {
1757
+ for (const field of ir.fields) {
1758
+ if (!fieldMap.has(field.name)) {
1759
+ fieldMap.set(field.name, field);
1760
+ } else {
1761
+ const existing = fieldMap.get(field.name);
1762
+ if (field.required && !existing.required) {
1763
+ existing.required = true;
1764
+ }
1765
+ if (field.default_value != null && field.default_value !== "" && field.default_value !== 0 && field.default_value !== false) {
1766
+ if (existing.default_value == null || existing.default_value === "" || existing.default_value === 0 || existing.default_value === false) {
1767
+ existing.default_value = field.default_value;
1768
+ }
1769
+ }
1770
+ }
1771
+ }
1772
+ }
1773
+ const stateMap = /* @__PURE__ */ new Map();
1774
+ for (const ir of irs) {
1775
+ for (const state of ir.states) {
1776
+ if (stateMap.has(state.name)) {
1777
+ const existing = stateMap.get(state.name);
1778
+ existing.on_enter = deduplicateActions([...existing.on_enter, ...state.on_enter]);
1779
+ existing.on_exit = deduplicateActions([...existing.on_exit, ...state.on_exit]);
1780
+ existing.during = deduplicateActions([...existing.during, ...state.during]);
1781
+ if (state.on_event) {
1782
+ existing.on_event = [...existing.on_event || [], ...state.on_event];
1783
+ }
1784
+ } else {
1785
+ stateMap.set(state.name, { ...state });
1786
+ }
1787
+ }
1788
+ }
1789
+ const transitionMap = /* @__PURE__ */ new Map();
1790
+ for (const ir of irs) {
1791
+ for (const transition of ir.transitions) {
1792
+ if (!transitionMap.has(transition.name)) {
1793
+ transitionMap.set(transition.name, transition);
1794
+ }
1795
+ }
1796
+ }
1797
+ const events = [];
1798
+ for (const ir of irs) {
1799
+ if (ir.on_event) {
1800
+ events.push(...ir.on_event);
1801
+ }
1802
+ }
1803
+ const viewTrees = [];
1804
+ for (const ir of irs) {
1805
+ const views = ir.views;
1806
+ if (views?.default) {
1807
+ viewTrees.push(views.default);
1808
+ }
1809
+ }
1810
+ const extensions = {};
1811
+ for (const ir of irs) {
1812
+ if (ir.extensions) {
1813
+ for (const [key, islands] of Object.entries(ir.extensions)) {
1814
+ if (!extensions[key]) extensions[key] = [];
1815
+ extensions[key].push(...islands);
1816
+ }
1817
+ }
1818
+ }
1819
+ const metadata = {};
1820
+ for (const ir of irs) {
1821
+ if (ir.metadata) {
1822
+ for (const [key, value] of Object.entries(ir.metadata)) {
1823
+ if (key === "errors" || key === "warnings") continue;
1824
+ metadata[key] = value;
1825
+ }
1826
+ }
1827
+ }
1828
+ const roleMap = /* @__PURE__ */ new Map();
1829
+ for (const ir of irs) {
1830
+ for (const role of ir.roles) {
1831
+ if (!roleMap.has(role.name)) {
1832
+ roleMap.set(role.name, role);
1833
+ }
1834
+ }
1835
+ }
1836
+ const base = irs[0];
1837
+ const merged = {
1838
+ slug: base.slug,
1839
+ name: base.name,
1840
+ version: base.version,
1841
+ description: base.description,
1842
+ category: base.category,
1843
+ fields: Array.from(fieldMap.values()),
1844
+ states: Array.from(stateMap.values()),
1845
+ transitions: Array.from(transitionMap.values()),
1846
+ roles: Array.from(roleMap.values()),
1847
+ tags: base.tags,
1848
+ metadata
1849
+ };
1850
+ if (events.length > 0) {
1851
+ merged.on_event = events;
1852
+ }
1853
+ if (Object.keys(extensions).length > 0) {
1854
+ merged.extensions = extensions;
1855
+ }
1856
+ if (viewTrees.length === 1) {
1857
+ merged.views = { default: viewTrees[0] };
1858
+ } else if (viewTrees.length > 1) {
1859
+ const rootView = {
1860
+ id: "project-root",
1861
+ component: "Stack",
1862
+ children: viewTrees
1863
+ };
1864
+ merged.views = { default: rootView };
1865
+ }
1866
+ return applyConfig(merged, config);
1867
+ }
1868
+ function applyConfig(ir, config) {
1869
+ if (config.slug) ir.slug = config.slug;
1870
+ if (config.name) ir.name = config.name;
1871
+ if (config.version) ir.version = config.version;
1872
+ if (config.description !== void 0) ir.description = config.description;
1873
+ if (config.category) ir.category = config.category;
1874
+ if (!ir.metadata) ir.metadata = {};
1875
+ ir.metadata.stable_id = "def-" + ir.slug;
1876
+ ir.metadata.provenance = {
1877
+ frontend: "react-compiler",
1878
+ source: "project",
1879
+ compiler_version: "2.0.0"
1880
+ };
1881
+ return ir;
1882
+ }
1883
+ function createEmptyIR(config) {
1884
+ return {
1885
+ slug: config.slug || "project",
1886
+ name: config.name || "Project",
1887
+ version: config.version || "0.1.0",
1888
+ description: config.description,
1889
+ category: config.category || "workflow",
1890
+ fields: [],
1891
+ states: [{
1892
+ name: "draft",
1893
+ type: "START",
1894
+ on_enter: [],
1895
+ during: [],
1896
+ on_exit: []
1897
+ }],
1898
+ transitions: [],
1899
+ roles: [],
1900
+ tags: [],
1901
+ metadata: {
1902
+ stable_id: "def-" + (config.slug || "project"),
1903
+ provenance: {
1904
+ frontend: "react-compiler",
1905
+ source: "project",
1906
+ compiler_version: "2.0.0"
1907
+ }
1908
+ }
1909
+ };
1910
+ }
1911
+ function resolveImportLinks(files, compilableFiles) {
1912
+ const links = [];
1913
+ for (const filename of compilableFiles) {
1914
+ const source = files[filename];
1915
+ const importRegex = /import\s+(?:type\s+)?(?:\{([^}]+)\}|(\w+))\s+from\s+['"](\.[^'"]+)['"]/g;
1916
+ let match;
1917
+ while ((match = importRegex.exec(source)) !== null) {
1918
+ const namedImports = match[1];
1919
+ const defaultImport = match[2];
1920
+ const importPath = match[3];
1921
+ const resolved = resolveImport(filename, importPath, Object.keys(files));
1922
+ if (!resolved || resolved === filename) continue;
1923
+ let linkType = "unknown";
1924
+ if (isModelFile(resolved)) {
1925
+ linkType = "data-source";
1926
+ } else if (isServerActionFile(resolved)) {
1927
+ linkType = "action";
1928
+ } else if (/components\//.test(resolved)) {
1929
+ linkType = "component";
1930
+ }
1931
+ const symbols = [];
1932
+ if (namedImports) {
1933
+ symbols.push(...namedImports.split(",").map((s) => s.trim().split(" as ")[0].trim()).filter(Boolean));
1934
+ }
1935
+ if (defaultImport) {
1936
+ symbols.push(defaultImport);
1937
+ }
1938
+ links.push({
1939
+ fromFile: filename,
1940
+ toFile: resolved,
1941
+ linkType,
1942
+ symbols
1943
+ });
1944
+ }
1945
+ }
1946
+ return links;
1947
+ }
1948
+ function resolveCompilationOrder(files, compilableFiles) {
1949
+ const { dependencies } = buildDependencyGraph(files);
1950
+ return topologicalSort(compilableFiles, dependencies);
1951
+ }
1952
+ function extractComponentProps(source) {
1953
+ const match = source.match(/function\s+\w+\s*\(\s*\{([^}]+)\}/);
1954
+ if (!match) return [];
1955
+ return match[1].split(",").map((p) => p.trim().split(/[\s=:]/)[0].replace(/^\.{3}/, "").trim()).filter(Boolean);
1956
+ }
1957
+ function generateModuleTypeStubs(childDefinitions, _modelResults) {
1958
+ const stubs = {};
1959
+ for (const child of childDefinitions) {
1960
+ if (!child.slug) continue;
1961
+ const category = child.category;
1962
+ const isModel = category === "data" || Array.isArray(category) && category.includes("model") || Array.isArray(category) && category.includes("data");
1963
+ if (!isModel || !child.fields || child.fields.length === 0) continue;
1964
+ const interfaceName = slugToInterfaceName(child.slug) + "Fields";
1965
+ const lines = [
1966
+ `// Auto-generated type stub for model: ${child.slug}`,
1967
+ `// Do not edit \u2014 regenerated on each build.`,
1968
+ ``,
1969
+ `export interface ${interfaceName} {`
1970
+ ];
1971
+ for (const field of child.fields) {
1972
+ const tsType = irFieldTypeToTs(field.type || "string");
1973
+ const optional = field.required ? "" : "?";
1974
+ const desc = field.description;
1975
+ if (desc) {
1976
+ lines.push(` /** ${desc} */`);
1977
+ }
1978
+ lines.push(` ${field.name}${optional}: ${tsType};`);
1979
+ }
1980
+ lines.push(`}`);
1981
+ lines.push(``);
1982
+ lines.push(`export declare const ${slugToCamelCase(child.slug)}Slug: '${child.slug}';`);
1983
+ lines.push(``);
1984
+ stubs[`types/modules/${child.slug}.d.ts`] = lines.join("\n");
1985
+ }
1986
+ return stubs;
1987
+ }
1988
+ function slugToInterfaceName(slug) {
1989
+ return slug.split("-").map((s) => s.charAt(0).toUpperCase() + s.slice(1)).join("");
1990
+ }
1991
+ function slugToCamelCase(slug) {
1992
+ const parts = slug.split("-");
1993
+ return parts[0] + parts.slice(1).map((s) => s.charAt(0).toUpperCase() + s.slice(1)).join("");
1994
+ }
1995
+ function irFieldTypeToTs(type) {
1996
+ switch (type) {
1997
+ case "string":
1998
+ case "text":
1999
+ case "email":
2000
+ case "url":
2001
+ case "phone":
2002
+ case "slug":
2003
+ case "color":
2004
+ case "password":
2005
+ return "string";
2006
+ case "number":
2007
+ case "integer":
2008
+ case "float":
2009
+ case "currency":
2010
+ case "percent":
2011
+ return "number";
2012
+ case "boolean":
2013
+ case "toggle":
2014
+ return "boolean";
2015
+ case "date":
2016
+ case "datetime":
2017
+ case "timestamp":
2018
+ return "string";
2019
+ case "json":
2020
+ case "object":
2021
+ return "Record<string, unknown>";
2022
+ case "array":
2023
+ return "unknown[]";
2024
+ case "enum":
2025
+ return "string";
2026
+ case "file":
2027
+ case "image":
2028
+ return "string";
2029
+ default:
2030
+ return "unknown";
2031
+ }
2032
+ }
2033
+ function buildComposedResult(files, fileIRs, config, errors, warnings, options = {}) {
2034
+ const usePhase2 = options.usePhase2Modules !== false;
2035
+ const workflowIRs = [];
2036
+ const modelIRs = [];
2037
+ const actionDefinitionIRs = [];
2038
+ const serverActionEntries = [];
2039
+ let modelResults;
2040
+ let actionResult;
2041
+ let routeResult;
2042
+ const componentDefinitions = {};
2043
+ for (const [filename, ir] of Object.entries(fileIRs)) {
2044
+ if (isWorkflowFile(filename)) {
2045
+ workflowIRs.push(ir);
2046
+ } else if (isModelFile(filename)) {
2047
+ if (!ir.category || ir.category === "workflow") {
2048
+ ir.category = "data";
2049
+ }
2050
+ modelIRs.push(ir);
2051
+ } else if (isServerActionFile(filename)) {
2052
+ const meta = ir.metadata;
2053
+ const actions = meta?.serverActions;
2054
+ if (actions) {
2055
+ for (const action of actions) {
2056
+ serverActionEntries.push({
2057
+ name: action.name,
2058
+ sourceFile: filename,
2059
+ async: action.async,
2060
+ params: action.params,
2061
+ description: action.description
2062
+ });
2063
+ }
2064
+ }
2065
+ } else if (isComponentFile(filename)) {
2066
+ const views = ir.views;
2067
+ const experience = views?.default ?? ir.experience;
2068
+ if (experience) {
2069
+ const baseName = filename.split("/").pop()?.replace(/\.(tsx?|jsx?)$/, "") || "Component";
2070
+ const source = files[filename];
2071
+ const props = source ? extractComponentProps(source) : [];
2072
+ componentDefinitions[baseName] = { experience, props };
2073
+ }
2074
+ }
2075
+ }
2076
+ for (const [filename, source] of Object.entries(files)) {
2077
+ if (isActionFile(filename)) {
2078
+ const result = extractAction(source, filename);
2079
+ if (result) {
2080
+ actionDefinitionIRs.push(result.ir);
2081
+ for (const w of result.warnings) {
2082
+ warnings.push({ file: filename, message: w, severity: "warning" });
2083
+ }
2084
+ }
2085
+ }
2086
+ }
2087
+ if (usePhase2) {
2088
+ const modelFiles = {};
2089
+ for (const [filename, source] of Object.entries(files)) {
2090
+ if (isModelFile(filename)) {
2091
+ modelFiles[filename] = source;
2092
+ }
2093
+ }
2094
+ if (Object.keys(modelFiles).length > 0) {
2095
+ modelResults = compileModels(modelFiles, { mode: options.mode || "infer" });
2096
+ modelIRs.length = 0;
2097
+ for (const [, result] of modelResults) {
2098
+ modelIRs.push(result.ir);
2099
+ }
2100
+ }
2101
+ const actionFiles = {};
2102
+ for (const [filename, source] of Object.entries(files)) {
2103
+ if (isServerActionFile(filename)) {
2104
+ actionFiles[filename] = source;
2105
+ }
2106
+ }
2107
+ if (Object.keys(actionFiles).length > 0) {
2108
+ actionResult = compileActions(actionFiles, {
2109
+ mode: options.mode || "infer",
2110
+ blueprintSlug: config.slug || "app"
2111
+ });
2112
+ serverActionEntries.length = 0;
2113
+ for (const reg of actionResult.actions) {
2114
+ serverActionEntries.push({
2115
+ name: reg.name,
2116
+ sourceFile: reg.sourceFile,
2117
+ async: reg.async,
2118
+ params: reg.params,
2119
+ description: reg.description,
2120
+ body: reg.body,
2121
+ returnType: reg.returnType
2122
+ });
2123
+ }
2124
+ }
2125
+ const appFiles = {};
2126
+ for (const [filename, source] of Object.entries(files)) {
2127
+ if (isAppDirFile(filename) || isPageFile2(filename)) {
2128
+ appFiles[filename] = source;
2129
+ }
2130
+ }
2131
+ if (Object.keys(appFiles).length > 0) {
2132
+ routeResult = extractRoutes(appFiles, {
2133
+ slugPrefix: config.slug || "app"
2134
+ });
2135
+ }
2136
+ }
2137
+ const childDefinitions = [
2138
+ ...workflowIRs,
2139
+ ...modelIRs,
2140
+ ...actionDefinitionIRs
2141
+ ];
2142
+ let routeTable = [];
2143
+ if (routeResult) {
2144
+ routeTable = routeResult.routes.map((r) => ({
2145
+ path: r.path,
2146
+ stateName: r.stateName,
2147
+ sourceFile: r.sourceFile,
2148
+ params: r.params
2149
+ }));
2150
+ childDefinitions.push(routeResult.routerIR);
2151
+ } else {
2152
+ const pageFiles = [];
2153
+ for (const filename of Object.keys(files)) {
2154
+ if (isPageFile2(filename)) {
2155
+ pageFiles.push({
2156
+ relativePath: filename,
2157
+ absolutePath: filename
2158
+ });
2159
+ const routePath = filename.replace(/^pages\//, "").replace(/^app\//, "").replace(/\.(tsx?|jsx?)$/, "").replace(/\/index$/, "").replace(/\/page$/, "");
2160
+ const stateName = pathToStateName(routePath);
2161
+ const urlPattern = pathToUrlPattern(filename, filename.split("/").pop() || "page.tsx");
2162
+ const params = extractParams(filename);
2163
+ routeTable.push({
2164
+ path: urlPattern,
2165
+ stateName,
2166
+ sourceFile: filename,
2167
+ params
2168
+ });
2169
+ }
2170
+ }
2171
+ if (pageFiles.length > 0) {
2172
+ const routerWorkflow = extractRouterWorkflow(pageFiles, {
2173
+ slug: config.slug ? config.slug + "-router" : "app-router",
2174
+ pageFileName: pageFiles[0]?.relativePath.split("/").pop() || "page.tsx"
2175
+ });
2176
+ childDefinitions.push(routerWorkflow);
2177
+ }
2178
+ }
2179
+ if (options.resolvedModules && options.resolvedModules.length > 0) {
2180
+ const depConfigs = parseDependencyRouteConfigs(files);
2181
+ for (const mod of options.resolvedModules) {
2182
+ const depConfig = depConfigs.get(mod.slug);
2183
+ const prefix = depConfig?.prefix ?? `/${mod.slug.replace(/^mod-/, "")}`;
2184
+ const routeOverrides = depConfig?.routes;
2185
+ for (const modRoute of mod.routeTable) {
2186
+ if (routeOverrides) {
2187
+ const override = routeOverrides[modRoute.path];
2188
+ if (override === false) continue;
2189
+ if (typeof override === "string") {
2190
+ const existingPaths2 = new Set(routeTable.map((r) => r.path));
2191
+ if (!existingPaths2.has(override)) {
2192
+ routeTable.push({
2193
+ path: override,
2194
+ stateName: `MOD_${mod.slug.replace(/-/g, "_").toUpperCase()}_${modRoute.stateName}`,
2195
+ sourceFile: modRoute.sourceFile,
2196
+ params: modRoute.params,
2197
+ moduleSlug: mod.slug
2198
+ });
2199
+ }
2200
+ continue;
2201
+ }
2202
+ }
2203
+ const prefixedPath = prefix + (modRoute.path === "/" ? "" : modRoute.path);
2204
+ const existingPaths = new Set(routeTable.map((r) => r.path));
2205
+ if (!existingPaths.has(prefixedPath)) {
2206
+ routeTable.push({
2207
+ path: prefixedPath,
2208
+ stateName: `MOD_${mod.slug.replace(/-/g, "_").toUpperCase()}_${modRoute.stateName}`,
2209
+ sourceFile: modRoute.sourceFile,
2210
+ params: modRoute.params,
2211
+ moduleSlug: mod.slug
2212
+ });
2213
+ }
2214
+ }
2215
+ }
2216
+ }
2217
+ if (options.resolvedModules && options.resolvedModules.length > 0) {
2218
+ for (const mod of options.resolvedModules) {
2219
+ if (mod.serverActions && mod.serverActions.length > 0) {
2220
+ for (const action of mod.serverActions) {
2221
+ const namespacedName = `${mod.slug}:${action.name}`;
2222
+ if (!serverActionEntries.some((a) => a.name === namespacedName)) {
2223
+ serverActionEntries.push({
2224
+ ...action,
2225
+ name: namespacedName,
2226
+ sourceFile: `${mod.slug}/${action.sourceFile}`
2227
+ });
2228
+ }
2229
+ }
2230
+ }
2231
+ }
2232
+ }
2233
+ const allIRs = Object.values(fileIRs);
2234
+ const parentIR = mergeIRs(allIRs, config);
2235
+ if (!parentIR.metadata) parentIR.metadata = {};
2236
+ const parentMeta = parentIR.metadata;
2237
+ parentMeta.childSlugs = childDefinitions.map((c) => c.slug);
2238
+ parentMeta.serverActions = serverActionEntries;
2239
+ if (routeTable.length > 0) {
2240
+ parentMeta.routeTable = routeTable;
2241
+ }
2242
+ parentMeta.composition = {
2243
+ workflowCount: workflowIRs.length,
2244
+ modelCount: modelIRs.length,
2245
+ actionCount: actionDefinitionIRs.length,
2246
+ serverActionCount: serverActionEntries.length,
2247
+ routeCount: routeTable.length,
2248
+ componentCount: Object.keys(componentDefinitions).length,
2249
+ totalFiles: Object.keys(files).length
2250
+ };
2251
+ if (Object.keys(componentDefinitions).length > 0) {
2252
+ parentMeta.componentDefinitions = componentDefinitions;
2253
+ }
2254
+ if (actionResult) {
2255
+ parentMeta.actionEndpoints = actionResult.actions.map((a) => ({
2256
+ actionId: a.actionId,
2257
+ endpoint: a.endpoint,
2258
+ group: a.group
2259
+ }));
2260
+ }
2261
+ for (const [filename, source] of Object.entries(files)) {
2262
+ if (isConfigFile(filename) || isModuleManifestFile(filename)) {
2263
+ const manifest2 = parseModuleManifest(source);
2264
+ if (manifest2) {
2265
+ parentMeta.module_manifest = manifest2;
2266
+ }
2267
+ break;
2268
+ }
2269
+ }
2270
+ const manifest = parentMeta.module_manifest;
2271
+ if (manifest?.dependencies) {
2272
+ parentMeta.module_dependencies = manifest.dependencies;
2273
+ }
2274
+ if (manifest?.contributions) {
2275
+ parentMeta.slot_contributions = manifest.contributions;
2276
+ }
2277
+ if (manifest?.configSchema) {
2278
+ parentMeta.configSchema = manifest.configSchema;
2279
+ }
2280
+ if (manifest?.dependencies) {
2281
+ const depConfigs = {};
2282
+ for (const dep of manifest.dependencies) {
2283
+ if (dep.config) {
2284
+ depConfigs[dep.slug] = dep.config;
2285
+ }
2286
+ }
2287
+ if (Object.keys(depConfigs).length > 0) {
2288
+ parentMeta.module_configs = depConfigs;
2289
+ }
2290
+ }
2291
+ const compilableFiles = Object.keys(files).filter(isCompilableFile);
2292
+ const importLinks = resolveImportLinks(files, compilableFiles);
2293
+ const pageExperiences = {};
2294
+ for (const [filename, ir] of Object.entries(fileIRs)) {
2295
+ if (isPageFile2(filename)) {
2296
+ const views = ir.views;
2297
+ if (views?.default) {
2298
+ pageExperiences[filename] = views.default;
2299
+ }
2300
+ }
2301
+ }
2302
+ const parentViews = parentIR.views;
2303
+ if (Object.keys(pageExperiences).length > 0) {
2304
+ const pageEntries = Object.entries(pageExperiences);
2305
+ const routeNodes = pageEntries.map(([pagePath, pageTree], i) => {
2306
+ const routePath = "/" + pagePath.replace(/^app\//, "").replace(/\.(tsx?|jsx?)$/, "").replace(/\/index$/, "").replace(/\/page$/, "");
2307
+ return {
2308
+ id: `route-${i}`,
2309
+ component: "Route",
2310
+ config: { path: routePath },
2311
+ children: [pageTree]
2312
+ };
2313
+ });
2314
+ const navLinks = pageEntries.map(([pagePath], i) => {
2315
+ const routePath = "/" + pagePath.replace(/^app\//, "").replace(/\.(tsx?|jsx?)$/, "").replace(/\/index$/, "").replace(/\/page$/, "");
2316
+ const segments = routePath.split("/").filter(Boolean);
2317
+ const label = segments[segments.length - 1]?.replace(/-/g, " ").replace(/\b\w/g, (c) => c.toUpperCase()) || "Home";
2318
+ return {
2319
+ id: `nav-link-${i}`,
2320
+ component: "NavLink",
2321
+ config: { to: routePath, label }
2322
+ };
2323
+ });
2324
+ routeNodes.unshift({
2325
+ id: "route-index",
2326
+ component: "Route",
2327
+ config: { path: "/", exact: true },
2328
+ children: [pageEntries[0][1]]
2329
+ });
2330
+ const moduleRoutes = routeTable.filter((r) => r.moduleSlug);
2331
+ for (let mi = 0; mi < moduleRoutes.length; mi++) {
2332
+ const mr = moduleRoutes[mi];
2333
+ routeNodes.push({
2334
+ id: `mod-route-${mi}`,
2335
+ component: "Route",
2336
+ config: { path: mr.path },
2337
+ children: [{
2338
+ id: `mod-route-${mi}-placeholder`,
2339
+ component: "ModuleView",
2340
+ config: { moduleSlug: mr.moduleSlug, sourceFile: mr.sourceFile, path: mr.path }
2341
+ }]
2342
+ });
2343
+ const segments = mr.path.split("/").filter(Boolean);
2344
+ const label = segments[segments.length - 1]?.replace(/-/g, " ").replace(/\b\w/g, (c) => c.toUpperCase()) || mr.moduleSlug;
2345
+ navLinks.push({
2346
+ id: `mod-nav-${mi}`,
2347
+ component: "NavLink",
2348
+ config: { to: mr.path, label, moduleSlug: mr.moduleSlug }
2349
+ });
2350
+ }
2351
+ const composedExperience = {
2352
+ id: "blueprint-root",
2353
+ component: "Stack",
2354
+ className: "h-full flex flex-col",
2355
+ children: [
2356
+ // Nav bar (always visible, not inside Router so it always renders)
2357
+ {
2358
+ id: "nav-bar",
2359
+ component: "Row",
2360
+ config: { gap: 1 },
2361
+ className: "px-4 py-2 border-b border-border bg-background/95 backdrop-blur-sm sticky top-0 z-10 flex-wrap",
2362
+ children: navLinks
2363
+ },
2364
+ // Router with page routes
2365
+ {
2366
+ id: "page-router",
2367
+ component: "Router",
2368
+ className: "flex-1 min-h-0 overflow-y-auto",
2369
+ children: routeNodes.map((r) => ({
2370
+ ...r,
2371
+ children: r.children?.map((child) => ({
2372
+ ...child,
2373
+ id: child.id || r.id + "-content",
2374
+ component: child.component || "Stack",
2375
+ config: { ...child.config, gap: 4, padding: 4 }
2376
+ }))
2377
+ }))
2378
+ }
2379
+ ]
2380
+ };
2381
+ parentIR.experience = composedExperience;
2382
+ const slug = config.slug || parentIR.slug || "blueprint";
2383
+ parentMeta.blueprint_manifest = {
2384
+ routes: [
2385
+ { path: `${slug}/*`, node: slug, label: config.name || parentIR.name || slug }
2386
+ ],
2387
+ config: {
2388
+ full_bleed: true
2389
+ }
2390
+ };
2391
+ } else if (parentViews?.default) {
2392
+ parentIR.experience = parentViews.default;
2393
+ }
2394
+ for (const childDef of childDefinitions) {
2395
+ for (const [filename, ir] of Object.entries(fileIRs)) {
2396
+ if (ir.slug === childDef.slug || isWorkflowFile(filename) && ir.slug === childDef.slug) {
2397
+ const views = ir.views;
2398
+ if (views?.default) {
2399
+ childDef.experience = views.default;
2400
+ }
2401
+ break;
2402
+ }
2403
+ }
2404
+ }
2405
+ const typeStubs = generateModuleTypeStubs(childDefinitions, modelResults);
2406
+ return {
2407
+ ir: parentIR,
2408
+ childDefinitions,
2409
+ fileIRs,
2410
+ routeTable,
2411
+ serverActions: serverActionEntries,
2412
+ errors,
2413
+ warnings,
2414
+ pageExperiences,
2415
+ componentDefinitions,
2416
+ importLinks,
2417
+ modelResults,
2418
+ actionResult,
2419
+ routeResult,
2420
+ typeStubs
2421
+ };
2422
+ }
2423
+ function compileProject(files, options = {}) {
2424
+ const allErrors = [];
2425
+ const allWarnings = [];
2426
+ const fileIRs = {};
2427
+ let config = {};
2428
+ for (const [filename, source] of Object.entries(files)) {
2429
+ if (isConfigFile(filename)) {
2430
+ config = parseConfig(source);
2431
+ break;
2432
+ }
2433
+ }
2434
+ const mode = config.mode || options.mode || "infer";
2435
+ const compilableFiles = Object.keys(files).filter(isCompilableFile);
2436
+ const orderedFiles = resolveCompilationOrder(files, compilableFiles);
2437
+ for (const filename of orderedFiles) {
2438
+ const source = files[filename];
2439
+ const { ir, errors } = compileFile(filename, source, mode);
2440
+ for (const e of errors) {
2441
+ if (e.severity === "error") allErrors.push(e);
2442
+ else allWarnings.push(e);
2443
+ }
2444
+ if (ir) {
2445
+ fileIRs[filename] = ir;
2446
+ }
2447
+ }
2448
+ return buildComposedResult(files, fileIRs, config, allErrors, allWarnings, {
2449
+ usePhase2Modules: options.usePhase2Modules,
2450
+ mode,
2451
+ resolvedModules: options.resolvedModules
2452
+ });
2453
+ }
2454
+ var IncrementalProjectCompiler = class {
2455
+ constructor() {
2456
+ this.lastConfig = {};
2457
+ this.cache = new IncrementalCache();
2458
+ }
2459
+ /**
2460
+ * Compile a project incrementally — only recompiles changed files.
2461
+ */
2462
+ compile(files, options = {}) {
2463
+ const startTime = Date.now();
2464
+ const { dependents } = buildDependencyGraph(files);
2465
+ const dirtySet = this.cache.detectDirtyFiles(files, dependents);
2466
+ const allDirty = /* @__PURE__ */ new Set([
2467
+ ...dirtySet.contentChanged,
2468
+ ...dirtySet.dependencyDirty,
2469
+ ...dirtySet.added
2470
+ ]);
2471
+ for (const removed of dirtySet.removed) {
2472
+ this.cache.delete(removed);
2473
+ }
2474
+ if (allDirty.size === 0 && this.cache.getCachedFiles().length > 0) {
2475
+ this.cache.updateStats(0, this.cache.getCachedFiles().length, Date.now() - startTime);
2476
+ return this.rebuildFromCache(files, options);
2477
+ }
2478
+ for (const [filename, source] of Object.entries(files)) {
2479
+ if (isConfigFile(filename)) {
2480
+ if (allDirty.has(filename)) {
2481
+ this.lastConfig = parseConfig(source);
2482
+ }
2483
+ break;
2484
+ }
2485
+ }
2486
+ const mode = this.lastConfig.mode || options.mode || "infer";
2487
+ const compilableFiles = Object.keys(files).filter(isCompilableFile);
2488
+ let recompiled = 0;
2489
+ let cacheHits = 0;
2490
+ for (const filename of compilableFiles) {
2491
+ if (allDirty.has(filename) || !this.cache.has(filename)) {
2492
+ const { ir, errors } = compileFile(filename, files[filename], mode);
2493
+ if (ir) {
2494
+ this.cache.set(filename, files[filename], { ir, errors });
2495
+ } else {
2496
+ this.cache.delete(filename);
2497
+ }
2498
+ recompiled++;
2499
+ } else {
2500
+ cacheHits++;
2501
+ }
2502
+ }
2503
+ for (const cached of this.cache.getCachedFiles()) {
2504
+ if (!compilableFiles.includes(cached)) {
2505
+ this.cache.delete(cached);
2506
+ }
2507
+ }
2508
+ const fileIRs = {};
2509
+ const allErrors = [];
2510
+ const allWarnings = [];
2511
+ for (const cached of this.cache.getCachedFiles()) {
2512
+ const entry = this.cache.get(cached);
2513
+ if (entry) {
2514
+ fileIRs[cached] = entry.ir;
2515
+ for (const e of entry.errors) {
2516
+ if (e.severity === "error") allErrors.push(e);
2517
+ else allWarnings.push(e);
2518
+ }
2519
+ }
2520
+ }
2521
+ this.cache.updateStats(recompiled, cacheHits, Date.now() - startTime);
2522
+ return buildComposedResult(files, fileIRs, this.lastConfig, allErrors, allWarnings, {
2523
+ usePhase2Modules: options.usePhase2Modules,
2524
+ mode,
2525
+ resolvedModules: options.resolvedModules
2526
+ });
2527
+ }
2528
+ /**
2529
+ * Rebuild result from cache without recompiling anything.
2530
+ */
2531
+ rebuildFromCache(files, options) {
2532
+ let config = this.lastConfig;
2533
+ if (!config.slug) {
2534
+ for (const [filename, source] of Object.entries(files)) {
2535
+ if (isConfigFile(filename)) {
2536
+ config = parseConfig(source);
2537
+ this.lastConfig = config;
2538
+ break;
2539
+ }
2540
+ }
2541
+ }
2542
+ const fileIRs = {};
2543
+ const allErrors = [];
2544
+ const allWarnings = [];
2545
+ for (const cached of this.cache.getCachedFiles()) {
2546
+ const entry = this.cache.get(cached);
2547
+ if (entry) {
2548
+ fileIRs[cached] = entry.ir;
2549
+ for (const e of entry.errors) {
2550
+ if (e.severity === "error") allErrors.push(e);
2551
+ else allWarnings.push(e);
2552
+ }
2553
+ }
2554
+ }
2555
+ const mode = this.lastConfig.mode || options.mode || "infer";
2556
+ return buildComposedResult(files, fileIRs, config, allErrors, allWarnings, {
2557
+ usePhase2Modules: options.usePhase2Modules,
2558
+ mode,
2559
+ resolvedModules: options.resolvedModules
2560
+ });
2561
+ }
2562
+ /** Invalidate a specific file's cache. */
2563
+ invalidate(filename) {
2564
+ this.cache.delete(filename);
2565
+ }
2566
+ /** Invalidate all caches. */
2567
+ invalidateAll() {
2568
+ this.cache.clear();
2569
+ this.lastConfig = {};
2570
+ }
2571
+ /** Check if a file would need recompilation given its current source. */
2572
+ isDirty(filename, source) {
2573
+ hashContent(source);
2574
+ const cached = this.cache.get(filename);
2575
+ return !cached;
2576
+ }
2577
+ /** Get list of files currently in cache. */
2578
+ getCachedFiles() {
2579
+ return this.cache.getCachedFiles();
2580
+ }
2581
+ /** Get compilation statistics. */
2582
+ getStats() {
2583
+ const stats = this.cache.getStats();
2584
+ return {
2585
+ cachedFiles: stats.totalCached,
2586
+ totalHashes: stats.totalCached,
2587
+ ...stats
2588
+ };
2589
+ }
2590
+ };
2591
+
2592
+ export {
2593
+ compileModel,
2594
+ compileModels,
2595
+ extractRoutes,
2596
+ compileActions,
2597
+ resolveActionReferences,
2598
+ hashContent,
2599
+ extractImports,
2600
+ resolveImport,
2601
+ buildDependencyGraph,
2602
+ computeTransitiveDirtySet,
2603
+ topologicalSort,
2604
+ IncrementalCache,
2605
+ compileProject,
2606
+ IncrementalProjectCompiler
2607
+ };