@writedocs/generator 0.10.14 → 0.10.16

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 (48) hide show
  1. package/astro.config.mjs +610 -572
  2. package/package.json +1 -1
  3. package/src/cli/generate-api-pages.js +418 -384
  4. package/src/cli/write-redirects-file.js +141 -116
  5. package/src/components/Accordion.astro +2 -1
  6. package/src/components/Callout.astro +1 -1
  7. package/src/components/CopyPageMenu.astro +1 -1
  8. package/src/components/Image.astro +19 -3
  9. package/src/components/Parameter.astro +11 -6
  10. package/src/components/Visibility.astro +11 -1
  11. package/src/layout/BaseLayout.astro +896 -831
  12. package/src/layout/components/AnalyticsScripts.astro +45 -77
  13. package/src/layout/components/Breadcrumbs.astro +1 -1
  14. package/src/layout/components/ConsentBanner.astro +118 -0
  15. package/src/layout/components/MobileMenu.astro +3 -2
  16. package/src/layout/components/Sidebar.astro +2 -2
  17. package/src/layout/components/SiteFooter.astro +3 -2
  18. package/src/layout/components/TopBar.astro +3 -2
  19. package/src/layout/styles/base.css +30 -0
  20. package/src/lib/agent-directive.js +47 -0
  21. package/src/lib/agent-markdown.js +22 -2
  22. package/src/lib/components-to-markdown.js +297 -0
  23. package/src/lib/config-schema.js +97 -10
  24. package/src/lib/config-schema.ts +1882 -1768
  25. package/src/lib/consent.js +102 -0
  26. package/src/lib/font-fallback.js +79 -0
  27. package/src/lib/image-size.js +140 -0
  28. package/src/lib/item-pages.js +63 -0
  29. package/src/lib/json-ld.js +127 -0
  30. package/src/lib/json-schema-descriptions.js +226 -212
  31. package/src/lib/last-modified.js +52 -0
  32. package/src/lib/link-check.js +506 -500
  33. package/src/lib/mcp-index.ts +1 -1
  34. package/src/lib/meta-description.js +41 -0
  35. package/src/lib/mintlify-convert.js +605 -603
  36. package/src/lib/moved-api-pages.js +54 -0
  37. package/src/lib/openapi-markdown.ts +16 -6
  38. package/src/lib/project-files-integration.js +61 -0
  39. package/src/lib/project-files.js +126 -0
  40. package/src/lib/rehype-image-loading.js +71 -0
  41. package/src/lib/robots-txt.js +16 -0
  42. package/src/lib/seo-tags.js +137 -0
  43. package/src/lib/styles-asset-integration.js +21 -3
  44. package/src/pages/[...slug].astro +22 -3
  45. package/src/pages/[...slug].md.ts +15 -5
  46. package/src/pages/llms-full.txt.ts +1 -1
  47. package/src/scripts/consent.ts +62 -0
  48. package/writedocs.schema.json +100 -0
