flagon-io/g1t

public

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

g1t/apps/web/app/lib/renamed.server.ts

31 lines1,203 bytesCodeBlame
1import { redirect } from "react-router";
2
3import { isValidNamespace } from "@g1t/contracts";
4
5import { identity } from "./services.server";
6
7/**
8 * A workspace that was renamed keeps its old address as a redirect for
9 * `SLUG_HOLD_DAYS`. Call this where a page is about to 404 on its first
10 * path segment: if `slug` is an old name, it throws a 301 to the same
11 * address (path and query) under the current one. Otherwise it returns, and
12 * the caller 404s as before. Only the not-found path pays for the lookup.
13 */
14export async function redirectIfRenamed(request: Request, slug: string): Promise<void> {
15 const old = slug.toLowerCase();
16 // Nothing that could never have been a workspace's name is looked up.
17 if (!isValidNamespace(old)) return;
18 let current: string | null = null;
19 try {
20 current = await identity.resolveSlug(old);
21 } catch {
22 // A lookup that fails leaves the page a 404, never a 500.
23 return;
24 }
25 if (!current || current === old) return;
26 const url = new URL(request.url);
27 const segments = url.pathname.split("/");
28 // segments[0] is the empty string before the leading slash.
29 segments[1] = current;
30 throw redirect(segments.join("/") + url.search, 301);
31}