@email-kit/cli 1.0.0 → 1.1.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/dist/cli.js CHANGED
@@ -1,15 +1,15 @@
1
1
  #!/usr/bin/env node
2
2
  import { SourceMap, createRequire } from "node:module";
3
3
  import process$1 from "node:process";
4
+ import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, rmdirSync, statSync, watch, writeFileSync } from "node:fs";
5
+ import { basename, dirname, isAbsolute, join, posix, relative, resolve, sep } from "node:path";
4
6
  import { cac } from "cac";
7
+ import { fileURLToPath, pathToFileURL } from "node:url";
5
8
  import { hasChildren, isComment, isTag, isText } from "domhandler";
6
9
  import { parseDocument } from "htmlparser2";
7
10
  import postcss from "postcss";
8
11
  import { blend, clampRgb, colorsNamed, converter, formatHex, parse, toGamut, wcagContrast } from "culori";
9
12
  import { EmailKitError, RESERVED_KEY, SENDER_KEYS, evaluate, familyList, fontClass, isEmailDefinition, isEmailKitError, isTemplateId, messageArguments, parseRoleClass, pseudoMessage, roleClass } from "@email-kit/core/internal";
10
- import { basename, dirname, isAbsolute, join, posix, relative, resolve, sep } from "node:path";
11
- import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, rmdirSync, statSync, watch, writeFileSync } from "node:fs";
12
- import { fileURLToPath, pathToFileURL } from "node:url";
13
13
  import { parseAst } from "rolldown/parseAst";
14
14
  import { createHash, randomUUID } from "node:crypto";
15
15
  import { findNodeAtLocation, parse as parse$1, parseTree } from "jsonc-parser";
@@ -19,7 +19,520 @@ import { stripVTControlCharacters, styleText } from "node:util";
19
19
  import { access, mkdir, rename, rm, writeFile } from "node:fs/promises";
20
20
  import { isolatedDeclarationSync } from "rolldown/experimental";
21
21
  import { transformSync } from "rolldown/utils";
