v4: every page and API URL follows one of two rules, written down in API.md — pages are a hierarchy where @name is a user and any other root word a category or an app page, tabs and views are plain segments and a default view is the bare path; API resources are /api/<plural>/<key>, a user's key being an id or @name, the caller's things under /api/me, media a sub-resource, lookups by another key a query filter. ~ is gone: the feed is /, /hot, /new, /journal, /follow and /music/hot, a profile /@bob with its overview and the tabs dumps, upvoted, playlists (her own only), follow (users, and /follow/playlists), invitees and manage (role and name, for user:manage), which replace the separate UserDumps, UserUpvoted and UserPlaylists pages; /settings holds the account (now with the username) and /manage the category manager, both linked from the user menu and one's profile. Dumps and playlists live under their owner, /@bob/dumps/<slug> and /@bob/playlists/<slug>, named by slug alone: migration 0021 re-slugs them to the bare slugify(title), unique per owner and kind (the oldest keeps it, clashes get -2), renames the categories whose slug v4 reserves (hot, follow, settings…), and rewrites this site's v3 links in dump notes, comments, chat, and playlist and profile descriptions. A slug changes only when edited, through the edit forms' new link field, which proposes slugify(title) as the title changes; a username changes from /settings or, for user:manage, from /@name/manage. Every slug or name left behind stays an alias of its item or user for good (dump_slug_aliases, playlist_slug_aliases, user_aliases), so old links redirect without chaining and nobody else can take one; slugs change 3 times a day per item, names once in 30 days, moderators exempt. An alias, or a name in another case, answers the item with its current path: the pages put it in their URL (useCanonicalPath, without fetching again), and the OG middleware answers a 301. shared/paths.ts builds and parses every page path, for the client's links, the emails' (digest-service lost its own builders and its id fallbacks, and links /follow and /settings) and the server's matchers (OG tags, self previews, backlinks, self-url); shared/slug.ts holds slugify and the format categories share. Dumps and playlists carry ownerUsername and a required slug, and notifications join their users' current names and their items' paths each time they are sent or read, so renames reach them and a deleted item's has no link. The API was renamed per the plan's table: POST /api/users and /api/sessions, /api/password-resets, /api/me (with settings, password, avatar, media-token, playlists?contains=, follow, feed?from=, notifications), /api/users/:key/{dumps,upvoted,playlists,follow/users,follow/playlists,invitees,avatar} and by path /api/users/:key/{dumps,playlists}/:slug, /api/dumps?url= and ?category=, /api/dumps/:id/{file,thumbnail,metadata}, /api/playlists/:id/cover, /api/remote/{preview,image,bandcamp,youtube} (one router), and /api/unsubscribe, the v3 POST /api/users/unsubscribe staying for the digests already sent. A stored default feed tab "followed" reads as "follow" once. dumps.slug and playlists.slug stay nullable, since SQLite can't add NOT NULL without rebuilding tables others reference; every writer sets them and unique (user_id, slug) indexes hold them. 254 backend tests (new: migration 0021 on a v3 fixture, slug aliases, swaps and rate limits, username renames, aliases and limits, reads by path and their privacy, the OG 301s, both unsubscribe paths, v4-shaped digest links with no ids, notification joins, shared paths and slugs) and 668 frontend tests (new: the profile's tabs and follow views, Settings, Manage, the link field, canonical URLs on the dump, playlist and profile pages, bare default feed paths) pass, and tsc, eslint, deno check, deno lint, deno fmt and doc:lint are clean; the migration was also run on a copy of the development database.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
khannurien
2026-10-06 16:08:59 +00:00
parent fd0d81fe66
commit 4468438ba7
228 changed files with 7320 additions and 5193 deletions

View File

