astralis-cli 0.4.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 -29
  7. package/src/commands/create.mjs +73 -100
  8. package/src/commands/init.mjs +59 -22
  9. package/src/commands/report.mjs +257 -0
  10. package/src/commands/theme.mjs +77 -104
  11. package/src/commands/validate.mjs +101 -0
  12. package/src/index.mjs +26 -48
  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 +85 -39
  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 +11 -19
  37. package/src/lib/suggest.mjs +32 -0
  38. package/src/lib/ui.mjs +78 -36
  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
package/src/lib/edits.mjs CHANGED
@@ -1,26 +1,149 @@
1
+ import { parse } from "@babel/parser";
2
+
3
+ /**
4
+ * Idempotent transforms for init's and theme's entry-file edits. Every function
5
+ * returns { source, changed, note? } and NEVER guesses: when a file's shape is
6
+ * ambiguous or unparseable it declines with a note, so the caller can print
7
+ * manual instructions instead of corrupting code.
8
+ */
9
+
10
+ const PARSE_OPTIONS = { sourceType: "module", plugins: ["typescript", "jsx"] };
11
+
12
+ function parseModule(source) {
13
+ try {
14
+ return parse(source, PARSE_OPTIONS);
15
+ } catch {
16
+ return null;
17
+ }
18
+ }
19
+
20
+ /** True when the source is a module Babel can parse — the check before any write. */
21
+ export function parses(source) {
22
+ return parseModule(source) !== null;
23
+ }
24
+
25
+ const importedName = (specifier) =>
26
+ specifier.imported.type === "Identifier" ? specifier.imported.name : specifier.imported.value;
27
+
28
+ /** Named imports that provide a runtime value (`import type` provides none). */
29
+ function valueNames(declaration) {
30
+ if (declaration.importKind === "type") return [];
31
+ return declaration.specifiers
32
+ .filter((s) => s.type === "ImportSpecifier" && s.importKind !== "type")
33
+ .map(importedName);
34
+ }
35
+
1
36
  /**
2
- * Idempotent string transforms for init's entry-file edits. Every function
3
- * returns { source, changed, note? } and NEVER guesses: when a file's shape
4
- * is ambiguous (zero or multiple wrap targets), it declines with a note so
5
- * init can print manual instructions instead of corrupting code.
37
+ * Where a new top-level line goes: after the last import, else after the
38
+ * directive prologue ("use client"), else at the very top. Positioned at the
39
+ * end of that statement's line, unless a comment opened on that line runs past
40
+ * it — then right after the statement.
6
41
  */
