@canonical/summon 0.36.0 → 0.38.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 (40) hide show
  1. package/dist/src/components/App.js +24 -2
  2. package/dist/src/components/App.js.map +1 -1
  3. package/dist/src/index.d.ts +15 -0
  4. package/dist/src/index.js +16 -0
  5. package/dist/src/index.js.map +1 -0
  6. package/dist/src/registration/registerFromBarrel.js +13 -0
  7. package/dist/src/registration/registerFromBarrel.js.map +1 -1
  8. package/package.json +22 -14
  9. package/src/bin.tsx +238 -0
  10. package/src/completion.test.ts +202 -0
  11. package/src/completion.ts +492 -0
  12. package/src/components/App.askMissing.test.tsx +164 -0
  13. package/src/components/App.confirmGate.test.tsx +111 -0
  14. package/src/components/App.escBack.test.tsx +98 -0
  15. package/src/components/App.invalidAnswer.test.tsx +71 -0
  16. package/src/components/App.tsx +1305 -0
  17. package/src/components/ExecutionProgress.tsx +222 -0
  18. package/src/components/FileTreePreview.tsx +97 -0
  19. package/src/components/PromptSequence.tsx +558 -0
  20. package/src/components/Spinner.tsx +36 -0
  21. package/src/components/index.ts +16 -0
  22. package/src/components/undoPlan.test.ts +99 -0
  23. package/src/components/undoPlan.ts +70 -0
  24. package/src/discovery/index.ts +1 -0
  25. package/src/discovery/loadGenerator.ts +40 -0
  26. package/src/display/index.ts +2 -0
  27. package/src/display/printGeneratorHelp.ts +130 -0
  28. package/src/display/printNode.ts +76 -0
  29. package/src/index.ts +16 -0
  30. package/src/registration/buildCommandBarrel.test.ts +80 -0
  31. package/src/registration/buildCommandBarrel.ts +66 -0
  32. package/src/registration/conformance.subprocess.test.ts +192 -0
  33. package/src/registration/index.ts +2 -0
  34. package/src/registration/interaction.subprocess.test.ts +458 -0
  35. package/src/registration/registerFromBarrel.tsx +501 -0
  36. package/src/registration/resolveMode.test.ts +118 -0
  37. package/src/registration/resolveMode.ts +52 -0
  38. package/src/testing/globalSetup.test.ts +165 -0
  39. package/src/testing/globalSetup.ts +501 -0
  40. package/src/ui/index.tsx +31 -0
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Pure helpers for presenting and gating an undo plan — shared by the Ink
3
+ * wizard and the batch path so both executors show the SAME plan under the
4
+ * SAME rules. Kept free of Ink/Commander so the contract is unit-testable
5
+ * without a terminal.
6
+ */
7
+
8
+ import { dryRun, type Effect, type Task } from "@canonical/task";
9
+
10
+ /** Effects an undo task walks through that are not part of what it reverses. */
11
+ const PLUMBING = new Set(["Log", "ReadFile", "Exists", "ReadContext"]);
12
+
13
+ /**
14
+ * Describe an undo plan in EXECUTION order (last collected step first —
15
+ * `runCollectedUndos` executes LIFO, and the preview must show the order
16
+ * that will actually run). Each undo contributes its visible effects; an
17
+ * undo whose dry-run yields only plumbing (e.g. a remove-line undo, whose
18
+ * reads are mocked so no write surfaces) contributes a synthetic Log line
19
+ * naming the file it will revert, so the plan never under-reports a step.
20
+ *
21
+ * @param undos - Undo tasks in forward collection order, as `collectUndos`
22
+ * returns them.
23
+ * @returns Effects describing the plan, in execution (reversed) order.
24
+ */
25
+ export function describeUndoSteps(undos: readonly Task<void>[]): Effect[] {
26
+ return [...undos].reverse().flatMap((undoTask) => {
27
+ const effects = dryRun(undoTask).effects;
28
+ const visible = effects.filter((effect) => !PLUMBING.has(effect._tag));
29
+ if (visible.length > 0) {
30
+ return visible;
31
+ }
32
+ const touched = effects.find(
33
+ (effect): effect is Effect & { path: string } =>
34
+ "path" in effect && typeof effect.path === "string",
35
+ );
36
+ if (touched === undefined) {
37
+ return [];
38
+ }
39
+ return [
40
+ {
41
+ _tag: "Log",
42
+ level: "info",
43
+ message: `Revert changes in ${touched.path}`,
44
+ } as Effect,
45
+ ];
46
+ });
47
+ }
48
+
49
+ /**
50
+ * Whether a forward effect will be left behind by the undo: an `Exec` with
51
+ * no undo of its own. An exec that carries an explicit `undo` is reversed
52
+ * like any other effect and must not be reported as residue.
53
+ */
54
+ export function isUnreversibleExec(effect: Effect): boolean {
55
+ return (
56
+ effect._tag === "Exec" && !("undo" in effect && effect.undo !== undefined)
57
+ );
58
+ }
59
+
60
+ /**
61
+ * Whether to skip the undo confirmation gate — the SAME contract the
62
+ * forward run applies to its preview gate: flags only pre-fill answers,
63
+ * while `--yes` and `--no-preview` both go straight to executing.
64
+ */
65
+ export function shouldSkipUndoGate(options: {
66
+ readonly yes: boolean;
67
+ readonly preview: boolean;
68
+ }): boolean {
69
+ return options.yes || !options.preview;
70
+ }
@@ -0,0 +1 @@
1
+ export { default as loadGenerator } from "./loadGenerator.js";
@@ -0,0 +1,40 @@
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 { pathToFileURL } from "node:url";
9
+ import type { GeneratorDefinition } from "@canonical/summon-core";
10
+ import { generatorCache } from "@canonical/summon-core";
11
+
12
+ /**
13
+ * Load a generator from a path or the cache.
14
+ *
15
+ * @note Impure — performs dynamic import when the generator is not cached.
16
+ */
17
+ export default async function loadGenerator(
18
+ generatorPath: string,
19
+ ): Promise<GeneratorDefinition> {
20
+ // Check if this is a cached generator from a package barrel
21
+ if (generatorPath.startsWith("cache:")) {
22
+ const cacheKey = generatorPath.slice(6);
23
+ const cached = generatorCache.get(cacheKey);
24
+ if (cached) return cached;
25
+ throw new Error(`Generator not found in cache: ${cacheKey}`);
26
+ }
27
+
28
+ // pathToFileURL: a raw absolute path is not a valid ESM specifier on
29
+ // Windows (the drive letter parses as a protocol).
30
+ const module = await import(pathToFileURL(generatorPath).href);
31
+ const generator = module.default ?? module.generator;
32
+
33
+ if (!generator) {
34
+ throw new Error(
35
+ `No default export or 'generator' export found in ${generatorPath}`,
36
+ );
37
+ }
38
+
39
+ return generator as GeneratorDefinition;
40
+ }
@@ -0,0 +1,2 @@
1
+ export { default as printGeneratorHelp } from "./printGeneratorHelp.js";
2
+ export { default as printNode } from "./printNode.js";
@@ -0,0 +1,130 @@
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 {
10
+ formatLlmHelp as formatGeneratorLlmHelp,
11
+ type GeneratorNode,
12
+ } from "@canonical/summon-core";
13
+ import { toKebabCase } from "@canonical/utils";
14
+ import chalk from "chalk";
15
+ import { loadGenerator } from "../discovery/index.js";
16
+ import printNode from "./printNode.js";
17
+
18
+ export default async function printGeneratorHelp(
19
+ node: GeneratorNode,
20
+ pathSegments: string[],
21
+ llmMode = false,
22
+ ): Promise<void> {
23
+ if (!node.indexPath) return;
24
+
25
+ try {
26
+ const generator = await loadGenerator(node.indexPath);
27
+ const { meta, prompts } = generator;
28
+ const commandPath = pathSegments.join(" ");
29
+
30
+ // LLM mode: output structured markdown help and return
31
+ if (llmMode) {
32
+ process.stdout.write(formatGeneratorLlmHelp(generator, commandPath));
33
+ return;
34
+ }
35
+
36
+ console.log();
37
+ console.log(chalk.bold.cyan(`summon ${commandPath}`));
38
+ console.log(chalk.dim(`v${meta.version}`));
39
+ console.log();
40
+ console.log(meta.description);
41
+
42
+ // Print extended help if available
43
+ if (meta.help) {
44
+ console.log();
45
+ console.log(meta.help);
46
+ }
47
+
48
+ // Print available options (from prompts)
49
+ if (prompts.length > 0) {
50
+ console.log();
51
+ console.log(chalk.bold("Options:"));
52
+ console.log();
53
+ for (const prompt of prompts) {
54
+ const flagName = `--${toKebabCase(prompt.name)}`;
55
+ const typeHint =
56
+ prompt.type === "confirm"
57
+ ? "[boolean]"
58
+ : prompt.type === "select"
59
+ ? `[${prompt.choices?.map((c) => c.value).join("|")}]`
60
+ : prompt.type === "multiselect"
61
+ ? "[value,value,...]"
62
+ : "<value>";
63
+
64
+ const defaultHint =
65
+ prompt.default !== undefined
66
+ ? chalk.dim(` (default: ${JSON.stringify(prompt.default)})`)
67
+ : "";
68
+
69
+ console.log(` ${chalk.cyan(flagName)} ${typeHint}${defaultHint}`);
70
+ console.log(` ${prompt.message}`);
71
+ }
72
+ }
73
+
74
+ // Print examples if available
75
+ if (meta.examples && meta.examples.length > 0) {
76
+ console.log();
77
+ console.log(chalk.bold("Examples:"));
78
+ console.log();
79
+ for (const example of meta.examples) {
80
+ console.log(` ${chalk.dim("$")} ${example}`);
81
+ }
82
+ }
83
+
84
+ // Print available subtopics if any
85
+ if (node.children.size > 0) {
86
+ console.log();
87
+ console.log(chalk.bold("Subtopics:"));
88
+ for (const [name, child] of node.children) {
89
+ const desc = child.meta?.description ?? "";
90
+ console.log(` ${chalk.cyan(name)}${desc ? ` - ${desc}` : ""}`);
91
+ }
92
+ }
93
+
94
+ // LLM Usage section
95
+ console.log();
96
+ console.log(chalk.bold("LLM Usage:"));
97
+ console.log(chalk.dim(" # Preview what will be generated (markdown):"));
98
+ console.log(
99
+ chalk.dim(
100
+ ` summon ${commandPath} ${prompts
101
+ .filter((p) => !p.when && p.default === undefined)
102
+ .map((p) => `--${toKebabCase(p.name)} <value>`)
103
+ .join(" ")} --llm`,
104
+ ),
105
+ );
106
+ console.log(chalk.dim(" # Preview (JSON):"));
107
+ console.log(
108
+ chalk.dim(
109
+ ` summon ${commandPath} ${prompts
110
+ .filter((p) => !p.when && p.default === undefined)
111
+ .map((p) => `--${toKebabCase(p.name)} <value>`)
112
+ .join(" ")} --format json`,
113
+ ),
114
+ );
115
+ console.log(chalk.dim(" # Execute directly:"));
116
+ console.log(
117
+ chalk.dim(
118
+ ` summon ${commandPath} ${prompts
119
+ .filter((p) => !p.when && p.default === undefined)
120
+ .map((p) => `--${toKebabCase(p.name)} <value>`)
121
+ .join(" ")} --yes`,
122
+ ),
123
+ );
124
+
125
+ console.log();
126
+ } catch {
127
+ // Couldn't load generator, fall back to basic node printing
128
+ printNode(node, pathSegments);
129
+ }
130
+ }
@@ -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
+ }
package/src/index.ts ADDED
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Public, types-only API surface for `@canonical/summon`.
3
+ *
4
+ * Per the tool-ts convention this barrel exports types only — no runtime
5
+ * values cross the package boundary, so importing it can never start the CLI.
6
+ * The runtime surface stays exactly where the `exports` map already puts it:
7
+ * the `summon` binary and the `@canonical/summon/ui` subpath.
8
+ *
9
+ * `src/bin.tsx` is deliberately NOT re-exported: it parses `argv` and runs a
10
+ * generator at module scope, so re-exporting it would turn an `import` into a
11
+ * CLI invocation.
12
+ *
13
+ * @module
14
+ */
15
+
16
+ export type { AppProps, AppState } from "./components/App.js";
@@ -0,0 +1,80 @@
1
+ import type {
2
+ GeneratorDefinition,
3
+ GeneratorNode,
4
+ } from "@canonical/summon-core";
5
+ import { generatorCache } from "@canonical/summon-core";
6
+ import { pure, task } from "@canonical/task";
7
+ import { afterEach, describe, expect, it, vi } from "vitest";
8
+ import buildCommandBarrel from "./buildCommandBarrel.js";
9
+
10
+ const generator: GeneratorDefinition = {
11
+ meta: { name: "g", displayName: "g", description: "g", version: "0" },
12
+ prompts: [],
13
+ generate: () => task(pure(undefined)).unwrap(),
14
+ };
15
+
16
+ function node(
17
+ name: string,
18
+ children: GeneratorNode[] = [],
19
+ indexPath?: string,
20
+ ): GeneratorNode {
21
+ return {
22
+ name,
23
+ path: `/${name}`,
24
+ ...(indexPath ? { indexPath } : {}),
25
+ children: new Map(children.map((child) => [child.name, child])),
26
+ };
27
+ }
28
+
29
+ describe("buildCommandBarrel", () => {
30
+ // The real loader path: `cache:` keys resolve through the shared
31
+ // generatorCache (how discovery hands over package-barrel generators),
32
+ // and a missing key throws — the load-failure path, no injection seam.
33
+ generatorCache.set("g", generator);
34
+
35
+ afterEach(() => {
36
+ vi.restoreAllMocks();
37
+ });
38
+
39
+ it("flattens runnable leaves, namespaces, and nested runnables — parents first", async () => {
40
+ const tree = node("root", [
41
+ node("component", [
42
+ node("react", [], "cache:g"),
43
+ node("svelte", [], "cache:g"),
44
+ ]),
45
+ node("init", [], "cache:g"),
46
+ // A runnable that ALSO has children: both the entry and its subtree land.
47
+ node("dual", [node("sub", [], "cache:g")], "cache:g"),
48
+ // Neither runnable nor a namespace: contributes nothing.
49
+ node("empty"),
50
+ ]);
51
+
52
+ const entries = await buildCommandBarrel(tree);
53
+
54
+ expect(entries.map((entry) => entry.path.join("/"))).toEqual([
55
+ "component",
56
+ "init",
57
+ "dual",
58
+ "component/react",
59
+ "component/svelte",
60
+ "dual/sub",
61
+ ]);
62
+ expect(entries[0]?.description).toBe("component generators");
63
+ expect(entries[0]?.generator).toBeUndefined();
64
+ expect(entries[1]?.generator).toBe(generator);
65
+ });
66
+
67
+ it("warns on a load failure and skips the entry, the rest still land", async () => {
68
+ const error = vi.spyOn(console, "error").mockImplementation(() => {});
69
+ const tree = node("root", [
70
+ node("bad", [], "cache:missing"),
71
+ node("good", [], "cache:g"),
72
+ ]);
73
+ const entries = await buildCommandBarrel(tree);
74
+ expect(entries.map((entry) => entry.path.join("/"))).toEqual(["good"]);
75
+ expect(error).toHaveBeenCalledWith(
76
+ expect.stringContaining("Warning: Could not load generator 'bad':"),
77
+ "Generator not found in cache: missing",
78
+ );
79
+ });
80
+ });
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Build a flat command list from a generator tree — summon's own barrel
3
+ * builder, this bin's ONE consumer of tree-walking barrel construction
4
+ * (pragma builds its barrel from its generated surface data). Flattens the
5
+ * tree into a list of {@link CommandEntry} sorted by depth so that parents
6
+ * are registered before children; a generator that fails to load gets a
7
+ * chalk warning and is skipped, the rest still register.
8
+ *
9
+ * @note Impure — loads generators via dynamic import, warns on stderr.
10
+ */
11
+
12
+ import type { GeneratorNode } from "@canonical/summon-core";
13
+ import type { CommandEntry } from "@canonical/summon-core/projection";
14
+ import chalk from "chalk";
15
+ import { loadGenerator } from "../discovery/index.js";
16
+
17
+ /**
18
+ * Flatten a generator tree into registration-ordered command entries.
19
+ *
20
+ * @param node - The tree node to flatten (the discovery root, or a subtree).
21
+ * @param pathSegments - The path prefix of `node` (used when recursing).
22
+ * @returns Entries sorted by path length (parents first).
23
+ */
24
+ export default async function buildCommandBarrel(
25
+ node: GeneratorNode,
26
+ pathSegments: readonly string[] = [],
27
+ ): Promise<CommandEntry[]> {
28
+ const entries: CommandEntry[] = [];
29
+
30
+ for (const [name, child] of node.children) {
31
+ const childPath = [...pathSegments, name];
32
+
33
+ if (child.indexPath) {
34
+ // Runnable generator
35
+ try {
36
+ const generator = await loadGenerator(child.indexPath);
37
+ entries.push({ path: childPath, generator });
38
+
39
+ // If it also has children, we need to ensure parent exists and recurse
40
+ if (child.children.size > 0) {
41
+ const childEntries = await buildCommandBarrel(child, childPath);
42
+ entries.push(...childEntries);
43
+ }
44
+ } catch (err) {
45
+ console.error(
46
+ chalk.yellow(`Warning: Could not load generator '${name}':`),
47
+ (err as Error).message,
48
+ );
49
+ }
50
+ } else if (child.children.size > 0) {
51
+ // Namespace-only (no indexPath but has children)
52
+ // Add a placeholder entry so we create the parent command
53
+ entries.push({
54
+ path: childPath,
55
+ description: `${name} generators`,
56
+ });
57
+
58
+ // Recurse into children
59
+ const childEntries = await buildCommandBarrel(child, childPath);
60
+ entries.push(...childEntries);
61
+ }
62
+ }
63
+
64
+ // Sort by path length so parents are registered before children
65
+ return entries.sort((a, b) => a.path.length - b.path.length);
66
+ }
@@ -0,0 +1,192 @@
1
+ /**
2
+ * PROTECTED — summon's side of the byte-equality seam.
3
+ *
4
+ * The guarantee is that both product binaries generate the same tree from the
5
+ * same generator and the same answers. Until now that was asserted only from
6
+ * PRAGMA's package: pragma's kernel path was diffed against summon-core's
7
+ * `execute`, and this package had no tests at all (`--passWithNoTests`), so the
8
+ * summon BIN — the Commander/Ink front-end over that same core — could drift
9
+ * and nothing would catch it.
10
+ *
11
+ * This runs the real bin in its own PROCESS, exactly as a user does
12
+ * (`summon example hello --name=… --yes`), and diffs its tree against
13
+ * {@link produceReference} — the shared definition of the seam in
14
+ * `@canonical/summon-core/testing`. Three generators are covered —
15
+ * `example/hello` (templates, a conditional file, EJS helpers),
16
+ * `example/webapp` (a framework/styling matrix, a multiselect, parallel
17
+ * effects) and `init` (a nested output path) — the three builtin leaves
18
+ * the bin ships, and a declaration tie on the builtin dir keeps this
19
+ * matrix honest: a fourth shipped leaf reddens it here instead of
20
+ * arriving covered by nothing.
21
+ *
22
+ * Subprocess, not in-process, deliberately: the bin's write path goes through
23
+ * Ink's `render`, and the risk being guarded is precisely that the front-end
24
+ * adds or drops a byte around the core. A non-TTY child is the CI shape, and it
25
+ * is the shape asserted here.
26
+ */
27
+
28
+ import { execFileSync } from "node:child_process";
29
+ import { existsSync, mkdtempSync, readdirSync } from "node:fs";
30
+ import { tmpdir } from "node:os";
31
+ import { dirname, join, resolve } from "node:path";
32
+ import { fileURLToPath } from "node:url";
33
+ import {
34
+ diffTrees,
35
+ formatTreeDiff,
36
+ isIdentical,
37
+ produceReference,
38
+ snapshotTree,
39
+ type TreeSnapshot,
40
+ } from "@canonical/summon-core/testing";
41
+ import { describe, expect, it } from "vitest";
42
+
43
+ const here = dirname(fileURLToPath(import.meta.url));
44
+ const packageRoot = resolve(here, "../..");
45
+ const summonBin = join(packageRoot, "src/bin.tsx");
46
+
47
+ const freshCwd = (): string => mkdtempSync(join(tmpdir(), "summon-conf-"));
48
+
49
+ /** Producer (1): the real summon bin, run non-interactively in its own process. */
50
+ function produceBin(args: readonly string[]): TreeSnapshot {
51
+ const cwd = freshCwd();
52
+ execFileSync("bun", [summonBin, ...args, "--yes"], {
53
+ cwd,
54
+ stdio: "pipe",
55
+ // A child with no stdin is the CI shape: `isTTY` is false, so the bin takes
56
+ // its non-interactive path with the answers it was given on the flags.
57
+ input: "",
58
+ });
59
+ return snapshotTree(cwd);
60
+ }
61
+
62
+ /** One case: the bin's argv, and the equivalent answers for the reference. */
63
+ interface Case {
64
+ readonly name: string;
65
+ readonly module: string;
66
+ readonly args: readonly string[];
67
+ readonly answers: Record<string, unknown>;
68
+ }
69
+
70
+ const cases: Case[] = [
71
+ {
72
+ name: "example/hello",
73
+ module: "../../generators/example/hello/index.js",
74
+ args: [
75
+ "example",
76
+ "hello",
77
+ "--name=conformance-app",
78
+ "--description=A conformance fixture.",
79
+ "--greeting=Hey",
80
+ ],
81
+ answers: {
82
+ name: "conformance-app",
83
+ description: "A conformance fixture.",
84
+ greeting: "Hey",
85
+ withReadme: true,
86
+ },
87
+ },
88
+ {
89
+ name: "example/hello without the optional README",
90
+ module: "../../generators/example/hello/index.js",
91
+ args: [
92
+ "example",
93
+ "hello",
94
+ "--name=terse-app",
95
+ "--description=No readme.",
96
+ "--greeting=Hi",
97
+ "--no-with-readme",
98
+ ],
99
+ answers: {
100
+ name: "terse-app",
101
+ description: "No readme.",
102
+ greeting: "Hi",
103
+ withReadme: false,
104
+ },
105
+ },
106
+ {
107
+ name: "example/webapp",
108
+ module: "../../generators/example/webapp/index.js",
109
+ args: [
110
+ "example",
111
+ "webapp",
112
+ "--name=conformance-web",
113
+ "--description=A conformance webapp.",
114
+ "--framework=react",
115
+ "--styling=tailwind",
116
+ "--features=router,state",
117
+ "--no-with-tests",
118
+ ],
119
+ answers: {
120
+ name: "conformance-web",
121
+ description: "A conformance webapp.",
122
+ framework: "react",
123
+ styling: "tailwind",
124
+ features: ["router", "state"],
125
+ withTests: false,
126
+ withDocs: true,
127
+ installDeps: false,
128
+ },
129
+ },
130
+ {
131
+ name: "init",
132
+ module: "../../generators/init/index.js",
133
+ args: [
134
+ "init",
135
+ "--generator-path=component/vue",
136
+ "--description=A vue generator.",
137
+ ],
138
+ answers: {
139
+ generatorPath: "component/vue",
140
+ description: "A vue generator.",
141
+ outputDir: "./generators",
142
+ },
143
+ },
144
+ ];
145
+
146
+ describe("byte-equality conformance — the summon bin ≡ the reference (PROTECTED)", () => {
147
+ it("the builtin dir ships EXACTLY the leaves this matrix covers — a fourth builtin must join it", () => {
148
+ // The declaration tie: enumerate the leaves the bin discovers (every
149
+ // dir under generators/ holding an index.ts — bin.tsx mounts whatever
150
+ // is there) and hold them to the covered set. The docblock once said
151
+ // "the two the bin actually ships" while three leaves shipped;
152
+ // example/webapp was covered by NOTHING and no suite could tell.
153
+ const builtinDir = join(packageRoot, "generators");
154
+ const leaves: string[] = [];
155
+ const walk = (dir: string, prefix: string): void => {
156
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
157
+ if (!entry.isDirectory()) continue;
158
+ const child = join(dir, entry.name);
159
+ const leafPath = prefix ? `${prefix}/${entry.name}` : entry.name;
160
+ if (existsSync(join(child, "index.ts"))) leaves.push(leafPath);
161
+ else walk(child, leafPath);
162
+ }
163
+ };
164
+ walk(builtinDir, "");
165
+ expect(leaves.sort()).toEqual(["example/hello", "example/webapp", "init"]);
166
+ // …and the covered set is those three (hello twice: ± the README).
167
+ expect([...new Set(cases.map((c) => c.module))].sort()).toEqual([
168
+ "../../generators/example/hello/index.js",
169
+ "../../generators/example/webapp/index.js",
170
+ "../../generators/init/index.js",
171
+ ]);
172
+ });
173
+
174
+ for (const testCase of cases) {
175
+ it(`${testCase.name}: the bin's tree matches the reference byte for byte`, async () => {
176
+ const bin = produceBin(testCase.args);
177
+ const { generator } = (await import(testCase.module)) as {
178
+ generator: Parameters<typeof produceReference>[0]["generator"];
179
+ };
180
+ const reference = await produceReference({
181
+ generator,
182
+ answers: testCase.answers,
183
+ });
184
+ expect(bin.size).toBeGreaterThan(0);
185
+ const diff = diffTrees(bin, reference);
186
+ expect(
187
+ isIdentical(diff),
188
+ formatTreeDiff(diff, "the summon bin", "the conformance reference"),
189
+ ).toBe(true);
190
+ }, 60_000);
191
+ }
192
+ });
@@ -0,0 +1,2 @@
1
+ export { default as buildCommandBarrel } from "./buildCommandBarrel.js";
2
+ export { default as registerFromBarrel } from "./registerFromBarrel.js";