@@ -12,7 +12,28 @@ function docsAlias(pathname: string) {
1212
1313 const next = locale === "root" ? `/docs${ tail } ` : `/docs/${ locale } ${ tail } `
1414 if ( next === pathname ) return null
15- return next
15+ return {
16+ path : next ,
17+ locale,
18+ }
19+ }
20+
21+ function cookie ( locale : string ) {
22+ const value = locale === "root" ? "en" : locale
23+ return `oc_locale=${ encodeURIComponent ( value ) } ; Path=/; Max-Age=31536000; SameSite=Lax`
24+ }
25+
26+ function redirect ( url : URL , path : string , locale ?: string ) {
27+ const next = new URL ( url . toString ( ) )
28+ next . pathname = path
29+ const headers = new Headers ( {
30+ Location : next . toString ( ) ,
31+ } )
32+ if ( locale ) headers . set ( "Set-Cookie" , cookie ( locale ) )
33+ return new Response ( null , {
34+ status : 302 ,
35+ headers,
36+ } )
1637}
1738
1839function localeFromCookie ( header : string | null ) {
@@ -59,9 +80,7 @@ function localeFromAcceptLanguage(header: string | null) {
5980export const onRequest = defineMiddleware ( ( ctx , next ) => {
6081 const alias = docsAlias ( ctx . url . pathname )
6182 if ( alias ) {
62- const url = new URL ( ctx . request . url )
63- url . pathname = alias
64- return ctx . redirect ( url . toString ( ) , 302 )
83+ return redirect ( ctx . url , alias . path , alias . locale )
6584 }
6685
6786 if ( ctx . url . pathname !== "/docs" && ctx . url . pathname !== "/docs/" ) return next ( )
@@ -71,7 +90,5 @@ export const onRequest = defineMiddleware((ctx, next) => {
7190 localeFromAcceptLanguage ( ctx . request . headers . get ( "accept-language" ) )
7291 if ( ! locale || locale === "root" ) return next ( )
7392
74- const url = new URL ( ctx . request . url )
75- url . pathname = `/docs/${ locale } /`
76- return ctx . redirect ( url . toString ( ) , 302 )
93+ return redirect ( ctx . url , `/docs/${ locale } /` )
7794} )
0 commit comments