-
Notifications
You must be signed in to change notification settings - Fork 59
Expand file tree
/
Copy pathvite.config.ts
More file actions
327 lines (306 loc) · 11 KB
/
Copy pathvite.config.ts
File metadata and controls
327 lines (306 loc) · 11 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
import fs from 'node:fs/promises'
import path from 'node:path'
import react from '@vitejs/plugin-react'
import { Instance } from 'prool'
import Icons from 'unplugin-icons/vite'
import { defineConfig, loadEnv, type Plugin, type ResolvedConfig } from 'vite'
import mkcert from 'vite-plugin-mkcert'
import { vocs } from 'vocs/vite'
import { canonicalizeGeneratedDeveloperLinks } from './src/lib/canonical-developer-links'
import { finalizeSitemap } from './src/lib/sitemap'
import { blogPostsPlugin, getBlogPostSlugs } from './src/marketing/blogPlugin'
// https://vite.dev/config/
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, process.cwd(), '')
for (const key of Object.keys(env)) {
if (!(key in process.env)) process.env[key] = env[key]
}
const useHttp = process.env.CI === 'true' || process.env.VITE_USE_HTTP === 'true'
const proxy = {
'/api/mcp': {
changeOrigin: true,
rewrite: () => '/',
secure: true,
target: 'https://mcp.tempo.xyz',
},
}
return {
define: {
'import.meta.env.VERCEL_ENV': JSON.stringify(process.env.VERCEL_ENV ?? ''),
},
plugins: [
blogPostsPlugin(),
marketingPages(),
developersProxyRouteNormalization(),
vocs(),
Icons({ compiler: 'jsx', jsx: 'react' }),
react(),
...(useHttp ? [] : [mkcert()]),
tempoNode(),
llmsFeedbackPreamble(),
],
resolve: {
alias: [
{
find: 'next/image',
replacement: path.resolve(process.cwd(), 'src/marketing/next-shims.tsx'),
},
{
find: 'next/link',
replacement: path.resolve(process.cwd(), 'src/marketing/next-shims.tsx'),
},
{
find: 'next/navigation',
replacement: path.resolve(process.cwd(), 'src/marketing/next-shims.tsx'),
},
{ find: 'next', replacement: path.resolve(process.cwd(), 'src/marketing/next-shims.tsx') },
],
},
server: {
...(useHttp ? { host: 'localhost' } : {}),
proxy,
},
}
})
const marketingRoutes = ['/', '/build', '/blog', '/performance']
function developersProxyRouteNormalization(): Plugin {
return {
name: 'tempo-developers-proxy-route-normalization',
enforce: 'post',
transform(code, id) {
if (id !== '\0virtual:vite-rsc-waku/client-entry') return
return code
.replace(
"import { Router } from 'waku/router/client';",
"import { Router, unstable_parseRoute } from 'waku/router/client';",
)
.replace(
'const rootElement = createElement(StrictMode, null, createElement(Router));',
`const developersPrefix = '/developers';
const shouldUseDevelopersPrefix = () => window.location.pathname === developersPrefix || window.location.pathname.startsWith(developersPrefix + '/');
const publicDevelopersPath = (path) => {
if (path === '/') return developersPrefix;
if (path.startsWith(developersPrefix + '/')) return path;
return developersPrefix + path;
};
const normalizeDevelopersRoute = (route) => {
const routePath = typeof route.path === 'string' ? route.path : '/';
if (routePath === '/developers') return { ...route, path: '/' };
if (routePath.startsWith('/developers/')) {
return { ...route, path: routePath.slice('/developers'.length) || '/' };
}
return route;
};
const getUnprefixedInternalLink = (event) => {
if (!shouldUseDevelopersPrefix()) return;
const link = event.target instanceof Element ? event.target.closest('a[href^="/"]') : null;
if (!(link instanceof HTMLAnchorElement)) return;
const href = link.getAttribute('href');
if (!href || href.startsWith('//') || href.startsWith(developersPrefix + '/')) return;
if (href.startsWith('/assets/') || href.startsWith('/fonts/') || href.startsWith('/RSC/')) return;
return { link, href };
};
const originalFetch = window.fetch.bind(window);
window.fetch = async (input, init) => {
const response = await originalFetch(input, init);
if (!shouldUseDevelopersPrefix()) return response;
const requestUrl = typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url;
if (!requestUrl.includes('/RSC/')) return response;
const clone = response.clone();
const contentType = clone.headers.get('content-type') || '';
if (!contentType.includes('text/plain')) return response;
const text = await clone.text();
const normalized = text
.replaceAll('route:/developers/', 'route:/')
.replaceAll('route:/developers"', 'route:/"')
.replaceAll('route:/developers,', 'route:/,')
.replaceAll('route:/developers\\n', 'route:/\\n');
if (normalized === text) return response;
return new Response(normalized, {
status: response.status,
statusText: response.statusText,
headers: response.headers,
});
};
document.addEventListener(
'click',
(event) => {
const target = getUnprefixedInternalLink(event);
if (!target) return;
event.preventDefault();
event.stopImmediatePropagation();
window.location.assign(publicDevelopersPath(target.href));
},
true,
);
for (const eventName of ['pointerover', 'mouseover']) {
document.addEventListener(
eventName,
(event) => {
if (!getUnprefixedInternalLink(event)) return;
event.stopImmediatePropagation();
},
true,
);
}
const initialRoute = normalizeDevelopersRoute(unstable_parseRoute(new URL(window.location.href)));
const rootElement = createElement(
StrictMode,
null,
createElement(Router, {
initialRoute,
unstable_routeInterceptor: normalizeDevelopersRoute,
}),
);`,
)
},
}
}
function isMarketingPath(pathname: string) {
const normalized = pathname.replace(/\/$/, '') || '/'
// Let requests for actual files (e.g. /blog/foo.svg) fall through to Vite's
// static asset serving instead of returning the marketing SPA shell.
const lastSegment = normalized.split('/').pop() ?? ''
if (lastSegment.includes('.')) return false
return (
marketingRoutes.includes(normalized) ||
normalized.startsWith('/build/') ||
normalized.startsWith('/blog/')
)
}
async function marketingHtml() {
const html = await fs.readFile(path.resolve(process.cwd(), 'src/marketing/index.html'), 'utf-8')
return html.replace('src="./main.tsx"', 'src="/src/marketing/main.tsx"')
}
function marketingPages(): Plugin {
return {
name: 'tempo-marketing-pages',
configureServer(server) {
server.middlewares.use(async (req, res, next) => {
if (!req.url) return next()
const url = new URL(req.url, 'http://localhost')
if (!isMarketingPath(url.pathname)) return next()
const html = await server.transformIndexHtml(url.pathname, await marketingHtml())
res.statusCode = 200
res.setHeader('Content-Type', 'text/html')
res.end(html)
})
},
}
}
const llmsFeedbackNotice = [
'> Feedback: If these docs are stale, missing, or confusing, post sanitized feedback to `https://tempo.xyz/developers/api/feedback` with `source: "mcp"`, a short `message`, and any relevant `toolName`, `relatedResource`, or `client`.',
'',
].join('\n')
function llmsFeedbackPreamble(): Plugin {
let viteConfig: ResolvedConfig
return {
name: 'tempo-llms-feedback-preamble',
configResolved(config) {
viteConfig = config
},
// Waku writes static HTML and RSC payloads during buildApp, after the
// environment closeBundle hooks have already finished.
buildApp: {
order: 'post',
async handler() {
const publicDir = path.resolve(viteConfig.root, viteConfig.build.outDir, 'public')
const candidates = [
path.join(publicDir, 'llms.txt'),
path.join(publicDir, 'llms-full.txt'),
...(await markdownFiles(path.join(publicDir, 'assets/md'))),
]
await Promise.all(candidates.map(prependFeedbackNotice))
if (process.env.VERCEL_ENV === 'production') {
const generatedPages = [
...(await filesWithExtension(publicDir, '.html')),
...(await filesWithExtension(path.join(publicDir, 'RSC'), '.txt')),
]
await Promise.all(
[...new Set([...candidates, ...generatedPages])].map(canonicalizeGeneratedLinksInFile),
)
}
await finalizeGeneratedSitemap(path.join(publicDir, 'sitemap.xml'))
},
},
}
}
async function markdownFiles(directory: string): Promise<string[]> {
try {
const entries = await fs.readdir(directory, { withFileTypes: true })
const files = await Promise.all(
entries.map(async (entry) => {
const entryPath = path.join(directory, entry.name)
if (entry.isDirectory()) return markdownFiles(entryPath)
if (entry.isFile() && entry.name.endsWith('.md')) return [entryPath]
return []
}),
)
return files.flat()
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return []
throw error
}
}
async function filesWithExtension(directory: string, extension: string): Promise<string[]> {
try {
const entries = await fs.readdir(directory, { withFileTypes: true })
const files = await Promise.all(
entries.map(async (entry) => {
const entryPath = path.join(directory, entry.name)
if (entry.isDirectory()) return filesWithExtension(entryPath, extension)
if (entry.isFile() && entry.name.endsWith(extension)) return [entryPath]
return []
}),
)
return files.flat()
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return []
throw error
}
}
async function prependFeedbackNotice(filePath: string) {
try {
const content = await fs.readFile(filePath, 'utf-8')
if (content.startsWith(llmsFeedbackNotice)) return
await fs.writeFile(filePath, `${llmsFeedbackNotice}${content}`, 'utf-8')
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return
throw error
}
}
async function canonicalizeGeneratedLinksInFile(filePath: string) {
try {
const content = await fs.readFile(filePath, 'utf-8')
const canonical = canonicalizeGeneratedDeveloperLinks(content)
if (canonical !== content) await fs.writeFile(filePath, canonical, 'utf-8')
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return
throw error
}
}
async function finalizeGeneratedSitemap(filePath: string) {
try {
const content = await fs.readFile(filePath, 'utf-8')
const finalized = finalizeSitemap(content, getBlogPostSlugs())
if (finalized !== content) await fs.writeFile(filePath, finalized, 'utf-8')
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return
throw error
}
}
function tempoNode(): Plugin {
return {
name: 'tempo-node',
async configureServer(_server) {
if (!('VITE_TEMPO_ENV' in process.env) || process.env.VITE_TEMPO_ENV !== 'localnet') return
const instance = Instance.tempo({
dev: { blockTime: '500ms' },
port: 8545,
})
console.log('→ starting tempo node...')
await instance.start()
console.log('√ tempo node started on port 8545')
},
}
}