-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcloudflare-worker.js
181 lines (162 loc) · 6.76 KB
/
cloudflare-worker.js
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
async function generateOGTags(url, SITE_URL, DOCS_URL) {
const params = new URLSearchParams(url.search);
let slug = '';
if (params.has('')) {
slug = params.get('');
} else {
for (const [key] of params) {
slug = key;
break;
}
}
const indexResponse = await fetch(`${DOCS_URL}/index.json`);
const indexData = await indexResponse.json();
const defaultPage = indexData.defaultPage || 'welcome';
slug = slug || defaultPage;
function findDocumentBySlug(documents, targetSlug) {
for (const doc of documents) {
if (doc.slug === targetSlug) return doc;
if (doc.type === 'folder' && doc.items) {
const found = findDocumentBySlug(doc.items, targetSlug);
if (found) return found;
}
}
return null;
}
const currentDoc = findDocumentBySlug(indexData.documents, slug);
let description = indexData.metadata?.description || 'Documentation reader';
let thumbnail = indexData.metadata?.thumbnail || 'img/og-image.png';
if (currentDoc) {
try {
const docResponse = await fetch(`${DOCS_URL}/${currentDoc.path}`);
const content = await docResponse.text();
const metadataMatch = content.match(/---\n([\s\S]*?)\n---/);
if (metadataMatch) {
const metadataStr = metadataMatch[1];
console.log(metadataMatch);
const thumbnailMatch = metadataStr.match(/thumbnail:\s*(.*)/);
if (thumbnailMatch) {
thumbnail = "docs/" + thumbnailMatch[1].trim();
}
const descriptionMatch = metadataStr.match(/description:\s*(.*)/);
if (descriptionMatch) {
description = descriptionMatch[1].trim();
}
if (!description) {
// Get content after metadata
const afterMetadata = content.substring(
metadataMatch.index + metadataMatch[0].length
);
const paragraphMatch = afterMetadata
.split('\n\n')
.find(p => p.trim() && !p.startsWith('#'));
if (paragraphMatch) {
description = paragraphMatch.trim().replace(/\[|\]|\(|\)/g, '').substring(0, 160);
}
}
}
} catch (e) {
console.error('Error fetching document:', e);
}
}
const site = new URL(SITE_URL);
site.pathname += (url.pathname === '/' ? '' : url.pathname);
site.search = url.search;
site.hash = url.hash;
const title = currentDoc?.title || 'Documentation';
const ogImage = new URL(thumbnail, SITE_URL).href;
const siteName = indexData.metadata?.site_name || 'Documentation';
return `
<meta property="og:title" content="${title} - ${siteName}">
<meta property="og:description" content="${description}">
<meta property="og:type" content="article">
<meta property="og:url" content="${site.href}">
<meta property="og:image" content="${ogImage}">
<meta property="og:site_name" content="${siteName}">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="${title} - ${siteName}">
<meta name="twitter:description" content="${description}">
<meta name="twitter:image" content="${ogImage}">`;
}
async function handleRequest(request, SITE_URL, DOCS_URL) {
const url = new URL(request.url);
const siteUrlObj = new URL(SITE_URL);
const pathPrefix = siteUrlObj.pathname;
const strippedPath = url.pathname.startsWith(pathPrefix)
? url.pathname.slice(pathPrefix.length - 1)
: url.pathname;
const docUrl = new URL(DOCS_URL);
docUrl.pathname = strippedPath;
docUrl.search = url.search;
docUrl.hash = url.hash;
const response = await fetch(docUrl.toString(), request);
if (url.pathname === pathPrefix || url.pathname === '/') {
const contentType = response.headers.get('content-type') || '';
if (contentType.includes('text/html')) {
let html = await response.text();
const ogTags = await generateOGTags(url, SITE_URL, DOCS_URL);
html = html.replace('<!--ogmetadata-->', ogTags);
return new Response(html, {
headers: {
'content-type': 'text/html;charset=UTF-8',
...Object.fromEntries(response.headers)
}
});
}
}
return new Response(response.body, response);
}
async function generateSitemap(DOCS_URL, SITE_URL) {
const indexResponse = await fetch(`${DOCS_URL}/index.json`);
const indexData = await indexResponse.json();
function collectUrls(documents) {
let urls = [];
for (const doc of documents) {
if (doc.slug) {
const url = new URL(SITE_URL);
// Fix: Directly append the slug to search without using searchParams
url.search = `?${doc.slug}`; // This creates clean URLs without =
urls.push({
loc: url.href,
lastmod: doc.lastModified || new Date().toISOString().split('T')[0],
priority: doc.type === 'folder' ? '0.8' : '0.6'
});
}
if (doc.type === 'folder' && doc.items) {
urls = urls.concat(collectUrls(doc.items));
}
}
return urls;
}
const urls = collectUrls(indexData.documents);
const sitemap = `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9
http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
${urls.map(url => `
<url>
<loc>${url.loc}</loc>
<lastmod>${url.lastmod}</lastmod>
<priority>${url.priority}</priority>
</url>`).join('')}
</urlset>`;
return new Response(sitemap.trim(), {
headers: {
'Content-Type': 'application/xml',
'Cache-Control': 'public, max-age=3600'
}
});
}
export default {
async fetch(request, env, ctx) {
const SITE_URL = env.SITE_URL;
const DOCS_URL = env.DOCS_URL;
const url = new URL(request.url);
// Fix: Check if path ends with sitemap.xml regardless of base path
if (url.pathname === '/sitemap.xml' || url.pathname.endsWith('/sitemap.xml')) {
return generateSitemap(DOCS_URL, SITE_URL);
}
return handleRequest(request, SITE_URL, DOCS_URL);
}
};