@writedocs/generator 0.13.3 → 0.13.4

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.
package/bin/writedocs.js CHANGED
@@ -1,325 +1,356 @@
1
- #!/usr/bin/env node
2
- import { Command } from 'commander';
3
- import fs from 'node:fs';
4
- import path from 'node:path';
5
- import { fileURLToPath } from 'node:url';
6
- import dotenv from 'dotenv';
7
- import { runDev } from '../src/cli/dev.js';
8
- import { runBuild } from '../src/cli/build.js';
9
- import { runInit } from '../src/cli/init.js';
10
- import { requireBuildKey } from '../src/cli/build-auth.js';
11
- import { log, step, plural, color, CliExit, errorText, stopActiveStep } from '../src/cli/output.js';
12
- import { startUpdateCheck, showUpdateNotice } from '../src/cli/update-check.js';
13
- import { readConfigText } from '../src/lib/config-file.js';
14
- import { canonicalPath } from '../src/lib/canonical-path.js';
15
- // O MESMO modulo que o build usa (via loadDocsConfig, que reexporta daqui) e
16
- // que a plataforma importa por `@writedocs/generator/config-schema` - e o que
17
- // faz os tres reportarem os mesmos problemas com as mesmas palavras, em vez de
18
- // cada um manter a sua copia do schema.
19
- //
20
- // `.js`, e nao o `.ts` que e a fonte de verdade: este arquivo e carregado por
21
- // node puro, sem o transform do Astro/Vite, e o Node RECUSA type stripping para
22
- // qualquer arquivo sob node_modules - por desenho, em qualquer versao
23
- // (ERR_UNSUPPORTED_NODE_MODULES_TYPE_STRIPPING). Ou seja: importar o `.ts` aqui
24
- // funciona a partir do checkout e falha 100% das vezes para quem instala o
25
- // pacote, que foi exatamente o que quebrou o `validate` no 0.2.0. O `.js` e
26
- // gerado do `.ts` pelo script `prepare` (package.json), entao ele existe tanto
27
- // no checkout quanto dentro do tarball, e o consumidor nao roda build nenhum.
28
- // Ver a mesma regra ja escrita em src/cli/write-redirects-file.js.
29
- import {
30
- validateDocsConfig,
31
- formatValidationIssuesDetailed,
32
- unknownRootKeyIssues,
33
- } from '../src/lib/config-schema.js';
34
-
35
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
36
- // The drive letter in capitals, however the shell spelled it - see
37
- // src/lib/canonical-path.js.
38
- const packageRoot = canonicalPath(path.resolve(__dirname, '..'));
39
- // Read rather than hardcode - a literal version string here silently drifts
40
- // from package.json's own "version" the moment either one is bumped without
41
- // the other (exactly what `npm version <bump>` does: it only touches
42
- // package.json). `writedocs --version` should always reflect what actually
43
- // got published, not whatever this string happened to say at the time this
44
- // line was last hand-edited.
45
- const { name: packageName, version } = JSON.parse(fs.readFileSync(path.join(packageRoot, 'package.json'), 'utf-8'));
46
-
47
- const program = new Command();
48
- program
49
- .name('writedocs')
50
- .description('Static site generator for writedocs.json + MDX')
51
- .version(version)
52
- // The built-in `help <command>` prints any command's usage, hidden ones
53
- // included - replaced by the `help` command at the bottom of this file.
54
- .helpCommand(false)
55
- // Every command checks for a newer writedocs (from a cache - see
56
- // src/cli/update-check.js); the notice prints after the command's output.
57
- .hook('preAction', (_program, command) => {
58
- startUpdateCheck({ command: command.name(), name: packageName, version, packageRoot });
59
- });
60
-
61
- program
62
- .command('dev')
63
- .description('Start a local dev server with hot reload')
64
- .argument('[dir]', 'content directory (contains writedocs.json and docs/)', '.')
65
- .option('-p, --port <port>', 'port to run on')
66
- .option('--verbose', "also print Astro's and Vite's own output")
67
- .option('--no-open', "don't open the preview in the browser")
68
- .action(async (dir, opts) => {
69
- await runDev({
70
- contentDir: canonicalPath(path.resolve(process.cwd(), dir)),
71
- packageRoot,
72
- port: opts.port,
73
- verbose: Boolean(opts.verbose),
74
- open: opts.open,
75
- });
76
- });
77
-
78
- program
79
- // { hidden: true } keeps `build` out of `writedocs --help` - it's not a
80
- // command ordinary users are meant to discover or run themselves. See
81
- // src/cli/build-auth.js for the second layer: even someone who knows the
82
- // command exists still can't run it without the right key.
83
- .command('build', { hidden: true })
84
- // `build --help` prints the general help, which doesn't list it: hidden
85
- // means not described anywhere (see the `help` command at the bottom too).
86
- .configureHelp({ formatHelp: () => program.helpInformation() })
87
- .description('Build a static site into <dir>/dist')
88
- .argument('[dir]', 'content directory (contains writedocs.json and docs/)', '.')
89
- .option('-k, --key <key>', 'build authorization key (or set WRITEDOCS_API_KEY)')
90
- .option('--verbose', "also print Astro's and Vite's own output")
91
- .action(async (dir, opts) => {
92
- const contentDir = canonicalPath(path.resolve(process.cwd(), dir));
93
- // Project-scoped, not global: a .env sitting next to this project's own
94
- // writedocs.json (WRITEDOCS_API_KEY) is picked up automatically, so
95
- // build doesn't need it exported by hand every
96
- // session. dotenv never overwrites a var already set in the real
97
- // environment - an explicit `export`/CI secret still wins over the file.
98
- dotenv.config({ path: path.join(contentDir, '.env'), quiet: true });
99
- await requireBuildKey(opts.key || process.env.WRITEDOCS_API_KEY);
100
- await runBuild({ contentDir, packageRoot, verbose: Boolean(opts.verbose) });
101
- });
102
-
103
- program
104
- // Visivel, ao contrario do `build`: validar a propria configuracao e
105
- // exatamente o tipo de coisa que um usuario deve poder rodar sozinho, no CI
106
- // inclusive. Sem chave, sem dotenv, sem rede - le um arquivo e sai 0 ou 1.
107
- .command('validate')
108
- .description('Validate writedocs.json and every page - frontmatter, MDX, navigation, components, icons')
109
- .argument('[dir]', 'content directory (contains writedocs.json)', '.')
110
- .option('--config-only', 'check writedocs.json only, not the pages')
111
- .action(async (dir, options) => {
112
- const contentDir = canonicalPath(path.resolve(process.cwd(), dir));
113
- const configPath = path.join(contentDir, 'writedocs.json');
114
- if (!fs.existsSync(configPath)) {
115
- // Mesma mensagem que loadDocsConfig() ja da pro mesmo caso.
116
- log.error(`No writedocs.json found in ${contentDir}`);
117
- log.detail(color.dim('Run "writedocs init" to create one.'));
118
- throw new CliExit(1);
119
- }
120
-
121
- const rawText = readConfigText(contentDir);
122
- const result = validateDocsConfig(rawText);
123
- // Chave desconhecida na raiz e AVISO, nunca erro: a raiz nao e `.strict()`
124
- // de proposito (tornar strict quebraria configs existentes), entao o Zod
125
- // descarta a chave em silencio. Sem JSON parseavel nao ha chave pra avaliar.
126
- const warnings = result.kind === 'invalid_json' ? [] : unknownRootKeyIssues(rawText);
127
- const nomeArquivo = path.basename(configPath);
128
-
129
- if (!result.ok) {
130
- // A versao longa (linha, frase humana, sugestao) em vez da curta que o
131
- // `writedocs build` imprime: aqui o usuario pediu explicitamente um
132
- // diagnostico, e tem a tela inteira pra ele.
133
- log.error(
134
- result.kind === 'invalid_json'
135
- ? `${nomeArquivo} is not valid JSON`
136
- : `${plural(result.issues.length, 'error')} in ${nomeArquivo}`
137
- );
138
- log.line();
139
- log.line(formatValidationIssuesDetailed(result.issues, { fileName: nomeArquivo }));
140
- log.line();
141
- }
142
-
143
- if (warnings.length > 0) {
144
- log.warn(`${plural(warnings.length, 'warning')} in ${nomeArquivo}`);
145
- log.line();
146
- log.line(formatValidationIssuesDetailed(warnings, { fileName: nomeArquivo }));
147
- log.line();
148
- }
149
-
150
- // The pages: everything that would fail the build (errors) or build
151
- // differently than written (warnings), in one pass - see
152
- // src/lib/content-check.js. Runs even when writedocs.json itself is
153
- // invalid, so one run reports both; only the navigation/icon checks
154
- // need writedocs.json to at least be valid JSON.
155
- let content = null;
156
- if (!options.configOnly) {
157
- const { checkContent, formatContentIssues } = await import('../src/lib/content-check.js');
158
- const checking = step('Checking pages');
159
- content = await checkContent(contentDir, result.kind === 'invalid_json' ? null : rawText);
160
- checking.stop();
161
- if (content.errors.length > 0) {
162
- log.error(`${plural(content.errors.length, 'error')} in the pages`);
163
- log.line();
164
- log.line(formatContentIssues(content.errors));
165
- log.line();
166
- }
167
- if (content.warnings.length > 0) {
168
- log.warn(`${plural(content.warnings.length, 'warning')} in the pages`);
169
- log.line();
170
- log.line(formatContentIssues(content.warnings));
171
- log.line();
172
- }
173
- }
174
-
175
- if (!result.ok || (content && content.errors.length > 0)) {
176
- const total = (result.ok ? 0 : result.issues.length) + (content ? content.errors.length : 0);
177
- log.error(`Not valid: ${plural(total, 'error')} to fix - the build would fail on these.`);
178
- throw new CliExit(1);
179
- }
180
- // Aviso nao invalida: um config so com avisos continua valido, e sai 0 -
181
- // o mesmo criterio que a plataforma usa pra marcar o projeto como `valid`.
182
- log.success(`${nomeArquivo} is valid`);
183
- if (content) {
184
- log.success(
185
- `Checked ${plural(content.pages, 'page')}: no errors` +
186
- (content.warnings.length ? `, ${plural(content.warnings.length, 'warning')} above` : '')
187
- );
188
- }
189
- });
190
-
191
- program
192
- // Like `validate`: no key, no build, no network - reads the project and
193
- // exits 0 (no broken links) or 1, so it works as a CI step.
194
- .command('broken-links')
195
- .description('Check every internal link - pages, anchors and files - in the pages and writedocs.json')
196
- .argument('[dir]', 'content directory (contains writedocs.json)', '.')
197
- .action(async (dir) => {
198
- const contentDir = canonicalPath(path.resolve(process.cwd(), dir));
199
- const { preflightCheck } = await import('../src/cli/preflight.js');
200
- preflightCheck(contentDir);
201
- const configText = readConfigText(contentDir);
202
- const checking = step('Checking links');
203
- // Generated OpenAPI pages are link targets too - same step dev/build run.
204
- const { generateApiPages } = await import('../src/cli/generate-api-pages.js');
205
- await generateApiPages({ contentDir });
206
- const { checkLinks } = await import('../src/lib/link-check.js');
207
- const { formatContentIssues } = await import('../src/lib/content-check.js');
208
- const result = await checkLinks(contentDir, configText);
209
- checking.stop();
210
-
211
- const summary = `${plural(result.links, 'link')} in ${plural(result.pages, 'page')}${
212
- result.external ? color.dim(` (${plural(result.external, 'external link')} not checked)`) : ''
213
- }`;
214
- if (result.broken.length === 0) {
215
- log.success(`No broken links - checked ${summary}`);
216
- return;
217
- }
218
- log.error(plural(result.broken.length, 'broken link'));
219
- log.line();
220
- log.line(formatContentIssues(result.broken));
221
- log.line();
222
- log.error(`${plural(result.broken.length, 'broken link')} - checked ${summary}`);
223
- throw new CliExit(1);
224
- });
225
-
226
- program
227
- // Same shape as `broken-links`: reads the project, exits 0 (nothing
228
- // found) or 1.
229
- .command('a11y')
230
- .description('Check accessibility - color contrast, image alt text, headings, link text')
231
- .argument('[dir]', 'content directory (contains writedocs.json)', '.')
232
- .action(async (dir) => {
233
- const contentDir = canonicalPath(path.resolve(process.cwd(), dir));
234
- const { preflightCheck } = await import('../src/cli/preflight.js');
235
- preflightCheck(contentDir);
236
- const configText = readConfigText(contentDir);
237
- const checking = step('Checking accessibility');
238
- const { checkAccessibility } = await import('../src/lib/a11y-check.js');
239
- const { formatContentIssues } = await import('../src/lib/content-check.js');
240
- const result = await checkAccessibility(contentDir, configText);
241
- checking.stop();
242
-
243
- if (result.issues.length === 0) {
244
- log.success(`No accessibility issues - checked writedocs.json and ${plural(result.pages, 'page')}`);
245
- return;
246
- }
247
- const count = plural(result.issues.length, 'accessibility issue');
248
- log.error(count);
249
- log.line();
250
- log.line(formatContentIssues(result.issues));
251
- log.line();
252
- log.error(`${count} - checked writedocs.json and ${plural(result.pages, 'page')}`);
253
- throw new CliExit(1);
254
- });
255
-
256
- program
257
- .command('convert')
258
- .description("Convert another docs tool's config into writedocs.json")
259
- .argument('[dir]', 'project directory (contains docs.json or config.json)', '.')
260
- .option('--mintlify', "convert a Mintlify project's docs.json")
261
- .option('--docs.json', 'same as --mintlify')
262
- .option('--writedocs', "convert a project from the previous writedocs (its config.json)")
263
- .option('--config.json', 'same as --writedocs')
264
- .option('--force', 'overwrite an existing writedocs.json')
265
- .option('--dry-run', 'print the converted writedocs.json instead of writing it')
266
- .action(async (dir, options) => {
267
- // Commander camel-cases only on hyphens: `--docs.json` is stored under
268
- // the key "docs.json", not `docsJson`.
269
- const mintlify = options.mintlify || options['docs.json'];
270
- const legacy = options.writedocs || options['config.json'];
271
- if (mintlify === legacy) {
272
- log.error(
273
- mintlify
274
- ? 'Pick one: --mintlify or --writedocs.'
275
- : 'Say what to convert from: writedocs convert --mintlify [dir], or --writedocs for the previous writedocs.'
276
- );
277
- throw new CliExit(1);
278
- }
279
- const { runConvert } = await import('../src/cli/convert.js');
280
- await runConvert({
281
- source: legacy ? 'writedocs' : 'mintlify',
282
- contentDir: canonicalPath(path.resolve(process.cwd(), dir)),
283
- force: Boolean(options.force),
284
- dryRun: Boolean(options.dryRun),
285
- });
286
- });
287
-
288
- program
289
- .command('update')
290
- .description('Update writedocs to the latest version')
291
- .action(async () => {
292
- const { runUpdate } = await import('../src/cli/update.js');
293
- await runUpdate({ name: packageName, version, packageRoot });
294
- });
295
-
296
- program
297
- .command('init')
298
- .description('Scaffold a writedocs.json and starter docs/ folder')
299
- .argument('[dir]', 'directory to scaffold into', '.')
300
- .action(async (dir) => {
301
- await runInit({ targetDir: path.resolve(process.cwd(), dir) });
302
- });
303
-
304
- // `writedocs help [command]` - commander's own, except that a hidden command
305
- // (`build`) gets the general help, like a name that isn't a command at all.
306
- const HIDDEN_COMMANDS = new Set(['build']);
307
- program
308
- .command('help')
309
- .description('display help for command')
310
- .argument('[command]')
311
- .action((name) => {
312
- const command = name && !HIDDEN_COMMANDS.has(name) ? program.commands.find((c) => c.name() === name) : undefined;
313
- (command ?? program).help();
314
- });
315
-
316
- program
317
- .parseAsync(process.argv)
318
- .then(showUpdateNotice)
319
- .catch((err) => {
320
- stopActiveStep();
321
- // A command that already printed its own error throws CliExit.
322
- if (!(err instanceof CliExit)) log.error(errorText(err));
323
- showUpdateNotice();
324
- process.exit(err instanceof CliExit ? err.code : 1);
325
- });
1
+ #!/usr/bin/env node
2
+ import { Command } from 'commander';
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ import dotenv from 'dotenv';
7
+ import { runDev } from '../src/cli/dev.js';
8
+ import { runBuild } from '../src/cli/build.js';
9
+ import { runInit } from '../src/cli/init.js';
10
+ import { requireBuildKey } from '../src/cli/build-auth.js';
11
+ import { log, step, plural, color, CliExit, errorText, stopActiveStep } from '../src/cli/output.js';
12
+ import { startUpdateCheck, showUpdateNotice } from '../src/cli/update-check.js';
13
+ import { exitWhenFlushed } from '../src/cli/exit-when-flushed.js';
14
+ import { readConfigText } from '../src/lib/config-file.js';
15
+ import { canonicalPath } from '../src/lib/canonical-path.js';
16
+ // O MESMO modulo que o build usa (via loadDocsConfig, que reexporta daqui) e
17
+ // que a plataforma importa por `@writedocs/generator/config-schema` - e o que
18
+ // faz os tres reportarem os mesmos problemas com as mesmas palavras, em vez de
19
+ // cada um manter a sua copia do schema.
20
+ //
21
+ // `.js`, e nao o `.ts` que e a fonte de verdade: este arquivo e carregado por
22
+ // node puro, sem o transform do Astro/Vite, e o Node RECUSA type stripping para
23
+ // qualquer arquivo sob node_modules - por desenho, em qualquer versao
24
+ // (ERR_UNSUPPORTED_NODE_MODULES_TYPE_STRIPPING). Ou seja: importar o `.ts` aqui
25
+ // funciona a partir do checkout e falha 100% das vezes para quem instala o
26
+ // pacote, que foi exatamente o que quebrou o `validate` no 0.2.0. O `.js` e
27
+ // gerado do `.ts` pelo script `prepare` (package.json), entao ele existe tanto
28
+ // no checkout quanto dentro do tarball, e o consumidor nao roda build nenhum.
29
+ // Ver a mesma regra ja escrita em src/cli/write-redirects-file.js.
30
+ import {
31
+ validateDocsConfig,
32
+ formatValidationIssuesDetailed,
33
+ unknownRootKeyWarnings,
34
+ VALIDATION_ISSUE_LIMIT,
35
+ } from '../src/lib/config-schema.js';
36
+
37
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
38
+ // The drive letter in capitals, however the shell spelled it - see
39
+ // src/lib/canonical-path.js.
40
+ const packageRoot = canonicalPath(path.resolve(__dirname, '..'));
41
+ // Read rather than hardcode - a literal version string here silently drifts
42
+ // from package.json's own "version" the moment either one is bumped without
43
+ // the other (exactly what `npm version <bump>` does: it only touches
44
+ // package.json). `writedocs --version` should always reflect what actually
45
+ // got published, not whatever this string happened to say at the time this
46
+ // line was last hand-edited.
47
+ const { name: packageName, version } = JSON.parse(fs.readFileSync(path.join(packageRoot, 'package.json'), 'utf-8'));
48
+
49
+ const program = new Command();
50
+ program
51
+ .name('writedocs')
52
+ .description('Static site generator for writedocs.json + MDX')
53
+ .version(version)
54
+ // The built-in `help <command>` prints any command's usage, hidden ones
55
+ // included - replaced by the `help` command at the bottom of this file.
56
+ .helpCommand(false)
57
+ // Every command checks for a newer writedocs (from a cache - see
58
+ // src/cli/update-check.js); the notice prints after the command's output.
59
+ .hook('preAction', (_program, command) => {
60
+ startUpdateCheck({ command: command.name(), name: packageName, version, packageRoot });
61
+ });
62
+
63
+ program
64
+ .command('dev')
65
+ .description('Start a local dev server with hot reload')
66
+ .argument('[dir]', 'content directory (contains writedocs.json and docs/)', '.')
67
+ .option('-p, --port <port>', 'port to run on')
68
+ .option('--verbose', "also print Astro's and Vite's own output")
69
+ .option('--no-open', "don't open the preview in the browser")
70
+ .action(async (dir, opts) => {
71
+ await runDev({
72
+ contentDir: canonicalPath(path.resolve(process.cwd(), dir)),
73
+ packageRoot,
74
+ port: opts.port,
75
+ verbose: Boolean(opts.verbose),
76
+ open: opts.open,
77
+ });
78
+ });
79
+
80
+ program
81
+ // { hidden: true } keeps `build` out of `writedocs --help` - it's not a
82
+ // command ordinary users are meant to discover or run themselves. See
83
+ // src/cli/build-auth.js for the second layer: even someone who knows the
84
+ // command exists still can't run it without the right key.
85
+ .command('build', { hidden: true })
86
+ // `build --help` prints the general help, which doesn't list it: hidden
87
+ // means not described anywhere (see the `help` command at the bottom too).
88
+ .configureHelp({ formatHelp: () => program.helpInformation() })
89
+ .description('Build a static site into <dir>/dist')
90
+ .argument('[dir]', 'content directory (contains writedocs.json and docs/)', '.')
91
+ .option('-k, --key <key>', 'build authorization key (or set WRITEDOCS_API_KEY)')
92
+ .option('--verbose', "also print Astro's and Vite's own output")
93
+ .action(async (dir, opts) => {
94
+ const contentDir = canonicalPath(path.resolve(process.cwd(), dir));
95
+ // Project-scoped, not global: a .env sitting next to this project's own
96
+ // writedocs.json (WRITEDOCS_API_KEY) is picked up automatically, so
97
+ // build doesn't need it exported by hand every
98
+ // session. dotenv never overwrites a var already set in the real
99
+ // environment - an explicit `export`/CI secret still wins over the file.
100
+ dotenv.config({ path: path.join(contentDir, '.env'), quiet: true });
101
+ await requireBuildKey(opts.key || process.env.WRITEDOCS_API_KEY);
102
+ await runBuild({ contentDir, packageRoot, verbose: Boolean(opts.verbose) });
103
+ });
104
+
105
+ program
106
+ // Visivel, ao contrario do `build`: validar a propria configuracao e
107
+ // exatamente o tipo de coisa que um usuario deve poder rodar sozinho, no CI
108
+ // inclusive. Sem chave, sem dotenv, sem rede - le um arquivo e sai 0 ou 1.
109
+ .command('validate')
110
+ .description('Validate writedocs.json and every page - frontmatter, MDX, navigation, components, icons')
111
+ .argument('[dir]', 'content directory (contains writedocs.json)', '.')
112
+ .option('--config-only', 'check writedocs.json only, not the pages')
113
+ .option('--all', `list every problem in writedocs.json, not only the first ${VALIDATION_ISSUE_LIMIT}`)
114
+ .action(async (dir, options) => {
115
+ const contentDir = canonicalPath(path.resolve(process.cwd(), dir));
116
+ const configPath = path.join(contentDir, 'writedocs.json');
117
+ if (!fs.existsSync(configPath)) {
118
+ // Mesma mensagem que loadDocsConfig() ja da pro mesmo caso.
119
+ log.error(`No writedocs.json found in ${contentDir}`);
120
+ log.detail(color.dim('Run "writedocs init" to create one.'));
121
+ throw new CliExit(1);
122
+ }
123
+
124
+ const rawText = readConfigText(contentDir);
125
+ // Sem `--all`, a validacao para depois de VALIDATION_ISSUE_LIMIT erros
126
+ // (WD-315): a lista traz os primeiros, e `issuesTruncated` diz que ha mais,
127
+ // sem saber quantos. `--all` valida tudo e lista tudo, como antes.
128
+ const all = Boolean(options.all);
129
+ const result = validateDocsConfig(rawText, { all });
130
+ // Chave desconhecida na raiz e AVISO, nunca erro: a raiz nao e `.strict()`
131
+ // de proposito (tornar strict quebraria configs existentes), entao o Zod
132
+ // descarta a chave em silencio. Sem JSON parseavel nao ha chave pra avaliar.
133
+ // Os avisos chegam com no maximo VALIDATION_ISSUE_LIMIT (todos, com `--all`),
134
+ // e o total deles e sempre exato.
135
+ const warnings = result.kind === 'invalid_json' ? { issues: [], issuesTotal: 0 } : unknownRootKeyWarnings(rawText, { all });
136
+ const nomeArquivo = path.basename(configPath);
137
+
138
+ if (!result.ok) {
139
+ // A versao longa (linha, frase humana, sugestao) em vez da curta que o
140
+ // `writedocs build` imprime: aqui o usuario pediu explicitamente um
141
+ // diagnostico, e tem a tela inteira pra ele.
142
+ log.error(
143
+ result.kind === 'invalid_json'
144
+ ? `${nomeArquivo} is not valid JSON`
145
+ : result.issuesTruncated
146
+ ? `More than ${VALIDATION_ISSUE_LIMIT} errors in ${nomeArquivo}`
147
+ : `${plural(result.issuesTotal, 'error')} in ${nomeArquivo}`
148
+ );
149
+ log.line();
150
+ log.line(
151
+ formatValidationIssuesDetailed(result.issues, {
152
+ fileName: nomeArquivo,
153
+ total: result.issuesTotal,
154
+ truncated: result.issuesTruncated,
155
+ })
156
+ );
157
+ log.line();
158
+ }
159
+
160
+ if (warnings.issuesTotal > 0) {
161
+ log.warn(`${plural(warnings.issuesTotal, 'warning')} in ${nomeArquivo}`);
162
+ log.line();
163
+ log.line(formatValidationIssuesDetailed(warnings.issues, { fileName: nomeArquivo, total: warnings.issuesTotal }));
164
+ log.line();
165
+ }
166
+
167
+ // The pages: everything that would fail the build (errors) or build
168
+ // differently than written (warnings), in one pass - see
169
+ // src/lib/content-check.js. Runs even when writedocs.json itself is
170
+ // invalid, so one run reports both; only the navigation/icon checks
171
+ // need writedocs.json to at least be valid JSON.
172
+ let content = null;
173
+ if (!options.configOnly) {
174
+ const { checkContent, formatContentIssues } = await import('../src/lib/content-check.js');
175
+ const checking = step('Checking pages');
176
+ content = await checkContent(contentDir, result.kind === 'invalid_json' ? null : rawText);
177
+ checking.stop();
178
+ if (content.errors.length > 0) {
179
+ log.error(`${plural(content.errors.length, 'error')} in the pages`);
180
+ log.line();
181
+ log.line(formatContentIssues(content.errors));
182
+ log.line();
183
+ }
184
+ if (content.warnings.length > 0) {
185
+ log.warn(`${plural(content.warnings.length, 'warning')} in the pages`);
186
+ log.line();
187
+ log.line(formatContentIssues(content.warnings));
188
+ log.line();
189
+ }
190
+ }
191
+
192
+ if (!result.ok || (content && content.errors.length > 0)) {
193
+ const nasPaginas = content ? content.errors.length : 0;
194
+ const total =
195
+ !result.ok && result.issuesTruncated
196
+ ? `more than ${VALIDATION_ISSUE_LIMIT + nasPaginas} errors`
197
+ : plural((result.ok ? 0 : result.issuesTotal) + nasPaginas, 'error');
198
+ log.error(`Not valid: ${total} to fix - the build would fail on these.`);
199
+ throw new CliExit(1);
200
+ }
201
+ // Aviso nao invalida: um config so com avisos continua valido, e sai 0 -
202
+ // o mesmo criterio que a plataforma usa pra marcar o projeto como `valid`.
203
+ log.success(`${nomeArquivo} is valid`);
204
+ if (content) {
205
+ log.success(
206
+ `Checked ${plural(content.pages, 'page')}: no errors` +
207
+ (content.warnings.length ? `, ${plural(content.warnings.length, 'warning')} above` : '')
208
+ );
209
+ }
210
+ });
211
+
212
+ program
213
+ // Like `validate`: no key, no build, no network - reads the project and
214
+ // exits 0 (no broken links) or 1, so it works as a CI step.
215
+ .command('broken-links')
216
+ .description('Check every internal link - pages, anchors and files - in the pages and writedocs.json')
217
+ .argument('[dir]', 'content directory (contains writedocs.json)', '.')
218
+ .action(async (dir) => {
219
+ const contentDir = canonicalPath(path.resolve(process.cwd(), dir));
220
+ const { preflightCheck } = await import('../src/cli/preflight.js');
221
+ preflightCheck(contentDir);
222
+ const configText = readConfigText(contentDir);
223
+ const checking = step('Checking links');
224
+ // Generated OpenAPI pages are link targets too - same step dev/build run.
225
+ const { generateApiPages } = await import('../src/cli/generate-api-pages.js');
226
+ await generateApiPages({ contentDir });
227
+ const { checkLinks } = await import('../src/lib/link-check.js');
228
+ const { formatContentIssues } = await import('../src/lib/content-check.js');
229
+ const result = await checkLinks(contentDir, configText);
230
+ checking.stop();
231
+
232
+ const summary = `${plural(result.links, 'link')} in ${plural(result.pages, 'page')}${
233
+ result.external ? color.dim(` (${plural(result.external, 'external link')} not checked)`) : ''
234
+ }`;
235
+ if (result.broken.length === 0) {
236
+ log.success(`No broken links - checked ${summary}`);
237
+ return;
238
+ }
239
+ log.error(plural(result.broken.length, 'broken link'));
240
+ log.line();
241
+ log.line(formatContentIssues(result.broken));
242
+ log.line();
243
+ log.error(`${plural(result.broken.length, 'broken link')} - checked ${summary}`);
244
+ throw new CliExit(1);
245
+ });
246
+
247
+ program
248
+ // Same shape as `broken-links`: reads the project, exits 0 (nothing
249
+ // found) or 1.
250
+ .command('a11y')
251
+ .description('Check accessibility - color contrast, image alt text, headings, link text')
252
+ .argument('[dir]', 'content directory (contains writedocs.json)', '.')
253
+ .action(async (dir) => {
254
+ const contentDir = canonicalPath(path.resolve(process.cwd(), dir));
255
+ const { preflightCheck } = await import('../src/cli/preflight.js');
256
+ preflightCheck(contentDir);
257
+ const configText = readConfigText(contentDir);
258
+ const checking = step('Checking accessibility');
259
+ const { checkAccessibility } = await import('../src/lib/a11y-check.js');
260
+ const { formatContentIssues } = await import('../src/lib/content-check.js');
261
+ const result = await checkAccessibility(contentDir, configText);
262
+ checking.stop();
263
+
264
+ if (result.issues.length === 0) {
265
+ log.success(`No accessibility issues - checked writedocs.json and ${plural(result.pages, 'page')}`);
266
+ return;
267
+ }
268
+ const count = plural(result.issues.length, 'accessibility issue');
269
+ log.error(count);
270
+ log.line();
271
+ log.line(formatContentIssues(result.issues));
272
+ log.line();
273
+ log.error(`${count} - checked writedocs.json and ${plural(result.pages, 'page')}`);
274
+ throw new CliExit(1);
275
+ });
276
+
277
+ program
278
+ .command('convert')
279
+ .description("Convert another docs tool's config into writedocs.json")
280
+ .argument('[dir]', 'project directory (contains docs.json or config.json)', '.')
281
+ .option('--mintlify', "convert a Mintlify project's docs.json")
282
+ .option('--docs.json', 'same as --mintlify')
283
+ .option('--writedocs', "convert a project from the previous writedocs (its config.json)")
284
+ .option('--config.json', 'same as --writedocs')
285
+ .option('--force', 'overwrite an existing writedocs.json')
286
+ .option('--dry-run', 'print the converted writedocs.json instead of writing it')
287
+ .action(async (dir, options) => {
288
+ // Commander camel-cases only on hyphens: `--docs.json` is stored under
289
+ // the key "docs.json", not `docsJson`.
290
+ const mintlify = options.mintlify || options['docs.json'];
291
+ const legacy = options.writedocs || options['config.json'];
292
+ if (mintlify === legacy) {
293
+ log.error(
294
+ mintlify
295
+ ? 'Pick one: --mintlify or --writedocs.'
296
+ : 'Say what to convert from: writedocs convert --mintlify [dir], or --writedocs for the previous writedocs.'
297
+ );
298
+ throw new CliExit(1);
299
+ }
300
+ const { runConvert } = await import('../src/cli/convert.js');
301
+ await runConvert({
302
+ source: legacy ? 'writedocs' : 'mintlify',
303
+ contentDir: canonicalPath(path.resolve(process.cwd(), dir)),
304
+ force: Boolean(options.force),
305
+ dryRun: Boolean(options.dryRun),
306
+ });
307
+ });
308
+
309
+ program
310
+ .command('update')
311
+ .description('Update writedocs to the latest version')
312
+ .action(async () => {
313
+ const { runUpdate } = await import('../src/cli/update.js');
314
+ await runUpdate({ name: packageName, version, packageRoot });
315
+ });
316
+
317
+ program
318
+ .command('init')
319
+ .description('Scaffold a writedocs.json and starter docs/ folder')
320
+ .argument('[dir]', 'directory to scaffold into', '.')
321
+ .action(async (dir) => {
322
+ await runInit({ targetDir: path.resolve(process.cwd(), dir) });
323
+ });
324
+
325
+ // `writedocs help [command]` - commander's own, except that a hidden command
326
+ // (`build`) gets the general help, like a name that isn't a command at all.
327
+ const HIDDEN_COMMANDS = new Set(['build']);
328
+ program
329
+ .command('help')
330
+ .description('display help for command')
331
+ .argument('[command]')
332
+ .action((name) => {
333
+ const command = name && !HIDDEN_COMMANDS.has(name) ? program.commands.find((c) => c.name() === name) : undefined;
334
+ (command ?? program).help();
335
+ });
336
+
337
+ // A command that succeeds ends on its own: Node keeps the process alive until
338
+ // what it wrote to a pipe has left. One that fails has to exit with its code,
339
+ // and process.exit() drops whatever a pipe hasn't taken yet - on Linux a pipe
340
+ // is asynchronous, and `writedocs validate` with 1,000 errors reached a CI log
341
+ // or the platform's build log with 1,198 of its 5,003 lines. exitWhenFlushed()
342
+ // waits for stdout and stderr first (10 s at most, for a reader that stopped
343
+ // reading). The exit codes are a contract with the platform: 0, 1, and 75
344
+ // from requireBuildKey() (src/cli/build-auth.js), which exits on its own after
345
+ // a few lines - they always fit in an empty pipe. Tested in
346
+ // scripts/cli-exit-flush.test.js.
347
+ program
348
+ .parseAsync(process.argv)
349
+ .then(showUpdateNotice)
350
+ .catch(async (err) => {
351
+ stopActiveStep();
352
+ // A command that already printed its own error throws CliExit.
353
+ if (!(err instanceof CliExit)) log.error(errorText(err));
354
+ showUpdateNotice();
355
+ await exitWhenFlushed(err instanceof CliExit ? err.code : 1);
356
+ });