// An app's screens as URLs, as its own web names them: each route in its // .json a path and the tool call that screen is, both written // with the same tokens (`/profile/{actor}/gallery/{rkey}` and // `{"name": "query", "args": {"method": "…getGallery", "params": // {"gallery": "at://{actor}/social.grain.gallery/{rkey}"}}}`). A call is a // route's when it holds every key the route's call names, its strings // matching; keys it has besides (a page's `limit`) are no part of its URL. // Routes are tried in order, so of two for one call or one path the first // wins. A token in the path's query string (`?name={name}`) may be absent; // a literal one there (`&tab=people`) must be present. A token written // `{actor:did}` in a call needs a DID there: a handle a URL names is // resolved first. In a URL an account is its handle where the app has seen // it (`Names`), its DID otherwise. A route's `tab`, a tab's label, is the // tab a URL of it opens under, its screen over that tab's root (Grain's // places and cameras under Explore); with none, the first tab. A route // with `pager` is a story's: its screen opens in the story viewer, over // whatever it is opened from, and its URL loaded opens over the screen // its `under` names (a path written with its own path's tokens: a story's // account's profile), so closing the story goes there. import type { Call, Viewer } from '@hud/shared/result'; export type Route = { path: string; call: Call; tab?: string; pager?: boolean; under?: string }; type Bound = Record; const TOKEN = /\{(\w+)(:did)?\}/g; const isObject = (value: unknown): value is Record => typeof value === 'object' && value !== null && !Array.isArray(value); const escape = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); /** The one token a string is, or null where it is more or less. */ function sole(pattern: string): string | null { const found = /^\{(\w+)(:did)?\}$/.exec(pattern); return found ? found[1] : null; } /** Whether two calls are the same call. */ export function same(a: Call, b: Call): boolean { return JSON.stringify(a) === JSON.stringify(b); } /** * A call as the screen it opens: less its `compose`, which asks the screen * to open its form once, as the call opens it. It is no part of where the * app is: the stacks, history entries, URLs and the memory of screens hold * a call so, and a screen gone back to, loaded again or shown again opens * no form. */ export function plain(call: Call): Call { if (call.args.compose === undefined) return call; const { compose: _, ...args } = call.args; return { ...call, args }; } /** Bind a token, or check it is bound to the same. */ function bind(bound: Bound, name: string, value: string): boolean { if (name in bound) return bound[name] === value; bound[name] = value; return true; } /** A pattern string matched against a value: a token alone takes all of it, in a longer string one segment between slashes. */ function matchText(pattern: string, value: unknown, bound: Bound): boolean { const names: string[] = []; let source = ''; let last = 0; for (const token of pattern.matchAll(TOKEN)) { source += escape(pattern.slice(last, token.index)) + (token[0] === pattern ? '(.+)' : '([^/]+)'); names.push(token[1]); last = token.index + token[0].length; } if (names.length === 0) return value === pattern; if (typeof value !== 'string') return false; const found = new RegExp(`^${source}${escape(pattern.slice(last))}$`).exec(value); return found !== null && names.every((name, i) => bind(bound, name, found[i + 1])); } /** A call's pattern matched against a call, binding its tokens; `optional` names those that may be absent. */ function match(pattern: unknown, value: unknown, bound: Bound, optional: Set): boolean { if (typeof pattern === 'string') return matchText(pattern, value, bound); if (Array.isArray(pattern)) return Array.isArray(value) && value.length === pattern.length && pattern.every((p, i) => match(p, value[i], bound, optional)); if (isObject(pattern)) { if (!isObject(value)) return false; return Object.entries(pattern).every(([key, p]) => { if (value[key] !== undefined) return match(p, value[key], bound, optional); const token = typeof p === 'string' ? sole(p) : null; return token !== null && optional.has(token); }); } return pattern === value; } /** A call's pattern with its tokens filled; a key whose token is unbound left out. */ function fill(pattern: unknown, bound: Bound): unknown { if (typeof pattern === 'string') return pattern.replace(TOKEN, (_, name: string) => bound[name] ?? ''); if (Array.isArray(pattern)) return pattern.map((p) => fill(p, bound)); if (!isObject(pattern)) return pattern; const out: Record = {}; for (const [key, p] of Object.entries(pattern)) { const token = typeof p === 'string' ? sole(p) : null; if (token === null || token in bound) out[key] = fill(p, bound); } return out; } /** The tokens a call's pattern needs as DIDs. */ function dids(pattern: unknown, into = new Set()): Set { if (typeof pattern === 'string') for (const token of pattern.matchAll(TOKEN)) if (token[2]) into.add(token[1]); if (Array.isArray(pattern)) for (const p of pattern) dids(p, into); if (isObject(pattern)) for (const p of Object.values(pattern)) dids(p, into); return into; } /** A route's path, split: its segments, and its query string's keys and their patterns. */ function parts(route: Route) { const [path, search = ''] = route.path.split('?'); const query = [...new URLSearchParams(search)]; const optional = new Set(query.flatMap(([, p]) => (sole(p) ? [sole(p)!] : []))); return { path, query, optional }; } /** The accounts the app has seen, each DID's handle, and the signed-in account's (as `me`), to name them by in URLs. */ export class Names { private handles: Map; /** Names already known, as `entries()` gave them: the server's, for the page it drew. */ constructor(known: [string, string][] = []) { this.handles = new Map(known); } /** Every name known, to start another `Names` with. */ entries(): [string, string][] { return [...this.handles]; } /** Every `{did, handle}` in an answer; whether any was new. */ learn(value: unknown, depth = 0): boolean { if (depth > 12 || typeof value !== 'object' || value === null) return false; let learnt = false; if (isObject(value) && typeof value.did === 'string' && value.did.startsWith('did:') && typeof value.handle === 'string') { learnt = this.set(value.did, value.handle); } for (const child of Object.values(value)) learnt = this.learn(child, depth + 1) || learnt; return learnt; } /** The signed-in account: `me` is its handle. */ viewer(viewer: Viewer): boolean { if (viewer.handle === null) return false; const me = this.set('me', viewer.handle); return this.set(viewer.did, viewer.handle) || me; } /** What a URL shows for a value: its handle where it is an account the app has seen. */ show(value: string): string { return this.handles.get(value) ?? value; } private set(key: string, handle: string): boolean { if (handle === '' || handle === 'handle.invalid' || this.handles.get(key) === handle) return false; this.handles.set(key, handle); return true; } } /** The first route a call matches with every token of its path bound, and what they are bound to; null where none does. */ function matched(call: Call, routes: Route[]): { route: Route; bound: Bound } | null { for (const route of routes) { const { path, optional } = parts(route); const bound: Bound = {}; if (!match(route.call, call, bound, optional)) continue; if ([...path.matchAll(TOKEN)].every((token) => token[1] in bound)) return { route, bound }; } return null; } /** The route a call has (its URL's, and whether it opens in the story viewer), or null where none does. */ export const routeOf = (call: Call, routes: Route[]): Route | null => matched(call, routes)?.route ?? null; /** The path (with its query string) a call has by the first route it matches, or null where none does. */ export function pathOf(call: Call, routes: Route[], names: Names): string | null { const found = matched(call, routes); if (!found) return null; const { bound } = found; const { path, query } = parts(found.route); const pathname = path.replace(TOKEN, (_, name: string) => encodeURIComponent(names.show(bound[name]))); const search = new URLSearchParams(); for (const [key, p] of query) { const token = sole(p); if (token === null) search.set(key, p); else if (token in bound) search.set(key, names.show(bound[token])); } const text = search.toString(); return text ? `${pathname}?${text}` : pathname; } /** A screen a path is: its call, the tab it opens under, and, a story's (`pager`), the path of the screen under it where its URL is loaded (`under`, its tokens as the path named them). */ export type Found = { call: Call; tab?: string; pager?: boolean; under?: string }; /** The screen a path (and its query string) is by the first route it matches: its call, a handle resolved to a DID where the route needs one, and the tab it opens under; null where none matches. */ export async function callOf(pathname: string, search: string, routes: Route[], resolve: (actor: string) => Promise): Promise { const given = new URLSearchParams(search); for (const route of routes) { const { path, query } = parts(route); const bound: Bound = {}; if (!matchPath(path, pathname, bound)) continue; const fits = query.every(([key, p]) => { const token = sole(p); const value = given.get(key); if (token === null) return value === p; if (value !== null) bound[token] = value; return true; }); if (!fits) continue; const under = route.pager && route.under ? route.under.replace(TOKEN, (_, name: string) => encodeURIComponent(bound[name] ?? '')) : undefined; for (const name of dids(route.call)) if (bound[name] && !bound[name].startsWith('did:')) bound[name] = await resolve(bound[name]); const found: Found = { call: fill(route.call, bound) as Call, tab: route.tab }; if (route.pager) found.pager = true; if (under) found.under = under; return found; } return null; } /** A route's path matched against a URL's, segment by segment. */ function matchPath(pattern: string, pathname: string, bound: Bound): boolean { const want = pattern.split('/'); const have = pathname.replace(/\/$/, '').split('/'); if (pattern === '/') return pathname === '/' || pathname === ''; if (want.length !== have.length) return false; return want.every((segment, i) => { const token = sole(segment); if (token === null) return segment === have[i]; if (have[i] === '') return false; bound[token] = decodeURIComponent(have[i]); return true; }); } /** The strings of a call's pattern naming a record (`at://…`). */ function uris(pattern: unknown, into: string[] = []): string[] { if (typeof pattern === 'string' && pattern.startsWith('at://')) into.push(pattern); if (Array.isArray(pattern)) for (const p of pattern) uris(p, into); if (isObject(pattern)) for (const p of Object.values(pattern)) uris(p, into); return into; } /** The screen of a record, by its at:// URI: the first route whose call names a record as it does (`at://{actor}/social.grain.gallery/{rkey}`), every token of its path bound, and the tab it opens under; null where none does. */ export function recordAt(uri: string, routes: Route[]): { call: Call; tab?: string } | null { for (const route of routes) { const { path } = parts(route); for (const pattern of uris(route.call)) { const bound: Bound = {}; if (!matchText(pattern, uri, bound)) continue; if ([...path.matchAll(TOKEN)].every((token) => token[1] in bound)) return { call: fill(route.call, bound) as Call, tab: route.tab }; } } return null; }