cascivo 1.8.2 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["resolvePath","ASTRO_CONFIG_FILES","DEFAULT_CONFIG","item","__exportAll","detectPackageManager","loadConfig","DEFAULT_CONFIG$1","installCommand","THEMES","installHint","CASCIVO_HOST","writeFileSafe","readFileSafe","resolveOutputPath","assertInside","fetchTextRetry","fetchJson","writeLock","findComponent","updateLockEntry","resolvedAlias","readLock","fetchRegistry","sha256","fileName","createLock","readInstalledPackageVersion","compareVersions","checkPeerVersions","positionalArgs","resolvePackageManagerFlag","flagValue","merge","installPackages","packages","pm","opts","cwd","cmd","args","spawnSync","GITHUB_RE","expandEnv","str","val","env","key","parseAddress","spec","slash","specWithoutRef","githubMatch","owner","repo","item","ref","resolveNamespaceUrl","template","nsCfg","ns","name","resolveItemUrl","addr","config","parts","url","headers","params","expandedHeaders","k","v","expandedParams","result","resolveNamespaceHook","hookResult","resolveClosure","seen","queue","specs","plan","identity","fetchOpts","parseItem","entry","dep","DIRECTORY_URL","pickRegistryUrl","raw","registries","e","\"namespace\"","\"registryUrl\"","resolveFromDirectory","data","fetchFn","res","msg","add_exports","LAYOUT_ALIASES","NAME_NOTES","add","isThirdParty","resolveBareClosure","resolveTemplateTarget","ASSUMED_DEPS","readProjectDeps","pkg","readFileSync","join","hintThemesIfMissing","deps","resolve","target","bareSpecs","installed","resolved","missing","resolvedName","registry","alias","FIRST_PARTY_URL","itemUrl","isMultiRegistrySpec","names","multiSpecs","n","templateNames","t","templateSpecs","lock","kind","isTemplateItem","f","arrow","registryBase","fileHashes","installItem","missingDeps","note","requested","viaAlias","announced","since","replacement","peerFloors","floor","npmPackages","importLines","outputName","fetched","dest","content","suffix","needed","p","violations","file","pages","doctor_exports","checkDuplicateCore","checkFormatterIgnore","checkProjectDependencies","checkSignalsCompat","checkSsrConfig","detectInstallPath","runDoctor","stripCommentsAndStrings","REQUIRED_RUNTIME_DEPS","REQUIRED_PREBUILT_DEPS","FORBIDDEN_PREBUILT_DEPS","ON_DEMAND_DEPS","CONFIG_FILES","hasPackageJson","usesPackage","copied","hasCopiedSource","dir","outputDirCandidates","full","existsSync","readdirSync","dirs","declared","path","findings","required","reason","CORE_DEPENDENTS","root","nested","ownerRoot","version","signals","react","signalsBelow3","hint","reactMajor","m","VITE_SSR_MARKERS","VITE_CONFIG_FILES","pairs","outputDir","configs","ignore","l","ASTRO_CONFIG_FILES$1","setsResolveNoExternal","match","depth","i","start","c","installedReactIsAstroSafe","keywords","checkAstroConfig","installPath","configFile","ssrOnly","astroConfig","framework","BANNED_HOOKS","out","source","next","componentsDir","components","d","reactIndex","indexContent","tsxPath","code","hook","OWNER_DIRECTORY","componentDirectory","component","COMPONENT_RE","PROP_RE","IDENT_RE","REF_RE","KEY_RE","fail","message","isRecord","parseRefs","parseTranslationRef","parseNode","node","props","bind","events","children","parseViewConfig","state","parsed","view","nodes","isTranslationRef","serializeInitial","value","serializeProp","renderChildren","renderNode","child","indent","componentPropNames","knownComponents","compName","propParts","propsStr","childrenStr","collectBindAndEvents","boundProps","actionProps","walk","usesStateSetter","r","byDirectory","directory","a","b","members","generateTsx","allNodes","stateEntries","hasState","needsCoerce","regionBlocks","regionName","hasData","hasActions","propsType","coreImport","coerceHelper","stateDecls","generate","outArg","inputArg","componentsDirArg","fromArg","viewConfig","propMetas","tsx","outPath","dirname","basename","writeFileSync","RUNTIME_DEPS","DEV_DEPS","promptTheme","rl","createInterface","stdin","stdout","answer","configFileContents","theme","ESLINT_CONFIGS","hintEslintIfPresent","recordDependencies","pkgPath","field","added","FORMATTER_IGNORES","ensureFormatterIgnore","line","hasPrettierKeyInPackageJson","current","banner","ASTRO_CONFIG_FILES","printAstroNextSteps","printDependencySummary","init","yes","noInstall","themeArg","pmFlag","interactive","configPath","runtimeOk","devOk","recorded","TYPE_LABELS","deprecationSuffix","formatGroup","rows","entries","widths","h","cells","cell","sep","w","formatList","groups","sections","label","list","options","validateTemplates","errors","warnings","localNames","index","validateTemplate","registryBuild","inFile","outDir","inPath","readFile","\"schemaVersion\"","parseLegacyRegistry","validateIndex","templateResult","buildRegistry","matchesQuery","q","query","search","nsFlag","registryFilter","results","indexUrl","validateItem","reg","DEFAULT_CONFIG","hashToConfig","hash","base64","json","FONT_STACKS","configToCSS","light","acc","chroma","lines","themeName","previewMode","\"humanist\"","THEME_NAME_RE","flag","eq","idx","themeCreate","dryRun","css","sub","diffLines","oldStr","newStr","lcs","j","hasChanges","confirm","question","update","updateCheck","lockEntry","lockedVersion","baseItemUrl","baseItem","threeWayUpdate","twoWayUpdate","upstreamEntry","summaries","pending","fname","baseFile","upstream","local","base","conflicts","text","s","icon","conflicted","updatedLock","hasConflicts","latest","outdated","lockByBase","changed","formatItem","meta","asTemplateMeta","VERSION","createRequire","HELP","THEME_LIST","COMMAND_HELP","run","command","rest","commandHelp","create","app","tokensArg","eject","templateInit","ci","runDoctorDrift","adopter","missingRequired","signalsCompat","signalsError","ssrHint","duplicateCore","formatterHint","driftOutcome","x","mcp","audit","email","tokensImport","argv","pathToFileURL","error"],"sources":["../src/utils/exec.ts","../src/utils/resolve.ts","../src/utils/directory.ts","../src/commands/add.ts","../src/commands/doctor.ts","../src/commands/generate.ts","../src/commands/init.ts","../src/commands/list.ts","../src/commands/registry.ts","../src/commands/search.ts","../../theme-kit/src/config.ts","../../theme-kit/src/hash.ts","../../theme-kit/src/css.ts","../src/commands/theme.ts","../src/utils/diff.ts","../src/commands/update.ts","../src/commands/view.ts","../src/index.ts"],"sourcesContent":["import { spawnSync } from 'node:child_process'\nimport { detectPackageManager, installCommand, installHint, type PackageManager } from './config.js'\n\n/**\n * Install npm packages using the detected (or explicitly chosen) package\n * manager, inheriting stdio so the user sees install progress. On failure it\n * prints the exact command to run by hand — the adopter can always recover even\n * when the spawn fails (e.g. npm crashing inside a pnpm workspace). Returns\n * false if the install failed.\n */\nexport function installPackages(\n packages: string[],\n cwd: string = process.cwd(),\n opts: {\n pm?: PackageManager\n dev?: boolean\n /** Registry peer floors, so a known minimum is honoured rather than silently ignored. */\n floors?: Record<string, string>\n /** `--pin <version>` escape hatch: install every `@cascivo/*` at exactly this version. */\n pin?: string\n } = {},\n): boolean {\n if (packages.length === 0) return true\n const pm = opts.pm ?? detectPackageManager(cwd)\n const [cmd, args] = installCommand(pm, packages, {\n dev: opts.dev ?? false,\n ...(opts.floors ? { floors: opts.floors } : {}),\n ...(opts.pin ? { pin: opts.pin } : {}),\n })\n console.log(`Installing ${packages.join(', ')} with ${cmd}…`)\n const result = spawnSync(cmd, args, {\n cwd,\n stdio: 'inherit',\n shell: process.platform === 'win32',\n })\n if (result.status !== 0) {\n console.error(`Failed to install: ${packages.join(', ')}`)\n console.error(\n `Install them yourself with: ${installHint(pm, packages, { dev: opts.dev ?? false })}`,\n )\n return false\n }\n return true\n}\n","import { CASCIVO_HOST, type CascadeConfig, type RegistryNamespaceConfig } from './config.js'\nimport { fetchJson } from './http.js'\nimport { parseItem } from '@cascivo/registry'\nimport type { RegistryItem } from '@cascivo/registry'\n\nexport type AddressKind = 'bare' | 'namespace' | 'url' | 'github'\n\nexport interface ParsedAddress {\n kind: AddressKind\n namespace?: string\n name: string\n ref?: string\n raw: string\n}\n\nconst GITHUB_RE = /^([^/]+)\\/([^/]+)\\/([^#]+)(?:#(.+))?$/\n\nfunction expandEnv(str: string, env: NodeJS.ProcessEnv = process.env): string {\n return str.replace(/\\$\\{([^}]+)\\}/g, (_, key: string) => {\n const val = env[key]\n if (val === undefined) throw new Error(`Environment variable ${key} is not set`)\n return val\n })\n}\n\nexport function parseAddress(spec: string, _env: NodeJS.ProcessEnv = process.env): ParsedAddress {\n if (\n spec.startsWith('http://') ||\n spec.startsWith('https://') ||\n spec.startsWith('./') ||\n spec.startsWith('/')\n ) {\n return { kind: 'url', name: spec, raw: spec }\n }\n\n if (spec.startsWith('@')) {\n const slash = spec.indexOf('/', 1)\n if (slash === -1) throw new Error(`Invalid namespace address: ${spec} (expected @ns/name)`)\n const namespace = spec.slice(0, slash)\n const name = spec.slice(slash + 1)\n return { kind: 'namespace', namespace, name, raw: spec }\n }\n\n // GitHub: owner/repo/item[#ref] — at least 3 path segments, no leading protocol/dot\n const specWithoutRef = spec.includes('#') ? spec.slice(0, spec.indexOf('#')) : spec\n const githubMatch = GITHUB_RE.exec(spec)\n if (githubMatch && !specWithoutRef.includes('.') && specWithoutRef.split('/').length >= 3) {\n const [, owner, repo, item, ref] = githubMatch\n return {\n kind: 'github',\n name: `${owner}/${repo}/${item}`,\n ref: ref ?? 'main',\n raw: spec,\n }\n }\n\n return { kind: 'bare', name: spec, raw: spec }\n}\n\nfunction resolveNamespaceUrl(\n ns: string,\n name: string,\n nsCfg: RegistryNamespaceConfig,\n env: NodeJS.ProcessEnv,\n): string {\n const template = typeof nsCfg === 'string' ? nsCfg : nsCfg.url\n if (!template.includes('{name}')) {\n throw new Error(`Registry namespace \"${ns}\" URL template must contain {name}: ${template}`)\n }\n return expandEnv(template.replace('{name}', name), env)\n}\n\nexport async function resolveItemUrl(\n addr: ParsedAddress,\n config: CascadeConfig,\n env: NodeJS.ProcessEnv = process.env,\n resolveNamespaceHook?: (ns: string) => Promise<RegistryNamespaceConfig | null>,\n): Promise<{ url: string; headers?: Record<string, string>; params?: Record<string, string> }> {\n switch (addr.kind) {\n case 'url':\n return { url: addr.name }\n\n case 'bare': {\n const base = config.registry.replace(/\\/registry\\.json$/, '').replace(/\\/r$/, '')\n return { url: `${base}/r/${addr.name}.json` }\n }\n\n case 'github': {\n const parts = addr.name.split('/')\n const owner = parts[0]!\n const repo = parts[1]!\n const item = parts.slice(2).join('/')\n const ref = addr.ref ?? 'main'\n return {\n url: `https://raw.githubusercontent.com/${owner}/${repo}/${ref}/r/${item}.json`,\n }\n }\n\n case 'namespace': {\n const ns = addr.namespace!\n const name = addr.name\n\n // Config-defined namespaces always win\n if (config.registries?.[ns]) {\n const nsCfg = config.registries[ns]!\n const url = resolveNamespaceUrl(ns, name, nsCfg, env)\n const headers = typeof nsCfg !== 'string' ? nsCfg.headers : undefined\n const params = typeof nsCfg !== 'string' ? nsCfg.params : undefined\n const expandedHeaders = headers\n ? Object.fromEntries(Object.entries(headers).map(([k, v]) => [k, expandEnv(v, env)]))\n : undefined\n const expandedParams = params\n ? Object.fromEntries(Object.entries(params).map(([k, v]) => [k, expandEnv(v, env)]))\n : undefined\n const result: {\n url: string\n headers?: Record<string, string>\n params?: Record<string, string>\n } = { url }\n if (expandedHeaders) result.headers = expandedHeaders\n if (expandedParams) result.params = expandedParams\n return result\n }\n\n // Directory fallback hook (injected from T3)\n if (resolveNamespaceHook) {\n const hookResult = await resolveNamespaceHook(ns)\n if (hookResult) {\n const url = resolveNamespaceUrl(ns, name, hookResult, env)\n return { url }\n }\n }\n\n // Built-in first-party namespace fallback (@cascade is the legacy alias)\n if (ns === '@cascivo' || ns === '@cascade') {\n return { url: `${CASCIVO_HOST}/r/${name}.json` }\n }\n\n throw new Error(\n `Unknown namespace \"${ns}\". Add it to registries in cascivo.config.ts or check the directory at cascivo.com`,\n )\n }\n }\n}\n\nexport interface InstallPlan {\n items: {\n spec: string\n addr: ParsedAddress\n itemUrl: string\n headers?: Record<string, string>\n params?: Record<string, string>\n item: RegistryItem\n registryBase: string\n }[]\n}\n\nexport async function resolveClosure(\n specs: string[],\n config: CascadeConfig,\n env: NodeJS.ProcessEnv = process.env,\n resolveNamespaceHook?: (ns: string) => Promise<RegistryNamespaceConfig | null>,\n): Promise<InstallPlan> {\n const seen = new Set<string>()\n const queue: string[] = [...specs]\n const plan: InstallPlan['items'] = []\n\n while (queue.length > 0) {\n const spec = queue.shift()!\n const addr = parseAddress(spec, env)\n const identity = addr.raw\n\n if (seen.has(identity)) continue\n seen.add(identity)\n\n const { url, headers, params } = await resolveItemUrl(addr, config, env, resolveNamespaceHook)\n const fetchOpts: Parameters<typeof fetchJson>[1] = {}\n if (headers) fetchOpts.headers = headers\n if (params) fetchOpts.params = params\n const item = parseItem(await fetchJson(url, fetchOpts), url)\n\n const base = url.replace(/\\/[^/]+\\.json$/, '')\n\n const entry: InstallPlan['items'][number] = {\n spec,\n addr,\n itemUrl: url,\n item,\n registryBase: base,\n }\n if (headers) entry.headers = headers\n if (params) entry.params = params\n plan.push(entry)\n\n for (const dep of item.registryDependencies ?? []) {\n queue.push(dep)\n }\n }\n\n return { items: plan }\n}\n","import type { RegistryNamespaceConfig } from './config.js'\nimport { fetchJson } from './http.js'\nimport type { FetchFn } from './http.js'\n\nimport { CASCIVO_HOST } from './config.js'\n\nexport const DIRECTORY_URL = `${CASCIVO_HOST}/r/registries.json`\n\n/**\n * Pull the registry URL for one namespace out of a directory payload, or null.\n *\n * The result is used as a fetch base for component installs, so an entry whose\n * `registryUrl` is not a string — or not http(s) — is dropped rather than\n * trusted: `resolveItemUrl` would otherwise build request URLs by concatenating\n * onto whatever came back.\n */\nfunction pickRegistryUrl(raw: unknown, ns: string): string | null {\n if (typeof raw !== 'object' || raw === null) return null\n const registries = (raw as { registries?: unknown }).registries\n if (!Array.isArray(registries)) return null\n for (const entry of registries) {\n if (typeof entry !== 'object' || entry === null) continue\n const e = entry as Record<string, unknown>\n if (e['namespace'] !== ns) continue\n const url = e['registryUrl']\n if (typeof url !== 'string' || !/^https?:\\/\\//.test(url)) return null\n return url\n }\n return null\n}\n\nexport async function resolveFromDirectory(\n ns: string,\n fetchFn?: FetchFn,\n): Promise<RegistryNamespaceConfig | null> {\n try {\n // fetchJson uses the module-level _fetchFn; if a custom fetchFn is provided, we use it directly\n let data: unknown\n if (fetchFn) {\n const res = await fetchFn(DIRECTORY_URL, { headers: { Accept: 'application/json' } })\n if (!res.ok) throw new Error(`HTTP ${res.status}`)\n data = await res.json()\n } else {\n data = await fetchJson(DIRECTORY_URL)\n }\n return pickRegistryUrl(data, ns)\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e)\n console.warn(`Could not reach cascivo.com directory: ${msg}`)\n return null\n }\n}\n","import { readFileSync } from 'node:fs'\nimport { join, resolve as resolvePath } from 'node:path'\nimport {\n detectPackageManager,\n installHint,\n type CascadeConfig,\n type PackageManager,\n} from '../utils/config.js'\nimport { installPackages } from '../utils/exec.js'\nimport { assertInside, resolveOutputPath, writeFileSafe } from '../utils/fs.js'\nimport { fetchTextRetry } from '../utils/http.js'\nimport {\n fetchRegistry,\n fileName,\n findComponent,\n resolvedAlias,\n type Registry,\n type RegistryComponent,\n} from '../utils/registry.js'\nimport { createLock, readLock, sha256, updateLockEntry, writeLock } from '../utils/lock.js'\nimport { checkPeerVersions } from '../utils/peer-versions.js'\nimport { resolveClosure } from '../utils/resolve.js'\nimport { resolveFromDirectory } from '../utils/directory.js'\nimport { isTemplateItem, type RegistryItem } from '@cascivo/registry'\n\n/** Dependencies always present in a cascade project — never auto-installed. */\nconst ASSUMED_DEPS = new Set(['react', 'react-dom'])\n\n/** Merged dependencies + devDependencies from the project's package.json (empty if none). */\nfunction readProjectDeps(cwd: string): Record<string, unknown> {\n try {\n const pkg = JSON.parse(readFileSync(join(cwd, 'package.json'), 'utf8')) as {\n dependencies?: Record<string, unknown>\n devDependencies?: Record<string, unknown>\n }\n return { ...pkg.dependencies, ...pkg.devDependencies }\n } catch {\n // No package.json — treat as no deps installed.\n return {}\n }\n}\n\n/**\n * Copied components read `--cascivo-*` custom properties; without\n * @cascivo/tokens or @cascivo/themes imported somewhere, they render unstyled.\n * Print the wiring once after a successful install if neither is a dependency.\n */\nfunction hintThemesIfMissing(cwd: string, pm: PackageManager): void {\n const deps = readProjectDeps(cwd)\n if (deps['@cascivo/themes'] !== undefined || deps['@cascivo/tokens'] !== undefined) return\n console.log(\n '\\nStyling: cascivo components read --cascivo-* tokens, which this project does not import yet.',\n )\n console.log(` ${installHint(pm, ['@cascivo/themes'])}`)\n console.log(\" import '@cascivo/themes/all' // once, in your entry file\")\n console.log(' <html data-theme=\"light\"> // or any container')\n}\n\n/** Resolve where a template's own file is written — relative to the project root. */\nexport function resolveTemplateTarget(cwd: string, target: string): string {\n return assertInside(cwd, resolvePath(cwd, target))\n}\n\nexport interface ResolvedBareEntry {\n entry: RegistryComponent\n /** True if reached via an original `cascivo add` argument; false if pulled as a transitive dependency. */\n requested: boolean\n /**\n * The foreign name the caller typed, when it differed from the component's own — `Switch`\n * for `toggle`. Reported before the copy so nobody wonders why a different file appeared.\n */\n viaAlias?: string\n}\n\n/**\n * Names from other libraries → the cascivo layout primitive that fills the same\n * role, so `cascivo add box` installs `layout/flex`. Bare names that already\n * resolve (e.g. `flex` → `layout/flex` via suffix match) still list an alias here\n * for discoverability.\n */\nexport const LAYOUT_ALIASES: Record<string, string> = {\n box: 'layout/flex',\n hstack: 'layout/flex',\n vstack: 'layout/flex',\n gap: 'spacer',\n}\n\n/**\n * Disambiguation printed when a requested bare name is a real cascivo component\n * whose meaning differs from the same name elsewhere, so an adopter who grabbed\n * it by name alone learns the right primitive. Keyed by lowercased bare name.\n */\nexport const NAME_NOTES: Record<string, string> = {\n stack:\n \"Note: cascivo's Stack overlaps children into a card-pile (z-axis), not a \" +\n 'vertical spacing layout. For vertical spacing use Flex direction=\"vertical\" ' +\n '(cascivo add flex; aliases: vstack, hstack).',\n}\n\n/**\n * Resolve the transitive closure of bare-name registry entries, following each\n * entry's `registryDependencies`. De-duped by resolved registry name and\n * cycle-safe (an entry is processed at most once). Returns resolved entries in\n * install order plus the names that could not be found. Pure — no I/O.\n */\nexport function resolveBareClosure(\n registry: Registry,\n bareSpecs: string[],\n): { resolved: ResolvedBareEntry[]; missing: string[] } {\n const queue: { name: string; requested: boolean }[] = bareSpecs.map((name) => ({\n name,\n requested: true,\n }))\n const installed = new Set<string>()\n const resolved: ResolvedBareEntry[] = []\n const missing: string[] = []\n\n while (queue.length > 0) {\n const { name, requested } = queue.shift()!\n const resolvedName = LAYOUT_ALIASES[name.toLowerCase()] ?? name\n const entry = findComponent(registry, resolvedName)\n if (!entry) {\n missing.push(name)\n continue\n }\n if (installed.has(entry.name)) continue\n installed.add(entry.name)\n const alias = resolvedAlias(entry, name)\n resolved.push({ entry, requested, ...(alias ? { viaAlias: alias } : {}) })\n for (const dep of entry.registryDependencies ?? []) {\n queue.push({ name: dep, requested: false })\n }\n }\n\n return { resolved, missing }\n}\n\n/**\n * First-party items are hosted on cascivo.com or the cascivo/cascivo GitHub\n * repo (raw file URLs). Anything else gets a review-before-use notice.\n */\nconst FIRST_PARTY_URL = /^https:\\/\\/(cascivo\\.com|raw\\.githubusercontent\\.com\\/cascivo\\/cascivo)\\//\n\nexport function isThirdParty(itemUrl: string): boolean {\n return !FIRST_PARTY_URL.test(itemUrl)\n}\n\nfunction isMultiRegistrySpec(name: string): boolean {\n return (\n name.startsWith('@') ||\n name.startsWith('http://') ||\n name.startsWith('https://') ||\n name.startsWith('./') ||\n name.startsWith('/') ||\n name.split('/').length >= 3\n )\n}\n\nexport async function add(\n names: string[],\n config: CascadeConfig,\n opts: {\n dryRun?: boolean\n yes?: boolean\n cwd?: string\n pm?: PackageManager\n noInstall?: boolean\n } = {},\n): Promise<void> {\n if (names.length === 0) {\n console.error('Usage: cascivo add <component...>')\n return\n }\n\n const cwd = opts.cwd ?? process.cwd()\n const pm = opts.pm ?? detectPackageManager(cwd)\n const multiSpecs = names.filter(isMultiRegistrySpec)\n let bareSpecs = names.filter((n) => !isMultiRegistrySpec(n))\n\n // Bare names that match a first-party template install through the per-item\n // path (they carry file targets the bare component path cannot express).\n let registry: Registry | null = null\n if (bareSpecs.length > 0) {\n registry = await fetchRegistry(config.registry)\n const templateNames = new Set(registry.templates.map((t) => t.toLowerCase()))\n const templateSpecs = bareSpecs.filter((n) => templateNames.has(n.toLowerCase()))\n if (templateSpecs.length > 0) {\n bareSpecs = bareSpecs.filter((n) => !templateNames.has(n.toLowerCase()))\n multiSpecs.push(...templateSpecs.map((n) => `@cascivo/${n.toLowerCase()}`))\n }\n }\n\n let lock = (await readLock(cwd)) ?? createLock()\n\n // Handle multi-registry specs (namespaces, URLs, GitHub)\n if (multiSpecs.length > 0) {\n const plan = await resolveClosure(multiSpecs, config, process.env, resolveFromDirectory)\n\n if (opts.dryRun) {\n console.log('Dry run — would install:')\n for (const item of plan.items) {\n const kind = isTemplateItem(item.item) ? ' [template]' : ''\n console.log(\n ` ${item.spec} (${item.item.name}@${item.item.version})${kind} from ${item.itemUrl}`,\n )\n for (const f of item.item.files) {\n const arrow = isTemplateItem(item.item) && f.target ? ` → ${f.target}` : ''\n console.log(` ${f.url}${arrow}`)\n }\n if (item.item.registryDependencies?.length) {\n console.log(` components: ${item.item.registryDependencies.join(', ')}`)\n }\n }\n return\n }\n\n for (const { item, itemUrl, registryBase } of plan.items) {\n if (isThirdParty(itemUrl)) {\n console.log(\n `\\nReview before use — files from non-directory registry: ${registryBase}\\n` +\n (item.files ?? []).map((f) => ` ${f.url}`).join('\\n'),\n )\n }\n\n let fileHashes: Record<string, string>\n try {\n fileHashes = await installItem(item, config, cwd, {\n pm,\n ...(opts.noInstall ? { noInstall: true } : {}),\n })\n } catch (e) {\n // Nothing was written for this item (fetch-all-then-write), so the\n // lockfile must not record it either.\n console.error(`Failed to install ${item.name}: ${e instanceof Error ? e.message : e}`)\n process.exitCode = 1\n continue\n }\n lock = updateLockEntry(lock, item.name, {\n registry: registryBase,\n version: item.version,\n installedAt: new Date().toISOString().slice(0, 10),\n files: fileHashes,\n })\n }\n await writeLock(lock, cwd)\n if (bareSpecs.length === 0) {\n hintThemesIfMissing(cwd, pm)\n return\n }\n }\n\n if (bareSpecs.length === 0) return\n // Legacy bare-name path (uses the registry fetched above for template\n // detection). Resolves the transitive closure of registry (component)\n // dependencies so a component that imports a shared hook/sibling\n // (e.g. `../popover/use-popover`) installs that dependency too.\n registry ??= await fetchRegistry(config.registry)\n const missingDeps = new Set<string>()\n const registryBase = config.registry.replace(/\\/registry\\.json$/, '').replace(/\\/r$/, '')\n\n for (const spec of bareSpecs) {\n const note = NAME_NOTES[spec.toLowerCase()]\n if (note) console.log(note)\n\n const alias = LAYOUT_ALIASES[spec.toLowerCase()]\n if (!alias) continue\n const target = findComponent(registry, alias)\n if (target) {\n console.log(\n `\"${spec}\" is not a cascivo component — installing ${target.name} (its ${spec} primitive).`,\n )\n }\n }\n\n const { resolved, missing } = resolveBareClosure(registry, bareSpecs)\n for (const name of missing) {\n console.error(`Component \"${name}\" not found in registry. Run \"cascivo list\".`)\n }\n\n // Announce the CHANNEL before anything else runs. `cascivo add area-chart` reads like\n // every other add — same syntax, same \"you own the code\" framing — but copies no source:\n // it installs an npm package. That was only stated inside the install log, which scrolls\n // past. Say it first, once per package, for what the caller actually asked for.\n // A foreign name resolved to a different file name: say so, or the copy looks like a\n // mistake. `Switch` is the highest-traffic case — every peer system calls it that.\n for (const { entry, requested, viaAlias } of resolved) {\n if (!requested || !viaAlias) continue\n console.log(`\\n\"${viaAlias}\" is cascivo's \"${entry.name}\" — installing that.`)\n }\n\n const announced = new Set<string>()\n for (const { entry, requested } of resolved) {\n if (!requested || !entry.install || announced.has(entry.install)) continue\n announced.add(entry.install)\n console.log(\n `\\n\"${entry.name}\" ships in the ${entry.install} npm package — no source is copied ` +\n 'into your project. Updates come from your package manager, not `cascivo update`.',\n )\n }\n\n // Warn BEFORE copying, and only for what the caller actually asked for — a deprecated\n // entry pulled in transitively is not their decision to make. The source's `@deprecated`\n // JSDoc arrives too late: by the time it is read, the file is already vendored.\n for (const { entry, requested } of resolved) {\n if (!requested || !entry.deprecated) continue\n const { replacement, since, note } = entry.deprecated\n console.warn(\n `\\n⚠ \"${entry.name}\" is deprecated since ${since}. Use \"${replacement}\" instead:\\n` +\n ` cascivo add ${replacement}\\n` +\n (note ? ` ${note}\\n` : '') +\n ` Adding \"${entry.name}\" anyway — it still works.\\n`,\n )\n }\n\n // Aggregate each resolved entry's peer-version floors (e.g. \"install data-table\n // needs @cascivo/i18n >= 0.2.1\") so we can verify what actually got installed.\n const peerFloors: Record<string, string> = {}\n for (const { entry } of resolved) {\n for (const [pkg, floor] of Object.entries(entry.peerVersions ?? {})) {\n peerFloors[pkg] = floor\n }\n }\n\n // npm-distributed entries (charts/flow/editor) are a runtime package, not\n // copied source. Collect their package + import lines here so N chart entries\n // produce ONE `@cascivo/charts` install rather than N, then install once below.\n const npmPackages = new Set<string>()\n const importLines: string[] = []\n\n for (const { entry, requested } of resolved) {\n if (entry.install) {\n const pkg = entry.install\n npmPackages.add(pkg)\n console.log(\n `\"${entry.name}\" is distributed as the npm package ${pkg} — a runtime dependency, ` +\n `not copied source (updates come via your package manager).`,\n )\n importLines.push(` import { ${entry.meta.name} } from '${pkg}'`)\n if (entry.styles) {\n importLines.push(` import '${entry.styles}' // once, in your entry file`)\n }\n continue\n }\n\n const outputName = entry.name.includes('/') ? entry.name.split('/').pop()! : entry.name\n const fileHashes: Record<string, string> = {}\n\n // Two-phase: fetch every file before writing any, so a mid-install network\n // failure can never leave a half-copied component (or a lockfile entry\n // pointing at one).\n let fetched: { url: string; content: string }[]\n try {\n fetched = await Promise.all(\n entry.files.map(async (url) => ({ url, content: await fetchTextRetry(url) })),\n )\n } catch (e) {\n console.error(`Failed to install ${entry.name}: ${e instanceof Error ? e.message : e}`)\n process.exitCode = 1\n continue\n }\n for (const { url, content } of fetched) {\n const dest = resolveOutputPath(config.outputDir, outputName, fileName(url), cwd)\n await writeFileSafe(dest, content)\n fileHashes[dest] = sha256(content)\n }\n\n for (const dep of entry.dependencies) {\n if (!ASSUMED_DEPS.has(dep)) missingDeps.add(dep)\n }\n\n lock = updateLockEntry(lock, entry.name, {\n registry: registryBase,\n version: entry.version,\n installedAt: new Date().toISOString().slice(0, 10),\n files: fileHashes,\n })\n\n const suffix = requested ? '' : ' (dependency)'\n console.log(`Added ${entry.name} to ${config.outputDir}/${outputName}/${suffix}`)\n }\n\n // Install npm-distributed packages (charts/flow/editor) once, deduped, skipping\n // any already in the project. `--no-install`/`--dry-run` fall back to printing.\n if (npmPackages.size > 0) {\n const deps = readProjectDeps(cwd)\n const needed = [...npmPackages].filter((p) => deps[p] === undefined)\n if (opts.dryRun) {\n console.log(`Dry run — would install npm package(s): ${[...npmPackages].join(', ')}`)\n } else if (needed.length > 0) {\n if (opts.noInstall) {\n console.log(`\\nSkipped install (--no-install). Install with:\\n ${installHint(pm, needed)}`)\n } else if (!installPackages(needed, cwd, { pm })) {\n process.exitCode = 1\n }\n }\n if (importLines.length > 0) {\n console.log(`\\nImport it:\\n${importLines.join('\\n')}`)\n }\n }\n\n if (missingDeps.size > 0 && !opts.dryRun) {\n if (opts.noInstall) {\n console.log(\n `\\nSkipped install (--no-install). Install with:\\n ${installHint(pm, [...missingDeps])}`,\n )\n } else {\n installPackages([...missingDeps], cwd, { pm })\n }\n }\n\n if (Object.keys(peerFloors).length > 0) {\n const violations = await checkPeerVersions(cwd, peerFloors)\n for (const v of violations) {\n console.error(\n `\\nWarning: ${v.pkg} ${v.installed ? `${v.installed} is` : 'is not'} installed, but ` +\n `the copied component source needs ${v.pkg} ${v.required}. ` +\n `Run: ${installHint(pm, [`${v.pkg}@latest`])}`,\n )\n process.exitCode = 1\n }\n }\n\n await writeLock(lock, cwd)\n hintThemesIfMissing(cwd, pm)\n}\n\n/**\n * Install a single resolved item, returning a map of written path → content\n * hash for the lockfile. A template writes its own files to their `target`\n * paths (relative to the project root); every other item writes its files under\n * the components output directory. A template's components are installed\n * separately as their own plan entries (via `registryDependencies`).\n */\nasync function installItem(\n item: RegistryItem,\n config: CascadeConfig,\n cwd: string,\n opts: { pm?: PackageManager; noInstall?: boolean } = {},\n): Promise<Record<string, string>> {\n const fileHashes: Record<string, string> = {}\n const missingDeps = new Set<string>()\n const template = isTemplateItem(item)\n const outputName = item.name.includes('/') ? item.name.split('/').pop()! : item.name\n\n // Two-phase: fetch every file before writing any. A failed fetch aborts the\n // whole item (throws to the caller) instead of silently installing a subset.\n const fetched = await Promise.all(\n (item.files ?? []).map(async (file) => ({\n file,\n content: await fetchTextRetry(file.url),\n })),\n )\n for (const { file, content } of fetched) {\n const dest =\n template && file.target\n ? resolveTemplateTarget(cwd, file.target)\n : resolveOutputPath(config.outputDir, outputName, fileName(file.url), cwd)\n await writeFileSafe(dest, content)\n fileHashes[dest] = sha256(content)\n }\n\n for (const dep of item.dependencies ?? []) {\n if (!ASSUMED_DEPS.has(dep)) missingDeps.add(dep)\n }\n\n if (missingDeps.size > 0) {\n if (opts.noInstall) {\n console.log(\n `\\nSkipped install (--no-install). Install with:\\n ${installHint(opts.pm ?? detectPackageManager(cwd), [...missingDeps])}`,\n )\n } else {\n installPackages([...missingDeps], cwd, opts.pm ? { pm: opts.pm } : {})\n }\n }\n\n if (template) {\n const pages = item.files?.filter((f) => f.target).map((f) => f.target) ?? []\n console.log(`Installed template ${item.name} (${pages.length} files)`)\n } else {\n console.log(`Added ${item.name} to ${config.outputDir}/${outputName}/`)\n }\n\n return fileHashes\n}\n","import { readFileSync, readdirSync, existsSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { detectPackageManager, installHint } from '../utils/config.js'\nimport { readInstalledPackageVersion } from '../utils/peer-versions.js'\nimport { compareVersions } from '../utils/semver.js'\n\nexport interface DoctorViolation {\n file: string\n rule: string\n detail: string\n}\n\nexport interface DoctorResult {\n violations: DoctorViolation[]\n passed: boolean\n}\n\n/** Runtime packages **copied** cascivo source needs; the last is @cascivo/core's peer. */\nconst REQUIRED_RUNTIME_DEPS = [\n '@cascivo/core',\n '@cascivo/tokens',\n '@cascivo/themes',\n '@preact/signals-react',\n]\n\n/** Runtime packages a **prebuilt** (Path B) app needs. */\nconst REQUIRED_PREBUILT_DEPS = ['@cascivo/react', '@cascivo/themes', '@preact/signals-react']\n\n/**\n * Packages a prebuilt app must NOT declare directly, with the rule each one breaks. They\n * are transitive there, and everything they export is re-exported from `@cascivo/react`.\n */\nconst FORBIDDEN_PREBUILT_DEPS: Record<string, string> = {\n '@cascivo/core':\n 'AI-RULES.md: never add @cascivo/core to a prebuilt-path app — it is transitive, and everything is re-exported from @cascivo/react',\n '@cascivo/tokens':\n 'GETTING-STARTED.md: @cascivo/tokens comes with @cascivo/themes as a direct dependency — never install it by hand',\n}\n\n/** Installed on demand by `cascivo add` when a component/chart declares them. */\nconst ON_DEMAND_DEPS = ['@cascivo/i18n', '@cascivo/charts']\n\nexport interface DependencyFinding {\n package: string\n /** true = a runtime dep whose absence breaks the build; false = advisory. */\n required: boolean\n hint: string\n /**\n * What is wrong. `'missing'` (the default) means install it; `'forbidden'` means the\n * project declares a package its install path must not. They need opposite advice, and\n * reporting both under the \"not in package.json — install it\" template produced a\n * self-contradicting message.\n */\n kind?: 'missing' | 'forbidden'\n}\n\nconst CONFIG_FILES = ['cascivo.config.ts', 'cascivo.config.js', 'cascivo.config.mjs']\n\n/**\n * How this project consumes cascivo.\n *\n * - `prebuilt` — Path B: depends on `@cascivo/react`, no copied source.\n * - `copied` — Path A: has vendored component source (or no `@cascivo/react`).\n * - `hybrid` — both: consumes the package AND copied something.\n * - `unknown` — no evidence either way; emit no dependency advice at all.\n */\nexport type InstallPath = 'prebuilt' | 'copied' | 'hybrid' | 'unknown'\n\n/**\n * Infer the install path from evidence.\n *\n * This used to be `isAdopterProject()` — \"does a `cascivo.config.*` exist?\" — and\n * `cascivo create` wrote that config into every scaffold, including prebuilt-path ones. So\n * every scaffolded app was judged copy-paste and told to install `@cascivo/core` and\n * `@cascivo/tokens`, which the docs explicitly forbid on that path. `doctor --ci` exited 1\n * on a correctly-installed app, which made the CI gate the docs recommend\n * (`cascivo doctor --ci && cascivo audit --ai src`) red on day one.\n *\n * A config file now only contributes evidence when it points at a directory that actually\n * contains copied source, which is what it was ever meant to signal.\n */\nexport function detectInstallPath(cwd: string): InstallPath {\n let deps: Record<string, unknown> = {}\n let hasPackageJson = true\n try {\n const pkg = JSON.parse(readFileSync(join(cwd, 'package.json'), 'utf8')) as {\n dependencies?: Record<string, unknown>\n devDependencies?: Record<string, unknown>\n }\n deps = { ...pkg.dependencies, ...pkg.devDependencies }\n } catch {\n hasPackageJson = false\n }\n\n if (!hasPackageJson) return 'unknown'\n\n const usesPackage = deps['@cascivo/react'] !== undefined\n const copied = hasCopiedSource(cwd)\n\n if (usesPackage && copied) return 'hybrid'\n if (usesPackage) return 'prebuilt'\n if (copied) return 'copied'\n // No package dependency and no copied source yet. A config file alone is NOT evidence of\n // a copy-paste app — it is what `cascivo add` writes before anything has been copied, and\n // treating it as proof is precisely what broke prebuilt-path projects. Advise on nothing.\n return 'unknown'\n}\n\n/** Whether the configured output directory holds vendored component source. */\nfunction hasCopiedSource(cwd: string): boolean {\n for (const dir of outputDirCandidates(cwd)) {\n const full = join(cwd, dir)\n if (!existsSync(full)) continue\n try {\n if (readdirSync(full).some((f) => f.endsWith('.tsx'))) return true\n } catch {\n // unreadable directory — no evidence, keep looking\n }\n }\n return false\n}\n\n/** `outputDir` from the config if it declares one, plus the documented default. */\nfunction outputDirCandidates(cwd: string): string[] {\n const dirs = new Set<string>(['src/components/ui'])\n for (const file of CONFIG_FILES) {\n const full = join(cwd, file)\n if (!existsSync(full)) continue\n try {\n const declared = /outputDir\\s*:\\s*['\"]([^'\"]+)['\"]/.exec(readFileSync(full, 'utf8'))?.[1]\n if (declared !== undefined) dirs.add(declared)\n } catch {\n // unreadable config — fall back to the default candidate\n }\n }\n return [...dirs]\n}\n\n/** Whether cwd looks like a cascivo adopter project (has a generated config). */\nexport function isAdopterProject(cwd: string): boolean {\n return CONFIG_FILES.some((f) => existsSync(join(cwd, f)))\n}\n\n/**\n * Check that the runtime dependencies this project's install path needs are declared in its\n * package.json — and, on the prebuilt path, that it declares none it must not.\n *\n * Turns the opaque \"cannot find module '@preact/signals-react'\" build failure into a\n * diagnosed condition with a fix. What it demands depends on `detectInstallPath`: requiring\n * `@cascivo/core` of a prebuilt app is not merely unhelpful, it is the opposite of what the\n * docs say, and following the advice makes a correct project wrong.\n *\n * `@cascivo/i18n`/`@cascivo/charts` stay advisory since not every project uses them, and an\n * `unknown` path emits nothing at all rather than guessing.\n */\nexport function checkProjectDependencies(cwd: string): DependencyFinding[] {\n let deps: Record<string, unknown> = {}\n try {\n const pkg = JSON.parse(readFileSync(join(cwd, 'package.json'), 'utf8')) as {\n dependencies?: Record<string, unknown>\n devDependencies?: Record<string, unknown>\n }\n deps = { ...pkg.dependencies, ...pkg.devDependencies }\n } catch {\n return [] // No readable package.json — nothing reliable to advise on.\n }\n const path = detectInstallPath(cwd)\n if (path === 'unknown') return []\n\n const pm = detectPackageManager(cwd)\n const findings: DependencyFinding[] = []\n\n const required = path === 'prebuilt' ? REQUIRED_PREBUILT_DEPS : REQUIRED_RUNTIME_DEPS\n for (const pkg of required) {\n if (deps[pkg] === undefined) {\n findings.push({\n package: pkg,\n required: true,\n hint: `detected ${path} install path — ${installHint(pm, [pkg])}`,\n })\n }\n }\n\n // Only meaningful on a pure prebuilt app. A hybrid legitimately needs `@cascivo/core`\n // for its copied source, so flagging it there would recreate the bug in mirror image.\n if (path === 'prebuilt') {\n for (const [pkg, reason] of Object.entries(FORBIDDEN_PREBUILT_DEPS)) {\n if (deps[pkg] !== undefined) {\n findings.push({ package: pkg, required: true, kind: 'forbidden', hint: reason })\n }\n }\n }\n\n for (const pkg of ON_DEMAND_DEPS) {\n if (deps[pkg] === undefined) {\n findings.push({ package: pkg, required: false, hint: installHint(pm, [pkg]) })\n }\n }\n return findings\n}\n\n/**\n * Two copies of `@cascivo/core` in one install.\n *\n * `@cascivo/react` and `@cascivo/charts` each depend on `@cascivo/core`, and the family\n * versions independently on 0.x. If their ranges do not overlap, the package manager\n * resolves a nested second copy — and because cascivo's reactivity is a module-level signal\n * registry, two copies means two registries: a signal written through one is invisible to\n * components subscribed through the other. Nothing errors. Handlers fire and the UI does\n * not move, which is the single hardest cascivo symptom to diagnose.\n *\n * Turning that into a named finding is the cheap half of the version-sprawl problem\n * (lockstep versioning is the expensive half, and is a policy decision).\n */\nexport interface DuplicateCoreFinding {\n /** Version at the install root, if any. */\n root: string | null\n /** Nested copies, as `<owner> → <version>`. */\n nested: string[]\n hint: string\n}\n\n/** Packages that carry their own `@cascivo/core` dependency. */\nconst CORE_DEPENDENTS = ['@cascivo/react', '@cascivo/charts', '@cascivo/flow', '@cascivo/editor']\n\nexport async function checkDuplicateCore(cwd: string): Promise<DuplicateCoreFinding | null> {\n const root = await readInstalledPackageVersion(cwd, '@cascivo/core')\n const nested: string[] = []\n for (const owner of CORE_DEPENDENTS) {\n const ownerRoot = join(cwd, 'node_modules', owner)\n if (!existsSync(ownerRoot)) continue\n const version = await readInstalledPackageVersion(ownerRoot, '@cascivo/core')\n // A nested copy only matters when it differs from the hoisted one.\n if (version !== null && version !== root) nested.push(`${owner} → ${version}`)\n }\n if (nested.length === 0) return null\n return {\n root,\n nested,\n hint:\n 'Align the @cascivo/* versions (they are released together — see breaking-changes.json) ' +\n 'and reinstall. Two copies of @cascivo/core means two signal registries: writes through ' +\n 'one are invisible to components subscribed through the other, with no error.',\n }\n}\n\nexport interface SignalsCompatFinding {\n /** 'error' = a runtime break (React 19 + signals <3); 'warning' = works but upgrade advised. */\n severity: 'error' | 'warning'\n detail: string\n hint: string\n}\n\n/**\n * Checks the installed `@preact/signals-react` against the installed React.\n * React 19 removed the `__SECRET_INTERNALS…` export that signals-react 2.x\n * imports, so a 2.x runtime on React 19 dies with a `SyntaxError` at module\n * evaluation (the 2026-07-20 report's blocker #2). cascivo peer-depends on\n * `>=3.0.0`, but a lockfile carried over from an earlier install can still pin\n * 2.x — this turns that into a diagnosed condition with a fix. Returns null when\n * either package is absent/unreadable (nothing reliable to advise on) or the\n * pairing is fine.\n */\nexport async function checkSignalsCompat(cwd: string): Promise<SignalsCompatFinding | null> {\n const [signals, react] = await Promise.all([\n readInstalledPackageVersion(cwd, '@preact/signals-react'),\n readInstalledPackageVersion(cwd, 'react'),\n ])\n if (signals === null) return null\n let signalsBelow3: boolean\n try {\n signalsBelow3 = compareVersions(signals, '3.0.0') < 0\n } catch {\n return null // unparsable installed signals version — don't advise on it\n }\n if (!signalsBelow3) return null\n const pm = detectPackageManager(cwd)\n const hint = installHint(pm, ['@preact/signals-react@^3'])\n let reactMajor: number | null = null\n if (react !== null) {\n const m = /^(\\d+)\\./.exec(react.trim())\n reactMajor = m ? Number(m[1]) : null\n }\n if (reactMajor !== null && reactMajor >= 19) {\n return {\n severity: 'error',\n detail: `@preact/signals-react ${signals} cannot run on React ${react} — React 19 removed an internal signals 2.x imports, so it fails at module load. Upgrade to signals-react 3.x.`,\n hint,\n }\n }\n return {\n severity: 'warning',\n detail: `@preact/signals-react ${signals} is below the required 3.x floor. It works on React 18 today but breaks the moment you move to React 19; upgrade now.`,\n hint,\n }\n}\n\n/** Vite SSR frameworks whose default setup needs `ssr.noExternal` for cascivo. */\nconst VITE_SSR_MARKERS = ['@tanstack/react-start', 'vite-ssr', '@remix-run/dev']\nconst VITE_CONFIG_FILES = ['vite.config.ts', 'vite.config.js', 'vite.config.mjs', 'vite.config.mts']\n\n/**\n * Advisory: on a Vite SSR framework, cascivo's per-component `.css` side-effect\n * imports crash a bare server-side ESM loader unless the packages are marked\n * `ssr.noExternal` (or the `cascivoSsr()` plugin is used). This warns when a known\n * Vite SSR framework is present but no vite config mentions either — the exact\n * cliff the 2026-07-20 report hit (blocker #1). A text match, not a gate. Returns\n * null when there's no Vite SSR framework or the config already handles it.\n */\n/**\n * Warn when the vendored components dir is not excluded from the project's formatter.\n *\n * Owning the code means your formatter rewrites it, and `cascivo update` then reports drift\n * on files you never edited. `cascivo init` writes the exclusion for you, but a project that\n * adopted cascivo before that existed — or that added Prettier afterwards — never got it.\n */\nexport function checkFormatterIgnore(cwd: string, outputDir: string): string | null {\n const pairs = [\n {\n configs: ['.prettierrc', '.prettierrc.json', '.prettierrc.js', 'prettier.config.js'],\n ignore: '.prettierignore',\n },\n { configs: ['.oxfmtrc', '.oxfmtrc.json'], ignore: '.oxfmtignore' },\n ]\n const dir = outputDir.replace(/\\/+$/, '')\n for (const { configs, ignore } of pairs) {\n if (!configs.some((f) => existsSync(join(cwd, f)))) continue\n let content = ''\n try {\n content = readFileSync(join(cwd, ignore), 'utf8')\n } catch {\n /* no ignore file at all */\n }\n if (content.split('\\n').some((l) => l.trim().replace(/\\/+$/, '') === dir)) continue\n return (\n `\"${dir}/\" is not excluded from your formatter. Running it will rewrite code you own, ` +\n `and \\`cascivo update\\` will then report drift on files you never edited. ` +\n `Add \"${dir}/\" to ${ignore}.`\n )\n }\n return null\n}\n\nconst ASTRO_CONFIG_FILES = [\n 'astro.config.mjs',\n 'astro.config.ts',\n 'astro.config.js',\n 'astro.config.mts',\n]\n\n/** Keyword every published cascivo CSS package carries (react >1.9.0): marks it Astro-safe. */\nconst ASTRO_COMPONENT_KEYWORD = 'astro-component'\n\n/**\n * True when `config` has a `resolve: { ... noExternal ... }` block. Astro prerenders in its own\n * Vite environment, which reads `resolve.noExternal` and ignores `ssr.noExternal`, so the two\n * must not be confused. Brace-balanced rather than a lazy regex: a `resolve` block commonly\n * holds a nested `alias: { ... }` before `noExternal`.\n */\nfunction setsResolveNoExternal(config: string): boolean {\n if (/\\bresolve\\s*\\.\\s*noExternal\\b/.test(config)) return true\n for (const match of config.matchAll(/\\bresolve\\s*:\\s*\\{/g)) {\n let depth = 1\n let i = match.index + match[0].length\n const start = i\n while (i < config.length && depth > 0) {\n const c = config[i]\n if (c === '{') depth++\n else if (c === '}') depth--\n i++\n }\n if (/\\bnoExternal\\b/.test(config.slice(start, i))) return true\n }\n return false\n}\n\n/**\n * True when the installed `@cascivo/react` declares `astro-component`. The file is third-party\n * input, so it is bound as `unknown` and narrowed before `keywords` is trusted.\n */\nfunction installedReactIsAstroSafe(cwd: string): boolean {\n let pkg: unknown\n try {\n pkg = JSON.parse(readFileSync(join(cwd, 'node_modules/@cascivo/react/package.json'), 'utf8'))\n } catch {\n return false\n }\n if (typeof pkg !== 'object' || pkg === null || !('keywords' in pkg)) return false\n const { keywords } = pkg\n return Array.isArray(keywords) && keywords.includes(ASTRO_COMPONENT_KEYWORD)\n}\n\n/**\n * Astro branch of {@link checkSsrConfig}. Without the integration, `resolve.noExternal`, or a\n * cascivo build that opts in via keyword, SSR'd islands render unstyled with no error.\n */\nfunction checkAstroConfig(cwd: string, configFile: string): string | null {\n // Only the prebuilt package's CSS can be externalized. Vendored source under src/ is compiled\n // by Vite itself, so a copy-paste-only project has nothing to warn about.\n const installPath = detectInstallPath(cwd)\n if (installPath !== 'prebuilt' && installPath !== 'hybrid') return null\n const config = readFileSync(join(cwd, configFile), 'utf8')\n if (/@cascivo\\/astro/.test(config)) return null\n if (setsResolveNoExternal(config)) return null\n if (installedReactIsAstroSafe(cwd)) return null\n const ssrOnly = /\\bssr\\s*:\\s*\\{[^}]*noExternal/.test(config)\n return (\n `${configFile} does not use the @cascivo/astro integration, so cascivo's CSS is ` +\n `externalized in Astro's prerender and islands render unstyled with no error` +\n (ssrOnly ? ` (Astro ignores ssr.noExternal; it reads resolve.noExternal)` : '') +\n `. Run \\`npx astro add @cascivo/astro\\`. ` +\n `Recipe: https://cascivo.com/docs/using-with-astro.md`\n )\n}\n\nexport function checkSsrConfig(cwd: string): string | null {\n // Astro first: it is not one of the Vite SSR frameworks below and needs a different config key.\n const astroConfig = ASTRO_CONFIG_FILES.find((f) => existsSync(join(cwd, f)))\n if (astroConfig !== undefined) return checkAstroConfig(cwd, astroConfig)\n\n let deps: Record<string, unknown> = {}\n try {\n const pkg = JSON.parse(readFileSync(join(cwd, 'package.json'), 'utf8')) as {\n dependencies?: Record<string, unknown>\n devDependencies?: Record<string, unknown>\n }\n deps = { ...pkg.dependencies, ...pkg.devDependencies }\n } catch {\n return null\n }\n const framework = VITE_SSR_MARKERS.find((m) => deps[m] !== undefined)\n if (framework === undefined) return null\n\n for (const file of VITE_CONFIG_FILES) {\n const path = join(cwd, file)\n if (!existsSync(path)) continue\n const config = readFileSync(path, 'utf8')\n // Either the manual noExternal entry or the cascivoSsr() plugin counts.\n if (/noExternal/.test(config) && /@cascivo/.test(config)) return null\n if (/cascivoSsr/.test(config)) return null\n }\n return (\n `${framework} is a Vite SSR framework, but no vite config marks the cascivo ` +\n `packages ssr.noExternal — an unconfigured SSR build crashes with ` +\n `\\`Unknown file extension \".css\"\\`. Add \\`ssr: { noExternal: [/^@cascivo\\\\//] }\\` ` +\n `(or the cascivoSsr() plugin from @cascivo/vite-plugin). ` +\n `Recipe: https://cascivo.com/docs/using-with-vite-ssr.md`\n )\n}\n\nconst BANNED_HOOKS = ['useState', 'useEffect', 'useLayoutEffect', 'useContext', 'useReducer']\n\n/**\n * Blank out comments and string/template-literal contents so identifier scans\n * only match real code. A mention of `useEffect` in a comment must not trip\n * the no-react-hooks rule. Single pass — a `//` inside a string (URLs) is not\n * treated as a comment.\n */\nexport function stripCommentsAndStrings(source: string): string {\n let out = ''\n let i = 0\n const n = source.length\n while (i < n) {\n const c = source[i]!\n const next = source[i + 1]\n if (c === '/' && next === '/') {\n while (i < n && source[i] !== '\\n') i++\n } else if (c === '/' && next === '*') {\n i += 2\n while (i < n && !(source[i] === '*' && source[i + 1] === '/')) i++\n i += 2\n } else if (c === \"'\" || c === '\"') {\n i++\n while (i < n && source[i] !== c) {\n if (source[i] === '\\\\') i++\n i++\n }\n i++\n out += c + c\n } else if (c === '`') {\n i++\n while (i < n && source[i] !== '`') {\n if (source[i] === '\\\\') i++\n i++\n }\n i++\n out += '``'\n } else {\n out += c\n i++\n }\n }\n return out\n}\n\nexport async function runDoctor(root: string): Promise<DoctorResult> {\n const violations: DoctorViolation[] = []\n const componentsDir = join(root, 'packages', 'components', 'src')\n if (!existsSync(componentsDir)) return { violations: [], passed: true }\n\n const components = readdirSync(componentsDir, { withFileTypes: true })\n .filter((d) => d.isDirectory())\n .map((d) => d.name)\n\n const reactIndex = join(root, 'packages', 'react', 'src', 'index.ts')\n const indexContent = existsSync(reactIndex) ? readFileSync(reactIndex, 'utf8') : ''\n\n for (const name of components) {\n const tsxPath = join(componentsDir, name, `${name}.tsx`)\n if (!existsSync(tsxPath)) continue\n const content = readFileSync(tsxPath, 'utf8')\n // Hook scan runs on code only; the aria-label scan below needs the\n // original source because it matches inside JSX string attributes.\n const code = stripCommentsAndStrings(content)\n\n for (const hook of BANNED_HOOKS) {\n if (new RegExp(`\\\\b${hook}\\\\b`).test(code)) {\n violations.push({\n file: tsxPath,\n rule: 'no-react-hooks',\n detail: `Banned hook '${hook}' in ${name}.tsx`,\n })\n }\n }\n\n if (/aria-label=\"[A-Z]/.test(content)) {\n violations.push({\n file: tsxPath,\n rule: 'no-hardcoded-strings',\n detail: `Hardcoded aria-label in ${name}.tsx — use t(builtin.*)`,\n })\n }\n\n if (!new RegExp(`from.*components/src/${name}`).test(indexContent)) {\n violations.push({\n file: tsxPath,\n rule: 'missing-react-export',\n detail: `${name} not exported from @cascivo/react`,\n })\n }\n }\n\n return { violations, passed: violations.length === 0 }\n}\n","import { writeFileSync } from 'node:fs'\nimport { basename, dirname, join } from 'node:path'\nimport type { CascadeConfig } from '../utils/config.js'\n\n// Inline validation types to avoid runtime dep on @cascivo/render\ninterface PropMeta {\n name: string\n type: string\n required?: boolean\n default?: string\n}\n\ninterface ComponentNode {\n component: string\n props?: Record<string, unknown>\n bind?: Record<string, string>\n events?: Record<string, string>\n children?: ComponentNode[] | string | { $t: string; params?: Record<string, string | number> }\n}\n\ninterface ViewConfig {\n state?: Record<string, string | number | boolean | null>\n view: {\n regions: Record<string, ComponentNode[]>\n }\n}\n\n/**\n * Sub-components installed into another component's registry directory. Every other name\n * resolves to its own kebab-case directory (`DataTable` → `data-table`); `generate.test.ts`\n * checks both rules against `registry.json`, so a new exception fails there, not in an\n * adopter's build.\n */\nconst OWNER_DIRECTORY: Record<string, string> = {\n AppFrame: 'app-shell',\n CardContent: 'card',\n CardFooter: 'card',\n CardHeader: 'card',\n CardTitle: 'card',\n ListItem: 'list',\n GridItem: 'grid',\n RadioCardGroup: 'radio-card',\n}\n\n/** The registry directory `cascivo add` installs `component` into. */\nexport function componentDirectory(component: string): string {\n return (\n OWNER_DIRECTORY[component] ?? component.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase()\n )\n}\n\n// Everything below is interpolated into TSX source, so the parser admits only names that\n// cannot break out of their position: identifiers for components, props and state keys,\n// dotted identifier paths for refs and translation keys.\nconst COMPONENT_RE = /^[A-Z][A-Za-z0-9]*$/\nconst PROP_RE = /^[A-Za-z_$][\\w$]*(?:-[\\w$]+)*$/\nconst IDENT_RE = /^[A-Za-z_$][\\w$]*$/\nconst REF_RE =\n /^\\$(?:data|actions|state|state\\.set|state\\.toggle)\\.[A-Za-z_$][\\w$]*(?:\\.[A-Za-z_$][\\w$]*)*$/\nconst KEY_RE = /^[\\w-]+(?:\\.[\\w-]+)*$/\n\nfunction fail(path: string, message: string): never {\n throw new Error(`Invalid ViewConfig at ${path}: ${message}`)\n}\n\nfunction isRecord(v: unknown): v is Record<string, unknown> {\n return typeof v === 'object' && v !== null && !Array.isArray(v)\n}\n\nfunction parseRefs(raw: unknown, path: string): Record<string, string> {\n if (!isRecord(raw)) fail(path, 'expected an object')\n const out: Record<string, string> = {}\n for (const [k, v] of Object.entries(raw)) {\n if (!PROP_RE.test(k)) fail(`${path}.${k}`, 'not a valid prop name')\n if (typeof v !== 'string' || !REF_RE.test(v)) {\n fail(`${path}.${k}`, 'expected a \"$data.*\", \"$actions.*\" or \"$state.*\" reference')\n }\n out[k] = v\n }\n return out\n}\n\nfunction parseTranslationRef(raw: Record<string, unknown>, path: string): { $t: string } {\n if (typeof raw.$t !== 'string' || !KEY_RE.test(raw.$t)) fail(`${path}.$t`, 'invalid key')\n return { $t: raw.$t }\n}\n\nfunction parseNode(raw: unknown, path: string): ComponentNode {\n if (!isRecord(raw)) fail(path, 'expected a component node object')\n const { component, props, bind, events, children } = raw\n if (typeof component !== 'string' || !COMPONENT_RE.test(component)) {\n fail(`${path}.component`, 'expected a PascalCase component name')\n }\n const node: ComponentNode = { component }\n if (props !== undefined) {\n if (!isRecord(props)) fail(`${path}.props`, 'expected an object')\n for (const [k, v] of Object.entries(props)) {\n if (!PROP_RE.test(k)) fail(`${path}.props.${k}`, 'not a valid prop name')\n if (isRecord(v) && '$t' in v) props[k] = parseTranslationRef(v, `${path}.props.${k}`)\n }\n node.props = props\n }\n if (bind !== undefined) node.bind = parseRefs(bind, `${path}.bind`)\n if (events !== undefined) node.events = parseRefs(events, `${path}.events`)\n if (children !== undefined) {\n if (typeof children === 'string') node.children = children\n else if (Array.isArray(children)) {\n node.children = children.map((c, i) => parseNode(c, `${path}.children[${i}]`))\n } else if (isRecord(children) && '$t' in children) {\n node.children = parseTranslationRef(children, `${path}.children`)\n } else fail(`${path}.children`, 'expected a string, a node array or a { $t } reference')\n }\n return node\n}\n\n/** Parse an untrusted ViewConfig (model output, a file) into one that is safe to emit as TSX. */\nexport function parseViewConfig(raw: unknown): ViewConfig {\n if (!isRecord(raw)) fail('$', 'expected an object')\n const { state, view } = raw\n const config: ViewConfig = { view: { regions: {} } }\n if (state !== undefined) {\n if (!isRecord(state)) fail('state', 'expected an object')\n const parsed: NonNullable<ViewConfig['state']> = {}\n for (const [k, v] of Object.entries(state)) {\n if (!IDENT_RE.test(k)) fail(`state.${k}`, 'not a valid identifier')\n if (v === null || typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean') {\n parsed[k] = v\n } else fail(`state.${k}`, 'expected a string, number, boolean or null')\n }\n config.state = parsed\n }\n if (!isRecord(view) || !isRecord(view.regions)) fail('view.regions', 'expected an object')\n for (const [name, nodes] of Object.entries(view.regions)) {\n if (!/^[\\w-]+$/.test(name)) fail(`view.regions.${name}`, 'not a valid region name')\n if (!Array.isArray(nodes)) fail(`view.regions.${name}`, 'expected an array of nodes')\n config.view.regions[name] = nodes.map((n, i) => parseNode(n, `view.regions.${name}[${i}]`))\n }\n return config\n}\n\nfunction isTranslationRef(v: unknown): v is { $t: string } {\n return typeof v === 'object' && v !== null && '$t' in v\n}\n\n/** A JS literal for a state initial value. */\nfunction serializeInitial(value: string | number | boolean | null): string {\n return typeof value === 'string' ? `'${value.replace(/'/g, \"\\\\'\")}'` : String(value)\n}\n\nfunction serializeProp(value: unknown): string {\n // A JSX attribute string has no escapes, so anything holding a quote goes through an\n // expression instead.\n if (typeof value === 'string')\n return value.includes('\"') ? `{${JSON.stringify(value)}}` : `\"${value}\"`\n if (typeof value === 'number' || typeof value === 'boolean') return `{${value}}`\n if (value === null) return `{null}`\n if (isTranslationRef(value)) return `{${JSON.stringify(value.$t)}} {/* i18n: ${value.$t} */}`\n return `{${JSON.stringify(value)}}`\n}\n\nfunction renderChildren(\n children: ComponentNode['children'],\n indent: string,\n componentPropNames: string[],\n knownComponents: Set<string>,\n): string {\n if (children === undefined) return ''\n // Text with JSX syntax in it (`{`, `<`) would be parsed as code; emit it as a string literal.\n if (typeof children === 'string') {\n return /[{}<>]/.test(children) ? `{${JSON.stringify(children)}}` : children\n }\n if (isTranslationRef(children)) return `{/* i18n: ${children.$t} */}`\n if (Array.isArray(children)) {\n return children\n .map((child) =>\n renderNode(child as ComponentNode, indent + ' ', componentPropNames, knownComponents),\n )\n .join('\\n')\n }\n return ''\n}\n\nfunction renderNode(\n node: ComponentNode,\n indent: string,\n _parentPropNames: string[],\n knownComponents: Set<string>,\n): string {\n const compName = node.component\n knownComponents.add(compName)\n const propParts: string[] = []\n\n if (node.props) {\n for (const [k, v] of Object.entries(node.props)) {\n propParts.push(`${k}=${serializeProp(v)}`)\n }\n }\n\n if (node.bind) {\n for (const [k, ref] of Object.entries(node.bind)) {\n if (ref.startsWith('$state.')) {\n propParts.push(`${k}={${ref.slice('$state.'.length)}.value}`)\n } else {\n propParts.push(`${k}={data.${ref.replace(/^\\$data\\./, '')}}`)\n }\n }\n }\n\n if (node.events) {\n for (const [k, ref] of Object.entries(node.events)) {\n if (ref.startsWith('$state.set.')) {\n const key = ref.slice('$state.set.'.length)\n propParts.push(`${k}={(e) => (${key}.value = coerceValue(e))}`)\n } else if (ref.startsWith('$state.toggle.')) {\n const key = ref.slice('$state.toggle.'.length)\n propParts.push(`${k}={() => (${key}.value = !${key}.value)}`)\n } else {\n propParts.push(`${k}={actions.${ref.replace(/^\\$actions\\./, '')}}`)\n }\n }\n }\n\n const propsStr = propParts.length > 0 ? ' ' + propParts.join(' ') : ''\n const childrenStr =\n node.children !== undefined\n ? renderChildren(node.children, indent, [], knownComponents)\n : undefined\n\n if (childrenStr !== undefined && childrenStr !== '') {\n return `${indent}<${compName}${propsStr}>\\n${indent} ${childrenStr}\\n${indent}</${compName}>`\n }\n return `${indent}<${compName}${propsStr} />`\n}\n\nfunction collectBindAndEvents(nodes: ComponentNode[]): {\n boundProps: string[]\n actionProps: string[]\n} {\n const boundProps: string[] = []\n const actionProps: string[] = []\n function walk(node: ComponentNode) {\n if (node.bind) {\n for (const ref of Object.values(node.bind)) {\n if (ref.startsWith('$state.')) continue // view-local state, not a host-data prop\n const path = ref.replace(/^\\$data\\./, '')\n if (!boundProps.includes(path)) boundProps.push(path)\n }\n }\n if (node.events) {\n for (const ref of Object.values(node.events)) {\n if (ref.startsWith('$state.')) continue // state writer, not a host action\n const name = ref.replace(/^\\$actions\\./, '')\n if (!actionProps.includes(name)) actionProps.push(name)\n }\n }\n if (Array.isArray(node.children)) {\n node.children.forEach(walk)\n }\n }\n nodes.forEach(walk)\n return { boundProps, actionProps }\n}\n\n/** True if any node writes state via \"$state.set.*\" (needs the coerceValue helper). */\nfunction usesStateSetter(nodes: ComponentNode[]): boolean {\n const walk = (node: ComponentNode): boolean => {\n if (node.events && Object.values(node.events).some((r) => r.startsWith('$state.set.'))) {\n return true\n }\n return Array.isArray(node.children) ? node.children.some(walk) : false\n }\n return nodes.some(walk)\n}\n\n/**\n * Where components are imported from: `dir` is the copy-paste components directory (one\n * import per registry directory), `package` a prebuilt package such as `@cascivo/react`.\n */\nexport type ImportSource = { dir: string } | { package: string }\n\nfunction importLines(components: Set<string>, source: ImportSource): string {\n const names = [...components].sort()\n if ('package' in source) return `import { ${names.join(', ')} } from '${source.package}'`\n const byDirectory = new Map<string, string[]>()\n for (const name of names) {\n const directory = componentDirectory(name)\n byDirectory.set(directory, [...(byDirectory.get(directory) ?? []), name])\n }\n return [...byDirectory]\n .sort(([a], [b]) => a.localeCompare(b))\n .map(\n ([directory, members]) =>\n `import { ${members.join(', ')} } from '${source.dir}/${directory}'`,\n )\n .join('\\n')\n}\n\nexport function generateTsx(\n config: ViewConfig,\n _propMetas: Map<string, PropMeta[]>,\n source: ImportSource,\n): string {\n const knownComponents = new Set<string>()\n const allNodes = Object.values(config.view.regions).flat()\n const { boundProps, actionProps } = collectBindAndEvents(allNodes)\n const stateEntries = Object.entries(config.state ?? {})\n const hasState = stateEntries.length > 0\n const needsCoerce = usesStateSetter(allNodes)\n\n const regionBlocks = Object.entries(config.view.regions)\n .map(([regionName, nodes]) => {\n const rendered = nodes.map((n) => renderNode(n, ' ', [], knownComponents)).join('\\n')\n return ` <div className=\"region-${regionName}\">\\n${rendered}\\n </div>`\n })\n .join('\\n')\n\n const hasData = boundProps.length > 0\n const hasActions = actionProps.length > 0\n\n const dataParam = hasData\n ? `data: {\\n${boundProps.map((p) => ` ${p.replace(/\\./g, '_')}: unknown // TODO: type your data`).join('\\n')}\\n }`\n : ''\n\n const actionsParam = hasActions\n ? `actions: {\\n${actionProps.map((a) => ` ${a}: (...args: unknown[]) => unknown`).join('\\n')}\\n }`\n : ''\n\n const params = [dataParam, actionsParam].filter(Boolean).join(',\\n ')\n const propsType = params ? `{\\n ${params}\\n}` : '{}'\n\n const coreImport = hasState ? \"\\nimport { useSignal, useSignals } from '@cascivo/core'\" : ''\n const coerceHelper = needsCoerce\n ? `\n/** Unwrap a DOM event into the value a state setter should store. */\nfunction coerceValue(e: unknown) {\n const t = (e as { target?: { type?: string; checked?: boolean; value?: unknown } })?.target\n if (t) return t.type === 'checkbox' || t.type === 'radio' ? t.checked : t.value\n return e\n}\n`\n : ''\n const stateDecls = hasState\n ? ' useSignals()\\n' +\n stateEntries.map(([k, v]) => ` const ${k} = useSignal(${serializeInitial(v)})`).join('\\n') +\n '\\n'\n : ''\n\n return `import React from 'react'${coreImport}\n${importLines(knownComponents, source)}\n${coerceHelper}\ninterface PageProps ${propsType}\n\nexport function GeneratedPage({ ${hasData ? 'data, ' : ''}${hasActions ? 'actions' : ''} }: PageProps) {\n${stateDecls} return (\n <div className=\"cascivo-view\">\n${regionBlocks}\n </div>\n )\n}\n`\n}\n\nexport async function generate(args: string[], config: CascadeConfig): Promise<void> {\n const outArg = args.find((_, i) => args[i - 1] === '--out')\n const inputArg = args.find((a) => !a.startsWith('--'))\n const componentsDirArg = args.find((_, i) => args[i - 1] === '--components-dir')\n const fromArg = args.find((_, i) => args[i - 1] === '--from')\n\n if (!inputArg) {\n console.error(\n 'Usage: cascivo generate <config.json> [--out output.tsx] [--components-dir ./src/components/ui | --from @cascivo/react]',\n )\n process.exitCode = 1\n return\n }\n if (fromArg && componentsDirArg) {\n console.error('Pass --from or --components-dir, not both.')\n process.exitCode = 1\n return\n }\n\n const { readFileSync } = await import('node:fs')\n let viewConfig: ViewConfig\n try {\n const raw: unknown = JSON.parse(readFileSync(inputArg, 'utf-8'))\n viewConfig = parseViewConfig(raw)\n } catch (e) {\n console.error(`${inputArg}: ${e instanceof Error ? e.message : String(e)}`)\n process.exitCode = 1\n return\n }\n\n // Prop metas are not available from the CLI registry type, so this passes an empty map.\n // (There used to be a `fetchRegistry` call here whose result was discarded — a network\n // round-trip on every `cascivo generate` that fed nothing. `noUnusedLocals` surfaced it.)\n const propMetas = new Map<string, PropMeta[]>()\n\n const source: ImportSource = fromArg\n ? { package: fromArg }\n : { dir: componentsDirArg ?? config.outputDir ?? './src/components/ui' }\n const tsx = generateTsx(viewConfig, propMetas, source)\n\n const outPath = outArg ?? join(dirname(inputArg), `${basename(inputArg, '.json')}.tsx`)\n\n writeFileSync(outPath, tsx, 'utf-8')\n console.log(`Generated ${outPath}`)\n\n // Try to format with vp fmt or prettier\n try {\n const { spawnSync } = await import('node:child_process')\n const fmtResult = spawnSync('pnpm', ['exec', 'vp', 'fmt', outPath], {\n encoding: 'utf8',\n stdio: 'inherit',\n })\n if (fmtResult.status !== 0) {\n const prettyResult = spawnSync('npx', ['--yes', 'prettier', '--write', outPath], {\n encoding: 'utf8',\n stdio: 'inherit',\n })\n if (prettyResult.status !== 0) {\n console.log('(Note: formatter not found — output may need manual formatting)')\n }\n }\n } catch {\n // formatting is best-effort\n }\n}\n","import { createInterface } from 'node:readline/promises'\nimport { stdin, stdout } from 'node:process'\nimport { existsSync, readFileSync, writeFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport {\n DEFAULT_CONFIG,\n detectPackageManager,\n installHint,\n THEMES,\n type ThemeName,\n} from '../utils/config.js'\nimport { installPackages } from '../utils/exec.js'\nimport { writeFileSafe } from '../utils/fs.js'\nimport { flagValue, resolvePackageManagerFlag } from '../utils/args.js'\n\n/**\n * Everything an app needs to build with copied cascivo source: the runtime\n * packages plus the `@preact/signals-react` peer of `@cascivo/core` (installed\n * explicitly rather than relying on peer auto-linking, which yarn never does and\n * npm skips when its install crashes). `@cascivo/i18n`/`@cascivo/charts` are\n * added on demand by `cascivo add` when a component or chart declares them.\n */\nconst RUNTIME_DEPS = [\n '@cascivo/core',\n '@cascivo/tokens',\n '@cascivo/themes',\n '@preact/signals-react',\n]\n\n/** Dev-only: `cascivo` provides the `CascadeConfig` type the generated config imports. */\nconst DEV_DEPS = ['cascivo']\n\nasync function promptTheme(): Promise<ThemeName> {\n const rl = createInterface({ input: stdin, output: stdout })\n try {\n const answer = (await rl.question(`Theme? (${THEMES.join('/')}) [light]: `))\n .trim()\n .toLowerCase()\n return (THEMES as readonly string[]).includes(answer) ? (answer as ThemeName) : 'light'\n } finally {\n rl.close()\n }\n}\n\nfunction configFileContents(theme: ThemeName): string {\n return `import type { CascadeConfig } from 'cascivo'\n\nconst config: CascadeConfig = {\n registry: '${DEFAULT_CONFIG.registry}',\n outputDir: '${DEFAULT_CONFIG.outputDir}',\n theme: '${theme}',\n}\n\nexport default config\n`\n}\n\nconst ESLINT_CONFIGS = [\n 'eslint.config.js',\n 'eslint.config.mjs',\n 'eslint.config.cjs',\n 'eslint.config.ts',\n '.eslintrc',\n '.eslintrc.js',\n '.eslintrc.cjs',\n '.eslintrc.json',\n '.eslintrc.yml',\n '.eslintrc.yaml',\n]\n\n/**\n * Copied cascivo source can trip a strict host ESLint config on stylistic rules.\n * If the project has an ESLint config, point at the scoping recipe rather than\n * editing the adopter's config for them.\n */\nfunction hintEslintIfPresent(cwd: string): void {\n if (!ESLINT_CONFIGS.some((f) => existsSync(join(cwd, f)))) return\n console.log('\\nESLint: copied cascivo source may trip a strict host config on stylistic rules.')\n console.log(' Scope them off your components dir — see docs/USING-WITH-STRICT-ESLINT.md')\n}\n\n/**\n * Write dependency entries into `package.json` so a failed install still leaves a\n * DECLARATIVE-complete project, one `install` away from working.\n *\n * The reported failure: one unrelated bad version range elsewhere in the adopter's\n * `package.json` made `pnpm add` exit non-zero. cascivo had already written\n * `cascivo.config.ts`, so the project claimed to be cascivo-configured with none of the\n * runtime present, and the printed advice (\"install them yourself\") was the same command\n * that had just failed. Recording the dependencies is the difference between \"recoverable\n * with one command\" and \"figure out what was supposed to be here\".\n *\n * Never overwrites an entry that already exists — the app's own pin wins.\n */\nfunction recordDependencies(cwd: string, packages: string[], opts: { dev: boolean }): string[] {\n const pkgPath = join(cwd, 'package.json')\n if (!existsSync(pkgPath)) return []\n let pkg: Record<string, unknown>\n try {\n pkg = JSON.parse(readFileSync(pkgPath, 'utf8')) as Record<string, unknown>\n } catch {\n return []\n }\n const field = opts.dev ? 'devDependencies' : 'dependencies'\n const deps = (pkg[field] ??= {}) as Record<string, string>\n const added: string[] = []\n for (const name of packages) {\n if (deps[name] !== undefined) continue\n deps[name] = 'latest'\n added.push(name)\n }\n if (added.length === 0) return []\n writeFileSync(pkgPath, `${JSON.stringify(pkg, null, 2)}\\n`, 'utf8')\n return added\n}\n\n/** Formatter ignore files, in the order a project is likely to use them. */\nconst FORMATTER_IGNORES = [\n {\n config: ['.prettierrc', '.prettierrc.json', '.prettierrc.js', 'prettier.config.js'],\n ignore: '.prettierignore',\n },\n { config: ['.oxfmtrc', '.oxfmtrc.json'], ignore: '.oxfmtignore' },\n] as const\n\n/**\n * Exclude the vendored components dir from the project's formatter.\n *\n * Owning the code means your formatter reformats it, and then `cascivo update` reports drift\n * on files you never touched. This ACTS rather than hints: the ESLint equivalent below only\n * prints a pointer, and an adopter ran `prettier --write .` before ever reading it.\n *\n * Idempotent, and never rewrites an existing line.\n */\nfunction ensureFormatterIgnore(cwd: string, outputDir: string): void {\n const line = `${outputDir.replace(/\\/+$/, '')}/`\n for (const { config, ignore } of FORMATTER_IGNORES) {\n const hasFormatter =\n config.some((f) => existsSync(join(cwd, f))) || hasPrettierKeyInPackageJson(cwd, ignore)\n if (!hasFormatter) continue\n\n const path = join(cwd, ignore)\n const current = existsSync(path) ? readFileSync(path, 'utf8') : ''\n if (current.split('\\n').some((l) => l.trim() === line)) continue\n\n const banner = '# cascivo: vendored component source — you own it, so do not reformat it\\n'\n const next =\n current === '' ? banner + line + '\\n' : `${current.replace(/\\n*$/, '\\n')}\\n${banner}${line}\\n`\n writeFileSync(path, next, 'utf8')\n console.log(\n `\\nAdded \"${line}\" to ${ignore} (so your formatter does not rewrite copied source).`,\n )\n }\n}\n\n/** `prettier` key in package.json counts as a Prettier config — only relevant to .prettierignore. */\nfunction hasPrettierKeyInPackageJson(cwd: string, ignore: string): boolean {\n if (ignore !== '.prettierignore') return false\n const pkgPath = join(cwd, 'package.json')\n if (!existsSync(pkgPath)) return false\n try {\n return 'prettier' in (JSON.parse(readFileSync(pkgPath, 'utf8')) as Record<string, unknown>)\n } catch {\n return false\n }\n}\n\nconst ASTRO_CONFIG_FILES = [\n 'astro.config.mjs',\n 'astro.config.ts',\n 'astro.config.js',\n 'astro.config.mts',\n]\n\n/** Astro prerenders in its own Vite environment, so the generic steps above are not enough. */\nfunction printAstroNextSteps(cwd: string): void {\n if (!ASTRO_CONFIG_FILES.some((f) => existsSync(join(cwd, f)))) return\n console.log('\\nAstro detected. Next steps:')\n console.log(\n ' npx astro add @cascivo/astro # layer order, theme and no-flash script, zero config',\n )\n console.log(' Compose compound components (Tabs, Accordion, Popover…) inside one .tsx island:')\n console.log(\n ' Astro renders each .astro child separately, so React context cannot reach their parts.',\n )\n console.log(' Hydrate only the interactive islands: client:visible or client:load on those,')\n console.log(' and leave static pieces without a client: directive.')\n}\n\n/** The \"here's everything you need\" summary, printed once at the end of init. */\nfunction printDependencySummary(): void {\n console.log('\\nDependencies')\n console.log(` runtime: ${RUNTIME_DEPS.join(' ')}`)\n console.log(` dev: ${DEV_DEPS.join(' ')} (types for cascivo.config.ts)`)\n console.log(\n ' on demand: @cascivo/i18n, @cascivo/charts — added by `cascivo add` when a component or chart needs them',\n )\n}\n\nexport async function init(args: string[] = [], cwd: string = process.cwd()): Promise<void> {\n const yes = args.includes('--yes') || args.includes('-y')\n const noInstall = args.includes('--no-install')\n const themeArg = flagValue(args, 'theme')?.toLowerCase()\n\n if (themeArg !== undefined && !(THEMES as readonly string[]).includes(themeArg)) {\n console.error(`Unknown theme \"${themeArg}\". Available: ${THEMES.join(', ')}`)\n process.exitCode = 1\n return\n }\n\n const pmFlag = resolvePackageManagerFlag(args)\n if ('error' in pmFlag) {\n console.error(pmFlag.error)\n process.exitCode = 1\n return\n }\n const pm = detectPackageManager(cwd, pmFlag.pm ? { override: pmFlag.pm } : {})\n\n // Prompt only when interactive: --yes, a valid --theme, or a non-TTY stdin\n // (CI, agents, pipes) all take the default without blocking.\n const interactive = themeArg === undefined && !yes && stdin.isTTY\n const theme: ThemeName = (themeArg as ThemeName) ?? (interactive ? await promptTheme() : 'light')\n\n // Write the config before installing so a failed install can never leave a\n // half-initialized project (the report's npm-in-pnpm crash left exactly this).\n const configPath = join(cwd, 'cascivo.config.ts')\n await writeFileSafe(configPath, configFileContents(theme))\n console.log(`\\nCreated cascivo.config.ts (theme: ${theme})`)\n\n if (noInstall) {\n console.log('\\nSkipped install (--no-install). Install the dependencies yourself:')\n console.log(` ${installHint(pm, RUNTIME_DEPS)}`)\n console.log(` ${installHint(pm, DEV_DEPS, { dev: true })}`)\n } else {\n const runtimeOk = installPackages(RUNTIME_DEPS, cwd, { pm })\n const devOk = installPackages(DEV_DEPS, cwd, { pm, dev: true })\n if (!runtimeOk || !devOk) {\n // Never leave a project \"configured but not installed\". Record what it needs, say\n // plainly what state it is in, and give a command that is not the one that just failed.\n const recorded = [\n ...(runtimeOk ? [] : recordDependencies(cwd, RUNTIME_DEPS, { dev: false })),\n ...(devOk ? [] : recordDependencies(cwd, DEV_DEPS, { dev: true })),\n ]\n console.error(\n '\\nInstall failed — cascivo.config.ts was written but the packages are not installed.',\n )\n if (recorded.length > 0) {\n console.error(\n `Wrote ${recorded.length} dependency entries to package.json: ${recorded.join(', ')}`,\n )\n console.error(`Recover with:\\n ${pm} install`)\n } else {\n console.error(\n `Recover with:\\n ${installHint(pm, RUNTIME_DEPS)}\\n ${installHint(pm, DEV_DEPS, { dev: true })}`,\n )\n }\n process.exitCode = 1\n }\n }\n\n // The COMPLETE stylesheet wiring, in import order. Printing only the theme line left an\n // adopter to discover the tokens sheet by debugging a grayscale app, and the charts sheet\n // by shipping a chart whose screen-reader data table rendered visibly.\n console.log('\\nStylesheets — import these once, in this order, in your entry file:')\n console.log(\n ` import '@cascivo/tokens' // primitive tokens — every --cascivo-* value`,\n )\n console.log(\n ` import '@cascivo/themes/${theme}.css'${' '.repeat(Math.max(1, 16 - theme.length))}// the ${theme} theme's semantic values`,\n )\n console.log(\n ` // …then your component CSS (\\`cascivo add\\` writes .module.css beside each component)`,\n )\n console.log('\\nThen set the theme on your root element:')\n console.log(` <html data-theme=\"${theme}\">`)\n console.log('\\nSwitching themes at runtime? Use a bundle instead of the single theme:')\n console.log(\" import '@cascivo/themes/light-dark.css' // light + dark — the common case\")\n console.log(\" import '@cascivo/themes/all.css' // all twelve themes\")\n console.log(\" import { ThemeProvider } from '@cascivo/core'\")\n // The single most likely first-day bug, and it has no error message: a component that\n // reads `signal.value` in render never re-renders without this, so handlers fire and the\n // UI just sits there. Consumer apps run no signals transform, so it is never automatic.\n console.log('\\nIn YOUR components, when you read a signal during render:')\n console.log(\" import { useSignals } from '@cascivo/core'\")\n console.log(' function MyComponent() {')\n console.log(' useSignals() // ← first statement, or the component never re-renders')\n console.log(' return <span>{count.value}</span>')\n console.log(' }')\n console.log('\\nAdding a chart later? Charts ship as an npm package with their own stylesheet:')\n console.log(\" import '@cascivo/charts/styles.css' // `cascivo add <chart>` reminds you\")\n\n printDependencySummary()\n ensureFormatterIgnore(cwd, DEFAULT_CONFIG.outputDir)\n hintEslintIfPresent(cwd)\n printAstroNextSteps(cwd)\n\n // The version spread (`@cascivo/react@0.18.x` next to `@cascivo/platform@0.0.x`) is first\n // seen HERE, in the install list this command just printed — not 249 lines into a guide.\n // A 2026-08-21 reporter flagged that it reads as \"half of this is pre-alpha\" and that the\n // answer, while documented, was only reachable if you already knew to look for it.\n console.log('\\nPackages version independently (changesets), so a low number means fewer')\n console.log('releases, not less finished. Pin exact versions, and before upgrading run:')\n console.log(' cascivo doctor --drift # reads breaking-changes.json, reports API drift')\n\n console.log('\\nAdd components with: cascivo add <name>')\n}\n","import { existsSync } from 'node:fs'\nimport { join } from 'node:path'\nimport type { CascadeConfig } from '../utils/config.js'\nimport { fetchRegistry, type RegistryComponent } from '../utils/registry.js'\n\nexport interface ListOptions {\n installed?: boolean\n}\n\nconst TYPE_LABELS: Record<string, string> = {\n component: 'Components',\n layout: 'Layouts (copy-paste)',\n block: 'Blocks (copy-paste)',\n section: 'Sections (copy-paste)',\n chart: 'Charts (npm: @cascivo/charts)',\n flow: 'Flow (npm: @cascivo/flow)',\n editor: 'Editor (npm: @cascivo/editor)',\n}\n\n/**\n * Deprecation marker for the listing.\n *\n * Shown at DISCOVERY time on purpose. `overflow-menu` carried a `@deprecated` JSDoc in its\n * source for months, which an adopter only meets after they have already vendored the file —\n * and it pointed at an import path that cannot resolve on either install path.\n */\nexport function deprecationSuffix(c: RegistryComponent): string {\n return c.deprecated ? ` ⚠ deprecated → ${c.deprecated.replacement}` : ''\n}\n\n/** Render a group of entries as an aligned text table (no section header). */\nfunction formatGroup(entries: RegistryComponent[]): string {\n const rows = entries.map(\n (c) => [c.name, c.category, c.description + deprecationSuffix(c)] as const,\n )\n const headers = ['Name', 'Category', 'Description'] as const\n const widths = headers.map((h, i) => Math.max(h.length, ...rows.map((r) => (r[i] ?? '').length)))\n\n const line = (cells: readonly string[]) =>\n cells\n .map((cell, i) => cell.padEnd(widths[i] ?? cell.length))\n .join(' ')\n .trimEnd()\n\n const sep = widths.map((w) => '-'.repeat(w)).join(' ')\n return [line(headers), sep, ...rows.map(line)].join('\\n')\n}\n\n/** Render the component list as an aligned text table, grouped by type. */\nexport function formatList(components: RegistryComponent[]): string {\n if (components.length === 0) return 'No components found.'\n\n // Determine whether any entry has an explicit type — if not, render flat.\n const hasTypes = components.some((c) => c.type !== undefined)\n if (!hasTypes) return formatGroup(components)\n\n // Group by type, preserving insertion order of first occurrence.\n const groups = new Map<string, RegistryComponent[]>()\n for (const c of components) {\n const key = c.type ?? 'component'\n if (!groups.has(key)) groups.set(key, [])\n groups.get(key)!.push(c)\n }\n\n const sections: string[] = []\n for (const [key, entries] of groups) {\n const label = TYPE_LABELS[key] ?? key\n sections.push(`${label}\\n${formatGroup(entries)}`)\n }\n return sections.join('\\n\\n')\n}\n\nexport async function list(config: CascadeConfig, options: ListOptions = {}): Promise<void> {\n const registry = await fetchRegistry(config.registry)\n let components = registry.components\n\n if (options.installed) {\n components = components.filter((c) => {\n const outputName = c.name.includes('/') ? c.name.split('/').pop()! : c.name\n return existsSync(join(process.cwd(), config.outputDir, outputName))\n })\n }\n\n console.log(formatList(components))\n console.log(\n '\\nTip: install any entry by its bare name — `cascivo add flex` resolves to ' +\n '`layout/flex`. Layout primitives (Flex, Grid, AutoGrid, Columns, Spacer, ' +\n 'Center) replace inline-style layout; see docs/cookbooks/layout-and-spacing.md.',\n )\n}\n","import { existsSync } from 'node:fs'\nimport { readFile } from 'node:fs/promises'\nimport { resolve, dirname } from 'node:path'\nimport {\n buildRegistry,\n validateIndex,\n parseLegacyRegistry,\n isTemplateItem,\n validateTemplate,\n type RegistryIndex,\n} from '@cascivo/registry'\n\n/**\n * Validate every template item in an index: each must pass `validateTemplate`,\n * and any bare `registryDependencies` not present in the same index produce a\n * warning (they are expected to resolve from another registry at install time).\n * Returns `{ errors, warnings }`.\n */\nexport function validateTemplates(index: RegistryIndex): { errors: string[]; warnings: string[] } {\n const errors: string[] = []\n const warnings: string[] = []\n const localNames = new Set(index.items.map((i) => i.name))\n\n for (const item of index.items) {\n if (!isTemplateItem(item)) continue\n for (const e of validateTemplate(item)) errors.push(`template \"${item.name}\": ${e}`)\n for (const dep of item.registryDependencies ?? []) {\n const isCrossRegistry = dep.includes('/') || dep.startsWith('@') || dep.startsWith('http')\n if (!isCrossRegistry && !localNames.has(dep)) {\n warnings.push(\n `template \"${item.name}\": component \"${dep}\" is not in this index — it must resolve from another registry at install time`,\n )\n }\n }\n }\n\n return { errors, warnings }\n}\n\nexport async function registryBuild(args: string[]): Promise<void> {\n let inFile = 'cascade-registry.json'\n let outDir = 'public/r'\n\n for (let i = 0; i < args.length; i++) {\n if (args[i] === '--in' && args[i + 1]) {\n inFile = args[i + 1]!\n i++\n } else if (args[i] === '--out' && args[i + 1]) {\n outDir = args[i + 1]!\n i++\n }\n }\n\n const inPath = resolve(inFile)\n if (!existsSync(inPath)) {\n console.error(`cascade registry build: file not found: ${inPath}`)\n process.exitCode = 1\n return\n }\n\n const raw = JSON.parse(await readFile(inPath, 'utf8')) as unknown\n const indexBase = dirname(inPath)\n void indexBase\n\n let index = (() => {\n if (\n typeof raw === 'object' &&\n raw !== null &&\n (raw as Record<string, unknown>)['schemaVersion'] === 2\n ) {\n return raw\n }\n return parseLegacyRegistry(raw)\n })()\n\n const result = validateIndex(index)\n if (result.warnings.length > 0) {\n for (const w of result.warnings) console.warn(`warn: ${w}`)\n }\n if (!result.ok) {\n for (const e of result.errors) console.error(`error: ${e}`)\n process.exitCode = 1\n return\n }\n\n const templateResult = validateTemplates(index as RegistryIndex)\n for (const w of templateResult.warnings) console.warn(`warn: ${w}`)\n if (templateResult.errors.length > 0) {\n for (const e of templateResult.errors) console.error(`error: ${e}`)\n process.exitCode = 1\n return\n }\n\n const outPath = resolve(outDir)\n await buildRegistry(index as Parameters<typeof buildRegistry>[0], outPath)\n console.log(`cascade registry build: wrote static output to ${outPath}`)\n}\n","import type { CascadeConfig } from '../utils/config.js'\nimport { fetchRegistry } from '../utils/registry.js'\nimport { fetchJson } from '../utils/http.js'\nimport { validateItem } from '@cascivo/registry'\nimport type { RegistryItem } from '@cascivo/registry'\n\ninterface SearchResult {\n name: string\n version: string\n description: string\n registry?: string\n}\n\nfunction matchesQuery(item: RegistryItem, query: string): boolean {\n const q = query.toLowerCase()\n return (\n item.name.toLowerCase().includes(q) ||\n item.description.toLowerCase().includes(q) ||\n item.tags.some((t) => t.toLowerCase().includes(q))\n )\n}\n\nexport async function search(args: string[], config: CascadeConfig): Promise<void> {\n const nsFlag = args.indexOf('--registry')\n const registryFilter = nsFlag !== -1 ? args[nsFlag + 1] : undefined\n const queryParts = args.filter((a, i) => a !== '--registry' && args[i - 1] !== '--registry')\n const query = queryParts.join(' ').trim()\n\n if (!query) {\n console.error('Usage: cascivo search <query> [--registry @ns]')\n return\n }\n\n const results: SearchResult[] = []\n\n if (!registryFilter) {\n // Search default registry\n const registry = await fetchRegistry(config.registry)\n for (const c of registry.components) {\n const item = c as unknown as RegistryItem\n if (matchesQuery(item, query)) {\n results.push({ name: c.name, version: c.version, description: c.description })\n }\n }\n }\n\n // Search configured namespace registries\n const registries = config.registries ?? {}\n for (const [ns, nsCfg] of Object.entries(registries)) {\n if (registryFilter && ns !== registryFilter) continue\n try {\n const template = typeof nsCfg === 'string' ? nsCfg : nsCfg.url\n const indexUrl = template.replace(/{name}[^$]*$/, '').replace(/\\/$/, '') + '/registry.json'\n const raw: unknown = await fetchJson(indexUrl)\n const entries =\n typeof raw === 'object' && raw !== null && Array.isArray((raw as { items?: unknown }).items)\n ? ((raw as { items: unknown[] }).items ?? [])\n : []\n // Search is read-only and lists many registries at once, so one malformed\n // entry skips rather than failing the whole query.\n for (const entry of entries) {\n if (!validateItem(entry).ok) continue\n const item = entry as RegistryItem\n if (matchesQuery(item, query)) {\n results.push({\n name: `${ns}/${item.name}`,\n version: item.version,\n description: item.description,\n registry: ns,\n })\n }\n }\n } catch {\n console.warn(` [warn] Could not search ${ns} registry`)\n }\n }\n\n if (results.length === 0) {\n console.log('No results found.')\n return\n }\n\n for (const r of results) {\n const reg = r.registry ? ` (${r.registry})` : ''\n console.log(`${r.name}@${r.version}${reg} — ${r.description}`)\n }\n}\n","export type FontFamily = 'system' | 'geometric' | 'humanist' | 'transitional' | 'mono'\n\nexport const RADIUS_STOPS = [0, 0.25, 0.375, 0.5, 0.75, 1.5] as const\nexport type RadiusStop = (typeof RADIUS_STOPS)[number]\n\nexport const RADIUS_LABELS: Record<RadiusStop, string> = {\n 0: 'none',\n 0.25: 'sm',\n 0.375: 'md',\n 0.5: 'lg',\n 0.75: 'xl',\n 1.5: 'pill',\n}\n\nexport type ThemeConfig = {\n baseMode: 'light' | 'dark'\n accentHue: number\n accentChroma: number\n radiusBase: RadiusStop\n fontFamily: FontFamily\n presetId: string | null\n}\n\nexport const DEFAULT_CONFIG: ThemeConfig = {\n baseMode: 'light',\n accentHue: 250,\n accentChroma: 0.2,\n radiusBase: 0.375,\n fontFamily: 'system',\n presetId: 'light',\n}\n","import { DEFAULT_CONFIG, type ThemeConfig } from './config.js'\n\n/** Encode a theme config as a URL-safe base64 string (shared by the /create URL\n * hash and the CLI `--from` handoff, so the two never drift). */\nexport function configToHash(config: ThemeConfig): string {\n const json = JSON.stringify(config)\n return btoa(json).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')\n}\n\n/** Decode a hash produced by {@link configToHash}. Returns null on malformed\n * input; unknown/missing fields fall back to {@link DEFAULT_CONFIG}. */\nexport function hashToConfig(hash: string): ThemeConfig | null {\n if (!hash) return null\n try {\n const base64 = hash.replace(/-/g, '+').replace(/_/g, '/')\n const json = atob(base64)\n const parsed = JSON.parse(json) as Partial<ThemeConfig>\n return {\n baseMode: parsed.baseMode === 'dark' ? 'dark' : 'light',\n accentHue: typeof parsed.accentHue === 'number' ? parsed.accentHue : DEFAULT_CONFIG.accentHue,\n accentChroma:\n typeof parsed.accentChroma === 'number' ? parsed.accentChroma : DEFAULT_CONFIG.accentChroma,\n radiusBase: (typeof parsed.radiusBase === 'number'\n ? parsed.radiusBase\n : DEFAULT_CONFIG.radiusBase) as ThemeConfig['radiusBase'],\n fontFamily: parsed.fontFamily ?? DEFAULT_CONFIG.fontFamily,\n presetId: parsed.presetId ?? null,\n }\n } catch {\n return null\n }\n}\n","import type { ThemeConfig } from './config.js'\n\nconst FONT_STACKS: Record<string, string> = {\n geometric: \"'Futura', 'Century Gothic', 'Trebuchet MS', ui-sans-serif, sans-serif\",\n humanist: \"'Gill Sans', 'Trebuchet MS', 'Calibri', ui-sans-serif, sans-serif\",\n transitional: \"'Optima', 'Candara', 'Palatino Linotype', ui-sans-serif, sans-serif\",\n mono: \"ui-monospace, SFMono-Regular, 'SF Mono', Menlo, Consolas, monospace\",\n}\n\n// Resolved concrete values from packages/themes/src/light.css + primitives\nconst BASE_LIGHT = `\n color-scheme: light;\n --cascivo-color-background: oklch(1 0 0);\n --cascivo-color-surface: oklch(0.985 0.002 264);\n --cascivo-color-surface-2: oklch(0.967 0.003 264);\n --cascivo-color-bg: var(--cascivo-color-background);\n --cascivo-color-bg-subtle: var(--cascivo-color-surface);\n --cascivo-color-surface-raised: var(--cascivo-color-surface);\n --cascivo-color-surface-overlay: var(--cascivo-color-background);\n --cascivo-color-border: oklch(0.928 0.006 264);\n --cascivo-color-border-strong: oklch(0.872 0.008 264);\n --cascivo-border-subtle: oklch(0.928 0.006 264);\n --cascivo-border-default: oklch(0.872 0.008 264);\n --cascivo-border-strong: oklch(0.707 0.015 264);\n --cascivo-color-foreground: oklch(0.145 0.005 264);\n --cascivo-color-foreground-muted: oklch(0.554 0.018 264);\n --cascivo-color-text: var(--cascivo-color-foreground);\n --cascivo-color-text-subtle: oklch(0.446 0.018 264);\n --cascivo-color-text-muted: oklch(0.707 0.015 264);\n --cascivo-color-text-on-accent: oklch(1 0 0);\n --cascivo-color-text-on-destructive: oklch(1 0 0);\n --cascivo-color-primary: oklch(0.205 0 0);\n --cascivo-color-primary-fg: oklch(0.985 0 0);\n --cascivo-color-primary-hover: oklch(0.27 0 0);\n --cascivo-color-primary-active: oklch(0.32 0 0);\n --cascivo-color-active-bg: oklch(0.145 0.005 264 / 6%);\n --cascivo-color-destructive: oklch(0.54 0.188 22);\n --cascivo-color-destructive-hover: oklch(0.448 0.17 22);\n --cascivo-color-destructive-subtle: oklch(0.971 0.013 22);\n --cascivo-color-error: oklch(0.628 0.188 22);\n --cascivo-color-warning: oklch(0.768 0.145 75);\n --cascivo-color-success: oklch(0.648 0.15 145);\n --cascivo-color-success-subtle: oklch(0.982 0.018 145);\n --cascivo-color-warning-subtle: oklch(0.98 0.02 75);\n --cascivo-color-info: oklch(0.546 0.224 250);\n --cascivo-color-info-subtle: oklch(0.97 0.025 250);\n --cascivo-color-success-foreground: oklch(0.45 0.14 145);\n --cascivo-color-warning-foreground: oklch(0.5 0.14 75);\n --cascivo-color-destructive-foreground: oklch(0.448 0.17 22);\n --cascivo-color-info-foreground: oklch(0.45 0.19 250);\n --cascivo-shadow-xs: 0 1px 2px oklch(0 0 0 / 0.05);\n --cascivo-shadow-sm: 0 1px 3px oklch(0 0 0 / 0.07), 0 1px 2px oklch(0 0 0 / 0.04);\n --cascivo-shadow-md: 0 2px 8px oklch(0 0 0 / 0.07), 0 1px 2px oklch(0 0 0 / 0.04);\n --cascivo-shadow-overlay: 0 4px 32px oklch(0 0 0 / 0.16), 0 0 0 1px oklch(0 0 0 / 0.04);\n --cascivo-shadow-lg: var(--cascivo-shadow-overlay);\n --cascivo-ring-width: 2px;\n --cascivo-ring-offset: 0px;\n --cascivo-ring-color: color-mix(in oklch, var(--cascivo-color-accent) 55%, transparent);\n --cascivo-focus-ring: 0 0 0 var(--cascivo-ring-width) var(--cascivo-ring-color);`\n\n// Resolved concrete values from packages/themes/src/dark.css + primitives\nconst BASE_DARK = `\n color-scheme: dark;\n --cascivo-color-background: oklch(0.145 0.005 250);\n --cascivo-color-surface: oklch(0.185 0.007 250);\n --cascivo-color-surface-2: oklch(0.22 0.008 250);\n --cascivo-color-bg: var(--cascivo-color-background);\n --cascivo-color-bg-subtle: var(--cascivo-color-surface);\n --cascivo-color-surface-raised: var(--cascivo-color-surface-2);\n --cascivo-color-surface-overlay: var(--cascivo-color-surface);\n --cascivo-color-border: oklch(1 0 0 / 10%);\n --cascivo-color-border-strong: oklch(1 0 0 / 16%);\n --cascivo-border-subtle: oklch(1 0 0 / 0.06);\n --cascivo-border-default: oklch(1 0 0 / 0.1);\n --cascivo-border-strong: oklch(1 0 0 / 0.2);\n --cascivo-color-foreground: oklch(0.985 0.002 264);\n --cascivo-color-foreground-muted: oklch(0.707 0.015 264);\n --cascivo-color-text: var(--cascivo-color-foreground);\n --cascivo-color-text-subtle: oklch(0.707 0.015 264);\n --cascivo-color-text-muted: oklch(0.554 0.018 264);\n --cascivo-color-text-on-accent: oklch(0.145 0.005 250);\n --cascivo-color-text-on-destructive: oklch(1 0 0);\n --cascivo-color-primary: oklch(0.922 0 0);\n --cascivo-color-primary-fg: oklch(0.205 0 0);\n --cascivo-color-primary-hover: oklch(0.86 0 0);\n --cascivo-color-primary-active: oklch(0.8 0 0);\n --cascivo-color-active-bg: oklch(1 0 0 / 8%);\n --cascivo-color-destructive: oklch(0.72 0.16 22);\n --cascivo-color-destructive-hover: oklch(0.628 0.188 22);\n --cascivo-color-destructive-subtle: oklch(0.628 0.188 22 / 0.1);\n --cascivo-color-error: oklch(0.72 0.16 22);\n --cascivo-color-warning: oklch(0.82 0.13 75);\n --cascivo-color-success: oklch(0.72 0.13 145);\n --cascivo-color-success-subtle: oklch(0.72 0.13 145 / 0.1);\n --cascivo-color-warning-subtle: oklch(0.82 0.13 75 / 0.1);\n --cascivo-color-info: oklch(0.65 0.2 250);\n --cascivo-color-info-subtle: oklch(0.65 0.2 250 / 0.1);\n --cascivo-color-success-foreground: oklch(0.72 0.13 145);\n --cascivo-color-warning-foreground: oklch(0.82 0.13 75);\n --cascivo-color-destructive-foreground: oklch(0.85 0.12 22);\n --cascivo-color-info-foreground: oklch(0.75 0.16 250);\n --cascivo-shadow-xs: none;\n --cascivo-shadow-sm: 0 1px 3px oklch(0 0 0 / 0.4);\n --cascivo-shadow-md: 0 2px 8px oklch(0 0 0 / 0.45);\n --cascivo-shadow-overlay: 0 4px 32px oklch(0 0 0 / 0.6), 0 0 0 1px oklch(1 0 0 / 0.06);\n --cascivo-shadow-lg: var(--cascivo-shadow-overlay);\n --cascivo-ring-width: 2px;\n --cascivo-ring-offset: 0px;\n --cascivo-ring-color: color-mix(in oklch, var(--cascivo-color-accent) 65%, transparent);\n --cascivo-focus-ring: 0 0 0 var(--cascivo-ring-width) var(--cascivo-ring-color);`\n\nexport interface ConfigToCSSOptions {\n /** When true, inline the full base theme token set so the block is\n * self-contained (used by the live preview). The exported theme omits these —\n * users import the base theme themselves. */\n previewMode?: boolean\n /** The `data-theme` selector value the generated tokens attach to. */\n themeName?: string\n}\n\nexport function configToCSS(config: ThemeConfig, options: ConfigToCSSOptions = {}): string {\n const { previewMode = false, themeName = 'create-custom' } = options\n const light = config.baseMode === 'light'\n const h = config.accentHue\n const c = config.accentChroma\n\n const acc = (l: number, chroma = c) => `oklch(${l} ${chroma.toFixed(3)} ${h})`\n\n const lines: string[] = [\n `/* Add to your project CSS after importing the base theme: */`,\n `/* @import '@cascivo/themes/${config.baseMode}.css'; */`,\n `/* @import './theme.css'; */`,\n ``,\n `@layer cascivo.theme {`,\n ` [data-theme=\"${themeName}\"] {`,\n ]\n\n if (previewMode) {\n lines.push(light ? BASE_LIGHT : BASE_DARK)\n lines.push(``)\n }\n\n lines.push(\n ` /* ── Accent ─────────────────────────────────── */`,\n ` --cascivo-color-accent: ${acc(light ? 0.52 : 0.65)};`,\n ` --cascivo-color-accent-foreground: ${light ? 'oklch(1 0 0)' : `oklch(0.145 0.005 ${h})`};`,\n ` --cascivo-color-accent-hover: ${acc(light ? 0.45 : 0.707)};`,\n ` --cascivo-color-accent-active: ${acc(light ? 0.373 : 0.808, Math.min(c, 0.155))};`,\n ` --cascivo-color-accent-subtle: ${acc(light ? 0.97 : 0.623, 0.025)};`,\n ` --cascivo-color-accent-muted: ${acc(light ? 0.932 : 0.623, light ? 0.055 : c * 0.2)};`,\n ``,\n ` /* ── Radius ─────────────────────────────────── */`,\n ` --cascivo-radius-base: ${config.radiusBase}rem;`,\n ` --cascivo-radius-control: var(--cascivo-radius-base);`,\n ` --cascivo-radius-surface: calc(var(--cascivo-radius-base) * 1.66);`,\n ` --cascivo-radius-indicator: calc(var(--cascivo-radius-base) / 2);`,\n ` --cascivo-radius-full: 9999px;`,\n ` --cascivo-radius-component: var(--cascivo-radius-base);`,\n ` --cascivo-radius-button: var(--cascivo-radius-base);`,\n ` --cascivo-radius-input: var(--cascivo-radius-base);`,\n ` --cascivo-radius-card: calc(var(--cascivo-radius-base) * 1.66);`,\n ` --cascivo-radius-badge: var(--cascivo-radius-full);`,\n ` --cascivo-radius-modal: calc(var(--cascivo-radius-base) * 2);`,\n )\n\n if (config.fontFamily !== 'system') {\n lines.push(``)\n lines.push(` /* ── Font ───────────────────────────────────── */`)\n lines.push(\n ` --cascivo-font-sans: ${FONT_STACKS[config.fontFamily] ?? FONT_STACKS['humanist']};`,\n )\n }\n\n lines.push(` }`)\n lines.push(`}`)\n\n return lines.join('\\n')\n}\n","import { resolve } from 'node:path'\nimport { configToCSS, hashToConfig } from '@cascivo/theme-kit'\nimport { THEMES } from '../utils/config.js'\nimport { installPackages } from '../utils/exec.js'\nimport { writeFileSafe } from '../utils/fs.js'\n\nconst THEME_NAME_RE = /^[a-z][a-z0-9-]*$/\n\n/** Read a `--key value` or `--key=value` flag from an argv slice. */\nfunction flag(args: string[], key: string): string | undefined {\n const eq = args.find((a) => a.startsWith(`--${key}=`))\n if (eq) return eq.slice(key.length + 3)\n const idx = args.indexOf(`--${key}`)\n const next = idx !== -1 ? args[idx + 1] : undefined\n return next && !next.startsWith('--') ? next : undefined\n}\n\n/**\n * `cascivo theme create <name> --from <hash>` — turn a /create theme-builder\n * config (the `#hash` in the builder URL, or its \"Copy CLI command\" output) into\n * an owned `<name>.theme.css` in the project. Uses the same generator the builder\n * previews with, so the file matches the preview exactly.\n */\nasync function themeCreate(args: string[], cwd: string): Promise<void> {\n const name = args.find((a) => !a.startsWith('--'))\n const hash = flag(args, 'from')\n const dryRun = args.includes('--dry-run')\n\n if (!name || !hash) {\n console.error('Usage: cascivo theme create <name> --from <hash> [--out <path>]')\n console.error(\n 'Get <hash> from the theme builder at https://cascivo.com/create (Copy CLI command).',\n )\n return\n }\n if (!THEME_NAME_RE.test(name)) {\n console.error(`Invalid theme name \"${name}\". Use lowercase letters, digits, and dashes.`)\n return\n }\n\n const config = hashToConfig(hash)\n if (!config) {\n console.error('Could not decode --from. Copy the command again from the theme builder.')\n return\n }\n\n const css = configToCSS(config, { themeName: name })\n if (dryRun) {\n console.log(css)\n return\n }\n\n const outPath = resolve(cwd, flag(args, 'out') ?? `${name}.theme.css`)\n await writeFileSafe(outPath, css)\n\n console.log(`\\n✓ Wrote ${name}.theme.css`)\n console.log(`\\nImport the base theme and your overlay in your entry CSS:`)\n console.log(` @import '@cascivo/themes/${config.baseMode}.css';`)\n console.log(` @import './${name}.theme.css';`)\n console.log(`Then set it on a container:`)\n console.log(` <div data-theme=\"${name}\">…</div>`)\n}\n\nexport async function theme(args: string[]): Promise<void> {\n const [sub, name] = args\n\n if (sub === 'create') {\n await themeCreate(args.slice(1), process.cwd())\n return\n }\n\n if (sub !== 'add' || !name) {\n console.error(`Usage: cascivo theme add <${THEMES.join('|')}>`)\n console.error(` cascivo theme create <name> --from <hash>`)\n return\n }\n if (!(THEMES as readonly string[]).includes(name)) {\n console.error(`Unknown theme \"${name}\". Available: ${THEMES.join(', ')}`)\n return\n }\n\n installPackages(['@cascivo/themes'])\n\n console.log(`\\nImport the theme in your root CSS or entry file:`)\n console.log(` import '@cascivo/themes/${name}.css'`)\n console.log(`Then set it on a container:`)\n console.log(` <div data-theme=\"${name}\">…</div>`)\n}\n","/**\n * Minimal line-based diff (LCS) rendered in a unified-ish format. Zero deps —\n * good enough to preview what `cascade update` will change.\n */\nexport function diffLines(oldStr: string, newStr: string): string[] {\n const a = oldStr.split('\\n')\n const b = newStr.split('\\n')\n const n = a.length\n const m = b.length\n\n // LCS length table.\n const lcs: number[][] = Array.from({ length: n + 1 }, () =>\n Array.from({ length: m + 1 }, () => 0),\n )\n for (let i = n - 1; i >= 0; i--) {\n for (let j = m - 1; j >= 0; j--) {\n lcs[i]![j] =\n a[i] === b[j] ? lcs[i + 1]![j + 1]! + 1 : Math.max(lcs[i + 1]![j]!, lcs[i]![j + 1]!)\n }\n }\n\n const out: string[] = []\n let i = 0\n let j = 0\n while (i < n && j < m) {\n if (a[i] === b[j]) {\n out.push(` ${a[i]}`)\n i++\n j++\n } else if (lcs[i + 1]![j]! >= lcs[i]![j + 1]!) {\n out.push(`- ${a[i]}`)\n i++\n } else {\n out.push(`+ ${b[j]}`)\n j++\n }\n }\n while (i < n) out.push(`- ${a[i++]}`)\n while (j < m) out.push(`+ ${b[j++]}`)\n return out\n}\n\n/** True when the two strings differ. */\nexport function hasChanges(oldStr: string, newStr: string): boolean {\n return oldStr !== newStr\n}\n","import { createInterface } from 'node:readline/promises'\nimport { stdin, stdout } from 'node:process'\nimport { readFile } from 'node:fs/promises'\nimport { existsSync } from 'node:fs'\nimport type { CascadeConfig } from '../utils/config.js'\nimport { diffLines, hasChanges } from '../utils/diff.js'\nimport { readFileSafe, resolveOutputPath, writeFileSafe } from '../utils/fs.js'\nimport { fetchRegistry, fileName, findComponent } from '../utils/registry.js'\nimport { readLock, writeLock, updateLockEntry } from '../utils/lock.js'\nimport { fetchJson, fetchTextRetry } from '../utils/http.js'\nimport { merge } from '../utils/merge.js'\nimport { parseItem } from '@cascivo/registry'\nimport type { RegistryItem } from '@cascivo/registry'\n\nasync function confirm(question: string): Promise<boolean> {\n const rl = createInterface({ input: stdin, output: stdout })\n try {\n const answer = (await rl.question(`${question} (y/N): `)).trim().toLowerCase()\n return answer === 'y' || answer === 'yes'\n } finally {\n rl.close()\n }\n}\n\nexport async function update(\n name: string | undefined,\n config: CascadeConfig,\n opts: { check?: boolean; yes?: boolean } = {},\n): Promise<void> {\n if (opts.check) {\n return updateCheck(config)\n }\n\n if (!name) {\n console.error('Usage: cascivo update <component>')\n return\n }\n\n const lock = await readLock()\n const lockEntry = lock?.items[name]\n\n const registry = await fetchRegistry(config.registry)\n const entry = findComponent(registry, name)\n if (!entry) {\n console.error(`Component \"${name}\" not found in registry. Run \"cascivo list\".`)\n return\n }\n\n if (lockEntry) {\n // Three-way merge path\n const lockedVersion = lockEntry.version\n const registryBase = lockEntry.registry\n const baseItemUrl = `${registryBase}/r/${name}@${lockedVersion}.json`\n\n let baseItem: RegistryItem | null = null\n try {\n baseItem = parseItem(await fetchJson(baseItemUrl), baseItemUrl)\n } catch {\n console.warn(\n `Warning: could not fetch base version ${lockedVersion} from ${baseItemUrl}. Falling back to two-way diff.`,\n )\n }\n\n if (baseItem) {\n await threeWayUpdate(name, entry, baseItem, config, opts)\n } else {\n await twoWayUpdate(name, entry, config, opts)\n }\n } else {\n console.warn(\n `Warning: \"${name}\" has no lock entry. Falling back to two-way diff update (pre-v11 install).`,\n )\n await twoWayUpdate(name, entry, config, opts)\n }\n}\n\nasync function threeWayUpdate(\n name: string,\n upstreamEntry: ReturnType<typeof findComponent>,\n baseItem: RegistryItem,\n config: CascadeConfig,\n opts: { yes?: boolean },\n): Promise<void> {\n if (!upstreamEntry) return\n const outputName = name.includes('/') ? name.split('/').pop()! : name\n const summaries: { file: string; result: 'clean' | 'conflict' | 'unchanged' }[] = []\n const pending: { dest: string; content: string; conflicts: number }[] = []\n\n for (const url of upstreamEntry.files) {\n const fname = fileName(url)\n const baseFile = baseItem.files.find((f) => fileName(f.url) === fname)\n const dest = resolveOutputPath(config.outputDir, outputName, fname)\n\n const upstream = await fetchTextRetry(url)\n const local = existsSync(dest) ? await readFile(dest, 'utf8') : ''\n const base = baseFile ? await fetchTextRetry(baseFile.url) : ''\n\n if (base === '' && local === '') {\n summaries.push({ file: fname, result: 'clean' })\n pending.push({ dest, content: upstream, conflicts: 0 })\n continue\n }\n\n const { text, conflicts } = merge(base, local, upstream)\n\n if (conflicts > 0) {\n summaries.push({ file: fname, result: 'conflict' })\n } else if (text === local) {\n summaries.push({ file: fname, result: 'unchanged' })\n continue\n } else {\n summaries.push({ file: fname, result: 'clean' })\n }\n pending.push({ dest, content: text, conflicts })\n }\n\n if (pending.length === 0) {\n console.log(`${name} is already up to date.`)\n return\n }\n\n for (const s of summaries) {\n const icon = s.result === 'conflict' ? '⚠' : s.result === 'clean' ? '✓' : '·'\n console.log(` ${icon} ${s.file} (${s.result})`)\n }\n\n const conflicted = pending.filter((p) => p.conflicts > 0)\n const shouldApply = opts.yes\n ? conflicted.length === 0 // --yes skips items with conflicts\n : await confirm(`\\nApply ${pending.length} change(s) to ${name}?`)\n\n if (shouldApply || opts.yes) {\n const lock = await readLock()\n let updatedLock = lock\n\n for (const { dest, content, conflicts } of pending) {\n if (opts.yes && conflicts > 0) {\n console.log(` skipped (conflicts): ${dest}`)\n continue\n }\n await writeFileSafe(dest, content)\n }\n\n if (lock && updatedLock) {\n const hasConflicts = conflicted.length > 0\n updatedLock = updateLockEntry(updatedLock, name, {\n ...lock.items[name]!,\n version: upstreamEntry.version,\n ...(hasConflicts ? { conflicted: true as const } : {}),\n })\n await writeLock(updatedLock)\n }\n\n console.log(`Updated ${name}.`)\n if (conflicted.length > 0) {\n console.log(`${conflicted.length} file(s) have conflict markers — resolve them manually.`)\n }\n } else {\n console.log('Aborted. No files changed.')\n }\n}\n\nasync function twoWayUpdate(\n name: string,\n entry: ReturnType<typeof findComponent>,\n config: CascadeConfig,\n opts: { yes?: boolean },\n): Promise<void> {\n if (!entry) return\n const pending: { path: string; content: string }[] = []\n\n for (const url of entry.files) {\n let latest: string\n try {\n latest = await fetchTextRetry(url)\n } catch (e) {\n console.error(e instanceof Error ? e.message : String(e))\n return\n }\n const dest = resolveOutputPath(config.outputDir, entry.name, fileName(url))\n const current = await readFileSafe(dest)\n\n if (current === null) {\n console.log(`New file: ${dest}`)\n pending.push({ path: dest, content: latest })\n } else if (hasChanges(current, latest)) {\n console.log(`\\n--- ${dest}`)\n console.log(diffLines(current, latest).join('\\n'))\n pending.push({ path: dest, content: latest })\n }\n }\n\n if (pending.length === 0) {\n console.log(`${name} is already up to date.`)\n return\n }\n\n const shouldApply = opts.yes || (await confirm(`\\nApply ${pending.length} change(s) to ${name}?`))\n\n if (shouldApply) {\n for (const { path, content } of pending) {\n await writeFileSafe(path, content)\n }\n console.log(`Updated ${name}.`)\n } else {\n console.log('Aborted. No files changed.')\n }\n}\n\nasync function updateCheck(config: CascadeConfig): Promise<void> {\n const lock = await readLock()\n if (!lock || Object.keys(lock.items).length === 0) {\n console.log('No installed components found in cascivo.lock.')\n return\n }\n\n const registry = await fetchRegistry(config.registry)\n let outdated = 0\n\n for (const [name, entry] of Object.entries(lock.items)) {\n const current = findComponent(registry, name)\n if (!current) continue\n // Content hashes are the accurate signal (they change with every source\n // edit); the version compare is the fallback for older registries.\n if (current.fileHashes && Object.keys(current.fileHashes).length > 0) {\n const lockByBase = new Map(\n Object.entries(entry.files).map(([dest, hash]) => [dest.split('/').pop()!, hash]),\n )\n const changed = Object.entries(current.fileHashes).filter(\n ([file, hash]) => lockByBase.get(file) !== hash,\n )\n if (changed.length > 0) {\n console.log(\n `${name}: ${changed.length} file(s) changed upstream (${entry.version} → ${current.version})`,\n )\n outdated++\n }\n } else if (current.version !== entry.version) {\n console.log(`${name}: ${entry.version} → ${current.version}`)\n outdated++\n }\n }\n\n if (outdated > 0) {\n console.log(`${outdated} component(s) outdated.`)\n process.exitCode = 1\n } else {\n console.log('All components up to date.')\n }\n}\n","import type { CascadeConfig } from '../utils/config.js'\nimport { parseAddress, resolveItemUrl } from '../utils/resolve.js'\nimport { fetchJson } from '../utils/http.js'\nimport { asTemplateMeta, isTemplateItem, parseItem, type RegistryItem } from '@cascivo/registry'\n\n/** Render an item's details as text. Pure, so it can be unit-tested. */\nexport function formatItem(item: RegistryItem): string {\n const lines: string[] = []\n lines.push(`\\n${item.name} v${item.version}`)\n lines.push(`Type: ${item.type}${item.category ? ` / ${item.category}` : ''}`)\n lines.push(item.description)\n if (item.author) lines.push(`Author: ${item.author}`)\n if (item.license) lines.push(`License: ${item.license}`)\n if (item.homepage) lines.push(`Homepage: ${item.homepage}`)\n\n if (item.install) {\n lines.push(`Distribution: npm package — pnpm add ${item.install}`)\n if (item.styles) lines.push(`Stylesheet: import '${item.styles}' (required)`)\n } else if (!isTemplateItem(item)) {\n lines.push(`Distribution: copy-paste — npx cascivo add ${item.name}`)\n }\n\n if (isTemplateItem(item)) {\n try {\n const meta = asTemplateMeta(item.meta)\n lines.push(`\\nTemplate: ${meta.intent}`)\n lines.push(`Framework: ${meta.framework}`)\n if (meta.demoUrl) lines.push(`Demo: ${meta.demoUrl}`)\n if (meta.pages?.length) {\n lines.push('Pages:')\n for (const p of meta.pages) lines.push(` ${p.name} → ${p.target}`)\n }\n } catch {\n // meta is malformed — base fields above are still useful.\n }\n }\n\n if (item.changelog?.length) {\n lines.push('\\nChangelog:')\n for (const c of item.changelog.slice(0, 5)) lines.push(` ${c.version}: ${c.note}`)\n }\n\n if (item.files?.length) {\n lines.push('\\nFiles:')\n for (const f of item.files) lines.push(` ${f.url}${f.target ? ` → ${f.target}` : ''}`)\n }\n\n if (item.dependencies?.length) lines.push(`\\nDependencies: ${item.dependencies.join(', ')}`)\n\n if (item.registryDependencies?.length) {\n const label = isTemplateItem(item) ? 'Components' : 'Registry dependencies'\n lines.push(`${label}: ${item.registryDependencies.join(', ')}`)\n }\n\n return lines.join('\\n')\n}\n\nexport async function view(args: string[], config: CascadeConfig): Promise<void> {\n const spec = args[0]\n if (!spec) {\n console.error('Usage: cascivo view <component-spec>')\n return\n }\n\n const addr = parseAddress(spec)\n const { url, headers, params } = await resolveItemUrl(addr, config)\n const fetchOpts: Parameters<typeof fetchJson>[1] = {}\n if (headers) fetchOpts.headers = headers\n if (params) fetchOpts.params = params\n const item = parseItem(await fetchJson(url, fetchOpts), url)\n\n console.log(formatItem(item))\n}\n","import { createRequire } from 'node:module'\nimport { argv } from 'node:process'\nimport { pathToFileURL } from 'node:url'\nimport { add } from './commands/add.js'\nimport { runDoctor } from './commands/doctor.js'\nimport { generate } from './commands/generate.js'\nimport { init } from './commands/init.js'\nimport { list } from './commands/list.js'\nimport { registryBuild } from './commands/registry.js'\nimport { search } from './commands/search.js'\nimport { theme } from './commands/theme.js'\nimport { update } from './commands/update.js'\nimport { view } from './commands/view.js'\nimport { loadConfig, THEMES } from './utils/config.js'\nimport { positionalArgs, resolvePackageManagerFlag } from './utils/args.js'\n\n// Read at runtime: this file lives one level below the package root both in\n// src/ (dev, tests) and in dist/ (published bundle), so ../package.json is\n// always the cascivo package manifest.\nexport const VERSION: string = (\n createRequire(import.meta.url)('../package.json') as { version: string }\n).version\n\nexport type { CascadeConfig, ThemeName } from './utils/config.js'\n\nconst HELP = `cascivo ${VERSION} — the CSS-native, signal-driven, AI-first design system\n\nUsage: cascivo <command> [options]\n\nCommands:\n create [name] Scaffold a new ready-to-run app (shell + nav + theme)\n (--template <spec>: start from a marketplace template)\n app add page \"<title>\" Add a page to the app (--block <name>); app add example <name>,\n app upgrade: change an app the way create would have made it\n init Set up cascivo in the current project\n add <component...> Add components or a template to your project\n list [--installed] List available components\n update [component] Update installed components (--check: list outdated)\n search <query> Search components across registries\n view <spec> View a component before installing\n theme <add|create> Install a first-party theme, or build a custom one from /create\n eject <component> Eject specific tokens into a scoped local override file\n generate <config.json> Generate TSX from a ViewConfig JSON file\n doctor [--ci] Check components for rule violations\n audit --ai <paths...> Audit AI-generated code against the cascivo contract\n mcp init Add the cascivo MCP server to your agent's config\n registry build Build a static registry from a cascivo-registry.json file\n template init <name> Scaffold a new template (source + manifest + registry entry)\n tokens import <file> Import external design tokens as cascivo overrides\n email lint <file...> Check rendered email HTML for client support and dead links\n\nRun \"cascivo <command> --help\" for details.`\n\nconst THEME_LIST = THEMES.join(' | ')\n\nconst COMMAND_HELP: Record<string, string> = {\n app: `Usage: cascivo app add page \"<title>\" [options]\n cascivo app add example <name>\n cascivo app upgrade\n\nChange an app made by \\`cascivo create\\` through its cascivo.app.json: add a page, add a\ncloudflare example, or regenerate it with this CLI's templates. The app is generated before and\nafter the change, and each file that changes is merged three ways: files you have not touched\nare replaced, your edits are kept, and a clash gets conflict markers (the command then exits\nnon-zero). The original files are rebuilt with the CLI version recorded in cascivo.app.json.\n\nOptions:\n --block <name> The registry block a new page renders (default: a page to build out)`,\n mcp: `Usage: cascivo mcp init [options]\n\nAdd the cascivo MCP server (npx -y @cascivo/mcp) to your coding agent's project config.\nOther servers in the file are kept; an existing cascivo entry is left as it is.\n\nOptions:\n --client <name> claude (default, .mcp.json) | cursor (.cursor/mcp.json)\n | vscode (.vscode/mcp.json)\n --dry-run Print the file instead of writing it\n\nExamples:\n npx cascivo mcp init\n npx cascivo mcp init --client cursor`,\n email: `Usage: cascivo email lint <file...> [options]\n\nCheck rendered email HTML against the Can I email support matrix — the same\nconformance lint @cascivo/email exposes as \\`lint()\\`, with the setup done for you —\nand for links that go nowhere (\\`checkLinks()\\`): empty, \\`#\\`, relative, an\nunreplaced {{merge tag}}, or a placeholder domain such as example.com.\n\nIt lints rendered HTML, not templates: render in your own build and pass the\noutput, or pipe it in.\n\nArguments:\n <file...> One or more rendered .html files, or \\`-\\` for stdin\n\nOptions:\n --data <file> Use a local copy of the matrix instead of fetching\n --refresh Re-fetch the matrix even if the cache is fresh\n --no-allowlist Report findings CASCIVO_ALLOW waives, too\n --check-links Also request every http(s) URL; one answering 4xx/5xx,\n or not at all within 10s, fails the command\n\nThe matrix is fetched from https://www.caniemail.com/api/data.json and cached for\na day. It is not bundled with @cascivo/email because it is ~483 KB of test data.\n\nExits non-zero when a floor client genuinely cannot support something, or a link\ncannot work. A caveat (partial support, a localhost or http: link) is worth knowing\nabout and never fails the command.\n\nExamples:\n cascivo email lint dist/emails/*.html\n node render.js | cascivo email lint -\n cascivo email lint dist/welcome.html --data caniemail.json\n cascivo email lint dist/emails/*.html --check-links`,\n\n create: `Usage: cascivo create [name] [options]\n\nScaffold a new ready-to-run app, pre-wired with the cascivo app shell, side\nnavigation, header, and a theme.\n\nOptions:\n --framework <name> react-vite (default), astro, or cloudflare (a client app and\n its API, deployed as one Cloudflare Worker)\n --runtime <name> preact (default) or react — for --framework cloudflare\n --example <name> board — a multiplayer page on a Durable Object (cloudflare only)\n agent — an AI assistant that answers with UI (cloudflare, React)\n notes — a local-first page that keeps edits offline (cloudflare)\n import — a CSV import on a Workflow, with live progress (cloudflare)\n files — uploads into R2 with progress and image previews (cloudflare)\n export — a report page downloadable as PDF/PNG via Browser Run (cloudflare)\n usage — API usage charts from Workers Analytics Engine (cloudflare)\n crud — a D1 table behind DataTable's server mode (cloudflare)\n live — an ops dashboard fed by a Queue, updating every second (cloudflare)\n voice — a voice assistant: Workers AI speech in and out (cloudflare)\n publish — publish views as pages, validated and stored in D1 (cloudflare)\n webhooks — signed GitHub deliveries, stored once, shown live (cloudflare)\n digest — the report as a PDF, emailed weekly on a Cron Trigger (cloudflare)\n search — help articles searched by meaning: Vectorize + Workers AI (cloudflare)\n checkout — sell a product with Stripe Checkout; orders and receipts (cloudflare)\n newsletter — double opt-in sign-up, issues sent through Amazon SES (cloudflare)\n social — post to Bluesky, Mastodon, LinkedIn, Threads and Buffer, now or\n scheduled, with images (cloudflare)\n --auth access Refuse every Worker request Cloudflare Access did not let\n through (cloudflare only)\n --auth email Accounts with emailed sign-in links; every API write needs a\n signed-in user (cloudflare only)\n --auth oauth Accounts with GitHub, Google and LinkedIn sign-in; every API\n write needs a signed-in user (cloudflare only).\n --auth email,oauth: both\n --template <spec> Start from a marketplace template (@ns/name or owner/repo/name)\n --from <file> Compile a blueprint (cascivo.app.json): name, framework, theme,\n pages [{ title, block? }], runtime, examples, auth. Each page\n renders its registry block. Replaces the other options.\n --workspace Put the app in a pnpm workspace: apps/web, packages/ui for your own\n components, Vite+ running every package's scripts, CI, a smoke test\n --theme <name> Theme to install (${THEME_LIST})\n --sections \"<a, b>\" Comma-separated nav section labels (one component each)\n --package-manager <pm> Package manager for README/next-steps (alias --pm; default: auto-detect)\n --yes, -y Accept defaults, never prompt`,\n init: `Usage: cascivo init [options]\n\nSet up cascivo in the current project: writes cascivo.config.ts and installs the\nruntime dependencies (@cascivo/core, @cascivo/tokens, @cascivo/themes, the\n@preact/signals-react peer) plus cascivo as a dev dependency for the config's types.\n\nOptions:\n --theme <name> Theme to configure (${THEME_LIST})\n --package-manager <pm> Force pnpm | yarn | npm | bun (alias --pm; default: auto-detect)\n --no-install Write files only; print the install commands to run yourself\n --yes, -y Accept defaults, never prompt (implied when stdin is not a TTY)`,\n add: `Usage: cascivo add <component...> [options]\n\nCopy component source (TSX + CSS module) from the registry into your project,\nresolving component dependencies. Also installs templates (@ns/name) and\nthird-party components (owner/repo/name).\n\nOptions:\n --dry-run Show what would be written without writing\n --package-manager <pm> Force pnpm | yarn | npm | bun (alias --pm; default: auto-detect)\n --no-install Don't install npm-distributed entries or deps; print the commands instead\n --yes, -y Skip confirmation prompts`,\n list: `Usage: cascivo list [options]\n\nList components available in the configured registry.\n\nOptions:\n --installed Only list components already installed in this project`,\n update: `Usage: cascivo update [component] [options]\n\nUpdate installed components to the current registry version. Without a\ncomponent argument, updates everything in the lockfile.\n\nOptions:\n --check List outdated components without writing\n --yes, -y Skip confirmation prompts`,\n search: `Usage: cascivo search <query> [options]\n\nSearch components across the configured registries.\n\nOptions:\n --registry <@ns> Restrict the search to one registry namespace`,\n view: `Usage: cascivo view <spec>\n\nPreview a component or template (files, dependencies, description) before\ninstalling. <spec> is a bare name, @ns/name, or owner/repo/name.`,\n theme: `Usage: cascivo theme add <name>\n cascivo theme create <name> --from <hash> [--out <path>]\n\nadd Install @cascivo/themes and print the import + data-theme wiring.\ncreate Turn a theme-builder config into an owned <name>.theme.css. Get <hash>\n from https://cascivo.com/create (\"Copy CLI command\"). --dry-run prints\n the CSS without writing.\n\nThemes: ${THEME_LIST}`,\n eject: `Usage: cascivo eject <component> [options]\n\nEject specific tokens into a scoped local override file so you can restyle a\ncomponent without forking it.\n\nOptions:\n --tokens <a,b> Comma-separated token names to eject (default: all)\n --scope <sel> CSS selector the overrides are scoped to\n --out <file> Output file path\n --dry-run Print the override file without writing`,\n generate: `Usage: cascivo generate <config.json> [options]\n\nGenerate TSX from a ViewConfig JSON file (see the MCP scaffold_view tool).\n\nOptions:\n --out <file> Output file (default: <config>.tsx beside the input)\n --components-dir <dir> Components import base (default: ./src/components/ui)\n --from <package> Import every component from one package instead, e.g. @cascivo/react`,\n doctor: `Usage: cascivo doctor [options]\n\nCheck components in this repo for cascivo rule violations (banned React hooks,\nhardcoded strings, missing @cascivo/react exports). In an adopter project (one\nwith a cascivo.config), also verifies the runtime dependencies copied source\nneeds — @cascivo/core, @cascivo/tokens, @cascivo/themes, and the\n@preact/signals-react peer — are declared in package.json.\n\nOptions:\n --ci Exit non-zero when violations or missing runtime deps are found\n --drift Compare installed components against the registry (copy-paste drift)`,\n audit: `Usage: cascivo audit --ai <paths...> [options]\n\nAudit AI-generated code against the cascivo contract: hard-coded values that\nshould be tokens, invented props, missing required props, raw strings where\ni18n is expected.\n\nOptions:\n --fix Rewrite unambiguous CSS literals to their token equivalents\n --json Machine-readable output\n --level <name> Minimum finding level to report (error | warn; default error)\n --contract <path> Use this audit-contract.json instead of the bundled one\n --verbose Report which contract source was used`,\n registry: `Usage: cascivo registry build [options]\n\nBuild a static registry (registry.json + file payloads) from a\ncascivo-registry.json manifest, ready to host on any static file server.\n\nOptions:\n --in <file> The registry manifest (default cascade-registry.json)\n --out <dir> Output directory (default public/r)`,\n template: `Usage: cascivo template init <name> [options]\n\nScaffold a new template: source, manifest, and registry entry.\n\nOptions:\n --category <name> Template category (e.g. dashboard)\n --framework <name> Target framework (default react-vite)\n --components <a,b> Registry components the template composes\n --repo <owner/repo> Repository the template will be hosted in`,\n tokens: `Usage: cascivo tokens import <file>\n\nImport external design tokens (W3C design-tokens JSON) as cascivo token\noverrides.`,\n}\n\nexport async function run(args: string[]): Promise<void> {\n const [command, ...rest] = args\n\n // Per-command help must short-circuit BEFORE any prompt, fetch, or install:\n // \"cascivo add --help\" must never try to install a component named --help.\n if (command !== undefined && (rest.includes('--help') || rest.includes('-h'))) {\n const commandHelp = COMMAND_HELP[command]\n if (commandHelp !== undefined) {\n console.log(commandHelp)\n return\n }\n }\n\n switch (command) {\n case 'create':\n // Lazy, like the other commands: its scaffold templates are most of the CLI's size.\n const { create } = await import('./commands/create.js')\n await create(rest)\n break\n case 'app': {\n const { app } = await import('./commands/app.js')\n await app(rest)\n break\n }\n case 'init':\n await init(rest)\n break\n case 'add': {\n const pmFlag = resolvePackageManagerFlag(rest)\n if ('error' in pmFlag) {\n console.error(pmFlag.error)\n process.exitCode = 1\n break\n }\n await add(positionalArgs(rest, ['pm', 'package-manager']), await loadConfig(), {\n dryRun: rest.includes('--dry-run'),\n yes: rest.includes('--yes'),\n noInstall: rest.includes('--no-install'),\n ...(pmFlag.pm ? { pm: pmFlag.pm } : {}),\n })\n break\n }\n case 'list':\n await list(await loadConfig(), { installed: rest.includes('--installed') })\n break\n case 'update':\n await update(rest.filter((r) => !r.startsWith('--'))[0], await loadConfig(), {\n check: rest.includes('--check'),\n yes: rest.includes('--yes'),\n })\n break\n case 'search':\n await search(rest, await loadConfig())\n break\n case 'view':\n await view(rest, await loadConfig())\n break\n case 'theme':\n await theme(rest)\n break\n case 'eject': {\n const { eject } = await import('./commands/eject.js')\n const flag = (key: string): string | undefined => {\n const eq = rest.find((r) => r.startsWith(`--${key}=`))\n if (eq) return eq.slice(key.length + 3)\n const idx = rest.indexOf(`--${key}`)\n const next = idx !== -1 ? rest[idx + 1] : undefined\n // Ignore a following token that is itself a flag (e.g. `--tokens --dry-run`).\n return next && !next.startsWith('--') ? next : undefined\n }\n const tokensArg = flag('tokens')\n await eject(rest, await loadConfig(), {\n ...(tokensArg\n ? {\n tokens: tokensArg\n .split(',')\n .map((t) => t.trim())\n .filter(Boolean),\n }\n : {}),\n ...(flag('scope') ? { scope: flag('scope')! } : {}),\n ...(flag('out') ? { out: flag('out')! } : {}),\n dryRun: rest.includes('--dry-run'),\n })\n break\n }\n case 'generate':\n await generate(rest, await loadConfig())\n break\n case 'registry':\n if (rest[0] === 'build') {\n await registryBuild(rest.slice(1))\n } else {\n console.error(`Unknown registry subcommand: ${rest[0]}`)\n process.exitCode = 1\n }\n break\n case 'template':\n if (rest[0] === 'init') {\n const { templateInit } = await import('./commands/template-init.js')\n await templateInit(rest.slice(1))\n } else {\n console.error(`Unknown template subcommand: ${rest[0]}`)\n process.exitCode = 1\n }\n break\n case 'doctor': {\n const ci = rest.includes('--ci')\n const drift = rest.includes('--drift')\n if (drift) {\n // `--drift` keeps its meaning: drift ONLY.\n const { runDoctorDrift } = await import('./commands/drift.js')\n await runDoctorDrift(await loadConfig())\n } else {\n const cwd = process.cwd()\n const result = await runDoctor(cwd)\n const {\n checkDuplicateCore,\n checkFormatterIgnore,\n checkProjectDependencies,\n checkSignalsCompat,\n checkSsrConfig,\n detectInstallPath,\n } = await import('./commands/doctor.js')\n // Gate on evidence of *any* cascivo install, not on a `cascivo.config.*` file. The\n // config gate mislabelled every prebuilt-path app as copy-paste (the scaffolder wrote\n // one unconditionally), and would now skip them entirely since it no longer does.\n const adopter = detectInstallPath(cwd) !== 'unknown'\n const deps = adopter ? checkProjectDependencies(cwd) : []\n const missingRequired = deps.filter((d) => d.required)\n const signalsCompat = adopter ? await checkSignalsCompat(cwd) : null\n const signalsError = signalsCompat?.severity === 'error'\n const ssrHint = adopter ? checkSsrConfig(cwd) : null\n const duplicateCore = adopter ? await checkDuplicateCore(cwd) : null\n const formatterHint = adopter\n ? checkFormatterIgnore(cwd, (await loadConfig()).outputDir)\n : null\n\n // Run the drift check as part of the DEFAULT invocation. These used to be disjoint\n // branches, so `cascivo doctor` printed \"No violations found.\" on a project where\n // `cascivo doctor --drift` reported five real issues. A clean report from a run that\n // never looked is worse than no report.\n const { runDoctorDrift } = await import('./commands/drift.js')\n const driftOutcome = adopter\n ? await runDoctorDrift(await loadConfig(), cwd)\n : { ran: false, reason: 'no cascivo install detected', issues: 0 }\n\n if (\n result.passed &&\n deps.length === 0 &&\n signalsCompat === null &&\n ssrHint === null &&\n duplicateCore === null &&\n formatterHint === null &&\n driftOutcome.issues === 0\n ) {\n // Never an unqualified \"clean\" when part of the check could not run.\n console.log(\n driftOutcome.ran\n ? 'No violations found.'\n : `No violations found (drift: not checked — ${driftOutcome.reason}).`,\n )\n } else {\n for (const v of result.violations) {\n console.error(`[${v.rule}] ${v.detail}\\n ${v.file}`)\n }\n for (const d of missingRequired) {\n // A forbidden dependency needs the opposite advice from a missing one. Sharing\n // the \"install it\" template told prebuilt-path adopters to install the very\n // packages the message was asking them to remove.\n console.error(\n d.kind === 'forbidden'\n ? `[forbidden-dependency] ${d.package} must not be a direct dependency here. Remove it — ${d.hint}`\n : `[missing-dependency] ${d.package} is not in package.json. Install: ${d.hint}`,\n )\n }\n if (signalsCompat) {\n const tag = signalsError ? 'signals-incompatible' : 'signals-outdated'\n const log = signalsError ? console.error : console.log\n log(`[${tag}] ${signalsCompat.detail} Upgrade: ${signalsCompat.hint}`)\n }\n if (ssrHint) {\n console.log(`[ssr-config] ${ssrHint}`)\n }\n if (formatterHint) {\n console.log(`[formatter-drift] ${formatterHint}`)\n }\n if (duplicateCore) {\n console.error(\n `[duplicate-core] More than one @cascivo/core is installed ` +\n `(root: ${duplicateCore.root ?? 'none'}; ${duplicateCore.nested.join('; ')}). ` +\n duplicateCore.hint,\n )\n }\n for (const d of deps.filter((x) => !x.required)) {\n console.log(\n `[optional] ${d.package} is not installed; add it when a component or chart needs it: ${d.hint}`,\n )\n }\n if (\n ci &&\n (result.violations.length > 0 ||\n missingRequired.length > 0 ||\n signalsError ||\n duplicateCore !== null ||\n driftOutcome.issues > 0)\n ) {\n process.exitCode = 1\n }\n }\n }\n break\n }\n case 'mcp': {\n const { mcp } = await import('./commands/mcp.js')\n await mcp(rest)\n break\n }\n case 'audit': {\n const { audit } = await import('./commands/audit.js')\n await audit(rest, await loadConfig())\n break\n }\n case 'email': {\n const { email } = await import('./commands/email.js')\n await email(rest)\n break\n }\n case 'tokens':\n if (rest[0] === 'import') {\n const { tokensImport } = await import('./commands/tokens.js')\n await tokensImport(rest.slice(1))\n } else {\n console.error(`Unknown tokens subcommand: ${rest[0]}`)\n process.exitCode = 1\n }\n break\n case undefined:\n case '--help':\n case '-h':\n case 'help':\n console.log(HELP)\n break\n case '--version':\n case '-v':\n console.log(VERSION)\n break\n default:\n console.error(`Unknown command: ${command}\\n`)\n console.log(HELP)\n process.exitCode = 1\n }\n}\n\nconst isMain = argv[1] !== undefined && import.meta.url === pathToFileURL(argv[1]).href\n\nif (isMain) {\n run(argv.slice(2)).catch((error: unknown) => {\n console.error(error instanceof Error ? error.message : String(error))\n process.exitCode = 1\n })\n}\n"],"mappings":"soCAUA,SAAgBkC,EACd,EACA,EAAc,QAAQ,IAAI,EAC1B,EAOI,CAAC,EACI,CACT,GAAIC,EAAS,SAAW,EAAG,MAAO,GAClC,IAAMC,EAAKC,EAAK,IAAMhC,EAAqBiC,CAAG,EACxC,CAACC,EAAKC,GAAQhC,EAAe4B,EAAID,EAAU,CAC/C,IAAKE,EAAK,KAAO,GACjB,GAAIA,EAAK,OAAS,CAAE,OAAQA,EAAK,MAAO,EAAI,CAAC,EAC7C,GAAIA,EAAK,IAAM,CAAE,IAAKA,EAAK,GAAI,EAAI,CAAC,CACtC,CAAC,EAcD,OAbA,QAAQ,IAAI,cAAcF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S,CACZ,GAAM,CAAE,SAAU,MAAM,OAAO,wBAC/B,MAAMkd,EAAMpB,CAAI,EAChB,KACF,CACA,IAAK,SACH,GAAIA,EAAK,KAAO,SAAU,CACxB,GAAM,CAAE,gBAAiB,MAAM,OAAO,yBACtC,MAAMqB,EAAarB,EAAK,MAAM,CAAC,CAAC,CAClC,MACE,QAAQ,MAAM,8BAA8BA,EAAK,IAAI,EACrD,QAAQ,SAAW,EAErB,MACF,KAAK,IAAA,GACL,IAAK,SACL,IAAK,KACL,IAAK,OACH,QAAQ,IAAIL,EAAI,EAChB,MACF,IAAK,YACL,IAAK,KACH,QAAQ,IAAIF,CAAO,EACnB,MACF,QACE,QAAQ,MAAM,oBAAoBM,EAAQ,GAAG,EAC7C,QAAQ,IAAIJ,EAAI,EAChB,QAAQ,SAAW,CACvB,CACF,CAEe2B,EAAK,KAAO,IAAA,IAAa,YAAY,MAAQC,GAAcD,EAAK,EAAE,CAAC,CAAC,MAGjFxB,GAAIwB,EAAK,MAAM,CAAC,CAAC,CAAC,CAAC,MAAO,GAAmB,CAC3C,QAAQ,MAAME,aAAiB,MAAQA,EAAM,QAAU,OAAOA,CAAK,CAAC,EACpE,QAAQ,SAAW,CACrB,CAAC"}
1
+ {"version":3,"file":"index.mjs","names":["resolvePath","ASTRO_CONFIG_FILES","DEFAULT_CONFIG","item","__exportAll","detectPackageManager","loadConfig","DEFAULT_CONFIG$1","installCommand","THEMES","installHint","CASCIVO_HOST","writeFileSafe","readFileSafe","resolveOutputPath","assertInside","fetchTextRetry","fetchJson","writeLock","findComponent","updateLockEntry","resolvedAlias","readLock","fetchRegistry","sha256","fileName","createLock","readInstalledPackageVersion","compareVersions","checkPeerVersions","positionalArgs","resolvePackageManagerFlag","flagValue","merge","installPackages","packages","pm","opts","cwd","cmd","args","spawnSync","GITHUB_RE","expandEnv","str","val","env","key","parseAddress","spec","slash","specWithoutRef","githubMatch","owner","repo","item","ref","resolveNamespaceUrl","template","nsCfg","ns","name","resolveItemUrl","addr","config","parts","url","headers","params","expandedHeaders","k","v","expandedParams","result","resolveNamespaceHook","hookResult","resolveClosure","seen","queue","specs","plan","identity","fetchOpts","parseItem","entry","dep","DIRECTORY_URL","pickRegistryUrl","raw","registries","e","\"namespace\"","\"registryUrl\"","resolveFromDirectory","data","fetchFn","res","msg","add_exports","LAYOUT_ALIASES","NAME_NOTES","add","isThirdParty","resolveBareClosure","resolveTemplateTarget","ASSUMED_DEPS","readProjectDeps","pkg","readFileSync","join","hintThemesIfMissing","deps","resolve","target","bareSpecs","installed","resolved","missing","resolvedName","registry","alias","FIRST_PARTY_URL","itemUrl","isMultiRegistrySpec","names","multiSpecs","n","templateNames","t","templateSpecs","lock","kind","isTemplateItem","f","arrow","registryBase","fileHashes","installItem","missingDeps","note","requested","viaAlias","announced","since","replacement","peerFloors","floor","npmPackages","importLines","outputName","fetched","dest","content","suffix","needed","p","violations","file","pages","doctor_exports","checkDuplicateCore","checkFormatterIgnore","checkProjectDependencies","checkSignalsCompat","checkSsrConfig","detectInstallPath","runDoctor","stripCommentsAndStrings","REQUIRED_RUNTIME_DEPS","REQUIRED_PREBUILT_DEPS","FORBIDDEN_PREBUILT_DEPS","ON_DEMAND_DEPS","CONFIG_FILES","hasPackageJson","usesPackage","copied","hasCopiedSource","dir","outputDirCandidates","full","existsSync","readdirSync","dirs","declared","path","findings","required","reason","CORE_DEPENDENTS","root","nested","ownerRoot","version","signals","react","signalsBelow3","hint","reactMajor","m","VITE_SSR_MARKERS","VITE_CONFIG_FILES","pairs","outputDir","configs","ignore","l","ASTRO_CONFIG_FILES$1","setsResolveNoExternal","match","depth","i","start","c","installedReactIsAstroSafe","keywords","checkAstroConfig","installPath","configFile","ssrOnly","astroConfig","framework","BANNED_HOOKS","out","source","next","componentsDir","components","d","reactIndex","indexContent","tsxPath","code","hook","OWNER_DIRECTORY","componentDirectory","component","COMPONENT_RE","PROP_RE","IDENT_RE","REF_RE","KEY_RE","fail","message","isRecord","parseRefs","parseTranslationRef","parseNode","node","props","bind","events","children","parseViewConfig","state","parsed","view","nodes","isTranslationRef","serializeInitial","value","serializeProp","renderChildren","renderNode","child","indent","componentPropNames","knownComponents","compName","propParts","propsStr","childrenStr","collectBindAndEvents","boundProps","actionProps","walk","usesStateSetter","r","byDirectory","directory","a","b","members","generateTsx","allNodes","stateEntries","hasState","needsCoerce","regionBlocks","regionName","hasData","hasActions","propsType","coreImport","coerceHelper","stateDecls","generate","outArg","inputArg","componentsDirArg","fromArg","viewConfig","propMetas","tsx","outPath","dirname","basename","writeFileSync","RUNTIME_DEPS","DEV_DEPS","promptTheme","rl","createInterface","stdin","stdout","answer","configFileContents","theme","ESLINT_CONFIGS","hintEslintIfPresent","recordDependencies","pkgPath","field","added","FORMATTER_IGNORES","ensureFormatterIgnore","line","hasPrettierKeyInPackageJson","current","banner","ASTRO_CONFIG_FILES","printAstroNextSteps","printDependencySummary","init","yes","noInstall","themeArg","pmFlag","interactive","configPath","runtimeOk","devOk","recorded","TYPE_LABELS","deprecationSuffix","formatGroup","rows","entries","widths","h","cells","cell","sep","w","formatList","groups","sections","label","list","options","validateTemplates","errors","warnings","localNames","index","validateTemplate","registryBuild","inFile","outDir","inPath","readFile","\"schemaVersion\"","parseLegacyRegistry","validateIndex","templateResult","buildRegistry","matchesQuery","q","query","search","nsFlag","registryFilter","results","indexUrl","validateItem","reg","DEFAULT_CONFIG","hashToConfig","hash","base64","json","FONT_STACKS","accentScale","light","configToCSS","scale","acc","role","lines","themeName","previewMode","\"humanist\"","THEME_NAME_RE","flag","eq","idx","themeCreate","dryRun","css","sub","diffLines","oldStr","newStr","lcs","j","hasChanges","confirm","question","update","updateCheck","lockEntry","lockedVersion","baseItemUrl","baseItem","threeWayUpdate","twoWayUpdate","upstreamEntry","summaries","pending","fname","baseFile","upstream","local","base","conflicts","text","s","icon","conflicted","updatedLock","hasConflicts","latest","outdated","lockByBase","changed","formatItem","meta","asTemplateMeta","VERSION","createRequire","HELP","THEME_LIST","COMMAND_HELP","run","command","rest","commandHelp","create","app","tokensArg","eject","templateInit","ci","runDoctorDrift","adopter","missingRequired","signalsCompat","signalsError","ssrHint","duplicateCore","formatterHint","driftOutcome","x","mcp","audit","design","email","tokensImport","argv","pathToFileURL","error"],"sources":["../src/utils/exec.ts","../src/utils/resolve.ts","../src/utils/directory.ts","../src/commands/add.ts","../src/commands/doctor.ts","../src/commands/generate.ts","../src/commands/init.ts","../src/commands/list.ts","../src/commands/registry.ts","../src/commands/search.ts","../../theme-kit/src/config.ts","../../theme-kit/src/hash.ts","../../theme-kit/src/css.ts","../src/commands/theme.ts","../src/utils/diff.ts","../src/commands/update.ts","../src/commands/view.ts","../src/index.ts"],"sourcesContent":["import { spawnSync } from 'node:child_process'\nimport { detectPackageManager, installCommand, installHint, type PackageManager } from './config.js'\n\n/**\n * Install npm packages using the detected (or explicitly chosen) package\n * manager, inheriting stdio so the user sees install progress. On failure it\n * prints the exact command to run by hand — the adopter can always recover even\n * when the spawn fails (e.g. npm crashing inside a pnpm workspace). Returns\n * false if the install failed.\n */\nexport function installPackages(\n packages: string[],\n cwd: string = process.cwd(),\n opts: {\n pm?: PackageManager\n dev?: boolean\n /** Registry peer floors, so a known minimum is honoured rather than silently ignored. */\n floors?: Record<string, string>\n /** `--pin <version>` escape hatch: install every `@cascivo/*` at exactly this version. */\n pin?: string\n } = {},\n): boolean {\n if (packages.length === 0) return true\n const pm = opts.pm ?? detectPackageManager(cwd)\n const [cmd, args] = installCommand(pm, packages, {\n dev: opts.dev ?? false,\n ...(opts.floors ? { floors: opts.floors } : {}),\n ...(opts.pin ? { pin: opts.pin } : {}),\n })\n console.log(`Installing ${packages.join(', ')} with ${cmd}…`)\n const result = spawnSync(cmd, args, {\n cwd,\n stdio: 'inherit',\n shell: process.platform === 'win32',\n })\n if (result.status !== 0) {\n console.error(`Failed to install: ${packages.join(', ')}`)\n console.error(\n `Install them yourself with: ${installHint(pm, packages, { dev: opts.dev ?? false })}`,\n )\n return false\n }\n return true\n}\n","import { CASCIVO_HOST, type CascadeConfig, type RegistryNamespaceConfig } from './config.js'\nimport { fetchJson } from './http.js'\nimport { parseItem } from '@cascivo/registry'\nimport type { RegistryItem } from '@cascivo/registry'\n\nexport type AddressKind = 'bare' | 'namespace' | 'url' | 'github'\n\nexport interface ParsedAddress {\n kind: AddressKind\n namespace?: string\n name: string\n ref?: string\n raw: string\n}\n\nconst GITHUB_RE = /^([^/]+)\\/([^/]+)\\/([^#]+)(?:#(.+))?$/\n\nfunction expandEnv(str: string, env: NodeJS.ProcessEnv = process.env): string {\n return str.replace(/\\$\\{([^}]+)\\}/g, (_, key: string) => {\n const val = env[key]\n if (val === undefined) throw new Error(`Environment variable ${key} is not set`)\n return val\n })\n}\n\nexport function parseAddress(spec: string, _env: NodeJS.ProcessEnv = process.env): ParsedAddress {\n if (\n spec.startsWith('http://') ||\n spec.startsWith('https://') ||\n spec.startsWith('./') ||\n spec.startsWith('/')\n ) {\n return { kind: 'url', name: spec, raw: spec }\n }\n\n if (spec.startsWith('@')) {\n const slash = spec.indexOf('/', 1)\n if (slash === -1) throw new Error(`Invalid namespace address: ${spec} (expected @ns/name)`)\n const namespace = spec.slice(0, slash)\n const name = spec.slice(slash + 1)\n return { kind: 'namespace', namespace, name, raw: spec }\n }\n\n // GitHub: owner/repo/item[#ref] — at least 3 path segments, no leading protocol/dot\n const specWithoutRef = spec.includes('#') ? spec.slice(0, spec.indexOf('#')) : spec\n const githubMatch = GITHUB_RE.exec(spec)\n if (githubMatch && !specWithoutRef.includes('.') && specWithoutRef.split('/').length >= 3) {\n const [, owner, repo, item, ref] = githubMatch\n return {\n kind: 'github',\n name: `${owner}/${repo}/${item}`,\n ref: ref ?? 'main',\n raw: spec,\n }\n }\n\n return { kind: 'bare', name: spec, raw: spec }\n}\n\nfunction resolveNamespaceUrl(\n ns: string,\n name: string,\n nsCfg: RegistryNamespaceConfig,\n env: NodeJS.ProcessEnv,\n): string {\n const template = typeof nsCfg === 'string' ? nsCfg : nsCfg.url\n if (!template.includes('{name}')) {\n throw new Error(`Registry namespace \"${ns}\" URL template must contain {name}: ${template}`)\n }\n return expandEnv(template.replace('{name}', name), env)\n}\n\nexport async function resolveItemUrl(\n addr: ParsedAddress,\n config: CascadeConfig,\n env: NodeJS.ProcessEnv = process.env,\n resolveNamespaceHook?: (ns: string) => Promise<RegistryNamespaceConfig | null>,\n): Promise<{ url: string; headers?: Record<string, string>; params?: Record<string, string> }> {\n switch (addr.kind) {\n case 'url':\n return { url: addr.name }\n\n case 'bare': {\n const base = config.registry.replace(/\\/registry\\.json$/, '').replace(/\\/r$/, '')\n return { url: `${base}/r/${addr.name}.json` }\n }\n\n case 'github': {\n const parts = addr.name.split('/')\n const owner = parts[0]!\n const repo = parts[1]!\n const item = parts.slice(2).join('/')\n const ref = addr.ref ?? 'main'\n return {\n url: `https://raw.githubusercontent.com/${owner}/${repo}/${ref}/r/${item}.json`,\n }\n }\n\n case 'namespace': {\n const ns = addr.namespace!\n const name = addr.name\n\n // Config-defined namespaces always win\n if (config.registries?.[ns]) {\n const nsCfg = config.registries[ns]!\n const url = resolveNamespaceUrl(ns, name, nsCfg, env)\n const headers = typeof nsCfg !== 'string' ? nsCfg.headers : undefined\n const params = typeof nsCfg !== 'string' ? nsCfg.params : undefined\n const expandedHeaders = headers\n ? Object.fromEntries(Object.entries(headers).map(([k, v]) => [k, expandEnv(v, env)]))\n : undefined\n const expandedParams = params\n ? Object.fromEntries(Object.entries(params).map(([k, v]) => [k, expandEnv(v, env)]))\n : undefined\n const result: {\n url: string\n headers?: Record<string, string>\n params?: Record<string, string>\n } = { url }\n if (expandedHeaders) result.headers = expandedHeaders\n if (expandedParams) result.params = expandedParams\n return result\n }\n\n // Directory fallback hook (injected from T3)\n if (resolveNamespaceHook) {\n const hookResult = await resolveNamespaceHook(ns)\n if (hookResult) {\n const url = resolveNamespaceUrl(ns, name, hookResult, env)\n return { url }\n }\n }\n\n // Built-in first-party namespace fallback (@cascade is the legacy alias)\n if (ns === '@cascivo' || ns === '@cascade') {\n return { url: `${CASCIVO_HOST}/r/${name}.json` }\n }\n\n throw new Error(\n `Unknown namespace \"${ns}\". Add it to registries in cascivo.config.ts or check the directory at cascivo.com`,\n )\n }\n }\n}\n\nexport interface InstallPlan {\n items: {\n spec: string\n addr: ParsedAddress\n itemUrl: string\n headers?: Record<string, string>\n params?: Record<string, string>\n item: RegistryItem\n registryBase: string\n }[]\n}\n\nexport async function resolveClosure(\n specs: string[],\n config: CascadeConfig,\n env: NodeJS.ProcessEnv = process.env,\n resolveNamespaceHook?: (ns: string) => Promise<RegistryNamespaceConfig | null>,\n): Promise<InstallPlan> {\n const seen = new Set<string>()\n const queue: string[] = [...specs]\n const plan: InstallPlan['items'] = []\n\n while (queue.length > 0) {\n const spec = queue.shift()!\n const addr = parseAddress(spec, env)\n const identity = addr.raw\n\n if (seen.has(identity)) continue\n seen.add(identity)\n\n const { url, headers, params } = await resolveItemUrl(addr, config, env, resolveNamespaceHook)\n const fetchOpts: Parameters<typeof fetchJson>[1] = {}\n if (headers) fetchOpts.headers = headers\n if (params) fetchOpts.params = params\n const item = parseItem(await fetchJson(url, fetchOpts), url)\n\n const base = url.replace(/\\/[^/]+\\.json$/, '')\n\n const entry: InstallPlan['items'][number] = {\n spec,\n addr,\n itemUrl: url,\n item,\n registryBase: base,\n }\n if (headers) entry.headers = headers\n if (params) entry.params = params\n plan.push(entry)\n\n for (const dep of item.registryDependencies ?? []) {\n queue.push(dep)\n }\n }\n\n return { items: plan }\n}\n","import type { RegistryNamespaceConfig } from './config.js'\nimport { fetchJson } from './http.js'\nimport type { FetchFn } from './http.js'\n\nimport { CASCIVO_HOST } from './config.js'\n\nexport const DIRECTORY_URL = `${CASCIVO_HOST}/r/registries.json`\n\n/**\n * Pull the registry URL for one namespace out of a directory payload, or null.\n *\n * The result is used as a fetch base for component installs, so an entry whose\n * `registryUrl` is not a string — or not http(s) — is dropped rather than\n * trusted: `resolveItemUrl` would otherwise build request URLs by concatenating\n * onto whatever came back.\n */\nfunction pickRegistryUrl(raw: unknown, ns: string): string | null {\n if (typeof raw !== 'object' || raw === null) return null\n const registries = (raw as { registries?: unknown }).registries\n if (!Array.isArray(registries)) return null\n for (const entry of registries) {\n if (typeof entry !== 'object' || entry === null) continue\n const e = entry as Record<string, unknown>\n if (e['namespace'] !== ns) continue\n const url = e['registryUrl']\n if (typeof url !== 'string' || !/^https?:\\/\\//.test(url)) return null\n return url\n }\n return null\n}\n\nexport async function resolveFromDirectory(\n ns: string,\n fetchFn?: FetchFn,\n): Promise<RegistryNamespaceConfig | null> {\n try {\n // fetchJson uses the module-level _fetchFn; if a custom fetchFn is provided, we use it directly\n let data: unknown\n if (fetchFn) {\n const res = await fetchFn(DIRECTORY_URL, { headers: { Accept: 'application/json' } })\n if (!res.ok) throw new Error(`HTTP ${res.status}`)\n data = await res.json()\n } else {\n data = await fetchJson(DIRECTORY_URL)\n }\n return pickRegistryUrl(data, ns)\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e)\n console.warn(`Could not reach cascivo.com directory: ${msg}`)\n return null\n }\n}\n","import { readFileSync } from 'node:fs'\nimport { join, resolve as resolvePath } from 'node:path'\nimport {\n detectPackageManager,\n installHint,\n type CascadeConfig,\n type PackageManager,\n} from '../utils/config.js'\nimport { installPackages } from '../utils/exec.js'\nimport { assertInside, resolveOutputPath, writeFileSafe } from '../utils/fs.js'\nimport { fetchTextRetry } from '../utils/http.js'\nimport {\n fetchRegistry,\n fileName,\n findComponent,\n resolvedAlias,\n type Registry,\n type RegistryComponent,\n} from '../utils/registry.js'\nimport { createLock, readLock, sha256, updateLockEntry, writeLock } from '../utils/lock.js'\nimport { checkPeerVersions } from '../utils/peer-versions.js'\nimport { resolveClosure } from '../utils/resolve.js'\nimport { resolveFromDirectory } from '../utils/directory.js'\nimport { isTemplateItem, type RegistryItem } from '@cascivo/registry'\n\n/** Dependencies always present in a cascade project — never auto-installed. */\nconst ASSUMED_DEPS = new Set(['react', 'react-dom'])\n\n/** Merged dependencies + devDependencies from the project's package.json (empty if none). */\nfunction readProjectDeps(cwd: string): Record<string, unknown> {\n try {\n const pkg = JSON.parse(readFileSync(join(cwd, 'package.json'), 'utf8')) as {\n dependencies?: Record<string, unknown>\n devDependencies?: Record<string, unknown>\n }\n return { ...pkg.dependencies, ...pkg.devDependencies }\n } catch {\n // No package.json — treat as no deps installed.\n return {}\n }\n}\n\n/**\n * Copied components read `--cascivo-*` custom properties; without\n * @cascivo/tokens or @cascivo/themes imported somewhere, they render unstyled.\n * Print the wiring once after a successful install if neither is a dependency.\n */\nfunction hintThemesIfMissing(cwd: string, pm: PackageManager): void {\n const deps = readProjectDeps(cwd)\n if (deps['@cascivo/themes'] !== undefined || deps['@cascivo/tokens'] !== undefined) return\n console.log(\n '\\nStyling: cascivo components read --cascivo-* tokens, which this project does not import yet.',\n )\n console.log(` ${installHint(pm, ['@cascivo/themes'])}`)\n console.log(\" import '@cascivo/themes/all' // once, in your entry file\")\n console.log(' <html data-theme=\"light\"> // or any container')\n}\n\n/** Resolve where a template's own file is written — relative to the project root. */\nexport function resolveTemplateTarget(cwd: string, target: string): string {\n return assertInside(cwd, resolvePath(cwd, target))\n}\n\nexport interface ResolvedBareEntry {\n entry: RegistryComponent\n /** True if reached via an original `cascivo add` argument; false if pulled as a transitive dependency. */\n requested: boolean\n /**\n * The foreign name the caller typed, when it differed from the component's own — `Switch`\n * for `toggle`. Reported before the copy so nobody wonders why a different file appeared.\n */\n viaAlias?: string\n}\n\n/**\n * Names from other libraries → the cascivo layout primitive that fills the same\n * role, so `cascivo add box` installs `layout/flex`. Bare names that already\n * resolve (e.g. `flex` → `layout/flex` via suffix match) still list an alias here\n * for discoverability.\n */\nexport const LAYOUT_ALIASES: Record<string, string> = {\n box: 'layout/flex',\n hstack: 'layout/flex',\n vstack: 'layout/flex',\n gap: 'spacer',\n}\n\n/**\n * Disambiguation printed when a requested bare name is a real cascivo component\n * whose meaning differs from the same name elsewhere, so an adopter who grabbed\n * it by name alone learns the right primitive. Keyed by lowercased bare name.\n */\nexport const NAME_NOTES: Record<string, string> = {\n stack:\n \"Note: cascivo's Stack overlaps children into a card-pile (z-axis), not a \" +\n 'vertical spacing layout. For vertical spacing use Flex direction=\"vertical\" ' +\n '(cascivo add flex; aliases: vstack, hstack).',\n}\n\n/**\n * Resolve the transitive closure of bare-name registry entries, following each\n * entry's `registryDependencies`. De-duped by resolved registry name and\n * cycle-safe (an entry is processed at most once). Returns resolved entries in\n * install order plus the names that could not be found. Pure — no I/O.\n */\nexport function resolveBareClosure(\n registry: Registry,\n bareSpecs: string[],\n): { resolved: ResolvedBareEntry[]; missing: string[] } {\n const queue: { name: string; requested: boolean }[] = bareSpecs.map((name) => ({\n name,\n requested: true,\n }))\n const installed = new Set<string>()\n const resolved: ResolvedBareEntry[] = []\n const missing: string[] = []\n\n while (queue.length > 0) {\n const { name, requested } = queue.shift()!\n const resolvedName = LAYOUT_ALIASES[name.toLowerCase()] ?? name\n const entry = findComponent(registry, resolvedName)\n if (!entry) {\n missing.push(name)\n continue\n }\n if (installed.has(entry.name)) continue\n installed.add(entry.name)\n const alias = resolvedAlias(entry, name)\n resolved.push({ entry, requested, ...(alias ? { viaAlias: alias } : {}) })\n for (const dep of entry.registryDependencies ?? []) {\n queue.push({ name: dep, requested: false })\n }\n }\n\n return { resolved, missing }\n}\n\n/**\n * First-party items are hosted on cascivo.com or the cascivo/cascivo GitHub\n * repo (raw file URLs). Anything else gets a review-before-use notice.\n */\nconst FIRST_PARTY_URL = /^https:\\/\\/(cascivo\\.com|raw\\.githubusercontent\\.com\\/cascivo\\/cascivo)\\//\n\nexport function isThirdParty(itemUrl: string): boolean {\n return !FIRST_PARTY_URL.test(itemUrl)\n}\n\nfunction isMultiRegistrySpec(name: string): boolean {\n return (\n name.startsWith('@') ||\n name.startsWith('http://') ||\n name.startsWith('https://') ||\n name.startsWith('./') ||\n name.startsWith('/') ||\n name.split('/').length >= 3\n )\n}\n\nexport async function add(\n names: string[],\n config: CascadeConfig,\n opts: {\n dryRun?: boolean\n yes?: boolean\n cwd?: string\n pm?: PackageManager\n noInstall?: boolean\n } = {},\n): Promise<void> {\n if (names.length === 0) {\n console.error('Usage: cascivo add <component...>')\n return\n }\n\n const cwd = opts.cwd ?? process.cwd()\n const pm = opts.pm ?? detectPackageManager(cwd)\n const multiSpecs = names.filter(isMultiRegistrySpec)\n let bareSpecs = names.filter((n) => !isMultiRegistrySpec(n))\n\n // Bare names that match a first-party template install through the per-item\n // path (they carry file targets the bare component path cannot express).\n let registry: Registry | null = null\n if (bareSpecs.length > 0) {\n registry = await fetchRegistry(config.registry)\n const templateNames = new Set(registry.templates.map((t) => t.toLowerCase()))\n const templateSpecs = bareSpecs.filter((n) => templateNames.has(n.toLowerCase()))\n if (templateSpecs.length > 0) {\n bareSpecs = bareSpecs.filter((n) => !templateNames.has(n.toLowerCase()))\n multiSpecs.push(...templateSpecs.map((n) => `@cascivo/${n.toLowerCase()}`))\n }\n }\n\n let lock = (await readLock(cwd)) ?? createLock()\n\n // Handle multi-registry specs (namespaces, URLs, GitHub)\n if (multiSpecs.length > 0) {\n const plan = await resolveClosure(multiSpecs, config, process.env, resolveFromDirectory)\n\n if (opts.dryRun) {\n console.log('Dry run — would install:')\n for (const item of plan.items) {\n const kind = isTemplateItem(item.item) ? ' [template]' : ''\n console.log(\n ` ${item.spec} (${item.item.name}@${item.item.version})${kind} from ${item.itemUrl}`,\n )\n for (const f of item.item.files) {\n const arrow = isTemplateItem(item.item) && f.target ? ` → ${f.target}` : ''\n console.log(` ${f.url}${arrow}`)\n }\n if (item.item.registryDependencies?.length) {\n console.log(` components: ${item.item.registryDependencies.join(', ')}`)\n }\n }\n return\n }\n\n for (const { item, itemUrl, registryBase } of plan.items) {\n if (isThirdParty(itemUrl)) {\n console.log(\n `\\nReview before use — files from non-directory registry: ${registryBase}\\n` +\n (item.files ?? []).map((f) => ` ${f.url}`).join('\\n'),\n )\n }\n\n let fileHashes: Record<string, string>\n try {\n fileHashes = await installItem(item, config, cwd, {\n pm,\n ...(opts.noInstall ? { noInstall: true } : {}),\n })\n } catch (e) {\n // Nothing was written for this item (fetch-all-then-write), so the\n // lockfile must not record it either.\n console.error(`Failed to install ${item.name}: ${e instanceof Error ? e.message : e}`)\n process.exitCode = 1\n continue\n }\n lock = updateLockEntry(lock, item.name, {\n registry: registryBase,\n version: item.version,\n installedAt: new Date().toISOString().slice(0, 10),\n files: fileHashes,\n })\n }\n await writeLock(lock, cwd)\n if (bareSpecs.length === 0) {\n hintThemesIfMissing(cwd, pm)\n return\n }\n }\n\n if (bareSpecs.length === 0) return\n // Legacy bare-name path (uses the registry fetched above for template\n // detection). Resolves the transitive closure of registry (component)\n // dependencies so a component that imports a shared hook/sibling\n // (e.g. `../popover/use-popover`) installs that dependency too.\n registry ??= await fetchRegistry(config.registry)\n const missingDeps = new Set<string>()\n const registryBase = config.registry.replace(/\\/registry\\.json$/, '').replace(/\\/r$/, '')\n\n for (const spec of bareSpecs) {\n const note = NAME_NOTES[spec.toLowerCase()]\n if (note) console.log(note)\n\n const alias = LAYOUT_ALIASES[spec.toLowerCase()]\n if (!alias) continue\n const target = findComponent(registry, alias)\n if (target) {\n console.log(\n `\"${spec}\" is not a cascivo component — installing ${target.name} (its ${spec} primitive).`,\n )\n }\n }\n\n const { resolved, missing } = resolveBareClosure(registry, bareSpecs)\n for (const name of missing) {\n console.error(`Component \"${name}\" not found in registry. Run \"cascivo list\".`)\n }\n\n // Announce the CHANNEL before anything else runs. `cascivo add area-chart` reads like\n // every other add — same syntax, same \"you own the code\" framing — but copies no source:\n // it installs an npm package. That was only stated inside the install log, which scrolls\n // past. Say it first, once per package, for what the caller actually asked for.\n // A foreign name resolved to a different file name: say so, or the copy looks like a\n // mistake. `Switch` is the highest-traffic case — every peer system calls it that.\n for (const { entry, requested, viaAlias } of resolved) {\n if (!requested || !viaAlias) continue\n console.log(`\\n\"${viaAlias}\" is cascivo's \"${entry.name}\" — installing that.`)\n }\n\n const announced = new Set<string>()\n for (const { entry, requested } of resolved) {\n if (!requested || !entry.install || announced.has(entry.install)) continue\n announced.add(entry.install)\n console.log(\n `\\n\"${entry.name}\" ships in the ${entry.install} npm package — no source is copied ` +\n 'into your project. Updates come from your package manager, not `cascivo update`.',\n )\n }\n\n // Warn BEFORE copying, and only for what the caller actually asked for — a deprecated\n // entry pulled in transitively is not their decision to make. The source's `@deprecated`\n // JSDoc arrives too late: by the time it is read, the file is already vendored.\n for (const { entry, requested } of resolved) {\n if (!requested || !entry.deprecated) continue\n const { replacement, since, note } = entry.deprecated\n console.warn(\n `\\n⚠ \"${entry.name}\" is deprecated since ${since}. Use \"${replacement}\" instead:\\n` +\n ` cascivo add ${replacement}\\n` +\n (note ? ` ${note}\\n` : '') +\n ` Adding \"${entry.name}\" anyway — it still works.\\n`,\n )\n }\n\n // Aggregate each resolved entry's peer-version floors (e.g. \"install data-table\n // needs @cascivo/i18n >= 0.2.1\") so we can verify what actually got installed.\n const peerFloors: Record<string, string> = {}\n for (const { entry } of resolved) {\n for (const [pkg, floor] of Object.entries(entry.peerVersions ?? {})) {\n peerFloors[pkg] = floor\n }\n }\n\n // npm-distributed entries (charts/flow/editor) are a runtime package, not\n // copied source. Collect their package + import lines here so N chart entries\n // produce ONE `@cascivo/charts` install rather than N, then install once below.\n const npmPackages = new Set<string>()\n const importLines: string[] = []\n\n for (const { entry, requested } of resolved) {\n if (entry.install) {\n const pkg = entry.install\n npmPackages.add(pkg)\n console.log(\n `\"${entry.name}\" is distributed as the npm package ${pkg} — a runtime dependency, ` +\n `not copied source (updates come via your package manager).`,\n )\n importLines.push(` import { ${entry.meta.name} } from '${pkg}'`)\n if (entry.styles) {\n importLines.push(` import '${entry.styles}' // once, in your entry file`)\n }\n continue\n }\n\n const outputName = entry.name.includes('/') ? entry.name.split('/').pop()! : entry.name\n const fileHashes: Record<string, string> = {}\n\n // Two-phase: fetch every file before writing any, so a mid-install network\n // failure can never leave a half-copied component (or a lockfile entry\n // pointing at one).\n let fetched: { url: string; content: string }[]\n try {\n fetched = await Promise.all(\n entry.files.map(async (url) => ({ url, content: await fetchTextRetry(url) })),\n )\n } catch (e) {\n console.error(`Failed to install ${entry.name}: ${e instanceof Error ? e.message : e}`)\n process.exitCode = 1\n continue\n }\n for (const { url, content } of fetched) {\n const dest = resolveOutputPath(config.outputDir, outputName, fileName(url), cwd)\n await writeFileSafe(dest, content)\n fileHashes[dest] = sha256(content)\n }\n\n for (const dep of entry.dependencies) {\n if (!ASSUMED_DEPS.has(dep)) missingDeps.add(dep)\n }\n\n lock = updateLockEntry(lock, entry.name, {\n registry: registryBase,\n version: entry.version,\n installedAt: new Date().toISOString().slice(0, 10),\n files: fileHashes,\n })\n\n const suffix = requested ? '' : ' (dependency)'\n console.log(`Added ${entry.name} to ${config.outputDir}/${outputName}/${suffix}`)\n }\n\n // Install npm-distributed packages (charts/flow/editor) once, deduped, skipping\n // any already in the project. `--no-install`/`--dry-run` fall back to printing.\n if (npmPackages.size > 0) {\n const deps = readProjectDeps(cwd)\n const needed = [...npmPackages].filter((p) => deps[p] === undefined)\n if (opts.dryRun) {\n console.log(`Dry run — would install npm package(s): ${[...npmPackages].join(', ')}`)\n } else if (needed.length > 0) {\n if (opts.noInstall) {\n console.log(`\\nSkipped install (--no-install). Install with:\\n ${installHint(pm, needed)}`)\n } else if (!installPackages(needed, cwd, { pm })) {\n process.exitCode = 1\n }\n }\n if (importLines.length > 0) {\n console.log(`\\nImport it:\\n${importLines.join('\\n')}`)\n }\n }\n\n if (missingDeps.size > 0 && !opts.dryRun) {\n if (opts.noInstall) {\n console.log(\n `\\nSkipped install (--no-install). Install with:\\n ${installHint(pm, [...missingDeps])}`,\n )\n } else {\n installPackages([...missingDeps], cwd, { pm })\n }\n }\n\n if (Object.keys(peerFloors).length > 0) {\n const violations = await checkPeerVersions(cwd, peerFloors)\n for (const v of violations) {\n console.error(\n `\\nWarning: ${v.pkg} ${v.installed ? `${v.installed} is` : 'is not'} installed, but ` +\n `the copied component source needs ${v.pkg} ${v.required}. ` +\n `Run: ${installHint(pm, [`${v.pkg}@latest`])}`,\n )\n process.exitCode = 1\n }\n }\n\n await writeLock(lock, cwd)\n hintThemesIfMissing(cwd, pm)\n}\n\n/**\n * Install a single resolved item, returning a map of written path → content\n * hash for the lockfile. A template writes its own files to their `target`\n * paths (relative to the project root); every other item writes its files under\n * the components output directory. A template's components are installed\n * separately as their own plan entries (via `registryDependencies`).\n */\nasync function installItem(\n item: RegistryItem,\n config: CascadeConfig,\n cwd: string,\n opts: { pm?: PackageManager; noInstall?: boolean } = {},\n): Promise<Record<string, string>> {\n const fileHashes: Record<string, string> = {}\n const missingDeps = new Set<string>()\n const template = isTemplateItem(item)\n const outputName = item.name.includes('/') ? item.name.split('/').pop()! : item.name\n\n // Two-phase: fetch every file before writing any. A failed fetch aborts the\n // whole item (throws to the caller) instead of silently installing a subset.\n const fetched = await Promise.all(\n (item.files ?? []).map(async (file) => ({\n file,\n content: await fetchTextRetry(file.url),\n })),\n )\n for (const { file, content } of fetched) {\n const dest =\n template && file.target\n ? resolveTemplateTarget(cwd, file.target)\n : resolveOutputPath(config.outputDir, outputName, fileName(file.url), cwd)\n await writeFileSafe(dest, content)\n fileHashes[dest] = sha256(content)\n }\n\n for (const dep of item.dependencies ?? []) {\n if (!ASSUMED_DEPS.has(dep)) missingDeps.add(dep)\n }\n\n if (missingDeps.size > 0) {\n if (opts.noInstall) {\n console.log(\n `\\nSkipped install (--no-install). Install with:\\n ${installHint(opts.pm ?? detectPackageManager(cwd), [...missingDeps])}`,\n )\n } else {\n installPackages([...missingDeps], cwd, opts.pm ? { pm: opts.pm } : {})\n }\n }\n\n if (template) {\n const pages = item.files?.filter((f) => f.target).map((f) => f.target) ?? []\n console.log(`Installed template ${item.name} (${pages.length} files)`)\n } else {\n console.log(`Added ${item.name} to ${config.outputDir}/${outputName}/`)\n }\n\n return fileHashes\n}\n","import { readFileSync, readdirSync, existsSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { detectPackageManager, installHint } from '../utils/config.js'\nimport { readInstalledPackageVersion } from '../utils/peer-versions.js'\nimport { compareVersions } from '../utils/semver.js'\n\nexport interface DoctorViolation {\n file: string\n rule: string\n detail: string\n}\n\nexport interface DoctorResult {\n violations: DoctorViolation[]\n passed: boolean\n}\n\n/** Runtime packages **copied** cascivo source needs; the last is @cascivo/core's peer. */\nconst REQUIRED_RUNTIME_DEPS = [\n '@cascivo/core',\n '@cascivo/tokens',\n '@cascivo/themes',\n '@preact/signals-react',\n]\n\n/** Runtime packages a **prebuilt** (Path B) app needs. */\nconst REQUIRED_PREBUILT_DEPS = ['@cascivo/react', '@cascivo/themes', '@preact/signals-react']\n\n/**\n * Packages a prebuilt app must NOT declare directly, with the rule each one breaks. They\n * are transitive there, and everything they export is re-exported from `@cascivo/react`.\n */\nconst FORBIDDEN_PREBUILT_DEPS: Record<string, string> = {\n '@cascivo/core':\n 'AI-RULES.md: never add @cascivo/core to a prebuilt-path app — it is transitive, and everything is re-exported from @cascivo/react',\n '@cascivo/tokens':\n 'GETTING-STARTED.md: @cascivo/tokens comes with @cascivo/themes as a direct dependency — never install it by hand',\n}\n\n/** Installed on demand by `cascivo add` when a component/chart declares them. */\nconst ON_DEMAND_DEPS = ['@cascivo/i18n', '@cascivo/charts']\n\nexport interface DependencyFinding {\n package: string\n /** true = a runtime dep whose absence breaks the build; false = advisory. */\n required: boolean\n hint: string\n /**\n * What is wrong. `'missing'` (the default) means install it; `'forbidden'` means the\n * project declares a package its install path must not. They need opposite advice, and\n * reporting both under the \"not in package.json — install it\" template produced a\n * self-contradicting message.\n */\n kind?: 'missing' | 'forbidden'\n}\n\nconst CONFIG_FILES = ['cascivo.config.ts', 'cascivo.config.js', 'cascivo.config.mjs']\n\n/**\n * How this project consumes cascivo.\n *\n * - `prebuilt` — Path B: depends on `@cascivo/react`, no copied source.\n * - `copied` — Path A: has vendored component source (or no `@cascivo/react`).\n * - `hybrid` — both: consumes the package AND copied something.\n * - `unknown` — no evidence either way; emit no dependency advice at all.\n */\nexport type InstallPath = 'prebuilt' | 'copied' | 'hybrid' | 'unknown'\n\n/**\n * Infer the install path from evidence.\n *\n * This used to be `isAdopterProject()` — \"does a `cascivo.config.*` exist?\" — and\n * `cascivo create` wrote that config into every scaffold, including prebuilt-path ones. So\n * every scaffolded app was judged copy-paste and told to install `@cascivo/core` and\n * `@cascivo/tokens`, which the docs explicitly forbid on that path. `doctor --ci` exited 1\n * on a correctly-installed app, which made the CI gate the docs recommend\n * (`cascivo doctor --ci && cascivo audit --ai src`) red on day one.\n *\n * A config file now only contributes evidence when it points at a directory that actually\n * contains copied source, which is what it was ever meant to signal.\n */\nexport function detectInstallPath(cwd: string): InstallPath {\n let deps: Record<string, unknown> = {}\n let hasPackageJson = true\n try {\n const pkg = JSON.parse(readFileSync(join(cwd, 'package.json'), 'utf8')) as {\n dependencies?: Record<string, unknown>\n devDependencies?: Record<string, unknown>\n }\n deps = { ...pkg.dependencies, ...pkg.devDependencies }\n } catch {\n hasPackageJson = false\n }\n\n if (!hasPackageJson) return 'unknown'\n\n const usesPackage = deps['@cascivo/react'] !== undefined\n const copied = hasCopiedSource(cwd)\n\n if (usesPackage && copied) return 'hybrid'\n if (usesPackage) return 'prebuilt'\n if (copied) return 'copied'\n // No package dependency and no copied source yet. A config file alone is NOT evidence of\n // a copy-paste app — it is what `cascivo add` writes before anything has been copied, and\n // treating it as proof is precisely what broke prebuilt-path projects. Advise on nothing.\n return 'unknown'\n}\n\n/** Whether the configured output directory holds vendored component source. */\nfunction hasCopiedSource(cwd: string): boolean {\n for (const dir of outputDirCandidates(cwd)) {\n const full = join(cwd, dir)\n if (!existsSync(full)) continue\n try {\n if (readdirSync(full).some((f) => f.endsWith('.tsx'))) return true\n } catch {\n // unreadable directory — no evidence, keep looking\n }\n }\n return false\n}\n\n/** `outputDir` from the config if it declares one, plus the documented default. */\nfunction outputDirCandidates(cwd: string): string[] {\n const dirs = new Set<string>(['src/components/ui'])\n for (const file of CONFIG_FILES) {\n const full = join(cwd, file)\n if (!existsSync(full)) continue\n try {\n const declared = /outputDir\\s*:\\s*['\"]([^'\"]+)['\"]/.exec(readFileSync(full, 'utf8'))?.[1]\n if (declared !== undefined) dirs.add(declared)\n } catch {\n // unreadable config — fall back to the default candidate\n }\n }\n return [...dirs]\n}\n\n/** Whether cwd looks like a cascivo adopter project (has a generated config). */\nexport function isAdopterProject(cwd: string): boolean {\n return CONFIG_FILES.some((f) => existsSync(join(cwd, f)))\n}\n\n/**\n * Check that the runtime dependencies this project's install path needs are declared in its\n * package.json — and, on the prebuilt path, that it declares none it must not.\n *\n * Turns the opaque \"cannot find module '@preact/signals-react'\" build failure into a\n * diagnosed condition with a fix. What it demands depends on `detectInstallPath`: requiring\n * `@cascivo/core` of a prebuilt app is not merely unhelpful, it is the opposite of what the\n * docs say, and following the advice makes a correct project wrong.\n *\n * `@cascivo/i18n`/`@cascivo/charts` stay advisory since not every project uses them, and an\n * `unknown` path emits nothing at all rather than guessing.\n */\nexport function checkProjectDependencies(cwd: string): DependencyFinding[] {\n let deps: Record<string, unknown> = {}\n try {\n const pkg = JSON.parse(readFileSync(join(cwd, 'package.json'), 'utf8')) as {\n dependencies?: Record<string, unknown>\n devDependencies?: Record<string, unknown>\n }\n deps = { ...pkg.dependencies, ...pkg.devDependencies }\n } catch {\n return [] // No readable package.json — nothing reliable to advise on.\n }\n const path = detectInstallPath(cwd)\n if (path === 'unknown') return []\n\n const pm = detectPackageManager(cwd)\n const findings: DependencyFinding[] = []\n\n const required = path === 'prebuilt' ? REQUIRED_PREBUILT_DEPS : REQUIRED_RUNTIME_DEPS\n for (const pkg of required) {\n if (deps[pkg] === undefined) {\n findings.push({\n package: pkg,\n required: true,\n hint: `detected ${path} install path — ${installHint(pm, [pkg])}`,\n })\n }\n }\n\n // Only meaningful on a pure prebuilt app. A hybrid legitimately needs `@cascivo/core`\n // for its copied source, so flagging it there would recreate the bug in mirror image.\n if (path === 'prebuilt') {\n for (const [pkg, reason] of Object.entries(FORBIDDEN_PREBUILT_DEPS)) {\n if (deps[pkg] !== undefined) {\n findings.push({ package: pkg, required: true, kind: 'forbidden', hint: reason })\n }\n }\n }\n\n for (const pkg of ON_DEMAND_DEPS) {\n if (deps[pkg] === undefined) {\n findings.push({ package: pkg, required: false, hint: installHint(pm, [pkg]) })\n }\n }\n return findings\n}\n\n/**\n * Two copies of `@cascivo/core` in one install.\n *\n * `@cascivo/react` and `@cascivo/charts` each depend on `@cascivo/core`, and the family\n * versions independently on 0.x. If their ranges do not overlap, the package manager\n * resolves a nested second copy — and because cascivo's reactivity is a module-level signal\n * registry, two copies means two registries: a signal written through one is invisible to\n * components subscribed through the other. Nothing errors. Handlers fire and the UI does\n * not move, which is the single hardest cascivo symptom to diagnose.\n *\n * Turning that into a named finding is the cheap half of the version-sprawl problem\n * (lockstep versioning is the expensive half, and is a policy decision).\n */\nexport interface DuplicateCoreFinding {\n /** Version at the install root, if any. */\n root: string | null\n /** Nested copies, as `<owner> → <version>`. */\n nested: string[]\n hint: string\n}\n\n/** Packages that carry their own `@cascivo/core` dependency. */\nconst CORE_DEPENDENTS = ['@cascivo/react', '@cascivo/charts', '@cascivo/flow', '@cascivo/editor']\n\nexport async function checkDuplicateCore(cwd: string): Promise<DuplicateCoreFinding | null> {\n const root = await readInstalledPackageVersion(cwd, '@cascivo/core')\n const nested: string[] = []\n for (const owner of CORE_DEPENDENTS) {\n const ownerRoot = join(cwd, 'node_modules', owner)\n if (!existsSync(ownerRoot)) continue\n const version = await readInstalledPackageVersion(ownerRoot, '@cascivo/core')\n // A nested copy only matters when it differs from the hoisted one.\n if (version !== null && version !== root) nested.push(`${owner} → ${version}`)\n }\n if (nested.length === 0) return null\n return {\n root,\n nested,\n hint:\n 'Align the @cascivo/* versions (they are released together — see breaking-changes.json) ' +\n 'and reinstall. Two copies of @cascivo/core means two signal registries: writes through ' +\n 'one are invisible to components subscribed through the other, with no error.',\n }\n}\n\nexport interface SignalsCompatFinding {\n /** 'error' = a runtime break (React 19 + signals <3); 'warning' = works but upgrade advised. */\n severity: 'error' | 'warning'\n detail: string\n hint: string\n}\n\n/**\n * Checks the installed `@preact/signals-react` against the installed React.\n * React 19 removed the `__SECRET_INTERNALS…` export that signals-react 2.x\n * imports, so a 2.x runtime on React 19 dies with a `SyntaxError` at module\n * evaluation (the 2026-07-20 report's blocker #2). cascivo peer-depends on\n * `>=3.0.0`, but a lockfile carried over from an earlier install can still pin\n * 2.x — this turns that into a diagnosed condition with a fix. Returns null when\n * either package is absent/unreadable (nothing reliable to advise on) or the\n * pairing is fine.\n */\nexport async function checkSignalsCompat(cwd: string): Promise<SignalsCompatFinding | null> {\n const [signals, react] = await Promise.all([\n readInstalledPackageVersion(cwd, '@preact/signals-react'),\n readInstalledPackageVersion(cwd, 'react'),\n ])\n if (signals === null) return null\n let signalsBelow3: boolean\n try {\n signalsBelow3 = compareVersions(signals, '3.0.0') < 0\n } catch {\n return null // unparsable installed signals version — don't advise on it\n }\n if (!signalsBelow3) return null\n const pm = detectPackageManager(cwd)\n const hint = installHint(pm, ['@preact/signals-react@^3'])\n let reactMajor: number | null = null\n if (react !== null) {\n const m = /^(\\d+)\\./.exec(react.trim())\n reactMajor = m ? Number(m[1]) : null\n }\n if (reactMajor !== null && reactMajor >= 19) {\n return {\n severity: 'error',\n detail: `@preact/signals-react ${signals} cannot run on React ${react} — React 19 removed an internal signals 2.x imports, so it fails at module load. Upgrade to signals-react 3.x.`,\n hint,\n }\n }\n return {\n severity: 'warning',\n detail: `@preact/signals-react ${signals} is below the required 3.x floor. It works on React 18 today but breaks the moment you move to React 19; upgrade now.`,\n hint,\n }\n}\n\n/** Vite SSR frameworks whose default setup needs `ssr.noExternal` for cascivo. */\nconst VITE_SSR_MARKERS = ['@tanstack/react-start', 'vite-ssr', '@remix-run/dev']\nconst VITE_CONFIG_FILES = ['vite.config.ts', 'vite.config.js', 'vite.config.mjs', 'vite.config.mts']\n\n/**\n * Advisory: on a Vite SSR framework, cascivo's per-component `.css` side-effect\n * imports crash a bare server-side ESM loader unless the packages are marked\n * `ssr.noExternal` (or the `cascivoSsr()` plugin is used). This warns when a known\n * Vite SSR framework is present but no vite config mentions either — the exact\n * cliff the 2026-07-20 report hit (blocker #1). A text match, not a gate. Returns\n * null when there's no Vite SSR framework or the config already handles it.\n */\n/**\n * Warn when the vendored components dir is not excluded from the project's formatter.\n *\n * Owning the code means your formatter rewrites it, and `cascivo update` then reports drift\n * on files you never edited. `cascivo init` writes the exclusion for you, but a project that\n * adopted cascivo before that existed — or that added Prettier afterwards — never got it.\n */\nexport function checkFormatterIgnore(cwd: string, outputDir: string): string | null {\n const pairs = [\n {\n configs: ['.prettierrc', '.prettierrc.json', '.prettierrc.js', 'prettier.config.js'],\n ignore: '.prettierignore',\n },\n { configs: ['.oxfmtrc', '.oxfmtrc.json'], ignore: '.oxfmtignore' },\n ]\n const dir = outputDir.replace(/\\/+$/, '')\n for (const { configs, ignore } of pairs) {\n if (!configs.some((f) => existsSync(join(cwd, f)))) continue\n let content = ''\n try {\n content = readFileSync(join(cwd, ignore), 'utf8')\n } catch {\n /* no ignore file at all */\n }\n if (content.split('\\n').some((l) => l.trim().replace(/\\/+$/, '') === dir)) continue\n return (\n `\"${dir}/\" is not excluded from your formatter. Running it will rewrite code you own, ` +\n `and \\`cascivo update\\` will then report drift on files you never edited. ` +\n `Add \"${dir}/\" to ${ignore}.`\n )\n }\n return null\n}\n\nconst ASTRO_CONFIG_FILES = [\n 'astro.config.mjs',\n 'astro.config.ts',\n 'astro.config.js',\n 'astro.config.mts',\n]\n\n/** Keyword every published cascivo CSS package carries (react >1.9.0): marks it Astro-safe. */\nconst ASTRO_COMPONENT_KEYWORD = 'astro-component'\n\n/**\n * True when `config` has a `resolve: { ... noExternal ... }` block. Astro prerenders in its own\n * Vite environment, which reads `resolve.noExternal` and ignores `ssr.noExternal`, so the two\n * must not be confused. Brace-balanced rather than a lazy regex: a `resolve` block commonly\n * holds a nested `alias: { ... }` before `noExternal`.\n */\nfunction setsResolveNoExternal(config: string): boolean {\n if (/\\bresolve\\s*\\.\\s*noExternal\\b/.test(config)) return true\n for (const match of config.matchAll(/\\bresolve\\s*:\\s*\\{/g)) {\n let depth = 1\n let i = match.index + match[0].length\n const start = i\n while (i < config.length && depth > 0) {\n const c = config[i]\n if (c === '{') depth++\n else if (c === '}') depth--\n i++\n }\n if (/\\bnoExternal\\b/.test(config.slice(start, i))) return true\n }\n return false\n}\n\n/**\n * True when the installed `@cascivo/react` declares `astro-component`. The file is third-party\n * input, so it is bound as `unknown` and narrowed before `keywords` is trusted.\n */\nfunction installedReactIsAstroSafe(cwd: string): boolean {\n let pkg: unknown\n try {\n pkg = JSON.parse(readFileSync(join(cwd, 'node_modules/@cascivo/react/package.json'), 'utf8'))\n } catch {\n return false\n }\n if (typeof pkg !== 'object' || pkg === null || !('keywords' in pkg)) return false\n const { keywords } = pkg\n return Array.isArray(keywords) && keywords.includes(ASTRO_COMPONENT_KEYWORD)\n}\n\n/**\n * Astro branch of {@link checkSsrConfig}. Without the integration, `resolve.noExternal`, or a\n * cascivo build that opts in via keyword, SSR'd islands render unstyled with no error.\n */\nfunction checkAstroConfig(cwd: string, configFile: string): string | null {\n // Only the prebuilt package's CSS can be externalized. Vendored source under src/ is compiled\n // by Vite itself, so a copy-paste-only project has nothing to warn about.\n const installPath = detectInstallPath(cwd)\n if (installPath !== 'prebuilt' && installPath !== 'hybrid') return null\n const config = readFileSync(join(cwd, configFile), 'utf8')\n if (/@cascivo\\/astro/.test(config)) return null\n if (setsResolveNoExternal(config)) return null\n if (installedReactIsAstroSafe(cwd)) return null\n const ssrOnly = /\\bssr\\s*:\\s*\\{[^}]*noExternal/.test(config)\n return (\n `${configFile} does not use the @cascivo/astro integration, so cascivo's CSS is ` +\n `externalized in Astro's prerender and islands render unstyled with no error` +\n (ssrOnly ? ` (Astro ignores ssr.noExternal; it reads resolve.noExternal)` : '') +\n `. Run \\`npx astro add @cascivo/astro\\`. ` +\n `Recipe: https://cascivo.com/docs/using-with-astro.md`\n )\n}\n\nexport function checkSsrConfig(cwd: string): string | null {\n // Astro first: it is not one of the Vite SSR frameworks below and needs a different config key.\n const astroConfig = ASTRO_CONFIG_FILES.find((f) => existsSync(join(cwd, f)))\n if (astroConfig !== undefined) return checkAstroConfig(cwd, astroConfig)\n\n let deps: Record<string, unknown> = {}\n try {\n const pkg = JSON.parse(readFileSync(join(cwd, 'package.json'), 'utf8')) as {\n dependencies?: Record<string, unknown>\n devDependencies?: Record<string, unknown>\n }\n deps = { ...pkg.dependencies, ...pkg.devDependencies }\n } catch {\n return null\n }\n const framework = VITE_SSR_MARKERS.find((m) => deps[m] !== undefined)\n if (framework === undefined) return null\n\n for (const file of VITE_CONFIG_FILES) {\n const path = join(cwd, file)\n if (!existsSync(path)) continue\n const config = readFileSync(path, 'utf8')\n // Either the manual noExternal entry or the cascivoSsr() plugin counts.\n if (/noExternal/.test(config) && /@cascivo/.test(config)) return null\n if (/cascivoSsr/.test(config)) return null\n }\n return (\n `${framework} is a Vite SSR framework, but no vite config marks the cascivo ` +\n `packages ssr.noExternal — an unconfigured SSR build crashes with ` +\n `\\`Unknown file extension \".css\"\\`. Add \\`ssr: { noExternal: [/^@cascivo\\\\//] }\\` ` +\n `(or the cascivoSsr() plugin from @cascivo/vite-plugin). ` +\n `Recipe: https://cascivo.com/docs/using-with-vite-ssr.md`\n )\n}\n\nconst BANNED_HOOKS = ['useState', 'useEffect', 'useLayoutEffect', 'useContext', 'useReducer']\n\n/**\n * Blank out comments and string/template-literal contents so identifier scans\n * only match real code. A mention of `useEffect` in a comment must not trip\n * the no-react-hooks rule. Single pass — a `//` inside a string (URLs) is not\n * treated as a comment.\n */\nexport function stripCommentsAndStrings(source: string): string {\n let out = ''\n let i = 0\n const n = source.length\n while (i < n) {\n const c = source[i]!\n const next = source[i + 1]\n if (c === '/' && next === '/') {\n while (i < n && source[i] !== '\\n') i++\n } else if (c === '/' && next === '*') {\n i += 2\n while (i < n && !(source[i] === '*' && source[i + 1] === '/')) i++\n i += 2\n } else if (c === \"'\" || c === '\"') {\n i++\n while (i < n && source[i] !== c) {\n if (source[i] === '\\\\') i++\n i++\n }\n i++\n out += c + c\n } else if (c === '`') {\n i++\n while (i < n && source[i] !== '`') {\n if (source[i] === '\\\\') i++\n i++\n }\n i++\n out += '``'\n } else {\n out += c\n i++\n }\n }\n return out\n}\n\nexport async function runDoctor(root: string): Promise<DoctorResult> {\n const violations: DoctorViolation[] = []\n const componentsDir = join(root, 'packages', 'components', 'src')\n if (!existsSync(componentsDir)) return { violations: [], passed: true }\n\n const components = readdirSync(componentsDir, { withFileTypes: true })\n .filter((d) => d.isDirectory())\n .map((d) => d.name)\n\n const reactIndex = join(root, 'packages', 'react', 'src', 'index.ts')\n const indexContent = existsSync(reactIndex) ? readFileSync(reactIndex, 'utf8') : ''\n\n for (const name of components) {\n const tsxPath = join(componentsDir, name, `${name}.tsx`)\n if (!existsSync(tsxPath)) continue\n const content = readFileSync(tsxPath, 'utf8')\n // Hook scan runs on code only; the aria-label scan below needs the\n // original source because it matches inside JSX string attributes.\n const code = stripCommentsAndStrings(content)\n\n for (const hook of BANNED_HOOKS) {\n if (new RegExp(`\\\\b${hook}\\\\b`).test(code)) {\n violations.push({\n file: tsxPath,\n rule: 'no-react-hooks',\n detail: `Banned hook '${hook}' in ${name}.tsx`,\n })\n }\n }\n\n if (/aria-label=\"[A-Z]/.test(content)) {\n violations.push({\n file: tsxPath,\n rule: 'no-hardcoded-strings',\n detail: `Hardcoded aria-label in ${name}.tsx — use t(builtin.*)`,\n })\n }\n\n if (!new RegExp(`from.*components/src/${name}`).test(indexContent)) {\n violations.push({\n file: tsxPath,\n rule: 'missing-react-export',\n detail: `${name} not exported from @cascivo/react`,\n })\n }\n }\n\n return { violations, passed: violations.length === 0 }\n}\n","import { writeFileSync } from 'node:fs'\nimport { basename, dirname, join } from 'node:path'\nimport type { CascadeConfig } from '../utils/config.js'\n\n// Inline validation types to avoid runtime dep on @cascivo/render\ninterface PropMeta {\n name: string\n type: string\n required?: boolean\n default?: string\n}\n\ninterface ComponentNode {\n component: string\n props?: Record<string, unknown>\n bind?: Record<string, string>\n events?: Record<string, string>\n children?: ComponentNode[] | string | { $t: string; params?: Record<string, string | number> }\n}\n\ninterface ViewConfig {\n state?: Record<string, string | number | boolean | null>\n view: {\n regions: Record<string, ComponentNode[]>\n }\n}\n\n/**\n * Sub-components installed into another component's registry directory. Every other name\n * resolves to its own kebab-case directory (`DataTable` → `data-table`); `generate.test.ts`\n * checks both rules against `registry.json`, so a new exception fails there, not in an\n * adopter's build.\n */\nconst OWNER_DIRECTORY: Record<string, string> = {\n AppFrame: 'app-shell',\n CardContent: 'card',\n CardFooter: 'card',\n CardHeader: 'card',\n CardTitle: 'card',\n ListItem: 'list',\n GridItem: 'grid',\n RadioCardGroup: 'radio-card',\n}\n\n/** The registry directory `cascivo add` installs `component` into. */\nexport function componentDirectory(component: string): string {\n return (\n OWNER_DIRECTORY[component] ?? component.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase()\n )\n}\n\n// Everything below is interpolated into TSX source, so the parser admits only names that\n// cannot break out of their position: identifiers for components, props and state keys,\n// dotted identifier paths for refs and translation keys.\nconst COMPONENT_RE = /^[A-Z][A-Za-z0-9]*$/\nconst PROP_RE = /^[A-Za-z_$][\\w$]*(?:-[\\w$]+)*$/\nconst IDENT_RE = /^[A-Za-z_$][\\w$]*$/\nconst REF_RE =\n /^\\$(?:data|actions|state|state\\.set|state\\.toggle)\\.[A-Za-z_$][\\w$]*(?:\\.[A-Za-z_$][\\w$]*)*$/\nconst KEY_RE = /^[\\w-]+(?:\\.[\\w-]+)*$/\n\nfunction fail(path: string, message: string): never {\n throw new Error(`Invalid ViewConfig at ${path}: ${message}`)\n}\n\nfunction isRecord(v: unknown): v is Record<string, unknown> {\n return typeof v === 'object' && v !== null && !Array.isArray(v)\n}\n\nfunction parseRefs(raw: unknown, path: string): Record<string, string> {\n if (!isRecord(raw)) fail(path, 'expected an object')\n const out: Record<string, string> = {}\n for (const [k, v] of Object.entries(raw)) {\n if (!PROP_RE.test(k)) fail(`${path}.${k}`, 'not a valid prop name')\n if (typeof v !== 'string' || !REF_RE.test(v)) {\n fail(`${path}.${k}`, 'expected a \"$data.*\", \"$actions.*\" or \"$state.*\" reference')\n }\n out[k] = v\n }\n return out\n}\n\nfunction parseTranslationRef(raw: Record<string, unknown>, path: string): { $t: string } {\n if (typeof raw.$t !== 'string' || !KEY_RE.test(raw.$t)) fail(`${path}.$t`, 'invalid key')\n return { $t: raw.$t }\n}\n\nfunction parseNode(raw: unknown, path: string): ComponentNode {\n if (!isRecord(raw)) fail(path, 'expected a component node object')\n const { component, props, bind, events, children } = raw\n if (typeof component !== 'string' || !COMPONENT_RE.test(component)) {\n fail(`${path}.component`, 'expected a PascalCase component name')\n }\n const node: ComponentNode = { component }\n if (props !== undefined) {\n if (!isRecord(props)) fail(`${path}.props`, 'expected an object')\n for (const [k, v] of Object.entries(props)) {\n if (!PROP_RE.test(k)) fail(`${path}.props.${k}`, 'not a valid prop name')\n if (isRecord(v) && '$t' in v) props[k] = parseTranslationRef(v, `${path}.props.${k}`)\n }\n node.props = props\n }\n if (bind !== undefined) node.bind = parseRefs(bind, `${path}.bind`)\n if (events !== undefined) node.events = parseRefs(events, `${path}.events`)\n if (children !== undefined) {\n if (typeof children === 'string') node.children = children\n else if (Array.isArray(children)) {\n node.children = children.map((c, i) => parseNode(c, `${path}.children[${i}]`))\n } else if (isRecord(children) && '$t' in children) {\n node.children = parseTranslationRef(children, `${path}.children`)\n } else fail(`${path}.children`, 'expected a string, a node array or a { $t } reference')\n }\n return node\n}\n\n/** Parse an untrusted ViewConfig (model output, a file) into one that is safe to emit as TSX. */\nexport function parseViewConfig(raw: unknown): ViewConfig {\n if (!isRecord(raw)) fail('$', 'expected an object')\n const { state, view } = raw\n const config: ViewConfig = { view: { regions: {} } }\n if (state !== undefined) {\n if (!isRecord(state)) fail('state', 'expected an object')\n const parsed: NonNullable<ViewConfig['state']> = {}\n for (const [k, v] of Object.entries(state)) {\n if (!IDENT_RE.test(k)) fail(`state.${k}`, 'not a valid identifier')\n if (v === null || typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean') {\n parsed[k] = v\n } else fail(`state.${k}`, 'expected a string, number, boolean or null')\n }\n config.state = parsed\n }\n if (!isRecord(view) || !isRecord(view.regions)) fail('view.regions', 'expected an object')\n for (const [name, nodes] of Object.entries(view.regions)) {\n if (!/^[\\w-]+$/.test(name)) fail(`view.regions.${name}`, 'not a valid region name')\n if (!Array.isArray(nodes)) fail(`view.regions.${name}`, 'expected an array of nodes')\n config.view.regions[name] = nodes.map((n, i) => parseNode(n, `view.regions.${name}[${i}]`))\n }\n return config\n}\n\nfunction isTranslationRef(v: unknown): v is { $t: string } {\n return typeof v === 'object' && v !== null && '$t' in v\n}\n\n/** A JS literal for a state initial value. */\nfunction serializeInitial(value: string | number | boolean | null): string {\n return typeof value === 'string' ? `'${value.replace(/'/g, \"\\\\'\")}'` : String(value)\n}\n\nfunction serializeProp(value: unknown): string {\n // A JSX attribute string has no escapes, so anything holding a quote goes through an\n // expression instead.\n if (typeof value === 'string')\n return value.includes('\"') ? `{${JSON.stringify(value)}}` : `\"${value}\"`\n if (typeof value === 'number' || typeof value === 'boolean') return `{${value}}`\n if (value === null) return `{null}`\n if (isTranslationRef(value)) return `{${JSON.stringify(value.$t)}} {/* i18n: ${value.$t} */}`\n return `{${JSON.stringify(value)}}`\n}\n\nfunction renderChildren(\n children: ComponentNode['children'],\n indent: string,\n componentPropNames: string[],\n knownComponents: Set<string>,\n): string {\n if (children === undefined) return ''\n // Text with JSX syntax in it (`{`, `<`) would be parsed as code; emit it as a string literal.\n if (typeof children === 'string') {\n return /[{}<>]/.test(children) ? `{${JSON.stringify(children)}}` : children\n }\n if (isTranslationRef(children)) return `{/* i18n: ${children.$t} */}`\n if (Array.isArray(children)) {\n return children\n .map((child) =>\n renderNode(child as ComponentNode, indent + ' ', componentPropNames, knownComponents),\n )\n .join('\\n')\n }\n return ''\n}\n\nfunction renderNode(\n node: ComponentNode,\n indent: string,\n _parentPropNames: string[],\n knownComponents: Set<string>,\n): string {\n const compName = node.component\n knownComponents.add(compName)\n const propParts: string[] = []\n\n if (node.props) {\n for (const [k, v] of Object.entries(node.props)) {\n propParts.push(`${k}=${serializeProp(v)}`)\n }\n }\n\n if (node.bind) {\n for (const [k, ref] of Object.entries(node.bind)) {\n if (ref.startsWith('$state.')) {\n propParts.push(`${k}={${ref.slice('$state.'.length)}.value}`)\n } else {\n propParts.push(`${k}={data.${ref.replace(/^\\$data\\./, '')}}`)\n }\n }\n }\n\n if (node.events) {\n for (const [k, ref] of Object.entries(node.events)) {\n if (ref.startsWith('$state.set.')) {\n const key = ref.slice('$state.set.'.length)\n propParts.push(`${k}={(e) => (${key}.value = coerceValue(e))}`)\n } else if (ref.startsWith('$state.toggle.')) {\n const key = ref.slice('$state.toggle.'.length)\n propParts.push(`${k}={() => (${key}.value = !${key}.value)}`)\n } else {\n propParts.push(`${k}={actions.${ref.replace(/^\\$actions\\./, '')}}`)\n }\n }\n }\n\n const propsStr = propParts.length > 0 ? ' ' + propParts.join(' ') : ''\n const childrenStr =\n node.children !== undefined\n ? renderChildren(node.children, indent, [], knownComponents)\n : undefined\n\n if (childrenStr !== undefined && childrenStr !== '') {\n return `${indent}<${compName}${propsStr}>\\n${indent} ${childrenStr}\\n${indent}</${compName}>`\n }\n return `${indent}<${compName}${propsStr} />`\n}\n\nfunction collectBindAndEvents(nodes: ComponentNode[]): {\n boundProps: string[]\n actionProps: string[]\n} {\n const boundProps: string[] = []\n const actionProps: string[] = []\n function walk(node: ComponentNode) {\n if (node.bind) {\n for (const ref of Object.values(node.bind)) {\n if (ref.startsWith('$state.')) continue // view-local state, not a host-data prop\n const path = ref.replace(/^\\$data\\./, '')\n if (!boundProps.includes(path)) boundProps.push(path)\n }\n }\n if (node.events) {\n for (const ref of Object.values(node.events)) {\n if (ref.startsWith('$state.')) continue // state writer, not a host action\n const name = ref.replace(/^\\$actions\\./, '')\n if (!actionProps.includes(name)) actionProps.push(name)\n }\n }\n if (Array.isArray(node.children)) {\n node.children.forEach(walk)\n }\n }\n nodes.forEach(walk)\n return { boundProps, actionProps }\n}\n\n/** True if any node writes state via \"$state.set.*\" (needs the coerceValue helper). */\nfunction usesStateSetter(nodes: ComponentNode[]): boolean {\n const walk = (node: ComponentNode): boolean => {\n if (node.events && Object.values(node.events).some((r) => r.startsWith('$state.set.'))) {\n return true\n }\n return Array.isArray(node.children) ? node.children.some(walk) : false\n }\n return nodes.some(walk)\n}\n\n/**\n * Where components are imported from: `dir` is the copy-paste components directory (one\n * import per registry directory), `package` a prebuilt package such as `@cascivo/react`.\n */\nexport type ImportSource = { dir: string } | { package: string }\n\nfunction importLines(components: Set<string>, source: ImportSource): string {\n const names = [...components].sort()\n if ('package' in source) return `import { ${names.join(', ')} } from '${source.package}'`\n const byDirectory = new Map<string, string[]>()\n for (const name of names) {\n const directory = componentDirectory(name)\n byDirectory.set(directory, [...(byDirectory.get(directory) ?? []), name])\n }\n return [...byDirectory]\n .sort(([a], [b]) => a.localeCompare(b))\n .map(\n ([directory, members]) =>\n `import { ${members.join(', ')} } from '${source.dir}/${directory}'`,\n )\n .join('\\n')\n}\n\nexport function generateTsx(\n config: ViewConfig,\n _propMetas: Map<string, PropMeta[]>,\n source: ImportSource,\n): string {\n const knownComponents = new Set<string>()\n const allNodes = Object.values(config.view.regions).flat()\n const { boundProps, actionProps } = collectBindAndEvents(allNodes)\n const stateEntries = Object.entries(config.state ?? {})\n const hasState = stateEntries.length > 0\n const needsCoerce = usesStateSetter(allNodes)\n\n const regionBlocks = Object.entries(config.view.regions)\n .map(([regionName, nodes]) => {\n const rendered = nodes.map((n) => renderNode(n, ' ', [], knownComponents)).join('\\n')\n return ` <div className=\"region-${regionName}\">\\n${rendered}\\n </div>`\n })\n .join('\\n')\n\n const hasData = boundProps.length > 0\n const hasActions = actionProps.length > 0\n\n const dataParam = hasData\n ? `data: {\\n${boundProps.map((p) => ` ${p.replace(/\\./g, '_')}: unknown // TODO: type your data`).join('\\n')}\\n }`\n : ''\n\n const actionsParam = hasActions\n ? `actions: {\\n${actionProps.map((a) => ` ${a}: (...args: unknown[]) => unknown`).join('\\n')}\\n }`\n : ''\n\n const params = [dataParam, actionsParam].filter(Boolean).join(',\\n ')\n const propsType = params ? `{\\n ${params}\\n}` : '{}'\n\n const coreImport = hasState ? \"\\nimport { useSignal, useSignals } from '@cascivo/core'\" : ''\n const coerceHelper = needsCoerce\n ? `\n/** Unwrap a DOM event into the value a state setter should store. */\nfunction coerceValue(e: unknown) {\n const t = (e as { target?: { type?: string; checked?: boolean; value?: unknown } })?.target\n if (t) return t.type === 'checkbox' || t.type === 'radio' ? t.checked : t.value\n return e\n}\n`\n : ''\n const stateDecls = hasState\n ? ' useSignals()\\n' +\n stateEntries.map(([k, v]) => ` const ${k} = useSignal(${serializeInitial(v)})`).join('\\n') +\n '\\n'\n : ''\n\n return `import React from 'react'${coreImport}\n${importLines(knownComponents, source)}\n${coerceHelper}\ninterface PageProps ${propsType}\n\nexport function GeneratedPage({ ${hasData ? 'data, ' : ''}${hasActions ? 'actions' : ''} }: PageProps) {\n${stateDecls} return (\n <div className=\"cascivo-view\">\n${regionBlocks}\n </div>\n )\n}\n`\n}\n\nexport async function generate(args: string[], config: CascadeConfig): Promise<void> {\n const outArg = args.find((_, i) => args[i - 1] === '--out')\n const inputArg = args.find((a) => !a.startsWith('--'))\n const componentsDirArg = args.find((_, i) => args[i - 1] === '--components-dir')\n const fromArg = args.find((_, i) => args[i - 1] === '--from')\n\n if (!inputArg) {\n console.error(\n 'Usage: cascivo generate <config.json> [--out output.tsx] [--components-dir ./src/components/ui | --from @cascivo/react]',\n )\n process.exitCode = 1\n return\n }\n if (fromArg && componentsDirArg) {\n console.error('Pass --from or --components-dir, not both.')\n process.exitCode = 1\n return\n }\n\n const { readFileSync } = await import('node:fs')\n let viewConfig: ViewConfig\n try {\n const raw: unknown = JSON.parse(readFileSync(inputArg, 'utf-8'))\n viewConfig = parseViewConfig(raw)\n } catch (e) {\n console.error(`${inputArg}: ${e instanceof Error ? e.message : String(e)}`)\n process.exitCode = 1\n return\n }\n\n // Prop metas are not available from the CLI registry type, so this passes an empty map.\n // (There used to be a `fetchRegistry` call here whose result was discarded — a network\n // round-trip on every `cascivo generate` that fed nothing. `noUnusedLocals` surfaced it.)\n const propMetas = new Map<string, PropMeta[]>()\n\n const source: ImportSource = fromArg\n ? { package: fromArg }\n : { dir: componentsDirArg ?? config.outputDir ?? './src/components/ui' }\n const tsx = generateTsx(viewConfig, propMetas, source)\n\n const outPath = outArg ?? join(dirname(inputArg), `${basename(inputArg, '.json')}.tsx`)\n\n writeFileSync(outPath, tsx, 'utf-8')\n console.log(`Generated ${outPath}`)\n\n // Try to format with vp fmt or prettier\n try {\n const { spawnSync } = await import('node:child_process')\n const fmtResult = spawnSync('pnpm', ['exec', 'vp', 'fmt', outPath], {\n encoding: 'utf8',\n stdio: 'inherit',\n })\n if (fmtResult.status !== 0) {\n const prettyResult = spawnSync('npx', ['--yes', 'prettier', '--write', outPath], {\n encoding: 'utf8',\n stdio: 'inherit',\n })\n if (prettyResult.status !== 0) {\n console.log('(Note: formatter not found — output may need manual formatting)')\n }\n }\n } catch {\n // formatting is best-effort\n }\n}\n","import { createInterface } from 'node:readline/promises'\nimport { stdin, stdout } from 'node:process'\nimport { existsSync, readFileSync, writeFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport {\n DEFAULT_CONFIG,\n detectPackageManager,\n installHint,\n THEMES,\n type ThemeName,\n} from '../utils/config.js'\nimport { installPackages } from '../utils/exec.js'\nimport { writeFileSafe } from '../utils/fs.js'\nimport { flagValue, resolvePackageManagerFlag } from '../utils/args.js'\n\n/**\n * Everything an app needs to build with copied cascivo source: the runtime\n * packages plus the `@preact/signals-react` peer of `@cascivo/core` (installed\n * explicitly rather than relying on peer auto-linking, which yarn never does and\n * npm skips when its install crashes). `@cascivo/i18n`/`@cascivo/charts` are\n * added on demand by `cascivo add` when a component or chart declares them.\n */\nconst RUNTIME_DEPS = [\n '@cascivo/core',\n '@cascivo/tokens',\n '@cascivo/themes',\n '@preact/signals-react',\n]\n\n/** Dev-only: `cascivo` provides the `CascadeConfig` type the generated config imports. */\nconst DEV_DEPS = ['cascivo']\n\nasync function promptTheme(): Promise<ThemeName> {\n const rl = createInterface({ input: stdin, output: stdout })\n try {\n const answer = (await rl.question(`Theme? (${THEMES.join('/')}) [light]: `))\n .trim()\n .toLowerCase()\n return (THEMES as readonly string[]).includes(answer) ? (answer as ThemeName) : 'light'\n } finally {\n rl.close()\n }\n}\n\nfunction configFileContents(theme: ThemeName): string {\n return `import type { CascadeConfig } from 'cascivo'\n\nconst config: CascadeConfig = {\n registry: '${DEFAULT_CONFIG.registry}',\n outputDir: '${DEFAULT_CONFIG.outputDir}',\n theme: '${theme}',\n}\n\nexport default config\n`\n}\n\nconst ESLINT_CONFIGS = [\n 'eslint.config.js',\n 'eslint.config.mjs',\n 'eslint.config.cjs',\n 'eslint.config.ts',\n '.eslintrc',\n '.eslintrc.js',\n '.eslintrc.cjs',\n '.eslintrc.json',\n '.eslintrc.yml',\n '.eslintrc.yaml',\n]\n\n/**\n * Copied cascivo source can trip a strict host ESLint config on stylistic rules.\n * If the project has an ESLint config, point at the scoping recipe rather than\n * editing the adopter's config for them.\n */\nfunction hintEslintIfPresent(cwd: string): void {\n if (!ESLINT_CONFIGS.some((f) => existsSync(join(cwd, f)))) return\n console.log('\\nESLint: copied cascivo source may trip a strict host config on stylistic rules.')\n console.log(' Scope them off your components dir — see docs/USING-WITH-STRICT-ESLINT.md')\n}\n\n/**\n * Write dependency entries into `package.json` so a failed install still leaves a\n * DECLARATIVE-complete project, one `install` away from working.\n *\n * The reported failure: one unrelated bad version range elsewhere in the adopter's\n * `package.json` made `pnpm add` exit non-zero. cascivo had already written\n * `cascivo.config.ts`, so the project claimed to be cascivo-configured with none of the\n * runtime present, and the printed advice (\"install them yourself\") was the same command\n * that had just failed. Recording the dependencies is the difference between \"recoverable\n * with one command\" and \"figure out what was supposed to be here\".\n *\n * Never overwrites an entry that already exists — the app's own pin wins.\n */\nfunction recordDependencies(cwd: string, packages: string[], opts: { dev: boolean }): string[] {\n const pkgPath = join(cwd, 'package.json')\n if (!existsSync(pkgPath)) return []\n let pkg: Record<string, unknown>\n try {\n pkg = JSON.parse(readFileSync(pkgPath, 'utf8')) as Record<string, unknown>\n } catch {\n return []\n }\n const field = opts.dev ? 'devDependencies' : 'dependencies'\n const deps = (pkg[field] ??= {}) as Record<string, string>\n const added: string[] = []\n for (const name of packages) {\n if (deps[name] !== undefined) continue\n deps[name] = 'latest'\n added.push(name)\n }\n if (added.length === 0) return []\n writeFileSync(pkgPath, `${JSON.stringify(pkg, null, 2)}\\n`, 'utf8')\n return added\n}\n\n/** Formatter ignore files, in the order a project is likely to use them. */\nconst FORMATTER_IGNORES = [\n {\n config: ['.prettierrc', '.prettierrc.json', '.prettierrc.js', 'prettier.config.js'],\n ignore: '.prettierignore',\n },\n { config: ['.oxfmtrc', '.oxfmtrc.json'], ignore: '.oxfmtignore' },\n] as const\n\n/**\n * Exclude the vendored components dir from the project's formatter.\n *\n * Owning the code means your formatter reformats it, and then `cascivo update` reports drift\n * on files you never touched. This ACTS rather than hints: the ESLint equivalent below only\n * prints a pointer, and an adopter ran `prettier --write .` before ever reading it.\n *\n * Idempotent, and never rewrites an existing line.\n */\nfunction ensureFormatterIgnore(cwd: string, outputDir: string): void {\n const line = `${outputDir.replace(/\\/+$/, '')}/`\n for (const { config, ignore } of FORMATTER_IGNORES) {\n const hasFormatter =\n config.some((f) => existsSync(join(cwd, f))) || hasPrettierKeyInPackageJson(cwd, ignore)\n if (!hasFormatter) continue\n\n const path = join(cwd, ignore)\n const current = existsSync(path) ? readFileSync(path, 'utf8') : ''\n if (current.split('\\n').some((l) => l.trim() === line)) continue\n\n const banner = '# cascivo: vendored component source — you own it, so do not reformat it\\n'\n const next =\n current === '' ? banner + line + '\\n' : `${current.replace(/\\n*$/, '\\n')}\\n${banner}${line}\\n`\n writeFileSync(path, next, 'utf8')\n console.log(\n `\\nAdded \"${line}\" to ${ignore} (so your formatter does not rewrite copied source).`,\n )\n }\n}\n\n/** `prettier` key in package.json counts as a Prettier config — only relevant to .prettierignore. */\nfunction hasPrettierKeyInPackageJson(cwd: string, ignore: string): boolean {\n if (ignore !== '.prettierignore') return false\n const pkgPath = join(cwd, 'package.json')\n if (!existsSync(pkgPath)) return false\n try {\n return 'prettier' in (JSON.parse(readFileSync(pkgPath, 'utf8')) as Record<string, unknown>)\n } catch {\n return false\n }\n}\n\nconst ASTRO_CONFIG_FILES = [\n 'astro.config.mjs',\n 'astro.config.ts',\n 'astro.config.js',\n 'astro.config.mts',\n]\n\n/** Astro prerenders in its own Vite environment, so the generic steps above are not enough. */\nfunction printAstroNextSteps(cwd: string): void {\n if (!ASTRO_CONFIG_FILES.some((f) => existsSync(join(cwd, f)))) return\n console.log('\\nAstro detected. Next steps:')\n console.log(\n ' npx astro add @cascivo/astro # layer order, theme and no-flash script, zero config',\n )\n console.log(' Compose compound components (Tabs, Accordion, Popover…) inside one .tsx island:')\n console.log(\n ' Astro renders each .astro child separately, so React context cannot reach their parts.',\n )\n console.log(' Hydrate only the interactive islands: client:visible or client:load on those,')\n console.log(' and leave static pieces without a client: directive.')\n}\n\n/** The \"here's everything you need\" summary, printed once at the end of init. */\nfunction printDependencySummary(): void {\n console.log('\\nDependencies')\n console.log(` runtime: ${RUNTIME_DEPS.join(' ')}`)\n console.log(` dev: ${DEV_DEPS.join(' ')} (types for cascivo.config.ts)`)\n console.log(\n ' on demand: @cascivo/i18n, @cascivo/charts — added by `cascivo add` when a component or chart needs them',\n )\n}\n\nexport async function init(args: string[] = [], cwd: string = process.cwd()): Promise<void> {\n const yes = args.includes('--yes') || args.includes('-y')\n const noInstall = args.includes('--no-install')\n const themeArg = flagValue(args, 'theme')?.toLowerCase()\n\n if (themeArg !== undefined && !(THEMES as readonly string[]).includes(themeArg)) {\n console.error(`Unknown theme \"${themeArg}\". Available: ${THEMES.join(', ')}`)\n process.exitCode = 1\n return\n }\n\n const pmFlag = resolvePackageManagerFlag(args)\n if ('error' in pmFlag) {\n console.error(pmFlag.error)\n process.exitCode = 1\n return\n }\n const pm = detectPackageManager(cwd, pmFlag.pm ? { override: pmFlag.pm } : {})\n\n // Prompt only when interactive: --yes, a valid --theme, or a non-TTY stdin\n // (CI, agents, pipes) all take the default without blocking.\n const interactive = themeArg === undefined && !yes && stdin.isTTY\n const theme: ThemeName = (themeArg as ThemeName) ?? (interactive ? await promptTheme() : 'light')\n\n // Write the config before installing so a failed install can never leave a\n // half-initialized project (the report's npm-in-pnpm crash left exactly this).\n const configPath = join(cwd, 'cascivo.config.ts')\n await writeFileSafe(configPath, configFileContents(theme))\n console.log(`\\nCreated cascivo.config.ts (theme: ${theme})`)\n\n if (noInstall) {\n console.log('\\nSkipped install (--no-install). Install the dependencies yourself:')\n console.log(` ${installHint(pm, RUNTIME_DEPS)}`)\n console.log(` ${installHint(pm, DEV_DEPS, { dev: true })}`)\n } else {\n const runtimeOk = installPackages(RUNTIME_DEPS, cwd, { pm })\n const devOk = installPackages(DEV_DEPS, cwd, { pm, dev: true })\n if (!runtimeOk || !devOk) {\n // Never leave a project \"configured but not installed\". Record what it needs, say\n // plainly what state it is in, and give a command that is not the one that just failed.\n const recorded = [\n ...(runtimeOk ? [] : recordDependencies(cwd, RUNTIME_DEPS, { dev: false })),\n ...(devOk ? [] : recordDependencies(cwd, DEV_DEPS, { dev: true })),\n ]\n console.error(\n '\\nInstall failed — cascivo.config.ts was written but the packages are not installed.',\n )\n if (recorded.length > 0) {\n console.error(\n `Wrote ${recorded.length} dependency entries to package.json: ${recorded.join(', ')}`,\n )\n console.error(`Recover with:\\n ${pm} install`)\n } else {\n console.error(\n `Recover with:\\n ${installHint(pm, RUNTIME_DEPS)}\\n ${installHint(pm, DEV_DEPS, { dev: true })}`,\n )\n }\n process.exitCode = 1\n }\n }\n\n // The COMPLETE stylesheet wiring, in import order. Printing only the theme line left an\n // adopter to discover the tokens sheet by debugging a grayscale app, and the charts sheet\n // by shipping a chart whose screen-reader data table rendered visibly.\n console.log('\\nStylesheets — import these once, in this order, in your entry file:')\n console.log(\n ` import '@cascivo/tokens' // primitive tokens — every --cascivo-* value`,\n )\n console.log(\n ` import '@cascivo/themes/${theme}.css'${' '.repeat(Math.max(1, 16 - theme.length))}// the ${theme} theme's semantic values`,\n )\n console.log(\n ` // …then your component CSS (\\`cascivo add\\` writes .module.css beside each component)`,\n )\n console.log('\\nThen set the theme on your root element:')\n console.log(` <html data-theme=\"${theme}\">`)\n console.log('\\nSwitching themes at runtime? Use a bundle instead of the single theme:')\n console.log(\" import '@cascivo/themes/light-dark.css' // light + dark — the common case\")\n console.log(\" import '@cascivo/themes/all.css' // all twelve themes\")\n console.log(\" import { ThemeProvider } from '@cascivo/core'\")\n // The single most likely first-day bug, and it has no error message: a component that\n // reads `signal.value` in render never re-renders without this, so handlers fire and the\n // UI just sits there. Consumer apps run no signals transform, so it is never automatic.\n console.log('\\nIn YOUR components, when you read a signal during render:')\n console.log(\" import { useSignals } from '@cascivo/core'\")\n console.log(' function MyComponent() {')\n console.log(' useSignals() // ← first statement, or the component never re-renders')\n console.log(' return <span>{count.value}</span>')\n console.log(' }')\n console.log('\\nAdding a chart later? Charts ship as an npm package with their own stylesheet:')\n console.log(\" import '@cascivo/charts/styles.css' // `cascivo add <chart>` reminds you\")\n\n printDependencySummary()\n ensureFormatterIgnore(cwd, DEFAULT_CONFIG.outputDir)\n hintEslintIfPresent(cwd)\n printAstroNextSteps(cwd)\n\n // The version spread (`@cascivo/react@0.18.x` next to `@cascivo/platform@0.0.x`) is first\n // seen HERE, in the install list this command just printed — not 249 lines into a guide.\n // A 2026-08-21 reporter flagged that it reads as \"half of this is pre-alpha\" and that the\n // answer, while documented, was only reachable if you already knew to look for it.\n console.log('\\nPackages version independently (changesets), so a low number means fewer')\n console.log('releases, not less finished. Pin exact versions, and before upgrading run:')\n console.log(' cascivo doctor --drift # reads breaking-changes.json, reports API drift')\n\n console.log('\\nAdd components with: cascivo add <name>')\n}\n","import { existsSync } from 'node:fs'\nimport { join } from 'node:path'\nimport type { CascadeConfig } from '../utils/config.js'\nimport { fetchRegistry, type RegistryComponent } from '../utils/registry.js'\n\nexport interface ListOptions {\n installed?: boolean\n}\n\nconst TYPE_LABELS: Record<string, string> = {\n component: 'Components',\n layout: 'Layouts (copy-paste)',\n block: 'Blocks (copy-paste)',\n section: 'Sections (copy-paste)',\n chart: 'Charts (npm: @cascivo/charts)',\n flow: 'Flow (npm: @cascivo/flow)',\n editor: 'Editor (npm: @cascivo/editor)',\n}\n\n/**\n * Deprecation marker for the listing.\n *\n * Shown at DISCOVERY time on purpose. `overflow-menu` carried a `@deprecated` JSDoc in its\n * source for months, which an adopter only meets after they have already vendored the file —\n * and it pointed at an import path that cannot resolve on either install path.\n */\nexport function deprecationSuffix(c: RegistryComponent): string {\n return c.deprecated ? ` ⚠ deprecated → ${c.deprecated.replacement}` : ''\n}\n\n/** Render a group of entries as an aligned text table (no section header). */\nfunction formatGroup(entries: RegistryComponent[]): string {\n const rows = entries.map(\n (c) => [c.name, c.category, c.description + deprecationSuffix(c)] as const,\n )\n const headers = ['Name', 'Category', 'Description'] as const\n const widths = headers.map((h, i) => Math.max(h.length, ...rows.map((r) => (r[i] ?? '').length)))\n\n const line = (cells: readonly string[]) =>\n cells\n .map((cell, i) => cell.padEnd(widths[i] ?? cell.length))\n .join(' ')\n .trimEnd()\n\n const sep = widths.map((w) => '-'.repeat(w)).join(' ')\n return [line(headers), sep, ...rows.map(line)].join('\\n')\n}\n\n/** Render the component list as an aligned text table, grouped by type. */\nexport function formatList(components: RegistryComponent[]): string {\n if (components.length === 0) return 'No components found.'\n\n // Determine whether any entry has an explicit type — if not, render flat.\n const hasTypes = components.some((c) => c.type !== undefined)\n if (!hasTypes) return formatGroup(components)\n\n // Group by type, preserving insertion order of first occurrence.\n const groups = new Map<string, RegistryComponent[]>()\n for (const c of components) {\n const key = c.type ?? 'component'\n if (!groups.has(key)) groups.set(key, [])\n groups.get(key)!.push(c)\n }\n\n const sections: string[] = []\n for (const [key, entries] of groups) {\n const label = TYPE_LABELS[key] ?? key\n sections.push(`${label}\\n${formatGroup(entries)}`)\n }\n return sections.join('\\n\\n')\n}\n\nexport async function list(config: CascadeConfig, options: ListOptions = {}): Promise<void> {\n const registry = await fetchRegistry(config.registry)\n let components = registry.components\n\n if (options.installed) {\n components = components.filter((c) => {\n const outputName = c.name.includes('/') ? c.name.split('/').pop()! : c.name\n return existsSync(join(process.cwd(), config.outputDir, outputName))\n })\n }\n\n console.log(formatList(components))\n console.log(\n '\\nTip: install any entry by its bare name — `cascivo add flex` resolves to ' +\n '`layout/flex`. Layout primitives (Flex, Grid, AutoGrid, Columns, Spacer, ' +\n 'Center) replace inline-style layout; see docs/cookbooks/layout-and-spacing.md.',\n )\n}\n","import { existsSync } from 'node:fs'\nimport { readFile } from 'node:fs/promises'\nimport { resolve, dirname } from 'node:path'\nimport {\n buildRegistry,\n validateIndex,\n parseLegacyRegistry,\n isTemplateItem,\n validateTemplate,\n type RegistryIndex,\n} from '@cascivo/registry'\n\n/**\n * Validate every template item in an index: each must pass `validateTemplate`,\n * and any bare `registryDependencies` not present in the same index produce a\n * warning (they are expected to resolve from another registry at install time).\n * Returns `{ errors, warnings }`.\n */\nexport function validateTemplates(index: RegistryIndex): { errors: string[]; warnings: string[] } {\n const errors: string[] = []\n const warnings: string[] = []\n const localNames = new Set(index.items.map((i) => i.name))\n\n for (const item of index.items) {\n if (!isTemplateItem(item)) continue\n for (const e of validateTemplate(item)) errors.push(`template \"${item.name}\": ${e}`)\n for (const dep of item.registryDependencies ?? []) {\n const isCrossRegistry = dep.includes('/') || dep.startsWith('@') || dep.startsWith('http')\n if (!isCrossRegistry && !localNames.has(dep)) {\n warnings.push(\n `template \"${item.name}\": component \"${dep}\" is not in this index — it must resolve from another registry at install time`,\n )\n }\n }\n }\n\n return { errors, warnings }\n}\n\nexport async function registryBuild(args: string[]): Promise<void> {\n let inFile = 'cascade-registry.json'\n let outDir = 'public/r'\n\n for (let i = 0; i < args.length; i++) {\n if (args[i] === '--in' && args[i + 1]) {\n inFile = args[i + 1]!\n i++\n } else if (args[i] === '--out' && args[i + 1]) {\n outDir = args[i + 1]!\n i++\n }\n }\n\n const inPath = resolve(inFile)\n if (!existsSync(inPath)) {\n console.error(`cascade registry build: file not found: ${inPath}`)\n process.exitCode = 1\n return\n }\n\n const raw = JSON.parse(await readFile(inPath, 'utf8')) as unknown\n const indexBase = dirname(inPath)\n void indexBase\n\n let index = (() => {\n if (\n typeof raw === 'object' &&\n raw !== null &&\n (raw as Record<string, unknown>)['schemaVersion'] === 2\n ) {\n return raw\n }\n return parseLegacyRegistry(raw)\n })()\n\n const result = validateIndex(index)\n if (result.warnings.length > 0) {\n for (const w of result.warnings) console.warn(`warn: ${w}`)\n }\n if (!result.ok) {\n for (const e of result.errors) console.error(`error: ${e}`)\n process.exitCode = 1\n return\n }\n\n const templateResult = validateTemplates(index as RegistryIndex)\n for (const w of templateResult.warnings) console.warn(`warn: ${w}`)\n if (templateResult.errors.length > 0) {\n for (const e of templateResult.errors) console.error(`error: ${e}`)\n process.exitCode = 1\n return\n }\n\n const outPath = resolve(outDir)\n await buildRegistry(index as Parameters<typeof buildRegistry>[0], outPath)\n console.log(`cascade registry build: wrote static output to ${outPath}`)\n}\n","import type { CascadeConfig } from '../utils/config.js'\nimport { fetchRegistry } from '../utils/registry.js'\nimport { fetchJson } from '../utils/http.js'\nimport { validateItem } from '@cascivo/registry'\nimport type { RegistryItem } from '@cascivo/registry'\n\ninterface SearchResult {\n name: string\n version: string\n description: string\n registry?: string\n}\n\nfunction matchesQuery(item: RegistryItem, query: string): boolean {\n const q = query.toLowerCase()\n return (\n item.name.toLowerCase().includes(q) ||\n item.description.toLowerCase().includes(q) ||\n item.tags.some((t) => t.toLowerCase().includes(q))\n )\n}\n\nexport async function search(args: string[], config: CascadeConfig): Promise<void> {\n const nsFlag = args.indexOf('--registry')\n const registryFilter = nsFlag !== -1 ? args[nsFlag + 1] : undefined\n const queryParts = args.filter((a, i) => a !== '--registry' && args[i - 1] !== '--registry')\n const query = queryParts.join(' ').trim()\n\n if (!query) {\n console.error('Usage: cascivo search <query> [--registry @ns]')\n return\n }\n\n const results: SearchResult[] = []\n\n if (!registryFilter) {\n // Search default registry\n const registry = await fetchRegistry(config.registry)\n for (const c of registry.components) {\n const item = c as unknown as RegistryItem\n if (matchesQuery(item, query)) {\n results.push({ name: c.name, version: c.version, description: c.description })\n }\n }\n }\n\n // Search configured namespace registries\n const registries = config.registries ?? {}\n for (const [ns, nsCfg] of Object.entries(registries)) {\n if (registryFilter && ns !== registryFilter) continue\n try {\n const template = typeof nsCfg === 'string' ? nsCfg : nsCfg.url\n const indexUrl = template.replace(/{name}[^$]*$/, '').replace(/\\/$/, '') + '/registry.json'\n const raw: unknown = await fetchJson(indexUrl)\n const entries =\n typeof raw === 'object' && raw !== null && Array.isArray((raw as { items?: unknown }).items)\n ? ((raw as { items: unknown[] }).items ?? [])\n : []\n // Search is read-only and lists many registries at once, so one malformed\n // entry skips rather than failing the whole query.\n for (const entry of entries) {\n if (!validateItem(entry).ok) continue\n const item = entry as RegistryItem\n if (matchesQuery(item, query)) {\n results.push({\n name: `${ns}/${item.name}`,\n version: item.version,\n description: item.description,\n registry: ns,\n })\n }\n }\n } catch {\n console.warn(` [warn] Could not search ${ns} registry`)\n }\n }\n\n if (results.length === 0) {\n console.log('No results found.')\n return\n }\n\n for (const r of results) {\n const reg = r.registry ? ` (${r.registry})` : ''\n console.log(`${r.name}@${r.version}${reg} — ${r.description}`)\n }\n}\n","export type FontFamily = 'system' | 'geometric' | 'humanist' | 'transitional' | 'mono'\n\nexport const RADIUS_STOPS = [0, 0.25, 0.375, 0.5, 0.75, 1.5] as const\nexport type RadiusStop = (typeof RADIUS_STOPS)[number]\n\nexport const RADIUS_LABELS: Record<RadiusStop, string> = {\n 0: 'none',\n 0.25: 'sm',\n 0.375: 'md',\n 0.5: 'lg',\n 0.75: 'xl',\n 1.5: 'pill',\n}\n\nexport type ThemeConfig = {\n baseMode: 'light' | 'dark'\n accentHue: number\n accentChroma: number\n radiusBase: RadiusStop\n fontFamily: FontFamily\n presetId: string | null\n}\n\nexport const DEFAULT_CONFIG: ThemeConfig = {\n baseMode: 'light',\n accentHue: 250,\n accentChroma: 0.2,\n radiusBase: 0.375,\n fontFamily: 'system',\n presetId: 'light',\n}\n","import { DEFAULT_CONFIG, type ThemeConfig } from './config.js'\n\n/** Encode a theme config as a URL-safe base64 string (shared by the /create URL\n * hash and the CLI `--from` handoff, so the two never drift). */\nexport function configToHash(config: ThemeConfig): string {\n const json = JSON.stringify(config)\n return btoa(json).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')\n}\n\n/** Decode a hash produced by {@link configToHash}. Returns null on malformed\n * input; unknown/missing fields fall back to {@link DEFAULT_CONFIG}. */\nexport function hashToConfig(hash: string): ThemeConfig | null {\n if (!hash) return null\n try {\n const base64 = hash.replace(/-/g, '+').replace(/_/g, '/')\n const json = atob(base64)\n const parsed = JSON.parse(json) as Partial<ThemeConfig>\n return {\n baseMode: parsed.baseMode === 'dark' ? 'dark' : 'light',\n accentHue: typeof parsed.accentHue === 'number' ? parsed.accentHue : DEFAULT_CONFIG.accentHue,\n accentChroma:\n typeof parsed.accentChroma === 'number' ? parsed.accentChroma : DEFAULT_CONFIG.accentChroma,\n radiusBase: (typeof parsed.radiusBase === 'number'\n ? parsed.radiusBase\n : DEFAULT_CONFIG.radiusBase) as ThemeConfig['radiusBase'],\n fontFamily: parsed.fontFamily ?? DEFAULT_CONFIG.fontFamily,\n presetId: parsed.presetId ?? null,\n }\n } catch {\n return null\n }\n}\n","import type { ThemeConfig } from './config.js'\n\nconst FONT_STACKS: Record<string, string> = {\n geometric: \"'Futura', 'Century Gothic', 'Trebuchet MS', ui-sans-serif, sans-serif\",\n humanist: \"'Gill Sans', 'Trebuchet MS', 'Calibri', ui-sans-serif, sans-serif\",\n transitional: \"'Optima', 'Candara', 'Palatino Linotype', ui-sans-serif, sans-serif\",\n mono: \"ui-monospace, SFMono-Regular, 'SF Mono', Menlo, Consolas, monospace\",\n}\n\n// Resolved concrete values from packages/themes/src/light.css + primitives\nconst BASE_LIGHT = `\n color-scheme: light;\n --cascivo-color-background: oklch(1 0 0);\n --cascivo-color-surface: oklch(0.985 0.002 264);\n --cascivo-color-surface-2: oklch(0.967 0.003 264);\n --cascivo-color-bg: var(--cascivo-color-background);\n --cascivo-color-bg-subtle: var(--cascivo-color-surface);\n --cascivo-color-surface-raised: var(--cascivo-color-surface);\n --cascivo-color-surface-overlay: var(--cascivo-color-background);\n --cascivo-color-border: oklch(0.928 0.006 264);\n --cascivo-color-border-strong: oklch(0.872 0.008 264);\n --cascivo-border-subtle: oklch(0.928 0.006 264);\n --cascivo-border-default: oklch(0.872 0.008 264);\n --cascivo-border-strong: oklch(0.707 0.015 264);\n --cascivo-color-foreground: oklch(0.145 0.005 264);\n --cascivo-color-foreground-muted: oklch(0.554 0.018 264);\n --cascivo-color-text: var(--cascivo-color-foreground);\n --cascivo-color-text-subtle: oklch(0.446 0.018 264);\n --cascivo-color-text-muted: oklch(0.707 0.015 264);\n --cascivo-color-text-on-accent: oklch(1 0 0);\n --cascivo-color-text-on-destructive: oklch(1 0 0);\n --cascivo-color-primary: oklch(0.205 0 0);\n --cascivo-color-primary-fg: oklch(0.985 0 0);\n --cascivo-color-primary-hover: oklch(0.27 0 0);\n --cascivo-color-primary-active: oklch(0.32 0 0);\n --cascivo-color-active-bg: oklch(0.145 0.005 264 / 6%);\n --cascivo-color-destructive: oklch(0.54 0.188 22);\n --cascivo-color-destructive-hover: oklch(0.448 0.17 22);\n --cascivo-color-destructive-subtle: oklch(0.971 0.013 22);\n --cascivo-color-error: oklch(0.628 0.188 22);\n --cascivo-color-warning: oklch(0.768 0.145 75);\n --cascivo-color-success: oklch(0.648 0.15 145);\n --cascivo-color-success-subtle: oklch(0.982 0.018 145);\n --cascivo-color-warning-subtle: oklch(0.98 0.02 75);\n --cascivo-color-info: oklch(0.546 0.224 250);\n --cascivo-color-info-subtle: oklch(0.97 0.025 250);\n --cascivo-color-success-foreground: oklch(0.45 0.14 145);\n --cascivo-color-warning-foreground: oklch(0.5 0.14 75);\n --cascivo-color-destructive-foreground: oklch(0.448 0.17 22);\n --cascivo-color-info-foreground: oklch(0.45 0.19 250);\n --cascivo-shadow-xs: 0 1px 2px oklch(0 0 0 / 0.05);\n --cascivo-shadow-sm: 0 1px 3px oklch(0 0 0 / 0.07), 0 1px 2px oklch(0 0 0 / 0.04);\n --cascivo-shadow-md: 0 2px 8px oklch(0 0 0 / 0.07), 0 1px 2px oklch(0 0 0 / 0.04);\n --cascivo-shadow-overlay: 0 4px 32px oklch(0 0 0 / 0.16), 0 0 0 1px oklch(0 0 0 / 0.04);\n --cascivo-shadow-lg: var(--cascivo-shadow-overlay);\n --cascivo-ring-width: 2px;\n --cascivo-ring-offset: 0px;\n --cascivo-ring-color: color-mix(in oklch, var(--cascivo-color-accent) 55%, transparent);\n --cascivo-focus-ring: 0 0 0 var(--cascivo-ring-width) var(--cascivo-ring-color);`\n\n// Resolved concrete values from packages/themes/src/dark.css + primitives\nconst BASE_DARK = `\n color-scheme: dark;\n --cascivo-color-background: oklch(0.145 0.005 250);\n --cascivo-color-surface: oklch(0.185 0.007 250);\n --cascivo-color-surface-2: oklch(0.22 0.008 250);\n --cascivo-color-bg: var(--cascivo-color-background);\n --cascivo-color-bg-subtle: var(--cascivo-color-surface);\n --cascivo-color-surface-raised: var(--cascivo-color-surface-2);\n --cascivo-color-surface-overlay: var(--cascivo-color-surface);\n --cascivo-color-border: oklch(1 0 0 / 10%);\n --cascivo-color-border-strong: oklch(1 0 0 / 16%);\n --cascivo-border-subtle: oklch(1 0 0 / 0.06);\n --cascivo-border-default: oklch(1 0 0 / 0.1);\n --cascivo-border-strong: oklch(1 0 0 / 0.2);\n --cascivo-color-foreground: oklch(0.985 0.002 264);\n --cascivo-color-foreground-muted: oklch(0.707 0.015 264);\n --cascivo-color-text: var(--cascivo-color-foreground);\n --cascivo-color-text-subtle: oklch(0.707 0.015 264);\n --cascivo-color-text-muted: oklch(0.554 0.018 264);\n --cascivo-color-text-on-accent: oklch(0.145 0.005 250);\n --cascivo-color-text-on-destructive: oklch(1 0 0);\n --cascivo-color-primary: oklch(0.922 0 0);\n --cascivo-color-primary-fg: oklch(0.205 0 0);\n --cascivo-color-primary-hover: oklch(0.86 0 0);\n --cascivo-color-primary-active: oklch(0.8 0 0);\n --cascivo-color-active-bg: oklch(1 0 0 / 8%);\n --cascivo-color-destructive: oklch(0.72 0.16 22);\n --cascivo-color-destructive-hover: oklch(0.628 0.188 22);\n --cascivo-color-destructive-subtle: oklch(0.628 0.188 22 / 0.1);\n --cascivo-color-error: oklch(0.72 0.16 22);\n --cascivo-color-warning: oklch(0.82 0.13 75);\n --cascivo-color-success: oklch(0.72 0.13 145);\n --cascivo-color-success-subtle: oklch(0.72 0.13 145 / 0.1);\n --cascivo-color-warning-subtle: oklch(0.82 0.13 75 / 0.1);\n --cascivo-color-info: oklch(0.65 0.2 250);\n --cascivo-color-info-subtle: oklch(0.65 0.2 250 / 0.1);\n --cascivo-color-success-foreground: oklch(0.72 0.13 145);\n --cascivo-color-warning-foreground: oklch(0.82 0.13 75);\n --cascivo-color-destructive-foreground: oklch(0.85 0.12 22);\n --cascivo-color-info-foreground: oklch(0.75 0.16 250);\n --cascivo-shadow-xs: none;\n --cascivo-shadow-sm: 0 1px 3px oklch(0 0 0 / 0.4);\n --cascivo-shadow-md: 0 2px 8px oklch(0 0 0 / 0.45);\n --cascivo-shadow-overlay: 0 4px 32px oklch(0 0 0 / 0.6), 0 0 0 1px oklch(1 0 0 / 0.06);\n --cascivo-shadow-lg: var(--cascivo-shadow-overlay);\n --cascivo-ring-width: 2px;\n --cascivo-ring-offset: 0px;\n --cascivo-ring-color: color-mix(in oklch, var(--cascivo-color-accent) 65%, transparent);\n --cascivo-focus-ring: 0 0 0 var(--cascivo-ring-width) var(--cascivo-ring-color);`\n\nexport interface ConfigToCSSOptions {\n /** When true, inline the full base theme token set so the block is\n * self-contained (used by the live preview). The exported theme omits these —\n * users import the base theme themselves. */\n previewMode?: boolean\n /** The `data-theme` selector value the generated tokens attach to. */\n themeName?: string\n}\n\n/** The accent roles a theme derives from one hue and chroma. */\nexport type AccentRole = 'accent' | 'hover' | 'active' | 'subtle' | 'muted'\n\n/**\n * The accent ramp as numbers: lightness and chroma per role, for one hue.\n *\n * The single place the lightness steps live. `configToCSS` formats it for the /create\n * builder; `@cascivo/design` starts from it and then tunes each role for contrast.\n */\nexport function accentScale(\n config: Pick<ThemeConfig, 'baseMode' | 'accentHue' | 'accentChroma'>,\n): Record<AccentRole, { l: number; c: number; h: number }> {\n const light = config.baseMode === 'light'\n const h = config.accentHue\n const c = config.accentChroma\n return {\n accent: { l: light ? 0.52 : 0.65, c, h },\n hover: { l: light ? 0.45 : 0.707, c, h },\n active: { l: light ? 0.373 : 0.808, c: Math.min(c, 0.155), h },\n subtle: { l: light ? 0.97 : 0.623, c: 0.025, h },\n muted: { l: light ? 0.932 : 0.623, c: light ? 0.055 : c * 0.2, h },\n }\n}\n\nexport function configToCSS(config: ThemeConfig, options: ConfigToCSSOptions = {}): string {\n const { previewMode = false, themeName = 'create-custom' } = options\n const light = config.baseMode === 'light'\n const h = config.accentHue\n const scale = accentScale(config)\n const acc = (role: AccentRole) => `oklch(${scale[role].l} ${scale[role].c.toFixed(3)} ${h})`\n\n const lines: string[] = [\n `/* Add to your project CSS after importing the base theme: */`,\n `/* @import '@cascivo/themes/${config.baseMode}.css'; */`,\n `/* @import './theme.css'; */`,\n ``,\n `@layer cascivo.theme {`,\n ` [data-theme=\"${themeName}\"] {`,\n ]\n\n if (previewMode) {\n lines.push(light ? BASE_LIGHT : BASE_DARK)\n lines.push(``)\n }\n\n lines.push(\n ` /* ── Accent ─────────────────────────────────── */`,\n ` --cascivo-color-accent: ${acc('accent')};`,\n ` --cascivo-color-accent-foreground: ${light ? 'oklch(1 0 0)' : `oklch(0.145 0.005 ${h})`};`,\n ` --cascivo-color-accent-hover: ${acc('hover')};`,\n ` --cascivo-color-accent-active: ${acc('active')};`,\n ` --cascivo-color-accent-subtle: ${acc('subtle')};`,\n ` --cascivo-color-accent-muted: ${acc('muted')};`,\n ``,\n ` /* ── Radius ─────────────────────────────────── */`,\n ` --cascivo-radius-base: ${config.radiusBase}rem;`,\n ` --cascivo-radius-control: var(--cascivo-radius-base);`,\n ` --cascivo-radius-surface: calc(var(--cascivo-radius-base) * 1.66);`,\n ` --cascivo-radius-indicator: calc(var(--cascivo-radius-base) / 2);`,\n ` --cascivo-radius-full: 9999px;`,\n ` --cascivo-radius-component: var(--cascivo-radius-base);`,\n ` --cascivo-radius-button: var(--cascivo-radius-base);`,\n ` --cascivo-radius-input: var(--cascivo-radius-base);`,\n ` --cascivo-radius-card: calc(var(--cascivo-radius-base) * 1.66);`,\n ` --cascivo-radius-badge: var(--cascivo-radius-full);`,\n ` --cascivo-radius-modal: calc(var(--cascivo-radius-base) * 2);`,\n )\n\n if (config.fontFamily !== 'system') {\n lines.push(``)\n lines.push(` /* ── Font ───────────────────────────────────── */`)\n lines.push(\n ` --cascivo-font-sans: ${FONT_STACKS[config.fontFamily] ?? FONT_STACKS['humanist']};`,\n )\n }\n\n lines.push(` }`)\n lines.push(`}`)\n\n return lines.join('\\n')\n}\n","import { resolve } from 'node:path'\nimport { configToCSS, hashToConfig } from '@cascivo/theme-kit'\nimport { THEMES } from '../utils/config.js'\nimport { installPackages } from '../utils/exec.js'\nimport { writeFileSafe } from '../utils/fs.js'\n\nconst THEME_NAME_RE = /^[a-z][a-z0-9-]*$/\n\n/** Read a `--key value` or `--key=value` flag from an argv slice. */\nfunction flag(args: string[], key: string): string | undefined {\n const eq = args.find((a) => a.startsWith(`--${key}=`))\n if (eq) return eq.slice(key.length + 3)\n const idx = args.indexOf(`--${key}`)\n const next = idx !== -1 ? args[idx + 1] : undefined\n return next && !next.startsWith('--') ? next : undefined\n}\n\n/**\n * `cascivo theme create <name> --from <hash>` — turn a /create theme-builder\n * config (the `#hash` in the builder URL, or its \"Copy CLI command\" output) into\n * an owned `<name>.theme.css` in the project. Uses the same generator the builder\n * previews with, so the file matches the preview exactly.\n */\nasync function themeCreate(args: string[], cwd: string): Promise<void> {\n const name = args.find((a) => !a.startsWith('--'))\n const hash = flag(args, 'from')\n const dryRun = args.includes('--dry-run')\n\n if (!name || !hash) {\n console.error('Usage: cascivo theme create <name> --from <hash> [--out <path>]')\n console.error(\n 'Get <hash> from the theme builder at https://cascivo.com/create (Copy CLI command).',\n )\n return\n }\n if (!THEME_NAME_RE.test(name)) {\n console.error(`Invalid theme name \"${name}\". Use lowercase letters, digits, and dashes.`)\n return\n }\n\n const config = hashToConfig(hash)\n if (!config) {\n console.error('Could not decode --from. Copy the command again from the theme builder.')\n return\n }\n\n const css = configToCSS(config, { themeName: name })\n if (dryRun) {\n console.log(css)\n return\n }\n\n const outPath = resolve(cwd, flag(args, 'out') ?? `${name}.theme.css`)\n await writeFileSafe(outPath, css)\n\n console.log(`\\n✓ Wrote ${name}.theme.css`)\n console.log(`\\nImport the base theme and your overlay in your entry CSS:`)\n console.log(` @import '@cascivo/themes/${config.baseMode}.css';`)\n console.log(` @import './${name}.theme.css';`)\n console.log(`Then set it on a container:`)\n console.log(` <div data-theme=\"${name}\">…</div>`)\n}\n\nexport async function theme(args: string[]): Promise<void> {\n const [sub, name] = args\n\n if (sub === 'create') {\n await themeCreate(args.slice(1), process.cwd())\n return\n }\n\n if (sub !== 'add' || !name) {\n console.error(`Usage: cascivo theme add <${THEMES.join('|')}>`)\n console.error(` cascivo theme create <name> --from <hash>`)\n return\n }\n if (!(THEMES as readonly string[]).includes(name)) {\n console.error(`Unknown theme \"${name}\". Available: ${THEMES.join(', ')}`)\n return\n }\n\n installPackages(['@cascivo/themes'])\n\n console.log(`\\nImport the theme in your root CSS or entry file:`)\n console.log(` import '@cascivo/themes/${name}.css'`)\n console.log(`Then set it on a container:`)\n console.log(` <div data-theme=\"${name}\">…</div>`)\n}\n","/**\n * Minimal line-based diff (LCS) rendered in a unified-ish format. Zero deps —\n * good enough to preview what `cascade update` will change.\n */\nexport function diffLines(oldStr: string, newStr: string): string[] {\n const a = oldStr.split('\\n')\n const b = newStr.split('\\n')\n const n = a.length\n const m = b.length\n\n // LCS length table.\n const lcs: number[][] = Array.from({ length: n + 1 }, () =>\n Array.from({ length: m + 1 }, () => 0),\n )\n for (let i = n - 1; i >= 0; i--) {\n for (let j = m - 1; j >= 0; j--) {\n lcs[i]![j] =\n a[i] === b[j] ? lcs[i + 1]![j + 1]! + 1 : Math.max(lcs[i + 1]![j]!, lcs[i]![j + 1]!)\n }\n }\n\n const out: string[] = []\n let i = 0\n let j = 0\n while (i < n && j < m) {\n if (a[i] === b[j]) {\n out.push(` ${a[i]}`)\n i++\n j++\n } else if (lcs[i + 1]![j]! >= lcs[i]![j + 1]!) {\n out.push(`- ${a[i]}`)\n i++\n } else {\n out.push(`+ ${b[j]}`)\n j++\n }\n }\n while (i < n) out.push(`- ${a[i++]}`)\n while (j < m) out.push(`+ ${b[j++]}`)\n return out\n}\n\n/** True when the two strings differ. */\nexport function hasChanges(oldStr: string, newStr: string): boolean {\n return oldStr !== newStr\n}\n","import { createInterface } from 'node:readline/promises'\nimport { stdin, stdout } from 'node:process'\nimport { readFile } from 'node:fs/promises'\nimport { existsSync } from 'node:fs'\nimport type { CascadeConfig } from '../utils/config.js'\nimport { diffLines, hasChanges } from '../utils/diff.js'\nimport { readFileSafe, resolveOutputPath, writeFileSafe } from '../utils/fs.js'\nimport { fetchRegistry, fileName, findComponent } from '../utils/registry.js'\nimport { readLock, writeLock, updateLockEntry } from '../utils/lock.js'\nimport { fetchJson, fetchTextRetry } from '../utils/http.js'\nimport { merge } from '../utils/merge.js'\nimport { parseItem } from '@cascivo/registry'\nimport type { RegistryItem } from '@cascivo/registry'\n\nasync function confirm(question: string): Promise<boolean> {\n const rl = createInterface({ input: stdin, output: stdout })\n try {\n const answer = (await rl.question(`${question} (y/N): `)).trim().toLowerCase()\n return answer === 'y' || answer === 'yes'\n } finally {\n rl.close()\n }\n}\n\nexport async function update(\n name: string | undefined,\n config: CascadeConfig,\n opts: { check?: boolean; yes?: boolean } = {},\n): Promise<void> {\n if (opts.check) {\n return updateCheck(config)\n }\n\n if (!name) {\n console.error('Usage: cascivo update <component>')\n return\n }\n\n const lock = await readLock()\n const lockEntry = lock?.items[name]\n\n const registry = await fetchRegistry(config.registry)\n const entry = findComponent(registry, name)\n if (!entry) {\n console.error(`Component \"${name}\" not found in registry. Run \"cascivo list\".`)\n return\n }\n\n if (lockEntry) {\n // Three-way merge path\n const lockedVersion = lockEntry.version\n const registryBase = lockEntry.registry\n const baseItemUrl = `${registryBase}/r/${name}@${lockedVersion}.json`\n\n let baseItem: RegistryItem | null = null\n try {\n baseItem = parseItem(await fetchJson(baseItemUrl), baseItemUrl)\n } catch {\n console.warn(\n `Warning: could not fetch base version ${lockedVersion} from ${baseItemUrl}. Falling back to two-way diff.`,\n )\n }\n\n if (baseItem) {\n await threeWayUpdate(name, entry, baseItem, config, opts)\n } else {\n await twoWayUpdate(name, entry, config, opts)\n }\n } else {\n console.warn(\n `Warning: \"${name}\" has no lock entry. Falling back to two-way diff update (pre-v11 install).`,\n )\n await twoWayUpdate(name, entry, config, opts)\n }\n}\n\nasync function threeWayUpdate(\n name: string,\n upstreamEntry: ReturnType<typeof findComponent>,\n baseItem: RegistryItem,\n config: CascadeConfig,\n opts: { yes?: boolean },\n): Promise<void> {\n if (!upstreamEntry) return\n const outputName = name.includes('/') ? name.split('/').pop()! : name\n const summaries: { file: string; result: 'clean' | 'conflict' | 'unchanged' }[] = []\n const pending: { dest: string; content: string; conflicts: number }[] = []\n\n for (const url of upstreamEntry.files) {\n const fname = fileName(url)\n const baseFile = baseItem.files.find((f) => fileName(f.url) === fname)\n const dest = resolveOutputPath(config.outputDir, outputName, fname)\n\n const upstream = await fetchTextRetry(url)\n const local = existsSync(dest) ? await readFile(dest, 'utf8') : ''\n const base = baseFile ? await fetchTextRetry(baseFile.url) : ''\n\n if (base === '' && local === '') {\n summaries.push({ file: fname, result: 'clean' })\n pending.push({ dest, content: upstream, conflicts: 0 })\n continue\n }\n\n const { text, conflicts } = merge(base, local, upstream)\n\n if (conflicts > 0) {\n summaries.push({ file: fname, result: 'conflict' })\n } else if (text === local) {\n summaries.push({ file: fname, result: 'unchanged' })\n continue\n } else {\n summaries.push({ file: fname, result: 'clean' })\n }\n pending.push({ dest, content: text, conflicts })\n }\n\n if (pending.length === 0) {\n console.log(`${name} is already up to date.`)\n return\n }\n\n for (const s of summaries) {\n const icon = s.result === 'conflict' ? '⚠' : s.result === 'clean' ? '✓' : '·'\n console.log(` ${icon} ${s.file} (${s.result})`)\n }\n\n const conflicted = pending.filter((p) => p.conflicts > 0)\n const shouldApply = opts.yes\n ? conflicted.length === 0 // --yes skips items with conflicts\n : await confirm(`\\nApply ${pending.length} change(s) to ${name}?`)\n\n if (shouldApply || opts.yes) {\n const lock = await readLock()\n let updatedLock = lock\n\n for (const { dest, content, conflicts } of pending) {\n if (opts.yes && conflicts > 0) {\n console.log(` skipped (conflicts): ${dest}`)\n continue\n }\n await writeFileSafe(dest, content)\n }\n\n if (lock && updatedLock) {\n const hasConflicts = conflicted.length > 0\n updatedLock = updateLockEntry(updatedLock, name, {\n ...lock.items[name]!,\n version: upstreamEntry.version,\n ...(hasConflicts ? { conflicted: true as const } : {}),\n })\n await writeLock(updatedLock)\n }\n\n console.log(`Updated ${name}.`)\n if (conflicted.length > 0) {\n console.log(`${conflicted.length} file(s) have conflict markers — resolve them manually.`)\n }\n } else {\n console.log('Aborted. No files changed.')\n }\n}\n\nasync function twoWayUpdate(\n name: string,\n entry: ReturnType<typeof findComponent>,\n config: CascadeConfig,\n opts: { yes?: boolean },\n): Promise<void> {\n if (!entry) return\n const pending: { path: string; content: string }[] = []\n\n for (const url of entry.files) {\n let latest: string\n try {\n latest = await fetchTextRetry(url)\n } catch (e) {\n console.error(e instanceof Error ? e.message : String(e))\n return\n }\n const dest = resolveOutputPath(config.outputDir, entry.name, fileName(url))\n const current = await readFileSafe(dest)\n\n if (current === null) {\n console.log(`New file: ${dest}`)\n pending.push({ path: dest, content: latest })\n } else if (hasChanges(current, latest)) {\n console.log(`\\n--- ${dest}`)\n console.log(diffLines(current, latest).join('\\n'))\n pending.push({ path: dest, content: latest })\n }\n }\n\n if (pending.length === 0) {\n console.log(`${name} is already up to date.`)\n return\n }\n\n const shouldApply = opts.yes || (await confirm(`\\nApply ${pending.length} change(s) to ${name}?`))\n\n if (shouldApply) {\n for (const { path, content } of pending) {\n await writeFileSafe(path, content)\n }\n console.log(`Updated ${name}.`)\n } else {\n console.log('Aborted. No files changed.')\n }\n}\n\nasync function updateCheck(config: CascadeConfig): Promise<void> {\n const lock = await readLock()\n if (!lock || Object.keys(lock.items).length === 0) {\n console.log('No installed components found in cascivo.lock.')\n return\n }\n\n const registry = await fetchRegistry(config.registry)\n let outdated = 0\n\n for (const [name, entry] of Object.entries(lock.items)) {\n const current = findComponent(registry, name)\n if (!current) continue\n // Content hashes are the accurate signal (they change with every source\n // edit); the version compare is the fallback for older registries.\n if (current.fileHashes && Object.keys(current.fileHashes).length > 0) {\n const lockByBase = new Map(\n Object.entries(entry.files).map(([dest, hash]) => [dest.split('/').pop()!, hash]),\n )\n const changed = Object.entries(current.fileHashes).filter(\n ([file, hash]) => lockByBase.get(file) !== hash,\n )\n if (changed.length > 0) {\n console.log(\n `${name}: ${changed.length} file(s) changed upstream (${entry.version} → ${current.version})`,\n )\n outdated++\n }\n } else if (current.version !== entry.version) {\n console.log(`${name}: ${entry.version} → ${current.version}`)\n outdated++\n }\n }\n\n if (outdated > 0) {\n console.log(`${outdated} component(s) outdated.`)\n process.exitCode = 1\n } else {\n console.log('All components up to date.')\n }\n}\n","import type { CascadeConfig } from '../utils/config.js'\nimport { parseAddress, resolveItemUrl } from '../utils/resolve.js'\nimport { fetchJson } from '../utils/http.js'\nimport { asTemplateMeta, isTemplateItem, parseItem, type RegistryItem } from '@cascivo/registry'\n\n/** Render an item's details as text. Pure, so it can be unit-tested. */\nexport function formatItem(item: RegistryItem): string {\n const lines: string[] = []\n lines.push(`\\n${item.name} v${item.version}`)\n lines.push(`Type: ${item.type}${item.category ? ` / ${item.category}` : ''}`)\n lines.push(item.description)\n if (item.author) lines.push(`Author: ${item.author}`)\n if (item.license) lines.push(`License: ${item.license}`)\n if (item.homepage) lines.push(`Homepage: ${item.homepage}`)\n\n if (item.install) {\n lines.push(`Distribution: npm package — pnpm add ${item.install}`)\n if (item.styles) lines.push(`Stylesheet: import '${item.styles}' (required)`)\n } else if (!isTemplateItem(item)) {\n lines.push(`Distribution: copy-paste — npx cascivo add ${item.name}`)\n }\n\n if (isTemplateItem(item)) {\n try {\n const meta = asTemplateMeta(item.meta)\n lines.push(`\\nTemplate: ${meta.intent}`)\n lines.push(`Framework: ${meta.framework}`)\n if (meta.demoUrl) lines.push(`Demo: ${meta.demoUrl}`)\n if (meta.pages?.length) {\n lines.push('Pages:')\n for (const p of meta.pages) lines.push(` ${p.name} → ${p.target}`)\n }\n } catch {\n // meta is malformed — base fields above are still useful.\n }\n }\n\n if (item.changelog?.length) {\n lines.push('\\nChangelog:')\n for (const c of item.changelog.slice(0, 5)) lines.push(` ${c.version}: ${c.note}`)\n }\n\n if (item.files?.length) {\n lines.push('\\nFiles:')\n for (const f of item.files) lines.push(` ${f.url}${f.target ? ` → ${f.target}` : ''}`)\n }\n\n if (item.dependencies?.length) lines.push(`\\nDependencies: ${item.dependencies.join(', ')}`)\n\n if (item.registryDependencies?.length) {\n const label = isTemplateItem(item) ? 'Components' : 'Registry dependencies'\n lines.push(`${label}: ${item.registryDependencies.join(', ')}`)\n }\n\n return lines.join('\\n')\n}\n\nexport async function view(args: string[], config: CascadeConfig): Promise<void> {\n const spec = args[0]\n if (!spec) {\n console.error('Usage: cascivo view <component-spec>')\n return\n }\n\n const addr = parseAddress(spec)\n const { url, headers, params } = await resolveItemUrl(addr, config)\n const fetchOpts: Parameters<typeof fetchJson>[1] = {}\n if (headers) fetchOpts.headers = headers\n if (params) fetchOpts.params = params\n const item = parseItem(await fetchJson(url, fetchOpts), url)\n\n console.log(formatItem(item))\n}\n","import { createRequire } from 'node:module'\nimport { argv } from 'node:process'\nimport { pathToFileURL } from 'node:url'\nimport { add } from './commands/add.js'\nimport { runDoctor } from './commands/doctor.js'\nimport { generate } from './commands/generate.js'\nimport { init } from './commands/init.js'\nimport { list } from './commands/list.js'\nimport { registryBuild } from './commands/registry.js'\nimport { search } from './commands/search.js'\nimport { theme } from './commands/theme.js'\nimport { update } from './commands/update.js'\nimport { view } from './commands/view.js'\nimport { loadConfig, THEMES } from './utils/config.js'\nimport { positionalArgs, resolvePackageManagerFlag } from './utils/args.js'\n\n// Read at runtime: this file lives one level below the package root both in\n// src/ (dev, tests) and in dist/ (published bundle), so ../package.json is\n// always the cascivo package manifest.\nexport const VERSION: string = (\n createRequire(import.meta.url)('../package.json') as { version: string }\n).version\n\nexport type { CascadeConfig, ThemeName } from './utils/config.js'\n\nconst HELP = `cascivo ${VERSION} — the CSS-native, signal-driven, AI-first design system\n\nUsage: cascivo <command> [options]\n\nCommands:\n create [name] Scaffold a new ready-to-run app (shell + nav + theme)\n (--template <spec>: start from a marketplace template)\n app add page \"<title>\" Add a page to the app (--block <name>); app add example <name>,\n app upgrade: change an app the way create would have made it\n init Set up cascivo in the current project\n add <component...> Add components or a template to your project\n list [--installed] List available components\n update [component] Update installed components (--check: list outdated)\n search <query> Search components across registries\n view <spec> View a component before installing\n theme <add|create> Install a first-party theme, or build a custom one from /create\n eject <component> Eject specific tokens into a scoped local override file\n generate <config.json> Generate TSX from a ViewConfig JSON file\n doctor [--ci] Check components for rule violations\n audit --ai <paths...> Audit AI-generated code against the cascivo contract\n design <subcommand> Plan a page from a brief and audit the rendered result\n (check | see | plan | init | theme; needs @cascivo/design)\n mcp init Add the cascivo MCP server to your agent's config\n registry build Build a static registry from a cascivo-registry.json file\n template init <name> Scaffold a new template (source + manifest + registry entry)\n tokens import <file> Import external design tokens as cascivo overrides\n email lint <file...> Check rendered email HTML for client support and dead links\n\nRun \"cascivo <command> --help\" for details.`\n\nconst THEME_LIST = THEMES.join(' | ')\n\nconst COMMAND_HELP: Record<string, string> = {\n app: `Usage: cascivo app add page \"<title>\" [options]\n cascivo app add example <name>\n cascivo app upgrade\n\nChange an app made by \\`cascivo create\\` through its cascivo.app.json: add a page, add a\ncloudflare example, or regenerate it with this CLI's templates. The app is generated before and\nafter the change, and each file that changes is merged three ways: files you have not touched\nare replaced, your edits are kept, and a clash gets conflict markers (the command then exits\nnon-zero). The original files are rebuilt with the CLI version recorded in cascivo.app.json.\n\nOptions:\n --block <name> The registry block a new page renders (default: a page to build out)`,\n mcp: `Usage: cascivo mcp init [options]\n\nAdd the cascivo MCP server (npx -y @cascivo/mcp) to your coding agent's project config.\nOther servers in the file are kept; an existing cascivo entry is left as it is.\n\nOptions:\n --client <name> claude (default, .mcp.json) | cursor (.cursor/mcp.json)\n | vscode (.vscode/mcp.json)\n --dry-run Print the file instead of writing it\n\nExamples:\n npx cascivo mcp init\n npx cascivo mcp init --client cursor`,\n email: `Usage: cascivo email lint <file...> [options]\n\nCheck rendered email HTML against the Can I email support matrix — the same\nconformance lint @cascivo/email exposes as \\`lint()\\`, with the setup done for you —\nand for links that go nowhere (\\`checkLinks()\\`): empty, \\`#\\`, relative, an\nunreplaced {{merge tag}}, or a placeholder domain such as example.com.\n\nIt lints rendered HTML, not templates: render in your own build and pass the\noutput, or pipe it in.\n\nArguments:\n <file...> One or more rendered .html files, or \\`-\\` for stdin\n\nOptions:\n --data <file> Use a local copy of the matrix instead of fetching\n --refresh Re-fetch the matrix even if the cache is fresh\n --no-allowlist Report findings CASCIVO_ALLOW waives, too\n --check-links Also request every http(s) URL; one answering 4xx/5xx,\n or not at all within 10s, fails the command\n\nThe matrix is fetched from https://www.caniemail.com/api/data.json and cached for\na day. It is not bundled with @cascivo/email because it is ~483 KB of test data.\n\nExits non-zero when a floor client genuinely cannot support something, or a link\ncannot work. A caveat (partial support, a localhost or http: link) is worth knowing\nabout and never fails the command.\n\nExamples:\n cascivo email lint dist/emails/*.html\n node render.js | cascivo email lint -\n cascivo email lint dist/welcome.html --data caniemail.json\n cascivo email lint dist/emails/*.html --check-links`,\n\n create: `Usage: cascivo create [name] [options]\n\nScaffold a new ready-to-run app, pre-wired with the cascivo app shell, side\nnavigation, header, and a theme.\n\nOptions:\n --framework <name> react-vite (default), astro, or cloudflare (a client app and\n its API, deployed as one Cloudflare Worker)\n --runtime <name> preact (default) or react — for --framework cloudflare\n --example <name> board — a multiplayer page on a Durable Object (cloudflare only)\n agent — an AI assistant that answers with UI (cloudflare, React)\n notes — a local-first page that keeps edits offline (cloudflare)\n import — a CSV import on a Workflow, with live progress (cloudflare)\n files — uploads into R2 with progress and image previews (cloudflare)\n export — a report page downloadable as PDF/PNG via Browser Run (cloudflare)\n usage — API usage charts from Workers Analytics Engine (cloudflare)\n crud — a D1 table behind DataTable's server mode (cloudflare)\n live — an ops dashboard fed by a Queue, updating every second (cloudflare)\n voice — a voice assistant: Workers AI speech in and out (cloudflare)\n publish — publish views as pages, validated and stored in D1 (cloudflare)\n webhooks — signed GitHub deliveries, stored once, shown live (cloudflare)\n digest — the report as a PDF, emailed weekly on a Cron Trigger (cloudflare)\n search — help articles searched by meaning: Vectorize + Workers AI (cloudflare)\n checkout — sell a product with Stripe Checkout; orders and receipts (cloudflare)\n newsletter — double opt-in sign-up, issues sent through Amazon SES (cloudflare)\n social — post to Bluesky, Mastodon, LinkedIn, Threads and Buffer, now or\n scheduled, with images (cloudflare)\n --auth access Refuse every Worker request Cloudflare Access did not let\n through (cloudflare only)\n --auth email Accounts with emailed sign-in links; every API write needs a\n signed-in user (cloudflare only)\n --auth oauth Accounts with GitHub, Google and LinkedIn sign-in; every API\n write needs a signed-in user (cloudflare only).\n --auth email,oauth: both\n --template <spec> Start from a marketplace template (@ns/name or owner/repo/name)\n --from <file> Compile a blueprint (cascivo.app.json): name, framework, theme,\n pages [{ title, block? }], runtime, examples, auth. Each page\n renders its registry block. Replaces the other options.\n --workspace Put the app in a pnpm workspace: apps/web, packages/ui for your own\n components, Vite+ running every package's scripts, CI, a smoke test\n --theme <name> Theme to install (${THEME_LIST})\n --sections \"<a, b>\" Comma-separated nav section labels (one component each)\n --package-manager <pm> Package manager for README/next-steps (alias --pm; default: auto-detect)\n --yes, -y Accept defaults, never prompt`,\n init: `Usage: cascivo init [options]\n\nSet up cascivo in the current project: writes cascivo.config.ts and installs the\nruntime dependencies (@cascivo/core, @cascivo/tokens, @cascivo/themes, the\n@preact/signals-react peer) plus cascivo as a dev dependency for the config's types.\n\nOptions:\n --theme <name> Theme to configure (${THEME_LIST})\n --package-manager <pm> Force pnpm | yarn | npm | bun (alias --pm; default: auto-detect)\n --no-install Write files only; print the install commands to run yourself\n --yes, -y Accept defaults, never prompt (implied when stdin is not a TTY)`,\n add: `Usage: cascivo add <component...> [options]\n\nCopy component source (TSX + CSS module) from the registry into your project,\nresolving component dependencies. Also installs templates (@ns/name) and\nthird-party components (owner/repo/name).\n\nOptions:\n --dry-run Show what would be written without writing\n --package-manager <pm> Force pnpm | yarn | npm | bun (alias --pm; default: auto-detect)\n --no-install Don't install npm-distributed entries or deps; print the commands instead\n --yes, -y Skip confirmation prompts`,\n list: `Usage: cascivo list [options]\n\nList components available in the configured registry.\n\nOptions:\n --installed Only list components already installed in this project`,\n update: `Usage: cascivo update [component] [options]\n\nUpdate installed components to the current registry version. Without a\ncomponent argument, updates everything in the lockfile.\n\nOptions:\n --check List outdated components without writing\n --yes, -y Skip confirmation prompts`,\n search: `Usage: cascivo search <query> [options]\n\nSearch components across the configured registries.\n\nOptions:\n --registry <@ns> Restrict the search to one registry namespace`,\n view: `Usage: cascivo view <spec>\n\nPreview a component or template (files, dependencies, description) before\ninstalling. <spec> is a bare name, @ns/name, or owner/repo/name.`,\n theme: `Usage: cascivo theme add <name>\n cascivo theme create <name> --from <hash> [--out <path>]\n\nadd Install @cascivo/themes and print the import + data-theme wiring.\ncreate Turn a theme-builder config into an owned <name>.theme.css. Get <hash>\n from https://cascivo.com/create (\"Copy CLI command\"). --dry-run prints\n the CSS without writing.\n\nThemes: ${THEME_LIST}`,\n eject: `Usage: cascivo eject <component> [options]\n\nEject specific tokens into a scoped local override file so you can restyle a\ncomponent without forking it.\n\nOptions:\n --tokens <a,b> Comma-separated token names to eject (default: all)\n --scope <sel> CSS selector the overrides are scoped to\n --out <file> Output file path\n --dry-run Print the override file without writing`,\n generate: `Usage: cascivo generate <config.json> [options]\n\nGenerate TSX from a ViewConfig JSON file (see the MCP scaffold_view tool).\n\nOptions:\n --out <file> Output file (default: <config>.tsx beside the input)\n --components-dir <dir> Components import base (default: ./src/components/ui)\n --from <package> Import every component from one package instead, e.g. @cascivo/react`,\n doctor: `Usage: cascivo doctor [options]\n\nCheck components in this repo for cascivo rule violations (banned React hooks,\nhardcoded strings, missing @cascivo/react exports). In an adopter project (one\nwith a cascivo.config), also verifies the runtime dependencies copied source\nneeds — @cascivo/core, @cascivo/tokens, @cascivo/themes, and the\n@preact/signals-react peer — are declared in package.json.\n\nOptions:\n --ci Exit non-zero when violations or missing runtime deps are found\n --drift Compare installed components against the registry (copy-paste drift)`,\n audit: `Usage: cascivo audit --ai <paths...> [options]\n\nAudit AI-generated code against the cascivo contract: hard-coded values that\nshould be tokens, invented props, missing required props, raw strings where\ni18n is expected.\n\nOptions:\n --fix Rewrite unambiguous CSS literals to their token equivalents\n --json Machine-readable output\n --level <name> Minimum finding level to report (error | warn; default error)\n --contract <path> Use this audit-contract.json instead of the bundled one\n --verbose Report which contract source was used`,\n design: `Usage: cascivo design check <url|path> [--json] [--max N] [--design <path>] [--storage-state <file>]\n cascivo design see <url|path> [--width N] [--out file.png] [--storage-state <file>]\n cascivo design plan \"<brief>\" [--format cv|view] [--json]\n cascivo design init [--theme <name>] [--force] [direction flags]\n cascivo design theme --seed <hex> [--mode light|dark] [--name <name>]\n cascivo design skill [--dir <skills-dir>] [--force]\n\nDeterministic UI planning and auditing for AI agents, from @cascivo/design (install it\nin the project first). The same input gives the same output; no model is involved.\n\n check Audit a rendered page (a URL or an HTML file). Needs playwright.\n see Print a text digest of a screenshot of the page. Needs playwright.\n plan Turn a brief into a page plan: archetype, slots, components, unmatched words.\n init Write a DESIGN.md (tokens of one theme, then rules). Keeps an existing file.\n theme Derive a theme from one seed colour and print its CSS.\n skill Write the cascivo-design agent skill to .claude/skills/ (offline, version-matched).\n\nOptions:\n --json Machine-readable output (check, plan)\n --max <n> check: report at most this many findings\n --width <n> see: viewport width in CSS pixels\n --format <f> plan: cv (.cv text) | view (ViewConfig JSON)\n --dir <path> skill: the skills directory to write into (default .claude/skills)\n --seed <hex> theme: the seed colour, e.g. \"#0079bf\"\n --storage-state <f> check, see: a Playwright storageState JSON (cookies + localStorage) loaded\n into the browser, to audit a page behind a login. Keep it out of git\n (docs/USING-CASCIVO-DESIGN.md shows how to create it).\n --design <p> check: the project's DESIGN.md; its front-matter tokens count as on-scale\n (default ./DESIGN.md when present). Custom properties on :root always count.\n\nDirection flags (init): write a chosen look into DESIGN.md and print the :root block for it.\n --accent, --primary, --background, --surface, --text <colour> hex or functional CSS colour\n --font-display <stack> font stack for display and headings\n --font-body <stack> font stack for everything else\n --signature \"<text>\" the one signature element, in a sentence\n --composition \"<text>\" the one composition move (the layout default it breaks), in a sentence`,\n registry: `Usage: cascivo registry build [options]\n\nBuild a static registry (registry.json + file payloads) from a\ncascivo-registry.json manifest, ready to host on any static file server.\n\nOptions:\n --in <file> The registry manifest (default cascade-registry.json)\n --out <dir> Output directory (default public/r)`,\n template: `Usage: cascivo template init <name> [options]\n\nScaffold a new template: source, manifest, and registry entry.\n\nOptions:\n --category <name> Template category (e.g. dashboard)\n --framework <name> Target framework (default react-vite)\n --components <a,b> Registry components the template composes\n --repo <owner/repo> Repository the template will be hosted in`,\n tokens: `Usage: cascivo tokens import <file>\n\nImport external design tokens (W3C design-tokens JSON) as cascivo token\noverrides.`,\n}\n\nexport async function run(args: string[]): Promise<void> {\n const [command, ...rest] = args\n\n // Per-command help must short-circuit BEFORE any prompt, fetch, or install:\n // \"cascivo add --help\" must never try to install a component named --help.\n if (command !== undefined && (rest.includes('--help') || rest.includes('-h'))) {\n const commandHelp = COMMAND_HELP[command]\n if (commandHelp !== undefined) {\n console.log(commandHelp)\n return\n }\n }\n\n switch (command) {\n case 'create':\n // Lazy, like the other commands: its scaffold templates are most of the CLI's size.\n const { create } = await import('./commands/create.js')\n await create(rest)\n break\n case 'app': {\n const { app } = await import('./commands/app.js')\n await app(rest)\n break\n }\n case 'init':\n await init(rest)\n break\n case 'add': {\n const pmFlag = resolvePackageManagerFlag(rest)\n if ('error' in pmFlag) {\n console.error(pmFlag.error)\n process.exitCode = 1\n break\n }\n await add(positionalArgs(rest, ['pm', 'package-manager']), await loadConfig(), {\n dryRun: rest.includes('--dry-run'),\n yes: rest.includes('--yes'),\n noInstall: rest.includes('--no-install'),\n ...(pmFlag.pm ? { pm: pmFlag.pm } : {}),\n })\n break\n }\n case 'list':\n await list(await loadConfig(), { installed: rest.includes('--installed') })\n break\n case 'update':\n await update(rest.filter((r) => !r.startsWith('--'))[0], await loadConfig(), {\n check: rest.includes('--check'),\n yes: rest.includes('--yes'),\n })\n break\n case 'search':\n await search(rest, await loadConfig())\n break\n case 'view':\n await view(rest, await loadConfig())\n break\n case 'theme':\n await theme(rest)\n break\n case 'eject': {\n const { eject } = await import('./commands/eject.js')\n const flag = (key: string): string | undefined => {\n const eq = rest.find((r) => r.startsWith(`--${key}=`))\n if (eq) return eq.slice(key.length + 3)\n const idx = rest.indexOf(`--${key}`)\n const next = idx !== -1 ? rest[idx + 1] : undefined\n // Ignore a following token that is itself a flag (e.g. `--tokens --dry-run`).\n return next && !next.startsWith('--') ? next : undefined\n }\n const tokensArg = flag('tokens')\n await eject(rest, await loadConfig(), {\n ...(tokensArg\n ? {\n tokens: tokensArg\n .split(',')\n .map((t) => t.trim())\n .filter(Boolean),\n }\n : {}),\n ...(flag('scope') ? { scope: flag('scope')! } : {}),\n ...(flag('out') ? { out: flag('out')! } : {}),\n dryRun: rest.includes('--dry-run'),\n })\n break\n }\n case 'generate':\n await generate(rest, await loadConfig())\n break\n case 'registry':\n if (rest[0] === 'build') {\n await registryBuild(rest.slice(1))\n } else {\n console.error(`Unknown registry subcommand: ${rest[0]}`)\n process.exitCode = 1\n }\n break\n case 'template':\n if (rest[0] === 'init') {\n const { templateInit } = await import('./commands/template-init.js')\n await templateInit(rest.slice(1))\n } else {\n console.error(`Unknown template subcommand: ${rest[0]}`)\n process.exitCode = 1\n }\n break\n case 'doctor': {\n const ci = rest.includes('--ci')\n const drift = rest.includes('--drift')\n if (drift) {\n // `--drift` keeps its meaning: drift ONLY.\n const { runDoctorDrift } = await import('./commands/drift.js')\n await runDoctorDrift(await loadConfig())\n } else {\n const cwd = process.cwd()\n const result = await runDoctor(cwd)\n const {\n checkDuplicateCore,\n checkFormatterIgnore,\n checkProjectDependencies,\n checkSignalsCompat,\n checkSsrConfig,\n detectInstallPath,\n } = await import('./commands/doctor.js')\n // Gate on evidence of *any* cascivo install, not on a `cascivo.config.*` file. The\n // config gate mislabelled every prebuilt-path app as copy-paste (the scaffolder wrote\n // one unconditionally), and would now skip them entirely since it no longer does.\n const adopter = detectInstallPath(cwd) !== 'unknown'\n const deps = adopter ? checkProjectDependencies(cwd) : []\n const missingRequired = deps.filter((d) => d.required)\n const signalsCompat = adopter ? await checkSignalsCompat(cwd) : null\n const signalsError = signalsCompat?.severity === 'error'\n const ssrHint = adopter ? checkSsrConfig(cwd) : null\n const duplicateCore = adopter ? await checkDuplicateCore(cwd) : null\n const formatterHint = adopter\n ? checkFormatterIgnore(cwd, (await loadConfig()).outputDir)\n : null\n\n // Run the drift check as part of the DEFAULT invocation. These used to be disjoint\n // branches, so `cascivo doctor` printed \"No violations found.\" on a project where\n // `cascivo doctor --drift` reported five real issues. A clean report from a run that\n // never looked is worse than no report.\n const { runDoctorDrift } = await import('./commands/drift.js')\n const driftOutcome = adopter\n ? await runDoctorDrift(await loadConfig(), cwd)\n : { ran: false, reason: 'no cascivo install detected', issues: 0 }\n\n if (\n result.passed &&\n deps.length === 0 &&\n signalsCompat === null &&\n ssrHint === null &&\n duplicateCore === null &&\n formatterHint === null &&\n driftOutcome.issues === 0\n ) {\n // Never an unqualified \"clean\" when part of the check could not run.\n console.log(\n driftOutcome.ran\n ? 'No violations found.'\n : `No violations found (drift: not checked — ${driftOutcome.reason}).`,\n )\n } else {\n for (const v of result.violations) {\n console.error(`[${v.rule}] ${v.detail}\\n ${v.file}`)\n }\n for (const d of missingRequired) {\n // A forbidden dependency needs the opposite advice from a missing one. Sharing\n // the \"install it\" template told prebuilt-path adopters to install the very\n // packages the message was asking them to remove.\n console.error(\n d.kind === 'forbidden'\n ? `[forbidden-dependency] ${d.package} must not be a direct dependency here. Remove it — ${d.hint}`\n : `[missing-dependency] ${d.package} is not in package.json. Install: ${d.hint}`,\n )\n }\n if (signalsCompat) {\n const tag = signalsError ? 'signals-incompatible' : 'signals-outdated'\n const log = signalsError ? console.error : console.log\n log(`[${tag}] ${signalsCompat.detail} Upgrade: ${signalsCompat.hint}`)\n }\n if (ssrHint) {\n console.log(`[ssr-config] ${ssrHint}`)\n }\n if (formatterHint) {\n console.log(`[formatter-drift] ${formatterHint}`)\n }\n if (duplicateCore) {\n console.error(\n `[duplicate-core] More than one @cascivo/core is installed ` +\n `(root: ${duplicateCore.root ?? 'none'}; ${duplicateCore.nested.join('; ')}). ` +\n duplicateCore.hint,\n )\n }\n for (const d of deps.filter((x) => !x.required)) {\n console.log(\n `[optional] ${d.package} is not installed; add it when a component or chart needs it: ${d.hint}`,\n )\n }\n if (\n ci &&\n (result.violations.length > 0 ||\n missingRequired.length > 0 ||\n signalsError ||\n duplicateCore !== null ||\n driftOutcome.issues > 0)\n ) {\n process.exitCode = 1\n }\n }\n }\n break\n }\n case 'mcp': {\n const { mcp } = await import('./commands/mcp.js')\n await mcp(rest)\n break\n }\n case 'audit': {\n const { audit } = await import('./commands/audit.js')\n await audit(rest, await loadConfig())\n break\n }\n case 'design': {\n const { design } = await import('./commands/design.js')\n await design(rest)\n break\n }\n case 'email': {\n const { email } = await import('./commands/email.js')\n await email(rest)\n break\n }\n case 'tokens':\n if (rest[0] === 'import') {\n const { tokensImport } = await import('./commands/tokens.js')\n await tokensImport(rest.slice(1))\n } else {\n console.error(`Unknown tokens subcommand: ${rest[0]}`)\n process.exitCode = 1\n }\n break\n case undefined:\n case '--help':\n case '-h':\n case 'help':\n console.log(HELP)\n break\n case '--version':\n case '-v':\n console.log(VERSION)\n break\n default:\n console.error(`Unknown command: ${command}\\n`)\n console.log(HELP)\n process.exitCode = 1\n }\n}\n\nconst isMain = argv[1] !== undefined && import.meta.url === pathToFileURL(argv[1]).href\n\nif (isMain) {\n run(argv.slice(2)).catch((error: unknown) => {\n console.error(error instanceof Error ? error.message : String(error))\n process.exitCode = 1\n })\n}\n"],"mappings":"ooCAUA,SAAgBkC,EACd,EACA,EAAc,QAAQ,IAAI,EAC1B,EAOI,CAAC,EACI,CACT,GAAIC,EAAS,SAAW,EAAG,MAAO,GAClC,IAAMC,EAAKC,EAAK,IAAMhC,EAAqBiC,CAAG,EACxC,CAACC,EAAKC,GAAQhC,EAAe4B,EAAID,EAAU,CAC/C,IAAKE,EAAK,KAAO,GACjB,GAAIA,EAAK,OAAS,CAAE,OAAQA,EAAK,MAAO,EAAI,CAAC,EAC7C,GAAIA,EAAK,IAAM,CAAE,IAAKA,EAAK,GAAI,EAAI,CAAC,CACtC,CAAC,EAcD,OAbA,QAAQ,IAAI,cAAcF,EAAS,KAAK,IAAI,EAAE,QAAQI,EAAI,EAAE,EAC7CE,GAAUF,EAAKC,EAAM,CAClC,MACA,MAAO,UACP,MAAO,QAAQ,WAAa,OAC9B,CACS,CAAC,CAAC,SAAW,IACpB,QAAQ,MAAM,sBAAsBL,EAA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