@writedocs/generator 0.13.4 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/README.md +28 -28
  2. package/astro.config.mjs +645 -645
  3. package/bin/writedocs.js +359 -356
  4. package/package.json +99 -99
  5. package/src/cli/base-path-layout.js +44 -44
  6. package/src/cli/build-auth.js +135 -135
  7. package/src/cli/build.js +223 -203
  8. package/src/cli/check-built-styles.js +41 -41
  9. package/src/cli/convert.js +124 -124
  10. package/src/cli/dev.js +269 -268
  11. package/src/cli/exit-when-flushed.js +42 -42
  12. package/src/cli/generate-api-pages.js +509 -507
  13. package/src/cli/og-image-worker.js +20 -20
  14. package/src/cli/og-images.js +70 -70
  15. package/src/cli/page-list-watch.js +71 -69
  16. package/src/cli/run-astro.js +97 -97
  17. package/src/cli/run-pagefind.js +154 -154
  18. package/src/cli/write-mcp-files.js +103 -103
  19. package/src/cli/write-redirects-file.js +158 -158
  20. package/src/components/ApiReferencePanel.astro +1792 -1792
  21. package/src/components/AppIcon.astro +51 -51
  22. package/src/components/Card.astro +193 -193
  23. package/src/components/CodeGroup.astro +63 -39
  24. package/src/components/CopyPageMenu.astro +374 -374
  25. package/src/components/Hint.astro +188 -188
  26. package/src/components/Icon.astro +72 -72
  27. package/src/components/Image.astro +165 -165
  28. package/src/components/Tile.astro +67 -67
  29. package/src/components/Video.astro +137 -137
  30. package/src/content.config.ts +219 -203
  31. package/src/layout/BaseLayout.astro +908 -908
  32. package/src/layout/components/AnalyticsScripts.astro +49 -49
  33. package/src/layout/components/Breadcrumbs.astro +98 -98
  34. package/src/layout/components/ConsentBanner.astro +119 -119
  35. package/src/layout/components/MobileMenu.astro +225 -225
  36. package/src/layout/components/NavTree.astro +422 -408
  37. package/src/layout/components/Sidebar.astro +232 -232
  38. package/src/layout/components/SiteFooter.astro +87 -87
  39. package/src/layout/components/TopBar.astro +386 -386
  40. package/src/layout/styles/base.css +332 -326
  41. package/src/layout/styles/mobile-menu.css +285 -285
  42. package/src/lib/agent-markdown.js +164 -164
  43. package/src/lib/asset-dimensions.js +89 -89
  44. package/src/lib/base-path.js +90 -90
  45. package/src/lib/cli-report.js +22 -22
  46. package/src/lib/code-line-numbers.js +13 -0
  47. package/src/lib/config-schema.js +12 -1
  48. package/src/lib/config-schema.ts +2523 -2509
  49. package/src/lib/config.ts +1331 -1316
  50. package/src/lib/consent.js +108 -108
  51. package/src/lib/content-check.js +4 -1
  52. package/src/lib/content-store-reload-integration.js +101 -101
  53. package/src/lib/drafts.js +186 -0
  54. package/src/lib/icon-data-dev.js +53 -53
  55. package/src/lib/image-size.js +152 -152
  56. package/src/lib/json-schema-descriptions.js +228 -228
  57. package/src/lib/link-check.js +553 -544
  58. package/src/lib/llms-index.ts +90 -90
  59. package/src/lib/mcp-dev-integration.js +65 -65
  60. package/src/lib/mcp-index.ts +102 -102
  61. package/src/lib/mintlify-convert.js +605 -605
  62. package/src/lib/moved-api-pages.js +49 -49
  63. package/src/lib/og-cards.js +33 -33
  64. package/src/lib/og-image.js +235 -235
  65. package/src/lib/openapi-dev-status.js +80 -80
  66. package/src/lib/openapi-reload-integration.js +193 -193
  67. package/src/lib/pages.js +346 -312
  68. package/src/lib/project-files-integration.js +116 -116
  69. package/src/lib/project-files.js +137 -137
  70. package/src/lib/rehype-base-path.js +62 -62
  71. package/src/lib/rehype-image-loading.js +71 -71
  72. package/src/lib/robots-txt.js +21 -21
  73. package/src/lib/search-scope.js +44 -44
  74. package/src/lib/selector-placement.js +50 -50
  75. package/src/lib/seo-tags.js +157 -155
  76. package/src/lib/shiki-code-block.js +7 -1
  77. package/src/lib/site-base.ts +27 -27
  78. package/src/lib/styles-asset-integration.js +291 -291
  79. package/src/lib/wdignore-cases.json +195 -195
  80. package/src/lib/wdignore.js +177 -177
  81. package/src/pages/404.astro +63 -63
  82. package/src/pages/[...slug].astro +1773 -1608
  83. package/src/pages/[...slug].md.ts +93 -93
  84. package/src/pages/llms-full.txt.ts +88 -88
  85. package/src/pages/og/[...slug].png.ts +63 -63
  86. package/src/scripts/mobile-menu.ts +80 -80
  87. package/src/scripts/search.ts +245 -245
  88. package/src/scripts/sidebar-scroll.ts +61 -61
  89. package/src/styles/global.css +40 -40