22
- import { cancel, confirm, isCancel, text } from "@clack/prompts";
22
+ import { cancel, confirm, isCancel, multiselect, text } from "@clack/prompts";
23
+ // src/paths.ts
24
+ /**
25
+ * A path relative to `from`, always with `/`: for findings, reporters, config files and imports,
26
+ * which read the same on every platform. `path.relative` uses `\` on Windows.
27
+ */
28
+ function relativePath(from, to) {
29
+ return toPosix(relative(from, to));
30
+ }
31
+ /** `src\mail` → `src/mail`; unchanged on POSIX. */
32
+ function toPosix(path) {
33
+ return sep === "\\" ? path.replaceAll("\\", "/") : path;
34
+ }
35
+ /** Whether `path` exists and is a folder. */
36
+ function isDirectory(path) {
37
+ return existsSync(path) && statSync(path).isDirectory();
38
+ }
39
+ /** Whether `path` is `folder` itself or anywhere inside it. */
40
+ function isWithin(folder, path) {
41
+ const rel = relative(folder, path);
42
+ return rel === "" || !rel.startsWith("..") && !isAbsolute(rel);
43
+ }
44
+ // src/agents/instructions.ts
45
+ const END = "<!-- email-kit:end -->";
46
+ /** The section's first line. In a monorepo it names the project, so each app has its own. */
47
+ const startOf = (project) => project ? `<!-- email-kit:start ${project} -->` : "<!-- email-kit:start -->";
48
+ /**
49
+ * The section email-kit keeps in `AGENTS.md`, `CLAUDE.md` or `GEMINI.md`: where the emails are,
50
+ * the commands, and the skill to read for the rest. It's short because agents load these files
51
+ * into every conversation; the skill loads only when a task needs it.
52
+ */
53
+ function section(pointer) {
54
+ const { project, folder, out, importPath, runner, skill } = pointer;
55
+ const cli = (command) => `\`${runner} email-kit ${command}\``;
56
+ const imports = importPath ? `\`${importPath}\`, as \`emails.<id>.render(data, { locale })\`` : `\`${folder}/index.ts\`, as \`emails.<id>.render(data, { locale })\``;
57
+ return [
58
+ startOf(project),
59
+ `## Emails${project ? ` in ${project}` : ""} (email-kit)`,
60
+ "",
61
+ `The emails this project sends are email-kit templates in \`${folder}/\`, one folder per email. Before you add or change an email, its copy or translations, or the code that sends it, read the email-kit skill: \`${skill}\`.`,
62
+ "",
63
+ ...project ? [`- Run email-kit commands in \`${project}\`.`] : [],
64
+ `- ${cli("new <id>")} adds an email. After each change, run ${cli("compile")}, then ${cli("check")}, and fix what they report.`,
65
+ `- Never edit \`${out}/\`: it's compiled output.`,
66
+ `- The app imports the emails from ${imports}.`,
67
+ END
68
+ ].join("\n");
69
+ }
70
+ /** `text` escaped for use in a regular expression. */
71
+ const escapeRegExp$1 = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
72
+ /**
73
+ * An instructions file with the project's section added or replaced, and everything else left as
74
+ * it was. `existing` is the file's content, or `undefined` for a file that doesn't exist yet.
75
+ */
76
+ function withSection(existing, project, text) {
77
+ if (existing === void 0 || existing.trim() === "") return `${text}\n`;
78
+ const block = new RegExp(`${escapeRegExp$1(startOf(project))}\\r?\\n[\\s\\S]*?${escapeRegExp$1(END)}`);
79
+ if (block.test(existing)) return existing.replace(block, () => text);
80
+ return `${existing.replace(/\s*$/, "")}\n\n${text}\n`;
81
+ }
82
+ /** Whether an instructions file has a section for the project. */
83
+ const hasSection = (existing, project) => existing.includes(startOf(project));
84
+ // src/version.ts
85
+ /**
86
+ * The email-kit version, from package.json. `--version` prints it, the compiler writes it into
87
+ * generated files and the manifest, and `init` uses it for the dependency ranges it adds.
88
+ */
89
+ const VERSION = "1.1.0";
90
+ // src/agents/skill.ts
91
+ /** The skill's name, and its folder's name in `.agents/skills/` and `.claude/skills/`. */
92
+ const SKILL_NAME = "email-kit";
93
+ /**
94
+ * The documentation pages the CLI ships for agents, in `dist/docs/`, by their path on the site and
95
+ * under `docs/` in the repository. The skill links to them instead of carrying copies, so a project
96
+ * holds only `SKILL.md` and the pages always match the installed version.
97
+ */
98
+ const DOC_PAGES = [...[
99
+ "templates",
100
+ "components",
101
+ "messages",
102
+ "theme",
103
+ "checks-and-ci",
104
+ "sending",
105
+ "formatting"
106
+ ].map((page) => `guide/${page}`), ...[
107
+ "cli",
108
+ "configuration",
109
+ "checks",
110
+ "errors",
111
+ "mustache-core"
112
+ ].map((page) => `reference/${page}`)];
113
+ /** The documentation site, which the skill in the repository links to. */
114
+ const SITE = "https://email-kit.dev";
115
+ /** Where the CLI's docs are inside its package. */
116
+ const PACKAGE_DOCS = "node_modules/@email-kit/cli/dist/docs";
117
+ /**
118
+ * The paragraph of the repository's `SKILL.md` that says where its links go. The copy `email-kit
119
+ * agents` writes says {@link localNote} instead.
120
+ */
121
+ const SITE_NOTE = `Read the page the task needs. Each is a page of the documentation at ${SITE}, which
122
+ describes the latest version; ${SITE}/llms-full.txt has all of it in one file. When
123
+ the project has email-kit installed, the same pages for its version are in
124
+ \`${PACKAGE_DOCS}/\`, such as \`reference/errors.md\`: read those instead.`;
125
+ /** The same paragraph, in a copy whose links go to the installed CLI's docs in `docs`. */
126
+ const localNote = (docs) => [
127
+ "Read the page the task needs. The links go to the documentation of the installed email-kit",
128
+ "version, which comes with the CLI. From the repository root, it's in:",
129
+ "",
130
+ ` ${docs}/`,
131
+ "",
132
+ `If that folder isn't there (before an install), read the same page at ${SITE}, such as`,
133
+ `${SITE}/reference/errors for \`reference/errors.md\`, or all of it at`,
134
+ `${SITE}/llms-full.txt.`
135
+ ].join("\n");
136
+ /**
137
+ * How a link in a skill folder reaches the repository root. Both `.agents/skills/email-kit/` and
138
+ * `.claude/skills/email-kit/` are three folders down, so their copies are the same.
139
+ */
140
+ const TO_ROOT = "../../../";
141
+ /**
142
+ * The folder of the skill this CLI ships: `dist/skill/email-kit/` in the published package, which
143
+ * the build copies from the repository's `skills/email-kit/`, or that folder itself when the CLI
144
+ * runs from its sources.
145
+ */
146
+ function bundledSkillDir() {
147
+ const candidates = [new URL("./skill/email-kit/", import.meta.url), new URL("../../../../skills/email-kit/", import.meta.url)];
148
+ for (const url of candidates) {
149
+ const dir = fileURLToPath(url);
150
+ if (existsSync(join(dir, "SKILL.md"))) return dir;
151
+ }
152
+ throw new Error("This copy of @email-kit/cli has no email-kit skill in it. Reinstall it.");
153
+ }
154
+ /** Every file in a folder, by `/`-separated relative path, skipping names that start with `.`. */
155
+ function readTree(dir) {
156
+ const files = /* @__PURE__ */ new Map();
157
+ for (const entry of readdirSync(dir, {
158
+ recursive: true,
159
+ withFileTypes: true
160
+ })) {
161
+ if (!entry.isFile()) continue;
162
+ const path = toPosix(relative(dir, join(entry.parentPath, entry.name)));
163
+ if (path.split("/").some((part) => part.startsWith("."))) continue;
164
+ files.set(path, readFileSync(join(dir, path), "utf8"));
165
+ }
166
+ return new Map([...files].sort(([a], [b]) => a.localeCompare(b)));
167
+ }
168
+ let bundled;
169
+ /** The skill's files as this CLI ships them, with their links to the site. */
170
+ function bundledSkill() {
171
+ bundled ??= readTree(bundledSkillDir());
172
+ return bundled;
173
+ }
174
+ /** The line that records which version of email-kit wrote a copy of the skill. */
175
+ const STAMP = /\nmetadata:\n {2}email-kit-version: "([^"\n]*)"/;
176
+ /**
177
+ * `SKILL.md` with the version that writes it as `metadata.email-kit-version`, at the end of the
178
+ * frontmatter, so `check` and `email-kit agents` can tell which version a copy came from.
179
+ */
180
+ function stamp(skillMd, version) {
181
+ const end = skillMd.indexOf("\n---", 3);
182
+ return `${skillMd.slice(0, end)}\nmetadata:\n email-kit-version: "${version}"${skillMd.slice(end)}`;
183
+ }
184
+ const escapeRegExp = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
185
+ /** A link to one of {@link DOC_PAGES} on the site: the page, and an optional `#` part. */
186
+ const SITE_LINK = new RegExp(`\\]\\(${escapeRegExp(SITE)}/(${DOC_PAGES.map(escapeRegExp).join("|")})(#[^)\\s]*)?\\)`, "g");
187
+ /**
188
+ * `SKILL.md` with its links to the shipped pages going to the installed CLI's copy instead, in
189
+ * `docs`, relative to the repository root. Links to other pages stay on the site.
190
+ */
191
+ function localize(skillMd, docs) {
192
+ return skillMd.replace(SITE_LINK, (_, page, hash = "") => `](${TO_ROOT}${docs}/${page}.md${hash})`).replace(SITE_NOTE, () => localNote(docs));
193
+ }
194
+ /**
195
+ * The installed CLI's docs, relative to the repository root `root`: the nearest
196
+ * `node_modules/@email-kit/cli` from the project's folder up to the root, as npm, pnpm and Yarn
197
+ * link it, or the project's own when there's none yet, as before an install.
198
+ */
199
+ function docsFolder(root, project) {
200
+ for (let at = project;; at = dirname(at)) {
201
+ if (existsSync(join(at, "node_modules/@email-kit/cli/package.json"))) return toPosix(join(relativePath(root, at), PACKAGE_DOCS));
202
+ if (at === root || dirname(at) === at) break;
203
+ }
204
+ return toPosix(join(relativePath(root, project), PACKAGE_DOCS));
205
+ }
206
+ /** The skill's files as `email-kit agents` writes them, linking to the docs in `docs`. */
207
+ function skillForProject(docs, version = VERSION) {
208
+ const files = new Map(bundledSkill());
209
+ files.set("SKILL.md", stamp(localize(files.get("SKILL.md") ?? "", docs), version));
210
+ return files;
211
+ }
212
+ /** Whether a `SKILL.md` is email-kit's: its frontmatter names the skill `email-kit`. */
213
+ function isOurs$1(skillMd) {
214
+ const frontmatter = /^---\n([\s\S]*?)\n---/.exec(skillMd.replaceAll("\r\n", "\n"))?.[1] ?? "";
215
+ return /^name:\s*["']?email-kit["']?\s*$/m.test(frontmatter);
216
+ }
217
+ /** The skill files with their version stamp taken out, so copies compare by content. */
218
+ const unstamped = (files) => JSON.stringify([...files].map(([path, text]) => [path, path === "SKILL.md" ? text.replace(STAMP, "") : text]));
219
+ /** The docs folder a written copy's links go to, or `undefined` for one that links to the site. */
220
+ const LINKED_DOCS = new RegExp(`\\]\\(${escapeRegExp(TO_ROOT)}([^)\\s]*?${escapeRegExp(PACKAGE_DOCS)})/`);
221
+ /** What's in the skill folder `dir`, such as `<repo>/.agents/skills/email-kit`. */
222
+ function skillState(dir) {
223
+ if (!existsSync(dir)) return { kind: "missing" };
224
+ const skillMd = join(dir, "SKILL.md");
225
+ if (!isDirectory(dir) || !existsSync(skillMd)) return { kind: "foreign" };
226
+ const text = readFileSync(skillMd, "utf8");
227
+ if (!isOurs$1(text)) return { kind: "foreign" };
228
+ const docs = LINKED_DOCS.exec(text)?.[1];
229
+ const expected = docs === void 0 ? bundledSkill() : skillForProject(docs);
230
+ return {
231
+ kind: "ours",
232
+ version: STAMP.exec(text)?.[1],
233
+ current: unstamped(readTree(dir)) === unstamped(expected)
234
+ };
235
+ }
236
+ /** Whether the skill folder `dir` holds exactly `files`. */
237
+ function hasExactly(dir, files) {
238
+ return JSON.stringify([...readTree(dir)]) === JSON.stringify([...files]);
239
+ }
240
+ /**
241
+ * Writes the skill into `dir`, which is missing or email-kit's own, and removes the files an older
242
+ * version had that this one doesn't.
243
+ */
244
+ function writeSkill(dir, files) {
245
+ if (existsSync(dir)) {
246
+ for (const path of readTree(dir).keys()) if (!files.has(path)) rmSync(join(dir, path));
247
+ removeEmptyFolders(dir);
248
+ }
249
+ for (const [path, text] of files) {
250
+ mkdirSync(dirname(join(dir, path)), { recursive: true });
251
+ writeFileSync(join(dir, path), text);
252
+ }
253
+ }
254
+ /** Removes the folders under `dir` that are left empty, such as an older version's `references/`. */
255
+ function removeEmptyFolders(dir) {
256
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
257
+ if (!entry.isDirectory()) continue;
258
+ const folder = join(dir, entry.name);
259
+ removeEmptyFolders(folder);
260
+ if (readdirSync(folder).length === 0) rmSync(folder, { recursive: true });
261
+ }
262
+ }
263
+ // src/agents/targets.ts
264
+ /**
265
+ * Every agent, in the order the question lists them. Each tool's locations are from its own docs
266
+ * (November 2026); see ADR 0009. Tools that wrap these agents, such as T3 Code or Conductor, read
267
+ * the files of the agent they run.
268
+ */
269
+ const AGENTS$1 = [
270
+ {
271
+ id: "claude",
272
+ label: "Claude Code",
273
+ skills: ".claude/skills",
274
+ instructions: "claude",
275
+ signs: [
276
+ "CLAUDE.md",
277
+ "CLAUDE.local.md",
278
+ ".claude"
279
+ ]
280
+ },
281
+ {
282
+ id: "codex",
283
+ label: "Codex",
284
+ skills: ".agents/skills",
285
+ instructions: "AGENTS.md",
286
+ signs: [".codex"]
287
+ },
288
+ {
289
+ id: "cursor",
290
+ label: "Cursor",
291
+ skills: ".agents/skills",
292
+ instructions: "AGENTS.md",
293
+ signs: [
294
+ ".cursor",
295
+ ".cursorrules",
296
+ ".cursorignore"
297
+ ]
298
+ },
299
+ {
300
+ id: "copilot",
301
+ label: "GitHub Copilot",
302
+ skills: ".agents/skills",
303
+ instructions: "AGENTS.md",
304
+ signs: [
305
+ ".github/copilot-instructions.md",
306
+ ".github/instructions",
307
+ ".github/prompts",
308
+ ".github/agents",
309
+ ".github/skills"
310
+ ]
311
+ },
312
+ {
313
+ id: "gemini",
314
+ label: "Gemini CLI",
315
+ skills: ".agents/skills",
316
+ instructions: "GEMINI.md",
317
+ signs: ["GEMINI.md", ".gemini"]
318
+ },
319
+ {
320
+ id: "antigravity",
321
+ label: "Antigravity",
322
+ skills: ".agents/skills",
323
+ instructions: "AGENTS.md",
324
+ signs: [
325
+ ".agent",
326
+ ".agents/rules",
327
+ ".agents/workflows"
328
+ ]
329
+ },
330
+ {
331
+ id: "windsurf",
332
+ label: "Windsurf",
333
+ skills: ".agents/skills",
334
+ instructions: "AGENTS.md",
335
+ signs: [".windsurf", ".windsurfrules"]
336
+ },
337
+ {
338
+ id: "agents-md",
339
+ label: "Other agents that read AGENTS.md",
340
+ inSentence: "other agents that read AGENTS.md",
341
+ hint: "Zed, Jules, Amp, opencode, Aider and more",
342
+ skills: ".agents/skills",
343
+ instructions: "AGENTS.md",
344
+ signs: ["AGENTS.md", ".agents/skills"]
345
+ }
346
+ ];
347
+ /** The agent with this id. */
348
+ const agentOf = (id) => AGENTS$1.find((agent) => agent.id === id);
349
+ /**
350
+ * The agents named in `--agents`: ids separated by commas, `all`, or `none`. Returns an error
351
+ * message for an id it doesn't know.
352
+ */
353
+ function parseAgents(value) {
354
+ const names = value.split(",").map((name) => name.trim().toLowerCase()).filter(Boolean);
355
+ if (names.length === 1 && names[0] === "none") return [];
356
+ if (names.length === 1 && names[0] === "all") return AGENTS$1.map((agent) => agent.id);
357
+ const unknown = names.filter((name) => !AGENTS$1.some((agent) => agent.id === name));
358
+ if (unknown.length > 0) return `Unknown agent "${unknown[0]}" (known: ${AGENTS$1.map((a) => a.id).join(", ")}, all, none)`;
359
+ return AGENTS$1.map((agent) => agent.id).filter((id) => names.includes(id));
360
+ }
361
+ /**
362
+ * The repository the project is in: the nearest folder from `dir` up with a `.git` (a folder, or a
363
+ * file in a worktree or submodule). Agents look for their files there, whichever folder they
364
+ * start in. Without one, the project's own folder.
365
+ */
366
+ function repositoryRoot(dir) {
367
+ for (let at = resolve(dir);; at = dirname(at)) {
368
+ if (existsSync(join(at, ".git"))) return at;
369
+ if (dirname(at) === at) return resolve(dir);
370
+ }
371
+ }
372
+ /** The agents with a sign of use in the repository root or the project's folder, in list order. */
373
+ function detectAgents(root, project) {
374
+ const folders = [.../* @__PURE__ */ new Set([root, project])];
375
+ return AGENTS$1.filter((agent) => agent.signs.some((sign) => folders.some((folder) => existsSync(join(folder, sign))))).map((agent) => agent.id);
376
+ }
377
+ // src/agents/index.ts
378
+ /**
379
+ * Sets up the AI coding agents a project uses: it writes the email-kit skill where they read
380
+ * skills, and a short section in the instructions file each always reads, pointing to it. The
381
+ * agents come from `--agents`, from what the repository shows (with `--yes`), or from a question
382
+ * with those preselected. A new file is created with the rest; a change to an existing file is
383
+ * asked about first. Returns the exit code.
384
+ */
385
+ async function setUpAgents(project, options, io) {
386
+ const root = repositoryRoot(project.dir);
387
+ const detected = detectAgents(root, project.dir);
388
+ const agents = options.agents ?? await chooseAgents(detected, options, io);
389
+ if (agents === void 0) return 1;
390
+ if (agents.length === 0) {
391
+ if (options.command === "agents") io.out("Nothing was changed.");
392
+ return 0;
393
+ }
394
+ const docs = docsFolder(root, project.dir);
395
+ const files = skillForProject(docs);
396
+ const skills = skillTargets(root, agents, files);
397
+ const instructions = instructionTargets(root, project, agents, skills);
398
+ io.out(plan$1(root, project.dir, agents, skills, instructions, docs));
399
+ const changes = instructions.filter((t) => t.status === "add" || t.status === "update");
400
+ const accepted = /* @__PURE__ */ new Set();
401
+ for (const target of changes) {
402
+ const message = target.status === "add" ? `${target.path}: add a section that points agents to the email-kit skill?` : `${target.path}: update email-kit's section?`;
403
+ if (options.yes || await io.prompter.confirm(message, true)) accepted.add(target.path);
404
+ }
405
+ for (const skill of skills) if (skill.status === "create" || skill.status === "update") writeSkill(join(root, skill.path), files);
406
+ for (const target of instructions) if (target.status === "create" || accepted.has(target.path)) writeFileSync(join(root, target.path), target.content);
407
+ const labels = list(agents.map(nameOf));
408
+ const written = skills.some((s) => s.status === "create" || s.status === "update") || instructions.some((t) => t.status === "create" || accepted.has(t.path));
409
+ io.out(written ? `Set up the email-kit skill for ${labels}.` : `The email-kit skill for ${labels} is up to date.`);
410
+ return 0;
411
+ }
412
+ /**
413
+ * The agents to set up: with `--yes` the detected ones, otherwise the user's pick, with those
414
+ * preselected. `undefined` when `email-kit agents --yes` finds none, which it reports.
415
+ */
416
+ async function chooseAgents(detected, options, io) {
417
+ if (options.yes) {
418
+ if (detected.length > 0 || options.command === "init") return detected;
419
+ io.err(`✗ No AI coding agent's files in this repository. Name them with --agents, such as --agents claude,codex (known: ${AGENTS$1.map((a) => a.id).join(", ")}).`);
420
+ return;
421
+ }
422
+ return io.prompter.multiselect("Which AI coding agents should learn to write email-kit emails? (none to skip)", AGENTS$1.map((agent) => ({
423
+ value: agent.id,
424
+ label: agent.label,
425
+ ...agent.hint !== void 0 && { hint: agent.hint }
426
+ })), detected);
427
+ }
428
+ /** The skill folders the agents read, shared first, with what writing them would do. */
429
+ function skillTargets(root, agents, files) {
430
+ const folders = new Set(agents.map((id) => agentOf(id).skills));
431
+ return [".agents/skills", ".claude/skills"].filter((folder) => folders.has(folder)).map((folder) => {
432
+ const path = posix.join(folder, SKILL_NAME);
433
+ const state = skillState(join(root, path));
434
+ return {
435
+ path,
436
+ status: state.kind === "missing" ? "create" : state.kind === "foreign" ? "foreign" : hasExactly(join(root, path), files) ? "unchanged" : "update"
437
+ };
438
+ });
439
+ }
440
+ /**
441
+ * The instructions files the agents read, with the section each gets. Claude Code reads
442
+ * `CLAUDE.md`, and `AGENTS.md` only when the repository has no `CLAUDE.md`, so it gets
443
+ * `CLAUDE.md` when there is one and shares `AGENTS.md` otherwise: creating `CLAUDE.md` would hide
444
+ * `AGENTS.md` from it.
445
+ */
446
+ function instructionTargets(root, project, agents, skills) {
447
+ const shared = posix.join(".agents/skills", SKILL_NAME);
448
+ const sharedBefore = skillState(join(root, shared)).kind === "ours";
449
+ const files = /* @__PURE__ */ new Map();
450
+ const add = (file, folder) => {
451
+ const keepShared = file === "AGENTS.md" && sharedBefore;
452
+ if (files.get(file) !== ".agents/skills") files.set(file, keepShared ? ".agents/skills" : folder);
453
+ };
454
+ for (const id of agents) {
455
+ const agent = agentOf(id);
456
+ if (agent.instructions === "claude") add(claudeFile(root), agent.skills);
457
+ else add(agent.instructions, agent.skills);
458
+ }
459
+ const relative = (path) => relativePath(root, path) || ".";
460
+ const usable = new Set(skills.filter((s) => s.status !== "foreign").map((s) => s.path));
461
+ if (sharedBefore) usable.add(shared);
462
+ return [...files].flatMap(([path, folder]) => {
463
+ const skillPath = posix.join(folder, SKILL_NAME);
464
+ if (!usable.has(skillPath)) return [];
465
+ const pointer = {
466
+ project: relativePath(root, project.dir),
467
+ folder: relative(project.folder),
468
+ out: relative(project.out),
469
+ importPath: project.importPath,
470
+ runner: project.runner,
471
+ skill: posix.join(skillPath, "SKILL.md")
472
+ };
473
+ const file = join(root, path);
474
+ const existing = existsSync(file) ? readFileSync(file, "utf8") : void 0;
475
+ const content = withSection(existing, pointer.project, section(pointer));
476
+ return [{
477
+ path,
478
+ status: existing === void 0 ? "create" : existing === content ? "unchanged" : hasSection(existing, pointer.project) ? "update" : "add",
479
+ content
480
+ }];
481
+ });
482
+ }
483
+ /** Claude Code's instructions file: the `CLAUDE.md` the repository has, else `AGENTS.md`. */
484
+ function claudeFile(root) {
485
+ if (existsSync(join(root, "CLAUDE.md"))) return "CLAUDE.md";
486
+ if (existsSync(join(root, ".claude/CLAUDE.md"))) return ".claude/CLAUDE.md";
487
+ if (existsSync(join(root, "CLAUDE.local.md"))) return "CLAUDE.md";
488
+ return "AGENTS.md";
489
+ }
490
+ /** What setting up the agents will do, before it asks about changes to existing files. */
491
+ function plan$1(root, projectDir, agents, skills, instructions, docs) {
492
+ const where = relativePath(projectDir, root);
493
+ const note = {
494
+ create: "new",
495
+ update: "update",
496
+ unchanged: "up to date"
497
+ };
498
+ const write = [...skills.filter((s) => s.status !== "foreign").map((s) => [`${s.path}/`, `the skill (${note[s.status]})`]), ...instructions.filter((t) => t.status === "create" || t.status === "unchanged").map((t) => [t.path, t.status === "create" ? "email-kit's section (new)" : "email-kit's section (up to date)"])];
499
+ const change = instructions.filter((t) => t.status === "add" || t.status === "update");
500
+ const foreign = skills.filter((s) => s.status === "foreign");
501
+ const width = Math.max(0, ...write.map(([path]) => path.length));
502
+ return [
503
+ "",
504
+ "AI coding agents",
505
+ "",
506
+ ` Agents ${list(agents.map(nameOf))}`,
507
+ ...where ? [` Where the repository root, ${where}`] : [],
508
+ ` Docs ${docs}/, the installed CLI's, which the skill links to`,
509
+ ...write.length > 0 ? [
510
+ "",
511
+ " Write",
512
+ ...write.map(([path, what]) => ` ${path.padEnd(width)} ${what}`)
513
+ ] : [],
514
+ ...change.length > 0 ? [
515
+ "",
516
+ " Change, if you agree",
517
+ ...change.map((t) => ` ${t.path}: ${t.status === "add" ? "add a section that points agents to the skill" : "update email-kit's section"}`)
518
+ ] : [],
519
+ ...foreign.length > 0 ? [
520
+ "",
521
+ " Skip",
522
+ ...foreign.map((s) => ` ${s.path}/ is a folder email-kit didn't write. Move it, then run \`email-kit agents\` again.`)
523
+ ] : [],
524
+ ""
525
+ ].join("\n");
526
+ }
527
+ /** An agent's name as it reads in a sentence. */
528
+ const nameOf = (id) => {
529
+ const agent = agentOf(id);
530
+ return agent.inSentence ?? agent.label;
531
+ };
532
+ /** Names joined for a sentence: `A`, `A and B`, `A, B and C`. */
533
+ function list(names) {
534
+ return names.length <= 1 ? names[0] ?? "" : `${names.slice(0, -1).join(", ")} and ${names[names.length - 1]}`;
535
+ }
23
536
  // src/checks/position.ts
