erudit 4.3.1 → 4.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/app/app.vue +1 -0
  2. package/app/components/aside/major/PaneHolder.vue +3 -3
  3. package/app/components/aside/major/contentNav/items/Flags.vue +4 -8
  4. package/app/components/main/MainTopicPartPage.vue +3 -1
  5. package/app/composables/analytics.ts +15 -8
  6. package/app/composables/favicon.ts +62 -15
  7. package/app/composables/formatText.ts +9 -9
  8. package/app/composables/jsonLd.ts +101 -0
  9. package/app/composables/lastmod.ts +6 -0
  10. package/app/composables/og.ts +21 -0
  11. package/app/pages/book/[...bookId].vue +3 -1
  12. package/app/pages/group/[...groupId].vue +3 -1
  13. package/app/pages/page/[...pageId].vue +3 -1
  14. package/app/plugins/prerender.server.ts +1 -0
  15. package/modules/erudit/setup/runtimeConfig.ts +39 -3
  16. package/nuxt.config.ts +1 -1
  17. package/package.json +12 -11
  18. package/server/api/main/content/[...contentTypePath].ts +2 -0
  19. package/server/api/prerender/favicons.ts +31 -0
  20. package/server/erudit/build.ts +2 -0
  21. package/server/erudit/content/lastmod.ts +206 -0
  22. package/server/erudit/content/repository/lastmod.ts +12 -0
  23. package/server/erudit/db/schema/content.ts +1 -0
  24. package/server/erudit/favicon/convertToPng.ts +48 -0
  25. package/server/erudit/favicon/loadSource.ts +139 -0
  26. package/server/erudit/favicon/shared.ts +48 -0
  27. package/server/erudit/language/list/en.ts +0 -9
  28. package/server/erudit/language/list/ru.ts +2 -11
  29. package/server/erudit/repository.ts +2 -0
  30. package/server/routes/favicon/[...path].ts +89 -0
  31. package/server/routes/sitemap.xml.ts +19 -10
  32. package/shared/types/language.ts +0 -6
  33. package/shared/types/mainContent.ts +1 -0
  34. package/shared/types/runtimeConfig.ts +4 -1
  35. package/app/composables/lastChanged.ts +0 -61
