contentbit 0.4.2 → 0.6.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 (57) hide show
  1. package/README.md +20 -2
  2. package/dist/bin.js +8183 -3889
  3. package/dist/cli-format.d.ts +17 -0
  4. package/dist/cli-format.d.ts.map +1 -0
  5. package/dist/cli-format.js +63 -0
  6. package/dist/commands/agents.d.ts +6 -1
  7. package/dist/commands/agents.d.ts.map +1 -1
  8. package/dist/commands/agents.js +13 -201
  9. package/dist/commands/brief.d.ts +12 -0
  10. package/dist/commands/brief.d.ts.map +1 -0
  11. package/dist/commands/brief.js +52 -0
  12. package/dist/commands/docs.d.ts +6 -1
  13. package/dist/commands/docs.d.ts.map +1 -1
  14. package/dist/commands/docs.js +5 -11
  15. package/dist/commands/doctor.d.ts +13 -1
  16. package/dist/commands/doctor.d.ts.map +1 -1
  17. package/dist/commands/doctor.js +124 -166
  18. package/dist/commands/init-targets.d.ts +27 -0
  19. package/dist/commands/init-targets.d.ts.map +1 -0
  20. package/dist/commands/init-targets.js +280 -0
  21. package/dist/commands/init.d.ts +12 -1
  22. package/dist/commands/init.d.ts.map +1 -1
  23. package/dist/commands/init.js +92 -340
  24. package/dist/commands/instructions.d.ts +8 -1
  25. package/dist/commands/instructions.d.ts.map +1 -1
  26. package/dist/commands/instructions.js +7 -15
  27. package/dist/commands/links.d.ts +7 -1
  28. package/dist/commands/links.d.ts.map +1 -1
  29. package/dist/commands/links.js +24 -37
  30. package/dist/commands/render.d.ts +8 -1
  31. package/dist/commands/render.d.ts.map +1 -1
  32. package/dist/commands/render.js +19 -24
  33. package/dist/commands/stats.d.ts +7 -1
  34. package/dist/commands/stats.d.ts.map +1 -1
  35. package/dist/commands/stats.js +28 -39
  36. package/dist/commands/studio.d.ts +13 -1
  37. package/dist/commands/studio.d.ts.map +1 -1
  38. package/dist/commands/studio.js +28 -39
  39. package/dist/commands/validate.d.ts +8 -1
  40. package/dist/commands/validate.d.ts.map +1 -1
  41. package/dist/commands/validate.js +39 -56
  42. package/dist/content-project.d.ts +12 -0
  43. package/dist/content-project.d.ts.map +1 -0
  44. package/dist/content-project.js +25 -0
  45. package/dist/link-options.d.ts +5 -0
  46. package/dist/link-options.d.ts.map +1 -1
  47. package/dist/link-options.js +5 -5
  48. package/dist/load-registry.d.ts +1 -3
  49. package/dist/load-registry.d.ts.map +1 -1
  50. package/dist/load-registry.js +1 -24
  51. package/dist/run.d.ts +10 -1
  52. package/dist/run.d.ts.map +1 -1
  53. package/dist/run.js +9603 -5307
  54. package/dist/seo-config.d.ts +12 -0
  55. package/dist/seo-config.d.ts.map +1 -0
  56. package/dist/seo-config.js +21 -0
  57. package/package.json +6 -5
@@ -1,119 +1,51 @@
1
- import { analyzeDocument, buildLinkIndex, extractFrontmatter, parseDocument, stripFrontmatter, validateDocument, validateLinks, } from '@contentbit/core';
2
- import { readFile } from 'node:fs/promises';
3
- import { parseArgs } from 'node:util';
4
- import { glob } from 'tinyglobby';
1
+ import { DEFAULT_MIN_SECTION_WORDS, } from '@contentbit/core';
2
+ import { color, displayPath, formatCommandList, formatRows, section, severityLabel, } from '../cli-format.js';
3
+ import { loadContentProject } from '../content-project.js';
5
4
  import { linkResolverOptions } from '../link-options.js';