@@ -1,8 +1,9 @@
import { describe, expect, test } from "vitest";
import { act, screen, waitFor, within } from "@testing-library/react";
import { userEvent } from "@testing-library/user-event";
import { useParams } from "react-router";
import { useLocation } from "react-router";
import { Index } from "../../pages/Index.tsx";
import { FEED_TABS, type FeedTab } from "../../../shared/paths.ts";
import { calls, fail, route } from "../fetch.ts";
import {
makeCategory,
@@ -18,10 +19,19 @@ import { FakeIntersectionObserver } from "../setup.ts";
const HOUR = 3_600_000;
const music = makeCategory({ id: "c-music", slug: "music", name: "Music" });
/** Reads a feed's path as `App`'s routes do. */
function Scoped() {
const { scope } = useParams();
const categorySlug = scope === "~" ? undefined : scope;
return <Index key={scope} categorySlug={categorySlug} />;
const { pathname } = useLocation();
const [first, second] = pathname.split("/").filter(Boolean);
const isTab = (FEED_TABS as readonly string[]).includes(first ?? "");
const categorySlug = first && !isTab ? first : undefined;
return (
<Index
key={categorySlug ?? ""}
categorySlug={categorySlug}
feedTab={(isTab ? first : second) as FeedTab | undefined}
/>
);
}
function setup(
@@ -31,7 +41,7 @@ function setup(
const user = userEvent.setup();
renderApp(<Scoped />, {
route: url,
path: "/:scope/:feedTab",
path: "*",
session,
categories: [music],
});
@@ -59,35 +69,59 @@ describe("Index feeds", () => {
});
test("New sorts by date, Hot by score", async () => {
route("GET /api/dumps/", () => page([older, newer]));
const { user } = setup("/~/new");
route("GET /api/dumps", () => page([older, newer]));
const { user } = setup("/new");
await screen.findByText("Brand new");
expect(titles()).toEqual(["Brand new", "Old but loved"]);
await user.click(screen.getAllByRole("button", { name: "Hot" })[0]);
expect(currentPath()).toBe("/~/hot");
expect(currentPath()).toBe("/hot");
expect(titles()).toEqual(["Old but loved", "Brand new"]);
expect(screen.getByText("You've reached the end.")).toBeInTheDocument();
// One fetch: switching tabs re-sorts what's loaded.
expect(calls("GET /api/dumps/")).toHaveLength(1);
expect(calls("GET /api/dumps")).toHaveLength(1);
});
test("the bare path is the viewer's default tab, with no redirect", async () => {
route("GET /api/dumps", () => page([older, newer]));
localStorage.setItem("default-feed-tab", "hot");
const { user } = setup("/");
await screen.findByText("Brand new");
expect(currentPath()).toBe("/");
expect(titles()).toEqual(["Old but loved", "Brand new"]);
await user.click(screen.getAllByRole("button", { name: "New" })[0]);
expect(currentPath()).toBe("/new");
// The default tab is the bare path again.
await user.click(screen.getAllByRole("button", { name: "Hot" })[0]);
expect(currentPath()).toBe("/");
});
test('a default tab stored as v3\'s "followed" is "follow" now', async () => {
route("GET /api/me/feed", () => page([]));
localStorage.setItem("default-feed-tab", "followed");
setup("/", { session: makeSession() });
expect(
await screen.findByText("Follow some users to see their dumps here."),
).toBeInTheDocument();
expect(localStorage.getItem("default-feed-tab")).toBe("follow");
});
test("Journal lays the feed out as a mosaic", async () => {
route("GET /api/dumps/", () => page([older, newer]));
setup("/~/journal");
route("GET /api/dumps", () => page([older, newer]));
setup("/journal");
await screen.findByText("Brand new");
expect(document.querySelector(".journal-grid")).not.toBeNull();
});
test("an empty feed and a failed one", async () => {
route("GET /api/dumps/", () => page([]));
const first = setup("/~/new");
route("GET /api/dumps", () => page([]));
const first = setup("/new");
await screen.findByText("No dumps yet. Be the first!");
first.socket.drop();
});
test("a failed load shows an error and disables posting", async () => {
route("GET /api/dumps/", () => fail("boom", 500));
setup("/~/new", { session: makeSession() });
route("GET /api/dumps", () => fail("boom", 500));
setup("/new", { session: makeSession() });
expect(await screen.findByRole("alert")).toHaveTextContent(
"Failed to load",
);
@@ -96,35 +130,35 @@ describe("Index feeds", () => {
test("sends the token so your own private dumps come back", async () => {
const session = makeSession();
route("GET /api/dumps/", () => page([]));
setup("/~/new", { session });
route("GET /api/dumps", () => page([]));
setup("/new", { session });
await screen.findByText("No dumps yet. Be the first!");
expect(calls("GET /api/dumps/")[0].headers.get("Authorization")).toBe(
expect(calls("GET /api/dumps")[0].headers.get("Authorization")).toBe(
`Bearer ${session.token}`,
);
});
test("scrolling to the end loads the next page", async () => {
route(
"GET /api/dumps/",
"GET /api/dumps",
(req) =>
req.url.searchParams.get("page") === "1"
? page([newer], true)
: page([older], false),
);
setup("/~/new");
setup("/new");
await screen.findByText("Brand new");
const observer = FakeIntersectionObserver.instances.findLast((o) =>
o.elements.size > 0
)!;
act(() => observer.report(true));
await screen.findByText("Old but loved");
expect(calls("GET /api/dumps/")[1].url.searchParams.get("page")).toBe("2");
expect(calls("GET /api/dumps")[1].url.searchParams.get("page")).toBe("2");
});
test("live: a new dump goes on top; a deleted one goes away", async () => {
route("GET /api/dumps/", () => page([older]));
const { socket } = setup("/~/new");
route("GET /api/dumps", () => page([older]));
const { socket } = setup("/new");
await screen.findByText("Old but loved");
socket.receive({
type: "dump_created",
@@ -138,8 +172,8 @@ describe("Index feeds", () => {
});
test("live votes update the count", async () => {
route("GET /api/dumps/", () => page([older]));
const { socket } = setup("/~/new");
route("GET /api/dumps", () => page([older]));
const { socket } = setup("/new");
await screen.findByText("Old but loved");
socket.receive({
type: "votes_update",
@@ -154,8 +188,8 @@ describe("Index feeds", () => {
});
test("guests can't vote", async () => {
route("GET /api/dumps/", () => page([older]));
setup("/~/new");
route("GET /api/dumps", () => page([older]));
setup("/new");
await screen.findByText("Old but loved");
expect(screen.getByRole("button", { name: "Upvote" })).toHaveAttribute(
"aria-disabled",
@@ -164,9 +198,9 @@ describe("Index feeds", () => {
});
test("a reconnect backfills what was missed", async () => {
route("GET /api/dumps/", () => page([older]), { once: true });
route("GET /api/dumps/", () => page([newer, older]));
const { socket } = setup("/~/new");
route("GET /api/dumps", () => page([older]), { once: true });
route("GET /api/dumps", () => page([newer, older]));
const { socket } = setup("/new");
await screen.findByText("Old but loved");
socket.drop();
await act(() => new Promise((r) => setTimeout(r, 600)));
@@ -176,12 +210,17 @@ describe("Index feeds", () => {
test("a category scopes the feed, and live arrivals to it", async () => {
route(
"GET /api/categories/:slug/dumps",
() => page([makeDump({ title: "A song", categoryIds: ["c-music"] })]),
"GET /api/dumps",
(req) =>
page(
req.url.searchParams.get("category") === "music"
? [makeDump({ title: "A song", categoryIds: ["c-music"] })]
: [],
),
);
const { socket } = setup("/music/new");
await screen.findByText("A song");
expect(calls("GET /api/categories/:slug/dumps")[0].params.slug).toBe(
expect(calls("GET /api/dumps")[0].url.searchParams.get("category")).toBe(
"music",
);
await waitFor(() => expect(document.title).toMatch(/^Music · /));
@@ -204,23 +243,26 @@ describe("Index feeds", () => {
});
test("an unknown category is a 404", async () => {
route("GET /api/categories/:slug/dumps", () => fail("nope", 404));
route("GET /api/dumps", () => fail("nope", 404));
setup("/nonsense/new");
expect(await screen.findByRole("heading", { name: "404" }))
.toBeInTheDocument();
});
test("a guest on the followed tab gets the default feed, not a blank page", async () => {
route("GET /api/dumps/", () => page([older]));
setup("/~/followed");
test("a guest on the follow tab gets the default feed, not a blank page", async () => {
route("GET /api/dumps", () => page([older]));
setup("/follow");
await screen.findByText("Old but loved");
});
test("the Android share sheet opens the new-dump form with the link", async () => {
route("GET /api/dumps/", () => page([]));
route("GET /api/preview", () => ({ reached: false, richContent: null }));
route("GET /api/dumps/by-url", () => []);
setup("/~/new?share_url=https%3A%2F%2Fshared.test%2F", {
route("GET /api/dumps", () => page([]));
route(
"GET /api/remote/preview",
() => ({ reached: false, richContent: null }),
);
route("GET /api/dumps", () => []);
setup("/new?share_url=https%3A%2F%2Fshared.test%2F", {
session: makeSession(),
});
const dialog = await screen.findByRole("dialog", { name: "New dump" });
@@ -234,34 +276,45 @@ describe("Followed feed", () => {
test("from people and from playlists", async () => {
const session = makeSession();
route(
"GET /api/follows/feed/users",
() => page([makeDump({ title: "By a friend" })]),
"GET /api/me/feed",
(req) =>
page(
req.url.searchParams.get("from") === "users"
? [makeDump({ title: "By a friend" })]
: [],
),
);
route("GET /api/follows/feed/playlists", () => page([]));
const { user } = setup("/~/followed", { session });
const { user } = setup("/follow", { session });
await screen.findByText("By a friend");
await user.click(screen.getByRole("button", { name: "From playlists" }));
expect(
screen.getByText("Follow some public playlists to see their dumps here."),
).toBeInTheDocument();
expect(calls("GET /api/follows/feed/users")[0].headers.get("Authorization"))
.toBe(`Bearer ${session.token}`);
const [feed] = calls("GET /api/me/feed");
expect(feed.headers.get("Authorization")).toBe(`Bearer ${session.token}`);
});
test("a category narrows it", async () => {
route("GET /api/follows/feed/users", () => page([]));
route("GET /api/follows/feed/playlists", () => page([]));
setup("/music/followed", { session: makeSession() });
route("GET /api/me/feed", () => page([]));
setup("/music/follow", { session: makeSession() });
await screen.findByText("Follow some users to see their dumps here.");
expect(
calls("GET /api/follows/feed/users")[0].url.searchParams.get("category"),
).toBe("music");
calls("GET /api/me/feed").map((r) => [
r.url.searchParams.get("from"),
r.url.searchParams.get("category"),
]).sort(),
).toEqual([["playlists", "music"], ["users", "music"]]);
});
test("a server error reads as one, not as a lost connection", async () => {
route("GET /api/follows/feed/users", () => fail("Internal error", 500));
route("GET /api/follows/feed/playlists", () => page([]));
setup("/~/followed", { session: makeSession() });
route(
"GET /api/me/feed",
(req) =>
req.url.searchParams.get("from") === "users"
? fail("Internal error", 500)
: page([]),
);
setup("/follow", { session: makeSession() });
const alert = await screen.findByRole("alert");
expect(alert).toHaveTextContent("Internal error");
expect(alert).not.toHaveTextContent(/Could not connect/);