Skip to content

search-helper

@vuepress/search-helper

Shared utilities for the local search plugins.

The package owns everything a local search plugin needs except the search engine itself: it collects the index items of the pages, keeps the mapping from the index ids back to the page paths, generates the worker that embeds the index, builds the results out of the engine hits, and ships the search box and the search modal of the client.

It is used by @vuepress/plugin-slimsearch, @vuepress/plugin-flexsearch and @vuepress/plugin-orama.

Usage

npm i @vuepress/search-helper@next

The local search plugins of this repository depend on the package, so it is installed together with them. Add it explicitly only when you write your own search plugin.

The node side collects the index of the pages and hands it to the engine, then embeds the encoded index into the worker of the plugin. MyIndex and createIndex below stand for the types and the API of the engine you use:

src/node/mySearchPlugin.ts
import {
  PathStore,
  collectPageIndex,
  generateSearchWorker,
  prepareStore,
} from '@vuepress/search-helper'
import type { SearchIndexStore } from '@vuepress/search-helper'
import type { Plugin } from 'vuepress/core'
import { path } from 'vuepress/utils'

export const mySearchPlugin = (): Plugin => (app) => {
  const store = new PathStore()
  const searchIndexStore: SearchIndexStore<MyIndex> = {}
  const indexesByPage = new Map<string, string[]>()

  return {
    name: 'my-search-plugin',

    onInitialized: () => {
      const { indexesByLocale } = collectPageIndex(
        app,
        {},
        store,
        indexesByPage,
      )

      for (const [localePath, items] of Object.entries(indexesByLocale))
        searchIndexStore[localePath] = createIndex(items)
    },

    onPrepared: () => prepareStore(app, 'my-search', store),

    onGenerated: () =>
      generateSearchWorker(app, {
        workerFile: path.resolve(import.meta.dirname, '../worker/build.js'),
        outputFile: 'my-search.worker.js',
        indexPlaceholder: '__MY_SEARCH_INDEX__',
        sortPlaceholder: '__MY_SEARCH_SORT_STRATEGY__',
        encode: (index) => JSON.stringify(index),
        searchIndexStore,
      }),
  }
}

The client side only needs the config of the search box, which is generated from the values that the plugin injects:

src/client/config.ts
import { createSearchClientConfig } from '@vuepress/search-helper/client'

export default createSearchClientConfig({
  options: __MY_SEARCH_OPTIONS__,
  locales: __MY_SEARCH_LOCALES__,
  store,
})

Guide

Indexing the pages

collectPageIndex() turns the pages of the site into index items grouped by locale path. A page is skipped when it is filtered out by the filter option or when it sets search: false in its frontmatter. Every indexable page contributes:

  • A page item, with the id of the page and its title.
  • A section item for each heading of the page, whose id carries the anchor of the section.
  • A custom field item for each indexable custom field of the page.

The ids are built from the numeric page id of the path store, INDEX_ID_SEPARATOR (the NUL character, which can never appear in an anchor) and a kind marker, e.g. 0, 0\u0000#anchor and 0\u0000@1. parseIndexId() splits them back, so an engine only has to store the id string.

PathStore maps the numeric ids to the page paths and back, and reuses the ids of the deleted paths, so that a page keeps a stable id while it exists:

const store = new PathStore()

store.addPath('/guide/') // 0
store.addPaths(['/guide/a.html', '/guide/b.html']) // [1, 2]
store.deletePath('/guide/a.html')
store.toJSON() // { '0': '/guide/', '2': '/guide/b.html' }

generatePageIndex() generates the items of a single page, which is what a dev server needs to update the index of a page without rebuilding everything.

Preparing the index for the client

The index of every locale is written into the temp directory of the plugin, where the client and the dev worker can import it:

  • prepareStore() writes the path store into <tempDir>/store.js.
  • writeLocaleIndex() writes the encoded index of a locale into its own chunk.
  • writeLocaleRegistry() writes <tempDir>/index.js, which lazily imports the chunks of every locale.
  • prepareSearchIndex() writes the chunks and the registry of every locale of an index store.
  • prepareWorkerOptions() writes the sort strategy into <tempDir>/worker-options.js.

In dev, the client loads these files; in build, the index is embedded into the worker by generateSearchWorker(), which is why the worker must be generated on the onGenerated hook, once every page is known.

Generating the search worker

generateSearchWorker() reads a worker template, replaces the placeholders of the index and of the sort strategy, and writes the result into the output directory. The template is a normal worker module, so it imports the engine, decodes the embedded index and answers every message with the shared protocol:

src/worker/build.ts
import { entries, fromEntries } from '@vuepress/helper/shared'
import {
  createWorkerResponse,
  getOwnEntry,
} from '@vuepress/search-helper/shared'

declare const __MY_SEARCH_INDEX__: string
declare const __MY_SEARCH_SORT_STRATEGY__: 'max' | 'total'

