ghostcn 1.1.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 (70) hide show
  1. package/README.md +225 -3
  2. package/dist/commands/add.d.ts +6 -1
  3. package/dist/commands/add.js +121 -83
  4. package/dist/commands/create.js +8 -1
  5. package/dist/commands/diff.d.ts +5 -0
  6. package/dist/commands/diff.js +54 -0
  7. package/dist/commands/doctor.d.ts +1 -0
  8. package/dist/commands/doctor.js +7 -0
  9. package/dist/commands/init.js +5 -0
  10. package/dist/commands/pack.d.ts +1 -0
  11. package/dist/commands/pack.js +8 -0
  12. package/dist/commands/playground.d.ts +3 -0
  13. package/dist/commands/playground.js +29 -0
  14. package/dist/index.js +20 -2
  15. package/dist/registry/components/alert.json +62 -0
  16. package/dist/registry/components/archive-header.json +57 -0
  17. package/dist/registry/components/author-card.json +23 -2
  18. package/dist/registry/components/author-list.json +55 -0
  19. package/dist/registry/components/badge.json +51 -0
  20. package/dist/registry/components/button.json +74 -0
  21. package/dist/registry/components/card.json +70 -0
  22. package/dist/registry/components/featured-posts.json +18 -1
  23. package/dist/registry/components/input.json +94 -0
  24. package/dist/registry/components/member-cta.json +15 -1
  25. package/dist/registry/components/newsletter-form.json +23 -2
  26. package/dist/registry/components/pagination.json +12 -1
  27. package/dist/registry/components/post-card.json +25 -2
  28. package/dist/registry/components/post-grid.json +54 -0
  29. package/dist/registry/components/post-header.json +18 -1
  30. package/dist/registry/components/post-navigation.json +41 -0
  31. package/dist/registry/components/pricing-table.json +34 -5
  32. package/dist/registry/components/related-posts.json +53 -0
  33. package/dist/registry/components/site-footer.json +15 -1
  34. package/dist/registry/components/site-header.json +17 -2
  35. package/dist/registry/components/table-of-contents.json +47 -0
  36. package/dist/registry/components/tag-grid.json +64 -0
  37. package/dist/registry/components/tag-list.json +38 -0
  38. package/dist/registry/index.json +131 -0
  39. package/dist/templates/playground/index.html +5 -0
  40. package/dist/templates/playground/playground.css +18 -0
  41. package/dist/templates/playground/playground.js +71 -0
  42. package/dist/templates/playground/preview.css +5 -0
  43. package/dist/templates/playground/preview.js +12 -0
  44. package/dist/templates/theme-tools.mjs +178 -0
  45. package/dist/utils/component-diff.d.ts +18 -0
  46. package/dist/utils/component-diff.js +93 -0
  47. package/dist/utils/component-files.d.ts +9 -0
  48. package/dist/utils/component-files.js +48 -0
  49. package/dist/utils/component-history.d.ts +11 -0
  50. package/dist/utils/component-history.js +47 -0
  51. package/dist/utils/component-installer.d.ts +2 -0
  52. package/dist/utils/component-installer.js +34 -36
  53. package/dist/utils/component-plan.d.ts +7 -0
  54. package/dist/utils/component-plan.js +43 -0
  55. package/dist/utils/playground-server.d.ts +9 -0
  56. package/dist/utils/playground-server.js +189 -0
  57. package/dist/utils/preview-renderer.d.ts +143 -0
  58. package/dist/utils/preview-renderer.js +70 -0
  59. package/dist/utils/registry.d.ts +7 -0
  60. package/dist/utils/registry.js +12 -18
  61. package/dist/utils/styles.d.ts +3 -0
  62. package/dist/utils/styles.js +20 -0
  63. package/dist/utils/theme-files.d.ts +2 -0
  64. package/dist/utils/theme-files.js +46 -4
  65. package/dist/utils/theme-project.js +9 -4
  66. package/dist/utils/theme-scaffold.js +61 -24
  67. package/dist/utils/theme-tooling.d.ts +2 -0
  68. package/dist/utils/theme-tooling.js +20 -0
  69. package/dist/utils/theme.js +4 -2
  70. package/package.json +6 -4