42
+ function insertionPoint(ast, source) {
43
+ const imports = ast.program.body.filter((n) => n.type === "ImportDeclaration");
44
+ const anchor = imports.at(-1) ?? ast.program.directives.at(-1) ?? ast.program.interpreter;
45
+ if (!anchor) return { at: 0, top: true };
7
46
 
8
- /** Add import lines that aren't already present, after the last existing import. */
47
+ const newline = source.indexOf("\n", anchor.end);
48
+ const lineEnd = newline === -1 ? source.length : newline;
49
+ const spanning = ast.comments.some((c) => c.start >= anchor.end && c.start < lineEnd && c.end > lineEnd);
50
+ return { at: spanning ? anchor.end : lineEnd, top: false };
51
+ }
52
+
53
+ /** The file's own quote and semicolon habit, read off its last import. */
54
+ function importStyle(ast) {
55
+ const last = ast.program.body.filter((n) => n.type === "ImportDeclaration").at(-1);
56
+ if (!last) return null;
57
+ return { quote: last.source.extra.raw[0], semicolon: last.source.end < last.end };
58
+ }
59
+
60
+ /** Re-render a single-line import in the file's style. */
61
+ function restyle(line, declaration, style) {
62
+ if (!style) return line;
63
+ const { start, end } = declaration.source;
64
+ const quoted = style.quote + declaration.source.value + style.quote;
65
+ const body = line.slice(0, start) + quoted + line.slice(end, declaration.end).replace(/;\s*$/, "");
66
+ return body + (style.semicolon ? ";" : "");
67
+ }
68
+
69
+ /**
70
+ * Add imports that aren't already satisfied, judged by parsed specifiers, not
71
+ * text: `import { AstralisProvider, Button } from 'astralis-ui'` already
72
+ * provides AstralisProvider, however it is quoted or wrapped. A named import
73
+ * missing from an existing declaration of the same module is merged into it,
74
+ * so the file never gains a second import of the same binding.
75
+ *
76
+ * `lines` are single import statements, e.g. `import "astralis-ui/styles.css";`.
77
+ * A default or namespace import is added whole unless one already exists.
78
+ */
9
79
  export function addImports(source, lines) {
10
- const missing = lines.filter((line) => !source.includes(line));
11
- if (missing.length === 0) return { source, changed: false };
12
-
13
- const block = missing.join("\n");
14
- const imports = [...source.matchAll(/^import\s[^\n]*$/gm)];
15
- if (imports.length > 0) {
16
- const last = imports[imports.length - 1];
17
- const insertAt = last.index + last[0].length;
18
- return { source: source.slice(0, insertAt) + "\n" + block + source.slice(insertAt), changed: true };
80
+ const ast = parseModule(source);
81
+ if (!ast) return { source, changed: false, note: "the file doesn't parse, so it was left alone" };
82
+
83
+ const existing = ast.program.body.filter((n) => n.type === "ImportDeclaration");
84
+ const style = importStyle(ast);
85
+ const merges = []; // { at, text }
86
+ const additions = [];
87
+
88
+ for (const line of lines) {
89
+ const wanted = parse(line, PARSE_OPTIONS).program.body[0];
90
+ const from = wanted.source.value;
91
+ const sameModule = existing.filter((n) => n.source.value === from);
92
+
93
+ if (wanted.specifiers.length === 0) {
94
+ // Any import of a module evaluates it, so a side-effect import is satisfied by any of them.
95
+ if (sameModule.length === 0) additions.push(restyle(line, wanted, style));
96
+ continue;
97
+ }
98
+
99
+ if (wanted.specifiers.some((s) => s.type !== "ImportSpecifier")) {
100
+ const kinds = wanted.specifiers.map((s) => s.type);
101
+ const satisfied = sameModule.some(
102
+ (n) => n.importKind !== "type" && kinds.every((kind) => n.specifiers.some((s) => s.type === kind)),
103
+ );
104
+ if (!satisfied) additions.push(restyle(line, wanted, style));
105
+ continue;
106
+ }
107
+
108
+ const have = new Set(sameModule.flatMap(valueNames));
109
+ const missing = valueNames(wanted).filter((name) => !have.has(name));
110
+ if (missing.length === 0) continue;
111
+
112
+ const target = sameModule.find(
113
+ (n) => n.importKind !== "type" && n.specifiers.some((s) => s.type === "ImportSpecifier"),
114
+ );
115
+ if (target) {
116
+ const lastSpecifier = target.specifiers.filter((s) => s.type === "ImportSpecifier").at(-1);
117
+ merges.push({ at: lastSpecifier.end, text: missing.map((name) => `, ${name}`).join("") });
118
+ } else {
119
+ const named = `import { ${missing.join(", ")} } from "${from}";`;
120
+ additions.push(restyle(named, parse(named, PARSE_OPTIONS).program.body[0], style));
121
+ }
19
122
  }
20
- // No imports at all — put them at the top, after a directive if present.
21
- const directive = source.match(/^["']use \w+["'];?\s*\n/);
22
- const insertAt = directive ? directive[0].length : 0;
23
- return { source: source.slice(0, insertAt) + block + "\n" + source.slice(insertAt), changed: true };
123
+
124
+ if (merges.length === 0 && additions.length === 0) return { source, changed: false };
125
+
126
+ // Splice from the end backwards so earlier offsets stay valid.
127
+ const { at, top } = insertionPoint(ast, source);
128
+ const edits = [...merges];
129
+ if (additions.length > 0) {
130
+ edits.push({ at, text: top ? additions.join("\n") + "\n" : "\n" + additions.join("\n") });
131
+ }
132
+ let next = source;
133
+ for (const edit of edits.sort((a, b) => b.at - a.at)) {
134
+ next = next.slice(0, edit.at) + edit.text + next.slice(edit.at);
135
+ }
136
+ return { source: next, changed: true };
137
+ }
138
+
139
+ /** Insert a top-level statement after the import block (e.g. the theme-init const). */
140
+ export function addStatementAfterImports(source, statement) {
141
+ if (source.includes(statement.slice(0, 40))) return { source, changed: false };
142
+ const ast = parseModule(source);
143
+ if (!ast) return { source, changed: false, note: "the file doesn't parse, so it was left alone" };
144
+ const { at, top } = insertionPoint(ast, source);
145
+ const text = top ? statement + "\n\n" : "\n\n" + statement;
146
+ return { source: source.slice(0, at) + text + source.slice(at), changed: true };
24
147
  }
25
148
 
26
149
  /** Wrap a single unambiguous occurrence of `target` in open/close JSX tags. */
@@ -39,6 +162,71 @@ export function addTagAttribute(source, tag, attribute) {
39
162
  return { source: source.replace(matches[0][0], `<${tag} ${attribute}`), changed: true };
40
163
  }
41
164
 
165
+ /**
166
+ * Insert markup as the last child of <body>, on its own line indented one
167
+ * step inside the body when </body> starts its line, else just before it.
168
+ * Skipped when `marker` (e.g. "<AstralisDevTools") is already in the file.
169
+ */
170
+ export function insertBeforeBodyClose(source, markup, marker = markup) {
171
+ if (source.includes(marker)) return { source, changed: false };
172
+ const matches = [...source.matchAll(/<\/body>/g)];
173
+ if (matches.length !== 1) return { source, changed: false, note: "</body> not found unambiguously" };
174
+ const at = matches[0].index;
175
+ const lineStart = source.lastIndexOf("\n", at - 1) + 1;
176
+ const before = source.slice(lineStart, at);
177
+ if (/^\s*$/.test(before)) {
178
+ const eol = source.includes("\r\n") ? "\r\n" : "\n";
179
+ return { source: `${source.slice(0, lineStart)}${before} ${markup}${eol}${source.slice(lineStart)}`, changed: true };
180
+ }
181
+ return { source: source.slice(0, at) + markup + source.slice(at), changed: true };
182
+ }
183
+
184
+ /**
185
+ * Append an element to the one array literal assigned to `property` (Vite's
186
+ * `plugins: [react()]`), matching the array's layout: inline stays inline, one
187
+ * per line stays one per line, a trailing comma stays. Skipped when `marker`
188
+ * already appears inside the array.
189
+ */
190
+ export function addArrayElement(source, property, element, marker = element) {
191
+ const ast = parseModule(source);
192
+ if (!ast) return { source, changed: false, note: "the file doesn't parse, so it was left alone" };
193
+
194
+ const arrays = [];
195
+ (function walk(node) {
196
+ if (!node || typeof node.type !== "string") return;
197
+ if (
198
+ (node.type === "ObjectProperty" || node.type === "Property") &&
199
+ !node.computed &&
200
+ (node.key.name ?? node.key.value) === property &&
201
+ node.value.type === "ArrayExpression"
202
+ ) {
203
+ arrays.push(node.value);
204
+ }
205
+ for (const key of Object.keys(node)) {
206
+ if (key === "loc" || key === "start" || key === "end") continue;
207
+ const value = node[key];
208
+ if (Array.isArray(value)) value.forEach(walk);
209
+ else if (value && typeof value === "object") walk(value);
210
+ }
211
+ })(ast.program);
212
+
213
+ if (arrays.length !== 1) return { source, changed: false, note: `no single \`${property}: [...]\` array found` };
214
+ const array = arrays[0];
215
+ if (source.slice(array.start, array.end).includes(marker)) return { source, changed: false };
216
+
217
+ const items = array.elements.filter(Boolean);
218
+ if (items.length === 0) {
219
+ return { source: source.slice(0, array.start + 1) + element + source.slice(array.end - 1), changed: true };
220
+ }
221
+ const last = items.at(-1);
222
+ const multiline = source.slice(array.start, array.end).includes("\n");
223
+ if (!multiline) return { source: `${source.slice(0, last.end)}, ${element}${source.slice(last.end)}`, changed: true };
224
+ const lineStart = source.lastIndexOf("\n", last.start - 1) + 1;
225
+ const indent = source.slice(lineStart, last.start).match(/^\s*/)[0];
226
+ const eol = source.includes("\r\n") ? "\r\n" : "\n";
227
+ return { source: `${source.slice(0, last.end)},${eol}${indent}${element}${source.slice(last.end)}`, changed: true };
228
+ }
229
+
42
230
  /** Insert markup right after the opening <body ...> tag. */
43
231
  export function insertAfterBodyTag(source, insert) {
44
232
  if (source.includes(insert.trim())) return { source, changed: false };
@@ -47,11 +235,3 @@ export function insertAfterBodyTag(source, insert) {
47
235
  const at = matches[0].index + matches[0][0].length;
48
236
  return { source: source.slice(0, at) + insert + source.slice(at), changed: true };
49
237
  }
50
-
51
- /** Insert a top-level statement after the import block (e.g. the theme-init const). */
52
- export function addStatementAfterImports(source, statement) {
53
- if (source.includes(statement.slice(0, 40))) return { source, changed: false };
54
- const imports = [...source.matchAll(/^import\s[^\n]*$/gm)];
55
- const insertAt = imports.length > 0 ? imports[imports.length - 1].index + imports[imports.length - 1][0].length : 0;
56
- return { source: source.slice(0, insertAt) + "\n\n" + statement + source.slice(insertAt), changed: true };
57
- }
@@ -0,0 +1,26 @@
1
+ import { isAbsolute, relative, resolve } from "node:path";
2
+ import { posix } from "./ui.mjs";
3
+
4
+ /**
5
+ * GitHub Actions workflow commands: one `::error` / `::warning` line per
6
+ * finding, which GitHub shows on the changed line of the pull request.
7
+ * https://docs.github.com/actions/reference/workflow-commands-for-github-actions
8
+ */
9
+
10
+ const escapeData = (text) => String(text).replaceAll("%", "%25").replaceAll("\r", "%0D").replaceAll("\n", "%0A");
11
+ const escapeProperty = (text) => escapeData(text).replaceAll(":", "%3A").replaceAll(",", "%2C");
12
+
13
+ /**
14
+ * GitHub places an annotation by its path from the repository root, which is
15
+ * not the working directory when the project sits in a subfolder of the repo.
16
+ */
17
+ export function repositoryPath(file, { cwd = process.cwd(), workspace = process.env.GITHUB_WORKSPACE } = {}) {
18
+ const absolute = isAbsolute(file) ? file : resolve(cwd, file);
19
+ return posix(workspace ? relative(workspace, absolute) : relative(cwd, absolute));
20
+ }
21
+
22
+ export function annotation(kind, finding, options) {
23
+ const file = repositoryPath(finding.file, options);
24
+ const properties = [`file=${escapeProperty(file)}`, `line=${finding.line}`, `col=${finding.column}`, `title=${escapeProperty(`astralis ${finding.code}`)}`];
25
+ return `::${kind === "error" ? "error" : "warning"} ${properties.join(",")}::${escapeData(finding.message)}`;
26
+ }
@@ -0,0 +1,72 @@
1
+ import type { Snapshot } from "./snapshot.mjs";
2
+
3
+ /** Reporting to GitHub: sign-in through the Astralis DevTools GitHub App, the saved sign-in, and issues. Node only. */
4
+
5
+ export const GITHUB_CLIENT_ID: string;
6
+ export const ISSUES_REPO: string;
7
+ /** The app's client ID (ASTRALIS_GITHUB_CLIENT_ID overrides it). Empty when sign-in is not set up. */
8
+ export function clientId(): string;
9
+ /** The repository reports go to (ASTRALIS_ISSUES_REPO overrides it). */
10
+ export function issuesRepo(): string;
11
+
12
+ export type GitHubErrorCode = "network" | "signed-out" | "forbidden" | "github" | "not-configured" | "expired" | "denied" | "cancelled";
13
+ export class GitHubError extends Error {
14
+ code: GitHubErrorCode;
15
+ }
16
+
17
+ export interface SavedSignIn {
18
+ token: string;
19
+ login: string;
20
+ savedAt: string;
21
+ }
22
+ /** The user's config directory for Astralis. */
23
+ export function configDir(env?: Record<string, string | undefined>): string;
24
+ export function tokenStore(dir?: string): {
25
+ file: string;
26
+ read(): SavedSignIn | null;
27
+ write(signIn: { token: string; login: string }): void;
28
+ clear(): void;
29
+ };
30
+
31
+ export interface SignInFlow {
32
+ deviceCode: string;
33
+ userCode: string;
34
+ verificationUri: string;
35
+ expiresAt: number;
36
+ interval: number;
37
+ }
38
+ interface FetchOptions {
39
+ fetchImpl?: typeof fetch;
40
+ }
41
+ export function startSignIn(options?: FetchOptions): Promise<SignInFlow>;
42
+ export function finishSignIn(
43
+ flow: SignInFlow,
44
+ options?: FetchOptions & { sleep?: (ms: number) => Promise<void>; signal?: AbortSignal },
45
+ ): Promise<{ token: string; login: string }>;
46
+
47
+ export interface IssueSummary {
48
+ number: number;
49
+ title: string;
50
+ state: "open" | "closed";
51
+ stateReason: string | null;
52
+ url: string;
53
+ comments: number;
54
+ labels: string[];
55
+ createdAt: string;
56
+ updatedAt: string;
57
+ }
58
+ export function createIssue(token: string, issue: { title: string; body: string }, options?: FetchOptions): Promise<{ number: number; url: string }>;
59
+ export function listIssues(token: string, login: string, options?: FetchOptions): Promise<IssueSummary[]>;
60
+ /** The title and Markdown body of the issue a snapshot becomes. */
61
+ export function issueFromSnapshot(snapshot: Snapshot): { title: string; body: string };
62
+
63
+ /** Add a report to an existing issue, as a comment. */
64
+ export function commentOnIssue(token: string, number: number, body: string, options?: FetchOptions): Promise<{ number: number; url: string }>;
65
+ /** The words a report's issue carries so a later search can find it: the same problem, and the same component. */
66
+ export function matchKeys(snapshot: Snapshot): { fingerprint: string | null; component: string | null };
67
+ /** Issues that may already report this: the same fingerprint, and other open issues about the same component. */
68
+ export function findSimilar(token: string, snapshot: Snapshot, options?: FetchOptions): Promise<{ duplicates: IssueSummary[]; related: IssueSummary[] }>;
69
+ /** The comment a snapshot becomes when it is added to an existing issue. */
70
+ export function commentFromSnapshot(snapshot: Snapshot): string;
71
+ /** GitHub's own new-issue form, pre-filled with the report: for reporting without signing in. At most about 8 kB. */
72
+ export function newIssueUrl(snapshot: Snapshot): string;