@writedocs/generator 0.10.14 → 0.10.15

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.
@@ -0,0 +1,54 @@
1
+ // Generated API pages whose address changed between writedocs versions, as
2
+ // redirects from the old address to the new one - so links to a published
3
+ // site keep working after an update.
4
+ //
5
+ // One case so far: an operation with no tag used to be served under
6
+ // "<path>/untagged/<operation>/" and is now at "<path>/<operation>/".
7
+ // generateApiPages() (src/cli/generate-api-pages.js) works the list out
8
+ // from the specs and writes it; astro.config.mjs adds it to the site's
9
+ // redirects (the redirect pages), src/cli/write-redirects-file.js to
10
+ // `_redirects` (real 301s on hosts that read it), and lib/link-check.js
11
+ // counts the old addresses as existing.
12
+ //
13
+ // Plain JavaScript: read by code that runs under plain Node.
14
+ import fs from 'node:fs';
15
+ import path from 'node:path';
16
+ import { writedocsTempDir } from './writedocs-temp-dir.js';
17
+
18
+ const fileFor = (contentDir) => path.join(writedocsTempDir(contentDir), 'openapi', 'moved.json');
19
+
20
+ /** `[{ source: "/api/untagged/get-pets", destination: "/api/get-pets/" }]` -
21
+ * empty when nothing moved, or generateApiPages() hasn't run. */
22
+ export function readMovedApiPages(contentDir) {
23
+ try {
24
+ const list = JSON.parse(fs.readFileSync(fileFor(contentDir), 'utf-8'));
25
+ return Array.isArray(list) ? list.filter((r) => typeof r?.source === 'string' && typeof r?.destination === 'string') : [];
26
+ } catch {
27
+ return [];
28
+ }
29
+ }
30
+
31
+ export function writeMovedApiPages(contentDir, redirects) {
32
+ const file = fileFor(contentDir);
33
+ fs.mkdirSync(path.dirname(file), { recursive: true });
34
+ fs.writeFileSync(file, JSON.stringify(redirects, null, 2));
35
+ }
36
+
37
+ /** The redirects for one spec's untagged operations. `moved` is
38
+ * `[{ oldSlug, newSlug }]` in the spec's order; `taken` holds every slug a
39
+ * page is served at (an operation tagged "untagged" still lives under
40
+ * that folder - its address isn't a redirect's to take). The folder's own
41
+ * address, which used to lead to its first page, goes to that page's new
42
+ * address. */
43
+ export function untaggedRedirects(pathPrefix, moved, taken) {
44
+ const redirects = [];
45
+ const free = (slug) => !taken.has(slug);
46
+ for (const { oldSlug, newSlug } of moved) {
47
+ if (free(oldSlug)) redirects.push({ source: `/${oldSlug}`, destination: `/${newSlug}/` });
48
+ }
49
+ const folder = `${pathPrefix}/untagged`;
50
+ if (moved.length && free(folder) && ![...taken].some((slug) => slug.startsWith(`${folder}/`))) {
51
+ redirects.push({ source: `/${folder}`, destination: `/${moved[0].newSlug}/` });
52
+ }
53
+ return redirects;
54
+ }
@@ -0,0 +1,61 @@
1
+ // Two build steps around the files a project publishes as they are (see
2
+ // lib/project-files.js for which):
3
+ //
4
+ // publishProjectFiles() - copies each one into the build output at its own
5
+ // path. Never over a file that's already there: a page the build
6
+ // rendered, or the same address in public/, wins. It has to come before
7
+ // the sitemap integration in astro.config.mjs's `integrations`, so a
8
+ // project's own sitemap.xml is in place when singleSitemapFile() decides
9
+ // whether to write the generated one there.
10
+ // generatedRobotsTxt() - writes robots.txt when the project didn't bring
11
+ // one (lib/robots-txt.js). After the sitemap integration, so it can name
12
+ // the sitemap file the build ended up with.
13
+ //
14
+ // `writedocs dev` serves the same files straight from the project
15
+ // (lib/styles-asset-integration.js); it has no generated robots.txt.
16
+ import fs from 'node:fs';
17
+ import path from 'node:path';
18
+ import { fileURLToPath } from 'node:url';
19
+ import { findPublishedFiles, readSpecPaths } from './project-files.js';
20
+ import { robotsTxt } from './robots-txt.js';
21
+ import { isNoindex } from './seo-tags.js';
22
+ import { report } from './cli-report.js';
23
+
24
+ export function publishProjectFiles(contentDir) {
25
+ return {
26
+ name: 'writedocs-publish-project-files',
27
+ hooks: {
28
+ 'astro:build:done': ({ dir }) => {
29
+ const outDir = fileURLToPath(dir);
30
+ let copied = 0;
31
+ for (const rel of findPublishedFiles(contentDir, { specs: readSpecPaths(contentDir) })) {
32
+ const segments = rel.split('/');
33
+ const outPath = path.join(outDir, ...segments);
34
+ if (fs.existsSync(outPath)) continue;
35
+ fs.mkdirSync(path.dirname(outPath), { recursive: true });
36
+ fs.copyFileSync(path.join(contentDir, ...segments), outPath);
37
+ copied += 1;
38
+ }
39
+ report('debug', `Published ${copied} project file(s) as they are.`);
40
+ },
41
+ },
42
+ };
43
+ }
44
+
45
+ export function generatedRobotsTxt({ siteUrl, seo }) {
46
+ return {
47
+ name: 'writedocs-robots-txt',
48
+ hooks: {
49
+ 'astro:build:done': ({ dir }) => {
50
+ const outDir = fileURLToPath(dir);
51
+ const target = path.join(outDir, 'robots.txt');
52
+ if (fs.existsSync(target)) {
53
+ report('debug', 'The project has its own robots.txt - kept as it is.');
54
+ return;
55
+ }
56
+ const sitemap = ['sitemap.xml', 'sitemap-index.xml'].find((name) => fs.existsSync(path.join(outDir, name))) ?? null;
57
+ fs.writeFileSync(target, robotsTxt({ siteUrl, sitemap, noindex: isNoindex(seo) }));
58
+ },
59
+ },
60
+ };
61
+ }
@@ -0,0 +1,126 @@
1
+ // Which of a project's files are published as they are, at their own path:
2
+ // `robots.txt` at the project root is served at /robots.txt,
3
+ // `files/terms.pdf` at /files/terms.pdf - with no `public/` folder to
4
+ // create. (A `public/` folder still works, and wins over a file of the same
5
+ // address outside it.)
6
+ //
7
+ // A file is published when its extension is in PUBLISHED_EXTENSIONS and it
8
+ // isn't part of how the site is built: writedocs.json and other tooling
9
+ // files, an OpenAPI spec the site reads, anything in a dot-folder,
10
+ // `node_modules/` or `dist/`. Pages (.md/.mdx), snippets (.jsx/.tsx) and
11
+ // the project's .css/.js (loaded into every page - findRootAssets(),
12
+ // lib/pages.js) are never published as files: their extensions aren't here.
13
+ //
14
+ // Used by the build (lib/project-files-integration.js copies them into the
15
+ // output), `writedocs dev` (lib/styles-asset-integration.js serves them),
16
+ // and `writedocs broken-links` (a link to one isn't broken).
17
+ //
18
+ // Plain JavaScript with no config.ts import, so scripts/project-files.test.js
19
+ // can run it directly.
20
+ import fs from 'node:fs';
21
+ import path from 'node:path';
22
+ import { EXCLUDED_TOP_LEVEL_DIRS } from './pages.js';
23
+ import { writedocsTempDir } from './writedocs-temp-dir.js';
24
+
25
+ /** Extension -> content type, for every kind of file that's published. */
26
+ export const PUBLISHED_TYPES = {
27
+ // Images and fonts.
28
+ '.svg': 'image/svg+xml',
29
+ '.png': 'image/png',
30
+ '.jpg': 'image/jpeg',
31
+ '.jpeg': 'image/jpeg',
32
+ '.gif': 'image/gif',
33
+ '.webp': 'image/webp',
34
+ '.avif': 'image/avif',
35
+ '.ico': 'image/x-icon',
36
+ '.woff': 'font/woff',
37
+ '.woff2': 'font/woff2',
38
+ '.ttf': 'font/ttf',
39
+ '.otf': 'font/otf',
40
+ // Text and data.
41
+ '.txt': 'text/plain; charset=utf-8',
42
+ '.xml': 'application/xml',
43
+ '.json': 'application/json',
44
+ '.csv': 'text/csv; charset=utf-8',
45
+ '.webmanifest': 'application/manifest+json',
46
+ // Downloads and media.
47
+ '.pdf': 'application/pdf',
48
+ '.zip': 'application/zip',
49
+ '.mp4': 'video/mp4',
50
+ '.webm': 'video/webm',
51
+ '.mov': 'video/quicktime',
52
+ '.mp3': 'audio/mpeg',
53
+ '.wav': 'audio/wav',
54
+ '.ogg': 'audio/ogg',
55
+ };
56
+
57
+ /** Files at the project root that configure the site or its tooling. */
58
+ const ROOT_CONFIG_FILES = new Set([
59
+ 'writedocs.json',
60
+ 'docs.json',
61
+ 'mint.json',
62
+ 'config.json',
63
+ 'package.json',
64
+ 'package-lock.json',
65
+ 'tsconfig.json',
66
+ 'jsconfig.json',
67
+ 'composer.json',
68
+ 'vercel.json',
69
+ 'netlify.json',
70
+ 'wrangler.json',
71
+ // Read by the build, which serves them itself (src/pages/llms*.ts).
72
+ 'llms.txt',
73
+ 'llms-full.txt',
74
+ ]);
75
+
76
+ /** Whether the file at `rel` (a POSIX path from the project root) is
77
+ * published. `specs` holds the OpenAPI specs the site reads, as paths of
78
+ * the same form. */
79
+ export function isPublishedFile(rel, { specs = new Set() } = {}) {
80
+ const parts = rel.split('/');
81
+ if (parts.some((part) => part === '' || part === '.' || part === '..' || part.startsWith('.'))) return false;
82
+ if (EXCLUDED_TOP_LEVEL_DIRS.has(parts[0])) return false;
83
+ const name = parts[parts.length - 1].toLowerCase();
84
+ if (!Object.prototype.hasOwnProperty.call(PUBLISHED_TYPES, path.posix.extname(name))) return false;
85
+ if (parts.length === 1 && ROOT_CONFIG_FILES.has(name)) return false;
86
+ if (specs.has(rel)) return false;
87
+ return true;
88
+ }
89
+
90
+ /** Every published file in the project, as POSIX paths from its root,
91
+ * sorted. */
92
+ export function findPublishedFiles(contentDir, options = {}) {
93
+ const found = [];
94
+ const walk = (dir, relBase) => {
95
+ let entries;
96
+ try {
97
+ entries = fs.readdirSync(dir, { withFileTypes: true });
98
+ } catch {
99
+ return;
100
+ }
101
+ for (const entry of entries) {
102
+ if (entry.name.startsWith('.')) continue;
103
+ const rel = relBase ? `${relBase}/${entry.name}` : entry.name;
104
+ if (entry.isDirectory()) {
105
+ if (relBase === '' && EXCLUDED_TOP_LEVEL_DIRS.has(entry.name)) continue;
106
+ walk(path.join(dir, entry.name), rel);
107
+ } else if (entry.isFile() && isPublishedFile(rel, options)) {
108
+ found.push(rel);
109
+ }
110
+ }
111
+ };
112
+ walk(contentDir, '');
113
+ return found.sort();
114
+ }
115
+
116
+ /** The OpenAPI specs the site reads: generateApiPages() (src/cli/
117
+ * generate-api-pages.js) lists them before each build and preview. An
118
+ * empty set when it hasn't run. */
119
+ export function readSpecPaths(contentDir) {
120
+ try {
121
+ const list = JSON.parse(fs.readFileSync(path.join(writedocsTempDir(contentDir), 'openapi', 'specs.json'), 'utf-8'));
122
+ return new Set(Array.isArray(list) ? list : []);
123
+ } catch {
124
+ return new Set();
125
+ }
126
+ }
@@ -0,0 +1,71 @@
1
+ // How content images load. For every image a page's Markdown or MDX writes -
2
+ // `![alt](/a.png)`, `<img src="/a.png">`, `<Image src="/a.png">`:
3
+ //
4
+ // - `loading="lazy"`: the browser fetches it when the reader gets near
5
+ // it, not with the page. The first image of a page is left alone - it's
6
+ // usually at the top, where waiting would make the page look slower.
7
+ // - `decoding="async"`: decoding it doesn't hold up the text.
8
+ // - `width` and `height`, read from the file: the browser keeps the
9
+ // image's place before it arrives, so the text below doesn't jump
10
+ // (layout shift). With them goes `data-wd-sized`, which base.css uses
11
+ // to keep the height following the width (`height: auto`) - without
12
+ // that, an image narrower than its file would be stretched.
13
+ //
14
+ // What the author wrote always wins: an image with its own `loading`,
15
+ // `width` or `height` keeps them, and gets no size from here.
16
+ //
17
+ // `<Image>` reads its own files' sizes (it may have two, light and dark -
18
+ // Image.astro); all it gets from here is `loading="eager"` when it's the
19
+ // page's first image. Sizes are only known for files in the project
20
+ // (addresses starting with "/"); a relative Markdown image is Astro's own
21
+ // to process, and an image on another site only gets the two loading hints.
22
+ import { imageFileFor, imageSize } from './image-size.js';
23
+
24
+ const isJsx = (node) => node.type === 'mdxJsxFlowElement' || node.type === 'mdxJsxTextElement';
25
+
26
+ /** A JSX attribute's value when it's a plain string; undefined when the
27
+ * attribute is absent, null when it's an expression (`src={logo}`). */
28
+ function jsxAttribute(node, name) {
29
+ const attribute = node.attributes?.find((a) => a.type === 'mdxJsxAttribute' && a.name === name);
30
+ if (!attribute) return undefined;
31
+ return typeof attribute.value === 'string' ? attribute.value : null;
32
+ }
33
+
34
+ const setJsx = (node, name, value) => node.attributes.push({ type: 'mdxJsxAttribute', name, value: String(value) });
35
+
36
+ export function rehypeImageLoading({ contentDir } = {}) {
37
+ return (tree) => {
38
+ let seen = 0;
39
+ const visit = (node) => {
40
+ if (node.type === 'element' && node.tagName === 'img') {
41
+ const first = seen++ === 0;
42
+ const p = (node.properties ??= {});
43
+ if (p.loading === undefined && !first) p.loading = 'lazy';
44
+ if (p.decoding === undefined) p.decoding = 'async';
45
+ if (p.width === undefined && p.height === undefined && contentDir) {
46
+ const file = imageFileFor(p.src, contentDir);
47
+ const size = file && imageSize(file);
48
+ if (size) Object.assign(p, { width: size.width, height: size.height, 'data-wd-sized': '' });
49
+ }
50
+ } else if (isJsx(node) && node.name === 'img') {
51
+ const first = seen++ === 0;
52
+ if (jsxAttribute(node, 'loading') === undefined && !first) setJsx(node, 'loading', 'lazy');
53
+ if (jsxAttribute(node, 'decoding') === undefined) setJsx(node, 'decoding', 'async');
54
+ if (jsxAttribute(node, 'width') === undefined && jsxAttribute(node, 'height') === undefined && contentDir) {
55
+ const file = imageFileFor(jsxAttribute(node, 'src'), contentDir);
56
+ const size = file && imageSize(file);
57
+ if (size) {
58
+ setJsx(node, 'width', size.width);
59
+ setJsx(node, 'height', size.height);
60
+ setJsx(node, 'data-wd-sized', '');
61
+ }
62
+ }
63
+ } else if (isJsx(node) && node.name === 'Image') {
64
+ const first = seen++ === 0;
65
+ if (first && jsxAttribute(node, 'loading') === undefined) setJsx(node, 'loading', 'eager');
66
+ }
67
+ if (Array.isArray(node.children)) node.children.forEach(visit);
68
+ };
69
+ visit(tree);
70
+ };
71
+ }
@@ -0,0 +1,16 @@
1
+ // The robots.txt a build writes when the project has none of its own
2
+ // (lib/project-files-integration.js). Plain JavaScript, for
3
+ // scripts/robots-txt.test.js.
4
+
5
+ /** `siteUrl`: the site's origin, or null without a `domain`.
6
+ * `sitemap`: the sitemap's file name in the build ("sitemap.xml",
7
+ * "sitemap-index.xml"), or null when there's none.
8
+ * `noindex`: the whole site is kept out of search engines (writedocs.json's
9
+ * `seo.noindex`, or a `seo.robots` with "noindex") - crawlers are then
10
+ * asked to stay out, and no sitemap is advertised. */
11
+ export function robotsTxt({ siteUrl = null, sitemap = null, noindex = false } = {}) {
12
+ if (noindex) return ['User-agent: *', 'Disallow: /', ''].join('\n');
13
+ const lines = ['User-agent: *', 'Allow: /'];
14
+ if (siteUrl && sitemap) lines.push('', `Sitemap: ${siteUrl}/${sitemap}`);
15
+ return `${lines.join('\n')}\n`;
16
+ }
@@ -0,0 +1,137 @@
1
+ // What a page's <head> says to search engines and link previews: the
2
+ // <title>, the canonical link, and every <meta> tag - built here from the
3
+ // page's title and description, the site's and the page's `seo`
4
+ // (seoFieldsSchema, lib/config-schema.ts), and the site's address.
5
+ // BaseLayout.astro renders the result as it is.
6
+ //
7
+ // Plain JavaScript with no Astro or config.ts import, so scripts/
8
+ // seo-tags.test.js can run it directly, and astro.config.mjs can use the
9
+ // same rules for the sitemap before any page is rendered.
10
+
11
+ /** Meta tags written as `<meta property>` (Open Graph and its relatives);
12
+ * every other one is `<meta name>`. */
13
+ const PROPERTY_PREFIXES = ['og:', 'article:', 'book:', 'profile:', 'music:', 'video:', 'fb:'];
14
+
15
+ /** Whether a `robots` value, or the older `noindex` flag, keeps a page out
16
+ * of search engines. `robots` wins when both are set. */
17
+ export function isNoindex(seo) {
18
+ if (!seo) return false;
19
+ if (typeof seo.robots === 'string') return /\bnoindex\b|\bnone\b/i.test(seo.robots);
20
+ return seo.noindex === true;
21
+ }
22
+
23
+ /** A page's frontmatter as gray-matter read it - before the schema folds
24
+ * Mintlify's top-level `noindex`/`robots` into `seo`, and marks a `hidden`
25
+ * page noindex. Used where pages aren't loaded yet (astro.config.mjs). */
26
+ export function frontmatterNoindex(data) {
27
+ const robots = data?.seo?.robots ?? data?.robots;
28
+ if (typeof robots === 'string') return isNoindex({ robots });
29
+ return (data?.seo?.noindex ?? data?.noindex ?? data?.hidden === true) === true;
30
+ }
31
+
32
+ function absoluteUrl(siteUrl, value) {
33
+ if (/^https?:\/\//i.test(value)) return value;
34
+ if (!siteUrl) return value;
35
+ return `${siteUrl}${value.startsWith('/') ? '' : '/'}${value}`;
36
+ }
37
+
38
+ /** A page's canonical URL: its own address on the site's domain, or
39
+ * `canonical` - a full URL, or a path on the same domain. Null when there's
40
+ * no full URL to give (no `domain`, and `canonical` is a path). */
41
+ export function canonicalUrl(siteUrl, pagePath, canonical) {
42
+ if (canonical) {
43
+ if (/^https?:\/\//i.test(canonical)) return canonical;
44
+ return siteUrl ? absoluteUrl(siteUrl, canonical) : null;
45
+ }
46
+ return siteUrl ? `${siteUrl}${pagePath}` : null;
47
+ }
48
+
49
+ const samePath = (a, b) => a.replace(/^\/+|\/+$/g, '').toLowerCase() === b.replace(/^\/+|\/+$/g, '').toLowerCase();
50
+
51
+ /** Whether `canonical` names another address than the page's own - such a
52
+ * page is left out of sitemap.xml, which lists canonical addresses only. */
53
+ export function canonicalIsElsewhere(siteUrl, pagePath, canonical) {
54
+ if (!canonical) return false;
55
+ if (/^https?:\/\//i.test(canonical)) {
56
+ if (!siteUrl) return true;
57
+ let url;
58
+ try {
59
+ url = new URL(canonical);
60
+ } catch {
61
+ return false;
62
+ }
63
+ return url.origin.toLowerCase() !== new URL(siteUrl).origin.toLowerCase() || !samePath(url.pathname, pagePath);
64
+ }
65
+ return !samePath(canonical, pagePath);
66
+ }
67
+
68
+ /** The `<link rel="alternate" hreflang>` set for a page: one per language
69
+ * it exists in (its own included - each page of the set has to list all
70
+ * of them, itself too), then `x-default`, the first language, for a
71
+ * reader whose language is none of them. `alternates` is
72
+ * `[{ lang, href }]` with site paths. Empty without a `domain` (the
73
+ * links must be full URLs) or with fewer than two languages. */
74
+ export function hreflangLinks(siteUrl, alternates = []) {
75
+ if (!siteUrl || alternates.length < 2) return [];
76
+ const links = alternates.map(({ lang, href }) => ({ hreflang: lang, href: absoluteUrl(siteUrl, href) }));
77
+ return [...links, { hreflang: 'x-default', href: links[0].href }];
78
+ }
79
+
80
+ /** The <title>: `seo.title` exactly as written, or "Page title · Site name"
81
+ * - the site name once when the page's title is the site's name. */
82
+ export function documentTitle(title, siteName, seoTitle) {
83
+ if (seoTitle && seoTitle.trim()) return seoTitle.trim();
84
+ if (!siteName || title.trim().toLowerCase() === siteName.trim().toLowerCase()) return title;
85
+ return `${title} · ${siteName}`;
86
+ }
87
+
88
+ /** Everything BaseLayout.astro writes for search engines and link previews.
89
+ * `seo` is the site's `seo` with the page's own merged over it (mergeSeo()).
90
+ * Returns `{ title, canonical, metas }`, each meta as
91
+ * `{ attr: 'name' | 'property', key, content }`, in the order they're
92
+ * written. An entry of `seo.metatags` replaces the tag of the same name,
93
+ * or is added after the others. */
94
+ export function seoHead({ title, siteName, description, siteDescription, seo = {}, siteUrl = null, path = '/' }) {
95
+ const shareTitle = seo.title?.trim() || title;
96
+ const metaDescription = seo.description?.trim() || description || siteDescription;
97
+ const canonical = canonicalUrl(siteUrl, path, seo.canonical);
98
+ const custom = seo.metatags ?? {};
99
+ const image = seo.ogImage ? absoluteUrl(siteUrl, seo.ogImage) : undefined;
100
+ // The large card needs a picture - from `ogImage`, or a tag set by hand.
101
+ const hasImage = Boolean(image || custom['og:image'] || custom['twitter:image']);
102
+ const robots = typeof seo.robots === 'string' && seo.robots.trim() ? seo.robots.trim() : seo.noindex ? 'noindex, nofollow' : undefined;
103
+
104
+ const tags = new Map();
105
+ const set = (key, content) => {
106
+ if (content === undefined || content === null || content === '') return;
107
+ tags.set(key, String(content));
108
+ };
109
+ set('description', metaDescription);
110
+ if (seo.keywords?.length) set('keywords', seo.keywords.join(', '));
111
+ set('robots', robots);
112
+ set('og:title', shareTitle);
113
+ set('og:description', metaDescription);
114
+ set('og:type', seo.ogType ?? 'website');
115
+ set('og:site_name', siteName);
116
+ set('og:url', canonical);
117
+ set('og:image', image);
118
+ set('twitter:card', seo.twitterCard ?? (hasImage ? 'summary_large_image' : 'summary'));
119
+ set('twitter:title', shareTitle);
120
+ set('twitter:description', metaDescription);
121
+ set('twitter:image', image);
122
+ for (const [key, value] of Object.entries(custom)) {
123
+ if (typeof value !== 'string' || !value.trim()) continue;
124
+ // A picture's address has to be a full URL for the sites that read it.
125
+ set(key, /(^|:)image$/.test(key) ? absoluteUrl(siteUrl, value) : value);
126
+ }
127
+
128
+ return {
129
+ title: documentTitle(title, siteName, seo.title),
130
+ canonical,
131
+ metas: [...tags].map(([key, content]) => ({
132
+ attr: PROPERTY_PREFIXES.some((prefix) => key.startsWith(prefix)) ? 'property' : 'name',
133
+ key,
134
+ content,
135
+ })),
136
+ };
137
+ }
@@ -57,6 +57,7 @@ import path from 'node:path';
57
57
  import { fileURLToPath } from 'node:url';
58
58
  import { loadDocsConfig, collectConfiguredAssetPaths } from './config.ts';
59
59
  import { resolveOutsidePublic } from './asset-path.js';
60
+ import { PUBLISHED_TYPES, isPublishedFile, readSpecPaths } from './project-files.js';
60
61
 
61
62
  const MIME_BY_EXTENSION = {
62
63
  '.svg': 'image/svg+xml',
@@ -74,7 +75,23 @@ const MIME_BY_EXTENSION = {
74
75
  };
75
76
 
76
77
  function mimeFor(filePath) {
77
- return MIME_BY_EXTENSION[path.extname(filePath).toLowerCase()] || 'application/octet-stream';
78
+ const extension = path.extname(filePath).toLowerCase();
79
+ return MIME_BY_EXTENSION[extension] || PUBLISHED_TYPES[extension] || 'application/octet-stream';
80
+ }
81
+
82
+ /** `writedocs dev`: a request for one of the project's published files that
83
+ * isn't an image or a font - robots.txt, a PDF, a JSON file (see
84
+ * lib/project-files.js; the build copies them, publishProjectFiles()).
85
+ * Images and fonts keep the wider rule above them: whatever path a page
86
+ * names is tried. */
87
+ function isPublishedFileRequest(urlPath, contentDir) {
88
+ let rel;
89
+ try {
90
+ rel = decodeURIComponent(urlPath).replace(/^\/+/, '');
91
+ } catch {
92
+ return false;
93
+ }
94
+ return isPublishedFile(rel, { specs: readSpecPaths(contentDir) });
78
95
  }
79
96
 
80
97
 
@@ -190,8 +207,9 @@ export function stylesAssetFallback(contentDir) {
190
207
  'astro:server:setup': ({ server }) => {
191
208
  server.middlewares.use((req, res, next) => {
192
209
  if (!req.url) return next();
193
- const urlPath = req.url.split('?')[0];
194
- if (!looksLikeAssetPath(urlPath)) return next();
210
+ const [urlPath, query = ''] = req.url.split('?');
211
+ // A request with a query is Vite's own (a module: `data.json?import`).
212
+ if (!looksLikeAssetPath(urlPath) && (query || !isPublishedFileRequest(urlPath, contentDir))) return next();
195
213
  if (fs.existsSync(publicPathFor(urlPath, contentDir))) return next(); // real public/ file - Vite's own static serving already handles it, don't shadow
196
214
  const resolved = resolveOutsidePublic(urlPath, contentDir);
197
215
  if (!resolved) return next();
@@ -24,6 +24,7 @@ import {
24
24
  } from "../lib/config";
25
25
  import { writedocsTempDir } from "../lib/writedocs-temp-dir.js";
26
26
  import { parseOpenApiRef } from "../lib/openapi-ref.js";
27
+ import { languageAlternates } from "../lib/item-pages.js";
27
28
  import BaseLayout from "../layout/BaseLayout.astro";
28
29
  import Sidebar from "../layout/components/Sidebar.astro";
29
30
  import TableOfContents from "../layout/components/TableOfContents.astro";
@@ -483,6 +484,21 @@ const globalDropdowns = buildGlobalDropdowns(
483
484
  // frontmatter-slug-override-aware routing logic.
484
485
  const pageSeo = mergeSeo(config.seo, entry.data.seo);
485
486
  const currentPath = hrefForSlug(currentFileId);
487
+ // This page in each language, for hreflang (languageAlternates() in
488
+ // lib/item-pages.js) - a hidden page belongs to no language level.
489
+ const alternates = isHidden
490
+ ? []
491
+ : languageAlternates(activeSection.path, currentFileId, activeSection.pages, landing !== undefined).map((a) => ({
492
+ lang: a.lang,
493
+ href: hrefForSlug(a.slug),
494
+ }));
495
+ // The trail for the page's structured data (lib/json-ld.js): home, the
496
+ // groups above the page that have a page of their own, the page.
497
+ const structuredTrail = [
498
+ { name: config.name, href: "/" },
499
+ ...breadcrumbs.filter((crumb) => crumb.href).map((crumb) => ({ name: crumb.label, href: crumb.href as string })),
500
+ ...(currentPath === "/" ? [] : [{ name: entry.data.title, href: currentPath }]),
501
+ ];
486
502
 
487
503
  // Page mode (content.config.ts's docsSchema `mode` field, defaulted to
488
504
  // 'default' there so this is never actually undefined) - see
@@ -588,6 +604,9 @@ const components = {
588
604
  globalDropdowns={globalDropdowns}
589
605
  mode={pageMode}
590
606
  lang={pageLang}
607
+ alternates={alternates}
608
+ breadcrumbs={structuredTrail}
609
+ isApi={Boolean(entry.data.openapi)}
591
610
  >
592
611
  {showSidebar && <Sidebar slot="sidebar" navTree={navTree} hrefForSlug={hrefForSlug} currentSlug={currentFileId} switchers={sidebarSwitchers} />}
593
612
  {
@@ -0,0 +1,62 @@
1
+ // The consent banner's behavior (ConsentBanner.astro) - shows it until the
2
+ // reader answers, stores the answer through window.wdConsent (defined in
3
+ // <head> by consentLoaderScript() in lib/consent.js, which also loads the
4
+ // analytics once the answer is "granted"), and opens it again from any link
5
+ // to #cookie-settings, so a reader can change their mind.
6
+ //
7
+ // Runs on every page load, client-side navigations included: the banner is
8
+ // part of <body>, which Astro's router replaces with the new page's - a new,
9
+ // hidden banner each time.
10
+
11
+ type Consent = { get(): 'granted' | 'denied' | null; set(value: 'granted' | 'denied'): void };
12
+
13
+ const SETTINGS_HASH = '#cookie-settings';
14
+
15
+ function show(banner: HTMLElement) {
16
+ banner.hidden = false;
17
+ // The strip covers the end of the page; this lets the footer scroll clear of it.
18
+ document.body.style.paddingBottom = `${banner.offsetHeight}px`;
19
+ }
20
+
21
+ function hide(banner: HTMLElement) {
22
+ banner.hidden = true;
23
+ document.body.style.paddingBottom = '';
24
+ }
25
+
26
+ let listening = false;
27
+
28
+ export function initConsent(root: Document) {
29
+ const banner = root.getElementById('wd-consent');
30
+ const consent = (window as unknown as { wdConsent?: Consent }).wdConsent;
31
+ if (!banner || !consent) return;
32
+
33
+ if (!banner.dataset.wdInit) {
34
+ banner.dataset.wdInit = 'true';
35
+ banner.querySelectorAll<HTMLButtonElement>('[data-consent]').forEach((button) => {
36
+ button.addEventListener('click', () => {
37
+ hide(banner);
38
+ // Answered: the address stops asking for the banner, so a reload
39
+ // (declining after accepting causes one) doesn't open it again.
40
+ if (location.hash === SETTINGS_HASH) history.replaceState(history.state, '', location.pathname + location.search);
41
+ consent.set(button.dataset.consent === 'granted' ? 'granted' : 'denied');
42
+ });
43
+ });
44
+ }
45
+
46
+ if (consent.get() === null || location.hash === SETTINGS_HASH) show(banner);
47
+ else hide(banner);
48
+
49
+ // One listener for the whole visit - it looks the banner up when clicked,
50
+ // since each navigation brings a new one.
51
+ if (listening) return;
52
+ listening = true;
53
+ document.addEventListener('click', (event) => {
54
+ const link = (event.target as Element | null)?.closest?.(`a[href$="${SETTINGS_HASH}"]`);
55
+ if (!link) return;
56
+ const current = document.getElementById('wd-consent');
57
+ if (!current) return;
58
+ event.preventDefault();
59
+ show(current);
60
+ current.querySelector<HTMLButtonElement>('[data-consent]')?.focus();
61
+ });
62
+ }