astralis-cli 0.2.1 → 0.4.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "astralis-cli",
3
- "version": "0.2.1",
3
+ "version": "0.4.0",
4
4
  "description": "Setup and tooling CLI for Astralis UI — wire up a project, generate a static brand theme, connect the MCP server.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -36,7 +36,7 @@
36
36
  "node": ">=18"
37
37
  },
38
38
  "dependencies": {
39
- "astralis-ui": "^0.2.0"
39
+ "astralis-ui": "^0.5.0"
40
40
  },
41
41
  "scripts": {
42
42
  "test": "node --test"
@@ -0,0 +1,177 @@
1
+ import { parseArgs } from "node:util";
2
+ import { existsSync, mkdirSync, writeFileSync } from "node:fs";
3
+ import { dirname, join, relative } from "node:path";
4
+ import { ok, warn, info, fail, cyan, dim, bold, confirm } from "../lib/ui.mjs";
5
+ import { readPackageJson, detectPackageManager } from "../lib/detect.mjs";
6
+ import { resolveBlocksDir } from "../lib/blocks-dir.mjs";
7
+ import { registryBase, fetchIndex, fetchBlock } from "../lib/registry.mjs";
8
+
9
+ /**
10
+ * Copies a block's source into the project.
11
+ *
12
+ * This is deliberately small compared with the equivalent in other libraries,
13
+ * and the reason is architectural: a block imports only astralis-ui, react, or
14
+ * a sibling file — the registry builder rejects anything else — and the
15
+ * stylesheet is precompiled. So there is no import rewriting to consumer
16
+ * aliases, no dependency graph between blocks, and no Tailwind config to
17
+ * merge. Fetch text, write files, check one dependency.
18
+ */
19
+
20
+ const USAGE = `Usage: astralis add <block>... [options]
21
+
22
+ Copies a block's source into your project. The files are yours after that —
23
+ no dependency to configure around.
24
+
25
+ Options
26
+ --list print every available block and exit
27
+ --dir <path> where to write (default: [src/]components/blocks)
28
+ --overwrite replace existing files without asking
29
+ --dry-run show what would be written, write nothing
30
+ --registry <url> read from a different registry host
31
+ -h, --help this message
32
+
33
+ Examples
34
+ astralis add hero-01
35
+ astralis add login-01 dashboard-02 --dir src/ui/blocks
36
+ astralis add --list
37
+ `;
38
+
39
+ /** Group ids by category for a readable --list. */
40
+ function printCatalogue(blocks) {
41
+ const byCategory = new Map();
42
+ for (const block of blocks) {
43
+ if (!byCategory.has(block.category)) byCategory.set(block.category, []);
44
+ byCategory.get(block.category).push(block);
45
+ }
46
+
47
+ console.log(`\n${bold("Available blocks")} ${dim(`(${blocks.length})`)}\n`);
48
+ for (const [category, items] of [...byCategory].sort()) {
49
+ console.log(` ${bold(category)}`);
50
+ for (const item of items.sort((a, b) => a.id.localeCompare(b.id))) {
51
+ console.log(` ${cyan(item.id.padEnd(22))} ${dim(item.name)}`);
52
+ }
53
+ console.log("");
54
+ }
55
+ console.log(` ${dim(`Add one with ${cyan("astralis add <id>")}`)}\n`);
56
+ }
57
+
58
+ export async function run(argv) {
59
+ let parsed;
60
+ try {
61
+ parsed = parseArgs({
62
+ args: argv,
63
+ allowPositionals: true,
64
+ options: {
65
+ list: { type: "boolean", default: false },
66
+ dir: { type: "string" },
67
+ overwrite: { type: "boolean", default: false },
68
+ "dry-run": { type: "boolean", default: false },
69
+ registry: { type: "string" },
70
+ help: { type: "boolean", short: "h", default: false },
71
+ },
72
+ });
73
+ } catch (error) {
74
+ fail(`${error.message}\n\n${USAGE}`);
75
+ }
76
+
77
+ const { values, positionals } = parsed;
78
+ if (values.help) return console.log(USAGE);
79
+
80
+ const cwd = process.cwd();
81
+ const base = registryBase(values.registry);
82
+
83
+ if (values.list) return printCatalogue((await fetchIndex(base)).blocks);
84
+
85
+ if (positionals.length === 0) {
86
+ fail(`Name at least one block — try ${cyan("astralis add --list")}.\n\n${USAGE}`);
87
+ }
88
+
89
+ /* --- resolve every id before writing anything -------------------------- */
90
+ const items = [];
91
+ for (const id of positionals) {
92
+ const block = await fetchBlock(base, id);
93
+ if (!block) {
94
+ fail(
95
+ `No block called ${cyan(id)}.\n` +
96
+ ` Run ${cyan("astralis add --list")} to see what exists.`,
97
+ );
98
+ }
99
+ items.push(block);
100
+ }
101
+
102
+ const { relative: dirRelative, source } = resolveBlocksDir(cwd, values.dir);
103
+ const target = join(cwd, dirRelative);
104
+ const dryRun = values["dry-run"];
105
+
106
+ // Paths are shown forward-slashed on every platform: they end up in an
107
+ // import statement, where a Windows separator would be wrong anyway.
108
+ const posix = (path) => path.split("\\").join("/");
109
+
110
+ console.log("");
111
+ info(
112
+ `Writing to ${cyan(posix(dirRelative))}` +
113
+ (source === "default" ? "" : dim(` (from ${source})`)),
114
+ );
115
+
116
+ /* --- write ------------------------------------------------------------- */
117
+ let written = 0;
118
+ let skipped = 0;
119
+
120
+ for (const block of items) {
121
+ for (const file of block.contents) {
122
+ const path = join(target, file.path);
123
+ const shown = posix(relative(cwd, path));
124
+
125
+ if (existsSync(path) && !values.overwrite) {
126
+ if (dryRun) {
127
+ warn(`${shown} ${dim("exists — would ask before replacing")}`);
128
+ skipped += 1;
129
+ continue;
130
+ }
131
+ const replace = await confirm(`${shown} already exists. Replace it?`);
132
+ if (!replace) {
133
+ warn(`skipped ${shown}`);
134
+ skipped += 1;
135
+ continue;
136
+ }
137
+ }
138
+
139
+ if (dryRun) {
140
+ ok(`${shown} ${dim(`(${Buffer.byteLength(file.content)} bytes)`)}`);
141
+ } else {
142
+ mkdirSync(dirname(path), { recursive: true });
143
+ writeFileSync(path, file.content);
144
+ ok(shown);
145
+ }
146
+ written += 1;
147
+ }
148
+ }
149
+
150
+ /* --- the one dependency a block actually has --------------------------- */
151
+ const pkg = readPackageJson(cwd);
152
+ const deps = { ...pkg?.dependencies, ...pkg?.devDependencies };
153
+ if (pkg && !deps["astralis-ui"]) {
154
+ const pm = detectPackageManager(cwd);
155
+ const install = pm === "npm" ? "npm install" : `${pm} add`;
156
+ console.log("");
157
+ warn(
158
+ `astralis-ui is not in this project's dependencies — the block will not compile.\n` +
159
+ ` Run ${cyan(`${install} astralis-ui`)}, or ${cyan("astralis init")} to wire it up fully.`,
160
+ );
161
+ }
162
+
163
+ console.log("");
164
+ const verb = dryRun ? "would write" : "wrote";
165
+ console.log(
166
+ `${verb} ${bold(String(written))} file(s)` +
167
+ (skipped ? dim(`, skipped ${skipped}`) : "") +
168
+ (dryRun ? dim(" — dry run, nothing changed") : ""),
169
+ );
170
+ if (!dryRun && written) {
171
+ const first = items[0];
172
+ const alias = posix(dirRelative.replace(/^src[\\/]/, ""));
173
+ const file = first.contents[0].path.replace(/\.tsx?$/, "");
174
+ console.log(dim(` import { ${first.component} } from "@/${alias}/${file}";`));
175
+ }
176
+ console.log("");
177
+ }
@@ -97,6 +97,8 @@ async function connectViaCommand(client) {
97
97
  return;
98
98
  }
99
99
 
100
+ // Safe to hand the terminal over: prompts run in a child process, so this
101
+ // one has never read stdin and is not holding the console.
100
102
  const result = spawnSync(cmdline, { stdio: "inherit", shell: true });
101
103
  if (result.status === 0) {
102
104
  ok(`Connected ${client.label} to the Astralis docs server.`);
@@ -1,8 +1,9 @@
1
- import { existsSync } from "node:fs";
2
- import { join } from "node:path";
1
+ import { existsSync, writeFileSync, rmSync } from "node:fs";
2
+ import { join, relative } from "node:path";
3
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";
4
+ import { ok, warn, info, fail, bold, cyan, dim, ask } from "../lib/ui.mjs";
5
+ import { findEntryFile } from "../lib/detect.mjs";
6
+ import { starterFile, starterCleanup } from "../lib/starter.mjs";
6
7
 
7
8
  /**
8
9
  * Scaffold a brand-new project and wire Astralis into it. We own NO project
@@ -21,37 +22,101 @@ export function invokingPackageManager(userAgent = process.env.npm_config_user_a
21
22
  return ["pnpm", "yarn", "bun"].includes(name) ? name : "npm";
22
23
  }
23
24
 
25
+ /** Did the caller already decide about create-vite's install-and-start step? */
26
+ const IMMEDIATE_FLAGS = new Set(["-i", "--immediate", "--no-immediate"]);
27
+
28
+ /** Did the caller pick their own template? */
29
+ const TEMPLATE_FLAGS = new Set(["-t", "--template"]);
30
+
31
+ /**
32
+ * Astralis is a React library — react and react-dom are its peer dependencies
33
+ * and every component is JSX. So the Vite path names a React template rather
34
+ * than letting create-vite offer its full menu: picking Vue there scaffolded a
35
+ * project the library cannot be used in, and the failure only surfaced two
36
+ * steps later when wiring found no React.
37
+ *
38
+ * `--template` selects framework AND variant together, so naming one also
39
+ * skips create-vite's TypeScript/JavaScript question. That is a choice the
40
+ * caller still owns, so we ask it ourselves and map the answer here.
41
+ */
42
+ const VITE_TEMPLATES = { ts: "react-ts", js: "react" };
43
+ const DEFAULT_VITE_TEMPLATE = VITE_TEMPLATES.ts;
44
+
24
45
  /** One shell command string (spawned with shell:true — pm binaries are .cmd shims on Windows). */
25
- export function buildScaffoldCommand(framework, name, forwarded, pm) {
46
+ export function buildScaffoldCommand(
47
+ framework,
48
+ name,
49
+ forwarded,
50
+ pm,
51
+ template = DEFAULT_VITE_TEMPLATE,
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
+ // Name the template so create-vite never offers Vue, Svelte and friends.
60
+ // `template` carries the language the caller chose — see VITE_TEMPLATES.
61
+ if (framework === "vite" && !args.some((arg) => TEMPLATE_FLAGS.has(arg))) {
62
+ args.push("--template", template);
63
+ }
64
+
65
+ /*
66
+ * create-vite offers to "install with npm and start now", and answering yes
67
+ * runs a dev server that never exits. Our wiring step sits behind that spawn,
68
+ * so it would never run and the user would be handed a plain Vite app with no
69
+ * Astralis in it — which is exactly what happened. Opt out by default; a
70
+ * caller who passes -i/--immediate themselves has chosen to skip our wiring.
71
+ */
72
+ if (framework === "vite" && !args.some((arg) => IMMEDIATE_FLAGS.has(arg))) {
73
+ args.push("--no-immediate");
74
+ }
75
+
29
76
  // 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(" ");
77
+ const separator = pm === "npm" && args.length > 0 ? ["--"] : [];
78
+ return [pm, "create", scaffolder, name, ...separator, ...args].filter(Boolean).join(" ");
32
79
  }
33
80
 
34
81
  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)")} `,
82
+ // Via ask(), which reads in a child process — this process must never touch
83
+ // stdin, or the scaffolder it spawns next will not receive a keystroke.
84
+ const answer = await ask(
85
+ `${bold("Framework?")} ${cyan("1")} Next.js ${cyan("2")} React ${dim("(Vite)")} `,
38
86
  );
39
- rl.close();
40
87
  const choice = answer.trim().toLowerCase();
41
88
  if (choice === "1" || choice === "next" || choice === "next.js" || choice === "nextjs") return "next";
42
- if (choice === "2" || choice === "vite") return "vite";
89
+ if (choice === "2" || choice === "vite" || choice === "react") return "vite";
43
90
  return null;
44
91
  }
45
92
 
93
+ /**
94
+ * The question create-vite would have asked, had we not named its template.
95
+ * create-next-app still asks this itself, so it is only needed on the Vite
96
+ * path. Anything unrecognised — including an empty answer on piped input —
97
+ * falls back to TypeScript.
98
+ */
99
+ async function promptLanguage() {
100
+ const answer = await ask(
101
+ `${bold("Language?")} ${cyan("1")} TypeScript ${cyan("2")} JavaScript `,
102
+ );
103
+ const choice = answer.trim().toLowerCase();
104
+ if (choice === "2" || choice === "js" || choice === "javascript") return VITE_TEMPLATES.js;
105
+ return VITE_TEMPLATES.ts;
106
+ }
107
+
46
108
  export async function run(argv) {
47
109
  // Manual parse: --framework is ours, first bare word is the name,
48
110
  // EVERYTHING else is forwarded untouched to the scaffolder.
49
111
  let framework;
50
112
  let name;
113
+ let starter = true;
51
114
  const forwarded = [];
52
115
  for (let i = 0; i < argv.length; i++) {
53
116
  const arg = argv[i];
54
117
  if (arg === "--framework") framework = argv[++i];
118
+ // Ours, not the scaffolder's — consume it so it isn't forwarded.
119
+ else if (arg === "--no-starter") starter = false;
55
120
  else if (!name && !arg.startsWith("-")) name = arg;
56
121
  else forwarded.push(arg);
57
122
  }
@@ -63,10 +128,33 @@ export async function run(argv) {
63
128
  framework ??= await promptFramework();
64
129
  if (framework !== "next" && framework !== "vite") fail('Pick a framework: "next" or "vite".');
65
130
 
131
+ /*
132
+ * Ask the language only when we are the ones naming the template, and only
133
+ * when there is somebody to answer: a caller who passed their own
134
+ * `--template` has already decided, and a non-interactive run (CI, piped
135
+ * input) must not block on a question. Both fall through to TypeScript.
136
+ */
137
+ const namesOwnTemplate = forwarded.some((arg) => TEMPLATE_FLAGS.has(arg));
138
+ const template =
139
+ framework === "vite" && !namesOwnTemplate && process.stdin.isTTY
140
+ ? await promptLanguage()
141
+ : DEFAULT_VITE_TEMPLATE;
142
+
66
143
  const pm = invokingPackageManager();
67
- const command = buildScaffoldCommand(framework, name, forwarded, pm);
144
+ const command = buildScaffoldCommand(framework, name, forwarded, pm, template);
145
+
146
+ // If they asked create-vite to start a dev server, it never returns and this
147
+ // process never gets to wire anything. Say so rather than appear to fail.
148
+ const startsDevServer = forwarded.some((arg) => arg === "-i" || arg === "--immediate");
149
+ if (startsDevServer) {
150
+ warn("--immediate starts a dev server that doesn't exit, so Astralis can't be wired in afterwards.");
151
+ console.log(dim(` Run ${cyan("astralis init")} inside ./${name} once you've stopped it.`));
152
+ }
68
153
  info(`${bold(command)} ${dim("(the scaffolder's own prompts — answer them as usual)")}`);
69
154
 
155
+ // The scaffolder's menu is arrow-driven and needs sole ownership of the
156
+ // console. That works because ask() reads in a child process, so this one
157
+ // has never opened stdin — see the note on ask() in lib/ui.mjs.
70
158
  const scaffold = spawnSync(command, { stdio: "inherit", shell: true });
71
159
  if (scaffold.status !== 0) fail("Scaffolding failed or was cancelled — nothing to wire up.");
72
160
  if (!existsSync(join(process.cwd(), name, "package.json"))) {
@@ -78,7 +166,40 @@ export async function run(argv) {
78
166
  info("wiring Astralis into it…");
79
167
  process.chdir(name);
80
168
  const init = await import("./init.mjs");
81
- await init.run([]);
169
+ await init.run([], { nested: true });
170
+
171
+ /*
172
+ * Replace the scaffolder's demo page with one built from Astralis.
173
+ *
174
+ * Only here, never in `init` — init runs on projects that already exist,
175
+ * where overwriting someone's entry component would be vandalism. On a
176
+ * directory the scaffolder created seconds ago there is nothing to lose,
177
+ * and it turns "did init work?" from a package.json inspection into
178
+ * something visible on first `dev`.
179
+ */
180
+ if (starter) {
181
+ const entry = findEntryFile(process.cwd(), framework);
182
+ if (entry) {
183
+ const shown = (p) => relative(process.cwd(), p).split("\\").join("/");
184
+
185
+ const { path, source } = starterFile(framework, entry.path);
186
+ writeFileSync(path, source);
187
+
188
+ // The template's demo CSS centres and re-colours everything it wraps, so
189
+ // it has to go with the demo it was written for. Reported as one line:
190
+ // clearing the scaffolder's own leftovers is part of writing the screen,
191
+ // not three separate things the reader has to follow.
192
+ const cleanup = starterCleanup(framework, entry.path);
193
+ for (const file of cleanup.rewrite) {
194
+ if (existsSync(file.path)) writeFileSync(file.path, file.source);
195
+ }
196
+ for (const orphan of cleanup.remove) {
197
+ if (existsSync(orphan)) rmSync(orphan);
198
+ }
199
+
200
+ ok(`welcome screen written ${dim(`(${shown(path)})`)}`);
201
+ }
202
+ }
82
203
 
83
204
  console.log(`\n${bold("Next steps:")}\n ${cyan(`cd ${name}`)}\n ${cyan(`${pm} run dev`)}`);
84
205
  }
@@ -21,7 +21,12 @@ const MANUAL_SNIPPET = `
21
21
  3. Wrap your app: <AstralisProvider defaultTheme="system">…</AstralisProvider>
22
22
  Full guide: ${cyan("https://astralis-zeta.vercel.app/docs/installation")}`;
23
23
 
24
- export async function run(argv) {
24
+ /**
25
+ * `nested` is set when `create` calls this as its wiring step. It suppresses
26
+ * the sign-off, because create prints its own "Next steps" immediately after —
27
+ * two closing blocks in one run read as the command finishing twice.
28
+ */
29
+ export async function run(argv, { nested = false } = {}) {
25
30
  const { values } = parseArgs({
26
31
  args: argv,
27
32
  options: { "dry-run": { type: "boolean", default: false } },
@@ -34,20 +39,58 @@ export async function run(argv) {
34
39
 
35
40
  const framework = detectFramework(pkg);
36
41
  if (!framework) {
37
- warn("Couldn't detect Next.js or Vite in this project.");
42
+ // Be specific about which half is missing. A Vue + Vite app used to be
43
+ // told "couldn't detect Vite", which is untrue and points at the wrong
44
+ // problem — Vite is there, React is not.
45
+ const deps = { ...pkg.dependencies, ...pkg.devDependencies };
46
+ if (deps.vite) {
47
+ warn("This is a Vite project, but not a React one.");
48
+ console.log(
49
+ dim(" Astralis is a React library — react and react-dom are its peer dependencies."),
50
+ );
51
+ } else {
52
+ warn("Couldn't detect Next.js or a React + Vite project here.");
53
+ }
38
54
  console.log(MANUAL_SNIPPET);
39
55
  return;
40
56
  }
41
57
  const pm = detectPackageManager(cwd);
42
- info(`${bold(framework === "next" ? "Next.js" : "Vite")} project, ${bold(pm)}${dryRun ? dim(" (dry run — nothing will be written)") : ""}`);
58
+
59
+ /*
60
+ * Step output is buffered until we know whether anything actually changed.
61
+ * Re-running init on an already-wired project used to print a checklist of
62
+ * things it had not done, followed by a sign-off — reading like work when
63
+ * the honest answer is "nothing to do".
64
+ *
65
+ * The moment a real change happens we flush and switch to printing live, so
66
+ * a package-manager install still streams in order.
67
+ */
68
+ const steps = [];
69
+ let printing = false;
70
+ let changed = false;
71
+ const step = (fn) => (printing ? fn() : steps.push(fn));
72
+ const flush = () => {
73
+ for (const fn of steps) fn();
74
+ steps.length = 0;
75
+ printing = true;
76
+ };
77
+
78
+ step(() =>
79
+ info(
80
+ `${bold(framework === "next" ? "Next.js" : "Vite")} project, ${bold(pm)}${dryRun ? dim(" (dry run — nothing will be written)") : ""}`,
81
+ ),
82
+ );
43
83
 
44
84
  // 1. Dependency
45
85
  const hasDep = Boolean(pkg.dependencies?.["astralis-ui"] ?? pkg.devDependencies?.["astralis-ui"]);
46
86
  if (hasDep) {
47
- ok("astralis-ui already in dependencies");
87
+ step(() => ok("astralis-ui already in dependencies"));
48
88
  } else if (dryRun) {
49
- info(`would run: ${pm} add astralis-ui`);
89
+ changed = true;
90
+ step(() => info(`would run: ${pm} add astralis-ui`));
50
91
  } else {
92
+ changed = true;
93
+ flush();
51
94
  info(`installing astralis-ui with ${pm}…`);
52
95
  // One command string: pm binaries are .cmd shims on Windows (need a shell),
53
96
  // and shell+args-array triggers Node's unescaped-args deprecation.
@@ -69,15 +112,17 @@ export async function run(argv) {
69
112
  const notes = [];
70
113
  const apply = (result, label) => {
71
114
  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`);
115
+ if (result.changed) {
116
+ changed = true;
117
+ step(() => ok(`${label} ${dim(`(${entry.relative})`)}`));
118
+ } else if (result.note) notes.push(`${label}: ${result.note}`);
119
+ else step(() => ok(`${label} — already present`));
75
120
  };
76
121
 
77
122
  apply(addImports(source, [PROVIDER_IMPORT, STYLES_IMPORT]), "imports added");
78
123
 
79
124
  if (source.includes("<AstralisProvider")) {
80
- ok("AstralisProvider already wraps this file");
125
+ step(() => ok("AstralisProvider already wraps this file"));
81
126
  } else if (framework === "next") {
82
127
  apply(
83
128
  wrapJsx(source, "{children}", '<AstralisProvider defaultTheme="system">', "</AstralisProvider>"),
@@ -98,12 +143,27 @@ export async function run(argv) {
98
143
 
99
144
  // 3. Write
100
145
  if (source !== original) {
101
- if (dryRun) info(`would update ${entry.relative}`);
146
+ if (dryRun) step(() => info(`would update ${entry.relative}`));
102
147
  else writeFileSync(entry.path, source);
103
148
  }
104
149
 
150
+ /*
151
+ * Nothing to do, and nothing that needed the reader's attention: say so in
152
+ * one line instead of listing the steps that were already satisfied.
153
+ */
154
+ if (!changed && notes.length === 0) {
155
+ ok("astralis-ui is already present in this project");
156
+ if (nested) return;
157
+ console.log(`Nothing to scaffold.\nDocs: ${cyan("https://astralis-zeta.vercel.app/docs")}`);
158
+ return;
159
+ }
160
+
161
+ flush();
162
+
105
163
  for (const note of notes) warn(note);
106
164
  if (notes.length > 0) console.log(MANUAL_SNIPPET);
107
165
 
166
+ if (nested) return;
167
+
108
168
  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")}`);
109
169
  }
@@ -1,7 +1,10 @@
1
1
  import { parseArgs } from "node:util";
2
- import { existsSync, writeFileSync } from "node:fs";
2
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
3
+ import { dirname, join, relative } from "node:path";
3
4
  import { themeCss, validateSeed, isEmptySeed } from "astralis-ui/serialize";
4
- import { ok, fail, cyan, dim } from "../lib/ui.mjs";
5
+ import { ok, warn, fail, cyan, dim } from "../lib/ui.mjs";
6
+ import { readPackageJson, detectFramework, findEntryFile } from "../lib/detect.mjs";
7
+ import { addImports } from "../lib/edits.mjs";
5
8
 
6
9
  /**
7
10
  * Renders a theme seed as a stylesheet — the static equivalent of
@@ -58,8 +61,10 @@ const USAGE = `Usage: astralis theme [options]
58
61
  --motion <n> duration multiplier (0 disables transitions)
59
62
 
60
63
  Output
61
- --out <file> default: astralis-theme.css
64
+ --out <file> default: src/astralis-theme.css, or
65
+ astralis-theme.css in a project with no src/
62
66
  --force overwrite an existing file
67
+ --no-import write the file but don't touch the entry point
63
68
 
64
69
  A bare hex is shorthand for --brand: astralis theme "#8b5cf6"`;
65
70
 
@@ -72,7 +77,10 @@ export async function run(argv) {
72
77
  ...Object.fromEntries(
73
78
  [...Object.keys(STRING_FLAGS), ...Object.keys(NUMBER_FLAGS)].map((f) => [f, { type: "string" }]),
74
79
  ),
75
- out: { type: "string", default: "astralis-theme.css" },
80
+ // No default: the destination depends on whether the project has a
81
+ // src/, resolved below so `--out` can still override it.
82
+ out: { type: "string" },
83
+ "no-import": { type: "boolean", default: false },
76
84
  force: { type: "boolean", default: false },
77
85
  help: { type: "boolean", default: false },
78
86
  },
@@ -112,19 +120,56 @@ export async function run(argv) {
112
120
  fail(`Invalid theme options:\n${issues.map((i) => ` ${i.field}: ${i.message}`).join("\n")}`);
113
121
  }
114
122
 
115
- if (existsSync(values.out) && !values.force) {
116
- fail(`${values.out} already exists — pass --force to overwrite.`);
117
- }
123
+ const cwd = process.cwd();
124
+ const posix = (p) => p.split("\\").join("/");
125
+
126
+ /*
127
+ * Default next to the code that imports it, not at the project root — the
128
+ * same rule `astralis add` follows for blocks. A stylesheet dropped beside
129
+ * package.json is not where anyone looks for one.
130
+ */
131
+ const out = values.out ?? (existsSync(join(cwd, "src")) ? join("src", "astralis-theme.css") : "astralis-theme.css");
118
132
 
119
- writeFileSync(values.out, themeCss(seed));
120
- ok(`wrote ${cyan(values.out)}`);
133
+ if (existsSync(out) && !values.force) {
134
+ fail(`${posix(out)} already exists — pass --force to overwrite.`);
135
+ }
121
136
 
137
+ writeFileSync(out, themeCss(seed));
138
+ ok(`wrote ${cyan(posix(out))}`);
139
+
140
+ /*
141
+ * Import it too. A generated stylesheet nobody imports changes nothing, and
142
+ * the failure is invisible: the file exists, the command reported success,
143
+ * and the brand colour is simply never applied.
144
+ *
145
+ * It goes after the last existing import, which puts it after
146
+ * `astralis-ui/styles.css` — the order the override depends on.
147
+ */
122
148
  const usesFont = seed.fontHeading || seed.fontBody || seed.fontMono;
123
- console.log(
124
- `\nImport it after the library stylesheet:\n` +
149
+ const pkg = readPackageJson(cwd);
150
+ const entry = pkg ? findEntryFile(cwd, detectFramework(pkg)) : null;
151
+
152
+ if (!values["no-import"] && entry) {
153
+ const specifier = posix(relative(dirname(entry.path), join(cwd, out)));
154
+ const line = `import "${specifier.startsWith(".") ? specifier : `./${specifier}`}";`;
155
+ const result = addImports(readFileSync(entry.path, "utf8"), [line]);
156
+
157
+ if (result.changed) {
158
+ writeFileSync(entry.path, result.source);
159
+ ok(`imported in ${cyan(entry.relative)} ${dim("(after the library stylesheet)")}`);
160
+ } else {
161
+ ok(`already imported in ${cyan(entry.relative)}`);
162
+ }
163
+ } else if (!values["no-import"]) {
164
+ warn("No Next.js or Vite entry point found — import it yourself:");
165
+ console.log(
125
166
  ` ${cyan('import "astralis-ui/styles.css";')}\n` +
126
- ` ${cyan(`import "./${values.out}";`)}\n` +
127
- (usesFont ? `${dim("Custom fonts must be loaded by your app (next/font or a <link>).")}\n` : "") +
128
- `${dim("Runtime alternative: <AstralisProvider tokens={…}> — same math.")}`,
129
- );
167
+ ` ${cyan(`import "./${posix(out)}";`)} ${dim("← must come second")}`,
168
+ );
169
+ }
170
+
171
+ if (usesFont) {
172
+ console.log(dim("\nCustom fonts must be loaded by your app (next/font or a <link>)."));
173
+ }
174
+ console.log(dim("Runtime alternative: <AstralisProvider tokens={…}> — same math."));
130
175
  }
package/src/index.mjs CHANGED
@@ -2,11 +2,12 @@
2
2
  import { readFileSync } from "node:fs";
3
3
  import { fileURLToPath } from "node:url";
4
4
  import { join, dirname } from "node:path";
5
- import { bold, cyan, dim, fail, closePrompts } from "./lib/ui.mjs";
5
+ import { bold, cyan, dim, fail, CliExit } from "./lib/ui.mjs";
6
6
 
7
7
  const COMMANDS = {
8
8
  create: () => import("./commands/create.mjs"),
9
9
  init: () => import("./commands/init.mjs"),
10
+ add: () => import("./commands/add.mjs"),
10
11
  theme: () => import("./commands/theme.mjs"),
11
12
  "connect-mcp": () => import("./commands/connect-mcp.mjs"),
12
13
  };
@@ -18,11 +19,18 @@ ${bold("Usage")}
18
19
  astralis <command> [options]
19
20
 
20
21
  ${bold("Commands")}
21
- ${cyan("create <name>")} scaffold a new project (official create-next-app /
22
- create-vite prompts) and wire Astralis into it
23
- ${dim("--framework next|vite · extra args pass to the scaffolder")}
24
- ${cyan("init")} wire astralis-ui into this project (Next.js or Vite)
22
+ ${cyan("create <name>")} scaffold a new project with the official scaffolder
23
+ (create-next-app / create-vite) and wire Astralis into it
24
+ ${dim("--framework next|vite Next.js, or React via Vite")}
25
+ ${dim("--no-starter keep the scaffolder's demo page")}
26
+ ${dim("extra args pass straight to the scaffolder")}
27
+ ${cyan("init")} wire astralis-ui into an existing React project
28
+ ${dim("Next.js, or React + Vite")}
25
29
  ${dim("--dry-run show the changes without writing")}
30
+ ${cyan("add <block>...")} copy a block's source into this project
31
+ ${dim("--list every available block, by category")}
32
+ ${dim("--dir <path> where to write (default [src/]components/blocks)")}
33
+ ${dim("--overwrite · --dry-run · --registry <url>")}
26
34
  ${cyan("theme")} generate a static theme stylesheet from a seed
27
35
  ${dim("--brand/--gray <hex> · --font-heading/-body/-mono <stack>")}
28
36
  ${dim("--radius/--spacing/--font-scale/--motion <n>")}
@@ -38,18 +46,20 @@ ${bold("Docs")} ${cyan("https://astralis-zeta.vercel.app/docs")}
38
46
 
39
47
  const [command, ...rest] = process.argv.slice(2);
40
48
 
41
- if (!command || command === "--help" || command === "-h" || command === "help") {
42
- console.log(HELP);
43
- } else if (command === "--version" || command === "-v") {
44
- const pkg = JSON.parse(readFileSync(join(dirname(fileURLToPath(import.meta.url)), "..", "package.json"), "utf8"));
45
- console.log(pkg.version);
46
- } else if (COMMANDS[command]) {
47
- const { run } = await COMMANDS[command]();
48
- try {
49
+ try {
50
+ if (!command || command === "--help" || command === "-h" || command === "help") {
51
+ console.log(HELP);
52
+ } else if (command === "--version" || command === "-v") {
53
+ const pkg = JSON.parse(readFileSync(join(dirname(fileURLToPath(import.meta.url)), "..", "package.json"), "utf8"));
54
+ console.log(pkg.version);
55
+ } else if (COMMANDS[command]) {
56
+ const { run } = await COMMANDS[command]();
49
57
  await run(rest);
50
- } finally {
51
- closePrompts();
58
+ } else {
59
+ fail(`Unknown command "${command}" — run ${cyan("astralis --help")}.`);
52
60
  }
53
- } else {
54
- fail(`Unknown command "${command}" — run ${cyan("astralis --help")}.`);
61
+ } catch (error) {
62
+ // fail() has already printed and set the exit code; anything else is a bug
63
+ // and deserves its stack.
64
+ if (!(error instanceof CliExit)) throw error;
55
65
  }
@@ -0,0 +1,49 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+
4
+ /**
5
+ * Where a block's files get written.
6
+ *
7
+ * `astralis init` writes no config file — the whole point of the precompiled
8
+ * stylesheet is that a project needs no Astralis-shaped setup — so this is
9
+ * convention first, with two escape hatches for people whose layout differs:
10
+ *
11
+ * 1. --dir on the command line, for a one-off
12
+ * 2. "blocksDir" in astralis.json, for a project that always differs
13
+ * 3. otherwise src/components/blocks, or components/blocks without a src/
14
+ *
15
+ * Never the project root: a block is a component, and dropping .tsx files
16
+ * beside package.json would be nobody's idea of where they live.
17
+ */
18
+
19
+ export const DEFAULT_SUBPATH = join("components", "blocks");
20
+
21
+ /** `astralis.json`, if the project has one. Malformed is treated as absent. */
22
+ export function readConfig(cwd) {
23
+ const path = join(cwd, "astralis.json");
24
+ if (!existsSync(path)) return null;
25
+ try {
26
+ return JSON.parse(readFileSync(path, "utf8"));
27
+ } catch {
28
+ return null;
29
+ }
30
+ }
31
+
32
+ /**
33
+ * Resolve the destination directory, relative to cwd.
34
+ * Returns { relative, source } — source names which rule won, for the log line.
35
+ */
36
+ export function resolveBlocksDir(cwd, flagDir) {
37
+ if (flagDir) return { relative: flagDir, source: "--dir" };
38
+
39
+ const configured = readConfig(cwd)?.blocksDir;
40
+ if (typeof configured === "string" && configured.trim()) {
41
+ return { relative: configured.trim(), source: "astralis.json" };
42
+ }
43
+
44
+ const hasSrc = existsSync(join(cwd, "src"));
45
+ return {
46
+ relative: hasSrc ? join("src", DEFAULT_SUBPATH) : DEFAULT_SUBPATH,
47
+ source: "default",
48
+ };
49
+ }
@@ -0,0 +1,51 @@
1
+ /*
2
+ * Reads exactly one line of input, writes it to stdout, exits.
3
+ *
4
+ * Two constraints shape this, and both were found the hard way.
5
+ *
6
+ * 1. It runs as a short-lived CHILD of the CLI, so the CLI process itself
7
+ * never reads stdin. On Windows libuv services a TTY on a dedicated thread
8
+ * blocked in ReadConsoleInputW, and once started that thread cannot be
9
+ * stopped — not by readline.close(), not by pause(), not by dropping
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.
15
+ *
16
+ * 2. It reads BYTE BY BYTE rather than with readline. readline buffers ahead,
17
+ * which is harmless on a terminal but swallows the whole pipe when input
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.
20
+ *
21
+ * Line editing still works: the terminal driver (or Windows console) handles
22
+ * backspace in cooked mode and only releases the finished line to us.
23
+ *
24
+ * Prompt text goes to stderr, which is inherited so the user sees it; the
25
+ * answer goes to stdout, which the parent pipes.
26
+ */
27
+ import { readSync } from "node:fs";
28
+
29
+ const prompt = process.argv[2] ?? "";
30
+ if (prompt) process.stderr.write(prompt);
31
+
32
+ const byte = Buffer.alloc(1);
33
+ const bytes = [];
34
+
35
+ while (true) {
36
+ let read;
37
+ try {
38
+ read = readSync(0, byte, 0, 1, null);
39
+ } catch (error) {
40
+ // Non-blocking stdin yields EAGAIN before data arrives; EOF ends the line.
41
+ if (error.code === "EAGAIN") continue;
42
+ if (error.code === "EOF") break;
43
+ throw error;
44
+ }
45
+ if (read === 0) break; // EOF
46
+ if (byte[0] === 0x0a) break; // \n — the line is done
47
+ if (byte[0] === 0x0d) continue; // \r from CRLF
48
+ bytes.push(byte[0]);
49
+ }
50
+
51
+ process.stdout.write(Buffer.from(bytes).toString("utf8"));
@@ -0,0 +1,56 @@
1
+ import { fail } from "./ui.mjs";
2
+
3
+ /**
4
+ * The block registry lives on the docs site as static JSON — see
5
+ * astralis-docs/scripts/gen-block-registry.mjs. Fetching it rather than
6
+ * bundling it into this package keeps the two on separate clocks: adding a
7
+ * block is a docs deploy, not a CLI release.
8
+ *
9
+ * --registry (or ASTRALIS_REGISTRY) points at a different host, which is how
10
+ * the registry gets tested against a local docs server before it ships.
11
+ */
12
+
13
+ const DEFAULT_REGISTRY = "https://astralis-zeta.vercel.app/r";
14
+
15
+ export function registryBase(flag) {
16
+ const base = flag ?? process.env.ASTRALIS_REGISTRY ?? DEFAULT_REGISTRY;
17
+ return base.replace(/\/+$/, "");
18
+ }
19
+
20
+ async function getJson(url) {
21
+ let response;
22
+ try {
23
+ response = await fetch(url);
24
+ } catch (error) {
25
+ fail(`Could not reach the block registry at ${url}\n ${error.message}`);
26
+ }
27
+ // Cancel the body on any path that will not read it. An undici response left
28
+ // unconsumed keeps its socket handle open, and a process.exit() while that
29
+ // handle is live trips a libuv assertion on Windows — the CLI printed a
30
+ // correct error and then crashed underneath it.
31
+ if (response.status === 404) {
32
+ await response.body?.cancel();
33
+ return null;
34
+ }
35
+ if (!response.ok) {
36
+ await response.body?.cancel();
37
+ fail(`Registry responded ${response.status} for ${url}`);
38
+ }
39
+ try {
40
+ return await response.json();
41
+ } catch {
42
+ fail(`Registry returned invalid JSON for ${url}`);
43
+ }
44
+ }
45
+
46
+ /** The catalogue: every block, without source. */
47
+ export async function fetchIndex(base) {
48
+ const data = await getJson(`${base}/index.json`);
49
+ if (!data) fail(`No block catalogue at ${base}/index.json`);
50
+ return data;
51
+ }
52
+
53
+ /** One block, with the full text of its files. Null when the id is unknown. */
54
+ export function fetchBlock(base, id) {
55
+ return getJson(`${base}/${id}.json`);
56
+ }
@@ -0,0 +1,227 @@
1
+ import { join, dirname } from "node:path";
2
+
3
+ /**
4
+ * The welcome screen `astralis create` leaves behind.
5
+ *
6
+ * Scope is deliberately one file. The scaffolder owns the project — router,
7
+ * config, folder layout, tooling — and we replace only what it put on screen.
8
+ * The moment this starts making structural decisions, Astralis owns a template,
9
+ * and templates rot behind the framework they wrap. That is the cost the
10
+ * wrap-the-official-scaffolder design exists to avoid.
11
+ *
12
+ * It earns its place by being an assertion rather than decoration: if the
13
+ * provider, the stylesheet and the token pipeline are all wired correctly you
14
+ * see this render. If `init` half-worked, it is visible immediately instead of
15
+ * hiding until the first component is used.
16
+ *
17
+ * No hooks, so it stays a Server Component under Next without a "use client"
18
+ * banner — ThemeToggle carries its own.
19
+ */
20
+
21
+ /**
22
+ * Every astralis-ui export the starter uses. The gate in test/ asserts these
23
+ * are real exports, and that this list matches what the source actually imports.
24
+ *
25
+ * Flat parts (Card, CardBody) rather than Card.Body: under Next this file
26
+ * is `app/page.tsx`, a Server Component, and namespace access on a
27
+ * client-reference stub is undefined across the RSC boundary. Same rule the
28
+ * block authoring gate enforces, for the same reason.
29
+ */
30
+ export const STARTER_IMPORTS = [
31
+ "Badge",
32
+ "Button",
33
+ "Card",
34
+ "CardBody",
35
+ "Code",
36
+ "Container",
37
+ "Flex",
38
+ "Heading",
39
+ "Stack",
40
+ "Text",
41
+ "ThemeToggle",
42
+ ];
43
+
44
+ function starterSource() {
45
+ return `import {
46
+ ${STARTER_IMPORTS.join(",\n ")},
47
+ } from "astralis-ui";
48
+
49
+ /**
50
+ * Astralis is wired up — this screen is rendering through the provider, the
51
+ * precompiled stylesheet and the token scales.
52
+ *
53
+ * It is an ordinary file in your project. Edit it, or delete it and start over.
54
+ */
55
+ /**
56
+ * The Astralis mark — an eight-point compass rose. Painted with the brand
57
+ * token rather than fixed hex, so it re-colours with the rest of the theme.
58
+ */
59
+ const ROTATIONS = [0, 90, 180, 270];
60
+
61
+ function AstralisMark() {
62
+ return (
63
+ <svg viewBox="0 0 32 32" width="28" height="28" aria-hidden="true">
64
+ {ROTATIONS.map((deg) => (
65
+ <g key={\`d\${deg}\`} transform={\`rotate(\${deg} 16 16)\`}>
66
+ <path d="M22.8 9.2 L17.7 11.1 L16 16 Z" fill="var(--astralis-color-brand-500)" />
67
+ <path d="M22.8 9.2 L20.9 14.3 L16 16 Z" fill="var(--astralis-color-brand-300)" />
68
+ </g>
69
+ ))}
70
+ {ROTATIONS.map((deg) => (
71
+ <g key={\`c\${deg}\`} transform={\`rotate(\${deg} 16 16)\`}>
72
+ <path d="M16 0.8 L14.15 12.4 L16 16 Z" fill="var(--astralis-color-brand-200)" />
73
+ <path d="M16 0.8 L17.85 12.4 L16 16 Z" fill="var(--astralis-color-brand-500)" />
74
+ </g>
75
+ ))}
76
+ </svg>
77
+ );
78
+ }
79
+
80
+ export default function Welcome() {
81
+ return (
82
+ <Container maxW="4xl" px={{ base: "6", lg: "8" }} py={{ base: "16", lg: "24" }}>
83
+ <Stack gap="10" alignItems="stretch">
84
+ <Flex justifyContent="between" alignItems="center" gap="4">
85
+ <Flex alignItems="center" gap="3">
86
+ <AstralisMark />
87
+ <Badge variant="subtle" colorScheme="brand" size="xs">
88
+ Astralis UI
89
+ </Badge>
90
+ </Flex>
91
+ <ThemeToggle variant="text" colorScheme="gray" size="sm" aria-label="Toggle theme" />
92
+ </Flex>
93
+
94
+ <Stack gap="4" alignItems="start">
95
+ <Heading as="h1" size={{ base: "2xl", lg: "3xl" }} weight="semibold" letterSpacing="tight">
96
+ You&apos;re set up.
97
+ </Heading>
98
+ <Text size="lg" color="muted" lineHeight="relaxed">
99
+ Everything here is themed through one accent channel. Change{" "}
100
+ <Code>colorScheme</Code> on any component and the rest follows — no
101
+ rebuild, no Tailwind config in your project.
102
+ </Text>
103
+ </Stack>
104
+
105
+ {/* as="a" — Button is polymorphic, so these are real links rather than
106
+ buttons that look clickable and do nothing. */}
107
+ <Flex gap="3" wrap="wrap">
108
+ <Button
109
+ as="a"
110
+ href="https://astralis-zeta.vercel.app/docs/quick-start"
111
+ target="_blank"
112
+ rel="noreferrer"
113
+ size="lg"
114
+ colorScheme="brand"
115
+ >
116
+ Get started
117
+ </Button>
118
+ <Button
119
+ as="a"
120
+ href="https://astralis-zeta.vercel.app/docs"
121
+ target="_blank"
122
+ rel="noreferrer"
123
+ size="lg"
124
+ variant="outline"
125
+ colorScheme="gray"
126
+ >
127
+ Read the docs
128
+ </Button>
129
+ </Flex>
130
+
131
+ {/* No width prop on Card by design — the Stack above stretches it. */}
132
+ <Card variant="outline" size="lg">
133
+ <CardBody>
134
+ <Stack gap="3" alignItems="start">
135
+ <Heading as="h2" size="md" weight="semibold">
136
+ Try it
137
+ </Heading>
138
+ <Text color="muted" lineHeight="relaxed">
139
+ Drop in a prebuilt section with <Code>astralis add hero-01</Code>,
140
+ or import anything from <Code>astralis-ui</Code> and compose your
141
+ own.
142
+ </Text>
143
+ <Flex gap="2" wrap="wrap">
144
+ <Badge variant="subtle" colorScheme="green" size="xs">
145
+ green
146
+ </Badge>
147
+ <Badge variant="subtle" colorScheme="blue" size="xs">
148
+ blue
149
+ </Badge>
150
+ <Badge variant="subtle" colorScheme="purple" size="xs">
151
+ purple
152
+ </Badge>
153
+ <Badge variant="subtle" colorScheme="orange" size="xs">
154
+ orange
155
+ </Badge>
156
+ </Flex>
157
+ </Stack>
158
+ </CardBody>
159
+ </Card>
160
+ </Stack>
161
+ </Container>
162
+ );
163
+ }
164
+ `;
165
+ }
166
+
167
+ /**
168
+ * Where the welcome screen goes, derived from the entry file `init` already
169
+ * located — so this never has to guess at the project's layout a second time.
170
+ *
171
+ * Next renders `page.tsx` beside the root layout; Vite renders `App.tsx`
172
+ * beside `main.tsx`. The extension follows the entry, so a JavaScript project
173
+ * gets .jsx (the source carries no type annotations either way).
174
+ */
175
+ export function starterTarget(framework, entryPath) {
176
+ const dir = dirname(entryPath);
177
+ const ext = entryPath.endsWith("x") ? (entryPath.endsWith(".tsx") ? "tsx" : "jsx") : "tsx";
178
+ return join(dir, framework === "next" ? `page.${ext}` : `App.${ext}`);
179
+ }
180
+
181
+ export function starterFile(framework, entryPath) {
182
+ return { path: starterTarget(framework, entryPath), source: starterSource() };
183
+ }
184
+
185
+ /**
186
+ * The stylesheet the Vite template ships to style its demo, and which fights
187
+ * anything you put in its place:
188
+ *
189
+ * #root { text-align: center; display: flex; max-width; margin: 0 auto }
190
+ * :root { font; color; background; color-scheme: light dark }
191
+ *
192
+ * Left in place it centres text that was authored left-aligned, overrides the
193
+ * type scale, and paints the page from the OS colour scheme rather than the
194
+ * provider's — so toggling to light left dark bars either side of the content.
195
+ *
196
+ * Replaced rather than deleted: main.tsx imports it, and the import is the
197
+ * natural place for a consumer to put their own global CSS.
198
+ */
199
+ const VITE_RESET = `/*
200
+ * Your global stylesheet.
201
+ *
202
+ * Astralis ships its own reset inside astralis-ui/styles.css, scoped so it
203
+ * cannot leak into the rest of your app. The Vite template's demo styles were
204
+ * removed from here because they centred and re-coloured everything.
205
+ */
206
+ html,
207
+ body,
208
+ #root {
209
+ margin: 0;
210
+ min-height: 100%;
211
+ }
212
+ `;
213
+
214
+ /**
215
+ * Files the scaffolder wrote purely to dress its demo, which stop being true
216
+ * the moment the demo is replaced. Vite only — create-next-app's globals.css
217
+ * may hold the Tailwind directives the user asked for, so it is never touched.
218
+ */
219
+ export function starterCleanup(framework, entryPath) {
220
+ if (framework !== "vite") return { rewrite: [], remove: [] };
221
+ const dir = dirname(entryPath);
222
+ return {
223
+ rewrite: [{ path: join(dir, "index.css"), source: VITE_RESET }],
224
+ // Styled the old App.tsx, which no longer exists to import it.
225
+ remove: [join(dir, "App.css")],
226
+ };
227
+ }
package/src/lib/ui.mjs CHANGED
@@ -1,4 +1,5 @@
1
- import readline from "node:readline/promises";
1
+ import { spawnSync } from "node:child_process";
2
+ import { fileURLToPath } from "node:url";
2
3
 
3
4
  /**
4
5
  * Terminal output helpers — raw ANSI, no dependencies. Colors switch off for
@@ -19,44 +20,48 @@ export const ok = (message) => console.log(`${green("✓")} ${message}`);
19
20
  export const warn = (message) => console.log(`${yellow("!")} ${message}`);
20
21
  export const info = (message) => console.log(`${cyan("→")} ${message}`);
21
22
 
22
- /** Print the error and exit non-zero — the CLI's only failure path. */
23
+ /** Thrown by fail() once the message is printed — index.mjs stops quietly on it. */
24
+ export class CliExit extends Error {}
25
+
26
+ /**
27
+ * Print the error and stop — the CLI's only failure path.
28
+ *
29
+ * Sets an exit code and unwinds rather than calling process.exit(): on Windows,
30
+ * process.exit() after any fetch() trips a libuv assertion
31
+ * (`!(handle->flags & UV_HANDLE_CLOSING)`) and reports exit 127 instead of 1.
32
+ * Verified in isolation — fetch alone is clean, exit alone is clean, only the
33
+ * pair crashes. Unwinding lets the event loop drain, so finally blocks run.
34
+ */
23
35
  export function fail(message) {
24
36
  console.error(`${red("✗")} ${message}`);
25
- process.exit(1);
37
+ process.exitCode = 1;
38
+ throw new CliExit(message);
26
39
  }
27
40
 
28
- /*
29
- * One shared readline for the whole process, draining lines through a queue.
30
- * readline reads ahead, so with piped input it emits the next line's `line`
31
- * event in the gap between one prompt resolving and the next registering its
32
- * listener (e.g. select → confirm) — a per-question `rl.question` loses it. A
33
- * standing `line` listener queues those reads instead. Callers run
34
- * closePrompts() when done so the open stream stops keeping the process alive.
35
- */
36
- let sharedRl = null;
37
- let lineQueue = [];
38
- let lineWaiter = null;
39
-
40
- function ask(promptText) {
41
- if (!sharedRl) {
42
- sharedRl = readline.createInterface({ input: process.stdin, output: process.stdout });
43
- sharedRl.on("line", (line) => {
44
- if (lineWaiter) { const resolve = lineWaiter; lineWaiter = null; resolve(line); }
45
- else lineQueue.push(line);
46
- });
47
- // EOF (piped input exhausted): unblock a pending prompt with an empty answer.
48
- sharedRl.on("close", () => { if (lineWaiter) { const resolve = lineWaiter; lineWaiter = null; resolve(""); } });
49
- }
50
- process.stdout.write(promptText);
51
- if (lineQueue.length) return Promise.resolve(lineQueue.shift());
52
- return new Promise((resolve) => { lineWaiter = resolve; });
53
- }
41
+ const PROMPT_CHILD = fileURLToPath(new URL("./prompt-child.mjs", import.meta.url));
54
42
 
55
- export function closePrompts() {
56
- sharedRl?.close();
57
- sharedRl = null;
58
- lineQueue = [];
59
- lineWaiter = null;
43
+ /**
44
+ * Read one line from the user, in a child process that exits immediately.
45
+ *
46
+ * This CLI must never read its own stdin. On Windows libuv services a TTY on a
47
+ * dedicated thread blocked in ReadConsoleInputW, and once started that thread
48
+ * cannot be stopped — not by readline.close(), not by pause(), not by dropping
49
+ * listeners. A process that has read stdin even once keeps consuming console
50
+ * input records for the rest of its life, starving any interactive child it
51
+ * later spawns. `astralis create` asked which framework, then handed over to
52
+ * create-vite, whose arrow-key menu drew perfectly and never received a
53
+ * keystroke; Ctrl+C did not reach it either.
54
+ *
55
+ * Isolated in a child, the read thread dies when the child exits and the
56
+ * terminal is clean for the scaffolder. Piped input still works: the child
57
+ * inherits the same stdin, and each prompt consumes one line.
58
+ */
59
+ export function ask(promptText) {
60
+ const result = spawnSync(process.execPath, [PROMPT_CHILD, promptText], {
61
+ stdio: ["inherit", "pipe", "inherit"],
62
+ encoding: "utf8",
63
+ });
64
+ return (result.stdout ?? "").trim();
60
65
  }
61
66
 
62
67
  /** y/N prompt; default no. */