basalt-ui 1.2.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "basalt-ui",
3
- "version": "1.2.0",
3
+ "version": "1.4.0",
4
4
  "description": "Opinionated framework for Mantine-based React apps — theme, app shell, visx charts, toolchain presets",
5
5
  "keywords": [
6
6
  "charts",
@@ -117,6 +117,7 @@
117
117
  "import": "./dist/connectivity/index.js"
118
118
  },
119
119
  "./styles.css": "./dist/styles.css",
120
+ "./tokens.css": "./dist/tokens.css",
120
121
  "./configs/*": "./configs/*",
121
122
  "./llms.txt": "./llms.txt"
122
123
  },
@@ -125,7 +126,7 @@
125
126
  "provenance": true
126
127
  },
127
128
  "scripts": {
128
- "build": "tsup && tsc --emitDeclarationOnly --declarationMap && bun scripts/copy-assets.mjs && bun scripts/fix-esm-extensions.mjs",
129
+ "build": "tsup && tsc --emitDeclarationOnly --declarationMap && bun scripts/copy-assets.mjs && bun scripts/gen-tokens-css.mjs && bun scripts/fix-esm-extensions.mjs",
129
130
  "typecheck": "tsc --noEmit",
130
131
  "pack-test": "bash scripts/pack-test.sh",
131
132
  "prepack": "bun run build",
@@ -195,9 +196,15 @@
195
196
  "vite-plugin-pwa": "^1.3.0"
196
197
  },
197
198
  "peerDependenciesMeta": {
199
+ "@mantine/core": {
200
+ "optional": true
201
+ },
198
202
  "@mantine/form": {
199
203
  "optional": true
200
204
  },
205
+ "@mantine/hooks": {
206
+ "optional": true
207
+ },
201
208
  "@shikijs/langs": {
202
209
  "optional": true
203
210
  },
@@ -216,6 +223,9 @@
216
223
  "@mantine/spotlight": {
217
224
  "optional": true
218
225
  },
226
+ "@tanstack/react-query": {
227
+ "optional": true
228
+ },
219
229
  "@tanstack/react-query-devtools": {
220
230
  "optional": true
221
231
  },
@@ -234,6 +244,12 @@
234
244
  "beautiful-mermaid": {
235
245
  "optional": true
236
246
  },
247
+ "react": {
248
+ "optional": true
249
+ },
250
+ "react-dom": {
251
+ "optional": true
252
+ },
237
253
  "react-markdown": {
238
254
  "optional": true
239
255
  },
@@ -684,3 +684,61 @@ describe('check-theme comment skipping', () => {
684
684
  expect(err).toContain('raw-visx-axis')
685
685
  })
686
686
  })
687
+
688
+ describe('severity — warnings report, errors fail', () => {
689
+ const RAW_HEX = `export const C = () => <div style={{ color: '#ff0000' }} />`
690
+
691
+ it('exits 1 on an error kind (the default)', () => {
692
+ fixture(RAW_HEX)
693
+ const { code, err } = run()
694
+ expect(code).toBe(1)
695
+ expect(err).toContain('✖ Theme guard')
696
+ expect(err).toContain('raw-hex')
697
+ })
698
+
699
+ it('exits 0 when the only findings are warnings, and still prints them', () => {
700
+ // The whole point of the grace minor: the consumer takes the upgrade on a green build and
701
+ // schedules the fix, rather than the release scheduling it for them. This case is the OTHER
702
+ // origin of a warning — a consumer override — so the heading must not promise promotion.
703
+ fixture(RAW_HEX, { roots: ['src'], severity: { 'raw-hex': 'warn' } })
704
+ const { code, err } = run()
705
+ expect(code).toBe(0)
706
+ expect(err).toContain('⚠ Theme guard')
707
+ expect(err).toContain('reported, not fatal')
708
+ expect(err).toContain('raw-hex')
709
+ expect(err).not.toContain('✖ Theme guard')
710
+ })
711
+
712
+ it('still fails when errors accompany warnings, and reports both blocks', () => {
713
+ fixture(`export const C = () => <div style={{ color: '#ff0000' }} p={18} />`, {
714
+ roots: ['src'],
715
+ spacingSteps: [18],
716
+ severity: { 'raw-hex': 'warn' },
717
+ })
718
+ const { code, err } = run()
719
+ expect(code).toBe(1)
720
+ expect(err).toContain('⚠ Theme guard')
721
+ expect(err).toContain('✖ Theme guard')
722
+ // Warnings first — "what will break later" is the less urgent read.
723
+ expect(err.indexOf('⚠ Theme guard')).toBeLessThan(err.indexOf('✖ Theme guard'))
724
+ })
725
+
726
+ it('ignores an unrecognized severity value instead of silently unguarding the kind', () => {
727
+ // The one config typo that would REMOVE enforcement: 'warning' matches neither bucket, so the
728
+ // finding would vanish and the command would exit 0 on a tree that is not clean.
729
+ fixture(RAW_HEX, { roots: ['src'], severity: { 'raw-hex': 'warning' } })
730
+ const { code, err } = run()
731
+ expect(code).toBe(1)
732
+ expect(err).toContain("not 'warn' or 'error'")
733
+ expect(err).toContain('✖ Theme guard')
734
+ expect(err).toContain('raw-hex')
735
+ })
736
+
737
+ it('ignores a severity block that is not an object', () => {
738
+ fixture(RAW_HEX, { roots: ['src'], severity: 'warn' })
739
+ const { code, err } = run()
740
+ expect(code).toBe(1)
741
+ expect(err).toContain('basalt.severity is not an object')
742
+ expect(err).toContain('✖ Theme guard')
743
+ })
744
+ })
package/src/cli/index.ts CHANGED
@@ -33,10 +33,11 @@ import { dirname, isAbsolute, relative, resolve } from 'node:path'
33
33
  import { fileURLToPath } from 'node:url'