24
537
  /**
25
538
  * A function that gives the line and column of an offset in `text`. The line starts are found
@@ -540,6 +1053,23 @@ const A11Y = [
540
1053
  })
541
1054
  }
542
1055
  ];
1056
+ // src/checks/catalogue/agents.ts
1057
+ /** The `agents.*` checks: the email-kit skill AI coding agents read matches this version. */
1058
+ const AGENTS = [{
1059
+ id: "agents.skill-outdated",
1060
+ level: "warn",
1061
+ rule: "Each copy of the email-kit skill for AI coding agents (`.agents/skills/email-kit/`, `.claude/skills/email-kit/`) matches the one the installed CLI ships.",
1062
+ fix: "Run `email-kit agents` to update it: agents follow the skill, and an older one describes an older email-kit.",
1063
+ run: (context, report) => {
1064
+ for (const skill of context.agentSkills ?? []) {
1065
+ if (skill.current) continue;
1066
+ report({
1067
+ message: skill.version && skill.version !== VERSION ? `${skill.file} is the skill from email-kit ${skill.version}; this is ${VERSION}` : `${skill.file} differs from the skill email-kit ${VERSION} ships`,
1068
+ subject: { file: skill.file }
1069
+ });
1070
+ }
1071
+ }
1072
+ }];
543
1073
  // src/checks/catalogue/compiler.ts