const searchIndex = fromEntries(
  entries(JSON.parse(__MY_SEARCH_INDEX__) as Record<string, string>).map(
    ([localePath, encoded]) => [localePath, loadIndex(decodeIndex(encoded))],
  ),
)

self.addEventListener('message', ({ data }) => {
  self.postMessage(
    createWorkerResponse(
      data,
      getOwnEntry(searchIndex, data.locale),
      { getSearchResults, getSuggestions },
      __MY_SEARCH_SORT_STRATEGY__,
    ),
  )
})

createWorkerResponse() resolves the type of the request (all, search or suggest), calls the matching handler and returns the payload of the response, so the client code does not have to know the engine.

Building the results

An engine returns its own hits: an index id, a score and the stored document. buildSearchResults() groups them by page, uses the page item as the title of the result and sorts the pages by the sortStrategy:

import { buildSearchResults } from '@vuepress/search-helper/shared'

const results = buildSearchResults({
  hits,
  displayTerms: terms,
  getPageTitle: (pageId) => store[pageId],
})

Every matched item keeps the ranges that getMatchedContent() computed, so the client can highlight the query without parsing the content again.

Tokenizing

A search engine tokenizes the indexed documents, and the query must be tokenized the same way, otherwise the terms do not match. createWordTokenizer() returns a tokenizer for a language, which lowercases the terms and folds their diacritics, and keeps the repetitions so that the phrase matching still works. isSegmenterAvailable() tells whether Intl.Segmenter can split languages without whitespace, and foldDiacritics() and segmentWords() expose the two steps on their own.

The client side

createSearchClientConfig() returns the client config of the plugin: it stores the config, injects the search options into the app, registers the SearchBox component and mounts the SearchModal root component. The config is read back by getSearchClientConfig() in these components and in the worker composables.

The options of the search box can also be read from a page with useSearchOptions(), which merges the engine defaults, the root options and the options of the current locale.

Node API

collectPageIndex

appRequiredApp

The VuePress app of the site.

optionsCollectPageIndexOptions

The options shared by the search plugins, i.e. indexContent, customFields, preserveTags and filter.

storeRequiredPathStore

The path store of the plugin.

indexesByPageMap<string, string[]>

The map to fill with the index ids of every page, which is used to remove the stale items of a page on update.

It returns CollectedPageIndex, i.e. { indexesByLocale, indexesByPage }, where the items are grouped by locale path.

generatePageIndex

pageRequiredPage

The page to index.

storeRequiredPathStore

The path store of the plugin.

optionsGeneratePageIndexOptions

The indexContent, customFields and preserveTags options.

It returns the IndexItem[] of a single page: the page item, a section item per heading and a custom field item per indexable field.

PathStore

The class that maps the numeric ids of the index to the page paths.

  • addPath(path): returns the id of the path, and creates it when it is new.
  • addPaths(paths): returns the ids of the paths.
  • deletePath(path): frees the id of the path, which is reused by a later path.
  • clear(): removes every path.
  • toJSON(): returns the Record<number, string> of the stored paths.

prepareStore

appRequiredApp

The VuePress app of the site.

tempDirRequiredstring

The name of the temp directory of the plugin.

storeRequiredPathStore

The path store of the plugin.

It writes the store into <tempDir>/store.js.

writeLocaleIndex

appRequiredApp

The VuePress app of the site.

optionsRequiredPrepareIndexOptions<TIndex>

The tempDir of the plugin and the encode function that serializes an index.

localeRequiredstring

The path of the locale.

indexRequiredTIndex

The index of the locale.

It writes the encoded index of a locale into its own chunk of the temp directory.

writeLocaleRegistry

appRequiredApp

The VuePress app of the site.

tempDirRequiredstring

The name of the temp directory of the plugin.

localesRequiredstring[]

The paths of the locales.

It writes <tempDir>/index.js, whose entries lazily import the chunk of every locale.

prepareSearchIndex

appRequiredApp

The VuePress app of the site.

optionsRequiredPrepareIndexOptions<TIndex>

The tempDir of the plugin and the encode function that serializes an index.

searchIndexStoreRequiredSearchIndexStore<TIndex>

The index of every locale.

It writes the chunks of every locale, then the registry.

prepareWorkerOptions

appRequiredApp

The VuePress app of the site.

tempDirRequiredstring

The name of the temp directory of the plugin.

sortStrategyRequiredSearchSortStrategy

The sort strategy of the results, i.e. 'max' or 'total'.

It writes the sort strategy into <tempDir>/worker-options.js.

generateSearchWorker

workerFileRequiredstring

The path of the worker template.

outputFileRequiredstring

The name of the generated worker, relative to the output directory.

indexPlaceholderRequiredstring

The placeholder of the encoded index in the template.

sortPlaceholderRequiredstring

The placeholder of the sort strategy in the template.

encodeRequired(index: TIndex) => string

The function that serializes an index, which is the same one as the encode of writeLocaleIndex().

