@writedocs/generator 0.13.4 → 0.13.5

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 (86) hide show
  1. package/README.md +28 -28
  2. package/astro.config.mjs +645 -645
  3. package/bin/writedocs.js +356 -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 +203 -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 +268 -268
  11. package/src/cli/exit-when-flushed.js +42 -42
  12. package/src/cli/generate-api-pages.js +507 -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 +69 -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 +203 -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 +408 -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.ts +2509 -2509
  48. package/src/lib/config.ts +1316 -1316
  49. package/src/lib/consent.js +108 -108
  50. package/src/lib/content-store-reload-integration.js +101 -101
  51. package/src/lib/icon-data-dev.js +53 -53
  52. package/src/lib/image-size.js +152 -152
  53. package/src/lib/json-schema-descriptions.js +228 -228
  54. package/src/lib/link-check.js +544 -544
  55. package/src/lib/llms-index.ts +90 -90
  56. package/src/lib/mcp-dev-integration.js +65 -65
  57. package/src/lib/mcp-index.ts +102 -102
  58. package/src/lib/mintlify-convert.js +605 -605
  59. package/src/lib/moved-api-pages.js +49 -49
  60. package/src/lib/og-cards.js +33 -33
  61. package/src/lib/og-image.js +235 -235
  62. package/src/lib/openapi-dev-status.js +80 -80
  63. package/src/lib/openapi-reload-integration.js +193 -193
  64. package/src/lib/pages.js +312 -312
  65. package/src/lib/project-files-integration.js +116 -116
  66. package/src/lib/project-files.js +137 -137
  67. package/src/lib/rehype-base-path.js +62 -62
  68. package/src/lib/rehype-image-loading.js +71 -71
  69. package/src/lib/robots-txt.js +21 -21
  70. package/src/lib/search-scope.js +44 -44
  71. package/src/lib/selector-placement.js +50 -50
  72. package/src/lib/seo-tags.js +155 -155
  73. package/src/lib/shiki-code-block.js +7 -1
  74. package/src/lib/site-base.ts +27 -27
  75. package/src/lib/styles-asset-integration.js +291 -291
  76. package/src/lib/wdignore-cases.json +195 -195
  77. package/src/lib/wdignore.js +177 -177
  78. package/src/pages/404.astro +63 -63
  79. package/src/pages/[...slug].astro +1762 -1608
  80. package/src/pages/[...slug].md.ts +93 -93
  81. package/src/pages/llms-full.txt.ts +88 -88
  82. package/src/pages/og/[...slug].png.ts +63 -63
  83. package/src/scripts/mobile-menu.ts +80 -80
  84. package/src/scripts/search.ts +245 -245
  85. package/src/scripts/sidebar-scroll.ts +61 -61
  86. package/src/styles/global.css +40 -40
