cascivo 0.1.6 → 0.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2024 urbanisierung
3
+ Copyright (c) cascivo contributors
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
package/README.md CHANGED
@@ -21,18 +21,33 @@ The `cascivo` CLI drives the copy-paste workflow — it scaffolds config, copies
21
21
  ## Commands
22
22
 
23
23
  ```sh
24
- npx cascivo init # scaffold cascivo.config.ts + tokens; detects your package manager
25
- cascivo add button card # copy component source from the registry into your project
26
- cascivo add owner/repo/button # install from any third-party registry
27
- cascivo list # list available components
28
- cascivo update # pull newer versions of copied components
29
- cascivo audit --ai # flag hard-coded values, invented props, missing wiring
30
- cascivo build # build a registry from your own components
24
+ npx cascivo create my-app # scaffold a full app — Vite + React, app shell, side nav, theme
25
+ npx cascivo create my-app --template owner/repo/dashboard # …and start from a template
26
+ npx cascivo init # scaffold cascivo.config.ts + tokens; detects your package manager
27
+ cascivo add button card # copy component source from the registry into your project
28
+ cascivo add owner/repo/button # install from any third-party registry
29
+ cascivo add owner/repo/dashboard # install a template (its components + page/fixture files)
30
+ cascivo view owner/repo/dashboard # preview an item (or template) before installing
31
+ cascivo list # list available components
32
+ cascivo update # pull newer versions of copied components
33
+ cascivo audit --ai # flag hard-coded values, invented props, missing wiring
34
+ cascivo search <query> # search components across registries
35
+ cascivo theme add <name> # install a first-party theme (12 available)
36
+ cascivo eject <component> # eject tokens into a scoped local override file
37
+ cascivo generate <config.json> # generate TSX from a ViewConfig JSON file
38
+ cascivo doctor [--ci] [--drift] # check components for rule violations / registry drift
39
+ cascivo tokens import <file> # import external design tokens as overrides
40
+ cascivo registry build # build a registry from your own components
41
+ cascivo template init <name> # scaffold a new template
31
42
  ```
32
43
 
44
+ Every command supports `--help` for its flags and examples.
45
+
46
+ A **template** is a registry item (`type: "template"`) that bundles a working page with the components it composes (in `registryDependencies`) and its own page/fixture files (each with a `target`). `cascivo add` installs the component closure into your components directory and writes the template's files to their targets; `create --template` does the same into a freshly scaffolded app.
47
+
33
48
  ## How it works
34
49
 
