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:
@@ -47,11 +47,17 @@ export interface Dump {
|
||||
id: string;
|
||||
kind: "url" | "file";
|
||||
title: string;
|
||||
/** Made from the title. The dump's page URL takes it in place of the id. */
|
||||
slug?: string;
|
||||
/**
|
||||
* Names the dump in its page's path, `dumpPath` (`shared/paths.ts`) building
|
||||
* it with {@link ownerUsername}. Made from the title on creation, it changes
|
||||
* only when edited, and is unique among its poster's dumps.
|
||||
*/
|
||||
slug: string;
|
||||
/** The poster's note on the dump, in Markdown. */
|
||||
comment?: string;
|
||||
userId: string;
|
||||
/** The poster's current name, which the dump's path starts with. */
|
||||
ownerUsername: string;
|
||||
createdAt: Date;
|
||||
updatedAt?: Date;
|
||||
url?: string;
|
||||
@@ -69,23 +75,23 @@ export interface Dump {
|
||||
}
|
||||
|
||||
/**
|
||||
* Returned by `GET /api/dumps/by-url` for each dump already posted with the
|
||||
* Returned by `GET /api/dumps?url=` for each dump already posted with the
|
||||
* link being typed, and shown by the create form's `DuplicateNotice`. It holds
|
||||
* only what the notice displays.
|
||||
* only what the notice displays and links to.
|
||||
*/
|
||||
export interface DumpUrlMatch {
|
||||
id: string;
|
||||
slug?: string;
|
||||
slug: string;
|
||||
title: string;
|
||||
/** The poster's username. */
|
||||
username: string;
|
||||
ownerUsername: string;
|
||||
createdAt: Date;
|
||||
voteCount: number;
|
||||
commentCount: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returned by `GET /api/preview` to the create form, which shows it before the
|
||||
* Returned by `GET /api/remote/preview` to the create form, which shows it before the
|
||||
* link is posted.
|
||||
*/
|
||||
export interface LinkPreview {
|
||||
@@ -123,6 +129,11 @@ export interface UpdateDumpRequest {
|
||||
/** Ignored for a file dump. A changed link has its preview fetched again. */
|
||||
url?: string;
|
||||
title?: string;
|
||||
/**
|
||||
* A new slug, which the edit page's slug field sends. A title change never
|
||||
* changes the slug by itself.
|
||||
*/
|
||||
slug?: string;
|
||||
/** `null` removes the note. */
|
||||
comment?: string | null;
|
||||
isPrivate?: boolean;
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
*/
|
||||
|
||||
/**
|
||||
* Returned by `GET /api/follows/status` to `FollowProvider`, which then keeps
|
||||
* Returned by `GET /api/me/follow` to `FollowProvider`, which then keeps
|
||||
* it up to date itself as the user follows and unfollows.
|
||||
*/
|
||||
export interface FollowStatus {
|
||||
|
||||
@@ -22,10 +22,26 @@ export type NotificationType =
|
||||
| "dump_commented"
|
||||
| "comment_liked";
|
||||
|
||||
/**
|
||||
* Where a notification's dump is now, for its link (`dumpPath`). The server
|
||||
* joins it each time it sends the notification, so a renamed dump or poster
|
||||
* still links right; it is absent once the dump is deleted.
|
||||
*/
|
||||
export interface DumpRef {
|
||||
dumpSlug?: string;
|
||||
dumpOwnerUsername?: string;
|
||||
}
|
||||
|
||||
/** Where a notification's playlist is now, joined as {@link DumpRef} is. */
|
||||
export interface PlaylistRef {
|
||||
playlistSlug?: string;
|
||||
playlistOwnerUsername?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Carried by a `playlist_followed` notification, sent to a playlist's owner.
|
||||
*/
|
||||
export interface PlaylistFollowedData {
|
||||
export interface PlaylistFollowedData extends PlaylistRef {
|
||||
followerId: string;
|
||||
followerUsername: string;
|
||||
playlistId: string;
|
||||
@@ -42,7 +58,7 @@ export interface UserFollowedData {
|
||||
* Carried by a `user_dump_posted` notification, sent to the followers of a
|
||||
* user who posted a public dump.
|
||||
*/
|
||||
export interface UserDumpPostedData {
|
||||
export interface UserDumpPostedData extends DumpRef {
|
||||
dumperId: string;
|
||||
dumperUsername: string;
|
||||
dumpId: string;
|
||||
@@ -53,7 +69,7 @@ export interface UserDumpPostedData {
|
||||
* Carried by a `playlist_dump_added` notification, sent to the followers of a
|
||||
* public playlist when a public dump is added to it.
|
||||
*/
|
||||
export interface PlaylistDumpAddedData {
|
||||
export interface PlaylistDumpAddedData extends DumpRef, PlaylistRef {
|
||||
dumpId: string;
|
||||
dumpTitle: string;
|
||||
playlistId: string;
|
||||
@@ -61,7 +77,7 @@ export interface PlaylistDumpAddedData {
|
||||
}
|
||||
|
||||
/** Carried by a `dump_upvoted` notification, sent to the dump's poster. */
|
||||
export interface DumpUpvotedData {
|
||||
export interface DumpUpvotedData extends DumpRef {
|
||||
voterId: string;
|
||||
voterUsername: string;
|
||||
dumpId: string;
|
||||
@@ -70,9 +86,11 @@ export interface DumpUpvotedData {
|
||||
|
||||
/**
|
||||
* Carried by a `user_mentioned` notification, sent to a user @mentioned in a
|
||||
* comment, a dump, a playlist's description or a chat message.
|
||||
* comment, a dump, a playlist's description or a chat message. Its
|
||||
* {@link DumpRef} is the dump's, or the comment's dump's; its
|
||||
* {@link PlaylistRef} the playlist's.
|
||||
*/
|
||||
export interface UserMentionedData {
|
||||
export interface UserMentionedData extends DumpRef, PlaylistRef {
|
||||
mentionerId: string;
|
||||
mentionerUsername: string;
|
||||
contextType: "comment" | "dump" | "playlist" | "chat";
|
||||
@@ -91,7 +109,7 @@ export interface UserMentionedData {
|
||||
}
|
||||
|
||||
/** Carried by a `dump_commented` notification, sent to the dump's poster. */
|
||||
export interface DumpCommentedData {
|
||||
export interface DumpCommentedData extends DumpRef {
|
||||
commenterId: string;
|
||||
commenterUsername: string;
|
||||
commentId: string;
|
||||
@@ -100,7 +118,7 @@ export interface DumpCommentedData {
|
||||
}
|
||||
|
||||
/** Carried by a `comment_liked` notification, sent to the comment's author. */
|
||||
export interface CommentLikedData {
|
||||
export interface CommentLikedData extends DumpRef {
|
||||
likerId: string;
|
||||
likerUsername: string;
|
||||
commentId: string;
|
||||
@@ -109,9 +127,9 @@ export interface CommentLikedData {
|
||||
}
|
||||
|
||||
/**
|
||||
* A snapshot taken when the notification is made: a name or title changed
|
||||
* later still shows the old one. The notification's `type` says which member
|
||||
* it is.
|
||||
* Stored when the notification is made, so a title changed later still shows
|
||||
* the old one. The `…Username` fields and the refs are joined when it is sent,
|
||||
* so they follow a rename. The notification's `type` says which member it is.
|
||||
*/
|
||||
export type NotificationData =
|
||||
| PlaylistFollowedData
|
||||
@@ -125,7 +143,7 @@ export type NotificationData =
|
||||
|
||||
/**
|
||||
* Pushed to its user's sockets in a `notification_created` message when it is
|
||||
* made, and returned by `GET /api/notifications`.
|
||||
* made, and returned by `GET /api/me/notifications`.
|
||||
*/
|
||||
export interface Notification {
|
||||
id: string;
|
||||
|
||||
163
shared/paths.ts
Normal file
163
shared/paths.ts
Normal file
@@ -0,0 +1,163 @@
|
||||
/**
|
||||
* Builds and parses the site's page paths, by the one rule they all follow:
|
||||
* the path is a hierarchy, `@name` is a user, and any other word under the
|
||||
* root is a category or an app page. Under a user each segment is a fixed tab
|
||||
* name, and under `dumps` or `playlists` a slug. A view of a page is one more
|
||||
* segment, and a default view is the bare path.
|
||||
*
|
||||
* The client links every page through the builders (`src/utils/shared/urls.ts`
|
||||
* wraps the dump and playlist ones), the emails prefix them with the
|
||||
* frontend's URL, and the server's matchers (the Open Graph tags, the
|
||||
* previews and backlinks of links to this site) read paths with
|
||||
* {@link parsePagePath}. Migration 0021 rewrote the v3 links in stored text
|
||||
* with the builders.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
|
||||
/**
|
||||
* The feed tabs, in the tab bar's order. Each is a path segment: `/hot` for
|
||||
* every dump, `/music/hot` for a category. They are reserved at the root, so
|
||||
* no category can take one.
|
||||
*/
|
||||
export const FEED_TABS = ["hot", "new", "journal", "follow"] as const;
|
||||
/** One of the {@link FEED_TABS}. */
|
||||
export type FeedTab = (typeof FEED_TABS)[number];
|
||||
|
||||
/**
|
||||
* The tabs of a profile, each a segment after `/@name`. The bare `/@name` is
|
||||
* the overview.
|
||||
*/
|
||||
export const PROFILE_TABS = [
|
||||
"dumps",
|
||||
"upvoted",
|
||||
"playlists",
|
||||
"follow",
|
||||
"invitees",
|
||||
"manage",
|
||||
] as const;
|
||||
/** One of the {@link PROFILE_TABS}. */
|
||||
export type ProfileTab = (typeof PROFILE_TABS)[number];
|
||||
|
||||
/**
|
||||
* The views of a profile's `follow` tab: the users followed at
|
||||
* `/@name/follow`, the playlists at `/@name/follow/playlists`.
|
||||
*/
|
||||
export const FOLLOW_VIEWS = ["users", "playlists"] as const;
|
||||
/** One of the {@link FOLLOW_VIEWS}. */
|
||||
export type FollowView = (typeof FOLLOW_VIEWS)[number];
|
||||
|
||||
/**
|
||||
* The tabs of the search page: the dumps at `/search`, the others at
|
||||
* `/search/<tab>`.
|
||||
*/
|
||||
export const SEARCH_TABS = ["dumps", "users", "playlists"] as const;
|
||||
/** One of the {@link SEARCH_TABS}. */
|
||||
export type SearchTab = (typeof SEARCH_TABS)[number];
|
||||
|
||||
/** Passed to {@link dumpPath} and {@link playlistPath}, usually as the item. */
|
||||
export interface OwnedItem {
|
||||
ownerUsername: string;
|
||||
slug: string;
|
||||
}
|
||||
|
||||
const seg = encodeURIComponent;
|
||||
|
||||
/**
|
||||
* Returns the path of `username`'s profile, of one of its tabs, or of a view
|
||||
* of the `follow` tab. The default view, `users`, is the bare tab.
|
||||
*/
|
||||
export function userPath(
|
||||
username: string,
|
||||
tab?: ProfileTab,
|
||||
view?: FollowView,
|
||||
): string {
|
||||
const base = `/@${seg(username)}`;
|
||||
if (!tab) return base;
|
||||
return view && view !== FOLLOW_VIEWS[0]
|
||||
? `${base}/${tab}/${view}`
|
||||
: `${base}/${tab}`;
|
||||
}
|
||||
|
||||
/** Returns the path of a dump's page, `/@owner/dumps/<slug>`. */
|
||||
export function dumpPath(dump: OwnedItem): string {
|
||||
return `${userPath(dump.ownerUsername)}/dumps/${seg(dump.slug)}`;
|
||||
}
|
||||
|
||||
/** Returns the path of a playlist's page, `/@owner/playlists/<slug>`. */
|
||||
export function playlistPath(playlist: OwnedItem): string {
|
||||
return `${userPath(playlist.ownerUsername)}/playlists/${seg(playlist.slug)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the path of a feed: every dump's at the root, or a category's at
|
||||
* `/<slug>`, on `tab`, or on the viewer's default tab without one.
|
||||
*/
|
||||
export function feedPath(categorySlug?: string, tab?: FeedTab): string {
|
||||
const base = categorySlug ? `/${seg(categorySlug)}` : "";
|
||||
return tab ? `${base}/${tab}` : base || "/";
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the path of the search page on `tab`, searching `query` when it is
|
||||
* given.
|
||||
*/
|
||||
export function searchPath(tab: SearchTab = "dumps", query?: string): string {
|
||||
const base = tab === SEARCH_TABS[0] ? "/search" : `/search/${tab}`;
|
||||
return query ? `${base}?q=${seg(query)}` : base;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returned by {@link parsePagePath} for a path under a user. `rest` holds the
|
||||
* segments after `/@name`, a profile tab and its view.
|
||||
*/
|
||||
export type PagePath =
|
||||
| { kind: "user"; username: string; rest: string[] }
|
||||
| { kind: "dump"; username: string; slug: string; edit: boolean }
|
||||
| { kind: "playlist"; username: string; slug: string };
|
||||
|
||||
/**
|
||||
* Returns what a page path under a user names: a profile (with its tab), a
|
||||
* dump (or its editor) or a playlist. It returns null for any other path, a
|
||||
* feed or an app page, and for one under a user that no page answers. The
|
||||
* names are decoded but not looked up, so the user or the item may not exist.
|
||||
*/
|
||||
export function parsePagePath(pathname: string): PagePath | null {
|
||||
let segments: string[];
|
||||
try {
|
||||
segments = pathname.replace(/\/+$/, "").split("/").slice(1).map(
|
||||
decodeURIComponent,
|
||||
);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
const [handle, section, slug, ...more] = segments;
|
||||
if (!handle?.startsWith("@") || !/^\w+$/.test(handle.slice(1))) return null;
|
||||
const username = handle.slice(1);
|
||||
|
||||
if ((section === "dumps" || section === "playlists") && slug) {
|
||||
if (section === "dumps" && more.length <= 1) {
|
||||
if (more.length === 0) {
|
||||
return { kind: "dump", username, slug, edit: false };
|
||||
}
|
||||
if (more[0] === "edit") {
|
||||
return { kind: "dump", username, slug, edit: true };
|
||||
}
|
||||
}
|
||||
if (section === "playlists" && more.length === 0) {
|
||||
return { kind: "playlist", username, slug };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const rest = segments.slice(1);
|
||||
if (rest.length === 0) return { kind: "user", username, rest };
|
||||
if (!(PROFILE_TABS as readonly string[]).includes(rest[0])) return null;
|
||||
if (rest.length === 1) return { kind: "user", username, rest };
|
||||
if (
|
||||
rest.length === 2 && rest[0] === "follow" &&
|
||||
(FOLLOW_VIEWS as readonly string[]).includes(rest[1]) &&
|
||||
rest[1] !== FOLLOW_VIEWS[0]
|
||||
) return { kind: "user", username, rest };
|
||||
return null;
|
||||
}
|
||||
@@ -29,7 +29,7 @@ export interface TralbumTrack {
|
||||
}
|
||||
|
||||
/**
|
||||
* Returned by `GET /api/bandcamp/tracks` for a Bandcamp album or track page,
|
||||
* Returned by `GET /api/remote/bandcamp` for a Bandcamp album or track page,
|
||||
* when the native player plays it.
|
||||
*/
|
||||
export interface Tralbum {
|
||||
@@ -55,7 +55,7 @@ export interface YouTubePlaylistTrack {
|
||||
}
|
||||
|
||||
/**
|
||||
* Returned by `GET /api/youtube/playlist` to the player, which shows the
|
||||
* Returned by `GET /api/remote/youtube` to the player, which shows the
|
||||
* titles and lengths of a playlist embed's videos, since the embed exposes
|
||||
* neither.
|
||||
*/
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* Playlists are ordered collections of dumps their owners curate. This module
|
||||
* types them, with the bodies that create, edit and reorder them. The client
|
||||
* shows them on `/playlists/:playlistId`, on profiles and in search results.
|
||||
* shows them on `/@owner/playlists/:slug`, on profiles and in search results.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
@@ -17,7 +17,13 @@ export interface Playlist {
|
||||
id: string;
|
||||
userId: string;
|
||||
title: string;
|
||||
slug?: string;
|
||||
/**
|
||||
* Names the playlist in its page's path, `playlistPath`
|
||||
* (`shared/paths.ts`) building it with {@link ownerUsername}. Made from the
|
||||
* title on creation, it changes only when edited, and is unique among its
|
||||
* owner's playlists.
|
||||
*/
|
||||
slug: string;
|
||||
/** It is written in Markdown. */
|
||||
description?: string;
|
||||
/**
|
||||
@@ -35,24 +41,25 @@ export interface Playlist {
|
||||
imageMime?: string;
|
||||
/**
|
||||
* It counts the dumps the viewer can't see too. It is undefined when the
|
||||
* query didn't count them, as for a new playlist or a membership.
|
||||
* query didn't count them.
|
||||
*/
|
||||
dumpCount?: number;
|
||||
/** It is undefined where `dumpCount` is. */
|
||||
ownerUsername?: string;
|
||||
/** The owner's current name, which the playlist's path starts with. */
|
||||
ownerUsername: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returned by `GET /api/playlists/:playlistId` to `PlaylistDetail`, with the
|
||||
* dumps the caller may see, in the playlist's order.
|
||||
* Returned by `GET /api/users/:key/playlists/:slug` to `PlaylistDetail`, and
|
||||
* by `GET /api/playlists/:playlistId`, with the dumps the caller may see, in
|
||||
* the playlist's order.
|
||||
*/
|
||||
export interface PlaylistWithDumps extends Playlist {
|
||||
dumps: Dump[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returned by `GET /api/playlists/by-dump/:dumpId/memberships`, one per
|
||||
* playlist of the caller's. `PlaylistMembershipPanel` ticks the playlists
|
||||
* Returned by `GET /api/me/playlists?contains=:dumpId`, one per playlist of
|
||||
* the caller's. `PlaylistMembershipPanel` ticks the playlists
|
||||
* with `hasDump`, in the add-to-playlist modal and the dump form.
|
||||
*/
|
||||
export interface PlaylistMembership {
|
||||
@@ -73,6 +80,11 @@ export interface CreatePlaylistRequest {
|
||||
*/
|
||||
export interface UpdatePlaylistRequest {
|
||||
title?: string;
|
||||
/**
|
||||
* A new slug, which the edit form's slug field sends. A title change never
|
||||
* changes the slug by itself.
|
||||
*/
|
||||
slug?: string;
|
||||
/** `null` removes the description. */
|
||||
description?: string | null;
|
||||
isPublic?: boolean;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* A user's settings follow their account from browser to browser, and the
|
||||
* server reads some of them itself (a digest is drawn in its reader's style).
|
||||
* This module types them for `GET` and `PATCH /api/users/me/settings`; the
|
||||
* This module types them for `GET` and `PATCH /api/me/settings`; the
|
||||
* client keeps them with its session.
|
||||
*
|
||||
* @module
|
||||
@@ -10,7 +10,7 @@
|
||||
import type { ColorScheme, StyleName } from "./theme.ts";
|
||||
|
||||
/**
|
||||
* Returned by `GET /api/users/me/settings`, and by a `PATCH` once applied.
|
||||
* Returned by `GET /api/me/settings`, and by a `PATCH` once applied.
|
||||
* The client's `useSettings` reads it from the session.
|
||||
*/
|
||||
export interface UserSettings {
|
||||
@@ -29,7 +29,7 @@ export interface UserSettings {
|
||||
}
|
||||
|
||||
/**
|
||||
* Sent to `PATCH /api/users/me/settings` with the settings to change; the
|
||||
* Sent to `PATCH /api/me/settings` with the settings to change; the
|
||||
* others keep their value.
|
||||
*/
|
||||
export type UpdateSettingsRequest = Partial<UserSettings>;
|
||||
|
||||
50
shared/slug.ts
Normal file
50
shared/slug.ts
Normal file
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* Defines what a slug is: the readable name of a category, a dump or a
|
||||
* playlist in a page URL. The server makes and checks slugs with it, and the
|
||||
* edit forms prefill their slug field with {@link slugify}.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
|
||||
/** The longest a dump's or a playlist's slug may be. */
|
||||
export const SLUG_MAX = 60;
|
||||
|
||||
/**
|
||||
* Matches a well-formed slug: lowercase letters and digits, in words joined by
|
||||
* single hyphens. Categories, dumps and playlists share it.
|
||||
*/
|
||||
export const SLUG_RE: RegExp = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
||||
|
||||
/**
|
||||
* Checks whether `slug` matches {@link SLUG_RE} and is at most `max`
|
||||
* characters long.
|
||||
*/
|
||||
export function isValidSlug(slug: string, max: number = SLUG_MAX): boolean {
|
||||
return slug.length <= max && SLUG_RE.test(slug);
|
||||
}
|
||||
|
||||
/**
|
||||
* Turns `title` into lowercase ASCII words joined by hyphens, at most `max`
|
||||
* characters long, cut at a hyphen when it must be cut. Accents are dropped,
|
||||
* and a title with no ASCII letter or digit gives `untitled`. The result
|
||||
* always passes {@link isValidSlug}.
|
||||
*/
|
||||
export function slugify(title: string, max: number = SLUG_MAX): string {
|
||||
const slug = title
|
||||
.toLowerCase()
|
||||
.normalize("NFD")
|
||||
// NFD splits an accented letter into the letter and a combining mark.
|
||||
.replace(/[\u0300-\u036f]/g, "")
|
||||
.replace(/[^a-z0-9]+/g, "-")
|
||||
.substring(0, max + 1)
|
||||
.replace(/^-+/, "");
|
||||
// Cut at the last hyphen within `max` rather than in the middle of a word,
|
||||
// unless the first word alone is longer.
|
||||
const cut = slug.length > max
|
||||
? slug.substring(
|
||||
0,
|
||||
slug.lastIndexOf("-", max) > 0 ? slug.lastIndexOf("-", max) : max,
|
||||
)
|
||||
: slug;
|
||||
return cut.replace(/-+$/, "") || "untitled";
|
||||
}
|
||||
77
shared/test/paths.test.ts
Normal file
77
shared/test/paths.test.ts
Normal file
@@ -0,0 +1,77 @@
|
||||
import { assertEquals } from "@std/assert";
|
||||
import {
|
||||
dumpPath,
|
||||
feedPath,
|
||||
parsePagePath,
|
||||
playlistPath,
|
||||
searchPath,
|
||||
userPath,
|
||||
} from "../paths.ts";
|
||||
|
||||
Deno.test("builders: one hierarchy, default views bare", () => {
|
||||
assertEquals(userPath("bob"), "/@bob");
|
||||
assertEquals(userPath("bob", "playlists"), "/@bob/playlists");
|
||||
assertEquals(userPath("bob", "follow"), "/@bob/follow");
|
||||
assertEquals(userPath("bob", "follow", "users"), "/@bob/follow");
|
||||
assertEquals(
|
||||
userPath("bob", "follow", "playlists"),
|
||||
"/@bob/follow/playlists",
|
||||
);
|
||||
const item = { ownerUsername: "bob", slug: "never-gonna" };
|
||||
assertEquals(dumpPath(item), "/@bob/dumps/never-gonna");
|
||||
assertEquals(playlistPath(item), "/@bob/playlists/never-gonna");
|
||||
assertEquals(feedPath(), "/");
|
||||
assertEquals(feedPath(undefined, "hot"), "/hot");
|
||||
assertEquals(feedPath("music"), "/music");
|
||||
assertEquals(feedPath("music", "follow"), "/music/follow");
|
||||
assertEquals(searchPath(), "/search");
|
||||
assertEquals(searchPath("users", "a b"), "/search/users?q=a%20b");
|
||||
assertEquals(searchPath("dumps", "x"), "/search?q=x");
|
||||
});
|
||||
|
||||
Deno.test("parsePagePath: what a path under a user names", () => {
|
||||
assertEquals(parsePagePath("/@bob"), {
|
||||
kind: "user",
|
||||
username: "bob",
|
||||
rest: [],
|
||||
});
|
||||
assertEquals(parsePagePath("/@bob/follow/playlists/"), {
|
||||
kind: "user",
|
||||
username: "bob",
|
||||
rest: ["follow", "playlists"],
|
||||
});
|
||||
assertEquals(parsePagePath("/@bob/dumps/never-gonna"), {
|
||||
kind: "dump",
|
||||
username: "bob",
|
||||
slug: "never-gonna",
|
||||
edit: false,
|
||||
});
|
||||
assertEquals(parsePagePath("/%40bob/dumps/x/edit"), {
|
||||
kind: "dump",
|
||||
username: "bob",
|
||||
slug: "x",
|
||||
edit: true,
|
||||
});
|
||||
assertEquals(parsePagePath("/@bob/playlists/mix"), {
|
||||
kind: "playlist",
|
||||
username: "bob",
|
||||
slug: "mix",
|
||||
});
|
||||
for (
|
||||
const other of [
|
||||
"/",
|
||||
"/hot",
|
||||
"/music/hot",
|
||||
"/search/users",
|
||||
"/@",
|
||||
"/@b-ob",
|
||||
"/@bob/nope",
|
||||
"/@bob/follow/users",
|
||||
"/@bob/dumps/x/y",
|
||||
"/@bob/playlists/x/edit",
|
||||
"/@bob/%E0%A4%A",
|
||||
]
|
||||
) {
|
||||
assertEquals(parsePagePath(other), null, other);
|
||||
}
|
||||
});
|
||||
25
shared/test/slug.test.ts
Normal file
25
shared/test/slug.test.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
import { assert, assertEquals, assertFalse } from "@std/assert";
|
||||
import { isValidSlug, slugify } from "../slug.ts";
|
||||
|
||||
Deno.test("slugify: lowercases, strips accents, dashes the rest", () => {
|
||||
assertEquals(slugify("Hello, World!"), "hello-world");
|
||||
assertEquals(slugify("Crème brûlée à Paris"), "creme-brulee-a-paris");
|
||||
assertEquals(slugify(" --already--dashed-- "), "already-dashed");
|
||||
assertEquals(slugify("日本語"), "untitled");
|
||||
assertEquals(slugify(""), "untitled");
|
||||
assertEquals(slugify("x".repeat(100)).length, 60);
|
||||
// A long title is cut at a word boundary, never left with a hyphen.
|
||||
const long = slugify(`${"word ".repeat(12)}tail`);
|
||||
assertEquals(long, "word-".repeat(12).slice(0, -1));
|
||||
assert(isValidSlug(long));
|
||||
});
|
||||
|
||||
Deno.test("isValidSlug: the format categories, dumps and playlists share", () => {
|
||||
assert(isValidSlug("music"));
|
||||
assert(isValidSlug("lo-fi-2"));
|
||||
for (const bad of ["Music", "-music", "music-", "lo--fi", "lo fi", ""]) {
|
||||
assertFalse(isValidSlug(bad), bad);
|
||||
}
|
||||
assertFalse(isValidSlug("a".repeat(61)));
|
||||
assertFalse(isValidSlug("a".repeat(51), 50));
|
||||
});
|
||||
@@ -10,7 +10,7 @@
|
||||
/**
|
||||
* Sets what a user may do beyond the basics, through `ROLE_PERMISSIONS`
|
||||
* (`shared/permissions.ts`). An admin changes it with
|
||||
* `PATCH /api/users/:userId/role`.
|
||||
* `PATCH /api/users/:key/role`.
|
||||
*/
|
||||
export type Role = "user" | "moderator" | "admin";
|
||||
|
||||
@@ -33,7 +33,10 @@ export function isRole(value: unknown): value is Role {
|
||||
*/
|
||||
export interface PublicUser {
|
||||
id: string;
|
||||
/** Fixed at sign-up. */
|
||||
/**
|
||||
* Picked at sign-up, and changeable since, a former name staying an alias
|
||||
* of the user for good. Pages write it as `@name` (`userPath`).
|
||||
*/
|
||||
username: string;
|
||||
role: Role;
|
||||
createdAt: Date;
|
||||
@@ -51,7 +54,7 @@ export interface PublicUser {
|
||||
|
||||
/**
|
||||
* Returned to a user about themselves: by sign-up and sign-in in
|
||||
* {@link AuthResponse}, by `GET /api/users/me`, and by an avatar upload.
|
||||
* {@link AuthResponse}, by `GET /api/me`, and by an avatar upload.
|
||||
*/
|
||||
export interface SelfUser extends PublicUser {
|
||||
/** Where password reset links go. It belongs to this account only. */
|
||||
@@ -59,7 +62,7 @@ export interface SelfUser extends PublicUser {
|
||||
}
|
||||
|
||||
/**
|
||||
* Returned by `GET /api/users/search` to the editor's @mention autocomplete.
|
||||
* Returned by `GET /api/users?q=` to the editor's @mention autocomplete.
|
||||
*/
|
||||
export interface UserSuggestion {
|
||||
id: string;
|
||||
@@ -70,7 +73,7 @@ export interface UserSuggestion {
|
||||
|
||||
/**
|
||||
* Returned, as a flat list in sign-up order, by
|
||||
* `GET /api/users/:username/invitees`. The profile page nests it into a tree
|
||||
* `GET /api/users/:key/invitees`. The profile page nests it into a tree
|
||||
* by `invitedById`.
|
||||
*/
|
||||
export interface Invitee {
|
||||
@@ -82,13 +85,13 @@ export interface Invitee {
|
||||
createdAt: Date;
|
||||
}
|
||||
|
||||
/** Sent to `POST /api/users/login` by the login page. */
|
||||
/** Sent to `POST /api/sessions` by the login page. */
|
||||
export interface LoginUserRequest {
|
||||
username: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
/** Sent to `POST /api/users/register` by the register page. */
|
||||
/** Sent to `POST /api/users` by the register page. */
|
||||
export interface RegisterUserRequest {
|
||||
username: string;
|
||||
password: string;
|
||||
@@ -98,9 +101,10 @@ export interface RegisterUserRequest {
|
||||
}
|
||||
|
||||
/**
|
||||
* Passed to `updateUser` by the users routes and the password reset. Of a
|
||||
* client's body, `PATCH /api/users/me` takes only `description` and `email`;
|
||||
* the role and the password change through their own endpoints.
|
||||
* Passed to `updateUser` by the users routes and the password reset, and sent
|
||||
* by a client to `PATCH /api/me`, which takes only `description`, `email` and
|
||||
* `username`; the role and the password change through their own endpoints,
|
||||
* and the username through `renameUser`.
|
||||
*/
|
||||
export interface UpdateUserRequest {
|
||||
username?: string;
|
||||
@@ -131,7 +135,7 @@ export interface AuthResponse extends AuthTokens {
|
||||
}
|
||||
|
||||
/**
|
||||
* Returned by `GET /api/users/me/media-token` to a session from before media
|
||||
* Returned by `GET /api/me/media-token` to a session from before media
|
||||
* tokens, which has none.
|
||||
*/
|
||||
export type MediaTokenResponse = Pick<AuthTokens, "mediaToken">;
|
||||
|
||||
@@ -37,6 +37,17 @@ export const USERNAME_RE: RegExp = new RegExp(
|
||||
`^[a-zA-Z0-9_]{${VALIDATION.USERNAME_MIN},${VALIDATION.USERNAME_MAX}}$`,
|
||||
);
|
||||
|
||||
/**
|
||||
* How often a slug or a username may change, counted from the aliases the
|
||||
* changes left: a dump's or a playlist's slug 3 times a day, a username once
|
||||
* a month. Moderators are exempt. The services refuse a change past it with a
|
||||
* 429, and the forms say what the limit is.
|
||||
*/
|
||||
export const RENAME_LIMITS = {
|
||||
SLUG: { count: 3, windowMs: 24 * 3_600_000 },
|
||||
USERNAME: { count: 1, windowMs: 30 * 24 * 3_600_000 },
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* Matches an email address well enough to catch a typo; only the reset email
|
||||
* arriving proves it.
|
||||
|
||||
Reference in New Issue
Block a user