@writedocs/generator 0.10.20 → 0.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/astro.config.mjs +32 -8
  2. package/package.json +3 -1
  3. package/src/cli/astro-output.js +44 -11
  4. package/src/cli/base-path-layout.js +44 -0
  5. package/src/cli/build.js +18 -9
  6. package/src/cli/check-built-styles.js +41 -33
  7. package/src/cli/dev.js +21 -4
  8. package/src/cli/run-pagefind.js +154 -148
  9. package/src/cli/write-mcp-files.js +103 -96
  10. package/src/cli/write-redirects-file.js +25 -8
  11. package/src/components/AppIcon.astro +51 -50
  12. package/src/components/Card.astro +193 -192
  13. package/src/components/CopyPageMenu.astro +374 -370
  14. package/src/components/Hint.astro +188 -187
  15. package/src/components/Icon.astro +72 -71
  16. package/src/components/Image.astro +3 -2
  17. package/src/components/Tile.astro +67 -66
  18. package/src/components/Video.astro +137 -136
  19. package/src/layout/BaseLayout.astro +21 -12
  20. package/src/layout/components/AnalyticsScripts.astro +6 -2
  21. package/src/layout/components/Breadcrumbs.astro +98 -97
  22. package/src/layout/components/ConsentBanner.astro +119 -118
  23. package/src/layout/components/MobileMenu.astro +229 -228
  24. package/src/layout/components/NavTree.astro +393 -392
  25. package/src/layout/components/Sidebar.astro +232 -231
  26. package/src/layout/components/SiteFooter.astro +87 -86
  27. package/src/layout/components/TopBar.astro +386 -385
  28. package/src/lib/agent-markdown.js +164 -162
  29. package/src/lib/asset-dimensions.js +89 -89
  30. package/src/lib/base-path.js +90 -0
  31. package/src/lib/config-schema.js +10 -0
  32. package/src/lib/config-schema.ts +17 -0
  33. package/src/lib/config.ts +1314 -1289
  34. package/src/lib/consent.js +108 -102
  35. package/src/lib/json-schema-descriptions.js +1 -0
  36. package/src/lib/link-check.js +7 -2
  37. package/src/lib/llms-index.ts +90 -88
  38. package/src/lib/mcp-dev-integration.js +65 -60
  39. package/src/lib/mcp-index.ts +102 -101
  40. package/src/lib/project-files-integration.js +2 -2
  41. package/src/lib/rehype-base-path.js +62 -0
  42. package/src/lib/robots-txt.js +21 -16
  43. package/src/lib/seo-tags.js +155 -140
  44. package/src/lib/site-base.ts +27 -0
  45. package/src/lib/styles-asset-integration.js +23 -10
  46. package/src/lib/wdignore-cases.json +195 -195
  47. package/src/lib/wdignore.js +177 -177
  48. package/src/pages/404.astro +63 -62
  49. package/src/pages/[...slug].astro +1604 -1597
  50. package/src/pages/[...slug].md.ts +93 -93
  51. package/src/pages/llms-full.txt.ts +88 -86
  52. package/src/scripts/search.ts +245 -237
  53. package/writedocs.schema.json +6 -0
package/astro.config.mjs CHANGED
@@ -39,12 +39,14 @@ import { stylesAssetFallback } from './src/lib/styles-asset-integration.js';
39
39
  import { mcpDevServer } from './src/lib/mcp-dev-integration.js';
40
40
  import { configReload } from './src/lib/config-reload-integration.js';
41
41
  import { canonicalPath } from './src/lib/canonical-path.js';
42
+ import { withBase, withoutBase } from './src/lib/base-path.js';
42
43
  import { folderAddresses } from './src/lib/folder-redirects.js';
43
44
  import { report } from './src/lib/cli-report.js';
44
45
  import { publishProjectFiles, generatedRobotsTxt } from './src/lib/project-files-integration.js';
45
46
  import { frontmatterNoindex, canonicalIsElsewhere } from './src/lib/seo-tags.js';
46
47
  import { readMovedApiPages } from './src/lib/moved-api-pages.js';
47
48
  import { rehypeImageLoading } from './src/lib/rehype-image-loading.js';