sortStrategySearchSortStrategy
Default'max'

The sort strategy of the results.

searchIndexStoreRequiredSearchIndexStore<TIndex>

The index of every locale.

It embeds the encoded index of every locale into the worker template and writes the result to the output directory. It must be called on the onGenerated hook.

createSearchLogger

It returns the VuePress logger of a plugin, so that every search plugin logs its messages with the same prefix.

getLocaleLanguage

It returns the language of a locale path, falling back to the lang of the site when the locale does not declare one.

getLocaleChunkName

It returns the name of the temp chunk of a locale, which is what writeLocaleRegistry() imports.

searchLocaleInfo

The default text of the search box for every built-in language, typed as DefaultLocaleInfo<SearchLocaleData>. The plugins pass it as the default of their locales option, so a site only has to translate the text it wants to change. See Locales.

Shared API

The shared entry, i.e. @vuepress/search-helper/shared, holds the code that runs in the worker and in the browser, so its values are also re-exported by the node entry.

buildSearchResults

hitsRequiredSearchHit[]

The hits of the engine, i.e. an index id, a score, the stored document and the matched terms.

displayTermsRequiredstring[]

The terms of the query, used to highlight the matches. They must be tokenized the same way as the index.

getPageTitleRequired(pageId: number) => string | undefined

It returns the title of a page by its index id.

sortStrategySearchSortStrategy
Default'max'

Whether a page is sorted by its best match ('max') or by the sum of its matches ('total').

It returns the SearchResult[] of the query, i.e. a title and the matched items of the page.

parseIndexId

It splits an index id into its pageId, its kind ('page', 'section' or 'customField') and its info, i.e. the anchor of a section or the index of a custom field.

isSectionIndexItem and isCustomFieldIndexItem

The type guards of the section items and of the custom field items of an IndexItem[].

getMatchedContent

It returns the snippet of a content around its matches, i.e. { text, highlights }, where highlights is the flat list of the ranges to highlight, or null when the content does not match.

Tokenizers

  • createWordTokenizer(language): returns the tokenizer of a language, which lowercases the terms and folds their diacritics.
  • foldDiacritics(text): replaces the accented characters by their base character, keeping the length of the text.
  • segmentWords(text, segmenter): splits a text with an Intl.Segmenter.
  • createSegmenter(language): returns the segmenter of a language.
  • isSegmenterAvailable(): tells whether the runtime provides Intl.Segmenter.
  • foldToken(token): folds a single token.

Worker protocol

The worker and the client share a message protocol, so an engine only has to implement the search itself:

  • WorkerMessageData<TOptions>: the request, i.e. a type ('all', 'search' or 'suggest'), a query, a locale, optional engine options and the id of the request.
  • WorkerResponse: the response, i.e. the type, the id and the payload of the request.
  • createWorkerResponse(data, localeIndex, handlers, sortStrategy): resolves the request and returns the response, with getSearchResults and getSuggestions as handlers.
  • getOwnEntry(record, key): reads an entry of a record, ignoring the inherited properties.

Client API

createSearchClientConfig

optionsRequiredSearchClientOptions

The options of the search box, i.e. suggestion, searchDelay, suggestDelay, queryHistoryCount, resultHistoryCount, hotKeys and worker.

localesRequiredExactLocaleConfig<SearchLocaleData>

The text of the search box of every locale.

customFieldConfigRecord<string, SearchCustomFieldFormatter>

The formatters of the custom fields, indexed by the index of the field.

storeRequiredRecord<number, string>

The path store, which maps the id of a page to its path.

createDevWorker() => Worker

The factory of the worker in the dev server. It must use the new Worker(new URL(...)) syntax, so that the bundler can resolve the imports of the worker.

getLocaleSearchOptions(lang: string) => WorkerSearchOptions

The engine specific defaults of the search options of a locale, merged before the user options.

It returns the client config of the plugin, which injects the options, registers the SearchBox component and mounts the SearchModal root component.

setSearchClientConfig and getSearchClientConfig

They set and read the config of the search client. getSearchClientConfig() throws when the config has not been set, i.e. when the client config of the plugin is not registered.

createSearchWorker

It creates the worker of the search and wraps the message protocol into a SearchWorker:

  • all(query, localePath?, options?): returns the QueryResult of the query, i.e. its suggestions and its results.
  • suggest(query, localePath?, options?): returns the suggestions of the query.
  • search(query, localePath?, options?): returns the results of the query.
  • terminate(): stops the worker.

In dev it creates the worker with createDevWorker, otherwise it loads options.worker from the site base.

defineSearchConfig, injectSearchConfig and useSearchOptions

defineSearchConfig() marks the options of the plugin, injectSearchConfig() provides them to the app, and useSearchOptions() returns the options of the current locale, merged from the engine defaults, the root options and the options of the locale. The options extend WorkerSearchOptions with querySplitter, suggestionsFilter and resultsFilter.

MIT Licensed