@writedocs/generator 0.11.1 → 0.13.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.
@@ -9,7 +9,8 @@ import { projectIgnore } from '../lib/project-ignore.js';
9
9
  import { readConfigText } from '../lib/config-file.js';
10
10
  import { HTTP_METHODS, collectOpenApiGroups } from '../lib/openapi-spec.js';
11
11
  import { operationMetaDescription } from '../lib/meta-description.js';
12
- import { writeMovedApiPages, untaggedRedirects } from '../lib/moved-api-pages.js';
12
+ import { movedApiPagesFile, untaggedRedirects } from '../lib/moved-api-pages.js';
13
+ import { canonicalPath } from '../lib/canonical-path.js';
13
14
 
14
15
 
15
16
  /** Canonical "METHOD /path" key used everywhere an operation needs to be
@@ -204,19 +205,26 @@ function operationJson(operation) {
204
205
  return JSON.stringify(cut(operation), null, 2);
205
206
  }
206
207
 
207
- function rmrf(dir) {
208
- fs.rmSync(dir, { recursive: true, force: true });
208
+ /** Parses and dereferences the spec at `specPath`, adding every local file it
209
+ * read - the spec and each file a `$ref` pointed into - to `sources`, which
210
+ * `writedocs dev` watches (lib/openapi-reload-integration.js). */
211
+ async function dereferenceSpec(specPath, sources) {
212
+ sources.add(canonicalPath(specPath));
213
+ const parser = new SwaggerParser();
214
+ const spec = await parser.dereference(specPath);
215
+ for (const file of parser.$refs.paths('file')) sources.add(canonicalPath(path.resolve(file)));
216
+ return spec;
209
217
  }
210
218
 