49
+ import { rehypeBasePath } from './src/lib/rehype-base-path.js';
48
50
  import { gitLastModified, newestDate } from './src/lib/last-modified.js';
49
51
  import { readSpecPaths } from './src/lib/project-files.js';
50
52
  import {
@@ -52,6 +54,8 @@ import {
52
54
  resolveCodeblockTheme,
53
55
  resolveCodeblockLangAlias,
54
56
  resolveSiteUrl,
57
+ resolveSiteOrigin,
58
+ resolveBasePath,
55
59
  normalizeEntryId,
56
60
  findAllPages,
57
61
  } from './src/lib/config.ts';
@@ -115,6 +119,10 @@ const contentPublicDir = path.join(contentDir, 'public');
115
119
  // config to be set and would otherwise throw, and a sitemap of
116
120
  // document-relative URLs isn't meaningful anyway.
117
121
  const siteUrl = resolveSiteUrl(docsConfig);
122
+ // writedocs.json's `basePath` ("" when unset) - see lib/base-path.js. Astro's
123
+ // own `base` gets it (bundled assets, the dev server's address), and so do
124
+ // the page scripts, as __WD_BASE__ (vite.define below).
125
+ const basePath = resolveBasePath(docsConfig);
118
126
  if (!siteUrl) {
119
127
  report(
120
128
  'info',
@@ -256,7 +264,10 @@ function singleSitemapFile() {
256
264
  // redirect from the old one the same way; a redirect the site wrote itself
257
265
  // for the same address comes later in the list, and wins.
258
266
  const movedApiPages = readMovedApiPages(contentDir);
259
- const redirectsConfig = Object.fromEntries([...movedApiPages, ...docsConfig.redirects].map((r) => [r.source, r.destination]));
267
+ // With a basePath, Astro serves a redirect's source under the base itself,
268
+ // but writes its destination as given - so a destination inside the site
269
+ // gets the base here (lib/base-path.js).
270
+ const redirectsConfig = Object.fromEntries([...movedApiPages, ...docsConfig.redirects].map((r) => [r.source, withBase(basePath, r.destination)]));
260
271
 
261
272
  /** Tailwind only scans the Vite root for class names - this package, not
262
273
  * the site being built, which is usually somewhere else entirely - so a
@@ -278,7 +289,10 @@ function contentTailwindSource() {
278
289
  }
279
290
 
280
291
  export default defineConfig({
281
- ...(siteUrl ? { site: siteUrl } : {}),
292
+ // The origin alone: Astro adds `base` to it itself (the sitemap's URLs).
293
+ ...(siteUrl ? { site: resolveSiteOrigin(docsConfig) } : {}),
294
+ // Only with a basePath: without one the config is exactly what it was.
295
+ ...(basePath ? { base: basePath } : {}),
282
296
  ...(Object.keys(redirectsConfig).length ? { redirects: redirectsConfig } : {}),
283
297
  // Astro's own dev-mode toolbar (the floating pill in the bottom center
284
298
  // of every page - inspect/audit/settings) is a tool for authoring
@@ -334,14 +348,16 @@ export default defineConfig({
334
348
  // @astrojs/sitemap é 45.000). Até aqui, tudo cabe num único
335
349
  // sitemap.xml - ver singleSitemapFile() abaixo.
336
350
  entryLimit: 50000,
351
+ // The plugin's URLs carry the base ("/docs/guides/a/") - the
352
+ // ids here don't.
337
353
  filter: (page) => {
338
- const pathname = new URL(page).pathname;
354
+ const pathname = withoutBase(basePath, new URL(page).pathname) ?? '/';
339
355
  const id = normalizeEntryId(pathname);
340
356
  return !noindexIds.has(id);
341
357
  },
342
358
  // <lastmod>, for the pages git has a date for.
343
359
  serialize: (item) => {
344
- const changed = lastModifiedById.get(normalizeEntryId(new URL(item.url).pathname));
360
+ const changed = lastModifiedById.get(normalizeEntryId(withoutBase(basePath, new URL(item.url).pathname) ?? '/'));
345
361
  return changed ? { ...item, lastmod: changed } : item;
346
362
  },
347
363
  }),
@@ -351,16 +367,16 @@ export default defineConfig({
351
367
  ]
352
368
  : []),
353
369
  // After the sitemap: the generated robots.txt names the sitemap file.
354
- generatedRobotsTxt({ siteUrl, seo: docsConfig.seo }),
370
+ generatedRobotsTxt({ siteUrl, seo: docsConfig.seo, basePath }),
355
371
  // Lets styles.favicon/styles.logo/styles.background.images/seo.ogImage/
356
372
  // styles.fonts.*.source resolve from anywhere in the project, not just
357
373
  // public/ - see collectConfiguredAssetPaths() (lib/config.ts) for the
358
374
  // field list and styles-asset-integration.js for how it's actually
359
375
  // served/copied.
360
- stylesAssetFallback(contentDir),
376
+ stylesAssetFallback(contentDir, { basePath }),
361
377
  // /mcp in `writedocs dev`, as the build's dist/_worker.js serves it -
362
378
  // see src/lib/mcp-dev-integration.js.
363
- mcpDevServer({ version: JSON.parse(fs.readFileSync(path.join(packageRoot, 'package.json'), 'utf-8')).version }),
379
+ mcpDevServer({ version: JSON.parse(fs.readFileSync(path.join(packageRoot, 'package.json'), 'utf-8')).version, basePath }),
364
380
  // writedocs dev: an edit to writedocs.json reloads the open tab.
365
381
  configReload({ configPath: path.join(contentDir, 'writedocs.json') }),
366
382
  ],
@@ -482,7 +498,10 @@ export default defineConfig({
482
498
  // neither plugin's output is visible to the other.
483
499
  // rehypeImageLoading: lazy loading and sizes for content images - see
484
500
  // lib/rehype-image-loading.js.
485
- rehypePlugins: [rehypeMermaid, rehypeKatex, [rehypeImageLoading, { contentDir }]],
501
+ // rehypeBasePath: the basePath in front of the content's own links and
502
+ // pictures (lib/rehype-base-path.js) - last, since rehypeImageLoading
503
+ // finds an image's file by the address as written.
504
+ rehypePlugins: [rehypeMermaid, rehypeKatex, [rehypeImageLoading, { contentDir }], [rehypeBasePath, { base: basePath }]],
486
505
  }),
487
506
  shikiConfig: {
488
507
  themes: codeblockTheme,
@@ -526,6 +545,11 @@ export default defineConfig({
526
545
  // working. See src/styles/global.css for the one @import that wires
527
546
  // Tailwind's utilities in.
528
547
  vite: {
548
+ // The base for page scripts and components: "" or "/docs". A constant
549
+ // rather than import.meta.env.BASE_URL ("/" with no base, "/docs" or
550
+ // "/docs/" with one), so `__WD_BASE__ + "/pagefind/..."` folds to the
551
+ // same string the bundle had before basePath existed.
552
+ define: { __WD_BASE__: JSON.stringify(basePath) },
529
553
  // The dev server only serves files under its workspace root by default.
530
554
  // A site's own snippets live in its content directory, and inline React
531
555
  // components moved out of pages (lib/mdx-inline-react.js) in writedocs'
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@writedocs/generator",
3
- "version": "0.10.20",
3
+ "version": "0.11.1",
4
4
  "description": "Static site generator for docs — a writedocs.json + MDX folder in, a static site out.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -83,9 +83,11 @@
83
83
  "react-dom": "19.2.8",
84
84
  "rehype-katex": "7.0.1",
85
85
  "remark-math": "6.0.0",
86
+ "rolldown": "1.2.4",
86
87
  "satori": "0.44.0",
87
88
  "shiki": "4.4.3",
88
89
  "tailwindcss": "4.3.3",
90
+ "vite": "8.2.1",
89
91
  "zod": "4.4.3"
90
92
  },
91
93
  "engines": {
@@ -5,6 +5,7 @@
5
5
  // author should see or noise to hide.
6
6
  import fs from 'node:fs';
7
7
  import path from 'node:path';
8
+ import { fileURLToPath } from 'node:url';
8
9
 
9
10
  const ANSI = /\x1b\[[0-9;]*m/g;
10
11
  export const stripAnsi = (text) => String(text ?? '').replace(ANSI, '');
@@ -14,7 +15,10 @@ export const stripAnsi = (text) => String(text ?? '').replace(ANSI, '');
14
15
  const SECTION = /\n\s*(Stack trace|Hint|Error reference|Location|Caused by):/;
15
16
 
16
17
  function absolutePath(file, root) {
17
- const clean = file.replace(/^file:\/\/\/?/, '').replace(/[?#].*$/, '');
18
+ const clean = file.replace(/[?#].*$/, '');
19
+ if (clean.startsWith('file:')) {
20
+ try { return fileURLToPath(clean); } catch {}
21
+ }
18
22
  return path.resolve(root ?? process.cwd(), clean);
19
23
  }
20
24
 
@@ -146,19 +150,48 @@ export function requestLog(event) {
146
150
  return match ? { status: Number(match[1]), url: match[2] } : null;
147
151
  }
148
152
 
153
+ // Warnings that name the author's page but are about code writedocs and
154
+ // Astro generate, so there's nothing for the author to do: newer rolldown
155
+ // versions flag the "use astro:head-inject" directive Astro writes into the
156
+ // wrapper module of every .mdx page (astro/dist/content/
157
+ // vite-plugin-content-assets.js) - one warning per page, on every build.
158
+ const GENERATED_CODE_WARNINGS = [/\[MODULE_LEVEL_DIRECTIVE\][^\n]*"use astro:head-inject"/];
159
+
160
+ const escapeRegExp = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
161
+
149
162
  /** An Astro/Vite warning worth showing the author: one about their own
150
- * files (it names a path inside the project), rewritten to relative
151
- * paths. Everything else - bundle sizes, dependency optimization, route
152
- * internals - is about writedocs itself, and stays hidden (--verbose shows
153
- * it). */
154
- export function authorWarning(event, contentDir) {
163
+ * files (it names a path inside the project), with those paths rewritten
164
+ * relative to the project. Everything else - bundle sizes, dependency
165
+ * optimization, route internals - is about writedocs itself, and stays
166
+ * hidden (--verbose shows it).
167
+ *
168
+ * A path counts only as a whole path that resolves inside contentDir:
169
+ * absolute, or relative to `root` (Astro's working folder, the package
170
+ * root - rolldown names modules that way). Matching contentDir as a bare
171
+ * substring once let a project at /build claim every warning naming
172
+ * ".../build/..." and turned "creator-review/build.mdx" into
173
+ * "creator-review..mdx". */
174
+ export function authorWarning(event, contentDir, { root } = {}) {
155
175
  if (event.type !== 'astro-log' || event.level !== 'warn') return null;
156
176
  const text = stripAnsi(event.message);
157
- const variants = [contentDir, contentDir.split(path.sep).join('/'), contentDir.split('/').join('\\')];
158
- if (!variants.some((v) => text.includes(v))) return null;
159
- let out = text;
160
- for (const v of variants) out = out.split(`${v}/`).join('').split(`${v}\\`).join('').split(v).join('.');
161
- return out.trim();
177
+ if (GENERATED_CODE_WARNINGS.some((pattern) => pattern.test(text))) return null;
178
+
179
+ // A path starts after a space, a quote or a bracket, as contentDir itself
180
+ // (which may hold spaces) or as ./ or ../, and runs to the next of those.
181
+ const variants = [...new Set([contentDir, contentDir.split(path.sep).join('/'), contentDir.split('/').join('\\')])];
182
+ const starts = [...variants.map(escapeRegExp), '\\.\\.?[\\\\/]'].join('|');
183
+ const pathToken = new RegExp(`(?<![^\\s"'\`(\\[<=])(?:file:///?)?(?:${starts})[^\\s"'\`()\\[\\]<>,]*`, 'g');
184
+
185
+ let named = false;
186
+ const out = text.replace(pathToken, (token) => {
187
+ const at = token.match(/(?::\d+){1,2}$/)?.[0] ?? '';
188
+ const file = token.slice(0, token.length - at.length);
189
+ const rel = relativeTo(contentDir, file, root);
190
+ if (rel === null) return token;
191
+ named = true;
192
+ return `${rel || '.'}${at}`;
193
+ });
194
+ return named ? out.trim() : null;
162
195
  }
163
196
 
164
197
  /** One event as a plain line, for --verbose. */
@@ -0,0 +1,44 @@
1
+ // Where a build puts the site in dist/ (build.js). Without a basePath, at
2
+ // dist/ itself, as always. With one ("/docs", writedocs.json - see
3
+ // lib/base-path.js), every file the site serves goes to dist/docs/: a static
4
+ // server that serves dist/ at its root answers /docs/... with no rule of its
5
+ // own, and a proxy that passes /docs/* on with its path unchanged finds every
6
+ // file where its address says.
7
+ //
8
+ // A few files aren't the site's but its host's, and the host reads them at
9
+ // the root of what it serves, so they stay in dist/:
10
+ // 404.html the page a host shows for an address it doesn't have
11
+ // (Cloudflare Pages, the WriteDocs platform look for it there);
12
+ // _redirects the host's redirects - every path in the generated rules
13
+ // carries the base (write-redirects-file.js);
14
+ // _headers the host's response headers, when the project has one;
15
+ // _worker.js, _routes.json, .assetsignore
16
+ // the Cloudflare MCP server (write-mcp-files.js), which
17
+ // Cloudflare only runs from the root.
18
+ import fs from 'node:fs';
19
+ import path from 'node:path';
20
+
21
+ /** The host's files - kept at the root of dist/, outside the basePath. */
22
+ export const ROOT_FILES = ['404.html', '_redirects', '_headers', '_worker.js', '_routes.json', '.assetsignore'];
23
+
24
+ /** The folder the site itself goes to: dist/ without a basePath,
25
+ * dist/docs/ for "/docs", dist/help/docs/ for "/help/docs". */
26
+ export function siteDirFor(distDir, basePath) {
27
+ const segments = (basePath ?? '').split('/').filter(Boolean);
28
+ return segments.length ? path.join(distDir, ...segments) : distDir;
29
+ }
30
+
31
+ /** Moves the host's files (ROOT_FILES) a build left in the site's folder up
32
+ * to the root of dist/. Nothing to do without a basePath. Returns the names
33
+ * moved. */
34
+ export function moveRootFiles(siteDir, distDir) {
35
+ if (path.resolve(siteDir) === path.resolve(distDir)) return [];
36
+ const moved = [];
37
+ for (const name of ROOT_FILES) {
38
+ const from = path.join(siteDir, name);
39
+ if (!fs.existsSync(from)) continue;
40
+ fs.renameSync(from, path.join(distDir, name));
41
+ moved.push(name);
42
+ }
43
+ return moved;
44
+ }
package/src/cli/build.js CHANGED
@@ -11,6 +11,8 @@ import { readConfigText } from '../lib/config-file.js';
11
11
  import { writeMcpFiles } from './write-mcp-files.js';
12
12
  import { pagesWithoutStyles } from './check-built-styles.js';
13
13
  import { writedocsBuildStagingDir } from '../lib/writedocs-temp-dir.js';
14
+ import { normalizeBasePath } from '../lib/base-path.js';
15
+ import { siteDirFor, moveRootFiles } from './base-path-layout.js';
14
16
  import { log, step, plural, duration, displayPath, formatProblems, color, CliExit } from './output.js';
15
17
  import { describeError, builtRoute, authorWarning, verboseLine } from './astro-output.js';
16
18
  import { reportApiPages } from './api-pages-output.js';
@@ -73,7 +75,7 @@ export async function runBuild({ contentDir, packageRoot, verbose = false }) {
73
75
  building.update(`Building pages ${color.dim(`(${pages})`)}`);
74
76
  return;
75
77
  }
76
- const warning = authorWarning(event, contentDir);
78
+ const warning = authorWarning(event, contentDir, { root: packageRoot });
77
79
  if (warning) addWarning(null, warning);
78
80
  },
79
81
  });
@@ -99,6 +101,13 @@ export async function runBuild({ contentDir, packageRoot, verbose = false }) {
99
101
  building.succeed(`Built ${plural(pages, 'page')} ${color.dim(`in ${duration(Date.now() - buildStarted)}`)}`);
100
102
 
101
103
  const distDir = path.join(contentDir, 'dist');
104
+ // writedocs.json has been through the build's own validation by now.
105
+ const siteConfig = JSON.parse(readConfigText(contentDir));
106
+ // With a `basePath` ("/docs"), the site goes to dist/docs/ and only the
107
+ // host's own files stay at the root of dist/ - see base-path-layout.js.
108
+ // Without one, siteDir is distDir, and every step below is what it was.
109
+ const basePath = normalizeBasePath(siteConfig.basePath);
110
+ const siteDir = siteDirFor(distDir, basePath);
102
111
  // Astro just wrote its actual output to writedocsBuildStagingDir()
103
112
  // (astro.config.mjs's own `outDir`), not distDir directly - see that
104
113
  // function's own comment (writedocs-temp-dir.js) for why. fs.cpSync
@@ -113,13 +122,14 @@ export async function runBuild({ contentDir, packageRoot, verbose = false }) {
113
122
  // writing directly into outDir.
114
123
  const stagingDir = writedocsBuildStagingDir(packageRoot, contentDir);
115
124
  fs.rmSync(distDir, { recursive: true, force: true });
116
- fs.cpSync(stagingDir, distDir, { recursive: true });
125
+ fs.cpSync(stagingDir, siteDir, { recursive: true });
117
126
  fs.rmSync(stagingDir, { recursive: true, force: true });
127
+ moveRootFiles(siteDir, distDir);
118
128
  // Every page writedocs renders links the site's stylesheet. Builds have
119
129
  // come out without it on every page while reporting success (the package
120
130
  // folder spelled `c:`, fixed in lib/canonical-path.js) - so it's checked
121
131
  // here, and a build like that stops instead of being deployed unstyled.
122
- const unstyled = pagesWithoutStyles(distDir);
132
+ const unstyled = pagesWithoutStyles(distDir, { basePath });
123
133
  if (unstyled.length) {
124
134
  log.error(`The build produced ${plural(unstyled.length, 'page')} without the site's styles - for example ${unstyled[0]}.`);
125
135
  log.detail(color.dim('This is a fault in the build, not in your pages. Build again; if it happens again, report it with the output of --verbose.'));
@@ -129,22 +139,21 @@ export async function runBuild({ contentDir, packageRoot, verbose = false }) {
129
139
  // ever produce client-side meta-refresh pages (see write-redirects-file.js)
130
140
  // - this turns those into real instant edge redirects on hosts that read
131
141
  // a `_redirects` file (Cloudflare Pages, Netlify), purely additively.
132
- writeRedirectsFile(distDir, contentDir);
142
+ writeRedirectsFile(siteDir, contentDir, { outDir: distDir, basePath });
133
143
  // Every other host follows Astro's redirect pages - rewritten so the
134
144
  // reader never sees one (rewrite-redirect-pages.js).
135
- const siteConfig = JSON.parse(readConfigText(contentDir));
136
- rewriteRedirectPages(distDir, { background: siteConfig.styles?.background?.colors });
145
+ rewriteRedirectPages(siteDir, { background: siteConfig.styles?.background?.colors });
137
146
  // The site's MCP server at /mcp: mcp-index.json is already in dist/ (an
138
147
  // Astro route); this adds the Cloudflare _worker.js that serves it - see
139
148
  // write-mcp-files.js for every host.
140
149
  const { version: writedocsVersion } = JSON.parse(fs.readFileSync(path.join(packageRoot, 'package.json'), 'utf-8'));
141
- const mcp = writeMcpFiles(distDir, contentDir, writedocsVersion);
142
- if (mcp.written.length) notes.push('MCP server at /mcp - dist/_worker.js runs it on Cloudflare; mcp-index.json holds the pages.');
150
+ const mcp = writeMcpFiles(distDir, contentDir, writedocsVersion, { siteDir, basePath });
151
+ if (mcp.written.length) notes.push(`MCP server at ${basePath}/mcp - dist/_worker.js runs it on Cloudflare; mcp-index.json holds the pages.`);
143
152
  if (mcp.skipped) addWarning(null, `No _worker.js for the MCP server: ${mcp.skipped}.`);
144
153
 
145
154
  const indexing = step('Indexing search');
146
155
  try {
147
- await runPagefind(distDir, { packageRoot });
156
+ await runPagefind(siteDir, { packageRoot });
148
157
  } catch (err) {
149
158
  indexing.fail('Search indexing failed');
150
159
  log.line();
@@ -1,33 +1,41 @@
1
- // After a build: the pages writedocs rendered that came out without the
2
- // site's styles. Every page BaseLayout.astro renders carries
3
- // <meta name="generator" content="writedocs"> and links its stylesheet
4
- // (/_astro/*.css), or inlines it in a <style>. Other HTML in dist/ - a
5
- // redirect page, a file from public/ - isn't writedocs' to check.
6
- import fs from 'node:fs';
7
- import path from 'node:path';
8
-
9
- const MARKER = /<meta name="generator" content="writedocs"/;
10
- const STYLES = /<link[^>]+rel="stylesheet"[^>]+href="\/_astro\/[^"]+\.css"|<link[^>]+href="\/_astro\/[^"]+\.css"[^>]+rel="stylesheet"|<style[\s>]/;
11
-
12
- function htmlFiles(dir) {
13
- const out = [];
14
- for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
15
- const full = path.join(dir, entry.name);
16
- if (entry.isDirectory()) {
17
- if (entry.name !== '_astro' && entry.name !== 'pagefind') out.push(...htmlFiles(full));
18
- } else if (entry.name.endsWith('.html')) out.push(full);
19
- }
20
- return out;
21
- }
22
-
23
- /** Paths (relative to `distDir`, with forward slashes) of writedocs pages
24
- * with no stylesheet. */
25
- export function pagesWithoutStyles(distDir) {
26
- return htmlFiles(distDir)
27
- .filter((file) => {
28
- const html = fs.readFileSync(file, 'utf8');
29
- return MARKER.test(html) && !STYLES.test(html);
30
- })
31
- .map((file) => path.relative(distDir, file).split(path.sep).join('/'))
32
- .sort();
33
- }
1
+ // After a build: the pages writedocs rendered that came out without the
2
+ // site's styles. Every page BaseLayout.astro renders carries
3
+ // <meta name="generator" content="writedocs"> and links its stylesheet
4
+ // (/_astro/*.css - /docs/_astro/*.css under a basePath), or inlines it in a
5
+ // <style>. Other HTML in dist/ - a redirect page, a file from public/ -
6
+ // isn't writedocs' to check.
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+
10
+ const MARKER = /<meta name="generator" content="writedocs"/;
11
+ /** The stylesheet link (or <style>) of a page whose site has `basePath` -
12
+ * "" or "/docs", lib/base-path.js: only lowercase letters, digits, "-", "_"
13
+ * and "/", nothing to escape in a pattern. */
14
+ function stylesPattern(basePath = '') {
15
+ const css = `${basePath}/_astro/[^"]+\\.css`;
16
+ return new RegExp(`<link[^>]+rel="stylesheet"[^>]+href="${css}"|<link[^>]+href="${css}"[^>]+rel="stylesheet"|<style[\\s>]`);
17
+ }
18
+
19
+ function htmlFiles(dir) {
20
+ const out = [];
21
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
22
+ const full = path.join(dir, entry.name);
23
+ if (entry.isDirectory()) {
24
+ if (entry.name !== '_astro' && entry.name !== 'pagefind') out.push(...htmlFiles(full));
25
+ } else if (entry.name.endsWith('.html')) out.push(full);
26
+ }
27
+ return out;
28
+ }
29
+
30
+ /** Paths (relative to `distDir`, with forward slashes) of writedocs pages
31
+ * with no stylesheet. */
32
+ export function pagesWithoutStyles(distDir, { basePath = '' } = {}) {
33
+ const STYLES = stylesPattern(basePath);
34
+ return htmlFiles(distDir)
35
+ .filter((file) => {
36
+ const html = fs.readFileSync(file, 'utf8');
37
+ return MARKER.test(html) && !STYLES.test(html);
38
+ })
39
+ .map((file) => path.relative(distDir, file).split(path.sep).join('/'))
40
+ .sort();
41
+ }
package/src/cli/dev.js CHANGED
@@ -9,6 +9,22 @@ import { runningPreview, writeLock, removeLock } from './dev-lock.js';
9
9
  import { showUpdateNotice } from './update-check.js';
10
10
  import { shouldOpenBrowser, openBrowser } from './open-browser.js';
11
11
  import { watchPageList } from './page-list-watch.js';
12
+ import { readConfigText } from '../lib/config-file.js';
13
+ import { normalizeBasePath } from '../lib/base-path.js';
14
+
15
+ /** The preview's address for the server's own (`http://localhost:4321/`):
16
+ * under writedocs.json's `basePath` when it has one - the site is served
17
+ * at /docs/ then, and / is Astro's "not here" page. Read when the server
18
+ * is ready, so it follows the file. */
19
+ export function previewAddress(serverUrl, configText) {
20
+ let basePath = '';
21
+ try {
22
+ basePath = normalizeBasePath(JSON.parse(configText).basePath);
23
+ } catch {
24
+ // An unreadable writedocs.json stops the preview elsewhere.
25
+ }
26
+ return basePath ? new URL(`${basePath.slice(1)}/`, serverUrl).href : serverUrl;
27
+ }
12
28
 
13
29
  // The same problem tends to arrive more than once in a row - Vite and
14
30
  // Astro each log a failed page, and a page compiles for more than one
@@ -96,9 +112,10 @@ export async function runDev({ contentDir, packageRoot, port, verbose = false, o
96
112
  case 'ready': {
97
113
  ready = true;
98
114
  const [local] = event.urls?.local ?? [];
99
- writeLock(packageRoot, { contentDir, url: local ?? null });
100
115
  const wanted = Number(port ?? 4321);
101
116
  const actual = local ? Number(new URL(local).port) : wanted;
117
+ const address = previewAddress(local ?? `http://localhost:${wanted}/`, readConfigText(contentDir));
118
+ writeLock(packageRoot, { contentDir, url: address });
102
119
  currentPort = actual;
103
120
  // Pages changed while it was starting: restart now that it's up.
104
121
  if (restartPending) {
@@ -114,7 +131,7 @@ export async function runDev({ contentDir, packageRoot, port, verbose = false, o
114
131
  }
115
132
  starting.succeed(`Preview ready ${color.dim(`in ${duration(Date.now() - started)}`)}`);
116
133
  log.line();
117
- log.line(` ${color.bold('Local:')} ${color.cyan(local ?? `http://localhost:${wanted}/`)}`);
134
+ log.line(` ${color.bold('Local:')} ${color.cyan(address)}`);
118
135
  if (actual !== wanted) log.line(color.dim(` Port ${wanted} was in use, so the preview is on ${actual}.`));
119
136
  log.line();
120
137
  log.line(color.dim(' Edit any page and the preview updates. Press Ctrl+C to stop.'));
@@ -126,7 +143,7 @@ export async function runDev({ contentDir, packageRoot, port, verbose = false, o
126
143
  // not again if Astro restarts the server.
127
144
  if (!browserOpened && shouldOpenBrowser({ open })) {
128
145
  browserOpened = true;
129
- openBrowser(local ?? `http://localhost:${wanted}/`);
146
+ openBrowser(address);
130
147
  }
131
148
  return;
132
149
  }
@@ -162,7 +179,7 @@ export async function runDev({ contentDir, packageRoot, port, verbose = false, o
162
179
  once(`404\n${request.url}`, () => log.warn(`${color.bold(request.url)} No page at this address (404).`));
163
180
  return;
164
181
  }
165
- const warning = authorWarning(event, contentDir);
182
+ const warning = authorWarning(event, contentDir, { root: packageRoot });
166
183
  if (warning) once(`warn\n${warning}`, () => log.warn(warning));
167
184
  return;
168
185
  }