544
1074
  const nothing = () => {};
545
1075
  /**
@@ -4763,27 +5293,6 @@ const HTML = [
4763
5293
  })
4764
5294
  }
4765
5295
  ];
4766
- // src/paths.ts
4767
- /**
4768
- * A path relative to `from`, always with `/`: for findings, reporters, config files and imports,
4769
- * which read the same on every platform. `path.relative` uses `\` on Windows.
4770
- */
4771
- function relativePath(from, to) {
4772
- return toPosix(relative(from, to));
4773
- }
4774
- /** `src\mail` → `src/mail`; unchanged on POSIX. */
4775
- function toPosix(path) {
4776
- return sep === "\\" ? path.replaceAll("\\", "/") : path;
4777
- }
4778
- /** Whether `path` exists and is a folder. */
4779
- function isDirectory(path) {
4780
- return existsSync(path) && statSync(path).isDirectory();
4781
- }
4782
- /** Whether `path` is `folder` itself or anywhere inside it. */
4783
- function isWithin(folder, path) {
4784
- const rel = relative(folder, path);
4785
- return rel === "" || !rel.startsWith("..") && !isAbsolute(rel);
4786
- }
4787
5296
  // src/checks/source.ts
4788
5297
  /**
4789
5298
  * Reads a project file for the `source.*` checks. It's parsed only when a check asks, and only
@@ -5993,7 +6502,8 @@ const CATALOGUE = [
5993
6502
  ...PREHEADER,
5994
6503
  ...SUBJECT,
5995
6504
  ...RENDER,
5996
- ...OUTPUT
6505
+ ...OUTPUT,
6506
+ ...AGENTS
5997
6507
  ];
5998
6508
  // ../runtime/dist/locale.js
5999
6509
  /**
@@ -15275,12 +15785,6 @@ function languageOf(tag) {
15275
15785
  function scriptOf(tag) {
15276
15786
  return tag?.split("-")[1]?.toLowerCase();
15277
15787
  }
15278
- // src/version.ts
15279
- /**
15280
- * The email-kit version, from package.json. `--version` prints it, the compiler writes it into
15281
- * generated files and the manifest, and `init` uses it for the dependency ranges it adds.
15282
- */
15283
- const VERSION = "1.0.0";
15284
15788
  // src/compiler/emit/javascript.ts
