From 144da6ad6ed4295eee3f091ba23faf45b39d3ab6 Mon Sep 17 00:00:00 2001 From: andatoshiki <101481353+andatoshiki@users.noreply.github.com> Date: Fri, 24 Mar 2023 16:28:03 +0800 Subject: [PATCH] feat: add rss building utils but yet to applied to production stage --- docs/.vitepress/theme/rss.ts | 77 ++++++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 docs/.vitepress/theme/rss.ts diff --git a/docs/.vitepress/theme/rss.ts b/docs/.vitepress/theme/rss.ts new file mode 100644 index 00000000..fa8595ea --- /dev/null +++ b/docs/.vitepress/theme/rss.ts @@ -0,0 +1,77 @@ +import { dirname } from 'path' +import fg from 'fast-glob' +import fs from 'fs-extra' +import matter from 'gray-matter' +import MarkdownIt from 'markdown-it' +import type { FeedOptions, Item } from 'feed' +import { Feed } from 'feed' + +const DOMAIN = 'https://note.toshiki.dev' +const AUTHOR = { + name: 'Anda Toshiki', + email: 'hello@toshiki.dev', + link: DOMAIN, +} +const OPTIONS: FeedOptions = { + title: "Toshiki's Notebook", + description: "Toshiki's web notebook built upon Vitepress and deployed via Vercel!", + id: `${DOMAIN}/`, + link: `${DOMAIN}/`, + copyright: 'MIT License', + feedLinks: { + json: DOMAIN + '/feed.json', + atom: DOMAIN + '/feed.atom', + rss: DOMAIN + '/feed.xml', + }, + author: AUTHOR, + image: 'https://note.toshiki.dev/logos/logo-308px.svg', + favicon: 'https://note.toshiki.dev/logos/logo-308px.svg', +} + +const markdown = MarkdownIt({ + html: true, + breaks: true, + linkify: true, +}) + +export async function buildDocsRSS() { + const posts = await generateRSS() + writeFeed('feed', posts) +} + +async function generateRSS() { + const files = await fg('docs/*.md') + + const posts: any[] = ( + await Promise.all( + files + .filter(i => !i.includes('index')) + .map(async i => { + const raw = await fs.readFile(i, 'utf-8') + const { data, content } = matter(raw) + const html = markdown.render(content).replace('src="/', `src="${DOMAIN}/`) + + return { + ...data, + date: new Date(data.date), + content: html, + author: [AUTHOR], + link: `${DOMAIN}/${i.replace('.md', '.html')}`, + } + }) + ) + ).filter(Boolean) + + posts.sort((a, b) => +new Date(b.date) - +new Date(a.date)) + return posts +} + +async function writeFeed(name: string, items: Item[]) { + const feed = new Feed(OPTIONS) + items.forEach(item => feed.addItem(item)) + + await fs.ensureDir(dirname(`./dist/${name}`)) + await fs.writeFile(`./dist/${name}.xml`, feed.rss2(), 'utf-8') + await fs.writeFile(`./dist/${name}.atom`, feed.atom1(), 'utf-8') + await fs.writeFile(`./dist/${name}.json`, feed.json1(), 'utf-8') +}