-
Notifications
You must be signed in to change notification settings - Fork 0
/
mod.ts
390 lines (341 loc) · 11.1 KB
/
mod.ts
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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
import { join, SEPARATOR } from 'jsr:@std/[email protected]'
import { ensureFile, exists } from 'jsr:@std/[email protected]'
/**
* Represents a single entry in the sitemap with a location and last modified date.
*/
export interface SiteMapEntry {
/** The location (URL) of the sitemap entry */
loc: string
/** The last modified date for the sitemap entry in ISO string format */
lastmod: string
}
/**
* A list of sitemap entries.
*/
export type Sitemap = SiteMapEntry[]
/**
* Options for configuring sitemap generation, including languages and default language.
*/
export interface SiteMapOptions {
/** Array of languages supported for the sitemap entries */
languages?: string[]
/** The default language for the sitemap if no specific language is specified */
defaultLanguage?: string
}
/**
* Configuration options for saving the sitemap and robots.txt.
*/
export interface SitemapConfig {
/** The base URL of the website (e.g., 'https://example.com') */
basename: string
/** Directory containing route files */
distDirectory: string
/** Directory containing posts in markdown format */
postsDirectory: string
/** Path to save the generated sitemap XML */
sitemapPath: string
/** Path to save the generated robots.txt */
robotsPath: string
/** Additional options for sitemap generation, including languages */
options?: SiteMapOptions
}
/**
* Generates a sitemap XML string from specified directories and a base URL.
* @param basename - The base URL of the website (e.g., 'https://example.com')
* @param distDirectory - The directory containing route files
* @param postsDirectory - The directory containing posts in markdown format
* @param options - Options for sitemap generation, including languages and default language
* @returns The generated sitemap as an XML string
*/
export async function generateSitemapXML(
basename: string,
distDirectory: string,
postsDirectory: string,
options: SiteMapOptions = {},
): Promise<string> {
const routesSitemap = await generateSitemap(basename, distDirectory, options)
const postsSitemap = await generatePostsSitemap(
basename,
postsDirectory,
options,
)
// Combine both sitemaps
const combinedSitemap = [...routesSitemap, ...postsSitemap]
// Remove duplicates and keep only the latest `lastmod` for each `loc`
const sitemapMap = new Map<string, string>()
for (const entry of combinedSitemap) {
const { loc, lastmod } = entry
const existingLastmod = sitemapMap.get(loc)
if (!existingLastmod || new Date(lastmod) > new Date(existingLastmod)) {
sitemapMap.set(loc, lastmod)
}
}
// Convert Map to array for XML generation
const uniqueSitemap = Array.from(sitemapMap.entries()).map(
([loc, lastmod]) => ({ loc, lastmod }),
)
return sitemapToXML(uniqueSitemap)
}
/**
* Generates content for the robots.txt file, including site and sitemap details.
* @param domain - The domain of the website (e.g., 'example.com')
* @returns The generated robots.txt file content
*/
function generateRobotsTxt(domain: string): string {
return `# *
User-agent: *
Allow: /
# Host
Host: https://${domain}
# Sitemaps
Sitemap: https://${domain}/sitemap.xml
`
}
/**
* Saves the generated sitemap XML and robots.txt files to specified file paths.
* @param config - Configuration object for sitemap and robots.txt generation
*/
export async function saveSitemapAndRobots(
config: SitemapConfig,
): Promise<void> {
const {
basename,
distDirectory,
postsDirectory,
sitemapPath,
robotsPath,
options = {},
} = config
const domain = new URL(basename).hostname
const sitemapXML = await generateSitemapXML(
basename,
distDirectory,
postsDirectory,
options,
)
const robotsTxt = generateRobotsTxt(domain)
await ensureFile(sitemapPath)
await Deno.writeTextFile(sitemapPath, sitemapXML)
await ensureFile(robotsPath)
await Deno.writeTextFile(robotsPath, robotsTxt)
}
/**
* Converts an array of strings to an object where each string becomes a key with a default value of 1.
* @param arr - Array of strings
* @returns Object with each string in arr as a key set to 1
*/
function arrayToObject(arr: string[]): Record<string, number> {
const result: Record<string, number> = {}
for (const segment of arr) {
result[segment] = 1
}
return result
}
/**
* Filters path segments based on specific criteria for sitemap inclusion.
* Sets the value to 0 for paths containing grouping indicators like parentheses or square brackets.
* @param pathMap - Object containing path segments with inclusion flags
* @returns Filtered pathMap with updated inclusion flags
*/
function checkSegments(
pathMap: Record<string, number>,
): Record<string, number> {
for (const key in pathMap) {
if (key.startsWith('(') && key.endsWith(')')) {
pathMap[key] = 0
}
if (key.startsWith('[') && key.endsWith(']')) {
pathMap[key] = 0
}
if (key === 'routes') {
pathMap[key] = 0
}
}
return pathMap
}
/**
* Generates sitemap entries for static routes, excluding dynamic and grouping directories.
* Uses a Map to ensure unique `loc` values in the sitemap, keeping only the most recent `lastmod` value.
* @param basename - The base URL of the website (e.g., 'https://example.com')
* @param distDirectory - Directory containing route files
* @param options - Options for sitemap generation, including languages and default language
* @returns Array of sitemap entries
*/
async function generateSitemap(
basename: string,
distDirectory: string,
options: SiteMapOptions,
): Promise<Sitemap> {
const sitemapMap = new Map<string, string>() // Key: loc, Value: lastmod
const pathMap: Record<string, number> = {}
function processPathSegments(path: string): void {
if (!path.endsWith('.tsx')) return
pathMap[path] = 1
if (path.includes('_')) {
pathMap[path] = 0
return
}
if (path.includes('[...slug]')) {
pathMap[path] = 0
return
}
}
async function addDirectory(directory: string) {
for await (const path of stableRecurseFiles(directory)) {
processPathSegments(path)
}
}
await addDirectory(distDirectory)
for (const path in pathMap) {
if (pathMap[path] === 1) {
const filePath = join(path)
if (!(await exists(filePath))) {
continue
}
const { mtime } = await Deno.stat(filePath)
const pathSegments = path.split(SEPARATOR)
const segCheckObj = arrayToObject(pathSegments)
const checkedSegments = checkSegments(segCheckObj)
const neededSegmentsPath = pathSegments
.filter((segment) => checkedSegments[segment] === 1)
.join('/')
const cleanedPath = neededSegmentsPath.replace(/\.tsx$/, '').replace(
/\index$/,
'',
)
options.languages?.forEach((lang) => {
const loc = `${basename}/${lang}${cleanedPath}`
const lastmod = (mtime ?? new Date()).toISOString()
// Check for existing loc and update lastmod if new date is more recent
const existingLastmod = sitemapMap.get(loc)
if (!existingLastmod || new Date(lastmod) > new Date(existingLastmod)) {
sitemapMap.set(loc, lastmod)
}
})
}
}
// Convert Map to Sitemap array
return Array.from(sitemapMap.entries()).map(([loc, lastmod]) => ({
loc,
lastmod,
}))
}
/**
* Recursively searches for a folder with a specific name within a given directory or its subdirectories.
* @param baseDirectory - The directory to start searching within
* @param targetFolderName - The name of the folder to search for
* @returns The path to the folder if it exists in any subdirectory, otherwise null
*/
async function findFolderPathRecursively(
baseDirectory: string,
targetFolderName: string,
): Promise<string | null> {
for await (const entry of Deno.readDir(baseDirectory)) {
const entryPath = `${baseDirectory}/${entry.name}`
if (entry.isDirectory) {
if (entry.name === targetFolderName) {
return entryPath
} else {
const foundInSubDir = await findFolderPathRecursively(
entryPath,
targetFolderName,
)
if (foundInSubDir) return foundInSubDir
}
}
}
return null
}
/**
* Generates sitemap entries for markdown posts, respecting language settings.
* Checks for existing routes and builds a path for each post.
* @param basename - The base URL
* @param postsDirectory - Directory containing post markdown files
* @param options - Options for sitemap generation, including languages
* @returns Array of sitemap entries for posts
*/
async function generatePostsSitemap(
basename: string,
postsDirectory: string,
options: SiteMapOptions,
): Promise<Sitemap> {
const sitemap: Sitemap = []
const languages = options.languages || []
if (!(await exists(postsDirectory))) return sitemap
async function addMarkdownFile(path: string) {
const relPath = path.replace(/\.md$/, '')
const segments = relPath.split(SEPARATOR)
const postType = segments[1]
const postRoute = await findFolderPathRecursively(
'./routes',
postType,
)
if (!postRoute) return
const routeSegments = postRoute.replace('./routes', '').split(
SEPARATOR,
)
const segCheckObj = arrayToObject(routeSegments)
const checkedSegments = checkSegments(segCheckObj)
const neededSegmentsPath = routeSegments
.filter((segment) => checkedSegments[segment] === 1)
.join('/')
const slugSegmentsPath = segments.slice(3).join('/')
const pathname = neededSegmentsPath + '/' + slugSegmentsPath
const urlPaths = languages.length > 0
? languages.map((lang) => `/${lang}${pathname}`)
: [pathname]
for (const urlPath of urlPaths) {
const { mtime } = await Deno.stat(path)
sitemap.push({
loc: basename.replace(/\/+$/, '') + urlPath,
lastmod: (mtime ?? new Date()).toISOString(),
})
}
}
for await (const path of stableRecurseFiles(postsDirectory)) {
if (path.endsWith('.md')) {
await addMarkdownFile(path)
}
}
return sitemap
}
/**
* Recursively iterates through a directory to retrieve all file paths in a stable, sorted order.
* @param directory - Directory path to recurse
* @returns Generator of file paths
*/
async function* stableRecurseFiles(directory: string): AsyncGenerator<string> {
const itr = Deno.readDir(directory)
const files: Deno.DirEntry[] = []
for await (const entry of itr) {
files.push(entry)
}
const sorted = files.sort(({ name: n0 }, { name: n1 }) =>
n0.localeCompare(n1)
)
for (const entry of sorted) {
const path = join(directory, entry.name)
if (entry.isFile) {
yield path
} else if (entry.isDirectory) {
yield* stableRecurseFiles(path)
}
}
}
/**
* Converts a Sitemap array to an XML string in the required format.
* @param sitemap - Array of sitemap entries
* @returns Generated XML string
*/
function sitemapToXML(sitemap: Sitemap): string {
return `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
${
sitemap
.map(({ loc, lastmod }) =>
`<url><loc>${loc}</loc><lastmod>${lastmod}</lastmod></url>`
)
.join('\n')
}
</urlset>`
}