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
@@ -1,15 +1,15 @@
1
- import { parseArgs } from "node:util";
2
1
  import { existsSync, readFileSync, writeFileSync, copyFileSync, mkdirSync } from "node:fs";
3
2
  import { join, dirname } from "node:path";
4
3
  import { homedir } from "node:os";
5
- import { spawnSync } from "node:child_process";
6
4
  import { ok, warn, info, fail, confirm, select, bold, cyan, dim } from "../lib/ui.mjs";
5
+ import { parseCommandArgs } from "../lib/args.mjs";
6
+ import { commandNamed } from "../lib/commands.mjs";
7
+ import { runCommand } from "../lib/run.mjs";
7
8
 
8
9
  /**
9
- * Connect one AI coding agent to the astralis-mcp docs server. Pick a client
10
- * (prompted, or via --client); the CLI explains exactly what it will do for
11
- * that client, confirms, then does it — running the client's own `mcp add`
12
- * command, or writing its JSON config file (with a backup).
10
+ * Connect one AI coding agent to the astralis-mcp docs server: pick a client,
11
+ * see exactly what will happen, confirm, and it runs the client's own
12
+ * `mcp add` or writes its JSON config (backing the old one up).
13
13
  */
14
14
 
15
15
  /** Windows can't spawn npx directly from a JSON command — it needs the cmd shim. */
@@ -35,39 +35,70 @@ export function antigravityConfigPath(home = homedir()) {
35
35
  }
36
36
 
37
37
  /**
38
- * Every supported client, in menu order. Two kinds:
39
- * "command" — the client owns its config; we run its `mcp add` for you.
40
- * "file" — we write an `mcpServers` entry into its JSON config (with backup).
38
+ * Every supported client, in menu order. "command" clients own their config
39
+ * and we run their `mcp add`; "file" clients get an `mcpServers` entry written
40
+ * into their JSON config. `root` is the directory that exists once the client
41
+ * is installed.
41
42
  */
42
43
  export const CLIENTS = {
43
44
  "claude-code": { label: "Claude Code", kind: "command", bin: "claude" },
44
45
  codex: { label: "Codex", kind: "command", bin: "codex" },
45
- cursor: { label: "Cursor", kind: "file", path: cursorConfigPath, reload: "Reload Cursor to pick it up." },
46
- "claude-desktop": { label: "Claude Desktop", kind: "file", path: claudeDesktopConfigPath, reload: "Restart Claude Desktop to pick it up." },
47
- antigravity: { label: "Antigravity", kind: "file", path: antigravityConfigPath, reload: "Reload Antigravity to pick it up." },
46
+ cursor: {
47
+ label: "Cursor",
48
+ kind: "file",
49
+ path: cursorConfigPath,
50
+ root: (home = homedir()) => join(home, ".cursor"),
51
+ reload: "Reload Cursor to pick it up.",
52
+ },
53
+ "claude-desktop": {
54
+ label: "Claude Desktop",
55
+ kind: "file",
56
+ path: claudeDesktopConfigPath,
57
+ root: () => dirname(claudeDesktopConfigPath()),
58
+ reload: "Restart Claude Desktop to pick it up.",
59
+ },
60
+ antigravity: {
61
+ label: "Antigravity",
62
+ kind: "file",
63
+ path: antigravityConfigPath,
64
+ root: (home = homedir()) => join(home, ".gemini"),
65
+ reload: "Reload Antigravity to pick it up.",
66
+ },
48
67
  };
49
68
 
50
- /** The `mcp add` argv both command-based clients happen to share. */
51
- const ADD_ARGS = ["mcp", "add", "astralis", "--", "npx", "-y", "astralis-mcp"];
69
+ /** The `mcp add` argv for a command client, launching the server the way this platform needs. */
70
+ export function mcpAddArgs(platform = process.platform) {
71
+ const entry = mcpServerEntry(platform);
72
+ return ["mcp", "add", "astralis", "--", entry.command, ...entry.args];
73
+ }
52
74
 
53
75
  /**
54
- * Parse an existing config file's contents. An empty or whitespace-only file
55
- * (something else touched it into existence) counts as a fresh config, not an
56
- * error; genuinely malformed JSON throws for the caller to report.
76
+ * An existing config file's contents. Empty or whitespace-only counts as a
77
+ * fresh config; malformed JSON throws for the caller to report.
57
78
  */