15285
15789
  /**
15286
15790
  * Converts the generated module to `index.mjs` and `index.d.mts`, for `module: "mjs"`. oxc, through
@@ -16338,6 +16842,7 @@ async function contextOf(project) {
16338
16842
  file: relativePath(config.dir, t.file),
16339
16843
  fixtures: Object.keys(t.fixtures)
16340
16844
  })),
16845
+ agentSkills: agentSkills(config.dir),
16341
16846
  sources: sourceFiles(project),
16342
16847
  theme: project.theme,
16343
16848
  themeFindings: project.themeFindings,
@@ -16385,6 +16890,29 @@ function sourceFiles(project) {
16385
16890
  for (const template of project.templates) for (const file of template.sources) users.set(file, [...users.get(file) ?? [], template.id]);
16386
16891
  return [...users].map(([file, ids]) => sourceFile(file, project.config.dir, ids));
16387
16892
  }
16893
+ /**
16894
+ * The copies of email-kit's skill in the project's folder and its repository's root, for
16895
+ * `agents.skill-outdated`. A CLI that can't find its own skill reports none.
16896
+ */
16897
+ function agentSkills(dir) {
16898
+ const folders = [.../* @__PURE__ */ new Set([dir, repositoryRoot(dir)])];
16899
+ const skills = [];
16900
+ try {
16901
+ for (const folder of folders) for (const location of [".agents/skills", ".claude/skills"]) {
16902
+ const path = join(folder, location, "email-kit");
16903
+ const state = skillState(path);
16904
+ if (state.kind !== "ours") continue;
16905
+ skills.push({
16906
+ file: relativePath(dir, path),
16907
+ version: state.version,
16908
+ current: state.current
16909
+ });
16910
+ }
16911
+ } catch {
16912
+ return [];
16913
+ }
16914
+ return skills;
16915
+ }
16388
16916
  // src/checks/custom.ts
