Repository navigation
Expand file tree
/
Copy pathvite-plugin-podcast.ts
More file actions
207 lines (196 loc) · 6.26 KB
/
Copy pathvite-plugin-podcast.ts
File metadata and controls
207 lines (196 loc) · 6.26 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
import fs from 'node:fs'
import path from 'node:path'
import type { IncomingMessage, ServerResponse } from 'node:http'
import { loadEnv, type Plugin, type ViteDevServer } from 'vite'
import { loadPodcastFeed } from './src/lib/load-rss'
import { resolveRssUrl } from './src/lib/podcast-config'
import { pathToHtmlFile, stripLocalePrefix } from './src/lib/locale'
import { applyHtmlTemplate } from './src/lib/ssr-template'
/**
* Build-time podcast plugin:
* - fetches RSS in Node (never in the browser) and exposes virtual:podcast-feed
* - SSR-renders HTML in `vite dev`
* - maps preview URLs onto prerendered dist/ files
* Skips feed load and middleware when VITEST is set.
*/
const VIRTUAL_ID = 'virtual:podcast-feed'
const RESOLVED_VIRTUAL_ID = `\0${VIRTUAL_ID}`
type FeedModule = {
podcast: {
title: string
description: string
link: string
coverArt: string
}
episodes: unknown[]
rssUrl: string
}
function isViteInternal(url: string) {
const pathname = url.split('?')[0] ?? url
if (
pathname.startsWith('/@') ||
pathname.startsWith('/node_modules') ||
pathname.startsWith('/src/') ||
pathname.startsWith('/__') ||
pathname.startsWith('/.vite')
) {
return true
}
const base = path.posix.basename(pathname)
return base.includes('.') && !pathname.endsWith('.html')
}
export function podcastPlugin(): Plugin {
let feed: FeedModule = {
podcast: { title: '', description: '', link: '', coverArt: '' },
episodes: [],
rssUrl: resolveRssUrl(),
}
async function loadFeed() {
const loaded = await loadPodcastFeed()
feed = {
podcast: loaded.podcast,
episodes: loaded.episodes,
rssUrl: loaded.rssUrl,
}
if (loaded.usedFallback) {
console.warn(
`[podcast] live feed unavailable; prerender/dev using fixture (${loaded.source})`,
)
} else {
console.log(
`[podcast] loaded ${loaded.episodes.length} episodes from ${loaded.source}`,
)
}
}
async function renderHtml(
server: ViteDevServer,
url: string,
templateSource: string,
) {
const template = await server.transformIndexHtml(url, templateSource)
const mod = await server.ssrLoadModule('/src/entry-server.tsx')
const result = mod.render(url)
return {
html: applyHtmlTemplate(template, result),
status: result.status as number,
}
}
return {
name: 'podcast-feed',
config(_config, { mode }) {
const env = loadEnv(mode, process.cwd(), '')
for (const [key, value] of Object.entries(env)) {
if (process.env[key] == null) process.env[key] = value
}
},
async buildStart() {
if (process.env.VITEST) return
await loadFeed()
},
resolveId(id) {
if (id === VIRTUAL_ID) return RESOLVED_VIRTUAL_ID
},
load(id) {
if (id === RESOLVED_VIRTUAL_ID) {
return `export const podcast = ${JSON.stringify(feed.podcast)};
export const episodes = ${JSON.stringify(feed.episodes)};
export const rssUrl = ${JSON.stringify(feed.rssUrl)};`
}
},
configureServer(server) {
if (process.env.VITEST) return
const indexPath = path.resolve(server.config.root, 'index.html')
server.middlewares.use(
async (req: IncomingMessage, res: ServerResponse, next) => {
try {
const url =
(req as IncomingMessage & { originalUrl?: string }).originalUrl ??
req.url ??
'/'
if (req.method !== 'GET' && req.method !== 'HEAD') {
next()
return
}
if (isViteInternal(url)) {
next()
return
}
const urlPath = decodeURIComponent(url.split('?')[0] ?? '/')
const redirectTo = stripLocalePrefix(urlPath)
if (redirectTo) {
res.statusCode = 301
res.setHeader('Location', redirectTo)
res.end()
return
}
const templateSource = fs.readFileSync(indexPath, 'utf8')
const rendered = await renderHtml(server, url, templateSource)
res.statusCode = rendered.status
res.setHeader('Content-Type', 'text/html; charset=utf-8')
res.end(rendered.html)
} catch (error) {
if (error instanceof Error) {
server.ssrFixStacktrace(error)
}
next(error)
}
},
)
},
configurePreviewServer(server) {
const dist = path.resolve(server.config.root, 'dist')
server.middlewares.use((req, res, next) => {
if (req.method !== 'GET' && req.method !== 'HEAD') {
next()
return
}
const urlPath = decodeURIComponent(
((req as IncomingMessage & { originalUrl?: string }).originalUrl ??
req.url ??
'/'
).split('?')[0] ?? '/',
)
const redirectTo = stripLocalePrefix(urlPath)
if (redirectTo) {
res.statusCode = 301
res.setHeader('Location', redirectTo)
res.end()
return
}
const ext = path.extname(urlPath)
if (ext && ext !== '.html') {
next()
return
}
const candidates: string[] = []
if (urlPath === '/' || urlPath === '') {
candidates.push(path.join(dist, 'index.html'))
} else {
const rel = urlPath.replace(/^\/+/, '').replace(/\/+$/, '')
candidates.push(path.join(dist, pathToHtmlFile('/' + rel)))
candidates.push(path.join(dist, rel, 'index.html'))
candidates.push(path.join(dist, `${rel}.html`))
if (rel.endsWith('.html')) {
candidates.push(path.join(dist, rel))
}
}
for (const file of candidates) {
if (fs.existsSync(file) && fs.statSync(file).isFile()) {
res.statusCode = 200
res.setHeader('Content-Type', 'text/html; charset=utf-8')
res.end(fs.readFileSync(file))
return
}
}
const notFound = path.join(dist, '404.html')
if (fs.existsSync(notFound)) {
res.statusCode = 404
res.setHeader('Content-Type', 'text/html; charset=utf-8')
res.end(fs.readFileSync(notFound))
return
}
next()
})
},
}
}