diff --git a/import-meta.d.ts b/import-meta.d.ts index 0e851a1c1..76569f8ce 100644 --- a/import-meta.d.ts +++ b/import-meta.d.ts @@ -12,7 +12,7 @@ declare global { readonly content: { /** Resolved `content.compatibilityVersion`. With `3`, v3 query/search composables are enabled and sql-query + FTS plugins are injected into the Content instance. */ readonly compatibilityVersion: 3 | 4 - /** Names of the content instances, defined for `app/content.ts` in the app build. */ + /** Names of the content instances, defined for `app/content.ts` and `app/content.worker.ts` in the app build. */ readonly sources: string[] /** Resolved `content.build.markdown.highlight` options, `false` when highlighting is disabled. */ readonly highlight: false | { themes: { light?: string, dark?: string }, langs: string[] } diff --git a/package.json b/package.json index 9526abc88..ae03da6c4 100644 --- a/package.json +++ b/package.json @@ -25,6 +25,7 @@ "./v3": "./dist/runtime/v3/index.js", "./content": "./dist/runtime/server/content.js", "./app": "./dist/runtime/client-content/app.js", + "./worker": "./dist/runtime/client-content/worker.js", "./utils": "./dist/runtime/utils/index.js", "./server": "./dist/runtime/v3/composables.server.js" }, @@ -57,7 +58,7 @@ "@nuxt/kit": "^4.7.0", "@sqlite.org/sqlite-wasm": "3.54.1-build1", "comark": "https://pkg.pr.new/comark@ff4661d", - "comark-content": "^0.6.2", + "comark-content": "https://pkg.pr.new/comark-content@ec7a084", "defu": "^6.1.7", "forges": "^0.3.2", "jiti": "^2.7.0" diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 367e48a83..7fa20406c 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -185,6 +185,7 @@ overrides: '@nuxt/content': link:. postcss-merge-rules@9>cssnano-utils: ^8.2.0 comark: https://pkg.pr.new/comark@ff4661d + comark-content: https://pkg.pr.new/comark-content@ec7a084 importers: @@ -203,8 +204,8 @@ importers: specifier: https://pkg.pr.new/comark@ff4661d version: https://pkg.pr.new/comark@ff4661d(shiki@4.6.0) comark-content: - specifier: ^0.6.2 - version: 0.6.3(forges@0.3.2)(shiki@4.6.0)(unstorage@1.17.6(db0@0.3.4)) + specifier: https://pkg.pr.new/comark-content@ec7a084 + version: https://pkg.pr.new/comark-content@ec7a084(forges@0.3.2)(shiki@4.6.0)(unstorage@1.17.6(db0@0.3.4)) defu: specifier: ^6.1.7 version: 6.1.7 @@ -297,8 +298,8 @@ importers: specifier: link:../.. version: link:../.. comark-content: - specifier: ^0.6.3 - version: 0.6.3(forges@0.3.2)(shiki@4.6.0)(unstorage@1.17.6(db0@0.3.4)) + specifier: https://pkg.pr.new/comark-content@ec7a084 + version: https://pkg.pr.new/comark-content@ec7a084(forges@0.3.2)(shiki@4.6.0)(unstorage@1.17.6(db0@0.3.4)) nuxt: specifier: ^4.7.0 version: 4.7.0(62a1abbd985dd3599f0ed9d942c3b910) @@ -3783,8 +3784,9 @@ packages: colortranslator@5.0.0: resolution: {integrity: sha512-Z3UPUKasUVDFCDYAjP2fmlVRf1jFHJv1izAmPjiOa0OCIw1W7iC8PZ2GsoDa8uZv+mKyWopxxStT9q05+27h7w==} - comark-content@0.6.3: - resolution: {integrity: sha512-AgQOrcmkymyu4PMaDBc97bvmIiZ7DAcvR0c83bmGrzUrf+yJ9khvpRxG0ZzpNDtmm7ahRlrrh8a+pPMK3f41Ng==} + comark-content@https://pkg.pr.new/comark-content@ec7a084: + resolution: {integrity: sha512-7rdCw/uPqoPTRe0arZWw/wc18LYS89613vtb544Nb4oojpsWXhD36he1j50dFr4vr59W1snCKZPmNptfRW3yEA==, tarball: https://pkg.pr.new/comark-content@ec7a084} + version: 0.6.3 hasBin: true peerDependencies: forges: ^0.3.0 @@ -10498,7 +10500,7 @@ snapshots: colortranslator@5.0.0: {} - comark-content@0.6.3(forges@0.3.2)(shiki@4.6.0)(unstorage@1.17.6(db0@0.3.4)): + comark-content@https://pkg.pr.new/comark-content@ec7a084(forges@0.3.2)(shiki@4.6.0)(unstorage@1.17.6(db0@0.3.4)): dependencies: comark: https://pkg.pr.new/comark@ff4661d(shiki@4.6.0) hookable: 6.1.2 diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index a847a13e6..3e578ae77 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -10,8 +10,10 @@ overrides: # postcss-merge-rules@9.1 uses `sameContainer`, added in cssnano-utils@8.2.0, but declares ^8.1.0 "postcss-merge-rules@9>cssnano-utils": ^8.2.0 comark: "https://pkg.pr.new/comark@ff4661d" + # `comark-content/worker` from comarkdown/comark-content#172 and `buildSearchIndex()` from #175, which is stacked on it, until they're released. + comark-content: https://pkg.pr.new/comark-content@ec7a084 -# The `comark` override above is a URL, which pnpm blocks below the top level. Remove both once comark is released. +# The `comark` and `comark-content` overrides above are URLs, which pnpm blocks below the top level. Remove this once both are released. blockExoticSubdeps: false allowBuilds: diff --git a/src/module.ts b/src/module.ts index cb7763cf0..fb77e66fd 100644 --- a/src/module.ts +++ b/src/module.ts @@ -1,12 +1,11 @@ import { comarkContent, contentHub, generateSourceTypes, isParsedSource, readArtifact } from 'comark-content' import defu from 'defu' import type { CacheArtifact, ContentSource, Manifest, AnyComarkContent, ContentHub, ParsedSnapshot, TypegenFieldContext } from 'comark-content' -import { defineNuxtModule, createResolver, addServerImports, addServerHandler, addImports, addComponent, addPlugin, addTemplate, addPrerenderRoutes, addDevServerHandler, addTypeTemplate, addServerTemplate, useLogger } from '@nuxt/kit' -import { existsSync } from 'node:fs' +import { defineNuxtModule, createResolver, addServerImports, addServerHandler, addImports, addComponent, addPlugin, addTemplate, addPrerenderRoutes, addDevServerHandler, addTypeTemplate, addServerTemplate, resolvePath, useLogger } from '@nuxt/kit' import { mkdir, writeFile } from 'node:fs/promises' import type { Nuxt } from 'nuxt/schema' import type { MediaMethods } from 'comark-content/plugins/media' -import { importContent, resolveContentEntry } from './utils/config' +import { importContent, resolveContentEntry, resolveLayerAppFile } from './utils/config' import { highlightTypesTemplate, importMetaTypesTemplate } from './utils/templates' import { highlightStylesTemplate, highlightTemplate, resolveHighlightOptions, type ResolvedHighlightOptions } from './utils/highlight' import { resolveTocOptions, type ResolvedTocOptions } from './utils/toc' @@ -17,7 +16,6 @@ import { v3ServerPlugins } from './runtime/v3/content-plugins.server' import { resolveContentConfigCollections, type ResolvedContentCollections } from './runtime/v3/content-config' import { HMR_REMOVE_EVENT, HMR_UPDATE_EVENT, type ContentHmrRemove, type ContentHmrUpdate } from './runtime/utils/hmr' import { fileURLToPath } from 'node:url' -import { join } from 'node:path' // `ContentHub`: its `query` is invariant in T, so a hub over a mutable array isn't a `ContentHub`. type ContentSurface = AnyComarkContent | ContentHub @@ -50,7 +48,7 @@ export default defineNuxtModule({ } /** - * Entry files + * Entry files, from the app then its layers */ const entry = resolveContentEntry(nuxt, options.compatibilityVersion!) const serverContentPath = entry.type === 'server' @@ -59,11 +57,15 @@ export default defineNuxtModule({ ? resolve('./runtime/server/internal/content-config') : resolve('./runtime/server/internal/fallback-content') // `app/content.ts` configures the browser instance, as `server/content.ts` does the server one. - let appContentPath: string | undefined = join(nuxt.options.srcDir, 'content') - if (!existsSync(`${appContentPath}.ts`)) appContentPath = undefined - if (appContentPath && (options.mode !== 'hybrid' || options.compatibilityVersion !== 4)) { - logger.warn('`app/content.ts` is only used with `mode: \'hybrid\'` and `compatibilityVersion: 4`, ignoring it.') - appContentPath = undefined + let appContentPath = resolveLayerAppFile(nuxt, 'content.ts')?.slice(0, -'.ts'.length) + // `app/content.worker.ts` runs instances in a web worker. + let workerPath = resolveLayerAppFile(nuxt, 'content.worker.ts') + // Both are new in v4: the v3 compat layer has its own browser search. + if (options.compatibilityVersion !== 4 && (appContentPath || workerPath)) { + for (const file of [appContentPath && 'app/content.ts', workerPath && 'app/content.worker.ts'].filter(Boolean)) { + logger.warn(`\`${file}\` is only used with \`compatibilityVersion: 4\`, ignoring it.`) + } + appContentPath = workerPath = undefined } /** @@ -87,6 +89,7 @@ export default defineNuxtModule({ '@nuxt/content/content': resolve('./runtime/server/content'), }) nuxt.options.alias['@nuxt/content/app'] = resolve('./runtime/client-content/app') + nuxt.options.alias['@nuxt/content/worker'] = resolve('./runtime/client-content/worker') nuxt.options.nitro.replace = defu(nuxt.options.nitro.replace, { 'import.meta.rootDir': JSON.stringify(nuxt.options.rootDir), @@ -109,7 +112,7 @@ export default defineNuxtModule({ /** * Server */ - const content = await setupContent(serverContentPath, nuxt, options, contentCollections, highlight, toc, anchorLinks) + const content = await setupContent(serverContentPath, nuxt, options, contentCollections, highlight, toc, anchorLinks, !!(appContentPath || workerPath)) // A build reads every document once, shared by the types and components templates. const readContent = content && !nuxt.options.dev && !nuxt.options._prepare ? createContentReader(content) : undefined @@ -119,7 +122,7 @@ export default defineNuxtModule({ /** * Browser */ - if (appContentPath) { + if (appContentPath || workerPath) { // `createNuxtContent()` is synchronous, so it can't fetch the manifest to know the instances. nuxt.options.vite.define = defu(nuxt.options.vite.define, { 'import.meta.content.sources': JSON.stringify(content ? resolveInstanceNames(content) : []), @@ -129,6 +132,9 @@ export default defineNuxtModule({ addImports({ name: 'content', from: clientContentPath }) // A dynamic import deadlocks the client's top-level `await` on Nuxt 4.7; the stub keeps sqlite out of v4 bundles. nuxt.options.alias['#content-wasm-plugins'] = resolve(`./runtime/v3/content-plugins.${options.compatibilityVersion === 3 ? 'wasm' : 'stub'}`) + if (workerPath) { + await setupWorker(workerPath, content ? resolveInstanceNames(content) : [], nuxt) + } /** * Components @@ -222,6 +228,71 @@ export default defineNuxtModule({ }, }) +/** + * Bundle `app/content.worker.ts` into a web worker, which Vite builds from a generated entry as its own chunk. + * Only the worker imports the file, so its plugins never reach the app's bundle. + */ +async function setupWorker(workerPath: string, names: string[], nuxt: Nuxt) { + const { resolve } = createResolver(import.meta.url) + const runtime = await resolvePath(resolve('./runtime/client-content/worker')) + // Written to disk: Vite bundles workers without Nuxt's plugins, which serve the other templates from memory. + const entry = addTemplate({ + // Names the worker's chunk, `content-worker-.js`. + filename: 'content/content-worker.mjs', + write: true, + getContents: () => [ + `import definition from ${JSON.stringify(workerPath)}`, + `import { startNuxtContentWorker } from ${JSON.stringify(runtime)}`, + // The `app.baseURL` of the build: a base set at runtime with `NUXT_APP_BASE_URL` isn't supported. + `startNuxtContentWorker(definition, ${JSON.stringify(names)}, ${JSON.stringify(nuxt.options.app.baseURL)})`, + ].join('\n') + '\n', + }) + nuxt.options.alias['@nuxt/content/worker-entry'] = entry.dst + // Vite lists the worker as an asset of the app's entry, which Nuxt would preload on every page. + nuxt.hook('build:manifest', (manifest) => { + for (const chunk of Object.values(manifest)) { + if (/^(?:.*\/)?content-worker-[\w-]+\.js$/.test(chunk.file)) { + chunk.preload = false + chunk.prefetch = false + } + } + }) + addImports({ name: 'useNuxtContentWorker', from: resolve('./runtime/client-content/worker-client') }) + + nuxt.options.vite.optimizeDeps = defu(nuxt.options.vite.optimizeDeps, { + // Pre-bundled, it can't find its `sqlite3.wasm` next to it. + exclude: ['@sqlite.org/sqlite-wasm'], + }) + const workerPlugins = nuxt.options.vite.worker?.plugins + nuxt.options.vite.worker = { + ...nuxt.options.vite.worker, + // Vite flattens nested and pending plugin lists, so the app's are kept as one entry. + plugins: () => [workerPlugins?.(), sqliteWorkerFilesPlugin(entry.dst)], + } +} + +/** + * sqlite-wasm references its Worker1 API and OPFS helper with `new URL(…, import.meta.url)`, so Vite emits both. + * An in-memory database loads neither, so they throw instead; sqlite-wasm catches the failed OPFS install. + * TODO: use the plugin from comark-content once it ships there. + */ +function sqliteWorkerFilesPlugin(entry: string) { + const files = /new URL\("(sqlite3-worker1\.mjs|sqlite3-opfs-async-proxy\.js)", import\.meta\.url\)/ + // Vite creates the worker plugins for each worker bundle: only the content worker's rewrites, the app's other workers keep both files. + let active = false + return { + name: 'nuxt-content:sqlite-worker-files', + enforce: 'pre' as const, + buildStart(options: { input: string[] | Record }) { + active = Object.values(options.input).includes(entry) + }, + transform: { + filter: { id: /[\\/]@sqlite\.org[\\/]sqlite-wasm[\\/]/, code: files }, + handler: (code: string) => active ? code.replace(new RegExp(files, 'g'), (_, file: string) => `(() => { throw new Error(${JSON.stringify(`\`${file}\` isn't bundled with the Nuxt Content worker.`)}) })()`) : undefined, + }, + } +} + function setupHighlight(highlight: ResolvedHighlightOptions | false, nuxt: Nuxt) { const { resolve } = createResolver(import.meta.url) @@ -445,7 +516,7 @@ async function cloneSurface( }) } -async function setupContent(contentPath: string, nuxt: Nuxt, options: ModuleOptions, collections: ResolvedContentCollections, highlight: ResolvedHighlightOptions | false, toc: ResolvedTocOptions, anchorLinks: string[]): Promise { +async function setupContent(contentPath: string, nuxt: Nuxt, options: ModuleOptions, collections: ResolvedContentCollections, highlight: ResolvedHighlightOptions | false, toc: ResolvedTocOptions, anchorLinks: string[], publicSnapshots: boolean): Promise { const { resolve } = createResolver(import.meta.url) const imported = await importContent(nuxt.options.rootDir, contentPath, { @@ -479,8 +550,9 @@ async function setupContent(contentPath: string, nuxt: Nuxt, options: ModuleOpti nitro.options.serverAssets.push({ baseName: 'content', dir }) nitro.hooks.hook('prerender:generate', async (route) => { if (!route.route.startsWith('/__nuxt_content')) return - // Server-only mode keeps them private. - if (options.mode === 'server-only') { + // Server-only mode keeps them private, except the manifest and snapshots `app/content.ts` and `app/content.worker.ts` hydrate from. + const browserArtifact = route.route === '/__nuxt_content/manifest.json' || route.route.startsWith('/__nuxt_content/snapshot/') + if (options.mode === 'server-only' && !(publicSnapshots && browserArtifact)) { route.skip = true } diff --git a/src/runtime/client-content/app.ts b/src/runtime/client-content/app.ts index c8170d350..c4c847181 100644 --- a/src/runtime/client-content/app.ts +++ b/src/runtime/client-content/app.ts @@ -13,7 +13,7 @@ export interface NuxtAppContentOptions { /** * Create the `content` the app reads, in `app/content.ts`. The browser counterpart of - * `createNuxtContent()` from `@nuxt/content/content`, for `compatibilityVersion: 4` in hybrid mode. + * `createNuxtContent()` from `@nuxt/content/content`, for `compatibilityVersion: 4`. */ export function createNuxtContent(options: NuxtAppContentOptions = {}): ContentClient { if (import.meta.server) { diff --git a/src/runtime/client-content/worker-client.ts b/src/runtime/client-content/worker-client.ts new file mode 100644 index 000000000..af69d5456 --- /dev/null +++ b/src/runtime/client-content/worker-client.ts @@ -0,0 +1,181 @@ +import { readonly, shallowRef, toValue, unref, watch, type MaybeRef, 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' +import type { NuxtContentWorkerBasePaths } from './worker' + +/** Matches the `searchStatus` prop of Nuxt UI's ``. */ +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 + /** + * Where the worker loads `snapshot/.json` from, such as `/api/content/blob/`, or a function of the instance name. + * Changing it starts a new worker. An instance without a path loads its prerendered snapshot. + */ + basePath?: MaybeRef | ((instance: string) => string | undefined) +} + +export interface NuxtContentWorker { + /** `ready` once the snapshots of the instances are loaded and their search index is built. */ + status: Readonly> + /** Start the worker and load the instances in the background, such as from `onNuxtReady()`. Safe to call again. */ + warmup: () => Promise + /** Full-text search in the worker. Takes the `search` prop of ``. */ + search: (query: string, opts?: NuxtContentWorkerSearchOptions) => Promise + /** 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>() +let worker: ContentWorker | undefined +/** Where the worker loads each instance from. */ +let basePaths: NuxtContentWorkerBasePaths = {} +let hmr = false + +// 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() +// Sends `?instance=`, 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 + // Vite bundles the generated entry as its own chunk. A `#` alias would be read as a URL hash. + const instance = new Worker(new URL('@nuxt/content/worker-entry', import.meta.url), { type: 'module', name: 'nuxt-content' }) + // Sent first: the worker creates its instances from it. + instance.postMessage({ basePaths }) + const connection = worker = connectContentWorker(instance) + // A failed connection rejects every later call: drop it, so the next call starts a new worker. + const reset = () => { + if (worker !== connection) return + connection.terminate() + worker = undefined + warmed.clear() + } + instance.addEventListener('error', reset) + instance.addEventListener('messageerror', reset) + + if (import.meta.hot && !hmr) { + hmr = true + import.meta.hot.on(HMR_UPDATE_EVENT, payload => worker?.update(payload)) + import.meta.hot.on(HMR_REMOVE_EVENT, payload => worker?.remove(payload)) + } +} + +const loadsFrom = (paths: NuxtContentWorkerBasePaths) => JSON.stringify(paths) === JSON.stringify(basePaths) + +/** Stop a worker that loads from other paths, so the next call starts one with these. */ +function useBasePaths(paths: NuxtContentWorkerBasePaths) { + if (loadsFrom(paths)) return + worker?.terminate() + worker = undefined + warmed.clear() + basePaths = paths +} + +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('idle') + // A plain copy: `postMessage()` can't clone a reactive array. + const names = () => [...(toValue(options.instances) ?? import.meta.content.sources)] + // Paths of every instance, so changing `instances` keeps the worker. + const paths = () => { + const { basePath } = options + if (basePath === undefined) return undefined + // Read into a variable: in dev, Nuxt doesn't replace the define when a property access follows it. + const sources = import.meta.content.sources + return Object.fromEntries(sources.map(name => [name, typeof basePath === 'function' ? basePath(name) : unref(basePath)])) + } + let started = false + let current: Promise | undefined + + function warmup() { + if (import.meta.server) return Promise.resolve() + const next = paths() + if (next) useBasePaths(next) + 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, paths], () => started && warmup().catch(() => {})) + } + + function ready() { + if (import.meta.server) throw new Error('`useNuxtContentWorker()` reads in the browser only.') + const next = paths() + // Warms up only when it hasn't, after a failure or for other paths: `` searches again each time `status` turns `ready`. + if (status.value === 'idle' || status.value === 'error' || (next && !loadsFrom(next))) warmup().catch(() => {}) + // A worker dropped after a failure restarts on the next read. + else start() + } + + 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'], + } +} diff --git a/src/runtime/client-content/worker.ts b/src/runtime/client-content/worker.ts new file mode 100644 index 000000000..8c3aa08ad --- /dev/null +++ b/src/runtime/client-content/worker.ts @@ -0,0 +1,42 @@ +import { comarkContent, contentHub } from 'comark-content/runtime' +import snapshot from 'comark-content/sources/snapshot' +import { serveContentWorker } from 'comark-content/worker' +import type { ContentPlugin } from 'comark-content' + +export { default as sqliteFullTextSearch } from 'comark-content/plugins/sqlite-full-text-search' +export { default as sqliteWasm } from 'comark-content/database/sqlite-wasm' + +export interface NuxtContentWorkerOptions { + /** Plugins of every instance in the worker, hydrated from the prerendered snapshots. Pass one database to rank a hub as one index. */ + plugins?: ContentPlugin[] +} + +/** + * Declare the content instances that run in a web worker, in `app/content.worker.ts`. + * The file is only evaluated in the worker, so its plugins (and sqlite-wasm) stay out of the app's bundle. + */ +export function createNuxtContentWorker(options: T): T { + return options +} + +/** Base path of each instance's snapshot, by instance name. */ +export type NuxtContentWorkerBasePaths = Record + +/** + * Serve the instances of `app/content.worker.ts` to `useNuxtContentWorker()`, from the generated worker entry. + * Each instance loads its snapshot on its first read, so only the instances read are downloaded. + * @internal + */ +export function startNuxtContentWorker(options: NuxtContentWorkerOptions, names: string[], baseURL: string) { + const prerendered = `${baseURL.replace(/\/?$/, '/')}__nuxt_content` + // The first message carries the base paths. + globalThis.addEventListener('message', ({ data }: MessageEvent<{ basePaths?: NuxtContentWorkerBasePaths }>) => { + serveContentWorker(contentHub( + names.map(name => comarkContent(name, { + source: snapshot(`${(data.basePaths?.[name] ?? prerendered).replace(/\/+$/, '')}/snapshot/${name}.json`), + plugins: options.plugins, + })), + { basePath: '/__nuxt_content' }, + )) + }, { once: true }) +} diff --git a/src/utils/config.ts b/src/utils/config.ts index 2cb8e38e8..101b4e896 100644 --- a/src/utils/config.ts +++ b/src/utils/config.ts @@ -74,6 +74,11 @@ export type ContentEntry = { type: 'fallback' } +/** The first `app/`, from the project then its layers by priority. */ +export function resolveLayerAppFile(nuxt: Nuxt, file: string): string | undefined { + return getLayerDirectories(nuxt).map(dirs => join(dirs.app, file)).find(path => existsSync(path)) +} + /** * The first `server/content.ts`, from the project then its layers by priority. * Without one, the v3 `content.config.ts` of every layer, which `compatibilityVersion: 4` ignores. diff --git a/src/utils/templates.ts b/src/utils/templates.ts index 1f1e9bcff..70a93f08a 100644 --- a/src/utils/templates.ts +++ b/src/utils/templates.ts @@ -13,7 +13,7 @@ readonly rootDir: string readonly content: { /** Resolved \`content.compatibilityVersion\`. With \`3\`, v3 query/search composables are enabled and sql-query + FTS plugins are injected into the Content instance. */ readonly compatibilityVersion: 3 | 4 -/** Names of the content instances, defined for \`app/content.ts\` in the app build. */ +/** Names of the content instances, defined for \`app/content.ts\` and \`app/content.worker.ts\` in the app build. */ readonly sources: string[] /** Collections resolved at build time from the v3 \`content.config.ts\` of every layer. */ readonly collections: import('@nuxt/content/v3').ResolvedContentCollections diff --git a/test/app-content-server-only.test.ts b/test/app-content-server-only.test.ts new file mode 100644 index 000000000..764707018 --- /dev/null +++ b/test/app-content-server-only.test.ts @@ -0,0 +1,58 @@ +import { existsSync } from 'node:fs' +import type { Server } from 'node:http' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { afterAll, beforeAll, describe, it, expect } from 'vitest' +import { chromium, type Browser } from 'playwright-core' +import { setup, useTestContext } from '@nuxt/test-utils/e2e' +import { serveStatic } from './fixtures/static-server' + +describe('app/content.ts in server-only mode, on a static host', async () => { + await setup({ + rootDir: fileURLToPath(new URL('./fixtures/app-content', import.meta.url)), + nuxtConfig: { + content: { mode: 'server-only' }, + nitro: { preset: 'static' }, + }, + // Served below from `.output/public`, without Nitro. + server: false, + }) + + let publicDir: string + let server: Server + let url: string + let browser: Browser + + beforeAll(async () => { + publicDir = join(useTestContext().nuxt!.options.nitro.output!.dir!, 'public') + server = serveStatic(publicDir) + await new Promise(resolve => server.listen(0, resolve)) + url = `http://localhost:${(server.address() as { port: number }).port}` + browser = await chromium.launch() + }) + + afterAll(async () => { + await browser?.close() + server?.close() + }) + + it('publishes the manifest and the snapshots', () => { + expect(existsSync(join(publicDir, '__nuxt_content/manifest.json'))).toBe(true) + expect(existsSync(join(publicDir, '__nuxt_content/snapshot/docs.json'))).toBe(true) + expect(existsSync(join(publicDir, '__nuxt_content/snapshot/blog.json'))).toBe(true) + }) + + it('reads in the browser from the snapshot, with the plugins of `app/content.ts`', { timeout: 30_000 }, async () => { + const page = await browser.newPage() + const requests: string[] = [] + page.on('request', request => requests.push(new URL(request.url()).pathname)) + await page.goto(url) + expect(JSON.parse(await page.locator('#probes').textContent() ?? '')).toEqual({ docs: ['project'], blog: ['project'] }) + + const title = await page.evaluate(() => (window as unknown as { __content: { get: (path: string) => Promise<{ meta: { title: string } } | null> } }).__content.get('/blog/hello').then(doc => doc?.meta.title)) + expect(title).toBe('Hello') + // Only artifacts: the `/__nuxt_content` API doesn't exist on a static host. A hub `get` by path loads every instance. + expect(requests.filter(path => path.startsWith('/__nuxt_content/')).sort()).toEqual(['/__nuxt_content/snapshot/blog.json', '/__nuxt_content/snapshot/docs.json']) + await page.close() + }) +}) diff --git a/test/app-content.test.ts b/test/app-content.test.ts index b9d61ee0c..dc18917d3 100644 --- a/test/app-content.test.ts +++ b/test/app-content.test.ts @@ -10,7 +10,7 @@ describe('app/content.ts', async () => { expect(html).toContain('The intro page.') }) - it('adds its plugins to every instance of the browser hub that `content` reads', async () => { + it('adds its plugins to every instance of the browser hub that `content` reads, over a layer\'s file', async () => { const page = await createPage('/') expect(JSON.parse(await page.locator('#probes').textContent() ?? '')).toEqual({ docs: ['project'], blog: ['project'] }) await page.close() diff --git a/test/fixtures/app-content/app/app.vue b/test/fixtures/app-content/app/app.vue index 3564f2b7c..9f2155e9a 100644 --- a/test/fixtures/app-content/app/app.vue +++ b/test/fixtures/app-content/app/app.vue @@ -5,6 +5,7 @@ const { data: page } = await useAsyncData('intro', () => content.get('/docs/intr const probes = ref() onMounted(() => { + Object.assign(window, { __content: content }) const hub = content as unknown as ContentHub probes.value = JSON.stringify(Object.fromEntries(hub.names.map((name: string) => [name, (hub.from(name) as AnyComarkContent & { probes?: string[] }).probes]))) }) diff --git a/test/fixtures/app-content/base-layer/app/content.ts b/test/fixtures/app-content/base-layer/app/content.ts new file mode 100644 index 000000000..6b24027e4 --- /dev/null +++ b/test/fixtures/app-content/base-layer/app/content.ts @@ -0,0 +1,13 @@ +import { createNuxtContent } from '@nuxt/content/app' +import type { ContentPlugin } from 'comark-content' + +// Shadowed by the project's `app/content.ts`. +const layer: ContentPlugin = { + name: 'probe-layer', + setup(content) { + const target = content as unknown as { probes?: string[] } + target.probes = [...(target.probes ?? []), 'layer'] + }, +} + +export const content = createNuxtContent({ plugins: [layer] }) diff --git a/test/fixtures/app-content/base-layer/nuxt.config.ts b/test/fixtures/app-content/base-layer/nuxt.config.ts new file mode 100644 index 000000000..268da7f8c --- /dev/null +++ b/test/fixtures/app-content/base-layer/nuxt.config.ts @@ -0,0 +1 @@ +export default defineNuxtConfig({}) diff --git a/test/fixtures/app-content/nuxt.config.ts b/test/fixtures/app-content/nuxt.config.ts index 7f2d139f7..552e39773 100644 --- a/test/fixtures/app-content/nuxt.config.ts +++ b/test/fixtures/app-content/nuxt.config.ts @@ -1,6 +1,8 @@ import MyModule from '../../../src/module' export default defineNuxtConfig({ + // Its own `app/content.ts` is shadowed by the project's. + extends: ['./base-layer'], modules: [ MyModule, ], diff --git a/test/fixtures/static-server.ts b/test/fixtures/static-server.ts new file mode 100644 index 000000000..d029993ae --- /dev/null +++ b/test/fixtures/static-server.ts @@ -0,0 +1,30 @@ +import { readFile } from 'node:fs/promises' +import { createServer } from 'node:http' +import { extname, join } from 'node:path' + +const TYPES: Record = { + '.html': 'text/html', + '.js': 'text/javascript', + '.mjs': 'text/javascript', + '.css': 'text/css', + '.json': 'application/json', + '.wasm': 'application/wasm', +} + +/** A static host: files from `dir`, `index.html` for directories, 404 for anything else. */ +export function serveStatic(dir: string) { + return createServer(async (req, res) => { + const pathname = decodeURIComponent(new URL(req.url!, 'http://localhost').pathname) + for (const file of [join(dir, pathname), join(dir, pathname, 'index.html')]) { + try { + const body = await readFile(file) + res.writeHead(200, { 'content-type': TYPES[extname(file)] ?? 'application/octet-stream' }) + return res.end(body) + } + catch { + // Not this candidate. + } + } + res.writeHead(404).end() + }) +} diff --git a/test/fixtures/worker-search/app/app.vue b/test/fixtures/worker-search/app/app.vue new file mode 100644 index 000000000..a217a63f2 --- /dev/null +++ b/test/fixtures/worker-search/app/app.vue @@ -0,0 +1,32 @@ + + + diff --git a/test/fixtures/worker-search/app/other.worker.ts b/test/fixtures/worker-search/app/other.worker.ts new file mode 100644 index 000000000..caab8db5d --- /dev/null +++ b/test/fixtures/worker-search/app/other.worker.ts @@ -0,0 +1,4 @@ +// An app worker of its own: sqlite-wasm keeps its Worker1 API and OPFS helper there. +import sqlite3InitModule from '@sqlite.org/sqlite-wasm' + +sqlite3InitModule() diff --git a/test/fixtures/worker-search/commits/b/en/quokka.md b/test/fixtures/worker-search/commits/b/en/quokka.md new file mode 100644 index 000000000..fcdcc2899 --- /dev/null +++ b/test/fixtures/worker-search/commits/b/en/quokka.md @@ -0,0 +1,3 @@ +# Quokka + +The quokka only lives at this commit. diff --git a/test/fixtures/worker-search/content/blog/hello.md b/test/fixtures/worker-search/content/blog/hello.md new file mode 100644 index 000000000..e4f221f09 --- /dev/null +++ b/test/fixtures/worker-search/content/blog/hello.md @@ -0,0 +1,3 @@ +# Hello + +A wombat wrote this post. diff --git a/test/fixtures/worker-search/content/blog/platypus.md b/test/fixtures/worker-search/content/blog/platypus.md new file mode 100644 index 000000000..bd32648a7 --- /dev/null +++ b/test/fixtures/worker-search/content/blog/platypus.md @@ -0,0 +1,3 @@ +# Platypus + +A short post. diff --git a/test/fixtures/worker-search/content/docs/en/animals.md b/test/fixtures/worker-search/content/docs/en/animals.md new file mode 100644 index 000000000..7febf5f21 --- /dev/null +++ b/test/fixtures/worker-search/content/docs/en/animals.md @@ -0,0 +1,3 @@ +# Animals + +The platypus lays eggs. diff --git a/test/fixtures/worker-search/content/docs/en/install.md b/test/fixtures/worker-search/content/docs/en/install.md new file mode 100644 index 000000000..5bae916b0 --- /dev/null +++ b/test/fixtures/worker-search/content/docs/en/install.md @@ -0,0 +1,7 @@ +# Install + +Add the module to your app. + +## Configure the worker + +The wombat runs the search in a web worker. diff --git a/test/fixtures/worker-search/content/docs/fr/install.md b/test/fixtures/worker-search/content/docs/fr/install.md new file mode 100644 index 000000000..ee6afc9c0 --- /dev/null +++ b/test/fixtures/worker-search/content/docs/fr/install.md @@ -0,0 +1,7 @@ +# Installation + +Ajoutez le module. + +## Configurer le worker + +Le wombat lance la recherche dans un web worker. diff --git a/test/fixtures/worker-search/nuxt.config.ts b/test/fixtures/worker-search/nuxt.config.ts new file mode 100644 index 000000000..bab6e483e --- /dev/null +++ b/test/fixtures/worker-search/nuxt.config.ts @@ -0,0 +1,22 @@ +import MyModule from '../../../src/module' + +export default defineNuxtConfig({ + // Ships `app/content.worker.ts`, as Docus would. + extends: ['./search-layer'], + modules: [ + MyModule, + ], + // As for an installed module: Nuxt doesn't auto-import in files under `node_modules`. + imports: { transform: { exclude: [/[\\/]src[\\/]runtime[\\/]/] } }, + content: { + compatibilityVersion: 4, + mode: 'server-only', + }, + nitro: { + // Only `.output/public`, served without a server. + preset: 'static', + // Serves `docs` at another commit. + prerender: { routes: ['/commits/b/snapshot/docs.json'] }, + imports: { exclude: [/\/src\/runtime\//] }, + }, +}) diff --git a/test/fixtures/worker-search/package.json b/test/fixtures/worker-search/package.json new file mode 100644 index 000000000..3e87fd082 --- /dev/null +++ b/test/fixtures/worker-search/package.json @@ -0,0 +1,5 @@ +{ + "private": true, + "name": "worker-search", + "type": "module" +} diff --git a/test/fixtures/worker-search/search-layer/app/content.worker.ts b/test/fixtures/worker-search/search-layer/app/content.worker.ts new file mode 100644 index 000000000..5bf693653 --- /dev/null +++ b/test/fixtures/worker-search/search-layer/app/content.worker.ts @@ -0,0 +1,6 @@ +import { createNuxtContentWorker, sqliteFullTextSearch, sqliteWasm } from '@nuxt/content/worker' + +// One database for every instance, so a search across them is ranked as one index. +export default createNuxtContentWorker({ + plugins: [sqliteFullTextSearch({ database: sqliteWasm() })], +}) diff --git a/test/fixtures/worker-search/search-layer/nuxt.config.ts b/test/fixtures/worker-search/search-layer/nuxt.config.ts new file mode 100644 index 000000000..268da7f8c --- /dev/null +++ b/test/fixtures/worker-search/search-layer/nuxt.config.ts @@ -0,0 +1 @@ +export default defineNuxtConfig({}) diff --git a/test/fixtures/worker-search/server/content.ts b/test/fixtures/worker-search/server/content.ts new file mode 100644 index 000000000..806c701a6 --- /dev/null +++ b/test/fixtures/worker-search/server/content.ts @@ -0,0 +1,10 @@ +import { createNuxtContent } from '@nuxt/content/content' +import fs from 'comark-content/sources/fs' + +export const content = createNuxtContent({ + mode: 'server-only', + sources: { + docs: fs('content/docs', { cwd: import.meta.rootDir, prefix: '/docs' }), + blog: fs('content/blog', { cwd: import.meta.rootDir, prefix: '/blog' }), + }, +}) diff --git a/test/fixtures/worker-search/server/routes/commits/[commit]/snapshot/[file].get.ts b/test/fixtures/worker-search/server/routes/commits/[commit]/snapshot/[file].get.ts new file mode 100644 index 000000000..434f6d103 --- /dev/null +++ b/test/fixtures/worker-search/server/routes/commits/[commit]/snapshot/[file].get.ts @@ -0,0 +1,14 @@ +import { createError, defineEventHandler, getRouterParam } from 'nuxt/server' +import { comarkContent } from 'comark-content' +import fs from 'comark-content/sources/fs' + +// Serve the snapshot of `docs` at another commit, as an app route such as `/api/content/blob/` does. +const commits: Record> = { + b: comarkContent('docs', { source: fs('commits/b', { cwd: import.meta.rootDir, prefix: '/docs' }) }), +} + +export default defineEventHandler((event) => { + const commit = commits[getRouterParam(event, 'commit')!] + if (!commit || getRouterParam(event, 'file') !== 'docs.json') throw createError({ statusCode: 404 }) + return commit.snapshot() +}) diff --git a/test/layer-sources.test.ts b/test/layer-sources.test.ts index 06f8834aa..6e412c33d 100644 --- a/test/layer-sources.test.ts +++ b/test/layer-sources.test.ts @@ -1,5 +1,5 @@ import { spawn, type ChildProcess } from 'node:child_process' -import { cpSync, readFileSync, rmSync } from 'node:fs' +import { cpSync, existsSync, readFileSync, rmSync } from 'node:fs' import { join } from 'node:path' import { fileURLToPath, pathToFileURL } from 'node:url' import { afterAll, beforeAll, describe, it, expect } from 'vitest' @@ -65,6 +65,11 @@ describe('sources provided by a layer', async () => { expect(page('fr/guide')).toContain('Page en français.') }) + // Only `app/content.worker.ts` reads them in the browser. + it('keeps the snapshots out of the public files without a content worker', () => { + expect(existsSync(join(useTestContext().nuxt!.options.nitro.output!.dir!, 'static/__nuxt_content'))).toBe(false) + }) + it('types the layer\'s source with its declared schema', () => { const types = readFileSync(join(useTestContext().nuxt!.options.buildDir, 'content/types.d.ts'), 'utf8') // `target` only comes from the schema: no document sets it. diff --git a/test/worker-search-dev.test.ts b/test/worker-search-dev.test.ts new file mode 100644 index 000000000..fcfb176fc --- /dev/null +++ b/test/worker-search-dev.test.ts @@ -0,0 +1,38 @@ +import { fileURLToPath } from 'node:url' +import { afterAll, beforeAll, describe, it, expect } from 'vitest' +import { chromium, type Browser } from 'playwright-core' +import { setup, url } from '@nuxt/test-utils/e2e' + +type Worker = { search: (q: string) => Promise<{ id: string }[]>, basePaths: { value: Record } } + +describe('search in a web worker, in dev', async () => { + await setup({ + rootDir: fileURLToPath(new URL('./fixtures/worker-search', import.meta.url)), + dev: true, + }) + + let browser: Browser + + beforeAll(async () => { + browser = await chromium.launch() + }) + + afterAll(async () => { + await browser?.close() + }) + + it('loads an instance from its `basePath`', { timeout: 90_000 }, async () => { + const page = await browser.newPage() + await page.goto(url('/')) + // Calls may fail until Vite has optimized the dependencies of a cold cache. + const search = (query: string, basePaths: Record) => page.evaluate(async ([query, basePaths]) => { + const worker = (window as unknown as { __worker: Worker }).__worker + worker.basePaths.value = basePaths + return (await worker.search(query)).map(result => result.id).sort() + }, [query, basePaths] as const).catch((error: Error) => error.message) + + await expect.poll(() => search('quokka', { docs: '/commits/b' }), { timeout: 60_000, interval: 500 }).toEqual(['/docs/en/quokka#quokka']) + expect(await search('wombat', { docs: '/commits/b' })).toEqual([]) + await page.close() + }) +}) diff --git a/test/worker-search.test.ts b/test/worker-search.test.ts new file mode 100644 index 000000000..6b8baaf26 --- /dev/null +++ b/test/worker-search.test.ts @@ -0,0 +1,161 @@ +import { existsSync, readdirSync, readFileSync } from 'node:fs' +import type { Server } from 'node:http' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { afterAll, beforeAll, describe, it, expect } from 'vitest' +import { chromium, type Browser } from 'playwright-core' +import { setup, useTestContext } from '@nuxt/test-utils/e2e' +import { serveStatic } from './fixtures/static-server' + +type SearchResult = { id: string, source: string, title: string, content: string } + +describe('search in a web worker, on a static host', async () => { + await setup({ + rootDir: fileURLToPath(new URL('./fixtures/worker-search', import.meta.url)), + // Served below from `.output/public`, without Nitro. + server: false, + }) + + let publicDir: string + let server: Server + let url: string + let browser: Browser + + beforeAll(async () => { + publicDir = join(useTestContext().nuxt!.options.nitro.output!.dir!, 'public') + server = serveStatic(publicDir) + await new Promise(resolve => server.listen(0, resolve)) + url = `http://localhost:${(server.address() as { port: number }).port}` + browser = await chromium.launch() + }) + + afterAll(async () => { + await browser?.close() + server?.close() + }) + + it('publishes the snapshots the worker hydrates from', () => { + expect(existsSync(join(publicDir, '__nuxt_content/snapshot/docs.json'))).toBe(true) + expect(existsSync(join(publicDir, '__nuxt_content/snapshot/blog.json'))).toBe(true) + expect(existsSync(join(publicDir, '__nuxt_content/manifest.json'))).toBe(true) + }) + + // sqlite-wasm references its own worker API and OPFS helper, which an in-memory database never loads. + it('drops sqlite-wasm\'s unused files from the content worker only', () => { + const dir = join(publicDir, '_nuxt') + const files = readdirSync(dir) + const chunk = (prefix: string) => readFileSync(join(dir, files.find(file => file.startsWith(prefix))!), 'utf8') + const emitted = /sqlite3-(?:worker1|opfs-async-proxy)-[\w-]+\.m?js/ + expect(chunk('content-worker-')).not.toMatch(emitted) + expect(chunk('other.worker-')).toMatch(emitted) + }) + + it('doesn\'t preload the worker with the page', () => { + const html = readFileSync(join(publicDir, 'index.html'), 'utf8') + expect(html).toContain('/_nuxt/') + expect(html).not.toContain('content-worker') + }) + + it('warms up after the page is ready and searches the prerendered content in the worker', { timeout: 60_000 }, async () => { + const page = await browser.newPage() + const errors: string[] = [] + page.on('pageerror', error => errors.push(error.message)) + await page.goto(url) + await page.getByText('The wombat runs the search in a web worker.').waitFor() + // Nobody searched yet: `onNuxtReady()` started the hydration. + await page.locator('#status', { hasText: 'ready' }).waitFor({ timeout: 30_000 }) + + type Worker = { search: (q: string, o?: object) => Promise, get: (key: string) => Promise<{ meta: { title: string } } | null>, instances: { value: string[] }, statuses: string[] } + const search = (query: string, opts?: object) => page.evaluate( + ([query, opts]) => (window as unknown as { __worker: Worker }).__worker.search(query as string, opts as object), + [query, opts] as const, + ) + const [worker] = page.workers() + const snapshots = () => worker!.evaluate(() => performance.getEntriesByType('resource').map(entry => new URL(entry.name).pathname).filter(path => path.startsWith('/__nuxt_content/'))) + + // Only the selected instance, as Docus selects the current locale's source. + expect(await snapshots()).toEqual(['/__nuxt_content/snapshot/docs.json']) + + // Reads on a ready worker leave `status` alone, or `` would search again forever. + const statuses = () => page.evaluate(() => [...(window as unknown as { __worker: Worker }).__worker.statuses]) + const before = await statuses() + await search('wombat') + await search('nothing-matches') + await page.evaluate(() => new Promise(resolve => setTimeout(resolve, 50))) + expect(await statuses()).toEqual(before) + const docs = await search('wombat') + expect(docs.map(result => result.id).sort()).toEqual(['/docs/en/install#configure-the-worker', '/docs/fr/install#configurer-le-worker']) + expect(docs.find(result => result.id === '/docs/en/install#configure-the-worker')).toMatchObject({ + source: 'docs', + title: 'Configure the worker', + content: 'The wombat runs the search in a web worker.', + }) + expect(await page.evaluate(() => (window as unknown as { __worker: Worker }).__worker.get('/docs/fr/install').then(doc => doc?.meta.title))).toBe('Installation') + expect(await snapshots()).toEqual(['/__nuxt_content/snapshot/docs.json']) + + // Selecting more instances loads them, and one shared database ranks them in a single query. + await page.evaluate(() => (window as unknown as { __worker: Worker }).__worker.instances.value = ['docs', 'blog']) + await page.locator('#status', { hasText: 'ready' }).waitFor() + expect(await snapshots()).toEqual(['/__nuxt_content/snapshot/docs.json', '/__nuxt_content/snapshot/blog.json']) + const all = await search('wombat') + expect(all.map(result => result.id).sort()).toEqual(['/blog/hello#hello', '/docs/en/install#configure-the-worker', '/docs/fr/install#configurer-le-worker']) + // A title match outranks a content match, though `blog` comes after `docs`. + expect((await search('platypus')).map(result => result.id)).toEqual(['/blog/platypus#platypus', '/docs/en/animals#animals']) + + // sqlite and the snapshots only ever load in the worker. + const mainResources = await page.evaluate(() => performance.getEntriesByType('resource').map(entry => entry.name)) + expect(mainResources.filter(name => /\.wasm|__nuxt_content/.test(name))).toEqual([]) + expect(await page.evaluate(() => 'sqlite3ApiConfig' in globalThis)).toBe(false) + const workerResources = await worker!.evaluate(() => performance.getEntriesByType('resource').map(entry => entry.name)) + expect(workerResources.some(path => path.endsWith('.wasm'))).toBe(true) + + // Nor in the scripts the page itself runs: only the worker's own script has it. + // Nuxt preloads the app's other worker like any chunk; it's not the content worker. + const scripts = mainResources.filter(name => name.endsWith('.js') && name !== worker!.url() && !name.includes('/other.worker-')) + expect(scripts.length).toBeGreaterThan(0) + const withSqlite = [] + for (const script of scripts) { + if ((await fetch(script).then(response => response.text())).includes('sqlite3')) withSqlite.push(script) + } + expect(withSqlite).toEqual([]) + + expect(errors).toEqual([]) + await page.close() + }) + + it('loads each instance from its `basePath`, in a new worker when it changes', { timeout: 60_000 }, async () => { + const page = await browser.newPage() + await page.goto(url) + await page.locator('#status', { hasText: 'ready' }).waitFor({ timeout: 30_000 }) + + type Worker = { search: (q: string) => Promise, instances: { value: string[] }, basePaths: { value: Record } } + const search = (query: string) => page.evaluate(query => (window as unknown as { __worker: Worker }).__worker.search(query).then(results => results.map(result => result.id).sort()), query) + const snapshots = () => Promise.all(page.workers().map(worker => worker.evaluate(() => performance.getEntriesByType('resource').map(entry => new URL(entry.name).pathname).filter(path => path.endsWith('.json'))))) + + expect(await snapshots()).toEqual([['/__nuxt_content/snapshot/docs.json']]) + expect(await search('quokka')).toEqual([]) + + await page.evaluate(() => (window as unknown as { __worker: Worker }).__worker.basePaths.value = { docs: '/commits/b' }) + await expect.poll(() => search('quokka'), { timeout: 30_000 }).toEqual(['/docs/en/quokka#quokka']) + expect(await search('wombat')).toEqual([]) + expect(await snapshots()).toEqual([['/commits/b/snapshot/docs.json']]) + + await page.evaluate(() => (window as unknown as { __worker: Worker }).__worker.instances.value = ['docs', 'blog']) + await expect.poll(() => search('platypus'), { timeout: 30_000 }).toEqual(['/blog/platypus#platypus']) + expect(await snapshots()).toEqual([['/commits/b/snapshot/docs.json', '/__nuxt_content/snapshot/blog.json']]) + await page.close() + }) + + it('starts a new worker after the previous one failed', { timeout: 60_000 }, async () => { + const page = await browser.newPage() + // The worker script fails to load once, as on a flaky network. + await page.route('**/_nuxt/content-worker-*.js', route => route.abort(), { times: 1 }) + await page.goto(url) + await page.locator('#status', { hasText: 'error' }).waitFor({ timeout: 30_000 }) + + const ids = await page.evaluate(() => (window as unknown as { __worker: { search: (q: string) => Promise } }).__worker.search('wombat').then(results => results.map(result => result.id).sort())) + expect(ids).toEqual(['/docs/en/install#configure-the-worker', '/docs/fr/install#configurer-le-worker']) + await page.locator('#status', { hasText: 'ready' }).waitFor() + await page.close() + }) +})