@@ -0,0 +1,206 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { eq } from 'drizzle-orm';
3
+ import type { LastmodProvider } from '@erudit-js/core/eruditConfig/lastmod';
4
+
5
+ export async function buildContentLastmod() {
6
+ const lastmodConfig = ERUDIT.config.lastmod;
7
+
8
+ if (!lastmodConfig) {
9
+ return;
10
+ }
11
+
12
+ ERUDIT.log.debug.start('Collecting lastmod dates...');
13
+
14
+ let collected = false;
15
+
16
+ if (lastmodConfig.type === 'git') {
17
+ collected = await collectGitLastmod();
18
+ } else if (lastmodConfig.type === 'custom' && lastmodConfig.scriptPath) {
19
+ collected = await collectCustomLastmod(lastmodConfig.scriptPath);
20
+ }
21
+
22
+ if (collected) {
23
+ ERUDIT.log.success('Lastmod dates collected!');
24
+ }
25
+ }
26
+
27
+ function getGitContentPrefix(): string | undefined {
28
+ const projectRoot = ERUDIT.paths.project();
29
+
30
+ const result = spawnSync('git', ['rev-parse', '--show-prefix'], {
31
+ cwd: projectRoot,
32
+ encoding: 'utf-8',
33
+ });
34
+
35
+ if (result.status !== 0) return undefined;
36
+
37
+ // gitPrefix is e.g. "playground/" or "" (if project is at repo root)
38
+ return result.stdout.trim() + 'content/';
39
+ }
40
+
41
+ async function collectGitLastmod(): Promise<boolean> {
42
+ const projectRoot = ERUDIT.paths.project();
43
+ const contentPrefix = getGitContentPrefix();
44
+
45
+ if (!contentPrefix) {
46
+ ERUDIT.log.warn(
47
+ 'Failed to detect git prefix — lastmod dates will be unavailable. ' +
48
+ 'Is this a git repository?',
49
+ );
50
+ return false;
51
+ }
52
+
53
+ const result = spawnSync(
54
+ 'git',
55
+ ['log', '--format=format:%cI', '--name-only', '--', contentPrefix],
56
+ {
57
+ cwd: projectRoot,
58
+ encoding: 'utf-8',
59
+ maxBuffer: 50 * 1024 * 1024,
60
+ },
61
+ );
62
+
63
+ if (result.status !== 0) {
64
+ ERUDIT.log.warn(
65
+ 'Failed to run git log — lastmod dates will be unavailable. ' +
66
+ 'Is this a git repository?',
67
+ );
68
+ return false;
69
+ }
70
+
71
+ const stdout = result.stdout;
72
+
73
+ if (!stdout.trim()) {
74
+ return false;
75
+ }
76
+
77
+ // Parse git log output: blocks separated by double newlines
78
+ // Each block: first line = ISO date, remaining lines = file paths
79
+ const dateMap = new Map<string, string>();
80
+ const blocks = stdout.split('\n\n');
81
+
82
+ for (const block of blocks) {
83
+ const lines = block.split('\n').filter(Boolean);
84
+ if (lines.length < 2) continue;
85
+
86
+ const date = lines[0]!;
87
+ for (let i = 1; i < lines.length; i++) {
88
+ const filePath = lines[i]!;
89
+ if (!filePath.startsWith(contentPrefix)) continue;
90
+
91
+ // Strip the prefix to get the content-relative path
92
+ // e.g. "playground/content/1-test/page.tsx" → "1-test"
93
+ const relPath = filePath.slice(contentPrefix.length);
94
+ const lastSlash = relPath.lastIndexOf('/');
95
+ const contentRelPath =
96
+ lastSlash > 0 ? relPath.slice(0, lastSlash) : relPath;
97
+
98
+ // Keep only the first (most recent) date per path
99
+ if (!dateMap.has(contentRelPath)) {
100
+ dateMap.set(contentRelPath, date);
101
+ }
102
+ }
103
+ }
104
+
105
+ // Detect shallow clone: if all dates are identical, warn
106
+ if (dateMap.size > 1) {
107
+ const dates = new Set(dateMap.values());
108
+ if (dates.size === 1) {
109
+ ERUDIT.log.warn(
110
+ 'All git lastmod dates are identical — this likely means a shallow clone. ' +
111
+ 'Use "fetch-depth: 0" in GitHub Actions checkout for accurate dates.',
112
+ );
113
+ }
114
+ }
115
+
116
+ // Build a map keyed by fullId from the contentRelPath-keyed dateMap
117
+ const ownDates = new Map<string, string>();
118
+ for (const [, navNode] of ERUDIT.contentNav.id2Node) {
119
+ const date = dateMap.get(navNode.contentRelPath);
120
+ if (date) {
121
+ ownDates.set(navNode.fullId, date);
122
+ }
123
+ }
124
+
125
+ await propagateAndSave(ownDates);
126
+ return true;
127
+ }
128
+
129
+ async function collectCustomLastmod(absPath: string): Promise<boolean> {
130
+ let provider: LastmodProvider;
131
+
132
+ try {
133
+ const module = await ERUDIT.import(absPath);
134
+ provider = (module as any).default;
135
+ } catch (error) {
136
+ ERUDIT.log.warn(
137
+ `Failed to import lastmod provider from "${absPath}":\n${error}`,
138
+ );
139
+ return false;
140
+ }
141
+
142
+ if (typeof provider !== 'function') {
143
+ ERUDIT.log.warn(
144
+ `Lastmod provider at "${absPath}" does not have a default-exported function!`,
145
+ );
146
+ return false;
147
+ }
148
+
149
+ // Collect dates from custom provider
150
+ const customDates = new Map<string, string>();
151
+
152
+ for (const [, navNode] of ERUDIT.contentNav.id2Node) {
153
+ try {
154
+ const date = await provider({
155
+ fullId: navNode.fullId,
156
+ mode: ERUDIT.mode,
157
+ projectPath: ERUDIT.paths.project(),
158
+ });
159
+ if (date instanceof Date && !isNaN(date.getTime())) {
160
+ customDates.set(navNode.fullId, date.toISOString());
161
+ }
162
+ } catch (error) {
163
+ ERUDIT.log.warn(
164
+ `Lastmod provider error for "${navNode.fullId}": ${error}`,
165
+ );
166
+ }
167
+ }
168
+
169
+ await propagateAndSave(customDates);
170
+ return true;
171
+ }
172
+
173
+ /**
174
+ * Propagate dates upward through the nav tree (parents inherit the most
175
+ * recent date from their children) and write resolved dates to the DB.
176
+ */
177
+ async function propagateAndSave(ownDates: Map<string, string>) {
178
+ // Process deepest nodes first so child dates are finalized before parents
179
+ const sortedNodes = Array.from(ERUDIT.contentNav.id2Node.values()).sort(
180
+ (a, b) => b.fullId.split('/').length - a.fullId.split('/').length,
181
+ );
182
+
183
+ const resolvedDates = new Map<string, string>();
184
+
185
+ for (const navNode of sortedNodes) {
186
+ let bestDate = ownDates.get(navNode.fullId);
187
+
188
+ for (const child of navNode.children ?? []) {
189
+ const childDate = resolvedDates.get(child.fullId);
190
+ if (childDate && (!bestDate || childDate > bestDate)) {
191
+ bestDate = childDate;
192
+ }
193
+ }
194
+
195
+ if (bestDate) {
196
+ resolvedDates.set(navNode.fullId, bestDate);
197
+ }
198
+ }
199
+
200
+ for (const [fullId, date] of resolvedDates) {
201
+ await ERUDIT.db
202
+ .update(ERUDIT.db.schema.content)
203
+ .set({ lastmod: date })
204
+ .where(eq(ERUDIT.db.schema.content.fullId, fullId));
205
+ }
206
+ }
@@ -0,0 +1,12 @@
1
+ import { eq } from 'drizzle-orm';
2
+
3
+ export async function getContentLastmod(
4
+ fullId: string,
5
+ ): Promise<string | undefined> {
6
+ const result = await ERUDIT.db.query.content.findFirst({
7
+ columns: { lastmod: true },
8
+ where: eq(ERUDIT.db.schema.content.fullId, fullId),
9
+ });
10
+
11
+ return result?.lastmod ?? undefined;
12
+ }
@@ -15,4 +15,5 @@ export const content = sqliteTable('content', {
15
15
  decorationExtension: text(),
16
16
  externals: text({ mode: 'json' }).$type<ContentExternalItem[]>(),
17
17
  seo: text({ mode: 'json' }).$type<ContentSeo>(),
18
+ lastmod: text(),
18
19
  });