@@ -1,20 +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');
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');
@@ -1,70 +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
+ // `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,69 +1,69 @@
1
- // `writedocs dev`: noticing pages added or removed. The preview's list of page
2
- // files is read once, when it starts (content.config.ts hands findAllPages()'s
3
- // list to Astro) - an edit to a page shows up at once, but a new page stays
4
- // "not found" and a deleted one keeps being served. So this watches the
5
- // content folder, and when the list findAllPages() gives changes, calls
6
- // `onChange` - cli/dev.js restarts the preview then.
7
- //
8
- // It compares the list itself, not file events: a Markdown file that isn't
9
- // a page (no frontmatter, not in the navigation), an edit to a page, or a
10
- // save that writes a file twice doesn't restart anything.
11
- import fs from 'node:fs';
12
- import { findAllPages, EXCLUDED_TOP_LEVEL_DIRS } from '../lib/pages.js';
13
- import { WDIGNORE_FILE } from '../lib/wdignore.js';
14
-
15
- /** Wait this long after the last file event before checking - a rename, a
16
- * copy of several files or an editor's save arrive as a burst of events. */
17
- export const SETTLE_MS = 400;
18
-
19
- /** Whether a changed file can change the page list: a .md/.mdx file, or
20
- * writedocs.json (it lists pages that have no frontmatter), outside the
21
- * folders findAllPages() never looks in - or the project's `.wdignore`,
22
- * which says which files aren't pages. */
23
- export function mayChangePages(relative) {
24
- if (!relative) return true;
25
- const parts = String(relative).split(/[\\/]/);
26
- if (parts.length === 1 && parts[0] === WDIGNORE_FILE) return true;
27
- if (EXCLUDED_TOP_LEVEL_DIRS.has(parts[0]) || parts.some((part) => part.startsWith('.'))) return false;
28
- const name = parts[parts.length - 1];
29
- return /\.mdx?$/i.test(name) || name === 'writedocs.json';
30
- }
31
-
32
- /** Starts watching; returns `{ close }`. `onChange({ added, removed })` gets
33
- * the page files (relative paths) that came and went. */
34
- export function watchPageList(contentDir, onChange, { settleMs = SETTLE_MS } = {}) {
35
- let current = new Set(findAllPages(contentDir));
36
- let timer = null;
37
- const check = () => {
38
- let next;
39
- try {
40
- next = new Set(findAllPages(contentDir));
41
- } catch {
42
- return; // mid-save, or a folder being moved - the next event checks again
43
- }
44
- const added = [...next].filter((file) => !current.has(file));
45
- const removed = [...current].filter((file) => !next.has(file));
46
- if (!added.length && !removed.length) return;
47
- current = next;
48
- onChange({ added, removed });
49
- };
50
- let watcher;
51
- try {
52
- watcher = fs.watch(contentDir, { recursive: true }, (_event, filename) => {
53
- if (!mayChangePages(filename)) return;
54
- clearTimeout(timer);
55
- timer = setTimeout(check, settleMs);
56
- });
57
- watcher.on('error', () => {});
58
- } catch {
59
- // A file system without recursive watching: pages added while `dev`
60
- // runs need a restart, as before.
61
- return { close() {} };
62
- }
63
- return {
64
- close() {
65
- clearTimeout(timer);
66
- watcher.close();
67
- },
68
- };
69
- }
1
+ // `writedocs dev`: noticing pages added or removed. The preview's list of page
2
+ // files is read once, when it starts (content.config.ts hands findAllPages()'s
3
+ // list to Astro) - an edit to a page shows up at once, but a new page stays
4
+ // "not found" and a deleted one keeps being served. So this watches the
5
+ // content folder, and when the list findAllPages() gives changes, calls
6
+ // `onChange` - cli/dev.js restarts the preview then.
7
+ //
8
+ // It compares the list itself, not file events: a Markdown file that isn't
9
+ // a page (no frontmatter, not in the navigation), an edit to a page, or a
10
+ // save that writes a file twice doesn't restart anything.
11
+ import fs from 'node:fs';
12
+ import { findAllPages, EXCLUDED_TOP_LEVEL_DIRS } from '../lib/pages.js';
13
+ import { WDIGNORE_FILE } from '../lib/wdignore.js';
14
+
15
+ /** Wait this long after the last file event before checking - a rename, a
16
+ * copy of several files or an editor's save arrive as a burst of events. */
17
+ export const SETTLE_MS = 400;
18
+
19
+ /** Whether a changed file can change the page list: a .md/.mdx file, or
20
+ * writedocs.json (it lists pages that have no frontmatter), outside the
21
+ * folders findAllPages() never looks in - or the project's `.wdignore`,
22
+ * which says which files aren't pages. */
23
+ export function mayChangePages(relative) {
24
+ if (!relative) return true;
25
+ const parts = String(relative).split(/[\\/]/);
26
+ if (parts.length === 1 && parts[0] === WDIGNORE_FILE) return true;
27
+ if (EXCLUDED_TOP_LEVEL_DIRS.has(parts[0]) || parts.some((part) => part.startsWith('.'))) return false;
28
+ const name = parts[parts.length - 1];
29
+ return /\.mdx?$/i.test(name) || name === 'writedocs.json';
30
+ }
31
+
32
+ /** Starts watching; returns `{ close }`. `onChange({ added, removed })` gets
33
+ * the page files (relative paths) that came and went. */
34
+ export function watchPageList(contentDir, onChange, { settleMs = SETTLE_MS } = {}) {
35
+ let current = new Set(findAllPages(contentDir));
36
+ let timer = null;
37
+ const check = () => {
38
+ let next;
39
+ try {
40
+ next = new Set(findAllPages(contentDir));
41
+ } catch {
42
+ return; // mid-save, or a folder being moved - the next event checks again
43
+ }
44
+ const added = [...next].filter((file) => !current.has(file));
45
+ const removed = [...current].filter((file) => !next.has(file));
46
+ if (!added.length && !removed.length) return;
47
+ current = next;
48
+ onChange({ added, removed });
49
+ };
50
+ let watcher;
51
+ try {
52
+ watcher = fs.watch(contentDir, { recursive: true }, (_event, filename) => {
53
+ if (!mayChangePages(filename)) return;
54
+ clearTimeout(timer);
55
+ timer = setTimeout(check, settleMs);
56
+ });
57
+ watcher.on('error', () => {});
58
+ } catch {
59
+ // A file system without recursive watching: pages added while `dev`
60
+ // runs need a restart, as before.
61
+ return { close() {} };
62
+ }
63
+ return {
64
+ close() {
65
+ clearTimeout(timer);
66
+ watcher.close();
67
+ },
68
+ };
69
+ }
@@ -1,97 +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
- * `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
- }
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
+ }