@luxalgo/vela-ui 0.3.0 → 0.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.
Files changed (167) hide show
  1. package/CHANGELOG.md +153 -132
  2. package/LICENSE +201 -201
  3. package/NOTICE +28 -28
  4. package/README.md +86 -86
  5. package/cli/engine.mjs +282 -282
  6. package/cli/index.mjs +154 -154
  7. package/dist/callout-bubble.js +2 -2
  8. package/dist/checkbox.js +2 -2
  9. package/dist/{chunk-KKS6NEGI.js → chunk-BWSOMG3G.js} +1 -1
  10. package/dist/chunk-GUIYFQ27.js +30 -0
  11. package/dist/{chunk-B2EZB5ZG.js → chunk-KUWTI2PE.js} +2 -2
  12. package/dist/{chunk-WWHNUKSZ.js → chunk-QGWAN3EP.js} +2 -2
  13. package/dist/{chunk-TBXUF5YX.js → chunk-RH53NQGE.js} +18 -4
  14. package/dist/{chunk-IOOYDSSK.js → chunk-SKFAYTDK.js} +1 -1
  15. package/dist/{chunk-OQXFQMZM.js → chunk-TGJNHUYV.js} +2 -2
  16. package/dist/{chunk-UEO6W37Z.js → chunk-VC7SVSDK.js} +1 -1
  17. package/dist/{chunk-OJ2SEMN6.js → chunk-YT2BSP7O.js} +1 -1
  18. package/dist/collapsible.js +1 -1
  19. package/dist/color-picker.js +4 -4
  20. package/dist/context-menu.js +3 -3
  21. package/dist/dialog.js +3 -3
  22. package/dist/donut.d.ts +1 -1
  23. package/dist/drawer.js +1 -1
  24. package/dist/dropdown-menu.js +3 -3
  25. package/dist/field.js +8 -8
  26. package/dist/{stat.d.ts → figure.d.ts} +9 -9
  27. package/dist/figure.js +41 -0
  28. package/dist/glyph-select.js +3 -3
  29. package/dist/index.d.ts +2 -2
  30. package/dist/index.js +1 -1
  31. package/dist/manifest.json +74 -74
  32. package/dist/number-input.js +2 -2
  33. package/dist/popover.js +2 -2
  34. package/dist/select.d.ts +1 -1
  35. package/dist/select.js +4 -4
  36. package/dist/slider.js +1 -1
  37. package/dist/sort-button.js +1 -1
  38. package/dist/switch.js +1 -1
  39. package/dist/tabs.js +1 -1
  40. package/dist/{theme-Ct-q58xz.d.ts → theme-TefB8vtl.d.ts} +2 -2
  41. package/dist/theme.d.ts +2 -2
  42. package/dist/theme.js +1 -1
  43. package/dist/theme.schema.json +30 -30
  44. package/dist/toast.d.ts +2 -2
  45. package/dist/toast.js +1 -1
  46. package/dist/toggle-group.js +1 -1
  47. package/dist/tooltip.js +1 -1
  48. package/dist/zag.d.ts +11 -2
  49. package/dist/zag.js +1 -1
  50. package/docs/theming.md +217 -217
  51. package/docs/what-to-change.md +20 -20
  52. package/docs/writing-a-component.md +250 -250
  53. package/llms.txt +3 -3
  54. package/package.json +90 -90
  55. package/registry/badge.ts +119 -119
  56. package/registry/bar-chart.ts +215 -215
  57. package/registry/button.ts +387 -387
  58. package/registry/callout-bubble.ts +347 -347
  59. package/registry/card.ts +379 -379
  60. package/registry/checkbox.ts +234 -234
  61. package/registry/collapsible.ts +271 -271
  62. package/registry/color-picker.ts +582 -582
  63. package/registry/context-menu.ts +208 -208
  64. package/registry/data-table.ts +215 -215
  65. package/registry/date-picker.ts +483 -483
  66. package/registry/dialog.ts +551 -551
  67. package/registry/donut.ts +145 -145
  68. package/registry/drawer.ts +636 -636
  69. package/registry/dropdown-menu.ts +762 -762
  70. package/registry/empty.ts +91 -91
  71. package/registry/field.ts +584 -584
  72. package/registry/{stat.ts → figure.ts} +96 -96
  73. package/registry/glyph-select.ts +268 -268
  74. package/registry/hover-card.ts +222 -222
  75. package/registry/input-group.ts +229 -229
  76. package/registry/input.ts +181 -181
  77. package/registry/item.ts +376 -376
  78. package/registry/kbd.ts +64 -64
  79. package/registry/line-chart.ts +218 -218
  80. package/registry/month-grid.ts +328 -328
  81. package/registry/number-input.ts +443 -443
  82. package/registry/popover.ts +368 -368
  83. package/registry/scatter-chart.ts +221 -221
  84. package/registry/select.ts +620 -620
  85. package/registry/slider.ts +259 -259
  86. package/registry/sort-button.ts +189 -189
  87. package/registry/sparkline.ts +114 -114
  88. package/registry/switch.ts +205 -205
  89. package/registry/tabs.ts +426 -426
  90. package/registry/text-area.ts +186 -186
  91. package/registry/toast.ts +965 -965
  92. package/registry/toggle-group.ts +295 -295
  93. package/registry/tooltip.ts +156 -156
  94. package/registry/treemap.ts +847 -847
  95. package/skills/theming-vela-ui/SKILL.md +137 -137
  96. package/skills/using-vela-ui-components/SKILL.md +139 -139
  97. package/skills/writing-vela-ui-components/SKILL.md +163 -163
  98. package/src/components/badge.ts +119 -119
  99. package/src/components/bar-chart.ts +215 -215
  100. package/src/components/button.ts +387 -387
  101. package/src/components/callout-bubble.ts +347 -347
  102. package/src/components/card.ts +379 -379
  103. package/src/components/checkbox.ts +234 -234
  104. package/src/components/collapsible.ts +271 -271
  105. package/src/components/color-picker.ts +582 -582
  106. package/src/components/context-menu.ts +208 -208
  107. package/src/components/data-table.ts +215 -215
  108. package/src/components/date-picker.ts +483 -483
  109. package/src/components/dialog.ts +551 -551
  110. package/src/components/donut.ts +145 -145
  111. package/src/components/drawer.ts +636 -636
  112. package/src/components/dropdown-menu.ts +762 -762
  113. package/src/components/empty.ts +91 -91
  114. package/src/components/field.ts +584 -584
  115. package/src/components/{stat.ts → figure.ts} +96 -96
  116. package/src/components/glyph-select.ts +268 -268
  117. package/src/components/hover-card.ts +222 -222
  118. package/src/components/input-group.ts +229 -229
  119. package/src/components/input.ts +181 -181
  120. package/src/components/item.ts +376 -376
  121. package/src/components/kbd.ts +64 -64
  122. package/src/components/line-chart.ts +218 -218
  123. package/src/components/month-grid.ts +328 -328
  124. package/src/components/number-input.ts +443 -443
  125. package/src/components/popover.ts +368 -368
  126. package/src/components/scatter-chart.ts +221 -221
  127. package/src/components/select.ts +620 -620
  128. package/src/components/slider.ts +259 -259
  129. package/src/components/sort-button.ts +189 -189
  130. package/src/components/sparkline.ts +114 -114
  131. package/src/components/switch.ts +205 -205
  132. package/src/components/tabs.ts +426 -426
  133. package/src/components/text-area.ts +186 -186
  134. package/src/components/toast.ts +965 -965
  135. package/src/components/toggle-group.ts +295 -295
  136. package/src/components/tooltip.ts +156 -156
  137. package/src/components/treemap.ts +847 -847
  138. package/src/index.ts +24 -24
  139. package/src/lib/calendar.ts +117 -117
  140. package/src/lib/chart.ts +72 -72
  141. package/src/lib/color.ts +89 -89
  142. package/src/lib/component-index.ts +163 -163
  143. package/src/lib/css.ts +48 -48
  144. package/src/lib/define.ts +45 -45
  145. package/src/lib/dispose.ts +36 -36
  146. package/src/lib/h.ts +55 -55
  147. package/src/lib/headless.ts +16 -16
  148. package/src/lib/i18n.ts +30 -30
  149. package/src/lib/icons.ts +244 -244
  150. package/src/lib/kit-text.ts +26 -26
  151. package/src/lib/page.ts +24 -24
  152. package/src/lib/palette.ts +81 -81
  153. package/src/lib/placement.ts +188 -188
  154. package/src/lib/scope.ts +135 -135
  155. package/src/lib/styles.ts +53 -53
  156. package/src/lib/surface-events.ts +31 -31
  157. package/src/lib/surface-exit.ts +87 -87
  158. package/src/lib/t.ts +68 -68
  159. package/src/lib/theme.ts +684 -670
  160. package/src/lib/tokens.ts +110 -110
  161. package/src/lib/variants.ts +32 -32
  162. package/src/lib/zag.ts +61 -46
  163. package/stylelint/index.mjs +60 -60
  164. package/stylelint/lint.mjs +81 -81
  165. package/stylelint/plugin.mjs +115 -115
  166. package/dist/chunk-P4MTEMT7.js +0 -23
  167. package/dist/stat.js +0 -41