35
- `init` detects npm / pnpm / yarn / bun, writes `cascivo.config.ts`, and wires up the token and theme imports. `add` resolves each component from [`registry.json`](https://github.com/cascivo/cascivo/blob/main/registry.json), fetches its source (TSX + CSS module + manifest) from GitHub raw URLs, and drops it into the path from your config — pulling in any dependencies it needs.
50
+ `create` scaffolds a complete Vite + React + TypeScript app — pre-wired with the cascivo app shell, side navigation, header, and your chosen theme. It asks for a project name, theme, and the nav sections you want, then generates a section component for each. Pass `--theme`, `--sections "Dashboard, Reports"`, or `--yes` to skip the prompts. `init` detects npm / pnpm / yarn / bun, writes `cascivo.config.ts`, and wires up the token and theme imports. `add` resolves each component from [`registry.json`](https://github.com/cascivo/cascivo/blob/main/registry.json), fetches its source (TSX + CSS module + manifest) from GitHub raw URLs, and drops it into the path from your config — pulling in any dependencies it needs.
36
51
 
37
52
  Because the registry model is open, `add owner/repo/component` installs from any compatible registry, not just the first-party one. See the [registry starter](https://github.com/cascivo/cascivo/tree/main/apps/examples/registry-starter) to publish your own.
38
53
 
@@ -389,11 +389,11 @@ function findRequiredPropViolations(source, filename, contract) {
389
389
  //#endregion
390
390
  //#region src/utils/contract.ts
391
391
  const HERE = dirname(fileURLToPath(import.meta.url));
392
- /** Walk up from a start directory looking for the apps/docs/public dir. */
392
+ /** Walk up from a start directory looking for the apps/site/public dir. */
393
393
  function findDocsPublic(startDir) {
394
394
  let dir = startDir;
395
395
  for (let i = 0; i < 10; i++) {
396
- const candidate = join(dir, "apps", "docs", "public");
396
+ const candidate = join(dir, "apps", "site", "public");
397
397
  if (existsSync(candidate)) return candidate;
398
398
  dir = join(dir, "..");
399
399
  }
@@ -411,18 +411,18 @@ function findRegistry(startDir) {
411
411
  }
412
412
  /**
413
413
  * Load the published cascade contract from local generated artifacts:
414
- * - token catalog (apps/docs/public/tokens.catalog.json) → value→token map
414
+ * - token catalog (apps/site/public/tokens.catalog.json) → value→token map
415
415
  * - registry.json (repo root) → component prop index
416
- * - context bundle (apps/docs/public/context.json) → which components have chrome text
416
+ * - context bundle (apps/site/public/context.json) → which components have chrome text
417
417
  */
418
418
  async function loadContract(options) {
419
419
  const docsPublic = findDocsPublic(HERE) ?? findDocsPublic(process.cwd());
420
420
  const catalogPath = options?.catalogPath ?? (docsPublic ? join(docsPublic, "tokens.catalog.json") : null);
421
421
  const contextPath = options?.contextPath ?? (docsPublic ? join(docsPublic, "context.json") : null);
422
422
  const registryPath = options?.registryPath ?? findRegistry(HERE) ?? findRegistry(process.cwd());
423
- if (!catalogPath || !existsSync(catalogPath)) throw new Error("token catalog not found (apps/docs/public/tokens.catalog.json)");
423
+ if (!catalogPath || !existsSync(catalogPath)) throw new Error("token catalog not found (apps/site/public/tokens.catalog.json)");
424
424
  if (!registryPath || !existsSync(registryPath)) throw new Error("registry.json not found");
425
- if (!contextPath || !existsSync(contextPath)) throw new Error("context bundle not found (apps/docs/public/context.json)");
425
+ if (!contextPath || !existsSync(contextPath)) throw new Error("context bundle not found (apps/site/public/context.json)");
426
426
  return buildContract({
427
427
  catalog: JSON.parse(readFileSync(catalogPath, "utf8")),
428
428
  registry: JSON.parse(readFileSync(registryPath, "utf8")),
@@ -544,7 +544,7 @@ function applyFixes(files, contract) {
544
544
  }
545
545
  async function audit(args, _config) {
546
546
  if (!args.includes("--ai")) {
547
- console.log("cascade audit: use --ai to audit AI-generated code against the cascade contract");
547
+ console.log("cascivo audit: use --ai to audit AI-generated code against the cascivo contract");
548
548
  return;
549
549
  }
550
550
  const jsonOutput = args.includes("--json");
@@ -580,4 +580,4 @@ async function audit(args, _config) {
580
580
  //#endregion
581
581
  export { audit };
582
582
 
583
- //# sourceMappingURL=audit-AHr4MDMK.mjs.map
583
+ //# sourceMappingURL=audit-InQqdY1s.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"audit-AHr4MDMK.mjs","names":[],"sources":["../src/utils/contract-pure.ts","../src/audit-ai/css-literals.ts","../src/audit-ai/jsx-props.ts","../src/audit-ai/raw-strings.ts","../src/audit-ai/required-props.ts","../src/utils/contract.ts","../src/commands/audit.ts"],"sourcesContent":["export interface PropInfo {\n name: string\n type: string\n required: boolean\n}\n\nexport interface ComponentInfo {\n props: PropInfo[]\n /** True if any prop has required: true */\n hasRequiredProps: boolean\n /** Props that have required: true */\n requiredProps: string[]\n /** True if the component declares user-facing chrome text (intent.content) */\n hasContent: boolean\n}\n\nexport interface Contract {\n /** Map from normalized color/size value → token names */\n tokensByValue: Map<string, string[]>\n /** Map from component name (PascalCase) → component info */\n components: Map<string, ComponentInfo>\n}\n\ninterface TokenEntry {\n name: string\n resolvedDefault: string | null\n}\n\ninterface CatalogFile {\n tokens: TokenEntry[]\n}\n\ninterface RegistryPropMeta {\n name: string\n type?: string\n required?: boolean\n}\n\ninterface RegistryComponentMeta {\n name: string\n props?: RegistryPropMeta[]\n}\n\ninterface RegistryEntry {\n meta?: RegistryComponentMeta\n}\n\ninterface RegistryFile {\n components: RegistryEntry[]\n}\n\ninterface ContextComponentEntry {\n name: string\n intent?: { content?: unknown }\n}\n\ninterface ContextFile {\n components: ContextComponentEntry[]\n}\n\nexport interface BuildContractInput {\n catalog: CatalogFile\n registry: RegistryFile\n context: ContextFile\n}\n\n/** Normalize a color/size value for catalog comparison: lowercase, strip spaces. */\nexport function normalizeValue(value: string): string {\n return value.toLowerCase().replace(/\\s+/g, '')\n}\n\n/** Pure builder — assemble a Contract from already-parsed JSON. Testable without fs. */\nexport function buildContract(input: BuildContractInput): Contract {\n const tokensByValue = new Map<string, string[]>()\n for (const token of input.catalog.tokens) {\n if (token.resolvedDefault == null) continue\n const key = normalizeValue(token.resolvedDefault)\n const list = tokensByValue.get(key)\n if (list) list.push(token.name)\n else tokensByValue.set(key, [token.name])\n }\n\n const contentNames = new Set<string>()\n for (const c of input.context.components) {\n if (c.intent?.content) contentNames.add(c.name)\n }\n\n const components = new Map<string, ComponentInfo>()\n for (const entry of input.registry.components) {\n const meta = entry.meta\n if (!meta?.name) continue\n const props: PropInfo[] = (meta.props ?? []).map((p) => ({\n name: p.name,\n type: p.type ?? 'unknown',\n required: p.required === true,\n }))\n const requiredProps = props.filter((p) => p.required).map((p) => p.name)\n components.set(meta.name, {\n props,\n requiredProps,\n hasRequiredProps: requiredProps.length > 0,\n hasContent: contentNames.has(meta.name),\n })\n }\n\n return { tokensByValue, components }\n}\n","import type { Contract } from '../utils/contract-pure.js'\nimport { normalizeValue } from '../utils/contract-pure.js'\n\nexport interface LiteralFinding {\n file: string\n line: number\n property: string\n value: string\n level: 'error' | 'info'\n rule: 'hardcoded-value'\n /** only when exactly one catalog match */\n suggestedToken?: string\n /** when multiple catalog matches → info */\n allMatches?: string[]\n}\n\n/** Visual CSS properties whose literal values should be tokens. */\nconst VISUAL_PROPS = new Set([\n 'color',\n 'background',\n 'background-color',\n 'border-color',\n 'box-shadow',\n 'border-radius',\n 'font-size',\n 'gap',\n 'padding',\n 'margin',\n 'width',\n 'height',\n])\n\n/** Inline-style camelCase → kebab-case for the props we care about. */\nconst INLINE_PROP_MAP: Record<string, string> = {\n color: 'color',\n background: 'background',\n backgroundColor: 'background-color',\n borderColor: 'border-color',\n boxShadow: 'box-shadow',\n borderRadius: 'border-radius',\n fontSize: 'font-size',\n gap: 'gap',\n padding: 'padding',\n margin: 'margin',\n width: 'width',\n height: 'height',\n}\n\n/** A literal value worth checking: hex, oklch/rgb/hsl(a), or px/rem number. */\nfunction isLiteralValue(value: string): boolean {\n const v = value.trim()\n if (v.includes('var(')) return false\n if (/^#[0-9a-fA-F]{3,8}$/.test(v)) return true\n if (/^(oklch|oklab|rgb|rgba|hsl|hsla)\\(/i.test(v)) return true\n if (/^-?\\d*\\.?\\d+(px|rem)$/.test(v)) return true\n return false\n}\n\nfunction classify(\n value: string,\n contract: Contract,\n): Pick<LiteralFinding, 'level' | 'suggestedToken' | 'allMatches'> | null {\n const matches = contract.tokensByValue.get(normalizeValue(value))\n if (!matches || matches.length === 0) return null\n const first = matches[0]\n if (matches.length === 1 && first) return { level: 'error', suggestedToken: first }\n return { level: 'info', allMatches: matches }\n}\n\n/**\n * Detect literal color/size values in CSS declarations and TSX inline styles\n * that exactly match a known cascade token. Heuristic, line-based — no full\n * CSS/JS parse. Values with no catalog match are NOT flagged (arbitrary brand\n * values are allowed).\n */\nexport function findCssLiteralViolations(\n source: string,\n filename: string,\n contract: Contract,\n): LiteralFinding[] {\n const findings: LiteralFinding[] = []\n const lines = source.split('\\n')\n\n // CSS declaration: `property: value;` (also matches the kebab props inside style=\"...\")\n const cssDecl = /(^|[;{\\s])([a-z-]+)\\s*:\\s*([^;}{]+?)\\s*(?=[;}]|$)/gi\n // Inline JSX style object: `color: '#fff'` or `color: \"#fff\"`\n const inlineDecl = /([A-Za-z][A-Za-z]*)\\s*:\\s*(['\"])([^'\"]+)\\2/g\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i]\n if (line === undefined) continue\n const seen = new Set<string>()\n\n for (const m of line.matchAll(cssDecl)) {\n if (m[2] === undefined || m[3] === undefined) continue\n const prop = m[2].toLowerCase()\n const rawValue = m[3].trim()\n if (!VISUAL_PROPS.has(prop)) continue\n if (!isLiteralValue(rawValue)) continue\n const cls = classify(rawValue, contract)\n if (!cls) continue\n const key = `${prop}|${rawValue}`\n seen.add(key)\n findings.push({\n file: filename,\n line: i + 1,\n property: prop,\n value: rawValue,\n rule: 'hardcoded-value',\n ...cls,\n })\n }\n\n for (const m of line.matchAll(inlineDecl)) {\n if (m[1] === undefined || m[3] === undefined) continue\n const prop = INLINE_PROP_MAP[m[1]]\n if (!prop) continue\n const rawValue = m[3].trim()\n if (!isLiteralValue(rawValue)) continue\n const key = `${prop}|${rawValue}`\n if (seen.has(key)) continue\n const cls = classify(rawValue, contract)\n if (!cls) continue\n findings.push({\n file: filename,\n line: i + 1,\n property: prop,\n value: rawValue,\n rule: 'hardcoded-value',\n ...cls,\n })\n }\n }\n\n return findings\n}\n","import type { Contract } from '../utils/contract-pure.js'\n\nexport interface PropFinding {\n file: string\n line: number\n component: string\n prop: string\n level: 'error' | 'info'\n rule: 'unknown-prop' | 'spread-suppressed'\n message: string\n}\n\n/** Props always allowed on any cascade component (DOM passthrough / React intrinsics). */\nconst PASSTHROUGH = new Set(['className', 'style', 'id', 'ref', 'key', 'children'])\n\nfunction isPassthrough(prop: string): boolean {\n if (PASSTHROUGH.has(prop)) return true\n if (prop.startsWith('data-')) return true\n if (prop.startsWith('aria-')) return true\n if (/^on[A-Z]/.test(prop)) return true\n return false\n}\n\n/** Names imported from @cascivo/react in this source. */\nexport function importedCascadeComponents(source: string): Set<string> {\n const names = new Set<string>()\n const importRe = /import\\s*\\{([^}]*)\\}\\s*from\\s*['\"]@cascivo\\/react['\"]/g\n for (const m of source.matchAll(importRe)) {\n const group = m[1]\n if (group === undefined) continue\n for (const raw of group.split(',')) {\n const name = raw\n .trim()\n .split(/\\s+as\\s+/)[0]\n ?.trim()\n if (name) names.add(name)\n }\n }\n return names\n}\n\n/** Find each opening tag for `comp`, returning its attribute substring + start index. */\nexport interface OpeningTag {\n attrs: string\n index: number\n hasSpread: boolean\n}\n\nexport function findOpeningTags(source: string, comp: string): OpeningTag[] {\n const tags: OpeningTag[] = []\n const re = new RegExp(`<${comp}(?=[\\\\s/>])`, 'g')\n for (const m of source.matchAll(re)) {\n const start = m.index ?? 0\n // Walk forward to the matching '>' that closes the opening tag, respecting\n // nested braces (JSX expressions) and quoted strings.\n let i = start + m[0].length\n let depth = 0\n let quote = ''\n let attrs = ''\n let closed = false\n for (; i < source.length; i++) {\n const ch = source[i]\n if (quote) {\n if (ch === quote) quote = ''\n attrs += ch\n continue\n }\n if (ch === '\"' || ch === \"'\" || ch === '`') {\n quote = ch\n attrs += ch\n continue\n }\n if (ch === '{') depth++\n else if (ch === '}') depth--\n else if (ch === '>' && depth === 0) {\n closed = true\n break\n }\n attrs += ch\n }\n if (!closed) continue\n const cleanAttrs = attrs.replace(/\\/$/, '')\n tags.push({ attrs: cleanAttrs, index: start, hasSpread: /\\{\\s*\\.\\.\\./.test(cleanAttrs) })\n }\n return tags\n}\n\n/** Extract top-level attribute names from an opening-tag attribute string. */\nexport function extractAttrNames(attrs: string): string[] {\n const names: string[] = []\n let depth = 0\n let quote = ''\n let token = ''\n const flush = () => {\n const name = token.trim().split('=')[0]?.trim()\n if (name && /^[A-Za-z]/.test(name)) names.push(name)\n token = ''\n }\n for (let i = 0; i < attrs.length; i++) {\n const ch = attrs[i]\n if (ch === undefined) continue\n if (quote) {\n if (ch === quote) quote = ''\n continue\n }\n if (ch === '\"' || ch === \"'\" || ch === '`') {\n quote = ch\n continue\n }\n if (ch === '{') {\n depth++\n continue\n }\n if (ch === '}') {\n depth--\n continue\n }\n if (depth > 0) continue\n if (ch === '=') {\n flush()\n // skip the value: handled by quote/brace state on next chars; reset token\n token = ''\n continue\n }\n if (/\\s/.test(ch)) {\n if (token.trim()) flush()\n continue\n }\n token += ch\n }\n if (token.trim()) flush()\n return names\n}\n\nexport function lineOf(source: string, index: number): number {\n let line = 1\n for (let i = 0; i < index && i < source.length; i++) {\n if (source[i] === '\\n') line++\n }\n return line\n}\n\n/**\n * Check JSX usages of imported cascade components for unknown props.\n * Heuristic — regex/brace-aware scan, not a full AST. Elements using a spread\n * (`{...rest}`) are reported as info and skipped (props can't be statically known).\n */\nexport function findJsxPropViolations(\n source: string,\n filename: string,\n contract: Contract,\n): PropFinding[] {\n const findings: PropFinding[] = []\n const tracked = importedCascadeComponents(source)\n\n for (const comp of tracked) {\n const info = contract.components.get(comp)\n if (!info) continue\n const known = new Set(info.props.map((p) => p.name))\n\n for (const tag of findOpeningTags(source, comp)) {\n const line = lineOf(source, tag.index)\n if (tag.hasSpread) {\n findings.push({\n file: filename,\n line,\n component: comp,\n prop: '...',\n level: 'info',\n rule: 'spread-suppressed',\n message: `<${comp}> uses a spread — prop checks skipped`,\n })\n continue\n }\n for (const name of extractAttrNames(tag.attrs)) {\n if (isPassthrough(name)) continue\n if (known.has(name)) continue\n findings.push({\n file: filename,\n line,\n component: comp,\n prop: name,\n level: 'error',\n rule: 'unknown-prop',\n message: `<${comp}> has unknown prop \"${name}\"`,\n })\n }\n }\n }\n\n return findings\n}\n","import type { Contract } from '../utils/contract-pure.js'\nimport { findOpeningTags, importedCascadeComponents, lineOf } from './jsx-props.js'\n\nexport interface RawStringFinding {\n file: string\n line: number\n component: string\n text: string\n level: 'warn'\n rule: 'raw-string'\n message: string\n}\n\n/** Looks like English prose worth flagging: ≥2 whitespace-separated words, letters/spaces only. */\nfunction looksLikeProse(text: string): boolean {\n const trimmed = text.trim()\n if (!/^[A-Za-z][A-Za-z\\s]*$/.test(trimmed)) return false\n return trimmed.split(/\\s+/).length >= 2\n}\n\n/**\n * Conservative raw-string check: for cascade components that own user-facing\n * chrome text (intent.content), warn when a literal multi-word English child\n * appears, suggesting the labels prop / i18n. Never errors. Only inspects the\n * immediate text directly after the opening tag (no nested element traversal).\n */\nexport function findRawStringViolations(\n source: string,\n filename: string,\n contract: Contract,\n): RawStringFinding[] {\n const findings: RawStringFinding[] = []\n const tracked = importedCascadeComponents(source)\n\n for (const comp of tracked) {\n const info = contract.components.get(comp)\n if (!info?.hasContent) continue\n\n for (const tag of findOpeningTags(source, comp)) {\n // Locate the end of this opening tag in the source.\n const openEnd = source.indexOf('>', tag.index)\n if (openEnd === -1) continue\n if (source[openEnd - 1] === '/') continue // self-closing, no children\n\n // Grab text up to the next tag/expression boundary.\n const after = source.slice(openEnd + 1)\n const stop = after.search(/[<{]/)\n const child = (stop === -1 ? after : after.slice(0, stop)).trim()\n if (!child || !looksLikeProse(child)) continue\n\n findings.push({\n file: filename,\n line: lineOf(source, openEnd),\n component: comp,\n text: child,\n level: 'warn',\n rule: 'raw-string',\n message: `<${comp}> raw text \"${child}\" — use the labels prop / i18n`,\n })\n }\n }\n\n return findings\n}\n","import type { Contract } from '../utils/contract-pure.js'\nimport {\n extractAttrNames,\n findOpeningTags,\n importedCascadeComponents,\n lineOf,\n} from './jsx-props.js'\n\nexport interface RequiredPropFinding {\n file: string\n line: number\n component: string\n prop: string\n level: 'error'\n rule: 'missing-prop'\n message: string\n}\n\n/**\n * Flag cascade elements that omit a prop the component marks required.\n * Elements using a spread are skipped (the prop may arrive via the spread).\n */\nexport function findRequiredPropViolations(\n source: string,\n filename: string,\n contract: Contract,\n): RequiredPropFinding[] {\n const findings: RequiredPropFinding[] = []\n const tracked = importedCascadeComponents(source)\n\n for (const comp of tracked) {\n const info = contract.components.get(comp)\n if (!info?.hasRequiredProps) continue\n\n for (const tag of findOpeningTags(source, comp)) {\n if (tag.hasSpread) continue\n const present = new Set(extractAttrNames(tag.attrs))\n const line = lineOf(source, tag.index)\n for (const req of info.requiredProps) {\n if (present.has(req)) continue\n findings.push({\n file: filename,\n line,\n component: comp,\n prop: req,\n level: 'error',\n rule: 'missing-prop',\n message: `<${comp}> requires \"${req}\"`,\n })\n }\n }\n }\n\n return findings\n}\n","import { existsSync, readFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\nexport type { BuildContractInput, ComponentInfo, Contract, PropInfo } from './contract-pure.js'\nexport { buildContract, normalizeValue } from './contract-pure.js'\nimport type { Contract } from './contract-pure.js'\nimport { buildContract } from './contract-pure.js'\n\nconst HERE = dirname(fileURLToPath(import.meta.url))\n\n/** Walk up from a start directory looking for the apps/docs/public dir. */\nfunction findDocsPublic(startDir: string): string | null {\n let dir = startDir\n for (let i = 0; i < 10; i++) {\n const candidate = join(dir, 'apps', 'docs', 'public')\n if (existsSync(candidate)) return candidate\n dir = join(dir, '..')\n }\n return null\n}\n\n/** Walk up from a start directory looking for registry.json at the repo root. */\nfunction findRegistry(startDir: string): string | null {\n let dir = startDir\n for (let i = 0; i < 10; i++) {\n const candidate = join(dir, 'registry.json')\n if (existsSync(candidate)) return candidate\n dir = join(dir, '..')\n }\n return null\n}\n\n/**\n * Load the published cascade contract from local generated artifacts:\n * - token catalog (apps/docs/public/tokens.catalog.json) → value→token map\n * - registry.json (repo root) → component prop index\n * - context bundle (apps/docs/public/context.json) → which components have chrome text\n */\nexport async function loadContract(options?: {\n catalogPath?: string\n contextPath?: string\n registryPath?: string\n}): Promise<Contract> {\n const docsPublic = findDocsPublic(HERE) ?? findDocsPublic(process.cwd())\n const catalogPath =\n options?.catalogPath ?? (docsPublic ? join(docsPublic, 'tokens.catalog.json') : null)\n const contextPath = options?.contextPath ?? (docsPublic ? join(docsPublic, 'context.json') : null)\n const registryPath = options?.registryPath ?? findRegistry(HERE) ?? findRegistry(process.cwd())\n\n if (!catalogPath || !existsSync(catalogPath)) {\n throw new Error('token catalog not found (apps/docs/public/tokens.catalog.json)')\n }\n if (!registryPath || !existsSync(registryPath)) {\n throw new Error('registry.json not found')\n }\n if (!contextPath || !existsSync(contextPath)) {\n throw new Error('context bundle not found (apps/docs/public/context.json)')\n }\n\n const catalog = JSON.parse(readFileSync(catalogPath, 'utf8')) as Parameters<\n typeof buildContract\n >[0]['catalog']\n const registry = JSON.parse(readFileSync(registryPath, 'utf8')) as Parameters<\n typeof buildContract\n >[0]['registry']\n const context = JSON.parse(readFileSync(contextPath, 'utf8')) as Parameters<\n typeof buildContract\n >[0]['context']\n\n return buildContract({ catalog, registry, context })\n}\n","import { existsSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'\nimport { extname, join } from 'node:path'\nimport type { LiteralFinding } from '../audit-ai/css-literals.js'\nimport { findCssLiteralViolations } from '../audit-ai/css-literals.js'\nimport type { PropFinding } from '../audit-ai/jsx-props.js'\nimport { findJsxPropViolations } from '../audit-ai/jsx-props.js'\nimport type { RawStringFinding } from '../audit-ai/raw-strings.js'\nimport { findRawStringViolations } from '../audit-ai/raw-strings.js'\nimport type { RequiredPropFinding } from '../audit-ai/required-props.js'\nimport { findRequiredPropViolations } from '../audit-ai/required-props.js'\nimport type { CascadeConfig } from '../utils/config.js'\nimport type { Contract } from '../utils/contract.js'\nimport { loadContract } from '../utils/contract.js'\n\nexport type Finding = LiteralFinding | PropFinding | RequiredPropFinding | RawStringFinding\n\nconst SKIP_DIRS = new Set(['node_modules', 'dist', '.git', 'build', '.next', 'coverage'])\n\nfunction collectFiles(paths: string[]): string[] {\n const out: string[] = []\n const walk = (p: string) => {\n if (!existsSync(p)) return\n const s = statSync(p)\n if (s.isDirectory()) {\n const base = p.split('/').pop() ?? ''\n if (SKIP_DIRS.has(base)) return\n for (const entry of readdirSync(p)) walk(join(p, entry))\n return\n }\n const ext = extname(p)\n if (ext === '.css' || ext === '.tsx' || ext === '.ts') out.push(p)\n }\n for (const p of paths) walk(p)\n return out\n}\n\nfunction findingsFor(file: string, source: string, contract: Contract): Finding[] {\n const ext = extname(file)\n const findings: Finding[] = []\n if (ext === '.css') {\n findings.push(...findCssLiteralViolations(source, file, contract))\n } else if (ext === '.tsx' || ext === '.ts') {\n findings.push(...findCssLiteralViolations(source, file, contract))\n findings.push(...findJsxPropViolations(source, file, contract))\n findings.push(...findRequiredPropViolations(source, file, contract))\n findings.push(...findRawStringViolations(source, file, contract))\n }\n return findings\n}\n\nfunction detail(f: Finding): string {\n switch (f.rule) {\n case 'hardcoded-value':\n if (f.suggestedToken) return `${f.value} → var(${f.suggestedToken})`\n return `${f.value} → ${f.allMatches?.join(' | ') ?? '(ambiguous)'}`\n case 'unknown-prop':\n return `<${f.component} ${f.prop}>`\n case 'spread-suppressed':\n return `<${f.component} {...}> (props not checked)`\n case 'missing-prop':\n return `<${f.component}> requires \"${f.prop}\"`\n case 'raw-string':\n return `\"${f.text}\" → use labels prop / i18n`\n }\n}\n\nfunction levelLabel(level: Finding['level']): string {\n return level === 'warn' ? 'warn' : level\n}\n\nfunction renderFindings(findings: Finding[]): void {\n if (findings.length === 0) {\n console.log('cascade audit --ai: no findings.')\n return\n }\n const rows = findings.map((f) => ({\n loc: `${f.file}:${f.line}`,\n level: levelLabel(f.level),\n rule: f.rule,\n detail: detail(f),\n }))\n const locW = Math.max(...rows.map((r) => r.loc.length), 8)\n const lvlW = Math.max(...rows.map((r) => r.level.length), 5)\n const ruleW = Math.max(...rows.map((r) => r.rule.length), 4)\n for (const r of rows) {\n console.log(\n `${r.loc.padEnd(locW)} ${r.level.padEnd(lvlW)} ${r.rule.padEnd(ruleW)} ${r.detail}`,\n )\n }\n console.log('---')\n const errors = findings.filter((f) => f.level === 'error').length\n const warnings = findings.filter((f) => f.level === 'warn').length\n const infos = findings.filter((f) => f.level === 'info').length\n const parts = [\n `${errors} error${errors === 1 ? '' : 's'}`,\n `${warnings} warning${warnings === 1 ? '' : 's'}`,\n ]\n if (infos) parts.push(`${infos} info`)\n console.log(parts.join(', '))\n}\n\nfunction escapeRe(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n}\n\n/**\n * Pure literal→token rewrite. Only rewrites simple `property: #hex;` style\n * declarations where exactly one token matches. Returns the new source and how\n * many findings were resolved (verified by re-running the checker).\n */\nexport function fixCssLiterals(\n source: string,\n file: string,\n contract: Contract,\n): { source: string; fixed: number } {\n const fixable = findCssLiteralViolations(source, file, contract).filter(\n (f) => f.level === 'error' && f.suggestedToken && /^#[0-9a-fA-F]{3,8}$/.test(f.value),\n )\n let next = source\n for (const f of fixable) {\n // Only rewrite a full-value declaration: `prop: #hex;` (or end of block).\n const re = new RegExp(`(${escapeRe(f.property)}\\\\s*:\\\\s*)${escapeRe(f.value)}(\\\\s*[;}])`, 'gi')\n next = next.replace(re, `$1var(${f.suggestedToken})$2`)\n }\n if (next === source) return { source, fixed: 0 }\n const remaining = findCssLiteralViolations(next, file, contract).filter(\n (f) => f.level === 'error' && f.suggestedToken,\n ).length\n return { source: next, fixed: fixable.length - remaining }\n}\n\n/** Apply {@link fixCssLiterals} to each .css file on disk. */\nfunction applyFixes(files: string[], contract: Contract): number {\n let fixed = 0\n for (const file of files) {\n if (extname(file) !== '.css') continue\n const { source, fixed: n } = fixCssLiterals(readFileSync(file, 'utf8'), file, contract)\n if (n > 0) {\n writeFileSync(file, source)\n fixed += n\n }\n }\n return fixed\n}\n\nexport async function audit(args: string[], _config: CascadeConfig): Promise<void> {\n if (!args.includes('--ai')) {\n console.log('cascade audit: use --ai to audit AI-generated code against the cascade contract')\n return\n }\n\n const jsonOutput = args.includes('--json')\n const fixMode = args.includes('--fix')\n const levelIdx = args.indexOf('--level')\n const minLevel = levelIdx >= 0 ? (args[levelIdx + 1] ?? 'error') : 'error'\n\n const paths = args.filter((a, i) => {\n if (a.startsWith('--')) return false\n if (levelIdx >= 0 && i === levelIdx + 1) return false\n return true\n })\n\n let contract: Contract\n try {\n contract = await loadContract()\n } catch (e) {\n console.error(`Contract unavailable: ${e instanceof Error ? e.message : String(e)}`)\n process.exitCode = 2\n return\n }\n\n const files = collectFiles(paths.length ? paths : [process.cwd()])\n\n if (fixMode) {\n const n = applyFixes(files, contract)\n console.log(`cascade audit --ai --fix: rewrote ${n} literal${n === 1 ? '' : 's'} to tokens.`)\n }\n\n const allFindings: Finding[] = []\n for (const file of files) {\n allFindings.push(...findingsFor(file, readFileSync(file, 'utf8'), contract))\n }\n\n if (jsonOutput) {\n console.log(JSON.stringify(allFindings, null, 2))\n } else {\n renderFindings(allFindings)\n }\n\n const hasErrors = allFindings.some((f) => f.level === 'error')\n if (minLevel === 'error' && hasErrors) process.exitCode = 1\n if (minLevel === 'warn' && allFindings.some((f) => f.level !== 'info')) process.exitCode = 1\n}\n"],"mappings":";;;;;AAmEA,SAAgB,eAAe,OAAuB;CACpD,OAAO,MAAM,YAAY,CAAC,CAAC,QAAQ,QAAQ,EAAE;AAC/C;;AAGA,SAAgB,cAAc,OAAqC;CACjE,MAAM,gCAAgB,IAAI,IAAsB;CAChD,KAAK,MAAM,SAAS,MAAM,QAAQ,QAAQ;EACxC,IAAI,MAAM,mBAAmB,MAAM;EACnC,MAAM,MAAM,eAAe,MAAM,eAAe;EAChD,MAAM,OAA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AAe,WAAW;CAG5B,MAAM,YAAY,YAAY,MAAM,MAAM,EAAE,UAAU,OAAO;CAC7D,IAAI,aAAa,WAAW,WAAW,QAAQ,WAAW;CAC1D,IAAI,aAAa,UAAU,YAAY,MAAM,MAAM,EAAE,UAAU,MAAM,GAAG,QAAQ,WAAW;AAC7F"}
1
+ {"version":3,"file":"audit-InQqdY1s.mjs","names":[],"sources":["../src/utils/contract-pure.ts","../src/audit-ai/css-literals.ts","../src/audit-ai/jsx-props.ts","../src/audit-ai/raw-strings.ts","../src/audit-ai/required-props.ts","../src/utils/contract.ts","../src/commands/audit.ts"],"sourcesContent":["export interface PropInfo {\n name: string\n type: string\n required: boolean\n}\n\nexport interface ComponentInfo {\n props: PropInfo[]\n /** True if any prop has required: true */\n hasRequiredProps: boolean\n /** Props that have required: true */\n requiredProps: string[]\n /** True if the component declares user-facing chrome text (intent.content) */\n hasContent: boolean\n}\n\nexport interface Contract {\n /** Map from normalized color/size value → token names */\n tokensByValue: Map<string, string[]>\n /** Map from component name (PascalCase) → component info */\n components: Map<string, ComponentInfo>\n}\n\ninterface TokenEntry {\n name: string\n resolvedDefault: string | null\n}\n\ninterface CatalogFile {\n tokens: TokenEntry[]\n}\n\ninterface RegistryPropMeta {\n name: string\n type?: string\n required?: boolean\n}\n\ninterface RegistryComponentMeta {\n name: string\n props?: RegistryPropMeta[]\n}\n\ninterface RegistryEntry {\n meta?: RegistryComponentMeta\n}\n\ninterface RegistryFile {\n components: RegistryEntry[]\n}\n\ninterface ContextComponentEntry {\n name: string\n intent?: { content?: unknown }\n}\n\ninterface ContextFile {\n components: ContextComponentEntry[]\n}\n\nexport interface BuildContractInput {\n catalog: CatalogFile\n registry: RegistryFile\n context: ContextFile\n}\n\n/** Normalize a color/size value for catalog comparison: lowercase, strip spaces. */\nexport function normalizeValue(value: string): string {\n return value.toLowerCase().replace(/\\s+/g, '')\n}\n\n/** Pure builder — assemble a Contract from already-parsed JSON. Testable without fs. */\nexport function buildContract(input: BuildContractInput): Contract {\n const tokensByValue = new Map<string, string[]>()\n for (const token of input.catalog.tokens) {\n if (token.resolvedDefault == null) continue\n const key = normalizeValue(token.resolvedDefault)\n const list = tokensByValue.get(key)\n if (list) list.push(token.name)\n else tokensByValue.set(key, [token.name])\n }\n\n const contentNames = new Set<string>()\n for (const c of input.context.components) {\n if (c.intent?.content) contentNames.add(c.name)\n }\n\n const components = new Map<string, ComponentInfo>()\n for (const entry of input.registry.components) {\n const meta = entry.meta\n if (!meta?.name) continue\n const props: PropInfo[] = (meta.props ?? []).map((p) => ({\n name: p.name,\n type: p.type ?? 'unknown',\n required: p.required === true,\n }))\n const requiredProps = props.filter((p) => p.required).map((p) => p.name)\n components.set(meta.name, {\n props,\n requiredProps,\n hasRequiredProps: requiredProps.length > 0,\n hasContent: contentNames.has(meta.name),\n })\n }\n\n return { tokensByValue, components }\n}\n","import type { Contract } from '../utils/contract-pure.js'\nimport { normalizeValue } from '../utils/contract-pure.js'\n\nexport interface LiteralFinding {\n file: string\n line: number\n property: string\n value: string\n level: 'error' | 'info'\n rule: 'hardcoded-value'\n /** only when exactly one catalog match */\n suggestedToken?: string\n /** when multiple catalog matches → info */\n allMatches?: string[]\n}\n\n/** Visual CSS properties whose literal values should be tokens. */\nconst VISUAL_PROPS = new Set([\n 'color',\n 'background',\n 'background-color',\n 'border-color',\n 'box-shadow',\n 'border-radius',\n 'font-size',\n 'gap',\n 'padding',\n 'margin',\n 'width',\n 'height',\n])\n\n/** Inline-style camelCase → kebab-case for the props we care about. */\nconst INLINE_PROP_MAP: Record<string, string> = {\n color: 'color',\n background: 'background',\n backgroundColor: 'background-color',\n borderColor: 'border-color',\n boxShadow: 'box-shadow',\n borderRadius: 'border-radius',\n fontSize: 'font-size',\n gap: 'gap',\n padding: 'padding',\n margin: 'margin',\n width: 'width',\n height: 'height',\n}\n\n/** A literal value worth checking: hex, oklch/rgb/hsl(a), or px/rem number. */\nfunction isLiteralValue(value: string): boolean {\n const v = value.trim()\n if (v.includes('var(')) return false\n if (/^#[0-9a-fA-F]{3,8}$/.test(v)) return true\n if (/^(oklch|oklab|rgb|rgba|hsl|hsla)\\(/i.test(v)) return true\n if (/^-?\\d*\\.?\\d+(px|rem)$/.test(v)) return true\n return false\n}\n\nfunction classify(\n value: string,\n contract: Contract,\n): Pick<LiteralFinding, 'level' | 'suggestedToken' | 'allMatches'> | null {\n const matches = contract.tokensByValue.get(normalizeValue(value))\n if (!matches || matches.length === 0) return null\n const first = matches[0]\n if (matches.length === 1 && first) return { level: 'error', suggestedToken: first }\n return { level: 'info', allMatches: matches }\n}\n\n/**\n * Detect literal color/size values in CSS declarations and TSX inline styles\n * that exactly match a known cascade token. Heuristic, line-based — no full\n * CSS/JS parse. Values with no catalog match are NOT flagged (arbitrary brand\n * values are allowed).\n */\nexport function findCssLiteralViolations(\n source: string,\n filename: string,\n contract: Contract,\n): LiteralFinding[] {\n const findings: LiteralFinding[] = []\n const lines = source.split('\\n')\n\n // CSS declaration: `property: value;` (also matches the kebab props inside style=\"...\")\n const cssDecl = /(^|[;{\\s])([a-z-]+)\\s*:\\s*([^;}{]+?)\\s*(?=[;}]|$)/gi\n // Inline JSX style object: `color: '#fff'` or `color: \"#fff\"`\n const inlineDecl = /([A-Za-z][A-Za-z]*)\\s*:\\s*(['\"])([^'\"]+)\\2/g\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i]\n if (line === undefined) continue\n const seen = new Set<string>()\n\n for (const m of line.matchAll(cssDecl)) {\n if (m[2] === undefined || m[3] === undefined) continue\n const prop = m[2].toLowerCase()\n const rawValue = m[3].trim()\n if (!VISUAL_PROPS.has(prop)) continue\n if (!isLiteralValue(rawValue)) continue\n const cls = classify(rawValue, contract)\n if (!cls) continue\n const key = `${prop}|${rawValue}`\n seen.add(key)\n findings.push({\n file: filename,\n line: i + 1,\n property: prop,\n value: rawValue,\n rule: 'hardcoded-value',\n ...cls,\n })\n }\n\n for (const m of line.matchAll(inlineDecl)) {\n if (m[1] === undefined || m[3] === undefined) continue\n const prop = INLINE_PROP_MAP[m[1]]\n if (!prop) continue\n const rawValue = m[3].trim()\n if (!isLiteralValue(rawValue)) continue\n const key = `${prop}|${rawValue}`\n if (seen.has(key)) continue\n const cls = classify(rawValue, contract)\n if (!cls) continue\n findings.push({\n file: filename,\n line: i + 1,\n property: prop,\n value: rawValue,\n rule: 'hardcoded-value',\n ...cls,\n })\n }\n }\n\n return findings\n}\n","import type { Contract } from '../utils/contract-pure.js'\n\nexport interface PropFinding {\n file: string\n line: number\n component: string\n prop: string\n level: 'error' | 'info'\n rule: 'unknown-prop' | 'spread-suppressed'\n message: string\n}\n\n/** Props always allowed on any cascade component (DOM passthrough / React intrinsics). */\nconst PASSTHROUGH = new Set(['className', 'style', 'id', 'ref', 'key', 'children'])\n\nfunction isPassthrough(prop: string): boolean {\n if (PASSTHROUGH.has(prop)) return true\n if (prop.startsWith('data-')) return true\n if (prop.startsWith('aria-')) return true\n if (/^on[A-Z]/.test(prop)) return true\n return false\n}\n\n/** Names imported from @cascivo/react in this source. */\nexport function importedCascadeComponents(source: string): Set<string> {\n const names = new Set<string>()\n const importRe = /import\\s*\\{([^}]*)\\}\\s*from\\s*['\"]@cascivo\\/react['\"]/g\n for (const m of source.matchAll(importRe)) {\n const group = m[1]\n if (group === undefined) continue\n for (const raw of group.split(',')) {\n const name = raw\n .trim()\n .split(/\\s+as\\s+/)[0]\n ?.trim()\n if (name) names.add(name)\n }\n }\n return names\n}\n\n/** Find each opening tag for `comp`, returning its attribute substring + start index. */\nexport interface OpeningTag {\n attrs: string\n index: number\n hasSpread: boolean\n}\n\nexport function findOpeningTags(source: string, comp: string): OpeningTag[] {\n const tags: OpeningTag[] = []\n const re = new RegExp(`<${comp}(?=[\\\\s/>])`, 'g')\n for (const m of source.matchAll(re)) {\n const start = m.index ?? 0\n // Walk forward to the matching '>' that closes the opening tag, respecting\n // nested braces (JSX expressions) and quoted strings.\n let i = start + m[0].length\n let depth = 0\n let quote = ''\n let attrs = ''\n let closed = false\n for (; i < source.length; i++) {\n const ch = source[i]\n if (quote) {\n if (ch === quote) quote = ''\n attrs += ch\n continue\n }\n if (ch === '\"' || ch === \"'\" || ch === '`') {\n quote = ch\n attrs += ch\n continue\n }\n if (ch === '{') depth++\n else if (ch === '}') depth--\n else if (ch === '>' && depth === 0) {\n closed = true\n break\n }\n attrs += ch\n }\n if (!closed) continue\n const cleanAttrs = attrs.replace(/\\/$/, '')\n tags.push({ attrs: cleanAttrs, index: start, hasSpread: /\\{\\s*\\.\\.\\./.test(cleanAttrs) })\n }\n return tags\n}\n\n/** Extract top-level attribute names from an opening-tag attribute string. */\nexport function extractAttrNames(attrs: string): string[] {\n const names: string[] = []\n let depth = 0\n let quote = ''\n let token = ''\n const flush = () => {\n const name = token.trim().split('=')[0]?.trim()\n if (name && /^[A-Za-z]/.test(name)) names.push(name)\n token = ''\n }\n for (let i = 0; i < attrs.length; i++) {\n const ch = attrs[i]\n if (ch === undefined) continue\n if (quote) {\n if (ch === quote) quote = ''\n continue\n }\n if (ch === '\"' || ch === \"'\" || ch === '`') {\n quote = ch\n continue\n }\n if (ch === '{') {\n depth++\n continue\n }\n if (ch === '}') {\n depth--\n continue\n }\n if (depth > 0) continue\n if (ch === '=') {\n flush()\n // skip the value: handled by quote/brace state on next chars; reset token\n token = ''\n continue\n }\n if (/\\s/.test(ch)) {\n if (token.trim()) flush()\n continue\n }\n token += ch\n }\n if (token.trim()) flush()\n return names\n}\n\nexport function lineOf(source: string, index: number): number {\n let line = 1\n for (let i = 0; i < index && i < source.length; i++) {\n if (source[i] === '\\n') line++\n }\n return line\n}\n\n/**\n * Check JSX usages of imported cascade components for unknown props.\n * Heuristic — regex/brace-aware scan, not a full AST. Elements using a spread\n * (`{...rest}`) are reported as info and skipped (props can't be statically known).\n */\nexport function findJsxPropViolations(\n source: string,\n filename: string,\n contract: Contract,\n): PropFinding[] {\n const findings: PropFinding[] = []\n const tracked = importedCascadeComponents(source)\n\n for (const comp of tracked) {\n const info = contract.components.get(comp)\n if (!info) continue\n const known = new Set(info.props.map((p) => p.name))\n\n for (const tag of findOpeningTags(source, comp)) {\n const line = lineOf(source, tag.index)\n if (tag.hasSpread) {\n findings.push({\n file: filename,\n line,\n component: comp,\n prop: '...',\n level: 'info',\n rule: 'spread-suppressed',\n message: `<${comp}> uses a spread — prop checks skipped`,\n })\n continue\n }\n for (const name of extractAttrNames(tag.attrs)) {\n if (isPassthrough(name)) continue\n if (known.has(name)) continue\n findings.push({\n file: filename,\n line,\n component: comp,\n prop: name,\n level: 'error',\n rule: 'unknown-prop',\n message: `<${comp}> has unknown prop \"${name}\"`,\n })\n }\n }\n }\n\n return findings\n}\n","import type { Contract } from '../utils/contract-pure.js'\nimport { findOpeningTags, importedCascadeComponents, lineOf } from './jsx-props.js'\n\nexport interface RawStringFinding {\n file: string\n line: number\n component: string\n text: string\n level: 'warn'\n rule: 'raw-string'\n message: string\n}\n\n/** Looks like English prose worth flagging: ≥2 whitespace-separated words, letters/spaces only. */\nfunction looksLikeProse(text: string): boolean {\n const trimmed = text.trim()\n if (!/^[A-Za-z][A-Za-z\\s]*$/.test(trimmed)) return false\n return trimmed.split(/\\s+/).length >= 2\n}\n\n/**\n * Conservative raw-string check: for cascade components that own user-facing\n * chrome text (intent.content), warn when a literal multi-word English child\n * appears, suggesting the labels prop / i18n. Never errors. Only inspects the\n * immediate text directly after the opening tag (no nested element traversal).\n */\nexport function findRawStringViolations(\n source: string,\n filename: string,\n contract: Contract,\n): RawStringFinding[] {\n const findings: RawStringFinding[] = []\n const tracked = importedCascadeComponents(source)\n\n for (const comp of tracked) {\n const info = contract.components.get(comp)\n if (!info?.hasContent) continue\n\n for (const tag of findOpeningTags(source, comp)) {\n // Locate the end of this opening tag in the source.\n const openEnd = source.indexOf('>', tag.index)\n if (openEnd === -1) continue\n if (source[openEnd - 1] === '/') continue // self-closing, no children\n\n // Grab text up to the next tag/expression boundary.\n const after = source.slice(openEnd + 1)\n const stop = after.search(/[<{]/)\n const child = (stop === -1 ? after : after.slice(0, stop)).trim()\n if (!child || !looksLikeProse(child)) continue\n\n findings.push({\n file: filename,\n line: lineOf(source, openEnd),\n component: comp,\n text: child,\n level: 'warn',\n rule: 'raw-string',\n message: `<${comp}> raw text \"${child}\" — use the labels prop / i18n`,\n })\n }\n }\n\n return findings\n}\n","import type { Contract } from '../utils/contract-pure.js'\nimport {\n extractAttrNames,\n findOpeningTags,\n importedCascadeComponents,\n lineOf,\n} from './jsx-props.js'\n\nexport interface RequiredPropFinding {\n file: string\n line: number\n component: string\n prop: string\n level: 'error'\n rule: 'missing-prop'\n message: string\n}\n\n/**\n * Flag cascade elements that omit a prop the component marks required.\n * Elements using a spread are skipped (the prop may arrive via the spread).\n */\nexport function findRequiredPropViolations(\n source: string,\n filename: string,\n contract: Contract,\n): RequiredPropFinding[] {\n const findings: RequiredPropFinding[] = []\n const tracked = importedCascadeComponents(source)\n\n for (const comp of tracked) {\n const info = contract.components.get(comp)\n if (!info?.hasRequiredProps) continue\n\n for (const tag of findOpeningTags(source, comp)) {\n if (tag.hasSpread) continue\n const present = new Set(extractAttrNames(tag.attrs))\n const line = lineOf(source, tag.index)\n for (const req of info.requiredProps) {\n if (present.has(req)) continue\n findings.push({\n file: filename,\n line,\n component: comp,\n prop: req,\n level: 'error',\n rule: 'missing-prop',\n message: `<${comp}> requires \"${req}\"`,\n })\n }\n }\n }\n\n return findings\n}\n","import { existsSync, readFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\nexport type { BuildContractInput, ComponentInfo, Contract, PropInfo } from './contract-pure.js'\nexport { buildContract, normalizeValue } from './contract-pure.js'\nimport type { Contract } from './contract-pure.js'\nimport { buildContract } from './contract-pure.js'\n\nconst HERE = dirname(fileURLToPath(import.meta.url))\n\n/** Walk up from a start directory looking for the apps/site/public dir. */\nfunction findDocsPublic(startDir: string): string | null {\n let dir = startDir\n for (let i = 0; i < 10; i++) {\n const candidate = join(dir, 'apps', 'site', 'public')\n if (existsSync(candidate)) return candidate\n dir = join(dir, '..')\n }\n return null\n}\n\n/** Walk up from a start directory looking for registry.json at the repo root. */\nfunction findRegistry(startDir: string): string | null {\n let dir = startDir\n for (let i = 0; i < 10; i++) {\n const candidate = join(dir, 'registry.json')\n if (existsSync(candidate)) return candidate\n dir = join(dir, '..')\n }\n return null\n}\n\n/**\n * Load the published cascade contract from local generated artifacts:\n * - token catalog (apps/site/public/tokens.catalog.json) → value→token map\n * - registry.json (repo root) → component prop index\n * - context bundle (apps/site/public/context.json) → which components have chrome text\n */\nexport async function loadContract(options?: {\n catalogPath?: string\n contextPath?: string\n registryPath?: string\n}): Promise<Contract> {\n const docsPublic = findDocsPublic(HERE) ?? findDocsPublic(process.cwd())\n const catalogPath =\n options?.catalogPath ?? (docsPublic ? join(docsPublic, 'tokens.catalog.json') : null)\n const contextPath = options?.contextPath ?? (docsPublic ? join(docsPublic, 'context.json') : null)\n const registryPath = options?.registryPath ?? findRegistry(HERE) ?? findRegistry(process.cwd())\n\n if (!catalogPath || !existsSync(catalogPath)) {\n throw new Error('token catalog not found (apps/site/public/tokens.catalog.json)')\n }\n if (!registryPath || !existsSync(registryPath)) {\n throw new Error('registry.json not found')\n }\n if (!contextPath || !existsSync(contextPath)) {\n throw new Error('context bundle not found (apps/site/public/context.json)')\n }\n\n const catalog = JSON.parse(readFileSync(catalogPath, 'utf8')) as Parameters<\n typeof buildContract\n >[0]['catalog']\n const registry = JSON.parse(readFileSync(registryPath, 'utf8')) as Parameters<\n typeof buildContract\n >[0]['registry']\n const context = JSON.parse(readFileSync(contextPath, 'utf8')) as Parameters<\n typeof buildContract\n >[0]['context']\n\n return buildContract({ catalog, registry, context })\n}\n","import { existsSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'\nimport { extname, join } from 'node:path'\nimport type { LiteralFinding } from '../audit-ai/css-literals.js'\nimport { findCssLiteralViolations } from '../audit-ai/css-literals.js'\nimport type { PropFinding } from '../audit-ai/jsx-props.js'\nimport { findJsxPropViolations } from '../audit-ai/jsx-props.js'\nimport type { RawStringFinding } from '../audit-ai/raw-strings.js'\nimport { findRawStringViolations } from '../audit-ai/raw-strings.js'\nimport type { RequiredPropFinding } from '../audit-ai/required-props.js'\nimport { findRequiredPropViolations } from '../audit-ai/required-props.js'\nimport type { CascadeConfig } from '../utils/config.js'\nimport type { Contract } from '../utils/contract.js'\nimport { loadContract } from '../utils/contract.js'\n\nexport type Finding = LiteralFinding | PropFinding | RequiredPropFinding | RawStringFinding\n\nconst SKIP_DIRS = new Set(['node_modules', 'dist', '.git', 'build', '.next', 'coverage'])\n\nfunction collectFiles(paths: string[]): string[] {\n const out: string[] = []\n const walk = (p: string) => {\n if (!existsSync(p)) return\n const s = statSync(p)\n if (s.isDirectory()) {\n const base = p.split('/').pop() ?? ''\n if (SKIP_DIRS.has(base)) return\n for (const entry of readdirSync(p)) walk(join(p, entry))\n return\n }\n const ext = extname(p)\n if (ext === '.css' || ext === '.tsx' || ext === '.ts') out.push(p)\n }\n for (const p of paths) walk(p)\n return out\n}\n\nfunction findingsFor(file: string, source: string, contract: Contract): Finding[] {\n const ext = extname(file)\n const findings: Finding[] = []\n if (ext === '.css') {\n findings.push(...findCssLiteralViolations(source, file, contract))\n } else if (ext === '.tsx' || ext === '.ts') {\n findings.push(...findCssLiteralViolations(source, file, contract))\n findings.push(...findJsxPropViolations(source, file, contract))\n findings.push(...findRequiredPropViolations(source, file, contract))\n findings.push(...findRawStringViolations(source, file, contract))\n }\n return findings\n}\n\nfunction detail(f: Finding): string {\n switch (f.rule) {\n case 'hardcoded-value':\n if (f.suggestedToken) return `${f.value} → var(${f.suggestedToken})`\n return `${f.value} → ${f.allMatches?.join(' | ') ?? '(ambiguous)'}`\n case 'unknown-prop':\n return `<${f.component} ${f.prop}>`\n case 'spread-suppressed':\n return `<${f.component} {...}> (props not checked)`\n case 'missing-prop':\n return `<${f.component}> requires \"${f.prop}\"`\n case 'raw-string':\n return `\"${f.text}\" → use labels prop / i18n`\n }\n}\n\nfunction levelLabel(level: Finding['level']): string {\n return level === 'warn' ? 'warn' : level\n}\n\nfunction renderFindings(findings: Finding[]): void {\n if (findings.length === 0) {\n console.log('cascade audit --ai: no findings.')\n return\n }\n const rows = findings.map((f) => ({\n loc: `${f.file}:${f.line}`,\n level: levelLabel(f.level),\n rule: f.rule,\n detail: detail(f),\n }))\n const locW = Math.max(...rows.map((r) => r.loc.length), 8)\n const lvlW = Math.max(...rows.map((r) => r.level.length), 5)\n const ruleW = Math.max(...rows.map((r) => r.rule.length), 4)\n for (const r of rows) {\n console.log(\n `${r.loc.padEnd(locW)} ${r.level.padEnd(lvlW)} ${r.rule.padEnd(ruleW)} ${r.detail}`,\n )\n }\n console.log('---')\n const errors = findings.filter((f) => f.level === 'error').length\n const warnings = findings.filter((f) => f.level === 'warn').length\n const infos = findings.filter((f) => f.level === 'info').length\n const parts = [\n `${errors} error${errors === 1 ? '' : 's'}`,\n `${warnings} warning${warnings === 1 ? '' : 's'}`,\n ]\n if (infos) parts.push(`${infos} info`)\n console.log(parts.join(', '))\n}\n\nfunction escapeRe(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n}\n\n/**\n * Pure literal→token rewrite. Only rewrites simple `property: #hex;` style\n * declarations where exactly one token matches. Returns the new source and how\n * many findings were resolved (verified by re-running the checker).\n */\nexport function fixCssLiterals(\n source: string,\n file: string,\n contract: Contract,\n): { source: string; fixed: number } {\n const fixable = findCssLiteralViolations(source, file, contract).filter(\n (f) => f.level === 'error' && f.suggestedToken && /^#[0-9a-fA-F]{3,8}$/.test(f.value),\n )\n let next = source\n for (const f of fixable) {\n // Only rewrite a full-value declaration: `prop: #hex;` (or end of block).\n const re = new RegExp(`(${escapeRe(f.property)}\\\\s*:\\\\s*)${escapeRe(f.value)}(\\\\s*[;}])`, 'gi')\n next = next.replace(re, `$1var(${f.suggestedToken})$2`)\n }\n if (next === source) return { source, fixed: 0 }\n const remaining = findCssLiteralViolations(next, file, contract).filter(\n (f) => f.level === 'error' && f.suggestedToken,\n ).length\n return { source: next, fixed: fixable.length - remaining }\n}\n\n/** Apply {@link fixCssLiterals} to each .css file on disk. */\nfunction applyFixes(files: string[], contract: Contract): number {\n let fixed = 0\n for (const file of files) {\n if (extname(file) !== '.css') continue\n const { source, fixed: n } = fixCssLiterals(readFileSync(file, 'utf8'), file, contract)\n if (n > 0) {\n writeFileSync(file, source)\n fixed += n\n }\n }\n return fixed\n}\n\nexport async function audit(args: string[], _config: CascadeConfig): Promise<void> {\n if (!args.includes('--ai')) {\n console.log('cascivo audit: use --ai to audit AI-generated code against the cascivo contract')\n return\n }\n\n const jsonOutput = args.includes('--json')\n const fixMode = args.includes('--fix')\n const levelIdx = args.indexOf('--level')\n const minLevel = levelIdx >= 0 ? (args[levelIdx + 1] ?? 'error') : 'error'\n\n const paths = args.filter((a, i) => {\n if (a.startsWith('--')) return false\n if (levelIdx >= 0 && i === levelIdx + 1) return false\n return true\n })\n\n let contract: Contract\n try {\n contract = await loadContract()\n } catch (e) {\n console.error(`Contract unavailable: ${e instanceof Error ? e.message : String(e)}`)\n process.exitCode = 2\n return\n }\n\n const files = collectFiles(paths.length ? paths : [process.cwd()])\n\n if (fixMode) {\n const n = applyFixes(files, contract)\n console.log(`cascade audit --ai --fix: rewrote ${n} literal${n === 1 ? '' : 's'} to tokens.`)\n }\n\n const allFindings: Finding[] = []\n for (const file of files) {\n allFindings.push(...findingsFor(file, readFileSync(file, 'utf8'), contract))\n }\n\n if (jsonOutput) {\n console.log(JSON.stringify(allFindings, null, 2))\n } else {\n renderFindings(allFindings)\n }\n\n const hasErrors = allFindings.some((f) => f.level === 'error')\n if (minLevel === 'error' && hasErrors) process.exitCode = 1\n if (minLevel === 'warn' && allFindings.some((f) => f.level !== 'info')) process.exitCode = 1\n}\n"],"mappings":";;;;;AAmEA,SAAgB,eAAe,OAAuB;CACpD,OAAO,MAAM,YAAY,CAAC,CAAC,QAAQ,QAAQ,EAAE;AAC/C;;AAGA,SAAgB,cA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AChC,KAAK,MAAM,QAAQ,OACjB,YAAY,KAAK,GAAG,YAAY,MAAM,aAAa,MAAM,MAAM,GAAG,QAAQ,CAAC;CAG7E,IAAI,YACF,QAAQ,IAAI,KAAK,UAAU,aAAa,MAAM,CAAC,CAAC;MAEhD,eAAe,WAAW;CAG5B,MAAM,YAAY,YAAY,MAAM,MAAM,EAAE,UAAU,OAAO;CAC7D,IAAI,aAAa,WAAW,WAAW,QAAQ,WAAW;CAC1D,IAAI,aAAa,UAAU,YAAY,MAAM,MAAM,EAAE,UAAU,MAAM,GAAG,QAAQ,WAAW;AAC7F"}
@@ -0,0 +1,106 @@
1
+ import "node:module";
2
+ import { pathToFileURL } from "node:url";
3
+ import { existsSync } from "node:fs";
4
+ import { join } from "node:path";
5
+ //#region \0rolldown/runtime.js
6
+ var __defProp = Object.defineProperty;
7
+ var __exportAll = (all, no_symbols) => {
8
+ let target = {};
9
+ for (var name in all) __defProp(target, name, {
10
+ get: all[name],
11
+ enumerable: true
12
+ });
13
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
14
+ return target;
15
+ };
16
+ //#endregion
17
+ //#region src/utils/config.ts
18
+ var config_exports = /* @__PURE__ */ __exportAll({
19
+ CASCIVO_HOST: () => CASCIVO_HOST,
20
+ DEFAULT_CONFIG: () => DEFAULT_CONFIG,
21
+ THEMES: () => THEMES,
22
+ applyEnvOverrides: () => applyEnvOverrides,
23
+ detectPackageManager: () => detectPackageManager,
24
+ installCommand: () => installCommand,
25
+ loadConfig: () => loadConfig,
26
+ resolveConfig: () => resolveConfig
27
+ });
28
+ /**
29
+ * Canonical host for hosted cascivo artifacts (registry.json, per-item
30
+ * r/<name>.json, marketplace.json). docs.cascivo.com mirrors the same tree.
31
+ * Keep in sync with CASCIVO_HOST in packages/mcp.
32
+ */
33
+ const CASCIVO_HOST = "https://cascivo.com";
34
+ /** All first-party themes shipped by @cascivo/themes (selectable via data-theme). */
35
+ const THEMES = [
36
+ "light",
37
+ "dark",
38
+ "warm",
39
+ "flat",
40
+ "minimal",
41
+ "midnight",
42
+ "pastel",
43
+ "brutalist",
44
+ "corporate",
45
+ "terminal",
46
+ "cyberpunk",
47
+ "arcade"
48
+ ];
49
+ const DEFAULT_CONFIG = {
50
+ registry: `${CASCIVO_HOST}/registry.json`,
51
+ outputDir: "src/components/ui",
52
+ theme: "light"
53
+ };
54
+ const CONFIG_FILES = [
55
+ "cascivo.config.ts",
56
+ "cascivo.config.js",
57
+ "cascivo.config.mjs"
58
+ ];
59
+ /** Apply defaults over a (possibly partial) user config object. */
60
+ function resolveConfig(partial) {
61
+ return {
62
+ ...DEFAULT_CONFIG,
63
+ ...partial
64
+ };
65
+ }
66
+ /** Let env vars override config — used by the MCP server to pass `outputDir`. */
67
+ function applyEnvOverrides(config, env = process.env) {
68
+ return {
69
+ ...config,
70
+ ...env.CASCIVO_REGISTRY ? { registry: env.CASCIVO_REGISTRY } : {},
71
+ ...env.CASCIVO_OUTPUT_DIR ? { outputDir: env.CASCIVO_OUTPUT_DIR } : {}
72
+ };
73
+ }
74
+ /**
75
+ * Locate and load `cascivo.config.{ts,js,mjs}` from `cwd`. Falls back to the
76
+ * default config when no file is found or the file cannot be loaded. Env vars
77
+ * (`CASCIVO_REGISTRY`, `CASCIVO_OUTPUT_DIR`) take precedence.
78
+ */
79
+ async function loadConfig(cwd = process.cwd()) {
80
+ for (const file of CONFIG_FILES) {
81
+ const path = join(cwd, file);
82
+ if (!existsSync(path)) continue;
83
+ try {
84
+ const mod = await import(pathToFileURL(path).href);
85
+ return applyEnvOverrides(resolveConfig(mod.default ?? mod));
86
+ } catch {
87
+ return applyEnvOverrides(resolveConfig(null));
88
+ }
89
+ }
90
+ return applyEnvOverrides(resolveConfig(null));
91
+ }
92
+ /** Detect the package manager in use from lock files, defaulting to npm. */
93
+ function detectPackageManager(cwd = process.cwd()) {
94
+ if (existsSync(join(cwd, "pnpm-lock.yaml"))) return "pnpm";
95
+ if (existsSync(join(cwd, "yarn.lock"))) return "yarn";
96
+ if (existsSync(join(cwd, "bun.lockb"))) return "bun";
97
+ return "npm";
98
+ }
99
+ /** The install subcommand each package manager uses to add dependencies. */
100
+ function installCommand(pm, packages) {
101
+ return [pm, [pm === "npm" ? "install" : "add", ...packages]];
102
+ }
103
+ //#endregion
104
+ export { detectPackageManager as a, __exportAll as c, config_exports as i, DEFAULT_CONFIG as n, installCommand as o, THEMES as r, loadConfig as s, CASCIVO_HOST as t };
105
+
106
+ //# sourceMappingURL=config-BsyJbMvD.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config-BsyJbMvD.mjs","names":[],"sources":["../src/utils/config.ts"],"sourcesContent":["import { existsSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { pathToFileURL } from 'node:url'\n\n/**\n * Canonical host for hosted cascivo artifacts (registry.json, per-item\n * r/<name>.json, marketplace.json). docs.cascivo.com mirrors the same tree.\n * Keep in sync with CASCIVO_HOST in packages/mcp.\n */\nexport const CASCIVO_HOST = 'https://cascivo.com'\n\n/** All first-party themes shipped by @cascivo/themes (selectable via data-theme). */\nexport const THEMES = [\n 'light',\n 'dark',\n 'warm',\n 'flat',\n 'minimal',\n 'midnight',\n 'pastel',\n 'brutalist',\n 'corporate',\n 'terminal',\n 'cyberpunk',\n 'arcade',\n] as const\n\nexport type ThemeName = (typeof THEMES)[number]\n\nexport type RegistryNamespaceConfig =\n | string\n | { url: string; headers?: Record<string, string>; params?: Record<string, string> }\n\nexport interface CascadeConfig {\n /** URL of the registry.json index. */\n registry: string\n /** Directory (relative to project root) where components are written. */\n outputDir: string\n /** Default theme imported by `cascade init`. */\n theme: ThemeName\n /** Namespace → registry URL template (with {name} placeholder) or auth config. */\n registries?: Record<string, RegistryNamespaceConfig>\n /** Whether to copy test files (*.contract.test.tsx) when adding components. */\n tests?: boolean\n}\n\nexport const DEFAULT_CONFIG: CascadeConfig = {\n // Canonical hosted registry index (served from the landing site, documented in\n // llms.txt). Prefer this over a branch's GitHub raw URL, which 404s for\n // unauthenticated/private-repo requests and breaks `cascivo list`/`add`.\n registry: `${CASCIVO_HOST}/registry.json`,\n outputDir: 'src/components/ui',\n theme: 'light',\n}\n\nconst CONFIG_FILES = ['cascivo.config.ts', 'cascivo.config.js', 'cascivo.config.mjs']\n\n/** Apply defaults over a (possibly partial) user config object. */\nexport function resolveConfig(partial: Partial<CascadeConfig> | null | undefined): CascadeConfig {\n return { ...DEFAULT_CONFIG, ...partial }\n}\n\n/** Let env vars override config — used by the MCP server to pass `outputDir`. */\nexport function applyEnvOverrides(\n config: CascadeConfig,\n env: NodeJS.ProcessEnv = process.env,\n): CascadeConfig {\n return {\n ...config,\n ...(env.CASCIVO_REGISTRY ? { registry: env.CASCIVO_REGISTRY } : {}),\n ...(env.CASCIVO_OUTPUT_DIR ? { outputDir: env.CASCIVO_OUTPUT_DIR } : {}),\n }\n}\n\n/**\n * Locate and load `cascivo.config.{ts,js,mjs}` from `cwd`. Falls back to the\n * default config when no file is found or the file cannot be loaded. Env vars\n * (`CASCIVO_REGISTRY`, `CASCIVO_OUTPUT_DIR`) take precedence.\n */\nexport async function loadConfig(cwd: string = process.cwd()): Promise<CascadeConfig> {\n for (const file of CONFIG_FILES) {\n const path = join(cwd, file)\n if (!existsSync(path)) continue\n try {\n const mod = (await import(pathToFileURL(path).href)) as {\n default?: Partial<CascadeConfig>\n }\n return applyEnvOverrides(resolveConfig(mod.default ?? (mod as Partial<CascadeConfig>)))\n } catch {\n // Unloadable config (e.g. unsupported TS syntax) — fall back to defaults.\n return applyEnvOverrides(resolveConfig(null))\n }\n }\n return applyEnvOverrides(resolveConfig(null))\n}\n\nexport type PackageManager = 'pnpm' | 'yarn' | 'npm' | 'bun'\n\n/** Detect the package manager in use from lock files, defaulting to npm. */\nexport function detectPackageManager(cwd: string = process.cwd()): PackageManager {\n if (existsSync(join(cwd, 'pnpm-lock.yaml'))) return 'pnpm'\n if (existsSync(join(cwd, 'yarn.lock'))) return 'yarn'\n if (existsSync(join(cwd, 'bun.lockb'))) return 'bun'\n return 'npm'\n}\n\n/** The install subcommand each package manager uses to add dependencies. */\nexport function installCommand(pm: PackageManager, packages: string[]): [string, string[]] {\n const verb = pm === 'npm' ? 'install' : 'add'\n return [pm, [verb, ...packages]]\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AASA,MAAa,eAAe;;AAG5B,MAAa,SAAS;CACpB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAqBA,MAAa,iBAAgC;CAI3C,UAAU,GAAG,aAAa;CAC1B,WAAW;CACX,OAAO;AACT;AAEA,MAAM,eAAe;CAAC;CAAqB;CAAqB;AAAoB;;AAGpF,SAAgB,cAAc,SAAmE;CAC/F,OAAO;EAAE,GAAG;EAAgB,GAAG;CAAQ;AACzC;;AAGA,SAAgB,kBACd,QACA,MAAyB,QAAQ,KAClB;CACf,OAAO;EACL,GAAG;EACH,GAAI,IAAI,mBAAmB,EAAE,UAAU,IAAI,iBAAiB,IAAI,CAAC;EACjE,GAAI,IAAI,qBAAqB,EAAE,WAAW,IAAI,mBAAmB,IAAI,CAAC;CACxE;AACF;;;;;;AAOA,eAAsB,WAAW,MAAc,QAAQ,IAAI,GAA2B;CACpF,KAAK,MAAM,QAAQ,cAAc;EAC/B,MAAM,OAAO,KAAK,KAAK,IAAI;EAC3B,IAAI,CAAC,WAAW,IAAI,GAAG;EACvB,IAAI;GACF,MAAM,MAAO,MAAM,OAAO,cAAc,IAAI,CAAC,CAAC;GAG9C,OAAO,kBAAkB,cAAc,IAAI,WAAY,GAA8B,CAAC;EACxF,QAAQ;GAEN,OAAO,kBAAkB,cAAc,IAAI,CAAC;EAC9C;CACF;CACA,OAAO,kBAAkB,cAAc,IAAI,CAAC;AAC9C;;AAKA,SAAgB,qBAAqB,MAAc,QAAQ,IAAI,GAAmB;CAChF,IAAI,WAAW,KAAK,KAAK,gBAAgB,CAAC,GAAG,OAAO;CACpD,IAAI,WAAW,KAAK,KAAK,WAAW,CAAC,GAAG,OAAO;CAC/C,IAAI,WAAW,KAAK,KAAK,WAAW,CAAC,GAAG,OAAO;CAC/C,OAAO;AACT;;AAGA,SAAgB,eAAe,IAAoB,UAAwC;CAEzF,OAAO,CAAC,IAAI,CADC,OAAO,QAAQ,YAAY,OACrB,GAAG,QAAQ,CAAC;AACjC"}
@@ -0,0 +1,56 @@
1
+ import { t as readFileSafe } from "./fs-m7ZvuBBm.mjs";
2
+ import { i as sha256, l as findComponent, r as readLock, s as fetchRegistry, t as checkPeerVersions } from "./peer-versions-B2bCgko-.mjs";
3
+ //#region src/commands/drift.ts
4
+ /**
5
+ * `cascivo doctor --drift` — compares installed components against the
6
+ * registry. Two drift classes:
7
+ *
8
+ * 1. Local-edit drift: an installed file's content no longer matches what
9
+ * was copied at install time (hand edits, or deleted after install).
10
+ * 2. Peer-version drift: the currently-registered component source needs a
11
+ * newer `@cascivo/*` peer package (per `peerVersions`) than what's
12
+ * actually installed in node_modules — the dashboard-feedback failure
13
+ * mode (DataTable referencing an i18n builtin key an older published
14
+ * @cascivo/i18n build doesn't have).
15
+ */
16
+ async function runDoctorDrift(config, cwd = process.cwd()) {
17
+ const lock = await readLock(cwd);
18
+ if (!lock || Object.keys(lock.items).length === 0) {
19
+ console.log("No installed components found in cascivo.lock.");
20
+ return;
21
+ }
22
+ const registry = await fetchRegistry(config.registry);
23
+ let driftCount = 0;
24
+ for (const [name, entry] of Object.entries(lock.items)) {
25
+ const current = findComponent(registry, name);
26
+ if (!current) continue;
27
+ for (const [path, lockedHash] of Object.entries(entry.files)) {
28
+ const content = await readFileSafe(path);
29
+ if (content === null) {
30
+ console.log(`${name}: ${path} is missing (installed, then deleted)`);
31
+ driftCount++;
32
+ continue;
33
+ }
34
+ if (sha256(content) !== lockedHash) {
35
+ console.log(`${name}: ${path} has local edits (differs from the version installed)`);
36
+ driftCount++;
37
+ }
38
+ }
39
+ if (current.peerVersions) {
40
+ const violations = await checkPeerVersions(cwd, current.peerVersions);
41
+ for (const v of violations) {
42
+ const installedDesc = v.installed ? `${v.installed} is installed` : "it is not installed";
43
+ console.log(`${name}: needs ${v.pkg} ${v.required}, but ${installedDesc}.`);
44
+ driftCount++;
45
+ }
46
+ }
47
+ }
48
+ if (driftCount > 0) {
49
+ console.log(`\n${driftCount} drift issue(s) found.`);
50
+ process.exitCode = 1;
51
+ } else console.log("No drift detected — installed components match the registry.");
52
+ }
53
+ //#endregion
54
+ export { runDoctorDrift };
55
+
56
+ //# sourceMappingURL=drift-Ciw5qeEt.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"drift-Ciw5qeEt.mjs","names":[],"sources":["../src/commands/drift.ts"],"sourcesContent":["import type { CascadeConfig } from '../utils/config.js'\nimport { readFileSafe } from '../utils/fs.js'\nimport { readLock, sha256 } from '../utils/lock.js'\nimport { checkPeerVersions } from '../utils/peer-versions.js'\nimport { fetchRegistry, findComponent } from '../utils/registry.js'\n\n/**\n * `cascivo doctor --drift` — compares installed components against the\n * registry. Two drift classes:\n *\n * 1. Local-edit drift: an installed file's content no longer matches what\n * was copied at install time (hand edits, or deleted after install).\n * 2. Peer-version drift: the currently-registered component source needs a\n * newer `@cascivo/*` peer package (per `peerVersions`) than what's\n * actually installed in node_modules — the dashboard-feedback failure\n * mode (DataTable referencing an i18n builtin key an older published\n * @cascivo/i18n build doesn't have).\n */\nexport async function runDoctorDrift(\n config: CascadeConfig,\n cwd: string = process.cwd(),\n): Promise<void> {\n const lock = await readLock(cwd)\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 driftCount = 0\n\n for (const [name, entry] of Object.entries(lock.items)) {\n const current = findComponent(registry, name)\n if (!current) continue\n\n for (const [path, lockedHash] of Object.entries(entry.files)) {\n const content = await readFileSafe(path)\n if (content === null) {\n console.log(`${name}: ${path} is missing (installed, then deleted)`)\n driftCount++\n continue\n }\n if (sha256(content) !== lockedHash) {\n console.log(`${name}: ${path} has local edits (differs from the version installed)`)\n driftCount++\n }\n }\n\n if (current.peerVersions) {\n const violations = await checkPeerVersions(cwd, current.peerVersions)\n for (const v of violations) {\n const installedDesc = v.installed ? `${v.installed} is installed` : 'it is not installed'\n console.log(`${name}: needs ${v.pkg} ${v.required}, but ${installedDesc}.`)\n driftCount++\n }\n }\n }\n\n if (driftCount > 0) {\n console.log(`\\n${driftCount} drift issue(s) found.`)\n process.exitCode = 1\n } else {\n console.log('No drift detected — installed components match the registry.')\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAkBA,eAAsB,eACpB,QACA,MAAc,QAAQ,IAAI,GACX;CACf,MAAM,OAAO,MAAM,SAAS,GAAG;CAC/B,IAAI,CAAC,QAAQ,OAAO,KAAK,KAAK,KAAK,CAAC,CAAC,WAAW,GAAG;EACjD,QAAQ,IAAI,gDAAgD;EAC5D;CACF;CAEA,MAAM,WAAW,MAAM,cAAc,OAAO,QAAQ;CACpD,IAAI,aAAa;CAEjB,KAAK,MAAM,CAAC,MAAM,UAAU,OAAO,QAAQ,KAAK,KAAK,GAAG;EACtD,MAAM,UAAU,cAAc,UAAU,IAAI;EAC5C,IAAI,CAAC,SAAS;EAEd,KAAK,MAAM,CAAC,MAAM,eAAe,OAAO,QAAQ,MAAM,KAAK,GAAG;GAC5D,MAAM,UAAU,MAAM,aAAa,IAAI;GACvC,IAAI,YAAY,MAAM;IACpB,QAAQ,IAAI,GAAG,KAAK,IAAI,KAAK,sCAAsC;IACnE;IACA;GACF;GACA,IAAI,OAAO,OAAO,MAAM,YAAY;IAClC,QAAQ,IAAI,GAAG,KAAK,IAAI,KAAK,sDAAsD;IACnF;GACF;EACF;EAEA,IAAI,QAAQ,cAAc;GACxB,MAAM,aAAa,MAAM,kBAAkB,KAAK,QAAQ,YAAY;GACpE,KAAK,MAAM,KAAK,YAAY;IAC1B,MAAM,gBAAgB,EAAE,YAAY,GAAG,EAAE,UAAU,iBAAiB;IACpE,QAAQ,IAAI,GAAG,KAAK,UAAU,EAAE,IAAI,GAAG,EAAE,SAAS,QAAQ,cAAc,EAAE;IAC1E;GACF;EACF;CACF;CAEA,IAAI,aAAa,GAAG;EAClB,QAAQ,IAAI,KAAK,WAAW,uBAAuB;EACnD,QAAQ,WAAW;CACrB,OACE,QAAQ,IAAI,8DAA8D;AAE9E"}
@@ -1,4 +1,4 @@
1
- import { t as fetchJson } from "./http-CLkdTpxD.mjs";
1
+ import { t as fetchJson } from "./http-CJZ5W0Fa.mjs";
2
2
  import { fileURLToPath } from "node:url";
3
3
  import { existsSync, readFileSync } from "node:fs";
4
4
  import { dirname, join } from "node:path";
@@ -48,7 +48,7 @@ function loadRegistry(config) {
48
48
  return fetchJson(config.registry);
49
49
  }
50
50
  function loadCatalog(config) {
51
- const local = findUp(HERE, join("apps", "docs", "public", "tokens.catalog.json")) ?? findUp(process.cwd(), join("apps", "docs", "public", "tokens.catalog.json"));
51
+ const local = findUp(HERE, join("apps", "site", "public", "tokens.catalog.json")) ?? findUp(process.cwd(), join("apps", "site", "public", "tokens.catalog.json"));
52
52
  if (local) return JSON.parse(readFileSync(local, "utf8"));
53
53
  return fetchJson(config.registry.replace(/registry\.json$/, "tokens.catalog.json"));
54
54
  }
@@ -113,4 +113,4 @@ async function eject(args, config, options = {}) {
113
113
  //#endregion
114
114
  export { eject };
115
115
 
116
- //# sourceMappingURL=eject-D_mC1lsq.mjs.map
116
+ //# sourceMappingURL=eject-Br8V7I3m.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"eject-D_mC1lsq.mjs","names":[],"sources":["../src/commands/eject.ts"],"sourcesContent":["import { existsSync, readFileSync } from 'node:fs'\nimport { mkdir, writeFile } from 'node:fs/promises'\nimport { dirname, join } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport type { CascadeConfig } from '../utils/config.js'\nimport { fetchJson } from '../utils/http.js'\n\nconst HERE = dirname(fileURLToPath(import.meta.url))\n\nexport interface EjectToken {\n name: string\n /** Resolved starting value (light theme), or null when unknown. */\n value: string | null\n}\n\ninterface RegistryComponentMeta {\n name: string\n tokens?: string[]\n}\ninterface RegistryEntry {\n name: string\n type?: string\n meta?: RegistryComponentMeta\n}\ninterface RegistryFile {\n components: RegistryEntry[]\n}\ninterface CatalogEntry {\n name: string\n value?: string\n resolvedDefault?: string | null\n}\ninterface CatalogFile {\n tokens: CatalogEntry[]\n}\n\n/**\n * Build a scoped, locally-owned token-override stylesheet. The component itself\n * stays imported from `@cascivo/react`; only the listed token values are\n * ejected so they can be tuned without copying the whole component in.\n *\n * The block is intentionally *unlayered*: unlayered declarations win over the\n * themed `@layer cascivo.theme` values, so the override always takes effect.\n */\nexport function buildOverrideCss(opts: {\n component: string\n scope: string\n tokens: EjectToken[]\n}): string {\n const { component, scope, tokens } = opts\n const lines: string[] = []\n lines.push(`/* cascivo eject — ${component}`)\n lines.push(' *')\n lines.push(` * Locally-owned token overrides. ${component} is still imported from`)\n lines.push(' * @cascivo/react — only these token values are ejected so you can tune them')\n lines.push(' * without copying the whole component into your repo.')\n lines.push(' *')\n lines.push(' * Unlayered, so these win over the themed layer values. Apply the scope by')\n lines.push(` * adding the selector to the subtree you want to affect, e.g.`)\n lines.push(` * <div data-cascivo-eject=\"${component}\">…</div>`)\n lines.push(' */')\n lines.push(`${scope} {`)\n for (const t of tokens) {\n if (t.value === null) {\n lines.push(` /* ${t.name}: set a value — resolves per theme by default */`)\n } else {\n lines.push(` ${t.name}: ${t.value};`)\n }\n }\n lines.push('}')\n return lines.join('\\n') + '\\n'\n}\n\n/** Walk up from a start dir looking for a file/dir match. */\nfunction findUp(startDir: string, rel: string): string | null {\n let dir = startDir\n for (let i = 0; i < 10; i++) {\n const candidate = join(dir, rel)\n if (existsSync(candidate)) return candidate\n dir = join(dir, '..')\n }\n return null\n}\n\nfunction loadRegistry(config: CascadeConfig): Promise<RegistryFile> | RegistryFile {\n const local = findUp(HERE, 'registry.json') ?? findUp(process.cwd(), 'registry.json')\n if (local) return JSON.parse(readFileSync(local, 'utf8')) as RegistryFile\n return fetchJson(config.registry) as Promise<RegistryFile>\n}\n\nfunction loadCatalog(config: CascadeConfig): Promise<CatalogFile> | CatalogFile {\n const local =\n findUp(HERE, join('apps', 'docs', 'public', 'tokens.catalog.json')) ??\n findUp(process.cwd(), join('apps', 'docs', 'public', 'tokens.catalog.json'))\n if (local) return JSON.parse(readFileSync(local, 'utf8')) as CatalogFile\n const catalogUrl = config.registry.replace(/registry\\.json$/, 'tokens.catalog.json')\n return fetchJson(catalogUrl) as Promise<CatalogFile>\n}\n\ninterface EjectOptions {\n tokens?: string[]\n scope?: string\n out?: string\n dryRun?: boolean\n}\n\n/**\n * `cascivo eject <component> [--tokens a,b] [--scope sel] [--out file]`\n *\n * Ejects a targeted slice of a component — specific design tokens — into a\n * scoped local override file, instead of copying the whole component.\n */\nexport async function eject(\n args: string[],\n config: CascadeConfig,\n options: EjectOptions = {},\n): Promise<void> {\n const component = args.find((a) => !a.startsWith('--'))\n if (!component) {\n console.error(\n 'Usage: cascivo eject <component> [--tokens a,b] [--scope <selector>] [--out <file>]',\n )\n process.exitCode = 1\n return\n }\n\n const registry = await loadRegistry(config)\n const entry = registry.components.find((c) => c.name === component)\n if (!entry) {\n console.error(`Component \"${component}\" not found in the registry.`)\n process.exitCode = 1\n return\n }\n\n const available = entry.meta?.tokens ?? []\n if (available.length === 0) {\n console.error(`Component \"${component}\" declares no tokens to eject.`)\n process.exitCode = 1\n return\n }\n\n let selected = available\n if (options.tokens && options.tokens.length > 0) {\n const unknown = options.tokens.filter((t) => !available.includes(t))\n if (unknown.length > 0) {\n console.error(\n `These tokens are not used by \"${component}\": ${unknown.join(', ')}\\n` +\n `Available: ${available.join(', ')}`,\n )\n process.exitCode = 1\n return\n }\n selected = options.tokens\n }\n\n const catalog = await loadCatalog(config)\n const valueOf = new Map(\n catalog.tokens.map((t) => [t.name, t.resolvedDefault ?? t.value ?? null] as const),\n )\n const tokens: EjectToken[] = selected.map((name) => ({ name, value: valueOf.get(name) ?? null }))\n\n const scope = options.scope ?? `[data-cascivo-eject='${component}']`\n const css = buildOverrideCss({ component, scope, tokens })\n\n if (options.dryRun) {\n console.log(css)\n return\n }\n\n const out = options.out ?? join('src', 'styles', `cascivo-${component}.overrides.css`)\n await mkdir(dirname(out), { recursive: true })\n await writeFile(out, css)\n console.log(`Ejected ${tokens.length} token(s) for \"${component}\" → ${out}`)\n console.log(`Import it after your theme CSS, then add the scope:`)\n console.log(` import './${out.replace(/\\\\/g, '/')}'`)\n console.log(` <div data-cascivo-eject=\"${component}\">…</div>`)\n}\n"],"mappings":";;;;;;AAOA,MAAM,OAAO,QAAQ,cAAc,OAAO,KAAK,GAAG,CAAC;;;;;;;;;AAqCnD,SAAgB,iBAAiB,MAItB;CACT,MAAM,EAAE,WAAW,OAAO,WAAW;CACrC,MAAM,QAAkB,CAAC;CACzB,MAAM,KAAK,sBAAsB,WAAW;CAC5C,MAAM,KAAK,IAAI;CACf,MAAM,KAAK,qCAAqC,UAAU,wBAAwB;CAClF,MAAM,KAAK,8EAA8E;CACzF,MAAM,KAAK,wDAAwD;CACnE,MAAM,KAAK,IAAI;CACf,MAAM,KAAK,6EAA6E;CACxF,MAAM,KAAK,gEAAgE;CAC3E,MAAM,KAAK,iCAAiC,UAAU,UAAU;CAChE,MAAM,KAAK,KAAK;CAChB,MAAM,KAAK,GAAG,MAAM,GAAG;CACvB,KAAK,MAAM,KAAK,QACd,IAAI,EAAE,UAAU,MACd,MAAM,KAAK,QAAQ,EAAE,KAAK,iDAAiD;MAE3E,MAAM,KAAK,KAAK,EAAE,KAAK,IAAI,EAAE,MAAM,EAAE;CAGzC,MAAM,KAAK,GAAG;CACd,OAAO,MAAM,KAAK,IAAI,IAAI;AAC5B;;AAGA,SAAS,OAAO,UAAkB,KAA4B;CAC5D,IAAI,MAAM;CACV,KAAK,IAAI,IAAI,GAAG,IAAI,IAAI,KAAK;EAC3B,MAAM,YAAY,KAAK,KAAK,GAAG;EAC/B,IAAI,WAAW,SAAS,GAAG,OAAO;EAClC,MAA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AAQ,MACN,iCAAiC,UAAU,KAAK,QAAQ,KAAK,IAAI,EAAE,eACnD,UAAU,KAAK,IAAI,GACrC;GACA,QAAQ,WAAW;GACnB;EACF;EACA,WAAW,QAAQ;CACrB;CAEA,MAAM,UAAU,MAAM,YAAY,MAAM;CACxC,MAAM,UAAU,IAAI,IAClB,QAAQ,OAAO,KAAK,MAAM,CAAC,EAAE,MAAM,EAAE,mBAAmB,EAAE,SAAS,IAAI,CAAU,CACnF;CACA,MAAM,SAAuB,SAAS,KAAK,UAAU;EAAE;EAAM,OAAO,QAAQ,IAAI,IAAI,KAAK;CAAK,EAAE;CAGhG,MAAM,MAAM,iBAAiB;EAAE;EAAW,OAD5B,QAAQ,SAAS,wBAAwB,UAAU;EAChB;CAAO,CAAC;CAEzD,IAAI,QAAQ,QAAQ;EAClB,QAAQ,IAAI,GAAG;EACf;CACF;CAEA,MAAM,MAAM,QAAQ,OAAO,KAAK,OAAO,UAAU,WAAW,UAAU,eAAe;CACrF,MAAM,MAAM,QAAQ,GAAG,GAAG,EAAE,WAAW,KAAK,CAAC;CAC7C,MAAM,UAAU,KAAK,GAAG;CACxB,QAAQ,IAAI,WAAW,OAAO,OAAO,iBAAiB,UAAU,MAAM,KAAK;CAC3E,QAAQ,IAAI,qDAAqD;CACjE,QAAQ,IAAI,eAAe,IAAI,QAAQ,OAAO,GAAG,EAAE,EAAE;CACrD,QAAQ,IAAI,8BAA8B,UAAU,UAAU;AAChE"}
1
+ {"version":3,"file":"eject-Br8V7I3m.mjs","names":[],"sources":["../src/commands/eject.ts"],"sourcesContent":["import { existsSync, readFileSync } from 'node:fs'\nimport { mkdir, writeFile } from 'node:fs/promises'\nimport { dirname, join } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport type { CascadeConfig } from '../utils/config.js'\nimport { fetchJson } from '../utils/http.js'\n\nconst HERE = dirname(fileURLToPath(import.meta.url))\n\nexport interface EjectToken {\n name: string\n /** Resolved starting value (light theme), or null when unknown. */\n value: string | null\n}\n\ninterface RegistryComponentMeta {\n name: string\n tokens?: string[]\n}\ninterface RegistryEntry {\n name: string\n type?: string\n meta?: RegistryComponentMeta\n}\ninterface RegistryFile {\n components: RegistryEntry[]\n}\ninterface CatalogEntry {\n name: string\n value?: string\n resolvedDefault?: string | null\n}\ninterface CatalogFile {\n tokens: CatalogEntry[]\n}\n\n/**\n * Build a scoped, locally-owned token-override stylesheet. The component itself\n * stays imported from `@cascivo/react`; only the listed token values are\n * ejected so they can be tuned without copying the whole component in.\n *\n * The block is intentionally *unlayered*: unlayered declarations win over the\n * themed `@layer cascivo.theme` values, so the override always takes effect.\n */\nexport function buildOverrideCss(opts: {\n component: string\n scope: string\n tokens: EjectToken[]\n}): string {\n const { component, scope, tokens } = opts\n const lines: string[] = []\n lines.push(`/* cascivo eject — ${component}`)\n lines.push(' *')\n lines.push(` * Locally-owned token overrides. ${component} is still imported from`)\n lines.push(' * @cascivo/react — only these token values are ejected so you can tune them')\n lines.push(' * without copying the whole component into your repo.')\n lines.push(' *')\n lines.push(' * Unlayered, so these win over the themed layer values. Apply the scope by')\n lines.push(` * adding the selector to the subtree you want to affect, e.g.`)\n lines.push(` * <div data-cascivo-eject=\"${component}\">…</div>`)\n lines.push(' */')\n lines.push(`${scope} {`)\n for (const t of tokens) {\n if (t.value === null) {\n lines.push(` /* ${t.name}: set a value — resolves per theme by default */`)\n } else {\n lines.push(` ${t.name}: ${t.value};`)\n }\n }\n lines.push('}')\n return lines.join('\\n') + '\\n'\n}\n\n/** Walk up from a start dir looking for a file/dir match. */\nfunction findUp(startDir: string, rel: string): string | null {\n let dir = startDir\n for (let i = 0; i < 10; i++) {\n const candidate = join(dir, rel)\n if (existsSync(candidate)) return candidate\n dir = join(dir, '..')\n }\n return null\n}\n\nfunction loadRegistry(config: CascadeConfig): Promise<RegistryFile> | RegistryFile {\n const local = findUp(HERE, 'registry.json') ?? findUp(process.cwd(), 'registry.json')\n if (local) return JSON.parse(readFileSync(local, 'utf8')) as RegistryFile\n return fetchJson(config.registry) as Promise<RegistryFile>\n}\n\nfunction loadCatalog(config: CascadeConfig): Promise<CatalogFile> | CatalogFile {\n const local =\n findUp(HERE, join('apps', 'site', 'public', 'tokens.catalog.json')) ??\n findUp(process.cwd(), join('apps', 'site', 'public', 'tokens.catalog.json'))\n if (local) return JSON.parse(readFileSync(local, 'utf8')) as CatalogFile\n const catalogUrl = config.registry.replace(/registry\\.json$/, 'tokens.catalog.json')\n return fetchJson(catalogUrl) as Promise<CatalogFile>\n}\n\ninterface EjectOptions {\n tokens?: string[]\n scope?: string\n out?: string\n dryRun?: boolean\n}\n\n/**\n * `cascivo eject <component> [--tokens a,b] [--scope sel] [--out file]`\n *\n * Ejects a targeted slice of a component — specific design tokens — into a\n * scoped local override file, instead of copying the whole component.\n */\nexport async function eject(\n args: string[],\n config: CascadeConfig,\n options: EjectOptions = {},\n): Promise<void> {\n const component = args.find((a) => !a.startsWith('--'))\n if (!component) {\n console.error(\n 'Usage: cascivo eject <component> [--tokens a,b] [--scope <selector>] [--out <file>]',\n )\n process.exitCode = 1\n return\n }\n\n const registry = await loadRegistry(config)\n const entry = registry.components.find((c) => c.name === component)\n if (!entry) {\n console.error(`Component \"${component}\" not found in the registry.`)\n process.exitCode = 1\n return\n }\n\n const available = entry.meta?.tokens ?? []\n if (available.length === 0) {\n console.error(`Component \"${component}\" declares no tokens to eject.`)\n process.exitCode = 1\n return\n }\n\n let selected = available\n if (options.tokens && options.tokens.length > 0) {\n const unknown = options.tokens.filter((t) => !available.includes(t))\n if (unknown.length > 0) {\n console.error(\n `These tokens are not used by \"${component}\": ${unknown.join(', ')}\\n` +\n `Available: ${available.join(', ')}`,\n )\n process.exitCode = 1\n return\n }\n selected = options.tokens\n }\n\n const catalog = await loadCatalog(config)\n const valueOf = new Map(\n catalog.tokens.map((t) => [t.name, t.resolvedDefault ?? t.value ?? null] as const),\n )\n const tokens: EjectToken[] = selected.map((name) => ({ name, value: valueOf.get(name) ?? null }))\n\n const scope = options.scope ?? `[data-cascivo-eject='${component}']`\n const css = buildOverrideCss({ component, scope, tokens })\n\n if (options.dryRun) {\n console.log(css)\n return\n }\n\n const out = options.out ?? join('src', 'styles', `cascivo-${component}.overrides.css`)\n await mkdir(dirname(out), { recursive: true })\n await writeFile(out, css)\n console.log(`Ejected ${tokens.length} token(s) for \"${component}\" → ${out}`)\n console.log(`Import it after your theme CSS, then add the scope:`)\n console.log(` import './${out.replace(/\\\\/g, '/')}'`)\n console.log(` <div data-cascivo-eject=\"${component}\">…</div>`)\n}\n"],"mappings":";;;;;;AAOA,MAAM,OAAO,QAAQ,cAAc,OAAO,KAAK,GAAG,CAAC;;;;;;;;;AAqCnD,SAAgB,iBAAiB,MAItB;CACT,MAAM,EAAE,WAAW,OAAO,WAAW;CACrC,MAAM,QAAkB,CAAC;CACzB,MAAM,KAAK,sBAAsB,WAAW;CAC5C,MAAM,KAAK,IAAI;CACf,MAAM,KAAK,qCAAqC,UAAU,wBAAwB;CAClF,MAAM,KAAK,8EAA8E;CACzF,MAAM,KAAK,wDAAwD;CACnE,MAAM,KAAK,IAAI;CACf,MAAM,KAAK,6EAA6E;CACxF,MAAM,KAAK,gEAAgE;CAC3E,MAAM,KAAK,iCAAiC,UAAU,UAAU;CAChE,MAAM,KAAK,KAAK;CAChB,MAAM,KAAK,GAAG,MAAM,GAAG;CACvB,KAAK,MAAM,KAAK,QACd,IAAI,EAAE,UAAU,MACd,MAAM,KAAK,QAAQ,EAAE,KAAK,iDAAiD;MAE3E,MAAM,KAAK,KAAK,EAAE,KAAK,IAAI,EAAE,MAAM,EAAE;CAGzC,MAAM,KAAK,GAAG;CACd,OAAO,MAAM,KAAK,IAAI,IAAI;AAC5B;;AAGA,SAAS,OAAO,UAAkB,KAA4B;CAC5D,IAAI,MAAM;CACV,KAAK,IAAI,IAAI,GAAG,IAAI,IAAI,KAAK;EAC3B,MAAM,YAAY,KAAK,KAAK,GAAG;EAC/B,IAAI,WAAW,SAAS,GAAG,OAAO;EAClC,MAAM,KAA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MACN,iCAAiC,UAAU,KAAK,QAAQ,KAAK,IAAI,EAAE,eACnD,UAAU,KAAK,IAAI,GACrC;GACA,QAAQ,WAAW;GACnB;EACF;EACA,WAAW,QAAQ;CACrB;CAEA,MAAM,UAAU,MAAM,YAAY,MAAM;CACxC,MAAM,UAAU,IAAI,IAClB,QAAQ,OAAO,KAAK,MAAM,CAAC,EAAE,MAAM,EAAE,mBAAmB,EAAE,SAAS,IAAI,CAAU,CACnF;CACA,MAAM,SAAuB,SAAS,KAAK,UAAU;EAAE;EAAM,OAAO,QAAQ,IAAI,IAAI,KAAK;CAAK,EAAE;CAGhG,MAAM,MAAM,iBAAiB;EAAE;EAAW,OAD5B,QAAQ,SAAS,wBAAwB,UAAU;EAChB;CAAO,CAAC;CAEzD,IAAI,QAAQ,QAAQ;EAClB,QAAQ,IAAI,GAAG;EACf;CACF;CAEA,MAAM,MAAM,QAAQ,OAAO,KAAK,OAAO,UAAU,WAAW,UAAU,eAAe;CACrF,MAAM,MAAM,QAAQ,GAAG,GAAG,EAAE,WAAW,KAAK,CAAC;CAC7C,MAAM,UAAU,KAAK,GAAG;CACxB,QAAQ,IAAI,WAAW,OAAO,OAAO,iBAAiB,UAAU,MAAM,KAAK;CAC3E,QAAQ,IAAI,qDAAqD;CACjE,QAAQ,IAAI,eAAe,IAAI,QAAQ,OAAO,GAAG,EAAE,EAAE;CACrD,QAAQ,IAAI,8BAA8B,UAAU,UAAU;AAChE"}
@@ -0,0 +1,24 @@
1
+ import { dirname, join, resolve } from "node:path";
2
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
3
+ //#region src/utils/fs.ts
4
+ /** Resolve where a component file should be written. */
5
+ function resolveOutputPath(outputDir, component, file, cwd = process.cwd()) {
6
+ return join(resolve(cwd, outputDir), component, file);
7
+ }
8
+ /** Write a file, creating parent directories as needed. */
9
+ async function writeFileSafe(path, content) {
10
+ await mkdir(dirname(path), { recursive: true });
11
+ await writeFile(path, content, "utf8");
12
+ }
13
+ /** Read a file, returning null if it does not exist. */
14
+ async function readFileSafe(path) {
15
+ try {
16
+ return await readFile(path, "utf8");
17
+ } catch {
18
+ return null;
19
+ }
20
+ }
21
+ //#endregion
22
+ export { resolveOutputPath as n, writeFileSafe as r, readFileSafe as t };
23
+
24
+ //# sourceMappingURL=fs-m7ZvuBBm.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fs-m7ZvuBBm.mjs","names":[],"sources":["../src/utils/fs.ts"],"sourcesContent":["import { mkdir, readFile, writeFile } from 'node:fs/promises'\nimport { dirname, join, resolve } from 'node:path'\n\n/** Resolve where a component file should be written. */\nexport function resolveOutputPath(\n outputDir: string,\n component: string,\n file: string,\n cwd: string = process.cwd(),\n): string {\n return join(resolve(cwd, outputDir), component, file)\n}\n\n/** Write a file, creating parent directories as needed. */\nexport async function writeFileSafe(path: string, content: string): Promise<void> {\n await mkdir(dirname(path), { recursive: true })\n await writeFile(path, content, 'utf8')\n}\n\n/** Read a file, returning null if it does not exist. */\nexport async function readFileSafe(path: string): Promise<string | null> {\n try {\n return await readFile(path, 'utf8')\n } catch {\n return null\n }\n}\n"],"mappings":";;;;AAIA,SAAgB,kBACd,WACA,WACA,MACA,MAAc,QAAQ,IAAI,GAClB;CACR,OAAO,KAAK,QAAQ,KAAK,SAAS,GAAG,WAAW,IAAI;AACtD;;AAGA,eAAsB,cAAc,MAAc,SAAgC;CAChF,MAAM,MAAM,QAAQ,IAAI,GAAG,EAAE,WAAW,KAAK,CAAC;CAC9C,MAAM,UAAU,MAAM,SAAS,MAAM;AACvC;;AAGA,eAAsB,aAAa,MAAsC;CACvE,IAAI;EACF,OAAO,MAAM,SAAS,MAAM,MAAM;CACpC,QAAQ;EACN,OAAO;CACT;AACF"}