@@ -0,0 +1,48 @@
1
+ import sharp from 'sharp';
2
+ import { Resvg } from '@resvg/resvg-js';
3
+ import type { FaviconSource } from './loadSource';
4
+
5
+ const cache = new Map<string, Buffer>();
6
+
7
+ export async function convertFaviconToPng(
8
+ faviconKey: string,
9
+ source: FaviconSource,
10
+ size: number,
11
+ ): Promise<Buffer> {
12
+ const cacheKey = `${faviconKey}:${size}`;
13
+ const cached = cache.get(cacheKey);
14
+ if (cached) return cached;
15
+
16
+ const png =
17
+ source.mime === 'image/svg+xml'
18
+ ? await svgToPng(source.buffer, size)
19
+ : await rasterToPng(source.buffer, size);
20
+
21
+ cache.set(cacheKey, png);
22
+ return png;
23
+ }
24
+
25
+ async function svgToPng(svgBuffer: Buffer, size: number): Promise<Buffer> {
26
+ const resvg = new Resvg(svgBuffer.toString('utf-8'), {
27
+ fitTo: { mode: 'width', value: size },
28
+ });
29
+ const rendered = Buffer.from(resvg.render().asPng());
30
+
31
+ return sharp(rendered)
32
+ .resize(size, size, {
33
+ fit: 'contain',
34
+ background: { r: 0, g: 0, b: 0, alpha: 0 },
35
+ })
36
+ .png()
37
+ .toBuffer();
38
+ }
39
+
40
+ async function rasterToPng(buffer: Buffer, size: number): Promise<Buffer> {
41
+ return sharp(buffer)
42
+ .resize(size, size, {
43
+ fit: 'contain',
44
+ background: { r: 0, g: 0, b: 0, alpha: 0 },
45
+ })
46
+ .png()
47
+ .toBuffer();
48
+ }
@@ -0,0 +1,139 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { isAbsolute } from 'node:path';
3
+ import { imageSize } from 'image-size';
4
+ import { mimeFromExt } from './shared';
5
+
6
+ export interface FaviconSource {
7
+ buffer: Buffer;
8
+ mime: string;
9
+ /** Undefined for SVG (treated as infinitely scalable) */
10
+ width?: number;
11
+ height?: number;
12
+ }
13
+
14
+ function mimeFromBuffer(buffer: Buffer): string | undefined {
15
+ if (buffer.length < 12) return undefined;
16
+
17
+ if (buffer[0] === 0xff && buffer[1] === 0xd8 && buffer[2] === 0xff)
18
+ return 'image/jpeg';
19
+
20
+ if (
21
+ buffer[0] === 0x89 &&
22
+ buffer[1] === 0x50 &&
23
+ buffer[2] === 0x4e &&
24
+ buffer[3] === 0x47
25
+ )
26
+ return 'image/png';
27
+
28
+ if (buffer[0] === 0x47 && buffer[1] === 0x49 && buffer[2] === 0x46)
29
+ return 'image/gif';
30
+
31
+ if (
32
+ buffer[0] === 0x52 &&
33
+ buffer[1] === 0x49 &&
34
+ buffer[2] === 0x46 &&
35
+ buffer[3] === 0x46 &&
36
+ buffer[8] === 0x57 &&
37
+ buffer[9] === 0x45 &&
38
+ buffer[10] === 0x42 &&
39
+ buffer[11] === 0x50
40
+ )
41
+ return 'image/webp';
42
+
43
+ if (buffer[0] === 0x42 && buffer[1] === 0x4d) return 'image/bmp';
44
+
45
+ if (
46
+ buffer[0] === 0x00 &&
47
+ buffer[1] === 0x00 &&
48
+ buffer[2] === 0x01 &&
49
+ buffer[3] === 0x00
50
+ )
51
+ return 'image/x-icon';
52
+
53
+ const head = buffer.subarray(0, 512).toString('utf-8').trim();
54
+ if (head.startsWith('<svg') || head.startsWith('<?xml'))
55
+ return 'image/svg+xml';
56
+
57
+ return undefined;
58
+ }
59
+
60
+ function resolveMime(
61
+ buffer: Buffer,
62
+ href: string,
63
+ serverMime?: string,
64
+ ): string {
65
+ return (
66
+ mimeFromBuffer(buffer) ||
67
+ mimeFromExt(href) ||
68
+ (serverMime?.startsWith('image/') ? serverMime : undefined) ||
69
+ 'application/octet-stream'
70
+ );
71
+ }
72
+
73
+ function detectDimensions(
74
+ buffer: Buffer,
75
+ mime: string,
76
+ ): { width?: number; height?: number } {
77
+ if (mime === 'image/svg+xml') return {};
78
+
79
+ try {
80
+ const size = imageSize(buffer);
81
+ return { width: size.width, height: size.height };
82
+ } catch {
83
+ return {};
84
+ }
85
+ }
86
+
87
+ function buildSource(buffer: Buffer, mime: string): FaviconSource {
88
+ return { buffer, mime, ...detectDimensions(buffer, mime) };
89
+ }
90
+
91
+ const cache = new Map<string, FaviconSource | null>();
92
+
93
+ export async function loadFaviconSource(
94
+ href: string,
95
+ ): Promise<FaviconSource | undefined> {
96
+ if (cache.has(href)) return cache.get(href) ?? undefined;
97
+
98
+ const source = await doLoad(href);
99
+ cache.set(href, source ?? null);
100
+ return source;
101
+ }
102
+
103
+ async function doLoad(href: string): Promise<FaviconSource | undefined> {
104
+ if (href.startsWith('http://') || href.startsWith('https://'))
105
+ return loadFromUrl(href);
106
+
107
+ return loadFromFilesystem(href);
108
+ }
109
+
110
+ async function loadFromUrl(url: string): Promise<FaviconSource | undefined> {
111
+ try {
112
+ const response = await fetch(url);
113
+ if (!response.ok) return undefined;
114
+
115
+ const buffer = Buffer.from(await response.arrayBuffer());
116
+ const serverMime = (response.headers.get('content-type') || '')
117
+ .split(';')[0]
118
+ ?.trim();
119
+ return buildSource(buffer, resolveMime(buffer, url, serverMime));
120
+ } catch {
121
+ return undefined;
122
+ }
123
+ }
124
+
125
+ async function loadFromFilesystem(
126
+ href: string,
127
+ ): Promise<FaviconSource | undefined> {
128
+ const cleanPath = href.replace(/^\.\//, '');
129
+ const localPath = isAbsolute(cleanPath)
130
+ ? cleanPath
131
+ : ERUDIT.paths.project(cleanPath);
132
+
133
+ try {
134
+ const buffer = await readFile(localPath);
135
+ return buildSource(buffer, resolveMime(buffer, href));
136
+ } catch {
137
+ return undefined;
138
+ }
139
+ }
@@ -0,0 +1,48 @@
1
+ export const FAVICON_SIZES = [32, 48, 180] as const;
2
+ export type FaviconSize = (typeof FAVICON_SIZES)[number];
3
+
4
+ // Mirrors contentTypes (minus 'topic') + topicParts from @erudit-js/core
5
+ export const FAVICON_KEYS = [
6
+ 'default',
7
+ 'book',
8
+ 'group',
9
+ 'page',
10
+ 'article',
11
+ 'summary',
12
+ 'practice',
13
+ ] as const;
14
+ export type FaviconKey = (typeof FAVICON_KEYS)[number];
15
+
16
+ function fallbackFaviconPath(): string {
17
+ return ERUDIT.paths.erudit('public', 'favicons', 'default.svg');
18
+ }
19
+
20
+ export function getFaviconHref(key: string): string | undefined {
21
+ const href = (
22
+ ERUDIT.config.public.favicon as Record<string, string> | undefined
23
+ )?.[key];
24
+ if (href) return href;
25
+ if (key === 'default') return fallbackFaviconPath();
26
+ return undefined;
27
+ }
28
+
29
+ const mimeByExt: Record<string, string> = {
30
+ '.svg': 'image/svg+xml',
31
+ '.png': 'image/png',
32
+ '.jpg': 'image/jpeg',
33
+ '.jpeg': 'image/jpeg',
34
+ '.gif': 'image/gif',
35
+ '.webp': 'image/webp',
36
+ '.bmp': 'image/bmp',
37
+ '.ico': 'image/x-icon',
38
+ };
39
+
40
+ export function extFromHref(href: string): string {
41
+ const path = href.split(/[?#]/)[0] ?? '';
42
+ const dot = path.lastIndexOf('.');
43
+ return dot === -1 ? '' : path.slice(dot).toLowerCase();
44
+ }
45
+
46
+ export function mimeFromExt(href: string): string | undefined {
47
+ return mimeByExt[extFromHref(href)];
48
+ }
@@ -24,15 +24,6 @@ export const phrases: LanguagePhrases = {
24
24
  no_content: 'No content.',
25
25
  to_index: 'To index',
26
26
  about_textbook: 'About textbook',
27
- flag_title_dev: 'Development',
28
- flag_hint_dev:
29
- 'This material is not complete, may contain error and will change in the future! Use with caution!',
30
- flag_title_advanced: 'Advanced',
31
- flag_hint_advanced:
32
- 'This material is for learners with a high level of knowledge. It contains information that is not suitable for beginners!',
33
- flag_title_secondary: 'Additional',
34
- flag_hint_secondary:
35
- 'This is an optional material is for learners who want to dive deeper and gain additional knowledge and context.',
36
27
  ads_replacer:
37
28
  'We help you. Help us back.<br><strong style="color: inherit;">Disable your ads blocker!</strong>',
38
29
  direct_link: 'Direct link',
@@ -24,15 +24,6 @@ export const phrases: LanguagePhrases = {
24
24
  no_content: 'Контента нет.',
25
25
  to_index: 'К оглавлению',
26
26
  about_textbook: 'Об учебнике',
27
- flag_title_dev: 'Разработка',
28
- flag_hint_dev:
29
- 'Этот материал не завершен, может содержать ошибки и измениться в будущем! Используйте с осторожностью!',
30
- flag_title_advanced: 'Профиль',
31
- flag_hint_advanced:
32
- 'Этот материал предназначен для учеников с хорошим уровнем понимания предмета. Информация здесь не предназначена для новичков!',
33
- flag_title_secondary: 'Дополнение',
34
- flag_hint_secondary:
35
- 'Это материал для тех, кто хочет глубже погрузиться предмет и получить дополнительные знания и контекст.',
36
27
  ads_replacer:
37
28
  'Помогите улучшить проект.<br><strong style="color: inherit;">Включите показ рекламы!</strong>',
38
29
  direct_link: 'Прямая ссылка',
@@ -55,7 +46,7 @@ export const phrases: LanguagePhrases = {
55
46
  'Этот материал предназначен для учеников с высоким уровнем понимания предмета. Информация здесь не предназначена для новичков!',
56
47
  flag_secondary: 'Дополнение',
57
48
  flag_secondary_description:
58
- 'Это дополнительный материал для тех, кто хочет глубже погрузиться предмет и получить дополнительные знания и контекст.',
49
+ 'Это дополнительный материал для тех, кто хочет глубже погрузиться в предмет и получить дополнительные знания и контекст.',
59
50
  key_elements: 'Ключевые элементы',
60
51
  stats: 'Статистика',
61
52
  connections: 'Связи',
@@ -96,7 +87,7 @@ export const phrases: LanguagePhrases = {
96
87
  article_seo_description: (contentTitle: string) =>
97
88
  `Понятное и интересное объяснение темы «${contentTitle}». Показательные примеры, важные свойства, интересные факты, применение в жизни, понятные доказательства. Здесь вы точно разберетесь!`,
98
89
  summary_seo_description: (contentTitle: string) =>
99
- `Конспект темы «${contentTitle}»: ключевые определения, теоремы, свойства и примеры их использвания. Все самое важное и в кратком виде!`,
90
+ `Конспект темы «${contentTitle}»: ключевые определения, теоремы, свойства и примеры их использования. Все самое важное и в кратком виде!`,
100
91
  practice_seo_description: (contentTitle: string) =>
101
92
  `Разнообразные задачи с подсказками и ответами по теме «${contentTitle}». Интересные условия, подсказки и подробные решения. Превратите знания в навык!`,
102
93
  externals_own: 'Собственные',
@@ -37,6 +37,7 @@ import {
37
37
  import { getContentSeo } from './content/repository/seo';
38
38
  import { getContentElementSnippets } from './content/repository/elementSnippets';
39
39
  import { isContentHidden } from './content/repository/hidden';
40
+ import { getContentLastmod } from './content/repository/lastmod';
40
41
  import { serverRawToProse } from './prose/repository/rawToProse';
41
42
 
42
43
  export const repository = {
@@ -77,6 +78,7 @@ export const repository = {
77
78
  updateSchemaCounts: updateContentSchemaCounts,
78
79
  contentContributions: getContentContributions,
79
80
  seo: getContentSeo,
81
+ lastmod: getContentLastmod,
80
82
  },
81
83
  prose: {
82
84
  fromRaw: serverRawToProse,
@@ -0,0 +1,89 @@
1
+ import { loadFaviconSource } from '#layers/erudit/server/erudit/favicon/loadSource';
2
+ import { convertFaviconToPng } from '#layers/erudit/server/erudit/favicon/convertToPng';
3
+ import {
4
+ FAVICON_SIZES,
5
+ FAVICON_KEYS,
6
+ getFaviconHref,
7
+ type FaviconSize,
8
+ type FaviconKey,
9
+ } from '#layers/erudit/server/erudit/favicon/shared';
10
+
11
+ export default defineEventHandler(async (event) => {
12
+ const rawPath = event.context.params?.path;
13
+ if (!rawPath) {
14
+ throw createError({
15
+ statusCode: 404,
16
+ statusMessage: 'Invalid favicon path',
17
+ });
18
+ }
19
+
20
+ const slashIdx = rawPath.indexOf('/');
21
+ if (slashIdx === -1) {
22
+ throw createError({
23
+ statusCode: 404,
24
+ statusMessage: 'Invalid favicon path',
25
+ });
26
+ }
27
+
28
+ const key = rawPath.slice(0, slashIdx);
29
+ const file = rawPath.slice(slashIdx + 1);
30
+
31
+ if (!FAVICON_KEYS.includes(key as FaviconKey)) {
32
+ throw createError({
33
+ statusCode: 404,
34
+ statusMessage: `Unknown favicon key: ${key}`,
35
+ });
36
+ }
37
+
38
+ const href = getFaviconHref(key);
39
+ if (!href) {
40
+ throw createError({
41
+ statusCode: 404,
42
+ statusMessage: `No favicon configured for: ${key}`,
43
+ });
44
+ }
45
+
46
+ const source = await loadFaviconSource(href);
47
+ if (!source) {
48
+ throw createError({
49
+ statusCode: 404,
50
+ statusMessage: 'Failed to load favicon source',
51
+ });
52
+ }
53
+
54
+ // Source route: {key}/source.{ext}
55
+ if (file.startsWith('source.')) {
56
+ setHeader(event, 'Content-Type', source.mime);
57
+ setHeader(event, 'Cache-Control', 'public, max-age=86400, s-maxage=86400');
58
+ return source.buffer;
59
+ }
60
+
61
+ // PNG route: {key}/{size}.png
62
+ if (!file.endsWith('.png')) {
63
+ throw createError({
64
+ statusCode: 404,
65
+ statusMessage: 'Invalid favicon path',
66
+ });
67
+ }
68
+
69
+ const size = Number(file.slice(0, -4)) as FaviconSize;
70
+
71
+ if (!FAVICON_SIZES.includes(size)) {
72
+ throw createError({
73
+ statusCode: 404,
74
+ statusMessage: `Invalid favicon size: ${file}`,
75
+ });
76
+ }
77
+
78
+ if (source.width !== undefined && source.width < size) {
79
+ throw createError({
80
+ statusCode: 404,
81
+ statusMessage: `Favicon source too small (${source.width}px) for size ${size}px`,
82
+ });
83
+ }
84
+
85
+ const png = await convertFaviconToPng(key, source, size);
86
+ setHeader(event, 'Content-Type', 'image/png');
87
+ setHeader(event, 'Cache-Control', 'public, max-age=86400, s-maxage=86400');
88
+ return png;
89
+ });
@@ -2,7 +2,14 @@ import { sn } from 'unslash';
2
2
 
3
3
  export default defineEventHandler(async (event) => {
4
4
  const urls = new Set<string>();
5
- urls.add(PAGES.index);
5
+ const urlLastmod = new Map<string, string>();
6
+
7
+ function addUrl(url: string, lastmod?: string) {
8
+ urls.add(url);
9
+ if (lastmod) urlLastmod.set(url, lastmod);
10
+ }
11
+
12
+ addUrl(PAGES.index);
6
13
 
7
14
  //
8
15
  // Contributors
@@ -34,7 +41,7 @@ export default defineEventHandler(async (event) => {
34
41
 
35
42
  {
36
43
  const dbContentItems = await ERUDIT.db.query.content.findMany({
37
- columns: { fullId: true },
44
+ columns: { fullId: true, lastmod: true },
38
45
  });
39
46
 
40
47
  for (const dbContentItem of dbContentItems) {
@@ -45,14 +52,15 @@ export default defineEventHandler(async (event) => {
45
52
  }
46
53
 
47
54
  const contentNode = ERUDIT.contentNav.getNodeOrThrow(fullId);
55
+ const lastmod = dbContentItem.lastmod ?? undefined;
48
56
 
49
57
  if (contentNode.type === 'topic') {
50
58
  const parts = await ERUDIT.repository.content.topicParts(fullId);
51
59
  for (const part of parts) {
52
- urls.add(PAGES.topic(part, contentNode.shortId));
60
+ addUrl(PAGES.topic(part, contentNode.shortId), lastmod);
53
61
  }
54
62
  } else {
55
- urls.add(PAGES[contentNode.type](fullId));
63
+ addUrl(PAGES[contentNode.type](fullId), lastmod);
56
64
  }
57
65
 
58
66
  const elementSnippets =
@@ -60,7 +68,7 @@ export default defineEventHandler(async (event) => {
60
68
 
61
69
  for (const snippet of elementSnippets || []) {
62
70
  if (snippet.seo) {
63
- urls.add(snippet.link);
71
+ addUrl(snippet.link, lastmod);
64
72
  }
65
73
  }
66
74
  }
@@ -75,11 +83,12 @@ export default defineEventHandler(async (event) => {
75
83
  const xml = `<?xml version="1.0" encoding="UTF-8"?>
76
84
  <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
77
85
  ${Array.from(urls)
78
- .map(
79
- (url) => ` <url>
80
- <loc>${sn(runtimeConfig.public.siteUrl, url)}</loc>
81
- </url>`,
82
- )
86
+ .map((url) => {
87
+ const lastmod = urlLastmod.get(url);
88
+ return ` <url>
89
+ <loc>${sn(runtimeConfig.public.siteUrl, url)}</loc>${lastmod ? `\n <lastmod>${lastmod}</lastmod>` : ''}
90
+ </url>`;
91
+ })
83
92
  .join('\n')}
84
93
  </urlset>`.trim();
85
94