@eluan/theme-generator 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.
package/README.md CHANGED
@@ -2,6 +2,8 @@
2
2
 
3
3
  CLI and library that generates accessible, light + dark mode [Eluan](https://github.com/vasfio/eluan) theme token sets from one to three accent colors. Contrast is checked (and auto-corrected) against a configurable minimum ratio, so generated themes are WCAG-aware out of the box.
4
4
 
5
+ The programmatic entry point (`@eluan/theme-generator`) is pure color math with no Node built-ins, so it runs in the browser as well as in Node. Only the `eluan-theme` binary touches the filesystem.
6
+
5
7
  ## Install
6
8
 
7
9
  ```bash
@@ -47,13 +49,52 @@ The generator writes primitive + semantic token JSON, theme CSS, and a smoke-tes
47
49
  import { generateTheme } from "@eluan/theme-generator"
48
50
 
49
51
  const result = generateTheme({
50
- name: "ocean",
51
- accents: ["#FF4A2C"],
52
+ accents: ["#FF4A2C"], // 1–3 hex accents
53
+ themeName: "ocean",
52
54
  minContrast: 4.5,
55
+ neutralTintRatio: 0.04,
53
56
  })
57
+
58
+ result.css.theme // drop-in CSS for both modes, as a string
59
+ result.createThemeTokens // light-mode token map for createTheme()
60
+ result.report // markdown report: warnings, contrast corrections
61
+ ```
62
+
63
+ Lower-level helpers are exported too — `generateScale`, `buildPrimitives`, `buildSemanticMap`, `checkContrast`, `autoCorrect`, `compileThemeCSS`, `compileCreateThemeTokens`, and the `hexToOklch` / `oklchToHex` color utilities. See the exported TypeScript types for the full shape of `GeneratorResult`.
64
+
65
+ ## Use in the browser
66
+
67
+ The package entry pulls in nothing from Node — no `fs`, no `crypto` — so you can import it in a client component and generate a theme live from user input. A `check:browser` script bundles the built entry with `esbuild --platform=browser` in CI to keep it that way.
68
+
69
+ ```tsx
70
+ "use client"
71
+
72
+ import { generateTheme, compileCreateThemeTokens } from "@eluan/theme-generator"
73
+
74
+ function applyTheme(accent: string) {
75
+ const result = generateTheme({
76
+ accents: [accent],
77
+ themeName: "live",
78
+ minContrast: 4.5,
79
+ neutralTintRatio: 0.04,
80
+ })
81
+
82
+ // Option A — inject the compiled CSS (both modes, scoped to data-theme="live")
83
+ const style = document.createElement("style")
84
+ style.textContent = result.css.theme
85
+ document.head.append(style)
86
+ document.documentElement.dataset.theme = "live"
87
+
88
+ // Option B — take the raw token maps and hand them to createTheme()
89
+ const light = result.createThemeTokens
90
+ const dark = compileCreateThemeTokens(result.semanticMap, result.primitives, "dark")
91
+ return { light, dark }
92
+ }
54
93
  ```
55
94
 
56
- Lower-level helpers are exported too — `generateScale`, `buildPrimitives`, `buildSemanticMap`, `checkContrast`, `autoCorrect`, `compileThemeCSS`, and the `hexToOklch` / `oklchToHex` color utilities. See the exported TypeScript types for the full shape of `GeneratorResult`.
95
+ `generateTheme` is synchronous and typically runs in a few milliseconds, but it is pure CPU work — debounce it if you are calling it on every keystroke of a color input.
96
+
97
+ Each generated theme carries a short input fingerprint (`computeInputHash`) in its CSS header. It is a cache-busting marker derived from the accents and contrast settings, not a cryptographic digest.
57
98
 
58
99
  ## License
59
100
 
@@ -133,7 +133,7 @@ function parseCliArgs() {
133
133
  help: { type: 'boolean', default: false },
134
134
  },
135
135
  allowPositionals: true,
136
- strict: false,
136
+ strict: true,
137
137
  });
138
138
  if (values.help) {
139
139
  printUsage();
@@ -204,4 +204,8 @@ async function main() {
204
204
  }
205
205
  generate(opts);
206
206
  }
