@writedocs/generator 0.10.20 → 0.11.1
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.
- package/astro.config.mjs +32 -8
- package/package.json +3 -1
- package/src/cli/astro-output.js +44 -11
- package/src/cli/base-path-layout.js +44 -0
- package/src/cli/build.js +18 -9
- package/src/cli/check-built-styles.js +41 -33
- package/src/cli/dev.js +21 -4
- package/src/cli/run-pagefind.js +154 -148
- package/src/cli/write-mcp-files.js +103 -96
- package/src/cli/write-redirects-file.js +25 -8
- package/src/components/AppIcon.astro +51 -50
- package/src/components/Card.astro +193 -192
- package/src/components/CopyPageMenu.astro +374 -370
- package/src/components/Hint.astro +188 -187
- package/src/components/Icon.astro +72 -71
- package/src/components/Image.astro +3 -2
- package/src/components/Tile.astro +67 -66
- package/src/components/Video.astro +137 -136
- package/src/layout/BaseLayout.astro +21 -12
- package/src/layout/components/AnalyticsScripts.astro +6 -2
- package/src/layout/components/Breadcrumbs.astro +98 -97
- package/src/layout/components/ConsentBanner.astro +119 -118
- package/src/layout/components/MobileMenu.astro +229 -228
- package/src/layout/components/NavTree.astro +393 -392
- package/src/layout/components/Sidebar.astro +232 -231
- package/src/layout/components/SiteFooter.astro +87 -86
- package/src/layout/components/TopBar.astro +386 -385
- package/src/lib/agent-markdown.js +164 -162
- package/src/lib/asset-dimensions.js +89 -89
- package/src/lib/base-path.js +90 -0
- package/src/lib/config-schema.js +10 -0
- package/src/lib/config-schema.ts +17 -0
- package/src/lib/config.ts +1314 -1289
- package/src/lib/consent.js +108 -102
- package/src/lib/json-schema-descriptions.js +1 -0
- package/src/lib/link-check.js +7 -2
- package/src/lib/llms-index.ts +90 -88
- package/src/lib/mcp-dev-integration.js +65 -60
- package/src/lib/mcp-index.ts +102 -101
- package/src/lib/project-files-integration.js +2 -2
- package/src/lib/rehype-base-path.js +62 -0
- package/src/lib/robots-txt.js +21 -16
- package/src/lib/seo-tags.js +155 -140
- package/src/lib/site-base.ts +27 -0
- package/src/lib/styles-asset-integration.js +23 -10
- package/src/lib/wdignore-cases.json +195 -195
- package/src/lib/wdignore.js +177 -177
- package/src/pages/404.astro +63 -62
- package/src/pages/[...slug].astro +1604 -1597
- package/src/pages/[...slug].md.ts +93 -93
- package/src/pages/llms-full.txt.ts +88 -86
- package/src/scripts/search.ts +245 -237
- package/writedocs.schema.json +6 -0
package/src/lib/consent.js
CHANGED
|
@@ -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
|
-
/**
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
*
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
}
|
|
56
|
-
if (
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
*
|
|
91
|
-
*
|
|
92
|
-
*
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
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
|
+
}
|
|
@@ -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.',
|
package/src/lib/link-check.js
CHANGED
|
@@ -7,7 +7,9 @@
|
|
|
7
7
|
// A link is broken when, on the built site:
|
|
8
8
|
// - no page, redirect or file is at its address;
|
|
9
9
|
// - its #anchor isn't on the target page (headings, titled components -
|
|
10
|
-
// Callout/Accordion/Update and friends - and elements with an `id`)
|
|
10
|
+
// Callout/Accordion/Update and friends - and elements with an `id`).
|
|
11
|
+
// #cookie-settings is on every page when writedocs.json turns on
|
|
12
|
+
// `integrations.consent`: it opens the consent banner (lib/consent.js);
|
|
11
13
|
// - it names a file the build doesn't publish (lib/project-files.js says
|
|
12
14
|
// which files of a project are published as they are).
|
|
13
15
|
//
|
|
@@ -40,6 +42,7 @@ import { folderAddresses } from './folder-redirects.js';
|
|
|
40
42
|
import { isPublishedFile, readSpecPaths } from './project-files.js';
|
|
41
43
|
import { projectIgnore } from './project-ignore.js';
|
|
42
44
|
import { readMovedApiPages } from './moved-api-pages.js';
|
|
45
|
+
import { consentOptions, CONSENT_SETTINGS_ANCHOR } from './consent.js';
|
|
43
46
|
|
|
44
47
|
// The same github-slugger Astro builds page URLs and heading ids with -
|
|
45
48
|
// resolved through Astro itself, so the two can't drift apart.
|
|
@@ -310,6 +313,8 @@ export async function checkLinks(contentDir, configText) {
|
|
|
310
313
|
const specs = readSpecPaths(contentDir);
|
|
311
314
|
const rules = projectIgnore(contentDir);
|
|
312
315
|
const special = new Set(['/llms.txt', '/llms-full.txt', '/404.html', '/404/', '/robots.txt']);
|
|
316
|
+
// With the consent banner on, #cookie-settings opens it from any page.
|
|
317
|
+
const pageWideAnchors = new Set(consentOptions(config.integrations?.consent) ? [CONSENT_SETTINGS_ANCHOR] : []);
|
|
313
318
|
if (config.domain) ['/sitemap.xml', '/sitemap-index.xml'].forEach((p) => special.add(p));
|
|
314
319
|
const knownUrls = [...pages.keys(), ...generated, ...redirects];
|
|
315
320
|
// Folder addresses with no page of their own redirect to one under them
|
|
@@ -408,7 +413,7 @@ export async function checkLinks(contentDir, configText) {
|
|
|
408
413
|
}
|
|
409
414
|
if (pageKey !== null) {
|
|
410
415
|
if (pages.has(pageKey)) {
|
|
411
|
-
if (!hash || hash === 'top') return;
|
|
416
|
+
if (!hash || hash === 'top' || pageWideAnchors.has(hash)) return;
|
|
412
417
|
const anchors = await anchorsOf(pages.get(pageKey).abs);
|
|
413
418
|
if (anchors.has(hash)) return;
|
|
414
419
|
const suggestion = closest(hash, [...anchors]);
|
package/src/lib/llms-index.ts
CHANGED
|
@@ -1,88 +1,90 @@
|
|
|
1
|
-
// llms.txt and its child files (/llms/*.md) - the pages an AI tool can
|
|
2
|
-
// discover, in the site's navigation structure. Shared by llms.txt.ts (the
|
|
3
|
-
// root file) and llms/[...path].md.ts (the child files a big site's llms.txt
|
|
4
|
-
// links to), so both render from the same tree in the same run. The
|
|
5
|
-
// structure and the splitting live in lib/llms.js.
|
|
6
|
-
import { getCollection, type CollectionEntry } from 'astro:content';
|
|
7
|
-
import fs from 'node:fs';
|
|
8
|
-
import path from 'node:path';
|
|
9
|
-
import { loadDocsConfig, normalizeEntryId, findAllPages,
|
|
10
|
-
import { buildLlmsTree, renderLlmsFiles } from './llms.js';
|
|
11
|
-
import { navigationPageOrder } from './pages.js';
|
|
12
|
-
import { writedocsTempDir } from './writedocs-temp-dir.js';
|
|
13
|
-
|
|
14
|
-
type DocsEntry = CollectionEntry<'pages'> | CollectionEntry<'generatedDocs'>;
|
|
15
|
-
|
|
16
|
-
// Mirrors Mintlify's own llms.txt behavior: a page's frontmatter
|
|
17
|
-
// `description` is cut at the first line break (a multi-paragraph
|
|
18
|
-
// description would blow out a one-line list entry) and at 300 characters,
|
|
19
|
-
// so every entry stays scannable.
|
|
20
|
-
const DESCRIPTION_MAX_CHARS = 300;
|
|
21
|
-
function truncateDescription(description: string | undefined): string | undefined {
|
|
22
|
-
if (!description) return undefined;
|
|
23
|
-
const firstLine = description.split('\n')[0].trim();
|
|
24
|
-
if (!firstLine) return undefined;
|
|
25
|
-
return firstLine.length > DESCRIPTION_MAX_CHARS ? firstLine.slice(0, DESCRIPTION_MAX_CHARS).trimEnd() + '…' : firstLine;
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
// Most characters one file holds - llms.txt or a child file. The llms.txt
|
|
29
|
-
// spec sets no limit ("small enough to fit in context"); this is Mintlify's,
|
|
30
|
-
// about 25,000 tokens. Past it, sections move into child files instead of
|
|
31
|
-
// pages being dropped.
|
|
32
|
-
export const LLMS_MAX_CHARS = 100_000;
|
|
33
|
-
|
|
34
|
-
/** The generated files as Map<path, text> - 'llms.txt', then 'llms/<...>.md'
|
|
35
|
-
* when the site needs them - or null when the project has its own
|
|
36
|
-
* llms.txt, which replaces all of it. */
|
|
37
|
-
export async function llmsIndexFiles(): Promise<Map<string, string> | null> {
|
|
38
|
-
const contentDir = process.env.WRITEDOCS_CONTENT_DIR || process.cwd();
|
|
39
|
-
const packageRoot = process.env.WRITEDOCS_PACKAGE_ROOT || process.cwd();
|
|
40
|
-
// A hand-authored llms.txt at the project root (next to writedocs.json)
|
|
41
|
-
// wins outright - same override convention Mintlify documents.
|
|
42
|
-
if (fs.existsSync(path.join(contentDir, 'llms.txt'))) return null;
|
|
43
|
-
|
|
44
|
-
const config = loadDocsConfig(contentDir);
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
const
|
|
48
|
-
|
|
49
|
-
const
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
const
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
// page
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
//
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
.
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
}
|
|
1
|
+
// llms.txt and its child files (/llms/*.md) - the pages an AI tool can
|
|
2
|
+
// discover, in the site's navigation structure. Shared by llms.txt.ts (the
|
|
3
|
+
// root file) and llms/[...path].md.ts (the child files a big site's llms.txt
|
|
4
|
+
// links to), so both render from the same tree in the same run. The
|
|
5
|
+
// structure and the splitting live in lib/llms.js.
|
|
6
|
+
import { getCollection, type CollectionEntry } from 'astro:content';
|
|
7
|
+
import fs from 'node:fs';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import { loadDocsConfig, normalizeEntryId, findAllPages, resolveSiteRoot, fileIdForEntry, contextMenuOptions } from './config';
|
|
10
|
+
import { buildLlmsTree, renderLlmsFiles } from './llms.js';
|
|
11
|
+
import { navigationPageOrder } from './pages.js';
|
|
12
|
+
import { writedocsTempDir } from './writedocs-temp-dir.js';
|
|
13
|
+
|
|
14
|
+
type DocsEntry = CollectionEntry<'pages'> | CollectionEntry<'generatedDocs'>;
|
|
15
|
+
|
|
16
|
+
// Mirrors Mintlify's own llms.txt behavior: a page's frontmatter
|
|
17
|
+
// `description` is cut at the first line break (a multi-paragraph
|
|
18
|
+
// description would blow out a one-line list entry) and at 300 characters,
|
|
19
|
+
// so every entry stays scannable.
|
|
20
|
+
const DESCRIPTION_MAX_CHARS = 300;
|
|
21
|
+
function truncateDescription(description: string | undefined): string | undefined {
|
|
22
|
+
if (!description) return undefined;
|
|
23
|
+
const firstLine = description.split('\n')[0].trim();
|
|
24
|
+
if (!firstLine) return undefined;
|
|
25
|
+
return firstLine.length > DESCRIPTION_MAX_CHARS ? firstLine.slice(0, DESCRIPTION_MAX_CHARS).trimEnd() + '…' : firstLine;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// Most characters one file holds - llms.txt or a child file. The llms.txt
|
|
29
|
+
// spec sets no limit ("small enough to fit in context"); this is Mintlify's,
|
|
30
|
+
// about 25,000 tokens. Past it, sections move into child files instead of
|
|
31
|
+
// pages being dropped.
|
|
32
|
+
export const LLMS_MAX_CHARS = 100_000;
|
|
33
|
+
|
|
34
|
+
/** The generated files as Map<path, text> - 'llms.txt', then 'llms/<...>.md'
|
|
35
|
+
* when the site needs them - or null when the project has its own
|
|
36
|
+
* llms.txt, which replaces all of it. */
|
|
37
|
+
export async function llmsIndexFiles(): Promise<Map<string, string> | null> {
|
|
38
|
+
const contentDir = process.env.WRITEDOCS_CONTENT_DIR || process.cwd();
|
|
39
|
+
const packageRoot = process.env.WRITEDOCS_PACKAGE_ROOT || process.cwd();
|
|
40
|
+
// A hand-authored llms.txt at the project root (next to writedocs.json)
|
|
41
|
+
// wins outright - same override convention Mintlify documents.
|
|
42
|
+
if (fs.existsSync(path.join(contentDir, 'llms.txt'))) return null;
|
|
43
|
+
|
|
44
|
+
const config = loadDocsConfig(contentDir);
|
|
45
|
+
// The site's URL if `domain` is set, else its base ("/docs", or "" at the
|
|
46
|
+
// root) - lib/config.ts.
|
|
47
|
+
const siteRoot = resolveSiteRoot(config);
|
|
48
|
+
|
|
49
|
+
const hasGeneratedDocs = fs.existsSync(path.join(writedocsTempDir(contentDir), 'generated-docs'));
|
|
50
|
+
const hasPages = findAllPages(contentDir).length > 0;
|
|
51
|
+
const [pagesEntries, generatedDocsEntries] = await Promise.all([
|
|
52
|
+
hasPages ? getCollection('pages') : Promise.resolve([]),
|
|
53
|
+
hasGeneratedDocs ? getCollection('generatedDocs') : Promise.resolve([]),
|
|
54
|
+
]);
|
|
55
|
+
const entries: DocsEntry[] = [...pagesEntries, ...generatedDocsEntries];
|
|
56
|
+
|
|
57
|
+
const pages = new Map<string, { title: string; href: string; description?: string; slug: string }>();
|
|
58
|
+
for (const entry of entries) {
|
|
59
|
+
// A page that opted out of search-engine indexing (`seo.noindex`, also
|
|
60
|
+
// left out of sitemap.xml) is left out here too, and a frontmatter `url`
|
|
61
|
+
// page (Mintlify's external link) has no content of its own.
|
|
62
|
+
if (entry.data.seo?.noindex || entry.data.url) continue;
|
|
63
|
+
const slug = normalizeEntryId(entry.id);
|
|
64
|
+
// The .md route when it exists ([...slug].md.ts - unless `contextMenu` is off,
|
|
65
|
+
// and never for an OpenAPI page, which renders from the spec), else the
|
|
66
|
+
// HTML page.
|
|
67
|
+
const hasMarkdownRoute = contextMenuOptions(config.contextMenu).length > 0;
|
|
68
|
+
const href = siteRoot + (hasMarkdownRoute ? `/${slug}.md` : slug === 'index' ? '/' : `/${slug}/`);
|
|
69
|
+
let description = truncateDescription(entry.data.description);
|
|
70
|
+
// Mirrors Mintlify: an OpenAPI operation page's description gets its
|
|
71
|
+
// "METHOD /path" appended - the page itself renders from the spec.
|
|
72
|
+
if (entry.data.openapi) description = description ? `${description} (${entry.data.openapi})` : entry.data.openapi;
|
|
73
|
+
pages.set(fileIdForEntry(contentDir, packageRoot, entry), { title: entry.data.title, href, description, slug });
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const listed = new Set(navigationPageOrder(config.navigation));
|
|
77
|
+
const unlisted = [...pages.entries()]
|
|
78
|
+
.filter(([id]) => !listed.has(id))
|
|
79
|
+
.sort((a, b) => a[1].slug.localeCompare(b[1].slug))
|
|
80
|
+
.map(([id]) => id);
|
|
81
|
+
const tree = buildLlmsTree(config.navigation, (id: string) => pages.get(id) ?? null, unlisted);
|
|
82
|
+
|
|
83
|
+
return renderLlmsFiles({
|
|
84
|
+
name: config.name,
|
|
85
|
+
description: config.description,
|
|
86
|
+
tree,
|
|
87
|
+
maxChars: LLMS_MAX_CHARS,
|
|
88
|
+
urlFor: (file: string) => `${siteRoot}/${file}`,
|
|
89
|
+
});
|
|
90
|
+
}
|
|
@@ -1,60 +1,65 @@
|
|
|
1
|
-
// `writedocs dev`: the site's MCP server at /mcp, as the build serves it - the
|
|
2
|
-
// same handler (src/mcp/server.js), answering from the dev server's own
|
|
3
|
-
// /mcp-index.json, so an edit shows up on the next request. Lets an author
|
|
4
|
-
// point an MCP client at http://localhost:4321/mcp before deploying.
|
|
5
|
-
import { handleMcpHttp } from '../mcp/server.js';
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
req.on('
|
|
12
|
-
req.on('
|
|
13
|
-
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
const
|
|
31
|
-
const
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
}
|
|
1
|
+
// `writedocs dev`: the site's MCP server at /mcp, as the build serves it - the
|
|
2
|
+
// same handler (src/mcp/server.js), answering from the dev server's own
|
|
3
|
+
// /mcp-index.json, so an edit shows up on the next request. Lets an author
|
|
4
|
+
// point an MCP client at http://localhost:4321/mcp before deploying.
|
|
5
|
+
import { handleMcpHttp } from '../mcp/server.js';
|
|
6
|
+
import { withoutBase } from './base-path.js';
|
|
7
|
+
|
|
8
|
+
function readBody(req) {
|
|
9
|
+
return new Promise((resolve, reject) => {
|
|
10
|
+
const chunks = [];
|
|
11
|
+
req.on('data', (chunk) => chunks.push(chunk));
|
|
12
|
+
req.on('end', () => resolve(Buffer.concat(chunks)));
|
|
13
|
+
req.on('error', reject);
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
// `basePath`: writedocs.json's ("" or "/docs") - the server is at /docs/mcp.
|
|
18
|
+
// Astro's dev server takes the base off req.url before this middleware runs
|
|
19
|
+
// (its devBaseMiddleware), so /docs/mcp and a bare /mcp would look the same
|
|
20
|
+
// there: the path asked for is req.originalUrl.
|
|
21
|
+
export function mcpDevServer({ version, basePath = '' }) {
|
|
22
|
+
return {
|
|
23
|
+
name: 'writedocs-mcp-dev',
|
|
24
|
+
hooks: {
|
|
25
|
+
'astro:server:setup': ({ server }) => {
|
|
26
|
+
server.middlewares.use(async (req, res, next) => {
|
|
27
|
+
const pathname = withoutBase(basePath, (req.originalUrl ?? req.url ?? '').split('?')[0]);
|
|
28
|
+
if (pathname !== '/mcp' && pathname !== '/mcp/') return next();
|
|
29
|
+
try {
|
|
30
|
+
const origin = `http://${req.headers.host}`;
|
|
31
|
+
const headers = new Headers();
|
|
32
|
+
for (const [key, value] of Object.entries(req.headers)) {
|
|
33
|
+
if (typeof value === 'string') headers.set(key, value);
|
|
34
|
+
}
|
|
35
|
+
const body = req.method === 'POST' ? await readBody(req) : undefined;
|
|
36
|
+
const request = new Request(origin + (req.originalUrl ?? req.url), { method: req.method, headers, body });
|
|
37
|
+
let missing = false;
|
|
38
|
+
const response = await handleMcpHttp(request, {
|
|
39
|
+
version,
|
|
40
|
+
loadIndex: async () => {
|
|
41
|
+
const index = await fetch(`${origin}${basePath}/mcp-index.json`);
|
|
42
|
+
if (!index.ok) {
|
|
43
|
+
missing = true;
|
|
44
|
+
return { meta: {}, docs: [] };
|
|
45
|
+
}
|
|
46
|
+
return index.json();
|
|
47
|
+
},
|
|
48
|
+
});
|
|
49
|
+
if (missing) {
|
|
50
|
+
res.statusCode = 404;
|
|
51
|
+
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
|
|
52
|
+
res.end('No MCP server: writedocs.json has "mcp": false.');
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
res.statusCode = response.status;
|
|
56
|
+
response.headers.forEach((value, key) => res.setHeader(key, value));
|
|
57
|
+
res.end(Buffer.from(await response.arrayBuffer()));
|
|
58
|
+
} catch (err) {
|
|
59
|
+
next(err);
|
|
60
|
+
}
|
|
61
|
+
});
|
|
62
|
+
},
|
|
63
|
+
},
|
|
64
|
+
};
|
|
65
|
+
}
|