@rotorsoft/act-diagram 0.3.9 → 0.4.0

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 (80) hide show
  1. package/README.md +27 -1
  2. package/dist/.tsbuildinfo +1 -0
  3. package/dist/@types/cli/colors.d.ts +19 -0
  4. package/dist/@types/cli/colors.d.ts.map +1 -0
  5. package/dist/@types/cli/contract-index.d.ts +57 -0
  6. package/dist/@types/cli/contract-index.d.ts.map +1 -0
  7. package/dist/@types/cli/format.d.ts +22 -0
  8. package/dist/@types/cli/format.d.ts.map +1 -0
  9. package/dist/@types/cli/index.d.ts +32 -0
  10. package/dist/@types/cli/index.d.ts.map +1 -0
  11. package/dist/@types/cli/json-schema.d.ts +13 -0
  12. package/dist/@types/cli/json-schema.d.ts.map +1 -0
  13. package/dist/@types/cli/load-project.d.ts +15 -0
  14. package/dist/@types/cli/load-project.d.ts.map +1 -0
  15. package/dist/@types/cli/markdown.d.ts +3 -0
  16. package/dist/@types/cli/markdown.d.ts.map +1 -0
  17. package/dist/@types/cli/open-editor.d.ts +23 -0
  18. package/dist/@types/cli/open-editor.d.ts.map +1 -0
  19. package/dist/@types/cli/repl.d.ts +3 -0
  20. package/dist/@types/cli/repl.d.ts.map +1 -0
  21. package/dist/@types/cli/vim-keys.d.ts +34 -0
  22. package/dist/@types/cli/vim-keys.d.ts.map +1 -0
  23. package/dist/@types/client/components/ActDiagram.d.ts +17 -0
  24. package/dist/@types/client/components/ActDiagram.d.ts.map +1 -0
  25. package/dist/@types/client/components/AiBar.d.ts +11 -0
  26. package/dist/@types/client/components/AiBar.d.ts.map +1 -0
  27. package/dist/@types/client/components/CodePreview.d.ts +10 -0
  28. package/dist/@types/client/components/CodePreview.d.ts.map +1 -0
  29. package/dist/@types/client/components/Diagram.d.ts +11 -0
  30. package/dist/@types/client/components/Diagram.d.ts.map +1 -0
  31. package/dist/@types/client/components/Logo.d.ts +6 -0
  32. package/dist/@types/client/components/Logo.d.ts.map +1 -0
  33. package/dist/@types/client/components/Tooltip.d.ts +16 -0
  34. package/dist/@types/client/components/Tooltip.d.ts.map +1 -0
  35. package/dist/@types/client/data/prompts.d.ts +5 -0
  36. package/dist/@types/client/data/prompts.d.ts.map +1 -0
  37. package/dist/@types/client/data/sample-files.d.ts +4 -0
  38. package/dist/@types/client/data/sample-files.d.ts.map +1 -0
  39. package/dist/@types/client/lib/build-model.d.ts +21 -0
  40. package/dist/@types/client/lib/build-model.d.ts.map +1 -0
  41. package/dist/@types/client/lib/evaluate.d.ts +10 -0
  42. package/dist/@types/client/lib/evaluate.d.ts.map +1 -0
  43. package/dist/@types/client/lib/layout.d.ts +82 -0
  44. package/dist/@types/client/lib/layout.d.ts.map +1 -0
  45. package/dist/@types/client/lib/mock-builders.d.ts +18 -0
  46. package/dist/@types/client/lib/mock-builders.d.ts.map +1 -0
  47. package/dist/@types/client/lib/navigate.d.ts +16 -0
  48. package/dist/@types/client/lib/navigate.d.ts.map +1 -0
  49. package/dist/@types/client/lib/schema-extract.d.ts +37 -0
  50. package/dist/@types/client/lib/schema-extract.d.ts.map +1 -0
  51. package/dist/@types/client/lib/sort.d.ts +4 -0
  52. package/dist/@types/client/lib/sort.d.ts.map +1 -0
  53. package/dist/@types/client/lib/strip-fences.d.ts +11 -0
  54. package/dist/@types/client/lib/strip-fences.d.ts.map +1 -0
  55. package/dist/@types/client/lib/validate.d.ts +4 -0
  56. package/dist/@types/client/lib/validate.d.ts.map +1 -0
  57. package/dist/@types/client/main.d.ts +2 -0
  58. package/dist/@types/client/main.d.ts.map +1 -0
  59. package/dist/@types/client/types/domain-model.d.ts +85 -0
  60. package/dist/@types/client/types/domain-model.d.ts.map +1 -0
  61. package/dist/@types/client/types/file-tab.d.ts +5 -0
  62. package/dist/@types/client/types/file-tab.d.ts.map +1 -0
  63. package/dist/@types/client/types/index.d.ts +5 -0
  64. package/dist/@types/client/types/index.d.ts.map +1 -0
  65. package/dist/@types/client/types/protocol.d.ts +29 -0
  66. package/dist/@types/client/types/protocol.d.ts.map +1 -0
  67. package/dist/@types/index.d.ts +17 -0
  68. package/dist/@types/index.d.ts.map +1 -0
  69. package/dist/@types/server/ai.d.ts +19 -0
  70. package/dist/@types/server/ai.d.ts.map +1 -0
  71. package/dist/@types/server/server.d.ts +2 -0
  72. package/dist/@types/server/server.d.ts.map +1 -0
  73. package/dist/cli/act.js +3324 -0
  74. package/dist/cli/act.js.map +1 -0
  75. package/dist/index.cjs +3268 -0
  76. package/dist/index.cjs.map +1 -0
  77. package/dist/index.js +3235 -0
  78. package/dist/index.js.map +1 -0
  79. package/dist/styles.css +2 -0
  80. package/package.json +17 -7
