docs/.vitepress/theme/workers/searchWorker.ts
416 lines · 10637 bytes
1import MiniSearch, {
2 type Options,
3 type SearchOptions,
4 type SearchResult
5} from 'minisearch'
6
7import type { PageLink, TabTarget } from '../../plugins/urlSearchPlugin'
8
9interface Result {
10 tabs?: string[]
11 title: string
12 titles: string[]
13 text?: string
14}
15
16type SearchMode = 'exact' | 'fuzzy' | 'url'
17
18type PlainRecord = Record<string, unknown>
19
20interface SearchConfig {
21 options?: PlainRecord
22 searchOptions?: PlainRecord
23 useDefaultBoostDocument?: boolean
24}
25
26interface PageGroupCount {
27 key: string
28 count: number
29}
30
31interface LoadIndexRequest {
32 type: 'load-index'
33 id: number
34 localeIndex: string
35 indexJson: unknown
36 indexVersion: number
37 config: SearchConfig
38}
39
40interface TextSearchRequest {
41 type: 'text-search'
42 id: number
43 query: string
44 mode: SearchMode
45 pageOrderEntries: [string, number][]
46}
47
48interface UrlSearchRequest {
49 type: 'url-search'
50 id: number
51 query: string
52 pageOrderEntries: [string, number][]
53}
54
55interface PreloadMetadataRequest {
56 type: 'preload-metadata'
57 id: number
58 pageOrderEntries: [string, number][]
59}
60
61type SearchWorkerRequest =
62 | LoadIndexRequest
63 | TextSearchRequest
64 | UrlSearchRequest
65 | PreloadMetadataRequest
66
67type WorkerSearchResult = SearchResult & Result
68
69let searchIndex: MiniSearch<Result> | null = null
70let searchIndexKey = ''
71let urlLinks: PageLink[] = []
72let urlLinkHrefsLower: string[] = []
73let urlLinksPromise: Promise<void> | null = null
74let tabTargetMap = new Map<string, string[]>()
75let tabTargetsPromise: Promise<void> | null = null
76let pageOrder = new Map<string, number>()
77let docOrder = new Map<string, number>()
78
79function defaultBoostDocument(
80 _: string,
81 term: string,
82 storedFields: Record<string, string | string[]>
83) {
84 const titles = ((storedFields?.titles as string[] | undefined) ?? [])
85 .filter((t) => Boolean(t))
86 .map((t) => t.toLowerCase())
87 const titleIndex = titles
88 .map((t, i) => (t?.includes(term) ? i : -1))
89 .find((i) => i >= 0) ?? -1
90 if (titleIndex >= 0) return 10000 - titleIndex
91 return 1
92}
93
94function stableStringify(value: unknown): string {
95 if (value === null || typeof value !== 'object') return JSON.stringify(value)
96 if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`
97 const object = value as Record<string, unknown>
98 return `{${
99 Object.keys(object).sort().map((key) =>
100 `${JSON.stringify(key)}:${stableStringify(object[key])}`
101 ).join(',')
102 }}`
103}
104
105function setPageOrder(entries: [string, number][]) {
106 pageOrder = new Map(entries)
107}
108
109function getPageKey(id: string) {
110 return id.split('#')[0].replace(/\/$/, '')
111}
112
113function getAnchorKey(pageId: string, anchor: string) {
114 return `${pageId.replace(/\/$/, '')}\x00${anchor}`
115}
116
117function getResultLocation(id: unknown) {
118 const value = String(id)
119 const hashIndex = value.indexOf('#')
120
121 return {
122 anchor: hashIndex >= 0 ? value.slice(hashIndex + 1) : '',
123 pageId: getPageKey(value)
124 }
125}
126
127function getPageOrder(key: string) {
128 return pageOrder.get(key) ?? Number.MAX_SAFE_INTEGER
129}
130
131function getDocOrder(id: string) {
132 return docOrder.get(id) ?? Number.MAX_SAFE_INTEGER
133}
134
135function compareByPageAndDoc(a: { id: unknown }, b: { id: unknown }) {
136 const aId = String(a.id)
137 const bId = String(b.id)
138 const pageDiff = getPageOrder(getPageKey(aId)) - getPageOrder(getPageKey(bId))
139 if (pageDiff !== 0) return pageDiff
140 return getDocOrder(aId) - getDocOrder(bId)
141}
142
143function stripMarkdown(value: string) {
144 return value
145 .replace(/`([^`]+)`/g, '$1')
146 .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')
147 .replace(/[*_~]/g, '')
148 .trim()
149}
150
151function getQueryTerms(query: string) {
152 return query
153 .toLowerCase()
154 .split(/\s+/)
155 .map((term) => term.trim())
156 .filter(Boolean)
157}
158
159function findMatchingLinkForResult(
160 result: WorkerSearchResult,
161 query: string
162) {
163 const pageId = getPageKey(String(result.id))
164 const anchor = String(result.id).split('#')[1] ?? ''
165 const terms = getQueryTerms(query)
166 if (!terms.length) return
167
168 return urlLinks.find((link) => {
169 if (link.pageId.replace(/\/$/, '') !== pageId || link.anchor !== anchor) {
170 return false
171 }
172
173 const linkText = stripMarkdown(link.linkText).toLowerCase()
174 return terms.every((term) => linkText.includes(term))
175 })
176}
177
178function withLinkPathTitles(
179 results: WorkerSearchResult[],
180 query: string
181) {
182 if (!urlLinks.length) return results
183
184 return results.map((result) => {
185 const link = findMatchingLinkForResult(result, query)
186 if (!link) return result
187
188 return {
189 ...result,
190 title: stripMarkdown(link.linkText),
191 titles: link.titles,
192 ...(link.tabs?.length ? { tabs: link.tabs } : {})
193 }
194 })
195}
196
197function getTabsForResult(result: WorkerSearchResult) {
198 if (result.tabs?.length) return result.tabs
199
200 const { pageId, anchor } = getResultLocation(result.id)
201 return tabTargetMap.get(getAnchorKey(pageId, anchor))
202}
203
204function withTabMetadata(results: WorkerSearchResult[]) {
205 if (!tabTargetMap.size) return results
206
207 return results.map((result) => {
208 const tabs = getTabsForResult(result)
209 return tabs?.length ? { ...result, tabs } : result
210 })
211}
212
213function rebuildDocOrder(index: MiniSearch<Result>) {
214 const map = new Map<string, number>()
215 const ids = (index as any)._documentIds
216 if (ids instanceof Map) {
217 let i = 0
218 for (const originalId of ids.values()) {
219 map.set(String(originalId), i++)
220 }
221 } else if (ids && typeof ids === 'object') {
222 const keys = Object.keys(ids)
223 .map(Number)
224 .sort((a, b) => a - b)
225 let i = 0
226 for (const key of keys) {
227 map.set(String(ids[key]), i++)
228 }
229 }
230 docOrder = map
231}
232
233async function loadSearchIndex(
234 localeIndex: string,
235 indexVersion: number,
236 indexJson: unknown,
237 config: SearchConfig
238) {
239 const key = `${localeIndex}\n${indexVersion}\n${stableStringify(config)}`
240 if (searchIndex && searchIndexKey === key) return
241
242 const searchOptions = {
243 boost: { title: 10, titles: 4, text: 1 },
244 ...(config.searchOptions ?? {}),
245 ...(config.useDefaultBoostDocument
246 ? { boostDocument: defaultBoostDocument }
247 : {})
248 } as SearchOptions
249
250 searchIndex = MiniSearch.loadJSON<Result>(
251 indexJson as any,
252 {
253 fields: ['title', 'titles', 'text'],
254 storeFields: ['title', 'titles'],
255 searchOptions,
256 ...(config.options ?? {})
257 } as Options<Result>
258 )
259 searchIndexKey = key
260 rebuildDocOrder(searchIndex)
261}
262
263async function textSearch(message: TextSearchRequest) {
264 setPageOrder(message.pageOrderEntries)
265 if (!searchIndex) throw new Error('Search index has not been loaded')
266
267 const dynamicSearchOptions = {
268 fuzzy: message.mode === 'fuzzy' ? (0.3 as number | false) : false,
269 prefix: message.mode === 'fuzzy'
270 ? (term: string) => term.length > 3
271 : false,
272 maxFuzzy: message.mode === 'fuzzy' ? 1 : 0,
273 boost: { title: 10, titles: 4, text: 1 }
274 } as SearchOptions
275
276 const ranked = searchIndex.search(
277 message.query,
278 dynamicSearchOptions
279 ) as WorkerSearchResult[]
280
281 const top = ranked.slice(0, 50)
282 const seen = new Set(top.map((r) => r.id))
283 const titleHits = ranked.filter(
284 (r) => !seen.has(r.id) && r.match && Object.keys(r.match).length > 0
285 )
286 const results = [...top, ...titleHits].sort(compareByPageAndDoc)
287 await ensureSearchMetadata()
288 const displayResults = withTabMetadata(
289 withLinkPathTitles(results, message.query)
290 )
291 const terms = new Set<string>()
292 for (const result of displayResults) {
293 for (const term in result.match) terms.add(term)
294 }
295
296 return {
297 results: displayResults,
298 terms: [...terms]
299 }
300}
301
302async function ensureUrlLinks() {
303 if (urlLinks.length > 0) return
304 if (urlLinksPromise) {
305 await urlLinksPromise
306 return
307 }
308
309 urlLinksPromise = fetch('/url-search-index.json')
310 .then((r) => r.json())
311 .then((data: PageLink[]) => {
312 data.sort((a, b) => getPageOrder(a.pageId) - getPageOrder(b.pageId))
313 urlLinks = data
314 urlLinkHrefsLower = data.map((link) => link.href.toLowerCase())
315 })
316 .catch(() => {
317 urlLinks = []
318 urlLinkHrefsLower = []
319 })
320 .finally(() => {
321 urlLinksPromise = null
322 })
323 await urlLinksPromise
324}
325
326async function ensureTabTargets() {
327 if (tabTargetMap.size > 0) return
328 if (tabTargetsPromise) {
329 await tabTargetsPromise
330 return
331 }
332
333 tabTargetsPromise = fetch('/tab-search-index.json')
334 .then((r) => r.json())
335 .then((data: TabTarget[]) => {
336 tabTargetMap = new Map(
337 data.map((target) => [
338 getAnchorKey(target.pageId, target.anchor),
339 target.tabs
340 ])
341 )
342 })
343 .catch(() => {
344 tabTargetMap = new Map()
345 })
346 .finally(() => {
347 tabTargetsPromise = null
348 })
349 await tabTargetsPromise
350}
351
352async function ensureSearchMetadata() {
353 await Promise.all([ensureUrlLinks(), ensureTabTargets()])
354}
355
356async function urlSearch(message: UrlSearchRequest) {
357 setPageOrder(message.pageOrderEntries)
358 await ensureSearchMetadata()
359
360 const query = message.query.trim().toLowerCase()
361 if (!query) return { matches: [], pageGroups: [] }
362
363 const matches: PageLink[] = []
364 const pageGroups = new Map<string, PageGroupCount>()
365 for (let i = 0; i < urlLinks.length; i++) {
366 if (!urlLinkHrefsLower[i].includes(query)) continue
367
368 const link = urlLinks[i]
369
370 if (link.tabs?.length) {
371 matches.push(link)
372 } else {
373 const tabs = tabTargetMap.get(getAnchorKey(link.pageId, link.anchor))
374 matches.push(tabs?.length ? { ...link, tabs } : link)
375 }
376 const existing = pageGroups.get(link.pageId)
377 if (existing) existing.count++
378 else pageGroups.set(link.pageId, { key: link.pageId, count: 1 })
379 }
380
381 return {
382 matches,
383 pageGroups: [...pageGroups.values()].sort(
384 (a, b) => getPageOrder(a.key) - getPageOrder(b.key)
385 )
386 }
387}
388
389self.onmessage = async (event: MessageEvent<SearchWorkerRequest>) => {
390 const message = event.data
391 try {
392 const payload = message.type === 'load-index'
393 ? await loadSearchIndex(
394 message.localeIndex,
395 message.indexVersion,
396 message.indexJson,
397 message.config
398 )
399 : message.type === 'text-search'
400 ? await textSearch(message)
401 : message.type === 'preload-metadata'
402 ? (setPageOrder(message.pageOrderEntries), await ensureSearchMetadata())
403 : await urlSearch(message)
404 self.postMessage({
405 type: `${message.type}:success`,
406 id: message.id,
407 payload
408 })
409 } catch (error) {
410 self.postMessage({
411 type: `${message.type}:error`,
412 id: message.id,
413 error: error instanceof Error ? error.message : String(error)
414 })
415 }
416}