@canonical/summon 0.17.1 → 0.21.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 (41) hide show
  1. package/generators/example/hello/index.ts +3 -9
  2. package/generators/example/webapp/index.ts +7 -5
  3. package/generators/init/index.ts +3 -8
  4. package/generators/init/templates/generator.ts.ejs +3 -9
  5. package/package.json +25 -27
  6. package/src/bin.tsx +199 -0
  7. package/src/completion.test.ts +202 -0
  8. package/src/completion.ts +4 -1
  9. package/src/components/App.tsx +108 -15
  10. package/src/components/ExecutionProgress.tsx +8 -4
  11. package/src/components/FileTreePreview.tsx +1 -1
  12. package/src/components/PromptSequence.tsx +1 -1
  13. package/src/discovery/index.ts +1 -0
  14. package/src/discovery/loadGenerator.ts +37 -0
  15. package/src/display/index.ts +2 -0
  16. package/src/display/printGeneratorHelp.ts +128 -0
  17. package/src/display/printNode.ts +76 -0
  18. package/src/registration/buildCommandBarrel.ts +57 -0
  19. package/src/registration/index.ts +3 -0
  20. package/src/registration/registerFromBarrel.tsx +548 -0
  21. package/src/registration/types.ts +28 -0
  22. package/README.md +0 -446
  23. package/src/__tests__/combinators.test.ts +0 -895
  24. package/src/__tests__/dry-run.test.ts +0 -927
  25. package/src/__tests__/effect.test.ts +0 -816
  26. package/src/__tests__/interpreter.test.ts +0 -673
  27. package/src/__tests__/primitives.test.ts +0 -970
  28. package/src/__tests__/task.test.ts +0 -929
  29. package/src/__tests__/template.test.ts +0 -666
  30. package/src/cli-format.ts +0 -236
  31. package/src/cli-types.ts +0 -53
  32. package/src/cli.tsx +0 -1366
  33. package/src/combinators.ts +0 -294
  34. package/src/dry-run.ts +0 -434
  35. package/src/effect.ts +0 -224
  36. package/src/index.ts +0 -266
  37. package/src/interpreter.ts +0 -463
  38. package/src/primitives.ts +0 -442
  39. package/src/task.ts +0 -245
  40. package/src/template.ts +0 -537
  41. package/src/types.ts +0 -453
@@ -4,17 +4,21 @@
4
4
  * Main CLI application component using React Ink.
5
5
  */
6
6
 
7
- import { Box, Text, useApp, useInput } from "ink";
8
- import { useCallback, useEffect, useState } from "react";
9
- import { dryRun } from "../dry-run.js";
10
- import type { StampConfig } from "../interpreter.js";
7
+ import { formatContentPreview } from "@canonical/cli-core";
11
8
  import type {
12
- Effect,
13
9
  GeneratorDefinition,
14
10
  PromptDefinition,
15
- Task,
16
- TaskError,
17
- } from "../types.js";
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";
18
22
  import { ExecutionProgress, type TimedEffect } from "./ExecutionProgress.js";
19
23
  import { PromptSequence } from "./PromptSequence.js";
20
24
  import { Spinner } from "./Spinner.js";
@@ -713,6 +717,52 @@ const summarizeEffects = (effects: TimedEffect[]): string => {
713
717
  return `Created ${parts.join(", ")}`;
714
718
  };
715
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
+
716
766
  export type AppState =
717
767
  | { phase: "loading" }
718
768
  | { phase: "prompting" }