package/dist/index.cjs ADDED
@@ -0,0 +1,3268 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ ActDiagram: () => ActDiagram,
24
+ AiBar: () => AiBar,
25
+ Diagram: () => Diagram,
26
+ Logo: () => Logo,
27
+ Tooltip: () => Tooltip,
28
+ buildModel: () => buildModel,
29
+ computeLayout: () => computeLayout,
30
+ deriveProjectName: () => deriveProjectName,
31
+ emptyModel: () => emptyModel2,
32
+ extractModel: () => extractModel,
33
+ navigateToCode: () => navigateToCode,
34
+ parseMultiFileResponse: () => parseMultiFileResponse,
35
+ stripFences: () => stripFences,
36
+ topoSort: () => topoSort,
37
+ validate: () => validate
38
+ });
39
+ module.exports = __toCommonJS(index_exports);
40
+
41
+ // src/client/components/ActDiagram.tsx
42
+ var import_react3 = require("react");
43
+
44
+ // src/client/lib/evaluate.ts
45
+ var import_sucrase = require("sucrase");
46
+
47
+ // src/client/lib/schema-extract.ts
48
+ var isWS = (c) => c === " " || c === " " || c === "\n" || c === "\r";
49
+ var isIdent = (c) => !!c && /[\w$]/.test(c);
50
+ function skipTrivia(src, from) {
51
+ let i = from;
52
+ while (i < src.length) {
53
+ const c = src[i];
54
+ if (isWS(c)) {
55
+ i++;
56
+ continue;
57
+ }
58
+ if (c === "/" && src[i + 1] === "/") {
59
+ while (i < src.length && src[i] !== "\n") i++;
60
+ continue;
61
+ }
62
+ if (c === "/" && src[i + 1] === "*") {
63
+ i += 2;
64
+ while (i < src.length && !(src[i - 1] === "*" && src[i] === "/")) i++;
65
+ i++;
66
+ continue;
67
+ }
68
+ break;
69
+ }
70
+ return i;
71
+ }
72
+ function readValue(src, start) {
73
+ let i = start;
74
+ let depth = 0;
75
+ while (i < src.length) {
76
+ const c = src[i];
77
+ if (c === '"' || c === "'") {
78
+ const q = c;
79
+ i++;
80
+ while (i < src.length && src[i] !== q) {
81
+ if (src[i] === "\\") {
82
+ i += 2;
83
+ continue;
84
+ }
85
+ i++;
86
+ }
87
+ i++;
88
+ continue;
89
+ }
90
+ if (c === "`") {
91
+ i++;
92
+ while (i < src.length && src[i] !== "`") {
93
+ if (src[i] === "\\") {
94
+ i += 2;
95
+ continue;
96
+ }
97
+ if (src[i] === "$" && src[i + 1] === "{") {
98
+ let td = 1;
99
+ i += 2;
100
+ while (i < src.length && td > 0) {
101
+ if (src[i] === "{") td++;
102
+ else if (src[i] === "}") td--;
103
+ if (td > 0) i++;
104
+ }
105
+ i++;
106
+ continue;
107
+ }
108
+ i++;
109
+ }
110
+ i++;
111
+ continue;
112
+ }
113
+ if (c === "/" && src[i + 1] === "/") {
114
+ while (i < src.length && src[i] !== "\n") i++;
115
+ continue;
116
+ }
117
+ if (c === "/" && src[i + 1] === "*") {
118
+ i += 2;
119
+ while (i < src.length && !(src[i - 1] === "*" && src[i] === "/")) i++;
120
+ i++;
121
+ continue;
122
+ }
123
+ if (c === "(" || c === "{" || c === "[") {
124
+ depth++;
125
+ i++;
126
+ continue;
127
+ }
128
+ if (c === ")" || c === "]") {
129
+ depth--;
130
+ i++;
131
+ continue;
132
+ }
133
+ if (c === "}") {
134
+ if (depth === 0) return i;
135
+ depth--;
136
+ i++;
137
+ continue;
138
+ }
139
+ if (c === "," && depth === 0) return i;
140
+ i++;
141
+ }
142
+ return i;
143
+ }
144
+ function parseObjectLiteral(src, startBrace) {
145
+ const entries = [];
146
+ let i = startBrace + 1;
147
+ while (i < src.length) {
148
+ i = skipTrivia(src, i);
149
+ if (src[i] === "}") return { entries, endBrace: i };
150
+ let key = "";
151
+ let keyStart = i;
152
+ let keyEnd = i;
153
+ let keyWasIdentifier = false;
154
+ if (src[i] === '"' || src[i] === "'") {
155
+ const q = src[i];
156
+ keyStart = ++i;
157
+ while (i < src.length && src[i] !== q) {
158
+ if (src[i] === "\\") {
159
+ i += 2;
160
+ continue;
161
+ }
162
+ i++;
163
+ }
164
+ key = src.slice(keyStart, i);
165
+ keyEnd = i;
166
+ i++;
167
+ } else if (isIdent(src[i])) {
168
+ keyStart = i;
169
+ while (isIdent(src[i])) i++;
170
+ key = src.slice(keyStart, i);
171
+ keyEnd = i;
172
+ keyWasIdentifier = true;
173
+ } else {
174
+ return null;
175
+ }
176
+ i = skipTrivia(src, i);
177
+ if (src[i] !== ":") {
178
+ if (keyWasIdentifier) {
179
+ entries.push({ key, valueStart: keyStart, valueEnd: keyEnd });
180
+ }
181
+ while (i < src.length && src[i] !== "," && src[i] !== "}") i++;
182
+ if (src[i] === ",") i++;
183
+ continue;
184
+ }
185
+ i++;
186
+ i = skipTrivia(src, i);
187
+ const valueStart = i;
188
+ const valueEnd = readValue(src, i);
189
+ entries.push({ key, valueStart, valueEnd });
190
+ i = valueEnd;
191
+ if (src[i] === ",") i++;
192
+ }
193
+ return null;
194
+ }
195
+ function readTopLevelExpression(src, start) {
196
+ let i = start;
197
+ let depth = 0;
198
+ while (i < src.length) {
199
+ const c = src[i];
200
+ if (c === '"' || c === "'") {
201
+ const q = c;
202
+ i++;
203
+ while (i < src.length && src[i] !== q) {
204
+ if (src[i] === "\\") {
205
+ i += 2;
206
+ continue;
207
+ }
208
+ i++;
209
+ }
210
+ i++;
211
+ continue;
212
+ }
213
+ if (c === "`") {
214
+ i++;
215
+ while (i < src.length && src[i] !== "`") {
216
+ if (src[i] === "\\") {
217
+ i += 2;
218
+ continue;
219
+ }
220
+ if (src[i] === "$" && src[i + 1] === "{") {
221
+ let td = 1;
222
+ i += 2;
223
+ while (i < src.length && td > 0) {
224
+ if (src[i] === "{") td++;
225
+ else if (src[i] === "}") td--;
226
+ if (td > 0) i++;
227
+ }
228
+ i++;
229
+ continue;
230
+ }
231
+ i++;
232
+ }
233
+ i++;
234
+ continue;
235
+ }
236
+ if (c === "/" && src[i + 1] === "/") {
237
+ while (i < src.length && src[i] !== "\n") i++;
238
+ continue;
239
+ }
240
+ if (c === "/" && src[i + 1] === "*") {
241
+ i += 2;
242
+ while (i < src.length && !(src[i - 1] === "*" && src[i] === "/")) i++;
243
+ i++;
244
+ continue;
245
+ }
246
+ if (c === "(" || c === "{" || c === "[") {
247
+ depth++;
248
+ i++;
249
+ continue;
250
+ }
251
+ if (c === ")" || c === "}" || c === "]") {
252
+ depth--;
253
+ i++;
254
+ continue;
255
+ }
256
+ if (c === ";" && depth === 0) return i;
257
+ i++;
258
+ }
259
+ return i;
260
+ }
261
+ function extractIdentifierAssignments(src) {
262
+ const out = /* @__PURE__ */ new Map();
263
+ const re = /(?:^|[^\w$])(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=\n;]{1,256})?=\s*/gm;
264
+ let m;
265
+ while ((m = re.exec(src)) !== null) {
266
+ const ident = m[1];
267
+ if (out.has(ident)) {
268
+ continue;
269
+ }
270
+ const start = m.index + m[0].length;
271
+ const end = readTopLevelExpression(src, start);
272
+ const text = src.slice(start, end).trim();
273
+ if (text) out.set(ident, text);
274
+ re.lastIndex = end;
275
+ }
276
+ return out;
277
+ }
278
+ function findIdentifierObjectLiteral(src, ident) {
279
+ const re = new RegExp(
280
+ `(?:^|[^\\w$])(?:const|let|var)\\s+${ident}\\b\\s*(?::[^=\\n;]+)?=\\s*`,
281
+ "m"
282
+ );
283
+ const m = re.exec(src);
284
+ if (!m) return -1;
285
+ const after = m.index + m[0].length;
286
+ const skipped = skipTrivia(src, after);
287
+ return src[skipped] === "{" ? skipped : -1;
288
+ }
289
+ var BARE_IDENT_RE = /^[A-Za-z_$][\w$]*$/;
290
+ function extractSchemasFromSource(src, eventNames, external) {
291
+ const out = /* @__PURE__ */ new Map();
292
+ if (!src || eventNames.size === 0) return out;
293
+ const localIdents = extractIdentifierAssignments(src);
294
+ const deref = (text) => BARE_IDENT_RE.test(text) ? localIdents.get(text) ?? external?.get(text) ?? text : text;
295
+ const emitsRe = /\.emits\s*\(/g;
296
+ let m;
297
+ while ((m = emitsRe.exec(src)) !== null) {
298
+ let i = skipTrivia(src, emitsRe.lastIndex);
299
+ if (isIdent(src[i])) {
300
+ const start = i;
301
+ while (isIdent(src[i])) i++;
302
+ const ident = src.slice(start, i);
303
+ const objStart = findIdentifierObjectLiteral(src, ident);
304
+ if (objStart < 0) continue;
305
+ i = objStart;
306
+ }
307
+ if (src[i] !== "{") continue;
308
+ const parsed = parseObjectLiteral(src, i);
309
+ if (!parsed) continue;
310
+ for (const e of parsed.entries) {
311
+ if (!eventNames.has(e.key)) continue;
312
+ const raw = src.slice(e.valueStart, e.valueEnd).trim();
313
+ const text = deref(raw);
314
+ if (text) out.set(e.key, text);
315
+ }
316
+ emitsRe.lastIndex = Math.max(emitsRe.lastIndex, parsed.endBrace + 1);
317
+ }
318
+ return out;
319
+ }
320
+
321
+ // src/client/lib/build-model.ts
322
+ var _stateIdx = 0;
323
+ function buildState(model, st) {
324
+ const events = st.events ?? {};
325
+ for (const [name, schema] of Object.entries(events)) {
326
+ if (schema === void 0)
327
+ return { error: `Event "${name}" has undefined schema` };
328
+ }
329
+ const rawActions = st.actions ?? {};
330
+ for (const [name, schema] of Object.entries(rawActions)) {
331
+ if (name.startsWith("__emits_")) continue;
332
+ if (schema === void 0)
333
+ return { error: `Action "${name}" has undefined schema` };
334
+ }
335
+ const domainName = st.name;
336
+ const uniqueKey = `${domainName}:${_stateIdx++}`;
337
+ const eventNodes = [];
338
+ for (const eventName of Object.keys(events)) {
339
+ eventNodes.push({
340
+ name: eventName,
341
+ hasCustomPatch: st.patches?.has(eventName) ?? false,
342
+ // Stash the runtime Zod schema so the JSON Schema exporter can
343
+ // call `z.toJSONSchema(zod)` later without re-running the parser.
344
+ zod: events[eventName]
345
+ });
346
+ }
347
+ const actionNodes = [];
348
+ for (const actionName of Object.keys(rawActions)) {
349
+ if (actionName.startsWith("__emits_")) continue;
350
+ const emits = rawActions[`__emits_${actionName}`] ?? [];
351
+ const invariants = (st.given?.[actionName] ?? []).map(
352
+ (inv) => inv.description ?? ""
353
+ );
354
+ actionNodes.push({ name: actionName, emits, invariants });
355
+ }
356
+ const node = {
357
+ name: domainName,
358
+ varName: uniqueKey,
359
+ events: eventNodes,
360
+ actions: actionNodes,
361
+ file: st._sourceFile
362
+ };
363
+ model.states.push(node);
364
+ st._modelKey = uniqueKey;
365
+ return { key: uniqueKey, node };
366
+ }
367
+ function fixupReactions(reactions, files, sourceFile) {
368
+ const fallbacks = reactions.filter((r) => r.handlerName.startsWith("on "));
369
+ if (fallbacks.length === 0) return;
370
+ const src = sourceFile ? files.find((f) => f.path === sourceFile)?.content : files.map((f) => f.content).join("\n");
371
+ if (!src) return;
372
+ const doRe = /\.on\(\s*["'`](\w+)["'`]\s*\)\s*\.do\(\s*(?:async\s+)?(?:function\s+(\w+)|(?:\w+\.)?(\w+))?/g;
373
+ let dm;
374
+ while ((dm = doRe.exec(src)) !== null) {
375
+ const eventName = dm[1];
376
+ const handlerName = dm[2] || dm[3];
377
+ if (!handlerName) continue;
378
+ const r = fallbacks.find(
379
+ (r2) => r2.event === eventName && r2.handlerName === `on ${eventName}`
380
+ );
381
+ if (r) r.handlerName = handlerName;
382
+ }
383
+ }
384
+ function buildModel(result, files, expectedSlices) {
385
+ const rawStates = result.states.filter((s) => s && s._tag === "State");
386
+ const rawSlices = result.slices.filter((s) => s && s._tag === "Slice");
387
+ const rawProjections = result.projections.filter(
388
+ (p) => p && p._tag === "Projection"
389
+ );
390
+ const rawActs = result.acts.filter((a) => a && a._tag === "Act");
391
+ const stateByRef = /* @__PURE__ */ new Map();
392
+ const model = {
393
+ entries: [],
394
+ states: [],
395
+ slices: [],
396
+ projections: [],
397
+ reactions: []
398
+ };
399
+ for (const st of rawStates) {
400
+ if (stateByRef.has(st)) continue;
401
+ try {
402
+ stateByRef.set(st, buildState(model, st));
403
+ } catch (e) {
404
+ stateByRef.set(st, {
405
+ error: e instanceof Error ? e.message : String(e)
406
+ });
407
+ }
408
+ }
409
+ for (const a of rawActs) {
410
+ for (const st of a.states ?? []) {
411
+ if (!st || st._tag !== "State" || stateByRef.has(st)) continue;
412
+ try {
413
+ stateByRef.set(st, buildState(model, st));
414
+ } catch (e) {
415
+ stateByRef.set(st, {
416
+ error: e instanceof Error ? e.message : String(e)
417
+ });
418
+ }
419
+ }
420
+ }
421
+ const builtSliceNames = /* @__PURE__ */ new Set();
422
+ for (const s of rawSlices) {
423
+ const sliceName = s._varName ?? "slice";
424
+ builtSliceNames.add(sliceName);
425
+ try {
426
+ try {
427
+ fixupReactions(s.reactions, files);
428
+ } catch {
429
+ }
430
+ const sliceStateKeys = [];
431
+ const errors = [];
432
+ for (const st of s.states ?? []) {
433
+ if (!st || typeof st !== "object") {
434
+ const fileErr = [...result.fileErrors.values()][0];
435
+ errors.push(fileErr ?? "Missing state (broken import)");
436
+ continue;
437
+ }
438
+ const built = stateByRef.get(st);
439
+ if (built) {
440
+ if ("error" in built) {
441
+ errors.push(built.error);
442
+ } else {
443
+ sliceStateKeys.push(built.key);
444
+ }
445
+ } else {
446
+ try {
447
+ const result2 = buildState(model, st);
448
+ stateByRef.set(st, result2);
449
+ if ("error" in result2) {
450
+ errors.push(result2.error);
451
+ } else {
452
+ sliceStateKeys.push(result2.key);
453
+ }
454
+ } catch (e) {
455
+ const msg = e instanceof Error ? e.message : String(e);
456
+ stateByRef.set(st, { error: msg });
457
+ errors.push(msg);
458
+ }
459
+ }
460
+ }
461
+ const projNames = [];
462
+ for (const p of s.projections ?? []) {
463
+ if (p && p._tag === "Projection") projNames.push(p.target);
464
+ }
465
+ const sliceFile = s._sourceFile;
466
+ model.slices.push({
467
+ name: sliceName,
468
+ states: sliceStateKeys,
469
+ stateVars: sliceStateKeys,
470
+ projections: projNames,
471
+ reactions: (s.reactions ?? []).map((r) => ({
472
+ ...r,
473
+ file: r.file ?? sliceFile
474
+ })),
475
+ file: sliceFile,
476
+ error: errors.length > 0 ? errors.join("; ") : void 0
477
+ });
478
+ } catch (e) {
479
+ const msg = e instanceof Error ? e.message : String(e);
480
+ model.slices.push({
481
+ name: sliceName,
482
+ states: [],
483
+ stateVars: [],
484
+ projections: [],
485
+ reactions: [],
486
+ error: msg,
487
+ file: s._sourceFile
488
+ });
489
+ }
490
+ }
491
+ for (const [name, filePath] of expectedSlices) {
492
+ if (!builtSliceNames.has(name)) {
493
+ model.slices.push({
494
+ name,
495
+ states: [],
496
+ stateVars: [],
497
+ projections: [],
498
+ reactions: [],
499
+ error: result.fileErrors.get(filePath) ?? result.error ?? "Failed to build slice",
500
+ file: filePath
501
+ });
502
+ }
503
+ }
504
+ const sourceByPath = /* @__PURE__ */ new Map();
505
+ const externalIdents = /* @__PURE__ */ new Map();
506
+ for (const f of files) {
507
+ sourceByPath.set(f.path, f.content);
508
+ for (const [ident, expr] of extractIdentifierAssignments(f.content)) {
509
+ if (!externalIdents.has(ident)) externalIdents.set(ident, expr);
510
+ }
511
+ }
512
+ for (const stNode of model.states) {
513
+ if (!stNode.file) continue;
514
+ const src = sourceByPath.get(stNode.file);
515
+ const names = new Set(stNode.events.map((e) => e.name));
516
+ if (names.size === 0) continue;
517
+ const schemas = extractSchemasFromSource(src, names, externalIdents);
518
+ for (const ev of stNode.events) {
519
+ ev.schema = schemas.get(ev.name);
520
+ }
521
+ }
522
+ for (const p of rawProjections) {
523
+ model.projections.push({
524
+ name: p.target,
525
+ varName: p.target,
526
+ handles: p.handles,
527
+ file: p._sourceFile
528
+ });
529
+ }
530
+ const statesInSlices = new Set(model.slices.flatMap((s) => s.states));
531
+ const globalStateKeys = model.states.filter((s) => !statesInSlices.has(s.varName)).map((s) => s.varName);
532
+ for (const a of rawActs) {
533
+ try {
534
+ fixupReactions(
535
+ a.reactions ?? [],
536
+ files,
537
+ a._sourceFile
538
+ );
539
+ } catch {
540
+ }
541
+ model.orchestrator = {
542
+ slices: model.slices.map((s) => s.name),
543
+ projections: model.projections.map((p) => p.name),
544
+ states: model.states.map((s) => s.name)
545
+ };
546
+ const actFile = a._sourceFile;
547
+ for (const r of a.reactions ?? []) {
548
+ model.reactions.push({ ...r, file: r.file ?? actFile });
549
+ }
550
+ const entryPath = a._sourceFile ?? "app.ts";
551
+ const actSliceNames = new Set(
552
+ (a.slices ?? []).filter((s) => s != null).map((s) => s._varName ?? "").filter(Boolean)
553
+ );
554
+ for (const sl of model.slices) {
555
+ if (sl.error && !actSliceNames.has(sl.name)) {
556
+ const actSrc = files.find((f) => f.path === entryPath)?.content ?? "";
557
+ if (actSrc.includes(sl.name)) {
558
+ actSliceNames.add(sl.name);
559
+ }
560
+ }
561
+ }
562
+ const entrySlices = model.slices.filter((s) => actSliceNames.has(s.name));
563
+ const sliceStateKeys = new Set(entrySlices.flatMap((s) => s.states));
564
+ const actStateKeys = /* @__PURE__ */ new Set();
565
+ for (const s of a.states ?? []) {
566
+ try {
567
+ if (s && s._tag === "State") {
568
+ actStateKeys.add(s._modelKey ?? s.name);
569
+ }
570
+ } catch {
571
+ }
572
+ }
573
+ const allStateKeys = /* @__PURE__ */ new Set([...actStateKeys, ...sliceStateKeys]);
574
+ const actProjNames = new Set(
575
+ (a.projections ?? []).filter((p) => p && p._tag === "Projection").map((p) => p.target)
576
+ );
577
+ for (const sl of entrySlices) {
578
+ for (const pn of sl.projections) actProjNames.add(pn);
579
+ }
580
+ model.entries.push({
581
+ path: entryPath,
582
+ states: model.states.filter((s) => allStateKeys.has(s.varName)),
583
+ slices: entrySlices,
584
+ projections: model.projections.filter((p) => actProjNames.has(p.name)),
585
+ reactions: a.reactions ?? []
586
+ });
587
+ }
588
+ if (globalStateKeys.length > 0 || model.reactions.length > 0) {
589
+ model.slices.push({
590
+ name: "global",
591
+ states: globalStateKeys,
592
+ stateVars: globalStateKeys,
593
+ projections: model.projections.map((p) => p.name),
594
+ reactions: model.reactions
595
+ });
596
+ }
597
+ if (model.entries.length === 0 && (model.states.length > 0 || model.slices.length > 0)) {
598
+ model.entries.push({
599
+ path: "app",
600
+ states: model.states,
601
+ slices: model.slices,
602
+ projections: model.projections,
603
+ reactions: model.reactions
604
+ });
605
+ }
606
+ if (result.error && model.states.length === 0 && model.slices.length === 0) {
607
+ return { model, error: result.error };
608
+ }
609
+ return { model };
610
+ }
611
+
612
+ // src/client/lib/mock-builders.ts
613
+ var import_zod = require("zod");
614
+ function proxyTarget() {
615
+ }
616
+ function attachEmit(info, actionName, handler) {
617
+ const emits = [];
618
+ if (typeof handler === "string") {
619
+ emits.push(handler);
620
+ } else if (typeof handler === "function") {
621
+ const src = String(handler);
622
+ for (const eventName of Object.keys(info.events)) {
623
+ if (src.includes(`"${eventName}"`) || src.includes(`'${eventName}'`) || src.includes(`\`${eventName}\``)) {
624
+ emits.push(eventName);
625
+ }
626
+ }
627
+ if (emits.length === 0) {
628
+ try {
629
+ const deepProxy = new Proxy(
630
+ {},
631
+ {
632
+ get: () => deepProxy,
633
+ has: () => true
634
+ }
635
+ );
636
+ const proxyFn = new Proxy(proxyTarget, {
637
+ get: () => deepProxy,
638
+ apply: () => deepProxy
639
+ });
640
+ const dummyArg = new Proxy(
641
+ {},
642
+ {
643
+ get: (_t, prop) => {
644
+ if (typeof prop === "string") return proxyFn;
645
+ return void 0;
646
+ }
647
+ }
648
+ );
649
+ const result = handler(dummyArg, dummyArg, dummyArg);
650
+ if (Array.isArray(result) && typeof result[0] === "string") {
651
+ emits.push(result[0]);
652
+ }
653
+ } catch {
654
+ }
655
+ }
656
+ }
657
+ info.actions[`__emits_${actionName}`] = emits;
658
+ }
659
+ function mockState(entry, onBuild) {
660
+ const name = Object.keys(entry)[0];
661
+ const info = {
662
+ name,
663
+ events: {},
664
+ actions: {},
665
+ given: {},
666
+ patches: /* @__PURE__ */ new Set(),
667
+ _tag: "State"
668
+ };
669
+ const actionBuilder = (_currentAction) => ({
670
+ on(actionEntry) {
671
+ const actionName = Object.keys(actionEntry)[0];
672
+ info.actions[actionName] = actionEntry[actionName];
673
+ return {
674
+ given(rules) {
675
+ if (rules) info.given[actionName] = rules;
676
+ return {
677
+ emit(handler) {
678
+ attachEmit(info, actionName, handler);
679
+ return actionBuilder(actionName);
680
+ }
681
+ };
682
+ },
683
+ emit(handler) {
684
+ attachEmit(info, actionName, handler);
685
+ return actionBuilder(actionName);
686
+ }
687
+ };
688
+ },
689
+ snap: () => actionBuilder(_currentAction),
690
+ build: () => {
691
+ onBuild?.(info);
692
+ return info;
693
+ }
694
+ });
695
+ return {
696
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
697
+ init: (_initFn) => ({
698
+ emits(events) {
699
+ info.events = events ?? {};
700
+ return {
701
+ ...actionBuilder(),
702
+ patch(patches) {
703
+ if (patches)
704
+ for (const k of Object.keys(patches)) info.patches.add(k);
705
+ return actionBuilder();
706
+ }
707
+ };
708
+ }
709
+ })
710
+ };
711
+ }
712
+ function captureDispatches(handler) {
713
+ const dispatches = [];
714
+ if (typeof handler !== "function") return dispatches;
715
+ try {
716
+ const safeProxy = () => new Proxy({}, { get: () => "" });
717
+ const mockApp = {
718
+ do: (actionName) => {
719
+ if (typeof actionName === "string" && !dispatches.includes(actionName))
720
+ dispatches.push(actionName);
721
+ return Promise.resolve([]);
722
+ },
723
+ load: () => Promise.resolve({ state: safeProxy(), version: 0 }),
724
+ query: () => Promise.resolve({ count: 0 }),
725
+ query_array: () => Promise.resolve([])
726
+ };
727
+ const mockEvent = new Proxy({}, {
728
+ get: (_, prop) => prop === "stream" ? "mock" : prop === "data" ? new Proxy({}, { get: () => "" }) : ""
729
+ });
730
+ const result = handler(mockEvent, "mock", mockApp);
731
+ if (result && typeof result.catch === "function") {
732
+ result.catch(() => {
733
+ });
734
+ }
735
+ } catch {
736
+ }
737
+ if (dispatches.length === 0) {
738
+ const src = String(handler);
739
+ const re = /\.do\(\s*["'](\w+)["']/g;
740
+ let m;
741
+ while ((m = re.exec(src)) !== null) {
742
+ if (!dispatches.includes(m[1])) dispatches.push(m[1]);
743
+ }
744
+ }
745
+ return dispatches;
746
+ }
747
+ function mockSlice(onBuild) {
748
+ const info = {
749
+ _tag: "Slice",
750
+ states: [],
751
+ projections: [],
752
+ reactions: []
753
+ };
754
+ const builder = {
755
+ withState(s) {
756
+ info.states.push(s ?? null);
757
+ return builder;
758
+ },
759
+ withProjection(p) {
760
+ if (p) info.projections.push(p);
761
+ return builder;
762
+ },
763
+ on(eventName) {
764
+ return {
765
+ do(handler) {
766
+ const dispatches = captureDispatches(handler);
767
+ const reaction = {
768
+ event: eventName,
769
+ handlerName: typeof handler?.name === "string" && handler.name || `on ${eventName}`,
770
+ dispatches
771
+ };
772
+ info.reactions.push(reaction);
773
+ return {
774
+ ...builder,
775
+ to() {
776
+ return builder;
777
+ }
778
+ };
779
+ }
780
+ };
781
+ },
782
+ build: () => {
783
+ onBuild?.(info);
784
+ return info;
785
+ }
786
+ };
787
+ return builder;
788
+ }
789
+ function mockProjection(target, onBuild) {
790
+ const info = {
791
+ _tag: "Projection",
792
+ target: target || "projection",
793
+ handles: []
794
+ };
795
+ const builder = {
796
+ on(eventEntry) {
797
+ const eventName = Object.keys(eventEntry)[0];
798
+ info.handles.push(eventName);
799
+ return {
800
+ do() {
801
+ return {
802
+ ...builder,
803
+ to(resolver) {
804
+ if (typeof resolver === "string") info.target = resolver;
805
+ return builder;
806
+ }
807
+ };
808
+ }
809
+ };
810
+ },
811
+ build: () => {
812
+ onBuild?.(info);
813
+ return info;
814
+ }
815
+ };
816
+ return builder;
817
+ }
818
+ function mockAct(onBuild) {
819
+ const info = {
820
+ _tag: "Act",
821
+ states: [],
822
+ slices: [],
823
+ projections: [],
824
+ reactions: []
825
+ };
826
+ const builder = {
827
+ withState(s) {
828
+ info.states.push(s ?? null);
829
+ return builder;
830
+ },
831
+ withSlice(s) {
832
+ info.slices.push(s ?? null);
833
+ return builder;
834
+ },
835
+ withProjection(p) {
836
+ if (p) info.projections.push(p);
837
+ return builder;
838
+ },
839
+ withActor: () => builder,
840
+ on(eventName) {
841
+ return {
842
+ do(handler) {
843
+ const dispatches = captureDispatches(handler);
844
+ const reaction = {
845
+ event: eventName,
846
+ handlerName: typeof handler?.name === "string" && handler.name || `on ${eventName}`,
847
+ dispatches
848
+ };
849
+ info.reactions.push(reaction);
850
+ return {
851
+ ...builder,
852
+ to() {
853
+ return builder;
854
+ }
855
+ };
856
+ }
857
+ };
858
+ },
859
+ build: () => {
860
+ const noop = () => actStub;
861
+ const actStub = {
862
+ ...info,
863
+ on: () => actStub,
864
+ do: () => Promise.resolve([]),
865
+ load: () => Promise.resolve({}),
866
+ drain: () => Promise.resolve(),
867
+ correlate: () => Promise.resolve({ subscribed: 0, last_id: 0 }),
868
+ settle: noop,
869
+ start_correlations: noop,
870
+ query_array: () => Promise.resolve([])
871
+ };
872
+ onBuild?.(actStub);
873
+ return actStub;
874
+ }
875
+ };
876
+ return builder;
877
+ }
878
+ var InvariantError = class extends Error {
879
+ constructor(message) {
880
+ super(message);
881
+ this.name = "InvariantError";
882
+ }
883
+ };
884
+ var cryptoMock = { randomUUID: () => "mock-uuid" };
885
+ var MODULES = {
886
+ "@rotorsoft/act": {
887
+ state: mockState,
888
+ slice: mockSlice,
889
+ projection: mockProjection,
890
+ act: mockAct,
891
+ store: () => ({
892
+ seed: () => Promise.resolve(),
893
+ drop: () => Promise.resolve(),
894
+ commit: () => Promise.resolve([]),
895
+ query: () => Promise.resolve(0),
896
+ dispose: () => Promise.resolve()
897
+ }),
898
+ dispose: () => () => Promise.resolve(),
899
+ ZodEmpty: import_zod.z.record(import_zod.z.string(), import_zod.z.never()),
900
+ InvariantError
901
+ },
902
+ zod: { z: import_zod.z, ...import_zod.z },
903
+ crypto: cryptoMock,
904
+ "node:crypto": cryptoMock
905
+ };
906
+ function unknownModuleProxy() {
907
+ const handler = {
908
+ get(_target, prop) {
909
+ if (prop === Symbol.toPrimitive) return () => "";
910
+ if (prop === "default") return proxy;
911
+ return proxy;
912
+ },
913
+ apply() {
914
+ return proxy;
915
+ },
916
+ construct() {
917
+ return proxy;
918
+ },
919
+ has() {
920
+ return true;
921
+ }
922
+ };
923
+ const proxy = new Proxy(proxyTarget, handler);
924
+ return proxy;
925
+ }
926
+
927
+ // src/client/lib/sort.ts
928
+ function topoSort(tsFiles) {
929
+ if (tsFiles.length <= 1) return tsFiles;
930
+ const strip = (p) => p.replace(/\.tsx?$/, "");
931
+ const byKey = /* @__PURE__ */ new Map();
932
+ for (const f of tsFiles) {
933
+ byKey.set(strip(f.path), f);
934
+ }
935
+ const deps = /* @__PURE__ */ new Map();
936
+ for (const f of tsFiles) {
937
+ const key = strip(f.path);
938
+ const fileDeps = /* @__PURE__ */ new Set();
939
+ deps.set(key, fileDeps);
940
+ const fromRe = /from\s+["']([^"']+)["']/g;
941
+ let m;
942
+ while ((m = fromRe.exec(f.content)) !== null) {
943
+ const imp = m[1];
944
+ const resolved = resolve(imp, key, byKey);
945
+ if (resolved && byKey.has(resolved)) fileDeps.add(resolved);
946
+ }
947
+ }
948
+ const inDegree = /* @__PURE__ */ new Map();
949
+ for (const f of tsFiles) inDegree.set(strip(f.path), 0);
950
+ for (const [, fileDeps] of deps) {
951
+ for (const dep of fileDeps) {
952
+ inDegree.set(dep, inDegree.get(dep) + 1);
953
+ }
954
+ }
955
+ const queue = [];
956
+ for (const [key, _deg] of inDegree) {
957
+ if (deps.get(key)?.size === 0) queue.push(key);
958
+ }
959
+ const order = [];
960
+ while (queue.length > 0) {
961
+ const key = queue.shift();
962
+ order.push(key);
963
+ for (const [other, fileDeps] of deps) {
964
+ if (fileDeps.has(key)) {
965
+ fileDeps.delete(key);
966
+ if (fileDeps.size === 0) queue.push(other);
967
+ }
968
+ }
969
+ }
970
+ for (const f of tsFiles) {
971
+ const key = strip(f.path);
972
+ if (!order.includes(key)) order.push(key);
973
+ }
974
+ return order.map((k) => byKey.get(k)).filter(Boolean);
975
+ }
976
+ function resolve(imp, fromPath, byKey) {
977
+ if (imp.startsWith(".")) {
978
+ const dir = fromPath.includes("/") ? fromPath.slice(0, fromPath.lastIndexOf("/")) : "";
979
+ const parts = (dir ? dir + "/" + imp : imp).split("/");
980
+ const resolved = [];
981
+ for (const p of parts) {
982
+ if (p === "." || p === "") continue;
983
+ if (p === "..") resolved.pop();
984
+ else resolved.push(p);
985
+ }
986
+ return resolved.join("/").replace(/\.js$/, "").replace(/\.ts$/, "");
987
+ }
988
+ if (imp.startsWith("@") && !imp.startsWith("@rotorsoft/")) {
989
+ const pkgName = imp.split("/")[1];
990
+ if (pkgName) {
991
+ for (const candidate of [
992
+ `packages/${pkgName}/src/index`,
993
+ `${pkgName}/src/index`,
994
+ `${pkgName}/index`
995
+ ]) {
996
+ if (byKey?.has(candidate)) return candidate;
997
+ }
998
+ return `packages/${pkgName}/src/index`;
999
+ }
1000
+ }
1001
+ return void 0;
1002
+ }
1003
+
1004
+ // src/client/lib/evaluate.ts
1005
+ var stripNonCode = (src, level = "full") => {
1006
+ const blank = (m) => m.replace(/[^\n]/g, " ");
1007
+ let result = src.replace(/\/\/[^\n]*/g, blank).replace(/\/\*[\s\S]*?\*\//g, blank).replace(/`(?:\\[\s\S]|[^`\\])*`/g, blank);
1008
+ if (level === "full") {
1009
+ result = result.replace(/"(?:\\[\s\S]|[^"\\])*"/g, blank).replace(/'(?:\\[\s\S]|[^'\\])*'/g, blank);
1010
+ }
1011
+ return result;
1012
+ };
1013
+ var isSourceFile = (f) => f.path.endsWith(".ts") && !f.path.endsWith(".d.ts") && !f.path.endsWith(".tsx") && !f.path.endsWith(".spec.ts") && !f.path.endsWith(".test.ts") && !f.path.includes("node_modules/") && !f.path.includes("__tests__/") && !f.path.includes("/test/") && !f.path.startsWith("test/");
1014
+ function transpile(code) {
1015
+ try {
1016
+ const safe = code.replace(/\bimport\.meta\.\w+/g, "'__import_meta__'");
1017
+ const { code: js } = (0, import_sucrase.transform)(safe, {
1018
+ transforms: ["typescript", "imports"]
1019
+ });
1020
+ return js.replace(
1021
+ /^(?:void\s+|await\s+)?(?:main|run|start|bootstrap|seed)\s*\([^)]*\)(?:\s*\.catch\([^)]*\))?;?\s*$/gm,
1022
+ "/* stripped runtime call */"
1023
+ );
1024
+ } catch {
1025
+ return code;
1026
+ }
1027
+ }
1028
+ function execute(files) {
1029
+ const result = {
1030
+ states: [],
1031
+ slices: [],
1032
+ projections: [],
1033
+ acts: [],
1034
+ error: void 0,
1035
+ fileErrors: /* @__PURE__ */ new Map(),
1036
+ expectedSlices: /* @__PURE__ */ new Map()
1037
+ };
1038
+ try {
1039
+ const __built__ = {
1040
+ states: [],
1041
+ slices: [],
1042
+ projections: [],
1043
+ acts: []
1044
+ };
1045
+ let _currentFile = "";
1046
+ const capture = (type) => (info) => {
1047
+ info._sourceFile = _currentFile;
1048
+ __built__[type + "s"].push(info);
1049
+ };
1050
+ const actModule = { ...MODULES["@rotorsoft/act"] };
1051
+ actModule.state = (entry) => MODULES["@rotorsoft/act"].state(entry, capture("state"));
1052
+ actModule.slice = () => MODULES["@rotorsoft/act"].slice(capture("slice"));
1053
+ actModule.projection = (target) => MODULES["@rotorsoft/act"].projection(
1054
+ target,
1055
+ capture("projection")
1056
+ );
1057
+ actModule.act = () => MODULES["@rotorsoft/act"].act(capture("act"));
1058
+ const pkgModules = {
1059
+ ...MODULES,
1060
+ "@rotorsoft/act": actModule
1061
+ };
1062
+ const fileExports = /* @__PURE__ */ new Map();
1063
+ const strip = (p) => p.replace(/\.tsx?$/, "");
1064
+ const resolveModule = (mod, fromPath) => {
1065
+ if (pkgModules[mod]) return pkgModules[mod];
1066
+ if (mod.startsWith(".")) {
1067
+ const dir = fromPath.includes("/") ? fromPath.slice(0, fromPath.lastIndexOf("/")) : "";
1068
+ const parts = (dir ? dir + "/" + mod : mod).split("/");
1069
+ const resolved = [];
1070
+ for (const p of parts) {
1071
+ if (p === "." || p === "") continue;
1072
+ if (p === "..") resolved.pop();
1073
+ else resolved.push(p);
1074
+ }
1075
+ const rp = resolved.join("/").replace(/\.js$/, "").replace(/\.ts$/, "");
1076
+ return fileExports.get(rp) ?? fileExports.get(rp + "/index") ?? {};
1077
+ }
1078
+ if (mod.startsWith("@") && !mod.startsWith("@rotorsoft/")) {
1079
+ const pkgName = mod.split("/")[1];
1080
+ const subPath = mod.split("/").slice(2).join("/");
1081
+ if (pkgName) {
1082
+ const suffix = subPath ? `/${subPath.replace(/\.js$/, "")}` : "/src/index";
1083
+ return fileExports.get(`packages/${pkgName}${suffix}`) ?? fileExports.get(`${pkgName}${suffix}`) ?? fileExports.get(`packages/${pkgName}/src/index`) ?? fileExports.get(`${pkgName}/src/index`) ?? fileExports.get(`${pkgName}/index`) ?? fileExports.get(pkgName) ?? unknownModuleProxy();
1084
+ }
1085
+ }
1086
+ return unknownModuleProxy();
1087
+ };
1088
+ const sorted = topoSort(files.filter(isSourceFile));
1089
+ for (const file of sorted) {
1090
+ _currentFile = file.path;
1091
+ const js = transpile(file.content);
1092
+ const key = strip(file.path);
1093
+ const fileExp = {};
1094
+ fileExports.set(key, fileExp);
1095
+ const sliceNamesInAct = [];
1096
+ const wsRe = /\.withSlice\(\s*(?:\w+\.)*(\w+)\s*\)/g;
1097
+ let wsm;
1098
+ const codeOnly = stripNonCode(js);
1099
+ while ((wsm = wsRe.exec(codeOnly)) !== null) {
1100
+ if (!sliceNamesInAct.includes(wsm[1])) sliceNamesInAct.push(wsm[1]);
1101
+ }
1102
+ for (const m of codeOnly.matchAll(
1103
+ /(?:exports\.)?(\w+)\s*=\s*(?:\w+\.)?slice(?:\s*\(\s*\)|\.call\(void 0,\s*\))/g
1104
+ )) {
1105
+ result.expectedSlices.set(m[1], file.path);
1106
+ }
1107
+ const fileRequire = Object.assign(
1108
+ (mod) => resolveModule(mod, key),
1109
+ { resolve: (mod) => mod, cache: {}, main: void 0 }
1110
+ );
1111
+ try {
1112
+ const cleanJs = js.replace(/\bconst\s+__dirname\b/g, "var __dirname").replace(/\bconst\s+__filename\b/g, "var __filename");
1113
+ const fn = new Function(
1114
+ // lgtm[js/code-injection]
1115
+ "require",
1116
+ "exports",
1117
+ "module",
1118
+ `
1119
+ "use strict";
1120
+ var __filename = ${JSON.stringify(file.path)};
1121
+ var __dirname = ".";
1122
+ var process = { env: {}, cwd: function() { return "/"; }, exit: function() {}, on: function() {}, off: function() {} };
1123
+ var Buffer = { from: function() { return ""; } };
1124
+ var console = { log: function() {}, error: function() {}, warn: function() {}, info: function() {}, debug: function() {} };
1125
+ ${cleanJs}
1126
+ `
1127
+ );
1128
+ fn(fileRequire, fileExp, { exports: fileExp });
1129
+ } catch (evalErr) {
1130
+ const errMsg = evalErr instanceof Error ? evalErr.message : String(evalErr);
1131
+ result.fileErrors.set(file.path, errMsg);
1132
+ }
1133
+ if (sliceNamesInAct.length > 0) {
1134
+ for (const actObj of __built__.acts) {
1135
+ if (actObj._sourceFile !== file.path) continue;
1136
+ const actSlices = actObj.slices;
1137
+ for (let ai = 0; ai < Math.min(sliceNamesInAct.length, actSlices.length); ai++) {
1138
+ if (actSlices[ai]) {
1139
+ actSlices[ai]._varName = sliceNamesInAct[ai];
1140
+ }
1141
+ }
1142
+ }
1143
+ }
1144
+ }
1145
+ result.states = __built__.states;
1146
+ result.slices = __built__.slices;
1147
+ result.projections = __built__.projections;
1148
+ result.acts = __built__.acts;
1149
+ } catch (e) {
1150
+ result.error = e instanceof Error ? e.message : String(e);
1151
+ }
1152
+ return result;
1153
+ }
1154
+ function extractModel(files) {
1155
+ const result = execute(files);
1156
+ return buildModel(result, files, result.expectedSlices);
1157
+ }
1158
+
1159
+ // src/client/lib/navigate.ts
1160
+ function positionAt(content, index) {
1161
+ const before = content.slice(0, index);
1162
+ const line = before.split("\n").length;
1163
+ const lastNl = before.lastIndexOf("\n");
1164
+ const col = index - (lastNl >= 0 ? lastNl : 0);
1165
+ return { line, col };
1166
+ }
1167
+ function buildPatterns(esc, type) {
1168
+ const statePatterns = [new RegExp(`state\\(\\s*\\{\\s*(${esc})\\s*[}:,]`)];
1169
+ const actionPatterns = [new RegExp(`\\.on\\(\\s*\\{\\s*(${esc})\\s*[},:]`)];
1170
+ const eventPatterns = [
1171
+ // Match event name inside .emits({ EventName: ... }) — inline declaration
1172
+ new RegExp(`\\.emits\\([\\s\\S]*?(${esc})\\s*:`),
1173
+ // Match event name as key in a schema object: EventName: z.object(...)
1174
+ new RegExp(`(${esc})\\s*:\\s*z\\.object\\(`)
1175
+ ];
1176
+ const reactionPatterns = [
1177
+ // .do(handlerName) or .do(module.handlerName) — handler declaration in builder
1178
+ new RegExp(`\\.do\\(\\s*(?:\\w+\\.)?(${esc})\\b`),
1179
+ // inline function in .do()
1180
+ new RegExp(
1181
+ `\\.on\\(\\s*["'\`][^"'\`]+["'\`]\\s*\\)\\s*\\.do\\(\\s*(?:async\\s+)?function\\s+(${esc})\\b`
1182
+ ),
1183
+ // Fallback: function definition
1184
+ new RegExp(`(?:export\\s+)?async\\s+function\\s+(${esc})\\s*\\(`)
1185
+ ];
1186
+ const projectionPatterns = [
1187
+ new RegExp(`(?:const|let|var)\\s+(${esc})\\s*=\\s*projection\\s*\\(`),
1188
+ new RegExp(`projection\\(\\s*["'\`](${esc})["'\`]`)
1189
+ ];
1190
+ const guardPatterns = [
1191
+ // Guard definition — prefer jumping to the declaration
1192
+ new RegExp(`(?:const|let|var)\\s+(${esc})\\s*(?::\\s*Invariant)?\\s*=`),
1193
+ new RegExp(`rule\\(\\s*["'\`](${esc})["'\`]`),
1194
+ new RegExp(`description:\\s*["'\`](${esc})["'\`]`),
1195
+ // .given() usage in the state builder — last resort
1196
+ new RegExp(`\\.given\\([\\s\\S]*?(${esc})`)
1197
+ ];
1198
+ const slicePatterns = [
1199
+ new RegExp(`(?:const|let|var)\\s+(${esc})\\s*=\\s*slice\\s*\\(`)
1200
+ ];
1201
+ const generic = [
1202
+ new RegExp(
1203
+ `(?:const|let|var)\\s+(${esc})\\s*=\\s*(?:state|slice|projection|act)\\s*\\(`
1204
+ ),
1205
+ new RegExp(`(?:const|let|var)\\s+(${esc})\\s*=`),
1206
+ new RegExp(`\\b(${esc})\\b`)
1207
+ ];
1208
+ switch (type) {
1209
+ case "state":
1210
+ return [...statePatterns, ...generic];
1211
+ case "action":
1212
+ return [...actionPatterns, ...generic];
1213
+ case "event":
1214
+ return [...eventPatterns, ...generic];
1215
+ case "reaction":
1216
+ return [...reactionPatterns, ...generic];
1217
+ case "projection":
1218
+ return [...projectionPatterns, ...generic];
1219
+ case "guard":
1220
+ return [...guardPatterns, ...generic];
1221
+ default:
1222
+ return [
1223
+ ...slicePatterns,
1224
+ ...statePatterns,
1225
+ ...actionPatterns,
1226
+ ...eventPatterns,
1227
+ ...reactionPatterns,
1228
+ ...projectionPatterns,
1229
+ ...guardPatterns,
1230
+ ...generic
1231
+ ];
1232
+ }
1233
+ }
1234
+ function navigateToCode(files, name, type, targetFile) {
1235
+ const stripped = /* @__PURE__ */ new Map();
1236
+ const code = (f) => {
1237
+ let c = stripped.get(f.path);
1238
+ if (c === void 0) {
1239
+ c = stripNonCode(f.content, "nav");
1240
+ stripped.set(f.path, c);
1241
+ }
1242
+ return c;
1243
+ };
1244
+ if (type === "file") {
1245
+ const file = files.find((f) => f.path === name || f.path.endsWith(name));
1246
+ if (file) {
1247
+ const actMatch = /\bact\s*\(\s*\)/.exec(code(file));
1248
+ if (actMatch) {
1249
+ const { line, col } = positionAt(file.content, actMatch.index);
1250
+ return { file: file.path, line, col };
1251
+ }
1252
+ return { file: file.path, line: 1, col: 1 };
1253
+ }
1254
+ return void 0;
1255
+ }
1256
+ if (targetFile) {
1257
+ const file = files.find((f) => f.path === targetFile);
1258
+ if (file) {
1259
+ const c = code(file);
1260
+ const esc2 = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1261
+ if (type === "event") {
1262
+ const emitsBlockRe = new RegExp(
1263
+ `\\.emits\\([\\s\\S]*?(${esc2})\\s*[,:}]`
1264
+ );
1265
+ const blockMatch = emitsBlockRe.exec(c);
1266
+ if (blockMatch) {
1267
+ const nameIdx = blockMatch.index + blockMatch[0].lastIndexOf(name);
1268
+ const { line, col } = positionAt(file.content, nameIdx);
1269
+ return { file: file.path, line, col };
1270
+ }
1271
+ const nameRe2 = new RegExp(`\\b${esc2}\\b`, "g");
1272
+ if (nameRe2.exec(c)) {
1273
+ const emitsMatch = /\.emits\s*\(/.exec(c);
1274
+ if (emitsMatch) {
1275
+ const { line, col } = positionAt(
1276
+ file.content,
1277
+ emitsMatch.index + 1
1278
+ );
1279
+ return { file: file.path, line, col };
1280
+ }
1281
+ }
1282
+ }
1283
+ if (type === "guard") {
1284
+ const descRe = new RegExp(`description:\\s*["'\`]${esc2}["'\`]`);
1285
+ const descMatch = descRe.exec(c);
1286
+ if (descMatch) {
1287
+ const before = c.slice(0, descMatch.index);
1288
+ const declRe = /(?:export\s+)?(?:const|let|var)\s+(\w+)\s*(?::\s*Invariant[^=]*)?\s*=/g;
1289
+ let lastDecl = null;
1290
+ let m;
1291
+ while ((m = declRe.exec(before)) !== null) {
1292
+ lastDecl = m;
1293
+ }
1294
+ if (lastDecl) {
1295
+ const nameIdx = lastDecl.index + lastDecl[0].indexOf(lastDecl[1]);
1296
+ const { line: line2, col: col2 } = positionAt(file.content, nameIdx);
1297
+ return { file: file.path, line: line2, col: col2 };
1298
+ }
1299
+ const { line, col } = positionAt(file.content, descMatch.index);
1300
+ return { file: file.path, line, col };
1301
+ }
1302
+ }
1303
+ if (type === "action") {
1304
+ const nameRe2 = new RegExp(`\\b${esc2}\\b`, "g");
1305
+ const blockStart = c.indexOf(".on(");
1306
+ if (blockStart >= 0) {
1307
+ nameRe2.lastIndex = blockStart;
1308
+ const match2 = nameRe2.exec(c);
1309
+ if (match2) {
1310
+ const { line, col } = positionAt(file.content, match2.index);
1311
+ return { file: file.path, line, col };
1312
+ }
1313
+ }
1314
+ }
1315
+ const nameRe = new RegExp(`\\b${esc2}\\b`);
1316
+ const match = nameRe.exec(c);
1317
+ if (match) {
1318
+ const { line, col } = positionAt(file.content, match.index);
1319
+ return { file: file.path, line, col };
1320
+ }
1321
+ }
1322
+ return void 0;
1323
+ }
1324
+ const esc = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1325
+ const isTestFile = (p) => /(?:\.spec\.|\.test\.|__tests__)/.test(p) || /\/test\//.test(p);
1326
+ const sortedFiles = [...files].sort(
1327
+ (a, b) => (isTestFile(a.path) ? 1 : 0) - (isTestFile(b.path) ? 1 : 0)
1328
+ );
1329
+ if (type === "guard") {
1330
+ const descRe = new RegExp(`description:\\s*["'\`]${esc}["'\`]`);
1331
+ for (const f of sortedFiles) {
1332
+ if (!/\.tsx?$/.test(f.path)) continue;
1333
+ const c = code(f);
1334
+ const descMatch = descRe.exec(c);
1335
+ if (descMatch) {
1336
+ const before = c.slice(0, descMatch.index);
1337
+ const declRe = /(?:export\s+)?(?:const|let|var)\s+(\w+)\s*(?::\s*Invariant[^=]*)?\s*=/g;
1338
+ let lastDecl = null;
1339
+ let m;
1340
+ while ((m = declRe.exec(before)) !== null) lastDecl = m;
1341
+ if (lastDecl) {
1342
+ const nameIdx = lastDecl.index + lastDecl[0].indexOf(lastDecl[1]);
1343
+ const { line: line2, col: col2 } = positionAt(f.content, nameIdx);
1344
+ return { file: f.path, line: line2, col: col2 };
1345
+ }
1346
+ const { line, col } = positionAt(f.content, descMatch.index);
1347
+ return { file: f.path, line, col };
1348
+ }
1349
+ }
1350
+ }
1351
+ const patterns = buildPatterns(esc, type);
1352
+ for (const re of patterns) {
1353
+ for (const f of sortedFiles) {
1354
+ if (!/\.tsx?$/.test(f.path)) continue;
1355
+ const c = code(f);
1356
+ const globalRe = new RegExp(re.source, re.flags + "g");
1357
+ let match;
1358
+ while ((match = globalRe.exec(c)) !== null) {
1359
+ const matchText = match[0];
1360
+ const nameOffsetInMatch = matchText.lastIndexOf(name);
1361
+ const nameStart = match.index + Math.max(0, nameOffsetInMatch);
1362
+ const { line, col } = positionAt(f.content, nameStart);
1363
+ return { file: f.path, line, col };
1364
+ }
1365
+ }
1366
+ }
1367
+ return void 0;
1368
+ }
1369
+
1370
+ // src/client/lib/validate.ts
1371
+ function validate(model) {
1372
+ const warnings = [];
1373
+ for (const s of model.states) {
1374
+ for (const a of s.actions) {
1375
+ if (a.emits.length === 0) {
1376
+ warnings.push({
1377
+ message: `Action "${a.name}" in "${s.name}" does not emit any events`,
1378
+ severity: "warning",
1379
+ element: a.name
1380
+ });
1381
+ }
1382
+ }
1383
+ }
1384
+ return warnings;
1385
+ }
1386
+
1387
+ // src/client/components/AiBar.tsx
1388
+ var import_lucide_react = require("lucide-react");
1389
+ var import_react = require("react");
1390
+ var import_jsx_runtime = require("react/jsx-runtime");
1391
+ var MODELS = [
1392
+ { id: "claude-sonnet-4-6", label: "Sonnet" },
1393
+ { id: "claude-opus-4-6", label: "Opus" },
1394
+ { id: "claude-haiku-4-5-20251001", label: "Haiku" }
1395
+ ];
1396
+ var TOKEN_OPTIONS = [
1397
+ { value: 4096, label: "4k" },
1398
+ { value: 8192, label: "8k" },
1399
+ { value: 16384, label: "16k" },
1400
+ { value: 32768, label: "32k" }
1401
+ ];
1402
+ function AiBar({ onSubmit, generating }) {
1403
+ const [prompt, setPrompt] = (0, import_react.useState)("");
1404
+ const [model, setModel] = (0, import_react.useState)(MODELS[0].id);
1405
+ const [maxTokens, setMaxTokens] = (0, import_react.useState)(16384);
1406
+ const submit = () => {
1407
+ if (prompt.trim()) {
1408
+ onSubmit(prompt, { model, maxTokens });
1409
+ setPrompt("");
1410
+ }
1411
+ };
1412
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "flex shrink-0 items-center gap-2 border-b border-zinc-800 bg-zinc-925 px-4 py-1.5", children: [
1413
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_lucide_react.Sparkles, { size: 13, className: "shrink-0 text-purple-400" }),
1414
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
1415
+ "textarea",
1416
+ {
1417
+ value: prompt,
1418
+ onChange: (e) => setPrompt(e.target.value),
1419
+ onKeyDown: (e) => {
1420
+ if (e.key === "Enter" && !e.shiftKey) {
1421
+ e.preventDefault();
1422
+ submit();
1423
+ }
1424
+ },
1425
+ placeholder: "Refine with AI... (Shift+Enter for new line)",
1426
+ rows: 1,
1427
+ className: "flex-1 resize-y rounded-md border border-zinc-700 bg-zinc-800 px-3 py-1 text-xs text-zinc-200 outline-none placeholder:text-zinc-600 focus:border-purple-600",
1428
+ style: { minHeight: "28px", maxHeight: "200px" },
1429
+ disabled: generating
1430
+ }
1431
+ ),
1432
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
1433
+ "select",
1434
+ {
1435
+ value: model,
1436
+ onChange: (e) => setModel(e.target.value),
1437
+ disabled: generating,
1438
+ className: "rounded-md border border-zinc-700 bg-zinc-800 px-1.5 py-1 text-[10px] text-zinc-400 outline-none focus:border-purple-600",
1439
+ children: MODELS.map((m) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)("option", { value: m.id, children: m.label }, m.id))
1440
+ }
1441
+ ),
1442
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
1443
+ "select",
1444
+ {
1445
+ value: maxTokens,
1446
+ onChange: (e) => setMaxTokens(Number(e.target.value)),
1447
+ disabled: generating,
1448
+ className: "rounded-md border border-zinc-700 bg-zinc-800 px-1.5 py-1 text-[10px] text-zinc-400 outline-none focus:border-purple-600",
1449
+ children: TOKEN_OPTIONS.map((t) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)("option", { value: t.value, children: t.label }, t.value))
1450
+ }
1451
+ ),
1452
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
1453
+ "button",
1454
+ {
1455
+ onClick: submit,
1456
+ disabled: generating || !prompt.trim(),
1457
+ className: "flex items-center gap-1 rounded-md bg-purple-600 px-3 py-1 text-[10px] font-medium text-white transition hover:bg-purple-500 disabled:opacity-50",
1458
+ children: generating ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_lucide_react.Loader2, { size: 11, className: "animate-spin" }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_lucide_react.Send, { size: 11 })
1459
+ }
1460
+ )
1461
+ ] });
1462
+ }
1463
+
1464
+ // src/client/components/Diagram.tsx
1465
+ var import_lucide_react2 = require("lucide-react");
1466
+ var import_react2 = require("react");
1467
+
1468
+ // src/client/lib/layout.ts
1469
+ var W = 100;
1470
+ var H = 36;
1471
+ var STATE_W = 80;
1472
+ var STATE_H = 80;
1473
+ var GAP = 12;
1474
+ var PAD = 10;
1475
+ var SLICE_PAD = 24;
1476
+ var SLICE_INNER = 16;
1477
+ var SLICE_GAP = 20;
1478
+ var MARGIN = 30;
1479
+ var COLORS = {
1480
+ action: { bg: "#1e40af", border: "#3b82f6", text: "#93c5fd" },
1481
+ event: { bg: "#c2410c", border: "#f97316", text: "#fed7aa" },
1482
+ state: { bg: "#a16207", border: "#eab308", text: "#fef08a" },
1483
+ reaction: { bg: "#7e22ce", border: "#a855f7", text: "#d8b4fe" },
1484
+ projection: { bg: "#15803d", border: "#22c55e", text: "#bbf7d0" }
1485
+ };
1486
+ function measureChain(rDef, lookup, visited, allStates) {
1487
+ const rows = [];
1488
+ let dispatchBlockH = 0;
1489
+ for (const an of rDef.dispatches) {
1490
+ const targetAction = allStates.flatMap((s) => s.actions).find((a) => a.name === an);
1491
+ const targetState = allStates.find(
1492
+ (s) => s.actions.some((a) => a.name === an)
1493
+ );
1494
+ const emitNames = targetAction?.emits ?? [];
1495
+ const emitInfos = [];
1496
+ let emitsH = 0;
1497
+ for (const en of emitNames) {
1498
+ const subR = lookup.get(en);
1499
+ let eventH = H;
1500
+ let subChain;
1501
+ if (subR && !visited.has(subR.handlerName)) {
1502
+ visited.add(subR.handlerName);
1503
+ subChain = measureChain(subR, lookup, visited, allStates);
1504
+ eventH = Math.max(H, subChain.groupH);
1505
+ }
1506
+ emitInfos.push({
1507
+ name: en,
1508
+ h: eventH,
1509
+ subChain,
1510
+ subReaction: subR && subChain ? subR : void 0
1511
+ });
1512
+ emitsH += eventH;
1513
+ }
1514
+ const rowH = Math.max(H, targetState ? STATE_H : 0, emitsH || H);
1515
+ rows.push({ an, rowH, emitInfos, emitsH, targetState });
1516
+ if (dispatchBlockH > 0) dispatchBlockH += GAP / 2;
1517
+ dispatchBlockH += rowH;
1518
+ }
1519
+ return { groupH: Math.max(H, dispatchBlockH), dispatchBlockH, rows };
1520
+ }
1521
+ function placeChain(measure, rDef, reactionY, rX, triggeredFromX, triggeredFromY, ns, es, sliceName, lookup, eventProjections, eventReactions, eventSchemas, sliceRightXRef) {
1522
+ const dispatchBaseX = rX + W + GAP;
1523
+ const rp = { x: rX, y: reactionY };
1524
+ ns.push({
1525
+ key: `r:${rDef.handlerName}:${sliceName}`,
1526
+ pos: rp,
1527
+ type: "reaction",
1528
+ label: rDef.handlerName
1529
+ });
1530
+ es.push({
1531
+ from: { x: triggeredFromX, y: triggeredFromY },
1532
+ to: { x: rp.x, y: rp.y + H / 2 },
1533
+ color: COLORS.reaction.border,
1534
+ dash: true
1535
+ });
1536
+ const reactionCenterY = reactionY + H / 2;
1537
+ let dispatchY = reactionCenterY - measure.dispatchBlockH / 2;
1538
+ for (const row of measure.rows) {
1539
+ const rowCenterY = dispatchY + row.rowH / 2;
1540
+ let nextX = dispatchBaseX;
1541
+ const dap = { x: nextX, y: rowCenterY - H / 2 };
1542
+ const dispatchedAction = row.targetState?.actions.find(
1543
+ (a) => a.name === row.an
1544
+ );
1545
+ ns.push({
1546
+ key: `a:${row.an}:dispatched:${rDef.handlerName}`,
1547
+ pos: dap,
1548
+ type: "action",
1549
+ label: row.an,
1550
+ sub: dispatchedAction && dispatchedAction.invariants.length > 0 ? "guarded" : void 0,
1551
+ guards: dispatchedAction && dispatchedAction.invariants.length > 0 ? dispatchedAction.invariants : void 0,
1552
+ file: row.targetState?.file,
1553
+ emits: dispatchedAction?.emits
1554
+ });
1555
+ es.push({
1556
+ from: { x: rp.x + W, y: rp.y + H / 2 },
1557
+ to: { x: dap.x, y: dap.y + H / 2 },
1558
+ color: COLORS.reaction.border,
1559
+ dash: true
1560
+ });
1561
+ nextX += W + GAP;
1562
+ if (row.targetState) {
1563
+ ns.push({
1564
+ key: `s:${row.targetState.name}:dispatched:${rDef.handlerName}:${row.an}`,
1565
+ pos: { x: nextX, y: rowCenterY - STATE_H / 2 },
1566
+ type: "state",
1567
+ label: row.targetState.name,
1568
+ file: row.targetState.file
1569
+ });
1570
+ nextX += STATE_W + GAP;
1571
+ }
1572
+ const evtX = nextX;
1573
+ const nEvents = row.emitInfos.length;
1574
+ const eventsOnlyH = nEvents * H + (nEvents - 1) * (GAP / 2);
1575
+ let emitY = rowCenterY - eventsOnlyH / 2;
1576
+ for (const emit of row.emitInfos) {
1577
+ ns.push({
1578
+ key: `e:${emit.name}:dispatched:${rDef.handlerName}:${row.an}`,
1579
+ pos: { x: evtX, y: emitY },
1580
+ type: "event",
1581
+ label: emit.name,
1582
+ file: row.targetState?.file,
1583
+ projections: eventProjections.get(emit.name),
1584
+ reactions: eventReactions.get(emit.name),
1585
+ schema: eventSchemas.get(emit.name)
1586
+ });
1587
+ if (emit.subChain && emit.subReaction) {
1588
+ const subRX = evtX + W + GAP * 3;
1589
+ placeChain(
1590
+ emit.subChain,
1591
+ emit.subReaction,
1592
+ emitY,
1593
+ // reaction aligns with emit
1594
+ subRX,
1595
+ evtX + W,
1596
+ emitY + H / 2,
1597
+ ns,
1598
+ es,
1599
+ sliceName,
1600
+ lookup,
1601
+ eventProjections,
1602
+ eventReactions,
1603
+ eventSchemas,
1604
+ sliceRightXRef
1605
+ );
1606
+ }
1607
+ emitY += H + GAP / 2;
1608
+ }
1609
+ if (row.emitInfos.length > 0) nextX = evtX + W + GAP;
1610
+ sliceRightXRef.value = Math.max(sliceRightXRef.value, nextX);
1611
+ dispatchY += row.rowH + GAP / 2;
1612
+ }
1613
+ }
1614
+ function computeLayout(viewModel) {
1615
+ const ns = [];
1616
+ const es = [];
1617
+ const boxes = [];
1618
+ const sv = /* @__PURE__ */ new Map();
1619
+ for (const s of viewModel.states) {
1620
+ sv.set(s.varName, s);
1621
+ sv.set(s.name, s);
1622
+ }
1623
+ const eventProjections = /* @__PURE__ */ new Map();
1624
+ const eventReactions = /* @__PURE__ */ new Map();
1625
+ const eventSchemas = /* @__PURE__ */ new Map();
1626
+ for (const s of viewModel.states) {
1627
+ for (const e of s.events) {
1628
+ if (e.schema && !eventSchemas.has(e.name)) {
1629
+ eventSchemas.set(e.name, e.schema);
1630
+ }
1631
+ }
1632
+ }
1633
+ const projectionHandles = /* @__PURE__ */ new Map();
1634
+ for (const proj of viewModel.projections) {
1635
+ projectionHandles.set(proj.name, proj.handles);
1636
+ }
1637
+ for (const slice of viewModel.slices) {
1638
+ for (const r of slice.reactions) {
1639
+ const list = eventReactions.get(r.event) ?? [];
1640
+ list.push(r.handlerName);
1641
+ eventReactions.set(r.event, list);
1642
+ }
1643
+ }
1644
+ for (const r of viewModel.reactions) {
1645
+ const list = eventReactions.get(r.event) ?? [];
1646
+ list.push(r.handlerName);
1647
+ eventReactions.set(r.event, list);
1648
+ }
1649
+ for (const proj of viewModel.projections) {
1650
+ for (const en of proj.handles) {
1651
+ const list = eventProjections.get(en) ?? [];
1652
+ list.push(proj.name);
1653
+ eventProjections.set(en, list);
1654
+ }
1655
+ }
1656
+ let cx = PAD;
1657
+ let globalY = 0;
1658
+ const sortedSlices = [...viewModel.slices].sort(
1659
+ (a, b) => a.name.localeCompare(b.name)
1660
+ );
1661
+ for (const slice of sortedSlices) {
1662
+ if (slice.error && slice.states.length === 0) {
1663
+ const sx2 = PAD;
1664
+ const errorW = Math.max(300, slice.error.length * 5);
1665
+ const nameH = slice.name.length * 7;
1666
+ const errorH = Math.max(H * 2 + GAP, nameH + GAP * 2);
1667
+ boxes.push({
1668
+ label: slice.name,
1669
+ x: sx2 - GAP / 2,
1670
+ y: globalY,
1671
+ w: errorW,
1672
+ h: errorH,
1673
+ error: slice.error
1674
+ });
1675
+ globalY += errorH + SLICE_GAP;
1676
+ continue;
1677
+ }
1678
+ cx = PAD;
1679
+ const sx = cx;
1680
+ cx += SLICE_PAD + GAP;
1681
+ const eventFileMap = /* @__PURE__ */ new Map();
1682
+ const actionFileMap = /* @__PURE__ */ new Map();
1683
+ const rawParts = slice.stateVars.map((v) => sv.get(v)).filter(Boolean);
1684
+ const mergedByName = /* @__PURE__ */ new Map();
1685
+ for (const st of rawParts) {
1686
+ for (const e of st.events) {
1687
+ if (st.file) eventFileMap.set(e.name, st.file);
1688
+ }
1689
+ for (const a of st.actions) {
1690
+ if (st.file) actionFileMap.set(a.name, st.file);
1691
+ }
1692
+ const existing = mergedByName.get(st.name);
1693
+ if (existing) {
1694
+ const actionNames = new Set(existing.actions.map((a) => a.name));
1695
+ for (const a of st.actions) {
1696
+ if (!actionNames.has(a.name)) existing.actions.push(a);
1697
+ }
1698
+ const eventNames = new Set(existing.events.map((e) => e.name));
1699
+ for (const e of st.events) {
1700
+ if (!eventNames.has(e.name)) existing.events.push(e);
1701
+ }
1702
+ } else {
1703
+ mergedByName.set(st.name, {
1704
+ ...st,
1705
+ actions: [...st.actions],
1706
+ events: [...st.events]
1707
+ });
1708
+ }
1709
+ }
1710
+ const parts = [...mergedByName.values()];
1711
+ let y = SLICE_INNER;
1712
+ let sliceRightX = cx;
1713
+ const sliceNodeStart = ns.length;
1714
+ const sliceEdgeStart = es.length;
1715
+ const sliceReactionsByEvent = /* @__PURE__ */ new Map();
1716
+ for (const r of slice.reactions) {
1717
+ const list = sliceReactionsByEvent.get(r.event) ?? [];
1718
+ list.push(r);
1719
+ sliceReactionsByEvent.set(r.event, list);
1720
+ }
1721
+ const sliceReactionByEvent = /* @__PURE__ */ new Map();
1722
+ for (const [event, reactions] of sliceReactionsByEvent) {
1723
+ sliceReactionByEvent.set(event, reactions[0]);
1724
+ }
1725
+ const visitedEvents = /* @__PURE__ */ new Set();
1726
+ const visitedReactions = /* @__PURE__ */ new Set();
1727
+ let partIdx = 0;
1728
+ for (const st of parts) {
1729
+ if (partIdx > 0) y += GAP * 2;
1730
+ const stateColX = cx + W + GAP;
1731
+ const eventColX = stateColX + STATE_W + GAP;
1732
+ const eventRows = [];
1733
+ const actionEmitted = /* @__PURE__ */ new Set();
1734
+ for (const action of st.actions) {
1735
+ for (const en of action.emits) {
1736
+ actionEmitted.add(en);
1737
+ }
1738
+ }
1739
+ for (const ev of st.events) {
1740
+ if (!actionEmitted.has(ev.name)) {
1741
+ eventRows.push({ eventName: ev.name, actionName: "" });
1742
+ }
1743
+ }
1744
+ for (const action of st.actions) {
1745
+ for (const en of action.emits) {
1746
+ eventRows.push({ eventName: en, actionName: action.name });
1747
+ }
1748
+ }
1749
+ const measuredEvents = [];
1750
+ let evtBlockH = 0;
1751
+ for (const { eventName: en, actionName } of eventRows) {
1752
+ const chains = [];
1753
+ if (!visitedEvents.has(en)) {
1754
+ const rDefs = sliceReactionsByEvent.get(en) ?? [];
1755
+ for (const rDef of rDefs) {
1756
+ if (visitedReactions.has(rDef.handlerName)) continue;
1757
+ visitedReactions.add(rDef.handlerName);
1758
+ const chain = measureChain(
1759
+ rDef,
1760
+ sliceReactionByEvent,
1761
+ visitedReactions,
1762
+ viewModel.states
1763
+ );
1764
+ chains.push({ chain, reaction: rDef });
1765
+ }
1766
+ if (rDefs.length > 0) visitedEvents.add(en);
1767
+ }
1768
+ measuredEvents.push({
1769
+ eventName: en,
1770
+ actionName,
1771
+ h: H,
1772
+ chains
1773
+ });
1774
+ if (evtBlockH > 0) evtBlockH += GAP / 2;
1775
+ evtBlockH += H;
1776
+ }
1777
+ if (evtBlockH === 0) evtBlockH = H;
1778
+ const nActs = st.actions.length;
1779
+ const actBlockH = nActs * H + (nActs - 1) * (GAP / 2);
1780
+ const primaryBlockH = Math.max(evtBlockH, actBlockH, STATE_H);
1781
+ const stCenterY = y + primaryBlockH / 2;
1782
+ ns.push({
1783
+ key: `s:${st.name}:${slice.name}`,
1784
+ pos: { x: stateColX, y: stCenterY - STATE_H / 2 },
1785
+ type: "state",
1786
+ label: st.name,
1787
+ file: st.file
1788
+ });
1789
+ const sliceRightXRef = { value: sliceRightX };
1790
+ let evtY = stCenterY - evtBlockH / 2;
1791
+ let chainWatermark = -Infinity;
1792
+ const eventYMap = /* @__PURE__ */ new Map();
1793
+ for (let ei = 0; ei < measuredEvents.length; ei++) {
1794
+ const { eventName: en, actionName, chains } = measuredEvents[ei];
1795
+ ns.push({
1796
+ key: `e:${en}:${slice.name}:${actionName}`,
1797
+ pos: { x: eventColX, y: evtY },
1798
+ type: "event",
1799
+ label: en,
1800
+ file: eventFileMap.get(en) ?? st.file,
1801
+ projections: eventProjections.get(en),
1802
+ reactions: eventReactions.get(en),
1803
+ schema: eventSchemas.get(en)
1804
+ });
1805
+ eventYMap.set(en, evtY);
1806
+ for (const { chain, reaction: chainReaction } of chains) {
1807
+ const rX = eventColX + W + GAP * 3;
1808
+ const minReactionY = chainWatermark + chain.dispatchBlockH / 2 - H / 2;
1809
+ const reactionY = Math.max(evtY, minReactionY);
1810
+ const chainStartIdx = ns.length;
1811
+ placeChain(
1812
+ chain,
1813
+ chainReaction,
1814
+ reactionY,
1815
+ rX,
1816
+ eventColX + W,
1817
+ evtY + H / 2,
1818
+ // arrow always from event center
1819
+ ns,
1820
+ es,
1821
+ slice.name,
1822
+ sliceReactionByEvent,
1823
+ eventProjections,
1824
+ eventReactions,
1825
+ eventSchemas,
1826
+ sliceRightXRef
1827
+ );
1828
+ for (let ni = chainStartIdx; ni < ns.length; ni++) {
1829
+ const n = ns[ni];
1830
+ const nh = n.type === "state" ? STATE_H : H;
1831
+ chainWatermark = Math.max(chainWatermark, n.pos.y + nh + GAP / 2);
1832
+ }
1833
+ }
1834
+ evtY += H + GAP / 2;
1835
+ }
1836
+ const seenProj = /* @__PURE__ */ new Set();
1837
+ for (const me of measuredEvents) {
1838
+ const projs = eventProjections.get(me.eventName);
1839
+ if (!projs) continue;
1840
+ for (const pn of projs) {
1841
+ if (seenProj.has(pn)) continue;
1842
+ seenProj.add(pn);
1843
+ ns.push({
1844
+ key: `p:${pn}:${slice.name}`,
1845
+ pos: { x: eventColX, y: evtY },
1846
+ type: "projection",
1847
+ label: pn,
1848
+ handles: projectionHandles.get(pn)
1849
+ });
1850
+ evtY += H + GAP / 2;
1851
+ }
1852
+ }
1853
+ sliceRightX = sliceRightXRef.value;
1854
+ let actY = stCenterY - actBlockH / 2;
1855
+ const actionColors = [
1856
+ "#60a5fa",
1857
+ "#f97316",
1858
+ "#a78bfa",
1859
+ "#34d399",
1860
+ "#fb7185",
1861
+ "#fbbf24"
1862
+ ];
1863
+ let actionIdx = 0;
1864
+ for (const action of st.actions) {
1865
+ const color = actionColors[actionIdx % actionColors.length];
1866
+ ns.push({
1867
+ key: `a:${action.name}:${slice.name}`,
1868
+ pos: { x: cx, y: actY },
1869
+ type: "action",
1870
+ label: action.name,
1871
+ sub: action.invariants.length > 0 ? "guarded" : void 0,
1872
+ guards: action.invariants.length > 0 ? action.invariants : void 0,
1873
+ file: actionFileMap.get(action.name) ?? st.file,
1874
+ emits: action.emits
1875
+ });
1876
+ for (const en of action.emits) {
1877
+ const ey = eventYMap.get(en);
1878
+ es.push({
1879
+ from: { x: cx + W, y: actY + H / 2 },
1880
+ to: { x: eventColX, y: ey + H / 2 },
1881
+ color,
1882
+ dash: false
1883
+ });
1884
+ }
1885
+ actY += H + GAP / 2;
1886
+ actionIdx++;
1887
+ }
1888
+ const contentBottomY = Math.max(
1889
+ y + primaryBlockH,
1890
+ evtY,
1891
+ chainWatermark > -Infinity ? chainWatermark : 0
1892
+ );
1893
+ y = contentBottomY + GAP / 2;
1894
+ partIdx++;
1895
+ }
1896
+ for (const r of slice.reactions) {
1897
+ if (visitedReactions.has(r.handlerName)) continue;
1898
+ const rX = sliceRightX + GAP * 2;
1899
+ const rp = { x: rX, y };
1900
+ ns.push({
1901
+ key: `r:${r.handlerName}:${slice.name}`,
1902
+ pos: rp,
1903
+ type: "reaction",
1904
+ label: r.handlerName
1905
+ });
1906
+ sliceRightX = Math.max(sliceRightX, rX + W + GAP);
1907
+ y += H + GAP / 2;
1908
+ }
1909
+ const bbox = {
1910
+ minX: Infinity,
1911
+ minY: Infinity,
1912
+ maxX: -Infinity,
1913
+ maxY: -Infinity
1914
+ };
1915
+ for (let ni = sliceNodeStart; ni < ns.length; ni++) {
1916
+ const n = ns[ni];
1917
+ const nw = n.type === "state" ? STATE_W : W;
1918
+ const nh = n.type === "state" ? STATE_H : H;
1919
+ bbox.minX = Math.min(bbox.minX, n.pos.x);
1920
+ bbox.minY = Math.min(bbox.minY, n.pos.y);
1921
+ bbox.maxX = Math.max(bbox.maxX, n.pos.x + nw);
1922
+ bbox.maxY = Math.max(bbox.maxY, n.pos.y + nh);
1923
+ }
1924
+ if (!Number.isFinite(bbox.minY)) {
1925
+ bbox.minX = sx;
1926
+ bbox.minY = 0;
1927
+ bbox.maxX = sx + W;
1928
+ bbox.maxY = H;
1929
+ }
1930
+ const contentH = bbox.maxY - bbox.minY;
1931
+ const boxH = contentH + SLICE_INNER * 2;
1932
+ const dy = globalY - bbox.minY + SLICE_INNER;
1933
+ for (let ni = sliceNodeStart; ni < ns.length; ni++) {
1934
+ ns[ni].pos.y += dy;
1935
+ }
1936
+ for (let ei = sliceEdgeStart; ei < es.length; ei++) {
1937
+ es[ei].from.y += dy;
1938
+ es[ei].to.y += dy;
1939
+ }
1940
+ boxes.push({
1941
+ label: slice.name,
1942
+ x: sx - GAP / 2,
1943
+ y: globalY,
1944
+ w: bbox.maxX - sx + GAP + SLICE_INNER,
1945
+ h: boxH,
1946
+ error: slice.error
1947
+ });
1948
+ globalY += boxH + SLICE_GAP;
1949
+ }
1950
+ cx = PAD;
1951
+ const claimed = new Set(sortedSlices.flatMap((sl) => sl.stateVars));
1952
+ const standaloneStates = [...viewModel.states].filter((s) => !claimed.has(s.varName)).sort((a, b) => a.name.localeCompare(b.name));
1953
+ for (const st of standaloneStates) {
1954
+ const stateColX = cx + W + GAP;
1955
+ const eventColX = stateColX + STATE_W + GAP;
1956
+ const actionEmittedEvents = new Set(st.actions.flatMap((a) => a.emits));
1957
+ const orphanEvents = st.events.map((e) => e.name).filter((en) => !actionEmittedEvents.has(en));
1958
+ const nEvents = actionEmittedEvents.size + orphanEvents.length;
1959
+ const evtBlockH = Math.max(nEvents, 1) * H + (Math.max(nEvents, 1) - 1) * (GAP / 2);
1960
+ const nActs = st.actions.length;
1961
+ const actBlockH = nActs * H + (nActs - 1) * (GAP / 2);
1962
+ const blockH = Math.max(evtBlockH, actBlockH, STATE_H);
1963
+ const stCenterY = globalY + blockH / 2;
1964
+ ns.push({
1965
+ key: `s:${st.name}:standalone`,
1966
+ pos: { x: stateColX, y: stCenterY - STATE_H / 2 },
1967
+ type: "state",
1968
+ label: st.name
1969
+ });
1970
+ let evtY = stCenterY - evtBlockH / 2;
1971
+ const eventYMap = /* @__PURE__ */ new Map();
1972
+ for (const action of st.actions) {
1973
+ for (const en of action.emits) {
1974
+ ns.push({
1975
+ key: `e:${en}:standalone`,
1976
+ pos: { x: eventColX, y: evtY },
1977
+ type: "event",
1978
+ label: en,
1979
+ projections: eventProjections.get(en),
1980
+ reactions: eventReactions.get(en),
1981
+ schema: eventSchemas.get(en)
1982
+ });
1983
+ eventYMap.set(en, evtY);
1984
+ evtY += H + GAP / 2;
1985
+ }
1986
+ }
1987
+ for (const en of orphanEvents) {
1988
+ ns.push({
1989
+ key: `e:${en}:standalone`,
1990
+ pos: { x: eventColX, y: evtY },
1991
+ type: "event",
1992
+ label: en,
1993
+ projections: eventProjections.get(en),
1994
+ reactions: eventReactions.get(en),
1995
+ schema: eventSchemas.get(en)
1996
+ });
1997
+ eventYMap.set(en, evtY);
1998
+ evtY += H + GAP / 2;
1999
+ }
2000
+ let actY = stCenterY - actBlockH / 2;
2001
+ const standaloneColors = [
2002
+ "#60a5fa",
2003
+ "#f97316",
2004
+ "#a78bfa",
2005
+ "#34d399",
2006
+ "#fb7185",
2007
+ "#fbbf24"
2008
+ ];
2009
+ let aIdx = 0;
2010
+ for (const action of st.actions) {
2011
+ const aColor = standaloneColors[aIdx % standaloneColors.length];
2012
+ ns.push({
2013
+ key: `a:${action.name}:standalone`,
2014
+ pos: { x: cx, y: actY },
2015
+ type: "action",
2016
+ label: action.name,
2017
+ sub: action.invariants.length > 0 ? "guarded" : void 0,
2018
+ guards: action.invariants.length > 0 ? action.invariants : void 0,
2019
+ emits: action.emits
2020
+ });
2021
+ for (const en of action.emits) {
2022
+ const ey = eventYMap.get(en);
2023
+ es.push({
2024
+ from: { x: cx + W, y: actY + H / 2 },
2025
+ to: { x: eventColX, y: ey + H / 2 },
2026
+ color: aColor,
2027
+ dash: false
2028
+ });
2029
+ }
2030
+ actY += H + GAP / 2;
2031
+ aIdx++;
2032
+ }
2033
+ globalY += blockH + GAP * 2;
2034
+ }
2035
+ if (viewModel.reactions.length > 0) {
2036
+ const reactionYByEvent = /* @__PURE__ */ new Map();
2037
+ for (const r of viewModel.reactions) {
2038
+ const trigNode = ns.find(
2039
+ (n) => n.type === "event" && n.label === r.event
2040
+ );
2041
+ const baseY = trigNode ? trigNode.pos.y : globalY;
2042
+ const rY = reactionYByEvent.get(r.event) ?? baseY;
2043
+ const rX = trigNode ? trigNode.pos.x + W + GAP * 3 : cx + W * 3 + GAP * 4;
2044
+ const rp = { x: rX, y: rY };
2045
+ ns.push({
2046
+ key: `r:${r.handlerName}:standalone`,
2047
+ pos: rp,
2048
+ type: "reaction",
2049
+ label: r.handlerName
2050
+ });
2051
+ if (trigNode) {
2052
+ es.push({
2053
+ from: { x: trigNode.pos.x + W, y: trigNode.pos.y + H / 2 },
2054
+ to: { x: rp.x, y: rp.y + H / 2 },
2055
+ color: COLORS.reaction.border,
2056
+ dash: true
2057
+ });
2058
+ }
2059
+ reactionYByEvent.set(r.event, rY + H + GAP / 2);
2060
+ globalY = Math.max(globalY, rY + H + GAP);
2061
+ }
2062
+ }
2063
+ let minX = 0, minY = 0, maxX = 0, maxY = 0;
2064
+ for (const n of ns) {
2065
+ const nw = n.type === "state" ? STATE_W : W;
2066
+ const nh = n.type === "state" ? STATE_H : H;
2067
+ minX = Math.min(minX, n.pos.x);
2068
+ minY = Math.min(minY, n.pos.y);
2069
+ maxX = Math.max(maxX, n.pos.x + nw);
2070
+ maxY = Math.max(maxY, n.pos.y + nh);
2071
+ }
2072
+ for (const b of boxes) {
2073
+ minX = Math.min(minX, b.x);
2074
+ minY = Math.min(minY, b.y);
2075
+ maxX = Math.max(maxX, b.x + b.w);
2076
+ maxY = Math.max(maxY, b.y + b.h);
2077
+ }
2078
+ return {
2079
+ ns,
2080
+ es,
2081
+ boxes,
2082
+ // Content bounds (used by viewBox to frame the diagram)
2083
+ minX: minX - MARGIN,
2084
+ minY: minY - MARGIN,
2085
+ width: maxX - minX + MARGIN * 2,
2086
+ height: maxY - minY + MARGIN * 2
2087
+ };
2088
+ }
2089
+
2090
+ // src/client/components/Diagram.tsx
2091
+ var import_jsx_runtime2 = require("react/jsx-runtime");
2092
+ var COLORS2 = {
2093
+ action: { bg: "#1e40af", border: "#3b82f6", text: "#93c5fd" },
2094
+ event: { bg: "#c2410c", border: "#f97316", text: "#fed7aa" },
2095
+ state: { bg: "#a16207", border: "#eab308", text: "#fef08a" },
2096
+ reaction: { bg: "#7e22ce", border: "#a855f7", text: "#d8b4fe" },
2097
+ projection: { bg: "#059669", border: "#34d399", text: "#6ff7b5" },
2098
+ error: { bg: "#991b1b", border: "#ef4444", text: "#fca5a5" }
2099
+ };
2100
+ var alpha = (hex, a) => {
2101
+ const r = parseInt(hex.slice(1, 3), 16);
2102
+ const g = parseInt(hex.slice(3, 5), 16);
2103
+ const b = parseInt(hex.slice(5, 7), 16);
2104
+ return `rgba(${r},${g},${b},${a})`;
2105
+ };
2106
+ var STATE_FONT = 10;
2107
+ function splitLabel(label, maxChars = 16) {
2108
+ const words = label.replace(/([a-z])([A-Z])/g, "$1 $2").split(" ");
2109
+ const lines = [];
2110
+ let cur = "";
2111
+ for (const w of words) {
2112
+ if (cur && (cur + " " + w).length > maxChars) {
2113
+ lines.push(cur);
2114
+ cur = w;
2115
+ } else cur = cur ? cur + " " + w : w;
2116
+ }
2117
+ if (cur) lines.push(cur);
2118
+ return lines.length > 0 ? lines : [label];
2119
+ }
2120
+ function formatModelTree(model) {
2121
+ const lines = [];
2122
+ for (const entry of model.entries) {
2123
+ const sortedSlices = [...entry.slices].sort(
2124
+ (a, b) => a.name.localeCompare(b.name)
2125
+ );
2126
+ for (const sl of sortedSlices) {
2127
+ lines.push(`Slice: ${sl.name}`);
2128
+ for (const stKey of sl.stateVars) {
2129
+ const st = entry.states.find((s) => s.varName === stKey);
2130
+ if (!st) continue;
2131
+ lines.push(` State: ${st.name}`);
2132
+ for (const a of st.actions) {
2133
+ let line = ` ${a.name} \u2192 [${a.emits.join(", ")}]`;
2134
+ if (a.invariants.length)
2135
+ line += ` guards: [${a.invariants.join(", ")}]`;
2136
+ lines.push(line);
2137
+ }
2138
+ }
2139
+ for (const r of sl.reactions) {
2140
+ lines.push(
2141
+ ` \u26A1 ${r.handlerName} on ${r.event} \u2192 [${r.dispatches.join(", ") || "\u2014"}]`
2142
+ );
2143
+ }
2144
+ }
2145
+ for (const p of entry.projections) {
2146
+ lines.push(`Projection: ${p.name} [${p.handles.join(", ")}]`);
2147
+ }
2148
+ const sliceStateKeys = new Set(entry.slices.flatMap((sl) => sl.stateVars));
2149
+ for (const st of entry.states.filter(
2150
+ (s) => !sliceStateKeys.has(s.varName)
2151
+ )) {
2152
+ lines.push(`State: ${st.name}`);
2153
+ for (const a of st.actions) {
2154
+ lines.push(` ${a.name} \u2192 [${a.emits.join(", ")}]`);
2155
+ }
2156
+ }
2157
+ for (const r of entry.reactions) {
2158
+ lines.push(
2159
+ `\u26A1 ${r.handlerName} on ${r.event} \u2192 [${r.dispatches.join(", ") || "\u2014"}]`
2160
+ );
2161
+ }
2162
+ const errors = entry.slices.filter((sl) => sl.error);
2163
+ if (errors.length > 0) {
2164
+ lines.push("");
2165
+ lines.push("Errors:");
2166
+ for (const sl of errors) {
2167
+ lines.push(` \u26A0 ${sl.name}: ${sl.error}`);
2168
+ }
2169
+ }
2170
+ }
2171
+ return lines.join("\n");
2172
+ }
2173
+ function Diagram({
2174
+ model,
2175
+ warnings,
2176
+ onClickElement,
2177
+ onFixWithAi,
2178
+ toolbarExtra
2179
+ }) {
2180
+ const [tip, setTip] = (0, import_react2.useState)(null);
2181
+ const KIND_TEXT = {
2182
+ event: "text-orange-300",
2183
+ action: "text-blue-300",
2184
+ state: "text-yellow-300",
2185
+ projection: "text-emerald-300",
2186
+ reaction: "text-fuchsia-300",
2187
+ error: "text-red-300"
2188
+ };
2189
+ const [activeTab, setActiveTab] = (0, import_react2.useState)(0);
2190
+ const [showTree, setShowTree] = (0, import_react2.useState)(false);
2191
+ const [showWarnings, setShowWarnings] = (0, import_react2.useState)(false);
2192
+ const warnSet = new Set(warnings.map((w) => w.element).filter(Boolean));
2193
+ const [pan, setPan] = (0, import_react2.useState)({ x: 0, y: 0 });
2194
+ const [zoom, setZoom] = (0, import_react2.useState)(1);
2195
+ const entry = model.entries[activeTab];
2196
+ const viewModel = entry ? {
2197
+ ...model,
2198
+ entries: [entry],
2199
+ states: entry.states,
2200
+ slices: entry.slices,
2201
+ projections: entry.projections,
2202
+ reactions: entry.reactions
2203
+ } : model;
2204
+ (0, import_react2.useEffect)(() => {
2205
+ if (activeTab >= model.entries.length) setActiveTab(0);
2206
+ }, [model.entries.length, activeTab]);
2207
+ const drag = (0, import_react2.useRef)(false);
2208
+ const start = (0, import_react2.useRef)({ x: 0, y: 0, px: 0, py: 0 });
2209
+ const svgContainerRef = (0, import_react2.useRef)(null);
2210
+ const panRafRef = (0, import_react2.useRef)(0);
2211
+ const pendingPanRef = (0, import_react2.useRef)(null);
2212
+ const zoomRafRef = (0, import_react2.useRef)(0);
2213
+ const pendingZoomRef = (0, import_react2.useRef)(null);
2214
+ (0, import_react2.useEffect)(() => {
2215
+ return () => {
2216
+ if (panRafRef.current) cancelAnimationFrame(panRafRef.current);
2217
+ if (zoomRafRef.current) cancelAnimationFrame(zoomRafRef.current);
2218
+ };
2219
+ }, []);
2220
+ (0, import_react2.useEffect)(() => {
2221
+ const el = svgContainerRef.current;
2222
+ if (!el) return;
2223
+ const handler = (e) => {
2224
+ e.preventDefault();
2225
+ const factor = e.deltaY < 0 ? 1.15 : 1 / 1.15;
2226
+ if (pendingZoomRef.current !== null) {
2227
+ pendingZoomRef.current *= factor;
2228
+ } else {
2229
+ pendingZoomRef.current = factor;
2230
+ }
2231
+ if (!zoomRafRef.current) {
2232
+ zoomRafRef.current = requestAnimationFrame(() => {
2233
+ zoomRafRef.current = 0;
2234
+ const f = pendingZoomRef.current;
2235
+ pendingZoomRef.current = null;
2236
+ if (f !== null) {
2237
+ setZoom((z2) => Math.max(0.2, Math.min(3, z2 * f)));
2238
+ }
2239
+ });
2240
+ }
2241
+ };
2242
+ el.addEventListener("wheel", handler, { passive: false });
2243
+ return () => el.removeEventListener("wheel", handler);
2244
+ }, [model]);
2245
+ const onDown = (0, import_react2.useCallback)(
2246
+ (e) => {
2247
+ if (e.button !== 0) return;
2248
+ drag.current = true;
2249
+ start.current = { x: e.clientX, y: e.clientY, px: pan.x, py: pan.y };
2250
+ },
2251
+ [pan]
2252
+ );
2253
+ const onMove = (0, import_react2.useCallback)((e) => {
2254
+ if (!drag.current) return;
2255
+ pendingPanRef.current = {
2256
+ x: start.current.px + (e.clientX - start.current.x),
2257
+ y: start.current.py + (e.clientY - start.current.y)
2258
+ };
2259
+ if (!panRafRef.current) {
2260
+ panRafRef.current = requestAnimationFrame(() => {
2261
+ panRafRef.current = 0;
2262
+ if (pendingPanRef.current !== null) {
2263
+ setPan(pendingPanRef.current);
2264
+ pendingPanRef.current = null;
2265
+ }
2266
+ });
2267
+ }
2268
+ }, []);
2269
+ const onUp = (0, import_react2.useCallback)(() => {
2270
+ drag.current = false;
2271
+ }, []);
2272
+ const { ns, es, boxes, minX, minY, width, height, layoutError } = (0, import_react2.useMemo)(() => {
2273
+ try {
2274
+ return {
2275
+ ...computeLayout(viewModel),
2276
+ layoutError: void 0
2277
+ };
2278
+ } catch (e) {
2279
+ const msg = e instanceof Error ? e.message : String(e);
2280
+ return {
2281
+ ns: [],
2282
+ es: [],
2283
+ boxes: [],
2284
+ minX: 0,
2285
+ minY: 0,
2286
+ width: 100,
2287
+ height: 100,
2288
+ layoutError: msg
2289
+ };
2290
+ }
2291
+ }, [viewModel]);
2292
+ const fitTransform = (0, import_react2.useCallback)(() => {
2293
+ const el = svgContainerRef.current;
2294
+ const cw = el?.clientWidth || 800;
2295
+ const ch = el?.clientHeight || 600;
2296
+ const dw = Math.max(width, 1);
2297
+ const dh = Math.max(height, 1);
2298
+ const fitZoom = Math.min(cw / dw, ch / dh);
2299
+ const z2 = Math.max(0.1, Math.min(3, fitZoom));
2300
+ const px = (cw - dw * z2) / 2 - minX * z2;
2301
+ const py = (ch - dh * z2) / 2 - minY * z2;
2302
+ return { z: z2, px, py };
2303
+ }, [width, height, minX, minY]);
2304
+ const reset = (0, import_react2.useCallback)(() => {
2305
+ const { z: z2, px, py } = fitTransform();
2306
+ setZoom(z2);
2307
+ setPan({ x: px, y: py });
2308
+ }, [fitTransform]);
2309
+ (0, import_react2.useEffect)(() => {
2310
+ const id = requestAnimationFrame(() => reset());
2311
+ return () => cancelAnimationFrame(id);
2312
+ }, [reset]);
2313
+ if (layoutError) {
2314
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: "flex h-full items-center justify-center text-xs text-red-400", children: [
2315
+ "Layout error: ",
2316
+ layoutError
2317
+ ] });
2318
+ }
2319
+ if (viewModel.states.length === 0 && viewModel.projections.length === 0) {
2320
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("div", { className: "flex h-full items-center justify-center text-xs text-zinc-600", children: "Nothing to diagram here" });
2321
+ }
2322
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: "relative flex h-full flex-col bg-zinc-950", children: [
2323
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: "flex items-center gap-1.5 border-b border-zinc-800 bg-zinc-925 px-3 py-1", children: [
2324
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
2325
+ "button",
2326
+ {
2327
+ onClick: () => setZoom((z2) => Math.min(3, z2 * 1.25)),
2328
+ className: "rounded p-1 text-zinc-500 hover:bg-zinc-800 hover:text-zinc-300",
2329
+ title: "Zoom in",
2330
+ children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_lucide_react2.ZoomIn, { size: 13 })
2331
+ }
2332
+ ),
2333
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
2334
+ "button",
2335
+ {
2336
+ onClick: () => setZoom((z2) => Math.max(0.2, z2 / 1.25)),
2337
+ className: "rounded p-1 text-zinc-500 hover:bg-zinc-800 hover:text-zinc-300",
2338
+ title: "Zoom out",
2339
+ children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_lucide_react2.ZoomOut, { size: 13 })
2340
+ }
2341
+ ),
2342
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
2343
+ "button",
2344
+ {
2345
+ onClick: reset,
2346
+ className: "rounded p-1 text-zinc-500 hover:bg-zinc-800 hover:text-zinc-300",
2347
+ title: "Fit",
2348
+ children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_lucide_react2.Maximize2, { size: 13 })
2349
+ }
2350
+ ),
2351
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("span", { className: "text-[9px] text-zinc-600", children: [
2352
+ Math.round(zoom * 100),
2353
+ "%"
2354
+ ] }),
2355
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("div", { className: "h-4 w-px bg-zinc-800" }),
2356
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
2357
+ "button",
2358
+ {
2359
+ onClick: () => setShowTree((v) => !v),
2360
+ className: `rounded p-1 transition ${showTree ? "bg-zinc-700 text-cyan-400" : "text-zinc-500 hover:bg-zinc-800 hover:text-zinc-300"}`,
2361
+ title: "Model tree",
2362
+ children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_lucide_react2.ListTree, { size: 13 })
2363
+ }
2364
+ ),
2365
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: "ml-auto flex items-center gap-1.5", children: [
2366
+ warnings.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
2367
+ "button",
2368
+ {
2369
+ onClick: () => setShowWarnings((v) => !v),
2370
+ className: `flex items-center gap-1 rounded p-1 text-[10px] transition ${showWarnings ? "bg-amber-900/40 text-amber-300" : "text-amber-400 hover:bg-zinc-800"}`,
2371
+ title: "Toggle warnings",
2372
+ children: [
2373
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_lucide_react2.AlertTriangle, { size: 11 }),
2374
+ warnings.length
2375
+ ]
2376
+ }
2377
+ ),
2378
+ toolbarExtra,
2379
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
2380
+ "span",
2381
+ {
2382
+ className: "select-none font-mono text-[9px] text-zinc-600",
2383
+ title: "@rotorsoft/act-diagram version",
2384
+ children: [
2385
+ "v",
2386
+ "0.3.10"
2387
+ ]
2388
+ }
2389
+ )
2390
+ ] })
2391
+ ] }),
2392
+ model.entries.length > 1 && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("div", { className: "flex gap-px border-b border-zinc-800 bg-zinc-900", children: model.entries.map((e, i) => /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
2393
+ "button",
2394
+ {
2395
+ onClick: () => {
2396
+ setActiveTab(i);
2397
+ onClickElement?.(e.path, "file");
2398
+ },
2399
+ className: `px-3 py-1 text-[10px] transition ${i === activeTab ? "border-b-2 border-cyan-500 bg-zinc-950 text-cyan-400" : "text-zinc-500 hover:bg-zinc-800 hover:text-zinc-300"}`,
2400
+ children: e.path
2401
+ },
2402
+ e.path
2403
+ )) }),
2404
+ showTree && /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: "flex max-h-[40%] flex-col border-b border-zinc-800 bg-zinc-950", children: [
2405
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: "flex items-center justify-between border-b border-zinc-800 bg-zinc-900 px-3 py-1", children: [
2406
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: "text-[10px] font-medium text-zinc-400", children: "Model Tree" }),
2407
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
2408
+ "button",
2409
+ {
2410
+ onClick: () => setShowTree(false),
2411
+ className: "rounded p-0.5 text-zinc-500 hover:bg-zinc-800 hover:text-zinc-300",
2412
+ children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_lucide_react2.X, { size: 12 })
2413
+ }
2414
+ )
2415
+ ] }),
2416
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("pre", { className: "flex-1 overflow-auto whitespace-pre px-3 py-2 font-mono text-[10px] leading-relaxed text-zinc-400 select-all", children: formatModelTree(viewModel) })
2417
+ ] }),
2418
+ showWarnings && warnings.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: "flex max-h-[30%] flex-col border-b border-zinc-800 bg-zinc-950", children: [
2419
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: "flex items-center justify-between border-b border-zinc-800 bg-zinc-900 px-3 py-1", children: [
2420
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("span", { className: "text-[10px] font-medium text-amber-400", children: [
2421
+ "Warnings (",
2422
+ warnings.length,
2423
+ ")"
2424
+ ] }),
2425
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: "flex items-center gap-1", children: [
2426
+ onFixWithAi && /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
2427
+ "button",
2428
+ {
2429
+ onClick: () => {
2430
+ const prompt = warnings.map((w) => `- ${w.message}`).join("\n");
2431
+ onFixWithAi(`Fix these issues:
2432
+ ${prompt}`);
2433
+ setShowWarnings(false);
2434
+ },
2435
+ className: "flex items-center gap-1 rounded px-1.5 py-0.5 text-[9px] text-purple-400 hover:bg-zinc-800",
2436
+ title: "Fix all with AI",
2437
+ children: [
2438
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_lucide_react2.Sparkles, { size: 10 }),
2439
+ "Fix all"
2440
+ ]
2441
+ }
2442
+ ),
2443
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
2444
+ "button",
2445
+ {
2446
+ onClick: () => setShowWarnings(false),
2447
+ className: "rounded p-0.5 text-zinc-500 hover:bg-zinc-800 hover:text-zinc-300",
2448
+ children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_lucide_react2.X, { size: 12 })
2449
+ }
2450
+ )
2451
+ ] })
2452
+ ] }),
2453
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("div", { className: "flex-1 overflow-auto px-3 py-2", children: warnings.map((w, i) => /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
2454
+ "div",
2455
+ {
2456
+ className: "flex items-start gap-2 py-0.5 text-[10px]",
2457
+ children: [
2458
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
2459
+ "span",
2460
+ {
2461
+ className: w.severity === "error" ? "text-red-400" : "text-amber-400",
2462
+ children: w.severity === "error" ? "\u25CF" : "\u25B2"
2463
+ }
2464
+ ),
2465
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: "text-zinc-300", children: w.message }),
2466
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: "ml-auto flex shrink-0 items-center gap-1", children: [
2467
+ onFixWithAi && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
2468
+ "button",
2469
+ {
2470
+ onClick: () => {
2471
+ onFixWithAi(`Fix: ${w.message}`);
2472
+ setShowWarnings(false);
2473
+ },
2474
+ className: "text-purple-500 hover:text-purple-300",
2475
+ title: "Fix with AI",
2476
+ children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_lucide_react2.Sparkles, { size: 10 })
2477
+ }
2478
+ ),
2479
+ w.element && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
2480
+ "button",
2481
+ {
2482
+ onClick: () => onClickElement?.(w.element),
2483
+ className: "text-zinc-500 hover:text-zinc-300",
2484
+ children: w.element
2485
+ }
2486
+ )
2487
+ ] })
2488
+ ]
2489
+ },
2490
+ i
2491
+ )) })
2492
+ ] }),
2493
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
2494
+ "div",
2495
+ {
2496
+ ref: svgContainerRef,
2497
+ className: `flex-1 overflow-hidden ${drag.current ? "cursor-grabbing" : "cursor-grab"}`,
2498
+ onMouseDown: onDown,
2499
+ onMouseMove: onMove,
2500
+ onMouseUp: onUp,
2501
+ onMouseLeave: onUp,
2502
+ children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("svg", { width: "100%", height: "100%", className: "select-none", children: /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("g", { transform: `translate(${pan.x},${pan.y}) scale(${zoom})`, children: [
2503
+ boxes.map((b) => {
2504
+ const isError = !!b.error;
2505
+ const boxColor = isError ? COLORS2.error : COLORS2.state;
2506
+ const stripFill = isError ? COLORS2.error.bg : "#a16207";
2507
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("g", { children: [
2508
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
2509
+ "rect",
2510
+ {
2511
+ x: b.x,
2512
+ y: b.y,
2513
+ width: b.w,
2514
+ height: b.h,
2515
+ rx: 8,
2516
+ fill: boxColor.bg,
2517
+ fillOpacity: 0.1,
2518
+ stroke: boxColor.border,
2519
+ strokeWidth: 1.5,
2520
+ strokeOpacity: isError ? 0.7 : 0.4
2521
+ }
2522
+ ),
2523
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("clipPath", { id: `clip-${b.label}`, children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("rect", { x: b.x, y: b.y, width: SLICE_PAD, height: b.h }) }),
2524
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
2525
+ "rect",
2526
+ {
2527
+ x: b.x,
2528
+ y: b.y,
2529
+ width: SLICE_PAD + 8,
2530
+ height: b.h,
2531
+ rx: 8,
2532
+ fill: stripFill,
2533
+ fillOpacity: 0.25,
2534
+ clipPath: `url(#clip-${b.label})`
2535
+ }
2536
+ ),
2537
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
2538
+ "text",
2539
+ {
2540
+ x: b.x + SLICE_PAD / 2,
2541
+ y: b.y + b.h / 2,
2542
+ fill: isError ? COLORS2.error.text : COLORS2.state.text,
2543
+ className: "cursor-pointer text-[10px] font-semibold hover:opacity-80",
2544
+ textAnchor: "middle",
2545
+ dominantBaseline: "central",
2546
+ transform: `rotate(-90, ${b.x + SLICE_PAD / 2}, ${b.y + b.h / 2})`,
2547
+ onClick: () => onClickElement?.(b.label),
2548
+ children: b.label
2549
+ }
2550
+ ),
2551
+ isError && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
2552
+ "foreignObject",
2553
+ {
2554
+ x: b.x + SLICE_PAD + 8,
2555
+ y: b.y + b.h - 28,
2556
+ width: b.w - SLICE_PAD - 16,
2557
+ height: 20,
2558
+ children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
2559
+ "div",
2560
+ {
2561
+ style: {
2562
+ fontSize: 9,
2563
+ fontFamily: "ui-monospace, monospace",
2564
+ color: COLORS2.error.text,
2565
+ lineHeight: 1.4,
2566
+ wordBreak: "break-word",
2567
+ overflow: "hidden",
2568
+ display: "flex",
2569
+ alignItems: "center",
2570
+ height: "100%"
2571
+ },
2572
+ children: b.error.replace(/^.*Error:\s*/, "").replace(/\n.*$/s, "")
2573
+ }
2574
+ )
2575
+ }
2576
+ )
2577
+ ] }, b.label);
2578
+ }),
2579
+ es.map((e, i) => {
2580
+ const dx = e.to.x - e.from.x;
2581
+ const isHint = !e.dash;
2582
+ const d = `M ${e.from.x} ${e.from.y} C ${e.from.x + dx * 0.4} ${e.from.y}, ${e.to.x - dx * 0.4} ${e.to.y}, ${e.to.x} ${e.to.y}`;
2583
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
2584
+ "path",
2585
+ {
2586
+ d,
2587
+ fill: "none",
2588
+ stroke: e.color,
2589
+ strokeWidth: isHint ? 0.75 : 1.5,
2590
+ strokeDasharray: e.dash ? "4,3" : void 0,
2591
+ opacity: isHint ? 0.35 : 0.7,
2592
+ markerEnd: "url(#arr)"
2593
+ },
2594
+ i
2595
+ );
2596
+ }),
2597
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("defs", { children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
2598
+ "marker",
2599
+ {
2600
+ id: "arr",
2601
+ viewBox: "0 0 10 10",
2602
+ refX: "10",
2603
+ refY: "5",
2604
+ markerWidth: "6",
2605
+ markerHeight: "6",
2606
+ orient: "auto-start-reverse",
2607
+ children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
2608
+ "path",
2609
+ {
2610
+ d: "M 0 1 L 8 5 L 0 9",
2611
+ fill: "none",
2612
+ stroke: "#71717a",
2613
+ strokeWidth: "1.5"
2614
+ }
2615
+ )
2616
+ }
2617
+ ) }),
2618
+ ns.map((n, ni) => {
2619
+ const c = COLORS2[n.type];
2620
+ const hasWarn = warnSet.has(n.label);
2621
+ const isState = n.type === "state";
2622
+ const nw = isState ? STATE_W : W;
2623
+ const nh = isState ? STATE_H : H;
2624
+ const lines = splitLabel(n.label, isState ? 10 : 16);
2625
+ const lineH = isState ? STATE_FONT + 2 : 11;
2626
+ const startY = n.pos.y + nh / 2 - (lines.length - 1) * lineH / 2;
2627
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
2628
+ "g",
2629
+ {
2630
+ className: "cursor-pointer",
2631
+ onClick: () => onClickElement?.(n.label, n.type, n.file),
2632
+ onMouseEnter: (ev) => {
2633
+ const sections = [];
2634
+ if (n.emits?.length)
2635
+ sections.push({ label: "Emits", items: n.emits });
2636
+ if (n.handles?.length)
2637
+ sections.push({ label: "Handles", items: n.handles });
2638
+ if (n.guards?.length)
2639
+ sections.push({ label: "Guards", items: n.guards });
2640
+ if (n.reactions?.length)
2641
+ sections.push({ label: "Reactions", items: n.reactions });
2642
+ if (n.projections?.length)
2643
+ sections.push({
2644
+ label: "Projections",
2645
+ items: n.projections
2646
+ });
2647
+ setTip({
2648
+ x: ev.clientX,
2649
+ y: ev.clientY,
2650
+ kind: n.type,
2651
+ title: n.label,
2652
+ schema: n.schema,
2653
+ sections,
2654
+ file: n.file
2655
+ });
2656
+ },
2657
+ onMouseLeave: () => setTip(null),
2658
+ children: [
2659
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
2660
+ "rect",
2661
+ {
2662
+ x: n.pos.x,
2663
+ y: n.pos.y,
2664
+ width: nw,
2665
+ height: nh,
2666
+ rx: isState ? 6 : 4,
2667
+ fill: alpha(c.bg, 0.75),
2668
+ stroke: hasWarn ? "#ef4444" : c.border,
2669
+ strokeWidth: hasWarn ? 2 : 1.5
2670
+ }
2671
+ ),
2672
+ lines.map((line, li) => /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
2673
+ "text",
2674
+ {
2675
+ x: n.pos.x + nw / 2,
2676
+ y: startY + li * lineH,
2677
+ textAnchor: "middle",
2678
+ dominantBaseline: "central",
2679
+ fill: c.text,
2680
+ className: isState ? "text-[10px] font-semibold" : "text-[8px] font-medium",
2681
+ children: line
2682
+ },
2683
+ li
2684
+ )),
2685
+ (() => {
2686
+ let ix = n.pos.x + nw - 13;
2687
+ const icons = [];
2688
+ if (n.guards?.length) {
2689
+ icons.unshift(
2690
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
2691
+ "g",
2692
+ {
2693
+ transform: `translate(${ix - 2},${n.pos.y})`,
2694
+ className: "cursor-pointer",
2695
+ pointerEvents: "all",
2696
+ onClick: (e) => {
2697
+ e.stopPropagation();
2698
+ onClickElement?.(n.guards[0], "guard");
2699
+ },
2700
+ onMouseEnter: (ev) => {
2701
+ ev.stopPropagation();
2702
+ setTip({
2703
+ x: ev.clientX,
2704
+ y: ev.clientY,
2705
+ t: `Guards: ${n.guards.join(", ")}`
2706
+ });
2707
+ },
2708
+ onMouseLeave: (ev) => {
2709
+ ev.stopPropagation();
2710
+ setTip(null);
2711
+ },
2712
+ children: [
2713
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
2714
+ "rect",
2715
+ {
2716
+ x: "-1",
2717
+ y: "-1",
2718
+ width: "14",
2719
+ height: "14",
2720
+ fill: "transparent"
2721
+ }
2722
+ ),
2723
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
2724
+ "path",
2725
+ {
2726
+ d: "M5 3L1 5v3c0 2.5 1.7 4.8 4 5.5 2.3-.7 4-3 4-5.5V5L5 3z",
2727
+ fill: "none",
2728
+ stroke: "#ef4444",
2729
+ strokeWidth: "1.2"
2730
+ }
2731
+ )
2732
+ ]
2733
+ },
2734
+ "g"
2735
+ )
2736
+ );
2737
+ ix -= 14;
2738
+ }
2739
+ if (n.projections?.length) {
2740
+ icons.unshift(
2741
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
2742
+ "g",
2743
+ {
2744
+ transform: `translate(${ix - 2},${n.pos.y})`,
2745
+ className: "cursor-pointer",
2746
+ pointerEvents: "all",
2747
+ onClick: (e) => {
2748
+ e.stopPropagation();
2749
+ onClickElement?.(n.projections[0], "projection");
2750
+ },
2751
+ onMouseEnter: (ev) => {
2752
+ ev.stopPropagation();
2753
+ setTip({
2754
+ x: ev.clientX,
2755
+ y: ev.clientY,
2756
+ t: `Projection: ${n.projections.join(", ")}`
2757
+ });
2758
+ },
2759
+ onMouseLeave: (ev) => {
2760
+ ev.stopPropagation();
2761
+ setTip(null);
2762
+ },
2763
+ children: [
2764
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
2765
+ "rect",
2766
+ {
2767
+ x: "-1",
2768
+ y: "-1",
2769
+ width: "14",
2770
+ height: "14",
2771
+ fill: "transparent"
2772
+ }
2773
+ ),
2774
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
2775
+ "rect",
2776
+ {
2777
+ x: "1",
2778
+ y: "3",
2779
+ width: "8",
2780
+ height: "6",
2781
+ rx: "1",
2782
+ fill: "none",
2783
+ stroke: COLORS2.projection.text,
2784
+ strokeWidth: "1"
2785
+ }
2786
+ ),
2787
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
2788
+ "line",
2789
+ {
2790
+ x1: "3",
2791
+ y1: "9",
2792
+ x2: "7",
2793
+ y2: "9",
2794
+ stroke: COLORS2.projection.text,
2795
+ strokeWidth: "1"
2796
+ }
2797
+ ),
2798
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
2799
+ "line",
2800
+ {
2801
+ x1: "5",
2802
+ y1: "9",
2803
+ x2: "5",
2804
+ y2: "11",
2805
+ stroke: COLORS2.projection.text,
2806
+ strokeWidth: "1"
2807
+ }
2808
+ )
2809
+ ]
2810
+ },
2811
+ "p"
2812
+ )
2813
+ );
2814
+ ix -= 14;
2815
+ }
2816
+ if (n.reactions?.length) {
2817
+ icons.unshift(
2818
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
2819
+ "g",
2820
+ {
2821
+ transform: `translate(${ix - 2},${n.pos.y})`,
2822
+ className: "cursor-pointer",
2823
+ pointerEvents: "all",
2824
+ onClick: (e) => {
2825
+ e.stopPropagation();
2826
+ onClickElement?.(n.reactions[0], "reaction");
2827
+ },
2828
+ onMouseEnter: (ev) => {
2829
+ ev.stopPropagation();
2830
+ setTip({
2831
+ x: ev.clientX,
2832
+ y: ev.clientY,
2833
+ t: `Reactions: ${n.reactions.join(", ")}`
2834
+ });
2835
+ },
2836
+ onMouseLeave: (ev) => {
2837
+ ev.stopPropagation();
2838
+ setTip(null);
2839
+ },
2840
+ children: [
2841
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
2842
+ "rect",
2843
+ {
2844
+ x: "-1",
2845
+ y: "-1",
2846
+ width: "14",
2847
+ height: "14",
2848
+ fill: "transparent"
2849
+ }
2850
+ ),
2851
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
2852
+ "path",
2853
+ {
2854
+ d: "M6 2L2 7h3L4 12L8 7H5L6 2z",
2855
+ fill: COLORS2.reaction.text
2856
+ }
2857
+ )
2858
+ ]
2859
+ },
2860
+ "r"
2861
+ )
2862
+ );
2863
+ }
2864
+ return icons;
2865
+ })()
2866
+ ]
2867
+ },
2868
+ `${n.key}:${ni}`
2869
+ );
2870
+ })
2871
+ ] }) })
2872
+ }
2873
+ ),
2874
+ tip && /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
2875
+ "div",
2876
+ {
2877
+ className: "pointer-events-none fixed z-50 max-w-sm rounded-lg border border-zinc-700 bg-zinc-900 px-3 py-2 shadow-2xl",
2878
+ style: { left: tip.x + 14, top: tip.y - 12 },
2879
+ children: [
2880
+ tip.t && tip.t.split("\n").map((line, i) => /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
2881
+ "div",
2882
+ {
2883
+ className: i === 0 ? "text-[11px] font-medium text-zinc-200" : "mt-0.5 text-[9px] text-zinc-400",
2884
+ children: i > 0 && line.includes(":") ? /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(import_jsx_runtime2.Fragment, { children: [
2885
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("span", { className: "text-zinc-500", children: [
2886
+ line.split(":")[0],
2887
+ ":"
2888
+ ] }),
2889
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: "text-zinc-300", children: line.slice(line.indexOf(":") + 1) })
2890
+ ] }) : line
2891
+ },
2892
+ i
2893
+ )),
2894
+ tip.title && tip.kind && /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(import_jsx_runtime2.Fragment, { children: [
2895
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: "flex items-baseline gap-1.5", children: [
2896
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
2897
+ "span",
2898
+ {
2899
+ className: `text-[9px] font-medium uppercase tracking-wide ${KIND_TEXT[tip.kind]}`,
2900
+ children: tip.kind
2901
+ }
2902
+ ),
2903
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: "text-[12px] font-semibold text-zinc-100", children: tip.title })
2904
+ ] }),
2905
+ tip.schema && /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: "mt-1.5", children: [
2906
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("div", { className: "text-[9px] uppercase tracking-wide text-zinc-500", children: "Schema" }),
2907
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("pre", { className: "mt-0.5 max-h-48 overflow-auto rounded border border-zinc-800 bg-zinc-950 px-2 py-1 font-mono text-[10px] leading-snug text-zinc-300 whitespace-pre", children: tip.schema })
2908
+ ] }),
2909
+ tip.sections && tip.sections.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("table", { className: "mt-1.5 w-full text-[10px] leading-snug", children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("tbody", { children: tip.sections.map((s) => /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("tr", { children: [
2910
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("td", { className: "w-[68px] shrink-0 pr-2 align-top text-zinc-500", children: s.label }),
2911
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("td", { className: "align-top text-zinc-300", children: s.items.join(", ") })
2912
+ ] }, s.label)) }) }),
2913
+ tip.file && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("div", { className: "mt-1.5 border-t border-zinc-800 pt-1 text-[9px] text-zinc-500", children: tip.file })
2914
+ ] })
2915
+ ]
2916
+ }
2917
+ )
2918
+ ] });
2919
+ }
2920
+
2921
+ // src/client/components/ActDiagram.tsx
2922
+ var import_jsx_runtime3 = require("react/jsx-runtime");
2923
+ var emptyModel = {
2924
+ entries: [],
2925
+ states: [],
2926
+ slices: [],
2927
+ projections: [],
2928
+ reactions: []
2929
+ };
2930
+ function useExtractModel(files) {
2931
+ const [result, setResult] = (0, import_react3.useState)({ model: emptyModel, warnings: [] });
2932
+ const lastGoodRef = (0, import_react3.useRef)(null);
2933
+ (0, import_react3.useEffect)(() => {
2934
+ if (files.length === 0) {
2935
+ lastGoodRef.current = null;
2936
+ setResult({ model: emptyModel, warnings: [] });
2937
+ return;
2938
+ }
2939
+ const timer = setTimeout(() => {
2940
+ const { model, error } = extractModel(files);
2941
+ const warnings = validate(model);
2942
+ const hasErrors = !!error || model.slices.some((s) => !!s.error);
2943
+ if (!hasErrors) {
2944
+ const next = { model, warnings };
2945
+ lastGoodRef.current = next;
2946
+ setResult(next);
2947
+ } else if (lastGoodRef.current) {
2948
+ } else {
2949
+ setResult({ model, warnings });
2950
+ }
2951
+ }, 500);
2952
+ return () => clearTimeout(timer);
2953
+ }, [files]);
2954
+ return result;
2955
+ }
2956
+ function ActDiagram({
2957
+ files: propFiles,
2958
+ onNavigate,
2959
+ usePostMessage,
2960
+ onAiRequest,
2961
+ generating
2962
+ }) {
2963
+ const [msgFiles, setMsgFiles] = (0, import_react3.useState)([]);
2964
+ const files = propFiles ?? msgFiles;
2965
+ (0, import_react3.useEffect)(() => {
2966
+ if (!usePostMessage) return;
2967
+ const handler = (e) => {
2968
+ const msg = e.data;
2969
+ if (!msg?.type) return;
2970
+ switch (msg.type) {
2971
+ case "files":
2972
+ setMsgFiles(msg.files);
2973
+ break;
2974
+ case "fileAdded":
2975
+ setMsgFiles((prev) => [
2976
+ ...prev,
2977
+ { path: msg.path, content: msg.content }
2978
+ ]);
2979
+ break;
2980
+ case "fileChanged":
2981
+ setMsgFiles((prev) => {
2982
+ const idx = prev.findIndex((f) => f.path === msg.path);
2983
+ if (idx < 0) return prev;
2984
+ const next = [...prev];
2985
+ next[idx] = { path: msg.path, content: msg.content };
2986
+ return next;
2987
+ });
2988
+ break;
2989
+ case "fileDeleted":
2990
+ setMsgFiles((prev) => prev.filter((f) => f.path !== msg.path));
2991
+ break;
2992
+ }
2993
+ };
2994
+ window.addEventListener("message", handler);
2995
+ return () => window.removeEventListener("message", handler);
2996
+ }, [usePostMessage]);
2997
+ const { model, warnings } = useExtractModel(files);
2998
+ const handleClick = (0, import_react3.useCallback)(
2999
+ (name, type, file) => {
3000
+ if (!onNavigate) return;
3001
+ const result = navigateToCode(files, name, type, file);
3002
+ if (result) onNavigate(result.file, result.line, result.col, type);
3003
+ },
3004
+ [files, onNavigate]
3005
+ );
3006
+ return /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "flex h-full flex-col", children: [
3007
+ onAiRequest && /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
3008
+ AiBar,
3009
+ {
3010
+ onSubmit: (prompt, options) => onAiRequest(prompt, files, options),
3011
+ generating
3012
+ }
3013
+ ),
3014
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
3015
+ Diagram,
3016
+ {
3017
+ model,
3018
+ warnings,
3019
+ onClickElement: handleClick,
3020
+ onFixWithAi: onAiRequest ? (prompt) => onAiRequest(prompt, files, {
3021
+ model: "claude-sonnet-4-6",
3022
+ maxTokens: 16384
3023
+ }) : void 0
3024
+ }
3025
+ )
3026
+ ] });
3027
+ }
3028
+
3029
+ // src/client/components/Logo.tsx
3030
+ var import_jsx_runtime4 = require("react/jsx-runtime");
3031
+ function Logo({ size = 24 }) {
3032
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(
3033
+ "svg",
3034
+ {
3035
+ width: size,
3036
+ height: size,
3037
+ viewBox: "0 0 32 32",
3038
+ fill: "none",
3039
+ xmlns: "http://www.w3.org/2000/svg",
3040
+ children: [
3041
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
3042
+ "rect",
3043
+ {
3044
+ x: "3",
3045
+ y: "3",
3046
+ width: "26",
3047
+ height: "26",
3048
+ rx: "3",
3049
+ stroke: "currentColor",
3050
+ strokeWidth: "2",
3051
+ className: "text-blue-400"
3052
+ }
3053
+ ),
3054
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
3055
+ "rect",
3056
+ {
3057
+ x: "7",
3058
+ y: "7",
3059
+ width: "8",
3060
+ height: "6",
3061
+ rx: "1.5",
3062
+ fill: "currentColor",
3063
+ className: "text-amber-400"
3064
+ }
3065
+ ),
3066
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
3067
+ "rect",
3068
+ {
3069
+ x: "17",
3070
+ y: "7",
3071
+ width: "8",
3072
+ height: "6",
3073
+ rx: "1.5",
3074
+ fill: "currentColor",
3075
+ className: "text-orange-500"
3076
+ }
3077
+ ),
3078
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
3079
+ "rect",
3080
+ {
3081
+ x: "7",
3082
+ y: "19",
3083
+ width: "8",
3084
+ height: "6",
3085
+ rx: "1.5",
3086
+ fill: "currentColor",
3087
+ className: "text-blue-500"
3088
+ }
3089
+ ),
3090
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
3091
+ "path",
3092
+ {
3093
+ d: "M17 22h5l-2-2M20 24l2-2",
3094
+ stroke: "currentColor",
3095
+ strokeWidth: "1.5",
3096
+ strokeLinecap: "round",
3097
+ strokeLinejoin: "round",
3098
+ className: "text-purple-400"
3099
+ }
3100
+ ),
3101
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
3102
+ "path",
3103
+ {
3104
+ d: "M15 10h2M11 13v6",
3105
+ stroke: "currentColor",
3106
+ strokeWidth: "1.5",
3107
+ strokeLinecap: "round",
3108
+ className: "text-zinc-500"
3109
+ }
3110
+ )
3111
+ ]
3112
+ }
3113
+ );
3114
+ }
3115
+
3116
+ // src/client/components/Tooltip.tsx
3117
+ var import_react4 = require("react");
3118
+ var import_react_dom = require("react-dom");
3119
+ var import_jsx_runtime5 = require("react/jsx-runtime");
3120
+ function Tooltip({
3121
+ title,
3122
+ description,
3123
+ details,
3124
+ children,
3125
+ position = "bottom",
3126
+ align = "center"
3127
+ }) {
3128
+ const [show, setShow] = (0, import_react4.useState)(false);
3129
+ const [coords, setCoords] = (0, import_react4.useState)({ x: 0, y: 0, w: 0 });
3130
+ const timeout = (0, import_react4.useRef)(void 0);
3131
+ const ref = (0, import_react4.useRef)(null);
3132
+ const onEnter = (0, import_react4.useCallback)(() => {
3133
+ timeout.current = setTimeout(() => {
3134
+ if (ref.current) {
3135
+ const r = ref.current.getBoundingClientRect();
3136
+ setCoords({
3137
+ x: r.left,
3138
+ y: position === "top" ? r.top : r.bottom,
3139
+ w: r.width
3140
+ });
3141
+ }
3142
+ setShow(true);
3143
+ }, 400);
3144
+ }, [position]);
3145
+ const onLeave = (0, import_react4.useCallback)(() => {
3146
+ clearTimeout(timeout.current);
3147
+ setShow(false);
3148
+ }, []);
3149
+ const left = align === "right" ? void 0 : align === "left" ? coords.x : coords.x + coords.w / 2;
3150
+ const right = align === "right" ? window.innerWidth - coords.x - coords.w : void 0;
3151
+ return /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(
3152
+ "div",
3153
+ {
3154
+ ref,
3155
+ className: "relative inline-flex",
3156
+ onMouseEnter: onEnter,
3157
+ onMouseLeave: onLeave,
3158
+ children: [
3159
+ children,
3160
+ show && (0, import_react_dom.createPortal)(
3161
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(
3162
+ "div",
3163
+ {
3164
+ className: `pointer-events-none fixed z-[100] rounded-lg border border-zinc-700 bg-zinc-900 shadow-xl ${details ? "w-80 px-3.5 py-3" : "max-w-52 px-2.5 py-1.5"} ${align === "center" ? "-translate-x-1/2" : ""}`,
3165
+ style: {
3166
+ top: position === "top" ? void 0 : coords.y + 6,
3167
+ bottom: position === "top" ? window.innerHeight - coords.y + 6 : void 0,
3168
+ left,
3169
+ right
3170
+ },
3171
+ children: [
3172
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("div", { className: "text-[11px] font-semibold text-zinc-100", children: title }),
3173
+ description && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("div", { className: "mt-0.5 text-[10px] leading-relaxed text-zinc-500", children: description }),
3174
+ details && details.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("table", { className: "mt-2 w-full border-t border-zinc-800 text-[10px] leading-snug", children: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("tbody", { children: details.map((d, i) => /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("tr", { className: i === 0 ? "first:*:pt-2" : "", children: [
3175
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("td", { className: "w-[52px] shrink-0 pr-2 pt-1.5 text-right align-top font-medium text-zinc-400", children: d.label }),
3176
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("td", { className: "pt-1.5 align-top text-zinc-500", children: d.text })
3177
+ ] }, i)) }) })
3178
+ ]
3179
+ }
3180
+ ),
3181
+ document.body
3182
+ )
3183
+ ]
3184
+ }
3185
+ );
3186
+ }
3187
+
3188
+ // src/client/lib/strip-fences.ts
3189
+ function parseMultiFileResponse(raw) {
3190
+ const files = [];
3191
+ const re = /```(?:typescript|ts):([^\n]+)\n([\s\S]*?)```/g;
3192
+ let m;
3193
+ while ((m = re.exec(raw)) !== null) {
3194
+ const path = m[1].trim();
3195
+ const content = m[2].trim();
3196
+ if (path && content) {
3197
+ files.push({ path, content });
3198
+ }
3199
+ }
3200
+ if (files.length === 0) {
3201
+ const code = stripFences(raw);
3202
+ if (code.trim()) {
3203
+ files.push({ path: "src/app.ts", content: code });
3204
+ }
3205
+ }
3206
+ return files;
3207
+ }
3208
+ function stripFences(code) {
3209
+ let result = code.replace(/```(?:typescript|ts)?\s*\n/g, "");
3210
+ result = result.replace(/\n?```\s*$/g, "");
3211
+ result = result.replace(
3212
+ /^[\s\S]*?(?=\/\*\*|\/\/|import\b|export\b|const\b|let\b|var\b|type\b|interface\b|function\b)/,
3213
+ ""
3214
+ );
3215
+ const lines = result.split("\n");
3216
+ let lastCodeLine = lines.length - 1;
3217
+ while (lastCodeLine > 0) {
3218
+ const trimmed = lines[lastCodeLine].trim();
3219
+ if (trimmed && /[;{})\]:]$|^\s*\/\/|^\s*\*\/|^\s*\*|^$/.test(trimmed))
3220
+ break;
3221
+ lastCodeLine--;
3222
+ }
3223
+ if (lastCodeLine < lines.length - 1) {
3224
+ result = lines.slice(0, lastCodeLine + 1).join("\n");
3225
+ }
3226
+ return result.trim();
3227
+ }
3228
+ function deriveProjectName(prompt, code) {
3229
+ if (code) {
3230
+ const actMatch = code.match(/(?:const|let|var)\s+(\w+)\s*=\s*act\s*\(/);
3231
+ if (actMatch) return actMatch[1];
3232
+ const stateMatch = code.match(/state\(\s*\{\s*(\w+)/);
3233
+ if (stateMatch) return stateMatch[1] + " App";
3234
+ }
3235
+ const words = prompt.replace(/[^\w\s]/g, "").split(/\s+/).filter((w) => w.length > 2).slice(0, 3);
3236
+ return words.length > 0 ? words.map((w) => w[0].toUpperCase() + w.slice(1).toLowerCase()).join(" ") : "Generated App";
3237
+ }
3238
+
3239
+ // src/client/types/domain-model.ts
3240
+ function emptyModel2() {
3241
+ return {
3242
+ entries: [],
3243
+ states: [],
3244
+ slices: [],
3245
+ projections: [],
3246
+ reactions: [],
3247
+ orchestrator: void 0
3248
+ };
3249
+ }
3250
+ // Annotate the CommonJS export names for ESM import in node:
3251
+ 0 && (module.exports = {
3252
+ ActDiagram,
3253
+ AiBar,
3254
+ Diagram,
3255
+ Logo,
3256
+ Tooltip,
3257
+ buildModel,
3258
+ computeLayout,
3259
+ deriveProjectName,
3260
+ emptyModel,
3261
+ extractModel,
3262
+ navigateToCode,
3263
+ parseMultiFileResponse,
3264
+ stripFences,
3265
+ topoSort,
3266
+ validate
3267
+ });
3268
+ //# sourceMappingURL=index.cjs.map