@writedocs/generator 0.10.19 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/astro.config.mjs +32 -8
  2. package/package.json +96 -93
  3. package/src/cli/base-path-layout.js +44 -0
  4. package/src/cli/build.js +177 -168
  5. package/src/cli/check-built-styles.js +41 -33
  6. package/src/cli/dev.js +261 -244
  7. package/src/cli/generate-api-pages.js +9 -5
  8. package/src/cli/page-list-watch.js +69 -66
  9. package/src/cli/run-pagefind.js +154 -148
  10. package/src/cli/write-mcp-files.js +103 -96
  11. package/src/cli/write-redirects-file.js +25 -8
  12. package/src/components/AppIcon.astro +51 -50
  13. package/src/components/Card.astro +193 -192
  14. package/src/components/CopyPageMenu.astro +374 -370
  15. package/src/components/Hint.astro +188 -187
  16. package/src/components/Icon.astro +72 -71
  17. package/src/components/Image.astro +165 -164
  18. package/src/components/Tile.astro +67 -66
  19. package/src/components/Video.astro +137 -136
  20. package/src/layout/BaseLayout.astro +21 -12
  21. package/src/layout/components/AnalyticsScripts.astro +6 -2
  22. package/src/layout/components/Breadcrumbs.astro +98 -97
  23. package/src/layout/components/ConsentBanner.astro +119 -118
  24. package/src/layout/components/MobileMenu.astro +229 -228
  25. package/src/layout/components/NavTree.astro +393 -392
  26. package/src/layout/components/Sidebar.astro +232 -231
  27. package/src/layout/components/SiteFooter.astro +87 -86
  28. package/src/layout/components/TopBar.astro +386 -385
  29. package/src/lib/agent-markdown.js +164 -162
  30. package/src/lib/asset-dimensions.js +89 -0
  31. package/src/lib/base-path.js +90 -0
  32. package/src/lib/config-schema.js +10 -0
  33. package/src/lib/config-schema.ts +17 -0
  34. package/src/lib/config.ts +1314 -1289
  35. package/src/lib/consent.js +108 -102
  36. package/src/lib/image-size.js +152 -140
  37. package/src/lib/json-schema-descriptions.js +1 -0
  38. package/src/lib/link-check.js +42 -4
  39. package/src/lib/llms-index.ts +90 -88
  40. package/src/lib/mcp-dev-integration.js +65 -60
  41. package/src/lib/mcp-index.ts +102 -101
  42. package/src/lib/pages.js +312 -304
  43. package/src/lib/project-files-integration.js +116 -61
  44. package/src/lib/project-files.js +137 -126
  45. package/src/lib/project-ignore.js +46 -0
  46. package/src/lib/rehype-base-path.js +62 -0
  47. package/src/lib/rehype-image-loading.js +71 -71
  48. package/src/lib/robots-txt.js +21 -16
  49. package/src/lib/seo-tags.js +155 -140
  50. package/src/lib/site-base.ts +27 -0
  51. package/src/lib/styles-asset-integration.js +58 -12
  52. package/src/lib/wdignore-cases.json +195 -0
  53. package/src/lib/wdignore.js +177 -0
  54. package/src/pages/404.astro +63 -62
  55. package/src/pages/[...slug].astro +1604 -1597
  56. package/src/pages/[...slug].md.ts +93 -93
  57. package/src/pages/llms-full.txt.ts +88 -86
  58. package/src/scripts/search.ts +241 -237
  59. package/writedocs.schema.json +6 -0