package/cli/engine.mjs CHANGED
@@ -1,282 +1,282 @@
1
- // The vela-ui CLI's engine, exported (`@luxalgo/vela-ui/cli`) so another CLI can reuse it: the
2
- // catalog (the manifest and registry this package ships), dependency checks, source copies
3
- // with their lock and base files, upstream diffs, and the project check.
4
- import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, writeFileSync } from 'node:fs';
5
- import { dirname, join, relative, resolve } from 'node:path';
6
-
7
- export const PACKAGE = '@luxalgo/vela-ui';
8
- export const CONFIG_FILE = 'vela-ui.json';
9
- export const LOCK_FILE = 'vela-ui.lock.json';
10
- /** Where each copy's upstream version is kept, the base `diff` compares against. */
11
- export const BASE_DIR = '.vela-ui';
12
-
13
- const readJson = (path, fallback) => (existsSync(path) ? JSON.parse(readFileSync(path, 'utf8')) : fallback);
14
- const writeJson = (path, value) => writeFileSync(path, `${JSON.stringify(value, null, 2)}\n`);
15
-
16
- /** The catalog a command reads: this package, or a checkout's (`--from`). */
17
- export function readCatalog(from) {
18
- const own = resolve(import.meta.dirname, '..');
19
- const root = from ? (existsSync(join(from, 'packages/vela-ui/package.json')) ? join(from, 'packages/vela-ui') : resolve(from)) : own;
20
- const manifestPath = join(root, 'dist/manifest.json');
21
- if (!existsSync(manifestPath)) throw new Error(`No manifest at ${manifestPath}: build the package first (npm run build -w ${PACKAGE}).`);
22
- const { version } = readJson(join(root, 'package.json'));
23
- return { root, version, manifest: readJson(manifestPath) };
24
- }
25
-
26
- /** A catalog item by its file name or its component name. */
27
- export function findItem(catalog, name) {
28
- return catalog.manifest.components.find((c) => c.name === name || c.component === name) ?? null;
29
- }
30
-
31
- export function detectPackageManager(cwd) {
32
- if (existsSync(join(cwd, 'pnpm-lock.yaml'))) return 'pnpm';
33
- if (existsSync(join(cwd, 'yarn.lock'))) return 'yarn';
34
- if (existsSync(join(cwd, 'bun.lockb')) || existsSync(join(cwd, 'bun.lock'))) return 'bun';
35
- return 'npm';
36
- }
37
-
38
- export function installCommand(pm, spec) {
39
- return pm === 'npm' ? `npm install ${spec}` : `${pm} add ${spec}`;
40
- }
41
-
42
- /** Whether the project lists the package itself (pnpm only lets a project import those). */
43
- export function isDirectDependency(cwd) {
44
- const pkg = readJson(join(cwd, 'package.json'), {});
45
- return Boolean(pkg.dependencies?.[PACKAGE] ?? pkg.devDependencies?.[PACKAGE] ?? pkg.peerDependencies?.[PACKAGE]);
46
- }
47
-
48
- export function readConfig(cwd) {
49
- return readJson(join(cwd, CONFIG_FILE), {});
50
- }
51
-
52
- /** The folder copies go to: `aliases.ui`, a path or a package.json `imports` alias (`#ui`). */
53
- export function copyFolder(cwd, config = readConfig(cwd)) {
54
- const alias = config.aliases?.ui ?? 'src/ui';
55
- if (!alias.startsWith('#')) return resolve(cwd, alias);
56
- const imports = readJson(join(cwd, 'package.json'), {}).imports ?? {};
57
- const target = imports[`${alias}/*`];
58
- const path = typeof target === 'string' ? target : target?.default;
59
- if (!path) throw new Error(`${CONFIG_FILE} sends copies to ${alias}, but package.json has no "imports" entry for "${alias}/*".`);
60
- return resolve(cwd, path.slice(0, path.indexOf('*')).replace(/\/$/, ''));
61
- }
62
-
63
- /** A component's source under a new name: its parts, its settings' variables and its sheet
64
- * follow the name, so the copy and the package's component never style each other. */
65
- export function renameComponent(source, from, to) {
66
- if (from === to) return source;
67
- // Component names are lowercase words joined by dashes: nothing in them needs escaping.
68
- for (const name of [from, to]) if (!COMPONENT_NAME.test(name)) throw new Error(`"${name}" is not a component name (lowercase words joined by dashes).`);
69
- return source
70
- .replace(new RegExp(`(name:\\s*)(['"])${from}\\2`), `$1$2${to}$2`)
71
- .replace(new RegExp(`(\\[data-slot~?=)(['"])${from}(?=['"-])`, 'g'), `$1$2${to}`)
72
- .replace(new RegExp(`(['"])vela-ui-${from}\\1`, 'g'), `$1vela-ui-${to}$1`);
73
- }
74
-
75
- export const COMPONENT_NAME = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
76
-
77
- /** The registry file of an item, renamed. */
78
- export function itemSource(catalog, item, as) {
79
- const path = join(catalog.root, 'registry', `${item.name}.ts`);
80
- if (!existsSync(path)) throw new Error(`No registry file for ${item.name} in ${catalog.root}: build the package first.`);
81
- return renameComponent(readFileSync(path, 'utf8'), item.component ?? item.name, as);
82
- }
83
-
84
- /** Copy an item's source into the project, recording it in the lock and keeping its base. */
85
- export function copyItem({ cwd, catalog, item, as, force = false }) {
86
- const folder = copyFolder(cwd);
87
- const file = join(folder, `${as}.ts`);
88
- if (existsSync(file) && !force) throw new Error(`${relative(cwd, file)} exists. Pass --force to overwrite it, or --as <name> for another copy.`);
89
- const source = itemSource(catalog, item, as);
90
- const header = `// Copied from ${PACKAGE} ${catalog.version} (${item.name}) by \`vela-ui add --source\`. Yours to change;\n// \`vela-ui diff ${as}\` shows what changed upstream since.\n`;
91
- mkdirSync(folder, { recursive: true });
92
- writeFileSync(file, header + source);
93
- mkdirSync(join(cwd, BASE_DIR), { recursive: true });
94
- writeFileSync(join(cwd, BASE_DIR, `${as}.ts`), source);
95
- const lock = readJson(join(cwd, LOCK_FILE), { items: {} });
96
- lock.items[as] = { item: item.name, version: catalog.version, file: relative(cwd, file).split('\\').join('/') };
97
- writeJson(join(cwd, LOCK_FILE), lock);
98
- return { file };
99
- }
100
-
101
- /** Line diff (longest common subsequence), as unified hunks with `context` lines around. */
102
- export function diffLines(before, after, context = 3) {
103
- const a = before.split(/\r?\n/);
104
- const b = after.split(/\r?\n/);
105
- const n = a.length;
106
- const m = b.length;
107
- const lcs = Array.from({ length: n + 1 }, () => new Uint32Array(m + 1));
108
- for (let i = n - 1; i >= 0; i -= 1) for (let j = m - 1; j >= 0; j -= 1) lcs[i][j] = a[i] === b[j] ? lcs[i + 1][j + 1] + 1 : Math.max(lcs[i + 1][j], lcs[i][j + 1]);
109
- const ops = [];
110
- let i = 0;
111
- let j = 0;
112
- while (i < n || j < m) {
113
- if (i < n && j < m && a[i] === b[j]) {
114
- ops.push(` ${a[i]}`);
115
- i += 1;
116
- j += 1;
117
- } else if (i < n && (j === m || lcs[i + 1][j] >= lcs[i][j + 1])) ops.push(`-${a[i++]}`);
118
- else ops.push(`+${b[j++]}`);
119
- }
120
- const shown = new Uint8Array(ops.length);
121
- ops.forEach((op, k) => {
122
- if (op[0] !== ' ') for (let c = Math.max(0, k - context); c <= Math.min(ops.length - 1, k + context); c += 1) shown[c] = 1;
123
- });
124
- const out = [];
125
- ops.forEach((op, k) => {
126
- if (!shown[k]) return;
127
- if (k > 0 && !shown[k - 1] && out.length) out.push('@@');
128
- out.push(op);
129
- });
130
- return out.join('\n');
131
- }
132
-
133
- /** What changed upstream since a copy was made: its base against the catalog's version. */
134
- export function upstreamDiff({ cwd, catalog, as }) {
135
- const entry = readJson(join(cwd, LOCK_FILE), { items: {} }).items[as];
136
- if (!entry) throw new Error(`${as} is not a copy recorded in ${LOCK_FILE}.`);
137
- const item = findItem(catalog, entry.item);
138
- if (!item) throw new Error(`${entry.item} is no longer in ${PACKAGE} ${catalog.version}.`);
139
- const base = readFileSync(join(cwd, BASE_DIR, `${as}.ts`), 'utf8');
140
- const next = itemSource(catalog, item, as);
141
- return { entry, base, next, diff: base === next ? '' : diffLines(base, next) };
142
- }
143
-
144
- /** Record that a copy has taken the upstream changes in: its base and version move up. */
145
- export function acceptUpstream({ cwd, catalog, as }) {
146
- const { next } = upstreamDiff({ cwd, catalog, as });
147
- writeFileSync(join(cwd, BASE_DIR, `${as}.ts`), next);
148
- const lock = readJson(join(cwd, LOCK_FILE), { items: {} });
149
- lock.items[as].version = catalog.version;
150
- writeJson(join(cwd, LOCK_FILE), lock);
151
- }
152
-
153
- const MARK_BEGIN = '<!-- BEGIN:vela-ui-agent-rules -->';
154
- const MARK_END = '<!-- END:vela-ui-agent-rules -->';
155
-
156
- export function agentsBlock() {
157
- return `${MARK_BEGIN}
158
- ## ${PACKAGE}
159
-
160
- Before writing UI with \`${PACKAGE}\`, read \`node_modules/${PACKAGE}/llms.txt\`: it indexes the
161
- component manifest, the theme schema, the guides and the agent skills
162
- (\`node_modules/${PACKAGE}/skills/*/SKILL.md\`) of the installed version. Mount components in a
163
- kit host (\`ensureUIHost\`); themes go through \`createTheme\`; restyle a component through its
164
- parts, never its class names.
165
- ${MARK_END}
166
- `;
167
- }
168
-
169
- export function hasAgentsBlock(cwd) {
170
- const path = join(cwd, 'AGENTS.md');
171
- return existsSync(path) && readFileSync(path, 'utf8').includes(MARK_BEGIN);
172
- }
173
-
174
- export function writeAgentsBlock(cwd) {
175
- const path = join(cwd, 'AGENTS.md');
176
- const text = existsSync(path) ? readFileSync(path, 'utf8') : '';
177
- if (text.includes(MARK_BEGIN)) return false;
178
- writeFileSync(path, `${text}${text && !text.endsWith('\n\n') ? (text.endsWith('\n') ? '\n' : '\n\n') : ''}${agentsBlock()}`);
179
- return true;
180
- }
181
-
182
- /** Every installed copy of the package under the project's node_modules. */
183
- export function installedCopies(cwd) {
184
- const found = [];
185
- const visit = (dir, depth) => {
186
- if (depth > 5 || !existsSync(dir)) return;
187
- const own = join(dir, '@luxalgo', 'vela-ui', 'package.json');
188
- if (existsSync(own)) found.push({ path: dirname(own), version: readJson(own).version });
189
- for (const name of readdirSync(dir)) {
190
- if (name === '.bin') continue;
191
- const sub = join(dir, name);
192
- if (name.startsWith('@')) {
193
- for (const inner of existsSync(sub) ? readdirSync(sub) : []) visit(join(sub, inner, 'node_modules'), depth + 1);
194
- } else if (name === '.pnpm') {
195
- for (const inner of readdirSync(sub)) if (inner.startsWith('@luxalgo+vela-ui@')) visit(join(sub, inner, 'node_modules'), depth + 1);
196
- } else visit(join(sub, 'node_modules'), depth + 1);
197
- }
198
- };
199
- visit(join(cwd, 'node_modules'), 0);
200
- // A link and the folder it points to are one copy (pnpm links each package from its store).
201
- const seen = new Set();
202
- return found.filter((c) => {
203
- const real = realpathSync(c.path);
204
- return !seen.has(real) && seen.add(real);
205
- });
206
- }
207
-
208
- const compareVersions = (x, y) => {
209
- const p = (v) => v.split(/[.-]/).map((s) => (Number.isNaN(Number(s)) ? 0 : Number(s)));
210
- const [a, b] = [p(x), p(y)];
211
- for (let k = 0; k < Math.max(a.length, b.length); k += 1) if ((a[k] ?? 0) !== (b[k] ?? 0)) return (a[k] ?? 0) - (b[k] ?? 0);
212
- return 0;
213
- };
214
-
215
- /** Validates a value against the subset of JSON Schema the theme schema uses. */
216
- export function validate(schema, value, root = schema, at = '') {
217
- if (schema.$ref) return validate(schema.$ref.slice(2).split('/').reduce((s, k) => s[k], root), value, root, at);
218
- if (schema.oneOf) {
219
- const ok = schema.oneOf.filter((s) => validate(s, value, root, at).length === 0);
220
- return ok.length === 1 ? [] : [`${at || '/'}: matches ${ok.length} of the allowed shapes, not one`];
221
- }
222
- if (schema.enum && !schema.enum.includes(value)) return [`${at || '/'}: must be one of ${schema.enum.join(', ')}`];
223
- if (schema.type === 'string') {
224
- if (typeof value !== 'string') return [`${at}: must be a string`];
225
- if (schema.pattern && !new RegExp(schema.pattern).test(value)) return [`${at}: "${value}" is not a color (#rrggbb, rgb() or var())`];
226
- return [];
227
- }
228
- if (schema.type === 'object') {
229
- if (!value || typeof value !== 'object' || Array.isArray(value)) return [`${at || '/'}: must be an object`];
230
- const errors = [];
231
- for (const key of schema.required ?? []) if (!(key in value)) errors.push(`${at}/${key}: is required`);
232
- for (const [key, v] of Object.entries(value)) {
233
- const sub = schema.properties?.[key];
234
- if (sub) errors.push(...validate(sub, v, root, `${at}/${key}`));
235
- else if (schema.additionalProperties === false) errors.push(`${at}/${key}: is not a known field`);
236
- }
237
- return errors;
238
- }
239
- return [];
240
- }
241
-
242
- /** The project's health: one copy of the package, copies of components not behind it, and
243
- * the theme file valid (against the schema, then `checkTheme`, the package's own, when
244
- * given). Each finding is `{ level: 'error' | 'warn', text }`. */
245
- // The caller loads `checkTheme`: a computed `import()` in this file hangs Vite's SSR
246
- // transform, which the tests load it through.
247
- export function checkProject({ cwd, catalog, checkTheme }) {
248
- const findings = [];
249
- const copies = installedCopies(cwd);
250
- const versions = [...new Set(copies.map((c) => c.version))];
251
- if (copies.length === 0) findings.push({ level: 'error', text: `${PACKAGE} is not installed (${installCommand(detectPackageManager(cwd), PACKAGE)}).` });
252
- else if (copies.length > 1)
253
- findings.push({ level: 'error', text: `${copies.length} copies of ${PACKAGE} are installed (${versions.join(', ')}): a page would carry every component twice. Align the versions that depend on it.\n${copies.map((c) => ` ${relative(cwd, c.path)} ${c.version}`).join('\n')}` });
254
- if (copies.length && !isDirectDependency(cwd)) findings.push({ level: 'warn', text: `${PACKAGE} is installed but not a direct dependency; pnpm will not let the project import it.` });
255
- const installed = copies[0]?.version ?? catalog.version;
256
- const lock = readJson(join(cwd, LOCK_FILE), { items: {} });
257
- for (const [as, entry] of Object.entries(lock.items)) {
258
- if (!existsSync(join(cwd, entry.file))) findings.push({ level: 'warn', text: `${as}: ${entry.file} is gone; remove it from ${LOCK_FILE}.` });
259
- else if (compareVersions(entry.version, installed) < 0) findings.push({ level: 'warn', text: `${as} was copied from ${entry.version}; ${installed} is installed. \`vela-ui diff ${as}\` shows what changed.` });
260
- }
261
- const config = readConfig(cwd);
262
- if (config.theme) {
263
- const themeFile = resolve(cwd, config.theme);
264
- if (!existsSync(themeFile)) findings.push({ level: 'error', text: `The theme file ${config.theme} does not exist.` });
265
- else {
266
- let input;
267
- try {
268
- input = JSON.parse(readFileSync(themeFile, 'utf8'));
269
- } catch (e) {
270
- findings.push({ level: 'error', text: `${config.theme} is not valid JSON: ${e.message}` });
271
- }
272
- if (input) {
273
- const schema = readJson(join(catalog.root, 'dist/theme.schema.json'));
274
- for (const text of validate(schema, input)) findings.push({ level: 'error', text: `${config.theme}${text}` });
275
- const theme = { ...input };
276
- delete theme.$schema;
277
- for (const text of checkTheme?.(theme) ?? []) findings.push({ level: 'warn', text: `${config.theme}: ${text}` });
278
- }
279
- }
280
- }
281
- return findings;
282
- }
1
+ // The vela-ui CLI's engine, exported (`@luxalgo/vela-ui/cli`) so another CLI can reuse it: the
2
+ // catalog (the manifest and registry this package ships), dependency checks, source copies
3
+ // with their lock and base files, upstream diffs, and the project check.
4
+ import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, writeFileSync } from 'node:fs';
5
+ import { dirname, join, relative, resolve } from 'node:path';
6
+
7
+ export const PACKAGE = '@luxalgo/vela-ui';
8
+ export const CONFIG_FILE = 'vela-ui.json';
9
+ export const LOCK_FILE = 'vela-ui.lock.json';
10
+ /** Where each copy's upstream version is kept, the base `diff` compares against. */
11
+ export const BASE_DIR = '.vela-ui';
12
+
13
+ const readJson = (path, fallback) => (existsSync(path) ? JSON.parse(readFileSync(path, 'utf8')) : fallback);
14
+ const writeJson = (path, value) => writeFileSync(path, `${JSON.stringify(value, null, 2)}\n`);
15
+
16
+ /** The catalog a command reads: this package, or a checkout's (`--from`). */
17
+ export function readCatalog(from) {
18
+ const own = resolve(import.meta.dirname, '..');
19
+ const root = from ? (existsSync(join(from, 'packages/vela-ui/package.json')) ? join(from, 'packages/vela-ui') : resolve(from)) : own;
20
+ const manifestPath = join(root, 'dist/manifest.json');
21
+ if (!existsSync(manifestPath)) throw new Error(`No manifest at ${manifestPath}: build the package first (npm run build -w ${PACKAGE}).`);
22
+ const { version } = readJson(join(root, 'package.json'));
23
+ return { root, version, manifest: readJson(manifestPath) };
24
+ }
25
+
26
+ /** A catalog item by its file name or its component name. */
27
+ export function findItem(catalog, name) {
28
+ return catalog.manifest.components.find((c) => c.name === name || c.component === name) ?? null;
29
+ }
30
+
31
+ export function detectPackageManager(cwd) {
32
+ if (existsSync(join(cwd, 'pnpm-lock.yaml'))) return 'pnpm';
33
+ if (existsSync(join(cwd, 'yarn.lock'))) return 'yarn';
34
+ if (existsSync(join(cwd, 'bun.lockb')) || existsSync(join(cwd, 'bun.lock'))) return 'bun';
35
+ return 'npm';
36
+ }
37
+
38
+ export function installCommand(pm, spec) {
39
+ return pm === 'npm' ? `npm install ${spec}` : `${pm} add ${spec}`;
40
+ }
41
+
42
+ /** Whether the project lists the package itself (pnpm only lets a project import those). */
43
+ export function isDirectDependency(cwd) {
44
+ const pkg = readJson(join(cwd, 'package.json'), {});
45
+ return Boolean(pkg.dependencies?.[PACKAGE] ?? pkg.devDependencies?.[PACKAGE] ?? pkg.peerDependencies?.[PACKAGE]);
46
+ }
47
+
48
+ export function readConfig(cwd) {
49
+ return readJson(join(cwd, CONFIG_FILE), {});
50
+ }
51
+
52
+ /** The folder copies go to: `aliases.ui`, a path or a package.json `imports` alias (`#ui`). */
53
+ export function copyFolder(cwd, config = readConfig(cwd)) {
54
+ const alias = config.aliases?.ui ?? 'src/ui';
55
+ if (!alias.startsWith('#')) return resolve(cwd, alias);
56
+ const imports = readJson(join(cwd, 'package.json'), {}).imports ?? {};
57
+ const target = imports[`${alias}/*`];
58
+ const path = typeof target === 'string' ? target : target?.default;
59
+ if (!path) throw new Error(`${CONFIG_FILE} sends copies to ${alias}, but package.json has no "imports" entry for "${alias}/*".`);
60
+ return resolve(cwd, path.slice(0, path.indexOf('*')).replace(/\/$/, ''));
61
+ }
62
+
63
+ /** A component's source under a new name: its parts, its settings' variables and its sheet
64
+ * follow the name, so the copy and the package's component never style each other. */
65
+ export function renameComponent(source, from, to) {
66
+ if (from === to) return source;
67
+ // Component names are lowercase words joined by dashes: nothing in them needs escaping.
68
+ for (const name of [from, to]) if (!COMPONENT_NAME.test(name)) throw new Error(`"${name}" is not a component name (lowercase words joined by dashes).`);
69
+ return source
70
+ .replace(new RegExp(`(name:\\s*)(['"])${from}\\2`), `$1$2${to}$2`)
71
+ .replace(new RegExp(`(\\[data-slot~?=)(['"])${from}(?=['"-])`, 'g'), `$1$2${to}`)
72
+ .replace(new RegExp(`(['"])vela-ui-${from}\\1`, 'g'), `$1vela-ui-${to}$1`);
73
+ }
74
+
75
+ export const COMPONENT_NAME = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
76
+
77
+ /** The registry file of an item, renamed. */
78
+ export function itemSource(catalog, item, as) {
79
+ const path = join(catalog.root, 'registry', `${item.name}.ts`);
80
+ if (!existsSync(path)) throw new Error(`No registry file for ${item.name} in ${catalog.root}: build the package first.`);
81
+ return renameComponent(readFileSync(path, 'utf8'), item.component ?? item.name, as);
82
+ }
83
+
84
+ /** Copy an item's source into the project, recording it in the lock and keeping its base. */
85
+ export function copyItem({ cwd, catalog, item, as, force = false }) {
86
+ const folder = copyFolder(cwd);
87
+ const file = join(folder, `${as}.ts`);
88
+ if (existsSync(file) && !force) throw new Error(`${relative(cwd, file)} exists. Pass --force to overwrite it, or --as <name> for another copy.`);
89
+ const source = itemSource(catalog, item, as);
90
+ const header = `// Copied from ${PACKAGE} ${catalog.version} (${item.name}) by \`vela-ui add --source\`. Yours to change;\n// \`vela-ui diff ${as}\` shows what changed upstream since.\n`;
91
+ mkdirSync(folder, { recursive: true });
92
+ writeFileSync(file, header + source);
93
+ mkdirSync(join(cwd, BASE_DIR), { recursive: true });
94
+ writeFileSync(join(cwd, BASE_DIR, `${as}.ts`), source);
95
+ const lock = readJson(join(cwd, LOCK_FILE), { items: {} });
96
+ lock.items[as] = { item: item.name, version: catalog.version, file: relative(cwd, file).split('\\').join('/') };
97
+ writeJson(join(cwd, LOCK_FILE), lock);
98
+ return { file };
99
+ }
100
+
101
+ /** Line diff (longest common subsequence), as unified hunks with `context` lines around. */
102
+ export function diffLines(before, after, context = 3) {
103
+ const a = before.split(/\r?\n/);
104
+ const b = after.split(/\r?\n/);
105
+ const n = a.length;
106
+ const m = b.length;
107
+ const lcs = Array.from({ length: n + 1 }, () => new Uint32Array(m + 1));
108
+ for (let i = n - 1; i >= 0; i -= 1) for (let j = m - 1; j >= 0; j -= 1) lcs[i][j] = a[i] === b[j] ? lcs[i + 1][j + 1] + 1 : Math.max(lcs[i + 1][j], lcs[i][j + 1]);
109
+ const ops = [];
110
+ let i = 0;
111
+ let j = 0;
112
+ while (i < n || j < m) {
113
+ if (i < n && j < m && a[i] === b[j]) {
114
+ ops.push(` ${a[i]}`);
115
+ i += 1;
116
+ j += 1;
117
+ } else if (i < n && (j === m || lcs[i + 1][j] >= lcs[i][j + 1])) ops.push(`-${a[i++]}`);
118
+ else ops.push(`+${b[j++]}`);
119
+ }
120
+ const shown = new Uint8Array(ops.length);
121
+ ops.forEach((op, k) => {
122
+ if (op[0] !== ' ') for (let c = Math.max(0, k - context); c <= Math.min(ops.length - 1, k + context); c += 1) shown[c] = 1;
123
+ });
124
+ const out = [];
125
+ ops.forEach((op, k) => {
126
+ if (!shown[k]) return;
127
+ if (k > 0 && !shown[k - 1] && out.length) out.push('@@');
128
+ out.push(op);
129
+ });
130
+ return out.join('\n');
131
+ }
132
+
133
+ /** What changed upstream since a copy was made: its base against the catalog's version. */
134
+ export function upstreamDiff({ cwd, catalog, as }) {
135
+ const entry = readJson(join(cwd, LOCK_FILE), { items: {} }).items[as];
136
+ if (!entry) throw new Error(`${as} is not a copy recorded in ${LOCK_FILE}.`);
137
+ const item = findItem(catalog, entry.item);
138
+ if (!item) throw new Error(`${entry.item} is no longer in ${PACKAGE} ${catalog.version}.`);
139
+ const base = readFileSync(join(cwd, BASE_DIR, `${as}.ts`), 'utf8');
140
+ const next = itemSource(catalog, item, as);
141
+ return { entry, base, next, diff: base === next ? '' : diffLines(base, next) };
142
+ }
143
+
144
+ /** Record that a copy has taken the upstream changes in: its base and version move up. */
145
+ export function acceptUpstream({ cwd, catalog, as }) {
146
+ const { next } = upstreamDiff({ cwd, catalog, as });
147
+ writeFileSync(join(cwd, BASE_DIR, `${as}.ts`), next);
148
+ const lock = readJson(join(cwd, LOCK_FILE), { items: {} });
149
+ lock.items[as].version = catalog.version;
150
+ writeJson(join(cwd, LOCK_FILE), lock);
151
+ }
152
+
153
+ const MARK_BEGIN = '<!-- BEGIN:vela-ui-agent-rules -->';
154
+ const MARK_END = '<!-- END:vela-ui-agent-rules -->';
155
+
156
+ export function agentsBlock() {
157
+ return `${MARK_BEGIN}
158
+ ## ${PACKAGE}
159
+
160
+ Before writing UI with \`${PACKAGE}\`, read \`node_modules/${PACKAGE}/llms.txt\`: it indexes the
161
+ component manifest, the theme schema, the guides and the agent skills
162
+ (\`node_modules/${PACKAGE}/skills/*/SKILL.md\`) of the installed version. Mount components in a
163
+ kit host (\`ensureUIHost\`); themes go through \`createTheme\`; restyle a component through its
164
+ parts, never its class names.
165
+ ${MARK_END}
166
+ `;
167
+ }
168
+
169
+ export function hasAgentsBlock(cwd) {
170
+ const path = join(cwd, 'AGENTS.md');
171
+ return existsSync(path) && readFileSync(path, 'utf8').includes(MARK_BEGIN);
172
+ }
173
+
174
+ export function writeAgentsBlock(cwd) {
175
+ const path = join(cwd, 'AGENTS.md');
176
+ const text = existsSync(path) ? readFileSync(path, 'utf8') : '';
177
+ if (text.includes(MARK_BEGIN)) return false;
178
+ writeFileSync(path, `${text}${text && !text.endsWith('\n\n') ? (text.endsWith('\n') ? '\n' : '\n\n') : ''}${agentsBlock()}`);
179
+ return true;
180
+ }
181
+
182
+ /** Every installed copy of the package under the project's node_modules. */
183
+ export function installedCopies(cwd) {
184
+ const found = [];
185
+ const visit = (dir, depth) => {
186
+ if (depth > 5 || !existsSync(dir)) return;
187
+ const own = join(dir, '@luxalgo', 'vela-ui', 'package.json');
188
+ if (existsSync(own)) found.push({ path: dirname(own), version: readJson(own).version });
189
+ for (const name of readdirSync(dir)) {
190
+ if (name === '.bin') continue;
191
+ const sub = join(dir, name);
192
+ if (name.startsWith('@')) {
193
+ for (const inner of existsSync(sub) ? readdirSync(sub) : []) visit(join(sub, inner, 'node_modules'), depth + 1);
194
+ } else if (name === '.pnpm') {
195
+ for (const inner of readdirSync(sub)) if (inner.startsWith('@luxalgo+vela-ui@')) visit(join(sub, inner, 'node_modules'), depth + 1);
196
+ } else visit(join(sub, 'node_modules'), depth + 1);
197
+ }
198
+ };
199
+ visit(join(cwd, 'node_modules'), 0);
200
+ // A link and the folder it points to are one copy (pnpm links each package from its store).
201
+ const seen = new Set();
202
+ return found.filter((c) => {
203
+ const real = realpathSync(c.path);
204
+ return !seen.has(real) && seen.add(real);
205
+ });
206
+ }
207
+
208
+ const compareVersions = (x, y) => {
209
+ const p = (v) => v.split(/[.-]/).map((s) => (Number.isNaN(Number(s)) ? 0 : Number(s)));
210
+ const [a, b] = [p(x), p(y)];
211
+ for (let k = 0; k < Math.max(a.length, b.length); k += 1) if ((a[k] ?? 0) !== (b[k] ?? 0)) return (a[k] ?? 0) - (b[k] ?? 0);
212
+ return 0;
213
+ };
214
+
215
+ /** Validates a value against the subset of JSON Schema the theme schema uses. */
216
+ export function validate(schema, value, root = schema, at = '') {
217
+ if (schema.$ref) return validate(schema.$ref.slice(2).split('/').reduce((s, k) => s[k], root), value, root, at);
218
+ if (schema.oneOf) {
219
+ const ok = schema.oneOf.filter((s) => validate(s, value, root, at).length === 0);
220
+ return ok.length === 1 ? [] : [`${at || '/'}: matches ${ok.length} of the allowed shapes, not one`];
221
+ }
222
+ if (schema.enum && !schema.enum.includes(value)) return [`${at || '/'}: must be one of ${schema.enum.join(', ')}`];
223
+ if (schema.type === 'string') {
224
+ if (typeof value !== 'string') return [`${at}: must be a string`];
225
+ if (schema.pattern && !new RegExp(schema.pattern).test(value)) return [`${at}: "${value}" is not a color (#rrggbb, rgb() or var())`];
226
+ return [];
227
+ }
228
+ if (schema.type === 'object') {
229
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return [`${at || '/'}: must be an object`];
230
+ const errors = [];
231
+ for (const key of schema.required ?? []) if (!(key in value)) errors.push(`${at}/${key}: is required`);
232
+ for (const [key, v] of Object.entries(value)) {
233
+ const sub = schema.properties?.[key];
234
+ if (sub) errors.push(...validate(sub, v, root, `${at}/${key}`));
235
+ else if (schema.additionalProperties === false) errors.push(`${at}/${key}: is not a known field`);
236
+ }
237
+ return errors;
238
+ }
239
+ return [];
240
+ }
241
+
242
+ /** The project's health: one copy of the package, copies of components not behind it, and
243
+ * the theme file valid (against the schema, then `checkTheme`, the package's own, when
244
+ * given). Each finding is `{ level: 'error' | 'warn', text }`. */
245
+ // The caller loads `checkTheme`: a computed `import()` in this file hangs Vite's SSR
246
+ // transform, which the tests load it through.
247
+ export function checkProject({ cwd, catalog, checkTheme }) {
248
+ const findings = [];
249
+ const copies = installedCopies(cwd);
250
+ const versions = [...new Set(copies.map((c) => c.version))];
251
+ if (copies.length === 0) findings.push({ level: 'error', text: `${PACKAGE} is not installed (${installCommand(detectPackageManager(cwd), PACKAGE)}).` });
252
+ else if (copies.length > 1)
253
+ findings.push({ level: 'error', text: `${copies.length} copies of ${PACKAGE} are installed (${versions.join(', ')}): a page would carry every component twice. Align the versions that depend on it.\n${copies.map((c) => ` ${relative(cwd, c.path)} ${c.version}`).join('\n')}` });
254
+ if (copies.length && !isDirectDependency(cwd)) findings.push({ level: 'warn', text: `${PACKAGE} is installed but not a direct dependency; pnpm will not let the project import it.` });
255
+ const installed = copies[0]?.version ?? catalog.version;
256
+ const lock = readJson(join(cwd, LOCK_FILE), { items: {} });
257
+ for (const [as, entry] of Object.entries(lock.items)) {
258
+ if (!existsSync(join(cwd, entry.file))) findings.push({ level: 'warn', text: `${as}: ${entry.file} is gone; remove it from ${LOCK_FILE}.` });
259
+ else if (compareVersions(entry.version, installed) < 0) findings.push({ level: 'warn', text: `${as} was copied from ${entry.version}; ${installed} is installed. \`vela-ui diff ${as}\` shows what changed.` });
260
+ }
261
+ const config = readConfig(cwd);
262
+ if (config.theme) {
263
+ const themeFile = resolve(cwd, config.theme);
264
+ if (!existsSync(themeFile)) findings.push({ level: 'error', text: `The theme file ${config.theme} does not exist.` });
265
+ else {
266
+ let input;
267
+ try {
268
+ input = JSON.parse(readFileSync(themeFile, 'utf8'));
269
+ } catch (e) {
270
+ findings.push({ level: 'error', text: `${config.theme} is not valid JSON: ${e.message}` });
271
+ }
272
+ if (input) {
273
+ const schema = readJson(join(catalog.root, 'dist/theme.schema.json'));
274
+ for (const text of validate(schema, input)) findings.push({ level: 'error', text: `${config.theme}${text}` });
275
+ const theme = { ...input };
276
+ delete theme.$schema;
277
+ for (const text of checkTheme?.(theme) ?? []) findings.push({ level: 'warn', text: `${config.theme}: ${text}` });
278
+ }
279
+ }
280
+ }
281
+ return findings;
282
+ }