forked from LibreChat-AI/librechat.ai
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.ts
More file actions
164 lines (141 loc) · 6.58 KB
/
Copy pathproxy.ts
File metadata and controls
164 lines (141 loc) · 6.58 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
import { NextRequest, NextResponse, type NextFetchEvent } from 'next/server'
import { createI18nMiddleware } from 'fumadocs-core/i18n/middleware'
import { i18n, LOCALIZED_HOME_LOCALES, LOCALE_COOKIE } from '@/lib/i18n'
const i18nMiddleware = createI18nMiddleware(i18n)
function matchLocale(tag: string, locales: readonly string[]): string | null {
const normalized = tag.toLowerCase()
const exact = locales.find((locale) => locale.toLowerCase() === normalized)
if (exact) return exact
const base = normalized.split('-')[0]
const baseLocale = locales.find((locale) => locale.toLowerCase() === base)
if (baseLocale) return baseLocale
return locales.find((locale) => locale.toLowerCase().split('-')[0] === base) ?? null
}
function isMarkdownPreferred(request: NextRequest): boolean {
const accept = request.headers.get('accept') ?? ''
const ranges = accept.split(',').map((part) => {
const [mediaRange = '', ...parameters] = part.split(';')
const qualityValue = parameters
.map((parameter) => parameter.trim().match(/^q\s*=\s*(.+)$/i)?.[1])
.find((value) => value !== undefined)
const parsedQuality = qualityValue === undefined ? 1 : Number(qualityValue)
const quality =
Number.isFinite(parsedQuality) && parsedQuality >= 0 && parsedQuality <= 1 ? parsedQuality : 0
return { mediaRange: mediaRange.trim().toLowerCase(), quality }
})
const qualityFor = (mediaType: string): number => {
const [type] = mediaType.split('/')
const matches = ranges
.map(({ mediaRange, quality }) => ({
quality,
specificity: mediaRange === mediaType ? 2 : mediaRange === `${type}/*` ? 1 : 0,
matches: mediaRange === mediaType || mediaRange === `${type}/*` || mediaRange === '*/*',
}))
.filter((candidate) => candidate.matches)
.sort((left, right) => right.specificity - left.specificity)
return matches[0]?.quality ?? 0
}
const markdownQuality = qualityFor('text/markdown')
const htmlQuality = qualityFor('text/html')
const explicitlyAcceptsMarkdown = ranges.some(
({ mediaRange, quality }) => mediaRange === 'text/markdown' && quality > 0,
)
return (
markdownQuality > 0 &&
(markdownQuality > htmlQuality ||
(markdownQuality === htmlQuality && explicitlyAcceptsMarkdown))
)
}
function rewriteToMarkdown(request: NextRequest, destination: string): NextResponse {
const response = NextResponse.rewrite(new URL(destination, request.nextUrl))
response.headers.set('Cache-Control', 'private, no-store')
response.headers.set('Vary', 'Accept')
return response
}
/**
* The reader's preferred site language: an explicit choice (the LOCALE_COOKIE
* set by the language switcher) wins; otherwise the best `Accept-Language`
* match among the locales we build; falling back to the default language.
*/
export function preferredLocale(
request: NextRequest,
locales: readonly string[] = i18n.languages,
): string {
const cookie = request.cookies.get(LOCALE_COOKIE)?.value
if (cookie) {
if (locales.includes(cookie)) return cookie
// A valid implemented locale cookie is still an explicit language choice,
// even if the caller passes a narrower locale set.
if (i18n.languages.includes(cookie)) return i18n.defaultLanguage
}
const header = request.headers.get('accept-language')
if (!header) return i18n.defaultLanguage
const ranked = header
.split(',')
.map((part) => {
const [tag, q] = part.trim().split(';q=')
return { tag, q: q ? Number(q) : 1 }
})
.sort((a, b) => b.q - a.q)
for (const { tag } of ranked) {
const locale = matchLocale(tag, locales)
if (locale) return locale
}
return i18n.defaultLanguage
}
export default function proxy(request: NextRequest, event: NextFetchEvent) {
const { pathname } = request.nextUrl
// Leave raw markdown routes to next.config rewrites; don't localize them.
// Must run before content negotiation: an Accept: text/markdown request to a
// .md/.mdx URL needs to keep its suffix so the next.config rewrite can strip
// it, otherwise the route handler gets a slug that still ends in .md and 404s.
if (pathname.endsWith('.md') || pathname.endsWith('.mdx')) return NextResponse.next()
// Serve curated Markdown for content-negotiated homepage requests.
if (isMarkdownPreferred(request) && pathname === '/') {
return rewriteToMarkdown(request, '/llms.txt')
}
// Serve raw Markdown for content-negotiated docs requests (LLM/agent tooling).
if (isMarkdownPreferred(request) && (pathname === '/docs' || pathname.startsWith('/docs/'))) {
const rest = pathname.slice('/docs'.length)
return rewriteToMarkdown(request, `/llms.mdx/docs${rest}`)
}
// Browser-language auto-detection, scoped to the prefix-less home page. A
// reader whose browser prefers an implemented non-default locale is forwarded
// to `/<locale>`. Deliberately limited to `/`: the content routes (/docs,
// /blog, …) are shared-CDN-cached, and an Accept-Language redirect there
// would be cached and served to every reader regardless of their language.
//
// The decision depends on Cookie + Accept-Language, so BOTH outcomes must stay
// out of any shared cache: a cached English `/` 200 (not just the redirect)
// would otherwise be replayed to a German/Spanish/… visitor without the proxy
// re-running, bypassing detection. `Vary` alone isn't enough — Cloudflare
// ignores it — so mark both responses `private, no-store`.
if (pathname === '/') {
const locale = preferredLocale(request, LOCALIZED_HOME_LOCALES)
let response: NextResponse
if (locale === i18n.defaultLanguage) {
response = NextResponse.next()
} else {
const url = request.nextUrl.clone()
url.pathname = `/${locale}`
response = NextResponse.redirect(url, 307)
}
response.headers.set('Cache-Control', 'private, no-store')
response.headers.set('Vary', 'Accept, Cookie, Accept-Language')
return response
}
// English docs have an explicit prefix-less route. Let Next.js render the
// same public pathname on the server and client so Fumadocs pathname-based
// state (breadcrumbs and active sidebar items) hydrates deterministically.
if (pathname === '/docs' || pathname.startsWith('/docs/')) {
const response = NextResponse.next()
response.headers.set('Vary', 'Accept')
return response
}
// Localized docs keep their visible locale prefix. The middleware also
// canonicalizes the default locale from /en/docs/* back to /docs/*.
return i18nMiddleware(request, event)
}
export const config = {
matcher: ['/', '/docs/:path*', '/(en|zh|es|fr|de|ja|pt-BR|it|nl|pl|vi|ko|id|tr)/docs/:path*'],
}