ghostcn 1.2.0 → 1.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.
Files changed (58) hide show
  1. package/README.md +182 -1
  2. package/dist/commands/add.d.ts +6 -1
  3. package/dist/commands/add.js +121 -83
  4. package/dist/commands/diff.d.ts +5 -0
  5. package/dist/commands/diff.js +54 -0
  6. package/dist/commands/playground.d.ts +3 -0
  7. package/dist/commands/playground.js +29 -0
  8. package/dist/index.js +16 -2
  9. package/dist/registry/components/alert.json +62 -0
  10. package/dist/registry/components/archive-header.json +57 -0
  11. package/dist/registry/components/author-card.json +23 -2
  12. package/dist/registry/components/author-list.json +55 -0
  13. package/dist/registry/components/badge.json +51 -0
  14. package/dist/registry/components/button.json +74 -0
  15. package/dist/registry/components/card.json +70 -0
  16. package/dist/registry/components/featured-posts.json +18 -1
  17. package/dist/registry/components/input.json +94 -0
  18. package/dist/registry/components/member-cta.json +15 -1
  19. package/dist/registry/components/newsletter-form.json +23 -2
  20. package/dist/registry/components/pagination.json +12 -1
  21. package/dist/registry/components/post-card.json +25 -2
  22. package/dist/registry/components/post-grid.json +54 -0
  23. package/dist/registry/components/post-header.json +18 -1
  24. package/dist/registry/components/post-navigation.json +41 -0
  25. package/dist/registry/components/pricing-table.json +31 -2
  26. package/dist/registry/components/related-posts.json +53 -0
  27. package/dist/registry/components/site-footer.json +15 -1
  28. package/dist/registry/components/site-header.json +16 -1
  29. package/dist/registry/components/table-of-contents.json +47 -0
  30. package/dist/registry/components/tag-grid.json +64 -0
  31. package/dist/registry/components/tag-list.json +38 -0
  32. package/dist/registry/index.json +131 -0
  33. package/dist/templates/playground/index.html +5 -0
  34. package/dist/templates/playground/playground.css +18 -0
  35. package/dist/templates/playground/playground.js +71 -0
  36. package/dist/templates/playground/preview.css +5 -0
  37. package/dist/templates/playground/preview.js +12 -0
  38. package/dist/templates/theme-tools.mjs +1 -1
  39. package/dist/utils/component-diff.d.ts +18 -0
  40. package/dist/utils/component-diff.js +93 -0
  41. package/dist/utils/component-files.d.ts +9 -0
  42. package/dist/utils/component-files.js +48 -0
  43. package/dist/utils/component-history.d.ts +11 -0
  44. package/dist/utils/component-history.js +47 -0
  45. package/dist/utils/component-installer.d.ts +2 -0
  46. package/dist/utils/component-installer.js +34 -37
  47. package/dist/utils/component-plan.d.ts +7 -0
  48. package/dist/utils/component-plan.js +43 -0
  49. package/dist/utils/playground-server.d.ts +9 -0
  50. package/dist/utils/playground-server.js +189 -0
  51. package/dist/utils/preview-renderer.d.ts +143 -0
  52. package/dist/utils/preview-renderer.js +70 -0
  53. package/dist/utils/registry.d.ts +7 -0
  54. package/dist/utils/registry.js +12 -18
  55. package/dist/utils/theme-files.d.ts +2 -0
  56. package/dist/utils/theme-files.js +41 -3
  57. package/dist/utils/theme-scaffold.js +12 -0
  58. package/package.json +2 -2
package/README.md CHANGED
@@ -49,6 +49,21 @@ You own the code. You customize the classes. Zero vendor lock-in.
49
49
  | **`pagination`** | Accessible replacement for Ghost’s native pagination partial | `partials/pagination.hbs`, `pagination.css` |
50
50
  | **`post-header`** | Editorial post heading, author metadata, reading time, and responsive image | `post-header.hbs`, `post-header.css` |
51
51
  | **`member-cta`** | Context-aware calls to action for visitors, free members, and paid members | `member-cta.hbs`, `member-cta.css` |
52
+ | **`related-posts`** | Related stories by primary tag, with an untagged fallback | `related-posts.hbs`, `related-posts.css` |
53
+ | **`post-navigation`** | Chronological previous/next story links | `post-navigation.hbs`, `post-navigation.css` |
54
+ | **`table-of-contents`** | Accessible article heading navigation with unique anchors | `table-of-contents.hbs`, `table-of-contents.css`, `table-of-contents.js` |
55
+ | **`tag-list`** | Public post tags, with internal tags hidden | `tag-list.hbs`, `tag-list.css` |
56
+ | **`button`** | Native button or link, with variants, sizes and disabled states | `button.hbs`, `button.css` |
57
+ | **`card`** | Content card accepting text or nested template blocks | `card.hbs`, `card.css` |
58
+ | **`badge`** | Non-interactive label with variants and sizes | `badge.hbs`, `badge.css` |
59
+ | **`input`** | Repeat-safe labeled native input and optional help text | `input.hbs`, `input.css` |
60
+ | **`alert`** | Accessible status message with optional urgent announcement | `alert.hbs`, `alert.css` |
61
+ | **`post-grid`** | Responsive current-post collection composed from post cards | `post-grid.hbs`, `post-grid.css` |
62
+ | **`author-list`** | Publication author collection composed from author cards | `author-list.hbs`, `author-list.css` |
63
+ | **`tag-grid`** | Public tag archive links composed from cards and buttons | `tag-grid.hbs`, `tag-grid.css` |
64
+ | **`archive-header`** | Shared author/tag archive heading with an optional badge/image | `archive-header.hbs`, `archive-header.css` |
65
+
66
+ The five primitives, four composed blocks, dependency installation, and local playground are **unreleased development features**. Use this checkout's built CLI to test them; updating an older npm release will not provide them.
52
67
 
