docs/.vitepress/configs/hooks/opengraph.ts
141 lines · 3910 bytes
1/**
2 * All Rights Reserved
3 *
4 * Copyright (c) 2025 taskylizard
5 *
6 * All rights reserved. This code and its associated files may not be copied, modified, distributed, sublicensed, or used in any form, in whole or in part, without prior written permission from the copyright holder.
7 */
8import { mkdir, readFile, writeFile } from 'node:fs/promises'
9import { dirname, resolve } from 'node:path'
10import { fileURLToPath } from 'node:url'
11import { type Font, render } from 'takumi-js'
12import { Renderer } from 'takumi-js/node'
13import { createContentLoader } from 'vitepress'
14import type { ContentData, SiteConfig } from 'vitepress'
15import { excludedFiles } from '../constants'
16import { OgImageTemplate } from './OgImageTemplate'
17
18const __dirname = dirname(fileURLToPath(import.meta.url))
19const __fonts = resolve(__dirname, '../fonts')
20const fonts: Font[] = [
21 {
22 name: 'Inter',
23 data: await readFile(resolve(__fonts, 'Inter-Regular.otf')),
24 weight: 400,
25 style: 'normal'
26 },
27 {
28 name: 'Inter',
29 data: await readFile(resolve(__fonts, 'Inter-Medium.otf')),
30 weight: 500,
31 style: 'normal'
32 },
33 {
34 name: 'Inter',
35 data: await readFile(resolve(__fonts, 'Inter-SemiBold.otf')),
36 weight: 600,
37 style: 'normal'
38 },
39 {
40 name: 'Inter',
41 data: await readFile(resolve(__fonts, 'Inter-Bold.otf')),
42 weight: 700,
43 style: 'normal'
44 }
45]
46
47const renderer = new Renderer()
48await renderer.loadFonts(fonts)
49
50const resourceCache = new Map<string, ArrayBuffer>()
51const persistentImageByUrl = new Map<string, string>()
52const defaultImage = 'https://i.wotaku.wiki/f/default.png'
53
54export async function generateImages(config: SiteConfig) {
55 const pages = await createContentLoader('**/*.md', {
56 excerpt: true,
57 globOptions: {
58 ignore: [...excludedFiles, 'node_modules', 'dist']
59 }
60 }).load()
61
62 const filteredPages = pages.filter((p) => p.frontmatter.image === undefined)
63
64 await loadPersistentImages(filteredPages)
65
66 for (const page of filteredPages) {
67 await generateImage({
68 page,
69 outDir: config.outDir
70 })
71 }
72}
73
74interface GenerateImagesOptions {
75 page: ContentData
76 outDir: string
77}
78
79async function generateImage({
80 page,
81 outDir
82}: GenerateImagesOptions) {
83 const { frontmatter, url } = page
84 const width = frontmatter.og?.width ?? 1800
85 const height = frontmatter.og?.height ?? 900
86 const title = String(
87 frontmatter.layout === 'home'
88 ? (frontmatter.hero.name ?? frontmatter.title)
89 : (frontmatter.customMetaTitle ?? frontmatter.title)
90 )
91 const image = getImage(page)
92
93 const png = await render(
94 OgImageTemplate({ title, image: persistentImageByUrl.get(image) ?? image }),
95 {
96 width,
97 height,
98 renderer,
99 resourcesOptions: {
100 cache: resourceCache
101 }
102 }
103 )
104
105 const outputFolder = resolve(outDir, url.substring(1), '__og_image__')
106 const outputFile = resolve(outputFolder, 'og.png')
107
108 await mkdir(outputFolder, { recursive: true })
109
110 return await writeFile(outputFile, png)
111}
112
113async function loadPersistentImages(pages: ContentData[]) {
114 const imageUrls = [...new Set(pages.map(getImage))]
115 .filter((url) => /^https?:\/\//.test(url))
116 .filter((url) => !persistentImageByUrl.has(url))
117 const offset = persistentImageByUrl.size
118
119 await Promise.all(
120 imageUrls.map(async (url, index) => {
121 const src = `og-background-${offset + index}`
122 const response = await fetch(url, {
123 signal: AbortSignal.timeout(5000)
124 })
125
126 if (!response.ok) {
127 throw new Error(
128 `Failed to fetch OpenGraph image ${url}: ${response.status} ${response.statusText}`
129 )
130 }
131
132 const data = await response.arrayBuffer()
133 await renderer.putPersistentImage({ src, data })
134 persistentImageByUrl.set(url, src)
135 })
136 )
137}
138
139function getImage(page: ContentData) {
140 return String(page.frontmatter.og?.image ?? defaultImage)
141}