Repository navigation
feat: search content in a web worker with app/content.worker.ts
#3931
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
Draft
larbish
wants to merge
1
commit into
v4
Choose a base branch
from
feat/content-worker-search
base: v4
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.
+511
−27
Draft
Changes from all commits
Commits
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
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
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,137 @@ | ||
| import { readonly, shallowRef, toValue, watch, type MaybeRefOrGetter, type Ref } from 'vue' | ||
| import type { SearchOptions, SearchResult } from 'comark-content' | ||
| import { createContentClient, type ContentClient, type ContentFetch } from 'comark-content/client' | ||
| import searchClient from 'comark-content/plugins/sqlite-full-text-search/client' | ||
| import { connectContentWorker, type ContentWorker } from 'comark-content/worker' | ||
| import { HMR_REMOVE_EVENT, HMR_UPDATE_EVENT } from '../utils/hmr' | ||
|
|
||
| /** Matches the `searchStatus` prop of Nuxt UI's `<UContentSearch>`. */ | ||
| export type NuxtContentWorkerStatus = 'idle' | 'loading' | 'ready' | 'error' | ||
|
|
||
| export interface NuxtContentWorkerSearchOptions extends SearchOptions { | ||
| /** Instances to search. Defaults to the instances of `useNuxtContentWorker()`. */ | ||
| instances?: string[] | ||
| } | ||
|
|
||
| export interface UseNuxtContentWorkerOptions { | ||
| /** | ||
| * Instances to load and read, such as the current locale's. Only their snapshots are downloaded. | ||
| * When it changes after `warmup()`, the new instances are loaded. Every instance by default. | ||
| */ | ||
| instances?: MaybeRefOrGetter<string[] | undefined> | ||
| } | ||
|
|
||
| export interface NuxtContentWorker { | ||
| /** `ready` once the snapshots of the instances are loaded and their search index is built. */ | ||
| status: Readonly<Ref<NuxtContentWorkerStatus>> | ||
| /** Start the worker and load the instances in the background, such as from `onNuxtReady()`. Safe to call again. */ | ||
| warmup: () => Promise<void> | ||
| /** Full-text search in the worker. Takes the `search` prop of `<UContentSearch>`. */ | ||
| search: (query: string, opts?: NuxtContentWorkerSearchOptions) => Promise<SearchResult[]> | ||
| /** A document of the instances, by public path. */ | ||
| get: ContentClient['get'] | ||
| /** The documents of the given instances, the composable's by default, without their bodies. */ | ||
| list: ContentClient['list'] | ||
| } | ||
|
|
||
| /** Instances loaded or loading in the worker, shared by every `useNuxtContentWorker()`. */ | ||
| const warmed = new Map<string, Promise<void>>() | ||
| let worker: ContentWorker | undefined | ||
|
|
||
| // The worker answers `handler()` requests, so the client is the one `server-only.ts` uses over HTTP. | ||
| const clientOptions = { | ||
| basePath: '/__nuxt_content', | ||
| fetch: ((url, opts) => worker!.fetch(url, opts)) as ContentFetch, | ||
| plugins: [searchClient()], | ||
| } | ||
| const hub = createContentClient(clientOptions) | ||
| const bound = new Map<string, typeof hub>() | ||
| // Sends `?instance=<name>`, so a read only loads that instance. | ||
| const client = (name: string) => bound.get(name) ?? bound.set(name, createContentClient(name, clientOptions)).get(name)! | ||
|
|
||
| /** Created on the first call, so a page that never reads it doesn't download the worker. */ | ||
| function start() { | ||
| if (worker) return | ||
| worker = connectContentWorker( | ||
| // Vite bundles the generated entry as its own chunk. A `#` alias would be read as a URL hash. | ||
| new Worker(new URL('@nuxt/content/worker-entry', import.meta.url), { type: 'module', name: 'nuxt-content' }), | ||
| ) | ||
|
|
||
| if (import.meta.hot) { | ||
| import.meta.hot.on(HMR_UPDATE_EVENT, payload => worker!.update(payload)) | ||
| import.meta.hot.on(HMR_REMOVE_EVENT, payload => worker!.remove(payload)) | ||
| } | ||
| } | ||
|
|
||
| function warmOne(name: string) { | ||
| let warming = warmed.get(name) | ||
| if (!warming) { | ||
| // The next call tries again. | ||
| warming = hub.buildSearchIndex({ instances: [name] }).catch((error) => { | ||
| warmed.delete(name) | ||
| throw error | ||
| }) | ||
| warmed.set(name, warming) | ||
| } | ||
| return warming | ||
| } | ||
|
|
||
| /** | ||
| * The content instances of `app/content.worker.ts`, running in a web worker. | ||
| * Reads and search there don't need a server, so they work on a static host. | ||
| */ | ||
| export function useNuxtContentWorker(options: UseNuxtContentWorkerOptions = {}): NuxtContentWorker { | ||
| const status = shallowRef<NuxtContentWorkerStatus>('idle') | ||
| // A plain copy: `postMessage()` can't clone a reactive array. | ||
| const names = () => [...(toValue(options.instances) ?? import.meta.content.sources)] | ||
| let started = false | ||
| let current: Promise<void> | undefined | ||
|
|
||
| function warmup() { | ||
| if (import.meta.server) return Promise.resolve() | ||
| start() | ||
| started = true | ||
| const loading = Promise.all(names().map(warmOne)).then(() => {}) | ||
| current = loading | ||
| status.value = 'loading' | ||
| // Only the latest instances decide the status: a locale switch makes the previous load stale. | ||
| loading.then( | ||
| () => current === loading && (status.value = 'ready'), | ||
| () => current === loading && (status.value = 'error'), | ||
| ) | ||
| return loading | ||
| } | ||
|
|
||
| if (import.meta.client) { | ||
| watch(names, () => started && warmup().catch(() => {})) | ||
| } | ||
|
|
||
| function ready() { | ||
| if (import.meta.server) throw new Error('`useNuxtContentWorker()` reads in the browser only.') | ||
| // Keeps `status` accurate; the worker loads the instances on the first read anyway. | ||
| warmup().catch(() => {}) | ||
| } | ||
|
|
||
| return { | ||
| status: readonly(status), | ||
| warmup, | ||
| search: async (query, opts = {}) => { | ||
| if (import.meta.server) return [] | ||
| ready() | ||
| return hub.search(query, { ...opts, instances: opts.instances ?? names() }) | ||
| }, | ||
| // A hub `get` would load every instance to find the path. | ||
| get: (async (path: string) => { | ||
| ready() | ||
| for (const name of names()) { | ||
| const doc = await client(name).get(path) | ||
| if (doc) return doc | ||
| } | ||
| return null | ||
| }) as ContentClient['get'], | ||
| list: ((list?: string[]) => { | ||
| ready() | ||
| return hub.list(list ?? names()) | ||
| }) as ContentClient['list'], | ||
| } | ||
| } |
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Limit the SQLite worker-file rewrite to the content worker build.
sqliteWorkerFilesPlugin()is added to the globalvite.worker.pluginsfactory (src/module.ts:267). Its filter matches every module under@sqlite.org/sqlite-wasm(src/module.ts:282). Any application worker that bundles that package receives the rewrite.In such a worker, two supported paths can fail:
bindVfscreates the OPFS async proxy withnew URL("sqlite3-opfs-async-proxy.js", import.meta.url)inside its Promise executor (dist/index.mjs:15786). The rewrite throws there, so the OPFS VFS install rejects. The inspected code does not show whether sqlite-wasm falls back to a transient database in that case.defaultConfig.workercreatessqlite3-worker1.mjswithnew URL(...)(dist/index.mjs:17670). The rewrite makes that call throw. Because the config function is invoked to produce the worker, creating a Worker1 promiser with the default config can throw.The content worker needs neither helper, so the rewrite is correct for it. Apply the rewrite only to the content worker build. The inspected code does not identify a build-level signal for that scope, so this comment does not prescribe a specific implementation.