contentbit 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"agents.d.ts","sourceRoot":"","sources":["../../src/commands/agents.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,EAAE,EAAE,MAAM,WAAW,CAAA;AA2JnC,MAAM,WAAW,YAAY;IAC3B,8EAA8E;IAC9E,MAAM,CAAC,EAAE,OAAO,CAAA;IAChB,oDAAoD;IACpD,QAAQ,CAAC,EAAE,OAAO,CAAA;CACnB;AAED,+EAA+E;AAC/E,wBAAsB,uBAAuB,CAC3C,GAAG,EAAE,MAAM,EACX,OAAO,EAAE,YAAY,EACrB,EAAE,EAAE,EAAE,GACL,OAAO,CAAC,IAAI,CAAC,CA6Bf;AAED,wBAAsB,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,EAAE,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC,CAkB3E"}
1
+ {"version":3,"file":"agents.d.ts","sourceRoot":"","sources":["../../src/commands/agents.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,EAAE,EAAE,MAAM,WAAW,CAAA;AAkNnC,MAAM,WAAW,YAAY;IAC3B,8EAA8E;IAC9E,MAAM,CAAC,EAAE,OAAO,CAAA;IAChB,oDAAoD;IACpD,QAAQ,CAAC,EAAE,OAAO,CAAA;CACnB;AAED,+EAA+E;AAC/E,wBAAsB,uBAAuB,CAC3C,GAAG,EAAE,MAAM,EACX,OAAO,EAAE,YAAY,EACrB,EAAE,EAAE,EAAE,GACL,OAAO,CAAC,IAAI,CAAC,CA6Bf;AAED,wBAAsB,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,EAAE,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC,CAkB3E"}
@@ -7,7 +7,7 @@ import { parseArgs } from 'node:util';
7
7
  // registry stays the single source of truth and nothing can drift. Bump the
8
8
  // frontmatter version when a template changes; `contentbit agents` re-runs
9
9
  // overwrite in place.
10
- const TEMPLATE_VERSION = 1;
10
+ const TEMPLATE_VERSION = 3;
11
11
  const AUTHOR_SKILL = `---
12
12
  name: contentbit-author
13
13
  description: |
@@ -30,6 +30,8 @@ Check \`package.json\` for a \`content:check\` script. It holds the canonical
30
30
  validate invocation for this project: the content glob and, if present, the
31
31
  \`--registry <path>\` flag pointing at custom block definitions. Reuse both
32
32
  below. No script? Default to \`content/**/*.md\` with no \`--registry\` flag.
33
+ If the project has a \`content:links\` script, use it for the internal-link
34
+ index; otherwise run \`contentbit links <content glob>\` directly.
33
35
 
34
36
  ## The loop
35
37
 
@@ -44,7 +46,19 @@ below. No script? Default to \`content/**/*.md\` with no \`--registry\` flag.
44
46
 
45
47
  2. **Write the document.** Plain Markdown everywhere; blocks only where the
46
48
  guide's use-when guidance fits. Keep frontmatter consistent with sibling
47
- documents in the same folder.
49
+ documents in the same folder. If sibling documents use \`slug\`, \`linksTo\`,
50
+ \`aliases\`, or \`keywords\`, run the link index first:
51
+
52
+ \`\`\`sh
53
+ contentbit links <content glob>
54
+ \`\`\`
55
+
56
+ Read \`.contentbit/link-index.json\` to pick existing slugs and related
57
+ pages. Author only \`slug\`, \`linksTo\`, \`aliases\`, and \`keywords\` in
58
+ frontmatter; never write derived \`linkedFrom\` into source files. When
59
+ creating a linked page, include \`keywords.primary\` and
60
+ \`keywords.secondary\` with search-intent phrases that would help future
61
+ agents choose this page as a \`linksTo\` target.
48
62
 
49
63
  3. **Validate and fix until clean:**
50
64
 
@@ -54,8 +68,19 @@ below. No script? Default to \`content/**/*.md\` with no \`--registry\` flag.
54
68
 
55
69
  Diagnostics print to stderr as \`file:line:col severity CODE message\`, often
56
70
  with a \`hint:\` line suggesting the fix. Exit 0 means clean; exit 1 means
57
- errors remain. Fix every diagnostic and re-run. Never finish with a failing
58
- validate.
71
+ errors remain. If the document has link frontmatter, validate the full
72
+ content glob so cross-file links are checked against the whole graph. Fix
73
+ every diagnostic and re-run. Never finish with a failing validate.
74
+
75
+ 4. **Refresh internal links when present:**
76
+
77
+ \`\`\`sh
78
+ contentbit links <content glob> --fix
79
+ \`\`\`
80
+
81
+ \`--fix\` only rewrites \`linksTo\` values that point at known aliases. It
82
+ does not invent links, remove aliases, or write backlinks. Re-run validate
83
+ after it changes files.
59
84
 
60
85
  ## Failure modes
61
86
 
@@ -75,33 +100,48 @@ version: ${TEMPLATE_VERSION}
75
100
 
76
101
  # Auditing contentbit content
77
102
 
78
- \`contentbit stats\` analyzes documents and prints JSON to stdout. It is a read
79
- tool: it always exits 0, even when documents have validation errors.
103
+ \`contentbit doctor\` is the first audit command. It reads content once, runs
104
+ block validation, link validation, and document stats, then prints a ranked
105
+ repair plan. It is read-only: it does not write the link index and never edits
106
+ source files. \`contentbit stats\` remains useful when you need raw JSON metrics.
107
+ \`contentbit links\` builds the frontmatter-authored internal-link graph and can
108
+ heal alias references with \`--fix\`.
80
109
 
81
110
  ## Gather
82
111
 
83
- Check \`package.json\` for the \`content:check\` script to find this project's
84
- content glob and \`--registry\` flag, then:
112
+ Check \`package.json\` for \`content:doctor\` first. If it exists, run it. If it
113
+ does not, use \`content:check\` to find this project's content glob and
114
+ \`--registry\` flag, then run:
85
115
 
86
116
  \`\`\`sh
117
+ contentbit doctor "content/**/*.md" [--registry <path>]
118
+ contentbit doctor "content/**/*.md" [--registry <path>] --json
87
119
  contentbit stats "content/**/*.md" [--registry <path>]
120
+ contentbit links "content/**/*.md"
88
121
  \`\`\`
89
122
 
90
- One matched file prints a single stats object; multiple files print an array.
91
- Each entry includes the file path, frontmatter data, a heading \`outline\` with
92
- per-section word counts, \`blocks.byName\` usage counts, \`links.domains\`, and
93
- a \`validation\` summary (\`errors\`/\`warnings\`).
123
+ \`doctor --json\` prints a stable report with summary counts and ranked
124
+ findings. \`stats\` prints per-file metrics: frontmatter data, a heading
125
+ \`outline\` with per-section word counts, \`blocks.byName\` usage counts,
126
+ \`links.domains\`, and a \`validation\` summary (\`errors\`/\`warnings\`).
127
+ \`contentbit links\` writes \`.contentbit/link-index.json\`, whose pages contain
128
+ \`slug\`, resolved \`linksTo\`, derived \`linkedFrom\`, \`aliases\`, and
129
+ \`keywords\`.
94
130
 
95
131
  ## Interpret
96
132
 
97
- Prioritize findings in this order:
133
+ Prioritize findings in the order \`doctor\` reports them:
98
134
 
99
135
  1. **Validation errors and warnings** — broken content ships broken pages.
100
- 2. **Thin documents** — outline sections with very low word counts.
101
- 3. **Block-less documents** — \`blocks.byName\` empty where sibling documents
136
+ 2. **Internal-link errors** — unresolved links, duplicate slugs, and alias
137
+ conflicts from \`contentbit links\`.
138
+ 3. **Orphans and self-links** — link warnings that point to isolated or noisy
139
+ pages.
140
+ 4. **Thin documents** — outline sections with very low word counts.
141
+ 5. **Block-less documents** — \`blocks.byName\` empty where sibling documents
102
142
  use blocks; structure (steps, callouts, comparisons, faq) may be missing.
103
- 4. **Missing or inconsistent frontmatter** compared to sibling documents.
104
- 5. **Structural imbalance** — skipped heading levels, single-section walls of text.
143
+ 6. **Missing or inconsistent frontmatter** compared to sibling documents.
144
+ 7. **Structural imbalance** — skipped heading levels, single-section walls of text.
105
145
 
106
146
  ## Report
107
147
 
@@ -117,21 +157,36 @@ This project validates Markdown content with contentbit. Documents are plain
117
157
  Markdown plus directive blocks (\`:::name{props} ... :::\`), each with a schema.
118
158
  The \`content:check\` script in package.json holds the canonical validate
119
159
  command — the content glob and the \`--registry\` flag — reuse its arguments.
160
+ If the project has a \`content:links\` script, use it to build the internal-link
161
+ index; otherwise run \`contentbit links <content glob>\`.
120
162
 
121
163
  When writing or editing content:
122
164
 
123
165
  1. Fetch the live authoring guide first — never guess block syntax:
124
166
  \`contentbit instructions --audience llm [--registry <path>]\`
125
167
  2. Write plain Markdown; use blocks where the guide's use-when guidance fits.
126
- 3. Validate until clean (exit 0): \`contentbit validate <file> [--registry <path>]\`.
168
+ 3. If sibling documents use \`slug\` / \`linksTo\`, read
169
+ \`.contentbit/link-index.json\` from \`contentbit links <content glob>\` and
170
+ author frontmatter links with existing slugs. When creating a linked page,
171
+ include \`keywords.primary\` and \`keywords.secondary\` with search-intent
172
+ phrases future agents can use to choose related pages.
173
+ 4. Validate until clean (exit 0): \`contentbit validate <file> [--registry <path>]\`.
127
174
  Diagnostics print as \`file:line:col severity CODE message\` with fix hints.
175
+ For link frontmatter, validate the full content glob so cross-file checks run.
128
176
 
129
177
  When auditing content health:
130
178
 
131
- - \`contentbit stats "content/**/*.md" [--registry <path>]\` prints JSON stats
132
- and always exits 0: outline word counts, block usage, link domains, and
133
- validation error/warning counts. Flag validation issues, thin documents, and
134
- block-less pages first.
179
+ - \`contentbit doctor "content/**/*.md" [--registry <path>]\` prints a ranked,
180
+ read-only repair plan: validation issues, link issues, thin sections,
181
+ block-less long documents, and missing image alt text.
182
+ - \`contentbit doctor "content/**/*.md" [--registry <path>] --json\` prints the
183
+ same findings as structured JSON for agents and CI.
184
+ - \`contentbit stats "content/**/*.md" [--registry <path>]\` prints raw JSON
185
+ stats: outline word counts, block usage, link domains, and validation
186
+ error/warning counts.
187
+ - \`contentbit links "content/**/*.md" [--fix]\` builds
188
+ \`.contentbit/link-index.json\`, reports dangling links/orphans, and rewrites
189
+ alias references in \`linksTo\` when \`--fix\` is used.
135
190
 
136
191
  If \`contentbit\` is unavailable, suggest \`npx contentbit@latest init\` instead
137
192
  of inventing block syntax.
@@ -0,0 +1,3 @@
1
+ import type { Io } from '../run.js';
2
+ export declare function doctorCommand(args: string[], io: Io): Promise<number>;
3
+ //# sourceMappingURL=doctor.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"doctor.d.ts","sourceRoot":"","sources":["../../src/commands/doctor.ts"],"names":[],"mappings":"AAeA,OAAO,KAAK,EAAE,EAAE,EAAE,MAAM,WAAW,CAAA;AA4BnC,wBAAsB,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,EAAE,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC,CAkH3E"}
@@ -0,0 +1,215 @@
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';
5
+ 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']);
30
+ if (minSectionWords === null) {
31
+ io.stderr('doctor: --min-section-words must be a non-negative integer.');
32
+ return 2;
33
+ }
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);
103
+ const report = {
104
+ files: files.length,
105
+ summary: summarize(findings),
106
+ ...(linkGraph ? { linkGraph } : {}),
107
+ findings,
108
+ };
109
+ if (values.json)
110
+ io.stdout(JSON.stringify(report, null, 2));
111
+ else
112
+ io.stdout(formatReport(report, positionals, values.registry, hasAliases(linkInputs)));
113
+ if (report.summary.errors > 0)
114
+ return 1;
115
+ if (report.summary.warnings > 0 && values['strict-warnings'])
116
+ return 1;
117
+ return 0;
118
+ }
119
+ function parseMinSectionWords(value) {
120
+ if (value === undefined)
121
+ return DEFAULT_MIN_SECTION_WORDS;
122
+ if (!/^\d+$/.test(value))
123
+ return null;
124
+ return Number(value);
125
+ }
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
+ function hasAliases(inputs) {
143
+ return inputs.some((input) => Array.isArray(input.data.aliases) && input.data.aliases.length > 0);
144
+ }
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) {
175
+ 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`);
178
+ if (report.linkGraph) {
179
+ lines.push(`${report.linkGraph.pages} linked page(s), ${report.linkGraph.links} link(s), ${report.linkGraph.orphans} orphan(s)`);
180
+ }
181
+ lines.push('');
182
+ if (report.findings.length === 0) {
183
+ lines.push('No findings. Content looks healthy.');
184
+ }
185
+ else {
186
+ lines.push('Repair plan:');
187
+ report.findings.forEach((finding, index) => {
188
+ lines.push(`${index + 1}. ${formatFinding(finding)}`);
189
+ if (finding.hint)
190
+ lines.push(` hint: ${finding.hint}`);
191
+ });
192
+ }
193
+ lines.push('');
194
+ lines.push('Next commands:');
195
+ lines.push(`- contentbit validate ${formatGlobs(globs)}${registryPath ? ` --registry ${formatArg(registryPath)}` : ''}`);
196
+ if (report.linkGraph) {
197
+ lines.push(`- contentbit links ${formatGlobs(globs)}`);
198
+ if (aliasFixMayApply && report.summary.errors === 0)
199
+ lines.push(`- contentbit links ${formatGlobs(globs)} --fix`);
200
+ }
201
+ lines.push(`- contentbit doctor ${formatGlobs(globs)} --json`);
202
+ return lines.join('\n');
203
+ }
204
+ function formatFinding(finding) {
205
+ 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}`;
209
+ }
210
+ function formatGlobs(globs) {
211
+ return globs.map(formatArg).join(' ');
212
+ }
213
+ function formatArg(value) {
214
+ return /\s/.test(value) ? JSON.stringify(value) : value;
215
+ }
@@ -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;AAgYnC,wBAAsB,WAAW,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,EAAE,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC,CAyNzE"}
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"}
@@ -78,7 +78,18 @@ export const blockComponents: Record<string, BlockComponent> = {
78
78
  }
79
79
  `;
