@writedocs/generator 0.13.4 → 0.14.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 (89) hide show
  1. package/README.md +28 -28
  2. package/astro.config.mjs +645 -645
  3. package/bin/writedocs.js +359 -356
  4. package/package.json +99 -99
  5. package/src/cli/base-path-layout.js +44 -44
  6. package/src/cli/build-auth.js +135 -135
  7. package/src/cli/build.js +223 -203
  8. package/src/cli/check-built-styles.js +41 -41
  9. package/src/cli/convert.js +124 -124
  10. package/src/cli/dev.js +269 -268
  11. package/src/cli/exit-when-flushed.js +42 -42
  12. package/src/cli/generate-api-pages.js +509 -507
  13. package/src/cli/og-image-worker.js +20 -20
  14. package/src/cli/og-images.js +70 -70
  15. package/src/cli/page-list-watch.js +71 -69
  16. package/src/cli/run-astro.js +97 -97
  17. package/src/cli/run-pagefind.js +154 -154
  18. package/src/cli/write-mcp-files.js +103 -103
  19. package/src/cli/write-redirects-file.js +158 -158
  20. package/src/components/ApiReferencePanel.astro +1792 -1792
  21. package/src/components/AppIcon.astro +51 -51
  22. package/src/components/Card.astro +193 -193
  23. package/src/components/CodeGroup.astro +63 -39
  24. package/src/components/CopyPageMenu.astro +374 -374
  25. package/src/components/Hint.astro +188 -188
  26. package/src/components/Icon.astro +72 -72
  27. package/src/components/Image.astro +165 -165
  28. package/src/components/Tile.astro +67 -67
  29. package/src/components/Video.astro +137 -137
  30. package/src/content.config.ts +219 -203
  31. package/src/layout/BaseLayout.astro +908 -908
  32. package/src/layout/components/AnalyticsScripts.astro +49 -49
  33. package/src/layout/components/Breadcrumbs.astro +98 -98
  34. package/src/layout/components/ConsentBanner.astro +119 -119
  35. package/src/layout/components/MobileMenu.astro +225 -225
  36. package/src/layout/components/NavTree.astro +422 -408
  37. package/src/layout/components/Sidebar.astro +232 -232
  38. package/src/layout/components/SiteFooter.astro +87 -87
  39. package/src/layout/components/TopBar.astro +386 -386
  40. package/src/layout/styles/base.css +332 -326
  41. package/src/layout/styles/mobile-menu.css +285 -285
  42. package/src/lib/agent-markdown.js +164 -164
  43. package/src/lib/asset-dimensions.js +89 -89
  44. package/src/lib/base-path.js +90 -90
  45. package/src/lib/cli-report.js +22 -22
  46. package/src/lib/code-line-numbers.js +13 -0
  47. package/src/lib/config-schema.js +12 -1
  48. package/src/lib/config-schema.ts +2523 -2509
  49. package/src/lib/config.ts +1331 -1316
  50. package/src/lib/consent.js +108 -108
  51. package/src/lib/content-check.js +4 -1
  52. package/src/lib/content-store-reload-integration.js +101 -101
  53. package/src/lib/drafts.js +186 -0
  54. package/src/lib/icon-data-dev.js +53 -53
  55. package/src/lib/image-size.js +152 -152
  56. package/src/lib/json-schema-descriptions.js +228 -228
  57. package/src/lib/link-check.js +553 -544
  58. package/src/lib/llms-index.ts +90 -90
  59. package/src/lib/mcp-dev-integration.js +65 -65
  60. package/src/lib/mcp-index.ts +102 -102
  61. package/src/lib/mintlify-convert.js +605 -605
  62. package/src/lib/moved-api-pages.js +49 -49
  63. package/src/lib/og-cards.js +33 -33
  64. package/src/lib/og-image.js +235 -235
  65. package/src/lib/openapi-dev-status.js +80 -80
  66. package/src/lib/openapi-reload-integration.js +193 -193
  67. package/src/lib/pages.js +346 -312
  68. package/src/lib/project-files-integration.js +116 -116
  69. package/src/lib/project-files.js +137 -137
  70. package/src/lib/rehype-base-path.js +62 -62
  71. package/src/lib/rehype-image-loading.js +71 -71
  72. package/src/lib/robots-txt.js +21 -21
  73. package/src/lib/search-scope.js +44 -44
  74. package/src/lib/selector-placement.js +50 -50
  75. package/src/lib/seo-tags.js +157 -155
  76. package/src/lib/shiki-code-block.js +7 -1
  77. package/src/lib/site-base.ts +27 -27
  78. package/src/lib/styles-asset-integration.js +291 -291
  79. package/src/lib/wdignore-cases.json +195 -195
  80. package/src/lib/wdignore.js +177 -177
  81. package/src/pages/404.astro +63 -63
  82. package/src/pages/[...slug].astro +1773 -1608
  83. package/src/pages/[...slug].md.ts +93 -93
  84. package/src/pages/llms-full.txt.ts +88 -88
  85. package/src/pages/og/[...slug].png.ts +63 -63
  86. package/src/scripts/mobile-menu.ts +80 -80
  87. package/src/scripts/search.ts +245 -245
  88. package/src/scripts/sidebar-scroll.ts +61 -61
  89. package/src/styles/global.css +40 -40
