@bezel-labs/bezel-kit 0.1.0 → 0.3.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,"sources":["../src/index.ts","../src/collapse.ts","../src/name.ts","../src/resolve.ts","../src/serialize.ts","../src/emit.ts","../src/defaults.ts","../src/options.ts","../src/contexts.ts","../src/fonts.ts"],"sourcesContent":["/**\n * bezel — isomorphic entry.\n *\n * The pure transform core: convert an in-memory W3C Design Tokens (DTCG) object\n * into a scoped `variables.css` string. Imports no `node:*`, so it runs anywhere\n * — browser, edge, Node. For the filesystem/CLI conveniences (reading a tokens\n * file, writing outputs), import from `bezel/node`.\n */\nimport { emitCss } from \"./emit\"\nimport { resolveCssOptions, type CssOptions } from \"./options\"\nimport type { DtcgNode } from \"./types\"\n\nexport type { CssOptions, ResolvedCssOptions } from \"./options\"\nexport type { DtcgNode, FlatToken, TokenValue, ColorValue, DimensionValue } from \"./types\"\nexport { DEFAULT_CONTEXTS, DEFAULT_NAME_EXTENSION } from \"./defaults\"\nexport { emitCss } from \"./emit\"\nexport { resolveCssOptions } from \"./options\"\nexport { getContexts, formatContextsModule, DEFAULT_CONTEXT_NAME } from \"./contexts\"\nexport { getFonts, formatFontsModule } from \"./fonts\"\nexport type { FontDef } from \"./fonts\"\n\n/**\n * Convert a DTCG token object into a scoped `variables.css` string.\n *\n * Resolves each configured context (with `$root` fallback and reference\n * resolution) and emits one CSS scope per context — the base context in full,\n * others as override-only blocks. Pure: no filesystem access.\n *\n * @example\n * const css = tokensToCss(tokens)\n *\n * @example\n * const css = tokensToCss(tokens, { colorFormat: \"hex\", contexts: { $root: \":root\" } })\n */\nexport function tokensToCss(tokens: DtcgNode, options: CssOptions = {}): string {\n return emitCss(tokens, resolveCssOptions(options))\n}\n","import type { DtcgNode, FlatToken, TokenValue } from \"./types\"\n\n/** The W3C \"root token\" key — the base value of a group / logical token. */\nexport const ROOT_CONTEXT = \"$root\"\n\nfunction isObject(v: unknown): v is Record<string, unknown> {\n return typeof v === \"object\" && v !== null && !Array.isArray(v)\n}\n\n/** A \"context wrapper\" is a child object that directly holds a `$value` (e.g. `dark`, `light`, `$root`). */\nfunction isContextWrapper(v: unknown): v is DtcgNode {\n return isObject(v) && \"$value\" in v\n}\n\n/** Keys that are DTCG metadata, never traversed as child tokens/contexts. */\nfunction isMetaKey(key: string): boolean {\n return key === \"$type\" || key === \"$description\" || key === \"$extensions\" || key === \"$value\"\n}\n\n/**\n * Collapse a DTCG token tree to the single value that applies for `context`, and\n * flatten it to a map of dot-path → {@link FlatToken}.\n *\n * Handles three node shapes:\n * - **Simple token** — a node with a direct `$value` (context-invariant).\n * - **Logical token** — a node whose children include context wrappers (one of\n * which is `$root`). The value for `context` is picked, falling back to `$root`.\n * - **Group** — anything else; recursed into.\n *\n * `$type` is inherited from the nearest ancestor that declares one.\n */\nexport function flattenForContext(tokens: DtcgNode, context: string): Map<string, FlatToken> {\n const out = new Map<string, FlatToken>()\n\n const walk = (node: DtcgNode, path: string, inheritedType: string | undefined): void => {\n const type = typeof node.$type === \"string\" ? node.$type : inheritedType\n\n // Simple token: direct $value.\n if (\"$value\" in node) {\n out.set(path, {\n path,\n value: node.$value as TokenValue,\n type,\n extensions: node.$extensions,\n })\n return\n }\n\n // Logical token: has context-wrapper children (dark/light/$root).\n const wrapperKeys = Object.keys(node).filter((k) => !isMetaKey(k) && isContextWrapper(node[k]))\n if (wrapperKeys.length > 0) {\n const chosen =\n (node[context] as DtcgNode | undefined) ??\n (node[ROOT_CONTEXT] as DtcgNode | undefined) ??\n (node[wrapperKeys[0]!] as DtcgNode)\n out.set(path, {\n path,\n value: chosen.$value as TokenValue,\n type,\n extensions: node.$extensions,\n })\n return\n }\n\n // Group: recurse into non-meta children.\n for (const key of Object.keys(node)) {\n if (isMetaKey(key)) continue\n const child = node[key]\n if (isObject(child)) {\n walk(child as DtcgNode, path ? `${path}.${key}` : key, type)\n }\n }\n }\n\n walk(tokens, \"\", undefined)\n return out\n}\n","import type { FlatToken } from \"./types\"\n\n/** Leading path segments dropped when deriving a CSS name from a token path. */\nconst DROPPED_PREFIXES = new Set([\"base\", \"semantic\"])\n/** Trailing path segments dropped (a group's \"default\"/root token maps to the bare group name). */\nconst DROPPED_SUFFIXES = new Set([\"default\", \"$root\"])\n\nfunction exportNames(token: FlatToken, nameExtension: string): string[] | undefined {\n const ext = token.extensions?.[nameExtension]\n if (ext && typeof ext === \"object\" && \"exportName\" in ext) {\n const names = (ext as { exportName: unknown }).exportName\n if (Array.isArray(names)) return names.filter((n): n is string => typeof n === \"string\")\n }\n return undefined\n}\n\n/** True if any token in the map declares an `exportName` under `nameExtension`. */\nexport function usesExportNames(\n tokens: Iterable<FlatToken>,\n nameExtension: string,\n): boolean {\n for (const token of tokens) {\n if (exportNames(token, nameExtension) !== undefined) return true\n }\n return false\n}\n\n/** Derive a CSS variable name from a dot-path (fallback when no `exportName` exists). */\nexport function nameFromPath(path: string): string {\n const segments = path.split(\".\")\n while (segments.length > 1 && DROPPED_PREFIXES.has(segments[0]!)) segments.shift()\n while (segments.length > 1 && DROPPED_SUFFIXES.has(segments[segments.length - 1]!)) {\n segments.pop()\n }\n return segments.join(\"-\")\n}\n\n/**\n * Resolve the CSS variable name(s) a token emits (without the leading `--`).\n *\n * - In **exportName mode** (`useExportName`), names come solely from the token's\n * `exportName` array. A token without one — or with only empty strings — emits\n * nothing (it exists purely as a reference target). One token may emit many names.\n * - Otherwise (generic DTCG), the name is derived from the token's path.\n */\nexport function cssNames(\n token: FlatToken,\n nameExtension: string,\n useExportName: boolean,\n): string[] {\n if (useExportName) {\n const names = exportNames(token, nameExtension)\n if (!names) return []\n return names.filter((n) => n.length > 0)\n }\n return [nameFromPath(token.path)]\n}\n","import type { FlatToken, TokenValue } from \"./types\"\n\nconst REFERENCE_RE = /^\\{([^{}]+)\\}$/\n\n/** Returns the referenced path if `value` is a whole-value DTCG alias `\"{a.b.c}\"`, else `null`. */\nexport function aliasTarget(value: TokenValue): string | null {\n if (typeof value !== \"string\") return null\n const match = REFERENCE_RE.exec(value.trim())\n return match ? match[1]!.trim() : null\n}\n\n/**\n * Resolve whole-value references (`\"{a.b.c}\"`) in a flattened, single-context token\n * map, in place. Because the map was collapsed for one context, following an alias\n * yields that context's value (with `$root` fallback already applied during collapse).\n *\n * Multi-hop aliases are followed, results memoized, and cycles guarded against.\n */\nexport function resolveReferences(tokens: Map<string, FlatToken>): Map<string, FlatToken> {\n const resolved = new Map<string, TokenValue>()\n\n const resolveValue = (value: TokenValue, seen: Set<string>): TokenValue => {\n const target = aliasTarget(value)\n if (target === null) return value\n\n if (resolved.has(target)) return resolved.get(target)!\n if (seen.has(target)) {\n throw new Error(`bezel: circular token reference detected at \"{${target}}\".`)\n }\n\n const token = tokens.get(target)\n if (!token) {\n throw new Error(`bezel: unresolved token reference \"{${target}}\".`)\n }\n\n seen.add(target)\n const value2 = resolveValue(token.value, seen)\n seen.delete(target)\n resolved.set(target, value2)\n return value2\n }\n\n for (const token of tokens.values()) {\n token.value = resolveValue(token.value, new Set())\n }\n return tokens\n}\n","import type { ResolvedCssOptions } from \"./options\"\nimport type {\n ColorValue,\n DimensionValue,\n TokenValue,\n} from \"./types\"\n\nfunction isObject(v: unknown): v is Record<string, unknown> {\n return typeof v === \"object\" && v !== null && !Array.isArray(v)\n}\n\nfunction isColor(v: unknown): v is ColorValue {\n return isObject(v) && \"colorSpace\" in v && Array.isArray(v[\"components\"])\n}\n\nfunction isDimension(v: unknown): v is DimensionValue {\n return isObject(v) && typeof v[\"value\"] === \"number\" && \"unit\" in v\n}\n\n/** Round to at most `dp` decimals without trailing zeros. */\nfunction round(n: number, dp: number): number {\n const f = 10 ** dp\n return Math.round(n * f) / f\n}\n\nfunction serializeColor(color: ColorValue, format: ResolvedCssOptions[\"colorFormat\"]): string {\n if (format === \"hex\" && color.hex) return color.hex.toLowerCase()\n\n if (color.colorSpace === \"oklch\") {\n const [l = 0, c = 0, h = 0] = color.components\n const base = `oklch(${round(l, 4)} ${round(c, 4)} ${round(h, 3)})`\n if (color.alpha !== undefined && color.alpha < 1) {\n return `oklch(${round(l, 4)} ${round(c, 4)} ${round(h, 3)} / ${round(color.alpha, 4)})`\n }\n return base\n }\n\n // Unknown color space: prefer hex fallback, else CSS color() function.\n if (color.hex) return color.hex.toLowerCase()\n return `color(${color.colorSpace} ${color.components.map((n) => round(n, 4)).join(\" \")})`\n}\n\nfunction serializeDimension(dim: DimensionValue, unit: ResolvedCssOptions[\"dimensionUnit\"]): string {\n if (unit === \"rem\" && dim.unit === \"px\") {\n return `${round(dim.value / 16, 4)}rem`\n }\n return `${dim.value}${dim.unit}`\n}\n\n/** Quote a font-family name if it contains whitespace and isn't already quoted. */\nfunction quoteFamily(name: string): string {\n const trimmed = name.trim()\n if (/^['\"].*['\"]$/.test(trimmed)) return trimmed\n return /\\s/.test(trimmed) ? `\"${trimmed}\"` : trimmed\n}\n\n/** Serialize a resolved token value to a CSS declaration value. */\nexport function serializeValue(value: TokenValue, options: ResolvedCssOptions): string {\n if (isColor(value)) return serializeColor(value, options.colorFormat)\n if (isDimension(value)) return serializeDimension(value, options.dimensionUnit)\n\n // fontFamily as an array of names.\n if (Array.isArray(value)) {\n return value.map((v) => quoteFamily(String(v))).join(\", \")\n }\n\n if (typeof value === \"number\") return String(value)\n\n // Strings: could be a single font-family name or an already-formatted value.\n // Quote multi-word family names; leave comma-lists and plain values untouched.\n const str = String(value)\n if (/\\s/.test(str) && !str.includes(\",\") && !/[()]/.test(str)) {\n return quoteFamily(str)\n }\n return str\n}\n","import { flattenForContext } from \"./collapse\"\nimport { cssNames, usesExportNames } from \"./name\"\nimport { resolveReferences } from \"./resolve\"\nimport { serializeValue } from \"./serialize\"\nimport type { ResolvedCssOptions } from \"./options\"\nimport type { DtcgNode } from \"./types\"\n\n/** An ordered map of CSS variable name → serialized value for one context. */\ntype VarMap = Map<string, string>\n\n/** Build the `name → cssValue` map for a single context. */\nfunction buildContextVars(\n tokens: DtcgNode,\n context: string,\n useExportName: boolean,\n options: ResolvedCssOptions,\n): VarMap {\n const flat = resolveReferences(flattenForContext(tokens, context))\n const vars: VarMap = new Map()\n for (const token of flat.values()) {\n const names = cssNames(token, options.nameExtension, useExportName)\n if (names.length === 0) continue\n const value = serializeValue(token.value, options)\n for (const name of names) vars.set(name, value)\n }\n return vars\n}\n\nfunction renderBlock(selector: string, vars: Iterable<[string, string]>): string {\n const lines = [...vars].map(([name, value]) => ` --${name}: ${value};`)\n if (lines.length === 0) return \"\"\n return `${selector} {\\n${lines.join(\"\\n\")}\\n}`\n}\n\n/**\n * Convert a DTCG token tree into a scoped CSS string. The first context in\n * `options.contexts` is the base (emitted in full); every other context emits\n * only the variables whose value differs from the base.\n */\nexport function emitCss(tokens: DtcgNode, options: ResolvedCssOptions): string {\n const contextNames = Object.keys(options.contexts)\n const useExportName = usesExportNames(\n flattenForContext(tokens, contextNames[0]!).values(),\n options.nameExtension,\n )\n\n const [baseContext, ...overrideContexts] = contextNames\n const baseVars = buildContextVars(tokens, baseContext!, useExportName, options)\n\n const blocks: string[] = [renderBlock(options.contexts[baseContext!]!, baseVars)]\n\n for (const context of overrideContexts) {\n const vars = buildContextVars(tokens, context, useExportName, options)\n const overrides = [...vars].filter(([name, value]) => baseVars.get(name) !== value)\n const block = renderBlock(options.contexts[context]!, overrides)\n if (block) blocks.push(block)\n }\n\n const header =\n \"/* Generated by bezel — do not edit by hand. */\\n\" +\n \"/* Run `npm run tokens` (or `bezel build`) to regenerate. */\\n\"\n return `${header}\\n${blocks.filter(Boolean).join(\"\\n\\n\")}\\n`\n}\n","/**\n * Pure default constants shared by the isomorphic core and the Node layer.\n * Kept free of `node:*` imports so the browser/edge entry can use them.\n */\n\n/** Default context → selector mapping. The first key is the base context. */\nexport const DEFAULT_CONTEXTS: Record<string, string> = {\n $root: \":root\",\n dark: \".dark\",\n light: \".light\",\n}\n\n/**\n * The DTCG input file the CLI reads from the project root. This is a cross-system\n * contract: it MUST stay in sync with the platform's `TOKENS_FILE_NAME` constant\n * (gundam: libs/keypuncher/data/constants/src/lib/tokens-file.ts) so any repo/app\n * the platform connects to resolves its tokens at the same name + location.\n */\nexport const DEFAULT_INPUT = \"design-tokens.json\"\nexport const DEFAULT_VARIABLES_OUTPUT = \"variables.css\"\nexport const DEFAULT_NAME_EXTENSION = \"com.tokendesigner.app\"\n","import { DEFAULT_CONTEXTS, DEFAULT_NAME_EXTENSION } from \"./defaults\"\n\n/**\n * Options for the pure CSS transform ({@link tokensToCss}/{@link emitCss}),\n * decoupled from any filesystem concern so they work in any environment.\n * All optional; defaults make the zero-config case work.\n */\nexport interface CssOptions {\n /**\n * Map of context name → CSS selector. The first entry is the base context (full\n * output); every other context emits only the variables that differ from the base.\n * Default: `{ \"$root\": \":root\", \"dark\": \".dark\", \"light\": \".light\" }`.\n */\n contexts?: Record<string, string>\n /** Color serialization. Default: `\"oklch\"`. */\n colorFormat?: \"oklch\" | \"hex\"\n /** Dimension handling: keep the authored unit, or convert `px` → `rem`. Default: `\"preserve\"`. */\n dimensionUnit?: \"preserve\" | \"rem\"\n /** `$extensions` key holding the `exportName` array. Default: `\"com.tokendesigner.app\"`. */\n nameExtension?: string\n}\n\n/** Fully-resolved CSS-transform options (no `undefined`). */\nexport interface ResolvedCssOptions {\n contexts: Record<string, string>\n colorFormat: \"oklch\" | \"hex\"\n dimensionUnit: \"preserve\" | \"rem\"\n nameExtension: string\n}\n\n/** Apply defaults to {@link CssOptions}. Pure — no path resolution, no `node:*`. */\nexport function resolveCssOptions(options: CssOptions = {}): ResolvedCssOptions {\n const contexts = options.contexts ?? DEFAULT_CONTEXTS\n if (Object.keys(contexts).length === 0) {\n throw new Error(\"bezel: `contexts` must define at least one context.\")\n }\n\n return {\n contexts,\n colorFormat: options.colorFormat ?? \"oklch\",\n dimensionUnit: options.dimensionUnit ?? \"preserve\",\n nameExtension: options.nameExtension ?? DEFAULT_NAME_EXTENSION,\n }\n}\n","import { ROOT_CONTEXT } from \"./collapse\"\nimport type { DtcgNode } from \"./types\"\n\n/** Name the `$root` context maps to in generated output (matches the `:root` CSS scope). */\nexport const DEFAULT_CONTEXT_NAME = \"default\"\n\nfunction isObject(v: unknown): v is Record<string, unknown> {\n return typeof v === \"object\" && v !== null && !Array.isArray(v)\n}\n\nfunction isContextWrapper(v: unknown): boolean {\n return isObject(v) && \"$value\" in v\n}\n\n/**\n * Extract the distinct context names declared anywhere in a DTCG token tree.\n *\n * Walks to each logical token (a node with a `$root` context wrapper) and collects the\n * context keys it declares (`$root`, `dark`, `light`, …). `$root` is mapped to\n * `\"default\"` and placed first; the rest follow in first-seen order, deduped.\n */\nexport function getContexts(tokens: DtcgNode, rootName: string = DEFAULT_CONTEXT_NAME): string[] {\n const order: string[] = []\n const seen = new Set<string>()\n\n const walk = (node: DtcgNode): void => {\n if (ROOT_CONTEXT in node && isContextWrapper(node[ROOT_CONTEXT])) {\n for (const key of Object.keys(node)) {\n if (key.startsWith(\"$\") && key !== ROOT_CONTEXT) continue\n if (isContextWrapper(node[key]) && !seen.has(key)) {\n seen.add(key)\n order.push(key)\n }\n }\n return\n }\n for (const key of Object.keys(node)) {\n if (key.startsWith(\"$\")) continue\n const child = node[key]\n if (isObject(child)) walk(child as DtcgNode)\n }\n }\n\n walk(tokens)\n\n const mapped = order.map((k) => (k === ROOT_CONTEXT ? rootName : k))\n return [...new Set([rootName, ...mapped])]\n}\n\n/** Render the generated `contexts.ts` module emitted alongside `variables.css`. */\nexport function formatContextsModule(contexts: string[]): string {\n const list = contexts.map((c) => JSON.stringify(c)).join(\", \")\n return (\n \"/* Generated by bezel — do not edit by hand. */\\n\" +\n \"/* Run `npm run tokens` (or `bezel build`) to regenerate. */\\n\\n\" +\n `export const CONTEXTS = [${list}] as const\\n\\n` +\n \"export type Context = (typeof CONTEXTS)[number]\\n\"\n )\n}\n","import { flattenForContext, ROOT_CONTEXT } from \"./collapse\"\nimport { resolveReferences } from \"./resolve\"\nimport type { DtcgNode, TokenValue } from \"./types\"\n\n/** A web font to load: a family name and the weights it is used at. */\nexport interface FontDef {\n family: string\n weights: number[]\n}\n\n/** Generic CSS family keywords that are never loaded as web fonts. */\nconst GENERIC_FAMILIES = new Set([\n \"serif\",\n \"sans-serif\",\n \"monospace\",\n \"cursive\",\n \"fantasy\",\n \"system-ui\",\n \"ui-serif\",\n \"ui-sans-serif\",\n \"ui-monospace\",\n \"ui-rounded\",\n \"math\",\n \"emoji\",\n \"fangsong\",\n \"inherit\",\n \"initial\",\n \"unset\",\n])\n\nconst DEFAULT_WEIGHT = 400\n\n/** Resolve a fontFamily token value to a primary family name (first non-generic), or null. */\nfunction primaryFamily(value: TokenValue): string | null {\n const candidates = Array.isArray(value) ? value : [value]\n for (const candidate of candidates) {\n if (typeof candidate !== \"string\") continue\n const name = candidate.trim().replace(/^['\"]|['\"]$/g, \"\")\n if (name && !GENERIC_FAMILIES.has(name.toLowerCase())) return name\n }\n return null\n}\n\nfunction parentPath(path: string): string {\n const i = path.lastIndexOf(\".\")\n return i === -1 ? \"\" : path.slice(0, i)\n}\n\n/**\n * Extract the web fonts referenced by a DTCG token tree.\n *\n * Collects every distinct `fontFamily` value (references resolved), then derives each\n * family's weights from the semantic typography composites — a group whose `font-family`\n * resolves to that family contributes its sibling `font-weight`. Families used without an\n * accompanying weight default to `[400]`. Result is sorted by family for determinism.\n */\nexport function getFonts(tokens: DtcgNode): FontDef[] {\n const flat = resolveReferences(flattenForContext(tokens, ROOT_CONTEXT))\n\n const families = new Set<string>()\n const familyByParent = new Map<string, string>()\n const weightByParent = new Map<string, number>()\n\n for (const token of flat.values()) {\n if (token.type === \"fontFamily\") {\n const family = primaryFamily(token.value)\n if (family) {\n families.add(family)\n familyByParent.set(parentPath(token.path), family)\n }\n } else if (token.type === \"fontWeight\" && typeof token.value === \"number\") {\n weightByParent.set(parentPath(token.path), token.value)\n }\n }\n\n const weightsByFamily = new Map<string, Set<number>>()\n for (const [parent, family] of familyByParent) {\n const weight = weightByParent.get(parent)\n if (weight === undefined) continue\n const set = weightsByFamily.get(family) ?? new Set<number>()\n set.add(weight)\n weightsByFamily.set(family, set)\n }\n\n return [...families].sort().map((family) => {\n const weights = weightsByFamily.get(family)\n return {\n family,\n weights: weights ? [...weights].sort((a, b) => a - b) : [DEFAULT_WEIGHT],\n }\n })\n}\n\n/** Render the generated `fonts.ts` module emitted alongside `variables.css`. */\nexport function formatFontsModule(fonts: FontDef[]): string {\n const entries = fonts\n .map((f) => ` { family: ${JSON.stringify(f.family)}, weights: [${f.weights.join(\", \")}] },`)\n .join(\"\\n\")\n return (\n \"/* Generated by bezel — do not edit by hand. */\\n\" +\n \"/* Run `npm run tokens` (or `bezel build`) to regenerate. */\\n\\n\" +\n `export const FONTS = [\\n${entries}\\n] as const\\n\\n` +\n \"export type FontDef = { family: string; weights: number[] }\\n\"\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACGO,IAAM,eAAe;AAE5B,SAAS,SAAS,GAA0C;AAC1D,SAAO,OAAO,MAAM,YAAY,MAAM,QAAQ,CAAC,MAAM,QAAQ,CAAC;AAChE;AAGA,SAAS,iBAAiB,GAA2B;AACnD,SAAO,SAAS,CAAC,KAAK,YAAY;AACpC;AAGA,SAAS,UAAU,KAAsB;AACvC,SAAO,QAAQ,WAAW,QAAQ,kBAAkB,QAAQ,iBAAiB,QAAQ;AACvF;AAcO,SAAS,kBAAkB,QAAkB,SAAyC;AAC3F,QAAM,MAAM,oBAAI,IAAuB;AAEvC,QAAM,OAAO,CAAC,MAAgB,MAAc,kBAA4C;AACtF,UAAM,OAAO,OAAO,KAAK,UAAU,WAAW,KAAK,QAAQ;AAG3D,QAAI,YAAY,MAAM;AACpB,UAAI,IAAI,MAAM;AAAA,QACZ;AAAA,QACA,OAAO,KAAK;AAAA,QACZ;AAAA,QACA,YAAY,KAAK;AAAA,MACnB,CAAC;AACD;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,MAAM,UAAU,UAAU;AACzE,qBAAe,IAAI,WAAW,MAAM,IAAI,GAAG,MAAM,KAAK;AAAA,IACxD;AAAA,EACF;AAEA,QAAM,kBAAkB,oBAAI,IAAyB;AACrD,aAAW,CAAC,QAAQ,MAAM,KAAK,gBAAgB;AAC7C,UAAM,SAAS,eAAe,IAAI,MAAM;AACxC,QAAI,WAAW,OAAW;AAC1B,UAAM,MAAM,gBAAgB,IAAI,MAAM,KAAK,oBAAI,IAAY;AAC3D,QAAI,IAAI,MAAM;AACd,oBAAgB,IAAI,QAAQ,GAAG;AAAA,EACjC;AAEA,SAAO,CAAC,GAAG,QAAQ,EAAE,KAAK,EAAE,IAAI,CAAC,WAAW;AAC1C,UAAM,UAAU,gBAAgB,IAAI,MAAM;AAC1C,WAAO;AAAA,MACL;AAAA,MACA,SAAS,UAAU,CAAC,GAAG,OAAO,EAAE,KAAK,CAAC,GAAG,MAAM,IAAI,CAAC,IAAI,CAAC,cAAc;AAAA,IACzE;AAAA,EACF,CAAC;AACH;AAGO,SAAS,kBAAkB,OAA0B;AAC1D,QAAM,UAAU,MACb,IAAI,CAAC,MAAM,eAAe,KAAK,UAAU,EAAE,MAAM,CAAC,eAAe,EAAE,QAAQ,KAAK,IAAI,CAAC,MAAM,EAC3F,KAAK,IAAI;AACZ,SACE;AAAA;AAAA;AAAA;AAAA,EAE2B,OAAO;AAAA;AAAA;AAAA;AAAA;AAGtC;;;ATtEO,SAAS,YAAY,QAAkB,UAAsB,CAAC,GAAW;AAC9E,SAAO,QAAQ,QAAQ,kBAAkB,OAAO,CAAC;AACnD;","names":["isObject","isObject","isContextWrapper"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/collapse.ts","../src/name.ts","../src/resolve.ts","../src/serialize.ts","../src/emit.ts","../src/defaults.ts","../src/options.ts","../src/contexts.ts","../src/fonts.ts"],"sourcesContent":["/**\n * bezel — isomorphic entry.\n *\n * The pure transform core: convert an in-memory W3C Design Tokens (DTCG) object\n * into a scoped `variables.css` string. Imports no `node:*`, so it runs anywhere\n * — browser, edge, Node. For the filesystem/CLI conveniences (reading a tokens\n * file, writing outputs), import from `bezel/node`.\n */\nimport { emitCss } from \"./emit\"\nimport { resolveCssOptions, type CssOptions } from \"./options\"\nimport type { DtcgNode } from \"./types\"\n\nexport type { CssOptions, ResolvedCssOptions } from \"./options\"\nexport type { DtcgNode, FlatToken, TokenValue, ColorValue, DimensionValue } from \"./types\"\nexport { DEFAULT_CONTEXTS, DEFAULT_NAME_EXTENSION } from \"./defaults\"\nexport { emitCss } from \"./emit\"\nexport { resolveCssOptions } from \"./options\"\nexport { getContexts, formatContextsModule, DEFAULT_CONTEXT_NAME } from \"./contexts\"\nexport { getFonts, formatFontsModule } from \"./fonts\"\nexport type { FontDef } from \"./fonts\"\n\n/**\n * Convert a DTCG token object into a scoped `variables.css` string.\n *\n * Resolves each configured context (with `$root` fallback and reference\n * resolution) and emits one CSS scope per context — the base context in full,\n * others as override-only blocks. Pure: no filesystem access.\n *\n * @example\n * const css = tokensToCss(tokens)\n *\n * @example\n * const css = tokensToCss(tokens, { colorFormat: \"hex\", contexts: { $root: \":root\" } })\n */\nexport function tokensToCss(tokens: DtcgNode, options: CssOptions = {}): string {\n return emitCss(tokens, resolveCssOptions(options))\n}\n","import type { DtcgNode, FlatToken, TokenValue } from \"./types\"\n\n/** The W3C \"root token\" key — the base value of a group / logical token. */\nexport const ROOT_CONTEXT = \"$root\"\n\nfunction isObject(v: unknown): v is Record<string, unknown> {\n return typeof v === \"object\" && v !== null && !Array.isArray(v)\n}\n\n/** A \"context wrapper\" is a child object that directly holds a `$value` (e.g. `dark`, `light`, `$root`). */\nfunction isContextWrapper(v: unknown): v is DtcgNode {\n return isObject(v) && \"$value\" in v\n}\n\n/** Keys that are DTCG metadata, never traversed as child tokens/contexts. */\nfunction isMetaKey(key: string): boolean {\n return key === \"$type\" || key === \"$description\" || key === \"$extensions\" || key === \"$value\"\n}\n\n/**\n * Collapse a DTCG token tree to the single value that applies for `context`, and\n * flatten it to a map of dot-path → {@link FlatToken}.\n *\n * Handles three node shapes:\n * - **Simple token** — a node with a direct `$value` (context-invariant).\n * - **Logical token** — a node whose children include context wrappers (one of\n * which is `$root`). The value for `context` is picked, falling back to `$root`.\n * - **Group** — anything else; recursed into.\n *\n * `$type` is inherited from the nearest ancestor that declares one.\n */\nexport function flattenForContext(tokens: DtcgNode, context: string): Map<string, FlatToken> {\n const out = new Map<string, FlatToken>()\n\n const walk = (node: DtcgNode, path: string, inheritedType: string | undefined): void => {\n const type = typeof node.$type === \"string\" ? node.$type : inheritedType\n\n // Simple token: direct $value.\n if (\"$value\" in node) {\n out.set(path, {\n path,\n value: node.$value as TokenValue,\n type,\n extensions: node.$extensions,\n })\n return\n }\n\n // Logical token: has context-wrapper children (dark/light/$root).\n const wrapperKeys = Object.keys(node).filter((k) => !isMetaKey(k) && isContextWrapper(node[k]))\n if (wrapperKeys.length > 0) {\n const chosen =\n (node[context] as DtcgNode | undefined) ??\n (node[ROOT_CONTEXT] as DtcgNode | undefined) ??\n (node[wrapperKeys[0]!] as DtcgNode)\n out.set(path, {\n path,\n value: chosen.$value as TokenValue,\n type,\n extensions: node.$extensions,\n })\n return\n }\n\n // Group: recurse into non-meta children.\n for (const key of Object.keys(node)) {\n if (isMetaKey(key)) continue\n const child = node[key]\n if (isObject(child)) {\n walk(child as DtcgNode, path ? `${path}.${key}` : key, type)\n }\n }\n }\n\n walk(tokens, \"\", undefined)\n return out\n}\n","import type { FlatToken } from \"./types\"\n\n/** Leading path segments dropped when deriving a CSS name from a token path. */\nconst DROPPED_PREFIXES = new Set([\"base\", \"semantic\"])\n/** Trailing path segments dropped (a group's \"default\"/root token maps to the bare group name). */\nconst DROPPED_SUFFIXES = new Set([\"default\", \"$root\"])\n\nfunction exportNames(token: FlatToken, nameExtension: string): string[] | undefined {\n const ext = token.extensions?.[nameExtension]\n if (ext && typeof ext === \"object\" && \"exportName\" in ext) {\n const names = (ext as { exportName: unknown }).exportName\n if (Array.isArray(names)) return names.filter((n): n is string => typeof n === \"string\")\n }\n return undefined\n}\n\n/** True if any token in the map declares an `exportName` under `nameExtension`. */\nexport function usesExportNames(\n tokens: Iterable<FlatToken>,\n nameExtension: string,\n): boolean {\n for (const token of tokens) {\n if (exportNames(token, nameExtension) !== undefined) return true\n }\n return false\n}\n\n/** Derive a CSS variable name from a dot-path (fallback when no `exportName` exists). */\nexport function nameFromPath(path: string): string {\n const segments = path.split(\".\")\n while (segments.length > 1 && DROPPED_PREFIXES.has(segments[0]!)) segments.shift()\n while (segments.length > 1 && DROPPED_SUFFIXES.has(segments[segments.length - 1]!)) {\n segments.pop()\n }\n return segments.join(\"-\")\n}\n\n/**\n * Resolve the CSS variable name(s) a token emits (without the leading `--`).\n *\n * - In **exportName mode** (`useExportName`), names come solely from the token's\n * `exportName` array. A token without one — or with only empty strings — emits\n * nothing (it exists purely as a reference target). One token may emit many names.\n * - Otherwise (generic DTCG), the name is derived from the token's path.\n */\nexport function cssNames(\n token: FlatToken,\n nameExtension: string,\n useExportName: boolean,\n): string[] {\n if (useExportName) {\n const names = exportNames(token, nameExtension)\n if (!names) return []\n return names.filter((n) => n.length > 0)\n }\n return [nameFromPath(token.path)]\n}\n","import type { FlatToken, TokenValue } from \"./types\"\n\nconst REFERENCE_RE = /^\\{([^{}]+)\\}$/\n\n/** Returns the referenced path if `value` is a whole-value DTCG alias `\"{a.b.c}\"`, else `null`. */\nexport function aliasTarget(value: TokenValue): string | null {\n if (typeof value !== \"string\") return null\n const match = REFERENCE_RE.exec(value.trim())\n return match ? match[1]!.trim() : null\n}\n\n/**\n * Resolve whole-value references (`\"{a.b.c}\"`) in a flattened, single-context token\n * map, in place. Because the map was collapsed for one context, following an alias\n * yields that context's value (with `$root` fallback already applied during collapse).\n *\n * Multi-hop aliases are followed, results memoized, and cycles guarded against.\n */\nexport function resolveReferences(tokens: Map<string, FlatToken>): Map<string, FlatToken> {\n const resolved = new Map<string, TokenValue>()\n\n const resolveValue = (value: TokenValue, seen: Set<string>): TokenValue => {\n const target = aliasTarget(value)\n if (target === null) return value\n\n if (resolved.has(target)) return resolved.get(target)!\n if (seen.has(target)) {\n throw new Error(`bezel: circular token reference detected at \"{${target}}\".`)\n }\n\n const token = tokens.get(target)\n if (!token) {\n throw new Error(`bezel: unresolved token reference \"{${target}}\".`)\n }\n\n seen.add(target)\n const value2 = resolveValue(token.value, seen)\n seen.delete(target)\n resolved.set(target, value2)\n return value2\n }\n\n for (const token of tokens.values()) {\n token.value = resolveValue(token.value, new Set())\n }\n return tokens\n}\n","import type { ResolvedCssOptions } from \"./options\"\nimport type {\n ColorValue,\n DimensionValue,\n TokenValue,\n} from \"./types\"\n\nfunction isObject(v: unknown): v is Record<string, unknown> {\n return typeof v === \"object\" && v !== null && !Array.isArray(v)\n}\n\nfunction isColor(v: unknown): v is ColorValue {\n return isObject(v) && \"colorSpace\" in v && Array.isArray(v[\"components\"])\n}\n\nfunction isDimension(v: unknown): v is DimensionValue {\n return isObject(v) && typeof v[\"value\"] === \"number\" && \"unit\" in v\n}\n\n/** Round to at most `dp` decimals without trailing zeros. */\nfunction round(n: number, dp: number): number {\n const f = 10 ** dp\n return Math.round(n * f) / f\n}\n\nfunction serializeColor(color: ColorValue, format: ResolvedCssOptions[\"colorFormat\"]): string {\n if (format === \"hex\" && color.hex) return color.hex.toLowerCase()\n\n if (color.colorSpace === \"oklch\") {\n const [l = 0, c = 0, h = 0] = color.components\n const base = `oklch(${round(l, 4)} ${round(c, 4)} ${round(h, 3)})`\n if (color.alpha !== undefined && color.alpha < 1) {\n return `oklch(${round(l, 4)} ${round(c, 4)} ${round(h, 3)} / ${round(color.alpha, 4)})`\n }\n return base\n }\n\n // Unknown color space: prefer hex fallback, else CSS color() function.\n if (color.hex) return color.hex.toLowerCase()\n return `color(${color.colorSpace} ${color.components.map((n) => round(n, 4)).join(\" \")})`\n}\n\nfunction serializeDimension(dim: DimensionValue, unit: ResolvedCssOptions[\"dimensionUnit\"]): string {\n if (unit === \"rem\" && dim.unit === \"px\") {\n return `${round(dim.value / 16, 4)}rem`\n }\n return `${dim.value}${dim.unit}`\n}\n\n/** Quote a font-family name if it contains whitespace and isn't already quoted. */\nfunction quoteFamily(name: string): string {\n const trimmed = name.trim()\n if (/^['\"].*['\"]$/.test(trimmed)) return trimmed\n return /\\s/.test(trimmed) ? `\"${trimmed}\"` : trimmed\n}\n\n/** Serialize a resolved token value to a CSS declaration value. */\nexport function serializeValue(value: TokenValue, options: ResolvedCssOptions): string {\n if (isColor(value)) return serializeColor(value, options.colorFormat)\n if (isDimension(value)) return serializeDimension(value, options.dimensionUnit)\n\n // fontFamily as an array of names.\n if (Array.isArray(value)) {\n return value.map((v) => quoteFamily(String(v))).join(\", \")\n }\n\n if (typeof value === \"number\") return String(value)\n\n // Strings: could be a single font-family name or an already-formatted value.\n // Quote multi-word family names; leave comma-lists and plain values untouched.\n const str = String(value)\n if (/\\s/.test(str) && !str.includes(\",\") && !/[()]/.test(str)) {\n return quoteFamily(str)\n }\n return str\n}\n","import { flattenForContext } from \"./collapse\"\nimport { cssNames, usesExportNames } from \"./name\"\nimport { resolveReferences } from \"./resolve\"\nimport { serializeValue } from \"./serialize\"\nimport type { ResolvedCssOptions } from \"./options\"\nimport type { DtcgNode } from \"./types\"\n\n/** An ordered map of CSS variable name → serialized value for one context. */\ntype VarMap = Map<string, string>\n\n/** Build the `name → cssValue` map for a single context. */\nfunction buildContextVars(\n tokens: DtcgNode,\n context: string,\n useExportName: boolean,\n options: ResolvedCssOptions,\n): VarMap {\n const flat = resolveReferences(flattenForContext(tokens, context))\n const vars: VarMap = new Map()\n for (const token of flat.values()) {\n const names = cssNames(token, options.nameExtension, useExportName)\n if (names.length === 0) continue\n const value = serializeValue(token.value, options)\n for (const name of names) vars.set(name, value)\n }\n return vars\n}\n\nfunction renderBlock(selector: string, vars: Iterable<[string, string]>): string {\n const lines = [...vars].map(([name, value]) => ` --${name}: ${value};`)\n if (lines.length === 0) return \"\"\n return `${selector} {\\n${lines.join(\"\\n\")}\\n}`\n}\n\n/**\n * Convert a DTCG token tree into a scoped CSS string. The first context in\n * `options.contexts` is the base (emitted in full); every other context emits\n * only the variables whose value differs from the base.\n */\nexport function emitCss(tokens: DtcgNode, options: ResolvedCssOptions): string {\n const contextNames = Object.keys(options.contexts)\n const useExportName = usesExportNames(\n flattenForContext(tokens, contextNames[0]!).values(),\n options.nameExtension,\n )\n\n const [baseContext, ...overrideContexts] = contextNames\n const baseVars = buildContextVars(tokens, baseContext!, useExportName, options)\n\n const blocks: string[] = [renderBlock(options.contexts[baseContext!]!, baseVars)]\n\n for (const context of overrideContexts) {\n const vars = buildContextVars(tokens, context, useExportName, options)\n const overrides = [...vars].filter(([name, value]) => baseVars.get(name) !== value)\n const block = renderBlock(options.contexts[context]!, overrides)\n if (block) blocks.push(block)\n }\n\n const header =\n \"/* Generated by bezel — do not edit by hand. */\\n\" +\n \"/* Run `npm run tokens` (or `bezel build`) to regenerate. */\\n\"\n return `${header}\\n${blocks.filter(Boolean).join(\"\\n\\n\")}\\n`\n}\n","/**\n * Pure default constants shared by the isomorphic core and the Node layer.\n * Kept free of `node:*` imports so the browser/edge entry can use them.\n */\n\n/** Default context → selector mapping. The first key is the base context. */\nexport const DEFAULT_CONTEXTS: Record<string, string> = {\n $root: \":root\",\n dark: \".dark\",\n light: \".light\",\n};\n\n/**\n * The DTCG input file the CLI reads from the project root. This is a cross-system\n * contract: it MUST stay in sync with the platform's `TOKENS_FILE_NAME` constant\n * so any repo/app the platform connects to resolves its tokens at the same name\n * and location.\n */\nexport const DEFAULT_INPUT = \"design-tokens.json\";\n\n/**\n * Directory generated outputs are written to, relative to the project root.\n *\n * Everything Bezel emits is generated and gitignored, and `bezel build` overwrites\n * without asking — so outputs live in their own directory rather than alongside\n * hand-written files, where a generic name like `variables.css` or `fonts.ts` could\n * silently clobber something the user wrote. {@link FALLBACK_OUTPUT_DIR} is used by\n * `bezel init` for projects with no `src/`.\n */\nexport const DEFAULT_OUTPUT_DIR = \"src/bezel\";\n/** Output directory `bezel init` picks when the project has no `src/`. */\nexport const FALLBACK_OUTPUT_DIR = \"bezel\";\n\n/** Generated output filenames, joined onto the output directory. */\nexport const VARIABLES_FILE = \"variables.css\";\nexport const CONTEXTS_FILE = \"contexts.ts\";\nexport const FONTS_FILE = \"fonts.ts\";\n\nexport const DEFAULT_VARIABLES_OUTPUT = `${DEFAULT_OUTPUT_DIR}/${VARIABLES_FILE}`;\nexport const DEFAULT_NAME_EXTENSION = \"com.bezel.app\";\n\n/** The config file `bezel init` writes and `bezel build` auto-loads from the project root. */\nexport const DEFAULT_CONFIG_FILE = \"bezel.json\";\n","import { DEFAULT_CONTEXTS, DEFAULT_NAME_EXTENSION } from \"./defaults\"\n\n/**\n * Options for the pure CSS transform ({@link tokensToCss}/{@link emitCss}),\n * decoupled from any filesystem concern so they work in any environment.\n * All optional; defaults make the zero-config case work.\n */\nexport interface CssOptions {\n /**\n * Map of context name → CSS selector. The first entry is the base context (full\n * output); every other context emits only the variables that differ from the base.\n * Default: `{ \"$root\": \":root\", \"dark\": \".dark\", \"light\": \".light\" }`.\n */\n contexts?: Record<string, string>\n /** Color serialization. Default: `\"oklch\"`. */\n colorFormat?: \"oklch\" | \"hex\"\n /** Dimension handling: keep the authored unit, or convert `px` → `rem`. Default: `\"preserve\"`. */\n dimensionUnit?: \"preserve\" | \"rem\"\n /** `$extensions` key holding the `exportName` array. Default: `\"com.bezel.app\"`. */\n nameExtension?: string\n}\n\n/** Fully-resolved CSS-transform options (no `undefined`). */\nexport interface ResolvedCssOptions {\n contexts: Record<string, string>\n colorFormat: \"oklch\" | \"hex\"\n dimensionUnit: \"preserve\" | \"rem\"\n nameExtension: string\n}\n\n/** Apply defaults to {@link CssOptions}. Pure — no path resolution, no `node:*`. */\nexport function resolveCssOptions(options: CssOptions = {}): ResolvedCssOptions {\n const contexts = options.contexts ?? DEFAULT_CONTEXTS\n if (Object.keys(contexts).length === 0) {\n throw new Error(\"bezel: `contexts` must define at least one context.\")\n }\n\n return {\n contexts,\n colorFormat: options.colorFormat ?? \"oklch\",\n dimensionUnit: options.dimensionUnit ?? \"preserve\",\n nameExtension: options.nameExtension ?? DEFAULT_NAME_EXTENSION,\n }\n}\n","import { ROOT_CONTEXT } from \"./collapse\"\nimport type { DtcgNode } from \"./types\"\n\n/** Name the `$root` context maps to in generated output (matches the `:root` CSS scope). */\nexport const DEFAULT_CONTEXT_NAME = \"default\"\n\nfunction isObject(v: unknown): v is Record<string, unknown> {\n return typeof v === \"object\" && v !== null && !Array.isArray(v)\n}\n\nfunction isContextWrapper(v: unknown): boolean {\n return isObject(v) && \"$value\" in v\n}\n\n/**\n * Extract the distinct context names declared anywhere in a DTCG token tree.\n *\n * Walks to each logical token (a node with a `$root` context wrapper) and collects the\n * context keys it declares (`$root`, `dark`, `light`, …). `$root` is mapped to\n * `\"default\"` and placed first; the rest follow in first-seen order, deduped.\n */\nexport function getContexts(tokens: DtcgNode, rootName: string = DEFAULT_CONTEXT_NAME): string[] {\n const order: string[] = []\n const seen = new Set<string>()\n\n const walk = (node: DtcgNode): void => {\n if (ROOT_CONTEXT in node && isContextWrapper(node[ROOT_CONTEXT])) {\n for (const key of Object.keys(node)) {\n if (key.startsWith(\"$\") && key !== ROOT_CONTEXT) continue\n if (isContextWrapper(node[key]) && !seen.has(key)) {\n seen.add(key)\n order.push(key)\n }\n }\n return\n }\n for (const key of Object.keys(node)) {\n if (key.startsWith(\"$\")) continue\n const child = node[key]\n if (isObject(child)) walk(child as DtcgNode)\n }\n }\n\n walk(tokens)\n\n const mapped = order.map((k) => (k === ROOT_CONTEXT ? rootName : k))\n return [...new Set([rootName, ...mapped])]\n}\n\n/** Render the generated `contexts.ts` module emitted alongside `variables.css`. */\nexport function formatContextsModule(contexts: string[]): string {\n const list = contexts.map((c) => JSON.stringify(c)).join(\", \")\n return (\n \"/* Generated by bezel — do not edit by hand. */\\n\" +\n \"/* Run `npm run tokens` (or `bezel build`) to regenerate. */\\n\\n\" +\n `export const CONTEXTS = [${list}] as const\\n\\n` +\n \"export type Context = (typeof CONTEXTS)[number]\\n\"\n )\n}\n","import { flattenForContext, ROOT_CONTEXT } from \"./collapse\"\nimport { resolveReferences } from \"./resolve\"\nimport type { DtcgNode, TokenValue } from \"./types\"\n\n/** A web font to load: a family name and the weights it is used at. */\nexport interface FontDef {\n family: string\n weights: number[]\n}\n\n/** Generic CSS family keywords that are never loaded as web fonts. */\nconst GENERIC_FAMILIES = new Set([\n \"serif\",\n \"sans-serif\",\n \"monospace\",\n \"cursive\",\n \"fantasy\",\n \"system-ui\",\n \"ui-serif\",\n \"ui-sans-serif\",\n \"ui-monospace\",\n \"ui-rounded\",\n \"math\",\n \"emoji\",\n \"fangsong\",\n \"inherit\",\n \"initial\",\n \"unset\",\n])\n\nconst DEFAULT_WEIGHT = 400\n\n/** Resolve a fontFamily token value to a primary family name (first non-generic), or null. */\nfunction primaryFamily(value: TokenValue): string | null {\n const candidates = Array.isArray(value) ? value : [value]\n for (const candidate of candidates) {\n if (typeof candidate !== \"string\") continue\n const name = candidate.trim().replace(/^['\"]|['\"]$/g, \"\")\n if (name && !GENERIC_FAMILIES.has(name.toLowerCase())) return name\n }\n return null\n}\n\nfunction parentPath(path: string): string {\n const i = path.lastIndexOf(\".\")\n return i === -1 ? \"\" : path.slice(0, i)\n}\n\n/**\n * Extract the web fonts referenced by a DTCG token tree.\n *\n * Collects every distinct `fontFamily` value (references resolved), then derives each\n * family's weights from the semantic typography composites — a group whose `font-family`\n * resolves to that family contributes its sibling `font-weight`. Families used without an\n * accompanying weight default to `[400]`. Result is sorted by family for determinism.\n */\nexport function getFonts(tokens: DtcgNode): FontDef[] {\n const flat = resolveReferences(flattenForContext(tokens, ROOT_CONTEXT))\n\n const families = new Set<string>()\n const familyByParent = new Map<string, string>()\n const weightByParent = new Map<string, number>()\n\n for (const token of flat.values()) {\n if (token.type === \"fontFamily\") {\n const family = primaryFamily(token.value)\n if (family) {\n families.add(family)\n familyByParent.set(parentPath(token.path), family)\n }\n } else if (token.type === \"fontWeight\" && typeof token.value === \"number\") {\n weightByParent.set(parentPath(token.path), token.value)\n }\n }\n\n const weightsByFamily = new Map<string, Set<number>>()\n for (const [parent, family] of familyByParent) {\n const weight = weightByParent.get(parent)\n if (weight === undefined) continue\n const set = weightsByFamily.get(family) ?? new Set<number>()\n set.add(weight)\n weightsByFamily.set(family, set)\n }\n\n return [...families].sort().map((family) => {\n const weights = weightsByFamily.get(family)\n return {\n family,\n weights: weights ? [...weights].sort((a, b) => a - b) : [DEFAULT_WEIGHT],\n }\n })\n}\n\n/** Render the generated `fonts.ts` module emitted alongside `variables.css`. */\nexport function formatFontsModule(fonts: FontDef[]): string {\n const entries = fonts\n .map((f) => ` { family: ${JSON.stringify(f.family)}, weights: [${f.weights.join(\", \")}] },`)\n .join(\"\\n\")\n return (\n \"/* Generated by bezel — do not edit by hand. */\\n\" +\n \"/* Run `npm run tokens` (or `bezel build`) to regenerate. */\\n\\n\" +\n `export const FONTS = [\\n${entries}\\n] as const\\n\\n` +\n \"export type FontDef = { family: string; weights: number[] }\\n\"\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACGO,IAAM,eAAe;AAE5B,SAAS,SAAS,GAA0C;AAC1D,SAAO,OAAO,MAAM,YAAY,MAAM,QAAQ,CAAC,MAAM,QAAQ,CAAC;AAChE;AAGA,SAAS,iBAAiB,GAA2B;AACnD,SAAO,SAAS,CAAC,KAAK,YAAY;AACpC;AAGA,SAAS,UAAU,KAAsB;AACvC,SAAO,QAAQ,WAAW,QAAQ,kBAAkB,QAAQ,iBAAiB,QAAQ;AACvF;AAcO,SAAS,kBAAkB,QAAkB,SAAyC;AAC3F,QAAM,MAAM,oBAAI,IAAuB;AAEvC,QAAM,OAAO,CAAC,MAAgB,MAAc,kBAA4C;AACtF,UAAM,OAAO,OAAO,KAAK,UAAU,WAAW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","names":["isObject","isObject","isContextWrapper"]}
package/dist/index.d.cts CHANGED
@@ -1,133 +1 @@
1
- /**
2
- * Options for the pure CSS transform ({@link tokensToCss}/{@link emitCss}),
3
- * decoupled from any filesystem concern so they work in any environment.
4
- * All optional; defaults make the zero-config case work.
5
- */
6
- interface CssOptions {
7
- /**
8
- * Map of context name → CSS selector. The first entry is the base context (full
9
- * output); every other context emits only the variables that differ from the base.
10
- * Default: `{ "$root": ":root", "dark": ".dark", "light": ".light" }`.
11
- */
12
- contexts?: Record<string, string>;
13
- /** Color serialization. Default: `"oklch"`. */
14
- colorFormat?: "oklch" | "hex";
15
- /** Dimension handling: keep the authored unit, or convert `px` → `rem`. Default: `"preserve"`. */
16
- dimensionUnit?: "preserve" | "rem";
17
- /** `$extensions` key holding the `exportName` array. Default: `"com.tokendesigner.app"`. */
18
- nameExtension?: string;
19
- }
20
- /** Fully-resolved CSS-transform options (no `undefined`). */
21
- interface ResolvedCssOptions {
22
- contexts: Record<string, string>;
23
- colorFormat: "oklch" | "hex";
24
- dimensionUnit: "preserve" | "rem";
25
- nameExtension: string;
26
- }
27
- /** Apply defaults to {@link CssOptions}. Pure — no path resolution, no `node:*`. */
28
- declare function resolveCssOptions(options?: CssOptions): ResolvedCssOptions;
29
-
30
- /**
31
- * Minimal type surface for the W3C Design Tokens (DTCG) 2025.10 format, plus
32
- * the internal shapes the generator passes between stages.
33
- *
34
- * @see https://www.designtokens.org/tr/2025.10/format/
35
- */
36
- /** A DTCG color value (e.g. `{ colorSpace: "oklch", components: [...], hex, alpha }`). */
37
- interface ColorValue {
38
- colorSpace: string;
39
- components: number[];
40
- hex?: string;
41
- alpha?: number;
42
- }
43
- /** A DTCG dimension value (e.g. `{ value: 12, unit: "px" }`). */
44
- interface DimensionValue {
45
- value: number;
46
- unit: string;
47
- }
48
- /** Any DTCG token value: a literal, a reference string `"{a.b.c}"`, or a typed object. */
49
- type TokenValue = string | number | ColorValue | DimensionValue | (string | number)[] | Record<string, unknown>;
50
- /**
51
- * An arbitrary DTCG node — either a group (nested nodes) or a token (`$value`).
52
- * Indexed loosely because we walk it structurally rather than by a fixed schema.
53
- */
54
- interface DtcgNode {
55
- $value?: TokenValue;
56
- $type?: string;
57
- $description?: string;
58
- $extensions?: Record<string, unknown>;
59
- [key: string]: unknown;
60
- }
61
- /** A single logical token after the tree has been collapsed + flattened for one context. */
62
- interface FlatToken {
63
- /** Dot-path of the token in the source tree (contexts already stripped). */
64
- path: string;
65
- /** The token's value for the active context (may still be a `"{ref}"`). */
66
- value: TokenValue;
67
- /** Resolved/inherited `$type`, if known. */
68
- type?: string;
69
- /** Vendor extensions carried through from the source token. */
70
- extensions?: Record<string, unknown>;
71
- }
72
-
73
- /**
74
- * Pure default constants shared by the isomorphic core and the Node layer.
75
- * Kept free of `node:*` imports so the browser/edge entry can use them.
76
- */
77
- /** Default context → selector mapping. The first key is the base context. */
78
- declare const DEFAULT_CONTEXTS: Record<string, string>;
79
- declare const DEFAULT_NAME_EXTENSION = "com.tokendesigner.app";
80
-
81
- /**
82
- * Convert a DTCG token tree into a scoped CSS string. The first context in
83
- * `options.contexts` is the base (emitted in full); every other context emits
84
- * only the variables whose value differs from the base.
85
- */
86
- declare function emitCss(tokens: DtcgNode, options: ResolvedCssOptions): string;
87
-
88
- /** Name the `$root` context maps to in generated output (matches the `:root` CSS scope). */
89
- declare const DEFAULT_CONTEXT_NAME = "default";
90
- /**
91
- * Extract the distinct context names declared anywhere in a DTCG token tree.
92
- *
93
- * Walks to each logical token (a node with a `$root` context wrapper) and collects the
94
- * context keys it declares (`$root`, `dark`, `light`, …). `$root` is mapped to
95
- * `"default"` and placed first; the rest follow in first-seen order, deduped.
96
- */
97
- declare function getContexts(tokens: DtcgNode, rootName?: string): string[];
98
- /** Render the generated `contexts.ts` module emitted alongside `variables.css`. */
99
- declare function formatContextsModule(contexts: string[]): string;
100
-
101
- /** A web font to load: a family name and the weights it is used at. */
102
- interface FontDef {
103
- family: string;
104
- weights: number[];
105
- }
106
- /**
107
- * Extract the web fonts referenced by a DTCG token tree.
108
- *
109
- * Collects every distinct `fontFamily` value (references resolved), then derives each
110
- * family's weights from the semantic typography composites — a group whose `font-family`
111
- * resolves to that family contributes its sibling `font-weight`. Families used without an
112
- * accompanying weight default to `[400]`. Result is sorted by family for determinism.
113
- */
114
- declare function getFonts(tokens: DtcgNode): FontDef[];
115
- /** Render the generated `fonts.ts` module emitted alongside `variables.css`. */
116
- declare function formatFontsModule(fonts: FontDef[]): string;
117
-
118
- /**
119
- * Convert a DTCG token object into a scoped `variables.css` string.
120
- *
121
- * Resolves each configured context (with `$root` fallback and reference
122
- * resolution) and emits one CSS scope per context — the base context in full,
123
- * others as override-only blocks. Pure: no filesystem access.
124
- *
125
- * @example
126
- * const css = tokensToCss(tokens)
127
- *
128
- * @example
129
- * const css = tokensToCss(tokens, { colorFormat: "hex", contexts: { $root: ":root" } })
130
- */
131
- declare function tokensToCss(tokens: DtcgNode, options?: CssOptions): string;
132
-
133
- export { type ColorValue, type CssOptions, DEFAULT_CONTEXTS, DEFAULT_CONTEXT_NAME, DEFAULT_NAME_EXTENSION, type DimensionValue, type DtcgNode, type FlatToken, type FontDef, type ResolvedCssOptions, type TokenValue, emitCss, formatContextsModule, formatFontsModule, getContexts, getFonts, resolveCssOptions, tokensToCss };
1
+ export { a as ColorValue, C as CssOptions, b as DEFAULT_CONTEXTS, c as DEFAULT_CONTEXT_NAME, d as DEFAULT_NAME_EXTENSION, f as DimensionValue, g as DtcgNode, h as FlatToken, i as FontDef, R as ResolvedCssOptions, T as TokenValue, j as emitCss, k as formatContextsModule, l as formatFontsModule, m as getContexts, n as getFonts, r as resolveCssOptions, t as tokensToCss } from './index-GGPx58oG.cjs';
package/dist/index.d.ts CHANGED
@@ -1,133 +1 @@
1
- /**
2
- * Options for the pure CSS transform ({@link tokensToCss}/{@link emitCss}),
3
- * decoupled from any filesystem concern so they work in any environment.
4
- * All optional; defaults make the zero-config case work.
5
- */
6
- interface CssOptions {
7
- /**
8
- * Map of context name → CSS selector. The first entry is the base context (full
9
- * output); every other context emits only the variables that differ from the base.
10
- * Default: `{ "$root": ":root", "dark": ".dark", "light": ".light" }`.
11
- */
12
- contexts?: Record<string, string>;
13
- /** Color serialization. Default: `"oklch"`. */
14
- colorFormat?: "oklch" | "hex";
15
- /** Dimension handling: keep the authored unit, or convert `px` → `rem`. Default: `"preserve"`. */
16
- dimensionUnit?: "preserve" | "rem";
17
- /** `$extensions` key holding the `exportName` array. Default: `"com.tokendesigner.app"`. */
18
- nameExtension?: string;
19
- }
20
- /** Fully-resolved CSS-transform options (no `undefined`). */
21
- interface ResolvedCssOptions {
22
- contexts: Record<string, string>;
23
- colorFormat: "oklch" | "hex";
24
- dimensionUnit: "preserve" | "rem";
25
- nameExtension: string;
26
- }
27
- /** Apply defaults to {@link CssOptions}. Pure — no path resolution, no `node:*`. */
28
- declare function resolveCssOptions(options?: CssOptions): ResolvedCssOptions;
29
-
30
- /**
31
- * Minimal type surface for the W3C Design Tokens (DTCG) 2025.10 format, plus
32
- * the internal shapes the generator passes between stages.
33
- *
34
- * @see https://www.designtokens.org/tr/2025.10/format/
35
- */
36
- /** A DTCG color value (e.g. `{ colorSpace: "oklch", components: [...], hex, alpha }`). */
37
- interface ColorValue {
38
- colorSpace: string;
39
- components: number[];
40
- hex?: string;
41
- alpha?: number;
42
- }
43
- /** A DTCG dimension value (e.g. `{ value: 12, unit: "px" }`). */
44
- interface DimensionValue {
45
- value: number;
46
- unit: string;
47
- }
48
- /** Any DTCG token value: a literal, a reference string `"{a.b.c}"`, or a typed object. */
49
- type TokenValue = string | number | ColorValue | DimensionValue | (string | number)[] | Record<string, unknown>;
50
- /**
51
- * An arbitrary DTCG node — either a group (nested nodes) or a token (`$value`).
52
- * Indexed loosely because we walk it structurally rather than by a fixed schema.
53
- */
54
- interface DtcgNode {
55
- $value?: TokenValue;
56
- $type?: string;
57
- $description?: string;
58
- $extensions?: Record<string, unknown>;
59
- [key: string]: unknown;
60
- }
61
- /** A single logical token after the tree has been collapsed + flattened for one context. */
62
- interface FlatToken {
63
- /** Dot-path of the token in the source tree (contexts already stripped). */
64
- path: string;
65
- /** The token's value for the active context (may still be a `"{ref}"`). */
66
- value: TokenValue;
67
- /** Resolved/inherited `$type`, if known. */
68
- type?: string;
69
- /** Vendor extensions carried through from the source token. */
70
- extensions?: Record<string, unknown>;
71
- }
72
-
73
- /**
74
- * Pure default constants shared by the isomorphic core and the Node layer.
75
- * Kept free of `node:*` imports so the browser/edge entry can use them.
76
- */
77
- /** Default context → selector mapping. The first key is the base context. */
78
- declare const DEFAULT_CONTEXTS: Record<string, string>;
79
- declare const DEFAULT_NAME_EXTENSION = "com.tokendesigner.app";
80
-
81
- /**
82
- * Convert a DTCG token tree into a scoped CSS string. The first context in
83
- * `options.contexts` is the base (emitted in full); every other context emits
84
- * only the variables whose value differs from the base.
85
- */
86
- declare function emitCss(tokens: DtcgNode, options: ResolvedCssOptions): string;
87
-
88
- /** Name the `$root` context maps to in generated output (matches the `:root` CSS scope). */
89
- declare const DEFAULT_CONTEXT_NAME = "default";
90
- /**
91
- * Extract the distinct context names declared anywhere in a DTCG token tree.
92
- *
93
- * Walks to each logical token (a node with a `$root` context wrapper) and collects the
94
- * context keys it declares (`$root`, `dark`, `light`, …). `$root` is mapped to
95
- * `"default"` and placed first; the rest follow in first-seen order, deduped.
96
- */
97
- declare function getContexts(tokens: DtcgNode, rootName?: string): string[];
98
- /** Render the generated `contexts.ts` module emitted alongside `variables.css`. */
99
- declare function formatContextsModule(contexts: string[]): string;
100
-
101
- /** A web font to load: a family name and the weights it is used at. */
102
- interface FontDef {
103
- family: string;
104
- weights: number[];
105
- }
106
- /**
107
- * Extract the web fonts referenced by a DTCG token tree.
108
- *
109
- * Collects every distinct `fontFamily` value (references resolved), then derives each
110
- * family's weights from the semantic typography composites — a group whose `font-family`
111
- * resolves to that family contributes its sibling `font-weight`. Families used without an
112
- * accompanying weight default to `[400]`. Result is sorted by family for determinism.
113
- */
114
- declare function getFonts(tokens: DtcgNode): FontDef[];
115
- /** Render the generated `fonts.ts` module emitted alongside `variables.css`. */
116
- declare function formatFontsModule(fonts: FontDef[]): string;
117
-
118
- /**
119
- * Convert a DTCG token object into a scoped `variables.css` string.
120
- *
121
- * Resolves each configured context (with `$root` fallback and reference
122
- * resolution) and emits one CSS scope per context — the base context in full,
123
- * others as override-only blocks. Pure: no filesystem access.
124
- *
125
- * @example
126
- * const css = tokensToCss(tokens)
127
- *
128
- * @example
129
- * const css = tokensToCss(tokens, { colorFormat: "hex", contexts: { $root: ":root" } })
130
- */
131
- declare function tokensToCss(tokens: DtcgNode, options?: CssOptions): string;
132
-
133
- export { type ColorValue, type CssOptions, DEFAULT_CONTEXTS, DEFAULT_CONTEXT_NAME, DEFAULT_NAME_EXTENSION, type DimensionValue, type DtcgNode, type FlatToken, type FontDef, type ResolvedCssOptions, type TokenValue, emitCss, formatContextsModule, formatFontsModule, getContexts, getFonts, resolveCssOptions, tokensToCss };
1
+ export { a as ColorValue, C as CssOptions, b as DEFAULT_CONTEXTS, c as DEFAULT_CONTEXT_NAME, d as DEFAULT_NAME_EXTENSION, f as DimensionValue, g as DtcgNode, h as FlatToken, i as FontDef, R as ResolvedCssOptions, T as TokenValue, j as emitCss, k as formatContextsModule, l as formatFontsModule, m as getContexts, n as getFonts, r as resolveCssOptions, t as tokensToCss } from './index-GGPx58oG.js';
package/dist/index.js CHANGED
@@ -9,7 +9,7 @@ import {
9
9
  getFonts,
10
10
  resolveCssOptions,
11
11
  tokensToCss
12
- } from "./chunk-5EW7EW3R.js";
12
+ } from "./chunk-T6DKROBI.js";
13
13
  export {
14
14
  DEFAULT_CONTEXTS,
15
15
  DEFAULT_CONTEXT_NAME,
package/dist/node.cjs CHANGED
@@ -20,22 +20,27 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/node.ts
21
21
  var node_exports = {};
22
22
  __export(node_exports, {
23
+ DEFAULT_CONFIG_FILE: () => DEFAULT_CONFIG_FILE,
23
24
  DEFAULT_CONTEXTS: () => DEFAULT_CONTEXTS,
24
25
  DEFAULT_CONTEXT_NAME: () => DEFAULT_CONTEXT_NAME,
25
26
  DEFAULT_NAME_EXTENSION: () => DEFAULT_NAME_EXTENSION,
27
+ DEFAULT_OUTPUT_DIR: () => DEFAULT_OUTPUT_DIR,
28
+ FALLBACK_OUTPUT_DIR: () => FALLBACK_OUTPUT_DIR,
26
29
  emitCss: () => emitCss,
27
30
  formatContextsModule: () => formatContextsModule,
28
31
  formatFontsModule: () => formatFontsModule,
29
32
  generateVariablesCss: () => generateVariablesCss,
30
33
  getContexts: () => getContexts,
31
34
  getFonts: () => getFonts,
35
+ initConfig: () => initConfig,
36
+ readPackageScripts: () => readPackageScripts,
32
37
  resolveCssOptions: () => resolveCssOptions,
33
38
  resolveOptions: () => resolveOptions,
34
39
  tokensToCss: () => tokensToCss
35
40
  });
36
41
  module.exports = __toCommonJS(node_exports);
37
- var import_promises = require("fs/promises");
38
- var import_node_path2 = require("path");
42
+ var import_promises2 = require("fs/promises");
43
+ var import_node_path3 = require("path");
39
44
 
40
45
  // src/config.ts
41
46
  var import_node_path = require("path");
@@ -47,8 +52,14 @@ var DEFAULT_CONTEXTS = {
47
52
  light: ".light"
48
53
  };
49
54
  var DEFAULT_INPUT = "design-tokens.json";
50
- var DEFAULT_VARIABLES_OUTPUT = "variables.css";
51
- var DEFAULT_NAME_EXTENSION = "com.tokendesigner.app";
55
+ var DEFAULT_OUTPUT_DIR = "src/bezel";
56
+ var FALLBACK_OUTPUT_DIR = "bezel";
57
+ var VARIABLES_FILE = "variables.css";
58
+ var CONTEXTS_FILE = "contexts.ts";
59
+ var FONTS_FILE = "fonts.ts";
60
+ var DEFAULT_VARIABLES_OUTPUT = `${DEFAULT_OUTPUT_DIR}/${VARIABLES_FILE}`;
61
+ var DEFAULT_NAME_EXTENSION = "com.bezel.app";
62
+ var DEFAULT_CONFIG_FILE = "bezel.json";
52
63
 
53
64
  // src/options.ts
54
65
  function resolveCssOptions(options = {}) {
@@ -442,12 +453,55 @@ function tokensToCss(tokens, options = {}) {
442
453
  return emitCss(tokens, resolveCssOptions(options));
443
454
  }
444
455
 
456
+ // src/init.ts
457
+ var import_node_fs = require("fs");
458
+ var import_promises = require("fs/promises");
459
+ var import_node_path2 = require("path");
460
+ var joinPath = (dir, file) => dir === "" ? file : `${dir.replace(/\/+$/, "")}/${file}`;
461
+ async function initConfig(options = {}) {
462
+ const cwd = options.cwd ?? process.cwd();
463
+ const toAbs = (p) => (0, import_node_path2.isAbsolute)(p) ? p : (0, import_node_path2.resolve)(cwd, p);
464
+ const configPath = toAbs(DEFAULT_CONFIG_FILE);
465
+ const hasTokensFile = (0, import_node_fs.existsSync)(toAbs(DEFAULT_INPUT));
466
+ const isTypeScript = (0, import_node_fs.existsSync)(toAbs("tsconfig.json"));
467
+ const hasSrc = (0, import_node_fs.existsSync)(toAbs("src"));
468
+ const outputDir = options.outputDir ?? (hasSrc ? DEFAULT_OUTPUT_DIR : FALLBACK_OUTPUT_DIR);
469
+ const wantsContexts = options.contextsOutput !== void 0 || (options.contexts ?? isTypeScript);
470
+ const wantsFonts = options.fontsOutput !== void 0 || (options.fonts ?? isTypeScript);
471
+ const config = {
472
+ variablesOutput: options.variablesOutput ?? joinPath(outputDir, VARIABLES_FILE)
473
+ };
474
+ if (wantsContexts) {
475
+ config.contextsOutput = options.contextsOutput ?? joinPath(outputDir, CONTEXTS_FILE);
476
+ }
477
+ if (wantsFonts) {
478
+ config.fontsOutput = options.fontsOutput ?? joinPath(outputDir, FONTS_FILE);
479
+ }
480
+ if (options.colorFormat) config.colorFormat = options.colorFormat;
481
+ if (options.dimensionUnit) config.dimensionUnit = options.dimensionUnit;
482
+ if ((0, import_node_fs.existsSync)(configPath) && !options.force) {
483
+ return { configPath, config, written: false, hasTokensFile, isTypeScript };
484
+ }
485
+ await (0, import_promises.writeFile)(configPath, `${JSON.stringify(config, null, 2)}
486
+ `, "utf8");
487
+ return { configPath, config, written: true, hasTokensFile, isTypeScript };
488
+ }
489
+ async function readPackageScripts(cwd) {
490
+ try {
491
+ const raw = await (0, import_promises.readFile)((0, import_node_path2.resolve)(cwd, "package.json"), "utf8");
492
+ const parsed = JSON.parse(raw);
493
+ return parsed.scripts ?? {};
494
+ } catch {
495
+ return {};
496
+ }
497
+ }
498
+
445
499
  // src/node.ts
446
500
  async function generateVariablesCss(options = {}) {
447
501
  const resolved = resolveOptions(options);
448
502
  let raw;
449
503
  try {
450
- raw = await (0, import_promises.readFile)(resolved.inputPath, "utf8");
504
+ raw = await (0, import_promises2.readFile)(resolved.inputPath, "utf8");
451
505
  } catch (err) {
452
506
  throw new Error(
453
507
  `bezel: could not read tokens file at "${resolved.inputPath}". A "design-tokens.json" file must exist at the project root.
@@ -463,17 +517,17 @@ ${err.message}`);
463
517
  }
464
518
  const css = emitCss(tokens, resolved);
465
519
  if (resolved.write) {
466
- await (0, import_promises.mkdir)((0, import_node_path2.dirname)(resolved.variablesOutputPath), { recursive: true });
467
- await (0, import_promises.writeFile)(resolved.variablesOutputPath, css, "utf8");
520
+ await (0, import_promises2.mkdir)((0, import_node_path3.dirname)(resolved.variablesOutputPath), { recursive: true });
521
+ await (0, import_promises2.writeFile)(resolved.variablesOutputPath, css, "utf8");
468
522
  if (resolved.contextsOutput) {
469
523
  const contextsModule = formatContextsModule(getContexts(tokens));
470
- await (0, import_promises.mkdir)((0, import_node_path2.dirname)(resolved.contextsOutput), { recursive: true });
471
- await (0, import_promises.writeFile)(resolved.contextsOutput, contextsModule, "utf8");
524
+ await (0, import_promises2.mkdir)((0, import_node_path3.dirname)(resolved.contextsOutput), { recursive: true });
525
+ await (0, import_promises2.writeFile)(resolved.contextsOutput, contextsModule, "utf8");
472
526
  }
473
527
  if (resolved.fontsOutput) {
474
528
  const fontsModule = formatFontsModule(getFonts(tokens));
475
- await (0, import_promises.mkdir)((0, import_node_path2.dirname)(resolved.fontsOutput), { recursive: true });
476
- await (0, import_promises.writeFile)(resolved.fontsOutput, fontsModule, "utf8");
529
+ await (0, import_promises2.mkdir)((0, import_node_path3.dirname)(resolved.fontsOutput), { recursive: true });
530
+ await (0, import_promises2.writeFile)(resolved.fontsOutput, fontsModule, "utf8");
477
531
  }
478
532
  if (resolved.gitignore) {
479
533
  await updateGitignore(resolved);
@@ -482,7 +536,7 @@ ${err.message}`);
482
536
  return css;
483
537
  }
484
538
  async function updateGitignore(resolved) {
485
- const dir = (0, import_node_path2.dirname)(resolved.gitignorePath);
539
+ const dir = (0, import_node_path3.dirname)(resolved.gitignorePath);
486
540
  const outputs = [
487
541
  resolved.variablesOutputPath,
488
542
  resolved.contextsOutput,
@@ -490,7 +544,7 @@ async function updateGitignore(resolved) {
490
544
  ].filter((p) => p !== null);
491
545
  const entries = [];
492
546
  for (const output of outputs) {
493
- const rel = (0, import_node_path2.relative)(dir, output);
547
+ const rel = (0, import_node_path3.relative)(dir, output);
494
548
  if (rel === "" || rel.startsWith("..")) {
495
549
  process.stderr.write(
496
550
  `bezel: skipping .gitignore entry for "${output}" \u2014 outside ${resolved.gitignorePath}
@@ -498,31 +552,36 @@ async function updateGitignore(resolved) {
498
552
  );
499
553
  continue;
500
554
  }
501
- entries.push(`/${rel.split(import_node_path2.sep).join("/")}`);
555
+ entries.push(`/${rel.split(import_node_path3.sep).join("/")}`);
502
556
  }
503
557
  if (entries.length === 0) return;
504
558
  let existing = "";
505
559
  try {
506
- existing = await (0, import_promises.readFile)(resolved.gitignorePath, "utf8");
560
+ existing = await (0, import_promises2.readFile)(resolved.gitignorePath, "utf8");
507
561
  } catch {
508
562
  }
509
563
  const next = mergeGitignore(existing, entries);
510
564
  if (next !== existing) {
511
- await (0, import_promises.mkdir)(dir, { recursive: true });
512
- await (0, import_promises.writeFile)(resolved.gitignorePath, next, "utf8");
565
+ await (0, import_promises2.mkdir)(dir, { recursive: true });
566
+ await (0, import_promises2.writeFile)(resolved.gitignorePath, next, "utf8");
513
567
  }
514
568
  }
515
569
  // Annotate the CommonJS export names for ESM import in node:
516
570
  0 && (module.exports = {
571
+ DEFAULT_CONFIG_FILE,
517
572
  DEFAULT_CONTEXTS,
518
573
  DEFAULT_CONTEXT_NAME,
519
574
  DEFAULT_NAME_EXTENSION,
575
+ DEFAULT_OUTPUT_DIR,
576
+ FALLBACK_OUTPUT_DIR,
520
577
  emitCss,
521
578
  formatContextsModule,
522
579
  formatFontsModule,
523
580
  generateVariablesCss,
524
581
  getContexts,
525
582
  getFonts,
583
+ initConfig,
584
+ readPackageScripts,
526
585
  resolveCssOptions,
527
586
  resolveOptions,
528
587
  tokensToCss