Repository navigation
Expand file tree
/
Copy pathmiddleware.ts
More file actions
130 lines (114 loc) · 4.29 KB
/
Copy pathmiddleware.ts
File metadata and controls
130 lines (114 loc) · 4.29 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
import {next} from '@vercel/functions'
import {parseGithubUrl} from './src/shared/utils/github.js'
import {
APP_NAME,
getRouteDescription,
getRouteTitle,
} from './src/shared/utils/routeMeta.js'
/**
* Vercel Routing Middleware: link-preview metadata for repository pages.
*
* Every route serves the same index.html, and link-preview crawlers (Discord,
* Slack, KakaoTalk, X, Facebook) do not run JavaScript, so they would all see
* the home page's title and image. For /owner/repo[/ref] this serves
* index.html with the title, description, og:* and twitter:* tags of that
* repository instead. Only the URL is used here (no GitHub requests), so the
* page is never slowed down; the dynamic image (/api/og) does the fetching.
*/
export const config = {
// Repository paths have at least two segments; static files sit at the top
// level (favicon.ico, thumbnail.png, ...), and /api, /proxy and /assets
// are left alone.
matcher: '/((?!api/|proxy/|assets/).+/.+)',
}
const OG_IMAGE_WIDTH = 1200
const OG_IMAGE_HEIGHT = 630
/** Tags this middleware writes; the same tags in index.html are dropped */
const REPLACED_TAGS =
/<title>[\s\S]*?<\/title>\s*|<meta\s+(?:property|name)="(?:description|og:title|og:description|og:url|og:image(?::width|:height|:alt)?|og:site_name|twitter:[a-z:]+)"[^>]*>\s*/g
function escapeHtml(value: string): string {
return value
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''')
}
/** index.html does not change within a deployment; fetch it once per instance */
let indexHtml: Promise<string> | null = null
function getIndexHtml(origin: string): Promise<string> {
if (!indexHtml) {
indexHtml = fetch(new URL('/index.html', origin)).then(response => {
if (!response.ok) throw new Error(`index.html: ${response.status}`)
return response.text()
})
// Forget a failed request so the next one retries
indexHtml.catch(() => {
indexHtml = null
})
}
return indexHtml
}
function safeDecode(value: string): string {
try {
return decodeURIComponent(value)
} catch {
return value
}
}
export default async function middleware(request: Request) {
if (request.method !== 'GET' && request.method !== 'HEAD') return next()
const url = new URL(request.url)
const repo = parseGithubUrl(safeDecode(url.pathname.slice(1)))
if (!repo) return next()
let html: string
try {
html = await getIndexHtml(url.origin)
} catch (error) {
console.error('middleware: falling back to the static page', error)
return next()
}
const imagePath = url.searchParams.get('image')
const title = getRouteTitle(repo, imagePath)
const description = getRouteDescription(repo, imagePath)
const ogImage = new URL('/api/og', url.origin)
ogImage.searchParams.set('owner', repo.owner)
ogImage.searchParams.set('repo', repo.name)
if (repo.ref) ogImage.searchParams.set('ref', repo.ref)
if (imagePath) ogImage.searchParams.set('image', imagePath)
const tags: [string, string, string][] = [
['name', 'description', description],
['property', 'og:site_name', APP_NAME],
['property', 'og:title', title],
['property', 'og:description', description],
['property', 'og:url', url.href],
['property', 'og:image', ogImage.href],
['property', 'og:image:width', String(OG_IMAGE_WIDTH)],
['property', 'og:image:height', String(OG_IMAGE_HEIGHT)],
['property', 'og:image:alt', title],
['name', 'twitter:card', 'summary_large_image'],
['name', 'twitter:title', title],
['name', 'twitter:description', description],
['name', 'twitter:image', ogImage.href],
]
const head = [
`<title>${escapeHtml(title)}</title>`,
...tags.map(
([attribute, key, value]) =>
`<meta ${attribute}="${key}" content="${escapeHtml(value)}" />`,
),
].join('\n ')
// Put the new tags where <title> was, then drop the rest of the old ones
let inserted = false
const body = html.replace(REPLACED_TAGS, match => {
if (inserted || !match.startsWith('<title>')) return ''
inserted = true
return `${head}\n `
})
return new Response(request.method === 'HEAD' ? null : body, {
headers: {
'Content-Type': 'text/html; charset=utf-8',
'Cache-Control': 'public, max-age=0, must-revalidate',
},
})
}