34
34
 
35
35
  import { checkSource, DEFAULT_GUARD_CONFIG, GUARD_RULES } from '../guard'
36
- import type { Finding, GuardConfig, GuardKind } from '../guard'
36
+ import type { Finding, GuardConfig, GuardKind, GuardSeverity } from '../guard'
37
37
  import { evaluateGuardHook } from '../guard/guard-hook'
38
38
  import { RULE_NAMES, SKILL_NAMES, SURFACES, TOKEN_LAYER_BOUNDARY_SURFACES } from '../surfaces'
39
39
  import type { DoctrineSpec, SurfaceSpec } from '../surfaces'
40
+ import { buildPaletteCss, deriveSpacing } from '../tokens'
40
41
 
41
42
  /** Shape of the optional `"basalt"` key in a consumer's package.json. */
42
43
  export type BasaltConfig = {
@@ -46,6 +47,9 @@ export type BasaltConfig = {
46
47
  exempt?: string[]
47
48
  /** Named spacing-scale steps (px) flagged when used as a raw spacing prop. Default: 10/12/16/20/32. */
48
49
  spacingSteps?: number[]
50
+ /** Per-kind severity override — `'warn'` reports without failing, `'error'` fails the build.
51
+ * See `GuardSeverity` in ../guard/types for the grace-minor doctrine behind it. */
52
+ severity?: Partial<Record<GuardKind, GuardSeverity>>
49
53
  /** Off-identity Mantine accent families forbidden as chrome accents. Default: argo's set. */
50
54
  forbiddenAccents?: string[]
51
55
  /** Earned accent hue recorded in DESIGN.md `{{ACCENT_HUE}}`. Default: `blue`. */
@@ -206,12 +210,46 @@ const SKIP = /\.gen\.ts$|\.test\.[tj]sx?$|\.d\.ts$/
206
210
  /** Filenames that look like they ARE the palette source, for the check-theme escape-hatch hint. */
207
211
  const SERIES_MODULE_HINT_RE = /(series|palette)\.tsx?$/i
208
212
 
213
+ const SEVERITY_VALUES: readonly string[] = ['warn', 'error']
214
+
215
+ /**
216
+ * Drop `basalt.severity` entries whose value is not `'warn'` / `'error'`, loudly.
217
+ *
218
+ * This is the one config field where a typo REMOVES enforcement rather than failing: package.json
219
+ * is untyped at runtime, and `"warning"` would stamp findings with a value matching neither the
220
+ * error bucket (which fails the build) nor the warn bucket (which prints them) — the kind would
221
+ * vanish and `check-theme` would exit 0 as if the tree were clean. Dropping the entry falls the
222
+ * kind back to its default, so the failure direction of a typo is "stricter than you meant, and
223
+ * told about it" instead of "silently unguarded".
224
+ */
225
+ function sanitizeSeverity(cfg: BasaltConfig): BasaltConfig {
226
+ const raw: unknown = cfg.severity
227
+ if (raw === undefined) return cfg
228
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {
229
+ console.error('⚠ basalt.severity is not an object — ignoring it; every kind keeps its default.')
230
+ const { severity: _dropped, ...rest } = cfg
231
+ return rest
232
+ }
233
+ const kept: Record<string, GuardSeverity> = {}
234
+ for (const [kind, value] of Object.entries(raw)) {
235
+ if (typeof value === 'string' && SEVERITY_VALUES.includes(value)) {
236
+ kept[kind] = value as GuardSeverity
237
+ continue
238
+ }
239
+ console.error(
240
+ `⚠ basalt.severity["${kind}"] is ${JSON.stringify(value)}, not 'warn' or 'error' — ` +
241
+ 'ignoring it; that kind keeps its default severity.',
242
+ )
243
+ }
244
+ return { ...cfg, severity: kept as Partial<Record<GuardKind, GuardSeverity>> }
245
+ }
246
+
209
247
  function readBasaltConfig(cwd: string): BasaltConfig {
210
248
  try {
211
249
  const pkg = JSON.parse(readFileSync(resolve(cwd, 'package.json'), 'utf8')) as {
212
250
  basalt?: BasaltConfig
213
251
  }
214
- return pkg.basalt ?? {}
252
+ return sanitizeSeverity(pkg.basalt ?? {})
215
253
  } catch {
216
254
  return {}
217
255
  }
@@ -324,6 +362,7 @@ export function checkTheme(cwd: string = process.cwd()): number {
324
362
  sub16InputFont: cfg.sub16InputFont ?? DEFAULT_GUARD_CONFIG.sub16InputFont,
325
363
  allowComment: 'theme-allow',
326
364
  exemptRules: cfg.exemptRules ?? DEFAULT_GUARD_CONFIG.exemptRules,
365
+ severity: cfg.severity ?? DEFAULT_GUARD_CONFIG.severity,
327
366
  }
328
367
 
329
368
  const findings: Finding[] = []
@@ -364,20 +403,43 @@ export function checkTheme(cwd: string = process.cwd()): number {
364
403
  return 0
365
404
  }
366
405
 
367
- const byFile = new Map<string, Finding[]>()
368
- for (const f of findings) {
369
- const list = byFile.get(f.relPath) ?? []
370
- list.push(f)
371
- byFile.set(f.relPath, list)
372
- }
373
- console.error(`✖ Theme guard: ${findings.length} off-palette / off-identity violation(s)\n`)
374
- for (const [file, vs] of [...byFile].toSorted()) {
375
- console.error(file)
376
- for (const v of vs.toSorted((a, b) => a.line - b.line)) {
377
- console.error(` ${String(v.line).padStart(4)} ${v.kind.padEnd(22)} ${v.token}`)
406
+ // Errors and warnings are reported as two separate blocks, not one list with a column: a
407
+ // consumer scanning the output needs "what breaks my build" answered before "what will later".
408
+ const errors = findings.filter((f) => f.severity === 'error')
409
+ const warnings = findings.filter((f) => f.severity === 'warn')
410
+
411
+ const report = (group: Finding[], heading: string): void => {
412
+ const byFile = new Map<string, Finding[]>()
413
+ for (const f of group) {
414
+ const list = byFile.get(f.relPath) ?? []
415
+ list.push(f)
416
+ byFile.set(f.relPath, list)
417
+ }
418
+ console.error(heading)
419
+ for (const [file, vs] of [...byFile].toSorted()) {
420
+ console.error(file)
421
+ for (const v of vs.toSorted((a, b) => a.line - b.line)) {
422
+ console.error(` ${String(v.line).padStart(4)} ${v.kind.padEnd(22)} ${v.token}`)
423
+ }
424
+ console.error('')
378
425
  }
379
- console.error('')
380
426
  }
427
+
428
+ if (warnings.length > 0) {
429
+ report(
430
+ warnings,
431
+ // Deliberately neutral about WHY a kind is a warning. Two origins reach this block — a kind
432
+ // in its grace minor, and a consumer's own `basalt.severity` override — and the finding
433
+ // doesn't carry which. Promising promotion next minor would be wrong for the second.
434
+ `⚠ Theme guard: ${warnings.length} warning(s) — reported, not fatal. A kind warns while it ` +
435
+ 'is in its grace minor, or because `basalt.severity` turned it down; fix on your own ' +
436
+ 'schedule.\n',
437
+ )
438
+ }
439
+ if (errors.length > 0) {
440
+ report(errors, `✖ Theme guard: ${errors.length} off-palette / off-identity violation(s)\n`)
441
+ }
442
+
381
443
  const presentKinds = new Set(findings.map((f) => f.kind))
382
444
  const explanations = (Object.keys(GUARD_KIND_EXPLANATIONS) as GuardKind[])
383
445
  .filter((kind) => presentKinds.has(kind))
@@ -391,13 +453,15 @@ export function checkTheme(cwd: string = process.cwd()): number {
391
453
 
392
454
  // A violation in a file that looks like the palette source itself is likely intentional — point
393
455
  // at the exempt escape hatch instead of leaving the author to search for it.
394
- if ([...byFile.keys()].some((f) => SERIES_MODULE_HINT_RE.test(f))) {
456
+ if (findings.some((f) => SERIES_MODULE_HINT_RE.test(f.relPath))) {
395
457
  console.error(
396
458
  'Hint: if a flagged file IS your palette/series source, exempt it via ' +
397
459
  '"basalt": { "exempt": ["<path>"] } in package.json.',
398
460
  )
399
461
  }
400
- return 1
462
+ // Warnings alone pass. That is the whole point of the grace minor: a consumer takes the upgrade
463
+ // on a green build and schedules the fix, instead of the release scheduling it for them.
464
+ return errors.length > 0 ? 1 : 0
401
465
  }
402
466
 
403
467
  // ──────────────────────────────────────────────────────────────────────────────
@@ -742,6 +806,19 @@ type Manifest = {
742
806
  basaltVersion?: string
743
807
  /** dest path → sha256 of the managed unit (file bytes, block body, or stanza) at last write. */
744
808
  files: Record<string, string>
809
+ /**
810
+ * The resolved level-0 spacing scale (`xs`..`xl`, px) at last write — `doctor`'s second
811
+ * reconciliation axis, and the only one that reports a change in RENDERED OUTPUT rather than in
812
+ * placed files.
813
+ *
814
+ * A retune of the spacing bases moves every surface in every consumer calling
815
+ * `createBasaltTheme()` bare. basalt-ui bans majors by design, so the changelog is the only
816
+ * channel that carries that, and a one-line `feat:` subject cannot convey blast radius: the
817
+ * 1.2.0 retune shipped as "tighten the sidebar, open up components" and went unverified in
818
+ * production for a day because nothing said "every padding moved". Recording the scale makes the
819
+ * move mechanically visible on the next `doctor` run instead of depending on a subject line.
820
+ */
821
+ spacingScale?: Record<string, number>
745
822
  }
746
823
 
747
824
  function readManifest(cwd: string): Manifest {
@@ -751,6 +828,20 @@ function readManifest(cwd: string): Manifest {
751
828
  const parsed = JSON.parse(raw) as Partial<Manifest>
752
829
  const manifest: Manifest = { version: 1, files: parsed.files ?? {} }
753
830
  if (typeof parsed.basaltVersion === 'string') manifest.basaltVersion = parsed.basaltVersion
831
+ // `typeof null === 'object'` and so is an array — a hand-edited manifest carrying either would
832
+ // reach doctor and be indexed as a record. Values must be numbers too: a `"4"` would never
833
+ // `===` the derived `4`, so doctor would report every step as moved. Anything else is treated
834
+ // as unrecorded, which reads as "run sync" rather than as a garbled diff.
835
+ const scale: unknown = parsed.spacingScale
836
+ if (
837
+ scale !== null &&
838
+ scale !== undefined &&
839
+ typeof scale === 'object' &&
840
+ !Array.isArray(scale) &&
841
+ Object.values(scale).every((v) => typeof v === 'number')
842
+ ) {
843
+ manifest.spacingScale = scale as Record<string, number>
844
+ }
754
845
  return manifest
755
846
  } catch {
756
847
  return { version: 1, files: {} }
@@ -972,6 +1063,7 @@ export function init(cwd: string = process.cwd(), scaffoldFlags: ScaffoldFlags =
972
1063
  }
973
1064
 
974
1065
  manifest.basaltVersion = ctx.vars.BASALT_VERSION
1066
+ manifest.spacingScale = { ...deriveSpacing(0).scale }
975
1067
  writeFileEnsuringDir(resolve(cwd, MANIFEST_PATH), `${JSON.stringify(manifest, null, 2)}\n`)
976
1068
 
977
1069
  console.log(`basalt-ui init: ${written} written, ${skipped} kept, manifest at ${MANIFEST_PATH}`)
@@ -1094,6 +1186,7 @@ export function sync(opts: SyncOptions = {}, cwd: string = process.cwd()): numbe
1094
1186
  }
1095
1187
 
1096
1188
  manifest.basaltVersion = ctx.vars.BASALT_VERSION
1189
+ manifest.spacingScale = { ...deriveSpacing(0).scale }
1097
1190
  writeFileEnsuringDir(resolve(cwd, MANIFEST_PATH), `${JSON.stringify(manifest, null, 2)}\n`)
1098
1191
 
1099
1192
  console.log(
@@ -1323,9 +1416,11 @@ type DoctorResult = {
1323
1416
  * 2. The installed node_modules/basalt-ui version matches the manifest's basaltVersion
1324
1417
  * (a mismatch means the package was upgraded but `sync` never ran — the placed doctrine is
1325
1418
  * stale).
1326
- * 3. The running CLI's own version matches the installed basalt-ui (catches a stale
1419
+ * 3. The spacing scale still matches the one stamped into the manifest at the last init/sync
1420
+ * (skipped when this CLI is demonstrably not the installed package — see the check).
1421
+ * 4. The running CLI's own version matches the installed basalt-ui (catches a stale
1327
1422
  * `bunx basalt-ui` npm fetch; best-effort, skipped if node_modules is absent).
1328
- * 4. `basaltAppPlugin`'s (basalt-ui/vite) default icon filenames exist under public/ (only when
1423
+ * 5. `basaltAppPlugin`'s (basalt-ui/vite) default icon filenames exist under public/ (only when
1329
1424
  * a public/ dir exists at all — skipped otherwise).
1330
1425
  *
1331
1426
  * Returns the exit code: 0 = all good, 1 = one or more hard failures.
@@ -1385,11 +1480,57 @@ export function doctor(cwd: string = process.cwd()): number {
1385
1480
  }
1386
1481
  }
1387
1482
 
1388
- // ── Warn check 3: running CLI version matches the consumer's installed basalt-ui ────
1483
+ const cliVersion = readFrameworkVersion(packageRoot())
1484
+
1485
+ // ── Warn check 3: the spacing scale has not moved under the app ────────────
1486
+ // The only check here that reports a change in RENDERED OUTPUT rather than in placed files. A
1487
+ // retune of the spacing bases moves every surface in an app calling `createBasaltTheme()` bare,
1488
+ // and majors are banned by design, so nothing in the version number says so — 1.2.0's retune
1489
+ // shipped under "tighten the sidebar, open up components" and sat unverified in production for a
1490
+ // day. Diffing the current scale against what last synced makes that move something a consumer
1491
+ // is told rather than something they have to notice.
1492
+ //
1493
+ // The scale that matters is the INSTALLED package's — that is what the app renders with — but
1494
+ // `deriveSpacing` here is the RUNNING CLI's, which a stale `bunx basalt-ui` fetch makes a
1495
+ // different package. Rather than load the installed tokens entry (async, and doctor is sync),
1496
+ // the comparison is skipped whenever the two versions are known to disagree: a false "matches"
1497
+ // is worse than no answer. Check 4 below names that disagreement, so this stays a neutral note.
1498
+ const cliIsTheInstall = installedVersion === null || installedVersion === cliVersion
1499
+ if (manifestExists && !cliIsTheInstall) {
1500
+ pass(
1501
+ `spacing scale not compared — this CLI (${cliVersion}) is not the installed basalt-ui ` +
1502
+ `(${installedVersion}), so its scale is not the one the app renders with`,
1503
+ )
1504
+ } else if (manifestExists) {
1505
+ const recorded = readManifest(cwd).spacingScale
1506
+ const current = deriveSpacing(0).scale as Record<string, number>
1507
+ if (recorded === undefined) {
1508
+ // Silent for a manifest written before this field existed — the version check above already
1509
+ // says "run sync", and a second warning for the same cause is noise.
1510
+ pass('spacing scale not yet recorded — `basalt-ui sync` will stamp it')
1511
+ } else {
1512
+ // Over the UNION of both key sets: a step the scale gained since the last sync is a move the
1513
+ // app feels, and so is one it lost. Iterating only `current` would miss the second.
1514
+ const steps = [...new Set([...Object.keys(current), ...Object.keys(recorded)])].toSorted()
1515
+ const moved = steps
1516
+ .filter((step) => recorded[step] !== current[step])
1517
+ .map((step) => `${step} ${recorded[step] ?? '(none)'}→${current[step] ?? '(removed)'}`)
1518
+ if (moved.length > 0) {
1519
+ warn(
1520
+ `the spacing scale moved since the last sync (${moved.join(', ')}) — every surface in an ` +
1521
+ 'app calling createBasaltTheme() bare shifts with it. Review the app visually, then run ' +
1522
+ '`basalt-ui sync` to record the new scale.',
1523
+ )
1524
+ } else {
1525
+ pass('spacing scale matches the last sync')
1526
+ }
1527
+ }
1528
+ }
1529
+
1530
+ // ── Warn check 4: running CLI version matches the consumer's installed basalt-ui ────
1389
1531
  // Catches the failure mode where bunx fetches a stale published package instead of the local
1390
1532
  // install — the CLI that ran doctor and the package resolved from the consumer's node_modules
1391
1533
  // silently disagree.
1392
- const cliVersion = readFrameworkVersion(packageRoot())
1393
1534
  if (installedVersion !== null) {
1394
1535
  if (installedVersion !== cliVersion) {
1395
1536
  warn(
@@ -1402,7 +1543,7 @@ export function doctor(cwd: string = process.cwd()): number {
1402
1543
  }
1403
1544
  }
1404
1545
 
1405
- // ── Warn check 4: basaltAppPlugin's default icon files exist in public/ ────
1546
+ // ── Warn check 5: basaltAppPlugin's default icon files exist in public/ ────
1406
1547
  // basalt-ui/vite's basaltAppPlugin (head/manifest metadata) references these filenames by
1407
1548
  // default (the realfavicongenerator convention). Only runs when a public/ dir exists at all —
1408
1549
  // apps that don't use the plugin, or don't use Vite's public-dir convention, get no false
@@ -1571,6 +1712,73 @@ export function info(flags: string[]): number {
1571
1712
  return 0
1572
1713
  }
1573
1714
 
1715
+ /** Read the value that follows a `--flag` in an argv slice; `undefined` when absent or terminal. */
1716
+ function flagValue(flags: string[], name: string): string | undefined {
1717
+ const i = flags.indexOf(name)
1718
+ if (i === -1) return undefined
1719
+ const value = flags[i + 1]
1720
+ return value === undefined || value.startsWith('--') ? undefined : value
1721
+ }
1722
+
1723
+ /**
1724
+ * tokens:css — emit the `--vx-*` stylesheet, optionally retargeted.
1725
+ *
1726
+ * The escape hatch from installing anything: a static site runs this once (`bunx basalt-ui
1727
+ * tokens:css --selector-attribute data-theme --out src/tokens.css`) and consumes basalt's token
1728
+ * system as plain CSS, with no package in its dependency tree at all. `basalt-ui/tokens.css` is the
1729
+ * same artifact for a consumer that does install; this command exists for the ones that shouldn't
1730
+ * have to just to change a selector.
1731
+ *
1732
+ * It parses flags and calls `buildPaletteCss` — nothing else. No emission logic, no post-processing
1733
+ * of the returned string: the CLI and the API must not be able to disagree about what basalt's
1734
+ * tokens are.
1735
+ */
1736
+ export function tokensCss(flags: string[], cwd: string = process.cwd()): number {
1737
+ const attribute = flagValue(flags, '--selector-attribute')
1738
+ const darkValue = flagValue(flags, '--dark-value')
1739
+ const lightValue = flagValue(flags, '--light-value')
1740
+ const defaultScheme = flagValue(flags, '--default-scheme')
1741
+
1742
+ const only = flagValue(flags, '--only')
1743
+
1744
+ if (defaultScheme !== undefined && !['dark', 'light', 'none'].includes(defaultScheme)) {
1745
+ console.error(
1746
+ `tokens:css: --default-scheme must be dark, light or none (got '${defaultScheme}')`,
1747
+ )
1748
+ return 1
1749
+ }
1750
+ if (only !== undefined && !['core', 'all'].includes(only)) {
1751
+ console.error(`tokens:css: --only must be core or all (got '${only}')`)
1752
+ return 1
1753
+ }
1754
+
1755
+ const scheme = {
1756
+ ...(attribute === undefined ? {} : { attribute }),
1757
+ ...(darkValue === undefined ? {} : { darkValue }),
1758
+ ...(lightValue === undefined ? {} : { lightValue }),
1759
+ }
1760
+
1761
+ const css = buildPaletteCss({
1762
+ ...(Object.keys(scheme).length === 0 ? {} : { scheme }),
1763
+ ...(defaultScheme === undefined
1764
+ ? {}
1765
+ : { defaultScheme: defaultScheme as 'dark' | 'light' | 'none' }),
1766
+ ...(flags.includes('--media-fallback') ? { mediaFallback: true } : {}),
1767
+ ...(only === undefined ? {} : { only: only as 'core' | 'all' }),
1768
+ })
1769
+
1770
+ const out = flagValue(flags, '--out')
1771
+ if (out === undefined) {
1772
+ process.stdout.write(`${css}\n`)
1773
+ return 0
1774
+ }
1775
+ const target = isAbsolute(out) ? out : resolve(cwd, out)
1776
+ mkdirSync(dirname(target), { recursive: true })
1777
+ writeFileSync(target, css)
1778
+ console.log(`wrote ${css.split('\n').length} lines → ${relative(cwd, target) || target}`)
1779
+ return 0
1780
+ }
1781
+
1574
1782
  /**
1575
1783
  * guard-hook — PreToolUse stdin adapter.
1576
1784
  *
@@ -1628,6 +1836,7 @@ export async function guardHook(cwd: string = process.cwd()): Promise<number> {
1628
1836
  sub16InputFont: cfg.sub16InputFont ?? DEFAULT_GUARD_CONFIG.sub16InputFont,
1629
1837
  allowComment: 'theme-allow',
1630
1838
  exemptRules: cfg.exemptRules ?? DEFAULT_GUARD_CONFIG.exemptRules,
1839
+ severity: cfg.severity ?? DEFAULT_GUARD_CONFIG.severity,
1631
1840
  }
1632
1841
 
1633
1842
  // Honor the consumer's roots / exempt / skip config so the hook never blocks edits to exempted
@@ -1668,7 +1877,10 @@ export async function guardHook(cwd: string = process.cwd()): Promise<number> {
1668
1877
  /** The one usage string — printed by `basalt help` / `--help` / `-h` AND the unknown-command fallback. */
1669
1878
  const USAGE =
1670
1879
  'Usage: basalt-ui <init [--with-router] [--with-query] | sync [--force] [--check] | ' +
1671
- 'check-theme | check-coverage | info [--json] | doctor | guard-hook | help>\n\n' +
1880
+ 'check-theme | check-coverage | info [--json] | doctor | guard-hook | tokens:css | help>\n\n' +
1881
+ 'tokens:css [--out <path>] [--selector-attribute <attr>] [--dark-value <v>] [--light-value <v>]\n' +
1882
+ ' [--default-scheme <dark|light|none>] [--media-fallback] [--only <core|all>]\n' +
1883
+ ' Emit the --vx-* stylesheet (stdout unless --out). Defaults reproduce basalt-ui/tokens.css.\n\n' +
1672
1884
  'Every subcommand accepts --help / -h to print this message and exit without running.'
1673
1885
 
1674
1886
  /**
@@ -1712,6 +1924,8 @@ export function run(argv: string[], cwd: string = process.cwd()): number | Promi
1712
1924
  return doctor(cwd)
1713
1925
  case 'guard-hook':
1714
1926
  return guardHook(cwd)
1927
+ case 'tokens:css':
1928
+ return tokensCss(flags, cwd)
1715
1929
  default:
1716
1930
  console.error(USAGE)
1717
1931
  return 1
@@ -0,0 +1,90 @@
1
+ /**
2
+ * `basalt-ui tokens:css` — the install-free path to the token system.
3
+ *
4
+ * The contract these tests hold is that the command is a FLAG PARSER, nothing more: whatever it
5
+ * prints must be exactly what `buildPaletteCss` returns for the same options. If the CLI ever grows
6
+ * emission logic of its own, a consumer who ran `bunx basalt-ui tokens:css` and a consumer who
7
+ * imported `basalt-ui/tokens` would be looking at two different design systems.
8
+ */
9
+ import { afterEach, beforeEach, describe, expect, it } from 'bun:test'
10
+ import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs'
11
+ import { tmpdir } from 'node:os'
12
+ import { join, resolve } from 'node:path'
13
+
14
+ import { buildPaletteCss } from '../tokens'
15
+ import { run, tokensCss } from './index'
16
+
17
+ const FIXTURE = join(import.meta.dir, '..', '..', 'tests', 'fixtures', 'palette-default.css')
18
+
19
+ let dir: string
20
+
21
+ beforeEach(() => {
22
+ dir = mkdtempSync(resolve(tmpdir(), 'basalt-tokens-css-'))
23
+ writeFileSync(resolve(dir, 'package.json'), JSON.stringify({ name: 'fixture' }))
24
+ })
25
+
26
+ afterEach(() => {
27
+ rmSync(dir, { recursive: true, force: true })
28
+ })
29
+
30
+ /** Run the command with `--out`, returning the written file — stdout is awkward to capture here. */
31
+ function emit(flags: string[], out = 'out.css'): string {
32
+ const code = tokensCss([...flags, '--out', out], dir)
33
+ expect(code).toBe(0)
34
+ return readFileSync(resolve(dir, out), 'utf8')
35
+ }
36
+
37
+ describe('tokens:css', () => {
38
+ it('with no flags emits the shipped default, byte for byte', () => {
39
+ expect(emit([])).toBe(readFileSync(FIXTURE, 'utf8'))
40
+ })
41
+
42
+ it('forwards the selector flags to buildPaletteCss and adds nothing of its own', () => {
43
+ const flags = ['--selector-attribute', 'data-theme', '--default-scheme', 'light']
44
+ expect(emit(flags)).toBe(
45
+ buildPaletteCss({ scheme: { attribute: 'data-theme' }, defaultScheme: 'light' }),
46
+ )
47
+ })
48
+
49
+ it('forwards the scheme VALUES and the media fallback', () => {
50
+ const flags = ['--dark-value', 'night', '--light-value', 'day', '--media-fallback']
51
+ expect(emit(flags)).toBe(
52
+ buildPaletteCss({ scheme: { darkValue: 'night', lightValue: 'day' }, mediaFallback: true }),
53
+ )
54
+ })
55
+
56
+ it('forwards --only core', () => {
57
+ expect(emit(['--only', 'core'])).toBe(buildPaletteCss({ only: 'core' }))
58
+ })
59
+
60
+ it('rejects an unknown --only instead of silently emitting everything', () => {
61
+ expect(tokensCss(['--only', 'spacing', '--out', 'out.css'], dir)).toBe(1)
62
+ expect(existsSync(resolve(dir, 'out.css'))).toBe(false)
63
+ })
64
+
65
+ it('creates the parent directory of --out', () => {
66
+ const css = emit([], 'nested/deep/tokens.css')
67
+ expect(css.startsWith(':root {')).toBe(true)
68
+ })
69
+
70
+ it('rejects an unknown --default-scheme instead of silently defaulting', () => {
71
+ const code = tokensCss(['--default-scheme', 'sepia', '--out', 'out.css'], dir)
72
+ expect(code).toBe(1)
73
+ expect(existsSync(resolve(dir, 'out.css'))).toBe(false)
74
+ })
75
+
76
+ it('`--help` short-circuits before the command runs — no file written', () => {
77
+ const originalLog = console.log
78
+ let log = ''
79
+ console.log = (...args: unknown[]) => {
80
+ log += `${args.join(' ')}\n`
81
+ }
82
+ try {
83
+ expect(run(['tokens:css', '--out', 'out.css', '--help'], dir)).toBe(0)
84
+ } finally {
85
+ console.log = originalLog
86
+ }
87
+ expect(log).toContain('Usage: basalt')
88
+ expect(readdirSync(dir)).toEqual(['package.json'])
89
+ })
90
+ })