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,134 @@
1
+ import { parse } from "@babel/parser";
2
+ import { clientTier, keptText, narrowProps, redactedText } from "./snapshot.mjs";
3
+
4
+ /* The component tree `astralis report` records from source files: the
5
+ astralis-ui elements in their JSX, with literal props only. The DevTools
6
+ build the same tree from the rendered page (astralis-devtools). */
7
+
8
+ const PARSE_OPTIONS = { sourceType: "module", plugins: ["typescript", "jsx"] };
9
+
10
+ /** local name -> astralis-ui export, for value imports from astralis-ui. */
11
+ function importsOf(ast) {
12
+ const imported = new Map();
13
+ for (const node of ast.program.body) {
14
+ if (node.type !== "ImportDeclaration" || node.source.value !== "astralis-ui" || node.importKind === "type") continue;
15
+ for (const s of node.specifiers) {
16
+ if (s.type !== "ImportSpecifier" || s.importKind === "type") continue;
17
+ imported.set(s.local.name, s.imported.type === "Identifier" ? s.imported.name : s.imported.value);
18
+ }
19
+ }
20
+ return imported;
21
+ }
22
+
23
+ /** The public name of a JSX element if it is an astralis-ui component, else null. */
24
+ function publicName(nameNode, imported, spec) {
25
+ if (nameNode.type === "JSXIdentifier") {
26
+ const exported = imported.get(nameNode.name);
27
+ if (!exported || !spec.components?.[exported]) return null;
28
+ // A flat part export (CardBody) is written the way the page names it: Card.Body.
29
+ const partOf = spec.components[exported].partOf;
30
+ return partOf ? `${partOf}.${exported.slice(partOf.length)}` : exported;
31
+ }
32
+ if (nameNode.type === "JSXMemberExpression" && nameNode.object.type === "JSXIdentifier") {
33
+ const owner = imported.get(nameNode.object.name);
34
+ if (!owner || !spec.components?.[owner]) return null;
35
+ const name = `${owner}.${nameNode.property.name}`;
36
+ return spec.components[owner].parts?.includes(nameNode.property.name) ? name : null;
37
+ }
38
+ return null;
39
+ }
40
+
41
+ /** A literal attribute value, or undefined when it is computed at run time. */
42
+ function literal(node) {
43
+ if (!node) return true; // <Button disabled />
44
+ if (node.type === "JSXExpressionContainer") return literal(node.expression);
45
+ if (node.type === "StringLiteral") return node.value;
46
+ if (node.type === "NumericLiteral" || node.type === "BooleanLiteral") return node.value;
47
+ if (node.type === "TemplateLiteral" && node.expressions.length === 0) return node.quasis[0].value.cooked;
48
+ if (node.type === "UnaryExpression" && node.operator === "-" && node.argument.type === "NumericLiteral") return -node.argument.value;
49
+ if (node.type === "ObjectExpression") {
50
+ const out = {};
51
+ for (const p of node.properties) {
52
+ if (p.type !== "ObjectProperty" || p.computed) return undefined;
53
+ const key = p.key.type === "Identifier" ? p.key.name : p.key.value;
54
+ const value = literal(p.value);
55
+ if (value === undefined) return undefined;
56
+ out[key] = value;
57
+ }
58
+ return out;
59
+ }
60
+ return undefined;
61
+ }
62
+
63
+ function propsOf(opening) {
64
+ const props = {};
65
+ for (const attr of opening.attributes) {
66
+ if (attr.type !== "JSXAttribute" || attr.name.type !== "JSXIdentifier") continue;
67
+ const value = literal(attr.value);
68
+ if (value !== undefined) props[attr.name.name] = value;
69
+ }
70
+ return props;
71
+ }
72
+
73
+ function childrenOf(nodes, ctx) {
74
+ const out = [];
75
+ for (const child of nodes) {
76
+ if (child.type === "JSXText") {
77
+ const text = child.value.replace(/\s+/g, " ").trim();
78
+ if (text) out.push(ctx.includeText ? keptText(text) : redactedText(text));
79
+ } else if (child.type === "JSXExpressionContainer") {
80
+ const value = literal(child.expression);
81
+ if (typeof value === "string" && value.trim()) out.push(ctx.includeText ? keptText(value.trim()) : redactedText(value.trim()));
82
+ } else if (child.type === "JSXElement" || child.type === "JSXFragment") {
83
+ out.push(...elementNodes(child, ctx));
84
+ }
85
+ }
86
+ return out;
87
+ }
88
+
89
+ /** An element as tree nodes: itself when it is an astralis-ui component, else what it contains. */
90
+ function elementNodes(node, ctx) {
91
+ if (node.type === "JSXFragment") return childrenOf(node.children, ctx);
92
+ const name = publicName(node.openingElement.name, ctx.imported, ctx.spec);
93
+ if (!name) return childrenOf(node.children, ctx);
94
+ return [{
95
+ component: name,
96
+ props: narrowProps(ctx.spec, name, propsOf(node.openingElement)),
97
+ client: clientTier(ctx.spec, name),
98
+ children: childrenOf(node.children, ctx),
99
+ }];
100
+ }
101
+
102
+ /** Every outermost JSX element or fragment in the file, in source order. */
103
+ function outermostJsx(ast) {
104
+ const found = [];
105
+ const walk = (node) => {
106
+ if (!node || typeof node.type !== "string") return;
107
+ if (node.type === "JSXElement" || node.type === "JSXFragment") {
108
+ found.push(node);
109
+ return;
110
+ }
111
+ for (const key of Object.keys(node)) {
112
+ if (key === "loc") continue;
113
+ const value = node[key];
114
+ if (Array.isArray(value)) value.forEach(walk);
115
+ else if (value && typeof value === "object") walk(value);
116
+ }
117
+ };
118
+ walk(ast.program);
119
+ return found;
120
+ }
121
+
122
+ /**
123
+ * The astralis-ui components in one source file, outermost first. Throws a
124
+ * SyntaxError when the file does not parse. Text becomes placeholders unless
125
+ * `includeText` is set.
126
+ */
127
+ export function treeFromSource(source, spec, { includeText = false } = {}) {
128
+ const ast = parse(source, PARSE_OPTIONS);
129
+ const ctx = { spec, imported: importsOf(ast), includeText };
130
+ // Text outside every component belongs to no component; the tree starts at components.
131
+ return outermostJsx(ast)
132
+ .flatMap((node) => elementNodes(node, ctx))
133
+ .filter((node) => "component" in node);
134
+ }
@@ -0,0 +1,39 @@
1
+ import { spawnSync } from "node:child_process";
2
+
3
+ /**
4
+ * Run a program with an argument array, never a concatenated shell string.
5
+ *
6
+ * POSIX spawns it directly: no shell, so nothing is globbed or split. Windows
7
+ * has to go through cmd.exe, because npm, pnpm and yarn are .cmd shims that
8
+ * can't be spawned without it; each argument is quoted for cmd there, and the
9
+ * ones cmd can't carry safely are refused rather than mangled.
10
+ */
11
+ export function runCommand(bin, args, { platform = process.platform, ...options } = {}) {
12
+ if (platform !== "win32") return spawnSync(bin, args, { stdio: "inherit", ...options });
13
+ const line = [bin, ...args].map(quoteForCmd).join(" ");
14
+ return spawnSync(process.env.ComSpec || "cmd.exe", ["/d", "/s", "/c", `"${line}"`], {
15
+ stdio: "inherit",
16
+ windowsVerbatimArguments: true,
17
+ ...options,
18
+ });
19
+ }
20
+
21
+ /** Characters cmd.exe gives meaning to. Inside double quotes it treats them as text. */
22
+ const CMD_SPECIAL = /[\s&|<>()^,;=!]/;
23
+
24
+ export class UnsafeArgumentError extends Error {}
25
+
26
+ /**
27
+ * One argument as cmd.exe and the program's argv parser will both read it back.
28
+ * `"` and `%` can't be protected by quoting in cmd, and a newline ends the
29
+ * command, so those are refused.
30
+ */
31
+ export function quoteForCmd(arg) {
32
+ const text = String(arg);
33
+ if (/["%\r\n]/.test(text)) {
34
+ throw new UnsafeArgumentError(`can't pass ${JSON.stringify(text)} through cmd.exe safely`);
35
+ }
36
+ if (text !== "" && !CMD_SPECIAL.test(text)) return text;
37
+ // A trailing backslash would escape the closing quote in the program's argv parser.
38
+ return `"${text.replace(/(\\+)$/, "$1$1")}"`;
39
+ }
@@ -0,0 +1,65 @@
1
+ /** Issue snapshots, format astralis-snapshot/1. Pure: runs in the browser and in Node. */
2
+
3
+ export const SNAPSHOT_FORMAT: "astralis-snapshot/1";
4
+ export const MAX_SNAPSHOT_BYTES: number;
5
+ export const LIMITS: {
6
+ nodes: number;
7
+ depth: number;
8
+ findings: number;
9
+ console: number;
10
+ consoleMessage: number;
11
+ text: number;
12
+ title: number;
13
+ body: number;
14
+ };
15
+
16
+ export type ClientTier = "none" | "leaf" | "required";
17
+ export type PropValue = string | number | boolean | { [key: string]: PropValue };
18
+
19
+ export interface ComponentNode {
20
+ /** Public name, e.g. "Card" or "Card.Body". */
21
+ component: string;
22
+ /** Spec-described configuration props only. */
23
+ props: Record<string, PropValue>;
24
+ client?: ClientTier | null;
25
+ /** Components it renders through onto the same element (internal composition). */
26
+ renders?: string[];
27
+ children?: TreeNode[];
28
+ }
29
+ export type TreeNode = ComponentNode | { text: string } | { redacted: true; length: number };
30
+
31
+ export interface Snapshot {
32
+ format: "astralis-snapshot/1";
33
+ source: "devtools" | "cli";
34
+ library: { name: "astralis-ui"; version: string; specVersion: number; specSha256: string };
35
+ environment: {
36
+ framework: { name: "next" | "vite" | null; version: string | null };
37
+ react: string | null;
38
+ browser: string | null;
39
+ viewport: { width: number; height: number } | null;
40
+ colorMode: "light" | "dark" | null;
41
+ };
42
+ route: string | null;
43
+ tree: ComponentNode[];
44
+ findings?: { code: string; file: string; line: number; column: number; message: string }[];
45
+ console?: string[];
46
+ screenshot?: string;
47
+ description: { title: string; happened?: string; expected?: string };
48
+ }
49
+
50
+ export function specEntry(spec: unknown, name: string): { key: string; entry: any } | null;
51
+ export function contentOf(spec: unknown, name: string): string | null;
52
+ export function clientTier(spec: unknown, name: string): ClientTier | null;
53
+ export function describedProps(spec: unknown, name: string): Set<string> | null;
54
+ export function isConfigurationProp(key: string): boolean;
55
+ export function narrowProps(spec: unknown, name: string, props?: Record<string, unknown>): Record<string, PropValue>;
56
+ /** Props narrowed and client tiers read from the spec, for every component in a tree. */
57
+ export function narrowTree(spec: unknown, nodes: unknown): TreeNode[];
58
+ export function redactedText(text: string): { redacted: true; length: number };
59
+ export function keptText(text: string): { text: string };
60
+ export function cleanRoute(route: string | null | undefined): string | null;
61
+ export function cleanConsoleMessage(message: unknown, origin?: string): string;
62
+ /** Problems with a snapshot, or an empty list when it is valid. */
63
+ export function checkSnapshot(value: unknown): string[];
64
+ /** The snapshot's tree as a minimal repro.tsx. */
65
+ export function toRepro(snapshot: Snapshot): string;
@@ -0,0 +1,371 @@
1
+ /* ==========================================================================
2
+ Issue snapshots (format astralis-snapshot/1): the unit of evidence in the
3
+ feedback loop. Built by the DevTools from a rendered page and by
4
+ `astralis report` from source files, and checked here before anything is
5
+ sent. github.mjs turns one into a GitHub issue.
6
+
7
+ Pure JavaScript with no Node built-ins, so the same code runs in the
8
+ browser overlay, the dev-server bridge, the CLI and the platform.
9
+ ========================================================================== */
10
+
11
+ export const SNAPSHOT_FORMAT = "astralis-snapshot/1";
12
+
13
+ /** The largest snapshot the platform accepts, screenshot included. */
14
+ export const MAX_SNAPSHOT_BYTES = 256 * 1024;
15
+
16
+ export const LIMITS = {
17
+ nodes: 300,
18
+ depth: 30,
19
+ findings: 100,
20
+ console: 20,
21
+ consoleMessage: 500,
22
+ text: 200,
23
+ title: 200,
24
+ body: 4000,
25
+ };
26
+
27
+ /* ---- names and the spec -------------------------------------------------------- */
28
+
29
+ /**
30
+ * The spec entry for a public name. "Card" and "CardBody" are keys already;
31
+ * a part ("Card.Body") is found through its root's partExports. "X.Root" is
32
+ * the root itself unless the root exports a separate Root (Calendar.Root is
33
+ * CalendarRoot, not Calendar).
34
+ */
35
+ export function specEntry(spec, name) {
36
+ const components = spec?.components ?? {};
37
+ const [root, part] = name.split(".");
38
+ const found = (key) => (components[key] ? { key, entry: components[key] } : null);
39
+ if (!part) return found(root);
40
+ const exported = components[root]?.partExports?.[part];
41
+ if (exported) return found(exported);
42
+ if (part === "Root") return found(root);
43
+ return found(`${root}${part}`);
44
+ }
45
+
46
+ /**
47
+ * What a component does with its children: "text", "element", "block" or
48
+ * "none". For a part, its root's partContent comes first: it describes the
49
+ * part as it is used (Modal.Trigger takes one element), where the flat twin's
50
+ * own entry describes the export on its own.
51
+ */
52
+ export function contentOf(spec, name) {
53
+ const [root, part] = name.split(".");
54
+ const asPart = part ? spec?.components?.[root]?.partContent?.[part] : undefined;
55
+ return asPart ?? specEntry(spec, name)?.entry?.content ?? null;
56
+ }
57
+
58
+ /** The spec's client tier for a name, or null when the spec has no entry for it. */
59
+ export function clientTier(spec, name) {
60
+ return specEntry(spec, name)?.entry?.client ?? null;
61
+ }
62
+
63
+ /**
64
+ * The props the spec describes for a name: its recipe and scalar props, the
65
+ * style-prop groups it takes (with the interaction states when it takes the
66
+ * box group) and the attributes it redefines, less those its type omits.
67
+ * Null when the spec has no entry for the name.
68
+ */
69
+ export function describedProps(spec, name) {
70
+ const found = specEntry(spec, name);
71
+ if (!found) return null;
72
+ const { entry } = found;
73
+ const names = new Set([...Object.keys(entry.props ?? {}), ...Object.keys(entry.scalarProps ?? {}), ...(entry.overrides ?? [])]);
74
+ for (const group of entry.groups ?? []) {
75
+ for (const prop of Object.keys(spec.propGroups?.[group] ?? {})) names.add(prop);
76
+ if (group === "box") for (const state of Object.keys(spec.states ?? {})) names.add(state);
77
+ }
78
+ for (const prop of entry.exclude ?? []) names.delete(prop);
79
+ return names;
80
+ }
81
+
82
+ /* ---- what may leave the machine ------------------------------------------------ */
83
+
84
+ /** Props that carry the application's content rather than how a component is configured. */
85
+ const CONTENT_PROPS = new Set([
86
+ "alt", "ariaLabel", "code", "content", "defaultValue", "fallback", "href", "id", "items", "name",
87
+ "options", "query", "sizes", "src", "srcSet", "srcset", "value",
88
+ ]);
89
+ const CONTENT_SUFFIX = /(text|label|title|description|message|placeholder|caption|heading|tooltip)$/i;
90
+ const LONGEST_VALUE = 64;
91
+
92
+ /** Whether a prop may appear in a snapshot at all (the spec narrows it further). */
93
+ export function isConfigurationProp(key) {
94
+ return !CONTENT_PROPS.has(key) && !CONTENT_SUFFIX.test(key) && !/^(on[A-Z]|data-|aria-)/.test(key);
95
+ }
96
+
97
+ function configurationValue(value, depth = 2) {
98
+ if (typeof value === "string") return value.length <= LONGEST_VALUE ? value : undefined;
99
+ if (typeof value === "boolean") return value;
100
+ if (typeof value === "number") return Number.isFinite(value) ? value : undefined;
101
+ if (depth === 0 || typeof value !== "object" || value === null || Array.isArray(value)) return undefined;
102
+ const out = {};
103
+ for (const [key, inner] of Object.entries(value)) {
104
+ const kept = configurationValue(inner, depth - 1);
105
+ if (kept !== undefined) out[key] = kept;
106
+ }
107
+ return Object.keys(out).length ? out : undefined;
108
+ }
109
+
110
+ /**
111
+ * Keep only the props a snapshot may carry: described by the spec for this
112
+ * name, configuration rather than content, and plain serialisable values.
113
+ */
114
+ export function narrowProps(spec, name, props = {}) {
115
+ const described = describedProps(spec, name);
116
+ const out = {};
117
+ if (!described) return out;
118
+ for (const [key, value] of Object.entries(props)) {
119
+ if (!described.has(key) || !isConfigurationProp(key)) continue;
120
+ const kept = configurationValue(value);
121
+ if (kept !== undefined) out[key] = kept;
122
+ }
123
+ return out;
124
+ }
125
+
126
+ /**
127
+ * A tree with every component's props narrowed and its client tier read from
128
+ * the spec. Whoever assembles a snapshot applies it, whatever built the tree,
129
+ * so the rule on what may leave the machine has one home.
130
+ */
131
+ export function narrowTree(spec, nodes) {
132
+ if (!Array.isArray(nodes)) return [];
133
+ return nodes.map((node) => {
134
+ if (!node || typeof node !== "object" || !("component" in node)) return node;
135
+ const out = {
136
+ component: node.component,
137
+ props: narrowProps(spec, node.component, node.props ?? {}),
138
+ client: clientTier(spec, node.component),
139
+ };
140
+ if (Array.isArray(node.renders) && node.renders.length) out.renders = node.renders;
141
+ out.children = narrowTree(spec, node.children ?? []);
142
+ return out;
143
+ });
144
+ }
145
+
146
+ /** A text placeholder: the reporter chose not to include page text. */
147
+ export const redactedText = (text) => ({ redacted: true, length: text.length });
148
+
149
+ /** Page text, trimmed to the snapshot's limit. */
150
+ export const keptText = (text) => ({ text: text.slice(0, LIMITS.text) });
151
+
152
+ /** A route without its query string or fragment. */
153
+ export const cleanRoute = (route) => (route ? route.split(/[?#]/)[0] || "/" : null);
154
+
155
+ /**
156
+ * A console message fit to leave the machine: trimmed, with this page's origin
157
+ * and any absolute file-system path reduced to what follows it.
158
+ */
159
+ export function cleanConsoleMessage(message, origin = "") {
160
+ let text = String(message);
161
+ if (origin) text = text.split(origin).join("");
162
+ text = text
163
+ .replace(/file:\/\/\/?[^\s)'"]*?\/(node_modules|src|app|components|pages)\//g, "$1/")
164
+ .replace(/[A-Za-z]:\\[^\s)'"]*?\\(node_modules|src|app|components|pages)\\/g, "$1/")
165
+ .replace(/\/(?:Users|home)\/[^\s)'"/]+\/[^\s)'"]*?\/(node_modules|src|app|components|pages)\//g, "$1/");
166
+ return text.slice(0, LIMITS.consoleMessage);
167
+ }
168
+
169
+ /* ---- the schema -------------------------------------------------------------- */
170
+
171
+ const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
172
+ const isString = (v, max = 1000) => typeof v === "string" && v.length <= max;
173
+ const isOptional = (v, check) => v === null || v === undefined || check(v);
174
+ const TOP_LEVEL = new Set([
175
+ "format", "source", "library", "environment", "route", "tree", "findings", "console", "screenshot", "description",
176
+ ]);
177
+ const TIERS = new Set(["none", "leaf", "required"]);
178
+
179
+ function checkTree(nodes, errors) {
180
+ let count = 0;
181
+ const walk = (list, depth, at) => {
182
+ if (!Array.isArray(list)) return errors.push(`${at} must be a list`);
183
+ if (depth > LIMITS.depth) return errors.push(`${at} is nested more than ${LIMITS.depth} deep`);
184
+ list.forEach((node, i) => {
185
+ const here = `${at}[${i}]`;
186
+ if (++count > LIMITS.nodes) return;
187
+ if (!isObject(node)) return errors.push(`${here} must be an object`);
188
+ if ("text" in node) {
189
+ if (!isString(node.text, LIMITS.text) || Object.keys(node).length !== 1) errors.push(`${here} is not a text node`);
190
+ return;
191
+ }
192
+ if ("redacted" in node) {
193
+ if (node.redacted !== true || !Number.isInteger(node.length) || Object.keys(node).length !== 2) {
194
+ errors.push(`${here} is not a redacted text node`);
195
+ }
196
+ return;
197
+ }
198
+ if (!isString(node.component, 100) || !/^[A-Z][A-Za-z0-9]*(\.[A-Z][A-Za-z0-9]*)?$/.test(node.component)) {
199
+ return errors.push(`${here}.component must be a component name`);
200
+ }
201
+ if (!isObject(node.props)) errors.push(`${here}.props must be an object`);
202
+ else if (JSON.stringify(node.props).length > 2000) errors.push(`${here}.props is too large`);
203
+ if (!isOptional(node.client, (c) => TIERS.has(c))) errors.push(`${here}.client must be none, leaf or required`);
204
+ if (node.renders !== undefined && !(Array.isArray(node.renders) && node.renders.every((r) => isString(r, 100)))) {
205
+ errors.push(`${here}.renders must be a list of names`);
206
+ }
207
+ const known = new Set(["component", "props", "client", "renders", "children"]);
208
+ for (const key of Object.keys(node)) if (!known.has(key)) errors.push(`${here} has an unknown field "${key}"`);
209
+ walk(node.children ?? [], depth + 1, `${here}.children`);
210
+ });
211
+ };
212
+ walk(nodes, 0, "tree");
213
+ if (count > LIMITS.nodes) errors.push(`tree has more than ${LIMITS.nodes} nodes`);
214
+ }
215
+
216
+ const RELATIVE_PATH = /^(?![/\\])(?![A-Za-z]:)(?!.*(^|[/\\])\.\.([/\\]|$))[^\0]{1,300}$/;
217
+
218
+ /**
219
+ * Check a snapshot against format astralis-snapshot/1. Returns the problems
220
+ * found, or an empty list. Unknown fields are rejected, so nothing travels
221
+ * that the reporter was not shown by name.
222
+ */
223
+ export function checkSnapshot(value) {
224
+ const errors = [];
225
+ if (!isObject(value)) return ["a snapshot must be a JSON object"];
226
+ for (const key of Object.keys(value)) if (!TOP_LEVEL.has(key)) errors.push(`unknown field "${key}"`);
227
+ if (value.format !== SNAPSHOT_FORMAT) errors.push(`format must be "${SNAPSHOT_FORMAT}"`);
228
+ if (value.source !== "devtools" && value.source !== "cli") errors.push('source must be "devtools" or "cli"');
229
+
230
+ const lib = value.library;
231
+ if (!isObject(lib) || lib.name !== "astralis-ui" || !isString(lib.version, 50) || !Number.isInteger(lib.specVersion) ||
232
+ !/^[0-9a-f]{64}$/.test(lib.specSha256 ?? "")) {
233
+ errors.push("library must give astralis-ui's version, specVersion and specSha256");
234
+ }
235
+
236
+ const env = value.environment;
237
+ if (!isObject(env)) errors.push("environment must be an object");
238
+ else {
239
+ const fw = env.framework;
240
+ if (!isObject(fw) || !isOptional(fw.name, (n) => n === "next" || n === "vite") || !isOptional(fw.version, (v) => isString(v, 50))) {
241
+ errors.push("environment.framework must give a name (next or vite) and a version, or nulls");
242
+ }
243
+ if (!isOptional(env.react, (v) => isString(v, 50))) errors.push("environment.react must be a version or null");
244
+ if (!isOptional(env.browser, (v) => isString(v, 60))) errors.push("environment.browser must be a short name or null");
245
+ if (!isOptional(env.viewport, (v) => isObject(v) && Number.isInteger(v.width) && Number.isInteger(v.height))) {
246
+ errors.push("environment.viewport must give an integer width and height, or null");
247
+ }
248
+ if (!isOptional(env.colorMode, (m) => m === "light" || m === "dark")) errors.push("environment.colorMode must be light, dark or null");
249
+ }
250
+
251
+ if (!isOptional(value.route, (r) => isString(r, 500) && r.startsWith("/") && !/[?#]/.test(r))) {
252
+ errors.push("route must be a path without a query string, or null");
253
+ }
254
+ if (!Array.isArray(value.tree) || value.tree.length === 0) errors.push("tree must list at least one component");
255
+ else if (!value.tree.every((node) => isObject(node) && "component" in node)) errors.push("tree must start at components, not text");
256
+ else checkTree(value.tree, errors);
257
+
258
+ if (value.findings !== undefined) {
259
+ if (!Array.isArray(value.findings) || value.findings.length > LIMITS.findings) {
260
+ errors.push(`findings must be a list of at most ${LIMITS.findings}`);
261
+ } else {
262
+ value.findings.forEach((f, i) => {
263
+ const ok = isObject(f) && isString(f.code, 60) && isString(f.message, 500) && Number.isInteger(f.line) &&
264
+ Number.isInteger(f.column) && typeof f.file === "string" && RELATIVE_PATH.test(f.file);
265
+ if (!ok) errors.push(`findings[${i}] must have a code, a project-relative file, a line, a column and a message`);
266
+ });
267
+ }
268
+ }
269
+ if (value.console !== undefined) {
270
+ const ok = Array.isArray(value.console) && value.console.length <= LIMITS.console &&
271
+ value.console.every((m) => isString(m, LIMITS.consoleMessage));
272
+ if (!ok) errors.push(`console must be a list of at most ${LIMITS.console} messages`);
273
+ }
274
+ if (value.screenshot !== undefined && !/^data:image\/(png|jpeg);base64,[A-Za-z0-9+/=]+$/.test(value.screenshot ?? "")) {
275
+ errors.push("screenshot must be a PNG or JPEG data URL");
276
+ }
277
+
278
+ const d = value.description;
279
+ if (!isObject(d) || !isString(d.title, LIMITS.title) || !d.title.trim()) errors.push(`description.title is required (at most ${LIMITS.title} characters)`);
280
+ else {
281
+ for (const key of ["happened", "expected"]) {
282
+ if (!isOptional(d[key], (t) => isString(t, LIMITS.body))) errors.push(`description.${key} must be at most ${LIMITS.body} characters`);
283
+ }
284
+ for (const key of Object.keys(d)) if (!["title", "happened", "expected"].includes(key)) errors.push(`description has an unknown field "${key}"`);
285
+ }
286
+
287
+ const bytes = new TextEncoder().encode(JSON.stringify(value)).length;
288
+ if (bytes > MAX_SNAPSHOT_BYTES) errors.push(`the snapshot is ${Math.ceil(bytes / 1024)} kB; the limit is ${MAX_SNAPSHOT_BYTES / 1024} kB`);
289
+ return errors;
290
+ }
291
+
292
+ /* ---- the reproduction file ------------------------------------------------------ */
293
+
294
+ const IDENT = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
295
+
296
+ function jsLiteral(value) {
297
+ if (typeof value === "string") return JSON.stringify(value);
298
+ if (typeof value !== "object" || value === null) return String(value);
299
+ const entries = Object.entries(value).map(([k, v]) => `${IDENT.test(k) ? k : JSON.stringify(k)}: ${jsLiteral(v)}`);
300
+ return `{ ${entries.join(", ")} }`;
301
+ }
302
+
303
+ function jsxAttribute(key, value) {
304
+ if (value === true) return key;
305
+ if (typeof value === "string" && !/["{}\\\n]/.test(value)) return `${key}="${value}"`;
306
+ return `${key}={${jsLiteral(value)}}`;
307
+ }
308
+
309
+ const escapeJsxText = (text) => text.replace(/[{}<>]/g, (c) => `{"${c}"}`);
310
+
311
+ function renderNodes(nodes, indent, lines) {
312
+ for (const node of nodes) {
313
+ if ("text" in node) {
314
+ const text = node.text.trim();
315
+ if (text) lines.push(`${indent}${escapeJsxText(text)}`);
316
+ continue;
317
+ }
318
+ if ("redacted" in node) {
319
+ lines.push(`${indent}Text`);
320
+ continue;
321
+ }
322
+ const attrs = Object.entries(node.props ?? {}).map(([k, v]) => jsxAttribute(k, v));
323
+ const open = [node.component, ...attrs].join(" ");
324
+ const children = node.children ?? [];
325
+ if (node.renders?.length) lines.push(`${indent}{/* renders through ${node.renders.join(", ")} */}`);
326
+ if (children.length === 0) {
327
+ lines.push(`${indent}<${open} />`);
328
+ continue;
329
+ }
330
+ lines.push(`${indent}<${open}>`);
331
+ renderNodes(children, `${indent} `, lines);
332
+ lines.push(`${indent}</${node.component}>`);
333
+ }
334
+ }
335
+
336
+ function importedNames(nodes, into = new Set()) {
337
+ for (const node of nodes) {
338
+ if (!node.component) continue;
339
+ into.add(node.component.split(".")[0]);
340
+ importedNames(node.children ?? [], into);
341
+ }
342
+ return into;
343
+ }
344
+
345
+ /**
346
+ * The snapshot's tree as a minimal file that renders it: repro.tsx. Page text
347
+ * the reporter kept is used; redacted text becomes the word "Text". Run the
348
+ * validator on it to see the snapshot's findings reproduce, or not.
349
+ */
350
+ export function toRepro(snapshot) {
351
+ const lib = snapshot.library ?? {};
352
+ const names = [...importedNames(snapshot.tree ?? [])].sort();
353
+ const lines = [];
354
+ renderNodes(snapshot.tree ?? [], " ", lines);
355
+ const where = snapshot.route ? ` on ${snapshot.route}` : "";
356
+ const how = snapshot.source === "cli" ? "astralis report" : "the Astralis DevTools";
357
+ return [
358
+ `// Reproduction of an Astralis issue snapshot${where}, captured with ${how}.`,
359
+ `// astralis-ui ${lib.version ?? "unknown"} (spec ${lib.specVersion ?? "?"}).`,
360
+ `import { ${names.join(", ")} } from "astralis-ui";`,
361
+ "",
362
+ "export default function Repro() {",
363
+ " return (",
364
+ " <>",
365
+ ...lines,
366
+ " </>",
367
+ " );",
368
+ "}",
369
+ "",
370
+ ].join("\n");
371
+ }
@@ -0,0 +1,29 @@
1
+ import { readdirSync, statSync } from "node:fs";
2
+ import { join } from "node:path";
3
+
4
+ /** Folders that hold dependencies or build output, never source to validate. */
5
+ export const SKIP_DIRS = new Set(["node_modules", ".git", ".next", "dist", "build", "out", ".astralis"]);
6
+
7
+ export const SOURCE_FILE = /\.(tsx|jsx)$/;
8
+
9
+ /**
10
+ * Every .tsx/.jsx file at or under `path`, skipping SKIP_DIRS: the files
11
+ * `astralis validate` checks, and the ones the DevTools bridge watches.
12
+ * Returns null when `path` does not exist.
13
+ */
14
+ export function collectSourceFiles(path, into = []) {
15
+ const stats = statSync(path, { throwIfNoEntry: false });
16
+ if (!stats) return null;
17
+ if (stats.isFile()) {
18
+ if (SOURCE_FILE.test(path)) into.push(path);
19
+ return into;
20
+ }
21
+ for (const entry of readdirSync(path, { withFileTypes: true })) {
22
+ if (entry.isDirectory()) {
23
+ if (!SKIP_DIRS.has(entry.name)) collectSourceFiles(join(path, entry.name), into);
24
+ } else if (SOURCE_FILE.test(entry.name)) {
25
+ into.push(join(path, entry.name));
26
+ }
27
+ }
28
+ return into;
29
+ }
@@ -0,0 +1,32 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { resolve } from "node:path";
3
+ import { cyan, fail } from "./ui.mjs";
4
+ import { findInstalledSpec } from "./spec-resolve.mjs";
5
+
6
+ /**
7
+ * The system spec a command judges against: `explicitPath` when given, else
8
+ * the installed astralis-ui's. Returns { spec, text } (the raw text is what a
9
+ * snapshot hashes) or stops the command with a message that says what to do.
10
+ */
11
+ export function loadSpec(explicitPath, cwd = process.cwd()) {
12
+ const path = explicitPath ? resolve(explicitPath) : findInstalledSpec(cwd);
13
+ if (!path) {
14
+ fail(`Could not find astralis-ui's system spec here — is astralis-ui installed? (or pass ${cyan("--spec <path>")})`);
15
+ }
16
+ let text;
17
+ try {
18
+ text = readFileSync(path, "utf8");
19
+ } catch (error) {
20
+ fail(`Can't read the spec at ${path} (${error.code ?? error.message}).`);
21
+ }
22
+ let spec;
23
+ try {
24
+ spec = JSON.parse(text);
25
+ } catch {
26
+ fail(`${path} isn't valid JSON — expected astralis-ui's dist/system-spec.json.`);
27
+ }
28
+ if (!spec?.components || !Array.isArray(spec.classes)) {
29
+ fail(`${path} isn't an astralis-ui system spec (it has no components or classes).`);
30
+ }
31
+ return { spec, text };
32
+ }