docs/.vitepress/theme/workers/searchWorker.ts

c8bed615164c23c60128fa8225a91db3371f58a1
wotaku/docs/.vitepress/theme/workers/searchWorker.ts history · blame · raw

336 lines · 8502 bytes

  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 urlLinkHrefsLower: string[] = []
 65let urlLinksPromise: Promise<void> | null = null
 66let pageOrder = new Map<string, number>()
 67let docOrder = new Map<string, number>()
 68
 69function defaultBoostDocument(
 70  _: string,
 71  term: string,
 72  storedFields: Record<string, string | string[]>
 73) {
 74  const titles = ((storedFields?.titles as string[] | undefined) ?? [])
 75    .filter((t) => Boolean(t))
 76    .map((t) => t.toLowerCase())
 77  const titleIndex = titles
 78    .map((t, i) => (t?.includes(term) ? i : -1))
 79    .find((i) => i >= 0) ?? -1
 80  if (titleIndex >= 0) return 10000 - titleIndex
 81  return 1
 82}
 83
 84function stableStringify(value: unknown): string {
 85  if (value === null || typeof value !== 'object') return JSON.stringify(value)
 86  if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`
 87  const object = value as Record<string, unknown>
 88  return `{${
 89    Object.keys(object).sort().map((key) =>
 90      `${JSON.stringify(key)}:${stableStringify(object[key])}`
 91    ).join(',')
 92  }}`
 93}
 94
 95function setPageOrder(entries: [string, number][]) {
 96  pageOrder = new Map(entries)
 97}
 98
 99function getPageKey(id: string) {
100  return id.split('#')[0].replace(/\/$/, '')
101}
102
103function getPageOrder(key: string) {
104  return pageOrder.get(key) ?? Number.MAX_SAFE_INTEGER
105}
106
107function getDocOrder(id: string) {
108  return docOrder.get(id) ?? Number.MAX_SAFE_INTEGER
109}
110
111function compareByPageAndDoc(a: { id: unknown }, b: { id: unknown }) {
112  const aId = String(a.id)
113  const bId = String(b.id)
114  const pageDiff = getPageOrder(getPageKey(aId)) - getPageOrder(getPageKey(bId))
115  if (pageDiff !== 0) return pageDiff
116  return getDocOrder(aId) - getDocOrder(bId)
117}
118
119function stripMarkdown(value: string) {
120  return value
121    .replace(/`([^`]+)`/g, '$1')
122    .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')
123    .replace(/[*_~]/g, '')
124    .trim()
125}
126
127function getQueryTerms(query: string) {
128  return query
129    .toLowerCase()
130    .split(/\s+/)
131    .map((term) => term.trim())
132    .filter(Boolean)
133}
134
135function findMatchingLinkForResult(
136  result: WorkerSearchResult,
137  query: string
138) {
139  const pageId = getPageKey(String(result.id))
140  const anchor = String(result.id).split('#')[1] ?? ''
141  const terms = getQueryTerms(query)
142  if (!terms.length) return
143
144  return urlLinks.find((link) => {
145    if (link.pageId.replace(/\/$/, '') !== pageId || link.anchor !== anchor) {
146      return false
147    }
148
149    const linkText = stripMarkdown(link.linkText).toLowerCase()
150    return terms.every((term) => linkText.includes(term))
151  })
152}
153
154function withLinkPathTitles(
155  results: WorkerSearchResult[],
156  query: string
157) {
158  if (!urlLinks.length) return results
159
160  return results.map((result) => {
161    const link = findMatchingLinkForResult(result, query)
162    if (!link) return result
163
164    return {
165      ...result,
166      title: stripMarkdown(link.linkText),
167      titles: link.titles
168    }
169  })
170}
171
172function rebuildDocOrder(index: MiniSearch<Result>) {
173  const map = new Map<string, number>()
174  const ids = (index as any)._documentIds
175  if (ids instanceof Map) {
176    let i = 0
177    for (const originalId of ids.values()) {
178      map.set(String(originalId), i++)
179    }
180  } else if (ids && typeof ids === 'object') {
181    const keys = Object.keys(ids)
182      .map(Number)
183      .sort((a, b) => a - b)
184    let i = 0
185    for (const key of keys) {
186      map.set(String(ids[key]), i++)
187    }
188  }
189  docOrder = map
190}
191
192async function loadSearchIndex(
193  localeIndex: string,
194  indexVersion: number,
195  indexJson: unknown,
196  config: SearchConfig
197) {
198  const key = `${localeIndex}\n${indexVersion}\n${stableStringify(config)}`
199  if (searchIndex && searchIndexKey === key) return
200
201  const searchOptions = {
202    boost: { title: 10, titles: 4, text: 1 },
203    ...(config.searchOptions ?? {}),
204    ...(config.useDefaultBoostDocument
205      ? { boostDocument: defaultBoostDocument }
206      : {})
207  } as SearchOptions
208
209  searchIndex = MiniSearch.loadJSON<Result>(
210    indexJson as any,
211    {
212      fields: ['title', 'titles', 'text'],
213      storeFields: ['title', 'titles'],
214      searchOptions,
215      ...(config.options ?? {})
216    } as Options<Result>
217  )
218  searchIndexKey = key
219  rebuildDocOrder(searchIndex)
220}
221
222async function textSearch(message: TextSearchRequest) {
223  setPageOrder(message.pageOrderEntries)
224  if (!searchIndex) throw new Error('Search index has not been loaded')
225
226  const dynamicSearchOptions = {
227    fuzzy: message.mode === 'fuzzy' ? (0.3 as number | false) : false,
228    prefix: message.mode === 'fuzzy'
229      ? (term: string) => term.length > 3
230      : false,
231    maxFuzzy: message.mode === 'fuzzy' ? 1 : 0,
232    boost: { title: 10, titles: 4, text: 1 }
233  } as SearchOptions
234
235  const ranked = searchIndex.search(
236    message.query,
237    dynamicSearchOptions
238  ) as WorkerSearchResult[]
239
240  const top = ranked.slice(0, 50)
241  const seen = new Set(top.map((r) => r.id))
242  const titleHits = ranked.filter(
243    (r) => !seen.has(r.id) && r.match && Object.keys(r.match).length > 0
244  )
245  const results = [...top, ...titleHits].sort(compareByPageAndDoc)
246  await ensureUrlLinks()
247  const displayResults = withLinkPathTitles(results, message.query)
248  const terms = new Set<string>()
249  for (const result of displayResults) {
250    for (const term in result.match) terms.add(term)
251  }
252
253  return {
254    results: displayResults,
255    terms: [...terms]
256  }
257}
258
259async function ensureUrlLinks() {
260  if (urlLinks.length > 0) return
261  if (urlLinksPromise) {
262    await urlLinksPromise
263    return
264  }
265
266  urlLinksPromise = fetch('/url-search-index.json')
267    .then((r) => r.json())
268    .then((data: PageLink[]) => {
269      data.sort((a, b) => getPageOrder(a.pageId) - getPageOrder(b.pageId))
270      urlLinks = data
271      urlLinkHrefsLower = data.map((link) => link.href.toLowerCase())
272    })
273    .catch(() => {
274      urlLinks = []
275      urlLinkHrefsLower = []
276    })
277    .finally(() => {
278      urlLinksPromise = null
279    })
280  await urlLinksPromise
281}
282
283async function urlSearch(message: UrlSearchRequest) {
284  setPageOrder(message.pageOrderEntries)
285  await ensureUrlLinks()
286
287  const query = message.query.trim().toLowerCase()
288  if (!query) return { matches: [], pageGroups: [] }
289
290  const matches: PageLink[] = []
291  const pageGroups = new Map<string, PageGroupCount>()
292  for (let i = 0; i < urlLinks.length; i++) {
293    if (!urlLinkHrefsLower[i].includes(query)) continue
294
295    const link = urlLinks[i]
296
297    matches.push(link)
298    const existing = pageGroups.get(link.pageId)
299    if (existing) existing.count++
300    else pageGroups.set(link.pageId, { key: link.pageId, count: 1 })
301  }
302
303  return {
304    matches,
305    pageGroups: [...pageGroups.values()].sort(
306      (a, b) => getPageOrder(a.key) - getPageOrder(b.key)
307    )
308  }
309}
310
311self.onmessage = async (event: MessageEvent<SearchWorkerRequest>) => {
312  const message = event.data
313  try {
314    const payload = message.type === 'load-index'
315      ? await loadSearchIndex(
316        message.localeIndex,
317        message.indexVersion,
318        message.indexJson,
319        message.config
320      )
321      : message.type === 'text-search'
322      ? await textSearch(message)
323      : await urlSearch(message)
324    self.postMessage({
325      type: `${message.type}:success`,
326      id: message.id,
327      payload
328    })
329  } catch (error) {
330    self.postMessage({
331      type: `${message.type}:error`,
332      id: message.id,
333      error: error instanceof Error ? error.message : String(error)
334    })
335  }
336}