justintsus-experiment Public
// The canonical form of a query: what the page puts in ?q= and shows in the search box. Parsing the// canonical form gives the same query back, so a URL round-trips.import type { DateFilter, Day, SearchQuery, Term, UserRef } from "./ast.tsus";import type { Option } from "@tsus/runtime";const BARE = /^[^\s"]+$/;const QUALIFIER = /^[A-Za-z]+(-[A-Za-z]+)*:/;const NUMBER = /^#[1-9][0-9]{0,8}$/;export const quote = (v: string): string => `"${v.replace(/[\\"]/g, (c) => `\\${c}`)}"`;const qualifierValue = (v: string): string => (BARE.test(v) ? v : quote(v));// Free text is bare only when reading it back gives free text again.const textValue = (v: string): string => BARE.test(v) && !v.startsWith("-") && !QUALIFIER.test(v) && !NUMBER.test(v) ? v : quote(v);const sign = (negated: boolean): string => (negated ? "-" : "");const user = (u: UserRef): string => match (u) { Me(_m) => "@me", User(x) => x.id, Agent(a) => a.slug, };const dayText = (d: Option<Day>): string => match (d) { Some(x) => x.text, None => "*", };const date = (f: DateFilter): string => match (f) { On(x) => x.day.text, Compare(x) => `${x.op}${x.day.text}`, Between(x) => `${dayText(x.from)}..${dayText(x.to)}`, Age(x) => `${x.op}${x.count}${x.unit}`, };export const serializeTerm = (t: Term): string => match (t) { Is(x) => `${sign(x.negated)}is:${x.state}`, Label(x) => `${sign(x.negated)}label:${qualifierValue(x.label)}`, NoLabel(_x) => "no:label", Author(x) => `${sign(x.negated)}author:${qualifierValue(user(x.user))}`, ReviewRequested(x) => `${sign(x.negated)}review-requested:${qualifierValue(user(x.user))}`, Sort(x) => `sort:${x.sort}`, Date(x) => `${x.field}:${qualifierValue(date(x.filter))}`, Number(x) => `#${x.number}`, Text(x) => `${sign(x.negated)}${textValue(x.text)}`, };export const serializeQuery = (q: SearchQuery): string => q.terms.map(serializeTerm).join(" ");