@raketa-cloud/design-cli 1.0.0 → 1.1.1
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 +23 -4
- package/build.mjs +90 -25
- package/catalog/css-native.mjs +4 -7
- package/cli.mjs +16 -3
- package/config.mjs +21 -12
- package/init.mjs +31 -0
- package/overlay.mjs +75 -0
- package/package.json +34 -7
- package/preset.mjs +158 -0
- package/preview-css.mjs +37 -10
- package/showcase/serve.mjs +37 -31
- package/skills/design-system/SKILL.md +27 -0
package/README.md
CHANGED
|
@@ -4,9 +4,10 @@ Shared Node 22+ tooling for local design systems. It serves the showcase and bui
|
|
|
4
4
|
|
|
5
5
|
## Usage
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
Initialize a host project, then generate and preview its design system:
|
|
8
8
|
|
|
9
9
|
```bash
|
|
10
|
+
npx @raketa-cloud/design-cli init
|
|
10
11
|
npx @raketa-cloud/design-cli generate
|
|
11
12
|
npx @raketa-cloud/design-cli serve
|
|
12
13
|
npx @raketa-cloud/design-cli new component my-pattern
|
|
@@ -14,6 +15,8 @@ npx @raketa-cloud/design-cli new layout my-pattern
|
|
|
14
15
|
```
|
|
15
16
|
|
|
16
17
|
Alternatively, install it with `npm install --save-dev @raketa-cloud/design-cli` and run `npx design <command>`. Run `npx @raketa-cloud/design-cli --help` for usage. `serve` listens on `127.0.0.1:4174`; `PORT` changes the port. `SHOWCASE_PRESET` selects a built-in or design-local preset. New scaffold previews link `/__showcase/theme.css`, so existing component classes work when opened through the showcase. Scaffolded markup and docs remain placeholders, not finished designs.
|
|
18
|
+
`init` creates a starter `.design` directory, installs the design-system skill to `.agents/skills/design-system`, and links it from `.claude/skills/` and `.pi/skills/`. It refuses to overwrite any of those paths. Update `.design/config.json`, tokens, and `DESIGN.md` for your project, then add patterns and wire the generated CSS into your application. The initializer does not change application code or dependencies.
|
|
19
|
+
|
|
17
20
|
|
|
18
21
|
Pattern previews are hand-maintained `preview.html` files, optionally accompanied by `docs.md` and reusable `styles.css`. Generation does not produce or overwrite previews.
|
|
19
22
|
|
|
@@ -32,13 +35,29 @@ A design directory has `config.json`:
|
|
|
32
35
|
|
|
33
36
|
The builder reads `tokens/tokens.json`, detects normalized or CSS-native data, emits custom properties and appends CSS files recursively from `components/`. `preview.css` is excluded because it contains specimen-only presentation. For CSS-native sources, `tokens/palettes.json` supplies optional `:root`/`.dark` custom properties, and `tokens/components.json` supplies optional component aliases and dark overrides. Normalized sources include their token groups and themes in `tokens.json`. Token references become CSS variable references. Component CSS must be standalone: Tailwind `@apply`, `@theme`, `@source`, and CSS `@import` are rejected. Relative asset URLs remain the component author's responsibility. Preview HTML, scripts, host runtime assets and application builds are not generated or updated.
|
|
34
37
|
|
|
35
|
-
The showcase reads `system.name` from configuration. Its token renderer detects normalized data (`primitive.color` and `semantic.color`) or Raketa CSS-native data (`blocks`). The latter
|
|
38
|
+
The showcase reads `system.name` from configuration. Its token renderer detects normalized data (`primitive.color` and `semantic.color`) or Raketa CSS-native data (`blocks`). The latter projection reads `tokens/components.json` and a transient Tailwind build for status colors; its typography specimens use Raketa's documented defaults. Unknown or ambiguous token formats are rejected. `DESIGN.md` remains a design reference; configuration supplies the showcase name.
|
|
39
|
+
|
|
40
|
+
`/__showcase/preview.css` uses the CLI's bundled Tailwind compiler, design tokens and component/layout previews, independent of the host framework. It includes the generated theme when present. If previews also depend on a Tailwind-compatible stylesheet, set `"preview": { "css": "raketa/index.css" }` in `config.json` (path relative to the project). This is preview-only and does not alter production CSS. The stylesheet and its imports must be compatible with the CLI's Tailwind version; host plugins must be resolvable by the host. Run `generate` before serving to include the theme. Missing output returns 404 at `/__showcase/theme.css`.
|
|
36
41
|
|
|
37
|
-
Configuration, preview HTML and `_theme_preview.html` are trusted local inputs; do not expose the server to untrusted networks. Apart from shared chrome under `/__showcase/` and `/showcase/asset-grid.css`, the server serves files only within the design directory, plus the configured output at `/__showcase/theme.css`.
|
|
42
|
+
Configuration, preview HTML and `_theme_preview.html` are trusted local inputs; do not expose the server to untrusted networks. Apart from shared chrome under `/__showcase/` and `/showcase/asset-grid.css`, the server serves files only within the design directory, plus the configured output at `/__showcase/theme.css`. The server watches the output directory for reloads when it exists at startup; restart after changing the output location or creating a previously missing directory. Theme selection and application-specific behavior must still be added to scaffolds.
|
|
38
43
|
|
|
39
44
|
Run `npm test` here for tooling behavior. Consumers should separately validate integration and preview appearance; the build does not change their production wiring.
|
|
40
45
|
|
|
46
|
+
## Repository-backed presets
|
|
47
|
+
|
|
48
|
+
Set `"preset": { "repo": "git@github.com:example/admin-ui.git", "ref": "main" }` in `.design/config.json`. The repository contains `.design/` for shared design inputs and `raketa/` for runtime assets. Run `design preset update` to resolve the ref and write `.design/preset.lock.json`; commit the lock. On a fresh checkout run `design preset install` before building. Generate and serve do not fetch; updates are explicit and reviewable. Git access must be available without an interactive prompt.
|
|
49
|
+
|
|
50
|
+
The disposable `.design/.preset/` cache is ignored by its own ignore file. Install and update link `.design/.preset/runtime` to the selected `raketa/` directory; host CSS and JavaScript can import from that path. Run generate or serve after changing the selected preset. Production builds must install first and include the generated theme and runtime assets using the host's framework-specific wiring.
|
|
51
|
+
|
|
52
|
+
For live preset development, set `DESIGN_PRESET_DIR` to a local checkout and run generate or serve. Changes to that checkout are visible through the runtime link and showcase. This override is forbidden when `CI` is set. Restart the showcase after changing the checkout location.
|
|
53
|
+
|
|
54
|
+
Token JSON objects merge recursively; arrays replace wholesale. Local component and layout pattern directories replace the entire matching preset pattern. Additional local component CSS follows preset CSS. `tokenOverrides` maps `:root` and `.dark` to existing CSS variable names and values; unknown names are rejected. For example: `"tokenOverrides": { ":root": { "--color-action": "#123456" } }`. Not every valid CSS color expression can be rendered in catalog swatches; inspect the actual preview and generated CSS.
|
|
55
|
+
|
|
56
|
+
Preset repositories, previews and runtime JavaScript are trusted inputs. The installer does not invoke preset install scripts, but Git uses your configuration and credentials, including any configured checkout filters. Using preset CSS, JavaScript or Tailwind plugins can execute or load untrusted content. Review changes and test framework integration separately.
|
|
57
|
+
|
|
41
58
|
## Publishing
|
|
42
59
|
|
|
43
|
-
The package is public on npm even though this repository is private.
|
|
60
|
+
The package is public on npm even though this repository is private. In npm package settings, add a GitHub Actions trusted publisher for organization `studioraketa`, repository `design-system-tools`, workflow filename `publish.yml`, with direct `npm publish` allowed and no environment name. The workflow uses GitHub OIDC rather than an npm token; Node 24 supplies the required npm 11.5.1 or later. Complete the first publish within two days of creating the trusted publisher. Private repositories do not generate npm provenance.
|
|
61
|
+
|
|
62
|
+
Update the package version and lockfile, then publish a GitHub release tagged with the exact version (for example, `1.0.2`); the workflow checks the tag, runs tests, and publishes to npm. Prereleases are not published. After a successful trusted publish, revoke the old npm publishing token and remove the `NPM_TOKEN` GitHub secret.
|
|
44
63
|
|
package/build.mjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import { lstat, mkdir, readFile,
|
|
2
|
-
import { dirname
|
|
1
|
+
import { lstat, mkdir, readFile, realpath, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { dirname } from 'node:path';
|
|
3
3
|
import { tokenSource, themePath } from './config.mjs';
|
|
4
|
+
import { overlayJson, overlayFiles } from './overlay.mjs';
|
|
4
5
|
|
|
5
6
|
const validName = /^--[a-z][a-z0-9-]*$/;
|
|
6
7
|
const safeValue = value => {
|
|
@@ -45,16 +46,12 @@ function block(selector, declarations) {
|
|
|
45
46
|
for (const [key, value] of Object.entries(declarations)) { if (!validName.test(key)) throw new Error('Invalid CSS token name: ' + key); safeValue(value); }
|
|
46
47
|
return selector + ' {\n' + Object.entries(declarations).map(([key, value]) => ` ${key}: ${value};`).join('\n') + '\n}\n';
|
|
47
48
|
}
|
|
48
|
-
async function
|
|
49
|
-
|
|
50
|
-
catch (error) { if (error.code === 'ENOENT') return null; throw error; }
|
|
51
|
-
}
|
|
52
|
-
async function tokenCSS(designDir) {
|
|
53
|
-
const { input, type } = await tokenSource(designDir);
|
|
49
|
+
export async function tokenCSS(context) {
|
|
50
|
+
const { input, type } = await tokenSource(context);
|
|
54
51
|
const native = type === 'raketa-css';
|
|
55
52
|
let css = '';
|
|
56
53
|
if (native) {
|
|
57
|
-
const extra = await
|
|
54
|
+
const extra = await overlayJson(context, 'tokens/palettes.json') || {};
|
|
58
55
|
for (const selector of Object.keys(extra)) if (![':root', '.dark'].includes(selector)) throw new Error('Unsupported palette selector: ' + selector);
|
|
59
56
|
const root = { ...(extra[':root'] || {}) };
|
|
60
57
|
let dark = { ...(extra['.dark'] || {}) };
|
|
@@ -69,7 +66,7 @@ async function tokenCSS(designDir) {
|
|
|
69
66
|
}
|
|
70
67
|
}
|
|
71
68
|
css += block(':root', root) + block('.dark', { ...themedAliases, ...dark });
|
|
72
|
-
const components = await
|
|
69
|
+
const components = await overlayJson(context, 'tokens/components.json');
|
|
73
70
|
if (components?.components) {
|
|
74
71
|
const baseRoles = flattenTokens(components.components, true, ['components']);
|
|
75
72
|
const darkRoles = components.themes?.dark?.components ? flattenTokens(components.themes.dark.components, true, ['components']) : {};
|
|
@@ -85,27 +82,95 @@ async function tokenCSS(designDir) {
|
|
|
85
82
|
css += block(name === 'dark' ? '.dark' : '.theme-' + name, { ...themed, ...flattenTokens(values, false) });
|
|
86
83
|
}
|
|
87
84
|
}
|
|
85
|
+
const overrides = context.config?.tokenOverrides;
|
|
86
|
+
if (overrides !== undefined) {
|
|
87
|
+
if (!overrides || typeof overrides !== 'object' || Array.isArray(overrides)) throw new Error('Invalid tokenOverrides');
|
|
88
|
+
const names = new Set([...css.matchAll(/(--[a-z][a-z0-9-]*)\s*:/g)].map(match => match[1]));
|
|
89
|
+
for (const [selector, values] of Object.entries(overrides)) {
|
|
90
|
+
if (![':root', '.dark'].includes(selector) || !values || typeof values !== 'object' || Array.isArray(values)) throw new Error('Invalid tokenOverrides selector: ' + selector);
|
|
91
|
+
for (const [name, value] of Object.entries(values)) {
|
|
92
|
+
if (!names.has(name)) throw new Error('Unknown CSS variable override: ' + name);
|
|
93
|
+
if (typeof value !== 'string') throw new Error('Invalid CSS token value');
|
|
94
|
+
safeValue(value);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
const darkBlocks = [...css.matchAll(/\.dark \{\n[^}]*\}\n/g)].map(match => match[0]).join('');
|
|
98
|
+
css = css.replace(/\.dark \{\n[^}]*\}\n/g, '');
|
|
99
|
+
if (overrides[':root']) css += block(':root', overrides[':root']);
|
|
100
|
+
css += darkBlocks;
|
|
101
|
+
if (overrides['.dark']) css += block('.dark', overrides['.dark']);
|
|
102
|
+
}
|
|
88
103
|
return css;
|
|
89
104
|
}
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
if (
|
|
97
|
-
|
|
98
|
-
|
|
105
|
+
export function applyCatalogOverrides(input, overrides = {}) {
|
|
106
|
+
const data = structuredClone(input);
|
|
107
|
+
const paths = new Map();
|
|
108
|
+
function collect(group, path = []) {
|
|
109
|
+
if (!group || typeof group !== 'object' || Array.isArray(group)) return;
|
|
110
|
+
if (Object.hasOwn(group, '$value')) { paths.set(cssName(path.join('.'), false), path.join('.')); return; }
|
|
111
|
+
for (const [key, child] of Object.entries(group)) if (!key.startsWith('$') && key !== 'themes') collect(child, [...path, key]);
|
|
112
|
+
}
|
|
113
|
+
collect(data);
|
|
114
|
+
let sequence = 0;
|
|
115
|
+
function colorReference(value) {
|
|
116
|
+
const variable = value.match(/^var\((--[a-z][a-z0-9-]*)\)$/)?.[1];
|
|
117
|
+
if (variable && paths.has(variable)) return `{${paths.get(variable)}}`;
|
|
118
|
+
const key = 'override-' + sequence++;
|
|
119
|
+
data.derived ||= {}; data.derived.color ||= {};
|
|
120
|
+
data.derived.color[key] = { $type: 'color', $value: value };
|
|
121
|
+
return `{derived.color.${key}}`;
|
|
122
|
+
}
|
|
123
|
+
function apply(group, values, path = []) {
|
|
124
|
+
if (!group || typeof group !== 'object' || Array.isArray(group)) return;
|
|
125
|
+
if (Object.hasOwn(group, '$value')) {
|
|
126
|
+
const name = cssName(path.join('.'), false);
|
|
127
|
+
if (Object.hasOwn(values, name)) group.$value = group.$type === 'color' && ['semantic', 'components'].includes(path[0]) ? colorReference(values[name]) : values[name];
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
for (const [key, child] of Object.entries(group)) if (!key.startsWith('$') && key !== 'themes') apply(child, values, [...path, key]);
|
|
131
|
+
}
|
|
132
|
+
apply(data, overrides[':root'] || {});
|
|
133
|
+
if (overrides['.dark']) {
|
|
134
|
+
data.themes ||= {}; data.themes.dark ||= {};
|
|
135
|
+
// Supply inherited groups so a dark-only override can target a root variable.
|
|
136
|
+
const inherited = structuredClone({ semantic: data.semantic, components: data.components || {} });
|
|
137
|
+
const merge = (a, b) => {
|
|
138
|
+
if (!a || !b || typeof a !== 'object' || typeof b !== 'object' || Array.isArray(a) || Array.isArray(b)) return b;
|
|
139
|
+
for (const [key, value] of Object.entries(b)) a[key] = key in a ? merge(a[key], value) : value;
|
|
140
|
+
return a;
|
|
141
|
+
};
|
|
142
|
+
data.themes.dark = merge(inherited, data.themes.dark);
|
|
143
|
+
apply(data.themes.dark, overrides['.dark']);
|
|
144
|
+
const replacements = new Map();
|
|
145
|
+
for (const [name, value] of Object.entries(overrides['.dark'])) {
|
|
146
|
+
const path = paths.get(name);
|
|
147
|
+
if (path?.startsWith('primitive.color.') || path?.startsWith('derived.color.')) replacements.set(`{${path}}`, colorReference(value));
|
|
148
|
+
}
|
|
149
|
+
function rewrite(group) {
|
|
150
|
+
if (!group || typeof group !== 'object' || Array.isArray(group)) return;
|
|
151
|
+
if (Object.hasOwn(group, '$value')) { if (replacements.has(group.$value)) group.$value = replacements.get(group.$value); return; }
|
|
152
|
+
for (const child of Object.values(group)) rewrite(child);
|
|
153
|
+
}
|
|
154
|
+
rewrite(data.themes.dark);
|
|
155
|
+
}
|
|
156
|
+
return data;
|
|
157
|
+
}
|
|
158
|
+
export async function renderTheme(context) {
|
|
159
|
+
let css = '/* Generated by design-tooling; edit the design sources instead. */\n' + await tokenCSS(context);
|
|
160
|
+
const files = (await overlayFiles(context, 'components')).filter(file => file.name.endsWith('.css') && !file.name.endsWith('/preview.css'));
|
|
161
|
+
const localRoot = await realpath(context.designDir);
|
|
162
|
+
files.sort((a, b) => Number(a.path.startsWith(localRoot + '/')) - Number(b.path.startsWith(localRoot + '/')) || a.name.localeCompare(b.name));
|
|
163
|
+
for (const { name, path } of files) {
|
|
164
|
+
const content = await readFile(path, 'utf8');
|
|
165
|
+
if (/@(?:apply|import|theme|source)\b/.test(content)) throw new Error('Component styles must be standalone CSS: ' + name);
|
|
166
|
+
css += `\n/* ${name} */\n` + content.trim() + '\n';
|
|
167
|
+
}
|
|
168
|
+
return css;
|
|
99
169
|
}
|
|
100
170
|
export async function build(context) {
|
|
101
171
|
const output = themePath(context);
|
|
102
172
|
const dir = dirname(output);
|
|
103
|
-
|
|
104
|
-
for (const path of await styles(join(context.designDir, 'components'))) {
|
|
105
|
-
const content = await readFile(path, 'utf8');
|
|
106
|
-
if (/@(?:apply|import|theme|source)\b/.test(content)) throw new Error('Component styles must be standalone CSS: ' + relative(context.designDir, path));
|
|
107
|
-
css += `\n/* ${relative(context.designDir, path).split('\\').join('/')} */\n` + content.trim() + '\n';
|
|
108
|
-
}
|
|
173
|
+
const css = await renderTheme(context);
|
|
109
174
|
const existing = await lstat(output).catch(error => { if (error.code === 'ENOENT') return null; throw error; });
|
|
110
175
|
if (existing && !existing.isFile()) throw new Error('Build output must be a regular file');
|
|
111
176
|
await mkdir(dir, { recursive: true });
|
package/catalog/css-native.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// Read-only projection for CSS-native Raketa token packages.
|
|
2
|
-
export function showcaseData(input,
|
|
2
|
+
export function showcaseData(input, status, componentTokens) {
|
|
3
3
|
if (!input.blocks) return input;
|
|
4
4
|
const declarations = selector => {
|
|
5
5
|
const block = input.blocks.find(block => block.selector === selector);
|
|
@@ -67,13 +67,10 @@ export function showcaseData(input, componentCSS, status, componentTokens) {
|
|
|
67
67
|
const type = (size, lineHeight, weight = 400) => ({ $type: 'typography', $value: { fontFamily: '{foundation.font.ui}', fontSize: { value: size, unit: 'px' }, lineHeight: Number(lineHeight.toFixed(2)), fontWeight: weight, letterSpacing: { value: 0, unit: 'em' } } });
|
|
68
68
|
const scale = { 'text-4xl': [36, 40 / 36], 'text-xl': [20, 28 / 20], 'text-sm': [14, 20 / 14], 'text-xs': [12, 16 / 12] };
|
|
69
69
|
const typography = {};
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
if (!rule) throw new Error('Missing authored typography rule: ' + name);
|
|
73
|
-
const utility = rule.match(/@apply (text-[\w-]+)/)?.[1];
|
|
74
|
-
if (!scale[utility]) throw new Error('Unknown authored typography size: ' + utility);
|
|
70
|
+
// Raketa's documented default typography specimens; host CSS is not a design input.
|
|
71
|
+
for (const [name, utility, weight] of [['title-page', 'text-4xl', 700], ['title-header', 'text-xl', 700], ['title-section', 'text-xl', 600], ['title-subsection', 'text-sm', 600]]) {
|
|
75
72
|
const [size, lineHeight] = scale[utility];
|
|
76
|
-
typography[name] = type(size, lineHeight,
|
|
73
|
+
typography[name] = type(size, lineHeight, weight);
|
|
77
74
|
}
|
|
78
75
|
typography['body-1'] = type(14, 20 / 14);
|
|
79
76
|
typography['text-sm'] = type(14, 20 / 14);
|
package/cli.mjs
CHANGED
|
@@ -6,10 +6,18 @@ import { build } from './build.mjs';
|
|
|
6
6
|
|
|
7
7
|
const [command, ...args] = process.argv.slice(2);
|
|
8
8
|
if (command === '--help' || command === '-h' || !command) {
|
|
9
|
-
console.log('Usage: design <generate|serve|new>\n\n generate Build the design system CSS\n serve Start the local showcase\n new <component|layout> <name> Scaffold a pattern');
|
|
9
|
+
console.log('Usage: design <init|generate|serve|new|preset>\n\n init Set up a design system and agent skill\n generate Build the design system CSS\n serve Start the local showcase\n new <component|layout> <name> Scaffold a pattern\n preset <update|install> Pin or install a preset');
|
|
10
10
|
} else if (command === '--version' || command === '-v') {
|
|
11
11
|
const { readFile } = await import('node:fs/promises');
|
|
12
12
|
console.log(JSON.parse(await readFile(new URL('./package.json', import.meta.url), 'utf8')).version);
|
|
13
|
+
} else if (command === 'init') {
|
|
14
|
+
if (args.length) throw new Error('Unexpected arguments');
|
|
15
|
+
const { init } = await import('./init.mjs');
|
|
16
|
+
await init();
|
|
17
|
+
} else if (command === 'preset') {
|
|
18
|
+
if (args.length !== 1 || !['update', 'install'].includes(args[0])) throw new Error('Usage: design preset <update|install>');
|
|
19
|
+
const { updatePreset, installPreset } = await import('./preset.mjs');
|
|
20
|
+
await (args[0] === 'update' ? updatePreset : installPreset)(await loadConfig());
|
|
13
21
|
} else if (command === 'new') {
|
|
14
22
|
const [kind, name, ...extra] = args;
|
|
15
23
|
if (!['component', 'layout'].includes(kind) || !/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(name || '') || extra.length) throw new Error('Usage: design new <component|layout> <kebab-case-name>');
|
|
@@ -30,8 +38,13 @@ if (command === '--help' || command === '-h' || !command) {
|
|
|
30
38
|
console.log(`Created ${kind}: ${target}`);
|
|
31
39
|
} else if (command === 'generate') {
|
|
32
40
|
if (args.length) throw new Error('Unexpected arguments');
|
|
33
|
-
|
|
41
|
+
const context = await loadConfig();
|
|
42
|
+
const { refreshPresetRuntime } = await import('./preset.mjs');
|
|
43
|
+
await refreshPresetRuntime(context);
|
|
44
|
+
await build(context);
|
|
34
45
|
} else if (command === 'serve') {
|
|
35
46
|
if (args.length) throw new Error('Unexpected arguments');
|
|
47
|
+
const { refreshPresetRuntime } = await import('./preset.mjs');
|
|
48
|
+
await refreshPresetRuntime(await loadConfig());
|
|
36
49
|
await import('./showcase/serve.mjs');
|
|
37
|
-
} else throw new Error('Usage: design <generate|serve|new>');
|
|
50
|
+
} else throw new Error('Usage: design <init|generate|serve|new|preset>');
|
package/config.mjs
CHANGED
|
@@ -3,6 +3,8 @@ import { dirname, resolve } from 'node:path';
|
|
|
3
3
|
import { showcaseData } from './catalog/css-native.mjs';
|
|
4
4
|
import { statusColors } from './catalog/status-colors.mjs';
|
|
5
5
|
import { previewCss } from './preview-css.mjs';
|
|
6
|
+
import { overlayJson } from './overlay.mjs';
|
|
7
|
+
import { tokenCSS, applyCatalogOverrides } from './build.mjs';
|
|
6
8
|
|
|
7
9
|
export async function loadConfig() {
|
|
8
10
|
const designDir = await realpath(resolve(process.env.DESIGN_DIR || '.design'));
|
|
@@ -17,26 +19,33 @@ export function themePath({ config, projectDir }) {
|
|
|
17
19
|
if (!build || typeof build.output !== 'string' || !build.output.trim()) throw new Error('build.output is required');
|
|
18
20
|
return resolve(projectDir, build.output, system.id, 'theme.css');
|
|
19
21
|
}
|
|
20
|
-
export async function tokenSource(
|
|
21
|
-
const
|
|
22
|
+
export async function tokenSource(source) {
|
|
23
|
+
const context = typeof source === 'string' ? { designDir: source } : source;
|
|
24
|
+
const input = await overlayJson(context, 'tokens/tokens.json', true);
|
|
22
25
|
const cssNative = Array.isArray(input?.blocks);
|
|
23
26
|
const normalized = !!input?.primitive?.color && !!input?.semantic?.color;
|
|
24
27
|
if (cssNative === normalized) throw new Error('Unrecognized or ambiguous tokens/tokens.json format');
|
|
25
28
|
return { input, type: cssNative ? 'raketa-css' : 'tokens' };
|
|
26
29
|
}
|
|
27
30
|
|
|
28
|
-
export async function raketaInputs(
|
|
29
|
-
const
|
|
30
|
-
|
|
31
|
-
readFile(resolve(projectDir, 'raketa/components.css'), 'utf8')
|
|
32
|
-
]);
|
|
33
|
-
return { input, componentTokens, css };
|
|
31
|
+
export async function raketaInputs(context, input) {
|
|
32
|
+
const componentTokens = await overlayJson(context, 'tokens/components.json', true);
|
|
33
|
+
return { input, componentTokens };
|
|
34
34
|
}
|
|
35
35
|
|
|
36
36
|
export async function catalog(context) {
|
|
37
|
-
const { input, type } = await tokenSource(context
|
|
38
|
-
|
|
39
|
-
|
|
37
|
+
const { input, type } = await tokenSource(context);
|
|
38
|
+
await tokenCSS(context); // Validate overrides even when only rendering the catalog.
|
|
39
|
+
if (type === 'tokens') return applyCatalogOverrides(input, context.config?.tokenOverrides);
|
|
40
|
+
const { componentTokens } = await raketaInputs(context, input);
|
|
40
41
|
const status = statusColors(await previewCss(context));
|
|
41
|
-
|
|
42
|
+
const adjusted = structuredClone(input);
|
|
43
|
+
for (const [selector, values] of Object.entries(context.config?.tokenOverrides || {})) {
|
|
44
|
+
for (const [name, value] of Object.entries(values)) {
|
|
45
|
+
for (const entry of adjusted.blocks) {
|
|
46
|
+
if (entry.selector === selector || (selector === ':root' && ['@theme', '@theme inline'].includes(entry.selector) && Object.hasOwn(entry.tokens, name))) entry.tokens[name] = { $type: 'string', $value: value };
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
return showcaseData(adjusted, status, componentTokens);
|
|
42
51
|
}
|
package/init.mjs
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { lstat, mkdir, readFile, symlink, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { resolve } from 'node:path';
|
|
3
|
+
|
|
4
|
+
export async function init() {
|
|
5
|
+
const root = process.cwd();
|
|
6
|
+
const paths = ['.design', '.agents/skills/design-system', '.claude/skills/design-system', '.pi/skills/design-system'];
|
|
7
|
+
for (const path of paths) {
|
|
8
|
+
try {
|
|
9
|
+
await lstat(resolve(root, path));
|
|
10
|
+
throw new Error(`Refusing to overwrite existing path: ${path}`);
|
|
11
|
+
} catch (error) {
|
|
12
|
+
if (error.code !== 'ENOENT') throw error;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
// Create the design directory exclusively; existing projects are never merged or overwritten.
|
|
16
|
+
await mkdir(resolve(root, '.design'));
|
|
17
|
+
for (const dir of ['tokens', 'components', 'layouts', 'rules', 'assets']) {
|
|
18
|
+
await mkdir(resolve(root, '.design', dir));
|
|
19
|
+
}
|
|
20
|
+
await writeFile(resolve(root, '.design/config.json'), JSON.stringify({ system: { name: 'My design system', id: 'my-design-system' }, build: { output: 'public/design' } }, null, 2) + '\n', { flag: 'wx' });
|
|
21
|
+
const tokens = { primitive: { color: { neutral: { white: { $type: 'color', $value: '#ffffff' }, black: { $type: 'color', $value: '#000000' } } } }, semantic: { color: { background: { $type: 'color', $value: '{primitive.color.neutral.white}' }, foreground: { $type: 'color', $value: '{primitive.color.neutral.black}' } } } };
|
|
22
|
+
await writeFile(resolve(root, '.design/tokens/tokens.json'), JSON.stringify(tokens, null, 2) + '\n', { flag: 'wx' });
|
|
23
|
+
await writeFile(resolve(root, '.design/DESIGN.md'), '# Design system\n\nReplace this starter with your design principles, conventions, and references.\n', { flag: 'wx' });
|
|
24
|
+
await mkdir(resolve(root, '.agents/skills/design-system'), { recursive: true });
|
|
25
|
+
await writeFile(resolve(root, '.agents/skills/design-system/SKILL.md'), await readFile(new URL('./skills/design-system/SKILL.md', import.meta.url)), { flag: 'wx' });
|
|
26
|
+
for (const agent of ['.claude', '.pi']) {
|
|
27
|
+
await mkdir(resolve(root, agent, 'skills'), { recursive: true });
|
|
28
|
+
await symlink('../../.agents/skills/design-system', resolve(root, agent, 'skills/design-system'), 'dir');
|
|
29
|
+
}
|
|
30
|
+
console.log('Initialized .design and installed the design-system skill.\n\nNext steps:\n 1. Update .design/config.json (system name, id, and output path).\n 2. Replace the starter tokens and document your system in .design/DESIGN.md and rules/.\n 3. Add patterns, run design generate and design serve, and wire the CSS into your app.');
|
|
31
|
+
}
|
package/overlay.mjs
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { lstat, readFile, readdir, realpath } from 'node:fs/promises';
|
|
2
|
+
import { join, resolve, sep } from 'node:path';
|
|
3
|
+
|
|
4
|
+
export async function presetDesign(context) {
|
|
5
|
+
// preset.mjs is supplied by the installer. Keep standalone callers working too.
|
|
6
|
+
let resolver;
|
|
7
|
+
try { ({ resolvePreset: resolver } = await import('./preset.mjs')); }
|
|
8
|
+
catch (error) { if (error.code === 'ERR_MODULE_NOT_FOUND' && error.message.includes("/preset.mjs")) return null; throw error; }
|
|
9
|
+
const root = await resolver(context);
|
|
10
|
+
if (!root) return null;
|
|
11
|
+
const directory = join(root, '.design');
|
|
12
|
+
const info = await lstat(directory);
|
|
13
|
+
if (!info.isDirectory()) throw new Error('Preset .design must be a directory, not a symlink');
|
|
14
|
+
return directory;
|
|
15
|
+
}
|
|
16
|
+
const object = x => x !== null && typeof x === 'object' && !Array.isArray(x);
|
|
17
|
+
export function mergeObjects(base, local) {
|
|
18
|
+
if (!object(base) || !object(local)) return local;
|
|
19
|
+
const result = { ...base };
|
|
20
|
+
for (const [key, value] of Object.entries(local)) {
|
|
21
|
+
if (['__proto__', 'constructor', 'prototype'].includes(key)) throw new Error('Invalid token key: ' + key);
|
|
22
|
+
result[key] = Object.hasOwn(result, key) ? mergeObjects(result[key], value) : value;
|
|
23
|
+
}
|
|
24
|
+
return result;
|
|
25
|
+
}
|
|
26
|
+
async function json(root, path) {
|
|
27
|
+
try {
|
|
28
|
+
const actual = await realpath(join(root, path));
|
|
29
|
+
if (!actual.startsWith(await realpath(root) + sep)) throw new Error('Token path escapes design directory');
|
|
30
|
+
return JSON.parse(await readFile(actual, 'utf8'));
|
|
31
|
+
}
|
|
32
|
+
catch (error) { if (error.code === 'ENOENT') return undefined; throw error; }
|
|
33
|
+
}
|
|
34
|
+
export async function overlayJson(context, path, required = false) {
|
|
35
|
+
const base = await presetDesign(context);
|
|
36
|
+
const [a, b] = await Promise.all([base ? json(base, path) : undefined, json(context.designDir, path)]);
|
|
37
|
+
if (a === undefined && b === undefined && required) { const e = new Error('Missing ' + path); e.code = 'ENOENT'; throw e; }
|
|
38
|
+
return b === undefined ? a : a === undefined ? b : mergeObjects(a, b);
|
|
39
|
+
}
|
|
40
|
+
async function exists(path) { try { return await lstat(path); } catch (e) { if (e.code === 'ENOENT' || e.code === 'ENOTDIR') return null; throw e; } }
|
|
41
|
+
// Resolve only inside the selected root; a local pattern replaces the complete base pattern.
|
|
42
|
+
export async function overlayPath(context, name, resolvedBase) {
|
|
43
|
+
const parts = name.split('/');
|
|
44
|
+
if (parts.some(p => !p || p === '.' || p === '..' || p.startsWith('.'))) return null;
|
|
45
|
+
const base = resolvedBase === undefined ? await presetDesign(context) : resolvedBase;
|
|
46
|
+
let root = context.designDir;
|
|
47
|
+
const unit = ['components', 'layouts'].includes(parts[0]) ? parts.slice(0, 2) : parts[0] === 'assets' ? parts.slice(0, 3) : parts;
|
|
48
|
+
const localUnit = await exists(join(root, ...unit));
|
|
49
|
+
if (!localUnit && base) root = base;
|
|
50
|
+
const path = resolve(root, ...parts);
|
|
51
|
+
try {
|
|
52
|
+
let current = root;
|
|
53
|
+
for (const part of parts) {
|
|
54
|
+
current = join(current, part);
|
|
55
|
+
if ((await lstat(current)).isSymbolicLink()) return null;
|
|
56
|
+
}
|
|
57
|
+
const realRoot = await realpath(root), actual = await realpath(path);
|
|
58
|
+
if (!actual.startsWith(realRoot + sep) || !(await lstat(path)).isFile()) return null;
|
|
59
|
+
return actual;
|
|
60
|
+
} catch (e) { if (e.code === 'ENOENT' || e.code === 'ENOTDIR') return null; throw e; }
|
|
61
|
+
}
|
|
62
|
+
export async function overlayFiles(context, folder) {
|
|
63
|
+
const base = await presetDesign(context);
|
|
64
|
+
async function walk(root, dir) {
|
|
65
|
+
let entries; try { entries = await readdir(join(root, dir), { withFileTypes: true }); } catch (e) { if (e.code === 'ENOENT' || e.code === 'ENOTDIR') return []; throw e; }
|
|
66
|
+
return (await Promise.all(entries.filter(e => !e.name.startsWith('.')).map(e => {
|
|
67
|
+
const path = [dir, e.name].join('/');
|
|
68
|
+
return e.isDirectory() ? walk(root, path) : e.isFile() ? [path] : [];
|
|
69
|
+
}))).flat();
|
|
70
|
+
}
|
|
71
|
+
const names = new Set([...(base ? await walk(base, folder) : []), ...await walk(context.designDir, folder)]);
|
|
72
|
+
const files = [];
|
|
73
|
+
for (const name of [...names].sort()) { const path = await overlayPath(context, name, base); if (path) files.push({ name, path }); }
|
|
74
|
+
return files;
|
|
75
|
+
}
|
package/package.json
CHANGED
|
@@ -1,12 +1,39 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@raketa-cloud/design-cli",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.1.1",
|
|
4
4
|
"description": "CLI for building and previewing local design systems",
|
|
5
|
-
"
|
|
6
|
-
|
|
7
|
-
|
|
5
|
+
"repository": {
|
|
6
|
+
"type": "git",
|
|
7
|
+
"url": "https://github.com/studioraketa/design-system-tools.git"
|
|
8
|
+
},
|
|
9
|
+
"bin": {
|
|
10
|
+
"design": "cli.mjs"
|
|
11
|
+
},
|
|
12
|
+
"files": [
|
|
13
|
+
"*.mjs",
|
|
14
|
+
"catalog/",
|
|
15
|
+
"showcase/",
|
|
16
|
+
"tokens/",
|
|
17
|
+
"skills/"
|
|
18
|
+
],
|
|
19
|
+
"publishConfig": {
|
|
20
|
+
"access": "public"
|
|
21
|
+
},
|
|
8
22
|
"type": "module",
|
|
9
|
-
"engines": {
|
|
10
|
-
|
|
11
|
-
|
|
23
|
+
"engines": {
|
|
24
|
+
"node": ">=22"
|
|
25
|
+
},
|
|
26
|
+
"exports": {
|
|
27
|
+
"./showcase/serve.mjs": "./showcase/serve.mjs",
|
|
28
|
+
"./showcase/assets.mjs": "./showcase/assets.mjs",
|
|
29
|
+
"./showcase/asset-grid.mjs": "./showcase/asset-grid.mjs",
|
|
30
|
+
"./cli.mjs": "./cli.mjs"
|
|
31
|
+
},
|
|
32
|
+
"scripts": {
|
|
33
|
+
"test": "node --test tests/*.test.mjs"
|
|
34
|
+
},
|
|
35
|
+
"dependencies": {
|
|
36
|
+
"@tailwindcss/cli": "^4.3.5",
|
|
37
|
+
"tailwindcss": "^4.3.5"
|
|
38
|
+
}
|
|
12
39
|
}
|
package/preset.mjs
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import { execFile } from 'node:child_process';
|
|
2
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
3
|
+
import { lstat, mkdir, mkdtemp, readFile, realpath, rename, rm, symlink, writeFile } from 'node:fs/promises';
|
|
4
|
+
import { isAbsolute, join, resolve, sep } from 'node:path';
|
|
5
|
+
import { promisify } from 'node:util';
|
|
6
|
+
|
|
7
|
+
const exec = promisify(execFile);
|
|
8
|
+
// Honor the user's Git credentials and SSH configuration while avoiding prompts.
|
|
9
|
+
const env = { ...process.env, GIT_TERMINAL_PROMPT: '0' };
|
|
10
|
+
async function git(args, cwd) {
|
|
11
|
+
const { stdout } = await exec('git', ['-c', 'core.hooksPath=/dev/null', '-c', 'core.fsmonitor=false', ...args], { cwd, env, maxBuffer: 10 * 1024 * 1024 });
|
|
12
|
+
return stdout.trim();
|
|
13
|
+
}
|
|
14
|
+
function presetConfig(context) {
|
|
15
|
+
const preset = context.config?.preset;
|
|
16
|
+
if (preset == null) return null;
|
|
17
|
+
if (!preset || typeof preset !== 'object' || Array.isArray(preset) || typeof preset.repo !== 'string' || !preset.repo.trim() || preset.repo !== preset.repo.trim() || /[\x00-\x1f]/.test(preset.repo) || preset.repo.startsWith('-') || preset.repo.includes('::') || (preset.repo.includes('://') && !/^(?:https|ssh|git|file):\/\//i.test(preset.repo)) || typeof preset.ref !== 'string' || !preset.ref.trim() || preset.ref !== preset.ref.trim() || preset.ref.startsWith('-') || /[\x00-\x20\x7f]/.test(preset.ref)) throw new Error('Invalid config.preset: repo and ref are required');
|
|
18
|
+
return { repo: preset.repo, ref: preset.ref };
|
|
19
|
+
}
|
|
20
|
+
function source(repo, context) {
|
|
21
|
+
if (isAbsolute(repo) || repo.includes('://') || /^[^/]+@[^:]+:/.test(repo)) return repo;
|
|
22
|
+
return resolve(context.projectDir || process.cwd(), repo);
|
|
23
|
+
}
|
|
24
|
+
function cachePath(context, lock) {
|
|
25
|
+
const key = createHash('sha256').update(JSON.stringify([lock.repo, lock.ref, lock.commit])).digest('hex');
|
|
26
|
+
return join(context.designDir, '.preset', key);
|
|
27
|
+
}
|
|
28
|
+
async function readLock(context, preset) {
|
|
29
|
+
let lock;
|
|
30
|
+
try { lock = JSON.parse(await readFile(join(context.designDir, 'preset.lock.json'), 'utf8')); }
|
|
31
|
+
catch (error) { throw new Error(`Cannot read preset lock; run design preset update: ${error.message}`); }
|
|
32
|
+
if (!lock || typeof lock !== 'object' || Array.isArray(lock) || typeof lock.repo !== 'string' || !lock.repo || typeof lock.ref !== 'string' || !lock.ref || typeof lock.commit !== 'string' || !/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(lock.commit) || Object.keys(lock).sort().join(',') !== 'commit,ref,repo') throw new Error('Malformed preset lock; run design preset update');
|
|
33
|
+
if (lock.repo !== preset.repo || lock.ref !== preset.ref) throw new Error('Preset lock does not match config.preset; run design preset update');
|
|
34
|
+
return lock;
|
|
35
|
+
}
|
|
36
|
+
async function validateCheckout(context, lock) {
|
|
37
|
+
const path = cachePath(context, lock);
|
|
38
|
+
try {
|
|
39
|
+
if (!(await lstat(path)).isDirectory()) throw new Error('not a directory');
|
|
40
|
+
const [head, origin, status] = await Promise.all([
|
|
41
|
+
git(['rev-parse', '--verify', 'HEAD^{commit}'], path),
|
|
42
|
+
git(['config', '--get', 'remote.origin.url'], path),
|
|
43
|
+
git(['status', '--porcelain', '--untracked-files=all', '--ignore-submodules=none'], path),
|
|
44
|
+
]);
|
|
45
|
+
if (head !== lock.commit || origin !== source(lock.repo, context) || status) throw new Error('checkout differs from lock or has local changes');
|
|
46
|
+
return path;
|
|
47
|
+
} catch (error) { throw new Error(`Preset checkout missing or invalid; run design preset install: ${error.message}`); }
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// This function only returns data paths; it never imports or executes preset files.
|
|
51
|
+
export async function resolvePreset(context) {
|
|
52
|
+
if (process.env.DESIGN_PRESET_DIR !== undefined) {
|
|
53
|
+
if (process.env.CI !== undefined) throw new Error('DESIGN_PRESET_DIR is forbidden when CI is set');
|
|
54
|
+
if (!process.env.DESIGN_PRESET_DIR) throw new Error('DESIGN_PRESET_DIR must not be empty');
|
|
55
|
+
const path = await realpath(resolve(process.env.DESIGN_PRESET_DIR));
|
|
56
|
+
if (!(await lstat(path)).isDirectory()) throw new Error('DESIGN_PRESET_DIR must be a directory');
|
|
57
|
+
return path;
|
|
58
|
+
}
|
|
59
|
+
const preset = presetConfig(context);
|
|
60
|
+
if (!preset) return null;
|
|
61
|
+
return validateCheckout(context, await readLock(context, preset));
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// Runtime assets are linked, never copied or executed, so local edits remain visible.
|
|
65
|
+
async function linkRuntime(preset, cache) {
|
|
66
|
+
const assets = join(preset, 'raketa');
|
|
67
|
+
let target;
|
|
68
|
+
try {
|
|
69
|
+
target = await realpath(assets);
|
|
70
|
+
if (!target.startsWith(await realpath(preset) + sep) || !(await lstat(target)).isDirectory()) throw new Error('not a directory inside the preset');
|
|
71
|
+
} catch (error) { throw new Error(`Invalid preset runtime directory ${assets}: ${error.message}`); }
|
|
72
|
+
const runtime = join(cache, 'runtime');
|
|
73
|
+
try {
|
|
74
|
+
if (!(await lstat(runtime)).isSymbolicLink()) throw new Error(`Refusing to replace non-symlink runtime path: ${runtime}`);
|
|
75
|
+
} catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
76
|
+
const temporary = join(cache, `.runtime-${randomUUID()}`);
|
|
77
|
+
try {
|
|
78
|
+
await symlink(target, temporary, 'dir');
|
|
79
|
+
await rename(temporary, runtime);
|
|
80
|
+
} finally { await rm(temporary, { force: true }); }
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export async function refreshPresetRuntime(context) {
|
|
84
|
+
const preset = await resolvePreset(context);
|
|
85
|
+
if (!preset) return;
|
|
86
|
+
await withOperation(context, cache => linkRuntime(preset, cache));
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function forbidCIOverride() {
|
|
90
|
+
if (process.env.DESIGN_PRESET_DIR !== undefined && process.env.CI !== undefined) throw new Error('DESIGN_PRESET_DIR is forbidden when CI is set');
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
async function withOperation(context, action) {
|
|
94
|
+
const cache = join(context.designDir, '.preset');
|
|
95
|
+
await mkdir(cache, { recursive: true });
|
|
96
|
+
// Ignore the entire disposable cache, including this ignore file itself.
|
|
97
|
+
await writeFile(join(cache, '.gitignore'), '*\n');
|
|
98
|
+
const mutex = join(cache, '.operation');
|
|
99
|
+
try { await mkdir(mutex); } catch (error) {
|
|
100
|
+
if (error.code === 'EEXIST') throw new Error('Another preset operation is in progress');
|
|
101
|
+
throw error;
|
|
102
|
+
}
|
|
103
|
+
try { return await action(cache); } finally { await rm(mutex, { recursive: true, force: true }); }
|
|
104
|
+
}
|
|
105
|
+
async function checkout(context, lock, temp) {
|
|
106
|
+
await git(['clone', '--no-checkout', '--no-hardlinks', '--', source(lock.repo, context), temp], context.projectDir);
|
|
107
|
+
if (!lock.commit) {
|
|
108
|
+
await git(['fetch', '--no-tags', 'origin', lock.ref], temp);
|
|
109
|
+
lock.commit = await git(['rev-parse', '--verify', 'FETCH_HEAD^{commit}'], temp);
|
|
110
|
+
} else {
|
|
111
|
+
try { await git(['cat-file', '-e', `${lock.commit}^{commit}`], temp); }
|
|
112
|
+
catch { await git(['fetch', '--no-tags', 'origin', lock.commit], temp); }
|
|
113
|
+
}
|
|
114
|
+
if (!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(lock.commit)) throw new Error('Invalid preset commit');
|
|
115
|
+
await git(['checkout', '--detach', '--force', lock.commit], temp);
|
|
116
|
+
}
|
|
117
|
+
async function install(context, lock, cache) {
|
|
118
|
+
const temp = await mkdtemp(join(cache, '.staging-'));
|
|
119
|
+
try {
|
|
120
|
+
await checkout(context, lock, temp);
|
|
121
|
+
const target = cachePath(context, lock);
|
|
122
|
+
// Existing immutable checkouts are only reused if still valid.
|
|
123
|
+
try { await validateCheckout(context, lock); return target; } catch { /* replace invalid checkout */ }
|
|
124
|
+
const old = join(cache, `.old-${randomUUID()}`);
|
|
125
|
+
try { await rename(target, old); } catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
126
|
+
try { await rename(temp, target); } catch (error) {
|
|
127
|
+
try { await rename(old, target); } catch { /* no previous checkout */ }
|
|
128
|
+
throw error;
|
|
129
|
+
} finally { await rm(old, { recursive: true, force: true }); }
|
|
130
|
+
return target;
|
|
131
|
+
} finally { await rm(temp, { recursive: true, force: true }); }
|
|
132
|
+
}
|
|
133
|
+
export async function updatePreset(context) {
|
|
134
|
+
forbidCIOverride();
|
|
135
|
+
const preset = presetConfig(context);
|
|
136
|
+
if (!preset) throw new Error('config.preset is required');
|
|
137
|
+
return withOperation(context, async cache => {
|
|
138
|
+
const lock = { ...preset, commit: '' };
|
|
139
|
+
const path = await install(context, lock, cache);
|
|
140
|
+
await linkRuntime(path, cache);
|
|
141
|
+
const temporary = join(context.designDir, `.preset-lock-${randomUUID()}`);
|
|
142
|
+
try {
|
|
143
|
+
await writeFile(temporary, JSON.stringify(lock, null, 2) + '\n', { flag: 'wx' });
|
|
144
|
+
await rename(temporary, join(context.designDir, 'preset.lock.json'));
|
|
145
|
+
} finally { await rm(temporary, { force: true }); }
|
|
146
|
+
return path;
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
export async function installPreset(context) {
|
|
150
|
+
forbidCIOverride();
|
|
151
|
+
const preset = presetConfig(context);
|
|
152
|
+
if (!preset) throw new Error('config.preset is required');
|
|
153
|
+
return withOperation(context, async cache => {
|
|
154
|
+
const path = await install(context, await readLock(context, preset), cache);
|
|
155
|
+
await linkRuntime(path, cache);
|
|
156
|
+
return path;
|
|
157
|
+
});
|
|
158
|
+
}
|
package/preview-css.mjs
CHANGED
|
@@ -1,22 +1,49 @@
|
|
|
1
1
|
import { spawn } from 'node:child_process';
|
|
2
|
-
import {
|
|
2
|
+
import { access } from 'node:fs/promises';
|
|
3
|
+
import { createRequire } from 'node:module';
|
|
4
|
+
import { dirname, resolve } from 'node:path';
|
|
5
|
+
import { themePath, tokenSource } from './config.mjs';
|
|
6
|
+
import { overlayFiles, presetDesign } from './overlay.mjs';
|
|
7
|
+
import { renderTheme } from './build.mjs';
|
|
3
8
|
|
|
4
|
-
|
|
5
|
-
|
|
9
|
+
const require = createRequire(import.meta.url);
|
|
10
|
+
const cli = resolve(dirname(require.resolve('@tailwindcss/cli/package.json')), 'dist/index.mjs');
|
|
11
|
+
const tailwind = require.resolve('tailwindcss/index.css');
|
|
12
|
+
|
|
13
|
+
// Preview compilation is independent of the host application's toolchain.
|
|
14
|
+
export async function previewCss(context) {
|
|
15
|
+
const { projectDir, designDir, config } = context;
|
|
16
|
+
const { input: tokens } = await tokenSource(context);
|
|
17
|
+
const base = await presetDesign(context);
|
|
18
|
+
const dynamic = !!base || !!config?.tokenOverrides;
|
|
19
|
+
const sources = dynamic ? [...await overlayFiles(context, 'components'), ...await overlayFiles(context, 'layouts')] : [];
|
|
20
|
+
const extraCss = config?.preview?.css;
|
|
21
|
+
if (extraCss !== undefined && (typeof extraCss !== 'string' || !extraCss.trim())) throw new Error('preview.css must be a non-empty path');
|
|
22
|
+
const output = config ? themePath(context) : null;
|
|
23
|
+
let generated = false;
|
|
24
|
+
if (output) {
|
|
25
|
+
try { await access(output); generated = true; } catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
26
|
+
}
|
|
27
|
+
const blocks = (tokens.blocks || []).filter(block => block.selector === '@theme' || block.selector === '@theme inline').map(block =>
|
|
28
|
+
`${block.selector} {\n${Object.entries(block.tokens).map(([name, token]) => ` ${name}: ${token.$value};`).join('\n')}\n}`
|
|
29
|
+
);
|
|
6
30
|
const input = [
|
|
7
|
-
`@import ${JSON.stringify(
|
|
8
|
-
`@
|
|
9
|
-
`@
|
|
31
|
+
`@import ${JSON.stringify(tailwind)} source(none);`,
|
|
32
|
+
...(dynamic ? [await renderTheme(context)] : generated ? [`@import ${JSON.stringify(output)};`] : []),
|
|
33
|
+
...(extraCss ? [`@import ${JSON.stringify(resolve(projectDir, extraCss))};`] : []),
|
|
34
|
+
...(typeof tokens.variant === 'string' ? [tokens.variant] : []),
|
|
35
|
+
...blocks,
|
|
36
|
+
...(dynamic ? sources.map(file => `@source ${JSON.stringify(file.path)};`) : [`@source ${JSON.stringify(resolve(designDir, 'components'))};`, `@source ${JSON.stringify(resolve(designDir, 'layouts'))};`]),
|
|
10
37
|
'@source inline("bg-{red,green,orange,yellow}-{50,{100..900..100},950}");'
|
|
11
38
|
].join('\n');
|
|
12
39
|
return new Promise((resolvePromise, reject) => {
|
|
13
|
-
const child = spawn(
|
|
14
|
-
let
|
|
15
|
-
child.stdout.setEncoding('utf8').on('data', chunk => {
|
|
40
|
+
const child = spawn(process.execPath, [cli, '-i', '-'], { cwd: projectDir, stdio: ['pipe', 'pipe', 'pipe'] });
|
|
41
|
+
let outputCss = '', errors = '';
|
|
42
|
+
child.stdout.setEncoding('utf8').on('data', chunk => { outputCss += chunk; });
|
|
16
43
|
child.stderr.setEncoding('utf8').on('data', chunk => { errors += chunk; });
|
|
17
44
|
child.on('error', reject);
|
|
18
45
|
child.stdin.on('error', error => { if (error.code !== 'EPIPE') reject(error); });
|
|
19
|
-
child.on('close', code => code === 0 ? resolvePromise(
|
|
46
|
+
child.on('close', code => code === 0 ? resolvePromise(outputCss) : reject(new Error(`Preview CSS compilation failed (${code}): ${errors}`)));
|
|
20
47
|
child.stdin.end(input);
|
|
21
48
|
});
|
|
22
49
|
}
|
package/showcase/serve.mjs
CHANGED
|
@@ -1,13 +1,15 @@
|
|
|
1
1
|
import { createServer } from 'node:http';
|
|
2
2
|
import { watch } from 'node:fs';
|
|
3
|
-
import { lstat, readFile,
|
|
4
|
-
import { dirname, extname, join,
|
|
3
|
+
import { lstat, readFile, realpath } from 'node:fs/promises';
|
|
4
|
+
import { dirname, extname, join, sep } from 'node:path';
|
|
5
5
|
import { fileURLToPath } from 'node:url';
|
|
6
6
|
import { resolveThemeDetails, cssName } from '../tokens/themes.mjs';
|
|
7
7
|
import { scanAssets } from './assets.mjs';
|
|
8
8
|
import { assetGrid } from './asset-grid.mjs';
|
|
9
9
|
import { loadConfig, catalog, themePath } from '../config.mjs';
|
|
10
10
|
import { previewCss } from '../preview-css.mjs';
|
|
11
|
+
import { overlayFiles, overlayPath, presetDesign } from '../overlay.mjs';
|
|
12
|
+
import { renderTheme } from '../build.mjs';
|
|
11
13
|
const toolDir = dirname(fileURLToPath(import.meta.url));
|
|
12
14
|
const context = await loadConfig();
|
|
13
15
|
const root = context.designDir;
|
|
@@ -36,28 +38,11 @@ async function designName() {
|
|
|
36
38
|
return name.trim();
|
|
37
39
|
}
|
|
38
40
|
async function optionalFontsLink() {
|
|
39
|
-
|
|
40
|
-
return (await stat(join(root, 'showcase-fonts.css'))).isFile() ? '<link rel="stylesheet" href="/showcase-fonts.css">' : '';
|
|
41
|
-
} catch (error) {
|
|
42
|
-
if (error.code === 'ENOENT') return '';
|
|
43
|
-
throw error;
|
|
44
|
-
}
|
|
41
|
+
return await overlayPath(await loadConfig(), 'showcase-fonts.css') ? '<link rel="stylesheet" href="/showcase-fonts.css">' : '';
|
|
45
42
|
}
|
|
46
43
|
|
|
47
44
|
async function files(folder) {
|
|
48
|
-
|
|
49
|
-
async function walk(dir) {
|
|
50
|
-
let entries;
|
|
51
|
-
try { entries = await readdir(dir, { withFileTypes: true }); }
|
|
52
|
-
catch (error) { if (error.code === 'ENOENT') return []; throw error; }
|
|
53
|
-
const nested = await Promise.all(entries.map(async entry => {
|
|
54
|
-
const path = join(dir, entry.name);
|
|
55
|
-
if (entry.isDirectory()) return walk(path);
|
|
56
|
-
return entry.isFile() ? [relative(root, path)] : [];
|
|
57
|
-
}));
|
|
58
|
-
return nested.flat();
|
|
59
|
-
}
|
|
60
|
-
return (await walk(start)).sort((a, b) => a.localeCompare(b));
|
|
45
|
+
return (await overlayFiles(await loadConfig(), folder)).map(file => file.name);
|
|
61
46
|
}
|
|
62
47
|
function tokensIn(group, path = []) {
|
|
63
48
|
if (!group || typeof group !== 'object') return [];
|
|
@@ -127,7 +112,8 @@ async function exampleIndex(folder) {
|
|
|
127
112
|
if (!examples.length) return '<p class="empty">No ' + escape(folder) + ' yet.</p>';
|
|
128
113
|
const items = await Promise.all(examples.map(async path => {
|
|
129
114
|
const companion = join(dirname(path), 'docs.md');
|
|
130
|
-
const
|
|
115
|
+
const companionPath = await overlayPath(await loadConfig(), companion);
|
|
116
|
+
const markdown = companionPath ? await readFile(companionPath, 'utf8') : '';
|
|
131
117
|
const name = dirname(path).split(sep).pop().replace(/[-_]/g, ' ');
|
|
132
118
|
const title = markdown.match(/^#\s+(.+)$/m)?.[1] || name;
|
|
133
119
|
return '<li><a class="example-title" href="' + urlFor(path) + '">' + escape(title) + '</a><span class="links"><a href="' + urlFor(path) + '">Preview ↗</a>' + (markdown ? '<a href="' + urlFor(companion) + '">Docs ↗</a>' : '') + '</span></li>';
|
|
@@ -135,7 +121,23 @@ async function exampleIndex(folder) {
|
|
|
135
121
|
return '<ul class="example-list">' + items.join('') + '</ul>';
|
|
136
122
|
}
|
|
137
123
|
async function assetIndex() {
|
|
138
|
-
const
|
|
124
|
+
const current = await loadConfig();
|
|
125
|
+
const base = await presetDesign(current);
|
|
126
|
+
async function safeScan(directory) {
|
|
127
|
+
const info = await lstat(join(directory, 'assets')).catch(error => { if (error.code === 'ENOENT') return null; throw error; });
|
|
128
|
+
return info?.isDirectory() ? scanAssets(directory) : { categories: [] };
|
|
129
|
+
}
|
|
130
|
+
const local = await safeScan(root);
|
|
131
|
+
const shared = base ? await safeScan(base) : { categories: [] };
|
|
132
|
+
const merged = new Map(shared.categories.map(category => [category.name, category]));
|
|
133
|
+
for (const category of local.categories) {
|
|
134
|
+
const prior = merged.get(category.name);
|
|
135
|
+
if (!prior) { merged.set(category.name, category); continue; }
|
|
136
|
+
const assets = new Map(prior.assets.map(asset => [asset.name, asset]));
|
|
137
|
+
for (const asset of category.assets) assets.set(asset.name, asset);
|
|
138
|
+
merged.set(category.name, { ...prior, ...category, docs: category.docs || prior.docs, invalid: [...prior.invalid, ...category.invalid], assets: [...assets.values()].sort((a, b) => a.name.localeCompare(b.name)) });
|
|
139
|
+
}
|
|
140
|
+
const categories = [...merged.values()].sort((a, b) => a.name.localeCompare(b.name));
|
|
139
141
|
if (!categories.length) return '<p class="empty">No asset categories included.</p>';
|
|
140
142
|
return categories.map(category => {
|
|
141
143
|
const title = category.name.replace(/[-_]/g, ' ');
|
|
@@ -213,7 +215,8 @@ function scheduleReload() {
|
|
|
213
215
|
clearTimeout(reloadTimer);
|
|
214
216
|
reloadTimer = setTimeout(() => { for (const client of clients) client.write('event: reload\ndata: changed\n\n'); }, 150);
|
|
215
217
|
}
|
|
216
|
-
|
|
218
|
+
const sharedRoot = await presetDesign(context);
|
|
219
|
+
for (const directory of [...new Set([root, ...(sharedRoot ? [sharedRoot] : []), ...(!toolDir.startsWith(root + sep) && toolDir !== root ? [toolDir] : [])])]) {
|
|
217
220
|
const watcher = watch(directory, { recursive: true }, scheduleReload);
|
|
218
221
|
watcher.on('error', error => console.error('Live reload watcher failed:', error));
|
|
219
222
|
}
|
|
@@ -252,9 +255,11 @@ createServer(async (req, res) => {
|
|
|
252
255
|
return res.end(req.method === 'HEAD' ? undefined : withReload(html));
|
|
253
256
|
}
|
|
254
257
|
if (pathname === '/__showcase/theme.css') {
|
|
255
|
-
const
|
|
256
|
-
|
|
257
|
-
const
|
|
258
|
+
const current = await loadConfig();
|
|
259
|
+
const output = themePath(current);
|
|
260
|
+
const dynamic = !!(await presetDesign(current)) || !!current.config?.tokenOverrides;
|
|
261
|
+
if (!dynamic && !(await lstat(output).catch(error => { if (error.code === 'ENOENT') return null; throw error; }))?.isFile()) { res.writeHead(404); return res.end('Not found'); }
|
|
262
|
+
const css = dynamic ? await renderTheme(current) : await readFile(output);
|
|
258
263
|
res.writeHead(200, { 'Content-Type': mime['.css'], 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' });
|
|
259
264
|
return res.end(req.method === 'HEAD' ? undefined : css);
|
|
260
265
|
}
|
|
@@ -275,10 +280,11 @@ createServer(async (req, res) => {
|
|
|
275
280
|
return res.end(req.method === 'HEAD' ? undefined : css);
|
|
276
281
|
}
|
|
277
282
|
if (pathname.includes('\0')) { res.writeHead(400); return res.end('Bad request'); }
|
|
278
|
-
const
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
283
|
+
const name = pathname.slice(1);
|
|
284
|
+
const segments = name.split('/');
|
|
285
|
+
if (segments.some(part => !part || part === '..' || part.startsWith('.')) || !['components', 'layouts', 'assets', 'DESIGN.md', '_theme_preview.html', 'showcase-fonts.css'].includes(segments[0])) { res.writeHead(404); return res.end('Not found'); }
|
|
286
|
+
const path = await overlayPath(await loadConfig(), name);
|
|
287
|
+
if (!path) { res.writeHead(404); return res.end('Not found'); }
|
|
282
288
|
const data = await readFile(path);
|
|
283
289
|
const extension = extname(path).toLowerCase();
|
|
284
290
|
res.writeHead(200, { 'Content-Type': mime[extension] || 'application/octet-stream', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' });
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: design-system
|
|
3
|
+
description: Use the project's .design system and its tooling when inspecting, designing, building, or changing interfaces, design tokens, components, layouts, or previews.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Design system workflow
|
|
7
|
+
|
|
8
|
+
Before designing or changing an interface, read `.design/DESIGN.md`, the relevant rules under `.design/rules/`, and the documentation and previews for the patterns involved. The design system is authoritative; flag conflicts with host conventions and ask. Accessibility takes precedence.
|
|
9
|
+
|
|
10
|
+
Use the project's tokens, assets and documented patterns. Preserve semantic structure, reading order, responsive behavior, keyboard access and visible focus. Report missing patterns or assets; do not invent imagery. Document new reusable patterns and known gaps, and ask when a necessary design decision is unresolved.
|
|
11
|
+
|
|
12
|
+
For design-system work, edit previews directly and keep them consistent with reusable styles and documentation. Follow the project's styling conventions.
|
|
13
|
+
|
|
14
|
+
## Tooling and validation
|
|
15
|
+
|
|
16
|
+
Requires Node 22+. Run these commands from the host project root:
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
npx @raketa-cloud/design-cli generate
|
|
20
|
+
npx @raketa-cloud/design-cli serve
|
|
21
|
+
npx @raketa-cloud/design-cli new component my-pattern
|
|
22
|
+
npx @raketa-cloud/design-cli new layout my-pattern
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
Generate before serving the showcase at `http://127.0.0.1:4174`; set `PORT` to use another port. The CLI bundles the Tailwind compiler for previews and does not require Rails or a host Tailwind installation. If previews depend on additional Tailwind-compatible CSS, set `preview.css` in `.design/config.json` to its project-relative path; validate that the preview matches the host. The `new` commands scaffold placeholders without overwriting existing patterns. If the project has not been initialized, run `npx @raketa-cloud/design-cli init`; it refuses to overwrite existing design or skill paths.
|
|
26
|
+
|
|
27
|
+
Edit tokens and component CSS, not generated CSS. The build does not regenerate previews or wire the host application. After relevant changes, generate, run focused tests, and inspect previews at desktop and narrow widths and in supported themes. Validate production integration separately and report gaps or anything unverified.
|