58
79
  export function parseConfigFile(raw) {
59
80
  return raw.trim() === "" ? {} : JSON.parse(raw);
60
81
  }
61
82
 
83
+ /** The first of `file.bak`, `file.bak.1`, `file.bak.2`… that doesn't exist yet, so no backup is overwritten. */
84
+ export function backupPath(file) {
85
+ if (!existsSync(`${file}.bak`)) return `${file}.bak`;
86
+ for (let n = 1; ; n++) {
87
+ if (!existsSync(`${file}.bak.${n}`)) return `${file}.bak.${n}`;
88
+ }
89
+ }
90
+
62
91
  export async function run(argv) {
63
- const { values } = parseArgs({ args: argv, options: { client: { type: "string" } } });
92
+ const args = parseCommandArgs(commandNamed("connect-mcp"), argv);
93
+ if (!args) return;
64
94
 
65
- let key = values.client;
95
+ let key = args.values.client;
66
96
  if (key === undefined) {
67
97
  console.log(`${bold("Connect a client")} to the Astralis MCP docs server.\n`);
68
98
  key = await select(
69
99
  "Which client do you want to connect?",
70
100
  Object.entries(CLIENTS).map(([value, { label }]) => ({ value, label })),
101
+ { hint: `Pass ${cyan("--client <name>")}.` },
71
102
  );
72
103
  if (key === null) {
73
104
  warn("No client selected — nothing to do.");
@@ -87,7 +118,8 @@ export async function run(argv) {
87
118
 
88
119
  /** Run the client's own `mcp add` command, falling back to a copy-paste line. */
89
120
  async function connectViaCommand(client) {
90
- const cmdline = `${client.bin} ${ADD_ARGS.join(" ")}`;
121
+ const addArgs = mcpAddArgs();
122
+ const cmdline = [client.bin, ...addArgs].join(" ");
91
123
  info(`${bold(client.label)} manages MCP servers with its own CLI.`);
92
124
  console.log(` I'll run: ${cyan(cmdline)}`);
93
125
  console.log(dim(` Needs the ${client.bin} CLI on your PATH.`));
@@ -97,7 +129,7 @@ async function connectViaCommand(client) {
97
129
  return;
98
130
  }
99
131
 
100
- const result = spawnSync(cmdline, { stdio: "inherit", shell: true });
132
+ const result = runCommand(client.bin, addArgs);
101
133
  if (result.status === 0) {
102
134
  ok(`Connected ${client.label} to the Astralis docs server.`);
103
135
  } else {
@@ -109,9 +141,15 @@ async function connectViaCommand(client) {
109
141
  async function connectViaFile(client) {
110
142
  const entry = mcpServerEntry();
111
143
  const configPath = client.path();
144
+ const snippet = `"astralis": ${JSON.stringify(entry)}`;
145
+
146
+ if (!existsSync(client.root())) {
147
+ fail(
148
+ `${client.label} doesn't look installed here (no ${client.root()}), so nothing was written.\n` +
149
+ ` Install it, or add this under "mcpServers" in its config yourself:\n ${cyan(snippet)}`,
150
+ );
151
+ }
112
152
 
113
- // Read the existing config first — nothing to describe or back up if the
114
- // server is already there.
115
153
  let config = {};
116
154
  if (existsSync(configPath)) {
117
155
  try {
@@ -127,20 +165,21 @@ async function connectViaFile(client) {
127
165
  return;
128
166
  }
129
167
 
168
+ const backup = existsSync(configPath) ? backupPath(configPath) : null;
130
169
  info(`${bold(client.label)} reads MCP servers from a JSON config file.`);
131
170
  console.log(` ${dim("file: ")} ${cyan(configPath)}`);
132
- console.log(` ${dim("adds: ")} ${cyan(`"astralis": ${JSON.stringify(entry)}`)}`);
133
- if (existsSync(configPath)) console.log(dim(" Your current config will be backed up for ease of revision."));
171
+ console.log(` ${dim("adds: ")} ${cyan(snippet)}`);
172
+ if (backup) console.log(dim(` Your current config is copied to ${backup} first.`));
134
173
 
135
174
  if (!(await confirm("Proceed?"))) {
136
175
  warn("Cancelled.");
137
176
  return;
138
177
  }
139
178
 
140
- if (existsSync(configPath)) copyFileSync(configPath, configPath + ".bak");
179
+ if (backup) copyFileSync(configPath, backup);
141
180
  else mkdirSync(dirname(configPath), { recursive: true });
142
181
  config.mcpServers = { ...config.mcpServers, astralis: entry };
143
182
  writeFileSync(configPath, JSON.stringify(config, null, 2) + "\n");
144
- ok(`written${existsSync(configPath + ".bak") ? dim(` (backup: ${configPath}.bak)`) : ""}`);
183
+ ok(`written${backup ? dim(` (backup: ${backup})`) : ""}`);
145
184
  info(client.reload);
146
185
  }
@@ -1,16 +1,18 @@
1
- import { existsSync } from "node:fs";
2
- import { join } from "node:path";
3
- import { spawnSync } from "node:child_process";
4
- import readline from "node:readline/promises";
5
- import { ok, warn, info, fail, bold, cyan, dim } from "../lib/ui.mjs";
1
+ import { existsSync, writeFileSync, rmSync } from "node:fs";
2
+ import { join, relative } from "node:path";
3
+ import { ok, warn, info, fail, bold, cyan, dim, ask, isAssumeYes, menu, posix, printBanner } from "../lib/ui.mjs";
4
+ import { parseCommandArgs } from "../lib/args.mjs";
5
+ import { commandNamed } from "../lib/commands.mjs";
6
+ import { runCommand, UnsafeArgumentError } from "../lib/run.mjs";
7
+ import { findEntryFile } from "../lib/detect.mjs";
8
+ import { starterFile, starterCleanup } from "../lib/starter.mjs";
6
9
 
7
10
  /**
8
11
  * Scaffold a brand-new project and wire Astralis into it. We own NO project
9
- * templates: the official scaffolder (create-next-app / create-vite) runs
10
- * interactively with its own prompts — TS, ESLint, Tailwind stay the user's
11
- * call, exactly as if they'd run it directly — and our `init` runs on the
12
- * result. Any extra args are forwarded verbatim to the scaffolder, so
13
- * non-interactive use works too:
12
+ * templates: the official scaffolder (create-next-app / create-vite) runs with
13
+ * its own prompts, so TS, ESLint and Tailwind stay the user's call, and our
14
+ * `init` runs on the result. Unrecognised args are forwarded verbatim to the
15
+ * scaffolder:
14
16
  *
15
17
  * astralis create my-app --framework vite --template react
16
18
  */
@@ -21,53 +23,121 @@ export function invokingPackageManager(userAgent = process.env.npm_config_user_a
21
23
  return ["pnpm", "yarn", "bun"].includes(name) ? name : "npm";
22
24
  }
23
25
 
24
- /** One shell command string (spawned with shell:true — pm binaries are .cmd shims on Windows). */
25
- export function buildScaffoldCommand(framework, name, forwarded, pm) {
26
+ /** Did the caller already decide about create-vite's install-and-start step? */
27
+ const IMMEDIATE_FLAGS = new Set(["-i", "--immediate", "--no-immediate"]);
28
+
29
+ /** Did the caller pick their own template? */
30
+ const TEMPLATE_FLAGS = new Set(["-t", "--template"]);
31
+
32
+ /** Each scaffolder's own switch for "ask nothing", passed on under --yes. */
33
+ const NON_INTERACTIVE_FLAG = { next: "--yes", vite: "--no-interactive" };
34
+
35
+ /**
36
+ * Astralis is a React library, so the Vite path names a React template rather
37
+ * than letting create-vite offer Vue and friends (picking one scaffolded a
38
+ * project the library can't be used in). Naming the template also skips
39
+ * create-vite's TypeScript/JavaScript question, so we ask it and map it here.
40
+ */
41
+ const VITE_TEMPLATES = { ts: "react-ts", js: "react" };
42
+ const DEFAULT_VITE_TEMPLATE = VITE_TEMPLATES.ts;
43
+
44
+ /** The scaffolder's argv: [pm, "create", scaffolder, name, ...args]. */
45
+ export function buildScaffoldCommand(
46
+ framework,
47
+ name,
48
+ forwarded,
49
+ pm,
50
+ template = DEFAULT_VITE_TEMPLATE,
51
+ { yes = false } = {},
52
+ ) {
26
53
  // yarn classic's `create` chokes on @latest tags; everyone else wants them.
27
54
  const tag = pm === "yarn" ? "" : "@latest";
28
55
  const scaffolder = framework === "next" ? `next-app${tag}` : `vite${tag}`;
56
+
57
+ const args = [...forwarded];
58
+
59
+ if (framework === "vite" && !args.some((arg) => TEMPLATE_FLAGS.has(arg))) {
60
+ args.push("--template", template);
61
+ }
62
+
63
+ // create-vite's "install and start now" runs a dev server that never exits,
64
+ // so our wiring step behind it would never run. Opt out unless the caller
65
+ // chose for themselves.
66
+ if (framework === "vite" && !args.some((arg) => IMMEDIATE_FLAGS.has(arg))) {
67
+ args.push("--no-immediate");
68
+ }
69
+
70
+ if (yes && !args.includes(NON_INTERACTIVE_FLAG[framework])) args.push(NON_INTERACTIVE_FLAG[framework]);
71
+
29
72
  // npm swallows flags meant for the scaffolder unless they sit behind `--`.
30
- const separator = pm === "npm" && forwarded.length > 0 ? ["--"] : [];
31
- return [pm, "create", scaffolder, name, ...separator, ...forwarded].filter(Boolean).join(" ");
73
+ const separator = pm === "npm" && args.length > 0 ? ["--"] : [];
74
+ return [pm, "create", scaffolder, name, ...separator, ...args];
32
75
  }
33
76
 
34
- async function promptFramework() {
35
- const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
36
- const answer = await rl.question(
37
- `${bold("Framework?")} ${cyan("1")} Next.js ${cyan("2")} Vite ${dim("(choose a React template when Vite asks)")} `,
38
- );
39
- rl.close();
40
- const choice = answer.trim().toLowerCase();
77
+ function promptFramework() {
78
+ const chosen = menu("Which framework?", [
79
+ { label: "Next.js", hint: "App Router; Server Components render with no library JavaScript" },
80
+ { label: "React (Vite)", hint: "A client-rendered single-page app" },
81
+ ]);
82
+ if (chosen !== null) return chosen === 0 ? "next" : "vite";
83
+ const answer = ask(`${bold("Framework?")} ${cyan("1")} Next.js ${cyan("2")} React ${dim("(Vite)")} `);
84
+ if (answer === null) fail(`No framework chosen and no input to read — pass ${cyan("--framework next|vite")}.`);
85
+ const choice = answer.toLowerCase();
41
86
  if (choice === "1" || choice === "next" || choice === "next.js" || choice === "nextjs") return "next";
42
- if (choice === "2" || choice === "vite") return "vite";
87
+ if (choice === "2" || choice === "vite" || choice === "react") return "vite";
43
88
  return null;
44
89
  }
45
90
 
91
+ /** create-vite's own language question; anything unrecognised, or no answer, means TypeScript. */
92
+ function promptLanguage() {
93
+ const chosen = menu("Which language?", [{ label: "TypeScript", hint: "Recommended: the props are typed" }, { label: "JavaScript" }]);
94
+ if (chosen !== null) return chosen === 1 ? VITE_TEMPLATES.js : VITE_TEMPLATES.ts;
95
+ const answer = ask(`${bold("Language?")} ${cyan("1")} TypeScript ${cyan("2")} JavaScript `)?.toLowerCase();
96
+ return answer === "2" || answer === "js" || answer === "javascript" ? VITE_TEMPLATES.js : VITE_TEMPLATES.ts;
97
+ }
98
+
46
99
  export async function run(argv) {
47
- // Manual parse: --framework is ours, first bare word is the name,
48
- // EVERYTHING else is forwarded untouched to the scaffolder.
49
- let framework;
50
- let name;
51
- const forwarded = [];
52
- for (let i = 0; i < argv.length; i++) {
53
- const arg = argv[i];
54
- if (arg === "--framework") framework = argv[++i];
55
- else if (!name && !arg.startsWith("-")) name = arg;
56
- else forwarded.push(arg);
57
- }
100
+ const args = parseCommandArgs(commandNamed("create"), argv);
101
+ if (!args) return;
102
+ const { values, forwarded } = args;
103
+ const [name] = args.positionals;
104
+ const yes = isAssumeYes();
58
105
 
59
- if (!name) fail('Usage: astralis create <project-name> [--framework next|vite] [scaffolder args…]');
106
+ if (!name) fail(`Name the project: ${cyan("astralis create <name>")}.`);
107
+ printBanner(`Creating ${name}`);
60
108
  if (!/^[a-z0-9@][a-z0-9-_.]*$/i.test(name)) fail(`"${name}" isn't a safe project name.`);
61
109
  if (existsSync(join(process.cwd(), name))) fail(`./${name} already exists.`);
62
110
 
63
- framework ??= await promptFramework();
111
+ let framework = values.framework;
112
+ if (framework === undefined) {
113
+ if (yes) fail(`--yes can't choose the framework — pass ${cyan("--framework next|vite")}.`);
114
+ framework = promptFramework();
115
+ }
64
116
  if (framework !== "next" && framework !== "vite") fail('Pick a framework: "next" or "vite".');
65
117
 
118
+ // Only ask the language when we name the template and someone can answer.
119
+ const namesOwnTemplate = forwarded.some((arg) => TEMPLATE_FLAGS.has(arg));
120
+ const template =
121
+ framework === "vite" && !namesOwnTemplate && !yes && process.stdin.isTTY ? promptLanguage() : DEFAULT_VITE_TEMPLATE;
122
+
66
123
  const pm = invokingPackageManager();
67
- const command = buildScaffoldCommand(framework, name, forwarded, pm);
68
- info(`${bold(command)} ${dim("(the scaffolder's own prompts — answer them as usual)")}`);
124
+ const [bin, ...scaffoldArgs] = buildScaffoldCommand(framework, name, forwarded, pm, template, { yes });
125
+
126
+ if (forwarded.some((arg) => arg === "-i" || arg === "--immediate")) {
127
+ warn("--immediate starts a dev server that doesn't exit, so Astralis can't be wired in afterwards.");
128
+ console.log(dim(` Run ${cyan("astralis init")} inside ./${name} once you've stopped it.`));
129
+ }
130
+ info(`${bold([bin, ...scaffoldArgs].join(" "))} ${dim("(the scaffolder's own prompts — answer them as usual)")}`);
69
131
 
70
- const scaffold = spawnSync(command, { stdio: "inherit", shell: true });
132
+ // The scaffolder's arrow-key menu needs the console to itself, which holds
133
+ // because this process has never read stdin (see lib/prompt-child.mjs).
134
+ let scaffold;
135
+ try {
136
+ scaffold = runCommand(bin, scaffoldArgs);
137
+ } catch (error) {
138
+ if (error instanceof UnsafeArgumentError) fail(`Couldn't forward that to the scaffolder: ${error.message}.`);
139
+ throw error;
140
+ }
71
141
  if (scaffold.status !== 0) fail("Scaffolding failed or was cancelled — nothing to wire up.");
72
142
  if (!existsSync(join(process.cwd(), name, "package.json"))) {
73
143
  fail(`Expected ./${name}/package.json after scaffolding — did the scaffolder use a different directory?`);
@@ -78,7 +148,31 @@ export async function run(argv) {
78
148
  info("wiring Astralis into it…");
79
149
  process.chdir(name);
80
150
  const init = await import("./init.mjs");
81
- await init.run([]);
151
+ await init.run(values["no-devtools"] ? [] : ["--devtools"], { nested: true, pm });
152
+
153
+ /*
154
+ * Replace the scaffolder's demo page with one built from Astralis. Only
155
+ * here, never in `init`: on a directory scaffolded seconds ago there is
156
+ * nothing to lose, and it makes "did init work?" visible on first `dev`.
157
+ */
158
+ if (!values["no-starter"]) {
159
+ const entry = findEntryFile(process.cwd(), framework);
160
+ if (entry) {
161
+ const { path, source } = starterFile(framework, entry.path);
162
+ writeFileSync(path, source);
163
+
164
+ // The template's demo CSS centres and re-colours everything, so it goes with its demo.
165
+ const cleanup = starterCleanup(framework, entry.path);
166
+ for (const file of cleanup.rewrite) {
167
+ if (existsSync(file.path)) writeFileSync(file.path, file.source);
168
+ }
169
+ for (const orphan of cleanup.remove) {
170
+ if (existsSync(orphan)) rmSync(orphan);
171
+ }
172
+
173
+ ok(`welcome screen written ${dim(`(${posix(relative(process.cwd(), path))})`)}`);
174
+ }
175
+ }
82
176
 
83
177
  console.log(`\n${bold("Next steps:")}\n ${cyan(`cd ${name}`)}\n ${cyan(`${pm} run dev`)}`);
84
178
  }
@@ -1,9 +1,12 @@
1
- import { parseArgs } from "node:util";
2
1
  import { readFileSync, writeFileSync } from "node:fs";
3
- import { spawnSync } from "node:child_process";
4
2
  import { readPackageJson, detectPackageManager, detectFramework, findEntryFile } from "../lib/detect.mjs";
5
- import { addImports, wrapJsx, addTagAttribute, insertAfterBodyTag, addStatementAfterImports } from "../lib/edits.mjs";
6
- import { ok, warn, info, fail, bold, dim, cyan } from "../lib/ui.mjs";
3
+ import { addImports, wrapJsx, addTagAttribute, insertAfterBodyTag, addStatementAfterImports, parses } from "../lib/edits.mjs";
4
+ import { ok, warn, info, fail, bold, dim, cyan, printBanner } from "../lib/ui.mjs";
5
+ import { parseCommandArgs } from "../lib/args.mjs";
6
+ import { commandNamed } from "../lib/commands.mjs";
7
+ import { runCommand } from "../lib/run.mjs";
8
+ import { setUpCi } from "../lib/ci-setup.mjs";
9
+ import { devtoolsLayoutEdits, setUpDevtools } from "../lib/devtools-setup.mjs";
7
10
 
8
11
  const PROVIDER_IMPORT = 'import { AstralisProvider } from "astralis-ui";';
9
12
  const STYLES_IMPORT = 'import "astralis-ui/styles.css";';
@@ -19,39 +22,85 @@ const MANUAL_SNIPPET = `
19
22
  1. ${PROVIDER_IMPORT}
20
23
  2. ${STYLES_IMPORT} ${dim("(once, at your entry point)")}
21
24
  3. Wrap your app: <AstralisProvider defaultTheme="system">…</AstralisProvider>
22
- Full guide: ${cyan("https://astralis-zeta.vercel.app/docs/installation")}`;
23
-
24
- export async function run(argv) {
25
- const { values } = parseArgs({
26
- args: argv,
27
- options: { "dry-run": { type: "boolean", default: false } },
28
- });
29
- const dryRun = values["dry-run"];
25
+ Full guide: ${cyan("https://astralis-ui.com/docs/installation")}`;
26
+
27
+ /**
28
+ * `nested` is set when `create` calls this as its wiring step. It suppresses
29
+ * the sign-off, because create prints its own "Next steps" immediately after —
30
+ * two closing blocks in one run read as the command finishing twice. `pm` is
31
+ * create's package manager: a fresh scaffold has no lockfile to detect it from.
32
+ */
33
+ export async function run(argv, { nested = false, pm: givenPm } = {}) {
34
+ const args = parseCommandArgs(commandNamed("init"), argv);
35
+ if (!args) return;
36
+ const dryRun = args.values["dry-run"];
37
+ const ci = args.values.ci;
38
+ const devtools = args.values.devtools;
39
+ if (args.values.force && !ci) fail("--force only applies with --ci (it replaces an existing workflow).");
30
40
  const cwd = process.cwd();
41
+ if (!nested) printBanner(ci ? "Setting up validation in CI" : devtools ? "Adding the DevTools" : "Adding Astralis UI to this project");
31
42
 
32
43
  const pkg = readPackageJson(cwd);
33
44
  if (!pkg) fail("No package.json here — run `astralis init` from your project root.");
34
45
 
35
46
  const framework = detectFramework(pkg);
36
47
  if (!framework) {
37
- warn("Couldn't detect Next.js or Vite in this project.");
48
+ // Be specific about which half is missing. A Vue + Vite app used to be
49
+ // told "couldn't detect Vite", which is untrue and points at the wrong
50
+ // problem — Vite is there, React is not.
51
+ const deps = { ...pkg.dependencies, ...pkg.devDependencies };
52
+ if (deps.vite) {
53
+ warn("This is a Vite project, but not a React one.");
54
+ console.log(
55
+ dim(" Astralis is a React library — react and react-dom are its peer dependencies."),
56
+ );
57
+ } else {
58
+ warn("Couldn't detect Next.js or a React + Vite project here.");
59
+ }
38
60
  console.log(MANUAL_SNIPPET);
39
61
  return;
40
62
  }
41
- const pm = detectPackageManager(cwd);
42
- info(`${bold(framework === "next" ? "Next.js" : "Vite")} project, ${bold(pm)}${dryRun ? dim(" (dry run — nothing will be written)") : ""}`);
63
+ const pm = givenPm ?? detectPackageManager(cwd);
64
+
65
+ /*
66
+ * Step output is buffered until we know whether anything actually changed.
67
+ * Re-running init on an already-wired project used to print a checklist of
68
+ * things it had not done, followed by a sign-off — reading like work when
69
+ * the honest answer is "nothing to do".
70
+ *
71
+ * The moment a real change happens we flush and switch to printing live, so
72
+ * a package-manager install still streams in order.
73
+ */
74
+ const steps = [];
75
+ const afterwards = [];
76
+ let printing = false;
77
+ let changed = false;
78
+ const step = (fn) => (printing ? fn() : steps.push(fn));
79
+ const flush = () => {
80
+ for (const fn of steps) fn();
81
+ steps.length = 0;
82
+ printing = true;
83
+ };
84
+ const out = { step, flush, changed: () => (changed = true), after: (fn) => afterwards.push(fn) };
85
+
86
+ step(() =>
87
+ info(
88
+ `${bold(framework === "next" ? "Next.js" : "Vite")} project, ${bold(pm)}${dryRun ? dim(" (dry run — nothing will be written)") : ""}`,
89
+ ),
90
+ );
43
91
 
44
92
  // 1. Dependency
45
93
  const hasDep = Boolean(pkg.dependencies?.["astralis-ui"] ?? pkg.devDependencies?.["astralis-ui"]);
46
94
  if (hasDep) {
47
- ok("astralis-ui already in dependencies");
95
+ step(() => ok("astralis-ui already in dependencies"));
48
96
  } else if (dryRun) {
49
- info(`would run: ${pm} add astralis-ui`);
97
+ changed = true;
98
+ step(() => info(`would run: ${pm} add astralis-ui`));
50
99
  } else {
100
+ changed = true;
101
+ flush();
51
102
  info(`installing astralis-ui with ${pm}…`);
52
- // One command string: pm binaries are .cmd shims on Windows (need a shell),
53
- // and shell+args-array triggers Node's unescaped-args deprecation.
54
- const result = spawnSync(`${pm} add astralis-ui`, { stdio: "inherit", shell: true });
103
+ const result = runCommand(pm, ["add", "astralis-ui"]);
55
104
  if (result.status !== 0) fail(`${pm} add astralis-ui failed — install it manually, then re-run init.`);
56
105
  ok("astralis-ui installed");
57
106
  }
@@ -59,8 +108,15 @@ export async function run(argv) {
59
108
  // 2. Entry file
60
109
  const entry = findEntryFile(cwd, framework);
61
110
  if (!entry) {
111
+ flush();
62
112
  warn(`Couldn't find your ${framework === "next" ? "root layout" : "src/main.tsx"} — wire the provider manually:`);
63
113
  console.log(MANUAL_SNIPPET);
114
+ const extra = [
115
+ ...(devtools ? setUpDevtools({ cwd, pkg, pm, framework, entry: null, dryRun, out }) : []),
116
+ ...(ci ? setUpCi({ cwd, pkg, pm, dryRun, force: args.values.force, out }) : []),
117
+ ];
118
+ for (const note of extra) warn(note);
119
+ for (const fn of afterwards) fn();
64
120
  return;
65
121
  }
66
122
 
@@ -69,15 +125,17 @@ export async function run(argv) {
69
125
  const notes = [];
70
126
  const apply = (result, label) => {
71
127
  source = result.source;
72
- if (result.changed) ok(`${label} ${dim(`(${entry.relative})`)}`);
73
- else if (result.note) notes.push(`${label}: ${result.note}`);
74
- else ok(`${label} — already present`);
128
+ if (result.changed) {
129
+ changed = true;
130
+ step(() => ok(`${label} ${dim(`(${entry.relative})`)}`));
131
+ } else if (result.note) notes.push(`${label}: ${result.note}`);
132
+ else step(() => ok(`${label} — already present`));
75
133
  };
76
134
 
77
135
  apply(addImports(source, [PROVIDER_IMPORT, STYLES_IMPORT]), "imports added");
78
136
 
79
137
  if (source.includes("<AstralisProvider")) {
80
- ok("AstralisProvider already wraps this file");
138
+ step(() => ok("AstralisProvider already wraps this file"));
81
139
  } else if (framework === "next") {
82
140
  apply(
83
141
  wrapJsx(source, "{children}", '<AstralisProvider defaultTheme="system">', "</AstralisProvider>"),
@@ -94,16 +152,55 @@ export async function run(argv) {
94
152
  apply(addStatementAfterImports(source, THEME_INIT_CONST), "anti-flash theme script const");
95
153
  apply(insertAfterBodyTag(source, THEME_INIT_SCRIPT), "theme script injected after <body>");
96
154
  apply(addTagAttribute(source, "html", "suppressHydrationWarning"), "suppressHydrationWarning on <html>");
155
+ if (devtools) {
156
+ const [imported, placed] = devtoolsLayoutEdits(source);
157
+ apply(imported, "DevTools import added");
158
+ apply(placed, "<AstralisDevTools /> placed before </body>");
159
+ }
97
160
  }
98
161
 
99
- // 3. Write
162
+ // 3. Write — never a file that no longer parses; hand over to the manual steps instead.
163
+ if (source !== original && !parses(source)) {
164
+ source = original;
165
+ notes.push(`${entry.relative}: the edits would leave it unparseable, so nothing was written`);
166
+ }
100
167
  if (source !== original) {
101
- if (dryRun) info(`would update ${entry.relative}`);
168
+ if (dryRun) step(() => info(`would update ${entry.relative}`));
102
169
  else writeFileSync(entry.path, source);
103
170
  }
104
171
 
172
+ // 4. DevTools and CI
173
+ const wiringNotes = notes.length;
174
+ if (devtools) notes.push(...setUpDevtools({ cwd, pkg, pm, framework, entry, dryRun, out }));
175
+ if (ci) notes.push(...setUpCi({ cwd, pkg, pm, dryRun, force: args.values.force, out }));
176
+
177
+ /*
178
+ * Nothing to do, and nothing that needed the reader's attention: say so in
179
+ * one line instead of listing the steps that were already satisfied.
180
+ */
181
+ if (!changed && notes.length === 0) {
182
+ const extras = [devtools && "the DevTools", ci && "its CI check"].filter(Boolean);
183
+ ok(
184
+ extras.length
185
+ ? `astralis-ui and ${extras.join(" and ")} are already set up in this project`
186
+ : "astralis-ui is already present in this project",
187
+ );
188
+ if (nested) return;
189
+ console.log(`Nothing to scaffold.\nDocs: ${cyan("https://astralis-ui.com/docs")}`);
190
+ return;
191
+ }
192
+
193
+ flush();
194
+
105
195
  for (const note of notes) warn(note);
106
- if (notes.length > 0) console.log(MANUAL_SNIPPET);
196
+ if (wiringNotes > 0) console.log(MANUAL_SNIPPET);
197
+ for (const fn of afterwards) fn();
107
198
 
108
- console.log(`\n${bold("Done.")} Try it:\n ${cyan('import { Button } from "astralis-ui";')}\n ${cyan('<Button colorScheme="teal">Hello</Button>')}\nDocs: ${cyan("https://astralis-zeta.vercel.app/docs")}`);
199
+ if (nested || !changed) return;
200
+
201
+ if (dryRun) {
202
+ console.log(`\n${bold("Dry run:")} nothing was written. Run ${cyan(["astralis init", devtools && "--devtools", ci && "--ci"].filter(Boolean).join(" "))} to apply it.`);
203
+ return;
204
+ }
205
+ console.log(`\n${bold("Done.")} Try it:\n ${cyan('import { Button } from "astralis-ui";')}\n ${cyan('<Button colorScheme="teal">Hello</Button>')}\nDocs: ${cyan("https://astralis-ui.com/docs")}`);
109
206
  }