207
- main();
207
+ main().catch((err) => {
208
+ const message = err instanceof Error ? err.message : String(err);
209
+ console.error(`\nError: ${message}`);
210
+ process.exit(1);
211
+ });
@@ -6,7 +6,15 @@ function resolveHex(ref, primitives) {
6
6
  return '#000000';
7
7
  const [scaleName, stepStr] = ref.split('.');
8
8
  const step = Number(stepStr);
9
- return primitives[scaleName][step].hex;
9
+ const scale = primitives[scaleName];
10
+ if (!scale) {
11
+ throw new Error(`Invalid token reference "${ref}": unknown scale "${scaleName}".`);
12
+ }
13
+ const entry = scale[step];
14
+ if (!entry) {
15
+ throw new Error(`Invalid token reference "${ref}": scale "${scaleName}" has no step ${stepStr}.`);
16
+ }
17
+ return entry.hex;
10
18
  }
11
19
  function scaleToW3C(name, scale) {
12
20
  const group = {};
@@ -49,6 +57,7 @@ export function compileSemanticJSON(map, primitives) {
49
57
  role: entry.role,
50
58
  ...(entry.contrastAgainst ? { contrastAgainst: entry.contrastAgainst } : {}),
51
59
  ...(entry.minContrast ? { minContrast: entry.minContrast } : {}),
60
+ ...(entry.allowBelowDefault ? { allowBelowDefault: true } : {}),
52
61
  };
53
62
  }
54
63
  return JSON.stringify(doc, null, 2);