80
80
  }
81
- const EXAMPLE_CONTENT = `# Hello, Content Blocks
81
+ const EXAMPLE_CONTENT = `---
82
+ slug: hello-content-blocks
83
+ linksTo:
84
+ - related-contentbit-workflows
85
+ aliases:
86
+ - getting-started-contentbit
87
+ keywords:
88
+ primary: validated Markdown blocks
89
+ secondary: [content workflow, agent writing]
90
+ ---
91
+
92
+ # Hello, Content Blocks
82
93
 
83
94
  Regular Markdown works everywhere. Blocks add validated structure:
84
95
 
@@ -100,6 +111,27 @@ The Analytical Engine weaves algebraic patterns just as the Jacquard loom
100
111
  weaves flowers and leaves.
101
112
  :::
102
113
  `;
114
+ const RELATED_CONTENT = `---
115
+ slug: related-contentbit-workflows
116
+ linksTo:
117
+ - hello-content-blocks
118
+ keywords:
119
+ primary: contentbit workflow
120
+ secondary: [validation loop, internal links]
121
+ ---
122
+
123
+ # Related contentbit workflows
124
+
125
+ This supporting page exists to show internal links in frontmatter. The link
126
+ graph is authored once with \`slug\` and \`linksTo\`, then contentbit derives
127
+ \`linkedFrom\` in \`.contentbit/link-index.json\`.
128
+
129
+ :::callout{type="note"}
130
+ Run \`contentbit links "content/**/*.md" --fix\` after renaming a page. Alias
131
+ references in \`linksTo\` are rewritten to the current slug, while \`aliases\`
132
+ stays as the rename record.
133
+ :::
134
+ `;
103
135
  /** The wrapper component: styled pack or headless, with or without a Markdown lib. */
