@canonical/summon 0.29.0 → 0.31.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 (99) hide show
  1. package/dist/generators/example/hello/index.d.ts +18 -0
  2. package/dist/generators/example/hello/index.js +104 -0
  3. package/dist/generators/example/hello/index.js.map +1 -0
  4. package/dist/generators/example/webapp/index.d.ts +22 -0
  5. package/dist/generators/example/webapp/index.js +374 -0
  6. package/dist/generators/example/webapp/index.js.map +1 -0
  7. package/dist/generators/init/index.d.ts +16 -0
  8. package/dist/generators/init/index.js +98 -0
  9. package/dist/generators/init/index.js.map +1 -0
  10. package/dist/src/bin.d.ts +10 -0
  11. package/dist/src/bin.js +153 -0
  12. package/dist/src/bin.js.map +1 -0
  13. package/dist/src/completion.d.ts +63 -0
  14. package/dist/src/completion.js +375 -0
  15. package/dist/src/completion.js.map +1 -0
  16. package/dist/src/components/App.d.ts +48 -0
  17. package/dist/src/components/App.js +621 -0
  18. package/dist/src/components/App.js.map +1 -0
  19. package/dist/src/components/ExecutionProgress.d.ts +27 -0
  20. package/dist/src/components/ExecutionProgress.js +132 -0
  21. package/dist/src/components/ExecutionProgress.js.map +1 -0
  22. package/dist/src/components/FileTreePreview.d.ts +13 -0
  23. package/dist/src/components/FileTreePreview.js +55 -0
  24. package/dist/src/components/FileTreePreview.js.map +1 -0
  25. package/dist/src/components/PromptSequence.d.ts +22 -0
  26. package/dist/src/components/PromptSequence.js +215 -0
  27. package/dist/src/components/PromptSequence.js.map +1 -0
  28. package/dist/src/components/Spinner.d.ts +12 -0
  29. package/dist/src/components/Spinner.js +20 -0
  30. package/dist/src/components/Spinner.js.map +1 -0
  31. package/{src/components/index.ts → dist/src/components/index.d.ts} +0 -1
  32. package/dist/src/components/index.js +11 -0
  33. package/dist/src/components/index.js.map +1 -0
  34. package/dist/src/discovery/index.js +2 -0
  35. package/dist/src/discovery/index.js.map +1 -0
  36. package/dist/src/discovery/loadGenerator.d.ts +13 -0
  37. package/dist/src/discovery/loadGenerator.js +29 -0
  38. package/dist/src/discovery/loadGenerator.js.map +1 -0
  39. package/dist/src/display/index.js +3 -0
  40. package/dist/src/display/index.js.map +1 -0
  41. package/dist/src/display/printGeneratorHelp.d.ts +9 -0
  42. package/dist/src/display/printGeneratorHelp.js +99 -0
  43. package/dist/src/display/printGeneratorHelp.js.map +1 -0
  44. package/dist/src/display/printNode.d.ts +7 -0
  45. package/dist/src/display/printNode.js +64 -0
  46. package/dist/src/display/printNode.js.map +1 -0
  47. package/dist/src/registration/buildCommandBarrel.d.ts +11 -0
  48. package/dist/src/registration/buildCommandBarrel.js +45 -0
  49. package/dist/src/registration/buildCommandBarrel.js.map +1 -0
  50. package/dist/src/registration/index.js +3 -0
  51. package/dist/src/registration/index.js.map +1 -0
  52. package/dist/src/registration/registerFromBarrel.d.ts +16 -0
  53. package/dist/src/registration/registerFromBarrel.js +408 -0
  54. package/dist/src/registration/registerFromBarrel.js.map +1 -0
  55. package/dist/src/registration/types.d.ts +26 -0
  56. package/dist/src/registration/types.js +2 -0
  57. package/dist/src/registration/types.js.map +1 -0
  58. package/dist/src/ui/index.d.ts +24 -0
  59. package/dist/src/ui/index.js +29 -0
  60. package/dist/src/ui/index.js.map +1 -0
  61. package/package.json +23 -15
  62. package/generators/application/react/index.ts +0 -4
  63. package/generators/domain/index.ts +0 -4
  64. package/generators/example/hello/index.ts +0 -126
  65. package/generators/example/webapp/index.ts +0 -511
  66. package/generators/init/index.ts +0 -119
  67. package/generators/route/index.ts +0 -4
  68. package/generators/wrapper/index.ts +0 -4
  69. package/src/bin.tsx +0 -199
  70. package/src/completion.test.ts +0 -202
  71. package/src/completion.ts +0 -492
  72. package/src/components/App.tsx +0 -1053
  73. package/src/components/ExecutionProgress.tsx +0 -209
  74. package/src/components/FileTreePreview.tsx +0 -97
  75. package/src/components/PromptSequence.tsx +0 -483
  76. package/src/components/Spinner.tsx +0 -36
  77. package/src/discovery/loadGenerator.ts +0 -37
  78. package/src/display/printGeneratorHelp.ts +0 -128
  79. package/src/display/printNode.ts +0 -76
  80. package/src/registration/buildCommandBarrel.ts +0 -57
  81. package/src/registration/registerFromBarrel.tsx +0 -548
  82. package/src/registration/types.ts +0 -28
  83. /package/{generators → dist/generators}/example/hello/templates/README.md.ejs +0 -0
  84. /package/{generators → dist/generators}/example/hello/templates/index.ts.ejs +0 -0
  85. /package/{generators → dist/generators}/example/webapp/templates/ARCHITECTURE.md.ejs +0 -0
  86. /package/{generators → dist/generators}/example/webapp/templates/App.tsx.ejs +0 -0
  87. /package/{generators → dist/generators}/example/webapp/templates/README.md.ejs +0 -0
  88. /package/{generators → dist/generators}/example/webapp/templates/app.test.ts.ejs +0 -0
  89. /package/{generators → dist/generators}/example/webapp/templates/app.ts.ejs +0 -0
  90. /package/{generators → dist/generators}/example/webapp/templates/feature.ts.ejs +0 -0
  91. /package/{generators → dist/generators}/example/webapp/templates/index.html.ejs +0 -0
  92. /package/{generators → dist/generators}/example/webapp/templates/main.tsx.ejs +0 -0
  93. /package/{generators → dist/generators}/example/webapp/templates/styles.css.ejs +0 -0
  94. /package/{generators → dist/generators}/init/templates/generator.ts.ejs +0 -0
  95. /package/{generators → dist/generators}/init/templates/template-index.ts.ejs +0 -0
  96. /package/{generators → dist/generators}/init/templates/template-test.ts.ejs +0 -0
  97. /package/{src/discovery/index.ts → dist/src/discovery/index.d.ts} +0 -0
  98. /package/{src/display/index.ts → dist/src/display/index.d.ts} +0 -0
  99. /package/{src/registration/index.ts → dist/src/registration/index.d.ts} +0 -0
