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