104
136
  function reactComponent(styled, mdWired, blocksImport) {
105
137
  const mdImport = mdWired ? "import ReactMarkdown from 'react-markdown'\n" : '';
@@ -117,7 +149,7 @@ import { ContentRenderer } from '@/components/content-blocks/content-renderer'`
117
149
  return `'use client'
118
150
 
119
151
  import { genericBlocks } from '@contentbit/blocks'
120
- import { createBlockRegistry, parseDocument, validateDocument } from '@contentbit/core'
152
+ import { createBlockRegistry, parseDocument, stripFrontmatter, validateDocument } from '@contentbit/core'
121
153
  ${reactImport}${mdImport}${rendererImport}
122
154
  // Everything block-related lives in the blocks/ folder: definitions in
123
155
  // registry.ts (shared with the validate CLI), components in components.tsx.
@@ -127,7 +159,7 @@ import { blockComponents } from '${blocksImport}/components'
127
159
  const registry = createBlockRegistry().use(genericBlocks()).use(customBlocks)
128
160
 
129
161
  export function Content({ source }: { source: string }) {
130
- const result = validateDocument(parseDocument(source), registry)
162
+ const result = validateDocument(parseDocument(stripFrontmatter(source)), registry)
131
163
  return (
132
164
  <${renderer}
133
165
  document={result.document}
@@ -151,14 +183,14 @@ const renderMarkdown = (md) => mdIt.render(md)`
151
183
  const renderMarkdown = undefined`;
152
184
  return `// Render content/example.md to example.html. Run: node scripts/render-example.mjs
153
185
  import { genericBlocks } from '@contentbit/blocks'
154
- import { createBlockRegistry, parseDocument, validateDocument } from '@contentbit/core'
186
+ import { createBlockRegistry, parseDocument, stripFrontmatter, validateDocument } from '@contentbit/core'
155
187
  import { renderToHtml } from '@contentbit/html'
156
188
  import { readFile, writeFile } from 'node:fs/promises'
157
189
  ${wiring}
158
190
 
159
191
  const source = await readFile('content/example.md', 'utf8')
160
192
  const registry = createBlockRegistry().use(genericBlocks())
161
- const result = validateDocument(parseDocument(source), registry)
193
+ const result = validateDocument(parseDocument(stripFrontmatter(source)), registry)
162
194
  const html = renderToHtml(result.document, { renderMarkdown })
163
195
  await writeFile('example.html', html, 'utf8')
164
196
  console.log('wrote example.html')
@@ -464,6 +496,7 @@ export async function initCommand(args, io) {
464
496
  const files = [
465
497
  ['blocks/registry.ts', REGISTRY_TEMPLATE],
466
498
  ['content/example.md', EXAMPLE_CONTENT],
499
+ ['content/related.md', RELATED_CONTENT],
467
500
  ];
468
501
  const layout = detectFramework(cwd, { ...pkg.dependencies, ...pkg.devDependencies });
469
502
  // shadcn project? Pull the styled component pack from the contentbit registry.
@@ -520,15 +553,33 @@ export async function initCommand(args, io) {
520
553
  const result = await scaffold(join(cwd, rel), content);
521
554
  io.stdout(`${result}: ${rel}`);
522
555
  }
523
- // Wire the validate script.
556
+ // Wire content scripts.
524
557
  const fresh = JSON.parse(await readFile(pkgPath, 'utf8'));
525
558
  fresh.scripts ??= {};
526
559
  if (!fresh.scripts['content:check']) {
527
560
  fresh.scripts['content:check'] =
528
561
  'contentbit validate "content/**/*.md" --registry ./blocks/registry.ts';
529
- await writeFile(pkgPath, `${JSON.stringify(fresh, null, 2)}\n`, 'utf8');
530
562
  io.stdout('added script: content:check');
531
563
  }
564
+ if (!fresh.scripts['content:links']) {
565
+ fresh.scripts['content:links'] = 'contentbit links "content/**/*.md"';
566
+ io.stdout('added script: content:links');
567
+ }
568
+ if (!fresh.scripts['content:doctor']) {
569
+ fresh.scripts['content:doctor'] =
570
+ 'contentbit doctor "content/**/*.md" --registry ./blocks/registry.ts';
571
+ io.stdout('added script: content:doctor');
572
+ }
573
+ if (!fresh.scripts.studio) {
574
+ fresh.scripts.studio = 'contentbit studio "content/**/*.md" --registry ./blocks/registry.ts';
575
+ io.stdout('added script: studio');
576
+ }
577
+ if (!pkg.scripts?.['content:check'] ||
578
+ !pkg.scripts?.['content:links'] ||
579
+ !pkg.scripts?.['content:doctor'] ||
580
+ !pkg.scripts?.studio) {
581
+ await writeFile(pkgPath, `${JSON.stringify(fresh, null, 2)}\n`, 'utf8');
582
+ }
532
583
  // Generate the LLM authoring guide from the registry, ready to paste into a prompt.
533
584
  let registry;
534
585
  try {
@@ -550,7 +601,10 @@ export async function initCommand(args, io) {
550
601
  }
551
602
  io.stdout('');
552
603
  io.stdout('Done. Next steps:');
553
- io.stdout(` 1. Validate the starter content: ${detectPackageManager(cwd)} run content:check`);
604
+ io.stdout(` 1. Browse content locally: ${detectPackageManager(cwd)} run studio`);
605
+ io.stdout(` Inspect content health: ${detectPackageManager(cwd)} run content:doctor`);
606
+ io.stdout(` Validate the starter content: ${detectPackageManager(cwd)} run content:check`);
607
+ io.stdout(` Build the link index: ${detectPackageManager(cwd)} run content:links`);
554
608
  if (target === 'react') {
555
609
  if (!values['no-page'] && layout.pagePath) {
556
610
  io.stdout(' 2. Start the dev server and open /example to see the article rendered.');
@@ -0,0 +1,3 @@
1
+ import type { Io } from '../run.js';
2
+ export declare function linksCommand(args: string[], io: Io): Promise<number>;
3
+ //# sourceMappingURL=links.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"links.d.ts","sourceRoot":"","sources":["../../src/commands/links.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EAAE,EAAE,EAAE,MAAM,WAAW,CAAA;AAKnC,wBAAsB,YAAY,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,EAAE,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC,CAuF1E"}
@@ -0,0 +1,97 @@
1
+ import { aliasReplacementsForPage, buildLinkIndex, extractFrontmatter, formatDiagnostic, serializeLinkIndex, validateLinks, } from '@contentbit/core';
2
+ import { mkdir, readFile } from 'node:fs/promises';
3
+ import { dirname, join } from 'node:path';
4
+ import { parseArgs } from 'node:util';
5
+ import { glob } from 'tinyglobby';
6
+ import { linkResolverOptions } from '../link-options.js';
7
+ import { collectLinkInputs } from '../links-io.js';
8
+ export async function linksCommand(args, io) {
9
+ const { values, positionals } = parseArgs({
10
+ args,
11
+ allowPositionals: true,
12
+ options: {
13
+ out: { type: 'string' },
14
+ fix: { type: 'boolean', default: false },
15
+ 'link-resolve': { type: 'string' },
16
+ 'locale-field': { type: 'string' },
17
+ 'slug-field': { type: 'string' },
18
+ 'key-field': { type: 'string' },
19
+ 'default-locale': { type: 'string' },
20
+ },
21
+ });
22
+ if (positionals.length === 0) {
23
+ io.stderr('links: provide at least one file or glob.');
24
+ return 2;
25
+ }
26
+ const files = (await glob(positionals, { absolute: true })).sort();
27
+ if (files.length === 0) {
28
+ io.stderr(`links: no files matched ${positionals.join(' ')}`);
29
+ return 2;
30
+ }
31
+ const inputs = await collectLinkInputs(files);
32
+ const linkOptions = linkResolverOptions(values);
33
+ let errors = 0;
34
+ let warnings = 0;
35
+ for (const { file, diagnostic } of validateLinks(inputs, linkOptions)) {
36
+ io.stderr(formatDiagnostic(diagnostic, file));
37
+ if (diagnostic.severity === 'error')
38
+ errors++;
39
+ else if (diagnostic.severity === 'warning')
40
+ warnings++;
41
+ }
42
+ const index = buildLinkIndex(inputs, linkOptions);
43
+ if (values.fix && errors > 0) {
44
+ io.stderr('links: --fix skipped because link errors must be resolved first.');
45
+ }
46
+ else if (values.fix && index.aliases.size > 0) {
47
+ for (const file of files) {
48
+ const source = await readFile(file, 'utf8');
49
+ const fm = extractFrontmatter(source);
50
+ if (!fm)
51
+ continue;
52
+ const lines = source.split('\n');
53
+ let changed = false;
54
+ // Only rewrite alias tokens inside the `linksTo:` block — never inside an
55
+ // `aliases:` list (which records the rename and must stay intact), and
56
+ // never in document body. Track whether we are within linksTo's scope:
57
+ // a top-level key resets it, dash-list / inline continuation keeps it.
58
+ let inLinksTo = false;
59
+ for (let i = 0; i < fm.lines.end && i < lines.length; i++) {
60
+ const line = lines[i];
61
+ const topKey = line.match(/^([A-Za-z0-9_.-]+):(.*)$/);
62
+ if (topKey)
63
+ inLinksTo = topKey[1] === 'linksTo';
64
+ if (!inLinksTo)
65
+ continue;
66
+ let next = line;
67
+ for (const [alias, current] of aliasReplacementsForPage(index, fm.data)) {
68
+ const re = new RegExp(`(^|[\\s\\[,'"-])${escapeRe(alias)}($|[\\s\\],'"])`, 'g');
69
+ next = next.replace(re, (_m, p1, p2) => `${p1}${current}${p2}`);
70
+ }
71
+ if (next !== line) {
72
+ lines[i] = next;
73
+ changed = true;
74
+ }
75
+ }
76
+ if (changed) {
77
+ await io.writeFile(file, lines.join('\n'));
78
+ io.stdout(`fixed alias references in ${file}`);
79
+ }
80
+ }
81
+ }
82
+ const outPath = values.out ?? join(process.cwd(), '.contentbit', 'link-index.json');
83
+ // The default target lives in a .contentbit/ dir that may not exist yet, and
84
+ // the shared Io.writeFile is a thin fs wrapper that won't create it.
85
+ await mkdir(dirname(outPath), { recursive: true });
86
+ await io.writeFile(outPath, JSON.stringify(serializeLinkIndex(index), null, 2) + '\n');
87
+ let edges = 0;
88
+ for (const p of index.pages.values())
89
+ edges += p.linksTo.length;
90
+ const orphans = [...index.pages.values()].filter((p) => p.linkedFrom.length === 0).length;
91
+ io.stdout(`${index.pages.size} page(s), ${edges} link(s), ${orphans} orphan(s): ${errors} errors, ${warnings} warnings`);
92
+ io.stdout(`index written to ${outPath}`);
93
+ return errors > 0 ? 1 : 0;
94
+ }
95
+ function escapeRe(s) {
96
+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
97
+ }
@@ -1 +1 @@
1
- {"version":3,"file":"render.d.ts","sourceRoot":"","sources":["../../src/commands/render.ts"],"names":[],"mappings":"AAWA,OAAO,KAAK,EAAE,EAAE,EAAE,MAAM,WAAW,CAAA;AAInC,wBAAsB,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,EAAE,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC,CA6B3E"}
1
+ {"version":3,"file":"render.d.ts","sourceRoot":"","sources":["../../src/commands/render.ts"],"names":[],"mappings":"AAYA,OAAO,KAAK,EAAE,EAAE,EAAE,MAAM,WAAW,CAAA;AAInC,wBAAsB,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,EAAE,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC,CA6B3E"}
@@ -1,5 +1,5 @@
1
1
  import { genericMarkdownRenderers } from '@contentbit/blocks';
2
- import { formatDiagnostic, parseDocument, renderToMarkdown, validateDocument, } from '@contentbit/core';
2
+ import { formatDiagnostic, parseDocument, renderToMarkdown, stripFrontmatter, validateDocument, } from '@contentbit/core';
3
3
  import { renderToHtml } from '@contentbit/html';
4
4
  import { readFile } from 'node:fs/promises';
5
5
  import { parseArgs } from 'node:util';
@@ -21,7 +21,7 @@ export async function renderCommand(args, io) {
21
21
  }
22
22
  const registry = await loadRegistry(values.registry);
23
23
  const source = await readFile(file, 'utf8');
24
- const result = validateDocument(parseDocument(source), registry);
24
+ const result = validateDocument(parseDocument(stripFrontmatter(source)), registry);
25
25
  if (!result.ok) {
26
26
  for (const d of result.diagnostics)
27
27
  io.stderr(formatDiagnostic(d, file));