@@ -1,108 +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
- /** 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
+ // 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
+ }
@@ -384,7 +384,10 @@ async function checkOpenApi(contentDir, config, locate, openapiRefs, errors, war
384
384
  export async function checkContent(contentDir, configText) {
385
385
  const errors = [];
386
386
  const warnings = [];
387
- const pages = findAllPages(contentDir);
387
+ // Drafts too (`draft: true`): the build leaves them out, but they're the
388
+ // project's pages - checked like any other, and the navigation can list
389
+ // them (the build takes those entries out, with a warning).
390
+ const pages = findAllPages(contentDir, { drafts: true });
388
391
  const openapiRefs = [];
389
392
  for (const rel of pages) await checkPage(contentDir, rel, errors, warnings, openapiRefs);
390
393
 
@@ -1,101 +1,101 @@
1
- // `writedocs dev`, installed: Astro's content store changes reach the page.
2
- //
3
- // When a collection entry changes - a page's frontmatter, a generated API
4
- // page added, renamed or removed (lib/openapi-reload-integration.js) - Astro
5
- // writes two files under <packageRoot>/.astro/ and learns that it did from
6
- // Vite's file watcher:
7
- // - data-store.json, the entries: on its change event Astro re-reads it,
8
- // clears the routes getStaticPaths() gave, and reloads the open tab
9
- // (astro/dist/content/vite-plugin-content-virtual-mod.js);
10
- // - content-modules.mjs, the module that renders each entry: an ordinary
11
- // module, which Vite invalidates when it changes - without that, a new
12
- // entry fails to render (UnknownContentCollectionError).
13
- // Vite's watcher ignores everything under node_modules, whatever the config
14
- // says - and an installed writedocs is there
15
- // (<project>/node_modules/@writedocs/generator/.astro/...). So neither event
16
- // came: a title edited in a page's frontmatter, or a new operation's page,
17
- // stayed as it was until the preview restarted. In a checkout of this
18
- // repository the folder isn't under node_modules and Vite sees it by itself.
19
- //
20
- // This watches the two files directly and hands their change events to
21
- // Vite's watcher - the module list first, so the reload Astro sends for the
22
- // store finds it current. lib/openapi-reload-integration.js hands them on
23
- // itself (contentStoreChanged()), at the moment it knows the store is
24
- // complete; the echo of that from the watcher is skipped.
25
- import fs from 'node:fs';
26
- import path from 'node:path';
27
-
28
- /** The files, in the order their change is handed on. */
29
- export const CONTENT_STORE_FILES = ['content-modules.mjs', 'data-store.json'];
30
-
31
- // When contentStoreChanged() last ran - the watcher's own event for the same
32
- // writes comes right after it.
33
- let handedOnAt = 0;
34
- const ECHO_MS = 1000;
35
-
36
- /** Hands Astro the change events of its content store files, as if Vite's
37
- * watcher had seen them - Astro re-reads the store, clears its routes and
38
- * reloads the open tab. For a caller that has just synced the store
39
- * (refreshContent() resolves once both files are written). */
40
- export function contentStoreChanged(server, packageRoot) {
41
- handedOnAt = Date.now();
42
- for (const name of CONTENT_STORE_FILES) {
43
- const file = path.join(packageRoot, '.astro', name);
44
- if (fs.existsSync(file)) server.watcher.emit('change', file);
45
- }
46
- }
47
-
48
- /** Whether Vite's watcher can't see files in `packageRoot` - it's inside a
49
- * node_modules folder. */
50
- export function insideNodeModules(packageRoot) {
51
- return path.resolve(packageRoot).split(/[\\/]/).includes('node_modules');
52
- }
53
-
54
- /** Calls `onChange(files)` - the ones of `names` in `dir` written since the
55
- * last call, in the order of `names` - once a burst of writes settles.
56
- * Astro replaces each file whole (a rename), so the folder is what's
57
- * watched. Returns a function that stops. */
58
- export function watchFiles(dir, names, onChange, { settleMs = 100 } = {}) {
59
- fs.mkdirSync(dir, { recursive: true });
60
- const changed = new Set();
61
- let timer = null;
62
- let watcher;
63
- try {
64
- watcher = fs.watch(dir, (_event, filename) => {
65
- if (!filename || !names.includes(filename)) return;
66
- changed.add(filename);
67
- clearTimeout(timer);
68
- timer = setTimeout(() => {
69
- const files = names.filter((name) => changed.has(name)).map((name) => path.join(dir, name)).filter((file) => fs.existsSync(file));
70
- changed.clear();
71
- if (files.length) onChange(files);
72
- }, settleMs);
73
- });
74
- watcher.on('error', () => {});
75
- } catch {
76
- return () => {};
77
- }
78
- return () => {
79
- clearTimeout(timer);
80
- watcher.close();
81
- };
82
- }
83
-
84
- export function contentStoreReload({ packageRoot }) {
85
- return {
86
- name: 'writedocs-content-store-reload',
87
- hooks: {
88
- 'astro:server:setup': ({ server }) => {
89
- if (!insideNodeModules(packageRoot)) return;
90
- // The paths exactly as Astro compares them: fileURLToPath() of
91
- // new URL('.astro/<file>', root), root being packageRoot.
92
- const dir = path.join(packageRoot, '.astro');
93
- const stop = watchFiles(dir, CONTENT_STORE_FILES, (files) => {
94
- if (Date.now() - handedOnAt < ECHO_MS) return;
95
- for (const file of files) server.watcher.emit('change', file);
96
- });
97
- server.httpServer?.once('close', stop);
98
- },
99
- },
100
- };
101
- }
1
+ // `writedocs dev`, installed: Astro's content store changes reach the page.
2
+ //
3
+ // When a collection entry changes - a page's frontmatter, a generated API
4
+ // page added, renamed or removed (lib/openapi-reload-integration.js) - Astro
5
+ // writes two files under <packageRoot>/.astro/ and learns that it did from
6
+ // Vite's file watcher:
7
+ // - data-store.json, the entries: on its change event Astro re-reads it,
8
+ // clears the routes getStaticPaths() gave, and reloads the open tab
9
+ // (astro/dist/content/vite-plugin-content-virtual-mod.js);
10
+ // - content-modules.mjs, the module that renders each entry: an ordinary
11
+ // module, which Vite invalidates when it changes - without that, a new
12
+ // entry fails to render (UnknownContentCollectionError).
13
+ // Vite's watcher ignores everything under node_modules, whatever the config
14
+ // says - and an installed writedocs is there
15
+ // (<project>/node_modules/@writedocs/generator/.astro/...). So neither event
16
+ // came: a title edited in a page's frontmatter, or a new operation's page,
17
+ // stayed as it was until the preview restarted. In a checkout of this
18
+ // repository the folder isn't under node_modules and Vite sees it by itself.
19
+ //
20
+ // This watches the two files directly and hands their change events to
21
+ // Vite's watcher - the module list first, so the reload Astro sends for the
22
+ // store finds it current. lib/openapi-reload-integration.js hands them on
23
+ // itself (contentStoreChanged()), at the moment it knows the store is
24
+ // complete; the echo of that from the watcher is skipped.
25
+ import fs from 'node:fs';
26
+ import path from 'node:path';
27
+
28
+ /** The files, in the order their change is handed on. */
29
+ export const CONTENT_STORE_FILES = ['content-modules.mjs', 'data-store.json'];
30
+
31
+ // When contentStoreChanged() last ran - the watcher's own event for the same
32
+ // writes comes right after it.
33
+ let handedOnAt = 0;
34
+ const ECHO_MS = 1000;
35
+
36
+ /** Hands Astro the change events of its content store files, as if Vite's
37
+ * watcher had seen them - Astro re-reads the store, clears its routes and
38
+ * reloads the open tab. For a caller that has just synced the store
39
+ * (refreshContent() resolves once both files are written). */
40
+ export function contentStoreChanged(server, packageRoot) {
41
+ handedOnAt = Date.now();
42
+ for (const name of CONTENT_STORE_FILES) {
43
+ const file = path.join(packageRoot, '.astro', name);
44
+ if (fs.existsSync(file)) server.watcher.emit('change', file);
45
+ }
46
+ }
47
+
48
+ /** Whether Vite's watcher can't see files in `packageRoot` - it's inside a
49
+ * node_modules folder. */
50
+ export function insideNodeModules(packageRoot) {
51
+ return path.resolve(packageRoot).split(/[\\/]/).includes('node_modules');
52
+ }
53
+
54
+ /** Calls `onChange(files)` - the ones of `names` in `dir` written since the
55
+ * last call, in the order of `names` - once a burst of writes settles.
56
+ * Astro replaces each file whole (a rename), so the folder is what's
57
+ * watched. Returns a function that stops. */
58
+ export function watchFiles(dir, names, onChange, { settleMs = 100 } = {}) {
59
+ fs.mkdirSync(dir, { recursive: true });
60
+ const changed = new Set();
61
+ let timer = null;
62
+ let watcher;
63
+ try {
64
+ watcher = fs.watch(dir, (_event, filename) => {
65
+ if (!filename || !names.includes(filename)) return;
66
+ changed.add(filename);
67
+ clearTimeout(timer);
68
+ timer = setTimeout(() => {
69
+ const files = names.filter((name) => changed.has(name)).map((name) => path.join(dir, name)).filter((file) => fs.existsSync(file));
70
+ changed.clear();
71
+ if (files.length) onChange(files);
72
+ }, settleMs);
73
+ });
74
+ watcher.on('error', () => {});
75
+ } catch {
76
+ return () => {};
77
+ }
78
+ return () => {
79
+ clearTimeout(timer);
80
+ watcher.close();
81
+ };
82
+ }
83
+
84
+ export function contentStoreReload({ packageRoot }) {
85
+ return {
86
+ name: 'writedocs-content-store-reload',
87
+ hooks: {
88
+ 'astro:server:setup': ({ server }) => {
89
+ if (!insideNodeModules(packageRoot)) return;
90
+ // The paths exactly as Astro compares them: fileURLToPath() of
91
+ // new URL('.astro/<file>', root), root being packageRoot.
92
+ const dir = path.join(packageRoot, '.astro');
93
+ const stop = watchFiles(dir, CONTENT_STORE_FILES, (files) => {
94
+ if (Date.now() - handedOnAt < ECHO_MS) return;
95
+ for (const file of files) server.watcher.emit('change', file);
96
+ });
97
+ server.httpServer?.once('close', stop);
98
+ },
99
+ },
100
+ };
101
+ }
@@ -0,0 +1,186 @@
1
+ // Draft pages - `draft: true` in a page's frontmatter (Docusaurus' key).
2
+ //
3
+ // In `writedocs build` a draft doesn't exist: it's left out where the build
4
+ // decides which pages there are - findAllPages() in lib/pages.js, the list
5
+ // every route, the content collection, the sitemap and `writedocs
6
+ // broken-links` start from - and where it reads the navigation:
7
+ // loadDocsConfig() in lib/config.ts puts the navigation through
8
+ // withoutDrafts() below, so the sidebar, the switchers, prev/next, the "/"
9
+ // redirect, llms.txt and the MCP index never see an entry for one. Nothing
10
+ // downstream filters drafts on its own.
11
+ //
12
+ // `writedocs dev` and `writedocs build --drafts` - a preview of them, for
13
+ // deploy previews - keep them (draftsIncluded() in lib/pages.js), marked: a
14
+ // strip at the top of the page (DRAFT_BANNER_HTML below, [...slug].astro), a
15
+ // mark on its sidebar entry (NavTree.astro) and "Draft" on its search
16
+ // result's section line - and noindex: the page schema makes every draft
17
+ // noindex (lib/config-schema.ts), which keeps it out of the sitemap, llms.txt
18
+ // and the MCP index the way any noindex page is.
19
+ //
20
+ // Plain JavaScript, for scripts/drafts.test.js and for the CLI, which prints
21
+ // draftWarnings() with the build's other warnings. No import of
22
+ // lib/config-schema.js: lib/config.ts loads this file inside Astro, where the
23
+ // schema comes from config-schema.ts - draftWarnings() gets its line locator
24
+ // from the caller instead.
25
+ import { navPageId, fileIdForPath } from './pages.js';
26
+
27
+ /** The key that names each kind of navigation item, in the order they're
28
+ * looked for - what a warning calls the item. */
29
+ const ITEM_KINDS = ['group', 'tab', 'version', 'language', 'dropdown', 'product'];
30
+
31
+ /**
32
+ * `navigation` without the entries that name a draft page: a page in a
33
+ * `pages` list, or an item's own `page`. An item that had pages and is left
34
+ * with none - every page in it was a draft - goes too, and so on up: a tab
35
+ * whose groups all went. An item that keeps its own `page`, or that never
36
+ * had pages (an `href`, an `openapi` group, which gets its pages later), is
37
+ * kept. The navigation's root is always kept.
38
+ *
39
+ * `draftIds` - the drafts' page ids (fileIdForPath()); a navigation entry
40
+ * matches by its page id (navPageId(): "guides/index" is "guides"). With no
41
+ * drafts, `navigation` itself comes back. Returns { navigation, leftOut }:
42
+ * `leftOut` lists what was taken out, in the order it was met - `{ path,
43
+ * page }` for an entry (`page` as the navigation writes it), `{ path, kind,
44
+ * name }` for an item - with `path` the JSON path from `navigation`.
45
+ */
46
+ export function withoutDrafts(navigation, draftIds) {
47
+ const leftOut = [];
48
+ if (!draftIds || draftIds.size === 0) return { navigation, leftOut };
49
+ const isDraftEntry = (value) => typeof value === 'string' && draftIds.has(navPageId(value));
50
+ const REMOVED = Symbol('removed');
51
+
52
+ function prune(node, trail) {
53
+ if (Array.isArray(node)) {
54
+ const kept = [];
55
+ node.forEach((item, i) => {
56
+ if (isDraftEntry(item)) {
57
+ leftOut.push({ path: [...trail, i], page: item });
58
+ return;
59
+ }
60
+ const value = prune(item, [...trail, i]);
61
+ if (value !== REMOVED) kept.push(value);
62
+ });
63
+ return kept;
64
+ }
65
+ if (!node || typeof node !== 'object') return node;
66
+ const out = {};
67
+ let hadPages = false;
68
+ let hasPages = false;
69
+ for (const [key, value] of Object.entries(node)) {
70
+ if (key === 'href' || key === 'openapi') {
71
+ out[key] = value;
72
+ continue;
73
+ }
74
+ if (key === 'page' && typeof value === 'string') {
75
+ if (isDraftEntry(value)) leftOut.push({ path: [...trail, key], page: value });
76
+ else out[key] = value;
77
+ continue;
78
+ }
79
+ const pruned = prune(value, [...trail, key]);
80
+ if (Array.isArray(value) && value.length > 0) {
81
+ hadPages = true;
82
+ if (pruned.length > 0) hasPages = true;
83
+ }
84
+ out[key] = pruned;
85
+ }
86
+ const emptied = hadPages && !hasPages && !('page' in out) && !('href' in out) && !('openapi' in out);
87
+ if (emptied && trail.length > 0) {
88
+ const kind = ITEM_KINDS.find((k) => typeof node[k] === 'string') ?? 'item';
89
+ leftOut.push({ path: trail, kind, name: node[kind] ?? '' });
90
+ return REMOVED;
91
+ }
92
+ return out;
93
+ }
94
+
95
+ return { navigation: prune(navigation, []), leftOut };
96
+ }
97
+
98
+ /** A page address the way writedocs.json's `redirects` and a page's `slug`
99
+ * write it, as one key: no slashes around it, no #anchor or ?query, lower
100
+ * case; the root is "index". */
101
+ function addressKey(value) {
102
+ const bare = String(value).split(/[?#]/)[0].replace(/^\/+|\/+$/g, '').toLowerCase();
103
+ return bare === '' ? 'index' : bare;
104
+ }
105
+
106
+ /**
107
+ * What `writedocs build` tells the author about the drafts it leaves out,
108
+ * as { warnings, notes } - warnings `{ where, message }` like the build's
109
+ * others, `where` a "writedocs.json:line" or the draft's own file:
110
+ * - each navigation entry for a draft, and each item left with no pages
111
+ * (withoutDrafts());
112
+ * - each redirect that leads to a draft - it stays, and shows "not found"
113
+ * until the page is published;
114
+ * - a draft home page - "/" goes to the navigation's first page instead.
115
+ * `notes` says how many drafts were left out. `configText` is
116
+ * writedocs.json's text (valid JSON - the build checked it first), `drafts`
117
+ * what findDraftPages() (lib/pages.js) gives, `locate` createJsonLocator()
118
+ * of that text (lib/config-schema.js). Empty without drafts.
119
+ */
120
+ export function draftWarnings({ configText, drafts, locate }) {
121
+ const warnings = [];
122
+ const notes = [];
123
+ if (!drafts.length) return { warnings, notes };
124
+ const config = JSON.parse(configText);
125
+ const where = (jsonPath) => {
126
+ const line = locate(jsonPath)?.line;
127
+ return line ? `writedocs.json:${line}` : 'writedocs.json';
128
+ };
129
+
130
+ const { leftOut } = withoutDrafts(config.navigation, new Set(drafts.map((draft) => fileIdForPath(draft.file))));
131
+ for (const entry of leftOut) {
132
+ const jsonPath = ['navigation', ...entry.path];
133
+ warnings.push({
134
+ where: where(jsonPath),
135
+ message: entry.page
136
+ ? `${entry.page} is a draft and was left out of the navigation.`
137
+ : `The ${entry.kind} "${entry.name}" was left out of the navigation: every page in it is a draft.`,
138
+ });
139
+ }
140
+
141
+ const byAddress = new Map(drafts.map((draft) => [addressKey(draft.slug ?? fileIdForPath(draft.file)), draft]));
142
+ (Array.isArray(config.redirects) ? config.redirects : []).forEach((redirect, i) => {
143
+ if (typeof redirect?.destination !== 'string' || /^[a-z][a-z0-9+.-]*:|^\/\//i.test(redirect.destination)) return;
144
+ const draft = byAddress.get(addressKey(redirect.destination));
145
+ if (!draft) return;
146
+ warnings.push({
147
+ where: where(['redirects', i, 'destination']),
148
+ message: `The redirect from ${redirect.source} leads to ${redirect.destination}, a draft (${draft.file}) - it shows "not found" until the page is published.`,
149
+ });
150
+ });
151
+
152
+ const home = byAddress.get('index');
153
+ if (home) {
154
+ warnings.push({
155
+ where: home.file,
156
+ message: "The home page is a draft - the site's address (/) opens the navigation's first page instead.",
157
+ });
158
+ }
159
+
160
+ notes.push(
161
+ drafts.length === 1
162
+ ? '1 draft page (draft: true) was left out of the site - writedocs dev shows it.'
163
+ : `${drafts.length} draft pages (draft: true) were left out of the site - writedocs dev shows them.`
164
+ );
165
+ return { warnings, notes };
166
+ }
167
+
168
+ /** The strip at the top of a draft page, in `writedocs dev` and `build
169
+ * --drafts` ([...slug].astro). Its stylesheet comes with it, inline: in the
170
+ * site's own CSS it would be on every site, and a site with no drafts builds
171
+ * byte for byte as it did before drafts existed. Left out of search's text
172
+ * and the page's Markdown copy. */
173
+ export const DRAFT_BANNER_HTML =
174
+ '<style>' +
175
+ '.wd-draft-banner{display:flex;flex-wrap:wrap;align-items:baseline;gap:.25rem .625rem;margin:0 0 1.5rem;padding:.625rem .875rem;' +
176
+ 'border:1px dashed color-mix(in srgb,#d97706 60%,transparent);border-radius:.5rem;' +
177
+ 'background:color-mix(in srgb,#d97706 9%,var(--wd-background));color:var(--wd-text);font-size:.875rem;line-height:1.5}' +
178
+ '.wd-draft-banner strong{color:#b45309;font-weight:700}' +
179
+ '[data-theme=dark] .wd-draft-banner strong{color:#fbbf24}' +
180
+ '.wd-draft-banner code{font-size:.8125rem}' +
181
+ '.wd-canvas>.wd-draft-banner{margin:1rem}' +
182
+ '</style>' +
183
+ '<div class="wd-draft-banner" role="note" data-pagefind-ignore data-markdown-ignore>' +
184
+ '<strong>Draft: not published</strong>' +
185
+ '<span>This page has <code>draft: true</code> - the published site leaves it out.</span>' +
186
+ '</div>';