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,257 @@
1
+ /* ==========================================================================
2
+ astralis report: an issue snapshot from source files.
3
+ --------------------------------------------------------------------------
4
+ The same astralis-snapshot/1 the DevTools build from a page, built here
5
+ from the JSX of the files that show the problem: the astralis-ui
6
+ components with their literal props, the validator's findings for those
7
+ files, and the versions installed. It prints the exact JSON and opens it
8
+ as a GitHub issue, from the reporter's own account, only when they
9
+ confirm. The first time, they sign in with a code on github.com.
10
+ ========================================================================== */
11
+
12
+ import { createHash } from "node:crypto";
13
+ import { readFileSync, statSync, writeFileSync } from "node:fs";
14
+ import { dirname, join, relative, resolve } from "node:path";
15
+ import { bold, cyan, dim, fail, info, ok, warn, ask, isAssumeYes, confirm, select, posix } from "../lib/ui.mjs";
16
+ import { parseCommandArgs } from "../lib/args.mjs";
17
+ import { commandNamed } from "../lib/commands.mjs";
18
+ import { loadSpec } from "../lib/spec-load.mjs";
19
+ import { detectFramework, readPackageJson } from "../lib/detect.mjs";
20
+ import { prepareSpec, validateSource } from "../lib/validate-core.mjs";
21
+ import { treeFromSource } from "../lib/report-tree.mjs";
22
+ import { SNAPSHOT_FORMAT, LIMITS, checkSnapshot } from "../lib/snapshot.mjs";
23
+ import {
24
+ commentFromSnapshot,
25
+ commentOnIssue,
26
+ createIssue,
27
+ findSimilar,
28
+ finishSignIn,
29
+ issueFromSnapshot,
30
+ issuesRepo,
31
+ newIssueUrl,
32
+ startSignIn,
33
+ tokenStore,
34
+ } from "../lib/github.mjs";
35
+
36
+ /** The nearest node_modules/<name>/package.json above `root`: its version, or null. */
37
+ function installedVersion(root, name) {
38
+ for (let dir = resolve(root); ; dir = dirname(dir)) {
39
+ const file = join(dir, "node_modules", name, "package.json");
40
+ if (statSync(file, { throwIfNoEntry: false })) {
41
+ try {
42
+ return JSON.parse(readFileSync(file, "utf8")).version ?? null;
43
+ } catch {
44
+ return null;
45
+ }
46
+ }
47
+ if (dirname(dir) === dir) return null;
48
+ }
49
+ }
50
+
51
+ function environmentOf(cwd) {
52
+ const framework = detectFramework(readPackageJson(cwd));
53
+ return {
54
+ framework: { name: framework, version: framework ? installedVersion(cwd, framework) : null },
55
+ react: installedVersion(cwd, "react"),
56
+ browser: null,
57
+ viewport: null,
58
+ colorMode: null,
59
+ };
60
+ }
61
+
62
+ /** The reporter's words: flags first, then prompts, with --yes taking what the flags gave. */
63
+ function describe(values) {
64
+ const answer = (flag, question) => {
65
+ if (values[flag] !== undefined) return values[flag];
66
+ if (isAssumeYes()) return undefined;
67
+ return ask(question) || undefined;
68
+ };
69
+ const title = answer("title", `${bold("Title")} ${dim("(one line)")}: `);
70
+ if (!title?.trim()) {
71
+ fail(`A report needs a title — pass ${cyan('--title "…"')}${isAssumeYes() ? " with --yes" : ""}.`);
72
+ }
73
+ const description = { title: title.trim().slice(0, LIMITS.title) };
74
+ const happened = answer("happened", `${bold("What happened?")} ${dim("(Enter to skip)")} `);
75
+ const expected = answer("expected", `${bold("What did you expect?")} ${dim("(Enter to skip)")} `);
76
+ if (happened?.trim()) description.happened = happened.trim().slice(0, LIMITS.body);
77
+ if (expected?.trim()) description.expected = expected.trim().slice(0, LIMITS.body);
78
+ return description;
79
+ }
80
+
81
+ /** Sign in with GitHub's device flow, in the terminal, and save the sign-in. */
82
+ async function signIn(store) {
83
+ let flow;
84
+ try {
85
+ flow = await startSignIn();
86
+ } catch (error) {
87
+ fail(`${error.message} Nothing was sent. ${cyan("--out snapshot.json")} saves the snapshot to attach by hand.`);
88
+ }
89
+ console.log("");
90
+ console.log(` Sign in to GitHub: open ${cyan(flow.verificationUri)} and enter ${bold(flow.userCode)}`);
91
+ console.log(dim(` The Astralis DevTools app can only read and write issues on ${issuesRepo()}.`));
92
+ console.log("");
93
+ try {
94
+ const signedIn = await finishSignIn(flow);
95
+ store.write(signedIn);
96
+ ok(`signed in as ${bold(signedIn.login)}`);
97
+ return signedIn;
98
+ } catch (error) {
99
+ fail(`${error.message} Nothing was sent.`);
100
+ }
101
+ }
102
+
103
+ export async function run(argv) {
104
+ const args = parseCommandArgs(commandNamed("report"), argv);
105
+ if (!args) return;
106
+ const { values, positionals } = args;
107
+ const cwd = process.cwd();
108
+ if (values["sign-out"]) {
109
+ const store = tokenStore();
110
+ const saved = store.read();
111
+ store.clear();
112
+ if (saved) ok(`signed out of GitHub (${saved.login}). The app's access ends when you revoke it at github.com/settings/applications.`);
113
+ else info("not signed in to GitHub.");
114
+ return;
115
+ }
116
+ if (positionals.length === 0) {
117
+ fail(`Name the files that show the problem: ${cyan("astralis report app/page.tsx")}.`);
118
+ }
119
+
120
+ const { spec, text: specText } = loadSpec(values.spec, cwd);
121
+ const prepared = prepareSpec(spec);
122
+ const tree = [];
123
+ const findings = [];
124
+ for (const given of positionals) {
125
+ const file = resolve(given);
126
+ if (!/\.(tsx|jsx)$/.test(file) || !statSync(file, { throwIfNoEntry: false })?.isFile()) {
127
+ fail(`${given} is not a .tsx or .jsx file.`);
128
+ }
129
+ const rel = posix(relative(cwd, file));
130
+ if (rel.startsWith("..")) fail(`${given} is outside this project; run the command from the project root.`);
131
+ const source = readFileSync(file, "utf8");
132
+ try {
133
+ tree.push(...treeFromSource(source, spec, { includeText: values["include-text"] }));
134
+ } catch (error) {
135
+ fail(`${rel} does not parse: ${error.message}`);
136
+ }
137
+ const { errors, warnings } = validateSource(source, prepared, rel);
138
+ findings.push(...errors, ...warnings);
139
+ }
140
+ if (tree.length === 0) fail("None of those files renders an astralis-ui component, so there is nothing to report.");
141
+
142
+ const snapshot = {
143
+ format: SNAPSHOT_FORMAT,
144
+ source: "cli",
145
+ library: {
146
+ name: "astralis-ui",
147
+ version: spec.version,
148
+ specVersion: spec.specVersion,
149
+ specSha256: createHash("sha256").update(specText).digest("hex"),
150
+ },
151
+ environment: environmentOf(cwd),
152
+ route: null,
153
+ tree,
154
+ ...(values["no-findings"] ? {} : { findings: findings.slice(0, LIMITS.findings) }),
155
+ description: describe(values),
156
+ };
157
+ const problems = checkSnapshot(snapshot);
158
+ if (problems.length) fail(`The snapshot is not valid: ${problems.join("; ")}`);
159
+
160
+ // The exact content, before anything leaves the machine.
161
+ const json = JSON.stringify(snapshot, null, 2);
162
+ console.log(json);
163
+
164
+ if (values.out) {
165
+ writeFileSync(resolve(values.out), `${json}\n`);
166
+ ok(`snapshot written to ${values.out} ${dim("(nothing was sent)")}`);
167
+ return;
168
+ }
169
+ if (values["dry-run"]) {
170
+ info("dry run: nothing was sent.");
171
+ return;
172
+ }
173
+ if (values.link) {
174
+ // No sign-in: GitHub's own form, pre-filled, submitted in the browser.
175
+ ok("open this link to check the report on GitHub and submit it yourself:");
176
+ console.log(` ${cyan(newIssueUrl(snapshot))}`);
177
+ console.log(dim(" Nothing is sent until you press Create on GitHub."));
178
+ return;
179
+ }
180
+ const send = await confirm(`Open this as an issue on github.com/${issuesRepo()}?`, {
181
+ hint: `Pass --yes to send, or ${cyan("--out snapshot.json")} to save it instead.`,
182
+ });
183
+ if (!send) {
184
+ info("nothing was sent.");
185
+ return;
186
+ }
187
+ const store = tokenStore();
188
+ let signedIn = store.read() ?? (await signIn(store));
189
+ const keep = `Nothing was sent. ${cyan("--out snapshot.json")} saves the snapshot to attach by hand.`;
190
+ /** Run `work` signed in; a sign-in GitHub revoked is replaced, once. */
191
+ const asUser = async (work) => {
192
+ try {
193
+ return await work(signedIn.token);
194
+ } catch (error) {
195
+ if (error.code !== "signed-out") throw error;
196
+ store.clear();
197
+ signedIn = await signIn(store);
198
+ return work(signedIn.token);
199
+ }
200
+ };
201
+
202
+ const target = await chooseTarget(values, () => asUser((token) => findSimilar(token, snapshot)));
203
+ try {
204
+ if (target) {
205
+ const added = await asUser((token) => commentOnIssue(token, target, commentFromSnapshot(snapshot)));
206
+ ok(`report added to issue #${added.number} as ${signedIn.login}: ${cyan(added.url)}`);
207
+ } else {
208
+ const created = await asUser((token) => createIssue(token, issueFromSnapshot(snapshot)));
209
+ ok(`issue #${created.number} opened as ${signedIn.login}: ${cyan(created.url)}`);
210
+ }
211
+ } catch (error) {
212
+ fail(`${error.message} ${keep}`);
213
+ }
214
+ }
215
+
216
+ const line = (issue) => `#${issue.number} ${issue.title} ${dim(`(${issue.state})`)}`;
217
+
218
+ /**
219
+ * Where the report goes: an existing issue's number, or null for a new issue.
220
+ * --add-to and --new decide without searching. Otherwise the issues that may
221
+ * already report it are shown, and the reporter chooses; with --yes, a new
222
+ * issue is opened and the possible duplicates are listed for them to check.
223
+ */
224
+ async function chooseTarget(values, searchSimilar) {
225
+ if (values["add-to"] !== undefined) {
226
+ const number = Number(String(values["add-to"]).replace(/^#/, ""));
227
+ if (!Number.isInteger(number) || number < 1) fail(`--add-to takes an issue number, like ${cyan("--add-to 12")}.`);
228
+ return number;
229
+ }
230
+ if (values.new) return null;
231
+ let similar;
232
+ try {
233
+ similar = await searchSimilar();
234
+ } catch (error) {
235
+ warn(`could not check for an existing issue (${error.message}); opening a new one.`);
236
+ return null;
237
+ }
238
+ const { duplicates, related } = similar;
239
+ if (related.length) {
240
+ info(`open issues about the same component:`);
241
+ for (const issue of related) console.log(` ${line(issue)} ${dim(issue.url)}`);
242
+ }
243
+ if (!duplicates.length) return null;
244
+ console.log("");
245
+ console.log(bold("This may already be reported:"));
246
+ for (const issue of duplicates) console.log(` ${line(issue)} ${dim(issue.url)}`);
247
+ if (isAssumeYes()) {
248
+ info(`opening a new issue; pass ${cyan(`--add-to ${duplicates[0].number}`)} to add your report to an existing one instead.`);
249
+ return null;
250
+ }
251
+ const choice = await select("Add your report to one of them, or open a new issue?", [
252
+ ...duplicates.slice(0, 3).map((issue) => ({ value: issue.number, label: `Add it to #${issue.number} ${issue.title}` })),
253
+ { value: 0, label: "Open a new issue" },
254
+ ]);
255
+ if (choice === null) fail("Choose one of the listed numbers. Nothing was sent.");
256
+ return choice || null;
257
+ }
@@ -1,15 +1,16 @@
1
- import { parseArgs } from "node:util";
2
- import { existsSync, writeFileSync } from "node:fs";
3
- import { themeCss, validateSeed, isEmptySeed } from "astralis-ui/serialize";
4
- import { ok, fail, cyan, dim } from "../lib/ui.mjs";
1
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { dirname, join, relative, resolve } from "node:path";
3
+ import { ok, warn, fail, cyan, dim, posix } from "../lib/ui.mjs";
4
+ import { parseCommandArgs } from "../lib/args.mjs";
5
+ import { commandNamed } from "../lib/commands.mjs";
6
+ import { readPackageJson, detectFramework, findEntryFile } from "../lib/detect.mjs";
7
+ import { addImports, parses } from "../lib/edits.mjs";
8
+ import { loadThemeLibrary } from "../lib/library.mjs";
5
9
 
6
10
  /**
7
- * Renders a theme seed as a stylesheet — the static equivalent of
8
- * <AstralisProvider tokens={seed}>, for people who prefer build-time theming
9
- * over the runtime provider.
10
- *
11
- * Both the colour maths and the serialization come from the library and are
12
- * never duplicated here, so `astralis theme` and the provider cannot drift.
11
+ * Renders a theme seed as a stylesheet: the static equivalent of
12
+ * <AstralisProvider tokens={seed}>. The colour maths and serialization come
13
+ * from the library, never duplicated here, so the two cannot drift.
13
14
  */
14
15
 
15
16
  /** Flag -> seed field. */
@@ -32,62 +33,7 @@ const NUMBER_FLAGS = {
32
33
  motion: "motionScale",
33
34
  };
34
35
 
35
- const USAGE = `Usage: astralis theme [options]
36
-
37
- Colours
38
- --brand <hex> brand hue, e.g. "#8b5cf6"
39
- --gray <hex> neutral hue — drives every surface, label and border,
40
- and tints white/black so the page follows the neutral
41
-
42
- Status (each seeds its own palette; the red/orange/green/blue hues and
43
- their colorScheme values are never altered)
44
- --error <hex> defaults to red
45
- --warning <hex> defaults to orange
46
- --success <hex> defaults to green
47
- --info <hex> defaults to blue
48
-
49
- Typefaces
50
- --font-heading <stack>
51
- --font-body <stack>
52
- --font-mono <stack>
53
-
54
- Scales (1 = library default; 0 is allowed)
55
- --radius <n> border-radius multiplier
56
- --spacing <n> spacing multiplier — the density dial
57
- --font-scale <n> font-size multiplier
58
- --motion <n> duration multiplier (0 disables transitions)
59
-
60
- Output
61
- --out <file> default: astralis-theme.css
62
- --force overwrite an existing file
63
-
64
- A bare hex is shorthand for --brand: astralis theme "#8b5cf6"`;
65
-
66
- export async function run(argv) {
67
- let parsed;
68
- try {
69
- parsed = parseArgs({
70
- args: argv,
71
- options: {
72
- ...Object.fromEntries(
73
- [...Object.keys(STRING_FLAGS), ...Object.keys(NUMBER_FLAGS)].map((f) => [f, { type: "string" }]),
74
- ),
75
- out: { type: "string", default: "astralis-theme.css" },
76
- force: { type: "boolean", default: false },
77
- help: { type: "boolean", default: false },
78
- },
79
- allowPositionals: true,
80
- });
81
- } catch (error) {
82
- fail(`${error.message}\n\n${USAGE}`);
83
- }
84
-
85
- const { values, positionals } = parsed;
86
- if (values.help) {
87
- console.log(USAGE);
88
- return;
89
- }
90
-
36
+ function seedFrom(values, positionals) {
91
37
  const seed = {};
92
38
  for (const [flag, field] of Object.entries(STRING_FLAGS)) {
93
39
  if (values[flag] !== undefined) seed[field] = values[flag];
@@ -95,36 +41,108 @@ export async function run(argv) {
95
41
  for (const [flag, field] of Object.entries(NUMBER_FLAGS)) {
96
42
  if (values[flag] === undefined) continue;
97
43
  const n = Number(values[flag]);
98
- if (!Number.isFinite(n)) fail(`--${flag} expects a number, got "${values[flag]}".`);
44
+ if (values[flag].trim() === "" || !Number.isFinite(n)) fail(`--${flag} expects a number, got "${values[flag]}".`);
99
45
  seed[field] = n;
100
46
  }
101
-
102
- // Back-compat: `astralis theme "#8b5cf6"` still means --brand.
47
+ // `astralis theme "#8b5cf6"` means --brand.
103
48
  if (positionals[0]) {
104
- if (seed.brandColor) fail("Pass the brand colour as a positional OR as --brand, not both.");
49
+ if (seed.brandColor) fail("Pass the brand colour as an argument or as --brand, not both.");
105
50
  seed.brandColor = positionals[0].toLowerCase();
106
51
  }
52
+ return seed;
53
+ }
54
+
55
+ /**
56
+ * The same WCAG contracts the library's build gate enforces, run against the
57
+ * palette this seed generates. Returns { results } or { skipped: reason }.
58
+ */
59
+ function checkContrast(library, seed) {
60
+ try {
61
+ const palette = library.contrast.parsePaletteFromCss(readFileSync(library.stylesPath, "utf8"));
62
+ return { results: library.contrast.verifySeedContrast(seed, palette) };
63
+ } catch (error) {
64
+ return { skipped: error.message };
65
+ }
66
+ }
67
+
68
+ export async function run(argv) {
69
+ const args = parseCommandArgs(commandNamed("theme"), argv);
70
+ if (!args) return;
71
+ const { values, positionals } = args;
107
72
 
108
- if (isEmptySeed(seed)) fail(`Nothing to generate — no theme options given.\n\n${USAGE}`);
73
+ const seed = seedFrom(values, positionals);
74
+ const cwd = process.cwd();
75
+ const library = await loadThemeLibrary(cwd);
76
+ const { themeCss, validateSeed, isEmptySeed } = library.serialize;
109
77
 
78
+ if (isEmptySeed(seed)) fail(`Nothing to generate: no theme options given. Run ${cyan("astralis theme --help")}.`);
110
79
  const issues = validateSeed(seed);
111
80
  if (issues.length) {
112
81
  fail(`Invalid theme options:\n${issues.map((i) => ` ${i.field}: ${i.message}`).join("\n")}`);
113
82
  }
114
83
 
115
- if (existsSync(values.out) && !values.force) {
116
- fail(`${values.out} already exists — pass --force to overwrite.`);
84
+ // Next to the code that imports it, as `astralis add` does for blocks.
85
+ const out = values.out ?? (existsSync(join(cwd, "src")) ? join("src", "astralis-theme.css") : "astralis-theme.css");
86
+ const outPath = resolve(cwd, out);
87
+ if (existsSync(outPath) && !values.force) fail(`${posix(out)} already exists — pass --force to overwrite.`);
88
+
89
+ const strict = values["strict-contrast"];
90
+ const contrast = checkContrast(library, seed);
91
+ if (contrast.skipped) {
92
+ if (strict) fail(`Couldn't verify contrast (${contrast.skipped}), so nothing was written under --strict-contrast.`);
93
+ warn(`contrast check skipped: ${contrast.skipped}`);
94
+ } else {
95
+ const failures = contrast.results.filter((r) => !r.pass);
96
+ for (const r of failures) {
97
+ warn(
98
+ `contrast: [${r.mode}] ${r.rule} — ${r.fgHex ?? "?"} on ${r.bgHex ?? "?"} is ` +
99
+ `${r.ratio ? r.ratio.toFixed(2) : "unresolvable"}:1, needs ${r.min}:1`,
100
+ );
101
+ }
102
+ if (failures.length === 0) {
103
+ ok(`contrast: all ${contrast.results.length} promised pairings clear WCAG AA (light + dark)`);
104
+ } else if (strict) {
105
+ fail(`${failures.length} of ${contrast.results.length} pairings fall below WCAG AA — nothing written under --strict-contrast.`);
106
+ } else {
107
+ warn(`${failures.length} of ${contrast.results.length} pairings fall below WCAG AA — a darker or lighter seed usually fixes it.`);
108
+ }
117
109
  }
118
110
 
119
- writeFileSync(values.out, themeCss(seed));
120
- ok(`wrote ${cyan(values.out)}`);
111
+ writeFileSync(outPath, themeCss(seed));
112
+ const from = library.source === "project" ? "your project's" : "the CLI's bundled";
113
+ ok(`wrote ${cyan(posix(out))} ${dim(`(astralis-ui ${library.version}, ${from} copy)`)}`);
114
+ if (library.outdated) {
115
+ warn(`Your astralis-ui ${library.outdated} predates static themes; upgrade it so the file matches the library you ship.`);
116
+ }
121
117
 
122
- const usesFont = seed.fontHeading || seed.fontBody || seed.fontMono;
123
- console.log(
124
- `\nImport it after the library stylesheet:\n` +
118
+ // A generated stylesheet nobody imports changes nothing, silently. After the
119
+ // last import is after astralis-ui/styles.css: the order the override needs.
120
+ const pkg = readPackageJson(cwd);
121
+ const entry = pkg ? findEntryFile(cwd, detectFramework(pkg)) : null;
122
+ const specifier = entry ? posix(relative(dirname(entry.path), outPath)) : null;
123
+ const line = specifier ? `import "${specifier.startsWith(".") ? specifier : `./${specifier}`}";` : null;
124
+
125
+ if (!values["no-import"] && entry) {
126
+ const result = addImports(readFileSync(entry.path, "utf8"), [line]);
127
+ if (result.changed && parses(result.source)) {
128
+ writeFileSync(entry.path, result.source);
129
+ ok(`imported in ${cyan(entry.relative)} ${dim("(after the library stylesheet)")}`);
130
+ } else if (result.changed || result.note) {
131
+ warn(`${entry.relative} ${result.note ?? "couldn't be edited safely"} — add this after the library stylesheet:`);
132
+ console.log(` ${cyan(line)}`);
133
+ } else {
134
+ ok(`already imported in ${cyan(entry.relative)}`);
135
+ }
136
+ } else if (!values["no-import"]) {
137
+ warn("No Next.js or Vite entry point found — import it yourself:");
138
+ console.log(
125
139
  ` ${cyan('import "astralis-ui/styles.css";')}\n` +
126
- ` ${cyan(`import "./${values.out}";`)}\n` +
127
- (usesFont ? `${dim("Custom fonts must be loaded by your app (next/font or a <link>).")}\n` : "") +
128
- `${dim("Runtime alternative: <AstralisProvider tokens={…}> — same math.")}`,
129
- );
140
+ ` ${cyan(`import "./${posix(out)}";`)} ${dim("← must come second")}`,
141
+ );
142
+ }
143
+
144
+ if (seed.fontHeading || seed.fontBody || seed.fontMono) {
145
+ console.log(dim("\nCustom fonts must be loaded by your app (next/font or a <link>)."));
146
+ }
147
+ console.log(dim("Runtime alternative: <AstralisProvider tokens={…}> — same math."));
130
148
  }
@@ -0,0 +1,101 @@
1
+ /* ==========================================================================
2
+ astralis validate — check TSX against the installed design system.
3
+ --------------------------------------------------------------------------
4
+ Loads dist/system-spec.json from the installed astralis-ui (or --spec) and
5
+ runs the validator core over every .tsx/.jsx under the given paths. Exits
6
+ 1 when anything that typechecks-but-fails is found.
7
+ ========================================================================== */
8
+
9
+ import { readFileSync } from "node:fs";
10
+ import { relative, resolve } from "node:path";
11
+ import { bold, dim, red, yellow, green, ok, fail } from "../lib/ui.mjs";
12
+ import { parseCommandArgs } from "../lib/args.mjs";
13
+ import { commandNamed } from "../lib/commands.mjs";
14
+ import { prepareSpec, validateSource } from "../lib/validate-core.mjs";
15
+ import { loadSpec } from "../lib/spec-load.mjs";
16
+ import { collectSourceFiles } from "../lib/source-files.mjs";
17
+ import { annotation } from "../lib/github-annotations.mjs";
18
+
19
+ const FORMATS = ["text", "json", "github"];
20
+
21
+ /** --format wins; --json means json; inside GitHub Actions the default is annotations. */
22
+ function chooseFormat(values, env = process.env) {
23
+ if (values.format !== undefined && !FORMATS.includes(values.format)) {
24
+ fail(`--format must be one of ${FORMATS.join(", ")} (got "${values.format}").`);
25
+ }
26
+ if (values.json && values.format !== undefined && values.format !== "json") {
27
+ fail(`--json and --format ${values.format} disagree; pass one of them.`);
28
+ }
29
+ if (values.json) return "json";
30
+ return values.format ?? (env.GITHUB_ACTIONS === "true" ? "github" : "text");
31
+ }
32
+
33
+ function collectFiles(path, into) {
34
+ if (!collectSourceFiles(path, into)) fail(`No such path: ${path}`);
35
+ return into;
36
+ }
37
+
38
+ export async function run(argv) {
39
+ const args = parseCommandArgs(commandNamed("validate"), argv);
40
+ if (!args) return;
41
+ const paths = args.positionals.length > 0 ? args.positionals : ["."];
42
+ const strictTokens = args.values["strict-tokens"];
43
+ const format = chooseFormat(args.values);
44
+
45
+ const { spec } = loadSpec(args.values.spec);
46
+ const prepared = prepareSpec(spec);
47
+ const files = paths.reduce((acc, p) => collectFiles(resolve(p), acc), []);
48
+ if (files.length === 0) fail("No .tsx/.jsx files found under the given paths.");
49
+
50
+ const results = [];
51
+ let errorCount = 0;
52
+ let warningCount = 0;
53
+
54
+ for (const file of files) {
55
+ const rel = relative(process.cwd(), file) || file;
56
+ const { errors, warnings } = validateSource(readFileSync(file, "utf8"), prepared, rel, { strictTokens });
57
+ errorCount += errors.length;
58
+ warningCount += warnings.length;
59
+ if (errors.length || warnings.length) results.push({ file: rel, errors, warnings });
60
+ }
61
+
62
+ if (format === "json") {
63
+ console.log(JSON.stringify({
64
+ spec: { name: spec.name, version: spec.version, specVersion: spec.specVersion },
65
+ files: files.length,
66
+ errors: errorCount,
67
+ warnings: warningCount,
68
+ results,
69
+ }, null, 2));
70
+ if (errorCount) process.exitCode = 1;
71
+ return;
72
+ }
73
+
74
+ if (format === "github") {
75
+ for (const r of results) {
76
+ for (const e of r.errors) console.log(annotation("error", e));
77
+ for (const w of r.warnings) console.log(annotation("warning", w));
78
+ }
79
+ }
80
+
81
+ for (const r of format === "text" ? results : []) {
82
+ console.log(`\n${bold(r.file)}`);
83
+ const all = [...r.errors.map((e) => ({ ...e, kind: "error" })), ...r.warnings.map((w) => ({ ...w, kind: "warn" }))]
84
+ .sort((a, b) => a.line - b.line || a.column - b.column);
85
+ for (const issue of all) {
86
+ const mark = issue.kind === "error" ? red("✗") : yellow("!");
87
+ console.log(` ${dim(`${issue.line}:${issue.column}`)} ${mark} ${issue.message} ${dim(issue.code)}`);
88
+ }
89
+ }
90
+
91
+ const summary = `${files.length} file(s) against ${spec.name}@${spec.version}` +
92
+ ` — ${errorCount ? red(`${errorCount} error(s)`) : green("0 errors")}, ` +
93
+ (warningCount ? yellow(`${warningCount} warning(s)`) : "0 warnings");
94
+ console.log("");
95
+ if (errorCount) {
96
+ console.error(`${red("✗")} ${summary}`);
97
+ process.exitCode = 1;
98
+ } else {
99
+ ok(summary);
100
+ }
101
+ }
package/src/index.mjs CHANGED
@@ -1,64 +1,43 @@
1
1
  #!/usr/bin/env node
2
2
  import { readFileSync } from "node:fs";
3
- import { fileURLToPath } from "node:url";
4
- import { join, dirname } from "node:path";
5
- import { bold, cyan, dim, fail, closePrompts, CliExit } from "./lib/ui.mjs";
3
+ import { cyan, dim, red, fail, CliExit } from "./lib/ui.mjs";
4
+ import { COMMANDS } from "./lib/commands.mjs";
5
+ import { mainHelp } from "./lib/args.mjs";
6
+ import { suggest } from "./lib/suggest.mjs";
6
7
 
7
- const COMMANDS = {
8
+ const MODULES = {
8
9
  create: () => import("./commands/create.mjs"),
9
10
  init: () => import("./commands/init.mjs"),
10
11
  add: () => import("./commands/add.mjs"),
11
12
  theme: () => import("./commands/theme.mjs"),
13
+ validate: () => import("./commands/validate.mjs"),
14
+ report: () => import("./commands/report.mjs"),
12
15
  "connect-mcp": () => import("./commands/connect-mcp.mjs"),
13
16
  };
14
17
 
15
- const HELP = `
16
- ${bold("astralis")} — setup and tooling for Astralis UI
17
-
18
- ${bold("Usage")}
19
- astralis <command> [options]
20
-
21
- ${bold("Commands")}
22
- ${cyan("create <name>")} scaffold a new project (official create-next-app /
23
- create-vite prompts) and wire Astralis into it
24
- ${dim("--framework next|vite · extra args pass to the scaffolder")}
25
- ${cyan("init")} wire astralis-ui into this project (Next.js or Vite)
26
- ${dim("--dry-run show the changes without writing")}
27
- ${cyan("add <block>...")} copy a block's source into this project
28
- ${dim("--list every available block, by category")}
29
- ${dim("--dir <path> where to write (default [src/]components/blocks)")}
30
- ${dim("--overwrite · --dry-run · --registry <url>")}
31
- ${cyan("theme")} generate a static theme stylesheet from a seed
32
- ${dim("--brand/--gray <hex> · --font-heading/-body/-mono <stack>")}
33
- ${dim("--radius/--spacing/--font-scale/--motion <n>")}
34
- ${dim("--out <file> (default astralis-theme.css) · --force")}
35
- ${dim("run `astralis theme --help` for the full list")}
36
- ${cyan("connect-mcp")} connect a client to the Astralis docs server
37
- ${dim("prompts for the client, then configures it for you")}
38
- ${dim("--client claude-code|codex|cursor|claude-desktop|antigravity")}
39
- ${dim(" skip the prompt and pick the client directly")}
40
-
41
- ${bold("Docs")} ${cyan("https://astralis-zeta.vercel.app/docs")}
42
- `;
43
-
44
- const [command, ...rest] = process.argv.slice(2);
18
+ const [name, ...rest] = process.argv.slice(2);
19
+ const debug = process.argv.includes("--debug");
45
20
 
46
21
  try {
47
- if (!command || command === "--help" || command === "-h" || command === "help") {
48
- console.log(HELP);
49
- } else if (command === "--version" || command === "-v") {
50
- const pkg = JSON.parse(readFileSync(join(dirname(fileURLToPath(import.meta.url)), "..", "package.json"), "utf8"));
51
- console.log(pkg.version);
52
- } else if (COMMANDS[command]) {
53
- const { run } = await COMMANDS[command]();
22
+ if (!name || name === "--help" || name === "-h" || name === "help") {
23
+ console.log(mainHelp(COMMANDS));
24
+ } else if (name === "--version" || name === "-v") {
25
+ console.log(JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version);
26
+ } else if (MODULES[name]) {
27
+ const { run } = await MODULES[name]();
54
28
  await run(rest);
55
29
  } else {
56
- fail(`Unknown command "${command}" — run ${cyan("astralis --help")}.`);
30
+ const near = suggest(name, Object.keys(MODULES));
31
+ fail(`Unknown command "${name}".${near ? ` Did you mean "${near}"?` : ""} Run ${cyan("astralis --help")} for the list.`);
57
32
  }
58
33
  } catch (error) {
59
- // fail() has already printed and set the exit code; anything else is a bug
60
- // and deserves its stack.
61
- if (!(error instanceof CliExit)) throw error;
62
- } finally {
63
- closePrompts();
34
+ if (!(error instanceof CliExit)) {
35
+ process.exitCode = 1;
36
+ if (debug) {
37
+ console.error(error);
38
+ } else {
39
+ console.error(`${red("✗")} Unexpected error: ${error?.message ?? error}`);
40
+ console.error(dim(` Run it again with --debug for the stack trace.`));
41
+ }
42
+ }
64
43
  }