-
Notifications
You must be signed in to change notification settings - Fork 17
feat(xref): move term autocomplete from client to server #511
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
marcoscaceres
wants to merge
5
commits into
main
Choose a base branch
from
feat/server-autocomplete
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
c814d48
fix(baseline): add .ts extension to update.worker import
marcoscaceres 74ee241
feat(xref): move term autocomplete from client to server
marcoscaceres 43a5052
fix(xref): handle fetch errors in autocomplete, test ordering
marcoscaceres 06120d7
fix(xref): handle array query params, remove stale terms reference
marcoscaceres dd311c4
test(xref): add tests for array query param normalization
marcoscaceres File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,79 @@ | ||
| import { Request, Response } from "express"; | ||
|
|
||
| import { seconds } from "../../utils/misc.js"; | ||
| import { store } from "./lib/store-init.js"; | ||
|
|
||
| interface TermEntry { | ||
| lower: string; | ||
| original: string; | ||
| } | ||
|
|
||
| let termsIndex: TermEntry[] = []; | ||
| let termsVersion = -1; | ||
|
|
||
| function getTermsIndex(): TermEntry[] { | ||
| if (termsVersion < store.version) { | ||
| const keys = Object.keys(store.byTerm).filter(k => k !== ""); | ||
| termsIndex = keys | ||
| .map(k => ({ lower: k.toLowerCase(), original: k })) | ||
| .sort((a, b) => (a.lower < b.lower ? -1 : a.lower > b.lower ? 1 : 0)); | ||
| termsVersion = store.version; | ||
| } | ||
| return termsIndex; | ||
| } | ||
|
|
||
| function bisectLeft(arr: TermEntry[], target: string): number { | ||
| let lo = 0; | ||
| let hi = arr.length; | ||
| while (lo < hi) { | ||
| const mid = (lo + hi) >>> 1; | ||
| if (arr[mid].lower < target) lo = mid + 1; | ||
| else hi = mid; | ||
| } | ||
| return lo; | ||
| } | ||
|
|
||
| function searchTerms(query: string, limit: number): string[] { | ||
| const index = getTermsIndex(); | ||
| const q = query.toLowerCase(); | ||
| const results: string[] = []; | ||
| const seen = new Set<string>(); | ||
|
|
||
| const start = bisectLeft(index, q); | ||
| for (let i = start; i < index.length && results.length < limit; i++) { | ||
| if (!index[i].lower.startsWith(q)) break; | ||
| seen.add(index[i].lower); | ||
| results.push(index[i].original); | ||
| } | ||
|
|
||
| if (results.length < limit) { | ||
| for (let i = 0; i < index.length && results.length < limit; i++) { | ||
| if (seen.has(index[i].lower)) continue; | ||
| if (index[i].lower.includes(q)) { | ||
| results.push(index[i].original); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| return results; | ||
| } | ||
|
|
||
| interface QueryParams { | ||
| q?: string | string[]; | ||
| limit?: string; | ||
| } | ||
| type IRequest = Request<never, any, never, QueryParams>; | ||
|
|
||
| export default function route(req: IRequest, res: Response) { | ||
| const q = Array.isArray(req.query.q) ? req.query.q[0] : req.query.q; | ||
| if (!q || q.length < 2) { | ||
| res.status(400).json({ error: "query must be at least 2 characters" }); | ||
| return; | ||
| } | ||
|
|
||
| const limit = Math.min(Math.max(parseInt(req.query.limit || "15", 10) || 15, 1), 50); | ||
| const results = searchTerms(q, limit); | ||
|
|
||
| res.set("Cache-Control", `max-age=${seconds("24h")}`); | ||
| res.json(results); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,169 @@ | ||
| import { mkdtemp, writeFile, mkdir, rm } from "fs/promises"; | ||
| import path from "path"; | ||
| import { tmpdir } from "os"; | ||
|
|
||
| let tmpDir; | ||
| let route; | ||
| let origDataDir; | ||
|
|
||
| const FIXTURE_XREF = { | ||
| EventTarget: [{ type: "interface", spec: "dom", uri: "#eventtarget" }], | ||
| "event target": [{ type: "dfn", spec: "dom", uri: "#concept-event-target" }], | ||
| event: [{ type: "dfn", spec: "dom", uri: "#concept-event" }], | ||
| "event handler": [{ type: "dfn", spec: "html", uri: "#event-handler" }], | ||
| "event loop": [{ type: "dfn", spec: "html", uri: "#event-loop" }], | ||
| element: [{ type: "dfn", spec: "dom", uri: "#concept-element" }], | ||
| "foreignObject": [{ type: "element", spec: "svg", uri: "#foreignObject" }], | ||
| fetch: [{ type: "dfn", spec: "fetch", uri: "#concept-fetch" }], | ||
| "fire an event": [{ type: "dfn", spec: "dom", uri: "#concept-event-fire" }], | ||
| "live event": [{ type: "dfn", spec: "html", uri: "#concept-live-event" }], | ||
| URL: [{ type: "interface", spec: "url", uri: "#url" }], | ||
| "url": [{ type: "dfn", spec: "url", uri: "#concept-url" }], | ||
| AbortController: [{ type: "interface", spec: "dom", uri: "#abortcontroller" }], | ||
| AbortSignal: [{ type: "interface", spec: "dom", uri: "#abortsignal" }], | ||
| "abort signal": [{ type: "dfn", spec: "dom", uri: "#concept-abort-signal" }], | ||
| Node: [{ type: "interface", spec: "dom", uri: "#node" }], | ||
| navigator: [{ type: "attribute", spec: "html", uri: "#navigator" }], | ||
| }; | ||
|
|
||
| beforeAll(async () => { | ||
| tmpDir = await mkdtemp(path.join(tmpdir(), "xref-terms-test-")); | ||
| const xrefDir = path.join(tmpDir, "xref"); | ||
| await mkdir(xrefDir, { recursive: true }); | ||
| await writeFile(path.join(xrefDir, "xref.json"), JSON.stringify(FIXTURE_XREF)); | ||
| await writeFile(path.join(xrefDir, "specs.json"), "{}"); | ||
| await writeFile(path.join(xrefDir, "specmap.json"), '{"current":{},"snapshot":{}}'); | ||
| await writeFile(path.join(xrefDir, "headings.json"), "{}"); | ||
|
|
||
| origDataDir = process.env.DATA_DIR; | ||
| process.env.DATA_DIR = tmpDir; | ||
|
|
||
| const mod = await import("../../../build/routes/xref/terms.get.js"); | ||
| route = mod.default; | ||
| }); | ||
|
|
||
| afterAll(async () => { | ||
| if (origDataDir !== undefined) { | ||
| process.env.DATA_DIR = origDataDir; | ||
| } | ||
| if (tmpDir) { | ||
| await rm(tmpDir, { recursive: true, force: true }); | ||
| } | ||
| }); | ||
|
|
||
| function mockReq(query = {}) { | ||
| return { query }; | ||
| } | ||
|
|
||
| function mockRes() { | ||
| const res = { | ||
| _status: 200, | ||
| _body: undefined, | ||
| _headers: {}, | ||
| status(code) { res._status = code; return res; }, | ||
| json(body) { res._body = body; return res; }, | ||
| set(header, value) { res._headers[header] = value; return res; }, | ||
| send(body) { res._body = body; return res; }, | ||
| }; | ||
| return res; | ||
| } | ||
|
|
||
| describe("xref/terms - server autocomplete", () => { | ||
| it("returns 400 when q is missing", () => { | ||
| const res = mockRes(); | ||
| route(mockReq(), res); | ||
| expect(res._status).toBe(400); | ||
| }); | ||
|
|
||
| it("returns 400 when q is too short", () => { | ||
| const res = mockRes(); | ||
| route(mockReq({ q: "a" }), res); | ||
| expect(res._status).toBe(400); | ||
| }); | ||
|
|
||
| it("returns prefix matches before infix-only matches", () => { | ||
| const res = mockRes(); | ||
| route(mockReq({ q: "ev" }), res); | ||
| const results = res._body; | ||
| const firstInfix = results.findIndex(t => !t.toLowerCase().startsWith("ev")); | ||
| const lastPrefix = results.findLastIndex(t => t.toLowerCase().startsWith("ev")); | ||
| if (firstInfix !== -1) { | ||
| expect(lastPrefix).toBeLessThan(firstInfix); | ||
| } | ||
| }); | ||
|
|
||
| it("returns prefix matches first", () => { | ||
| const res = mockRes(); | ||
| route(mockReq({ q: "ev" }), res); | ||
| expect(res._status).toBe(200); | ||
| expect(Array.isArray(res._body)).toBeTrue(); | ||
| expect(res._body.length).toBeGreaterThan(0); | ||
| for (const term of res._body) { | ||
| expect(term.toLowerCase()).toMatch(/ev/); | ||
| } | ||
| }); | ||
|
|
||
| it("matches case-insensitively but preserves original case", () => { | ||
| const res = mockRes(); | ||
| route(mockReq({ q: "eventtarget" }), res); | ||
| expect(res._body).toContain("EventTarget"); | ||
| }); | ||
|
|
||
| it("returns infix matches when prefix results are insufficient", () => { | ||
| const res = mockRes(); | ||
| route(mockReq({ q: "signal" }), res); | ||
| expect(res._body).toContain("AbortSignal"); | ||
| expect(res._body).toContain("abort signal"); | ||
| }); | ||
|
|
||
| it("respects the limit parameter", () => { | ||
| const res = mockRes(); | ||
| route(mockReq({ q: "ev", limit: "3" }), res); | ||
| expect(res._body.length).toBeLessThanOrEqual(3); | ||
| }); | ||
|
|
||
| it("caps limit at 50", () => { | ||
| const res = mockRes(); | ||
| route(mockReq({ q: "ev", limit: "100" }), res); | ||
| expect(res._body.length).toBeLessThanOrEqual(50); | ||
| }); | ||
|
|
||
| it("defaults limit to 15", () => { | ||
| const res = mockRes(); | ||
| route(mockReq({ q: "ab" }), res); | ||
| expect(res._body.length).toBeLessThanOrEqual(15); | ||
| }); | ||
|
|
||
| it("sets Cache-Control header", () => { | ||
| const res = mockRes(); | ||
| route(mockReq({ q: "ev" }), res); | ||
| expect(res._headers["Cache-Control"]).toBeDefined(); | ||
| expect(res._headers["Cache-Control"]).toMatch(/max-age=/); | ||
| }); | ||
|
|
||
| it("returns empty array for no matches", () => { | ||
| const res = mockRes(); | ||
| route(mockReq({ q: "zzzzzzz" }), res); | ||
| expect(res._body).toEqual([]); | ||
| }); | ||
|
|
||
| it("handles mixed case query preserving original", () => { | ||
| const res = mockRes(); | ||
| route(mockReq({ q: "ForeignObj" }), res); | ||
| expect(res._body).toContain("foreignObject"); | ||
| }); | ||
|
|
||
| it("normalizes array query params to first element", () => { | ||
| const res = mockRes(); | ||
| route(mockReq({ q: ["event", "ignored"] }), res); | ||
| expect(res._status).toBe(200); | ||
| expect(Array.isArray(res._body)).toBeTrue(); | ||
| expect(res._body.length).toBeGreaterThan(0); | ||
| }); | ||
|
|
||
| it("returns 400 when array query param has short first element", () => { | ||
| const res = mockRes(); | ||
| route(mockReq({ q: ["a", "event"] }), res); | ||
| expect(res._status).toBe(400); | ||
| }); | ||
| }); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.