@templatical/template-tools 0.51.1 → 0.52.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 +12 -0
- package/dist/bin.d.ts +0 -2
- package/dist/bin.js +14 -27
- package/dist/bin.js.map +1 -1
- package/dist/{custom-block-B2hUl-PC.js → custom-block-BgJCmUbD.js} +23 -33
- package/dist/custom-block-BgJCmUbD.js.map +1 -0
- package/dist/index.d.ts +1 -11
- package/dist/index.js +1 -1
- package/dist/live/index.d.ts +1 -3
- package/dist/live/index.js +3 -4
- package/dist/live/index.js.map +1 -1
- package/package.json +13 -13
- package/dist/custom-block-B2hUl-PC.js.map +0 -1
package/README.md
CHANGED
|
@@ -24,6 +24,18 @@ npx -y @templatical/template-tools validate .templatical/my-template.json
|
|
|
24
24
|
|
|
25
25
|
Add `--json` to any command for machine-readable output on stdout.
|
|
26
26
|
|
|
27
|
+
## Custom block output
|
|
28
|
+
|
|
29
|
+
Custom block templates HTML-escape `{{ }}`, `{% echo %}`, `{% liquid %}` echo and `{% cycle %}` output by default: `&`, `<`, `>`, `"` and `'` become `&`, `<`, `>`, `"` and `'`. To render a field as HTML, write `{{ body | raw }}`. Always quote attribute values and validate URL schemes from untrusted sources; escaping does not validate URLs. The editor canvas also sanitizes rendered blocks; MJML and email output keep the template's HTML. Server-side rendering uses `renderToMjml(content, { customBlocks: definitions })`; a lower-level resolver uses the same engine:
|
|
30
|
+
|
|
31
|
+
```ts
|
|
32
|
+
import * as liquidjs from 'liquidjs';
|
|
33
|
+
import { createCustomBlockLiquid } from '@templatical/types';
|
|
34
|
+
const liquid = createCustomBlockLiquid(liquidjs);
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Install `@templatical/types` and `liquidjs` in the resolver project. See the [Custom blocks guide](https://docs.templatical.com/guide/custom-blocks) for the renderer option and factory contracts. Data-source recipes retain an unescaped engine so JSON body quotes are preserved; use `{{ key | json }}` for JSON values.
|
|
38
|
+
|
|
27
39
|
## Exit codes
|
|
28
40
|
|
|
29
41
|
| Code | Meaning |
|
package/dist/bin.d.ts
CHANGED
package/dist/bin.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { a as buildSpecimenTemplate, c as runRecipe, d as schema, f as validateTemplate, i as buildSpecimen, l as validateCustomBlockDefinition, n as renderSpecimenMjml, r as SPECIMEN_STATES, s as checkRecipe, t as checkCustomBlock, u as runQualityLint } from "./custom-block-
|
|
2
|
+
import { a as buildSpecimenTemplate, c as runRecipe, d as schema, f as validateTemplate, i as buildSpecimen, l as validateCustomBlockDefinition, n as renderSpecimenMjml, r as SPECIMEN_STATES, s as checkRecipe, t as checkCustomBlock, u as runQualityLint } from "./custom-block-BgJCmUbD.js";
|
|
3
3
|
import "./index.js";
|
|
4
4
|
import { DEFAULT_PORT, WORKING_DIR, listWorkingFiles, openBrowser, pidfilePath, processAlive, readPidfile, readWorkingFile, startBridgePreferring } from "./live/index.js";
|
|
5
5
|
import { lintCompiledHtml } from "@templatical/quality";
|
|
@@ -8,7 +8,7 @@ import { renderToMjml } from "@templatical/renderer";
|
|
|
8
8
|
import { existsSync, mkdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
|
|
9
9
|
import { basename, dirname, extname, isAbsolute, join, resolve } from "node:path";
|
|
10
10
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
11
|
-
|
|
11
|
+
// src/cli/args.ts
|
|
12
12
|
/** Flags that consume the next argv entry as their value. */
|
|
13
13
|
const VALUE_FLAGS = /* @__PURE__ */ new Set([
|
|
14
14
|
"format",
|
|
@@ -60,8 +60,7 @@ function flagValue(args, ...names) {
|
|
|
60
60
|
if (typeof v === "string") return v;
|
|
61
61
|
}
|
|
62
62
|
}
|
|
63
|
-
|
|
64
|
-
//#region src/cli/output.ts
|
|
63
|
+
// src/cli/output.ts
|
|
65
64
|
let jsonMode = false;
|
|
66
65
|
function setJsonMode(on) {
|
|
67
66
|
jsonMode = on;
|
|
@@ -78,8 +77,7 @@ function emit(payload, human) {
|
|
|
78
77
|
function note(message) {
|
|
79
78
|
process.stderr.write(`${message}\n`);
|
|
80
79
|
}
|
|
81
|
-
|
|
82
|
-
//#region src/cli/io.ts
|
|
80
|
+
// src/cli/io.ts
|
|
83
81
|
const EXIT = {
|
|
84
82
|
ok: 0,
|
|
85
83
|
/** Structural errors, or quality issues of severity "error". */
|
|
@@ -128,8 +126,7 @@ function writeTemplateFile(file, content, cwd = process.cwd()) {
|
|
|
128
126
|
writeFileSync(path, `${JSON.stringify(content, null, 2)}\n`, "utf8");
|
|
129
127
|
return path;
|
|
130
128
|
}
|
|
131
|
-
|
|
132
|
-
//#region src/cli/commands/schema.ts
|
|
129
|
+
// src/cli/commands/schema.ts
|
|
133
130
|
function runSchema(args) {
|
|
134
131
|
const out = flagValue(args, "out", "o");
|
|
135
132
|
if (out) {
|
|
@@ -139,8 +136,7 @@ function runSchema(args) {
|
|
|
139
136
|
emit(schema, () => JSON.stringify(schema, null, 2));
|
|
140
137
|
return EXIT.ok;
|
|
141
138
|
}
|
|
142
|
-
|
|
143
|
-
//#region src/cli/resolve-optional.ts
|
|
139
|
+
// src/cli/resolve-optional.ts
|
|
144
140
|
/**
|
|
145
141
|
* Walk up from `dir` through every ancestor's node_modules looking for
|
|
146
142
|
* <specifier>/package.json — the same directory-walk Node's own resolver uses
|
|
@@ -189,8 +185,7 @@ async function resolveOptional(specifier, cwd = process.cwd()) {
|
|
|
189
185
|
}
|
|
190
186
|
return null;
|
|
191
187
|
}
|
|
192
|
-
|
|
193
|
-
//#region src/cli/mjml.ts
|
|
188
|
+
// src/cli/mjml.ts
|
|
194
189
|
async function loadMjml(cwd) {
|
|
195
190
|
const mod = await resolveOptional("mjml", cwd);
|
|
196
191
|
return mod ? mod.default : null;
|
|
@@ -200,8 +195,7 @@ async function requireMjml(cwd, purpose) {
|
|
|
200
195
|
if (!mjml) throw new MissingDependencyError("mjml", `${purpose} needs the optional \`mjml\` package, which isn't installed.\n npm install mjml`);
|
|
201
196
|
return mjml;
|
|
202
197
|
}
|
|
203
|
-
|
|
204
|
-
//#region src/cli/commands/validate.ts
|
|
198
|
+
// src/cli/commands/validate.ts
|
|
205
199
|
async function runValidate(args) {
|
|
206
200
|
const file = args.positional[0];
|
|
207
201
|
if (!file) throw new UsageError("validate needs a template file.");
|
|
@@ -239,8 +233,7 @@ async function runValidate(args) {
|
|
|
239
233
|
});
|
|
240
234
|
return blocking.length > 0 ? EXIT.invalid : EXIT.ok;
|
|
241
235
|
}
|
|
242
|
-
|
|
243
|
-
//#region src/cli/commands/render.ts
|
|
236
|
+
// src/cli/commands/render.ts
|
|
244
237
|
const FORMATS$1 = /* @__PURE__ */ new Set(["mjml", "html"]);
|
|
245
238
|
async function runRender(args) {
|
|
246
239
|
const file = args.positional[0];
|
|
@@ -268,8 +261,7 @@ async function runRender(args) {
|
|
|
268
261
|
}, () => output);
|
|
269
262
|
return EXIT.ok;
|
|
270
263
|
}
|
|
271
|
-
|
|
272
|
-
//#region src/cli/commands/edit.ts
|
|
264
|
+
// src/cli/commands/edit.ts
|
|
273
265
|
function parseOperations(args, cwd) {
|
|
274
266
|
const inline = flagValue(args, "op");
|
|
275
267
|
const batchFile = flagValue(args, "ops");
|
|
@@ -315,8 +307,7 @@ function runEdit(args) {
|
|
|
315
307
|
}, () => `Applied ${operations.length} operation(s) to ${path}`);
|
|
316
308
|
return EXIT.ok;
|
|
317
309
|
}
|
|
318
|
-
|
|
319
|
-
//#region src/cli/commands/import.ts
|
|
310
|
+
// src/cli/commands/import.ts
|
|
320
311
|
const FORMATS = {
|
|
321
312
|
unlayer: {
|
|
322
313
|
pkg: "@templatical/import-unlayer",
|
|
@@ -541,8 +532,7 @@ async function runImport(args) {
|
|
|
541
532
|
].filter(Boolean).join("\n"));
|
|
542
533
|
return EXIT.ok;
|
|
543
534
|
}
|
|
544
|
-
|
|
545
|
-
//#region src/cli/commands/custom-block.ts
|
|
535
|
+
// src/cli/commands/custom-block.ts
|
|
546
536
|
const USAGE$1 = "Use `custom-block validate <file>`, `custom-block render <file>` or `custom-block fetch <file>`.";
|
|
547
537
|
function formatIssues(issues) {
|
|
548
538
|
return issues.map((i) => ` - [${i.severity}] ${i.ruleId}${i.path ? ` ${i.path}` : ""}: ${i.message}${i.suggestion ? `\n → ${i.suggestion}` : ""}`).join("\n");
|
|
@@ -621,8 +611,7 @@ async function runCustomBlock(args) {
|
|
|
621
611
|
emit(result, () => result.ok ? `✓ ${result.status} · ${JSON.stringify(result.values, null, 2)}${result.unmapped.length ? `\nUnmapped: ${result.unmapped.join(", ")}` : ""}` : `✗ ${result.error}`);
|
|
622
612
|
return result.ok ? EXIT.ok : EXIT.invalid;
|
|
623
613
|
}
|
|
624
|
-
|
|
625
|
-
//#region src/cli/commands/live.ts
|
|
614
|
+
// src/cli/commands/live.ts
|
|
626
615
|
/**
|
|
627
616
|
* The first title block's text in document order, as a hint for `list`.
|
|
628
617
|
*
|
|
@@ -784,8 +773,7 @@ async function runLive(args) {
|
|
|
784
773
|
note("After writing the working file, run: templatical live reload");
|
|
785
774
|
return new Promise(() => {});
|
|
786
775
|
}
|
|
787
|
-
|
|
788
|
-
//#region src/bin.ts
|
|
776
|
+
// src/bin.ts
|
|
789
777
|
const USAGE = `templatical <command> [options]
|
|
790
778
|
|
|
791
779
|
validate <file> [--html] structural + quality lint; --html checks compiled size
|
|
@@ -858,7 +846,6 @@ if (isEntryPoint()) main(process.argv.slice(2)).then((code) => process.exit(code
|
|
|
858
846
|
note(`Unexpected error: ${err?.message ?? String(err)}`);
|
|
859
847
|
process.exit(EXIT.usage);
|
|
860
848
|
});
|
|
861
|
-
//#endregion
|
|
862
849
|
export { isEntryPoint, main };
|
|
863
850
|
|
|
864
851
|
//# sourceMappingURL=bin.js.map
|
package/dist/bin.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bin.js","names":["FORMATS","content","USAGE"],"sources":["../src/cli/args.ts","../src/cli/output.ts","../src/cli/io.ts","../src/cli/commands/schema.ts","../src/cli/resolve-optional.ts","../src/cli/mjml.ts","../src/cli/commands/validate.ts","../src/cli/commands/render.ts","../src/cli/commands/edit.ts","../src/cli/commands/import.ts","../src/cli/commands/custom-block.ts","../src/cli/commands/live.ts","../src/bin.ts"],"sourcesContent":["// Argv parsing for the CLI. Deliberately hand-rolled: the package has no\n// runtime dependency for this, and the surface is a dozen flags.\n\n/** Flags that consume the next argv entry as their value. */\nconst VALUE_FLAGS = new Set([\n \"format\",\n \"out\",\n \"o\",\n \"op\",\n \"ops\",\n \"file\",\n \"port\",\n \"cwd\",\n \"state\",\n \"values\",\n \"custom-block\",\n \"host\",\n]);\n\nexport interface ParsedArgs {\n command?: string;\n /** Everything that is not the command and not a flag — including subcommands. */\n positional: string[];\n json: boolean;\n flags: Record<string, string | true>;\n}\n\nexport function parseArgs(argv: string[]): ParsedArgs {\n const positional: string[] = [];\n const flags: Record<string, string | true> = {};\n let json = false;\n\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i];\n if (!arg.startsWith(\"-\")) {\n positional.push(arg);\n continue;\n }\n\n const bare = arg.replace(/^--?/, \"\");\n const eq = bare.indexOf(\"=\");\n if (eq !== -1) {\n flags[bare.slice(0, eq)] = bare.slice(eq + 1);\n continue;\n }\n if (bare === \"json\") {\n json = true;\n continue;\n }\n // A value flag at the end of argv has no value; record it as present so the\n // command reports a useful usage error rather than reading `undefined`.\n flags[bare] =\n VALUE_FLAGS.has(bare) && i + 1 < argv.length ? argv[++i] : true;\n }\n\n return { command: positional.shift(), positional, json, flags };\n}\n\n/** Read a value flag as a string, or undefined when absent or valueless. */\nexport function flagValue(\n args: ParsedArgs,\n ...names: string[]\n): string | undefined {\n for (const name of names) {\n const v = args.flags[name];\n if (typeof v === \"string\") return v;\n }\n return undefined;\n}\n","// The ONLY module in this package that writes to stdout.\n//\n// `--json` promises callers exactly one parseable document on stdout, and a\n// future stdio-based caller — an MCP server reserving stdout for JSON-RPC —\n// would need that to hold just as strictly. Either way a second writer\n// breaks the contract. tests/cli-output-discipline.test.ts asserts no other\n// source file touches stdout.\n\nlet jsonMode = false;\n\nexport function setJsonMode(on: boolean): void {\n jsonMode = on;\n}\n\nexport function isJsonMode(): boolean {\n return jsonMode;\n}\n\n/**\n * Emit a command's result. Under `--json` the payload is serialized; otherwise\n * `human()` is called for the readable form — as a thunk, so building the\n * pretty output costs nothing in JSON mode.\n */\nexport function emit(payload: unknown, human: () => string): void {\n process.stdout.write(\n jsonMode ? `${JSON.stringify(payload)}\\n` : `${human()}\\n`,\n );\n}\n\n/** Diagnostics, progress and errors. Always stderr, in both modes. */\nexport function note(message: string): void {\n process.stderr.write(`${message}\\n`);\n}\n","// Shared file IO and the error→exit-code contract.\n\nimport { mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname, isAbsolute, resolve } from \"node:path\";\n\nexport const EXIT = {\n ok: 0,\n /** Structural errors, or quality issues of severity \"error\". */\n invalid: 1,\n /** Bad flags, missing arguments, unreadable input. */\n usage: 2,\n /** An optional dependency is not installed; the message names the install. */\n missingDep: 3,\n} as const;\n\nexport class UsageError extends Error {}\n\nexport class InvalidTemplateError extends Error {\n constructor(\n message: string,\n readonly errors: string[] = [],\n ) {\n super(message);\n }\n}\n\nexport class MissingDependencyError extends Error {\n constructor(\n readonly pkg: string,\n message: string,\n ) {\n super(message);\n }\n}\n\nexport function resolveFrom(file: string, cwd = process.cwd()): string {\n return isAbsolute(file) ? file : resolve(cwd, file);\n}\n\nexport function readTemplateFile(file: string, cwd = process.cwd()): unknown {\n const path = resolveFrom(file, cwd);\n let raw: string;\n try {\n raw = readFileSync(path, \"utf8\");\n } catch {\n throw new UsageError(`Could not read ${file}`);\n }\n try {\n return JSON.parse(raw);\n } catch (err) {\n throw new UsageError(\n `${file} is not valid JSON: ${(err as Error).message}`,\n );\n }\n}\n\n/** Write a template, creating the parent directory. Returns the path written. */\nexport function writeTemplateFile(\n file: string,\n content: unknown,\n cwd = process.cwd(),\n): string {\n const path = resolveFrom(file, cwd);\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, `${JSON.stringify(content, null, 2)}\\n`, \"utf8\");\n return path;\n}\n","import { flagValue, type ParsedArgs } from \"../args\";\nimport { emit, note } from \"../output\";\nimport { EXIT, writeTemplateFile } from \"../io\";\nimport { schema } from \"../../index\";\n\nexport function runSchema(args: ParsedArgs): number {\n const out = flagValue(args, \"out\", \"o\");\n if (out) {\n // writeTemplateFile JSON-stringifies with the same shape this command\n // wrote by hand, and creates the parent directory as a side effect.\n const path = writeTemplateFile(out, schema);\n // stdout stays empty: the caller asked for a file, and under --json a path\n // string would not be the document they are parsing for.\n note(`Wrote ${path}`);\n return EXIT.ok;\n }\n emit(schema, () => JSON.stringify(schema, null, 2));\n return EXIT.ok;\n}\n","//\n// Optional dependencies must resolve from the CONSUMER'S cwd, not from this\n// module's location. When the CLI runs via npx it lives in npm's cache, so a\n// package the user installs in their own project is invisible to the CLI's own\n// resolution — and the remediation message (\"npm install mjml\") would be\n// impossible to satisfy. Anchoring the walk at the cwd fixes that; the CLI's\n// own directory is tried second, as a fallback — not for ajv (a hard\n// `dependencies` entry, imported statically in src/validate.ts, so it never\n// passes through this function at all), but for a global install (`npm\n// install -g mjml` places the optional peer as a sibling of this package\n// under one shared global node_modules that only this anchor can reach) and\n// for this package's own tests, which anchor at a throwaway cwd outside the\n// repo and rely on this anchor climbing from inside the repo tree up to the\n// root node_modules holding the @templatical/import-* converters as root\n// devDependencies.\n//\n// Resolution deliberately does NOT go through require.resolve()/createRequire.\n// That API performs Node's CJS-invoked exports resolution, which checks the\n// condition list [\"require\", \"node\", \"default\"] and never \"import\" — so it\n// throws ERR_PACKAGE_PATH_NOT_EXPORTED for any package whose exports map\n// declares only \"import\", which is every first-party package in this monorepo\n// (ESM-only: `exports` exposes only the \"import\" condition, never \"require\"\n// or \"main\"). That map also omits \"./package.json\", so\n// require.resolve can't even read the manifest to look further. The result\n// under the old createRequire-based resolution: every @templatical/import-*\n// converter reported as \"not installed\" even when built and present on disk.\n// The ESM-native alternative, import.meta.resolve(specifier, parentURL),\n// would honor the right condition set and resolve this cwd-anchored — but its\n// second (parentURL) parameter, the one needed to anchor anywhere other than\n// this module's own URL, is documented as requiring the\n// --experimental-import-meta-resolve flag, and a published CLI that must run\n// un-flagged on Node 20 and 22 cannot bet a core resolution path on that.\n//\n// The fix walks node_modules directories by hand (findPackageDir) — a plain\n// filesystem read bypasses the exports map entirely — then reads the found\n// package's own package.json and picks its entry file directly\n// (entryFileFor), honoring exports[\".\"].import, a string exports[\".\"],\n// exports[\".\"].default, a root-string exports field, \"module\", then \"main\",\n// in that order.\n//\n// Returning null instead of throwing lets callers distinguish \"not installed\"\n// (exit 3, name the install command) from \"installed but broken\" (a real error\n// worth surfacing). Same discipline as tryLoadRenderer() in\n// packages/editor/src/utils/toMjml.ts: findPackageDir returning null is the\n// only thing that continues to the next anchor — a found package's own entry\n// resolution or import() is never caught, so a genuinely broken install\n// propagates as a real error rather than a misleading install hint.\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\n\ninterface ExportsConditions {\n import?: string;\n default?: string;\n}\n\ninterface PackageManifest {\n exports?: string | Record<string, string | ExportsConditions>;\n module?: string;\n main?: string;\n}\n\n/**\n * Walk up from `dir` through every ancestor's node_modules looking for\n * <specifier>/package.json — the same directory-walk Node's own resolver uses\n * to locate a package, without then asking Node to apply exports-map\n * resolution. `dir` is normalized to an absolute path via `resolve()` before\n * the walk starts, so a relative anchor (e.g. \".\") climbs real ancestors —\n * unnormalized, `dirname(\".\")` is \".\" forever and the walk would give up\n * after the first miss.\n */\nfunction findPackageDir(specifier: string, dir: string): string | null {\n let current = resolve(dir);\n for (;;) {\n const candidate = join(current, \"node_modules\", specifier);\n if (existsSync(join(candidate, \"package.json\"))) return candidate;\n const parent = dirname(current);\n if (parent === current) return null;\n current = parent;\n }\n}\n\n/**\n * Pick a found package's entry file straight from its own manifest, honoring\n * exports[\".\"].import, a string exports[\".\"], exports[\".\"].default, a\n * root-string exports field, \"module\", then \"main\" — the fields an ESM\n * consumer needs, read without Node's exports-map gating.\n */\nfunction entryFileFor(pkgDir: string): string {\n const manifest = JSON.parse(\n readFileSync(join(pkgDir, \"package.json\"), \"utf8\"),\n ) as PackageManifest;\n\n const dot =\n manifest.exports && typeof manifest.exports === \"object\"\n ? manifest.exports[\".\"]\n : undefined;\n const conditions = dot && typeof dot === \"object\" ? dot : undefined;\n // \"exports\": \"./dist/index.js\" — no \".\" key at all. PackageManifest already\n // types this shape; the code just never read it.\n const rootExports =\n typeof manifest.exports === \"string\" ? manifest.exports : undefined;\n\n const entry =\n conditions?.import ??\n (typeof dot === \"string\" ? dot : undefined) ??\n conditions?.default ??\n rootExports ??\n manifest.module ??\n manifest.main;\n\n // typeof, not just truthiness: the tsup/tsdown types-first shape nests\n // exports[\".\"].import as a further conditions object ({ types, default }),\n // not a string. Without this check that object flows into join() below and\n // throws a raw `TypeError: The \"path\" argument must be of type string`\n // instead of this function's own, actionable error.\n if (!entry || typeof entry !== \"string\") {\n throw new Error(\n `${pkgDir} has no resolvable entry point (exports/module/main).`,\n );\n }\n return join(pkgDir, entry);\n}\n\nexport async function resolveOptional<T>(\n specifier: string,\n cwd: string = process.cwd(),\n): Promise<T | null> {\n const anchors = [cwd, dirname(fileURLToPath(import.meta.url))];\n\n for (const anchor of anchors) {\n const pkgDir = findPackageDir(specifier, anchor);\n if (!pkgDir) continue; // not found from this anchor — try the next\n // Deliberately outside the try below: a manifest that names no usable\n // entry is a packaging fault the caller can act on, and it keeps throwing.\n const resolved = entryFileFor(pkgDir);\n try {\n return (await import(pathToFileURL(resolved).href)) as T;\n } catch {\n // The manifest is fine but the file it names isn't there — a workspace\n // package whose dist/ hasn't been built is the everyday case. \"Optional\"\n // has to cover this, or `import --list-formats`, whose whole job is to\n // report which converters resolve, crashes on the first one that doesn't.\n // Keep looking: a later anchor may hold a complete copy.\n continue;\n }\n }\n return null;\n}\n","// The optional `mjml` peer, resolved from the user's cwd first. The SDK\n// bundles no MJML compiler by design, so a missing peer is either skipped\n// (validate) or a hard stop with an install hint (render --format html).\n//\n// The mjml package's top-level function is `async`, so it always returns a\n// Promise even though the underlying compile is synchronous.\n\nimport { MissingDependencyError } from \"./io\";\nimport { resolveOptional } from \"./resolve-optional\";\n\nexport type Mjml2Html = (\n mjml: string,\n options?: Record<string, unknown>,\n) => Promise<{ html: string; errors: unknown[] }>;\n\nexport async function loadMjml(cwd: string): Promise<Mjml2Html | null> {\n const mod = await resolveOptional<{ default: Mjml2Html }>(\"mjml\", cwd);\n return mod ? mod.default : null;\n}\n\nexport async function requireMjml(\n cwd: string,\n purpose: string,\n): Promise<Mjml2Html> {\n const mjml = await loadMjml(cwd);\n if (!mjml) {\n throw new MissingDependencyError(\n \"mjml\",\n `${purpose} needs the optional \\`mjml\\` package, which isn't installed.\\n npm install mjml`,\n );\n }\n return mjml;\n}\n","import { flagValue, type ParsedArgs } from \"../args\";\nimport { emit, note } from \"../output\";\nimport { EXIT, readTemplateFile, UsageError } from \"../io\";\nimport { runQualityLint, validateTemplate } from \"../../index\";\nimport { renderToMjml } from \"@templatical/renderer\";\nimport { lintCompiledHtml } from \"@templatical/quality\";\nimport type { TemplateContent } from \"@templatical/types\";\nimport { requireMjml } from \"../mjml\";\n\nexport async function runValidate(args: ParsedArgs): Promise<number> {\n const file = args.positional[0];\n if (!file) throw new UsageError(\"validate needs a template file.\");\n const cwd = flagValue(args, \"cwd\") ?? process.cwd();\n const compile =\n args.flags.html === true\n ? await requireMjml(cwd, \"Validating HTML size\")\n : null;\n\n const data = readTemplateFile(file, cwd);\n const { valid, errors } = validateTemplate(data);\n\n if (!valid) {\n emit({ valid: false, errors, issues: [] }, () =>\n [\n `✗ Structural validation failed (${errors.length}):`,\n ...errors.map((e) => ` - ${e}`),\n ].join(\"\\n\"),\n );\n return EXIT.invalid;\n }\n\n // The linter assumes a structurally-valid template, so it runs only here.\n const quality = runQualityLint(data);\n if (quality.error) {\n note(`Quality lint could not run: ${quality.error}`);\n }\n\n const issues = [...quality.issues];\n let htmlBytes: number | undefined;\n if (compile) {\n const mjml = await renderToMjml(data as TemplateContent);\n const html = (await compile(mjml, { validationLevel: \"soft\" })).html;\n htmlBytes = new TextEncoder().encode(html).byteLength;\n issues.push(...lintCompiledHtml(html));\n }\n const blocking = issues.filter((i) => i.severity === \"error\");\n\n emit(\n {\n valid: true,\n errors: [],\n issues,\n ...(htmlBytes !== undefined ? { htmlBytes } : {}),\n },\n () => {\n if (issues.length === 0) return \"✓ Valid — no quality issues\";\n const lines = issues.flatMap((i) => [\n ` - [${i.severity}] ${i.ruleId}: ${i.message}`,\n ` → ${i.suggestion}`,\n ]);\n return [\n `✓ Structurally valid · ${issues.length} quality issue(s):`,\n ...lines,\n ].join(\"\\n\");\n },\n );\n\n // A severity-\"error\" issue is a real defect, not advice, so it fails the\n // command — matching the script this replaces. Warnings and info do not.\n return blocking.length > 0 ? EXIT.invalid : EXIT.ok;\n}\n","import { mkdirSync, writeFileSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\nimport { renderToMjml } from \"@templatical/renderer\";\nimport type { TemplateContent } from \"@templatical/types\";\nimport { flagValue, type ParsedArgs } from \"../args\";\nimport { emit, note } from \"../output\";\nimport {\n EXIT,\n InvalidTemplateError,\n readTemplateFile,\n resolveFrom,\n UsageError,\n} from \"../io\";\nimport { requireMjml } from \"../mjml\";\nimport { validateTemplate } from \"../../index\";\n\nconst FORMATS = new Set([\"mjml\", \"html\"]);\n\nexport async function runRender(args: ParsedArgs): Promise<number> {\n const file = args.positional[0];\n if (!file) throw new UsageError(\"render needs a template file.\");\n\n const format = flagValue(args, \"format\") ?? \"mjml\";\n if (!FORMATS.has(format)) {\n throw new UsageError(`Unknown --format \"${format}\". Use mjml or html.`);\n }\n\n const cwd = flagValue(args, \"cwd\") ?? process.cwd();\n const data = readTemplateFile(file, cwd);\n\n // A structurally invalid template must fail with the error list (exit 1),\n // not surface as a renderer-internals crash (exit 2) — edit.ts validates\n // for the same reason before it writes.\n const { valid, errors } = validateTemplate(data);\n if (!valid) {\n throw new InvalidTemplateError(\n `${file} is not structurally valid (${errors.length} error(s)).`,\n errors,\n );\n }\n\n const content = data as TemplateContent;\n const mjml = await renderToMjml(content);\n\n let output = mjml;\n if (format === \"html\") {\n const compile = await requireMjml(cwd, \"Rendering HTML\");\n output = (await compile(mjml, { validationLevel: \"soft\" })).html;\n }\n\n const out = flagValue(args, \"out\", \"o\");\n if (out) {\n const path = resolveFrom(out, cwd);\n // render writes raw text, not JSON, so it can't reuse writeTemplateFile —\n // create the parent directory directly instead.\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, output, \"utf8\");\n note(`Wrote ${path}`);\n return EXIT.ok;\n }\n\n emit({ format, output }, () => output);\n return EXIT.ok;\n}\n","import type { Operation, TemplateContent } from \"@templatical/types\";\nimport { applyOperations, OperationError } from \"@templatical/types\";\nimport { flagValue, type ParsedArgs } from \"../args\";\nimport { emit } from \"../output\";\nimport {\n EXIT,\n InvalidTemplateError,\n readTemplateFile,\n UsageError,\n writeTemplateFile,\n} from \"../io\";\nimport { validateTemplate } from \"../../index\";\n\nfunction parseOperations(args: ParsedArgs, cwd: string): unknown[] {\n const inline = flagValue(args, \"op\");\n const batchFile = flagValue(args, \"ops\");\n // !== undefined, not truthy: flagValue returns \"\" for an explicitly-empty\n // flag, and a truthy check would let --op \"\" --ops <file> silently run the\n // batch instead of reporting that both were passed.\n if (inline !== undefined && batchFile !== undefined) {\n throw new UsageError(\"Pass either --op or --ops, not both.\");\n }\n if (inline) {\n try {\n return [JSON.parse(inline) as unknown];\n } catch (err) {\n throw new UsageError(`--op is not valid JSON: ${(err as Error).message}`);\n }\n }\n if (batchFile) {\n const parsed = readTemplateFile(batchFile, cwd);\n if (!Array.isArray(parsed)) {\n throw new UsageError(\"--ops must point at a JSON array of operations.\");\n }\n return parsed;\n }\n throw new UsageError(\n \"edit needs --op '<json>' for one operation or --ops <file> for a batch.\",\n );\n}\n\n/** An object written in the old vocabulary: `{\"operation\": …, \"data\": …}`. */\nfunction isOldVocabulary(input: unknown): boolean {\n return (\n typeof input === \"object\" &&\n input !== null &&\n \"operation\" in input &&\n !(\"op\" in input)\n );\n}\n\nexport function runEdit(args: ParsedArgs): number {\n const file = args.positional[0];\n if (!file) throw new UsageError(\"edit needs a template file.\");\n const cwd = flagValue(args, \"cwd\") ?? process.cwd();\n\n const operations = parseOperations(args, cwd);\n const oldIndex = operations.findIndex(isOldVocabulary);\n if (oldIndex !== -1) {\n throw new UsageError(\n `Operation ${oldIndex + 1} uses the old {\"operation\", \"data\"} form. ` +\n 'Write {\"op\": \"updateBlock\", \"blockId\": …, \"set\": {…}} and the like: ' +\n \"see the operations reference.\",\n );\n }\n const before = readTemplateFile(file, cwd) as TemplateContent;\n\n // All or nothing: the engine throws at the first refused operation and\n // nothing is written. A working file has one writer, so there are no locks.\n let content: TemplateContent;\n try {\n content = applyOperations(before, operations as Operation[]);\n } catch (error) {\n if (!(error instanceof OperationError)) throw error;\n const refused = operations[error.opIndex] as { op?: unknown } | undefined;\n throw new UsageError(\n `Operation ${error.opIndex + 1} (${String(refused?.op)}) was refused: ${error.code} — ${error.message}`,\n );\n }\n\n // An operation can produce a structurally invalid document, so validate\n // before writing: the working file must always be valid.\n const { valid, errors } = validateTemplate(content);\n if (!valid) {\n throw new InvalidTemplateError(\n `The edited template is not structurally valid (${errors.length} error(s)); ${file} was not written.`,\n errors,\n );\n }\n\n const path = writeTemplateFile(file, content, cwd);\n emit(\n { applied: operations.length, file: path },\n () => `Applied ${operations.length} operation(s) to ${path}`,\n );\n return EXIT.ok;\n}\n","// The format registry. A new @templatical/import-* converter is ONE entry here\n// and nothing else: reference/import.md documents the routing rule rather than\n// the list, and `--list-formats` answers what is resolvable at runtime. That is\n// what lets a new importer ship without a skill edit.\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { basename, extname } from \"node:path\";\nimport { flagValue, type ParsedArgs } from \"../args\";\nimport { emit } from \"../output\";\nimport {\n EXIT,\n MissingDependencyError,\n resolveFrom,\n UsageError,\n writeTemplateFile,\n} from \"../io\";\nimport { resolveOptional } from \"../resolve-optional\";\nimport { WORKING_DIR } from \"../../live/index\";\n\ninterface FormatSpec {\n pkg: string;\n /** The converter's exported function name. */\n fn: string;\n /**\n * What the converter is handed. `json` parses the source first, `text` passes\n * it through, and `stripo` unpacks a `{ html, css }` envelope — Stripo is the\n * one format whose export may arrive as either shape.\n */\n input: \"json\" | \"text\" | \"stripo\";\n}\n\nexport const FORMATS: Record<string, FormatSpec> = {\n unlayer: {\n pkg: \"@templatical/import-unlayer\",\n fn: \"convertUnlayerTemplate\",\n input: \"json\",\n },\n beefree: {\n pkg: \"@templatical/import-beefree\",\n fn: \"convertBeeFreeTemplate\",\n input: \"json\",\n },\n stripo: {\n pkg: \"@templatical/import-stripo\",\n fn: \"convertStripoTemplate\",\n input: \"stripo\",\n },\n topol: {\n pkg: \"@templatical/import-topol\",\n fn: \"convertTopolTemplate\",\n input: \"json\",\n },\n chamaileon: {\n pkg: \"@templatical/import-chamaileon\",\n fn: \"convertChamaileonTemplate\",\n input: \"json\",\n },\n \"easy-email-pro\": {\n pkg: \"@templatical/import-easy-email-pro\",\n fn: \"convertEasyEmailProTemplate\",\n input: \"json\",\n },\n mjml: {\n pkg: \"@templatical/import-mjml\",\n fn: \"convertMjmlTemplate\",\n input: \"text\",\n },\n html: {\n pkg: \"@templatical/import-html\",\n fn: \"convertHtmlTemplate\",\n input: \"text\",\n },\n};\n\n/** Strip a tag and its contents, so class scanning never reads CSS or script. */\nfunction withoutElements(html: string, tag: string): string {\n const open = `<${tag}`;\n const close = `</${tag}`;\n const lower = html.toLowerCase();\n let out = \"\";\n let pos = 0;\n while (pos < html.length) {\n const start = lower.indexOf(open, pos);\n if (start === -1) {\n out += html.slice(pos);\n break;\n }\n const next = lower[start + open.length];\n // `<style` matches `<styles>` too unless the next char ends the tag name.\n if (next !== undefined && /[a-z0-9-]/.test(next)) {\n out += html.slice(pos, start + open.length);\n pos = start + open.length;\n continue;\n }\n out += html.slice(pos, start);\n const gt = html.indexOf(\">\", start);\n if (gt === -1) break;\n const closeAt = lower.indexOf(close, gt + 1);\n if (closeAt === -1) break;\n const closeGt = html.indexOf(\">\", closeAt);\n if (closeGt === -1) break;\n out += \" \";\n pos = closeGt + 1;\n }\n return out;\n}\n\n/** Every class token in the markup, ignoring <style> and <script> contents. */\nfunction markupClassTokens(html: string): string[] {\n const stripped = withoutElements(withoutElements(html, \"style\"), \"script\");\n const tokens: string[] = [];\n const re = /\\bclass\\s*=\\s*([\"'])([^\"']*)\\1/gi;\n let m: RegExpExecArray | null;\n while ((m = re.exec(stripped))) {\n tokens.push(...m[2].trim().split(/\\s+/).filter(Boolean));\n }\n return tokens;\n}\n\n/** Stripo's own class prefixes, which survive both of its export shapes. */\nfunction looksLikeStripoHtml(html: unknown): boolean {\n if (typeof html !== \"string\" || html.trim().length === 0) return false;\n const tokens = markupClassTokens(html);\n if (\n tokens.some(\n (t) =>\n t === \"esd-stripe\" ||\n t === \"esd-structure\" ||\n t === \"esd-container-frame\" ||\n t.startsWith(\"esd-block-\"),\n )\n ) {\n return true;\n }\n return tokens.some(\n (t) =>\n t === \"es-wrapper\" || t === \"es-content-body\" || t === \"es-header-body\",\n );\n}\n\n/** Easy Email Pro marks its own nodes `standard-*`; OSS Easy Email does not. */\nfunction hasStandardType(node: unknown): boolean {\n if (!node || typeof node !== \"object\") return false;\n const n = node as { type?: unknown; children?: unknown };\n if (typeof n.type === \"string\" && n.type.startsWith(\"standard-\")) return true;\n if (Array.isArray(n.children)) return n.children.some(hasStandardType);\n return false;\n}\n\n/** Guess the source format, or null when the caller must pass --format. */\nexport function detectFormat(fileName: string, content: string): string | null {\n const ext = extname(fileName).toLowerCase();\n const trimmed = content.trimStart();\n\n // MJML is decided before both the extension check and the generic `<` branch:\n // an MJML document saved as .html is still MJML, and reading it as HTML\n // silently produces a table-soup import that looks like a bad converter.\n if (ext === \".mjml\") return \"mjml\";\n if (/^<(\\?xml[^>]*\\?>\\s*)?<?\\s*mjml[\\s>]/i.test(trimmed)) return \"mjml\";\n if (/^<\\s*mj-body[\\s>]/i.test(trimmed)) return \"mjml\";\n\n // Stripo's compiled File→HTML and its plugin storage are both `.html` (or a\n // JSON `{ html, css }` blob), so the class check must run before the generic\n // html branch or every Stripo export imports as table soup.\n if (looksLikeStripoHtml(content)) return \"stripo\";\n\n if (ext === \".html\" || ext === \".htm\") return \"html\";\n if (trimmed.startsWith(\"<\")) return \"html\";\n if (trimmed.startsWith(\"{\")) {\n let obj: {\n body?: { rows?: unknown; type?: unknown };\n page?: { rows?: unknown };\n tagName?: unknown;\n content?: { type?: unknown };\n type?: unknown;\n html?: unknown;\n };\n try {\n obj = JSON.parse(content);\n } catch {\n return null;\n }\n // Unlayer designs come from editor.saveDesign(): { body: { rows } }.\n if (obj?.body?.rows) return \"unlayer\";\n // BeeFree templates: { page: { rows } }.\n if (obj?.page?.rows) return \"beefree\";\n // Topol designs are an MJML-shaped tree rooted at the global style.\n if (obj?.tagName === \"mj-global-style\") return \"topol\";\n // Chamaileon getDocument(): { body: { type: \"body\" } }. Unlayer's\n // { body: { rows } } is matched above, so the order between them matters.\n if (obj?.body?.type === \"body\") return \"chamaileon\";\n // Easy Email Pro persist: { content: { type: \"page\" } } or a bare page,\n // distinguished from OSS Easy Email by its `standard-*` node types.\n const page =\n obj?.content?.type === \"page\"\n ? obj.content\n : obj?.type === \"page\"\n ? obj\n : null;\n if (page && hasStandardType(page)) return \"easy-email-pro\";\n // A plugin host often persists the whole getTemplateData() object.\n if (typeof obj?.html === \"string\" && looksLikeStripoHtml(obj.html)) {\n return \"stripo\";\n }\n return null;\n }\n return null;\n}\n\n/** Split a Stripo source into html + css, whichever shape it arrived in. */\nexport function unpackStripoSource(source: string): {\n html: string;\n css?: string;\n} {\n const trimmed = source.trimStart();\n if (trimmed.startsWith(\"{\")) {\n try {\n const obj = JSON.parse(source) as { html?: unknown; css?: unknown };\n if (typeof obj?.html === \"string\") {\n return {\n html: obj.html,\n css: typeof obj.css === \"string\" ? obj.css : undefined,\n };\n }\n } catch {\n // Not an envelope after all — treat the whole thing as markup.\n }\n }\n return { html: source };\n}\n\n/** The stylesheet a plugin host wrote beside an HTML export, if there is one. */\nfunction siblingCss(sourcePath: string, source: string): string | undefined {\n // A JSON envelope carries its own css; only a bare .html file has a sibling.\n if (source.trimStart().startsWith(\"{\")) return undefined;\n const cssPath = sourcePath.replace(/\\.[^.]+$/, \".css\");\n if (cssPath === sourcePath || !existsSync(cssPath)) return undefined;\n return readFileSync(cssPath, \"utf8\");\n}\n\nexport interface ReportCounts {\n total: number;\n converted: number;\n approximated: number;\n htmlFallback: number;\n skipped: number;\n warnings: string[];\n}\n\n/**\n * Status counts from a converter's report. Derived from `report.entries` (every\n * entry carries a `status`) rather than each package's own `summary` shape, so\n * it works identically across all three converters and any future one.\n */\nexport function summarizeReport(report: unknown): ReportCounts {\n const r = report as\n { entries?: Array<{ status?: string }>; warnings?: string[] } | undefined;\n const counts: ReportCounts = {\n total: 0,\n converted: 0,\n approximated: 0,\n htmlFallback: 0,\n skipped: 0,\n warnings: r?.warnings ?? [],\n };\n for (const e of r?.entries ?? []) {\n counts.total++;\n if (e.status === \"converted\") counts.converted++;\n else if (e.status === \"approximated\") counts.approximated++;\n else if (e.status === \"html-fallback\") counts.htmlFallback++;\n else if (e.status === \"skipped\") counts.skipped++;\n }\n return counts;\n}\n\nasync function listFormats(cwd: string): Promise<number> {\n const formats: Array<{\n format: string;\n package: string;\n available: boolean;\n }> = [];\n for (const [format, spec] of Object.entries(FORMATS)) {\n formats.push({\n format,\n package: spec.pkg,\n available: (await resolveOptional(spec.pkg, cwd)) !== null,\n });\n }\n emit({ formats }, () =>\n formats\n .map(\n (f) =>\n ` ${f.format.padEnd(14)} ${f.package}${f.available ? \"\" : \" (not installed)\"}`,\n )\n .join(\"\\n\"),\n );\n return EXIT.ok;\n}\n\nexport async function runImport(args: ParsedArgs): Promise<number> {\n const cwd = flagValue(args, \"cwd\") ?? process.cwd();\n if (args.flags[\"list-formats\"]) return listFormats(cwd);\n\n const file = args.positional[0];\n if (!file) throw new UsageError(\"import needs a source file.\");\n const path = resolveFrom(file, cwd);\n\n let source: string;\n try {\n source = readFileSync(path, \"utf8\");\n } catch {\n throw new UsageError(`Could not read ${file}`);\n }\n\n const known = Object.keys(FORMATS).join(\", \");\n const requested = flagValue(args, \"format\");\n if (requested && !FORMATS[requested]) {\n throw new UsageError(\n `Unknown --format \"${requested}\". Known formats: ${known}.`,\n );\n }\n const format = requested ?? detectFormat(path, source);\n if (!format) {\n throw new UsageError(\n `Could not detect the format of ${file}. Pass --format with one of: ${known}.`,\n );\n }\n\n const spec = FORMATS[format];\n const mod = await resolveOptional<Record<string, unknown>>(spec.pkg, cwd);\n if (!mod) {\n throw new MissingDependencyError(\n spec.pkg,\n `Importing ${format} needs ${spec.pkg}, which isn't installed.\\n npm install ${spec.pkg}`,\n );\n }\n const convert = mod[spec.fn] as (\n input: unknown,\n options?: unknown,\n ) => {\n content: unknown;\n report: unknown;\n };\n\n let content: unknown;\n let report: unknown;\n if (spec.input === \"stripo\") {\n // Plugin storage keeps the stylesheet out of the markup — either beside the\n // html in one JSON envelope, or as a sibling .css file the host wrote next\n // to it. Without the CSS every block imports unstyled, which reads as a\n // broken converter rather than a missing file.\n const unpacked = unpackStripoSource(source);\n const css = unpacked.css ?? siblingCss(path, source);\n ({ content, report } = convert(unpacked.html, css ? { css } : undefined));\n } else {\n const input = spec.input === \"json\" ? JSON.parse(source) : source;\n ({ content, report } = convert(input));\n }\n\n const outName = flagValue(args, \"out\") ?? basename(path, extname(path));\n const written = writeTemplateFile(\n `${WORKING_DIR}/${outName}.json`,\n content,\n cwd,\n );\n\n const counts = summarizeReport(report);\n const lossy = counts.htmlFallback + counts.skipped > 0;\n emit({ format, file: written, report: counts }, () =>\n [\n `Imported ${format} to ${written}`,\n ` ${counts.converted} converted, ${counts.approximated} approximated, ${counts.htmlFallback} html fallback, ${counts.skipped} skipped`,\n ...counts.warnings.map((w) => ` ! ${w}`),\n lossy\n ? \" Import is lossy. Open it in live mode and refine the fallback blocks.\"\n : \"\",\n ]\n .filter(Boolean)\n .join(\"\\n\"),\n );\n return EXIT.ok;\n}\n","import { mkdirSync, writeFileSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\nimport { flagValue, type ParsedArgs } from \"../args\";\nimport { emit, note } from \"../output\";\nimport {\n EXIT,\n InvalidTemplateError,\n readTemplateFile,\n resolveFrom,\n UsageError,\n} from \"../io\";\nimport { loadMjml, requireMjml } from \"../mjml\";\nimport {\n buildSpecimen,\n buildSpecimenTemplate,\n checkCustomBlock,\n checkRecipe,\n renderSpecimenMjml,\n runRecipe,\n SPECIMEN_STATES,\n validateCustomBlockDefinition,\n type CustomBlockIssue,\n type CustomBlockWorkingFile,\n type SpecimenState,\n} from \"../../custom-block\";\n\nconst USAGE =\n \"Use `custom-block validate <file>`, `custom-block render <file>` or `custom-block fetch <file>`.\";\n\nfunction formatIssues(issues: CustomBlockIssue[]): string {\n return issues\n .map(\n (i) =>\n ` - [${i.severity}] ${i.ruleId}${i.path ? ` ${i.path}` : \"\"}: ${i.message}${i.suggestion ? `\\n → ${i.suggestion}` : \"\"}`,\n )\n .join(\"\\n\");\n}\n\n/** `--values '<json>'`: field values a recipe runs with, over the defaults. */\nexport function parseValuesFlag(\n raw: string | undefined,\n): Record<string, unknown> {\n if (raw === undefined) return {};\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n throw new UsageError(\"--values must be a JSON object.\");\n }\n if (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n throw new UsageError(\"--values must be a JSON object.\");\n }\n return parsed as Record<string, unknown>;\n}\n\nfunction loadValid(file: string, cwd: string): CustomBlockWorkingFile {\n const data = readTemplateFile(file, cwd);\n const r = validateCustomBlockDefinition(data);\n if (!r.valid) {\n throw new InvalidTemplateError(\n `${file} is not a valid custom block definition.`,\n r.issues.filter((i) => i.severity === \"error\").map((i) => i.message),\n );\n }\n return data as CustomBlockWorkingFile;\n}\n\nexport async function runCustomBlock(args: ParsedArgs): Promise<number> {\n const sub = args.positional[0];\n const file = args.positional[1];\n if (sub !== \"validate\" && sub !== \"render\" && sub !== \"fetch\") {\n throw new UsageError(`Unknown \"custom-block ${sub ?? \"\"}\". ${USAGE}`);\n }\n if (!file)\n throw new UsageError(`custom-block ${sub} needs a definition file.`);\n const cwd = flagValue(args, \"cwd\") ?? process.cwd();\n\n if (sub === \"validate\") {\n const mjml = await loadMjml(cwd);\n const result = await checkCustomBlock(readTemplateFile(file, cwd), {\n compileMjml: mjml\n ? async (m) => ({\n errors: (await mjml(m, { validationLevel: \"soft\" })).errors,\n })\n : undefined,\n });\n if (!mjml)\n note(\"`mjml` isn't installed, so the HTML compile check was skipped.\");\n emit(result, () =>\n result.issues.length === 0\n ? \"✓ Valid custom block — no issues\"\n : `${result.valid ? \"✓ Valid\" : \"✗ Invalid\"} · ${result.issues.length} issue(s):\\n${formatIssues(result.issues)}`,\n );\n return result.valid ? EXIT.ok : EXIT.invalid;\n }\n\n const def = loadValid(file, cwd);\n\n if (sub === \"render\") {\n const state = flagValue(args, \"state\");\n if (\n state !== undefined &&\n !(SPECIMEN_STATES as readonly string[]).includes(state)\n ) {\n throw new UsageError(\n `Unknown --state \"${state}\". Use one of: ${SPECIMEN_STATES.join(\", \")}.`,\n );\n }\n // A state the definition doesn't produce would render a sheet without the\n // block, which reads as a block that renders nothing.\n if (state !== undefined) {\n const states = buildSpecimen(def).map((i) => i.state);\n if (!(states as string[]).includes(state)) {\n throw new UsageError(\n `${file} has no \"${state}\" state: it has no ${state === \"flipped\" ? \"boolean\" : \"repeatable\"} field. Its states: ${states.join(\", \")}.`,\n );\n }\n }\n const format = flagValue(args, \"format\") ?? \"mjml\";\n if (format !== \"mjml\" && format !== \"html\")\n throw new UsageError(`Unknown --format \"${format}\". Use mjml or html.`);\n let output: string;\n try {\n output = await renderSpecimenMjml(\n def,\n buildSpecimenTemplate(\n def,\n undefined,\n state as SpecimenState | undefined,\n ),\n );\n } catch (err) {\n throw new InvalidTemplateError(`${file} does not render.`, [\n (err as Error).message,\n ]);\n }\n if (format === \"html\")\n output = (\n await (\n await requireMjml(cwd, \"Rendering HTML\")\n )(output, { validationLevel: \"soft\" })\n ).html;\n const out = flagValue(args, \"out\", \"o\");\n if (out) {\n const path = resolveFrom(out, cwd);\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, output, \"utf8\");\n note(`Wrote ${path}`);\n return EXIT.ok;\n }\n emit({ format, output }, () => output);\n return EXIT.ok;\n }\n\n // sub === \"fetch\"\n if (!def.dataSourcePreview)\n throw new UsageError(`${file} has no \\`dataSourcePreview\\` to run.`);\n const recipeErrors = checkRecipe(def).filter((i) => i.severity === \"error\");\n if (recipeErrors.length > 0) {\n throw new InvalidTemplateError(\n `${file} has a dataSourcePreview the bridge would refuse to run.`,\n recipeErrors.map((i) => `${i.ruleId}: ${i.message}`),\n );\n }\n const overrides = parseValuesFlag(flagValue(args, \"values\"));\n const defaults = buildSpecimen(def)[0].fieldValues;\n const result = await runRecipe(def.dataSourcePreview, {\n ...defaults,\n ...overrides,\n });\n emit(result, () =>\n result.ok\n ? `✓ ${result.status} · ${JSON.stringify(result.values, null, 2)}${result.unmapped.length ? `\\nUnmapped: ${result.unmapped.join(\", \")}` : \"\"}`\n : `✗ ${result.error}`,\n );\n return result.ok ? EXIT.ok : EXIT.invalid;\n}\n","import { mkdirSync, rmSync, writeFileSync } from \"node:fs\";\nimport { dirname, isAbsolute, join, resolve } from \"node:path\";\nimport { flagValue, type ParsedArgs } from \"../args\";\nimport { emit, note } from \"../output\";\nimport { EXIT, resolveFrom, UsageError } from \"../io\";\nimport { parseValuesFlag } from \"./custom-block\";\nimport {\n DEFAULT_PORT,\n listWorkingFiles,\n type FetchSummary,\n type LiveMode,\n type PidfileInfo,\n openBrowser,\n pidfilePath,\n processAlive,\n readPidfile,\n readWorkingFile,\n startBridgePreferring,\n WORKING_DIR,\n} from \"../../live/index\";\n\n/**\n * The first title block's text in document order, as a hint for `list`.\n *\n * It must descend into a section's columns, not scan top-level blocks only:\n * templates put their content inside sections (that is the documented\n * structure), so a top-level scan finds nothing for a real template. Measured\n * across all five of the templatical skill's examples — event-invite, newsletter,\n * product-sale, receipt, welcome — none has a top-level title block, so a\n * shallow version of this returns null every time and the hint is dead code.\n */\nfunction titleHint(content: unknown): string | null {\n return findTitle((content as { blocks?: unknown })?.blocks);\n}\n\nfunction findTitle(blocks: unknown): string | null {\n if (!Array.isArray(blocks)) return null;\n for (const block of blocks as Array<{\n type?: string;\n content?: string;\n children?: unknown[];\n }>) {\n if (block?.type === \"title\" && typeof block.content === \"string\") {\n return block.content;\n }\n if (block?.type === \"section\" && Array.isArray(block.children)) {\n for (const column of block.children) {\n const hit = findTitle(column);\n if (hit) return hit;\n }\n }\n }\n return null;\n}\n\nexport function runList(args: ParsedArgs): number {\n const cwd = flagValue(args, \"cwd\") ?? process.cwd();\n const templates = listWorkingFiles(cwd).map((name) => ({\n name,\n title: titleHint(readWorkingFile(join(cwd, WORKING_DIR, name))),\n }));\n emit({ templates }, () =>\n templates.length === 0\n ? `No templates in ${WORKING_DIR}/`\n : templates\n .map((t) => ` ${t.name}${t.title ? ` - ${t.title}` : \"\"}`)\n .join(\"\\n\"),\n );\n return EXIT.ok;\n}\n\nasync function postTo(\n port: number,\n path: string,\n body?: unknown,\n): Promise<Response> {\n return fetch(`http://localhost:${port}${path}`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: body === undefined ? undefined : JSON.stringify(body),\n });\n}\n\n/** The fetched state's outcome, as one line of reload or start output. */\nfunction fetchLine(fetch: FetchSummary): string {\n if (!fetch.ok) return `Fetched state: the request failed. ${fetch.error}`;\n return fetch.unmapped.length > 0\n ? `Fetched state: filled from the API; not in the response: ${fetch.unmapped.join(\", \")}.`\n : \"Fetched state: filled from the API.\";\n}\n\nexport async function runLive(args: ParsedArgs): Promise<number> {\n const sub = args.positional[0];\n const cwd = resolveFrom(flagValue(args, \"cwd\") ?? \".\", process.cwd());\n\n if (sub === \"reload\" || sub === \"stop\") {\n const info = readPidfile(cwd);\n if (!info || !processAlive(info.pid)) {\n throw new UsageError(\n `No live server is running here (no live pidfile at ${WORKING_DIR}/live-server.pid).`,\n );\n }\n if (sub === \"reload\") {\n const consumeAnnotations = args.flags[\"consume-annotations\"] === true;\n const res = await postTo(\n info.port,\n \"/reload\",\n consumeAnnotations ? { consumeAnnotations: true } : undefined,\n );\n const body = (await res.json().catch(() => ({}))) as {\n ok?: boolean;\n clients?: number;\n consumed?: boolean;\n mode?: LiveMode;\n error?: string;\n fetch?: FetchSummary;\n };\n const clients = body.clients ?? 0;\n const consumed = body.consumed === true;\n // The bridge's error already names what failed and what to run; a\n // refused request (a 403 from a rewritten Host, say) has no body at all.\n if (res.status >= 400 || body.ok === false) {\n const reason =\n body.error ??\n (res.status >= 400\n ? `The live server refused the reload (${res.status}).`\n : \"The live server reported a failed reload.\");\n const error = `${reason} Nothing was pushed.`;\n emit(\n { reloaded: false, ok: false, clients, consumed, error },\n () => error,\n );\n return EXIT.invalid;\n }\n const fetch = body.fetch;\n emit(\n {\n reloaded: true,\n ok: true,\n clients,\n consumed,\n ...(fetch ? { fetch } : {}),\n },\n () =>\n [\n body.mode === \"custom-block\"\n ? `Pushed the custom block to ${clients} page(s).`\n : `Pushed the working file to ${clients} connected page(s).`,\n fetch ? fetchLine(fetch) : \"\",\n ]\n .filter(Boolean)\n .join(\"\\n\"),\n );\n return EXIT.ok;\n }\n try {\n process.kill(info.pid, \"SIGTERM\");\n } catch {\n /* already gone */\n }\n rmSync(pidfilePath(cwd), { force: true });\n emit({ stopped: true }, () => \"Stopped the live server.\");\n return EXIT.ok;\n }\n\n if (sub !== undefined) {\n throw new UsageError(\n `Unknown \"live ${sub}\". Use \\`live\\`, \\`live reload\\` or \\`live stop\\`.`,\n );\n }\n\n // start\n const portFlag = flagValue(args, \"port\");\n const preferredPort = portFlag ? Number(portFlag) : DEFAULT_PORT;\n const file = flagValue(args, \"file\");\n const customBlock = flagValue(args, \"custom-block\");\n const host = flagValue(args, \"host\");\n if (customBlock && file) {\n throw new UsageError(\"Pass either --file or --custom-block, not both.\");\n }\n if (host && !customBlock) {\n throw new UsageError(\"--host only applies with --custom-block.\");\n }\n const fetchOn = args.flags.fetch === true;\n if (fetchOn && !customBlock) {\n throw new UsageError(\"--fetch only applies with --custom-block.\");\n }\n const valuesRaw = flagValue(args, \"values\");\n if (valuesRaw !== undefined && !fetchOn) {\n throw new UsageError(\"--values only applies with --fetch.\");\n }\n const fetchValues = fetchOn ? parseValuesFlag(valuesRaw) : undefined;\n const abs = (p: string) => (isAbsolute(p) ? p : resolve(cwd, p));\n const requested: Required<Pick<PidfileInfo, \"mode\" | \"path\">> &\n Pick<PidfileInfo, \"host\" | \"fetch\"> = {\n mode: customBlock ? \"custom-block\" : \"template\",\n path: abs(customBlock ?? file ?? join(WORKING_DIR, \"template.json\")),\n ...(host ? { host: abs(host) } : {}),\n ...(fetchValues ? { fetch: fetchValues } : {}),\n };\n\n const existing = readPidfile(cwd);\n if (existing && processAlive(existing.pid)) {\n // A pidfile without `mode` came from a template-only bridge; one without\n // `path` can't be compared, so only its mode is.\n const mode = existing.mode ?? \"template\";\n if (\n mode !== requested.mode ||\n (existing.path !== undefined && existing.path !== requested.path) ||\n (mode === \"custom-block\" &&\n (existing.host !== requested.host ||\n JSON.stringify(existing.fetch) !== JSON.stringify(requested.fetch)))\n ) {\n throw new UsageError(\n `A live server is already running for ${existing.path ?? \"another file\"} (${mode}). Run \\`templatical live stop\\` first.`,\n );\n }\n emit(\n {\n url: `http://localhost:${existing.port}/`,\n pid: existing.pid,\n alreadyRunning: true,\n },\n () =>\n `Live server already running (pid ${existing.pid}) at http://localhost:${existing.port}/`,\n );\n return EXIT.ok;\n }\n if (existing) rmSync(pidfilePath(cwd), { force: true }); // stale\n\n const handle = await startBridgePreferring({\n cwd,\n preferredPort,\n file,\n customBlock,\n host,\n ...(fetchValues ? { fetch: { values: fetchValues } } : {}),\n });\n\n mkdirSync(dirname(pidfilePath(cwd)), { recursive: true });\n writeFileSync(\n pidfilePath(cwd),\n JSON.stringify({\n pid: process.pid,\n port: handle.port,\n ...requested,\n path: handle.workingPath,\n } satisfies PidfileInfo),\n \"utf8\",\n );\n\n const cleanup = () => {\n rmSync(pidfilePath(cwd), { force: true });\n handle.close().finally(() => process.exit(EXIT.ok));\n };\n process.on(\"SIGINT\", cleanup);\n process.on(\"SIGTERM\", cleanup);\n\n // Emit before blocking: the caller needs the URL and the working path now,\n // not when the server shuts down.\n const fetch = handle.lastFetch();\n emit(\n {\n url: handle.url,\n port: handle.port,\n preferredPort,\n fellBack: handle.fellBack,\n workingFile: handle.workingPath,\n customBlock: customBlock ? handle.workingPath : undefined,\n fetch: fetch ?? undefined,\n },\n () =>\n [\n `Templatical live preview running at ${handle.url}`,\n handle.fellBack\n ? `(port ${preferredPort} was busy - using ${handle.port})`\n : \"\",\n `${customBlock ? \"Custom block\" : \"Working file\"}: ${handle.workingPath}`,\n fetch ? fetchLine(fetch) : \"\",\n ]\n .filter(Boolean)\n .join(\"\\n\"),\n );\n\n if (args.flags[\"no-open\"]) {\n note(`Open ${handle.url} in a browser.`);\n } else {\n note(`Opening ${handle.url} in your default browser...`);\n openBrowser(handle.url);\n }\n note(\"After writing the working file, run: templatical live reload\");\n\n // Block: the bridge owns the process until a signal arrives.\n return new Promise<number>(() => {});\n}\n","#!/usr/bin/env node\n// The CLI entry point.\n//\n// Every command is a thin shell over this package's library functions; the\n// dispatch below owns argument handling, the error→exit-code mapping, and\n// nothing else. Human-facing output goes through cli/output.ts.\n\nimport { realpathSync } from \"node:fs\";\nimport { pathToFileURL } from \"node:url\";\nimport { parseArgs } from \"./cli/args\";\nimport { note, setJsonMode } from \"./cli/output\";\nimport {\n EXIT,\n InvalidTemplateError,\n MissingDependencyError,\n UsageError,\n} from \"./cli/io\";\nimport { runSchema } from \"./cli/commands/schema\";\nimport { runValidate } from \"./cli/commands/validate\";\nimport { runRender } from \"./cli/commands/render\";\nimport { runEdit } from \"./cli/commands/edit\";\nimport { runImport } from \"./cli/commands/import\";\nimport { runCustomBlock } from \"./cli/commands/custom-block\";\nimport { runList, runLive } from \"./cli/commands/live\";\n\nconst USAGE = `templatical <command> [options]\n\n validate <file> [--html] structural + quality lint; --html checks compiled size\n schema [--out <file>] print the block JSON Schema\n render <file> [--format mjml|html] [-o <file>] render to MJML or HTML\n edit <file> --op '<json>' | --ops <file> apply operations, write the result\n import <file> [--format <fmt>] | --list-formats convert a design to Templatical JSON\n live [--file <f>] [--port <n>] [--cwd <d>] [--no-open]\n live reload | live stop\n custom-block validate <file> check a custom block definition\n custom-block render <file> [--state <s>] [--format mjml|html] [-o <file>]\n custom-block fetch <file> [--values '<json>'] run its dataSourcePreview once\n live --custom-block <file> [--host <template>] [--fetch [--values '<json>']]\n preview a custom block\n list working files in .templatical/\n\nOptions:\n --json machine-readable output on stdout\n`;\n\nexport async function main(argv: string[]): Promise<number> {\n const args = parseArgs(argv);\n setJsonMode(args.json);\n\n switch (args.command) {\n case \"validate\":\n return runValidate(args);\n case \"schema\":\n return runSchema(args);\n case \"render\":\n return await runRender(args);\n case \"edit\":\n return runEdit(args);\n case \"import\":\n return await runImport(args);\n case \"live\":\n return await runLive(args);\n case \"list\":\n return runList(args);\n case \"custom-block\":\n return await runCustomBlock(args);\n case \"help\":\n note(USAGE);\n return EXIT.ok;\n case undefined:\n // parseArgs strips leading dashes into flags, so `--help`/`-h` never\n // reach args.command — they land here, not on a (dead) case \"--help\".\n // Asking for help is not a usage error; a bare invocation still is.\n if (args.flags.help === true || args.flags.h === true) {\n note(USAGE);\n return EXIT.ok;\n }\n note(USAGE);\n return EXIT.usage;\n default:\n note(`Unknown command \"${args.command}\".\\n\\n${USAGE}`);\n return EXIT.usage;\n }\n}\n\n// Only self-invoke when run as the CLI entry point, not when imported — this\n// package's own tests import `main` directly to exercise the dispatch above\n// without spawning a subprocess.\n//\n// import.meta.url is always a realpath, but process.argv[1] is not: npm's\n// `bin` field links a real symlink into the consumer's node_modules/.bin\n// (e.g. node_modules/.bin/templatical -> ../@templatical/template-tools/dist/bin.js),\n// and Node leaves argv[1] as that symlink path instead of resolving it.\n// Comparing them directly is false for every consumer who runs the published\n// binary, so main() would silently never run. realpathSync(argv[1]) resolves\n// the symlink so both sides name the same file.\nexport function isEntryPoint(): boolean {\n const argv1 = process.argv[1];\n if (!argv1) return false;\n try {\n return pathToFileURL(realpathSync(argv1)).href === import.meta.url;\n } catch {\n // realpathSync throws (e.g. ENOENT) if argv[1] doesn't exist or can't be\n // read. This guard runs at module load, so failing open into a crash\n // would be worse than just not self-invoking.\n return false;\n }\n}\n\nif (isEntryPoint()) {\n main(process.argv.slice(2))\n .then((code) => process.exit(code))\n .catch((err: unknown) => {\n if (err instanceof InvalidTemplateError) {\n note(err.message);\n for (const e of err.errors) note(` - ${e}`);\n process.exit(EXIT.invalid);\n }\n if (err instanceof MissingDependencyError) {\n note(err.message);\n process.exit(EXIT.missingDep);\n }\n if (err instanceof UsageError) {\n note(err.message);\n process.exit(EXIT.usage);\n }\n note(`Unexpected error: ${(err as Error)?.message ?? String(err)}`);\n process.exit(EXIT.usage);\n });\n}\n"],"mappings":";;;;;;;;;;;;AAIA,MAAM,8BAAc,IAAI,IAAI;CAC1B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAUD,SAAgB,UAAU,MAA4B;CACpD,MAAM,aAAuB,CAAC;CAC9B,MAAM,QAAuC,CAAC;CAC9C,IAAI,OAAO;CAEX,KAAK,IAAI,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;EACpC,MAAM,MAAM,KAAK;EACjB,IAAI,CAAC,IAAI,WAAW,GAAG,GAAG;GACxB,WAAW,KAAK,GAAG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version":3,"file":"bin.js","names":["FORMATS","content","USAGE"],"sources":["../src/cli/args.ts","../src/cli/output.ts","../src/cli/io.ts","../src/cli/commands/schema.ts","../src/cli/resolve-optional.ts","../src/cli/mjml.ts","../src/cli/commands/validate.ts","../src/cli/commands/render.ts","../src/cli/commands/edit.ts","../src/cli/commands/import.ts","../src/cli/commands/custom-block.ts","../src/cli/commands/live.ts","../src/bin.ts"],"sourcesContent":["// Argv parsing for the CLI. Deliberately hand-rolled: the package has no\n// runtime dependency for this, and the surface is a dozen flags.\n\n/** Flags that consume the next argv entry as their value. */\nconst VALUE_FLAGS = new Set([\n \"format\",\n \"out\",\n \"o\",\n \"op\",\n \"ops\",\n \"file\",\n \"port\",\n \"cwd\",\n \"state\",\n \"values\",\n \"custom-block\",\n \"host\",\n]);\n\nexport interface ParsedArgs {\n command?: string;\n /** Everything that is not the command and not a flag — including subcommands. */\n positional: string[];\n json: boolean;\n flags: Record<string, string | true>;\n}\n\nexport function parseArgs(argv: string[]): ParsedArgs {\n const positional: string[] = [];\n const flags: Record<string, string | true> = {};\n let json = false;\n\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i];\n if (!arg.startsWith(\"-\")) {\n positional.push(arg);\n continue;\n }\n\n const bare = arg.replace(/^--?/, \"\");\n const eq = bare.indexOf(\"=\");\n if (eq !== -1) {\n flags[bare.slice(0, eq)] = bare.slice(eq + 1);\n continue;\n }\n if (bare === \"json\") {\n json = true;\n continue;\n }\n // A value flag at the end of argv has no value; record it as present so the\n // command reports a useful usage error rather than reading `undefined`.\n flags[bare] =\n VALUE_FLAGS.has(bare) && i + 1 < argv.length ? argv[++i] : true;\n }\n\n return { command: positional.shift(), positional, json, flags };\n}\n\n/** Read a value flag as a string, or undefined when absent or valueless. */\nexport function flagValue(\n args: ParsedArgs,\n ...names: string[]\n): string | undefined {\n for (const name of names) {\n const v = args.flags[name];\n if (typeof v === \"string\") return v;\n }\n return undefined;\n}\n","// The ONLY module in this package that writes to stdout.\n//\n// `--json` promises callers exactly one parseable document on stdout, and a\n// future stdio-based caller — an MCP server reserving stdout for JSON-RPC —\n// would need that to hold just as strictly. Either way a second writer\n// breaks the contract. tests/cli-output-discipline.test.ts asserts no other\n// source file touches stdout.\n\nlet jsonMode = false;\n\nexport function setJsonMode(on: boolean): void {\n jsonMode = on;\n}\n\nexport function isJsonMode(): boolean {\n return jsonMode;\n}\n\n/**\n * Emit a command's result. Under `--json` the payload is serialized; otherwise\n * `human()` is called for the readable form — as a thunk, so building the\n * pretty output costs nothing in JSON mode.\n */\nexport function emit(payload: unknown, human: () => string): void {\n process.stdout.write(\n jsonMode ? `${JSON.stringify(payload)}\\n` : `${human()}\\n`,\n );\n}\n\n/** Diagnostics, progress and errors. Always stderr, in both modes. */\nexport function note(message: string): void {\n process.stderr.write(`${message}\\n`);\n}\n","// Shared file IO and the error→exit-code contract.\n\nimport { mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname, isAbsolute, resolve } from \"node:path\";\n\nexport const EXIT = {\n ok: 0,\n /** Structural errors, or quality issues of severity \"error\". */\n invalid: 1,\n /** Bad flags, missing arguments, unreadable input. */\n usage: 2,\n /** An optional dependency is not installed; the message names the install. */\n missingDep: 3,\n} as const;\n\nexport class UsageError extends Error {}\n\nexport class InvalidTemplateError extends Error {\n constructor(\n message: string,\n readonly errors: string[] = [],\n ) {\n super(message);\n }\n}\n\nexport class MissingDependencyError extends Error {\n constructor(\n readonly pkg: string,\n message: string,\n ) {\n super(message);\n }\n}\n\nexport function resolveFrom(file: string, cwd = process.cwd()): string {\n return isAbsolute(file) ? file : resolve(cwd, file);\n}\n\nexport function readTemplateFile(file: string, cwd = process.cwd()): unknown {\n const path = resolveFrom(file, cwd);\n let raw: string;\n try {\n raw = readFileSync(path, \"utf8\");\n } catch {\n throw new UsageError(`Could not read ${file}`);\n }\n try {\n return JSON.parse(raw);\n } catch (err) {\n throw new UsageError(\n `${file} is not valid JSON: ${(err as Error).message}`,\n );\n }\n}\n\n/** Write a template, creating the parent directory. Returns the path written. */\nexport function writeTemplateFile(\n file: string,\n content: unknown,\n cwd = process.cwd(),\n): string {\n const path = resolveFrom(file, cwd);\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, `${JSON.stringify(content, null, 2)}\\n`, \"utf8\");\n return path;\n}\n","import { flagValue, type ParsedArgs } from \"../args\";\nimport { emit, note } from \"../output\";\nimport { EXIT, writeTemplateFile } from \"../io\";\nimport { schema } from \"../../index\";\n\nexport function runSchema(args: ParsedArgs): number {\n const out = flagValue(args, \"out\", \"o\");\n if (out) {\n // writeTemplateFile JSON-stringifies with the same shape this command\n // wrote by hand, and creates the parent directory as a side effect.\n const path = writeTemplateFile(out, schema);\n // stdout stays empty: the caller asked for a file, and under --json a path\n // string would not be the document they are parsing for.\n note(`Wrote ${path}`);\n return EXIT.ok;\n }\n emit(schema, () => JSON.stringify(schema, null, 2));\n return EXIT.ok;\n}\n","//\n// Optional dependencies must resolve from the CONSUMER'S cwd, not from this\n// module's location. When the CLI runs via npx it lives in npm's cache, so a\n// package the user installs in their own project is invisible to the CLI's own\n// resolution — and the remediation message (\"npm install mjml\") would be\n// impossible to satisfy. Anchoring the walk at the cwd fixes that; the CLI's\n// own directory is tried second, as a fallback — not for ajv (a hard\n// `dependencies` entry, imported statically in src/validate.ts, so it never\n// passes through this function at all), but for a global install (`npm\n// install -g mjml` places the optional peer as a sibling of this package\n// under one shared global node_modules that only this anchor can reach) and\n// for this package's own tests, which anchor at a throwaway cwd outside the\n// repo and rely on this anchor climbing from inside the repo tree up to the\n// root node_modules holding the @templatical/import-* converters as root\n// devDependencies.\n//\n// Resolution deliberately does NOT go through require.resolve()/createRequire.\n// That API performs Node's CJS-invoked exports resolution, which checks the\n// condition list [\"require\", \"node\", \"default\"] and never \"import\" — so it\n// throws ERR_PACKAGE_PATH_NOT_EXPORTED for any package whose exports map\n// declares only \"import\", which is every first-party package in this monorepo\n// (ESM-only: `exports` exposes only the \"import\" condition, never \"require\"\n// or \"main\"). That map also omits \"./package.json\", so\n// require.resolve can't even read the manifest to look further. The result\n// under the old createRequire-based resolution: every @templatical/import-*\n// converter reported as \"not installed\" even when built and present on disk.\n// The ESM-native alternative, import.meta.resolve(specifier, parentURL),\n// would honor the right condition set and resolve this cwd-anchored — but its\n// second (parentURL) parameter, the one needed to anchor anywhere other than\n// this module's own URL, is documented as requiring the\n// --experimental-import-meta-resolve flag, and a published CLI that must run\n// un-flagged on Node 20 and 22 cannot bet a core resolution path on that.\n//\n// The fix walks node_modules directories by hand (findPackageDir) — a plain\n// filesystem read bypasses the exports map entirely — then reads the found\n// package's own package.json and picks its entry file directly\n// (entryFileFor), honoring exports[\".\"].import, a string exports[\".\"],\n// exports[\".\"].default, a root-string exports field, \"module\", then \"main\",\n// in that order.\n//\n// Returning null instead of throwing lets callers distinguish \"not installed\"\n// (exit 3, name the install command) from \"installed but broken\" (a real error\n// worth surfacing). Same discipline as tryLoadRenderer() in\n// packages/editor/src/utils/toMjml.ts: findPackageDir returning null is the\n// only thing that continues to the next anchor — a found package's own entry\n// resolution or import() is never caught, so a genuinely broken install\n// propagates as a real error rather than a misleading install hint.\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\n\ninterface ExportsConditions {\n import?: string;\n default?: string;\n}\n\ninterface PackageManifest {\n exports?: string | Record<string, string | ExportsConditions>;\n module?: string;\n main?: string;\n}\n\n/**\n * Walk up from `dir` through every ancestor's node_modules looking for\n * <specifier>/package.json — the same directory-walk Node's own resolver uses\n * to locate a package, without then asking Node to apply exports-map\n * resolution. `dir` is normalized to an absolute path via `resolve()` before\n * the walk starts, so a relative anchor (e.g. \".\") climbs real ancestors —\n * unnormalized, `dirname(\".\")` is \".\" forever and the walk would give up\n * after the first miss.\n */\nfunction findPackageDir(specifier: string, dir: string): string | null {\n let current = resolve(dir);\n for (;;) {\n const candidate = join(current, \"node_modules\", specifier);\n if (existsSync(join(candidate, \"package.json\"))) return candidate;\n const parent = dirname(current);\n if (parent === current) return null;\n current = parent;\n }\n}\n\n/**\n * Pick a found package's entry file straight from its own manifest, honoring\n * exports[\".\"].import, a string exports[\".\"], exports[\".\"].default, a\n * root-string exports field, \"module\", then \"main\" — the fields an ESM\n * consumer needs, read without Node's exports-map gating.\n */\nfunction entryFileFor(pkgDir: string): string {\n const manifest = JSON.parse(\n readFileSync(join(pkgDir, \"package.json\"), \"utf8\"),\n ) as PackageManifest;\n\n const dot =\n manifest.exports && typeof manifest.exports === \"object\"\n ? manifest.exports[\".\"]\n : undefined;\n const conditions = dot && typeof dot === \"object\" ? dot : undefined;\n // \"exports\": \"./dist/index.js\" — no \".\" key at all. PackageManifest already\n // types this shape; the code just never read it.\n const rootExports =\n typeof manifest.exports === \"string\" ? manifest.exports : undefined;\n\n const entry =\n conditions?.import ??\n (typeof dot === \"string\" ? dot : undefined) ??\n conditions?.default ??\n rootExports ??\n manifest.module ??\n manifest.main;\n\n // typeof, not just truthiness: the tsup/tsdown types-first shape nests\n // exports[\".\"].import as a further conditions object ({ types, default }),\n // not a string. Without this check that object flows into join() below and\n // throws a raw `TypeError: The \"path\" argument must be of type string`\n // instead of this function's own, actionable error.\n if (!entry || typeof entry !== \"string\") {\n throw new Error(\n `${pkgDir} has no resolvable entry point (exports/module/main).`,\n );\n }\n return join(pkgDir, entry);\n}\n\nexport async function resolveOptional<T>(\n specifier: string,\n cwd: string = process.cwd(),\n): Promise<T | null> {\n const anchors = [cwd, dirname(fileURLToPath(import.meta.url))];\n\n for (const anchor of anchors) {\n const pkgDir = findPackageDir(specifier, anchor);\n if (!pkgDir) continue; // not found from this anchor — try the next\n // Deliberately outside the try below: a manifest that names no usable\n // entry is a packaging fault the caller can act on, and it keeps throwing.\n const resolved = entryFileFor(pkgDir);\n try {\n return (await import(pathToFileURL(resolved).href)) as T;\n } catch {\n // The manifest is fine but the file it names isn't there — a workspace\n // package whose dist/ hasn't been built is the everyday case. \"Optional\"\n // has to cover this, or `import --list-formats`, whose whole job is to\n // report which converters resolve, crashes on the first one that doesn't.\n // Keep looking: a later anchor may hold a complete copy.\n continue;\n }\n }\n return null;\n}\n","// The optional `mjml` peer, resolved from the user's cwd first. The SDK\n// bundles no MJML compiler by design, so a missing peer is either skipped\n// (validate) or a hard stop with an install hint (render --format html).\n//\n// The mjml package's top-level function is `async`, so it always returns a\n// Promise even though the underlying compile is synchronous.\n\nimport { MissingDependencyError } from \"./io\";\nimport { resolveOptional } from \"./resolve-optional\";\n\nexport type Mjml2Html = (\n mjml: string,\n options?: Record<string, unknown>,\n) => Promise<{ html: string; errors: unknown[] }>;\n\nexport async function loadMjml(cwd: string): Promise<Mjml2Html | null> {\n const mod = await resolveOptional<{ default: Mjml2Html }>(\"mjml\", cwd);\n return mod ? mod.default : null;\n}\n\nexport async function requireMjml(\n cwd: string,\n purpose: string,\n): Promise<Mjml2Html> {\n const mjml = await loadMjml(cwd);\n if (!mjml) {\n throw new MissingDependencyError(\n \"mjml\",\n `${purpose} needs the optional \\`mjml\\` package, which isn't installed.\\n npm install mjml`,\n );\n }\n return mjml;\n}\n","import { flagValue, type ParsedArgs } from \"../args\";\nimport { emit, note } from \"../output\";\nimport { EXIT, readTemplateFile, UsageError } from \"../io\";\nimport { runQualityLint, validateTemplate } from \"../../index\";\nimport { renderToMjml } from \"@templatical/renderer\";\nimport { lintCompiledHtml } from \"@templatical/quality\";\nimport type { TemplateContent } from \"@templatical/types\";\nimport { requireMjml } from \"../mjml\";\n\nexport async function runValidate(args: ParsedArgs): Promise<number> {\n const file = args.positional[0];\n if (!file) throw new UsageError(\"validate needs a template file.\");\n const cwd = flagValue(args, \"cwd\") ?? process.cwd();\n const compile =\n args.flags.html === true\n ? await requireMjml(cwd, \"Validating HTML size\")\n : null;\n\n const data = readTemplateFile(file, cwd);\n const { valid, errors } = validateTemplate(data);\n\n if (!valid) {\n emit({ valid: false, errors, issues: [] }, () =>\n [\n `✗ Structural validation failed (${errors.length}):`,\n ...errors.map((e) => ` - ${e}`),\n ].join(\"\\n\"),\n );\n return EXIT.invalid;\n }\n\n // The linter assumes a structurally-valid template, so it runs only here.\n const quality = runQualityLint(data);\n if (quality.error) {\n note(`Quality lint could not run: ${quality.error}`);\n }\n\n const issues = [...quality.issues];\n let htmlBytes: number | undefined;\n if (compile) {\n const mjml = await renderToMjml(data as TemplateContent);\n const html = (await compile(mjml, { validationLevel: \"soft\" })).html;\n htmlBytes = new TextEncoder().encode(html).byteLength;\n issues.push(...lintCompiledHtml(html));\n }\n const blocking = issues.filter((i) => i.severity === \"error\");\n\n emit(\n {\n valid: true,\n errors: [],\n issues,\n ...(htmlBytes !== undefined ? { htmlBytes } : {}),\n },\n () => {\n if (issues.length === 0) return \"✓ Valid — no quality issues\";\n const lines = issues.flatMap((i) => [\n ` - [${i.severity}] ${i.ruleId}: ${i.message}`,\n ` → ${i.suggestion}`,\n ]);\n return [\n `✓ Structurally valid · ${issues.length} quality issue(s):`,\n ...lines,\n ].join(\"\\n\");\n },\n );\n\n // A severity-\"error\" issue is a real defect, not advice, so it fails the\n // command — matching the script this replaces. Warnings and info do not.\n return blocking.length > 0 ? EXIT.invalid : EXIT.ok;\n}\n","import { mkdirSync, writeFileSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\nimport { renderToMjml } from \"@templatical/renderer\";\nimport type { TemplateContent } from \"@templatical/types\";\nimport { flagValue, type ParsedArgs } from \"../args\";\nimport { emit, note } from \"../output\";\nimport {\n EXIT,\n InvalidTemplateError,\n readTemplateFile,\n resolveFrom,\n UsageError,\n} from \"../io\";\nimport { requireMjml } from \"../mjml\";\nimport { validateTemplate } from \"../../index\";\n\nconst FORMATS = new Set([\"mjml\", \"html\"]);\n\nexport async function runRender(args: ParsedArgs): Promise<number> {\n const file = args.positional[0];\n if (!file) throw new UsageError(\"render needs a template file.\");\n\n const format = flagValue(args, \"format\") ?? \"mjml\";\n if (!FORMATS.has(format)) {\n throw new UsageError(`Unknown --format \"${format}\". Use mjml or html.`);\n }\n\n const cwd = flagValue(args, \"cwd\") ?? process.cwd();\n const data = readTemplateFile(file, cwd);\n\n // A structurally invalid template must fail with the error list (exit 1),\n // not surface as a renderer-internals crash (exit 2) — edit.ts validates\n // for the same reason before it writes.\n const { valid, errors } = validateTemplate(data);\n if (!valid) {\n throw new InvalidTemplateError(\n `${file} is not structurally valid (${errors.length} error(s)).`,\n errors,\n );\n }\n\n const content = data as TemplateContent;\n const mjml = await renderToMjml(content);\n\n let output = mjml;\n if (format === \"html\") {\n const compile = await requireMjml(cwd, \"Rendering HTML\");\n output = (await compile(mjml, { validationLevel: \"soft\" })).html;\n }\n\n const out = flagValue(args, \"out\", \"o\");\n if (out) {\n const path = resolveFrom(out, cwd);\n // render writes raw text, not JSON, so it can't reuse writeTemplateFile —\n // create the parent directory directly instead.\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, output, \"utf8\");\n note(`Wrote ${path}`);\n return EXIT.ok;\n }\n\n emit({ format, output }, () => output);\n return EXIT.ok;\n}\n","import type { Operation, TemplateContent } from \"@templatical/types\";\nimport { applyOperations, OperationError } from \"@templatical/types\";\nimport { flagValue, type ParsedArgs } from \"../args\";\nimport { emit } from \"../output\";\nimport {\n EXIT,\n InvalidTemplateError,\n readTemplateFile,\n UsageError,\n writeTemplateFile,\n} from \"../io\";\nimport { validateTemplate } from \"../../index\";\n\nfunction parseOperations(args: ParsedArgs, cwd: string): unknown[] {\n const inline = flagValue(args, \"op\");\n const batchFile = flagValue(args, \"ops\");\n // !== undefined, not truthy: flagValue returns \"\" for an explicitly-empty\n // flag, and a truthy check would let --op \"\" --ops <file> silently run the\n // batch instead of reporting that both were passed.\n if (inline !== undefined && batchFile !== undefined) {\n throw new UsageError(\"Pass either --op or --ops, not both.\");\n }\n if (inline) {\n try {\n return [JSON.parse(inline) as unknown];\n } catch (err) {\n throw new UsageError(`--op is not valid JSON: ${(err as Error).message}`);\n }\n }\n if (batchFile) {\n const parsed = readTemplateFile(batchFile, cwd);\n if (!Array.isArray(parsed)) {\n throw new UsageError(\"--ops must point at a JSON array of operations.\");\n }\n return parsed;\n }\n throw new UsageError(\n \"edit needs --op '<json>' for one operation or --ops <file> for a batch.\",\n );\n}\n\n/** An object written in the old vocabulary: `{\"operation\": …, \"data\": …}`. */\nfunction isOldVocabulary(input: unknown): boolean {\n return (\n typeof input === \"object\" &&\n input !== null &&\n \"operation\" in input &&\n !(\"op\" in input)\n );\n}\n\nexport function runEdit(args: ParsedArgs): number {\n const file = args.positional[0];\n if (!file) throw new UsageError(\"edit needs a template file.\");\n const cwd = flagValue(args, \"cwd\") ?? process.cwd();\n\n const operations = parseOperations(args, cwd);\n const oldIndex = operations.findIndex(isOldVocabulary);\n if (oldIndex !== -1) {\n throw new UsageError(\n `Operation ${oldIndex + 1} uses the old {\"operation\", \"data\"} form. ` +\n 'Write {\"op\": \"updateBlock\", \"blockId\": …, \"set\": {…}} and the like: ' +\n \"see the operations reference.\",\n );\n }\n const before = readTemplateFile(file, cwd) as TemplateContent;\n\n // All or nothing: the engine throws at the first refused operation and\n // nothing is written. A working file has one writer, so there are no locks.\n let content: TemplateContent;\n try {\n content = applyOperations(before, operations as Operation[]);\n } catch (error) {\n if (!(error instanceof OperationError)) throw error;\n const refused = operations[error.opIndex] as { op?: unknown } | undefined;\n throw new UsageError(\n `Operation ${error.opIndex + 1} (${String(refused?.op)}) was refused: ${error.code} — ${error.message}`,\n );\n }\n\n // An operation can produce a structurally invalid document, so validate\n // before writing: the working file must always be valid.\n const { valid, errors } = validateTemplate(content);\n if (!valid) {\n throw new InvalidTemplateError(\n `The edited template is not structurally valid (${errors.length} error(s)); ${file} was not written.`,\n errors,\n );\n }\n\n const path = writeTemplateFile(file, content, cwd);\n emit(\n { applied: operations.length, file: path },\n () => `Applied ${operations.length} operation(s) to ${path}`,\n );\n return EXIT.ok;\n}\n","// The format registry. A new @templatical/import-* converter is ONE entry here\n// and nothing else: reference/import.md documents the routing rule rather than\n// the list, and `--list-formats` answers what is resolvable at runtime. That is\n// what lets a new importer ship without a skill edit.\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { basename, extname } from \"node:path\";\nimport { flagValue, type ParsedArgs } from \"../args\";\nimport { emit } from \"../output\";\nimport {\n EXIT,\n MissingDependencyError,\n resolveFrom,\n UsageError,\n writeTemplateFile,\n} from \"../io\";\nimport { resolveOptional } from \"../resolve-optional\";\nimport { WORKING_DIR } from \"../../live/index\";\n\ninterface FormatSpec {\n pkg: string;\n /** The converter's exported function name. */\n fn: string;\n /**\n * What the converter is handed. `json` parses the source first, `text` passes\n * it through, and `stripo` unpacks a `{ html, css }` envelope — Stripo is the\n * one format whose export may arrive as either shape.\n */\n input: \"json\" | \"text\" | \"stripo\";\n}\n\nexport const FORMATS: Record<string, FormatSpec> = {\n unlayer: {\n pkg: \"@templatical/import-unlayer\",\n fn: \"convertUnlayerTemplate\",\n input: \"json\",\n },\n beefree: {\n pkg: \"@templatical/import-beefree\",\n fn: \"convertBeeFreeTemplate\",\n input: \"json\",\n },\n stripo: {\n pkg: \"@templatical/import-stripo\",\n fn: \"convertStripoTemplate\",\n input: \"stripo\",\n },\n topol: {\n pkg: \"@templatical/import-topol\",\n fn: \"convertTopolTemplate\",\n input: \"json\",\n },\n chamaileon: {\n pkg: \"@templatical/import-chamaileon\",\n fn: \"convertChamaileonTemplate\",\n input: \"json\",\n },\n \"easy-email-pro\": {\n pkg: \"@templatical/import-easy-email-pro\",\n fn: \"convertEasyEmailProTemplate\",\n input: \"json\",\n },\n mjml: {\n pkg: \"@templatical/import-mjml\",\n fn: \"convertMjmlTemplate\",\n input: \"text\",\n },\n html: {\n pkg: \"@templatical/import-html\",\n fn: \"convertHtmlTemplate\",\n input: \"text\",\n },\n};\n\n/** Strip a tag and its contents, so class scanning never reads CSS or script. */\nfunction withoutElements(html: string, tag: string): string {\n const open = `<${tag}`;\n const close = `</${tag}`;\n const lower = html.toLowerCase();\n let out = \"\";\n let pos = 0;\n while (pos < html.length) {\n const start = lower.indexOf(open, pos);\n if (start === -1) {\n out += html.slice(pos);\n break;\n }\n const next = lower[start + open.length];\n // `<style` matches `<styles>` too unless the next char ends the tag name.\n if (next !== undefined && /[a-z0-9-]/.test(next)) {\n out += html.slice(pos, start + open.length);\n pos = start + open.length;\n continue;\n }\n out += html.slice(pos, start);\n const gt = html.indexOf(\">\", start);\n if (gt === -1) break;\n const closeAt = lower.indexOf(close, gt + 1);\n if (closeAt === -1) break;\n const closeGt = html.indexOf(\">\", closeAt);\n if (closeGt === -1) break;\n out += \" \";\n pos = closeGt + 1;\n }\n return out;\n}\n\n/** Every class token in the markup, ignoring <style> and <script> contents. */\nfunction markupClassTokens(html: string): string[] {\n const stripped = withoutElements(withoutElements(html, \"style\"), \"script\");\n const tokens: string[] = [];\n const re = /\\bclass\\s*=\\s*([\"'])([^\"']*)\\1/gi;\n let m: RegExpExecArray | null;\n while ((m = re.exec(stripped))) {\n tokens.push(...m[2].trim().split(/\\s+/).filter(Boolean));\n }\n return tokens;\n}\n\n/** Stripo's own class prefixes, which survive both of its export shapes. */\nfunction looksLikeStripoHtml(html: unknown): boolean {\n if (typeof html !== \"string\" || html.trim().length === 0) return false;\n const tokens = markupClassTokens(html);\n if (\n tokens.some(\n (t) =>\n t === \"esd-stripe\" ||\n t === \"esd-structure\" ||\n t === \"esd-container-frame\" ||\n t.startsWith(\"esd-block-\"),\n )\n ) {\n return true;\n }\n return tokens.some(\n (t) =>\n t === \"es-wrapper\" || t === \"es-content-body\" || t === \"es-header-body\",\n );\n}\n\n/** Easy Email Pro marks its own nodes `standard-*`; OSS Easy Email does not. */\nfunction hasStandardType(node: unknown): boolean {\n if (!node || typeof node !== \"object\") return false;\n const n = node as { type?: unknown; children?: unknown };\n if (typeof n.type === \"string\" && n.type.startsWith(\"standard-\")) return true;\n if (Array.isArray(n.children)) return n.children.some(hasStandardType);\n return false;\n}\n\n/** Guess the source format, or null when the caller must pass --format. */\nexport function detectFormat(fileName: string, content: string): string | null {\n const ext = extname(fileName).toLowerCase();\n const trimmed = content.trimStart();\n\n // MJML is decided before both the extension check and the generic `<` branch:\n // an MJML document saved as .html is still MJML, and reading it as HTML\n // silently produces a table-soup import that looks like a bad converter.\n if (ext === \".mjml\") return \"mjml\";\n if (/^<(\\?xml[^>]*\\?>\\s*)?<?\\s*mjml[\\s>]/i.test(trimmed)) return \"mjml\";\n if (/^<\\s*mj-body[\\s>]/i.test(trimmed)) return \"mjml\";\n\n // Stripo's compiled File→HTML and its plugin storage are both `.html` (or a\n // JSON `{ html, css }` blob), so the class check must run before the generic\n // html branch or every Stripo export imports as table soup.\n if (looksLikeStripoHtml(content)) return \"stripo\";\n\n if (ext === \".html\" || ext === \".htm\") return \"html\";\n if (trimmed.startsWith(\"<\")) return \"html\";\n if (trimmed.startsWith(\"{\")) {\n let obj: {\n body?: { rows?: unknown; type?: unknown };\n page?: { rows?: unknown };\n tagName?: unknown;\n content?: { type?: unknown };\n type?: unknown;\n html?: unknown;\n };\n try {\n obj = JSON.parse(content);\n } catch {\n return null;\n }\n // Unlayer designs come from editor.saveDesign(): { body: { rows } }.\n if (obj?.body?.rows) return \"unlayer\";\n // BeeFree templates: { page: { rows } }.\n if (obj?.page?.rows) return \"beefree\";\n // Topol designs are an MJML-shaped tree rooted at the global style.\n if (obj?.tagName === \"mj-global-style\") return \"topol\";\n // Chamaileon getDocument(): { body: { type: \"body\" } }. Unlayer's\n // { body: { rows } } is matched above, so the order between them matters.\n if (obj?.body?.type === \"body\") return \"chamaileon\";\n // Easy Email Pro persist: { content: { type: \"page\" } } or a bare page,\n // distinguished from OSS Easy Email by its `standard-*` node types.\n const page =\n obj?.content?.type === \"page\"\n ? obj.content\n : obj?.type === \"page\"\n ? obj\n : null;\n if (page && hasStandardType(page)) return \"easy-email-pro\";\n // A plugin host often persists the whole getTemplateData() object.\n if (typeof obj?.html === \"string\" && looksLikeStripoHtml(obj.html)) {\n return \"stripo\";\n }\n return null;\n }\n return null;\n}\n\n/** Split a Stripo source into html + css, whichever shape it arrived in. */\nexport function unpackStripoSource(source: string): {\n html: string;\n css?: string;\n} {\n const trimmed = source.trimStart();\n if (trimmed.startsWith(\"{\")) {\n try {\n const obj = JSON.parse(source) as { html?: unknown; css?: unknown };\n if (typeof obj?.html === \"string\") {\n return {\n html: obj.html,\n css: typeof obj.css === \"string\" ? obj.css : undefined,\n };\n }\n } catch {\n // Not an envelope after all — treat the whole thing as markup.\n }\n }\n return { html: source };\n}\n\n/** The stylesheet a plugin host wrote beside an HTML export, if there is one. */\nfunction siblingCss(sourcePath: string, source: string): string | undefined {\n // A JSON envelope carries its own css; only a bare .html file has a sibling.\n if (source.trimStart().startsWith(\"{\")) return undefined;\n const cssPath = sourcePath.replace(/\\.[^.]+$/, \".css\");\n if (cssPath === sourcePath || !existsSync(cssPath)) return undefined;\n return readFileSync(cssPath, \"utf8\");\n}\n\nexport interface ReportCounts {\n total: number;\n converted: number;\n approximated: number;\n htmlFallback: number;\n skipped: number;\n warnings: string[];\n}\n\n/**\n * Status counts from a converter's report. Derived from `report.entries` (every\n * entry carries a `status`) rather than each package's own `summary` shape, so\n * it works identically across all three converters and any future one.\n */\nexport function summarizeReport(report: unknown): ReportCounts {\n const r = report as\n { entries?: Array<{ status?: string }>; warnings?: string[] } | undefined;\n const counts: ReportCounts = {\n total: 0,\n converted: 0,\n approximated: 0,\n htmlFallback: 0,\n skipped: 0,\n warnings: r?.warnings ?? [],\n };\n for (const e of r?.entries ?? []) {\n counts.total++;\n if (e.status === \"converted\") counts.converted++;\n else if (e.status === \"approximated\") counts.approximated++;\n else if (e.status === \"html-fallback\") counts.htmlFallback++;\n else if (e.status === \"skipped\") counts.skipped++;\n }\n return counts;\n}\n\nasync function listFormats(cwd: string): Promise<number> {\n const formats: Array<{\n format: string;\n package: string;\n available: boolean;\n }> = [];\n for (const [format, spec] of Object.entries(FORMATS)) {\n formats.push({\n format,\n package: spec.pkg,\n available: (await resolveOptional(spec.pkg, cwd)) !== null,\n });\n }\n emit({ formats }, () =>\n formats\n .map(\n (f) =>\n ` ${f.format.padEnd(14)} ${f.package}${f.available ? \"\" : \" (not installed)\"}`,\n )\n .join(\"\\n\"),\n );\n return EXIT.ok;\n}\n\nexport async function runImport(args: ParsedArgs): Promise<number> {\n const cwd = flagValue(args, \"cwd\") ?? process.cwd();\n if (args.flags[\"list-formats\"]) return listFormats(cwd);\n\n const file = args.positional[0];\n if (!file) throw new UsageError(\"import needs a source file.\");\n const path = resolveFrom(file, cwd);\n\n let source: string;\n try {\n source = readFileSync(path, \"utf8\");\n } catch {\n throw new UsageError(`Could not read ${file}`);\n }\n\n const known = Object.keys(FORMATS).join(\", \");\n const requested = flagValue(args, \"format\");\n if (requested && !FORMATS[requested]) {\n throw new UsageError(\n `Unknown --format \"${requested}\". Known formats: ${known}.`,\n );\n }\n const format = requested ?? detectFormat(path, source);\n if (!format) {\n throw new UsageError(\n `Could not detect the format of ${file}. Pass --format with one of: ${known}.`,\n );\n }\n\n const spec = FORMATS[format];\n const mod = await resolveOptional<Record<string, unknown>>(spec.pkg, cwd);\n if (!mod) {\n throw new MissingDependencyError(\n spec.pkg,\n `Importing ${format} needs ${spec.pkg}, which isn't installed.\\n npm install ${spec.pkg}`,\n );\n }\n const convert = mod[spec.fn] as (\n input: unknown,\n options?: unknown,\n ) => {\n content: unknown;\n report: unknown;\n };\n\n let content: unknown;\n let report: unknown;\n if (spec.input === \"stripo\") {\n // Plugin storage keeps the stylesheet out of the markup — either beside the\n // html in one JSON envelope, or as a sibling .css file the host wrote next\n // to it. Without the CSS every block imports unstyled, which reads as a\n // broken converter rather than a missing file.\n const unpacked = unpackStripoSource(source);\n const css = unpacked.css ?? siblingCss(path, source);\n ({ content, report } = convert(unpacked.html, css ? { css } : undefined));\n } else {\n const input = spec.input === \"json\" ? JSON.parse(source) : source;\n ({ content, report } = convert(input));\n }\n\n const outName = flagValue(args, \"out\") ?? basename(path, extname(path));\n const written = writeTemplateFile(\n `${WORKING_DIR}/${outName}.json`,\n content,\n cwd,\n );\n\n const counts = summarizeReport(report);\n const lossy = counts.htmlFallback + counts.skipped > 0;\n emit({ format, file: written, report: counts }, () =>\n [\n `Imported ${format} to ${written}`,\n ` ${counts.converted} converted, ${counts.approximated} approximated, ${counts.htmlFallback} html fallback, ${counts.skipped} skipped`,\n ...counts.warnings.map((w) => ` ! ${w}`),\n lossy\n ? \" Import is lossy. Open it in live mode and refine the fallback blocks.\"\n : \"\",\n ]\n .filter(Boolean)\n .join(\"\\n\"),\n );\n return EXIT.ok;\n}\n","import { mkdirSync, writeFileSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\nimport { flagValue, type ParsedArgs } from \"../args\";\nimport { emit, note } from \"../output\";\nimport {\n EXIT,\n InvalidTemplateError,\n readTemplateFile,\n resolveFrom,\n UsageError,\n} from \"../io\";\nimport { loadMjml, requireMjml } from \"../mjml\";\nimport {\n buildSpecimen,\n buildSpecimenTemplate,\n checkCustomBlock,\n checkRecipe,\n renderSpecimenMjml,\n runRecipe,\n SPECIMEN_STATES,\n validateCustomBlockDefinition,\n type CustomBlockIssue,\n type CustomBlockWorkingFile,\n type SpecimenState,\n} from \"../../custom-block\";\n\nconst USAGE =\n \"Use `custom-block validate <file>`, `custom-block render <file>` or `custom-block fetch <file>`.\";\n\nfunction formatIssues(issues: CustomBlockIssue[]): string {\n return issues\n .map(\n (i) =>\n ` - [${i.severity}] ${i.ruleId}${i.path ? ` ${i.path}` : \"\"}: ${i.message}${i.suggestion ? `\\n → ${i.suggestion}` : \"\"}`,\n )\n .join(\"\\n\");\n}\n\n/** `--values '<json>'`: field values a recipe runs with, over the defaults. */\nexport function parseValuesFlag(\n raw: string | undefined,\n): Record<string, unknown> {\n if (raw === undefined) return {};\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n throw new UsageError(\"--values must be a JSON object.\");\n }\n if (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n throw new UsageError(\"--values must be a JSON object.\");\n }\n return parsed as Record<string, unknown>;\n}\n\nfunction loadValid(file: string, cwd: string): CustomBlockWorkingFile {\n const data = readTemplateFile(file, cwd);\n const r = validateCustomBlockDefinition(data);\n if (!r.valid) {\n throw new InvalidTemplateError(\n `${file} is not a valid custom block definition.`,\n r.issues.filter((i) => i.severity === \"error\").map((i) => i.message),\n );\n }\n return data as CustomBlockWorkingFile;\n}\n\nexport async function runCustomBlock(args: ParsedArgs): Promise<number> {\n const sub = args.positional[0];\n const file = args.positional[1];\n if (sub !== \"validate\" && sub !== \"render\" && sub !== \"fetch\") {\n throw new UsageError(`Unknown \"custom-block ${sub ?? \"\"}\". ${USAGE}`);\n }\n if (!file)\n throw new UsageError(`custom-block ${sub} needs a definition file.`);\n const cwd = flagValue(args, \"cwd\") ?? process.cwd();\n\n if (sub === \"validate\") {\n const mjml = await loadMjml(cwd);\n const result = await checkCustomBlock(readTemplateFile(file, cwd), {\n compileMjml: mjml\n ? async (m) => ({\n errors: (await mjml(m, { validationLevel: \"soft\" })).errors,\n })\n : undefined,\n });\n if (!mjml)\n note(\"`mjml` isn't installed, so the HTML compile check was skipped.\");\n emit(result, () =>\n result.issues.length === 0\n ? \"✓ Valid custom block — no issues\"\n : `${result.valid ? \"✓ Valid\" : \"✗ Invalid\"} · ${result.issues.length} issue(s):\\n${formatIssues(result.issues)}`,\n );\n return result.valid ? EXIT.ok : EXIT.invalid;\n }\n\n const def = loadValid(file, cwd);\n\n if (sub === \"render\") {\n const state = flagValue(args, \"state\");\n if (\n state !== undefined &&\n !(SPECIMEN_STATES as readonly string[]).includes(state)\n ) {\n throw new UsageError(\n `Unknown --state \"${state}\". Use one of: ${SPECIMEN_STATES.join(\", \")}.`,\n );\n }\n // A state the definition doesn't produce would render a sheet without the\n // block, which reads as a block that renders nothing.\n if (state !== undefined) {\n const states = buildSpecimen(def).map((i) => i.state);\n if (!(states as string[]).includes(state)) {\n throw new UsageError(\n `${file} has no \"${state}\" state: it has no ${state === \"flipped\" ? \"boolean\" : \"repeatable\"} field. Its states: ${states.join(\", \")}.`,\n );\n }\n }\n const format = flagValue(args, \"format\") ?? \"mjml\";\n if (format !== \"mjml\" && format !== \"html\")\n throw new UsageError(`Unknown --format \"${format}\". Use mjml or html.`);\n let output: string;\n try {\n output = await renderSpecimenMjml(\n def,\n buildSpecimenTemplate(\n def,\n undefined,\n state as SpecimenState | undefined,\n ),\n );\n } catch (err) {\n throw new InvalidTemplateError(`${file} does not render.`, [\n (err as Error).message,\n ]);\n }\n if (format === \"html\")\n output = (\n await (\n await requireMjml(cwd, \"Rendering HTML\")\n )(output, { validationLevel: \"soft\" })\n ).html;\n const out = flagValue(args, \"out\", \"o\");\n if (out) {\n const path = resolveFrom(out, cwd);\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, output, \"utf8\");\n note(`Wrote ${path}`);\n return EXIT.ok;\n }\n emit({ format, output }, () => output);\n return EXIT.ok;\n }\n\n // sub === \"fetch\"\n if (!def.dataSourcePreview)\n throw new UsageError(`${file} has no \\`dataSourcePreview\\` to run.`);\n const recipeErrors = checkRecipe(def).filter((i) => i.severity === \"error\");\n if (recipeErrors.length > 0) {\n throw new InvalidTemplateError(\n `${file} has a dataSourcePreview the bridge would refuse to run.`,\n recipeErrors.map((i) => `${i.ruleId}: ${i.message}`),\n );\n }\n const overrides = parseValuesFlag(flagValue(args, \"values\"));\n const defaults = buildSpecimen(def)[0].fieldValues;\n const result = await runRecipe(def.dataSourcePreview, {\n ...defaults,\n ...overrides,\n });\n emit(result, () =>\n result.ok\n ? `✓ ${result.status} · ${JSON.stringify(result.values, null, 2)}${result.unmapped.length ? `\\nUnmapped: ${result.unmapped.join(\", \")}` : \"\"}`\n : `✗ ${result.error}`,\n );\n return result.ok ? EXIT.ok : EXIT.invalid;\n}\n","import { mkdirSync, rmSync, writeFileSync } from \"node:fs\";\nimport { dirname, isAbsolute, join, resolve } from \"node:path\";\nimport { flagValue, type ParsedArgs } from \"../args\";\nimport { emit, note } from \"../output\";\nimport { EXIT, resolveFrom, UsageError } from \"../io\";\nimport { parseValuesFlag } from \"./custom-block\";\nimport {\n DEFAULT_PORT,\n listWorkingFiles,\n type FetchSummary,\n type LiveMode,\n type PidfileInfo,\n openBrowser,\n pidfilePath,\n processAlive,\n readPidfile,\n readWorkingFile,\n startBridgePreferring,\n WORKING_DIR,\n} from \"../../live/index\";\n\n/**\n * The first title block's text in document order, as a hint for `list`.\n *\n * It must descend into a section's columns, not scan top-level blocks only:\n * templates put their content inside sections (that is the documented\n * structure), so a top-level scan finds nothing for a real template. Measured\n * across all five of the templatical skill's examples — event-invite, newsletter,\n * product-sale, receipt, welcome — none has a top-level title block, so a\n * shallow version of this returns null every time and the hint is dead code.\n */\nfunction titleHint(content: unknown): string | null {\n return findTitle((content as { blocks?: unknown })?.blocks);\n}\n\nfunction findTitle(blocks: unknown): string | null {\n if (!Array.isArray(blocks)) return null;\n for (const block of blocks as Array<{\n type?: string;\n content?: string;\n children?: unknown[];\n }>) {\n if (block?.type === \"title\" && typeof block.content === \"string\") {\n return block.content;\n }\n if (block?.type === \"section\" && Array.isArray(block.children)) {\n for (const column of block.children) {\n const hit = findTitle(column);\n if (hit) return hit;\n }\n }\n }\n return null;\n}\n\nexport function runList(args: ParsedArgs): number {\n const cwd = flagValue(args, \"cwd\") ?? process.cwd();\n const templates = listWorkingFiles(cwd).map((name) => ({\n name,\n title: titleHint(readWorkingFile(join(cwd, WORKING_DIR, name))),\n }));\n emit({ templates }, () =>\n templates.length === 0\n ? `No templates in ${WORKING_DIR}/`\n : templates\n .map((t) => ` ${t.name}${t.title ? ` - ${t.title}` : \"\"}`)\n .join(\"\\n\"),\n );\n return EXIT.ok;\n}\n\nasync function postTo(\n port: number,\n path: string,\n body?: unknown,\n): Promise<Response> {\n return fetch(`http://localhost:${port}${path}`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: body === undefined ? undefined : JSON.stringify(body),\n });\n}\n\n/** The fetched state's outcome, as one line of reload or start output. */\nfunction fetchLine(fetch: FetchSummary): string {\n if (!fetch.ok) return `Fetched state: the request failed. ${fetch.error}`;\n return fetch.unmapped.length > 0\n ? `Fetched state: filled from the API; not in the response: ${fetch.unmapped.join(\", \")}.`\n : \"Fetched state: filled from the API.\";\n}\n\nexport async function runLive(args: ParsedArgs): Promise<number> {\n const sub = args.positional[0];\n const cwd = resolveFrom(flagValue(args, \"cwd\") ?? \".\", process.cwd());\n\n if (sub === \"reload\" || sub === \"stop\") {\n const info = readPidfile(cwd);\n if (!info || !processAlive(info.pid)) {\n throw new UsageError(\n `No live server is running here (no live pidfile at ${WORKING_DIR}/live-server.pid).`,\n );\n }\n if (sub === \"reload\") {\n const consumeAnnotations = args.flags[\"consume-annotations\"] === true;\n const res = await postTo(\n info.port,\n \"/reload\",\n consumeAnnotations ? { consumeAnnotations: true } : undefined,\n );\n const body = (await res.json().catch(() => ({}))) as {\n ok?: boolean;\n clients?: number;\n consumed?: boolean;\n mode?: LiveMode;\n error?: string;\n fetch?: FetchSummary;\n };\n const clients = body.clients ?? 0;\n const consumed = body.consumed === true;\n // The bridge's error already names what failed and what to run; a\n // refused request (a 403 from a rewritten Host, say) has no body at all.\n if (res.status >= 400 || body.ok === false) {\n const reason =\n body.error ??\n (res.status >= 400\n ? `The live server refused the reload (${res.status}).`\n : \"The live server reported a failed reload.\");\n const error = `${reason} Nothing was pushed.`;\n emit(\n { reloaded: false, ok: false, clients, consumed, error },\n () => error,\n );\n return EXIT.invalid;\n }\n const fetch = body.fetch;\n emit(\n {\n reloaded: true,\n ok: true,\n clients,\n consumed,\n ...(fetch ? { fetch } : {}),\n },\n () =>\n [\n body.mode === \"custom-block\"\n ? `Pushed the custom block to ${clients} page(s).`\n : `Pushed the working file to ${clients} connected page(s).`,\n fetch ? fetchLine(fetch) : \"\",\n ]\n .filter(Boolean)\n .join(\"\\n\"),\n );\n return EXIT.ok;\n }\n try {\n process.kill(info.pid, \"SIGTERM\");\n } catch {\n /* already gone */\n }\n rmSync(pidfilePath(cwd), { force: true });\n emit({ stopped: true }, () => \"Stopped the live server.\");\n return EXIT.ok;\n }\n\n if (sub !== undefined) {\n throw new UsageError(\n `Unknown \"live ${sub}\". Use \\`live\\`, \\`live reload\\` or \\`live stop\\`.`,\n );\n }\n\n // start\n const portFlag = flagValue(args, \"port\");\n const preferredPort = portFlag ? Number(portFlag) : DEFAULT_PORT;\n const file = flagValue(args, \"file\");\n const customBlock = flagValue(args, \"custom-block\");\n const host = flagValue(args, \"host\");\n if (customBlock && file) {\n throw new UsageError(\"Pass either --file or --custom-block, not both.\");\n }\n if (host && !customBlock) {\n throw new UsageError(\"--host only applies with --custom-block.\");\n }\n const fetchOn = args.flags.fetch === true;\n if (fetchOn && !customBlock) {\n throw new UsageError(\"--fetch only applies with --custom-block.\");\n }\n const valuesRaw = flagValue(args, \"values\");\n if (valuesRaw !== undefined && !fetchOn) {\n throw new UsageError(\"--values only applies with --fetch.\");\n }\n const fetchValues = fetchOn ? parseValuesFlag(valuesRaw) : undefined;\n const abs = (p: string) => (isAbsolute(p) ? p : resolve(cwd, p));\n const requested: Required<Pick<PidfileInfo, \"mode\" | \"path\">> &\n Pick<PidfileInfo, \"host\" | \"fetch\"> = {\n mode: customBlock ? \"custom-block\" : \"template\",\n path: abs(customBlock ?? file ?? join(WORKING_DIR, \"template.json\")),\n ...(host ? { host: abs(host) } : {}),\n ...(fetchValues ? { fetch: fetchValues } : {}),\n };\n\n const existing = readPidfile(cwd);\n if (existing && processAlive(existing.pid)) {\n // A pidfile without `mode` came from a template-only bridge; one without\n // `path` can't be compared, so only its mode is.\n const mode = existing.mode ?? \"template\";\n if (\n mode !== requested.mode ||\n (existing.path !== undefined && existing.path !== requested.path) ||\n (mode === \"custom-block\" &&\n (existing.host !== requested.host ||\n JSON.stringify(existing.fetch) !== JSON.stringify(requested.fetch)))\n ) {\n throw new UsageError(\n `A live server is already running for ${existing.path ?? \"another file\"} (${mode}). Run \\`templatical live stop\\` first.`,\n );\n }\n emit(\n {\n url: `http://localhost:${existing.port}/`,\n pid: existing.pid,\n alreadyRunning: true,\n },\n () =>\n `Live server already running (pid ${existing.pid}) at http://localhost:${existing.port}/`,\n );\n return EXIT.ok;\n }\n if (existing) rmSync(pidfilePath(cwd), { force: true }); // stale\n\n const handle = await startBridgePreferring({\n cwd,\n preferredPort,\n file,\n customBlock,\n host,\n ...(fetchValues ? { fetch: { values: fetchValues } } : {}),\n });\n\n mkdirSync(dirname(pidfilePath(cwd)), { recursive: true });\n writeFileSync(\n pidfilePath(cwd),\n JSON.stringify({\n pid: process.pid,\n port: handle.port,\n ...requested,\n path: handle.workingPath,\n } satisfies PidfileInfo),\n \"utf8\",\n );\n\n const cleanup = () => {\n rmSync(pidfilePath(cwd), { force: true });\n handle.close().finally(() => process.exit(EXIT.ok));\n };\n process.on(\"SIGINT\", cleanup);\n process.on(\"SIGTERM\", cleanup);\n\n // Emit before blocking: the caller needs the URL and the working path now,\n // not when the server shuts down.\n const fetch = handle.lastFetch();\n emit(\n {\n url: handle.url,\n port: handle.port,\n preferredPort,\n fellBack: handle.fellBack,\n workingFile: handle.workingPath,\n customBlock: customBlock ? handle.workingPath : undefined,\n fetch: fetch ?? undefined,\n },\n () =>\n [\n `Templatical live preview running at ${handle.url}`,\n handle.fellBack\n ? `(port ${preferredPort} was busy - using ${handle.port})`\n : \"\",\n `${customBlock ? \"Custom block\" : \"Working file\"}: ${handle.workingPath}`,\n fetch ? fetchLine(fetch) : \"\",\n ]\n .filter(Boolean)\n .join(\"\\n\"),\n );\n\n if (args.flags[\"no-open\"]) {\n note(`Open ${handle.url} in a browser.`);\n } else {\n note(`Opening ${handle.url} in your default browser...`);\n openBrowser(handle.url);\n }\n note(\"After writing the working file, run: templatical live reload\");\n\n // Block: the bridge owns the process until a signal arrives.\n return new Promise<number>(() => {});\n}\n","#!/usr/bin/env node\n// The CLI entry point.\n//\n// Every command is a thin shell over this package's library functions; the\n// dispatch below owns argument handling, the error→exit-code mapping, and\n// nothing else. Human-facing output goes through cli/output.ts.\n\nimport { realpathSync } from \"node:fs\";\nimport { pathToFileURL } from \"node:url\";\nimport { parseArgs } from \"./cli/args\";\nimport { note, setJsonMode } from \"./cli/output\";\nimport {\n EXIT,\n InvalidTemplateError,\n MissingDependencyError,\n UsageError,\n} from \"./cli/io\";\nimport { runSchema } from \"./cli/commands/schema\";\nimport { runValidate } from \"./cli/commands/validate\";\nimport { runRender } from \"./cli/commands/render\";\nimport { runEdit } from \"./cli/commands/edit\";\nimport { runImport } from \"./cli/commands/import\";\nimport { runCustomBlock } from \"./cli/commands/custom-block\";\nimport { runList, runLive } from \"./cli/commands/live\";\n\nconst USAGE = `templatical <command> [options]\n\n validate <file> [--html] structural + quality lint; --html checks compiled size\n schema [--out <file>] print the block JSON Schema\n render <file> [--format mjml|html] [-o <file>] render to MJML or HTML\n edit <file> --op '<json>' | --ops <file> apply operations, write the result\n import <file> [--format <fmt>] | --list-formats convert a design to Templatical JSON\n live [--file <f>] [--port <n>] [--cwd <d>] [--no-open]\n live reload | live stop\n custom-block validate <file> check a custom block definition\n custom-block render <file> [--state <s>] [--format mjml|html] [-o <file>]\n custom-block fetch <file> [--values '<json>'] run its dataSourcePreview once\n live --custom-block <file> [--host <template>] [--fetch [--values '<json>']]\n preview a custom block\n list working files in .templatical/\n\nOptions:\n --json machine-readable output on stdout\n`;\n\nexport async function main(argv: string[]): Promise<number> {\n const args = parseArgs(argv);\n setJsonMode(args.json);\n\n switch (args.command) {\n case \"validate\":\n return runValidate(args);\n case \"schema\":\n return runSchema(args);\n case \"render\":\n return await runRender(args);\n case \"edit\":\n return runEdit(args);\n case \"import\":\n return await runImport(args);\n case \"live\":\n return await runLive(args);\n case \"list\":\n return runList(args);\n case \"custom-block\":\n return await runCustomBlock(args);\n case \"help\":\n note(USAGE);\n return EXIT.ok;\n case undefined:\n // parseArgs strips leading dashes into flags, so `--help`/`-h` never\n // reach args.command — they land here, not on a (dead) case \"--help\".\n // Asking for help is not a usage error; a bare invocation still is.\n if (args.flags.help === true || args.flags.h === true) {\n note(USAGE);\n return EXIT.ok;\n }\n note(USAGE);\n return EXIT.usage;\n default:\n note(`Unknown command \"${args.command}\".\\n\\n${USAGE}`);\n return EXIT.usage;\n }\n}\n\n// Only self-invoke when run as the CLI entry point, not when imported — this\n// package's own tests import `main` directly to exercise the dispatch above\n// without spawning a subprocess.\n//\n// import.meta.url is always a realpath, but process.argv[1] is not: npm's\n// `bin` field links a real symlink into the consumer's node_modules/.bin\n// (e.g. node_modules/.bin/templatical -> ../@templatical/template-tools/dist/bin.js),\n// and Node leaves argv[1] as that symlink path instead of resolving it.\n// Comparing them directly is false for every consumer who runs the published\n// binary, so main() would silently never run. realpathSync(argv[1]) resolves\n// the symlink so both sides name the same file.\nexport function isEntryPoint(): boolean {\n const argv1 = process.argv[1];\n if (!argv1) return false;\n try {\n return pathToFileURL(realpathSync(argv1)).href === import.meta.url;\n } catch {\n // realpathSync throws (e.g. ENOENT) if argv[1] doesn't exist or can't be\n // read. This guard runs at module load, so failing open into a crash\n // would be worse than just not self-invoking.\n return false;\n }\n}\n\nif (isEntryPoint()) {\n main(process.argv.slice(2))\n .then((code) => process.exit(code))\n .catch((err: unknown) => {\n if (err instanceof InvalidTemplateError) {\n note(err.message);\n for (const e of err.errors) note(` - ${e}`);\n process.exit(EXIT.invalid);\n }\n if (err instanceof MissingDependencyError) {\n note(err.message);\n process.exit(EXIT.missingDep);\n }\n if (err instanceof UsageError) {\n note(err.message);\n process.exit(EXIT.usage);\n }\n note(`Unexpected error: ${(err as Error)?.message ?? String(err)}`);\n process.exit(EXIT.usage);\n });\n}\n"],"mappings":";;;;;;;;;;;;AAIA,MAAM,8BAAc,IAAI,IAAI;CAC1B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAUD,SAAgB,UAAU,MAA4B;CACpD,MAAM,aAAuB,CAAC;CAC9B,MAAM,QAAuC,CAAC;CAC9C,IAAI,OAAO;CAEX,KAAK,IAAI,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;EACpC,MAAM,MAAM,KAAK;EACjB,IAAI,CAA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