@canonical/summon 0.17.0 → 0.20.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 (39) 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 +24 -27
  6. package/src/bin.tsx +199 -0
  7. package/src/completion.ts +4 -1
  8. package/src/components/App.tsx +108 -15
  9. package/src/components/ExecutionProgress.tsx +8 -4
  10. package/src/components/FileTreePreview.tsx +1 -1
  11. package/src/components/PromptSequence.tsx +1 -1
  12. package/src/discovery/loadGenerator.ts +37 -0
  13. package/src/display/index.ts +2 -0
  14. package/src/display/printGeneratorHelp.ts +133 -0
  15. package/src/display/printNode.ts +76 -0
  16. package/src/registration/buildCommandBarrel.ts +57 -0
  17. package/src/registration/index.ts +3 -0
  18. package/src/registration/registerFromBarrel.tsx +548 -0
  19. package/src/registration/types.ts +28 -0
  20. package/README.md +0 -446
  21. package/src/__tests__/combinators.test.ts +0 -895
  22. package/src/__tests__/dry-run.test.ts +0 -927
  23. package/src/__tests__/effect.test.ts +0 -816
  24. package/src/__tests__/interpreter.test.ts +0 -673
  25. package/src/__tests__/primitives.test.ts +0 -970
  26. package/src/__tests__/task.test.ts +0 -929
  27. package/src/__tests__/template.test.ts +0 -666
  28. package/src/cli-format.ts +0 -236
  29. package/src/cli-types.ts +0 -53
  30. package/src/cli.tsx +0 -1366
  31. package/src/combinators.ts +0 -294
  32. package/src/dry-run.ts +0 -434
  33. package/src/effect.ts +0 -224
  34. package/src/index.ts +0 -266
  35. package/src/interpreter.ts +0 -463
  36. package/src/primitives.ts +0 -442
  37. package/src/task.ts +0 -245
  38. package/src/template.ts +0 -537
  39. package/src/types.ts +0 -453