@@ -0,0 +1,178 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+
5
+ function inside(root, relative) {
6
+ const target = path.resolve(root, relative);
7
+ if (target === root || !target.startsWith(root + path.sep)) throw new Error(`Path escapes theme: ${relative}`);
8
+ // Never follow links when inspecting or packaging a theme.
9
+ let current = root;
10
+ for (const part of path.relative(root, target).split(path.sep)) {
11
+ current = path.join(current, part);
12
+ if (fs.existsSync(current) && fs.lstatSync(current).isSymbolicLink()) throw new Error(`Symlink is not supported: ${relative}`);
13
+ }
14
+ return target;
15
+ }
16
+
17
+ export function inspectTheme(themeRoot) {
18
+ const root = path.resolve(themeRoot);
19
+ const errors = [], warnings = [];
20
+ const exists = relative => fs.existsSync(inside(root, relative));
21
+ const read = relative => fs.readFileSync(inside(root, relative), 'utf8').replace(/^\uFEFF/, '');
22
+ let pkg, config;
23
+ try {
24
+ for (const required of ['package.json', 'default.hbs', 'index.hbs']) {
25
+ if (!exists(required)) errors.push(`Missing ${required}`);
26
+ }
27
+ if (exists('package.json')) {
28
+ pkg = JSON.parse(read('package.json'));
29
+ if (!pkg.engines?.ghost) errors.push('package.json needs engines.ghost');
30
+ if (!pkg.author?.email) errors.push('package.json needs author.email');
31
+ }
32
+ if (exists('components.json')) {
33
+ config = JSON.parse(read('components.json'));
34
+ if (!['tailwind', 'css'].includes(config.style)) errors.push('components.json style must be tailwind or css');
35
+ for (const relative of [config.cssFile, config.aliases?.styles, config.aliases?.partials]) {
36
+ if (typeof relative !== 'string' || !relative.trim()) errors.push('components.json needs cssFile and partials/styles aliases');
37
+ else if (!exists(relative)) errors.push(`Missing configured path: ${relative}`);
38
+ }
39
+ if (config.style === 'tailwind' && !pkg?.devDependencies?.tailwindcss && !pkg?.dependencies?.tailwindcss) {
40
+ warnings.push('Tailwind selected but no local tailwindcss dependency. Configure a build pipeline before using utilities.');
41
+ }
42
+ if (config.style === 'tailwind' && !pkg?.scripts?.build) warnings.push('No build script is configured. Tailwind classes need compiled CSS loaded by your layout.');
43
+ } else warnings.push('No components.json. Run ghostcn init if you want to install components.');
44
+ const scan = (dir, visit) => {
45
+ for (const entry of fs.readdirSync(inside(root, dir), { withFileTypes: true })) {
46
+ const relative = path.posix.join(dir, entry.name);
47
+ inside(root, relative);
48
+ if (entry.isDirectory()) scan(relative, visit);
49
+ else if (entry.isFile()) visit(relative);
50
+ }
51
+ };
52
+ const templates = fs.readdirSync(root).filter(name => name.endsWith('.hbs'));
53
+ if (exists('partials')) scan('partials', file => { if (file.endsWith('.hbs')) templates.push(file); });
54
+ for (const file of templates) {
55
+ const source = read(file).replace(/\{\{!--[\s\S]*?--\}\}/g, '');
56
+ for (const match of source.matchAll(/\{\{asset\s+["']([^"']+)["']/g)) {
57
+ if (!exists(`assets/${match[1]}`)) errors.push(`${file}: missing asset ${match[1]} (run your build)`);
58
+ }
59
+ for (const match of source.matchAll(/\{\{(?:#>|>)\s*["']([^"']+)["']/g)) {
60
+ if (!exists(`partials/${match[1]}.hbs`)) errors.push(`${file}: missing partial ${match[1]}`);
61
+ }
62
+ }
63
+ if (exists('default.hbs')) {
64
+ const layout = read('default.hbs');
65
+ const linked = new Set();
66
+ for (const tag of layout.replace(/\{\{!--[\s\S]*?--\}\}/g, '').matchAll(/<link\b[^>]*>/gi)) {
67
+ if (!/\brel\s*=\s*["']stylesheet["']/i.test(tag[0])) continue;
68
+ const asset = tag[0].match(/\{\{asset\s+["']([^"']+)["']/);
69
+ if (asset) linked.add(asset[1]);
70
+ }
71
+ for (const helper of ['ghost_head', 'ghost_foot']) {
72
+ if (!new RegExp(`\\{\\{\\s*${helper}\\s*\\}\\}`).test(layout)) errors.push(`default.hbs needs {{${helper}}}`);
73
+ }
74
+ if (config && !linked.has(path.relative(path.join(root, 'assets'), inside(root, config.cssFile)).replaceAll('\\', '/'))) {
75
+ errors.push('default.hbs does not link the configured ghostcn stylesheet');
76
+ }
77
+ if (config?.aliases?.styles && exists(config.aliases.styles)) {
78
+ for (const name of fs.readdirSync(inside(root, config.aliases.styles)).filter(name => name.endsWith('.css'))) {
79
+ const asset = path.relative(path.join(root, 'assets'), inside(root, path.join(config.aliases.styles, name))).replaceAll('\\', '/');
80
+ if (!linked.has(asset)) errors.push(`default.hbs does not link component stylesheet ${asset}`);
81
+ }
82
+ }
83
+ }
84
+ } catch (error) { errors.push(error.message); }
85
+ return { errors: [...new Set(errors)], warnings: [...new Set(warnings)] };
86
+ }
87
+
88
+ function crc32(buffer) {
89
+ let crc = 0xffffffff;
90
+ for (const byte of buffer) {
91
+ crc ^= byte;
92
+ for (let bit = 0; bit < 8; bit++) crc = (crc >>> 1) ^ ((crc & 1) ? 0xedb88320 : 0);
93
+ }
94
+ return (crc ^ 0xffffffff) >>> 0;
95
+ }
96
+
97
+ export function packageTheme(themeRoot) {
98
+ const root = path.resolve(themeRoot);
99
+ const result = inspectTheme(root);
100
+ if (result.errors.length) throw new Error(result.errors.join('\n'));
101
+ const pkg = JSON.parse(fs.readFileSync(inside(root, 'package.json'), 'utf8'));
102
+ if (!/^[a-z0-9][a-z0-9-]*$/.test(pkg.name) || !/^\d+\.\d+\.\d+(?:-[a-zA-Z0-9.-]+)?$/.test(pkg.version)) {
103
+ throw new Error('Packaging needs a safe lowercase theme name and a semantic version in package.json');
104
+ }
105
+ const files = fs.readdirSync(root).filter(name => name.endsWith('.hbs') || ['package.json', 'LICENSE', 'LICENSE.md'].includes(name));
106
+ // Keep a source stylesheet if an existing theme actually links it at runtime.
107
+ const sourceStyles = new Set(['assets/css/source.css', 'assets/css/ghostcn-tailwind.css']);
108
+ const linkedStyles = new Set();
109
+ const findLinks = dir => {
110
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
111
+ if (entry.name.startsWith('.') || entry.name === 'node_modules' || entry.name === 'dist' || entry.name === 'assets') continue;
112
+ const target = path.join(dir, entry.name);
113
+ if (entry.isDirectory() && entry.name === 'partials') {
114
+ inside(root, path.relative(root, target));
115
+ findLinks(target);
116
+ }
117
+ else if (entry.isFile() && entry.name.endsWith('.hbs')) {
118
+ inside(root, path.relative(root, target));
119
+ for (const match of fs.readFileSync(target, 'utf8').matchAll(/\{\{asset\s+["']([^"']+)["']/g)) linkedStyles.add(`assets/${match[1]}`);
120
+ }
121
+ }
122
+ };
123
+ findLinks(root);
124
+ const collect = dir => {
125
+ for (const entry of fs.readdirSync(inside(root, dir), { withFileTypes: true })) {
126
+ if (entry.name.startsWith('.') || entry.name === 'node_modules') continue;
127
+ const relative = path.posix.join(dir, entry.name);
128
+ inside(root, relative);
129
+ if (entry.isDirectory()) collect(relative);
130
+ else if (entry.isFile() && !relative.endsWith('.map') && (!sourceStyles.has(relative) || linkedStyles.has(relative))) files.push(relative);
131
+ }
132
+ };
133
+ for (const dir of ['partials', 'assets']) if (fs.existsSync(inside(root, dir))) collect(dir);
134
+ const chunks = [], directory = [];
135
+ let offset = 0;
136
+ for (const file of files.sort()) {
137
+ const name = Buffer.from(file.replaceAll('\\', '/'));
138
+ const data = fs.readFileSync(inside(root, file));
139
+ const crc = crc32(data);
140
+ const local = Buffer.alloc(30);
141
+ local.writeUInt32LE(0x04034b50); local.writeUInt16LE(20, 4); local.writeUInt16LE(0x800, 6);
142
+ local.writeUInt16LE(33, 12); // 1980-01-01: deterministic archive timestamps
143
+ local.writeUInt32LE(crc, 14); local.writeUInt32LE(data.length, 18); local.writeUInt32LE(data.length, 22); local.writeUInt16LE(name.length, 26);
144
+ chunks.push(local, name, data);
145
+ const central = Buffer.alloc(46);
146
+ central.writeUInt32LE(0x02014b50); central.writeUInt16LE(20, 4); central.writeUInt16LE(20, 6); central.writeUInt16LE(0x800, 8);
147
+ central.writeUInt16LE(33, 14); central.writeUInt32LE(crc, 16); central.writeUInt32LE(data.length, 20); central.writeUInt32LE(data.length, 24);
148
+ central.writeUInt16LE(name.length, 28); central.writeUInt32LE(offset, 42);
149
+ directory.push(central, name);
150
+ offset += local.length + name.length + data.length;
151
+ }
152
+ if (files.length > 65535 || offset > 0xffffffff) throw new Error('Theme exceeds ZIP32 limits');
153
+ const central = Buffer.concat(directory), end = Buffer.alloc(22);
154
+ end.writeUInt32LE(0x06054b50); end.writeUInt16LE(files.length, 8); end.writeUInt16LE(files.length, 10);
155
+ end.writeUInt32LE(central.length, 12); end.writeUInt32LE(offset, 16);
156
+ const dist = inside(root, 'dist');
157
+ fs.mkdirSync(dist, { recursive: true });
158
+ const output = inside(root, `dist/${pkg.name}-${pkg.version}.zip`);
159
+ fs.writeFileSync(output, Buffer.concat([...chunks, central, end]));
160
+ return { output, files };
161
+ }
162
+
163
+ export function reportTheme(themeRoot) {
164
+ const result = inspectTheme(themeRoot);
165
+ for (const warning of result.warnings) console.warn(`WARN: ${warning}`);
166
+ for (const error of result.errors) console.error(`ERROR: ${error}`);
167
+ if (result.errors.length) return false;
168
+ console.log('Theme checks passed. Run the official gscan validator before publishing.');
169
+ return true;
170
+ }
171
+
172
+ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
173
+ const root = path.resolve(process.argv[3] || process.cwd());
174
+ try {
175
+ if (process.argv[2] === 'pack') console.log(`Created ${packageTheme(root).output}`);
176
+ else if (!reportTheme(root)) process.exitCode = 1;
177
+ } catch (error) { console.error(error.message); process.exitCode = 1; }
178
+ }
@@ -0,0 +1,18 @@
1
+ import { ComponentManifest } from './registry';
2
+ import { GhostcnConfig } from './theme-project';
3
+ export type FileStatus = 'unchanged' | 'upstream-changed' | 'locally-modified' | 'conflict' | 'missing' | 'untracked' | 'removed-upstream';
4
+ export interface FileComparison {
5
+ path: string;
6
+ status: FileStatus;
7
+ baseline?: string;
8
+ local?: string;
9
+ incoming?: string;
10
+ }
11
+ export declare function comparisonManifest(name: string, latest: boolean): Promise<ComponentManifest>;
12
+ export declare function compareComponent(themeRoot: string, config: GhostcnConfig, manifest: ComponentManifest): {
13
+ name: string;
14
+ installedRevision: string;
15
+ incomingRevision: string;
16
+ files: FileComparison[];
17
+ };
18
+ export declare function unifiedDiff(before: string | undefined, after: string | undefined, label: string): string;
@@ -0,0 +1,93 @@
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.comparisonManifest = comparisonManifest;
7
+ exports.compareComponent = compareComponent;
8
+ exports.unifiedDiff = unifiedDiff;
9
+ const fs_1 = __importDefault(require("fs"));
10
+ const registry_1 = require("./registry");
11
+ const component_files_1 = require("./component-files");
12
+ const component_history_1 = require("./component-history");
13
+ async function comparisonManifest(name, latest) {
14
+ name = (0, registry_1.sanitizeComponentName)(name);
15
+ if (!latest) {
16
+ const manifest = await (0, registry_1.getComponent)(name);
17
+ if (!manifest)
18
+ throw new Error(`Component "${name}" was not found.`);
19
+ return manifest;
20
+ }
21
+ // A latest comparison must never silently fall back to a stale bundled registry.
22
+ const base = process.env.GHOST_UI_REGISTRY_URL || registry_1.DEFAULT_REGISTRY_URL;
23
+ const url = new URL(`${base.replace(/\/$/, '')}/components/${name}.json`);
24
+ if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password)
25
+ throw new Error('Invalid registry URL.');
26
+ const manifest = await (0, registry_1.fetchRegistryJson)(url.href, 10000);
27
+ if (manifest.name !== name || !Array.isArray(manifest.files))
28
+ throw new Error('Registry returned an invalid component manifest.');
29
+ return manifest;
30
+ }
31
+ function compareComponent(themeRoot, config, manifest) {
32
+ const files = (0, component_files_1.componentFiles)(themeRoot, config, manifest);
33
+ const saved = (0, component_history_1.readHistory)(themeRoot).components[manifest.name];
34
+ const incoming = Object.fromEntries(files.map(file => [file.relative, file.content]));
35
+ const paths = [...new Set([...Object.keys(incoming), ...Object.keys(saved?.files || {})])].sort();
36
+ const comparisons = paths.map(relative => {
37
+ const target = (0, component_files_1.safeThemePath)(themeRoot, relative);
38
+ const baseline = saved?.files[relative];
39
+ const local = fs_1.default.existsSync(target) ? fs_1.default.readFileSync(target, 'utf8') : undefined;
40
+ const next = incoming[relative];
41
+ let status;
42
+ if (next === undefined)
43
+ status = 'removed-upstream';
44
+ else if (local === undefined)
45
+ status = 'missing';
46
+ else if (local === next)
47
+ status = 'unchanged';
48
+ else if (baseline === undefined)
49
+ status = 'untracked';
50
+ else if (baseline === next)
51
+ status = 'locally-modified';
52
+ else if (baseline === local)
53
+ status = 'upstream-changed';
54
+ else
55
+ status = 'conflict';
56
+ return { path: relative, status, baseline, local, incoming: next };
57
+ });
58
+ return { name: manifest.name, installedRevision: saved?.revision, incomingRevision: (0, component_history_1.revision)(incoming), files: comparisons };
59
+ }
60
+ // Complete line diff with bounded memory. Large files remain reviewable as replacement hunks.
61
+ function unifiedDiff(before, after, label) {
62
+ if (before === after)
63
+ return '';
64
+ const split = (value) => value?.replace(/\r\n/g, '\n').match(/[^\n]*\n|[^\n]+$/g) || [];
65
+ const a = split(before);
66
+ const b = split(after);
67
+ const lines = [`--- ${label} (local)`, `+++ ${label} (registry)`, `@@ -${a.length ? 1 : 0},${a.length} +${b.length ? 1 : 0},${b.length} @@`];
68
+ const emit = (prefix, value) => {
69
+ lines.push(prefix + (value.endsWith('\n') ? value.slice(0, -1) : value));
70
+ if (!value.endsWith('\n'))
71
+ lines.push('\');
72
+ };
73
+ if (a.length * b.length > 1_000_000) {
74
+ a.forEach(value => emit('-', value));
75
+ b.forEach(value => emit('+', value));
76
+ return lines.join('\n');
77
+ }
78
+ const width = b.length + 1;
79
+ const matrix = new Uint32Array((a.length + 1) * width);
80
+ for (let i = a.length - 1; i >= 0; i--)
81
+ for (let j = b.length - 1; j >= 0; j--)
82
+ matrix[i * width + j] = a[i] === b[j] ? 1 + matrix[(i + 1) * width + j + 1] : Math.max(matrix[(i + 1) * width + j], matrix[i * width + j + 1]);
83
+ let i = 0, j = 0;
84
+ while (i < a.length || j < b.length) {
85
+ if (i < a.length && j < b.length && a[i] === b[j])
86
+ emit(' ', a[i++]), j++;
87
+ else if (i < a.length && (j === b.length || matrix[(i + 1) * width + j] >= matrix[i * width + j + 1]))
88
+ emit('-', a[i++]);
89
+ else
90
+ emit('+', b[j++]);
91
+ }
92
+ return lines.join('\n');
93
+ }
@@ -0,0 +1,9 @@
1
+ import { ComponentManifest } from './registry';
2
+ import { GhostcnConfig } from './theme-project';
3
+ export { safeThemePath } from './theme-files';
4
+ export declare function componentPartialName(config: GhostcnConfig, name: string): string;
5
+ export declare function componentFiles(themeRoot: string, config: GhostcnConfig, manifest: ComponentManifest): {
6
+ relative: string;
7
+ target: string;
8
+ content: string;
9
+ }[];
@@ -0,0 +1,48 @@
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.safeThemePath = void 0;
7
+ exports.componentPartialName = componentPartialName;
8
+ exports.componentFiles = componentFiles;
9
+ const path_1 = __importDefault(require("path"));
10
+ const fs_1 = __importDefault(require("fs"));
11
+ const theme_files_1 = require("./theme-files");
12
+ const styles_1 = require("./styles");
13
+ var theme_files_2 = require("./theme-files");
14
+ Object.defineProperty(exports, "safeThemePath", { enumerable: true, get: function () { return theme_files_2.safeThemePath; } });
15
+ function componentPartialName(config, name) {
16
+ const directory = path_1.default.posix.normalize((config.aliases?.partials || 'partials/components').replace(/\\/g, '/'));
17
+ if (directory !== 'partials' && !directory.startsWith('partials/'))
18
+ throw new Error('Component partials must live under partials/ for Ghost to load them.');
19
+ return [directory.slice('partials'.length).replace(/^\//, ''), name].filter(Boolean).join('/');
20
+ }
21
+ function aliasedPartial(content, config) {
22
+ // Rewrite only static component invocations, including partial blocks and their closing tags.
23
+ // Shared by diff and install: incoming content and saved baselines use identical aliasing.
24
+ return content.replace(/(\{\{(?:#>|>|\/)\s*)(["']?)components\/([a-z0-9-]+)(\2)(?=[\s}])/g, (_all, prefix, quote, name) => `${prefix}${quote}${componentPartialName(config, name)}${quote}`);
25
+ }
26
+ // Shared by installation and read-only comparisons so aliases and CSS layers cannot drift.
27
+ function componentFiles(themeRoot, config, manifest) {
28
+ const targets = new Set();
29
+ return manifest.files.map(file => {
30
+ if (path_1.default.basename(file.name) !== file.name || /[\\/]/.test(file.name))
31
+ throw new Error('Unsafe component file name.');
32
+ const aliases = { partial: config.aliases?.partials || 'partials/components', style: config.aliases?.styles || 'assets/css/components', js: config.aliases?.js || 'assets/js/components' };
33
+ if (!['partial', 'style', 'js'].includes(file.type) || typeof file.content !== 'string')
34
+ throw new Error('Invalid component file.');
35
+ const relative = file.placement === 'theme' ? file.target : path_1.default.join(aliases[file.type], file.name);
36
+ if (!relative)
37
+ throw new Error('Missing component target.');
38
+ const target = (0, theme_files_1.safeThemePath)(themeRoot, relative);
39
+ if (fs_1.default.existsSync(target) && !fs_1.default.statSync(target).isFile())
40
+ throw new Error('Component target must be a file, not a directory.');
41
+ if (file.type === 'style' || file.type === 'js')
42
+ (0, theme_files_1.toGhostAssetPath)(relative);
43
+ if (targets.has(target))
44
+ throw new Error('Duplicate component target.');
45
+ targets.add(target);
46
+ return { relative: path_1.default.relative(path_1.default.resolve(themeRoot), target).replace(/\\/g, '/'), target, content: file.type === 'style' ? (0, styles_1.componentCss)(file.content, config.style) : file.type === 'partial' ? aliasedPartial(file.content, config) : file.content };
47
+ });
48
+ }
@@ -0,0 +1,11 @@
1
+ export interface InstalledComponent {
2
+ revision: string;
3
+ files: Record<string, string>;
4
+ }
5
+ export interface ComponentHistory {
6
+ schema: 1;
7
+ components: Record<string, InstalledComponent>;
8
+ }
9
+ export declare function revision(files: Record<string, string>): string;
10
+ export declare function readHistory(themeRoot: string): ComponentHistory;
11
+ export declare function recordInstalledFiles(themeRoot: string, name: string, files: Record<string, string>): void;
@@ -0,0 +1,47 @@
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.revision = revision;
7
+ exports.readHistory = readHistory;
8
+ exports.recordInstalledFiles = recordInstalledFiles;
9
+ const fs_1 = __importDefault(require("fs"));
10
+ const crypto_1 = require("crypto");
11
+ const path_1 = __importDefault(require("path"));
12
+ const component_files_1 = require("./component-files");
13
+ const registry_1 = require("./registry");
14
+ function revision(files) {
15
+ return (0, crypto_1.createHash)('sha256').update(JSON.stringify(Object.entries(files).sort(([a], [b]) => a.localeCompare(b)))).digest('hex');
16
+ }
17
+ function readHistory(themeRoot) {
18
+ const target = (0, component_files_1.safeThemePath)(themeRoot, '.ghostcn/installed.json');
19
+ if (!fs_1.default.existsSync(target))
20
+ return { schema: 1, components: {} };
21
+ const state = JSON.parse(fs_1.default.readFileSync(target, 'utf8'));
22
+ if (state.schema !== 1 || !state.components || Array.isArray(state.components) || typeof state.components !== 'object')
23
+ throw new Error('Invalid .ghostcn/installed.json; preserve it and repair before continuing.');
24
+ for (const [name, entry] of Object.entries(state.components)) {
25
+ (0, registry_1.sanitizeComponentName)(name);
26
+ if (!entry || typeof entry.revision !== 'string' || !entry.files || typeof entry.files !== 'object' || Array.isArray(entry.files))
27
+ throw new Error('Invalid component history.');
28
+ for (const [relative, content] of Object.entries(entry.files)) {
29
+ (0, component_files_1.safeThemePath)(themeRoot, relative);
30
+ if (typeof content !== 'string')
31
+ throw new Error('Invalid component baseline.');
32
+ }
33
+ if (revision(entry.files) !== entry.revision)
34
+ throw new Error('Component history checksum mismatch; preserve it and repair before continuing.');
35
+ }
36
+ return state;
37
+ }
38
+ function recordInstalledFiles(themeRoot, name, files) {
39
+ const state = readHistory(themeRoot);
40
+ const previous = state.components[name]?.files || {};
41
+ // Skipped files keep their prior baseline; never pretend a customization was an upstream original.
42
+ const merged = { ...previous, ...files };
43
+ state.components[name] = { revision: revision(merged), files: merged };
44
+ const target = (0, component_files_1.safeThemePath)(themeRoot, '.ghostcn/installed.json');
45
+ fs_1.default.mkdirSync(path_1.default.dirname(target), { recursive: true });
46
+ fs_1.default.writeFileSync(target, JSON.stringify(state, null, 2) + '\n', 'utf8');
47
+ }
@@ -12,5 +12,7 @@ export interface InstallComponentResult {
12
12
  installed: string[];
13
13
  skipped: string[];
14
14
  styleSync?: StyleSyncResult;
15
+ scriptSync?: StyleSyncResult;
16
+ dependencies?: InstallComponentResult[];
15
17
  }
16
18
  export declare function installComponent(options: InstallComponentOptions): Promise<InstallComponentResult>;
@@ -8,52 +8,50 @@ const fs_1 = __importDefault(require("fs"));
8
8
  const path_1 = __importDefault(require("path"));
9
9
  const registry_1 = require("./registry");
10
10
  const theme_files_1 = require("./theme-files");
11
- function aliasedTarget(config, file) {
12
- if (file.placement === 'theme') {
13
- if (!file.target)
14
- throw new Error(`Registry file "${file.name}" is missing its theme target.`);
15
- return file.target;
16
- }
17
- let alias = '';
18
- if (file.type === 'partial')
19
- alias = config.aliases?.partials || 'partials/components';
20
- if (file.type === 'style')
21
- alias = config.aliases?.styles || 'assets/css/components';
22
- if (file.type === 'js')
23
- alias = config.aliases?.js || 'assets/js/components';
24
- if (!alias)
25
- throw new Error(`Unsupported registry file type "${file.type}".`);
26
- return path_1.default.join(alias, file.name);
27
- }
11
+ const component_plan_1 = require("./component-plan");
12
+ const component_history_1 = require("./component-history");
28
13
  async function installComponent(options) {
29
14
  const name = (0, registry_1.sanitizeComponentName)(options.componentName);
30
- const manifest = await (0, registry_1.getComponent)(name);
31
- if (!manifest)
32
- throw new Error(`Component "${name}" was not found in the registry.`);
33
- const result = { name, installed: [], skipped: [] };
34
- for (const file of manifest.files) {
35
- if (path_1.default.basename(file.name) !== file.name) {
36
- throw new Error(`Registry returned an unsafe file name for "${name}".`);
37
- }
38
- const relativeTarget = aliasedTarget(options.config, file);
39
- const targetPath = (0, theme_files_1.resolveWithinTheme)(options.themeRoot, relativeTarget);
40
- if (fs_1.default.existsSync(targetPath) && !options.overwrite) {
41
- const replace = options.shouldOverwrite ? await options.shouldOverwrite(relativeTarget.replace(/\\/g, '/')) : false;
42
- if (!replace) {
43
- result.skipped.push(relativeTarget);
44
- continue;
15
+ (0, component_history_1.readHistory)(options.themeRoot); // Validate before any component files are written.
16
+ const plan = await (0, component_plan_1.componentPlan)(options.themeRoot, options.config, name);
17
+ // Validate managed layout/asset targets before any component writes.
18
+ (0, theme_files_1.safeThemePath)(options.themeRoot, 'default.hbs');
19
+ if (plan.some(entry => entry.manifest.files.some(file => file.type === 'style')))
20
+ (0, theme_files_1.safeThemePath)(options.themeRoot, options.config.cssFile || 'assets/css/ghostcn.css');
21
+ const results = [];
22
+ for (const { manifest, files } of plan) {
23
+ const isDependency = manifest.name !== name;
24
+ const result = { name: manifest.name, installed: [], skipped: [] };
25
+ const baseline = {};
26
+ for (const file of files) {
27
+ const relativeTarget = file.relative;
28
+ const targetPath = file.target;
29
+ if (fs_1.default.existsSync(targetPath) && (isDependency || !options.overwrite)) {
30
+ const replace = !isDependency && options.shouldOverwrite ? await options.shouldOverwrite(relativeTarget.replace(/\\/g, '/')) : false;
31
+ if (!replace) {
32
+ result.skipped.push(relativeTarget);
33
+ continue;
34
+ }
45
35
  }
36
+ fs_1.default.mkdirSync(path_1.default.dirname(targetPath), { recursive: true });
37
+ fs_1.default.writeFileSync(targetPath, file.content, 'utf8');
38
+ baseline[relativeTarget] = file.content;
39
+ result.installed.push(relativeTarget);
46
40
  }
47
- fs_1.default.mkdirSync(path_1.default.dirname(targetPath), { recursive: true });
48
- fs_1.default.writeFileSync(targetPath, file.content, 'utf8');
49
- result.installed.push(relativeTarget);
41
+ if (result.installed.length)
42
+ (0, component_history_1.recordInstalledFiles)(options.themeRoot, manifest.name, baseline);
43
+ results.push(result);
50
44
  }
51
- if (manifest.files.some(file => file.type === 'style')) {
45
+ const result = results[results.length - 1];
46
+ result.dependencies = results.slice(0, -1);
47
+ if (plan.some(entry => entry.manifest.files.some(file => file.type === 'style'))) {
52
48
  result.styleSync = (0, theme_files_1.syncGhostcnStyles)({
53
49
  themeRoot: options.themeRoot,
54
50
  cssFile: options.config.cssFile || 'assets/css/ghostcn.css',
55
51
  stylesDir: options.config.aliases?.styles || 'assets/css/components'
56
52
  });
57
53
  }
54
+ if (plan.some(entry => entry.manifest.files.some(file => file.type === 'js')))
55
+ result.scriptSync = (0, theme_files_1.syncGhostcnScripts)(options.themeRoot, options.config.aliases?.js || 'assets/js/components');
58
56
  return result;
59
57
  }
@@ -0,0 +1,7 @@
1
+ import { ComponentManifest } from './registry';
2
+ import { GhostcnConfig } from './theme-project';
3
+ import { componentFiles } from './component-files';
4
+ export declare function componentPlan(themeRoot: string, config: GhostcnConfig, name: string, load?: (name: string) => Promise<ComponentManifest | null>): Promise<{
5
+ manifest: ComponentManifest;
6
+ files: ReturnType<typeof componentFiles>;
7
+ }[]>;
@@ -0,0 +1,43 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.componentPlan = componentPlan;
4
+ const registry_1 = require("./registry");
5
+ const component_files_1 = require("./component-files");
6
+ // Resolve and validate the entire dependency graph before an installer writes any files.
7
+ // The caller owns overwrite policy; this helper only supplies a dependency-first plan.
8
+ async function componentPlan(themeRoot, config, name, load = registry_1.getComponent) {
9
+ const visiting = new Set();
10
+ const completed = new Set();
11
+ const targets = new Map();
12
+ const entries = [];
13
+ async function visit(requested) {
14
+ const key = (0, registry_1.sanitizeComponentName)(requested);
15
+ if (visiting.has(key))
16
+ throw new Error(`Component dependency cycle at "${key}".`);
17
+ if (completed.has(key))
18
+ return;
19
+ const manifest = await load(key);
20
+ if (!manifest)
21
+ throw new Error(`Component "${key}" was not found in the registry.`);
22
+ if (manifest.name !== key)
23
+ throw new Error(`Registry returned an unexpected component for "${key}".`);
24
+ if (manifest.dependencies !== undefined && (!Array.isArray(manifest.dependencies) || manifest.dependencies.some(value => typeof value !== 'string')))
25
+ throw new Error(`Invalid dependencies for "${key}".`);
26
+ visiting.add(key);
27
+ for (const dependency of manifest.dependencies || [])
28
+ await visit(dependency);
29
+ const files = (0, component_files_1.componentFiles)(themeRoot, config, manifest);
30
+ for (const file of files) {
31
+ // Case-insensitive Windows paths must not allow graph entries to silently collide.
32
+ const target = process.platform === 'win32' ? file.target.toLowerCase() : file.target;
33
+ if (targets.has(target))
34
+ throw new Error(`Components "${targets.get(target)}" and "${key}" target the same file.`);
35
+ targets.set(target, key);
36
+ }
37
+ entries.push({ manifest, files });
38
+ visiting.delete(key);
39
+ completed.add(key);
40
+ }
41
+ await visit(name);
42
+ return entries;
43
+ }
@@ -0,0 +1,9 @@
1
+ import http from 'http';
2
+ export declare function startPlayground(options: {
3
+ themeRoot: string;
4
+ port?: number;
5
+ }): Promise<{
6
+ server: http.Server<typeof http.IncomingMessage, typeof http.ServerResponse>;
7
+ url: string;
8
+ close: () => Promise<void>;
9
+ }>;