Commit 7dcde1e400

7dcde1e4007e4a3e18c5604dd4234071897ac944

parent: 221bb3fdd4

Unsigned

taskylizard <75871323+taskylizard@users.noreply.github.com> · 2026-06-04 13:32 UTC

try using worker for search

Layout: unified · split

docs/.vitepress/theme/components/Search.vue +283 −141
@@ -1,5 +1,5 @@
1<script lang="ts" setup> 1<script lang="ts" setup>
2import MiniSearch, { type SearchResult } from 'minisearch' 2import type { SearchResult } from 'minisearch'
3import { dataSymbol, type DefaultTheme, inBrowser, useRouter } from 'vitepress' 3import { dataSymbol, type DefaultTheme, inBrowser, useRouter } from 'vitepress'
4import { 4import {
5 computed, 5 computed,
@@ -80,7 +80,14 @@ const el = shallowRef<HTMLElement>()
80const resultsEl = shallowRef<HTMLElement>() 80const resultsEl = shallowRef<HTMLElement>()
81 81
82/* Search */ 82/* Search */
83interface Result {
84 title: string
85 titles: string[]
86 text?: string
87}
88
83const searchIndexData = shallowRef(localSearchIndex) 89const searchIndexData = shallowRef(localSearchIndex)
90const searchIndexVersion = ref(0)
84 91
85// @ts-ignore 92// @ts-ignore
86if (import.meta.hot) { 93if (import.meta.hot) {
@@ -88,16 +95,11 @@ if (import.meta.hot) {
88 import.meta.hot.accept('@localSearchIndex', (m) => { 95 import.meta.hot.accept('@localSearchIndex', (m) => {
89 if (m) { 96 if (m) {
90 searchIndexData.value = m.default 97 searchIndexData.value = m.default
98 searchIndexVersion.value++
91 } 99 }
92 }) 100 })
93} 101}
94 102
95interface Result {
96 title: string
97 titles: string[]
98 text?: string
99}
100
101const vitePressData = useData() 103const vitePressData = useData()
102const { activate } = useFocusTrap(el, { 104const { activate } = useFocusTrap(el, {
103 immediate: true, 105 immediate: true,
@@ -110,24 +112,6 @@ const { activate } = useFocusTrap(el, {
110 } 112 }
111}) 113})
112const { localeIndex, theme } = vitePressData 114const { localeIndex, theme } = vitePressData
113const searchIndex = computedAsync(async () =>
114 markRaw(
115 MiniSearch.loadJSON<Result>(
116 (await searchIndexData.value[localeIndex.value]?.())?.default,
117 {
118 fields: ['title', 'titles', 'text'],
119 storeFields: ['title', 'titles'],
120 searchOptions: {
121 boost: { title: 10, titles: 4, text: 1 },
122 ...(theme.value.search?.provider === 'local' &&
123 theme.value.search.options?.miniSearch?.searchOptions)
124 },
125 ...(theme.value.search?.provider === 'local' &&
126 theme.value.search.options?.miniSearch?.options)
127 }
128 )
129 )
130)
131 115
132const disableQueryPersistence = computed(() => { 116const disableQueryPersistence = computed(() => {
133 return ( 117 return (
@@ -287,37 +271,13 @@ function cycleSearchMode() {
287const matchExact = computed(() => searchMode.value === 'exact') 271const matchExact = computed(() => searchMode.value === 'exact')
288const urlSearchMode = computed(() => searchMode.value === 'url') 272const urlSearchMode = computed(() => searchMode.value === 'url')
289 273
290const allLinks = shallowRef<PageLink[]>([]) 274interface PageGroupCount {
291let allLinksFetchPromise: Promise<void> | null = null 275 key: string
292 276 count: number
293async function ensureAllLinks() {
294 if (allLinks.value.length > 0) return
295 if (allLinksFetchPromise) {
296 await allLinksFetchPromise
297 return
298 }
299 allLinksFetchPromise = fetch('/url-search-index.json')
300 .then((r) => r.json())
301 .then((data: PageLink[]) => {
302 data.sort((a, b) => {
303 const pa = pageMeta.get(a.pageId)?.order ?? Number.MAX_SAFE_INTEGER
304 const pb = pageMeta.get(b.pageId)?.order ?? Number.MAX_SAFE_INTEGER
305 return pa - pb
306 })
307 allLinks.value = data
308 })
309 .catch(() => {
310 allLinks.value = []
311 })
312 .finally(() => {
313 allLinksFetchPromise = null
314 })
315 await allLinksFetchPromise
316} 277}
317 278
318watch(urlSearchMode, (active) => { 279const urlMatches = shallowRef<PageLink[]>([])
319 if (active) ensureAllLinks() 280const urlPageGroupCounts = shallowRef<PageGroupCount[]>([])
320}, { immediate: true })
321 281
322interface UrlResult { 282interface UrlResult {
323 href: string 283 href: string
@@ -333,34 +293,21 @@ const URL_PAGE_SIZE = 25
333// 1-indexed current page within the URL results. 293// 1-indexed current page within the URL results.
334const urlPage = ref(1) 294const urlPage = ref(1)
335 295
336// Full match set — cheap string filtering only (no regex, no object churn). 296// Full URL match set returned by the search worker.
337// Used for accurate page-group counts in the ribbon and for pagination. 297// Used for accurate page-group counts in the ribbon and for pagination.
338const urlMatches = computed((): PageLink[] => {
339 if (!urlSearchMode.value || !filterText.value.trim()) return []
340 const query = urlFilterDebounced.value.trim().toLowerCase()
341 if (!query) return []
342 const out: PageLink[] = []
343 for (const link of allLinks.value) {
344 if (link.href.toLowerCase().includes(query)) out.push(link)
345 }
346 return out
347})
348 298
349// URL mode page ribbon — mirrors the normal pageGroups/filteredResults logic 299// URL mode page ribbon — mirrors the normal pageGroups/filteredResults logic
350const urlActivePageFilter = ref<string | null>(null) 300const urlActivePageFilter = ref<string | null>(null)
351 301
352const urlPageGroups = computed(() => { 302const urlPageGroups = computed(() =>
353 const map = new Map<string, { key: string; label: string; count: number }>() 303 urlPageGroupCounts.value
354 for (const r of urlMatches.value) { 304 .map((group) => ({
355 const key = r.pageId 305 key: group.key,
356 const existing = map.get(key) 306 label: getPageLabel(group.key),
357 if (existing) existing.count++ 307 count: group.count
358 else map.set(key, { key, label: getPageLabel(key), count: 1 }) 308 }))
359 } 309 .sort((a, b) => getPageOrder(a.key) - getPageOrder(b.key))
360 return [...map.values()].sort((a, b) => 310)
361 getPageOrder(a.key) - getPageOrder(b.key)
362 )
363})
364 311
365// Full match set honoring the active ribbon page filter (uncapped). 312// Full match set honoring the active ribbon page filter (uncapped).
366const urlFilteredMatches = computed((): PageLink[] => { 313const urlFilteredMatches = computed((): PageLink[] => {
@@ -540,36 +487,209 @@ const pageMeta = (() => {
540 return map 487 return map
541})() 488})()
542 489
490type SearchMode = 'exact' | 'fuzzy' | 'url'
491
492interface TextSearchWorkerPayload {
493 results: (SearchResult & Result)[]
494 terms: string[]
495}
496
497interface UrlSearchWorkerPayload {
498 matches: PageLink[]
499 pageGroups: PageGroupCount[]
500}
501
502interface LoadIndexWorkerRequest {
503 type: 'load-index'
504 localeIndex: string
505 indexJson: unknown
506 indexVersion: number
507 config: ReturnType<typeof getMiniSearchWorkerConfig>
508}
509
510interface TextSearchWorkerRequest {
511 type: 'text-search'
512 query: string
513 mode: SearchMode
514 pageOrderEntries: [string, number][]
515}
516
517interface UrlSearchWorkerRequest {
518 type: 'url-search'
519 query: string
520 pageOrderEntries: [string, number][]
521}
522
523type SearchWorkerRequest =
524 | LoadIndexWorkerRequest
525 | TextSearchWorkerRequest
526 | UrlSearchWorkerRequest
527
543const activePageFilter = ref<string | null>(null) 528const activePageFilter = ref<string | null>(null)
529const searchWorkerReady = ref(false)
530const searchWorkerConfigKey = computed(() =>
531 JSON.stringify(getMiniSearchWorkerConfig())
532)
533let searchWorker: Worker | undefined
534let searchWorkerRequestId = 0
535let loadedWorkerIndexKey = ''
536const searchWorkerRequests = new Map<
537 number,
538 {
539 resolve: (value: unknown) => void
540 reject: (reason?: unknown) => void
541 }
542>()
543
544function getPageOrderEntries(): [string, number][] {
545 return [...pageMeta.entries()].map(([key, meta]) => [key, meta.order])
546}
547
548function stripNonCloneable(value: unknown): unknown {
549 if (typeof value === 'function' || typeof value === 'symbol') return undefined
550 if (!value || typeof value !== 'object') return value
551 if (Array.isArray(value)) {
552 return value
553 .map((item) => stripNonCloneable(item))
554 .filter((item) => item !== undefined)
555 }
556
557 const out: Record<string, unknown> = {}
558 for (const [key, nestedValue] of Object.entries(value)) {
559 const cloneable = stripNonCloneable(nestedValue)
560 if (cloneable !== undefined) out[key] = cloneable
561 }
562 return out
563}
564
565function getMiniSearchWorkerConfig() {
566 const miniSearch = theme.value.search?.provider === 'local'
567 ? theme.value.search.options?.miniSearch
568 : undefined
569 const rawSearchOptions = miniSearch?.searchOptions as
570 | Record<string, unknown>
571 | undefined
572
573 return {
574 options: stripNonCloneable(miniSearch?.options) as
575 | Record<string, unknown>
576 | undefined,
577 searchOptions: stripNonCloneable(rawSearchOptions) as
578 | Record<string, unknown>
579 | undefined,
580 useDefaultBoostDocument:
581 typeof rawSearchOptions?.boostDocument === 'function'
582 }
583}
584
585function ensureSearchWorker() {
586 if (!inBrowser || searchWorker) return searchWorker
587
588 try {
589 searchWorker = new Worker(
590 new URL('../workers/searchWorker.ts', import.meta.url),
591 {
592 type: 'module'
593 }
594 )
595 } catch (error) {
596 console.error('[search] failed to start search worker', error)
597 return
598 }
544 599
545const docOrder = computed(() => { 600 searchWorker.onmessage = (event: MessageEvent) => {
546 const map = new Map<string, number>() 601 const data = event.data as {
547 const index = searchIndex.value as any 602 id: number
548 if (!index) return map 603 type: string
549 // _documentIds maps internalDocId -> original id, in insertion order. 604 payload?: unknown
550 const ids = index._documentIds 605 error?: string
551 if (ids instanceof Map) {
552 let i = 0
553 for (const originalId of ids.values()) {
554 map.set(String(originalId), i++)
555 } 606 }
556 } else if (ids && typeof ids === 'object') { 607 const request = searchWorkerRequests.get(data.id)
557 // Some versions store it as a plain object keyed by numeric doc id. 608 if (!request) return
558 const keys = Object.keys(ids) 609
559 .map(Number) 610 searchWorkerRequests.delete(data.id)
560 .sort((a, b) => a - b) 611 if (data.type.endsWith(':error')) {
561 let i = 0 612 request.reject(new Error(data.error ?? 'Search worker failed'))
562 for (const k of keys) { 613 } else {
563 map.set(String(ids[k]), i++) 614 request.resolve(data.payload)
564 } 615 }
565 } 616 }
566 return map 617 searchWorker.onerror = (event) => {
567}) 618 console.error('[search] search worker error', event)
619 }
620 searchWorkerReady.value = true
621 return searchWorker
622}
623
624function postSearchWorker<T>(message: SearchWorkerRequest) {
625 const worker = ensureSearchWorker()
626 if (!worker) return Promise.reject(new Error('Search worker is unavailable'))
568 627
569function getDocOrder(id: string) { 628 const id = ++searchWorkerRequestId
570 return docOrder.value.get(id) ?? Number.MAX_SAFE_INTEGER 629 return new Promise<T>((resolve, reject) => {
630 searchWorkerRequests.set(id, {
631 resolve: (value) => resolve(value as T),
632 reject
633 })
634 worker.postMessage({ ...message, id })
635 })
571} 636}
572 637
638onMounted(() => {
639 ensureSearchWorker()
640})
641
642onBeforeUnmount(() => {
643 searchWorker?.terminate()
644 searchWorker = undefined
645 loadedWorkerIndexKey = ''
646 searchWorkerReady.value = false
647 for (const request of searchWorkerRequests.values()) {
648 request.reject(new Error('Search worker was terminated'))
649 }
650 searchWorkerRequests.clear()
651})
652
653watch(
654 () =>
655 [
656 searchWorkerReady.value,
657 urlSearchMode.value,
658 urlFilterDebounced.value
659 ] as const,
660 async ([ready, active, query], _old, onCleanup) => {
661 let canceled = false
662 onCleanup(() => {
663 canceled = true
664 })
665
666 if (!active || !query.trim()) {
667 urlMatches.value = []
668 urlPageGroupCounts.value = []
669 return
670 }
671 if (!ready) return
672
673 try {
674 const payload = await postSearchWorker<UrlSearchWorkerPayload>({
675 type: 'url-search',
676 query,
677 pageOrderEntries: getPageOrderEntries()
678 })
679 if (canceled) return
680 urlMatches.value = payload.matches
681 urlPageGroupCounts.value = payload.pageGroups
682 } catch (error) {
683 if (!canceled) {
684 console.error('[search] URL search worker request failed', error)
685 urlMatches.value = []
686 urlPageGroupCounts.value = []
687 }
688 }
689 },
690 { immediate: true }
691)
692
573function getPageKey(id: string) { 693function getPageKey(id: string) {
574 return id.split('#')[0].replace(/\/$/, '') 694 return id.split('#')[0].replace(/\/$/, '')
575} 695}
@@ -893,18 +1013,34 @@ function buildDocExcerpt(
893watchDebounced( 1013watchDebounced(
894 () => 1014 () =>
895 [ 1015 [
896 searchIndex.value, 1016 searchWorkerReady.value,
1017 localeIndex.value,
1018 searchIndexVersion.value,
1019 searchWorkerConfigKey.value,
897 filterText.value, 1020 filterText.value,
898 showDetailedList.value, 1021 showDetailedList.value,
899 searchMode.value 1022 searchMode.value
900 ] as const, 1023 ] as const,
901 async ( 1024 async (
902 [index, filterTextValue, showDetailedListValue, mode], 1025 [
1026 ready,
1027 localeIndexValue,
1028 indexVersion,
1029 configKey,
1030 filterTextValue,
1031 showDetailedListValue,
1032 mode
1033 ],
903 old, 1034 old,
904 onCleanup 1035 onCleanup
905 ) => { 1036 ) => {
906 if (old?.[0] !== index) { 1037 if (
907 // in case of hmr 1038 old?.[1] !== localeIndexValue ||
1039 old?.[2] !== indexVersion ||
1040 old?.[3] !== configKey
1041 ) {
1042 // Locale/config changes rebuild the worker index, so cached excerpts may no
1043 // longer match the active result set.
908 cache.clear() 1044 cache.clear()
909 } 1045 }
910 1046
@@ -913,35 +1049,55 @@ watchDebounced(
913 canceled = true 1049 canceled = true
914 }) 1050 })
915 1051
916 if (!index) return 1052 if (!ready) return
917 1053
918 // In URL search mode, skip normal text search 1054 // In URL search mode, skip normal text search
919 if (mode === 'url') { 1055 if (mode === 'url') {
920 results.value = [] 1056 results.value = []
1057 currentTerms.value = new Set()
921 enableNoResults.value = true 1058 enableNoResults.value = true
922 return 1059 return
923 } 1060 }
924 1061
925 // Dynamic search options based on matchExact toggle 1062 let workerPayload: TextSearchWorkerPayload
926 const dynamicSearchOptions = { 1063 try {
927 fuzzy: mode === 'fuzzy' ? (0.3 as number | false) : false, 1064 const workerIndexKey =
928 prefix: mode === 'fuzzy' ? (term: string) => term.length > 3 : false, 1065 `${localeIndexValue}\n${indexVersion}\n${configKey}`
929 maxFuzzy: mode === 'fuzzy' ? 1 : 0, 1066 if (loadedWorkerIndexKey !== workerIndexKey) {
930 boost: { title: 10, titles: 4, text: 1 } 1067 const indexJson = (await searchIndexData.value[localeIndexValue]?.())
931 } 1068 ?.default
1069 if (canceled) return
1070 await postSearchWorker<void>({
1071 type: 'load-index',
1072 localeIndex: localeIndexValue,
1073 indexJson,
1074 indexVersion,
1075 config: getMiniSearchWorkerConfig()
1076 })
1077 if (canceled) return
1078 loadedWorkerIndexKey = workerIndexKey
1079 }
932 1080
933 // Search 1081 workerPayload = await postSearchWorker<TextSearchWorkerPayload>({
934 const ranked = index.search( 1082 type: 'text-search',
935 filterTextValue, 1083 query: filterTextValue,
936 dynamicSearchOptions 1084 mode,
937 ) as (SearchResult & Result)[] 1085 pageOrderEntries: getPageOrderEntries()
1086 })
1087 } catch (error) {
1088 if (!canceled) {
1089 console.error('[search] text search worker request failed', error)
1090 results.value = []
1091 currentTerms.value = new Set()
1092 enableNoResults.value = true
1093 }
1094 return
1095 }
1096 if (canceled) return
938 1097
939 const top = ranked.slice(0, 50) 1098 const _result = workerPayload.results
940 const seen = new Set(top.map((r) => r.id)) 1099 const terms = new Set(workerPayload.terms)
941 const titleHits = ranked.filter( 1100 currentTerms.value = terms
942 (r) => !seen.has(r.id) && r.match && Object.keys(r.match).length > 0
943 )
944 const _result = [...top, ...titleHits] as (SearchResult & Result)[]
945 enableNoResults.value = true 1101 enableNoResults.value = true
946 1102
947 if (!_result.length) { 1103 if (!_result.length) {
@@ -949,26 +1105,12 @@ watchDebounced(
949 return 1105 return
950 } 1106 }
951 1107
952 // Collect highlight terms up front (cheap — no rendering needed).
953 const terms = new Set<string>()
954 for (const r of _result) {
955 for (const term in r.match) terms.add(term)
956 }
957 currentTerms.value = terms
958
959 const toRows = (list: (SearchResult & Result)[]) => 1108 const toRows = (list: (SearchResult & Result)[]) =>
960 list 1109 list.map((r) => {
961 .map((r) => { 1110 const [id, anchor] = r.id.split('#')
962 const [id, anchor] = r.id.split('#') 1111 const map = cache.get(`${id}\n${filterTextValue}`)
963 const map = cache.get(`${id}\n${filterTextValue}`) 1112 return { ...r, text: map?.get(anchor) ?? '' }
964 return { ...r, text: map?.get(anchor) ?? '' } 1113 })
965 })
966 .sort((a, b) => {
967 const pageDiff = getPageOrder(getPageKey(a.id)) -
968 getPageOrder(getPageKey(b.id))
969 if (pageDiff !== 0) return pageDiff
970 return getDocOrder(a.id) - getDocOrder(b.id)
971 })
972 1114
973 const highlight = () => 1115 const highlight = () =>
974 new Promise<void>((resolve) => { 1116 new Promise<void>((resolve) => {
docs/.vitepress/theme/workers/searchWorker.ts added +276
@@ -0,0 +1,276 @@
1import MiniSearch, {
2 type Options,
3 type SearchOptions,
4 type SearchResult
5} from 'minisearch'
6
7import type { PageLink } from '../../plugins/urlSearchPlugin'
8
9interface Result {
10 title: string
11 titles: string[]
12 text?: string
13}
14
15type SearchMode = 'exact' | 'fuzzy' | 'url'
16
17type PlainRecord = Record<string, unknown>
18
19interface SearchConfig {
20 options?: PlainRecord
21 searchOptions?: PlainRecord
22 useDefaultBoostDocument?: boolean
23}
24
25interface PageGroupCount {
26 key: string
27 count: number
28}
29
30interface LoadIndexRequest {
31 type: 'load-index'
32 id: number
33 localeIndex: string
34 indexJson: unknown
35 indexVersion: number
36 config: SearchConfig
37}
38
39interface TextSearchRequest {
40 type: 'text-search'
41 id: number
42 query: string
43 mode: SearchMode
44 pageOrderEntries: [string, number][]
45}
46
47interface UrlSearchRequest {
48 type: 'url-search'
49 id: number
50 query: string
51 pageOrderEntries: [string, number][]
52}
53
54type SearchWorkerRequest =
55 | LoadIndexRequest
56 | TextSearchRequest
57 | UrlSearchRequest
58
59type WorkerSearchResult = SearchResult & Result
60
61let searchIndex: MiniSearch<Result> | null = null
62let searchIndexKey = ''
63let urlLinks: PageLink[] = []
64let urlLinksPromise: Promise<void> | null = null
65let pageOrder = new Map<string, number>()
66let docOrder = new Map<string, number>()
67
68function defaultBoostDocument(
69 _: string,
70 term: string,
71 storedFields: Record<string, string | string[]>
72) {
73 const titles = ((storedFields?.titles as string[] | undefined) ?? [])
74 .filter((t) => Boolean(t))
75 .map((t) => t.toLowerCase())
76 const titleIndex = titles
77 .map((t, i) => (t?.includes(term) ? i : -1))
78 .find((i) => i >= 0) ?? -1
79 if (titleIndex >= 0) return 10000 - titleIndex
80 return 1
81}
82
83function stableStringify(value: unknown): string {
84 if (value === null || typeof value !== 'object') return JSON.stringify(value)
85 if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`
86 const object = value as Record<string, unknown>
87 return `{${
88 Object.keys(object).sort().map((key) =>
89 `${JSON.stringify(key)}:${stableStringify(object[key])}`
90 ).join(',')
91 }}`
92}
93
94function setPageOrder(entries: [string, number][]) {
95 pageOrder = new Map(entries)
96}
97
98function getPageKey(id: string) {
99 return id.split('#')[0].replace(/\/$/, '')
100}
101
102function getPageOrder(key: string) {
103 return pageOrder.get(key) ?? Number.MAX_SAFE_INTEGER
104}
105
106function getDocOrder(id: string) {
107 return docOrder.get(id) ?? Number.MAX_SAFE_INTEGER
108}
109
110function compareByPageAndDoc(a: { id: unknown }, b: { id: unknown }) {
111 const aId = String(a.id)
112 const bId = String(b.id)
113 const pageDiff = getPageOrder(getPageKey(aId)) - getPageOrder(getPageKey(bId))
114 if (pageDiff !== 0) return pageDiff
115 return getDocOrder(aId) - getDocOrder(bId)
116}
117
118function rebuildDocOrder(index: MiniSearch<Result>) {
119 const map = new Map<string, number>()
120 const ids = (index as any)._documentIds
121 if (ids instanceof Map) {
122 let i = 0
123 for (const originalId of ids.values()) {
124 map.set(String(originalId), i++)
125 }
126 } else if (ids && typeof ids === 'object') {
127 const keys = Object.keys(ids)
128 .map(Number)
129 .sort((a, b) => a - b)
130 let i = 0
131 for (const key of keys) {
132 map.set(String(ids[key]), i++)
133 }
134 }
135 docOrder = map
136}
137
138async function loadSearchIndex(
139 localeIndex: string,
140 indexVersion: number,
141 indexJson: unknown,
142 config: SearchConfig
143) {
144 const key = `${localeIndex}\n${indexVersion}\n${stableStringify(config)}`
145 if (searchIndex && searchIndexKey === key) return
146
147 const searchOptions = {
148 boost: { title: 10, titles: 4, text: 1 },
149 ...(config.searchOptions ?? {}),
150 ...(config.useDefaultBoostDocument
151 ? { boostDocument: defaultBoostDocument }
152 : {})
153 } as SearchOptions
154
155 searchIndex = MiniSearch.loadJSON<Result>(
156 indexJson as any,
157 {
158 fields: ['title', 'titles', 'text'],
159 storeFields: ['title', 'titles'],
160 searchOptions,
161 ...(config.options ?? {})
162 } as Options<Result>
163 )
164 searchIndexKey = key
165 rebuildDocOrder(searchIndex)
166}
167
168async function textSearch(message: TextSearchRequest) {
169 setPageOrder(message.pageOrderEntries)
170 if (!searchIndex) throw new Error('Search index has not been loaded')
171
172 const dynamicSearchOptions = {
173 fuzzy: message.mode === 'fuzzy' ? (0.3 as number | false) : false,
174 prefix: message.mode === 'fuzzy'
175 ? (term: string) => term.length > 3
176 : false,
177 maxFuzzy: message.mode === 'fuzzy' ? 1 : 0,
178 boost: { title: 10, titles: 4, text: 1 }
179 } as SearchOptions
180
181 const ranked = searchIndex.search(
182 message.query,
183 dynamicSearchOptions
184 ) as WorkerSearchResult[]
185
186 const top = ranked.slice(0, 50)
187 const seen = new Set(top.map((r) => r.id))
188 const titleHits = ranked.filter(
189 (r) => !seen.has(r.id) && r.match && Object.keys(r.match).length > 0
190 )
191 const results = [...top, ...titleHits].sort(compareByPageAndDoc)
192 const terms = new Set<string>()
193 for (const result of results) {
194 for (const term in result.match) terms.add(term)
195 }
196
197 return {
198 results,
199 terms: [...terms]
200 }
201}
202
203async function ensureUrlLinks() {
204 if (urlLinks.length > 0) return
205 if (urlLinksPromise) {
206 await urlLinksPromise
207 return
208 }
209
210 urlLinksPromise = fetch('/url-search-index.json')
211 .then((r) => r.json())
212 .then((data: PageLink[]) => {
213 data.sort((a, b) => getPageOrder(a.pageId) - getPageOrder(b.pageId))
214 urlLinks = data
215 })
216 .catch(() => {
217 urlLinks = []
218 })
219 .finally(() => {
220 urlLinksPromise = null
221 })
222 await urlLinksPromise
223}
224
225async function urlSearch(message: UrlSearchRequest) {
226 setPageOrder(message.pageOrderEntries)
227 await ensureUrlLinks()
228
229 const query = message.query.trim().toLowerCase()
230 if (!query) return { matches: [], pageGroups: [] }
231
232 const matches: PageLink[] = []
233 const pageGroups = new Map<string, PageGroupCount>()
234 for (const link of urlLinks) {
235 if (!link.href.toLowerCase().includes(query)) continue
236
237 matches.push(link)
238 const existing = pageGroups.get(link.pageId)
239 if (existing) existing.count++
240 else pageGroups.set(link.pageId, { key: link.pageId, count: 1 })
241 }
242
243 return {
244 matches,
245 pageGroups: [...pageGroups.values()].sort(
246 (a, b) => getPageOrder(a.key) - getPageOrder(b.key)
247 )
248 }
249}
250
251self.onmessage = async (event: MessageEvent<SearchWorkerRequest>) => {
252 const message = event.data
253 try {
254 const payload = message.type === 'load-index'
255 ? await loadSearchIndex(
256 message.localeIndex,
257 message.indexVersion,
258 message.indexJson,
259 message.config
260 )
261 : message.type === 'text-search'
262 ? await textSearch(message)
263 : await urlSearch(message)
264 self.postMessage({
265 type: `${message.type}:success`,
266 id: message.id,
267 payload
268 })
269 } catch (error) {
270 self.postMessage({
271 type: `${message.type}:error`,
272 id: message.id,
273 error: error instanceof Error ? error.message : String(error)
274 })
275 }
276}