16389
16917
  /**
16390
16918
  * An email as a team check sees it: plain data from the public `CheckEmail` type, with its
@@ -17522,7 +18050,7 @@ const RUNNER = {
17522
18050
  bun: "bunx"
17523
18051
  };
17524
18052
  /** What `init` says when the project already has email-kit. */
17525
- const alreadySetUp = (where) => `email-kit is already set up here (${where}). Add a template with \`email-kit new <id>\`.`;
18053
+ const alreadySetUp = (where) => `email-kit is already set up here (${where}). Add a template with \`email-kit new <id>\`, and set up AI coding agents with \`email-kit agents\`.`;
17526
18054
  /**
17527
18055
  * `email-kit init`: adds email-kit to the project it runs in. It shows every file it creates and
17528
18056
  * every change it makes, asks before each change to an existing file, and never writes into a
@@ -17603,6 +18131,22 @@ async function init(options, io) {
17603
18131
  io.err("! The first compile didn't run: install the dependencies, then run `email-kit compile`.");
17604
18132
  io.err(formatError(error, io));
17605
18133
  }
18134
+ try {
18135
+ await setUpAgents({
18136
+ dir,
18137
+ folder: join(dir, folder),
18138
+ out: join(dir, folder, GENERATED_FOLDER),
18139
+ importPath,
18140
+ runner: RUNNER[project.packageManager]
18141
+ }, {
18142
+ command: "init",
18143
+ ...options.yes !== void 0 && { yes: options.yes },
18144
+ ...options.agents !== void 0 && { agents: options.agents }
18145
+ }, io);
18146
+ } catch (error) {
18147
+ if (error instanceof EmailKitError && error.code === "init-cancelled") throw error;
18148
+ io.err(`! The AI coding agents weren't set up: ${error.message}`);
18149
+ }
17606
18150
  io.out(nextSteps(project.packageManager, importPath, has("scripts") ? scriptPrefix : void 0));
17607
18151
  return 0;
17608
18152
  }
@@ -17692,7 +18236,8 @@ function nextSteps(pm, importPath, scriptPrefix) {
17692
18236
  [command("compile"), "after changing a template or message"],
17693
18237
  [command("watch"), "recompile on every change, while you work"],
17694
18238
  [command("check"), "the checks, for CI"],
17695
- [`${RUNNER[pm]} email-kit new <id>`, "another template"]
18239
+ [`${RUNNER[pm]} email-kit new <id>`, "another template"],
18240
+ [`${RUNNER[pm]} email-kit agents`, "set up or update the skill for AI coding agents"]
17696
18241
  ]),
17697
18242
  "",
17698
18243
  "Docs: https://github.com/email-kit/email-kit#readme"
@@ -17805,10 +18350,13 @@ const stop = () => {
17805
18350
  cancel("Nothing more was changed.");
17806
18351
  throw new EmailKitError("init-cancelled", "init was cancelled");
17807
18352
  };
17808
- /** Stops `init` when there's no terminal to ask in, pointing at `--yes` rather than guessing. */
18353
+ /**
18354
+ * Stops `init` or `agents` when there's no terminal to ask in, pointing at `--yes` rather than
18355
+ * guessing.
18356
+ */
17809
18357
  function needTerminal() {
17810
18358
  if (process.stdin.isTTY) return;
17811
- throw new EmailKitError("init-needs-answers", "init asks before it changes files, and there's no terminal to ask in. Run it with --yes to accept the defaults.");
18359
+ throw new EmailKitError("init-needs-answers", "email-kit asks before it changes files, and there's no terminal to ask in. Run it with --yes to accept the defaults.");
17812
18360
  }
