Cotton code
904 lines · 42.9 KB · SwiftRaw
// Where the app is, as a value — one case per screen the phone has.//// Design P6: **the route STRINGS are wire protocol and do not move.** The// Android keyboard's links carry them,// `NOTIFICATION_ROUTES` maps to them, and `tinmen-cotton://capture` is a// documented entry point. So the LIST is not this file's opinion: it is// `crates/cotton-ffi/src/phone/routes.rs`'s `ROUTES`, and// `RouteTableTests` holds this enum's `allPatterns` set-equal to it. This file// is a parser and a formatter over a list somebody else already agreed.//// One parser (`Route.parse`) and one formatter (`route.path`), and every// external caller goes through the pair — a deep link, a notification. `parse(r.path) == r` for every case, which is what makes the// pair a bijection rather than two tables that agree today.//// Matching is EXACT, never a prefix: `/todos/done` and `/todos/todo/[id]` are// two screens, and a parser that answered "yes" to `/todos/anything` would send// a notification tap to the wrong one. Where a literal and a parameter could// both match one path (`/messages/import` against `/messages/[thread]`,// `/calendar/event/edit` against `/calendar/event/[id]`) the LITERAL wins, and// that is a property of the ordering rather than of the order the cases happen// to be written in: candidates are tried by ascending parameter count.//// Query state rides on the case that reads it, so a route is one value rather// than a value plus a dictionary. The set is small and evidenced — it is what// this app actually puts in a query string (`?date=`, `?at=`, `?new=1`,// `?import=1`, `?project=`, `?status=`, `?person=`, and `?raise=` on any// page — the one parameter no case owns, `.raised` wraps the page) and// nothing else.// A path pattern is a different thing from the query that rides on it, which is// why `allPatterns` below carries no query at all and the Rust `ROUTES` table// it is set-compared against is untouched by any of these flags.import Foundationpublic indirect enum Route: Hashable, Sendable {    /// `/`    case root    /// `/money`    case money    /// `/money/accounts/[id]`    case moneyAccount(id: String)    /// `/money/statements/[id]`    case moneyStatement(id: String)    /// `/money/transactions/[id]`    case moneyTransaction(id: String)    /// `/activity`    case activity    /// `/alarms`    case alarms    /// `/bin`    case bin    /// `/tools` — the Tools screen (Spec 9.1): every tool of this database,    /// On Home in Home's order and Not on Home. Home's fixed last entry.    case tools    /// `/tools/board/[id]` — a data tool's own board: a tile per table of the    /// package, each opening that table's list. A route, not a view pushed    /// beside the path, for the reason `tableList` is one — and because a    /// board pushed over Home cannot push a view of its own (build 228's    /// Disk: SwiftUI honours one `navigationDestination(item:)` per type, the    /// one nearest the root, so the pushed board's was ignored).    case toolBoard(id: String)    /// `/briefing`    case briefing(project: String?)    /// `/calendar`    case calendar(date: String?, show: String? = nil)    /// `/calendar/event/[id]`    case calendarEvent(id: String, date: String?, at: String?)    /// `/calendar/event/edit`    case calendarEventEdit(id: String?, date: String?, at: String?)    /// `/calendar/month`    case calendarMonth(date: String?)    /// `/calls/call/[id]`    case callsCall(id: String)    /// `/calls/history`    case callsHistory(person: String?)    /// `/camera` — the Camera tool's live capture surface; each shot is saved    /// into Cotton at once (`camera.shot`).    case camera    /// `/capture`    case capture    /// `/code`    case code    /// `/code/new` — the ONE form that starts a session. `project` is the    /// project it opens on (`?project=`), which is what the project page's own    /// `+` carries; `nil` is the form asking.    case codeNew(project: String?)    /// `/code/defaults` — the one page of what a new session starts on.    case codeDefaults    /// `/devices` — the machines that hold this database.    case devices    /// `/devices/[id]` — one machine: what it is, where it stands in the    /// serving order, and what it may run.    case devicesId(id: String)    /// `/devices/[id]/storage` — what another device keeps, by tool, and its    /// keep rules, set from here and applied there (Spec 10.5).    case deviceStorage(id: String)    /// `/documents`    case documents(status: String?)    /// `/documents/document/[id]`    case documentsDocument(id: String)    /// `/documents/document/[id]/viewer`    case documentsDocumentViewer(id: String)    /// `/documents/import`    case documentsImport    /// `/email`    case email    /// `/email/[id]` — `?at=` names the message a Find hit matched, which the    /// reader opens on (mailsearch); absent, it opens at the newest.    case emailId(id: String, at: String? = nil)    /// `/goals`    case goals    /// `/goals/goal/[id]`    case goalsGoal(id: String)    /// `/home`    case home    /// `/storage` — what this device holds by tool, its keep rules and the    /// room to free (Spec 10.5).    case storage    /// `/storage/[id]` — one line of it: a kind, a file, a chat.    case storageId(id: String)    /// `/journal`    case journal    /// `/journal/[date]`    case journalDate(date: String)    /// `/keyboard-take`    case keyboardTake    /// `/lists/[table]` — one table's own list narrowed by a `where` (`?where=`,    /// its column values as JSON, a value or an array meaning any of them),    /// under a title (`?title=`), searched (`?q=`): what a list link, a    /// capped section's "All 2,120" and a page's side link open. A route,    /// not a view pushed beside the path, so the records opened from it push    /// onto the same stack and Back comes back to it.    case tableList(table: String, filter: String?, title: String?, query: String?, archived: Bool = false, section: String? = nil,                   view: String? = nil)    /// `/lists/[table]/[id]` — one record of a table no named route addresses    /// (a data tool's row, an alarm, the database's own record): its table's    /// page. A record WITH a route of its own opens there (`BoardRecord.route`).    case tableRecord(table: String, id: String)    /// `/legal/privacy`    case aboutWhatsNew    case aboutHelp    case legalPrivacy    /// `/legal/terms`    case legalTerms    /// `/locations`    case locations    /// `/locations/location/[id]`    case locationsLocation(id: String)    /// `/meetings` — `importing: true` is `?import=1`, the + fan asking the    /// list to raise its file picker on arrival. A PARAM rather than a second    /// route, exactly as `/todos?new=1` is: the link names an INTENT and the    /// screen behind it stays free to move, and the route TABLE is untouched    /// because a query is not a path.    case meetings(importing: Bool)    /// `/meetings/meeting/[id]`    case meetingsMeeting(id: String)    /// `/meetings/record` — Meetings asked to record: the meeting table's list    /// with the recorder drawn as a sheet over it (`MeetingRecorderSheet`), the    /// way `?import=1` is the list with the picker up. Recording is a FLOW on    /// the list, never a record screen: the meeting it makes is the meeting    /// table's page. The sheet reads nothing (its line in    /// `phone/reads.rs::READ_LESS` says so); what it produces is one    /// `meetings.create` call at Stop. The path stays, because the lock-screen    /// card, the + fan and the definition's "Record a meeting" all name it.    case meetingsRecord    /// `/memory/[id]`    case memory(id: String)    /// `/memory/dropped`    case memoryDropped    /// `/messages`    case messages    /// `/messages/[thread]`    case messagesThread(thread: String)    /// `/messages/[thread]/info`    case messagesInfo(thread: String)    /// `/messages/[thread]/media`    case messagesMedia(thread: String)    /// `/messages/import`    case messagesImport    /// `/messages/new` — a Cotton chat started with a number or a person    /// (Messages' Plus, `ChatStartScreen`).    case messagesNew    /// `/messages/starred`    case messagesStarred    /// `/mood` — the timeline of moments. It carries nothing: a link that    /// still says `?score=4` (the retired mood link's) opens the screen and    /// records nothing, because a moment is something a person says.    case mood    /// `/news`    case news    /// `/news/edition/[id]`    case newsEdition(id: String)    /// `/news/settings`    case newsSettings    /// `/news/topic/[id]`    case newsTopic(id: String)    /// `/news/topic/new`    case newsTopicNew    /// `/notes`    case notes    /// `/notes/journal-today`    case notesJournalToday    /// `/notes/note/[id]`    case notesNote(id: String)    /// `/passwords`    case passwords    /// `/passwords/[id]`    case passwordsSecret(id: String)    /// `/people`    case people    /// `/people/import` — People asked to import: the person table's list with    /// the contacts import drawn as a sheet over it (`PeopleImportSheet`), the    /// list's "Import contacts" act. The path stays, because the definition's    /// menu line, the + fan's Contact and the Imports list all name it.    case peopleImport    /// `/people/person/[id]`    case peoplePerson(id: String, database: String? = nil)    /// `/people/person/[id]/[section]` — one kind of record about one person,    /// in full (the person page shows a few of each).    case peoplePersonSection(id: String, section: String)    /// `/photos` — the one library of pictures AND films. `show` is    /// `photos` or `videos` to narrow it; `nil` is everything.    case photos(show: String?)    /// `/photos/album/[id]`    case photosAlbum(id: String)    /// `/photos/album/[id]/add`    case photosAlbumAdd(id: String)    /// `/photos/albums`    case photosAlbums    /// `/photos/duplicates`    case photosDuplicates    /// `/photos/people`    case photosPeople    /// `/photos/photo/[id]`    case photosPhoto(id: String)    /// `/projects`    case projects    /// `/projects/[slug]`    case projectsSlug(slug: String)    /// `/projects/[slug]/[section]`    case projectsSlugSection(slug: String, section: String)    /// `/projects/[slug]/brand`    case projectsBrand(slug: String)    /// `/projects/[slug]/code`    case projectsCode(slug: String)    /// `/projects/[slug]/feedback`    case projectsFeedback(slug: String)    /// `/projects/[slug]/feedback/[id]` — one report of the project's feedback.    case projectsFeedbackReport(slug: String, id: String)    /// `/projects/[slug]/memory`    case projectsMemory(slug: String)    /// `/projects/[slug]/todos`    case projectsTodos(slug: String)    /// `/reader`    case reader    /// `/reader/page/[id]`    case readerPage(id: String)    /// `/rejected` — the writes this device parked rather than folded.    ///    /// A PAGE, not a settings panel, and not under `/settings`: nothing inside    /// the settings sheet is a pushed settings page (`SettingsSheetTests`), and    /// this is a list with rows and a verb — the Bin's shape. Reached from the    /// count on the join sheet's merge report and from Settings › Devices. The    /// rows are this DEVICE's own `_parked` table, which never syncs, so    /// two devices can honestly hold different lists.    case rejected    /// `/members` — the Members tool (Spec 9.3): the people in the database    /// the window shows besides the reader, those asking to join first, and    /// "Admit a person" where the database takes people. Opened from its Home    /// card and from the board head's "with …" line. Not `/people`, which is    /// the People tool.    case members    /// `/members/admit` — the existing creation flow.    case membersAdmit    /// `/members/[id]` — one person in it, or one asking to join: who they    /// are, what they may do, and Admit, Turn away or Remove.    case membersId(id: String)    /// `/search` — the everything-search, drawn as objects (redesign phase 16).    case search    /// `/sessions/[id]` — one session's page, the destination of every card    /// on `/code`. There is no `/sessions` list any more: one list, and it is    /// the Code screen.    case sessionsId(id: String)    /// `/sessions/[id]/terminal` — that session's live terminal, pushed by its    /// page's "Open the terminal".    case sessionsTerminal(id: String)    /// `/device` — THIS device's page (Spec 10.4): how it syncs and backs up, its    /// notifications, its city, the words it hears, what it keeps. Home's stack button    /// "This phone" and every device notification open it. The phone has no    /// Settings screen (Spec 10.9).    case device    /// `/backup` — Settings › Backup: backing this phone's database up to    /// the person's own Cotton (`BackupRoute`), and once it is, this    /// phone's device card.    case backup    /// `/server` — Settings › Cotton server: what the person's own server    /// adds, and its address once backed up (`ServerRoute`).    case server    /// `/bring-in` — Settings › Bring in: files chosen from Files, taken by    /// the share drain's own branches (`ShareIntake.intake`).    case bringIn    /// `/export` — Settings › Export: tables chosen, one Cotton package    /// written by the core (`Packages.export`) and handed to the share sheet.    case export    /// `/device/[page]` — one of THIS device's pages that only its host can    /// draw (a Mac's API keys, its sources, what it is serving), opened from    /// this device's own record page. The page id is opaque here: the host's    /// `HostSettingsSlot` names its pages and draws them, and a device whose    /// host names none (the phone) has nothing at any id.    case hostPage(id: String)    /// `/me` — the owner's own person, opened from the Me card on the    /// personal database's Home (owner, 11 Oct 2026): the People row whose id    /// `cotton_workspaces.owner_person_id` holds, never one found by name.    case me    /// `/database` — the database page (Spec 10.2): the shown database's cap,    /// name and colour, members, what it keeps here, and leaving it. Home's stack button    /// "This database" opens it.    case database    /// `/about` — the app's version and build, privacy, terms and reporting a    /// problem (Spec 10.8), from the foot of the Tools screen.    case about    /// `/settings/join-request/[id]` — one device asking to join, by its    /// pairing id. Reached from the `device_join_requested` push and from the    /// waiting list on Settings.    case settingsJoinRequest(id: String)    /// `/take`    case take    /// `/thoughts` — every capture, newest first. Back on 2026-09-28, when To    /// decide stopped holding thoughts.    case thoughts    /// `/thoughts/thought/[id]`    case thoughtsThought(id: String)    /// `/todos` — `new: true` is `?new=1`, the + fan asking the timeline for    /// its create sheet.    case todos(new: Bool)    /// `/todos/done` — `project` is a project's id OR its slug: the Done link    /// on a project's own timeline carries an id and    /// `/projects/[slug]/todos` carries a slug, and    /// the crate resolves either, id first. A Done list opened from inside a    /// project's folder is LOCKED to that project, and a value that resolves to    /// NEITHER narrows to nothing rather than to the whole workspace    /// (the empty scope `crates/cotton-ffi/src/phone/reads/day.rs` documents,    /// which is safe-by-default and the half that must never be lost quietly).    case todosDone(project: String?)    /// `/todos/dropped` — the same, for the dropped list.    case todosDropped(project: String?)    /// `/todos/todo/[id]`    case todosTodo(id: String)    /// `/videos` — the Videos tool: the video table's own list.    case videos    /// `/videos/video/[id]`    case videosVideo(id: String)    /// `/voice-words` — the words dictation listens for (the Voice words    /// tool, Spec 9.3): the person's, the same in every database.    case voiceWords    /// `/voice-words/[id]` — one word, with how often dictation heard it.    case voiceWordsId(id: String)    /// `?raise=<column>` on any page route — that page with one of its cards    /// raised: the card's question asked when it is empty, the card shown and    /// lifted when it holds a value. One parameter every page reads, never a    /// page's own flag, so a definition row can send a person straight to the    /// card that holds a fact (Settings › Your city → `/me?raise=city`).    case raised(Route, part: String)}extension Route {    /// The path this route is reached by. The formatter half of the pair.    public var path: String {        switch self {        case .raised(let page, let part):            let base = page.path            return base + (base.contains("?") ? "&" : "?") + "raise=" + Route.esc(part)        case .root: return "/"        case .money: return "/money"        case .moneyAccount(let id): return "/money/accounts/\(Route.esc(id))"        case .moneyStatement(let id): return "/money/statements/\(Route.esc(id))"        case .moneyTransaction(let id): return "/money/transactions/\(Route.esc(id))"        case .database: return "/database"        case .me: return "/me"        case .device: return "/device"        case .backup: return "/backup"        case .server: return "/server"        case .bringIn: return "/bring-in"        case .export: return "/export"        case .hostPage(let id): return "/device/\(Route.esc(id))"        case .activity: return "/activity"        case .alarms: return "/alarms"        case .bin: return "/bin"        case .briefing(let project):            var query: [(String, String)] = []            if let project, !project.isEmpty { query.append(("project", project)) }            return Route.join("/briefing", query)        case .calendar(let date, let show):            var query: [(String, String)] = []            if let date, !date.isEmpty { query.append(("date", date)) }            // `invites`: the events still asking for a reply (Home's row).            if let show, !show.isEmpty { query.append(("show", show)) }            return Route.join("/calendar", query)        case .calendarEvent(let id, let date, let at):            var query: [(String, String)] = []            if let date, !date.isEmpty { query.append(("date", date)) }            if let at, !at.isEmpty { query.append(("at", at)) }            return Route.join("/calendar/event/\(Route.esc(id))", query)        case .calendarEventEdit(let id, let date, let at):            var query: [(String, String)] = []            if let id, !id.isEmpty { query.append(("id", id)) }            if let date, !date.isEmpty { query.append(("date", date)) }            if let at, !at.isEmpty { query.append(("at", at)) }            return Route.join("/calendar/event/edit", query)        case .calendarMonth(let date):            var query: [(String, String)] = []            if let date, !date.isEmpty { query.append(("date", date)) }            return Route.join("/calendar/month", query)        case .callsCall(let id): return "/calls/call/\(Route.esc(id))"        case .callsHistory(let person):            var query: [(String, String)] = []            if let person, !person.isEmpty { query.append(("person", person)) }            return Route.join("/calls/history", query)        case .camera: return "/camera"        case .capture: return "/capture"        case .code: return "/code"        case .codeNew(let project):            var query: [(String, String)] = []            if let project, !project.isEmpty { query.append(("project", project)) }            return Route.join("/code/new", query)        case .codeDefaults: return "/code/defaults"        case .devices: return "/devices"        case .devicesId(let id): return "/devices/\(Route.esc(id))"        case .deviceStorage(let id): return "/devices/\(Route.esc(id))/storage"        case .documents(let status):            var query: [(String, String)] = []            if let status, !status.isEmpty { query.append(("status", status)) }            return Route.join("/documents", query)        case .documentsDocument(let id): return "/documents/document/\(Route.esc(id))"        case .documentsDocumentViewer(let id): return "/documents/document/\(Route.esc(id))/viewer"        case .documentsImport: return "/documents/import"        case .email: return "/email"        case .emailId(let id, let at):            var query: [(String, String)] = []            if let at, !at.isEmpty { query.append(("at", at)) }            return Route.join("/email/\(Route.esc(id))", query)        case .goals: return "/goals"        case .goalsGoal(let id): return "/goals/goal/\(Route.esc(id))"        case .home: return "/home"        case .storage: return "/storage"        case .storageId(let id): return "/storage/\(Route.esc(id))"        case .journal: return "/journal"        case .journalDate(let date): return "/journal/\(Route.esc(date))"        case .keyboardTake: return "/keyboard-take"        case .tableList(let table, let filter, let title, let query, let archived, let section, let view):            var pairs: [(String, String)] = []            if let filter, !filter.isEmpty { pairs.append(("where", filter)) }            if let title, !title.isEmpty { pairs.append(("title", title)) }            if let query, !query.isEmpty { pairs.append(("q", query)) }            // The list of what is archived (S7).            if archived { pairs.append(("archived", "1")) }            // One section of a planned list: its past (`?section=earlier`).            if let section, !section.isEmpty { pairs.append(("section", section)) }            // A tool's view the list reads (`<tool>/<id>`): a group card's            // person under With person (`GroupOpening`).            if let view, !view.isEmpty { pairs.append(("view", view)) }            return Route.join("/lists/\(Route.esc(table))", pairs)        case .tableRecord(let table, let id): return "/lists/\(Route.esc(table))/\(Route.esc(id))"        case .about: return "/about"        case .aboutWhatsNew: return "/about/whats-new"        case .aboutHelp: return "/about/help"        case .legalPrivacy: return "/legal/privacy"        case .legalTerms: return "/legal/terms"        case .locations: return "/locations"        case .locationsLocation(let id): return "/locations/location/\(Route.esc(id))"        case .meetings(let importing):            var query: [(String, String)] = []            if importing { query.append(("import", "1")) }            return Route.join("/meetings", query)        case .meetingsMeeting(let id): return "/meetings/meeting/\(Route.esc(id))"        case .meetingsRecord: return "/meetings/record"        case .memory(let id): return "/memory/\(Route.esc(id))"        case .memoryDropped: return "/memory/dropped"        case .messages: return "/messages"        case .messagesThread(let thread): return "/messages/\(Route.esc(thread))"        case .messagesInfo(let thread): return "/messages/\(Route.esc(thread))/info"        case .messagesMedia(let thread): return "/messages/\(Route.esc(thread))/media"        case .messagesImport: return "/messages/import"        case .messagesNew: return "/messages/new"        case .messagesStarred: return "/messages/starred"        case .mood: return "/mood"        case .news: return "/news"        case .newsEdition(let id): return "/news/edition/\(Route.esc(id))"        case .newsSettings: return "/news/settings"        case .newsTopic(let id): return "/news/topic/\(Route.esc(id))"        case .newsTopicNew: return "/news/topic/new"        case .notes: return "/notes"        case .notesJournalToday: return "/notes/journal-today"        case .notesNote(let id): return "/notes/note/\(Route.esc(id))"        case .passwords: return "/passwords"        case .passwordsSecret(let id): return "/passwords/\(Route.esc(id))"        case .people: return "/people"        case .peopleImport: return "/people/import"        case .peoplePerson(let id, let database):            return Route.join("/people/person/\(Route.esc(id))", database.map { [("database", $0)] } ?? [])        case .peoplePersonSection(let id, let section): return "/people/person/\(Route.esc(id))/\(Route.esc(section))"        case .photos(let show):            var query: [(String, String)] = []            if let show, !show.isEmpty { query.append(("show", show)) }            return Route.join("/photos", query)        case .photosAlbum(let id): return "/photos/album/\(Route.esc(id))"        case .photosAlbumAdd(let id): return "/photos/album/\(Route.esc(id))/add"        case .photosAlbums: return "/photos/albums"        case .photosDuplicates: return "/photos/duplicates"        case .photosPeople: return "/photos/people"        case .photosPhoto(let id): return "/photos/photo/\(Route.esc(id))"        case .projects: return "/projects"        case .projectsSlug(let slug): return "/projects/\(Route.esc(slug))"        case .projectsSlugSection(let slug, let section): return "/projects/\(Route.esc(slug))/\(Route.esc(section))"        case .projectsBrand(let slug): return "/projects/\(Route.esc(slug))/brand"        case .projectsCode(let slug): return "/projects/\(Route.esc(slug))/code"        case .projectsFeedback(let slug): return "/projects/\(Route.esc(slug))/feedback"        case .projectsFeedbackReport(let slug, let id): return "/projects/\(Route.esc(slug))/feedback/\(Route.esc(id))"        case .projectsMemory(let slug): return "/projects/\(Route.esc(slug))/memory"        case .projectsTodos(let slug): return "/projects/\(Route.esc(slug))/todos"        case .reader: return "/reader"        case .readerPage(let id): return "/reader/page/\(Route.esc(id))"        case .rejected: return "/rejected"        case .membersAdmit: return "/members/admit"        case .members: return "/members"        case .membersId(let id): return "/members/\(Route.esc(id))"        case .search: return "/search"        case .sessionsId(let id): return "/sessions/\(Route.esc(id))"        case .sessionsTerminal(let id): return "/sessions/\(Route.esc(id))/terminal"        case .settingsJoinRequest(let id): return "/settings/join-request/\(Route.esc(id))"        case .take: return "/take"        case .thoughts: return "/thoughts"        case .thoughtsThought(let id): return "/thoughts/thought/\(Route.esc(id))"        case .todos(let new):            var query: [(String, String)] = []            if new { query.append(("new", "1")) }            return Route.join("/todos", query)        case .todosDone(let project):            var query: [(String, String)] = []            if let project { query.append(("project", project)) }            return Route.join("/todos/done", query)        case .todosDropped(let project):            var query: [(String, String)] = []            if let project { query.append(("project", project)) }            return Route.join("/todos/dropped", query)        case .todosTodo(let id): return "/todos/todo/\(Route.esc(id))"        case .tools: return "/tools"        case .toolBoard(let id): return "/tools/board/\(Route.esc(id))"        case .videos: return "/videos"        case .videosVideo(let id): return "/videos/video/\(Route.esc(id))"        case .voiceWords: return "/voice-words"        case .voiceWordsId(let id): return "/voice-words/\(Route.esc(id))"        }    }    /// Read a path back. `nil` for anything this app has no screen for — a    /// stale link, a notification from a server one deploy ahead, a link    /// somebody typed. Never a guess: an unknown path is a no-op, which is what    /// `NOTIFICATION_ROUTES`' deliberate no-op has always been.    public static func parse(_ text: String) -> Route? {        var (rawPath, query) = splitQuery(text)        // `raise` rides on any page and is read by none of them, so it is        // lifted off before the page's own query is matched.        if let part = query.removeValue(forKey: "raise") {            let rest = join(rawPath, query.sorted { $0.key < $1.key }.map { ($0.key, $0.value) })            guard !part.isEmpty, let page = parse(rest), page.tier == .page else { return nil }            return .raised(page, part: part)        }        guard rawPath.hasPrefix("/") else { return nil }        let path = rawPath == "/calls" ? "/calls/history" : rawPath        let segments = path.split(separator: "/").map { unesc(String($0)) }        for candidate in compiled where candidate.parts.count == segments.count {            var bound: [String: String] = [:]            var matched = true            for (index, part) in candidate.parts.enumerated() {                if part.hasPrefix("[") {                    let segment = segments[index]                    if segment.isEmpty { matched = false; break }                    bound[String(part.dropFirst().dropLast())] = segment                } else if part != segments[index] {                    matched = false                    break                }            }            guard matched else { continue }            return build(candidate.template, bound, query)        }        return nil    }    /// A record's own screen from its definition's `route`: a pattern of    /// `allPatterns` with exactly one parameter, filled with the record's id.    /// `nil` for a pattern this app has no screen for.    public static func record(_ pattern: String, id: String) -> Route? {        guard allPatterns.contains(pattern) else { return nil }        let parameters = pattern.split(separator: "/").filter { $0.hasPrefix("[") }        guard parameters.count == 1, let parameter = parameters.first else { return nil }        return parse(pattern.replacingOccurrences(of: String(parameter), with: esc(id)))    }    /// Every route pattern, as the template string Rust's `ROUTES` holds.    /// `RouteTableTests` set-compares this with that table.    public static let allPatterns: [String] = [        "/",        "/about",        "/about/help",        "/about/whats-new",        "/activity",        "/alarms",        "/backup",        "/bin",        "/briefing",        "/bring-in",        "/calendar",        "/calendar/event/[id]",        "/calendar/event/edit",        "/calendar/month",        "/calls/call/[id]",        "/calls/history",        "/camera",        "/capture",        "/code",        "/code/defaults",        "/code/new",        "/database",        "/device",        "/device/[page]",        "/devices",        "/devices/[id]",        "/devices/[id]/storage",        "/documents",        "/documents/document/[id]",        "/documents/document/[id]/viewer",        "/documents/import",        "/email",        "/email/[id]",        "/export",        "/goals",        "/goals/goal/[id]",        "/home",        "/journal",        "/journal/[date]",        "/keyboard-take",        "/legal/privacy",        "/legal/terms",        "/lists/[table]",        "/lists/[table]/[id]",        "/locations",        "/locations/location/[id]",        "/me",        "/meetings",        "/meetings/meeting/[id]",        "/meetings/record",        "/members",        "/members/[id]",        "/members/admit",        "/memory/[id]",        "/memory/dropped",        "/messages",        "/messages/[thread]",        "/messages/[thread]/info",        "/messages/[thread]/media",        "/messages/import",        "/messages/new",        "/messages/starred",        "/money",        "/money/accounts/[id]",        "/money/statements/[id]",        "/money/transactions/[id]",        "/mood",        "/news",        "/news/edition/[id]",        "/news/settings",        "/news/topic/[id]",        "/news/topic/new",        "/notes",        "/notes/journal-today",        "/notes/note/[id]",        "/passwords",        "/passwords/[id]",        "/people",        "/people/import",        "/people/person/[id]",        "/people/person/[id]/[section]",        "/photos",        "/photos/album/[id]",        "/photos/album/[id]/add",        "/photos/albums",        "/photos/duplicates",        "/photos/people",        "/photos/photo/[id]",        "/projects",        "/projects/[slug]",        "/projects/[slug]/[section]",        "/projects/[slug]/brand",        "/projects/[slug]/code",        "/projects/[slug]/feedback",        "/projects/[slug]/feedback/[id]",        "/projects/[slug]/memory",        "/projects/[slug]/todos",        "/reader",        "/reader/page/[id]",        "/rejected",        "/search",        "/server",        "/sessions/[id]",        "/sessions/[id]/terminal",        "/settings/join-request/[id]",        "/storage",        "/storage/[id]",        "/take",        "/thoughts",        "/thoughts/thought/[id]",        "/todos",        "/todos/done",        "/todos/dropped",        "/todos/todo/[id]",        "/tools",        "/tools/board/[id]",        "/videos",        "/videos/video/[id]",        "/voice-words",        "/voice-words/[id]",    ]    // ── The pair's private half ───────────────────────────────────────────    /// The patterns, split and ORDERED so a literal beats a parameter at the    /// same length. Ascending parameter count, then alphabetical — so the order    /// is a property of the data and not of how the array happens to be typed.    private static let compiled: [(template: String, parts: [String])] = allPatterns        .map { (template: $0, parts: $0.split(separator: "/").map(String.init)) }        .sorted { first, second in            let a = first.parts.filter { $0.hasPrefix("[") }.count            let b = second.parts.filter { $0.hasPrefix("[") }.count            return a == b ? first.template < second.template : a < b        }    private static func build(        _ template: String,        _ parts: [String: String],        _ query: [String: String]    ) -> Route? {        switch template {        case "/": return .root        case "/money": return .money        case "/money/accounts/[id]": return .moneyAccount(id: parts["id"] ?? "")        case "/money/statements/[id]": return .moneyStatement(id: parts["id"] ?? "")        case "/money/transactions/[id]": return .moneyTransaction(id: parts["id"] ?? "")        case "/database": return .database        case "/me": return .me        case "/device": return .device        case "/backup": return .backup        case "/server": return .server        case "/bring-in": return .bringIn        case "/export": return .export        case "/device/[page]": return .hostPage(id: parts["page"] ?? "")        case "/activity": return .activity        case "/alarms": return .alarms        case "/bin": return .bin        case "/briefing": return .briefing(project: query["project"])        case "/calendar": return .calendar(date: query["date"], show: query["show"])        case "/calendar/event/[id]": return .calendarEvent(id: parts["id"] ?? "", date: query["date"], at: query["at"])        case "/calendar/event/edit": return .calendarEventEdit(id: query["id"], date: query["date"], at: query["at"])        case "/calendar/month": return .calendarMonth(date: query["date"])        case "/calls/call/[id]": return .callsCall(id: parts["id"] ?? "")        case "/calls/history": return .callsHistory(person: query["person"])        case "/camera": return .camera        case "/capture": return .capture        case "/code": return .code        case "/code/new": return .codeNew(project: query["project"])        case "/code/defaults": return .codeDefaults        case "/devices": return .devices        case "/devices/[id]": return .devicesId(id: parts["id"] ?? "")        case "/devices/[id]/storage": return .deviceStorage(id: parts["id"] ?? "")        case "/documents": return .documents(status: query["status"])        case "/documents/document/[id]": return .documentsDocument(id: parts["id"] ?? "")        case "/documents/document/[id]/viewer": return .documentsDocumentViewer(id: parts["id"] ?? "")        case "/documents/import": return .documentsImport        case "/email": return .email        case "/email/[id]": return .emailId(id: parts["id"] ?? "", at: query["at"])        case "/goals": return .goals        case "/goals/goal/[id]": return .goalsGoal(id: parts["id"] ?? "")        case "/home": return .home        case "/storage": return .storage        case "/storage/[id]": return .storageId(id: parts["id"] ?? "")        case "/journal": return .journal        case "/journal/[date]": return .journalDate(date: parts["date"] ?? "")        case "/keyboard-take": return .keyboardTake        case "/lists/[table]":            return .tableList(                table: parts["table"] ?? "", filter: query["where"], title: query["title"], query: query["q"],                archived: query["archived"] == "1", section: query["section"], view: query["view"])        case "/lists/[table]/[id]": return .tableRecord(table: parts["table"] ?? "", id: parts["id"] ?? "")        case "/about": return .about        case "/about/help": return .aboutHelp        case "/about/whats-new": return .aboutWhatsNew        case "/legal/privacy": return .legalPrivacy        case "/legal/terms": return .legalTerms        case "/locations": return .locations        case "/locations/location/[id]": return .locationsLocation(id: parts["id"] ?? "")        case "/meetings": return .meetings(importing: query["import"] == "1")        case "/meetings/meeting/[id]": return .meetingsMeeting(id: parts["id"] ?? "")        case "/meetings/record": return .meetingsRecord        case "/memory/[id]": return .memory(id: parts["id"] ?? "")        case "/memory/dropped": return .memoryDropped        case "/messages": return .messages        case "/messages/[thread]": return .messagesThread(thread: parts["thread"] ?? "")        case "/messages/[thread]/info": return .messagesInfo(thread: parts["thread"] ?? "")        case "/messages/[thread]/media": return .messagesMedia(thread: parts["thread"] ?? "")        case "/messages/import": return .messagesImport        case "/messages/new": return .messagesNew        case "/messages/starred": return .messagesStarred        case "/mood": return .mood        case "/news": return .news        case "/news/edition/[id]": return .newsEdition(id: parts["id"] ?? "")        case "/news/settings": return .newsSettings        case "/news/topic/[id]": return .newsTopic(id: parts["id"] ?? "")        case "/news/topic/new": return .newsTopicNew        case "/notes": return .notes        case "/notes/journal-today": return .notesJournalToday        case "/notes/note/[id]": return .notesNote(id: parts["id"] ?? "")        case "/passwords": return .passwords        case "/passwords/[id]": return .passwordsSecret(id: parts["id"] ?? "")        case "/people": return .people        case "/people/import": return .peopleImport        case "/people/person/[id]": return .peoplePerson(id: parts["id"] ?? "", database: query["database"])        case "/people/person/[id]/[section]": return .peoplePersonSection(id: parts["id"] ?? "", section: parts["section"] ?? "")        case "/photos": return .photos(show: query["show"])        case "/photos/album/[id]": return .photosAlbum(id: parts["id"] ?? "")        case "/photos/album/[id]/add": return .photosAlbumAdd(id: parts["id"] ?? "")        case "/photos/albums": return .photosAlbums        case "/photos/duplicates": return .photosDuplicates        case "/photos/people": return .photosPeople        case "/photos/photo/[id]": return .photosPhoto(id: parts["id"] ?? "")        case "/projects": return .projects        case "/projects/[slug]": return .projectsSlug(slug: parts["slug"] ?? "")        case "/projects/[slug]/[section]": return .projectsSlugSection(slug: parts["slug"] ?? "", section: parts["section"] ?? "")        case "/projects/[slug]/brand": return .projectsBrand(slug: parts["slug"] ?? "")        case "/projects/[slug]/code": return .projectsCode(slug: parts["slug"] ?? "")        case "/projects/[slug]/feedback": return .projectsFeedback(slug: parts["slug"] ?? "")        case "/projects/[slug]/feedback/[id]": return .projectsFeedbackReport(slug: parts["slug"] ?? "", id: parts["id"] ?? "")        case "/projects/[slug]/memory": return .projectsMemory(slug: parts["slug"] ?? "")        case "/projects/[slug]/todos": return .projectsTodos(slug: parts["slug"] ?? "")        case "/reader": return .reader        case "/reader/page/[id]": return .readerPage(id: parts["id"] ?? "")        case "/rejected": return .rejected        case "/members/admit": return .membersAdmit        case "/members": return .members        case "/members/[id]": return .membersId(id: parts["id"] ?? "")        case "/search": return .search        case "/sessions/[id]": return .sessionsId(id: parts["id"] ?? "")        case "/sessions/[id]/terminal": return .sessionsTerminal(id: parts["id"] ?? "")        case "/settings/join-request/[id]": return .settingsJoinRequest(id: parts["id"] ?? "")        case "/take": return .take        case "/thoughts": return .thoughts        case "/thoughts/thought/[id]": return .thoughtsThought(id: parts["id"] ?? "")        // Only an explicit "1" is an ask.        case "/todos": return .todos(new: query["new"] == "1")        case "/todos/done": return .todosDone(project: query["project"])        case "/todos/dropped": return .todosDropped(project: query["project"])        case "/todos/todo/[id]": return .todosTodo(id: parts["id"] ?? "")        case "/tools": return .tools        case "/tools/board/[id]": return .toolBoard(id: parts["id"] ?? "")        case "/videos": return .videos        case "/videos/video/[id]": return .videosVideo(id: parts["id"] ?? "")        case "/voice-words": return .voiceWords        case "/voice-words/[id]": return .voiceWordsId(id: parts["id"] ?? "")        default: return nil        }    }    /// A path plus its query, in the order the case declares — so a route    /// formats the same way twice and `parse(r.path) == r` holds.    public static func join(_ path: String, _ query: [(String, String)]) -> String {        guard !query.isEmpty else { return path }        return path + "?" + query.map { "\(esc($0.0))=\(esc($0.1))" }.joined(separator: "&")    }    public static func esc(_ text: String) -> String {        text.addingPercentEncoding(withAllowedCharacters: unreserved) ?? text    }    static func unesc(_ text: String) -> String {        text.removingPercentEncoding ?? text    }    private static let unreserved: CharacterSet = {        var set = CharacterSet.alphanumerics        set.insert(charactersIn: "-._~")        return set    }()    public static func splitQuery(_ text: String) -> (String, [String: String]) {        guard let mark = text.firstIndex(of: "?") else { return (text, [:]) }        var query: [String: String] = [:]        for pair in text[text.index(after: mark)...].split(separator: "&") {            let halves = pair.split(separator: "=", maxSplits: 1)            guard halves.count == 2 else { continue }            query[unesc(String(halves[0]))] = unesc(String(halves[1]))        }        return (String(text[..<mark]), query)    }}