@getvitops/cli 4.0.0 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.mjs","names":["formatMediaPlan","planSetup","formatSetupPlan"],"sources":["../src/agents.ts","../src/css-scan.ts","../src/lint-css.ts","../src/lint.ts","../src/cli.ts"],"sourcesContent":["/**\n * Side-effect-free helpers for the `vitops agents` / `vitops docs` commands.\n * Kept out of cli.ts (which runs main() on import) so they are unit-testable.\n */\nimport {\n existsSync,\n lstatSync,\n mkdirSync,\n readFileSync,\n readlinkSync,\n rmSync,\n symlinkSync,\n} from 'node:fs';\nimport { dirname, join, parse, relative, resolve } from 'node:path';\n\nexport const SKILL_NAME = 'vitops-design-system';\n\n/** Marker the 0.5.0-era generated skill carried; lets us migrate that layout. */\nexport const GENERATED_MARKER = '<!-- GENERATED by @getvitops/cli';\n\n/**\n * `vitops docs` topics → docs-bundle paths (as returned by `generateDocs`).\n * Order is the `--all` concatenation order.\n */\nexport const TOPICS: Record<string, { path: string; summary: string }> = {\n classes: {\n path: 'css/classes.md',\n summary: 'CSS framework class vocabulary (colour, type, space, layout, animation, patterns)',\n },\n authoring: {\n path: 'authoring.md',\n summary: 'every design-system.json field, rendered from the JSON Schema',\n },\n config: {\n path: 'config.md',\n summary:\n 'every field of the three-section config (designSystem / organization / site), rendered from the JSON Schema',\n },\n formats: {\n path: 'formats.md',\n summary: \"tailwind vs css vs bricks: what's emitted vs what the platform provides\",\n },\n color: {\n path: 'concepts/color.md',\n summary: 'seeded OKLCH scales, functional tokens, automatic dark mode',\n },\n scales: {\n path: 'concepts/scales.md',\n summary: 'fluid modular type & space scales',\n },\n icons: {\n path: 'concepts/icons.md',\n summary: 'semantic icon names across sets, bundle derivation, sprite delivery',\n },\n patterns: {\n path: 'concepts/patterns.md',\n summary: 'pattern CSS: token cascade, override hooks, states, role variants',\n },\n components: {\n path: 'concepts/components.md',\n summary: 'which of the four tiers provides each pattern, and the call to make',\n },\n consent: {\n path: 'concepts/consent.md',\n summary: 'the consent gate: inert gated tags, demand-driven prompting, three-valued choices',\n },\n tracking: {\n path: 'concepts/tracking.md',\n summary: 'ad-click attribution, the `_ac` cookie, conversion notifications',\n },\n search: {\n path: 'concepts/search.md',\n summary: 'what search engines accept, Search Console onboarding, deploy notification',\n },\n legal: {\n path: 'concepts/legal.md',\n summary: 'privacy policy / terms / cookie notice derived from config facts',\n },\n elements: {\n path: 'bricks/elements.md',\n summary: 'Bricks Builder custom elements, controls, defaults',\n },\n};\n\n/**\n * Find the installed package's skill directory by walking up from `cwd` looking\n * for `node_modules/@getvitops/cli/skill/SKILL.md`. Returns the LOGICAL path\n * (through the `node_modules/@getvitops/cli` link, unresolved) or null.\n *\n * Deliberately not derived from import.meta.url: under pnpm the running module's\n * URL is the realpath in `node_modules/.pnpm/@getvitops+cli@<version>/…`, which\n * changes on every version bump — a symlink to it would dangle after upgrades.\n * The logical path is recreated by the package manager on every install, so a\n * link through it always resolves to the currently installed version.\n */\nexport function findSkillTarget(cwd: string): string | null {\n let dir = resolve(cwd);\n const { root } = parse(dir);\n for (;;) {\n const skillDir = join(dir, 'node_modules', '@getvitops', 'cli', 'skill');\n if (existsSync(join(skillDir, 'SKILL.md'))) return skillDir;\n if (dir === root) return null;\n dir = dirname(dir);\n }\n}\n\n/**\n * Idempotently symlink `linkPath` → `targetDir` (relative target). Replaces a\n * stale symlink; migrates a real directory left by the old emitting `vitops\n * agents` (identified by GENERATED_MARKER in its SKILL.md); refuses to clobber\n * anything else. Returns a warning string, or null on success / no-op.\n */\nexport function linkSkill(linkPath: string, targetDir: string): string | null {\n const target = relative(dirname(linkPath), resolve(targetDir));\n try {\n const st = lstatSync(linkPath, { throwIfNoEntry: false });\n if (st && !st.isSymbolicLink()) {\n const oldSkill = join(linkPath, 'SKILL.md');\n const isGenerated =\n st.isDirectory() &&\n existsSync(oldSkill) &&\n readFileSync(oldSkill, 'utf8').includes(GENERATED_MARKER);\n if (!isGenerated)\n return `left ${linkPath} alone (exists and is not a symlink) — link it to ${targetDir} yourself if wanted`;\n rmSync(linkPath, { recursive: true }); // old generated skill layout → replace\n } else if (st) {\n if (readlinkSync(linkPath) === target) return null;\n rmSync(linkPath);\n } else {\n mkdirSync(dirname(linkPath), { recursive: true });\n }\n symlinkSync(target, linkPath);\n return null;\n } catch (err) {\n return `could not symlink ${linkPath}: ${(err as Error).message}`;\n }\n}\n","/**\n * A minimal reader for hand-written CSS: rule selector, declarations as authored,\n * and the at-rule conditions the rule sits inside.\n *\n * **Why not lightningcss.** The generator owns it, and exposing an `analyzeCss`\n * from there was the obvious move — but lightningcss parses declarations into a\n * typed value model, and the typed model is exactly what these rules need to see\n * through. `display: flex` comes back as `pair`, `grid-template-columns: 1fr 1fr`\n * as `track-list`, and `margin-inline: auto` as an empty structured node. Every\n * rule here matches on *authored text*, so recovering it property-by-property\n * would mean re-implementing a serialiser for each one.\n *\n * A brace-depth scanner keeps the text intact, needs no native binary in the\n * CLI's dependency tree, and follows what `generate.ts` already does twice\n * (`stripForTailwind`, `isVariantBlock`).\n *\n * It is deliberately shallow: no specificity, no cascade, no `@supports`\n * semantics. It answers \"what did someone type in this rule\", which is all a\n * reuse suggestion needs.\n */\n\nexport interface CssDeclaration {\n property: string;\n value: string;\n}\n\nexport interface CssRule {\n selector: string;\n declarations: CssDeclaration[];\n /** Enclosing at-rule preludes, outermost first (`@media (min-width: 48rem)`). */\n conditions: string[];\n /** 1-indexed line of the selector. */\n line: number;\n}\n\n/** Strip comments, preserving newlines so line numbers survive. */\nfunction stripComments(css: string): string {\n return css.replace(/\\/\\*[\\s\\S]*?\\*\\//g, (m) => m.replace(/[^\\n]/g, ''));\n}\n\nconst lineAt = (src: string, index: number) => src.slice(0, index).split('\\n').length;\n\n/**\n * Parse declarations from a rule body. Splits on top-level `;` only, so a\n * `var(--x, a; b)` or a data URI cannot end a declaration early.\n */\nfunction parseDeclarations(body: string): CssDeclaration[] {\n const out: CssDeclaration[] = [];\n let depth = 0;\n let start = 0;\n const push = (chunk: string) => {\n const colon = chunk.indexOf(':');\n if (colon < 0) return;\n const property = chunk.slice(0, colon).trim();\n const value = chunk.slice(colon + 1).trim();\n // A nested block leaks in as a property containing `{`; skip it rather than\n // reporting a declaration that was never written.\n if (!property || property.includes('{') || !value) return;\n out.push({ property, value });\n };\n for (let i = 0; i < body.length; i++) {\n const ch = body[i];\n if (ch === '(' || ch === '[') depth++;\n else if (ch === ')' || ch === ']') depth--;\n else if (ch === ';' && depth === 0) {\n push(body.slice(start, i));\n start = i + 1;\n }\n }\n push(body.slice(start));\n return out;\n}\n\n/**\n * Scan a stylesheet into its style rules.\n *\n * Never throws: this runs over consumer source that may be a fragment, and a\n * linter that dies on one unparseable file is one nobody keeps in CI.\n */\nexport function scanCss(css: string): CssRule[] {\n const src = stripComments(css);\n const rules: CssRule[] = [];\n // Each open brace pushes its prelude; at-rule preludes become `conditions` for\n // everything nested inside, style-rule preludes become a selector.\n const stack: { prelude: string; index: number }[] = [];\n let depth = 0;\n let preludeStart = 0;\n\n for (let i = 0; i < src.length; i++) {\n const ch = src[i];\n if (ch === '\"' || ch === \"'\") {\n // Skip strings whole — a brace inside content: \"{\" would desync the depth.\n const quote = ch;\n i++;\n while (i < src.length && src[i] !== quote) {\n if (src[i] === '\\\\') i++;\n i++;\n }\n continue;\n }\n if (ch === '{') {\n const raw = src.slice(preludeStart, i);\n const prelude = raw.trim();\n // Offset of the first non-whitespace character, not of `preludeStart` —\n // that sits where the previous rule ended, so a rule's reported line would\n // be the blank line above it.\n stack.push({ prelude, index: preludeStart + raw.indexOf(prelude.slice(0, 1)) });\n depth++;\n preludeStart = i + 1;\n continue;\n }\n if (ch === '}') {\n const frame = stack.pop();\n depth--;\n if (frame && !frame.prelude.startsWith('@')) {\n // A style rule: its body is everything since it opened, minus any nested\n // blocks, which `parseDeclarations` discards.\n const bodyStart = src.indexOf('{', frame.index) + 1;\n rules.push({\n selector: frame.prelude,\n declarations: parseDeclarations(src.slice(bodyStart, i)),\n conditions: stack.filter((f) => f.prelude.startsWith('@')).map((f) => f.prelude),\n line: lineAt(src, frame.index),\n });\n }\n preludeStart = i + 1;\n continue;\n }\n }\n // Unbalanced braces (a fragment, a truncated file) leave frames on the stack;\n // returning what was parsed beats reporting nothing.\n return rules.filter((r) => r.selector && depth >= 0);\n}\n\n/** `<style>` block contents from an .astro/.vue/.svelte/.html file. */\nexport function extractStyleBlocks(src: string): { css: string; line: number }[] {\n const out: { css: string; line: number }[] = [];\n for (const m of src.matchAll(/<style\\b[^>]*>([\\s\\S]*?)<\\/style>/gi)) {\n // Offset so a finding's line number points into the original file, not into\n // the extracted block.\n const line = lineAt(src, (m.index ?? 0) + m[0].indexOf('>') + 1);\n out.push({ css: m[1] ?? '', line });\n }\n return out;\n}\n","/**\n * The inverse of `lint.ts`: hand-written CSS that re-implements a framework\n * primitive.\n *\n * `lint.ts` catches a class that resolves to nothing — you named something and it\n * isn't there. This catches the costlier direction, where the code *works*: a\n * centred container written by hand, a two-column split behind a media query, a\n * flex row. Nothing is broken, so nothing ever surfaces it, and the design system\n * quietly stops being the place those decisions live.\n *\n * Every finding here is a `suggestion`, never an `error`. These are judgement\n * calls — a rule can be right about the pattern and wrong about the intent — and\n * a reuse hint that failed CI on the day it shipped would be a worse defect than\n * the drift it reports. `--strict` is there for consumers who want the ratchet.\n *\n * Rules stay conservative on purpose: each requires the *combination* that makes\n * the intent unambiguous. `margin-inline: auto` alone is not a centred track;\n * `display: flex` alone is not a cluster.\n */\nimport type { Format } from '@getvitops/generator';\nimport { type CssRule, extractStyleBlocks, scanCss } from './css-scan.ts';\nimport type { LintFinding } from './lint.ts';\n\n/**\n * The framework's own track widths. Declared in two places today\n * (`core/css/layout.css` and the tailwind emitter), so a rule keyed to the token\n * NAME rather than to a value survives either one moving.\n */\nconst TRACK_WIDTHS = ['--width-measure', '--width-breakout', '--width-spotlight'];\n\n/**\n * Column ratios that correspond to a `split-<a>-<b>` class.\n *\n * `.split` is FLEX, not grid — `display: flex` with `flex: 1` children, and a\n * ratio class setting `--_split-a`/`--_split-b`. Equal columns are the base\n * `.split` with no ratio class, which is why `1fr 1fr` is deliberately absent:\n * suggesting `split-1-1` would name a class that does not exist, and this file\n * would then be committing the very defect `lint.ts` reports.\n */\nconst SPLITS: Record<string, string> = {\n '1fr 2fr': '1-2',\n '2fr 1fr': '2-1',\n '1fr 3fr': '1-3',\n '3fr 1fr': '3-1',\n '1fr 4fr': '1-4',\n '4fr 1fr': '4-1',\n '2fr 3fr': '2-3',\n '3fr 2fr': '3-2',\n};\n\nconst decl = (rule: CssRule, property: string) =>\n rule.declarations.find((d) => d.property === property)?.value;\n\n/** Is this rule inside a `min-width` media or container query? */\nconst inMinWidthQuery = (rule: CssRule) => rule.conditions.some((c) => /min-width\\s*:/.test(c));\n\n/** The framework breakpoint a `min-width` condition corresponds to, if any. */\nfunction breakpointOf(rule: CssRule): string | null {\n const rem = rule.conditions.map((c) => /min-width\\s*:\\s*([\\d.]+)rem/.exec(c)?.[1]).find(Boolean);\n if (!rem) return null;\n const n = Number(rem);\n // The framework's container breakpoints: sm/md/lg/xl = 30/48/64/80rem.\n return n >= 80 ? 'xl' : n >= 64 ? 'lg' : n >= 48 ? 'md' : n >= 30 ? 'sm' : null;\n}\n\n/** Spell a responsive utility the way the target format actually emits it. */\nconst responsive = (bp: string, base: string, format: Format) =>\n format === 'tailwind' ? `@${bp}:${base}` : `${bp}-${base}`;\n\ntype Verdict = Omit<LintFinding, 'file' | 'line'>;\n\n/**\n * One rule = one check. Kept as data rather than a chain of ifs so adding a\n * primitive is adding an entry, and so each carries its own explanation.\n */\nconst RULES: ((rule: CssRule, format: Format) => Verdict | null)[] = [\n // ── a centred track, written by hand ──────────────────────────────────────\n (rule) => {\n const token = TRACK_WIDTHS.find(\n (t) => decl(rule, 'max-inline-size')?.includes(t) || decl(rule, 'max-width')?.includes(t),\n );\n const centred = /\\bauto\\b/.test(decl(rule, 'margin-inline') ?? decl(rule, 'margin') ?? '');\n if (!token || !centred) return null;\n return {\n cls: `${rule.selector} { max-inline-size: var(${token}); margin-inline: auto }`,\n severity: 'suggestion',\n reason:\n '`.centered` is this pattern — a grid of named tracks, not a max-width plus auto margins',\n suggestion:\n 'use `.centered`, and widen an individual child with `breakout`, `spotlight` or ' +\n '`fullbleed` on that child rather than overriding the parent',\n };\n },\n\n // ── a two-column split behind a breakpoint ────────────────────────────────\n (rule, format) => {\n const cols = decl(rule, 'grid-template-columns');\n if (!cols || !inMinWidthQuery(rule)) return null;\n const ratio = SPLITS[cols.replace(/\\s+/g, ' ').trim()];\n const bp = ratio && breakpointOf(rule);\n if (!ratio || !bp) return null;\n return {\n cls: `${rule.selector} { grid-template-columns: ${cols} }`,\n severity: 'suggestion',\n reason: `a ${cols} split behind a min-width query is the \\`split-${ratio}\\` utility`,\n suggestion:\n `${responsive(bp, `split-${ratio}`, format)} on the container — the responsive form is ` +\n 'equal below the breakpoint and takes the ratio above it, which is what the query is doing by hand',\n };\n },\n\n // ── a flex row with centred items ─────────────────────────────────────────\n (rule, format) => {\n if (decl(rule, 'display') !== 'flex') return null;\n if (decl(rule, 'align-items') !== 'center') return null;\n if (/column/.test(decl(rule, 'flex-direction') ?? '')) return null;\n return {\n cls: `${rule.selector} { display: flex; align-items: center }`,\n severity: 'suggestion',\n reason: 'the framework has this as utilities',\n suggestion:\n format === 'tailwind'\n ? \"Tailwind's own `flex items-center` (the framework drops these names in this format)\"\n : '`flex items-center`, or `.cluster-start` if this is a row of related controls',\n };\n },\n];\n\n/**\n * Lint stylesheets and the `<style>` blocks of component files.\n *\n * `files` carries raw text, same as `lintSource` — this module stays free of the\n * filesystem so the caller owns discovery.\n */\n/**\n * The banner every generated stylesheet opens with.\n *\n * Linting the generator's own output is the worst false positive this tool can\n * produce: the emitted bundle contains the framework's real implementations of\n * these very patterns, so it reports `.split` as reinventing `.split`. The\n * `css` format writes `styles.css` into the consumer's source tree (`src/styles`\n * by default), which is squarely inside what `--src` scans.\n *\n * Matched on the banner rather than on a path, because the output directory is\n * configurable and a path rule would silently stop working when someone changes\n * it.\n */\n// Case-sensitive on purpose: the banner shouts `GENERATED`, and matching it\n// case-insensitively also swallowed an authored `/* generated content here */`.\nconst GENERATED = /^\\s*\\/\\*!?\\s*GENERATED\\b|do not edit by hand\\./;\n\nexport function lintCss(files: { path: string; text: string }[], format: Format): LintFinding[] {\n const findings: LintFinding[] = [];\n const seen = new Set<string>();\n for (const file of files) {\n if (GENERATED.test(file.text.slice(0, 400))) continue;\n // A .css file is one block starting at line 1; a component file may hold\n // several, each offset to where its <style> opens so a reported line points\n // into the original file rather than into the extracted block.\n const blocks = file.path.endsWith('.css')\n ? [{ css: file.text, line: 1 }]\n : extractStyleBlocks(file.text);\n for (const block of blocks)\n for (const rule of scanCss(block.css))\n for (const check of RULES) {\n const verdict = check(rule, format);\n if (!verdict) continue;\n const line = block.line + rule.line - 1;\n const key = `${file.path}:${line}:${verdict.reason}`;\n if (seen.has(key)) continue;\n seen.add(key);\n findings.push({ file: file.path, line, ...verdict });\n break; // one suggestion per rule — the first match wins\n }\n }\n return findings;\n}\n","/**\n * `vitops lint` — find framework classes in consumer source that resolve to\n * nothing in the format being built.\n *\n * The problem this exists for: an unknown utility class is indistinguishable\n * from a working one. Nothing errors, nothing warns, the element just doesn't\n * get the style. Two shapes of that were found in a real consumer site:\n *\n * • `bg-navy-d` — a leftover from the named-step scale (`d`/`xd`/`xxd`)\n * deleted in favour of numeric steps. The hue is real, the step is not.\n * It appeared ~10× and looked fine only because the `.card` it sat on\n * supplied its own background.\n * • `md-flex-row` — the css/bricks spelling of a responsive variant, used in\n * a `tailwind`-format project where that class is never emitted (Tailwind\n * regenerates those on demand as `@md:`). Silently inert.\n *\n * DESIGN: this deliberately only inspects classes ANCHORED TO THE CONSUMER'S\n * OWN CONFIG — a hue name, a role name, a type role, a shadow, a pattern. It\n * never tries to enumerate \"all valid classes\", because in the tailwind format\n * that would mean knowing Tailwind's entire built-in vocabulary, and every\n * unknown would be a false positive. Anchoring means a finding is always\n * actionable: you named something from your design system, and it doesn't\n * resolve.\n */\nimport { NUMERIC_STEPS, type DesignSystem, type Format } from '@getvitops/generator';\n\n/**\n * `error` — you named something from your design system and it resolves to\n * nothing. Always actionable, and fails the command.\n *\n * `suggestion` — the code works, but the framework already has a primitive for\n * it. Advisory by design: these are judgement calls, and a new rule that failed\n * CI on first run would be a worse defect than the drift it reports. `--strict`\n * promotes them for consumers who want the ratchet.\n */\nexport type LintSeverity = 'error' | 'suggestion';\n\nexport interface LintFinding {\n file: string;\n line: number;\n /** The class token, or for a CSS rule the declaration that triggered it. */\n cls: string;\n reason: string;\n suggestion?: string;\n severity: LintSeverity;\n}\n\nconst UTIL_FAMILIES = ['bg', 'text', 'icon', 'border', 'outline', 'fill', 'stroke'];\nconst BREAKPOINTS = ['sm', 'md', 'lg', 'xl'];\n\n/**\n * The modifiers actually emitted for one family + role, read back out of the\n * generator's own class list.\n *\n * This used to be a hand-maintained array, which is the wrong shape for a\n * suggestion: the two role kinds emit different modifiers (a chromatic role has\n * `solid` and no bare form; a surface role the reverse), so a single list was\n * wrong for one of them no matter what it said.\n */\nconst emittedModifiers = (roleClasses: Set<string>, fam: string, role: string): string[] => {\n const prefix = `${fam}-${role}`;\n return [...roleClasses]\n .filter((c) => c === prefix || c.startsWith(`${prefix}-`))\n .map((c) => c.slice(prefix.length + 1))\n .filter(Boolean)\n .sort();\n};\n\n/** Everything the config makes namable, so we only judge classes we can judge. */\ninterface Vocabulary {\n roles: string[];\n hues: string[];\n steps: string[];\n typeRoles: string[];\n shadows: string[];\n patterns: string[];\n /** Every role utility the generator actually emits, e.g. `bg-surface-x-muted`. */\n roleClasses: Set<string>;\n}\n\nexport function vocabulary(ds: DesignSystem, roleClasses: Iterable<string>): Vocabulary {\n return {\n roles: Object.keys(ds.colors?.roles ?? {}),\n hues: Object.keys(ds.colors?.palette ?? {}),\n steps: [...NUMERIC_STEPS],\n typeRoles: Object.keys(ds.typography?.roles ?? {}),\n shadows: Object.keys(ds.shadows ?? {}),\n patterns: Object.keys(ds.patterns?.items ?? {}),\n roleClasses: new Set(roleClasses),\n };\n}\n\n/**\n * Strip variant prefixes (`@md:`, `hover:`, `dark:`) from a candidate.\n *\n * Format-aware, because the container-query spelling only exists in tailwind.\n * Stripping `@md:` unconditionally made the check asymmetric: `md-split-1-2` in a\n * tailwind project was caught, but `@md:split-1-2` in a css/bricks project became\n * a bare `split-1-2` that matched nothing and returned null — the same silent\n * no-op, in the other direction, unreported.\n */\nconst stripVariants = (cls: string, format: Format): string => {\n let out = cls;\n while (/^@?[a-zA-Z0-9_-]+:/.test(out)) {\n if (format !== 'tailwind' && out.startsWith('@')) break;\n out = out.slice(out.indexOf(':') + 1);\n }\n return out;\n};\n\nconst nearest = (want: string, pool: string[]): string | undefined =>\n pool.find((p) => p.startsWith(want) || want.startsWith(p));\n\n/**\n * Judge one class token. Returns null when the class is none of our business —\n * which is the common case and the whole reason this is low-noise.\n */\nexport function judge(\n raw: string,\n v: Vocabulary,\n format: Format,\n): Omit<LintFinding, 'file' | 'line'> | null {\n const cls = stripVariants(raw, format);\n\n // ── the `@<bp>:` container-query spelling, in a format that has none ───────\n // Tailwind's engine expands these; css/bricks ship pre-expanded `<bp>-` classes\n // instead, so this spelling resolves to nothing there.\n const cq = /^@(sm|md|lg|xl):(.+)$/.exec(cls);\n if (cq && format !== 'tailwind')\n return {\n cls: raw,\n severity: 'error' as const,\n reason: `\\`@${cq[1]}:\\` container-query variants are a tailwind-format spelling; the ${format} format emits pre-expanded classes`,\n suggestion: `${cq[1]}-${cq[2]}`,\n };\n\n // ── the `<bp>-` responsive spelling ────────────────────────────────────────\n const bp = /^(sm|md|lg|xl)-(.+)$/.exec(cls);\n if (bp && format === 'tailwind')\n return {\n cls: raw,\n severity: 'error' as const,\n reason: `\\`${bp[1]}-\\` responsive classes are not emitted in the tailwind format`,\n suggestion: `@${bp[1]}:${bp[2]} (framework breakpoints) or ${bp[1]}:${bp[2]} (Tailwind's)`,\n };\n // In css/bricks the bare-prefix form is real; fall through and judge the base\n // against the rest of the vocabulary.\n const base = bp && format !== 'tailwind' ? (bp[2] as string) : cls;\n\n // ── <util>-<hue>-<step> ────────────────────────────────────────────────────\n const util = new RegExp(`^(${UTIL_FAMILIES.join('|')})-(.+)$`).exec(base);\n if (util) {\n const [, fam, rest] = util as unknown as [string, string, string];\n // Anything the generator actually emits is valid, full stop. Checking this\n // first also settles the ambiguity below for every well-formed class.\n if (v.roleClasses.has(base)) return null;\n\n // Role and hue names can share a prefix — `defaultConfig()` has the hue\n // `brand` and the role `brand-primary`, so matching hues first would read\n // `bg-brand-primary-x-muted` as hue `brand` + step `primary-x-muted` and\n // report a bogus bad step. Take the LONGEST match across both vocabularies.\n const prefix = (names: string[]) =>\n names\n .filter((n) => rest === n || rest.startsWith(`${n}-`))\n .sort((a, b) => b.length - a.length)[0];\n const hue = prefix(v.hues);\n const role = prefix(v.roles);\n const useRole = role && (!hue || role.length > hue.length);\n\n if (useRole) {\n const mod = rest.slice((role as string).length + 1);\n const valid = emittedModifiers(v.roleClasses, fam as string, role as string);\n return {\n cls: raw,\n severity: 'error' as const,\n reason: `\\`${fam}-${role}${mod ? `-${mod}` : ''}\\` is not emitted for the \\`${role}\\` role`,\n suggestion: valid.length\n ? `valid modifiers: ${valid.join(', ')}`\n : `the \\`${role}\\` role emits no \\`${fam}-*\\` utilities`,\n };\n }\n if (hue) {\n const step = rest.slice(hue.length + 1);\n if (step === '')\n return {\n cls: raw,\n severity: 'error' as const,\n reason: `\\`${fam}-${hue}\\` names a palette hue with no step`,\n suggestion: `${fam}-${hue}-500, or a role such as ${fam}-${v.roles[0] ?? 'neutral'}`,\n };\n if (!v.steps.includes(step))\n return {\n cls: raw,\n severity: 'error' as const,\n reason: `\\`${step}\\` is not a step on the \\`${hue}\\` scale (steps are 50…950)`,\n suggestion: `${fam}-${hue}-500, or a role such as ${fam}-${v.roles[0] ?? 'neutral'} which also flips in dark mode`,\n };\n return null; // valid raw step\n }\n return null; // not anchored to this config — not ours to judge\n }\n\n // ── font-<type-role> ───────────────────────────────────────────────────────\n const font = /^font-(.+)$/.exec(base);\n if (font && v.typeRoles.length && !v.typeRoles.includes(font[1] as string)) {\n const near = nearest(font[1] as string, v.typeRoles);\n // Only complain when it looks like a type role attempt, not e.g. font-bold.\n if (near)\n return {\n cls: raw,\n severity: 'error' as const,\n reason: `\\`${font[1]}\\` is not a typography role`,\n suggestion: `font-${near}`,\n };\n }\n\n // ── drop-shadow-<name> ─────────────────────────────────────────────────────\n const ds = /^drop-shadow-(.+)$/.exec(base);\n if (ds && v.shadows.length && !v.shadows.includes(ds[1] as string))\n return {\n cls: raw,\n severity: 'error' as const,\n reason: `\\`${ds[1]}\\` is not a defined shadow`,\n suggestion: `drop-shadow-${v.shadows[0]}`,\n };\n\n return null;\n}\n\nconst CLASS_ATTR = /(?:class|className|:class)\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)'|\\{`([^`]*)`\\})/g;\n\n/** Extract class tokens from a source file, with line numbers. */\nexport function extractClasses(src: string): { cls: string; line: number }[] {\n const out: { cls: string; line: number }[] = [];\n for (const m of src.matchAll(CLASS_ATTR)) {\n const value = m[1] ?? m[2] ?? m[3] ?? '';\n const line = src.slice(0, m.index).split('\\n').length;\n for (const tok of value.split(/\\s+/))\n // Skip template holes and dynamic fragments — a partial token would be\n // judged as a typo and this must not cry wolf.\n if (tok && !tok.includes('${') && !tok.includes('{') && /^[@\\w:[\\]().%/-]+$/.test(tok))\n out.push({ cls: tok, line });\n }\n return out;\n}\n\nexport function lintSource(\n files: { path: string; text: string }[],\n v: Vocabulary,\n format: Format,\n): LintFinding[] {\n const findings: LintFinding[] = [];\n const seen = new Set<string>();\n for (const f of files)\n for (const { cls, line } of extractClasses(f.text)) {\n const verdict = judge(cls, v, format);\n if (!verdict) continue;\n const key = `${f.path}:${line}:${cls}`;\n if (seen.has(key)) continue;\n seen.add(key);\n findings.push({ file: f.path, line, ...verdict });\n }\n return findings;\n}\n","#!/usr/bin/env node\n/**\n * `vitops` — CLI for the Vitops design-system generator.\n *\n * vitops generate --input <json> --format <bricks|css|tailwind|design[,…]> --out <dir>\n * vitops init [--out design-system.json] [--force]\n * vitops validate <design-system.json|site.json>\n * vitops favicon --input <svg|png> --out <dir> [--low-res <svg|png>] [--background <hex>]\n * vitops agents [--input <json>] [--out AGENTS.md] [--docs-dir <dir>]\n * vitops docs [topic] [--input <json>] [--all]\n * vitops lint [--input <json>] [--format <fmt>] [--src <dir>]\n * vitops legal [--input <site.json>] [--doc <name>] [--format <md|html|portable-text>] [--out <dir>]\n * vitops search setup [--domain <name>] [--dry] [--check] | notify [--dry] [--all] [--check]\n * vitops media [--raw <dir>] [--out <dir>] [--force] [--dry]\n *\n * Thin wrapper over @getvitops/generator (generation) and @getvitops/utils (favicons).\n * Every client brings their own consumer-editable design-system.json.\n */\nimport { parseArgs } from 'node:util';\nimport { writeFileSync, existsSync, readFileSync, mkdirSync } from 'node:fs';\nimport { resolve, join, dirname, relative } from 'node:path';\nimport { createRequire } from 'node:module';\nimport { pathToFileURL } from 'node:url';\nimport {\n buildIconSprite,\n generate,\n validate,\n defaultConfig,\n generateDocs,\n generateLegal,\n enabledDocs,\n isConfig,\n resolveInput,\n resolveConfig,\n resolveTheme,\n roleColorUtilities,\n functionalRole,\n expandPalette,\n roleHue,\n roleKind,\n SCHEMA_URL,\n type Format,\n type StylesheetFormat,\n type DesignSystem,\n type LegalDoc,\n type LegalOutput,\n type ResolvedInput,\n type Config,\n} from '@getvitops/generator';\nimport {\n collectIconRefs,\n generateFavicons,\n generateIconInclude,\n resolveIcon,\n scanFiles,\n} from '@getvitops/utils';\n// Its own subpath: `indexing` is the only network-touching module in utils, and the\n// other commands should not pull it in.\nimport {\n SNAPSHOT_PATH,\n collectEntries,\n formatPlan,\n SCOPES,\n googleAccessToken,\n inspectUrl,\n keyFileContents,\n newKey,\n parseServiceAccount,\n plan,\n readSnapshot,\n resolveKeyLocation,\n resolveSitemapUrl,\n submitBatch,\n submitSitemap,\n toSnapshot,\n verifyKeyFile,\n writeSnapshot,\n type GoogleCredential,\n type IndexingConfig,\n type ServiceAccount,\n} from '@getvitops/utils/indexing';\n// Its own subpath for the same reason: `onboarding` is network-touching (Cloudflare\n// DNS + Google). `formatPlan`/`plan` are aliased — indexing exports the same names.\nimport {\n addSite,\n backoffSchedule,\n createApexTxt,\n findZoneId,\n formatPlan as formatSetupPlan,\n formatSummary,\n refreshTokenGrant,\n getSite,\n getVerificationToken,\n getWebResource,\n hasDrift,\n listApexTxt,\n ownerUnion,\n plan as planSetup,\n siteUrlFor,\n updateOwners,\n verifyWebResource,\n type DomainResult,\n type DomainSetup,\n type DomainState,\n type GoogleOAuth,\n} from '@getvitops/utils/onboarding';\n// Its own subpath for the same reason: `media` shells out to ffmpeg, and no other\n// command should carry it. `formatPlan` is aliased — indexing exports one too.\nimport {\n MEDIA_MANIFEST_PATH,\n formatPlan as formatMediaPlan,\n processMedia,\n type MediaConfig,\n type OutputKind,\n} from '@getvitops/utils/media';\nimport { findSkillTarget, linkSkill, SKILL_NAME, TOPICS } from './agents.ts';\nimport { lintCss } from './lint-css.ts';\nimport { lintSource, vocabulary } from './lint.ts';\n\nconst FORMATS = new Set<Format>(['bricks', 'css', 'tailwind', 'design']);\n// `lint` judges class names against what a build emits, and the `design` format\n// emits no CSS at all — so it is a valid target for `generate` and a category\n// error for `lint`.\nconst LINT_FORMATS = new Set<StylesheetFormat>(['bricks', 'css', 'tailwind']);\n\n// `legal` reads a *site* config, not a design-system.json, and has its own\n// output set — it renders documents, not stylesheets.\nconst LEGAL_DOCS = new Set<LegalDoc>(['privacy', 'terms', 'cookies']);\nconst LEGAL_OUTPUTS = new Set<LegalOutput>(['md', 'html', 'portable-text']);\n\nconst HELP = `vitops — generate design-system outputs from a design-system.json\n\nAnywhere a command takes --input, that file may be a design-system.json OR the\nlarger site config that embeds one (company.json / site.json). The two are told\napart by shape, and a site config also supplies the site-level facts generation\nreads — its default colour scheme, its legal documents, its icon sprite.\n\nUsage:\n vitops generate [options] Generate platform output from a config\n vitops init [options] Scaffold a starter design-system.json\n vitops validate <file> Validate a config against the schema it says it is\n vitops favicon [options] Generate a favicon set from a source image\n vitops agents [options] Link the design-system agent skill + AGENTS.md pointer\n vitops docs [topic] Print live design-system reference docs to stdout\n vitops lint [options] Report framework classes in your source that resolve to nothing\n vitops legal [options] Render legal documents from a site config\n vitops icons [options] Report which icons your source uses, and build the sprite\n vitops search <sub> [opts] Search Console: onboard domains (setup) + notify deploys (notify)\n vitops media [options] Encode raw video into web-ready WebM + MP4 + poster\n\nGenerate options:\n -i, --input <path> design-system.json or site config (default: ./design-system.json)\n -f, --format <list> bricks | css | tailwind | design (comma-separated; default: bricks)\n design emits DESIGN.md only (the agent-facing brief) — pair it\n with --out . to write it beside AGENTS.md, or compose:\n --format css,design\n -o, --out <dir> Output directory (default: ./dist)\n --theme <name> Which designSystem.themes entry to build, when --input is\n a site config (default: its defaultTheme, else \"default\")\n --site <path> Site config, when it is a different file from --input.\n Emits legal/*.html into the output directory (see:\n vitops legal). Omitted with a plain design-system.json:\n no legal files.\n --site-env <env> Environment whose A/B variant applies (default: production)\n\nInit options:\n -o, --out <path> Where to write (default: ./design-system.json)\n --force Overwrite an existing file\n\nFavicon options:\n -i, --input <path> Source SVG or PNG (required)\n -o, --out <dir> Output directory (default: ./public)\n --low-res <path> Optional simplified source for the 16px icon\n --background <hex> Background under the maskable icons, which must be\n opaque (default: #ffffff)\n\nAgents options:\n -i, --input <path> design-system.json or site config (default: ./design-system.json;\n validated if present)\n --theme <name> Theme to read, when --input is a site config\n -o, --out <path> Doc file to update, idempotently (default: ./AGENTS.md)\n --docs-dir <dir> Legacy layout: write the docs bundle as files to this dir\n instead of linking the packaged skill\n\nDocs options:\n <topic> classes | authoring | formats | color | scales | patterns | elements\n (no topic: list topics with summaries)\n -i, --input <path> design-system.json or site config (default: ./design-system.json)\n --theme <name> Theme to render docs from, when --input is a site config\n --all Print every topic, concatenated\n\nIcons options:\n --site <path> Site config carrying the \"icons\" block (default: ./site.json)\n --src <dir> Source to scan for icon usage (default: ./src)\n --sprite Also build the SVG sprite\n -o, --out <dir> Where to write icons.svg with --sprite (default: ./dist)\n --json Machine-readable report on stdout\n\nLint options:\n -i, --input <path> design-system.json or site config (default: ./design-system.json)\n --theme <name> Theme to judge classes against, when --input is a site config\n -f, --format <fmt> Format you build (bricks | css | tailwind; default: bricks).\n Responsive md-* classes are real in css/bricks, inert in tailwind.\n -s, --src <dir> Directory to scan (default: ./src)\n --strict Also fail on suggestions (reuse hints), not just on\n classes that resolve to nothing\n\nLegal options:\n -i, --input <path> Site config: .json, or a .js/.ts module with a default\n export (default: ./site.json)\n -d, --doc <name> privacy | terms | cookies (repeatable; default: those\n enabled in the config)\n -f, --format <fmt> md | html | portable-text (default: md)\n html suits WordPress/Bricks and plain sites;\n portable-text suits EmDash\n -o, --out <dir> Write files here (default: print to stdout)\n --site-env <env> Environment whose A/B variant applies (default: production)\n\n Generated from your config — a starting point, not legal advice. Review before\n publishing, and make sure the config describes what your site actually does.\n\nSearch subcommands:\n vitops search setup [opts] Onboard site.searchConsole domains into GSC\n vitops search notify [opts] Tell search engines about a deploy (sitemap + IndexNow)\n\nSearch setup options:\n -i, --input <path> Site config carrying site.searchConsole (default: ./site.json)\n --site-env <env> Environment whose A/B variant applies (default: production)\n --domain <name> Scope to a single site.searchConsole entry\n --dry Print the plan and exit. Changes nothing.\n --check Report drift and exit non-zero if any domain is not fully\n onboarded. Mutates nothing.\n\n For each domain it ensures the apex verification TXT in Cloudflare, verifies\n ownership (DNS_TXT, retried with backoff while DNS propagates — a still-\n unverified domain is reported PENDING, not failed), adds the sc-domain: property,\n and adds any delegatedOwners to the web resource. DNS is only ever created,\n never edited or deleted. Credentials come from the environment:\n CLOUDFLARE_API_TOKEN (Zone:DNS:Edit), and VITOPS_GOOGLE_CLIENT_ID /\n VITOPS_GOOGLE_CLIENT_SECRET / VITOPS_GOOGLE_REFRESH_TOKEN (a user OAuth token\n scoped to siteverification + webmasters). Granting a Google Group Full-User\n access has no API and is surfaced as a reminder.\n\nSearch notify options:\n -i, --input <path> Site config carrying seo.indexing (default: ./site.json)\n --site-env <env> Environment to notify for (default: production). An\n environment whose robots policy says noindex is refused.\n --sitemap <src> Sitemap URL or local path (default: from the config)\n --urls <list> Comma-separated URLs to submit, skipping the diff\n --all Submit every URL in the sitemap, not just what changed\n --dry Print the plan and exit. Makes no requests.\n --check Read-only: ask Google whether seo.indexing.priorityUrls\n are indexed. Exits non-zero if one is not.\n --new-key Print a fresh IndexNow key and exit\n --write-key <dir> Write the IndexNow key file into <dir> (for stacks with\n no Astro integration to do it — Bricks, WordPress)\n --snapshot <path> Changed-URL state file (default: .vitops/sitemap-snapshot.json).\n Persist it between runs (a CI cache) or every run submits\n everything.\n\n What notify can and cannot do: Google exposes no \"request indexing\" API, and its\n sitemap ping endpoint was removed in 2023 — so it resubmits your sitemap\n through the Search Console API and verifies the result with --check. IndexNow\n reaches Bing, Yandex, Naver, Seznam and Yep; Google does not participate.\n Search Console takes either credential, whichever you already have, added as an\n owner of the property: a service account in VITOPS_GSC_SERVICE_ACCOUNT (inline\n JSON) or GOOGLE_APPLICATION_CREDENTIALS (a path), or the same user OAuth\n credential \"search setup\" uses (VITOPS_GOOGLE_CLIENT_ID / _CLIENT_SECRET /\n _REFRESH_TOKEN). The service account is preferred when both are set — this runs\n on every deploy, and it does not expire.\n\nMedia options:\n --raw <dir> Directory of unprocessed video, walked recursively\n (default: ./raw)\n -o, --out <dir> Where the encoded outputs go (default: ./src/assets/processed).\n Subdirectories under --raw are preserved.\n --max-width <px> Cap the output width, keeping aspect ratio (default: 1920;\n 0 disables scaling)\n --crf <n> Quality on VP9's scale, 0-63, lower is better (default: 32).\n The MP4 fallback uses the equivalent on H.264's scale.\n --max-bitrate <r> Optional ceiling, e.g. 2M or 800k (default: none, which is\n constant quality rather than constrained)\n --audio Keep the audio track (default: dropped — the common case is\n a muted autoplay loop)\n --poster-time <s> Timestamp the poster frame is taken from (default: 0, which\n is often black on a clip that fades in)\n --outputs <list> Comma-separated: webm | mp4 | poster (default: all three)\n --manifest <path> Cache file (default: .vitops/media-manifest.json)\n --force Re-encode everything, ignoring the cache\n --dry Print the plan and exit. Encodes nothing.\n\n Needs ffmpeg on PATH — it is an external tool, not an npm dependency, and this\n command fails rather than quietly skipping. Commit the outputs and the manifest:\n ffmpeg output is not reproducible across versions, so re-encoding in CI churns\n the diff on every toolchain bump. Use --force when you mean to re-encode.\n\nCommon:\n -h, --help Show this help\n`;\n\nconst SEARCH_HELP = `vitops search — Google Search Console\n\n vitops search setup [opts] Onboard site.searchConsole domains as GSC domain properties\n vitops search notify [opts] Tell search engines a deploy happened (sitemap + IndexNow)\n\nRun \\`vitops --help\\` for the full option list for each subcommand.\n`;\n\nfunction fail(msg: string): never {\n console.error(`✖ ${msg}`);\n process.exit(1);\n}\n\nasync function cmdGenerate(argv: string[]) {\n const { values } = parseArgs({\n args: argv,\n options: {\n input: { type: 'string', short: 'i', default: 'design-system.json' },\n format: { type: 'string', short: 'f', default: 'bricks' },\n out: { type: 'string', short: 'o', default: 'dist' },\n site: { type: 'string' },\n theme: { type: 'string' },\n 'site-env': { type: 'string' },\n },\n allowPositionals: false,\n });\n const input = resolve(values.input as string);\n if (!existsSync(input)) fail(`config not found: ${input}`);\n const site = values.site ? resolve(values.site as string) : undefined;\n if (site && !existsSync(site)) fail(`site config not found: ${site}`);\n const formats = (values.format as string)\n .split(',')\n .map((f) => f.trim())\n .filter(Boolean);\n for (const f of formats)\n if (!FORMATS.has(f as Format))\n fail(`unknown format \"${f}\" (expected: bricks | css | tailwind | design)`);\n\n for (const format of formats as Format[]) {\n try {\n const res = await generate({\n input,\n format,\n outDir: values.out as string,\n ...(site ? { site } : {}),\n ...(values.theme ? { theme: values.theme as string } : {}),\n ...(values['site-env'] ? { siteEnv: values['site-env'] as string } : {}),\n });\n console.log(`✓ ${format} → ${res.outDir} (${res.written.length} paths)`);\n } catch (err) {\n fail((err as Error).message);\n }\n }\n}\n\nfunction cmdInit(argv: string[]) {\n const { values } = parseArgs({\n args: argv,\n options: {\n out: { type: 'string', short: 'o', default: 'design-system.json' },\n force: { type: 'boolean', default: false },\n },\n allowPositionals: false,\n });\n const out = resolve(values.out as string);\n if (existsSync(out) && !values.force) fail(`${out} already exists (use --force to overwrite)`);\n writeFileSync(out, JSON.stringify(defaultConfig(), null, 2) + '\\n');\n console.log(`✓ wrote ${out}`);\n console.log(\n ` Edit it, then: vitops generate --input ${values.out} --format tailwind --out src/styles`,\n );\n console.log(` Editors read the \"$schema\" (${SCHEMA_URL}) for autocomplete + validation.`);\n}\n\n/**\n * Validate a config against the schema its shape says it is.\n *\n * Routing on kind rather than asking the caller matters here: pointed at a site\n * config, the design-system schema used to report a single `unrecognized_keys`\n * for `designSystem` and nothing about the file's actual contents — a wrong\n * answer that reads like a right one. A site config is validated whole, which\n * also covers the cross-field integrity JSON Schema can't express.\n */\nfunction cmdValidate(argv: string[]) {\n const { values, positionals } = parseArgs({\n args: argv,\n options: { input: { type: 'string', short: 'i' }, 'site-env': { type: 'string' } },\n allowPositionals: true,\n });\n const path = resolve((positionals[0] ?? values.input ?? 'design-system.json') as string);\n if (!existsSync(path)) fail(`config not found: ${path}`);\n let raw: unknown;\n try {\n raw = JSON.parse(readFileSync(path, 'utf8'));\n } catch (err) {\n fail(`could not parse JSON: ${(err as Error).message}`);\n }\n\n if (isConfig(raw)) {\n let site: Config;\n try {\n site = resolveConfig(raw, values['site-env'] as string | undefined);\n } catch (err) {\n // Already formatted as one issue per line, with field paths.\n console.error(`✖ ${path} is invalid as a site config:`);\n console.error((err as Error).message.replace(/^Invalid site config:\\n/, ''));\n process.exit(1);\n }\n // Each theme is validated in turn: `validateConfig` checks the `extends` chain\n // resolves, not that what it resolves to is a complete design system, so a\n // theme could pass there and still fail to build.\n const themes = (site.designSystem?.themes ?? {}) as Parameters<typeof resolveTheme>[0];\n let bad = false;\n for (const name of Object.keys(themes)) {\n const result = validate(resolveTheme(themes, name));\n for (const w of result.warnings) console.warn(` ! designSystem.themes.${name}: ${w}`);\n if (result.ok) continue;\n bad = true;\n console.error(`✖ ${path} — designSystem.themes.${name} is not a complete design system:`);\n for (const e of result.errors)\n console.error(` • ${e.path.join('.') || '(root)'}: ${e.message}`);\n }\n if (bad) process.exit(1);\n const n = Object.keys(themes).length;\n console.log(`✓ ${path} is a valid site config (${n} theme${n === 1 ? '' : 's'})`);\n return;\n }\n\n const result = validate(raw);\n for (const w of result.warnings) console.warn(` ! ${w}`);\n if (result.ok) {\n console.log(`✓ ${path} is valid`);\n return;\n }\n console.error(`✖ ${path} is invalid:`);\n for (const e of result.errors) console.error(` • ${e.path.join('.') || '(root)'}: ${e.message}`);\n process.exit(1);\n}\n\nasync function cmdFavicon(argv: string[]) {\n const { values } = parseArgs({\n args: argv,\n options: {\n input: { type: 'string', short: 'i' },\n out: { type: 'string', short: 'o', default: 'public' },\n 'low-res': { type: 'string' },\n // The maskable outputs must be opaque — the OS crops them to its own shape,\n // so transparency there becomes a black frame, not \"no background\".\n background: { type: 'string' },\n },\n allowPositionals: false,\n });\n if (!values.input) fail('favicon: --input <svg|png> is required');\n const source = resolve(values.input as string);\n if (!existsSync(source)) fail(`source not found: ${source}`);\n try {\n const written = await generateFavicons({\n source,\n outputDir: values.out as string,\n ...(values['low-res'] ? { lowResSource: resolve(values['low-res'] as string) } : {}),\n ...(values.background ? { backgroundColor: values.background as string } : {}),\n });\n console.log(`✓ favicons → ${values.out} (${written.length} files)`);\n } catch (err) {\n fail((err as Error).message);\n }\n}\n\nconst OUTPUT_KINDS = new Set<OutputKind>(['webm', 'mp4', 'poster']);\n\n/**\n * `vitops media` — encode a directory of raw video into web-ready outputs.\n *\n * Flags only, with no config file, following `favicon`: `site.favicon` exists in\n * the schema and `cmdFavicon` still doesn't read it. The same reasoning applies\n * more strongly here — `legal`, `icons` and `indexing` are anchored to a\n * `Config` because what they emit *describes the site*, and an encoder setting\n * describes a build step.\n */\nasync function cmdMedia(argv: string[]) {\n const { values } = parseArgs({\n args: argv,\n options: {\n raw: { type: 'string', default: 'raw' },\n out: { type: 'string', short: 'o', default: 'src/assets/processed' },\n 'max-width': { type: 'string' },\n crf: { type: 'string' },\n 'max-bitrate': { type: 'string' },\n audio: { type: 'boolean', default: false },\n 'poster-time': { type: 'string' },\n outputs: { type: 'string' },\n manifest: { type: 'string', default: MEDIA_MANIFEST_PATH },\n force: { type: 'boolean', default: false },\n dry: { type: 'boolean', default: false },\n },\n allowPositionals: false,\n });\n\n // Parsed here rather than passed through as strings, so a typo is caught before\n // ffmpeg spends minutes encoding at a quality nobody asked for.\n const num = (flag: string, raw: string | undefined): number | undefined => {\n if (raw === undefined) return undefined;\n const n = Number(raw);\n if (!Number.isFinite(n) || n < 0) fail(`media: --${flag} must be a non-negative number`);\n return n;\n };\n\n let outputs: OutputKind[] | undefined;\n if (values.outputs) {\n outputs = (values.outputs as string).split(',').map((s) => s.trim()) as OutputKind[];\n for (const kind of outputs)\n if (!OUTPUT_KINDS.has(kind))\n fail(`media: unknown output \"${kind}\" (expected: webm | mp4 | poster)`);\n }\n\n const maxWidth = num('max-width', values['max-width'] as string | undefined);\n const crf = num('crf', values.crf as string | undefined);\n const posterTime = num('poster-time', values['poster-time'] as string | undefined);\n\n const config: MediaConfig = {\n ...(maxWidth !== undefined ? { maxWidth } : {}),\n ...(crf !== undefined ? { crf } : {}),\n ...(values['max-bitrate'] ? { maxBitrate: values['max-bitrate'] as string } : {}),\n ...(values.audio ? { audio: true } : {}),\n ...(posterTime !== undefined ? { posterTime } : {}),\n ...(outputs ? { outputs } : {}),\n };\n\n try {\n const result = await processMedia({\n raw: values.raw as string,\n out: values.out as string,\n config,\n manifest: values.manifest as string,\n force: values.force as boolean,\n dry: values.dry as boolean,\n // An encode is minutes of silence otherwise, which reads as a hang.\n onProgress: (message) => console.error(` … ${message}`),\n });\n\n if (values.dry) {\n console.log(formatMediaPlan(result.plan));\n return;\n }\n console.log(\n `✓ media → ${values.out} (${result.written.length} written, ${result.skipped} unchanged)`,\n );\n for (const note of result.plan.notes) console.error(` ! ${note}`);\n } catch (err) {\n fail((err as Error).message);\n }\n}\n\n/**\n * Read + parse + validate the design system at `path`, or exit with a message.\n *\n * `path` may be a `design-system.json` **or** the larger site config that embeds\n * one — every command that judges source against the design system (`docs`,\n * `lint`, `agents`) accepts either, so a consumer who keeps their tokens in\n * `company.json` doesn't have to maintain a second file for the tooling's sake.\n * `resolveInput` tells them apart by shape and resolves the theme.\n */\nfunction loadDesignSystem(path: string, theme?: string): DesignSystem {\n if (!existsSync(path)) fail(`config not found: ${path}`);\n let raw: unknown;\n try {\n raw = JSON.parse(readFileSync(path, 'utf8'));\n } catch (err) {\n fail(`could not parse JSON: ${(err as Error).message}`);\n }\n let resolved: ResolvedInput;\n try {\n resolved = resolveInput(raw, theme != null ? { theme } : {});\n } catch (err) {\n // resolveConfig formats one issue per line; a bad --theme is one line.\n fail(`${path}: ${(err as Error).message}`);\n }\n const result = validate(resolved.designSystem);\n if (!result.ok) {\n const where = resolved.theme != null ? ` (designSystem.themes.${resolved.theme})` : '';\n console.error(`✖ ${path}${where} is invalid:`);\n for (const e of result.errors)\n console.error(` • ${e.path.join('.') || '(root)'}: ${e.message}`);\n process.exit(1);\n }\n // Warnings go to stderr, not stdout: `vitops docs <topic>` is designed to be\n // piped, so anything here must not land in the piped document. They used to\n // be dropped entirely on this path, which meant `docs` and `agents` stayed\n // silent about collisions that `generate` and `validate` both reported.\n for (const w of result.warnings) console.warn(` ! ${w}`);\n return result.data;\n}\n\n/**\n * Read + resolve a site config, or exit with a message.\n *\n * Accepts JSON, or a JS/TS module with a default export — deliberately not YAML,\n * which would mean a parser dependency for one command. `resolveConfig` is\n * documented as taking an already-parsed object precisely so the loader is the\n * consumer's choice; anyone on YAML can convert it or export from a module.\n */\nasync function loadConfig(path: string, siteEnv: string): Promise<Config> {\n if (!existsSync(path)) fail(`site config not found: ${path}`);\n let raw: unknown;\n if (/\\.(json)$/.test(path)) {\n try {\n raw = JSON.parse(readFileSync(path, 'utf8'));\n } catch (err) {\n fail(`could not parse JSON: ${(err as Error).message}`);\n }\n } else {\n try {\n raw = (await import(pathToFileURL(path).href)).default;\n } catch (err) {\n fail(`could not import ${path}: ${(err as Error).message}`);\n }\n if (raw == null) fail(`${path} has no default export`);\n }\n try {\n return resolveConfig(raw, siteEnv);\n } catch (err) {\n // resolveConfig already formats one issue per line.\n fail((err as Error).message);\n }\n}\n\n/**\n * Render the site's legal documents.\n *\n * The universal delivery path: every consumer has this CLI regardless of stack,\n * so a WordPress theme, an Eleventy build or a hand-written HTML site all get\n * the same documents without any integration code. Prints to stdout like\n * `vitops docs`, or writes files when given `--out`.\n */\n/**\n * Report the icon vocabulary a project actually uses, and optionally build the\n * sprite from it.\n *\n * A sibling of `legal` rather than a widening of `lint`: `lint` judges classes\n * against a design-system.json, whereas icons are anchored to a Config.\n *\n * Exit codes carry the same distinction the Astro integration makes. A name the\n * config DECLARES but that doesn't resolve is a config error and fails the\n * command; a name only the SCAN found is reported and tolerated, because a bare\n * unmapped name is more often a local src/icons/*.svg than a mistake. Runtime-\n * computed names are listed with file and line so they can be declared, never\n * guessed at.\n */\nasync function cmdIcons(argv: string[]) {\n const { values } = parseArgs({\n args: argv,\n options: {\n site: { type: 'string', default: 'site.json' },\n src: { type: 'string', default: 'src' },\n sprite: { type: 'boolean', default: false },\n out: { type: 'string', short: 'o', default: 'dist' },\n json: { type: 'boolean', default: false },\n 'site-env': { type: 'string', default: 'production' },\n },\n allowPositionals: false,\n });\n\n const sitePath = resolve(values.site as string);\n const icons = existsSync(sitePath)\n ? (((await loadConfig(sitePath, values['site-env'] as string)).site.icons ?? {}) as Record<\n string,\n unknown\n >)\n : {};\n const ui = (icons.ui as string) ?? 'fa7-solid';\n const brand = (icons.brand as string) ?? 'simple-icons';\n const weight = icons.weight as string | undefined;\n const weightOpt = weight ? { weight } : {};\n\n // Declared first — this throws on an unresolvable name, by design.\n let include: Record<string, string[]> = {};\n try {\n include = generateIconInclude({ ...(icons as object) } as Parameters<\n typeof generateIconInclude\n >[0]);\n } catch (e) {\n fail((e as Error).message);\n }\n const add = (prefix: string, name: string) => {\n const list = (include[prefix] ??= []);\n if (!list.includes(name)) list.push(name);\n };\n\n const srcDir = resolve(values.src as string);\n const scanned = existsSync(srcDir) ? collectIconRefs(scanFiles(srcDir)) : null;\n const unmapped: string[] = [];\n for (const name of scanned?.names ?? []) {\n const colon = name.indexOf(':');\n if (colon > 0) {\n add(name.slice(0, colon), name.slice(colon + 1));\n continue;\n }\n try {\n const q = resolveIcon(name, ui, weightOpt);\n add(q.slice(0, q.indexOf(':')), q.slice(q.indexOf(':') + 1));\n } catch {\n unmapped.push(name);\n }\n }\n\n const dynamic = (scanned?.dynamic ?? []).map((d) => ({\n file: relative(process.cwd(), d.file),\n line: d.line,\n expr: d.expr,\n }));\n const total = Object.values(include).flat().length;\n\n let sprite: { ids: string[]; missing: string[] } | null = null;\n if (values.sprite) {\n const aliases: Record<string, string> = {};\n for (const name of (icons.semantic as string[]) ?? []) {\n try {\n aliases[`icon-${name}`] = resolveIcon(name, ui, weightOpt);\n } catch {\n /* already reported by generateIconInclude above */\n }\n }\n const built = await buildIconSprite({ include, aliases });\n const outDir = resolve(values.out as string);\n mkdirSync(outDir, { recursive: true });\n writeFileSync(join(outDir, 'icons.svg'), built.svg);\n sprite = { ids: built.ids, missing: built.missing };\n }\n\n if (values.json) {\n process.stdout.write(\n `${JSON.stringify({ ui, brand, weight: weight ?? null, include, unmapped, dynamic, sprite }, null, 2)}\\n`,\n );\n } else {\n console.log(`icon sets: ui=${ui} brand=${brand}${weight ? ` weight=${weight}` : ''}`);\n for (const [prefix, names] of Object.entries(include))\n console.log(` ${prefix}: ${names.length} — ${names.join(', ')}`);\n console.log(`✓ ${total} icon(s) across ${Object.keys(include).length} set(s)`);\n if (sprite)\n console.log(\n `✓ sprite → ${resolve(values.out as string)}/icons.svg (${sprite.ids.length} symbols)`,\n );\n for (const d of dynamic)\n console.log(` ! ${d.file}:${d.line} ${d.expr} — computed at runtime, declare it in icons`);\n if (unmapped.length)\n console.log(\n ` ! not in the '${ui}' map: ${unmapped.join(', ')} (fine for a local svg or sprite id)`,\n );\n if (sprite?.missing.length)\n console.log(` ! absent from the sprite: ${sprite.missing.join(', ')}`);\n }\n\n // Dynamic holes and unmapped bare names are warnings, not failures — same\n // tolerance `lint` shows template holes, but visible rather than silent.\n if (sprite?.missing.length) process.exitCode = 1;\n}\n\nasync function cmdLegal(argv: string[]) {\n const { values } = parseArgs({\n args: argv,\n options: {\n input: { type: 'string', short: 'i', default: 'site.json' },\n doc: { type: 'string', short: 'd', multiple: true },\n format: { type: 'string', short: 'f', default: 'md' },\n out: { type: 'string', short: 'o' },\n 'site-env': { type: 'string', default: 'production' },\n },\n allowPositionals: false,\n });\n\n const output = values.format as LegalOutput;\n if (!LEGAL_OUTPUTS.has(output))\n fail(`unknown format \"${output}\" (expected: ${[...LEGAL_OUTPUTS].join(' | ')})`);\n\n const requested = (values.doc ?? []) as string[];\n for (const d of requested)\n if (!LEGAL_DOCS.has(d as LegalDoc))\n fail(`unknown doc \"${d}\" (expected: ${[...LEGAL_DOCS].join(' | ')})`);\n\n const site = await loadConfig(resolve(values.input as string), values['site-env'] as string);\n const docs = requested.length ? (requested as LegalDoc[]) : enabledDocs(site);\n if (docs.length === 0)\n fail(\n 'no legal documents are enabled — set site.legal.privacyPolicy.enabled (or termsOfService / cookieConsent) in your config, or name one with --doc',\n );\n\n const files = generateLegal(site, { docs, output });\n\n if (!values.out) {\n process.stdout.write(Object.values(files).join('\\n'));\n return;\n }\n const outDir = resolve(values.out as string);\n mkdirSync(outDir, { recursive: true });\n for (const [name, content] of Object.entries(files)) writeFileSync(join(outDir, name), content);\n console.log(`✓ legal → ${outDir} (${Object.keys(files).length} files)`);\n console.log(\n ' These are generated from your config and are not legal advice — review them before publishing.',\n );\n}\n\n/**\n * Adapt a `Config` to the indexing module's own option shape.\n *\n * A flat field map, as intended: `@getvitops/utils` cannot import from the\n * generator (the generator already depends on it), so `IndexingConfig` mirrors the\n * `seo.indexing` block rather than being it. The one piece of judgment here is the\n * origin — see below.\n */\nfunction toIndexingConfig(cfg: Config, siteEnv: string): IndexingConfig {\n const site = cfg.site;\n const indexing = site.seo?.indexing ?? {};\n const env = site.environments?.[siteEnv];\n /*\n * The environment's own URL wins over `domains.canonical`.\n *\n * `domains.canonical` is the production origin — it is what absolute URLs and\n * SEO tags resolve against. Notifying a non-production environment while\n * deriving URLs from the canonical origin would submit *production* URLs under\n * the belief they were staging's, which the noindex gate below would then not\n * catch, because the gate reads the environment and the URLs would not.\n */\n const canonical = env?.url ?? site.domains?.canonical;\n return {\n ...(canonical ? { canonical } : {}),\n ...(indexing.sitemapUrl ? { sitemapUrl: indexing.sitemapUrl } : {}),\n ...(indexing.indexNow ? { indexNow: indexing.indexNow } : {}),\n ...(indexing.searchConsole ? { searchConsole: indexing.searchConsole } : {}),\n ...(indexing.priorityUrls ? { priorityUrls: indexing.priorityUrls } : {}),\n // Fall back to the site-wide policy so a site that states `noindex` once,\n // globally, is still protected.\n ...((env?.robots ?? site.seo?.robots) ? { robots: env?.robots ?? site.seo?.robots } : {}),\n };\n}\n\n/**\n * The Search Console credential, from either supported source.\n *\n * Never from the config file: it is the one genuine secret in this command, and a\n * `site.json` is committed. Returns `undefined` rather than failing, so a site\n * running IndexNow alone doesn't need a GCP project at all.\n */\nfunction loadServiceAccount(): ServiceAccount | undefined {\n const inline = process.env.VITOPS_GSC_SERVICE_ACCOUNT;\n const path = process.env.GOOGLE_APPLICATION_CREDENTIALS;\n const raw = inline ?? (path && existsSync(path) ? readFileSync(path, 'utf8') : undefined);\n if (!raw) return undefined;\n try {\n return parseServiceAccount(raw);\n } catch (err) {\n fail(\n `${inline ? 'VITOPS_GSC_SERVICE_ACCOUNT' : `GOOGLE_APPLICATION_CREDENTIALS (${path})`}: ${(err as Error).message}`,\n );\n }\n}\n\n/** Read a sitemap from a URL or a local path. */\nconst readSitemap = async (source: string): Promise<string> => {\n if (/^https?:\\/\\//i.test(source)) {\n const res = await fetch(source);\n if (!res.ok) fail(`could not fetch ${source}: ${res.status}`);\n return res.text();\n }\n if (!existsSync(source)) fail(`sitemap not found: ${source}`);\n return readFileSync(source, 'utf8');\n};\n\n/**\n * Tell search engines a deploy happened.\n *\n * Worth being precise about what this is, because the obvious expectation is\n * wrong: **Google has no API that requests indexing.** The Search Console button\n * is not exposed anywhere, URL Inspection is read-only, and the sitemap ping\n * endpoint was removed in 2023. So the Google half of this command resubmits the\n * sitemap and then *verifies* the outcome with `--check`; the immediate-push half\n * is IndexNow, which Google does not participate in.\n *\n * The Indexing API is deliberately absent — see `@getvitops/utils/indexing`'s\n * `gsc.ts`.\n */\nasync function cmdSearchNotify(argv: string[]) {\n const { values } = parseArgs({\n args: argv,\n options: {\n input: { type: 'string', short: 'i', default: 'site.json' },\n 'site-env': { type: 'string', default: 'production' },\n sitemap: { type: 'string' },\n urls: { type: 'string' },\n all: { type: 'boolean', default: false },\n dry: { type: 'boolean', default: false },\n check: { type: 'boolean', default: false },\n 'new-key': { type: 'boolean', default: false },\n 'write-key': { type: 'string' },\n snapshot: { type: 'string', default: SNAPSHOT_PATH },\n },\n allowPositionals: false,\n });\n\n // Stands alone: generating a key is what you do *before* there is a config to\n // put it in.\n if (values['new-key']) {\n const key = newKey();\n console.log(key);\n console.log(\n `\\n Add to your site config:\\n \"seo\": { \"indexing\": { \"indexNow\": { \"key\": \"${key}\" } } }`,\n );\n console.log(` Then serve it at /${key}.txt — \\`vitops search notify --write-key public\\`.`);\n return;\n }\n\n const site = await loadConfig(resolve(values.input as string), values['site-env'] as string);\n const config = toIndexingConfig(site, values['site-env'] as string);\n\n if (values['write-key'] !== undefined) {\n const key = config.indexNow?.key;\n if (!key) fail('no site.seo.indexing.indexNow.key in the config — generate one with --new-key');\n const dir = resolve(values['write-key']);\n mkdirSync(dir, { recursive: true });\n const file = join(dir, `${key}.txt`);\n writeFileSync(file, keyFileContents(key));\n console.log(`✓ IndexNow key file → ${file}`);\n console.log(` It must be served at ${resolveKeyLocation(config) ?? `/${key}.txt`}`);\n return;\n }\n\n const sitemapUrl = (values.sitemap as string | undefined) ?? resolveSitemapUrl(config);\n if (!sitemapUrl)\n fail(\n 'no sitemap to read — set seo.indexing.sitemapUrl or domains.canonical, or pass --sitemap',\n );\n\n const explicitUrls = values.urls\n ? (values.urls as string)\n .split(',')\n .map((u) => u.trim())\n .filter(Boolean)\n : undefined;\n\n // The sitemap is only needed when the URL set comes from it.\n const current =\n explicitUrls?.length && !values.check\n ? []\n : (await collectEntries(sitemapUrl, readSitemap)).entries;\n\n const snapshotPath = resolve(values.snapshot as string);\n const p = plan({\n config: { ...config, sitemapUrl },\n current,\n previous: readSnapshot(snapshotPath),\n explicitUrls,\n all: values.all as boolean,\n });\n\n console.log(formatPlan(p));\n\n if (p.blocked) {\n // Not a failure. Running this against a `noindex` environment is a coherent\n // thing for a deploy script to do — the config said not to index it, and the\n // command honoured that. Failing the build would punish the correct setup.\n return;\n }\n if (values.dry) {\n console.log('\\n(--dry: nothing was submitted)');\n return;\n }\n\n const credential = loadSearchCredential();\n let failed = false;\n\n // ── --check: read-only, and nothing else runs ───────────────────────────────\n if (values.check) {\n if (!p.searchConsole.siteUrl)\n fail('--check needs seo.indexing.searchConsole.siteUrl (the Search Console property)');\n if (!credential) fail(`--check needs a Search Console credential — ${CREDENTIAL_HINT}`);\n if (p.check.length === 0)\n fail('--check needs seo.indexing.priorityUrls — the pages whose indexing matters');\n\n const token = await googleAccessToken(credential);\n console.log(`\\nInspecting ${p.check.length} priority URL(s):`);\n for (const url of p.check) {\n const r = await inspectUrl(token, p.searchConsole.siteUrl, url);\n if (r.error) {\n console.log(` ? ${url} — ${r.error}`);\n failed = true;\n } else {\n console.log(\n ` ${r.indexed ? '✓' : '✗'} ${url} — ${r.coverageState ?? r.verdict ?? 'unknown'}`,\n );\n if (!r.indexed) failed = true;\n }\n }\n if (failed) {\n console.error('\\n✖ one or more priority URLs are not indexed');\n process.exit(1);\n }\n console.log('\\n✓ every priority URL is indexed');\n return;\n }\n\n // ── IndexNow ────────────────────────────────────────────────────────────────\n if (p.indexNow.enabled) {\n const { key, keyLocation } = p.indexNow;\n const check = await verifyKeyFile(keyLocation!, key!);\n if (!check.ok) {\n // Hard stop rather than \"submit and hope\": IndexNow answers 202 and then\n // discards the batch when the key doesn't verify, so submitting anyway\n // would print a success it did not earn.\n console.error(`✖ IndexNow key file check failed — ${check.reason}`);\n console.error(` Write it with: vitops search notify --write-key <public dir>`);\n failed = true;\n } else {\n let sent = 0;\n for (const batch of p.indexNow.batches) {\n const r = await submitBatch(p.indexNow, batch);\n if (!r.ok) {\n console.error(`✖ IndexNow: ${r.message ?? r.status}`);\n failed = true;\n break;\n }\n sent += r.urls;\n }\n if (!failed) console.log(`✓ IndexNow: ${sent} URL(s) submitted`);\n }\n }\n\n // ── Search Console ──────────────────────────────────────────────────────────\n if (p.searchConsole.enabled) {\n if (!credential) {\n console.log(`· Search Console: skipped — no credential (${CREDENTIAL_HINT})`);\n } else {\n const token = await googleAccessToken(credential);\n const r = await submitSitemap(token, p.searchConsole.siteUrl!, sitemapUrl);\n if (r.ok) console.log(`✓ Search Console: sitemap resubmitted`);\n else {\n console.error(`✖ Search Console: ${r.message}`);\n failed = true;\n }\n }\n }\n\n if (failed) process.exit(1);\n\n /*\n * The snapshot is written last, and only on success.\n *\n * Writing it eagerly would record URLs as notified that never were — and since\n * the next run diffs against it, a single transient 503 would drop those pages\n * from every future run, silently and permanently.\n */\n if (current.length > 0) {\n writeSnapshot(snapshotPath, toSnapshot(sitemapUrl, current, new Date().toISOString()));\n console.log(` state → ${relative(process.cwd(), snapshotPath)}`);\n }\n if (p.check.length > 0)\n console.log(\n `\\n Indexing is not instant. Run \\`vitops search notify --check\\` in a day or two to see what Google actually did.`,\n );\n}\n\n/**\n * Adapt a `Config` to the onboarding module's own option shape.\n *\n * The same flat field map as `toIndexingConfig`, and for the same reason — utils\n * cannot import the generator. `--domain` scopes to a single `site.searchConsole`\n * entry, and a name that isn't there is an error, not an empty run.\n */\nfunction toSearchConsoleSetup(cfg: Config, domainFilter: string | undefined): DomainSetup[] {\n const entries = cfg.site.searchConsole ?? {};\n const setups: DomainSetup[] = Object.entries(entries).map(([domain, e]) => ({\n domain,\n ...(e.delegatedOwners ? { delegatedOwners: e.delegatedOwners } : {}),\n ...(e.fullUserGroup ? { fullUserGroup: e.fullUserGroup } : {}),\n }));\n if (domainFilter) {\n const one = setups.find((s) => s.domain === domainFilter);\n if (!one)\n fail(\n `--domain \"${domainFilter}\" is not in site.searchConsole (have: ${setups.map((s) => s.domain).join(', ') || 'none'})`,\n );\n return [one];\n }\n return setups;\n}\n\n/**\n * The Cloudflare DNS credential. From the environment only — a `site.json` is\n * committed, and this is a real secret. A `Zone:DNS:Edit` token (the standard\n * \"Edit zone DNS\" template, which also carries `Zone:Read`).\n */\nfunction loadCloudflareToken(): string | undefined {\n return process.env.CLOUDFLARE_API_TOKEN || undefined;\n}\n\n/**\n * The Google user-OAuth credential (refresh-token flow), from the environment.\n *\n * A user token, not a service account: onboarding acts *as a person* who can own\n * the sites. All-or-nothing — a partial set is a misconfiguration worth naming\n * rather than a reason to run degraded.\n */\nfunction loadGoogleOAuth(): GoogleOAuth | undefined {\n const clientId = process.env.VITOPS_GOOGLE_CLIENT_ID;\n const clientSecret = process.env.VITOPS_GOOGLE_CLIENT_SECRET;\n const refreshToken = process.env.VITOPS_GOOGLE_REFRESH_TOKEN;\n if (!clientId && !clientSecret && !refreshToken) return undefined;\n const missing = [\n ['VITOPS_GOOGLE_CLIENT_ID', clientId],\n ['VITOPS_GOOGLE_CLIENT_SECRET', clientSecret],\n ['VITOPS_GOOGLE_REFRESH_TOKEN', refreshToken],\n ]\n .filter(([, v]) => !v)\n .map(([k]) => k);\n if (missing.length) fail(`incomplete Google OAuth credential — missing ${missing.join(', ')}`);\n return { clientId: clientId!, clientSecret: clientSecret!, refreshToken: refreshToken! };\n}\n\n/**\n * The Google identity for `search notify`, preferring a service account.\n *\n * Search Console accepts either, and the preference is about *where this command\n * runs*: it fires on every deploy, in CI, and a service account has no expiry,\n * while a refresh token can be revoked — and for an OAuth client still in\n * *Testing* publishing status Google expires it after 7 days, which is a bad\n * property for a deploy step. So the robot wins when it is available.\n *\n * The fallback is the point, though. `search setup` needs user OAuth (verifying\n * a site makes the caller an owner, which should be a person), so a consumer who\n * ran setup already has a Google credential. Demanding a second, unrelated one\n * for the other half of the same command bought nothing.\n */\nfunction loadSearchCredential(): GoogleCredential | undefined {\n const account = loadServiceAccount();\n if (account) return { kind: 'service-account', account, scope: SCOPES.webmasters };\n const oauth = loadGoogleOAuth();\n return oauth ? { kind: 'oauth', oauth } : undefined;\n}\n\n/** Both spellings, for an error that has to tell you what to actually set. */\nconst CREDENTIAL_HINT =\n 'a service account in VITOPS_GSC_SERVICE_ACCOUNT / GOOGLE_APPLICATION_CREDENTIALS, or a user OAuth credential in VITOPS_GOOGLE_CLIENT_ID / VITOPS_GOOGLE_CLIENT_SECRET / VITOPS_GOOGLE_REFRESH_TOKEN';\n\nconst sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));\n\n/**\n * `vitops search` — everything that talks to search engines.\n *\n * Two subcommands, split by what they touch: `setup` onboards a domain into\n * Search Console (DNS + verification + property), `notify` tells the engines a\n * deploy happened (sitemap + IndexNow). `notify` is the former top-level\n * `vitops indexing`.\n */\nasync function cmdSearch(argv: string[]) {\n const [sub, ...rest] = argv;\n switch (sub) {\n case 'setup':\n return cmdSearchSetup(rest);\n case 'notify':\n return cmdSearchNotify(rest);\n case undefined:\n case '-h':\n case '--help':\n console.log(SEARCH_HELP);\n return;\n default:\n fail(`unknown \"search\" subcommand \"${sub}\" (expected: setup | notify). Try: vitops --help`);\n }\n}\n\n/**\n * Onboard domains into Google Search Console as domain properties.\n *\n * Idempotent by construction: the planner decides each step from the domain's live\n * state, so a re-run of a fully-onboarded domain is all skips. `--check` reports\n * drift and exits non-zero without mutating; `--dry` prints the plan and stops.\n * DNS is only ever *created* — the verification TXT — never edited or removed.\n *\n * Search Console has no user/permission API, so granting a Google Group Full-User\n * access stays manual and is surfaced as a reminder, not attempted.\n */\nasync function cmdSearchSetup(argv: string[]) {\n const { values } = parseArgs({\n args: argv,\n options: {\n input: { type: 'string', short: 'i', default: 'site.json' },\n 'site-env': { type: 'string', default: 'production' },\n domain: { type: 'string' },\n check: { type: 'boolean', default: false },\n dry: { type: 'boolean', default: false },\n },\n allowPositionals: false,\n });\n\n const cfg = await loadConfig(resolve(values.input as string), values['site-env'] as string);\n const domains = toSearchConsoleSetup(cfg, values.domain as string | undefined);\n if (domains.length === 0)\n fail('no domains in site.searchConsole — add domains to onboard (keyed by bare hostname)');\n\n const cfToken = loadCloudflareToken();\n const oauth = loadGoogleOAuth();\n if (!cfToken)\n fail('set CLOUDFLARE_API_TOKEN (a Zone:DNS:Edit token) — reading and writing DNS needs it');\n if (!oauth)\n fail(\n 'set VITOPS_GOOGLE_CLIENT_ID / VITOPS_GOOGLE_CLIENT_SECRET / VITOPS_GOOGLE_REFRESH_TOKEN — a user OAuth token scoped to siteverification + webmasters',\n );\n\n const token = await refreshTokenGrant(oauth);\n\n // ── Observe live state per domain (the executors gather; the planner decides) ──\n const states = new Map<string, DomainState>();\n const verifyTokens = new Map<string, string>();\n const webIds = new Map<string, string>();\n for (const d of domains) {\n const zone = await findZoneId(cfToken, d.domain);\n if (!zone.ok || !zone.zoneId) fail(`${d.domain}: ${zone.message}`);\n\n const vt = await getVerificationToken(token, d.domain);\n if (!vt.ok || !vt.token)\n fail(`${d.domain}: could not obtain a verification token — ${vt.message}`);\n verifyTokens.set(d.domain, vt.token);\n\n const txt = await listApexTxt(cfToken, zone.zoneId, d.domain);\n if (!txt.ok) fail(`${d.domain}: ${txt.message}`);\n\n const wr = await getWebResource(token, d.domain);\n if (!wr.ok) fail(`${d.domain}: ${wr.message}`);\n if (wr.id) webIds.set(d.domain, wr.id);\n\n const site = await getSite(token, siteUrlFor(d.domain));\n if (!site.ok) fail(`${d.domain}: ${site.message}`);\n\n states.set(d.domain, {\n zoneId: zone.zoneId,\n txtPresent: txt.contents.includes(vt.token),\n verified: wr.exists,\n currentOwners: wr.owners,\n propertyExists: site.exists,\n });\n }\n\n const p = planSetup({ domains }, states);\n console.log(formatSetupPlan(p));\n\n if (values.check) {\n if (hasDrift(p)) {\n console.error('\\n✖ drift — one or more domains are not fully onboarded');\n process.exit(1);\n }\n console.log('\\n✓ every domain is onboarded');\n return;\n }\n if (values.dry) {\n console.log('\\n(--dry: nothing was changed)');\n return;\n }\n\n // ── Execute ─────────────────────────────────────────────────────────────────\n const results: DomainResult[] = [];\n let failed = false;\n const delays = backoffSchedule();\n\n for (const d of domains) {\n const dp = p.domains.find((x) => x.domain === d.domain)!;\n const state = states.get(d.domain)!;\n const result: DomainResult = {\n domain: d.domain,\n txt: '—',\n verified: '—',\n property: '—',\n reminders: dp.reminders,\n };\n\n // 1. Ensure the apex TXT record (create only).\n if (dp.txt.action === 'skip') result.txt = 'present';\n else {\n const r = await createApexTxt(cfToken, state.zoneId!, d.domain, verifyTokens.get(d.domain)!);\n if (!r.ok) {\n console.error(`✖ ${d.domain} TXT: ${r.message}`);\n result.txt = 'failed';\n failed = true;\n results.push(result);\n continue;\n }\n result.txt = 'created';\n }\n\n // 2. Verify ownership, retrying with backoff while DNS propagates.\n let verified = state.verified;\n if (verified) result.verified = 'yes';\n else {\n for (let attempt = 0; attempt < delays.length; attempt++) {\n const v = await verifyWebResource(token, d.domain);\n if (v.ok) {\n verified = true;\n if (v.id) webIds.set(d.domain, v.id);\n // Verification is what CREATES the web resource, so this response is the\n // first sight of its owner list — and it contains the verifying account.\n // The pre-verification observation could only report `[]`. Dropping this\n // makes the union below a bare `ownersToAdd`, and the PUT then removes\n // the very account that just proved ownership.\n state.currentOwners = v.owners;\n break;\n }\n if (attempt < delays.length - 1) {\n const wait = delays[attempt]!;\n console.log(\n ` … ${d.domain}: not verified yet (attempt ${attempt + 1}/${delays.length}); retrying in ${wait / 1000}s`,\n );\n await sleep(wait);\n }\n }\n // PENDING, not failed: propagation is slow, not broken. Re-run later.\n result.verified = verified ? 'yes' : 'pending';\n }\n if (!verified) {\n results.push(result);\n continue;\n }\n\n // 3. Add the Search Console property.\n if (dp.property.action === 'skip') result.property = 'present';\n else {\n const r = await addSite(token, dp.siteUrl);\n if (!r.ok) {\n console.error(`✖ ${d.domain} property: ${r.message}`);\n result.property = 'failed';\n failed = true;\n } else result.property = 'added';\n }\n\n // 4. Add delegated owners to the verified web resource (additive union).\n if (dp.owners.action === 'update' && dp.ownersToAdd.length) {\n const id = webIds.get(d.domain);\n if (!id) {\n console.error(`✖ ${d.domain} owners: no web-resource id (verify may be too fresh)`);\n failed = true;\n } else {\n const r = await updateOwners(\n token,\n id,\n d.domain,\n ownerUnion(state.currentOwners, dp.ownersToAdd),\n );\n if (!r.ok) {\n console.error(`✖ ${d.domain} owners: ${r.message}`);\n failed = true;\n } else console.log(`✓ ${d.domain}: added ${dp.ownersToAdd.length} owner(s)`);\n }\n }\n\n results.push(result);\n }\n\n console.log(`\\n${formatSummary(results)}`);\n if (failed) process.exit(1);\n}\n\n// This CLI's own version (dist/cli.mjs → package-root package.json).\nfunction cliVersion(): string {\n try {\n return (\n JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version ??\n '0.0.0'\n );\n } catch {\n return '0.0.0';\n }\n}\n\n// The framework asset root shipped inside @getvitops/generator (holds the Bricks\n// PHP that generateDocs reads for the element reference).\nfunction generatorAssetsDir(): string {\n const pkg = createRequire(import.meta.url).resolve('@getvitops/generator/package.json');\n return join(dirname(pkg), 'assets');\n}\n\nconst AGENTS_START = '<!-- vitops:start -->';\nconst AGENTS_END = '<!-- vitops:end -->';\n\n/** Print a live reference doc (rendered from the project's config) to stdout. */\nfunction cmdDocs(argv: string[]) {\n const { values, positionals } = parseArgs({\n args: argv,\n options: {\n input: { type: 'string', short: 'i', default: 'design-system.json' },\n theme: { type: 'string' },\n all: { type: 'boolean', default: false },\n },\n allowPositionals: true,\n });\n const topic = positionals[0];\n const topicList = () =>\n Object.entries(TOPICS)\n .map(([name, t]) => ` ${name.padEnd(10)} ${t.summary}`)\n .join('\\n');\n if (!topic && !values.all) {\n console.log(\n `vitops docs <topic> — print a live design-system reference to stdout\\n\\nTopics:\\n${topicList()}\\n\\nAlso: vitops docs --all (every topic, concatenated)`,\n );\n return;\n }\n if (topic && !TOPICS[topic]) fail(`unknown topic \"${topic}\". Valid topics:\\n${topicList()}`);\n const ds = loadDesignSystem(resolve(values.input as string), values.theme as string | undefined);\n const docs = generateDocs(ds, generatorAssetsDir());\n const paths = values.all\n ? Object.values(TOPICS).map((t) => t.path)\n : [TOPICS[topic as string]!.path];\n process.stdout.write(paths.map((p) => docs[p]).join('\\n'));\n}\n\nfunction cmdLint(argv: string[]) {\n const { values } = parseArgs({\n args: argv,\n options: {\n input: { type: 'string', short: 'i', default: 'design-system.json' },\n theme: { type: 'string' },\n format: { type: 'string', short: 'f', default: 'bricks' },\n src: { type: 'string', short: 's', default: 'src' },\n // Suggestions are advisory: a reuse rule that failed CI the day it shipped\n // would be a worse defect than the drift it reports.\n strict: { type: 'boolean', default: false },\n },\n allowPositionals: false,\n });\n const format = values.format as StylesheetFormat;\n if (!LINT_FORMATS.has(format))\n fail(`unknown format \"${format}\" (expected: bricks | css | tailwind)`);\n const ds = loadDesignSystem(resolve(values.input as string), values.theme as string | undefined);\n const srcDir = resolve(values.src as string);\n if (!existsSync(srcDir)) fail(`source directory not found: ${srcDir}`);\n\n // Ask the generator what it actually emits rather than re-deriving the rules\n // here — a linter that models the vocabulary separately just drifts into\n // reporting classes that do exist.\n const palette = expandPalette(ds.colors.palette);\n const roleClasses = roleColorUtilities(\n Object.entries(ds.colors.roles).map(([role, spec]) =>\n functionalRole(role, roleHue(spec), palette[roleHue(spec)]!, roleKind(spec)),\n ),\n ds.colors.utilities ?? ['bg', 'text', 'icon', 'border'],\n ).map((u) => u.cls);\n\n const files = scanFiles(srcDir);\n // `.css` is not in the default extension set — the class linter reads markup,\n // not stylesheets — so the reuse rules get their own pass. Component files are\n // scanned twice on purpose: once for their class attributes, once for any\n // `<style>` block, which is where hand-rolled layout tends to accumulate.\n const cssFiles = [...files, ...scanFiles(srcDir, { exts: ['.css'] })];\n const findings = [\n ...lintSource(files, vocabulary(ds, roleClasses), format),\n ...lintCss(cssFiles, format),\n ];\n\n if (!findings.length) {\n console.log(\n `✓ no unresolvable framework classes in ${values.src} ` +\n `(${files.length} file${files.length === 1 ? '' : 's'} scanned)`,\n );\n return;\n }\n\n const errors = findings.filter((f) => f.severity === 'error');\n const suggestions = findings.filter((f) => f.severity === 'suggestion');\n // Errors first: a class that resolves to nothing is a defect, a reuse\n // suggestion is a judgement call, and mixing them buries the former.\n for (const f of [...errors, ...suggestions]) {\n console.error(`${f.file}:${f.line} ${f.severity === 'error' ? f.cls : `(${f.cls})`}`);\n console.error(` ${f.reason}`);\n if (f.suggestion) console.error(` try: ${f.suggestion}`);\n }\n\n const count = (n: number, one: string, many: string) => `${n} ${n === 1 ? one : many}`;\n const parts: string[] = [];\n if (errors.length) parts.push(count(errors.length, 'unresolvable class', 'unresolvable classes'));\n if (suggestions.length) parts.push(count(suggestions.length, 'suggestion', 'suggestions'));\n const failing = errors.length > 0 || (values.strict === true && suggestions.length > 0);\n console.error(\n `\\n${failing ? '✖' : '!'} ${parts.join(', ')} in ` +\n `${files.length} file${files.length === 1 ? '' : 's'}` +\n (suggestions.length && !values.strict ? ' (suggestions do not fail; use --strict)' : ''),\n );\n if (failing) process.exit(1);\n}\n\nfunction cmdAgents(argv: string[]) {\n const { values } = parseArgs({\n args: argv,\n options: {\n input: { type: 'string', short: 'i', default: 'design-system.json' },\n theme: { type: 'string' },\n out: { type: 'string', short: 'o', default: 'AGENTS.md' },\n 'docs-dir': { type: 'string' },\n },\n allowPositionals: false,\n });\n const inputRel = values.input as string;\n // The command is pure wiring: validate the config when present (fail on an\n // invalid one), but don't require it — docs are rendered live by `vitops docs`.\n let ds: DesignSystem | null = null;\n if (existsSync(resolve(inputRel)))\n ds = loadDesignSystem(resolve(inputRel), values.theme as string | undefined);\n else console.warn(` ⚠ ${inputRel} not found — run \\`vitops init\\` to scaffold one`);\n\n // Explicit --docs-dir = legacy layout: write the docs bundle as files, no skill.\n const legacyDocsDir = values['docs-dir'] as string | undefined;\n let summary: string;\n let pointer: string[];\n\n if (legacyDocsDir) {\n if (!ds) fail(`--docs-dir needs a config to render docs from (${inputRel} not found)`);\n let docs: Record<string, string> = {};\n try {\n docs = generateDocs(ds, generatorAssetsDir());\n } catch (err) {\n fail(`could not generate docs: ${(err as Error).message}`);\n }\n for (const [rel, content] of Object.entries(docs)) {\n const p = resolve(legacyDocsDir, rel);\n mkdirSync(dirname(p), { recursive: true });\n writeFileSync(p, content);\n }\n summary = `wrote ${Object.keys(docs).length} docs to ${legacyDocsDir}/`;\n pointer = [\n 'Prefer the framework’s utility + component classes over hand-written CSS.',\n `Reference docs (regenerate with \\`vitops agents --docs-dir ${legacyDocsDir}\\`): \\`${legacyDocsDir}/css/classes.md\\`,`,\n `\\`${legacyDocsDir}/authoring.md\\`, \\`${legacyDocsDir}/formats.md\\`, \\`${legacyDocsDir}/bricks/elements.md\\`.`,\n ];\n } else {\n // Link the packaged skill (ships inside @getvitops/cli) into the agent\n // discovery locations; nothing is generated into the repo.\n const target = findSkillTarget(process.cwd());\n if (target) {\n for (const dir of ['.agents', '.claude']) {\n const warn = linkSkill(resolve(dir, 'skills', SKILL_NAME), target);\n if (warn) console.warn(` ⚠ ${warn}`);\n }\n summary = `linked {.agents,.claude}/skills/${SKILL_NAME} → ${target}`;\n } else {\n console.warn(\n ` ⚠ could not find node_modules/@getvitops/cli/skill — install @getvitops/cli as a devDependency, then re-run \\`vitops agents\\``,\n );\n summary = 'no skill linked';\n }\n pointer = [\n 'Prefer the framework’s utility + component classes over hand-written CSS.',\n `Full design-system context lives in the \\`${SKILL_NAME}\\` skill (linked from`,\n '`.agents/skills/` and `.claude/skills/` into the installed `@getvitops/cli`;',\n 're-link with `vitops agents` if the links are deleted — they survive version',\n 'bumps). Reference docs print live, from this project’s config, via:',\n '',\n ...Object.entries(TOPICS).map(([name, t]) => `- \\`vitops docs ${name}\\` — ${t.summary}`),\n ];\n }\n\n const block = [\n AGENTS_START,\n '## Vitops design system',\n '',\n `Styled with the Vitops design system (\\`@getvitops/*\\`); tokens live in \\`${inputRel}\\`.`,\n 'Generate output with the CLI:',\n '',\n '- `vitops generate --format tailwind --out src/styles` — Tailwind v4 / Astro',\n '- `vitops generate --format css --out dist` — standalone CSS',\n '- `vitops generate --format bricks --out <theme>/dist` — WordPress / Bricks',\n '- `vitops generate --format design --out .` — `DESIGN.md`, the agent-facing brief',\n '- `vitops init` · `vitops validate` · `vitops favicon`',\n '',\n ...pointer,\n '',\n `<!-- regenerate: vitops agents · @getvitops/cli@${cliVersion()} -->`,\n AGENTS_END,\n ].join('\\n');\n\n const outPath = resolve(values.out as string);\n let next: string;\n let action: string;\n if (existsSync(outPath)) {\n const cur = readFileSync(outPath, 'utf8');\n const s = cur.indexOf(AGENTS_START);\n const e = cur.indexOf(AGENTS_END);\n if (s !== -1 && e !== -1 && e > s) {\n next = cur.slice(0, s) + block + cur.slice(e + AGENTS_END.length);\n action = 'updated block in';\n } else {\n next = cur.replace(/\\s*$/, '') + '\\n\\n' + block + '\\n';\n action = 'appended block to';\n }\n } else {\n mkdirSync(dirname(outPath), { recursive: true });\n next = block + '\\n';\n action = 'created';\n }\n writeFileSync(outPath, next);\n console.log(`✓ ${action} ${values.out} + ${summary}`);\n}\n\nasync function main() {\n const [command, ...rest] = process.argv.slice(2);\n if (!command || command === '-h' || command === '--help' || command === 'help') {\n console.log(HELP);\n return;\n }\n switch (command) {\n case 'generate':\n return cmdGenerate(rest);\n case 'init':\n return cmdInit(rest);\n case 'validate':\n return cmdValidate(rest);\n case 'favicon':\n return cmdFavicon(rest);\n case 'agents':\n return cmdAgents(rest);\n case 'docs':\n return cmdDocs(rest);\n case 'lint':\n return cmdLint(rest);\n case 'legal':\n return cmdLegal(rest);\n case 'icons':\n return cmdIcons(rest);\n case 'search':\n return cmdSearch(rest);\n case 'media':\n return cmdMedia(rest);\n default:\n fail(\n `unknown command \"${command}\" (expected: generate | init | validate | favicon | agents | docs | lint | legal | icons | search | media). Try: vitops --help`,\n );\n }\n}\n\nmain().catch((err) => fail((err as Error).message));\n"],"mappings":";;;;;;;;;;;;;;;;;AAeA,MAAa,aAAa;;AAG1B,MAAa,mBAAmB;;;;;AAMhC,MAAa,SAA4D;CACvE,SAAS;EACP,MAAM;EACN,SAAS;CACX;CACA,WAAW;EACT,MAAM;EACN,SAAS;CACX;CACA,QAAQ;EACN,MAAM;EACN,SACE;CACJ;CACA,SAAS;EACP,MAAM;EACN,SAAS;CACX;CACA,OAAO;EACL,MAAM;EACN,SAAS;CACX;CACA,QAAQ;EACN,MAAM;EACN,SAAS;CACX;CACA,OAAO;EACL,MAAM;EACN,SAAS;CACX;CACA,UAAU;EACR,MAAM;EACN,SAAS;CACX;CACA,YAAY;EACV,MAAM;EACN,SAAS;CACX;CACA,SAAS;EACP,MAAM;EACN,SAAS;CACX;CACA,UAAU;EACR,MAAM;EACN,SAAS;CACX;CACA,QAAQ;EACN,MAAM;EACN,SAAS;CACX;CACA,OAAO;EACL,MAAM;EACN,SAAS;CACX;CACA,UAAU;EACR,MAAM;EACN,SAAS;CACX;AACF;;;;;;;;;;;;AAaA,SAAgB,gBAAgB,KAA4B;CAC1D,IAAI,MAAM,QAAQ,GAAG;CACrB,MAAM,EAAE,SAAS,MAAM,GAAG;CAC1B,SAAS;EACP,MAAM,WAAW,KAAK,KAAK,gBAAgB,cAAc,OAAO,OAAO;EACvE,IAAI,WAAW,KAAK,UAAU,UAAU,CAAC,GAAG,OAAO;EACnD,IAAI,QAAQ,MAAM,OAAO;EACzB,MAAM,QAAQ,GAAG;CACnB;A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C,OAAO,QAAQ,KAAM,IAAc,OAAO,CAAC"}
1
+ {"version":3,"file":"cli.mjs","names":["lineAt","CLASS_ATTR","formatMediaPlan","formatSetupPlan","planSetup","planAds","formatPlanAds","hasAdsDrift","formatAdsSummary"],"sources":["../src/agents.ts","../src/help.ts","../src/prompt.ts","../src/css-scan.ts","../src/lint-css.ts","../src/lint-markup.ts","../src/lint-tokens.ts","../src/lint.ts","../src/cli.ts"],"sourcesContent":["/**\n * Side-effect-free helpers for the `vitops agents` / `vitops docs` commands.\n * Kept out of cli.ts (which runs main() on import) so they are unit-testable.\n */\nimport {\n existsSync,\n lstatSync,\n mkdirSync,\n readFileSync,\n readlinkSync,\n rmSync,\n symlinkSync,\n} from 'node:fs';\nimport { dirname, join, parse, relative, resolve } from 'node:path';\n\nexport const SKILL_NAME = 'vitops-design-system';\n\n/** Marker the 0.5.0-era generated skill carried; lets us migrate that layout. */\nexport const GENERATED_MARKER = '<!-- GENERATED by @getvitops/cli';\n\n/**\n * `vitops docs` topics → docs-bundle paths (as returned by `generateDocs`).\n * Order is the `--all` concatenation order.\n */\nexport const TOPICS: Record<string, { path: string; summary: string }> = {\n classes: {\n path: 'css/classes.md',\n summary: 'CSS framework class vocabulary (colour, type, space, layout, animation, patterns)',\n },\n authoring: {\n path: 'authoring.md',\n summary: 'every design-system.json field, rendered from the JSON Schema',\n },\n config: {\n path: 'config.md',\n summary:\n 'every field of the three-section config (designSystem / organization / site), rendered from the JSON Schema',\n },\n formats: {\n path: 'formats.md',\n summary: \"tailwind vs css vs bricks: what's emitted vs what the platform provides\",\n },\n color: {\n path: 'concepts/color.md',\n summary: 'seeded OKLCH scales, functional tokens, automatic dark mode',\n },\n scales: {\n path: 'concepts/scales.md',\n summary: 'fluid modular type & space scales',\n },\n icons: {\n path: 'concepts/icons.md',\n summary: 'semantic icon names across sets, bundle derivation, sprite delivery',\n },\n patterns: {\n path: 'concepts/patterns.md',\n summary: 'pattern CSS: token cascade, override hooks, states, role variants',\n },\n components: {\n path: 'concepts/components.md',\n summary: 'which of the four tiers provides each pattern, and the call to make',\n },\n consent: {\n path: 'concepts/consent.md',\n summary: 'the consent gate: inert gated tags, demand-driven prompting, three-valued choices',\n },\n tracking: {\n path: 'concepts/tracking.md',\n summary: 'ad-click attribution, the `_ac` cookie, conversion notifications',\n },\n search: {\n path: 'concepts/search.md',\n summary: 'what search engines accept, Search Console onboarding, deploy notification',\n },\n legal: {\n path: 'concepts/legal.md',\n summary: 'privacy policy / terms / cookie notice derived from config facts',\n },\n elements: {\n path: 'bricks/elements.md',\n summary: 'Bricks Builder custom elements, controls, defaults',\n },\n};\n\n/**\n * Find the installed package's skill directory by walking up from `cwd` looking\n * for `node_modules/@getvitops/cli/skill/SKILL.md`. Returns the LOGICAL path\n * (through the `node_modules/@getvitops/cli` link, unresolved) or null.\n *\n * Deliberately not derived from import.meta.url: under pnpm the running module's\n * URL is the realpath in `node_modules/.pnpm/@getvitops+cli@<version>/…`, which\n * changes on every version bump — a symlink to it would dangle after upgrades.\n * The logical path is recreated by the package manager on every install, so a\n * link through it always resolves to the currently installed version.\n */\nexport function findSkillTarget(cwd: string): string | null {\n let dir = resolve(cwd);\n const { root } = parse(dir);\n for (;;) {\n const skillDir = join(dir, 'node_modules', '@getvitops', 'cli', 'skill');\n if (existsSync(join(skillDir, 'SKILL.md'))) return skillDir;\n if (dir === root) return null;\n dir = dirname(dir);\n }\n}\n\n/**\n * Idempotently symlink `linkPath` → `targetDir` (relative target). Replaces a\n * stale symlink; migrates a real directory left by the old emitting `vitops\n * agents` (identified by GENERATED_MARKER in its SKILL.md); refuses to clobber\n * anything else. Returns a warning string, or null on success / no-op.\n */\nexport function linkSkill(linkPath: string, targetDir: string): string | null {\n const target = relative(dirname(linkPath), resolve(targetDir));\n try {\n const st = lstatSync(linkPath, { throwIfNoEntry: false });\n if (st && !st.isSymbolicLink()) {\n const oldSkill = join(linkPath, 'SKILL.md');\n const isGenerated =\n st.isDirectory() &&\n existsSync(oldSkill) &&\n readFileSync(oldSkill, 'utf8').includes(GENERATED_MARKER);\n if (!isGenerated)\n return `left ${linkPath} alone (exists and is not a symlink) — link it to ${targetDir} yourself if wanted`;\n rmSync(linkPath, { recursive: true }); // old generated skill layout → replace\n } else if (st) {\n if (readlinkSync(linkPath) === target) return null;\n rmSync(linkPath);\n } else {\n mkdirSync(dirname(linkPath), { recursive: true });\n }\n symlinkSync(target, linkPath);\n return null;\n } catch (err) {\n return `could not symlink ${linkPath}: ${(err as Error).message}`;\n }\n}\n","/**\n * The CLI's help text, and the addressing that lets every subcommand answer\n * `--help`.\n *\n * It lives beside `cli.ts` rather than inside it for one reason: `cli.ts` calls\n * `main()` at import time, so nothing can import it to check anything. The\n * drift guard in `help.test.ts` needs `COMMANDS` and `helpSection` as values.\n */\n\nexport const HELP = `vitops — generate design-system outputs from a design-system.json\n\nAnywhere a command takes --input, that file may be a design-system.json OR the\nlarger site config that embeds one (company.json / site.json). The two are told\napart by shape, and a site config also supplies the site-level facts generation\nreads — its default colour scheme, its legal documents, its icon sprite.\n\nUsage:\n vitops generate [options] Generate platform output from a config\n vitops init [options] Scaffold a starter design-system.json\n vitops validate <file> Validate a config against the schema it says it is\n vitops favicon [options] Generate a favicon set from a source image\n vitops agents [options] Link the design-system agent skill + AGENTS.md pointer\n vitops docs [topic] Print live design-system reference docs to stdout\n vitops lint [opts] [files] Report classes that resolve to nothing + primitives you re-implemented\n vitops legal [options] Render legal documents from a site config\n vitops icons [options] Report which icons your source uses, and build the sprite\n vitops search <sub> [opts] Search Console: onboard domains (setup) + notify deploys (notify)\n vitops ads <sub> [opts] Ad properties: verify domains (setup) + emit pixels (tags) + lint\n vitops media [options] Encode raw video into web-ready WebM + MP4 + poster\n\nGenerate options:\n -i, --input <path> design-system.json or site config (default: ./design-system.json)\n -f, --format <list> bricks | css | tailwind | design (comma-separated; default: bricks)\n design emits DESIGN.md only (the agent-facing brief) — pair it\n with --out . to write it beside AGENTS.md, or compose:\n --format css,design\n -o, --out <dir> Output directory (default: ./dist)\n --theme <name> Which designSystem.themes entry to build, when --input is\n a site config (default: its defaultTheme, else \"default\")\n --site <path> Site config, when it is a different file from --input.\n Emits legal/*.html into the output directory (see:\n vitops legal). Omitted with a plain design-system.json:\n no legal files.\n --site-env <env> Environment whose A/B variant applies (default: production)\n\nInit options:\n -o, --out <path> Where to write (default: ./design-system.json)\n --force Overwrite an existing file\n\nValidate options:\n <file> Config to check (default: ./design-system.json). Either\n kind — a design-system.json or the config that embeds one.\n -i, --input <path> Same, as a flag\n --site-env <env> Environment whose A/B variant applies (default: production)\n\n Checks the schema, then the things a schema cannot: that every role points at a\n palette hue that exists, that every var() an authored declaration references\n resolves to a token this config emits, and that the colour grammar is current.\n\nFavicon options:\n -i, --input <path> Source SVG or PNG (required)\n -o, --out <dir> Output directory (default: ./public)\n --low-res <path> Optional simplified source for the 16px icon\n --background <hex> Background under the maskable icons, which must be\n opaque (default: #ffffff)\n\nAgents options:\n -i, --input <path> design-system.json or site config (default: ./design-system.json;\n validated if present)\n --theme <name> Theme to read, when --input is a site config\n -o, --out <path> Doc file to update, idempotently (default: ./AGENTS.md)\n --docs-dir <dir> Legacy layout: write the docs bundle as files to this dir\n instead of linking the packaged skill\n\nDocs options:\n <topic> classes | authoring | formats | color | scales | patterns | elements\n (no topic: list topics with summaries)\n -i, --input <path> design-system.json or site config (default: ./design-system.json)\n --theme <name> Theme to render docs from, when --input is a site config\n --all Print every topic, concatenated\n\nIcons options:\n --site <path> Site config carrying the \"icons\" block (default: ./site.json)\n --src <dir> Source to scan for icon usage (default: ./src)\n --sprite Also build the SVG sprite\n -o, --out <dir> Where to write icons.svg with --sprite (default: ./dist)\n --json Machine-readable report on stdout\n\nLint options:\n -i, --input <path> design-system.json or site config (default: ./design-system.json)\n --theme <name> Theme to judge classes against, when --input is a site config\n -f, --format <fmt> Format you build (bricks | css | tailwind; default: bricks).\n Responsive md-* classes are real in css/bricks, inert in tailwind.\n -s, --src <dir> Directory to scan (default: ./src)\n --strict Also fail on suggestions (reuse hints), not just on\n classes that resolve to nothing\n [files...] Lint these paths instead of scanning --src. Unreadable\n and non-source paths are skipped, so this can be wired\n into a pre-commit hook that appends the staged files.\n --fix Rewrite pre-1.0 colour-grammar token references\n (var(--<role>-<suffix>) → var(--color-<target>-<role>…))\n in CSS and <style> blocks. Applied in ONE pass, so the\n renames that rotate cannot compound. Nothing else is\n rewritten — every other finding is a judgement call.\n\n Run this after a major bump: it is the migration tool for anything the\n changelog says was renamed.\n\nLegal options:\n -i, --input <path> Site config: .json, or a .js/.ts module with a default\n export (default: ./site.json)\n -d, --doc <name> privacy | terms | cookies (repeatable; default: those\n enabled in the config)\n -f, --format <fmt> md | html | portable-text (default: md)\n html suits WordPress/Bricks and plain sites;\n portable-text suits EmDash\n -o, --out <dir> Write files here (default: print to stdout)\n --site-env <env> Environment whose A/B variant applies (default: production)\n\n Generated from your config — a starting point, not legal advice. Review before\n publishing, and make sure the config describes what your site actually does.\n\nSearch subcommands:\n vitops search setup [opts] Onboard site.searchConsole domains into GSC\n vitops search notify [opts] Tell search engines about a deploy (sitemap + IndexNow)\n\nSearch setup options:\n -i, --input <path> Site config carrying site.searchConsole (default: ./site.json)\n --site-env <env> Environment whose A/B variant applies (default: production)\n --domain <name> Scope to a single site.searchConsole entry\n --dry Print the plan and exit. Changes nothing, and runs without\n credentials (planning from scratch, which it says).\n --check Report drift and exit non-zero if any domain is not fully\n onboarded. Mutates nothing, but does need credentials —\n drift is a comparison against live state.\n\n For each domain it ensures the apex verification TXT in Cloudflare, verifies\n ownership (DNS_TXT, retried with backoff while DNS propagates — a still-\n unverified domain is reported PENDING, not failed), adds the sc-domain: property,\n and adds any delegatedOwners to the web resource. DNS is only ever created,\n never edited or deleted. Credentials come from the environment:\n CLOUDFLARE_API_TOKEN (Zone:DNS:Edit + Zone:Read — the standard \"Edit zone DNS\"\n template covers both; Zone:Read is what the zone-by-name lookup uses), and\n VITOPS_GOOGLE_CLIENT_ID /\n VITOPS_GOOGLE_CLIENT_SECRET / VITOPS_GOOGLE_REFRESH_TOKEN (a user OAuth token\n scoped to siteverification + webmasters). Granting a Google Group Full-User\n access has no API and is surfaced as a reminder.\n\nSearch notify options:\n -i, --input <path> Site config carrying seo.indexing (default: ./site.json)\n --site-env <env> Environment to notify for (default: production). An\n environment whose robots policy says noindex is refused.\n --sitemap <src> Sitemap URL or local path (default: from the config)\n --urls <list> Comma-separated URLs to submit, skipping the diff\n --all Submit every URL in the sitemap, not just what changed\n --dry Print the plan and exit. Makes no requests.\n --check Read-only: ask Google whether seo.indexing.priorityUrls\n are indexed. Exits non-zero if one is not.\n --new-key Print a fresh IndexNow key and exit\n --write-key <dir> Write the IndexNow key file into <dir> (for stacks with\n no Astro integration to do it — Bricks, WordPress)\n --snapshot <path> Changed-URL state file (default: .vitops/sitemap-snapshot.json).\n Persist it between runs (a CI cache) or every run submits\n everything.\n\n What notify can and cannot do: Google exposes no \"request indexing\" API, and its\n sitemap ping endpoint was removed in 2023 — so it resubmits your sitemap\n through the Search Console API and verifies the result with --check. IndexNow\n reaches Bing, Yandex, Naver, Seznam and Yep; Google does not participate.\n Search Console takes either credential, whichever you already have, added as an\n owner of the property: a service account in VITOPS_GSC_SERVICE_ACCOUNT (inline\n JSON) or GOOGLE_APPLICATION_CREDENTIALS (a path), or the same user OAuth\n credential \"search setup\" uses (VITOPS_GOOGLE_CLIENT_ID / _CLIENT_SECRET /\n _REFRESH_TOKEN). The service account is preferred when both are set — this runs\n on every deploy, and it does not expire.\n\nAds subcommands:\n vitops ads setup [opts] Ensure each platform's domain-verification DNS record\n vitops ads tags [opts] Print the consent-gated pixel snippets\n vitops ads lint [opts] Report ad properties the rest of the config can't see\n\nAds setup options:\n -i, --input <path> Site config carrying site.ads (default: ./site.json)\n --site-env <env> Environment whose A/B variant applies (default: production)\n --provider <name> Scope to one site.ads entry (google | meta | linkedin |\n reddit | tiktok | microsoft | pinterest | snapchat)\n --dry Print the plan and exit. Creates nothing. With\n CLOUDFLARE_API_TOKEN set it reads live DNS first, so the\n plan says what is already done; without one it plans from\n scratch and says so, rather than refusing to run.\n --check Report drift and exit non-zero if any property is not\n linked. Mutates nothing, prompts for nothing.\n --no-prompt Never ask for a missing token; fail with the field name\n instead (the default when stdin is not a TTY, e.g. in CI)\n --no-write Don't persist an answered token back into the config\n\n Four platforms verify a domain by DNS TXT — Meta, TikTok, Pinterest, Snapchat —\n and that record is the one thing this creates for you (in Cloudflare, via\n CLOUDFLARE_API_TOKEN; created only, never edited or deleted). Google Ads,\n LinkedIn, Reddit and Microsoft Ads have no domain verification at all: linking\n there is the tag and the account ID, and the run says so rather than skipping in\n silence. No platform Marketing API is called — Meta's needs a system-user token\n and Google's needs an approved developer token, so the final \"Verify\" click stays\n a reminder. The verification token is not a secret (it is published in DNS, which\n is the ownership proof), so it lives in the config and is prompted for on the\n first run.\n\nAds tags options:\n -i, --input <path> Site config carrying site.ads (default: ./site.json)\n --provider <name> Print one platform's tag\n --strategy <s> idle | async | interaction (default: idle)\n\n Prints each pixel as an INERT, consent-gated <script>: type=\"text/plain\" with the\n library URL on data-src, so an undecided visitor's page issues no third-party\n request. For stacks with no Astro integration — Bricks, WordPress, Eleventy.\n Paste into your template; @getvitops/core's consent runtime activates them.\n\nAds lint options:\n -i, --input <path> Site config carrying site.ads (default: ./site.json)\n\n Reports the gaps that are invisible at runtime: a click-ID parameter this\n platform stamps that attribution doesn't capture, a pixel while site.tracking is\n off (every conversion arrives unattributed), and a configured property with no\n tag ID. Exits non-zero on a finding.\n\nMedia options:\n --raw <dir> Directory of unprocessed video, walked recursively\n (default: ./raw)\n -o, --out <dir> Where the encoded outputs go (default: ./src/assets/processed).\n Subdirectories under --raw are preserved.\n --max-width <px> Cap the output width, keeping aspect ratio (default: 1920;\n 0 disables scaling)\n --crf <n> Quality on VP9's scale, 0-63, lower is better (default: 32).\n The MP4 fallback uses the equivalent on H.264's scale.\n --max-bitrate <r> Optional ceiling, e.g. 2M or 800k (default: none, which is\n constant quality rather than constrained)\n --audio Keep the audio track (default: dropped — the common case is\n a muted autoplay loop)\n --poster-time <s> Timestamp the poster frame is taken from (default: 0, which\n is often black on a clip that fades in)\n --outputs <list> Comma-separated: webm | mp4 | poster (default: all three)\n --manifest <path> Cache file (default: .vitops/media-manifest.json)\n --force Re-encode everything, ignoring the cache\n --dry Print the plan and exit. Encodes nothing.\n\n Needs ffmpeg on PATH — it is an external tool, not an npm dependency, and this\n command fails rather than quietly skipping. Commit the outputs and the manifest:\n ffmpeg output is not reproducible across versions, so re-encoding in CI churns\n the diff on every toolchain bump. Use --force when you mean to re-encode.\n\nCommon:\n -h, --help Show this help\n`;\n\nexport const SEARCH_HELP = `vitops search — Google Search Console\n\n vitops search setup [opts] Onboard site.searchConsole domains as GSC domain properties\n vitops search notify [opts] Tell search engines a deploy happened (sitemap + IndexNow)\n\nRun \\`vitops --help\\` for the full option list for each subcommand.\n`;\n\nexport const ADS_HELP = `vitops ads — link this site to its ad properties\n\n vitops ads setup [opts] Ensure each platform's domain-verification DNS record\n vitops ads tags [opts] Print the consent-gated pixel snippets\n vitops ads lint [opts] Report ad properties the rest of the config can't see\n\nRun \\`vitops --help\\` for the full option list for each subcommand.\n`;\n\n/**\n * Every command `main()` dispatches. Exported so the unknown-command message\n * and the help drift guard read the same list — the message used to carry its\n * own hand-maintained copy.\n */\nexport const COMMANDS = [\n 'generate',\n 'init',\n 'validate',\n 'favicon',\n 'agents',\n 'docs',\n 'lint',\n 'legal',\n 'icons',\n 'search',\n 'ads',\n 'media',\n] as const;\n\n/** Commands that group subcommands instead of taking options directly. */\nexport const SUBCOMMANDS: Record<string, readonly string[]> = {\n search: ['setup', 'notify'],\n ads: ['setup', 'tags', 'lint'],\n};\n\n/**\n * The slice of `HELP` documenting one command, addressed by its heading.\n *\n * `HELP` is already organised as `<Command> options:` blocks, so this reads the\n * section rather than duplicating it — a second copy of every option list is a\n * second thing to keep true.\n */\nexport function helpSection(...parts: string[]): string | undefined {\n // Headings capitalise the command only, not the subcommand (\"Search setup\n // options:\"), so capitalising every part silently misses the two-word ones.\n const name = parts.join(' ');\n const title = `${name.charAt(0).toUpperCase()}${name.slice(1)} options:`;\n const start = HELP.indexOf(`\\n${title}\\n`);\n if (start === -1) return undefined;\n const body = HELP.slice(start + 1);\n // Stop at the next top-level heading (`Legal options:`, `Common:`, …).\n const next = body.slice(title.length).search(/\\n[A-Z][A-Za-z ]*:\\n/);\n return next === -1 ? body : body.slice(0, title.length + next);\n}\n\n/**\n * `--help` on a leaf subcommand used to reach `parseArgs`, which is strict and\n * declares no `help` option — so `vitops lint --help` exited non-zero with a\n * bare `Unknown option '--help'`. Every subcommand answers it now, and it is\n * resolved in one place rather than in fifteen `options` objects, so a new\n * command cannot forget to.\n */\nexport const wantsHelp = (argv: string[]): boolean =>\n argv.includes('-h') || argv.includes('--help');\n\n/** The help text to print for `vitops <command> [sub] --help`. */\nexport function helpFor(command: string, argv: string[]): string {\n const sub = argv[0] && !argv[0].startsWith('-') ? argv[0] : undefined;\n return (\n (sub ? helpSection(command, sub) : undefined) ??\n helpSection(command) ??\n (command === 'search' ? SEARCH_HELP : command === 'ads' ? ADS_HELP : undefined) ??\n HELP\n );\n}\n","/**\n * Asking for the config values `vitops ads setup` cannot derive, and writing the\n * answers back.\n *\n * The realistic first run has no verification token in the config, because the\n * token does not exist until someone opens the platform UI and asks for one. That\n * makes a missing token a **question**, not an error — but only when there is\n * somebody there to answer it, which is why every decision about *whether* to ask\n * is made here and the planner stays pure.\n *\n * The split mirrors the rest of the toolchain: `questionFor` and `patchRaw` are\n * pure and tested; `ask` and `writeConfigPatch` are the I/O, and they decide\n * nothing.\n *\n * Two rules hold the whole file together:\n *\n * - **A prompt must never hang a CI run.** Asking requires a TTY and an explicit\n * absence of `--dry` / `--check` / `--no-prompt`; otherwise the caller gets the\n * same named error it would have got before this file existed.\n * - **A fact about the site goes in the config; a credential stays in the\n * environment.** A verification token is published in DNS — the platform\n * fetching it back is the ownership proof — so persisting it is right, and it is\n * the only thing here that gets written. `CLOUDFLARE_API_TOKEN` may be typed at\n * a prompt and lives only in the process.\n */\nimport { existsSync, readFileSync, writeFileSync } from 'node:fs';\nimport { createInterface } from 'node:readline/promises';\nimport { AD_PLATFORMS, type AdProvider, type MissingField } from '@getvitops/utils/ads';\n\nexport interface Question {\n provider: AdProvider;\n needs: MissingField;\n /** One line naming what is being asked for. */\n title: string;\n /** Where to get it — UI path first, then the URL. */\n hints: string[];\n /** The inline label the answer is typed after. */\n label: string;\n}\n\n/**\n * What to ask for one gap, and where the operator finds it.\n *\n * The hints are the point. \"meta.domainVerification is missing\" is true and\n * useless; the UI path plus the console URL is the difference between a prompt\n * someone can answer now and one they abandon to go searching.\n */\nexport function questionFor(provider: AdProvider, needs: MissingField): Question {\n const platform = AD_PLATFORMS[provider];\n if (needs === 'domainVerification') {\n return {\n provider,\n needs,\n title: `${platform.name} — domain verification token`,\n hints: [\n ...(platform.verification.where ? [platform.verification.where] : []),\n platform.consoleUrl,\n ],\n // The prefix is shown as part of the prompt so it is obvious the platform's\n // bare token is what goes here, not the whole record. `txtRecord` accepts\n // either, but showing the prefix stops the ambiguity arising at all.\n label: platform.verification.txtPrefix ?? 'token',\n };\n }\n const what =\n needs === 'pixelId'\n ? provider === 'google'\n ? 'conversion ID (AW-…, not the customer ID)'\n : 'pixel / tag ID'\n : 'advertising account ID';\n return {\n provider,\n needs,\n title: `${platform.name} — ${what}`,\n hints: [platform.consoleUrl],\n label: needs,\n };\n}\n\n/** The error a non-interactive run gets instead of a prompt. */\nexport function missingFieldMessage(provider: AdProvider, needs: MissingField): string {\n const q = questionFor(provider, needs);\n return (\n `site.ads.${provider}.${needs} is not set — ${q.title}.\\n` +\n q.hints.map((h) => ` ${h}`).join('\\n') +\n `\\n Run this interactively to be prompted for it, or add it to the config yourself.`\n );\n}\n\n/** Whether this run is allowed to ask. Everything that would hang CI is checked here. */\nexport function canPrompt(opts: {\n dry: boolean;\n check: boolean;\n noPrompt: boolean;\n isTty?: boolean | undefined;\n}): boolean {\n if (opts.dry || opts.check || opts.noPrompt) return false;\n return opts.isTty ?? Boolean(process.stdin.isTTY && process.stdout.isTTY);\n}\n\n/**\n * Ask one question. An empty answer means \"skip this one\" — reported as still\n * blocked rather than treated as a value, so nothing is written and nothing is\n * created on the strength of a stray Enter.\n */\nexport async function ask(q: Question): Promise<string | undefined> {\n const rl = createInterface({ input: process.stdin, output: process.stdout });\n try {\n console.log(`\\n${q.title}`);\n for (const hint of q.hints) console.log(` ${hint}`);\n const answer = (await rl.question(` ${q.label} `)).trim();\n return answer || undefined;\n } finally {\n rl.close();\n }\n}\n\n/**\n * Merge one ad-property field into a **raw, on-disk** config object.\n *\n * Raw is load-bearing, and it is the rule `@getvitops/vite`'s `designSystemPath()`\n * already follows for the theme editor's save: `resolveConfig` normalises shorthand\n * shapes and resolves `extends` in memory, so writing from the resolved object\n * would grow keys beside the author's and silently edit a copy nothing builds from.\n * Everything outside `site.ads.<provider>.<field>` is left exactly as it was.\n */\nexport function patchRaw(\n raw: unknown,\n provider: AdProvider,\n field: MissingField,\n value: string,\n): unknown {\n if (typeof raw !== 'object' || raw == null || Array.isArray(raw))\n throw new Error('config is not an object');\n const root = raw as Record<string, unknown>;\n const site = (root['site'] ?? {}) as Record<string, unknown>;\n const ads = (site['ads'] ?? {}) as Record<string, unknown>;\n const entry = (ads[provider] ?? {}) as Record<string, unknown>;\n return {\n ...root,\n site: { ...site, ads: { ...ads, [provider]: { ...entry, [field]: value } } },\n };\n}\n\n/** Indentation the file already uses, so a patch doesn't reformat the whole document. */\nfunction detectIndent(source: string): string | number {\n const match = /\\n([ \\t]+)\"/.exec(source);\n if (!match?.[1]) return 2;\n return match[1].includes('\\t') ? '\\t' : match[1].length;\n}\n\n/**\n * Persist one answered field into the config file.\n *\n * JSON only: a `.js`/`.ts` config is code, and rewriting code to insert a value is\n * a different (and much worse) problem than merging an object — so the caller is\n * told to paste it instead. Returns whether it wrote.\n */\nexport function writeConfigPatch(\n path: string,\n provider: AdProvider,\n field: MissingField,\n value: string,\n): { written: boolean; reason?: string } {\n if (!path.endsWith('.json'))\n return {\n written: false,\n reason: `${path} is a module, not JSON — add \"${field}\": \"${value}\" to site.ads.${provider} yourself`,\n };\n if (!existsSync(path)) return { written: false, reason: `${path} no longer exists` };\n const source = readFileSync(path, 'utf8');\n const raw: unknown = JSON.parse(source);\n const next = patchRaw(raw, provider, field, value);\n const trailingNewline = source.endsWith('\\n') ? '\\n' : '';\n writeFileSync(path, JSON.stringify(next, null, detectIndent(source)) + trailingNewline);\n return { written: true };\n}\n","/**\n * A minimal reader for hand-written CSS: rule selector, declarations as authored,\n * and the at-rule conditions the rule sits inside.\n *\n * **Why not lightningcss.** The generator owns it, and exposing an `analyzeCss`\n * from there was the obvious move — but lightningcss parses declarations into a\n * typed value model, and the typed model is exactly what these rules need to see\n * through. `display: flex` comes back as `pair`, `grid-template-columns: 1fr 1fr`\n * as `track-list`, and `margin-inline: auto` as an empty structured node. Every\n * rule here matches on *authored text*, so recovering it property-by-property\n * would mean re-implementing a serialiser for each one.\n *\n * A brace-depth scanner keeps the text intact, needs no native binary in the\n * CLI's dependency tree, and follows what `generate.ts` already does twice\n * (`stripForTailwind`, `isVariantBlock`).\n *\n * It is deliberately shallow: no specificity, no cascade, no `@supports`\n * semantics. It answers \"what did someone type in this rule\", which is all a\n * reuse suggestion needs.\n */\n\nexport interface CssDeclaration {\n property: string;\n value: string;\n}\n\nexport interface CssRule {\n selector: string;\n declarations: CssDeclaration[];\n /** Enclosing at-rule preludes, outermost first (`@media (min-width: 48rem)`). */\n conditions: string[];\n /** 1-indexed line of the selector. */\n line: number;\n}\n\n/** Strip comments, preserving newlines so line numbers survive. */\nfunction stripComments(css: string): string {\n return css.replace(/\\/\\*[\\s\\S]*?\\*\\//g, (m) => m.replace(/[^\\n]/g, ''));\n}\n\nconst lineAt = (src: string, index: number) => src.slice(0, index).split('\\n').length;\n\n/**\n * Parse declarations from a rule body. Splits on top-level `;` only, so a\n * `var(--x, a; b)` or a data URI cannot end a declaration early.\n */\nfunction parseDeclarations(body: string): CssDeclaration[] {\n const out: CssDeclaration[] = [];\n let depth = 0;\n let start = 0;\n const push = (chunk: string) => {\n const colon = chunk.indexOf(':');\n if (colon < 0) return;\n const property = chunk.slice(0, colon).trim();\n const value = chunk.slice(colon + 1).trim();\n // A nested block leaks in as a property containing `{`; skip it rather than\n // reporting a declaration that was never written.\n if (!property || property.includes('{') || !value) return;\n out.push({ property, value });\n };\n for (let i = 0; i < body.length; i++) {\n const ch = body[i];\n if (ch === '(' || ch === '[') depth++;\n else if (ch === ')' || ch === ']') depth--;\n else if (ch === ';' && depth === 0) {\n push(body.slice(start, i));\n start = i + 1;\n }\n }\n push(body.slice(start));\n return out;\n}\n\n/**\n * Scan a stylesheet into its style rules.\n *\n * Never throws: this runs over consumer source that may be a fragment, and a\n * linter that dies on one unparseable file is one nobody keeps in CI.\n */\nexport function scanCss(css: string): CssRule[] {\n const src = stripComments(css);\n const rules: CssRule[] = [];\n // Each open brace pushes its prelude; at-rule preludes become `conditions` for\n // everything nested inside, style-rule preludes become a selector.\n const stack: { prelude: string; index: number }[] = [];\n let depth = 0;\n let preludeStart = 0;\n\n for (let i = 0; i < src.length; i++) {\n const ch = src[i];\n if (ch === '\"' || ch === \"'\") {\n // Skip strings whole — a brace inside content: \"{\" would desync the depth.\n const quote = ch;\n i++;\n while (i < src.length && src[i] !== quote) {\n if (src[i] === '\\\\') i++;\n i++;\n }\n continue;\n }\n if (ch === '{') {\n const raw = src.slice(preludeStart, i);\n const prelude = raw.trim();\n // Offset of the first non-whitespace character, not of `preludeStart` —\n // that sits where the previous rule ended, so a rule's reported line would\n // be the blank line above it.\n stack.push({ prelude, index: preludeStart + raw.indexOf(prelude.slice(0, 1)) });\n depth++;\n preludeStart = i + 1;\n continue;\n }\n if (ch === '}') {\n const frame = stack.pop();\n depth--;\n if (frame && !frame.prelude.startsWith('@')) {\n // A style rule: its body is everything since it opened, minus any nested\n // blocks, which `parseDeclarations` discards.\n const bodyStart = src.indexOf('{', frame.index) + 1;\n rules.push({\n selector: frame.prelude,\n declarations: parseDeclarations(src.slice(bodyStart, i)),\n conditions: stack.filter((f) => f.prelude.startsWith('@')).map((f) => f.prelude),\n line: lineAt(src, frame.index),\n });\n }\n preludeStart = i + 1;\n continue;\n }\n }\n // Unbalanced braces (a fragment, a truncated file) leave frames on the stack;\n // returning what was parsed beats reporting nothing.\n return rules.filter((r) => r.selector && depth >= 0);\n}\n\n/** `<style>` block contents from an .astro/.vue/.svelte/.html file. */\nexport function extractStyleBlocks(src: string): { css: string; line: number }[] {\n const out: { css: string; line: number }[] = [];\n for (const m of src.matchAll(/<style\\b[^>]*>([\\s\\S]*?)<\\/style>/gi)) {\n // Offset so a finding's line number points into the original file, not into\n // the extracted block.\n const line = lineAt(src, (m.index ?? 0) + m[0].indexOf('>') + 1);\n out.push({ css: m[1] ?? '', line });\n }\n return out;\n}\n","/**\n * The inverse of `lint.ts`: hand-written CSS that re-implements a framework\n * primitive.\n *\n * `lint.ts` catches a class that resolves to nothing — you named something and it\n * isn't there. This catches the costlier direction, where the code *works*: a\n * centred container written by hand, a two-column split behind a media query, a\n * flex row. Nothing is broken, so nothing ever surfaces it, and the design system\n * quietly stops being the place those decisions live.\n *\n * Every finding here is a `suggestion`, never an `error`. These are judgement\n * calls — a rule can be right about the pattern and wrong about the intent — and\n * a reuse hint that failed CI on the day it shipped would be a worse defect than\n * the drift it reports. `--strict` is there for consumers who want the ratchet.\n *\n * Rules stay conservative on purpose: each requires the *combination* that makes\n * the intent unambiguous. `margin-inline: auto` alone is not a centred track;\n * `display: flex` alone is not a cluster.\n */\nimport type { Format } from '@getvitops/generator';\nimport { type CssRule, extractStyleBlocks, scanCss } from './css-scan.ts';\nimport type { LintFinding } from './lint.ts';\n\n/**\n * The framework's own track widths. Declared in two places today\n * (`core/css/layout.css` and the tailwind emitter), so a rule keyed to the token\n * NAME rather than to a value survives either one moving.\n */\nconst TRACK_WIDTHS = ['--width-measure', '--width-breakout', '--width-spotlight'];\n\n/**\n * Class names that mean \"the thing that constrains page width\".\n *\n * The token-anchored rule below only fires once someone already knows about\n * `--width-measure`, which is precisely the author who was never going to\n * hand-roll a container. The reported failure was the other author: agents\n * inventing a `.wrap` from scratch, with a plain pixel `max-width`, on site after\n * site. `wrap` is also the more *available* name for the concept, so it wins the\n * naming race against `.centered` every time unless something says otherwise.\n *\n * Matched on the name only in combination with a width-constraining declaration —\n * a `.wrapper` that merely sets `display: flex` is not this pattern.\n */\nconst CONTAINER_NAMES = [\n 'wrap',\n 'wrapper',\n 'container',\n 'inner',\n 'outer',\n 'content-wrap',\n 'content-wrapper',\n 'page-wrap',\n 'page-wrapper',\n 'site-wrap',\n 'site-wrapper',\n 'shell',\n 'constrain',\n 'measure',\n];\n\n/**\n * Page scale, as a rem-equivalent, above which a width cap is a *container*\n * rather than an element.\n *\n * Keyed to the framework's own `md` breakpoint (48rem) rather than to a number\n * picked for this rule, and it is what keeps a capped figure quiet — someone\n * writing `max-width: 40rem` on an image is not reinventing `.centered`.\n */\nconst PAGE_SCALE_REM = 48;\n/** The same line in `ch`, where a width cap is a reading measure by construction. */\nconst PAGE_SCALE_CH = 40;\n\n/**\n * The largest length in a width value, as a rem-equivalent — so `min(100%,\n * 1200px)` and `clamp(20rem, 90vw, 75rem)` are read at their cap rather than\n * skipped for not being a bare length.\n *\n * Relative-to-viewport units (`%`, `vw`, `vmin`) are deliberately ignored: they\n * express \"as wide as there is\", which is not a container cap.\n */\nfunction widthScale(value: string): { rem: number; ch: number } {\n let rem = 0;\n let ch = 0;\n for (const m of value.matchAll(/([\\d.]+)(rem|px|em|ch)\\b/g)) {\n const n = Number(m[1]);\n if (!Number.isFinite(n)) continue;\n if (m[2] === 'ch') ch = Math.max(ch, n);\n else rem = Math.max(rem, m[2] === 'px' ? n / 16 : n);\n }\n return { rem, ch };\n}\n\n/**\n * Column ratios that correspond to a `split-<a>-<b>` class.\n *\n * `.split` is FLEX, not grid — `display: flex` with `flex: 1` children, and a\n * ratio class setting `--_split-a`/`--_split-b`. Equal columns are the base\n * `.split` with no ratio class, which is why `1fr 1fr` is deliberately absent:\n * suggesting `split-1-1` would name a class that does not exist, and this file\n * would then be committing the very defect `lint.ts` reports.\n */\nconst SPLITS: Record<string, string> = {\n '1fr 2fr': '1-2',\n '2fr 1fr': '2-1',\n '1fr 3fr': '1-3',\n '3fr 1fr': '3-1',\n '1fr 4fr': '1-4',\n '4fr 1fr': '4-1',\n '2fr 3fr': '2-3',\n '3fr 2fr': '3-2',\n};\n\nconst decl = (rule: CssRule, property: string) =>\n rule.declarations.find((d) => d.property === property)?.value;\n\n/** Is this rule inside a `min-width` media or container query? */\nconst inMinWidthQuery = (rule: CssRule) => rule.conditions.some((c) => /min-width\\s*:/.test(c));\n\n/** The framework breakpoint a `min-width` condition corresponds to, if any. */\nfunction breakpointOf(rule: CssRule): string | null {\n const rem = rule.conditions.map((c) => /min-width\\s*:\\s*([\\d.]+)rem/.exec(c)?.[1]).find(Boolean);\n if (!rem) return null;\n const n = Number(rem);\n // The framework's container breakpoints: sm/md/lg/xl = 30/48/64/80rem.\n return n >= 80 ? 'xl' : n >= 64 ? 'lg' : n >= 48 ? 'md' : n >= 30 ? 'sm' : null;\n}\n\n/** Spell a responsive utility the way the target format actually emits it. */\nconst responsive = (bp: string, base: string, format: Format) =>\n format === 'tailwind' ? `@${bp}:${base}` : `${bp}-${base}`;\n\ntype Verdict = Omit<LintFinding, 'file' | 'line'>;\n\n/**\n * One rule = one check. Kept as data rather than a chain of ifs so adding a\n * primitive is adding an entry, and so each carries its own explanation.\n */\nconst RULES: ((rule: CssRule, format: Format) => Verdict | null)[] = [\n // ── a centred track, written by hand ──────────────────────────────────────\n //\n // Three ways in, one verdict. They are one rule rather than three because they\n // describe the same mistake and a rule reports once — a `.wrap` with a pixel cap\n // and auto margins trips all three, and three findings on one line would read as\n // three problems.\n (rule) => {\n const cap = decl(rule, 'max-inline-size') ?? decl(rule, 'max-width') ?? decl(rule, 'width');\n const centred = /\\bauto\\b/.test(decl(rule, 'margin-inline') ?? decl(rule, 'margin') ?? '');\n if (!cap) return null;\n\n const token = TRACK_WIDTHS.find((t) => cap.includes(t));\n const { rem, ch } = widthScale(cap);\n const pageScale = rem >= PAGE_SCALE_REM || ch >= PAGE_SCALE_CH;\n // A container-shaped NAME lowers the bar to any cap at all: the name is the\n // stated intent, so the value no longer has to prove it.\n const named = CONTAINER_NAMES.some((n) =>\n // `[-_]+` rather than `[-_]`, so BEM's `__` separator is one boundary:\n // `.site-header__inner` is the container here, and requiring a single\n // separator missed every element-notation selector.\n new RegExp(`[.#]([a-z0-9]+[-_]+)*${n}([-_]+[a-z0-9]+)*\\\\b`, 'i').test(rule.selector),\n );\n\n // What makes each trigger unambiguous. A framework track token or a\n // container-shaped name is enough on its own; a bare length has to be both\n // page-scale AND centred, or it is just a capped element.\n const why = token\n ? `it caps width at \\`var(${token})\\`, a framework track`\n : named\n ? `\\`${rule.selector.trim()}\\` names a page container`\n : pageScale && centred\n ? `it caps width at page scale and centres with auto margins`\n : null;\n if (!why) return null;\n if (token && !centred) return null;\n\n return {\n cls: `${rule.selector} { ${cap.length > 40 ? 'width cap' : `max-width: ${cap}`} }`,\n severity: 'suggestion',\n reason: `\\`.centered\\` is this pattern — ${why}`,\n suggestion:\n 'use `.centered`. It is a grid of named tracks, not a max-width box, so a child ' +\n 'opts into a wider track with `breakout`, `spotlight` or `fullbleed` on itself — ' +\n 'a hand-rolled container has no answer for the full-bleed image except more CSS',\n };\n },\n\n // ── a two-column split behind a breakpoint ────────────────────────────────\n (rule, format) => {\n const cols = decl(rule, 'grid-template-columns');\n if (!cols || !inMinWidthQuery(rule)) return null;\n const ratio = SPLITS[cols.replace(/\\s+/g, ' ').trim()];\n const bp = ratio && breakpointOf(rule);\n if (!ratio || !bp) return null;\n return {\n cls: `${rule.selector} { grid-template-columns: ${cols} }`,\n severity: 'suggestion',\n reason: `a ${cols} split behind a min-width query is the \\`split-${ratio}\\` utility`,\n suggestion:\n `${responsive(bp, `split-${ratio}`, format)} on the container — the responsive form is ` +\n 'equal below the breakpoint and takes the ratio above it, which is what the query is doing by hand',\n };\n },\n\n // ── a repeated-item grid, which is what `.subgrid` is for ─────────────────\n //\n // Deliberately NOT gated on a media query, which is what keeps it off the split\n // rule's territory: a `repeat()` is a set of like items, an explicit `1fr 2fr`\n // is two different panels. The two cannot both fire on one rule anyway — this\n // requires `repeat()` and the split requires a `min-width` condition.\n (rule) => {\n const cols = decl(rule, 'grid-template-columns');\n if (!cols || !/^\\s*repeat\\(/i.test(cols)) return null;\n if (!/\\bgrid\\b/.test(decl(rule, 'display') ?? '')) return null;\n // `subgrid` in the same rule means this IS the framework pattern, being\n // configured or extended rather than replaced.\n if (rule.declarations.some((d) => /subgrid/.test(d.value))) return null;\n\n const count = /^\\s*repeat\\(\\s*(\\d+)/i.exec(cols)?.[1];\n const auto = /^\\s*repeat\\(\\s*auto-(fit|fill)/i.test(cols);\n if (!count && !auto) return null;\n if (count && Number(count) < 2) return null;\n\n return {\n cls: `${rule.selector} { grid-template-columns: ${cols} }`,\n severity: 'suggestion',\n reason:\n 'a grid of repeated items is `.subgrid` — a plain grid aligns the outer boxes but ' +\n 'not the tranches inside them, so headings, bodies and footers land at different ' +\n 'heights across the set',\n suggestion: auto\n ? '`.subgrid subgrid-responsive` (2 columns under 60rem, 1 under 40rem) with ' +\n '`--subgrid-row-span` set to the number of row bands each item contains — or ' +\n '`.grid-auto` with `--grid-min`, which is the framework class for this exact ' +\n 'auto-fit track and the right answer when the items have no tranches to align'\n : `\\`.subgrid subgrid-cols-${count}\\`, with \\`--subgrid-row-span\\` (or ` +\n '`subgrid-rows-<n>`) set to the number of row bands each item contains — and ' +\n '`.subgrid-card` on the items to get an edge-bled `__media` and a pinned `__footer`',\n };\n },\n\n // ── a flex row with centred items ─────────────────────────────────────────\n (rule, format) => {\n if (decl(rule, 'display') !== 'flex') return null;\n if (decl(rule, 'align-items') !== 'center') return null;\n if (/column/.test(decl(rule, 'flex-direction') ?? '')) return null;\n return {\n cls: `${rule.selector} { display: flex; align-items: center }`,\n severity: 'suggestion',\n reason: 'the framework has this as utilities',\n suggestion:\n format === 'tailwind'\n ? \"Tailwind's own `flex items-center` (the framework drops these names in this format)\"\n : '`flex items-center`, or `.cluster-start` if this is a row of related controls',\n };\n },\n];\n\n/**\n * Lint stylesheets and the `<style>` blocks of component files.\n *\n * `files` carries raw text, same as `lintSource` — this module stays free of the\n * filesystem so the caller owns discovery.\n */\n/**\n * The banner every generated stylesheet opens with.\n *\n * Linting the generator's own output is the worst false positive this tool can\n * produce: the emitted bundle contains the framework's real implementations of\n * these very patterns, so it reports `.split` as reinventing `.split`. The\n * `css` format writes `styles.css` into the consumer's source tree (`src/styles`\n * by default), which is squarely inside what `--src` scans.\n *\n * Matched on the banner rather than on a path, because the output directory is\n * configurable and a path rule would silently stop working when someone changes\n * it.\n */\n// Case-sensitive on purpose: the banner shouts `GENERATED`, and matching it\n// case-insensitively also swallowed an authored `/* generated content here */`.\nconst GENERATED = /^\\s*\\/\\*!?\\s*GENERATED\\b|do not edit by hand\\./;\n\nexport function lintCss(files: { path: string; text: string }[], format: Format): LintFinding[] {\n const findings: LintFinding[] = [];\n const seen = new Set<string>();\n for (const file of files) {\n if (GENERATED.test(file.text.slice(0, 400))) continue;\n // A .css file is one block starting at line 1; a component file may hold\n // several, each offset to where its <style> opens so a reported line points\n // into the original file rather than into the extracted block.\n const blocks = file.path.endsWith('.css')\n ? [{ css: file.text, line: 1 }]\n : extractStyleBlocks(file.text);\n for (const block of blocks)\n for (const rule of scanCss(block.css))\n for (const check of RULES) {\n const verdict = check(rule, format);\n if (!verdict) continue;\n const line = block.line + rule.line - 1;\n const key = `${file.path}:${line}:${verdict.reason}`;\n if (seen.has(key)) continue;\n seen.add(key);\n findings.push({ file: file.path, line, ...verdict });\n break; // one suggestion per rule — the first match wins\n }\n }\n return findings;\n}\n","/**\n * The third linting direction: markup that lays out a repeated set of things\n * without the framework's pattern for it.\n *\n * `lint.ts` catches a class that resolves to nothing. `lint-css.ts` catches\n * hand-written CSS that re-implements a primitive. Neither reaches the most common\n * reported drift, because it involves no bad class and no hand-written CSS at all:\n * a page renders a list of cards with `class=\"grid\"`, or with nothing, and every\n * class in it is real. The design system has `.subgrid` for exactly this and it\n * goes unused, so across three cards the headings sit at three heights and the\n * CTAs float wherever the copy ended.\n *\n * That cannot be judged from a class token in isolation, so this module is the one\n * that looks at *shape*: is there a repeated card construct here, and is it inside\n * a subgrid?\n *\n * **It is heuristic, and the heuristics are chosen to under-report.** Every finding\n * is a `suggestion`, at most one per file, and each requires a repetition signal\n * strong enough to state in the message: a loop that renders a card, or three or\n * more sibling cards written out. Two cards in a file is not enough — they are as\n * likely to be in unrelated sections, and a rule that fires there would teach\n * people to stop reading the output, which costs more than the drift.\n */\nimport { extname } from 'node:path';\nimport type { LintFinding } from './lint.ts';\n\n/**\n * Only real markup is examined.\n *\n * Markdown is excluded on purpose, and it is the exclusion that matters most: a\n * `.md` file is as likely to *discuss* `.card` as to use it. Run against this\n * repo's own docs site, the first version reported `changelog.md` and two\n * generated reference pages — prose about the framework, counted as drift by it.\n * A consumer's markdown content can hold real markup, so this does give up a\n * little coverage; that is the right side to err on for a heuristic.\n */\nconst MARKUP_EXT = new Set([\n '.astro',\n '.html',\n '.htm',\n '.jsx',\n '.tsx',\n '.vue',\n '.svelte',\n '.ts',\n '.js',\n]);\n\n/**\n * A class attribute's value, in the spellings the supported frameworks use.\n * Mirrors `lint.ts`'s extractor — the token must be in a real `class`, not merely\n * somewhere in the file.\n */\nconst CLASS_ATTR =\n /(?:class|className|class:list)\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)'|\\{`([^`]*)`\\}|\\{([^}]*)\\})/g;\n\n/**\n * The card-ish classes worth caring about.\n *\n * Anchored to `card` as a whole word or suffix, which covers the framework's own\n * `card` / `subgrid-card` / `pricing-card` and a consumer's `service-card` alike.\n * Not `*-item` or `*-tile`: too many of those are not laid out as a set.\n */\nconst CARD_CLASS = /(?:^|[\\s\"'`])((?:[a-z0-9]+-)*card)(?:__[a-z0-9-]+)?(?=[\\s\"'`]|$)/i;\n\n/** Every card class named in a real class attribute, with its offset in `src`. */\nfunction cardsInClassAttrs(src: string): { name: string; index: number }[] {\n const out: { name: string; index: number }[] = [];\n for (const m of src.matchAll(CLASS_ATTR)) {\n const value = m[1] ?? m[2] ?? m[3] ?? m[4] ?? '';\n for (const tok of value.split(/[\\s'\"`]+/)) {\n const card = CARD_CLASS.exec(` ${tok} `);\n // Element classes (`card__body`) belong to a card already counted by its\n // block class — counting them would report every single-card file as three.\n if (card && !tok.includes('__')) out.push({ name: card[1] as string, index: m.index ?? 0 });\n }\n }\n return out;\n}\n\n/**\n * Already using the pattern — in any tier's spelling.\n *\n * `<Cards>` and `<wc-cards>` count: `<Cards>` renders a `Subgrid`, and `<wc-cards>`\n * only ever wraps one. Omitting them reported a correct card grid as a missed one.\n */\nconst HAS_SUBGRID = /\\bsubgrid\\b|<Subgrid\\b|<Cards\\b|<wc-cards\\b/;\n\n/**\n * Constructs that render one item many times.\n *\n * The JS/Astro/JSX `.map(`, and the block forms Svelte/Vue/Handlebars use. A loop\n * whose body contains a card is a repeated card set by construction — no counting\n * and no sibling analysis needed, which is why it is the primary signal.\n */\nconst LOOPS = [/\\.\\s*map\\s*\\(/g, /\\{#each\\b/g, /v-for\\s*=/g, /\\{%\\s*for\\b/g];\n\n/** Line number of a character offset. */\nconst lineAt = (src: string, index: number) => src.slice(0, index).split('\\n').length;\n\n/**\n * The body of a loop, approximated by taking the text that follows it.\n *\n * A real brace-matcher would be more precise and is not worth it: the question is\n * only \"does a card appear inside this repetition\", and a card 600 characters past\n * a `.map(` is inside it in every realistic template. Over-reaching here can only\n * produce a suggestion on a file that does render cards somewhere.\n */\nconst LOOP_WINDOW = 600;\n\ninterface CardSignal {\n line: number;\n /** What made this a repeated set, phrased for the message. */\n evidence: string;\n cls: string;\n}\n\n/** The strongest repetition signal in one file, or none. */\nfunction cardSignal(text: string): CardSignal | null {\n const cards = cardsInClassAttrs(text);\n if (!cards.length) return null;\n\n // ── a loop that renders a card ────────────────────────────────────────────\n // The stronger signal, and it needs no counting: one card inside a repetition\n // is a set by construction.\n for (const loop of LOOPS)\n for (const m of text.matchAll(loop)) {\n const start = (m.index ?? 0) + m[0].length;\n const card = cards.find((c) => c.index >= start && c.index < start + LOOP_WINDOW);\n if (!card) continue;\n return {\n line: lineAt(text, m.index ?? 0),\n evidence: `a \\`${m[0].trim()}\\` loop renders \\`.${card.name}\\``,\n cls: `${m[0].trim()} … .${card.name}`,\n };\n }\n\n // ── three or more cards written out ──────────────────────────────────────\n if (cards.length >= 3) {\n const first = cards[0] as { name: string; index: number };\n return {\n line: lineAt(text, first.index),\n evidence: `\\`.${first.name}\\` appears on ${cards.length} elements in this file`,\n cls: `.${first.name} ×${cards.length}`,\n };\n }\n return null;\n}\n\n/**\n * Lint markup for repeated card sets laid out without `.subgrid`.\n *\n * Takes raw text like the other linters — discovery stays with the caller. One\n * finding per file: the drift is a decision about a layout, not about a line, and\n * repeating it per card would bury every other finding the command prints.\n */\n/**\n * An anchor carrying a card class inside a subgrid.\n *\n * The shape everyone reaches for when the whole card is a link — and it renders\n * fine, which is why it survives. The `<li>` is the grid item, so the anchor is an\n * ordinary block inside it and the tranches within the anchor never reach the\n * parent's shared row lines: the alignment `.subgrid` exists for silently does not\n * happen, and the anchor doesn't fill the cell either. This is the one markup\n * finding that reports a *broken* result rather than a missed primitive.\n */\nconst LINK_CARD = /<a\\b[^>]*\\bclass(?:Name)?\\s*=\\s*[\"'{][^\"'}]*\\b(?:[a-z0-9]+-)*card\\b/gi;\n\n/**\n * Is this offset inside an `<li>`?\n *\n * The rule's claim is \"the anchor is nested inside the grid item rather than being\n * it\", and only an anchor within an `<li>` is that. Checking the file merely\n * *mentions* subgrid is far too coarse: a page documenting several patterns tripped\n * on a standalone `<a class=\"tile card\">`, which is a perfectly good anchor-as-card —\n * outside a grid there is no grid item for it to compete with.\n */\nfunction insideListItem(text: string, index: number): boolean {\n const before = text.slice(0, index);\n return before.lastIndexOf('<li') > before.lastIndexOf('</li');\n}\n\nfunction linkCardFinding(file: { path: string; text: string }): LintFinding | null {\n const m = [...file.text.matchAll(LINK_CARD)].find((hit) =>\n insideListItem(file.text, hit.index ?? 0),\n );\n if (!m || m.index === undefined) return null;\n return {\n file: file.path,\n line: lineAt(file.text, m.index),\n cls: '<a class=\"…card\">',\n severity: 'suggestion',\n reason:\n 'a card class on an `<a>` inside a `subgrid` does not align — the `<li>` is the grid ' +\n \"item, so the anchor's tranches never reach the parent's shared row lines, and the \" +\n 'anchor does not fill the cell either. It renders, it just silently is not a subgrid',\n suggestion:\n 'keep the card as the item (`<li class=\"card subgrid-card\">`) and make the whole card ' +\n 'clickable from inside it — either `class=\"stretched-link\"` on a link (no JS, but the ' +\n \"card's text stops being selectable) or `<Cards>` / `<wc-cards>` around the list \" +\n '(keeps selection, needs JS, falls back to the link). Both keep the accessible name on ' +\n 'real text. Lift anything that must stay above a stretched overlay with `raised`',\n };\n}\n\n/**\n * `.stretched-link` inside `<wc-cards>` — the two whole-card-click mechanisms layered.\n *\n * They are alternatives, not layers, and combining them is silently the worse of the\n * two: the overlay takes the pointer-drag, so the card's text stops being selectable\n * — which is the only reason to reach for `<wc-cards>` — and the element's\n * click-vs-drag logic never gets a chance to run, because the browser follows the\n * overlaid link natively first.\n */\nconst WC_CARDS = /<wc-cards\\b|<Cards\\b/;\nconst STRETCHED = /\\bclass(?:Name)?\\s*=\\s*[\"'{][^\"'}]*\\bstretched-link\\b/;\n\nfunction layeredCardLinkFinding(file: { path: string; text: string }): LintFinding | null {\n if (!WC_CARDS.test(file.text)) return null;\n const m = STRETCHED.exec(file.text);\n if (!m) return null;\n return {\n file: file.path,\n line: lineAt(file.text, m.index),\n cls: 'stretched-link inside wc-cards',\n severity: 'suggestion',\n reason:\n '`.stretched-link` and `<wc-cards>` are two ways to do the same thing, and layering ' +\n \"them silently picks the worse one — the overlay takes the pointer-drag, so the card's \" +\n 'text is no longer selectable, which is the only reason to use `<wc-cards>` at all',\n suggestion:\n 'drop one. Keep `stretched-link` and use `<Subgrid>` if you want zero JS and can accept ' +\n 'unselectable card text; keep `<Cards>` / `<wc-cards>` and remove `stretched-link` if ' +\n 'selectable text matters — the plain `link` class on the heading is then the fallback',\n };\n}\n\nexport function lintMarkup(files: { path: string; text: string }[]): LintFinding[] {\n const findings: LintFinding[] = [];\n for (const file of files) {\n if (!MARKUP_EXT.has(extname(file.path).toLowerCase())) continue;\n // Layering the two whole-card-click mechanisms is judged wherever it appears —\n // `<wc-cards>` governs any container, not only a subgrid.\n const layered = layeredCardLinkFinding(file);\n if (layered) findings.push(layered);\n if (HAS_SUBGRID.test(file.text)) {\n // Already using the pattern, so the missed-primitive rule does not apply —\n // but the link-card mistake only exists *inside* a subgrid, so it is checked\n // here rather than skipped with everything else.\n const broken = linkCardFinding(file);\n if (broken) findings.push(broken);\n continue;\n }\n const signal = cardSignal(file.text);\n if (!signal) continue;\n // `.grid-auto` and `.grid` ARE framework classes, so a message implying no\n // framework layout was used would be wrong on exactly the sites that are\n // trying — and a linter that misreads what you wrote stops being read. The\n // point stands either way; only the framing changes.\n const usingGrid = /\\bgrid-auto\\b|class(?:Name)?=\"[^\"]*\\bgrid\\b/.test(file.text);\n findings.push({\n file: file.path,\n line: signal.line,\n cls: signal.cls,\n severity: 'suggestion',\n reason:\n `${signal.evidence}, ${\n usingGrid\n ? 'laid out with a plain grid rather than a `subgrid`'\n : 'and nothing here is a `subgrid`'\n } — more than one card is what \\`.subgrid\\` is for. A plain grid aligns the outer boxes ` +\n \"but not the tranches inside them, so the set's headings, bodies and footers land at \" +\n 'different heights',\n suggestion:\n '`<ul class=\"subgrid subgrid-cols-3\" role=\"list\">` with ' +\n '`<li class=\"card subgrid-card\">` items (a set of cards is a list; `role=\"list\"` is ' +\n 'needed because `.subgrid` is markerless and Safari stops announcing a marker-less ' +\n '`ul` as a list); set `--subgrid-row-span` to the number of row bands each card ' +\n 'contains. In Astro, `<Subgrid />` adds the role for you. If the items genuinely have ' +\n 'no internal tranches to align (a bare image gallery), `.grid-auto` is the right call ' +\n 'and this is a false positive',\n });\n }\n return findings;\n}\n","/**\n * `vitops lint` — find pre-1.0 colour-grammar token references in consumer\n * source, and rewrite them.\n *\n * The class linter (`lint.ts`) reads `class` attributes; this reads `var(--…)`\n * out of CSS and `<style>` blocks, which is the other half of where a design\n * system is referenced and the half nothing checked. `validate()` covers the\n * same grammar inside a `design-system.json`; a consumer's own stylesheets are\n * outside that file and were entirely unguarded.\n *\n * **Why a codemod and not just a report.** The 1.0 rename is mechanical, and a\n * downstream consumer did it by hand — correctly, but only because they noticed\n * that applying the renames *sequentially* compounds them. A surface role's\n * backgrounds rotate (`--surface-bg` → `--color-bg-surface-muted`,\n * `--surface-bg-bold` → `--color-bg-surface`), so a naive\n * find-and-replace-each-in-turn walks a value through two renames and lands\n * somewhere neither table entry names. `applyRenames` builds one alternation and\n * rewrites in a single pass, which makes simultaneity structural rather than\n * something the operator has to know.\n */\nimport type { LintFinding } from './lint.ts';\n\n/** A rewrite this tool can perform without a judgement call. */\nexport interface TokenFix {\n from: string;\n to: string;\n}\n\n/**\n * Rewrite every old name in one pass.\n *\n * Longest-first alternation so a name that is a prefix of another (`--x-bg` vs\n * `--x-bg-bold`) cannot be matched short, and a single `replace` so no output of\n * one rename is ever input to the next.\n */\nexport function applyRenames(text: string, renames: Record<string, string>): string {\n const names = Object.keys(renames).sort((a, b) => b.length - a.length);\n if (!names.length) return text;\n const escaped = names.map((n) => n.replaceAll(/[.*+?^${}()|[\\]\\\\]/g, String.raw`\\$&`));\n // `(?![\\w-])` so `--brand-bg` does not match inside `--brand-bg-bold` — the\n // longest-first ordering handles the listed names, this handles unlisted ones.\n const re = new RegExp(`(${escaped.join('|')})(?![\\\\w-])`, 'g');\n return text.replace(re, (m) => renames[m] ?? m);\n}\n\n/** Every `var(--name)` in a text, with its line number. */\nfunction varRefs(src: string): { name: string; line: number }[] {\n const out: { name: string; line: number }[] = [];\n for (const m of src.matchAll(/var\\(\\s*(--[\\w-]+)/g))\n out.push({ name: m[1] as string, line: src.slice(0, m.index).split('\\n').length });\n return out;\n}\n\n/**\n * Report old-grammar token references in source files.\n *\n * `renames` comes from the generator's `movedTokens()`, built from the\n * consumer's own role names — there is no fixed list, which is why nothing\n * detected these before.\n */\nexport function lintTokens(\n files: { path: string; text: string }[],\n renames: Record<string, string>,\n): (LintFinding & { fix: TokenFix })[] {\n const findings: (LintFinding & { fix: TokenFix })[] = [];\n const seen = new Set<string>();\n for (const f of files)\n for (const { name, line } of varRefs(f.text)) {\n const to = renames[name];\n if (to == null) continue;\n const key = `${f.path}:${line}:${name}`;\n if (seen.has(key)) continue;\n seen.add(key);\n findings.push({\n file: f.path,\n line,\n cls: `var(${name})`,\n severity: 'error',\n reason: `\\`${name}\\` is the pre-1.0 colour grammar and resolves to nothing`,\n suggestion: `var(${to})`,\n fix: { from: name, to },\n });\n }\n return findings;\n}\n","/**\n * `vitops lint` — find framework classes in consumer source that resolve to\n * nothing in the format being built.\n *\n * The problem this exists for: an unknown utility class is indistinguishable\n * from a working one. Nothing errors, nothing warns, the element just doesn't\n * get the style. Two shapes of that were found in a real consumer site:\n *\n * • `bg-navy-d` — a leftover from the named-step scale (`d`/`xd`/`xxd`)\n * deleted in favour of numeric steps. The hue is real, the step is not.\n * It appeared ~10× and looked fine only because the `.card` it sat on\n * supplied its own background.\n * • `md-flex-row` — the css/bricks spelling of a responsive variant, used in\n * a `tailwind`-format project where that class is never emitted (Tailwind\n * regenerates those on demand as `@md:`). Silently inert.\n *\n * DESIGN: this deliberately only inspects classes ANCHORED TO THE CONSUMER'S\n * OWN CONFIG — a hue name, a role name, a type role, a shadow, a pattern. It\n * never tries to enumerate \"all valid classes\", because in the tailwind format\n * that would mean knowing Tailwind's entire built-in vocabulary, and every\n * unknown would be a false positive. Anchoring means a finding is always\n * actionable: you named something from your design system, and it doesn't\n * resolve.\n */\nimport { NUMERIC_STEPS, type DesignSystem, type Format } from '@getvitops/generator';\n\n/**\n * `error` — you named something from your design system and it resolves to\n * nothing. Always actionable, and fails the command.\n *\n * `suggestion` — the code works, but the framework already has a primitive for\n * it. Advisory by design: these are judgement calls, and a new rule that failed\n * CI on first run would be a worse defect than the drift it reports. `--strict`\n * promotes them for consumers who want the ratchet.\n */\nexport type LintSeverity = 'error' | 'suggestion';\n\nexport interface LintFinding {\n file: string;\n line: number;\n /** The class token, or for a CSS rule the declaration that triggered it. */\n cls: string;\n reason: string;\n suggestion?: string;\n severity: LintSeverity;\n}\n\nconst UTIL_FAMILIES = ['bg', 'text', 'icon', 'border', 'outline', 'fill', 'stroke'];\nconst BREAKPOINTS = ['sm', 'md', 'lg', 'xl'];\n\n/**\n * The modifiers actually emitted for one family + role, read back out of the\n * generator's own class list.\n *\n * This used to be a hand-maintained array, which is the wrong shape for a\n * suggestion: the two role kinds emit different modifiers (a chromatic role has\n * `solid` and no bare form; a surface role the reverse), so a single list was\n * wrong for one of them no matter what it said.\n */\nconst emittedModifiers = (roleClasses: Set<string>, fam: string, role: string): string[] => {\n const prefix = `${fam}-${role}`;\n return [...roleClasses]\n .filter((c) => c === prefix || c.startsWith(`${prefix}-`))\n .map((c) => c.slice(prefix.length + 1))\n .filter(Boolean)\n .sort();\n};\n\n/** Everything the config makes namable, so we only judge classes we can judge. */\ninterface Vocabulary {\n roles: string[];\n hues: string[];\n steps: string[];\n typeRoles: string[];\n shadows: string[];\n patterns: string[];\n /** Every role utility the generator actually emits, e.g. `bg-surface-x-muted`. */\n roleClasses: Set<string>;\n}\n\nexport function vocabulary(ds: DesignSystem, roleClasses: Iterable<string>): Vocabulary {\n return {\n roles: Object.keys(ds.colors?.roles ?? {}),\n hues: Object.keys(ds.colors?.palette ?? {}),\n steps: [...NUMERIC_STEPS],\n typeRoles: Object.keys(ds.typography?.roles ?? {}),\n shadows: Object.keys(ds.shadows ?? {}),\n patterns: Object.keys(ds.patterns?.items ?? {}),\n roleClasses: new Set(roleClasses),\n };\n}\n\n/**\n * Strip variant prefixes (`@md:`, `hover:`, `dark:`) from a candidate.\n *\n * Format-aware, because the container-query spelling only exists in tailwind.\n * Stripping `@md:` unconditionally made the check asymmetric: `md-split-1-2` in a\n * tailwind project was caught, but `@md:split-1-2` in a css/bricks project became\n * a bare `split-1-2` that matched nothing and returned null — the same silent\n * no-op, in the other direction, unreported.\n */\nconst stripVariants = (cls: string, format: Format): string => {\n let out = cls;\n while (/^@?[a-zA-Z0-9_-]+:/.test(out)) {\n if (format !== 'tailwind' && out.startsWith('@')) break;\n out = out.slice(out.indexOf(':') + 1);\n }\n return out;\n};\n\nconst nearest = (want: string, pool: string[]): string | undefined =>\n pool.find((p) => p.startsWith(want) || want.startsWith(p));\n\n/**\n * Judge one class token. Returns null when the class is none of our business —\n * which is the common case and the whole reason this is low-noise.\n */\nexport function judge(\n raw: string,\n v: Vocabulary,\n format: Format,\n): Omit<LintFinding, 'file' | 'line'> | null {\n const cls = stripVariants(raw, format);\n\n // ── the `@<bp>:` container-query spelling, in a format that has none ───────\n // Tailwind's engine expands these; css/bricks ship pre-expanded `<bp>-` classes\n // instead, so this spelling resolves to nothing there.\n const cq = /^@(sm|md|lg|xl):(.+)$/.exec(cls);\n if (cq && format !== 'tailwind')\n return {\n cls: raw,\n severity: 'error' as const,\n reason: `\\`@${cq[1]}:\\` container-query variants are a tailwind-format spelling; the ${format} format emits pre-expanded classes`,\n suggestion: `${cq[1]}-${cq[2]}`,\n };\n\n // ── the `<bp>-` responsive spelling ────────────────────────────────────────\n const bp = /^(sm|md|lg|xl)-(.+)$/.exec(cls);\n if (bp && format === 'tailwind')\n return {\n cls: raw,\n severity: 'error' as const,\n reason: `\\`${bp[1]}-\\` responsive classes are not emitted in the tailwind format`,\n suggestion: `@${bp[1]}:${bp[2]} (framework breakpoints) or ${bp[1]}:${bp[2]} (Tailwind's)`,\n };\n // In css/bricks the bare-prefix form is real; fall through and judge the base\n // against the rest of the vocabulary.\n const base = bp && format !== 'tailwind' ? (bp[2] as string) : cls;\n\n // ── <util>-<hue>-<step> ────────────────────────────────────────────────────\n const util = new RegExp(`^(${UTIL_FAMILIES.join('|')})-(.+)$`).exec(base);\n if (util) {\n const [, fam, rest] = util as unknown as [string, string, string];\n // Anything the generator actually emits is valid, full stop. Checking this\n // first also settles the ambiguity below for every well-formed class.\n if (v.roleClasses.has(base)) return null;\n\n // Role and hue names can share a prefix — `defaultConfig()` has the hue\n // `brand` and the role `brand-primary`, so matching hues first would read\n // `bg-brand-primary-x-muted` as hue `brand` + step `primary-x-muted` and\n // report a bogus bad step. Take the LONGEST match across both vocabularies.\n const prefix = (names: string[]) =>\n names\n .filter((n) => rest === n || rest.startsWith(`${n}-`))\n .sort((a, b) => b.length - a.length)[0];\n const hue = prefix(v.hues);\n const role = prefix(v.roles);\n const useRole = role && (!hue || role.length > hue.length);\n\n if (useRole) {\n const mod = rest.slice((role as string).length + 1);\n const valid = emittedModifiers(v.roleClasses, fam as string, role as string);\n return {\n cls: raw,\n severity: 'error' as const,\n reason: `\\`${fam}-${role}${mod ? `-${mod}` : ''}\\` is not emitted for the \\`${role}\\` role`,\n suggestion: valid.length\n ? `valid modifiers: ${valid.join(', ')}`\n : `the \\`${role}\\` role emits no \\`${fam}-*\\` utilities`,\n };\n }\n if (hue) {\n const step = rest.slice(hue.length + 1);\n if (step === '')\n return {\n cls: raw,\n severity: 'error' as const,\n reason: `\\`${fam}-${hue}\\` names a palette hue with no step`,\n suggestion: `${fam}-${hue}-500, or a role such as ${fam}-${v.roles[0] ?? 'neutral'}`,\n };\n if (!v.steps.includes(step))\n return {\n cls: raw,\n severity: 'error' as const,\n reason: `\\`${step}\\` is not a step on the \\`${hue}\\` scale (steps are 50…950)`,\n suggestion: `${fam}-${hue}-500, or a role such as ${fam}-${v.roles[0] ?? 'neutral'} which also flips in dark mode`,\n };\n return null; // valid raw step\n }\n return null; // not anchored to this config — not ours to judge\n }\n\n // ── font-<type-role> ───────────────────────────────────────────────────────\n const font = /^font-(.+)$/.exec(base);\n if (font && v.typeRoles.length && !v.typeRoles.includes(font[1] as string)) {\n const near = nearest(font[1] as string, v.typeRoles);\n // Only complain when it looks like a type role attempt, not e.g. font-bold.\n if (near)\n return {\n cls: raw,\n severity: 'error' as const,\n reason: `\\`${font[1]}\\` is not a typography role`,\n suggestion: `font-${near}`,\n };\n }\n\n // ── drop-shadow-<name> ─────────────────────────────────────────────────────\n const ds = /^drop-shadow-(.+)$/.exec(base);\n if (ds && v.shadows.length && !v.shadows.includes(ds[1] as string))\n return {\n cls: raw,\n severity: 'error' as const,\n reason: `\\`${ds[1]}\\` is not a defined shadow`,\n suggestion: `drop-shadow-${v.shadows[0]}`,\n };\n\n return null;\n}\n\nconst CLASS_ATTR = /(?:class|className|:class)\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)'|\\{`([^`]*)`\\})/g;\n\n/** Extract class tokens from a source file, with line numbers. */\nexport function extractClasses(src: string): { cls: string; line: number }[] {\n const out: { cls: string; line: number }[] = [];\n for (const m of src.matchAll(CLASS_ATTR)) {\n const value = m[1] ?? m[2] ?? m[3] ?? '';\n const line = src.slice(0, m.index).split('\\n').length;\n for (const tok of value.split(/\\s+/))\n // Skip template holes and dynamic fragments — a partial token would be\n // judged as a typo and this must not cry wolf.\n if (tok && !tok.includes('${') && !tok.includes('{') && /^[@\\w:[\\]().%/-]+$/.test(tok))\n out.push({ cls: tok, line });\n }\n return out;\n}\n\nexport function lintSource(\n files: { path: string; text: string }[],\n v: Vocabulary,\n format: Format,\n): LintFinding[] {\n const findings: LintFinding[] = [];\n const seen = new Set<string>();\n for (const f of files)\n for (const { cls, line } of extractClasses(f.text)) {\n const verdict = judge(cls, v, format);\n if (!verdict) continue;\n const key = `${f.path}:${line}:${cls}`;\n if (seen.has(key)) continue;\n seen.add(key);\n findings.push({ file: f.path, line, ...verdict });\n }\n return findings;\n}\n","#!/usr/bin/env node\n/**\n * `vitops` — CLI for the Vitops design-system generator.\n *\n * vitops generate --input <json> --format <bricks|css|tailwind|design[,…]> --out <dir>\n * vitops init [--out design-system.json] [--force]\n * vitops validate <design-system.json|site.json>\n * vitops favicon --input <svg|png> --out <dir> [--low-res <svg|png>] [--background <hex>]\n * vitops agents [--input <json>] [--out AGENTS.md] [--docs-dir <dir>]\n * vitops docs [topic] [--input <json>] [--all]\n * vitops lint [--input <json>] [--format <fmt>] [--src <dir>]\n * vitops legal [--input <site.json>] [--doc <name>] [--format <md|html|portable-text>] [--out <dir>]\n * vitops search setup [--domain <name>] [--dry] [--check] | notify [--dry] [--all] [--check]\n * vitops ads setup [--provider <name>] [--dry] [--check] | tags | lint\n * vitops media [--raw <dir>] [--out <dir>] [--force] [--dry]\n *\n * Thin wrapper over @getvitops/generator (generation) and @getvitops/utils (favicons).\n * Every client brings their own consumer-editable design-system.json.\n */\nimport { parseArgs } from 'node:util';\nimport { writeFileSync, existsSync, readFileSync, mkdirSync } from 'node:fs';\nimport { resolve, join, dirname, relative, extname } from 'node:path';\nimport { createRequire } from 'node:module';\nimport { pathToFileURL } from 'node:url';\nimport {\n buildIconSprite,\n generate,\n validate,\n defaultConfig,\n generateDocs,\n generateLegal,\n enabledDocs,\n processorsMissingLocation,\n JURISDICTION_COUNTRIES,\n isConfig,\n resolveInput,\n resolveConfig,\n resolveTheme,\n roleColorUtilities,\n functionalRole,\n expandPalette,\n roleHue,\n roleKind,\n movedTokens,\n SCHEMA_LOCAL_PATH,\n type Format,\n type StylesheetFormat,\n type DesignSystem,\n type LegalDoc,\n type LegalOutput,\n type ResolvedInput,\n type Config,\n} from '@getvitops/generator';\nimport {\n collectIconRefs,\n generateFavicons,\n generateIconInclude,\n resolveIcon,\n scanFiles,\n} from '@getvitops/utils';\n// Its own subpath: `indexing` is the only network-touching module in utils, and the\n// other commands should not pull it in.\nimport {\n SNAPSHOT_PATH,\n collectEntries,\n formatPlan,\n SCOPES,\n googleAccessToken,\n inspectUrl,\n keyFileContents,\n newKey,\n parseServiceAccount,\n plan,\n readSnapshot,\n resolveKeyLocation,\n resolveSitemapUrl,\n submitBatch,\n submitSitemap,\n toSnapshot,\n verifyKeyFile,\n writeSnapshot,\n type GoogleCredential,\n type IndexingConfig,\n type ServiceAccount,\n} from '@getvitops/utils/indexing';\n// Its own subpath for the same reason: `onboarding` is network-touching (Cloudflare\n// DNS + Google). `formatPlan`/`plan` are aliased — indexing exports the same names.\nimport {\n addSite,\n backoffSchedule,\n createApexTxt,\n findZoneId,\n formatPlan as formatSetupPlan,\n formatSummary,\n refreshTokenGrant,\n getSite,\n getVerificationToken,\n getWebResource,\n hasDrift,\n listApexTxt,\n ownerUnion,\n plan as planSetup,\n siteUrlFor,\n updateOwners,\n verifyWebResource,\n type DomainResult,\n type DomainSetup,\n type DomainState,\n type GoogleOAuth,\n} from '@getvitops/utils/onboarding';\n// Its own subpath for the same reason: `ads` touches Cloudflare DNS. `plan`,\n// `formatPlan`, `hasDrift` and `formatSummary` are aliased — indexing and\n// onboarding export those names too.\nimport {\n AD_PLATFORMS,\n AD_PROVIDER_KEYS,\n formatPlan as formatPlanAds,\n formatSummary as formatAdsSummary,\n hasDrift as hasAdsDrift,\n isAdProvider,\n missingFields,\n plan as planAds,\n renderTag,\n tagId,\n type AdDomainState,\n type AdPropertyResult,\n type AdPropertySetup,\n type AdProvider,\n type MissingField,\n} from '@getvitops/utils/ads';\nimport { PLATFORM_PARAMS } from '@getvitops/utils/tracking';\n// Its own subpath for the same reason: `media` shells out to ffmpeg, and no other\n// command should carry it. `formatPlan` is aliased — indexing exports one too.\nimport {\n MEDIA_MANIFEST_PATH,\n formatPlan as formatMediaPlan,\n processMedia,\n type MediaConfig,\n type OutputKind,\n} from '@getvitops/utils/media';\nimport { findSkillTarget, linkSkill, SKILL_NAME, TOPICS } from './agents.ts';\nimport { ADS_HELP, COMMANDS, HELP, SEARCH_HELP, helpFor, wantsHelp } from './help.ts';\nimport { ask, canPrompt, missingFieldMessage, questionFor, writeConfigPatch } from './prompt.ts';\nimport { lintCss } from './lint-css.ts';\nimport { lintMarkup } from './lint-markup.ts';\nimport { applyRenames, lintTokens } from './lint-tokens.ts';\nimport { lintSource, vocabulary } from './lint.ts';\n\nconst FORMATS = new Set<Format>(['bricks', 'css', 'tailwind', 'design']);\n// `lint` judges class names against what a build emits, and the `design` format\n// emits no CSS at all — so it is a valid target for `generate` and a category\n// error for `lint`.\nconst LINT_FORMATS = new Set<StylesheetFormat>(['bricks', 'css', 'tailwind']);\n\n// `legal` reads a *site* config, not a design-system.json, and has its own\n// output set — it renders documents, not stylesheets.\nconst LEGAL_DOCS = new Set<LegalDoc>(['privacy', 'terms', 'cookies']);\nconst LEGAL_OUTPUTS = new Set<LegalOutput>(['md', 'html', 'portable-text']);\n\nfunction fail(msg: string): never {\n console.error(`✖ ${msg}`);\n process.exit(1);\n}\n\nasync function cmdGenerate(argv: string[]) {\n const { values } = parseArgs({\n args: argv,\n options: {\n input: { type: 'string', short: 'i', default: 'design-system.json' },\n format: { type: 'string', short: 'f', default: 'bricks' },\n out: { type: 'string', short: 'o', default: 'dist' },\n site: { type: 'string' },\n theme: { type: 'string' },\n 'site-env': { type: 'string' },\n },\n allowPositionals: false,\n });\n const input = resolve(values.input as string);\n if (!existsSync(input)) fail(`config not found: ${input}`);\n const site = values.site ? resolve(values.site as string) : undefined;\n if (site && !existsSync(site)) fail(`site config not found: ${site}`);\n const formats = (values.format as string)\n .split(',')\n .map((f) => f.trim())\n .filter(Boolean);\n for (const f of formats)\n if (!FORMATS.has(f as Format))\n fail(`unknown format \"${f}\" (expected: bricks | css | tailwind | design)`);\n\n for (const format of formats as Format[]) {\n try {\n const res = await generate({\n input,\n format,\n outDir: values.out as string,\n ...(site ? { site } : {}),\n ...(values.theme ? { theme: values.theme as string } : {}),\n ...(values['site-env'] ? { siteEnv: values['site-env'] as string } : {}),\n });\n console.log(`✓ ${format} → ${res.outDir} (${res.written.length} paths)`);\n } catch (err) {\n fail((err as Error).message);\n }\n }\n}\n\nfunction cmdInit(argv: string[]) {\n const { values } = parseArgs({\n args: argv,\n options: {\n out: { type: 'string', short: 'o', default: 'design-system.json' },\n force: { type: 'boolean', default: false },\n },\n allowPositionals: false,\n });\n const out = resolve(values.out as string);\n if (existsSync(out) && !values.force) fail(`${out} already exists (use --force to overwrite)`);\n writeFileSync(out, JSON.stringify(defaultConfig(), null, 2) + '\\n');\n console.log(`✓ wrote ${out}`);\n console.log(\n ` Edit it, then: vitops generate --input ${values.out} --format tailwind --out src/styles`,\n );\n console.log(\n ` Editors read the \"$schema\" (${SCHEMA_LOCAL_PATH}) for autocomplete + validation — ` +\n `the installed copy, so it matches the toolchain you build with.`,\n );\n}\n\n/**\n * Validate a config against the schema its shape says it is.\n *\n * Routing on kind rather than asking the caller matters here: pointed at a site\n * config, the design-system schema used to report a single `unrecognized_keys`\n * for `designSystem` and nothing about the file's actual contents — a wrong\n * answer that reads like a right one. A site config is validated whole, which\n * also covers the cross-field integrity JSON Schema can't express.\n */\nfunction cmdValidate(argv: string[]) {\n const { values, positionals } = parseArgs({\n args: argv,\n options: { input: { type: 'string', short: 'i' }, 'site-env': { type: 'string' } },\n allowPositionals: true,\n });\n const path = resolve((positionals[0] ?? values.input ?? 'design-system.json') as string);\n if (!existsSync(path)) fail(`config not found: ${path}`);\n let raw: unknown;\n try {\n raw = JSON.parse(readFileSync(path, 'utf8'));\n } catch (err) {\n fail(`could not parse JSON: ${(err as Error).message}`);\n }\n\n if (isConfig(raw)) {\n let site: Config;\n try {\n site = resolveConfig(raw, values['site-env'] as string | undefined);\n } catch (err) {\n // Already formatted as one issue per line, with field paths.\n console.error(`✖ ${path} is invalid as a site config:`);\n console.error((err as Error).message.replace(/^Invalid site config:\\n/, ''));\n process.exit(1);\n }\n // Each theme is validated in turn: `validateConfig` checks the `extends` chain\n // resolves, not that what it resolves to is a complete design system, so a\n // theme could pass there and still fail to build.\n const themes = (site.designSystem?.themes ?? {}) as Parameters<typeof resolveTheme>[0];\n let bad = false;\n for (const name of Object.keys(themes)) {\n const result = validate(resolveTheme(themes, name));\n for (const w of result.warnings) console.warn(` ! designSystem.themes.${name}: ${w}`);\n if (result.ok) continue;\n bad = true;\n console.error(`✖ ${path} — designSystem.themes.${name} is not a complete design system:`);\n for (const e of result.errors)\n console.error(` • ${e.path.join('.') || '(root)'}: ${e.message}`);\n }\n if (bad) process.exit(1);\n const n = Object.keys(themes).length;\n console.log(`✓ ${path} is a valid site config (${n} theme${n === 1 ? '' : 's'})`);\n return;\n }\n\n const result = validate(raw);\n for (const w of result.warnings) console.warn(` ! ${w}`);\n if (result.ok) {\n console.log(`✓ ${path} is valid`);\n return;\n }\n console.error(`✖ ${path} is invalid:`);\n for (const e of result.errors) console.error(` • ${e.path.join('.') || '(root)'}: ${e.message}`);\n process.exit(1);\n}\n\nasync function cmdFavicon(argv: string[]) {\n const { values } = parseArgs({\n args: argv,\n options: {\n input: { type: 'string', short: 'i' },\n out: { type: 'string', short: 'o', default: 'public' },\n 'low-res': { type: 'string' },\n // The maskable outputs must be opaque — the OS crops them to its own shape,\n // so transparency there becomes a black frame, not \"no background\".\n background: { type: 'string' },\n },\n allowPositionals: false,\n });\n if (!values.input) fail('favicon: --input <svg|png> is required');\n const source = resolve(values.input as string);\n if (!existsSync(source)) fail(`source not found: ${source}`);\n try {\n const written = await generateFavicons({\n source,\n outputDir: values.out as string,\n ...(values['low-res'] ? { lowResSource: resolve(values['low-res'] as string) } : {}),\n ...(values.background ? { backgroundColor: values.background as string } : {}),\n });\n console.log(`✓ favicons → ${values.out} (${written.length} files)`);\n } catch (err) {\n fail((err as Error).message);\n }\n}\n\nconst OUTPUT_KINDS = new Set<OutputKind>(['webm', 'mp4', 'poster']);\n\n/**\n * `vitops media` — encode a directory of raw video into web-ready outputs.\n *\n * Flags only, with no config file, following `favicon`: `site.favicon` exists in\n * the schema and `cmdFavicon` still doesn't read it. The same reasoning applies\n * more strongly here — `legal`, `icons` and `indexing` are anchored to a\n * `Config` because what they emit *describes the site*, and an encoder setting\n * describes a build step.\n */\nasync function cmdMedia(argv: string[]) {\n const { values } = parseArgs({\n args: argv,\n options: {\n raw: { type: 'string', default: 'raw' },\n out: { type: 'string', short: 'o', default: 'src/assets/processed' },\n 'max-width': { type: 'string' },\n crf: { type: 'string' },\n 'max-bitrate': { type: 'string' },\n audio: { type: 'boolean', default: false },\n 'poster-time': { type: 'string' },\n outputs: { type: 'string' },\n manifest: { type: 'string', default: MEDIA_MANIFEST_PATH },\n force: { type: 'boolean', default: false },\n dry: { type: 'boolean', default: false },\n },\n allowPositionals: false,\n });\n\n // Parsed here rather than passed through as strings, so a typo is caught before\n // ffmpeg spends minutes encoding at a quality nobody asked for.\n const num = (flag: string, raw: string | undefined): number | undefined => {\n if (raw === undefined) return undefined;\n const n = Number(raw);\n if (!Number.isFinite(n) || n < 0) fail(`media: --${flag} must be a non-negative number`);\n return n;\n };\n\n let outputs: OutputKind[] | undefined;\n if (values.outputs) {\n outputs = (values.outputs as string).split(',').map((s) => s.trim()) as OutputKind[];\n for (const kind of outputs)\n if (!OUTPUT_KINDS.has(kind))\n fail(`media: unknown output \"${kind}\" (expected: webm | mp4 | poster)`);\n }\n\n const maxWidth = num('max-width', values['max-width'] as string | undefined);\n const crf = num('crf', values.crf as string | undefined);\n const posterTime = num('poster-time', values['poster-time'] as string | undefined);\n\n const config: MediaConfig = {\n ...(maxWidth !== undefined ? { maxWidth } : {}),\n ...(crf !== undefined ? { crf } : {}),\n ...(values['max-bitrate'] ? { maxBitrate: values['max-bitrate'] as string } : {}),\n ...(values.audio ? { audio: true } : {}),\n ...(posterTime !== undefined ? { posterTime } : {}),\n ...(outputs ? { outputs } : {}),\n };\n\n try {\n const result = await processMedia({\n raw: values.raw as string,\n out: values.out as string,\n config,\n manifest: values.manifest as string,\n force: values.force as boolean,\n dry: values.dry as boolean,\n // An encode is minutes of silence otherwise, which reads as a hang.\n onProgress: (message) => console.error(` … ${message}`),\n });\n\n if (values.dry) {\n console.log(formatMediaPlan(result.plan));\n return;\n }\n console.log(\n `✓ media → ${values.out} (${result.written.length} written, ${result.skipped} unchanged)`,\n );\n for (const note of result.plan.notes) console.error(` ! ${note}`);\n } catch (err) {\n fail((err as Error).message);\n }\n}\n\n/**\n * Read + parse + validate the design system at `path`, or exit with a message.\n *\n * `path` may be a `design-system.json` **or** the larger site config that embeds\n * one — every command that judges source against the design system (`docs`,\n * `lint`, `agents`) accepts either, so a consumer who keeps their tokens in\n * `company.json` doesn't have to maintain a second file for the tooling's sake.\n * `resolveInput` tells them apart by shape and resolves the theme.\n */\nfunction loadDesignSystem(path: string, theme?: string): DesignSystem {\n if (!existsSync(path)) fail(`config not found: ${path}`);\n let raw: unknown;\n try {\n raw = JSON.parse(readFileSync(path, 'utf8'));\n } catch (err) {\n fail(`could not parse JSON: ${(err as Error).message}`);\n }\n let resolved: ResolvedInput;\n try {\n resolved = resolveInput(raw, theme != null ? { theme } : {});\n } catch (err) {\n // resolveConfig formats one issue per line; a bad --theme is one line.\n fail(`${path}: ${(err as Error).message}`);\n }\n const result = validate(resolved.designSystem);\n if (!result.ok) {\n const where = resolved.theme != null ? ` (designSystem.themes.${resolved.theme})` : '';\n console.error(`✖ ${path}${where} is invalid:`);\n for (const e of result.errors)\n console.error(` • ${e.path.join('.') || '(root)'}: ${e.message}`);\n process.exit(1);\n }\n // Warnings go to stderr, not stdout: `vitops docs <topic>` is designed to be\n // piped, so anything here must not land in the piped document. They used to\n // be dropped entirely on this path, which meant `docs` and `agents` stayed\n // silent about collisions that `generate` and `validate` both reported.\n for (const w of result.warnings) console.warn(` ! ${w}`);\n return result.data;\n}\n\n/**\n * Read + resolve a site config, or exit with a message.\n *\n * Accepts JSON, or a JS/TS module with a default export — deliberately not YAML,\n * which would mean a parser dependency for one command. `resolveConfig` is\n * documented as taking an already-parsed object precisely so the loader is the\n * consumer's choice; anyone on YAML can convert it or export from a module.\n */\nasync function loadConfig(path: string, siteEnv: string): Promise<Config> {\n if (!existsSync(path)) fail(`site config not found: ${path}`);\n let raw: unknown;\n if (/\\.(json)$/.test(path)) {\n try {\n raw = JSON.parse(readFileSync(path, 'utf8'));\n } catch (err) {\n fail(`could not parse JSON: ${(err as Error).message}`);\n }\n } else {\n try {\n raw = (await import(pathToFileURL(path).href)).default;\n } catch (err) {\n fail(`could not import ${path}: ${(err as Error).message}`);\n }\n if (raw == null) fail(`${path} has no default export`);\n }\n try {\n return resolveConfig(raw, siteEnv);\n } catch (err) {\n // resolveConfig already formats one issue per line.\n fail((err as Error).message);\n }\n}\n\n/**\n * Render the site's legal documents.\n *\n * The universal delivery path: every consumer has this CLI regardless of stack,\n * so a WordPress theme, an Eleventy build or a hand-written HTML site all get\n * the same documents without any integration code. Prints to stdout like\n * `vitops docs`, or writes files when given `--out`.\n */\n/**\n * Report the icon vocabulary a project actually uses, and optionally build the\n * sprite from it.\n *\n * A sibling of `legal` rather than a widening of `lint`: `lint` judges classes\n * against a design-system.json, whereas icons are anchored to a Config.\n *\n * Exit codes carry the same distinction the Astro integration makes. A name the\n * config DECLARES but that doesn't resolve is a config error and fails the\n * command; a name only the SCAN found is reported and tolerated, because a bare\n * unmapped name is more often a local src/icons/*.svg than a mistake. Runtime-\n * computed names are listed with file and line so they can be declared, never\n * guessed at.\n */\nasync function cmdIcons(argv: string[]) {\n const { values } = parseArgs({\n args: argv,\n options: {\n site: { type: 'string', default: 'site.json' },\n src: { type: 'string', default: 'src' },\n sprite: { type: 'boolean', default: false },\n out: { type: 'string', short: 'o', default: 'dist' },\n json: { type: 'boolean', default: false },\n 'site-env': { type: 'string', default: 'production' },\n },\n allowPositionals: false,\n });\n\n const sitePath = resolve(values.site as string);\n const icons = existsSync(sitePath)\n ? (((await loadConfig(sitePath, values['site-env'] as string)).site.icons ?? {}) as Record<\n string,\n unknown\n >)\n : {};\n const ui = (icons.ui as string) ?? 'fa7-solid';\n const brand = (icons.brand as string) ?? 'simple-icons';\n const weight = icons.weight as string | undefined;\n const weightOpt = weight ? { weight } : {};\n\n // Declared first — this throws on an unresolvable name, by design.\n let include: Record<string, string[]> = {};\n try {\n include = generateIconInclude({ ...(icons as object) } as Parameters<\n typeof generateIconInclude\n >[0]);\n } catch (e) {\n fail((e as Error).message);\n }\n const add = (prefix: string, name: string) => {\n const list = (include[prefix] ??= []);\n if (!list.includes(name)) list.push(name);\n };\n\n const srcDir = resolve(values.src as string);\n const scanned = existsSync(srcDir) ? collectIconRefs(scanFiles(srcDir)) : null;\n const unmapped: string[] = [];\n for (const name of scanned?.names ?? []) {\n const colon = name.indexOf(':');\n if (colon > 0) {\n add(name.slice(0, colon), name.slice(colon + 1));\n continue;\n }\n try {\n const q = resolveIcon(name, ui, weightOpt);\n add(q.slice(0, q.indexOf(':')), q.slice(q.indexOf(':') + 1));\n } catch {\n unmapped.push(name);\n }\n }\n\n const dynamic = (scanned?.dynamic ?? []).map((d) => ({\n file: relative(process.cwd(), d.file),\n line: d.line,\n expr: d.expr,\n }));\n const total = Object.values(include).flat().length;\n\n let sprite: { ids: string[]; missing: string[] } | null = null;\n if (values.sprite) {\n const aliases: Record<string, string> = {};\n for (const name of (icons.semantic as string[]) ?? []) {\n try {\n aliases[`icon-${name}`] = resolveIcon(name, ui, weightOpt);\n } catch {\n /* already reported by generateIconInclude above */\n }\n }\n const built = await buildIconSprite({ include, aliases });\n const outDir = resolve(values.out as string);\n mkdirSync(outDir, { recursive: true });\n writeFileSync(join(outDir, 'icons.svg'), built.svg);\n sprite = { ids: built.ids, missing: built.missing };\n }\n\n if (values.json) {\n process.stdout.write(\n `${JSON.stringify({ ui, brand, weight: weight ?? null, include, unmapped, dynamic, sprite }, null, 2)}\\n`,\n );\n } else {\n console.log(`icon sets: ui=${ui} brand=${brand}${weight ? ` weight=${weight}` : ''}`);\n for (const [prefix, names] of Object.entries(include))\n console.log(` ${prefix}: ${names.length} — ${names.join(', ')}`);\n console.log(`✓ ${total} icon(s) across ${Object.keys(include).length} set(s)`);\n if (sprite)\n console.log(\n `✓ sprite → ${resolve(values.out as string)}/icons.svg (${sprite.ids.length} symbols)`,\n );\n for (const d of dynamic)\n console.log(` ! ${d.file}:${d.line} ${d.expr} — computed at runtime, declare it in icons`);\n if (unmapped.length)\n console.log(\n ` ! not in the '${ui}' map: ${unmapped.join(', ')} (fine for a local svg or sprite id)`,\n );\n if (sprite?.missing.length)\n console.log(` ! absent from the sprite: ${sprite.missing.join(', ')}`);\n }\n\n // Dynamic holes and unmapped bare names are warnings, not failures — same\n // tolerance `lint` shows template holes, but visible rather than silent.\n if (sprite?.missing.length) process.exitCode = 1;\n}\n\nasync function cmdLegal(argv: string[]) {\n const { values } = parseArgs({\n args: argv,\n options: {\n input: { type: 'string', short: 'i', default: 'site.json' },\n doc: { type: 'string', short: 'd', multiple: true },\n format: { type: 'string', short: 'f', default: 'md' },\n out: { type: 'string', short: 'o' },\n 'site-env': { type: 'string', default: 'production' },\n },\n allowPositionals: false,\n });\n\n const output = values.format as LegalOutput;\n if (!LEGAL_OUTPUTS.has(output))\n fail(`unknown format \"${output}\" (expected: ${[...LEGAL_OUTPUTS].join(' | ')})`);\n\n const requested = (values.doc ?? []) as string[];\n for (const d of requested)\n if (!LEGAL_DOCS.has(d as LegalDoc))\n fail(`unknown doc \"${d}\" (expected: ${[...LEGAL_DOCS].join(' | ')})`);\n\n const site = await loadConfig(resolve(values.input as string), values['site-env'] as string);\n const docs = requested.length ? (requested as LegalDoc[]) : enabledDocs(site);\n if (docs.length === 0)\n fail(\n 'no legal documents are enabled — set site.legal.privacyPolicy.enabled (or termsOfService / cookieConsent) in your config, or name one with --doc',\n );\n\n const files = generateLegal(site, { docs, output });\n\n /**\n * A processor placed nowhere cannot appear in the cross-border disclosure — there\n * is nothing true to say about it — so it drops out of that section silently,\n * which is the failure that looks tidy. Reported here rather than in the document:\n * a policy must not editorialise about its own gaps.\n *\n * On **stderr** because stdout is the document and gets piped or redirected.\n */\n if (docs.includes('privacy'))\n for (const name of processorsMissingLocation(site))\n console.error(\n ` ! ${name}: no country, storage or operatorCountry declared — it will not appear in the cross-border transfer disclosure. Add one, or state storage: [{ country: \"${JURISDICTION_COUNTRIES[site.site.legal?.jurisdiction ?? 'ca']}\" }] to say it does not leave the country.`,\n );\n\n const REVIEW =\n ' These are generated from your config and are not legal advice — review them before publishing.';\n\n if (!values.out) {\n process.stdout.write(Object.values(files).join('\\n'));\n // On stderr, so it survives a redirect of the document itself. It used to be\n // omitted entirely on this path — the one path where the output is most\n // likely being piped straight into a page.\n console.error(REVIEW);\n return;\n }\n const outDir = resolve(values.out as string);\n mkdirSync(outDir, { recursive: true });\n // Enabling a document is a config edit with consequences outside the config —\n // a new file needs a page, a route, a menu link, a policyUrl. Flipping\n // `cookieConsent.enabled` silently produced `cookie-notice.*` and said only\n // \"3 files\", so nothing pointed at the work that had just appeared.\n const isNew = (name: string) => !existsSync(join(outDir, name));\n const added = Object.keys(files).filter(isNew);\n for (const [name, content] of Object.entries(files)) writeFileSync(join(outDir, name), content);\n console.log(`✓ legal → ${outDir}`);\n for (const name of Object.keys(files))\n console.log(` ${name}${added.includes(name) ? ' (new)' : ''}`);\n if (added.length)\n console.log(\n added.length === 1\n ? `\\n That document is new. It needs somewhere to live: a page or route that renders it, ` +\n `and a link to it${added[0]?.startsWith('cookie') ? ' — including the URL your consent banner points at' : ''}.`\n : `\\n Those ${added.length} documents are new. Each needs somewhere to live: a page or ` +\n `route that renders it, and a link to it — for a cookie notice, including the URL your ` +\n `consent banner points at.`,\n );\n console.log(REVIEW);\n}\n\n/**\n * Adapt a `Config` to the indexing module's own option shape.\n *\n * A flat field map, as intended: `@getvitops/utils` cannot import from the\n * generator (the generator already depends on it), so `IndexingConfig` mirrors the\n * `seo.indexing` block rather than being it. The one piece of judgment here is the\n * origin — see below.\n */\nfunction toIndexingConfig(cfg: Config, siteEnv: string): IndexingConfig {\n const site = cfg.site;\n const indexing = site.seo?.indexing ?? {};\n const env = site.environments?.[siteEnv];\n /*\n * The environment's own URL wins over `domains.canonical`.\n *\n * `domains.canonical` is the production origin — it is what absolute URLs and\n * SEO tags resolve against. Notifying a non-production environment while\n * deriving URLs from the canonical origin would submit *production* URLs under\n * the belief they were staging's, which the noindex gate below would then not\n * catch, because the gate reads the environment and the URLs would not.\n */\n const canonical = env?.url ?? site.domains?.canonical;\n return {\n ...(canonical ? { canonical } : {}),\n ...(indexing.sitemapUrl ? { sitemapUrl: indexing.sitemapUrl } : {}),\n ...(indexing.indexNow ? { indexNow: indexing.indexNow } : {}),\n ...(indexing.searchConsole ? { searchConsole: indexing.searchConsole } : {}),\n ...(indexing.priorityUrls ? { priorityUrls: indexing.priorityUrls } : {}),\n // Fall back to the site-wide policy so a site that states `noindex` once,\n // globally, is still protected.\n ...((env?.robots ?? site.seo?.robots) ? { robots: env?.robots ?? site.seo?.robots } : {}),\n };\n}\n\n/**\n * The Search Console credential, from either supported source.\n *\n * Never from the config file: it is the one genuine secret in this command, and a\n * `site.json` is committed. Returns `undefined` rather than failing, so a site\n * running IndexNow alone doesn't need a GCP project at all.\n */\nfunction loadServiceAccount(): ServiceAccount | undefined {\n const inline = process.env.VITOPS_GSC_SERVICE_ACCOUNT;\n const path = process.env.GOOGLE_APPLICATION_CREDENTIALS;\n const raw = inline ?? (path && existsSync(path) ? readFileSync(path, 'utf8') : undefined);\n if (!raw) return undefined;\n try {\n return parseServiceAccount(raw);\n } catch (err) {\n fail(\n `${inline ? 'VITOPS_GSC_SERVICE_ACCOUNT' : `GOOGLE_APPLICATION_CREDENTIALS (${path})`}: ${(err as Error).message}`,\n );\n }\n}\n\n/** Read a sitemap from a URL or a local path. */\nconst readSitemap = async (source: string): Promise<string> => {\n if (/^https?:\\/\\//i.test(source)) {\n const res = await fetch(source);\n if (!res.ok) fail(`could not fetch ${source}: ${res.status}`);\n return res.text();\n }\n if (!existsSync(source)) fail(`sitemap not found: ${source}`);\n return readFileSync(source, 'utf8');\n};\n\n/**\n * Tell search engines a deploy happened.\n *\n * Worth being precise about what this is, because the obvious expectation is\n * wrong: **Google has no API that requests indexing.** The Search Console button\n * is not exposed anywhere, URL Inspection is read-only, and the sitemap ping\n * endpoint was removed in 2023. So the Google half of this command resubmits the\n * sitemap and then *verifies* the outcome with `--check`; the immediate-push half\n * is IndexNow, which Google does not participate in.\n *\n * The Indexing API is deliberately absent — see `@getvitops/utils/indexing`'s\n * `gsc.ts`.\n */\nasync function cmdSearchNotify(argv: string[]) {\n const { values } = parseArgs({\n args: argv,\n options: {\n input: { type: 'string', short: 'i', default: 'site.json' },\n 'site-env': { type: 'string', default: 'production' },\n sitemap: { type: 'string' },\n urls: { type: 'string' },\n all: { type: 'boolean', default: false },\n dry: { type: 'boolean', default: false },\n check: { type: 'boolean', default: false },\n 'new-key': { type: 'boolean', default: false },\n 'write-key': { type: 'string' },\n snapshot: { type: 'string', default: SNAPSHOT_PATH },\n },\n allowPositionals: false,\n });\n\n // Stands alone: generating a key is what you do *before* there is a config to\n // put it in.\n if (values['new-key']) {\n const key = newKey();\n console.log(key);\n console.log(\n `\\n Add to your site config:\\n \"seo\": { \"indexing\": { \"indexNow\": { \"key\": \"${key}\" } } }`,\n );\n console.log(` Then serve it at /${key}.txt — \\`vitops search notify --write-key public\\`.`);\n return;\n }\n\n const site = await loadConfig(resolve(values.input as string), values['site-env'] as string);\n const config = toIndexingConfig(site, values['site-env'] as string);\n\n if (values['write-key'] !== undefined) {\n const key = config.indexNow?.key;\n if (!key) fail('no site.seo.indexing.indexNow.key in the config — generate one with --new-key');\n const dir = resolve(values['write-key']);\n mkdirSync(dir, { recursive: true });\n const file = join(dir, `${key}.txt`);\n writeFileSync(file, keyFileContents(key));\n console.log(`✓ IndexNow key file → ${file}`);\n console.log(` It must be served at ${resolveKeyLocation(config) ?? `/${key}.txt`}`);\n return;\n }\n\n const sitemapUrl = (values.sitemap as string | undefined) ?? resolveSitemapUrl(config);\n if (!sitemapUrl)\n fail(\n 'no sitemap to read — set seo.indexing.sitemapUrl or domains.canonical, or pass --sitemap',\n );\n\n const explicitUrls = values.urls\n ? (values.urls as string)\n .split(',')\n .map((u) => u.trim())\n .filter(Boolean)\n : undefined;\n\n // The sitemap is only needed when the URL set comes from it.\n const current =\n explicitUrls?.length && !values.check\n ? []\n : (await collectEntries(sitemapUrl, readSitemap)).entries;\n\n const snapshotPath = resolve(values.snapshot as string);\n const p = plan({\n config: { ...config, sitemapUrl },\n current,\n previous: readSnapshot(snapshotPath),\n explicitUrls,\n all: values.all as boolean,\n });\n\n console.log(formatPlan(p));\n\n if (p.blocked) {\n // Not a failure. Running this against a `noindex` environment is a coherent\n // thing for a deploy script to do — the config said not to index it, and the\n // command honoured that. Failing the build would punish the correct setup.\n return;\n }\n if (values.dry) {\n console.log('\\n(--dry: nothing was submitted)');\n return;\n }\n\n const credential = loadSearchCredential();\n let failed = false;\n\n // ── --check: read-only, and nothing else runs ───────────────────────────────\n if (values.check) {\n if (!p.searchConsole.siteUrl)\n fail('--check needs seo.indexing.searchConsole.siteUrl (the Search Console property)');\n if (!credential) fail(`--check needs a Search Console credential — ${CREDENTIAL_HINT}`);\n if (p.check.length === 0)\n fail('--check needs seo.indexing.priorityUrls — the pages whose indexing matters');\n\n const token = await googleAccessToken(credential);\n console.log(`\\nInspecting ${p.check.length} priority URL(s):`);\n for (const url of p.check) {\n const r = await inspectUrl(token, p.searchConsole.siteUrl, url);\n if (r.error) {\n console.log(` ? ${url} — ${r.error}`);\n failed = true;\n } else {\n console.log(\n ` ${r.indexed ? '✓' : '✗'} ${url} — ${r.coverageState ?? r.verdict ?? 'unknown'}`,\n );\n if (!r.indexed) failed = true;\n }\n }\n if (failed) {\n console.error('\\n✖ one or more priority URLs are not indexed');\n process.exit(1);\n }\n console.log('\\n✓ every priority URL is indexed');\n return;\n }\n\n // ── IndexNow ────────────────────────────────────────────────────────────────\n if (p.indexNow.enabled) {\n const { key, keyLocation } = p.indexNow;\n const check = await verifyKeyFile(keyLocation!, key!);\n if (!check.ok) {\n // Hard stop rather than \"submit and hope\": IndexNow answers 202 and then\n // discards the batch when the key doesn't verify, so submitting anyway\n // would print a success it did not earn.\n console.error(`✖ IndexNow key file check failed — ${check.reason}`);\n console.error(` Write it with: vitops search notify --write-key <public dir>`);\n failed = true;\n } else {\n let sent = 0;\n for (const batch of p.indexNow.batches) {\n const r = await submitBatch(p.indexNow, batch);\n if (!r.ok) {\n console.error(`✖ IndexNow: ${r.message ?? r.status}`);\n failed = true;\n break;\n }\n sent += r.urls;\n }\n if (!failed) console.log(`✓ IndexNow: ${sent} URL(s) submitted`);\n }\n }\n\n // ── Search Console ──────────────────────────────────────────────────────────\n if (p.searchConsole.enabled) {\n if (!credential) {\n console.log(`· Search Console: skipped — no credential (${CREDENTIAL_HINT})`);\n } else {\n const token = await googleAccessToken(credential);\n const r = await submitSitemap(token, p.searchConsole.siteUrl!, sitemapUrl);\n if (r.ok) console.log(`✓ Search Console: sitemap resubmitted`);\n else {\n console.error(`✖ Search Console: ${r.message}`);\n failed = true;\n }\n }\n }\n\n if (failed) process.exit(1);\n\n /*\n * The snapshot is written last, and only on success.\n *\n * Writing it eagerly would record URLs as notified that never were — and since\n * the next run diffs against it, a single transient 503 would drop those pages\n * from every future run, silently and permanently.\n */\n if (current.length > 0) {\n writeSnapshot(snapshotPath, toSnapshot(sitemapUrl, current, new Date().toISOString()));\n console.log(` state → ${relative(process.cwd(), snapshotPath)}`);\n }\n if (p.check.length > 0)\n console.log(\n `\\n Indexing is not instant. Run \\`vitops search notify --check\\` in a day or two to see what Google actually did.`,\n );\n}\n\n/**\n * Adapt a `Config` to the onboarding module's own option shape.\n *\n * The same flat field map as `toIndexingConfig`, and for the same reason — utils\n * cannot import the generator. `--domain` scopes to a single `site.searchConsole`\n * entry, and a name that isn't there is an error, not an empty run.\n */\nfunction toSearchConsoleSetup(cfg: Config, domainFilter: string | undefined): DomainSetup[] {\n const entries = cfg.site.searchConsole ?? {};\n const setups: DomainSetup[] = Object.entries(entries).map(([domain, e]) => ({\n domain,\n ...(e.delegatedOwners ? { delegatedOwners: e.delegatedOwners } : {}),\n ...(e.fullUserGroup ? { fullUserGroup: e.fullUserGroup } : {}),\n }));\n if (domainFilter) {\n const one = setups.find((s) => s.domain === domainFilter);\n if (!one)\n fail(\n `--domain \"${domainFilter}\" is not in site.searchConsole (have: ${setups.map((s) => s.domain).join(', ') || 'none'})`,\n );\n return [one];\n }\n return setups;\n}\n\n/**\n * The Cloudflare DNS credential. From the environment only — a `site.json` is\n * committed, and this is a real secret. A `Zone:DNS:Edit` token (the standard\n * \"Edit zone DNS\" template, which also carries `Zone:Read`).\n */\nfunction loadCloudflareToken(): string | undefined {\n return process.env.CLOUDFLARE_API_TOKEN || undefined;\n}\n\n/**\n * The Google user-OAuth credential (refresh-token flow), from the environment.\n *\n * A user token, not a service account: onboarding acts *as a person* who can own\n * the sites. All-or-nothing — a partial set is a misconfiguration worth naming\n * rather than a reason to run degraded.\n */\nfunction loadGoogleOAuth(): GoogleOAuth | undefined {\n const clientId = process.env.VITOPS_GOOGLE_CLIENT_ID;\n const clientSecret = process.env.VITOPS_GOOGLE_CLIENT_SECRET;\n const refreshToken = process.env.VITOPS_GOOGLE_REFRESH_TOKEN;\n if (!clientId && !clientSecret && !refreshToken) return undefined;\n const missing = [\n ['VITOPS_GOOGLE_CLIENT_ID', clientId],\n ['VITOPS_GOOGLE_CLIENT_SECRET', clientSecret],\n ['VITOPS_GOOGLE_REFRESH_TOKEN', refreshToken],\n ]\n .filter(([, v]) => !v)\n .map(([k]) => k);\n if (missing.length) fail(`incomplete Google OAuth credential — missing ${missing.join(', ')}`);\n return { clientId: clientId!, clientSecret: clientSecret!, refreshToken: refreshToken! };\n}\n\n/**\n * The Google identity for `search notify`, preferring a service account.\n *\n * Search Console accepts either, and the preference is about *where this command\n * runs*: it fires on every deploy, in CI, and a service account has no expiry,\n * while a refresh token can be revoked — and for an OAuth client still in\n * *Testing* publishing status Google expires it after 7 days, which is a bad\n * property for a deploy step. So the robot wins when it is available.\n *\n * The fallback is the point, though. `search setup` needs user OAuth (verifying\n * a site makes the caller an owner, which should be a person), so a consumer who\n * ran setup already has a Google credential. Demanding a second, unrelated one\n * for the other half of the same command bought nothing.\n */\nfunction loadSearchCredential(): GoogleCredential | undefined {\n const account = loadServiceAccount();\n if (account) return { kind: 'service-account', account, scope: SCOPES.webmasters };\n const oauth = loadGoogleOAuth();\n return oauth ? { kind: 'oauth', oauth } : undefined;\n}\n\n/** Both spellings, for an error that has to tell you what to actually set. */\nconst CREDENTIAL_HINT =\n 'a service account in VITOPS_GSC_SERVICE_ACCOUNT / GOOGLE_APPLICATION_CREDENTIALS, or a user OAuth credential in VITOPS_GOOGLE_CLIENT_ID / VITOPS_GOOGLE_CLIENT_SECRET / VITOPS_GOOGLE_REFRESH_TOKEN';\n\nconst sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));\n\n/**\n * `vitops search` — everything that talks to search engines.\n *\n * Two subcommands, split by what they touch: `setup` onboards a domain into\n * Search Console (DNS + verification + property), `notify` tells the engines a\n * deploy happened (sitemap + IndexNow). `notify` is the former top-level\n * `vitops indexing`.\n */\nasync function cmdSearch(argv: string[]) {\n const [sub, ...rest] = argv;\n switch (sub) {\n case 'setup':\n return cmdSearchSetup(rest);\n case 'notify':\n return cmdSearchNotify(rest);\n case undefined:\n case '-h':\n case '--help':\n console.log(SEARCH_HELP);\n return;\n default:\n fail(`unknown \"search\" subcommand \"${sub}\" (expected: setup | notify). Try: vitops --help`);\n }\n}\n\n/**\n * Onboard domains into Google Search Console as domain properties.\n *\n * Idempotent by construction: the planner decides each step from the domain's live\n * state, so a re-run of a fully-onboarded domain is all skips. `--check` reports\n * drift and exits non-zero without mutating; `--dry` prints the plan and stops.\n * DNS is only ever *created* — the verification TXT — never edited or removed.\n *\n * Search Console has no user/permission API, so granting a Google Group Full-User\n * access stays manual and is surfaced as a reminder, not attempted.\n */\nasync function cmdSearchSetup(argv: string[]) {\n const { values } = parseArgs({\n args: argv,\n options: {\n input: { type: 'string', short: 'i', default: 'site.json' },\n 'site-env': { type: 'string', default: 'production' },\n domain: { type: 'string' },\n check: { type: 'boolean', default: false },\n dry: { type: 'boolean', default: false },\n },\n allowPositionals: false,\n });\n\n const cfg = await loadConfig(resolve(values.input as string), values['site-env'] as string);\n const domains = toSearchConsoleSetup(cfg, values.domain as string | undefined);\n if (domains.length === 0)\n fail('no domains in site.searchConsole — add domains to onboard (keyed by bare hostname)');\n\n const cfToken = loadCloudflareToken();\n const oauth = loadGoogleOAuth();\n\n // A dry run that mutates nothing should not demand the credentials to mutate.\n // It cannot READ live state without them either, so it plans from \"nothing is\n // done yet\" and says so — which is still the complete account of what a first\n // run would do, and is what makes the plan showable before anyone has\n // provisioned anything. `--check` is different: reporting drift means\n // comparing against reality, so it keeps needing to see it.\n if (values.dry && (!cfToken || !oauth)) {\n const blank: DomainState = {\n zoneId: '',\n txtPresent: false,\n verified: false,\n currentOwners: [],\n propertyExists: false,\n };\n console.log(\n formatSetupPlan(planSetup({ domains }, new Map(domains.map((d) => [d.domain, blank])))),\n );\n const missing = [\n ...(cfToken ? [] : ['CLOUDFLARE_API_TOKEN (Zone:DNS:Edit + Zone:Read)']),\n ...(oauth\n ? []\n : ['VITOPS_GOOGLE_CLIENT_ID / VITOPS_GOOGLE_CLIENT_SECRET / VITOPS_GOOGLE_REFRESH_TOKEN']),\n ];\n console.log(\n `\\n(--dry, and no credentials set: planned from scratch rather than from live state, ` +\n `so nothing here is reported as already done.\\n A real run needs ${missing.join(' and ')}.)`,\n );\n return;\n }\n\n if (!cfToken)\n fail(\n 'set CLOUDFLARE_API_TOKEN (a Zone:DNS:Edit token — the standard \"Edit zone DNS\" template, ' +\n 'which also carries the Zone:Read that the zone-by-name lookup needs)',\n );\n if (!oauth)\n fail(\n 'set VITOPS_GOOGLE_CLIENT_ID / VITOPS_GOOGLE_CLIENT_SECRET / VITOPS_GOOGLE_REFRESH_TOKEN — a user OAuth token scoped to siteverification + webmasters',\n );\n\n const token = await refreshTokenGrant(oauth);\n\n // ── Observe live state per domain (the executors gather; the planner decides) ──\n const states = new Map<string, DomainState>();\n const verifyTokens = new Map<string, string>();\n const webIds = new Map<string, string>();\n for (const d of domains) {\n const zone = await findZoneId(cfToken, d.domain);\n if (!zone.ok || !zone.zoneId) fail(`${d.domain}: ${zone.message}`);\n\n const vt = await getVerificationToken(token, d.domain);\n if (!vt.ok || !vt.token)\n fail(`${d.domain}: could not obtain a verification token — ${vt.message}`);\n verifyTokens.set(d.domain, vt.token);\n\n const txt = await listApexTxt(cfToken, zone.zoneId, d.domain);\n if (!txt.ok) fail(`${d.domain}: ${txt.message}`);\n\n const wr = await getWebResource(token, d.domain);\n if (!wr.ok) fail(`${d.domain}: ${wr.message}`);\n if (wr.id) webIds.set(d.domain, wr.id);\n\n const site = await getSite(token, siteUrlFor(d.domain));\n if (!site.ok) fail(`${d.domain}: ${site.message}`);\n\n states.set(d.domain, {\n zoneId: zone.zoneId,\n txtPresent: txt.contents.includes(vt.token),\n verified: wr.exists,\n currentOwners: wr.owners,\n propertyExists: site.exists,\n });\n }\n\n const p = planSetup({ domains }, states);\n console.log(formatSetupPlan(p));\n\n if (values.check) {\n if (hasDrift(p)) {\n console.error('\\n✖ drift — one or more domains are not fully onboarded');\n process.exit(1);\n }\n console.log('\\n✓ every domain is onboarded');\n return;\n }\n if (values.dry) {\n console.log('\\n(--dry: nothing was changed)');\n return;\n }\n\n // ── Execute ─────────────────────────────────────────────────────────────────\n const results: DomainResult[] = [];\n let failed = false;\n const delays = backoffSchedule();\n\n for (const d of domains) {\n const dp = p.domains.find((x) => x.domain === d.domain)!;\n const state = states.get(d.domain)!;\n const result: DomainResult = {\n domain: d.domain,\n txt: '—',\n verified: '—',\n property: '—',\n reminders: dp.reminders,\n };\n\n // 1. Ensure the apex TXT record (create only).\n if (dp.txt.action === 'skip') result.txt = 'present';\n else {\n const r = await createApexTxt(cfToken, state.zoneId!, d.domain, verifyTokens.get(d.domain)!);\n if (!r.ok) {\n console.error(`✖ ${d.domain} TXT: ${r.message}`);\n result.txt = 'failed';\n failed = true;\n results.push(result);\n continue;\n }\n result.txt = 'created';\n }\n\n // 2. Verify ownership, retrying with backoff while DNS propagates.\n let verified = state.verified;\n if (verified) result.verified = 'yes';\n else {\n for (let attempt = 0; attempt < delays.length; attempt++) {\n const v = await verifyWebResource(token, d.domain);\n if (v.ok) {\n verified = true;\n if (v.id) webIds.set(d.domain, v.id);\n // Verification is what CREATES the web resource, so this response is the\n // first sight of its owner list — and it contains the verifying account.\n // The pre-verification observation could only report `[]`. Dropping this\n // makes the union below a bare `ownersToAdd`, and the PUT then removes\n // the very account that just proved ownership.\n state.currentOwners = v.owners;\n break;\n }\n if (attempt < delays.length - 1) {\n const wait = delays[attempt]!;\n console.log(\n ` … ${d.domain}: not verified yet (attempt ${attempt + 1}/${delays.length}); retrying in ${wait / 1000}s`,\n );\n await sleep(wait);\n }\n }\n // PENDING, not failed: propagation is slow, not broken. Re-run later.\n result.verified = verified ? 'yes' : 'pending';\n }\n if (!verified) {\n results.push(result);\n continue;\n }\n\n // 3. Add the Search Console property.\n if (dp.property.action === 'skip') result.property = 'present';\n else {\n const r = await addSite(token, dp.siteUrl);\n if (!r.ok) {\n console.error(`✖ ${d.domain} property: ${r.message}`);\n result.property = 'failed';\n failed = true;\n } else result.property = 'added';\n }\n\n // 4. Add delegated owners to the verified web resource (additive union).\n if (dp.owners.action === 'update' && dp.ownersToAdd.length) {\n const id = webIds.get(d.domain);\n if (!id) {\n console.error(`✖ ${d.domain} owners: no web-resource id (verify may be too fresh)`);\n failed = true;\n } else {\n const r = await updateOwners(\n token,\n id,\n d.domain,\n ownerUnion(state.currentOwners, dp.ownersToAdd),\n );\n if (!r.ok) {\n console.error(`✖ ${d.domain} owners: ${r.message}`);\n failed = true;\n } else console.log(`✓ ${d.domain}: added ${dp.ownersToAdd.length} owner(s)`);\n }\n }\n\n results.push(result);\n }\n\n console.log(`\\n${formatSummary(results)}`);\n if (failed) process.exit(1);\n}\n\n/**\n * Adapt a `Config` to the ads module's own option shape.\n *\n * The same flat field map as `toSearchConsoleSetup` and `toIndexingConfig`, for the\n * same reason — utils cannot import the generator. The domain default is the one\n * derived value: a platform verifies the host the site is published at, so\n * `domains.canonical` answers it, and only an ad account verified against some\n * other host needs `site.ads.<provider>.domain` stated.\n */\nfunction toAdProperties(cfg: Config, providerFilter: string | undefined): AdPropertySetup[] {\n const canonicalHost = (() => {\n const url = cfg.site.domains?.canonical;\n if (!url) return undefined;\n try {\n return new URL(url).hostname;\n } catch {\n return undefined;\n }\n })();\n\n const entries = cfg.site.ads ?? {};\n const properties: AdPropertySetup[] = AD_PROVIDER_KEYS.filter((p) => entries[p] != null).map(\n (provider) => {\n const e = entries[provider]!;\n const domain = e.domain ?? canonicalHost;\n return {\n provider,\n ...(e.accountId ? { accountId: e.accountId } : {}),\n ...(e.pixelId ? { pixelId: e.pixelId } : {}),\n ...(e.conversionLabel ? { conversionLabel: e.conversionLabel } : {}),\n ...(domain ? { domain } : {}),\n ...(e.domainVerification ? { domainVerification: e.domainVerification } : {}),\n ...(e.category ? { category: e.category } : {}),\n ...(e.enabled != null ? { enabled: e.enabled } : {}),\n };\n },\n );\n\n if (providerFilter) {\n if (!isAdProvider(providerFilter))\n fail(\n `--provider \"${providerFilter}\" is not a known ad platform (expected: ${AD_PROVIDER_KEYS.join(' | ')})`,\n );\n const one = properties.find((p) => p.provider === providerFilter);\n if (!one)\n fail(\n `--provider \"${providerFilter}\" is not in site.ads (have: ${properties.map((p) => p.provider).join(', ') || 'none'})`,\n );\n return [one];\n }\n return properties;\n}\n\n/**\n * `vitops ads` — everything that links this site to an ad platform.\n *\n * Three subcommands, split by what they touch: `setup` writes DNS, `tags` writes\n * nothing and prints markup, `lint` reads and reports.\n */\nasync function cmdAds(argv: string[]) {\n const [sub, ...rest] = argv;\n switch (sub) {\n case 'setup':\n return cmdAdsSetup(rest);\n case 'tags':\n return cmdAdsTags(rest);\n case 'lint':\n return cmdAdsLint(rest);\n case undefined:\n case '-h':\n case '--help':\n console.log(ADS_HELP);\n return;\n default:\n fail(`unknown \"ads\" subcommand \"${sub}\" (expected: setup | tags | lint). Try: vitops --help`);\n }\n}\n\n/**\n * Link each configured ad property: ensure the platform's domain-verification TXT,\n * report what only a human can finish.\n *\n * Idempotent by construction — the planner decides each step from live DNS, so a\n * re-run of a linked property is all skips. `--check` reports drift and exits\n * non-zero without mutating; `--dry` prints the plan and stops. Neither is offline:\n * the DNS observation runs before the planner either way.\n *\n * The one thing this does that `search setup` does not is **ask**. A first run has\n * no verification token, because the token doesn't exist until someone fetches it\n * from the platform UI — so a blocked step becomes a prompt, the answer is folded\n * into the setup, and the planner runs again on it. That re-plan matters: what gets\n * executed is always a plan the pure planner produced, never a special case built\n * out of an answer.\n */\nasync function cmdAdsSetup(argv: string[]) {\n const { values } = parseArgs({\n args: argv,\n options: {\n input: { type: 'string', short: 'i', default: 'site.json' },\n 'site-env': { type: 'string', default: 'production' },\n provider: { type: 'string' },\n check: { type: 'boolean', default: false },\n dry: { type: 'boolean', default: false },\n 'no-prompt': { type: 'boolean', default: false },\n 'no-write': { type: 'boolean', default: false },\n },\n allowPositionals: false,\n });\n\n const input = resolve(values.input as string);\n const cfg = await loadConfig(input, values['site-env'] as string);\n let properties = toAdProperties(cfg, values.provider as string | undefined);\n if (properties.length === 0)\n fail('no properties in site.ads — add the ad platforms this site is linked to');\n\n const dry = values.dry as boolean;\n const check = values.check as boolean;\n\n // Only the DNS-verifying platforms need a Cloudflare token; a config of\n // tag-only platforms (Google Ads, LinkedIn, Reddit, Microsoft) has no DNS work\n // at all, and demanding a credential for a run that writes nothing would be an\n // obstacle standing in front of an empty room.\n const needsDns = properties.some(\n (p) => AD_PLATFORMS[p.provider].verification.method === 'dns-txt',\n );\n const cfToken = loadCloudflareToken();\n // As in `search setup`: a dry run mutates nothing, so it must not demand the\n // credential to mutate. Without one it cannot read live DNS either, so\n // `observe()` returns an empty map and the plan is \"from scratch\" — still the\n // complete account of a first run, and showable before anything is provisioned.\n if (needsDns && !cfToken && values.dry !== true)\n fail(\n 'set CLOUDFLARE_API_TOKEN (a Zone:DNS:Edit token — the standard \"Edit zone DNS\" template, ' +\n 'which also carries the Zone:Read that the zone-by-name lookup needs)',\n );\n\n /** Observe live DNS per domain. Cached by domain: several platforms share one. */\n const observe = async (): Promise<Map<string, AdDomainState>> => {\n const states = new Map<string, AdDomainState>();\n if (!cfToken) return states;\n for (const p of properties) {\n const domain = p.domain;\n if (!domain || states.has(domain)) continue;\n if (AD_PLATFORMS[p.provider].verification.method !== 'dns-txt') continue;\n const zone = await findZoneId(cfToken, domain);\n if (!zone.ok || !zone.zoneId) fail(`${domain}: ${zone.message}`);\n const txt = await listApexTxt(cfToken, zone.zoneId, domain);\n if (!txt.ok) fail(`${domain}: ${txt.message}`);\n states.set(domain, { zoneId: zone.zoneId, txtContents: txt.contents });\n }\n return states;\n };\n\n let states = await observe();\n let adsPlan = planAds({ properties }, states);\n\n // ── Ask for what the config is missing, then re-plan on the answers ──────────\n const interactive = canPrompt({\n dry,\n check,\n noPrompt: values['no-prompt'] as boolean,\n });\n const gaps = missingFields(adsPlan);\n if (gaps.length && interactive) {\n const answers: { provider: AdProvider; needs: MissingField; value: string }[] = [];\n for (const gap of gaps) {\n const value = await ask(questionFor(gap.provider as AdProvider, gap.needs));\n if (value) answers.push({ provider: gap.provider as AdProvider, needs: gap.needs, value });\n }\n if (answers.length) {\n properties = properties.map((p) => {\n const mine = answers.filter((a) => a.provider === p.provider);\n return mine.reduce((acc, a) => ({ ...acc, [a.needs]: a.value }), p);\n });\n adsPlan = planAds({ properties }, states);\n if (!(values['no-write'] as boolean)) {\n for (const a of answers) {\n const res = writeConfigPatch(input, a.provider, a.needs, a.value);\n if (res.written) console.log(`✓ wrote site.ads.${a.provider}.${a.needs} to ${input}`);\n else console.error(`! ${res.reason}`);\n }\n }\n }\n // A token answered now may name a record we haven't looked for yet.\n states = await observe();\n adsPlan = planAds({ properties }, states);\n } else if (gaps.length && !dry && !check) {\n for (const gap of gaps)\n console.error(`! ${missingFieldMessage(gap.provider as AdProvider, gap.needs)}`);\n }\n\n if (dry || check) {\n console.log(formatPlanAds(adsPlan));\n if (check && hasAdsDrift(adsPlan)) {\n console.error('\\n✖ ad properties are not fully linked');\n process.exit(1);\n }\n return;\n }\n\n // ── Apply ────────────────────────────────────────────────────────────────────\n const results: AdPropertyResult[] = [];\n let failed = false;\n for (const p of adsPlan.properties) {\n const result: AdPropertyResult = {\n provider: p.provider,\n domain: p.domain ?? '—',\n txt: 'n/a',\n tag: p.tag.action === 'skip' ? 'ready' : 'blocked',\n reminders: p.reminders,\n };\n // A property still missing a field after the prompt round is not linked, and\n // the exit code has to say so — a run that silently succeeds while a pixel has\n // no id is the failure this command exists to make visible.\n if (p.txt.action === 'blocked' || p.tag.action === 'blocked') failed = true;\n if (p.txt.action === 'blocked') result.txt = 'blocked';\n else if (p.txt.action === 'skip')\n result.txt = AD_PLATFORMS[p.provider].verification.method === 'dns-txt' ? 'present' : 'n/a';\n else {\n const zoneId = p.domain ? states.get(p.domain)?.zoneId : undefined;\n if (!cfToken || !zoneId || !p.domain || !p.txtContent) {\n console.error(`✖ ${p.provider}: no Cloudflare zone for ${p.domain ?? '(no domain)'}`);\n result.txt = 'failed';\n failed = true;\n } else {\n const r = await createApexTxt(cfToken, zoneId, p.domain, p.txtContent);\n if (!r.ok) {\n console.error(`✖ ${p.provider} TXT: ${r.message}`);\n result.txt = 'failed';\n failed = true;\n } else {\n console.log(`✓ ${p.provider}: created TXT on ${p.domain}`);\n result.txt = 'created';\n }\n }\n }\n results.push(result);\n }\n\n console.log(`\\n${formatAdsSummary(results)}`);\n if (results.some((r) => r.txt === 'created'))\n console.log('\\n DNS takes minutes to propagate before a platform can see the record.');\n if (results.some((r) => r.reminders.length))\n console.log(' Finish the reminders above in the platform UI — no API covers those.');\n if (failed) process.exit(1);\n}\n\n/**\n * Print each configured pixel as an inert, consent-gated `<script>`.\n *\n * The universal delivery path, the same reasoning as `vitops legal`: every consumer\n * has this CLI whatever their stack, so Bricks, WordPress and a hand-built site all\n * get the correct gated markup without integration code.\n */\nasync function cmdAdsTags(argv: string[]) {\n const { values } = parseArgs({\n args: argv,\n options: {\n input: { type: 'string', short: 'i', default: 'site.json' },\n 'site-env': { type: 'string', default: 'production' },\n provider: { type: 'string' },\n strategy: { type: 'string', default: 'idle' },\n },\n allowPositionals: false,\n });\n\n const strategy = values.strategy as string;\n if (!['idle', 'async', 'interaction'].includes(strategy))\n fail(`--strategy \"${strategy}\" is not one of: idle | async | interaction`);\n\n const cfg = await loadConfig(resolve(values.input as string), values['site-env'] as string);\n const properties = toAdProperties(cfg, values.provider as string | undefined);\n if (properties.length === 0) fail('no properties in site.ads — nothing to emit');\n\n const out: string[] = [];\n for (const p of properties) {\n if (p.enabled === false) continue;\n const tag = renderTag(p, strategy as 'idle' | 'async' | 'interaction');\n if (!tag) {\n console.error(\n `! ${p.provider}: no ${AD_PLATFORMS[p.provider].tag.needs} — skipped (run \\`vitops ads setup\\` to be prompted for it)`,\n );\n continue;\n }\n out.push(tag);\n }\n if (out.length === 0) fail('no ad property has a tag id yet');\n console.log(out.join('\\n\\n'));\n}\n\n/**\n * Report the ad-property gaps that are invisible at runtime.\n *\n * Each finding is a silent failure, which is the bar for being here at all: an\n * uncaptured click ID looks exactly like organic traffic, and a pixel on a site\n * with tracking off produces conversions no campaign gets credit for.\n */\nasync function cmdAdsLint(argv: string[]) {\n const { values } = parseArgs({\n args: argv,\n options: {\n input: { type: 'string', short: 'i', default: 'site.json' },\n 'site-env': { type: 'string', default: 'production' },\n },\n allowPositionals: false,\n });\n\n const cfg = await loadConfig(resolve(values.input as string), values['site-env'] as string);\n const properties = toAdProperties(cfg, undefined);\n if (properties.length === 0) {\n console.log('· no site.ads properties — nothing to check');\n return;\n }\n\n const findings: string[] = [];\n const trackingOn = cfg.site.tracking?.enabled === true;\n\n for (const p of properties) {\n const platform = AD_PLATFORMS[p.provider];\n if (p.enabled === false) continue;\n\n if (!tagId(p))\n findings.push(\n `${p.provider}: no ${platform.tag.needs} — the property is on record but no tag can be emitted`,\n );\n\n const uncaptured = platform.clickIdParams.filter((param) => !(param in PLATFORM_PARAMS));\n if (uncaptured.length)\n findings.push(\n `${p.provider}: click ID ${uncaptured.join(', ')} is not in the capture vocabulary — every conversion from this platform will arrive unattributed`,\n );\n\n if (!trackingOn)\n findings.push(\n `${p.provider}: site.tracking.enabled is not true, so ${platform.clickIdParams.join('/')} is never captured — conversions will be unattributed`,\n );\n }\n\n if (findings.length === 0) {\n console.log(\n `✓ ${properties.length} ad propert${properties.length === 1 ? 'y' : 'ies'} check out`,\n );\n return;\n }\n for (const f of findings) console.error(`✖ ${f}`);\n process.exit(1);\n}\n\n// This CLI's own version (dist/cli.mjs → package-root package.json).\nfunction cliVersion(): string {\n try {\n return (\n JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version ??\n '0.0.0'\n );\n } catch {\n return '0.0.0';\n }\n}\n\n// The framework asset root shipped inside @getvitops/generator (holds the Bricks\n// PHP that generateDocs reads for the element reference).\nfunction generatorAssetsDir(): string {\n const pkg = createRequire(import.meta.url).resolve('@getvitops/generator/package.json');\n return join(dirname(pkg), 'assets');\n}\n\nconst AGENTS_START = '<!-- vitops:start -->';\nconst AGENTS_END = '<!-- vitops:end -->';\n\n/** Print a live reference doc (rendered from the project's config) to stdout. */\nfunction cmdDocs(argv: string[]) {\n const { values, positionals } = parseArgs({\n args: argv,\n options: {\n input: { type: 'string', short: 'i', default: 'design-system.json' },\n theme: { type: 'string' },\n all: { type: 'boolean', default: false },\n },\n allowPositionals: true,\n });\n const topic = positionals[0];\n const topicList = () =>\n Object.entries(TOPICS)\n .map(([name, t]) => ` ${name.padEnd(10)} ${t.summary}`)\n .join('\\n');\n if (!topic && !values.all) {\n console.log(\n `vitops docs <topic> — print a live design-system reference to stdout\\n\\nTopics:\\n${topicList()}\\n\\nAlso: vitops docs --all (every topic, concatenated)`,\n );\n return;\n }\n if (topic && !TOPICS[topic]) fail(`unknown topic \"${topic}\". Valid topics:\\n${topicList()}`);\n const ds = loadDesignSystem(resolve(values.input as string), values.theme as string | undefined);\n const docs = generateDocs(ds, generatorAssetsDir());\n const paths = values.all\n ? Object.values(TOPICS).map((t) => t.path)\n : [TOPICS[topic as string]!.path];\n process.stdout.write(paths.map((p) => docs[p]).join('\\n'));\n}\n\nfunction cmdLint(argv: string[]) {\n const { values, positionals } = parseArgs({\n args: argv,\n options: {\n input: { type: 'string', short: 'i', default: 'design-system.json' },\n theme: { type: 'string' },\n format: { type: 'string', short: 'f', default: 'bricks' },\n src: { type: 'string', short: 's', default: 'src' },\n // Suggestions are advisory: a reuse rule that failed CI the day it shipped\n // would be a worse defect than the drift it reports.\n strict: { type: 'boolean', default: false },\n fix: { type: 'boolean', default: false },\n },\n // Positionals are explicit files to lint instead of scanning `--src`. This is\n // what makes the command usable as a pre-commit hook: `vp`'s `staged` key\n // appends the staged paths to whatever it runs, so a command that refused\n // positionals could not be wired into the one place the feedback actually\n // lands — at the moment the code is written, rather than whenever someone\n // remembers to run a linter.\n allowPositionals: true,\n });\n const format = values.format as StylesheetFormat;\n if (!LINT_FORMATS.has(format))\n fail(`unknown format \"${format}\" (expected: bricks | css | tailwind)`);\n const ds = loadDesignSystem(resolve(values.input as string), values.theme as string | undefined);\n const srcDir = resolve(values.src as string);\n if (!positionals.length && !existsSync(srcDir)) fail(`source directory not found: ${srcDir}`);\n\n // Ask the generator what it actually emits rather than re-deriving the rules\n // here — a linter that models the vocabulary separately just drifts into\n // reporting classes that do exist.\n const palette = expandPalette(ds.colors.palette);\n const roleClasses = roleColorUtilities(\n Object.entries(ds.colors.roles).map(([role, spec]) =>\n functionalRole(role, roleHue(spec), palette[roleHue(spec)]!, roleKind(spec)),\n ),\n ds.colors.utilities ?? ['bg', 'text', 'icon', 'border'],\n ).map((u) => u.cls);\n\n // Explicit paths win over the scan. A pre-commit hook is handed whatever was\n // staged, which includes deletions and files of every kind, so unreadable and\n // uninteresting paths are skipped rather than fatal — a hook that fails because\n // someone staged a PNG is a hook that gets removed.\n const LINTABLE = new Set(['.astro', '.html', '.js', '.jsx', '.ts', '.tsx', '.vue', '.svelte']);\n const named = positionals\n .filter((p) => LINTABLE.has(extname(p)) || extname(p) === '.css')\n .flatMap((p) => {\n try {\n return [{ path: p, text: readFileSync(resolve(p), 'utf8') }];\n } catch {\n return [];\n }\n });\n // `.css` is not in the default extension set — the class linter reads markup,\n // not stylesheets — so the reuse rules get their own pass. Component files are\n // scanned twice on purpose: once for their class attributes, once for any\n // `<style>` block, which is where hand-rolled layout tends to accumulate.\n const files = positionals.length\n ? named.filter((f) => extname(f.path) !== '.css')\n : scanFiles(srcDir);\n const cssFiles = positionals.length\n ? named\n : [...files, ...scanFiles(srcDir, { exts: ['.css'] })];\n // Nothing staged that this command has an opinion about — say so and succeed,\n // rather than reporting a clean run over zero files as if it had checked them.\n if (positionals.length && !cssFiles.length) {\n console.log('✓ no lintable files among the paths given');\n return;\n }\n // The pre-1.0 colour grammar, built from this config's own role names. Read\n // from CSS and <style> blocks — the half of a codebase that references the\n // design system by token rather than by class, and the half nothing checked.\n const renames = movedTokens(ds.colors.roles);\n const tokenFindings = lintTokens(cssFiles, renames);\n const findings = [\n ...lintSource(files, vocabulary(ds, roleClasses), format),\n ...lintCss(cssFiles, format),\n // Markup shape, which is the only one of the three that can see a repeated\n // card set laid out with no bad class and no hand-written CSS — every class\n // real, the pattern simply unused. Reads `files`, not `cssFiles`: a stylesheet\n // has no markup, and passing the doubled list would report each component\n // twice.\n ...lintMarkup(files),\n ...tokenFindings,\n ];\n\n if (values.fix === true) {\n // Only the token renames are rewritten. Everything else this command\n // reports is a judgement call — `bg-navy-d`'s \"suggestion\" is the linter's\n // best guess at what you meant, and silently writing a guess into source is\n // worse than printing it.\n const byFile = new Map<string, Set<string>>();\n for (const f of tokenFindings)\n (byFile.get(f.file) ?? byFile.set(f.file, new Set()).get(f.file)!).add(f.fix.from);\n for (const [file, names] of byFile) {\n const subset = Object.fromEntries([...names].map((n) => [n, renames[n] as string]));\n writeFileSync(file, applyRenames(readFileSync(file, 'utf8'), subset));\n }\n const remaining = findings.length - tokenFindings.length;\n console.log(\n `✓ rewrote ${tokenFindings.length} token reference${tokenFindings.length === 1 ? '' : 's'} ` +\n `in ${byFile.size} file${byFile.size === 1 ? '' : 's'}` +\n (remaining\n ? `\\n! ${remaining} other finding${remaining === 1 ? '' : 's'} need a decision — ` +\n `re-run without --fix to see ${remaining === 1 ? 'it' : 'them'}`\n : ''),\n );\n if (remaining) process.exitCode = 1;\n return;\n }\n\n // Name what was actually checked. With explicit paths `--src` was never read,\n // and reporting it would claim a scan that did not happen.\n const scope = positionals.length ? 'the files given' : (values.src as string);\n const scanned = positionals.length ? cssFiles.length : files.length;\n\n if (!findings.length) {\n console.log(\n `✓ no unresolvable framework classes or missed primitives in ${scope} ` +\n `(${scanned} file${scanned === 1 ? '' : 's'} checked)`,\n );\n return;\n }\n\n const errors = findings.filter((f) => f.severity === 'error');\n const suggestions = findings.filter((f) => f.severity === 'suggestion');\n // Errors first: a class that resolves to nothing is a defect, a reuse\n // suggestion is a judgement call, and mixing them buries the former.\n for (const f of [...errors, ...suggestions]) {\n console.error(`${f.file}:${f.line} ${f.severity === 'error' ? f.cls : `(${f.cls})`}`);\n console.error(` ${f.reason}`);\n if (f.suggestion) console.error(` try: ${f.suggestion}`);\n }\n\n const count = (n: number, one: string, many: string) => `${n} ${n === 1 ? one : many}`;\n const parts: string[] = [];\n if (errors.length) parts.push(count(errors.length, 'unresolvable class', 'unresolvable classes'));\n if (suggestions.length) parts.push(count(suggestions.length, 'suggestion', 'suggestions'));\n const failing = errors.length > 0 || (values.strict === true && suggestions.length > 0);\n console.error(\n `\\n${failing ? '✖' : '!'} ${parts.join(', ')} in ` +\n `${scanned} file${scanned === 1 ? '' : 's'}` +\n (suggestions.length && !values.strict ? ' (suggestions do not fail; use --strict)' : ''),\n );\n if (failing) process.exit(1);\n}\n\n/**\n * Find the config when `design-system.json` isn't there.\n *\n * Keyed to SHAPE, not just to the filename — `resolveInput` already tells a\n * design system from the config that embeds one, and consumers name that file\n * whatever they like (`company.json`, `site.json`). The candidate list is\n * ordered, and a tie is resolved by taking the first: this only ever supplies a\n * default that the run then prints, so a wrong guess is visible rather than\n * silent, and `-i` overrides it.\n */\nfunction discoverConfig(cwd: string): string | undefined {\n const candidates = [\n 'design-system.json',\n 'vitops.json',\n 'site.json',\n 'company.json',\n 'organization.json',\n ];\n for (const name of candidates) {\n const p = resolve(cwd, name);\n if (!existsSync(p)) continue;\n try {\n const raw = JSON.parse(readFileSync(p, 'utf8'));\n // Either kind counts: a bare design system, or a config that embeds one.\n if (isConfig(raw) || (raw && typeof raw === 'object' && 'colors' in raw)) return name;\n } catch {\n // Unparseable: not a candidate, and the real error surfaces if -i names it.\n }\n }\n return undefined;\n}\n\nfunction cmdAgents(argv: string[]) {\n const { values } = parseArgs({\n args: argv,\n options: {\n input: { type: 'string', short: 'i', default: 'design-system.json' },\n theme: { type: 'string' },\n out: { type: 'string', short: 'o', default: 'AGENTS.md' },\n 'docs-dir': { type: 'string' },\n },\n allowPositionals: false,\n });\n // This command WRITES documentation, so getting the input path wrong is not a\n // missing feature, it is a false statement committed to the repo: it used to\n // warn and then write \"tokens live in design-system.json\" into a project whose\n // tokens are in company.json, with the emitted commands broken to match. So\n // when the default path is absent, look for the config rather than assuming\n // it — and fail if there is nothing to name.\n const explicitInput = argv.includes('-i') || argv.includes('--input');\n let inputRel = values.input as string;\n if (!explicitInput && !existsSync(resolve(inputRel))) {\n const found = discoverConfig(process.cwd());\n if (found) {\n inputRel = found;\n console.warn(` ⚠ no design-system.json here — using ${found} (pass -i to choose another)`);\n } else {\n fail(\n `config not found: ${resolve(inputRel)}\\n` +\n ` This command writes the path into ${values.out}, so it will not guess one. ` +\n `Pass -i <path> if your tokens live elsewhere (a site config works), or run \\`vitops init\\`.`,\n );\n }\n }\n // Validate the config (fail on an invalid one). Docs themselves are rendered\n // live by `vitops docs`, so nothing is generated into the repo from it here.\n let ds: DesignSystem | null = null;\n if (existsSync(resolve(inputRel)))\n ds = loadDesignSystem(resolve(inputRel), values.theme as string | undefined);\n else console.warn(` ⚠ ${inputRel} not found — run \\`vitops init\\` to scaffold one`);\n\n // Explicit --docs-dir = legacy layout: write the docs bundle as files, no skill.\n const legacyDocsDir = values['docs-dir'] as string | undefined;\n let summary: string;\n let pointer: string[];\n\n if (legacyDocsDir) {\n if (!ds) fail(`--docs-dir needs a config to render docs from (${inputRel} not found)`);\n let docs: Record<string, string> = {};\n try {\n docs = generateDocs(ds, generatorAssetsDir());\n } catch (err) {\n fail(`could not generate docs: ${(err as Error).message}`);\n }\n for (const [rel, content] of Object.entries(docs)) {\n const p = resolve(legacyDocsDir, rel);\n mkdirSync(dirname(p), { recursive: true });\n writeFileSync(p, content);\n }\n summary = `wrote ${Object.keys(docs).length} docs to ${legacyDocsDir}/`;\n pointer = [\n 'Prefer the framework’s utility + component classes over hand-written CSS.',\n `Reference docs (regenerate with \\`vitops agents --docs-dir ${legacyDocsDir}\\`): \\`${legacyDocsDir}/css/classes.md\\`,`,\n `\\`${legacyDocsDir}/authoring.md\\`, \\`${legacyDocsDir}/formats.md\\`, \\`${legacyDocsDir}/bricks/elements.md\\`.`,\n ];\n } else {\n // Link the packaged skill (ships inside @getvitops/cli) into the agent\n // discovery locations; nothing is generated into the repo.\n const target = findSkillTarget(process.cwd());\n if (target) {\n for (const dir of ['.agents', '.claude']) {\n const warn = linkSkill(resolve(dir, 'skills', SKILL_NAME), target);\n if (warn) console.warn(` ⚠ ${warn}`);\n }\n summary = `linked {.agents,.claude}/skills/${SKILL_NAME} → ${target}`;\n } else {\n console.warn(\n ` ⚠ could not find node_modules/@getvitops/cli/skill — install @getvitops/cli as a devDependency, then re-run \\`vitops agents\\``,\n );\n summary = 'no skill linked';\n }\n pointer = [\n 'Prefer the framework’s utility + component classes over hand-written CSS.',\n `Full design-system context lives in the \\`${SKILL_NAME}\\` skill (linked from`,\n '`.agents/skills/` and `.claude/skills/` into the installed `@getvitops/cli`;',\n 're-link with `vitops agents` if the links are deleted — they survive version',\n 'bumps). Reference docs print live, from this project’s config, via:',\n '',\n ...Object.entries(TOPICS).map(([name, t]) => `- \\`vitops docs ${name}\\` — ${t.summary}`),\n ];\n }\n\n // Only spelled out when it isn't the default the commands already assume.\n const inputFlag = inputRel === 'design-system.json' ? '' : ` --input ${inputRel}`;\n const block = [\n AGENTS_START,\n '## Vitops design system',\n '',\n `Styled with the Vitops design system (\\`@getvitops/*\\`); tokens live in \\`${inputRel}\\`.`,\n 'Generate output with the CLI:',\n '',\n // Interpolated, not hard-coded: `generate` defaults --input to\n // design-system.json and hard-fails when it is absent, so an emitted command\n // without the flag is copy-paste-broken in exactly the projects that most\n // need the block to be right.\n `- \\`vitops generate${inputFlag} --format tailwind --out src/styles\\` — Tailwind v4 / Astro`,\n `- \\`vitops generate${inputFlag} --format css --out dist\\` — standalone CSS`,\n `- \\`vitops generate${inputFlag} --format bricks --out <theme>/dist\\` — WordPress / Bricks`,\n `- \\`vitops generate${inputFlag} --format design --out .\\` — \\`DESIGN.md\\`, the agent-facing brief`,\n `- \\`vitops init\\` · \\`vitops validate${inputFlag}\\` · \\`vitops favicon\\``,\n '',\n ...pointer,\n '',\n `<!-- regenerate: vitops agents · @getvitops/cli@${cliVersion()} -->`,\n AGENTS_END,\n ].join('\\n');\n\n const outPath = resolve(values.out as string);\n let next: string;\n let action: string;\n if (existsSync(outPath)) {\n const cur = readFileSync(outPath, 'utf8');\n const s = cur.indexOf(AGENTS_START);\n const e = cur.indexOf(AGENTS_END);\n if (s !== -1 && e !== -1 && e > s) {\n next = cur.slice(0, s) + block + cur.slice(e + AGENTS_END.length);\n action = 'updated block in';\n } else {\n next = cur.replace(/\\s*$/, '') + '\\n\\n' + block + '\\n';\n action = 'appended block to';\n }\n } else {\n mkdirSync(dirname(outPath), { recursive: true });\n next = block + '\\n';\n action = 'created';\n }\n writeFileSync(outPath, next);\n console.log(`✓ ${action} ${values.out} + ${summary}`);\n}\n\nasync function main() {\n const [command, ...rest] = process.argv.slice(2);\n if (!command || command === '-h' || command === '--help' || command === 'help') {\n console.log(HELP);\n return;\n }\n // Answered before dispatch, because `parseArgs` is strict and every\n // subcommand would otherwise reject `--help` as an unknown option.\n if (wantsHelp(rest)) {\n console.log(helpFor(command, rest));\n return;\n }\n switch (command) {\n case 'generate':\n return cmdGenerate(rest);\n case 'init':\n return cmdInit(rest);\n case 'validate':\n return cmdValidate(rest);\n case 'favicon':\n return cmdFavicon(rest);\n case 'agents':\n return cmdAgents(rest);\n case 'docs':\n return cmdDocs(rest);\n case 'lint':\n return cmdLint(rest);\n case 'legal':\n return cmdLegal(rest);\n case 'icons':\n return cmdIcons(rest);\n case 'search':\n return cmdSearch(rest);\n case 'ads':\n return cmdAds(rest);\n case 'media':\n return cmdMedia(rest);\n default:\n fail(`unknown command \"${command}\" (expected: ${COMMANDS.join(' | ')}). Try: vitops --help`);\n }\n}\n\nmain().catch((err) => fail((err as Error).message));\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAeA,MAAa,aAAa;;AAG1B,MAAa,mBAAmB;;;;;AAMhC,MAAa,SAA4D;CACvE,SAAS;EACP,MAAM;EACN,SAAS;CACX;CACA,WAAW;EACT,MAAM;EACN,SAAS;CACX;CACA,QAAQ;EACN,MAAM;EACN,SACE;CACJ;CACA,SAAS;EACP,MAAM;EACN,SAAS;CACX;CACA,OAAO;EACL,MAAM;EACN,SAAS;CACX;CACA,QAAQ;EACN,MAAM;EACN,SAAS;CACX;CACA,OAAO;EACL,MAAM;EACN,SAAS;CACX;CACA,UAAU;EACR,MAAM;EACN,SAAS;CACX;CACA,YAAY;EACV,MAAM;EACN,SAAS;CACX;CACA,SAAS;EACP,MAAM;EACN,SAAS;CACX;CACA,UAAU;EACR,MAAM;EACN,SAAS;CACX;CACA,QAAQ;EACN,MAAM;EACN,SAAS;CACX;CACA,OAAO;EACL,MAAM;EACN,SAAS;CACX;CACA,UAAU;EACR,MAAM;EACN,SAAS;CACX;AACF;;;;;;;;;;;;AAaA,SAAgB,gBAAgB,KAA4B;CAC1D,IAAI,MAAM,QAAQ,GAAG;CACrB,MAAM,EAAE,SAAS,MAAM,GAAG;CAC1B,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