@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,102 +1,108 @@
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
- }
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
+ /** The anchor that opens the banner again, from a link on any page - no
15
+ * heading has it. src/scripts/consent.ts listens for it (its own
16
+ * SETTINGS_HASH); `writedocs broken-links` (lib/link-check.js) accepts it
17
+ * when the banner is on. */
18
+ export const CONSENT_SETTINGS_ANCHOR = 'cookie-settings';
19
+
20
+ /** localStorage key holding the reader's answer: "granted" or "denied". */
21
+ export const CONSENT_STORAGE_KEY = 'wd-consent';
22
+
23
+ export const CONSENT_DEFAULTS = {
24
+ message: 'We use cookies to understand how this site is used and to improve it.',
25
+ acceptLabel: 'Accept',
26
+ declineLabel: 'Decline',
27
+ policyLabel: 'Privacy policy',
28
+ };
29
+
30
+ /** `integrations.consent` as the banner's texts - null when it's off
31
+ * (absent or false). `true` gives the defaults. */
32
+ export function consentOptions(value) {
33
+ if (!value) return null;
34
+ const given = value === true ? {} : value;
35
+ const text = (key) => (typeof given[key] === 'string' && given[key].trim() ? given[key].trim() : CONSENT_DEFAULTS[key]);
36
+ return {
37
+ message: text('message'),
38
+ acceptLabel: text('acceptLabel'),
39
+ declineLabel: text('declineLabel'),
40
+ policyUrl: typeof given.policyUrl === 'string' && given.policyUrl.trim() ? given.policyUrl.trim() : null,
41
+ policyLabel: text('policyLabel'),
42
+ };
43
+ }
44
+
45
+ /** One <script> per entry, in order: `{ src, attrs }` for a file, or
46
+ * `{ content }` for code. `attrs` values are strings, or `true` for a
47
+ * bare attribute (`async`, `defer`).
48
+ *
49
+ * Every snippet is the provider's own install snippet - see
50
+ * docs/dev/docs/integrations.mdx for where each came from. Config values
51
+ * go in through JSON.stringify, so a quote or backslash in one can't break
52
+ * out of the generated script. */
53
+ export function analyticsTags(integrations = {}) {
54
+ const tags = [];
55
+ const { ga4, googleTagManager, plausible, fathom, posthog, umami } = integrations;
56
+ if (ga4) {
57
+ tags.push({ src: `https://www.googletagmanager.com/gtag/js?id=${ga4.measurementId}`, attrs: { async: true } });
58
+ tags.push({
59
+ content: `window.dataLayer=window.dataLayer||[];function gtag(){dataLayer.push(arguments);}gtag('js',new Date());gtag('config',${JSON.stringify(ga4.measurementId)});`,
60
+ });
61
+ }
62
+ if (googleTagManager) {
63
+ // Google's own long-stable snippet: pushes the first 'gtm.js' event and
64
+ // adds the real gtm.js loader.
65
+ tags.push({
66
+ 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)});`,
67
+ });
68
+ }
69
+ if (plausible) tags.push({ src: plausible.src, attrs: { defer: true, 'data-domain': plausible.domain } });
70
+ if (fathom) tags.push({ src: 'https://cdn.usefathom.com/script.js', attrs: { 'data-site': fathom.siteId, defer: true } });
71
+ if (posthog) {
72
+ // PostHog's "array.js" loader, from posthog.com/docs/libraries/js.
73
+ // PostHog revises its minified body now and then - fetch it again and
74
+ // compare before changing it. `defaults` is their dated configuration
75
+ // snapshot; move it on when their docs do.
76
+ tags.push({
77
+ 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'});`,
78
+ });
79
+ }
80
+ if (umami) tags.push({ src: umami.src, attrs: { defer: true, 'data-website-id': umami.websiteId } });
81
+ return tags;
82
+ }
83
+
84
+ /** `scripts.head`/`scripts.body` entries marked `consent: true`, as tags. */
85
+ export function scriptTags(entries = []) {
86
+ return entries.map((entry) => (entry.src ? { src: entry.src, attrs: {} } : { content: entry.content }));
87
+ }
88
+
89
+ /** The <head> script that stands in for `tags` when the banner is on. It
90
+ * defines `window.wdConsent`:
91
+ * get() "granted", "denied" or null (no answer yet)
92
+ * set(value) stores the answer; "granted" adds the tags, once. Going
93
+ * from "granted" to "denied" reloads the page - scripts
94
+ * that already ran can't be taken back any other way.
95
+ * and fires a `wd:consent` event on `document` with the answer as `detail`,
96
+ * for a site's own scripts. The tags are added on load when the stored
97
+ * answer is already "granted". A browser with no localStorage asks again
98
+ * on every page, and loads nothing until the reader accepts. */
99
+ export function consentLoaderScript(tags) {
100
+ // "</script" inside the JSON would end the inline script early.
101
+ const list = JSON.stringify(tags).replace(/</g, '\\u003c');
102
+ return `(function(){var T=${list},K=${JSON.stringify(CONSENT_STORAGE_KEY)},loaded=false,answer=null;
103
+ function read(){try{var v=localStorage.getItem(K);return v==="granted"||v==="denied"?v:null}catch(e){return null}}
104
+ 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)})}
105
+ answer=read();
106
+ 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()}};
107
+ if(answer==="granted")load();})();`;
108
+ }
@@ -1,140 +1,152 @@
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
- }
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
+ //
9
+ // A project can hand the sizes over instead (.writedocs/asset-dimensions.json,
10
+ // lib/asset-dimensions.js): an image listed there is never opened here. The
11
+ // WriteDocs platform builds with placeholder files in place of the images,
12
+ // so there the list is the only place a size can come from.
13
+ import fs from 'node:fs';
14
+ import path from 'node:path';
15
+ import { providedImageSize } from './asset-dimensions.js';
16
+ import { isIgnoredFile } from './project-ignore.js';
17
+
18
+ /** JPEG keeps its size in a start-of-frame segment, somewhere after the
19
+ * metadata - which can be long (an embedded thumbnail), so more is read. */
20
+ const HEAD_BYTES = 256 * 1024;
21
+
22
+ function png(b) {
23
+ if (b.length < 24 || b.readUInt32BE(0) !== 0x89504e47 || b.toString('ascii', 12, 16) !== 'IHDR') return null;
24
+ return { width: b.readUInt32BE(16), height: b.readUInt32BE(20) };
25
+ }
26
+
27
+ function gif(b) {
28
+ if (b.length < 10 || !/^GIF8[79]a$/.test(b.toString('ascii', 0, 6))) return null;
29
+ return { width: b.readUInt16LE(6), height: b.readUInt16LE(8) };
30
+ }
31
+
32
+ function jpeg(b) {
33
+ if (b.length < 4 || b[0] !== 0xff || b[1] !== 0xd8) return null;
34
+ let offset = 2;
35
+ while (offset + 9 < b.length) {
36
+ if (b[offset] !== 0xff) return null;
37
+ const marker = b[offset + 1];
38
+ // Fill bytes and markers with no length field.
39
+ if (marker === 0xff) {
40
+ offset += 1;
41
+ continue;
42
+ }
43
+ if (marker === 0x01 || (marker >= 0xd0 && marker <= 0xd9)) {
44
+ offset += 2;
45
+ continue;
46
+ }
47
+ // Start of frame (every SOFn but the tables that share the range).
48
+ if (marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc) {
49
+ return { width: b.readUInt16BE(offset + 7), height: b.readUInt16BE(offset + 5) };
50
+ }
51
+ offset += 2 + b.readUInt16BE(offset + 2);
52
+ }
53
+ return null;
54
+ }
55
+
56
+ function webp(b) {
57
+ if (b.length < 30 || b.toString('ascii', 0, 4) !== 'RIFF' || b.toString('ascii', 8, 12) !== 'WEBP') return null;
58
+ const format = b.toString('ascii', 12, 16);
59
+ if (format === 'VP8 ') return { width: b.readUInt16LE(26) & 0x3fff, height: b.readUInt16LE(28) & 0x3fff };
60
+ if (format === 'VP8L') {
61
+ const bits = b.readUInt32LE(21);
62
+ return { width: (bits & 0x3fff) + 1, height: ((bits >> 14) & 0x3fff) + 1 };
63
+ }
64
+ if (format === 'VP8X') return { width: b.readUIntLE(24, 3) + 1, height: b.readUIntLE(27, 3) + 1 };
65
+ return null;
66
+ }
67
+
68
+ /** An SVG's own width and height when both are plain numbers (px or none),
69
+ * else its viewBox - the ratio is what matters to the page. */
70
+ function svg(text) {
71
+ const tag = text.match(/<svg\b[^>]*>/i)?.[0];
72
+ if (!tag) return null;
73
+ const attr = (name) => tag.match(new RegExp(`\\s${name}\\s*=\\s*["']([^"']*)["']`, 'i'))?.[1];
74
+ const pixels = (value) => (value && /^\s*\d+(\.\d+)?(px)?\s*$/i.test(value) ? parseFloat(value) : null);
75
+ const width = pixels(attr('width'));
76
+ const height = pixels(attr('height'));
77
+ if (width && height) return { width: Math.round(width), height: Math.round(height) };
78
+ const box = attr('viewBox')?.trim().split(/[\s,]+/).map(Number);
79
+ if (box?.length === 4 && box[2] > 0 && box[3] > 0) return { width: Math.round(box[2]), height: Math.round(box[3]) };
80
+ return null;
81
+ }
82
+
83
+ /** `{ width, height }` of the image in `buffer`, or null. */
84
+ export function imageSizeOf(buffer, extension = '') {
85
+ let size = null;
86
+ try {
87
+ size = extension.toLowerCase() === '.svg' ? svg(buffer.toString('utf8')) : (png(buffer) ?? gif(buffer) ?? jpeg(buffer) ?? webp(buffer) ?? svg(buffer.toString('utf8')));
88
+ } catch {
89
+ return null; // a truncated or odd file
90
+ }
91
+ return size && size.width > 0 && size.height > 0 ? size : null;
92
+ }
93
+
94
+ const cache = new Map();
95
+
96
+ /** `{ width, height }` of the image file at `file`, or null: the size the
97
+ * project's asset-dimensions.json gives for it, else the one read from the
98
+ * file - once per file and build. */
99
+ export function imageSize(file, contentDir = process.env.WRITEDOCS_CONTENT_DIR || process.cwd()) {
100
+ const provided = providedImageSize(file, contentDir);
101
+ if (provided) return provided;
102
+ if (cache.has(file)) return cache.get(file);
103
+ let size = null;
104
+ try {
105
+ const fd = fs.openSync(file, 'r');
106
+ try {
107
+ const buffer = Buffer.alloc(HEAD_BYTES);
108
+ const read = fs.readSync(fd, buffer, 0, HEAD_BYTES, 0);
109
+ size = imageSizeOf(buffer.subarray(0, read), path.extname(file));
110
+ } finally {
111
+ fs.closeSync(fd);
112
+ }
113
+ } catch {
114
+ size = null;
115
+ }
116
+ cache.set(file, size);
117
+ return size;
118
+ }
119
+
120
+ /** The width a logo takes at `height` pixels tall, from its file's own
121
+ * proportions - written on the <img> beside its height, so the browser
122
+ * keeps the logo's place before it loads. Undefined when the file isn't
123
+ * in the project or can't be read: the image is then left as it was. */
124
+ export function logoWidth(src, height = 24, contentDir = process.env.WRITEDOCS_CONTENT_DIR || process.cwd()) {
125
+ const file = imageFileFor(src, contentDir);
126
+ const size = file && imageSize(file, contentDir);
127
+ return size ? Math.round((size.width / size.height) * height) : undefined;
128
+ }
129
+
130
+ /** The file behind a root-relative image address ("/images/a.png"): in
131
+ * public/, or anywhere in the project - where the build finds it too
132
+ * (lib/styles-asset-integration.js). Null for any other address, and for
133
+ * a file the project's ignore rules leave out (lib/wdignore.js): it isn't
134
+ * published, so it's as if it weren't there. */
135
+ export function imageFileFor(src, contentDir) {
136
+ if (typeof src !== 'string' || !src.startsWith('/') || src.startsWith('//')) return null;
137
+ let pathname;
138
+ try {
139
+ pathname = decodeURIComponent(src.split(/[?#]/)[0]);
140
+ } catch {
141
+ return null;
142
+ }
143
+ const segments = pathname.replace(/^\/+/, '').split('/');
144
+ if (segments.some((segment) => segment === '' || segment === '.' || segment === '..')) return null;
145
+ for (const base of [path.join(contentDir, 'public'), contentDir]) {
146
+ const file = path.join(base, ...segments);
147
+ try {
148
+ if (fs.statSync(file).isFile() && !isIgnoredFile(file, contentDir)) return file;
149
+ } catch {}
150
+ }
151
+ return null;
152
+ }
@@ -165,6 +165,7 @@ export const DESCRIPTIONS = {
165
165
  api: 'The API playground.',
166
166
  'api.proxy': 'When the browser blocks a "Try it" request (the API doesn\'t allow calls from other sites - CORS), retry it through writedocs\' proxy. Requests always go to the API directly first. Default true.',
167
167
  domain: 'The site\'s address, like "docs.example.com". Turns on sitemap.xml and absolute URLs in link previews.',
168
+ basePath: 'The path the site is served under, like "/docs" for example.com/docs - usually behind your own proxy. Every address the site makes starts with it, and the build writes the site to dist/docs/. Starts with "/", no "/" at the end; lowercase letters, digits, "-" and "_". Default: none, the site at the root.',
168
169
 
169
170
  seo: 'Default metadata for every page. A page\'s own `seo` frontmatter overrides it field by field.',
170
171
  'seo.ogImage': 'Image shown in link previews - a path or a full URL.',