@getvitops/cli 8.2.0 → 8.3.0-alpha.1

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 CHANGED
@@ -2,7 +2,7 @@
2
2
  import { createRequire } from "node:module";
3
3
  import { parseArgs } from "node:util";
4
4
  import { pathToFileURL } from "node:url";
5
- import { existsSync, lstatSync, mkdirSync, readFileSync, readlinkSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
5
+ import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, readlinkSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
6
6
  import { dirname, extname, join, parse, relative, resolve } from "node:path";
7
7
  import { CONFIG_SCHEMA_LOCAL_PATH, JURISDICTION_COUNTRIES, NUMERIC_STEPS, SCHEMA_LOCAL_PATH, buildIconSprite, defaultConfig, defaultSiteConfig, enabledDocs, expandPalette, functionalRole, generate, generateDocs, generateLegal, isConfig, movedTokens, processorsMissingLocation, renderRobotsTxt, resolveConfig, resolveInput, resolveTheme, roleColorUtilities, roleHue, roleKind, validate } from "@getvitops/generator";
8
8
  import { collectIconRefs, generateFavicons, generateIconInclude, resolveIcon, scanFiles } from "@getvitops/utils";
@@ -14,11 +14,14 @@ import { addSite, backoffSchedule, createApexTxt, findZoneId, formatPlan as form
14
14
  import { AD_PLATFORMS, AD_PROVIDER_KEYS, formatPlan as formatPlan$4, formatSummary as formatSummary$1, hasDrift as hasDrift$1, isAdProvider, missingFields, normalizeConversionActionIds, normalizeConversionLabels, plan as plan$3, renderTag, tagId } from "@getvitops/utils/ads";
15
15
  import { PLATFORM_PARAMS } from "@getvitops/utils/tracking";
16
16
  import { createInterface } from "node:readline/promises";
17
+ import { DEFAULT_BUDGETS, buildReport, fetchSitemapPaths, formatSummary as formatSummary$2, parseImpacts, pathsFromSeed, planPages, preflight, reportFiles, runAudit, runCommand, startPreview } from "@getvitops/utils/audit";
17
18
  import { zohoAccountsHost, zohoApiHost } from "@getvitops/utils/crm";
18
- import { backoffSchedule as backoffSchedule$1, blockedDomains, collectFromAddresses, dnsStatus, enableSending, findZoneForHost, formatPlan as formatPlan$5, formatSummary as formatSummary$2, hasDrift as hasDrift$2, listSendingSubdomains, planSendingDomains, resolveTxt, sendingDns } from "@getvitops/utils/email";
19
+ import { backoffSchedule as backoffSchedule$1, blockedDomains, collectFromAddresses, dnsStatus, enableSending, findZoneForHost, formatPlan as formatPlan$5, formatSummary as formatSummary$3, hasDrift as hasDrift$2, listSendingSubdomains, planSendingDomains, resolveTxt, sendingDns } from "@getvitops/utils/email";
19
20
  import { normalizeEmailChannel, resolveSender } from "@getvitops/utils/notify";
20
- import { execFileSync } from "node:child_process";
21
- import { adminCollaboratorIds, branches, createD1, createDevEnvironment, createProdEnvironment, createR2Bucket, createRepo, defaultBranch, environments, findD1, findR2Bucket, formatPlan as formatPlan$6, formatSummary as formatSummary$3, ghAuthed, mainProtected, originRemote, plan as plan$4, planDomainConsistency, protectMain, pushBranches, repoNwo, secretsPresent, setDefaultBranch, setSecret, wranglerWhoami } from "@getvitops/utils/hosting";
21
+ import { execFileSync, spawnSync } from "node:child_process";
22
+ import { createServer } from "node:net";
23
+ import { adminCollaboratorIds, branches, createD1, createDevEnvironment, createProdEnvironment, createR2Bucket, createRepo, defaultBranch, environments, findD1, findR2Bucket, formatPlan as formatPlan$6, formatSummary as formatSummary$4, ghAuthed, mainProtected, originRemote, plan as plan$4, planDomainConsistency, protectMain, pushBranches, repoNwo, secretsPresent, setDefaultBranch, setSecret, wranglerWhoami } from "@getvitops/utils/hosting";
24
+ import { createWidget, deriveDomains, formatPlan as formatPlan$7, formatSummary as formatSummary$5, hasDrift as hasDrift$3, listWidgets, patchSiteKey, plan as plan$5, resolveAccountId } from "@getvitops/utils/turnstile";
22
25
 
23
26
  // src/args.ts
24
27
  /**
@@ -360,6 +363,7 @@ Usage:
360
363
  vitops setup <sub> [opts] Scripted onboarding: repo, hosting, domain, search, ads, all
361
364
  vitops email <sub> [opts] Sender-domain onboarding: check (setup) + deploy guard (check)
362
365
  vitops media [options] Encode raw video into web-ready WebM + MP4 + poster
366
+ vitops audit [options] Performance + accessibility budgets over a built site (Lighthouse + axe)
363
367
 
364
368
  Generate options:
365
369
  -i, --input <path> design-system.json or site config (default: ./design-system.json)
@@ -415,7 +419,8 @@ Agents options:
415
419
  Docs options:
416
420
  <topic> classes | authoring | formats | color | scales | patterns | elements
417
421
  (no topic: list topics with summaries)
418
- -i, --input <path> design-system.json or site config (default: ./design-system.json)
422
+ -i, --input <path> site config or design-system.json (default: ./site.json, else
423
+ ./design-system.json)
419
424
  --theme <name> Theme to render docs from, when --input is a site config
420
425
  --all Print every topic, concatenated
421
426
 
@@ -428,7 +433,8 @@ Icons options:
428
433
  --json Machine-readable report on stdout
429
434
 
430
435
  Lint options:
431
- -i, --input <path> design-system.json or site config (default: ./design-system.json)
436
+ -i, --input <path> site config or design-system.json (default: ./site.json, else
437
+ ./design-system.json)
432
438
  --theme <name> Theme to judge classes against, when --input is a site config
433
439
  -f, --format <fmt> Format you build (bricks | css | tailwind; default: bricks).
434
440
  Responsive md-* classes are real in css/bricks, inert in tailwind.
@@ -671,6 +677,22 @@ Setup domain options:
671
677
  or deploys. Cutover overwrites the zone's DNS record and can take an existing live
672
678
  site down; that step is manual, on purpose. See SETUP.html's "Domain strategy" stage.
673
679
 
680
+ Setup turnstile options:
681
+ -i, --input <path> Site config (default: ./site.json)
682
+ --site-env <env> Environment to read (default: production)
683
+ --dry Print the plan and exit (needs no token)
684
+ --check Exit non-zero if no widget/site key is set up; mutates nothing
685
+ --no-write Do not write site.security.turnstile.siteKey back to the config
686
+ --no-secret Do not run \`wrangler secret put\` for the new widget's secret
687
+
688
+ Creates a managed Turnstile widget for the site's hostnames (canonical + each
689
+ environment URL) unless one already covers them, and writes the PUBLIC site key to
690
+ site.security.turnstile.siteKey. The SECRET is returned once at creation: it is piped
691
+ to \`wrangler secret put VITOPS_TURNSTILE_SECRET\` and never written to a config file.
692
+ Never edits, rotates or deletes an existing widget.
693
+ Needs CLOUDFLARE_API_TOKEN with "Account > Turnstile > Edit", plus CLOUDFLARE_ACCOUNT_ID
694
+ (or a token that can list accounts), and \`wrangler login\` for the secret.
695
+
674
696
  Setup search options:
675
697
  Forwards every option to \`vitops search setup\` unchanged — see "Search setup
676
698
  options:" above.
@@ -689,6 +711,21 @@ Setup all options:
689
711
  Runs repo, hosting, search, ads in order. Stops at the first stage that fails;
690
712
  a blocked step (the API token, GitHub Pro/Team gating) is reported, not fatal.
691
713
 
714
+ Emdash subcommands:
715
+ vitops emdash prepare-db Migrate and seed the local D1 the build prerenders from
716
+ vitops emdash check-prerender [d] Fail if a prerendered page is not a real page
717
+
718
+ Emdash prepare-db options:
719
+ (none) Starts \`astro dev\` once, calls EmDash's dev-bypass setup (migrates, applies the
720
+ seed's sample content), checks the home page renders, stops. Only writes the
721
+ disposable .wrangler/state. SKIP_PREPARE_LOCAL_DB=1 skips it.
722
+
723
+ Emdash check-prerender options:
724
+ [dir] Build output to check (default: dist/client). Fails on a page that carries the
725
+ pending-migrations message, is not an HTML document, or has no <title>.
726
+ --strict Also fail (not just warn) when a page uses a type-role class (font-display, …)
727
+ the built CSS has no rule for.
728
+
692
729
  Email subcommands:
693
730
  vitops email setup [domain] Onboard a from-address domain, waiting for its DNS to resolve
694
731
  vitops email check [opts] Non-blocking deploy guard: warn if a from domain isn't onboarded
@@ -754,6 +791,31 @@ Media options:
754
791
  ffmpeg output is not reproducible across versions, so re-encoding in CI churns
755
792
  the diff on every toolchain bump. Use --force when you mean to re-encode.
756
793
 
794
+ Audit options:
795
+ --build Run \`astro build\` first (default: audit the existing build)
796
+ --url <base> Audit an already-running server instead of \`astro preview\`
797
+ --port <n> Port for \`astro preview\` (default: 4398; aborts if taken)
798
+ --dir <path> Project directory (default: .)
799
+ --pages <list> Extra comma-separated paths. The page list is the built sitemap
800
+ plus links in seed/seed.json's primary* and footer* menus; only
801
+ when neither exists are / /privacy /terms /cookies /contact
802
+ guessed. A 404 skips a page (with its reason in the report); a
803
+ 404 on / fails the run.
804
+ --no-defaults Never guess the default pages
805
+ --seed <path> EmDash seed to read menus from (default: seed/seed.json if present)
806
+ --lcp <ms> LCP budget (default: 2500)
807
+ --cls <n> CLS budget (default: 0.1)
808
+ --tbt <ms> Total Blocking Time budget, the INP proxy (default: 200)
809
+ --impact <list> axe impacts that fail a page (default: serious,critical)
810
+ --form-factor <f> mobile | desktop Lighthouse profile (default: mobile)
811
+ -o, --out <dir> Report directory (default: .vitops/audit): report.json, report.md,
812
+ and pages/<page>.{json,md}
813
+ --warn Report without failing (exit 0), for first adoption
814
+
815
+ Needs the optional packages: vp add -D playwright @axe-core/playwright lighthouse
816
+ && vp exec playwright install chromium (checked before any server starts). A pass means no automated axe violations and the
817
+ budgets held — it is NOT AODA certification; report.md lists the manual checks.
818
+
757
819
  Common:
758
820
  -h, --help Show this help
759
821
  `;
@@ -784,6 +846,15 @@ const EMAIL_HELP = `vitops email — sender-domain onboarding checks
784
846
  vitops email setup [domain] Onboard a from-address domain, waiting for its DNS to resolve
785
847
  vitops email check [opts] Non-blocking deploy guard: warn if a from domain isn't onboarded
786
848
 
849
+ Run \`vitops --help\` for the full option list for each subcommand.
850
+ `;
851
+ const EMDASH_HELP = `vitops emdash — build-time steps for an EmDash site
852
+
853
+ vitops emdash prepare-db Migrate and seed the local D1 the build prerenders from
854
+ (SKIP_PREPARE_LOCAL_DB=1 skips)
855
+ vitops emdash check-prerender [d] Fail if a prerendered page under [d] (default dist/client)
856
+ is not a real page
857
+
787
858
  Run \`vitops --help\` for the full option list for each subcommand.
788
859
  `;
789
860
  const SETUP_HELP$1 = `vitops setup — the scripted path from an empty scaffold to a live site
@@ -820,7 +891,9 @@ const COMMANDS = [
820
891
  "crm",
821
892
  "setup",
822
893
  "email",
823
- "media"
894
+ "emdash",
895
+ "media",
896
+ "audit"
824
897
  ];
825
898
  /**
826
899
  * The slice of `HELP` documenting one command, addressed by its heading.
@@ -849,7 +922,7 @@ const wantsHelp = (argv) => argv.includes("-h") || argv.includes("--help");
849
922
  /** The help text to print for `vitops <command> [sub] --help`. */
850
923
  function helpFor(command, argv) {
851
924
  const sub = argv[0] && !argv[0].startsWith("-") ? argv[0] : void 0;
852
- return (sub ? helpSection(command, sub) : void 0) ?? helpSection(command) ?? (command === "search" ? "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" : command === "ads" ? "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" : command === "crm" ? "vitops crm — push form submissions into a client CRM\n\n vitops crm check [opts] Compare site.crm's fieldMap/trackingFields against the live CRM\n vitops crm setup [opts] Create missing HubSpot properties (Bigin/Jobber have no such API)\n\nRun `vitops --help` for the full option list for each subcommand.\n" : command === "setup" ? "vitops setup — the scripted path from an empty scaffold to a live site\n\n vitops setup repo [opts] GitHub repo + branch policy (main protected, dev open)\n vitops setup hosting [opts] Dev D1 + R2 + repo secrets (cloudflare) or a Node target\n vitops setup domain [opts] Plan/check the workers.dev-vs-custom-domain consistency\n (never applies the cutover — see SETUP.html)\n vitops setup search [opts] Forwards to `vitops search setup`\n vitops setup ads [opts] Forwards to `vitops ads setup`\n vitops setup all [opts] Run repo, hosting, search, ads in order\n\nRun `vitops --help` for the full option list for each subcommand.\n" : command === "email" ? "vitops email — sender-domain onboarding checks\n\n vitops email setup [domain] Onboard a from-address domain, waiting for its DNS to resolve\n vitops email check [opts] Non-blocking deploy guard: warn if a from domain isn't onboarded\n\nRun `vitops --help` for the full option list for each subcommand.\n" : void 0) ?? "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 robots [options] Render robots.txt from a site config's environment\n vitops reviews [options] Fetch + cache Google Business Profile reviews\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 setup <sub> [opts] Scripted onboarding: repo, hosting, domain, search, ads, all\n vitops email <sub> [opts] Sender-domain onboarding: check (setup) + deploy guard (check)\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, or\n ./site.json with --site)\n --force Overwrite an existing file\n --site Write a site config (Config) instead of a bare\n design-system.json — embeds a starter design system at\n designSystem.themes.default, since a Config can't\n merely reference a sibling file\n --name <name> organization.name, when --site is set\n --url <url> site.environments.{production,dev}.url, when --site is set\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 -i, --input <path> Site config carrying the \"icons\" block (default: ./site.json)\n --site-env <env> Environment whose A/B variant applies (default: production)\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\nRobots options:\n -i, --input <path> Site config: .json, or a .js/.ts module with a default\n export (default: ./site.json)\n -o, --out <dir> Write robots.txt here (default: print to stdout)\n --site-env <env> Which site.environments entry to render for (default: production)\n\n Reads the resolved environment's robots directive (falling back to\n site.seo.robots) — the same fact vitops search notify's noindex gate already\n reads. A directive containing noindex disallows every user agent and emits\n no Sitemap line; otherwise it allows everything and links\n site.seo.indexing.sitemapUrl, or the derived <canonical>/sitemap-index.xml.\n\nReviews options:\n -i, --input <path> Site config carrying site.reviews (default: ./site.json)\n --site-env <env> Environment whose A/B variant applies (default: production)\n --location <key> Fetch only this site.reviews.locations key\n --cache <path> Where to read/write the cache (default: .vitops/reviews.json)\n --out <dir> Also write the selected reviews per location as JSON here\n --dry Print the plan and exit. Fetches nothing.\n --check Fetch and diff against the cache; exit non-zero on drift.\n Mutates nothing.\n\n Reviews live only on the legacy Business Profile v4 API — there is no newer\n replacement — and the calling GCP project must be allowlisted by Google before\n any call succeeds (a one-time approval; a 403 says so rather than failing\n opaquely). Auth is user OAuth, the same VITOPS_GOOGLE_CLIENT_ID /\n VITOPS_GOOGLE_CLIENT_SECRET / VITOPS_GOOGLE_REFRESH_TOKEN (or ADC login) that\n vitops search setup uses, scoped to business.manage. The cache is meant to be\n committed: reviews change slowly, and a build should not need a live Google\n credential. Review JSON-LD is off by default (site.reviews.schema) — a business\n marking up reviews of itself is not eligible for Google's rich results and\n risks a manual action.\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\n Or just be logged in: with no VITOPS_GOOGLE_* set, an Application Default\n Credentials login is used —\n gcloud auth application-default login \\\n --scopes=openid,https://www.googleapis.com/auth/siteverification,\\\n https://www.googleapis.com/auth/webmasters,https://www.googleapis.com/auth/cloud-platform\n ADC authenticates through a shared OAuth client that owns no project, so it also\n needs site.google.project in the config (sent as x-goog-user-project), both APIs\n enabled on that project, and serviceusage.services.use on it. One project per site\n is what keeps each site's API usage and billing separate.\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\nCrm check options:\n -i, --input <path> Site config carrying site.crm (default: ./site.json)\n --site-env <env> Environment to resolve (default: production)\n\n Fetches the live field/property list (HubSpot: crm/v3/properties/contacts;\n Bigin: bigin/v2/settings/fields) and reports every fieldMap/trackingFields\n target that doesn't exist there. HubSpot rejects a submission naming an\n unrecognised property; Bigin silently ignores it — this is the only way to\n see a broken mapping before a real submission finds it. Needs\n VITOPS_HUBSPOT_ACCESS_TOKEN, VITOPS_ZOHO_CLIENT_ID/_CLIENT_SECRET/\n _REFRESH_TOKEN, or (unused for now) VITOPS_JOBBER_CLIENT_ID/_CLIENT_SECRET/\n _REFRESH_TOKEN, matching whichever provider site.crm names. Jobber currently\n renders fieldMap/trackingFields as note-text lines rather than app-configured\n custom fields, so there is nothing live to check there yet. Exits non-zero\n on any missing target.\n\nCrm setup options:\n -i, --input <path> Site config carrying site.crm (default: ./site.json)\n --site-env <env> Environment to resolve (default: production)\n --dry Print what would be created and exit. Creates nothing.\n\n HubSpot: creates missing contact properties named by fieldMap/trackingFields.\n Bigin: no such API exists, so this always prints a manual reminder listing\n the fields to add in Zoho Bigin's field editor, then re-run \"crm check\".\n Jobber: app-configured custom fields aren't wired up yet, so this prints a\n reminder instead of creating anything.\n\nSetup repo options:\n --dry Print the plan and exit\n --check Report drift/blocked steps and exit non-zero, mutating nothing\n --public Create the repo public (default: private)\n --platform <p> cloudflare (default) | node — shown for parity with the hosting stage's plan\n --no-dev-resources Same — this stage never provisions D1/R2 either way\n\n Creates the GitHub repo (via `gh`), pushes main + dev, makes dev the default\n branch, and requests main branch protection + the production/dev environments.\n Idempotent — a re-run of a fully set-up repo is all skips. Branch protection and\n environment reviewers 403 on a private repo without GitHub Pro/Team; that is\n reported as blocked, with the manual Settings path, never as a failure.\n\nSetup hosting options:\n --dry Print the plan and exit\n --check Report drift/blocked steps and exit non-zero, mutating nothing\n --platform <p> cloudflare (default) | node\n --no-dev-resources Skip D1/R2 — a pure static Workers Assets project has\n nothing to provision, just the account id + token\n\n Provisions the isolated dev D1 database + R2 bucket (cloudflare) and sets the\n DEV_D1_ID / CLOUDFLARE_ACCOUNT_ID repo secrets, once `vitops setup repo` has run.\n CLOUDFLARE_API_TOKEN is always reported as blocked — no API can create one; see\n the printed dashboard link. Requires `npx wrangler login` first.\n\nSetup domain options:\n -i, --input <path> Site config (default: ./site.json)\n --site-env <env> Environment to check (default: production)\n --dry Print the plan and exit\n --check Exit non-zero if the domain state is inconsistent\n --domain <apex> Print the manual cutover steps for this apex\n\n Plans and checks the consistency between wrangler.jsonc's workers.dev/custom-domain\n state and site.json's environments/domains/robots — it NEVER edits wrangler.jsonc\n or deploys. Cutover overwrites the zone's DNS record and can take an existing live\n site down; that step is manual, on purpose. See SETUP.html's \"Domain strategy\" stage.\n\nSetup search options:\n Forwards every option to `vitops search setup` unchanged — see \"Search setup\n options:\" above.\n\nSetup ads options:\n Forwards every option to `vitops ads setup` unchanged — see \"Ads setup options:\"\n above.\n\nSetup all options:\n --dry Print every stage's plan and exit\n --check Report drift across every stage and exit non-zero\n --public Create the repo public, for the repo stage\n --platform <p> cloudflare (default) | node, for the repo + hosting stages\n --no-dev-resources Skip D1/R2 in the hosting stage (repo stage never provisions them)\n\n Runs repo, hosting, search, ads in order. Stops at the first stage that fails;\n a blocked step (the API token, GitHub Pro/Team gating) is reported, not fatal.\n\nEmail subcommands:\n vitops email setup [domain] Onboard a from-address domain, waiting for its DNS to resolve\n vitops email check [opts] Non-blocking deploy guard: warn if a from domain isn't onboarded\n\nEmail setup options:\n -i, --input <path> Site config carrying site.notifications.email (default: ./site.json)\n --site-env <env> Environment whose A/B variant applies (default: production)\n [domain] Onboard this exact name instead of deriving candidates from\n config + a source scan\n --src <dir> Source to scan for from: literals as a supplement to config\n (default: ./src)\n --dry Print the plan and exit. Needs no credential — plans from\n scratch and says so.\n --check Report drift and exit non-zero. Mutates nothing.\n --no-prompt Never ask before enabling a domain (the default when\n stdin is not a TTY, e.g. in CI — it just enables)\n --timeout <s> Cap on each DNS-propagation poll wait, in seconds (default: 5)\n\n The onboarded entity is an EXACT name, and it is usually a subdomain\n (send.example.com), never the apex a from address names. When the exact\n domain is absent but a sibling in the same zone is already onboarded, this\n is reported blocked rather than silently enabling the apex too — enabling\n it rewrites _dmarc.<domain>, which can tighten policy on every OTHER mail\n sent from that domain. Sending from the onboarded sibling is the\n recommended fix. Needs CLOUDFLARE_API_TOKEN (Zone:Read + an Email Sending\n scope — broader than the \"Edit zone DNS\" template other commands use).\n\nEmail check options:\n -i, --input <path> Site config carrying site.notifications.email (default: ./site.json)\n --site-env <env> Environment whose A/B variant applies (default: production)\n --src <dir> Source to scan for from: literals (default: ./src)\n --strict Exit non-zero on drift (the default just warns and exits 0)\n --skip Skip the check entirely (same as VITOPS_SKIP_EMAIL_CHECK)\n\n Meant to run before a deploy. With no CLOUDFLARE_API_TOKEN it reports \"not\n checked\" and exits 0, so a CI job without the secret never fails on the\n check itself. Skip per-site with site.notifications.email.verifySender: false\n when the scan can't see the real from address and the warning would be a\n false positive.\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";
925
+ return (sub ? helpSection(command, sub) : void 0) ?? helpSection(command) ?? (command === "search" ? "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" : command === "ads" ? "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" : command === "crm" ? "vitops crm — push form submissions into a client CRM\n\n vitops crm check [opts] Compare site.crm's fieldMap/trackingFields against the live CRM\n vitops crm setup [opts] Create missing HubSpot properties (Bigin/Jobber have no such API)\n\nRun `vitops --help` for the full option list for each subcommand.\n" : command === "setup" ? "vitops setup — the scripted path from an empty scaffold to a live site\n\n vitops setup repo [opts] GitHub repo + branch policy (main protected, dev open)\n vitops setup hosting [opts] Dev D1 + R2 + repo secrets (cloudflare) or a Node target\n vitops setup domain [opts] Plan/check the workers.dev-vs-custom-domain consistency\n (never applies the cutover — see SETUP.html)\n vitops setup search [opts] Forwards to `vitops search setup`\n vitops setup ads [opts] Forwards to `vitops ads setup`\n vitops setup all [opts] Run repo, hosting, search, ads in order\n\nRun `vitops --help` for the full option list for each subcommand.\n" : command === "email" ? "vitops email — sender-domain onboarding checks\n\n vitops email setup [domain] Onboard a from-address domain, waiting for its DNS to resolve\n vitops email check [opts] Non-blocking deploy guard: warn if a from domain isn't onboarded\n\nRun `vitops --help` for the full option list for each subcommand.\n" : command === "emdash" ? "vitops emdash — build-time steps for an EmDash site\n\n vitops emdash prepare-db Migrate and seed the local D1 the build prerenders from\n (SKIP_PREPARE_LOCAL_DB=1 skips)\n vitops emdash check-prerender [d] Fail if a prerendered page under [d] (default dist/client)\n is not a real page\n\nRun `vitops --help` for the full option list for each subcommand.\n" : void 0) ?? "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 robots [options] Render robots.txt from a site config's environment\n vitops reviews [options] Fetch + cache Google Business Profile reviews\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 setup <sub> [opts] Scripted onboarding: repo, hosting, domain, search, ads, all\n vitops email <sub> [opts] Sender-domain onboarding: check (setup) + deploy guard (check)\n vitops media [options] Encode raw video into web-ready WebM + MP4 + poster\n vitops audit [options] Performance + accessibility budgets over a built site (Lighthouse + axe)\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, or\n ./site.json with --site)\n --force Overwrite an existing file\n --site Write a site config (Config) instead of a bare\n design-system.json — embeds a starter design system at\n designSystem.themes.default, since a Config can't\n merely reference a sibling file\n --name <name> organization.name, when --site is set\n --url <url> site.environments.{production,dev}.url, when --site is set\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> site config or design-system.json (default: ./site.json, else\n ./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 -i, --input <path> Site config carrying the \"icons\" block (default: ./site.json)\n --site-env <env> Environment whose A/B variant applies (default: production)\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> site config or design-system.json (default: ./site.json, else\n ./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\nRobots options:\n -i, --input <path> Site config: .json, or a .js/.ts module with a default\n export (default: ./site.json)\n -o, --out <dir> Write robots.txt here (default: print to stdout)\n --site-env <env> Which site.environments entry to render for (default: production)\n\n Reads the resolved environment's robots directive (falling back to\n site.seo.robots) — the same fact vitops search notify's noindex gate already\n reads. A directive containing noindex disallows every user agent and emits\n no Sitemap line; otherwise it allows everything and links\n site.seo.indexing.sitemapUrl, or the derived <canonical>/sitemap-index.xml.\n\nReviews options:\n -i, --input <path> Site config carrying site.reviews (default: ./site.json)\n --site-env <env> Environment whose A/B variant applies (default: production)\n --location <key> Fetch only this site.reviews.locations key\n --cache <path> Where to read/write the cache (default: .vitops/reviews.json)\n --out <dir> Also write the selected reviews per location as JSON here\n --dry Print the plan and exit. Fetches nothing.\n --check Fetch and diff against the cache; exit non-zero on drift.\n Mutates nothing.\n\n Reviews live only on the legacy Business Profile v4 API — there is no newer\n replacement — and the calling GCP project must be allowlisted by Google before\n any call succeeds (a one-time approval; a 403 says so rather than failing\n opaquely). Auth is user OAuth, the same VITOPS_GOOGLE_CLIENT_ID /\n VITOPS_GOOGLE_CLIENT_SECRET / VITOPS_GOOGLE_REFRESH_TOKEN (or ADC login) that\n vitops search setup uses, scoped to business.manage. The cache is meant to be\n committed: reviews change slowly, and a build should not need a live Google\n credential. Review JSON-LD is off by default (site.reviews.schema) — a business\n marking up reviews of itself is not eligible for Google's rich results and\n risks a manual action.\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\n Or just be logged in: with no VITOPS_GOOGLE_* set, an Application Default\n Credentials login is used —\n gcloud auth application-default login \\\n --scopes=openid,https://www.googleapis.com/auth/siteverification,\\\n https://www.googleapis.com/auth/webmasters,https://www.googleapis.com/auth/cloud-platform\n ADC authenticates through a shared OAuth client that owns no project, so it also\n needs site.google.project in the config (sent as x-goog-user-project), both APIs\n enabled on that project, and serviceusage.services.use on it. One project per site\n is what keeps each site's API usage and billing separate.\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\nCrm check options:\n -i, --input <path> Site config carrying site.crm (default: ./site.json)\n --site-env <env> Environment to resolve (default: production)\n\n Fetches the live field/property list (HubSpot: crm/v3/properties/contacts;\n Bigin: bigin/v2/settings/fields) and reports every fieldMap/trackingFields\n target that doesn't exist there. HubSpot rejects a submission naming an\n unrecognised property; Bigin silently ignores it — this is the only way to\n see a broken mapping before a real submission finds it. Needs\n VITOPS_HUBSPOT_ACCESS_TOKEN, VITOPS_ZOHO_CLIENT_ID/_CLIENT_SECRET/\n _REFRESH_TOKEN, or (unused for now) VITOPS_JOBBER_CLIENT_ID/_CLIENT_SECRET/\n _REFRESH_TOKEN, matching whichever provider site.crm names. Jobber currently\n renders fieldMap/trackingFields as note-text lines rather than app-configured\n custom fields, so there is nothing live to check there yet. Exits non-zero\n on any missing target.\n\nCrm setup options:\n -i, --input <path> Site config carrying site.crm (default: ./site.json)\n --site-env <env> Environment to resolve (default: production)\n --dry Print what would be created and exit. Creates nothing.\n\n HubSpot: creates missing contact properties named by fieldMap/trackingFields.\n Bigin: no such API exists, so this always prints a manual reminder listing\n the fields to add in Zoho Bigin's field editor, then re-run \"crm check\".\n Jobber: app-configured custom fields aren't wired up yet, so this prints a\n reminder instead of creating anything.\n\nSetup repo options:\n --dry Print the plan and exit\n --check Report drift/blocked steps and exit non-zero, mutating nothing\n --public Create the repo public (default: private)\n --platform <p> cloudflare (default) | node — shown for parity with the hosting stage's plan\n --no-dev-resources Same — this stage never provisions D1/R2 either way\n\n Creates the GitHub repo (via `gh`), pushes main + dev, makes dev the default\n branch, and requests main branch protection + the production/dev environments.\n Idempotent — a re-run of a fully set-up repo is all skips. Branch protection and\n environment reviewers 403 on a private repo without GitHub Pro/Team; that is\n reported as blocked, with the manual Settings path, never as a failure.\n\nSetup hosting options:\n --dry Print the plan and exit\n --check Report drift/blocked steps and exit non-zero, mutating nothing\n --platform <p> cloudflare (default) | node\n --no-dev-resources Skip D1/R2 — a pure static Workers Assets project has\n nothing to provision, just the account id + token\n\n Provisions the isolated dev D1 database + R2 bucket (cloudflare) and sets the\n DEV_D1_ID / CLOUDFLARE_ACCOUNT_ID repo secrets, once `vitops setup repo` has run.\n CLOUDFLARE_API_TOKEN is always reported as blocked — no API can create one; see\n the printed dashboard link. Requires `npx wrangler login` first.\n\nSetup domain options:\n -i, --input <path> Site config (default: ./site.json)\n --site-env <env> Environment to check (default: production)\n --dry Print the plan and exit\n --check Exit non-zero if the domain state is inconsistent\n --domain <apex> Print the manual cutover steps for this apex\n\n Plans and checks the consistency between wrangler.jsonc's workers.dev/custom-domain\n state and site.json's environments/domains/robots — it NEVER edits wrangler.jsonc\n or deploys. Cutover overwrites the zone's DNS record and can take an existing live\n site down; that step is manual, on purpose. See SETUP.html's \"Domain strategy\" stage.\n\nSetup turnstile options:\n -i, --input <path> Site config (default: ./site.json)\n --site-env <env> Environment to read (default: production)\n --dry Print the plan and exit (needs no token)\n --check Exit non-zero if no widget/site key is set up; mutates nothing\n --no-write Do not write site.security.turnstile.siteKey back to the config\n --no-secret Do not run `wrangler secret put` for the new widget's secret\n\n Creates a managed Turnstile widget for the site's hostnames (canonical + each\n environment URL) unless one already covers them, and writes the PUBLIC site key to\n site.security.turnstile.siteKey. The SECRET is returned once at creation: it is piped\n to `wrangler secret put VITOPS_TURNSTILE_SECRET` and never written to a config file.\n Never edits, rotates or deletes an existing widget.\n Needs CLOUDFLARE_API_TOKEN with \"Account > Turnstile > Edit\", plus CLOUDFLARE_ACCOUNT_ID\n (or a token that can list accounts), and `wrangler login` for the secret.\n\nSetup search options:\n Forwards every option to `vitops search setup` unchanged — see \"Search setup\n options:\" above.\n\nSetup ads options:\n Forwards every option to `vitops ads setup` unchanged — see \"Ads setup options:\"\n above.\n\nSetup all options:\n --dry Print every stage's plan and exit\n --check Report drift across every stage and exit non-zero\n --public Create the repo public, for the repo stage\n --platform <p> cloudflare (default) | node, for the repo + hosting stages\n --no-dev-resources Skip D1/R2 in the hosting stage (repo stage never provisions them)\n\n Runs repo, hosting, search, ads in order. Stops at the first stage that fails;\n a blocked step (the API token, GitHub Pro/Team gating) is reported, not fatal.\n\nEmdash subcommands:\n vitops emdash prepare-db Migrate and seed the local D1 the build prerenders from\n vitops emdash check-prerender [d] Fail if a prerendered page is not a real page\n\nEmdash prepare-db options:\n (none) Starts `astro dev` once, calls EmDash's dev-bypass setup (migrates, applies the\n seed's sample content), checks the home page renders, stops. Only writes the\n disposable .wrangler/state. SKIP_PREPARE_LOCAL_DB=1 skips it.\n\nEmdash check-prerender options:\n [dir] Build output to check (default: dist/client). Fails on a page that carries the\n pending-migrations message, is not an HTML document, or has no <title>.\n --strict Also fail (not just warn) when a page uses a type-role class (font-display, …)\n the built CSS has no rule for.\n\nEmail subcommands:\n vitops email setup [domain] Onboard a from-address domain, waiting for its DNS to resolve\n vitops email check [opts] Non-blocking deploy guard: warn if a from domain isn't onboarded\n\nEmail setup options:\n -i, --input <path> Site config carrying site.notifications.email (default: ./site.json)\n --site-env <env> Environment whose A/B variant applies (default: production)\n [domain] Onboard this exact name instead of deriving candidates from\n config + a source scan\n --src <dir> Source to scan for from: literals as a supplement to config\n (default: ./src)\n --dry Print the plan and exit. Needs no credential — plans from\n scratch and says so.\n --check Report drift and exit non-zero. Mutates nothing.\n --no-prompt Never ask before enabling a domain (the default when\n stdin is not a TTY, e.g. in CI — it just enables)\n --timeout <s> Cap on each DNS-propagation poll wait, in seconds (default: 5)\n\n The onboarded entity is an EXACT name, and it is usually a subdomain\n (send.example.com), never the apex a from address names. When the exact\n domain is absent but a sibling in the same zone is already onboarded, this\n is reported blocked rather than silently enabling the apex too — enabling\n it rewrites _dmarc.<domain>, which can tighten policy on every OTHER mail\n sent from that domain. Sending from the onboarded sibling is the\n recommended fix. Needs CLOUDFLARE_API_TOKEN (Zone:Read + an Email Sending\n scope — broader than the \"Edit zone DNS\" template other commands use).\n\nEmail check options:\n -i, --input <path> Site config carrying site.notifications.email (default: ./site.json)\n --site-env <env> Environment whose A/B variant applies (default: production)\n --src <dir> Source to scan for from: literals (default: ./src)\n --strict Exit non-zero on drift (the default just warns and exits 0)\n --skip Skip the check entirely (same as VITOPS_SKIP_EMAIL_CHECK)\n\n Meant to run before a deploy. With no CLOUDFLARE_API_TOKEN it reports \"not\n checked\" and exits 0, so a CI job without the secret never fails on the\n check itself. Skip per-site with site.notifications.email.verifySender: false\n when the scan can't see the real from address and the warning would be a\n false positive.\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\nAudit options:\n --build Run `astro build` first (default: audit the existing build)\n --url <base> Audit an already-running server instead of `astro preview`\n --port <n> Port for `astro preview` (default: 4398; aborts if taken)\n --dir <path> Project directory (default: .)\n --pages <list> Extra comma-separated paths. The page list is the built sitemap\n plus links in seed/seed.json's primary* and footer* menus; only\n when neither exists are / /privacy /terms /cookies /contact\n guessed. A 404 skips a page (with its reason in the report); a\n 404 on / fails the run.\n --no-defaults Never guess the default pages\n --seed <path> EmDash seed to read menus from (default: seed/seed.json if present)\n --lcp <ms> LCP budget (default: 2500)\n --cls <n> CLS budget (default: 0.1)\n --tbt <ms> Total Blocking Time budget, the INP proxy (default: 200)\n --impact <list> axe impacts that fail a page (default: serious,critical)\n --form-factor <f> mobile | desktop Lighthouse profile (default: mobile)\n -o, --out <dir> Report directory (default: .vitops/audit): report.json, report.md,\n and pages/<page>.{json,md}\n --warn Report without failing (exit 0), for first adoption\n\n Needs the optional packages: vp add -D playwright @axe-core/playwright lighthouse\n && vp exec playwright install chromium (checked before any server starts). A pass means no automated axe violations and the\n budgets held — it is NOT AODA certification; report.md lists the manual checks.\n\nCommon:\n -h, --help Show this help\n";
853
926
  }
854
927
 
855
928
  // src/commands/search.ts
@@ -1666,6 +1739,163 @@ async function cmdAds(argv) {
1666
1739
  }
1667
1740
  }
1668
1741
 
1742
+ // src/commands/audit.ts
1743
+ /**
1744
+ * `vitops audit` — performance + accessibility budgets over a built site.
1745
+ *
1746
+ * The planner (page discovery, status handling, budgets, report rendering) is pure and
1747
+ * lives in `@getvitops/utils/audit` beside `ads/`, `indexing/` and `onboarding/`, as
1748
+ * `plan.ts`; this file is wiring only — flags in, files + exit code out. The browser
1749
+ * tooling (Playwright, axe, Lighthouse) is lazy and optional, see `audit/run.ts`.
1750
+ */
1751
+ /** Dedicated port: not Astro's 4321, which a developer's own `astro dev` is likely on. */
1752
+ const DEFAULT_PORT = 4398;
1753
+ function num(flag, raw, fallback) {
1754
+ if (raw === void 0) return fallback;
1755
+ const n = Number(raw);
1756
+ if (!Number.isFinite(n) || n <= 0) fail(`audit: --${flag} must be a positive number`);
1757
+ return n;
1758
+ }
1759
+ async function cmdAudit(argv) {
1760
+ const args = parse$1(argv, {
1761
+ dir: {
1762
+ type: "string",
1763
+ default: "."
1764
+ },
1765
+ url: { type: "string" },
1766
+ build: {
1767
+ type: "boolean",
1768
+ default: false
1769
+ },
1770
+ port: { type: "string" },
1771
+ pages: { type: "string" },
1772
+ "no-defaults": {
1773
+ type: "boolean",
1774
+ default: false
1775
+ },
1776
+ seed: { type: "string" },
1777
+ out: {
1778
+ type: "string",
1779
+ short: "o",
1780
+ default: ".vitops/audit"
1781
+ },
1782
+ lcp: { type: "string" },
1783
+ cls: { type: "string" },
1784
+ tbt: { type: "string" },
1785
+ impact: { type: "string" },
1786
+ "form-factor": {
1787
+ type: "string",
1788
+ default: "mobile"
1789
+ },
1790
+ warn: {
1791
+ type: "boolean",
1792
+ default: false
1793
+ }
1794
+ });
1795
+ const dir = resolve(args.str("dir"));
1796
+ const formFactor = args.str("form-factor");
1797
+ if (formFactor !== "mobile" && formFactor !== "desktop") fail("audit: --form-factor must be mobile or desktop");
1798
+ let impacts = DEFAULT_BUDGETS.blockingImpacts;
1799
+ const impactFlag = args.opt("impact");
1800
+ if (impactFlag) try {
1801
+ impacts = parseImpacts(impactFlag);
1802
+ } catch (err) {
1803
+ fail(`audit: ${msg(err)}`);
1804
+ }
1805
+ const budgets = {
1806
+ lcpMs: num("lcp", args.opt("lcp"), DEFAULT_BUDGETS.lcpMs),
1807
+ cls: num("cls", args.opt("cls"), DEFAULT_BUDGETS.cls),
1808
+ tbtMs: num("tbt", args.opt("tbt"), DEFAULT_BUDGETS.tbtMs),
1809
+ blockingImpacts: impacts
1810
+ };
1811
+ const seedFlag = args.opt("seed");
1812
+ const seedPath = seedFlag ? resolve(seedFlag) : join(dir, "seed", "seed.json");
1813
+ let menuPaths = [];
1814
+ if (existsSync(seedPath)) try {
1815
+ menuPaths = pathsFromSeed(JSON.parse(readFileSync(seedPath, "utf8")));
1816
+ } catch (err) {
1817
+ fail(`audit: could not read menus from ${seedPath}: ${msg(err)}`);
1818
+ }
1819
+ else if (seedFlag) fail(`audit: seed not found: ${seedPath}`);
1820
+ if (args.flag("build") && !args.opt("url")) {
1821
+ console.log("▸ building (astro build)");
1822
+ try {
1823
+ await runCommand("npx", [
1824
+ "--no-install",
1825
+ "astro",
1826
+ "build"
1827
+ ], dir);
1828
+ } catch (err) {
1829
+ fail(`audit: build failed: ${msg(err)}`);
1830
+ }
1831
+ }
1832
+ try {
1833
+ await preflight();
1834
+ } catch (err) {
1835
+ fail(`audit: ${msg(err)}`);
1836
+ }
1837
+ let server;
1838
+ let baseUrl = args.opt("url");
1839
+ const stopServer = () => server?.stop();
1840
+ const onSignal = (signal) => {
1841
+ stopServer();
1842
+ process.exit(signal === "SIGINT" ? 130 : 143);
1843
+ };
1844
+ process.once("SIGINT", onSignal);
1845
+ process.once("SIGTERM", onSignal);
1846
+ process.once("exit", stopServer);
1847
+ try {
1848
+ if (!baseUrl) {
1849
+ const port = num("port", args.opt("port"), DEFAULT_PORT);
1850
+ console.log(`▸ astro preview on :${port}`);
1851
+ server = await startPreview({
1852
+ cwd: dir,
1853
+ port
1854
+ });
1855
+ baseUrl = server.baseUrl;
1856
+ }
1857
+ const sitemapPaths = await fetchSitemapPaths(baseUrl);
1858
+ const paths = planPages({
1859
+ sitemapPaths,
1860
+ menuPaths,
1861
+ extra: (args.opt("pages") ?? "").split(",").map((s) => s.trim()).filter(Boolean),
1862
+ includeDefaults: !args.flag("no-defaults")
1863
+ });
1864
+ console.log(sitemapPaths.length ? `▸ ${sitemapPaths.length} page(s) from the sitemap` : "▸ no sitemap found; using menus and defaults");
1865
+ console.log(`▸ auditing ${paths.length} candidate page(s) at ${baseUrl} (${formFactor})`);
1866
+ const pages = await runAudit({
1867
+ baseUrl,
1868
+ paths,
1869
+ budgets,
1870
+ formFactor,
1871
+ onProgress: (m) => console.log(` ${m}`)
1872
+ });
1873
+ const report = buildReport({
1874
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
1875
+ baseUrl,
1876
+ formFactor,
1877
+ budgets,
1878
+ pages
1879
+ });
1880
+ const out = resolve(dir, args.str("out"));
1881
+ for (const [name, contents] of Object.entries(reportFiles(report))) {
1882
+ const file = join(out, name);
1883
+ mkdirSync(dirname(file), { recursive: true });
1884
+ writeFileSync(file, contents);
1885
+ }
1886
+ console.log(`\n${formatSummary$2(report)}\n\nReport: ${join(out, "report.md")}`);
1887
+ if (!report.passed) {
1888
+ if (args.flag("warn")) console.log("(--warn: reporting only, exit 0)");
1889
+ else process.exitCode = 1;
1890
+ }
1891
+ } catch (err) {
1892
+ server?.stop();
1893
+ fail(`audit: ${msg(err)}`);
1894
+ } finally {
1895
+ server?.stop();
1896
+ }
1897
+ }
1898
+
1669
1899
  // src/commands/crm.ts
1670
1900
  /**
1671
1901
  * `vitops crm` — the two things `site.crm` needs a human-in-the-loop for.
@@ -2084,7 +2314,7 @@ async function cmdEmailSetup(argv) {
2084
2314
  reminders
2085
2315
  });
2086
2316
  }
2087
- console.log(`\n${formatSummary$2(results)}`);
2317
+ console.log(`\n${formatSummary$3(results)}`);
2088
2318
  for (const n of dynamicNotes) console.log(n);
2089
2319
  for (const f of failures) console.error(`! ${f}`);
2090
2320
  if (failed) process.exit(1);
@@ -2164,6 +2394,202 @@ async function cmdEmail(argv) {
2164
2394
  }
2165
2395
  }
2166
2396
 
2397
+ // src/prerender-check.ts
2398
+ /**
2399
+ * The pure half of `vitops emdash check-prerender`: is a prerendered `.html` body a real page?
2400
+ *
2401
+ * `astro build` succeeds even when a prerendered route's response was an error. Against a local
2402
+ * database with pending migrations EmDash answers with a one-line "Database migrations are
2403
+ * required" body, which is written to `index.html` like any other page, and the deploy then
2404
+ * publishes it.
2405
+ */
2406
+ const PENDING_MIGRATIONS = /Database migrations are required/i;
2407
+ /** Why `html` is not a real page, or `undefined` when it looks like one. */
2408
+ function prerenderProblem(html) {
2409
+ if (PENDING_MIGRATIONS.test(html)) return "carries the pending-migrations message";
2410
+ if (!/<html[\s>]/i.test(html)) return "is not an HTML document";
2411
+ if (!/<title>[^<]+<\/title>/i.test(html)) return "has no <title>";
2412
+ }
2413
+ const TYPE_ROLE_CLASS = new RegExp(`^font-(?:${[
2414
+ "display",
2415
+ "title",
2416
+ "heading",
2417
+ "body",
2418
+ "quote",
2419
+ "caption",
2420
+ "eyebrow",
2421
+ "code",
2422
+ "lead",
2423
+ "footnote",
2424
+ "tag"
2425
+ ].join("|")})$`);
2426
+ /** Every `class="…"` token in a page. */
2427
+ function classesIn(html) {
2428
+ const out = /* @__PURE__ */ new Set();
2429
+ for (const m of html.matchAll(/\sclass\s*=\s*(?:"([^"]*)"|'([^']*)')/gi)) for (const token of (m[1] ?? m[2] ?? "").split(/\s+/)) if (token) out.add(token);
2430
+ return out;
2431
+ }
2432
+ /**
2433
+ * Type-role classes a page uses that the built stylesheet has no rule for.
2434
+ *
2435
+ * Tailwind v4 does not scan `node_modules`, so a utility used only by a package's own renderer
2436
+ * (`font-display` in `vitops.stats`) was never generated, and the page rendered at body size with
2437
+ * no error. The type roles are the one family checkable without the site's config: the list is
2438
+ * closed. A class is "defined" when the CSS names it as a selector.
2439
+ */
2440
+ function missingTypeRoleRules(html, css) {
2441
+ const defined = (cls) => new RegExp(`\\.${cls}(?![\\w-])`).test(css);
2442
+ return [...classesIn(html)].filter((c) => TYPE_ROLE_CLASS.test(c) && !defined(c)).sort();
2443
+ }
2444
+
2445
+ // src/commands/emdash.ts
2446
+ /**
2447
+ * `vitops emdash` — build-time steps for an EmDash site on the Cloudflare adapter.
2448
+ *
2449
+ * These used to be copied into every scaffold as `scripts/*.mjs`, which froze each fix at
2450
+ * scaffold time. As commands they arrive with `@getvitops/cli`, so a site's `package.json`
2451
+ * keeps one-line entries and `vp update` delivers the logic (the same move `vitops setup`
2452
+ * made for the template's old `init-github`/`init-hosting` scripts).
2453
+ *
2454
+ * prepare-db migrate and seed the LOCAL D1 the build prerenders from
2455
+ * check-prerender fail if a prerendered page is not a real page
2456
+ *
2457
+ * Why both exist: `astro build` prerenders every page inside a local workerd against a local D1
2458
+ * (`.wrangler/state`), never the deployed database. The template sets
2459
+ * `migrations.runtime: 'check'`, so a build against a local database with pending migrations
2460
+ * prerenders EmDash's one-line "Database migrations are required" response into every page,
2461
+ * and the build still succeeds. A fresh CI runner, a first deploy, a `SKIP_PULL_CONTENT=1`
2462
+ * build and an upgrade deploy all hand the build exactly that database.
2463
+ */
2464
+ function freePort() {
2465
+ return new Promise((resolve, reject) => {
2466
+ const server = createServer();
2467
+ server.once("error", reject);
2468
+ server.listen(0, "127.0.0.1", () => {
2469
+ const { port } = server.address() ?? { port: 0 };
2470
+ server.close(() => resolve(port));
2471
+ });
2472
+ });
2473
+ }
2474
+ async function until(test, what, ms = 12e4) {
2475
+ const deadline = Date.now() + ms;
2476
+ while (Date.now() < deadline) {
2477
+ try {
2478
+ if (await test()) return;
2479
+ } catch {}
2480
+ await new Promise((r) => setTimeout(r, 1e3));
2481
+ }
2482
+ throw new Error(`timed out waiting for ${what}`);
2483
+ }
2484
+ const log = (msg) => console.log(`prepare-db: ${msg}`);
2485
+ /**
2486
+ * `astro dev` daemonizes: the child outlives the command that started it, so capturing its
2487
+ * output through pipes would leave this process waiting on the daemon's inherited handles,
2488
+ * which looks exactly like a hang. Output is ignored and every call has a timeout.
2489
+ */
2490
+ const astro = (args) => spawnSync(existsSync("node_modules/.bin/astro") ? "node_modules/.bin/astro" : "astro", args, {
2491
+ stdio: "ignore",
2492
+ timeout: 3e5,
2493
+ env: {
2494
+ ...process.env,
2495
+ CI: "1"
2496
+ }
2497
+ });
2498
+ /**
2499
+ * Starts `astro dev` once, calls EmDash's `dev-bypass` setup endpoint (the non-interactive
2500
+ * setup wizard: it runs migrations, `dev: 'auto'`, and applies the seed), checks the home page
2501
+ * renders, stops. Only ever writes the local `.wrangler/state`, which is disposable; the dev
2502
+ * administrator it creates lives in that copy and is never deployed. Content already there
2503
+ * (from `pull-content`) is kept: the seed applies with `onConflict: skip`.
2504
+ */
2505
+ async function cmdPrepareDb() {
2506
+ if (process.env.SKIP_PREPARE_LOCAL_DB) {
2507
+ log("SKIP_PREPARE_LOCAL_DB set — leaving the local database as it is.");
2508
+ return;
2509
+ }
2510
+ const port = await freePort();
2511
+ const base = `http://127.0.0.1:${port}`;
2512
+ log(`starting astro dev on ${base} ...`);
2513
+ const started = astro([
2514
+ "dev",
2515
+ "--port",
2516
+ String(port),
2517
+ "--host",
2518
+ "127.0.0.1"
2519
+ ]);
2520
+ if (started.error?.code === "ENOENT") fail("`astro` is not on PATH. Run it through the package scripts (`vpr prepare-local-db`).");
2521
+ if (started.status !== 0) fail(`could not start astro dev (${started.signal ?? `exit ${started.status}`}). It is killed after 5 minutes (exit 143 = SIGTERM). Run \`astro dev\` by hand to see why.`);
2522
+ let failure = null;
2523
+ try {
2524
+ await until(async () => (await fetch(`${base}/_emdash/api/setup/status`)).ok, "astro dev");
2525
+ log("dev server is up; migrating and seeding (first run can take a minute) ...");
2526
+ const setup = await fetch(`${base}/_emdash/api/setup/dev-bypass?redirect=/`, {
2527
+ redirect: "manual",
2528
+ signal: AbortSignal.timeout(12e4)
2529
+ });
2530
+ if (setup.status >= 400) console.warn(`prepare-db: dev-bypass answered ${setup.status}; checking the home page anyway.`);
2531
+ const home = await fetch(`${base}/`);
2532
+ const html = await home.text();
2533
+ if (!home.ok) throw new Error(`astro dev answered ${home.status} on / — the dev runtime is broken`);
2534
+ if (PENDING_MIGRATIONS.test(html)) throw new Error("the local database still has pending migrations");
2535
+ log("the local database is migrated and the home page renders.");
2536
+ } catch (e) {
2537
+ failure = e;
2538
+ } finally {
2539
+ astro(["dev", "stop"]);
2540
+ }
2541
+ if (failure) fail(`${failure.message}\nRefusing to continue: prerendering now would publish error pages as the site.`);
2542
+ }
2543
+ function* filesWith(dir, ext) {
2544
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
2545
+ const path = join(dir, entry.name);
2546
+ if (entry.isDirectory()) yield* filesWith(path, ext);
2547
+ else if (entry.name.endsWith(ext)) yield path;
2548
+ }
2549
+ }
2550
+ const htmlFiles = (dir) => filesWith(dir, ".html");
2551
+ const cssFiles = (dir) => [...filesWith(dir, ".css")];
2552
+ function cmdCheckPrerender(argv) {
2553
+ const root = argv.find((a) => !a.startsWith("-")) ?? "dist/client";
2554
+ const strict = argv.includes("--strict");
2555
+ if (!existsSync(root)) fail(`${root} does not exist (run \`astro build\` first).`);
2556
+ const bad = [];
2557
+ const unstyled = [];
2558
+ const css = cssFiles(root).map((f) => readFileSync(f, "utf8")).join("\n");
2559
+ let count = 0;
2560
+ for (const file of htmlFiles(root)) {
2561
+ count += 1;
2562
+ const html = readFileSync(file, "utf8");
2563
+ const why = prerenderProblem(html);
2564
+ if (why) bad.push(` ${file} ${why}`);
2565
+ else if (css) {
2566
+ const missing = missingTypeRoleRules(html, css);
2567
+ if (missing.length) unstyled.push(` ${file}: ${missing.join(", ")}`);
2568
+ }
2569
+ }
2570
+ if (count === 0) fail(`no .html files under ${root}.`);
2571
+ if (bad.length) fail(`the build prerendered pages that are not real pages:\n${bad.join("\n")}\n\nThe local database the build reads is probably unmigrated. Run \`vpr prepare-local-db\` (it migrates and seeds the local D1 through \`astro dev\`), then build again.`);
2572
+ if (unstyled.length) {
2573
+ const note = `type-role classes with no rule in the built CSS (they render at body size):\n${unstyled.join("\n")}\n\nTailwind does not scan node_modules. Use @getvitops/astro >= the release that adds the \`@source\` lines, or add \`@source\` for the package that renders them to the site's stylesheet.`;
2574
+ if (strict) fail(note);
2575
+ console.warn(`check-prerender: warning: ${note}`);
2576
+ }
2577
+ console.log(`check-prerender: ${count} prerendered page(s) look like real pages.`);
2578
+ }
2579
+ async function cmdEmdash(argv) {
2580
+ const [sub, ...rest] = argv;
2581
+ switch (sub) {
2582
+ case "prepare-db": return cmdPrepareDb();
2583
+ case "check-prerender": return cmdCheckPrerender(rest);
2584
+ case void 0:
2585
+ case "-h":
2586
+ case "--help":
2587
+ console.log(EMDASH_HELP);
2588
+ return;
2589
+ default: fail(`unknown "emdash" subcommand "${sub}" (expected: prepare-db | check-prerender). Try: vitops --help`);
2590
+ }
2591
+ }
2592
+
2167
2593
  // src/commands/setup.ts
2168
2594
  /**
2169
2595
  * `vitops setup` — the scripted path from an empty scaffold to a live site.
@@ -2188,6 +2614,7 @@ const SETUP_HELP = `vitops setup <sub> [options]
2188
2614
  vitops setup repo [--dry] [--check] [--public]
2189
2615
  vitops setup hosting [--dry] [--check] [--platform cloudflare|node]
2190
2616
  vitops setup domain [--dry] [--check] [--domain <apex>]
2617
+ vitops setup turnstile [--dry] [--check] [--no-write] [--no-secret]
2191
2618
  vitops setup search [options] (forwards to \`vitops search setup\`)
2192
2619
  vitops setup ads [options] (forwards to \`vitops ads setup\`)
2193
2620
  vitops setup all [--dry] [--check] [--public] [--platform <p>]
@@ -2355,7 +2782,7 @@ async function cmdSetupRepo(argv) {
2355
2782
  status: "blocked",
2356
2783
  detail: "no GitHub repo yet — run this again once \"repo\" succeeds"
2357
2784
  });
2358
- console.log(formatSummary$3(results));
2785
+ console.log(formatSummary$4(results));
2359
2786
  if (results.some((r) => r.status === "failed")) process.exit(1);
2360
2787
  }
2361
2788
  async function cmdSetupHosting(argv) {
@@ -2465,7 +2892,7 @@ async function cmdSetupHosting(argv) {
2465
2892
  status: "blocked",
2466
2893
  detail: p.secrets["CLOUDFLARE_API_TOKEN"]?.detail ?? "create it by hand"
2467
2894
  });
2468
- console.log(formatSummary$3(results));
2895
+ console.log(formatSummary$4(results));
2469
2896
  for (const n of p.notes) console.log(`! ${n}`);
2470
2897
  if (results.some((r) => r.status === "failed")) process.exit(1);
2471
2898
  }
@@ -2501,6 +2928,157 @@ async function cmdSetupDomain(argv) {
2501
2928
  if (a.opt("domain")) console.log(`\nCutover is never applied by this command — see SETUP.html stage 4b. To cut over: uncomment routes in wrangler.jsonc with "pattern": "${a.opt("domain")}", deploy, then update site.domains.canonical and site.environments.${a.str("site-env")}.url to match.`);
2502
2929
  if (a.flag("check") && step.action !== "skip") process.exit(1);
2503
2930
  }
2931
+ /**
2932
+ * Create the Cloudflare Turnstile widget for the site and record its PUBLIC site key.
2933
+ *
2934
+ * The secret is returned by Cloudflare only at creation. It is never written to a config
2935
+ * file: it is piped to `wrangler secret put VITOPS_TURNSTILE_SECRET` on stdin (never argv,
2936
+ * never logged). If that fails, it is shown once on an interactive terminal and otherwise
2937
+ * not at all, with the rotate instruction. Never edits, rotates or deletes a widget.
2938
+ */
2939
+ async function cmdSetupTurnstile(argv) {
2940
+ const a = parse$1(argv, {
2941
+ ...SITE_OPTS,
2942
+ dry: {
2943
+ type: "boolean",
2944
+ default: false
2945
+ },
2946
+ check: {
2947
+ type: "boolean",
2948
+ default: false
2949
+ },
2950
+ "no-write": {
2951
+ type: "boolean",
2952
+ default: false
2953
+ },
2954
+ "no-secret": {
2955
+ type: "boolean",
2956
+ default: false
2957
+ }
2958
+ });
2959
+ const input = a.path("input");
2960
+ const cfg = await loadConfig(input, a.str("site-env"));
2961
+ const dry = a.flag("dry");
2962
+ const check = a.flag("check");
2963
+ const token = loadCloudflareToken();
2964
+ if (!token && !dry) fail(`${CLOUDFLARE_TOKEN_HINT}\n For this command the token needs "Account > Turnstile > Edit" (also set CLOUDFLARE_ACCOUNT_ID, or the token must be able to list accounts).`);
2965
+ const setup = {
2966
+ name: (() => {
2967
+ const n = cfg.organization?.name;
2968
+ return (typeof n === "string" ? n : n ? Object.values(n)[0] : void 0) ?? projectName();
2969
+ })(),
2970
+ domains: deriveDomains(cfg.site),
2971
+ siteKey: cfg.site.security?.turnstile?.siteKey
2972
+ };
2973
+ let accountId;
2974
+ let widgets = [];
2975
+ if (token) {
2976
+ const acct = await resolveAccountId(token, process.env.CLOUDFLARE_ACCOUNT_ID || void 0);
2977
+ if (!acct.ok) {
2978
+ if (!dry) fail(`Cloudflare account: ${acct.message}`);
2979
+ } else {
2980
+ accountId = acct.accountId;
2981
+ const listed = await listWidgets(token, accountId);
2982
+ if (!listed.ok) fail(`listing Turnstile widgets: ${listed.message}`);
2983
+ widgets = listed.widgets;
2984
+ }
2985
+ }
2986
+ const p = plan$5(setup, {
2987
+ accountId,
2988
+ widgets
2989
+ });
2990
+ if (dry || check) {
2991
+ console.log(formatPlan$7(p));
2992
+ if (check && hasDrift$3(p)) {
2993
+ console.error("\n✖ Turnstile is not set up");
2994
+ process.exit(1);
2995
+ }
2996
+ return;
2997
+ }
2998
+ const results = [];
2999
+ let siteKey = p.adopt?.sitekey;
3000
+ if (p.widget.action === "blocked") results.push({
3001
+ step: "widget",
3002
+ status: "blocked",
3003
+ detail: p.widget.detail
3004
+ });
3005
+ else if (p.widget.action === "create") {
3006
+ const r = await createWidget(token, accountId, {
3007
+ name: setup.name,
3008
+ domains: p.domains
3009
+ });
3010
+ if (!r.ok) results.push({
3011
+ step: "widget",
3012
+ status: "failed",
3013
+ detail: r.message ?? "failed"
3014
+ });
3015
+ else {
3016
+ siteKey = r.sitekey;
3017
+ results.push({
3018
+ step: "widget",
3019
+ status: "created",
3020
+ detail: r.sitekey
3021
+ });
3022
+ if (a.flag("no-secret")) console.error("! --no-secret: the secret was NOT saved and cannot be read back. Rotate it in the dashboard, then `wrangler secret put VITOPS_TURNSTILE_SECRET`.");
3023
+ else try {
3024
+ execFileSync("npx", [
3025
+ "wrangler",
3026
+ "secret",
3027
+ "put",
3028
+ "VITOPS_TURNSTILE_SECRET"
3029
+ ], {
3030
+ input: r.secret,
3031
+ stdio: [
3032
+ "pipe",
3033
+ "inherit",
3034
+ "inherit"
3035
+ ]
3036
+ });
3037
+ results.push({
3038
+ step: "secret",
3039
+ status: "created",
3040
+ detail: "VITOPS_TURNSTILE_SECRET (Worker secret)"
3041
+ });
3042
+ } catch {
3043
+ results.push({
3044
+ step: "secret",
3045
+ status: "failed",
3046
+ detail: "wrangler secret put failed"
3047
+ });
3048
+ if (process.stdout.isTTY) console.error(`! Save this now, it is shown once: VITOPS_TURNSTILE_SECRET=${r.secret}\n Then: npx wrangler secret put VITOPS_TURNSTILE_SECRET`);
3049
+ else console.error("! The secret was not saved and is not printed (non-interactive). Rotate it in the dashboard, then `wrangler secret put VITOPS_TURNSTILE_SECRET`.");
3050
+ }
3051
+ }
3052
+ } else results.push({
3053
+ step: "widget",
3054
+ status: "present",
3055
+ detail: p.widget.detail
3056
+ });
3057
+ if (siteKey && p.config.action === "create" && !a.flag("no-write")) {
3058
+ if (!input.endsWith(".json")) results.push({
3059
+ step: "site.json",
3060
+ status: "blocked",
3061
+ detail: `${input} is a module — add site.security.turnstile.siteKey: "${siteKey}" yourself`
3062
+ });
3063
+ else {
3064
+ const source = readFileSync(input, "utf8");
3065
+ const indent = /\n([ \t]+)"/.exec(source)?.[1];
3066
+ writeFileSync(input, JSON.stringify(patchSiteKey(JSON.parse(source), siteKey), null, indent?.includes(" ") ? " " : indent?.length ?? 2) + (source.endsWith("\n") ? "\n" : ""));
3067
+ results.push({
3068
+ step: "site.json",
3069
+ status: "created",
3070
+ detail: "site.security.turnstile.siteKey"
3071
+ });
3072
+ }
3073
+ } else if (p.config.action === "skip") results.push({
3074
+ step: "site.json",
3075
+ status: "present",
3076
+ detail: p.config.detail
3077
+ });
3078
+ console.log(`\n${formatSummary$5(results)}`);
3079
+ for (const r of p.reminders) console.log(` ${r}`);
3080
+ if (results.some((r) => r.status === "failed" || r.status === "blocked")) process.exit(1);
3081
+ }
2504
3082
  /** Forward to the CLI's own `search setup` / `ads setup` as a child process — see
2505
3083
  * this module's docblock for why (their behaviour must not be re-derived). */
2506
3084
  function forward(sub, argv) {
@@ -2523,6 +3101,7 @@ async function cmdSetup(argv) {
2523
3101
  case "repo": return cmdSetupRepo(rest);
2524
3102
  case "hosting": return cmdSetupHosting(rest);
2525
3103
  case "domain": return cmdSetupDomain(rest);
3104
+ case "turnstile": return cmdSetupTurnstile(rest);
2526
3105
  case "search":
2527
3106
  if (!forward("search", rest)) process.exit(1);
2528
3107
  return;
@@ -2575,7 +3154,7 @@ async function cmdSetup(argv) {
2575
3154
  case "--help":
2576
3155
  console.log(SETUP_HELP);
2577
3156
  return;
2578
- default: fail(`unknown "setup" subcommand "${sub}" (expected: repo | hosting | domain | search | ads | all). Try: vitops --help`);
3157
+ default: fail(`unknown "setup" subcommand "${sub}" (expected: repo | hosting | domain | turnstile | search | ads | all). Try: vitops --help`);
2579
3158
  }
2580
3159
  }
2581
3160
 
@@ -3329,6 +3908,18 @@ const UTIL_FAMILIES = [
3329
3908
  "fill",
3330
3909
  "stroke"
3331
3910
  ];
3911
+ /** Class families the framework owns in every format, for variant-spelling checks. */
3912
+ const FRAMEWORK_FAMILY = new RegExp(`^(${[
3913
+ ...UTIL_FAMILIES,
3914
+ "font",
3915
+ "drop-shadow",
3916
+ "split",
3917
+ "flex",
3918
+ "items",
3919
+ "justify",
3920
+ "gap",
3921
+ "space"
3922
+ ].join("|")})(-|$)`);
3332
3923
  /**
3333
3924
  * The modifiers actually emitted for one family + role, read back out of the
3334
3925
  * generator's own class list.
@@ -3384,6 +3975,13 @@ function judge(raw, v, format) {
3384
3975
  reason: `\`@${cq[1]}:\` container-query variants are a tailwind-format spelling; the ${format} format emits pre-expanded classes`,
3385
3976
  suggestion: `${cq[1]}-${cq[2]}`
3386
3977
  };
3978
+ const sv = /^(hover|focus|focus-visible|focus-within|active|disabled|dark|group-hover):(.+)$/.exec(raw);
3979
+ if (sv && format !== "tailwind" && FRAMEWORK_FAMILY.test(sv[2])) return {
3980
+ cls: raw,
3981
+ severity: "error",
3982
+ reason: `\`${sv[1]}:\` state variants are a tailwind-format spelling; the ${format} format emits no such class`,
3983
+ suggestion: `${sv[1]}-${sv[2]} where an effect class exists, otherwise a pattern state`
3984
+ };
3387
3985
  const bp = /^(sm|md|lg|xl)-(.+)$/.exec(cls);
3388
3986
  if (bp && format === "tailwind") return {
3389
3987
  cls: raw,
@@ -3496,7 +4094,9 @@ function lintSource(files, v, format) {
3496
4094
  * vitops ads setup [--provider <name>] [--dry] [--check] | tags | lint
3497
4095
  * vitops setup repo | hosting | domain | search | ads | all [--dry] [--check]
3498
4096
  * vitops email setup [domain] [--dry] [--check] | check [--strict] [--skip]
4097
+ * vitops emdash prepare-db | check-prerender [dir]
3499
4098
  * vitops media [--raw <dir>] [--out <dir>] [--force] [--dry]
4099
+ * vitops audit [--url <base>] [--build] [--pages <list>] [--warn] [--out <dir>]
3500
4100
  *
3501
4101
  * Thin wrapper over @getvitops/generator (generation) and @getvitops/utils (favicons).
3502
4102
  * Every client brings their own consumer-editable design-system.json.
@@ -4145,6 +4745,20 @@ function generatorAssetsDir() {
4145
4745
  }
4146
4746
  const AGENTS_START = "<!-- vitops:start -->";
4147
4747
  const AGENTS_END = "<!-- vitops:end -->";
4748
+ /**
4749
+ * Input path for the read-only commands (`docs`, `lint`) when `-i` is absent.
4750
+ *
4751
+ * `site.json` is the file `vitops init --site` and every scaffold write, so it
4752
+ * is the default; a bare `design-system.json` is the fallback for projects that
4753
+ * keep tokens on their own. An explicit `-i` is never second-guessed. If
4754
+ * neither exists the legacy name is returned so the "config not found" message
4755
+ * names a path a reader recognises.
4756
+ */
4757
+ function defaultDesignInput(argv, value) {
4758
+ if (argv.some((a) => a === "-i" || a === "--input" || a.startsWith("--input="))) return value;
4759
+ for (const name of ["site.json", "design-system.json"]) if (existsSync(resolve(name))) return name;
4760
+ return value;
4761
+ }
4148
4762
  /** Print a live reference doc (rendered from the project's config) to stdout. */
4149
4763
  async function cmdDocs(argv) {
4150
4764
  const { values, positionals } = parseArgs({
@@ -4171,7 +4785,7 @@ async function cmdDocs(argv) {
4171
4785
  }
4172
4786
  if (topic && !TOPICS[topic]) fail(`unknown topic "${topic}". Valid topics:\n${topicList()}`);
4173
4787
  const names = values.all ? Object.keys(TOPICS) : [topic];
4174
- const docs = names.every((n) => TOPICS[n].external) ? {} : generateDocs(loadDesignSystem(resolve(values.input), values.theme), generatorAssetsDir());
4788
+ const docs = names.every((n) => TOPICS[n].external) ? {} : generateDocs(loadDesignSystem(resolve(defaultDesignInput(argv, values.input)), values.theme), generatorAssetsDir());
4175
4789
  const parts = [];
4176
4790
  for (const name of names) {
4177
4791
  const t = TOPICS[name];
@@ -4229,7 +4843,7 @@ function cmdLint(argv) {
4229
4843
  });
4230
4844
  const format = values.format;
4231
4845
  if (!LINT_FORMATS.has(format)) fail(`unknown format "${format}" (expected: bricks | css | tailwind)`);
4232
- const ds = loadDesignSystem(resolve(values.input), values.theme);
4846
+ const ds = loadDesignSystem(resolve(defaultDesignInput(argv, values.input)), values.theme);
4233
4847
  const srcDir = resolve(values.src);
4234
4848
  if (!positionals.length && !existsSync(srcDir)) fail(`source directory not found: ${srcDir}`);
4235
4849
  const palette = expandPalette(ds.colors.palette);
@@ -4474,8 +5088,10 @@ async function main() {
4474
5088
  case "ads": return cmdAds(rest);
4475
5089
  case "crm": return cmdCrm(rest);
4476
5090
  case "email": return cmdEmail(rest);
5091
+ case "emdash": return cmdEmdash(rest);
4477
5092
  case "setup": return cmdSetup(rest);
4478
5093
  case "media": return cmdMedia(rest);
5094
+ case "audit": return cmdAudit(rest);
4479
5095
  default: fail(`unknown command "${command}" (expected: ${COMMANDS.join(" | ")}). Try: vitops --help`);
4480
5096
  }
4481
5097
  }