6
- import { loadRegistry } from '../load-registry.js';
7
- const DEFAULT_MIN_SECTION_WORDS = 25;
8
- const BLOCKLESS_WORDS = 250;
9
- export async function doctorCommand(args, io) {
10
- const { values, positionals } = parseArgs({
11
- args,
12
- allowPositionals: true,
13
- options: {
14
- registry: { type: 'string' },
15
- 'strict-warnings': { type: 'boolean', default: false },
16
- json: { type: 'boolean', default: false },
17
- 'min-section-words': { type: 'string' },
18
- 'link-resolve': { type: 'string' },
19
- 'locale-field': { type: 'string' },
20
- 'slug-field': { type: 'string' },
21
- 'key-field': { type: 'string' },
22
- 'default-locale': { type: 'string' },
23
- },
24
- });
25
- if (positionals.length === 0) {
26
- io.stderr('doctor: provide at least one file or glob.');
27
- return 2;
28
- }
29
- const minSectionWords = parseMinSectionWords(values['min-section-words']);
5
+ import { loadSeoConfig } from '../seo-config.js';
6
+ export async function doctorCommand(input, io) {
7
+ const minSectionWords = parseMinSectionWords(input.minSectionWords);
30
8
  if (minSectionWords === null) {
31
9
  io.stderr('doctor: --min-section-words must be a non-negative integer.');
32
10
  return 2;
33
11
  }
34
- const files = (await glob(positionals, { absolute: true })).sort();
35
- if (files.length === 0) {
36
- io.stderr(`doctor: no files matched ${positionals.join(' ')}`);
37
- return 2;
38
- }
39
- const registry = await loadRegistry(values.registry);
40
- const linkOptions = linkResolverOptions(values);
41
- const findings = [];
42
- const linkInputs = [];
43
- for (const file of files) {
44
- const source = await readFile(file, 'utf8');
45
- const frontmatter = extractFrontmatter(source);
46
- linkInputs.push({ path: file, data: frontmatter?.data ?? {} });
47
- const validation = validateDocument(parseDocument(stripFrontmatter(source)), registry);
48
- for (const diagnostic of validation.diagnostics) {
49
- findings.push(findingFromDiagnostic('validation', file, diagnostic));
50
- }
51
- const stats = analyzeDocument(source, { path: file });
52
- for (const section of stats.outline) {
53
- if (section.words < minSectionWords) {
54
- findings.push({
55
- severity: 'info',
56
- source: 'stats',
57
- code: 'CB_THIN_SECTION',
58
- file,
59
- line: section.line,
60
- column: 1,
61
- message: `section "${section.text}" has ${section.words} words`,
62
- hint: `Add detail or merge it with a nearby section. Threshold: ${minSectionWords} words.`,
63
- });
64
- }
65
- }
66
- if (stats.length.words >= BLOCKLESS_WORDS && stats.blocks.total === 0) {
67
- findings.push({
68
- severity: 'info',
69
- source: 'stats',
70
- code: 'CB_BLOCKLESS_DOCUMENT',
71
- file,
72
- message: `document has ${stats.length.words} words and no structured blocks`,
73
- hint: 'Consider a callout, steps, comparison, FAQ, or another registered block if it clarifies the page.',
74
- });
75
- }
76
- if (stats.images.missingAlt > 0) {
77
- findings.push({
78
- severity: 'info',
79
- source: 'stats',
80
- code: 'CB_IMAGE_ALT_MISSING',
81
- file,
82
- message: `${stats.images.missingAlt} image(s) are missing alt text`,
83
- hint: 'Add descriptive alt text for meaningful images; use empty alt only for decorative images.',
84
- });
85
- }
86
- }
87
- let linkGraph;
88
- if (hasLinkFrontmatter(linkInputs, linkOptions.slugField)) {
89
- for (const { file, diagnostic } of validateLinks(linkInputs, linkOptions)) {
90
- findings.push(findingFromDiagnostic('links', file, diagnostic));
91
- }
92
- const index = buildLinkIndex(linkInputs, linkOptions);
93
- let links = 0;
94
- for (const page of index.pages.values())
95
- links += page.linksTo.length;
96
- linkGraph = {
97
- pages: index.pages.size,
98
- links,
99
- orphans: [...index.pages.values()].filter((page) => page.linkedFrom.length === 0).length,
100
- };
101
- }
102
- findings.sort(compareFindings);
12
+ const includeGenericBlocks = !input.noGenericBlocks;
13
+ const linkOptions = linkResolverOptions(input);
14
+ const seoConfig = await loadSeoConfig({ seoConfig: input.seoConfig, noSeo: input.noSeo });
15
+ const { files, scan } = await loadContentProject({
16
+ cmd: 'doctor',
17
+ positionals: input.globs,
18
+ registry: input.registry,
19
+ includeGenericBlocks,
20
+ linkOptions,
21
+ scan: { minSectionWords, seoConfig: seoConfig.config, seoConfigPath: seoConfig.path },
22
+ });
103
23
  const report = {
104
24
  files: files.length,
105
- summary: summarize(findings),
106
- ...(linkGraph ? { linkGraph } : {}),
107
- findings,
25
+ summary: scan.summary,
26
+ ...(scan.linkGraph ? { linkGraph: scan.linkGraph } : {}),
27
+ ...(scan.seo
28
+ ? {
29
+ seo: {
30
+ schemaVersion: scan.seo.schemaVersion,
31
+ pages: scan.seo.pages.length,
32
+ findings: scan.seo.findings,
33
+ },
34
+ }
35
+ : {}),
36
+ findings: scan.findings,
108
37
  };
109
- if (values.json)
38
+ if (input.json)
110
39
  io.stdout(JSON.stringify(report, null, 2));
111
40
  else
112
- io.stdout(formatReport(report, positionals, values.registry, hasAliases(linkInputs)));
41
+ io.stdout(formatReport(report, input.globs, input.registry, includeGenericBlocks, linkOptions, hasAliases(scan.linkInputs)));
113
42
  if (report.summary.errors > 0)
114
43
  return 1;
115
- if (report.summary.warnings > 0 && values['strict-warnings'])
44
+ if (report.summary.warnings > 0 && input.strictWarnings)
45
+ return 1;
46
+ if (input.strictSeo && report.seo?.findings.some((finding) => finding.severity === 'warning')) {
116
47
  return 1;
48
+ }
117
49
  return 0;
118
50
  }
119
51
  function parseMinSectionWords(value) {
@@ -123,89 +55,93 @@ function parseMinSectionWords(value) {
123
55
  return null;
124
56
  return Number(value);
125
57
  }
126
- function findingFromDiagnostic(source, file, diagnostic) {
127
- return {
128
- severity: diagnostic.severity,
129
- source,
130
- code: diagnostic.code,
131
- file,
132
- line: diagnostic.position.start.line,
133
- column: diagnostic.position.start.column,
134
- message: diagnostic.message,
135
- ...(diagnostic.hint ? { hint: diagnostic.hint } : {}),
136
- };
137
- }
138
- function hasLinkFrontmatter(inputs, configuredSlugField) {
139
- const slugField = configuredSlugField ?? 'slug';
140
- return inputs.some((input) => Object.prototype.hasOwnProperty.call(input.data, slugField));
141
- }
142
58
  function hasAliases(inputs) {
143
59
  return inputs.some((input) => Array.isArray(input.data.aliases) && input.data.aliases.length > 0);
144
60
  }
145
- function summarize(findings) {
146
- return {
147
- errors: findings.filter((f) => f.severity === 'error').length,
148
- warnings: findings.filter((f) => f.severity === 'warning').length,
149
- suggestions: findings.filter((f) => f.severity === 'info').length,
150
- };
151
- }
152
- function compareFindings(a, b) {
153
- return (rank(a) - rank(b) ||
154
- a.file.localeCompare(b.file) ||
155
- (a.line ?? 0) - (b.line ?? 0) ||
156
- (a.column ?? 0) - (b.column ?? 0) ||
157
- a.code.localeCompare(b.code));
158
- }
159
- function rank(finding) {
160
- if (finding.severity === 'error' && finding.source === 'validation')
161
- return 0;
162
- if (finding.severity === 'error' && finding.source === 'links')
163
- return 1;
164
- if (finding.severity === 'warning')
165
- return 2;
166
- if (finding.code === 'CB_THIN_SECTION')
167
- return 3;
168
- if (finding.code === 'CB_BLOCKLESS_DOCUMENT')
169
- return 4;
170
- if (finding.code === 'CB_IMAGE_ALT_MISSING')
171
- return 5;
172
- return 6;
173
- }
174
- function formatReport(report, globs, registryPath, aliasFixMayApply) {
61
+ function formatReport(report, globs, registryPath, includeGenericBlocks, linkOptions, aliasFixMayApply) {
175
62
  const lines = [];
176
- lines.push('contentbit doctor');
177
- lines.push(`${report.files} file(s): ${report.summary.errors} errors, ${report.summary.warnings} warnings, ${report.summary.suggestions} suggestions`);
63
+ lines.push(section('contentbit doctor'));
64
+ lines.push('');
65
+ lines.push(section('Health'));
66
+ lines.push(...formatRows([
67
+ { label: 'Files', value: report.files },
68
+ {
69
+ label: 'Errors',
70
+ value: report.summary.errors,
71
+ tone: report.summary.errors > 0 ? 'error' : 'success',
72
+ },
73
+ {
74
+ label: 'Warnings',
75
+ value: report.summary.warnings,
76
+ tone: report.summary.warnings > 0 ? 'warning' : 'success',
77
+ },
78
+ {
79
+ label: 'Suggestions',
80
+ value: report.summary.suggestions,
81
+ tone: report.summary.suggestions > 0 ? 'info' : 'success',
82
+ },
83
+ ]));
178
84
  if (report.linkGraph) {
179
- lines.push(`${report.linkGraph.pages} linked page(s), ${report.linkGraph.links} link(s), ${report.linkGraph.orphans} orphan(s)`);
85
+ lines.push('');
86
+ lines.push(section('Link Graph'));
87
+ lines.push(...formatRows([
88
+ { label: 'Pages', value: report.linkGraph.pages },
89
+ { label: 'Links', value: report.linkGraph.links },
90
+ {
91
+ label: 'Orphans',
92
+ value: report.linkGraph.orphans,
93
+ tone: report.linkGraph.orphans > 0 ? 'warning' : 'success',
94
+ },
95
+ ]));
96
+ }
97
+ if (report.seo) {
98
+ lines.push('');
99
+ lines.push(section('SEO'));
100
+ lines.push(...formatRows([
101
+ { label: 'Pages', value: report.seo.pages },
102
+ {
103
+ label: 'Findings',
104
+ value: report.seo.findings.length,
105
+ tone: report.seo.findings.length > 0 ? 'warning' : 'success',
106
+ },
107
+ ]));
180
108
  }
181
109
  lines.push('');
182
110
  if (report.findings.length === 0) {
183
- lines.push('No findings. Content looks healthy.');
111
+ lines.push(color('No findings. Content looks healthy.', 'success'));
184
112
  }
185
113
  else {
186
- lines.push('Repair plan:');
114
+ lines.push(section('Repair Plan'));
187
115
  report.findings.forEach((finding, index) => {
188
- lines.push(`${index + 1}. ${formatFinding(finding)}`);
189
- if (finding.hint)
190
- lines.push(` hint: ${finding.hint}`);
116
+ lines.push(...formatFinding(index + 1, finding));
191
117
  });
192
118
  }
193
119
  lines.push('');
194
- lines.push('Next commands:');
195
- lines.push(`- contentbit validate ${formatGlobs(globs)}${registryPath ? ` --registry ${formatArg(registryPath)}` : ''}`);
120
+ lines.push(section('Next Commands'));
121
+ const registryArgs = formatRegistryArgs(registryPath, includeGenericBlocks);
122
+ const linkArgs = formatLinkArgs(linkOptions);
123
+ const commands = [`contentbit validate ${formatGlobs(globs)}${registryArgs}${linkArgs}`];
196
124
  if (report.linkGraph) {
197
- lines.push(`- contentbit links ${formatGlobs(globs)}`);
125
+ commands.push(`contentbit links ${formatGlobs(globs)}${linkArgs}`);
198
126
  if (aliasFixMayApply && report.summary.errors === 0)
199
- lines.push(`- contentbit links ${formatGlobs(globs)} --fix`);
127
+ commands.push(`contentbit links ${formatGlobs(globs)}${linkArgs} --fix`);
200
128
  }
201
- lines.push(`- contentbit doctor ${formatGlobs(globs)} --json`);
129
+ commands.push(`contentbit doctor ${formatGlobs(globs)}${registryArgs}${linkArgs} --json`);
130
+ lines.push(...formatCommandList(commands));
202
131
  return lines.join('\n');
203
132
  }
204
- function formatFinding(finding) {
133
+ function formatFinding(index, finding) {
205
134
  const location = finding.line !== undefined && finding.column !== undefined
206
- ? `${finding.file}:${finding.line}:${finding.column}`
207
- : finding.file;
208
- return `[${finding.severity}] ${finding.source} ${finding.code} ${location} - ${finding.message}`;
135
+ ? `${displayPath(finding.file)}:${finding.line}:${finding.column}`
136
+ : displayPath(finding.file);
137
+ const lines = [
138
+ ` ${index}. ${severityLabel(finding.severity)} ${finding.source} ${finding.code}`,
139
+ ` ${color('at', 'muted')} ${location}`,
140
+ ` ${finding.message}`,
141
+ ];
142
+ if (finding.hint)
143
+ lines.push(` ${color('hint', 'muted')} ${finding.hint}`);
144
+ return lines;
209
145
  }
210
146
  function formatGlobs(globs) {
211
147
  return globs.map(formatArg).join(' ');
@@ -213,3 +149,25 @@ function formatGlobs(globs) {
213
149
  function formatArg(value) {
214
150
  return /\s/.test(value) ? JSON.stringify(value) : value;
215
151
  }
152
+ function formatRegistryArgs(registryPath, includeGenericBlocks) {
153
+ const args = [];
154
+ if (registryPath)
155
+ args.push('--registry', formatArg(registryPath));
156
+ if (!includeGenericBlocks)
157
+ args.push('--no-generic-blocks');
158
+ return args.length > 0 ? ` ${args.join(' ')}` : '';
159
+ }
160
+ function formatLinkArgs(options) {
161
+ const args = [];
162
+ if (options.resolve)
163
+ args.push('--link-resolve', options.resolve);
164
+ if (options.localeField)
165
+ args.push('--locale-field', formatArg(options.localeField));
166
+ if (options.slugField)
167
+ args.push('--slug-field', formatArg(options.slugField));
168
+ if (options.keyField)
169
+ args.push('--key-field', formatArg(options.keyField));
170
+ if (options.defaultLocale)
171
+ args.push('--default-locale', formatArg(options.defaultLocale));
172
+ return args.length > 0 ? ` ${args.join(' ')}` : '';
173
+ }
@@ -0,0 +1,27 @@
1
+ import type { Io } from '../run.js';
2
+ export type Target = 'react' | 'markdown' | 'astro';
3
+ export type Md = 'react-markdown' | 'none';
4
+ export declare const TARGETS: Target[];
5
+ type ScaffoldFile = [path: string, content: string];
6
+ export interface InitTargetPlan {
7
+ files: ScaffoldFile[];
8
+ nextSteps: string[];
9
+ }
10
+ interface InitTargetContext {
11
+ cwd: string;
12
+ deps: Record<string, string>;
13
+ md: Md;
14
+ noPage: boolean;
15
+ noStyled: boolean;
16
+ io: Io;
17
+ installStyledPack: (pack: string) => Promise<boolean>;
18
+ }
19
+ interface InitTargetAdapter {
20
+ markdownChoices: Md[];
21
+ runtimeDependencies(md: Md): string[];
22
+ createPlan(ctx: InitTargetContext): Promise<InitTargetPlan>;
23
+ }
24
+ export declare const TARGET_ADAPTERS: Record<Target, InitTargetAdapter>;
25
+ export declare function detectTarget(deps: Record<string, string>): Target;
26
+ export {};
27
+ //# sourceMappingURL=init-targets.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"init-targets.d.ts","sourceRoot":"","sources":["../../src/commands/init-targets.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,EAAE,EAAE,MAAM,WAAW,CAAA;AAEnC,MAAM,MAAM,MAAM,GAAG,OAAO,GAAG,UAAU,GAAG,OAAO,CAAA;AACnD,MAAM,MAAM,EAAE,GAAG,gBAAgB,GAAG,MAAM,CAAA;AAE1C,eAAO,MAAM,OAAO,EAAE,MAAM,EAAmC,CAAA;AAE/D,KAAK,YAAY,GAAG,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,CAAC,CAAA;AAEnD,MAAM,WAAW,cAAc;IAC7B,KAAK,EAAE,YAAY,EAAE,CAAA;IACrB,SAAS,EAAE,MAAM,EAAE,CAAA;CACpB;AAED,UAAU,iBAAiB;IACzB,GAAG,EAAE,MAAM,CAAA;IACX,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;IAC5B,EAAE,EAAE,EAAE,CAAA;IACN,MAAM,EAAE,OAAO,CAAA;IACf,QAAQ,EAAE,OAAO,CAAA;IACjB,EAAE,EAAE,EAAE,CAAA;IACN,iBAAiB,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC,OAAO,CAAC,CAAA;CACtD;AAED,UAAU,iBAAiB;IACzB,eAAe,EAAE,EAAE,EAAE,CAAA;IACrB,mBAAmB,CAAC,EAAE,EAAE,EAAE,GAAG,MAAM,EAAE,CAAA;IACrC,UAAU,CAAC,GAAG,EAAE,iBAAiB,GAAG,OAAO,CAAC,cAAc,CAAC,CAAA;CAC5D;AA0RD,eAAO,MAAM,eAAe,EAAE,MAAM,CAAC,MAAM,EAAE,iBAAiB,CAoB7D,CAAA;AAED,wBAAgB,YAAY,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,MAAM,CAIjE"}
@@ -0,0 +1,280 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ export const TARGETS = ['react', 'markdown', 'astro'];
4
+ const RUNTIME_BASE = ['@contentbit/core', '@contentbit/blocks', 'zod'];
5
+ /** blocks/components.tsx — React components for custom blocks, next to their definitions. */
6
+ function blockComponentsTemplate(styled) {
7
+ const body = styled
8
+ ? ` return (
9
+ <figure className="my-6 border-s-2 ps-4">
10
+ <blockquote className="text-lg italic">{ctx.renderMarkdown(data.markdown)}</blockquote>
11
+ <figcaption className="text-muted-foreground mt-2 text-sm">
12
+ — {String(node.props.author)}
13
+ {node.props.role ? \`, \${String(node.props.role)}\` : null}
14
+ </figcaption>
15
+ </figure>
16
+ )`
17
+ : ` return (
18
+ <figure style={{ margin: '1.5rem 0', borderLeft: '2px solid #d4d4d4', paddingLeft: '1rem' }}>
19
+ <blockquote style={{ fontStyle: 'italic' }}>{ctx.renderMarkdown(data.markdown)}</blockquote>
20
+ <figcaption style={{ marginTop: '0.5rem', fontSize: '0.875rem', opacity: 0.7 }}>
21
+ — {String(node.props.author)}
22
+ {node.props.role ? \`, \${String(node.props.role)}\` : null}
23
+ </figcaption>
24
+ </figure>
25
+ )`;
26
+ return `import type { BlockComponent, BlockComponentProps } from '@contentbit/react'
27
+
28
+ // One React component per custom block, keyed by block name. Definitions
29
+ // live in ./registry.ts — add a block there, add its component here, and
30
+ // the rest of the app never changes.
31
+ function QuoteBlock({ node, ctx }: BlockComponentProps) {
32
+ const data = node.data as { markdown: string }
33
+ ${body}
34
+ }
35
+
36
+ export const blockComponents: Record<string, BlockComponent> = {
37
+ quote: QuoteBlock,
38
+ }
39
+ `;
40
+ }
41
+ /** The wrapper component: styled pack or headless, with or without a Markdown lib. */
42
+ function reactComponent(styled, mdWired, blocksImport) {
43
+ const mdImport = mdWired ? "import ReactMarkdown from 'react-markdown'\n" : '';
44
+ const mdProp = mdWired
45
+ ? '\n renderMarkdown={(md) => <ReactMarkdown>{md}</ReactMarkdown>}'
46
+ : `\n // TODO: plug your Markdown library in here, e.g. react-markdown.
47
+ // One function renders all prose: https://contentbit.dev/docs/guides/markdown
48
+ // renderMarkdown={(md) => <Markdown source={md} />}`;
49
+ const rendererImport = styled
50
+ ? `\n// The styled pack installed by shadcn. Yours to edit.
51
+ import { ContentRenderer } from '@/components/content-blocks/content-renderer'`
52
+ : '';
53
+ const renderer = styled ? 'ContentRenderer' : 'ContentBlocks';
54
+ const reactImport = styled ? '' : "import { ContentBlocks } from '@contentbit/react'\n";
55
+ return `'use client'
56
+
57
+ import { genericBlocks } from '@contentbit/blocks'
58
+ import { createBlockRegistry, parseDocument, stripFrontmatter, validateDocument } from '@contentbit/core'
59
+ ${reactImport}${mdImport}${rendererImport}
60
+ // Everything block-related lives in the blocks/ folder: definitions in
61
+ // registry.ts (shared with the validate CLI), components in components.tsx.
62
+ import customBlocks from '${blocksImport}/registry'
63
+ import { blockComponents } from '${blocksImport}/components'
64
+
65
+ const registry = createBlockRegistry().use(genericBlocks()).use(customBlocks)
66
+
67
+ export function Content({ source }: { source: string }) {
68
+ const result = validateDocument(parseDocument(stripFrontmatter(source)), registry)
69
+ return (
70
+ <${renderer}
71
+ document={result.document}
72
+ components={blockComponents}${mdProp}
73
+ />
74
+ )
75
+ }
76
+ `;
77
+ }
78
+ /** Where the component and example page belong for the detected framework. */
79
+ function detectFramework(cwd, deps) {
80
+ if ((deps['@tanstack/react-start'] || deps['@tanstack/react-router']) &&
81
+ existsSync(join(cwd, 'src/routes'))) {
82
+ return {
83
+ framework: 'tanstack',
84
+ componentPath: 'src/components/content-blocks.tsx',
85
+ pagePath: 'src/routes/example.tsx',
86
+ };
87
+ }
88
+ if (deps.next) {
89
+ const appDir = existsSync(join(cwd, 'src/app')) ? 'src/app' : 'app';
90
+ if (existsSync(join(cwd, appDir))) {
91
+ return {
92
+ framework: 'next',
93
+ componentPath: 'components/content-blocks.tsx',
94
+ pagePath: `${appDir}/example/page.tsx`,
95
+ };
96
+ }
97
+ }
98
+ return { framework: null, componentPath: 'components/content-blocks.tsx', pagePath: null };
99
+ }
100
+ const TANSTACK_PAGE = `import { createFileRoute } from '@tanstack/react-router'
101
+
102
+ import { Content } from '../components/content-blocks'
103
+ // Vite's ?raw import inlines the Markdown as a string at build time.
104
+ import source from '../../content/example.md?raw'
105
+
106
+ export const Route = createFileRoute('/example')({ component: ExamplePage })
107
+
108
+ function ExamplePage() {
109
+ return (
110
+ <main style={{ maxWidth: '42rem', margin: '0 auto', padding: '3rem 1.5rem' }}>
111
+ <Content source={source} />
112
+ </main>
113
+ )
114
+ }
115
+ `;
116
+ const NEXT_PAGE = `import { readFile } from 'node:fs/promises'
117
+
118
+ // If your project has no "@/" path alias, switch to a relative import.
119
+ import { Content } from '@/components/content-blocks'
120
+
121
+ export default async function ExamplePage() {
122
+ const source = await readFile('content/example.md', 'utf8')
123
+ return (
124
+ <main style={{ maxWidth: '42rem', margin: '0 auto', padding: '3rem 1.5rem' }}>
125
+ <Content source={source} />
126
+ </main>
127
+ )
128
+ }
129
+ `;
130
+ const ASTRO_CONTENT_CONFIG = `import { defineCollection } from 'astro:content'
131
+ import { glob } from 'astro/loaders'
132
+
133
+ export const collections = {
134
+ articles: defineCollection({
135
+ // Astro's builtin Markdown loader. Entry bodies are parsed and validated
136
+ // where they render (see src/pages/example.astro); \`contentbit validate\`
137
+ // covers the same files in CI.
138
+ loader: glob({ pattern: '**/*.md', base: './content' }),
139
+ }),
140
+ }
141
+ `;
142
+ const ASTRO_QUOTE_BLOCK = `---
143
+ // The Astro component for the custom \`quote\` block defined in blocks/registry.ts.
144
+ // Block props arrive as component props; nested content arrives via <slot />.
145
+ interface Props {
146
+ author: string
147
+ role?: string
148
+ }
149
+
150
+ const { author, role } = Astro.props
151
+ ---
152
+
153
+ <figure style="margin: 1.5rem 0; border-left: 2px solid #d4d4d4; padding-left: 1rem;">
154
+ <blockquote style="font-style: italic;"><slot /></blockquote>
155
+ <figcaption style="margin-top: 0.5rem; font-size: 0.875rem; opacity: 0.7;">
156
+ — {author}{role ? \`, \${role}\` : null}
157
+ </figcaption>
158
+ </figure>
159
+ `;
160
+ /** The example page: styled pack renderer or the headless ContentBlocks. */
161
+ function astroPage(styled) {
162
+ const importLine = styled
163
+ ? "import ContentRenderer from '../components/content-blocks/content-renderer.astro'"
164
+ : "import { ContentBlocks } from '@contentbit/astro/components'";
165
+ const renderer = styled ? 'ContentRenderer' : 'ContentBlocks';
166
+ return `---
167
+ import { genericBlocks } from '@contentbit/blocks'
168
+ import { createBlockRegistry, parseDocument, validateDocument } from '@contentbit/core'
169
+ import { getEntry } from 'astro:content'
170
+
171
+ ${importLine}
172
+
173
+ // Definitions in blocks/registry.ts are shared with the validate CLI.
174
+ import customBlocks from '../../blocks/registry'
175
+ import QuoteBlock from '../../blocks/QuoteBlock.astro'
176
+
177
+ // Entry ids are the file path relative to the collection base, minus ".md".
178
+ const entry = await getEntry('articles', 'example')
179
+ if (!entry?.body) throw new Error('Entry "example" not found in the articles collection.')
180
+
181
+ const registry = createBlockRegistry().use(genericBlocks()).use(customBlocks)
182
+ // Static pages render at build time, so invalid blocks fail the build here.
183
+ const result = validateDocument(parseDocument(entry.body), registry)
184
+ ---
185
+
186
+ <main style="max-width: 42rem; margin: 0 auto; padding: 3rem 1.5rem;">
187
+ <${renderer} document={result.document} components={{ quote: QuoteBlock }} />
188
+ </main>
189
+ `;
190
+ }
191
+ function runtimeWith(...extra) {
192
+ return [...RUNTIME_BASE, ...extra];
193
+ }
194
+ function reactRuntime(md) {
195
+ return runtimeWith('@contentbit/react', ...(md === 'none' ? [] : [md]));
196
+ }
197
+ async function createReactPlan(ctx) {
198
+ const files = [];
199
+ const layout = detectFramework(ctx.cwd, ctx.deps);
200
+ const componentsJsonPath = join(ctx.cwd, 'components.json');
201
+ const styled = !ctx.noStyled &&
202
+ existsSync(componentsJsonPath) &&
203
+ (await ctx.installStyledPack('@contentbit/generic-pack'));
204
+ const depth = layout.componentPath.split('/').length - 1;
205
+ const blocksImport = `${'../'.repeat(depth)}blocks`;
206
+ files.push(['blocks/components.tsx', blockComponentsTemplate(styled)]);
207
+ files.push([
208
+ layout.componentPath,
209
+ reactComponent(styled, ctx.md === 'react-markdown', blocksImport),
210
+ ]);
211
+ if (!ctx.noPage && layout.pagePath) {
212
+ files.push([layout.pagePath, layout.framework === 'tanstack' ? TANSTACK_PAGE : NEXT_PAGE]);
213
+ }
214
+ const nextSteps = !ctx.noPage && layout.pagePath
215
+ ? [' 2. Start the dev server and open /example to see the article rendered.']
216
+ : [
217
+ ' 2. Render it: import { Content } from "./components/content-blocks"',
218
+ ' <Content source={...content/example.md as a string} />',
219
+ ];
220
+ nextSteps.push(' 3. Styled components: pnpm dlx shadcn@latest add @contentbit/generic-pack');
221
+ return { files, nextSteps };
222
+ }
223
+ async function createAstroPlan(ctx) {
224
+ const files = [['blocks/QuoteBlock.astro', ASTRO_QUOTE_BLOCK]];
225
+ const componentsJsonPath = join(ctx.cwd, 'components.json');
226
+ const styled = !ctx.noStyled &&
227
+ existsSync(componentsJsonPath) &&
228
+ (await ctx.installStyledPack('@contentbit/astro-pack'));
229
+ // Every config filename Astro resolves (src/content.config.* plus the legacy
230
+ // src/content/config.* location), so we never scaffold a second config that
231
+ // Astro would silently ignore.
232
+ const configCandidates = ['ts', 'mts', 'mjs', 'js'].flatMap((ext) => [
233
+ `src/content.config.${ext}`,
234
+ `src/content/config.${ext}`,
235
+ ]);
236
+ const existingConfig = configCandidates.find((p) => existsSync(join(ctx.cwd, p)));
237
+ if (existingConfig) {
238
+ ctx.io.stdout(`content config exists (${existingConfig}); add this collection manually:`);
239
+ ctx.io.stdout(ASTRO_CONTENT_CONFIG);
240
+ ctx.io.stdout('the example page expects the "articles" collection above');
241
+ }
242
+ else {
243
+ files.push(['src/content.config.ts', ASTRO_CONTENT_CONFIG]);
244
+ }
245
+ if (!ctx.noPage)
246
+ files.push(['src/pages/example.astro', astroPage(styled)]);
247
+ return {
248
+ files,
249
+ nextSteps: [
250
+ ' 2. Start the dev server and open /example to see the article rendered.',
251
+ ' 3. Styled components: pnpm dlx shadcn@latest add @contentbit/astro-pack',
252
+ ],
253
+ };
254
+ }
255
+ export const TARGET_ADAPTERS = {
256
+ react: {
257
+ markdownChoices: ['react-markdown', 'none'],
258
+ runtimeDependencies: reactRuntime,
259
+ createPlan: createReactPlan,
260
+ },
261
+ markdown: {
262
+ markdownChoices: ['none'],
263
+ runtimeDependencies: () => runtimeWith(),
264
+ createPlan: async () => ({
265
+ files: [],
266
+ nextSteps: [' 2. Render it: contentbit render content/example.md'],
267
+ }),
268
+ },
269
+ astro: {
270
+ // Astro projects usually reuse their host Markdown pipeline.
271
+ markdownChoices: ['none'],
272
+ runtimeDependencies: () => runtimeWith('@contentbit/astro'),
273
+ createPlan: createAstroPlan,
274
+ },
275
+ };
276
+ export function detectTarget(deps) {
277
+ const hasReact = Boolean(deps.react);
278
+ const hasAstro = Boolean(deps.astro);
279
+ return hasAstro ? 'astro' : hasReact ? 'react' : 'markdown';
280
+ }
@@ -1,3 +1,14 @@
1
1
  import type { Io } from '../run.js';
2
- export declare function initCommand(args: string[], io: Io): Promise<number>;
2
+ export interface InitCommandInput {
3
+ target?: string;
4
+ md?: string;
5
+ yes?: boolean;
6
+ cwd?: string;
7
+ noInstall?: boolean;
8
+ noPage?: boolean;
9
+ noStyled?: boolean;
10
+ noAgents?: boolean;
11
+ seo?: boolean;
12
+ }
13
+ export declare function initCommand(input: InitCommandInput, io: Io): Promise<number>;
3
14
  //# sourceMappingURL=init.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"init.d.ts","sourceRoot":"","sources":["../../src/commands/init.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,EAAE,EAAE,MAAM,WAAW,CAAA;AAianC,wBAAsB,WAAW,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,EAAE,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC,CAqPzE"}
1
+ {"version":3,"file":"init.d.ts","sourceRoot":"","sources":["../../src/commands/init.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,EAAE,EAAE,MAAM,WAAW,CAAA;AA+NnC,MAAM,WAAW,gBAAgB;IAC/B,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,EAAE,CAAC,EAAE,MAAM,CAAA;IACX,GAAG,CAAC,EAAE,OAAO,CAAA;IACb,GAAG,CAAC,EAAE,MAAM,CAAA;IACZ,SAAS,CAAC,EAAE,OAAO,CAAA;IACnB,MAAM,CAAC,EAAE,OAAO,CAAA;IAChB,QAAQ,CAAC,EAAE,OAAO,CAAA;IAClB,QAAQ,CAAC,EAAE,OAAO,CAAA;IAClB,GAAG,CAAC,EAAE,OAAO,CAAA;CACd;AAED,wBAAsB,WAAW,CAAC,KAAK,EAAE,gBAAgB,EAAE,EAAE,EAAE,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC,CA+KlF"}