astralis-cli 0.3.0 → 0.5.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 (42) hide show
  1. package/CHANGELOG.md +167 -0
  2. package/LICENSE +21 -0
  3. package/README.md +179 -29
  4. package/package.json +29 -10
  5. package/src/commands/add.mjs +48 -71
  6. package/src/commands/connect-mcp.mjs +66 -27
  7. package/src/commands/create.mjs +133 -39
  8. package/src/commands/init.mjs +125 -28
  9. package/src/commands/report.mjs +257 -0
  10. package/src/commands/theme.mjs +100 -82
  11. package/src/commands/validate.mjs +101 -0
  12. package/src/index.mjs +26 -47
  13. package/src/lib/args.mjs +135 -0
  14. package/src/lib/aria.mjs +40 -0
  15. package/src/lib/children-rule.mjs +23 -0
  16. package/src/lib/ci-setup.mjs +78 -0
  17. package/src/lib/ci.mjs +155 -0
  18. package/src/lib/commands.mjs +214 -0
  19. package/src/lib/css-value.mjs +141 -0
  20. package/src/lib/devtools-setup.mjs +142 -0
  21. package/src/lib/edits.mjs +206 -26
  22. package/src/lib/github-annotations.mjs +26 -0
  23. package/src/lib/github.d.mts +72 -0
  24. package/src/lib/github.mjs +339 -0
  25. package/src/lib/library.mjs +40 -0
  26. package/src/lib/menu.mjs +59 -0
  27. package/src/lib/prompt-child.mjs +97 -0
  28. package/src/lib/registry.mjs +37 -4
  29. package/src/lib/report-tree.mjs +134 -0
  30. package/src/lib/run.mjs +39 -0
  31. package/src/lib/snapshot.d.mts +65 -0
  32. package/src/lib/snapshot.mjs +371 -0
  33. package/src/lib/source-files.mjs +29 -0
  34. package/src/lib/spec-load.mjs +32 -0
  35. package/src/lib/spec-resolve.mjs +20 -0
  36. package/src/lib/starter.mjs +219 -0
  37. package/src/lib/suggest.mjs +32 -0
  38. package/src/lib/ui.mjs +85 -51
  39. package/src/lib/validate-core.d.mts +48 -0
  40. package/src/lib/validate-core.mjs +652 -0
  41. package/src/lib/validate.d.mts +33 -0
  42. package/src/lib/validate.mjs +8 -0
