|
| 1 | +// Exports |
| 2 | +// ============================================================================= |
| 3 | +export const config = { |
| 4 | + matcher: ['/preview/(index.html)?'], |
| 5 | +}; |
| 6 | + |
| 7 | +// Rewrite rules shared with local server configurations |
| 8 | +export const rewriteRules = [ |
| 9 | + // Replace CDN URLs with local paths |
| 10 | + { |
| 11 | + match: /https?.*\/CHANGELOG.md/g, |
| 12 | + replace: '/CHANGELOG.md', |
| 13 | + }, |
| 14 | + { |
| 15 | + // CDN versioned default |
| 16 | + // Ex1: //cdn.com/package-name |
| 17 | + // Ex2: http://cdn.com/[email protected] |
| 18 | + // Ex3: https://cdn.com/package-name@latest |
| 19 | + match: /(?:https?:)*\/\/.*cdn.*docsify[@\d.latest]*(?=["'])/g, |
| 20 | + replace: '/lib/docsify.min.js', |
| 21 | + }, |
| 22 | + { |
| 23 | + // CDN paths to local paths |
| 24 | + // Ex1: //cdn.com/package-name/path/file.js => /path/file.js |
| 25 | + // Ex2: http://cdn.com/[email protected]/dist/file.js => /dist/file.js |
| 26 | + // Ex3: https://cdn.com/package-name@latest/dist/file.js => /dist/file.js |
| 27 | + match: /(?:https?:)*\/\/.*cdn.*docsify[@\d.latest]*\/(?:lib\/)/g, |
| 28 | + replace: '/lib/', |
| 29 | + }, |
| 30 | +]; |
| 31 | + |
| 32 | +// Serve virtual /preview/index.html |
| 33 | +// Note: See vercel.json for preview routing configuration |
| 34 | +// 1. Fetch index.html from /docs/ directory |
| 35 | +// 2. Replace CDN URLs with local paths (see rewriteRules) |
| 36 | +// 3. Return preview HTML |
| 37 | +export default async function middleware(request) { |
| 38 | + const { origin } = new URL(request.url); |
| 39 | + const indexURL = `${origin}/docs/index.html`; |
| 40 | + const indexHTML = await fetch(indexURL).then(res => res.text()); |
| 41 | + const previewHTML = rewriteRules.reduce( |
| 42 | + (html, rule) => html.replace(rule.match, rule.replace), |
| 43 | + indexHTML |
| 44 | + ); |
| 45 | + |
| 46 | + return new Response(previewHTML, { |
| 47 | + status: 200, |
| 48 | + headers: { |
| 49 | + 'content-type': 'text/html', |
| 50 | + 'x-robots-tag': 'noindex', |
| 51 | + }, |
| 52 | + }); |
| 53 | +} |
0 commit comments