-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsitemap.mts
293 lines (258 loc) · 7.87 KB
/
sitemap.mts
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
import { XMLParser, XMLBuilder, XMLValidator } from "fast-xml-parser";
import { URL } from "node:url";
import { dirname } from "node:path";
import { promisify } from "node:util";
import { gunzip } from "node:zlib";
import { globalHeaders } from "./global.mjs";
import { httpHeaderParse, parsedHTTPHeaders } from './httpHeaderParse.mjs';
type sitemapType = "index" | "xml" | "rss" | "atom" | "text";
interface parsedSitemapEntry {
url : string,
lastModified? : number | undefined,
changeFrequency? : "always" | "hourly" | "daily" | "weekly" | "monthly" | "yearly" | "never" | undefined,
priority? : number,
languages? : Map<string, string>,
content? : Array<parsedSitemapEntry>
};
type parsedSitemap = Array<parsedSitemapEntry>;
const doGunzip = promisify(gunzip);
const alwaysArray = [
"sitemapindex.sitemap",
"sitemapindex.sitemap.xhtml:link",
"urlset.url",
"urlset.url.xhtml:link",
"channel.item",
"feed.entry"
];
const parserOpts = {
ignoreAttributes: false,
allowBooleanAttributes: true,
attributeNamePrefix: "@_",
isArray: (name : string, jpath : string, isLeafNode : boolean, isAttribute : boolean) : boolean => { return ((alwaysArray.indexOf(jpath) !== -1) ? true : false); }
};
const parser : XMLParser = new XMLParser(parserOpts);
function parseSitemapIndex(rawObject : {
[key : string] : any
}) : parsedSitemap {
let result : parsedSitemap = [];
if (rawObject.sitemapindex.sitemap.length > 50000) {
throw new RangeError("Sitemap is too large.");
}
for (let sitemap of rawObject.sitemapindex.sitemap) {
let tempRes : parsedSitemapEntry = {
url: sitemap.loc,
lastModified: sitemap.lastmod !== undefined ? Date.parse(sitemap.lastmod) : undefined
};
if (sitemap["xhtml:link"]) {
tempRes.languages = new Map<string, string>();
for (let lang of sitemap["xhtml:link"]) {
tempRes.languages.set(lang["@_hreflang"], lang["@_href"]);
}
}
result.push(tempRes);
}
return result;
}
function parseXmlSitemap (rawObject : {
[key : string] : any
}) : parsedSitemap {
let result : parsedSitemap = [];
if (rawObject.urlset.url.length > 50000) {
throw new RangeError("Sitemap is too large.");
}
for (let url of rawObject.urlset.url) {
let tempRes : parsedSitemapEntry = {
url: url.loc,
lastModified: url.lastmod !== undefined ? Date.parse(url.lastmod) : undefined,
changeFrequency: url.changefreq !== undefined ? url.changefreq : undefined,
priority: url.priority !== undefined ? url.priority : undefined
};
if (url["xhtml:link"]) {
tempRes.languages = new Map<string, string>();
for (let lang of url["xhtml:link"]) {
tempRes.languages.set(lang["@_hreflang"], lang["@_href"]);
}
}
result.push(tempRes);
}
return result;
}
function parseRssSitemap (rawObject : {
[key : string] : any
}) : parsedSitemap {
let result : parsedSitemap = [];
if (rawObject.channel.entry.length > 50000) {
throw new RangeError("Sitemap is too large.");
}
for (let item of rawObject.channel.item) {
result.push({
url: item.link,
lastModified: item.pubdate !== undefined ? Date.parse(item.pubdate) : undefined
});
}
return result;
}
function parseAtomSitemap (rawObject : {
[key : string] : any
}) : parsedSitemap {
let result : parsedSitemap = [];
if (rawObject.feed.entry.length > 50000) {
throw new RangeError("Sitemap is too large.");
}
for (let entry of rawObject.feed.entry) {
if (entry.link === undefined) {
continue;
}
result.push({
url: entry.link,
lastModified: Date.parse(entry.updated)
});
}
return result;
}
function parseTextSitemap (text : string) : parsedSitemap {
let result : parsedSitemap = [];
const lines = text.split("\n");
if (lines.length > 50000) {
throw new RangeError("Sitemap is too large.");
}
for (let line of lines) {
line = line.trim();
if (line !== "") {
result.push({
url: line
});
}
}
return result;
}
async function getSitemap(url : URL) : Promise<parsedSitemap> {
try {
const headers : Headers = new Headers(globalHeaders);
const options = {
headers: headers
};
const res = await fetch(url.href, options);
const params : parsedHTTPHeaders = httpHeaderParse(res.headers.get("Content-Type") ?? "");
const contentType = params[params.length - 1].mainParam ?? "application/xml";
let charset : BufferEncoding = "utf-8";
for (let line of params) {
if (line.params.has("charset")) switch (line.params.get("charset") ?? "") {
case 'ascii':
charset = "ascii";
break;
case 'utf8': // pass
case 'utf-8':
charset = "utf8";
break;
case 'utf16le':
charset = "ascii";
break;
case 'ucs2': // pass
case 'ucs-2':
charset = "ucs2";
break;
case 'base64':
charset = "base64";
break;
case 'latin1':
charset = "ascii";
break;
case 'binary':
charset = "binary";
break;
case 'hex':
charset = "hex";
break;
};
}
let result : parsedSitemap;
let sitemap : {
[key : string] : any
};
let rawSitemap : string = "";
switch (contentType) {
case 'application/gzip':
// pass
case 'application/x-gzip':
const dec = new TextDecoder(charset);
const compressed : ArrayBuffer = await res.arrayBuffer();
if (compressed.byteLength > 52428800) {
throw new RangeError("Sitemap is too large.");
}
rawSitemap = dec.decode(await doGunzip(compressed));
// pass
case 'application/xml':
// pass
case 'text/xml':
rawSitemap = rawSitemap !== "" ? rawSitemap : await res.text();
if (Buffer.byteLength(rawSitemap, charset) > 52428800) {
throw new RangeError("Sitemap is too large.");
}
sitemap = parser.parse(rawSitemap);
if (sitemap.sitemapindex !== undefined) {
result = parseSitemapIndex(sitemap);
for (let i = 0; i < result.length; i++) {
result[i].content = await getSitemap(new URL(result[i].url));
}
result = sitemapBadUrls(url, result);
result = getIndexContent(result);
return result;
} else if (sitemap.urlset !== undefined) {
result = parseXmlSitemap(sitemap);
} else if (sitemap.rss !== undefined) {
result = parseRssSitemap(sitemap);
} else if (sitemap.feed !== undefined) {
result = parseAtomSitemap(sitemap);
} else {
throw new RangeError("Unknown XML sitemap format");
}
break;
case 'text/plain':
rawSitemap = await res.text();
if (Buffer.byteLength(rawSitemap, charset) > 52428800) {
throw new RangeError("Sitemap is too large.");
}
result = parseTextSitemap(rawSitemap);
break;
default:
throw new RangeError(`Unknown Content-Type "${contentType}"`);
}
result = sitemapBadUrls(url, result);
return result;
} catch (err) {
throw err;
}
}
function sitemapBadUrls(url : URL, sitemap : any) {
let result = [];
const siteBaseUrl = url.origin + dirname(url.pathname);
for (let entry of sitemap) {
const url = new URL(entry.url);
const entryBaseUrl = url.origin + dirname(url.pathname);
if (entryBaseUrl.startsWith(siteBaseUrl)) {
if (entry.content !== undefined) {
entry.content = sitemapBadUrls(url, entry.content);
}
result.push(entry);
} else {
// console.error(`Site-Wide base URL: ${siteBaseUrl}\nEntry base URL: ${entryBaseUrl}`);
}
}
return result;
}
function getIndexContent(index : parsedSitemap) : parsedSitemap {
let result : parsedSitemap = [];
for (let sitemap of index) {
for (let entry of sitemap.content ?? []) {
if (entry instanceof Array) {
for (let entry2 of getIndexContent(entry)) {
result.push(entry2);
}
} else result.push(entry);
}
}
return result;
}
// console.log(await getSitemap(new URL("http://www.gnu.org/sitemap.xml")));
export { getIndexContent, sitemapBadUrls, getSitemap, parseSitemapIndex, parseXmlSitemap, parseRssSitemap, parseAtomSitemap, parseTextSitemap, sitemapType, parsedSitemapEntry, parsedSitemap };