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