@@ -76,7 +85,6 @@ function compileModeCSSBlock(map, primitives, mode, scaleName, cssPrefix) {
76
85
  if (!scale)
77
86
  return '';
78
87
  const lines = [];
79
- const ref = mode === 'light' ? 'light' : 'dark';
80
88
  const mainStep = mode === 'light' ? 500 : 400;
81
89
  const bgStep = mode === 'light' ? 50 : 950;
82
90
  const tintStep = mode === 'light' ? 100 : 900;
@@ -1,3 +1,10 @@
1
1
  import type { GeneratorConfig, GeneratorResult } from './types.js';
2
+ /**
3
+ * Short, deterministic fingerprint of the inputs that shape a generated theme.
4
+ *
5
+ * Same config in, same 12-character lowercase hex string out. Used to stamp
6
+ * generated CSS and the generation report. Not a security primitive — see the
7
+ * note on the FNV-1a constants above.
8
+ */
2
9
  export declare function computeInputHash(config: GeneratorConfig): string;
3
10
  export declare function generateTheme(config: GeneratorConfig): GeneratorResult;
package/dist/generate.js CHANGED
@@ -1,9 +1,43 @@
1
- import { createHash } from 'node:crypto';
2
1
  import { validateAccents } from './input/validate.js';
3
2
  import { buildPrimitives } from './tokens/primitives.js';
4
3
  import { buildSemanticMap } from './tokens/semanticMap.js';
5
4
  import { autoCorrect } from './tokens/contrast.js';
6
5
  import { compilePrimitivesCSS, compileModeCSS, compileThemeCSS, compileCreateThemeTokens, } from './compile/css.js';
6
+ /*
7
+ * FNV-1a (64-bit) constants.
8
+ *
9
+ * This is a *fingerprint*, not a cryptographic digest. It exists so a generated
10
+ * theme carries a short, stable marker of the inputs it came from — enough to
11
+ * cache-bust and to tell "regenerated from the same config" apart from
12
+ * "regenerated from a different config" at a glance. It is NOT collision
13
+ * resistant and must never be used for integrity, authentication, or any other
14
+ * security purpose.
15
+ *
16
+ * FNV-1a is used here instead of a `node:crypto` SHA-256 digest so that the
17
+ * programmatic entry point of this package stays free of Node built-ins and can
18
+ * run unchanged in the browser.
19
+ */
20
+ const FNV_OFFSET_BASIS_64 = 0xcbf29ce484222325n;
21
+ const FNV_PRIME_64 = 0x100000001b3n;
22
+ const U64_MASK = 0xffffffffffffffffn;
23
+ function fnv1a64(input) {
24
+ let hash = FNV_OFFSET_BASIS_64;
25
+ for (let i = 0; i < input.length; i++) {
26
+ // Hash UTF-16 code units. Inputs here are hex colors and numbers, so this is
27
+ // effectively ASCII, but code-unit iteration keeps the result deterministic
28
+ // for any string.
29
+ hash ^= BigInt(input.charCodeAt(i));
30
+ hash = (hash * FNV_PRIME_64) & U64_MASK;
31
+ }
32
+ return hash;
33
+ }
34
+ /**
35
+ * Short, deterministic fingerprint of the inputs that shape a generated theme.
36
+ *
37
+ * Same config in, same 12-character lowercase hex string out. Used to stamp
38
+ * generated CSS and the generation report. Not a security primitive — see the
39
+ * note on the FNV-1a constants above.
40
+ */
7
41
  export function computeInputHash(config) {
8
42
  const input = JSON.stringify({
9
43
  accents: config.accents,
@@ -12,7 +46,9 @@ export function computeInputHash(config) {
12
46
  systemHues: config.systemHues,
13
47
  curve: config.curve,
14
48
  });
15
- return createHash('sha256').update(input).digest('hex').slice(0, 12);
49
+ // Take the high 48 bits: FNV-1a mixes upward through the multiply, so the high
50
+ // nibbles are the better-distributed end of the digest.
51
+ return fnv1a64(input).toString(16).padStart(16, '0').slice(0, 12);
16
52
  }
17
53
  function buildReport(config, warnings, corrections, primitives, inputHash) {
18
54
  const lines = [];
@@ -7,7 +7,15 @@ function resolveHex(ref, primitives) {
7
7
  return '#000000';
8
8
  const [scaleName, stepStr] = ref.split('.');
9
9
  const step = Number(stepStr);
10
- return primitives[scaleName][step].hex;
10
+ const scale = primitives[scaleName];
11
+ if (!scale) {
12
+ throw new Error(`Invalid token reference "${ref}": unknown scale "${scaleName}".`);
13
+ }
14
+ const entry = scale[step];
15
+ if (!entry) {
16
+ throw new Error(`Invalid token reference "${ref}": scale "${scaleName}" has no step ${stepStr}.`);
17
+ }
18
+ return entry.hex;
11
19
  }
12
20
  function textColor(hex) {
13
21
  const r = parseInt(hex.slice(1, 3), 16);
@@ -3,7 +3,7 @@ const ORDERED_STEPS = [50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 950];
3
3
  export function checkContrast(fgHex, bgHex) {
4
4
  return wcagContrast(fgHex, bgHex);
5
5
  }
6
- function resolveTokenRef(ref, primitives, neutralScale) {
6
+ function resolveTokenRef(ref, primitives) {
7
7
  if (ref === 'white')
8
8
  return '#ffffff';
9
9
  if (ref === 'black')
@@ -97,7 +97,11 @@ export function autoCorrect(map, primitives, mode, defaultMinContrast) {
97
97
  const fgHex = resolveTokenRef(fgRef, primitives);
98
98
  if (!bgHex || !fgHex)
99
99
  continue;
100
- const minContrast = entry.minContrast ?? defaultMinContrast;
100
+ // The config-wide minimum is a floor: per-entry values can raise it but
101
+ // not lower it, except for entries that opt into a lower WCAG tier.
102
+ const minContrast = entry.allowBelowDefault && entry.minContrast !== undefined
103
+ ? entry.minContrast
104
+ : Math.max(entry.minContrast ?? 0, defaultMinContrast);
101
105
  const ratio = checkContrast(fgHex, bgHex);
102
106
  if (ratio >= minContrast)
103
107
  continue;
@@ -23,7 +23,9 @@ export function buildSemanticMap() {
23
23
  'interactive-border-alt': { light: 'neutral.300', dark: 'neutral.600', role: 'border' },
24
24
  'interactive-border-disabled': { light: 'neutral.300', dark: 'neutral.600', role: 'border' },
25
25
  'interactive-fg': { light: 'neutral.950', dark: 'neutral.50', role: 'fg', contrastAgainst: 'interactive-bg', minContrast: 4.5 },
26
- 'interactive-fg-alt': { light: 'neutral.600', dark: 'neutral.300', role: 'fg', contrastAgainst: 'interactive-bg', minContrast: 3.0 },
26
+ // Secondary text targets the WCAG 3:1 large-text/UI tier; allowBelowDefault
27
+ // keeps it there even when the config asks for a stricter floor (e.g. AAA).
28
+ 'interactive-fg-alt': { light: 'neutral.600', dark: 'neutral.300', role: 'fg', contrastAgainst: 'interactive-bg', minContrast: 3.0, allowBelowDefault: true },
27
29
  'interactive-fg-readonly': { light: 'neutral.800', dark: 'neutral.100', role: 'fg', contrastAgainst: 'interactive-bg', minContrast: 4.5 },
28
30
  'interactive-fg-disabled': { light: 'neutral.400', dark: 'neutral.500', role: 'fg' },
29
31
  'interactive-fg-active': { light: 'primary.100', dark: 'primary.900', role: 'fg', contrastAgainst: 'interactive-bg-active', minContrast: 4.5 },
package/dist/types.d.ts CHANGED
@@ -27,12 +27,24 @@ export type SemanticEntry = {
27
27
  dark: TokenRef;
28
28
  contrastAgainst?: string;
29
29
  minContrast?: number;
30
+ /**
31
+ * Honor `minContrast` as-is even when it is below the config-wide minimum.
32
+ * For entries that deliberately target a lower WCAG tier (e.g. the 3:1
33
+ * large-text/UI tier for secondary text) and must not be raised by a
34
+ * stricter `GeneratorConfig.minContrast`.
35
+ */
36
+ allowBelowDefault?: boolean;
30
37
  role: SemanticRole;
31
38
  };
32
39
  export type SemanticMap = Record<string, SemanticEntry>;
33
40
  export type GeneratorConfig = {
34
41
  accents: string[];
35
42
  themeName: string;
43
+ /**
44
+ * Contrast floor for every checked fg/border pairing (4.5 = WCAG AA,
45
+ * 7 = AAA). Per-entry `minContrast` values can raise the floor for a token
46
+ * but never lower it, unless the entry sets `allowBelowDefault`.
47
+ */
36
48
  minContrast: number;
37
49
  neutralTintRatio: number;
38
50
  curve?: ScaleStep[];
package/package.json CHANGED
@@ -1,8 +1,9 @@
1
1
  {
2
2
  "name": "@eluan/theme-generator",
3
- "description": "CLI tool that generates accessible, light + dark mode Eluan theme token sets from accent colors",
4
- "version": "0.1.0",
3
+ "description": "CLI and browser-safe library that generates accessible, light + dark mode Eluan theme token sets from accent colors",
4
+ "version": "0.3.0",
5
5
  "license": "MIT",
6
+ "author": "Frolda",
6
7
  "homepage": "https://github.com/vasfio/eluan#readme",
7
8
  "repository": {
8
9
  "type": "git",
@@ -17,9 +18,18 @@
17
18
  "theme",
18
19
  "cli",
19
20
  "eluan",
20
- "color"
21
+ "color",
22
+ "oklch",
23
+ "accessibility",
24
+ "browser"
21
25
  ],
22
26
  "type": "module",
27
+ "sideEffects": [
28
+ "./dist/cli/*.js"
29
+ ],
30
+ "engines": {
31
+ "node": ">=20"
32
+ },
23
33
  "main": "./dist/index.js",
24
34
  "types": "./dist/index.d.ts",
25
35
  "bin": {
@@ -43,12 +53,15 @@
43
53
  },
44
54
  "devDependencies": {
45
55
  "@types/prompts": "^2.4.9",
56
+ "esbuild": "^0.27.7",
46
57
  "typescript": "^5.4.5",
47
58
  "vitest": "^2.0.0"
48
59
  },
49
60
  "scripts": {
50
61
  "build": "rm -rf dist && tsc -p tsconfig.build.json",
51
62
  "dev": "tsc --watch",
63
+ "lint": "eslint src --report-unused-disable-directives --max-warnings 0",
64
+ "check:browser": "pnpm run build && esbuild dist/index.js --bundle --platform=browser --outfile=/dev/null --log-level=warning",
52
65
  "test": "vitest run",
53
66
  "test:watch": "vitest"
54
67
  }