@@ -0,0 +1,652 @@
1
+ /* ==========================================================================
2
+ ASTRALIS — VALIDATOR CORE (Tier A: vocabulary)
3
+ --------------------------------------------------------------------------
4
+ Pure function: (TSX source, system spec) -> { errors, warnings }. Browser-
5
+ safe: it reaches no Node builtins, so it also runs client-side.
6
+
7
+ The system spec (dist/system-spec.json, emitted by the astralis-ui build)
8
+ is the ground truth; nothing here is hand-listed twice. The checks target
9
+ the class of mistakes that TYPECHECK AND STILL FAIL:
10
+
11
+ - a component or compound part that doesn't exist (unknown-import,
12
+ unknown-part)
13
+ - a keyword prop value outside its closed set (invalid-keyword-value)
14
+ - a breakpoint or state key that isn't one (invalid-breakpoint-key,
15
+ invalid-state-prop)
16
+ - an `astralis:*` class missing from the compiled CSS (unknown-class)
17
+ - a var(--astralis-*) reference no stylesheet declares (unknown-css-variable)
18
+ - a prop its component deliberately types away (excluded-prop)
19
+ - a bare number where CSS needs a unit (bare-number-value)
20
+ - a style prop the component does not take, which reaches the HTML as a
21
+ stray attribute and changes nothing (unknown-style-prop)
22
+ - a component left empty that its type requires children for (missing-children):
23
+ tsc catches it too, but agents and copied snippets produce code no one type-checks
24
+
25
+ And, as warnings (advice, which the DevTools show as recommendations):
26
+
27
+ - a Flex set to a column, which is a VStack (prefer-vstack)
28
+ - a Button that shows only an icon and has no name (icon-button-label)
29
+
30
+ Dynamic expressions are skipped, not guessed at: this validator makes no
31
+ claim it cannot decide statically. Components whose spec entry has no
32
+ groups ("props manifest pending") get only the universal checks.
33
+ ========================================================================== */
34
+
35
+ import { parse } from "@babel/parser";
36
+ import { classifyChannelValue } from "./css-value.mjs";
37
+ import { ARIA_ATTRS, ROLES } from "./aria.mjs";
38
+ import { suggest } from "./suggest.mjs";
39
+ import { checkRequiredChildren } from "./children-rule.mjs";
40
+
41
+ const BARE_NUMBER = /^-?(\d+\.?\d*|\.\d+)$/;
42
+ const CSS_VAR_REF = /var\((--astralis-[^,()\s]+)\)/g; // no-fallback form only
43
+
44
+ /* Paint props that recipe components deliberately refuse: the "a component
45
+ owns how it looks" doctrine (utils/placement.ts). Given to one, they do
46
+ nothing, so the error points at variant and colorScheme instead. `rounded`
47
+ is NOT here: like `size`, the name is reused as a recipe prop (Button/Image
48
+ radius scale, Tabs boolean). */
49
+ const DOCTRINE_PAINT_PROPS = new Set([
50
+ "p", "px", "py", "pt", "pr", "pb", "pl",
51
+ "bg", "borderColor", "shadow",
52
+ ]);
53
+
54
+ /* Style-prop names that are also real HTML attributes (img width, input size,
55
+ textarea wrap, font color, table border and align). On a component that
56
+ does not take them as style props they may still be meant for the element,
57
+ so they are never reported as stray. */
58
+ const HTML_ATTRIBUTE_NAMES = new Set(["width", "height", "size", "color", "wrap", "align", "border"]);
59
+
60
+ /* Packages whose components are icons, for the icon-only Button rule. */
61
+ const ICON_PACKAGES = /^(lucide-react|react-icons(\/.*)?|@heroicons\/react(\/.*)?|@radix-ui\/react-icons|@tabler\/icons-react|@phosphor-icons\/react)$/;
62
+
63
+ /** Precompute the lookup tables one spec produces. Reusable across files. */
64
+ export function prepareSpec(spec) {
65
+ const classSet = new Set(spec.classes);
66
+ const varSet = new Set(spec.cssVariables);
67
+
68
+ // Channel custom properties are legal style keys/references even though no
69
+ // token stylesheet declares them: --astralis-p, --astralis-p-md, --astralis-p-hover.
70
+ const channelVarSet = new Set();
71
+ const suffixes = ["", ...Object.keys(spec.breakpoints), ...Object.values(spec.states)];
72
+ for (const slug of Object.values(spec.channelProps)) {
73
+ for (const s of suffixes) channelVarSet.add(s ? `--astralis-${slug}-${s}` : `--astralis-${slug}`);
74
+ }
75
+
76
+ // What a state object may carry: box's channel props plus the gap family.
77
+ const statePayload = {};
78
+ for (const name of spec.stateableProps) {
79
+ statePayload[name] = spec.propGroups.box[name] ?? spec.propGroups.flex[name];
80
+ }
81
+
82
+ // Every style-prop name any group defines: one a component does not take is stray.
83
+ const stylePropNames = new Set();
84
+ for (const group of Object.values(spec.propGroups)) for (const name of Object.keys(group)) stylePropNames.add(name);
85
+
86
+ return {
87
+ spec,
88
+ classSet,
89
+ varSet,
90
+ channelVarSet,
91
+ statePayload,
92
+ stylePropNames,
93
+ // Container keys (@sm..@xl) are additive in the spec; older specs lack
94
+ // them and older code must keep validating.
95
+ bpKeys: new Set(["base", ...Object.keys(spec.breakpoints), ...Object.keys(spec.containerBreakpoints ?? {})]),
96
+ stateProps: new Set(Object.keys(spec.states)),
97
+ // Every exported value and type (spec 3+). Null for older specs.
98
+ exportSet: spec.exports ? new Set(spec.exports) : null,
99
+ };
100
+ }
101
+
102
+ /**
103
+ * Whether astralis-ui exports `name`. Specs before version 3 list only
104
+ * components, so constants (COLOR_SCHEMES) and props types (ButtonProps) are
105
+ * given the benefit of the doubt there rather than reported.
106
+ */
107
+ function isExported(ctx, name) {
108
+ if (ctx.spec.components[name]) return true;
109
+ return ctx.exportSet ? ctx.exportSet.has(name) : /^[A-Z0-9_]+$|Props$/.test(name);
110
+ }
111
+
112
+ /* ---- AST helpers ------------------------------------------------------------ */
113
+
114
+ /** Literal string out of a value node, or null when it's dynamic. */
115
+ function literalOf(v) {
116
+ if (!v) return null;
117
+ if (v.type === "StringLiteral") return v.value;
118
+ if (v.type === "NumericLiteral") return String(v.value);
119
+ if (v.type === "BooleanLiteral") return String(v.value);
120
+ if (v.type === "TemplateLiteral" && v.expressions.length === 0) return v.quasis[0].value.cooked;
121
+ return null;
122
+ }
123
+
124
+ /** A JSX attribute value's literal, written either `x="…"` or `x={"…"}`; null when dynamic. */
125
+ function attributeLiteral(value) {
126
+ return literalOf(value) ?? (value?.type === "JSXExpressionContainer" ? literalOf(value.expression) : null);
127
+ }
128
+
129
+ const keyName = (property) => (property.key.type === "Identifier" ? property.key.name : property.key.value);
130
+
131
+ function findAttribute(opening, name) {
132
+ return opening.attributes.find(
133
+ (a) => a.type === "JSXAttribute" && a.name.type === "JSXIdentifier" && a.name.name === name,
134
+ );
135
+ }
136
+
137
+ /** "did you mean" for a near miss, else the start of the closed set. */
138
+ function closedSetHint(value, values) {
139
+ const near = suggest(value, values);
140
+ if (near) return ` (did you mean "${near}"?)`;
141
+ return ` (valid: ${values.slice(0, 8).join(", ")}${values.length > 8 ? ", …" : ""})`;
142
+ }
143
+
144
+ /* ---- per-file context ----------------------------------------------------------- */
145
+
146
+ function createContext(prepared, filePath, opts) {
147
+ const errors = [];
148
+ const warnings = [];
149
+ const report = (list, code, node, message) =>
150
+ list.push({
151
+ code,
152
+ file: filePath,
153
+ line: node?.loc?.start.line ?? 0,
154
+ column: (node?.loc?.start.column ?? 0) + 1,
155
+ message,
156
+ ...whereOf(ctx.at),
157
+ });
158
+ const ctx = {
159
+ ...prepared,
160
+ opts,
161
+ errors,
162
+ warnings,
163
+ error: (code, node, message) => report(errors, code, node, message),
164
+ warn: (code, node, message) => report(warnings, code, node, message),
165
+ knownVar: (name) => prepared.varSet.has(name) || prepared.channelVarSet.has(name),
166
+ imported: new Map(), // local name -> astralis-ui export name
167
+ iconLocals: new Set(), // local names of components from icon packages
168
+ ancestors: [], // JSX identities above the current node
169
+ tabsStack: [], // open <Tabs> scopes
170
+ at: null, // the component, prop and literal value being checked, for findings to name
171
+ };
172
+ return ctx;
173
+ }
174
+
175
+ /** A finding's optional component, prop and value: only the fields that are known. */
176
+ function whereOf(at) {
177
+ if (!at?.component) return {};
178
+ const where = { component: at.component };
179
+ if (at.prop) where.prop = at.prop;
180
+ if (typeof at.value === "string" || typeof at.value === "number") where.value = at.value;
181
+ return where;
182
+ }
183
+
184
+ /** The name a component goes by on the page: "Card.Body" whether written <Card.Body> or <CardBody>. */
185
+ const componentName = (identity) => (identity.owner ? `${identity.owner}.${identity.part}` : identity.specName);
186
+
187
+ /* ---- rule: imports from astralis-ui ------------------------------------------- */
188
+
189
+ function collectImports(ctx, ast) {
190
+ for (const node of ast.program.body) {
191
+ if (node.type === "ImportDeclaration" && ICON_PACKAGES.test(node.source.value)) {
192
+ for (const s of node.specifiers) ctx.iconLocals.add(s.local.name);
193
+ continue;
194
+ }
195
+ if (node.type !== "ImportDeclaration" || node.source.value !== "astralis-ui") continue;
196
+ for (const s of node.specifiers) {
197
+ if (s.type !== "ImportSpecifier" || s.importKind === "type" || node.importKind === "type") continue;
198
+ const name = s.imported.type === "Identifier" ? s.imported.name : s.imported.value;
199
+ ctx.imported.set(s.local.name, name);
200
+ // Only capitalised names are checked: a lowercase hook or util typo is TypeScript's to catch.
201
+ if (/^[A-Z]/.test(name) && !isExported(ctx, name)) {
202
+ ctx.error("unknown-import", s, `"${name}" is not exported by astralis-ui — check the spelling against the components list`);
203
+ }
204
+ }
205
+ }
206
+ }
207
+
208
+ /* ---- rule: prop values ---------------------------------------------------------- */
209
+
210
+ function checkScalar(ctx, comp, prop, propSpec, value, node) {
211
+ if (propSpec.tokens.includes(value)) return;
212
+ if (propSpec.kind === "keyword") {
213
+ ctx.error("invalid-keyword-value", node,
214
+ `${comp}: "${value}" is not a ${prop} value — keyword props are closed sets` + closedSetHint(value, propSpec.tokens));
215
+ return;
216
+ }
217
+ // Channel prop: an arbitrary value rides the var, but it still has to BE a
218
+ // value. The grammar condemns only the definitely-wrong.
219
+ if (value === "") {
220
+ ctx.error("empty-channel-value", node, `${comp}: ${prop}="" resolves to nothing`);
221
+ return;
222
+ }
223
+ for (const m of value.matchAll(CSS_VAR_REF)) {
224
+ if (!ctx.knownVar(m[1])) {
225
+ ctx.error("unknown-css-variable", node, `${comp}: ${prop} references var(${m[1]}), which no token stylesheet declares`);
226
+ }
227
+ }
228
+ const verdict = classifyChannelValue(value, propSpec.valueType ?? "length");
229
+ if (verdict.verdict === "invalid") {
230
+ const near = suggest(value, propSpec.tokens);
231
+ ctx.error("channel-value-invalid", node,
232
+ `${comp}: ${prop}="${value}" is neither a token nor valid CSS — ${verdict.reason}` +
233
+ (near ? ` (did you mean "${near}"?)` : ""));
234
+ } else if (verdict.verdict === "bare-number" || (BARE_NUMBER.test(value) && !propSpec.unitless)) {
235
+ ctx.warn("bare-number-value", node,
236
+ `${comp}: ${prop}="${value}" is not a token, and a bare number is not valid CSS here — did you mean a token, or "${value}px"?`);
237
+ } else if (ctx.opts.strictTokens && propSpec.valueType === "color") {
238
+ ctx.warn("off-token-color", node,
239
+ `${comp}: ${prop}="${value}" is a raw color — it won't follow the theme or dark mode; prefer a token`);
240
+ }
241
+ }
242
+
243
+ function checkPropValue(ctx, comp, prop, propSpec, valueNode, attr) {
244
+ if (valueNode === null) {
245
+ // A bare attribute is JSX for {true}: legal exactly when the variant map is boolean-keyed.
246
+ if (!propSpec.tokens.includes("true")) ctx.error("invalid-value", attr, `${comp}: ${prop} needs a value`);
247
+ return;
248
+ }
249
+ const direct = literalOf(valueNode);
250
+ if (direct !== null) return checkScalar(ctx, comp, prop, propSpec, direct, valueNode);
251
+ if (valueNode.type !== "JSXExpressionContainer") return;
252
+ const expr = valueNode.expression;
253
+ const inner = literalOf(expr);
254
+ if (inner !== null) return checkScalar(ctx, comp, prop, propSpec, inner, expr);
255
+ if (expr.type !== "ObjectExpression") return; // any other expression is dynamic
256
+
257
+ for (const p of expr.properties) {
258
+ if (p.type !== "ObjectProperty" || p.computed) continue;
259
+ const key = keyName(p);
260
+ if (!ctx.bpKeys.has(key)) {
261
+ const keys = ["base", ...Object.keys(ctx.spec.breakpoints), ...Object.keys(ctx.spec.containerBreakpoints ?? {})];
262
+ ctx.error("invalid-breakpoint-key", p, `${comp}: "${key}" is not a breakpoint — responsive maps take ${keys.join("/")}`);
263
+ continue;
264
+ }
265
+ const v = literalOf(p.value);
266
+ if (v !== null) checkScalar(ctx, comp, prop, propSpec, v, p.value);
267
+ }
268
+ }
269
+
270
+ function checkStateValue(ctx, comp, state, valueNode) {
271
+ if (valueNode?.type !== "JSXExpressionContainer" || valueNode.expression.type !== "ObjectExpression") return;
272
+ for (const p of valueNode.expression.properties) {
273
+ if (p.type !== "ObjectProperty" || p.computed) continue;
274
+ const key = keyName(p);
275
+ const payloadSpec = ctx.statePayload[key];
276
+ if (!payloadSpec) {
277
+ ctx.error("invalid-state-prop", p,
278
+ `${comp}: "${key}" cannot appear in ${state} — states carry channel props only (spacing, sizing, gap, paint, …)`);
279
+ continue;
280
+ }
281
+ const v = literalOf(p.value);
282
+ if (v !== null) checkScalar(ctx, comp, `${state}.${key}`, payloadSpec, v, p.value);
283
+ }
284
+ }
285
+
286
+ /* ---- rules: universal attributes (every element, astralis or not) ------------- */
287
+
288
+ function checkClassNameString(ctx, text, node) {
289
+ for (const token of text.split(/\s+/)) {
290
+ if (token.startsWith("astralis") && !ctx.classSet.has(token)) {
291
+ ctx.error("unknown-class", node, `class "${token}" does not exist in the compiled CSS — it will silently do nothing`);
292
+ }
293
+ }
294
+ }
295
+
296
+ function checkClassName(ctx, attr) {
297
+ const v = attr.value;
298
+ const direct = attributeLiteral(v);
299
+ if (direct !== null) return checkClassNameString(ctx, direct, v);
300
+ const tpl = v?.type === "JSXExpressionContainer" && v.expression.type === "TemplateLiteral" ? v.expression : null;
301
+ if (!tpl) return;
302
+ // Check whitespace-delimited tokens, dropping any that touch an expression: those are only partly literal.
303
+ tpl.quasis.forEach((q, i) => {
304
+ const text = q.value.cooked ?? "";
305
+ const parts = text.split(/\s+/);
306
+ if (i > 0 && !/^\s/.test(text)) parts.shift();
307
+ if (i < tpl.expressions.length && !/\s$/.test(text)) parts.pop();
308
+ checkClassNameString(ctx, parts.join(" "), q);
309
+ });
310
+ }
311
+
312
+ function checkStyle(ctx, attr) {
313
+ if (attr.value?.type !== "JSXExpressionContainer" || attr.value.expression.type !== "ObjectExpression") return;
314
+ for (const p of attr.value.expression.properties) {
315
+ if (p.type !== "ObjectProperty") continue;
316
+ const key = p.key.type === "StringLiteral" ? p.key.value : null;
317
+ if (key?.startsWith("--astralis-") && !ctx.knownVar(key)) {
318
+ ctx.error("unknown-css-variable", p, `"${key}" is not a declared token or channel variable`);
319
+ }
320
+ const v = literalOf(p.value);
321
+ if (v === null) continue;
322
+ for (const m of v.matchAll(CSS_VAR_REF)) {
323
+ if (!ctx.knownVar(m[1])) {
324
+ ctx.error("unknown-css-variable", p.value,
325
+ `var(${m[1]}) is not declared by any token stylesheet — the declaration will fall back to nothing`);
326
+ }
327
+ }
328
+ }
329
+ }
330
+
331
+ function checkAriaAttribute(ctx, attr, prop) {
332
+ if (ARIA_ATTRS.has(prop)) return;
333
+ const near = suggest(prop, [...ARIA_ATTRS]);
334
+ ctx.error("unknown-aria-attribute", attr,
335
+ `"${prop}" is not an ARIA attribute — it renders, and assistive technology hears nothing` +
336
+ (near ? ` (did you mean "${near}"?)` : ""));
337
+ }
338
+
339
+ function checkRole(ctx, attr) {
340
+ const value = attributeLiteral(attr.value);
341
+ if (value === null) return;
342
+ for (const token of value.split(/\s+/).filter(Boolean)) {
343
+ if (ROLES.has(token)) continue;
344
+ const near = suggest(token, [...ROLES]);
345
+ ctx.error("invalid-role", attr, `"${token}" is not an ARIA role${near ? ` (did you mean "${near}"?)` : ""}`);
346
+ }
347
+ }
348
+
349
+ function checkTabIndex(ctx, attr) {
350
+ const value = attributeLiteral(attr.value);
351
+ if (value !== null && Number(value) > 0) {
352
+ ctx.warn("positive-tabindex", attr,
353
+ `tabIndex={${value}} hijacks the page's tab order — use 0 (in order) or -1 (programmatic only)`);
354
+ }
355
+ }
356
+
357
+ /* ---- rule: astralis component props --------------------------------------------- */
358
+
359
+ function checkComponentProp(ctx, identity, comp, allowed, attr, prop) {
360
+ const name = identity.specName;
361
+ if (comp.exclude?.includes(prop)) {
362
+ const short = allowed[prop]?.short;
363
+ const hint =
364
+ name === "Container" ? " — Container has no size scale; use maxW" :
365
+ prop === "direction" ? ` — the axis is fixed by the preset; use Stack for a switchable direction` :
366
+ short && !comp.exclude.includes(short) ? ` — use ${short}` : "";
367
+ ctx.error("excluded-prop", attr, `${name} has no "${prop}" prop${hint}`);
368
+ return;
369
+ }
370
+ // The component's own attribute under a style prop's name (Image's width): not a style prop.
371
+ if (comp.overrides?.includes(prop)) return;
372
+ if (ctx.stateProps.has(prop)) {
373
+ // Only Box-composing primitives resolve states; elsewhere no claim.
374
+ if (comp.groups.includes("box")) checkStateValue(ctx, name, prop, attr.value);
375
+ return;
376
+ }
377
+ if (allowed[prop]) {
378
+ checkPropValue(ctx, name, prop, allowed[prop], attr.value, attr);
379
+ return;
380
+ }
381
+ // Recipe props (Button variant, Alert status, …): closed vocabularies read
382
+ // out of the shipped d.ts. Literal values only; dynamic ones are TypeScript's.
383
+ if (comp.props?.[prop]) {
384
+ const values = comp.props[prop];
385
+ const value = attributeLiteral(attr.value);
386
+ if (value !== null && !values.includes(value)) {
387
+ ctx.error("invalid-recipe-value", attr, `${name}: "${value}" is not a ${prop} value` + closedSetHint(value, values));
388
+ }
389
+ return;
390
+ }
391
+ // A style prop this component's type does not take at all: it is passed to
392
+ // the DOM, where it is a meaningless attribute. Only decided when the spec
393
+ // lists the component's own style-prop names (spec builds from Oct 2026).
394
+ if (comp.ownStyleProps && !comp.ownStyleProps.includes(prop) && ctx.stylePropNames.has(prop) && !HTML_ATTRIBUTE_NAMES.has(prop)) {
395
+ const recipe = comp.groups.length === 1 && comp.groups[0] === "placement" && DOCTRINE_PAINT_PROPS.has(prop);
396
+ ctx.error("unknown-style-prop", attr,
397
+ `${name} does not take ${prop}: it reaches the HTML as a stray attribute and changes nothing` +
398
+ (recipe
399
+ ? ` (${name} owns how it looks; reach for variant, size or colorScheme)`
400
+ : ` (${name} takes ${comp.groups.join(", ")} props; put ${prop} on a Box around it)`));
401
+ }
402
+ // Anything else: DOM prop or open-typed, no claim.
403
+ }
404
+
405
+ /* ---- one element: identity, then every attribute ----------------------------- */
406
+
407
+ /** Who a JSX element is, for anatomy: { display, specName, owner, part, dom }. */
408
+ function resolveIdentity(ctx, node) {
409
+ const identity = { display: null, specName: null, owner: null, part: null, dom: null };
410
+ const { spec, imported } = ctx;
411
+
412
+ if (node.name.type === "JSXIdentifier") {
413
+ const local = node.name.name;
414
+ identity.display = local;
415
+ if (/^[a-z]/.test(local)) identity.dom = local;
416
+ const specName = imported.get(local) ?? null;
417
+ if (specName && spec.components[specName]) {
418
+ identity.specName = specName;
419
+ // A flat part export (CardBody) knows its compound via partOf.
420
+ const partOf = spec.components[specName].partOf;
421
+ if (partOf) {
422
+ identity.owner = partOf;
423
+ identity.part = specName.slice(partOf.length);
424
+ }
425
+ }
426
+ } else if (
427
+ node.name.type === "JSXMemberExpression" &&
428
+ node.name.object.type === "JSXIdentifier" &&
429
+ imported.has(node.name.object.name)
430
+ ) {
431
+ // <Menu.Trigger /> validates against the parts the spec enumerated from
432
+ // the real export object. The flat-name guess is NOT a fallback: some
433
+ // compounds are dot-only, and a flat cousin wouldn't make a dot-part render.
434
+ const owner = imported.get(node.name.object.name);
435
+ const part = node.name.property.name;
436
+ identity.display = `${owner}.${part}`;
437
+ const ownerSpec = spec.components[owner];
438
+ if (ownerSpec?.parts?.includes(part)) {
439
+ identity.owner = owner;
440
+ identity.part = part;
441
+ // A part with a flat twin (CardBody) carries that twin's groups.
442
+ if (spec.components[owner + part]) identity.specName = owner + part;
443
+ } else if (ownerSpec) {
444
+ ctx.error("unknown-part", node.name,
445
+ `${owner}.${part} — no such part${ownerSpec.parts ? ` (${owner} has: ${ownerSpec.parts.join(", ")})` : ""}`);
446
+ }
447
+ }
448
+ return identity;
449
+ }
450
+
451
+ function analyzeOpening(ctx, node) {
452
+ const identity = resolveIdentity(ctx, node);
453
+ const component = componentName(identity);
454
+ ctx.at = { component };
455
+ const comp = identity.specName ? ctx.spec.components[identity.specName] : null;
456
+ const allowed = {};
457
+ if (comp) for (const g of comp.groups) Object.assign(allowed, ctx.spec.propGroups[g]);
458
+
459
+ let hasSpread = false;
460
+ let hasAlt = false;
461
+ let hasAriaCover = false; // aria-label / aria-labelledby / aria-hidden
462
+
463
+ for (const attr of node.attributes) {
464
+ if (attr.type === "JSXSpreadAttribute") { hasSpread = true; continue; }
465
+ if (attr.name.type !== "JSXIdentifier") continue;
466
+ const prop = attr.name.name;
467
+ ctx.at = { component, prop, value: attributeLiteral(attr.value) };
468
+
469
+ if (prop === "className") checkClassName(ctx, attr);
470
+ else if (prop === "style") checkStyle(ctx, attr);
471
+ else if (prop.startsWith("aria-")) {
472
+ hasAriaCover ||= prop === "aria-label" || prop === "aria-labelledby" || prop === "aria-hidden";
473
+ checkAriaAttribute(ctx, attr, prop);
474
+ } else if (prop === "role") checkRole(ctx, attr);
475
+ else if (prop === "tabIndex") checkTabIndex(ctx, attr);
476
+ else if (prop === "alt") hasAlt = true;
477
+ else if (comp) checkComponentProp(ctx, identity, comp, allowed, attr, prop);
478
+ }
479
+
480
+ if (identity.specName === "Flex") {
481
+ const direction = findAttribute(node, "direction");
482
+ if (direction && attributeLiteral(direction.value) === "column") {
483
+ ctx.at = { component, prop: "direction", value: "column" };
484
+ ctx.warn("prefer-vstack", direction,
485
+ `Flex direction="column" is a VStack: VStack stacks its children with gap, and says what it is`);
486
+ }
487
+ }
488
+
489
+ ctx.at = { component };
490
+ // Images need a text alternative: real <img>, or our Image wrapper (which
491
+ // jsx-a11y can't know renders an img). A spread may carry alt, so it silences the claim.
492
+ if ((identity.dom === "img" || identity.specName === "Image") && !hasSpread && !hasAlt && !hasAriaCover) {
493
+ ctx.error("missing-alt", node, `${identity.display} has no alt — pass alt="…" (or alt="" if purely decorative)`);
494
+ }
495
+ return identity;
496
+ }
497
+
498
+ /* ---- rule: anatomy — parts want their compound root above them ------------------ */
499
+
500
+ const providesRoot = (ancestor, owner) =>
501
+ ancestor.specName === owner ||
502
+ ancestor.specName === owner + "Root" ||
503
+ (ancestor.owner === owner && ancestor.part === "Root");
504
+
505
+ function checkAnatomy(ctx, identity, node) {
506
+ if (!identity.owner || identity.part === "Root") return;
507
+ // Only anatomy CHILDREN are claimed: namespaced variants (Input.Password)
508
+ // and container parts (Radio.Group) carry no requirement.
509
+ const anatomy = ctx.spec.components[identity.owner]?.anatomy;
510
+ if (!anatomy?.children.includes(identity.part)) return;
511
+ const { ancestors } = ctx;
512
+ if (ancestors.some((a) => providesRoot(a, identity.owner))) return;
513
+ // A detached subtree (the expression's root, or only under its own
514
+ // compound's parts) is composed under the real root elsewhere: no claim.
515
+ if (ancestors.length === 0) return;
516
+ if (ancestors.every((a) => a.owner === identity.owner)) return;
517
+ // Under FOREIGN structure with no root in sight. Warn: file-local analysis
518
+ // can't see whether a root wraps this component at its call sites.
519
+ ctx.warn("part-outside-root", node,
520
+ `${identity.display} sits outside a ${identity.owner} in this tree — legal only if a ${identity.owner} wraps this component where it's used`);
521
+ }
522
+
523
+ /* ---- advice: an icon-only Button needs a name ------------------------------------- */
524
+
525
+ const isIconElement = (ctx, child) => {
526
+ if (child.type !== "JSXElement" || child.openingElement.name.type !== "JSXIdentifier") return false;
527
+ const local = child.openingElement.name.name;
528
+ return local === "svg" || ctx.imported.get(local) === "Icon" || ctx.iconLocals.has(local);
529
+ };
530
+
531
+ /** A Button whose only content is an icon, with nothing naming it for assistive technology. */
532
+ function checkIconButton(ctx, identity, element) {
533
+ if (identity.specName !== "Button") return;
534
+ const opening = element.openingElement;
535
+ if (opening.attributes.some((a) => a.type === "JSXSpreadAttribute")) return;
536
+ const named = ["aria-label", "aria-labelledby", "title"].some((n) => findAttribute(opening, n));
537
+ if (named) return;
538
+ const children = element.children.filter((c) => !(c.type === "JSXText" && !c.value.trim()));
539
+ const iconProp = findAttribute(opening, "leftIcon") || findAttribute(opening, "rightIcon");
540
+ const iconOnly = children.length === 0 ? Boolean(iconProp) : children.length === 1 && isIconElement(ctx, children[0]);
541
+ if (!iconOnly) return;
542
+ ctx.at = { component: componentName(identity) };
543
+ ctx.warn("icon-button-label", opening,
544
+ `This Button shows only an icon, so screen readers announce it as just "button": give it aria-label="…"`);
545
+ }
546
+
547
+ /* ---- rule: Tabs triggers and panels must speak the same values ------------------ */
548
+
549
+ function openTabsScope(ctx, opening) {
550
+ const attr = findAttribute(opening, "defaultValue");
551
+ ctx.tabsStack.push({
552
+ triggers: [],
553
+ contents: [],
554
+ dynamic: false,
555
+ node: opening,
556
+ defaultValue: attr ? attributeLiteral(attr.value) : null,
557
+ });
558
+ }
559
+
560
+ function collectTabsValue(ctx, identity, node) {
561
+ if (ctx.tabsStack.length === 0 || identity.owner !== "Tabs") return;
562
+ if (identity.part !== "Trigger" && identity.part !== "Content") return;
563
+ const scope = ctx.tabsStack.at(-1);
564
+ const attr = findAttribute(node, "value");
565
+ const value = attr ? attributeLiteral(attr.value) : null;
566
+ if (value === null) { scope.dynamic = true; return; }
567
+ (identity.part === "Trigger" ? scope.triggers : scope.contents).push({ value, node: attr, component: componentName(identity) });
568
+ }
569
+
570
+ function settleTabs(ctx, scope) {
571
+ // Any dynamic value and the pairing is not statically decidable.
572
+ if (scope.dynamic || scope.triggers.length === 0 || scope.contents.length === 0) return;
573
+ const triggerValues = new Set(scope.triggers.map((t) => t.value));
574
+ const contentValues = new Set(scope.contents.map((c) => c.value));
575
+ for (const t of scope.triggers) {
576
+ ctx.at = { component: t.component, prop: "value", value: t.value };
577
+ if (!contentValues.has(t.value)) {
578
+ ctx.error("tabs-value-mismatch", t.node, `Tabs trigger "${t.value}" has no matching content panel — clicking it shows nothing`);
579
+ }
580
+ }
581
+ for (const c of scope.contents) {
582
+ ctx.at = { component: c.component, prop: "value", value: c.value };
583
+ if (!triggerValues.has(c.value)) {
584
+ ctx.warn("tabs-value-mismatch", c.node, `Tabs content "${c.value}" has no trigger — the panel is unreachable`);
585
+ }
586
+ }
587
+ ctx.at = { component: "Tabs", prop: "defaultValue", value: scope.defaultValue };
588
+ if (scope.defaultValue !== null && !triggerValues.has(scope.defaultValue)) {
589
+ ctx.error("tabs-value-mismatch", scope.node, `Tabs defaultValue "${scope.defaultValue}" matches no trigger`);
590
+ }
591
+ }
592
+
593
+ /* ---- traversal, carrying JSX ancestry ------------------------------------------- */
594
+
595
+ function traverse(ctx, node) {
596
+ let pushed = false;
597
+ let tabsPushed = false;
598
+
599
+ if (node.type === "JSXElement") {
600
+ const opening = node.openingElement;
601
+ const identity = analyzeOpening(ctx, opening);
602
+ ctx.at = { component: componentName(identity) };
603
+ checkAnatomy(ctx, identity, opening);
604
+ checkRequiredChildren(ctx, identity, node);
605
+ checkIconButton(ctx, identity, node);
606
+ collectTabsValue(ctx, identity, opening);
607
+ ctx.at = null;
608
+ if (identity.specName === "Tabs") {
609
+ openTabsScope(ctx, opening);
610
+ tabsPushed = true;
611
+ }
612
+ ctx.ancestors.push(identity);
613
+ pushed = true;
614
+ }
615
+
616
+ for (const key of Object.keys(node)) {
617
+ if (key === "loc") continue;
618
+ const v = node[key];
619
+ if (Array.isArray(v)) {
620
+ for (const c of v) if (c && typeof c.type === "string") traverse(ctx, c);
621
+ } else if (v && typeof v.type === "string") {
622
+ traverse(ctx, v);
623
+ }
624
+ }
625
+
626
+ if (tabsPushed) {
627
+ settleTabs(ctx, ctx.tabsStack.pop());
628
+ ctx.at = null;
629
+ }
630
+ if (pushed) ctx.ancestors.pop();
631
+ }
632
+
633
+ /** Validate one TSX/JSX source. `prepared` comes from prepareSpec().
634
+ * opts.strictTokens: additionally warn on every valid-but-off-token color —
635
+ * the drift check, opt-in because arbitrary values are a feature. */
636
+ export function validateSource(source, prepared, filePath = "<source>", opts = {}) {
637
+ const ctx = createContext(prepared, filePath, opts);
638
+
639
+ let ast;
640
+ try {
641
+ ast = parse(source, { sourceType: "module", plugins: ["typescript", "jsx"] });
642
+ } catch (e) {
643
+ ctx.error("parse-error", { loc: e.loc && { start: e.loc } }, `could not parse: ${e.message}`);
644
+ return { errors: ctx.errors, warnings: ctx.warnings };
645
+ }
646
+
647
+ collectImports(ctx, ast);
648
+ traverse(ctx, ast.program);
649
+
650
+ const byPosition = (a, b) => a.line - b.line || a.column - b.column;
651
+ return { errors: ctx.errors.sort(byPosition), warnings: ctx.warnings.sort(byPosition) };
652
+ }
@@ -0,0 +1,33 @@
1
+ export {
2
+ prepareSpec,
3
+ validateSource,
4
+ type Finding,
5
+ type ValidationResult,
6
+ type ValidateOptions,
7
+ type PreparedSpec,
8
+ } from "./validate-core.mjs";
9
+
10
+ /**
11
+ * Walk up from `startDir` to the nearest installed astralis-ui's
12
+ * `dist/system-spec.json`. Returns its path, or null. Node only.
13
+ */
14
+ export function findInstalledSpec(startDir: string): string | null;
15
+
16
+ /**
17
+ * Walk up from `startDir` to the nearest `node_modules/astralis-ui/<file>`
18
+ * (default `package.json`). Returns its path, or null. Node only.
19
+ */
20
+ export function findInstalledLibrary(startDir: string, file?: string): string | null;
21
+
22
+ /**
23
+ * Every .tsx/.jsx file at or under `path`, skipping dependency and build
24
+ * folders (SKIP_DIRS): the files `astralis validate` checks. Appends to
25
+ * `into` and returns it, or returns null when `path` does not exist. Node only.
26
+ */
27
+ export function collectSourceFiles(path: string, into?: string[]): string[] | null;
28
+
29
+ /** Folder names never descended into. */
30
+ export const SKIP_DIRS: ReadonlySet<string>;
31
+
32
+ /** Matches the file names that are validated (.tsx and .jsx). */
33
+ export const SOURCE_FILE: RegExp;