|
| 1 | +import { MOVE_REFERENCE_BRANCHES, type MoveNetwork } from "../content.config"; |
| 2 | + |
| 3 | +const NETWORK_NAMES = MOVE_REFERENCE_BRANCHES.map((branch) => branch.name); |
| 4 | +const DEFAULT_NETWORK: MoveNetwork = "mainnet"; |
| 5 | + |
| 6 | +// eslint-disable-next-line @typescript-eslint/no-invalid-void-type |
| 7 | +export default function middleware(request: Request): Response | void { |
| 8 | + const url = new URL(request.url); |
| 9 | + const pathname = url.pathname; |
| 10 | + |
| 11 | + // Check for cookie |
| 12 | + const cookies = request.headers.get("cookie") ?? ""; |
| 13 | + const networkCookieMatch = /preferred_network=([a-z-]+)/.exec(cookies); |
| 14 | + let preferredNetwork: MoveNetwork = DEFAULT_NETWORK; |
| 15 | + |
| 16 | + // Validate that the cookie value is a valid network |
| 17 | + if (networkCookieMatch && NETWORK_NAMES.includes(networkCookieMatch[1] as MoveNetwork)) { |
| 18 | + preferredNetwork = networkCookieMatch[1] as MoveNetwork; |
| 19 | + } |
| 20 | + |
| 21 | + // Only process move-reference paths |
| 22 | + if (!pathname.startsWith("/move-reference")) { |
| 23 | + return undefined; |
| 24 | + } |
| 25 | + |
| 26 | + // Check if the path already includes a network |
| 27 | + const networkPathMatch = /^\/move-reference\/([a-z-]+)(\/.*|$)/.exec(pathname); |
| 28 | + |
| 29 | + if (networkPathMatch) { |
| 30 | + const pathNetwork = networkPathMatch[1]; |
| 31 | + const remainingPath = networkPathMatch[2] ?? "/"; |
| 32 | + |
| 33 | + // If the network in the path is valid but different from the preferred one, redirect |
| 34 | + if (NETWORK_NAMES.includes(pathNetwork as MoveNetwork) && pathNetwork !== preferredNetwork) { |
| 35 | + url.pathname = `/move-reference/${preferredNetwork}${remainingPath}`; |
| 36 | + return Response.redirect(url); |
| 37 | + } |
| 38 | + } else if (pathname === "/move-reference" || pathname === "/move-reference/") { |
| 39 | + // If no network is specified in the path, redirect to the preferred network |
| 40 | + url.pathname = `/move-reference/${preferredNetwork}/`; |
| 41 | + return Response.redirect(url); |
| 42 | + } |
| 43 | + |
| 44 | + return undefined; |
| 45 | +} |
0 commit comments