53
68
  ---
54
69
 
@@ -119,7 +134,17 @@ Membership components respect disabled, invite-only and self-signup settings. Pa
119
134
 
120
135
  ### Updating an existing ghostcn theme
121
136
 
122
- Your copied files are yours; an npm update does not silently rewrite them. Back up or commit your theme first. Compare the new components in a fresh throwaway theme, then merge the changes you want. To replace unmodified files directly, run `ghostcn init` with your existing palette/paths and re-add the relevant components. Initialization regenerates tokens; `add -y` overwrites component customizations, so use it only deliberately. Existing Tailwind styles from older ghostcn releases are unlayered and need the new token/component CSS for ordinary utility overrides to work.
137
+ Your copied files are yours; an npm update does not silently rewrite them. Back up or commit your theme first, then review changes without modifying any files:
138
+
139
+ ```bash
140
+ npx ghostcn@latest diff
141
+ npx ghostcn@latest diff pricing-table --latest
142
+ npx ghostcn@latest diff pricing-table --json
143
+ ```
144
+
145
+ By default, `diff` uses the bundled registry (or your configured registry). `--latest` explicitly checks the remote registry's current branch, which may be ahead of npm; a failed request is reported, not silently replaced by an older bundled version. It compares the installed baseline, your current file, and the incoming version. Review upstream changes and conflicts, then manually merge what you want. New installs record content baselines in `.ghostcn/installed.json`; older files without a baseline are labeled **untracked**, not presumed safe to overwrite. Keep this file with your theme to retain three-way comparison history.
146
+
147
+ `diff` never installs, deletes, or merges files. `add -y` still deliberately overwrites component files. Initialization regenerates tokens, so preserve your chosen palette and paths. Existing Tailwind styles from older releases are unlayered and need the new token/component CSS for ordinary utility overrides.
123
148
 
124
149
  ### 1. Initialize your Ghost Theme
125
150
 
@@ -179,6 +204,16 @@ Add a specific component:
179
204
  npx ghostcn add newsletter-form
180
205
  ```
181
206
 
207
+ Add multiple components in one command (unreleased development CLI):
208
+
209
+ ```bash
210
+ ghostcn add button card badge input alert post-grid author-list tag-grid archive-header
211
+ ```
212
+
213
+ For existing files, the spinner pauses before a single overwrite decision per requested component. Enter / N preserves them and continues with the rest; Y replaces that component's existing files. Ctrl+C cancels the remaining work (earlier installs are not rolled back). Review `ghostcn diff <name>` before replacing customizations.
214
+
215
+ For scripts or a quick safe re-run, `ghostcn add button card --skip-existing` installs missing files and preserves existing ones without prompts. Without a terminal, existing files are also preserved and the CLI prints review/replacement directions. Use `--yes` only for deliberate replacement; do not combine it with `--skip-existing`.
216
+
182
217
  Or run `add` without arguments to pick interactively from a checklist:
183
218
  ```bash
184
219
  npx ghostcn add
@@ -211,6 +246,84 @@ Include the installed partial anywhere in your Handlebars templates:
211
246
  {{/foreach}}
