-
Notifications
You must be signed in to change notification settings - Fork 258
Expand file tree
/
Copy pathtypedoc-plugin-seo.mjs
More file actions
315 lines (274 loc) · 9.91 KB
/
typedoc-plugin-seo.mjs
File metadata and controls
315 lines (274 loc) · 9.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
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
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
/**
* TypeDoc plugin that adds SEO metadata to generated pages.
*
* - Normalizes document page filenames to lowercase-hyphenated slugs
* - Injects JSON-LD (TechArticle / WebPage) structured data for search crawlers
* - Adds per-page meta description tags extracted from page content
* - Copies favicons to the output directory
*/
import { Renderer } from "typedoc";
import fs from "node:fs";
import path from "node:path";
import zlib from "node:zlib";
import * as htmlparser2 from "htmlparser2";
const SITE_NAME = "MCP Apps";
/**
* Convert a TypeDoc-generated document filename to a lowercase hyphenated slug.
* e.g. "CSP_and_CORS.html" → "csp-and-cors.html"
* "Testing_MCP_Apps.html" → "testing-mcp-apps.html"
* @param {string} filename
* @returns {string}
*/
function toSlug(filename) {
return filename
.replace(/\.html$/, "")
.replace(/_/g, "-")
.toLowerCase()
.concat(".html");
}
/**
* Extract a plain-text description from the rendered HTML body.
* Parses the first content paragraph using htmlparser2 and truncates.
* @param {string} html
* @returns {string}
*/
function extractDescription(html) {
// Find the main content area
const contentMatch = html.match(
/<div class="tsd-panel tsd-typography">([\s\S]*?)<\/div>\s*<\/div>/,
);
if (!contentMatch) return "";
const content = contentMatch[1];
// Find first <p> that has real content (skip headings, code blocks, lists)
const paragraphs = content.match(/<p>([^<][\s\S]*?)<\/p>/g);
if (!paragraphs) return "";
for (const p of paragraphs) {
const text = htmlparser2
.parseDocument(p)
.children.map((node) => htmlparser2.DomUtils.textContent(node))
.join("")
.replace(/\s+/g, " ")
.trim();
// Skip very short or code-heavy paragraphs
if (text.length > 40) {
return text.length > 160 ? text.slice(0, 157) + "..." : text;
}
}
return "";
}
/**
* Extract the page title from the <title> tag.
* @param {string} html
* @returns {string}
*/
function extractTitle(html) {
const match = html.match(/<title>([^<]+)<\/title>/);
return match ? match[1] : SITE_NAME;
}
/**
* Determine if a page is a document (guide) or API reference page.
* @param {string} url
* @returns {boolean}
*/
function isDocumentPage(url) {
return url.includes("documents/");
}
/**
* Build a JSON-LD structured data object for the page.
* @param {object} options
* @param {string} options.title
* @param {string} options.description
* @param {string} options.url
* @param {boolean} options.isDocument
* @returns {object}
*/
function buildJsonLd({ title, description, url, isDocument }) {
return {
"@context": "https://schema.org",
"@type": isDocument ? "TechArticle" : "WebPage",
name: title,
headline: title,
...(description && { description }),
...(url && { url }),
isPartOf: {
"@type": "WebSite",
name: SITE_NAME,
url: "https://apps.extensions.modelcontextprotocol.io/",
},
};
}
/**
* TypeDoc plugin entry point.
* @param {import('typedoc').Application} app
*/
export function load(app) {
const hostedBaseUrl = app.options.getValue("hostedBaseUrl") || "";
// --- Per-page: inject JSON-LD, meta descriptions, and favicons ---
app.renderer.on(Renderer.EVENT_END_PAGE, (page) => {
if (!page.contents) return;
const title = extractTitle(page.contents);
// Prefer frontmatter description, fall back to auto-extraction
const frontmatterDesc =
page.model?.isDocument?.() && page.model.frontmatter?.description
? String(page.model.frontmatter.description)
: "";
const description = frontmatterDesc || extractDescription(page.contents);
const fullUrl = hostedBaseUrl
? `${hostedBaseUrl.replace(/\/$/, "")}/${page.url}`
: "";
// Build JSON-LD
const jsonLd = buildJsonLd({
title,
description,
url: fullUrl,
isDocument: isDocumentPage(page.url),
});
const jsonLdScript = `<script type="application/ld+json">${JSON.stringify(jsonLd)}</script>`;
// Build meta description tag (replace the generic one if present)
const metaDescription = description
? `<meta name="description" content="${description.replace(/"/g, """)}"/>`
: "";
// Replace existing generic meta description
if (metaDescription) {
page.contents = page.contents.replace(
/<meta name="description" content="Documentation for [^"]*"\/>/,
metaDescription,
);
}
// Build favicon tags with correct relative path
const depth = page.url.split("/").length - 1;
const base = depth > 0 ? "../".repeat(depth) : "./";
const faviconTags = [
`<link rel="icon" href="${base}favicons/favicon-32x32.png" type="image/png" sizes="32x32" media="(prefers-color-scheme: light)"/>`,
`<link rel="icon" href="${base}favicons/favicon-16x16.png" type="image/png" sizes="16x16" media="(prefers-color-scheme: light)"/>`,
`<link rel="shortcut icon" href="${base}favicons/favicon.ico" type="image/x-icon" media="(prefers-color-scheme: light)"/>`,
`<link rel="icon" href="${base}favicons/favicon-dark-32x32.png" type="image/png" sizes="32x32" media="(prefers-color-scheme: dark)"/>`,
`<link rel="icon" href="${base}favicons/favicon-dark-16x16.png" type="image/png" sizes="16x16" media="(prefers-color-scheme: dark)"/>`,
`<link rel="shortcut icon" href="${base}favicons/favicon-dark.ico" type="image/x-icon" media="(prefers-color-scheme: dark)"/>`,
`<link rel="apple-touch-icon" href="${base}favicons/apple-touch-icon.png" type="image/png" sizes="180x180"/>`,
].join("\n");
// Inject favicons and JSON-LD before </head>
const headInjections = [faviconTags, jsonLdScript]
.filter(Boolean)
.join("\n");
page.contents = page.contents.replace(
"</head>",
headInjections + "\n</head>",
);
});
// --- Post-render: copy favicons + rename document slugs ---
app.renderer.on(Renderer.EVENT_END, (event) => {
const outDir = event.outputDirectory;
// Copy favicons to output directory
const srcFavicons = path.join(path.dirname(outDir), "favicons");
const destFavicons = path.join(outDir, "favicons");
if (fs.existsSync(srcFavicons)) {
if (!fs.existsSync(destFavicons)) fs.mkdirSync(destFavicons);
for (const file of fs.readdirSync(srcFavicons)) {
fs.copyFileSync(
path.join(srcFavicons, file),
path.join(destFavicons, file),
);
}
}
const docsDir = path.join(outDir, "documents");
if (!fs.existsSync(docsDir)) return;
// Build rename map: old filename → new slug
const renameMap = new Map();
for (const file of fs.readdirSync(docsDir)) {
if (!file.endsWith(".html")) continue;
const slug = toSlug(file);
if (slug !== file) {
renameMap.set(file, slug);
}
}
if (renameMap.size === 0) return;
// Rename the files
for (const [oldName, newName] of renameMap) {
fs.renameSync(path.join(docsDir, oldName), path.join(docsDir, newName));
}
// Build link replacement patterns (documents/OldName.html → documents/new-name.html)
const replacements = [...renameMap.entries()].map(([oldName, newName]) => ({
old: `documents/${oldName}`,
new: `documents/${newName}`,
}));
// Update all HTML files in the output directory
updateLinksRecursive(outDir, replacements);
// Update compressed JS data files (navigation + search index)
updateCompressedJsData(
path.join(outDir, "assets", "navigation.js"),
"navigationData",
replacements,
);
updateCompressedJsData(
path.join(outDir, "assets", "search.js"),
"searchData",
replacements,
);
// Update sitemap.xml
const sitemapPath = path.join(outDir, "sitemap.xml");
if (fs.existsSync(sitemapPath)) {
let sitemap = fs.readFileSync(sitemapPath, "utf8");
for (const r of replacements) {
sitemap = sitemap.replaceAll(r.old, r.new);
}
fs.writeFileSync(sitemapPath, sitemap);
}
});
}
/**
* Decompress a TypeDoc JS data file, replace document slugs, and recompress.
* TypeDoc stores navigation and search data as deflate-compressed base64.
* @param {string} filePath
* @param {string} varName - JS variable name (e.g. "navigationData", "searchData")
* @param {Array<{old: string, new: string}>} replacements
*/
function updateCompressedJsData(filePath, varName, replacements) {
if (!fs.existsSync(filePath)) return;
let content = fs.readFileSync(filePath, "utf8");
const pattern = new RegExp(`window\\.${varName} = "(.+)"`);
const match = content.match(pattern);
if (!match) return;
// Decompress
const buf = Buffer.from(match[1], "base64");
let json = zlib.inflateSync(buf).toString();
// Replace slugs
let changed = false;
for (const r of replacements) {
if (json.includes(r.old)) {
json = json.replaceAll(r.old, r.new);
changed = true;
}
}
if (!changed) return;
// Recompress and write
const compressed = zlib.deflateSync(json);
const encoded = compressed.toString("base64");
content = content.replace(pattern, `window.${varName} = "${encoded}"`);
fs.writeFileSync(filePath, content);
}
/**
* Recursively update links in all HTML files under a directory.
* @param {string} dir
* @param {Array<{old: string, new: string}>} replacements
*/
function updateLinksRecursive(dir, replacements) {
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
const fullPath = path.join(dir, entry.name);
if (entry.isDirectory()) {
updateLinksRecursive(fullPath, replacements);
} else if (entry.name.endsWith(".html") || entry.name.endsWith(".js")) {
let content = fs.readFileSync(fullPath, "utf8");
let changed = false;
for (const r of replacements) {
if (content.includes(r.old)) {
content = content.replaceAll(r.old, r.new);
changed = true;
}
}
if (changed) {
fs.writeFileSync(fullPath, content);
}
}
}
}