17813
18361
  /** Asks `init`'s questions in a terminal, with @clack/prompts. */
17814
18362
  const terminalPrompter = {
@@ -17827,6 +18375,16 @@ const terminalPrompter = {
17827
18375
  initialValue: initial
17828
18376
  });
17829
18377
  return isCancel(answer) ? stop() : answer;
18378
+ },
18379
+ async multiselect(message, options, initial) {
18380
+ needTerminal();
18381
+ const answer = await multiselect({
18382
+ message,
18383
+ options: options.map((option) => ({ ...option })),
18384
+ initialValues: [...initial],
18385
+ required: false
18386
+ });
18387
+ return isCancel(answer) ? stop() : answer;
17830
18388
  }
17831
18389
  };
17832
18390
  // src/theme/report.ts
@@ -17876,7 +18434,7 @@ function formatTokens(theme, findings) {
17876
18434
  // src/run.ts
17877
18435
  /**
17878
18436
  * Runs the `email-kit` command with the given arguments, without `node` and the script path:
17879
- * `compile` (or `generate`), `init`, `new`, `check` or `tokens`. Returns the exit code.
18437
+ * `compile` (or `generate`), `init`, `new`, `check`, `tokens` or `agents`. Returns the exit code.
17880
18438
  */
17881
18439
  async function run(args, io) {
17882
18440
  const cli = cac("email-kit");
@@ -17884,9 +18442,12 @@ async function run(args, io) {
17884
18442
  cli.command("compile", "Compile the templates into the output folder").alias("generate").option("--config <path>", "Use this config file instead of ./email-kit.config.ts").option("--watch", "Recompile when a template, component, message or the config changes").option("--quiet", "Print errors only").option("--verbose", "Also print each template's sizes per locale, and the files that changed").action((options) => {
17885
18443
  pending = compileCommand(options, io);
17886
18444
  });
17887
- cli.command("init", "Add email-kit to this project: a config, a folder and a welcome template").option("--yes", "Accept every default without asking (for CI)").option("--dir <path>", "Put the email-kit folder in this code root instead of the detected one").option("--config <path>", "Name the config file something other than email-kit.config.ts").option("--force", "Overwrite an existing config").option("--no-install", "Don't run the package manager after adding the dependencies").action((options) => {
18445
+ cli.command("init", "Add email-kit to this project: a config, a folder and a welcome template").option("--yes", "Accept every default without asking (for CI)").option("--dir <path>", "Put the email-kit folder in this code root instead of the detected one").option("--config <path>", "Name the config file something other than email-kit.config.ts").option("--force", "Overwrite an existing config").option("--no-install", "Don't run the package manager after adding the dependencies").option("--agents [list]", "Set up these AI coding agents instead of asking: claude, codex, cursor, copilot, gemini, antigravity, windsurf, agents-md, all or none").option("--no-agents", "Don't set up AI coding agents").action((options) => {
17888
18446
  pending = initCommand(options, io);
17889
18447
  });
18448
+ cli.command("agents", "Add or update the email-kit skill for AI coding agents (Claude Code, Codex, Cursor and others)").option("--agents <list>", "These agents instead of asking: claude, codex, cursor, copilot, gemini, antigravity, windsurf, agents-md, all or none").option("--yes", "Take the agents the repository shows and accept every change without asking").option("--config <path>", "Use this config file instead of ./email-kit.config.ts").action((options) => {
18449
+ pending = agentsCommand(options, io);
18450
+ });
17890
18451
  cli.command("new <id>", "Add a template, with its messages in every locale and a fixture").option("--config <path>", "Use this config file instead of ./email-kit.config.ts").action((id, options) => {
17891
18452
  pending = newTemplate(id, {
17892
18453
  cwd: io.cwd,
@@ -17926,6 +18487,15 @@ async function run(args, io) {
17926
18487
  if (!cli.options.help && !cli.options.version) cli.outputHelp();
17927
18488
  return 0;
17928
18489
  }
18490
+ /**
18491
+ * The agents `--agents` and `--no-agents` name: `undefined` to detect or ask, `[]` for none, or an
18492
+ * error message for a name that isn't an agent.
18493
+ */
18494
+ function agentsFlag(value) {
18495
+ if (value === void 0 || value === true) return void 0;
18496
+ if (value === false) return [];
18497
+ return parseAgents(String(value));
18498
+ }
17929
18499
  const REPORTERS = {
17930
18500
  human: formatHuman,
17931
18501
  json: formatJson,
@@ -17983,12 +18553,56 @@ async function tokensCommand(options, io) {
17983
18553
  return 1;
17984
18554
  }
17985
18555
  }
18556
+ /**
18557
+ * `email-kit agents`: writes the email-kit skill for the AI coding agents the project uses, and a
18558
+ * section pointing to it in their instructions files, for the project the config describes.
18559
+ */
18560
+ async function agentsCommand(options, io) {
18561
+ const agents = agentsFlag(options.agents);
18562
+ if (typeof agents === "string") {
18563
+ io.err(`✗ ${agents}`);
18564
+ return 1;
18565
+ }
18566
+ try {
18567
+ const config = await loadConfig({
18568
+ cwd: io.cwd,
18569
+ config: options.config
18570
+ });
18571
+ const dir = findProject(config.dir);
18572
+ const packageJson = JSON.parse(readFileSync(join(dir, "package.json"), "utf8"));
18573
+ return await setUpAgents({
18574
+ dir: config.dir,
18575
+ folder: config.root,
18576
+ out: config.out,
18577
+ importPath: config.importPath,
18578
+ runner: RUNNER[packageManagerOf(dir, packageJson)]
18579
+ }, {
18580
+ command: "agents",
18581
+ ...options.yes !== void 0 && { yes: options.yes },
18582
+ ...agents !== void 0 && { agents }
18583
+ }, {
18584
+ out: io.out,
18585
+ err: io.err,
18586
+ prompter: io.prompter ?? terminalPrompter
18587
+ });
18588
+ } catch (error) {
18589
+ io.err(formatError(error, io));
18590
+ return 1;
18591
+ }
18592
+ }
17986
18593
  /** `email-kit init`: asks in the terminal unless `io` brings its own prompter. */
17987
- async function initCommand(options, io) {
18594
+ async function initCommand(flags, io) {
18595
+ const { agents: agentsValue, ...options } = flags;
18596
+ const agents = agentsFlag(agentsValue);
18597
+ if (typeof agents === "string") {
18598
+ io.err(`✗ ${agents}`);
18599
+ return 1;
18600
+ }
17988
18601
  try {
17989
18602
  return await init({
17990
18603
  cwd: io.cwd,
17991
- ...options
18604
+ ...options,
18605
+ ...agents !== void 0 && { agents }
17992
18606
  }, {
17993
18607
  out: io.out,
17994
18608
  err: io.err,