contentbit 0.5.0 → 0.6.1

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 (52) hide show
  1. package/README.md +13 -0
  2. package/dist/bin.js +4807 -501
  3. package/dist/commands/agents.d.ts +6 -1
  4. package/dist/commands/agents.d.ts.map +1 -1
  5. package/dist/commands/brief.d.ts +12 -0
  6. package/dist/commands/brief.d.ts.map +1 -0
  7. package/dist/commands/docs.d.ts +6 -1
  8. package/dist/commands/docs.d.ts.map +1 -1
  9. package/dist/commands/doctor.d.ts +13 -1
  10. package/dist/commands/doctor.d.ts.map +1 -1
  11. package/dist/commands/init.d.ts +12 -1
  12. package/dist/commands/init.d.ts.map +1 -1
  13. package/dist/commands/instructions.d.ts +8 -1
  14. package/dist/commands/instructions.d.ts.map +1 -1
  15. package/dist/commands/links.d.ts +7 -1
  16. package/dist/commands/links.d.ts.map +1 -1
  17. package/dist/commands/render.d.ts +8 -1
  18. package/dist/commands/render.d.ts.map +1 -1
  19. package/dist/commands/stats.d.ts +7 -1
  20. package/dist/commands/stats.d.ts.map +1 -1
  21. package/dist/commands/studio.d.ts +13 -1
  22. package/dist/commands/studio.d.ts.map +1 -1
  23. package/dist/commands/validate.d.ts +8 -1
  24. package/dist/commands/validate.d.ts.map +1 -1
  25. package/dist/content-project.d.ts +2 -22
  26. package/dist/content-project.d.ts.map +1 -1
  27. package/dist/link-options.d.ts +5 -0
  28. package/dist/link-options.d.ts.map +1 -1
  29. package/dist/load-registry.d.ts +1 -6
  30. package/dist/load-registry.d.ts.map +1 -1
  31. package/dist/run.d.ts +1 -1
  32. package/dist/run.d.ts.map +1 -1
  33. package/dist/run.js +4805 -499
  34. package/dist/seo-config.d.ts +12 -0
  35. package/dist/seo-config.d.ts.map +1 -0
  36. package/package.json +6 -5
  37. package/dist/cli-format.js +0 -63
  38. package/dist/commands/agents.js +0 -73
  39. package/dist/commands/docs.js +0 -21
  40. package/dist/commands/doctor.js +0 -149
  41. package/dist/commands/init-targets.js +0 -280
  42. package/dist/commands/init.js +0 -343
  43. package/dist/commands/instructions.js +0 -26
  44. package/dist/commands/links.js +0 -101
  45. package/dist/commands/render.js +0 -45
  46. package/dist/commands/stats.js +0 -48
  47. package/dist/commands/studio.js +0 -78
  48. package/dist/commands/validate.js +0 -64
  49. package/dist/content-project.js +0 -34
  50. package/dist/link-options.js +0 -31
  51. package/dist/links-io.js +0 -14
  52. package/dist/load-registry.js +0 -26
