@astralkit/cli 4.2.3 → 4.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.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,36 @@ All notable changes to the `@astralkit/cli` package.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [4.5.0] — 2026-07-04
9
+
10
+ ### Added
11
+ - **`append-unique-block` merge strategy.** Boosters can now append a marker-guarded text block to a file the user owns, creating it if absent. Built for Prisma model additions (`prisma/schema.prisma`) and `.env.example` variable appends. The block must contain the `idempotency_marker` (the CLI rejects the merge otherwise), so re-installs detect the previous append and skip. Shows the block (first 20 lines) and prompts before applying; files created fresh don't prompt.
12
+ - **Local registry mode for boosters (dev/QA).** Setting `ASTRALKIT_REGISTRY_DIR` to a local `registry-dev/` checkout serves `add <slug> --booster` and booster listings straight from disk — no API, no auth — so boosters can be QA'd before being pushed to the live registry. Components and workflows still require the API.
13
+
14
+ ### Compatibility
15
+ - Additive only. Boosters without `append-unique-block` merges behave exactly as before; older CLI versions report the new strategy as "unknown — skipped" and continue.
16
+
17
+ ## [4.4.0] — 2026-05-28
18
+
19
+ ### Added
20
+ - **Booster file-merge strategies.** Boosters can now declare a `merges` array in `booster.json` that the CLI applies after copying files. Two strategies are supported in this release:
21
+ - `wrap-jsx-children` — injects imports and wraps the children of a JSX anchor element (default `<body>`) with an opening/closing fragment. Used by Stack Auth boosters to wrap the user's existing `layout.tsx` with `<StackProvider><StackTheme>` without overwriting it. Shows the exact diff and prompts before applying (default Yes); skips silently if an idempotency marker is already present so re-installs are safe.
22
+ - `ensure-middleware` — creates `src/middleware.ts` if it doesn't exist; if it does and the booster's marker isn't found, prints explicit merge instructions instead of overwriting. Used by WorkOS boosters so they never blow away a user's existing middleware.
23
+ - Implementation lives in `src/lib/merges.js`; `addBooster` calls `applyMerges` after the dep-install prompt and before `post_install`.
24
+
25
+ ### Compatibility
26
+ - Additive only. Boosters without a `merges` array behave exactly as before. Older CLI versions ignore the `merges` field harmlessly — they fall back to whatever the booster's `post_install` documents.
27
+
28
+ ## [4.3.0] — 2026-04-22
29
+
30
+ ### Fixed
31
+ - **No more silent modification of `layout.tsx`.** When a component pulls in a side-effect import package (e.g. `@phosphor-icons/web` registering its font CSS), the CLI previously injected `import '@phosphor-icons/web/regular'` lines into `src/app/layout.tsx` without asking. Root layout is one of the most critical files in a Next.js app — silent edits broke trust with users installing into mature projects. The CLI now prints the exact diff and prompts with a default of **No**; declining leaves the component files in place and prints the imports so the user can add them by hand.
32
+ - **Phosphor icon conflict detection.** `@phosphor-icons/web` (CSS classes) and `@phosphor-icons/react` (React components) are separate packages that ship two different icon systems. Installing both in one codebase bloats the bundle and splits the icon convention. If the host project already has `@phosphor-icons/react` as a dependency, the CLI now warns and asks before installing `@phosphor-icons/web` — and if the user declines, skips both the dependency install and the layout-file edit.
33
+ - **End-of-install summary.** After any `astralkit add`, the CLI now prints a grouped summary of Created files, Modified files (with reason), Installed deps, Already-satisfied deps, and Skipped items — so users don't have to run `git diff` to see what changed.
34
+
35
+ ### Compatibility
36
+ - No breaking changes. All new behavior is additive (prompts where there was silent action) and defaults bias toward user consent.
37
+
8
38
  ## [4.2.3] — 2026-04-19
9
39
 
10
40
  ### Fixed
package/bin/index.js CHANGED
@@ -31,12 +31,12 @@ program
31
31
 
32
32
  // ─── init ────────────────────────────────────────────
33
33
  program
34
- .command('init')
35
- .description('Initialize AstralKit in your project')
34
+ .command('init [project-name]')
35
+ .description('Initialize AstralKit in your project, or scaffold a new project from the Starter Kit')
36
36
  .option('--api-key <key>', 'Your API key (from astralkit.com/account)')
37
37
  .option('--framework <framework>', 'Framework to use (auto-detected if omitted)')
38
38
  .option('--dir <directory>', 'Component output directory', 'src/components/ui')
39
- .action(initCommand);
39
+ .action((projectName, options) => initCommand({ ...options, projectName }));
40
40
 
41
41
  // ─── add ─────────────────────────────────────────────
42
42
  program
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astralkit/cli",
3
- "version": "4.2.3",
3
+ "version": "4.5.0",
4
4
  "description": "AstralKit CLI — Install and manage UI components in your project",
5
5
  "type": "module",