package/bin/writedocs.js CHANGED
@@ -1,356 +1,359 @@
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
- });
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
+ // A preview of the drafts (src/lib/drafts.js): included, marked and
94
+ // noindex, out of the sitemap, llms.txt and the MCP index.
95
+ .option('--drafts', 'include draft pages (draft: true), marked and noindex')
96
+ .action(async (dir, opts) => {
97
+ const contentDir = canonicalPath(path.resolve(process.cwd(), dir));
98
+ // Project-scoped, not global: a .env sitting next to this project's own
99
+ // writedocs.json (WRITEDOCS_API_KEY) is picked up automatically, so
100
+ // build doesn't need it exported by hand every
101
+ // session. dotenv never overwrites a var already set in the real
102
+ // environment - an explicit `export`/CI secret still wins over the file.
103
+ dotenv.config({ path: path.join(contentDir, '.env'), quiet: true });
104
+ await requireBuildKey(opts.key || process.env.WRITEDOCS_API_KEY);
105
+ await runBuild({ contentDir, packageRoot, verbose: Boolean(opts.verbose), drafts: Boolean(opts.drafts) });
106
+ });
107
+
108
+ program
109
+ // Visivel, ao contrario do `build`: validar a propria configuracao e
110
+ // exatamente o tipo de coisa que um usuario deve poder rodar sozinho, no CI
111
+ // inclusive. Sem chave, sem dotenv, sem rede - le um arquivo e sai 0 ou 1.
112
+ .command('validate')
113
+ .description('Validate writedocs.json and every page - frontmatter, MDX, navigation, components, icons')
114
+ .argument('[dir]', 'content directory (contains writedocs.json)', '.')
115
+ .option('--config-only', 'check writedocs.json only, not the pages')
116
+ .option('--all', `list every problem in writedocs.json, not only the first ${VALIDATION_ISSUE_LIMIT}`)
117
+ .action(async (dir, options) => {
118
+ const contentDir = canonicalPath(path.resolve(process.cwd(), dir));
119
+ const configPath = path.join(contentDir, 'writedocs.json');
120
+ if (!fs.existsSync(configPath)) {
121
+ // Mesma mensagem que loadDocsConfig() ja da pro mesmo caso.
122
+ log.error(`No writedocs.json found in ${contentDir}`);
123
+ log.detail(color.dim('Run "writedocs init" to create one.'));
124
+ throw new CliExit(1);
125
+ }
126
+
127
+ const rawText = readConfigText(contentDir);
128
+ // Sem `--all`, a validacao para depois de VALIDATION_ISSUE_LIMIT erros
129
+ // (WD-315): a lista traz os primeiros, e `issuesTruncated` diz que ha mais,
130
+ // sem saber quantos. `--all` valida tudo e lista tudo, como antes.
131
+ const all = Boolean(options.all);
132
+ const result = validateDocsConfig(rawText, { all });
133
+ // Chave desconhecida na raiz e AVISO, nunca erro: a raiz nao e `.strict()`
134
+ // de proposito (tornar strict quebraria configs existentes), entao o Zod
135
+ // descarta a chave em silencio. Sem JSON parseavel nao ha chave pra avaliar.
136
+ // Os avisos chegam com no maximo VALIDATION_ISSUE_LIMIT (todos, com `--all`),
137
+ // e o total deles e sempre exato.
138
+ const warnings = result.kind === 'invalid_json' ? { issues: [], issuesTotal: 0 } : unknownRootKeyWarnings(rawText, { all });
139
+ const nomeArquivo = path.basename(configPath);
140
+
141
+ if (!result.ok) {
142
+ // A versao longa (linha, frase humana, sugestao) em vez da curta que o
143
+ // `writedocs build` imprime: aqui o usuario pediu explicitamente um
144
+ // diagnostico, e tem a tela inteira pra ele.
145
+ log.error(
146
+ result.kind === 'invalid_json'
147
+ ? `${nomeArquivo} is not valid JSON`
148
+ : result.issuesTruncated
149
+ ? `More than ${VALIDATION_ISSUE_LIMIT} errors in ${nomeArquivo}`
150
+ : `${plural(result.issuesTotal, 'error')} in ${nomeArquivo}`
151
+ );
152
+ log.line();
153
+ log.line(
154
+ formatValidationIssuesDetailed(result.issues, {
155
+ fileName: nomeArquivo,
156
+ total: result.issuesTotal,
157
+ truncated: result.issuesTruncated,
158
+ })
159
+ );
160
+ log.line();
161
+ }
162
+
163
+ if (warnings.issuesTotal > 0) {
164
+ log.warn(`${plural(warnings.issuesTotal, 'warning')} in ${nomeArquivo}`);
165
+ log.line();
166
+ log.line(formatValidationIssuesDetailed(warnings.issues, { fileName: nomeArquivo, total: warnings.issuesTotal }));
167
+ log.line();
168
+ }
169
+
170
+ // The pages: everything that would fail the build (errors) or build
171
+ // differently than written (warnings), in one pass - see
172
+ // src/lib/content-check.js. Runs even when writedocs.json itself is
173
+ // invalid, so one run reports both; only the navigation/icon checks
174
+ // need writedocs.json to at least be valid JSON.
175
+ let content = null;
176
+ if (!options.configOnly) {
177
+ const { checkContent, formatContentIssues } = await import('../src/lib/content-check.js');
178
+ const checking = step('Checking pages');
179
+ content = await checkContent(contentDir, result.kind === 'invalid_json' ? null : rawText);
180
+ checking.stop();
181
+ if (content.errors.length > 0) {
182
+ log.error(`${plural(content.errors.length, 'error')} in the pages`);
183
+ log.line();
184
+ log.line(formatContentIssues(content.errors));
185
+ log.line();
186
+ }
187
+ if (content.warnings.length > 0) {
188
+ log.warn(`${plural(content.warnings.length, 'warning')} in the pages`);
189
+ log.line();
190
+ log.line(formatContentIssues(content.warnings));
191
+ log.line();
192
+ }
193
+ }
194
+
195
+ if (!result.ok || (content && content.errors.length > 0)) {
196
+ const nasPaginas = content ? content.errors.length : 0;
197
+ const total =
198
+ !result.ok && result.issuesTruncated
199
+ ? `more than ${VALIDATION_ISSUE_LIMIT + nasPaginas} errors`
200
+ : plural((result.ok ? 0 : result.issuesTotal) + nasPaginas, 'error');
201
+ log.error(`Not valid: ${total} to fix - the build would fail on these.`);
202
+ throw new CliExit(1);
203
+ }
204
+ // Aviso nao invalida: um config so com avisos continua valido, e sai 0 -
205
+ // o mesmo criterio que a plataforma usa pra marcar o projeto como `valid`.
206
+ log.success(`${nomeArquivo} is valid`);
207
+ if (content) {
208
+ log.success(
209
+ `Checked ${plural(content.pages, 'page')}: no errors` +
210
+ (content.warnings.length ? `, ${plural(content.warnings.length, 'warning')} above` : '')
211
+ );
212
+ }
213
+ });
214
+
215
+ program
216
+ // Like `validate`: no key, no build, no network - reads the project and
217
+ // exits 0 (no broken links) or 1, so it works as a CI step.
218
+ .command('broken-links')
219
+ .description('Check every internal link - pages, anchors and files - in the pages and writedocs.json')
220
+ .argument('[dir]', 'content directory (contains writedocs.json)', '.')
221
+ .action(async (dir) => {
222
+ const contentDir = canonicalPath(path.resolve(process.cwd(), dir));
223
+ const { preflightCheck } = await import('../src/cli/preflight.js');
224
+ preflightCheck(contentDir);
225
+ const configText = readConfigText(contentDir);
226
+ const checking = step('Checking links');
227
+ // Generated OpenAPI pages are link targets too - same step dev/build run.
228
+ const { generateApiPages } = await import('../src/cli/generate-api-pages.js');
229
+ await generateApiPages({ contentDir });
230
+ const { checkLinks } = await import('../src/lib/link-check.js');
231
+ const { formatContentIssues } = await import('../src/lib/content-check.js');
232
+ const result = await checkLinks(contentDir, configText);
233
+ checking.stop();
234
+
235
+ const summary = `${plural(result.links, 'link')} in ${plural(result.pages, 'page')}${
236
+ result.external ? color.dim(` (${plural(result.external, 'external link')} not checked)`) : ''
237
+ }`;
238
+ if (result.broken.length === 0) {
239
+ log.success(`No broken links - checked ${summary}`);
240
+ return;
241
+ }
242
+ log.error(plural(result.broken.length, 'broken link'));
243
+ log.line();
244
+ log.line(formatContentIssues(result.broken));
245
+ log.line();
246
+ log.error(`${plural(result.broken.length, 'broken link')} - checked ${summary}`);
247
+ throw new CliExit(1);
248
+ });
249
+
250
+ program
251
+ // Same shape as `broken-links`: reads the project, exits 0 (nothing
252
+ // found) or 1.
253
+ .command('a11y')
254
+ .description('Check accessibility - color contrast, image alt text, headings, link text')
255
+ .argument('[dir]', 'content directory (contains writedocs.json)', '.')
256
+ .action(async (dir) => {
257
+ const contentDir = canonicalPath(path.resolve(process.cwd(), dir));
258
+ const { preflightCheck } = await import('../src/cli/preflight.js');
259
+ preflightCheck(contentDir);
260
+ const configText = readConfigText(contentDir);
261
+ const checking = step('Checking accessibility');
262
+ const { checkAccessibility } = await import('../src/lib/a11y-check.js');
263
+ const { formatContentIssues } = await import('../src/lib/content-check.js');
264
+ const result = await checkAccessibility(contentDir, configText);
265
+ checking.stop();
266
+
267
+ if (result.issues.length === 0) {
268
+ log.success(`No accessibility issues - checked writedocs.json and ${plural(result.pages, 'page')}`);
269
+ return;
270
+ }
271
+ const count = plural(result.issues.length, 'accessibility issue');
272
+ log.error(count);
273
+ log.line();
274
+ log.line(formatContentIssues(result.issues));
275
+ log.line();
276
+ log.error(`${count} - checked writedocs.json and ${plural(result.pages, 'page')}`);
277
+ throw new CliExit(1);
278
+ });
279
+
280
+ program
281
+ .command('convert')
282
+ .description("Convert another docs tool's config into writedocs.json")
283
+ .argument('[dir]', 'project directory (contains docs.json or config.json)', '.')
284
+ .option('--mintlify', "convert a Mintlify project's docs.json")
285
+ .option('--docs.json', 'same as --mintlify')
286
+ .option('--writedocs', "convert a project from the previous writedocs (its config.json)")
287
+ .option('--config.json', 'same as --writedocs')
288
+ .option('--force', 'overwrite an existing writedocs.json')
289
+ .option('--dry-run', 'print the converted writedocs.json instead of writing it')
290
+ .action(async (dir, options) => {
291
+ // Commander camel-cases only on hyphens: `--docs.json` is stored under
292
+ // the key "docs.json", not `docsJson`.
293
+ const mintlify = options.mintlify || options['docs.json'];
294
+ const legacy = options.writedocs || options['config.json'];
295
+ if (mintlify === legacy) {
296
+ log.error(
297
+ mintlify
298
+ ? 'Pick one: --mintlify or --writedocs.'
299
+ : 'Say what to convert from: writedocs convert --mintlify [dir], or --writedocs for the previous writedocs.'
300
+ );
301
+ throw new CliExit(1);
302
+ }
303
+ const { runConvert } = await import('../src/cli/convert.js');
304
+ await runConvert({
305
+ source: legacy ? 'writedocs' : 'mintlify',
306
+ contentDir: canonicalPath(path.resolve(process.cwd(), dir)),
307
+ force: Boolean(options.force),
308
+ dryRun: Boolean(options.dryRun),
309
+ });
310
+ });
311
+
312
+ program
313
+ .command('update')
314
+ .description('Update writedocs to the latest version')
315
+ .action(async () => {
316
+ const { runUpdate } = await import('../src/cli/update.js');
317
+ await runUpdate({ name: packageName, version, packageRoot });
318
+ });
319
+
320
+ program
321
+ .command('init')
322
+ .description('Scaffold a writedocs.json and starter docs/ folder')
323
+ .argument('[dir]', 'directory to scaffold into', '.')
324
+ .action(async (dir) => {
325
+ await runInit({ targetDir: path.resolve(process.cwd(), dir) });
326
+ });
327
+
328
+ // `writedocs help [command]` - commander's own, except that a hidden command
329
+ // (`build`) gets the general help, like a name that isn't a command at all.
330
+ const HIDDEN_COMMANDS = new Set(['build']);
331
+ program
332
+ .command('help')
333
+ .description('display help for command')
334
+ .argument('[command]')
335
+ .action((name) => {
336
+ const command = name && !HIDDEN_COMMANDS.has(name) ? program.commands.find((c) => c.name() === name) : undefined;
337
+ (command ?? program).help();
338
+ });
339
+
340
+ // A command that succeeds ends on its own: Node keeps the process alive until
341
+ // what it wrote to a pipe has left. One that fails has to exit with its code,
342
+ // and process.exit() drops whatever a pipe hasn't taken yet - on Linux a pipe
343
+ // is asynchronous, and `writedocs validate` with 1,000 errors reached a CI log
344
+ // or the platform's build log with 1,198 of its 5,003 lines. exitWhenFlushed()
345
+ // waits for stdout and stderr first (10 s at most, for a reader that stopped
346
+ // reading). The exit codes are a contract with the platform: 0, 1, and 75
347
+ // from requireBuildKey() (src/cli/build-auth.js), which exits on its own after
348
+ // a few lines - they always fit in an empty pipe. Tested in
349
+ // scripts/cli-exit-flush.test.js.
350
+ program
351
+ .parseAsync(process.argv)
352
+ .then(showUpdateNotice)
353
+ .catch(async (err) => {
354
+ stopActiveStep();
355
+ // A command that already printed its own error throws CliExit.
356
+ if (!(err instanceof CliExit)) log.error(errorText(err));
357
+ showUpdateNotice();
358
+ await exitWhenFlushed(err instanceof CliExit ? err.code : 1);
359
+ });