@@ -733,6 +783,8 @@ export interface AppProps {
733
783
  preview?: boolean;
734
784
  /** Whether to run in dry-run mode only */
735
785
  dryRunOnly?: boolean;
786
+ /** Whether to reverse a previously executed generator */
787
+ undo?: boolean;
736
788
  /** Whether to show debug output */
737
789
  verbose?: boolean;
738
790
  /** Pre-filled answers (for non-interactive mode) */
@@ -745,6 +797,7 @@ export const App = ({
745
797
  generator,
746
798
  preview = true,
747
799
  dryRunOnly = false,
800
+ undo = false,
748
801
  verbose = false,
749
802
  answers: prefilledAnswers,
750
803
  stamp,
@@ -756,6 +809,7 @@ export const App = ({
756
809
  const [answers, setAnswers] = useState<Record<string, unknown>>(
757
810
  prefilledAnswers ?? {},
758
811
  );
812
+ const [showFiles, setShowFiles] = useState(false);
759
813
 
760
814
  const handlePromptsComplete = useCallback(
761
815
  (promptAnswers: Record<string, unknown>) => {
@@ -764,6 +818,36 @@ export const App = ({
764
818
  // Generate the task
765
819
  const task = generator.generate(promptAnswers);
766
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
+
767
851
  if (dryRunOnly || preview) {
768
852
  // Run dry-run to collect effects
769
853
  try {
@@ -791,7 +875,7 @@ export const App = ({
791
875
  setState({ phase: "executing", task });
792
876
  }
793
877
  },
794
- [generator, preview, dryRunOnly],
878
+ [generator, preview, dryRunOnly, undo],
795
879
  );
796
880
 
797
881
  const handleConfirm = useCallback(() => {
@@ -826,14 +910,18 @@ export const App = ({
826
910
 
827
911
  // Handle going back from confirmation to prompting
828
912
  const handleGoBack = useCallback(() => {
913
+ setShowFiles(false);
829
914
  setState({ phase: "prompting" });
830
915
  }, []);
831
916
 
832
- // Handle confirm/cancel/back input when in confirming state
917
+ // Handle confirm/cancel/back/show-files input when in confirming state
833
918
  useInput(
834
919
  (input, key) => {
835
920
  if (state.phase === "confirming") {
836
- if (key.escape) {
921
+ // Ctrl+O toggles file content view
922
+ if (key.ctrl && input === "o") {
923
+ setShowFiles((prev) => !prev);
924
+ } else if (key.escape) {
837
925
  handleGoBack();
838
926
  } else if (key.return || input.toLowerCase() === "y") {
839
927
  // Enter or Y confirms
@@ -890,15 +978,20 @@ export const App = ({
890
978
  prompts={generator.prompts}
891
979
  answers={state.promptAnswers}
892
980
  />
893
- {/* Show effects summary table */}
894
- <EffectsSummaryTable effects={state.effects} />
895
- {/* Confirmation prompt with escape hint */}
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 */}
896
988
  <Box>
897
989
  <Text color="magenta">› </Text>
898
990
  <Text bold>Proceed? </Text>
899
991
  <Text dimColor>(Y/n) </Text>
900
992
  <Text dimColor italic>
901
- esc to go back
993
+ esc to go back · ctrl+o {showFiles ? "hide" : "show"} file
994
+ contents
902
995
  </Text>
903
996
  </Box>
904
997
  </Box>
@@ -4,12 +4,16 @@
4
4
  * Displays the progress of task execution with effect-by-effect feedback.
5
5
  */
6
6
 
7
+ import { runTaskWithStamp, type StampConfig } from "@canonical/summon-core";
8
+ import {
9
+ describeEffect,
10
+ type Effect,
11
+ type Task,
12
+ type TaskError,
13
+ } from "@canonical/task";
7
14
  import { Box, Text } from "ink";
8
15
  import type React from "react";
9
16
  import { useEffect, useState } from "react";
10
- import { describeEffect } from "../effect.js";
11
- import { runTask, type StampConfig } from "../interpreter.js";
12
- import type { Effect, Task, TaskError } from "../types.js";
13
17
  import { Spinner } from "./Spinner.js";
14
18
 
15
19
  /** Effect with timing information for the completion timeline */
@@ -89,7 +93,7 @@ export const ExecutionProgress: React.FC<ExecutionProgressProps> = ({
89
93
 
90
94
  const executeWithProgress = async () => {
91
95
  try {
92
- await runTask(task, {
96
+ await runTaskWithStamp(task, {
93
97
  stamp,
94
98
  onEffectStart: (effect) => {
95
99
  // Skip showing duplicate MakeDir in spinner
@@ -4,8 +4,8 @@
4
4
  * Displays a list of files that will be created/modified.
5
5
  */
6
6
 
7
+ import type { Effect } from "@canonical/task";
7
8
  import { Box, Text } from "ink";
8
- import type { Effect } from "../types.js";
9
9
 
10
10
  export interface FileTreePreviewProps {
11
11
  /** Effects to display */
@@ -9,11 +9,11 @@
9
9
  * - Group headers
10
10
  */
11
11
 
12
+ import type { PromptDefinition } from "@canonical/summon-core";
12
13
  import { Box, Text, useInput } from "ink";
13
14
  import SelectInput from "ink-select-input";
14
15
  import TextInput from "ink-text-input";
15
16
  import { useCallback, useEffect, useState } from "react";
16
- import type { PromptDefinition } from "../types.js";
17
17
 
18
18
  export interface PromptSequenceProps {
19
19
  /** List of prompts to display */
@@ -0,0 +1 @@
1
+ export { default as loadGenerator } from "./loadGenerator.js";
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Load a generator definition from a file path or the in-memory cache.
3
+ *
4
+ * Cached entries are inserted by {@link discoverGeneratorTree} when it
5
+ * processes barrel exports from summon-* packages.
6
+ */
7
+
8
+ import type { GeneratorDefinition } from "@canonical/summon-core";
9
+ import { generatorCache } from "@canonical/summon-core";
10
+
11
+ /**
12
+ * Load a generator from a path or the cache.
13
+ *
14
+ * @note Impure — performs dynamic import when the generator is not cached.
15
+ */
16
+ export default async function loadGenerator(
17
+ generatorPath: string,
18
+ ): Promise<GeneratorDefinition> {
19
+ // Check if this is a cached generator from a package barrel
20
+ if (generatorPath.startsWith("cache:")) {
21
+ const cacheKey = generatorPath.slice(6);
22
+ const cached = generatorCache.get(cacheKey);
23
+ if (cached) return cached;
24
+ throw new Error(`Generator not found in cache: ${cacheKey}`);
25
+ }
26
+
27
+ const module = await import(generatorPath);
28
+ const generator = module.default ?? module.generator;
29
+
30
+ if (!generator) {
31
+ throw new Error(
32
+ `No default export or 'generator' export found in ${generatorPath}`,
33
+ );
34
+ }
35
+
36
+ return generator as GeneratorDefinition;
37
+ }
@@ -0,0 +1,2 @@
1
+ export { default as printGeneratorHelp } from "./printGeneratorHelp.js";
2
+ export { default as printNode } from "./printNode.js";
@@ -0,0 +1,128 @@
1
+ /**
2
+ * Print detailed help for a generator (meta.help and examples).
3
+ *
4
+ * When `llmMode` is true, outputs structured markdown help via formatLlmHelp.
5
+ *
6
+ * @note Impure — writes to stdout, loads generators via dynamic import.
7
+ */
8
+
9
+ import { formatGeneratorLlmHelp } from "@canonical/cli-core";
10
+ import type { GeneratorNode } from "@canonical/summon-core";
11
+ import { toKebabCase } from "@canonical/utils";
12
+ import chalk from "chalk";
13
+ import { loadGenerator } from "../discovery/index.js";
14
+ import printNode from "./printNode.js";
15
+
16
+ export default async function printGeneratorHelp(
17
+ node: GeneratorNode,
18
+ pathSegments: string[],
19
+ llmMode = false,
20
+ ): Promise<void> {
21
+ if (!node.indexPath) return;
22
+
23
+ try {
24
+ const generator = await loadGenerator(node.indexPath);
25
+ const { meta, prompts } = generator;
26
+ const commandPath = pathSegments.join(" ");
27
+
28
+ // LLM mode: output structured markdown help and return
29
+ if (llmMode) {
30
+ process.stdout.write(formatGeneratorLlmHelp(generator, commandPath));
31
+ return;
32
+ }
33
+
34
+ console.log();
35
+ console.log(chalk.bold.cyan(`summon ${commandPath}`));
36
+ console.log(chalk.dim(`v${meta.version}`));
37
+ console.log();
38
+ console.log(meta.description);
39
+
40
+ // Print extended help if available
41
+ if (meta.help) {
42
+ console.log();
43
+ console.log(meta.help);
44
+ }
45
+
46
+ // Print available options (from prompts)
47
+ if (prompts.length > 0) {
48
+ console.log();
49
+ console.log(chalk.bold("Options:"));
50
+ console.log();
51
+ for (const prompt of prompts) {
52
+ const flagName = `--${toKebabCase(prompt.name)}`;
53
+ const typeHint =
54
+ prompt.type === "confirm"
55
+ ? "[boolean]"
56
+ : prompt.type === "select"
57
+ ? `[${prompt.choices?.map((c) => c.value).join("|")}]`
58
+ : prompt.type === "multiselect"
59
+ ? "[value,value,...]"
60
+ : "<value>";
61
+
62
+ const defaultHint =
63
+ prompt.default !== undefined
64
+ ? chalk.dim(` (default: ${JSON.stringify(prompt.default)})`)
65
+ : "";
66
+
67
+ console.log(` ${chalk.cyan(flagName)} ${typeHint}${defaultHint}`);
68
+ console.log(` ${prompt.message}`);
69
+ }
70
+ }
71
+
72
+ // Print examples if available
73
+ if (meta.examples && meta.examples.length > 0) {
74
+ console.log();
75
+ console.log(chalk.bold("Examples:"));
76
+ console.log();
77
+ for (const example of meta.examples) {
78
+ console.log(` ${chalk.dim("$")} ${example}`);
79
+ }
80
+ }
81
+
82
+ // Print available subtopics if any
83
+ if (node.children.size > 0) {
84
+ console.log();
85
+ console.log(chalk.bold("Subtopics:"));
86
+ for (const [name, child] of node.children) {
87
+ const desc = child.meta?.description ?? "";
88
+ console.log(` ${chalk.cyan(name)}${desc ? ` - ${desc}` : ""}`);
89
+ }
90
+ }
91
+
92
+ // LLM Usage section
93
+ console.log();
94
+ console.log(chalk.bold("LLM Usage:"));
95
+ console.log(chalk.dim(" # Preview what will be generated (markdown):"));
96
+ console.log(
97
+ chalk.dim(
98
+ ` summon ${commandPath} ${prompts
99
+ .filter((p) => !p.when && p.default === undefined)
100
+ .map((p) => `--${toKebabCase(p.name)} <value>`)
101
+ .join(" ")} --llm`,
102
+ ),
103
+ );
104
+ console.log(chalk.dim(" # Preview (JSON):"));
105
+ console.log(
106
+ chalk.dim(
107
+ ` summon ${commandPath} ${prompts
108
+ .filter((p) => !p.when && p.default === undefined)
109
+ .map((p) => `--${toKebabCase(p.name)} <value>`)
110
+ .join(" ")} --format json`,
111
+ ),
112
+ );
113
+ console.log(chalk.dim(" # Execute directly:"));
114
+ console.log(
115
+ chalk.dim(
116
+ ` summon ${commandPath} ${prompts
117
+ .filter((p) => !p.when && p.default === undefined)
118
+ .map((p) => `--${toKebabCase(p.name)} <value>`)
119
+ .join(" ")} --yes`,
120
+ ),
121
+ );
122
+
123
+ console.log();
124
+ } catch {
125
+ // Couldn't load generator, fall back to basic node printing
126
+ printNode(node, pathSegments);
127
+ }
128
+ }
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Print available generators/sub-generators at a tree node.
3
+ *
4
+ * @note Impure — writes to stdout.
5
+ */
6
+
7
+ import type { GeneratorNode, GeneratorOrigin } from "@canonical/summon-core";
8
+ import chalk from "chalk";
9
+
10
+ /**
11
+ * Format origin badge for display.
12
+ */
13
+ const formatOrigin = (origin?: GeneratorOrigin): string => {
14
+ switch (origin) {
15
+ case "local":
16
+ return chalk.green("[local]");
17
+ case "global":
18
+ return chalk.blue("[global]");
19
+ case "package":
20
+ return chalk.magenta("[pkg]");
21
+ case "builtin":
22
+ return chalk.dim("[builtin]");
23
+ default:
24
+ return "";
25
+ }
26
+ };
27
+
28
+ export default function printNode(
29
+ node: GeneratorNode,
30
+ pathSegments: string[],
31
+ ): void {
32
+ const prefix = pathSegments.length > 0 ? `${pathSegments.join(" ")} ` : "";
33
+ const isRoot = pathSegments.length === 0;
34
+
35
+ if (node.children.size === 0) {
36
+ console.log(chalk.yellow("No generators found"));
37
+ console.log(chalk.dim("\nInstall a generator package:"));
38
+ console.log(chalk.dim(" bun add @scope/summon-<name>"));
39
+ console.log(chalk.dim("\nOr link globally (from the package directory):"));
40
+ console.log(chalk.dim(" bun link # for bun users"));
41
+ console.log(chalk.dim(" npm link # for npm users"));
42
+ return;
43
+ }
44
+
45
+ if (isRoot) {
46
+ console.log(chalk.bold("\nAvailable topics:\n"));
47
+ } else {
48
+ console.log(chalk.bold(`\nAvailable under '${pathSegments.join(" ")}':\n`));
49
+ }
50
+
51
+ for (const [name, child] of node.children) {
52
+ const hasChildren = child.children.size > 0;
53
+ const isRunnable = !!child.indexPath;
54
+ const originBadge = child.origin ? ` ${formatOrigin(child.origin)}` : "";
55
+
56
+ let suffix = "";
57
+ if (hasChildren && isRunnable) {
58
+ suffix = chalk.dim(" (runnable, has subtopics)");
59
+ } else if (hasChildren) {
60
+ suffix = chalk.dim(" (has subtopics)");
61
+ }
62
+
63
+ console.log(chalk.cyan(` ${name}`) + originBadge + suffix);
64
+
65
+ // Show immediate children as hints
66
+ if (hasChildren) {
67
+ const childNames = [...child.children.keys()].slice(0, 5);
68
+ const more =
69
+ child.children.size > 5 ? `, +${child.children.size - 5} more` : "";
70
+ console.log(chalk.dim(` └─ ${childNames.join(", ")}${more}`));
71
+ }
72
+ }
73
+
74
+ console.log(chalk.dim(`\nUsage: summon ${prefix}<topic>`));
75
+ console.log();
76
+ }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Build a flat command list from a generator tree.
3
+ *
4
+ * Flattens the tree into a list of {@link CommandEntry} sorted by depth
5
+ * so that parents are registered before children.
6
+ *
7
+ * @note Impure — loads generators via dynamic import.
8
+ */
9
+
10
+ import type { GeneratorNode } from "@canonical/summon-core";
11
+ import chalk from "chalk";
12
+ import { loadGenerator } from "../discovery/index.js";
13
+ import type { CommandEntry } from "./types.js";
14
+
15
+ export default async function buildCommandBarrel(
16
+ node: GeneratorNode,
17
+ pathSegments: string[] = [],
18
+ ): Promise<CommandEntry[]> {
19
+ const entries: CommandEntry[] = [];
20
+
21
+ for (const [name, child] of node.children) {
22
+ const childPath = [...pathSegments, name];
23
+
24
+ if (child.indexPath) {
25
+ // Runnable generator
26
+ try {
27
+ const generator = await loadGenerator(child.indexPath);
28
+ entries.push({ path: childPath, generator });
29
+
30
+ // If it also has children, we need to ensure parent exists and recurse
31
+ if (child.children.size > 0) {
32
+ const childEntries = await buildCommandBarrel(child, childPath);
33
+ entries.push(...childEntries);
34
+ }
35
+ } catch (err) {
36
+ console.error(
37
+ chalk.yellow(`Warning: Could not load generator '${name}':`),
38
+ (err as Error).message,
39
+ );
40
+ }
41
+ } else if (child.children.size > 0) {
42
+ // Namespace-only (no indexPath but has children)
43
+ // Add a placeholder entry so we create the parent command
44
+ entries.push({
45
+ path: childPath,
46
+ description: `${name} generators`,
47
+ });
48
+
49
+ // Recurse into children
50
+ const childEntries = await buildCommandBarrel(child, childPath);
51
+ entries.push(...childEntries);
52
+ }
53
+ }
54
+
55
+ // Sort by path length so parents are registered before children
56
+ return entries.sort((a, b) => a.path.length - b.path.length);
57
+ }
@@ -0,0 +1,3 @@
1
+ export { default as buildCommandBarrel } from "./buildCommandBarrel.js";
2
+ export { default as registerFromBarrel } from "./registerFromBarrel.js";
3
+ export type { CommandEntry, OptionInfo } from "./types.js";