6
6
  "bin": {
@@ -2,7 +2,7 @@ import fs from 'fs';
2
2
  import path from 'path';
3
3
  import pc from 'picocolors';
4
4
  import * as p from '@clack/prompts';
5
- import { getComponent, getBooster, getWorkflow, listComponents, listBoosters, listWorkflows } from '../lib/api.js';
5
+ import { getComponent, getBooster, getWorkflow, listComponents, listBoosters, listWorkflows, LOCAL_REGISTRY_DIR } from '../lib/api.js';
6
6
  import {
7
7
  detectFramework,
8
8
  detectTypeScript,
@@ -13,6 +13,7 @@ import {
13
13
  import { validateSlug, validateFramework, isSafePath, writeFiles, isSafeInstallDir, filterSafePackages, sanitizeForTerminal } from '../lib/validators.js';
14
14
  import { detectPackageManager, getRunCommand, runInstall } from '../lib/pkg-manager.js';
15
15
  import { saveApiKey, getApiKey, getAuth } from '../lib/auth.js';
16
+ import { applyMerges } from '../lib/merges.js';
16
17
 
17
18
  const FRAMEWORK_LABELS = { nextjs: 'Next.js', react: 'React' };
18
19
 
@@ -25,7 +26,10 @@ export async function addCommand(nameOrSlug, options) {
25
26
  saveApiKey(options.apiKey);
26
27
  }
27
28
 
28
- if (!getApiKey()) {
29
+ // Local registry mode reads boosters from the developer's own disk — no
30
+ // account needed. Components/workflows still require auth (they hit the API).
31
+ const localBoosterInstall = LOCAL_REGISTRY_DIR && options.booster;
32
+ if (!getApiKey() && !localBoosterInstall) {
29
33
  const auth = getAuth();
30
34
  if (!auth.token) {
31
35
  p.log.warn('No API key found. Run ' + pc.cyan('astralkit init --api-key <key>') + ' first.');
@@ -143,6 +147,27 @@ function resolveExtension(framework) {
143
147
  return isTS ? '.tsx' : '.jsx';
144
148
  }
145
149
 
150
+ // Read the target project's package.json. Used to detect package conflicts
151
+ // (e.g. host already uses @phosphor-icons/react and we're about to add the
152
+ // separate @phosphor-icons/web). Returns null if the file is unreadable.
153
+ function readHostPackageJson() {
154
+ try {
155
+ const raw = fs.readFileSync(path.join(process.cwd(), 'package.json'), 'utf8');
156
+ return JSON.parse(raw);
157
+ } catch {
158
+ return null;
159
+ }
160
+ }
161
+
162
+ function hostHasDep(pkg, name) {
163
+ if (!pkg) return false;
164
+ return Boolean(
165
+ pkg.dependencies?.[name] ||
166
+ pkg.devDependencies?.[name] ||
167
+ pkg.optionalDependencies?.[name]
168
+ );
169
+ }
170
+
146
171
  async function addComponent(componentSlug, options) {
147
172
  if (!validateSlug(componentSlug)) process.exit(1);
148
173
  if (!fs.existsSync(path.join(process.cwd(), 'package.json'))) {
@@ -150,6 +175,17 @@ async function addComponent(componentSlug, options) {
150
175
  return;
151
176
  }
152
177
 
178
+ // Tracked across the full install so the end-of-run summary can tell the
179
+ // user exactly what changed in their project (created files, modified
180
+ // files, installed deps, anything skipped by user confirmation).
181
+ const installSummary = {
182
+ created: [], // relative file paths written
183
+ modified: [], // { path, note }
184
+ installed: [], // dep names
185
+ alreadySatisfied: [], // dep names
186
+ skipped: [], // { what, reason }
187
+ };
188
+
153
189
  const ora = (await import('ora')).default;
154
190
  const framework = resolveFramework(options);
155
191
  const ext = resolveExtension(framework);
@@ -202,16 +238,16 @@ async function addComponent(componentSlug, options) {
202
238
  for (const file of filesToWrite) {
203
239
  if (!isSafePath(dir, file.path)) {
204
240
  console.log(pc.red(` Skipping suspicious path: ${file.path}`));
241
+ installSummary.skipped.push({ what: file.path, reason: 'unsafe path' });
205
242
  continue;
206
243
  }
207
244
  const filePath = path.resolve(dir, file.path);
208
245
  fs.mkdirSync(path.dirname(filePath), { recursive: true });
209
246
  fs.writeFileSync(filePath, file.content);
247
+ installSummary.created.push(path.join(componentsDir, file.path).replace(/\\/g, '/'));
210
248
  }
211
249
 
212
250
  spinner.succeed(`Added ${pc.cyan(data.name || componentSlug)} (${FRAMEWORK_LABELS[framework]})`);
213
- console.log(pc.gray(` ${componentsDir}/`));
214
- for (const file of filesToWrite) console.log(pc.gray(` ${file.path}`));
215
251
 
216
252
  if (!isAstralkitInstalled()) {
217
253
  p.log.warn('Run ' + pc.cyan('astralkit init') + ' to set up design tokens.');
@@ -227,13 +263,42 @@ async function addComponent(componentSlug, options) {
227
263
 
228
264
  // Detect if component uses Phosphor Icons (CSS class-based icons)
229
265
  const componentCode = data.files?.map(f => f.content).join('') || '';
230
- const usesPhosphorCss = componentCode.includes('class="ph ') || componentCode.includes("class='ph ") || componentCode.includes('"ph ph-') || componentCode.includes("'ph ph-");
266
+ let usesPhosphorCss = componentCode.includes('class="ph ') || componentCode.includes("class='ph ") || componentCode.includes('"ph ph-') || componentCode.includes("'ph ph-");
267
+
268
+ // Phosphor conflict guard: @phosphor-icons/web and @phosphor-icons/react
269
+ // are SEPARATE packages (CSS classes vs React components). Installing both
270
+ // ships two icon systems in the same codebase — bundle bloat and a
271
+ // long-term consistency tax. If the host already uses the React package,
272
+ // warn loudly and let the user opt out of auto-installing web.
273
+ if (usesPhosphorCss) {
274
+ const hostPkg = readHostPackageJson();
275
+ if (hostHasDep(hostPkg, '@phosphor-icons/react')) {
276
+ p.log.warn(`This component uses ${pc.cyan('@phosphor-icons/web')} (CSS class-based icons).`);
277
+ p.log.warn(`Your project already uses ${pc.cyan('@phosphor-icons/react')} (React components) — a ${pc.bold('separate package')} from the same vendor.`);
278
+ p.log.warn(`Installing both ships two icon systems side by side.`);
279
+
280
+ const proceed = await p.confirm({
281
+ message: 'Install @phosphor-icons/web anyway?',
282
+ initialValue: false,
283
+ });
284
+ if (p.isCancel(proceed) || !proceed) {
285
+ p.log.info('Skipping @phosphor-icons/web and the layout.tsx import.');
286
+ p.log.info(pc.gray('Adapt the component\'s <i className="ph ph-*"> tags to @phosphor-icons/react React components.'));
287
+ usesPhosphorCss = false;
288
+ installSummary.skipped.push({
289
+ what: '@phosphor-icons/web',
290
+ reason: 'host project uses @phosphor-icons/react; user declined',
291
+ });
292
+ }
293
+ }
294
+ }
231
295
 
232
296
  if (data.dependencies?.length || usesPhosphorCss) {
233
297
  const pm = detectPackageManager();
234
298
  const rawDepList = (data.dependencies || []).filter(d => d !== 'astralkit' && d !== 'clsx' && d !== 'tailwind-merge');
235
299
 
236
300
  // Auto-add @phosphor-icons/web if component uses CSS-based Phosphor icons
301
+ // AND we didn't skip it above due to a @phosphor-icons/react conflict.
237
302
  if (usesPhosphorCss && !rawDepList.includes('@phosphor-icons/web')) {
238
303
  rawDepList.push('@phosphor-icons/web');
239
304
  }
@@ -247,21 +312,46 @@ async function addComponent(componentSlug, options) {
247
312
  }
248
313
 
249
314
  if (depList.length > 0) {
250
- // Always ask before running npm install — mirrors the booster flow.
251
- const install = await p.confirm({
252
- message: `Install dependencies? (${depList.join(', ')})`,
253
- initialValue: true,
254
- });
255
- if (!p.isCancel(install) && install) {
256
- const s = ora(`Installing ${depList.join(', ')}...`).start();
257
- const result = await runInstall(pm, process.cwd(), depList);
258
- if (result.success) s.succeed(`Installed ${depList.join(', ')}`);
259
- else { s.fail(sanitizeForTerminal(result.error || 'Install failed')); if (result.hint) console.log(pc.gray(` ${sanitizeForTerminal(result.hint)}`)); }
315
+ // Split into already-present vs to-install so the user sees both in
316
+ // the end-of-install summary.
317
+ const hostPkg = readHostPackageJson();
318
+ const toInstall = depList.filter(d => !hostHasDep(hostPkg, d));
319
+ const alreadyThere = depList.filter(d => hostHasDep(hostPkg, d));
320
+ for (const d of alreadyThere) installSummary.alreadySatisfied.push(d);
321
+
322
+ if (toInstall.length > 0) {
323
+ // Always ask before running npm install — mirrors the booster flow.
324
+ const install = await p.confirm({
325
+ message: `Install dependencies? (${toInstall.join(', ')})`,
326
+ initialValue: true,
327
+ });
328
+ if (!p.isCancel(install) && install) {
329
+ const s = ora(`Installing ${toInstall.join(', ')}...`).start();
330
+ const result = await runInstall(pm, process.cwd(), toInstall);
331
+ if (result.success) {
332
+ s.succeed(`Installed ${toInstall.join(', ')}`);
333
+ for (const d of toInstall) installSummary.installed.push(d);
334
+ } else {
335
+ s.fail(sanitizeForTerminal(result.error || 'Install failed'));
336
+ if (result.hint) console.log(pc.gray(` ${sanitizeForTerminal(result.hint)}`));
337
+ for (const d of toInstall) {
338
+ installSummary.skipped.push({ what: d, reason: 'install failed' });
339
+ }
340
+ }
341
+ } else {
342
+ for (const d of toInstall) {
343
+ installSummary.skipped.push({ what: d, reason: 'user declined install' });
344
+ }
345
+ }
260
346
  }
261
347
  }
262
348
 
263
349
  // Auto-add JS imports for icon/font packages in layout file
264
- // (CSS @import doesn't resolve node_modules exports in Next.js PostCSS)
350
+ // (CSS @import doesn't resolve node_modules exports in Next.js PostCSS).
351
+ // This modifies a user-owned file — one of the most critical in a
352
+ // Next.js app — so we now show the exact diff and prompt for consent
353
+ // with a default of NO. Silent modification of layout.tsx was a
354
+ // reported trust issue (CLI feedback 2026-04-22).
265
355
  const JS_DEPENDENCY_IMPORTS = {
266
356
  '@phosphor-icons/web': [
267
357
  "import '@phosphor-icons/web/regular'",
@@ -269,10 +359,15 @@ async function addComponent(componentSlug, options) {
269
359
  ],
270
360
  };
271
361
 
362
+ // Only consider packages we actually installed (or that were already
363
+ // present) — no point prompting about imports for a dep the user skipped.
364
+ const effectiveDeps = new Set([
365
+ ...installSummary.installed,
366
+ ...installSummary.alreadySatisfied,
367
+ ]);
272
368
  for (const [pkg, imports] of Object.entries(JS_DEPENDENCY_IMPORTS)) {
273
- if (!depList.includes(pkg)) continue;
369
+ if (!effectiveDeps.has(pkg)) continue;
274
370
 
275
- // Find the layout file
276
371
  const layoutCandidates = [
277
372
  'src/app/layout.tsx', 'src/app/layout.jsx', 'src/app/layout.js',
278
373
  'app/layout.tsx', 'app/layout.jsx', 'app/layout.js',
@@ -291,30 +386,88 @@ async function addComponent(componentSlug, options) {
291
386
 
292
387
  const layoutContent = fs.readFileSync(layoutFile.path, 'utf8');
293
388
  const missing = imports.filter(imp => !layoutContent.includes(imp));
294
- if (missing.length > 0) {
295
- // Add after the first import line
296
- const lines = layoutContent.split('\n');
297
- let lastImportIdx = -1;
298
- for (let i = 0; i < lines.length; i++) {
299
- if (lines[i].trim().startsWith('import ')) lastImportIdx = i;
300
- }
301
- if (lastImportIdx >= 0) {
302
- lines.splice(lastImportIdx + 1, 0, ...missing);
303
- } else {
304
- lines.unshift(...missing);
305
- }
306
- fs.writeFileSync(layoutFile.path, lines.join('\n'));
307
- p.log.success(`Added ${pc.cyan(pkg)} imports to ${pc.cyan(layoutFile.relative)}`);
389
+ if (missing.length === 0) continue;
390
+
391
+ // Show the exact diff we want to apply — never silently modify.
392
+ p.log.warn(`${pc.cyan(pkg)} needs these side-effect imports in your root layout:`);
393
+ console.log(pc.gray(` ${layoutFile.relative}`));
394
+ for (const imp of missing) console.log(` ${pc.green('+')} ${imp}`);
395
+
396
+ const proceed = await p.confirm({
397
+ message: `Add these imports to ${layoutFile.relative}?`,
398
+ initialValue: false,
399
+ });
400
+
401
+ if (p.isCancel(proceed) || !proceed) {
402
+ p.log.info(`Skipped ${layoutFile.relative} edit. Add these lines manually to enable icons:`);
403
+ for (const imp of missing) console.log(pc.gray(` ${imp}`));
404
+ installSummary.skipped.push({
405
+ what: `${layoutFile.relative} imports (${pkg})`,
406
+ reason: 'user declined',
407
+ });
408
+ continue;
409
+ }
410
+
411
+ const lines = layoutContent.split('\n');
412
+ let lastImportIdx = -1;
413
+ for (let i = 0; i < lines.length; i++) {
414
+ if (lines[i].trim().startsWith('import ')) lastImportIdx = i;
308
415
  }
416
+ if (lastImportIdx >= 0) {
417
+ lines.splice(lastImportIdx + 1, 0, ...missing);
418
+ } else {
419
+ lines.unshift(...missing);
420
+ }
421
+ fs.writeFileSync(layoutFile.path, lines.join('\n'));
422
+ installSummary.modified.push({
423
+ path: layoutFile.relative,
424
+ note: `+${missing.length} ${missing.length === 1 ? 'import' : 'imports'} (${pkg})`,
425
+ });
426
+ p.log.success(`Added ${pc.cyan(pkg)} imports to ${pc.cyan(layoutFile.relative)}`);
309
427
  }
310
428
  }
311
429
 
430
+ printInstallSummary(installSummary);
431
+
312
432
  } catch (err) {
313
433
  spinner.fail('Failed to add component.');
314
434
  handleAddError(err, componentSlug, framework);
315
435
  }
316
436
  }
317
437
 
438
+ // End-of-install summary. Prints what the CLI did to the user's project so
439
+ // they never have to run `git diff` just to find out what was touched. Split
440
+ // into Created / Modified / Installed / Skipped so each category is scannable.
441
+ function printInstallSummary(s) {
442
+ const hasAny =
443
+ s.created.length || s.modified.length || s.installed.length ||
444
+ s.alreadySatisfied.length || s.skipped.length;
445
+ if (!hasAny) return;
446
+
447
+ console.log('');
448
+ p.log.step(pc.bold('What changed in your project'));
449
+ if (s.created.length) {
450
+ console.log(pc.green(' Created:'));
451
+ for (const f of s.created) console.log(pc.gray(` ${f}`));
452
+ }
453
+ if (s.modified.length) {
454
+ console.log(pc.yellow(' Modified:'));
455
+ for (const m of s.modified) console.log(pc.gray(` ${m.path} ${pc.dim(m.note)}`));
456
+ }
457
+ if (s.installed.length) {
458
+ console.log(pc.cyan(' Installed:'));
459
+ for (const d of s.installed) console.log(pc.gray(` ${d}`));
460
+ }
461
+ if (s.alreadySatisfied.length) {
462
+ console.log(pc.gray(' Already satisfied:'));
463
+ for (const d of s.alreadySatisfied) console.log(pc.gray(` ${d}`));
464
+ }
465
+ if (s.skipped.length) {
466
+ console.log(pc.gray(' Skipped:'));
467
+ for (const k of s.skipped) console.log(pc.gray(` ${k.what} ${pc.dim(`(${k.reason})`)}`));
468
+ }
469
+ }
470
+
318
471
  async function addBooster(slug, options) {
319
472
  if (!validateSlug(slug, 'booster name')) process.exit(1);
320
473
 
@@ -386,7 +539,9 @@ async function addBooster(slug, options) {
386
539
  spinner.stop();
387
540
  console.log(pc.yellow('\nThese files already exist:'));
388
541
  conflicts.forEach(c => console.log(pc.gray(` ${c}`)));
389
- const overwrite = await p.confirm({ message: 'Overwrite existing files?', initialValue: false });
542
+ const overwrite = process.env.ASTRALKIT_YES === '1'
543
+ ? true
544
+ : await p.confirm({ message: 'Overwrite existing files?', initialValue: false });
390
545
  if (p.isCancel(overwrite) || !overwrite) return;
391
546
  }
392
547
  }
@@ -413,10 +568,12 @@ async function addBooster(slug, options) {
413
568
  }
414
569
  if (safeDeps.length > 0) {
415
570
  console.log();
416
- const install = await p.confirm({
417
- message: `Install dependencies? (${safeDeps.join(', ')})`,
418
- initialValue: true,
419
- });
571
+ const install = process.env.ASTRALKIT_YES === '1'
572
+ ? true
573
+ : await p.confirm({
574
+ message: `Install dependencies? (${safeDeps.join(', ')})`,
575
+ initialValue: true,
576
+ });
420
577
  if (!p.isCancel(install) && install) {
421
578
  const s = ora('Installing dependencies...').start();
422
579
  const result = await runInstall(pm, process.cwd(), safeDeps);
@@ -426,6 +583,34 @@ async function addBooster(slug, options) {
426
583
  }
427
584
  }
428
585
 
586
+ // Apply file-merge patches (e.g. wrap layout.tsx with a provider, ensure
587
+ // middleware.ts exists or print merge instructions). Runs after deps install
588
+ // so the wrapped file's imports resolve immediately on `npm run dev`.
589
+ if (Array.isArray(data.merges) && data.merges.length > 0) {
590
+ const mergeSummary = { created: [], modified: [], installed: [], alreadySatisfied: [], skipped: [] };
591
+ await applyMerges(data.merges, process.cwd(), mergeSummary);
592
+
593
+ // Surface what changed in the user's existing files. We don't reuse
594
+ // printInstallSummary here because the booster file list was already
595
+ // printed above; this is the focused "what we touched outside the
596
+ // install_paths" report.
597
+ if (mergeSummary.created.length || mergeSummary.modified.length || mergeSummary.skipped.length) {
598
+ console.log();
599
+ if (mergeSummary.created.length) {
600
+ console.log(pc.green(' Created:'));
601
+ for (const f of mergeSummary.created) console.log(pc.gray(` ${f}`));
602
+ }
603
+ if (mergeSummary.modified.length) {
604
+ console.log(pc.yellow(' Patched:'));
605
+ for (const m of mergeSummary.modified) console.log(pc.gray(` ${m.path} ${pc.dim(m.note)}`));
606
+ }
607
+ if (mergeSummary.skipped.length) {
608
+ console.log(pc.gray(' Merge skipped:'));
609
+ for (const k of mergeSummary.skipped) console.log(pc.gray(` ${k.what} ${pc.dim(`(${k.reason})`)}`));
610
+ }
611
+ }
612
+ }
613
+
429
614
  if (data.dependencies?.env?.length) {
430
615
  console.log();
431
616
  p.log.warn('Add these to your .env:');
@@ -15,10 +15,15 @@ import {
15
15
  import { getAiRulesContent } from '../lib/ai-rules.js';
16
16
  import { saveApiKey, getApiKey } from '../lib/auth.js';
17
17
  import { detectPackageManager, runInstall } from '../lib/pkg-manager.js';
18
+ import { getStarterKit } from '../lib/api.js';
18
19
 
19
20
  const FRAMEWORK_LABELS = { nextjs: 'Next.js', react: 'React' };
20
21
 
21
22
  export async function initCommand(options) {
23
+ if (options.projectName) {
24
+ return scaffoldCommand(options);
25
+ }
26
+
22
27
  p.intro(pc.bgBlue(pc.white(' AstralKit Setup ')));
23
28
 
24
29
  // ─── Step 1: API Key ─────────────────────────────────
@@ -197,3 +202,122 @@ export async function initCommand(options) {
197
202
  console.log(pc.gray(' Browse all: '), pc.cyan('astralkit list'));
198
203
  console.log();
199
204
  }
205
+
206
+ async function scaffoldCommand(options) {
207
+ const projectName = options.projectName;
208
+ p.intro(pc.bgBlue(pc.white(' AstralKit Starter Kit ')));
209
+
210
+ // Validate project name
211
+ if (!/^[a-zA-Z0-9_-]+$/.test(projectName)) {
212
+ p.cancel(pc.red('Project name can only contain letters, numbers, hyphens, and underscores.'));
213
+ process.exit(1);
214
+ }
215
+
216
+ const targetDir = path.resolve(process.cwd(), projectName);
217
+ if (fs.existsSync(targetDir)) {
218
+ p.cancel(pc.red(`Directory "${projectName}" already exists.`));
219
+ process.exit(1);
220
+ }
221
+
222
+ // API key is required for downloading the starter kit
223
+ let apiKey = options.apiKey || getApiKey();
224
+
225
+ if (options.apiKey) {
226
+ if (!options.apiKey.startsWith('ak_')) {
227
+ p.cancel(pc.red('Invalid API key format. Keys start with ak_'));
228
+ console.log(pc.gray('Get your key at ') + pc.cyan('https://astralkit.com/account'));
229
+ process.exit(1);
230
+ }
231
+ saveApiKey(options.apiKey);
232
+ p.log.success('API key saved');
233
+ } else if (!apiKey) {
234
+ p.log.warn('An API key is required to download the Starter Kit.');
235
+ console.log();
236
+ console.log(pc.gray(' Get your free API key at: ') + pc.cyan('https://astralkit.com/account'));
237
+ console.log();
238
+
239
+ const keyInput = await p.text({
240
+ message: 'Paste your API key:',
241
+ placeholder: 'ak_...',
242
+ validate(val) {
243
+ if (!val) return 'API key is required for the Starter Kit';
244
+ if (!val.startsWith('ak_')) return 'Keys start with ak_ — check astralkit.com/account';
245
+ },
246
+ });
247
+
248
+ if (p.isCancel(keyInput)) {
249
+ p.cancel('Setup cancelled.');
250
+ process.exit(0);
251
+ }
252
+
253
+ saveApiKey(keyInput);
254
+ apiKey = keyInput;
255
+ p.log.success('API key saved');
256
+ } else {
257
+ p.log.success('API key found');
258
+ }
259
+
260
+ // Download starter kit
261
+ const ora = (await import('ora')).default;
262
+ const spinner = ora('Downloading Starter Kit...').start();
263
+
264
+ let data;
265
+ try {
266
+ data = await getStarterKit();
267
+ } catch (err) {
268
+ spinner.fail('Failed to download Starter Kit.');
269
+ if (err.code === 'AUTH_REQUIRED') {
270
+ console.log(pc.gray(' Your API key may be invalid. Get a new one at ') + pc.cyan('https://astralkit.com/account'));
271
+ } else {
272
+ console.log(pc.gray(' ' + err.message));
273
+ }
274
+ process.exit(1);
275
+ }
276
+
277
+ if (!data.files || data.files.length === 0) {
278
+ spinner.fail('Starter Kit is empty or unavailable.');
279
+ process.exit(1);
280
+ }
281
+
282
+ spinner.succeed(`Downloaded ${data.files.length} files`);
283
+
284
+ // Write files to target directory
285
+ const writeSpinner = ora(`Creating ${pc.cyan(projectName)}/...`).start();
286
+
287
+ for (const file of data.files) {
288
+ const filePath = path.join(targetDir, file.path);
289
+ const dir = path.dirname(filePath);
290
+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
291
+ fs.writeFileSync(filePath, file.content, 'utf8');
292
+ }
293
+
294
+ writeSpinner.succeed(`Created ${pc.cyan(projectName)}/`);
295
+
296
+ // Install dependencies
297
+ const pm = detectPackageManager();
298
+ const installSpinner = ora(`Installing dependencies with ${pm}...`).start();
299
+
300
+ try {
301
+ const result = await runInstall(pm, targetDir, []);
302
+ if (result.success) {
303
+ installSpinner.succeed('Dependencies installed');
304
+ } else {
305
+ installSpinner.warn('Could not install dependencies automatically.');
306
+ console.log(pc.gray(` Run ${pm === 'npm' ? 'npm install' : pm + ' install'} manually in ${projectName}/`));
307
+ }
308
+ } catch {
309
+ installSpinner.warn('Could not install dependencies automatically.');
310
+ console.log(pc.gray(` Run ${pm === 'npm' ? 'npm install' : pm + ' install'} manually in ${projectName}/`));
311
+ }
312
+
313
+ p.outro(pc.green('Starter Kit is ready!'));
314
+
315
+ console.log();
316
+ console.log(pc.gray(' Get started:'));
317
+ console.log(pc.cyan(` cd ${projectName}`));
318
+ console.log(pc.cyan(` ${pm === 'npm' ? 'npm run' : pm} dev`));
319
+ console.log();
320
+ console.log(pc.gray(' Add a component:'), pc.cyan('astralkit add button-variants'));
321
+ console.log(pc.gray(' Browse all: '), pc.cyan('astralkit list'));
322
+ console.log();
323
+ }
@@ -22,28 +22,54 @@ export function getAiRulesContent() {
22
22
  function getEmbeddedRules() {
23
23
  return `# AstralKit — AI Coding Rules
24
24
 
25
- ## Component Usage
26
- - Import components from the components directory: \`import { Button } from '@/components/ui/button'\`
27
- - Use the \`cn()\` helper for conditional classes: \`import { cn } from '@/lib/utils'\`
28
- - All components use Tailwind CSS for styling
29
- - Components are built on top of Radix UI primitives where applicable
30
-
31
- ## Design Tokens
32
- - Use CSS variables for colors: \`var(--color-primary)\`
33
- - Spacing follows Tailwind's scale
34
- - All tokens are defined in \`astralkit/theme\`
35
-
36
- ## File Structure
25
+ ## Token-First Rule
26
+ ALWAYS use \`ak-*\` design tokens. NEVER use arbitrary bracket values or raw Tailwind defaults.
27
+
28
+ \`\`\`tsx
29
+ // CORRECT
30
+ <div className="p-ak-3 gap-ak-2 text-ak-base bg-ak-surface text-ak-text rounded-ak-lg">
31
+
32
+ // WRONG — arbitrary values silently collapse in Tailwind v4
33
+ <div className="p-[1.5rem] gap-4 text-base bg-gray-50 text-gray-900 rounded-lg">
34
+ \`\`\`
35
+
36
+ ## Semantic Colors
37
+ - Backgrounds: \`bg-ak-bg\`, \`bg-ak-surface\`, \`bg-ak-surface-2\`, \`bg-ak-hover\`
38
+ - Text: \`text-ak-text\`, \`text-ak-text-secondary\`, \`text-ak-text-muted\`
39
+ - Borders: \`border-ak-border\`, \`border-ak-border-subtle\`, \`border-ak-border-strong\`
40
+ - Primary: \`bg-ak-primary\`, \`text-ak-on-primary\`, \`bg-ak-primary-hover\`
41
+ - Status: \`bg-ak-success\`, \`bg-ak-danger\`, \`bg-ak-warning\`, \`bg-ak-info\` (+ \`-subtle\` variants)
42
+
43
+ ## Typography
44
+ - Use \`text-ak-*\` sizes: \`text-ak-xs\` (12px), \`text-ak-sm\` (14px), \`text-ak-base\` (16px), \`text-ak-lg\` (18px), \`text-ak-xl\` (20px), \`text-ak-2xl\` (24px), up to \`text-ak-10xl\`
45
+ - Fluid responsive: \`text-ak-fl-*\` (scales from 320px→1400px viewport, zero breakpoints)
46
+ - Display/hero: \`text-ak-display-*\` (dramatic scaling for marketing headings)
47
+ - Fonts: \`font-ak-sans\` (Inter), \`font-ak-serif\` (DM Serif Display), \`font-ak-mono\` (JetBrains Mono)
48
+
49
+ ## Spacing
50
+ Use \`ak-*\` spacing tokens: \`ak-0_5\` (4px), \`ak-1\` (8px), \`ak-1_5\` (12px), \`ak-2\` (16px), \`ak-3\` (24px), \`ak-4\` (32px), \`ak-6\` (48px), \`ak-8\` (64px)
51
+ - Fluid: \`ak-fl-xs\` through \`ak-fl-3xl\` (responsive, no breakpoints)
52
+ - Page margin: \`px-ak-fl-page-margin\` (16px mobile → 80px desktop)
53
+
54
+ ## Icons
55
+ Phosphor Icons ONLY (\`@phosphor-icons/react\`). Never inline SVGs or other icon libraries.
56
+
57
+ ## Components
58
+ - Install via CLI: \`astralkit add <component-name>\`
37
59
  - Components live in \`src/components/ui/\`
38
- - Boosters live in \`src/lib/<booster-name>/\` (core) and \`src/components/<booster-name>/\` (adapters)
39
- - Configuration is in \`astralkit.config.json\`
60
+ - Use \`cn()\` for conditional classes: \`import { cn } from '@/lib/utils'\`
40
61
 
41
- ## Adding Components
42
- - Use the CLI: \`astralkit add <component-name>\`
43
- - Never manually copy components — always use the CLI to get the latest version
62
+ ## Conventions
63
+ - No inline \`style={{}}\` — use Tailwind classes
64
+ - No shadows on panels/dropdowns — use borders
65
+ - No Framer Motion — use CSS animations
66
+ - 16px body floor + AAA contrast minimum
67
+ - All buttons/inputs: \`min-h-[3rem]\` touch target + \`cursor-pointer\`
68
+ - Dark mode: \`.dark\` class or \`data-theme="dark"\` on \`<html>\`
69
+ - Palettes: \`data-ak-theme="ocean-blue"\` (16 presets available)
70
+ - Density: \`data-ak-density="compact|spacious"\` on any container
44
71
 
45
- ## Pro Components
46
- - Run \`astralkit login\` to access Pro content
47
- - Pro components are marked with ✨ in the CLI output
72
+ ## For the full token reference
73
+ See \`.claude/CLAUDE.md\` if present, or visit https://astralkit.com/docs
48
74
  `;
49
75
  }
package/src/lib/api.js CHANGED
@@ -1,6 +1,7 @@
1
+ import fs from 'fs';
1
2
  import { createRequire } from 'module';
2
3
  import { fileURLToPath } from 'url';
3
- import { dirname, join } from 'path';
4
+ import { dirname, join, relative, resolve } from 'path';
4
5
  import { getAuth, getApiKey } from './auth.js';
5
6
 
6
7
  const __dirname = dirname(fileURLToPath(import.meta.url));
@@ -11,6 +12,16 @@ const CLI_VERSION = pkg.version;
11
12
  const DEFAULT_API_BASE = 'https://astralkit.com';
12
13
  const REQUEST_TIMEOUT_MS = 30_000;
13
14
 
15
+ /**
16
+ * Local registry mode (dev/QA only). When ASTRALKIT_REGISTRY_DIR points at a
17
+ * local registry-dev/ checkout, booster reads are served straight from disk
18
+ * instead of the live API — used to QA boosters before pushing them to the
19
+ * astral-kit/registry repo. Components and workflows still hit the API.
20
+ */
21
+ export const LOCAL_REGISTRY_DIR = process.env.ASTRALKIT_REGISTRY_DIR
22
+ ? resolve(process.env.ASTRALKIT_REGISTRY_DIR)
23
+ : null;
24
+
14
25
  export const API_BASE = (() => {
15
26
  const override = process.env.ASTRALKIT_API_URL;
16
27
  if (!override) return DEFAULT_API_BASE;
@@ -134,6 +145,7 @@ export async function getComponent(slug, framework = 'html') {
134
145
  }
135
146
 
136
147
  export async function listBoosters({ framework, search, pro, free } = {}) {
148
+ if (LOCAL_REGISTRY_DIR) return listLocalBoosters({ search });
137
149
  const params = new URLSearchParams();
138
150
  if (framework) params.set('framework', framework);
139
151
  if (pro) params.set('pro', 'true');
@@ -144,10 +156,61 @@ export async function listBoosters({ framework, search, pro, free } = {}) {
144
156
  }
145
157
 
146
158
  export async function getBooster(slug, framework = 'nextjs') {
159
+ if (LOCAL_REGISTRY_DIR) return getLocalBooster(slug, framework);
147
160
  const res = await apiRequest(`/api/cli/boosters/${encodeURIComponent(slug)}?framework=${encodeURIComponent(framework)}`);
148
161
  return res.json();
149
162
  }
150
163
 
164
+ // ─── Local registry implementations ──────────────────────────────────────────
165
+
166
+ function walkLocalFiles(root) {
167
+ if (!fs.existsSync(root)) return [];
168
+ const out = [];
169
+ const stack = [root];
170
+ while (stack.length > 0) {
171
+ const dir = stack.pop();
172
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
173
+ const full = join(dir, entry.name);
174
+ if (entry.isDirectory()) stack.push(full);
175
+ else out.push({
176
+ path: relative(root, full).split('\\').join('/'),
177
+ content: fs.readFileSync(full, 'utf8'),
178
+ });
179
+ }
180
+ }
181
+ return out;
182
+ }
183
+
184
+ function getLocalBooster(slug, framework) {
185
+ const boosterDir = join(LOCAL_REGISTRY_DIR, 'boosters', slug);
186
+ const manifestPath = join(boosterDir, 'booster.json');
187
+ if (!fs.existsSync(manifestPath)) {
188
+ const err = new Error(`Booster "${slug}" not found in local registry (${LOCAL_REGISTRY_DIR}).`);
189
+ err.code = 'API_ERROR';
190
+ throw err;
191
+ }
192
+ const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
193
+ return {
194
+ ...manifest,
195
+ core_files: walkLocalFiles(join(boosterDir, 'core')),
196
+ adapter_files: walkLocalFiles(join(boosterDir, 'adapters', framework)),
197
+ };
198
+ }
199
+
200
+ function listLocalBoosters({ search } = {}) {
201
+ const boostersRoot = join(LOCAL_REGISTRY_DIR, 'boosters');
202
+ if (!fs.existsSync(boostersRoot)) return { boosters: [] };
203
+ const q = (search || '').toLowerCase();
204
+ const boosters = fs.readdirSync(boostersRoot, { withFileTypes: true })
205
+ .filter((e) => e.isDirectory() && fs.existsSync(join(boostersRoot, e.name, 'booster.json')))
206
+ .map((e) => JSON.parse(fs.readFileSync(join(boostersRoot, e.name, 'booster.json'), 'utf8')))
207
+ .filter((m) => !q ||
208
+ (m.slug || '').toLowerCase().includes(q) ||
209
+ (m.name || '').toLowerCase().includes(q) ||
210
+ (m.description || '').toLowerCase().includes(q));
211
+ return { boosters };
212
+ }
213
+
151
214
  export async function listWorkflows({ framework, search, pro, free } = {}) {
152
215
  const params = new URLSearchParams();
153
216
  if (framework) params.set('framework', framework);
@@ -162,3 +225,8 @@ export async function getWorkflow(slug, framework = 'nextjs') {
162
225
  const res = await apiRequest(`/api/cli/workflows/${encodeURIComponent(slug)}?framework=${encodeURIComponent(framework)}`);
163
226
  return res.json();
164
227
  }
228
+
229
+ export async function getStarterKit() {
230
+ const res = await apiRequest('/api/cli/starter-kit');
231
+ return res.json();
232
+ }
@@ -0,0 +1,310 @@
1
+ /**
2
+ * Booster Merge Strategies
3
+ * ────────────────────────
4
+ * Patches the CLI applies to files the user already owns. A booster declares
5
+ * these in its `merges` array (see BoosterJson.merges in src/lib/github-registry.ts).
6
+ *
7
+ * Strategies:
8
+ * - wrap-jsx-children — inject imports + wrap the children of a JSX anchor
9
+ * element (default <body>) with an opening/closing fragment. Used by Stack
10
+ * Auth and similar boosters to wrap layout.tsx with <Provider><Theme>.
11
+ *
12
+ * - ensure-middleware — create src/middleware.ts if it doesn't exist; if it
13
+ * does and the booster's marker isn't found, print explicit merge instructions
14
+ * instead of overwriting. Used by WorkOS-style middleware boosters.
15
+ *
16
+ * - append-unique-block — append a marker-guarded text block to a file the
17
+ * user owns (creating it if absent). Used for Prisma model additions
18
+ * (prisma/schema.prisma) and .env.example variable appends. The block MUST
19
+ * contain the idempotency_marker so re-installs detect it.
20
+ *
21
+ * Each strategy is idempotent: re-running an install detects the marker and skips.
22
+ */
23
+
24
+ import fs from 'fs';
25
+ import path from 'path';
26
+ import pc from 'picocolors';
27
+ import * as p from '@clack/prompts';
28
+ import { isSafePath, isSafeInstallDir } from './validators.js';
29
+
30
+ /**
31
+ * Confirm with the user, or auto-accept when ASTRALKIT_YES=1 (CI/QA runs where
32
+ * no TTY is attached). Returns true/false; never a cancel symbol.
33
+ */
34
+ async function confirmOrAuto(opts) {
35
+ if (process.env.ASTRALKIT_YES === '1') return true;
36
+ const answer = await p.confirm(opts);
37
+ return !p.isCancel(answer) && answer;
38
+ }
39
+
40
+ /**
41
+ * Entry point: walk the merges array and dispatch each to its strategy handler.
42
+ * Mutates `installSummary` so the end-of-install report reflects what changed.
43
+ */
44
+ export async function applyMerges(merges, projectRoot, installSummary) {
45
+ if (!Array.isArray(merges) || merges.length === 0) return;
46
+
47
+ for (const merge of merges) {
48
+ try {
49
+ if (merge.strategy === 'wrap-jsx-children') {
50
+ await applyWrapJsxChildren(merge, projectRoot, installSummary);
51
+ } else if (merge.strategy === 'ensure-middleware') {
52
+ await applyEnsureMiddleware(merge, projectRoot, installSummary);
53
+ } else if (merge.strategy === 'append-unique-block') {
54
+ await applyAppendUniqueBlock(merge, projectRoot, installSummary);
55
+ } else {
56
+ p.log.warn(`Unknown merge strategy "${merge.strategy}" — skipped`);
57
+ installSummary.skipped.push({
58
+ what: merge.target || merge.strategy,
59
+ reason: `unknown strategy: ${merge.strategy}`,
60
+ });
61
+ }
62
+ } catch (err) {
63
+ p.log.warn(`Merge failed for ${merge.target}: ${err.message || err}`);
64
+ installSummary.skipped.push({
65
+ what: merge.target,
66
+ reason: `merge error: ${err.message || err}`,
67
+ });
68
+ }
69
+ }
70
+ }
71
+
72
+ // ─── Strategy: wrap-jsx-children ──────────────────────────────────────────────
73
+
74
+ async function applyWrapJsxChildren(merge, projectRoot, installSummary) {
75
+ const { target, imports = [], open, close } = merge;
76
+ const anchor = merge.anchor || 'body';
77
+ const marker = merge.idempotency_marker || open;
78
+
79
+ if (!target || !open || !close) {
80
+ p.log.warn(`wrap-jsx-children merge is missing target/open/close — skipped`);
81
+ return;
82
+ }
83
+
84
+ if (!isSafeInstallDir(projectRoot, target)) {
85
+ p.log.warn(`Refusing merge: unsafe target path "${target}"`);
86
+ installSummary.skipped.push({ what: target, reason: 'unsafe target path' });
87
+ return;
88
+ }
89
+
90
+ const filePath = path.resolve(projectRoot, target);
91
+ if (!fs.existsSync(filePath)) {
92
+ p.log.warn(`Cannot wrap ${target} — file does not exist. Skipped.`);
93
+ p.log.info(`Manually add the booster's provider wrap to your layout.`);
94
+ installSummary.skipped.push({ what: target, reason: 'file not found' });
95
+ return;
96
+ }
97
+
98
+ const original = fs.readFileSync(filePath, 'utf8');
99
+
100
+ // Idempotency: marker already present → already wrapped.
101
+ if (original.includes(marker)) {
102
+ installSummary.skipped.push({ what: target, reason: 'already wrapped' });
103
+ return;
104
+ }
105
+
106
+ // Locate the anchor tags. We accept simple `<body>` or `<body className="...">`,
107
+ // including multi-line tags, but not nested same-name elements.
108
+ const openRe = new RegExp(`<${anchor}\\b[^>]*>`);
109
+ const closeRe = new RegExp(`</${anchor}>`);
110
+ const openMatch = original.match(openRe);
111
+ const closeMatch = original.match(closeRe);
112
+
113
+ if (!openMatch || !closeMatch) {
114
+ p.log.warn(`Could not locate <${anchor}> in ${target} — skipped.`);
115
+ p.log.info(`Manually wrap the contents of <${anchor}> with: ${open}…${close}`);
116
+ installSummary.skipped.push({
117
+ what: target,
118
+ reason: `no <${anchor}> element found`,
119
+ });
120
+ return;
121
+ }
122
+
123
+ const openEnd = openMatch.index + openMatch[0].length;
124
+ const closeStart = closeMatch.index;
125
+ if (closeStart <= openEnd) {
126
+ p.log.warn(`Malformed <${anchor}> in ${target} — skipped.`);
127
+ installSummary.skipped.push({ what: target, reason: 'malformed anchor element' });
128
+ return;
129
+ }
130
+
131
+ // Decide which imports need adding. We do not edit anything unless the user
132
+ // consents to the full diff, so we just calculate the missing set here.
133
+ const missingImports = imports.filter((line) => !original.includes(line));
134
+
135
+ // Compose the new file content.
136
+ const beforeOpen = original.slice(0, openEnd);
137
+ const inside = original.slice(openEnd, closeStart);
138
+ const afterClose = original.slice(closeStart);
139
+ const wrapped = `${beforeOpen}\n ${open}${inside}${close}\n ${afterClose}`;
140
+
141
+ // Insert missing imports after the last existing import (or at file head).
142
+ let withImports = wrapped;
143
+ if (missingImports.length > 0) {
144
+ const lines = wrapped.split('\n');
145
+ let lastImportIdx = -1;
146
+ for (let i = 0; i < lines.length; i++) {
147
+ if (lines[i].trim().startsWith('import ')) lastImportIdx = i;
148
+ }
149
+ if (lastImportIdx >= 0) {
150
+ lines.splice(lastImportIdx + 1, 0, ...missingImports);
151
+ } else {
152
+ lines.unshift(...missingImports, '');
153
+ }
154
+ withImports = lines.join('\n');
155
+ }
156
+
157
+ // Preview before applying — this file is heavily user-owned, so consent is required.
158
+ console.log();
159
+ p.log.step(`Booster wants to patch ${pc.cyan(target)}:`);
160
+ if (missingImports.length > 0) {
161
+ console.log(pc.gray(' Add imports:'));
162
+ for (const imp of missingImports) console.log(` ${pc.green('+')} ${imp}`);
163
+ }
164
+ console.log(pc.gray(` Wrap children of <${anchor}> with:`));
165
+ console.log(` ${pc.green('+')} ${open}…${close}`);
166
+
167
+ const proceed = await confirmOrAuto({
168
+ message: `Apply this patch to ${target}?`,
169
+ initialValue: true,
170
+ });
171
+
172
+ if (!proceed) {
173
+ p.log.info(`Skipped ${target}. Wrap manually with:`);
174
+ if (missingImports.length > 0) {
175
+ for (const imp of missingImports) console.log(pc.gray(` ${imp}`));
176
+ }
177
+ console.log(pc.gray(` Inside <${anchor}>: ${open} ... {children} ... ${close}`));
178
+ installSummary.skipped.push({ what: target, reason: 'user declined wrap' });
179
+ return;
180
+ }
181
+
182
+ fs.writeFileSync(filePath, withImports, 'utf8');
183
+ const noteParts = [];
184
+ if (missingImports.length > 0) noteParts.push(`+${missingImports.length} import${missingImports.length === 1 ? '' : 's'}`);
185
+ noteParts.push(`wrapped <${anchor}>`);
186
+ installSummary.modified.push({ path: target, note: noteParts.join(', ') });
187
+ p.log.success(`Patched ${pc.cyan(target)}`);
188
+ }
189
+
190
+ // ─── Strategy: append-unique-block ────────────────────────────────────────────
191
+
192
+ async function applyAppendUniqueBlock(merge, projectRoot, installSummary) {
193
+ const { target, block, idempotency_marker } = merge;
194
+
195
+ if (!target || !block || !idempotency_marker) {
196
+ p.log.warn(`append-unique-block merge is missing target/block/idempotency_marker — skipped`);
197
+ return;
198
+ }
199
+
200
+ // The marker must live inside the block itself, otherwise a re-install could
201
+ // never detect the previous append and would duplicate it.
202
+ if (!block.includes(idempotency_marker)) {
203
+ p.log.warn(`append-unique-block for ${target}: idempotency_marker not found inside block — skipped (authoring error)`);
204
+ installSummary.skipped.push({ what: target, reason: 'marker missing from block' });
205
+ return;
206
+ }
207
+
208
+ if (!isSafeInstallDir(projectRoot, target)) {
209
+ p.log.warn(`Refusing merge: unsafe target path "${target}"`);
210
+ installSummary.skipped.push({ what: target, reason: 'unsafe target path' });
211
+ return;
212
+ }
213
+
214
+ const filePath = path.resolve(projectRoot, target);
215
+
216
+ if (!fs.existsSync(filePath)) {
217
+ // Clean install — create the file with just the block.
218
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
219
+ fs.writeFileSync(filePath, block.endsWith('\n') ? block : `${block}\n`, 'utf8');
220
+ installSummary.created.push(target);
221
+ p.log.success(`Created ${pc.cyan(target)}`);
222
+ return;
223
+ }
224
+
225
+ const existing = fs.readFileSync(filePath, 'utf8');
226
+ if (existing.includes(idempotency_marker)) {
227
+ installSummary.skipped.push({ what: target, reason: 'already appended' });
228
+ return;
229
+ }
230
+
231
+ // Preview before applying — these files (prisma/schema.prisma, .env.example)
232
+ // are user-owned, so consent is required like the other patch strategies.
233
+ const blockLines = block.replace(/\n$/, '').split('\n');
234
+ const PREVIEW_MAX = 20;
235
+ console.log();
236
+ p.log.step(`Booster wants to append to ${pc.cyan(target)}:`);
237
+ for (const line of blockLines.slice(0, PREVIEW_MAX)) {
238
+ console.log(` ${pc.green('+')} ${line}`);
239
+ }
240
+ if (blockLines.length > PREVIEW_MAX) {
241
+ console.log(pc.gray(` … (+${blockLines.length - PREVIEW_MAX} more lines)`));
242
+ }
243
+
244
+ const proceed = await confirmOrAuto({
245
+ message: `Append ${blockLines.length} line${blockLines.length === 1 ? '' : 's'} to ${target}?`,
246
+ initialValue: true,
247
+ });
248
+
249
+ if (!proceed) {
250
+ p.log.info(`Skipped ${target}. Append the block manually (it is marker-guarded, shown above).`);
251
+ installSummary.skipped.push({ what: target, reason: 'user declined append' });
252
+ return;
253
+ }
254
+
255
+ const separator = existing.endsWith('\n') ? '\n' : '\n\n';
256
+ const appended = `${existing}${separator}${block}${block.endsWith('\n') ? '' : '\n'}`;
257
+ fs.writeFileSync(filePath, appended, 'utf8');
258
+ installSummary.modified.push({ path: target, note: `+${blockLines.length} lines appended` });
259
+ p.log.success(`Patched ${pc.cyan(target)}`);
260
+ }
261
+
262
+ // ─── Strategy: ensure-middleware ──────────────────────────────────────────────
263
+
264
+ async function applyEnsureMiddleware(merge, projectRoot, installSummary) {
265
+ const { target, content, idempotency_marker, merge_note } = merge;
266
+
267
+ if (!target || !content || !idempotency_marker) {
268
+ p.log.warn(`ensure-middleware merge is missing target/content/idempotency_marker — skipped`);
269
+ return;
270
+ }
271
+
272
+ if (!isSafeInstallDir(projectRoot, target)) {
273
+ p.log.warn(`Refusing merge: unsafe target path "${target}"`);
274
+ installSummary.skipped.push({ what: target, reason: 'unsafe target path' });
275
+ return;
276
+ }
277
+
278
+ const filePath = path.resolve(projectRoot, target);
279
+
280
+ if (!fs.existsSync(filePath)) {
281
+ // Clean install — just write it.
282
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
283
+ fs.writeFileSync(filePath, content, 'utf8');
284
+ installSummary.created.push(target);
285
+ p.log.success(`Created ${pc.cyan(target)}`);
286
+ return;
287
+ }
288
+
289
+ // Existing file. Idempotency check first.
290
+ const existing = fs.readFileSync(filePath, 'utf8');
291
+ if (existing.includes(idempotency_marker)) {
292
+ installSummary.skipped.push({ what: target, reason: 'already wired' });
293
+ return;
294
+ }
295
+
296
+ // Conflict: file exists but isn't wired. Print explicit instructions instead
297
+ // of attempting an automated merge — middleware shapes vary too much for a
298
+ // safe one-size-fits-all rewrite, and the cost of a broken edit here is high
299
+ // (every request goes through middleware).
300
+ console.log();
301
+ p.log.warn(`Cannot auto-update ${pc.cyan(target)} — file already exists and the booster's marker is missing.`);
302
+ console.log(pc.gray(' To finish wiring, do the following manually:'));
303
+ for (const line of String(merge_note).split('\n')) {
304
+ console.log(pc.gray(` ${line}`));
305
+ }
306
+ installSummary.skipped.push({
307
+ what: target,
308
+ reason: 'exists — manual merge required (see notes above)',
309
+ });
310
+ }