@@ -1,343 +0,0 @@
1
- import { spawn } from 'node:child_process';
2
- import { existsSync } from 'node:fs';
3
- import { mkdir, readFile, writeFile } from 'node:fs/promises';
4
- import { join } from 'node:path';
5
- import { parseArgs } from 'node:util';
6
- import { loadRegistry } from '../load-registry.js';
7
- import { installAgentIntegration } from './agents.js';
8
- import { detectTarget, TARGET_ADAPTERS, TARGETS } from './init-targets.js';
9
- const REGISTRY_TEMPLATE = `// Custom block definitions for this project. The CLI and your app share
10
- // this module — Node 22.18+ imports TypeScript directly:
11
- //
12
- // contentbit validate "content/**/*.md" --registry ./blocks/registry.ts
13
- //
14
- // Definitions stay framework-free (the CLI and every render target use
15
- // them); render components live next door in blocks/components.tsx or
16
- // framework-specific component files copied from the shadcn registry.
17
- // Docs: https://contentbit.dev/docs/guides/custom-blocks
18
- import { defineBlock, markdownBody, type BlockDefinition } from '@contentbit/core'
19
- import { z } from 'zod'
20
-
21
- export const quote = defineBlock({
22
- name: 'quote',
23
- description: 'A pull quote with an author.',
24
- props: z.object({
25
- author: z.string().min(1),
26
- role: z.string().optional(),
27
- }),
28
- content: markdownBody({ minLength: 3 }),
29
- authoring: {
30
- useWhen: ['Quoting a person to support a point'],
31
- avoidWhen: ['Highlighting your own remark, use callout instead'],
32
- example: ':::quote{author="Ada Lovelace"}\\nThe Analytical Engine weaves algebraic patterns.\\n:::',
33
- },
34
- })
35
-
36
- export default [quote] satisfies BlockDefinition<unknown>[]
37
- `;
38
- const EXAMPLE_CONTENT = `---
39
- slug: hello-content-blocks
40
- linksTo:
41
- - related-contentbit-workflows
42
- aliases:
43
- - getting-started-contentbit
44
- keywords:
45
- primary: validated Markdown blocks
46
- secondary: [content workflow, agent writing]
47
- ---
48
-
49
- # Hello, Content Blocks
50
-
51
- Regular Markdown works everywhere. Blocks add validated structure:
52
-
53
- :::callout{type="tip" title="Try breaking this file"}
54
- Run the validate script and you will get file:line:col diagnostics.
55
- :::
56
-
57
- :::steps
58
- 1. Edit this file and add or break a block.
59
- 2. Run \`contentbit validate "content/**/*.md"\`.
60
- 3. Render it with the target you picked at init.
61
- :::
62
-
63
- This one is a **custom block**, defined in \`blocks/registry.ts\` and rendered
64
- by the \`QuoteBlock\` component, in about twenty lines:
65
-
66
- :::quote{author="Ada Lovelace" role="Notes on the Analytical Engine, 1843"}
67
- The Analytical Engine weaves algebraic patterns just as the Jacquard loom
68
- weaves flowers and leaves.
69
- :::
70
- `;
71
- const RELATED_CONTENT = `---
72
- slug: related-contentbit-workflows
73
- linksTo:
74
- - hello-content-blocks
75
- keywords:
76
- primary: contentbit workflow
77
- secondary: [validation loop, internal links]
78
- ---
79
-
80
- # Related contentbit workflows
81
-
82
- This supporting page exists to show internal links in frontmatter. The link
83
- graph is authored once with \`slug\` and \`linksTo\`, then contentbit derives
84
- \`linkedFrom\` in \`.contentbit/link-index.json\`.
85
-
86
- :::callout{type="note"}
87
- Run \`contentbit links "content/**/*.md" --fix\` after renaming a page. Alias
88
- references in \`linksTo\` are rewritten to the current slug, while \`aliases\`
89
- stays as the rename record.
90
- :::
91
- `;
92
- function detectPackageManager(cwd) {
93
- // The project's lockfile outranks however the CLI itself was launched.
94
- const locks = [
95
- ['pnpm-lock.yaml', 'pnpm'],
96
- ['yarn.lock', 'yarn'],
97
- ['bun.lock', 'bun'],
98
- ['bun.lockb', 'bun'],
99
- ['package-lock.json', 'npm'],
100
- ];
101
- for (const [file, pm] of locks) {
102
- if (existsSync(join(cwd, file)))
103
- return pm;
104
- }
105
- const agent = process.env.npm_config_user_agent ?? '';
106
- for (const pm of ['pnpm', 'yarn', 'bun']) {
107
- if (agent.startsWith(pm))
108
- return pm;
109
- }
110
- return 'npm';
111
- }
112
- function installArgs(pm, dev, pkgs) {
113
- const add = pm === 'npm' ? 'install' : 'add';
114
- return dev ? [add, '-D', ...pkgs] : [add, ...pkgs];
115
- }
116
- function dlxCommand(pm) {
117
- if (pm === 'pnpm')
118
- return ['pnpm', ['dlx']];
119
- if (pm === 'yarn')
120
- return ['yarn', ['dlx']];
121
- if (pm === 'bun')
122
- return ['bunx', []];
123
- return ['npx', ['--yes']];
124
- }
125
- function runInstall(pm, args, cwd) {
126
- return new Promise((resolve) => {
127
- const child = spawn(pm, args, { cwd, stdio: 'inherit', shell: process.platform === 'win32' });
128
- child.on('close', (code) => resolve(code ?? 1));
129
- child.on('error', () => resolve(1));
130
- });
131
- }
132
- /** Wire the @contentbit shadcn registry and install a styled pack. Returns true on success. */
133
- async function installStyledPack(cwd, pack, noInstall, io) {
134
- const componentsJsonPath = join(cwd, 'components.json');
135
- const componentsJson = JSON.parse(await readFile(componentsJsonPath, 'utf8'));
136
- componentsJson.registries ??= {};
137
- if (!componentsJson.registries['@contentbit']) {
138
- componentsJson.registries['@contentbit'] = 'https://contentbit.dev/r/{name}.json';
139
- await writeFile(componentsJsonPath, `${JSON.stringify(componentsJson, null, 2)}\n`, 'utf8');
140
- io.stdout('added @contentbit registry to components.json');
141
- }
142
- if (noInstall) {
143
- io.stdout(`skipped: shadcn add ${pack}`);
144
- return true;
145
- }
146
- const [bin, prefix] = dlxCommand(detectPackageManager(cwd));
147
- io.stdout(`installing the styled pack: shadcn add ${pack}`);
148
- const code = await runInstall(bin, [...prefix, 'shadcn@latest', 'add', pack, '--yes'], cwd);
149
- if (code !== 0)
150
- io.stderr('styled pack install failed; falling back to the headless renderer');
151
- return code === 0;
152
- }
153
- /** Write a file unless it already exists; returns what happened for the summary. */
154
- async function scaffold(path, content) {
155
- try {
156
- await readFile(path, 'utf8');
157
- return 'skipped';
158
- }
159
- catch {
160
- await mkdir(join(path, '..'), { recursive: true });
161
- await writeFile(path, content, 'utf8');
162
- return 'created';
163
- }
164
- }
165
- export async function initCommand(args, io) {
166
- const { values } = parseArgs({
167
- args,
168
- options: {
169
- target: { type: 'string', short: 't' },
170
- md: { type: 'string' },
171
- yes: { type: 'boolean', short: 'y', default: false },
172
- cwd: { type: 'string', default: process.cwd() },
173
- 'no-install': { type: 'boolean', default: false },
174
- 'no-page': { type: 'boolean', default: false },
175
- 'no-styled': { type: 'boolean', default: false },
176
- 'no-agents': { type: 'boolean', default: false },
177
- },
178
- });
179
- const cwd = values.cwd;
180
- // A project to init into is required.
181
- let pkg;
182
- const pkgPath = join(cwd, 'package.json');
183
- try {
184
- pkg = JSON.parse(await readFile(pkgPath, 'utf8'));
185
- }
186
- catch {
187
- io.stderr('No package.json found. Run this inside a project (npm init first).');
188
- return 1;
189
- }
190
- const deps = { ...pkg.dependencies, ...pkg.devDependencies };
191
- // Resolve the render target: flag > prompt (interactive) > detection.
192
- const detected = detectTarget(deps);
193
- let target;
194
- if (values.target) {
195
- if (!TARGETS.includes(values.target)) {
196
- io.stderr(`Unknown target "${values.target}". Use one of: ${TARGETS.join(', ')}`);
197
- return 2;
198
- }
199
- target = values.target;
200
- }
201
- else if (!values.yes && process.stdin.isTTY && process.stdout.isTTY) {
202
- const { isCancel, select } = await import('@clack/prompts');
203
- const answer = await select({
204
- message: 'Render target?',
205
- initialValue: detected,
206
- options: [
207
- { value: 'react', label: 'React', hint: 'ContentBlocks component' },
208
- { value: 'astro', label: 'Astro', hint: 'content collections + .astro components' },
209
- { value: 'markdown', label: 'Plain Markdown', hint: 'fallback rendering only' },
210
- ],
211
- });
212
- if (isCancel(answer))
213
- return 1;
214
- target = answer;
215
- }
216
- else {
217
- target = detected;
218
- }
219
- const adapter = TARGET_ADAPTERS[target];
220
- // Resolve the Markdown library: flag > prompt (interactive) > target default.
221
- // The default gives working prose rendering out of the box; 'none' opts out.
222
- const choices = adapter.markdownChoices;
223
- let md;
224
- if (values.md) {
225
- if (!choices.includes(values.md)) {
226
- io.stderr(`Unknown markdown library "${values.md}". Use one of: ${choices.join(', ')}`);
227
- return 2;
228
- }
229
- md = values.md;
230
- }
231
- else if (choices.length > 1 && !values.yes && process.stdin.isTTY && process.stdout.isTTY) {
232
- const { isCancel, select } = await import('@clack/prompts');
233
- const answer = await select({
234
- message: 'Markdown library for prose rendering?',
235
- initialValue: choices[0],
236
- options: choices.map((c) => ({
237
- value: c,
238
- label: c,
239
- hint: c === 'none' ? 'wire one yourself later' : 'installed and wired for you',
240
- })),
241
- });
242
- if (isCancel(answer))
243
- return 1;
244
- md = answer;
245
- }
246
- else {
247
- md = choices[0];
248
- }
249
- // Install runtime packages plus the CLI as a dev dependency.
250
- const runtime = adapter.runtimeDependencies(md);
251
- if (values['no-install']) {
252
- io.stdout(`skipped install: ${runtime.join(' ')} + contentbit (dev)`);
253
- }
254
- else {
255
- const pm = detectPackageManager(cwd);
256
- io.stdout(`installing with ${pm}: ${runtime.join(' ')}`);
257
- if ((await runInstall(pm, installArgs(pm, false, runtime), cwd)) !== 0) {
258
- io.stderr('install failed');
259
- return 1;
260
- }
261
- if ((await runInstall(pm, installArgs(pm, true, ['contentbit']), cwd)) !== 0) {
262
- io.stderr('install failed');
263
- return 1;
264
- }
265
- }
266
- const plan = await adapter.createPlan({
267
- cwd,
268
- deps,
269
- md,
270
- noPage: Boolean(values['no-page']),
271
- noStyled: Boolean(values['no-styled']),
272
- io,
273
- installStyledPack: (pack) => installStyledPack(cwd, pack, values['no-install'], io),
274
- });
275
- // Scaffold project files; never overwrite.
276
- const files = [
277
- ['blocks/registry.ts', REGISTRY_TEMPLATE],
278
- ['content/example.md', EXAMPLE_CONTENT],
279
- ['content/related.md', RELATED_CONTENT],
280
- ...plan.files,
281
- ];
282
- for (const [rel, content] of files) {
283
- const result = await scaffold(join(cwd, rel), content);
284
- io.stdout(`${result}: ${rel}`);
285
- }
286
- // Wire content scripts.
287
- const fresh = JSON.parse(await readFile(pkgPath, 'utf8'));
288
- fresh.scripts ??= {};
289
- if (!fresh.scripts['content:check']) {
290
- fresh.scripts['content:check'] =
291
- 'contentbit validate "content/**/*.md" --registry ./blocks/registry.ts';
292
- io.stdout('added script: content:check');
293
- }
294
- if (!fresh.scripts['content:links']) {
295
- fresh.scripts['content:links'] = 'contentbit links "content/**/*.md"';
296
- io.stdout('added script: content:links');
297
- }
298
- if (!fresh.scripts['content:doctor']) {
299
- fresh.scripts['content:doctor'] =
300
- 'contentbit doctor "content/**/*.md" --registry ./blocks/registry.ts';
301
- io.stdout('added script: content:doctor');
302
- }
303
- if (!fresh.scripts.studio) {
304
- fresh.scripts.studio = 'contentbit studio "content/**/*.md" --registry ./blocks/registry.ts';
305
- io.stdout('added script: studio');
306
- }
307
- if (!pkg.scripts?.['content:check'] ||
308
- !pkg.scripts?.['content:links'] ||
309
- !pkg.scripts?.['content:doctor'] ||
310
- !pkg.scripts?.studio) {
311
- await writeFile(pkgPath, `${JSON.stringify(fresh, null, 2)}\n`, 'utf8');
312
- }
313
- // Generate the LLM authoring guide from the registry, ready to paste into a prompt.
314
- let registry;
315
- try {
316
- // Include the scaffolded custom blocks so the guide covers them too.
317
- registry = await loadRegistry(join(cwd, 'blocks/registry.ts'));
318
- }
319
- catch {
320
- registry = await loadRegistry(); // packages not installed yet (--no-install)
321
- }
322
- const guide = registry.toAuthoringGuide({ audience: 'llm', includeExamples: true });
323
- await writeFile(join(cwd, 'contentbit-guide.md'), guide, 'utf8');
324
- io.stdout('created: contentbit-guide.md (LLM authoring instructions)');
325
- // Coding-agent integration: an AGENTS.md block for every agent, plus Claude
326
- // Code skills when a .claude/ directory exists. `contentbit agents` refreshes.
327
- if (!values['no-agents']) {
328
- await installAgentIntegration(cwd, {}, io);
329
- io.stdout('Agent integration installed — try asking your agent:');
330
- io.stdout(' "write a blog post about X" or "audit my content"');
331
- }
332
- io.stdout('');
333
- io.stdout('Done. Next steps:');
334
- const pm = detectPackageManager(cwd);
335
- io.stdout(` 1. Browse content locally: ${pm} run studio`);
336
- io.stdout(` Inspect content health: ${pm} run content:doctor`);
337
- io.stdout(` Validate the starter content: ${pm} run content:check`);
338
- io.stdout(` Build the link index: ${pm} run content:links`);
339
- for (const line of plan.nextSteps)
340
- io.stdout(line);
341
- io.stdout(' Docs: https://contentbit.dev/docs');
342
- return 0;
343
- }
@@ -1,26 +0,0 @@
1
- import { parseArgs } from 'node:util';
2
- import { loadRegistry } from '../load-registry.js';
3
- export async function instructionsCommand(args, io) {
4
- const { values } = parseArgs({
5
- args,
6
- options: {
7
- audience: { type: 'string', default: 'llm' },
8
- 'no-examples': { type: 'boolean', default: false },
9
- registry: { type: 'string' },
10
- 'no-generic-blocks': { type: 'boolean', default: false },
11
- out: { type: 'string' },
12
- },
13
- });
14
- const registry = await loadRegistry(values.registry, {
15
- includeGenericBlocks: !values['no-generic-blocks'],
16
- });
17
- const guide = registry.toAuthoringGuide({
18
- audience: values.audience === 'human' ? 'human' : 'llm',
19
- includeExamples: !values['no-examples'],
20
- });
21
- if (values.out)
22
- await io.writeFile(values.out, guide);
23
- else
24
- io.stdout(guide);
25
- return 0;
26
- }
@@ -1,101 +0,0 @@
1
- import { aliasReplacementsForPage, buildLinkIndex, extractFrontmatter, 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 { formatDiagnosticForCli, formatRows, section } from '../cli-format.js';
6
- import { resolveContentFiles } from '../content-project.js';
7
- import { linkResolverOptions } from '../link-options.js';
8
- import { collectLinkInputs } from '../links-io.js';
9
- export async function linksCommand(args, io) {
10
- const { values, positionals } = parseArgs({
11
- args,
12
- allowPositionals: true,
13
- options: {
14
- out: { type: 'string' },
15
- fix: { type: 'boolean', default: false },
16
- 'link-resolve': { type: 'string' },
17
- 'locale-field': { type: 'string' },
18
- 'slug-field': { type: 'string' },
19
- 'key-field': { type: 'string' },
20
- 'default-locale': { type: 'string' },
21
- },
22
- });
23
- const files = await resolveContentFiles(positionals, 'links');
24
- const inputs = await collectLinkInputs(files);
25
- const linkOptions = linkResolverOptions(values);
26
- let errors = 0;
27
- let warnings = 0;
28
- for (const { file, diagnostic } of validateLinks(inputs, linkOptions)) {
29
- io.stderr(formatDiagnosticForCli(diagnostic, file));
30
- if (diagnostic.severity === 'error')
31
- errors++;
32
- else if (diagnostic.severity === 'warning')
33
- warnings++;
34
- }
35
- const index = buildLinkIndex(inputs, linkOptions);
36
- if (values.fix && errors > 0) {
37
- io.stderr('links: --fix skipped because link errors must be resolved first.');
38
- }
39
- else if (values.fix && index.aliases.size > 0) {
40
- for (const file of files) {
41
- const source = await readFile(file, 'utf8');
42
- const fm = extractFrontmatter(source);
43
- if (!fm)
44
- continue;
45
- const lines = source.split('\n');
46
- let changed = false;
47
- // Only rewrite alias tokens inside the `linksTo:` block — never inside an
48
- // `aliases:` list (which records the rename and must stay intact), and
49
- // never in document body. Track whether we are within linksTo's scope:
50
- // a top-level key resets it, dash-list / inline continuation keeps it.
51
- let inLinksTo = false;
52
- for (let i = 0; i < fm.lines.end && i < lines.length; i++) {
53
- const line = lines[i];
54
- const topKey = line.match(/^([A-Za-z0-9_.-]+):(.*)$/);
55
- if (topKey)
56
- inLinksTo = topKey[1] === 'linksTo';
57
- if (!inLinksTo)
58
- continue;
59
- let next = line;
60
- for (const [alias, current] of aliasReplacementsForPage(index, fm.data)) {
61
- const re = new RegExp(`(^|[\\s\\[,'"-])${escapeRe(alias)}($|[\\s\\],'"])`, 'g');
62
- next = next.replace(re, (_m, p1, p2) => `${p1}${current}${p2}`);
63
- }
64
- if (next !== line) {
65
- lines[i] = next;
66
- changed = true;
67
- }
68
- }
69
- if (changed) {
70
- await io.writeFile(file, lines.join('\n'));
71
- io.stdout(`fixed alias references in ${file}`);
72
- }
73
- }
74
- }
75
- const outPath = values.out ?? join(process.cwd(), '.contentbit', 'link-index.json');
76
- // The default target lives in a .contentbit/ dir that may not exist yet, and
77
- // the shared Io.writeFile is a thin fs wrapper that won't create it.
78
- await mkdir(dirname(outPath), { recursive: true });
79
- await io.writeFile(outPath, JSON.stringify(serializeLinkIndex(index), null, 2) + '\n');
80
- let edges = 0;
81
- for (const p of index.pages.values())
82
- edges += p.linksTo.length;
83
- const orphans = [...index.pages.values()].filter((p) => p.linkedFrom.length === 0).length;
84
- io.stdout([
85
- section('Link Index'),
86
- ...formatRows([
87
- { label: 'Pages', value: index.pages.size },
88
- { label: 'Links', value: edges },
89
- { label: 'Orphans', value: orphans, tone: orphans > 0 ? 'warning' : 'success' },
90
- { label: 'Errors', value: errors, tone: errors > 0 ? 'error' : 'success' },
91
- { label: 'Warnings', value: warnings, tone: warnings > 0 ? 'warning' : 'success' },
92
- ]),
93
- '',
94
- section('Written'),
95
- ` ${outPath}`,
96
- ].join('\n'));
97
- return errors > 0 ? 1 : 0;
98
- }
99
- function escapeRe(s) {
100
- return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
101
- }
@@ -1,45 +0,0 @@
1
- import { genericMarkdownRenderers } from '@contentbit/blocks';
2
- import { parseDocument, renderToMarkdown, stripFrontmatter, validateDocument, } from '@contentbit/core';
3
- import { readFile } from 'node:fs/promises';
4
- import { parseArgs } from 'node:util';
5
- import { formatDiagnosticForCli } from '../cli-format.js';
6
- import { loadRegistry } from '../load-registry.js';
7
- export async function renderCommand(args, io) {
8
- const { values, positionals } = parseArgs({
9
- args,
10
- allowPositionals: true,
11
- options: {
12
- target: { type: 'string', default: 'markdown' },
13
- registry: { type: 'string' },
14
- 'no-generic-blocks': { type: 'boolean', default: false },
15
- out: { type: 'string' },
16
- },
17
- });
18
- const file = positionals[0];
19
- if (!file || values.target !== 'markdown') {
20
- io.stderr('render: usage: render <file> [--target markdown] ' +
21
- '[--registry <module.ts>] [--no-generic-blocks] [--out <file>]');
22
- return 2;
23
- }
24
- const includeGenericBlocks = !values['no-generic-blocks'];
25
- const registry = await loadRegistry(values.registry, { includeGenericBlocks });
26
- const source = await readFile(file, 'utf8');
27
- const result = validateDocument(parseDocument(stripFrontmatter(source)), registry);
28
- if (!result.ok) {
29
- for (const d of result.diagnostics)
30
- io.stderr(formatDiagnosticForCli(d, file));
31
- return 1;
32
- }
33
- const output = renderToMarkdown(result.document, {
34
- renderers: includeGenericBlocks ? genericMarkdownRenderers : genericMarkdownFallbackRenderers,
35
- });
36
- if (values.out)
37
- await io.writeFile(values.out, output);
38
- else
39
- io.stdout(output);
40
- return 0;
41
- }
42
- const genericMarkdownFallbackRenderers = Object.fromEntries(Object.keys(genericMarkdownRenderers).map((name) => [
43
- name,
44
- ((node) => `${node.body}\n`),
45
- ]));
@@ -1,48 +0,0 @@
1
- import { analyzeDocument } from '@contentbit/core';
2
- import { readFile } from 'node:fs/promises';
3
- import { parseArgs } from 'node:util';
4
- import { loadContentProject, resolveContentFiles } from '../content-project.js';
5
- export async function statsCommand(args, io) {
6
- const { values, positionals } = parseArgs({
7
- args,
8
- allowPositionals: true,
9
- options: {
10
- registry: { type: 'string' },
11
- 'no-generic-blocks': { type: 'boolean', default: false },
12
- 'no-validate': { type: 'boolean', default: false },
13
- },
14
- });
15
- const all = values['no-validate']
16
- ? await statsOnly(positionals)
17
- : await statsWithValidation(values, positionals);
18
- // A single file keeps the flat object shape; multiple files emit an array.
19
- io.stdout(JSON.stringify(all.length === 1 ? all[0] : all, null, 2));
20
- return 0;
21
- }
22
- /** Default path: cross the loaded-content-project seam so stats and the other
23
- * read-commands share one validation path. */
24
- async function statsWithValidation(values, positionals) {
25
- const { scan } = await loadContentProject({
26
- cmd: 'stats',
27
- positionals,
28
- registry: values.registry,
29
- includeGenericBlocks: !values['no-generic-blocks'],
30
- linkOptions: {},
31
- });
32
- return scan.files.map((file) => {
33
- let errors = 0;
34
- let warnings = 0;
35
- for (const d of file.validation.diagnostics) {
36
- if (d.severity === 'error')
37
- errors++;
38
- else if (d.severity === 'warning')
39
- warnings++;
40
- }
41
- return { ...file.stats, validation: { errors, warnings } };
42
- });
43
- }
44
- /** `--no-validate`: stats only, no registry, no scan. */
45
- async function statsOnly(positionals) {
46
- const files = await resolveContentFiles(positionals, 'stats');
47
- return Promise.all(files.map(async (file) => analyzeDocument(await readFile(file, 'utf8'), { path: file })));
48
- }
@@ -1,78 +0,0 @@
1
- import { parseArgs } from 'node:util';
2
- import { formatRows, section } from '../cli-format.js';
3
- import { resolveContentFiles } from '../content-project.js';
4
- import { linkResolverOptions } from '../link-options.js';
5
- export async function studioCommand(args, io) {
6
- const { values, positionals } = parseArgs({
7
- args,
8
- allowPositionals: true,
9
- options: {
10
- registry: { type: 'string' },
11
- port: { type: 'string' },
12
- host: { type: 'string' },
13
- 'no-open': { type: 'boolean', default: false },
14
- 'no-generic-blocks': { type: 'boolean', default: false },
15
- 'min-section-words': { type: 'string' },
16
- 'link-resolve': { type: 'string' },
17
- 'locale-field': { type: 'string' },
18
- 'slug-field': { type: 'string' },
19
- 'key-field': { type: 'string' },
20
- 'default-locale': { type: 'string' },
21
- },
22
- });
23
- const port = parsePort(values.port);
24
- if (port === null) {
25
- io.stderr('studio: --port must be an integer between 0 and 65535.');
26
- return 2;
27
- }
28
- const minSectionWords = parseMinSectionWords(values['min-section-words']);
29
- if (minSectionWords === null) {
30
- io.stderr('studio: --min-section-words must be a non-negative integer.');
31
- return 2;
32
- }
33
- // Guard empty/no-match the same way the read-commands do; startStudio does its
34
- // own globbing from `positionals`, so we only need the shared check here.
35
- await resolveContentFiles(positionals, 'studio');
36
- const { startStudio } = (await import('@contentbit/studio'));
37
- const server = await startStudio({
38
- globs: positionals,
39
- registryPath: values.registry,
40
- includeGenericBlocks: !values['no-generic-blocks'],
41
- host: values.host,
42
- ...(port !== undefined ? { port } : {}),
43
- open: !values['no-open'],
44
- linkOptions: linkResolverOptions(values),
45
- minSectionWords,
46
- });
47
- io.stdout([
48
- section('contentbit studio'),
49
- ...formatRows([
50
- { label: 'URL', value: server.url, tone: 'info' },
51
- { label: 'Stop', value: 'Ctrl+C' },
52
- ]),
53
- ].join('\n'));
54
- const close = () => {
55
- void server.close();
56
- };
57
- process.once('SIGINT', close);
58
- process.once('SIGTERM', close);
59
- await server.closed;
60
- process.off('SIGINT', close);
61
- process.off('SIGTERM', close);
62
- return 0;
63
- }
64
- function parsePort(value) {
65
- if (value === undefined)
66
- return undefined;
67
- if (!/^\d+$/.test(value))
68
- return null;
69
- const port = Number(value);
70
- return port >= 0 && port <= 65535 ? port : null;
71
- }
72
- function parseMinSectionWords(value) {
73
- if (value === undefined)
74
- return undefined;
75
- if (!/^\d+$/.test(value))
76
- return null;
77
- return Number(value);
78
- }