package/README.md DELETED
@@ -1,446 +0,0 @@
1
- # Summon
2
-
3
- A code generator framework where generators are pure functions that return data, not side effects.
4
-
5
- Write a generator once. Run it for real. Preview with `--dry-run`. Test without mocks. Same code, different interpreters.
6
-
7
- ```typescript
8
- generate: (answers) => writeFile(`src/${answers.name}.ts`, code)
9
- // Returns a Task describing "write this file"
10
- // Not a file write. Data.
11
- ```
12
-
13
- ## Installation
14
-
15
- ```bash
16
- bun add @canonical/summon
17
- ```
18
-
19
- ## Using Generators
20
-
21
- Summon discovers generators from installed packages automatically.
22
-
23
- ```bash
24
- # See what's available
25
- summon
26
-
27
- # Run a generator interactively
28
- summon component react
29
-
30
- # Pass answers as positional argument (when supported)
31
- summon component react src/components/Button
32
-
33
- # Or as a flag
34
- summon component react --component-path=src/components/Button
35
-
36
- # Preview first (nothing written to disk)
37
- summon component react src/components/Button --dry-run
38
-
39
- # Show debug output
40
- summon component react src/components/Button --verbose
41
- ```
42
-
43
- Every prompt becomes a CLI flag. Boolean prompts with `default: true` use the `--no-` prefix to disable. Generators may also define a **positional argument** for their primary input (like a path), allowing cleaner command invocations.
44
-
45
- ### CLI Options
46
-
47
- | Flag | Description |
48
- |------|-------------|
49
- | `-d, --dry-run` | Preview without writing files |
50
- | `-y, --yes` | Skip confirmation prompts and preview |
51
- | `-v, --verbose` | Show debug output |
52
- | `--show-contents` | Show file contents in dry-run (useful for LLMs) |
53
- | `--no-preview` | Skip the file preview |
54
- | `--no-generated-stamp` | Disable generated file stamp comments |
55
-
56
- **LLM Usage:** The `--show-contents` flag is particularly useful for AI assistants and LLM agents. When combined with `--dry-run`, it outputs the complete generated file contents, allowing the LLM to review, analyze, or use the generated code without writing to disk:
57
-
58
- ```bash
59
- summon component react src/components/Button --dry-run --show-contents -y
60
- ```
61
-
62
- ### Shell Autocompletion
63
-
64
- Summon supports TAB completion for Bash, Zsh, and Fish shells. Completions are **dynamic** - they automatically detect newly installed generator packages without needing to re-run setup.
65
-
66
- ```bash
67
- # Automatic setup (recommended)
68
- summon --setup-completion
69
-
70
- # Or manual installation for each shell:
71
-
72
- # Zsh
73
- echo '. <(summon --completion)' >> ~/.zshrc
74
-
75
- # Bash (may need: brew install bash-completion on macOS)
76
- summon --completion >> ~/.summon-completion.sh
77
- echo 'source ~/.summon-completion.sh' >> ~/.bash_profile
78
-
79
- # Fish
80
- echo 'summon --completion-fish | source' >> ~/.config/fish/config.fish
81
- ```
82
-
83
- After setup, restart your shell or source the config file. Then:
84
-
85
- ```bash
86
- summon <TAB> # Shows: component, init, ...
87
- summon component <TAB> # Shows: react, svelte
88
- summon component react <TAB> # Shows: --component-path, --no-with-styles, ...
89
- summon component react --comp<TAB> # Completes to: --component-path
90
- ```
91
-
92
- Completion features:
93
- - **Generator names** - Navigate the command tree with TAB
94
- - **Generator flags** - All prompts become completable flags
95
- - **Confirm prompts** - Shows `--no-X` for prompts with `default: true`
96
- - **Select/multiselect** - Completes with available choices
97
- - **Path prompts** - Filesystem path completion for prompts containing "path", "dir", "file", etc.
98
-
99
- To remove autocompletion:
100
-
101
- ```bash
102
- summon --cleanup-completion
103
- ```
104
-
105
- ### Positional Arguments
106
-
107
- Generators can define one prompt as a **positional argument**, allowing users to provide the primary input without a flag:
108
-
109
- ```bash
110
- # With positional argument support
111
- summon component react src/components/Button
112
-
113
- # Equivalent to
114
- summon component react --component-path=src/components/Button
115
- ```
116
-
117
- Positional arguments also get filesystem path completion when using TAB:
118
-
119
- ```bash
120
- summon component react src/comp<TAB> # Completes to: src/components/
121
- ```
122
-
123
- ### Installing Generator Packages
124
-
125
- Generator packages follow the naming convention `summon-*` or `@scope/summon-*`:
126
-
127
- ```bash
128
- # Install a generator package
129
- bun add @canonical/summon-component
130
-
131
- # Now available (completions work immediately!)
132
- summon component react
133
- summon component svelte
134
- ```
135
-
136
- ## Creating Generators
137
-
138
- A generator is a pure function that takes answers and returns a `Task`—a data structure describing what to do.
139
-
140
- ```typescript
141
- // src/module/types.ts
142
- interface ModuleAnswers {
143
- name: string;
144
- withTests: boolean;
145
- }
146
-
147
- // src/module/generator.ts
148
- import type { GeneratorDefinition } from "@canonical/summon";
149
- import { debug, info, writeFile, mkdir, sequence_, when } from "@canonical/summon";
150
- import type { ModuleAnswers } from "./types.js";
151
-
152
- export const generator = {
153
- meta: {
154
- name: "module",
155
- description: "Creates a new module",
156
- version: "0.1.0",
157
- },
158
-
159
- prompts: [
160
- // positional: true allows `summon module src/utils` instead of `--name=src/utils`
161
- { name: "name", type: "text", message: "Module name:", positional: true },
162
- { name: "withTests", type: "confirm", message: "Include tests?", default: true },
163
- ],
164
-
165
- generate: (answers) => sequence_([
166
- info(`Creating module: ${answers.name}`),
167
-
168
- debug("Creating module directory"),
169
- mkdir(`src/${answers.name}`),
170
-
171
- debug("Creating index file"),
172
- writeFile(`src/${answers.name}/index.ts`, `export const ${answers.name} = {};\n`),
173
-
174
- when(answers.withTests, debug("Creating test file")),
175
- when(answers.withTests,
176
- writeFile(`src/${answers.name}/index.test.ts`, `test("works", () => {});\n`)
177
- ),
178
-
179
- info(`Created module at src/${answers.name}`),
180
- ]),
181
- } as const satisfies GeneratorDefinition<ModuleAnswers>;
182
-
183
- // src/module/index.ts (barrel)
184
- export { generator } from "./generator.js";
185
- export type { ModuleAnswers } from "./types.js";
186
-
187
- // src/index.ts (package barrel)
188
- import type { AnyGenerator } from "@canonical/summon";
189
- import { generator as moduleGenerator } from "./module/index.js";
190
-
191
- export const generators = {
192
- "module": moduleGenerator,
193
- } as const satisfies Record<string, AnyGenerator>;
194
- ```
195
-
196
- ### Package Structure
197
-
198
- Each generator should be split into three files for maintainability:
199
-
200
- ```
201
- my-summon-package/
202
- ├── package.json
203
- ├── src/
204
- │ ├── index.ts # Package barrel - exports generators record
205
- │ ├── module/
206
- │ │ ├── index.ts # Generator barrel
207
- │ │ ├── types.ts # Answer types
208
- │ │ └── generator.ts # Generator definition
209
- │ └── templates/ # EJS templates (optional)
210
- └── README.md
211
- ```
212
-
213
- ```json
214
- {
215
- "name": "@myorg/summon-module",
216
- "main": "src/index.ts",
217
- "peerDependencies": {
218
- "@canonical/summon": "workspace:*"
219
- }
220
- }
221
- ```
222
-
223
- ### Local Development
224
-
225
- For developing generators locally, link them to make them globally available:
226
-
227
- ```bash
228
- # From your generator package directory
229
- cd /path/to/my-summon-package
230
- bun link # for bun
231
- npm link # for npm
232
-
233
- # Now available everywhere
234
- summon module src/utils
235
- ```
236
-
237
- Project-local packages (in `./node_modules`) take precedence over globally linked ones, so you can override with project-specific versions.
238
-
239
- ### Testing Generators
240
-
241
- Because generators return data, testing is straightforward—no mocks needed:
242
-
243
- ```typescript
244
- import { dryRun, getAffectedFiles } from "@canonical/summon";
245
- import { generators } from "./index";
246
-
247
- const generator = generators["module"];
248
-
249
- test("creates expected files", () => {
250
- const task = generator.generate({ name: "utils", withTests: true });
251
- const { effects } = dryRun(task);
252
-
253
- expect(getAffectedFiles(effects)).toEqual([
254
- "src/utils/index.ts",
255
- "src/utils/index.test.ts",
256
- ]);
257
- });
258
-
259
- test("skips test file when disabled", () => {
260
- const task = generator.generate({ name: "utils", withTests: false });
261
- const { effects } = dryRun(task);
262
-
263
- expect(getAffectedFiles(effects)).not.toContain("src/utils/index.test.ts");
264
- });
265
- ```
266
-
267
- The dry-run interpreter maintains a virtual filesystem, so conditional logic based on `exists()` works correctly even without touching the disk.
268
-
269
- ## The Monadic Pattern
270
-
271
- Summon uses a **monad** to compose tasks. If you've used Promises, you already understand the core idea.
272
-
273
- ### What's a Monad?
274
-
275
- A monad is a design pattern for chaining operations that have some context (like "might fail" or "has effects"). Think of it as a pipeline where each step can:
276
-
277
- 1. **Transform values** (`map`) — Apply a function to the result
278
- 2. **Chain operations** (`flatMap`) — Use the result to create the next step
279
- 3. **Short-circuit on failure** — Errors propagate automatically
280
-
281
- ```typescript
282
- // Promise (async context)
283
- fetchUser(id)
284
- .then(user => fetchOrders(user.id)) // chain
285
- .then(orders => orders.length) // transform
286
- .catch(handleError); // recover
287
-
288
- // Task (effect context)
289
- task(readFile("config.json"))
290
- .map(content => JSON.parse(content)) // transform
291
- .flatMap(config => writeFile( // chain
292
- config.outputPath,
293
- generateCode(config)
294
- ))
295
- .recover(err => pure(defaultConfig)); // recover
296
- ```
297
-
298
- ### The Task Type
299
-
300
- `Task<A>` represents a computation that:
301
- - Describes effects (file I/O, shell commands, etc.)
302
- - Eventually produces a value of type `A`
303
- - May fail with an error
304
-
305
- ```typescript
306
- // A Task is one of three things:
307
- type Task<A> =
308
- | { _tag: "Pure"; value: A } // Done, here's the value
309
- | { _tag: "Fail"; error: TaskError } // Failed with error
310
- | { _tag: "Effect"; effect: Effect; cont: ... } // Do this effect, then continue
311
- ```
312
-
313
- ### Composing Tasks
314
-
315
- The `TaskBuilder` provides a fluent API for composition:
316
-
317
- ```typescript
318
- import { task, pure } from "@canonical/summon";
319
-
320
- // Build a pipeline
321
- const pipeline = task(readFile("input.txt"))
322
- .map(content => content.toUpperCase()) // Transform the value
323
- .flatMap(upper => writeFile("output.txt", upper)) // Chain another effect
324
- .andThen(info("Done!")) // Sequence (ignore previous value)
325
- .recover(err => pure(void 0)); // Handle errors
326
-
327
- // pipeline is still just data — nothing has executed yet
328
- ```
329
-
330
- ### Key Operations
331
-
332
- | Operation | Description | Example |
333
- |-----------|-------------|---------|
334
- | `pure(value)` | Wrap a value in a Task | `pure(42)` |
335
- | `map(fn)` | Transform the result | `.map(x => x * 2)` |
336
- | `flatMap(fn)` | Chain with another Task | `.flatMap(x => writeFile(...))` |
337
- | `andThen(task)` | Sequence, discard previous | `.andThen(info("next"))` |
338
- | `recover(fn)` | Handle errors | `.recover(e => pure(default))` |
339
- | `tap(fn)` | Side effect, keep value | `.tap(x => debug(x))` |
340
-
341
- ### Why Monads for Generators?
342
-
343
- 1. **Composable** — Small tasks combine into complex workflows
344
- 2. **Predictable** — Errors propagate without explicit handling at each step
345
- 3. **Testable** — The pipeline is data; inspect it without running effects
346
- 4. **Declarative** — Describe *what* to do, not *how* to do it
347
-
348
- ```typescript
349
- // Complex workflow, reads like a recipe
350
- const scaffoldFeature = (name: string) =>
351
- task(mkdir(`src/features/${name}`))
352
- .andThen(template({
353
- source: "templates/feature.ts.ejs",
354
- dest: `src/features/${name}/index.ts`,
355
- vars: { name },
356
- }))
357
- .andThen(when(config.withTests,
358
- template({
359
- source: "templates/test.ts.ejs",
360
- dest: `src/features/${name}/index.test.ts`,
361
- vars: { name },
362
- })
363
- ))
364
- .andThen(info(`Created feature: ${name}`))
365
- .unwrap();
366
- ```
367
-
368
- For a deeper dive into the "effects as data" philosophy, see [Explanation](docs/explanation.md).
369
-
370
- ## Templating Engine
371
-
372
- Summon uses EJS by default for template rendering, but supports custom templating engines via the `TemplatingEngine` interface.
373
-
374
- ### Default (EJS)
375
-
376
- ```typescript
377
- import { template, templateDir } from "@canonical/summon";
378
-
379
- // Uses EJS by default
380
- template({
381
- source: "templates/component.tsx.ejs",
382
- dest: "src/components/<%= name %>.tsx",
383
- vars: { name: "Button" },
384
- });
385
- ```
386
-
387
- ### Custom Engines
388
-
389
- Implement `TemplatingEngine` to use Handlebars, Mustache, Nunjucks, or any other engine:
390
-
391
- ```typescript
392
- import type { TemplatingEngine } from "@canonical/summon";
393
- import Handlebars from "handlebars";
394
- import * as fs from "node:fs/promises";
395
-
396
- const handlebarsEngine: TemplatingEngine = {
397
- render(template, vars) {
398
- return Handlebars.compile(template)(vars);
399
- },
400
-
401
- async renderAsync(template, vars) {
402
- return Handlebars.compile(template)(vars);
403
- },
404
-
405
- async renderFile(templatePath, vars) {
406
- const content = await fs.readFile(templatePath, "utf-8");
407
- return Handlebars.compile(content)(vars);
408
- },
409
- };
410
-
411
- // Use in templates
412
- template({
413
- source: "templates/component.hbs",
414
- dest: "src/components/{{name}}.tsx",
415
- vars: { name: "Button" },
416
- engine: handlebarsEngine,
417
- });
418
- ```
419
-
420
- ### Interface
421
-
422
- ```typescript
423
- interface TemplatingEngine {
424
- /** Render a template string synchronously */
425
- render(template: string, vars: Record<string, unknown>): string;
426
-
427
- /** Render a template string asynchronously */
428
- renderAsync(template: string, vars: Record<string, unknown>): Promise<string>;
429
-
430
- /** Render a template file asynchronously */
431
- renderFile(templatePath: string, vars: Record<string, unknown>): Promise<string>;
432
- }
433
- ```
434
-
435
- The `engine` option is available on `template()`, `templateDir()`, `renderString()`, `renderStringAsync()`, and `renderFile()`.
436
-
437
- ## Documentation
438
-
439
- - **[Tutorial](docs/tutorial.md)** — Build your first generator from scratch
440
- - **[How-To Guides](docs/how-to.md)** — Solve specific problems
441
- - **[Reference](docs/reference.md)** — Complete API documentation
442
- - **[Explanation](docs/explanation.md)** — Why effects as data? The ideas behind Summon
443
-
444
- ## License
445
-
446
- GPL-3.0