@@ -1,1053 +0,0 @@
1
- /**
2
- * App Component
3
- *
4
- * Main CLI application component using React Ink.
5
- */
6
-
7
- import { formatContentPreview } from "@canonical/cli-core";
8
- import type {
9
- GeneratorDefinition,
10
- PromptDefinition,
11
- StampConfig,
12
- } from "@canonical/summon-core";
13
- import {
14
- dryRun,
15
- type Effect,
16
- runUndo,
17
- type Task,
18
- type TaskError,
19
- } from "@canonical/task";
20
- import { Box, Text, useApp, useInput } from "ink";
21
- import { useCallback, useEffect, useState } from "react";
22
- import { ExecutionProgress, type TimedEffect } from "./ExecutionProgress.js";
23
- import { PromptSequence } from "./PromptSequence.js";
24
- import { Spinner } from "./Spinner.js";
25
-
26
- // =============================================================================
27
- // Effect Tree - Hierarchical display with action labels and tree connectors
28
- // =============================================================================
29
-
30
- interface GroupedEffects {
31
- files: Effect[];
32
- directories: Effect[];
33
- commands: Effect[];
34
- logs: Effect[];
35
- }
36
-
37
- /**
38
- * Group effects by category for display.
39
- * @param effects - The effects to group
40
- * @param verbose - If true, include debug logs
41
- */
42
- const groupEffects = (effects: Effect[], verbose = false): GroupedEffects => {
43
- const groups: GroupedEffects = {
44
- files: [],
45
- directories: [],
46
- commands: [],
47
- logs: [],
48
- };
49
-
50
- for (const effect of effects) {
51
- switch (effect._tag) {
52
- case "WriteFile":
53
- case "AppendFile":
54
- case "CopyFile":
55
- case "CopyDirectory":
56
- case "DeleteFile":
57
- groups.files.push(effect);
58
- break;
59
- case "MakeDir":
60
- case "DeleteDirectory":
61
- groups.directories.push(effect);
62
- break;
63
- case "Exec":
64
- groups.commands.push(effect);
65
- break;
66
- case "Log":
67
- // Filter out debug logs unless verbose is enabled
68
- if (effect.level !== "debug" || verbose) {
69
- groups.logs.push(effect);
70
- }
71
- break;
72
- // Ignore internal effects: ReadFile, Exists, Glob, ReadContext, WriteContext, Parallel, Race
73
- }
74
- }
75
-
76
- return groups;
77
- };
78
-
79
- /**
80
- * Get human-readable action label for an effect.
81
- */
82
- const getActionLabel = (effect: Effect): string => {
83
- switch (effect._tag) {
84
- case "WriteFile":
85
- return "Created file";
86
- case "AppendFile":
87
- return "Appended to";
88
- case "MakeDir":
89
- return "Created dir";
90
- case "CopyFile":
91
- return "Copied file";
92
- case "CopyDirectory":
93
- return "Copied dir";
94
- case "DeleteFile":
95
- return "Deleted file";
96
- case "DeleteDirectory":
97
- return "Deleted dir";
98
- case "Exec":
99
- return "Executed";
100
- case "Log":
101
- switch (effect.level) {
102
- case "debug":
103
- return "Debug";
104
- case "info":
105
- return "Info";
106
- case "warn":
107
- return "Warning";
108
- case "error":
109
- return "Error";
110
- default:
111
- return "Log";
112
- }
113
- default:
114
- return effect._tag;
115
- }
116
- };
117
-
118
- /**
119
- * Get color for action label based on effect type.
120
- */
121
- const getActionColor = (
122
- effect: Effect,
123
- ): "green" | "red" | "yellow" | "cyan" | "blue" | "magenta" | undefined => {
124
- switch (effect._tag) {
125
- case "WriteFile":
126
- case "MakeDir":
127
- return "green";
128
- case "AppendFile":
129
- return "magenta";
130
- case "DeleteFile":
131
- case "DeleteDirectory":
132
- return "red";
133
- case "CopyFile":
134
- case "CopyDirectory":
135
- return "cyan";
136
- case "Exec":
137
- return "yellow";
138
- case "Log":
139
- switch (effect.level) {
140
- case "error":
141
- return "red";
142
- case "warn":
143
- return "yellow";
144
- case "debug":
145
- return undefined; // dim by default
146
- default:
147
- return "blue";
148
- }
149
- default:
150
- return undefined;
151
- }
152
- };
153
-
154
- /**
155
- * Get the payload (description) for an effect.
156
- */
157
- const getEffectPayload = (effect: Effect): string => {
158
- switch (effect._tag) {
159
- case "WriteFile":
160
- return effect.path;
161
- case "AppendFile":
162
- return effect.path;
163
- case "MakeDir":
164
- return effect.path;
165
- case "CopyFile":
166
- return `${effect.source} → ${effect.dest}`;
167
- case "CopyDirectory":
168
- return `${effect.source}/ → ${effect.dest}/`;
169
- case "DeleteFile":
170
- case "DeleteDirectory":
171
- return effect.path;
172
- case "Exec":
173
- return `${effect.command} ${effect.args.join(" ")}`;
174
- case "Log":
175
- return effect.message;
176
- default:
177
- return effect._tag;
178
- }
179
- };
180
-
181
- // Fixed width for action label column (padded to align payloads)
182
- const ACTION_LABEL_WIDTH = 14;
183
-
184
- /**
185
- * Render a single effect as a tree row with action label and payload.
186
- */
187
- const EffectTreeRow = ({
188
- effect,
189
- isLast,
190
- }: {
191
- effect: Effect;
192
- isLast: boolean;
193
- }) => {
194
- const connector = isLast ? "└─" : "├─";
195
- const actionLabel = getActionLabel(effect);
196
- const color = getActionColor(effect);
197
- const payload = getEffectPayload(effect);
198
-
199
- return (
200
- <Box>
201
- <Text dimColor>{connector} </Text>
202
- <Text color={color}>{actionLabel.padEnd(ACTION_LABEL_WIDTH)}</Text>
203
- <Text>{payload}</Text>
204
- </Box>
205
- );
206
- };
207
-
208
- /**
209
- * Render a section of the effect tree (e.g., Files, Directories).
210
- */
211
- const EffectTreeSection = ({
212
- title,
213
- effects,
214
- }: {
215
- title: string;
216
- effects: Effect[];
217
- }) => {
218
- if (effects.length === 0) {
219
- return null;
220
- }
221
-
222
- return (
223
- <Box flexDirection="column" marginTop={1}>
224
- <Text bold dimColor>
225
- {title}:
226
- </Text>
227
- <Box flexDirection="column" marginLeft={1}>
228
- {effects.map((effect, index) => (
229
- <EffectTreeRow
230
- key={`${effect._tag}:${getEffectPayload(effect)}`}
231
- effect={effect}
232
- isLast={index === effects.length - 1}
233
- />
234
- ))}
235
- </Box>
236
- </Box>
237
- );
238
- };
239
-
240
- /**
241
- * Render a tree view of completed effects, grouped by category.
242
- */
243
- const _EffectTree = ({ effects }: { effects: Effect[] }) => {
244
- const groups = groupEffects(effects);
245
- const hasAnyEffects =
246
- groups.files.length > 0 ||
247
- groups.directories.length > 0 ||
248
- groups.commands.length > 0 ||
249
- groups.logs.length > 0;
250
-
251
- if (!hasAnyEffects) {
252
- return null;
253
- }
254
-
255
- return (
256
- <Box flexDirection="column">
257
- <EffectTreeSection title="Files" effects={groups.files} />
258
- <EffectTreeSection title="Directories" effects={groups.directories} />
259
- <EffectTreeSection title="Commands" effects={groups.commands} />
260
- <EffectTreeSection title="Logs" effects={groups.logs} />
261
- </Box>
262
- );
263
- };
264
-
265
- // =============================================================================
266
- // Effect Timeline - Chronological display with timestamps
267
- // =============================================================================
268
-
269
- // Width for timestamp column (e.g., "+123ms")
270
- const TIMESTAMP_WIDTH = 8;
271
-
272
- /**
273
- * Filter effects to only show user-relevant ones (not internal effects).
274
- * @param effect - The effect to check
275
- * @param verbose - If true, include debug logs
276
- */
277
- const isVisibleEffect = (effect: Effect, verbose = false): boolean => {
278
- switch (effect._tag) {
279
- case "WriteFile":
280
- case "AppendFile":
281
- case "MakeDir":
282
- case "CopyFile":
283
- case "CopyDirectory":
284
- case "DeleteFile":
285
- case "DeleteDirectory":
286
- case "Exec":
287
- return true;
288
- case "Log":
289
- // Filter out debug logs unless verbose is enabled
290
- if (effect.level === "debug") {
291
- return verbose;
292
- }
293
- return true;
294
- // Internal effects are not shown
295
- case "ReadFile":
296
- case "Exists":
297
- case "Glob":
298
- case "ReadContext":
299
- case "WriteContext":
300
- case "Prompt":
301
- case "Parallel":
302
- case "Race":
303
- return false;
304
- default:
305
- return false;
306
- }
307
- };
308
-
309
- /**
310
- * Render a single timeline row with timestamp, action, and payload.
311
- */
312
- const TimelineRow = ({
313
- effect,
314
- timestamp,
315
- showTimestamp,
316
- isLast,
317
- }: {
318
- effect: Effect;
319
- timestamp: number;
320
- showTimestamp: boolean;
321
- isLast: boolean;
322
- }) => {
323
- const connector = isLast ? "└─" : "├─";
324
- const actionLabel = getActionLabel(effect);
325
- const color = getActionColor(effect);
326
- const payload = getEffectPayload(effect);
327
- const timestampStr = showTimestamp
328
- ? `+${Math.round(timestamp)}ms`.padEnd(TIMESTAMP_WIDTH)
329
- : " ".repeat(TIMESTAMP_WIDTH);
330
-
331
- return (
332
- <Box>
333
- <Text dimColor>{timestampStr}</Text>
334
- <Text dimColor>{connector} </Text>
335
- <Text color={color}>{actionLabel.padEnd(ACTION_LABEL_WIDTH)}</Text>
336
- <Text>{payload}</Text>
337
- </Box>
338
- );
339
- };
340
-
341
- /**
342
- * Render effects in chronological order with timestamps.
343
- * Timestamps are only shown when they differ from the previous effect.
344
- * Duplicate MakeDir effects (same path) are deduplicated.
345
- */
346
- const EffectTimeline = ({
347
- effects,
348
- verbose = false,
349
- }: {
350
- effects: TimedEffect[];
351
- verbose?: boolean;
352
- }) => {
353
- // Filter to visible effects only and deduplicate MakeDir by path
354
- const seenDirPaths = new Set<string>();
355
- const visibleEffects = effects.filter((e) => {
356
- if (!isVisibleEffect(e.effect, verbose)) return false;
357
- // Deduplicate MakeDir by path (keep only first occurrence)
358
- if (e.effect._tag === "MakeDir") {
359
- if (seenDirPaths.has(e.effect.path)) return false;
360
- seenDirPaths.add(e.effect.path);
361
- }
362
- return true;
363
- });
364
-
365
- if (visibleEffects.length === 0) {
366
- return null;
367
- }
368
-
369
- // Track which timestamps to show (only when different from previous)
370
- let lastShownTimestamp = -1;
371
-
372
- return (
373
- <Box flexDirection="column" marginTop={1}>
374
- <Text bold dimColor>
375
- Timeline:
376
- </Text>
377
- <Box flexDirection="column" marginLeft={1}>
378
- {visibleEffects.map((item, index) => {
379
- const roundedTimestamp = Math.round(item.timestamp);
380
- const showTimestamp = roundedTimestamp !== lastShownTimestamp;
381
- if (showTimestamp) {
382
- lastShownTimestamp = roundedTimestamp;
383
- }
384
- // Effects are append-only, index is stable
385
- const key = `${item.timestamp}-${item.effect._tag}-${index}`;
386
- return (
387
- <TimelineRow
388
- key={key}
389
- effect={item.effect}
390
- timestamp={item.timestamp}
391
- showTimestamp={showTimestamp}
392
- isLast={index === visibleEffects.length - 1}
393
- />
394
- );
395
- })}
396
- </Box>
397
- </Box>
398
- );
399
- };
400
-
401
- // =============================================================================
402
- // Dry-Run Timeline - Preview without timestamps
403
- // =============================================================================
404
-
405
- /**
406
- * Render a single dry-run row (no timestamp column).
407
- */
408
- const DryRunRow = ({ effect, isLast }: { effect: Effect; isLast: boolean }) => {
409
- const connector = isLast ? "└─" : "├─";
410
- const actionLabel = getActionLabel(effect);
411
- const color = getActionColor(effect);
412
- const payload = getEffectPayload(effect);
413
-
414
- return (
415
- <Box>
416
- <Text dimColor>{connector} </Text>
417
- <Text color={color}>{actionLabel.padEnd(ACTION_LABEL_WIDTH)}</Text>
418
- <Text>{payload}</Text>
419
- </Box>
420
- );
421
- };
422
-
423
- /**
424
- * Render effects as a preview timeline (dry-run mode).
425
- * Shows the same format as execution timeline but without timestamps.
426
- */
427
- const DryRunTimeline = ({
428
- effects,
429
- title = "Plan:",
430
- verbose = false,
431
- }: {
432
- effects: Effect[];
433
- title?: string;
434
- verbose?: boolean;
435
- }) => {
436
- // Filter to visible effects only and deduplicate MakeDir by path
437
- const seenDirPaths = new Set<string>();
438
- const visibleEffects = effects.filter((e) => {
439
- if (!isVisibleEffect(e, verbose)) return false;
440
- // Deduplicate MakeDir by path (keep only first occurrence)
441
- if (e._tag === "MakeDir") {
442
- if (seenDirPaths.has(e.path)) return false;
443
- seenDirPaths.add(e.path);
444
- }
445
- return true;
446
- });
447
-
448
- if (visibleEffects.length === 0) {
449
- return (
450
- <Box>
451
- <Text dimColor>No operations planned.</Text>
452
- </Box>
453
- );
454
- }
455
-
456
- return (
457
- <Box flexDirection="column">
458
- <Text bold dimColor>
459
- {title}
460
- </Text>
461
- <Box flexDirection="column" marginLeft={1}>
462
- {visibleEffects.map((effect, index) => {
463
- const key = `${effect._tag}-${index}`;
464
- return (
465
- <DryRunRow
466
- key={key}
467
- effect={effect}
468
- isLast={index === visibleEffects.length - 1}
469
- />
470
- );
471
- })}
472
- </Box>
473
- </Box>
474
- );
475
- };
476
-
477
- // =============================================================================
478
- // Completed Answers Display (for confirmation phase)
479
- // =============================================================================
480
-
481
- /**
482
- * Format answer value for display based on prompt type.
483
- */
484
- const formatAnswerValue = (
485
- value: unknown,
486
- prompt: PromptDefinition,
487
- ): string => {
488
- if (value === undefined || value === null) return "";
489
-
490
- if (prompt.type === "confirm") {
491
- return value ? "Yes" : "No";
492
- }
493
-
494
- if (prompt.type === "select" && prompt.choices) {
495
- const choice = prompt.choices.find((c) => c.value === value);
496
- return choice?.label ?? String(value);
497
- }
498
-
499
- if (prompt.type === "multiselect" && Array.isArray(value)) {
500
- if (value.length === 0) return "None";
501
- if (prompt.choices) {
502
- return value
503
- .map((v) => prompt.choices?.find((c) => c.value === v)?.label ?? v)
504
- .join(", ");
505
- }
506
- return value.join(", ");
507
- }
508
-
509
- return String(value);
510
- };
511
-
512
- /**
513
- * Display all completed answers in a borderless table format for confirmation review.
514
- */
515
- const CompletedAnswersTable = ({
516
- prompts,
517
- answers,
518
- }: {
519
- prompts: PromptDefinition[];
520
- answers: Record<string, unknown>;
521
- }) => {
522
- // Filter to only show prompts that have answers and pass their `when` condition
523
- const activePrompts = prompts.filter((prompt) => {
524
- if (prompt.when && !prompt.when(answers)) {
525
- return false;
526
- }
527
- return prompt.name in answers;
528
- });
529
-
530
- if (activePrompts.length === 0) {
531
- return null;
532
- }
533
-
534
- // Calculate max width for the question column (for alignment)
535
- const maxQuestionWidth = Math.max(
536
- ...activePrompts.map((p) => p.message.length),
537
- );
538
-
539
- return (
540
- <Box flexDirection="column" marginBottom={1}>
541
- {activePrompts.map((prompt) => {
542
- const value = answers[prompt.name];
543
- const displayValue = formatAnswerValue(value, prompt);
544
-
545
- return (
546
- <Box key={prompt.name}>
547
- <Text color="green">✔ </Text>
548
- <Text dimColor>{prompt.message.padEnd(maxQuestionWidth)}</Text>
549
- <Text dimColor> </Text>
550
- <Text color="cyan">{displayValue}</Text>
551
- </Box>
552
- );
553
- })}
554
- </Box>
555
- );
556
- };
557
-
558
- /**
559
- * Display a summary of planned effects in a borderless table format.
560
- */
561
- const EffectsSummaryTable = ({ effects }: { effects: Effect[] }) => {
562
- const files = new Set<string>();
563
- const directories = new Set<string>();
564
- const copied = new Set<string>();
565
- const deleted = new Set<string>();
566
- let commands = 0;
567
-
568
- for (const effect of effects) {
569
- switch (effect._tag) {
570
- case "WriteFile":
571
- case "AppendFile":
572
- files.add(effect.path);
573
- break;
574
- case "MakeDir":
575
- directories.add(effect.path);
576
- break;
577
- case "CopyFile":
578
- copied.add(effect.dest);
579
- break;
580
- case "CopyDirectory":
581
- copied.add(effect.dest);
582
- break;
583
- case "DeleteFile":
584
- case "DeleteDirectory":
585
- deleted.add(effect.path);
586
- break;
587
- case "Exec":
588
- commands++;
589
- break;
590
- }
591
- }
592
-
593
- // Build rows for non-zero counts
594
- const rows: Array<{ label: string; count: number; color: string }> = [];
595
-
596
- if (files.size > 0) {
597
- rows.push({
598
- label: `File${files.size > 1 ? "s" : ""} to create`,
599
- count: files.size,
600
- color: "green",
601
- });
602
- }
603
- if (directories.size > 0) {
604
- rows.push({
605
- label: `Director${directories.size > 1 ? "ies" : "y"} to create`,
606
- count: directories.size,
607
- color: "green",
608
- });
609
- }
610
- if (copied.size > 0) {
611
- rows.push({
612
- label: `Item${copied.size > 1 ? "s" : ""} to copy`,
613
- count: copied.size,
614
- color: "cyan",
615
- });
616
- }
617
- if (deleted.size > 0) {
618
- rows.push({
619
- label: `Item${deleted.size > 1 ? "s" : ""} to delete`,
620
- count: deleted.size,
621
- color: "red",
622
- });
623
- }
624
- if (commands > 0) {
625
- rows.push({
626
- label: `Command${commands > 1 ? "s" : ""} to run`,
627
- count: commands,
628
- color: "yellow",
629
- });
630
- }
631
-
632
- if (rows.length === 0) {
633
- return (
634
- <Box marginBottom={1}>
635
- <Text dimColor>No operations planned.</Text>
636
- </Box>
637
- );
638
- }
639
-
640
- // Calculate max label width for alignment
641
- const maxLabelWidth = Math.max(...rows.map((r) => r.label.length));
642
-
643
- return (
644
- <Box flexDirection="column" marginBottom={1}>
645
- <Text bold dimColor>
646
- Operations:
647
- </Text>
648
- {rows.map((row) => (
649
- <Box key={row.label}>
650
- <Text dimColor> {row.label.padEnd(maxLabelWidth)} </Text>
651
- <Text color={row.color as "green" | "cyan" | "red" | "yellow"}>
652
- {row.count}
653
- </Text>
654
- </Box>
655
- ))}
656
- </Box>
657
- );
658
- };
659
-
660
- /**
661
- * Summarize effects into a human-readable string.
662
- * Deduplicates paths to avoid counting the same directory multiple times.
663
- */
664
- const summarizeEffects = (effects: TimedEffect[]): string => {
665
- const files = new Set<string>();
666
- const directories = new Set<string>();
667
- const copied = new Set<string>();
668
- const deleted = new Set<string>();
669
- let commands = 0;
670
-
671
- for (const { effect } of effects) {
672
- switch (effect._tag) {
673
- case "WriteFile":
674
- files.add(effect.path);
675
- break;
676
- case "MakeDir":
677
- directories.add(effect.path);
678
- break;
679
- case "CopyFile":
680
- copied.add(effect.dest);
681
- break;
682
- case "DeleteFile":
683
- case "DeleteDirectory":
684
- deleted.add(effect.path);
685
- break;
686
- case "Exec":
687
- commands++;
688
- break;
689
- // Log effects are not counted in summary
690
- }
691
- }
692
-
693
- const parts: string[] = [];
694
-
695
- if (files.size > 0) {
696
- parts.push(`${files.size} file${files.size > 1 ? "s" : ""}`);
697
- }
698
- if (directories.size > 0) {
699
- parts.push(
700
- `${directories.size} director${directories.size > 1 ? "ies" : "y"}`,
701
- );
702
- }
703
- if (copied.size > 0) {
704
- parts.push(`${copied.size} copied`);
705
- }
706
- if (deleted.size > 0) {
707
- parts.push(`${deleted.size} deleted`);
708
- }
709
- if (commands > 0) {
710
- parts.push(`${commands} command${commands > 1 ? "s" : ""}`);
711
- }
712
-
713
- if (parts.length === 0) {
714
- return "No changes made";
715
- }
716
-
717
- return `Created ${parts.join(", ")}`;
718
- };
719
-
720
- // =============================================================================
721
- // File Content View - Full file content display (for Ctrl+O toggle)
722
- // =============================================================================
723
-
724
- /**
725
- * Display the full content of all WriteFile/AppendFile effects.
726
- * Used when the user toggles file content view with Ctrl+O.
727
- */
728
- const FileContentView = ({ effects }: { effects: Effect[] }) => {
729
- const writeEffects = effects.filter(
730
- (e): e is Effect & { _tag: "WriteFile" | "AppendFile" } =>
731
- e._tag === "WriteFile" || e._tag === "AppendFile",
732
- );
733
-
734
- if (writeEffects.length === 0) {
735
- return (
736
- <Box marginBottom={1}>
737
- <Text dimColor>No file contents to display.</Text>
738
- </Box>
739
- );
740
- }
741
-
742
- return (
743
- <Box flexDirection="column" marginBottom={1}>
744
- <Text bold dimColor>
745
- File contents:
746
- </Text>
747
- {writeEffects.map((effect, i) => (
748
- // biome-ignore lint/suspicious/noArrayIndexKey: path may be duplicated across effects
749
- <Box key={`${effect.path}-${i}`} flexDirection="column" marginTop={1}>
750
- <Text color="green" bold>
751
- {effect.path}
752
- </Text>
753
- <Box marginLeft={1}>
754
- <Text>{formatContentPreview(effect.content)}</Text>
755
- </Box>
756
- </Box>
757
- ))}
758
- </Box>
759
- );
760
- };
761
-
762
- // =============================================================================
763
- // App State and Component
764
- // =============================================================================
765
-
766
- export type AppState =
767
- | { phase: "loading" }
768
- | { phase: "prompting" }
769
- | { phase: "preview"; effects: Effect[] }
770
- | {
771
- phase: "confirming";
772
- effects: Effect[];
773
- promptAnswers: Record<string, unknown>;
774
- }
775
- | { phase: "executing"; task: Task<void> }
776
- | { phase: "complete"; effects: TimedEffect[]; duration: number }
777
- | { phase: "error"; error: TaskError; answers?: Record<string, unknown> };
778
-
779
- export interface AppProps {
780
- /** The generator to run */
781
- generator: GeneratorDefinition;
782
- /** Whether to show a preview before executing */
783
- preview?: boolean;
784
- /** Whether to run in dry-run mode only */
785
- dryRunOnly?: boolean;
786
- /** Whether to reverse a previously executed generator */
787
- undo?: boolean;
788
- /** Whether to show debug output */
789
- verbose?: boolean;
790
- /** Pre-filled answers (for non-interactive mode) */
791
- answers?: Record<string, unknown>;
792
- /** Stamp configuration for generated files (undefined = no stamps) */
793
- stamp?: StampConfig;
794
- }
795
-
796
- export const App = ({
797
- generator,
798
- preview = true,
799
- dryRunOnly = false,
800
- undo = false,
801
- verbose = false,
802
- answers: prefilledAnswers,
803
- stamp,
804
- }: AppProps) => {
805
- const { exit } = useApp();
806
- const [state, setState] = useState<AppState>(
807
- prefilledAnswers ? { phase: "loading" } : { phase: "prompting" },
808
- );
809
- const [answers, setAnswers] = useState<Record<string, unknown>>(
810
- prefilledAnswers ?? {},
811
- );
812
- const [showFiles, setShowFiles] = useState(false);
813
-
814
- const handlePromptsComplete = useCallback(
815
- (promptAnswers: Record<string, unknown>) => {
816
- setAnswers(promptAnswers);
817
-
818
- // Generate the task
819
- const task = generator.generate(promptAnswers);
820
-
821
- // Undo mode: run undo directly
822
- if (undo) {
823
- (async () => {
824
- try {
825
- const result = await runUndo(task);
826
- setState({
827
- phase: "complete",
828
- effects: [],
829
- duration: 0,
830
- });
831
- if (result.undoCount === 0) {
832
- setState({
833
- phase: "error",
834
- error: { code: "NOTHING_TO_UNDO", message: "Nothing to undo." },
835
- });
836
- }
837
- } catch (err) {
838
- setState({
839
- phase: "error",
840
- error:
841
- err instanceof Error
842
- ? { code: "UNDO_ERROR", message: err.message }
843
- : { code: "UNKNOWN_ERROR", message: String(err) },
844
- answers: promptAnswers,
845
- });
846
- }
847
- })();
848
- return;
849
- }
850
-
851
- if (dryRunOnly || preview) {
852
- // Run dry-run to collect effects
853
- try {
854
- const result = dryRun(task);
855
- if (dryRunOnly) {
856
- setState({ phase: "preview", effects: result.effects });
857
- } else {
858
- setState({
859
- phase: "confirming",
860
- effects: result.effects,
861
- promptAnswers,
862
- });
863
- }
864
- } catch (err) {
865
- setState({
866
- phase: "error",
867
- error:
868
- err instanceof Error
869
- ? { code: "DRY_RUN_ERROR", message: err.message }
870
- : { code: "UNKNOWN_ERROR", message: String(err) },
871
- answers: promptAnswers,
872
- });
873
- }
874
- } else {
875
- setState({ phase: "executing", task });
876
- }
877
- },
878
- [generator, preview, dryRunOnly, undo],
879
- );
880
-
881
- const handleConfirm = useCallback(() => {
882
- const task = generator.generate(answers);
883
- setState({ phase: "executing", task });
884
- }, [generator, answers]);
885
-
886
- const handleCancel = useCallback(() => {
887
- exit();
888
- }, [exit]);
889
-
890
- const handleExecutionComplete = useCallback(
891
- (effects: TimedEffect[], duration: number) => {
892
- setState({ phase: "complete", effects, duration });
893
- },
894
- [],
895
- );
896
-
897
- const handleExecutionError = useCallback(
898
- (error: TaskError) => {
899
- setState({ phase: "error", error, answers });
900
- },
901
- [answers],
902
- );
903
-
904
- // Handle pre-filled answers
905
- useEffect(() => {
906
- if (prefilledAnswers && state.phase === "loading") {
907
- handlePromptsComplete(prefilledAnswers);
908
- }
909
- }, [prefilledAnswers, state.phase, handlePromptsComplete]);
910
-
911
- // Handle going back from confirmation to prompting
912
- const handleGoBack = useCallback(() => {
913
- setShowFiles(false);
914
- setState({ phase: "prompting" });
915
- }, []);
916
-
917
- // Handle confirm/cancel/back/show-files input when in confirming state
918
- useInput(
919
- (input, key) => {
920
- if (state.phase === "confirming") {
921
- // Ctrl+O toggles file content view
922
- if (key.ctrl && input === "o") {
923
- setShowFiles((prev) => !prev);
924
- } else if (key.escape) {
925
- handleGoBack();
926
- } else if (key.return || input.toLowerCase() === "y") {
927
- // Enter or Y confirms
928
- handleConfirm();
929
- } else if (input.toLowerCase() === "n") {
930
- handleCancel();
931
- }
932
- }
933
- },
934
- { isActive: state.phase === "confirming" },
935
- );
936
-
937
- return (
938
- <Box flexDirection="column" padding={1}>
939
- {/* Header */}
940
- <Box marginBottom={1}>
941
- <Text bold color="magenta">
942
- {generator.meta.name}
943
- </Text>
944
- <Text dimColor> v{generator.meta.version}</Text>
945
- </Box>
946
- <Text dimColor>{generator.meta.description}</Text>
947
- <Box marginBottom={1} />
948
-
949
- {/* Content based on state */}
950
- {state.phase === "loading" && <Spinner label="Loading..." />}
951
-
952
- {state.phase === "prompting" && (
953
- <PromptSequence
954
- prompts={generator.prompts}
955
- onComplete={handlePromptsComplete}
956
- onCancel={handleCancel}
957
- initialAnswers={answers}
958
- />
959
- )}
960
-
961
- {state.phase === "preview" && (
962
- <Box flexDirection="column">
963
- <DryRunTimeline
964
- effects={state.effects}
965
- title="Plan (dry-run):"
966
- verbose={verbose}
967
- />
968
- <Box marginTop={1}>
969
- <Text dimColor>Dry-run complete. No files were modified.</Text>
970
- </Box>
971
- </Box>
972
- )}
973
-
974
- {state.phase === "confirming" && (
975
- <Box flexDirection="column">
976
- {/* Show completed answers in table format */}
977
- <CompletedAnswersTable
978
- prompts={generator.prompts}
979
- answers={state.promptAnswers}
980
- />
981
- {/* Show effects summary or file contents based on toggle */}
982
- {showFiles ? (
983
- <FileContentView effects={state.effects} />
984
- ) : (
985
- <EffectsSummaryTable effects={state.effects} />
986
- )}
987
- {/* Confirmation prompt with escape hint and Ctrl+O hint */}
988
- <Box>
989
- <Text color="magenta">› </Text>
990
- <Text bold>Proceed? </Text>
991
- <Text dimColor>(Y/n) </Text>
992
- <Text dimColor italic>
993
- esc to go back · ctrl+o {showFiles ? "hide" : "show"} file
994
- contents
995
- </Text>
996
- </Box>
997
- </Box>
998
- )}
999
-
1000
- {state.phase === "executing" && (
1001
- <ExecutionProgress
1002
- task={state.task}
1003
- onComplete={handleExecutionComplete}
1004
- onError={handleExecutionError}
1005
- stamp={stamp}
1006
- />
1007
- )}
1008
-
1009
- {state.phase === "complete" && (
1010
- <Box flexDirection="column">
1011
- <Box>
1012
- <Text color="green">✓ Generation complete!</Text>
1013
- </Box>
1014
- <EffectTimeline effects={state.effects} verbose={verbose} />
1015
- <Box marginTop={1}>
1016
- <Text dimColor>
1017
- {summarizeEffects(state.effects)} in {state.duration.toFixed(0)}ms
1018
- </Text>
1019
- </Box>
1020
- </Box>
1021
- )}
1022
-
1023
- {state.phase === "error" && (
1024
- <Box flexDirection="column">
1025
- <Box>
1026
- <Text color="red">✗ Error: {state.error.message}</Text>
1027
- </Box>
1028
- {state.error.code && (
1029
- <Box marginTop={1}>
1030
- <Text dimColor>Code: {state.error.code}</Text>
1031
- </Box>
1032
- )}
1033
- {state.answers && Object.keys(state.answers).length > 0 && (
1034
- <Box flexDirection="column" marginTop={1}>
1035
- <Text dimColor bold>
1036
- Arguments:
1037
- </Text>
1038
- <Box flexDirection="column" marginLeft={1}>
1039
- {Object.entries(state.answers).map(([key, value]) => (
1040
- <Box key={key}>
1041
- <Text dimColor>
1042
- {key}: {JSON.stringify(value)}
1043
- </Text>
1044
- </Box>
1045
- ))}
1046
- </Box>
1047
- </Box>
1048
- )}
1049
- </Box>
1050
- )}
1051
- </Box>
1052
- );
1053
- };