212
247
  ```
213
248
 
249
+ ### 5. Style each instance without changing the shared component
250
+
251
+ Every component accepts `class` for its root element. Optional named slots style specific parts **inside** a component: `buttonClass` styles its theme-owned buttons, while `cardClass` styles nested pricing/featured cards. These are ordinary class strings, not new CSS syntax, and work with Tailwind or your own vanilla CSS.
252
+
253
+ ```handlebars
254
+ {{> "components/pricing-table"
255
+ class="mx-auto my-12 w-full max-w-md"
256
+ cardClass="rounded-2xl bg-card p-8 shadow-lg"
257
+ buttonClass="bg-purple-600 hover:bg-purple-700 text-white"
258
+ }}
259
+
260
+ {{!-- Another independent instance; the shared partial stays unchanged --}}
261
+ {{> "components/pricing-table"
262
+ class="mx-auto max-w-6xl"
263
+ cardClass="rounded-lg p-4 shadow-none"
264
+ buttonClass="bg-emerald-600 hover:bg-emerald-700 text-white"
265
+ }}
266
+
267
+ {{> "components/newsletter-form"
268
+ class="max-w-lg p-4 shadow-none"
269
+ inputClass="rounded-xl"
270
+ buttonClass="rounded-xl bg-purple-600 text-white"
271
+ }}
272
+
273
+ {{#foreach posts}}
274
+ {{> "components/post-card" class="rounded-xl shadow-none" titleClass="text-2xl"}}
275
+ {{/foreach}}
276
+ ```
277
+
278
+ All components keep their semantic identity classes and default CSS. Defaults live in the component layer for Tailwind, so normal utilities override them without `!` modifiers or a class-merging helper. Keep `npm run dev` running; classes must appear as complete literal strings in scanned `.hbs` files (do not construct `bg-{{color}}-600`). If you pass classes from runtime data, include their complete names in a scanned source or explicitly safelist them with Tailwind's `@source inline()`.
279
+
280
+ | Component | Root | Additional styling parameters |
281
+ | --- | --- | --- |
282
+ | `pricing-table` | `class` | `titleClass`, `gridClass`, `cardClass`, `buttonClass`, `cardTitleClass`, `descriptionClass`, `priceClass`, `benefitsClass` |
283
+ | `newsletter-form` | `class` | `titleClass`, `descriptionClass`, `formClass`, `inputClass`, `buttonClass` |
284
+ | `post-card` | `class` | `imageClass`, `contentClass`, `titleClass`, `descriptionClass`, `metaClass`, `footerClass` |
285
+ | `author-card` | `class` | `avatarClass`, `contentClass`, `titleClass`, `descriptionClass`, `metaClass` |
286
+ | `site-header` | `class` | `innerClass`, `navClass`, `buttonClass` |
287
+ | `site-footer` | `class` | `innerClass`, `navClass`, `socialClass` |
288
+ | `featured-posts` | `class` | `titleClass`, `gridClass`, `cardClass`, `contentClass` |
289
+ | `pagination` | `class` | `buttonClass`, `statusClass` |
290
+ | `post-header` | `class` | `titleClass`, `descriptionClass`, `metaClass`, `imageClass` |
291
+ | `member-cta` | `class` | `titleClass`, `descriptionClass`, `buttonClass` |
292
+ | `related-posts` | `class` | `titleClass`, `gridClass`, `cardClass`, `cardTitleClass`, `imageClass`, `contentClass`, `descriptionClass` |
293
+ | `post-navigation` | `class` | `cardClass`, `titleClass`, `labelClass` |
294
+ | `table-of-contents` | `class` | `titleClass`, `listClass`, `linkClass` |
295
+ | `tag-list` | `class` | `listClass`, `linkClass` |
296
+
297
+ Slots only affect elements that render for the current content/member state. `buttonClass` applies to all theme-owned buttons in that component, not individual monthly/yearly actions and not Ghost-generated search/Portal/comments UI. Use scoped descendant selectors for more granular targeting. Root `class` does not automatically recolor children that have their own colors; use the corresponding slot. To customize pagination at the call site, use `{{> "pagination" pagination class="my-pagination"}}`; the native `{{pagination}}` helper retains its default appearance.
298
+
299
+ ### Pair custom backgrounds with foregrounds
300
+
301
+ Default semantic surfaces (`bg-card text-card-foreground`) follow Light/Dark/Auto. Arbitrary background utilities do **not** select a matching text color automatically. For example, `bg-purple-50` alone leaves dark-mode foreground tokens white. Always pair custom surfaces and text, including their dark variants:
302
+
303
+ ```handlebars
304
+ {{> "components/pricing-table"
305
+ class="mx-auto my-12 max-w-5xl"
306
+ cardClass="rounded-2xl bg-purple-50 text-purple-950 dark:bg-purple-950 dark:text-purple-50 p-8 shadow-lg"
307
+ buttonClass="bg-purple-600 text-white hover:bg-purple-700"
308
+ }}
309
+ ```
310
+
311
+ Pricing titles, descriptions, benefits, prices, and billing intervals inherit the card's local text color; use their named slots for individual overrides. Standalone cards use the same pairing on `class`, not `cardClass`. For vanilla custom surfaces, set **both** `background` and `color` on your own class. Review contrast in every color mode; arbitrary custom colors are not automatically contrast-corrected.
312
+
313
+ For vanilla CSS, pass custom class names and define them in your theme-owned `assets/css/source.css`:
314
+
315
+ ```handlebars
316
+ {{> "components/pricing-table" class="membership" cardClass="membership-card" buttonClass="membership-button"}}
317
+ ```
318
+
319
+ ```css
320
+ .membership { max-width: 40rem; }
321
+ .membership .membership-card { border-radius: 1.5rem; box-shadow: 0 8px 24px #0002; }
322
+ .membership .membership-button { background: #7c3aed; color: white; }
323
+ ```
324
+
325
+ Load custom CSS after component styles and match selector specificity where needed. Re-adding a component with `-y` still overwrites its copied partial/CSS, but **not** the calling page template or `source.css`. Back up first when upgrading old customized partials. Existing installations must merge or re-add the new partials to gain these parameters; updating the CLI alone does not rewrite your theme. A future component release may still require migration if it changes or removes a documented slot.
326
+
214
327
  ---
215
328
 
216
329
  ## Project Structure
@@ -230,6 +343,68 @@ ghostcn/
230
343
 
231
344
  ## Development & Testing
232
345
 
346
+ ### Composable components (unreleased)
347
+
348
+ Every component still accepts `class`. A standalone button or card uses `class` for itself; `cardClass` and `buttonClass` belong only to blocks containing those elements. Primitives support `size="sm|default|lg"`. Their supported variants are:
349
+
350
+ | Component | Variants |
351
+ | :--- | :--- |
352
+ | `button` | `default`, `secondary`, `outline`, `ghost`, `destructive`, `link` |
353
+ | `card` | `default`, `secondary`, `outline` |
354
+ | `badge` | `default`, `secondary`, `outline`, `destructive` |
355
+ | `input` | `default`, `filled` |
356
+ | `alert` | `default`, `secondary`, `outline`, `destructive` |
357
+
358
+ Unknown variants/sizes fall back to `default`. Existing components do not gain invented variant parameters. Pass booleans as `disabled=true`, not `disabled="false"` (a nonempty string is truthy in Handlebars).
359
+
360
+ ```handlebars
361
+ {{> "components/button" text="Subscribe" href="#/portal/signup" dataPortal="signup"
362
+ variant="outline" size="sm" class="bg-purple-600 hover:bg-purple-700 text-white"
363
+ }}
364
+
365
+ {{#> "components/card" heading="Join the publication" class="mx-auto max-w-md p-8"}}
366
+ <p>Your own content, in your own template.</p>
367
+ {{> "components/button" text="Learn more" href="/about/" class="rounded-xl"}}
368
+ {{/components/card}}
369
+
370
+ {{> "components/input" label="Email" type="email" name="email" required=true
371
+ hint="Used for replies only" hintId="contact-email-hint" inputClass="rounded-xl"
372
+ }}
373
+
374
+ {{> "components/post-grid" posts=posts heading="Latest stories" cardClass="rounded-xl"}}
375
+ {{> "components/author-list" heading="Our authors"}}
376
+ {{> "components/tag-grid" heading="Topics" cardVariant="outline"}}
377
+ {{#tag}}{{> "components/archive-header" eyebrow="Topic" archiveImage=feature_image}}{{/tag}}
378
+ ```
379
+
380
+ Use ordinary CSS classes instead of utilities in vanilla themes, with your stylesheet loaded after component defaults. Variants deliberately use low-specificity selectors. `input`'s root class styles the field wrapper; `inputClass` targets the control. Each label wraps its input, so no ID is required; provide a **unique** `hintId` with `hint` for an accessible help-text association. These inputs do not submit to Ghost by themselves. Use `newsletter-form` for native member signup.
381
+
382
+ Cards accept escaped `body` text or a trusted Handlebars partial block as above—never pass untrusted raw HTML. Partial calls follow normal Handlebars context inheritance: explicitly set/reset nested parameters (e.g. `class=""`, `variant="default"`) when you don't want an outer card's values. Button `href` values must come from trusted theme code or Ghost URLs; HTML escaping is not URL sanitization. Disabled links have no `href` or Portal action. Alerts default to `role="status"`; use `urgent=true` only for urgent dynamic announcements.
383
+
384
+ Adding a composed block installs missing dependencies first. **Existing dependency files are preserved even with `add -y`.** To replace a dependency deliberately, add that component explicitly. Requested root components use one overwrite decision each; Enter preserves existing files and continues. Custom partial aliases under `partials/` are reflected in nested references. Review `ghostcn diff` before merging updates.
385
+
386
+ `author-list` and `tag-grid` query up to 100 records; they are compact discovery blocks, not paginated directories. Use a custom paginated Ghost query with the reusable cards for larger archives. `post-grid` renders the collection you pass. Empty collections render nothing unless the block receives `emptyText`.
387
+
388
+ ### Local playground (unreleased)
389
+
390
+ Build the CLI in this repository, then invoke its absolute `packages/cli/dist/index.js` path from your **theme directory**:
391
+
392
+ ```bash
393
+ # Repository directory:
394
+ npm run build
395
+
396
+ # Theme directory, replacing the placeholder with this checkout's actual path:
397
+ node /absolute/path/to/ghost/packages/cli/dist/index.js add tag-grid
398
+ node /absolute/path/to/ghost/packages/cli/dist/index.js playground
399
+ # Optional: --port 4191 (or --port 0 for an available port)
400
+ ```
401
+
402
+ Open the printed localhost URL. The playground reads your installed partials and layout's local stylesheet links, shows controls for supported parameters, and reloads when theme files change. Keep `npm run dev` running in another terminal. Tailwind classes typed only into a preview field are not compiled automatically: add complete class literals to a scanned `.hbs` file first. Preview controls are temporary; copy the generated usage into your theme to save it.
403
+
404
+ The server binds to loopback only, rejects writes and unsafe/symlinked paths, and sandbox-previews synthetic data. It does not start Ghost, send emails, perform payments or change your theme files. Custom Ghost helpers, real query results, Portal, comments, access control and the rest of your theme must still be tested in Ghost. Stop with Ctrl+C.
405
+
406
+ The real-Ghost browser suite builds both styling systems in Light/Dark/Auto, exercises desktop/mobile layouts, reading navigation, real comments, and visitor/free/paid access. It runs an isolated database and content directory; it never changes your installed publication. See [the regression setup](tests/e2e/README.md) for prerequisites, commands, and coverage boundaries.
407
+
233
408
  ```bash
234
409
  # Install dependencies
235
410
  npm install
@@ -240,6 +415,12 @@ npm run build
240
415
  # Run automated tests
241
416
  npm test
242
417
 
418
+ # Local playground UI and documentation browser checks
419
+ npm run docs:build
420
+ npm run docs:check
421
+ npm run docs:browser
422
+ npm run test:playground
423
+
243
424
  # Verify theme compatibility with Ghost validator
244
425
  cd example-theme
245
426
  npx gscan .
@@ -1,4 +1,9 @@
1
1
  export interface AddOptions {
2
2
  yes?: boolean;
3
+ skipExisting?: boolean;
3
4
  }
4
- export declare function add(componentName?: string, options?: AddOptions): Promise<void>;
5
+ export declare function createOverwriteDecision(name: string, spinner: {
6
+ stop(): unknown;
7
+ start(): unknown;
8
+ }, interactive?: boolean): (relativePath: string) => Promise<boolean>;
9
+ export declare function add(componentNames?: string[] | string, options?: AddOptions): Promise<void>;
@@ -3,6 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.createOverwriteDecision = createOverwriteDecision;
6
7
  exports.add = add;
7
8
  const fs_1 = __importDefault(require("fs"));
8
9
  const path_1 = __importDefault(require("path"));
@@ -11,112 +12,149 @@ const chalk_1 = __importDefault(require("chalk"));
11
12
  const ora_1 = __importDefault(require("ora"));
12
13
  const registry_1 = require("../utils/registry");
13
14
  const component_installer_1 = require("../utils/component-installer");
14
- async function installSingleComponent(componentName, config, options) {
15
- let sanitizedName;
16
- try {
17
- sanitizedName = (0, registry_1.sanitizeComponentName)(componentName);
18
- }
19
- catch (err) {
20
- console.error(chalk_1.default.red(err.message));
21
- return false;
22
- }
23
- const cwd = process.cwd();
24
- const spinner = (0, ora_1.default)(`Fetching component "${sanitizedName}"...`).start();
15
+ class AddCancelled extends Error {
16
+ }
17
+ // One decision per requested component, never a spinner competing with a prompt.
18
+ // Installer mechanics and dependency preservation remain in the shared installer.
19
+ function createOverwriteDecision(name, spinner, interactive = Boolean(process.stdin.isTTY && process.stdout.isTTY)) {
20
+ let decision;
21
+ return async (relativePath) => {
22
+ if (decision !== undefined)
23
+ return decision;
24
+ spinner.stop();
25
+ if (!interactive)
26
+ return decision = false;
27
+ console.log(chalk_1.default.yellow(`Component "${name}" already has files, including ${relativePath}.`));
28
+ console.log(`Press Enter / N to keep existing files and continue; Y replaces this component's files.`);
29
+ console.log(`Review first: ghostcn diff ${name}. Cancel with Ctrl+C. Dependencies are preserved.`);
30
+ let cancelled = false;
31
+ const response = await (0, prompts_1.default)({
32
+ type: 'confirm', name: 'overwrite', message: `Replace existing files for "${name}"?`, initial: false
33
+ }, { onCancel: () => { cancelled = true; } });
34
+ if (cancelled)
35
+ throw new AddCancelled('Cancelled. Existing files were kept; earlier installs were not rolled back.');
36
+ decision = Boolean(response.overwrite);
37
+ spinner.start();
38
+ return decision;
39
+ };
40
+ }
41
+ async function installSingleComponent(name, config, options) {
42
+ const spinner = (0, ora_1.default)(`Installing component "${name}" (registry requests time out after 5 seconds)...`).start();
25
43
  let result;
26
44
  try {
27
45
  result = await (0, component_installer_1.installComponent)({
28
- themeRoot: cwd,
29
- componentName: sanitizedName,
30
- config,
31
- overwrite: options.yes,
32
- shouldOverwrite: async (relativePath) => {
33
- const response = await (0, prompts_1.default)({
34
- type: 'confirm',
35
- name: 'overwrite',
36
- message: `File ${relativePath} already exists. Overwrite?`,
37
- initial: false
38
- }, {
39
- onCancel: () => {
40
- console.log(chalk_1.default.yellow('\nOperation cancelled.'));
41
- process.exit(0);
42
- }
43
- });
44
- return Boolean(response.overwrite);
45
- }
46
+ themeRoot: process.cwd(), componentName: name, config, overwrite: options.yes,
47
+ shouldOverwrite: options.skipExisting ? async () => false : createOverwriteDecision(name, spinner)
46
48
  });
47
49
  }
48
50
  catch (error) {
51
+ if (error instanceof AddCancelled) {
52
+ spinner.stop();
53
+ console.log(chalk_1.default.yellow(error.message));
54
+ return 'cancelled';
55
+ }
49
56
  spinner.fail(chalk_1.default.red(error.message));
50
- return false;
57
+ console.error(`Check the component name and registry connection, then retry: ghostcn add ${name}`);
58
+ return 'failed';
59
+ }
60
+ const outcome = result.installed.length ? 'installed' : 'kept';
61
+ spinner.succeed(outcome === 'installed' ? `Installed "${name}".` : `Kept existing "${name}" files.`);
62
+ for (const dependency of result.dependencies || []) {
63
+ for (const file of dependency.installed)
64
+ console.log(chalk_1.default.green(` ✓ Dependency ${dependency.name}: installed ${file}`));
65
+ for (const file of dependency.skipped)
66
+ console.log(chalk_1.default.yellow(` - Dependency ${dependency.name}: preserved ${file}`));
67
+ }
68
+ for (const file of result.installed)
69
+ console.log(chalk_1.default.green(` ✓ Installed ${file}`));
70
+ for (const file of result.skipped)
71
+ console.log(chalk_1.default.yellow(` - Preserved ${file}`));
72
+ if (result.skipped.length) {
73
+ console.log(`Review changes: ghostcn diff ${name}`);
74
+ console.log(`To replace deliberately (back up first): ghostcn add ${name} --yes`);
51
75
  }
52
- spinner.succeed(`Found "${sanitizedName}"!`);
53
- for (const installed of result.installed)
54
- console.log(chalk_1.default.green(` ✓ Installed ${installed}`));
55
- for (const skipped of result.skipped)
56
- console.log(chalk_1.default.yellow(` - Skipped ${skipped}`));
57
76
  if (result.styleSync?.status === 'missing-template') {
58
77
  console.warn(chalk_1.default.yellow(' ⚠ default.hbs was not found, so component styles could not be linked automatically.'));
59
78
  }
60
79
  else if (result.styleSync?.status === 'updated') {
61
80
  console.log(chalk_1.default.green(' ✓ Updated the managed stylesheet links in default.hbs'));
62
81
  }
63
- console.log(chalk_1.default.bold.blue(`Component "${sanitizedName}" successfully installed!`));
64
- return true;
82
+ if (result.scriptSync?.status === 'updated')
83
+ console.log(chalk_1.default.green(' ✓ Updated managed component script links in default.hbs'));
84
+ if (result.scriptSync?.status === 'missing-template') {
85
+ console.warn(chalk_1.default.yellow(' ⚠ Add these script links before </body> in your layout:'));
86
+ for (const asset of result.scriptSync.assetPaths)
87
+ console.log(`<script defer src="{{asset "${asset}"}}"></script>`);
88
+ }
89
+ return outcome;
65
90
  }
66
- async function add(componentName, options = {}) {
67
- const cwd = process.cwd();
68
- const configPath = path_1.default.join(cwd, 'components.json');
91
+ async function add(componentNames = [], options = {}) {
92
+ if (options.yes && options.skipExisting) {
93
+ console.error('Choose either --yes (replace) or --skip-existing (preserve), not both.');
94
+ process.exitCode = 1;
95
+ return;
96
+ }
97
+ const configPath = path_1.default.join(process.cwd(), 'components.json');
69
98
  if (!fs_1.default.existsSync(configPath)) {
70
- console.error(chalk_1.default.red('components.json not found. Please run "npx ghostcn init" first.'));
71
- process.exit(1);
99
+ console.error(chalk_1.default.red('components.json not found. Run "ghostcn init" from your theme directory first.'));
100
+ process.exitCode = 1;
101
+ return;
72
102
  }
73
103
  let config;
104
+ let names;
74
105
  try {
75
- const raw = fs_1.default.readFileSync(configPath, 'utf8').replace(/^\uFEFF/, '');
76
- config = JSON.parse(raw);
77
- }
78
- catch {
79
- console.error(chalk_1.default.red('Could not parse components.json. Ensure it contains valid JSON.'));
80
- process.exit(1);
106
+ config = JSON.parse(fs_1.default.readFileSync(configPath, 'utf8').replace(/^\uFEFF/, ''));
107
+ names = [...new Set((typeof componentNames === 'string' ? [componentNames] : componentNames).map(registry_1.sanitizeComponentName))];
81
108
  }
82
- // If component name is provided directly, install it
83
- if (componentName) {
84
- const ok = await installSingleComponent(componentName, config, options);
85
- if (!ok)
86
- process.exit(1);
109
+ catch (error) {
110
+ console.error(chalk_1.default.red(error instanceof SyntaxError ? 'Could not parse components.json. Ensure it contains valid JSON.' : error.message));
111
+ process.exitCode = 1;
87
112
  return;
88
113
  }
89
- // If no component specified, display interactive selection
90
- const spinner = (0, ora_1.default)('Loading component catalog...').start();
91
- const availableItems = await (0, registry_1.getRegistryIndex)();
92
- spinner.stop();
93
- if (!availableItems || availableItems.length === 0) {
94
- console.error(chalk_1.default.red('No components found in the registry.'));
95
- process.exit(1);
96
- }
97
- const response = await (0, prompts_1.default)({
98
- type: 'multiselect',
99
- name: 'selected',
100
- message: 'Which components would you like to install?',
101
- choices: availableItems.map(item => ({
102
- title: `${item.name.padEnd(18)} ${chalk_1.default.dim(item.description)}`,
103
- value: item.name
104
- })),
105
- hint: '- Space to select. Return to submit'
106
- }, {
107
- onCancel: () => {
108
- console.log(chalk_1.default.yellow('\nCancelled.'));
109
- process.exit(0);
114
+ if (!names.length) {
115
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
116
+ console.error('Interactive selection requires a terminal. Specify names: ghostcn add button card --skip-existing');
117
+ process.exitCode = 1;
118
+ return;
119
+ }
120
+ const spinner = (0, ora_1.default)('Loading component catalog (registry requests time out after 5 seconds)...').start();
121
+ let availableItems;
122
+ try {
123
+ availableItems = await (0, registry_1.getRegistryIndex)();
124
+ }
125
+ finally {
126
+ spinner.stop();
127
+ }
128
+ if (!availableItems.length) {
129
+ console.error('No components found. Check your registry connection and retry "ghostcn list".');
130
+ process.exitCode = 1;
131
+ return;
132
+ }
133
+ let cancelled = false;
134
+ const response = await (0, prompts_1.default)({
135
+ type: 'multiselect', name: 'selected', message: 'Which components would you like to install?',
136
+ choices: availableItems.map(item => ({ title: `${item.name.padEnd(18)} ${chalk_1.default.dim(item.description)}`, value: item.name })),
137
+ hint: '- Space to select. Return to submit. Ctrl+C to cancel.'
138
+ }, { onCancel: () => { cancelled = true; } });
139
+ if (cancelled) {
140
+ console.log('Cancelled. No components were installed.');
141
+ return;
142
+ }
143
+ names = response.selected || [];
144
+ if (!names.length) {
145
+ console.log('No components selected. Exiting.');
146
+ return;
110
147
  }
111
- });
112
- if (!response.selected || response.selected.length === 0) {
113
- console.log(chalk_1.default.yellow('No components selected. Exiting.'));
114
- return;
115
148
  }
116
- console.log(chalk_1.default.blue(`\nInstalling ${response.selected.length} component(s)...\n`));
117
- for (const item of response.selected) {
118
- await installSingleComponent(item, config, options);
119
- console.log('');
149
+ console.log(chalk_1.default.blue(`Installing ${names.length} component(s)...`));
150
+ const counts = { installed: 0, kept: 0, failed: 0 };
151
+ for (const name of names) {
152
+ const outcome = await installSingleComponent(name, config, options);
153
+ if (outcome === 'cancelled')
154
+ return;
155
+ counts[outcome]++;
120
156
  }
121
- console.log(chalk_1.default.bold.green('All selected components have been installed!'));
157
+ console.log(`Finished: ${counts.installed} installed, ${counts.kept} kept existing, ${counts.failed} failed.`);
158
+ if (counts.failed)
159
+ process.exitCode = 1;
122
160
  }
@@ -0,0 +1,5 @@
1
+ export declare function diff(component: string | undefined, options?: {
2
+ latest?: boolean;
3
+ summary?: boolean;
4
+ json?: boolean;
5
+ }): Promise<void>;
@@ -0,0 +1,54 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.diff = diff;
7
+ const fs_1 = __importDefault(require("fs"));
8
+ const path_1 = __importDefault(require("path"));
9
+ const component_diff_1 = require("../utils/component-diff");
10
+ const registry_1 = require("../utils/registry");
11
+ const component_history_1 = require("../utils/component-history");
12
+ const component_files_1 = require("../utils/component-files");
13
+ async function diff(component, options = {}) {
14
+ try {
15
+ const root = process.cwd();
16
+ const config = JSON.parse(fs_1.default.readFileSync(path_1.default.join(root, 'components.json'), 'utf8').replace(/^\uFEFF/, ''));
17
+ let names;
18
+ if (component)
19
+ names = [(0, registry_1.sanitizeComponentName)(component)];
20
+ else {
21
+ const tracked = Object.keys((0, component_history_1.readHistory)(root).components);
22
+ const installed = [];
23
+ for (const item of await (0, registry_1.getRegistryIndex)()) {
24
+ const manifest = await (0, component_diff_1.comparisonManifest)(item.name, false);
25
+ if ((0, component_files_1.componentFiles)(root, config, manifest).some(file => fs_1.default.existsSync(file.target)))
26
+ installed.push(item.name);
27
+ }
28
+ names = [...new Set([...tracked, ...installed])];
29
+ }
30
+ const results = [];
31
+ for (const name of names)
32
+ results.push((0, component_diff_1.compareComponent)(root, config, await (0, component_diff_1.comparisonManifest)(name, !!options.latest)));
33
+ if (options.json)
34
+ console.log(JSON.stringify({ source: options.latest ? 'latest-registry' : 'installed-cli-registry', components: results }, null, 2));
35
+ else {
36
+ console.log(`Read-only comparison against ${options.latest ? 'the latest registry (main), not necessarily the latest npm release' : 'this CLI\'s registry'}. No files are changed.`);
37
+ if (!results.length)
38
+ console.log('No installed components found.');
39
+ for (const result of results) {
40
+ console.log(`\n${result.name}: ${result.installedRevision?.slice(0, 12) || 'unknown baseline'} -> ${result.incomingRevision.slice(0, 12)}`);
41
+ for (const file of result.files) {
42
+ console.log(` ${file.status}: ${file.path}`);
43
+ if (!options.summary && file.local !== file.incoming)
44
+ console.log((0, component_diff_1.unifiedDiff)(file.local, file.incoming, file.path));
45
+ }
46
+ }
47
+ console.log('\nKeep your local files; manually merge the changes you want. Do not use add -y to review updates.');
48
+ }
49
+ }
50
+ catch (error) {
51
+ console.error(`Could not compare components: ${error.message}`);
52
+ process.exitCode = 1;
53
+ }
54
+ }
@@ -0,0 +1,3 @@
1
+ export declare function playground(options?: {
2
+ port?: string;
3
+ }): Promise<void>;
@@ -0,0 +1,29 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.playground = playground;
4
+ const playground_server_1 = require("../utils/playground-server");
5
+ async function playground(options = {}) {
6
+ try {
7
+ if (options.port !== undefined && !/^\d+$/.test(options.port))
8
+ throw new Error('Port must be an integer between 0 and 65535.');
9
+ const runtime = await (0, playground_server_1.startPlayground)({ themeRoot: process.cwd(), port: options.port === undefined ? undefined : Number(options.port) });
10
+ console.log(`Ghostcn playground: ${runtime.url}`);
11
+ console.log('Read-only previews of installed components with synthetic content. Keep npm run dev running for CSS changes.');
12
+ console.log('Press Ctrl+C to stop.');
13
+ let stopping = false;
14
+ const stop = async () => {
15
+ if (stopping)
16
+ return;
17
+ stopping = true;
18
+ process.off('SIGINT', stop);
19
+ process.off('SIGTERM', stop);
20
+ await runtime.close();
21
+ };
22
+ process.on('SIGINT', stop);
23
+ process.on('SIGTERM', stop);
24
+ }
25
+ catch (error) {
26
+ console.error(error.message);
27
+ process.exitCode = 1;
28
+ }
29
+ }
package/dist/index.js CHANGED
@@ -11,6 +11,8 @@ const list_1 = require("./commands/list");
11
11
  const create_1 = require("./commands/create");
12
12
  const doctor_1 = require("./commands/doctor");
13
13
  const pack_1 = require("./commands/pack");
14
+ const diff_1 = require("./commands/diff");
15
+ const playground_1 = require("./commands/playground");
14
16
  const package_json_1 = __importDefault(require("../package.json"));
15
17
  function main() {
16
18
  const program = new commander_1.Command()
@@ -36,11 +38,23 @@ function main() {
36
38
  program
37
39
  .command('add')
38
40
  .description('Add one or more components to your Ghost theme')
39
- .argument('[component]', 'The component to add (leave blank for interactive selection)')
41
+ .argument('[components...]', 'Component names to add (leave blank for interactive selection)')
40
42
  .option('-y, --yes', 'Overwrite existing files without prompting')
43
+ .option('--skip-existing', 'Keep existing files and install missing files without prompting')
41
44
  .action(add_1.add);
42
45
  program.command('doctor').description('Check theme configuration, local assets, partials and build readiness').action(doctor_1.doctor);
46
+ program.command('diff').description('Review component changes without writing or overwriting any files')
47
+ .argument('[component]', 'Compare one component, or all installed components')
48
+ .option('--latest', 'Compare with the latest remote registry (main); fail if unavailable')
49
+ .option('--summary', 'Show file statuses without full diffs')
50
+ .option('--json', 'Return machine-readable comparisons with baseline, local and registry content')
51
+ .action(diff_1.diff);
43
52
  program.command('pack').description('Package built theme runtime files as a Ghost-uploadable ZIP').action(pack_1.pack);
44
- program.parse();
53
+ program.command('playground').description('Preview installed components locally with synthetic content (read-only)')
54
+ .option('--port <number>', 'Local loopback port (0 chooses an available port)', '4190').action(playground_1.playground);
55
+ program.parseAsync().catch(error => {
56
+ console.error(error.message);
57
+ process.exitCode = 1;
58
+ });
45
59
  }
46
60
  main();