-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
351 lines (298 loc) · 13.4 KB
/
Copy pathmain.js
File metadata and controls
351 lines (298 loc) · 13.4 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
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
// Sitemap Fix - Copyright (C) 2026 InPoint Automation Sp. z o.o.
// Licensed under the GNU General Public License v3 or later; see LICENSE.
//
// afterRender: rewrite sitemap.xml with correct lastmod + image entries for
// prefixed post URLs, plus lastmod for tag/category and homepage pages.
const fs = require('fs');
const path = require('path');
class SitemapFix {
constructor(API, name, config) {
this.API = API;
this.name = name;
this.config = config;
}
addEvents() {
this.API.addEvent('afterRender', this.fixSitemap, 1, this);
}
// afterRender: re-read DB, rebuild postData keyed by slug, rewrite
// sitemap.xml with correct lastmod + image entries.
fixSitemap(rendererInstance) {
const db = rendererInstance.db;
const outputDir = rendererInstance.outputDir;
const siteConfig = rendererInstance.siteConfig;
const sitemapPath = path.join(outputDir, 'sitemap.xml');
if (!fs.existsSync(sitemapPath)) {
return;
}
// Build post data keyed by slug
const postData = this.buildPostData(db, siteConfig);
// Build tag data keyed by slug (most recent post date per tag)
const tagData = this.buildTagData(db);
// Read existing sitemap
let xml = fs.readFileSync(sitemapPath, 'utf8');
// Get homepage lastmod if a page is set as frontpage
const homepageLastmod = this.getHomepageLastmod(db, siteConfig);
// For each <url> block, check if it's a post missing data and patch it
xml = xml.replace(/<url>\s*\n<loc>([^<]+)<\/loc>\s*\n(<lastmod>[^<]*<\/lastmod>\s*\n)?(<image:image>[\s\S]*?)?<\/url>/g,
(match, loc, existingLastmod, existingImages) => {
// Check if this is the homepage
const domain = siteConfig.domain.replace(/\/$/, '');
const relative = loc.replace(domain, '').replace(/^\//, '');
if ((relative === '' || relative === '/' || relative === 'index.html') && !existingLastmod && homepageLastmod) {
let result = '<url>\n';
result += '<loc>' + loc + '</loc>\n';
result += '<lastmod>' + homepageLastmod + '</lastmod>\n';
result += '</url>';
return result;
}
// Check if this is a tag/category page
const tagSlug = this.extractTagSlug(loc, siteConfig);
if (tagSlug && tagData[tagSlug] && !existingLastmod) {
let result = '<url>\n';
result += '<loc>' + loc + '</loc>\n';
result += '<lastmod>' + tagData[tagSlug] + '</lastmod>\n';
result += '</url>';
return result;
}
// Extract post/page slug from URL
const slug = this.extractSlug(loc, siteConfig);
if (!slug || !postData[slug]) {
return match; // Not a post or no data, leave as-is
}
const data = postData[slug];
let result = '<url>\n';
result += '<loc>' + loc + '</loc>\n';
// Add lastmod (prefer existing if present, otherwise inject from DB)
if (existingLastmod) {
result += existingLastmod;
} else if (data.lastMod) {
result += '<lastmod>' + data.lastMod + '</lastmod>\n';
}
// Add images (prefer existing if present, otherwise inject from DB)
if (existingImages) {
result += existingImages;
} else if (data.images && data.images.length > 0) {
const addExternal = siteConfig.advanced.sitemapAddExternalImages;
const domain = siteConfig.domain + '/';
for (const img of data.images) {
if (!addExternal && img.url.indexOf(domain) === -1) {
continue;
}
result += '<image:image>\n';
result += '<image:loc>' + img.url.replace(/\\/g, '/') + '</image:loc>\n';
result += '<image:title><![CDATA[' + (img.alt || '') + ']]></image:title>\n';
result += '</image:image>\n';
}
}
result += '</url>';
return result;
}
);
fs.writeFileSync(sitemapPath, xml, 'utf8');
console.log('[Sitemap Fix] Patched sitemap.xml with correct lastmod, image, and tag data.');
}
// post/page slug from a full sitemap URL. handles prefixed posts
// (/content/my-post/) and root-level pages (/about/).
extractSlug(url, siteConfig) {
const domain = siteConfig.domain.replace(/\/$/, '');
let relative = url.replace(domain, '').replace(/^\//, '').replace(/\/$/, '');
// Strip posts prefix if present (e.g., "content/my-post" -> "my-post")
const postsPrefix = siteConfig.advanced && siteConfig.advanced.urls
? siteConfig.advanced.urls.postsPrefix
: '';
if (postsPrefix && relative.startsWith(postsPrefix + '/')) {
relative = relative.substring(postsPrefix.length + 1);
}
// Skip pagination, tags, authors, etc.
if (relative.includes('/') || relative === '' || relative === 'index.html') {
return null;
}
// Remove .html extension if clean URLs are off
relative = relative.replace(/\.html$/, '');
return relative;
}
// lastmod for the homepage when a page is set as frontpage
getHomepageLastmod(db, siteConfig) {
if (!siteConfig.advanced.usePageAsFrontpage || !siteConfig.advanced.pageAsFrontpage) {
return null;
}
try {
const pageId = parseInt(siteConfig.advanced.pageAsFrontpage, 10);
const rows = db.prepare(
'SELECT modified_at FROM posts WHERE id = ' + pageId
).all();
if (rows.length && rows[0].modified_at) {
return this.formatDate(rows[0].modified_at);
}
} catch (e) {
console.warn('[Sitemap Fix] Homepage page query failed:', e.message);
}
return null;
}
// tag slug from a category URL (/categories/game-mods/ -> game-mods)
extractTagSlug(url, siteConfig) {
const domain = siteConfig.domain.replace(/\/$/, '');
let relative = url.replace(domain, '').replace(/^\//, '').replace(/\/$/, '');
const tagsPrefix = siteConfig.advanced && siteConfig.advanced.urls
? siteConfig.advanced.urls.tagsPrefix
: '';
const postsPrefix = siteConfig.advanced && siteConfig.advanced.urls
? siteConfig.advanced.urls.postsPrefix
: '';
if (!tagsPrefix) return null;
// Tags can be at /categories/slug/ or /content/categories/slug/
if (postsPrefix && relative.startsWith(postsPrefix + '/' + tagsPrefix + '/')) {
relative = relative.substring(postsPrefix.length + 1 + tagsPrefix.length + 1);
} else if (relative.startsWith(tagsPrefix + '/')) {
relative = relative.substring(tagsPrefix.length + 1);
} else {
return null;
}
// Only match direct tag slugs, not pagination subpages
if (relative.includes('/') || relative === '') {
return null;
}
return relative;
}
// most recent post modified_at per tag, keyed by tag slug
buildTagData(db) {
const data = {};
try {
const rows = db.prepare(`
SELECT
tags.slug,
MAX(posts.modified_at) AS latest_modified
FROM
posts_tags
JOIN tags ON posts_tags.tag_id = tags.id
JOIN posts ON posts_tags.post_id = posts.id
GROUP BY tags.slug
`).all();
for (const row of rows) {
const formatted = this.formatDate(row.latest_modified);
if (formatted) {
data[row.slug] = formatted;
}
}
} catch (e) {
console.warn('[Sitemap Fix] Tag query failed:', e.message);
}
return data;
}
// post data keyed by slug. mirrors Publii's Sitemap.getData()
// but without the prefix bug that drops lastmod/images.
buildPostData(db, siteConfig) {
const data = {};
// No external dependencies needed, using native Date
let rows;
try {
rows = db.prepare(`
SELECT
posts.id,
posts.slug,
posts.text,
posts.modified_at,
posts_images.url,
posts_images.additional_data,
posts_additional_data.value AS core_post_data
FROM
posts
LEFT JOIN
posts_images
ON posts.featured_image_id = posts_images.id
LEFT JOIN
posts_additional_data
ON posts.id = posts_additional_data.post_id
WHERE
posts_additional_data.key = '_core'
ORDER BY
posts.id ASC
`).all();
} catch (e) {
console.warn('[Sitemap Fix] DB query failed:', e.message);
return data;
}
const domain = siteConfig.domain;
for (const post of rows) {
let images = [];
let featuredImageUrl = false;
let featuredImageAlt = '';
const mediaPath = domain + '/' + path.join('media', 'posts', String(post.id)).replace(/\\/g, '/') + '/';
// Featured image
if (post.url) {
featuredImageUrl = mediaPath + post.url;
try {
const imgData = JSON.parse(post.additional_data);
featuredImageAlt = imgData.alt || '';
} catch (e) {}
}
// HTML editor images
if (post.text.indexOf('<img') > -1) {
const imgMatches = post.text.match(/<img[\s\S]*?>/gmi) || [];
for (const tag of imgMatches) {
let urlMatch = tag.match(/src="(.*?)"/mi);
let altMatch = tag.match(/alt="(.*?)"/mi);
let url = urlMatch && urlMatch[1] ? urlMatch[1].replace('#DOMAIN_NAME#', mediaPath) : false;
let alt = altMatch && altMatch[1] ? altMatch[1] : '';
if (url) images.push({ url, alt });
}
}
// Block editor images
if (post.core_post_data && post.core_post_data.indexOf('"editor":"blockeditor"') > -1) {
try {
const blocks = JSON.parse(post.text);
for (const block of blocks) {
if (block.type === 'publii-image' && block.content) {
images.push({
url: block.content.image.replace('#DOMAIN_NAME#', mediaPath),
alt: block.content.alt || ''
});
} else if (block.type === 'publii-gallery' && block.content && block.content.images) {
for (const img of block.content.images) {
images.push({
url: img.src.replace('#DOMAIN_NAME#', mediaPath),
alt: img.alt || ''
});
}
}
}
} catch (e) {}
}
// Markdown editor images
if (post.core_post_data && post.core_post_data.indexOf('"editor":"markdown"') > -1) {
const mdRegex = /!\[([^\]]*)\]\(([^)]*)\)/gmi;
const mdMatches = [...post.text.matchAll(mdRegex)];
for (const m of mdMatches) {
images.push({
url: m[2].replace('#DOMAIN_NAME#', mediaPath).replace(/\s=\d+x\d+$/, ''),
alt: m[1]
});
}
}
// Prepend featured image
if (featuredImageUrl) {
images.unshift({ url: featuredImageUrl, alt: featuredImageAlt });
}
data[post.slug] = {
lastMod: this.formatDate(post.modified_at),
images: images
};
}
return data;
}
// ISO 8601 with timezone offset, matching Publii's date format
formatDate(dateValue) {
const d = new Date(dateValue);
if (isNaN(d.getTime())) return '';
const pad = (n) => String(n).padStart(2, '0');
const offset = -d.getTimezoneOffset();
const sign = offset >= 0 ? '+' : '-';
const absOff = Math.abs(offset);
const offH = pad(Math.floor(absOff / 60));
const offM = pad(absOff % 60);
return d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate()) +
'T' + pad(d.getHours()) + ':' + pad(d.getMinutes()) + ':' + pad(d.getSeconds()) +
sign + offH + ':' + offM;
}
}
module.exports = SitemapFix;