astralis-cli 0.4.0 → 0.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +179 -0
- package/LICENSE +21 -0
- package/README.md +179 -29
- package/package.json +29 -10
- package/src/commands/add.mjs +48 -71
- package/src/commands/connect-mcp.mjs +66 -29
- package/src/commands/create.mjs +73 -100
- package/src/commands/init.mjs +59 -22
- package/src/commands/report.mjs +257 -0
- package/src/commands/theme.mjs +77 -104
- package/src/commands/validate.mjs +101 -0
- package/src/index.mjs +26 -48
- package/src/lib/args.mjs +135 -0
- package/src/lib/aria.mjs +40 -0
- package/src/lib/children-rule.mjs +23 -0
- package/src/lib/ci-setup.mjs +78 -0
- package/src/lib/ci.mjs +155 -0
- package/src/lib/commands.mjs +214 -0
- package/src/lib/css-value.mjs +141 -0
- package/src/lib/devtools-setup.mjs +142 -0
- package/src/lib/edits.mjs +206 -26
- package/src/lib/github-annotations.mjs +26 -0
- package/src/lib/github.d.mts +72 -0
- package/src/lib/github.mjs +339 -0
- package/src/lib/library.mjs +40 -0
- package/src/lib/menu.mjs +59 -0
- package/src/lib/prompt-child.mjs +85 -39
- package/src/lib/registry.mjs +37 -4
- package/src/lib/report-tree.mjs +134 -0
- package/src/lib/run.mjs +39 -0
- package/src/lib/snapshot.d.mts +65 -0
- package/src/lib/snapshot.mjs +371 -0
- package/src/lib/source-files.mjs +29 -0
- package/src/lib/spec-load.mjs +32 -0
- package/src/lib/spec-resolve.mjs +20 -0
- package/src/lib/starter.mjs +11 -19
- package/src/lib/suggest.mjs +32 -0
- package/src/lib/ui.mjs +78 -36
- package/src/lib/validate-core.d.mts +48 -0
- package/src/lib/validate-core.mjs +655 -0
- package/src/lib/validate.d.mts +33 -0
- package/src/lib/validate.mjs +8 -0
|
@@ -0,0 +1,339 @@
|
|
|
1
|
+
/* ==========================================================================
|
|
2
|
+
Reporting to GitHub: sign-in, the saved sign-in, and the issues.
|
|
3
|
+
--------------------------------------------------------------------------
|
|
4
|
+
A report becomes an issue on the Astralis repository, opened by the
|
|
5
|
+
reporter's own GitHub account. Sign-in is GitHub's device flow through the
|
|
6
|
+
Astralis DevTools GitHub App: the reporter enters a short code on
|
|
7
|
+
github.com, and the app can do one thing, read and write issues on the
|
|
8
|
+
Astralis repository. It needs no client secret, so none ships here.
|
|
9
|
+
|
|
10
|
+
The token is saved in a file only the user can read, in their config
|
|
11
|
+
directory, and is shared by `astralis report` and the DevTools bridge. It
|
|
12
|
+
never reaches a web page: both run in Node and call GitHub themselves.
|
|
13
|
+
========================================================================== */
|
|
14
|
+
|
|
15
|
+
import { createHash } from "node:crypto";
|
|
16
|
+
import { chmodSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
17
|
+
import { homedir } from "node:os";
|
|
18
|
+
import { join } from "node:path";
|
|
19
|
+
import { LIMITS, toRepro } from "./snapshot.mjs";
|
|
20
|
+
|
|
21
|
+
/** The Astralis DevTools GitHub App. Public by design: the device flow has no secret. */
|
|
22
|
+
export const GITHUB_CLIENT_ID = "Iv23liqZqPWZWAsCwTUG";
|
|
23
|
+
|
|
24
|
+
/** Where reports go. */
|
|
25
|
+
export const ISSUES_REPO = "sekiro-9/astralis-ui";
|
|
26
|
+
|
|
27
|
+
/** github.com and its API; ASTRALIS_GITHUB_URL and ASTRALIS_GITHUB_API_URL override them, for tests. */
|
|
28
|
+
const web = () => process.env.ASTRALIS_GITHUB_URL || "https://github.com";
|
|
29
|
+
const api = () => process.env.ASTRALIS_GITHUB_API_URL || "https://api.github.com";
|
|
30
|
+
/** GitHub refuses an issue body longer than this. */
|
|
31
|
+
const MAX_BODY = 65536;
|
|
32
|
+
/** The longest new-issue link GitHub and browsers reliably take. */
|
|
33
|
+
const MAX_URL = 8000;
|
|
34
|
+
|
|
35
|
+
/** The app's client ID; ASTRALIS_GITHUB_CLIENT_ID overrides it (another app, or "" to switch sign-in off). */
|
|
36
|
+
export const clientId = () => process.env.ASTRALIS_GITHUB_CLIENT_ID ?? GITHUB_CLIENT_ID;
|
|
37
|
+
/** The repository; ASTRALIS_ISSUES_REPO overrides it, for testing against another repository. */
|
|
38
|
+
export const issuesRepo = () => process.env.ASTRALIS_ISSUES_REPO || ISSUES_REPO;
|
|
39
|
+
|
|
40
|
+
/** An error a person can act on, with a code a program can branch on. */
|
|
41
|
+
export class GitHubError extends Error {
|
|
42
|
+
constructor(code, message) {
|
|
43
|
+
super(message);
|
|
44
|
+
this.code = code;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/* ---- the saved sign-in ------------------------------------------------------------- */
|
|
49
|
+
|
|
50
|
+
/** The user's config directory for Astralis: %APPDATA%\astralis on Windows, else $XDG_CONFIG_HOME or ~/.config. */
|
|
51
|
+
export function configDir(env = process.env) {
|
|
52
|
+
if (env.ASTRALIS_CONFIG_DIR) return env.ASTRALIS_CONFIG_DIR;
|
|
53
|
+
if (process.platform === "win32" && env.APPDATA) return join(env.APPDATA, "astralis");
|
|
54
|
+
return join(env.XDG_CONFIG_HOME || join(homedir(), ".config"), "astralis");
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** The saved GitHub sign-in: { token, login, savedAt }, or null. */
|
|
58
|
+
export function tokenStore(dir = configDir()) {
|
|
59
|
+
const file = join(dir, "github.json");
|
|
60
|
+
return {
|
|
61
|
+
file,
|
|
62
|
+
read() {
|
|
63
|
+
try {
|
|
64
|
+
const saved = JSON.parse(readFileSync(file, "utf8"));
|
|
65
|
+
return typeof saved?.token === "string" && typeof saved?.login === "string" ? saved : null;
|
|
66
|
+
} catch {
|
|
67
|
+
return null;
|
|
68
|
+
}
|
|
69
|
+
},
|
|
70
|
+
write({ token, login }) {
|
|
71
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
72
|
+
writeFileSync(file, `${JSON.stringify({ token, login, savedAt: new Date().toISOString() }, null, 2)}\n`, { mode: 0o600 });
|
|
73
|
+
// writeFileSync keeps an existing file's mode; make sure it is the user's alone.
|
|
74
|
+
try {
|
|
75
|
+
chmodSync(file, 0o600);
|
|
76
|
+
} catch {
|
|
77
|
+
// Windows: the file sits in the user's own profile, which is theirs alone
|
|
78
|
+
}
|
|
79
|
+
},
|
|
80
|
+
clear() {
|
|
81
|
+
rmSync(file, { force: true });
|
|
82
|
+
},
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/* ---- talking to GitHub ------------------------------------------------------------- */
|
|
87
|
+
|
|
88
|
+
async function call(fetchImpl, url, { method = "GET", token, body, form } = {}) {
|
|
89
|
+
const isApi = url.startsWith(api());
|
|
90
|
+
let response;
|
|
91
|
+
try {
|
|
92
|
+
response = await fetchImpl(url, {
|
|
93
|
+
method,
|
|
94
|
+
headers: {
|
|
95
|
+
accept: isApi ? "application/vnd.github+json" : "application/json",
|
|
96
|
+
"user-agent": "astralis-cli",
|
|
97
|
+
...(isApi ? { "x-github-api-version": "2022-11-28" } : {}),
|
|
98
|
+
...(token ? { authorization: `Bearer ${token}` } : {}),
|
|
99
|
+
...(body ? { "content-type": "application/json" } : {}),
|
|
100
|
+
...(form ? { "content-type": "application/x-www-form-urlencoded" } : {}),
|
|
101
|
+
},
|
|
102
|
+
body: body ? JSON.stringify(body) : form ? new URLSearchParams(form).toString() : undefined,
|
|
103
|
+
signal: AbortSignal.timeout(15000),
|
|
104
|
+
});
|
|
105
|
+
} catch (error) {
|
|
106
|
+
throw new GitHubError("network", `Could not reach GitHub (${error.name === "TimeoutError" ? "timed out" : error.message}).`);
|
|
107
|
+
}
|
|
108
|
+
let data = null;
|
|
109
|
+
try {
|
|
110
|
+
data = await response.json();
|
|
111
|
+
} catch {
|
|
112
|
+
// no JSON body
|
|
113
|
+
}
|
|
114
|
+
if (response.status === 401) throw new GitHubError("signed-out", "GitHub no longer accepts this sign-in. Sign in again.");
|
|
115
|
+
if (!response.ok) {
|
|
116
|
+
const reason = data?.message ?? `${response.status} ${response.statusText}`.trim();
|
|
117
|
+
throw new GitHubError(response.status === 403 || response.status === 404 ? "forbidden" : "github", `GitHub refused the request: ${reason}.`);
|
|
118
|
+
}
|
|
119
|
+
return data;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Start a sign-in. Resolves to the code the user enters, the page they enter
|
|
124
|
+
* it on, and the device code to poll with (which stays in this process).
|
|
125
|
+
*/
|
|
126
|
+
export async function startSignIn({ fetchImpl = globalThis.fetch } = {}) {
|
|
127
|
+
const id = clientId();
|
|
128
|
+
if (!id) throw new GitHubError("not-configured", "GitHub sign-in is not set up in this version of astralis-cli.");
|
|
129
|
+
const data = await call(fetchImpl, `${web()}/login/device/code`, { method: "POST", form: { client_id: id } });
|
|
130
|
+
if (data?.error) throw new GitHubError("github", `GitHub could not start the sign-in: ${data.error_description ?? data.error}.`);
|
|
131
|
+
return {
|
|
132
|
+
deviceCode: data.device_code,
|
|
133
|
+
userCode: data.user_code,
|
|
134
|
+
verificationUri: data.verification_uri,
|
|
135
|
+
expiresAt: Date.now() + data.expires_in * 1000,
|
|
136
|
+
interval: data.interval ?? 5,
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
const wait = (ms) => new Promise((done) => setTimeout(done, ms));
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* Wait for the user to enter the code. Resolves to { token, login } once they
|
|
144
|
+
* have; rejects with code "expired" or "denied" when they will not.
|
|
145
|
+
*/
|
|
146
|
+
export async function finishSignIn(flow, { fetchImpl = globalThis.fetch, sleep = wait, signal } = {}) {
|
|
147
|
+
let interval = flow.interval;
|
|
148
|
+
while (Date.now() < flow.expiresAt) {
|
|
149
|
+
await sleep(interval * 1000);
|
|
150
|
+
if (signal?.aborted) throw new GitHubError("cancelled", "The sign-in was cancelled.");
|
|
151
|
+
const data = await call(fetchImpl, `${web()}/login/oauth/access_token`, {
|
|
152
|
+
method: "POST",
|
|
153
|
+
form: { client_id: clientId(), device_code: flow.deviceCode, grant_type: "urn:ietf:params:oauth:grant-type:device_code" },
|
|
154
|
+
});
|
|
155
|
+
if (data?.access_token) {
|
|
156
|
+
const user = await call(fetchImpl, `${api()}/user`, { token: data.access_token });
|
|
157
|
+
return { token: data.access_token, login: user.login };
|
|
158
|
+
}
|
|
159
|
+
switch (data?.error) {
|
|
160
|
+
case "authorization_pending":
|
|
161
|
+
continue;
|
|
162
|
+
case "slow_down":
|
|
163
|
+
interval = data.interval ?? interval + 5;
|
|
164
|
+
continue;
|
|
165
|
+
case "expired_token":
|
|
166
|
+
throw new GitHubError("expired", "The code expired before it was entered. Start the sign-in again.");
|
|
167
|
+
case "access_denied":
|
|
168
|
+
throw new GitHubError("denied", "The sign-in was declined on GitHub.");
|
|
169
|
+
default:
|
|
170
|
+
throw new GitHubError("github", `GitHub ended the sign-in: ${data?.error_description ?? data?.error ?? "no reason given"}.`);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
throw new GitHubError("expired", "The code expired before it was entered. Start the sign-in again.");
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** Open an issue on the Astralis repository as the signed-in user. Resolves to { number, url }. */
|
|
177
|
+
export async function createIssue(token, { title, body }, { fetchImpl = globalThis.fetch } = {}) {
|
|
178
|
+
const issue = await call(fetchImpl, `${api()}/repos/${issuesRepo()}/issues`, { method: "POST", token, body: { title, body } });
|
|
179
|
+
return { number: issue.number, url: issue.html_url };
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** Add a report to an existing issue, as a comment. Resolves to { number, url }. */
|
|
183
|
+
export async function commentOnIssue(token, number, body, { fetchImpl = globalThis.fetch } = {}) {
|
|
184
|
+
const comment = await call(fetchImpl, `${api()}/repos/${issuesRepo()}/issues/${number}/comments`, { method: "POST", token, body: { body } });
|
|
185
|
+
return { number, url: comment.html_url };
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
const summary = (issue) => ({
|
|
189
|
+
number: issue.number,
|
|
190
|
+
title: issue.title,
|
|
191
|
+
state: issue.state,
|
|
192
|
+
stateReason: issue.state_reason ?? null,
|
|
193
|
+
url: issue.html_url,
|
|
194
|
+
comments: issue.comments,
|
|
195
|
+
labels: (issue.labels ?? []).map((label) => (typeof label === "string" ? label : label.name)),
|
|
196
|
+
createdAt: issue.created_at,
|
|
197
|
+
updatedAt: issue.updated_at,
|
|
198
|
+
});
|
|
199
|
+
|
|
200
|
+
/** The issues `login` opened on the Astralis repository, most recently updated first. */
|
|
201
|
+
export async function listIssues(token, login, { fetchImpl = globalThis.fetch } = {}) {
|
|
202
|
+
const query = new URLSearchParams({ creator: login, state: "all", sort: "updated", per_page: "50" });
|
|
203
|
+
const list = await call(fetchImpl, `${api()}/repos/${issuesRepo()}/issues?${query}`, { token });
|
|
204
|
+
return (list ?? []).filter((issue) => !issue.pull_request).map(summary);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/* ---- duplicates -------------------------------------------------------------------- */
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* The keys a report is matched on, written into every issue it opens so
|
|
211
|
+
* GitHub's search can find them again. `fingerprint` is the same problem: the
|
|
212
|
+
* same component, the same rule codes in its findings, and the same minor
|
|
213
|
+
* version of astralis-ui. `component` is the same component, whatever else.
|
|
214
|
+
* Each is one word, so a search matches it exactly.
|
|
215
|
+
*/
|
|
216
|
+
export function matchKeys(snapshot) {
|
|
217
|
+
const component = snapshot.tree?.[0]?.component ?? null;
|
|
218
|
+
if (!component) return { fingerprint: null, component: null };
|
|
219
|
+
const codes = [...new Set((snapshot.findings ?? []).map((f) => f.code))].sort();
|
|
220
|
+
const minor = (snapshot.library?.version ?? "").split(".").slice(0, 2).join(".");
|
|
221
|
+
const hash = createHash("sha256").update(JSON.stringify([component, codes, minor])).digest("hex").slice(0, 12);
|
|
222
|
+
return { fingerprint: `afp${hash}`, component: `acmp${component.replace(/[^A-Za-z0-9]/g, "").toLowerCase()}` };
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
async function search(token, q, fetchImpl) {
|
|
226
|
+
const query = new URLSearchParams({ q: `repo:${issuesRepo()} is:issue ${q}`, sort: "updated", per_page: "10" });
|
|
227
|
+
const found = await call(fetchImpl, `${api()}/search/issues?${query}`, { token });
|
|
228
|
+
return (found?.items ?? []).filter((issue) => !issue.pull_request).map(summary);
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* Issues that may already report this problem. `duplicates`: the same
|
|
233
|
+
* fingerprint, open first. `related`: other open issues about the same
|
|
234
|
+
* component, at most three.
|
|
235
|
+
*/
|
|
236
|
+
export async function findSimilar(token, snapshot, { fetchImpl = globalThis.fetch } = {}) {
|
|
237
|
+
const keys = matchKeys(snapshot);
|
|
238
|
+
if (!keys.fingerprint) return { duplicates: [], related: [] };
|
|
239
|
+
const [duplicates, sameComponent] = await Promise.all([
|
|
240
|
+
search(token, keys.fingerprint, fetchImpl),
|
|
241
|
+
search(token, `is:open ${keys.component}`, fetchImpl),
|
|
242
|
+
]);
|
|
243
|
+
duplicates.sort((a, b) => (a.state === b.state ? 0 : a.state === "open" ? -1 : 1));
|
|
244
|
+
const seen = new Set(duplicates.map((issue) => issue.number));
|
|
245
|
+
return { duplicates, related: sameComponent.filter((issue) => !seen.has(issue.number)).slice(0, 3) };
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/* ---- a snapshot as an issue --------------------------------------------------------- */
|
|
249
|
+
|
|
250
|
+
const fence = (lang, text) => {
|
|
251
|
+
const ticks = "`".repeat(Math.max(3, ...[...text.matchAll(/`+/g)].map((m) => m[0].length + 1)));
|
|
252
|
+
return `${ticks}${lang}\n${text}\n${ticks}`;
|
|
253
|
+
};
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* The issue a snapshot becomes: the reporter's words first, then where it
|
|
257
|
+
* happened, the validator's findings, a reproduction, and the snapshot itself.
|
|
258
|
+
* A screenshot is never in the body (GitHub's API cannot attach images).
|
|
259
|
+
*/
|
|
260
|
+
export function issueFromSnapshot(snapshot) {
|
|
261
|
+
return composeIssue(snapshot, {
|
|
262
|
+
fits: (body) => body.length <= MAX_BODY,
|
|
263
|
+
tooLarge: "_The snapshot was too large to include in full._",
|
|
264
|
+
});
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/**
|
|
268
|
+
* GitHub's own new-issue form for a snapshot, pre-filled: the way to report
|
|
269
|
+
* without signing in to the app, since the reporter submits it on github.com
|
|
270
|
+
* as themselves. A link holds about 8 kB, so the snapshot's JSON is the first
|
|
271
|
+
* thing left out, then the body is cut; the report's words always come first.
|
|
272
|
+
*/
|
|
273
|
+
export function newIssueUrl(snapshot) {
|
|
274
|
+
const base = `https://github.com/${issuesRepo()}/issues/new`;
|
|
275
|
+
const url = (title, body) => `${base}?${new URLSearchParams({ title, body })}`;
|
|
276
|
+
const { title, body } = composeIssue(snapshot, {
|
|
277
|
+
fits: (text) => url(snapshot.description?.title ?? "", text).length <= MAX_URL,
|
|
278
|
+
tooLarge: "_The full snapshot does not fit in a link: attach the file from Download, or send from the DevTools signed in._",
|
|
279
|
+
});
|
|
280
|
+
return url(title, body);
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
function composeIssue(snapshot, { fits, tooLarge }) {
|
|
284
|
+
const d = snapshot.description ?? {};
|
|
285
|
+
const lib = snapshot.library ?? {};
|
|
286
|
+
const env = snapshot.environment ?? {};
|
|
287
|
+
const where = [
|
|
288
|
+
`astralis-ui ${lib.version ?? "?"} (spec ${lib.specVersion ?? "?"})`,
|
|
289
|
+
env.framework?.name ? `${env.framework.name === "next" ? "Next.js" : env.framework.name === "vite" ? "Vite" : env.framework.name} ${env.framework.version ?? ""}`.trim() : null,
|
|
290
|
+
env.react ? `React ${env.react}` : null,
|
|
291
|
+
env.browser,
|
|
292
|
+
env.viewport ? `${env.viewport.width}×${env.viewport.height}` : null,
|
|
293
|
+
env.colorMode ? `${env.colorMode} mode` : null,
|
|
294
|
+
].filter(Boolean);
|
|
295
|
+
const top = snapshot.tree?.[0]?.component;
|
|
296
|
+
const how = snapshot.source === "cli" ? "`astralis report`" : "the Astralis DevTools";
|
|
297
|
+
|
|
298
|
+
const parts = [];
|
|
299
|
+
if (d.happened) parts.push("### What happened", d.happened);
|
|
300
|
+
if (d.expected) parts.push("### What I expected", d.expected);
|
|
301
|
+
parts.push(
|
|
302
|
+
"### Where",
|
|
303
|
+
[`- ${where.join(" · ")}`, snapshot.route ? `- Page: \`${snapshot.route}\`` : null, top ? `- Component: \`${top}\`` : null].filter(Boolean).join("\n"),
|
|
304
|
+
);
|
|
305
|
+
if (snapshot.findings?.length) {
|
|
306
|
+
parts.push(
|
|
307
|
+
"### Validator findings",
|
|
308
|
+
snapshot.findings
|
|
309
|
+
.slice(0, LIMITS.findings)
|
|
310
|
+
.map((f) => `- \`${f.code}\` ${f.file}:${f.line}:${f.column}: ${f.message}`)
|
|
311
|
+
.join("\n"),
|
|
312
|
+
);
|
|
313
|
+
}
|
|
314
|
+
if (snapshot.console?.length) parts.push("### Console errors", fence("text", snapshot.console.join("\n")));
|
|
315
|
+
parts.push("### Reproduction", fence("tsx", toRepro(snapshot)));
|
|
316
|
+
|
|
317
|
+
const keys = matchKeys(snapshot);
|
|
318
|
+
const footer = `<sub>Reported with ${how}.${keys.fingerprint ? ` Match keys: ${keys.fingerprint} ${keys.component}` : ""}</sub>`;
|
|
319
|
+
const { screenshot: _shot, ...rest } = snapshot;
|
|
320
|
+
const json = `<details>\n<summary>Issue snapshot (${snapshot.format})</summary>\n\n${fence("json", JSON.stringify(rest, null, 2))}\n\n</details>`;
|
|
321
|
+
let body = [...parts, json, footer].join("\n\n");
|
|
322
|
+
if (!fits(body)) body = [...parts, tooLarge, footer].join("\n\n");
|
|
323
|
+
if (!fits(body)) {
|
|
324
|
+
// Cut the words, keeping the note and the footer, with its match keys, whole.
|
|
325
|
+
const whole = parts.join("\n\n");
|
|
326
|
+
let keep = whole.length;
|
|
327
|
+
do {
|
|
328
|
+
keep = Math.floor(keep * 0.85);
|
|
329
|
+
body = `${whole.slice(0, keep)}…\n\n${tooLarge}\n\n${footer}`;
|
|
330
|
+
} while (!fits(body) && keep > 100);
|
|
331
|
+
}
|
|
332
|
+
return { title: (d.title ?? "").trim().slice(0, LIMITS.title), body };
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/** A report added to an existing issue: the same content, marked as another report. */
|
|
336
|
+
export function commentFromSnapshot(snapshot) {
|
|
337
|
+
const { title, body } = issueFromSnapshot(snapshot);
|
|
338
|
+
return `**Another report of this problem:** ${title}\n\n${body}`;
|
|
339
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { dirname, join } from "node:path";
|
|
3
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
4
|
+
import { findInstalledLibrary } from "./spec-resolve.mjs";
|
|
5
|
+
|
|
6
|
+
const THEME_EXPORTS = ["./serialize", "./contrast", "./styles.css"];
|
|
7
|
+
|
|
8
|
+
function exportTarget(pkg, subpath) {
|
|
9
|
+
const entry = pkg.exports?.[subpath];
|
|
10
|
+
return typeof entry === "string" ? entry : (entry?.import ?? entry?.default ?? null);
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* The theme maths and stylesheet `astralis theme` should use: the project's
|
|
15
|
+
* own astralis-ui when it has one new enough, so the generated file matches
|
|
16
|
+
* the version it will be loaded next to; otherwise the copy bundled with the
|
|
17
|
+
* CLI. `source` is "project" or "bundled"; `outdated` names a project copy
|
|
18
|
+
* that was passed over.
|
|
19
|
+
*/
|
|
20
|
+
export async function loadThemeLibrary(cwd) {
|
|
21
|
+
let outdated = null;
|
|
22
|
+
const pkgPath = findInstalledLibrary(cwd);
|
|
23
|
+
if (pkgPath) {
|
|
24
|
+
const pkg = JSON.parse(readFileSync(pkgPath, "utf8"));
|
|
25
|
+
const root = dirname(pkgPath);
|
|
26
|
+
const [serializeFile, contrastFile, stylesFile] = THEME_EXPORTS.map((subpath) => exportTarget(pkg, subpath));
|
|
27
|
+
if (serializeFile && contrastFile && stylesFile) {
|
|
28
|
+
const [serialize, contrast] = await Promise.all(
|
|
29
|
+
[serializeFile, contrastFile].map((file) => import(pathToFileURL(join(root, file)).href)),
|
|
30
|
+
);
|
|
31
|
+
return { serialize, contrast, stylesPath: join(root, stylesFile), version: pkg.version, source: "project" };
|
|
32
|
+
}
|
|
33
|
+
outdated = pkg.version;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const [serialize, contrast] = await Promise.all([import("astralis-ui/serialize"), import("astralis-ui/contrast")]);
|
|
37
|
+
const stylesPath = fileURLToPath(import.meta.resolve("astralis-ui/styles.css"));
|
|
38
|
+
const version = JSON.parse(readFileSync(join(dirname(stylesPath), "..", "package.json"), "utf8")).version;
|
|
39
|
+
return { serialize, contrast, stylesPath, version, source: "bundled", outdated };
|
|
40
|
+
}
|
package/src/lib/menu.mjs
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/* The arrow-key menu's logic, apart from any terminal: what a key does to the
|
|
2
|
+
choice, and the lines that show it. prompt-child.mjs drives it in a
|
|
3
|
+
throwaway process (the CLI itself never reads stdin), and the tests drive
|
|
4
|
+
it with plain objects. Also the one-line banner. */
|
|
5
|
+
|
|
6
|
+
const ESC = "\u001b";
|
|
7
|
+
const sgr = (open, close) => (color) => (text) => (color ? `${ESC}[${open}m${text}${ESC}[${close}m` : text);
|
|
8
|
+
const brand = sgr("38;2;234;179;8", "39"); // the brand yellow, #eab308
|
|
9
|
+
|
|
10
|
+
const paint = (color) => ({
|
|
11
|
+
brand: brand(color),
|
|
12
|
+
bold: sgr("1", "22")(color),
|
|
13
|
+
dim: sgr("2", "22")(color),
|
|
14
|
+
green: sgr("32", "39")(color),
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* A key, as Node's keypress events name it, applied to the menu.
|
|
19
|
+
* Returns the next state; `done` is the chosen index, or "cancel".
|
|
20
|
+
*/
|
|
21
|
+
export function press(state, key = {}) {
|
|
22
|
+
const count = state.options.length;
|
|
23
|
+
if (key.ctrl && key.name === "c") return { ...state, done: "cancel" };
|
|
24
|
+
if (key.name === "escape") return { ...state, done: "cancel" };
|
|
25
|
+
if (key.name === "return" || key.name === "enter") return { ...state, done: state.index };
|
|
26
|
+
if (key.name === "up" || key.name === "k") return { ...state, index: (state.index - 1 + count) % count };
|
|
27
|
+
if (key.name === "down" || key.name === "j" || key.name === "tab") return { ...state, index: (state.index + 1) % count };
|
|
28
|
+
const digit = Number(key.sequence);
|
|
29
|
+
if (Number.isInteger(digit) && digit >= 1 && digit <= count) return { ...state, index: digit - 1, done: digit - 1 };
|
|
30
|
+
return state;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** The menu while it is open: the question, then each option, the current one marked. */
|
|
34
|
+
export function drawOpen(state, { color = true } = {}) {
|
|
35
|
+
const c = paint(color);
|
|
36
|
+
const lines = [`${c.brand("◆")} ${c.bold(state.question)}`];
|
|
37
|
+
state.options.forEach((option, i) => {
|
|
38
|
+
const current = i === state.index;
|
|
39
|
+
const mark = current ? c.brand("●") : c.dim("○");
|
|
40
|
+
const label = current ? option.label : c.dim(option.label);
|
|
41
|
+
const hint = option.hint && current ? ` ${c.dim(option.hint)}` : "";
|
|
42
|
+
lines.push(`${c.dim("│")} ${mark} ${label}${hint}`);
|
|
43
|
+
});
|
|
44
|
+
lines.push(`${c.dim("└")} ${c.dim("↑/↓ to move · enter to choose")}`);
|
|
45
|
+
return lines;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** The menu once answered: one line, the question and the answer. */
|
|
49
|
+
export function drawDone(state, { color = true } = {}) {
|
|
50
|
+
const c = paint(color);
|
|
51
|
+
if (state.done === "cancel") return [`${c.dim("◇")} ${c.dim(state.question)} ${c.dim("· cancelled")}`];
|
|
52
|
+
return [`${c.green("◇")} ${state.question} ${c.dim("›")} ${state.options[state.done].label}`];
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** The banner: one line, the name and version, then what is about to happen. */
|
|
56
|
+
export function banner({ version, subtitle, color = true }) {
|
|
57
|
+
const c = paint(color);
|
|
58
|
+
return `\n${c.brand("◆")} ${c.bold("Astralis CLI")} ${c.dim(`v${version}`)} ${c.dim("·")} ${subtitle}\n`;
|
|
59
|
+
}
|
package/src/lib/prompt-child.mjs
CHANGED
|
@@ -1,51 +1,97 @@
|
|
|
1
1
|
/*
|
|
2
|
-
* Reads exactly one line of input, writes it to stdout, exits.
|
|
2
|
+
* Reads exactly one line of input, writes it to stdout, exits. Exit code 3
|
|
3
|
+
* means stdin was already at EOF: nobody is there to answer.
|
|
3
4
|
*
|
|
4
|
-
*
|
|
5
|
+
* Why a CHILD process: the CLI itself must never read stdin. On Windows libuv
|
|
6
|
+
* services a TTY on a thread blocked in ReadConsoleInputW that cannot be
|
|
7
|
+
* stopped once started (not by readline.close(), pause(), or dropping
|
|
8
|
+
* listeners), so a process that read stdin once keeps eating console input for
|
|
9
|
+
* the rest of its life. `astralis create` then handed over to create-vite,
|
|
10
|
+
* whose arrow-key menu drew and never received a keystroke. Here the read
|
|
11
|
+
* thread dies when this process exits.
|
|
5
12
|
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
* listeners. A process that has read stdin even once keeps consuming
|
|
11
|
-
* console input records for the rest of its life, starving any interactive
|
|
12
|
-
* child it later spawns: `astralis create` asked which framework, then
|
|
13
|
-
* handed to create-vite, whose arrow-key menu drew perfectly and never saw
|
|
14
|
-
* a keystroke. Here the read thread dies when this process exits.
|
|
13
|
+
* Why BYTE BY BYTE: readline buffers ahead, which swallows the rest of a piped
|
|
14
|
+
* input and leaves the next prompt's child at EOF. Stopping at the first
|
|
15
|
+
* newline leaves the rest of the pipe for the next prompt. Line editing still
|
|
16
|
+
* works: the terminal driver releases only the finished line.
|
|
15
17
|
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
* is piped — the next prompt's child would then see EOF. Stopping at the
|
|
19
|
-
* first newline leaves the rest of the pipe for the next prompt.
|
|
18
|
+
* The prompt goes to stderr (inherited, so the user sees it); the answer goes
|
|
19
|
+
* to stdout, which the parent pipes.
|
|
20
20
|
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
* answer goes to stdout, which the parent pipes.
|
|
21
|
+
* MENU MODE (`--menu <json>`): an arrow-key menu, drawn on stderr, with the
|
|
22
|
+
* chosen index on stdout. Exit 3: not a terminal, so the parent falls back to
|
|
23
|
+
* a numbered prompt. Exit 130: cancelled (Ctrl+C or Esc). Raw mode and the
|
|
24
|
+
* console read thread end with this process, as above.
|
|
26
25
|
*/
|
|
27
26
|
import { readSync } from "node:fs";
|
|
27
|
+
import { emitKeypressEvents } from "node:readline";
|
|
28
|
+
import { drawDone, drawOpen, press } from "./menu.mjs";
|
|
28
29
|
|
|
29
|
-
const
|
|
30
|
-
if (prompt) process.stderr.write(prompt);
|
|
30
|
+
const ESC = "\u001b";
|
|
31
31
|
|
|
32
|
-
|
|
33
|
-
|
|
32
|
+
if (process.argv[2] === "--menu") menu(JSON.parse(process.argv[3]));
|
|
33
|
+
else line(process.argv[2] ?? "");
|
|
34
34
|
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
if (
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
35
|
+
function menu({ question, options, index = 0, color = true }) {
|
|
36
|
+
if (!process.stdin.isTTY || !process.stderr.isTTY) process.exit(3);
|
|
37
|
+
const out = process.stderr;
|
|
38
|
+
let state = { question, options, index, done: null };
|
|
39
|
+
let drawn = 0;
|
|
40
|
+
const draw = (lines) => {
|
|
41
|
+
// Back to the menu's first line and clear what was drawn, then draw again.
|
|
42
|
+
if (drawn) out.write(`${ESC}[${drawn}A${ESC}[0J`);
|
|
43
|
+
out.write(lines.join("\n") + "\n");
|
|
44
|
+
drawn = lines.length;
|
|
45
|
+
};
|
|
46
|
+
out.write(`${ESC}[?25l`); // hide the cursor while the menu is open
|
|
47
|
+
process.on("exit", () => out.write(`${ESC}[?25h`));
|
|
48
|
+
draw(drawOpen(state, { color }));
|
|
49
|
+
emitKeypressEvents(process.stdin);
|
|
50
|
+
process.stdin.setRawMode(true);
|
|
51
|
+
process.stdin.on("keypress", (_text, key) => {
|
|
52
|
+
state = press(state, key ?? {});
|
|
53
|
+
if (state.done === null) return draw(drawOpen(state, { color }));
|
|
54
|
+
draw(drawDone(state, { color }));
|
|
55
|
+
process.stdin.setRawMode(false);
|
|
56
|
+
if (state.done === "cancel") process.exit(130);
|
|
57
|
+
process.stdout.write(String(state.done));
|
|
58
|
+
process.exit(0);
|
|
59
|
+
});
|
|
49
60
|
}
|
|
50
61
|
|
|
51
|
-
|
|
62
|
+
function line(prompt) {
|
|
63
|
+
if (prompt) process.stderr.write(prompt);
|
|
64
|
+
|
|
65
|
+
const byte = Buffer.alloc(1);
|
|
66
|
+
const bytes = [];
|
|
67
|
+
const pause = new Int32Array(new SharedArrayBuffer(4));
|
|
68
|
+
let atEof = false;
|
|
69
|
+
|
|
70
|
+
while (true) {
|
|
71
|
+
let read;
|
|
72
|
+
try {
|
|
73
|
+
read = readSync(0, byte, 0, 1, null);
|
|
74
|
+
} catch (error) {
|
|
75
|
+
// Non-blocking stdin yields EAGAIN until data arrives: wait rather than spin.
|
|
76
|
+
if (error.code === "EAGAIN") {
|
|
77
|
+
Atomics.wait(pause, 0, 0, 20);
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
if (error.code === "EOF") {
|
|
81
|
+
atEof = true;
|
|
82
|
+
break;
|
|
83
|
+
}
|
|
84
|
+
throw error;
|
|
85
|
+
}
|
|
86
|
+
if (read === 0) {
|
|
87
|
+
atEof = true;
|
|
88
|
+
break;
|
|
89
|
+
}
|
|
90
|
+
if (byte[0] === 0x0a) break; // \n: the line is done
|
|
91
|
+
if (byte[0] === 0x0d) continue; // \r from CRLF
|
|
92
|
+
bytes.push(byte[0]);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
if (atEof && bytes.length === 0) process.exit(3);
|
|
96
|
+
process.stdout.write(Buffer.from(bytes).toString("utf8"));
|
|
97
|
+
}
|
package/src/lib/registry.mjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { isAbsolute, resolve, sep } from "node:path";
|
|
1
2
|
import { fail } from "./ui.mjs";
|
|
2
3
|
|
|
3
4
|
/**
|
|
@@ -10,17 +11,30 @@ import { fail } from "./ui.mjs";
|
|
|
10
11
|
* the registry gets tested against a local docs server before it ships.
|
|
11
12
|
*/
|
|
12
13
|
|
|
13
|
-
const DEFAULT_REGISTRY = "https://astralis-
|
|
14
|
+
const DEFAULT_REGISTRY = "https://astralis-ui.com/r";
|
|
14
15
|
|
|
15
16
|
export function registryBase(flag) {
|
|
16
|
-
const base = flag ?? process.env.ASTRALIS_REGISTRY
|
|
17
|
+
const base = flag ?? (process.env.ASTRALIS_REGISTRY || DEFAULT_REGISTRY);
|
|
17
18
|
return base.replace(/\/+$/, "");
|
|
18
19
|
}
|
|
19
20
|
|
|
21
|
+
export const REGISTRY_TIMEOUT_MS = 10_000;
|
|
22
|
+
|
|
23
|
+
/** fetch() that gives up after `ms`, body read included, with a readable error. */
|
|
24
|
+
export async function fetchWithTimeout(url, ms = REGISTRY_TIMEOUT_MS) {
|
|
25
|
+
const signal = AbortSignal.timeout(ms);
|
|
26
|
+
try {
|
|
27
|
+
return { response: await fetch(url, { signal }), signal };
|
|
28
|
+
} catch (error) {
|
|
29
|
+
throw signal.aborted ? new Error(`timed out after ${ms / 1000}s`) : error;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
20
33
|
async function getJson(url) {
|
|
21
34
|
let response;
|
|
35
|
+
let signal;
|
|
22
36
|
try {
|
|
23
|
-
response = await
|
|
37
|
+
({ response, signal } = await fetchWithTimeout(url));
|
|
24
38
|
} catch (error) {
|
|
25
39
|
fail(`Could not reach the block registry at ${url}\n ${error.message}`);
|
|
26
40
|
}
|
|
@@ -39,7 +53,7 @@ async function getJson(url) {
|
|
|
39
53
|
try {
|
|
40
54
|
return await response.json();
|
|
41
55
|
} catch {
|
|
42
|
-
fail(`Registry returned invalid JSON for ${url}`);
|
|
56
|
+
fail(signal.aborted ? `Registry timed out sending ${url}` : `Registry returned invalid JSON for ${url}`);
|
|
43
57
|
}
|
|
44
58
|
}
|
|
45
59
|
|
|
@@ -50,6 +64,25 @@ export async function fetchIndex(base) {
|
|
|
50
64
|
return data;
|
|
51
65
|
}
|
|
52
66
|
|
|
67
|
+
/** Block ids are what the registry builder emits: lowercase words and dashes. */
|
|
68
|
+
export function isBlockId(id) {
|
|
69
|
+
return /^[a-z0-9]+(-[a-z0-9]+)*$/.test(id);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Where a registry file may be written: inside `target`, or nowhere. The
|
|
74
|
+
* registry is remote input, so a path that is absolute or climbs out with
|
|
75
|
+
* `..` is refused rather than normalised. Returns the absolute path, or null.
|
|
76
|
+
*/
|
|
77
|
+
export function resolveBlockFile(target, filePath) {
|
|
78
|
+
if (typeof filePath !== "string" || filePath === "" || filePath.includes("\0")) return null;
|
|
79
|
+
if (isAbsolute(filePath) || /^[\\/]|^[a-z]:/i.test(filePath)) return null;
|
|
80
|
+
if (filePath.split(/[\\/]/).some((segment) => segment === ".." || segment === "")) return null;
|
|
81
|
+
const root = resolve(target);
|
|
82
|
+
const full = resolve(root, filePath);
|
|
83
|
+
return full.startsWith(root + sep) ? full : null;
|
|
84
|
+
}
|
|
85
|
+
|
|
53
86
|
/** One block, with the full text of its files. Null when the id is unknown. */
|
|
54
87
|
export function fetchBlock(base, id) {
|
|
55
88
|
return getJson(`${base}/${id}.json`);
|