@@ -0,0 +1,102 @@
1
+ // The analytics integrations' <script> tags (writedocs.json's
2
+ // `integrations`), and the consent banner that can hold them back.
3
+ //
4
+ // Without `integrations.consent`, AnalyticsScripts.astro writes each tag
5
+ // into <head> and the browser loads them with the page. With it, no tag is
6
+ // written: consentLoaderScript() puts the same list in one small script,
7
+ // which adds the tags only once the reader has accepted - on this visit, or
8
+ // an earlier one (the answer is kept in localStorage). ConsentBanner.astro
9
+ // is the banner; src/scripts/consent.ts wires its buttons.
10
+ //
11
+ // Plain JavaScript with no Astro import, so scripts/consent.test.js can run
12
+ // it directly.
13
+
14
+ /** localStorage key holding the reader's answer: "granted" or "denied". */
15
+ export const CONSENT_STORAGE_KEY = 'wd-consent';
16
+
17
+ export const CONSENT_DEFAULTS = {
18
+ message: 'We use cookies to understand how this site is used and to improve it.',
19
+ acceptLabel: 'Accept',
20
+ declineLabel: 'Decline',
21
+ policyLabel: 'Privacy policy',
22
+ };
23
+
24
+ /** `integrations.consent` as the banner's texts - null when it's off
25
+ * (absent or false). `true` gives the defaults. */
26
+ export function consentOptions(value) {
27
+ if (!value) return null;
28
+ const given = value === true ? {} : value;
29
+ const text = (key) => (typeof given[key] === 'string' && given[key].trim() ? given[key].trim() : CONSENT_DEFAULTS[key]);
30
+ return {
31
+ message: text('message'),
32
+ acceptLabel: text('acceptLabel'),
33
+ declineLabel: text('declineLabel'),
34
+ policyUrl: typeof given.policyUrl === 'string' && given.policyUrl.trim() ? given.policyUrl.trim() : null,
35
+ policyLabel: text('policyLabel'),
36
+ };
37
+ }
38
+
39
+ /** One <script> per entry, in order: `{ src, attrs }` for a file, or
40
+ * `{ content }` for code. `attrs` values are strings, or `true` for a
41
+ * bare attribute (`async`, `defer`).
42
+ *
43
+ * Every snippet is the provider's own install snippet - see
44
+ * docs/dev/docs/integrations.mdx for where each came from. Config values
45
+ * go in through JSON.stringify, so a quote or backslash in one can't break
46
+ * out of the generated script. */
47
+ export function analyticsTags(integrations = {}) {
48
+ const tags = [];
49
+ const { ga4, googleTagManager, plausible, fathom, posthog, umami } = integrations;
50
+ if (ga4) {
51
+ tags.push({ src: `https://www.googletagmanager.com/gtag/js?id=${ga4.measurementId}`, attrs: { async: true } });
52
+ tags.push({
53
+ content: `window.dataLayer=window.dataLayer||[];function gtag(){dataLayer.push(arguments);}gtag('js',new Date());gtag('config',${JSON.stringify(ga4.measurementId)});`,
54
+ });
55
+ }
56
+ if (googleTagManager) {
57
+ // Google's own long-stable snippet: pushes the first 'gtm.js' event and
58
+ // adds the real gtm.js loader.
59
+ tags.push({
60
+ content: `(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src='https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);})(window,document,'script','dataLayer',${JSON.stringify(googleTagManager.containerId)});`,
61
+ });
62
+ }
63
+ if (plausible) tags.push({ src: plausible.src, attrs: { defer: true, 'data-domain': plausible.domain } });
64
+ if (fathom) tags.push({ src: 'https://cdn.usefathom.com/script.js', attrs: { 'data-site': fathom.siteId, defer: true } });
65
+ if (posthog) {
66
+ // PostHog's "array.js" loader, from posthog.com/docs/libraries/js.
67
+ // PostHog revises its minified body now and then - fetch it again and
68
+ // compare before changing it. `defaults` is their dated configuration
69
+ // snapshot; move it on when their docs do.
70
+ tags.push({
71
+ content: `!function(t,e){var o,n,p,r;e.__SV||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split(".");2==o.length&&(t=t[o[0]],e=o[1]),t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}(p=t.createElement("script")).type="text/javascript",p.crossOrigin="anonymous",p.async=!0,p.src=s.api_host.replace(".i.posthog.com","-assets.i.posthog.com")+"/static/array.js",(r=t.getElementsByTagName("script")[0]).parentNode.insertBefore(p,r);var u=e;for(void 0!==a?u=e[a]=[]:a="posthog",u.people=u.people||[],u.toString=function(t){var e="posthog";return"posthog"!==a&&(e+="."+a),t||(e+=" (stub)"),e},u.people.toString=function(){return u.toString(1)+".people (stub)"},o="init capture register register_once register_for_session unregister unregister_for_session getFeatureFlag getFeatureFlagResult isFeatureEnabled reloadFeatureFlags updateEarlyAccessFeatureEnrollment getEarlyAccessFeatures on onFeatureFlags onSessionId getSurveys getActiveMatchingSurveys renderSurvey canRenderSurvey getNextSurveyStep identify setPersonProperties group resetGroups setPersonPropertiesForFlags resetPersonPropertiesForFlags setGroupPropertiesForFlags resetGroupPropertiesForFlags reset get_distinct_id getGroups get_session_id get_session_replay_url alias set_config startSessionRecording stopSessionRecording sessionRecordingStarted captureException loadToolbar get_property getSessionProperty createPersonProfile opt_in_capturing opt_out_capturing has_opted_in_capturing has_opted_out_capturing clear_opt_in_out_capturing debug".split(" "),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]);posthog.init(${JSON.stringify(posthog.apiKey)},{api_host:${JSON.stringify(posthog.apiHost)},defaults:'2026-05-30'});`,
72
+ });
73
+ }
74
+ if (umami) tags.push({ src: umami.src, attrs: { defer: true, 'data-website-id': umami.websiteId } });
75
+ return tags;
76
+ }
77
+
78
+ /** `scripts.head`/`scripts.body` entries marked `consent: true`, as tags. */
79
+ export function scriptTags(entries = []) {
80
+ return entries.map((entry) => (entry.src ? { src: entry.src, attrs: {} } : { content: entry.content }));
81
+ }
82
+
83
+ /** The <head> script that stands in for `tags` when the banner is on. It
84
+ * defines `window.wdConsent`:
85
+ * get() "granted", "denied" or null (no answer yet)
86
+ * set(value) stores the answer; "granted" adds the tags, once. Going
87
+ * from "granted" to "denied" reloads the page - scripts
88
+ * that already ran can't be taken back any other way.
89
+ * and fires a `wd:consent` event on `document` with the answer as `detail`,
90
+ * for a site's own scripts. The tags are added on load when the stored
91
+ * answer is already "granted". A browser with no localStorage asks again
92
+ * on every page, and loads nothing until the reader accepts. */
93
+ export function consentLoaderScript(tags) {
94
+ // "</script" inside the JSON would end the inline script early.
95
+ const list = JSON.stringify(tags).replace(/</g, '\\u003c');
96
+ return `(function(){var T=${list},K=${JSON.stringify(CONSENT_STORAGE_KEY)},loaded=false,answer=null;
97
+ function read(){try{var v=localStorage.getItem(K);return v==="granted"||v==="denied"?v:null}catch(e){return null}}
98
+ function load(){if(loaded)return;loaded=true;T.forEach(function(t){var s=document.createElement("script");s.async=false;for(var k in t.attrs||{}){if(t.attrs[k]===true)s.setAttribute(k,"");else s.setAttribute(k,t.attrs[k])}if(t.src)s.src=t.src;else s.text=t.content;document.head.appendChild(s)})}
99
+ answer=read();
100
+ window.wdConsent={get:function(){return answer},set:function(v){if(v!=="granted"&&v!=="denied")return;var was=answer;answer=v;try{localStorage.setItem(K,v)}catch(e){}document.dispatchEvent(new CustomEvent("wd:consent",{detail:v}));if(v==="granted")load();else if(was==="granted"&&loaded)location.reload()}};
101
+ if(answer==="granted")load();})();`;
102
+ }
@@ -0,0 +1,79 @@
1
+ // A site's font stack, and the stand-in shown until its web font arrives.
2
+ //
3
+ // A web font loads after the page's text is on screen (`font-display:
4
+ // swap`), in whatever font comes next in the stack. When the web font
5
+ // arrives, every line is laid out again - and if the two fonts set text at
6
+ // different widths, paragraphs gain or lose a line and everything below
7
+ // them moves. That's layout shift (CLS): 0.06 on Windows for the default
8
+ // font, far more where the system's fallback is a wider one.
9
+ //
10
+ // The fix is a second @font-face that points at a font every system has
11
+ // (Arial, or its metric-compatible stand-ins on Linux and Android) and
12
+ // scales it to the web font's own proportions - `size-adjust` for the width
13
+ // of its letters, the `*-override`s for its line height. Text then takes
14
+ // the same space before and after the swap, and nothing moves.
15
+ //
16
+ // Each font needs its own numbers, so this covers the fonts in
17
+ // FALLBACK_METRICS - the default, Inter, first of all. Any other font
18
+ // keeps the plain system stack, as before.
19
+ //
20
+ // Plain JavaScript, for scripts/font-fallback.test.js.
21
+
22
+ /** Per web font (lower-cased family): how Arial has to be adjusted to take
23
+ * the same space, in percent.
24
+ * sizeAdjust - the web font's average letter width over Arial's.
25
+ * ascent/descent/lineGap - the web font's own vertical metrics, divided
26
+ * by sizeAdjust (the overrides apply after the scaling).
27
+ * Inter's come from its font file (unitsPerEm 2048, ascender 1984,
28
+ * descender -494, line gap 0), with the width ratio the build's browser
29
+ * check confirms to within 1% - see docs/dev/docs/site-config.mdx for how
30
+ * to measure a new font before adding it here. */
31
+ export const FALLBACK_METRICS = {
32
+ inter: { sizeAdjust: 107.06, ascent: 90.49, descent: 22.56, lineGap: 0 },
33
+ };
34
+
35
+ /** Arial, then the fonts that stand in for it where it isn't installed -
36
+ * Liberation Sans and Arimo have Arial's exact metrics (Linux, ChromeOS,
37
+ * Android), so the same numbers hold. The first one found is used. */
38
+ const LOCAL_FONTS = ['Arial', 'Liberation Sans', 'Arimo'].map((name) => `local('${name}')`).join(', ');
39
+
40
+ const metricsFor = (family) => FALLBACK_METRICS[String(family ?? '').trim().toLowerCase()] ?? null;
41
+
42
+ /** The stand-in's family name for `family` ("Inter Fallback"), or null when
43
+ * there are no numbers for that font. */
44
+ export function fallbackFontName(family) {
45
+ return metricsFor(family) ? `${String(family).trim()} Fallback` : null;
46
+ }
47
+
48
+ /** The stand-in's @font-face rule, or '' for a font with no numbers. */
49
+ export function fallbackFontFace(family) {
50
+ const metrics = metricsFor(family);
51
+ if (!metrics) return '';
52
+ return (
53
+ `@font-face { font-family: '${fallbackFontName(family)}'; src: ${LOCAL_FONTS}; ` +
54
+ `size-adjust: ${metrics.sizeAdjust}%; ascent-override: ${metrics.ascent}%; ` +
55
+ `descent-override: ${metrics.descent}%; line-gap-override: ${metrics.lineGap}%; }`
56
+ );
57
+ }
58
+
59
+ /** The `font-family` value for `family`: the font, its stand-in when it has
60
+ * one, then the system fonts. */
61
+ export function fontStack(family) {
62
+ const fallback = fallbackFontName(family);
63
+ return `'${family}', ${fallback ? `'${fallback}', ` : ''}-apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif`;
64
+ }
65
+
66
+ /** The stand-in rules for a set of families, one per font that has numbers,
67
+ * without repeats. */
68
+ export function fallbackFontFaces(families) {
69
+ const seen = new Set();
70
+ return families
71
+ .filter((family) => {
72
+ const name = fallbackFontName(family);
73
+ if (!name || seen.has(name)) return false;
74
+ seen.add(name);
75
+ return true;
76
+ })
77
+ .map(fallbackFontFace)
78
+ .join('\n');
79
+ }
@@ -0,0 +1,140 @@
1
+ // The pixel size of an image file, read from its first bytes - for the
2
+ // width/height the build writes on content images, so the page keeps their
3
+ // place while they load (lib/rehype-image-loading.js, Image.astro).
4
+ // PNG, JPEG, GIF, WebP and SVG; anything else, or a file that doesn't parse,
5
+ // gives null and the image is left as it was.
6
+ //
7
+ // Plain JavaScript and no dependency: it's a few header fields per format.
8
+ import fs from 'node:fs';
9
+ import path from 'node:path';
10
+
11
+ /** JPEG keeps its size in a start-of-frame segment, somewhere after the
12
+ * metadata - which can be long (an embedded thumbnail), so more is read. */
13
+ const HEAD_BYTES = 256 * 1024;
14
+
15
+ function png(b) {
16
+ if (b.length < 24 || b.readUInt32BE(0) !== 0x89504e47 || b.toString('ascii', 12, 16) !== 'IHDR') return null;
17
+ return { width: b.readUInt32BE(16), height: b.readUInt32BE(20) };
18
+ }
19
+
20
+ function gif(b) {
21
+ if (b.length < 10 || !/^GIF8[79]a$/.test(b.toString('ascii', 0, 6))) return null;
22
+ return { width: b.readUInt16LE(6), height: b.readUInt16LE(8) };
23
+ }
24
+
25
+ function jpeg(b) {
26
+ if (b.length < 4 || b[0] !== 0xff || b[1] !== 0xd8) return null;
27
+ let offset = 2;
28
+ while (offset + 9 < b.length) {
29
+ if (b[offset] !== 0xff) return null;
30
+ const marker = b[offset + 1];
31
+ // Fill bytes and markers with no length field.
32
+ if (marker === 0xff) {
33
+ offset += 1;
34
+ continue;
35
+ }
36
+ if (marker === 0x01 || (marker >= 0xd0 && marker <= 0xd9)) {
37
+ offset += 2;
38
+ continue;
39
+ }
40
+ // Start of frame (every SOFn but the tables that share the range).
41
+ if (marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc) {
42
+ return { width: b.readUInt16BE(offset + 7), height: b.readUInt16BE(offset + 5) };
43
+ }
44
+ offset += 2 + b.readUInt16BE(offset + 2);
45
+ }
46
+ return null;
47
+ }
48
+
49
+ function webp(b) {
50
+ if (b.length < 30 || b.toString('ascii', 0, 4) !== 'RIFF' || b.toString('ascii', 8, 12) !== 'WEBP') return null;
51
+ const format = b.toString('ascii', 12, 16);
52
+ if (format === 'VP8 ') return { width: b.readUInt16LE(26) & 0x3fff, height: b.readUInt16LE(28) & 0x3fff };
53
+ if (format === 'VP8L') {
54
+ const bits = b.readUInt32LE(21);
55
+ return { width: (bits & 0x3fff) + 1, height: ((bits >> 14) & 0x3fff) + 1 };
56
+ }
57
+ if (format === 'VP8X') return { width: b.readUIntLE(24, 3) + 1, height: b.readUIntLE(27, 3) + 1 };
58
+ return null;
59
+ }
60
+
61
+ /** An SVG's own width and height when both are plain numbers (px or none),
62
+ * else its viewBox - the ratio is what matters to the page. */
63
+ function svg(text) {
64
+ const tag = text.match(/<svg\b[^>]*>/i)?.[0];
65
+ if (!tag) return null;
66
+ const attr = (name) => tag.match(new RegExp(`\\s${name}\\s*=\\s*["']([^"']*)["']`, 'i'))?.[1];
67
+ const pixels = (value) => (value && /^\s*\d+(\.\d+)?(px)?\s*$/i.test(value) ? parseFloat(value) : null);
68
+ const width = pixels(attr('width'));
69
+ const height = pixels(attr('height'));
70
+ if (width && height) return { width: Math.round(width), height: Math.round(height) };
71
+ const box = attr('viewBox')?.trim().split(/[\s,]+/).map(Number);
72
+ if (box?.length === 4 && box[2] > 0 && box[3] > 0) return { width: Math.round(box[2]), height: Math.round(box[3]) };
73
+ return null;
74
+ }
75
+
76
+ /** `{ width, height }` of the image in `buffer`, or null. */
77
+ export function imageSizeOf(buffer, extension = '') {
78
+ let size = null;
79
+ try {
80
+ size = extension.toLowerCase() === '.svg' ? svg(buffer.toString('utf8')) : (png(buffer) ?? gif(buffer) ?? jpeg(buffer) ?? webp(buffer) ?? svg(buffer.toString('utf8')));
81
+ } catch {
82
+ return null; // a truncated or odd file
83
+ }
84
+ return size && size.width > 0 && size.height > 0 ? size : null;
85
+ }
86
+
87
+ const cache = new Map();
88
+
89
+ /** `{ width, height }` of the image file at `file`, or null - read once per
90
+ * file and build. */
91
+ export function imageSize(file) {
92
+ if (cache.has(file)) return cache.get(file);
93
+ let size = null;
94
+ try {
95
+ const fd = fs.openSync(file, 'r');
96
+ try {
97
+ const buffer = Buffer.alloc(HEAD_BYTES);
98
+ const read = fs.readSync(fd, buffer, 0, HEAD_BYTES, 0);
99
+ size = imageSizeOf(buffer.subarray(0, read), path.extname(file));
100
+ } finally {
101
+ fs.closeSync(fd);
102
+ }
103
+ } catch {
104
+ size = null;
105
+ }
106
+ cache.set(file, size);
107
+ return size;
108
+ }
109
+
110
+ /** The width a logo takes at `height` pixels tall, from its file's own
111
+ * proportions - written on the <img> beside its height, so the browser
112
+ * keeps the logo's place before it loads. Undefined when the file isn't
113
+ * in the project or can't be read: the image is then left as it was. */
114
+ export function logoWidth(src, height = 24, contentDir = process.env.WRITEDOCS_CONTENT_DIR || process.cwd()) {
115
+ const file = imageFileFor(src, contentDir);
116
+ const size = file && imageSize(file);
117
+ return size ? Math.round((size.width / size.height) * height) : undefined;
118
+ }
119
+
120
+ /** The file behind a root-relative image address ("/images/a.png"): in
121
+ * public/, or anywhere in the project - where the build finds it too
122
+ * (lib/styles-asset-integration.js). Null for any other address. */
123
+ export function imageFileFor(src, contentDir) {
124
+ if (typeof src !== 'string' || !src.startsWith('/') || src.startsWith('//')) return null;
125
+ let pathname;
126
+ try {
127
+ pathname = decodeURIComponent(src.split(/[?#]/)[0]);
128
+ } catch {
129
+ return null;
130
+ }
131
+ const segments = pathname.replace(/^\/+/, '').split('/');
132
+ if (segments.some((segment) => segment === '' || segment === '.' || segment === '..')) return null;
133
+ for (const base of [path.join(contentDir, 'public'), contentDir]) {
134
+ const file = path.join(base, ...segments);
135
+ try {
136
+ if (fs.statSync(file).isFile()) return file;
137
+ } catch {}
138
+ }
139
+ return null;
140
+ }
@@ -87,3 +87,66 @@ export function equivalentItem(from, remainingPath) {
87
87
  }
88
88
  return node;
89
89
  }
90
+
91
+ /** A sidebar's pages in order, as page ids - a group's own page, then what
92
+ * it holds; links aren't pages. (flattenNav() in lib/config.ts, without
93
+ * the group names.) */
94
+ function pageSlugs(pages) {
95
+ return (Array.isArray(pages) ? pages : []).flatMap((item) => {
96
+ if (typeof item === 'string') return [item];
97
+ if (!item || typeof item !== 'object' || 'href' in item || 'openapi' in item) return [];
98
+ return [...(typeof item.page === 'string' ? [item.page] : []), ...pageSlugs(item.pages)];
99
+ });
100
+ }
101
+
102
+ /** The `pages` list `remainingPath` leads to inside `item`, or null when
103
+ * `item` isn't built the same way that far down. */
104
+ function leafPagesIn(item, remainingPath) {
105
+ if (!item || typeof item !== 'object' || 'href' in item) return null;
106
+ if (Array.isArray(item.pages)) return item.pages;
107
+ const [next, ...rest] = remainingPath;
108
+ if (!next) return null;
109
+ const level = childLevel(item);
110
+ if (!level || level.kind !== next.kind) return null;
111
+ return leafPagesIn(level.items[next.index], rest);
112
+ }
113
+
114
+ /** This page in each language, for `<link rel="alternate" hreflang>` -
115
+ * `[{ lang, slug }]`, the page's own language included, in the order
116
+ * writedocs.json lists them. Empty when the page isn't under a `languages`
117
+ * level, or has no counterpart in any other language.
118
+ *
119
+ * `path` is the page's navigation path (`{ kind, index, items }` segments),
120
+ * `pages` its sidebar, `landing` whether it's an item's own page.
121
+ *
122
+ * Stricter than the language switcher, on purpose. The switcher sends the
123
+ * reader to the page at the same position and, failing that, to the
124
+ * language's first page - a reader always lands somewhere sensible. An
125
+ * hreflang link is a claim to search engines that two pages are the same
126
+ * content, and a wrong one is worse than none. So a language only counts
127
+ * when its section is built the same way *and* lists the same number of
128
+ * pages as this page's - positions in two lists of different lengths don't
129
+ * line up. An item's own page pairs with the same item's own page in the
130
+ * other language, never its first page. Hidden languages and links are
131
+ * never offered. */
132
+ export function languageAlternates(path, currentSlug, pages, landing = false) {
133
+ const segIndex = path.findIndex((segment) => segment.kind === 'language');
134
+ if (segIndex === -1) return [];
135
+ const segment = path[segIndex];
136
+ const remainingPath = path.slice(segIndex + 1);
137
+ const own = pageSlugs(pages);
138
+ const position = own.indexOf(currentSlug);
139
+ const found = [];
140
+ segment.items.forEach((item, i) => {
141
+ if (!item || typeof item !== 'object' || item.hidden === true || 'href' in item || typeof item.language !== 'string') return;
142
+ let slug = null;
143
+ if (i === segment.index) slug = currentSlug;
144
+ else if (landing) slug = itemPage(equivalentItem(item, remainingPath));
145
+ else if (position >= 0) {
146
+ const theirs = pageSlugs(leafPagesIn(item, remainingPath));
147
+ if (theirs.length === own.length) slug = theirs[position] ?? null;
148
+ }
149
+ if (slug) found.push({ lang: item.language, slug });
150
+ });
151
+ return found.length > 1 ? found : [];
152
+ }
@@ -0,0 +1,127 @@
1
+ // The structured data (JSON-LD, schema.org) a page carries for search
2
+ // engines - built here, written by BaseLayout.astro as one
3
+ // <script type="application/ld+json"> per block, in the page's HTML.
4
+ //
5
+ // What a page gets, when the site has a `domain` (schema.org URLs must be
6
+ // full URLs) and the page isn't noindex:
7
+ // - the page itself: TechArticle, APIReference for an API page, or
8
+ // WebPage for a page with a layout of its own (frame, custom, blank);
9
+ // - BreadcrumbList: home, the linked groups above the page, the page;
10
+ // - on the home page: WebSite, and Organization when writedocs.json has
11
+ // `seo.organization`.
12
+ // A page's own `seo.jsonLd` blocks are added after those, always - they're
13
+ // the author's, whatever the domain or robots say.
14
+ //
15
+ // Plain JavaScript with no Astro import, for scripts/json-ld.test.js.
16
+
17
+ const CONTEXT = 'https://schema.org';
18
+
19
+ /** Google shows at most this much of a headline. */
20
+ const HEADLINE_LENGTH = 110;
21
+
22
+ const absolute = (siteUrl, value) => (/^https?:\/\//i.test(value) ? value : `${siteUrl}${value.startsWith('/') ? '' : '/'}${value}`);
23
+
24
+ /** Drops undefined, null, '' and empty arrays, so a block only says what's known. */
25
+ function compact(object) {
26
+ return Object.fromEntries(
27
+ Object.entries(object).filter(([, value]) => value !== undefined && value !== null && value !== '' && !(Array.isArray(value) && value.length === 0))
28
+ );
29
+ }
30
+
31
+ /** writedocs.json's `seo.organization` as an Organization block - its logo
32
+ * and profiles falling back to the site's own logo and `socials`. */
33
+ export function organizationBlock({ organization, siteUrl, logo, socials = {} }) {
34
+ if (!organization?.name) return null;
35
+ const image = organization.logo ?? logo;
36
+ const sameAs = organization.sameAs ?? Object.values(socials).filter((url) => /^https?:\/\//i.test(url));
37
+ return compact({
38
+ '@context': CONTEXT,
39
+ '@type': 'Organization',
40
+ name: organization.name,
41
+ url: organization.url ?? `${siteUrl}/`,
42
+ logo: image ? absolute(siteUrl, image) : undefined,
43
+ sameAs,
44
+ });
45
+ }
46
+
47
+ /** `breadcrumbs`: `[{ name, href }]` from the home page down to this page,
48
+ * hrefs as site paths. Fewer than two entries is no trail at all. */
49
+ export function breadcrumbBlock(siteUrl, breadcrumbs = []) {
50
+ const items = breadcrumbs.filter((crumb) => crumb?.name && crumb.href);
51
+ if (items.length < 2) return null;
52
+ return {
53
+ '@context': CONTEXT,
54
+ '@type': 'BreadcrumbList',
55
+ itemListElement: items.map((crumb, index) => ({
56
+ '@type': 'ListItem',
57
+ position: index + 1,
58
+ name: crumb.name,
59
+ item: absolute(siteUrl, crumb.href),
60
+ })),
61
+ };
62
+ }
63
+
64
+ /** A page's own `seo.jsonLd` - one block or a list - each with the
65
+ * schema.org context when it didn't bring one. */
66
+ export function customBlocks(custom) {
67
+ if (!custom) return [];
68
+ return (Array.isArray(custom) ? custom : [custom])
69
+ .filter((block) => block && typeof block === 'object' && !Array.isArray(block) && Object.keys(block).length)
70
+ .map((block) => ('@context' in block ? block : { '@context': CONTEXT, ...block }));
71
+ }
72
+
73
+ /** Every block for one page, in the order they're written.
74
+ * `canonical` is the page's canonical URL (seoHead() in lib/seo-tags.js),
75
+ * `mode` its frontmatter mode, `isApi` whether it's an OpenAPI page. */
76
+ export function jsonLd({
77
+ siteUrl = null,
78
+ siteName,
79
+ siteDescription,
80
+ title,
81
+ description,
82
+ path = '/',
83
+ canonical = null,
84
+ lang = 'en',
85
+ mode = 'default',
86
+ isApi = false,
87
+ noindex = false,
88
+ breadcrumbs = [],
89
+ organization,
90
+ logo,
91
+ socials,
92
+ custom,
93
+ }) {
94
+ const blocks = [];
95
+ if (siteUrl && !noindex) {
96
+ const website = { '@type': 'WebSite', name: siteName, url: `${siteUrl}/` };
97
+ const publisher = organizationBlock({ organization, siteUrl, logo, socials });
98
+ const type = isApi ? 'APIReference' : mode === 'default' || mode === 'wide' ? 'TechArticle' : 'WebPage';
99
+ blocks.push(
100
+ compact({
101
+ '@context': CONTEXT,
102
+ '@type': type,
103
+ // An article has a headline; a plain page only a name.
104
+ ...(type === 'WebPage' ? { name: title } : { headline: title.length > HEADLINE_LENGTH ? `${title.slice(0, HEADLINE_LENGTH - 1)}…` : title }),
105
+ description: description || undefined,
106
+ url: canonical ?? `${siteUrl}${path}`,
107
+ inLanguage: lang,
108
+ isPartOf: website,
109
+ publisher: publisher ? compact({ '@type': 'Organization', name: publisher.name, url: publisher.url, logo: publisher.logo }) : undefined,
110
+ })
111
+ );
112
+ const trail = breadcrumbBlock(siteUrl, breadcrumbs);
113
+ if (trail) blocks.push(trail);
114
+ if (path === '/') {
115
+ blocks.push(compact({ '@context': CONTEXT, ...website, description: siteDescription || undefined, inLanguage: lang }));
116
+ if (publisher) blocks.push(publisher);
117
+ }
118
+ }
119
+ blocks.push(...customBlocks(custom));
120
+ return blocks;
121
+ }
122
+
123
+ /** A block as the text of its <script>: "<" escaped, so nothing in a title
124
+ * or a custom block can end the tag early. */
125
+ export function serializeJsonLd(block) {
126
+ return JSON.stringify(block).replace(/</g, '\\u003c');
127
+ }