@@ -1,71 +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
- }
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, contentDir);
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, contentDir);
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
+ }
@@ -1,16 +1,21 @@
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
- }
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
+ import { withBase } from './base-path.js';
5
+
6
+ /** `siteUrl`: the site's URL ({domain}{basePath}), or null without a `domain`.
7
+ * `sitemap`: the sitemap's file name in the build ("sitemap.xml",
8
+ * "sitemap-index.xml"), or null when there's none.
9
+ * `noindex`: the whole site is kept out of search engines (writedocs.json's
10
+ * `seo.noindex`, or a `seo.robots` with "noindex") - crawlers are then
11
+ * asked to stay out, and no sitemap is advertised.
12
+ * `basePath`: the site's base ("/docs", lib/base-path.js) - the rules then
13
+ * cover the site's own path, ready to copy into the robots.txt at the root
14
+ * of the domain (crawlers only read that one, not /docs/robots.txt). */
15
+ export function robotsTxt({ siteUrl = null, sitemap = null, noindex = false, basePath = '' } = {}) {
16
+ const root = withBase(basePath, '/');
17
+ if (noindex) return ['User-agent: *', `Disallow: ${root}`, ''].join('\n');
18
+ const lines = ['User-agent: *', `Allow: ${root}`];
19
+ if (siteUrl && sitemap) lines.push('', `Sitemap: ${siteUrl}/${sitemap}`);
20
+ return `${lines.join('\n')}\n`;
21
+ }
@@ -1,140 +1,155 @@
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
- // The picture in a link preview: the page's or the site's `ogImage` -
100
- // or, set by [...slug].astro when there is neither, the card generated
101
- // for the page (lib/og-image.js).
102
- const image = seo.ogImage ? absoluteUrl(siteUrl, seo.ogImage) : undefined;
103
- // The large card needs a picture - that one, or a tag set by hand.
104
- const hasImage = Boolean(image || custom['og:image'] || custom['twitter:image']);
105
- const robots = typeof seo.robots === 'string' && seo.robots.trim() ? seo.robots.trim() : seo.noindex ? 'noindex, nofollow' : undefined;
106
-
107
- const tags = new Map();
108
- const set = (key, content) => {
109
- if (content === undefined || content === null || content === '') return;
110
- tags.set(key, String(content));
111
- };
112
- set('description', metaDescription);
113
- if (seo.keywords?.length) set('keywords', seo.keywords.join(', '));
114
- set('robots', robots);
115
- set('og:title', shareTitle);
116
- set('og:description', metaDescription);
117
- set('og:type', seo.ogType ?? 'website');
118
- set('og:site_name', siteName);
119
- set('og:url', canonical);
120
- set('og:image', image);
121
- set('twitter:card', seo.twitterCard ?? (hasImage ? 'summary_large_image' : 'summary'));
122
- set('twitter:title', shareTitle);
123
- set('twitter:description', metaDescription);
124
- set('twitter:image', image);
125
- for (const [key, value] of Object.entries(custom)) {
126
- if (typeof value !== 'string' || !value.trim()) continue;
127
- // A picture's address has to be a full URL for the sites that read it.
128
- set(key, /(^|:)image$/.test(key) ? absoluteUrl(siteUrl, value) : value);
129
- }
130
-
131
- return {
132
- title: documentTitle(title, siteName, seo.title),
133
- canonical,
134
- metas: [...tags].map(([key, content]) => ({
135
- attr: PROPERTY_PREFIXES.some((prefix) => key.startsWith(prefix)) ? 'property' : 'name',
136
- key,
137
- content,
138
- })),
139
- };
140
- }
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
+ // `siteUrl` is the site's URL - {domain}{basePath}, see resolveSiteUrl() in
12
+ // lib/config.ts - and a page's `path` is its address in the site, without
13
+ // the base ("/guides/a/").
14
+ import { withBase } from './base-path.js';
15
+
16
+ /** Meta tags written as `<meta property>` (Open Graph and its relatives);
17
+ * every other one is `<meta name>`. */
18
+ const PROPERTY_PREFIXES = ['og:', 'article:', 'book:', 'profile:', 'music:', 'video:', 'fb:'];
19
+
20
+ /** Whether a `robots` value, or the older `noindex` flag, keeps a page out
21
+ * of search engines. `robots` wins when both are set. */
22
+ export function isNoindex(seo) {
23
+ if (!seo) return false;
24
+ if (typeof seo.robots === 'string') return /\bnoindex\b|\bnone\b/i.test(seo.robots);
25
+ return seo.noindex === true;
26
+ }
27
+
28
+ /** A page's frontmatter as gray-matter read it - before the schema folds
29
+ * Mintlify's top-level `noindex`/`robots` into `seo`, and marks a `hidden`
30
+ * page noindex. Used where pages aren't loaded yet (astro.config.mjs). */
31
+ export function frontmatterNoindex(data) {
32
+ const robots = data?.seo?.robots ?? data?.robots;
33
+ if (typeof robots === 'string') return isNoindex({ robots });
34
+ return (data?.seo?.noindex ?? data?.noindex ?? data?.hidden === true) === true;
35
+ }
36
+
37
+ /** `value` - a full URL or a site address - as a full URL; without a
38
+ * siteUrl, a site address with the site's `base` in front. */
39
+ function absoluteUrl(siteUrl, value, base = '') {
40
+ if (/^https?:\/\//i.test(value)) return value;
41
+ if (!siteUrl) return withBase(base, value);
42
+ return `${siteUrl}${value.startsWith('/') ? '' : '/'}${value}`;
43
+ }
44
+
45
+ /** A page's canonical URL: its own address on the site's domain, or
46
+ * `canonical` - a full URL, or a path on the same domain. Null when there's
47
+ * no full URL to give (no `domain`, and `canonical` is a path). */
48
+ export function canonicalUrl(siteUrl, pagePath, canonical) {
49
+ if (canonical) {
50
+ if (/^https?:\/\//i.test(canonical)) return canonical;
51
+ return siteUrl ? absoluteUrl(siteUrl, canonical) : null;
52
+ }
53
+ return siteUrl ? `${siteUrl}${pagePath}` : null;
54
+ }
55
+
56
+ const samePath = (a, b) => a.replace(/^\/+|\/+$/g, '').toLowerCase() === b.replace(/^\/+|\/+$/g, '').toLowerCase();
57
+
58
+ /** Whether `canonical` names another address than the page's own - such a
59
+ * page is left out of sitemap.xml, which lists canonical addresses only. */
60
+ export function canonicalIsElsewhere(siteUrl, pagePath, canonical) {
61
+ if (!canonical) return false;
62
+ if (/^https?:\/\//i.test(canonical)) {
63
+ if (!siteUrl) return true;
64
+ let url;
65
+ try {
66
+ url = new URL(canonical);
67
+ } catch {
68
+ return false;
69
+ }
70
+ const site = new URL(siteUrl);
71
+ if (url.origin.toLowerCase() !== site.origin.toLowerCase()) return true;
72
+ // The canonical's path, from the site's root - outside the basePath, it's
73
+ // another site's address.
74
+ const root = site.pathname.replace(/\/+$/, '').toLowerCase();
75
+ const pathname = url.pathname.toLowerCase();
76
+ if (root && pathname !== root && !pathname.startsWith(`${root}/`)) return true;
77
+ return !samePath(pathname.slice(root.length), pagePath);
78
+ }
79
+ return !samePath(canonical, pagePath);
80
+ }
81
+
82
+ /** The `<link rel="alternate" hreflang>` set for a page: one per language
83
+ * it exists in (its own included - each page of the set has to list all
84
+ * of them, itself too), then `x-default`, the first language, for a
85
+ * reader whose language is none of them. `alternates` is
86
+ * `[{ lang, href }]` with site paths. Empty without a `domain` (the
87
+ * links must be full URLs) or with fewer than two languages. */
88
+ export function hreflangLinks(siteUrl, alternates = []) {
89
+ if (!siteUrl || alternates.length < 2) return [];
90
+ const links = alternates.map(({ lang, href }) => ({ hreflang: lang, href: absoluteUrl(siteUrl, href) }));
91
+ return [...links, { hreflang: 'x-default', href: links[0].href }];
92
+ }
93
+
94
+ /** The <title>: `seo.title` exactly as written, or "Page title · Site name"
95
+ * - the site name once when the page's title is the site's name. */
96
+ export function documentTitle(title, siteName, seoTitle) {
97
+ if (seoTitle && seoTitle.trim()) return seoTitle.trim();
98
+ if (!siteName || title.trim().toLowerCase() === siteName.trim().toLowerCase()) return title;
99
+ return `${title} · ${siteName}`;
100
+ }
101
+
102
+ /** Everything BaseLayout.astro writes for search engines and link previews.
103
+ * `seo` is the site's `seo` with the page's own merged over it (mergeSeo()).
104
+ * Returns `{ title, canonical, metas }`, each meta as
105
+ * `{ attr: 'name' | 'property', key, content }`, in the order they're
106
+ * written. An entry of `seo.metatags` replaces the tag of the same name,
107
+ * or is added after the others. `base` is the site's basePath ("/docs"),
108
+ * for a picture's address when there's no siteUrl to make it full. */
109
+ export function seoHead({ title, siteName, description, siteDescription, seo = {}, siteUrl = null, path = '/', base = '' }) {
110
+ const shareTitle = seo.title?.trim() || title;
111
+ const metaDescription = seo.description?.trim() || description || siteDescription;
112
+ const canonical = canonicalUrl(siteUrl, path, seo.canonical);
113
+ const custom = seo.metatags ?? {};
114
+ // The picture in a link preview: the page's or the site's `ogImage` -
115
+ // or, set by [...slug].astro when there is neither, the card generated
116
+ // for the page (lib/og-image.js).
117
+ const image = seo.ogImage ? absoluteUrl(siteUrl, seo.ogImage, base) : undefined;
118
+ // The large card needs a picture - that one, or a tag set by hand.
119
+ const hasImage = Boolean(image || custom['og:image'] || custom['twitter:image']);
120
+ const robots = typeof seo.robots === 'string' && seo.robots.trim() ? seo.robots.trim() : seo.noindex ? 'noindex, nofollow' : undefined;
121
+
122
+ const tags = new Map();
123
+ const set = (key, content) => {
124
+ if (content === undefined || content === null || content === '') return;
125
+ tags.set(key, String(content));
126
+ };
127
+ set('description', metaDescription);
128
+ if (seo.keywords?.length) set('keywords', seo.keywords.join(', '));
129
+ set('robots', robots);
130
+ set('og:title', shareTitle);
131
+ set('og:description', metaDescription);
132
+ set('og:type', seo.ogType ?? 'website');
133
+ set('og:site_name', siteName);
134
+ set('og:url', canonical);
135
+ set('og:image', image);
136
+ set('twitter:card', seo.twitterCard ?? (hasImage ? 'summary_large_image' : 'summary'));
137
+ set('twitter:title', shareTitle);
138
+ set('twitter:description', metaDescription);
139
+ set('twitter:image', image);
140
+ for (const [key, value] of Object.entries(custom)) {
141
+ if (typeof value !== 'string' || !value.trim()) continue;
142
+ // A picture's address has to be a full URL for the sites that read it.
143
+ set(key, /(^|:)image$/.test(key) ? absoluteUrl(siteUrl, value, base) : value);
144
+ }
145
+
146
+ return {
147
+ title: documentTitle(title, siteName, seo.title),
148
+ canonical,
149
+ metas: [...tags].map(([key, content]) => ({
150
+ attr: PROPERTY_PREFIXES.some((prefix) => key.startsWith(prefix)) ? 'property' : 'name',
151
+ key,
152
+ content,
153
+ })),
154
+ };
155
+ }
@@ -0,0 +1,27 @@
1
+ // The site's base (writedocs.json `basePath`) for components and page
2
+ // scripts - lib/base-path.js explains the base and which addresses take it.
3
+ // __WD_BASE__ is "" or "/docs", set by astro.config.mjs (vite.define), so
4
+ // the same import works in a component's frontmatter and in a <script>; with
5
+ // no base, siteHref() returns its argument and the built pages don't change.
6
+ //
7
+ // The rule: logic keeps site addresses as they are ("/guides/a/"); the base
8
+ // goes in where the address is written - an href, a src, a url() - with
9
+ // siteHref(). Doing it once there is what keeps an address from getting it
10
+ // twice.
11
+ import { withBase, srcsetWithBase } from './base-path.js';
12
+
13
+ declare const __WD_BASE__: string;
14
+
15
+ /** "" or "/docs". */
16
+ export const BASE: string = __WD_BASE__;
17
+
18
+ /** A site address with the base in front ("/a/" -> "/docs/a/"); anything
19
+ * else - a full URL, "#x", a relative path - as it is. */
20
+ export function siteHref<T extends string | undefined | null>(url: T): T {
21
+ return withBase(BASE, url) as T;
22
+ }
23
+
24
+ /** A `srcset` with the base in front of each site address. */
25
+ export function siteSrcset<T extends string | undefined | null>(srcset: T): T {
26
+ return srcsetWithBase(BASE, srcset) as T;
27
+ }