211
- /** Generates every page for one `{ group, openapi: { src, path } }`
212
- * navigation node: dereferences its spec, writes a stub page per
213
- * operation (unless a hand-written override already claims it), and
214
- * writes this spec's own manifest + resolved operation JSON under
219
+ /** Works out every page for one `{ group, openapi: { src, path } }`
220
+ * navigation node: dereferences its spec, and adds to `files` a stub page
221
+ * per operation (unless a hand-written override already claims it) and
222
+ * this spec's own manifest + resolved operation JSON under
215
223
  * writedocsTempDir()'s openapi/<path>/ directory - namespaced by `path` so multiple specs
216
224
  * in the same writedocs.json never collide with each other on disk, exactly
217
225
  * as they won't collide in the URL space either (both keyed off the
218
- * same `path` value). */
219
- async function generateApiPagesForGroup({ contentDir, generatedDocsDir, group, overrides, summary, moves }) {
226
+ * same `path` value). Nothing is written here - see writeGeneratedFiles(). */
227
+ async function generateApiPagesForGroup({ contentDir, generatedDocsDir, group, overrides, summary, moves, files, sources }) {
220
228
  const pathPrefix = normalizePathPrefix(group.openapi.path);
221
229
  const specPath = path.resolve(contentDir, group.openapi.src);
222
230
  if (!fs.existsSync(specPath)) {
@@ -226,11 +234,10 @@ async function generateApiPagesForGroup({ contentDir, generatedDocsDir, group, o
226
234
  );
227
235
  }
228
236
 
229
- const spec = await SwaggerParser.dereference(specPath);
237
+ const spec = await dereferenceSpec(specPath, sources);
230
238
  const operations = buildOperations(spec);
231
239
 
232
240
  const openapiOutDir = path.join(writedocsTempDir(contentDir), 'openapi', pathPrefix);
233
- fs.mkdirSync(path.join(openapiOutDir, 'operations'), { recursive: true });
234
241
 
235
242
  const manifest = [];
236
243
  const untagged = [];
@@ -252,7 +259,6 @@ async function generateApiPagesForGroup({ contentDir, generatedDocsDir, group, o
252
259
  // exactly this value regardless of whatever id Astro's own
253
260
  // default (path-derived) computation would otherwise have picked.
254
261
  const filePath = path.join(generatedDocsDir, `${slug}.mdx`);
255
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
256
262
  const frontmatter = [
257
263
  '---',
258
264
  `title: ${JSON.stringify(title)}`,
@@ -270,7 +276,7 @@ async function generateApiPagesForGroup({ contentDir, generatedDocsDir, group, o
270
276
  ]
271
277
  .filter((line) => line !== null)
272
278
  .join('\n');
273
- fs.writeFileSync(filePath, frontmatter);
279
+ files.set(filePath, frontmatter);
274
280
  if (!operation.tags.length) untagged.push({ oldSlug: legacyUntaggedSlugFor(pathPrefix, operation.method, operation.path), newSlug: slug });
275
281
  }
276
282
  moves.slugs.add(slug);
@@ -278,10 +284,10 @@ async function generateApiPagesForGroup({ contentDir, generatedDocsDir, group, o
278
284
  manifest.push({ slug, method: operation.method, path: operation.path, tags: operation.tags, title, generated });
279
285
 
280
286
  const opFile = path.join(openapiOutDir, 'operations', operationFileName(operation.method, operation.path));
281
- fs.writeFileSync(opFile, operationJson(operation));
287
+ files.set(opFile, operationJson(operation));
282
288
  }
283
289
 
284
- fs.writeFileSync(path.join(openapiOutDir, 'manifest.json'), JSON.stringify(manifest, null, 2));
290
+ files.set(path.join(openapiOutDir, 'manifest.json'), JSON.stringify(manifest, null, 2));
285
291
  if (untagged.length) moves.untagged.push({ pathPrefix, moved: untagged });
286
292
  summary.groups.push({ group: group.group, src: group.openapi.src, operations: operations.length });
287
293
  }
@@ -316,29 +322,48 @@ async function generateApiPagesForGroup({ contentDir, generatedDocsDir, group, o
316
322
  * writedocs.json's navigation has no openapi groups at all - most sites don't
317
323
  * have one.
318
324
  *
325
+ * Every spec is parsed, and every file worked out, before anything is
326
+ * written: a spec that doesn't parse throws with the previous output still
327
+ * in place - `writedocs dev` keeps serving the last version that worked
328
+ * while the spec is mid-edit (lib/openapi-reload-integration.js). Then the
329
+ * two folders are brought to exactly that output, writing only the files
330
+ * that changed (writeGeneratedFiles()) - so a dev regeneration after a
331
+ * one-line edit to the spec touches one page, not all of them. The result
332
+ * on disk is the same as clearing both folders and writing everything.
333
+ * `keepEmptyFolders` keeps a folder left with no files (the dev preview,
334
+ * whose watchers are on it); otherwise it goes, as it always did -
335
+ * content.config.ts skips a generated-docs/ that doesn't exist.
336
+ *
319
337
  * Prints nothing: returns what it did, for the CLI to report -
320
338
  * { groups: [{ group, src, operations }], pageSpecs: [{ spec, operations }],
321
- * warnings: [message] }.
339
+ * warnings: [message], sources: [every local spec file read, $refs
340
+ * included], written: [paths], removed: [paths] }.
322
341
  */
323
- export async function generateApiPages({ contentDir }) {
324
- const summary = { groups: [], pageSpecs: [], warnings: [] };
342
+ export async function generateApiPages({ contentDir, keepEmptyFolders = false }) {
343
+ const { summary, files, roots } = await planApiPages({ contentDir });
344
+ const { written, removed } = writeGeneratedFiles(roots, files, { keepEmptyFolders });
345
+ return { ...summary, written, removed };
346
+ }
347
+
348
+ /** Everything generateApiPages() would write, without writing it:
349
+ * `{ summary, files, roots }` - `files` maps each absolute path to its
350
+ * content, `roots` are the two folders it owns (generated-docs/ first).
351
+ * `writedocs dev` writes it in two steps (lib/openapi-reload-integration.js). */
352
+ export async function planApiPages({ contentDir }) {
353
+ const summary = { groups: [], pageSpecs: [], warnings: [], sources: [] };
325
354
  const generatedDocsDir = path.join(writedocsTempDir(contentDir), 'generated-docs');
326
355
  const openapiOutDir = path.join(writedocsTempDir(contentDir), 'openapi');
356
+ const roots = [generatedDocsDir, openapiOutDir];
327
357
 
328
358
  let config;
329
359
  try {
330
360
  config = JSON.parse(readConfigText(contentDir));
331
361
  } catch {
332
- return summary; // preflightCheck() (run first, see dev.js/build.js) already reports this
362
+ // preflightCheck() (run first, see dev.js/build.js) already reports this.
363
+ // Nothing to write - and nothing to delete either.
364
+ return { summary, files: null, roots };
333
365
  }
334
366
 
335
- // Always start from a clean slate: a group's `path` (or the group
336
- // itself) may have changed or been removed since the last run, and
337
- // there's no cheap way to tell stale generated output apart from
338
- // still-current output without just regenerating everything.
339
- rmrf(generatedDocsDir);
340
- rmrf(openapiOutDir);
341
-
342
367
  const groups = collectOpenApiGroups(config.navigation);
343
368
 
344
369
  const seenPaths = new Map(); // normalized path -> owning group's label
@@ -359,22 +384,83 @@ export async function generateApiPages({ contentDir }) {
359
384
  // overriding page is served at - for the redirects from where untagged
360
385
  // operations used to be (lib/moved-api-pages.js).
361
386
  const moves = { untagged: [], slugs: new Set() };
387
+ // Absolute path -> content: everything the two folders will hold.
388
+ const files = new Map();
389
+ const sources = new Set();
362
390
  for (const group of groups) {
363
- await generateApiPagesForGroup({ contentDir, generatedDocsDir, group, overrides, summary, moves });
391
+ await generateApiPagesForGroup({ contentDir, generatedDocsDir, group, overrides, summary, moves, files, sources });
364
392
  }
365
393
  const moved = moves.untagged.flatMap(({ pathPrefix, moved: list }) => untaggedRedirects(pathPrefix, list, moves.slugs));
366
- if (moved.length) writeMovedApiPages(contentDir, moved);
394
+ if (moved.length) files.set(movedApiPagesFile(contentDir), JSON.stringify(moved, null, 2));
367
395
 
368
396
  const groupSpecs = groups.map((g) => path.resolve(contentDir, g.openapi.src));
369
- const pageSpecs = await parsePageSpecs({ contentDir, openapiOutDir, groupSpecs, summary });
397
+ const pageSpecs = await parsePageSpecs({ contentDir, openapiOutDir, groupSpecs, summary, files, sources });
370
398
  // Every spec the site reads, as paths from the project root: these are
371
399
  // how the site is built, not files it publishes (lib/project-files.js).
372
400
  if (groupSpecs.length || pageSpecs.length) {
373
401
  const specs = [...new Set([...groupSpecs, ...pageSpecs].map((abs) => path.relative(contentDir, abs).split(path.sep).join('/')))];
374
- fs.mkdirSync(openapiOutDir, { recursive: true });
375
- fs.writeFileSync(path.join(openapiOutDir, 'specs.json'), JSON.stringify(specs, null, 2));
402
+ files.set(path.join(openapiOutDir, 'specs.json'), JSON.stringify(specs, null, 2));
403
+ }
404
+
405
+ summary.sources = [...sources];
406
+ return { summary, files, roots };
407
+ }
408
+
409
+ function listFiles(dir) {
410
+ let entries;
411
+ try {
412
+ entries = fs.readdirSync(dir, { withFileTypes: true });
413
+ } catch {
414
+ return [];
415
+ }
416
+ return entries.flatMap((entry) => {
417
+ const full = path.join(dir, entry.name);
418
+ return entry.isDirectory() ? listFiles(full) : [full];
419
+ });
420
+ }
421
+
422
+ /** Removes the empty folders under `dir`, and `dir` itself when it ends up
423
+ * empty and `keepRoot` is false. */
424
+ function removeEmptyFolders(dir, keepRoot) {
425
+ let entries;
426
+ try {
427
+ entries = fs.readdirSync(dir, { withFileTypes: true });
428
+ } catch {
429
+ return;
430
+ }
431
+ for (const entry of entries) if (entry.isDirectory()) removeEmptyFolders(path.join(dir, entry.name), false);
432
+ if (!keepRoot && fs.readdirSync(dir).length === 0) fs.rmdirSync(dir);
433
+ }
434
+
435
+ /** Brings the folders in `roots` to exactly `files` (absolute path ->
436
+ * content): every other file under them is deleted, a file whose content is
437
+ * already the same is left alone, and the rest are written. Folders left
438
+ * empty are removed - each root too, unless `keepEmptyFolders`. Returns the
439
+ * paths written and removed. `files` null (writedocs.json unreadable) leaves
440
+ * everything as it is. */
441
+ export function writeGeneratedFiles(roots, files, { keepEmptyFolders = false } = {}) {
442
+ if (!files) return { written: [], removed: [] };
443
+ const written = [];
444
+ const removed = [];
445
+ for (const root of roots) {
446
+ for (const file of listFiles(root)) {
447
+ if (files.has(file)) continue;
448
+ fs.rmSync(file, { force: true });
449
+ removed.push(file);
450
+ }
451
+ }
452
+ for (const [file, content] of files) {
453
+ let current = null;
454
+ try {
455
+ current = fs.readFileSync(file, 'utf-8');
456
+ } catch {}
457
+ if (current === content) continue;
458
+ fs.mkdirSync(path.dirname(file), { recursive: true });
459
+ fs.writeFileSync(file, content);
460
+ written.push(file);
376
461
  }
377
- return summary;
462
+ for (const root of roots) removeEmptyFolders(root, keepEmptyFolders);
463
+ return { written, removed };
378
464
  }
379
465
 
380
466
  /** Mintlify's page-level form, `openapi: "/spec.json METHOD /path"`: the
@@ -385,7 +471,7 @@ export async function generateApiPages({ contentDir }) {
385
471
  * pages are generated - the pages that name the spec are the pages. A
386
472
  * spec that's missing or doesn't parse is a warning, not a build failure:
387
473
  * its pages show the playground's own "no operation found" notice. */
388
- async function parsePageSpecs({ contentDir, openapiOutDir, groupSpecs, summary }) {
474
+ async function parsePageSpecs({ contentDir, openapiOutDir, groupSpecs, summary, files, sources }) {
389
475
  const specs = new Set();
390
476
  for (const rel of findAllPages(contentDir)) {
391
477
  let data;
@@ -406,15 +492,14 @@ async function parsePageSpecs({ contentDir, openapiOutDir, groupSpecs, summary }
406
492
  }
407
493
  let operations;
408
494
  try {
409
- operations = buildOperations(await SwaggerParser.dereference(specPath));
495
+ operations = buildOperations(await dereferenceSpec(specPath, sources));
410
496
  } catch (err) {
411
497
  summary.warnings.push(`Couldn't parse the OpenAPI spec "${spec}" that pages name: ${err.message}`);
412
498
  continue;
413
499
  }
414
500
  const outDir = path.join(openapiOutDir, '_pages', specDirName(spec), 'operations');
415
- fs.mkdirSync(outDir, { recursive: true });
416
501
  for (const operation of operations) {
417
- fs.writeFileSync(path.join(outDir, operationFileName(operation.method, operation.path)), operationJson(operation));
502
+ files.set(path.join(outDir, operationFileName(operation.method, operation.path)), operationJson(operation));
418
503
  }
419
504
  summary.pageSpecs.push({ spec, operations: operations.length });
420
505
  }
@@ -0,0 +1,20 @@
1
+ // One of og-images.js's threads: asks for a card, draws it into the site's
2
+ // og/ folder, asks for the next - until it's sent null.
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import { parentPort, workerData } from 'node:worker_threads';
6
+ import { ogImagePng, ogImagePath } from '../lib/og-image.js';
7
+ import { ogCardOptions } from '../lib/og-cards.js';
8
+
9
+ const { shared, siteDir } = workerData;
10
+ parentPort.on('message', async (card) => {
11
+ if (card === null) {
12
+ parentPort.close();
13
+ return;
14
+ }
15
+ const file = path.join(siteDir, ...ogImagePath(card.slug).split('/').filter(Boolean));
16
+ fs.mkdirSync(path.dirname(file), { recursive: true });
17
+ fs.writeFileSync(file, await ogImagePng(ogCardOptions(shared, card)));
18
+ parentPort.postMessage('drawn');
19
+ });
20
+ parentPort.postMessage('ready');
@@ -0,0 +1,70 @@
1
+ // `writedocs build`'s link-preview cards (lib/og-cards.js), drawn after
2
+ // Astro, in worker threads - one per CPU this process may use
3
+ // (os.availableParallelism(), which follows a container's CPU limit), and
4
+ // at most MAX_THREADS (ogThreads()).
5
+ //
6
+ // Inside Astro they were one route among the others (src/pages/og/
7
+ // [...slug].png.ts), and Astro renders its routes one at a time on one core:
8
+ // on a site with 800 OpenAPI operations, the 800 cards were a third of the
9
+ // build. The route still decides nothing here - it writes the list of cards
10
+ // to the file it's given (WRITEDOCS_OG_CARDS_FILE, set by build.js) and
11
+ // renders none; each thread draws a card with the same ogImagePng() call the
12
+ // route makes in `writedocs dev`, so the files are the same, byte for byte.
13
+ //
14
+ // Each thread holds its own resvg, satori and fonts, ~110 MB: the threads
15
+ // start after Astro has exited, so that isn't on top of its peak.
16
+ import fs from 'node:fs';
17
+ import os from 'node:os';
18
+ import { Worker } from 'node:worker_threads';
19
+
20
+ /** No more threads than this, however many CPUs a machine shows: a CI host
21
+ * can show dozens without a quota, and dozens of threads would be gigabytes.
22
+ * The platform's container has 4 CPUs; 800 cards take ~3.5 s there. */
23
+ export const MAX_THREADS = 4;
24
+
25
+ /** How many threads draw the cards, for `available` CPUs. */
26
+ export function ogThreads(available = os.availableParallelism()) {
27
+ return Math.max(1, Math.min(available, MAX_THREADS));
28
+ }
29
+
30
+ /** Draws every card in `listFile` into `siteDir`/og/ - the site's root
31
+ * folder: build.js passes the staging folder, before it replaces dist/.
32
+ * Returns how many.
33
+ * The list is removed afterwards, drawn or not: it's only this build's, and
34
+ * it holds the logo, base64-encoded - no reason to leave it in the temp
35
+ * folder. */
36
+ export async function drawOgImages(listFile, siteDir, { threads = ogThreads() } = {}) {
37
+ try {
38
+ return await drawEach(listFile, siteDir, threads);
39
+ } finally {
40
+ fs.rmSync(listFile, { force: true });
41
+ }
42
+ }
43
+
44
+ async function drawEach(listFile, siteDir, threads) {
45
+ // No file: the route never ran - a site with no pages to give a card.
46
+ if (!fs.existsSync(listFile)) return 0;
47
+ const { cards, ...shared } = JSON.parse(fs.readFileSync(listFile, 'utf8'));
48
+ if (!cards.length) return 0;
49
+ let next = 0;
50
+ const workers = [];
51
+ try {
52
+ await Promise.all(
53
+ Array.from({ length: Math.min(threads, cards.length) }, () => {
54
+ const worker = new Worker(new URL('./og-image-worker.js', import.meta.url), { workerData: { shared, siteDir } });
55
+ workers.push(worker);
56
+ return new Promise((resolve, reject) => {
57
+ // A card at a time, to whichever thread is free: a long title or a
58
+ // logo makes one slower than another.
59
+ worker.on('message', () => worker.postMessage(next < cards.length ? cards[next++] : null));
60
+ worker.on('error', reject);
61
+ worker.on('exit', (code) => (code === 0 ? resolve() : reject(new Error(`A thread drawing the link previews stopped (exit code ${code}).`))));
62
+ });
63
+ })
64
+ );
65
+ } finally {
66
+ // One thread failing stops the others.
67
+ await Promise.all(workers.map((worker) => worker.terminate()));
68
+ }
69
+ return cards.length;
70
+ }
@@ -1,93 +1,97 @@
1
- import path from 'node:path';
2
- import { spawn } from 'node:child_process';
3
- import { canonicalPath } from '../lib/canonical-path.js';
4
- import { fileURLToPath } from 'node:url';
5
-
6
- const workerPath = path.join(path.dirname(fileURLToPath(import.meta.url)), 'astro-worker.js');
7
-
8
- /**
9
- * Runs Astro (`command`: 'dev' or 'build') in a child process -
10
- * astro-worker.js - and turns everything it reports into events for
11
- * `onEvent`, so the CLI decides what reaches the terminal:
12
- *
13
- * { type: 'astro-log', level, label, message } - an Astro/Vite log line
14
- * { type: 'report', level, message, where } - writedocs' own code
15
- * (lib/cli-report.js)
16
- * { type: 'raw', stream, line } - anything printed directly
17
- * { type: 'ready', urls } / { type: 'done' } / { type: 'fatal', error }
18
- *
19
- * A raw "[writedocs] ..." line is turned into a 'report' too, so a
20
- * console.warn that doesn't go through cli-report.js still shows up.
21
- *
22
- * Returns { child, exited } - `exited` resolves with the exit code.
23
- */
24
- export function runAstro(command, { packageRoot, contentDir, port, onEvent }) {
25
- // One spelling of each folder for Astro and Vite - see canonical-path.js.
26
- packageRoot = canonicalPath(packageRoot);
27
- contentDir = canonicalPath(contentDir);
28
- const child = spawn(process.execPath, [workerPath, command], {
29
- stdio: ['ignore', 'pipe', 'pipe', 'ipc'],
30
- // Explicit, not inherited: astro.config.mjs's own `outDir` lives
31
- // inside packageRoot (writedocsBuildStagingDir() - see its own
32
- // comment in writedocs-temp-dir.js for the full EXDEV story this is
33
- // one half of), and Astro's static builder only stages its
34
- // prerendered output *inside* that outDir - rather than falling
35
- // back to `<process.cwd()>/.astro/.prerender/` - when outDir starts
36
- // with process.cwd() (getOutDirWithinCwd, astro/dist/core/build/
37
- // common.js). Left unset, this child would just inherit whatever
38
- // directory the *parent* writedocs CLI process happened to be
39
- // launched from - unrelated to packageRoot for a real globally-
40
- // installed CLI invoked from wherever the user's shell happens to
41
- // be - so the fallback branch would fire regardless, staging
42
- // outside packageRoot again and reintroducing the exact module-
43
- // resolution problem this whole design is meant to avoid. Pinning
44
- // cwd to packageRoot here guarantees the "starts with cwd" check
45
- // passes deterministically, independent of the parent process's own
46
- // cwd.
47
- cwd: packageRoot,
48
- env: {
49
- ...process.env,
50
- WRITEDOCS_CONTENT_DIR: contentDir,
51
- // Astro is always run with root: packageRoot (astro-worker.js), so
52
- // every CollectionEntry's `filePath` comes back relative to *this*,
53
- // not to contentDir or the process's cwd. Exposed so lib/config.ts's
54
- // fileIdForEntry() can resolve it back into a docs/-relative file id
55
- // - see that function for why.
56
- WRITEDOCS_PACKAGE_ROOT: packageRoot,
57
- // 'dev' or 'build' - lib/build-memo.js keeps per-build results only in a build.
58
- WRITEDOCS_COMMAND: command,
59
- ...(port ? { WRITEDOCS_PORT: String(port) } : {}),
60
- },
61
- });
62
-
63
- child.on('message', (message) => {
64
- if (message && typeof message === 'object' && typeof message.type === 'string') onEvent(message);
65
- });
66
-
67
- for (const streamName of ['stdout', 'stderr']) {
68
- let pending = '';
69
- const emit = (line) => {
70
- if (line.trim() === '') return;
71
- const own = line.match(/^\[writedocs\]\s+(?:(\S+:\d+(?::\d+)?) - )?(.*)$/);
72
- if (own) onEvent({ type: 'report', level: streamName === 'stderr' ? 'warn' : 'info', message: own[2], where: own[1] ?? null });
73
- else onEvent({ type: 'raw', stream: streamName, line });
74
- };
75
- child[streamName].setEncoding('utf8');
76
- child[streamName].on('data', (chunk) => {
77
- pending += chunk;
78
- const lines = pending.split(/\r?\n/);
79
- pending = lines.pop();
80
- lines.forEach(emit);
81
- });
82
- child[streamName].on('end', () => {
83
- if (pending) emit(pending);
84
- pending = '';
85
- });
86
- }
87
-
88
- const exited = new Promise((resolve, reject) => {
89
- child.on('error', reject);
90
- child.on('close', (code, signal) => resolve(code ?? (signal ? 1 : 0)));
91
- });
92
- return { child, exited };
93
- }
1
+ import path from 'node:path';
2
+ import { spawn } from 'node:child_process';
3
+ import { canonicalPath } from '../lib/canonical-path.js';
4
+ import { fileURLToPath } from 'node:url';
5
+
6
+ const workerPath = path.join(path.dirname(fileURLToPath(import.meta.url)), 'astro-worker.js');
7
+
8
+ /**
9
+ * Runs Astro (`command`: 'dev' or 'build') in a child process -
10
+ * astro-worker.js - and turns everything it reports into events for
11
+ * `onEvent`, so the CLI decides what reaches the terminal:
12
+ *
13
+ * { type: 'astro-log', level, label, message } - an Astro/Vite log line
14
+ * { type: 'report', level, message, where } - writedocs' own code
15
+ * (lib/cli-report.js)
16
+ * { type: 'raw', stream, line } - anything printed directly
17
+ * { type: 'ready', urls } / { type: 'done' } / { type: 'fatal', error }
18
+ *
19
+ * A raw "[writedocs] ..." line is turned into a 'report' too, so a
20
+ * console.warn that doesn't go through cli-report.js still shows up.
21
+ *
22
+ * `env` adds variables for the child only (build.js's
23
+ * WRITEDOCS_OG_CARDS_FILE).
24
+ *
25
+ * Returns { child, exited } - `exited` resolves with the exit code.
26
+ */
27
+ export function runAstro(command, { packageRoot, contentDir, port, env = {}, onEvent }) {
28
+ // One spelling of each folder for Astro and Vite - see canonical-path.js.
29
+ packageRoot = canonicalPath(packageRoot);
30
+ contentDir = canonicalPath(contentDir);
31
+ const child = spawn(process.execPath, [workerPath, command], {
32
+ stdio: ['ignore', 'pipe', 'pipe', 'ipc'],
33
+ // Explicit, not inherited: astro.config.mjs's own `outDir` lives
34
+ // inside packageRoot (writedocsBuildStagingDir() - see its own
35
+ // comment in writedocs-temp-dir.js for the full EXDEV story this is
36
+ // one half of), and Astro's static builder only stages its
37
+ // prerendered output *inside* that outDir - rather than falling
38
+ // back to `<process.cwd()>/.astro/.prerender/` - when outDir starts
39
+ // with process.cwd() (getOutDirWithinCwd, astro/dist/core/build/
40
+ // common.js). Left unset, this child would just inherit whatever
41
+ // directory the *parent* writedocs CLI process happened to be
42
+ // launched from - unrelated to packageRoot for a real globally-
43
+ // installed CLI invoked from wherever the user's shell happens to
44
+ // be - so the fallback branch would fire regardless, staging
45
+ // outside packageRoot again and reintroducing the exact module-
46
+ // resolution problem this whole design is meant to avoid. Pinning
47
+ // cwd to packageRoot here guarantees the "starts with cwd" check
48
+ // passes deterministically, independent of the parent process's own
49
+ // cwd.
50
+ cwd: packageRoot,
51
+ env: {
52
+ ...process.env,
53
+ WRITEDOCS_CONTENT_DIR: contentDir,
54
+ // Astro is always run with root: packageRoot (astro-worker.js), so
55
+ // every CollectionEntry's `filePath` comes back relative to *this*,
56
+ // not to contentDir or the process's cwd. Exposed so lib/config.ts's
57
+ // fileIdForEntry() can resolve it back into a docs/-relative file id
58
+ // - see that function for why.
59
+ WRITEDOCS_PACKAGE_ROOT: packageRoot,
60
+ // 'dev' or 'build' - lib/build-memo.js keeps per-build results only in a build.
61
+ WRITEDOCS_COMMAND: command,
62
+ ...(port ? { WRITEDOCS_PORT: String(port) } : {}),
63
+ ...env,
64
+ },
65
+ });
66
+
67
+ child.on('message', (message) => {
68
+ if (message && typeof message === 'object' && typeof message.type === 'string') onEvent(message);
69
+ });
70
+
71
+ for (const streamName of ['stdout', 'stderr']) {
72
+ let pending = '';
73
+ const emit = (line) => {
74
+ if (line.trim() === '') return;
75
+ const own = line.match(/^\[writedocs\]\s+(?:(\S+:\d+(?::\d+)?) - )?(.*)$/);
76
+ if (own) onEvent({ type: 'report', level: streamName === 'stderr' ? 'warn' : 'info', message: own[2], where: own[1] ?? null });
77
+ else onEvent({ type: 'raw', stream: streamName, line });
78
+ };
79
+ child[streamName].setEncoding('utf8');
80
+ child[streamName].on('data', (chunk) => {
81
+ pending += chunk;
82
+ const lines = pending.split(/\r?\n/);
83
+ pending = lines.pop();
84
+ lines.forEach(emit);
85
+ });
86
+ child[streamName].on('end', () => {
87
+ if (pending) emit(pending);
88
+ pending = '';
89
+ });
90
+ }
91
+
92
+ const exited = new Promise((resolve, reject) => {
93
+ child.on('error', reject);
94
+ child.on('close', (code, signal) => resolve(code ?? (signal ? 1 : 0)));
95
+ });
96
+ return { child, exited };
97
+ }